区块链

python BlockChain(一)区块链结构

2018-06-30  本文已影响1人  ab64fd4eaee3
# {
#     "index":0,
#     "timestmp": "",
#     "transactions":[
#         {
#             "sender":" ",
#             "recipient":"",
#             "amount":5
#
#         }
#     ],
#     "proof":"",
#     "previous_hash":""
#
# }
import hashlib
from time import time
import json


class BlockChain:
    def __init__(self):
        self.chain = []
        self.current_transactions = []

        self.new_block(proof=1, previous_hash=1)

    def new_block(self, proof, previous_hash=None):
        block = {
            'index': len(self.chain) + 1,
            'timestamp': time(),
            'transcations': self.current_transactions,
            'proof': proof,
            'previous_hash': previous_hash or self.hash(self.last_block)
        }
        self.current_transactions = []
        self.chain.append(block)

    def new_transaction(self, sender, recipient, amount) -> int:
        self.current_transactions.append(
            {
                'sender': sender,
                'recipient': recipient,
                'amount': amount
            }
        )
        return self.last_block["index"] + 1

    @property
    def last_block(self):
        return self.chain[-1]

    @staticmethod
    def hash(block):
        block_string = json.dumps(block, sort_keys=True).encode()
        return hashlib.sha256(block_string).hexdigest()

    def proof_work(self, last_proof: int) -> int:
        proof = 0
        while self.valid_proof(last_proof, proof) is False:
            proof += 1

        print(proof)
        return proof

    def valid_proof(self, last_proof: int, proof: int) -> bool:
        guess = f
        '{last_proof}{proof}'.encode()
        guess_hash = hashlib.sha256(guess).hexdigest()

        print(guess_hash)
        return guess_hash[0:4] == "0000"


#testPow = BlockChain()
#testPow.proof_work(100)

app = Flask(__name__)

if __name__ == '__main__':
    app.run(host="0.0.0.0",port=5000)

运行服务

 pipenv run python blockchain.py
上一篇下一篇

猜你喜欢

热点阅读