def NewUser(self, uname, encoded_udata): hashed_uname = sm3_hash(list(bytes(uname, "UTF-8"))) self.cursor.execute("INSERT INTO User(HashedName, Data) VALUES(?, ?)", ( hashed_uname, encoded_udata, )) self.connection.commit()
def GetUserData(self, uname): hashed_uname = sm3_hash(list(bytes(uname, "UTF-8"))) result_set = self.cursor.execute( "SELECT Data FROM User WHERE HashedName=?", (hashed_uname, )) data = result_set.fetchone() if data == None: return None return data[0]
def miner(): global difficulty sleep(5) print(">>>广播@%d: 矿工已启动" % time()) try: while True: try: r = requests.get("http://127.0.0.1:8888/list").json() node_list = r["list"] difficulty = max(difficulty, r["difficulty"]) except: print(">>>广播@%d: 无法连接节点tracker" % time()) continue last_block = blockchain.last_block if last_block == []: nonce = 0 else: nonce = last_block["nonce"] pow = 0 while True: guess = f"{nonce}{pow}".encode() guess_hash = sm3_hash(list(guess)) if guess_hash[:difficulty] == "".join( ["0" for i in range(difficulty)]): print(">>>广播@%d: 计算出POW: %d" % (time(), pow)) break pow += 1 # 检验POW、同步区块 successful = 0 # 发送者为 "0" 表明是新挖出的币 blockchain.new_transaction({ "sender": "0", "recipient": address, "amount": 1, "timestamp": time() }) broadcast = blockchain.new_block() broadcast["pow"] = pow for url in node_list: try: r = requests.post("http://%s:%d/checkpow" % (url["addr"], url["port"]), json=broadcast) except: continue if r.status_code == 200: successful += 1 if successful >= len(node_list["list"]): break continue # 半数以上节点通过即可 if successful >= len(node_list): print(">>>广播@%d: %s 获得1个奖励币" % (time(), address[:10])) else: blockchain.chain.remove(blockchain.last_block) # 删除新生成的区块 continue except KeyboardInterrupt: return
def valid_pow(self, last_nonce, pow): guess = f"{last_nonce}{pow}".encode() guess_hash = sm3_hash(list(guess)) return guess_hash[:difficulty] == "".join( ["0" for i in range(difficulty)])
def hash(block): block_string = json.dumps(block, sort_keys=True).encode() return sm3_hash(list(block_string))
def __sm3Hash(self, inputStr): return sm3_hash(list(bytes(inputStr, "UTF-8")))