def send_coin(coin_amount, to_user): """ A function for sending coins. Inputs: * coin_amount: A int or float amount to be sent. * to_user: Receiver's address. """ my_public_key = Wallet_Import(0, 0) my_private_key = Wallet_Import(0, 1) if isinstance(coin_amount, int): coin_amount = float(coin_amount) if not isinstance(coin_amount, float): print("This is not int or float coin amount.") return None if coin_amount < 0: print("This is negative coin amount.") return None send(my_public_key=my_public_key, my_private_key=my_private_key, to_user=to_user, amount=coin_amount)
def send_new_message(message, publickey): data = {"app": "messagingapp", "command": "newmessage", "message": message} send(Wallet_Import(0, 0), Wallet_Import(0, 1), publickey, data=data, amount=0)
def test_saving_and_importing_and_deleting_the_wallet(self): password = "******" temp_private_key = Wallet_Create(password) saved_wallets = get_saved_wallet() result = False for each_wallet in saved_wallets: if temp_private_key == (saved_wallets[each_wallet]["privatekey"]): if temp_private_key == (Wallet_Import(each_wallet, 1, password)): Wallet_Delete(each_wallet) result = True if each_wallet not in get_saved_wallet( ) else False break elif decrypt(temp_private_key, password) == (Wallet_Import( each_wallet, 1, password)): Wallet_Delete(each_wallet) result = True if each_wallet not in get_saved_wallet( ) else False break self.assertEqual(result, True, "A problem on the saving and importing the wallet.")
def send_coin(coin_amount, to_user): my_public_key = Wallet_Import(0,0) my_private_key = Wallet_Import(0,1) if not isinstance(coin_amount, float): print("This is not float coin amount.") return None if coin_amount < 0: print("This is negative coin amount.") return None send(my_public_key = my_public_key, my_private_key = my_private_key, to_user = to_user, amount = coin_amount)
def add_new_user_request(publickey): key = the_keys()["1"] data = { "app": "messagingapp", "command": "addnewuser", "n": key["n"], "e": key["e"] } send(Wallet_Import(0, 0), Wallet_Import(0, 1), publickey, data=data, amount=0) create_new_user("unknow", publickey, 0, 0)
def __init__(self, host, port, callback=None): super(Node, self).__init__() self.terminate_flag = threading.Event() self.host = host self.port = port self.callback = callback self.nodes_inbound = [] self.nodes_outbound = [] from wallet.wallet import Wallet_Import self.id = "".join([ l.strip() for l in Wallet_Import(0,0).splitlines() if l and not l.startswith("-----") ]) self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.init_server() self.message_count_send = 0 self.message_count_recv = 0 self.message_count_rerr = 0
def print_balance(): """ Prints the current wallet balance. """ balance = GetBalance(Wallet_Import(-1, 0), GetBlock()) print(balance) return balance
def callback_for_menu_items(self, *args): if not args[0] == the_settings()["wallet"]: change_wallet(args[0]) self.reflesh_balance() else: change_wallet(args[0]) Clipboard.copy(Wallet_Import(int(args[0]),3)) toast("The address has been copied to your clipboard.")
def __init__(self, host, port, callback=None): """Create instance of a Node. If you want to implement the Node functionality with a callback, you should provide a callback method. It is preferred to implement a new node by extending this Node class. host: The host name or ip address that is used to bind the TCP/IP server to. port: The port number that is used to bind the TCP/IP server to. callback: (optional) The callback that is invokes when events happen inside the network.""" super(Node, self).__init__() # When this flag is set, the node will stop and close self.terminate_flag = threading.Event() # Server details, host (or ip) to bind to and the port self.host = host self.port = port # Events are send back to the given callback self.callback = callback # Nodes that have established a connection with this node self.nodes_inbound = [] # Nodes that are connect with us N->(US)->N # Nodes that this nodes is connected to self.nodes_outbound = [] # Nodes that we are connected to (US)->N """ # Create a unique ID for each node. # TODO: A fixed unique ID is required for each node, node some random is created, need to think of it. id = hashlib.sha512() t = self.host + str(self.port) + str(random.randint(1, 99999999)) id.update(t.encode('ascii')) self.id = id.hexdigest() """ from wallet.wallet import Wallet_Import self.id = Wallet_Import(0, 0) # Start the TCP/IP server self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.init_server() # Message counters to make sure everyone is able to track the total messages self.message_count_send = 0 self.message_count_recv = 0 self.message_count_rerr = 0 # Debugging on or off! self.debug = False
def callback_for_menu_items(self, *args): if not args[0] == the_settings()["wallet"]: change_wallet(int(args[0])) self.reflesh_balance() Clipboard.copy(Wallet_Import(int(args[0]), 3)) SweetAlert().fire( "The address has been copied to your clipboard.", type='success', )
def ndid(): """ Returns the our node id. """ return "".join([ l.strip() for l in Wallet_Import(0, 0).splitlines() if l and not l.startswith("-----") ])
def create_ledger(): if the_settings().test_mode(): dprint("Creating new ledger") system = ledger(Wallet_Import(0, 0)) from node.myownp2pn import MyOwnPeer2PeerNode MyOwnPeer2PeerNode.main_node.send_full_chain() else: dprint("Getting ledger from nodes") get_ledger()
def delete_the_wallet(self, widget): saved_wallets = get_saved_wallet() selected_wallet_pubkey = Wallet_Import(int(the_settings()["wallet"]), 0) for each_wallet in saved_wallets: if selected_wallet_pubkey == saved_wallets[each_wallet][ "publickey"]: change_wallet(0) Wallet_Delete(each_wallet) self.reflesh_balance() self.dismiss_delete_wallet_alert_dialog(widget)
def send_my_response_on_transaction(self, temp_transaction, response, transaction_sender): items = { "transactionresponse": 1, "fromUser": mynode.main_node.id, "response": response, "transaction_signature": temp_transaction.signature, "signature": Ecdsa.sign( response+str(temp_transaction.signature), PrivateKey.fromPem(Wallet_Import(0, 1)) ).toBase64() } mynode.main_node.send_data_to_node(transaction_sender, items)
def send_the_coin(receiver, temp_coin_amount, password): try: temp_coin_amount = float(temp_coin_amount) except ValueError: print("This is not float coin amount.") return False if not temp_coin_amount < GetBlock().minumum_transfer_amount: if Wallet_Import(int(the_settings()["wallet"]), 2) == sha256(password.encode("utf-8")).hexdigest(): send_coin(float(temp_coin_amount), receiver, password) else: print("Password is not correct")
def send_full_blockshash(self, node=None): dprint("Sending full chain to node or nodes." + " Node: " + str(node)) file = open(TEMP_BLOCKSHASH_PATH, "rb") SendData = file.read(1024) while SendData: data = { "fullblockshash": 1, "byte": (SendData.decode(encoding='iso-8859-1')), "signature": Ecdsa.sign( "fullblockshash" + str( (SendData.decode(encoding='iso-8859-1'))), PrivateKey.fromPem(Wallet_Import(0, 1))).toBase64() } if not node is None: self.send_data_to_node(node, data) else: self.send_data_to_nodes(data) SendData = file.read(1024) dprint(SendData) if not SendData: data = { "fullblockshash": 1, "byte": "end", "signature": Ecdsa.sign("fullblockshash" + "end", PrivateKey.fromPem(Wallet_Import( 0, 1))).toBase64() } if not node is None: self.send_data_to_node(node, data) else: self.send_data_to_nodes(data)
def saveBlockstoBlockchainDB(block): """ Adds the block to the blockchain database at BLOCKS_PATH. """ our_tx = False my_public_key = "".join([ l.strip() for l in Wallet_Import(-1, 0).splitlines() if l and not l.startswith("-----") ]) my_address = Wallet_Import(-1, 3) for validated_transaction in block.validating_list: if validated_transaction.fromUser == my_public_key or validated_transaction.toUser == my_address: our_tx = True # If the block is our transaction, then add it to the blockchain database. if our_tx: # with open(BLOCKS_PATH + str(block.sequance_number) + ".block", "wb") as block_file: pickle.dump(block, block_file, protocol=2) with open(BLOCKS_PATH + str(block.sequance_number) + ".accounts", "wb") as block_file: pickle.dump(GetAccounts(), block_file, protocol=2) with open(BLOCKS_PATH + str(block.sequance_number) + ".accountspart", "wb") as block_file: pickle.dump(GetAccounts_part(), block_file, protocol=2) with open(BLOCKS_PATH + str(block.sequance_number) + ".blockshash", "wb") as block_file: pickle.dump(GetBlockshash(), block_file, protocol=2) with open(BLOCKS_PATH + str(block.sequance_number) + ".blockshashpart", "wb") as block_file: pickle.dump(GetBlockshash_part(), block_file, protocol=2)
def get_transaction(self, data, node): from ledger.ledger_main import get_ledger dprint("Getting the transactions") system = get_ledger() system.createTrans(sequance_number=data["sequance_number"], signature=data["signature"], fromUser=data["fromUser"], toUser=data["to_user"], data=data["data"], amount=data["amount"], transaction_fee=data["transaction_fee"], transaction_sender=node, response=data["response"]) system.Verificate_Pending_Trans(Wallet_Import(0, 0))
def delete_current_wallet(): """ Deletes the current wallet. """ if not the_settings()["wallet"] == 0: saved_wallets = get_saved_wallet() selected_wallet_pubkey = Wallet_Import(int(the_settings()["wallet"]), 0) for each_wallet in saved_wallets: if selected_wallet_pubkey == saved_wallets[each_wallet]["publickey"]: change_wallet(0) Wallet_Delete(each_wallet) else: print("First wallet cannot be deleted.")
def create_ledger(): if the_settings()["test_mode"]: dprint("Creating new ledger") pubkey = "".join([ l.strip() for l in Wallet_Import(0, 0).splitlines() if l and not l.startswith("-----") ]) system = ledger(pubkey) from node.myownp2pn import MyOwnPeer2PeerNode MyOwnPeer2PeerNode.main_node.send_full_chain() else: dprint("Getting ledger from nodes") get_ledger()
def send_my_block(self, nodes): system = GetBlock() new_list = [] signature_list = [] for element in system.validating_list: new_list.append(element.dump_json()) signature_list.append(element.signature) dprint("signature_list: " + str(signature_list)) dprint("publickey from pem: " + str(Wallet_Import(0, 1))) Merkle_signature_list = MerkleTree( signature_list).getRootHash() if len(signature_list) != 0 else "0" dprint("\nmerkleroot: " + Merkle_signature_list) data = { "action": "myblock", "transaction": new_list, "sequance_number": system.sequance_number, "signature": Ecdsa.sign( "myblock" + Merkle_signature_list + str(system.sequance_number), PrivateKey.fromPem(Wallet_Import(0, 1))).toBase64() } for each_node in nodes: dprint("Raund 1: second ok of get candidate block: " + str(each_node.__dict__)) self.send_data_to_node(each_node, data)
def CreateBlock(): """ If test mode is on, creates genesis block and send the connected nodes, if it is off, it calls get_block() function. """ if the_settings()["test_mode"]: dprint("Creating the genesis block") Block(0, Wallet_Import(0, 3)) mynode.main_node.send_full_accounts() mynode.main_node.send_full_chain() else: dprint("Getting block from nodes") GetBlock()
def test_saving_and_importing_the_wallet(self): temp_private_key_class = Wallet_Create() temp_private_key = temp_private_key_class.toPem().replace('\n', '') saved_wallets = get_saved_wallet() result = False for each_wallet in saved_wallets: if temp_private_key == (each_wallet[1]).replace('\n', ''): if temp_private_key == (Wallet_Import((saved_wallets.index(each_wallet)),1)).replace('\n', ''): result = True Wallet_Delete(each_wallet) break result = True if "PRIVATE" in temp_private_key else False self.assertEqual(result, True, "A problem on the saving and importing the wallet.")
def send_my_response_on_transaction(self, temp_transaction, response, transaction_sender): from node.myownp2pn import MyOwnPeer2PeerNode MyOwnPeer2PeerNode.main_node.send_to_node( transaction_sender, { "transactionresponse": 1, "fromUser": MyOwnPeer2PeerNode.main_node.id, "response": response, "transaction_signature": temp_transaction.signature, "signature": Ecdsa.sign(response + str(temp_transaction.signature), PrivateKey.fromPem(Wallet_Import(0, 1))).toBase64() })
def test_saving_and_importing_and_deleting_the_wallet(self): temp_private_key_class = Wallet_Create() temp_private_key = temp_private_key_class.toPem() saved_wallets = get_saved_wallet() result = False for each_wallet in saved_wallets: if temp_private_key == (saved_wallets[each_wallet]["privatekey"]): if temp_private_key == (Wallet_Import( each_wallet, 1)) and "PRIVATE" in temp_private_key: Wallet_Delete(each_wallet) result = True if each_wallet not in get_saved_wallet( ) else False break self.assertEqual(result, True, "A problem on the saving and importing the wallet.")
def sent_the_coins(self, widget): text_list = self.get_send_coin_dialog_text() receiver_adress = text_list[2] amount = text_list[1] if not float(amount) < GetBlock().minumum_transfer_amount: if Wallet_Import(int(the_settings()["wallet"]), 2) == sha256( text_list[0].encode("utf-8")).hexdigest(): send_coin(float(amount), receiver_adress, text_list[0]) else: SweetAlert().fire( "Password is not correct", type='failure', ) del text_list self.send_coin_dialog.dismiss()
def messaging_app_main_tx(tx): tx_pubkey = tx.toUser tx_pubkey_fromUser = tx.fromUser my_pubkey = "".join([ l.strip() for l in Wallet_Import(0, 0).splitlines() if l and not l.startswith("-----") ]) print("\n") print("\n\n" + tx_pubkey) print(my_pubkey + "\n\n") print(tx_pubkey == my_pubkey or tx_pubkey in my_pubkey or my_pubkey in tx_pubkey) print(tx.__dict__) print(tx.data) print(type(tx.data)) print("\n") control = False to_User = False from_User = False if tx_pubkey == my_pubkey or tx_pubkey in my_pubkey or my_pubkey in tx_pubkey: control = True to_User = True elif tx_pubkey_fromUser == my_pubkey or tx_pubkey_fromUser in my_pubkey or my_pubkey in tx_pubkey_fromUser: control = True from_User = True if control: if tx.data != None: print("\n not none \n") if "app" in tx.data: print("\n app in data \n") if tx.data["app"] == "messagingapp": print("""\n tx.data["app"] == "messagingapp" \n""") if tx.data["command"] == "addnewuser" and to_User: print("""\n tx.data["command"] == "addnewuser" \n""") from apps.Messaging_App.func.create_new_user import create_new_user create_new_user("unknow", tx.fromUser, tx.data["n"], tx.data["e"]) elif tx.data["command"] == "newmessage" and to_User: from apps.Messaging_App.func.decrypt import decrypt_text decrypt_text(tx.data["message"], tx_pubkey_fromUser)
def show_example_list_bottom_sheet(self): bottom_sheet_menu = MDListBottomSheet(radius=25, radius_from="top") data = {} all_wallets = list(get_saved_wallet()) current_wallet = the_settings()["wallet"] for wallet in all_wallets: number = all_wallets.index(wallet) address = Wallet_Import(all_wallets.index(wallet), 3) if not current_wallet == number: data[number] = address else: data[number] = address + " - CURRENTLY USED" for item in data.items(): bottom_sheet_menu.add_item( str(item[0]) + " : " + item[1], lambda x, y=item[0]: self.callback_for_menu_items(y), ) bottom_sheet_menu.open()
def print_wallets(): """ Prints the wallets. """ all_wallets = list(get_saved_wallet()) current_wallet = the_settings()["wallet"] print("\nWallets:") result = [] for wallet in all_wallets: number = all_wallets.index(wallet) address = Wallet_Import(all_wallets.index(wallet), 3) if not current_wallet == number: text = menu_maker(menu_number=number, menu_text=address) print(text) result.append(text) else: text = menu_maker(menu_number=number, menu_text=address + " - CURRENTLY USED") print(text) result.append(text) return result
def send_my_block_hash(self, nodes): system = GetBlock() if system.raund_1 and not system.raund_2: data = { "action": "myblockhash", "hash": system.hash, "sequance_number": system.sequance_number, "signature": Ecdsa.sign( "myblockhash" + system.hash + str(system.sequance_number), PrivateKey.fromPem(Wallet_Import(0, 1))).toBase64() } for each_node in nodes: dprint("Raund 2: second ok of get candidate block hashes: " + str(each_node.__dict__)) self.send_data_to_node(each_node, data)