classBlockchain(object):def__init__(self):self.chain=[]self.current_transactions=[]defnew_block(self):# Creates a new Block and adds it to the chainpassdefnew_transaction(self):# Adds a new transaction to the list of transactionpass@staticmethoddefhash(block):# Hashes a Blockpass@propertydeflast_block(self):# Returns the last Block in the chainpass
1.2. Blockchain class 생성자
123456
def__init__(self):self.chain=[]# chain에 여러 block들 들어옴self.current_transaction=[]# 임시 transaction 넣어줌# genesis block 생성self.new_block(previous_hash=1,proof=100)
1.3. new_block 함수
1 2 3 4 5 6 7 8 9101112
defnew_block(self,proof,previous_hash=None):# Creates a new Block and adds it to the chainblock={'index':len(self.chain)+1,'timestamp':time(),# timestamp from 1970'transactions':self.current_transaction,'proof':proof,'previous_hash':previous_hashorself.hash(self.chain[-1]),}self.current_transaction=[]self.chain.append(block)returnblock
1.4. new_transaction 함수
1 2 3 4 5 6 7 8 910
defnew_transaction(self,sender,recipient,amount):# Adds a new transaction to the list of transactionself.current_transaction.append({'sender':sender,# 송신자'recipient':recipient,# 수신자'amount':amount# 금액})returnself.last_block['index']+1
1.5. hash 함수
1234567
@staticmethoddefhash(block):# Hashes a Blockblock_string=json.dumps(block,sort_keys=True).encode()# hash 라이브러리로 sha256 사용returnhashlib.sha256(block_string).hexdigest()
1.6. pow(proof of work) 함수
1234567
defpow(self,last_proof):proof=0# valid proof 함수를 통해 맞을 때까지 반복적으로 검증whileself.valid_proof(last_proof,proof)isFalse:proof+=1returnproof
1.7. valid_proof 함수
12345678
@staticmethoddefvalid_proof(last_proof,proof):# 전 proof와 구할 proof 문자열 연결guess=str(last_proof+proof).encode()# 이 hash 값 저장guess_hash=hashlib.sha256(guess).hexdigest()# 앞 4자리가 0000 이면 Truereturnguess_hash[:4]=="0000"# nonce
# /chain: 현재 블록체인 보여줌# /transaction/new: 새 트랜잭션 생성# /mine: server에게 새 블록 채굴 요청fromflaskimportFlask,jsonify,requestfromblockchainimportBlockchainfromuuidimportuuid4app=Flask(__name__)# Universial Unique Identifiernode_identifider=str(uuid4()).replace("-","")blockchain=Blockchain()@app.route("/chain",methods=["GET"])deffull_chain():response={"chain":blockchain.chain,"length":len(blockchain.chain),}returnjsonify(response),200@app.route("/mine",methods=["GET"])defmine():last_block=blockchain.last_blocklast_proof=last_block["proof"]proof=blockchain.pow(last_proof)blockchain.new_transaction(sender="0",recipient=node_identifider,amount=1# coinbase transaction)# forge the new block by adding it to the chainprevious_hash=blockchain.hash(last_block)block=blockchain.new_block(proof,previous_hash)response={"message":"new block found","index":block["index"],"transactions":block["transactions"],"proof":block["proof"],"previous_hash":block["previous_hash"],}returnresponse,200@app.route("/transactions/new",methods=["POST"])defnew_transactions():values=request.get_json()required=["sender","recipient","amount"]ifnotall(kinvaluesforkinrequired):return"missing values",400# Create a new Transactionindex=blockchain.new_transaction(values["sender"],values["recipient"],values["amount"])response={"message":"Transaction will be added to Block {%s}"%index}returnjsonify(response),201if__name__=="__main__":app.run(host="0.0.0.0",port=5000)