def start_block_building(self): if (int(level_param.get_block_num(PARAM_P) + len(self.bm.chain)) < (SAVE_BORDER - 5)) and SKIP_INTERVAL: CHECK_INTERVAL = 0 else: if RAND_INTERVAL: CHECK_INTERVAL = randint(39, 60) else: CHECK_INTERVAL = INTERVAL self.bb_timer = threading.Timer(CHECK_INTERVAL, self.__generate_block_with_tp) self.bb_timer.start()
def add_db(ldb_p, param_p, zip_p, vals: list): p = Path(ldb_p) db_list = list(p.glob("block*.ldb")) file_count = len(db_list) file_num = str(file_count + 1).zfill(6) make_ldb_path = ldb_p + "block{}.ldb".format(str(file_num)) for val in vals: lated_bl_num = level_param.get_block_num(param_p=param_p) level_param.update_key(param_p=param_p, block_num=lated_bl_num + 1) str_val = json.dumps(val) db = plyvel.DB(make_ldb_path, create_if_missing=True) db.put(str(lated_bl_num + 1).zfill(6).encode(), str_val.encode()) db.close() shutil.make_archive(zip_p + "block{}".format(str(file_num)), "zip", root_dir=make_ldb_path)
def __init__(self, my_port=50082, core_node_host=None, core_node_port=None): self.server_state = STATE_INIT print('Initializing server...') self.my_ip = self.__get_myip() print('Server IP address is set to ... ', self.my_ip) self.my_port = my_port self.cm = ConnectionManager(self.my_ip, self.my_port, self.__handle_message, self) self.mpmh = MyProtocolMessageHandler() self.core_node_host = core_node_host self.core_node_port = core_node_port self.bb = BlockBuilder() self.flag_stop_block_build = True self.is_bb_running = False if main_level.get_genesis(LDB_P): self.bm = BlockchainManager() latest_dbd_block = main_level.get_latest_block(LDB_P) self.prev_block_hash = self.bm.get_hash(latest_dbd_block) block_num = level_param.get_block_num(PARAM_P) + len(self.bm.chain) new_block = self.bb.generate_new_block({}, self.prev_block_hash, str(block_num), ADDRESS, {}, self) self.bm.set_reconnect_block(new_block.to_dict()) self.prev_block_hash = self.bm.get_hash(new_block.to_dict()) else: my_genesis_block = self.bb.generate_genesis_block() self.bm = BlockchainManager(my_genesis_block.to_dict()) self.prev_block_hash = self.bm.get_hash(my_genesis_block.to_dict()) self.tp = TransactionPool() if core_node_host and core_node_port: self.plz_share_db() else: self.flag_stop_block_build = False
def __generate_block_with_tp(self): if DEBUG: print('Thread for generate_block_with_tp started!') try: if RAND_INTERVAL: CHECK_INTERVAL = randint(39, 60) else: CHECK_INTERVAL = INTERVAL print( "■■■■■■■■■■■■■■■■■■■ Current BC ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■" ) print(self.bm.chain) # self.save_block_2_db() saved_bcs = self.bm.save_block_2_db() print("txs_hash len:", self.tp.get_txs_hash_len()) print("txs_hash:", self.tp.get_txs_hash()) # txs_hash = self.tp.get_txs_hash().values() # for t in txs_hash: # print(f"addrs:{t} / len:{len(t)}") if saved_bcs: prev_ts = 0.0 ts_list = [] for saved_bc in saved_bcs: # genesis_blockはトランザクションがハッシュ値なのでloadsできない try: self.tp.clear_my_hash_txs( json.loads(saved_bc["transactions"])) except json.decoder.JSONDecodeError: pass if prev_ts == 0.0: prev_ts = saved_bc["timestamp"] else: ts_list.append(saved_bc["timestamp"] - prev_ts) prev_ts = saved_bc["timestamp"] print("■■■■■■■■■■■■■■■■■■■") print("平均ブロック生成時間") print(sum(ts_list) / len(saved_bcs)) print("■■■■■■■■■■■■■■■■■■■") print("txs_hash len:", self.tp.get_txs_hash_len()) # print("txs_hash:", self.tp.get_txs_hash()) # while self.flag_stop_block_build is not True: if self.flag_stop_block_build is not True: # new_tp = self.tp.get_stored_transactions2() # new_tp = deepcopy(self.tp.transactions) new_tp = self.tp.get_stored_transactions3() if DEBUG: print("■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■") print("transactions", new_tp) print("■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■") # if not result: # print('Transaction Pool is empty ...') # new_block = self.bb.generate_new_block("", self.prev_block_hash) # self.bm.set_new_block(new_block.to_dict()) # self.prev_block_hash = self.bm.get_hash(new_block.to_dict()) # # message_new_block = self.cm.get_message_text(MSG_NEW_BLOCK, # # json.dumps(new_block.to_dict(), sort_keys=True, # # ensure_ascii=False)) # message_new_block = self.cm.get_message_text(MSG_NEW_BLOCK, json.dumps(new_block.to_dict())) # self.cm.send_msg_to_all_peer(message_new_block) # index = len(result) # self.tp.clear_my_transactions(index) # new_tp = self.bm.remove_useless_transaction(result) # self.tp.renew_my_transactions(new_tp) # if len(new_tp) == 0: # TODO TPが0のとき、終わるように。コメントアウトで切り替え # break # TODO ここでiteration errorでる。値変わってるせい。 txs_hash = self.tp.get_txs_hash() block_num = level_param.get_block_num(PARAM_P) + len( self.bm.chain) new_block = self.bb.generate_new_block(new_tp, self.prev_block_hash, str(block_num), ADDRESS, txs_hash, self) new_block_dic = new_block.to_dict() if not new_block_dic: print("■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■") print("■■■■■■■■■■■■■■ 負け!w ■■■■■■■■■■■■■■■") print("■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■") self.flag_stop_block_build = False self.is_bb_running = False self.bb_timer = threading.Timer( CHECK_INTERVAL, self.__generate_block_with_tp) self.bb_timer.start() return elif int(new_block_dic["block_number"]) < int( self.bm.chain[-1]["block_number"]): print("■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■") print("■■■■■■■■■■■■■■ YOU LOSE ■■■■■■■■■■■■■■■") print("■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■") self.flag_stop_block_build = False self.is_bb_running = False self.bb_timer = threading.Timer( CHECK_INTERVAL, self.__generate_block_with_tp) self.bb_timer.start() return # elif (int(new_block_dic["block_number"]) == int(self.bm.chain[-1]["block_number"])) and ( # new_block_dic["total_majority"] <= self.bm.chain[-1]["total_majority"]): # print("■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■") # print("■■■■■■■■■■■■■■ u r 少数派 ■■■■■■■■■■■■■■") # print("■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■") # self.flag_stop_block_build = False # self.is_bb_running = False # self.bb_timer = threading.Timer(CHECK_INTERVAL, self.__generate_block_with_tp) # self.bb_timer.start() # return print("ブロック生成") print(new_block_dic) if len(self.bm.chain) >= 2: print("ブロック生成時間") print( self.__calculate_gene_time(self.bm.chain[-2], self.bm.chain[-1])) if self.bm.set_new_block(new_block.to_dict(), self.prev_block_hash): self.prev_block_hash = self.bm.get_hash( new_block.to_dict()) # self.save_block_2_db() message_new_block = self.cm.get_message_text( MSG_NEW_BLOCK, json.dumps(new_block.to_dict())) self.cm.send_msg_to_all_peer(message_new_block) # index = len(result) # self.tp.clear_my_transactions(index) # 排除対象になったtxを取り込み済みtxから除く exclusion_txs = new_block.get_exclusion_tx() for ex_tx in exclusion_txs: try: del new_tp[ex_tx] except KeyError: pass self.tp.add_through_count(exclusion_txs) self.tp.clear_my_transactions2(new_tp) with open(f'logs/{ADDRESS}_generate_block.csv', 'a') as f: writer = csv.writer(f) writer.writerow([ datetime.now(), new_block_dic["block_number"], # new_block_dic["total_majority"], new_block_dic["nTx"], # new_block_dic["over_half"], ]) # break # print('Current prev_block_hash is ... ', self.prev_block_hash) self.flag_stop_block_build = False self.is_bb_running = False self.bb_timer = threading.Timer(CHECK_INTERVAL, self.__generate_block_with_tp) self.bb_timer.start() except: with open(f"logs/{ADDRESS}_error.log", "a") as f: print(traceback.print_exc(file=f))