-
-
Notifications
You must be signed in to change notification settings - Fork 29
/
HavenoClient.test.ts
4518 lines (3949 loc) · 213 KB
/
HavenoClient.test.ts
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
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright Haveno
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// --------------------------------- IMPORTS ----------------------------------
// haveno imports
import {
HavenoClient,
HavenoError,
HavenoUtils,
OfferDirection,
MarketPriceInfo,
NotificationMessage,
OfferInfo,
TradeInfo,
UrlConnection,
XmrBalanceInfo,
Attachment,
DisputeResult,
PaymentMethod,
PaymentAccount,
PaymentAccountForm,
PaymentAccountFormField,
PaymentAccountPayload,
XmrDestination,
XmrNodeSettings,
XmrTx,
XmrIncomingTransfer,
XmrOutgoingTransfer,
} from "./index";
import AuthenticationStatus = UrlConnection.AuthenticationStatus;
import OnlineStatus = UrlConnection.OnlineStatus;
// other imports
import fs from "fs";
import path from "path";
import net from "net";
import assert from "assert";
import console from "console"; // import console because jest swallows messages in real time
import moneroTs from "monero-ts";
import * as os from 'os';
// ------------------------------ TEST CONFIG ---------------------------------
enum BaseCurrencyNetwork {
XMR_MAINNET = "XMR_MAINNET",
XMR_STAGENET = "XMR_STAGENET",
XMR_LOCAL = "XMR_LOCAL"
}
// clients
const startupHavenodUrls: string[] = [];
let arbitrator: HavenoClient;
let user1: HavenoClient;
let user2: HavenoClient;
let monerod: moneroTs.MoneroDaemon;
let fundingWallet: moneroTs.MoneroWalletRpc;
let user1Wallet: moneroTs.MoneroWalletRpc;
let user2Wallet: moneroTs.MoneroWalletRpc;
enum TradeRole {
MAKER = "MAKER",
TAKER = "TAKER",
}
enum SaleRole {
BUYER = "BUYER",
SELLER = "SELLER"
}
enum DisputeContext {
NONE = "NONE",
OPEN_AFTER_DEPOSITS_UNLOCK = "OPEN_AFTER_DEPOSITS_UNLOCK",
OPEN_AFTER_PAYMENT_SENT = "OPEN_AFTER_PAYMENT_SENT"
}
/**
* Test context for a single peer in a trade.
*/
class PeerContext {
havenod?: HavenoClient;
wallet?: moneroTs.MoneroWallet;
trade?: TradeInfo;
// context to test balances after trade
balancesBeforeOffer?: XmrBalanceInfo;
splitOutputTxFee?: bigint;
balancesBeforeTake?: XmrBalanceInfo;
balancesAfterTake?: XmrBalanceInfo;
balancesBeforePayout?: XmrBalanceInfo;
balancesAfterPayout?: XmrBalanceInfo;
tradeFee?: bigint;
depositTx?: moneroTs.MoneroTx;
depositTxFee?: bigint;
securityDepositActual?: bigint;
payoutTxFee?: bigint;
payoutAmount?: bigint;
constructor(ctx?: Partial<PeerContext>) {
Object.assign(this, ctx);
}
}
/**
* Default trade configuration.
*/
const defaultTradeConfig: Partial<TradeContext> = {
arbitrator: new PeerContext(),
maker: new PeerContext(),
taker: new PeerContext(),
makeOffer: true,
takeOffer: true,
awaitFundsToMakeOffer: true,
direction: OfferDirection.BUY, // buy or sell xmr
offerAmount: 193312996088n,
offerMinAmount: undefined,
assetCode: "usd", // counter asset to trade
makerPaymentAccountId: undefined,
securityDepositPct: 0.15,
price: undefined, // use market price if undefined
triggerPrice: undefined,
awaitFundsToTakeOffer: true,
offerId: undefined,
takerPaymentAccountId: undefined,
buyerSendsPayment: true,
sellerReceivesPayment: true,
resolveDispute: true, // resolve dispute after opening
disputeWinner: DisputeResult.Winner.SELLER,
disputeReason: DisputeResult.Reason.PEER_WAS_LATE,
disputeSummary: "Seller is winner",
walletSyncPeriodMs: 5000,
maxTimePeerNoticeMs: 5000,
testChatMessages: true,
stopOnFailure: false, // TODO: setting to true can cause error: Http response at 400 or 500 level, http status code: 503
testPayoutConfirmed: true,
testPayoutUnlocked: false,
maxConcurrency: getMaxConcurrency(),
isPrivateOffer: false,
buyerAsTakerWithoutDeposit: undefined
}
/**
* Configuration and context for a single trade.
*/
class TradeContext {
// trade peers
arbitrator!: Partial<PeerContext>;
maker!: Partial<PeerContext>;
taker!: Partial<PeerContext>;
// trade flow
concurrentTrades?: boolean; // testing trades at same time
makeOffer?: boolean;
takeOffer?: boolean;
buyerOfflineAfterTake?: boolean;
sellerOfflineAfterTake?: boolean;
buyerOfflineAfterPaymentSent?: boolean
buyerOfflineAfterDisputeOpened?: boolean;
sellerOfflineAfterDisputeOpened?: boolean;
sellerDisputeContext?: DisputeContext;
buyerDisputeContext?: DisputeContext;
buyerSendsPayment?: boolean;
sellerReceivesPayment?: boolean
// make offer
awaitFundsToMakeOffer?: boolean
direction?: OfferDirection;
assetCode?: string;
offerAmount?: bigint; // offer amount or max
offerMinAmount?: bigint;
tradeAmount?: bigint; // trade amount within offer range
makerPaymentAccountId?: string;
securityDepositPct?: number;
price?: number;
priceMargin?: number;
triggerPrice?: number;
reserveExactAmount?: boolean;
isPrivateOffer?: boolean;
buyerAsTakerWithoutDeposit?: boolean; // buyer as taker security deposit is optional for private offers
// take offer
awaitFundsToTakeOffer?: boolean;
offerId?: string;
takerPaymentAccountId?: string;
challenge?: string;
testTraderChat?: boolean;
// resolve dispute
resolveDispute?: boolean
disputeOpener?: SaleRole;
disputeWinner?: DisputeResult.Winner;
disputeReason?: DisputeResult.Reason;
disputeSummary?: string;
disputeWinnerAmount?: bigint;
// other context
offer?: OfferInfo;
index?: number;
isOfferTaken?: boolean;
isPaymentSent?: boolean;
isPaymentReceived?: boolean;
phase?: string;
payoutState?: string[];
disputeState?: string;
isCompleted?: boolean;
isPayoutPublished?: boolean; // TODO: test isDepositsPublished; etc
isPayoutConfirmed?: boolean;
isPayoutUnlocked?: boolean
buyerOpenedDispute?: boolean;
sellerOpenedDispute?: boolean;
walletSyncPeriodMs!: number;
maxTimePeerNoticeMs!: number;
testChatMessages!: boolean;
stopOnFailure?: boolean;
buyerAppName?: string;
sellerAppName?: string;
usedPorts?: string[];
testPayoutConfirmed?: boolean;
testPayoutUnlocked?: boolean;
payoutTxId?: string
testBalanceChangeEndToEnd?: boolean;
isStopped!: boolean;
maxConcurrency!: number;
constructor(ctx?: Partial<TradeContext>) {
Object.assign(this, ctx);
if (this.arbitrator) this.arbitrator = new PeerContext(this.arbitrator);
if (this.maker) this.maker = new PeerContext(this.maker);
if (this.taker) this.taker = new PeerContext(this.taker);
}
getMaker(): PeerContext {
return this.maker as PeerContext;
}
getTaker(): PeerContext {
return this.taker as PeerContext;
}
getBuyer(): PeerContext {
return (this.direction === OfferDirection.BUY ? this.maker : this.taker) as PeerContext;
}
getSeller(): PeerContext {
return (this.direction === OfferDirection.BUY ? this.taker : this.maker) as PeerContext;
}
isBuyerMaker(): boolean {
return this.direction === OfferDirection.BUY;
}
getDisputeOpener(): PeerContext | undefined {
if (this.disputeOpener === undefined) return undefined;
return this.disputeOpener === SaleRole.BUYER ? this.getBuyer() : this.getSeller();
}
getDisputePeer(): PeerContext | undefined {
if (this.disputeOpener === undefined) return undefined;
return this.disputeOpener === SaleRole.BUYER ? this.getSeller() : this.getBuyer();
}
getDisputeWinner(): PeerContext | undefined {
if (this.disputeWinner === undefined) return undefined;
return this.disputeWinner === DisputeResult.Winner.BUYER ? this.getBuyer() : this.getSeller();
}
getDisputeLoser(): PeerContext | undefined {
if (this.disputeWinner === undefined) return undefined;
return this.disputeWinner === DisputeResult.Winner.BUYER ? this.getSeller() : this.getBuyer();
}
isOfflineFlow() {
return this.buyerOfflineAfterDisputeOpened || this.sellerOfflineAfterDisputeOpened || this.buyerOfflineAfterPaymentSent || this.buyerOfflineAfterTake || this.sellerOfflineAfterTake;
}
getPhase() {
return this.isPaymentReceived ? "PAYMENT_RECEIVED" : this.isPaymentSent ? "PAYMENT_SENT" : "DEPOSITS_UNLOCKED";
}
hasBuyerAsTakerWithoutDeposit() {
return this.getBuyer() === this.getTaker() && this.buyerAsTakerWithoutDeposit;
}
static init(ctxP: Partial<TradeContext> | undefined): TradeContext {
let ctx = ctxP instanceof TradeContext ? ctxP : new TradeContext(ctxP);
if (!ctx.offerAmount && ctx.tradeAmount) ctx.offerAmount = ctx.tradeAmount;
if (!ctx.offerMinAmount && ctx.offerAmount) ctx.offerMinAmount = ctx.offerAmount;
Object.assign(ctx, new TradeContext(TestConfig.trade), Object.assign({}, ctx));
return ctx;
}
async toSummary(): Promise<string> {
let str: string = "";
str += "Type: Maker/" + (this.direction === OfferDirection.BUY ? "Buyer" : "Seller") + ", Taker/" + (this.direction === OfferDirection.BUY ? "Seller" : "Buyer");
str += "\nOffer id: " + this.offerId;
if (this.maker.havenod) str += "\nMaker uri: " + this.maker?.havenod?.getUrl();
if (this.taker.havenod) str += "\nTaker uri: " + this.taker?.havenod?.getUrl();
str += "\nAsset code: " + this.assetCode?.toUpperCase();
str += "\nMaker payment account id: " + this.makerPaymentAccountId;
str += "\nTaker payment account id: " + this.takerPaymentAccountId;
str += "\nTrade amount: " + this.tradeAmount;
str += "\nMin amount: " + this.offerMinAmount;
str += "\nMax amount: " + this.offerAmount;
str += "\nSecurity deposit percent: " + this.securityDepositPct;
str += "\nMaker balance before offer: " + this.maker.balancesBeforeOffer?.getBalance();
str += "\nMaker split output tx fee: " + this.maker.splitOutputTxFee;
if (this.offer) {
str += "\nMaker fee percent: " + this.offer!.getMakerFeePct();
str += "\nTaker fee percent: " + this.offer!.getTakerFeePct();
}
if (this.arbitrator && this.arbitrator!.trade) {
str += "\nMaker trade fee: " + this.arbitrator?.trade?.getMakerFee();
str += "\nMaker deposit tx id: " + this.arbitrator!.trade!.getMakerDepositTxId();
if (this.arbitrator!.trade!.getMakerDepositTxId()) {
let tx = await monerod.getTx(this.arbitrator!.trade!.getMakerDepositTxId());
str += "\nMaker deposit tx fee: " + (tx ? tx?.getFee() : undefined);
}
str += "\nMaker security deposit received: " + (this.direction == OfferDirection.BUY ? this.arbitrator!.trade!.getBuyerSecurityDeposit() : this.arbitrator!.trade!.getSellerSecurityDeposit());
}
str += "\nTaker balance before offer: " + this.taker.balancesBeforeOffer?.getBalance();
if (this.arbitrator && this.arbitrator!.trade) {
str += "\nTaker trade fee: " + this.arbitrator?.trade?.getTakerFee();
str += "\nTaker deposit tx id: " + this.arbitrator!.trade!.getTakerDepositTxId();
if (this.arbitrator!.trade!.getTakerDepositTxId()) {
let tx = await monerod.getTx(this.arbitrator!.trade!.getTakerDepositTxId());
str += "\nTaker deposit tx fee: " + (tx ? tx?.getFee() : undefined);
}
str += "\nTaker security deposit received: " + (this.direction == OfferDirection.BUY ? this.arbitrator!.trade!.getSellerSecurityDeposit() : this.arbitrator!.trade!.getBuyerSecurityDeposit());
if (this.disputeWinner) str += "\nDispute winner: " + (this.disputeWinner == DisputeResult.Winner.BUYER ? "Buyer" : "Seller");
str += "\nPayout tx id: " + this.payoutTxId;
if (this.payoutTxId) {
str += "\nPayout fee: " + (await monerod.getTx(this.payoutTxId!))!.getFee()!;
if (this.getBuyer().havenod) str += "\nBuyer payout: " + (await this.getBuyer().havenod!.getXmrTx(this.payoutTxId!))?.getIncomingTransfersList()[0].getAmount()!;
if (this.getSeller().havenod) str += "\nSeller payout: " + (await this.getSeller().havenod!.getXmrTx(this.payoutTxId!))?.getIncomingTransfersList()[0].getAmount()!;
}
}
str += "\nOffer json: " + JSON.stringify(this.offer?.toObject());
return str;
}
}
/**
* Default test configuration.
*/
const TestConfig = {
logLevel: 2,
baseCurrencyNetwork: getBaseCurrencyNetwork(),
networkType: getBaseCurrencyNetwork() == BaseCurrencyNetwork.XMR_MAINNET ? moneroTs.MoneroNetworkType.MAINNET : getBaseCurrencyNetwork() == BaseCurrencyNetwork.XMR_LOCAL ? moneroTs.MoneroNetworkType.TESTNET : moneroTs.MoneroNetworkType.STAGENET,
moneroBinsDir: "../haveno/.localnet",
testDataDir: "./testdata",
deferralMs: 25000,
haveno: {
path: "../haveno",
version: "1.0.16"
},
monerod: {
url: "http://localhost:" + getNetworkStartPort() + "8081", // 18081, 28081, 38081 for mainnet, testnet, and stagenet, respectively
username: "",
password: ""
},
monerod3: { // corresponds to monerod3-local in Makefile
url: "http://localhost:58081",
username: "superuser",
password: "abctesting123",
p2pBindPort: "58080",
rpcBindPort: "58081",
zmqRpcBindPort: "58082"
},
fundingWallet: {
url: "http://localhost:" + getNetworkStartPort() + "8084", // 18084, 28084, 38084 for mainnet, testnet, stagenet respectively
username: "rpc_user",
password: "abc123",
walletPassword: "abc123",
defaultPath: "funding_wallet-" + getBaseCurrencyNetwork(),
minimumFunding: 5000000000000n,
seed: "origin hickory pavements tudor sizes hornet tether segments sack technical elbow unsafe legion nitrogen adapt yearbook idols fuzzy pitched goes tusks elbow erase fossil erase",
primaryAddress: "9xSyMy1r9h3BVjMrF3CTqQCQy36yCfkpn7uVfMyTUbez3hhumqBUqGUNNALjcd7f1HJBRdeH82bCC3veFHW7z3xm28gug4d",
restoreHeight: 150
},
defaultHavenod: {
logProcessOutput: true, // log output for processes started by tests (except arbitrator, user1, and user2 which are configured separately)
logLevel: "info",
apiPassword: "apitest",
walletUsername: "haveno_user",
walletDefaultPassword: "password", // only used if account password not set
accountPasswordRequired: true,
accountPassword: "abctesting789",
autoLogin: true
},
startupHavenods: [{
appName: "haveno-" + getBaseCurrencyNetwork() + "_arbitrator", // arbritrator
logProcessOutput: true,
port: "8079",
accountPasswordRequired: false,
accountPassword: "abctesting123",
}, {
appName: "haveno-" + getBaseCurrencyNetwork() + "_user1", // user1
logProcessOutput: true,
port: "8080",
accountPasswordRequired: false,
accountPassword: "abctesting456",
walletUrl: "http://127.0.0.1:38091",
}, {
appName: "haveno-" + getBaseCurrencyNetwork() + "_user2", // user2
logProcessOutput: true,
port: "8081",
accountPasswordRequired: false,
accountPassword: "abctesting789",
walletUrl: "http://127.0.0.1:38092",
}
],
maxFee: HavenoUtils.xmrToAtomicUnits(0.5), // local testnet fees can be relatively high
minSecurityDeposit: moneroTs.MoneroUtils.xmrToAtomicUnits(0.1),
maxAdjustmentPct: 0.2,
daemonPollPeriodMs: 5000,
maxWalletStartupMs: 10000, // TODO (woodser): make shorter by switching to jni
maxCpuPct: 0.25,
paymentMethods: Object.keys(PaymentAccountForm.FormId), // all supported payment methods
assetCodes: ["USD", "GBP", "EUR", "ETH", "BTC", "BCH", "LTC", "USDT-ERC20", "USDT-TRC20", "USDC-ERC20"], // crypto asset codes
fixedPriceAssetCodes: ["XAG", "XAU", "XGB"],
cryptoAddresses: [{
currencyCode: "ETH",
address: "0xdBdAb835Acd6fC84cF5F9aDD3c0B5a1E25fbd99f"
}, {
currencyCode: "BTC",
address: "1G457efxTyci67msm2dSqyhFzxPYFWaghe"
}, {
currencyCode: "BCH",
address: "qz54ydhwzn25wzf8pge5s26udvtx33yhyq3lnv6vq6"
}, {
currencyCode: "LTC",
address: "LXUTUN5mTPc2LsS7cEjkyjTRcfYyJGoUuQ"
}, {
currencyCode: "USDT-ERC20",
address: "0x9Fc17f65060080491c09e879dE8C7cc6dC72Fed7"
}, {
currencyCode: "USDT-TRC20",
address: "TVnmu3E6DYVL4bpAoZnPNEPVUrgC7eSWaX"
}, {
currencyCode: "USDC-ERC20",
address: "0x1165cE9056620C9012D098103a08267e3c48B86B"
}
],
ports: new Map<string, string[]>([ // map http ports to havenod api and p2p ports
["8079", ["9998", "4444"]], // arbitrator
["8080", ["9999", "5555"]], // user1
["8081", ["10000", "6666"]], // user2
["8082", ["10001", "7777"]],
["8083", ["10002", "7778"]],
["8084", ["10003", "7779"]],
["8085", ["10004", "7780"]],
["8086", ["10005", "7781"]],
]),
arbitratorPrivKeys: {
XMR_LOCAL: ["6ac43ea1df2a290c1c8391736aa42e4339c5cb4f110ff0257a13b63211977b7a", "d96c4e7be030564cfa64a4040060574a8e92a79f574104ab8bb0c1166db28047", "6d5c86cbc5fc7ce3c97b06969661eae5c018cb2923856cc51341d182a45d1e9d"],
XMR_STAGENET: ["1aa111f817b7fdaaec1c8d5281a1837cc71c336db09b87cf23344a0a4e3bb2cb", "6b5a404eb5ff7154f2357126c84c3becfe2e7c59ca3844954ce9476bec2a6228", "fd4ef301a2e4faa3c77bc26393919895fa29b0908f2bbd51f6f6de3e46fb7a6e"],
XMR_MAINNET: []
},
tradeStepTimeoutMs: getBaseCurrencyNetwork() === BaseCurrencyNetwork.XMR_LOCAL ? 60000 : 180000,
testTimeout: getBaseCurrencyNetwork() === BaseCurrencyNetwork.XMR_LOCAL ? 2400000 : 5400000, // timeout in ms for each test to complete (40 minutes for private network, 90 minutes for public network)
trade: new TradeContext(defaultTradeConfig)
};
interface HavenodContext {
logProcessOutput?: boolean,
logLevel?: string,
apiPassword?: string,
walletUsername?: string,
walletDefaultPassword?: string,
accountPasswordRequired?: boolean,
accountPassword?: string,
autoLogin?: boolean,
appName?: string,
port?: string,
excludePorts?: string[],
walletUrl?: string
}
interface TxContext {
isCreatedTx: boolean;
}
// track started haveno processes
const HAVENO_CLIENTS: HavenoClient[] = [];
const HAVENO_PROCESS_PORTS: string[] = [];
const HAVENO_WALLETS: Map<HavenoClient, any> = new Map<HavenoClient, any>();
// other config
const OFFLINE_ERR_MSG = "Http response at 400 or 500 level";
function getMaxConcurrency() {
return isGitHubActions() ? 4 : 20;
}
function isGitHubActions() {
return process.env.GITHUB_ACTIONS === 'true';
}
// -------------------------- BEFORE / AFTER TESTS ----------------------------
jest.setTimeout(TestConfig.testTimeout);
beforeEach(async () => {
HavenoUtils.log(0, "BEFORE TEST \"" + expect.getState().currentTestName + "\"");
});
beforeAll(async () => {
try {
// set log level for tests
HavenoUtils.setLogLevel(TestConfig.logLevel);
// initialize funding wallet
HavenoUtils.log(0, "Initializing funding wallet");
await initFundingWallet();
HavenoUtils.log(0, "Funding wallet balance: " + await fundingWallet.getBalance());
HavenoUtils.log(0, "Funding wallet unlocked balance: " + await fundingWallet.getUnlockedBalance());
const subaddress = await fundingWallet.createSubaddress(0);
HavenoUtils.log(0, "Funding wallet height: " + await fundingWallet.getHeight());
HavenoUtils.log(0, "Funding wallet seed: " + await fundingWallet.getSeed());
HavenoUtils.log(0, "Funding wallet primary address: " + await fundingWallet.getPrimaryAddress());
HavenoUtils.log(0, "Funding wallet new subaddress: " + subaddress.getAddress());
// initialize monerod
try {
monerod = await moneroTs.connectToDaemonRpc(TestConfig.monerod.url, TestConfig.monerod.username, TestConfig.monerod.password);
await mineToHeight(160); // initialize blockchain to latest block type
} catch (err: any) {
HavenoUtils.log(0, "Error initializing internal monerod: " + err.message); // allowed in order to test starting and stopping local node
}
// start configured haveno daemons
const startupHavenods: HavenoClient[] = [];
const promises: Promise<HavenoClient>[] = [];
let err;
for (const config of TestConfig.startupHavenods) promises.push(initHaveno(config));
for (const settledPromise of await Promise.allSettled(promises)) {
if (settledPromise.status === "fulfilled") {
startupHavenods.push((settledPromise as PromiseFulfilledResult<HavenoClient>).value);
startupHavenodUrls.push(startupHavenods[startupHavenods.length - 1].getUrl());
}
else if (!err) err = new Error((settledPromise as PromiseRejectedResult).reason);
}
if (err) throw err;
// assign arbitrator, user1, user2
arbitrator = startupHavenods[0];
user1 = startupHavenods[1];
user2 = startupHavenods[2];
TestConfig.trade.arbitrator.havenod = arbitrator;
TestConfig.trade.maker.havenod = user1;
TestConfig.trade.taker.havenod = user2;
// connect client wallets
user1Wallet = await moneroTs.connectToWalletRpc(TestConfig.startupHavenods[1].walletUrl!, TestConfig.defaultHavenod.walletUsername, TestConfig.startupHavenods[1].accountPasswordRequired ? TestConfig.startupHavenods[1].accountPassword : TestConfig.defaultHavenod.walletDefaultPassword);
user2Wallet = await moneroTs.connectToWalletRpc(TestConfig.startupHavenods[2].walletUrl!, TestConfig.defaultHavenod.walletUsername, TestConfig.startupHavenods[2].accountPasswordRequired ? TestConfig.startupHavenods[2].accountPassword : TestConfig.defaultHavenod.walletDefaultPassword);
// register arbitrator dispute agent
await arbitrator.registerDisputeAgent("arbitrator", getArbitratorPrivKey(0));
// create test data directory if it doesn't exist
if (!fs.existsSync(TestConfig.testDataDir)) fs.mkdirSync(TestConfig.testDataDir);
} catch (err) {
await shutDown();
throw err;
}
});
afterEach(async () => {
// collect unreleased clients
const unreleasedClients: HavenoClient[] = [];
for (const havenod of HAVENO_CLIENTS.slice()) {
if (!moneroTs.GenUtils.arrayContains(startupHavenodUrls, havenod.getUrl())) {
unreleasedClients.push(havenod);
}
}
// release clients
if (unreleasedClients.length > 0) {
const promises: Promise<void>[] = [];
HavenoUtils.log(0, unreleasedClients.length + " Haveno clients were not released after test \"" + expect.getState().currentTestName + "\", releasing...");
for (const client of unreleasedClients) {
HavenoUtils.log(0, "\tUnreleased Haveno client: " + client.getUrl());
promises.push(releaseHavenoClient(client));
}
await Promise.all(promises);
HavenoUtils.log(0, "Done releasing " + unreleasedClients.length + " unreleased Haveno clients");
}
});
afterAll(async () => {
await shutDown();
});
async function shutDown() {
// release all clients
const promises: Promise<void>[] = [];
for (const client of HAVENO_CLIENTS.slice()) {
promises.push(releaseHavenoClient(client));
}
await Promise.all(promises);
// terminate monero-ts worker
await moneroTs.LibraryUtils.terminateWorker();
}
// ----------------------------------- TESTS ----------------------------------
test("Can get the version (CI)", async () => {
const version = await arbitrator.getVersion();
expect(version).toEqual(TestConfig.haveno.version);
});
test("Can convert between XMR and atomic units (CI)", async () => {
expect(BigInt(250000000000)).toEqual(HavenoUtils.xmrToAtomicUnits(0.25));
expect(HavenoUtils.atomicUnitsToXmr("250000000000")).toEqual(.25);
expect(HavenoUtils.atomicUnitsToXmr(250000000000n)).toEqual(.25);
});
test("Can manage an account (CI)", async () => {
let user3: HavenoClient|undefined;
let err: any;
try {
// start user3 without opening account
user3 = await initHaveno({autoLogin: false});
assert(!await user3.accountExists());
// test errors when account not open
await testAccountNotOpen(user3);
// create account
let password = "testPassword";
await user3.createAccount(password);
if (await user3.isConnectedToMonero()) await user3.getBalances(); // only connected if local node running
assert(await user3.accountExists());
assert(await user3.isAccountOpen());
// create payment account
const paymentAccount = await user3.createCryptoPaymentAccount("My ETH account", TestConfig.cryptoAddresses[0].currencyCode, TestConfig.cryptoAddresses[0].address);
// close account
await user3.closeAccount();
assert(await user3.accountExists());
assert(!await user3.isAccountOpen());
await testAccountNotOpen(user3);
// open account with wrong password
try {
await user3.openAccount("wrongPassword");
throw new Error("Should have failed opening account with wrong password");
} catch (err: any) {
assert.equal(err.message, "Incorrect password");
}
// open account
await user3.openAccount(password);
assert(await user3.accountExists());
assert(await user3.isAccountOpen());
// restart user3
const user3Config = {appName: user3.getAppName(), autoLogin: false}
await releaseHavenoProcess(user3);
user3 = await initHaveno(user3Config);
assert(await user3.accountExists());
assert(!await user3.isAccountOpen());
// open account
await user3.openAccount(password);
assert(await user3.accountExists());
assert(await user3.isAccountOpen());
// try changing incorrect password
try {
await user3.changePassword("wrongPassword", "abc123");
throw new Error("Should have failed changing wrong password");
} catch (err: any) {
assert.equal(err.message, "Incorrect password");
}
// try setting password below minimum length
try {
await user3.changePassword(password, "abc123");
throw new Error("Should have failed setting password below minimum length")
} catch (err: any) {
assert.equal(err.message, "Password must be at least 8 characters");
}
// change password
const newPassword = "newPassword";
await user3.changePassword(password, newPassword);
password = newPassword;
assert(await user3.accountExists());
assert(await user3.isAccountOpen());
// restart user3
await releaseHavenoProcess(user3);
user3 = await initHaveno(user3Config);
await testAccountNotOpen(user3);
// open account
await user3.openAccount(password);
assert(await user3.accountExists());
assert(await user3.isAccountOpen());
// backup account to zip file
const zipFile = TestConfig.testDataDir + "/backup.zip";
const stream = fs.createWriteStream(zipFile);
const size = await user3.backupAccount(stream);
stream.end();
assert(size > 0);
// delete account and wait until connected
await user3.deleteAccount();
HavenoUtils.log(1, "Waiting to be connected to havenod after deleting account"); // TODO: build this into deleteAccount
do { await wait(1000); }
while(!await user3.isConnectedToDaemon());
HavenoUtils.log(1, "Reconnecting to havenod");
assert(!await user3.accountExists());
// restore account
const zipBytes: Uint8Array = new Uint8Array(fs.readFileSync(zipFile));
await user3.restoreAccount(zipBytes);
do { await wait(1000); }
while(!await user3.isConnectedToDaemon());
assert(await user3.accountExists());
// open restored account
await user3.openAccount(password);
assert(await user3.isAccountOpen());
// check the persisted payment account
const paymentAccount2 = await user3.getPaymentAccount(paymentAccount.getId());
testCryptoPaymentAccountsEqual(paymentAccount, paymentAccount2);
} catch (err2) {
err = err2;
}
// stop and delete instances
if (user3) await releaseHavenoProcess(user3, true);
if (err) throw err;
async function testAccountNotOpen(havenod: HavenoClient): Promise<void> { // TODO: generalize this?
try { await havenod.getMoneroConnections(); throw new Error("Should have thrown"); }
catch (err: any) { assert.equal(err.message, "Account not open"); }
try { await havenod.getXmrTxs(); throw new Error("Should have thrown"); }
catch (err: any) { assert.equal(err.message, "Account not open"); }
try { await havenod.getBalances(); throw new Error("Should have thrown"); }
catch (err: any) { assert.equal(err.message, "Account not open"); }
try { await havenod.createCryptoPaymentAccount("My ETH account", TestConfig.cryptoAddresses[0].currencyCode, TestConfig.cryptoAddresses[0].address); throw new Error("Should have thrown"); }
catch (err: any) { assert.equal(err.message, "Account not open"); }
}
});
test("Can manage Monero daemon connections (CI)", async () => {
let monerod3: moneroTs.MoneroDaemonRpc | undefined = undefined;
let user3: HavenoClient|undefined;
let err: any;
try {
// start user3
user3 = await initHaveno();
// disable auto switch for tests
assert.equal(true, await user3.getAutoSwitch());
await user3.setAutoSwitch(false);
// test default connections
const monerodUrl1 = "http://127.0.0.1:" + getNetworkStartPort() + "8081"; // TODO: (woodser): move to config
let connections: UrlConnection[] = await user3.getMoneroConnections();
testConnection(getConnection(connections, monerodUrl1)!, monerodUrl1, OnlineStatus.ONLINE, AuthenticationStatus.AUTHENTICATED, 1);
// test default connection
let connection: UrlConnection|undefined = await user3.getMoneroConnection();
assert(await user3.isConnectedToMonero());
testConnection(connection!, monerodUrl1, OnlineStatus.ONLINE, AuthenticationStatus.AUTHENTICATED, 1); // TODO: should be no authentication?
// add a new connection
const fooBarUrl = "http://foo.bar";
await user3.addMoneroConnection(fooBarUrl);
connections = await user3.getMoneroConnections();
connection = getConnection(connections, fooBarUrl);
testConnection(connection!, fooBarUrl, OnlineStatus.UNKNOWN, AuthenticationStatus.NO_AUTHENTICATION, 0);
// set prioritized connection without credentials
await user3.setMoneroConnection(new UrlConnection()
.setUrl(TestConfig.monerod3.url)
.setPriority(1));
connection = await user3.getMoneroConnection();
testConnection(connection!, TestConfig.monerod3.url, undefined, undefined, 1); // status may or may not be known due to periodic connection checking
// connection is offline
connection = await user3.checkMoneroConnection();
assert(!await user3.isConnectedToMonero());
testConnection(connection!, TestConfig.monerod3.url, OnlineStatus.OFFLINE, AuthenticationStatus.NO_AUTHENTICATION, 1);
// start monerod3
const cmd = [
TestConfig.moneroBinsDir + "/monerod",
"--no-igd",
"--hide-my-port",
"--data-dir", TestConfig.moneroBinsDir + "/" + TestConfig.baseCurrencyNetwork.toLowerCase() + "/node3",
"--p2p-bind-ip", "127.0.0.1",
"--p2p-bind-port", TestConfig.monerod3.p2pBindPort,
"--rpc-bind-port", TestConfig.monerod3.rpcBindPort,
"--zmq-rpc-bind-port", TestConfig.monerod3.zmqRpcBindPort,
"--log-level", "0",
"--confirm-external-bind",
"--rpc-access-control-origins", "http://localhost:8080",
"--fixed-difficulty", "500",
"--disable-rpc-ban"
];
if (getBaseCurrencyNetwork() !== BaseCurrencyNetwork.XMR_MAINNET) cmd.push("--" + moneroTs.MoneroNetworkType.toString(TestConfig.networkType).toLowerCase());
if (TestConfig.monerod3.username) cmd.push("--rpc-login", TestConfig.monerod3.username + ":" + TestConfig.monerod3.password);
monerod3 = await moneroTs.connectToDaemonRpc(cmd);
// connection is online and not authenticated
connection = await user3.checkMoneroConnection();
assert(!await user3.isConnectedToMonero());
testConnection(connection!, TestConfig.monerod3.url, OnlineStatus.ONLINE, AuthenticationStatus.NOT_AUTHENTICATED, 1);
// set connection credentials
await user3.setMoneroConnection(new UrlConnection()
.setUrl(TestConfig.monerod3.url)
.setUsername(TestConfig.monerod3.username)
.setPassword(TestConfig.monerod3.password)
.setPriority(1));
connection = await user3.getMoneroConnection();
testConnection(connection!, TestConfig.monerod3.url, undefined, undefined, 1);
// connection is online and authenticated
connection = await user3.checkMoneroConnection();
assert(await user3.isConnectedToMonero());
testConnection(connection!, TestConfig.monerod3.url, OnlineStatus.ONLINE, AuthenticationStatus.AUTHENTICATED, 1);
// change account password
const newPassword = "newPassword";
await user3.changePassword(TestConfig.defaultHavenod.accountPassword, newPassword);
// restart user3
const appName = user3.getAppName();
await releaseHavenoProcess(user3);
user3 = await initHaveno({appName: appName, accountPassword: newPassword});
// connection is restored, online, and authenticated
await user3.checkMoneroConnection();
connection = await user3.getMoneroConnection();
testConnection(connection!, TestConfig.monerod3.url, OnlineStatus.ONLINE, AuthenticationStatus.AUTHENTICATED, 1);
// priority connections are polled
await user3.checkMoneroConnections();
connections = await user3.getMoneroConnections();
testConnection(getConnection(connections, monerodUrl1)!, monerodUrl1, OnlineStatus.ONLINE, AuthenticationStatus.AUTHENTICATED, 1);
// enable auto switch
await user3.setAutoSwitch(true);
assert.equal(true, await user3.getAutoSwitch());
// stop monerod
//await monerod3.stopProcess(); // TODO (monero-ts): monerod remains available after await monerod.stopProcess() for up to 40 seconds
await moneroTs.GenUtils.killProcess(monerod3.getProcess(), "SIGKILL");
// test auto switch after periodic connection check
await wait(TestConfig.daemonPollPeriodMs * 2);
await user3.checkMoneroConnection();
connection = await user3.getMoneroConnection();
testConnection(connection!, monerodUrl1, OnlineStatus.ONLINE, AuthenticationStatus.AUTHENTICATED, 1);
// stop auto switch and checking connection periodically
await user3.setAutoSwitch(false);
assert.equal(false, await user3.getAutoSwitch());
await user3.stopCheckingConnection();
// remove current connection
await user3.removeMoneroConnection(monerodUrl1);
// check current connection
connection = await user3.checkMoneroConnection();
assert.equal(connection, undefined);
// check all connections
await user3.checkMoneroConnections();
connections = await user3.getMoneroConnections();
testConnection(getConnection(connections, fooBarUrl)!, fooBarUrl, OnlineStatus.OFFLINE, AuthenticationStatus.NO_AUTHENTICATION, 0);
// set connection to previous url
await user3.setMoneroConnection(fooBarUrl);
connection = await user3.getMoneroConnection();
testConnection(connection!, fooBarUrl, OnlineStatus.OFFLINE, AuthenticationStatus.NO_AUTHENTICATION, 0);
// set connection to new url
const fooBarUrl2 = "http://foo.bar.xyz";
await user3.setMoneroConnection(fooBarUrl2);
connections = await user3.getMoneroConnections();
connection = getConnection(connections, fooBarUrl2);
testConnection(connection!, fooBarUrl2, OnlineStatus.UNKNOWN, AuthenticationStatus.NO_AUTHENTICATION, 0);
// reset connection
await user3.setMoneroConnection();
assert.equal(await user3.getMoneroConnection(), undefined);
// test auto switch after start checking connection
await user3.setAutoSwitch(false);
await user3.startCheckingConnection(5000); // checks the connection
await user3.setAutoSwitch(true);
await user3.addMoneroConnection(new UrlConnection()
.setUrl(TestConfig.monerod.url)
.setUsername(TestConfig.monerod.username)
.setPassword(TestConfig.monerod.password)
.setPriority(2));
await wait(10000);
connection = await user3.getMoneroConnection();
testConnection(connection!, TestConfig.monerod.url, OnlineStatus.ONLINE, AuthenticationStatus.AUTHENTICATED, 2);
} catch (err2) {
err = err2;
}
// stop processes
if (user3) await releaseHavenoProcess(user3, true);
if (monerod3) await monerod3.stopProcess();
if (err) throw err;
});
// NOTE: To run full test, the following conditions must be met:
// - monerod1-local must be stopped
// - monerod2-local must be running
// - user1-daemon-local must be running and own its monerod process (so it can be stopped)
test("Can start and stop a local Monero node (CI)", async() => {
// expect error stopping stopped local node
try {
await user1.stopMoneroNode();
HavenoUtils.log(1, "Running local Monero node stopped");
await user1.stopMoneroNode(); // stop 2nd time to force error
throw new Error("should have thrown");
} catch (err: any) {
if (err.message !== "Local Monero node is not running" &&
err.message !== "Cannot stop local Monero node because we don't own its process") {
throw new Error("Unexpected error: " + err.message);
}
}
if (await user1.isMoneroNodeOnline()) {
HavenoUtils.log(0, "Warning: local Monero node is already running, skipping start and stop local Monero node tests");
// expect error due to existing running node
const newSettings = new XmrNodeSettings();
try {
await user1.startMoneroNode(newSettings);
throw new Error("should have thrown");
} catch (err: any) {
if (err.message !== "Local Monero node already online") throw new Error("Unexpected error: " + err.message);
}
} else {
// expect error when passing in bad arguments
const badSettings = new XmrNodeSettings();
badSettings.setStartupFlagsList(["--invalid-flag"]);
try {
await user1.startMoneroNode(badSettings);
throw new Error("should have thrown");
} catch (err: any) {
if (!err.message.startsWith("Failed to start monerod:")) throw new Error("Unexpected error: ");
}
// expect successful start with custom settings
const connectionsBefore = await user1.getMoneroConnections();
const settings: XmrNodeSettings = new XmrNodeSettings();
const dataDir = TestConfig.moneroBinsDir + "/" + TestConfig.baseCurrencyNetwork.toLowerCase() + "/node1";
const logFile = dataDir + "/test.log";
settings.setBlockchainPath(dataDir);
settings.setStartupFlagsList(["--log-file", logFile, "--no-zmq"]);
await user1.startMoneroNode(settings);
assert(await user1.isMoneroNodeOnline());
// expect settings are updated
const settingsAfter = await user1.getMoneroNodeSettings();
testMoneroNodeSettingsEqual(settings, settingsAfter!);
// expect connection to local monero node to succeed
let daemon = await moneroTs.connectToDaemonRpc(TestConfig.monerod.url, "superuser", "abctesting123");
let height = await daemon.getHeight();