antitheft159 commited on
Commit
f9870f1
·
verified ·
1 Parent(s): 083d41d

Upload class_blockchain.py

Browse files
Files changed (1) hide show
  1. class_blockchain.py +57 -0
class_blockchain.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Class Blockchain
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1EWMY4elMMGzoscgstOWF8wkyv0-3yShT
8
+ """
9
+
10
+ import hashlib
11
+ import time
12
+
13
+ class Block:
14
+ def __init__(self, index, previous_hash, timestamp, data, hash):
15
+ self.index = index
16
+ self.previous_hash = previous_hash
17
+ self.timestamp = timestamp
18
+ self.data = data
19
+ self.hash = hash
20
+
21
+ def calculate_hash(index, previous_hash, timestamp, data):
22
+ value = str(index) + str(previous_hash) + str(timestamp) + str(data)
23
+ return hashlib.sha256(value.encode('utf-8')).hexdigest()
24
+
25
+ def create_genesis_block():
26
+ return Block(0, "0", int(time.time()), "Genesis Block", Block.calculate_hash(0, "0", int(time.time()), "Genesis Block"))
27
+
28
+ class Blockchain:
29
+ def __init__(self):
30
+ self.chain = [create_genesis_block()]
31
+
32
+ def get_latest_block(self):
33
+ return self.chain[-1]
34
+
35
+ def add_block(self, new_block):
36
+ new_block.previous_hash = self.get_latest_block().hash
37
+ new_block.hash = Block.calculate_hash(new_block.index, new_block.previous_hash, new_block.timestamp, new_block.data)
38
+
39
+ def create_new_block(previous_block, data):
40
+ index = previous_block.index + 1
41
+ timestamp = int(time.time())
42
+ return Block(index, previous_block.hash, timestamp, data, Block.calculate_hash(index, previous_block.hash, timestamp, data))
43
+
44
+ blockchain = Blockchain()
45
+
46
+ new_block = create_new_block(blockchain.get_latest_block(), "First new block after genesis")
47
+ blockchain.add_block(new_block)
48
+
49
+ new_block = create_new_block(blockchain.get_latest_block(), "Second new block after genesis")
50
+ blockchain.add_block(new_block)
51
+
52
+ for block in blockchain.chain:
53
+ print(f"Index: {block.index}")
54
+ print(f"Previous Hash: {block.previous_hash}")
55
+ print(f"Timestamp: {block.timestamp}")
56
+ print(f"Data: {block.data}")
57
+ print(f"Hash: {block.hash}\n")