forked from Scottcjn/Rustchain
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfaucet.py
More file actions
324 lines (274 loc) · 9.27 KB
/
faucet.py
File metadata and controls
324 lines (274 loc) · 9.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
#!/usr/bin/env python3
"""
RustChain Testnet Faucet
A simple Flask web application that dispenses test RTC tokens.
Features:
- IP-based rate limiting
- SQLite backend for tracking
- Simple HTML form for requesting tokens
"""
import sqlite3
import time
import os
from datetime import datetime, timedelta
from flask import Flask, request, jsonify, render_template_string
app = Flask(__name__)
DATABASE = 'faucet.db'
# Rate limiting settings (per 24 hours)
MAX_DRIP_AMOUNT = 0.5 # RTC
RATE_LIMIT_HOURS = 24
def init_db():
"""Initialize the SQLite database."""
conn = sqlite3.connect(DATABASE)
c = conn.cursor()
c.execute('''
CREATE TABLE IF NOT EXISTS drip_requests (
id INTEGER PRIMARY KEY AUTOINCREMENT,
wallet TEXT NOT NULL,
ip_address TEXT NOT NULL,
amount REAL NOT NULL,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)
''')
conn.commit()
conn.close()
def get_client_ip():
"""Get client IP address from request."""
if request.headers.get('X-Forwarded-For'):
return request.headers.get('X-Forwarded-For').split(',')[0].strip()
return request.remote_addr or '127.0.0.1'
def get_last_drip_time(ip_address):
"""Get the last time this IP requested a drip."""
conn = sqlite3.connect(DATABASE)
c = conn.cursor()
c.execute('''
SELECT timestamp FROM drip_requests
WHERE ip_address = ?
ORDER BY timestamp DESC
LIMIT 1
''', (ip_address,))
result = c.fetchone()
conn.close()
return result[0] if result else None
def can_drip(ip_address):
"""Check if the IP can request a drip (rate limiting)."""
last_time = get_last_drip_time(ip_address)
if not last_time:
return True
last_drip = datetime.fromisoformat(last_time.replace('Z', '+00:00'))
now = datetime.now(last_drip.tzinfo)
hours_since = (now - last_drip).total_seconds() / 3600
return hours_since >= RATE_LIMIT_HOURS
def get_next_available(ip_address):
"""Get the next available time for this IP."""
last_time = get_last_drip_time(ip_address)
if not last_time:
return None
last_drip = datetime.fromisoformat(last_time.replace('Z', '+00:00'))
next_available = last_drip + timedelta(hours=RATE_LIMIT_HOURS)
now = datetime.now(last_drip.tzinfo)
if next_available > now:
return next_available.isoformat()
return None
def record_drip(wallet, ip_address, amount):
"""Record a drip request to the database."""
conn = sqlite3.connect(DATABASE)
c = conn.cursor()
c.execute('''
INSERT INTO drip_requests (wallet, ip_address, amount)
VALUES (?, ?, ?)
''', (wallet, ip_address, amount))
conn.commit()
conn.close()
# HTML Template
HTML_TEMPLATE = """
<!DOCTYPE html>
<html>
<head>
<title>RustChain Testnet Faucet</title>
<style>
body {
font-family: 'Courier New', monospace;
max-width: 600px;
margin: 50px auto;
padding: 20px;
background: #0a0a0a;
color: #00ff00;
}
h1 {
color: #00ff00;
border-bottom: 2px solid #00ff00;
padding-bottom: 10px;
text-align: center;
}
.form-section {
background: #1a1a1a;
border: 1px solid #00ff00;
padding: 20px;
margin: 20px 0;
border-radius: 5px;
}
input[type="text"] {
width: 100%;
padding: 12px;
margin: 10px 0;
background: #002200;
color: #00ff00;
border: 1px solid #00ff00;
border-radius: 3px;
font-family: 'Courier New', monospace;
font-size: 16px;
box-sizing: border-box;
}
button {
width: 100%;
padding: 15px;
background: #00aa00;
color: #000;
border: none;
border-radius: 3px;
font-size: 16px;
font-weight: bold;
cursor: pointer;
transition: all 0.3s;
}
button:hover {
background: #00ff00;
}
button:disabled {
background: #333;
color: #666;
cursor: not-allowed;
}
.result {
padding: 15px;
margin: 15px 0;
border-radius: 3px;
}
.success {
background: #002200;
border: 1px solid #00ff00;
color: #00ff00;
}
.error {
background: #220000;
border: 1px solid #ff0000;
color: #ff0000;
}
.info {
background: #000022;
border: 1px solid #0000ff;
color: #6666ff;
}
.note {
color: #888;
font-size: 12px;
margin-top: 10px;
}
</style>
</head>
<body>
<h1>💧 RustChain Testnet Faucet</h1>
<div class="form-section">
<p>Get free test RTC tokens for development.</p>
<form id="faucetForm">
<label for="wallet">Your RTC Wallet Address:</label>
<input type="text" id="wallet" name="wallet" placeholder="0x..." required>
<button type="submit" id="submitBtn">Get Test RTC</button>
</form>
<div id="result"></div>
</div>
<div class="note">
<p><strong>Rate Limit:</strong> {{ rate_limit }} RTC per {{ hours }} hours per IP</p>
<p><strong>Network:</strong> RustChain Testnet</p>
</div>
<script>
const form = document.getElementById('faucetForm');
const result = document.getElementById('result');
const submitBtn = document.getElementById('submitBtn');
form.addEventListener('submit', async (e) => {
e.preventDefault();
submitBtn.disabled = true;
submitBtn.textContent = 'Requesting...';
result.innerHTML = '';
const wallet = document.getElementById('wallet').value;
try {
const response = await fetch('/faucet/drip', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({wallet})
});
const data = await response.json();
if (data.ok) {
result.innerHTML = '<div class="result success">✅ Success! Sent ' + data.amount + ' RTC to ' + wallet + '</div>';
if (data.next_available) {
result.innerHTML += '<div class="result info">Next available: ' + data.next_available + '</div>';
}
} else {
result.innerHTML = '<div class="result error">❌ ' + data.error + '</div>';
if (data.next_available) {
result.innerHTML += '<div class="result info">Next available: ' + data.next_available + '</div>';
}
}
} catch (err) {
result.innerHTML = '<div class="result error">❌ Error: ' + err.message + '</div>';
}
submitBtn.disabled = false;
submitBtn.textContent = 'Get Test RTC';
});
</script>
</body>
</html>
"""
@app.route('/')
def index():
"""Serve the faucet homepage."""
return render_template_string(HTML_TEMPLATE, rate_limit=MAX_DRIP_AMOUNT, hours=RATE_LIMIT_HOURS)
@app.route('/faucet')
def faucet_page():
"""Serve the faucet page (alias for index)."""
return render_template_string(HTML_TEMPLATE, rate_limit=MAX_DRIP_AMOUNT, hours=RATE_LIMIT_HOURS)
@app.route('/faucet/drip', methods=['POST'])
def drip():
"""
Handle drip requests.
Request body:
{"wallet": "0x..."}
Response:
{"ok": true, "amount": 0.5, "next_available": "2026-03-08T12:00:00Z"}
"""
data = request.get_json()
if not data or 'wallet' not in data:
return jsonify({'ok': False, 'error': 'Wallet address required'}), 400
wallet = data['wallet'].strip()
# Basic wallet validation (should start with 0x and be reasonably long)
if not wallet.startswith('0x') or len(wallet) < 10:
return jsonify({'ok': False, 'error': 'Invalid wallet address'}), 400
ip = get_client_ip()
# Check rate limit
if not can_drip(ip):
next_available = get_next_available(ip)
return jsonify({
'ok': False,
'error': 'Rate limit exceeded',
'next_available': next_available
}), 429
# Record the drip (in production, this would actually transfer tokens)
# For now, we simulate the drip
amount = MAX_DRIP_AMOUNT
record_drip(wallet, ip, amount)
return jsonify({
'ok': True,
'amount': amount,
'wallet': wallet,
'next_available': (datetime.now() + timedelta(hours=RATE_LIMIT_HOURS)).isoformat()
})
if __name__ == '__main__':
# Initialize database
if not os.path.exists(DATABASE):
init_db()
else:
init_db() # Ensure table exists
# Run the server
print("Starting RustChain Faucet on http://0.0.0.0:8090/faucet")
app.run(host='0.0.0.0', port=8090, debug=False)