fix: Only update address every 24 hrs and increase the receiveWindow
All checks were successful
Build Docker / Build Image (push) Successful in 50s

This commit is contained in:
Nathan Woodburn 2024-07-23 10:03:30 +10:00
parent 9604f08c4e
commit 4e8ca03aed
Signed by: nathanwoodburn
GPG Key ID: 203B000478AD0EF1
2 changed files with 112 additions and 92 deletions

202
main.py
View File

@ -1,4 +1,12 @@
from flask import Flask, make_response, redirect, request, jsonify, render_template, send_from_directory from flask import (
Flask,
make_response,
redirect,
request,
jsonify,
render_template,
send_from_directory,
)
import os import os
import dotenv import dotenv
import requests import requests
@ -11,173 +19,186 @@ from email_validator import validate_email, EmailNotValidError
app = Flask(__name__) app = Flask(__name__)
dotenv.load_dotenv() dotenv.load_dotenv()
address = 'hs1qr7d0xqsyatls47jf28gvm97twe8k606gspfpsz' address = "hs1qr7d0xqsyatls47jf28gvm97twe8k606gspfpsz"
if os.getenv('address') != None: if os.getenv("address") != None:
address = os.getenv('address') address = os.getenv("address")
#Assets routes
@app.route('/assets/<path:path>') # Assets routes
@app.route("/assets/<path:path>")
def send_report(path): def send_report(path):
return send_from_directory('templates/assets', path) return send_from_directory("templates/assets", path)
@app.route("/")
@app.route('/')
def index(): def index():
params = request.args params = request.args
if 'r' in request.cookies: if "r" in request.cookies:
print("Referer: " + request.cookies['r']) print("Referer: " + request.cookies["r"])
return render_template('index.html', hidden=request.cookies['r'],address=address) return render_template(
"index.html", hidden=request.cookies["r"], address=address
)
if "r" in params:
if 'r' in params: print("Referer: " + params["r"])
print("Referer: " + params['r'])
# Set cookie # Set cookie
resp = make_response(render_template('index.html', hidden=params['r'],address=address)) resp = make_response(
resp.set_cookie('r', params['r'], max_age=60*60*24) render_template("index.html", hidden=params["r"], address=address)
)
resp.set_cookie("r", params["r"], max_age=60 * 60 * 24)
return resp return resp
return render_template('index.html',address=address) return render_template("index.html", address=address)
@app.route('/', methods=['POST']) @app.route("/", methods=["POST"])
def submit(): def submit():
name = request.form['name'] name = request.form["name"]
email = request.form['email'] email = request.form["email"]
hidden = request.form['hi'] hidden = request.form["hi"]
ip = request.remote_addr ip = request.remote_addr
if 'X-REAL-IP' in request.headers: if "X-REAL-IP" in request.headers:
ip = request.headers['X-REAL-IP'] ip = request.headers["X-REAL-IP"]
if 'X-Real-Ip' in request.headers: if "X-Real-Ip" in request.headers:
ip = request.headers['X-Real-Ip'] ip = request.headers["X-Real-Ip"]
if hidden == '': if hidden == "":
hidden = 'None' hidden = "None"
if 'r' in request.cookies: if "r" in request.cookies:
hidden = request.cookies['r'] hidden = request.cookies["r"]
# Validate email # Validate email
try: try:
emailinfo = validate_email(email, check_deliverability=False) emailinfo = validate_email(email, check_deliverability=False)
email = emailinfo.normalized email = emailinfo.normalized
except EmailNotValidError as e: except EmailNotValidError as e:
return render_template('error.html',error='Invalid email address',address=address) return render_template(
"error.html", error="Invalid email address", address=address
)
status = gift.gift(name, email, hidden, ip) status = gift.gift(name, email, hidden, ip)
print(status,flush=True) print(status, flush=True)
if status == True: if status == True:
return render_template('success.html',address=address) return render_template("success.html", address=address)
else: else:
return render_template('error.html',error=status,address=address) return render_template("error.html", error=status, address=address)
@app.route('/api', methods=['POST'])
@app.route("/api", methods=["POST"])
def api(): def api():
# Get from params # Get from params
params = request.args params = request.args
name = params['name'] name = params["name"]
email = params['email'] email = params["email"]
key = params['key'] key = params["key"]
if key != os.getenv('api_key'): if key != os.getenv("api_key"):
return jsonify({'error': 'Invalid API key', 'success': False}) return jsonify({"error": "Invalid API key", "success": False})
if 'X-REAL-IP' in request.headers: if "X-REAL-IP" in request.headers:
ip = request.headers['X-REAL-IP'] ip = request.headers["X-REAL-IP"]
if 'X-Real-Ip' in request.headers: if "X-Real-Ip" in request.headers:
ip = request.headers['X-Real-Ip'] ip = request.headers["X-Real-Ip"]
# Validate email # Validate email
try: try:
emailinfo = validate_email(email, check_deliverability=False) emailinfo = validate_email(email, check_deliverability=False)
email = emailinfo.normalized email = emailinfo.normalized
except EmailNotValidError as e: except EmailNotValidError as e:
return jsonify({'error': 'Invalid email address', 'success': False}) return jsonify({"error": "Invalid email address", "success": False})
status = gift.gift(name, email, "api", ip, True)
status = gift.gift(name, email, "api", ip,True) print(status, flush=True)
print(status,flush=True)
if status == True: if status == True:
return jsonify({'success': True}) return jsonify({"success": True})
else: else:
return jsonify({'error': status, 'success': False}) return jsonify({"error": status, "success": False})
# Special routes # Special routes
@app.route('/.well-known/wallets/<token>') @app.route("/.well-known/wallets/<token>")
def send_wallet(token): def send_wallet(token):
address = requests.get('https://nathan.woodburn.au/.well-known/wallets/'+token).text address = requests.get(
return make_response(address, 200, {'Content-Type': 'text/plain'}) "https://nathan.woodburn.au/.well-known/wallets/" + token
).text
return make_response(address, 200, {"Content-Type": "text/plain"})
@app.route('/stats')
@app.route("/stats")
def stats(): def stats():
# Read the file # Read the file
path = '/data/gifts.json' path = "/data/gifts.json"
if os.getenv('local') == 'true': if os.getenv("local") == "true":
path = './gifts.json' path = "./gifts.json"
# Load file # Load file
gifts = [] gifts = []
if os.path.isfile(path): if os.path.isfile(path):
with open(path, 'r') as f: with open(path, "r") as f:
gifts = json.load(f) gifts = json.load(f)
# Loop through gifts # Loop through gifts
referals = {} referals = {}
for gift_item in gifts: for gift_item in gifts:
if gift_item['referer'] not in referals: if gift_item["referer"] not in referals:
referals[gift_item['referer']] = 1 referals[gift_item["referer"]] = 1
else: else:
referals[gift_item['referer']] += 1 referals[gift_item["referer"]] += 1
statsHTML = 'Total gifts: ' + str(len(gifts)) + '<br><br>' statsHTML = "Total gifts: " + str(len(gifts)) + "<br><br>"
statsHTML += 'Referals:<br>' statsHTML += "Referals:<br>"
for referal in referals: for referal in referals:
statsHTML += referal + ': ' + str(referals[referal]) + '<br>' statsHTML += referal + ": " + str(referals[referal]) + "<br>"
statsHTML += "<br>Remaining balance: " + str(gift.balance()) + " HNS<br>"
return render_template("stats.html", address=address, stats=statsHTML)
statsHTML += '<br>Remaining balance: ' + str(gift.balance()) + ' HNS<br>' @app.route("/<path:path>")
return render_template('stats.html',address=address,stats=statsHTML)
@app.route('/<path:path>')
def catch_all(path): def catch_all(path):
return redirect('/?r='+path) return redirect("/?r=" + path)
# 404 catch all # 404 catch all
@app.errorhandler(404) @app.errorhandler(404)
def not_found(e): def not_found(e):
return redirect('/') return redirect("/")
def update_address(): def update_address():
global address global address
payload = { payload = {
"asset": "HNS", "asset": "HNS",
# "timestamp": 1699411892673,
"timestamp": int(round(time.time() * 1000)), "timestamp": int(round(time.time() * 1000)),
"receiveWindow": 10000 "receiveWindow": 20000,
} }
nbcookie = os.getenv('cookie') nbcookie = os.getenv("cookie")
cookies = {"namebase-main": nbcookie} cookies = {"namebase-main": nbcookie}
headers = {"Accept": "application/json", "Content-Type": "application/json"} headers = {"Accept": "application/json", "Content-Type": "application/json"}
r = requests.post('https://www.namebase.io/api/v0/deposit/address', data=json.dumps(payload), headers=headers, cookies=cookies) r = requests.post(
if 'address' not in r.json(): "https://www.namebase.io/api/v0/deposit/address",
print("Error: " + r.text,flush=True) data=json.dumps(payload),
headers=headers,
cookies=cookies,
)
if "address" not in r.json():
print("Error: " + r.text, flush=True)
# Send alert via discord # Send alert via discord
url = os.getenv('discord_webhook') url = os.getenv("discord_webhook")
if url == None: if url == None:
return "No webhook set" return "No webhook set"
payload = { payload = {"content": "NB cookie has expired\n@everyone"}
"content": "NB cookie has expired\n@everyone" response = requests.post(
} url, data=json.dumps(payload), headers={"Content-Type": "application/json"}
response = requests.post(url, data=json.dumps(payload), headers={'Content-Type': 'application/json'}) )
# Check if the message was sent successfully # Check if the message was sent successfully
if response.status_code == 204: if response.status_code == 204:
@ -187,13 +208,12 @@ def update_address():
print(response.text) print(response.text)
return return
address = r.json()['address'] address = r.json()["address"]
print("Address updated: " + address,flush=True) print("Address updated: " + address, flush=True)
update_address() update_address()
if __name__ == "__main__":
if __name__ == '__main__': app.run(debug=False, port=5000, host="0.0.0.0")
app.run(debug=False, port=5000, host='0.0.0.0')

View File

@ -27,7 +27,7 @@ class GunicornApp(BaseApplication):
if __name__ == '__main__': if __name__ == '__main__':
# Every hour # Every hour
scheduler = BackgroundScheduler() scheduler = BackgroundScheduler()
scheduler.add_job(main.update_address, 'cron', hour='*') scheduler.add_job(main.update_address, 'cron', hour='0')
scheduler.start() scheduler.start()