-
Notifications
You must be signed in to change notification settings - Fork 2
/
lightning-custodian-wallet.js
701 lines (591 loc) · 20.1 KB
/
lightning-custodian-wallet.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
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
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
import { LegacyWallet } from './legacy-wallet';
import Frisbee from 'frisbee';
import bolt11 from 'bolt11';
import { BitcoinUnit, Chain } from '../models/bitcoinUnits';
export class LightningCustodianWallet extends LegacyWallet {
static type = 'lightningCustodianWallet';
static typeReadable = 'Lightning';
static defaultBaseUri = 'https://lndhub.herokuapp.com/';
constructor(props) {
super(props);
this.setBaseURI(); // no args to init with default value
this.init();
this.refresh_token = '';
this.access_token = '';
this._refresh_token_created_ts = 0;
this._access_token_created_ts = 0;
this.refill_addressess = [];
this.pending_transactions_raw = [];
this.user_invoices_raw = [];
this.info_raw = false;
this.preferredBalanceUnit = BitcoinUnit.SATS;
this.chain = Chain.OFFCHAIN;
}
/**
* requires calling init() after setting
*
* @param URI
*/
setBaseURI(URI) {
if (URI) {
this.baseURI = URI;
} else {
this.baseURI = LightningCustodianWallet.defaultBaseUri;
}
}
getBaseURI() {
return this.baseURI;
}
allowSend() {
return true;
}
getAddress() {
if (this.refill_addressess.length > 0) {
return this.refill_addressess[0];
} else {
return undefined;
}
}
getSecret() {
if (this.baseURI === LightningCustodianWallet.defaultBaseUri) {
return this.secret;
}
return this.secret + '@' + this.baseURI;
}
timeToRefreshBalance() {
return (+new Date() - this._lastBalanceFetch) / 1000 > 300; // 5 min
}
timeToRefreshTransaction() {
return (+new Date() - this._lastTxFetch) / 1000 > 300; // 5 min
}
static fromJson(param) {
let obj = super.fromJson(param);
obj.init();
return obj;
}
init() {
this._api = new Frisbee({
baseURI: this.baseURI,
});
}
accessTokenExpired() {
return (+new Date() - this._access_token_created_ts) / 1000 >= 3600 * 2; // 2h
}
refreshTokenExpired() {
return (+new Date() - this._refresh_token_created_ts) / 1000 >= 3600 * 24 * 7; // 7d
}
generate() {
// nop
}
async createAccount(isTest) {
let response = await this._api.post('/create', {
body: { partnerid: 'bluewallet', accounttype: (isTest && 'test') || 'common' },
headers: { 'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json' },
});
let json = response.body;
if (typeof json === 'undefined') {
throw new Error('API failure: ' + response.err + ' ' + JSON.stringify(response.body));
}
if (json && json.error) {
throw new Error('API error: ' + (json.message ? json.message : json.error) + ' (code ' + json.code + ')');
}
if (!json.login || !json.password) {
throw new Error('API unexpected response: ' + JSON.stringify(response.body));
}
this.secret = 'lndhub://' + json.login + ':' + json.password;
}
async payInvoice(invoice, freeAmount = 0) {
let response = await this._api.post('/payinvoice', {
body: { invoice: invoice, amount: freeAmount },
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
Authorization: 'Bearer' + ' ' + this.access_token,
},
});
if (response.originalResponse && typeof response.originalResponse === 'string') {
try {
response.originalResponse = JSON.parse(response.originalResponse);
} catch (_) {}
}
if (response.originalResponse && response.originalResponse.status && response.originalResponse.status === 503) {
throw new Error('Payment is in transit');
}
let json = response.body;
if (typeof json === 'undefined') {
throw new Error('API failure: ' + response.err + ' ' + JSON.stringify(response.originalResponse));
}
if (json && json.error) {
throw new Error('API error: ' + json.message + ' (code ' + json.code + ')');
}
this.last_paid_invoice_result = json;
}
/**
* Returns list of LND invoices created by user
*
* @return {Promise.<Array>}
*/
async getUserInvoices(limit = false) {
let limitString = '';
if (limit) limitString = '?limit=' + parseInt(limit);
let response = await this._api.get('/getuserinvoices' + limitString, {
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
Authorization: 'Bearer' + ' ' + this.access_token,
},
});
let json = response.body;
if (typeof json === 'undefined') {
throw new Error('API failure: ' + response.err + ' ' + JSON.stringify(response.originalResponse));
}
if (json && json.error) {
throw new Error('API error: ' + json.message + ' (code ' + json.code + ')');
}
if (limit) {
// need to merge existing invoices with the ones that arrived
// but the ones received later should overwrite older ones
for (let oldInvoice of this.user_invoices_raw) {
// iterate all OLD invoices
let found = false;
for (let newInvoice of json) {
// iterate all NEW invoices
if (newInvoice.payment_request === oldInvoice.payment_request) found = true;
}
if (!found) {
// if old invoice is not found in NEW array, we simply add it:
json.push(oldInvoice);
}
}
}
this.user_invoices_raw = json.sort(function(a, b) {
return a.timestamp - b.timestamp;
});
return this.user_invoices_raw;
}
/**
* Basically the same as this.getUserInvoices() but saves invoices list
* to internal variable
*
* @returns {Promise<void>}
*/
async fetchUserInvoices() {
await this.getUserInvoices();
}
isInvoiceGeneratedByWallet(paymentRequest) {
return this.user_invoices_raw.some(invoice => invoice.payment_request === paymentRequest);
}
async addInvoice(amt, memo) {
let response = await this._api.post('/addinvoice', {
body: { amt: amt + '', memo: memo },
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
Authorization: 'Bearer' + ' ' + this.access_token,
},
});
let json = response.body;
if (typeof json === 'undefined') {
throw new Error('API failure: ' + response.err + ' ' + JSON.stringify(response.originalResponse));
}
if (json && json.error) {
throw new Error('API error: ' + json.message + ' (code ' + json.code + ')');
}
if (!json.r_hash || !json.pay_req) {
throw new Error('API unexpected response: ' + JSON.stringify(response.body));
}
return json.pay_req;
}
async checkRouteInvoice(invoice) {
let response = await this._api.get('/checkrouteinvoice?invoice=' + invoice, {
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
Authorization: 'Bearer' + ' ' + this.access_token,
},
});
let json = response.body;
if (typeof json === 'undefined') {
throw new Error('API failure: ' + response.err + ' ' + JSON.stringify(response.body));
}
if (json && json.error) {
throw new Error('API error: ' + json.message + ' (code ' + json.code + ')');
}
}
/**
* Uses login & pass stored in `this.secret` to authorize
* and set internal `access_token` & `refresh_token`
*
* @return {Promise.<void>}
*/
async authorize() {
let login, password;
if (this.secret.indexOf('blitzhub://') !== -1) {
login = this.secret.replace('blitzhub://', '').split(':')[0];
password = this.secret.replace('blitzhub://', '').split(':')[1];
} else {
login = this.secret.replace('lndhub://', '').split(':')[0];
password = this.secret.replace('lndhub://', '').split(':')[1];
}
let response = await this._api.post('/auth?type=auth', {
body: { login: login, password: password },
headers: { 'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json' },
});
let json = response.body;
if (typeof json === 'undefined') {
throw new Error('API failure: ' + response.err + ' ' + JSON.stringify(response.body));
}
if (json && json.error) {
throw new Error('API error: ' + json.message + ' (code ' + json.code + ')');
}
if (!json.access_token || !json.refresh_token) {
throw new Error('API unexpected response: ' + JSON.stringify(response.body));
}
this.refresh_token = json.refresh_token;
this.access_token = json.access_token;
this._refresh_token_created_ts = +new Date();
this._access_token_created_ts = +new Date();
}
async checkLogin() {
if (this.accessTokenExpired() && this.refreshTokenExpired()) {
// all tokens expired, only option is to login with login and password
return this.authorize();
}
if (this.accessTokenExpired()) {
// only access token expired, so only refreshing it
let refreshedOk = true;
try {
await this.refreshAcessToken();
} catch (Err) {
refreshedOk = false;
}
if (!refreshedOk) {
// something went wrong, lets try to login regularly
return this.authorize();
}
}
}
async refreshAcessToken() {
let response = await this._api.post('/auth?type=refresh_token', {
body: { refresh_token: this.refresh_token },
headers: { 'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json' },
});
let json = response.body;
if (typeof json === 'undefined') {
throw new Error('API failure: ' + response.err + ' ' + JSON.stringify(response.body));
}
if (json && json.error) {
throw new Error('API error: ' + json.message + ' (code ' + json.code + ')');
}
if (!json.access_token || !json.refresh_token) {
throw new Error('API unexpected response: ' + JSON.stringify(response.body));
}
this.refresh_token = json.refresh_token;
this.access_token = json.access_token;
this._refresh_token_created_ts = +new Date();
this._access_token_created_ts = +new Date();
}
async fetchBtcAddress() {
let response = await this._api.get('/getbtc', {
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
Authorization: 'Bearer' + ' ' + this.access_token,
},
});
let json = response.body;
if (typeof json === 'undefined') {
throw new Error('API failure: ' + response.err + ' ' + JSON.stringify(response.body));
}
if (json && json.error) {
throw new Error('API error: ' + json.message + ' (code ' + json.code + ')');
}
this.refill_addressess = [];
for (let arr of json) {
this.refill_addressess.push(arr.address);
}
}
async getAddressAsync() {
return this.fetchBtcAddress();
}
async allowOnchainAddress() {
if (this.getAddress() !== undefined) {
return true;
} else {
await this.fetchBtcAddress();
return this.getAddress() !== undefined;
}
}
getTransactions() {
let txs = [];
this.pending_transactions_raw = this.pending_transactions_raw || [];
this.user_invoices_raw = this.user_invoices_raw || [];
this.transactions_raw = this.transactions_raw || [];
txs = txs.concat(this.pending_transactions_raw.slice(), this.transactions_raw.slice().reverse(), this.user_invoices_raw.slice()); // slice so array is cloned
// transforming to how wallets/list screen expects it
for (let tx of txs) {
tx.fromWallet = this.getSecret();
if (tx.amount) {
// pending tx
tx.amt = tx.amount * -100000000;
tx.fee = 0;
tx.timestamp = tx.time;
tx.memo = 'On-chain transaction';
}
if (typeof tx.amt !== 'undefined' && typeof tx.fee !== 'undefined') {
// lnd tx outgoing
tx.value = parseInt((tx.amt * 1 + tx.fee * 1) * -1);
}
if (tx.type === 'paid_invoice') {
tx.memo = tx.memo || 'Lightning payment';
if (tx.value > 0) tx.value = tx.value * -1; // value already includes fee in it (see lndhub)
// outer code expects spending transactions to of negative value
}
if (tx.type === 'bitcoind_tx') {
tx.memo = 'On-chain transaction';
}
if (tx.type === 'user_invoice') {
// incoming ln tx
tx.value = parseInt(tx.amt);
tx.memo = tx.description || 'Lightning invoice';
}
tx.received = new Date(tx.timestamp * 1000).toString();
}
return txs.sort(function(a, b) {
return b.timestamp - a.timestamp;
});
}
async fetchPendingTransactions() {
let response = await this._api.get('/getpending', {
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
Authorization: 'Bearer' + ' ' + this.access_token,
},
});
let json = response.body;
if (typeof json === 'undefined') {
throw new Error('API failure: ' + response.err + ' ' + JSON.stringify(response));
}
if (json && json.error) {
throw new Error('API error: ' + json.message + ' (code ' + json.code + ')');
}
this.pending_transactions_raw = json;
}
async fetchTransactions() {
// TODO: iterate over all available pages
const limit = 10;
let queryRes = '';
let offset = 0;
queryRes += '?limit=' + limit;
queryRes += '&offset=' + offset;
let response = await this._api.get('/gettxs' + queryRes, {
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
Authorization: 'Bearer' + ' ' + this.access_token,
},
});
let json = response.body;
if (typeof json === 'undefined') {
throw new Error('API failure: ' + response.err + ' ' + JSON.stringify(response.body));
}
if (json && json.error) {
throw new Error('API error: ' + json.message + ' (code ' + json.code + ')');
}
if (!Array.isArray(json)) {
throw new Error('API unexpected response: ' + JSON.stringify(response.body));
}
this._lastTxFetch = +new Date();
this.transactions_raw = json;
}
getBalance() {
return this.balance;
}
async fetchBalance(noRetry) {
await this.checkLogin();
let response = await this._api.get('/balance', {
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
Authorization: 'Bearer' + ' ' + this.access_token,
},
});
let json = response.body;
if (typeof json === 'undefined') {
throw new Error('API failure: ' + response.err + ' ' + JSON.stringify(response.body));
}
if (json && json.error) {
if (json.code * 1 === 1 && !noRetry) {
await this.authorize();
return this.fetchBalance(true);
}
throw new Error('API error: ' + json.message + ' (code ' + json.code + ')');
}
if (!json.BTC || typeof json.BTC.AvailableBalance === 'undefined') {
throw new Error('API unexpected response: ' + JSON.stringify(response.body));
}
this.balance_raw = json;
this.balance = json.BTC.AvailableBalance;
this._lastBalanceFetch = +new Date();
}
/**
* Example return:
* { destination: '03864ef025fde8fb587d989186ce6a4a186895ee44a926bfc370e2c366597a3f8f',
* payment_hash: 'faf996300a468b668c58ca0702a12096475a0dd2c3dde8e812f954463966bcf4',
* num_satoshis: '100',
* timestamp: '1535116657',
* expiry: '3600',
* description: 'hundredSatoshis blitzhub',
* description_hash: '',
* fallback_addr: '',
* cltv_expiry: '10',
* route_hints: [] }
*
* @param invoice BOLT invoice string
* @return {Promise.<Object>}
*/
decodeInvoice(invoice) {
let { payeeNodeKey, tags, satoshis, millisatoshis, timestamp } = bolt11.decode(invoice);
let decoded = {
destination: payeeNodeKey,
num_satoshis: satoshis ? satoshis.toString() : '0',
num_millisatoshis: millisatoshis ? millisatoshis.toString() : '0',
timestamp: timestamp.toString(),
fallback_addr: '',
route_hints: [],
};
for (let i = 0; i < tags.length; i++) {
let { tagName, data } = tags[i];
switch (tagName) {
case 'payment_hash':
decoded.payment_hash = data;
break;
case 'purpose_commit_hash':
decoded.description_hash = data;
break;
case 'min_final_cltv_expiry':
decoded.cltv_expiry = data.toString();
break;
case 'expire_time':
decoded.expiry = data.toString();
break;
case 'description':
decoded.description = data;
break;
}
}
if (!decoded.expiry) decoded.expiry = '3600'; // default
if (parseInt(decoded.num_satoshis) === 0 && decoded.num_millisatoshis > 0) {
decoded.num_satoshis = (decoded.num_millisatoshis / 1000).toString();
}
return (this.decoded_invoice_raw = decoded);
}
async fetchInfo() {
let response = await this._api.get('/getinfo', {
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
Authorization: 'Bearer' + ' ' + this.access_token,
},
});
let json = response.body;
if (typeof json === 'undefined') {
throw new Error('API failure: ' + response.err + ' ' + JSON.stringify(response.body));
}
if (json && json.error) {
throw new Error('API error: ' + json.message + ' (code ' + json.code + ')');
}
if (!json.identity_pubkey) {
throw new Error('API unexpected response: ' + JSON.stringify(response.body));
}
this.info_raw = json;
}
static async isValidNodeAddress(address) {
let apiCall = new Frisbee({
baseURI: address,
});
let response = await apiCall.get('/getinfo', {
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
},
});
let json = response.body;
if (typeof json === 'undefined') {
throw new Error('API failure: ' + response.err + ' ' + JSON.stringify(response.body));
}
if (json && json.code && json.code !== 1) {
throw new Error('API error: ' + json.message + ' (code ' + json.code + ')');
}
return true;
}
allowReceive() {
return true;
}
/**
* Example return:
* { destination: '03864ef025fde8fb587d989186ce6a4a186895ee44a926bfc370e2c366597a3f8f',
* payment_hash: 'faf996300a468b668c58ca0702a12096475a0dd2c3dde8e812f954463966bcf4',
* num_satoshis: '100',
* timestamp: '1535116657',
* expiry: '3600',
* description: 'hundredSatoshis blitzhub',
* description_hash: '',
* fallback_addr: '',
* cltv_expiry: '10',
* route_hints: [] }
*
* @param invoice BOLT invoice string
* @return {Promise.<Object>}
*/
async decodeInvoiceRemote(invoice) {
await this.checkLogin();
let response = await this._api.get('/decodeinvoice?invoice=' + invoice, {
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
Authorization: 'Bearer' + ' ' + this.access_token,
},
});
let json = response.body;
if (typeof json === 'undefined') {
throw new Error('API failure: ' + response.err + ' ' + JSON.stringify(response.body));
}
if (json && json.error) {
throw new Error('API error: ' + json.message + ' (code ' + json.code + ')');
}
if (!json.payment_hash) {
throw new Error('API unexpected response: ' + JSON.stringify(response.body));
}
return (this.decoded_invoice_raw = json);
}
}
/*
pending tx:
[ { amount: 0.00078061,
account: '521172',
address: '3F9seBGCJZQ4WJJHwGhrxeGXCGbrm5SNpF',
category: 'receive',
confirmations: 0,
blockhash: '',
blockindex: 0,
blocktime: 0,
txid: '28a74277e47c2d772ee8a40464209c90dce084f3b5de38a2f41b14c79e3bfc62',
walletconflicts: [],
time: 1535024434,
timereceived: 1535024434 } ]
tx:
[ { amount: 0.00078061,
account: '521172',
address: '3F9seBGCJZQ4WJJHwGhrxeGXCGbrm5SNpF',
category: 'receive',
confirmations: 5,
blockhash: '0000000000000000000edf18e9ece18e449c6d8eed1f729946b3531c32ee9f57',
blockindex: 693,
blocktime: 1535024914,
txid: '28a74277e47c2d772ee8a40464209c90dce084f3b5de38a2f41b14c79e3bfc62',
walletconflicts: [],
time: 1535024434,
timereceived: 1535024434 } ]
*/