forked from rajat-babel/blockchainSimulator
-
Notifications
You must be signed in to change notification settings - Fork 1
/
mine.py
55 lines (46 loc) · 1.52 KB
/
mine.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
from block import Block
import datetime as date
import time
import sync
import json
import hashlib
NUM_ZEROS = 5
def generate_header(index, prev_hash, data, timestamp, nonce):
return str(index) + prev_hash + data + str(timestamp) + str(nonce)
def calculate_hash(index, prev_hash, data, timestamp, nonce):
header_string = generate_header(index, prev_hash, data, timestamp, nonce)
sha = hashlib.sha256()
sha.update(header_string)
return sha.hexdigest()
def mine(last_block):
index = int(last_block.index) + 1
print "index"
print index
timestamp = date.datetime.now()
data = "I block #%s" % (int(last_block.index) + 1) #random string for now, not transactions
prev_hash = last_block.hash
nonce = 0
block_hash = calculate_hash(index, prev_hash, data, timestamp, nonce)
while str(block_hash[0:NUM_ZEROS]) != '0' * NUM_ZEROS:
nonce += 1
block_hash = calculate_hash(index, prev_hash, data, timestamp, nonce)
#dictionary to create the new block object.
block_data = {}
block_data['index'] = index
block_data['prev_hash'] = last_block.hash
block_data['timestamp'] = timestamp
block_data['data'] = "Gimme %s dollars" % index
block_data['hash'] = block_hash
block_data['nonce'] = nonce
print "Block Data"
print block_data
return Block(block_data)
if __name__ == '__main__':
node_blocks = sync.sync() #gather last node
for node in node_blocks:
print node.hash
prev_block = node_blocks[-1]
print "prev block "
print prev_block.hash
new_block = mine(prev_block)
new_block.self_save()