import hashlib import os from flask import Flask, request, render_template, redirect app = Flask(__name__) # Global storage for the current challenge current_challenge = {} # Redirect root URL to get-challenge @app.route('/', methods=['GET']) def index(): return redirect('/get-challenge') # Redirect to the challenge page # Generate a nonce and difficulty for the client @app.route('/get-challenge', methods=['GET']) def get_challenge(): global current_challenge nonce = os.urandom(16).hex() # Generate a random 16-byte nonce difficulty = 4 # Set the difficulty (number of leading zeros) current_challenge = {'nonce': nonce, 'difficulty': difficulty} return render_template('challenge.html', nonce=nonce, difficulty=difficulty) # Verify the solution provided by the client @app.route('/verify', methods=['POST']) def verify_solution(): solution = request.form['solution'] nonce = current_challenge['nonce'] difficulty = current_challenge['difficulty'] # Recompute the hash with the client's solution hash_result = hashlib.sha256((nonce + solution).encode()).hexdigest() # Check if the hash has the required number of leading zeros if hash_result.startswith('0' * difficulty): return render_template('result.html', status="Success! Solution is correct.") else: return render_template('result.html', status="Failed. Incorrect solution.") if __name__ == '__main__': app.run(host='0.0.0.0', port=6969)