def resolve(self): """Checks all peer nodes' blockchains and replaces the local one with longer valid ones.""" # Below: winner chain to hold the value of the chain we'd use winner_chain = self.chain # Below: replace varaible to keep track of whether the winner_chain variable changed replace = False for node in self.__peer_nodes: url = f"http://{node}/chain" 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) print(node_chain_length) print(Verification.verify_chain(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_conflict = False self.chain = winner_chain if replace: self.__open_transactions = [] self.save_data() return replace
def listen_for_input(self): while True: user_input = self.get_user_choice() if user_input == '1': tx_data = self.get_transaction_value() #unpacking 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): print('Transaction Added') else: print('Transaction Failed') #print(open_transactions) elif user_input == '2': if not self.blockchain.mine_block(): print('No Wallet. Mining Failed') elif user_input == '3': self.display_blockchain() elif user_input == '4': if Verification.verify_chain(self.blockchain.chain): print('\nThe Blockchain is Valid') else: print('\nThe Blockchain has been compromised') break elif user_input == '5': if Verification.verify_transactions( self.blockchain.get_open_transaction, self.blockchain.get_balances): print('Valid Transactions') else: print('Invalid Transactions') elif user_input == '6': self.wallet.create_keys() self.blockchain = Blockchain(self.wallet.public_key) elif user_input == '7': self.wallet.load_keys() self.blockchain = Blockchain(self.wallet.public_key) elif user_input == '8': self.wallet.save_keys() else: break print('New Balance for {} : {:10.2f}'.format( self.wallet.public_key, self.blockchain.get_balances())) if not Verification.verify_chain(self.blockchain.chain): print('\nThe Blockchain has been compromised') break
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.transactions = [Transaction(tx["sender"], tx["recipient"], tx["signature"], tx["amount"]) for tx in node_chain["transactions"]] node_chain_length = len(node_chain) local_chain_length = len(self.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
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: 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 wallet keys") print("q: Quit") user_choice = self.get_user_choice() if "1" == user_choice: tx_data = self.get_transaction_value() recipient, amount = tx_data # Add the transaction amount to the blockchain 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 "2" == user_choice: if not self.blockchain.mine_block(): print("Mining failed. Got no wallet?") elif "3" == user_choice: self.print_blockchain_elements() elif "4" == user_choice: 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 "5" == user_choice: self.wallet.create_keys() self.blockchain = Blockchain(self.wallet.public_key) elif "6" == user_choice: self.wallet.load_key() self.blockchain = Blockchain(self.wallet.public_key) elif "7" == user_choice: self.wallet.save_keys() elif "q" == user_choice: # 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.chain): self.print_blockchain_elements() print("Invalid blockchain!") # Break out of the loop break print("Balance of '{}': {:6.2f}".format(self.wallet.public_key, self.blockchain.get_balance())) else: print("User left!") print("Done!")
def resolve(self): """Checks all peer nodes' blockchains and replaces the local one with longer valid ones.""" # Initialize the winner chain with the local chain winner_chain = self.chain replace = False for node in self.__peer_nodes: url = 'http://{}/chain'.format(node) try: # Send a request and store the response response = requests.get(url) # Retrieve the JSON data as a dictionary node_chain = response.json() # Convert the dictionary list to a list of block AND 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] node_chain_length = len(node_chain) local_chain_length = len(winner_chain) # Store the received chain as the current winner chain if it's longer AND valid 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 # Replace the local chain with the winner chain self.chain = winner_chain if replace: self.__open_transactions = [] self.save_data() return replace
def resolve(self): winner_chain = self.get_chain() whether_replace_local_chain = False for node in self.__peer_nodes: url = "http://{}/chain".format(node) try: response = requests.get(url) peer_chain = response.json() peer_chain = [Block(block["index"], block["previous_hash"], block["transactions"], block["proof"], block["time_stamp"]) for block in peer_chain] for elem in peer_chain: elem.transactions = [Transaction(tx["sender"], tx["recipient"], tx["signature"], tx["amount"]) for tx in elem.transactions] peer_chain_length = len(peer_chain) local_chain_length = len(winner_chain) whether_peer_chain_longer = peer_chain_length > local_chain_length whether_peer_chain_valid = Verification.verify_chain(peer_chain) if whether_peer_chain_longer and whether_peer_chain_valid: winner_chain = peer_chain[:] whether_replace_local_chain = True except requests.exceptions.ConnectionError: print("Connection failed with node : %s"%node) continue self.resolve_conflicts = False self.__chain = winner_chain if whether_replace_local_chain: self.__open_transactions = [] self.save_data() return whether_replace_local_chain
def listen_for_input(self): """Starts the node and waits for user input.""" 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: 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 # Add the transaction amount to the blockchain 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': # 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.chain): self.print_blockchain_elements() print('Invalid blockchain!') # Break out of the loop break print('Balance of {}: {:6.2f}'.format(self.wallet.public_key, self.blockchain.get_balance())) else: print('User left!') print('Done!')
def resolve(self): winner_chain = self.chain replace = False # whether our current chain is getting replaced, initially is False for node in self.__peer_nodes: url = 'http://{}/chain'.format(node) try: response = requests.get(url) node_chain = response.json() # list of block dict # create list of block object with a list of dict transaction 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 # if replace is True, we can assume our transactions are incorrect except requests.exceptions.ConnectionError: continue self.resolve_conflicts = False self.chain = winner_chain if replace: self.__open_transactions = [ ] # if chain is replaced, set local open tx to [] self.save_data() return replace
def resolve(self): winner_chain = self.chain replace = False for node in self.peer_nodes: try: resp = requests.get(f'http://{node}/chain') node_chain = resp.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(self.chain) if node_chain_length > local_chain_length and Verification.verify_chain(self.get_balance, self.difficulty, self.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
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_last_blockchain_value) elif user_choice == '2': if not self.blockchain.mine_block(): print('I left my wallet in El Segundo') 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!') print('Done!')
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 = [ self.get_block_object_from_json(block) for block in node_chain ] node_chain_len = len(node_chain) local_chain_len = len(self.chain) if node_chain_len > local_chain_len 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
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() block_transactions = [ Transaction(tx['sender'], tx['recipient'], tx['signature'], tx['amount']) for tx in node_chain['transactions'] ] node_chain = [ Block(block['index'], block['previous_hash'], 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
def resolve(self): winner_chain = self.chain replace = False ## Control whether current chain is being replaced # Get a snapshot of blockcahin on every peer node to check which peer node has which blockchain & which one is correct. 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): # if chain of peer node is longer and valid, use it as local chain winner_chain = node_chain replace = True except requests.exceptions.ConnectionError: continue # avoids break down code for node offline that cant be reached self.resolve_conflicts = False self.chain = winner_chain if replace: self.__open_transactions = [] self.save_data() return replace
def resolve(self): # we are looping over, so each time we get a new one we assign it here winner_chain = self.__chain # checking if our current chain has been replaced to clear the open transactions replace = False for node in self.__peer_nodes: url = "http://{}/chain".format(node) try: response = requests.get(url) # this is a list node_chain = response.json() # we are converting block to an object # now we are converting transactions to object 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 # we resolved the conflicts so it is False now self.resolve_conflicts = False if replace: self.__open_transactions = [] self.save_data() return replace
def resolve(self): winner_chain = self.__chain replace = False for node in self.__peers_nodes: url = f'http://{node}/chain' try: response = requests.get(url) node_chain = response.json() node_chain = [ Block.dict_to_object(block) for block in node_chain['blockchain'] ] node_chain_len = len(node_chain) local_chain_len = len(winner_chain) if node_chain_len > local_chain_len 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.clear() return replace
def resolve(self): #Resolves conflict when two copies of the blockchain don't match #the blockchain with the longer length persists 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 #clear the open transactions list of the chain with the shorter length if replace: self.__open_transactions = [] self.save_data() return replace
def listen_for_input(self): waiting_for_input = True while waiting_for_input: print('\n Please choose') 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 wallet') print('6: Load wallet') print('7: Save keys') print('q: Quit') user_choice = self.get_user_choice() if user_choice == '1': recipient, amount = self.get_transaction_value() 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 \n") print(self.blockchain.get_open_transactions()) elif user_choice == '2': if not self.blockchain.mine_block(): print("Mining has 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( f"Balance of {self.wallet.public_key}: {self.blockchain.get_balance()}" ) print(self.blockchain.get_balance()) else: print('User left!')
def resolve(self): ''' Update OLD STATE blockchain of current node to longest one from configured peer nodes ''' winner = { 'node': None, 'chain': [], } for node in self.__peer_nodes: node_url = f'http://{node}/chain' try: response = requests.get(node_url) except requests.exceptions.ConnectionError: continue if not response.ok: continue remote_blockchain = response.json() # Find longest blockchain among configured peers if len(winner['chain']) < len(remote_blockchain): winner['node'] = node winner['chain'] = remote_blockchain # Convert chain to list of Block Objects winner['chain'] = [ self.block_as_object(block_dict) for block_dict in winner['chain'] ] if Verification.verify_chain(winner['chain'], DIFFICULTY): # Update Blockchain self.__chain = winner['chain'] self.save_blockchain() # Get winner node open transactions node = winner['node'] node_url = f'http://{node}/transactions' try: response = requests.get(node_url) except requests.exceptions.ConnectionError: print('Connection error with winner node') # Update open transactions if response.ok: winner_txs = response.json() winner_txs = self.tansactions_as_objects(winner_txs) self.__open_transactions = winner_txs else: self.__open_transactions.clear() self.save_open_transactions() self.resolve_conflicts = False print('Updated current blockchain length:', len(self.__chain)) return True return False
def listen_for_input(self): waiting_for_input = True while waiting_for_input: print("Please Choose") print("1: Add a new trasaction 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 wallet 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_transactions(self.wallet.public_key, recipient, amount) if self.blockchain.add_transaction(recipient, self.wallet.public_key, amount, signature): 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_element() 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": if self.wallet.public_key != None and self.wallet.private_key != None: self.wallet.save_keys() elif user_choice == "q": waiting_for_input = False else: print("Invalid input. Please select a value from the list") if not Verification.verify_chain(self.blockchain.get_chain()): print("Invalid blockchain") break print( f'Balance of {self.wallet.public_key}: {self.blockchain.get_balance():6.2f}') else: print("User left") print('Done')
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: Min 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: To 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_blockchainelements() elif (user_choice == "4"): if Verification.verify_transactions( self.blockchain.get_open_transactions(), self.blockchain.get_balance): print("All transactions are valid") else: print("A transaction is invalid") 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 Verification.verify_chain(self.blockchain.chain) == False: print("invalid blockchain") waiting_for_input = False print('Balance of {}: {:6.2f}'.format( self.wallet.public_key, self.blockchain.get_balance())) else: print("User left!") print("Done")
def UI(self): while self.waiting_for_input: print('Enter Choice') print('1:Add transaction') print('2:Mine bLock') print('3: Create Wallet') print('4: Check Transaction valididty: ') print('5:Print bocks') 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() receipent, amount = tx_data signature = self.wallet.sign_transaction( self.wallet.public_key, receipent, amount) if self.blockchain.add_transaction( receipent=receipent, sender=self.wallet.public_key, signature=signature, amount=amount): print("Successful") else: print("Failed") # print(open_transaction) elif user_choice == '2': if not self.blockchain.mine_block(): print("Mining Failed") elif user_choice == '3': self.wallet.create_keys() self.blockchain = Blockchain(self.wallet.public_key) elif user_choice == '4': if Verification.verify_transactions( self.blockchain.get_open_transaction(), self.blockchain.get_balance): print("Valid Transaction") else: print("Invalid transaction") elif user_choice == '5': self.print_blockchain() elif user_choice == '6': self.wallet.load_keys() print('Loaded') elif user_choice == '7': if self.wallet.private_key is not None and self.wallet.public_key is not None: self.wallet.save_keys() print('Saved') elif user_choice == 'q': self.waiting_for_input = False else: print("Invalid Choice") if not Verification.verify_chain(self.blockchain.get_chain()): print("Invalid Blockchain") break print('Balance of {} : {:6.2f}'.format( self.wallet.public_key, self.blockchain.get_balance())) else: print("User Left")
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 the current block') print('3: Ouput the blockchain blocks') print('4: Verify transactions validitya') 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': recipient, amount = self.get_transaction_value() signature = self.wallet.sign_transaction( self.wallet.public_key, recipient, amount) if self.blockchain.add_transaction(self.wallet.public_key, recipient, signature, amount): print('Transction succeeded') 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('Transactions are valid') else: print('There is an invalid transaction') 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 self.blockchain != None and (not Verification.verify_chain( self.blockchain.chain)): print('Invalid blockchain') break print('Done')
def listen_for_input(self): waiting_for_input=True while waiting_for_input : print('Enter your choice :') print('1.Make a new transaction') print('2. Mine a new block ') print("3.Print all the blocks") print('4.Create wallet') print('5.Load wallet') print('6.Save keys') print("7.Quit") user_choice=input() if user_choice=='1' : #Take the user input and store it in a tuple tx_data=self.get_transaction_data() #unpack the tuple here and pass the arguments recipient,amount=tx_data signature=self.wallet.sign_transaction(self.wallet.public_key,recipient,amount) #We need a named argument since sender is the second field in the function definition if self.blockchain.add_transaction(recipient,self.wallet.public_key,signature,amount=amount) : print("Transaction added successfully") else : print("Insufficient Balance of sender") elif user_choice=='2' : #Will fail if user does not have a wallet(public key) if not self.blockchain.mine_block(): print('Mining failed ! Got not wallet ? ') print('Or, One or multiple transaction were modified !') elif user_choice=='3': print(self.blockchain.get_chain()) elif user_choice=='4': self.wallet.create_keys() #Blockchain is initialised in our code only when user has a wallet self.blockchain=Blockchain(self.wallet.public_key) elif user_choice=='5': self.wallet.load_keys() self.blockchain=Blockchain(self.wallet.public_key) elif user_choice=='6': self.wallet.save_keys() elif user_choice=='7' : waiting_for_input=False else : print("Invalid input,please input a valid value from the choices !") """Check the validity of blockchain after each user operation""" if not Verification.verify_chain(self.blockchain.get_chain()): print('Invalid blockchain!') # Break out of the loop break print('Balance of {} is {:6.2f}'.format(self.wallet.public_key,self.blockchain.get_balance()))
def listen_for_input(self): waiting_for_input = True while waiting_for_input: print('---Choose your action---') print('1: Add new transactin value.') print('2: Mine a new block.') print('3: Output the blockchain.') print('4: Check transaction validity.') print('5: Create wallet.') 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('New transaction was added!') else: print('Transaction failed! Error.') elif user_choice == '2': if self.blockchain.mine_block(): print('Successfully mined.') else: print('Mining faled. 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 is valid.') else: print('Transactions validation is faled!') 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('Invalid input. Try again.') if not Verification.verify_chain(self.blockchain.chain): print('ERROR! Chain is not valid!') break print('Balance of {}: {:6.2f}'.format( self.wallet.public_key, self.blockchain.get_balance())) print('Goodbye.')
def listen_for_input(self): waiting_for_input = True while waiting_for_input: self.print_options() user_choice = self.get_user_choice() if user_choice == '1': tx_data = self.get_transaction_value() recipient, amount = tx_data # Add the transaction amount to the blockchain 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 with valid keys?') 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('Option not recognised!') if not Verification.verify_chain(self.blockchain.get_chain()): print("***Invalid blockchain!***") break print( f'{self.wallet.public_key}\'s Balance is {self.blockchain.get_balance(self.wallet.public_key):6.2f}' ) else: #Loop is done - didn't break print('User Left!') print('Done!')
def listen_for_input(self): while True: print('Please choose') print('1: Add a new transaction') print('2: Print blockchain') print('3: Quit') print('4: Verify all transaction') print('5: Mine a new block') print('6: Create wallet') print('7: Load wallet') print('8: Save wallet') user_choice = self.get_user_choice() if user_choice == 1: tx_data = self.get_transaction_value() tx_recipient, tx_amount = tx_data signature = self.wallet.sign_transaction( self.wallet.public_key, tx_recipient, tx_amount) if self.blockchain.add_transaction(tx_recipient, self.wallet.public_key, signature, amount=tx_amount): print('Added transaction!') else: print('Transaction failed!') print(self.blockchain.get_open_transactions()) elif user_choice == 2: 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 == 3: break elif user_choice == 5: if not self.blockchain.mine_block(): print("Mining failed") elif user_choice == 6: self.wallet.create_keys() self.blockchain = Blockchain(self.wallet.public_key) elif user_choice == 7: self.wallet.load_keys() self.blockchain = Blockchain(self.wallet.public_key) elif user_choice == 8: self.wallet.save_keys() else: print('Invalid choice') if not Verification.verify_chain(self.blockchain.chain): print('Invalid blockchain!') break print('Balance of {}: {:6.2f}'.format( self.wallet.public_key, self.blockchain.get_balance())) print("Done!")
def listen_for_input(self): waiting_for_input = True while waiting_for_input: print(""" Please choose: 1) Add a new transaction value 2) Mine a new block 3) Output the blockchain blocks 4) Check transaction validity 5) Create wallet 6) Load keys 7) Save keys q: Quit """) user_choice = self.get_user_choice() if user_choice == '1': recipient, amount = self.get_transaction_value() signature = self.wallet.sign_transaction(sender=self.wallet.public_key, recipient=recipient, amount=amount) if self.blockchain.add_transaction(sender=self.wallet.public_key, recipient=recipient, amount=amount, signature=signature): print('Added transaction') else: print('Transaction failed') # print(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 transaction 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('invalid input, choose a value from the list') print("Balance of {}: {:6.2f}".format(self.wallet.public_key, self.blockchain.get_balance())) if not Verification.verify_chain(self.blockchain.chain): self.print_blockchain_elements() print('invalid blockchain!') break
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 transactions 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": recipient, amount = self.get_transaction_value() signature = self.wallet.sign_transaction( self.wallet.public_key, recipient, amount) if self.blockchain.add_transaction(recipient=recipient, sender=self.wallet.public_key, signature=signature, amount=amount): print("Added transaction") else: print("Transaction failed") elif user_choice == "2": if not self.blockchain.mine_block(self.wallet.public_key): print("Mining failed. Got not 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_to_file() 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( f"Balance of {self.wallet.public_key}: {self.blockchain.get_balance():6.2f}") else: print("User left") print("Done")
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 block') print('3: Output the blockchain blocks') print('4: Check transaction validity') print('q: quit') user_choice = self.get_user_choice() if user_choice == '1': tx_data = self.get_transaction_value() # Unpacking the tuple # Pulls out first el and stores in recipient then pulls second el and stores in amount recipient, amount = tx_data # Since sender = owner, we need to put amount = amount to skip the default for sender if self.blockchain.add_transaction(recipient, self.id, amount=amount): print('Added transaction!') else: print('Transaction failed!') print(self.blockchain.get_open_transactions()) elif user_choice == '2': self.blockchain.mine_block() elif user_choice == '3': self.print_blockchain_elements() elif user_choice == '4': # Calling the class directly with static methods 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 == 'q': waiting_for_input = False else: print('Invalid input. Please pick from the menu items') if not Verification.verify_chain(self.blockchain.chain): self.print_blockchain_elements() print('Invalid blockchain!') break else: print('Verfication Occurred') # Using format method to output nice string print('Balance of {}:{:6.2f}'.format( self.id, self.blockchain.get_balance())) else: print('User left!') print('Done!')
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('q: Quit') user_choice = self.get_user_choice() if user_choice == '1': tx_data = self.get_transaction_value() recipient, amount = tx_data if self.blockchain.add_transaction(recipient, self.id, amount=amount): print('Added transaction') else: print('Transaction failed!') print(self.blockchain.get_open_transactions()) elif user_choice == '2': self.blockchain.mine_block() elif user_choice == '3': self.print_blockchain_elements() elif user_choice == '4': if Verification.verify_transactions( self.blockchain.open_transactions, self.blockchain.get_balance): print('----- All transactions are valid -----') else: print('----- There are invalid transactions -----') elif user_choice == 'q': waiting_for_input = False else: print('Invalid input') if not Verification.verify_chain(self.blockchain.chain): self.print_blockchain_elements() print('Invalid blockchain!') break print('Balance of {} : {:6.2f}'.format( self.id, self.blockchain.get_balance())) print('Done !')
def resolve(self): winner_chain = self.get_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(self.get_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
def listen_for_input(self): """Starts the node and waits for user input.""" 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: print("Please enter your choice") print("1: Add a new transaction value") print("2: Mine 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) # Add the transaction amount to the blockchain 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_blocks() elif user_choice == "4": # verifier = Verification() if Verification.verify_transactions(self.blockchain.get_open_transactions(), self.blockchain.get_balances): print("All transactions are valid!") else: print("There are some transactions failed!") 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 is invalid, please pick a value from a list.") # verifier = Verification() if not Verification.verify_chain(self.blockchain.get_chain()): self.print_blockchain_blocks() print("Invalid Blockchain!") # Break out of the loop break print("Balance of {}: {:6.2f}".format(self.wallet.public_key, self.blockchain.get_balances())) else: print("User Left!") print ("Done!")