def resolve(self): winnerChain = self.__chain replace = False for node in self.__peerNodes: url = 'http://{}/chain'.format(node) # try: response = requests.get(url) nodeChain = response.json() nodeChain = [ Block(block['index'], block['previousHash'], [ Transaction(tx['copyrightOwner'], tx['picUrl'], tx['signature'], tx['picPhash']) for tx in block['transactions'] ], block['proof'], block['timestamp']) for block in nodeChain ] nodeChainLength = len(nodeChain) localChainLength = len(winnerChain) print nodeChainLength > localChainLength print Verification.verifyChain(nodeChain) if nodeChainLength > localChainLength and Verification.verifyChain( nodeChain): winnerChain = nodeChain replace = True # except requests.exceptions.ConnectionError: # print 'requestsErr' # continue self.resolveConflicts = False self.__chain = winnerChain if replace: self.__openTransactions = [] self.saveData() return replace
def listenForImput(self): """命令行函数""" waitingForInput = True while waitingForInput: print("帮助:") print("1:添加新的事务") print("2:挖掘新区块") print("3:打印所有区块") print("4:创建用户") print("5:加载用户") print('6:保存公私钥') print("q:退出") userChoice = input("请选择一项并执行:") # 命令行列表 if userChoice == '1': txData = self.getTransactionValue() picUrl, phash = txData signature = self.user.signTransaction(self.user.publicKey, picUrl, phash) if self.blockChain.addTransaction(self.user.publicKey, picUrl, signature, phash): print(self.blockChain.getOpenTransactions()) else: print('事务添加失败') elif userChoice == '2': if not self.blockChain.mineBlock: print('挖掘失败,请检查是否存在已加载或创建的用户') elif userChoice == '3': self.printAllBlock() elif userChoice == '4': self.user.createKeys() self.blockChain = BlockChain(self.user.publicKey) elif userChoice == '5': self.user.loadKeys() self.blockChain = BlockChain(self.user.publicKey) elif userChoice == '6': self.user.saveKeys() elif userChoice == 'q': waitingForInput = False else: print("参数不合法,请重新输入") continue if not Verification.verifyChain(self.blockChain.getChain()): print("区块链不合法") waitingForInput = False