-
Notifications
You must be signed in to change notification settings - Fork 0
/
example-platform-api.js
348 lines (297 loc) · 9.01 KB
/
example-platform-api.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
const fs = require("fs");
const express = require("express");
const http = require("http");
const bodyParser = require("body-parser");
const pubKey = fs.readFileSync(`./keys/pub.pem`);
const crypto = require("crypto");
const HdAddGen = require("hdaddressgenerator");
const sigMan = require("./lib/signatureManager");
const serverPort = 7001;
const nonceTolerance = 1000;
const validationTypes = ["hash", "address"];
// Used to generate example responses.
const allConfigs = require("./config");
const coin = process.argv[2];
const config = allConfigs[coin];
if (config === undefined) {
console.log("Coin must be defined. Example: node example-platform.js BTC");
}
// This is expecting a file containing the wallet TX output from the listsinceblock RPC command and is used as example data to test the /validate/deposits route. It is looking for just the "transactions" array from this output.
// File content example: 'module.exports = [transactions array]
let exampleDeposits = [];
try {
exampleDeposits = require("./test/exampleDeposits.js"); // eslint-disable-line
} catch (e) {
console.log(
"No example deposit data supplied. Route validate/deposits will not work.",
e
);
}
(async () => {
const app = express();
// app.use(
// bodyParser.text({
// type(req) {
// return "text";
// },
// })
// );
// Validate signature on all requests.
app.use(async (req, res, next) => {
const sigResult = await sigMan.verify(
pubKey,
req.body,
req.headers.signature
);
if (sigResult) return next();
console.log(`Invalid signature.`);
res.status(403).send({
status: "fail",
message: "Invalid signature.",
});
return true;
});
// Validate nonce on all requests.
app.use(async (req, res, next) => {
const now = Date.now();
const { nonce } = JSON.parse(req.body);
if (nonce === undefined || nonce < now - nonceTolerance) {
console.log(
`Invalid nonce. Sent: ${nonce}, No later then: ${now - nonceTolerance}`
);
res.status(403).send({
status: "fail",
message: "Invalid nonce.",
});
return true;
}
return next();
});
// Log incoming request to console.
app.use(async (req, res, next) => {
console.log(req.originalUrl, req.body);
next();
});
// Add addresses.
app.post("/addresses", async (req, res) => {
// Here is where you would add the new addresses to your DB.
res.status(200).send({
status: "success",
message: "",
});
});
// Add deposits.
app.post("/deposits", async (req, res) => {
// Here is where you would add the new deposits to your DB.
res.status(200).send({
status: "success",
message: null,
data: null,
});
});
// Validate Deposit Addresses.
app.post("/validate/addresses", async (req, res) => {
let validRequest = true;
let reqData = {};
// This is basic validation for this example. In a live environment this should be replaced with something more robust.
try {
reqData = JSON.parse(req.body).data;
} catch (e) {
validRequest = false;
}
if (
reqData.xPubHash === undefined ||
reqData.validationType === undefined ||
reqData.xPubHash.length !== 64 ||
!validationTypes.includes(reqData.validationType) ||
Number.isNaN(reqData.startIndex) ||
Number.isNaN(reqData.endIndex)
) {
validRequest = false;
}
if (validRequest === false) {
res.status(400).send({
status: "fail",
message:
"Invalid request. Body must include data object with xPubHash, validationType, startIndex, and endIndex.",
data: null,
});
return;
}
// Request to validate deposit addresses by hash.
if (reqData.validationType === "hash") {
let addressHash = "";
try {
// This is where you would retrieve the deposit addresses from the DB associated with the submitted xPubHash and in the startIndex to endIndex range then you would build a validation string and get the HEX encoded SHA256 hash. Here we simulate this by generating the addresses directly and hashing them.
addressHash = await getAddressHash(
reqData.startIndex,
reqData.endIndex
);
} catch (e) {
console.log("Error generating address hash. Raw Error:", e);
res.status(500).send({
status: "fail",
message: "Unknown Error",
data: null,
});
return;
}
res.status(200).send({
status: "success",
message: null,
data: {
hash: addressHash,
},
});
}
if (reqData.validationType === "address") {
let addresses = {};
try {
addresses = await getAddresses(reqData.startIndex, reqData.endIndex);
} catch (e) {
console.log("Error generating addresses. Raw Error:", e);
res.status(500).send({
status: "fail",
message: "Unknown Error",
data: null,
});
return;
}
res.status(200).send({
status: "success",
message: null,
data: {
addresses,
},
});
}
});
// Validate Deposits.
app.post("/validate/deposits", async (req, res) => {
let validRequest = true;
let reqData = {};
// This is basic validation for this example. In a live environment this should be replaced with something more robust.
try {
reqData = JSON.parse(req.body).data;
} catch (e) {
validRequest = false;
}
if (
reqData.xPubHash === undefined ||
reqData.xPubHash.length !== 64 ||
Number.isNaN(reqData.startBlock) ||
Number.isNaN(reqData.endBlock)
) {
validRequest = false;
}
if (validRequest === false) {
res.status(400).send({
status: "fail",
message:
"Invalid request. Body must include data object with xPubHash, startBlock, and endBlock.",
data: null,
});
return;
}
let deposits = {};
try {
deposits = await getDeposits(reqData.startBlock, reqData.endBlock);
} catch (e) {
res.status(500).send({
status: "fail",
message: "Unknown Error",
data: null,
});
return;
}
res.status(200).send({
status: "success",
message: null,
data: {
deposits,
},
});
});
try {
http.createServer(app).listen(serverPort);
console.log(`Example Server running on port ${serverPort}`);
} catch (e) {
console.log(e);
}
})();
/**
* This is an EXAMPLE function for creating an address hash string.
* Addresses are generated here in a real API they would be retrieved from the DB.
* @param {num} startIndex Index to start generating addresses from.
* @param {num} numberToValidate Number of addresses to validate from index.
* @returns {str} Hash of deposit addresses in range.
*/
async function getAddressHash(startIndex, endIndex) {
const addGen = HdAddGen.withExtPub(
config.addressGen.xpub,
coin,
parseInt(config.addressGen.bip, 10)
);
const numberToValidate = endIndex - startIndex + 1;
const addresses = await addGen.generate(
parseInt(numberToValidate, 10),
parseInt(startIndex, 10)
);
let validationString = "";
addresses.forEach((address) => {
validationString += `${address.index},${address.address},`;
});
const validationHash = crypto
.createHash("sha256")
.update(validationString)
.digest("hex");
return validationHash;
}
/**
* This is an EXAMPLE function for formatting addresses for validation withing a certain range.
* In a real API these addresses would be returned from the DB.
* @param {num} startIndex
* @param {num} numberToValidate
* @returns {obj} deposit address object.
*/
async function getAddresses(startIndex, endIndex) {
const addGen = HdAddGen.withExtPub(
config.addressGen.xpub,
coin,
parseInt(config.addressGen.bip, 10)
);
const numberToValidate = endIndex - startIndex + 1;
const addresses = await addGen.generate(
parseInt(numberToValidate, 10),
parseInt(startIndex, 10)
);
const addObj = {};
let index = startIndex;
addresses.forEach((address) => {
addObj[index] = address.address;
index += 1;
});
return addObj;
}
/**
* This is an EXAMPLE function for retrieving deposits within a certain range and formatting them for validation.
* Raw wallet data is used instead of a DB.
* @param {num} startBlock First block in range to retrieve deposits from.
* @param {num} endBlock Last block in range to retrieve deposits from.
* @returns
*/
async function getDeposits(startBlock, endBlock) {
// Format wallet transactions.
const formDeposits = {};
exampleDeposits.forEach((deposit) => {
// Exclude deposits outside of range.
if (deposit.blockheight < startBlock || deposit.blockheight > endBlock) {
return;
}
if (formDeposits[deposit.txid] === undefined) {
formDeposits[deposit.txid] = {};
}
formDeposits[deposit.txid][deposit.address] = deposit.amount;
});
return formDeposits;
}