/
AdvancedReOrgTests.swift
1436 lines (1196 loc) · 53 KB
/
AdvancedReOrgTests.swift
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
//
// AdvancedReOrgTests.swift
// ZcashLightClientKit-Unit-Tests
//
// Created by Francisco Gindre on 5/14/20.
//
import Combine
import XCTest
@testable import TestUtils
@testable import ZcashLightClientKit
class AdvancedReOrgTests: ZcashTestCase {
let sendAmount = Zatoshi(1000)
var birthday: BlockHeight = 663150
let defaultLatestHeight: BlockHeight = 663175
var coordinator: TestCoordinator!
var syncedExpectation = XCTestExpectation(description: "synced")
var sentTransactionExpectation = XCTestExpectation(description: "sent")
var expectedReorgHeight: BlockHeight = 665188
var expectedRewindHeight: BlockHeight = 665188
var reorgExpectation = XCTestExpectation(description: "reorg")
let branchID = "2bb40e60"
let chainName = "main"
let network = DarksideWalletDNetwork()
var cancellables: [AnyCancellable] = []
override func setUp() async throws {
try await super.setUp()
// don't use an exact birthday, users never do.
self.coordinator = try await TestCoordinator(
container: mockContainer,
walletBirthday: birthday + 50,
network: network
)
try await coordinator.reset(
saplingActivation: 663150,
startSaplingTreeSize: 128607,
startOrchardTreeSize: 0,
branchID: self.branchID,
chainName: self.chainName
)
}
override func tearDown() async throws {
try await super.tearDown()
let coordinator = self.coordinator!
self.coordinator = nil
cancellables = []
try await coordinator.stop()
try? FileManager.default.removeItem(at: coordinator.databases.fsCacheDbRoot)
try? FileManager.default.removeItem(at: coordinator.databases.dataDB)
}
func handleReorg(event: CompactBlockProcessor.Event) {
guard case let .handledReorg(reorgHeight, rewindHeight) = event else { return XCTFail("empty reorg event") }
logger.debug("--- REORG DETECTED \(reorgHeight)--- RewindHeight: \(rewindHeight)", file: #file, function: #function, line: #line)
XCTAssertEqual(reorgHeight, expectedReorgHeight)
reorgExpectation.fulfill()
}
/// pre-condition: know balances before tx at received_Tx_height arrives
/// 1. Setup w/ default dataset
/// 2. applyStaged(received_Tx_height)
/// 3. sync up to received_Tx_height
/// 3a. verify that balance is previous balance + tx amount
/// 4. get that transaction hex encoded data
/// 5. stage 5 empty blocks w/heights received_Tx_height to received_Tx_height + 3
/// 6. stage tx at received_Tx_height + 3
/// 6a. applyheight(received_Tx_height + 1)
/// 7. sync to received_Tx_height + 1
/// 8. assert that reorg happened at received_Tx_height
/// 9. verify that balance equals initial balance
/// 10. sync up to received_Tx_height + 3
/// 11. verify that balance equals initial balance + tx amount
func testReOrgChangesInboundTxMinedHeight() async throws {
await hookToReOrgNotification()
try FakeChainBuilder.buildChain(darksideWallet: coordinator.service, branchID: branchID, chainName: chainName)
var shouldContinue = false
let receivedTxHeight: BlockHeight = 663188
var initialTotalBalance = Zatoshi(-1)
var initialVerifiedBalance = Zatoshi(-1)
self.expectedReorgHeight = receivedTxHeight + 1
/*
precondition:know balances before tx at received_Tx_height arrives
*/
try coordinator.applyStaged(blockheight: receivedTxHeight - 1)
sleep(3)
let preTxExpectation = XCTestExpectation(description: "pre receive")
var synchronizer: SDKSynchronizer?
do {
try await coordinator.sync(
completion: { synchro in
synchronizer = synchro
initialVerifiedBalance = try await synchro.getAccountBalance()?.saplingBalance.spendableValue ?? .zero
initialTotalBalance = try await synchro.getAccountBalance()?.saplingBalance.total() ?? .zero
preTxExpectation.fulfill()
shouldContinue = true
},
error: self.handleError
)
} catch {
await handleError(error)
}
await fulfillment(of: [preTxExpectation], timeout: 10)
guard shouldContinue else {
XCTFail("pre receive sync failed")
return
}
/*
2. applyStaged(received_Tx_height)
*/
try coordinator.applyStaged(blockheight: receivedTxHeight)
sleep(2)
/*
3. sync up to received_Tx_height
*/
let receivedTxExpectation = XCTestExpectation(description: "received tx")
var receivedTxTotalBalance = Zatoshi(-1)
var receivedTxVerifiedBalance = Zatoshi(-1)
do {
try await coordinator.sync(
completion: { synchro in
synchronizer = synchro
receivedTxVerifiedBalance = try await synchro.getAccountBalance()?.saplingBalance.spendableValue ?? .zero
receivedTxTotalBalance = try await synchro.getAccountBalance()?.saplingBalance.total() ?? .zero
receivedTxExpectation.fulfill()
}, error: self.handleError
)
} catch {
await handleError(error)
}
sleep(2)
await fulfillment(of: [receivedTxExpectation], timeout: 10)
guard let syncedSynchronizer = synchronizer else {
XCTFail("nil synchronizer")
return
}
sleep(5)
guard let receivedTx = await syncedSynchronizer.receivedTransactions.first, receivedTx.minedHeight == receivedTxHeight else {
XCTFail("did not receive transaction")
return
}
/*
3a. verify that balance is previous balance + tx amount
*/
XCTAssertEqual(receivedTxTotalBalance, initialTotalBalance + receivedTx.value)
XCTAssertEqual(receivedTxVerifiedBalance, initialVerifiedBalance)
/*
4. get that transaction hex encoded data
*/
let receivedTxData = receivedTx.raw ?? Data()
let receivedRawTx = RawTransaction.with { rawTx in
rawTx.height = UInt64(receivedTxHeight)
rawTx.data = receivedTxData
}
/*
5. stage 5 empty blocks w/heights received_Tx_height to received_Tx_height + 4
*/
try coordinator.stageBlockCreate(height: receivedTxHeight, count: 5)
/*
6. stage tx at received_Tx_height + 3
*/
let reorgedTxheight = receivedTxHeight + 2
try coordinator.stageTransaction(receivedRawTx, at: reorgedTxheight)
/*
6a. applyheight(received_Tx_height + 1)
*/
try coordinator.applyStaged(blockheight: receivedTxHeight + 1)
sleep(2)
/*
7. sync to received_Tx_height + 1
*/
let reorgSyncexpectation = XCTestExpectation(description: "reorg expectation")
var afterReorgTxTotalBalance = Zatoshi(-1)
var afterReorgTxVerifiedBalance = Zatoshi(-1)
do {
try await coordinator.sync(
completion: { synchronizer in
afterReorgTxTotalBalance = try await synchronizer.getAccountBalance()?.saplingBalance.total() ?? .zero
afterReorgTxVerifiedBalance = try await synchronizer.getAccountBalance()?.saplingBalance.spendableValue ?? .zero
reorgSyncexpectation.fulfill()
},
error: self.handleError
)
} catch {
await handleError(error)
}
/*
8. assert that reorg happened at received_Tx_height
*/
sleep(2)
await fulfillment(of: [reorgExpectation, reorgSyncexpectation], timeout: 5, enforceOrder: false)
/*
9. verify that balance equals initial balance
*/
XCTAssertEqual(afterReorgTxVerifiedBalance, initialVerifiedBalance)
XCTAssertEqual(afterReorgTxTotalBalance, initialTotalBalance)
/*
10. sync up to received_Tx_height + 3
*/
let finalsyncExpectation = XCTestExpectation(description: "final sync")
var finalReorgTxTotalBalance = Zatoshi(-1)
var finalReorgTxVerifiedBalance = Zatoshi(-1)
try coordinator.applyStaged(blockheight: reorgedTxheight + 1)
sleep(3)
do {
try await coordinator.sync(
completion: { synchronizer in
finalReorgTxTotalBalance = try await synchronizer.getAccountBalance()?.saplingBalance.total() ?? .zero
finalReorgTxVerifiedBalance = try await synchronizer.getAccountBalance()?.saplingBalance.spendableValue ?? .zero
finalsyncExpectation.fulfill()
},
error: self.handleError
)
} catch {
await handleError(error)
}
await fulfillment(of: [finalsyncExpectation], timeout: 5)
sleep(3)
guard let reorgedTx = await coordinator.synchronizer.receivedTransactions.first else {
XCTFail("no transactions found")
return
}
XCTAssertEqual(reorgedTx.minedHeight, reorgedTxheight)
XCTAssertEqual(initialVerifiedBalance, finalReorgTxVerifiedBalance)
XCTAssertEqual(initialTotalBalance + receivedTx.value, finalReorgTxTotalBalance)
}
/// An outbound, unconfirmed transaction in a specific block changes height in the event of a reorg
///
///
/// The wallet handles this change, reflects it appropriately in local storage, and funds remain spendable post confirmation.
///
/// Pre-conditions:
/// - Wallet has spendable funds
///
/// 1. Setup w/ default dataset
/// 2. applyStaged(received_Tx_height)
/// 3. sync up to received_Tx_height
/// 4. create transaction
/// 5. stage 10 empty blocks
/// 6. submit tx at sentTxHeight
/// a. getIncomingTx
/// b. stageTransaction(sentTx, sentTxHeight)
/// c. applyheight(sentTxHeight + 1 )
/// 7. sync to sentTxHeight + 2
/// 8. stage sentTx and otherTx at sentTxheight
/// 9. applyStaged(sentTx + 2)
/// 10. sync up to received_Tx_height + 2
/// 11. verify that the sent tx is mined and balance is correct
/// 12. applyStaged(sentTx + 10)
/// 13. verify that there's no more pending transaction
func testReorgChangesOutboundTxIndex() async throws {
try FakeChainBuilder.buildChain(darksideWallet: self.coordinator.service, branchID: branchID, chainName: chainName)
let receivedTxHeight: BlockHeight = 663188
var initialTotalBalance = Zatoshi(-1)
/*
2. applyStaged(received_Tx_height)
*/
try coordinator.applyStaged(blockheight: receivedTxHeight)
sleep(2)
let preTxExpectation = XCTestExpectation(description: "pre receive")
/*
3. sync up to received_Tx_height
*/
do {
try await coordinator.sync(
completion: { synchronizer in
initialTotalBalance = try await synchronizer.getAccountBalance()?.saplingBalance.total() ?? .zero
preTxExpectation.fulfill()
},
error: self.handleError
)
} catch {
await handleError(error)
}
await fulfillment(of: [preTxExpectation], timeout: 5)
let sendExpectation = XCTestExpectation(description: "sendToAddress")
var pendingEntity: ZcashTransaction.Overview?
var testError: Error?
let sendAmount = Zatoshi(10000)
/*
4. create transaction
*/
do {
let pendingTx = try await coordinator.synchronizer.sendToAddress(
spendingKey: coordinator.spendingKey,
zatoshi: sendAmount,
toAddress: try Recipient(Environment.testRecipientAddress, network: self.network.networkType),
memo: try Memo(string: "test transaction")
)
pendingEntity = pendingTx
sendExpectation.fulfill()
} catch {
testError = error
XCTFail("error sending to address. Error: \(String(describing: error))")
}
await fulfillment(of: [sendExpectation], timeout: 2)
guard let pendingTx = pendingEntity else {
XCTFail("error sending to address. Error: \(String(describing: testError))")
return
}
/*
5. stage 10 empty blocks
*/
try coordinator.stageBlockCreate(height: receivedTxHeight + 1, count: 10)
let sentTxHeight = receivedTxHeight + 1
/*
6. stage sent tx at sentTxHeight
*/
guard let sentTx = try coordinator.getIncomingTransactions()?.first else {
XCTFail("sent transaction not present on Darksidewalletd")
return
}
try coordinator.stageTransaction(sentTx, at: sentTxHeight)
/*
6a. applyheight(sentTxHeight + 1 )
*/
try coordinator.applyStaged(blockheight: sentTxHeight + 1)
sleep(2)
// TODO: [#1247] needs to review this to properly solve, https://github.com/zcash/ZcashLightClientKit/issues/1247
/*
7. sync to sentTxHeight + 1
*/
// let sentTxSyncExpectation = XCTestExpectation(description: "sent tx sync expectation")
//
// do {
// try await coordinator.sync(
// completion: { synchronizer in
// let pMinedHeight = await synchronizer.pendingTransactions.first?.minedHeight
// XCTAssertEqual(pMinedHeight, sentTxHeight)
// sentTxSyncExpectation.fulfill()
// },
// error: self.handleError
// )
// } catch {
// await handleError(error)
// }
//
// await fulfillment(of: [sentTxSyncExpectation], timeout: 5)
/*
8. stage sentTx and otherTx at sentTxheight
*/
try coordinator.stageBlockCreate(height: sentTxHeight, count: 20, nonce: 5)
try coordinator.stageTransaction(url: FakeChainBuilder.someOtherTxUrl, at: sentTxHeight)
try coordinator.stageTransaction(sentTx, at: sentTxHeight)
/*
9. applyStaged(sentTx + 1)
*/
try coordinator.applyStaged(blockheight: sentTxHeight + 1)
sleep(2)
// TODO: [#1247] needs to review this to properly solve, https://github.com/zcash/ZcashLightClientKit/issues/1247
// print("Starting after reorg sync")
// let afterReOrgExpectation = XCTestExpectation(description: "after ReOrg Expectation")
// do {
// try await coordinator.sync(
// completion: { synchronizer in
// /*
// 11. verify that the sent tx is mined and balance is correct
// */
// let pMinedHeight = await synchronizer.pendingTransactions.first?.minedHeight
// XCTAssertEqual(pMinedHeight, sentTxHeight)
// // fee change on this branch
// let expectedBalance = try await synchronizer.getShieldedBalance()
// XCTAssertEqual(initialTotalBalance - sendAmount - Zatoshi(10000), expectedBalance)
// afterReOrgExpectation.fulfill()
// },
// error: self.handleError
// )
// } catch {
// await handleError(error)
// }
//
// await fulfillment(of: [afterReOrgExpectation], timeout: 5)
/*
12. applyStaged(sentTx + 10)
*/
try coordinator.applyStaged(blockheight: sentTxHeight + 12)
sleep(2)
/*
13. verify that there's no more pending transaction
*/
let lastSyncExpectation = XCTestExpectation(description: "sync to confirmation")
do {
try await coordinator.sync(
completion: { _ in
lastSyncExpectation.fulfill()
},
error: self.handleError
)
} catch {
await handleError(error)
}
await fulfillment(of: [lastSyncExpectation], timeout: 5)
let expectedVerifiedBalance = initialTotalBalance + pendingTx.value
let currentVerifiedBalance = try await coordinator.synchronizer.getAccountBalance()?.saplingBalance.spendableValue ?? .zero
// TODO: [#1247] needs to review this to properly solve, https://github.com/zcash/ZcashLightClientKit/issues/1247
// let expectedPendingTransactionsCount = await coordinator.synchronizer.pendingTransactions.count
// XCTAssertEqual(expectedPendingTransactionsCount, 0)
XCTAssertEqual(expectedVerifiedBalance, currentVerifiedBalance)
let resultingBalance: Zatoshi = try await coordinator.synchronizer.getAccountBalance()?.saplingBalance.total() ?? .zero
XCTAssertEqual(resultingBalance, currentVerifiedBalance)
}
func testIncomingTransactionIndexChange() async throws {
await hookToReOrgNotification()
self.expectedReorgHeight = 663196
self.expectedRewindHeight = 663175
try await coordinator.reset(
saplingActivation: birthday,
startSaplingTreeSize: 128607,
startOrchardTreeSize: 0,
branchID: "2bb40e60",
chainName: "main"
)
try coordinator.resetBlocks(dataset: .predefined(dataset: .txIndexChangeBefore))
try coordinator.applyStaged(blockheight: 663195)
sleep(1)
let firstSyncExpectation = XCTestExpectation(description: "first sync expectation")
var preReorgTotalBalance = Zatoshi.zero
var preReorgVerifiedBalance = Zatoshi.zero
try await coordinator.sync(
completion: { synchronizer in
preReorgTotalBalance = try await synchronizer.getAccountBalance()?.saplingBalance.total() ?? .zero
preReorgVerifiedBalance = try await synchronizer.getAccountBalance()?.saplingBalance.spendableValue ?? .zero
firstSyncExpectation.fulfill()
},
error: self.handleError
)
await fulfillment(of: [firstSyncExpectation], timeout: 10)
/*
trigger reorg
*/
try coordinator.resetBlocks(dataset: .predefined(dataset: .txIndexChangeAfter))
try coordinator.applyStaged(blockheight: 663200)
sleep(1)
let afterReorgSync = XCTestExpectation(description: "after reorg sync")
var postReorgTotalBalance = Zatoshi.zero
var postReorgVerifiedBalance = Zatoshi.zero
try await coordinator.sync(
completion: { synchronizer in
postReorgTotalBalance = try await synchronizer.getAccountBalance()?.saplingBalance.total() ?? .zero
postReorgVerifiedBalance = try await synchronizer.getAccountBalance()?.saplingBalance.spendableValue ?? .zero
afterReorgSync.fulfill()
},
error: self.handleError
)
await fulfillment(of: [reorgExpectation, afterReorgSync], timeout: 30)
XCTAssertEqual(postReorgVerifiedBalance, preReorgVerifiedBalance)
XCTAssertEqual(postReorgTotalBalance, preReorgTotalBalance)
}
func testReOrgExpiresInboundTransaction() async throws {
try FakeChainBuilder.buildChain(darksideWallet: coordinator.service, branchID: branchID, chainName: chainName)
let receivedTxHeight = BlockHeight(663188)
try coordinator.applyStaged(blockheight: receivedTxHeight - 1)
sleep(2)
let expectation = XCTestExpectation(description: "sync to \(receivedTxHeight - 1) expectation")
var initialBalance = Zatoshi(-1)
var initialVerifiedBalance = Zatoshi(-1)
try await coordinator.sync(
completion: { synchronizer in
initialBalance = try await synchronizer.getAccountBalance()?.saplingBalance.total() ?? .zero
initialVerifiedBalance = try await synchronizer.getAccountBalance()?.saplingBalance.spendableValue ?? .zero
expectation.fulfill()
},
error: self.handleError
)
await fulfillment(of: [expectation], timeout: 5)
let afterTxHeight = receivedTxHeight + 1
try coordinator.applyStaged(blockheight: afterTxHeight)
sleep(2)
let afterTxSyncExpectation = XCTestExpectation(description: "sync to \(afterTxHeight) expectation")
var afterTxBalance = Zatoshi(-1)
var afterTxVerifiedBalance = Zatoshi(-1)
try await coordinator.sync(
completion: { synchronizer in
afterTxBalance = try await synchronizer.getAccountBalance()?.saplingBalance.total() ?? .zero
afterTxVerifiedBalance = try await synchronizer.getAccountBalance()?.saplingBalance.spendableValue ?? .zero
let receivedTransactions = await synchronizer.receivedTransactions
XCTAssertNotNil(
receivedTransactions.first { $0.minedHeight == receivedTxHeight },
"Transaction not found at \(receivedTxHeight)"
)
afterTxSyncExpectation.fulfill()
},
error: self.handleError
)
await fulfillment(of: [afterTxSyncExpectation], timeout: 10.0)
XCTAssertEqual(initialVerifiedBalance, afterTxVerifiedBalance)
XCTAssertNotEqual(initialBalance, afterTxBalance)
let reorgSize: Int = 3
let newBlocksCount: Int = 11 + reorgSize
try coordinator.stageBlockCreate(height: receivedTxHeight - reorgSize, count: newBlocksCount + reorgSize)
try coordinator.applyStaged(blockheight: receivedTxHeight + newBlocksCount - 1)
sleep(2)
let afterReorgExpectation = XCTestExpectation(description: "after reorg expectation")
var afterReOrgBalance = Zatoshi(-1)
var afterReOrgVerifiedBalance = Zatoshi(-1)
try await coordinator.sync(
completion: { synchronizer in
afterReOrgBalance = try await synchronizer.getAccountBalance()?.saplingBalance.total() ?? .zero
afterReOrgVerifiedBalance = try await synchronizer.getAccountBalance()?.saplingBalance.spendableValue ?? .zero
let receivedTransactions = await synchronizer.receivedTransactions
XCTAssertNil(
receivedTransactions.first { $0.minedHeight == receivedTxHeight },
"Transaction found at \(receivedTxHeight) after reorg"
)
afterReorgExpectation.fulfill()
},
error: self.handleError
)
await fulfillment(of: [afterReorgExpectation], timeout: 5)
XCTAssertEqual(afterReOrgBalance, initialBalance)
XCTAssertEqual(afterReOrgVerifiedBalance, initialVerifiedBalance)
guard
let receivedTransaction = try await coordinator.synchronizer.allTransactions().first
else {
XCTFail("expected to have a received transaction, but found none")
return
}
let transactionOutputs = await coordinator.synchronizer.getTransactionOutputs(
for: receivedTransaction
)
guard transactionOutputs.count == 1 else {
XCTFail("expected output count to be 1")
return
}
let output = transactionOutputs[0]
XCTAssertEqual(output.recipient, .internalAccount(0))
XCTAssertEqual(output.value, Zatoshi(100000))
}
/// Steps:
/// 1. sync up to an incoming transaction (incomingTxHeight + 1)
/// 1a. save balances
/// 2. stage 4 blocks from incomingTxHeight - 1 with different nonce
/// 3. stage otherTx at incomingTxHeight
/// 4. stage incomingTx at incomingTxHeight
/// 5. applyHeight(incomingHeight + 3)
/// 6. sync to latest height
/// 7. check that balances still match
func testReOrgChangesInboundTxIndexInBlock() async throws {
try FakeChainBuilder.buildChain(darksideWallet: coordinator.service, branchID: branchID, chainName: chainName)
let incomingTxHeight = BlockHeight(663188)
try coordinator.applyStaged(blockheight: incomingTxHeight + 1)
sleep(1)
/*
1. sync up to an incoming transaction (incomingTxHeight + 1)
*/
let firstSyncExpectation = XCTestExpectation(description: "first sync test expectation")
var initialBalance = Zatoshi(-1)
var initialVerifiedBalance = Zatoshi(-1)
var incomingTx: ZcashTransaction.Overview!
try await coordinator.sync(
completion: { _ in
firstSyncExpectation.fulfill()
}, error: self.handleError
)
await fulfillment(of: [firstSyncExpectation], timeout: 5)
/*
1a. save balances
*/
var accountBalance = try await coordinator.synchronizer.getAccountBalance()
initialBalance = accountBalance?.saplingBalance.total() ?? .zero
initialVerifiedBalance = accountBalance?.saplingBalance.spendableValue ?? .zero
incomingTx = await coordinator.synchronizer.receivedTransactions.first(where: { $0.minedHeight == incomingTxHeight })
let txRawData = incomingTx.raw ?? Data()
let rawTransaction = RawTransaction.with({ rawTx in
rawTx.data = txRawData
})
/*
2. stage 10 blocks from incomingTxHeight - 1 with different nonce
*/
let blockCount = 10
try coordinator.stageBlockCreate(height: incomingTxHeight - 1, count: blockCount, nonce: 1)
/*
3. stage otherTx at incomingTxHeight
*/
try coordinator.stageTransaction(url: FakeChainBuilder.someOtherTxUrl, at: incomingTxHeight)
/*
4. stage incomingTx at incomingTxHeight
*/
try coordinator.stageTransaction(rawTransaction, at: incomingTxHeight)
/*
5. applyHeight(incomingHeight + 3)
*/
try coordinator.applyStaged(blockheight: incomingTxHeight + 3)
sleep(1)
let lastSyncExpectation = XCTestExpectation(description: "last sync expectation")
/*
6. sync to latest height
*/
try await coordinator.sync(
completion: { _ in
lastSyncExpectation.fulfill()
}, error: self.handleError
)
await fulfillment(of: [lastSyncExpectation], timeout: 5)
/*
7. check that balances still match
*/
accountBalance = try await coordinator.synchronizer.getAccountBalance()
let expectedVerifiedBalance = accountBalance?.saplingBalance.spendableValue ?? .zero
let expectedBalance = accountBalance?.saplingBalance.total() ?? .zero
XCTAssertEqual(expectedVerifiedBalance, initialVerifiedBalance)
XCTAssertEqual(expectedBalance, initialBalance)
}
func testTxIndexReorg() async throws {
try coordinator.resetBlocks(dataset: .predefined(dataset: .txIndexChangeBefore))
let txReorgHeight = BlockHeight(663195)
let finalHeight = BlockHeight(663200)
try coordinator.applyStaged(blockheight: txReorgHeight)
sleep(1)
let firstSyncExpectation = XCTestExpectation(description: "first sync test expectation")
var initialBalance = Zatoshi(-1)
var initialVerifiedBalance = Zatoshi(-1)
try await coordinator.sync(
completion: { synchronizer in
initialBalance = try await synchronizer.getAccountBalance()?.saplingBalance.total() ?? .zero
initialVerifiedBalance = try await synchronizer.getAccountBalance()?.saplingBalance.spendableValue ?? .zero
firstSyncExpectation.fulfill()
},
error: self.handleError
)
await fulfillment(of: [firstSyncExpectation], timeout: 5)
try coordinator.resetBlocks(dataset: .predefined(dataset: .txIndexChangeAfter))
try coordinator.applyStaged(blockheight: finalHeight)
sleep(1)
let lastSyncExpectation = XCTestExpectation(description: "last sync expectation")
try await coordinator.sync(
completion: { _ in
lastSyncExpectation.fulfill()
},
error: self.handleError
)
await fulfillment(of: [lastSyncExpectation], timeout: 5)
let accountBalance = try await coordinator.synchronizer.getAccountBalance()
let expectedVerifiedBalance = accountBalance?.saplingBalance.spendableValue ?? .zero
let expectedBalance = accountBalance?.saplingBalance.total() ?? .zero
XCTAssertEqual(expectedBalance, initialBalance)
XCTAssertEqual(expectedVerifiedBalance, initialVerifiedBalance)
}
/// A Re Org occurs and changes the height of an outbound transaction
/// Pre-condition: Wallet has funds
///
/// Steps:
/// 1. create fake chain
/// 1a. sync to latest height
/// 2. send transaction to recipient address
/// 3. getIncomingTransaction
/// 4. stage transaction at sentTxHeight
/// 5. applyHeight(sentTxHeight)
/// 6. sync to latest height
/// 6a. verify that there's a pending transaction with a mined height of sentTxHeight
/// 7. stage 15 blocks from sentTxHeight
/// 7. a stage sent tx to sentTxHeight + 2
/// 8. applyHeight(sentTxHeight + 1) to cause a 1 block reorg
/// 9. sync to latest height
/// 10. verify that there's a pending transaction with -1 mined height
/// 11. applyHeight(sentTxHeight + 2)
/// 11a. sync to latest height
/// 12. verify that there's a pending transaction with a mined height of sentTxHeight + 2
/// 13. apply height(sentTxHeight + 15)
/// 14. sync to latest height
/// 15. verify that there's no pending transaction and that the tx is displayed on the sentTransactions collection
func testReOrgChangesOutboundTxMinedHeight() async throws {
await hookToReOrgNotification()
/*
1. create fake chain
*/
try FakeChainBuilder.buildChain(darksideWallet: coordinator.service, branchID: branchID, chainName: chainName)
try coordinator.applyStaged(blockheight: 663188)
sleep(2)
let firstSyncExpectation = XCTestExpectation(description: "first sync")
/*
1a. sync to latest height
*/
do {
try await coordinator.sync(
completion: { _ in
firstSyncExpectation.fulfill()
},
error: self.handleError
)
} catch {
await handleError(error)
}
await fulfillment(of: [firstSyncExpectation], timeout: 5)
sleep(1)
// let initialTotalBalance: Zatoshi = try await coordinator.synchronizer.getShieldedBalance()
let sendExpectation = XCTestExpectation(description: "send expectation")
var pendingEntity: ZcashTransaction.Overview?
/*
2. send transaction to recipient address
*/
let recipient = try Recipient(Environment.testRecipientAddress, network: self.network.networkType)
do {
let pendingTx = try await coordinator.synchronizer.sendToAddress(
spendingKey: self.coordinator.spendingKey,
zatoshi: Zatoshi(20000),
toAddress: recipient,
memo: try Memo(string: "this is a test")
)
pendingEntity = pendingTx
sendExpectation.fulfill()
} catch {
await handleError(error)
}
await fulfillment(of: [sendExpectation], timeout: 11)
guard pendingEntity != nil else {
XCTFail("no pending transaction after sending")
try await coordinator.stop()
return
}
/**
3. getIncomingTransaction
*/
guard let incomingTx = try coordinator.getIncomingTransactions()?.first else {
XCTFail("no incoming transaction")
try await coordinator.stop()
return
}
let sentTxHeight: BlockHeight = 663189
/*
4. stage transaction at sentTxHeight
*/
try coordinator.stageBlockCreate(height: sentTxHeight)
try coordinator.stageTransaction(incomingTx, at: sentTxHeight)
/*
5. applyHeight(sentTxHeight)
*/
try coordinator.applyStaged(blockheight: sentTxHeight)
sleep(2)
/*
6. sync to latest height
*/
let secondSyncExpectation = XCTestExpectation(description: "after send expectation")
do {
try await coordinator.sync(
completion: { _ in
secondSyncExpectation.fulfill()
},
error: self.handleError
)
} catch {
await handleError(error)
}
await fulfillment(of: [secondSyncExpectation], timeout: 5)
// TODO: [#1247] needs to review this to properly solve, https://github.com/zcash/ZcashLightClientKit/issues/1247
// var pendingTransactionsCount = await coordinator.synchronizer.pendingTransactions.count
// XCTAssertEqual(pendingTransactionsCount, 1)
// guard let afterStagePendingTx = await coordinator.synchronizer.pendingTransactions.first else {
// return
// }
/*
6a. verify that there's a pending transaction with a mined height of sentTxHeight
*/
// XCTAssertEqual(afterStagePendingTx.minedHeight, sentTxHeight)
/*
7. stage 20 blocks from sentTxHeight
*/
try coordinator.stageBlockCreate(height: sentTxHeight, count: 25)
/*
7a. stage sent tx to sentTxHeight + 2
*/
try coordinator.stageTransaction(incomingTx, at: sentTxHeight + 2)
/*
8. applyHeight(sentTxHeight + 1) to cause a 1 block reorg
*/
try coordinator.applyStaged(blockheight: sentTxHeight + 1)
sleep(2)
/*
9. sync to latest height
*/
self.expectedReorgHeight = sentTxHeight + 1
let afterReorgExpectation = XCTestExpectation(description: "after reorg sync")
do {
try await coordinator.sync(
completion: { _ in
afterReorgExpectation.fulfill()
},
error: self.handleError
)
} catch {
await handleError(error)
}
await fulfillment(of: [reorgExpectation, afterReorgExpectation], timeout: 5)
// TODO: [#1247] needs to review this to properly solve, https://github.com/zcash/ZcashLightClientKit/issues/1247
/*
10. verify that there's a pending transaction with -1 mined height
*/
// guard let newPendingTx = await coordinator.synchronizer.pendingTransactions.first else {
// XCTFail("No pending transaction")
// try await coordinator.stop()
// return
// }
//
// XCTAssertNil(newPendingTx.minedHeight)
/*
11. applyHeight(sentTxHeight + 2)
*/
try coordinator.applyStaged(blockheight: sentTxHeight + 2)
sleep(2)
let yetAnotherExpectation = XCTestExpectation(description: "after staging expectation")
/*
11a. sync to latest height
*/
do {
try await coordinator.sync(
completion: { _ in
yetAnotherExpectation.fulfill()
},
error: self.handleError
)
} catch {
await handleError(error)
}
await fulfillment(of: [yetAnotherExpectation], timeout: 5)
// TODO: [#1247] needs to review this to properly solve, https://github.com/zcash/ZcashLightClientKit/issues/1247
/*
12. verify that there's a pending transaction with a mined height of sentTxHeight + 2
*/
// pendingTransactionsCount = await coordinator.synchronizer.pendingTransactions.count
// XCTAssertEqual(pendingTransactionsCount, 1)
// guard let newlyPendingTx = try await coordinator.synchronizer.allPendingTransactions().first(where: { $0.isSentTransaction }) else {
// XCTFail("no pending transaction")
// try await coordinator.stop()
// return
// }
//
// XCTAssertEqual(newlyPendingTx.minedHeight, sentTxHeight + 2)
/*
13. apply height(sentTxHeight + 25)
*/
try coordinator.applyStaged(blockheight: sentTxHeight + 25)
sleep(2)
let thisIsTheLastExpectationIPromess = XCTestExpectation(description: "last sync")
/*
14. sync to latest height
*/
do {
try await coordinator.sync(
completion: { _ in
thisIsTheLastExpectationIPromess.fulfill()
},
error: self.handleError
)
} catch {