Simple Python Blockchain Implementation - Simplecoin part 3

Posted by Suraj Singh on May 24, 2018 · 46 mins read
hii readers,



Sorry For my late blog posts, Actually I'm still busy in studying blockchain and bitcoin concepts. So, Today, again I am going to share with you a new python script where I tried to add some more features in previous simple blockchain based ledger python script.

For Previous post

Part 1 :  check here
Part 2 : check here

Note

  • Tutorials And Reference For This Script Coming Soon...
  • Sorry For Less Comments And Bad Coding Styles.

Actually, Guys, I'm Still Busy In Developing This Script To Make More Advance, Adding More Features In It.
So, I'm Open For Suggestions Comments.

Some Key Features Of This Script.

  • Transactions Feature Supported
  • Transactions Merkle Data hashing Algorithm Supported
  • Proof Of Work Supported (hashcash)
  • Database created In Json To Make It More Simple To Understand
  • Python Object Orient Programming Basic Support


Requirements


  • PyCrypto Module
  • Python2.7
  • Currently Tested On Ubuntu Only


For More Details. Refer To my Github Repo. Check Here



  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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
#!/usr/bin/python

__author__='''
Suraj Singh bisht
surajsinghbisht054@gmail.com
www.bitforestinfo.com
github.com/surajsinghbisht054


'''

# coding: utf-8

# In[9]:


import json
import os
from hashlib import sha256
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from hashlib import md5
from hashlib import sha256
from Crypto.Hash import SHA256
import binascii
import base64
import time


# In[10]:


#
# User Authentication Handling Class
#
class User:
def __init__(self, private=None, public=None):
'''
A Simple Class To Handle User Authentication Activities

'''

if public:
self.publickey = public
else:
self.publickey = ''

if private:
self.privatekey = RSA.importKey(private)
else:
(self.privatekey, self.address) = self.generate_key_pair()

def generate_key_pair(self):
'''
Generate New Pair Of Keys For New Users

'''
private = None
public = None

# Random Number Generated
random = RSA.Random.new().read
PUB_LEN = 1024


# RSA Object
RSAKey = RSA.generate(PUB_LEN, random)

# Private Key
private = RSAKey.exportKey()

# Public Key
self.publickey = RSAKey.publickey().exportKey()

public = sha256(self.publickey).hexdigest()
public = sha256(public).hexdigest()
public = md5(public).hexdigest()

return (private, public)

def signature(self, data):
'''
Sign Data Using User Inserted/Generated Private Key
'''

r = RSA.importKey(self.privatekey)
siger = PKCS1_v1_5.new(r)
h = SHA256.new(data)
return binascii.hexlify(siger.sign(h))

#u = User()
#print u.publickey
#print u.privatekey
#print u.address
#print u.signature(u.address)


# In[11]:


# Global Functions

def previous_block_hash(blockitemdict):
'''
Global Function To Calculate previous block hashes
'''
return sha256("{index}{previoushash}{timestamp}{hash}{datahash}{nonce}{targetbit}".format(**blockitemdict)).hexdigest()

def transection_hash(data):
'''
Global Function To Calculate Transection hashes
'''
return sha256("{category}{txni}{coin}{fee}{signature}{time}".format(**data.getitems())).hexdigest()

def merkle_hash(dataload):
'''
A Simple Class That Automatically Calculate Hashes Of All Transection feilds using
Merkle Type Algorithm.

'''

# Two Empty Containers
hl1 = []
hl2 = []

for data in dataload:
hl1.append(transection_hash(data))

if not hl1:
return sha256('').hexdigest()

while True:
v1 = ''
v2 = ''
hl2 = []
if int(len(hl1) % 2)==0 and len(hl1)>1:
# Even Number's List

for h in hl1:

if not v1:
v1 = h
continue
v2 = h

hl2.append(sha256(v1+v2).hexdigest())
v1 = ''
v2 = ''

elif int(len(hl1) % 2)==1 and len(hl1)>1:
hl2 = hl1
hl2.append('')


elif len(hl1)==1:
return hl1[0]

else:
return False

hl1 = hl2

return False


# In[12]:


#
# trasenction feild structure
# (
# category, --> mine, send, receive
# sender --> Sender Wallet Address
# receiver --> Receiver Wallet Address
# txni, --> input transection
# txno, --> output transection
# ccoin --> net balance
# coin, --> coin
# fee, --> transection fee
# time, --> time
# signature, --> hash = sha256(category + sender + receiver + txni + txno + coin + fee + time)
# hash = private_key_signature(hash)
#
#
# verification --> SENDER_PUBLIC_KEY
# )
#
# Trasenction Unique Identities
#
# structure
# (
#
# Name : SHA256( sender + receiver ) ---> Result Hash Will Be Same
# if Sender and Reciever are same (Not Unique)
# txnid : SHA256( Name + Signature) --> Always Unique
#
# txn : trasenction feild
#
# )
#
#
#
#







# Simple Request Transection ()
class RequestTransection:
def __init__(self, user):
'''
A Simple Class To Handle And Generate Valid Transection Requests
Using User Object Authentication Object.

'''
self.category = ''
self.user = user
self.sender = None
self.receiver = None
self.txni = []
self.ccoin = ''
self.coin = ''
self.time = ''
self.fee = ''
self.signature = ''
self.transection = {}
self.verification = ''

def getitems(self):
'''
Get All Feild Items
'''
return {
"category" : self.category,
"txni" : self.txni,
"ccoin" : self.ccoin,
"coin" : self.coin,
"fee" : self.fee,
"signature" : self.signature,
"time" : self.time,

}

def __repr__(self):
return "< transReq {} | {} >".format(self.category, self.time)


def create_transection(self, category='mine', txni=[], coin='',
fee='', receiver = '', sender = ''):
'''
Generate Valid Transection Request With Automatic Hash And Signature handling
'''
if not sender:
sender = self.user.address

if category=="mine":
sender =''
receiver = self.user.address

if not receiver:
raise "please insert valid receiver address."

# Lower case --- > category
category = category.lower()

# Check category
if category not in ['mine', 'send']:
raise "please use valid categories like mine or send "


# initialise values
self.category = category
self.sender = sender
self.receiver = receiver
self.txni = ''.join(i for i in txni)
self.coin = coin
self.fee = fee
self.time = str(time.time())
#
# signature, --> hash = sha256(category + sender + receiver + txni + coin + fee + time)
# private_key_signature(hash)
#
h = self.category + self.sender + self.receiver + self.txni + self.coin + self.fee + self.time
h = sha256(h).hexdigest()


if self.category!="mine":
self.verification = self.user.publickey

self.signature = self.user.signature(h)

self.transection = {
"name" : sha256(self.sender + self.receiver).hexdigest(),
"txn" : sha256( sha256(self.sender + self.receiver).hexdigest() + self.signature).hexdigest(),
"load" : self.getitems(),

}
return


# In[13]:


#
#
# RequestBlock Object handler
#
# Structure
# (
# index ---> current block index in chain
# previoushash ---> previous block hash
# timestamp ---> timestamp
# targetbit ---> difficulty bit in hash calculation
# hash ---> self block hash (proof of work)
# datahash ---> datahash (merkle hash of transection feilds)
# dataload ---> all transection data
# nonce ---> nonce (proof of work)
# )
#
#
#
#
#
class RequestBlock:
def __init__(self, index, previoushash, targetbit=4, transbuffer = []):
'''
A Simple Class To Handle All Transection Request And Generate A Valid Block.
'''

self.index = index
self.previoushash = previoushash
self.timestamp = str(time.time())
self.targetbit = targetbit
self.hash = ''
self.datahash = ''
self.dataload = []
self.nonce = ''
self.transbuffer = transbuffer
self.calculate_block()



def calculate_block(self):
'''
Calculate Block Hash
'''
# load transections from Node Buffer
self.load_data_from_network_buffer()
tmp = merkle_hash(self.dataload)
if not tmp:
print "[Note] No Data load Found"
self.datahash = tmp
return


def load_data_from_network_buffer(self):
'''
Load Trasection Requests
'''
for trans_req in self.transbuffer:
if trans_req not in self.dataload:
self.dataload.append(trans_req)
return

def getitems(self):
'''
return items
'''
return {
"index" : self.index,
"previoushash": self.previoushash,
"timestamp" : self.timestamp,
"targetbit" : self.targetbit,
"hash" : self.hash,
"datahash" : self.datahash,
"dataload" : [i.transection for i in self.dataload],
"nonce" : self.nonce,
}


# In[14]:


#
# Class Design To Perform Proof Of Work Hash Calculations
#
class MineBlock:
'''
A Simple Class That will Automatically handle Block Mining And Other Important Stuff.

'''
def __init__(self):
self.pow = False
self.block = ''
self.difficulty = 0

def block_validator(self, block):
# Check Index
# Check PRevious hash
# check timestamp
# check merkle hash
if merkle_hash(block.dataload):
return True
return False

def load(self, block):
'''
Load Block
'''
if self.block_validator(block):
self.block = block
self.difficulty = int(self.block.targetbit)
self.proof_of_work_number_generator()
self.pow = True
return True

return False

def getblock(self):
return self.block

def getitems(self):
return self.block.getitems()

def proof_of_work_number_generator(self):
self.block.nonce = 0
while sha256("{}{}{}{}{}".format(self.block.previoushash,self.block.datahash,self.block.timestamp,self.block.targetbit,self.block.nonce)).hexdigest()[:self.difficulty]!='0'*self.difficulty:
self.block.nonce+= 1
self.block.hash = sha256("{}{}{}{}{}".format(self.block.previoushash,self.block.datahash,self.block.timestamp,self.block.targetbit,self.block.nonce)).hexdigest()
return self.block.nonce



# In[15]:


#
# Class To handle Block chain database and act as a central sever to handle all block request
#
class SimpleBlockChain:
'''
A Simple Class To Handle Block Chain Database.
'''
def __init__(self, dbname='ChainStore.json', targetbit = 4):
self.targetbit = targetbit
self.dbname = dbname

# Check BlockChain Json Storage File
if os.path.exists(self.dbname):
self.chain = json.load(open(self.dbname, 'r'))
else:
self.chain = {
"blockchain": [],
'lastupdate': time.time(),
}


# Check BlockChain Status
if not self.check_chain_len():

# Add Genesis Block
self.add_genesis_block()


# add genesis block request
def add_genesis_block(self):
'''
Add Genesis Block
'''
print "Add Genesis Block Request"
tmpobj = RequestBlock(1,0)
mineblock = MineBlock()
mineblock.load(tmpobj)
self.new_block_request(mineblock.getblock())
return

# New Blocking Join Request
def new_block_request(self, block):
'''
New Block Request
'''
# Verify Block
if self.validate_new_block(block):
self.chain['blockchain'].append(block.getitems())

print "[+] Request Block Verified."
else:
print "[Error] Request Block Is Not Valid."
return


# Validate New Block Before Joining It to main Chain
def validate_new_block(self, block):
'''
Validate And Verify Various Hash Calculations
'''
# check target bit
# check block index
# check previous block hash
# check Proof of work
# check timestamp
# check datahash

diff = self.targetbit == int(block.targetbit)

if self.check_chain_len()==0:
previoushash = True

else:
previoushash = block.previoushash == previous_block_hash(self.pre_block())#sha256("{index}{previoushash}{timestamp}{hash}{datahash}{nonce}{targetbit}".format(**self.pre_block())).hexdigest()

proof_of_work_hash = sha256("{previoushash}{datahash}{timestamp}{targetbit}{nonce}".format(**block.getitems())).hexdigest()[:block.targetbit]=='0'*block.targetbit

timestamp = float(block.timestamp) < time.time()

index = block.index == self.check_chain_len()+1

datahash = merkle_hash(block.dataload)

if previoushash and proof_of_work_hash and timestamp and index and datahash and diff:
return True
print previoushash
print proof_of_work_hash
print timestamp
print index
print datahash
print diff
return False

# Check block chain length
def check_chain_len(self):
return len(self.chain['blockchain'])

def pre_block(self):
return self.chain['blockchain'][-1]
#return

# save updates
def close(self):
f = open(self.dbname, 'w')
self.chain['lastupdate']= time.time()
json.dump(self.chain, f, sort_keys=True, indent=4, separators=(',', ': '))
f.close()
return






# In[18]:


# -----------------------------------------------------------
# ================= Global Object ===========================
# -----------------------------------------------------------
# Create Blockchain handler object
sbc = SimpleBlockChain()

# ------------------------------------------------------------
# ==================== Miner =================================
# ------------------------------------------------------------


# Create User Authentication Object
u = User()

# Create First Transection And Get Miners Reward
req = RequestTransection(u)

#create_transection
req.create_transection(category='mine', coin='25', fee='0', receiver = u.address)

reward_trasection = req.transection



# assemble all transection and create a block object
reqblock = RequestBlock(
index = sbc.check_chain_len()+1,
previoushash = previous_block_hash(sbc.pre_block()),
transbuffer=[req]
)

# Miner Object
mineblock = MineBlock()

# Load Block and find proof of work
mineblock.load(reqblock)


# print proof of work
mineblock.getitems()



# insert block object to blockchain handler
sbc.new_block_request(mineblock.getblock())

# Now, Our First Transection Is Complete..

# Now, Let's Try Second Transection Request By Any Node


# ------------------------------------------------------------
# ==================== Nodes =================================
# ------------------------------------------------------------

node = User() # Example Node

# Create Transection Request object
n_address = node.address # Shared its receiving address with miners.. because at this time,
# miner is the only one account that contain 25 coins


# Miner Requested A Transection
req = RequestTransection(u)
req.create_transection(category='send', sender=u.address, receiver=n_address, coin='20',txni=reward_trasection['txn'])
transer_money_reference_ = req.transection


# Wait... To Add This Block... Miner Again Need To Use its Computational Power... So,,

# Create First Transection And Get Miners Reward
req1 = RequestTransection(u) #

#create_transection
req1.create_transection(category='mine', coin='25', fee='0', receiver = u.address)

reward_2_trasection = req1.transection


# assemble all transection and create a block object
reqblock = RequestBlock(
index = sbc.check_chain_len()+1,
previoushash = previous_block_hash(sbc.pre_block()),
transbuffer=[req, req1]
)

# Miner Object
mineblock = MineBlock()

# Load Block and find proof of work
mineblock.load(reqblock)


# print proof of work
mineblock.getitems()



# insert block object to blockchain handler
sbc.new_block_request(mineblock.getblock())

sbc.close()

To Run This Script.
Just Type:


$ python path/to/script.py

Blockchain JSON Output



{
"blockchain": [
{
"datahash": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"dataload": [],
"hash": "000052310a4d3de6ee472d732681a44fee20bf6a5e1d4c804db3698d74773ae4",
"index": 1,
"nonce": 46130,
"previoushash": 0,
"targetbit": 4,
"timestamp": "1527104534.07"
},
{
"datahash": "5052de176f294ec4a653c412017d6be2a25a0bf61060b7ceaf921eade8c8fea4",
"dataload": [
{
"load": {
"category": "mine",
"ccoin": "",
"coin": "25",
"fee": "0",
"signature": "426371426864bc1c533eab894ecc97564be2cc3efe6473da10556e15aeff9626bc6a38283d5ae5b604977710c36be6c31fef68a1d5423690329d11af806c1068dbb4ed46ded5228d5f2858b908c2c56f7f9825bb23e74a33393f1ce83fc619ed80c4dc99844de13c052f170a4ff84d4144831f42dad9104298c00f243afccfc3",
"time": "1527104534.24",
"txni": ""
},
"name": "5355f59a8bc194a061de7bc8477f7a9b30279438a55964fd3db0c5a6ce3635ce",
"txn": "0fba77b217f80aa8010dc2c59e61b0525be42c688efb46db8c6528b33a2baf54"
}
],
"hash": "0000a7b48edc29d16f8765b5f6a2934f37823287171ff4ec8d205fa845b1bfb9",
"index": 2,
"nonce": 67206,
"previoushash": "654053b0fc898cfc65f541d6defeb4612b9e7f130a3bfaab6167b25061434bbf",
"targetbit": 4,
"timestamp": "1527104534.24"
},
{
"datahash": "75f53deb9fe5677905da2574a27218482dee6260163bb9d059a657310eddd9e1",
"dataload": [
{
"load": {
"category": "send",
"ccoin": "",
"coin": "20",
"fee": "",
"signature": "95af23ed0b2fadaa9d23867bd54b050d2f9e28ec9feb843ea60c6facb1ae6c8366fd9e5125c9d9ce452fc6a087081264bcf2de2d626f8db0361a61f95a9a492484580c8b874862cd1012fc421a19b81b2cdfbe9e940941c614e60109c21738305f93015b157b9fcec6d6c5861e77424f287f3185e557f720aa900251d9d2e0c3",
"time": "1527104534.48",
"txni": "0fba77b217f80aa8010dc2c59e61b0525be42c688efb46db8c6528b33a2baf54"
},
"name": "5b196c89d45bfa3cc0e9d5536570f8fa05b60a10338b38473290a98ca634f09d",
"txn": "93f668eb9e534500ec20a9c00aba757686fb849ce39f812c622a6374835fe313"
},
{
"load": {
"category": "mine",
"ccoin": "",
"coin": "25",
"fee": "0",
"signature": "0e2e1c9a632880e82f28a969656e0a9a77dc5c174275d0a28d33e8900ca41c05c413694a5d8903868727a1d591c9b8bb1d295f50f4a7d876c76634418f4a6ad2d913f8aa80c92d5c9b70007dabb47f9ee0d136da36ed6068ef8a46b882752b90368d3ee08c562b95227cee1675377e1e2b7f4cfee958163532284018db173851",
"time": "1527104534.48",
"txni": ""
},
"name": "5355f59a8bc194a061de7bc8477f7a9b30279438a55964fd3db0c5a6ce3635ce",
"txn": "c1d3d60008cf4bcd4a5352af5342ecd9c8f89786c017b146b9a10f7c81a834eb"
}
],
"hash": "0000e8398d66849abb87013f24d6cff4a40241d550bf4b64c8d1cf520fcb39f0",
"index": 3,
"nonce": 38503,
"previoushash": "497d1754ab20124cd85419a69526be4f8cfa12a11771c7f999d3c4827de950dd",
"targetbit": 4,
"timestamp": "1527104534.48"
}
],
"lastupdate": 1527104534.605635
}