def deploy_contract(public_key, private_key, type,target_ip, amount, msg,contract_source): trx_json = TransactionController.create_transaction(public_key, private_key, type, target_ip, amount, msg, contract_source) if BlockGenerator.check_block_generation_condition(): block = BlockGenerator.generate_block(trx_json) block_temp = json.dumps(block, indent=4, default=lambda o: o.__dict__, sort_keys=True) print "Sending block (" + block.block_id + ") to others" Sender.send_to_all_node(block_temp) else: print "Sending transaction to others" Sender.send_to_all_node(trx_json) FileController.add_transaction(trx_json)
def check_block_generation_condition(): from StorageManager import FileController from SeChainController import Property if FileController.get_number_of_transactions() >= Property.max_transaction: return True return False
def get_node(): from NodeManager import Node import json from SeChainController import Property from NodeManager import Ecdsa # Check node list (NodeInfo.txt) # Create New Node and Send node information to SEZIP. if FileController.get_node() is False: print("Joining SeChain") ''' need to change -> Ecdsa key pair ''' gen_public_key, gen_private_key = KeyGenerator.generation_key_pair( 2**256) node = Node.Node(Property.my_ip_address) node.public_key = gen_public_key node.private_key = gen_private_key node.private_key = Ecdsa.generate_pri_key()[0] node.public_key = Ecdsa.generate_pub_key(node.private_key)[0] node.address = Ecdsa.generate_address() # node.key_pair = Ecdsa.keyPair() ''' Date: 2016/11/11 remove redundancy field ''' json_node = { 'type': 'N', 'ip_address': node.ip_address, 'public_key': node.public_key, 'private_key': node.private_key, 'address': node.address } json_string = json.dumps(json_node, cls=JsonEncoder.json_encoder) FileController.add_node_info( json.dumps(json_node, cls=JsonEncoder.json_encoder)) return json_node, json_string # Node exist else: print("Node is already in the list") existed_node = FileController.get_node() existed_node_json = json.loads(existed_node) return existed_node_json, existed_node
def deploy_contract(public_key, private_key, type, target_ip, amount, msg, contract_source): trx_json = TransactionController.create_transaction( public_key, private_key, type, target_ip, amount, msg, contract_source) if BlockGenerator.check_block_generation_condition(): block = BlockGenerator.generate_block(trx_json) block_temp = json.dumps(block, indent=4, default=lambda o: o.__dict__, sort_keys=True) print("Sending block (" + block.block_id + ") to others") Sender.send_to_all_node(block_temp) else: print("Sending transaction to others") Sender.send_to_all_node(trx_json) FileController.add_transaction(trx_json)
def get_node(): import Node, json from SeChainController import Property from KeyGenerator import generation_key_pair import Ecdsa # Check node list (NodeInfo.txt) # Create New Node and Send node information to SEZIP. if FileController.get_node() is False: print "Joining SeChain" ''' need to change -> Ecdsa key pair ''' gen_public_key, gen_private_key = generation_key_pair(2 ** 256) node = Node.Node(Property.my_ip_address) node.public_key = gen_public_key node.private_key = gen_private_key node.private_key = Ecdsa.generate_pri_key()[0] node.public_key = Ecdsa.generate_pub_key(node.private_key)[0] node.address = Ecdsa.generate_address() # node.key_pair = Ecdsa.keyPair() ''' Date: 2016/11/11 remove redundancy field ''' json_node = { 'type': 'N', 'ip_address': node.ip_address, 'public_key': node.public_key, 'private_key': node.private_key, 'address': node.address } json_string = json.dumps(json_node, cls=JsonEncoder.json_encoder) FileController.add_node_info(json.dumps(json_node, cls=JsonEncoder.json_encoder)) return json_node, json_string # Node exist else: print("Node is already in the list") existed_node = FileController.get_node() existed_node_json = json.loads(existed_node) return existed_node_json, existed_node
def add_new_node(node_info_entity): sync_flag = False # Parameter : data_entity(JSON object) node_list = FileController.get_ip_list() for outer_list in node_list: outer_list = str(outer_list) if outer_list in node_info_entity['ip_address']: sync_flag = True if sync_flag is False: if Property.my_ip_address != node_info_entity['ip_address']: FileController.add_node_info(json.dumps(node_info_entity)) print "New node("+ node_info_entity['ip_address'] +") is added in local storage" else : print "Node(" + node_info_entity['ip_address'] + ") is already listed" return True
def print_all_transaction(): from StorageManager import FileController transaction_list = FileController.get_transaction_list() for tr in transaction_list: transaction_entity = json.loads(tr) transaction_entity['message'] = transaction_entity['message'].decode('string_escape') data = data_decode(transaction_entity['message'], transaction_entity['sender_public_key']) value = json.loads(data) print "TimeStamp : ", transaction_entity['time_stamp'], "SenderIP : ", value['sender_ip'], " ReceiverIP : ", value['receiver_ip'], " Amount : ", value['amount'], " Msg : ", value['message']
def receive_block_for_sync(*args): from StorageManager import FileController #processing response addr = (Property.my_ip_address, Property.port) buf_size = 10000 tcp_socket = socket(AF_INET, SOCK_STREAM) tcp_socket.bind(addr) tcp_socket.listen(5) while True: receive_socket, sender_ip = tcp_socket.accept() while True: data = receive_socket.recv(buf_size) sync_flag = False try: if data == "": break data_entity = json.loads(data) print("Receiving " + data_entity['type']) #if sync is finished if data_entity['type'] == 'Q': print('Block sync complete') Property.block_sync = True break # if sync is not finished, receive block elif data_entity['type'] == 'W': FileController.write( FileController.block_storage_path + data_entity['file_name'], data_entity['message']) except: traceback.print_exc() break if Property.block_sync is True: receive_socket.close() tcp_socket.close() break
def receive_block_for_sync(*args): from StorageManager import FileController #processing response addr = (Property.my_ip_address, Property.port) buf_size = 10000 tcp_socket = socket(AF_INET, SOCK_STREAM) tcp_socket.bind(addr) tcp_socket.listen(5) while True: receive_socket, sender_ip = tcp_socket.accept() while True: data = receive_socket.recv(buf_size) sync_flag = False try: if data == "": break data_entity = json.loads(data) print "Receiving " + data_entity['type'] #if sync is finished if data_entity['type'] == 'Q': print 'Block sync complete' Property.block_sync = True break # if sync is not finished, receive block elif data_entity['type'] == 'W': FileController.write(FileController.block_storage_path + data_entity['file_name'], data_entity['message']) except: traceback.print_exc() break if Property.block_sync is True: receive_socket.close() tcp_socket.close() break
def add_new_node(node_info_entity): sync_flag = False # Parameter : data_entity(JSON object) node_list = FileController.get_ip_list() for outer_list in node_list: outer_list = str(outer_list) if outer_list in node_info_entity['ip_address']: sync_flag = True if sync_flag is False: if Property.my_ip_address != node_info_entity['ip_address']: FileController.add_node_info(json.dumps(node_info_entity)) print("New node(" + node_info_entity['ip_address'] + ") is added in local storage") else: print("Node(" + node_info_entity['ip_address'] + ") is already listed") return True
def generate_block(last_transaction): from BlockManager import Block from StorageManager import FileController from SmartContractManager import ContractManager from BlockManager import BlockVerifier import hashlib import json transactions = FileController.get_transaction_list() transactions.append(last_transaction + "\n") contract_states = ContractManager.process_contract(transactions) # last block -> hash last_block_id, last_block = FileController.get_last_block() last_block_hash = hashlib.sha256(last_block).hexdigest() block = Block.Block(last_block_id, last_block_hash, transactions,contract_states) block_temp = json.dumps(block, indent=4, default=lambda o: o.__dict__, sort_keys=True) FileController.save_my_block(block_temp) return block
def node_start(): from SeChainController import Property # import thread from StorageManager import FileController from CommunicationManager import Receiver from SeChainUI import MainUI from CommunicationManager import ConnectionChecker #my node check MainController.set_my_node() print("Have got node information") MainUI.MainFrame.write_console(Property.ui_frame, "Have got node information") ''' 2016/11/11 connection check point find out the alive nodes through ping test ''' ping = ConnectionChecker.Pinger() ping.thread_count = 8 ping.hosts = FileController.get_ip_list() Property.alive_nodes = ping.start() # broadcast my node to all others and local if this is not the trust node MainUI.MainFrame.write_console(Property.ui_frame, "Broadcast my node information") NodeController.add_new_node(Property.myNode) if Property.my_ip_address != Property.trust_node_ip: NodeController.send_my_node_info(Property.myNode['ip_address']) #node listener start Property.nodeList = FileController.get_node_list() _thread.start_new_thread( Receiver.start, ("Listener_Thread", Property.my_ip_address, Property.port)) Property.node_started = True
def node_start(): import Property import thread from StorageManager import FileController from CommunicationManager import Receiver from SeChainUI import MainUI from CommunicationManager import ConnectionChecker #my node check MainController.set_my_node() print ("Have got node information") MainUI.MainFrame.write_console(Property.ui_frame, "Have got node information") ''' 2016/11/11 connection check point find out the alive nodes through ping test ''' ping = ConnectionChecker.Pinger() ping.thread_count = 8 ping.hosts = FileController.get_ip_list() Property.alive_nodes = ping.start() # broadcast my node to all others and local if this is not the trust node MainUI.MainFrame.write_console(Property.ui_frame, "Broadcast my node information") NodeController.add_new_node(Property.myNode) if Property.my_ip_address != Property.trust_node_ip: NodeController.send_my_node_info(Property.myNode['ip_address']) #node listener start Property.nodeList = FileController.get_node_list() thread.start_new_thread(Receiver.start, ("Listener_Thread", Property.my_ip_address, Property.port)) Property.node_started = True
def print_all_transaction(): from StorageManager import FileController transaction_list = FileController.get_transaction_list() for tr in transaction_list: transaction_entity = json.loads(tr) transaction_entity['message'] = transaction_entity['message'].decode( 'string_escape') data = data_decode(transaction_entity['message'], transaction_entity['sender_public_key']) value = json.loads(data) print("TimeStamp : ", transaction_entity['time_stamp'], "SenderIP : ", value['sender_ip'], " ReceiverIP : ", value['receiver_ip'], " Amount : ", value['amount'], " Msg : ", value['message'])
def request_block_sync(): from NodeManager import NodeController from StorageManager import FileController import json trust_node_ip = Property.trust_node_ip json_node, new_json_nodes = NodeController.get_node() last_file = FileController.get_last_file() json_nodes = { 'type': 'C', 'last_file': last_file, 'ip_address': json_node['ip_address'] } new_json_node = json.dumps(json_nodes) Sender.send(trust_node_ip, new_json_node, Property.port)
def send_tx(receiver_address, coin, msg, contract_source): trx_json = TransactionController.create_tx(Property.myNode['public_key'], receiver_address, coin, msg, 't', contract_source) if BlockGenerator.check_block_generation_condition(): block = BlockGenerator.generate_block(trx_json) block_temp = json.dumps(block, indent=4, default=lambda o: o.__dict__, sort_keys=True) print "Sending block (" + block.block_id+") to others" Sender.send_to_all_node(block_temp) FileController.remove_all_transactions() FileController.create_new_block(block.block_id, block_temp) else: print "Sending Transaction to others" Sender.send_to_all_node(trx_json) FileController.add_transaction(trx_json)
def send_tx(receiver_address, coin, msg, contract_source): trx_json = TransactionController.create_tx(Property.myNode['public_key'], receiver_address, coin, msg, 't', contract_source) if BlockGenerator.check_block_generation_condition(): block = BlockGenerator.generate_block(trx_json) block_temp = json.dumps(block, indent=4, default=lambda o: o.__dict__, sort_keys=True) print("Sending block (" + block.block_id + ") to others") Sender.send_to_all_node(block_temp) FileController.remove_all_transactions() FileController.create_new_block(block.block_id, block_temp) else: print("Sending Transaction to others") Sender.send_to_all_node(trx_json) FileController.add_transaction(trx_json)
def send_transaction(receiver_ip, amount, message): print "pubkey", Property.myNode['public_key'] trx_json = TransactionController.create_transaction(Property.myNode['public_key'], Property.myNode['private_key'], 't', receiver_ip, amount, message, '') #Check block generating condition if BlockGenerator.check_block_generation_condition(): block = BlockGenerator.generate_block(trx_json) block_temp = json.dumps(block, indent=4, default=lambda o: o.__dict__, sort_keys=True) print "Sending block (" + block.block_id+") to others" Sender.send_to_all_node(block_temp) FileController.remove_all_transactions() FileController.create_new_block(block.block_id, block_temp) else: print "Sending transaction to others" Sender.send_to_all_node(trx_json) FileController.add_transaction(trx_json)
def send_transaction(receiver_ip, amount, message): print("pubkey", Property.myNode['public_key']) trx_json = TransactionController.create_transaction( Property.myNode['public_key'], Property.myNode['private_key'], 't', receiver_ip, amount, message, '') #Check block generating condition if BlockGenerator.check_block_generation_condition(): block = BlockGenerator.generate_block(trx_json) block_temp = json.dumps(block, indent=4, default=lambda o: o.__dict__, sort_keys=True) print("Sending block (" + block.block_id + ") to others") Sender.send_to_all_node(block_temp) FileController.remove_all_transactions() FileController.create_new_block(block.block_id, block_temp) else: print("Sending transaction to others") Sender.send_to_all_node(trx_json) FileController.add_transaction(trx_json)
def start(thread_name, ip_address, port): import json import time import sys from StorageManager import FileController from SeChainController import Property from StorageManager import utxoDB addr = (ip_address, port) buf_size = 10000 tcp_socket = socket(AF_INET, SOCK_STREAM) tcp_socket.bind(addr) tcp_socket.listen(5) print "Receiver is started " + str(ip_address)+":"+str(port) while True: receive_socket, sender_ip = tcp_socket.accept() print sender_ip while True: data = receive_socket.recv(buf_size) sync_flag = False try: if data == "": break data_entity = json.loads(data) print "Receiving " + data print "Receiving " + data_entity['type'] if data_entity['type'] == 't' or data_entity['type'] == 'ct' or data_entity['type'] == 'rt': print "\nTransaction received from ", sender_ip ''' update UTXO db ''' FileController.add_transaction(data) break # When new node is added elif data_entity['type'] == 'N': from NodeManager import NodeController from StorageManager import FileController node_list = FileController.get_ip_list() received_ip = data_entity['ip_address'] for outer_list in node_list: outer_list = str(outer_list) if outer_list == received_ip: sync_flag = True if sync_flag is False: NodeController.add_new_node(data_entity) print "New node is connected" break #When new block is received elif data_entity['type'] == 'B': from SmartContractManager import ContractManager from BlockManager import BlockVerifier received_time = time.strftime('%Y%m%d%H%M%S', time.gmtime()) block_size = sys.getsizeof(data_entity) print "Block received: "," ", received_time print "size :", block_size if BlockVerifier.verify(data_entity) is True: FileController.remove_all_transactions() FileController.create_new_block(data_entity['block_id'], data) # Processing smart contract ContractManager.process_contract(data_entity['transactions']) break #When other node request sync block elif data_entity['type'] == 'C': from StorageManager import FileController from CommunicationManager import Sender last_file = FileController.get_last_file() #print 'my_last_file = ' + last_file #print 'last_file = ' + data_entity['last_file'] #blocks are synchronized if last_file == data_entity['last_file']: json_data = { "type": "Q", "ip_address": data_entity['ip_address'] } json_dump = json.dumps(json_data) print 'Sending block sync complete message to ' + data_entity['ip_address'] Sender.send(data_entity['ip_address'], json_dump, port) # blocks are not synchronized else: import os for root, dirs, files in os.walk(FileController.block_storage_path): for file in files: if file <= data_entity['last_file']: continue # send block else: f = open(FileController.block_storage_path + file, 'r') mess = f.read() write_file = { 'type': 'W', 'file_name': file, 'message': mess } f.close() datas = json.dumps(write_file) print 'Sending block to ' + data_entity['ip_address'] Sender.send(data_entity['ip_address'], datas, port) fin_message = { 'type': 'Q', 'ip_address': data_entity['ip_address'] } fin_json_message = json.dumps(fin_message) print 'Sending block sync complete message to ' + data_entity['ip_address'] Sender.send(data_entity['ip_address'], fin_json_message, port) break elif data_entity['type'] == 'RN': node_list = FileController.get_node_list() for n in node_list: json_data = { 'type': 'N', 'message' : n } json_dump = json.dumps(json_data) print 'Sending node information to ' + data_entity['ip_address'] Sender.send(data_entity['ip_address'], json_dump, port) fin_data = { 'type': 'QN', } fin_dump = json.dumps(fin_data) print 'Sending node info sync complete message to ' + data_entity['ip_address'] Sender.send(data_entity['ip_address'], fin_dump, port) break except: traceback.print_exc() break tcp_socket.close() receive_socket.close() print "socket closed."
def start(thread_name, ip_address, port): import json import time import sys from StorageManager import FileController from SeChainController import Property from StorageManager import utxoDB addr = (ip_address, port) buf_size = 10000 tcp_socket = socket(AF_INET, SOCK_STREAM) tcp_socket.bind(addr) tcp_socket.listen(5) print("Receiver is started " + str(ip_address) + ":" + str(port)) while True: receive_socket, sender_ip = tcp_socket.accept() print(sender_ip) while True: data = receive_socket.recv(buf_size) sync_flag = False try: if data == "": break print(data) data_entity = json.loads(data) print("Receiving " + data.decode()) print("Receiving " + data_entity['type']) if data_entity['type'] == 't' or data_entity[ 'type'] == 'ct' or data_entity['type'] == 'rt': print("\nTransaction received from ", sender_ip) ''' update UTXO db ''' FileController.add_transaction(data) break # When new node is added elif data_entity['type'] == 'N': from NodeManager import NodeController from StorageManager import FileController node_list = FileController.get_ip_list() received_ip = data_entity['ip_address'] for outer_list in node_list: outer_list = str(outer_list) if outer_list == received_ip: sync_flag = True if sync_flag is False: NodeController.add_new_node(data_entity) print("New node is connected") break #When new block is received elif data_entity['type'] == 'B': from SmartContractManager import ContractManager from BlockManager import BlockVerifier received_time = time.strftime('%Y%m%d%H%M%S', time.gmtime()) block_size = sys.getsizeof(data_entity) print("Block received: ", " ", received_time) print("size :", block_size) if BlockVerifier.verify(data_entity) is True: FileController.remove_all_transactions() FileController.create_new_block( data_entity['block_id'], data) # Processing smart contract ContractManager.process_contract( data_entity['transactions']) break #When other node request sync block elif data_entity['type'] == 'C': from StorageManager import FileController from CommunicationManager import Sender last_file = FileController.get_last_file() #print 'my_last_file = ' + last_file #print 'last_file = ' + data_entity['last_file'] #blocks are synchronized if last_file == data_entity['last_file']: json_data = { "type": "Q", "ip_address": data_entity['ip_address'] } json_dump = json.dumps(json_data) print('Sending block sync complete message to ' + data_entity['ip_address']) Sender.send(data_entity['ip_address'], json_dump, port) # blocks are not synchronized else: import os for root, dirs, files in os.walk( FileController.block_storage_path): for file in files: if file <= data_entity['last_file']: continue # send block else: f = open( FileController.block_storage_path + file, 'r') mess = f.read() write_file = { 'type': 'W', 'file_name': file, 'message': mess } f.close() datas = json.dumps(write_file) print('Sending block to ' + data_entity['ip_address']) Sender.send(data_entity['ip_address'], datas, port) fin_message = { 'type': 'Q', 'ip_address': data_entity['ip_address'] } fin_json_message = json.dumps(fin_message) print('Sending block sync complete message to ' + data_entity['ip_address']) Sender.send(data_entity['ip_address'], fin_json_message, port) break elif data_entity['type'] == 'RN': node_list = FileController.get_node_list() for n in node_list: json_data = {'type': 'N', 'message': n} json_dump = json.dumps(json_data) print('Sending node information to ' + data_entity['ip_address']) Sender.send(data_entity['ip_address'], json_dump, port) fin_data = { 'type': 'QN', } fin_dump = json.dumps(fin_data) print('Sending node info sync complete message to ' + data_entity['ip_address']) Sender.send(data_entity['ip_address'], fin_dump, port) break except: traceback.print_exc() break tcp_socket.close() receive_socket.close() print("socket closed.")