-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple-blockchain.py
More file actions
77 lines (39 loc) · 1.35 KB
/
simple-blockchain.py
File metadata and controls
77 lines (39 loc) · 1.35 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
from hashlib import sha256
import json
import time
class Chain:
def __init__(self):
self.blockchain = []
self.pending = []
self.add_block(prevhash="Genesis", proof=123)
def add_transaction(self, sender, recipient, amount):
transaction = {
"sender": sender,
"recipient": recipient,
"amount": amount
}
self.pending.append(transaction)
def compute_hash(self, block):
json_block = json.dumps(block, sort_keys=True).encode()
curhash = sha256(json_block).hexdigest()
return curhash
def add_block(self, proof, prevhash=None):
block = {
"index": len(self.blockchain),
"timestamp": time.time(),
"transactions": self.pending,
"proof": proof,
"prevhash": prevhash or self.compute_hash(self.blockchain[-1])
}
self.pending = []
self.blockchain.append(block)
chain = Chain()
t1 = chain.add_transaction("Shreyash", "Chauhan", 100)
t2 = chain.add_transaction("Sujal", "Samai", 10)
t3 = chain.add_transaction("Yash", "Sehgal", 34)
chain.add_block(12345)
t4 = chain.add_transaction("Uttam", "Singh", 23)
t5 = chain.add_transaction("Tejas", "Shah", 3)
t6 = chain.add_transaction("Nishant", "Jain", 88)
chain.add_block(6789)
print(chain.blockchain)