Exemplo n.º 1
0
 def listen_for_input(self):
     waiting_for_input = True
     while waiting_for_input:
         choice = self.get_user_choice()
         if 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 choice == '2':
             if not self.blockchain.mine_block():
                 print('Mining failed! Do you have a wallet?')
         elif choice == '3':
             self.print_blockchain()
         elif 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 choice == '5':
             self.wallet.create_keys()
             self.blockchain = Blockchain(self.wallet.public_key)
         elif choice == '6':
             self.wallet.load_keys()
             self.blockchain = Blockchain(self.wallet.public_key)
         elif choice == '7':
             self.wallet.save_keys()
         elif choice == 'q':
             waiting_for_input = False
         else:
             print('Invalid choice! Choose again.')
         if not Verification.verify_chain(self.blockchain.chain):
             self.print_blockchain()
             print('Invalid blockchain!')
             break
         print('Balance of {}: {:6.2f}'.format(
             self.wallet.public_key, self.blockchain.get_balance()))
         print()
     else:
         print('User done!')
Exemplo n.º 2
0
 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
Exemplo n.º 3
0
 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
Exemplo n.º 4
0
 def proof_of_work(self):
     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
Exemplo n.º 5
0
 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
Exemplo n.º 6
0
 def add_transaction(self, recipient, sender, signature, amount=1.0):
     """ Append a new value as well as the last blockchain value to the blockchain.
     Arguments:
         :sender: The sender of the funds.
         :recipient: The recipient of the funds.
         :amount: The amount of funds sent with the transaction (default = 1.0)
     """
     if self.hosting_node == None:
         return False
     transaction = Transaction(sender, recipient, signature, amount)
     if Verification.verify_transaction(transaction, self.get_balance):
         # add new transaction details to open transactions
         self.__open_transactions.append(transaction)
         self.save_data()
         return True
     return False
Exemplo n.º 7
0
    def add_transaction(self,
                        recipient,
                        sender,
                        signature,
                        amount=1.0,
                        is_receiving=False):
        """ Append latest value to previous block and push to open_blockchain

        Arguments:
        sender: sender of coins
        recipient: coin recipient
        amount: count of coins 

        """

        # 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
Exemplo n.º 8
0
    def listen_for_input(self):
        waiting_for_input = True
        # A while loop for the user input interface
        # It's a loop that exits once waiting_for_input becomes False or when break is called
        while waiting_for_input:
            """ Create an infite loop to run the blockchain cli """
            # print the user options
            print("------------------------------------- ")
            print(" ")
            print('Please choose an option?')
            print(" ")
            print('1: Allocate Portfolio Coin Value')
            print('2: Mine new block')
            print('3: Output the blockchain')
            print('4: Check blockchain validity')
            print('5: Create Client wallet')
            print('6: Load Client wallet')
            print('7: Save Client keys')
            print('q: Quit')
            print(" ")
            print("------------------------------------- ")
            print(" ")
            # save user input
            user_choice = self.get_user_choice()
            # Create a conditions to service the user input
            if user_choice == '1':
                tx_data = self.get_transaction_value()
                recipient, amount = tx_data  # I can destructure or unpack a tuple as such
                # create a transaction signature
                tx_signature = self.wallet.sign_transaction(
                    self.wallet.public_key, recipient, amount)
                # Add the transaction amount to the blockchain
                if self.blockchain.add_transaction(
                        recipient,
                        self.wallet.public_key,
                        tx_signature,
                        amount=amount
                ):  # add transactiont to open transactions
                    print('Added transaction!')
                else:
                    print('Transaction failed!')
                print("Open Txn: ", self.blockchain.get_open_transactions())
            elif user_choice == '2':
                try:
                    if not self.blockchain.mine_block():
                        print(" ")
                        print("Mining Failed, You need a Wallet")
                        print(" ")
                except:
                    print(
                        "Mining failed please establish a wallet and public key"
                    )
                    continue
            elif user_choice == '3':  # output existing blocks
                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':
                # This will lead to the loop to exist because it's running condition becomes False
                waiting_for_input = False
            else:
                print('Input was invalid, please pick a value from the list!')
            if not Verification.verify_chain(self.blockchain.get_chain()):
                self.print_blockchain_elements()
                print('Invalid blockchain!')
                # Break out of the loop
                break
            print("-------------------------------------")
            print(" ")
            print("Node Details:")
            print('Account Key: {}, Current Coin Value :{:6.2f}'.format(
                self.wallet.public_key, self.blockchain.get_balance()))
            print(" ")
        else:
            print('Session closed')

        print('Program secure, Logged Out!')
        print(" ")