Skip to content

Commit f321695

Browse files
authored
Merge pull request #29 from DefangLabs/lio/check-pow-nonce
Check POW nonce in server
2 parents c0eff63 + b23d85d commit f321695

File tree

4 files changed

+21
-5
lines changed

4 files changed

+21
-5
lines changed

.dockerignore

Lines changed: 0 additions & 1 deletion
This file was deleted.

app/.dockerignore

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
myenv
2+
.direnv
3+
.envrc
4+
__pycache__

app/app.py

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,41 @@
11
from flask import Flask, request, jsonify, render_template, Response, stream_with_context
22
from flask_wtf.csrf import CSRFProtect
33
from rag_system import rag_system
4+
import hashlib
45
import subprocess
5-
app = Flask(__name__, static_folder='templates/images')
6-
76
import os
87

8+
app = Flask(__name__, static_folder='templates/images')
99
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY')
1010
app.config['SESSION_COOKIE_HTTPONLY'] = True
1111
app.config['SESSION_COOKIE_SECURE'] = bool(os.getenv('SESSION_COOKIE_SECURE'))
1212

1313
csrf = CSRFProtect(app)
1414

15+
16+
def validate_pow(nonce, data, difficulty):
17+
# Calculate the sha256 of the concatenated string of 32-bit X-Nonce header and raw body.
18+
# This calculation has to match the code on the client side, in index.html.
19+
nonce_bytes = int(nonce).to_bytes(4, byteorder='little') # 32-bit = 4 bytes
20+
calculated_hash = hashlib.sha256(nonce_bytes + data).digest()
21+
first_uint32 = int.from_bytes(calculated_hash[:4], byteorder='big')
22+
return first_uint32 <= difficulty
23+
24+
1525
@app.route('/', methods=['GET', 'POST'])
1626
def index():
1727
return render_template('index.html')
1828

1929
@app.route('/ask', methods=['POST'])
2030
def ask():
31+
if not validate_pow(request.headers.get('X-Nonce'), request.get_data(), 0x50000):
32+
return jsonify({"error": "Invalid proof of work"}), 400
33+
2134
data = request.get_json()
2235
query = data.get('query')
2336
if not query:
2437
return jsonify({"error": "No query provided"}), 400
25-
38+
2639
def generate():
2740
try:
2841
for token in rag_system.answer_query_stream(query):

compose.dev.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ services:
55
shm_size: "16gb"
66
ports:
77
- target: 5000
8-
published: 5000
8+
published: 5001 # MacOS AirPlay uses port 5000
99
protocol: tcp
1010
mode: ingress
1111
environment:

0 commit comments

Comments
 (0)