-
Notifications
You must be signed in to change notification settings - Fork 0
/
simpleblockchain.py
261 lines (213 loc) · 8.52 KB
/
simpleblockchain.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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
# -*- coding: utf-8 -*-
"""SimpleBlockchain.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/github/serrodcal/SimpleBlockchain/blob/master/SimpleBlockchain.ipynb
"""
import uuid
import time
import json
from hashlib import sha256
from Crypto import Random
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA512, SHA384, SHA256, SHA, MD5
def generate_key(bits=2048):
random_generator = Random.new().read
key = RSA.generate(bits, random_generator)
sk, pk = key, key.publickey()
return sk, pk
sk, pk = generate_key()
print(sk.exportKey())
print(pk.exportKey())
def encrypt(message, pk):
#RSA encryption protocol according to PKCS#1 OAEP
cipher = PKCS1_OAEP.new(pk)
return cipher.encrypt(message)
def decrypt(ciphertext, sk):
#RSA encryption protocol according to PKCS#1 OAEP
cipher = PKCS1_OAEP.new(sk)
return cipher.decrypt(ciphertext)
def sign(message, sk, hashAlg="SHA-256"):
global hash
hash = hashAlg
signer = PKCS1_v1_5.new(sk)
if (hash == "SHA-512"):
digest = SHA512.new()
elif (hash == "SHA-384"):
digest = SHA384.new()
elif (hash == "SHA-256"):
digest = SHA256.new()
elif (hash == "SHA-1"):
digest = SHA.new()
else:
digest = MD5.new()
digest.update(message)
return signer.sign(digest)
def verify(message, signature, pk):
signer = PKCS1_v1_5.new(pk)
if (hash == "SHA-512"):
digest = SHA512.new()
elif (hash == "SHA-384"):
digest = SHA384.new()
elif (hash == "SHA-256"):
digest = SHA256.new()
elif (hash == "SHA-1"):
digest = SHA.new()
else:
digest = MD5.new()
digest.update(message)
return signer.verify(digest, signature)
message = 'My name is Alice!'
encoded_message = message.encode()
encrypted_message = encrypt(encoded_message, pk)
print(encrypted_message)
decrypted_encoded_message = decrypt(encrypted_message, sk)
decoded_message = decrypted_encoded_message.decode()
print(decoded_message)
signed_message = sign(encoded_message, sk)
print(signed_message)
verified = verify(encoded_message, signed_message, pk)
print(verified)
keystore = {}
#Alice
a_sk, a_pk = generate_key()
keystore['alice'] = (a_sk, a_pk)
#Bob
b_sk, b_pk = generate_key()
keystore['bob'] = (b_sk, b_pk)
#Charlie
c_sk, c_pk = generate_key()
keystore['charlie'] = (c_sk, c_pk)
class Transaction:
def __init__(self, id, author, content, timestamp, signature, public_key):
self.id = id
self.author = author
self.content = content
self.timestamp = timestamp
self.signature = signature
self.public_key = public_key
def __str__(self):
attributes = {}
attributes['id'] = self.id
attributes['author'] = self.author
attributes['content'] = self.content
attributes['timestamp'] = self.timestamp
attributes['signature'] = str(self.signature)
attributes['public_key'] = self.public_key.exportKey().decode()
return json.dumps(attributes)
def verify_transaction(self):
encoded_message = ('-'.join([self.id, self.author, self.content, self.timestamp])).encode()
return verify(encoded_message, self.signature, self.public_key)
transaction1_info = ['1','alice','alice_content1',str(time.time())]
transaction1_message = "-".join(transaction1_info)
transaction1_encode_message = transaction1_message.encode()
transaction1_signature = sign(transaction1_encode_message, sk)
transaction1 = Transaction(transaction1_info[0], transaction1_info[1], transaction1_info[2], transaction1_info[3], transaction1_signature, pk)
print(transaction1)
print(transaction1.verify_transaction())
class Block:
def __init__(self, index, transactions, timestamp, previous_hash):
self.index = index
self.transactions = transactions
self.timestamp = timestamp
self.previous_hash = previous_hash
self.nonce = 0
def compute_hash(self):
attributes = self.__dict__.copy()
transaction_str = [str(transaction) for transaction in self.transactions]
attributes['transactions'] = transaction_str
block_string = json.dumps(attributes)
return sha256(block_string.encode()).hexdigest()
block1 = Block(1, [transaction1], time.time(), '0')
hash_block1 = block1.compute_hash()
print(hash_block1)
class Blockchain:
def __init__(self, difficulty=2, block_len=3):
self.difficulty = difficulty
self.block_len = block_len
self.unconfirmed_transactions = []
self.chain = []
self.create_genesis_block()
def create_genesis_block(self):
genesis_block = Block(0, [], time.time(), "0")
self.chain.append(genesis_block)
def add_transaction(self, transaction):
self.unconfirmed_transactions.append(transaction)
def has_unconfirmed_transactions(self):
if self.unconfirmed_transactions:
return True
return False
def number_of_blocks(self):
return len(self.chain)
def last_block(self):
return self.chain[-1]
def proof_of_work(self, block):
computed_hash = block.compute_hash()
while not computed_hash.startswith('0' * self.difficulty):
block.nonce += 1
computed_hash = block.compute_hash()
return computed_hash, block
def check_proof(self, block, block_hash):
return (block_hash.startswith('0' * self.difficulty) and
block_hash == block.compute_hash())
def add_block(self, block, proof):
previous_hash = self.last_block().compute_hash()
if previous_hash != block.previous_hash:
return False
if not self.check_proof(block, proof):
return False
self.chain.append(block)
return True
def mine(self):
if len(self.unconfirmed_transactions) < self.block_len:
return False
while len(self.unconfirmed_transactions) > self.block_len:
previous_block = self.last_block()
current_unconfirmed_transaction = [self.unconfirmed_transactions.pop(0) for _ in range(self.block_len)]
new_block = Block(index=previous_block.index + 1,
transactions=current_unconfirmed_transaction,
timestamp=time.time(),
previous_hash=previous_block.compute_hash())
proof, updated_block = self.proof_of_work(new_block)
self.add_block(updated_block, proof)
return self.last_block().index
def create_transaction(info, sk, pk):
message = "-".join(info)
encoded_message = message.encode()
signature = sign(encoded_message, sk)
return Transaction(info[0], info[1], info[2], info[3], signature, pk)
transactions = [[uuid.uuid4().hex,'alice','alice_content1',str(time.time())],
[uuid.uuid4().hex,'bob','bob_content1',str(time.time())],
[uuid.uuid4().hex,'charlie','charlie_content1',str(time.time())],
[uuid.uuid4().hex,'alice','alice_content2',str(time.time())],
[uuid.uuid4().hex,'bob','bob_content2',str(time.time())],
[uuid.uuid4().hex,'charlie','charlie_content2',str(time.time())],
[uuid.uuid4().hex,'alice','alice_content3',str(time.time())],
[uuid.uuid4().hex,'bob','bob_content3',str(time.time())],
[uuid.uuid4().hex,'charlie','charlie_content3',str(time.time())],
[uuid.uuid4().hex,'alice','alice_content4',str(time.time())],
[uuid.uuid4().hex,'bob','bob_content4',str(time.time())],
[uuid.uuid4().hex,'charlie','charlie_content4',str(time.time())],
[uuid.uuid4().hex,'alice','alice_content5',str(time.time())]]
blockchain = Blockchain()
for transaction in transactions:
transaction_obj = create_transaction(transaction, keystore[transaction[1]][0], keystore[transaction[1]][1])
blockchain.add_transaction(transaction_obj)
last_index = blockchain.mine()
print(last_index)
print(blockchain.has_unconfirmed_transactions())
print(len(blockchain.unconfirmed_transactions))
last_transaction = blockchain.unconfirmed_transactions[0]
print(last_transaction)
info = [last_transaction.id, last_transaction.author, last_transaction.content, last_transaction.timestamp]
message = "-".join(info)
signature = sign(message.encode(), keystore['alice'][0])
print(last_transaction.public_key == keystore['alice'][1])
print(last_transaction.signature == signature)
print(last_transaction.verify_transaction())
print(verify(message.encode(), signature, keystore['alice'][1]))
last_block = blockchain.last_block()
print(last_block.nonce)
print(last_block.compute_hash())