Skip to content

Commit

Permalink
PR comments: validate_pow
Browse files Browse the repository at this point in the history
  • Loading branch information
lionello committed Dec 19, 2024
1 parent 6c89a93 commit b23d85d
Showing 1 changed file with 12 additions and 8 deletions.
20 changes: 12 additions & 8 deletions app/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,32 @@
from rag_system import rag_system
import hashlib
import subprocess
app = Flask(__name__, static_folder='templates/images')

import os

app = Flask(__name__, static_folder='templates/images')
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY')
app.config['SESSION_COOKIE_HTTPONLY'] = True
app.config['SESSION_COOKIE_SECURE'] = bool(os.getenv('SESSION_COOKIE_SECURE'))

csrf = CSRFProtect(app)


def validate_pow(nonce, data, difficulty):
# Calculate the sha256 of the concatenated string of 32-bit X-Nonce header and raw body.
# This calculation has to match the code on the client side, in index.html.
nonce_bytes = int(nonce).to_bytes(4, byteorder='little') # 32-bit = 4 bytes
calculated_hash = hashlib.sha256(nonce_bytes + data).digest()
first_uint32 = int.from_bytes(calculated_hash[:4], byteorder='big')
return first_uint32 <= difficulty


@app.route('/', methods=['GET', 'POST'])
def index():
return render_template('index.html')

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

data = request.get_json()
Expand Down

0 comments on commit b23d85d

Please sign in to comment.