-
Notifications
You must be signed in to change notification settings - Fork 0
/
blockchain.py
154 lines (115 loc) · 4.29 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
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
import hashlib
import json
from time import time
import copy
import random
import requests
from bitcoin.wallet import CBitcoinSecret
from bitcoin.signmessage import BitcoinMessage, VerifyMessage, SignMessage
DIFFICULTY = 4
class Blockchain(object):
def __init__(self):
self.chain = []
self.memPool = []
self.nodes = []
self.createGenesisBlock()
def createGenesisBlock(self):
self.createBlock(previousHash='0'*64, nonce=0)
self.mineProofOfWork(self.prevBlock)
def createBlock(self, nonce=0, previousHash=None):
if (previousHash == None):
previousBlock = self.chain[-1]
previousBlockCopy = copy.copy(previousBlock)
previousBlockCopy.pop("transactions", None)
block = {
'index': len(self.chain) + 1,
'timestamp': int(time()),
'transactions': self.memPool,
'merkleRoot': self.generateMerkleRoot(self.memPool),
'nonce': nonce,
'previousHash': previousHash or self.generateHash(previousBlockCopy),
}
self.memPool = []
self.chain.append(block)
return block
def mineProofOfWork(self, prevBlock):
nonce = 0
while self.isValidProof(prevBlock, nonce) is False:
nonce += 1
return nonce
def createTransaction(self, sender, recipient, amount, timestamp, privKey):
tx = {
'sender': sender,
'recipient': recipient,
'amount': amount,
'timestamp': timestamp
}
tx['signature'] = Blockchain.sign(privKey, json.dumps(tx, sort_keys=True)).decode('utf-8')
self.memPool.append(tx)
return self.prevBlock['index'] + 1
def isValidChain(self, chain):
for block in chain:
hashBlock = self.getBlockID(block)
if (hashBlock[:DIFFICULTY] == "0" * DIFFICULTY):
if (block["merkleRoot"] == self.generateMerkleRoot(block["transactions"])):
return True
else:
return False
def resolveConflicts(self):
for node in self.nodes:
chain = requests.get(self.node + "/chain")
nodeChain = chain.json()
if self.isValidChain(nodeChain):
if len(nodeChain) > len(self.chain):
self.chain = nodeChain
return self.chain
@staticmethod
def generateMerkleRoot(transactions):
transactionsData = json.dumps(transactions, sort_keys=True)
return Blockchain.generateHash(transactionsData)
merkleTree = transactions.copy()
if(len(merkleTree) % 2 != 0):
merkleTree.append(merkleTree[-1])
while (len(merkleTree)> 1):
j = 0
for i in range(0, len(merkleTree) - 1):
merkleTree[j] = Blockchain.generateHash(str(merkleTree[i]) + str(merkleTree[i+1]))
i += 2
j += 1
lastDelete = i - j
del merkleTree[-lastDelete:]
return merkleTree
@staticmethod
def isValidProof(block, nonce):
block['nonce'] = nonce
guessHash = Blockchain.getBlockID(block)
return guessHash[:DIFFICULTY] == '0' * DIFFICULTY
@staticmethod
def generateHash(data):
blkSerial = json.dumps(data, sort_keys=True).encode()
return hashlib.sha256(blkSerial).hexdigest()
@staticmethod
def getBlockID(block):
blockCopy = copy.copy(block)
blockCopy.pop("transactions", None)
return Blockchain.generateHash(blockCopy)
def printChain(self):
for i in self.chain:
block = (json.dumps(i, sort_keys=True, indent=2))
block = block.replace(",", "")
block = block.replace("\"", "")
block = block.replace("{", "")
block = block.replace("}", "")
print(block, "\n")
@property
def prevBlock(self):
return self.chain[-1]
@staticmethod
def sign(privKey, message):
secret = CBitcoinSecret(privKey)
msg = BitcoinMessage(message)
return SignMessage(secret, msg)
@staticmethod
def verifySignature(address, signature, message):
msg = BitcoinMessage(message)
return VerifyMessage(address, msg, signature)