-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblockchain.py
45 lines (32 loc) · 1.35 KB
/
blockchain.py
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
import hashlib
class Block:
def __init__(self, index, timestamp, data, previousHash = ""):
self.index = index
self.previousHash = previousHash
self.timestamp = timestamp
self.data = data;
self.hash = self.calculateHash()
def calculateHash(self):
return (hashlib.sha256((str(self.index) + str(self.previousHash) + str(self.timestamp) + str(self.data)).encode('utf-8')).hexdigest())
def setdict(self):
d = { "index":self.index, "previousHash":self.previousHash, "timestamp":self.timestamp, "data":self.data, "hash":self.hash}
return d
class Blockchain:
def __init__(self):
self.chain = [self.createGenesisBlock().setdict()]
def createGenesisBlock(self):
return Block(0, "2019/01/01", "Genesis block","0")
def getLatestBlock(self):
return self.chain[len(self.chain) - 1]
def addBlock(self, newBlock):
newBlock.previousHash = self.getLatestBlock()["hash"]
newBlock.hash = newBlock.calculateHash()
self.chain.append(newBlock.setdict())
def main():
coin = Blockchain()
coin.addBlock(Block(1, "2019/01/02", "Yotaro: 100000"))
coin.addBlock(Block(2, "2019/01/03", "mayumi: 10000"))
coin.addBlock(Block(3, "2019/01/04", "Hitoshi: 10000"))
print("chain:{}\n".format(coin.chain))
if __name__ == '__main__':
main()