pipinstallFlaskrequest
classBlockchain(object):
def__init__(self): self.chain=[]
classBlockchain(object):def__init__(self):self.chain=[]self.current_transactions=[]
defaddBlock(self):passdefaddTransaction(self):pass
@staticmethoddefhash(block):pass
@propertydeflastBlock(self):pass
defnew_transaction(self,sender,recipient,amount):
self.current_transactions.append({'sender':sender,'recipient':recipient,'amount':amount,})
returnself.last_block['index']+1
defaddTransaction(self,sender,recipient,amount):self.current_transactions.append({'sender':sender,'recipient':recipient,'amount':amount,})returnself.last_block['index']+1
self.new_block(previous_hash=1,proof=100)
defaddBlock(self,proof,previous_hash=None):block={'index':len(self.chain)+1,'timestamp':time(),'transactions':self.current_transactions,'proof':proof,'previous_hash':previous_hashorself.hash(self.chain[-1]),}self.current_transactions=[]self.chain.append(block)returnblock
@staticmethoddefhash(block):block_string=json.dumps(block,sort_keys=True).encode()returnhashlib.sha256(block_string).hexdigest()
@propertydeflast_block(self):returnself.chain[-1]
importhashlibimportjsonfromtimeimporttimefromuuidimportuuid4
defproof_of_work(self,last_proof):
@staticmethoddefvalid_proof(last_proof,proof):
defproof_of_work(self,last_proof):proof=0whileself.valid_proof(last_proof,proof)isFalse:proof+=1returnproof@staticmethoddefvalid_proof(last_proof,proof):guess=f'{last_proof}{proof}'.encode()guess_hash=hashlib.sha256(guess).hexdigest()returnguess_hash[:4]=="0000"
fromflaskimportFlaskapp=Flask(__name__)node_identifier=str(uuid4()).replace('-','')blockchain=Blockchain()@app.route('/mine',methods=['GET'])defmine():return"MininganewBlock"@app.route('/transactions/new',methods=['POST'])defnew_transaction():return"AddinganewTransaction"@app.route('/chain',methods=['GET'])deffull_chain():response={'chain':blockchain.chain,'length':len(blockchain.chain),}returnjsonify(response),200if__name__=='__main__':app.run(host='0.0.0.0',port=5000)
@app.route('/transactions/new',methods=['POST'])defnewTransaction():values=request.get_json()required=['sender','recipient','amount']ifnotall(kinvaluesforkinrequired):return'Missingvalues',400index=blockchain.new_transaction(values['sender'],values['recipient'],values['amount'])response={'message':f'TransactionwillbeaddedtoBlock{index}'}returnjsonify(response),201
证明
矿工奖励
新区块+将其添加到链中
@app.route('/mine',methods=['GET'])defmine():last_block=blockchain.last_blocklast_proof=last_block['proof']proof=blockchain.proof_of_work(last_proof)blockchain.new_transaction(sender="0",recipient=node_identifier,amount=1,)previous_hash=blockchain.hash(last_block)block=blockchain.new_block(proof,previous_hash)response={'message':"NewBlockCreated",'index':block['index'],'transactions':block['transactions'],'proof':block['proof'],'previous_hash':block['previous_hash'],}returnjsonify(response),200
$pythonapp.py$Runningonhttp://127.0.0.1:5000/(PressCTRL+Ctoquit)
$curl-XPOST-H"Content-Type:application/json"-d'{"sender":"d4ee26eee15148ee92c6cd394edd974e","recipient":"address2","amount":5}'"http://localhost:5000/transactions/new"
{"chain":[{"index":1,"previous_hash":1,"proof":100,"timestamp":1606910340,"transactions":[]},}
importrequestsfromtimeimporttimeimporthashlibimportjsonfromflaskimportFlaskfromtimeimporttimefromuuidimportuuid4classBlockchain(object):app=Flask(__name__)node_identifier=str(uuid4()).replace('-','')blockchain=Blockchain()@app.route('/mine',methods=['GET'])defmine():last_block=blockchain.last_blocklast_proof=last_block['proof']proof=blockchain.proof_of_work(last_proof)blockchain.new_transaction(sender="0",recipient=node_identifier,amount=1,)previous_hash=blockchain.hash(last_block)block=blockchain.new_block(proof,previous_hash)response={'message':"NewBlockForged",'index':block['index'],'transactions':block['transactions'],'proof':block['proof'],'previous_hash':block['previous_hash'],}returnjsonify(response),200@app.route('/transactions/new',methods=['POST'])defnewTransaction():values=request.get_json()required=['sender','recipient','amount']ifnotall(kinvaluesforkinrequired):return'Missingvalues',400index=blockchain.new_transaction(values['sender'],values['recipient'],values['amount'])response={'message':f'TransactionwillbeaddedtoBlock{index}'}returnjsonify(response),201@app.route('/chain',methods=['GET'])deffull_chain():response={'chain':blockchain.chain,'length':len(blockchain.chain),}returnjsonify(response),200if__name__=='__main__':app.run(host='0.0.0.0',port=5000)def__init__(self):self.chain=[]self.current_transactions=[]defproof_of_work(self,last_proof):proof=0whileself.valid_proof(last_proof,proof)isFalse:proof+=1returnproof@staticmethoddefvalid_proof(last_proof,proof):guess=f'{last_proof}{proof}'.encode()guess_hash=hashlib.sha256(guess).hexdigest()returnguess_hash[:4]=="0000"defaddBlock(self,proof,previous_hash=None):block={'index':len(self.chain)+1,'timestamp':time(),'transactions':self.current_transactions,'proof':proof,'previous_hash':previous_hashorself.hash(self.chain[-1]),}self.current_transactions=[]self.chain.append(block)returnblockdefaddTransaction(self,sender,recipient,amount):self.current_transactions.append({'sender':sender,'recipient':recipient,'amount':amount,})returnself.last_block['index']+1@staticmethoddefhash(block):block_string=json.dumps(block,sort_keys=True).encode()returnhashlib.sha256(block_string).hexdigest()@propertydeflast_block(self):returnself.chain[-1]
作者:链三丰,来源:区块链研究实验室
郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。
郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。