-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
executable file
·963 lines (850 loc) · 30.8 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
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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
/* eslint-disable no-undef */
/* eslint-disable no-prototype-builtins */
/* eslint-disable no-redeclare */
const fs = require("fs");
const crypto = require("crypto");
const compare = require("underscore");
const xrpl = require("@transia/xrpl");
// const VerifySignature = require("verify-xrpl-signature").verifySignature;
// const { XrplDefinitions } = require("xrpl-accountlib");
// const definitions = fs.readFileSync(__dirname + "/DKM/dApp/definitions.json").toString(); // fs.readFileSync(__dirname+"/DKM/dApp/definitions.json").toString());
// const CustomDefinitions = new XrplDefinitions(JSON.parse(definitions));
// const { decode } = require("ripple-codec-binary");
// const { XrplClient } = require("xrpl-client");
// const xrplAccount = require("xrpl-accountlib");
/**
* The 'Decentralized Key Management' framework for HotPocket applications.
* @author Wo Jake
* @version 0.4.4
* @description A NodeJS framework for HotPocket clusters to manage their Decentralized Application's signer keys in a decentralized manner (XRPL).
*
* See https://github.com/wojake/DKM to learn more and contribute to the codebase, any type of contribution is truly appreciated.
*/
// PUBLIC FUNCTIONS
// API Request : getNetwork, getSignerList, getTransactions
// Setup : init, setSignerList, addSignerKey, removeSignerKey
// Transaction : packageTxAPI, autofillTx, submitTx, signTx
/**
* Get a XRPL node's URL from DKM config file.
*
* @param {string} network - The network (testnet, devnet, hooks)
* @returns {object} The network {wss: string, network_id: string}
*/
function getNetwork(network) {
const config = JSON.parse(fs.readFileSync(__dirname+"/DKM/dApp/config.json").toString());
return config.network[network];
}
class Manager {
constructor(ctx, npl, network) {
this.ctx = ctx;
this.npl = npl; // NPLBroker.init(ctx);
const _network = getNetwork(network);
this.networkID = _network.id;
this.client = new xrpl.Client(_network.url);
this.dkmConfig = JSON.parse(fs.readFileSync(__dirname+"/DKM/dApp/config.json").toString());
// false: 0 signerlist on account root
// true: 1 signerlist on account root
this.signerlistCount = 0;
}
get config() {
return this.dkmConfig;
}
// The HotPocket node's unique keypair, used for signing XRPL transactions.
// Each HP node has its own unique keypair, stored & used privately.
get hpNodeSignerAddress() {
return this.hpSignerAddress;
}
get hpNodeSignerSeed() {
return this.hpSignerSeed;
}
// The HP dApp's XRPL account, representing the dApp's balances and "web3" interface on the XRPL.
// The account is controlled by the HP cluster in a decentralized manner via a signer list (multi-sig).
get dAppXrplAccountClassicAddress() {
return this.dAppAccountClassicAddress;
}
get dAppXrplAccountSeed() {
return this.dAppAccountSeed;
}
get dAppXrplAccountSequence() {
return this.dAppAccountSeq;
}
// The HP dApp's signer list data.
get dAppXrplsigners() {
return this.signers;
}
get dAppXrplsignersLocation() {
return this.signersLocation;
}
get dAppXrplsignersWeight() {
return this.signersWeight;
}
get dAppXrplSignerListQuorum() {
return this.signerlistQuorum;
}
get dAppXrplTransactions() {
return this.transactions;
}
// XRPL details
get xrplNetworkID() {
return this.networkID;
}
/**
* Internal use to delay code execution.
*
* @param {number} ms unit of time measurement: *millisecond*
*/
async #Delay(ms) {
return await new Promise(resolve => setTimeout(resolve, ms));
}
/**
* Log messages to DKM's log files, used internally.
*
* @param {string} type - The log message's type (FTL: Fatal, ERR: Error, WRN: Warn, INF: Info, DBG: Debug)
* @param {string} message - The log message
*/
#Log(type, message) {
message = `DKM ${type} @ HP Ledger #${this.ctx.lclSeqNo}: ${message}`;
console.log(message);
fs.appendFileSync("../gen-logs.txt", message);
switch (type) {
case "FTL":
fs.appendFileSync(`../${type}-logs.txt`, message);
break;
case "ERR":
fs.appendFileSync(`../${type}-logs.txt`, message);
break;
case "WRN":
fs.appendFileSync(`../${type}-logs.txt`, message);
break;
case "INF":
fs.appendFileSync(`../${type}-logs.txt`, message);
break;
case "DBG":
fs.appendFileSync(`../${type}-logs.txt`, message);
break;
}
}
/**
* Query the XRP Ledger for data.
*
* @async
* @param {object} request - The request
* @returns {Promise<object>} The request's result
*/
async #requestRippled(request) {
try {
this.#Log("INF", `${this.#requestRippled.name}: Requesting ${request.command} data from ${this.client.url}`);
return await this.client.request(request);
} catch (err) {
return err;
}
}
/**
* Generate a unique keypair for the HotPocket node.
*/
#generateSignerCredentials() {
const keyFile = `../${this.ctx.publicKey}-signerKey.json`;
if (!fs.existsSync(keyFile)) {
this.#Log("INF", `${this.#generateSignerCredentials.name}: Generating XRPL signer key`);
var scheme = this.dkmConfig.signer.scheme;
if (scheme.length > 0) {
var index = Math.abs(Math.floor(Math.random() * scheme.length));
scheme = scheme[index];
} else {
throw new Error(`${this.#generateSignerCredentials.name}: config.signer.scheme[] is not defined in config.json file`);
}
const signerKeypair = xrpl.Wallet.generate(scheme);
fs.writeFileSync(keyFile, JSON.stringify({
"seed": signerKeypair.seed,
"classicAddress": signerKeypair.classicAddress
}));
}
}
/**
* Construct an *unfilled* Payment transaction with a memo field attached.
*
* DKM leverages the memo field on an XRPL transaction so that the dApp could transmit data temporarily to its users on the XRPL.
*
* @param {string} destination - The recipient's XRPL account address
* @param {string} amount - (Optional) The amount of XRP that will be sent. Default value: 1 drop.
* @param {object} memo - The memo field { type, data, format }
* @returns {object} The transaction with a memo field attached
*/
packageTxAPI({destination, amount, memo}) {
if (typeof amount !== "undefined" && typeof amount !== "string") {
throw new Error(`${this.packageTxAPI.name}: amount field is a ${typeof amount} instead of a string`);
}
return {
TransactionType: "Payment",
Account: this.dAppAccountClassicAddress,
Destination: destination,
Amount: amount ?? 1,
Memos: [{
Memo: {
MemoType: Buffer.from(memo.type, "utf8").toString("hex"),
MemoData: Buffer.from(memo.data, "utf8").toString("hex"),
MemoFormat: Buffer.from(memo.format, "utf8").toString("hex") // Common ones are "application/json" or "text/csv"
}
}],
NetworkID: this.networkID
};
}
/**
* Autofill an unfilled XRPL transaction.
*
* @async
* @param {object} tx - The constructed transaction
* @param {boolean} multisig - The transaction's type (single signature or multi signature)
* @param {number} fee - The fee set for each signer
* @returns {Promise<object>} The autofilled transaction
*/
async autofillTx({tx, multisig, fee}) {
this.#Log("INF", `${this.autofillTx.name}: Autofilling ${tx.TransactionType} transaction`);
if (multisig) {
if (this.signerlistCount === 0) {
const signerlist = await this.getSignerList();
if (!signerlist.SignerListCount === 0) {
throw new Error(`${this.autofillTx.name}: signerlist does not exist`);
}
}
if (!this.signerlistQuorum > 0) {
throw new Error(`${this.autofillTx.name}: signerlistQuorum is less than 0, value: ${this.signerlistQuorum}`);
}
if (typeof tx.Fee === "number") {
throw new Error(`${this.autofillTx.name}: tx.Fee is a number instead of a string`);
}
if (typeof tx.Fee === "undefined") {
tx.Fee = ((this.signerlistQuorum + 1) * (fee ?? this.dkmConfig.signer.default_fee_per_signer)).toString();
}
try {
var preparedTx = await this.client.autofill(tx, this.signerlistQuorum);
} catch (err) {
return err;
}
} else {
var preparedTx = await this.client.autofill(tx);
}
return preparedTx;
}
/**
* Submit a signed transaction to a rippled node (XRPLP powered network).
*
* @async
* @param {string} tx - The signed transaction blob
* @returns {Promise<object>} The transaction's result
*/
async submitTx(tx) {
// Inputted transaction must be a signedTxBlob (Signed-Transaction-Object.tx_blob)
if (typeof tx === "number" || tx === undefined) {
throw new Error(`${this.submitTx.name}: No signed transaction blob was provided`);
} else {
var tt = xrpl.decode(tx).TransactionType;
}
try {
this.#Log("INF", `${this.submitTx.name}: Submitting ${tt} transaction to rippled node`);
return await this.client.submit(tx);
} catch (err) {
throw new Error(`${this.submitTx.name}: Failed submitting ${tt} transaction to rippled node. Error: ${err}`);
}
}
/**
* Submit a signed transaction to a rippled node.
*
* @async
* @param {string} tx - The signed transaction blob
* @returns {Promise<object>} The transaction's result
*/
async submitTxAndWait(tx) {
// Inputted transaction must be a signedTxBlob (Signed-Transaction-Object.tx_blob)
if (typeof tx === "number" || tx === undefined) {
throw new Error(`${this.submitTxAndWait.name}: No signed transaction blob was provided`);
} else {
var tt = xrpl.decode(tx).TransactionType;
}
try {
this.#Log("INF", `${this.submitTxAndWait.name}: Submitting ${tt} transaction to rippled node`);
return await this.client.submitAndWait(tx);
} catch (err) {
throw new Error(`${this.submitTxAndWait.name}: Error submitting ${tt} transaction to rippled node. Error: ${err}`);
}
}
/**
* Get the dApp's XRPL account signer list.
*
* By default, `getSignerList()` will request the dApp's signer list but in the case that the `address` parameter is filled, it'll search for that XRPL account's signer list instead.
*
* @async
* @param {string} address - (Optional) The account to look up
* @returns {Promise<object>} The request's result
*/
async getSignerList(address) {
const request = await this.#requestRippled({
"command": "account_objects",
"account": address ?? this.dAppAccountClassicAddress,
"ledger_index": "validated",
"type": "signer_list"
});
if (request.hasOwnProperty("result")) {
for (let i = 0; i < request.result.account_objects.length; i++) {
if (request.result.account_objects[i].hasOwnProperty("SignerEntries")) {
const signerlist = request.result.account_objects[i].SignerEntries;
const dAppSigners = [],
signersWeight = [],
signersLocation = [];
signerlist.forEach(signer => {
dAppSigners.push(signer.SignerEntry.Account),
signersLocation.push({
xrpl_signing_key: signer.SignerEntry.Account,
hp_public_key: signer.SignerEntry.WalletLocator
}),
signersWeight.push({
account: signer.SignerEntry.Account,
weight: signer.SignerEntry.SignerWeight
});
});
this.signerlistCount = 1,
this.signers = dAppSigners,
this.signersLocation = signersLocation,
this.signersWeight = signersWeight,
this.signerlistQuorum = request.result.account_objects[0].SignerQuorum;
return {
SignerListCount: this.signerlistCount,
Signers: this.signers,
SignersWeight: this.signersWeight,
SignerlistQuorum: this.signerlistQuorum
};
}
}
}
this.signerlistCount = 0,
this.signers = [],
this.signersLocation = [],
this.signersWeight = [],
this.signerlistQuorum = 0;
return {
SignerListCount: this.signerlistCount,
Signers: this.signers,
SignersWeight: this.signersWeight,
SignerlistQuorum: this.signerlistQuorum
};
}
/**
* Sign an XRPL transaction with all the participating signers' signature.
*
* All active participating signers will sign the transaction and distribute their signatures via NPL.
*
* @async
* @param {object} tx - The transaction
* @returns {Promise<object>} The multi-signed transaction
*/
async signTx(tx) {
// Signers that are apart of the dApp's signer list get to be apart of the multisig transaction, other signer's tx blob are ignored
if (this.signers.includes(this.hpSignerAddress)) {
const signedTxBlob = this.hpSignerWallet.sign(tx, true).tx_blob;
this.#Log("INF", `${this.signTx.name}: Multi-signing ${tx.TransactionType} transaction`);
// Hash the unsigned tx's object as a checksum for the NPL roundname
const roundName = crypto.createHash("sha256").update(JSON.stringify(tx)).digest("hex").toUpperCase();
const signatures = await this.npl.performNplRound({
roundName: `signature-collection-${roundName}`,
content: JSON.stringify({
account: this.hpNodeSignerAddress,
tx: signedTxBlob
}),
desiredCount: this.signerlistQuorum,
timeout: this.dkmConfig.NPL_round_timeout["signing"]
});
const validSignatures = [];
var collectedQuorum = 0;
signatures.record.forEach(packet => {
const signature = JSON.parse(packet.content);
// Check if we have enough signers && check if the signature's signer key is on the signer list
if (collectedQuorum < this.signerlistQuorum && this.signers.includes(signature.account)) {
validSignatures.push(signature.tx),
collectedQuorum += this.signersWeight.find(({ account }) => account === signature.account).weight;
// THIS NEEDS FIXING WHEN WE INTEGRATE XRPLCLIENT & XRPLACCOUNTLIB
// const verification = VerifySignature(signature.tx, signature.account, CustomDefinitions);
// if (verification.signedBy === signature.account && verification.signatureValid && verification.signatureMultiSign) {
// validSignatures.push(signature.tx),
// collectedQuorum += this.signersWeight.find(({ account }) => account === signature.account).weight;
// } else {
// if (verification.signedBy !== signature.account) {
// var reason = "Transaction was not signed by the specified signer key";
// }
// if (verification.signatureValid !== true) {
// var reason = "Transaction's signature was not valid";
// }
// if (verification.signatureMultiSign !== true) {
// var reason = "Transaction was not a multi-sig transaction";
// }
// throw new Error(`${this.signTx.name}: Signer ${signature.account} did not provide a valid signature. Reason: ${reason}`);
// }
}
});
if (collectedQuorum === this.signerlistQuorum) {
return xrpl.multisign(validSignatures);
} else {
return undefined;
}
} else {
return undefined;
}
}
/**
* Construct a Signer List for the dApp's account.
*
* @async
* @param {array} signers - The dApp's SignerList {xrpl_signing_key: string, hp_public_key: string} (HP node's public key, signer's address)
* @param {number} fee - The fee for each participating signer or the fee for the transaction during setup
* @returns {Promise<object>} The transaction's result
*/
async setSignerList({signers, fee}) {
if (typeof signers === "undefined") {
throw new Error(`${this.setSignerList.name}: proposed signer list has 0 signers`);
}
if (signers.length > 32) {
throw new Error(`${this.setSignerList.name}: proposed signer list has over 32 signers. The max amount of signers on a signer list is 32`);
}
if ((new Set(signers)).size !== signers.length) {
throw new Error(`${this.setSignerList.name}: signer list has duplicate values`);
}
// var sortedSigners = [];
// // if there are no duplicate values (keys), we simply copy signerKeys.
// if ((new Set(signerKeys)).size === signerKeys.length) {
// sortedSigners = signerKeys;
// } else {
// // filter duplicate values :p
// signerKeys.forEach(xrpl_signing_key => {
// signers.forEach(signer => {
// if (signer.xrpl_signing_key === xrpl_signing_key) sortedSigners.push(signer);
// signers = signers.filter((signer) => signer.xrpl_signing_key !== xrpl_signing_key);
// });
// });
// }
// regex for SHA256 hash
const newSignerList = [];
signers.forEach(signer => {
newSignerList.push({
"SignerEntry": {
"Account": signer.xrpl_signing_key,
"SignerWeight": 1,
"WalletLocator": crypto.createHash("sha256").update(signer.hp_public_key).digest("hex").toUpperCase()
}
});
});
if (this.signerlistCount === 0) {
var SetSignerListTx = await this.autofillTx({
tx: {
TransactionType: "SignerListSet",
Account: this.dAppAccountClassicAddress, // <- fuck you xrpl.js why didn't you tell me this was the problem
SignerEntries: newSignerList,
SignerQuorum: Math.round(newSignerList.length * this.dkmConfig.account.signerlist_quorum),
Memos: [{
Memo: {
MemoType: Buffer.from("Evernode", "utf8").toString("hex"),
MemoData: Buffer.from("DKM: HotPocket dApp's SignerList", "utf8").toString("hex"),
MemoFormat: Buffer.from("text/plain", "utf8").toString("hex")
}
}],
NetworkID: this.networkID
},
multisig: false
});
var SetSignerListTxSigned = this.dAppAccountWallet.sign(SetSignerListTx).tx_blob;
} else {
var SetSignerListTx = await this.autofillTx({
tx: {
TransactionType: "SignerListSet",
Account: this.dAppAccountClassicAddress,
SignerEntries: newSignerList,
SignerQuorum: Math.round(newSignerList.length * this.dkmConfig.account.signerlist_quorum),
Memos: [{
Memo: {
MemoType: Buffer.from("Evernode", "utf8").toString("hex"),
MemoData: Buffer.from("DKM: HotPocket dApp's SignerList", "utf8").toString("hex"),
MemoFormat: Buffer.from("text/plain", "utf8").toString("hex")
}
}],
NetworkID: this.networkID
},
multisig: true,
fee: fee,
});
var SetSignerListTxSigned = await this.signTx(SetSignerListTx);
}
const submittedTx = await this.submitTx(SetSignerListTxSigned);
var retries = 0;
while (retries < 2) {
await this.#Delay(4000);
await this.getSignerList();
if (this.signerlistCount === 1) {
return {
Result: "success",
TransactionResult: submittedTx
};
} else {
if (retries === 1) {
return {
Result: "failed",
TransactionResult: submittedTx
};
} else {
retries++;
}
}
}
}
/**
* Disable the dApp's XRPL account Master Key.
*
* @async
* @returns {Promise<object>} The transaction's result
*/
async #disableMasterKey() {
const DisableMasterKeyTx = await this.autofillTx({
tx: {
TransactionType: "AccountSet",
Account: this.dAppAccountClassicAddress,
SetFlag: 4,
Memos: [{
Memo:{
MemoType: Buffer.from("Evernode", "utf8").toString("hex"),
MemoData: Buffer.from("DKM: This XRPL account is now fully controlled by its signers", "utf8").toString("hex"),
MemoFormat: Buffer.from("text/plain", "utf8").toString("hex")
}
}],
NetworkID: this.networkID
},
multisig: false,
});
const DisableMasterKeyTxSigned = this.dAppAccountWallet.sign(DisableMasterKeyTx).tx_blob;
const submittedTx = await this.submitTx(DisableMasterKeyTxSigned);
var retries = 0;
while (retries < 2) {
await this.#Delay(4000);
const lsfDisableMaster = await this.#requestRippled({
"command": "account_info",
"account": this.dAppAccountClassicAddress,
"ledger_index": "validated"
});
if ((0x00100000 & lsfDisableMaster.result.account_data.Flags)) {
return {
Result: "success",
TransactionResult: submittedTx
};
} else {
if (retries === 1) {
return {
Result: "failed",
TransactionResult: submittedTx
};
} else {
retries++;
}
}
}
}
/**
* Setup the HP dApp's XRPL account, this account will own a SignerList ledger object consisting of all the HP nodes' signer key and its account's master key will be disabled
*
* @returns {Promise<object>} The transactions' result
*/
async #setupDAppAccount() {
// Do not use getTransactions(), it doesn't work until we've created the '/DKM/dApp/dApp-xrplAccount.json' file
// Past transactions before this step (#setupDAppAccount()) will be ignored, they will not be processed as we're setting the dApp's XRPL account up
// SignerListSet and MasterKey is set to "failed" as default value. If not changed, the tx failed.
var SignerListSet = "failed",
MasterKeyDisabled = "failed",
hpSignersRecord = undefined,
hpClusterThreshold = false;
// 2 tries
var retries = 0;
while (retries < 2) {
if (retries === 0) {
var hpClusterSignerAddresses = await this.npl.performNplRound({
roundName:`signerlist-setup-${this.dAppAccountClassicAddress}-${retries}`,
content: this.hpSignerAddress,
desiredCount: this.ctx.unl.count(),
timeout: this.dkmConfig.NPL_round_timeout["signerlist_setup"]
});
hpSignersRecord = hpClusterSignerAddresses.record;
} else {
// hp publickey address
var unfilledHpSignersRecord = [];
if (hpSignersRecord.length > 0) {
hpSignersRecord.forEach(packet => {
unfilledHpSignersRecord.push(packet.content);
});
var hpClusterSignerAddresses = await this.npl.performNplRound({
roundName:`signerlist-setup-${this.dAppAccountClassicAddress}-${retries}`,
content: hpSignersRecord,
desiredCount: this.ctx.unl.count(),
timeout: this.dkmConfig.NPL_round_timeout["signerlist_setup"] / 2
});
hpClusterSignerAddresses.record.forEach(packet => {
if (hpSignersRecord.length < this.ctx.unl.count()) {
// go through the packets provided by the `publickey` hp node
packet.content.forEach(packet => {
if (hpSignersRecord.length < this.ctx.unl.count() && !unfilledHpSignersRecord.includes(packet.content)) {
hpSignersRecord.push(packet);
}
});
}
});
// In the case that x number of nodes are not present on all nodes' NPL round, we exclude them from the signerlist.
// aka. if x nodes are just offline/non-responding: ignore them, for now.
// Needs more comments on this condition.
if (this.ctx.unl.count() - hpClusterSignerAddresses.length === this.ctx.unl.count() - hpSignersRecord) hpClusterThreshold = true;
}
}
var _signers = [];
var signerlist = [];
if (hpSignersRecord.length === this.ctx.unl.count() || hpClusterThreshold) {
hpSignersRecord.forEach(record => {
const signerRecord = {
"xrpl_signing_key": record.content,
"hp_public_key": record.node
};
if (!_signers.includes(record.content)) {
signerlist.push(signerRecord);
_signers.push(record.content);
}
});
this.#Log("INF", `${this.#setupDAppAccount.name}: Setting up dApp XRPL account`);
var signerListSetTx = await this.setSignerList({
signers: signerlist
});
if (signerListSetTx.Result === "success") {
retries = 2,
SignerListSet = "success";
} else {
retries += 1;
}
if (signerListSetTx.hasOwnProperty("TransactionResult")) var signerlistsetTR = signerListSetTx.TransactionResult;
} else {
if (hpSignersRecord.length !== this.ctx.unl.count()) this.#Log("INF", `${this.#setupDAppAccount.name}: Failed to collect enough XRPL signer keys in round #${retries} to construct XRPL signerlist`);
retries++;
}
}
// 2 tries
// even if this node failed to collect enough NPL messages to setup the dApp's SignerList,
// it will attempt to contribute by disabling the master key;
// if it is successful, it will indicate that the dApp's XRPL account has been setup.
while (retries < 4) {
var disableMasterKeyTx = await this.#disableMasterKey();
if (disableMasterKeyTx.Result === "success") {
retries = 4;
MasterKeyDisabled = "success";
} else {
retries++;
}
}
if (MasterKeyDisabled === "success") this.#Log("INF", `${this.#setupDAppAccount.name}: Successfully set up dApp XRPL account`);
return {
result: MasterKeyDisabled, // if MasterKey was successful, that means the dApp xrpl account is setup (w/ signerlist)
Transactions: {
SignerListSet: {
"Result": SignerListSet,
"TransactionResult": signerlistsetTR
},
DisableMasterKey: {
"Result": MasterKeyDisabled,
"TransactionResult": disableMasterKeyTx.TransactionResult
}
}
};
}
/**
* Retrieve a new set of outgoing/incoming transactions that have not been acknowledged or 'processed'.
*
* @async
* @returns {Promise<array>} The transactions that have not been acknowledged
*/
async getTransactions() {
const request = await this.#requestRippled({
command: "account_tx",
account: this.dAppAccountClassicAddress,
ledger_index_min: this.dAppAccountSeq + 1,
ledger_index_max: -1,
binary: false,
forward: true
});
if (request.hasOwnProperty("result") ) {
if (request.result.transactions.length > 0) {
this.dAppAccountSeq = request.result.transactions[request.result.transactions.length - 1].tx.ledger_index;
const dAppXrplAccountCreds = {
"classicAddress": this.dAppAccountClassicAddress,
"seed": this.dAppAccountSeed,
"sequence": this.dAppAccountSeq
};
fs.writeFileSync(__dirname+"/DKM/dApp/dApp-xrplAccount.json", JSON.stringify(dAppXrplAccountCreds));
this.transactions = request.result.transactions;
return this.transactions;
} else {
this.transactions = [];
return this.transactions;
}
}
}
/**
* Check up on the cluster's status, particularly signers that are on the signer list.
*
* @async
* @returns {Promise<object>} The status of the cluster's signers (limited to the node's UNL)
*/
async checkupClusterSigners() {
if (!this.signerlistCount) {
throw new Error(`${this.checkupClusterSigners.name}: signerlist does not exist`);
}
const hpClusterSignerAddresses = await this.npl.performNplRound({
roundName: `signer-status-checkup-${this.dAppAccountClassicAddress}`,
content: this.hpSignerAddress,
desiredCount: this.ctx.unl.count(),
timeout: this.dkmConfig.NPL_round_timeout["signer_status_checkup"]
});
// this is a mess. if you have a better alternative, please suggest one !
var onlineSigners = [];
if (hpClusterSignerAddresses.record.length > 0) {
hpClusterSignerAddresses.record.forEach(record => {
const signerRecord = {
"xrpl_signing_key": record.content,
"hp_public_key": crypto.createHash("sha256").update(record.node).digest("hex").toUpperCase()
};
if (this.signersLocation.some(record => record.xrpl_signing_key === signerRecord.xrpl_signing_key)) {
onlineSigners.push(signerRecord);
}
});
var offlineSigners = [];
this.signersLocation.forEach(signer => {
if (!onlineSigners.some(record => record.xrpl_signing_key === signer.xrpl_signing_key)) {
offlineSigners.push(signer);
}
});
}
return {
OnlineSigners: onlineSigners,
OfflineSigners: offlineSigners,
Record: hpClusterSignerAddresses.record,
Timeout: hpClusterSignerAddresses.timeout,
TimeTaken: hpClusterSignerAddresses.timeTaken
};
}
/**
* Add a set of signer keys to the dApp's XRPL account SignerList.
*
* @async
* @param {array<string>} signers - Signer keys to add to the signer list { xrpl_signing_key: string, hp_public_key: string }
* @param {number} fee - The fee per each participating signer
* @returns {Promise<object>} The transaction's result
*/
async addSignerKey({signers, fee}) {
if (!this.signerlistCount) {
throw new Error(`${this.addSignerKey.name}: signerlist does not exist`);
}
if (this.signers.length + signers.length > 32) {
throw new Error(`${this.addSignerKey.name}: cannot append new signer keys as it exceeds the 32 signer slot limit on the XRP Ledger`);
}
signers.forEach(key => {
if (!xrpl.isValidClassicAddress(key.xrpl_signing_key)) {
throw new Error(`${this.addSignerKey.name}: "${key}" is not a valid XRPL address, cannot append to dApp's signerlist`);
}
});
const newSignerList = [];
// temporarily populate newSignerList w/ the current signerlist
this.signersLocation.forEach(key => {
newSignerList.push(key);
}),
signers.forEach(signer0 => {
newSignerList.forEach(signer1 => {
if (signer0.xrpl_signing_key === signer1.xrpl_signing_key) {
signers = signers.filter((signer0) => signer0.xrpl_signing_key !== signer1.xrpl_signing_key);
duplicate = true;
}
});
});
const differentKeys = compare.difference(newSignerList, this.signersLocation);
if (differentKeys.length > 0) {
return await this.setSignerList({
signers: newSignerList,
fee: fee
});
}
}
/**
* Remove signer keys from the dApp's XRPL account SignerList.
*
* @async
* @param {array<string>} signers - Signer keys to remove from the signer list
* @param {number} fee - The fee per each participating signer
* @returns {Promise<object>} The transaction's result
*/
async removeSignerKey({signers, fee}) {
if (!this.signerlistCount) {
throw new Error(`${this.addSignerKey.name}: signerlist does not exist`);
}
if (this.signers.length - signers.length === 0) {
throw new Error(`${this.addSignerKey.name}: cannot remove given signer keys as it will result in the dApp's signer list having 0 signers`);
}
var newSigners = this.signersLocation;
// filter out the signer keys that are instructed to be removed
signers.forEach(key => {
newSigners.forEach(signer => {
if (signer.xrpl_signing_key === key) {
newSigners = newSigners.filter((signer) => signer.xrpl_signing_key !== key);
}
});
});
if (newSigners.length < this.signersLocation.length) {
return await this.setSignerList({
signers: newSigners,
fee: fee
});
}
}
async init() {
this.#generateSignerCredentials();
if (this.client.isConnected) await this.client.connect();
const hpSignerCredential = JSON.parse(fs.readFileSync(`../${this.ctx.publicKey}-signerKey.json`).toString());
this.hpSignerSeed = hpSignerCredential.seed;
this.hpSignerAddress = hpSignerCredential.classicAddress;
this.hpSignerWallet = xrpl.Wallet.fromSecret(this.hpSignerSeed);
if (this.ctx.lclSeqNo > 1 ) {
const dAppXrplAccount = JSON.parse(fs.readFileSync(__dirname+"/DKM/dApp/dApp-xrplAccount.json").toString());
this.dAppAccountClassicAddress = dAppXrplAccount.classicAddress,
this.dAppAccountSeed = dAppXrplAccount.seed,
this.dAppAccountSeq = dAppXrplAccount.sequence;
this.dAppAccountWallet = xrpl.Wallet.fromSecret(this.dAppAccountSeed);
} else {
this.dAppAccountWallet = xrpl.Wallet.fromSecret(this.dkmConfig.account.seed);
this.dAppAccountSeed = this.dAppAccountWallet.seed,
this.dAppAccountClassicAddress = this.dAppAccountWallet.classicAddress;
}
await this.getSignerList();
if (this.signerlistCount === 0) {
try {
var setupResult = await this.#setupDAppAccount();
} catch (err) {
var setupResult = {
result: "failed"
};
throw new Error(`${this.init.name}: ${err}`);
}
} else {
var setupResult = {
result: "successful",
};
}
await this.getTransactions();
return setupResult;
}
/**
* Close XRPL node connection.
*/
async close() {
if (this.client.isConnected) await this.client.disconnect();
}
}
module.exports = {
getNetwork,
Manager
};
// e3c2064ece7e8bbbebb2a06be96607bb560a2ab8314e3ae64a43aaf3d2954830c760ad7ed923ca2ce3303a1bbc9a2e4d26bf177bae5416af0cc157a60dcc82e4