step-2 after getting chain details we now have to create a new transaction.
*code snippets for some important topics of blockchain:- *
making new block
def new_block(self, proof, previous_hash=None):
block = {
'index': len(self.chain) + 1,
'timestamp': time(),
'transactions': self.current_transactions,
'proof': proof,
'previous_hash': previous_hash or self.hash(self.chain[-1] if self.chain else '0'),
}
*making new transaction
*
def new_transaction(self, sender, recipient, amount):
# Add a new transaction to the list of transactions
self.current_transactions.append({
'sender': sender,
'recipient': recipient,
'amount': amount,
})
return self.last_block['index'] + 1 # Return the index of the block that will hold this transaction
for hashing
@staticmethod
def hash(block):
# Creates a SHA-256 hash of a Block
block_string = json.dumps(block, sort_keys=True).encode()
return hashlib.sha256(block_string).hexdigest()
proof of work mechanism
def proof_of_work(self, last_proof):
proof = 0
while self.valid_proof(last_proof, proof) is False:
proof += 1
return proof
@staticmethod
def valid_proof(last_proof, proof):
# Validates the Proof by checking if hash(last_proof, proof) has 4 leading zeroes
guess = f"{last_proof}{proof}".encode()
guess_hash = hashlib.sha256(guess).hexdigest()
return guess_hash[:4] == "0000"
Check out my GitHub repo for the full code and documentation and also for more interesting projects like this. I'd love to hear your feedback or ideas for improvement!" -https://github.com/Arish2008/CodeSphere
I’m always looking to improve and learn. If you have suggestions, ideas, or improvements, drop a comment below or create an issue on GitHub.
🤝 Let’s Collaborate!
Are you working on something exciting in AI, web development, blockchain, or Python? I’d love to connect and collaborate. You can reach me on:
Twitter: [@arish_seth]
Thank you for reading, and I can’t wait to hear your thoughts! 🚀
SOCIAL SHARE CARD GENERATOR