├── .gitignore
├── run_app.py
├── requirements.txt
├── app
├── __init__.py
├── templates
│ ├── base.html
│ └── index.html
└── views.py
├── screenshots
├── 1.png
├── 2.png
└── 3.png
├── .dockerignore
├── .deepsource.toml
├── Dockerfile.backend
├── Dockerfile.frontend
├── Makefile
├── CONTRIBUTING.md
├── compose.yaml
├── README.md
└── node_server.py
/.gitignore:
--------------------------------------------------------------------------------
1 | *.pyc
2 | **/*.pyc
3 |
--------------------------------------------------------------------------------
/run_app.py:
--------------------------------------------------------------------------------
1 | from app import app
2 |
3 | app.run(debug=True)
4 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | Flask~=1.1
2 | requests~=2.22
3 | markupsafe<2.1.0
--------------------------------------------------------------------------------
/app/__init__.py:
--------------------------------------------------------------------------------
1 | from flask import Flask
2 |
3 | app = Flask(__name__)
4 |
5 | from app import views
--------------------------------------------------------------------------------
/screenshots/1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/0x0factor/python_blockchain_app-master/HEAD/screenshots/1.png
--------------------------------------------------------------------------------
/screenshots/2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/0x0factor/python_blockchain_app-master/HEAD/screenshots/2.png
--------------------------------------------------------------------------------
/screenshots/3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/0x0factor/python_blockchain_app-master/HEAD/screenshots/3.png
--------------------------------------------------------------------------------
/.dockerignore:
--------------------------------------------------------------------------------
1 | Dockerfile.backend
2 | Dockerfile.frontend
3 | Makefile
4 | compose.yaml
5 | *.md
6 | screenshots
7 | .gitignore
8 |
--------------------------------------------------------------------------------
/.deepsource.toml:
--------------------------------------------------------------------------------
1 | version = 1
2 |
3 | test_patterns = [
4 |
5 | ]
6 |
7 | exclude_patterns = [
8 |
9 | ]
10 |
11 | [[analyzers]]
12 | name = 'python'
13 | enabled = true
14 | runtime_version = '3.x.x'
15 |
--------------------------------------------------------------------------------
/Dockerfile.backend:
--------------------------------------------------------------------------------
1 | FROM python:3.11
2 |
3 | RUN mkdir /app
4 | COPY . /app
5 | WORKDIR /app
6 | RUN python -m pip install -r requirements.txt
7 | ENV FLASK_APP=node_server.py
8 | ENTRYPOINT [ "flask", "run", "--host", "0.0.0.0" ]
9 |
--------------------------------------------------------------------------------
/Dockerfile.frontend:
--------------------------------------------------------------------------------
1 | FROM python:3.11
2 |
3 | RUN mkdir /app
4 | COPY . /app
5 | WORKDIR /app
6 | RUN python -m pip install -r requirements.txt
7 | ENV FLASK_RUN_SERVER_NAME=0.0.0.0
8 | EXPOSE 5000
9 | ENTRYPOINT [ "python", "run_app.py" ]
10 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | .PHONY: build
2 | build: build-frontend build-backend
3 |
4 | .PHONY: build-frontend
5 | build-frontend:
6 | docker build -t python-blockchain-frontend -f Dockerfile.frontend .
7 |
8 | .PHONY: build-backend
9 | build-backend:
10 | docker build -t python-blockchain-backend -f Dockerfile.backend .
11 |
12 | .PHONY: run
13 | run: build-backend build-frontend
14 | docker-compose up
15 |
--------------------------------------------------------------------------------
/app/templates/base.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | {{ title }}
4 |
5 |
6 |
7 | {{ title }}
8 |
9 | {% with messages = get_flashed_messages() %}
10 | {% if messages %}
11 |
12 | {% for message in messages %}
13 | - {{ message }}
14 | {% endfor %}
15 |
16 | {% endif %}
17 | {% endwith %}
18 | {% block content %}{% endblock %}
19 |
20 |
21 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | ## How to contribute to the project?
2 |
3 | All kind of contributions are welcome. If the change you are suggesting is significant, please do create an issue before working on the patch.
4 |
5 | ## Things to keep in mind
6 |
7 | - The project is designed to be beginner friendly. There are some conscious trade-offs that I've made to keep it simple (as compared to a real-world blockchain project like Bitcoin which will involve a lot of intricacies).
8 | - The coding style is analogous to PEP-8. It's not strictly followed, but please do keep existing style in mind while writing code and as many comments as possible (so that it's easier for others to understand).
9 |
10 | Lastly, thanks for considering to contribute to the project.
11 |
--------------------------------------------------------------------------------
/compose.yaml:
--------------------------------------------------------------------------------
1 | volumes:
2 | data1:
3 | data2:
4 | data3:
5 |
6 | services:
7 | backend1:
8 | build:
9 | context: .
10 | dockerfile: Dockerfile.backend
11 | image: python-blockchain-backend
12 | environment:
13 | FLASK_RUN_PORT: 8000
14 | DATA_FILE: /data/chain.json
15 | network_mode: "host"
16 | volumes:
17 | - "data1:/data"
18 | backend2:
19 | build:
20 | context: .
21 | dockerfile: Dockerfile.backend
22 | image: python-blockchain-backend
23 | environment:
24 | FLASK_RUN_PORT: 8001
25 | DATA_FILE: /data/chain.json
26 | network_mode: "host"
27 | volumes:
28 | - "data2:/data"
29 | backend3:
30 | build:
31 | context: .
32 | dockerfile: Dockerfile.backend
33 | image: python-blockchain-backend
34 | environment:
35 | FLASK_RUN_PORT: 8002
36 | DATA_FILE: /data/chain.json
37 | network_mode: "host"
38 | volumes:
39 | - "data3:/data"
40 | frontend:
41 | build:
42 | context: .
43 | dockerfile: Dockerfile.frontend
44 | image: python-blockchain-frontend
45 | environment:
46 | FLASK_RUN_PORT: 5000
47 | network_mode: "host"
48 |
--------------------------------------------------------------------------------
/app/views.py:
--------------------------------------------------------------------------------
1 | import datetime
2 | import json
3 |
4 | import requests
5 | from flask import render_template, redirect, request
6 |
7 | from app import app
8 |
9 | # The node with which our application interacts, there can be multiple
10 | # such nodes as well.
11 | CONNECTED_NODE_ADDRESS = "http://127.0.0.1:8000"
12 |
13 | posts = []
14 |
15 |
16 | def fetch_posts():
17 | """
18 | Function to fetch the chain from a blockchain node, parse the
19 | data and store it locally.
20 | """
21 | get_chain_address = "{}/chain".format(CONNECTED_NODE_ADDRESS)
22 | response = requests.get(get_chain_address)
23 | if response.status_code == 200:
24 | content = []
25 | chain = json.loads(response.content)
26 | for block in chain["chain"]:
27 | for tx in block["transactions"]:
28 | tx["index"] = block["index"]
29 | tx["hash"] = block["previous_hash"]
30 | content.append(tx)
31 |
32 | global posts
33 | posts = sorted(content, key=lambda k: k['timestamp'],
34 | reverse=True)
35 |
36 |
37 | @app.route('/')
38 | def index():
39 | fetch_posts()
40 | return render_template('index.html',
41 | title='YourNet: Decentralized '
42 | 'content sharing',
43 | posts=posts,
44 | node_address=CONNECTED_NODE_ADDRESS,
45 | readable_time=timestamp_to_string)
46 |
47 |
48 | @app.route('/submit', methods=['POST'])
49 | def submit_textarea():
50 | """
51 | Endpoint to create a new transaction via our application.
52 | """
53 | post_content = request.form["content"]
54 | author = request.form["author"]
55 |
56 | post_object = {
57 | 'author': author,
58 | 'content': post_content,
59 | }
60 |
61 | # Submit a transaction
62 | new_tx_address = "{}/new_transaction".format(CONNECTED_NODE_ADDRESS)
63 |
64 | requests.post(new_tx_address,
65 | json=post_object,
66 | headers={'Content-type': 'application/json'})
67 |
68 | return redirect('/')
69 |
70 |
71 | def timestamp_to_string(epoch_time):
72 | return datetime.datetime.fromtimestamp(epoch_time).strftime('%H:%M')
73 |
--------------------------------------------------------------------------------
/app/templates/index.html:
--------------------------------------------------------------------------------
1 |
2 | {% extends "base.html" %}
3 |
4 | {% block content %}
5 |
6 |
7 |
8 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 | {% for post in posts %}
24 |
25 |
31 |
32 |
33 |
{{post.content}}
34 |
35 |
36 |
37 | {% endfor %}
38 |
39 |
101 |
102 | {% endblock %}
103 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # python_blockchain_app
2 |
3 | A simple tutorial for developing a blockchain application from scratch in Python.
4 |
5 | ## What is blockchain? How it is implemented? And how it works?
6 |
7 | Please read the [step-by-step implementation tutorial](https://gist.github.com/satwikkansal/4a857cad2797b9d199547a752933a715) to get your answers :)
8 |
9 | ## Instructions to run
10 |
11 | Clone the project,
12 |
13 | ```sh
14 | $ git clone https://github.com/satwikkansal/python_blockchain_app.git
15 | ```
16 |
17 | Install the dependencies,
18 |
19 | ```sh
20 | $ cd python_blockchain_app
21 | $ pip install -r requirements.txt
22 | ```
23 |
24 | Start a blockchain node server,
25 |
26 | ```sh
27 | $ export FLASK_APP=node_server.py
28 | $ flask run --port 8000
29 | ```
30 |
31 | ### For windows users
32 | ```
33 | set LANG=C.UTF-8
34 | set FLASK_APP=node_server.py
35 | flask run --port 8000
36 | ```
37 | One instance of our blockchain node is now up and running at port 8000.
38 |
39 |
40 | Run the application on a different terminal session,
41 |
42 | ```sh
43 | $ python run_app.py
44 | ```
45 |
46 | ### For windows users
47 | ```
48 | set LANG=C.UTF-8
49 | set FLASK_APP=run_app.py
50 | flask run --port 8000
51 | ```
52 |
53 | The application should be up and running at [http://localhost:5000](http://localhost:5000).
54 |
55 | Here are a few screenshots
56 |
57 | 1. Posting some content
58 |
59 | 
60 |
61 | 2. Requesting the node to mine
62 |
63 | 
64 |
65 | 3. Resyncing with the chain for updated data
66 |
67 | 
68 |
69 | To play around by spinning off multiple custom nodes, use the `register_with/` endpoint to register a new node.
70 |
71 | Here's a sample scenario that you might wanna try,
72 |
73 | ```sh
74 | # Make sure you set the FLASK_APP environment variable to node_server.py before running these nodes
75 | # already running
76 | $ flask run --port 8000 &
77 | # spinning up new nodes
78 | $ flask run --port 8001 &
79 | $ flask run --port 8002 &
80 | ```
81 |
82 | You can use the following cURL requests to register the nodes at port `8001` and `8002` with the already running `8000`.
83 |
84 | ```sh
85 | curl -X POST \
86 | http://127.0.0.1:8001/register_with \
87 | -H 'Content-Type: application/json' \
88 | -d '{"node_address": "http://127.0.0.1:8000"}'
89 | ```
90 |
91 | ```sh
92 | curl -X POST \
93 | http://127.0.0.1:8002/register_with \
94 | -H 'Content-Type: application/json' \
95 | -d '{"node_address": "http://127.0.0.1:8000"}'
96 | ```
97 |
98 | This will make the node at port 8000 aware of the nodes at port 8001 and 8002, and make the newer nodes sync the chain with the node 8000, so that they are able to actively participate in the mining process post registration.
99 |
100 | To update the node with which the frontend application syncs (default is localhost port 8000), change `CONNECTED_NODE_ADDRESS` field in the [views.py](/app/views.py) file.
101 |
102 | Once you do all this, you can run the application, create transactions (post messages via the web inteface), and once you mine the transactions, all the nodes in the network will update the chain. The chain of the nodes can also be inspected by inovking `/chain` endpoint using cURL.
103 |
104 | ```sh
105 | $ curl -X GET http://localhost:8001/chain
106 | $ curl -X GET http://localhost:8002/chain
107 | ```
108 |
--------------------------------------------------------------------------------
/node_server.py:
--------------------------------------------------------------------------------
1 | import os
2 | import sys
3 | import signal
4 | import atexit
5 | from hashlib import sha256
6 | import json
7 | import time
8 |
9 | from flask import Flask, request
10 | import requests
11 |
12 |
13 | class Block:
14 | def __init__(self, index, transactions, timestamp, previous_hash, nonce=0):
15 | self.index = index
16 | self.transactions = transactions
17 | self.timestamp = timestamp
18 | self.previous_hash = previous_hash
19 | self.nonce = nonce
20 |
21 | def compute_hash(self):
22 | """
23 | A function that return the hash of the block contents.
24 | """
25 | block_string = json.dumps(self.__dict__, sort_keys=True)
26 | return sha256(block_string.encode()).hexdigest()
27 |
28 |
29 | class Blockchain:
30 | # difficulty of our PoW algorithm
31 | difficulty = 2
32 |
33 | def __init__(self, chain=None):
34 | self.unconfirmed_transactions = []
35 | self.chain = chain
36 | if self.chain is None:
37 | self.chain = []
38 | self.create_genesis_block()
39 |
40 | def create_genesis_block(self):
41 | """
42 | A function to generate genesis block and appends it to
43 | the chain. The block has index 0, previous_hash as 0, and
44 | a valid hash.
45 | """
46 | genesis_block = Block(0, [], 0, "0")
47 | genesis_block.hash = genesis_block.compute_hash()
48 | self.chain.append(genesis_block)
49 |
50 | @property
51 | def last_block(self):
52 | return self.chain[-1]
53 |
54 | def add_block(self, block, proof):
55 | """
56 | A function that adds the block to the chain after verification.
57 | Verification includes:
58 | * Checking if the proof is valid.
59 | * The previous_hash referred in the block and the hash of latest block
60 | in the chain match.
61 | """
62 | previous_hash = self.last_block.hash
63 |
64 | if previous_hash != block.previous_hash:
65 | raise ValueError("Previous hash incorrect")
66 |
67 | if not Blockchain.is_valid_proof(block, proof):
68 | raise ValueError("Block proof invalid")
69 |
70 | block.hash = proof
71 | self.chain.append(block)
72 |
73 | @staticmethod
74 | def proof_of_work(block):
75 | """
76 | Function that tries different values of nonce to get a hash
77 | that satisfies our difficulty criteria.
78 | """
79 | block.nonce = 0
80 |
81 | computed_hash = block.compute_hash()
82 | while not computed_hash.startswith('0' * Blockchain.difficulty):
83 | block.nonce += 1
84 | computed_hash = block.compute_hash()
85 |
86 | return computed_hash
87 |
88 | def add_new_transaction(self, transaction):
89 | self.unconfirmed_transactions.append(transaction)
90 |
91 | @classmethod
92 | def is_valid_proof(cls, block, block_hash):
93 | """
94 | Check if block_hash is valid hash of block and satisfies
95 | the difficulty criteria.
96 | """
97 | return (block_hash.startswith('0' * Blockchain.difficulty) and
98 | block_hash == block.compute_hash())
99 |
100 | @classmethod
101 | def check_chain_validity(cls, chain):
102 | result = True
103 | previous_hash = "0"
104 |
105 | for block in chain:
106 | block_hash = block.hash
107 | # remove the hash field to recompute the hash again
108 | # using `compute_hash` method.
109 | delattr(block, "hash")
110 |
111 | if not cls.is_valid_proof(block, block_hash) or \
112 | previous_hash != block.previous_hash:
113 | result = False
114 | break
115 |
116 | block.hash, previous_hash = block_hash, block_hash
117 |
118 | return result
119 |
120 | def mine(self):
121 | """
122 | This function serves as an interface to add the pending
123 | transactions to the blockchain by adding them to the block
124 | and figuring out Proof Of Work.
125 | """
126 | if not self.unconfirmed_transactions:
127 | return False
128 |
129 | last_block = self.last_block
130 |
131 | new_block = Block(index=last_block.index + 1,
132 | transactions=self.unconfirmed_transactions,
133 | timestamp=time.time(),
134 | previous_hash=last_block.hash)
135 |
136 | proof = self.proof_of_work(new_block)
137 | self.add_block(new_block, proof)
138 |
139 | self.unconfirmed_transactions = []
140 |
141 | return True
142 |
143 |
144 | app = Flask(__name__)
145 |
146 | # the node's copy of blockchain
147 | blockchain = None
148 |
149 | # the address to other participating members of the network
150 | peers = set()
151 |
152 |
153 | # endpoint to submit a new transaction. This will be used by
154 | # our application to add new data (posts) to the blockchain
155 | @app.route('/new_transaction', methods=['POST'])
156 | def new_transaction():
157 | tx_data = request.get_json()
158 | required_fields = ["author", "content"]
159 |
160 | for field in required_fields:
161 | if not tx_data.get(field):
162 | return "Invalid transaction data", 404
163 |
164 | tx_data["timestamp"] = time.time()
165 |
166 | blockchain.add_new_transaction(tx_data)
167 |
168 | return "Success", 201
169 |
170 |
171 | chain_file_name = os.environ.get('DATA_FILE')
172 |
173 |
174 | def create_chain_from_dump(chain_dump):
175 | generated_blockchain = Blockchain()
176 | for idx, block_data in enumerate(chain_dump):
177 | if idx == 0:
178 | continue # skip genesis block
179 | block = Block(block_data["index"],
180 | block_data["transactions"],
181 | block_data["timestamp"],
182 | block_data["previous_hash"],
183 | block_data["nonce"])
184 | proof = block_data['hash']
185 | generated_blockchain.add_block(block, proof)
186 | return generated_blockchain
187 |
188 |
189 | # endpoint to return the node's copy of the chain.
190 | # Our application will be using this endpoint to query
191 | # all the posts to display.
192 | @app.route('/chain', methods=['GET'])
193 | def get_chain():
194 | chain_data = []
195 | for block in blockchain.chain:
196 | chain_data.append(block.__dict__)
197 | return json.dumps({"length": len(chain_data),
198 | "chain": chain_data,
199 | "peers": list(peers)})
200 |
201 |
202 | def save_chain():
203 | if chain_file_name is not None:
204 | with open(chain_file_name, 'w') as chain_file:
205 | chain_file.write(get_chain())
206 |
207 |
208 | def exit_from_signal(signum, stack_frame):
209 | sys.exit(0)
210 |
211 |
212 | atexit.register(save_chain)
213 | signal.signal(signal.SIGTERM, exit_from_signal)
214 | signal.signal(signal.SIGINT, exit_from_signal)
215 |
216 |
217 | if chain_file_name is None:
218 | data = None
219 | else:
220 | with open(chain_file_name, 'r') as chain_file:
221 | raw_data = chain_file.read()
222 | if raw_data is None or len(raw_data) == 0:
223 | data = None
224 | else:
225 | data = json.loads(raw_data)
226 |
227 | if data is None:
228 | # the node's copy of blockchain
229 | blockchain = Blockchain()
230 | else:
231 | blockchain = create_chain_from_dump(data['chain'])
232 | peers.update(data['peers'])
233 |
234 |
235 | # endpoint to request the node to mine the unconfirmed
236 | # transactions (if any). We'll be using it to initiate
237 | # a command to mine from our application itself.
238 | @app.route('/mine', methods=['GET'])
239 | def mine_unconfirmed_transactions():
240 | result = blockchain.mine()
241 | if not result:
242 | return "No transactions to mine"
243 | else:
244 | # Making sure we have the longest chain before announcing to the network
245 | chain_length = len(blockchain.chain)
246 | consensus()
247 | if chain_length == len(blockchain.chain):
248 | # announce the recently mined block to the network
249 | announce_new_block(blockchain.last_block)
250 | return "Block #{} is mined.".format(blockchain.last_block.index)
251 |
252 |
253 | # endpoint to add new peers to the network.
254 | @app.route('/register_node', methods=['POST'])
255 | def register_new_peers():
256 | node_address = request.get_json()["node_address"]
257 | if not node_address:
258 | return "Invalid data", 400
259 |
260 | # Add the node to the peer list
261 | peers.add(node_address)
262 |
263 | # Return the consensus blockchain to the newly registered node
264 | # so that he can sync
265 | return get_chain()
266 |
267 |
268 | @app.route('/register_with', methods=['POST'])
269 | def register_with_existing_node():
270 | """
271 | Internally calls the `register_node` endpoint to
272 | register current node with the node specified in the
273 | request, and sync the blockchain as well as peer data.
274 | """
275 | node_address = request.get_json()["node_address"]
276 | if not node_address:
277 | return "Invalid data", 400
278 |
279 | data = {"node_address": request.host_url}
280 | headers = {'Content-Type': "application/json"}
281 |
282 | # Make a request to register with remote node and obtain information
283 | response = requests.post(node_address + "/register_node",
284 | data=json.dumps(data), headers=headers)
285 |
286 | if response.status_code == 200:
287 | global blockchain
288 | global peers
289 | # update chain and the peers
290 | chain_dump = response.json()['chain']
291 | blockchain = create_chain_from_dump(chain_dump)
292 | peers.update(response.json()['peers'])
293 | return "Registration successful", 200
294 | else:
295 | # if something goes wrong, pass it on to the API response
296 | return response.content, response.status_code
297 |
298 |
299 | # endpoint to add a block mined by someone else to
300 | # the node's chain. The block is first verified by the node
301 | # and then added to the chain.
302 | @app.route('/add_block', methods=['POST'])
303 | def verify_and_add_block():
304 | block_data = request.get_json()
305 | block = Block(block_data["index"],
306 | block_data["transactions"],
307 | block_data["timestamp"],
308 | block_data["previous_hash"],
309 | block_data["nonce"])
310 |
311 | proof = block_data['hash']
312 | try:
313 | blockchain.add_block(block, proof)
314 | except ValueError as e:
315 | return "The block was discarded by the node: " + e.str(), 400
316 |
317 | return "Block added to the chain", 201
318 |
319 |
320 | # endpoint to query unconfirmed transactions
321 | @app.route('/pending_tx')
322 | def get_pending_tx():
323 | return json.dumps(blockchain.unconfirmed_transactions)
324 |
325 |
326 | def consensus():
327 | """
328 | Our naive consnsus algorithm. If a longer valid chain is
329 | found, our chain is replaced with it.
330 | """
331 | global blockchain
332 |
333 | longest_chain = None
334 | current_len = len(blockchain.chain)
335 |
336 | for node in peers:
337 | response = requests.get('{}chain'.format(node))
338 | length = response.json()['length']
339 | chain = response.json()['chain']
340 | if length > current_len and blockchain.check_chain_validity(chain):
341 | current_len = length
342 | longest_chain = chain
343 |
344 | if longest_chain:
345 | blockchain = longest_chain
346 | return True
347 |
348 | return False
349 |
350 |
351 | def announce_new_block(block):
352 | """
353 | A function to announce to the network once a block has been mined.
354 | Other blocks can simply verify the proof of work and add it to their
355 | respective chains.
356 | """
357 | for peer in peers:
358 | url = "{}add_block".format(peer)
359 | headers = {'Content-Type': "application/json"}
360 | requests.post(url,
361 | data=json.dumps(block.__dict__, sort_keys=True),
362 | headers=headers)
363 |
364 | # Uncomment this line if you want to specify the port number in the code
365 | #app.run(debug=True, port=8000)
366 |
--------------------------------------------------------------------------------