def start_peermgr() -> bool: if nodeproperty.My_IP_address != peermgr_IP: monitoring.log('log.Only a node with a predefined IP can run PeerMgr.') return False monitoring.log( 'log.Start listening thread to wait for connection of PeerConnector.') listening_to_peerconnector_thr = ListeningToPeerConnectorThread( 1, "ListeningToPeerConnectorThread", peermgr_IP, peermgr_Port, connectedPeer_rcvddata_q, connectedPeer_socket_q, connectedPeer_IP_q ) listening_to_peerconnector_thr.start() monitoring.log( 'log.The listening thread is started to wait for the connection of PeerConnector.') monitoring.log('log.Start a thread to manage ConnectedPeerList.') managing_peertable_thr = ManagingConnectedPeerListThread( 1, "ManagingConnectedPeerListThread", Predefined_peer_list, connectedPeer_rcvddata_q, connectedPeer_socket_q, connectedPeer_IP_q ) managing_peertable_thr.start() monitoring.log( 'log.The thread to manage the ConnectedPeerList has started.') return True
def genesisblock_generate(): transaction = "Base lab logchain project" prev_hash = "N/A" nonce = "N/A" merkle_root = hashlib.sha256(str(transaction).encode('utf-8')).hexdigest() vote_result = "N/A" timestamp = "20170904" block_header = block.BlockHeader(prev_hash, nonce, merkle_root, vote_result, timestamp) block_header.block_id = 'genesis_block' block_header.block_number = "1" block_header.block_info = block_header.prev_hash + block_header.merkle_root block_header.block_hash = hashlib.sha256( str(block_header.block_info).encode('utf-8')).hexdigest() block_header.miner = "Base Lab" block_header.num_tx = "1" genesisblock = block.Block(block_header, transaction) json_genesisblock = json.dumps(genesisblock, indent=4, default=lambda o: o.__dict__, sort_keys=True) file_controller.create_new_block(str(block_header.block_number), json_genesisblock) monitoring.log('log.Genesis block created now.') monitoring.log("log. - block hash: " + block_header.block_hash) monitoring.log("log. - block ID: " + block_header.block_id) monitoring.log("log. - block info: " + block_header.block_info) monitoring.log("log. - block transaction: " + transaction)
def initialize(): monitoring.log('log.Start the blockchain initialization process...') file_controller.remove_all_transactions() file_controller.remove_all_blocks() file_controller.remove_all_voting() monitoring.log('log.Complete the blockchain initialization process...') set_peer.init_myIP()
def get_last_block(): block_list = [] block_list_size = 0 for (path, dir, files) in os.walk(block_storage_path): block_list = files block_list_size = len(files) j = 0 for i in block_list: block_list[j] = int(i) j = j + 1 # last_block_file_name = block_list[-1] last_block_file_name = str(block_list_size) monitoring.log("log.last_block_file_name is .. "+ last_block_file_name) # monitoring.log("log."+last_block_file_name+type(last_block_file_name)) last_block_tx_list = read_all_line( str(block_storage_path) + last_block_file_name) last_block = "\n".join(last_block_tx_list) a = json.loads(last_block) return a['block_header']['block_number'], a['block_header']['block_hash']
def remove_all_blocks(): try: shutil.rmtree(block_storage_path) os.makedirs(block_storage_path) monitoring.log('log.All blocks were removed.') except Exception as e: print(e)
def run(self): while True: rcvd_data = self.rcvddata_q.get() request_sock = self.socket_q.get() socketip = self.socketip_q.get() # Assuming the format of the incoming message is json rcvd_data_json = json.loads(rcvd_data) peerid = rcvd_data_json['ID'] monitoring.log("log.The ID of ConnectedPeer: " + peerid) monitoring.log("log.The IP of ConnectedPeer: " + socketip) if peerid in self.peer_list: monitoring.log("log.Add new peer's IP to ConnectedPeerList.") nodeproperty.ConnectedPeerList.append([peerid, socketip]) nodeproperty.ConnectedPeerList.sort() request_sock.close() connected_peer_list_json = json.dumps( nodeproperty.ConnectedPeerList, indent=4, default=lambda o: o.__dict__, sort_keys=True) monitoring.log( "log.Updated ConnectedPeerList(json format): " + connected_peer_list_json) sender.send_to_all_peers_except_itself( connected_peer_list_json, peerconnector_Port) set_peer.set_my_peer_num() set_peer.set_total_peer_num() else: request_sock.close() # If there is no ID in the peer list, ignore it. monitoring.log( "log.Ignore it because there is no corresponding ID in the predefined list.")
def connect_to_peermgr(): monitoring.log('log.Start a thread to connect to PeerMgr.') # TODO: If there is no response after pinging PeerMgr, attempt to connect to another PeerMgr. # Returns False if all attempts to connect to the PeerMgr fail. connecting_to_peermgr_thr = ConnectingToPeerMgrThread( 1, "ConnectingToPeerMgrThread", peermgr_IP, peermgr_Port) connecting_to_peermgr_thr.start() monitoring.log('log.The thread to connect to PeerMgr has started.')
def send_to_all_node(message, my_ip, my_port): address_list = file_controller.get_ip_list() for addr in address_list: try: send(addr, message, my_port) except Exception as e: print(e) monitoring.log("log." + "send block")
def transaction_validation(): monitoring.log('log.validation.tx') hash_value = request.json["hash_value"] block_id = request.json["block_id"] block = search.search_block(block_id) request_transaction, block_transaction, validation_value = validation.tx_validation(hash_value, block) return jsonify({ "request_transaction": request_transaction, "block_transaction": block_transaction, "validation": validation })
def get_my_ip_rpi(): iflist = netifaces.interfaces() if 'wlan0' in iflist: ip = netifaces.ifaddresses('wlan0')[netifaces.AF_INET][0]['addr'] monitoring.log("log.IP address:" + ip) return ip elif 'eth0' in iflist: ip = netifaces.ifaddresses('eth0')[netifaces.AF_INET][0]['addr'] monitoring.log("log.IP address:" + ip) return ip
def set_my_peer_num() -> int: if nodeproperty.My_IP_address == None: init_myIP() p_num = 1 for i in peerproperty.nodeproperty.ConnectedPeerList: if i[1] == nodeproperty.My_IP_address: nodeproperty.My_peer_num = p_num else: p_num = p_num + 1 monitoring.log("log.my peer num: "+str(nodeproperty.My_peer_num)) return nodeproperty.My_peer_num
def receive_event(p_thrd_name, p_inq): total_tx_count = 1 while True: monitoring.log("log.Wait for transaction creation request.") dequeued = p_inq.get() tx = transaction.Transaction(dequeued) # temp = json.dumps( # tx, indent=4, default=lambda o: o.__dict__, sort_keys=True) # for try temp = json.dumps(tx, default=lambda o: o.__dict__, sort_keys=True) # sender.send_to_all(temp) sender.send_to_all_peers(temp, nodeproperty.My_receiver_port) monitoring.log("log.Transaction creation request - rcvd: " + str(dequeued)) monitoring.log("log.Transaction creation request - rcvd(json): " + str(temp)) monitoring.log("log.Total number of transaction creation request: " + str(total_tx_count)) # monitoring.log("log."+str(p_inq.qsize())) total_tx_count = total_tx_count + 1
def receive_event(p_thrd_name, p_inq): total_tx_count = 1 while True: monitoring.log("log.Waiting the request for contract deployment.") (restapi_request_json, restapi_request_ip) = p_inq.get() tx = transaction.Transaction('CT', restapi_request_ip, restapi_request_json) # temp = json.dumps( # tx, indent=4, default=lambda o: o.__dict__, sort_keys=True) # for try temp = json.dumps(tx, default=lambda o: o.__dict__, sort_keys=True) # sender.send_to_all(temp) sender.send_to_all_peers(temp, nodeproperty.My_receiver_port) monitoring.log("log.Contract Deployment request - rcvd: " + str(restapi_request_json)) monitoring.log("log.Contract Deployment request - rcvd(json): " + str(temp)) monitoring.log("log.Total number of Contract Deployment request: " + str(total_tx_count)) # monitoring.log("log."+str(p_inq.qsize())) total_tx_count = total_tx_count + 1
def run(self): while True: rcvd_data = self.rcvddata_q.get() request_sock = self.socket_q.get() # Assuming the format of the incoming message is json rcvd_list = json.loads(rcvd_data) monitoring.log("log.Received ConnectedPeerList: " + rcvd_data) request_sock.close() nodeproperty.ConnectedPeerList = rcvd_list set_peer.set_my_peer_num() set_peer.set_total_peer_num()
def result_voting(): list = file_controller.get_voting_list() voting_count = len(list) MajorityCount = nodeproperty.Total_peer_num / 2 print("MajorityCount: "+ str(MajorityCount)) print("My number of votes: "+ str(voting_count)) if voting_count > MajorityCount : difficulty = 2 monitoring.log("log.result voting : "+ str(voting_count)) return difficulty else: difficulty = 0 return difficulty
def receive_event(p_thrd_name, p_inq): count = 1 while True: monitoring.log("log.Waiting for event") (restapi_request_json, restapi_request_ip) = p_inq.get() # 어떤 노드에게 조회 요청을 보낸 후에, 해당 노드로부터 정보를 받은 후에 출력? # 또는 해당 노드에게 직접 접근해서 조회요청을 보내고, 정보를 받은 후에 출력 # 낭종호 교수님 연구실에서 개발을 해야할 부분인듯한데...이는 1차년도 시연에서 제외하는 것이 맞는것인지 확인 필요 2017-09-27 monitoring.log("log." + str(restapi_request_json)) logging.debug(count) logging.debug(str(p_inq.qsize())) count = count + 1 time.sleep(queue_strategy.QUERY_DEQUEUE_INTERVAL)
def send(p_ip, p_msg, p_port, *args): # if p_ip == nodeproperty.my_node.self_node: # # print "Error" # receiver_addr = (p_ip, p_port) # # tcp_socket = socket(AF_INET, SOCK_STREAM) # # try: # # tcp_socket.connect(receiver_addr) # tcp_socket.settimeout(5) # tcp_socket.send(p_msg.encode('utf-8')) # # except Exception as e: # print(e) # # tcp_socket.close() # # else: receiver_addr = (p_ip, p_port) tcp_socket = socket(AF_INET, SOCK_STREAM) print("receiver addr =" + str(p_ip) + " , " + str(p_port)) monitoring.log("log." + "receiver addr =" + str(p_ip) + " , " + str(p_port)) print(" ") try: tcp_socket.connect(receiver_addr) print("connected........") monitoring.log("log." + "connected........") tcp_socket.settimeout(2) print(p_msg) monitoring.log("log." + p_msg) tcp_socket.send(p_msg.encode('utf-8')) monitoring.log("log.end send") except Exception as e: print(e) tcp_socket.close() monitoring.log("log.Sending complete")
def send_to_all_peers_except_itself(p_msg, p_port): monitoring.log("log.Send to all peers in ConnectedPeerList") for peer in peerproperty.nodeproperty.ConnectedPeerList: if peer[1] == peerproperty.nodeproperty.My_IP_address: monitoring.log("log.Do not send msg it to peer itself.") else: try: send(peer[1], p_msg, p_port) except Exception as e: print(e) monitoring.log("log.ConnectedPeerList ID: " + peer[0]) monitoring.log("log.ConnectedPeerList IP: " + peer[1])
def init_myIP(): monitoring.log("log.Set the peer's own IP address.") os = platform.system() if os == 'Linux': monitoring.log("log.Peer's os is Linux.") # For raspberry pi, we use wlan, # so we need to figure out the IP address in a different way. nodeproperty.My_IP_address = file_controller.get_my_ip_rpi() elif os == 'Windows': monitoring.log("log.Peer's os is Windows.") nodeproperty.My_IP_address = file_controller.get_my_ip() monitoring.log("log.Peer's IP: " + nodeproperty.My_IP_address)
def run(self): addr = (self.listening_ip, self.listening_port) buf_size = 100 tcp_socket = socket(AF_INET, SOCK_STREAM) tcp_socket.bind(addr) tcp_socket.listen(5) while True: monitoring.log('log.Wait for PeerConnector to connect.') request_sock, request_ip = tcp_socket.accept() monitoring.log('log.PeerConnector connected.') monitoring.log("log.PeerConnector IP: " + request_ip[0]) while True: rcvd_total = [] while True: # Assuming the format of the incoming message is json rcvd_pkt = request_sock.recv(buf_size) if not rcvd_pkt: break rcvd_total.append(rcvd_pkt) rcvd_data = "" for i in rcvd_total: rcvd_data += i.decode('utf-8') logging.debug("rcvd_data: " + rcvd_data) if rcvd_data == "": break try: self.rcvddata_q.put(rcvd_data) self.socket_q.put(request_sock) self.socketip_q.put(request_ip[0]) break except Exception as e: logging.debug(e)
def tx_save(): monitoring.log('log.request(save tx) rcvd...') if not request.json or not 'tx_title' in request.json: abort(400) savetx_q.put((request.json, request.remote_addr)) monitoring.log("log."+str(savetx_q)) monitoring.log("log."+str(savetx_q.qsize())) monitoring.log("transaction." + str(savetx_q) + '(' + str(savetx_q.qsize()) + ')') return jsonify({ "tx_title": request.json["tx_title"], "tx_body": request.json["tx_body"], 'info' : "You can see the tx address via the following link:" "http://host:5000/info/tx/" }), 201
def receive_event(p_thrd_name, p_inq): while True: monitoring.log("log.Waiting for V type msg") (recv_data, request_sock) = p_inq.get() # recv_data = p_inq.get() # request_sock = p_socketq.get() monitoring.log("log.V type msg rcvd: " + recv_data) file_controller.add_voting(recv_data) monitoring.log("voting." + recv_data) difficulty = voting.result_voting() if (difficulty > 0): monitoring.log("Enter block generator") block_generator.generate_block(difficulty, transaction.Merkle_root, transaction.Transactions) else: monitoring.log("log.") request_sock.close()
def send_to_all_peers(p_msg, p_port): monitoring.log("log.Send to all peers in ConnectedPeerList") for peer in peerproperty.nodeproperty.ConnectedPeerList: try: send(peer[1], p_msg, p_port) except Exception as e: print(e) monitoring.log("log.ConnectedPeerList ID: " + peer[0]) monitoring.log("log.ConnectedPeerList IP: " + peer[1])
def tx_save(): monitoring.log('log.request(save tx) rcvd...') savetx_q.put((request.json, request.remote_addr)) monitoring.log("log."+str(savetx_q)) monitoring.log("log."+str(savetx_q.qsize())) time.sleep(5) block = file_controller.get_last_block_payup() hashvalue = hashlib.sha256(str(block["tx_list"]).encode('utf-8')).hexdigest() return jsonify({ "status" : "pay_up transaction request complete", "block Id " : block['block_header']['block_id'], "hash_value": hashvalue })
def contract_deploy(): monitoring.log('log.request(deploy smart contract) rcvd.') if not request.json or not 'contract_title' in request.json or not 'contract_body' in request.json or not 'contract_args' in request.json: abort(400) smartcontract_deploy_q.put((request.json,request.remote_addr)) monitoring.log("log."+str(smartcontract_deploy_q)) monitoring.log("log." + str(smartcontract_deploy_q.qsize())) return jsonify({ "contract_title": request.json["contract_title"], "contract_body": request.json["contract_body"], "contract_args": request.json["contract_args"], 'info' : "You can see the deployed contract address list via the following link:" "http://host:5000/info/contract/deployed/" }), 201
def receive_event(p_thrd_name, p_inq): while True: monitoring.log("log.Waiting for B type msg") (recv_data, request_sock) = p_inq.get() Data_jobj = json.loads(recv_data) monitoring.log("log.B type msg rcvd: " + recv_data) file_controller.create_new_block( str(Data_jobj['block_header']['block_number']), recv_data) block_verify.verify_tx_list(Data_jobj['tx_list']) monitoring.log("log.End create _new block") monitoring.log("block." + str(Data_jobj['block_header']['block_number'])) # try file_controller.remove_all_transactions() file_controller.remove_all_voting() # try request_sock.close()
def contract_execute(): monitoring.log('log.request(execute contract) rcvd.') if not request.json or not 'contract_addr' in request.json or not 'contract_function' in request.json or not 'contract_args' in request.json: abort(400) smartcontract_execute_q.put((request.json, request.remote_addr)) monitoring.log("log."+str(smartcontract_execute_q)) monitoring.log("log." + str(smartcontract_execute_q.qsize())) return jsonify({ "contract_addr": request.json["contract_addr"], "contract_function": request.json["contract_function"], "contract_args": request.json["contract_args"], 'info' : "You can see the executed contract list via the following link:" "http://host:5000/info/contract/executed/" }), 201
def receive_event(p_thrd_name, p_inq, p_socketq): while True: monitoring.log("log.Waiting for B type msg") recv_data = p_inq.get() Data_jobj = json.loads(recv_data) request_sock = p_socketq.get() monitoring.log("log.B type msg rcvd: " + recv_data) file_controller.create_new_block( str(Data_jobj['block_header']['block_number']), recv_data) monitoring.log("log.End create _new block") file_controller.remove_all_transactions() file_controller.remove_all_voting() request_sock.close()
def create_rule(): monitoring.log('log.request(create rule) rcvd...') savetx_q.put(request.json) monitoring.log("log."+str(savetx_q)) monitoring.log("log."+str(savetx_q.qsize())) if not request.json or not 'title' in request.json: abort(400) rule = { 'index': rulelist[-1]['index'] + 1, 'title': request.json['title'], 'body': request.json.get('body', "") } rulelist.append(rule) return jsonify({'rule': rule}), 201
def start_peerconnector() -> bool: connect_to_peermgr() monitoring.log( 'log.Start listening thread to wait for connection of PeerMgr.') listening_to_peerconnector_thr = ListeningToPeerMgrThread( 1, "ListeningToPeerMgrThread", nodeproperty.My_IP_address, peerconnector_Port, connectedPeerMgr_rcvddata_q, connectedPeerMgr_socket_q) listening_to_peerconnector_thr.start() monitoring.log( 'log.The listening thread is started to wait for the connection of PeerMgr.' ) monitoring.log('log.Start a thread to update ConnectedPeerList.') updating_peertable_thr = UpdatingConnectedPeerListThread( 1, "UpdatingConnectedPeerListThread", connectedPeerMgr_rcvddata_q, connectedPeerMgr_socket_q) updating_peertable_thr.start() monitoring.log( 'log.The thread has started to update ConnectedPeerList that the peer has internally.' ) return True