Skip to content

Commit b23d85d

Browse files
committed
PR comments: validate_pow
1 parent 6c89a93 commit b23d85d

File tree

1 file changed

+12
-8
lines changed

1 file changed

+12
-8
lines changed

app/app.py

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,28 +3,32 @@
33
from rag_system import rag_system
44
import hashlib
55
import subprocess
6-
app = Flask(__name__, static_folder='templates/images')
7-
86
import os
97

8+
app = Flask(__name__, static_folder='templates/images')
109
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY')
1110
app.config['SESSION_COOKIE_HTTPONLY'] = True
1211
app.config['SESSION_COOKIE_SECURE'] = bool(os.getenv('SESSION_COOKIE_SECURE'))
1312

1413
csrf = CSRFProtect(app)
1514

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+
1625
@app.route('/', methods=['GET', 'POST'])
1726
def index():
1827
return render_template('index.html')
1928

2029
@app.route('/ask', methods=['POST'])
2130
def ask():
22-
# Calculate the sha256 of the concatenated string of 32-bit X-Nonce header and raw body.
23-
x_nonce = request.headers.get('X-Nonce')
24-
x_nonce_bytes = int(x_nonce).to_bytes(4, byteorder='little') # 32-bit = 4 bytes
25-
calculated_hash = hashlib.sha256(x_nonce_bytes + request.get_data()).digest()
26-
first_uint32 = int.from_bytes(calculated_hash[:4], byteorder='big')
27-
if first_uint32 > 0x50000:
31+
if not validate_pow(request.headers.get('X-Nonce'), request.get_data(), 0x50000):
2832
return jsonify({"error": "Invalid proof of work"}), 400
2933

3034
data = request.get_json()

0 commit comments

Comments
 (0)