Skip to content

Commit 6a091e0

Browse files
Add files via upload
This file contains the code for basic implementation of blockchain with the help of poof of work algorithm.
1 parent 729c1f9 commit 6a091e0

File tree

1 file changed

+112
-0
lines changed

1 file changed

+112
-0
lines changed

blockchain/blockchain_main.py

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
import hashlib
2+
import json
3+
from time import time
4+
from uuid import uuid4
5+
6+
class Blockchain:
7+
def __init__(self):
8+
# Initialize blockchain as an empty list and pending transactions
9+
self.chain = []
10+
self.current_transactions = []
11+
12+
# Create the genesis block
13+
self.new_block(previous_hash='1', proof=100)
14+
15+
def new_block(self, proof, previous_hash=None):
16+
"""
17+
Creates a new block and adds it to the chain.
18+
:param proof: The proof given by the Proof of Work algorithm
19+
:param previous_hash: (Optional) Hash of previous block
20+
:return: New Block
21+
"""
22+
block = {
23+
'index': len(self.chain) + 1,
24+
'timestamp': time(),
25+
'transactions': self.current_transactions,
26+
'proof': proof,
27+
'previous_hash': previous_hash or self.hash(self.chain[-1])
28+
}
29+
30+
# Reset the current list of transactions
31+
self.current_transactions = []
32+
33+
self.chain.append(block)
34+
return block
35+
36+
def new_transaction(self, sender, recipient, amount):
37+
"""
38+
Creates a new transaction to go into the next mined block.
39+
:param sender: Address of the sender
40+
:param recipient: Address of the recipient
41+
:param amount: Amount of the transaction
42+
:return: The index of the block that will hold this transaction
43+
"""
44+
self.current_transactions.append({
45+
'sender': sender,
46+
'recipient': recipient,
47+
'amount': amount
48+
})
49+
50+
return self.last_block['index'] + 1
51+
52+
@staticmethod
53+
def hash(block):
54+
"""
55+
Creates a SHA-256 hash of a block.
56+
:param block: Block
57+
:return: Hash as a hex string
58+
"""
59+
# Ensure the dictionary is ordered to avoid inconsistent hashes
60+
block_string = json.dumps(block, sort_keys=True).encode()
61+
return hashlib.sha256(block_string).hexdigest()
62+
63+
@property
64+
def last_block(self):
65+
"""
66+
Returns the last block in the chain.
67+
:return: Last Block
68+
"""
69+
return self.chain[-1]
70+
71+
def proof_of_work(self, last_proof):
72+
"""
73+
Simple Proof of Work algorithm:
74+
- Find a number p' such that hash(pp') contains leading 4 zeroes
75+
- p is the previous proof, and p' is the new proof
76+
:param last_proof: Previous proof
77+
:return: New proof
78+
"""
79+
proof = 0
80+
while self.valid_proof(last_proof, proof) is False:
81+
proof += 1
82+
83+
# Add the mining reward here
84+
self.new_transaction(
85+
sender="0", # System or network
86+
recipient="Miner1", # Replace with the miner's address
87+
amount=1 # Reward amount
88+
)
89+
return proof
90+
91+
@staticmethod
92+
def valid_proof(last_proof, proof):
93+
"""
94+
Validates the proof: Does hash(last_proof, proof) contain 4 leading zeroes?
95+
:param last_proof: Previous proof
96+
:param proof: Current proof
97+
:return: True if correct, False if not.
98+
"""
99+
guess = f'{last_proof}{proof}'.encode()
100+
guess_hash = hashlib.sha256(guess).hexdigest()
101+
return guess_hash[:4] == "0000"
102+
103+
# Create a new blockchain instance
104+
blockchain = Blockchain()
105+
106+
# Example usage: Add a new transaction and mine a new block
107+
blockchain.new_transaction(sender="Alice", recipient="Bob", amount=50)
108+
last_proof = blockchain.last_block['proof']
109+
proof = blockchain.proof_of_work(last_proof)
110+
block = blockchain.new_block(proof)
111+
112+
print(f"New block created: {block}")

0 commit comments

Comments
 (0)