-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
277 lines (233 loc) · 9.08 KB
/
server.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
const { Worker } = require('worker_threads');
const express = require('express');
const bodyParser = require('body-parser')
const cors = require('cors')
const axios = require('axios');
const https = require('https');
const fs = require('fs');
const path = require('path');
const dotenv = require('dotenv');
dotenv.config();
const {verify} = require('hcaptcha');
const hc_secret = process.env.HCAPTCHA_SECRET;
const useHttps = false;
const LiteWallet = require('./zingolib-wrapper/zingo_litewallet');
const { TxBuilder } = require('./zingolib-wrapper/utils/utils');
const { join } = require('path');
const app = express();
const port = 2653;
// Set faucet payout in decimal ZEC
const u_payout = 0.0005;
const z_payout = 0.0004;
const t_payout = 0.0003;
const memo = "Thanks for using ZecFaucet.com"
// Queue for the faucet payout
let queue = [];
const waitlist = [];
const waittime = 120; // Time in minuts before next claim
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json()) // to convert the request into JSON
app.use(cors()) // to allow cross origin requests
app.set("trust proxy", true);
// Serve static files from the 'dist' directory
// app.use(express.static(path.join(__dirname, 'dist')));
// Setup lib
const lwd = "https://mainnet.lightwalletd.com:9067/";
const zingo = new LiteWallet(lwd, "main", false);
let syncing = true;
let logStream;
// Initialize zingolib
zingo.init().then(async () => {
// Start the logger
logStream = fs.createWriteStream("log.txt", {flags:'a'});
// Send payments every 2 minutes
const timerID = setInterval(async() => {
const sendProgress = zingo.inSend;
const notes = await zingo.fetchNotes();
let pending = notes.pending_orchard_notes.length > 0 || notes.pending_sapling_notes.length > 0 || notes.pending_utxos.length > 0;
syncing = zingo.inRefresh;
console.log(`Queue: ${queue.length} | Sending: ${sendProgress} | Pending: ${pending} | Syncing: ${syncing}`);
if(queue.length > 0 && !sendProgress && !pending && !syncing) {
const tmpQueue = queue.slice();
zingo.sendTransaction(tmpQueue).then((txid)=>{
console.log(txid);
logStream.write(`txid: ${txid}\n============\n`);
// clear the queue
tmpQueue.forEach((el) => {
queue.splice(queue.indexOf(el), 1);
});
}).catch((err) => {
console.log(err);
});
}
// Clear waitlist for users that waited more than waittime
const timeStamp = new Date();
waitlist.forEach((el) => {
const oldTimeStamp = el.timestamp;
const nextClaim = waittime - ((timeStamp - oldTimeStamp) / (1000*60));
if(nextClaim < 0) {
waitlist.splice(waitlist.indexOf(el), 1);
}
});
console.log(`Waitlist length: ${waitlist.length}`);
}, 2 * 60 * 1000);
});
// Serve the Vue.js app
// app.get('/', (req, res) => {
// res.sendFile(path.join(__dirname, 'dist', 'index.html'));
// });
app.get ('/payout', (req, res) =>{
res.json({
u_pay: u_payout,
z_pay: z_payout,
t_pay: t_payout
});
});
app.get('/donate', async (req, res) => {
const addr = await zingo.fetchAllAddresses();
res.send(addr[0].address);
});
app.get('/balance', async (req, res) => {
// If syncing, return balance of 0.0
const ss = await zingo.doSyncStatus();
syncing = ss.in_progress;
if(syncing) res.send('0.0');
else {
// Fetch total balance and return
// const bal = await zingo.fetchTotalBalance();
const bal = zingo.totalBalance;
res.send(`${bal.total.toFixed(8)}`);
}
});
app.get('/log', async (req, res) => {
res.sendFile(path.join(__dirname, 'log.txt'));
});
app.get('/txns', async (req, res) => {
// await zingo.fetchTandZandOTransactionsSummaries();
const txList = zingo.transactionsList.filter((t) => t.type == "Received")
res.json(txList.slice(0,10));
});
app.get('/stats', async (req, res) => {
await zingo.fetchTandZandOTransactionsSummaries();
const txList = zingo.transactionsList.filter((t) => t.type == "Sent")
const totalSent = txList.reduce((acc, el) => acc + el.txDetails[0].amount, 0);
const totalClaims = txList.length;
const result = {
sent: totalSent.toFixed(8),
claims: totalClaims
}
res.json(result);
});
app.post('/add', async (req, res) => {
const ss = await zingo.doSyncStatus();
syncing = ss.in_progress;
if(syncing) res.send('syncing');
else {
// CHeck if it is a valid address
const addr = req.body.address;
const validAddr = await zingo.parseAddress(addr);
const token = req.body.token;
const validToken = await verify(hc_secret, token);
if(!validToken.success) {
res.send("invalid-token");
return;
}
else if(validAddr) {
// First, check if user can claim faucet
const userIp = req.ip; // TODO improve remote IP fetching
const userFp = req.body.fingerprint;
const timeStamp = new Date();
// Check if user is using proxy/vpn
const ipAddress = userIp.match(/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/)[0];
try {
const proxyOrVpn = await axios.get(`http://check.getipintel.net/check.php?ip=${ipAddress}&contact=james.j.katz@protonmail.com`);
console.log("User blocked!");
if(proxyOrVpn.data >= 0.95) {
logStream.write(`${timeStamp .toISOString()} | Proxy or VPN blocked: ${ipAddress}\n\n`);
res.send('invalid-token');
return;
}
}
catch(err) {
console.log("Couldn't check user ip for proxy or vpn.");
}
const user = waitlist.filter(el => (el.ip === userIp || el.fp === userFp || el.address === addr));
if(user.length > 0) {
const oldTimeStamp = user[0].timestamp;
const nextClaim = waittime - ((timeStamp - oldTimeStamp) / (1000*60));
if(nextClaim < 0) {
waitlist.splice(waitlist.indexOf(user[0]), 1);
}
else {
res.send(`greedy ${ Math.ceil(nextClaim) }`);
return;
}
}
// Also block sequential IP addresses based on the first 2 octets
let ipOctet = userIp.slice(0,15);
let seqIp = waitlist.filter((el) => el.ip.startsWith(ipOctet));
if(seqIp.length > 0) {
logStream.write(`${timeStamp .toISOString()} | Sequential IP blocked: ${ipAddress}\n\n`);
res.send('invalid-token');
return;
}
const pay = validAddr.address_kind === 'unified' ? u_payout.toFixed(4) : validAddr.address_kind === 'sapling' ? z_payout.toFixed(4) : 0;
// Reject if it's transparent address
if(pay == 0) {
res.send("transparent");
return;
}
// Construct transaction
const tx = new TxBuilder()
.setRecipient(addr)
.setAmount(pay)
.setMemo(memo);
// Get sendJson
const sendJson = tx.getSendJSON();
// Check if faucet has enough bals
const bal = await zingo.fetchTotalBalance();
const fee = await zingo.getDefaultFee();
const queueSum = queue.map((el) => el.amount).reduce((acc, curr) => acc + curr, fee);
if(queueSum + sendJson[0].amount > (bal.total * 10**8)) {
res.send('faucet-dry');
return;
}
// Add tx to the queue
queue.push(sendJson[0]);
console.log("New address added to the queue");
// Add user IP and browser firgerprint to the wait list
waitlist.push({
address: addr,
ip: userIp,
fp: userFp,
timestamp: timeStamp
});
// Add this claim to log file
logStream.write(`${timeStamp .toISOString()} | IP: ${userIp} | Fingerprint: ${userFp} | Address: ${addr}\n\n`);
res.json({
success: 'success',
amount: pay
});
}
else res.send('invalid');
}
});
if(useHttps) {
const options = {
key: fs.readFileSync('path_to_key.pem'),
cert: fs.readFileSync('path_to_cert.pem')
};
https.createServer(options, app).listen(port);
console.log(`App listening at https://localhost:${port}`)
}
else {
app.listen(port, () => {
console.log(`App listening at http://localhost:${port}`)
});
}
process.on('SIGINT', async () => {
console.log("Safely shutdown zingolib");
logStream.end();
await zingo.deinitialize();
process.exit();
});