Learn Blockchains by Building One

The fastest way to learn how Blockchains work is to build one

Before you get started…

 pip install Flask==0.12.2 requests==2.18.4 

Step 1: Building a Blockchain

Blueprint of our Blockchain Class
Example of a Block in our Blockchain
from hashlib import sha256x = 5
y = 0 # We don't know what y should be yet...
while sha256(f'{x*y}'.encode()).hexdigest()[-1] != "0":
y += 1
print(f'The solution is y = {y}')
hash(5 * 21) = 1253e9373e...5e3600155e860

Find a number p that when hashed with the previous block’s solution a hash with 4 leading 0s is produced.

Step 2: Our Blockchain as an API

{
"sender": "my address",
"recipient": "someone else's address",
"amount": 5
}
A method for creating Transactions

Step 3: Interacting with our Blockchain

$ python blockchain.py* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Using Postman to make a GET request
Using Postman to make a POST request
$ curl -X POST -H "Content-Type: application/json" -d '{
"sender": "d4ee26eee15148ee92c6cd394edd974e",
"recipient": "someone-other-address",
"amount": 5
}' "http://localhost:5000/transactions/new"
{
"chain": [
{
"index": 1,
"previous_hash": 1,
"proof": 100,
"timestamp": 1506280650.770839,
"transactions": []
},
{
"index": 2,
"previous_hash": "c099bc...bfb7",
"proof": 35293,
"timestamp": 1506280664.717925,
"transactions": [
{
"amount": 1,
"recipient": "8bbcb347e0634905b0cac7955bae152b",
"sender": "0"
}
]
},
{
"index": 3,
"previous_hash": "eff91a...10f2",
"proof": 35089,
"timestamp": 1506280666.1086972,
"transactions": [
{
"amount": 1,
"recipient": "8bbcb347e0634905b0cac7955bae152b",
"sender": "0"
}
]
}
],
"length": 3
}

Step 4: Consensus

A method for adding neighbouring nodes to our Network
Registering a new Node
Consensus Algorithm at Work

If you enjoyed this guide, or have any suggestions or questions, let me know in the comments. And if you’ve spotted any errors, feel free to contribute to the code here!

--

--

https://twitter.com/van_flymen • Software Engineer • https://dvf.nyc • South African in NYC ✌️

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store