Created
July 23, 2017 13:56
-
-
Save aunyks/a01b13e9ffba1d0734cfd19ff02f058d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @node.route('/blocks', methods=['GET']) | |
| def get_blocks(): | |
| chain_to_send = blockchain | |
| # Convert our blocks into dictionaries | |
| # so we can send them as json objects later | |
| for block in chain_to_send: | |
| block_index = str(block.index) | |
| block_timestamp = str(block.timestamp) | |
| block_data = str(block.data) | |
| block_hash = block.hash | |
| block = { | |
| "index": block_index, | |
| "timestamp": block_timestamp, | |
| "data": block_data, | |
| "hash": block_hash | |
| } | |
| # Send our chain to whomever requested it | |
| chain_to_send = json.dumps(chain_to_send) | |
| return chain_to_send | |
| def find_new_chains(): | |
| # Get the blockchains of every | |
| # other node | |
| other_chains = [] | |
| for node_url in peer_nodes: | |
| # Get their chains using a GET request | |
| block = requests.get(node_url + "/blocks").content | |
| # Convert the JSON object to a Python dictionary | |
| block = json.loads(block) | |
| # Add it to our list | |
| other_chains.append(block) | |
| return other_chains | |
| def consensus(): | |
| # Get the blocks from other nodes | |
| other_chains = find_new_chains() | |
| # If our chain isn't longest, | |
| # then we store the longest chain | |
| longest_chain = blockchain | |
| for chain in other_chains: | |
| if len(longest_chain) < len(chain): | |
| longest_chain = chain | |
| # If the longest chain wasn't ours, | |
| # then we set our chain to the longest | |
| blockchain = longest_chain |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment