ZcashLightClientKit/Tests/DarksideTests/SychronizerDarksideTests.swift

257 lines
8.6 KiB
Swift
Raw Normal View History

//
// SychronizerDarksideTests.swift
// ZcashLightClientKit-Unit-Tests
//
// Created by Francisco Gindre on 10/20/20.
//
import XCTest
import Combine
2022-02-28 09:03:20 -08:00
@testable import TestUtils
@testable import ZcashLightClientKit
2021-09-23 06:26:41 -07:00
class SychronizerDarksideTests: XCTestCase {
let sendAmount: Int64 = 1000
let defaultLatestHeight: BlockHeight = 663175
2021-09-23 06:26:41 -07:00
let branchID = "2bb40e60"
let chainName = "main"
let network = DarksideWalletDNetwork()
var birthday: BlockHeight = 663150
var coordinator: TestCoordinator!
var syncedExpectation = XCTestExpectation(description: "synced")
var sentTransactionExpectation = XCTestExpectation(description: "sent")
var expectedReorgHeight: BlockHeight = 665188
var expectedRewindHeight: BlockHeight = 665188
2021-09-23 06:26:41 -07:00
var reorgExpectation = XCTestExpectation(description: "reorg")
var foundTransactions: [ZcashTransaction.Overview] = []
var cancellables: [AnyCancellable] = []
2021-09-23 06:26:41 -07:00
override func setUpWithError() throws {
2021-09-23 06:26:41 -07:00
try super.setUpWithError()
self.coordinator = try TestCoordinator(
walletBirthday: self.birthday,
network: self.network
)
try self.coordinator.reset(saplingActivation: 663150, branchID: "e9ff75a6", chainName: "main")
}
override func tearDownWithError() throws {
2021-09-23 06:26:41 -07:00
try super.tearDownWithError()
NotificationCenter.default.removeObserver(self)
try coordinator.stop()
- [#679] Implementation of the File-system based block cache (#679) Closes https://github.com/zcash/ZcashLightClientKit/issues/697 Closes https://github.com/zcash/ZcashLightClientKit/issues/720 Closes https://github.com/zcash/ZcashLightClientKit/issues/587 Closes https://github.com/zcash/ZcashLightClientKit/issues/667 Closes https://github.com/zcash/ZcashLightClientKit/issues/443 Closes https://github.com/zcash/ZcashLightClientKit/issues/754 - [#790] Fix ShieldFundsTests Closes #790 Removes comments on `ShieldFundsTests` since those issues have been fixed Depends on zcash-light-client-ffi changes that adopt newer versions of librustzcash crates `zcash_primitives 0.10`, `zcash_client_backend 0.7`, `zcash_proofs 0.10`, `zcash_client_sqlite 0.5.0`. Also allows wallets to define a shielding_threshold and will set foundations to customize minimum confirmations for balances, spends and shielding operations. **Test Bootstrapping** - `ZcashCompactBlockDescriptor`: struct that holds functions to describe blocks as filenames and compare those filenames `ZcashCompactBlockDescriptor.live` has the actual implementation but it can be replaced by mocks if needed on Tests main implementations are held under `FSCompactBlockRepository.filenameDescription` and `FSCompactBlockRepository.filenameComparison` on a separate extention `DirectoryListingProviders` provide two default implementations of listing a directory deterministically. `FileManager` does not define a sorting and needs to be done in-memory by calling `.sorted()` on the resulting collection. If this is a big toll on performance it can be changed to a POSIX implementation but this is good for now. `ZcashCompactBlockDescriptor` adds a `height` helper function to turn a filename into the height of the block stored. Implemented `func latestHeight() throws -> BlockHeight ` that returns the blockheight by querying the cache directory in a sorted fashion and getting the last value and turning the filename into a `BlockHeight` Added `Meta` struct to ZcashCompactBlock. Tests implemented: - `filterBlockFiles` - `testClearTheCache` - `testLatestHeightEmptyCacheThrows` - `testLatestHeightEmptyCacheThrowsAsync` - `testRewindEmptyCacheDoesNothing` - `testRewindEmptyCacheDoesNothingAsync` - `testWhenBlockIsStoredItFollowsTheDescribedFormat` - `testWhenBlockIsStoredItFollowsTheFilenameConvention` - `testGetLatestHeight` - `testRewindDeletesTheRightBlocks` test - `testPerformanceExample` test. This isn't a real performance test because the API doesn't work with async/await yet adopts `shield_funds` shielding threshold parameter Implements `initBlockMetadataDb` and fix tests Renames dbCache parameter to `fsBlockDbRoot`. Builds but tests don't pass. Removes cacheDb uses from code. Testing utilities still persist. Added needed information in MIGRATING and CHANGELOG. Added helper to perform deletion of legacy db and creation a the new file system backed cache. Renames parameters and changes code where needed. Network Constants turned into `enum` with static methods. DeletelastDownloadedBlock helper from initializer Removes CompactBlockStorage and CompactBlockEntity. Implements `latestCachedBlockHeight` on rustbackend. *Replaces dependencies on ZcashRustWelding with `FSMetadataStore`* This allows the tests to not depend in a particular implementation of either the MockRustBackend of or ZcashRustBackend. Also provides a way to test errors properly and switch implementations of critical areas like `writeBlocks`.
2023-02-02 08:58:12 -08:00
try? FileManager.default.removeItem(at: coordinator.databases.fsCacheDbRoot)
try? FileManager.default.removeItem(at: coordinator.databases.dataDB)
try? FileManager.default.removeItem(at: coordinator.databases.pendingDB)
2023-02-16 08:14:31 -08:00
coordinator = nil
foundTransactions = []
cancellables = []
}
func testFoundTransactions() throws {
2021-09-23 06:26:41 -07:00
NotificationCenter.default.addObserver(
self,
selector: #selector(handleFoundTransactions(_:)),
name: Notification.Name.synchronizerFoundTransactions,
object: nil
)
2021-05-18 14:22:29 -07:00
try FakeChainBuilder.buildChain(darksideWallet: self.coordinator.service, branchID: branchID, chainName: chainName)
let receivedTxHeight: BlockHeight = 663188
try coordinator.applyStaged(blockheight: receivedTxHeight + 1)
sleep(2)
let preTxExpectation = XCTestExpectation(description: "pre receive")
2021-09-23 06:26:41 -07:00
try coordinator.sync(completion: { _ in
preTxExpectation.fulfill()
}, error: self.handleError)
wait(for: [preTxExpectation], timeout: 5)
XCTAssertEqual(self.foundTransactions.count, 2)
}
func testFoundManyTransactions() throws {
2021-09-23 06:26:41 -07:00
NotificationCenter.default.addObserver(
self,
selector: #selector(handleFoundTransactions(_:)),
name: Notification.Name.synchronizerFoundTransactions,
object: nil
)
2021-09-23 06:26:41 -07:00
try FakeChainBuilder.buildChain(darksideWallet: self.coordinator.service, branchID: branchID, chainName: chainName, length: 1000)
let receivedTxHeight: BlockHeight = 663229
try coordinator.applyStaged(blockheight: receivedTxHeight + 1)
sleep(2)
let firsTxExpectation = XCTestExpectation(description: "first sync")
2021-09-23 06:26:41 -07:00
try coordinator.sync(completion: { _ in
firsTxExpectation.fulfill()
}, error: self.handleError)
wait(for: [firsTxExpectation], timeout: 10)
XCTAssertEqual(self.foundTransactions.count, 5)
self.foundTransactions.removeAll()
try coordinator.applyStaged(blockheight: 663900)
sleep(2)
let preTxExpectation = XCTestExpectation(description: "intermediate sync")
2021-09-23 06:26:41 -07:00
try coordinator.sync(completion: { _ in
preTxExpectation.fulfill()
}, error: self.handleError)
wait(for: [preTxExpectation], timeout: 10)
2021-09-23 06:26:41 -07:00
XCTAssertTrue(self.foundTransactions.isEmpty)
let findManyTxExpectation = XCTestExpectation(description: "final sync")
try coordinator.applyStaged(blockheight: 664010)
sleep(2)
2021-09-23 06:26:41 -07:00
try coordinator.sync(completion: { _ in
findManyTxExpectation.fulfill()
}, error: self.handleError)
wait(for: [findManyTxExpectation], timeout: 10)
XCTAssertEqual(self.foundTransactions.count, 2)
}
func testLastStates() throws {
var disposeBag: [AnyCancellable] = []
var states: [SDKSynchronizer.SynchronizerState] = []
try FakeChainBuilder.buildChain(darksideWallet: self.coordinator.service, branchID: branchID, chainName: chainName)
let receivedTxHeight: BlockHeight = 663188
try coordinator.applyStaged(blockheight: receivedTxHeight + 1)
sleep(2)
let preTxExpectation = XCTestExpectation(description: "pre receive")
coordinator.synchronizer.lastState
.receive(on: DispatchQueue.main)
.sink { state in
states.append(state)
}
.store(in: &disposeBag)
try coordinator.sync(completion: { _ in
preTxExpectation.fulfill()
}, error: self.handleError)
wait(for: [preTxExpectation], timeout: 5)
XCTAssertEqual(states, [
SDKSynchronizer.SynchronizerState(
shieldedBalance: .zero,
transparentBalance: .zero,
syncStatus: .unprepared,
latestScannedHeight: .zero
),
SDKSynchronizer.SynchronizerState(
shieldedBalance: WalletBalance(verified: Zatoshi(0), total: Zatoshi(0)),
transparentBalance: WalletBalance(verified: Zatoshi(0), total: Zatoshi(0)),
syncStatus: SyncStatus.disconnected,
latestScannedHeight: 663150
),
SDKSynchronizer.SynchronizerState(
shieldedBalance: WalletBalance(verified: Zatoshi(100000), total: Zatoshi(200000)),
transparentBalance: WalletBalance(verified: Zatoshi(0), total: Zatoshi(0)),
syncStatus: SyncStatus.synced,
latestScannedHeight: 663189
)
])
}
@MainActor func testSyncAfterWipeWorks() async throws {
try FakeChainBuilder.buildChain(darksideWallet: self.coordinator.service, branchID: branchID, chainName: chainName)
let receivedTxHeight: BlockHeight = 663188
try coordinator.applyStaged(blockheight: receivedTxHeight + 1)
sleep(2)
let firsSyncExpectation = XCTestExpectation(description: "first sync")
try coordinator.sync(
completion: { _ in
firsSyncExpectation.fulfill()
},
error: self.handleError
)
wait(for: [firsSyncExpectation], timeout: 10)
let wipeFinished = XCTestExpectation(description: "SynchronizerWipeFinished Expectation")
coordinator.synchronizer.wipe()
.sink(
receiveCompletion: { completion in
switch completion {
case .finished:
wipeFinished.fulfill()
case .failure(let error):
XCTFail("Wipe should finish successfully. \(error)")
}
},
receiveValue: {
XCTFail("No no value should be received from wipe.")
}
)
.store(in: &cancellables)
wait(for: [wipeFinished], timeout: 1)
_ = try coordinator.prepare(seed: Environment.seedBytes)
let secondSyncExpectation = XCTestExpectation(description: "second sync")
try coordinator.sync(
completion: { _ in
secondSyncExpectation.fulfill()
},
error: self.handleError
)
wait(for: [secondSyncExpectation], timeout: 10)
}
@objc func handleFoundTransactions(_ notification: Notification) {
2021-09-23 06:26:41 -07:00
guard
let userInfo = notification.userInfo,
let transactions = userInfo[SDKSynchronizer.NotificationKeys.foundTransactions] as? [ZcashTransaction.Overview]
2021-09-23 06:26:41 -07:00
else {
return
}
self.foundTransactions.append(contentsOf: transactions)
}
func handleError(_ error: Error?) {
_ = try? coordinator.stop()
guard let testError = error else {
XCTFail("failed with nil error")
return
}
XCTFail("Failed with error: \(testError)")
}
}
extension Zatoshi: CustomDebugStringConvertible {
public var debugDescription: String {
"Zatoshi(\(self.amount))"
}
}