ZcashLightClientKit/Sources/ZcashLightClientKit/Block/CompactBlockProcessor.swift

1329 lines
52 KiB
Swift
Raw Normal View History

//
// CompactBlockProcessor.swift
// ZcashLightClientKit
//
// Created by Francisco Gindre on 18/09/2019.
// Copyright © 2019 Electric Coin Company. All rights reserved.
//
2021-09-15 05:21:29 -07:00
// swiftlint:disable file_length type_body_length
import Foundation
import Combine
public typealias RefreshedUTXOs = (inserted: [UnspentTransactionOutputEntity], skipped: [UnspentTransactionOutputEntity])
2021-09-17 06:49:58 -07:00
2021-06-07 16:00:33 -07:00
public enum CompactBlockProgress {
case syncing(_ progress: BlockProgress)
case enhance(_ progress: EnhancementProgress)
2021-06-07 16:00:33 -07:00
case fetch
public var progress: Float {
switch self {
case .syncing(let blockProgress):
2021-09-15 05:21:29 -07:00
return blockProgress.progress
case .enhance(let enhancementProgress):
return enhancementProgress.progress
2021-06-07 16:00:33 -07:00
default:
return 0
}
}
public var progressHeight: BlockHeight? {
switch self {
case .syncing(let blockProgress):
2021-09-15 05:21:29 -07:00
return blockProgress.progressHeight
case .enhance(let enhancementProgress):
return enhancementProgress.lastFoundTransaction?.minedHeight
2021-06-07 16:00:33 -07:00
default:
return 0
}
}
public var blockDate: Date? {
if case .enhance(let enhancementProgress) = self, let time = enhancementProgress.lastFoundTransaction?.blockTime {
2021-06-07 16:00:33 -07:00
return Date(timeIntervalSince1970: time)
}
2021-09-17 06:49:58 -07:00
2021-06-07 16:00:33 -07:00
return nil
}
2021-07-07 07:42:45 -07:00
public var targetHeight: BlockHeight? {
switch self {
case .syncing(let blockProgress):
2021-09-15 05:21:29 -07:00
return blockProgress.targetHeight
2021-07-07 07:42:45 -07:00
default:
return nil
}
}
2021-06-07 16:00:33 -07:00
}
public struct EnhancementProgress: Equatable {
[#361] Introduce ZcashError (#1005) This PR introduces `ZcashError` enum. This enum represents any error that can be thrown inside of the SDK and outside of the SDK. Also `ZcashError` is used in `LightWalletGRPCService` and handled in `CompactBlockProcessor` as example. Why enum? First I tried this with some structure which contained code, message and underlyingError. Problem was when some specific place in the SDK would like to attach some additional data to error. I didn't want to add some generic dictionary to store anything with the error. So I used enum to identify error. Each member can have specified amount of associated values. So specific error can bring some context data. And it's type safe. Each error has also a code. Relationship between errors and codes is 1:1. It may looks bit redundant but it's important. The client app now can choose how to process errors. Either identify those by the error itself or by code. Definition or errors and codes is in `ZcashErrorDefinition`. And then `ZcashError` and `ZcashErrorCode` are generated by Sourcery. Thanks to this it is easier to maintain the final code. And it gives us ability to generate any kind of documentation for the errors and codes. I created simple example of this in this PR. And it doesn't make the SDK completely dependent on the Sourcery. Final structures aren't super complicated and can be written manually if needed. [#923] Update error handling in DatabaseStorageManager.swift - cleanup of DatabaseStorageManager, not used anymore - ZcashError for SimpleConnectionProvider Revert "[#923] Update error handling in DatabaseStorageManager.swift" This reverts commit 94e028d31a0f6635800c297eb741db74c6a6ff45. Fix script which generates ZcashError [#922] Update error handling in DatabaseMigrationManager.swift Closes #922 [#923] Update error handling in DatabaseStorageManager.swift - The DatabaseStorageManager is not used so I deleted it - SimpleConnectionProvider's errors updated Fix tests [#955] Update error handling in SaplingParameterDownloader Closes #955 [#936] Update error handling in NotesDao Closes #936 [#935] Update error handling in BlockDao Closes #935 [#931] InternalSyncProgress.computeNextState doesn't need to throw Closes #931 [#950] Update error handling in rust backend Closes #949 Closes #950 [#941] Update error handling in AccountEntity Closes #941 [#928] Update error handling in FSCompactBlockRepository Closes #928 [#925] Update error handling in BlockDownloaderService (#974) - BlockDownloaderService errors updated [#924] Update error handling in BlockDownloader (#973) - BlockDownloaderStream nextBlock updated [#942] Update error handling in TransactionEntity (#977) - ZcashTransaction init errors converted to the ZcashError [#939] Update error handling in TransactionDao (#976) - TransactionRepositoryError removed and replaced with ZcashError - all TransactionDAO errors converted to ZcashError [#943] Update error handling in ZcashCompactBlock Closes #943 [#945] Update error handling in Memo Closes #945 [#934] Update error handling in Checkpoint Closes #944 Closes #934 [#938] Update error handling in PendingTransactionDao Closes #938 [#926] Update error handling in BlockEnhancer - WIP, switching to transaction repository to unblock this ticket [#926] Update error handling in BlockEnhancer - enhancer's errors done [#926] Update error handling in BlockEnhancer (#994) - cleanup [#952] Update error handling in DerivationTool Closes #952 [#932] Update error handling in BlockValidator Closes #932 [#940] Update error handling in UnspentTransactionOutputDao Closes #940 [#946] Update error handling in WalletTypes Closes #946 [#954] Update error handling in WalletTransactionEncoder Closes #954 [#953] Update error handling in PersistentTransactionManager Closes #953 [#956] Update error handling in Initializer Closes #956 [#947] Update error handling in Zatoshi (#996) - Zatoshi's errors converted to ZcashError [#927] Update error handling in UTXOFetcher (#997) - UTXOFetcher resolved Use let instead of var where applicable In the SDK `var` was used on places where `let` would be sufficient. And default strategy in Swift should use use `let` until mutability is required. So all these places are changed. No logic is changed. [#933] Update error handling in CompactBlockProcessor - CompactBlockProcessor's errors refactored to ZcashError [#933] Update error handling in CompactBlockProcessor #999 - comments addressed [#951] Update error handling in SDKSynchronizer - SDKSynchronizer's errors refactored to ZcashError [#951] Update error handling in SDKSynchronizer (#1002) - comments resolved Make DerivationTool constructor public DerivationTool.init should be public. This was removed by accident when adopting async. [#361] Add changelog
2023-04-24 14:15:20 -07:00
public let totalTransactions: Int
public let enhancedTransactions: Int
public let lastFoundTransaction: ZcashTransaction.Overview?
public let range: CompactBlockRange
public init(totalTransactions: Int, enhancedTransactions: Int, lastFoundTransaction: ZcashTransaction.Overview?, range: CompactBlockRange) {
self.totalTransactions = totalTransactions
self.enhancedTransactions = enhancedTransactions
self.lastFoundTransaction = lastFoundTransaction
self.range = range
}
2021-06-07 16:00:33 -07:00
public var progress: Float {
totalTransactions > 0 ? Float(enhancedTransactions) / Float(totalTransactions) : 0
}
public static var zero: EnhancementProgress {
EnhancementProgress(totalTransactions: 0, enhancedTransactions: 0, lastFoundTransaction: nil, range: 0...0)
}
public static func == (lhs: EnhancementProgress, rhs: EnhancementProgress) -> Bool {
return
lhs.totalTransactions == rhs.totalTransactions &&
lhs.enhancedTransactions == rhs.enhancedTransactions &&
lhs.lastFoundTransaction?.id == rhs.lastFoundTransaction?.id &&
lhs.range == rhs.range
}
2021-06-07 16:00:33 -07:00
}
/// The compact block processor is in charge of orchestrating the download and caching of compact blocks from a LightWalletEndpoint
/// when started the processor downloads does a download - validate - scan cycle until it reaches latest height on the blockchain.
actor CompactBlockProcessor {
[#831] Add SDKSynchronizer wrappers for non-async API This change introduces two new protocols: `ClosureSynchronizer` and `CombineSynchronizer`. These two protocols define API that doesn't use `async`. So the client can choose exactly which API it wants to use. This change also introduces two new objects: `ClosureSDKSynchronizer` and `CombineSDKSynchronizer`. These two implement the respective protocols mentioned above. Both are structures. Neither of these two keeps any state. Thanks to this each is very cheap to create. And usage of these two isn't mutually exclusive. So devs can really choose the best SDK API for each part of the client app. [#831] Use async inside of the SDKSynchronizer - In general lot of methods inside the `SDKSynchronizer` and `CompactBlockProcessoer` which weren't async are now async. And other changes are made because of this change. - `CompactBlockProcessor` no longer uses Combine to communicate with `SDKSynchronizer`. Reason for this is that Combine doesn't play great with async. Closure passed to `sink` isn't async. - Because of this and because of how our tests work (receiving signals from CBP directly) `CompactBlockProcessor` must be able to handle more event closures. Not just one. So it now has `eventClosures` dictionary. It's little bit strange but it works fine. - `SyncStatus` inside the `SDKSynchronizer` was previously protected by lock. Now it's protected by simple actor wrapper. - Changes in tests are minimal. Changes were mady only because `CompactBlockProcessor` changes from Combine to closures. [#831] Add tests for ClosureSDKSynchronizer - Added tests are testing in general if the `ClosuresSDKSynchronizer` is correctly calling `Synchronizer` and if the values are correctly returned. - `ClosuresSDKSynchronizer` doesn't contain any logic but it is public API and we should be sure that it works correctly. [#831] Add tests for CombineSDKSynchronizer [#831] Add changelog
2023-03-16 02:11:18 -07:00
typealias EventClosure = (Event) async -> Void
enum Event {
/// Event sent when the CompactBlockProcessor presented an error.
[#361] Introduce ZcashError (#1005) This PR introduces `ZcashError` enum. This enum represents any error that can be thrown inside of the SDK and outside of the SDK. Also `ZcashError` is used in `LightWalletGRPCService` and handled in `CompactBlockProcessor` as example. Why enum? First I tried this with some structure which contained code, message and underlyingError. Problem was when some specific place in the SDK would like to attach some additional data to error. I didn't want to add some generic dictionary to store anything with the error. So I used enum to identify error. Each member can have specified amount of associated values. So specific error can bring some context data. And it's type safe. Each error has also a code. Relationship between errors and codes is 1:1. It may looks bit redundant but it's important. The client app now can choose how to process errors. Either identify those by the error itself or by code. Definition or errors and codes is in `ZcashErrorDefinition`. And then `ZcashError` and `ZcashErrorCode` are generated by Sourcery. Thanks to this it is easier to maintain the final code. And it gives us ability to generate any kind of documentation for the errors and codes. I created simple example of this in this PR. And it doesn't make the SDK completely dependent on the Sourcery. Final structures aren't super complicated and can be written manually if needed. [#923] Update error handling in DatabaseStorageManager.swift - cleanup of DatabaseStorageManager, not used anymore - ZcashError for SimpleConnectionProvider Revert "[#923] Update error handling in DatabaseStorageManager.swift" This reverts commit 94e028d31a0f6635800c297eb741db74c6a6ff45. Fix script which generates ZcashError [#922] Update error handling in DatabaseMigrationManager.swift Closes #922 [#923] Update error handling in DatabaseStorageManager.swift - The DatabaseStorageManager is not used so I deleted it - SimpleConnectionProvider's errors updated Fix tests [#955] Update error handling in SaplingParameterDownloader Closes #955 [#936] Update error handling in NotesDao Closes #936 [#935] Update error handling in BlockDao Closes #935 [#931] InternalSyncProgress.computeNextState doesn't need to throw Closes #931 [#950] Update error handling in rust backend Closes #949 Closes #950 [#941] Update error handling in AccountEntity Closes #941 [#928] Update error handling in FSCompactBlockRepository Closes #928 [#925] Update error handling in BlockDownloaderService (#974) - BlockDownloaderService errors updated [#924] Update error handling in BlockDownloader (#973) - BlockDownloaderStream nextBlock updated [#942] Update error handling in TransactionEntity (#977) - ZcashTransaction init errors converted to the ZcashError [#939] Update error handling in TransactionDao (#976) - TransactionRepositoryError removed and replaced with ZcashError - all TransactionDAO errors converted to ZcashError [#943] Update error handling in ZcashCompactBlock Closes #943 [#945] Update error handling in Memo Closes #945 [#934] Update error handling in Checkpoint Closes #944 Closes #934 [#938] Update error handling in PendingTransactionDao Closes #938 [#926] Update error handling in BlockEnhancer - WIP, switching to transaction repository to unblock this ticket [#926] Update error handling in BlockEnhancer - enhancer's errors done [#926] Update error handling in BlockEnhancer (#994) - cleanup [#952] Update error handling in DerivationTool Closes #952 [#932] Update error handling in BlockValidator Closes #932 [#940] Update error handling in UnspentTransactionOutputDao Closes #940 [#946] Update error handling in WalletTypes Closes #946 [#954] Update error handling in WalletTransactionEncoder Closes #954 [#953] Update error handling in PersistentTransactionManager Closes #953 [#956] Update error handling in Initializer Closes #956 [#947] Update error handling in Zatoshi (#996) - Zatoshi's errors converted to ZcashError [#927] Update error handling in UTXOFetcher (#997) - UTXOFetcher resolved Use let instead of var where applicable In the SDK `var` was used on places where `let` would be sufficient. And default strategy in Swift should use use `let` until mutability is required. So all these places are changed. No logic is changed. [#933] Update error handling in CompactBlockProcessor - CompactBlockProcessor's errors refactored to ZcashError [#933] Update error handling in CompactBlockProcessor #999 - comments addressed [#951] Update error handling in SDKSynchronizer - SDKSynchronizer's errors refactored to ZcashError [#951] Update error handling in SDKSynchronizer (#1002) - comments resolved Make DerivationTool constructor public DerivationTool.init should be public. This was removed by accident when adopting async. [#361] Add changelog
2023-04-24 14:15:20 -07:00
case failed (Error)
2021-09-17 06:49:58 -07:00
/// Event sent when the CompactBlockProcessor has finished syncing the blockchain to latest height
case finished (_ lastScannedHeight: BlockHeight, _ foundBlocks: Bool)
2021-09-17 06:49:58 -07:00
/// Event sent when the CompactBlockProcessor enhanced a bunch of transactions in some range.
case foundTransactions ([ZcashTransaction.Overview], CompactBlockRange)
2021-09-17 06:49:58 -07:00
/// Event sent when the CompactBlockProcessor handled a ReOrg.
/// `reorgHeight` is the height on which the reorg was detected.
/// `rewindHeight` is the height that the processor backed to in order to solve the Reorg.
case handledReorg (_ reorgHeight: BlockHeight, _ rewindHeight: BlockHeight)
2021-09-17 06:49:58 -07:00
/// Event sent when progress of the sync process changes.
case progressUpdated (CompactBlockProgress)
2021-09-17 06:49:58 -07:00
/// Event sent when the CompactBlockProcessor fetched utxos from lightwalletd attempted to store them.
case storedUTXOs ((inserted: [UnspentTransactionOutputEntity], skipped: [UnspentTransactionOutputEntity]))
2021-09-17 06:49:58 -07:00
/// Event sent when the CompactBlockProcessor starts enhancing of the transactions.
case startedEnhancing
/// Event sent when the CompactBlockProcessor starts fetching of the UTXOs.
case startedFetching
/// Event sent when the CompactBlockProcessor starts syncing.
case startedSyncing
/// Event sent when the CompactBlockProcessor stops syncing.
case stopped
}
/// Compact Block Processor configuration
///
- [#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
/// - parameter fsBlockCacheRoot: absolute root path where the filesystem block cache will be stored.
/// - parameter dataDb: absolute file path of the DB where all information derived from the cache DB is stored.
/// - parameter spendParamsURL: absolute file path of the sapling-spend.params file
/// - parameter outputParamsURL: absolute file path of the sapling-output.params file
struct Configuration {
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
let alias: ZcashSynchronizerAlias
let saplingParamsSourceURL: SaplingParamsSourceURL
[#361] Introduce ZcashError (#1005) This PR introduces `ZcashError` enum. This enum represents any error that can be thrown inside of the SDK and outside of the SDK. Also `ZcashError` is used in `LightWalletGRPCService` and handled in `CompactBlockProcessor` as example. Why enum? First I tried this with some structure which contained code, message and underlyingError. Problem was when some specific place in the SDK would like to attach some additional data to error. I didn't want to add some generic dictionary to store anything with the error. So I used enum to identify error. Each member can have specified amount of associated values. So specific error can bring some context data. And it's type safe. Each error has also a code. Relationship between errors and codes is 1:1. It may looks bit redundant but it's important. The client app now can choose how to process errors. Either identify those by the error itself or by code. Definition or errors and codes is in `ZcashErrorDefinition`. And then `ZcashError` and `ZcashErrorCode` are generated by Sourcery. Thanks to this it is easier to maintain the final code. And it gives us ability to generate any kind of documentation for the errors and codes. I created simple example of this in this PR. And it doesn't make the SDK completely dependent on the Sourcery. Final structures aren't super complicated and can be written manually if needed. [#923] Update error handling in DatabaseStorageManager.swift - cleanup of DatabaseStorageManager, not used anymore - ZcashError for SimpleConnectionProvider Revert "[#923] Update error handling in DatabaseStorageManager.swift" This reverts commit 94e028d31a0f6635800c297eb741db74c6a6ff45. Fix script which generates ZcashError [#922] Update error handling in DatabaseMigrationManager.swift Closes #922 [#923] Update error handling in DatabaseStorageManager.swift - The DatabaseStorageManager is not used so I deleted it - SimpleConnectionProvider's errors updated Fix tests [#955] Update error handling in SaplingParameterDownloader Closes #955 [#936] Update error handling in NotesDao Closes #936 [#935] Update error handling in BlockDao Closes #935 [#931] InternalSyncProgress.computeNextState doesn't need to throw Closes #931 [#950] Update error handling in rust backend Closes #949 Closes #950 [#941] Update error handling in AccountEntity Closes #941 [#928] Update error handling in FSCompactBlockRepository Closes #928 [#925] Update error handling in BlockDownloaderService (#974) - BlockDownloaderService errors updated [#924] Update error handling in BlockDownloader (#973) - BlockDownloaderStream nextBlock updated [#942] Update error handling in TransactionEntity (#977) - ZcashTransaction init errors converted to the ZcashError [#939] Update error handling in TransactionDao (#976) - TransactionRepositoryError removed and replaced with ZcashError - all TransactionDAO errors converted to ZcashError [#943] Update error handling in ZcashCompactBlock Closes #943 [#945] Update error handling in Memo Closes #945 [#934] Update error handling in Checkpoint Closes #944 Closes #934 [#938] Update error handling in PendingTransactionDao Closes #938 [#926] Update error handling in BlockEnhancer - WIP, switching to transaction repository to unblock this ticket [#926] Update error handling in BlockEnhancer - enhancer's errors done [#926] Update error handling in BlockEnhancer (#994) - cleanup [#952] Update error handling in DerivationTool Closes #952 [#932] Update error handling in BlockValidator Closes #932 [#940] Update error handling in UnspentTransactionOutputDao Closes #940 [#946] Update error handling in WalletTypes Closes #946 [#954] Update error handling in WalletTransactionEncoder Closes #954 [#953] Update error handling in PersistentTransactionManager Closes #953 [#956] Update error handling in Initializer Closes #956 [#947] Update error handling in Zatoshi (#996) - Zatoshi's errors converted to ZcashError [#927] Update error handling in UTXOFetcher (#997) - UTXOFetcher resolved Use let instead of var where applicable In the SDK `var` was used on places where `let` would be sufficient. And default strategy in Swift should use use `let` until mutability is required. So all these places are changed. No logic is changed. [#933] Update error handling in CompactBlockProcessor - CompactBlockProcessor's errors refactored to ZcashError [#933] Update error handling in CompactBlockProcessor #999 - comments addressed [#951] Update error handling in SDKSynchronizer - SDKSynchronizer's errors refactored to ZcashError [#951] Update error handling in SDKSynchronizer (#1002) - comments resolved Make DerivationTool constructor public DerivationTool.init should be public. This was removed by accident when adopting async. [#361] Add changelog
2023-04-24 14:15:20 -07:00
let fsBlockCacheRoot: URL
let dataDb: URL
let spendParamsURL: URL
let outputParamsURL: URL
let downloadBatchSize: Int
let scanningBatchSize: Int
let retries: Int
let maxBackoffInterval: TimeInterval
let maxReorgSize = ZcashSDK.maxReorgSize
let rewindDistance: Int
let walletBirthdayProvider: () -> BlockHeight
[#361] Introduce ZcashError (#1005) This PR introduces `ZcashError` enum. This enum represents any error that can be thrown inside of the SDK and outside of the SDK. Also `ZcashError` is used in `LightWalletGRPCService` and handled in `CompactBlockProcessor` as example. Why enum? First I tried this with some structure which contained code, message and underlyingError. Problem was when some specific place in the SDK would like to attach some additional data to error. I didn't want to add some generic dictionary to store anything with the error. So I used enum to identify error. Each member can have specified amount of associated values. So specific error can bring some context data. And it's type safe. Each error has also a code. Relationship between errors and codes is 1:1. It may looks bit redundant but it's important. The client app now can choose how to process errors. Either identify those by the error itself or by code. Definition or errors and codes is in `ZcashErrorDefinition`. And then `ZcashError` and `ZcashErrorCode` are generated by Sourcery. Thanks to this it is easier to maintain the final code. And it gives us ability to generate any kind of documentation for the errors and codes. I created simple example of this in this PR. And it doesn't make the SDK completely dependent on the Sourcery. Final structures aren't super complicated and can be written manually if needed. [#923] Update error handling in DatabaseStorageManager.swift - cleanup of DatabaseStorageManager, not used anymore - ZcashError for SimpleConnectionProvider Revert "[#923] Update error handling in DatabaseStorageManager.swift" This reverts commit 94e028d31a0f6635800c297eb741db74c6a6ff45. Fix script which generates ZcashError [#922] Update error handling in DatabaseMigrationManager.swift Closes #922 [#923] Update error handling in DatabaseStorageManager.swift - The DatabaseStorageManager is not used so I deleted it - SimpleConnectionProvider's errors updated Fix tests [#955] Update error handling in SaplingParameterDownloader Closes #955 [#936] Update error handling in NotesDao Closes #936 [#935] Update error handling in BlockDao Closes #935 [#931] InternalSyncProgress.computeNextState doesn't need to throw Closes #931 [#950] Update error handling in rust backend Closes #949 Closes #950 [#941] Update error handling in AccountEntity Closes #941 [#928] Update error handling in FSCompactBlockRepository Closes #928 [#925] Update error handling in BlockDownloaderService (#974) - BlockDownloaderService errors updated [#924] Update error handling in BlockDownloader (#973) - BlockDownloaderStream nextBlock updated [#942] Update error handling in TransactionEntity (#977) - ZcashTransaction init errors converted to the ZcashError [#939] Update error handling in TransactionDao (#976) - TransactionRepositoryError removed and replaced with ZcashError - all TransactionDAO errors converted to ZcashError [#943] Update error handling in ZcashCompactBlock Closes #943 [#945] Update error handling in Memo Closes #945 [#934] Update error handling in Checkpoint Closes #944 Closes #934 [#938] Update error handling in PendingTransactionDao Closes #938 [#926] Update error handling in BlockEnhancer - WIP, switching to transaction repository to unblock this ticket [#926] Update error handling in BlockEnhancer - enhancer's errors done [#926] Update error handling in BlockEnhancer (#994) - cleanup [#952] Update error handling in DerivationTool Closes #952 [#932] Update error handling in BlockValidator Closes #932 [#940] Update error handling in UnspentTransactionOutputDao Closes #940 [#946] Update error handling in WalletTypes Closes #946 [#954] Update error handling in WalletTransactionEncoder Closes #954 [#953] Update error handling in PersistentTransactionManager Closes #953 [#956] Update error handling in Initializer Closes #956 [#947] Update error handling in Zatoshi (#996) - Zatoshi's errors converted to ZcashError [#927] Update error handling in UTXOFetcher (#997) - UTXOFetcher resolved Use let instead of var where applicable In the SDK `var` was used on places where `let` would be sufficient. And default strategy in Swift should use use `let` until mutability is required. So all these places are changed. No logic is changed. [#933] Update error handling in CompactBlockProcessor - CompactBlockProcessor's errors refactored to ZcashError [#933] Update error handling in CompactBlockProcessor #999 - comments addressed [#951] Update error handling in SDKSynchronizer - SDKSynchronizer's errors refactored to ZcashError [#951] Update error handling in SDKSynchronizer (#1002) - comments resolved Make DerivationTool constructor public DerivationTool.init should be public. This was removed by accident when adopting async. [#361] Add changelog
2023-04-24 14:15:20 -07:00
var walletBirthday: BlockHeight { walletBirthdayProvider() }
let downloadBufferSize: Int = 10
let network: ZcashNetwork
let saplingActivation: BlockHeight
let cacheDbURL: URL?
var blockPollInterval: TimeInterval {
2021-09-17 06:49:58 -07:00
TimeInterval.random(in: ZcashSDK.defaultPollInterval / 2 ... ZcashSDK.defaultPollInterval * 1.5)
}
[#361] Introduce ZcashError (#1005) This PR introduces `ZcashError` enum. This enum represents any error that can be thrown inside of the SDK and outside of the SDK. Also `ZcashError` is used in `LightWalletGRPCService` and handled in `CompactBlockProcessor` as example. Why enum? First I tried this with some structure which contained code, message and underlyingError. Problem was when some specific place in the SDK would like to attach some additional data to error. I didn't want to add some generic dictionary to store anything with the error. So I used enum to identify error. Each member can have specified amount of associated values. So specific error can bring some context data. And it's type safe. Each error has also a code. Relationship between errors and codes is 1:1. It may looks bit redundant but it's important. The client app now can choose how to process errors. Either identify those by the error itself or by code. Definition or errors and codes is in `ZcashErrorDefinition`. And then `ZcashError` and `ZcashErrorCode` are generated by Sourcery. Thanks to this it is easier to maintain the final code. And it gives us ability to generate any kind of documentation for the errors and codes. I created simple example of this in this PR. And it doesn't make the SDK completely dependent on the Sourcery. Final structures aren't super complicated and can be written manually if needed. [#923] Update error handling in DatabaseStorageManager.swift - cleanup of DatabaseStorageManager, not used anymore - ZcashError for SimpleConnectionProvider Revert "[#923] Update error handling in DatabaseStorageManager.swift" This reverts commit 94e028d31a0f6635800c297eb741db74c6a6ff45. Fix script which generates ZcashError [#922] Update error handling in DatabaseMigrationManager.swift Closes #922 [#923] Update error handling in DatabaseStorageManager.swift - The DatabaseStorageManager is not used so I deleted it - SimpleConnectionProvider's errors updated Fix tests [#955] Update error handling in SaplingParameterDownloader Closes #955 [#936] Update error handling in NotesDao Closes #936 [#935] Update error handling in BlockDao Closes #935 [#931] InternalSyncProgress.computeNextState doesn't need to throw Closes #931 [#950] Update error handling in rust backend Closes #949 Closes #950 [#941] Update error handling in AccountEntity Closes #941 [#928] Update error handling in FSCompactBlockRepository Closes #928 [#925] Update error handling in BlockDownloaderService (#974) - BlockDownloaderService errors updated [#924] Update error handling in BlockDownloader (#973) - BlockDownloaderStream nextBlock updated [#942] Update error handling in TransactionEntity (#977) - ZcashTransaction init errors converted to the ZcashError [#939] Update error handling in TransactionDao (#976) - TransactionRepositoryError removed and replaced with ZcashError - all TransactionDAO errors converted to ZcashError [#943] Update error handling in ZcashCompactBlock Closes #943 [#945] Update error handling in Memo Closes #945 [#934] Update error handling in Checkpoint Closes #944 Closes #934 [#938] Update error handling in PendingTransactionDao Closes #938 [#926] Update error handling in BlockEnhancer - WIP, switching to transaction repository to unblock this ticket [#926] Update error handling in BlockEnhancer - enhancer's errors done [#926] Update error handling in BlockEnhancer (#994) - cleanup [#952] Update error handling in DerivationTool Closes #952 [#932] Update error handling in BlockValidator Closes #932 [#940] Update error handling in UnspentTransactionOutputDao Closes #940 [#946] Update error handling in WalletTypes Closes #946 [#954] Update error handling in WalletTransactionEncoder Closes #954 [#953] Update error handling in PersistentTransactionManager Closes #953 [#956] Update error handling in Initializer Closes #956 [#947] Update error handling in Zatoshi (#996) - Zatoshi's errors converted to ZcashError [#927] Update error handling in UTXOFetcher (#997) - UTXOFetcher resolved Use let instead of var where applicable In the SDK `var` was used on places where `let` would be sufficient. And default strategy in Swift should use use `let` until mutability is required. So all these places are changed. No logic is changed. [#933] Update error handling in CompactBlockProcessor - CompactBlockProcessor's errors refactored to ZcashError [#933] Update error handling in CompactBlockProcessor #999 - comments addressed [#951] Update error handling in SDKSynchronizer - SDKSynchronizer's errors refactored to ZcashError [#951] Update error handling in SDKSynchronizer (#1002) - comments resolved Make DerivationTool constructor public DerivationTool.init should be public. This was removed by accident when adopting async. [#361] Add changelog
2023-04-24 14:15:20 -07:00
init(
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
alias: ZcashSynchronizerAlias,
- [#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
cacheDbURL: URL? = nil,
fsBlockCacheRoot: URL,
2021-07-26 16:22:30 -07:00
dataDb: URL,
spendParamsURL: URL,
outputParamsURL: URL,
saplingParamsSourceURL: SaplingParamsSourceURL,
[#361] Introduce ZcashError (#1005) This PR introduces `ZcashError` enum. This enum represents any error that can be thrown inside of the SDK and outside of the SDK. Also `ZcashError` is used in `LightWalletGRPCService` and handled in `CompactBlockProcessor` as example. Why enum? First I tried this with some structure which contained code, message and underlyingError. Problem was when some specific place in the SDK would like to attach some additional data to error. I didn't want to add some generic dictionary to store anything with the error. So I used enum to identify error. Each member can have specified amount of associated values. So specific error can bring some context data. And it's type safe. Each error has also a code. Relationship between errors and codes is 1:1. It may looks bit redundant but it's important. The client app now can choose how to process errors. Either identify those by the error itself or by code. Definition or errors and codes is in `ZcashErrorDefinition`. And then `ZcashError` and `ZcashErrorCode` are generated by Sourcery. Thanks to this it is easier to maintain the final code. And it gives us ability to generate any kind of documentation for the errors and codes. I created simple example of this in this PR. And it doesn't make the SDK completely dependent on the Sourcery. Final structures aren't super complicated and can be written manually if needed. [#923] Update error handling in DatabaseStorageManager.swift - cleanup of DatabaseStorageManager, not used anymore - ZcashError for SimpleConnectionProvider Revert "[#923] Update error handling in DatabaseStorageManager.swift" This reverts commit 94e028d31a0f6635800c297eb741db74c6a6ff45. Fix script which generates ZcashError [#922] Update error handling in DatabaseMigrationManager.swift Closes #922 [#923] Update error handling in DatabaseStorageManager.swift - The DatabaseStorageManager is not used so I deleted it - SimpleConnectionProvider's errors updated Fix tests [#955] Update error handling in SaplingParameterDownloader Closes #955 [#936] Update error handling in NotesDao Closes #936 [#935] Update error handling in BlockDao Closes #935 [#931] InternalSyncProgress.computeNextState doesn't need to throw Closes #931 [#950] Update error handling in rust backend Closes #949 Closes #950 [#941] Update error handling in AccountEntity Closes #941 [#928] Update error handling in FSCompactBlockRepository Closes #928 [#925] Update error handling in BlockDownloaderService (#974) - BlockDownloaderService errors updated [#924] Update error handling in BlockDownloader (#973) - BlockDownloaderStream nextBlock updated [#942] Update error handling in TransactionEntity (#977) - ZcashTransaction init errors converted to the ZcashError [#939] Update error handling in TransactionDao (#976) - TransactionRepositoryError removed and replaced with ZcashError - all TransactionDAO errors converted to ZcashError [#943] Update error handling in ZcashCompactBlock Closes #943 [#945] Update error handling in Memo Closes #945 [#934] Update error handling in Checkpoint Closes #944 Closes #934 [#938] Update error handling in PendingTransactionDao Closes #938 [#926] Update error handling in BlockEnhancer - WIP, switching to transaction repository to unblock this ticket [#926] Update error handling in BlockEnhancer - enhancer's errors done [#926] Update error handling in BlockEnhancer (#994) - cleanup [#952] Update error handling in DerivationTool Closes #952 [#932] Update error handling in BlockValidator Closes #932 [#940] Update error handling in UnspentTransactionOutputDao Closes #940 [#946] Update error handling in WalletTypes Closes #946 [#954] Update error handling in WalletTransactionEncoder Closes #954 [#953] Update error handling in PersistentTransactionManager Closes #953 [#956] Update error handling in Initializer Closes #956 [#947] Update error handling in Zatoshi (#996) - Zatoshi's errors converted to ZcashError [#927] Update error handling in UTXOFetcher (#997) - UTXOFetcher resolved Use let instead of var where applicable In the SDK `var` was used on places where `let` would be sufficient. And default strategy in Swift should use use `let` until mutability is required. So all these places are changed. No logic is changed. [#933] Update error handling in CompactBlockProcessor - CompactBlockProcessor's errors refactored to ZcashError [#933] Update error handling in CompactBlockProcessor #999 - comments addressed [#951] Update error handling in SDKSynchronizer - SDKSynchronizer's errors refactored to ZcashError [#951] Update error handling in SDKSynchronizer (#1002) - comments resolved Make DerivationTool constructor public DerivationTool.init should be public. This was removed by accident when adopting async. [#361] Add changelog
2023-04-24 14:15:20 -07:00
downloadBatchSize: Int = ZcashSDK.DefaultDownloadBatch,
retries: Int = ZcashSDK.defaultRetries,
maxBackoffInterval: TimeInterval = ZcashSDK.defaultMaxBackOffInterval,
rewindDistance: Int = ZcashSDK.defaultRewindDistance,
scanningBatchSize: Int = ZcashSDK.DefaultScanningBatch,
walletBirthdayProvider: @escaping () -> BlockHeight,
2021-07-26 16:22:30 -07:00
saplingActivation: BlockHeight,
2021-07-28 09:59:10 -07:00
network: ZcashNetwork
2021-09-17 06:49:58 -07:00
) {
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
self.alias = alias
- [#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
self.fsBlockCacheRoot = fsBlockCacheRoot
self.dataDb = dataDb
self.spendParamsURL = spendParamsURL
self.outputParamsURL = outputParamsURL
self.saplingParamsSourceURL = saplingParamsSourceURL
2021-07-26 16:22:30 -07:00
self.network = network
self.downloadBatchSize = downloadBatchSize
self.retries = retries
self.maxBackoffInterval = maxBackoffInterval
self.rewindDistance = rewindDistance
[#361] Introduce ZcashError (#1005) This PR introduces `ZcashError` enum. This enum represents any error that can be thrown inside of the SDK and outside of the SDK. Also `ZcashError` is used in `LightWalletGRPCService` and handled in `CompactBlockProcessor` as example. Why enum? First I tried this with some structure which contained code, message and underlyingError. Problem was when some specific place in the SDK would like to attach some additional data to error. I didn't want to add some generic dictionary to store anything with the error. So I used enum to identify error. Each member can have specified amount of associated values. So specific error can bring some context data. And it's type safe. Each error has also a code. Relationship between errors and codes is 1:1. It may looks bit redundant but it's important. The client app now can choose how to process errors. Either identify those by the error itself or by code. Definition or errors and codes is in `ZcashErrorDefinition`. And then `ZcashError` and `ZcashErrorCode` are generated by Sourcery. Thanks to this it is easier to maintain the final code. And it gives us ability to generate any kind of documentation for the errors and codes. I created simple example of this in this PR. And it doesn't make the SDK completely dependent on the Sourcery. Final structures aren't super complicated and can be written manually if needed. [#923] Update error handling in DatabaseStorageManager.swift - cleanup of DatabaseStorageManager, not used anymore - ZcashError for SimpleConnectionProvider Revert "[#923] Update error handling in DatabaseStorageManager.swift" This reverts commit 94e028d31a0f6635800c297eb741db74c6a6ff45. Fix script which generates ZcashError [#922] Update error handling in DatabaseMigrationManager.swift Closes #922 [#923] Update error handling in DatabaseStorageManager.swift - The DatabaseStorageManager is not used so I deleted it - SimpleConnectionProvider's errors updated Fix tests [#955] Update error handling in SaplingParameterDownloader Closes #955 [#936] Update error handling in NotesDao Closes #936 [#935] Update error handling in BlockDao Closes #935 [#931] InternalSyncProgress.computeNextState doesn't need to throw Closes #931 [#950] Update error handling in rust backend Closes #949 Closes #950 [#941] Update error handling in AccountEntity Closes #941 [#928] Update error handling in FSCompactBlockRepository Closes #928 [#925] Update error handling in BlockDownloaderService (#974) - BlockDownloaderService errors updated [#924] Update error handling in BlockDownloader (#973) - BlockDownloaderStream nextBlock updated [#942] Update error handling in TransactionEntity (#977) - ZcashTransaction init errors converted to the ZcashError [#939] Update error handling in TransactionDao (#976) - TransactionRepositoryError removed and replaced with ZcashError - all TransactionDAO errors converted to ZcashError [#943] Update error handling in ZcashCompactBlock Closes #943 [#945] Update error handling in Memo Closes #945 [#934] Update error handling in Checkpoint Closes #944 Closes #934 [#938] Update error handling in PendingTransactionDao Closes #938 [#926] Update error handling in BlockEnhancer - WIP, switching to transaction repository to unblock this ticket [#926] Update error handling in BlockEnhancer - enhancer's errors done [#926] Update error handling in BlockEnhancer (#994) - cleanup [#952] Update error handling in DerivationTool Closes #952 [#932] Update error handling in BlockValidator Closes #932 [#940] Update error handling in UnspentTransactionOutputDao Closes #940 [#946] Update error handling in WalletTypes Closes #946 [#954] Update error handling in WalletTransactionEncoder Closes #954 [#953] Update error handling in PersistentTransactionManager Closes #953 [#956] Update error handling in Initializer Closes #956 [#947] Update error handling in Zatoshi (#996) - Zatoshi's errors converted to ZcashError [#927] Update error handling in UTXOFetcher (#997) - UTXOFetcher resolved Use let instead of var where applicable In the SDK `var` was used on places where `let` would be sufficient. And default strategy in Swift should use use `let` until mutability is required. So all these places are changed. No logic is changed. [#933] Update error handling in CompactBlockProcessor - CompactBlockProcessor's errors refactored to ZcashError [#933] Update error handling in CompactBlockProcessor #999 - comments addressed [#951] Update error handling in SDKSynchronizer - SDKSynchronizer's errors refactored to ZcashError [#951] Update error handling in SDKSynchronizer (#1002) - comments resolved Make DerivationTool constructor public DerivationTool.init should be public. This was removed by accident when adopting async. [#361] Add changelog
2023-04-24 14:15:20 -07:00
self.scanningBatchSize = scanningBatchSize
self.walletBirthdayProvider = walletBirthdayProvider
self.saplingActivation = saplingActivation
- [#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
self.cacheDbURL = cacheDbURL
assert(downloadBatchSize >= scanningBatchSize)
}
init(
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
alias: ZcashSynchronizerAlias,
- [#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
fsBlockCacheRoot: URL,
dataDb: URL,
spendParamsURL: URL,
outputParamsURL: URL,
saplingParamsSourceURL: SaplingParamsSourceURL,
[#361] Introduce ZcashError (#1005) This PR introduces `ZcashError` enum. This enum represents any error that can be thrown inside of the SDK and outside of the SDK. Also `ZcashError` is used in `LightWalletGRPCService` and handled in `CompactBlockProcessor` as example. Why enum? First I tried this with some structure which contained code, message and underlyingError. Problem was when some specific place in the SDK would like to attach some additional data to error. I didn't want to add some generic dictionary to store anything with the error. So I used enum to identify error. Each member can have specified amount of associated values. So specific error can bring some context data. And it's type safe. Each error has also a code. Relationship between errors and codes is 1:1. It may looks bit redundant but it's important. The client app now can choose how to process errors. Either identify those by the error itself or by code. Definition or errors and codes is in `ZcashErrorDefinition`. And then `ZcashError` and `ZcashErrorCode` are generated by Sourcery. Thanks to this it is easier to maintain the final code. And it gives us ability to generate any kind of documentation for the errors and codes. I created simple example of this in this PR. And it doesn't make the SDK completely dependent on the Sourcery. Final structures aren't super complicated and can be written manually if needed. [#923] Update error handling in DatabaseStorageManager.swift - cleanup of DatabaseStorageManager, not used anymore - ZcashError for SimpleConnectionProvider Revert "[#923] Update error handling in DatabaseStorageManager.swift" This reverts commit 94e028d31a0f6635800c297eb741db74c6a6ff45. Fix script which generates ZcashError [#922] Update error handling in DatabaseMigrationManager.swift Closes #922 [#923] Update error handling in DatabaseStorageManager.swift - The DatabaseStorageManager is not used so I deleted it - SimpleConnectionProvider's errors updated Fix tests [#955] Update error handling in SaplingParameterDownloader Closes #955 [#936] Update error handling in NotesDao Closes #936 [#935] Update error handling in BlockDao Closes #935 [#931] InternalSyncProgress.computeNextState doesn't need to throw Closes #931 [#950] Update error handling in rust backend Closes #949 Closes #950 [#941] Update error handling in AccountEntity Closes #941 [#928] Update error handling in FSCompactBlockRepository Closes #928 [#925] Update error handling in BlockDownloaderService (#974) - BlockDownloaderService errors updated [#924] Update error handling in BlockDownloader (#973) - BlockDownloaderStream nextBlock updated [#942] Update error handling in TransactionEntity (#977) - ZcashTransaction init errors converted to the ZcashError [#939] Update error handling in TransactionDao (#976) - TransactionRepositoryError removed and replaced with ZcashError - all TransactionDAO errors converted to ZcashError [#943] Update error handling in ZcashCompactBlock Closes #943 [#945] Update error handling in Memo Closes #945 [#934] Update error handling in Checkpoint Closes #944 Closes #934 [#938] Update error handling in PendingTransactionDao Closes #938 [#926] Update error handling in BlockEnhancer - WIP, switching to transaction repository to unblock this ticket [#926] Update error handling in BlockEnhancer - enhancer's errors done [#926] Update error handling in BlockEnhancer (#994) - cleanup [#952] Update error handling in DerivationTool Closes #952 [#932] Update error handling in BlockValidator Closes #932 [#940] Update error handling in UnspentTransactionOutputDao Closes #940 [#946] Update error handling in WalletTypes Closes #946 [#954] Update error handling in WalletTransactionEncoder Closes #954 [#953] Update error handling in PersistentTransactionManager Closes #953 [#956] Update error handling in Initializer Closes #956 [#947] Update error handling in Zatoshi (#996) - Zatoshi's errors converted to ZcashError [#927] Update error handling in UTXOFetcher (#997) - UTXOFetcher resolved Use let instead of var where applicable In the SDK `var` was used on places where `let` would be sufficient. And default strategy in Swift should use use `let` until mutability is required. So all these places are changed. No logic is changed. [#933] Update error handling in CompactBlockProcessor - CompactBlockProcessor's errors refactored to ZcashError [#933] Update error handling in CompactBlockProcessor #999 - comments addressed [#951] Update error handling in SDKSynchronizer - SDKSynchronizer's errors refactored to ZcashError [#951] Update error handling in SDKSynchronizer (#1002) - comments resolved Make DerivationTool constructor public DerivationTool.init should be public. This was removed by accident when adopting async. [#361] Add changelog
2023-04-24 14:15:20 -07:00
downloadBatchSize: Int = ZcashSDK.DefaultDownloadBatch,
retries: Int = ZcashSDK.defaultRetries,
maxBackoffInterval: TimeInterval = ZcashSDK.defaultMaxBackOffInterval,
rewindDistance: Int = ZcashSDK.defaultRewindDistance,
scanningBatchSize: Int = ZcashSDK.DefaultScanningBatch,
walletBirthdayProvider: @escaping () -> BlockHeight,
network: ZcashNetwork
) {
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
self.alias = alias
- [#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
self.fsBlockCacheRoot = fsBlockCacheRoot
self.dataDb = dataDb
self.spendParamsURL = spendParamsURL
self.outputParamsURL = outputParamsURL
self.saplingParamsSourceURL = saplingParamsSourceURL
self.walletBirthdayProvider = walletBirthdayProvider
2021-09-15 05:21:29 -07:00
self.saplingActivation = network.constants.saplingActivationHeight
2021-07-28 09:59:10 -07:00
self.network = network
- [#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
self.cacheDbURL = nil
[#361] Introduce ZcashError (#1005) This PR introduces `ZcashError` enum. This enum represents any error that can be thrown inside of the SDK and outside of the SDK. Also `ZcashError` is used in `LightWalletGRPCService` and handled in `CompactBlockProcessor` as example. Why enum? First I tried this with some structure which contained code, message and underlyingError. Problem was when some specific place in the SDK would like to attach some additional data to error. I didn't want to add some generic dictionary to store anything with the error. So I used enum to identify error. Each member can have specified amount of associated values. So specific error can bring some context data. And it's type safe. Each error has also a code. Relationship between errors and codes is 1:1. It may looks bit redundant but it's important. The client app now can choose how to process errors. Either identify those by the error itself or by code. Definition or errors and codes is in `ZcashErrorDefinition`. And then `ZcashError` and `ZcashErrorCode` are generated by Sourcery. Thanks to this it is easier to maintain the final code. And it gives us ability to generate any kind of documentation for the errors and codes. I created simple example of this in this PR. And it doesn't make the SDK completely dependent on the Sourcery. Final structures aren't super complicated and can be written manually if needed. [#923] Update error handling in DatabaseStorageManager.swift - cleanup of DatabaseStorageManager, not used anymore - ZcashError for SimpleConnectionProvider Revert "[#923] Update error handling in DatabaseStorageManager.swift" This reverts commit 94e028d31a0f6635800c297eb741db74c6a6ff45. Fix script which generates ZcashError [#922] Update error handling in DatabaseMigrationManager.swift Closes #922 [#923] Update error handling in DatabaseStorageManager.swift - The DatabaseStorageManager is not used so I deleted it - SimpleConnectionProvider's errors updated Fix tests [#955] Update error handling in SaplingParameterDownloader Closes #955 [#936] Update error handling in NotesDao Closes #936 [#935] Update error handling in BlockDao Closes #935 [#931] InternalSyncProgress.computeNextState doesn't need to throw Closes #931 [#950] Update error handling in rust backend Closes #949 Closes #950 [#941] Update error handling in AccountEntity Closes #941 [#928] Update error handling in FSCompactBlockRepository Closes #928 [#925] Update error handling in BlockDownloaderService (#974) - BlockDownloaderService errors updated [#924] Update error handling in BlockDownloader (#973) - BlockDownloaderStream nextBlock updated [#942] Update error handling in TransactionEntity (#977) - ZcashTransaction init errors converted to the ZcashError [#939] Update error handling in TransactionDao (#976) - TransactionRepositoryError removed and replaced with ZcashError - all TransactionDAO errors converted to ZcashError [#943] Update error handling in ZcashCompactBlock Closes #943 [#945] Update error handling in Memo Closes #945 [#934] Update error handling in Checkpoint Closes #944 Closes #934 [#938] Update error handling in PendingTransactionDao Closes #938 [#926] Update error handling in BlockEnhancer - WIP, switching to transaction repository to unblock this ticket [#926] Update error handling in BlockEnhancer - enhancer's errors done [#926] Update error handling in BlockEnhancer (#994) - cleanup [#952] Update error handling in DerivationTool Closes #952 [#932] Update error handling in BlockValidator Closes #932 [#940] Update error handling in UnspentTransactionOutputDao Closes #940 [#946] Update error handling in WalletTypes Closes #946 [#954] Update error handling in WalletTransactionEncoder Closes #954 [#953] Update error handling in PersistentTransactionManager Closes #953 [#956] Update error handling in Initializer Closes #956 [#947] Update error handling in Zatoshi (#996) - Zatoshi's errors converted to ZcashError [#927] Update error handling in UTXOFetcher (#997) - UTXOFetcher resolved Use let instead of var where applicable In the SDK `var` was used on places where `let` would be sufficient. And default strategy in Swift should use use `let` until mutability is required. So all these places are changed. No logic is changed. [#933] Update error handling in CompactBlockProcessor - CompactBlockProcessor's errors refactored to ZcashError [#933] Update error handling in CompactBlockProcessor #999 - comments addressed [#951] Update error handling in SDKSynchronizer - SDKSynchronizer's errors refactored to ZcashError [#951] Update error handling in SDKSynchronizer (#1002) - comments resolved Make DerivationTool constructor public DerivationTool.init should be public. This was removed by accident when adopting async. [#361] Add changelog
2023-04-24 14:15:20 -07:00
self.downloadBatchSize = downloadBatchSize
self.retries = retries
self.maxBackoffInterval = maxBackoffInterval
self.rewindDistance = rewindDistance
self.scanningBatchSize = scanningBatchSize
assert(downloadBatchSize >= scanningBatchSize)
}
}
2021-09-17 06:49:58 -07:00
/**
2021-09-17 06:49:58 -07:00
Represents the possible states of a CompactBlockProcessor
*/
enum State {
/**
2021-09-17 06:49:58 -07:00
connected and downloading blocks
*/
case syncing
[#831] Add SDKSynchronizer wrappers for non-async API This change introduces two new protocols: `ClosureSynchronizer` and `CombineSynchronizer`. These two protocols define API that doesn't use `async`. So the client can choose exactly which API it wants to use. This change also introduces two new objects: `ClosureSDKSynchronizer` and `CombineSDKSynchronizer`. These two implement the respective protocols mentioned above. Both are structures. Neither of these two keeps any state. Thanks to this each is very cheap to create. And usage of these two isn't mutually exclusive. So devs can really choose the best SDK API for each part of the client app. [#831] Use async inside of the SDKSynchronizer - In general lot of methods inside the `SDKSynchronizer` and `CompactBlockProcessoer` which weren't async are now async. And other changes are made because of this change. - `CompactBlockProcessor` no longer uses Combine to communicate with `SDKSynchronizer`. Reason for this is that Combine doesn't play great with async. Closure passed to `sink` isn't async. - Because of this and because of how our tests work (receiving signals from CBP directly) `CompactBlockProcessor` must be able to handle more event closures. Not just one. So it now has `eventClosures` dictionary. It's little bit strange but it works fine. - `SyncStatus` inside the `SDKSynchronizer` was previously protected by lock. Now it's protected by simple actor wrapper. - Changes in tests are minimal. Changes were mady only because `CompactBlockProcessor` changes from Combine to closures. [#831] Add tests for ClosureSDKSynchronizer - Added tests are testing in general if the `ClosuresSDKSynchronizer` is correctly calling `Synchronizer` and if the values are correctly returned. - `ClosuresSDKSynchronizer` doesn't contain any logic but it is public API and we should be sure that it works correctly. [#831] Add tests for CombineSDKSynchronizer [#831] Add changelog
2023-03-16 02:11:18 -07:00
/**
2021-09-17 06:49:58 -07:00
was doing something but was paused
*/
case stopped
2021-09-17 06:49:58 -07:00
/**
2021-09-17 06:49:58 -07:00
Processor is Enhancing transactions
*/
case enhancing
/**
2021-09-17 06:49:58 -07:00
fetching utxos
*/
case fetching
2021-09-17 06:49:58 -07:00
/**
2021-09-17 06:49:58 -07:00
was processing but erred
*/
case error(_ error: Error)
/// Download sapling param files if needed.
case handlingSaplingFiles
/**
2021-09-17 06:49:58 -07:00
Processor is up to date with the blockchain and you can now make transactions.
*/
case synced
}
private var afterSyncHooksManager = AfterSyncHooksManager()
[#831] Add SDKSynchronizer wrappers for non-async API This change introduces two new protocols: `ClosureSynchronizer` and `CombineSynchronizer`. These two protocols define API that doesn't use `async`. So the client can choose exactly which API it wants to use. This change also introduces two new objects: `ClosureSDKSynchronizer` and `CombineSDKSynchronizer`. These two implement the respective protocols mentioned above. Both are structures. Neither of these two keeps any state. Thanks to this each is very cheap to create. And usage of these two isn't mutually exclusive. So devs can really choose the best SDK API for each part of the client app. [#831] Use async inside of the SDKSynchronizer - In general lot of methods inside the `SDKSynchronizer` and `CompactBlockProcessoer` which weren't async are now async. And other changes are made because of this change. - `CompactBlockProcessor` no longer uses Combine to communicate with `SDKSynchronizer`. Reason for this is that Combine doesn't play great with async. Closure passed to `sink` isn't async. - Because of this and because of how our tests work (receiving signals from CBP directly) `CompactBlockProcessor` must be able to handle more event closures. Not just one. So it now has `eventClosures` dictionary. It's little bit strange but it works fine. - `SyncStatus` inside the `SDKSynchronizer` was previously protected by lock. Now it's protected by simple actor wrapper. - Changes in tests are minimal. Changes were mady only because `CompactBlockProcessor` changes from Combine to closures. [#831] Add tests for ClosureSDKSynchronizer - Added tests are testing in general if the `ClosuresSDKSynchronizer` is correctly calling `Synchronizer` and if the values are correctly returned. - `ClosuresSDKSynchronizer` doesn't contain any logic but it is public API and we should be sure that it works correctly. [#831] Add tests for CombineSDKSynchronizer [#831] Add changelog
2023-03-16 02:11:18 -07:00
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
let metrics: SDKMetrics
let logger: Logger
[#831] Add SDKSynchronizer wrappers for non-async API This change introduces two new protocols: `ClosureSynchronizer` and `CombineSynchronizer`. These two protocols define API that doesn't use `async`. So the client can choose exactly which API it wants to use. This change also introduces two new objects: `ClosureSDKSynchronizer` and `CombineSDKSynchronizer`. These two implement the respective protocols mentioned above. Both are structures. Neither of these two keeps any state. Thanks to this each is very cheap to create. And usage of these two isn't mutually exclusive. So devs can really choose the best SDK API for each part of the client app. [#831] Use async inside of the SDKSynchronizer - In general lot of methods inside the `SDKSynchronizer` and `CompactBlockProcessoer` which weren't async are now async. And other changes are made because of this change. - `CompactBlockProcessor` no longer uses Combine to communicate with `SDKSynchronizer`. Reason for this is that Combine doesn't play great with async. Closure passed to `sink` isn't async. - Because of this and because of how our tests work (receiving signals from CBP directly) `CompactBlockProcessor` must be able to handle more event closures. Not just one. So it now has `eventClosures` dictionary. It's little bit strange but it works fine. - `SyncStatus` inside the `SDKSynchronizer` was previously protected by lock. Now it's protected by simple actor wrapper. - Changes in tests are minimal. Changes were mady only because `CompactBlockProcessor` changes from Combine to closures. [#831] Add tests for ClosureSDKSynchronizer - Added tests are testing in general if the `ClosuresSDKSynchronizer` is correctly calling `Synchronizer` and if the values are correctly returned. - `ClosuresSDKSynchronizer` doesn't contain any logic but it is public API and we should be sure that it works correctly. [#831] Add tests for CombineSDKSynchronizer [#831] Add changelog
2023-03-16 02:11:18 -07:00
/// Don't update this variable directly. Use `updateState()` method.
var state: State = .stopped
private(set) var config: Configuration
2021-09-17 06:49:58 -07:00
var maxAttemptsReached: Bool {
self.retryAttempts >= self.config.retries
}
2021-09-17 06:49:58 -07:00
var shouldStart: Bool {
switch self.state {
2021-09-17 06:49:58 -07:00
case .stopped, .synced, .error:
return !maxAttemptsReached
default:
return false
}
}
[#831] Add SDKSynchronizer wrappers for non-async API This change introduces two new protocols: `ClosureSynchronizer` and `CombineSynchronizer`. These two protocols define API that doesn't use `async`. So the client can choose exactly which API it wants to use. This change also introduces two new objects: `ClosureSDKSynchronizer` and `CombineSDKSynchronizer`. These two implement the respective protocols mentioned above. Both are structures. Neither of these two keeps any state. Thanks to this each is very cheap to create. And usage of these two isn't mutually exclusive. So devs can really choose the best SDK API for each part of the client app. [#831] Use async inside of the SDKSynchronizer - In general lot of methods inside the `SDKSynchronizer` and `CompactBlockProcessoer` which weren't async are now async. And other changes are made because of this change. - `CompactBlockProcessor` no longer uses Combine to communicate with `SDKSynchronizer`. Reason for this is that Combine doesn't play great with async. Closure passed to `sink` isn't async. - Because of this and because of how our tests work (receiving signals from CBP directly) `CompactBlockProcessor` must be able to handle more event closures. Not just one. So it now has `eventClosures` dictionary. It's little bit strange but it works fine. - `SyncStatus` inside the `SDKSynchronizer` was previously protected by lock. Now it's protected by simple actor wrapper. - Changes in tests are minimal. Changes were mady only because `CompactBlockProcessor` changes from Combine to closures. [#831] Add tests for ClosureSDKSynchronizer - Added tests are testing in general if the `ClosuresSDKSynchronizer` is correctly calling `Synchronizer` and if the values are correctly returned. - `ClosuresSDKSynchronizer` doesn't contain any logic but it is public API and we should be sure that it works correctly. [#831] Add tests for CombineSDKSynchronizer [#831] Add changelog
2023-03-16 02:11:18 -07:00
// It would be better to use Combine here but Combine doesn't work great with async. When this runs regularly only one closure is stored here
// and that is one provided by `SDKSynchronizer`. But while running tests more "subscribers" is required here. Therefore it's required to handle
// more closures here.
var eventClosures: [String: EventClosure] = [:]
let blockDownloaderService: BlockDownloaderService
let blockDownloader: BlockDownloader
let blockValidator: BlockValidator
let blockScanner: BlockScanner
let blockEnhancer: BlockEnhancer
let utxoFetcher: UTXOFetcher
let saplingParametersHandler: SaplingParametersHandler
private let latestBlocksDataProvider: LatestBlocksDataProvider
[#361] Introduce ZcashError (#1005) This PR introduces `ZcashError` enum. This enum represents any error that can be thrown inside of the SDK and outside of the SDK. Also `ZcashError` is used in `LightWalletGRPCService` and handled in `CompactBlockProcessor` as example. Why enum? First I tried this with some structure which contained code, message and underlyingError. Problem was when some specific place in the SDK would like to attach some additional data to error. I didn't want to add some generic dictionary to store anything with the error. So I used enum to identify error. Each member can have specified amount of associated values. So specific error can bring some context data. And it's type safe. Each error has also a code. Relationship between errors and codes is 1:1. It may looks bit redundant but it's important. The client app now can choose how to process errors. Either identify those by the error itself or by code. Definition or errors and codes is in `ZcashErrorDefinition`. And then `ZcashError` and `ZcashErrorCode` are generated by Sourcery. Thanks to this it is easier to maintain the final code. And it gives us ability to generate any kind of documentation for the errors and codes. I created simple example of this in this PR. And it doesn't make the SDK completely dependent on the Sourcery. Final structures aren't super complicated and can be written manually if needed. [#923] Update error handling in DatabaseStorageManager.swift - cleanup of DatabaseStorageManager, not used anymore - ZcashError for SimpleConnectionProvider Revert "[#923] Update error handling in DatabaseStorageManager.swift" This reverts commit 94e028d31a0f6635800c297eb741db74c6a6ff45. Fix script which generates ZcashError [#922] Update error handling in DatabaseMigrationManager.swift Closes #922 [#923] Update error handling in DatabaseStorageManager.swift - The DatabaseStorageManager is not used so I deleted it - SimpleConnectionProvider's errors updated Fix tests [#955] Update error handling in SaplingParameterDownloader Closes #955 [#936] Update error handling in NotesDao Closes #936 [#935] Update error handling in BlockDao Closes #935 [#931] InternalSyncProgress.computeNextState doesn't need to throw Closes #931 [#950] Update error handling in rust backend Closes #949 Closes #950 [#941] Update error handling in AccountEntity Closes #941 [#928] Update error handling in FSCompactBlockRepository Closes #928 [#925] Update error handling in BlockDownloaderService (#974) - BlockDownloaderService errors updated [#924] Update error handling in BlockDownloader (#973) - BlockDownloaderStream nextBlock updated [#942] Update error handling in TransactionEntity (#977) - ZcashTransaction init errors converted to the ZcashError [#939] Update error handling in TransactionDao (#976) - TransactionRepositoryError removed and replaced with ZcashError - all TransactionDAO errors converted to ZcashError [#943] Update error handling in ZcashCompactBlock Closes #943 [#945] Update error handling in Memo Closes #945 [#934] Update error handling in Checkpoint Closes #944 Closes #934 [#938] Update error handling in PendingTransactionDao Closes #938 [#926] Update error handling in BlockEnhancer - WIP, switching to transaction repository to unblock this ticket [#926] Update error handling in BlockEnhancer - enhancer's errors done [#926] Update error handling in BlockEnhancer (#994) - cleanup [#952] Update error handling in DerivationTool Closes #952 [#932] Update error handling in BlockValidator Closes #932 [#940] Update error handling in UnspentTransactionOutputDao Closes #940 [#946] Update error handling in WalletTypes Closes #946 [#954] Update error handling in WalletTransactionEncoder Closes #954 [#953] Update error handling in PersistentTransactionManager Closes #953 [#956] Update error handling in Initializer Closes #956 [#947] Update error handling in Zatoshi (#996) - Zatoshi's errors converted to ZcashError [#927] Update error handling in UTXOFetcher (#997) - UTXOFetcher resolved Use let instead of var where applicable In the SDK `var` was used on places where `let` would be sufficient. And default strategy in Swift should use use `let` until mutability is required. So all these places are changed. No logic is changed. [#933] Update error handling in CompactBlockProcessor - CompactBlockProcessor's errors refactored to ZcashError [#933] Update error handling in CompactBlockProcessor #999 - comments addressed [#951] Update error handling in SDKSynchronizer - SDKSynchronizer's errors refactored to ZcashError [#951] Update error handling in SDKSynchronizer (#1002) - comments resolved Make DerivationTool constructor public DerivationTool.init should be public. This was removed by accident when adopting async. [#361] Add changelog
2023-04-24 14:15:20 -07:00
let service: LightWalletService
let storage: CompactBlockRepository
let transactionRepository: TransactionRepository
let accountRepository: AccountRepository
let rustBackend: ZcashRustBackendWelding
private var retryAttempts: Int = 0
private var backoffTimer: Timer?
private var lastChainValidationFailure: BlockHeight?
private var consecutiveChainValidationErrors: Int = 0
[476] CompactBlockProcessor to async/await - getting rid of the Operation Queue - the cleanup is needed - the update of tests is needed - tested and it successfully finishes the sync process [476] CompactBlockProcessor to async/await - old processNewBlocks() removed [476] CompactBlockProcessor to async/await - unused operations removed [476] CompactBlockProcessor to async/await - unit tests update [476] CompactBlockProcessor to async/await - unit tests refactored [476] CompactBlockProcessor to async/await - cleanup of deprecated method [476] CompactBlockProcessor to async/await - fail(error) was called even for canceled tasks but that must be excluded [476] CompactBlockProcessor to async/await - removal of all ZcashOperations from the code (unit test will follow) [476] CompactBlockProcessor to async/await - network tests in building and success order again [476] CompactBlockProcessor to async/await - offline tests in building and success order [476] CompactBlockProcessor to async/await (519) - cleanup of suspending the task [476] CompactBlockProcessor to async/await (519) - most comments resolved [476] CompactBlockProcessor to async/await (519) - thread safe state for both sync and async context [476] CompactBlockProcessor to async/await (519) - fixed build for a sample project [476] CompactBlockProcessor to async/await (519) - func testStartNotifiesSuscriptors() reverted [476] CompactBlockProcessor to async/await (519) - TODO added to track why we used NSLock instead of an Actor - Task priority enhanced [476] CompactBlockProcessor to async/await (519) - cleanup in Tasks and priorities
2022-09-01 05:58:41 -07:00
var processingError: Error?
2021-09-17 06:49:58 -07:00
private var foundBlocks = false
private var maxAttempts: Int {
config.retries
}
var batchSize: BlockHeight {
BlockHeight(self.config.downloadBatchSize)
}
2021-09-17 06:49:58 -07:00
[476] CompactBlockProcessor to async/await - getting rid of the Operation Queue - the cleanup is needed - the update of tests is needed - tested and it successfully finishes the sync process [476] CompactBlockProcessor to async/await - old processNewBlocks() removed [476] CompactBlockProcessor to async/await - unused operations removed [476] CompactBlockProcessor to async/await - unit tests update [476] CompactBlockProcessor to async/await - unit tests refactored [476] CompactBlockProcessor to async/await - cleanup of deprecated method [476] CompactBlockProcessor to async/await - fail(error) was called even for canceled tasks but that must be excluded [476] CompactBlockProcessor to async/await - removal of all ZcashOperations from the code (unit test will follow) [476] CompactBlockProcessor to async/await - network tests in building and success order again [476] CompactBlockProcessor to async/await - offline tests in building and success order [476] CompactBlockProcessor to async/await (519) - cleanup of suspending the task [476] CompactBlockProcessor to async/await (519) - most comments resolved [476] CompactBlockProcessor to async/await (519) - thread safe state for both sync and async context [476] CompactBlockProcessor to async/await (519) - fixed build for a sample project [476] CompactBlockProcessor to async/await (519) - func testStartNotifiesSuscriptors() reverted [476] CompactBlockProcessor to async/await (519) - TODO added to track why we used NSLock instead of an Actor - Task priority enhanced [476] CompactBlockProcessor to async/await (519) - cleanup in Tasks and priorities
2022-09-01 05:58:41 -07:00
private var cancelableTask: Task<Void, Error>?
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
private let internalSyncProgress: InternalSyncProgress
/// Initializes a CompactBlockProcessor instance
/// - Parameters:
/// - service: concrete implementation of `LightWalletService` protocol
- [#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
/// - storage: concrete implementation of `CompactBlockRepository` protocol
/// - backend: a class that complies to `ZcashRustBackendWelding`
/// - config: `Configuration` struct for this processor
init(
container: DIContainer,
config: Configuration
2021-09-15 05:21:29 -07:00
) {
self.init(
container: container,
2021-09-15 05:21:29 -07:00
config: config,
accountRepository: AccountRepositoryBuilder.build(dataDbURL: config.dataDb, readOnly: true, logger: container.resolve(Logger.self))
2021-09-17 06:49:58 -07:00
)
}
/// Initializes a CompactBlockProcessor instance from an Initialized object
- [#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
/// - Parameters:
/// - initializer: an instance that complies to CompactBlockDownloading protocol
init(initializer: Initializer, walletBirthdayProvider: @escaping () -> BlockHeight) {
2021-09-15 05:21:29 -07:00
self.init(
container: initializer.container,
2021-09-15 05:21:29 -07:00
config: Configuration(
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
alias: initializer.alias,
- [#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
fsBlockCacheRoot: initializer.fsBlockDbRoot,
2021-09-15 05:21:29 -07:00
dataDb: initializer.dataDbURL,
spendParamsURL: initializer.spendParamsURL,
outputParamsURL: initializer.outputParamsURL,
saplingParamsSourceURL: initializer.saplingParamsSourceURL,
walletBirthdayProvider: walletBirthdayProvider,
2021-09-15 05:21:29 -07:00
network: initializer.network
),
accountRepository: initializer.accountRepository
2021-09-17 06:49:58 -07:00
)
}
2021-09-15 05:21:29 -07:00
internal init(
container: DIContainer,
2021-09-15 05:21:29 -07:00
config: Configuration,
accountRepository: AccountRepository
2021-09-15 05:21:29 -07:00
) {
Dependencies.setupCompactBlockProcessor(
in: container,
config: config,
accountRepository: accountRepository
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
)
self.metrics = container.resolve(SDKMetrics.self)
self.logger = container.resolve(Logger.self)
self.latestBlocksDataProvider = container.resolve(LatestBlocksDataProvider.self)
self.internalSyncProgress = container.resolve(InternalSyncProgress.self)
self.blockDownloaderService = container.resolve(BlockDownloaderService.self)
self.blockDownloader = container.resolve(BlockDownloader.self)
self.blockValidator = container.resolve(BlockValidator.self)
self.blockScanner = container.resolve(BlockScanner.self)
self.blockEnhancer = container.resolve(BlockEnhancer.self)
self.utxoFetcher = container.resolve(UTXOFetcher.self)
self.saplingParametersHandler = container.resolve(SaplingParametersHandler.self)
self.service = container.resolve(LightWalletService.self)
self.rustBackend = container.resolve(ZcashRustBackendWelding.self)
self.storage = container.resolve(CompactBlockRepository.self)
self.config = config
self.transactionRepository = container.resolve(TransactionRepository.self)
2021-04-08 10:18:16 -07:00
self.accountRepository = accountRepository
}
deinit {
[476] CompactBlockProcessor to async/await - getting rid of the Operation Queue - the cleanup is needed - the update of tests is needed - tested and it successfully finishes the sync process [476] CompactBlockProcessor to async/await - old processNewBlocks() removed [476] CompactBlockProcessor to async/await - unused operations removed [476] CompactBlockProcessor to async/await - unit tests update [476] CompactBlockProcessor to async/await - unit tests refactored [476] CompactBlockProcessor to async/await - cleanup of deprecated method [476] CompactBlockProcessor to async/await - fail(error) was called even for canceled tasks but that must be excluded [476] CompactBlockProcessor to async/await - removal of all ZcashOperations from the code (unit test will follow) [476] CompactBlockProcessor to async/await - network tests in building and success order again [476] CompactBlockProcessor to async/await - offline tests in building and success order [476] CompactBlockProcessor to async/await (519) - cleanup of suspending the task [476] CompactBlockProcessor to async/await (519) - most comments resolved [476] CompactBlockProcessor to async/await (519) - thread safe state for both sync and async context [476] CompactBlockProcessor to async/await (519) - fixed build for a sample project [476] CompactBlockProcessor to async/await (519) - func testStartNotifiesSuscriptors() reverted [476] CompactBlockProcessor to async/await (519) - TODO added to track why we used NSLock instead of an Actor - Task priority enhanced [476] CompactBlockProcessor to async/await (519) - cleanup in Tasks and priorities
2022-09-01 05:58:41 -07:00
cancelableTask?.cancel()
}
func update(config: Configuration) async {
self.config = config
await stop()
}
[#831] Add SDKSynchronizer wrappers for non-async API This change introduces two new protocols: `ClosureSynchronizer` and `CombineSynchronizer`. These two protocols define API that doesn't use `async`. So the client can choose exactly which API it wants to use. This change also introduces two new objects: `ClosureSDKSynchronizer` and `CombineSDKSynchronizer`. These two implement the respective protocols mentioned above. Both are structures. Neither of these two keeps any state. Thanks to this each is very cheap to create. And usage of these two isn't mutually exclusive. So devs can really choose the best SDK API for each part of the client app. [#831] Use async inside of the SDKSynchronizer - In general lot of methods inside the `SDKSynchronizer` and `CompactBlockProcessoer` which weren't async are now async. And other changes are made because of this change. - `CompactBlockProcessor` no longer uses Combine to communicate with `SDKSynchronizer`. Reason for this is that Combine doesn't play great with async. Closure passed to `sink` isn't async. - Because of this and because of how our tests work (receiving signals from CBP directly) `CompactBlockProcessor` must be able to handle more event closures. Not just one. So it now has `eventClosures` dictionary. It's little bit strange but it works fine. - `SyncStatus` inside the `SDKSynchronizer` was previously protected by lock. Now it's protected by simple actor wrapper. - Changes in tests are minimal. Changes were mady only because `CompactBlockProcessor` changes from Combine to closures. [#831] Add tests for ClosureSDKSynchronizer - Added tests are testing in general if the `ClosuresSDKSynchronizer` is correctly calling `Synchronizer` and if the values are correctly returned. - `ClosuresSDKSynchronizer` doesn't contain any logic but it is public API and we should be sure that it works correctly. [#831] Add tests for CombineSDKSynchronizer [#831] Add changelog
2023-03-16 02:11:18 -07:00
func updateState(_ newState: State) async -> Void {
let oldState = state
state = newState
await transitionState(from: oldState, to: newState)
}
func updateEventClosure(identifier: String, closure: @escaping (Event) async -> Void) async {
eventClosures[identifier] = closure
}
func send(event: Event) async {
for item in eventClosures {
await item.value(event)
}
}
2021-09-17 06:49:58 -07:00
static func validateServerInfo(
_ info: LightWalletdInfo,
saplingActivation: BlockHeight,
localNetwork: ZcashNetwork,
[#888] Make actor from ZcashRustBackendWelding Closes #888. - `ZcashRustBackend` is actor now. So majority of methods in this actor are now async. - Some methods stayed `static` in `ZcashRustBackend`. It would be hard to pass instance of the `ZcashRustBackend` to the places where these methods are used in static manner. And it would change lot of APIs. But it isn't problem from technical perspective because these methods would be `nonisolated` otherwise. - Methods `lastError()` and `getLastError()` in `ZcashRustBackend` are now private. This makes sure that ther won't be aby race condition between other methods and these two error methods. - All the methods for which was `lastError()` used in code now throw error. So `lastError()` is no longer needed outside of the `ZcashRustBackend`. - There are in the public API related to `DerivationTool`. - `DerivationTool` now requires instance of the `ZcashRustBackend`. And `ZcashRustBackend` isn't public type. So `DerivationTool` doesn't have any public constructor now. It can be created only via `Initializer.makeDerivationTool()` instance method. - `deriveUnifiedSpendingKey()` and `deriveUnifiedFullViewingKey()` in `DerivationTool` are now async. It is because these are using `ZcashRustBackend` inside. `DerivationTool` offers alternative (closure and combine) APIs. But downside is that there is no sync API to dervie spending key or viewing key. - Some methods of the `DerivationTool` are now static. These methods don't use anything that requires instance of the `DerivationTool` inside. [#888] Use Sourcery to generate mocks - I wrote mock for `Synchronizer` manually. And it's tedious and long and boring work. - Now `ZcashRustBackendWelding` is changed a lot so it means `MockRustBackend` must be changed a lot. So I decided to introduce `sourcery` to generate mocks from protocols so we don't have to do it manually ever. - To generate mocks go to `ZcashLightClientKit/Tests/TestUtils/Sourcery` directory and run `generateMocks.sh` script. - Your protocol must be mentioned in `AutoMockable.swift` file. Generated mocks are in `AutoMockable.generated.swift` file. [#888] Fix Offline tests - Offline tests target now runs and tests are green. - There is log of changes in tests. But logic is not changed. - Updated `AutoMockable.stencil` so sourcery is able to generate mock as actor when protocol is marked with: `// sourcery: mockActor`. - Last few updates in `ZcashRustBackendWelding`. In previous PR `rewindCacheToHeight` methods was overlooked and it didn't throw error. - Removed `MockRustBackend` and using generated `ZCashRustBackendWeldingMock` instead. - Using generated `SynchronizerMock`. [#888] Fix NetworkTests - Changed a bit how rust backend mock is used in the tests. Introduced `RustBackendMockHelper`. There are some state variables that must be preserved within one instance of the mock. This helper does exactly this. It keeps this state variables in the memory and helping mock to work as expected. [#888] Fix Darkside tests Create ZcashKeyDeriving internal protocol Use New DerivationTool that does not require RustBackend Remove duplicated methods that had been copied over [#888] Fix potentially broken tests I broke the tests because I moved `testTempDirectory` from each `TestCase` to the `Environment`. By this I caused that each tests uses exactly same URL. Which is directly against purpose of `testTempDirectory`. So now each test calls this one and store it to local variable. So each test has unique URL. [#888] Add ability to mock nonisolated methods to AutoMockable.stencil [#888] Add changelog and fix the documentation in ZcashRustBackendWelding [#888] Rename derivation rust backend protocol and remove static methods - Renamed `ZcashKeyDeriving` to `ZcashKeyDerivationBackendWelding`. So the naming scheme is same as for `ZcashRustBackendWelding`. - `ZcashKeyDerivationBackend` is now struct instead of enum. - Methods in `ZcashKeyDerivationBackendWelding` (except one) are no longer static. Because of this the respective methods in `DerivationTool` aren't also static anymore.
2023-03-31 10:10:35 -07:00
rustBackend: ZcashRustBackendWelding
) async throws {
2021-09-17 06:49:58 -07:00
// check network types
guard let remoteNetworkType = NetworkType.forChainName(info.chainName) else {
[#361] Introduce ZcashError (#1005) This PR introduces `ZcashError` enum. This enum represents any error that can be thrown inside of the SDK and outside of the SDK. Also `ZcashError` is used in `LightWalletGRPCService` and handled in `CompactBlockProcessor` as example. Why enum? First I tried this with some structure which contained code, message and underlyingError. Problem was when some specific place in the SDK would like to attach some additional data to error. I didn't want to add some generic dictionary to store anything with the error. So I used enum to identify error. Each member can have specified amount of associated values. So specific error can bring some context data. And it's type safe. Each error has also a code. Relationship between errors and codes is 1:1. It may looks bit redundant but it's important. The client app now can choose how to process errors. Either identify those by the error itself or by code. Definition or errors and codes is in `ZcashErrorDefinition`. And then `ZcashError` and `ZcashErrorCode` are generated by Sourcery. Thanks to this it is easier to maintain the final code. And it gives us ability to generate any kind of documentation for the errors and codes. I created simple example of this in this PR. And it doesn't make the SDK completely dependent on the Sourcery. Final structures aren't super complicated and can be written manually if needed. [#923] Update error handling in DatabaseStorageManager.swift - cleanup of DatabaseStorageManager, not used anymore - ZcashError for SimpleConnectionProvider Revert "[#923] Update error handling in DatabaseStorageManager.swift" This reverts commit 94e028d31a0f6635800c297eb741db74c6a6ff45. Fix script which generates ZcashError [#922] Update error handling in DatabaseMigrationManager.swift Closes #922 [#923] Update error handling in DatabaseStorageManager.swift - The DatabaseStorageManager is not used so I deleted it - SimpleConnectionProvider's errors updated Fix tests [#955] Update error handling in SaplingParameterDownloader Closes #955 [#936] Update error handling in NotesDao Closes #936 [#935] Update error handling in BlockDao Closes #935 [#931] InternalSyncProgress.computeNextState doesn't need to throw Closes #931 [#950] Update error handling in rust backend Closes #949 Closes #950 [#941] Update error handling in AccountEntity Closes #941 [#928] Update error handling in FSCompactBlockRepository Closes #928 [#925] Update error handling in BlockDownloaderService (#974) - BlockDownloaderService errors updated [#924] Update error handling in BlockDownloader (#973) - BlockDownloaderStream nextBlock updated [#942] Update error handling in TransactionEntity (#977) - ZcashTransaction init errors converted to the ZcashError [#939] Update error handling in TransactionDao (#976) - TransactionRepositoryError removed and replaced with ZcashError - all TransactionDAO errors converted to ZcashError [#943] Update error handling in ZcashCompactBlock Closes #943 [#945] Update error handling in Memo Closes #945 [#934] Update error handling in Checkpoint Closes #944 Closes #934 [#938] Update error handling in PendingTransactionDao Closes #938 [#926] Update error handling in BlockEnhancer - WIP, switching to transaction repository to unblock this ticket [#926] Update error handling in BlockEnhancer - enhancer's errors done [#926] Update error handling in BlockEnhancer (#994) - cleanup [#952] Update error handling in DerivationTool Closes #952 [#932] Update error handling in BlockValidator Closes #932 [#940] Update error handling in UnspentTransactionOutputDao Closes #940 [#946] Update error handling in WalletTypes Closes #946 [#954] Update error handling in WalletTransactionEncoder Closes #954 [#953] Update error handling in PersistentTransactionManager Closes #953 [#956] Update error handling in Initializer Closes #956 [#947] Update error handling in Zatoshi (#996) - Zatoshi's errors converted to ZcashError [#927] Update error handling in UTXOFetcher (#997) - UTXOFetcher resolved Use let instead of var where applicable In the SDK `var` was used on places where `let` would be sufficient. And default strategy in Swift should use use `let` until mutability is required. So all these places are changed. No logic is changed. [#933] Update error handling in CompactBlockProcessor - CompactBlockProcessor's errors refactored to ZcashError [#933] Update error handling in CompactBlockProcessor #999 - comments addressed [#951] Update error handling in SDKSynchronizer - SDKSynchronizer's errors refactored to ZcashError [#951] Update error handling in SDKSynchronizer (#1002) - comments resolved Make DerivationTool constructor public DerivationTool.init should be public. This was removed by accident when adopting async. [#361] Add changelog
2023-04-24 14:15:20 -07:00
throw ZcashError.compactBlockProcessorChainName(info.chainName)
}
2021-09-17 06:49:58 -07:00
guard remoteNetworkType == localNetwork.networkType else {
[#361] Introduce ZcashError (#1005) This PR introduces `ZcashError` enum. This enum represents any error that can be thrown inside of the SDK and outside of the SDK. Also `ZcashError` is used in `LightWalletGRPCService` and handled in `CompactBlockProcessor` as example. Why enum? First I tried this with some structure which contained code, message and underlyingError. Problem was when some specific place in the SDK would like to attach some additional data to error. I didn't want to add some generic dictionary to store anything with the error. So I used enum to identify error. Each member can have specified amount of associated values. So specific error can bring some context data. And it's type safe. Each error has also a code. Relationship between errors and codes is 1:1. It may looks bit redundant but it's important. The client app now can choose how to process errors. Either identify those by the error itself or by code. Definition or errors and codes is in `ZcashErrorDefinition`. And then `ZcashError` and `ZcashErrorCode` are generated by Sourcery. Thanks to this it is easier to maintain the final code. And it gives us ability to generate any kind of documentation for the errors and codes. I created simple example of this in this PR. And it doesn't make the SDK completely dependent on the Sourcery. Final structures aren't super complicated and can be written manually if needed. [#923] Update error handling in DatabaseStorageManager.swift - cleanup of DatabaseStorageManager, not used anymore - ZcashError for SimpleConnectionProvider Revert "[#923] Update error handling in DatabaseStorageManager.swift" This reverts commit 94e028d31a0f6635800c297eb741db74c6a6ff45. Fix script which generates ZcashError [#922] Update error handling in DatabaseMigrationManager.swift Closes #922 [#923] Update error handling in DatabaseStorageManager.swift - The DatabaseStorageManager is not used so I deleted it - SimpleConnectionProvider's errors updated Fix tests [#955] Update error handling in SaplingParameterDownloader Closes #955 [#936] Update error handling in NotesDao Closes #936 [#935] Update error handling in BlockDao Closes #935 [#931] InternalSyncProgress.computeNextState doesn't need to throw Closes #931 [#950] Update error handling in rust backend Closes #949 Closes #950 [#941] Update error handling in AccountEntity Closes #941 [#928] Update error handling in FSCompactBlockRepository Closes #928 [#925] Update error handling in BlockDownloaderService (#974) - BlockDownloaderService errors updated [#924] Update error handling in BlockDownloader (#973) - BlockDownloaderStream nextBlock updated [#942] Update error handling in TransactionEntity (#977) - ZcashTransaction init errors converted to the ZcashError [#939] Update error handling in TransactionDao (#976) - TransactionRepositoryError removed and replaced with ZcashError - all TransactionDAO errors converted to ZcashError [#943] Update error handling in ZcashCompactBlock Closes #943 [#945] Update error handling in Memo Closes #945 [#934] Update error handling in Checkpoint Closes #944 Closes #934 [#938] Update error handling in PendingTransactionDao Closes #938 [#926] Update error handling in BlockEnhancer - WIP, switching to transaction repository to unblock this ticket [#926] Update error handling in BlockEnhancer - enhancer's errors done [#926] Update error handling in BlockEnhancer (#994) - cleanup [#952] Update error handling in DerivationTool Closes #952 [#932] Update error handling in BlockValidator Closes #932 [#940] Update error handling in UnspentTransactionOutputDao Closes #940 [#946] Update error handling in WalletTypes Closes #946 [#954] Update error handling in WalletTransactionEncoder Closes #954 [#953] Update error handling in PersistentTransactionManager Closes #953 [#956] Update error handling in Initializer Closes #956 [#947] Update error handling in Zatoshi (#996) - Zatoshi's errors converted to ZcashError [#927] Update error handling in UTXOFetcher (#997) - UTXOFetcher resolved Use let instead of var where applicable In the SDK `var` was used on places where `let` would be sufficient. And default strategy in Swift should use use `let` until mutability is required. So all these places are changed. No logic is changed. [#933] Update error handling in CompactBlockProcessor - CompactBlockProcessor's errors refactored to ZcashError [#933] Update error handling in CompactBlockProcessor #999 - comments addressed [#951] Update error handling in SDKSynchronizer - SDKSynchronizer's errors refactored to ZcashError [#951] Update error handling in SDKSynchronizer (#1002) - comments resolved Make DerivationTool constructor public DerivationTool.init should be public. This was removed by accident when adopting async. [#361] Add changelog
2023-04-24 14:15:20 -07:00
throw ZcashError.compactBlockProcessorNetworkMismatch(localNetwork.networkType, remoteNetworkType)
}
2021-09-17 06:49:58 -07:00
guard saplingActivation == info.saplingActivationHeight else {
[#361] Introduce ZcashError (#1005) This PR introduces `ZcashError` enum. This enum represents any error that can be thrown inside of the SDK and outside of the SDK. Also `ZcashError` is used in `LightWalletGRPCService` and handled in `CompactBlockProcessor` as example. Why enum? First I tried this with some structure which contained code, message and underlyingError. Problem was when some specific place in the SDK would like to attach some additional data to error. I didn't want to add some generic dictionary to store anything with the error. So I used enum to identify error. Each member can have specified amount of associated values. So specific error can bring some context data. And it's type safe. Each error has also a code. Relationship between errors and codes is 1:1. It may looks bit redundant but it's important. The client app now can choose how to process errors. Either identify those by the error itself or by code. Definition or errors and codes is in `ZcashErrorDefinition`. And then `ZcashError` and `ZcashErrorCode` are generated by Sourcery. Thanks to this it is easier to maintain the final code. And it gives us ability to generate any kind of documentation for the errors and codes. I created simple example of this in this PR. And it doesn't make the SDK completely dependent on the Sourcery. Final structures aren't super complicated and can be written manually if needed. [#923] Update error handling in DatabaseStorageManager.swift - cleanup of DatabaseStorageManager, not used anymore - ZcashError for SimpleConnectionProvider Revert "[#923] Update error handling in DatabaseStorageManager.swift" This reverts commit 94e028d31a0f6635800c297eb741db74c6a6ff45. Fix script which generates ZcashError [#922] Update error handling in DatabaseMigrationManager.swift Closes #922 [#923] Update error handling in DatabaseStorageManager.swift - The DatabaseStorageManager is not used so I deleted it - SimpleConnectionProvider's errors updated Fix tests [#955] Update error handling in SaplingParameterDownloader Closes #955 [#936] Update error handling in NotesDao Closes #936 [#935] Update error handling in BlockDao Closes #935 [#931] InternalSyncProgress.computeNextState doesn't need to throw Closes #931 [#950] Update error handling in rust backend Closes #949 Closes #950 [#941] Update error handling in AccountEntity Closes #941 [#928] Update error handling in FSCompactBlockRepository Closes #928 [#925] Update error handling in BlockDownloaderService (#974) - BlockDownloaderService errors updated [#924] Update error handling in BlockDownloader (#973) - BlockDownloaderStream nextBlock updated [#942] Update error handling in TransactionEntity (#977) - ZcashTransaction init errors converted to the ZcashError [#939] Update error handling in TransactionDao (#976) - TransactionRepositoryError removed and replaced with ZcashError - all TransactionDAO errors converted to ZcashError [#943] Update error handling in ZcashCompactBlock Closes #943 [#945] Update error handling in Memo Closes #945 [#934] Update error handling in Checkpoint Closes #944 Closes #934 [#938] Update error handling in PendingTransactionDao Closes #938 [#926] Update error handling in BlockEnhancer - WIP, switching to transaction repository to unblock this ticket [#926] Update error handling in BlockEnhancer - enhancer's errors done [#926] Update error handling in BlockEnhancer (#994) - cleanup [#952] Update error handling in DerivationTool Closes #952 [#932] Update error handling in BlockValidator Closes #932 [#940] Update error handling in UnspentTransactionOutputDao Closes #940 [#946] Update error handling in WalletTypes Closes #946 [#954] Update error handling in WalletTransactionEncoder Closes #954 [#953] Update error handling in PersistentTransactionManager Closes #953 [#956] Update error handling in Initializer Closes #956 [#947] Update error handling in Zatoshi (#996) - Zatoshi's errors converted to ZcashError [#927] Update error handling in UTXOFetcher (#997) - UTXOFetcher resolved Use let instead of var where applicable In the SDK `var` was used on places where `let` would be sufficient. And default strategy in Swift should use use `let` until mutability is required. So all these places are changed. No logic is changed. [#933] Update error handling in CompactBlockProcessor - CompactBlockProcessor's errors refactored to ZcashError [#933] Update error handling in CompactBlockProcessor #999 - comments addressed [#951] Update error handling in SDKSynchronizer - SDKSynchronizer's errors refactored to ZcashError [#951] Update error handling in SDKSynchronizer (#1002) - comments resolved Make DerivationTool constructor public DerivationTool.init should be public. This was removed by accident when adopting async. [#361] Add changelog
2023-04-24 14:15:20 -07:00
throw ZcashError.compactBlockProcessorSaplingActivationMismatch(saplingActivation, BlockHeight(info.saplingActivationHeight))
2021-09-17 06:49:58 -07:00
}
// check branch id
[#888] Make actor from ZcashRustBackendWelding Closes #888. - `ZcashRustBackend` is actor now. So majority of methods in this actor are now async. - Some methods stayed `static` in `ZcashRustBackend`. It would be hard to pass instance of the `ZcashRustBackend` to the places where these methods are used in static manner. And it would change lot of APIs. But it isn't problem from technical perspective because these methods would be `nonisolated` otherwise. - Methods `lastError()` and `getLastError()` in `ZcashRustBackend` are now private. This makes sure that ther won't be aby race condition between other methods and these two error methods. - All the methods for which was `lastError()` used in code now throw error. So `lastError()` is no longer needed outside of the `ZcashRustBackend`. - There are in the public API related to `DerivationTool`. - `DerivationTool` now requires instance of the `ZcashRustBackend`. And `ZcashRustBackend` isn't public type. So `DerivationTool` doesn't have any public constructor now. It can be created only via `Initializer.makeDerivationTool()` instance method. - `deriveUnifiedSpendingKey()` and `deriveUnifiedFullViewingKey()` in `DerivationTool` are now async. It is because these are using `ZcashRustBackend` inside. `DerivationTool` offers alternative (closure and combine) APIs. But downside is that there is no sync API to dervie spending key or viewing key. - Some methods of the `DerivationTool` are now static. These methods don't use anything that requires instance of the `DerivationTool` inside. [#888] Use Sourcery to generate mocks - I wrote mock for `Synchronizer` manually. And it's tedious and long and boring work. - Now `ZcashRustBackendWelding` is changed a lot so it means `MockRustBackend` must be changed a lot. So I decided to introduce `sourcery` to generate mocks from protocols so we don't have to do it manually ever. - To generate mocks go to `ZcashLightClientKit/Tests/TestUtils/Sourcery` directory and run `generateMocks.sh` script. - Your protocol must be mentioned in `AutoMockable.swift` file. Generated mocks are in `AutoMockable.generated.swift` file. [#888] Fix Offline tests - Offline tests target now runs and tests are green. - There is log of changes in tests. But logic is not changed. - Updated `AutoMockable.stencil` so sourcery is able to generate mock as actor when protocol is marked with: `// sourcery: mockActor`. - Last few updates in `ZcashRustBackendWelding`. In previous PR `rewindCacheToHeight` methods was overlooked and it didn't throw error. - Removed `MockRustBackend` and using generated `ZCashRustBackendWeldingMock` instead. - Using generated `SynchronizerMock`. [#888] Fix NetworkTests - Changed a bit how rust backend mock is used in the tests. Introduced `RustBackendMockHelper`. There are some state variables that must be preserved within one instance of the mock. This helper does exactly this. It keeps this state variables in the memory and helping mock to work as expected. [#888] Fix Darkside tests Create ZcashKeyDeriving internal protocol Use New DerivationTool that does not require RustBackend Remove duplicated methods that had been copied over [#888] Fix potentially broken tests I broke the tests because I moved `testTempDirectory` from each `TestCase` to the `Environment`. By this I caused that each tests uses exactly same URL. Which is directly against purpose of `testTempDirectory`. So now each test calls this one and store it to local variable. So each test has unique URL. [#888] Add ability to mock nonisolated methods to AutoMockable.stencil [#888] Add changelog and fix the documentation in ZcashRustBackendWelding [#888] Rename derivation rust backend protocol and remove static methods - Renamed `ZcashKeyDeriving` to `ZcashKeyDerivationBackendWelding`. So the naming scheme is same as for `ZcashRustBackendWelding`. - `ZcashKeyDerivationBackend` is now struct instead of enum. - Methods in `ZcashKeyDerivationBackendWelding` (except one) are no longer static. Because of this the respective methods in `DerivationTool` aren't also static anymore.
2023-03-31 10:10:35 -07:00
let localBranch = try rustBackend.consensusBranchIdFor(height: Int32(info.blockHeight))
2021-09-17 06:49:58 -07:00
guard let remoteBranchID = ConsensusBranchID.fromString(info.consensusBranchID) else {
[#361] Introduce ZcashError (#1005) This PR introduces `ZcashError` enum. This enum represents any error that can be thrown inside of the SDK and outside of the SDK. Also `ZcashError` is used in `LightWalletGRPCService` and handled in `CompactBlockProcessor` as example. Why enum? First I tried this with some structure which contained code, message and underlyingError. Problem was when some specific place in the SDK would like to attach some additional data to error. I didn't want to add some generic dictionary to store anything with the error. So I used enum to identify error. Each member can have specified amount of associated values. So specific error can bring some context data. And it's type safe. Each error has also a code. Relationship between errors and codes is 1:1. It may looks bit redundant but it's important. The client app now can choose how to process errors. Either identify those by the error itself or by code. Definition or errors and codes is in `ZcashErrorDefinition`. And then `ZcashError` and `ZcashErrorCode` are generated by Sourcery. Thanks to this it is easier to maintain the final code. And it gives us ability to generate any kind of documentation for the errors and codes. I created simple example of this in this PR. And it doesn't make the SDK completely dependent on the Sourcery. Final structures aren't super complicated and can be written manually if needed. [#923] Update error handling in DatabaseStorageManager.swift - cleanup of DatabaseStorageManager, not used anymore - ZcashError for SimpleConnectionProvider Revert "[#923] Update error handling in DatabaseStorageManager.swift" This reverts commit 94e028d31a0f6635800c297eb741db74c6a6ff45. Fix script which generates ZcashError [#922] Update error handling in DatabaseMigrationManager.swift Closes #922 [#923] Update error handling in DatabaseStorageManager.swift - The DatabaseStorageManager is not used so I deleted it - SimpleConnectionProvider's errors updated Fix tests [#955] Update error handling in SaplingParameterDownloader Closes #955 [#936] Update error handling in NotesDao Closes #936 [#935] Update error handling in BlockDao Closes #935 [#931] InternalSyncProgress.computeNextState doesn't need to throw Closes #931 [#950] Update error handling in rust backend Closes #949 Closes #950 [#941] Update error handling in AccountEntity Closes #941 [#928] Update error handling in FSCompactBlockRepository Closes #928 [#925] Update error handling in BlockDownloaderService (#974) - BlockDownloaderService errors updated [#924] Update error handling in BlockDownloader (#973) - BlockDownloaderStream nextBlock updated [#942] Update error handling in TransactionEntity (#977) - ZcashTransaction init errors converted to the ZcashError [#939] Update error handling in TransactionDao (#976) - TransactionRepositoryError removed and replaced with ZcashError - all TransactionDAO errors converted to ZcashError [#943] Update error handling in ZcashCompactBlock Closes #943 [#945] Update error handling in Memo Closes #945 [#934] Update error handling in Checkpoint Closes #944 Closes #934 [#938] Update error handling in PendingTransactionDao Closes #938 [#926] Update error handling in BlockEnhancer - WIP, switching to transaction repository to unblock this ticket [#926] Update error handling in BlockEnhancer - enhancer's errors done [#926] Update error handling in BlockEnhancer (#994) - cleanup [#952] Update error handling in DerivationTool Closes #952 [#932] Update error handling in BlockValidator Closes #932 [#940] Update error handling in UnspentTransactionOutputDao Closes #940 [#946] Update error handling in WalletTypes Closes #946 [#954] Update error handling in WalletTransactionEncoder Closes #954 [#953] Update error handling in PersistentTransactionManager Closes #953 [#956] Update error handling in Initializer Closes #956 [#947] Update error handling in Zatoshi (#996) - Zatoshi's errors converted to ZcashError [#927] Update error handling in UTXOFetcher (#997) - UTXOFetcher resolved Use let instead of var where applicable In the SDK `var` was used on places where `let` would be sufficient. And default strategy in Swift should use use `let` until mutability is required. So all these places are changed. No logic is changed. [#933] Update error handling in CompactBlockProcessor - CompactBlockProcessor's errors refactored to ZcashError [#933] Update error handling in CompactBlockProcessor #999 - comments addressed [#951] Update error handling in SDKSynchronizer - SDKSynchronizer's errors refactored to ZcashError [#951] Update error handling in SDKSynchronizer (#1002) - comments resolved Make DerivationTool constructor public DerivationTool.init should be public. This was removed by accident when adopting async. [#361] Add changelog
2023-04-24 14:15:20 -07:00
throw ZcashError.compactBlockProcessorConsensusBranchID
2021-09-17 06:49:58 -07:00
}
guard remoteBranchID == localBranch else {
[#361] Introduce ZcashError (#1005) This PR introduces `ZcashError` enum. This enum represents any error that can be thrown inside of the SDK and outside of the SDK. Also `ZcashError` is used in `LightWalletGRPCService` and handled in `CompactBlockProcessor` as example. Why enum? First I tried this with some structure which contained code, message and underlyingError. Problem was when some specific place in the SDK would like to attach some additional data to error. I didn't want to add some generic dictionary to store anything with the error. So I used enum to identify error. Each member can have specified amount of associated values. So specific error can bring some context data. And it's type safe. Each error has also a code. Relationship between errors and codes is 1:1. It may looks bit redundant but it's important. The client app now can choose how to process errors. Either identify those by the error itself or by code. Definition or errors and codes is in `ZcashErrorDefinition`. And then `ZcashError` and `ZcashErrorCode` are generated by Sourcery. Thanks to this it is easier to maintain the final code. And it gives us ability to generate any kind of documentation for the errors and codes. I created simple example of this in this PR. And it doesn't make the SDK completely dependent on the Sourcery. Final structures aren't super complicated and can be written manually if needed. [#923] Update error handling in DatabaseStorageManager.swift - cleanup of DatabaseStorageManager, not used anymore - ZcashError for SimpleConnectionProvider Revert "[#923] Update error handling in DatabaseStorageManager.swift" This reverts commit 94e028d31a0f6635800c297eb741db74c6a6ff45. Fix script which generates ZcashError [#922] Update error handling in DatabaseMigrationManager.swift Closes #922 [#923] Update error handling in DatabaseStorageManager.swift - The DatabaseStorageManager is not used so I deleted it - SimpleConnectionProvider's errors updated Fix tests [#955] Update error handling in SaplingParameterDownloader Closes #955 [#936] Update error handling in NotesDao Closes #936 [#935] Update error handling in BlockDao Closes #935 [#931] InternalSyncProgress.computeNextState doesn't need to throw Closes #931 [#950] Update error handling in rust backend Closes #949 Closes #950 [#941] Update error handling in AccountEntity Closes #941 [#928] Update error handling in FSCompactBlockRepository Closes #928 [#925] Update error handling in BlockDownloaderService (#974) - BlockDownloaderService errors updated [#924] Update error handling in BlockDownloader (#973) - BlockDownloaderStream nextBlock updated [#942] Update error handling in TransactionEntity (#977) - ZcashTransaction init errors converted to the ZcashError [#939] Update error handling in TransactionDao (#976) - TransactionRepositoryError removed and replaced with ZcashError - all TransactionDAO errors converted to ZcashError [#943] Update error handling in ZcashCompactBlock Closes #943 [#945] Update error handling in Memo Closes #945 [#934] Update error handling in Checkpoint Closes #944 Closes #934 [#938] Update error handling in PendingTransactionDao Closes #938 [#926] Update error handling in BlockEnhancer - WIP, switching to transaction repository to unblock this ticket [#926] Update error handling in BlockEnhancer - enhancer's errors done [#926] Update error handling in BlockEnhancer (#994) - cleanup [#952] Update error handling in DerivationTool Closes #952 [#932] Update error handling in BlockValidator Closes #932 [#940] Update error handling in UnspentTransactionOutputDao Closes #940 [#946] Update error handling in WalletTypes Closes #946 [#954] Update error handling in WalletTransactionEncoder Closes #954 [#953] Update error handling in PersistentTransactionManager Closes #953 [#956] Update error handling in Initializer Closes #956 [#947] Update error handling in Zatoshi (#996) - Zatoshi's errors converted to ZcashError [#927] Update error handling in UTXOFetcher (#997) - UTXOFetcher resolved Use let instead of var where applicable In the SDK `var` was used on places where `let` would be sufficient. And default strategy in Swift should use use `let` until mutability is required. So all these places are changed. No logic is changed. [#933] Update error handling in CompactBlockProcessor - CompactBlockProcessor's errors refactored to ZcashError [#933] Update error handling in CompactBlockProcessor #999 - comments addressed [#951] Update error handling in SDKSynchronizer - SDKSynchronizer's errors refactored to ZcashError [#951] Update error handling in SDKSynchronizer (#1002) - comments resolved Make DerivationTool constructor public DerivationTool.init should be public. This was removed by accident when adopting async. [#361] Add changelog
2023-04-24 14:15:20 -07:00
throw ZcashError.compactBlockProcessorWrongConsensusBranchId(localBranch, remoteBranchID)
}
}
2021-09-17 06:49:58 -07:00
/// Starts the CompactBlockProcessor instance and starts downloading and processing blocks
///
/// triggers the blockProcessorStartedDownloading notification
///
/// - Important: subscribe to the notifications before calling this method
func start(retry: Bool = false) async {
if retry {
self.retryAttempts = 0
self.processingError = nil
self.backoffTimer?.invalidate()
self.backoffTimer = nil
}
2021-09-17 06:49:58 -07:00
guard shouldStart else {
switch self.state {
case .error(let error):
// max attempts have been reached
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
logger.info("max retry attempts reached with error: \(error)")
[#361] Introduce ZcashError (#1005) This PR introduces `ZcashError` enum. This enum represents any error that can be thrown inside of the SDK and outside of the SDK. Also `ZcashError` is used in `LightWalletGRPCService` and handled in `CompactBlockProcessor` as example. Why enum? First I tried this with some structure which contained code, message and underlyingError. Problem was when some specific place in the SDK would like to attach some additional data to error. I didn't want to add some generic dictionary to store anything with the error. So I used enum to identify error. Each member can have specified amount of associated values. So specific error can bring some context data. And it's type safe. Each error has also a code. Relationship between errors and codes is 1:1. It may looks bit redundant but it's important. The client app now can choose how to process errors. Either identify those by the error itself or by code. Definition or errors and codes is in `ZcashErrorDefinition`. And then `ZcashError` and `ZcashErrorCode` are generated by Sourcery. Thanks to this it is easier to maintain the final code. And it gives us ability to generate any kind of documentation for the errors and codes. I created simple example of this in this PR. And it doesn't make the SDK completely dependent on the Sourcery. Final structures aren't super complicated and can be written manually if needed. [#923] Update error handling in DatabaseStorageManager.swift - cleanup of DatabaseStorageManager, not used anymore - ZcashError for SimpleConnectionProvider Revert "[#923] Update error handling in DatabaseStorageManager.swift" This reverts commit 94e028d31a0f6635800c297eb741db74c6a6ff45. Fix script which generates ZcashError [#922] Update error handling in DatabaseMigrationManager.swift Closes #922 [#923] Update error handling in DatabaseStorageManager.swift - The DatabaseStorageManager is not used so I deleted it - SimpleConnectionProvider's errors updated Fix tests [#955] Update error handling in SaplingParameterDownloader Closes #955 [#936] Update error handling in NotesDao Closes #936 [#935] Update error handling in BlockDao Closes #935 [#931] InternalSyncProgress.computeNextState doesn't need to throw Closes #931 [#950] Update error handling in rust backend Closes #949 Closes #950 [#941] Update error handling in AccountEntity Closes #941 [#928] Update error handling in FSCompactBlockRepository Closes #928 [#925] Update error handling in BlockDownloaderService (#974) - BlockDownloaderService errors updated [#924] Update error handling in BlockDownloader (#973) - BlockDownloaderStream nextBlock updated [#942] Update error handling in TransactionEntity (#977) - ZcashTransaction init errors converted to the ZcashError [#939] Update error handling in TransactionDao (#976) - TransactionRepositoryError removed and replaced with ZcashError - all TransactionDAO errors converted to ZcashError [#943] Update error handling in ZcashCompactBlock Closes #943 [#945] Update error handling in Memo Closes #945 [#934] Update error handling in Checkpoint Closes #944 Closes #934 [#938] Update error handling in PendingTransactionDao Closes #938 [#926] Update error handling in BlockEnhancer - WIP, switching to transaction repository to unblock this ticket [#926] Update error handling in BlockEnhancer - enhancer's errors done [#926] Update error handling in BlockEnhancer (#994) - cleanup [#952] Update error handling in DerivationTool Closes #952 [#932] Update error handling in BlockValidator Closes #932 [#940] Update error handling in UnspentTransactionOutputDao Closes #940 [#946] Update error handling in WalletTypes Closes #946 [#954] Update error handling in WalletTransactionEncoder Closes #954 [#953] Update error handling in PersistentTransactionManager Closes #953 [#956] Update error handling in Initializer Closes #956 [#947] Update error handling in Zatoshi (#996) - Zatoshi's errors converted to ZcashError [#927] Update error handling in UTXOFetcher (#997) - UTXOFetcher resolved Use let instead of var where applicable In the SDK `var` was used on places where `let` would be sufficient. And default strategy in Swift should use use `let` until mutability is required. So all these places are changed. No logic is changed. [#933] Update error handling in CompactBlockProcessor - CompactBlockProcessor's errors refactored to ZcashError [#933] Update error handling in CompactBlockProcessor #999 - comments addressed [#951] Update error handling in SDKSynchronizer - SDKSynchronizer's errors refactored to ZcashError [#951] Update error handling in SDKSynchronizer (#1002) - comments resolved Make DerivationTool constructor public DerivationTool.init should be public. This was removed by accident when adopting async. [#361] Add changelog
2023-04-24 14:15:20 -07:00
await notifyError(ZcashError.compactBlockProcessorMaxAttemptsReached(self.maxAttempts))
[#831] Add SDKSynchronizer wrappers for non-async API This change introduces two new protocols: `ClosureSynchronizer` and `CombineSynchronizer`. These two protocols define API that doesn't use `async`. So the client can choose exactly which API it wants to use. This change also introduces two new objects: `ClosureSDKSynchronizer` and `CombineSDKSynchronizer`. These two implement the respective protocols mentioned above. Both are structures. Neither of these two keeps any state. Thanks to this each is very cheap to create. And usage of these two isn't mutually exclusive. So devs can really choose the best SDK API for each part of the client app. [#831] Use async inside of the SDKSynchronizer - In general lot of methods inside the `SDKSynchronizer` and `CompactBlockProcessoer` which weren't async are now async. And other changes are made because of this change. - `CompactBlockProcessor` no longer uses Combine to communicate with `SDKSynchronizer`. Reason for this is that Combine doesn't play great with async. Closure passed to `sink` isn't async. - Because of this and because of how our tests work (receiving signals from CBP directly) `CompactBlockProcessor` must be able to handle more event closures. Not just one. So it now has `eventClosures` dictionary. It's little bit strange but it works fine. - `SyncStatus` inside the `SDKSynchronizer` was previously protected by lock. Now it's protected by simple actor wrapper. - Changes in tests are minimal. Changes were mady only because `CompactBlockProcessor` changes from Combine to closures. [#831] Add tests for ClosureSDKSynchronizer - Added tests are testing in general if the `ClosuresSDKSynchronizer` is correctly calling `Synchronizer` and if the values are correctly returned. - `ClosuresSDKSynchronizer` doesn't contain any logic but it is public API and we should be sure that it works correctly. [#831] Add tests for CombineSDKSynchronizer [#831] Add changelog
2023-03-16 02:11:18 -07:00
await updateState(.stopped)
case .stopped:
// max attempts have been reached
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
logger.info("max retry attempts reached")
[#361] Introduce ZcashError (#1005) This PR introduces `ZcashError` enum. This enum represents any error that can be thrown inside of the SDK and outside of the SDK. Also `ZcashError` is used in `LightWalletGRPCService` and handled in `CompactBlockProcessor` as example. Why enum? First I tried this with some structure which contained code, message and underlyingError. Problem was when some specific place in the SDK would like to attach some additional data to error. I didn't want to add some generic dictionary to store anything with the error. So I used enum to identify error. Each member can have specified amount of associated values. So specific error can bring some context data. And it's type safe. Each error has also a code. Relationship between errors and codes is 1:1. It may looks bit redundant but it's important. The client app now can choose how to process errors. Either identify those by the error itself or by code. Definition or errors and codes is in `ZcashErrorDefinition`. And then `ZcashError` and `ZcashErrorCode` are generated by Sourcery. Thanks to this it is easier to maintain the final code. And it gives us ability to generate any kind of documentation for the errors and codes. I created simple example of this in this PR. And it doesn't make the SDK completely dependent on the Sourcery. Final structures aren't super complicated and can be written manually if needed. [#923] Update error handling in DatabaseStorageManager.swift - cleanup of DatabaseStorageManager, not used anymore - ZcashError for SimpleConnectionProvider Revert "[#923] Update error handling in DatabaseStorageManager.swift" This reverts commit 94e028d31a0f6635800c297eb741db74c6a6ff45. Fix script which generates ZcashError [#922] Update error handling in DatabaseMigrationManager.swift Closes #922 [#923] Update error handling in DatabaseStorageManager.swift - The DatabaseStorageManager is not used so I deleted it - SimpleConnectionProvider's errors updated Fix tests [#955] Update error handling in SaplingParameterDownloader Closes #955 [#936] Update error handling in NotesDao Closes #936 [#935] Update error handling in BlockDao Closes #935 [#931] InternalSyncProgress.computeNextState doesn't need to throw Closes #931 [#950] Update error handling in rust backend Closes #949 Closes #950 [#941] Update error handling in AccountEntity Closes #941 [#928] Update error handling in FSCompactBlockRepository Closes #928 [#925] Update error handling in BlockDownloaderService (#974) - BlockDownloaderService errors updated [#924] Update error handling in BlockDownloader (#973) - BlockDownloaderStream nextBlock updated [#942] Update error handling in TransactionEntity (#977) - ZcashTransaction init errors converted to the ZcashError [#939] Update error handling in TransactionDao (#976) - TransactionRepositoryError removed and replaced with ZcashError - all TransactionDAO errors converted to ZcashError [#943] Update error handling in ZcashCompactBlock Closes #943 [#945] Update error handling in Memo Closes #945 [#934] Update error handling in Checkpoint Closes #944 Closes #934 [#938] Update error handling in PendingTransactionDao Closes #938 [#926] Update error handling in BlockEnhancer - WIP, switching to transaction repository to unblock this ticket [#926] Update error handling in BlockEnhancer - enhancer's errors done [#926] Update error handling in BlockEnhancer (#994) - cleanup [#952] Update error handling in DerivationTool Closes #952 [#932] Update error handling in BlockValidator Closes #932 [#940] Update error handling in UnspentTransactionOutputDao Closes #940 [#946] Update error handling in WalletTypes Closes #946 [#954] Update error handling in WalletTransactionEncoder Closes #954 [#953] Update error handling in PersistentTransactionManager Closes #953 [#956] Update error handling in Initializer Closes #956 [#947] Update error handling in Zatoshi (#996) - Zatoshi's errors converted to ZcashError [#927] Update error handling in UTXOFetcher (#997) - UTXOFetcher resolved Use let instead of var where applicable In the SDK `var` was used on places where `let` would be sufficient. And default strategy in Swift should use use `let` until mutability is required. So all these places are changed. No logic is changed. [#933] Update error handling in CompactBlockProcessor - CompactBlockProcessor's errors refactored to ZcashError [#933] Update error handling in CompactBlockProcessor #999 - comments addressed [#951] Update error handling in SDKSynchronizer - SDKSynchronizer's errors refactored to ZcashError [#951] Update error handling in SDKSynchronizer (#1002) - comments resolved Make DerivationTool constructor public DerivationTool.init should be public. This was removed by accident when adopting async. [#361] Add changelog
2023-04-24 14:15:20 -07:00
await notifyError(ZcashError.compactBlockProcessorMaxAttemptsReached(self.maxAttempts))
case .synced:
// max attempts have been reached
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
logger.warn("max retry attempts reached on synced state, this indicates malfunction")
[#361] Introduce ZcashError (#1005) This PR introduces `ZcashError` enum. This enum represents any error that can be thrown inside of the SDK and outside of the SDK. Also `ZcashError` is used in `LightWalletGRPCService` and handled in `CompactBlockProcessor` as example. Why enum? First I tried this with some structure which contained code, message and underlyingError. Problem was when some specific place in the SDK would like to attach some additional data to error. I didn't want to add some generic dictionary to store anything with the error. So I used enum to identify error. Each member can have specified amount of associated values. So specific error can bring some context data. And it's type safe. Each error has also a code. Relationship between errors and codes is 1:1. It may looks bit redundant but it's important. The client app now can choose how to process errors. Either identify those by the error itself or by code. Definition or errors and codes is in `ZcashErrorDefinition`. And then `ZcashError` and `ZcashErrorCode` are generated by Sourcery. Thanks to this it is easier to maintain the final code. And it gives us ability to generate any kind of documentation for the errors and codes. I created simple example of this in this PR. And it doesn't make the SDK completely dependent on the Sourcery. Final structures aren't super complicated and can be written manually if needed. [#923] Update error handling in DatabaseStorageManager.swift - cleanup of DatabaseStorageManager, not used anymore - ZcashError for SimpleConnectionProvider Revert "[#923] Update error handling in DatabaseStorageManager.swift" This reverts commit 94e028d31a0f6635800c297eb741db74c6a6ff45. Fix script which generates ZcashError [#922] Update error handling in DatabaseMigrationManager.swift Closes #922 [#923] Update error handling in DatabaseStorageManager.swift - The DatabaseStorageManager is not used so I deleted it - SimpleConnectionProvider's errors updated Fix tests [#955] Update error handling in SaplingParameterDownloader Closes #955 [#936] Update error handling in NotesDao Closes #936 [#935] Update error handling in BlockDao Closes #935 [#931] InternalSyncProgress.computeNextState doesn't need to throw Closes #931 [#950] Update error handling in rust backend Closes #949 Closes #950 [#941] Update error handling in AccountEntity Closes #941 [#928] Update error handling in FSCompactBlockRepository Closes #928 [#925] Update error handling in BlockDownloaderService (#974) - BlockDownloaderService errors updated [#924] Update error handling in BlockDownloader (#973) - BlockDownloaderStream nextBlock updated [#942] Update error handling in TransactionEntity (#977) - ZcashTransaction init errors converted to the ZcashError [#939] Update error handling in TransactionDao (#976) - TransactionRepositoryError removed and replaced with ZcashError - all TransactionDAO errors converted to ZcashError [#943] Update error handling in ZcashCompactBlock Closes #943 [#945] Update error handling in Memo Closes #945 [#934] Update error handling in Checkpoint Closes #944 Closes #934 [#938] Update error handling in PendingTransactionDao Closes #938 [#926] Update error handling in BlockEnhancer - WIP, switching to transaction repository to unblock this ticket [#926] Update error handling in BlockEnhancer - enhancer's errors done [#926] Update error handling in BlockEnhancer (#994) - cleanup [#952] Update error handling in DerivationTool Closes #952 [#932] Update error handling in BlockValidator Closes #932 [#940] Update error handling in UnspentTransactionOutputDao Closes #940 [#946] Update error handling in WalletTypes Closes #946 [#954] Update error handling in WalletTransactionEncoder Closes #954 [#953] Update error handling in PersistentTransactionManager Closes #953 [#956] Update error handling in Initializer Closes #956 [#947] Update error handling in Zatoshi (#996) - Zatoshi's errors converted to ZcashError [#927] Update error handling in UTXOFetcher (#997) - UTXOFetcher resolved Use let instead of var where applicable In the SDK `var` was used on places where `let` would be sufficient. And default strategy in Swift should use use `let` until mutability is required. So all these places are changed. No logic is changed. [#933] Update error handling in CompactBlockProcessor - CompactBlockProcessor's errors refactored to ZcashError [#933] Update error handling in CompactBlockProcessor #999 - comments addressed [#951] Update error handling in SDKSynchronizer - SDKSynchronizer's errors refactored to ZcashError [#951] Update error handling in SDKSynchronizer (#1002) - comments resolved Make DerivationTool constructor public DerivationTool.init should be public. This was removed by accident when adopting async. [#361] Add changelog
2023-04-24 14:15:20 -07:00
await notifyError(ZcashError.compactBlockProcessorMaxAttemptsReached(self.maxAttempts))
case .syncing, .enhancing, .fetching, .handlingSaplingFiles:
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
logger.debug("Warning: compact block processor was started while busy!!!!")
afterSyncHooksManager.insert(hook: .anotherSync)
}
return
}
2021-09-17 06:49:58 -07:00
- [#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
do {
if let legacyCacheDbURL = self.config.cacheDbURL {
try await self.migrateCacheDb(legacyCacheDbURL)
}
} catch {
await self.fail(error)
}
await self.nextBatch()
}
2021-09-17 06:49:58 -07:00
/**
2021-09-17 06:49:58 -07:00
Stops the CompactBlockProcessor
Note: retry count is reset
*/
func stop() async {
self.backoffTimer?.invalidate()
self.backoffTimer = nil
2021-09-17 06:49:58 -07:00
[476] CompactBlockProcessor to async/await - getting rid of the Operation Queue - the cleanup is needed - the update of tests is needed - tested and it successfully finishes the sync process [476] CompactBlockProcessor to async/await - old processNewBlocks() removed [476] CompactBlockProcessor to async/await - unused operations removed [476] CompactBlockProcessor to async/await - unit tests update [476] CompactBlockProcessor to async/await - unit tests refactored [476] CompactBlockProcessor to async/await - cleanup of deprecated method [476] CompactBlockProcessor to async/await - fail(error) was called even for canceled tasks but that must be excluded [476] CompactBlockProcessor to async/await - removal of all ZcashOperations from the code (unit test will follow) [476] CompactBlockProcessor to async/await - network tests in building and success order again [476] CompactBlockProcessor to async/await - offline tests in building and success order [476] CompactBlockProcessor to async/await (519) - cleanup of suspending the task [476] CompactBlockProcessor to async/await (519) - most comments resolved [476] CompactBlockProcessor to async/await (519) - thread safe state for both sync and async context [476] CompactBlockProcessor to async/await (519) - fixed build for a sample project [476] CompactBlockProcessor to async/await (519) - func testStartNotifiesSuscriptors() reverted [476] CompactBlockProcessor to async/await (519) - TODO added to track why we used NSLock instead of an Actor - Task priority enhanced [476] CompactBlockProcessor to async/await (519) - cleanup in Tasks and priorities
2022-09-01 05:58:41 -07:00
cancelableTask?.cancel()
await blockDownloader.stopDownload()
2021-09-17 06:49:58 -07:00
self.retryAttempts = 0
}
2021-09-17 06:49:58 -07:00
// MARK: Rewind
- [#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
/// Rewinds to provided height.
/// - Parameter height: height to rewind to. If nil is provided, it will rescan to nearest height (quick rescan)
///
/// - Note: If this is called while sync is in progress then the sync process is stopped first and then rewind is executed.
func rewind(context: AfterSyncHooksManager.RewindContext) async {
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
logger.debug("Starting rewind")
switch self.state {
case .syncing, .enhancing, .fetching, .handlingSaplingFiles:
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
logger.debug("Stopping sync because of rewind")
afterSyncHooksManager.insert(hook: .rewind(context))
await stop()
2021-09-17 06:49:58 -07:00
case .stopped, .error, .synced:
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
logger.debug("Sync doesn't run. Executing rewind.")
await doRewind(context: context)
}
}
private func doRewind(context: AfterSyncHooksManager.RewindContext) async {
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
logger.debug("Executing rewind.")
let lastDownloaded = await internalSyncProgress.latestDownloadedBlockHeight
let height = Int32(context.height ?? lastDownloaded)
2021-09-17 06:49:58 -07:00
[#888] Make actor from ZcashRustBackendWelding Closes #888. - `ZcashRustBackend` is actor now. So majority of methods in this actor are now async. - Some methods stayed `static` in `ZcashRustBackend`. It would be hard to pass instance of the `ZcashRustBackend` to the places where these methods are used in static manner. And it would change lot of APIs. But it isn't problem from technical perspective because these methods would be `nonisolated` otherwise. - Methods `lastError()` and `getLastError()` in `ZcashRustBackend` are now private. This makes sure that ther won't be aby race condition between other methods and these two error methods. - All the methods for which was `lastError()` used in code now throw error. So `lastError()` is no longer needed outside of the `ZcashRustBackend`. - There are in the public API related to `DerivationTool`. - `DerivationTool` now requires instance of the `ZcashRustBackend`. And `ZcashRustBackend` isn't public type. So `DerivationTool` doesn't have any public constructor now. It can be created only via `Initializer.makeDerivationTool()` instance method. - `deriveUnifiedSpendingKey()` and `deriveUnifiedFullViewingKey()` in `DerivationTool` are now async. It is because these are using `ZcashRustBackend` inside. `DerivationTool` offers alternative (closure and combine) APIs. But downside is that there is no sync API to dervie spending key or viewing key. - Some methods of the `DerivationTool` are now static. These methods don't use anything that requires instance of the `DerivationTool` inside. [#888] Use Sourcery to generate mocks - I wrote mock for `Synchronizer` manually. And it's tedious and long and boring work. - Now `ZcashRustBackendWelding` is changed a lot so it means `MockRustBackend` must be changed a lot. So I decided to introduce `sourcery` to generate mocks from protocols so we don't have to do it manually ever. - To generate mocks go to `ZcashLightClientKit/Tests/TestUtils/Sourcery` directory and run `generateMocks.sh` script. - Your protocol must be mentioned in `AutoMockable.swift` file. Generated mocks are in `AutoMockable.generated.swift` file. [#888] Fix Offline tests - Offline tests target now runs and tests are green. - There is log of changes in tests. But logic is not changed. - Updated `AutoMockable.stencil` so sourcery is able to generate mock as actor when protocol is marked with: `// sourcery: mockActor`. - Last few updates in `ZcashRustBackendWelding`. In previous PR `rewindCacheToHeight` methods was overlooked and it didn't throw error. - Removed `MockRustBackend` and using generated `ZCashRustBackendWeldingMock` instead. - Using generated `SynchronizerMock`. [#888] Fix NetworkTests - Changed a bit how rust backend mock is used in the tests. Introduced `RustBackendMockHelper`. There are some state variables that must be preserved within one instance of the mock. This helper does exactly this. It keeps this state variables in the memory and helping mock to work as expected. [#888] Fix Darkside tests Create ZcashKeyDeriving internal protocol Use New DerivationTool that does not require RustBackend Remove duplicated methods that had been copied over [#888] Fix potentially broken tests I broke the tests because I moved `testTempDirectory` from each `TestCase` to the `Environment`. By this I caused that each tests uses exactly same URL. Which is directly against purpose of `testTempDirectory`. So now each test calls this one and store it to local variable. So each test has unique URL. [#888] Add ability to mock nonisolated methods to AutoMockable.stencil [#888] Add changelog and fix the documentation in ZcashRustBackendWelding [#888] Rename derivation rust backend protocol and remove static methods - Renamed `ZcashKeyDeriving` to `ZcashKeyDerivationBackendWelding`. So the naming scheme is same as for `ZcashRustBackendWelding`. - `ZcashKeyDerivationBackend` is now struct instead of enum. - Methods in `ZcashKeyDerivationBackendWelding` (except one) are no longer static. Because of this the respective methods in `DerivationTool` aren't also static anymore.
2023-03-31 10:10:35 -07:00
let nearestHeight: Int32
do {
nearestHeight = try await rustBackend.getNearestRewindHeight(height: height)
} catch {
await fail(error)
return await context.completion(.failure(error))
2021-04-19 10:07:50 -07:00
}
2021-09-17 06:49:58 -07:00
// FIXME: [#719] this should be done on the rust layer, https://github.com/zcash/ZcashLightClientKit/issues/719
2021-09-17 06:49:58 -07:00
let rewindHeight = max(Int32(nearestHeight - 1), Int32(config.walletBirthday))
[#888] Make actor from ZcashRustBackendWelding Closes #888. - `ZcashRustBackend` is actor now. So majority of methods in this actor are now async. - Some methods stayed `static` in `ZcashRustBackend`. It would be hard to pass instance of the `ZcashRustBackend` to the places where these methods are used in static manner. And it would change lot of APIs. But it isn't problem from technical perspective because these methods would be `nonisolated` otherwise. - Methods `lastError()` and `getLastError()` in `ZcashRustBackend` are now private. This makes sure that ther won't be aby race condition between other methods and these two error methods. - All the methods for which was `lastError()` used in code now throw error. So `lastError()` is no longer needed outside of the `ZcashRustBackend`. - There are in the public API related to `DerivationTool`. - `DerivationTool` now requires instance of the `ZcashRustBackend`. And `ZcashRustBackend` isn't public type. So `DerivationTool` doesn't have any public constructor now. It can be created only via `Initializer.makeDerivationTool()` instance method. - `deriveUnifiedSpendingKey()` and `deriveUnifiedFullViewingKey()` in `DerivationTool` are now async. It is because these are using `ZcashRustBackend` inside. `DerivationTool` offers alternative (closure and combine) APIs. But downside is that there is no sync API to dervie spending key or viewing key. - Some methods of the `DerivationTool` are now static. These methods don't use anything that requires instance of the `DerivationTool` inside. [#888] Use Sourcery to generate mocks - I wrote mock for `Synchronizer` manually. And it's tedious and long and boring work. - Now `ZcashRustBackendWelding` is changed a lot so it means `MockRustBackend` must be changed a lot. So I decided to introduce `sourcery` to generate mocks from protocols so we don't have to do it manually ever. - To generate mocks go to `ZcashLightClientKit/Tests/TestUtils/Sourcery` directory and run `generateMocks.sh` script. - Your protocol must be mentioned in `AutoMockable.swift` file. Generated mocks are in `AutoMockable.generated.swift` file. [#888] Fix Offline tests - Offline tests target now runs and tests are green. - There is log of changes in tests. But logic is not changed. - Updated `AutoMockable.stencil` so sourcery is able to generate mock as actor when protocol is marked with: `// sourcery: mockActor`. - Last few updates in `ZcashRustBackendWelding`. In previous PR `rewindCacheToHeight` methods was overlooked and it didn't throw error. - Removed `MockRustBackend` and using generated `ZCashRustBackendWeldingMock` instead. - Using generated `SynchronizerMock`. [#888] Fix NetworkTests - Changed a bit how rust backend mock is used in the tests. Introduced `RustBackendMockHelper`. There are some state variables that must be preserved within one instance of the mock. This helper does exactly this. It keeps this state variables in the memory and helping mock to work as expected. [#888] Fix Darkside tests Create ZcashKeyDeriving internal protocol Use New DerivationTool that does not require RustBackend Remove duplicated methods that had been copied over [#888] Fix potentially broken tests I broke the tests because I moved `testTempDirectory` from each `TestCase` to the `Environment`. By this I caused that each tests uses exactly same URL. Which is directly against purpose of `testTempDirectory`. So now each test calls this one and store it to local variable. So each test has unique URL. [#888] Add ability to mock nonisolated methods to AutoMockable.stencil [#888] Add changelog and fix the documentation in ZcashRustBackendWelding [#888] Rename derivation rust backend protocol and remove static methods - Renamed `ZcashKeyDeriving` to `ZcashKeyDerivationBackendWelding`. So the naming scheme is same as for `ZcashRustBackendWelding`. - `ZcashKeyDerivationBackend` is now struct instead of enum. - Methods in `ZcashKeyDerivationBackendWelding` (except one) are no longer static. Because of this the respective methods in `DerivationTool` aren't also static anymore.
2023-03-31 10:10:35 -07:00
do {
try await rustBackend.rewindToHeight(height: rewindHeight)
} catch {
await fail(error)
return await context.completion(.failure(error))
}
2021-09-17 06:49:58 -07:00
// clear cache
let rewindBlockHeight = BlockHeight(rewindHeight)
do {
try await blockDownloaderService.rewind(to: rewindBlockHeight)
} catch {
return await context.completion(.failure(error))
}
await internalSyncProgress.rewind(to: rewindBlockHeight)
2021-04-12 09:10:14 -07:00
self.lastChainValidationFailure = nil
await context.completion(.success(rewindBlockHeight))
}
2021-09-17 06:49:58 -07:00
// MARK: Wipe
func wipe(context: AfterSyncHooksManager.WipeContext) async {
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
logger.debug("Starting wipe")
switch self.state {
case .syncing, .enhancing, .fetching, .handlingSaplingFiles:
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
logger.debug("Stopping sync because of wipe")
afterSyncHooksManager.insert(hook: .wipe(context))
await stop()
case .stopped, .error, .synced:
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
logger.debug("Sync doesn't run. Executing wipe.")
await doWipe(context: context)
}
}
private func doWipe(context: AfterSyncHooksManager.WipeContext) async {
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
logger.debug("Executing wipe.")
context.prewipe()
[#831] Add SDKSynchronizer wrappers for non-async API This change introduces two new protocols: `ClosureSynchronizer` and `CombineSynchronizer`. These two protocols define API that doesn't use `async`. So the client can choose exactly which API it wants to use. This change also introduces two new objects: `ClosureSDKSynchronizer` and `CombineSDKSynchronizer`. These two implement the respective protocols mentioned above. Both are structures. Neither of these two keeps any state. Thanks to this each is very cheap to create. And usage of these two isn't mutually exclusive. So devs can really choose the best SDK API for each part of the client app. [#831] Use async inside of the SDKSynchronizer - In general lot of methods inside the `SDKSynchronizer` and `CompactBlockProcessoer` which weren't async are now async. And other changes are made because of this change. - `CompactBlockProcessor` no longer uses Combine to communicate with `SDKSynchronizer`. Reason for this is that Combine doesn't play great with async. Closure passed to `sink` isn't async. - Because of this and because of how our tests work (receiving signals from CBP directly) `CompactBlockProcessor` must be able to handle more event closures. Not just one. So it now has `eventClosures` dictionary. It's little bit strange but it works fine. - `SyncStatus` inside the `SDKSynchronizer` was previously protected by lock. Now it's protected by simple actor wrapper. - Changes in tests are minimal. Changes were mady only because `CompactBlockProcessor` changes from Combine to closures. [#831] Add tests for ClosureSDKSynchronizer - Added tests are testing in general if the `ClosuresSDKSynchronizer` is correctly calling `Synchronizer` and if the values are correctly returned. - `ClosuresSDKSynchronizer` doesn't contain any logic but it is public API and we should be sure that it works correctly. [#831] Add tests for CombineSDKSynchronizer [#831] Add changelog
2023-03-16 02:11:18 -07:00
await updateState(.stopped)
- [#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
do {
try await self.storage.clear()
await internalSyncProgress.rewind(to: 0)
wipeLegacyCacheDbIfNeeded()
- [#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
let fileManager = FileManager.default
if fileManager.fileExists(atPath: config.dataDb.path) {
try fileManager.removeItem(at: config.dataDb)
}
[#831] Add SDKSynchronizer wrappers for non-async API This change introduces two new protocols: `ClosureSynchronizer` and `CombineSynchronizer`. These two protocols define API that doesn't use `async`. So the client can choose exactly which API it wants to use. This change also introduces two new objects: `ClosureSDKSynchronizer` and `CombineSDKSynchronizer`. These two implement the respective protocols mentioned above. Both are structures. Neither of these two keeps any state. Thanks to this each is very cheap to create. And usage of these two isn't mutually exclusive. So devs can really choose the best SDK API for each part of the client app. [#831] Use async inside of the SDKSynchronizer - In general lot of methods inside the `SDKSynchronizer` and `CompactBlockProcessoer` which weren't async are now async. And other changes are made because of this change. - `CompactBlockProcessor` no longer uses Combine to communicate with `SDKSynchronizer`. Reason for this is that Combine doesn't play great with async. Closure passed to `sink` isn't async. - Because of this and because of how our tests work (receiving signals from CBP directly) `CompactBlockProcessor` must be able to handle more event closures. Not just one. So it now has `eventClosures` dictionary. It's little bit strange but it works fine. - `SyncStatus` inside the `SDKSynchronizer` was previously protected by lock. Now it's protected by simple actor wrapper. - Changes in tests are minimal. Changes were mady only because `CompactBlockProcessor` changes from Combine to closures. [#831] Add tests for ClosureSDKSynchronizer - Added tests are testing in general if the `ClosuresSDKSynchronizer` is correctly calling `Synchronizer` and if the values are correctly returned. - `ClosuresSDKSynchronizer` doesn't contain any logic but it is public API and we should be sure that it works correctly. [#831] Add tests for CombineSDKSynchronizer [#831] Add changelog
2023-03-16 02:11:18 -07:00
await context.completion(nil)
} catch {
[#831] Add SDKSynchronizer wrappers for non-async API This change introduces two new protocols: `ClosureSynchronizer` and `CombineSynchronizer`. These two protocols define API that doesn't use `async`. So the client can choose exactly which API it wants to use. This change also introduces two new objects: `ClosureSDKSynchronizer` and `CombineSDKSynchronizer`. These two implement the respective protocols mentioned above. Both are structures. Neither of these two keeps any state. Thanks to this each is very cheap to create. And usage of these two isn't mutually exclusive. So devs can really choose the best SDK API for each part of the client app. [#831] Use async inside of the SDKSynchronizer - In general lot of methods inside the `SDKSynchronizer` and `CompactBlockProcessoer` which weren't async are now async. And other changes are made because of this change. - `CompactBlockProcessor` no longer uses Combine to communicate with `SDKSynchronizer`. Reason for this is that Combine doesn't play great with async. Closure passed to `sink` isn't async. - Because of this and because of how our tests work (receiving signals from CBP directly) `CompactBlockProcessor` must be able to handle more event closures. Not just one. So it now has `eventClosures` dictionary. It's little bit strange but it works fine. - `SyncStatus` inside the `SDKSynchronizer` was previously protected by lock. Now it's protected by simple actor wrapper. - Changes in tests are minimal. Changes were mady only because `CompactBlockProcessor` changes from Combine to closures. [#831] Add tests for ClosureSDKSynchronizer - Added tests are testing in general if the `ClosuresSDKSynchronizer` is correctly calling `Synchronizer` and if the values are correctly returned. - `ClosuresSDKSynchronizer` doesn't contain any logic but it is public API and we should be sure that it works correctly. [#831] Add tests for CombineSDKSynchronizer [#831] Add changelog
2023-03-16 02:11:18 -07:00
await context.completion(error)
}
}
// MARK: Sync
func validateServer() async {
do {
let info = try await self.service.getInfo()
[#888] Make actor from ZcashRustBackendWelding Closes #888. - `ZcashRustBackend` is actor now. So majority of methods in this actor are now async. - Some methods stayed `static` in `ZcashRustBackend`. It would be hard to pass instance of the `ZcashRustBackend` to the places where these methods are used in static manner. And it would change lot of APIs. But it isn't problem from technical perspective because these methods would be `nonisolated` otherwise. - Methods `lastError()` and `getLastError()` in `ZcashRustBackend` are now private. This makes sure that ther won't be aby race condition between other methods and these two error methods. - All the methods for which was `lastError()` used in code now throw error. So `lastError()` is no longer needed outside of the `ZcashRustBackend`. - There are in the public API related to `DerivationTool`. - `DerivationTool` now requires instance of the `ZcashRustBackend`. And `ZcashRustBackend` isn't public type. So `DerivationTool` doesn't have any public constructor now. It can be created only via `Initializer.makeDerivationTool()` instance method. - `deriveUnifiedSpendingKey()` and `deriveUnifiedFullViewingKey()` in `DerivationTool` are now async. It is because these are using `ZcashRustBackend` inside. `DerivationTool` offers alternative (closure and combine) APIs. But downside is that there is no sync API to dervie spending key or viewing key. - Some methods of the `DerivationTool` are now static. These methods don't use anything that requires instance of the `DerivationTool` inside. [#888] Use Sourcery to generate mocks - I wrote mock for `Synchronizer` manually. And it's tedious and long and boring work. - Now `ZcashRustBackendWelding` is changed a lot so it means `MockRustBackend` must be changed a lot. So I decided to introduce `sourcery` to generate mocks from protocols so we don't have to do it manually ever. - To generate mocks go to `ZcashLightClientKit/Tests/TestUtils/Sourcery` directory and run `generateMocks.sh` script. - Your protocol must be mentioned in `AutoMockable.swift` file. Generated mocks are in `AutoMockable.generated.swift` file. [#888] Fix Offline tests - Offline tests target now runs and tests are green. - There is log of changes in tests. But logic is not changed. - Updated `AutoMockable.stencil` so sourcery is able to generate mock as actor when protocol is marked with: `// sourcery: mockActor`. - Last few updates in `ZcashRustBackendWelding`. In previous PR `rewindCacheToHeight` methods was overlooked and it didn't throw error. - Removed `MockRustBackend` and using generated `ZCashRustBackendWeldingMock` instead. - Using generated `SynchronizerMock`. [#888] Fix NetworkTests - Changed a bit how rust backend mock is used in the tests. Introduced `RustBackendMockHelper`. There are some state variables that must be preserved within one instance of the mock. This helper does exactly this. It keeps this state variables in the memory and helping mock to work as expected. [#888] Fix Darkside tests Create ZcashKeyDeriving internal protocol Use New DerivationTool that does not require RustBackend Remove duplicated methods that had been copied over [#888] Fix potentially broken tests I broke the tests because I moved `testTempDirectory` from each `TestCase` to the `Environment`. By this I caused that each tests uses exactly same URL. Which is directly against purpose of `testTempDirectory`. So now each test calls this one and store it to local variable. So each test has unique URL. [#888] Add ability to mock nonisolated methods to AutoMockable.stencil [#888] Add changelog and fix the documentation in ZcashRustBackendWelding [#888] Rename derivation rust backend protocol and remove static methods - Renamed `ZcashKeyDeriving` to `ZcashKeyDerivationBackendWelding`. So the naming scheme is same as for `ZcashRustBackendWelding`. - `ZcashKeyDerivationBackend` is now struct instead of enum. - Methods in `ZcashKeyDerivationBackendWelding` (except one) are no longer static. Because of this the respective methods in `DerivationTool` aren't also static anymore.
2023-03-31 10:10:35 -07:00
try await Self.validateServerInfo(
info,
saplingActivation: self.config.saplingActivation,
localNetwork: self.config.network,
rustBackend: self.rustBackend
)
} catch {
[#831] Add SDKSynchronizer wrappers for non-async API This change introduces two new protocols: `ClosureSynchronizer` and `CombineSynchronizer`. These two protocols define API that doesn't use `async`. So the client can choose exactly which API it wants to use. This change also introduces two new objects: `ClosureSDKSynchronizer` and `CombineSDKSynchronizer`. These two implement the respective protocols mentioned above. Both are structures. Neither of these two keeps any state. Thanks to this each is very cheap to create. And usage of these two isn't mutually exclusive. So devs can really choose the best SDK API for each part of the client app. [#831] Use async inside of the SDKSynchronizer - In general lot of methods inside the `SDKSynchronizer` and `CompactBlockProcessoer` which weren't async are now async. And other changes are made because of this change. - `CompactBlockProcessor` no longer uses Combine to communicate with `SDKSynchronizer`. Reason for this is that Combine doesn't play great with async. Closure passed to `sink` isn't async. - Because of this and because of how our tests work (receiving signals from CBP directly) `CompactBlockProcessor` must be able to handle more event closures. Not just one. So it now has `eventClosures` dictionary. It's little bit strange but it works fine. - `SyncStatus` inside the `SDKSynchronizer` was previously protected by lock. Now it's protected by simple actor wrapper. - Changes in tests are minimal. Changes were mady only because `CompactBlockProcessor` changes from Combine to closures. [#831] Add tests for ClosureSDKSynchronizer - Added tests are testing in general if the `ClosuresSDKSynchronizer` is correctly calling `Synchronizer` and if the values are correctly returned. - `ClosuresSDKSynchronizer` doesn't contain any logic but it is public API and we should be sure that it works correctly. [#831] Add tests for CombineSDKSynchronizer [#831] Add changelog
2023-03-16 02:11:18 -07:00
await self.severeFailure(error)
}
}
[476] CompactBlockProcessor to async/await - getting rid of the Operation Queue - the cleanup is needed - the update of tests is needed - tested and it successfully finishes the sync process [476] CompactBlockProcessor to async/await - old processNewBlocks() removed [476] CompactBlockProcessor to async/await - unused operations removed [476] CompactBlockProcessor to async/await - unit tests update [476] CompactBlockProcessor to async/await - unit tests refactored [476] CompactBlockProcessor to async/await - cleanup of deprecated method [476] CompactBlockProcessor to async/await - fail(error) was called even for canceled tasks but that must be excluded [476] CompactBlockProcessor to async/await - removal of all ZcashOperations from the code (unit test will follow) [476] CompactBlockProcessor to async/await - network tests in building and success order again [476] CompactBlockProcessor to async/await - offline tests in building and success order [476] CompactBlockProcessor to async/await (519) - cleanup of suspending the task [476] CompactBlockProcessor to async/await (519) - most comments resolved [476] CompactBlockProcessor to async/await (519) - thread safe state for both sync and async context [476] CompactBlockProcessor to async/await (519) - fixed build for a sample project [476] CompactBlockProcessor to async/await (519) - func testStartNotifiesSuscriptors() reverted [476] CompactBlockProcessor to async/await (519) - TODO added to track why we used NSLock instead of an Actor - Task priority enhanced [476] CompactBlockProcessor to async/await (519) - cleanup in Tasks and priorities
2022-09-01 05:58:41 -07:00
/// Processes new blocks on the given range based on the configuration set for this instance
func processNewBlocks(ranges: SyncRanges) async {
2021-04-01 07:27:26 -07:00
self.foundBlocks = true
cancelableTask = Task(priority: .userInitiated) {
[476] CompactBlockProcessor to async/await - getting rid of the Operation Queue - the cleanup is needed - the update of tests is needed - tested and it successfully finishes the sync process [476] CompactBlockProcessor to async/await - old processNewBlocks() removed [476] CompactBlockProcessor to async/await - unused operations removed [476] CompactBlockProcessor to async/await - unit tests update [476] CompactBlockProcessor to async/await - unit tests refactored [476] CompactBlockProcessor to async/await - cleanup of deprecated method [476] CompactBlockProcessor to async/await - fail(error) was called even for canceled tasks but that must be excluded [476] CompactBlockProcessor to async/await - removal of all ZcashOperations from the code (unit test will follow) [476] CompactBlockProcessor to async/await - network tests in building and success order again [476] CompactBlockProcessor to async/await - offline tests in building and success order [476] CompactBlockProcessor to async/await (519) - cleanup of suspending the task [476] CompactBlockProcessor to async/await (519) - most comments resolved [476] CompactBlockProcessor to async/await (519) - thread safe state for both sync and async context [476] CompactBlockProcessor to async/await (519) - fixed build for a sample project [476] CompactBlockProcessor to async/await (519) - func testStartNotifiesSuscriptors() reverted [476] CompactBlockProcessor to async/await (519) - TODO added to track why we used NSLock instead of an Actor - Task priority enhanced [476] CompactBlockProcessor to async/await (519) - cleanup in Tasks and priorities
2022-09-01 05:58:41 -07:00
do {
let totalProgressRange = computeTotalProgressRange(from: ranges)
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
logger.debug("""
Syncing with ranges:
downloaded but not scanned: \
\(ranges.downloadedButUnscannedRange?.lowerBound ?? -1)...\(ranges.downloadedButUnscannedRange?.upperBound ?? -1)
download and scan: \(ranges.downloadAndScanRange?.lowerBound ?? -1)...\(ranges.downloadAndScanRange?.upperBound ?? -1)
enhance range: \(ranges.enhanceRange?.lowerBound ?? -1)...\(ranges.enhanceRange?.upperBound ?? -1)
fetchUTXO range: \(ranges.fetchUTXORange?.lowerBound ?? -1)...\(ranges.fetchUTXORange?.upperBound ?? -1)
total progress range: \(totalProgressRange.lowerBound)...\(totalProgressRange.upperBound)
""")
var anyActionExecuted = false
// clear any present cached state if needed.
// this checks if there was a sync in progress that was
// interrupted abruptly and cache was not able to be cleared
// properly and internal state set to the appropriate value
if let newLatestDownloadedHeight = ranges.shouldClearBlockCacheAndUpdateInternalState() {
try await storage.clear()
await internalSyncProgress.set(newLatestDownloadedHeight, .latestDownloadedBlockHeight)
} else {
try await storage.create()
}
if let range = ranges.downloadedButUnscannedRange {
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
logger.debug("Starting scan with downloaded but not scanned blocks with range: \(range.lowerBound)...\(range.upperBound)")
try await blockScanner.scanBlocks(at: range, totalProgressRange: totalProgressRange) { [weak self] lastScannedHeight in
let progress = BlockProgress(
startHeight: totalProgressRange.lowerBound,
targetHeight: totalProgressRange.upperBound,
progressHeight: lastScannedHeight
)
await self?.notifyProgress(.syncing(progress))
}
}
if let range = ranges.downloadAndScanRange {
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
logger.debug("Starting sync with range: \(range.lowerBound)...\(range.upperBound)")
try await blockDownloader.setSyncRange(range)
try await downloadAndScanBlocks(at: range, totalProgressRange: totalProgressRange)
}
if let range = ranges.enhanceRange {
anyActionExecuted = true
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
logger.debug("Enhancing with range: \(range.lowerBound)...\(range.upperBound)")
[#831] Add SDKSynchronizer wrappers for non-async API This change introduces two new protocols: `ClosureSynchronizer` and `CombineSynchronizer`. These two protocols define API that doesn't use `async`. So the client can choose exactly which API it wants to use. This change also introduces two new objects: `ClosureSDKSynchronizer` and `CombineSDKSynchronizer`. These two implement the respective protocols mentioned above. Both are structures. Neither of these two keeps any state. Thanks to this each is very cheap to create. And usage of these two isn't mutually exclusive. So devs can really choose the best SDK API for each part of the client app. [#831] Use async inside of the SDKSynchronizer - In general lot of methods inside the `SDKSynchronizer` and `CompactBlockProcessoer` which weren't async are now async. And other changes are made because of this change. - `CompactBlockProcessor` no longer uses Combine to communicate with `SDKSynchronizer`. Reason for this is that Combine doesn't play great with async. Closure passed to `sink` isn't async. - Because of this and because of how our tests work (receiving signals from CBP directly) `CompactBlockProcessor` must be able to handle more event closures. Not just one. So it now has `eventClosures` dictionary. It's little bit strange but it works fine. - `SyncStatus` inside the `SDKSynchronizer` was previously protected by lock. Now it's protected by simple actor wrapper. - Changes in tests are minimal. Changes were mady only because `CompactBlockProcessor` changes from Combine to closures. [#831] Add tests for ClosureSDKSynchronizer - Added tests are testing in general if the `ClosuresSDKSynchronizer` is correctly calling `Synchronizer` and if the values are correctly returned. - `ClosuresSDKSynchronizer` doesn't contain any logic but it is public API and we should be sure that it works correctly. [#831] Add tests for CombineSDKSynchronizer [#831] Add changelog
2023-03-16 02:11:18 -07:00
await updateState(.enhancing)
let transactions = try await blockEnhancer.enhance(at: range) { [weak self] progress in
await self?.notifyProgress(.enhance(progress))
}
[#831] Add SDKSynchronizer wrappers for non-async API This change introduces two new protocols: `ClosureSynchronizer` and `CombineSynchronizer`. These two protocols define API that doesn't use `async`. So the client can choose exactly which API it wants to use. This change also introduces two new objects: `ClosureSDKSynchronizer` and `CombineSDKSynchronizer`. These two implement the respective protocols mentioned above. Both are structures. Neither of these two keeps any state. Thanks to this each is very cheap to create. And usage of these two isn't mutually exclusive. So devs can really choose the best SDK API for each part of the client app. [#831] Use async inside of the SDKSynchronizer - In general lot of methods inside the `SDKSynchronizer` and `CompactBlockProcessoer` which weren't async are now async. And other changes are made because of this change. - `CompactBlockProcessor` no longer uses Combine to communicate with `SDKSynchronizer`. Reason for this is that Combine doesn't play great with async. Closure passed to `sink` isn't async. - Because of this and because of how our tests work (receiving signals from CBP directly) `CompactBlockProcessor` must be able to handle more event closures. Not just one. So it now has `eventClosures` dictionary. It's little bit strange but it works fine. - `SyncStatus` inside the `SDKSynchronizer` was previously protected by lock. Now it's protected by simple actor wrapper. - Changes in tests are minimal. Changes were mady only because `CompactBlockProcessor` changes from Combine to closures. [#831] Add tests for ClosureSDKSynchronizer - Added tests are testing in general if the `ClosuresSDKSynchronizer` is correctly calling `Synchronizer` and if the values are correctly returned. - `ClosuresSDKSynchronizer` doesn't contain any logic but it is public API and we should be sure that it works correctly. [#831] Add tests for CombineSDKSynchronizer [#831] Add changelog
2023-03-16 02:11:18 -07:00
await notifyTransactions(transactions, in: range)
}
if let range = ranges.fetchUTXORange {
anyActionExecuted = true
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
logger.debug("Fetching UTXO with range: \(range.lowerBound)...\(range.upperBound)")
[#831] Add SDKSynchronizer wrappers for non-async API This change introduces two new protocols: `ClosureSynchronizer` and `CombineSynchronizer`. These two protocols define API that doesn't use `async`. So the client can choose exactly which API it wants to use. This change also introduces two new objects: `ClosureSDKSynchronizer` and `CombineSDKSynchronizer`. These two implement the respective protocols mentioned above. Both are structures. Neither of these two keeps any state. Thanks to this each is very cheap to create. And usage of these two isn't mutually exclusive. So devs can really choose the best SDK API for each part of the client app. [#831] Use async inside of the SDKSynchronizer - In general lot of methods inside the `SDKSynchronizer` and `CompactBlockProcessoer` which weren't async are now async. And other changes are made because of this change. - `CompactBlockProcessor` no longer uses Combine to communicate with `SDKSynchronizer`. Reason for this is that Combine doesn't play great with async. Closure passed to `sink` isn't async. - Because of this and because of how our tests work (receiving signals from CBP directly) `CompactBlockProcessor` must be able to handle more event closures. Not just one. So it now has `eventClosures` dictionary. It's little bit strange but it works fine. - `SyncStatus` inside the `SDKSynchronizer` was previously protected by lock. Now it's protected by simple actor wrapper. - Changes in tests are minimal. Changes were mady only because `CompactBlockProcessor` changes from Combine to closures. [#831] Add tests for ClosureSDKSynchronizer - Added tests are testing in general if the `ClosuresSDKSynchronizer` is correctly calling `Synchronizer` and if the values are correctly returned. - `ClosuresSDKSynchronizer` doesn't contain any logic but it is public API and we should be sure that it works correctly. [#831] Add tests for CombineSDKSynchronizer [#831] Add changelog
2023-03-16 02:11:18 -07:00
await updateState(.fetching)
let result = try await utxoFetcher.fetch(at: range)
[#831] Add SDKSynchronizer wrappers for non-async API This change introduces two new protocols: `ClosureSynchronizer` and `CombineSynchronizer`. These two protocols define API that doesn't use `async`. So the client can choose exactly which API it wants to use. This change also introduces two new objects: `ClosureSDKSynchronizer` and `CombineSDKSynchronizer`. These two implement the respective protocols mentioned above. Both are structures. Neither of these two keeps any state. Thanks to this each is very cheap to create. And usage of these two isn't mutually exclusive. So devs can really choose the best SDK API for each part of the client app. [#831] Use async inside of the SDKSynchronizer - In general lot of methods inside the `SDKSynchronizer` and `CompactBlockProcessoer` which weren't async are now async. And other changes are made because of this change. - `CompactBlockProcessor` no longer uses Combine to communicate with `SDKSynchronizer`. Reason for this is that Combine doesn't play great with async. Closure passed to `sink` isn't async. - Because of this and because of how our tests work (receiving signals from CBP directly) `CompactBlockProcessor` must be able to handle more event closures. Not just one. So it now has `eventClosures` dictionary. It's little bit strange but it works fine. - `SyncStatus` inside the `SDKSynchronizer` was previously protected by lock. Now it's protected by simple actor wrapper. - Changes in tests are minimal. Changes were mady only because `CompactBlockProcessor` changes from Combine to closures. [#831] Add tests for ClosureSDKSynchronizer - Added tests are testing in general if the `ClosuresSDKSynchronizer` is correctly calling `Synchronizer` and if the values are correctly returned. - `ClosuresSDKSynchronizer` doesn't contain any logic but it is public API and we should be sure that it works correctly. [#831] Add tests for CombineSDKSynchronizer [#831] Add changelog
2023-03-16 02:11:18 -07:00
await send(event: .storedUTXOs(result))
}
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
logger.debug("Fetching sapling parameters")
[#831] Add SDKSynchronizer wrappers for non-async API This change introduces two new protocols: `ClosureSynchronizer` and `CombineSynchronizer`. These two protocols define API that doesn't use `async`. So the client can choose exactly which API it wants to use. This change also introduces two new objects: `ClosureSDKSynchronizer` and `CombineSDKSynchronizer`. These two implement the respective protocols mentioned above. Both are structures. Neither of these two keeps any state. Thanks to this each is very cheap to create. And usage of these two isn't mutually exclusive. So devs can really choose the best SDK API for each part of the client app. [#831] Use async inside of the SDKSynchronizer - In general lot of methods inside the `SDKSynchronizer` and `CompactBlockProcessoer` which weren't async are now async. And other changes are made because of this change. - `CompactBlockProcessor` no longer uses Combine to communicate with `SDKSynchronizer`. Reason for this is that Combine doesn't play great with async. Closure passed to `sink` isn't async. - Because of this and because of how our tests work (receiving signals from CBP directly) `CompactBlockProcessor` must be able to handle more event closures. Not just one. So it now has `eventClosures` dictionary. It's little bit strange but it works fine. - `SyncStatus` inside the `SDKSynchronizer` was previously protected by lock. Now it's protected by simple actor wrapper. - Changes in tests are minimal. Changes were mady only because `CompactBlockProcessor` changes from Combine to closures. [#831] Add tests for ClosureSDKSynchronizer - Added tests are testing in general if the `ClosuresSDKSynchronizer` is correctly calling `Synchronizer` and if the values are correctly returned. - `ClosuresSDKSynchronizer` doesn't contain any logic but it is public API and we should be sure that it works correctly. [#831] Add tests for CombineSDKSynchronizer [#831] Add changelog
2023-03-16 02:11:18 -07:00
await updateState(.handlingSaplingFiles)
try await saplingParametersHandler.handleIfNeeded()
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
logger.debug("Clearing cache")
- [#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 await clearCompactBlockCache()
if !Task.isCancelled {
let newBlocksMined = await ranges.latestBlockHeight < latestBlocksDataProvider.latestBlockHeight
await processBatchFinished(height: (anyActionExecuted && !newBlocksMined) ? ranges.latestBlockHeight : nil)
}
[476] CompactBlockProcessor to async/await - getting rid of the Operation Queue - the cleanup is needed - the update of tests is needed - tested and it successfully finishes the sync process [476] CompactBlockProcessor to async/await - old processNewBlocks() removed [476] CompactBlockProcessor to async/await - unused operations removed [476] CompactBlockProcessor to async/await - unit tests update [476] CompactBlockProcessor to async/await - unit tests refactored [476] CompactBlockProcessor to async/await - cleanup of deprecated method [476] CompactBlockProcessor to async/await - fail(error) was called even for canceled tasks but that must be excluded [476] CompactBlockProcessor to async/await - removal of all ZcashOperations from the code (unit test will follow) [476] CompactBlockProcessor to async/await - network tests in building and success order again [476] CompactBlockProcessor to async/await - offline tests in building and success order [476] CompactBlockProcessor to async/await (519) - cleanup of suspending the task [476] CompactBlockProcessor to async/await (519) - most comments resolved [476] CompactBlockProcessor to async/await (519) - thread safe state for both sync and async context [476] CompactBlockProcessor to async/await (519) - fixed build for a sample project [476] CompactBlockProcessor to async/await (519) - func testStartNotifiesSuscriptors() reverted [476] CompactBlockProcessor to async/await (519) - TODO added to track why we used NSLock instead of an Actor - Task priority enhanced [476] CompactBlockProcessor to async/await (519) - cleanup in Tasks and priorities
2022-09-01 05:58:41 -07:00
} catch {
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
logger.error("Sync failed with error: \(error)")
if Task.isCancelled {
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
logger.info("Processing cancelled.")
[#831] Add SDKSynchronizer wrappers for non-async API This change introduces two new protocols: `ClosureSynchronizer` and `CombineSynchronizer`. These two protocols define API that doesn't use `async`. So the client can choose exactly which API it wants to use. This change also introduces two new objects: `ClosureSDKSynchronizer` and `CombineSDKSynchronizer`. These two implement the respective protocols mentioned above. Both are structures. Neither of these two keeps any state. Thanks to this each is very cheap to create. And usage of these two isn't mutually exclusive. So devs can really choose the best SDK API for each part of the client app. [#831] Use async inside of the SDKSynchronizer - In general lot of methods inside the `SDKSynchronizer` and `CompactBlockProcessoer` which weren't async are now async. And other changes are made because of this change. - `CompactBlockProcessor` no longer uses Combine to communicate with `SDKSynchronizer`. Reason for this is that Combine doesn't play great with async. Closure passed to `sink` isn't async. - Because of this and because of how our tests work (receiving signals from CBP directly) `CompactBlockProcessor` must be able to handle more event closures. Not just one. So it now has `eventClosures` dictionary. It's little bit strange but it works fine. - `SyncStatus` inside the `SDKSynchronizer` was previously protected by lock. Now it's protected by simple actor wrapper. - Changes in tests are minimal. Changes were mady only because `CompactBlockProcessor` changes from Combine to closures. [#831] Add tests for ClosureSDKSynchronizer - Added tests are testing in general if the `ClosuresSDKSynchronizer` is correctly calling `Synchronizer` and if the values are correctly returned. - `ClosuresSDKSynchronizer` doesn't contain any logic but it is public API and we should be sure that it works correctly. [#831] Add tests for CombineSDKSynchronizer [#831] Add changelog
2023-03-16 02:11:18 -07:00
await updateState(.stopped)
await handleAfterSyncHooks()
} else {
[#361] Introduce ZcashError (#1005) This PR introduces `ZcashError` enum. This enum represents any error that can be thrown inside of the SDK and outside of the SDK. Also `ZcashError` is used in `LightWalletGRPCService` and handled in `CompactBlockProcessor` as example. Why enum? First I tried this with some structure which contained code, message and underlyingError. Problem was when some specific place in the SDK would like to attach some additional data to error. I didn't want to add some generic dictionary to store anything with the error. So I used enum to identify error. Each member can have specified amount of associated values. So specific error can bring some context data. And it's type safe. Each error has also a code. Relationship between errors and codes is 1:1. It may looks bit redundant but it's important. The client app now can choose how to process errors. Either identify those by the error itself or by code. Definition or errors and codes is in `ZcashErrorDefinition`. And then `ZcashError` and `ZcashErrorCode` are generated by Sourcery. Thanks to this it is easier to maintain the final code. And it gives us ability to generate any kind of documentation for the errors and codes. I created simple example of this in this PR. And it doesn't make the SDK completely dependent on the Sourcery. Final structures aren't super complicated and can be written manually if needed. [#923] Update error handling in DatabaseStorageManager.swift - cleanup of DatabaseStorageManager, not used anymore - ZcashError for SimpleConnectionProvider Revert "[#923] Update error handling in DatabaseStorageManager.swift" This reverts commit 94e028d31a0f6635800c297eb741db74c6a6ff45. Fix script which generates ZcashError [#922] Update error handling in DatabaseMigrationManager.swift Closes #922 [#923] Update error handling in DatabaseStorageManager.swift - The DatabaseStorageManager is not used so I deleted it - SimpleConnectionProvider's errors updated Fix tests [#955] Update error handling in SaplingParameterDownloader Closes #955 [#936] Update error handling in NotesDao Closes #936 [#935] Update error handling in BlockDao Closes #935 [#931] InternalSyncProgress.computeNextState doesn't need to throw Closes #931 [#950] Update error handling in rust backend Closes #949 Closes #950 [#941] Update error handling in AccountEntity Closes #941 [#928] Update error handling in FSCompactBlockRepository Closes #928 [#925] Update error handling in BlockDownloaderService (#974) - BlockDownloaderService errors updated [#924] Update error handling in BlockDownloader (#973) - BlockDownloaderStream nextBlock updated [#942] Update error handling in TransactionEntity (#977) - ZcashTransaction init errors converted to the ZcashError [#939] Update error handling in TransactionDao (#976) - TransactionRepositoryError removed and replaced with ZcashError - all TransactionDAO errors converted to ZcashError [#943] Update error handling in ZcashCompactBlock Closes #943 [#945] Update error handling in Memo Closes #945 [#934] Update error handling in Checkpoint Closes #944 Closes #934 [#938] Update error handling in PendingTransactionDao Closes #938 [#926] Update error handling in BlockEnhancer - WIP, switching to transaction repository to unblock this ticket [#926] Update error handling in BlockEnhancer - enhancer's errors done [#926] Update error handling in BlockEnhancer (#994) - cleanup [#952] Update error handling in DerivationTool Closes #952 [#932] Update error handling in BlockValidator Closes #932 [#940] Update error handling in UnspentTransactionOutputDao Closes #940 [#946] Update error handling in WalletTypes Closes #946 [#954] Update error handling in WalletTransactionEncoder Closes #954 [#953] Update error handling in PersistentTransactionManager Closes #953 [#956] Update error handling in Initializer Closes #956 [#947] Update error handling in Zatoshi (#996) - Zatoshi's errors converted to ZcashError [#927] Update error handling in UTXOFetcher (#997) - UTXOFetcher resolved Use let instead of var where applicable In the SDK `var` was used on places where `let` would be sufficient. And default strategy in Swift should use use `let` until mutability is required. So all these places are changed. No logic is changed. [#933] Update error handling in CompactBlockProcessor - CompactBlockProcessor's errors refactored to ZcashError [#933] Update error handling in CompactBlockProcessor #999 - comments addressed [#951] Update error handling in SDKSynchronizer - SDKSynchronizer's errors refactored to ZcashError [#951] Update error handling in SDKSynchronizer (#1002) - comments resolved Make DerivationTool constructor public DerivationTool.init should be public. This was removed by accident when adopting async. [#361] Add changelog
2023-04-24 14:15:20 -07:00
if case let ZcashError.rustValidateCombinedChainInvalidChain(height) = error {
await validationFailed(at: BlockHeight(height))
} else {
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
logger.error("processing failed with error: \(error)")
await fail(error)
}
[476] CompactBlockProcessor to async/await - getting rid of the Operation Queue - the cleanup is needed - the update of tests is needed - tested and it successfully finishes the sync process [476] CompactBlockProcessor to async/await - old processNewBlocks() removed [476] CompactBlockProcessor to async/await - unused operations removed [476] CompactBlockProcessor to async/await - unit tests update [476] CompactBlockProcessor to async/await - unit tests refactored [476] CompactBlockProcessor to async/await - cleanup of deprecated method [476] CompactBlockProcessor to async/await - fail(error) was called even for canceled tasks but that must be excluded [476] CompactBlockProcessor to async/await - removal of all ZcashOperations from the code (unit test will follow) [476] CompactBlockProcessor to async/await - network tests in building and success order again [476] CompactBlockProcessor to async/await - offline tests in building and success order [476] CompactBlockProcessor to async/await (519) - cleanup of suspending the task [476] CompactBlockProcessor to async/await (519) - most comments resolved [476] CompactBlockProcessor to async/await (519) - thread safe state for both sync and async context [476] CompactBlockProcessor to async/await (519) - fixed build for a sample project [476] CompactBlockProcessor to async/await (519) - func testStartNotifiesSuscriptors() reverted [476] CompactBlockProcessor to async/await (519) - TODO added to track why we used NSLock instead of an Actor - Task priority enhanced [476] CompactBlockProcessor to async/await (519) - cleanup in Tasks and priorities
2022-09-01 05:58:41 -07:00
}
}
}
}
private func handleAfterSyncHooks() async {
let afterSyncHooksManager = self.afterSyncHooksManager
self.afterSyncHooksManager = AfterSyncHooksManager()
if let wipeContext = afterSyncHooksManager.shouldExecuteWipeHook() {
await doWipe(context: wipeContext)
} else if let rewindContext = afterSyncHooksManager.shouldExecuteRewindHook() {
await doRewind(context: rewindContext)
} else if afterSyncHooksManager.shouldExecuteAnotherSyncHook() {
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
logger.debug("Starting new sync.")
await nextBatch()
}
}
private func downloadAndScanBlocks(at range: CompactBlockRange, totalProgressRange: CompactBlockRange) async throws {
// Divide `range` by `batchSize` and compute how many time do we need to run to download and scan all the blocks.
// +1 must be done here becase `range` is closed range. So even if upperBound and lowerBound are same there is one block to sync.
let blocksCountToSync = (range.upperBound - range.lowerBound) + 1
var loopsCount = blocksCountToSync / batchSize
if blocksCountToSync % batchSize != 0 {
loopsCount += 1
}
var lastScannedHeight: BlockHeight = .zero
for i in 0..<loopsCount {
let processingRange = computeSingleLoopDownloadRange(fullRange: range, loopCounter: i, batchSize: batchSize)
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
logger.debug("Sync loop #\(i + 1) range: \(processingRange.lowerBound)...\(processingRange.upperBound)")
// This is important. We must be sure that no new download is executed when this Task is canceled. Without this line `stop()` doesn't
// work.
try Task.checkCancellation()
do {
await blockDownloader.setDownloadLimit(processingRange.upperBound + (2 * batchSize))
await blockDownloader.startDownload(maxBlockBufferSize: config.downloadBufferSize)
try await blockDownloader.waitUntilRequestedBlocksAreDownloaded(in: processingRange)
} catch {
await ifTaskIsNotCanceledClearCompactBlockCache(lastScannedHeight: lastScannedHeight)
throw error
}
do {
try await blockValidator.validate()
} catch {
await ifTaskIsNotCanceledClearCompactBlockCache(lastScannedHeight: lastScannedHeight)
[#361] Introduce ZcashError (#1005) This PR introduces `ZcashError` enum. This enum represents any error that can be thrown inside of the SDK and outside of the SDK. Also `ZcashError` is used in `LightWalletGRPCService` and handled in `CompactBlockProcessor` as example. Why enum? First I tried this with some structure which contained code, message and underlyingError. Problem was when some specific place in the SDK would like to attach some additional data to error. I didn't want to add some generic dictionary to store anything with the error. So I used enum to identify error. Each member can have specified amount of associated values. So specific error can bring some context data. And it's type safe. Each error has also a code. Relationship between errors and codes is 1:1. It may looks bit redundant but it's important. The client app now can choose how to process errors. Either identify those by the error itself or by code. Definition or errors and codes is in `ZcashErrorDefinition`. And then `ZcashError` and `ZcashErrorCode` are generated by Sourcery. Thanks to this it is easier to maintain the final code. And it gives us ability to generate any kind of documentation for the errors and codes. I created simple example of this in this PR. And it doesn't make the SDK completely dependent on the Sourcery. Final structures aren't super complicated and can be written manually if needed. [#923] Update error handling in DatabaseStorageManager.swift - cleanup of DatabaseStorageManager, not used anymore - ZcashError for SimpleConnectionProvider Revert "[#923] Update error handling in DatabaseStorageManager.swift" This reverts commit 94e028d31a0f6635800c297eb741db74c6a6ff45. Fix script which generates ZcashError [#922] Update error handling in DatabaseMigrationManager.swift Closes #922 [#923] Update error handling in DatabaseStorageManager.swift - The DatabaseStorageManager is not used so I deleted it - SimpleConnectionProvider's errors updated Fix tests [#955] Update error handling in SaplingParameterDownloader Closes #955 [#936] Update error handling in NotesDao Closes #936 [#935] Update error handling in BlockDao Closes #935 [#931] InternalSyncProgress.computeNextState doesn't need to throw Closes #931 [#950] Update error handling in rust backend Closes #949 Closes #950 [#941] Update error handling in AccountEntity Closes #941 [#928] Update error handling in FSCompactBlockRepository Closes #928 [#925] Update error handling in BlockDownloaderService (#974) - BlockDownloaderService errors updated [#924] Update error handling in BlockDownloader (#973) - BlockDownloaderStream nextBlock updated [#942] Update error handling in TransactionEntity (#977) - ZcashTransaction init errors converted to the ZcashError [#939] Update error handling in TransactionDao (#976) - TransactionRepositoryError removed and replaced with ZcashError - all TransactionDAO errors converted to ZcashError [#943] Update error handling in ZcashCompactBlock Closes #943 [#945] Update error handling in Memo Closes #945 [#934] Update error handling in Checkpoint Closes #944 Closes #934 [#938] Update error handling in PendingTransactionDao Closes #938 [#926] Update error handling in BlockEnhancer - WIP, switching to transaction repository to unblock this ticket [#926] Update error handling in BlockEnhancer - enhancer's errors done [#926] Update error handling in BlockEnhancer (#994) - cleanup [#952] Update error handling in DerivationTool Closes #952 [#932] Update error handling in BlockValidator Closes #932 [#940] Update error handling in UnspentTransactionOutputDao Closes #940 [#946] Update error handling in WalletTypes Closes #946 [#954] Update error handling in WalletTransactionEncoder Closes #954 [#953] Update error handling in PersistentTransactionManager Closes #953 [#956] Update error handling in Initializer Closes #956 [#947] Update error handling in Zatoshi (#996) - Zatoshi's errors converted to ZcashError [#927] Update error handling in UTXOFetcher (#997) - UTXOFetcher resolved Use let instead of var where applicable In the SDK `var` was used on places where `let` would be sufficient. And default strategy in Swift should use use `let` until mutability is required. So all these places are changed. No logic is changed. [#933] Update error handling in CompactBlockProcessor - CompactBlockProcessor's errors refactored to ZcashError [#933] Update error handling in CompactBlockProcessor #999 - comments addressed [#951] Update error handling in SDKSynchronizer - SDKSynchronizer's errors refactored to ZcashError [#951] Update error handling in SDKSynchronizer (#1002) - comments resolved Make DerivationTool constructor public DerivationTool.init should be public. This was removed by accident when adopting async. [#361] Add changelog
2023-04-24 14:15:20 -07:00
logger.error("Block validation failed with error: \(error)")
throw error
}
// Without this `stop()` would work. But this line improves support for Task cancelation.
try Task.checkCancellation()
do {
lastScannedHeight = try await blockScanner.scanBlocks(
at: processingRange,
totalProgressRange: totalProgressRange
) { [weak self] lastScannedHeight in
let progress = BlockProgress(
startHeight: totalProgressRange.lowerBound,
targetHeight: totalProgressRange.upperBound,
progressHeight: lastScannedHeight
)
await self?.notifyProgress(.syncing(progress))
}
} catch {
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
logger.error("Scanning failed with error: \(error)")
await ifTaskIsNotCanceledClearCompactBlockCache(lastScannedHeight: lastScannedHeight)
throw error
}
try await clearCompactBlockCache(upTo: lastScannedHeight)
let progress = BlockProgress(
startHeight: totalProgressRange.lowerBound,
targetHeight: totalProgressRange.upperBound,
progressHeight: processingRange.upperBound
)
[#831] Add SDKSynchronizer wrappers for non-async API This change introduces two new protocols: `ClosureSynchronizer` and `CombineSynchronizer`. These two protocols define API that doesn't use `async`. So the client can choose exactly which API it wants to use. This change also introduces two new objects: `ClosureSDKSynchronizer` and `CombineSDKSynchronizer`. These two implement the respective protocols mentioned above. Both are structures. Neither of these two keeps any state. Thanks to this each is very cheap to create. And usage of these two isn't mutually exclusive. So devs can really choose the best SDK API for each part of the client app. [#831] Use async inside of the SDKSynchronizer - In general lot of methods inside the `SDKSynchronizer` and `CompactBlockProcessoer` which weren't async are now async. And other changes are made because of this change. - `CompactBlockProcessor` no longer uses Combine to communicate with `SDKSynchronizer`. Reason for this is that Combine doesn't play great with async. Closure passed to `sink` isn't async. - Because of this and because of how our tests work (receiving signals from CBP directly) `CompactBlockProcessor` must be able to handle more event closures. Not just one. So it now has `eventClosures` dictionary. It's little bit strange but it works fine. - `SyncStatus` inside the `SDKSynchronizer` was previously protected by lock. Now it's protected by simple actor wrapper. - Changes in tests are minimal. Changes were mady only because `CompactBlockProcessor` changes from Combine to closures. [#831] Add tests for ClosureSDKSynchronizer - Added tests are testing in general if the `ClosuresSDKSynchronizer` is correctly calling `Synchronizer` and if the values are correctly returned. - `ClosuresSDKSynchronizer` doesn't contain any logic but it is public API and we should be sure that it works correctly. [#831] Add tests for CombineSDKSynchronizer [#831] Add changelog
2023-03-16 02:11:18 -07:00
await notifyProgress(.syncing(progress))
}
}
/*
Here range for one batch is computed. For example if we want to sync blocks 0...1000 with batchSize 100 we want to generage blocks like
this:
0...99
100...199
200...299
300...399
...
900...999
1000...1000
*/
func computeSingleLoopDownloadRange(fullRange: CompactBlockRange, loopCounter: Int, batchSize: BlockHeight) -> CompactBlockRange {
let lowerBound = fullRange.lowerBound + (loopCounter * batchSize)
let upperBound = min(fullRange.lowerBound + ((loopCounter + 1) * batchSize) - 1, fullRange.upperBound)
return lowerBound...upperBound
}
/// It may happen that sync process start with syncing blocks that were downloaded but not synced in previous run of the sync process. This
/// methods analyses what must be done and computes range that should be used to compute reported progress.
private func computeTotalProgressRange(from syncRanges: SyncRanges) -> CompactBlockRange {
guard syncRanges.downloadedButUnscannedRange != nil || syncRanges.downloadAndScanRange != nil else {
// In this case we are sure that no downloading or scanning happens so this returned range won't be even used. And it's easier to return
// this "fake" range than to handle nil.
return 0...0
}
// Thanks to guard above we can be sure that one of these two ranges is not nil.
let lowerBound = syncRanges.downloadedButUnscannedRange?.lowerBound ?? syncRanges.downloadAndScanRange?.lowerBound ?? 0
let upperBound = syncRanges.downloadAndScanRange?.upperBound ?? syncRanges.downloadedButUnscannedRange?.upperBound ?? 0
return lowerBound...upperBound
}
[#831] Add SDKSynchronizer wrappers for non-async API This change introduces two new protocols: `ClosureSynchronizer` and `CombineSynchronizer`. These two protocols define API that doesn't use `async`. So the client can choose exactly which API it wants to use. This change also introduces two new objects: `ClosureSDKSynchronizer` and `CombineSDKSynchronizer`. These two implement the respective protocols mentioned above. Both are structures. Neither of these two keeps any state. Thanks to this each is very cheap to create. And usage of these two isn't mutually exclusive. So devs can really choose the best SDK API for each part of the client app. [#831] Use async inside of the SDKSynchronizer - In general lot of methods inside the `SDKSynchronizer` and `CompactBlockProcessoer` which weren't async are now async. And other changes are made because of this change. - `CompactBlockProcessor` no longer uses Combine to communicate with `SDKSynchronizer`. Reason for this is that Combine doesn't play great with async. Closure passed to `sink` isn't async. - Because of this and because of how our tests work (receiving signals from CBP directly) `CompactBlockProcessor` must be able to handle more event closures. Not just one. So it now has `eventClosures` dictionary. It's little bit strange but it works fine. - `SyncStatus` inside the `SDKSynchronizer` was previously protected by lock. Now it's protected by simple actor wrapper. - Changes in tests are minimal. Changes were mady only because `CompactBlockProcessor` changes from Combine to closures. [#831] Add tests for ClosureSDKSynchronizer - Added tests are testing in general if the `ClosuresSDKSynchronizer` is correctly calling `Synchronizer` and if the values are correctly returned. - `ClosuresSDKSynchronizer` doesn't contain any logic but it is public API and we should be sure that it works correctly. [#831] Add tests for CombineSDKSynchronizer [#831] Add changelog
2023-03-16 02:11:18 -07:00
func notifyProgress(_ progress: CompactBlockProgress) async {
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
logger.debug("progress: \(progress)")
[#831] Add SDKSynchronizer wrappers for non-async API This change introduces two new protocols: `ClosureSynchronizer` and `CombineSynchronizer`. These two protocols define API that doesn't use `async`. So the client can choose exactly which API it wants to use. This change also introduces two new objects: `ClosureSDKSynchronizer` and `CombineSDKSynchronizer`. These two implement the respective protocols mentioned above. Both are structures. Neither of these two keeps any state. Thanks to this each is very cheap to create. And usage of these two isn't mutually exclusive. So devs can really choose the best SDK API for each part of the client app. [#831] Use async inside of the SDKSynchronizer - In general lot of methods inside the `SDKSynchronizer` and `CompactBlockProcessoer` which weren't async are now async. And other changes are made because of this change. - `CompactBlockProcessor` no longer uses Combine to communicate with `SDKSynchronizer`. Reason for this is that Combine doesn't play great with async. Closure passed to `sink` isn't async. - Because of this and because of how our tests work (receiving signals from CBP directly) `CompactBlockProcessor` must be able to handle more event closures. Not just one. So it now has `eventClosures` dictionary. It's little bit strange but it works fine. - `SyncStatus` inside the `SDKSynchronizer` was previously protected by lock. Now it's protected by simple actor wrapper. - Changes in tests are minimal. Changes were mady only because `CompactBlockProcessor` changes from Combine to closures. [#831] Add tests for ClosureSDKSynchronizer - Added tests are testing in general if the `ClosuresSDKSynchronizer` is correctly calling `Synchronizer` and if the values are correctly returned. - `ClosuresSDKSynchronizer` doesn't contain any logic but it is public API and we should be sure that it works correctly. [#831] Add tests for CombineSDKSynchronizer [#831] Add changelog
2023-03-16 02:11:18 -07:00
await send(event: .progressUpdated(progress))
}
[#831] Add SDKSynchronizer wrappers for non-async API This change introduces two new protocols: `ClosureSynchronizer` and `CombineSynchronizer`. These two protocols define API that doesn't use `async`. So the client can choose exactly which API it wants to use. This change also introduces two new objects: `ClosureSDKSynchronizer` and `CombineSDKSynchronizer`. These two implement the respective protocols mentioned above. Both are structures. Neither of these two keeps any state. Thanks to this each is very cheap to create. And usage of these two isn't mutually exclusive. So devs can really choose the best SDK API for each part of the client app. [#831] Use async inside of the SDKSynchronizer - In general lot of methods inside the `SDKSynchronizer` and `CompactBlockProcessoer` which weren't async are now async. And other changes are made because of this change. - `CompactBlockProcessor` no longer uses Combine to communicate with `SDKSynchronizer`. Reason for this is that Combine doesn't play great with async. Closure passed to `sink` isn't async. - Because of this and because of how our tests work (receiving signals from CBP directly) `CompactBlockProcessor` must be able to handle more event closures. Not just one. So it now has `eventClosures` dictionary. It's little bit strange but it works fine. - `SyncStatus` inside the `SDKSynchronizer` was previously protected by lock. Now it's protected by simple actor wrapper. - Changes in tests are minimal. Changes were mady only because `CompactBlockProcessor` changes from Combine to closures. [#831] Add tests for ClosureSDKSynchronizer - Added tests are testing in general if the `ClosuresSDKSynchronizer` is correctly calling `Synchronizer` and if the values are correctly returned. - `ClosuresSDKSynchronizer` doesn't contain any logic but it is public API and we should be sure that it works correctly. [#831] Add tests for CombineSDKSynchronizer [#831] Add changelog
2023-03-16 02:11:18 -07:00
func notifyTransactions(_ txs: [ZcashTransaction.Overview], in range: CompactBlockRange) async {
await send(event: .foundTransactions(txs, range))
}
2021-09-17 06:49:58 -07:00
func determineLowerBound(
errorHeight: Int,
consecutiveErrors: Int,
walletBirthday: BlockHeight
) -> BlockHeight {
let offset = min(ZcashSDK.maxReorgSize, ZcashSDK.defaultRewindDistance * (consecutiveErrors + 1))
return max(errorHeight - offset, walletBirthday - ZcashSDK.maxReorgSize)
}
[#831] Add SDKSynchronizer wrappers for non-async API This change introduces two new protocols: `ClosureSynchronizer` and `CombineSynchronizer`. These two protocols define API that doesn't use `async`. So the client can choose exactly which API it wants to use. This change also introduces two new objects: `ClosureSDKSynchronizer` and `CombineSDKSynchronizer`. These two implement the respective protocols mentioned above. Both are structures. Neither of these two keeps any state. Thanks to this each is very cheap to create. And usage of these two isn't mutually exclusive. So devs can really choose the best SDK API for each part of the client app. [#831] Use async inside of the SDKSynchronizer - In general lot of methods inside the `SDKSynchronizer` and `CompactBlockProcessoer` which weren't async are now async. And other changes are made because of this change. - `CompactBlockProcessor` no longer uses Combine to communicate with `SDKSynchronizer`. Reason for this is that Combine doesn't play great with async. Closure passed to `sink` isn't async. - Because of this and because of how our tests work (receiving signals from CBP directly) `CompactBlockProcessor` must be able to handle more event closures. Not just one. So it now has `eventClosures` dictionary. It's little bit strange but it works fine. - `SyncStatus` inside the `SDKSynchronizer` was previously protected by lock. Now it's protected by simple actor wrapper. - Changes in tests are minimal. Changes were mady only because `CompactBlockProcessor` changes from Combine to closures. [#831] Add tests for ClosureSDKSynchronizer - Added tests are testing in general if the `ClosuresSDKSynchronizer` is correctly calling `Synchronizer` and if the values are correctly returned. - `ClosuresSDKSynchronizer` doesn't contain any logic but it is public API and we should be sure that it works correctly. [#831] Add tests for CombineSDKSynchronizer [#831] Add changelog
2023-03-16 02:11:18 -07:00
func severeFailure(_ error: Error) async {
[476] CompactBlockProcessor to async/await - getting rid of the Operation Queue - the cleanup is needed - the update of tests is needed - tested and it successfully finishes the sync process [476] CompactBlockProcessor to async/await - old processNewBlocks() removed [476] CompactBlockProcessor to async/await - unused operations removed [476] CompactBlockProcessor to async/await - unit tests update [476] CompactBlockProcessor to async/await - unit tests refactored [476] CompactBlockProcessor to async/await - cleanup of deprecated method [476] CompactBlockProcessor to async/await - fail(error) was called even for canceled tasks but that must be excluded [476] CompactBlockProcessor to async/await - removal of all ZcashOperations from the code (unit test will follow) [476] CompactBlockProcessor to async/await - network tests in building and success order again [476] CompactBlockProcessor to async/await - offline tests in building and success order [476] CompactBlockProcessor to async/await (519) - cleanup of suspending the task [476] CompactBlockProcessor to async/await (519) - most comments resolved [476] CompactBlockProcessor to async/await (519) - thread safe state for both sync and async context [476] CompactBlockProcessor to async/await (519) - fixed build for a sample project [476] CompactBlockProcessor to async/await (519) - func testStartNotifiesSuscriptors() reverted [476] CompactBlockProcessor to async/await (519) - TODO added to track why we used NSLock instead of an Actor - Task priority enhanced [476] CompactBlockProcessor to async/await (519) - cleanup in Tasks and priorities
2022-09-01 05:58:41 -07:00
cancelableTask?.cancel()
await blockDownloader.stopDownload()
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
logger.error("show stopper failure: \(error)")
2021-09-17 06:49:58 -07:00
self.backoffTimer?.invalidate()
self.retryAttempts = config.retries
self.processingError = error
[#831] Add SDKSynchronizer wrappers for non-async API This change introduces two new protocols: `ClosureSynchronizer` and `CombineSynchronizer`. These two protocols define API that doesn't use `async`. So the client can choose exactly which API it wants to use. This change also introduces two new objects: `ClosureSDKSynchronizer` and `CombineSDKSynchronizer`. These two implement the respective protocols mentioned above. Both are structures. Neither of these two keeps any state. Thanks to this each is very cheap to create. And usage of these two isn't mutually exclusive. So devs can really choose the best SDK API for each part of the client app. [#831] Use async inside of the SDKSynchronizer - In general lot of methods inside the `SDKSynchronizer` and `CompactBlockProcessoer` which weren't async are now async. And other changes are made because of this change. - `CompactBlockProcessor` no longer uses Combine to communicate with `SDKSynchronizer`. Reason for this is that Combine doesn't play great with async. Closure passed to `sink` isn't async. - Because of this and because of how our tests work (receiving signals from CBP directly) `CompactBlockProcessor` must be able to handle more event closures. Not just one. So it now has `eventClosures` dictionary. It's little bit strange but it works fine. - `SyncStatus` inside the `SDKSynchronizer` was previously protected by lock. Now it's protected by simple actor wrapper. - Changes in tests are minimal. Changes were mady only because `CompactBlockProcessor` changes from Combine to closures. [#831] Add tests for ClosureSDKSynchronizer - Added tests are testing in general if the `ClosuresSDKSynchronizer` is correctly calling `Synchronizer` and if the values are correctly returned. - `ClosuresSDKSynchronizer` doesn't contain any logic but it is public API and we should be sure that it works correctly. [#831] Add tests for CombineSDKSynchronizer [#831] Add changelog
2023-03-16 02:11:18 -07:00
await updateState(.error(error))
await self.notifyError(error)
2021-09-17 06:49:58 -07:00
}
func fail(_ error: Error) async {
// TODO: [#713] specify: failure. https://github.com/zcash/ZcashLightClientKit/issues/713
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
logger.error("\(error)")
[476] CompactBlockProcessor to async/await - getting rid of the Operation Queue - the cleanup is needed - the update of tests is needed - tested and it successfully finishes the sync process [476] CompactBlockProcessor to async/await - old processNewBlocks() removed [476] CompactBlockProcessor to async/await - unused operations removed [476] CompactBlockProcessor to async/await - unit tests update [476] CompactBlockProcessor to async/await - unit tests refactored [476] CompactBlockProcessor to async/await - cleanup of deprecated method [476] CompactBlockProcessor to async/await - fail(error) was called even for canceled tasks but that must be excluded [476] CompactBlockProcessor to async/await - removal of all ZcashOperations from the code (unit test will follow) [476] CompactBlockProcessor to async/await - network tests in building and success order again [476] CompactBlockProcessor to async/await - offline tests in building and success order [476] CompactBlockProcessor to async/await (519) - cleanup of suspending the task [476] CompactBlockProcessor to async/await (519) - most comments resolved [476] CompactBlockProcessor to async/await (519) - thread safe state for both sync and async context [476] CompactBlockProcessor to async/await (519) - fixed build for a sample project [476] CompactBlockProcessor to async/await (519) - func testStartNotifiesSuscriptors() reverted [476] CompactBlockProcessor to async/await (519) - TODO added to track why we used NSLock instead of an Actor - Task priority enhanced [476] CompactBlockProcessor to async/await (519) - cleanup in Tasks and priorities
2022-09-01 05:58:41 -07:00
cancelableTask?.cancel()
await blockDownloader.stopDownload()
2021-09-17 06:49:58 -07:00
self.retryAttempts += 1
self.processingError = error
switch self.state {
2021-09-17 06:49:58 -07:00
case .error:
[#831] Add SDKSynchronizer wrappers for non-async API This change introduces two new protocols: `ClosureSynchronizer` and `CombineSynchronizer`. These two protocols define API that doesn't use `async`. So the client can choose exactly which API it wants to use. This change also introduces two new objects: `ClosureSDKSynchronizer` and `CombineSDKSynchronizer`. These two implement the respective protocols mentioned above. Both are structures. Neither of these two keeps any state. Thanks to this each is very cheap to create. And usage of these two isn't mutually exclusive. So devs can really choose the best SDK API for each part of the client app. [#831] Use async inside of the SDKSynchronizer - In general lot of methods inside the `SDKSynchronizer` and `CompactBlockProcessoer` which weren't async are now async. And other changes are made because of this change. - `CompactBlockProcessor` no longer uses Combine to communicate with `SDKSynchronizer`. Reason for this is that Combine doesn't play great with async. Closure passed to `sink` isn't async. - Because of this and because of how our tests work (receiving signals from CBP directly) `CompactBlockProcessor` must be able to handle more event closures. Not just one. So it now has `eventClosures` dictionary. It's little bit strange but it works fine. - `SyncStatus` inside the `SDKSynchronizer` was previously protected by lock. Now it's protected by simple actor wrapper. - Changes in tests are minimal. Changes were mady only because `CompactBlockProcessor` changes from Combine to closures. [#831] Add tests for ClosureSDKSynchronizer - Added tests are testing in general if the `ClosuresSDKSynchronizer` is correctly calling `Synchronizer` and if the values are correctly returned. - `ClosuresSDKSynchronizer` doesn't contain any logic but it is public API and we should be sure that it works correctly. [#831] Add tests for CombineSDKSynchronizer [#831] Add changelog
2023-03-16 02:11:18 -07:00
await notifyError(error)
2021-09-17 06:49:58 -07:00
default:
break
}
[#831] Add SDKSynchronizer wrappers for non-async API This change introduces two new protocols: `ClosureSynchronizer` and `CombineSynchronizer`. These two protocols define API that doesn't use `async`. So the client can choose exactly which API it wants to use. This change also introduces two new objects: `ClosureSDKSynchronizer` and `CombineSDKSynchronizer`. These two implement the respective protocols mentioned above. Both are structures. Neither of these two keeps any state. Thanks to this each is very cheap to create. And usage of these two isn't mutually exclusive. So devs can really choose the best SDK API for each part of the client app. [#831] Use async inside of the SDKSynchronizer - In general lot of methods inside the `SDKSynchronizer` and `CompactBlockProcessoer` which weren't async are now async. And other changes are made because of this change. - `CompactBlockProcessor` no longer uses Combine to communicate with `SDKSynchronizer`. Reason for this is that Combine doesn't play great with async. Closure passed to `sink` isn't async. - Because of this and because of how our tests work (receiving signals from CBP directly) `CompactBlockProcessor` must be able to handle more event closures. Not just one. So it now has `eventClosures` dictionary. It's little bit strange but it works fine. - `SyncStatus` inside the `SDKSynchronizer` was previously protected by lock. Now it's protected by simple actor wrapper. - Changes in tests are minimal. Changes were mady only because `CompactBlockProcessor` changes from Combine to closures. [#831] Add tests for ClosureSDKSynchronizer - Added tests are testing in general if the `ClosuresSDKSynchronizer` is correctly calling `Synchronizer` and if the values are correctly returned. - `ClosuresSDKSynchronizer` doesn't contain any logic but it is public API and we should be sure that it works correctly. [#831] Add tests for CombineSDKSynchronizer [#831] Add changelog
2023-03-16 02:11:18 -07:00
await updateState(.error(error))
2021-09-17 06:49:58 -07:00
guard self.maxAttemptsReached else { return }
// don't set a new timer if there are no more attempts.
await self.setTimer()
2021-09-17 06:49:58 -07:00
}
private func validateConfiguration() throws {
- [#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
guard FileManager.default.isReadableFile(atPath: config.fsBlockCacheRoot.absoluteString) else {
[#361] Introduce ZcashError (#1005) This PR introduces `ZcashError` enum. This enum represents any error that can be thrown inside of the SDK and outside of the SDK. Also `ZcashError` is used in `LightWalletGRPCService` and handled in `CompactBlockProcessor` as example. Why enum? First I tried this with some structure which contained code, message and underlyingError. Problem was when some specific place in the SDK would like to attach some additional data to error. I didn't want to add some generic dictionary to store anything with the error. So I used enum to identify error. Each member can have specified amount of associated values. So specific error can bring some context data. And it's type safe. Each error has also a code. Relationship between errors and codes is 1:1. It may looks bit redundant but it's important. The client app now can choose how to process errors. Either identify those by the error itself or by code. Definition or errors and codes is in `ZcashErrorDefinition`. And then `ZcashError` and `ZcashErrorCode` are generated by Sourcery. Thanks to this it is easier to maintain the final code. And it gives us ability to generate any kind of documentation for the errors and codes. I created simple example of this in this PR. And it doesn't make the SDK completely dependent on the Sourcery. Final structures aren't super complicated and can be written manually if needed. [#923] Update error handling in DatabaseStorageManager.swift - cleanup of DatabaseStorageManager, not used anymore - ZcashError for SimpleConnectionProvider Revert "[#923] Update error handling in DatabaseStorageManager.swift" This reverts commit 94e028d31a0f6635800c297eb741db74c6a6ff45. Fix script which generates ZcashError [#922] Update error handling in DatabaseMigrationManager.swift Closes #922 [#923] Update error handling in DatabaseStorageManager.swift - The DatabaseStorageManager is not used so I deleted it - SimpleConnectionProvider's errors updated Fix tests [#955] Update error handling in SaplingParameterDownloader Closes #955 [#936] Update error handling in NotesDao Closes #936 [#935] Update error handling in BlockDao Closes #935 [#931] InternalSyncProgress.computeNextState doesn't need to throw Closes #931 [#950] Update error handling in rust backend Closes #949 Closes #950 [#941] Update error handling in AccountEntity Closes #941 [#928] Update error handling in FSCompactBlockRepository Closes #928 [#925] Update error handling in BlockDownloaderService (#974) - BlockDownloaderService errors updated [#924] Update error handling in BlockDownloader (#973) - BlockDownloaderStream nextBlock updated [#942] Update error handling in TransactionEntity (#977) - ZcashTransaction init errors converted to the ZcashError [#939] Update error handling in TransactionDao (#976) - TransactionRepositoryError removed and replaced with ZcashError - all TransactionDAO errors converted to ZcashError [#943] Update error handling in ZcashCompactBlock Closes #943 [#945] Update error handling in Memo Closes #945 [#934] Update error handling in Checkpoint Closes #944 Closes #934 [#938] Update error handling in PendingTransactionDao Closes #938 [#926] Update error handling in BlockEnhancer - WIP, switching to transaction repository to unblock this ticket [#926] Update error handling in BlockEnhancer - enhancer's errors done [#926] Update error handling in BlockEnhancer (#994) - cleanup [#952] Update error handling in DerivationTool Closes #952 [#932] Update error handling in BlockValidator Closes #932 [#940] Update error handling in UnspentTransactionOutputDao Closes #940 [#946] Update error handling in WalletTypes Closes #946 [#954] Update error handling in WalletTransactionEncoder Closes #954 [#953] Update error handling in PersistentTransactionManager Closes #953 [#956] Update error handling in Initializer Closes #956 [#947] Update error handling in Zatoshi (#996) - Zatoshi's errors converted to ZcashError [#927] Update error handling in UTXOFetcher (#997) - UTXOFetcher resolved Use let instead of var where applicable In the SDK `var` was used on places where `let` would be sufficient. And default strategy in Swift should use use `let` until mutability is required. So all these places are changed. No logic is changed. [#933] Update error handling in CompactBlockProcessor - CompactBlockProcessor's errors refactored to ZcashError [#933] Update error handling in CompactBlockProcessor #999 - comments addressed [#951] Update error handling in SDKSynchronizer - SDKSynchronizer's errors refactored to ZcashError [#951] Update error handling in SDKSynchronizer (#1002) - comments resolved Make DerivationTool constructor public DerivationTool.init should be public. This was removed by accident when adopting async. [#361] Add changelog
2023-04-24 14:15:20 -07:00
throw ZcashError.compactBlockProcessorMissingDbPath(config.fsBlockCacheRoot.absoluteString)
2021-09-17 06:49:58 -07:00
}
guard FileManager.default.isReadableFile(atPath: config.dataDb.absoluteString) else {
[#361] Introduce ZcashError (#1005) This PR introduces `ZcashError` enum. This enum represents any error that can be thrown inside of the SDK and outside of the SDK. Also `ZcashError` is used in `LightWalletGRPCService` and handled in `CompactBlockProcessor` as example. Why enum? First I tried this with some structure which contained code, message and underlyingError. Problem was when some specific place in the SDK would like to attach some additional data to error. I didn't want to add some generic dictionary to store anything with the error. So I used enum to identify error. Each member can have specified amount of associated values. So specific error can bring some context data. And it's type safe. Each error has also a code. Relationship between errors and codes is 1:1. It may looks bit redundant but it's important. The client app now can choose how to process errors. Either identify those by the error itself or by code. Definition or errors and codes is in `ZcashErrorDefinition`. And then `ZcashError` and `ZcashErrorCode` are generated by Sourcery. Thanks to this it is easier to maintain the final code. And it gives us ability to generate any kind of documentation for the errors and codes. I created simple example of this in this PR. And it doesn't make the SDK completely dependent on the Sourcery. Final structures aren't super complicated and can be written manually if needed. [#923] Update error handling in DatabaseStorageManager.swift - cleanup of DatabaseStorageManager, not used anymore - ZcashError for SimpleConnectionProvider Revert "[#923] Update error handling in DatabaseStorageManager.swift" This reverts commit 94e028d31a0f6635800c297eb741db74c6a6ff45. Fix script which generates ZcashError [#922] Update error handling in DatabaseMigrationManager.swift Closes #922 [#923] Update error handling in DatabaseStorageManager.swift - The DatabaseStorageManager is not used so I deleted it - SimpleConnectionProvider's errors updated Fix tests [#955] Update error handling in SaplingParameterDownloader Closes #955 [#936] Update error handling in NotesDao Closes #936 [#935] Update error handling in BlockDao Closes #935 [#931] InternalSyncProgress.computeNextState doesn't need to throw Closes #931 [#950] Update error handling in rust backend Closes #949 Closes #950 [#941] Update error handling in AccountEntity Closes #941 [#928] Update error handling in FSCompactBlockRepository Closes #928 [#925] Update error handling in BlockDownloaderService (#974) - BlockDownloaderService errors updated [#924] Update error handling in BlockDownloader (#973) - BlockDownloaderStream nextBlock updated [#942] Update error handling in TransactionEntity (#977) - ZcashTransaction init errors converted to the ZcashError [#939] Update error handling in TransactionDao (#976) - TransactionRepositoryError removed and replaced with ZcashError - all TransactionDAO errors converted to ZcashError [#943] Update error handling in ZcashCompactBlock Closes #943 [#945] Update error handling in Memo Closes #945 [#934] Update error handling in Checkpoint Closes #944 Closes #934 [#938] Update error handling in PendingTransactionDao Closes #938 [#926] Update error handling in BlockEnhancer - WIP, switching to transaction repository to unblock this ticket [#926] Update error handling in BlockEnhancer - enhancer's errors done [#926] Update error handling in BlockEnhancer (#994) - cleanup [#952] Update error handling in DerivationTool Closes #952 [#932] Update error handling in BlockValidator Closes #932 [#940] Update error handling in UnspentTransactionOutputDao Closes #940 [#946] Update error handling in WalletTypes Closes #946 [#954] Update error handling in WalletTransactionEncoder Closes #954 [#953] Update error handling in PersistentTransactionManager Closes #953 [#956] Update error handling in Initializer Closes #956 [#947] Update error handling in Zatoshi (#996) - Zatoshi's errors converted to ZcashError [#927] Update error handling in UTXOFetcher (#997) - UTXOFetcher resolved Use let instead of var where applicable In the SDK `var` was used on places where `let` would be sufficient. And default strategy in Swift should use use `let` until mutability is required. So all these places are changed. No logic is changed. [#933] Update error handling in CompactBlockProcessor - CompactBlockProcessor's errors refactored to ZcashError [#933] Update error handling in CompactBlockProcessor #999 - comments addressed [#951] Update error handling in SDKSynchronizer - SDKSynchronizer's errors refactored to ZcashError [#951] Update error handling in SDKSynchronizer (#1002) - comments resolved Make DerivationTool constructor public DerivationTool.init should be public. This was removed by accident when adopting async. [#361] Add changelog
2023-04-24 14:15:20 -07:00
throw ZcashError.compactBlockProcessorMissingDbPath(config.dataDb.absoluteString)
2021-09-17 06:49:58 -07:00
}
}
private func nextBatch() async {
[#831] Add SDKSynchronizer wrappers for non-async API This change introduces two new protocols: `ClosureSynchronizer` and `CombineSynchronizer`. These two protocols define API that doesn't use `async`. So the client can choose exactly which API it wants to use. This change also introduces two new objects: `ClosureSDKSynchronizer` and `CombineSDKSynchronizer`. These two implement the respective protocols mentioned above. Both are structures. Neither of these two keeps any state. Thanks to this each is very cheap to create. And usage of these two isn't mutually exclusive. So devs can really choose the best SDK API for each part of the client app. [#831] Use async inside of the SDKSynchronizer - In general lot of methods inside the `SDKSynchronizer` and `CompactBlockProcessoer` which weren't async are now async. And other changes are made because of this change. - `CompactBlockProcessor` no longer uses Combine to communicate with `SDKSynchronizer`. Reason for this is that Combine doesn't play great with async. Closure passed to `sink` isn't async. - Because of this and because of how our tests work (receiving signals from CBP directly) `CompactBlockProcessor` must be able to handle more event closures. Not just one. So it now has `eventClosures` dictionary. It's little bit strange but it works fine. - `SyncStatus` inside the `SDKSynchronizer` was previously protected by lock. Now it's protected by simple actor wrapper. - Changes in tests are minimal. Changes were mady only because `CompactBlockProcessor` changes from Combine to closures. [#831] Add tests for ClosureSDKSynchronizer - Added tests are testing in general if the `ClosuresSDKSynchronizer` is correctly calling `Synchronizer` and if the values are correctly returned. - `ClosuresSDKSynchronizer` doesn't contain any logic but it is public API and we should be sure that it works correctly. [#831] Add tests for CombineSDKSynchronizer [#831] Add changelog
2023-03-16 02:11:18 -07:00
await updateState(.syncing)
if backoffTimer == nil { await setTimer() }
do {
let nextState = try await NextStateHelper.nextState(
service: self.service,
downloaderService: blockDownloaderService,
latestBlocksDataProvider: latestBlocksDataProvider,
config: self.config,
rustBackend: self.rustBackend,
internalSyncProgress: internalSyncProgress
)
switch nextState {
case .finishProcessing(let height):
await self.processingFinished(height: height)
case .processNewBlocks(let ranges):
await self.processNewBlocks(ranges: ranges)
case let .wait(latestHeight, latestDownloadHeight):
// Lightwalletd might be syncing
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
logger.info(
"Lightwalletd might be syncing: latest downloaded block height is: \(latestDownloadHeight) " +
"while latest blockheight is reported at: \(latestHeight)"
)
await self.processingFinished(height: latestDownloadHeight)
}
} catch {
[#831] Add SDKSynchronizer wrappers for non-async API This change introduces two new protocols: `ClosureSynchronizer` and `CombineSynchronizer`. These two protocols define API that doesn't use `async`. So the client can choose exactly which API it wants to use. This change also introduces two new objects: `ClosureSDKSynchronizer` and `CombineSDKSynchronizer`. These two implement the respective protocols mentioned above. Both are structures. Neither of these two keeps any state. Thanks to this each is very cheap to create. And usage of these two isn't mutually exclusive. So devs can really choose the best SDK API for each part of the client app. [#831] Use async inside of the SDKSynchronizer - In general lot of methods inside the `SDKSynchronizer` and `CompactBlockProcessoer` which weren't async are now async. And other changes are made because of this change. - `CompactBlockProcessor` no longer uses Combine to communicate with `SDKSynchronizer`. Reason for this is that Combine doesn't play great with async. Closure passed to `sink` isn't async. - Because of this and because of how our tests work (receiving signals from CBP directly) `CompactBlockProcessor` must be able to handle more event closures. Not just one. So it now has `eventClosures` dictionary. It's little bit strange but it works fine. - `SyncStatus` inside the `SDKSynchronizer` was previously protected by lock. Now it's protected by simple actor wrapper. - Changes in tests are minimal. Changes were mady only because `CompactBlockProcessor` changes from Combine to closures. [#831] Add tests for ClosureSDKSynchronizer - Added tests are testing in general if the `ClosuresSDKSynchronizer` is correctly calling `Synchronizer` and if the values are correctly returned. - `ClosuresSDKSynchronizer` doesn't contain any logic but it is public API and we should be sure that it works correctly. [#831] Add tests for CombineSDKSynchronizer [#831] Add changelog
2023-03-16 02:11:18 -07:00
await self.severeFailure(error)
}
}
2021-09-17 06:49:58 -07:00
internal func validationFailed(at height: BlockHeight) async {
// cancel all Tasks
[476] CompactBlockProcessor to async/await - getting rid of the Operation Queue - the cleanup is needed - the update of tests is needed - tested and it successfully finishes the sync process [476] CompactBlockProcessor to async/await - old processNewBlocks() removed [476] CompactBlockProcessor to async/await - unused operations removed [476] CompactBlockProcessor to async/await - unit tests update [476] CompactBlockProcessor to async/await - unit tests refactored [476] CompactBlockProcessor to async/await - cleanup of deprecated method [476] CompactBlockProcessor to async/await - fail(error) was called even for canceled tasks but that must be excluded [476] CompactBlockProcessor to async/await - removal of all ZcashOperations from the code (unit test will follow) [476] CompactBlockProcessor to async/await - network tests in building and success order again [476] CompactBlockProcessor to async/await - offline tests in building and success order [476] CompactBlockProcessor to async/await (519) - cleanup of suspending the task [476] CompactBlockProcessor to async/await (519) - most comments resolved [476] CompactBlockProcessor to async/await (519) - thread safe state for both sync and async context [476] CompactBlockProcessor to async/await (519) - fixed build for a sample project [476] CompactBlockProcessor to async/await (519) - func testStartNotifiesSuscriptors() reverted [476] CompactBlockProcessor to async/await (519) - TODO added to track why we used NSLock instead of an Actor - Task priority enhanced [476] CompactBlockProcessor to async/await (519) - cleanup in Tasks and priorities
2022-09-01 05:58:41 -07:00
cancelableTask?.cancel()
await blockDownloader.stopDownload()
2020-12-05 10:11:29 -08:00
// register latest failure
self.lastChainValidationFailure = height
// rewind
2021-09-15 05:21:29 -07:00
let rewindHeight = determineLowerBound(
2021-09-17 06:49:58 -07:00
errorHeight: height,
consecutiveErrors: consecutiveChainValidationErrors,
walletBirthday: self.config.walletBirthday
)
self.consecutiveChainValidationErrors += 1
[#888] Make actor from ZcashRustBackendWelding Closes #888. - `ZcashRustBackend` is actor now. So majority of methods in this actor are now async. - Some methods stayed `static` in `ZcashRustBackend`. It would be hard to pass instance of the `ZcashRustBackend` to the places where these methods are used in static manner. And it would change lot of APIs. But it isn't problem from technical perspective because these methods would be `nonisolated` otherwise. - Methods `lastError()` and `getLastError()` in `ZcashRustBackend` are now private. This makes sure that ther won't be aby race condition between other methods and these two error methods. - All the methods for which was `lastError()` used in code now throw error. So `lastError()` is no longer needed outside of the `ZcashRustBackend`. - There are in the public API related to `DerivationTool`. - `DerivationTool` now requires instance of the `ZcashRustBackend`. And `ZcashRustBackend` isn't public type. So `DerivationTool` doesn't have any public constructor now. It can be created only via `Initializer.makeDerivationTool()` instance method. - `deriveUnifiedSpendingKey()` and `deriveUnifiedFullViewingKey()` in `DerivationTool` are now async. It is because these are using `ZcashRustBackend` inside. `DerivationTool` offers alternative (closure and combine) APIs. But downside is that there is no sync API to dervie spending key or viewing key. - Some methods of the `DerivationTool` are now static. These methods don't use anything that requires instance of the `DerivationTool` inside. [#888] Use Sourcery to generate mocks - I wrote mock for `Synchronizer` manually. And it's tedious and long and boring work. - Now `ZcashRustBackendWelding` is changed a lot so it means `MockRustBackend` must be changed a lot. So I decided to introduce `sourcery` to generate mocks from protocols so we don't have to do it manually ever. - To generate mocks go to `ZcashLightClientKit/Tests/TestUtils/Sourcery` directory and run `generateMocks.sh` script. - Your protocol must be mentioned in `AutoMockable.swift` file. Generated mocks are in `AutoMockable.generated.swift` file. [#888] Fix Offline tests - Offline tests target now runs and tests are green. - There is log of changes in tests. But logic is not changed. - Updated `AutoMockable.stencil` so sourcery is able to generate mock as actor when protocol is marked with: `// sourcery: mockActor`. - Last few updates in `ZcashRustBackendWelding`. In previous PR `rewindCacheToHeight` methods was overlooked and it didn't throw error. - Removed `MockRustBackend` and using generated `ZCashRustBackendWeldingMock` instead. - Using generated `SynchronizerMock`. [#888] Fix NetworkTests - Changed a bit how rust backend mock is used in the tests. Introduced `RustBackendMockHelper`. There are some state variables that must be preserved within one instance of the mock. This helper does exactly this. It keeps this state variables in the memory and helping mock to work as expected. [#888] Fix Darkside tests Create ZcashKeyDeriving internal protocol Use New DerivationTool that does not require RustBackend Remove duplicated methods that had been copied over [#888] Fix potentially broken tests I broke the tests because I moved `testTempDirectory` from each `TestCase` to the `Environment`. By this I caused that each tests uses exactly same URL. Which is directly against purpose of `testTempDirectory`. So now each test calls this one and store it to local variable. So each test has unique URL. [#888] Add ability to mock nonisolated methods to AutoMockable.stencil [#888] Add changelog and fix the documentation in ZcashRustBackendWelding [#888] Rename derivation rust backend protocol and remove static methods - Renamed `ZcashKeyDeriving` to `ZcashKeyDerivationBackendWelding`. So the naming scheme is same as for `ZcashRustBackendWelding`. - `ZcashKeyDerivationBackend` is now struct instead of enum. - Methods in `ZcashKeyDerivationBackendWelding` (except one) are no longer static. Because of this the respective methods in `DerivationTool` aren't also static anymore.
2023-03-31 10:10:35 -07:00
do {
try await rustBackend.rewindToHeight(height: Int32(rewindHeight))
} catch {
await fail(error)
return
}
do {
try await blockDownloaderService.rewind(to: rewindHeight)
await internalSyncProgress.rewind(to: rewindHeight)
[#831] Add SDKSynchronizer wrappers for non-async API This change introduces two new protocols: `ClosureSynchronizer` and `CombineSynchronizer`. These two protocols define API that doesn't use `async`. So the client can choose exactly which API it wants to use. This change also introduces two new objects: `ClosureSDKSynchronizer` and `CombineSDKSynchronizer`. These two implement the respective protocols mentioned above. Both are structures. Neither of these two keeps any state. Thanks to this each is very cheap to create. And usage of these two isn't mutually exclusive. So devs can really choose the best SDK API for each part of the client app. [#831] Use async inside of the SDKSynchronizer - In general lot of methods inside the `SDKSynchronizer` and `CompactBlockProcessoer` which weren't async are now async. And other changes are made because of this change. - `CompactBlockProcessor` no longer uses Combine to communicate with `SDKSynchronizer`. Reason for this is that Combine doesn't play great with async. Closure passed to `sink` isn't async. - Because of this and because of how our tests work (receiving signals from CBP directly) `CompactBlockProcessor` must be able to handle more event closures. Not just one. So it now has `eventClosures` dictionary. It's little bit strange but it works fine. - `SyncStatus` inside the `SDKSynchronizer` was previously protected by lock. Now it's protected by simple actor wrapper. - Changes in tests are minimal. Changes were mady only because `CompactBlockProcessor` changes from Combine to closures. [#831] Add tests for ClosureSDKSynchronizer - Added tests are testing in general if the `ClosuresSDKSynchronizer` is correctly calling `Synchronizer` and if the values are correctly returned. - `ClosuresSDKSynchronizer` doesn't contain any logic but it is public API and we should be sure that it works correctly. [#831] Add tests for CombineSDKSynchronizer [#831] Add changelog
2023-03-16 02:11:18 -07:00
await send(event: .handledReorg(height, rewindHeight))
// process next batch
await self.nextBatch()
} catch {
await self.fail(error)
}
}
2021-09-17 06:49:58 -07:00
internal func processBatchFinished(height: BlockHeight?) async {
retryAttempts = 0
consecutiveChainValidationErrors = 0
if let height {
await processingFinished(height: height)
} else {
await nextBatch()
}
}
private func processingFinished(height: BlockHeight) async {
[#831] Add SDKSynchronizer wrappers for non-async API This change introduces two new protocols: `ClosureSynchronizer` and `CombineSynchronizer`. These two protocols define API that doesn't use `async`. So the client can choose exactly which API it wants to use. This change also introduces two new objects: `ClosureSDKSynchronizer` and `CombineSDKSynchronizer`. These two implement the respective protocols mentioned above. Both are structures. Neither of these two keeps any state. Thanks to this each is very cheap to create. And usage of these two isn't mutually exclusive. So devs can really choose the best SDK API for each part of the client app. [#831] Use async inside of the SDKSynchronizer - In general lot of methods inside the `SDKSynchronizer` and `CompactBlockProcessoer` which weren't async are now async. And other changes are made because of this change. - `CompactBlockProcessor` no longer uses Combine to communicate with `SDKSynchronizer`. Reason for this is that Combine doesn't play great with async. Closure passed to `sink` isn't async. - Because of this and because of how our tests work (receiving signals from CBP directly) `CompactBlockProcessor` must be able to handle more event closures. Not just one. So it now has `eventClosures` dictionary. It's little bit strange but it works fine. - `SyncStatus` inside the `SDKSynchronizer` was previously protected by lock. Now it's protected by simple actor wrapper. - Changes in tests are minimal. Changes were mady only because `CompactBlockProcessor` changes from Combine to closures. [#831] Add tests for ClosureSDKSynchronizer - Added tests are testing in general if the `ClosuresSDKSynchronizer` is correctly calling `Synchronizer` and if the values are correctly returned. - `ClosuresSDKSynchronizer` doesn't contain any logic but it is public API and we should be sure that it works correctly. [#831] Add tests for CombineSDKSynchronizer [#831] Add changelog
2023-03-16 02:11:18 -07:00
await send(event: .finished(height, foundBlocks))
await updateState(.synced)
await setTimer()
}
private func ifTaskIsNotCanceledClearCompactBlockCache(lastScannedHeight: BlockHeight) async {
guard !Task.isCancelled else { return }
do {
// Blocks download work in parallel with scanning. So imagine this scenario:
//
// Scanning is done until height 10300. Blocks are downloaded until height 10400.
// And now validation fails and this method is called. And `.latestDownloadedBlockHeight` in `internalSyncProgress` is set to 10400. And
// all the downloaded blocks are removed here.
//
// If this line doesn't happen then when sync starts next time it thinks that all the blocks are downloaded until 10400. But all were
// removed. So blocks between 10300 and 10400 wouldn't ever be scanned.
//
// Scanning is done until 10300 so the SDK can be sure that blocks with height below 10300 are not required. So it makes sense to set
// `.latestDownloadedBlockHeight` to `lastScannedHeight`. And sync will work fine in next run.
await internalSyncProgress.set(lastScannedHeight, .latestDownloadedBlockHeight)
try await clearCompactBlockCache()
} catch {
logger.error("`clearCompactBlockCache` failed after error: \(error)")
}
}
private func clearCompactBlockCache(upTo height: BlockHeight) async throws {
try await storage.clear(upTo: height)
logger.info("Cache removed upTo \(height)")
}
- [#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
private func clearCompactBlockCache() async throws {
await blockDownloader.stopDownload()
- [#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 await storage.clear()
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
logger.info("Cache removed")
- [#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
}
private func setTimer() async {
let interval = self.config.blockPollInterval
self.backoffTimer?.invalidate()
2021-09-17 06:49:58 -07:00
let timer = Timer(
timeInterval: interval,
repeats: true,
block: { [weak self] _ in
[#895] Add Sync Session ID Synchronizer State (#906) Closes #895 Add Sync Session ID to `SynchronizerState`. A SyncSession is an attempt to sync the blockchain within the lifetime of a Synchronizer. A Synchronizer can sync many times, when synced it will refresh every ~20 seconds +- random padding. each sync attempt will have a different UUID even if it's from the same instance of SDKSynchronizer. **How are SyncSessions are delimited? With `SyncStatus` changes.** changes from [`.unprepared`|`.error`|`.disconnected`|`.stopped`] to `.syncing` assign a new sessionID to the synchronizer. Any other transitions won't. `areTwoStatusesDifferent ` was refactored to a helper function of `SyncStatus` **How are IDs generated?** ID generation is not mandated but delegated to a protocol `SyncSessionIDGenerator`. Tests inject their own deterministic generator to avoid test flakiness. Default implementation of SyncSessionIDGenerator is ````Swift struct UniqueSyncSessionIDGenerator {} extension UniqueSyncSessionIDGenerator: SyncSessionIDGenerator { func nextID() -> UUID { UUID() } } ```` **SyncSession Pseudo-Atomicity and thread safety** SyncSession is a type alias of a GenericActor holding a UUID ```` typealias SyncSession = GenericActor<UUID> extension SyncSession { /// updates the current sync session to a new value with the given generator /// - Parameters generator: a `SyncSessionIDGenerator` /// - returns: the `UUID` of the newly updated value. @discardableResult func newSession(with generator: SyncSessionIDGenerator) async -> UUID { return await self.update(generator.nextID()) } } ```` Closes #895 SessionTicker struct to control session transitions. switching to `.unprepared` now makes syncID to be `.nullID`
2023-04-07 05:02:05 -07:00
Task { [weak self] in
guard let self else { return }
switch await self.state {
case .syncing, .enhancing, .fetching, .handlingSaplingFiles:
await self.latestBlocksDataProvider.updateBlockData()
case .stopped, .error, .synced:
if await self.shouldStart {
self.logger.debug(
"""
Timer triggered: Starting compact Block processor!.
Processor State: \(await self.state)
latestHeight: \(try await self.transactionRepository.lastScannedHeight())
attempts: \(await self.retryAttempts)
"""
)
await self.start()
} else if await self.maxAttemptsReached {
[#361] Introduce ZcashError (#1005) This PR introduces `ZcashError` enum. This enum represents any error that can be thrown inside of the SDK and outside of the SDK. Also `ZcashError` is used in `LightWalletGRPCService` and handled in `CompactBlockProcessor` as example. Why enum? First I tried this with some structure which contained code, message and underlyingError. Problem was when some specific place in the SDK would like to attach some additional data to error. I didn't want to add some generic dictionary to store anything with the error. So I used enum to identify error. Each member can have specified amount of associated values. So specific error can bring some context data. And it's type safe. Each error has also a code. Relationship between errors and codes is 1:1. It may looks bit redundant but it's important. The client app now can choose how to process errors. Either identify those by the error itself or by code. Definition or errors and codes is in `ZcashErrorDefinition`. And then `ZcashError` and `ZcashErrorCode` are generated by Sourcery. Thanks to this it is easier to maintain the final code. And it gives us ability to generate any kind of documentation for the errors and codes. I created simple example of this in this PR. And it doesn't make the SDK completely dependent on the Sourcery. Final structures aren't super complicated and can be written manually if needed. [#923] Update error handling in DatabaseStorageManager.swift - cleanup of DatabaseStorageManager, not used anymore - ZcashError for SimpleConnectionProvider Revert "[#923] Update error handling in DatabaseStorageManager.swift" This reverts commit 94e028d31a0f6635800c297eb741db74c6a6ff45. Fix script which generates ZcashError [#922] Update error handling in DatabaseMigrationManager.swift Closes #922 [#923] Update error handling in DatabaseStorageManager.swift - The DatabaseStorageManager is not used so I deleted it - SimpleConnectionProvider's errors updated Fix tests [#955] Update error handling in SaplingParameterDownloader Closes #955 [#936] Update error handling in NotesDao Closes #936 [#935] Update error handling in BlockDao Closes #935 [#931] InternalSyncProgress.computeNextState doesn't need to throw Closes #931 [#950] Update error handling in rust backend Closes #949 Closes #950 [#941] Update error handling in AccountEntity Closes #941 [#928] Update error handling in FSCompactBlockRepository Closes #928 [#925] Update error handling in BlockDownloaderService (#974) - BlockDownloaderService errors updated [#924] Update error handling in BlockDownloader (#973) - BlockDownloaderStream nextBlock updated [#942] Update error handling in TransactionEntity (#977) - ZcashTransaction init errors converted to the ZcashError [#939] Update error handling in TransactionDao (#976) - TransactionRepositoryError removed and replaced with ZcashError - all TransactionDAO errors converted to ZcashError [#943] Update error handling in ZcashCompactBlock Closes #943 [#945] Update error handling in Memo Closes #945 [#934] Update error handling in Checkpoint Closes #944 Closes #934 [#938] Update error handling in PendingTransactionDao Closes #938 [#926] Update error handling in BlockEnhancer - WIP, switching to transaction repository to unblock this ticket [#926] Update error handling in BlockEnhancer - enhancer's errors done [#926] Update error handling in BlockEnhancer (#994) - cleanup [#952] Update error handling in DerivationTool Closes #952 [#932] Update error handling in BlockValidator Closes #932 [#940] Update error handling in UnspentTransactionOutputDao Closes #940 [#946] Update error handling in WalletTypes Closes #946 [#954] Update error handling in WalletTransactionEncoder Closes #954 [#953] Update error handling in PersistentTransactionManager Closes #953 [#956] Update error handling in Initializer Closes #956 [#947] Update error handling in Zatoshi (#996) - Zatoshi's errors converted to ZcashError [#927] Update error handling in UTXOFetcher (#997) - UTXOFetcher resolved Use let instead of var where applicable In the SDK `var` was used on places where `let` would be sufficient. And default strategy in Swift should use use `let` until mutability is required. So all these places are changed. No logic is changed. [#933] Update error handling in CompactBlockProcessor - CompactBlockProcessor's errors refactored to ZcashError [#933] Update error handling in CompactBlockProcessor #999 - comments addressed [#951] Update error handling in SDKSynchronizer - SDKSynchronizer's errors refactored to ZcashError [#951] Update error handling in SDKSynchronizer (#1002) - comments resolved Make DerivationTool constructor public DerivationTool.init should be public. This was removed by accident when adopting async. [#361] Add changelog
2023-04-24 14:15:20 -07:00
await self.fail(ZcashError.compactBlockProcessorMaxAttemptsReached(self.config.retries))
}
}
}
2021-09-17 06:49:58 -07:00
}
)
RunLoop.main.add(timer, forMode: .default)
self.backoffTimer = timer
}
[#831] Add SDKSynchronizer wrappers for non-async API This change introduces two new protocols: `ClosureSynchronizer` and `CombineSynchronizer`. These two protocols define API that doesn't use `async`. So the client can choose exactly which API it wants to use. This change also introduces two new objects: `ClosureSDKSynchronizer` and `CombineSDKSynchronizer`. These two implement the respective protocols mentioned above. Both are structures. Neither of these two keeps any state. Thanks to this each is very cheap to create. And usage of these two isn't mutually exclusive. So devs can really choose the best SDK API for each part of the client app. [#831] Use async inside of the SDKSynchronizer - In general lot of methods inside the `SDKSynchronizer` and `CompactBlockProcessoer` which weren't async are now async. And other changes are made because of this change. - `CompactBlockProcessor` no longer uses Combine to communicate with `SDKSynchronizer`. Reason for this is that Combine doesn't play great with async. Closure passed to `sink` isn't async. - Because of this and because of how our tests work (receiving signals from CBP directly) `CompactBlockProcessor` must be able to handle more event closures. Not just one. So it now has `eventClosures` dictionary. It's little bit strange but it works fine. - `SyncStatus` inside the `SDKSynchronizer` was previously protected by lock. Now it's protected by simple actor wrapper. - Changes in tests are minimal. Changes were mady only because `CompactBlockProcessor` changes from Combine to closures. [#831] Add tests for ClosureSDKSynchronizer - Added tests are testing in general if the `ClosuresSDKSynchronizer` is correctly calling `Synchronizer` and if the values are correctly returned. - `ClosuresSDKSynchronizer` doesn't contain any logic but it is public API and we should be sure that it works correctly. [#831] Add tests for CombineSDKSynchronizer [#831] Add changelog
2023-03-16 02:11:18 -07:00
private func transitionState(from oldValue: State, to newValue: State) async {
guard oldValue != newValue else {
return
}
2021-09-17 06:49:58 -07:00
switch newValue {
case .error(let err):
[#831] Add SDKSynchronizer wrappers for non-async API This change introduces two new protocols: `ClosureSynchronizer` and `CombineSynchronizer`. These two protocols define API that doesn't use `async`. So the client can choose exactly which API it wants to use. This change also introduces two new objects: `ClosureSDKSynchronizer` and `CombineSDKSynchronizer`. These two implement the respective protocols mentioned above. Both are structures. Neither of these two keeps any state. Thanks to this each is very cheap to create. And usage of these two isn't mutually exclusive. So devs can really choose the best SDK API for each part of the client app. [#831] Use async inside of the SDKSynchronizer - In general lot of methods inside the `SDKSynchronizer` and `CompactBlockProcessoer` which weren't async are now async. And other changes are made because of this change. - `CompactBlockProcessor` no longer uses Combine to communicate with `SDKSynchronizer`. Reason for this is that Combine doesn't play great with async. Closure passed to `sink` isn't async. - Because of this and because of how our tests work (receiving signals from CBP directly) `CompactBlockProcessor` must be able to handle more event closures. Not just one. So it now has `eventClosures` dictionary. It's little bit strange but it works fine. - `SyncStatus` inside the `SDKSynchronizer` was previously protected by lock. Now it's protected by simple actor wrapper. - Changes in tests are minimal. Changes were mady only because `CompactBlockProcessor` changes from Combine to closures. [#831] Add tests for ClosureSDKSynchronizer - Added tests are testing in general if the `ClosuresSDKSynchronizer` is correctly calling `Synchronizer` and if the values are correctly returned. - `ClosuresSDKSynchronizer` doesn't contain any logic but it is public API and we should be sure that it works correctly. [#831] Add tests for CombineSDKSynchronizer [#831] Add changelog
2023-03-16 02:11:18 -07:00
await notifyError(err)
case .stopped:
[#831] Add SDKSynchronizer wrappers for non-async API This change introduces two new protocols: `ClosureSynchronizer` and `CombineSynchronizer`. These two protocols define API that doesn't use `async`. So the client can choose exactly which API it wants to use. This change also introduces two new objects: `ClosureSDKSynchronizer` and `CombineSDKSynchronizer`. These two implement the respective protocols mentioned above. Both are structures. Neither of these two keeps any state. Thanks to this each is very cheap to create. And usage of these two isn't mutually exclusive. So devs can really choose the best SDK API for each part of the client app. [#831] Use async inside of the SDKSynchronizer - In general lot of methods inside the `SDKSynchronizer` and `CompactBlockProcessoer` which weren't async are now async. And other changes are made because of this change. - `CompactBlockProcessor` no longer uses Combine to communicate with `SDKSynchronizer`. Reason for this is that Combine doesn't play great with async. Closure passed to `sink` isn't async. - Because of this and because of how our tests work (receiving signals from CBP directly) `CompactBlockProcessor` must be able to handle more event closures. Not just one. So it now has `eventClosures` dictionary. It's little bit strange but it works fine. - `SyncStatus` inside the `SDKSynchronizer` was previously protected by lock. Now it's protected by simple actor wrapper. - Changes in tests are minimal. Changes were mady only because `CompactBlockProcessor` changes from Combine to closures. [#831] Add tests for ClosureSDKSynchronizer - Added tests are testing in general if the `ClosuresSDKSynchronizer` is correctly calling `Synchronizer` and if the values are correctly returned. - `ClosuresSDKSynchronizer` doesn't contain any logic but it is public API and we should be sure that it works correctly. [#831] Add tests for CombineSDKSynchronizer [#831] Add changelog
2023-03-16 02:11:18 -07:00
await send(event: .stopped)
case .enhancing:
[#831] Add SDKSynchronizer wrappers for non-async API This change introduces two new protocols: `ClosureSynchronizer` and `CombineSynchronizer`. These two protocols define API that doesn't use `async`. So the client can choose exactly which API it wants to use. This change also introduces two new objects: `ClosureSDKSynchronizer` and `CombineSDKSynchronizer`. These two implement the respective protocols mentioned above. Both are structures. Neither of these two keeps any state. Thanks to this each is very cheap to create. And usage of these two isn't mutually exclusive. So devs can really choose the best SDK API for each part of the client app. [#831] Use async inside of the SDKSynchronizer - In general lot of methods inside the `SDKSynchronizer` and `CompactBlockProcessoer` which weren't async are now async. And other changes are made because of this change. - `CompactBlockProcessor` no longer uses Combine to communicate with `SDKSynchronizer`. Reason for this is that Combine doesn't play great with async. Closure passed to `sink` isn't async. - Because of this and because of how our tests work (receiving signals from CBP directly) `CompactBlockProcessor` must be able to handle more event closures. Not just one. So it now has `eventClosures` dictionary. It's little bit strange but it works fine. - `SyncStatus` inside the `SDKSynchronizer` was previously protected by lock. Now it's protected by simple actor wrapper. - Changes in tests are minimal. Changes were mady only because `CompactBlockProcessor` changes from Combine to closures. [#831] Add tests for ClosureSDKSynchronizer - Added tests are testing in general if the `ClosuresSDKSynchronizer` is correctly calling `Synchronizer` and if the values are correctly returned. - `ClosuresSDKSynchronizer` doesn't contain any logic but it is public API and we should be sure that it works correctly. [#831] Add tests for CombineSDKSynchronizer [#831] Add changelog
2023-03-16 02:11:18 -07:00
await send(event: .startedEnhancing)
case .fetching:
[#831] Add SDKSynchronizer wrappers for non-async API This change introduces two new protocols: `ClosureSynchronizer` and `CombineSynchronizer`. These two protocols define API that doesn't use `async`. So the client can choose exactly which API it wants to use. This change also introduces two new objects: `ClosureSDKSynchronizer` and `CombineSDKSynchronizer`. These two implement the respective protocols mentioned above. Both are structures. Neither of these two keeps any state. Thanks to this each is very cheap to create. And usage of these two isn't mutually exclusive. So devs can really choose the best SDK API for each part of the client app. [#831] Use async inside of the SDKSynchronizer - In general lot of methods inside the `SDKSynchronizer` and `CompactBlockProcessoer` which weren't async are now async. And other changes are made because of this change. - `CompactBlockProcessor` no longer uses Combine to communicate with `SDKSynchronizer`. Reason for this is that Combine doesn't play great with async. Closure passed to `sink` isn't async. - Because of this and because of how our tests work (receiving signals from CBP directly) `CompactBlockProcessor` must be able to handle more event closures. Not just one. So it now has `eventClosures` dictionary. It's little bit strange but it works fine. - `SyncStatus` inside the `SDKSynchronizer` was previously protected by lock. Now it's protected by simple actor wrapper. - Changes in tests are minimal. Changes were mady only because `CompactBlockProcessor` changes from Combine to closures. [#831] Add tests for ClosureSDKSynchronizer - Added tests are testing in general if the `ClosuresSDKSynchronizer` is correctly calling `Synchronizer` and if the values are correctly returned. - `ClosuresSDKSynchronizer` doesn't contain any logic but it is public API and we should be sure that it works correctly. [#831] Add tests for CombineSDKSynchronizer [#831] Add changelog
2023-03-16 02:11:18 -07:00
await send(event: .startedFetching)
case .handlingSaplingFiles:
// We don't report this to outside world as separate phase for now.
break
case .synced:
// transition to this state is handled by `processingFinished(height: BlockHeight)`
break
case .syncing:
[#831] Add SDKSynchronizer wrappers for non-async API This change introduces two new protocols: `ClosureSynchronizer` and `CombineSynchronizer`. These two protocols define API that doesn't use `async`. So the client can choose exactly which API it wants to use. This change also introduces two new objects: `ClosureSDKSynchronizer` and `CombineSDKSynchronizer`. These two implement the respective protocols mentioned above. Both are structures. Neither of these two keeps any state. Thanks to this each is very cheap to create. And usage of these two isn't mutually exclusive. So devs can really choose the best SDK API for each part of the client app. [#831] Use async inside of the SDKSynchronizer - In general lot of methods inside the `SDKSynchronizer` and `CompactBlockProcessoer` which weren't async are now async. And other changes are made because of this change. - `CompactBlockProcessor` no longer uses Combine to communicate with `SDKSynchronizer`. Reason for this is that Combine doesn't play great with async. Closure passed to `sink` isn't async. - Because of this and because of how our tests work (receiving signals from CBP directly) `CompactBlockProcessor` must be able to handle more event closures. Not just one. So it now has `eventClosures` dictionary. It's little bit strange but it works fine. - `SyncStatus` inside the `SDKSynchronizer` was previously protected by lock. Now it's protected by simple actor wrapper. - Changes in tests are minimal. Changes were mady only because `CompactBlockProcessor` changes from Combine to closures. [#831] Add tests for ClosureSDKSynchronizer - Added tests are testing in general if the `ClosuresSDKSynchronizer` is correctly calling `Synchronizer` and if the values are correctly returned. - `ClosuresSDKSynchronizer` doesn't contain any logic but it is public API and we should be sure that it works correctly. [#831] Add tests for CombineSDKSynchronizer [#831] Add changelog
2023-03-16 02:11:18 -07:00
await send(event: .startedSyncing)
}
}
2021-09-17 06:49:58 -07:00
[#831] Add SDKSynchronizer wrappers for non-async API This change introduces two new protocols: `ClosureSynchronizer` and `CombineSynchronizer`. These two protocols define API that doesn't use `async`. So the client can choose exactly which API it wants to use. This change also introduces two new objects: `ClosureSDKSynchronizer` and `CombineSDKSynchronizer`. These two implement the respective protocols mentioned above. Both are structures. Neither of these two keeps any state. Thanks to this each is very cheap to create. And usage of these two isn't mutually exclusive. So devs can really choose the best SDK API for each part of the client app. [#831] Use async inside of the SDKSynchronizer - In general lot of methods inside the `SDKSynchronizer` and `CompactBlockProcessoer` which weren't async are now async. And other changes are made because of this change. - `CompactBlockProcessor` no longer uses Combine to communicate with `SDKSynchronizer`. Reason for this is that Combine doesn't play great with async. Closure passed to `sink` isn't async. - Because of this and because of how our tests work (receiving signals from CBP directly) `CompactBlockProcessor` must be able to handle more event closures. Not just one. So it now has `eventClosures` dictionary. It's little bit strange but it works fine. - `SyncStatus` inside the `SDKSynchronizer` was previously protected by lock. Now it's protected by simple actor wrapper. - Changes in tests are minimal. Changes were mady only because `CompactBlockProcessor` changes from Combine to closures. [#831] Add tests for ClosureSDKSynchronizer - Added tests are testing in general if the `ClosuresSDKSynchronizer` is correctly calling `Synchronizer` and if the values are correctly returned. - `ClosuresSDKSynchronizer` doesn't contain any logic but it is public API and we should be sure that it works correctly. [#831] Add tests for CombineSDKSynchronizer [#831] Add changelog
2023-03-16 02:11:18 -07:00
private func notifyError(_ err: Error) async {
[#361] Introduce ZcashError (#1005) This PR introduces `ZcashError` enum. This enum represents any error that can be thrown inside of the SDK and outside of the SDK. Also `ZcashError` is used in `LightWalletGRPCService` and handled in `CompactBlockProcessor` as example. Why enum? First I tried this with some structure which contained code, message and underlyingError. Problem was when some specific place in the SDK would like to attach some additional data to error. I didn't want to add some generic dictionary to store anything with the error. So I used enum to identify error. Each member can have specified amount of associated values. So specific error can bring some context data. And it's type safe. Each error has also a code. Relationship between errors and codes is 1:1. It may looks bit redundant but it's important. The client app now can choose how to process errors. Either identify those by the error itself or by code. Definition or errors and codes is in `ZcashErrorDefinition`. And then `ZcashError` and `ZcashErrorCode` are generated by Sourcery. Thanks to this it is easier to maintain the final code. And it gives us ability to generate any kind of documentation for the errors and codes. I created simple example of this in this PR. And it doesn't make the SDK completely dependent on the Sourcery. Final structures aren't super complicated and can be written manually if needed. [#923] Update error handling in DatabaseStorageManager.swift - cleanup of DatabaseStorageManager, not used anymore - ZcashError for SimpleConnectionProvider Revert "[#923] Update error handling in DatabaseStorageManager.swift" This reverts commit 94e028d31a0f6635800c297eb741db74c6a6ff45. Fix script which generates ZcashError [#922] Update error handling in DatabaseMigrationManager.swift Closes #922 [#923] Update error handling in DatabaseStorageManager.swift - The DatabaseStorageManager is not used so I deleted it - SimpleConnectionProvider's errors updated Fix tests [#955] Update error handling in SaplingParameterDownloader Closes #955 [#936] Update error handling in NotesDao Closes #936 [#935] Update error handling in BlockDao Closes #935 [#931] InternalSyncProgress.computeNextState doesn't need to throw Closes #931 [#950] Update error handling in rust backend Closes #949 Closes #950 [#941] Update error handling in AccountEntity Closes #941 [#928] Update error handling in FSCompactBlockRepository Closes #928 [#925] Update error handling in BlockDownloaderService (#974) - BlockDownloaderService errors updated [#924] Update error handling in BlockDownloader (#973) - BlockDownloaderStream nextBlock updated [#942] Update error handling in TransactionEntity (#977) - ZcashTransaction init errors converted to the ZcashError [#939] Update error handling in TransactionDao (#976) - TransactionRepositoryError removed and replaced with ZcashError - all TransactionDAO errors converted to ZcashError [#943] Update error handling in ZcashCompactBlock Closes #943 [#945] Update error handling in Memo Closes #945 [#934] Update error handling in Checkpoint Closes #944 Closes #934 [#938] Update error handling in PendingTransactionDao Closes #938 [#926] Update error handling in BlockEnhancer - WIP, switching to transaction repository to unblock this ticket [#926] Update error handling in BlockEnhancer - enhancer's errors done [#926] Update error handling in BlockEnhancer (#994) - cleanup [#952] Update error handling in DerivationTool Closes #952 [#932] Update error handling in BlockValidator Closes #932 [#940] Update error handling in UnspentTransactionOutputDao Closes #940 [#946] Update error handling in WalletTypes Closes #946 [#954] Update error handling in WalletTransactionEncoder Closes #954 [#953] Update error handling in PersistentTransactionManager Closes #953 [#956] Update error handling in Initializer Closes #956 [#947] Update error handling in Zatoshi (#996) - Zatoshi's errors converted to ZcashError [#927] Update error handling in UTXOFetcher (#997) - UTXOFetcher resolved Use let instead of var where applicable In the SDK `var` was used on places where `let` would be sufficient. And default strategy in Swift should use use `let` until mutability is required. So all these places are changed. No logic is changed. [#933] Update error handling in CompactBlockProcessor - CompactBlockProcessor's errors refactored to ZcashError [#933] Update error handling in CompactBlockProcessor #999 - comments addressed [#951] Update error handling in SDKSynchronizer - SDKSynchronizer's errors refactored to ZcashError [#951] Update error handling in SDKSynchronizer (#1002) - comments resolved Make DerivationTool constructor public DerivationTool.init should be public. This was removed by accident when adopting async. [#361] Add changelog
2023-04-24 14:15:20 -07:00
await send(event: .failed(err))
}
// TODO: [#713] encapsulate service errors better, https://github.com/zcash/ZcashLightClientKit/issues/713
}
extension CompactBlockProcessor.State: Equatable {
public static func == (lhs: CompactBlockProcessor.State, rhs: CompactBlockProcessor.State) -> Bool {
switch (lhs, rhs) {
2021-09-17 06:49:58 -07:00
case
(.syncing, .syncing),
2021-09-17 06:49:58 -07:00
(.stopped, .stopped),
(.error, .error),
(.synced, .synced),
(.enhancing, .enhancing),
2021-09-17 06:49:58 -07:00
(.fetching, .fetching):
return true
default:
return false
}
}
}
2021-04-08 10:18:16 -07:00
extension CompactBlockProcessor {
func getUnifiedAddress(accountIndex: Int) async throws -> UnifiedAddress {
[#888] Make actor from ZcashRustBackendWelding Closes #888. - `ZcashRustBackend` is actor now. So majority of methods in this actor are now async. - Some methods stayed `static` in `ZcashRustBackend`. It would be hard to pass instance of the `ZcashRustBackend` to the places where these methods are used in static manner. And it would change lot of APIs. But it isn't problem from technical perspective because these methods would be `nonisolated` otherwise. - Methods `lastError()` and `getLastError()` in `ZcashRustBackend` are now private. This makes sure that ther won't be aby race condition between other methods and these two error methods. - All the methods for which was `lastError()` used in code now throw error. So `lastError()` is no longer needed outside of the `ZcashRustBackend`. - There are in the public API related to `DerivationTool`. - `DerivationTool` now requires instance of the `ZcashRustBackend`. And `ZcashRustBackend` isn't public type. So `DerivationTool` doesn't have any public constructor now. It can be created only via `Initializer.makeDerivationTool()` instance method. - `deriveUnifiedSpendingKey()` and `deriveUnifiedFullViewingKey()` in `DerivationTool` are now async. It is because these are using `ZcashRustBackend` inside. `DerivationTool` offers alternative (closure and combine) APIs. But downside is that there is no sync API to dervie spending key or viewing key. - Some methods of the `DerivationTool` are now static. These methods don't use anything that requires instance of the `DerivationTool` inside. [#888] Use Sourcery to generate mocks - I wrote mock for `Synchronizer` manually. And it's tedious and long and boring work. - Now `ZcashRustBackendWelding` is changed a lot so it means `MockRustBackend` must be changed a lot. So I decided to introduce `sourcery` to generate mocks from protocols so we don't have to do it manually ever. - To generate mocks go to `ZcashLightClientKit/Tests/TestUtils/Sourcery` directory and run `generateMocks.sh` script. - Your protocol must be mentioned in `AutoMockable.swift` file. Generated mocks are in `AutoMockable.generated.swift` file. [#888] Fix Offline tests - Offline tests target now runs and tests are green. - There is log of changes in tests. But logic is not changed. - Updated `AutoMockable.stencil` so sourcery is able to generate mock as actor when protocol is marked with: `// sourcery: mockActor`. - Last few updates in `ZcashRustBackendWelding`. In previous PR `rewindCacheToHeight` methods was overlooked and it didn't throw error. - Removed `MockRustBackend` and using generated `ZCashRustBackendWeldingMock` instead. - Using generated `SynchronizerMock`. [#888] Fix NetworkTests - Changed a bit how rust backend mock is used in the tests. Introduced `RustBackendMockHelper`. There are some state variables that must be preserved within one instance of the mock. This helper does exactly this. It keeps this state variables in the memory and helping mock to work as expected. [#888] Fix Darkside tests Create ZcashKeyDeriving internal protocol Use New DerivationTool that does not require RustBackend Remove duplicated methods that had been copied over [#888] Fix potentially broken tests I broke the tests because I moved `testTempDirectory` from each `TestCase` to the `Environment`. By this I caused that each tests uses exactly same URL. Which is directly against purpose of `testTempDirectory`. So now each test calls this one and store it to local variable. So each test has unique URL. [#888] Add ability to mock nonisolated methods to AutoMockable.stencil [#888] Add changelog and fix the documentation in ZcashRustBackendWelding [#888] Rename derivation rust backend protocol and remove static methods - Renamed `ZcashKeyDeriving` to `ZcashKeyDerivationBackendWelding`. So the naming scheme is same as for `ZcashRustBackendWelding`. - `ZcashKeyDerivationBackend` is now struct instead of enum. - Methods in `ZcashKeyDerivationBackendWelding` (except one) are no longer static. Because of this the respective methods in `DerivationTool` aren't also static anymore.
2023-03-31 10:10:35 -07:00
try await rustBackend.getCurrentAddress(account: Int32(accountIndex))
2021-04-08 10:18:16 -07:00
}
func getSaplingAddress(accountIndex: Int) async throws -> SaplingAddress {
try await getUnifiedAddress(accountIndex: accountIndex).saplingReceiver()
2021-04-08 10:18:16 -07:00
}
func getTransparentAddress(accountIndex: Int) async throws -> TransparentAddress {
try await getUnifiedAddress(accountIndex: accountIndex).transparentReceiver()
2021-04-08 10:18:16 -07:00
}
func getTransparentBalance(accountIndex: Int) async throws -> WalletBalance {
guard accountIndex >= 0 else {
[#361] Introduce ZcashError (#1005) This PR introduces `ZcashError` enum. This enum represents any error that can be thrown inside of the SDK and outside of the SDK. Also `ZcashError` is used in `LightWalletGRPCService` and handled in `CompactBlockProcessor` as example. Why enum? First I tried this with some structure which contained code, message and underlyingError. Problem was when some specific place in the SDK would like to attach some additional data to error. I didn't want to add some generic dictionary to store anything with the error. So I used enum to identify error. Each member can have specified amount of associated values. So specific error can bring some context data. And it's type safe. Each error has also a code. Relationship between errors and codes is 1:1. It may looks bit redundant but it's important. The client app now can choose how to process errors. Either identify those by the error itself or by code. Definition or errors and codes is in `ZcashErrorDefinition`. And then `ZcashError` and `ZcashErrorCode` are generated by Sourcery. Thanks to this it is easier to maintain the final code. And it gives us ability to generate any kind of documentation for the errors and codes. I created simple example of this in this PR. And it doesn't make the SDK completely dependent on the Sourcery. Final structures aren't super complicated and can be written manually if needed. [#923] Update error handling in DatabaseStorageManager.swift - cleanup of DatabaseStorageManager, not used anymore - ZcashError for SimpleConnectionProvider Revert "[#923] Update error handling in DatabaseStorageManager.swift" This reverts commit 94e028d31a0f6635800c297eb741db74c6a6ff45. Fix script which generates ZcashError [#922] Update error handling in DatabaseMigrationManager.swift Closes #922 [#923] Update error handling in DatabaseStorageManager.swift - The DatabaseStorageManager is not used so I deleted it - SimpleConnectionProvider's errors updated Fix tests [#955] Update error handling in SaplingParameterDownloader Closes #955 [#936] Update error handling in NotesDao Closes #936 [#935] Update error handling in BlockDao Closes #935 [#931] InternalSyncProgress.computeNextState doesn't need to throw Closes #931 [#950] Update error handling in rust backend Closes #949 Closes #950 [#941] Update error handling in AccountEntity Closes #941 [#928] Update error handling in FSCompactBlockRepository Closes #928 [#925] Update error handling in BlockDownloaderService (#974) - BlockDownloaderService errors updated [#924] Update error handling in BlockDownloader (#973) - BlockDownloaderStream nextBlock updated [#942] Update error handling in TransactionEntity (#977) - ZcashTransaction init errors converted to the ZcashError [#939] Update error handling in TransactionDao (#976) - TransactionRepositoryError removed and replaced with ZcashError - all TransactionDAO errors converted to ZcashError [#943] Update error handling in ZcashCompactBlock Closes #943 [#945] Update error handling in Memo Closes #945 [#934] Update error handling in Checkpoint Closes #944 Closes #934 [#938] Update error handling in PendingTransactionDao Closes #938 [#926] Update error handling in BlockEnhancer - WIP, switching to transaction repository to unblock this ticket [#926] Update error handling in BlockEnhancer - enhancer's errors done [#926] Update error handling in BlockEnhancer (#994) - cleanup [#952] Update error handling in DerivationTool Closes #952 [#932] Update error handling in BlockValidator Closes #932 [#940] Update error handling in UnspentTransactionOutputDao Closes #940 [#946] Update error handling in WalletTypes Closes #946 [#954] Update error handling in WalletTransactionEncoder Closes #954 [#953] Update error handling in PersistentTransactionManager Closes #953 [#956] Update error handling in Initializer Closes #956 [#947] Update error handling in Zatoshi (#996) - Zatoshi's errors converted to ZcashError [#927] Update error handling in UTXOFetcher (#997) - UTXOFetcher resolved Use let instead of var where applicable In the SDK `var` was used on places where `let` would be sufficient. And default strategy in Swift should use use `let` until mutability is required. So all these places are changed. No logic is changed. [#933] Update error handling in CompactBlockProcessor - CompactBlockProcessor's errors refactored to ZcashError [#933] Update error handling in CompactBlockProcessor #999 - comments addressed [#951] Update error handling in SDKSynchronizer - SDKSynchronizer's errors refactored to ZcashError [#951] Update error handling in SDKSynchronizer (#1002) - comments resolved Make DerivationTool constructor public DerivationTool.init should be public. This was removed by accident when adopting async. [#361] Add changelog
2023-04-24 14:15:20 -07:00
throw ZcashError.compactBlockProcessorInvalidAccount
2021-04-08 10:18:16 -07:00
}
return WalletBalance(
verified: Zatoshi(
[#888] Make actor from ZcashRustBackendWelding Closes #888. - `ZcashRustBackend` is actor now. So majority of methods in this actor are now async. - Some methods stayed `static` in `ZcashRustBackend`. It would be hard to pass instance of the `ZcashRustBackend` to the places where these methods are used in static manner. And it would change lot of APIs. But it isn't problem from technical perspective because these methods would be `nonisolated` otherwise. - Methods `lastError()` and `getLastError()` in `ZcashRustBackend` are now private. This makes sure that ther won't be aby race condition between other methods and these two error methods. - All the methods for which was `lastError()` used in code now throw error. So `lastError()` is no longer needed outside of the `ZcashRustBackend`. - There are in the public API related to `DerivationTool`. - `DerivationTool` now requires instance of the `ZcashRustBackend`. And `ZcashRustBackend` isn't public type. So `DerivationTool` doesn't have any public constructor now. It can be created only via `Initializer.makeDerivationTool()` instance method. - `deriveUnifiedSpendingKey()` and `deriveUnifiedFullViewingKey()` in `DerivationTool` are now async. It is because these are using `ZcashRustBackend` inside. `DerivationTool` offers alternative (closure and combine) APIs. But downside is that there is no sync API to dervie spending key or viewing key. - Some methods of the `DerivationTool` are now static. These methods don't use anything that requires instance of the `DerivationTool` inside. [#888] Use Sourcery to generate mocks - I wrote mock for `Synchronizer` manually. And it's tedious and long and boring work. - Now `ZcashRustBackendWelding` is changed a lot so it means `MockRustBackend` must be changed a lot. So I decided to introduce `sourcery` to generate mocks from protocols so we don't have to do it manually ever. - To generate mocks go to `ZcashLightClientKit/Tests/TestUtils/Sourcery` directory and run `generateMocks.sh` script. - Your protocol must be mentioned in `AutoMockable.swift` file. Generated mocks are in `AutoMockable.generated.swift` file. [#888] Fix Offline tests - Offline tests target now runs and tests are green. - There is log of changes in tests. But logic is not changed. - Updated `AutoMockable.stencil` so sourcery is able to generate mock as actor when protocol is marked with: `// sourcery: mockActor`. - Last few updates in `ZcashRustBackendWelding`. In previous PR `rewindCacheToHeight` methods was overlooked and it didn't throw error. - Removed `MockRustBackend` and using generated `ZCashRustBackendWeldingMock` instead. - Using generated `SynchronizerMock`. [#888] Fix NetworkTests - Changed a bit how rust backend mock is used in the tests. Introduced `RustBackendMockHelper`. There are some state variables that must be preserved within one instance of the mock. This helper does exactly this. It keeps this state variables in the memory and helping mock to work as expected. [#888] Fix Darkside tests Create ZcashKeyDeriving internal protocol Use New DerivationTool that does not require RustBackend Remove duplicated methods that had been copied over [#888] Fix potentially broken tests I broke the tests because I moved `testTempDirectory` from each `TestCase` to the `Environment`. By this I caused that each tests uses exactly same URL. Which is directly against purpose of `testTempDirectory`. So now each test calls this one and store it to local variable. So each test has unique URL. [#888] Add ability to mock nonisolated methods to AutoMockable.stencil [#888] Add changelog and fix the documentation in ZcashRustBackendWelding [#888] Rename derivation rust backend protocol and remove static methods - Renamed `ZcashKeyDeriving` to `ZcashKeyDerivationBackendWelding`. So the naming scheme is same as for `ZcashRustBackendWelding`. - `ZcashKeyDerivationBackend` is now struct instead of enum. - Methods in `ZcashKeyDerivationBackendWelding` (except one) are no longer static. Because of this the respective methods in `DerivationTool` aren't also static anymore.
2023-03-31 10:10:35 -07:00
try await rustBackend.getVerifiedTransparentBalance(account: Int32(accountIndex))
),
total: Zatoshi(
[#888] Make actor from ZcashRustBackendWelding Closes #888. - `ZcashRustBackend` is actor now. So majority of methods in this actor are now async. - Some methods stayed `static` in `ZcashRustBackend`. It would be hard to pass instance of the `ZcashRustBackend` to the places where these methods are used in static manner. And it would change lot of APIs. But it isn't problem from technical perspective because these methods would be `nonisolated` otherwise. - Methods `lastError()` and `getLastError()` in `ZcashRustBackend` are now private. This makes sure that ther won't be aby race condition between other methods and these two error methods. - All the methods for which was `lastError()` used in code now throw error. So `lastError()` is no longer needed outside of the `ZcashRustBackend`. - There are in the public API related to `DerivationTool`. - `DerivationTool` now requires instance of the `ZcashRustBackend`. And `ZcashRustBackend` isn't public type. So `DerivationTool` doesn't have any public constructor now. It can be created only via `Initializer.makeDerivationTool()` instance method. - `deriveUnifiedSpendingKey()` and `deriveUnifiedFullViewingKey()` in `DerivationTool` are now async. It is because these are using `ZcashRustBackend` inside. `DerivationTool` offers alternative (closure and combine) APIs. But downside is that there is no sync API to dervie spending key or viewing key. - Some methods of the `DerivationTool` are now static. These methods don't use anything that requires instance of the `DerivationTool` inside. [#888] Use Sourcery to generate mocks - I wrote mock for `Synchronizer` manually. And it's tedious and long and boring work. - Now `ZcashRustBackendWelding` is changed a lot so it means `MockRustBackend` must be changed a lot. So I decided to introduce `sourcery` to generate mocks from protocols so we don't have to do it manually ever. - To generate mocks go to `ZcashLightClientKit/Tests/TestUtils/Sourcery` directory and run `generateMocks.sh` script. - Your protocol must be mentioned in `AutoMockable.swift` file. Generated mocks are in `AutoMockable.generated.swift` file. [#888] Fix Offline tests - Offline tests target now runs and tests are green. - There is log of changes in tests. But logic is not changed. - Updated `AutoMockable.stencil` so sourcery is able to generate mock as actor when protocol is marked with: `// sourcery: mockActor`. - Last few updates in `ZcashRustBackendWelding`. In previous PR `rewindCacheToHeight` methods was overlooked and it didn't throw error. - Removed `MockRustBackend` and using generated `ZCashRustBackendWeldingMock` instead. - Using generated `SynchronizerMock`. [#888] Fix NetworkTests - Changed a bit how rust backend mock is used in the tests. Introduced `RustBackendMockHelper`. There are some state variables that must be preserved within one instance of the mock. This helper does exactly this. It keeps this state variables in the memory and helping mock to work as expected. [#888] Fix Darkside tests Create ZcashKeyDeriving internal protocol Use New DerivationTool that does not require RustBackend Remove duplicated methods that had been copied over [#888] Fix potentially broken tests I broke the tests because I moved `testTempDirectory` from each `TestCase` to the `Environment`. By this I caused that each tests uses exactly same URL. Which is directly against purpose of `testTempDirectory`. So now each test calls this one and store it to local variable. So each test has unique URL. [#888] Add ability to mock nonisolated methods to AutoMockable.stencil [#888] Add changelog and fix the documentation in ZcashRustBackendWelding [#888] Rename derivation rust backend protocol and remove static methods - Renamed `ZcashKeyDeriving` to `ZcashKeyDerivationBackendWelding`. So the naming scheme is same as for `ZcashRustBackendWelding`. - `ZcashKeyDerivationBackend` is now struct instead of enum. - Methods in `ZcashKeyDerivationBackendWelding` (except one) are no longer static. Because of this the respective methods in `DerivationTool` aren't also static anymore.
2023-03-31 10:10:35 -07:00
try await rustBackend.getTransparentBalance(account: Int32(accountIndex))
)
)
2021-04-08 10:18:16 -07:00
}
}
extension CompactBlockProcessor {
func refreshUTXOs(tAddress: TransparentAddress, startHeight: BlockHeight) async throws -> RefreshedUTXOs {
2021-04-08 10:18:16 -07:00
let dataDb = self.config.dataDb
[476] CompactBlockProcessor to async/await - getting rid of the Operation Queue - the cleanup is needed - the update of tests is needed - tested and it successfully finishes the sync process [476] CompactBlockProcessor to async/await - old processNewBlocks() removed [476] CompactBlockProcessor to async/await - unused operations removed [476] CompactBlockProcessor to async/await - unit tests update [476] CompactBlockProcessor to async/await - unit tests refactored [476] CompactBlockProcessor to async/await - cleanup of deprecated method [476] CompactBlockProcessor to async/await - fail(error) was called even for canceled tasks but that must be excluded [476] CompactBlockProcessor to async/await - removal of all ZcashOperations from the code (unit test will follow) [476] CompactBlockProcessor to async/await - network tests in building and success order again [476] CompactBlockProcessor to async/await - offline tests in building and success order [476] CompactBlockProcessor to async/await (519) - cleanup of suspending the task [476] CompactBlockProcessor to async/await (519) - most comments resolved [476] CompactBlockProcessor to async/await (519) - thread safe state for both sync and async context [476] CompactBlockProcessor to async/await (519) - fixed build for a sample project [476] CompactBlockProcessor to async/await (519) - func testStartNotifiesSuscriptors() reverted [476] CompactBlockProcessor to async/await (519) - TODO added to track why we used NSLock instead of an Actor - Task priority enhanced [476] CompactBlockProcessor to async/await (519) - cleanup in Tasks and priorities
2022-09-01 05:58:41 -07:00
let stream: AsyncThrowingStream<UnspentTransactionOutputEntity, Error> = blockDownloaderService.fetchUnspentTransactionOutputs(
tAddress: tAddress.stringEncoded,
startHeight: startHeight
)
[476] CompactBlockProcessor to async/await - getting rid of the Operation Queue - the cleanup is needed - the update of tests is needed - tested and it successfully finishes the sync process [476] CompactBlockProcessor to async/await - old processNewBlocks() removed [476] CompactBlockProcessor to async/await - unused operations removed [476] CompactBlockProcessor to async/await - unit tests update [476] CompactBlockProcessor to async/await - unit tests refactored [476] CompactBlockProcessor to async/await - cleanup of deprecated method [476] CompactBlockProcessor to async/await - fail(error) was called even for canceled tasks but that must be excluded [476] CompactBlockProcessor to async/await - removal of all ZcashOperations from the code (unit test will follow) [476] CompactBlockProcessor to async/await - network tests in building and success order again [476] CompactBlockProcessor to async/await - offline tests in building and success order [476] CompactBlockProcessor to async/await (519) - cleanup of suspending the task [476] CompactBlockProcessor to async/await (519) - most comments resolved [476] CompactBlockProcessor to async/await (519) - thread safe state for both sync and async context [476] CompactBlockProcessor to async/await (519) - fixed build for a sample project [476] CompactBlockProcessor to async/await (519) - func testStartNotifiesSuscriptors() reverted [476] CompactBlockProcessor to async/await (519) - TODO added to track why we used NSLock instead of an Actor - Task priority enhanced [476] CompactBlockProcessor to async/await (519) - cleanup in Tasks and priorities
2022-09-01 05:58:41 -07:00
var utxos: [UnspentTransactionOutputEntity] = []
do {
for try await utxo in stream {
utxos.append(utxo)
2021-04-08 10:18:16 -07:00
}
return await storeUTXOs(utxos, in: dataDb)
[476] CompactBlockProcessor to async/await - getting rid of the Operation Queue - the cleanup is needed - the update of tests is needed - tested and it successfully finishes the sync process [476] CompactBlockProcessor to async/await - old processNewBlocks() removed [476] CompactBlockProcessor to async/await - unused operations removed [476] CompactBlockProcessor to async/await - unit tests update [476] CompactBlockProcessor to async/await - unit tests refactored [476] CompactBlockProcessor to async/await - cleanup of deprecated method [476] CompactBlockProcessor to async/await - fail(error) was called even for canceled tasks but that must be excluded [476] CompactBlockProcessor to async/await - removal of all ZcashOperations from the code (unit test will follow) [476] CompactBlockProcessor to async/await - network tests in building and success order again [476] CompactBlockProcessor to async/await - offline tests in building and success order [476] CompactBlockProcessor to async/await (519) - cleanup of suspending the task [476] CompactBlockProcessor to async/await (519) - most comments resolved [476] CompactBlockProcessor to async/await (519) - thread safe state for both sync and async context [476] CompactBlockProcessor to async/await (519) - fixed build for a sample project [476] CompactBlockProcessor to async/await (519) - func testStartNotifiesSuscriptors() reverted [476] CompactBlockProcessor to async/await (519) - TODO added to track why we used NSLock instead of an Actor - Task priority enhanced [476] CompactBlockProcessor to async/await (519) - cleanup in Tasks and priorities
2022-09-01 05:58:41 -07:00
} catch {
[#361] Introduce ZcashError (#1005) This PR introduces `ZcashError` enum. This enum represents any error that can be thrown inside of the SDK and outside of the SDK. Also `ZcashError` is used in `LightWalletGRPCService` and handled in `CompactBlockProcessor` as example. Why enum? First I tried this with some structure which contained code, message and underlyingError. Problem was when some specific place in the SDK would like to attach some additional data to error. I didn't want to add some generic dictionary to store anything with the error. So I used enum to identify error. Each member can have specified amount of associated values. So specific error can bring some context data. And it's type safe. Each error has also a code. Relationship between errors and codes is 1:1. It may looks bit redundant but it's important. The client app now can choose how to process errors. Either identify those by the error itself or by code. Definition or errors and codes is in `ZcashErrorDefinition`. And then `ZcashError` and `ZcashErrorCode` are generated by Sourcery. Thanks to this it is easier to maintain the final code. And it gives us ability to generate any kind of documentation for the errors and codes. I created simple example of this in this PR. And it doesn't make the SDK completely dependent on the Sourcery. Final structures aren't super complicated and can be written manually if needed. [#923] Update error handling in DatabaseStorageManager.swift - cleanup of DatabaseStorageManager, not used anymore - ZcashError for SimpleConnectionProvider Revert "[#923] Update error handling in DatabaseStorageManager.swift" This reverts commit 94e028d31a0f6635800c297eb741db74c6a6ff45. Fix script which generates ZcashError [#922] Update error handling in DatabaseMigrationManager.swift Closes #922 [#923] Update error handling in DatabaseStorageManager.swift - The DatabaseStorageManager is not used so I deleted it - SimpleConnectionProvider's errors updated Fix tests [#955] Update error handling in SaplingParameterDownloader Closes #955 [#936] Update error handling in NotesDao Closes #936 [#935] Update error handling in BlockDao Closes #935 [#931] InternalSyncProgress.computeNextState doesn't need to throw Closes #931 [#950] Update error handling in rust backend Closes #949 Closes #950 [#941] Update error handling in AccountEntity Closes #941 [#928] Update error handling in FSCompactBlockRepository Closes #928 [#925] Update error handling in BlockDownloaderService (#974) - BlockDownloaderService errors updated [#924] Update error handling in BlockDownloader (#973) - BlockDownloaderStream nextBlock updated [#942] Update error handling in TransactionEntity (#977) - ZcashTransaction init errors converted to the ZcashError [#939] Update error handling in TransactionDao (#976) - TransactionRepositoryError removed and replaced with ZcashError - all TransactionDAO errors converted to ZcashError [#943] Update error handling in ZcashCompactBlock Closes #943 [#945] Update error handling in Memo Closes #945 [#934] Update error handling in Checkpoint Closes #944 Closes #934 [#938] Update error handling in PendingTransactionDao Closes #938 [#926] Update error handling in BlockEnhancer - WIP, switching to transaction repository to unblock this ticket [#926] Update error handling in BlockEnhancer - enhancer's errors done [#926] Update error handling in BlockEnhancer (#994) - cleanup [#952] Update error handling in DerivationTool Closes #952 [#932] Update error handling in BlockValidator Closes #932 [#940] Update error handling in UnspentTransactionOutputDao Closes #940 [#946] Update error handling in WalletTypes Closes #946 [#954] Update error handling in WalletTransactionEncoder Closes #954 [#953] Update error handling in PersistentTransactionManager Closes #953 [#956] Update error handling in Initializer Closes #956 [#947] Update error handling in Zatoshi (#996) - Zatoshi's errors converted to ZcashError [#927] Update error handling in UTXOFetcher (#997) - UTXOFetcher resolved Use let instead of var where applicable In the SDK `var` was used on places where `let` would be sufficient. And default strategy in Swift should use use `let` until mutability is required. So all these places are changed. No logic is changed. [#933] Update error handling in CompactBlockProcessor - CompactBlockProcessor's errors refactored to ZcashError [#933] Update error handling in CompactBlockProcessor #999 - comments addressed [#951] Update error handling in SDKSynchronizer - SDKSynchronizer's errors refactored to ZcashError [#951] Update error handling in SDKSynchronizer (#1002) - comments resolved Make DerivationTool constructor public DerivationTool.init should be public. This was removed by accident when adopting async. [#361] Add changelog
2023-04-24 14:15:20 -07:00
throw error
2021-04-08 10:18:16 -07:00
}
}
private func storeUTXOs(_ utxos: [UnspentTransactionOutputEntity], in dataDb: URL) async -> RefreshedUTXOs {
2021-09-17 06:49:58 -07:00
var refreshed: [UnspentTransactionOutputEntity] = []
var skipped: [UnspentTransactionOutputEntity] = []
2021-04-08 10:18:16 -07:00
for utxo in utxos {
do {
[#888] Make actor from ZcashRustBackendWelding Closes #888. - `ZcashRustBackend` is actor now. So majority of methods in this actor are now async. - Some methods stayed `static` in `ZcashRustBackend`. It would be hard to pass instance of the `ZcashRustBackend` to the places where these methods are used in static manner. And it would change lot of APIs. But it isn't problem from technical perspective because these methods would be `nonisolated` otherwise. - Methods `lastError()` and `getLastError()` in `ZcashRustBackend` are now private. This makes sure that ther won't be aby race condition between other methods and these two error methods. - All the methods for which was `lastError()` used in code now throw error. So `lastError()` is no longer needed outside of the `ZcashRustBackend`. - There are in the public API related to `DerivationTool`. - `DerivationTool` now requires instance of the `ZcashRustBackend`. And `ZcashRustBackend` isn't public type. So `DerivationTool` doesn't have any public constructor now. It can be created only via `Initializer.makeDerivationTool()` instance method. - `deriveUnifiedSpendingKey()` and `deriveUnifiedFullViewingKey()` in `DerivationTool` are now async. It is because these are using `ZcashRustBackend` inside. `DerivationTool` offers alternative (closure and combine) APIs. But downside is that there is no sync API to dervie spending key or viewing key. - Some methods of the `DerivationTool` are now static. These methods don't use anything that requires instance of the `DerivationTool` inside. [#888] Use Sourcery to generate mocks - I wrote mock for `Synchronizer` manually. And it's tedious and long and boring work. - Now `ZcashRustBackendWelding` is changed a lot so it means `MockRustBackend` must be changed a lot. So I decided to introduce `sourcery` to generate mocks from protocols so we don't have to do it manually ever. - To generate mocks go to `ZcashLightClientKit/Tests/TestUtils/Sourcery` directory and run `generateMocks.sh` script. - Your protocol must be mentioned in `AutoMockable.swift` file. Generated mocks are in `AutoMockable.generated.swift` file. [#888] Fix Offline tests - Offline tests target now runs and tests are green. - There is log of changes in tests. But logic is not changed. - Updated `AutoMockable.stencil` so sourcery is able to generate mock as actor when protocol is marked with: `// sourcery: mockActor`. - Last few updates in `ZcashRustBackendWelding`. In previous PR `rewindCacheToHeight` methods was overlooked and it didn't throw error. - Removed `MockRustBackend` and using generated `ZCashRustBackendWeldingMock` instead. - Using generated `SynchronizerMock`. [#888] Fix NetworkTests - Changed a bit how rust backend mock is used in the tests. Introduced `RustBackendMockHelper`. There are some state variables that must be preserved within one instance of the mock. This helper does exactly this. It keeps this state variables in the memory and helping mock to work as expected. [#888] Fix Darkside tests Create ZcashKeyDeriving internal protocol Use New DerivationTool that does not require RustBackend Remove duplicated methods that had been copied over [#888] Fix potentially broken tests I broke the tests because I moved `testTempDirectory` from each `TestCase` to the `Environment`. By this I caused that each tests uses exactly same URL. Which is directly against purpose of `testTempDirectory`. So now each test calls this one and store it to local variable. So each test has unique URL. [#888] Add ability to mock nonisolated methods to AutoMockable.stencil [#888] Add changelog and fix the documentation in ZcashRustBackendWelding [#888] Rename derivation rust backend protocol and remove static methods - Renamed `ZcashKeyDeriving` to `ZcashKeyDerivationBackendWelding`. So the naming scheme is same as for `ZcashRustBackendWelding`. - `ZcashKeyDerivationBackend` is now struct instead of enum. - Methods in `ZcashKeyDerivationBackendWelding` (except one) are no longer static. Because of this the respective methods in `DerivationTool` aren't also static anymore.
2023-03-31 10:10:35 -07:00
try await rustBackend.putUnspentTransparentOutput(
2021-04-08 10:18:16 -07:00
txid: utxo.txid.bytes,
index: utxo.index,
script: utxo.script.bytes,
value: Int64(utxo.valueZat),
[#888] Make actor from ZcashRustBackendWelding Closes #888. - `ZcashRustBackend` is actor now. So majority of methods in this actor are now async. - Some methods stayed `static` in `ZcashRustBackend`. It would be hard to pass instance of the `ZcashRustBackend` to the places where these methods are used in static manner. And it would change lot of APIs. But it isn't problem from technical perspective because these methods would be `nonisolated` otherwise. - Methods `lastError()` and `getLastError()` in `ZcashRustBackend` are now private. This makes sure that ther won't be aby race condition between other methods and these two error methods. - All the methods for which was `lastError()` used in code now throw error. So `lastError()` is no longer needed outside of the `ZcashRustBackend`. - There are in the public API related to `DerivationTool`. - `DerivationTool` now requires instance of the `ZcashRustBackend`. And `ZcashRustBackend` isn't public type. So `DerivationTool` doesn't have any public constructor now. It can be created only via `Initializer.makeDerivationTool()` instance method. - `deriveUnifiedSpendingKey()` and `deriveUnifiedFullViewingKey()` in `DerivationTool` are now async. It is because these are using `ZcashRustBackend` inside. `DerivationTool` offers alternative (closure and combine) APIs. But downside is that there is no sync API to dervie spending key or viewing key. - Some methods of the `DerivationTool` are now static. These methods don't use anything that requires instance of the `DerivationTool` inside. [#888] Use Sourcery to generate mocks - I wrote mock for `Synchronizer` manually. And it's tedious and long and boring work. - Now `ZcashRustBackendWelding` is changed a lot so it means `MockRustBackend` must be changed a lot. So I decided to introduce `sourcery` to generate mocks from protocols so we don't have to do it manually ever. - To generate mocks go to `ZcashLightClientKit/Tests/TestUtils/Sourcery` directory and run `generateMocks.sh` script. - Your protocol must be mentioned in `AutoMockable.swift` file. Generated mocks are in `AutoMockable.generated.swift` file. [#888] Fix Offline tests - Offline tests target now runs and tests are green. - There is log of changes in tests. But logic is not changed. - Updated `AutoMockable.stencil` so sourcery is able to generate mock as actor when protocol is marked with: `// sourcery: mockActor`. - Last few updates in `ZcashRustBackendWelding`. In previous PR `rewindCacheToHeight` methods was overlooked and it didn't throw error. - Removed `MockRustBackend` and using generated `ZCashRustBackendWeldingMock` instead. - Using generated `SynchronizerMock`. [#888] Fix NetworkTests - Changed a bit how rust backend mock is used in the tests. Introduced `RustBackendMockHelper`. There are some state variables that must be preserved within one instance of the mock. This helper does exactly this. It keeps this state variables in the memory and helping mock to work as expected. [#888] Fix Darkside tests Create ZcashKeyDeriving internal protocol Use New DerivationTool that does not require RustBackend Remove duplicated methods that had been copied over [#888] Fix potentially broken tests I broke the tests because I moved `testTempDirectory` from each `TestCase` to the `Environment`. By this I caused that each tests uses exactly same URL. Which is directly against purpose of `testTempDirectory`. So now each test calls this one and store it to local variable. So each test has unique URL. [#888] Add ability to mock nonisolated methods to AutoMockable.stencil [#888] Add changelog and fix the documentation in ZcashRustBackendWelding [#888] Rename derivation rust backend protocol and remove static methods - Renamed `ZcashKeyDeriving` to `ZcashKeyDerivationBackendWelding`. So the naming scheme is same as for `ZcashRustBackendWelding`. - `ZcashKeyDerivationBackend` is now struct instead of enum. - Methods in `ZcashKeyDerivationBackendWelding` (except one) are no longer static. Because of this the respective methods in `DerivationTool` aren't also static anymore.
2023-03-31 10:10:35 -07:00
height: utxo.height
)
refreshed.append(utxo)
2021-04-08 10:18:16 -07:00
} catch {
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
logger.info("failed to put utxo - error: \(error)")
2021-04-08 10:18:16 -07:00
skipped.append(utxo)
}
}
return (inserted: refreshed, skipped: skipped)
}
}
extension CompactBlockProcessor {
enum NextState: Equatable {
case finishProcessing(height: BlockHeight)
case processNewBlocks(ranges: SyncRanges)
case wait(latestHeight: BlockHeight, latestDownloadHeight: BlockHeight)
}
@discardableResult
func figureNextBatch(
downloaderService: BlockDownloaderService
) async throws -> NextState {
try Task.checkCancellation()
do {
return try await CompactBlockProcessor.NextStateHelper.nextState(
service: service,
downloaderService: downloaderService,
latestBlocksDataProvider: latestBlocksDataProvider,
config: config,
rustBackend: rustBackend,
internalSyncProgress: internalSyncProgress
)
} catch {
throw error
}
}
}
extension CompactBlockProcessor {
2021-09-15 05:21:29 -07:00
enum NextStateHelper {
// swiftlint:disable:next function_parameter_count
static func nextState(
service: LightWalletService,
downloaderService: BlockDownloaderService,
latestBlocksDataProvider: LatestBlocksDataProvider,
config: Configuration,
[#888] Make actor from ZcashRustBackendWelding Closes #888. - `ZcashRustBackend` is actor now. So majority of methods in this actor are now async. - Some methods stayed `static` in `ZcashRustBackend`. It would be hard to pass instance of the `ZcashRustBackend` to the places where these methods are used in static manner. And it would change lot of APIs. But it isn't problem from technical perspective because these methods would be `nonisolated` otherwise. - Methods `lastError()` and `getLastError()` in `ZcashRustBackend` are now private. This makes sure that ther won't be aby race condition between other methods and these two error methods. - All the methods for which was `lastError()` used in code now throw error. So `lastError()` is no longer needed outside of the `ZcashRustBackend`. - There are in the public API related to `DerivationTool`. - `DerivationTool` now requires instance of the `ZcashRustBackend`. And `ZcashRustBackend` isn't public type. So `DerivationTool` doesn't have any public constructor now. It can be created only via `Initializer.makeDerivationTool()` instance method. - `deriveUnifiedSpendingKey()` and `deriveUnifiedFullViewingKey()` in `DerivationTool` are now async. It is because these are using `ZcashRustBackend` inside. `DerivationTool` offers alternative (closure and combine) APIs. But downside is that there is no sync API to dervie spending key or viewing key. - Some methods of the `DerivationTool` are now static. These methods don't use anything that requires instance of the `DerivationTool` inside. [#888] Use Sourcery to generate mocks - I wrote mock for `Synchronizer` manually. And it's tedious and long and boring work. - Now `ZcashRustBackendWelding` is changed a lot so it means `MockRustBackend` must be changed a lot. So I decided to introduce `sourcery` to generate mocks from protocols so we don't have to do it manually ever. - To generate mocks go to `ZcashLightClientKit/Tests/TestUtils/Sourcery` directory and run `generateMocks.sh` script. - Your protocol must be mentioned in `AutoMockable.swift` file. Generated mocks are in `AutoMockable.generated.swift` file. [#888] Fix Offline tests - Offline tests target now runs and tests are green. - There is log of changes in tests. But logic is not changed. - Updated `AutoMockable.stencil` so sourcery is able to generate mock as actor when protocol is marked with: `// sourcery: mockActor`. - Last few updates in `ZcashRustBackendWelding`. In previous PR `rewindCacheToHeight` methods was overlooked and it didn't throw error. - Removed `MockRustBackend` and using generated `ZCashRustBackendWeldingMock` instead. - Using generated `SynchronizerMock`. [#888] Fix NetworkTests - Changed a bit how rust backend mock is used in the tests. Introduced `RustBackendMockHelper`. There are some state variables that must be preserved within one instance of the mock. This helper does exactly this. It keeps this state variables in the memory and helping mock to work as expected. [#888] Fix Darkside tests Create ZcashKeyDeriving internal protocol Use New DerivationTool that does not require RustBackend Remove duplicated methods that had been copied over [#888] Fix potentially broken tests I broke the tests because I moved `testTempDirectory` from each `TestCase` to the `Environment`. By this I caused that each tests uses exactly same URL. Which is directly against purpose of `testTempDirectory`. So now each test calls this one and store it to local variable. So each test has unique URL. [#888] Add ability to mock nonisolated methods to AutoMockable.stencil [#888] Add changelog and fix the documentation in ZcashRustBackendWelding [#888] Rename derivation rust backend protocol and remove static methods - Renamed `ZcashKeyDeriving` to `ZcashKeyDerivationBackendWelding`. So the naming scheme is same as for `ZcashRustBackendWelding`. - `ZcashKeyDerivationBackend` is now struct instead of enum. - Methods in `ZcashKeyDerivationBackendWelding` (except one) are no longer static. Because of this the respective methods in `DerivationTool` aren't also static anymore.
2023-03-31 10:10:35 -07:00
rustBackend: ZcashRustBackendWelding,
internalSyncProgress: InternalSyncProgress
) async throws -> CompactBlockProcessor.NextState {
// It should be ok to not create new Task here because this method is already async. But for some reason something not good happens
// when Task is not created here. For example tests start failing. Reason is unknown at this time.
let task = Task(priority: .userInitiated) {
let info = try await service.getInfo()
[#888] Make actor from ZcashRustBackendWelding Closes #888. - `ZcashRustBackend` is actor now. So majority of methods in this actor are now async. - Some methods stayed `static` in `ZcashRustBackend`. It would be hard to pass instance of the `ZcashRustBackend` to the places where these methods are used in static manner. And it would change lot of APIs. But it isn't problem from technical perspective because these methods would be `nonisolated` otherwise. - Methods `lastError()` and `getLastError()` in `ZcashRustBackend` are now private. This makes sure that ther won't be aby race condition between other methods and these two error methods. - All the methods for which was `lastError()` used in code now throw error. So `lastError()` is no longer needed outside of the `ZcashRustBackend`. - There are in the public API related to `DerivationTool`. - `DerivationTool` now requires instance of the `ZcashRustBackend`. And `ZcashRustBackend` isn't public type. So `DerivationTool` doesn't have any public constructor now. It can be created only via `Initializer.makeDerivationTool()` instance method. - `deriveUnifiedSpendingKey()` and `deriveUnifiedFullViewingKey()` in `DerivationTool` are now async. It is because these are using `ZcashRustBackend` inside. `DerivationTool` offers alternative (closure and combine) APIs. But downside is that there is no sync API to dervie spending key or viewing key. - Some methods of the `DerivationTool` are now static. These methods don't use anything that requires instance of the `DerivationTool` inside. [#888] Use Sourcery to generate mocks - I wrote mock for `Synchronizer` manually. And it's tedious and long and boring work. - Now `ZcashRustBackendWelding` is changed a lot so it means `MockRustBackend` must be changed a lot. So I decided to introduce `sourcery` to generate mocks from protocols so we don't have to do it manually ever. - To generate mocks go to `ZcashLightClientKit/Tests/TestUtils/Sourcery` directory and run `generateMocks.sh` script. - Your protocol must be mentioned in `AutoMockable.swift` file. Generated mocks are in `AutoMockable.generated.swift` file. [#888] Fix Offline tests - Offline tests target now runs and tests are green. - There is log of changes in tests. But logic is not changed. - Updated `AutoMockable.stencil` so sourcery is able to generate mock as actor when protocol is marked with: `// sourcery: mockActor`. - Last few updates in `ZcashRustBackendWelding`. In previous PR `rewindCacheToHeight` methods was overlooked and it didn't throw error. - Removed `MockRustBackend` and using generated `ZCashRustBackendWeldingMock` instead. - Using generated `SynchronizerMock`. [#888] Fix NetworkTests - Changed a bit how rust backend mock is used in the tests. Introduced `RustBackendMockHelper`. There are some state variables that must be preserved within one instance of the mock. This helper does exactly this. It keeps this state variables in the memory and helping mock to work as expected. [#888] Fix Darkside tests Create ZcashKeyDeriving internal protocol Use New DerivationTool that does not require RustBackend Remove duplicated methods that had been copied over [#888] Fix potentially broken tests I broke the tests because I moved `testTempDirectory` from each `TestCase` to the `Environment`. By this I caused that each tests uses exactly same URL. Which is directly against purpose of `testTempDirectory`. So now each test calls this one and store it to local variable. So each test has unique URL. [#888] Add ability to mock nonisolated methods to AutoMockable.stencil [#888] Add changelog and fix the documentation in ZcashRustBackendWelding [#888] Rename derivation rust backend protocol and remove static methods - Renamed `ZcashKeyDeriving` to `ZcashKeyDerivationBackendWelding`. So the naming scheme is same as for `ZcashRustBackendWelding`. - `ZcashKeyDerivationBackend` is now struct instead of enum. - Methods in `ZcashKeyDerivationBackendWelding` (except one) are no longer static. Because of this the respective methods in `DerivationTool` aren't also static anymore.
2023-03-31 10:10:35 -07:00
try await CompactBlockProcessor.validateServerInfo(
info,
saplingActivation: config.saplingActivation,
localNetwork: config.network,
rustBackend: rustBackend
)
let latestDownloadHeight = try await downloaderService.lastDownloadedBlockHeight()
- [#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
await internalSyncProgress.migrateIfNeeded(latestDownloadedBlockHeightFromCacheDB: latestDownloadHeight)
await latestBlocksDataProvider.updateScannedData()
await latestBlocksDataProvider.updateBlockData()
[#361] Introduce ZcashError (#1005) This PR introduces `ZcashError` enum. This enum represents any error that can be thrown inside of the SDK and outside of the SDK. Also `ZcashError` is used in `LightWalletGRPCService` and handled in `CompactBlockProcessor` as example. Why enum? First I tried this with some structure which contained code, message and underlyingError. Problem was when some specific place in the SDK would like to attach some additional data to error. I didn't want to add some generic dictionary to store anything with the error. So I used enum to identify error. Each member can have specified amount of associated values. So specific error can bring some context data. And it's type safe. Each error has also a code. Relationship between errors and codes is 1:1. It may looks bit redundant but it's important. The client app now can choose how to process errors. Either identify those by the error itself or by code. Definition or errors and codes is in `ZcashErrorDefinition`. And then `ZcashError` and `ZcashErrorCode` are generated by Sourcery. Thanks to this it is easier to maintain the final code. And it gives us ability to generate any kind of documentation for the errors and codes. I created simple example of this in this PR. And it doesn't make the SDK completely dependent on the Sourcery. Final structures aren't super complicated and can be written manually if needed. [#923] Update error handling in DatabaseStorageManager.swift - cleanup of DatabaseStorageManager, not used anymore - ZcashError for SimpleConnectionProvider Revert "[#923] Update error handling in DatabaseStorageManager.swift" This reverts commit 94e028d31a0f6635800c297eb741db74c6a6ff45. Fix script which generates ZcashError [#922] Update error handling in DatabaseMigrationManager.swift Closes #922 [#923] Update error handling in DatabaseStorageManager.swift - The DatabaseStorageManager is not used so I deleted it - SimpleConnectionProvider's errors updated Fix tests [#955] Update error handling in SaplingParameterDownloader Closes #955 [#936] Update error handling in NotesDao Closes #936 [#935] Update error handling in BlockDao Closes #935 [#931] InternalSyncProgress.computeNextState doesn't need to throw Closes #931 [#950] Update error handling in rust backend Closes #949 Closes #950 [#941] Update error handling in AccountEntity Closes #941 [#928] Update error handling in FSCompactBlockRepository Closes #928 [#925] Update error handling in BlockDownloaderService (#974) - BlockDownloaderService errors updated [#924] Update error handling in BlockDownloader (#973) - BlockDownloaderStream nextBlock updated [#942] Update error handling in TransactionEntity (#977) - ZcashTransaction init errors converted to the ZcashError [#939] Update error handling in TransactionDao (#976) - TransactionRepositoryError removed and replaced with ZcashError - all TransactionDAO errors converted to ZcashError [#943] Update error handling in ZcashCompactBlock Closes #943 [#945] Update error handling in Memo Closes #945 [#934] Update error handling in Checkpoint Closes #944 Closes #934 [#938] Update error handling in PendingTransactionDao Closes #938 [#926] Update error handling in BlockEnhancer - WIP, switching to transaction repository to unblock this ticket [#926] Update error handling in BlockEnhancer - enhancer's errors done [#926] Update error handling in BlockEnhancer (#994) - cleanup [#952] Update error handling in DerivationTool Closes #952 [#932] Update error handling in BlockValidator Closes #932 [#940] Update error handling in UnspentTransactionOutputDao Closes #940 [#946] Update error handling in WalletTypes Closes #946 [#954] Update error handling in WalletTransactionEncoder Closes #954 [#953] Update error handling in PersistentTransactionManager Closes #953 [#956] Update error handling in Initializer Closes #956 [#947] Update error handling in Zatoshi (#996) - Zatoshi's errors converted to ZcashError [#927] Update error handling in UTXOFetcher (#997) - UTXOFetcher resolved Use let instead of var where applicable In the SDK `var` was used on places where `let` would be sufficient. And default strategy in Swift should use use `let` until mutability is required. So all these places are changed. No logic is changed. [#933] Update error handling in CompactBlockProcessor - CompactBlockProcessor's errors refactored to ZcashError [#933] Update error handling in CompactBlockProcessor #999 - comments addressed [#951] Update error handling in SDKSynchronizer - SDKSynchronizer's errors refactored to ZcashError [#951] Update error handling in SDKSynchronizer (#1002) - comments resolved Make DerivationTool constructor public DerivationTool.init should be public. This was removed by accident when adopting async. [#361] Add changelog
2023-04-24 14:15:20 -07:00
return await internalSyncProgress.computeNextState(
latestBlockHeight: latestBlocksDataProvider.latestBlockHeight,
latestScannedHeight: latestBlocksDataProvider.latestScannedHeight,
walletBirthday: config.walletBirthday
)
}
return try await task.value
}
}
}
- [#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
/// This extension contains asociated types and functions needed to clean up the
/// `cacheDb` in favor of `FsBlockDb`. Once this cleanup functionality is deprecated,
/// delete the whole extension and reference to it in other parts of the code including tests.
extension CompactBlockProcessor {
public enum CacheDbMigrationError: Error {
case fsCacheMigrationFailedSameURL
case failedToDeleteLegacyDb(Error)
case failedToInitFsBlockDb(Error)
case failedToSetDownloadHeight(Error)
}
/// Deletes the SQLite cacheDb and attempts to initialize the fsBlockDbRoot
/// - parameter legacyCacheDbURL: the URL where the cache Db used to be stored.
[#361] Introduce ZcashError (#1005) This PR introduces `ZcashError` enum. This enum represents any error that can be thrown inside of the SDK and outside of the SDK. Also `ZcashError` is used in `LightWalletGRPCService` and handled in `CompactBlockProcessor` as example. Why enum? First I tried this with some structure which contained code, message and underlyingError. Problem was when some specific place in the SDK would like to attach some additional data to error. I didn't want to add some generic dictionary to store anything with the error. So I used enum to identify error. Each member can have specified amount of associated values. So specific error can bring some context data. And it's type safe. Each error has also a code. Relationship between errors and codes is 1:1. It may looks bit redundant but it's important. The client app now can choose how to process errors. Either identify those by the error itself or by code. Definition or errors and codes is in `ZcashErrorDefinition`. And then `ZcashError` and `ZcashErrorCode` are generated by Sourcery. Thanks to this it is easier to maintain the final code. And it gives us ability to generate any kind of documentation for the errors and codes. I created simple example of this in this PR. And it doesn't make the SDK completely dependent on the Sourcery. Final structures aren't super complicated and can be written manually if needed. [#923] Update error handling in DatabaseStorageManager.swift - cleanup of DatabaseStorageManager, not used anymore - ZcashError for SimpleConnectionProvider Revert "[#923] Update error handling in DatabaseStorageManager.swift" This reverts commit 94e028d31a0f6635800c297eb741db74c6a6ff45. Fix script which generates ZcashError [#922] Update error handling in DatabaseMigrationManager.swift Closes #922 [#923] Update error handling in DatabaseStorageManager.swift - The DatabaseStorageManager is not used so I deleted it - SimpleConnectionProvider's errors updated Fix tests [#955] Update error handling in SaplingParameterDownloader Closes #955 [#936] Update error handling in NotesDao Closes #936 [#935] Update error handling in BlockDao Closes #935 [#931] InternalSyncProgress.computeNextState doesn't need to throw Closes #931 [#950] Update error handling in rust backend Closes #949 Closes #950 [#941] Update error handling in AccountEntity Closes #941 [#928] Update error handling in FSCompactBlockRepository Closes #928 [#925] Update error handling in BlockDownloaderService (#974) - BlockDownloaderService errors updated [#924] Update error handling in BlockDownloader (#973) - BlockDownloaderStream nextBlock updated [#942] Update error handling in TransactionEntity (#977) - ZcashTransaction init errors converted to the ZcashError [#939] Update error handling in TransactionDao (#976) - TransactionRepositoryError removed and replaced with ZcashError - all TransactionDAO errors converted to ZcashError [#943] Update error handling in ZcashCompactBlock Closes #943 [#945] Update error handling in Memo Closes #945 [#934] Update error handling in Checkpoint Closes #944 Closes #934 [#938] Update error handling in PendingTransactionDao Closes #938 [#926] Update error handling in BlockEnhancer - WIP, switching to transaction repository to unblock this ticket [#926] Update error handling in BlockEnhancer - enhancer's errors done [#926] Update error handling in BlockEnhancer (#994) - cleanup [#952] Update error handling in DerivationTool Closes #952 [#932] Update error handling in BlockValidator Closes #932 [#940] Update error handling in UnspentTransactionOutputDao Closes #940 [#946] Update error handling in WalletTypes Closes #946 [#954] Update error handling in WalletTransactionEncoder Closes #954 [#953] Update error handling in PersistentTransactionManager Closes #953 [#956] Update error handling in Initializer Closes #956 [#947] Update error handling in Zatoshi (#996) - Zatoshi's errors converted to ZcashError [#927] Update error handling in UTXOFetcher (#997) - UTXOFetcher resolved Use let instead of var where applicable In the SDK `var` was used on places where `let` would be sufficient. And default strategy in Swift should use use `let` until mutability is required. So all these places are changed. No logic is changed. [#933] Update error handling in CompactBlockProcessor - CompactBlockProcessor's errors refactored to ZcashError [#933] Update error handling in CompactBlockProcessor #999 - comments addressed [#951] Update error handling in SDKSynchronizer - SDKSynchronizer's errors refactored to ZcashError [#951] Update error handling in SDKSynchronizer (#1002) - comments resolved Make DerivationTool constructor public DerivationTool.init should be public. This was removed by accident when adopting async. [#361] Add changelog
2023-04-24 14:15:20 -07:00
/// - Throws: `InitializerError.fsCacheInitFailedSameURL` when the given URL
- [#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
/// is the same URL than the one provided as `self.fsBlockDbRoot` assuming that's a
/// programming error being the `legacyCacheDbURL` a sqlite database file and not a
/// directory. Also throws errors from initializing the fsBlockDbRoot.
///
/// - Note: Errors from deleting the `legacyCacheDbURL` won't be throwns.
func migrateCacheDb(_ legacyCacheDbURL: URL) async throws {
guard legacyCacheDbURL != config.fsBlockCacheRoot else {
[#361] Introduce ZcashError (#1005) This PR introduces `ZcashError` enum. This enum represents any error that can be thrown inside of the SDK and outside of the SDK. Also `ZcashError` is used in `LightWalletGRPCService` and handled in `CompactBlockProcessor` as example. Why enum? First I tried this with some structure which contained code, message and underlyingError. Problem was when some specific place in the SDK would like to attach some additional data to error. I didn't want to add some generic dictionary to store anything with the error. So I used enum to identify error. Each member can have specified amount of associated values. So specific error can bring some context data. And it's type safe. Each error has also a code. Relationship between errors and codes is 1:1. It may looks bit redundant but it's important. The client app now can choose how to process errors. Either identify those by the error itself or by code. Definition or errors and codes is in `ZcashErrorDefinition`. And then `ZcashError` and `ZcashErrorCode` are generated by Sourcery. Thanks to this it is easier to maintain the final code. And it gives us ability to generate any kind of documentation for the errors and codes. I created simple example of this in this PR. And it doesn't make the SDK completely dependent on the Sourcery. Final structures aren't super complicated and can be written manually if needed. [#923] Update error handling in DatabaseStorageManager.swift - cleanup of DatabaseStorageManager, not used anymore - ZcashError for SimpleConnectionProvider Revert "[#923] Update error handling in DatabaseStorageManager.swift" This reverts commit 94e028d31a0f6635800c297eb741db74c6a6ff45. Fix script which generates ZcashError [#922] Update error handling in DatabaseMigrationManager.swift Closes #922 [#923] Update error handling in DatabaseStorageManager.swift - The DatabaseStorageManager is not used so I deleted it - SimpleConnectionProvider's errors updated Fix tests [#955] Update error handling in SaplingParameterDownloader Closes #955 [#936] Update error handling in NotesDao Closes #936 [#935] Update error handling in BlockDao Closes #935 [#931] InternalSyncProgress.computeNextState doesn't need to throw Closes #931 [#950] Update error handling in rust backend Closes #949 Closes #950 [#941] Update error handling in AccountEntity Closes #941 [#928] Update error handling in FSCompactBlockRepository Closes #928 [#925] Update error handling in BlockDownloaderService (#974) - BlockDownloaderService errors updated [#924] Update error handling in BlockDownloader (#973) - BlockDownloaderStream nextBlock updated [#942] Update error handling in TransactionEntity (#977) - ZcashTransaction init errors converted to the ZcashError [#939] Update error handling in TransactionDao (#976) - TransactionRepositoryError removed and replaced with ZcashError - all TransactionDAO errors converted to ZcashError [#943] Update error handling in ZcashCompactBlock Closes #943 [#945] Update error handling in Memo Closes #945 [#934] Update error handling in Checkpoint Closes #944 Closes #934 [#938] Update error handling in PendingTransactionDao Closes #938 [#926] Update error handling in BlockEnhancer - WIP, switching to transaction repository to unblock this ticket [#926] Update error handling in BlockEnhancer - enhancer's errors done [#926] Update error handling in BlockEnhancer (#994) - cleanup [#952] Update error handling in DerivationTool Closes #952 [#932] Update error handling in BlockValidator Closes #932 [#940] Update error handling in UnspentTransactionOutputDao Closes #940 [#946] Update error handling in WalletTypes Closes #946 [#954] Update error handling in WalletTransactionEncoder Closes #954 [#953] Update error handling in PersistentTransactionManager Closes #953 [#956] Update error handling in Initializer Closes #956 [#947] Update error handling in Zatoshi (#996) - Zatoshi's errors converted to ZcashError [#927] Update error handling in UTXOFetcher (#997) - UTXOFetcher resolved Use let instead of var where applicable In the SDK `var` was used on places where `let` would be sufficient. And default strategy in Swift should use use `let` until mutability is required. So all these places are changed. No logic is changed. [#933] Update error handling in CompactBlockProcessor - CompactBlockProcessor's errors refactored to ZcashError [#933] Update error handling in CompactBlockProcessor #999 - comments addressed [#951] Update error handling in SDKSynchronizer - SDKSynchronizer's errors refactored to ZcashError [#951] Update error handling in SDKSynchronizer (#1002) - comments resolved Make DerivationTool constructor public DerivationTool.init should be public. This was removed by accident when adopting async. [#361] Add changelog
2023-04-24 14:15:20 -07:00
throw ZcashError.compactBlockProcessorCacheDbMigrationFsCacheMigrationFailedSameURL
- [#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
}
[#209] Add support for multiple instances of the SDKSynchronizer Closes #209. [#845] Introduce ZcashSynchronizerAlias enum Closes #845. [#852] SDKSynchronizer using queues label based on the alias Closes #852. [#847] Remove posibility to use DatabaseStorageManager as singleton Closes #847. [#850] Remove synchronizerConnectionStateChanged notification Closes #850. [#855] Add check if the Alias is already used Closes #855 - Added `UsedAliasesChecker` utility which is used to register aliases that are in use. - `prepare()` and `wipe()` methods now check if the current alias can't be used and if not then `InitializerError.aliasAlreadyInUse` is thrown/emitted. - Some public methods that could cause harm if used with the Alias that is already in use now throw `SynchronizerError.notPrepared`. Thanks to this the client app is forced to call `prepare()` first. And `prepare()` does check for the Alias. - Added tests for new conditions. [#849] Make InternalSyncProgress aware of the Alias Closes #849. [#853] Only instance with default Alias migrates legacy cache DB Closes #853. [#851] Apply the Alias to the URLs Closes #851. - `Initializer` now updates paths according to alias before paths are used anywhere in the SDK. - Paths update can fail. It would be incovenient for the client apps to handle errors thrown from `Initiliazer` constructor. So the error is then handled in `SDKSynchronizer.prepare()` or `SDKSynchronizer.wipe()`. [#846] Stop using SDKMetrics as singleton (#862) - metrics are not longer a singleton - tests fixed - metrics outside init of the synchronizer [#848] Make logger aware of the alias - logger is now an instance passed throughout the sdk instead of a static proxy [#848] Make logger aware of the alias (#868) - comments addressed [#848] Make logger aware of the alias (#868) - returning protocol back Fix typos [#856] Add possibility to test multiple synchronizers in the sample app Closes #856. - Added `alias` property to `Synchronizer`. - Added `SyncBlocksListViewController` which provides UI to use multiple synchronizers at once. [#209] Add changelog - Add changelog for #209. - Overall improve readability of the rendered changelog. Tickets references are now prefixed with `###` instead of `- `. Fix compilation
2023-03-22 05:47:32 -07:00
// Instance with alias `default` is same as instance before the Alias was introduced. So it makes sense that only this instance handles
// legacy cache DB. Any instance with different than `default` alias was created after the Alias was introduced and at this point legacy
// cache DB is't anymore. So there is nothing to migrate for instances with not default Alias.
guard config.alias == .default else {
return
}
- [#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
// if the URL provided is not readable, it means that the client has a reference
// to the cacheDb file but it has been deleted in a prior sync cycle. there's
// nothing to do here.
guard FileManager.default.isReadableFile(atPath: legacyCacheDbURL.path) else {
return
}
do {
// if there's a readable file at the provided URL, delete it.
try FileManager.default.removeItem(at: legacyCacheDbURL)
} catch {
[#361] Introduce ZcashError (#1005) This PR introduces `ZcashError` enum. This enum represents any error that can be thrown inside of the SDK and outside of the SDK. Also `ZcashError` is used in `LightWalletGRPCService` and handled in `CompactBlockProcessor` as example. Why enum? First I tried this with some structure which contained code, message and underlyingError. Problem was when some specific place in the SDK would like to attach some additional data to error. I didn't want to add some generic dictionary to store anything with the error. So I used enum to identify error. Each member can have specified amount of associated values. So specific error can bring some context data. And it's type safe. Each error has also a code. Relationship between errors and codes is 1:1. It may looks bit redundant but it's important. The client app now can choose how to process errors. Either identify those by the error itself or by code. Definition or errors and codes is in `ZcashErrorDefinition`. And then `ZcashError` and `ZcashErrorCode` are generated by Sourcery. Thanks to this it is easier to maintain the final code. And it gives us ability to generate any kind of documentation for the errors and codes. I created simple example of this in this PR. And it doesn't make the SDK completely dependent on the Sourcery. Final structures aren't super complicated and can be written manually if needed. [#923] Update error handling in DatabaseStorageManager.swift - cleanup of DatabaseStorageManager, not used anymore - ZcashError for SimpleConnectionProvider Revert "[#923] Update error handling in DatabaseStorageManager.swift" This reverts commit 94e028d31a0f6635800c297eb741db74c6a6ff45. Fix script which generates ZcashError [#922] Update error handling in DatabaseMigrationManager.swift Closes #922 [#923] Update error handling in DatabaseStorageManager.swift - The DatabaseStorageManager is not used so I deleted it - SimpleConnectionProvider's errors updated Fix tests [#955] Update error handling in SaplingParameterDownloader Closes #955 [#936] Update error handling in NotesDao Closes #936 [#935] Update error handling in BlockDao Closes #935 [#931] InternalSyncProgress.computeNextState doesn't need to throw Closes #931 [#950] Update error handling in rust backend Closes #949 Closes #950 [#941] Update error handling in AccountEntity Closes #941 [#928] Update error handling in FSCompactBlockRepository Closes #928 [#925] Update error handling in BlockDownloaderService (#974) - BlockDownloaderService errors updated [#924] Update error handling in BlockDownloader (#973) - BlockDownloaderStream nextBlock updated [#942] Update error handling in TransactionEntity (#977) - ZcashTransaction init errors converted to the ZcashError [#939] Update error handling in TransactionDao (#976) - TransactionRepositoryError removed and replaced with ZcashError - all TransactionDAO errors converted to ZcashError [#943] Update error handling in ZcashCompactBlock Closes #943 [#945] Update error handling in Memo Closes #945 [#934] Update error handling in Checkpoint Closes #944 Closes #934 [#938] Update error handling in PendingTransactionDao Closes #938 [#926] Update error handling in BlockEnhancer - WIP, switching to transaction repository to unblock this ticket [#926] Update error handling in BlockEnhancer - enhancer's errors done [#926] Update error handling in BlockEnhancer (#994) - cleanup [#952] Update error handling in DerivationTool Closes #952 [#932] Update error handling in BlockValidator Closes #932 [#940] Update error handling in UnspentTransactionOutputDao Closes #940 [#946] Update error handling in WalletTypes Closes #946 [#954] Update error handling in WalletTransactionEncoder Closes #954 [#953] Update error handling in PersistentTransactionManager Closes #953 [#956] Update error handling in Initializer Closes #956 [#947] Update error handling in Zatoshi (#996) - Zatoshi's errors converted to ZcashError [#927] Update error handling in UTXOFetcher (#997) - UTXOFetcher resolved Use let instead of var where applicable In the SDK `var` was used on places where `let` would be sufficient. And default strategy in Swift should use use `let` until mutability is required. So all these places are changed. No logic is changed. [#933] Update error handling in CompactBlockProcessor - CompactBlockProcessor's errors refactored to ZcashError [#933] Update error handling in CompactBlockProcessor #999 - comments addressed [#951] Update error handling in SDKSynchronizer - SDKSynchronizer's errors refactored to ZcashError [#951] Update error handling in SDKSynchronizer (#1002) - comments resolved Make DerivationTool constructor public DerivationTool.init should be public. This was removed by accident when adopting async. [#361] Add changelog
2023-04-24 14:15:20 -07:00
throw ZcashError.compactBlockProcessorCacheDbMigrationFailedToDeleteLegacyDb(error)
- [#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
}
// create the storage
[#361] Introduce ZcashError (#1005) This PR introduces `ZcashError` enum. This enum represents any error that can be thrown inside of the SDK and outside of the SDK. Also `ZcashError` is used in `LightWalletGRPCService` and handled in `CompactBlockProcessor` as example. Why enum? First I tried this with some structure which contained code, message and underlyingError. Problem was when some specific place in the SDK would like to attach some additional data to error. I didn't want to add some generic dictionary to store anything with the error. So I used enum to identify error. Each member can have specified amount of associated values. So specific error can bring some context data. And it's type safe. Each error has also a code. Relationship between errors and codes is 1:1. It may looks bit redundant but it's important. The client app now can choose how to process errors. Either identify those by the error itself or by code. Definition or errors and codes is in `ZcashErrorDefinition`. And then `ZcashError` and `ZcashErrorCode` are generated by Sourcery. Thanks to this it is easier to maintain the final code. And it gives us ability to generate any kind of documentation for the errors and codes. I created simple example of this in this PR. And it doesn't make the SDK completely dependent on the Sourcery. Final structures aren't super complicated and can be written manually if needed. [#923] Update error handling in DatabaseStorageManager.swift - cleanup of DatabaseStorageManager, not used anymore - ZcashError for SimpleConnectionProvider Revert "[#923] Update error handling in DatabaseStorageManager.swift" This reverts commit 94e028d31a0f6635800c297eb741db74c6a6ff45. Fix script which generates ZcashError [#922] Update error handling in DatabaseMigrationManager.swift Closes #922 [#923] Update error handling in DatabaseStorageManager.swift - The DatabaseStorageManager is not used so I deleted it - SimpleConnectionProvider's errors updated Fix tests [#955] Update error handling in SaplingParameterDownloader Closes #955 [#936] Update error handling in NotesDao Closes #936 [#935] Update error handling in BlockDao Closes #935 [#931] InternalSyncProgress.computeNextState doesn't need to throw Closes #931 [#950] Update error handling in rust backend Closes #949 Closes #950 [#941] Update error handling in AccountEntity Closes #941 [#928] Update error handling in FSCompactBlockRepository Closes #928 [#925] Update error handling in BlockDownloaderService (#974) - BlockDownloaderService errors updated [#924] Update error handling in BlockDownloader (#973) - BlockDownloaderStream nextBlock updated [#942] Update error handling in TransactionEntity (#977) - ZcashTransaction init errors converted to the ZcashError [#939] Update error handling in TransactionDao (#976) - TransactionRepositoryError removed and replaced with ZcashError - all TransactionDAO errors converted to ZcashError [#943] Update error handling in ZcashCompactBlock Closes #943 [#945] Update error handling in Memo Closes #945 [#934] Update error handling in Checkpoint Closes #944 Closes #934 [#938] Update error handling in PendingTransactionDao Closes #938 [#926] Update error handling in BlockEnhancer - WIP, switching to transaction repository to unblock this ticket [#926] Update error handling in BlockEnhancer - enhancer's errors done [#926] Update error handling in BlockEnhancer (#994) - cleanup [#952] Update error handling in DerivationTool Closes #952 [#932] Update error handling in BlockValidator Closes #932 [#940] Update error handling in UnspentTransactionOutputDao Closes #940 [#946] Update error handling in WalletTypes Closes #946 [#954] Update error handling in WalletTransactionEncoder Closes #954 [#953] Update error handling in PersistentTransactionManager Closes #953 [#956] Update error handling in Initializer Closes #956 [#947] Update error handling in Zatoshi (#996) - Zatoshi's errors converted to ZcashError [#927] Update error handling in UTXOFetcher (#997) - UTXOFetcher resolved Use let instead of var where applicable In the SDK `var` was used on places where `let` would be sufficient. And default strategy in Swift should use use `let` until mutability is required. So all these places are changed. No logic is changed. [#933] Update error handling in CompactBlockProcessor - CompactBlockProcessor's errors refactored to ZcashError [#933] Update error handling in CompactBlockProcessor #999 - comments addressed [#951] Update error handling in SDKSynchronizer - SDKSynchronizer's errors refactored to ZcashError [#951] Update error handling in SDKSynchronizer (#1002) - comments resolved Make DerivationTool constructor public DerivationTool.init should be public. This was removed by accident when adopting async. [#361] Add changelog
2023-04-24 14:15:20 -07:00
try await self.storage.create()
- [#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
// The database has been deleted, so we have adjust the internal state of the
// `CompactBlockProcessor` so that it doesn't rely on download heights set
// by a previous processing cycle.
[#361] Introduce ZcashError (#1005) This PR introduces `ZcashError` enum. This enum represents any error that can be thrown inside of the SDK and outside of the SDK. Also `ZcashError` is used in `LightWalletGRPCService` and handled in `CompactBlockProcessor` as example. Why enum? First I tried this with some structure which contained code, message and underlyingError. Problem was when some specific place in the SDK would like to attach some additional data to error. I didn't want to add some generic dictionary to store anything with the error. So I used enum to identify error. Each member can have specified amount of associated values. So specific error can bring some context data. And it's type safe. Each error has also a code. Relationship between errors and codes is 1:1. It may looks bit redundant but it's important. The client app now can choose how to process errors. Either identify those by the error itself or by code. Definition or errors and codes is in `ZcashErrorDefinition`. And then `ZcashError` and `ZcashErrorCode` are generated by Sourcery. Thanks to this it is easier to maintain the final code. And it gives us ability to generate any kind of documentation for the errors and codes. I created simple example of this in this PR. And it doesn't make the SDK completely dependent on the Sourcery. Final structures aren't super complicated and can be written manually if needed. [#923] Update error handling in DatabaseStorageManager.swift - cleanup of DatabaseStorageManager, not used anymore - ZcashError for SimpleConnectionProvider Revert "[#923] Update error handling in DatabaseStorageManager.swift" This reverts commit 94e028d31a0f6635800c297eb741db74c6a6ff45. Fix script which generates ZcashError [#922] Update error handling in DatabaseMigrationManager.swift Closes #922 [#923] Update error handling in DatabaseStorageManager.swift - The DatabaseStorageManager is not used so I deleted it - SimpleConnectionProvider's errors updated Fix tests [#955] Update error handling in SaplingParameterDownloader Closes #955 [#936] Update error handling in NotesDao Closes #936 [#935] Update error handling in BlockDao Closes #935 [#931] InternalSyncProgress.computeNextState doesn't need to throw Closes #931 [#950] Update error handling in rust backend Closes #949 Closes #950 [#941] Update error handling in AccountEntity Closes #941 [#928] Update error handling in FSCompactBlockRepository Closes #928 [#925] Update error handling in BlockDownloaderService (#974) - BlockDownloaderService errors updated [#924] Update error handling in BlockDownloader (#973) - BlockDownloaderStream nextBlock updated [#942] Update error handling in TransactionEntity (#977) - ZcashTransaction init errors converted to the ZcashError [#939] Update error handling in TransactionDao (#976) - TransactionRepositoryError removed and replaced with ZcashError - all TransactionDAO errors converted to ZcashError [#943] Update error handling in ZcashCompactBlock Closes #943 [#945] Update error handling in Memo Closes #945 [#934] Update error handling in Checkpoint Closes #944 Closes #934 [#938] Update error handling in PendingTransactionDao Closes #938 [#926] Update error handling in BlockEnhancer - WIP, switching to transaction repository to unblock this ticket [#926] Update error handling in BlockEnhancer - enhancer's errors done [#926] Update error handling in BlockEnhancer (#994) - cleanup [#952] Update error handling in DerivationTool Closes #952 [#932] Update error handling in BlockValidator Closes #932 [#940] Update error handling in UnspentTransactionOutputDao Closes #940 [#946] Update error handling in WalletTypes Closes #946 [#954] Update error handling in WalletTransactionEncoder Closes #954 [#953] Update error handling in PersistentTransactionManager Closes #953 [#956] Update error handling in Initializer Closes #956 [#947] Update error handling in Zatoshi (#996) - Zatoshi's errors converted to ZcashError [#927] Update error handling in UTXOFetcher (#997) - UTXOFetcher resolved Use let instead of var where applicable In the SDK `var` was used on places where `let` would be sufficient. And default strategy in Swift should use use `let` until mutability is required. So all these places are changed. No logic is changed. [#933] Update error handling in CompactBlockProcessor - CompactBlockProcessor's errors refactored to ZcashError [#933] Update error handling in CompactBlockProcessor #999 - comments addressed [#951] Update error handling in SDKSynchronizer - SDKSynchronizer's errors refactored to ZcashError [#951] Update error handling in SDKSynchronizer (#1002) - comments resolved Make DerivationTool constructor public DerivationTool.init should be public. This was removed by accident when adopting async. [#361] Add changelog
2023-04-24 14:15:20 -07:00
let lastScannedHeight = try await transactionRepository.lastScannedHeight()
await internalSyncProgress.set(lastScannedHeight, .latestDownloadedBlockHeight)
- [#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
}
func wipeLegacyCacheDbIfNeeded() {
guard let cacheDbURL = config.cacheDbURL else {
return
}
guard FileManager.default.isDeletableFile(atPath: cacheDbURL.pathExtension) else {
return
}
try? FileManager.default.removeItem(at: cacheDbURL)
}
}
extension SyncRanges {
/// Tells whether the state represented by these sync ranges evidence some sort of
/// outdated state on the cache or the internal state of the compact block processor.
///
/// - Note: this can mean that the processor has synced over the height that the internal
/// state knows of because the sync process was interrupted before it could reflect
/// it in the internal state storage. This could happen because of many factors, the
/// most feasible being OS shutting down a background process or the user abruptly
/// exiting the app.
/// - Returns: an ``Optional<BlockHeight>`` where Some represents what's the
/// new state the internal state should reflect and indicating that the cache should be cleared
/// as well. c`None` means that no action is required.
func shouldClearBlockCacheAndUpdateInternalState() -> BlockHeight? {
guard self.downloadedButUnscannedRange != nil else {
return nil
}
guard
let latestScannedHeight = self.latestScannedHeight,
let latestDownloadedHeight = self.latestDownloadedBlockHeight,
latestScannedHeight > latestDownloadedHeight
else { return nil }
return latestScannedHeight
}
}