1+ from uuid import uuid4
12from Crypto .Hash import SHA
23from Crypto .PublicKey import RSA
34from flask import Flask , render_template , jsonify , request
89from Crypto .Signature import PKCS1_v1_5
910
1011MINING_SENDER = "blockchain"
12+ MINING_REWARD = 1
1113
1214
1315class Blockchain :
1416 def __init__ (self ):
1517 self .transactions = []
1618 self .chain = []
19+ self .node_id = str (uuid4 ()).replace ('-' , '' )
1720 # create the genesis block
1821 self .create_block (0 , '00' )
1922
@@ -31,6 +34,7 @@ def create_block(self, nonce, previous_hash):
3134 # reset the current list of transactions
3235 self .transactions = []
3336 self .chain .append (block )
37+ return block
3438
3539 def verify_transaction_signature (self , sender_public_key , signature , transaction ):
3640 public_key = RSA .importKey (binascii .unhexlify (sender_public_key ))
@@ -42,6 +46,12 @@ def verify_transaction_signature(self, sender_public_key, signature, transaction
4246 except ValueError :
4347 return False
4448
49+ def proof_of_work (self ):
50+ return 123
51+
52+ def hash (self , block ):
53+ return 'abs'
54+
4555 def submit_transaction (self , sender_public_key , recipient_public_key , signature , amount ):
4656 # Signature validation
4757 transaction = OrderedDict ({
@@ -83,13 +93,33 @@ def get_transactions():
8393 return jsonify (response ), 200
8494
8595
96+ @app .route ("/mine" , methods = ['GET' ])
97+ def mine ():
98+ # We run the proof of work algo
99+ nonce = blockchain .proof_of_work ()
100+ blockchain .submit_transaction (sender_public_key = MINING_SENDER , recipient_public_key = blockchain .node_id ,
101+ signature = '' , amount = MINING_REWARD )
102+ last_block = blockchain .chain [- 1 ]
103+ previous_hash = blockchain .hash (last_block )
104+ block = blockchain .create_block (nonce , previous_hash )
105+ response = {
106+ "message" : "New block created" ,
107+ "block_number" : block ["block_number" ],
108+ "transactions" : block ["transactions" ],
109+ "nonce" : block ["nonce" ],
110+ "previous_hash" : block ["previous_hash" ],
111+ }
112+ return jsonify (response ), 201
113+
114+
86115@app .route ("/transactions_new" , methods = ['POST' ])
87116def transactions_new ():
88117 values = request .form
89118
90119 # check required fields [Notes: This is just a demo, not production code, so not checking thoroughly, just doing
91120 # basic checks]
92- required = ['confirmation_sender_public_key' , 'confirmation_recipient_public_key' , 'transaction_signature' , 'confirmation_amount' ]
121+ required = ['confirmation_sender_public_key' , 'confirmation_recipient_public_key' , 'transaction_signature' ,
122+ 'confirmation_amount' ]
93123 if not all (k in values for k in required ):
94124 return 'Missing Values' , 400
95125
0 commit comments