-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathb1
41 lines (34 loc) · 1.31 KB
/
b1
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
import hashlib
import datetime
class Block:
def __init__(self, index, timestamp, owner, previous_hash):
self.index = index
self.timestamp = timestamp
self.owner = owner
self.previous_hash = previous_hash
self.hash = self.calculate_hash()
def calculate_hash(self):
data = str(self.index) + str(self.timestamp) + str(self.owner) + str(self.previous_hash)
sha = hashlib.sha256()
sha.update(data.encode('utf-8'))
return sha.hexdigest()
class Blockchain:
def __init__(self):
self.chain = [self.create_genesis_block()]
def create_genesis_block(self):
return Block(0, datetime.datetime.now(), "Original Owner", "0")
def get_latest_block(self):
return self.chain[-1]
def add_block(self, new_block):
new_block.previous_hash = self.get_latest_block().hash
new_block.hash = new_block.calculate_hash()
self.chain.append(new_block)
def is_valid(self):
for i in range(1, len(self.chain)):
current_block = self.chain[i]
previous_block = self.chain[i-1]
if current_block.hash != current_block.calculate_hash():
return False
if current_block.previous_hash != previous_block.hash:
return False
return True