def listen_for_input(self):
        waiting_for_input = True

        while waiting_for_input:
            print()
            print('Please choose'.upper())
            print('-' * 25)
            print('1. Add transaction')
            print('2. Mine block')
            print('3. Output blockchain')
            print('4. Check transaction validity')
            print('5. Create wallet')
            print('6. Load wallet')
            print('7. Save wallet')
            print('0. Exit')
            print('-' * 25)
            user_choice = self.get_user_choice()

            if user_choice == '1':
                tx_data = self.get_transaction_value()
                recipient, amount = tx_data
                signature = self.wallet.sign_transaction(
                    self.wallet.public_key, recipient, amount)

                if self.blockchain.add_transaction(recipient,
                                                   self.wallet.public_key,
                                                   signature, amount):
                    print('Added transaction')
                else:
                    print('Transaction failed')
                print(self.blockchain.get_open_transactions())
            elif user_choice == '2':
                if not self.blockchain.mine_block():
                    print('Mining failed. Got no wallet?')
            elif user_choice == '3':
                self.print_blockchain()
            elif user_choice == '4':
                Verification.verify_transactions(
                    self.blockchain.get_open_transactions(),
                    self.blockchain.get_balance)
            elif user_choice == '5':
                self.wallet.create_keys()
                self.blockchain = Blockchain(self.wallet.public_key)
            elif user_choice == '6':
                self.wallet.load_keys()
                self.blockchain = Blockchain(self.wallet.public_key)
            elif user_choice == '7':
                self.wallet.save_keys()
            elif user_choice == '0':
                waiting_for_input = False
            else:
                print('Invalid choice')
            if not Verification.verify_chain(self.blockchain.chain):
                print('Invalid chain')
                break
            print('The balance of {} is {:6.2f}'.format(
                self.wallet.public_key, self.blockchain.get_balance()))

        else:
            print('Goodbye')
Example #2
0
    def listen_for_input(self):
        # ----------------------------------------------------
        # variable to finish the while loop
        waiting_for_input = True

        # while loop
        while waiting_for_input:
            print('Please choose: ')
            print('1: Add a new transaction value')
            print('2: Output the blockchain blocks')
            print('3: Mine a new block')
            print('4: Check transaction validity')
            print('5: Create new wallet')
            print('6: Load Wallet')
            print('7: Save wallet keys')
            print('q: Finish the transactions')
            user_choice = self.get_user_choice()
            if user_choice == '1':
                tx_data = self.get_transaction_value()
                recipient, amount = tx_data
                signature = self.wallet.sign_transaction(
                    self.wallet.public_key, recipient, amount)
                if self.blockchain.add_transaction(recipient,
                                                   self.wallet.public_key,
                                                   signature,
                                                   amount=amount):
                    print('Added transaction!')
                else:
                    print('Transaction failed!')
                print(self.blockchain.get_open_transactions())
            elif user_choice == '2':
                self.print_blockchain_blocks()
            elif user_choice == '3':
                if not self.blockchain.mine_block():
                    print('Mining failed!')
            elif user_choice == '4':
                if Verification.verify_transactions(
                        self.blockchain.get_open_transactions(),
                        self.blockchain.get_balance):
                    print('All transactions are valid!')
                else:
                    print('There are invalid transactions')
            elif user_choice == '5':
                self.wallet.create_keys()
                self.blockchain = Blockchain(self.wallet.public_key)
            elif user_choice == '6':
                self.wallet.load_keys()
                self.blockchain = Blockchain(self.wallet.public_key)
            elif user_choice == '7':
                self.wallet.save_keys()
            elif user_choice == 'q':
                waiting_for_input = False
            else:
                print('Input was invalid!!')
            if not Verification.verify_chain(self.blockchain.get_blockchain()):
                self.print_blockchain_blocks()
                print('The blockchain was modified, Invalid!')
                break
            print('Balance of {}:{:6.2f}'.format(
                self.wallet.public_key, self.blockchain.get_balance()))
Example #3
0
    def listen_to_input(self):
        waiting_for_input = True

        while waiting_for_input:
            print('Please chose')
            print('1: Add new transaction value')
            print('2: Mine a new block')
            print('3: Output the blockchain blocks')
            print('4: Check transaction validity')
            print('5: Create new wallet')
            print('6: Load wallet')
            print('7: Save keys')
            print('q: Quit')

            user_choice = self.get_user_choice()

            if user_choice == '1':
                tx_data = self.get_transaction_value()
                recipient, amount = tx_data
                signature = self.wallet.sign_transaction(self.wallet.public_key, recipient, amount)
                if self.blockchain.add_transaction(recipient, self.wallet.public_key, signature, amount=amount):
                    print('Added transaction!')
                else:
                    print('Transaction failed!')
                print(self.blockchain.get_open_transactions())
            elif user_choice == '2':
                if not self.blockchain.mine_block():
                    print('Mining failed. Got no wallet?')
            elif user_choice == '3':
                self.print_blockchain_elements()
            elif user_choice == '4':
                open_transactions = self.blockchain.get_open_transactions()
                if Verification.verify_transactions(open_transactions, self.blockchain.get_balance):
                    print('All transaction is valid!')
                else:
                    print('There are invalid transactions')
            elif user_choice == '5':
                self.wallet.create_keys()
                self.blockchain = Blockchain(self.wallet.public_key)
            elif user_choice == '6':
                self.wallet.load_keys()
                self.blockchain = Blockchain(self.wallet.public_key)
            elif user_choice == '7':
                self.wallet.save_keys()
            elif user_choice == 'q':
                waiting_for_input = False
            else:
                print('Input was invalid, please pick a value from the list!')
            if not Verification.verify_chain(self.blockchain.chain):
                self.print_blockchain_elements()
                print('Invalid blockchain!')
                break
            print(30 * '-')
            print('Balance of {}:{:6.2f} coins'.format(self.wallet.public_key, self.blockchain.get_balance()))
        else:
            print('User left!')
Example #4
0
 def prompt_for_input(self):
     while True:
         print("Please choose")
         print("1: Add a new transaction value")
         print("2: Mine a block")
         print("3: Print blocks")
         print("4: Check validity of all transactions")
         print("5: Create wallet, make sure to save too")
         print("6: Load wallet")
         print("7: Save wallet")
         print("q: Quit")
         user_choice = self.get_user_choice()
         if user_choice == "1":
             tx_data = self.get_transaction_value()
             recipient, amount = tx_data
             signature = self.wallet.sign_transaction(
                 self.wallet.public_key, recipient, amount)
             if self.blockchain.add_transaction(recipient,
                                                self.wallet.public_key,
                                                signature,
                                                amount=amount):
                 print("Added transaction")
             else:
                 print("Transaction failed")
         elif user_choice == "2":
             if not self.blockchain.mine_block():
                 print("No wallet found, mining failed")
         elif user_choice == "3":
             self.print_blockchain_elements()
         elif user_choice == "4":
             if Verification.verify_transactions(
                     self.blockchain.get_open_transactions(),
                     self.blockchain.get_balance):
                 print("All transactions are valid")
             else:
                 print("There are invalid transactions")
         elif user_choice == "5":
             self.wallet.create_keys()
             self.blockchain = Blockchain(self.wallet.public_key)
         elif user_choice == "6":
             self.wallet.load_keys()
             self.blockchain = Blockchain(self.wallet.public_key)
         elif user_choice == "7":
             self.wallet.save_keys()
         elif user_choice == "q":
             break
         else:
             print("Input was invalid, please pick a value from the list!")
         if not Verification.verify_chain(self.blockchain.chain):
             print("Invalid blockchain!")
             break
         print("Balance of {}: {:*^10.2f}".format(
             self.wallet.public_key, self.blockchain.get_balance()))
     print("Done!")
Example #5
0
    def listen_for_input(self):
        waiting_for_input = True

        while waiting_for_input:
            print('Please choose an option: ')
            print('1: Add a new transaction value')
            print('2: Mine a new block')
            print('3: Output the blockchain blocks')
            print('4: Check transactions validity')
            print('5: Create a new wallet')
            print('6: Load a wallet')
            print('7: Save a wallet (keys)')
            print('9: Quit')
            user_choice = self.get_user_choice()
            if user_choice == '1':
                tx_data = self.get_transaction_value()
                recipient, amount = tx_data
                signature = self.wallet.sign_transaction(self.wallet.public_key, recipient, amount)
                if self.blockchain.add_transaction(recipient, amount, self.wallet.public_key, signature):
                    print('Transaction has been added successfully!')
                else:
                    print('The transaction has failed!')
                print(self.blockchain.get_open_transactions())
            elif user_choice == '2':
                if not self.blockchain.mine_block():
                    print('The mining failed. Check if you already have a wallet!')
            elif user_choice == '3':
                self.print_blockchain_elements()
            elif user_choice == '4':
                if Verification.verify_transactions(self.blockchain.get_open_transactions(),
                                                    self.blockchain.get_balance):
                    print('All transactions are valid!')
                else:
                    print('There are invalid transactions!')
            elif user_choice == '5':
                self.wallet.create_keys()
                self.blockchain = Blockchain(self.wallet.public_key)
            elif user_choice == '6':
                self.wallet.load_keys()
                self.blockchain = Blockchain(self.wallet.public_key)
            elif user_choice == '7':
                self.wallet.save_keys()
            elif user_choice == '9':
                waiting_for_input = False
            else:
                print('Input was invalid, please, choose a value from the list!')

            # After each action, we verify if the chain was not manipulated.
            if not Verification.verify_chain(self.blockchain.get_chain()):
                print('Invalid blockchain!')
                waiting_for_input = False
            print('Balance of {}: {:6.2f}'.format(self.wallet.public_key, self.blockchain.get_balance()))
        print('Done!')
Example #6
0
    def add_transaction(self,
                        recipient,
                        sender,
                        signature,
                        amount=1.0,
                        is_receiving=False):
        # if self.public_key == None:
        #     return False

        transaction = Transaction(sender, recipient, signature, amount)

        if Verification.verify_tx(transaction, self.get_balance):
            self.__open_transactions.append(transaction)
            self.save_data()
            if not is_receiving:
                for node in self.__peer_nodes:
                    url = 'http://{}/broadcast'.format(node)
                    try:
                        response = requests.post(url,
                                                 json={
                                                     "sender": sender,
                                                     "recipient": recipient,
                                                     "amount": amount,
                                                     "signature": signature
                                                 })
                        if response.status_code == 400 or response.status_code == 500:
                            print("Couldn't add TX to peer_nodes")
                            return False
                    except requests.exceptions.ConnectionError:
                        continue
            return True
        return False
 def add_block(self, block):
     # Create a list of transaction objects with the content in the dictionary key of the block 'transaction'
     transactions = [
         Transaction(tx['sender'], tx['recipient'], tx['signature'],
                     tx['amount']) for tx in block['transactions']
     ]
     # call the valid_proof without the last transaction because is the MINING reward transaction
     proof_is_valid = Verification.valid_proof(transactions[:-1],
                                               block['previous_hash'],
                                               block['proof'])
     hashes_match = create_hash_block(
         self.get_blockchain()[-1]) == block['previous_hash']
     if not proof_is_valid or not hashes_match:
         return False
     converted_block = Block(block['index'], block['previous_hash'],
                             transactions, block['proof'],
                             block['timestamp'])
     self.__blockchain.append(converted_block)
     stored_transactions = self.__open_transactions[:]
     # show if the incoming transactions are part of the open transactions and remove it if it´s the case
     for itx in block['transactions']:
         for opentx in stored_transactions:
             if opentx.sender == itx['sender'] and opentx.recipient == itx[
                     'recipient'] and opentx.amount == itx[
                         'amount'] and opentx.signature == itx['signature']:
                 try:
                     self.__open_transactions.remove(opentx)
                 except ValueError:
                     print('Item was already removed')
     self.save_data()
     return True
    def add_transaction(self,
                        recipient: str,
                        sender: str,
                        signature: str,
                        amount: float = 1.0,
                        is_receiving=False) -> bool:
        if self.public_key is None:
            return False

        transaction = Transaction(sender, recipient, signature, amount)

        if Verification.verify_transaction(transaction, self.get_balance):
            self.__open_transactions.append(transaction)
            self.save_data()
            if not is_receiving:
                for node in self.__peer_nodes:
                    url = 'http://{}/broadcast-transaction'.format(node)
                    try:
                        response = requests.post(url,
                                                 json={
                                                     'sender': sender,
                                                     'recipient': recipient,
                                                     'amount': amount,
                                                     'signature': signature
                                                 })
                        if response.status_code == 400 or response.status_code == 500:
                            print('Transaction declined, needs resolving')
                            return False
                    except requests.exceptions.ConnectionError:
                        continue
            return True
        return False
 def add_transaction(self,
                     recipient,
                     sender,
                     signature,
                     amount=1.0,
                     is_receiving=False):
     # if self.public_key == None:
     #     return False
     # Create transaction class object
     transaction = Transaction(sender, recipient, signature, amount)
     if Verification.verify_transaction(transaction, self.get_balance):
         self.__open_transactions.append(transaction)
         self.save_data()
         # send to all nodes the transaction added if there is not the direct receiving node
         if not is_receiving:
             for node in self.__peer_nodes:
                 url = 'http://{}/broadcast-transaction'.format(node)
                 try:
                     response = requests.post(url,
                                              json={
                                                  'sender': sender,
                                                  'recipient': recipient,
                                                  'amount': amount,
                                                  'signature': signature
                                              })
                     if response.status_code == 400 or response.status_code == 500:
                         print('Transaction declined, needs resolving')
                         return False
                 except requests.exceptions.ConnectionError:
                     continue
         return True
     return False
    def add_value(self, signature, sender, recipient, amount=1.0):
        """ appends a new value to the open transaction list.
        Arguments:
        :sender: The sender of the transaction.
        :recipient: Receiver of the transaction.
        :amount: The amount of the transaction.
        """
        # transaction = {
        #     "sender": sender,
        #     "recipient": recipient,
        #     "amount": amount
        # }
        if self.hosting_node == None:
            return False
        transaction = Transaction(signature, sender, recipient, amount)

        if not Wallet.verify_signature(transaction):
            return False

        if Verification.verify_transaction(transaction, self.get_balance):
            self.__open_transactions.append(transaction)
            self.save_data()
            return True

        print("insufficient funds")
        return False
 def resolve(self):
     winner_chain = self.chain
     replace = False
     # check which peer_nodes have which blockchain (peer_nodes storage in the blockchain.txt)
     for node in self.__peer_nodes:
         url = 'http://{}/chain'.format(node)
         try:
             response = requests.get(url)
             # extract json like a dictionary
             node_chain = response.json()
             # transform the chain into a list of block objects and the transactions inside into a list of transaction objects
             node_chain = [
                 Block(block['index'], block['previous_hash'], [
                     Transaction(tx['sender'], tx['recipient'],
                                 tx['signature'], tx['amount'])
                     for tx in block['transactions']
                 ], block['proof'], block['timestamp'])
                 for block in node_chain
             ]
             # compare local blockchain with the blockchain of each peer_node storaged
             node_chain_length = len(node_chain)
             local_chain_length = len(winner_chain)
             if node_chain_length > local_chain_length and Verification.verify_chain(
                     node_chain):
                 winner_chain = node_chain
                 replace = True
         # except can occurs when a peer_node is not connected
         except requests.exceptions.ConnectionError:
             continue
     self.resolve_conflicts = False
     self.chain = winner_chain
     if replace:
         self.__open_transactions = []
     self.save_data()
     return replace
 def add_block(self, block):
     transactions = [
         Transaction(tx['sender'], tx['recipient'], tx['signature'],
                     tx['amount']) for tx in block['transactions']
     ]
     proof_is_valid = Verification.valid_proof(transactions[:-1],
                                               block['previous_hash'],
                                               block['proof'])
     hashes_match = hash_block(self.chain[-1]) == block['previous_hash']
     if not proof_is_valid or not hashes_match:
         return False
     converted_block = Block(block['index'], block['previous_hash'],
                             transactions, block['proof'],
                             block['timestamp'])
     self.__chain.append(converted_block)
     stored_transactions = self.__open_transactions[:]
     for itx in block['transactions']:
         for opentx in stored_transactions:
             if opentx.sender == itx['sender'] and opentx.recipient == itx[
                     'recipient'] and opentx.amount == itx[
                         'amount'] and opentx.signature == itx['signature']:
                 try:
                     self.__open_transactions.remove(opentx)
                 except ValueError:
                     print('Item was already removed')
     self.save_data()
     return True
Example #13
0
 def add_block(self, block):
     """
     Add an already created Block when broadcasting Blocks from different peers.
     :param block: the Block that will be added.
     :return: if the addition was successfully.
     """
     transactions = [
         Transaction(
             transaction['sender'],
             transaction['recipient'],
             transaction['amount'],
             transaction['signature']) for transaction in block['transactions']
     ]
     proof_is_valid = Verification.valid_proof(transactions[:-1], block['previous_hash'], block['proof'])
     hashes_match = hash_util.hash_block(self.get_chain()[-1]) == block['previous_hash']
     if not proof_is_valid or not hashes_match:
         return False
     converted_block = Block(block['index'], block['previous_hash'], transactions, block['proof'],
                             block['timestamp'])
     self.__chain.append(converted_block)
     stored_transactions = self.__open_transactions[:]
     for incoming_transaction in block['transactions']:
         for open_transaction in stored_transactions:
             if open_transaction.sender == incoming_transaction['sender'] \
                     and open_transaction.recipient == incoming_transaction['recipient'] \
                     and open_transaction.amount == incoming_transaction['amount'] \
                     and open_transaction.signature == incoming_transaction['signature']:
                 try:
                     self.__open_transactions.remove(open_transaction)
                 except ValueError:
                     print('The transaction was already removed!')
     self.save_data()
     return True
 def resolve(self):
     winner_chain = self.chain
     replace = False
     for node in self.__peer_nodes:
         url = 'http://{}/chain'.format(node)
         try:
             response = requests.get(url)
             node_chain = response.json()
             node_chain = [
                 Block(block['index'], block['previous_hash'], [
                     Transaction(tx['sender'], tx['recipient'],
                                 tx['signature'], tx['amount'])
                     for tx in block['transactions']
                 ], block['proof'], block['timestamp'])
                 for block in node_chain
             ]
             node_chain_length = len(node_chain)
             local_chain_length = len(winner_chain)
             if node_chain_length > local_chain_length and Verification.verify_chain(
                     node_chain):
                 winner_chain = node_chain
                 replace = True
         except requests.exceptions.ConnectionError:
             continue
     self.resolve_conflicts = False
     self.chain = winner_chain
     if replace:
         self.__open_transactions = []
     self.save_data()
     return replace
Example #15
0
    def add_transaction(self, recipient, amount=1.0, sender=None, signature='', is_receiving=False):
        """ Appends a new value as well as the last blockchain to the blockchain.
            :argument sender The sender of the coins.
            :argument recipient The recipient of the coins.
            :argument amount The amount of coins (default[1])
        """
        if self.hosting_node is None:
            return False

        transaction = Transaction(sender, recipient, amount, signature)

        if not Wallet.verify_transaction(transaction):
            return False

        if Verification.verify_transaction(transaction, self.get_balance):
            self.__open_transactions.append(transaction)
            self.save_data()
            if not is_receiving:
                for node in self.__peer_nodes:
                    url = 'http://{}/broadcast'.format(node)
                    try:
                        response = requests.post(url, json={'sender': sender, 'recipient': recipient, 'amount': amount,
                                                            'signature': signature})
                        if response.status_code == 400 or response.status_code == 500:
                            print('Transaction declined!')
                            return False
                    except requests.exceptions.ConnectionError:
                        continue
            return True
        return False
Example #16
0
 def generate_proof_of_work(self):
     last_block = self.__chain[-1]
     last_hash = hash_util.hash_block(last_block)
     proof = 0
     while not Verification.validate_proof(self.__open_transactions,
                                           last_hash, proof):
         proof += 1
     return proof
    def proof_of_work(self) -> int:
        last_hash = hash_block(self.__chain[-1])
        proof = 0
        print('Proof of work...')
        while not Verification.valid_proof(self.__open_transactions, last_hash,
                                           proof):
            proof += 1

        return proof
 def proof_of_work(self):
     # get the first list element from the right
     last_block = self.__blockchain[-1]
     last_hash = create_hash_block(last_block)
     proof = 0
     while not Verification.valid_proof(self.__open_transactions, last_hash,
                                        proof):
         proof += 1
     return proof
Example #19
0
 def add_transaction(self, recipient, sender, signature, amount=1.0):
     if self.public_key is None:
         return False
     transaction = Transaction(sender, recipient, signature, amount)
     if Verification.verify_transaction(transaction, self.get_balance):
         self.__open_transactions.append(transaction)
         self.save_data()
         return True
     return False
 def proof_of_work(self):
     """Generate a proof of work for the open transactions, the hash of the previous block and a random number (which is guessed until it fits)."""
     last_block = self.__chain[-1]
     last_hash = hash_block(last_block)
     proof = 0
     # Try different PoW numbers and return the first valid one
     while not Verification.valid_proof(self.__open_transactions, last_hash,
                                        proof):
         proof += 1
     return proof
Example #21
0
 def proof_of_work(self):
     """
     Generates a proof of work for the open transactions, based on the last hashed block which is guessed until it fits.
     :return: a valid number for the proof of work.
     """
     last_block = self.__chain[-1]
     last_hash = hash_util.hash_block(last_block)
     proof = 0
     while not Verification.valid_proof(self.__open_transactions, last_hash, proof):
         proof += 1
     return proof
Example #22
0
    def proof_of_work(self):
        """ Calculates proof of work for mining a new block """

        last_block = self.get_last_blockchain_value()
        last_hash = hash_block(last_block)

        proof = 0
        while not Verification.valid_proof(self.__open_transactions, last_hash,
                                           proof):
            proof += 1

        return proof
    def add_block(self, block):
        transactions = [
            Transaction(tx['sender'], tx['recipient'], tx['signature'],
                        tx['amount']) for tx in block['transactions']
        ]
        proof_is_valid = Verification.valid_proof(transactions[:-1],
                                                  block['previous_hash'],
                                                  block['proof'])
        hashes_match = hash_block(self.chain[-1]) == block['previous_hash']
        if not proof_is_valid or not hashes_match:
            return False

        self.__chain.append(
            Block(block['index'], block['previous_hash'], transactions,
                  block['proof'], block['timestamp']))
        self.save_data()
        return True
Example #24
0
    def proof_of_work(self):
        """
        Function to find the valid proof of work that the proof validation condition

        Returns
        -------
            proof (integer): Proof of work which satisfies condition

        """
        logger.info('Finding proof of work')
        last_block = self.__chain[-1]
        last_hash = hash_block(last_block)
        proof = 0
        while not Verification.valid_proof(self.__open_transactions, last_hash,
                                           proof):
            proof += 1
        return proof
Example #25
0
    def add_transaction(self, recipient, sender, signature, amount=1.0):
        """ Adding value to the blockchain
        
            Arguments:
                :sender: The sender of the coins.
                :recipient: The recipient of the coins.
                :amount: The amount of coins sent. Default 1.0.
        
        """

        transaction = Transaction(sender, recipient, signature, amount)

        if Verification.verify_transaction(transaction, self.get_balance):
            self.__open_transactions.append(transaction)
            self.save_data()

            return True

        return False
    def add_transaction(self,
                        recipient,
                        sender,
                        signature,
                        amount=1.0,
                        is_receiving=False):
        """ Append a new value as well as the last blockchain value to the blockchain.

        Arguments:
            :sender: Tecihe sender of the coins.
            :rpient: The recipient of the coins.
            :amount: The amount of coins sent with the transaction (default = 1.0)
        """
        # transaction = {
        #     'sender': sender,
        #     'recipient': recipient,
        #     'amount': amount
        # }
        # if self.public_key == None:
        #     return False
        transaction = Transaction(sender, recipient, signature, amount)
        if Verification.verify_transaction(transaction, self.get_balance):
            self.__open_transactions.append(transaction)
            self.save_data()
            if not is_receiving:
                for node in self.__peer_nodes:
                    url = 'http://{}/broadcast-transaction'.format(node)
                    try:
                        response = requests.post(url,
                                                 json={
                                                     'sender': sender,
                                                     'recipient': recipient,
                                                     'amount': amount,
                                                     'signature': signature
                                                 })
                        if response.status_code == 400 or response.status_code == 500:
                            print('Transaction declined, needs resolving')
                            return False
                    except requests.exceptions.ConnectionError:
                        continue
            return True
        return False
Example #27
0
 def listen_for_input(self):
     while self.add_new:
         user_answer = self.get_user_choice()
         if user_answer == "1":
             if self.wallet.public_key == None:
                 print(
                     "transaction cancelled, please log in or create account"
                 )
                 continue
             new_transaction = self.get_transaction()
             recipient, amount = new_transaction
             signature = self.wallet.sign_transaction(
                 self.wallet.public_key, recipient, amount)
             if self.blockchain.add_value(signature, self.wallet.public_key,
                                          recipient, amount):
                 print("success!!")
             else:
                 print("transaction cancelled")
         elif user_answer == "2":
             if not self.blockchain.mine_block():
                 print("no wallet found")
         elif user_answer == "3":
             self.add_new = False
         elif user_answer == "4":
             if self.wallet.public_key == None:
                 print("please login or create a new account")
                 continue
             print("balance for {} : {:6.2f}".format(
                 self.wallet.public_key, self.blockchain.get_balance()))
         elif user_answer == "5":
             self.blockchain.print_blockchain()
         elif user_answer == "6":
             self.wallet.create_keys()
             self.blockchain = Blockchain(self.wallet.public_key)
         elif user_answer == "7":
             self.wallet.load_keys()
             self.blockchain = Blockchain(self.wallet.public_key)
         else:
             print("answer invalid")
         if not Verification.verify_chain(self.blockchain.chain):
             print("hack detected")
             break
Example #28
0
    def add_transaction(self, recipient, sender, signature, amount=1.0):
        """
        Adds a new transaction (if valid) to the list of open transactions.

        Parameters
        ----------
            sender (String): The sender of the coins
            recipient (String): The recipient of the coins
            amount (float): The amount of coins sent in the transaction
                            (default = 1.0)
        """
        if self.hosting_node is None:
            return False

        transaction = Transaction(sender, recipient, signature, amount)

        if Verification.verify_transaction(transaction, self.get_balances):
            logger.info(
                'Valid transaction. Adding to list of open transactions.')
            self.__open_transactions.append(transaction)
            self.save_data()
            return True
        return False
    def listen_for_input(self):
        while True:
            print('==================================')
            print('Please choose')
            print('0: Create wallet')
            print('1: Load wallet')
            print('2: Save wallet')
            print('3: Add a new transaction')
            print('4: Mine new block')
            print('5: Show blockchain')
            print('6: Show balance')
            print('7: Show open transactions')
            print('8: Check transaction validity')
            print('q: Quit')
            print('==================================')
            user_choice = self.get_user_choice()
            if user_choice == '0':  # Create wallet
                self.wallet.create_keys()
                self.blockchain = Blockchain(self.wallet.public_key)

            elif user_choice == '1':  # Load wallet
                self.wallet.load_keys()
                self.blockchain = Blockchain(self.wallet.public_key)

            elif user_choice == '2':  # Save wallet
                self.wallet.save_keys()

            elif user_choice == '3':  # Add new open transaction
                tx_data = self.get_transaction_value()  # returns a tuple
                recipient, amount = tx_data
                signature = self.wallet.sign_transaction(
                    self.wallet.public_key, recipient, amount)
                if self.blockchain.add_transaction(recipient,
                                                   self.wallet.public_key,
                                                   signature,
                                                   amount=amount):
                    print('Added transaction!')
                else:
                    print('Transaction failed!')

            elif user_choice == '4':  # Mine new block
                if not self.blockchain.mine_block():
                    print('Mining failed. Wallet wasnot found')

            elif user_choice == '5':  # Show blockchain
                self.print_blockchain_elements()

            elif user_choice == '6':  # Show balance
                (amount_sent, amount_recieved,
                 balance) = self.blockchain.get_balance()
                print(f'{self.wallet.public_key[:5]} sent: {amount_sent:.2f}')
                print(
                    f'{self.wallet.public_key[:5]} recieved: {amount_recieved:.2f}'
                )
                print(
                    f'Balance of {self.wallet.public_key[:5]}: {balance:.2f}')

            elif user_choice == '7':  # Show open transactions
                print(self.blockchain.get_open_transactions())

            elif user_choice == '8':
                if Verification.check_transaction_validity(
                        self.blockchain.get_open_transactions(),
                        self.blockchain.get_balance):
                    print('All transactions are valid')
                else:
                    print('There are invalid transactions!')

            elif user_choice == 'q':
                break

            else:
                print('Input was invalid, please pick a value from the list!')

            if not Verification.verify_chain(self.blockchain.chain):
                print('Invalid blockchain')
                break
        print('Done!')
Example #30
0
    def listen_for_input(self):

        waiting_for_input = True

        while waiting_for_input:
            print('Please Choose')
            print('1: Add a New Transaction Value ')
            print('2: Mine a new Block ')
            print('3: Output the Blockchain Blocks')
            print('4: Check Transaction Validity')
            print('5: Create Wallet')
            print('6: Load Wallet')
            print('7: Save Keys')
            print('q: Quit')

            user_choice = self.get_user_choice()
            if user_choice == '1':
                tx_data = self.get_transaction_value()
                recipient, amount = tx_data

                signature = self.wallet.sign_transaction(
                    self.wallet.public_key, recipient, amount)

                if self.blockchain.add_transaction(recipient,
                                                   self.wallet.public_key,
                                                   signature,
                                                   amount=amount):
                    print('Added Transaction!')
                else:
                    print('Transaction Failed')
                print(self.blockchain.get_open_transactions())
            elif user_choice == '2':
                if not self.blockchain.mine_block():
                    print('Mining Failed, Got No Wallet?')

            elif user_choice == '3':
                self.print_blockchain_elements()
            elif user_choice == '4':
                if Verification.verify_transactions(
                        self.blockchain.get_open_transactions(),
                        self.blockchain.get_balance):
                    print('All Transactions are Valid')
                else:
                    print('There are Invalid Transactions')
            elif user_choice == '5':
                self.wallet.create_keys()
                self.blockchain = Blockchain(self.wallet.public_key)
            elif user_choice == '6':
                self.wallet.load_keys()
                self.blockchain = Blockchain(self.wallet.public_key)
            elif user_choice == '7':
                self.wallet.save_keys()
            elif user_choice == 'q':
                waiting_for_input = False
            else:
                print('Input was Invalid , Please Pick a Value From the List ')

            if not Verification.verify_chain(self.blockchain.chain):
                self.print_blockchain_elements()
                print('Invalid Blockchain !')
                break
            print('Balance of {} : {:6.2f}'.format(
                self.wallet.public_key, self.blockchain.get_balance()))
        else:
            print('User Left !')