-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
564 lines (508 loc) · 16.4 KB
/
index.js
File metadata and controls
564 lines (508 loc) · 16.4 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
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
const AWS = require('aws-sdk');
const nano_client = require('@nanobox/nano-client');
const { NANO } = require('@nanobox/nano-client/dist/models');
const axios = require('axios');
const FormData = require('form-data');
const { HttpResponse } = require('aws-sdk');
require('dotenv').config();
const FAUCET_PUBLIC_KEY = process.env.FAUCET_PUBLIC_KEY,
FAUCET_PRIVATE_KEY = process.env.FAUCET_PRIVATE_KEY,
FAUCET_ADDRESS = process.env.FAUCET_ADDRESS,
CAPTCHA_SECRET = process.env.CAPTCHA_SECRET;
const DDB_WALLET_TABLE_NAME = 'TryNanoWallets';
const DDB_FAUCET_IP_HISTORY_TABLE_NAME = 'FaucetIpHistory';
/*
Must wait 1 hour after last wallet usage until eligible to return to
faucet.
Ensures that funds are not returned to faucet while user is still
using the wallet.
*/
const RETURN_TO_FAUCET_EPOCH_MS = 3600000;
const WALLET_EXPIRATION_TIME_SECONDS = 259200; // 72 hours
const FAUCET_IP_HISTORY_EXPIRATION_TIME_SECONDS = 172800; // 48 hours
const FAUCET_THROTTLE_DURATION_SECONDS = 600; // 10 minutes
const FAUCET_INVOKE_LIMIT = 10;
const FAUCET_RESET_TIME_HOURS = 24;
const FAUCET_PERCENT = 0.000125;
const c = new nano_client.NanoClient({
url: 'https://proxy.powernode.cc/proxy',
});
const ddb = new AWS.DynamoDB({
region: 'us-west-1',
});
const apiMapping = {
'/api/createWallets': createWallets,
'/api/send': send,
'/api/receive': receive,
'/api/getFromFaucet': getFromFaucet,
'/api/getFaucetInfo': getFaucetInfo,
};
/**
* Entry-point for the NanoFaucet AWS Lambda function. Checks recaptcha token and reroutes to appropriate api method based off the requested path.
*
* @param {APIGatewayProxyEvent} event the API Gateway event data
* @returns {HttpResponse} Http response object
*/
exports.handler = async function (event) {
try {
if (event.requestContext.http.method === 'OPTIONS') {
return response(200, {});
}
const error = validateState();
if (error) {
return response(500, { error: error });
}
const token = event.headers['x-recaptcha'];
const captchaResponse = token ? await validateCaptcha(token) : undefined;
if (!(captchaResponse && captchaResponse.success)) {
return response(403, { error: 'access denied: invalid recaptcha token' });
}
const path = event.rawPath;
const params = event.body ? JSON.parse(event.body) : {};
const apiMethod = apiMapping[path];
if (!apiMethod) {
return response(404, 'not found');
}
return await apiMethod(event, params);
} catch (err) {
console.log(`caught error: ${err.message}`);
return response(500, { error: 'Server error, please try again later!' });
}
};
/**
* Generates two brand new TryNano wallets and logs the wallet info to DynamoDB.
*
* @param {APIGatewayProxyEvent} _event the API Gateway event data
* @param {Object} _params the http request body data
* @returns a list of two generated wallets with their corresponding address, privateKey, and balance (starts at 0)
*/
async function createWallets(_event, _params) {
let wallets = [];
for (let i = 0; i < 2; i++) {
const wallet = c.generateWallet().accounts[0];
await ddb
.putItem({
TableName: DDB_WALLET_TABLE_NAME,
Item: AWS.DynamoDB.Converter.marshall({
walletID: wallet.address,
expirationTs:
Math.round(Date.now() / 1000) + WALLET_EXPIRATION_TIME_SECONDS,
privateKey: wallet.privateKey,
publicKey: wallet.publicKey,
balance: 0,
returnToFaucetEpoch: Date.now() + RETURN_TO_FAUCET_EPOCH_MS,
}),
})
.promise();
wallets.push({
address: wallet.address,
privateKey: wallet.privateKey,
balance: { raw: '0' },
});
}
return response(200, {
wallets: wallets,
});
}
/**
* Sends either the max account balance or a specified amount of nano from one nano account to another.
*
* @param {APIGatewayProxyEvent} _event the API Gateway event data
* @param {Object} params the http request body data
* @returns the sender address, updated sender account balance , and starting timestamp of the send transaction
*/
async function send(_event, params) {
const acc = await loadNanoAccountFromDB(params.fromAddress);
if (!acc) {
return response(400, {
error: `${params.fromAddress} is an invalid wallet address`,
});
}
// Extra security measure to prove the wallet was generated by the user sending the nano
if (params.privateKey !== acc.privateKey) {
return response(400, {
error: `invalid private key for wallet address ${params.fromAddress}`,
});
}
const accountInfo = await c.updateWalletAccount({
address: acc.address,
publicKey: acc.publicKey,
privateKey: acc.privateKey,
});
if (!accountInfo) {
return response(500, {
error: `unable to retrieve account info for address sending Nano`,
});
}
if (accountInfo.balance.asNumber === 0) {
return response(400, {
error: `wallet balance is zero`,
});
}
const ts = Date.now();
let res;
if (params.amount) {
if (params.amount.asString === '0') {
return response(400, {
error: 'Unable to send zero amount of Nano',
});
}
res = await c.send(acc, params.toAddress, params.amount);
} else {
res = await c.sendMax(acc, params.toAddress);
}
if (!res) {
return response(500, {
error: `unable to send from ${params.fromAddress} to ${params.toAddress}`,
});
}
// update balance in DynamoDB
const updatedBalance = res.balance.asString;
await updateNanoBalanceInDB(params.fromAddress, updatedBalance);
return response(200, {
address: params.fromAddress,
balance: updatedBalance,
sendTimestamp: ts,
});
}
/**
* Receives all pending transactions for a given nano account.
*
* @param {APIGatewayProxyEvent} _event the API Gateway event data
* @param {Object} params the http request body data
* @returns the address, updated account balance, and resolved count for the given nano account.
*/
async function receive(_event, params) {
const acc = await loadNanoAccountFromDB(params.receiveAddress);
if (!acc) {
return response(400, { error: 'invalid wallet address' });
}
const res = await c.update(acc);
// update balance in DynamoDB after receive
const updatedBalance = res.account.balance.asString;
await updateNanoBalanceInDB(params.receiveAddress, updatedBalance);
return response(200, {
address: params.receiveAddress,
balance: updatedBalance,
resolvedCount: res.resolvedCount,
});
}
/**
* Sends a percentage of nano from the TryNano Faucet to the provided nano account.
*
* @param {APIGatewayProxyEvent} _event the API Gateway event data
* @param {Object} params the http request body data
* @returns the faucet address and the updated faucet balance
*/
async function getFromFaucet(event, params) {
if (process.env.DISABLE_FAUCET === 'true') {
// disable faucet until network is stable again (i.e. no more unconfirmed blocks in faucet account)
return response(500, {
error: `TryNano Faucet has been disabled until network is fully resolved. Please use another option.`,
});
}
const acc = await loadNanoAccountFromDB(params.toAddress);
if (!acc) {
return response(400, {
error: `${params.toAddress} is an invalid wallet address`,
});
}
// Extra security measure to prove the wallet was generated by the user requesting nano from the faucet
if (params.privateKey !== acc.privateKey) {
return response(400, {
error: `invalid private key for wallet address ${params.toAddress}`,
});
}
// Reject the user's faucet request if not eligible
const faucetEligibilityStatus = await checkFaucetEligibility(
event.requestContext.http.sourceIp
);
if (!faucetEligibilityStatus.isEligible) {
return response(400, {
error: faucetEligibilityStatus.reason,
});
}
// Get Faucet account info to check things like the current balance
const faucetAccountInfo = await c.updateWalletAccount({
address: FAUCET_ADDRESS,
publicKey: FAUCET_PUBLIC_KEY,
privateKey: FAUCET_PRIVATE_KEY,
});
if (!faucetAccountInfo) {
return response(500, { error: `unable to retrieve faucet account info` });
}
// Make sure there's sufficient funds in the faucet
if (faucetAccountInfo.balance.asNumber === 0) {
return response(400, { error: `Faucet balance is zero` });
}
const res = await c.send(
faucetAccountInfo,
acc.address,
NANO.fromNumber(faucetAccountInfo.balance.asNumber * FAUCET_PERCENT)
);
if (!res) {
return response(500, {
error: `unable to send from ${FAUCET_ADDRESS} to ${acc.address}`,
});
}
return response(200, {
address: FAUCET_ADDRESS,
balance: res.balance.asNumber,
});
}
/**
* Gets the current faucet balance + payout percentage.
*
* @param {APIGatewayProxyEvent} _event the API Gateway event data
* @param {Object} _params the http request body data
* @returns current faucet balance and payout percentage (decimal)
*/
async function getFaucetInfo(_event, _params) {
// Get Faucet account info to check things like the current balance
const accountInfo = await c.updateWalletAccount({
address: FAUCET_ADDRESS,
publicKey: FAUCET_PUBLIC_KEY,
privateKey: FAUCET_PRIVATE_KEY,
});
if (!accountInfo) {
return response(500, { error: `unable to retrieve faucet account info` });
}
return response(200, {
balance: accountInfo.balance.asNumber,
payout: FAUCET_PERCENT,
});
}
/**
* Constructs an HttpResponse object with the appropriate CORS headers.
*
* @param {HttpStatus} code HTTP response status code
* @param {Object} body response body
* @returns {HttpResponse} HTTP response object
*/
function response(code, body) {
return {
statusCode: code,
headers: {
'Access-Control-Allow-Headers': 'Content-Type, X-Recaptcha, X-Api-Key',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'OPTIONS,POST,GET',
},
body: JSON.stringify(body),
};
}
/**
* Loads a TryNano generated wallet from DynamoDB.
*
* @param {string} address the address of the nano account
* @returns The corresponding Nano account info: walletID, publicKey, and privateKey
*/
async function loadNanoAccountFromDB(address) {
const res = await ddb
.getItem({
TableName: DDB_WALLET_TABLE_NAME,
Key: {
walletID: {
S: address,
},
},
})
.promise();
if (!res.Item) {
return null;
}
const wallet = AWS.DynamoDB.Converter.unmarshall(res.Item);
const nanoAccount = {
address: wallet.walletID,
publicKey: wallet.publicKey,
privateKey: wallet.privateKey,
};
return nanoAccount;
}
/**
* Updates the balance for a TryNano wallet in DynamoDB.
* Also update the returnToFaucetEpoch field since we've used the wallet.
*
* @param {string} address the address of the nano account
* @param {string} updatedBalance the updated wallet balance
*/
async function updateNanoBalanceInDB(address, updatedBalance) {
await ddb
.updateItem({
TableName: DDB_WALLET_TABLE_NAME,
Key: {
walletID: {
S: address,
},
},
UpdateExpression: 'SET balance = :u, returnToFaucetEpoch = :r',
ExpressionAttributeValues: {
':u': {
N: updatedBalance,
},
':r': {
N: (Date.now() + RETURN_TO_FAUCET_EPOCH_MS).toString(),
},
},
ReturnValues: 'UPDATED_NEW',
})
.promise();
}
/**
* Check the user's eligibility to use the faucet.
*
* @param {string} ipAddress the user's IP address
* @returns {boolean} is the user eligible to use the faucet or not
*/
async function checkFaucetEligibility(ipAddress) {
const ts = Date.now();
const expirationTs =
Math.round(ts / 1000) + FAUCET_IP_HISTORY_EXPIRATION_TIME_SECONDS;
const res = await ddb
.getItem({
TableName: DDB_FAUCET_IP_HISTORY_TABLE_NAME,
Key: {
ipAddress: {
S: ipAddress,
},
},
})
.promise();
if (!res.Item) {
await ddb
.putItem({
TableName: DDB_FAUCET_IP_HISTORY_TABLE_NAME,
Item: AWS.DynamoDB.Converter.marshall({
ipAddress: ipAddress,
numFaucetInvocations: 1,
lastUsedTs: ts,
expirationTs: expirationTs,
}),
})
.promise();
return {
isEligible: true,
};
}
const ipHistoryData = AWS.DynamoDB.Converter.unmarshall(res.Item);
const currNumInvokes = ipHistoryData.numFaucetInvocations + 1;
const numSecondsSinceLastInvoke = (ts - ipHistoryData.lastUsedTs) / 1000;
const numHoursSinceLastInvoke = numSecondsSinceLastInvoke / 3600;
/*
If this IP Address has:
(a) Invoked the faucet in the past 10 minutes, or
(b) Invoked the faucet more than 10 times in the past 24 hours
then reject the request.
*/
if (numSecondsSinceLastInvoke < FAUCET_THROTTLE_DURATION_SECONDS) {
return {
isEligible: false,
reason:
'Faucet was used within the past 10 minutes, please try again later.',
};
}
if (
currNumInvokes > FAUCET_INVOKE_LIMIT &&
numHoursSinceLastInvoke < FAUCET_RESET_TIME_HOURS
) {
return {
isEligible: false,
reason:
'You have reached the max number of faucet uses, please try again after 24 hours.',
};
}
await ddb
.updateItem({
TableName: DDB_FAUCET_IP_HISTORY_TABLE_NAME,
Key: {
ipAddress: {
S: ipAddress,
},
},
UpdateExpression:
'SET numFaucetInvocations = :n, lastUsedTs = :l, expirationTs = :e',
ExpressionAttributeValues: {
':n': {
N: numHoursSinceLastInvoke < 24 ? currNumInvokes.toString() : '1',
},
':l': { N: ts.toString() },
':e': { N: expirationTs.toString() },
},
ReturnValues: 'UPDATED_NEW',
})
.promise();
return {
isEligible: true,
};
}
/**
* Validates the recaptcha token attached to the request header.
*
* @param {string} token Google ReCaptchaV3 token
*/
async function validateCaptcha(token) {
const fd = new FormData();
fd.append('secret', CAPTCHA_SECRET);
fd.append('response', token);
const res = await axios.post(
'https://www.google.com/recaptcha/api/siteverify',
fd,
{
headers: fd.getHeaders(),
}
);
return {
success: res.data.success,
errors: res.data['error-codes'],
};
}
/**
* Ensures all required environment variables are present.
*
* @returns {string} Error message
*/
function validateState() {
if (!FAUCET_ADDRESS) {
return 'ADDRESS key missing from .env - you must fix';
} else if (!FAUCET_PUBLIC_KEY) {
return 'FAUCET_PUBLIC_KEY key missing from .env - you must fix';
} else if (!FAUCET_PRIVATE_KEY) {
return 'FAUCET_PRIVATE_KEY key missing from .env - you must fix';
} else if (!CAPTCHA_SECRET) {
return 'CAPTCHA_SECRET key missing from .env - you must fix';
}
return null;
}
/*
Runs a lambda server locally
*/
if (process.env.EXEC_LOCAL) {
const path = require('path');
const lambdaLocal = require('lambda-local');
const express = require('express');
var cors = require('cors');
var bodyParser = require('body-parser');
const app = express();
// Process body as plain text as this is
// how it would come from API Gateway
app.use(express.text());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
app.options('*', cors());
app.use('/lambda', async (req, res) => {
const result = await lambdaLocal.execute({
lambdaPath: path.join(__dirname, 'index'),
lambdaHandler: 'handler',
envfile: path.join(__dirname, '.env'),
event: {
headers: req.headers, // Pass on request headers
body: req.body, // Pass on request body
rawPath: req.url, // Pass on requested resource url
},
timeoutMs: 30000,
});
// Respond to HTTP request
res.status(result.statusCode).set(result.headers).end(result.body);
});
app.listen(3000, () => console.log('listening on port: 3000'));
}