Simple Python Blockchain Implementation - Simplecoin part 4

Namaste Friends,



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 the Previous post

Part 1: check here
Part 2: check here
Part 3:  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 And Contributions.

Some Key Features Of This Script.

  • Transactions Feature Supported
  • Transaction Address Supported
  • Double Spend Detection Supported
  • Strict Transaction Validations Supported
  • Simple wallet Supported
  • Miner Automatic Reward Receiving Supported
  • Transactions Merkle Data hashing Algorithm Supported
  • Block Hashing Verification Supported
  • Previous block hash verification supported
  • Transaction Signature Verification
  • Proof Of Work Supported (hashcash)
  • Proof Of Work Verification Supported
  • Invalid Transaction Detection Functions
  • Balance Finding Supported
  • All Transaction Extraction Supported
  • Automatic Key Handling Supported
  • Input Transaction Verification Available
  • Easy Signature Verification Handling
  • 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
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
#!/usr/bin/python

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


'''


# coding: utf-8

# In[100]:


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


# In[101]:


#
# 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_PSS.new(r)
        h = SHA256.new(data)
        sign = base64.b64encode(siger.sign(h))
        return sign

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


# In[102]:


# 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


# (
#    category,  --> mine, send, receive
#    sender     --> Sender Wallet Address
#    receiver   --> Receiver Wallet Address
#    txni,      --> input 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
# )
def verify_transection(bco, transobj):
    # Load Values From Transection Object
    category     = transobj.category
    sender       = transobj.sender 
    receiver     = transobj.receiver
    txni         = transobj.txni
    ccoin        = transobj.ccoin
    coin         = transobj.coin
    fee          = transobj.fee
    timestamp    = transobj.time
    signature    = transobj.signature
    verification = transobj.verification
    
    # Check sender address length
    if len(receiver)!=32:
        print "[+] Condition No. 1 Failed By ", receiver
        return False
    
    # Check Current Transection Time With Previous block time
    if not (float(timestamp) < float(time.time())):
        print "[+] Condition No. 2 Failed By ", receiver
        print "[-] Timestamp {}, Current Time {}".format(timestamp, time.time())
        return False
    
    
    # Miners Transection Conditions
    if (category=='mine') and (sender!=''):
        print "[+] Condition No. 3 Failed By ", receiver
        return False
    
    if (category=='mine') and txni:
        print "[+] Condition No. 4 Failed By ", receiver
        return False
    
    if (category=='mine') and ccoin:
        print "[+] Condition No. 5 Failed By ", receiver
        return False
    
    if (category=='mine') and (int(coin) != 25 ):
        print "[+] Condition No. 6 Failed By ", receiver
        return False
    
    if (category=='mine') and fee:
        print "[+] Condition No. 7 Failed By ", receiver
        return False
    
    if (category=='mine') and not signature:
        print "[+] Condition No. 8 Failed By ", receiver
        return False
    
    if (category=='mine') and verification:
        print "[+] Condition No. 9 Failed By ", receiver
        return False
    
    # Miners Conditions Close
    if category=="mine":
        return True
    
    # Senders Conditions Verification
    if (category=='send') and (len(sender)!=32):
        print "[+] Condition No. 10 Failed By ", sender
        return False
    
    if (category=='send') and not txni:
        print "[+] Condition No. 11 Failed By ", sender
        return False
    
    if (category=='send') and not coin:
        print "[+] Condition No. 12 Failed By ", sender
        return False
    
    if (category=='send') and not fee:
        print "[+] Condition No. 13 Failed By ", sender
        return False
    
    if (category=='send') and not signature:
        print "[+] Condition No. 14 Failed By ", sender
        return False
    
    if (category=='send') and not verification:
        print "[+] Condition No. 15 Failed By ", sender
        return False
    
    
    # Verify verification and sender address
    public = sha256(verification).hexdigest()
    public = sha256(public).hexdigest()
    public = md5(public).hexdigest()
    
    
    
    if not (public==sender):
        print "[x] Invalid Sender Address : {} | {}".format(sender, public)
        return False
    
    # Verify Signature
    h = category + sender + receiver + txni + coin + fee + timestamp
    h = sha256(h).hexdigest()
    h = SHA256.new(h)
    
    r = RSA.importKey(verification)
    sign_verify = PKCS1_PSS.new(r)
    dsignature = base64.b64decode(signature)
    
    if not sign_verify.verify(h, dsignature):
        print "[x] Signature Invalid. Transection Index {} | Sender {} ".format(txni, sender)
        return False
    
    print "[+] Transection Signature Verified."
    
    #
    # So, Previous Conditions Verified That Request Is Generated From Real User
    #
    # Now, Let's Do Some mathematical Calculations for Amount.
    #
    
    input_transections = []
    balance = 0.0
    
    n = len(txni)/64
    for i in range(n):
        input_transections.append(txni[i*64: (i+1)*64])
    
    
    for pretxnid in input_transections:
        if bco.double_spend_check(sender, pretxnid):
            print "[x] Double Spend Detected. Transection Index {}, InputTransection {}".format(txni, pretxnid)
            return False
    # Find Transections Into Blockchain
        data = bco.search_transection_dict(pretxnid)

        if not data:
            print "[x] Invalid Transection Input."
            return False
        #{
        #    'category'
        #    'sender'
        #    'receiver'
        #    'fee': '', 
        #    'ccoin': '', 
        #    'txni': '', 
        #    'time': '1526936989.86', 
        #    'signature': '40eee107b43f2254ef8ea5c9d15f63bba6e872bb2421b3da09173fb88cdd1c8c6578bfe7780cc1d5223c289c95dbbb9bfcc303cd9379e4f47ea7ca095b1e1e4125ed6fbb3c072901dc7c45e34faeeccec1b07bbe972ed94f354a1153ed9ecca402098e64eaf07621d8b35deaa8bcd003edc8f3d8770a93627f8e073d4b1c6ff6', 
        #    'coin': '25'
        #}
        # Verify Input Transection Signatures
        load = data['load']
        
        if load['receiver']==sender:
            #
            # Taking Balance Inputs From Receiving Transections
            #
        
            # Verify Signature
            tmp = load['category'] + load['sender'] + load['receiver'] + load['txni'] + load['coin'] + load['fee'] + load['time']
            tmp = sha256(tmp).hexdigest()
            tmp = SHA256.new(tmp)
            dsignature = base64.b64decode(load['signature'])
        
            if sign_verify.verify(tmp, dsignature):
                print "[+] Input Transection {} \n\t\tVerified By {}".format(pretxnid, sender)
            else:
                print "[-] Input Transection {} \n\t\tVerification Failed By {}".format(pretxnid, sender)
                return False
        
            balance+= float(load['coin'])
        
        elif load['sender']==sender:
            #
            # Taking Inputs From Transection Balance Changes
            #
            balance+= float(load['ccoin'])
        
        else:
            print "[-] Something Wrong With Conditions."
            print load
            pass                                        
    
    
    if balance==0.0:
        print "[x] Insuffecient Balance"
        return False
    
    
    if balance < float(float(coin)+float(fee)+float(ccoin)):
        print "[x] Low Balance"
        return False
        
    return balance



# In[103]:


#
# 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
        '''
        time.sleep(1)
        return {
            "category" : self.category, 
            'sender': self.sender,
            'receiver' :self.receiver,
            "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 = '', ccoin=''):
        '''
        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.ccoin     = ccoin
        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[104]:


#
#
# 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, bco, targetbit=4, transbuffer = []):
        '''
         A Simple Class To Handle All Transection Request And Generate A Valid Block.
        '''
        self.bco         = bco   # SimpleBlockChain Class Object
        self.index       = self.bco.check_chain_len()+1
        
        if self.bco.pre_block():
            self.previoushash = previous_block_hash(self.bco.pre_block())
        else:
            self.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
        '''
        senders = []
        for trans_req in self.transbuffer:
            if trans_req not in self.dataload:
                if verify_transection(self.bco, trans_req):
                    if trans_req.sender not in senders:
                        self.dataload.append(trans_req)
                        senders.append(trans_req.sender)
                    else:
                        print "[x] Double Transection Request Found. ", trans_req
                else:
                    print "[x] Transection Verification Fail.", 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[105]:


#
# 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, block_chain_obj):
        self.bco = block_chain_obj
        self.pow = False
        self.block = ''
        self.difficulty = 0
        
    def block_validator(self, block):
        # Check Index
        # Check PRevious hash
        # check timestamp
        # check merkle hash
        
               
        if self.bco.check_chain_len()==0:
            previoushash = True
        
        else:
            previoushash = block.previoushash == previous_block_hash(self.bco.pre_block())#sha256("{index}{previoushash}{timestamp}{hash}{datahash}{nonce}{targetbit}".format(**self.pre_block())).hexdigest()
        
        timestamp = float(block.timestamp) < time.time()
        
        index = block.index == self.bco.check_chain_len()+1
        
        datahash = merkle_hash(block.dataload)
        
        if previoushash and timestamp and index and datahash:
            return True
        
        print "[+] Block Condition Failur During MineBLock Verification."
        print "[-] Previous hash verify  : ", previoushash 
        #print "[-] Proof Of Work verify  : ",  proof_of_work_hash 
        print "[-] Timestamp verify      : ",  timestamp 
        print "[-] Block Index verify    : ",  index 
        print "[-] Block Datahash verify : ",  datahash 
        return False
    
    def load(self, block):
        '''
        Load Block
        '''
        
        time.sleep(2)  # To pass timestamp condition
        
        
        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[106]:


#
# 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()
            
    def getchain(self):
        return self.chain
    
    def search_transection_dict(self, txnid):
        for b in self.chain['blockchain'][::-1]:
            for l in b['dataload']:
                if l['txn']==txnid:
                    return l
        return False
    
    def get_all_transections(self, address):
        rectxn = []
        sentxn = []
        for b in self.chain['blockchain'][::-1]:
            for l in b['dataload']:
                txn =  l['txn']
                n = l['load']
                if n['sender']==address:
                    sentxn.append(l)
                if n['receiver']==address:
                    rectxn.append(l)
        
        return (rectxn, sentxn)
        
        
    # add genesis block request
    def add_genesis_block(self):
        '''
        Add Genesis Block
        '''
        print "[+] Add Genesis Block Request."
        tmpobj = RequestBlock(self)
        mineblock = MineBlock(self)
        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. Index : ", block.index
        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 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 "[+] Block Condition Failur During SimpleBLockChain Verification Member Function."
        print "[-] Previous hash verify  : ",  previoushash 
        print "[-] Proof Of Work verify  : ",  proof_of_work_hash 
        print "[-] Timestamp verify      : ",  timestamp 
        print "[-] Block Index verify    : ",  index 
        print "[-] Block Datahash verify : ",  datahash 
        print "[-] Block Targetbit verify: ",  diff
        return False
        
    # Check block chain length
    def check_chain_len(self):
        return len(self.chain['blockchain'])
    
    def pre_block(self):
        if self.chain['blockchain']:
            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
    
    
    def get_address_trans(self, address):
        received = []
        sent = []
        changes = []
    
        retxn, setxn = self.get_all_transections(address)
    
        # Receiving Transection List
        for r in retxn:
            received.append((float(r['load']['coin']), r['txn']))
    
        # Spent Transection list
        for s in setxn:
            sent.append((float(s['load']['coin'])+float(s['load']['fee']), s['txn']))
        
            if s['load']['ccoin']:
                changes.append((float(s['load']['ccoin']), s['txn']))
        
        return (received, sent, changes)

    def get_address_balance(self, address):
        rec, sen, cha = self.get_address_trans(address)
    
        r = 0.0
        s = 0.0
        for amount, txnid in rec:
            r+= amount
        for amount, txnid in sen:
            s+= amount
    
        return r-s
    
    def double_spend_check(self, address, txn):
        rcv, snt = self.get_all_transections(address)
        input_transections = []
        
        for t in snt:
            k=t['load']['txni']
            n = len(k)/64
            for i in range(n):
                tmp = k[i*64: (i+1)*64]
                if tmp:
                    input_transections.append(tmp)
                
        if txn in input_transections:
            print "[X] Double Spend Found : ", txn
            
            return True
        print "[x] Double Spend Clear : ", input_transections, txn
        return False
 


    
    
    
    


# In[107]:


class PleaseMine:
    def __init__(self, sbc, auth, transreq = []):
        self.sbc = sbc
        self.auth = auth
        self.drop_fraud_minning_requests(transreq)
        self.add_award_transection()
        
    def drop_fraud_minning_requests(self, transreq):
        self.transreq = []
        
        for trans in transreq:
            if trans.category=="mine":
                pass
            elif trans.category=='send':
                self.transreq.append(trans)
            else:
                print "[x] Unknown Input Transections : ", transreq
        return
        
    def add_award_transection(self):
        req = RequestTransection(self.auth)
        #create_transection
        req.create_transection(category='mine', 
                               coin='25', 
                               receiver = self.auth.address)
        self.reward_txn = req.transection
        self.transreq.append(req)
        
        # assemble all transection and create a block object
        reqblock = RequestBlock(
            self.sbc,
            transbuffer=self.transreq
            )
    
        # Miner Object
        mineblock = MineBlock(self.sbc)


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


        # print proof of work
        #print mineblock.getitems()

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


# In[108]:


import os
import pickle


# In[109]:



class Wallet:
    def __init__(self, db = 'walletdb.json'):
        self.dbname = db
        self.username = None
        self.password = None
        
        self.retreive_wallet()
        
        
    def create_new_user(self, username, password):
        # Create User Authentication Object
        u = User()
        
        self.db[username+password] = {
            'auth': pickle.dumps(u),
            'rtxn': [],
            'stxn': [],
            'bal' : [],
        }
        
        return
    
    def check_account(self, username, password):
        if username+password in self.db.keys():
            return True
        return False
    
    def load_account(self, username, password):
        if self.check_account(username, password):
            self.auth = pickle.loads(self.db[username+password]['auth'])
            self.rtxn = self.db[username+password]['rtxn']
            self.stxn = self.db[username+password]['stxn']
            self.bal = self.db[username+password]['bal']
        return
        
    def retreive_wallet(self):
        if os.path.exists(self.dbname):
            self.db = json.load(open(self.dbname, 'r'))
        else:
            self.db = {}
            
        return
    
    def refresh(self):
        self.close()
        self.retreive_wallet()
        return
    
    def close(self):
        tmp = open(self.dbname, 'w')
        json.dump(self.db, tmp, sort_keys=True, indent=4, separators=(',', ': '))
        tmp.close()
        return
        


# In[110]:



if __name__=='__main__':
    # -----------------------------------------------------------
    # ================= Global Object ===========================
    # -----------------------------------------------------------
    # Create Blockchain handler object
    sbc = SimpleBlockChain() 


    w = Wallet()
    w.create_new_user('suraj', 'singh')
    w.refresh()
    w.load_account('suraj', 'singh')
    # ------------------------------------------------------------
    # ==================== Miner =================================
    # ------------------------------------------------------------


    # Create User Authentication Object
    u = w.auth #= User()
    print "[*] Miner Address : ", u.address


    # [Mining First Block]
    miner = PleaseMine(sbc, u)
    print "[*] Miner Reward : ", miner.reward_txn['txn']


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

    node = User()  # Example Node
    print "[*] Node Address : ", node.address
    # 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, 
                           fee='0.1' ,
                           coin='20',
                           ccoin = str(25.0-(20.0+0.1)),
                           txni= miner.reward_txn['txn']
                          )
    req1 = RequestTransection(u)

    req1.create_transection(category='send', 
                           sender=u.address, 
                           receiver=n_address, 
                           fee='0.1' ,
                           coin='20',
                           ccoin = str(25.0-(20.0+0.1)),
                           txni= miner.reward_txn['txn'][::-1]
                          )
    transer_money_reference_ = req.transection

    print "[+] Changes Left : ", req.ccoin

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


    u1 = User()
    #PleaseMine(sbc, u1, transreq=[req])
    #PleaseMine(sbc, u1, transreq=[req1])
    #PleaseMine(sbc, u1, transreq=[req, req1])


    sbc.close()


# In[111]:



print sbc.get_address_balance(u.address)

#retxn, setxn = sbc.get_all_transections(node.address)








To Run This Script.
Just Type:


$ python path/to/script.py

Blockchain JSON Output





{
    "blockchain": [
        {
            "datahash": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
            "dataload": [],
            "hash": "00006284e622e53b43465efa8364dc1276a9b95f2527cc3884b272471ca646d3",
            "index": 1,
            "nonce": 40892,
            "previoushash": "",
            "targetbit": 4,
            "timestamp": "1527104940.71"
        },
        {
            "datahash": "0bab71baf46e56008a760bd1893585be7cc11d128128b120fb3584691d949fd5",
            "dataload": [
                {
                    "load": {
                        "category": "mine",
                        "ccoin": "",
                        "coin": "25",
                        "fee": "",
                        "receiver": "d8c649dba3d74c641404658208dac1fb",
                        "sender": "",
                        "signature": "eMlXEm91bUf7hsDGCLjmHgD6Xr3LhhY9TSAjWSuqDNYQBhQ1hFCrmi9FIzDruoR2uatDrhmYz2fD8Ia6PxVZJ7mPC9RPaeNE2NGhqoF/wyyZX/nnqQRDZfYF75BY0PtUI8HqBm2vn6mKANAeiUfZ9uEdc48aMBdmHl70MD4p4JA=",
                        "time": "1527104942.9",
                        "txni": ""
                    },
                    "name": "b365d2a9061472e2ed270755ce96e88e280509d45d9a0ce1f1dfe4b89250f094",
                    "txn": "2e325a95a6a1d00e8ac4af041061ad5bfd6c767196c90df111b6d685b38d6037"
                }
            ],
            "hash": "0000a15c752c3352cac66858db17a2525cd12105978da2cfdeaa90b228b9c670",
            "index": 2,
            "nonce": 96223,
            "previoushash": "bdeec364fa8bf87075a5d2e0067b58e396693417f12a04cd397978d635a2660a",
            "targetbit": 4,
            "timestamp": "1527104943.9"
        }
    ],
    "lastupdate": 1527104951.334412
}



Share this

Related Posts

Previous
Next Post »