def block(): global blockchain ip = request.remote_addr if ip != "127.0.0.1" and ip not in Variables.PEER_NODES: Variables.PEER_NODES.append(ip) if ip == '127.0.0.1': raw = request.data.decode('utf-8') parsed = xmltodict.parse(raw) b = Block() b.import_from_xml(parsed['block']) print("I made", b) blockchain.add(b) #Distribute the block to our peers for peer in Variables.PEER_NODES: try: url = "http://" + peer + ":" + str(Variables.PORT) + "/block" xml = b.export_to_xml() headers = {'Content-Type': 'application/xml'} resp = requests.post(url, data=xml, headers=headers).text except: Variables.PEER_NODES.remove(peer) else: block_number = None try: block_number = int(request.args['block_number']) except: pass if block_number is not None: return blockchain.get(block_number).export_to_xml() else: raw = request.data.decode('utf-8') parsed = xmltodict.parse(raw) b = Block() b.import_from_xml(parsed['block']) print("receiv", b) if Utility.validate(b): blockchain.add(b) global event event.set() else: print("Block did not validate",ip) return "0"
def find_new_chains(): func = inspect.currentframe().f_back.f_code logging.info("Starting to find new chains") # Get the blockchains of every other node peers = variables.PEER_NODES logging.debug("peers: {}".format(len(peers))) other_chains = [] for node_url in peers: blockchain_json = None found_blockchain = [] url = "http://" + node_url + ":" + str(variables.PORT) + "/blocks" try: logging.debug("Attempting to access {}".format(node_url)) blockchain_json = requests.post(url) except: logging.warning("Failed to access {}, removing from peers".format(node_url)) variables.PEER_NODES.remove(node_url) continue # Convert the JSON object to a Python dictionary if blockchain_json is not None: blockchain_json = json.loads(blockchain_json.content) for block_json in blockchain_json: temp = Block() temp.importjson(block_json) if Utility.validate(temp): logging.debug("Block validated, adding") found_blockchain.append(temp) else: logging.warning("Block NOT valid, next peer") continue # Verify other node block is correct logging.debug("Attempting to validate this: {}".format(found_blockchain)) validated = Utility.validate_blockchain(found_blockchain) if validated: logging.debug("Blockchain did validate") other_chains.append(found_blockchain) else: logging.warning("Blockchain did not validate") continue logging.info("Ending find new chains") return other_chains