-
Notifications
You must be signed in to change notification settings - Fork 1
/
sample blockchain.py
123 lines (104 loc) · 3.14 KB
/
sample 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
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
import datetime
import hashlib
import json
from flask import Flask, jsonify
# Initialize the web app
app = Flask(__name__)
class Blockchain:
def __init__(self):
self.chain = []
self.create_genesis_block()
def create_genesis_block(self):
# Initialize the first block (genesis block)
nonce = 0
prev = "0"
data = {
'index': 1,
'nonce': nonce,
'timestamp': str(datetime.datetime.now()),
'prev': prev
}
HASH = self.calculate_hash(data)
while HASH[:4] != '0000':
nonce += 1
data['nonce'] = nonce
HASH = self.calculate_hash(data)
block = {
'index': 1,
'nonce': nonce,
'timestamp': data['timestamp'],
'prev': data['prev'],
'HASH': HASH
}
#adding genesis block to blockchain
self.chain.append(block)
# we create block after genesis block
def create_block(self, prev_block):
prev_hash = prev_block['HASH']
index = prev_block['index'] + 1
timestamp = str(datetime.datetime.now())
nonce = self.calculate_nonce(prev_hash,index, timestamp)
data = {
'index': index,
'nonce': nonce,
'timestamp': timestamp,
'prev': prev_hash
}
HASH = self.calculate_hash(data)
block = {
'index': index,
'nonce': nonce,
'timestamp': timestamp,
'prev': prev_hash,
'HASH': HASH
}
self.chain.append(block)
def calculate_hash(self, data):
block_str = json.dumps(data, sort_keys=True).encode()
return hashlib.sha256(block_str).hexdigest()
def calculate_nonce(self, prev_hash,index, timestamp):
nonce = 0
flag = False
while flag is False:
data = {
'index': index,
'timestamp': timestamp,
'prev': prev_hash,
'nonce': nonce
}
HASH = self.calculate_hash(data)
if HASH[:4] == '0000':
flag = True
return nonce
else:
nonce += 1
def get_previous_block(self):
return self.chain[-1]
def get_blockchain(self):
return self.chain
blockchain = Blockchain()
@app.route('/mine', methods=['GET'])
def mine_block():
#data from last block is taken
prev_block = blockchain.get_previous_block()
blockchain.create_block(prev_block)
block = blockchain.get_previous_block()
response = {
'message': 'Block mined successfully!',
'index': block['index'],
'nonce': block['nonce'],
'timestamp': block['timestamp'],
'prev': block['prev'],
'HASH': block['HASH']
}
return jsonify(response), 200
@app.route('/chain', methods=['GET'])
def get_chain():
chain = blockchain.get_blockchain()
response = {
'chain': chain,
'length': len(chain)
}
return jsonify(response), 200
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5002)