|
3 | 3 | from rag_system import rag_system |
4 | 4 | import hashlib |
5 | 5 | import subprocess |
6 | | -app = Flask(__name__, static_folder='templates/images') |
7 | | - |
8 | 6 | import os |
9 | 7 |
|
| 8 | +app = Flask(__name__, static_folder='templates/images') |
10 | 9 | app.config['SECRET_KEY'] = os.getenv('SECRET_KEY') |
11 | 10 | app.config['SESSION_COOKIE_HTTPONLY'] = True |
12 | 11 | app.config['SESSION_COOKIE_SECURE'] = bool(os.getenv('SESSION_COOKIE_SECURE')) |
13 | 12 |
|
14 | 13 | csrf = CSRFProtect(app) |
15 | 14 |
|
| 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 | + |
16 | 25 | @app.route('/', methods=['GET', 'POST']) |
17 | 26 | def index(): |
18 | 27 | return render_template('index.html') |
19 | 28 |
|
20 | 29 | @app.route('/ask', methods=['POST']) |
21 | 30 | 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): |
28 | 32 | return jsonify({"error": "Invalid proof of work"}), 400 |
29 | 33 |
|
30 | 34 | data = request.get_json() |
|
0 commit comments