-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblockchain.py
More file actions
51 lines (42 loc) · 1.62 KB
/
blockchain.py
File metadata and controls
51 lines (42 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import hashlib
import time
class Block:
def __init__(self, index, previous_hash, timestamp, data, nonce=0):
self.index = index
self.previous_hash = previous_hash
self.timestamp = timestamp
self.data = data
self.nonce = nonce
self.hash = self.calculate_hash()
def calculate_hash(self):
block_string = f"{self.index}{self.previous_hash}{self.timestamp}{self.data}{self.nonce}"
return hashlib.sha256(block_string.encode()).hexdigest()
class Blockchain:
def __init__(self):
self.chain = [self.create_genesis_block()]
def create_genesis_block(self):
return Block(0, "0", time.time(), "Genesis Block")
def get_latest_block(self):
return self.chain[-1]
def add_block(self, new_data):
last_block = self.get_latest_block()
new_index = last_block.index + 1
new_timestamp = time.time()
new_block = Block(new_index, last_block.hash, new_timestamp, new_data)
mined_block = self.proof_of_work(new_block)
self.chain.append(mined_block)
def proof_of_work(self, block, difficulty=4):
prefix = '0' * difficulty
while not block.hash.startswith(prefix):
block.nonce += 1
block.hash = block.calculate_hash()
return block
def is_chain_valid(self):
for i in range(1, len(self.chain)):
current = self.chain[i]
prev = self.chain[i - 1]
if current.hash != current.calculate_hash():
return False
if current.previous_hash != prev.hash:
return False
return True