1+ from Crypto .Hash import SHA
2+ from Crypto .PublicKey import RSA
13from flask import Flask , render_template , jsonify , request
24from time import time
35from flask_cors import CORS
46from collections import OrderedDict
7+ import binascii
8+ from Crypto .Signature import PKCS1_v1_5
9+
10+ MINING_SENDER = "blockchain"
511
612
713class Blockchain :
@@ -26,22 +32,36 @@ def create_block(self, nonce, previous_hash):
2632 self .transactions = []
2733 self .chain .append (block )
2834
29- def submit_transaction (self , sender_public_key , recipient_public_key , signature , amount ):
30- # TODO: reward miner
31- # TODO: Signature validation
35+ def verify_transaction_signature (self , sender_public_key , signature , transaction ):
36+ public_key = RSA .importKey (binascii .unhexlify (sender_public_key ))
37+ verifier = PKCS1_v1_5 .new (public_key )
38+ hash = SHA .new (str (transaction ).encode ('utf8' ))
39+ try :
40+ verifier .verify (hash , binascii .unhexlify (signature ))
41+ return True
42+ except ValueError :
43+ return False
3244
45+ def submit_transaction (self , sender_public_key , recipient_public_key , signature , amount ):
46+ # Signature validation
3347 transaction = OrderedDict ({
3448 'sender_public_key' : sender_public_key ,
3549 'recipient_public_key' : recipient_public_key ,
36- 'signature' : signature ,
3750 'amount' : amount ,
3851 })
39- signature_verification = True
40- if signature_verification :
52+
53+ # reward for miner
54+ if sender_public_key == MINING_SENDER :
4155 self .transactions .append (transaction )
4256 return len (self .chain ) + 1
4357 else :
44- return False
58+ # Transaction from wallet to another wallet
59+ signature_verification = self .verify_transaction_signature (sender_public_key , signature , transaction )
60+ if signature_verification :
61+ self .transactions .append (transaction )
62+ return len (self .chain ) + 1
63+ else :
64+ return False
4565
4666
4767blockchain = Blockchain ()
@@ -60,7 +80,12 @@ def index():
6080def transactions_new ():
6181 values = request .form
6282
63- # TODO: check required fields
83+ # check required fields [Notes: This is just a demo, not production code, so not checking thoroughly, just doing
84+ # basic checks]
85+ required = ['confirmation_sender_public_key' , 'confirmation_recipient_public_key' , 'transaction_signature' , 'confirmation_amount' ]
86+ if not all (k in values for k in required ):
87+ return 'Missing Values' , 400
88+
6489 transaction_results = blockchain .submit_transaction (values ['confirmation_sender_public_key' ],
6590 values ['confirmation_recipient_public_key' ],
6691 values ['transaction_signature' ], values ['confirmation_amount' ])
0 commit comments