classStringUtils: @staticmethod defsha256(msg): sh = hashlib.sha256() sh.update(msg) return sh.hexdigest()
下面为Block类添加一个计算hash的方法: 代码清单 block.py
1 2 3 4
from strutils import StringUtils ... defcalculateHash(self): return StringUtils.sha256(self.previousHash+self.data+str(self.nonce)+str(self.timeStamp))
创建几个区块打印hash测试一下是否能正确运行: 代码清单 noobchain.py
1 2 3 4 5 6 7 8
from block import Block
genesisBlock = Block("Hi im the first block", "0") print"Hash for block 1: " + genesisBlock.hash secondBlock = Block("Hi im the second block", genesisBlock.hash) print"Hash for block 2: " + secondBlock.hash thirdBlock = Block("Hi im the third block", secondBlock.hash) print"Hash for block 3: " + thirdBlock.hash
1 2 3 4
$ python noobchain.py Hash for block 1: 9dbe25df31f62ecdda90aac0ab7b25603fcdada1f890c910a7e8007560ef9689 Hash for block 2: bb2983a4837cdd83acdf398929babb592c8f9d4165b3eec07279d1bfcc49d199 Hash for block 3: 1e2b74ee552ae2a59b5215eaab87e896e11c33e94541917323d1f2e58f47fa87
blockchain.append(Block('Hi im the first block', '0')) blockchain.append(Block('Yo im the second block', blockchain[len(blockchain)-1].hash)) blockchain.append(Block('Hey im the third block', blockchain[len(blockchain)-1].hash))
blockdict = [] for b in blockchain: blockdict.append(b.__dict__)
defisChainValid(): for i inrange(1, len(blockchain)): curblock = blockchain[i] preblock = blockchain[i-1] if curblock.hash != curblock.calculateHash(): print'Current Hashes not equal' returnFalse if preblock.hash != curblock.previousHash: print'Previous Hashes not equal' returnFalse returnTrue
blockchain.append(Block('Hi im the first block', '0')) print'Trying to mine block 1...' blockchain[0].mineBlock(difficulty)
blockchain.append(Block('Yo im the second block', blockchain[len(blockchain)-1].hash)) print'Trying to mine block 2...' blockchain[1].mineBlock(difficulty)
blockchain.append(Block('Hey im the third block', blockchain[len(blockchain)-1].hash)) print'Trying to mine block 3...' blockchain[2].mineBlock(difficulty)
print'Blockchain is Valid:' + str(isChainValid())
blockdict = [] for b in blockchain: blockdict.append(b.__dict__)