-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
379 lines (340 loc) · 10.3 KB
/
index.js
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
require("dotenv").config();
const fs = require("fs");
const path = require("path");
const express = require("express");
const bodyParser = require("body-parser");
const Client = require("bitcoin-core");
const cors = require("cors");
const sqlite3 = require("sqlite3").verbose();
const rateLimit = require("express-rate-limit");
const basicAuth = require("express-basic-auth");
const {
API_PORT,
BTC_NODE_URL,
BTC_NODE_PORT,
BTC_USER,
BTC_PASS,
BTC_WALLET,
BTC_AMOUNT,
FRONTEND_URL,
CAPTCHA_SECRET,
CAPTCHA_KEY,
GITHUB_LINK,
TWITTER_LINK,
AUTH_USERNAME,
AUTH_PASSWORD,
} = process.env;
let authMiddleware;
if (AUTH_USERNAME && AUTH_PASSWORD) {
authMiddleware = basicAuth({
users: { [AUTH_USERNAME]: AUTH_PASSWORD },
challenge: true,
});
} else {
authMiddleware = (req, res, next) => next();
}
const limiter = rateLimit({
windowMs: 24 * 60 * 60 * 1000,
max: 3,
message: {
success: false,
error: "Too many requests, please try again later.",
},
});
const app = express();
app.set("trust proxy", true);
const allowedOrigins = (FRONTEND_URL || "http://localhost:3000").split(",");
const corsOptions = {
origin: function (origin, callback) {
if (allowedOrigins.indexOf(origin) !== -1) {
callback(null, true);
} else {
callback(null, false);
}
},
};
app.use(cors(corsOptions));
app.use(bodyParser.json());
const db = new sqlite3.Database("./faucet.db", (err) => {
if (err) {
console.error("Error opening database:", err.message);
} else {
console.log("Connected to SQLite database.");
db.run(
`CREATE TABLE IF NOT EXISTS transactions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
address TEXT NOT NULL,
amount REAL NOT NULL,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
);`,
(err) => {
if (err)
console.error("Error creating transactions table:", err.message);
},
);
db.run(
`CREATE TABLE IF NOT EXISTS queue (
id INTEGER PRIMARY KEY AUTOINCREMENT,
address TEXT NOT NULL,
txid TEXT,
status TEXT DEFAULT 'pending',
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
);`,
(err) => {
if (err) console.error("Error creating queue table:", err.message);
},
);
}
});
const client = new Client({
network: "testnet",
host: BTC_NODE_URL.replace(/^http(s)?:\/\//, ""),
port: BTC_NODE_PORT,
username: BTC_USER,
password: BTC_PASS,
allowDefaultWallet: true,
wallet: BTC_WALLET,
});
app.use(authMiddleware);
app.get("/", (req, res) => {
const indexHtmlPath = path.join(__dirname, "public", "index.html");
fs.readFile(indexHtmlPath, "utf8", (err, data) => {
if (err) {
console.error("Error reading index.html:", err.message);
return res.status(500).send("Error loading the page.");
}
const modifiedHtml = data
.replace("__API_BASE_URL__", FRONTEND_URL)
.replace("__GITHUB_LINK__", GITHUB_LINK)
.replace("__BTC_AMOUNT__", BTC_AMOUNT)
.replace("__CAPTCHA_KEY__", CAPTCHA_KEY)
.replace("__TWITTER_LINK__", TWITTER_LINK);
res.send(modifiedHtml);
});
});
app.use(express.static(path.join(__dirname, "public")));
app.use("/sendbtc", limiter, authMiddleware);
app.post("/sendbtc", async (req, res) => {
const { recaptchaToken, address } = req.body;
if (req.body.email) {
return res.status(400).json({ success: false, error: "Fuck off" });
}
if (!address) {
return res.status(400).json({ success: false, error: "Invalid address." });
}
if (!recaptchaToken) {
return res
.status(400)
.json({ success: false, error: "Captcha is required." });
}
// Verify reCAPTCHA
try {
const captchaResponse = await fetch(
`https://challenges.cloudflare.com/turnstile/v0/siteverify`,
{
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: `secret=${CAPTCHA_SECRET}&response=${recaptchaToken}`,
},
);
const captchaResult = await captchaResponse.json();
if (!captchaResult.success) {
return res.status(403).json({ success: false, error: "Captcha failed." });
}
} catch (error) {
console.error("Error verifying reCAPTCHA:", error.message);
return res
.status(500)
.json({ success: false, error: "Captcha verification failed." });
}
db.run(`INSERT INTO queue (address) VALUES (?)`, [address], function (err) {
if (err) {
console.error("Error inserting into queue:", err.message);
return res
.status(500)
.json({ success: false, error: "Internal server error." });
}
const newRequestId = this.lastID;
db.all(
`SELECT id FROM queue WHERE status='pending' ORDER BY id ASC`,
[],
(err, rows) => {
if (err) {
console.error("Error getting queue position:", err.message);
return res
.status(500)
.json({ success: false, error: "Internal server error." });
}
const ids = rows.map((r) => r.id);
const position = ids.indexOf(newRequestId) + 1;
res.json({
success: true,
message: "Your request is added to the queue! ;)",
queueId: newRequestId,
position,
});
},
);
});
});
app.use("/transactions", authMiddleware);
app.get("/transactions", (req, res) => {
const limit = parseInt(req.query.limit, 10) || null;
if (limit > 10) limit = 10;
let query = `SELECT * FROM transactions ORDER BY timestamp DESC`;
if (limit) {
query += ` LIMIT ?`;
}
db.all(query, limit ? [limit] : [], (err, rows) => {
if (err) {
console.error("Error retrieving transactions:", err.message);
res.status(500).json({ success: false, error: err.message });
} else {
res.json({ success: true, transactions: rows });
}
});
});
app.use("/queue-status", authMiddleware);
app.get("/queue-status", (req, res) => {
const { queueId } = req.query;
if (!queueId) {
return res.status(400).json({ success: false, error: "Missing queueId." });
}
db.get(`SELECT id, status FROM queue WHERE id=?`, [queueId], (err, row) => {
if (err) {
console.error("Error retrieving queue status:", err.message);
return res
.status(500)
.json({ success: false, error: "Internal server error." });
}
if (!row) {
return res.status(404).json({ success: false, error: "Not found." });
}
if (row.status === "pending") {
db.all(
`SELECT id FROM queue WHERE status='pending' ORDER BY id ASC`,
[],
(err, rows) => {
if (err) {
console.log(err);
return res
.status(500)
.json({ success: false, error: "Internal server error." });
}
const ids = rows.map((r) => r.id);
const position = ids.indexOf(row.id) + 1;
res.json({ success: true, status: "pending", position });
},
);
} else if (row.status === "completed") {
db.get(`SELECT txid FROM queue WHERE id=?`, [row.id], (err, txRow) => {
if (err) {
console.log(err);
return res
.status(500)
.json({ success: false, error: "Internal server error." });
}
res.json({
success: true,
status: "completed",
txid: txRow?.txid || null,
});
});
} else {
res.json({ success: true, status: row.status });
}
});
});
async function processQueue() {
db.all(
`SELECT * FROM queue WHERE status='pending' ORDER BY id ASC LIMIT 500`,
[],
async (err, rows) => {
if (err) {
console.error("Error fetching queue:", err.message);
return; // Try again next time
}
if (!rows || rows.length === 0) {
// No pending requests
return;
}
const sends = {};
const requestIds = rows.map((r) => r.id);
const amount = parseFloat(BTC_AMOUNT);
const validRows = [];
for (const row of rows) {
try {
const validateResult = await client.validateAddress(row.address);
if (validateResult.isvalid) {
sends[row.address] = amount;
validRows.push(row);
} else {
db.run(
`UPDATE queue SET status='invalid' WHERE id=?`,
[row.id],
(err) => {
if (err)
console.error("Error marking invalid address:", err.message);
},
);
}
} catch (validateError) {
console.error(
`Error validating address ${row.address}:`,
validateError.message,
);
db.run(
`UPDATE queue SET status='invalid' WHERE id=?`,
[row.id],
(err) => {
if (err)
console.error("Error marking invalid address:", err.message);
},
);
}
}
try {
const txid = await client.sendMany(
"",
sends,
1, // minconf
"", // comment
[], // subtractFeeFrom (list of addresses to subtract fee from)
true, // replaceable (RBF)
undefined, // conf_target
"unset", // estimate_mode
10, // fee_rate in sat/vB (this sets the fee rate)
);
// Update queue status to completed
const placeholders = requestIds.map(() => "?").join(",");
db.run(
`UPDATE queue SET status='completed', txid=? WHERE id IN (${placeholders})`,
[txid, ...requestIds],
(err) => {
if (err) {
console.error("Error updating queue for batch:", err.message);
}
},
);
const insertStmt = db.prepare(
`INSERT INTO transactions (address, amount) VALUES (?, ?)`,
);
for (const addr of Object.keys(sends)) {
insertStmt.run([addr, sends[addr]], (err) => {
if (err) console.error("Error inserting transaction:", err.message);
});
}
insertStmt.finalize();
console.log(
`Processed ${rows.length} queued requests in a single transaction: ${txid}`,
);
} catch (error) {
console.error("Error sending BTC from queue:", error.message);
}
},
);
}
setInterval(processQueue, 15000);
app.listen(API_PORT, () =>
console.log(`Faucet backend running on port ${API_PORT}`),
);