Commit Graph

68 Commits

Author SHA1 Message Date
Lukas Korba ffc7fd1be9 [#1412] Review wipe function and in memory values
- The wipe() is now resetting local in memory values of latestBlocksDataProvider. In some case this could cause a reset of CBP's state machine context sooner than it was supposed to, resulting in corrupted sync.
2024-04-16 16:48:20 +02:00
Jack Grigg 86defc8b4a Remove `AccountRepository`
This removes the last direct access to the `accounts` table; all access
now goes through the Rust FFI.
2024-03-15 15:26:44 +00:00
Lukas Korba e51f425c54 [#1369] SynchronizerState refactor
- plural of account balances refactor to singular

[#1369] SynchronizerState refactor

- transaprent balance removed from SynchronizerState
- all balances are now handled with AccountBalance

[#1369] SynchronizerState refactor and balances cleanup

- WalletBalance has been removed from the SDK, replaced with AccountBalance
- public APIs for individual balances (getTransparent, getShielded, getShieldedVerfied) have been removed from the SDK, replaced with getAccountBalance
- tests refactored

[#1369] SynchronizerState refactor and balances cleanup

- dark side tests refactored

[#1369] SynchronizerState refactor and balances cleanup (#1372)

- addressed comments

[#1369] SynchronizerState refactor

- ZcashError for spending key does not belong to the wallet
2024-02-12 17:41:26 +01:00
Lukas Korba 99d4821769 [#1368] Handle any lightwalletd error with retry logic
- The retry logic was implemented for blockStream errors only but this PR generalize it for any lightwalletd error
2024-02-12 17:40:28 +01:00
Lukas Korba c7369057f1 [#1153] Allow runtime switch of lightwalletd servers
- new public API switchTo(endpoint:) implemented

[#1153] Allow runtime switch of lightwalletd servers

- API documented
- code cleaned up

[#1153] Allow runtime switch of lightwalletd servers

- mocks generated

[#1153] Allow runtime switch of lightwalletd servers (#1373)

- sever validation added

[#1153] Allow runtime switch of lightwalletd servers (#1373)

- enhanced validation of the server

[#1153] Allow runtime switch of lightwalletd servers (#1373)

- new ZcashError.synchronizerServerSwitch that represents the state when the endpoint fails validation

[#1153] Allow runtime switch of lightwalletd servers (#1373)

- ZcashError definition update

[#1153] Allow runtime switch of lightwalletd servers (#1373)

- addressed comments

[#1153] Allow runtime switch of lightwalletd servers (#1373)

- changelog revert according to proposal
2024-02-12 17:13:08 +01:00
Jack Grigg ded20fe7b0 Migrate to in-progress version of FFI backend 0.5.0
Includes:
- Exposed `WalletSummary`.
- Exposed transaction proposals.
- `ScanSummary` returned from `ZcashRustBackend.scanBlocks`.

Closes Electric-Coin-Company/zcash-swift-wallet-sdk#1259.
Closes Electric-Coin-Company/zcash-swift-wallet-sdk#1299.
2024-01-29 09:47:14 -08:00
Lukas Korba f2a2dfb03c [#1351] Recover from block stream issues
- changelog updated
- block stream errors are now handled as a special case of error, retry logic is triggered but at most 3-times in case of service being truly down
- the failure is not passed to the clients so ideally the false positive errors are reduced as well as the delay in the sync time

[#1351] Recover from block stream issues (#1352)

- typo fixed
2024-01-25 13:35:46 +01:00
Lukas Korba 1dde31e41a [#1336] Tweaks for sdk metrics
- the logs are split so it's not a huge string
- the log method is async
- added a new log with balances

[#1336] Tweaks for sdk metrics

- wait a bit so the logs are sorted in time

[#1336] Tweaks for sdk metrics

- wait a bit so the logs are sorted in time

[#1336] Tweaks for sdk metrics

- wait a bit so the logs are sorted in time

[#1336] Tweaks for sdk metrics

- cleanup

[#1336] Tweaks for sdk metrics

- changelog update

[#1336] Tweaks for sdk metrics

- checkpoints updated

[#1336] Tweaks for sdk metrics

- changelog typos fixed

[#1336] Tweaks for sdk metrics

- mocks generated
2023-12-15 09:01:04 +01:00
Lukas Korba 3e263f0c35 [#1325] Log metrics
- the logger has been extended to log the level as well
- there is only partial match of levels between SDK logger levels, OSLogEntryLogLevel and OSLogType so only debug, info, error are fully matched
- this is a base for the exporter on client's side

[#1325] Log metrics

- typos fixed

[#1325] Log metrics

- scan metric logs added

[#1325] Log metrics

- Scan & Enhance logs

[#1325] Log metrics

- checkpoints updated
- every CBP action is measured separately and collects the data, when the sync is done it dumps overview of the run to the logger
- next run clears out the previous data and starts to collect fresh reports for the run

[#1325] Log metrics (#1327)

- changelog update

[#1325] Log metrics (#1327)

- SDKMetrics updated to be mockable
- unit test updated

[#1325] Log metrics (#1327)

- performance tests cleaned out

[#1325] Log metrics (#1327)

- Network tests buildable again
2023-12-12 08:59:52 +01:00
Lukas Korba e763e29dc1 [#1301] foundTransactions don't emit after rewind
- There was a reset missing in the rewind() call. This method is a direct call affecting the state of the compact block processor but the ActionContext has been handled only in the synchronization pipeline. Manual reset was needed to reset the last enhanced height.
- tests added
2023-10-12 15:59:47 +02:00
Lukas Korba 95c9746303 cbp_state_machine updated
- cbp_state_machine.png as well as .puml files updated to reflect the State Machine changes after SBS
- one small cleanup of clearCache, no longer needed to be called twice, only after enhance (missed removal of linear sync)
2023-09-13 15:25:25 +02:00
Lukas Korba 4b45c15a96 Comments addressed
- all comments from the review (round 1) resolved
2023-09-13 09:24:26 +02:00
Lukas Korba fdcb52c088 [#1240] Remove previous progress reporting
- CompactBlockProgress has been update to use syncProgress only
- CompactBlockProgressUpdate removed
- BlockProgress removed
- enhance and fetch progresses removed
- progressPartialUpdate refactored to syncProgress
- tests updated
2023-09-11 09:30:44 +02:00
Lukas Korba d956e9940b [#1230] Remove linear sync from the SDK
- concept of linear syncing fully removed from the SDK, it's fully replaced with Spend-before-Sync
- BlockDAO - table blocks is no longer used, removed from the SDK and all it's associated getLastBlocks/ScannedHeights as with it
- concept of pending transactions removed from the SDK
- unit tests refactored
2023-09-08 07:40:08 +02:00
Lukas Korba 95536638e5 [#1176] Cover Spend before Sync with tests
- WIP

[#1176] Cover Spend before Sync with tests

- next batch of updates

[#1176] Cover Spend before Sync with tests

- last batch of fixes and new tests

[#1176] Cover Spend before Sync with tests

- package.resolved updated

[#1176] Cover Spend before Sync with tests (#1212)

- added tests for brand new actions related Spend before Sync
- RewindActionTests
- UpdateChainTipActionTests
- UpdateSubtreeRootsActionTests
- ProcessSuggestedScanRangesActionTests
2023-09-07 13:23:50 +02:00
Lukas Korba d9f92ec7a9 [#1181] Correct computation of progress for Spend before Sync
- the computation of progress changed, the total range is computed, that way it works for any kind of sync algorithm
- the progress depends on finished scan action, whenever it processes some blocks, it's counted up
- the final progress is a ratio between these new values
2023-09-07 13:23:47 +02:00
Lukas Korba 1205f402c6 [#1180] Handle production GetSubtreeRootsArg
- the value 65536 set only for testnet
2023-09-07 13:23:47 +02:00
Lukas Korba 9676c7fc67 [#1189] Implement continuity check and RewindAction
- RewindAction added
- rust's isContinuityError() emulated on iOS side
- verify scan range is now properly handled with rewind as well as check for continuity error

[#1189] Implement continuity check and RewindAction (#1195)

- TODO cleanup
2023-09-07 13:23:47 +02:00
Lukas Korba c894f46ce9 [#1188] Working prototype of SbS
- cleaned up the code
- ScanAlgorithm enum added to the SDK
- preferred sync algorithm set to .linear as default but can be changed to Spend before Sync as the Initializer.init parameter

[#1188] Working prototype of SbS

- error codes for failure states in the SbS State Machine changes added

[#1188] Working prototype of SbS (#1192)

- offline tests fixed
2023-09-07 13:23:47 +02:00
Lukas Korba 88019ebff1 [#1169] Step 5 -Get the suggested scan ranges from the wallet database
- initial action in place
- verify loop WIP

[#1169] Step 5 -Get the suggested scan ranges from the wallet database

- firstUnenhancedHeight fix

[#1169] Step 5 -Get the suggested scan ranges from the wallet database

- first working version implemented
- download, scan and enhance actions are dependent on the context values only
2023-09-07 13:23:47 +02:00
Lukas Korba 27e417a669 [#1167] Step 3 - Download chain tip metadata from lightwalletd
- update chain tip action added

[#1167] Step 3 - Download chain tip metadata from lightwalletd

- roots removed from the ActionContext

[#1167] Step 3 - Download chain tip metadata from lightwalletd

- fallback to linear sync until next step is implemented

[#1167] Step 3 - Download chain tip metadata from lightwalletd

- offline tests fixed
2023-09-07 13:23:47 +02:00
Lukas Korba 8f7294c3e1 [#1165] draft
draft

[#1165] Step 1 - Download note commitment tree data from lightwalletd

- code cleanup after draft

[#1165] Step 1 - Download note commitment tree data from lightwalletd

- UpdateSubtreeRootsAction added, ensuring the roots are downloaded and stored in the DB

[#1165] Step 1 - Download note commitment tree data from lightwalletd

- added ZcashError for putSaplingSubtreeRoots failure
- cleaned up action

[#1165] Step 1 - Download note commitment tree data from lightwalletd

- demo app config temporarily updated to Nighthawk server

[#1165] Step 1 - Download note commitment tree data from lightwalletd

- file header updated

[#1165] Step 1 - Download note commitment tree data from lightwalletd (#1174)

- demo app config cleaned up

[#1165] Step 1 - Download note commitment tree data from lightwalletd (#1174)

- offline tests fixed
2023-09-07 13:23:47 +02:00
Lukas Korba 5ac2121230 [#1208] Bitrise fails to build
- hotfix for explicit use of self in a Task, CI fails to build it without it
2023-08-23 17:29:42 +02:00
Jack Grigg 6eb39561ec Migrate to Rust backend with fast spendability support 2023-07-19 18:13:59 +01:00
Lukas Korba 34af1f1611 [#1140] ClearCache action before anything starts
- draft

[#1140] ClearCache action before anything starts

- ClearCache action right after the idle action, clearing out metadata so the sync process can be fully restored from the DB and live blockchain values only.
- InternalSyncProgress removed
- InternalSyncProgressStorage removed
- Sync process control logic updated, controlled by latestScannedHeight and firstUnenhancedHeight only
- cleaned up unused code

[#1140] ClearCache action before anything starts

- ChecksBeforeSyncAction removed
- Offline tests fixed

[#1140] ClearCache action before anything starts

- fixed injection of a wallet birthday, the sync range must start with wallet BD instead of lower bound

[#1140] ClearCache action before anything starts

- Network tests fixed
- DarkSideTests partially fixed

[#1140] ClearCache action before anything starts

- rewind actions extension in compact block processor added

[#1140] ClearCache action before anything starts

- draft

[#1140] ClearCache action before anything starts

- DarkSideTests fixed

[#1140] ClearCache action before anything starts

- SyncRanges modified to be even less dependent on ranges, now it holds just 3 values (latest block height, latest scanned height if any, first unenhanced height if any), the rest is computed on the fly

[#1140] ClearCache action before anything starts

- SyncRanges struct not anymore, refactored to SyncControlData, holding just 3 mentioned values

[#1140] ClearCache action before anything starts

- cleanup

[#1140] ClearCache action before anything starts (#1148)

- TODO solved, the UTXOs fetcher doesn't work with range anymore, therefore reporting 100%
2023-06-28 12:34:41 +02:00
Michal Fousek 21a3c06b00 [#700] CompactBlockProcessor as state machine proof of concept
- For now I created `CompactBlockProcessorNG` where I started with
  implementation of the state machine. I did it to not break the rest of
  the SDK. This change will be merged to the feature branch. And before
  it is merged to `main` branch code from `CompactBlockProcessorNG` will
  be moved to `CompactBlockProcessor`.
- The new code is not used. It just shows and explains how it is done.
  It is proof of concept.
- I did put either commented current code or comment to some places to
  explain what should be done there.
- New important data types:
  - `ActionContext` is context that can hold any data that needs to be
    shared between actions. For example sync ranges or current state.
  - `CBPState` is state of the `CompactBlockProcessor`. Each state is
    handled by one action. This doesn't apply to terminal states like
    `finished` or `failed`.
  - `ActionProgress` is very similar to `CompactBlockProgress`.
    Different actions reports progress differently and `ActionProgress`
    represents this.
  - `Action` is protocol that defines API of an action. It has one run
    method that executes the code of the action
- CBP first creates actions for (almost) each state in `makeActions()`
  method. Then the "magic" is done in `CompactBlockProcessorNG.run()` method.
  Here is main loop which takes action for current state and execute it.
  It's expected that action does it's work and then updates the context
  with new state. And this happens until some terminal state
  (`finished`, `failed`, `stopped`) is reached.
- After the transition to state machine API of the
  `CompactBlockProcessor` should stay the same. No changes should be
  required in `SDKSynchronizer`.

[#700] Add documentation for CompactBlockProcessor state machine

- plantuml tool is used to generate diagram.

[#1054] Add config to state machine CBP

Closes #1054

[#1043] Implement DownloadAction

Closes #1043

[#1049] Implement ValidateAction

Closes #1049

[#1050] Implement ValidateServerAction

Closes #1050

[#1056] Add constructors to state machine CBP

Closes #1056

[#1061] Add failure methods for state machine CBP

Closes #1061

[#1055] Implement retry timer to state machine CBP

Closes #1055

[#1057] Implement start for state machine CBP

Closes #1057

[#1058] Implement stop for state machine CBP

Closes #1058

[#1052] Implement AfterSyncHooksManager when using state machine CBP

Closes #1052

[#1060] Implement wipe for state machine CBP

Closes #1060

[#1059] Implement rewind for state machine CBP

Closes #1059

[#700] Add idle state to CBP state machine

This is required so the CBP can detect start of the sync process.

[#700] Implement sending of some events from CompactBlockProcessorNG

[#700] Implement progress reporting in state machine CBP

[#1045] Implement FetchUTXOsAction

- draft of the fetching

[#1045] Implement FetchUTXOsAction

- updated the way Actions communicate data back to the CBP
- used this mechanism to pass result of utxos fetch so it's passed to the SDKSynchronizer as an Event

[#1042] Implement ComputeSyncRangesAction

Closes #1042

[#700] Implement cache clearing when some actions fail

[#1043] Fix batch range computation in DownloadAction

[#1046] Implement SaplingParamsAction

- action for sapling param files finished

[#1048] Implement ScanDownloadedButUnscannedAction

- scan downloaded but unscanned blocks

[#1047] Implement ScanAction

- scan action with the proper ranges computed

[#1047] Implement ScanAction (#1085)

- fixed logger message

[#1044] Implement EnhanceAction

Closes #1044

[#1041] Implement ClearCacheAction

Closes #1041

[#1040] Implement ClearAlreadyScannedBlocksAction

Closes #1040

[#1039] Implement ChecksBeforeSyncAction

Closes #1039

[#700] Make CBP state machine work

[#1050] Implement ValidateServerAction

- broken tests commented out and tracked in the tickets
- new test for ValidateServerAction

[#1051] Update how progress is computed after switch to state machine

Closes #1051

- new proposal for the progress computation
- OverallProgress value is passed to the Synchronizer as a Float
- OverallProgress is a result of fetch, scan and enhance operations
- Order of actions no longer influences the computation
- Actions report partial updates, CompactBlockProgress actor holds current state and computes the OverallProgress

[#1049] Implement ValidateAction

- synchronizer offline tests updated so it compiles, review is requested in a different ticket
- ValidateAction tests added
- BlockValidator mock generated

[#1047] Implement ScanAction

- ScanAction tests
- refactor of validateAction -> validateServerAction
- generated few more mocks for the DI

[#1045] Implement FetchUTXOsAction

- FetchUTXOsAction tests
- UTXOFetcher mocks

[#1045] Implement FetchUTXOsAction

- enhanced with mocked values and more checks

[#1046] Implement SaplingParamsAction

- SaplingParamsAction tests
- added TODO for TestCoordinator reset()
- SaplingParametersHandler mock added

[#1046] Implement SaplingParamsAction

- SaplingParamsAction tests
- added TODO for TestCoordinator reset()
- SaplingParametersHandler mock added

[#1046] Implement SaplingParamsAction

- rebased so I get functionality of improved mock checks
- enhanced SaplingParamsAction tests
- enhanced ValidateAction tests
- enhanced ScanAction tests

[#1046] Implement SaplingParamsAction

- scanAction tests more checks added

[#1044] Implement EnhanceAction

- EnhanceAction tests focused on 2 different methods:
- decideWhatToDoNext covered separately, decisions where the state machine goes next
- run tests for different cases
- new mocks generated for enhacer
- some typos fixed

[#1044] Implement EnhanceAction (#1107)

- empty assert messages fixed

[#700] Get rid of ScanDownloadedButUnscannedAction

Before the state machine download and scan was called in one loop. And
processing range for one batch was same for both of them. Therefore
there was code which scanned downloaded but not scanned blocks.

But now download and scan are independent. So it is possible to remove
`ScanDownloadedButUnscannedAction`.

[#700] Make NetworkTests compilable

Some tests are disabled for now (list is in #1115). And `NetworkTests`
can be compiled and all the enabled tests work.

[#1043] Implement DownloadAction

- DownloadAction tests
- BlockDownloader mock

[#1043] Implement DownloadAction (#1110)

- support functions set to private

[#1039] Implement ChecksBeforeSyncAction

- ChecksBeforeSyncAction tests
- all support functions in Action tests are set to private
- let _ = -> _ = refactor
- CompactBlockRepository mock added

[#1040] Implement ClearAlreadyScannedBlocksAction

- Implement ClearAlreadyScannedBlocksAction tests
- CompactBlockRepository mock added

[#1041] Implement ClearCacheAction

- ClearCacheAction tests
- CompactBlockRepository mock added

[#1042] Implement ComputeSyncRangesAction

- ComputeSyncRangesAction tests
- fixed all tests after merge of latest SDK changes related InternalSyncProgress
- all actions marked as final class

[#1042] Implement ComputeSyncRangesAction (#1120)

- Custom LatestBlocksDataProviderMock removed from the project

[#1122] Implement FileManager protocol and dependency

- ZcashFileManager implemented
- MigrateLegacyCacheDBAction refactored to be dependent on ZcashFileManager
- ZcashFileManager mock added

[#1122] Implement FileManager protocol and dependency (#1124)

- code cleanup

[#1121] Implement MigrateLegacyCacheDBAction

- MigrateLegacyCacheDBAction tests WIP
- tests naming cleanup

[#1121] Implement MigrateLegacyCacheDBAction

- MigrateLegacyCacheDBAction tests finished

[#700] Fix DarksideTests

Closes #1102

Some tests that can't be compiled are disabled for now. List is in #1126.

This PR contains multiple fixes. Most of the fixes is done in the code.
Not in the tests. That is good news.

Fixes:
- `config` inside `CompactBlockProcessor` can be updated during the
  tests. And it must be also updated inside the actions. So
  `ConfigProvider` is added and it is wrapper for config that is passed
  to any instance of `Action` and provides updated config.
- Fixed `EnhanceAction`. Now it should update all the blocks in the
  enhance range even when the remaining count of blocks is lower than
  1000.
- Fixed `fail()` and `validationFailed()`. These two were canceling
  `syncTask`. But that stopped run loop in a bad way.

[#1129] Final check of all State Machine Action tests

- XTCAsset messages checked
- test naming checked and fixed

[#1126] Fix DarksideTests in state machine branch

Closes #1126

Fix offline tests

Closes #1098
Closes #1095
Closes #1094

Most of the tests is removed. Either the code that was tested doesn't
exists. Or now tests for state machine actions do this work.

[#1115] Fix NetworkTests in state machine branch

Closes #1115

[#700] Fix progress reporting

Some actions in the sync process may not run. For example there are no
transactions to enhance and therefore there is no enhance progress. And in
cases like this computation of final progress won't work properly.
So let's fake 100% progress at the end of the sync process.
2023-05-30 15:01:42 +02:00
Michal Fousek c0c0c426d5 [#1111] Change storage for InternalSyncProgress
Closes #1111

- `InternalSyncProgress` has now new disk storage implementation:
  `InternalSyncProgressDiskStorage`.
- When then `UserDefaults` was used as disk storage there were no IO errors
  to handle. But now the code in `InternalSyncProgressDiskStorage`
  writes to files and reads from files. So there are errors to handle.
  Because of this protocol `InternalSyncProgressStorage` changed a bit
  and API of `InternalSyncProgress` changed a bit. Now all the functions
  throws.
- It is possible to make progress storage IO errors silent but I think
  that storing of the progress is very essential to the sync process. So
  I think that when progress storage fails then the sync process should
  fail.
- `Initializer` has new parameter `generalStorageURL`. It is directory
  where `InternalSyncProgressDiskStorage` stores progress files. In
  future this can be used for storing any data the SDK wants.
2023-05-22 20:42:11 +02:00
Michal Fousek d091660b79 [#1016] Rebuild download stream periodically while downloading
- Rebuild download stream in `BlockDownloaderImpl` each 10 batches. So
  currently stream downloads 1000 blocks and then new stream is created.
- Memory stays between 60MB and 70MB during sync in the Sample app.
2023-05-17 10:36:02 +02:00
Francisco Gindre f98692c0ea
[#781] This fixes test `testMaxAmountMinusOneSend` by creating two se… (#1034)
* [#781] This fixes test `testMaxAmountMinusOneSend` by creating two separate
tests:
  - testMaxAmountMinusOneSendFails
  - testMaxAmountSend

Also includes new functionality that tracks sent transactions so
that users can be notified specifically when they are mined and uses "idea B" of
issue #1033.

closes #1033
closes #781

* Fix tests
2023-05-10 17:13:29 -03:00
Lukas Korba 44e17ca042 [#843] Simplify Synchronizer Status
- SyncStatus refactored to InternalSyncStatus, so the SDK works internally with the SyncStatus as previously
- new SyncStatus is a computed property that maps InternalSyncStatus to simplified SyncStatus

[#843] Simplify Synchronizer Status (#1010)

- simplification of SyncStatus done
- % computation moved to the mapping function so the rest of the SDK works just like before
- fixed unit tests
- new unit tests checking the boundaries of the new progress

[#843] Simplify Synchronizer Status (#1010)

- removed commented code

[#843] Simplify Synchronizer Status (#1010)

- package.resolved

[#843] Simplify Synchronizer Status (#1010)

- fixed dark side tests

[#843] Simplify Synchronizer Status (#1010)

- package.resolved
2023-05-09 12:35:49 +02:00
Michal Fousek 5d2b2298b5 [#1012] Introduce dependency injection in the SDK
Closes #1012

- This is the first change for the dependency injection. This change
  adds `DIContainer` which is used to register and resolve dependencies.
- Then this change shows how `DIContainer` can be used to resolve
  dependencies. And it also shows how to mock dependencies in tests.
- Constructors of `Initializer` are changed to support mocking of
  depedendencies. But it doesn't affect public API in any way.
- Depedencies are registered in `Dependencies.setup()`. Then in the code
  `container.resolve(SomeType.self)` is called to get instance of the
  dependency.
- `ZcashTestCase` class is added. It inherits from `XCTestCase` and
  should be used for base class in tests. `ZcashTestCase` takes care of
  creation of `DIContainer` for dependencies mocking. In future we can
  maybe move there more things that are used in each test.
- Lot is missing here. Not all the code is using dependency injection.
  Tests for `DIContainer` are missing. Only `OfflineTests` work now
  (other tests can't be even compiled). It will be added in future
  changes.
2023-05-08 14:58:49 +02:00
Michal Fousek 84d8002ddb Fix tests related to blocks downloading
- Call `setSyncRange()` in tests.
- Little update to `BlockDownloader` API so it makes more sense.
2023-05-08 11:08:54 +02:00
Francisco Gindre f5e7c027af
[#1001] Remove PendingDb in favor of `v_transactions` and `v_tx_output` Views (#1001)
Removes `PendingTransactionEntity` and all of its related components.
Pending items are still tracked and visualized by the existing APIs
but they are retrieved from the `TransactionRepository` instead by
returning `ZcashTransaction.Overview` instead.

`pendingDbURL` is removed from every place it was required. Its
deletion is responsibility of wallet developers.

`ClearedTransactions` are now just `transactions`.

`MigrationManager` is deleted. Now all migrations are in charge of
the rust welding layer.

`PendingTransactionDao.swift` is removed.

Implementation of `AccountEntity` called `Account` is now `DbAccount`

`ZcashTransaction.Overview` can be checked for "pending-ness" by calling
`.isPending(latestHeight:)` latest height must be provided so that minedHeight
can be compared with the lastest and the `defaultStaleTolerance` constant.

`TransactionRecipient` is now a public type.

protocol `PendingTransactionRepository` is removed.

`TransactionManagerError` and `PersistentTransactionManager` are deleted.

`OutboundTransactionManager` is deleted and replaced by `TransactionEncoder`
which now incorporates `submit(encoded:)` functionality

`WalletTransactionEncoder` now uses a `LightWalletService` to submit the
encoded transactions.

Add changelog changes

Delete references to PendingDb from tests and documentation.

Fixes some typos. Adds the ability to trace transaction repository
SQL queries from test

Fix rebase conflicts and generate code

[#837] Memo tests regarding transparent address

Closes #837

Add model for transaction output

Point to FFI branch

Fix issue where sync wouldn't resume after wipe. Becasue GRPC
channel would be closed

Fix Tests

Fix testPendingTransactionMinedHeightUpdated

Fix testLastStates

[#921] Fix  broken SynchronizerDarksideTests

Add ZcashTransaction.Output API to Synchronizer

Changelog + comment fix

Add Assertions for transaction outputs and recipients

Point to FFI 0.3.1

Fix Demo App Compiler errors

Fix Demo App Compiler errors

fix cacheDb warnings

Fix Tests and compiler errors of rebase

build demo app

Remove `ZcashTransaction.Sent` and `.Received`. Add `.State` and tests

Fix SPM warning

PR Suggestions

Removes errors that are not used anymore

fix warnings
2023-05-05 14:30:47 -03:00
Michal Fousek 0032fedde7 [#442] Introduce parallel downloading and scanning
- `BlockDownloaderImpl` is changed. It now spawns detached Task to
  download blocks. So blocks can be downloaded in parallel with scanning
  process.
- `Synchronizer.stop()` is no longer async.
- Blocks cache cleaning is changed. It's not possible to drop the whole
  cache now. There are some blocks pre-downloaded which weren't scanned
  yet.
2023-05-05 09:35:43 +02:00
Lukas Korba 4197436668 [#1011] Improve end of the sync process
- added check for mined blocks, if yes, the next batch is called
2023-05-04 10:11:57 +02:00
Michal Fousek 724d410fad
[#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 94e028d31a.

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 18:15:20 -03:00
Michal Fousek 7b3b45adca
Merge pull request #978 from zcash/969_clear_cache_on_error
[#969] Clear blocks cache when error occurs
2023-04-18 14:26:46 +02:00
Michal Fousek 488864ec55 [#969] Clear blocks cache when error occurs
Closes #969.
2023-04-18 12:41:12 +02:00
Lukas Korba 99b24c2081
[#908] Add last and latest blocks data to Synchronizer State (#911)
- attached to the processor's timer
- added latest scanned time and latest block height
- sample app showing the new values alongside with the %
- unit tests fixed
- latestBlock() API added
- the transaction repository is no longer used to update the exposed values during the syncing
2023-04-14 09:08:37 +02:00
Michal Fousek 2bbc5800bd [#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-04-11 17:51:28 +02:00
Francisco Gindre 6b7fbdd908
[#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 09:02:05 -03:00
Michal Fousek 8983b01f6c Rename Single and Completable 2023-04-03 17:19:40 +02:00
Lukas Korba 16d70cfead
[#896] Fix SDK compilation fail caused by Swift 5.8 (#897)
- Fixed the guard with explicit self
2023-04-03 09:16:07 +02:00
Michal Fousek c4f7f6ff1e [#469] Make ZcashRustBackendWelding async
Closes #469.

- Methods defined in `ZcashRustBackendWelding` protocol which are doing
  some IO operations are now async.
- `Initializer` no longer have methods to get balance. Only
  `Synchronizer` now have these methods. These methods are newly async.
  And `Initilializer` doesn't have alternative APIs.
- There is lot of changes in tests but those are mostly adding `await`.
  No logic is changed.
2023-03-30 19:08:56 +02:00
Michal Fousek 3971f80eef [#484] Use async for TransactionsRepository
Closes #484.

- `TransactionRepository` has async API. `Synchronizer` and alternative
  APIs are updated accordingly.

These methods and properties in the `Synchronizer` are async now:
- `cancelSpend(transaction:)`
- All the variants of the `getMemos(for:)` method.
- All the variants fo the `getRecipients(for:)` method.
- `allConfirmedTransactions(from:limit:)`
- `pendingTransactions`
- `clearedTransactions`
- `sentTransactions`
- `receivedTransactions`
2023-03-28 10:17:14 +02:00
Michal Fousek 5c979f42e6 [#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-27 20:42:52 +02:00
Michal Fousek c2d9c6f1e8 [#871] Cleanup internals of the SDK and use async where applicable
Closes #871.
2023-03-27 16:16:42 +02:00
Michal Fousek ce83dcef12 [#870] LightWalletGRPCService is using only async streamer
Closes #870.
2023-03-27 13:45:22 +02:00
Michal Fousek 436fa1fc47 [#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-21 22:47:19 +01:00
Michal Fousek a38e8134b8 [#724] Switch from NotificationCenter to Combine
Closes #724

- All the notifications are gone. Only
  `synchronizerConnectionStateChanged` stayed because it's used
  internally. Let's deal with this one in another task.
- Synchronizer has now two new publishers (`stateStream` and
  (`eventStream`) which are used to notify the client app about
  what is going on. These publishers replace notifications.
- There is also new property `latestState` which can be used to get the
  SDK state in synchronous manner.
- `SDKSynchronizer.status` is no longer public. It is used internally to
  refresh `latestState` and emit new values from `stateStream.
- When `SDKSynchronizer.status` is update `notify()` function is
  triggered. And this function is now responsible for generating new
  snapshot of `SynchronizerState` and updating `latestState` and
  `stateStream`.
2023-03-17 10:18:51 +01:00