1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| ''' 一个区块的结构 { "index":0, //索引 "timestamp":"", //时间戳 "proof":"", //工作量证明 "transactions":[ //交易 "sender":"", //交易发出者 "receiver":"", //交易接收者 "amount":5, //交易金额 ], "prehash":"", //前一块区块的hash值 } '''
import hashlib import json import time
class BlockChain:
def __init__(self): self.chain = [] self.current_transactions = []
self.new_block(proof = 100, pre_hash= 1)
def new_block(self, proof, pre_hash = None):
block = { 'index':len(self.chain) + 1, 'timestamp': time.time(), 'transactions':self.current_transactions, 'proof':proof, 'pre_hash':pre_hash or self.hash(self.chain[-1]) }
self.current_transactions = [] self.chain.append(block)
return block
def new_transactions(self, sender, receiver, amount) ->int: self.current_transactions.append( { 'sender':sender, 'receiver':receiver, 'amount':amount } ) return self.last_block['index'] + 1
@staticmethod def hash(block): block_sring = json.dumps(block, sort_keys=True).encode() hashlib.sha256(block_sring).hexdigest()
@property def last_block(self): return self.chain[-1]
def proof_of_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" ''' if guess_hash[0:4] == "0000": return True else: return False ''' if __name__ == "__main__": testPow = BlockChain() testPow.proof_of_work(100)
|