Commit Graph

45 Commits

Author SHA1 Message Date
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
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
Matthew Watt 58b99c8fb1
[#1013] - Enable more granular control over logging behavior (#1014)
* Add new model for logging configuration

* Fix the example app and update the changelog
2023-05-02 16:59:49 -03:00
Michal Fousek 88e120509b
Merge pull request #1007 from Chlup/ZcashKeyDerivationBackend_non_async
Make all methods in ZcashKeyDerivationBackendWelding non async
2023-04-25 16:23:48 +02:00
Michal Fousek 5f162d01f8 Make all methods in ZcashKeyDerivationBackendWelding non async
It looks like that some methods in `ZcashKeyDerivationBackendWelding`
were left async by mistake. There is no reason for any method there to
be async.

After this change no method in `DerivationTool` has to async. It makes
things much easier.
2023-04-25 16:16:04 +02:00
Francisco Gindre 86458ea76a
[#644] AdvancedReOrg Tests fails when running Lightwalletd on `master` (#1006)
Fixes nonce paramenter in darkside api. also corrects tests block staging
for the failing tests

closes #644
2023-04-25 10:41:03 -03:00
Michal Fousek 34db6b594a Make DerivationTool constructor public
DerivationTool.init should be public. This was removed by accident when
adopting async.
2023-04-24 16:24:36 +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 96f763d42f [#462] Get rid of XCTestCase.wait 2023-03-31 08:58:19 +02:00
Michal Fousek 8e5db5e0b5 [#876] Add tests which runs multiple instances of the SDKSynchronizer
Closes #876.

- Add `testMultipleSynchronizersCanRunAtOnce()` test which creates
  multiple instances of the `SDKSynchronizer` and then executes sync in
  parallel.
- To achieve this it's required to have multiple instances of the
  lightwalletd in the darkside mode. Because of this new test is in the
  new target `AliasDarksideTests`. It's little bit harder to run this
  test than to run regular darkside tests. So it has it's own target.
- Fix bug when all the instances of the `SDKSynchronizer` used same data
  DB even with different aliases.
- Add script to run multiple instances of the lightwalletd in
  darkside mode. And add script to stop these instances and clean after
  those.
- Update `DarksideWalletService` a little so the endpoint can be passed
  to it. Without this it would always use default endpoint when created
  with service.
- Small cleanup in `TestCoordinator`.
2023-03-28 16:11:13 +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 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
Michal Fousek cb31acdd81 [#826] Change how the SDK is initialised
Closes #826

- `viewingKeys` and `walletBirthday` are removed from `Initializer`
  constuctor. These parameters are moved to `SDKSynchronizer.prepare`
  function.
- Constructor of the `SDKSynchronizer` no longer throws exception.
- Any value emitted from `lastState` stream before `SDKSynchronizer.prepare`
  is called has `latestScannedHeight` set to 0.
- `Initializer.initialize` function isn't public anymore. To initialize
  SDK call `SDKSynchronizer.prepare` instead.
- Real birthday is now known after the `SDKSynchronizer.prepare` is
  called. But this function isn't async and therefore it's hard to
  pass birthday from here to `CompactBlockProcessor` in synchronous
  manner. We must be sure that it's safe to call start() after prepare
  function finishes.
    For this reason `CompactBlockProcessor` has `walletBirthdayProvider`
  instead of `walletBirthday`. And this new parameter is closure which
  reads birthday from `Initiliazer` on each call. Thanks to this
  `CompactBlockProcessor` has always the right birthday.
- Some cleanup is done in `TestCoordinator`.
2023-03-13 15:32:55 +01:00
Michal Fousek d09b00cabe [#795] Include sapling-spend file into bundle for tests
Closes #795

- Added structure `SaplingParamsSourceURL` which holds source URLs for
  sapling-spend file and sapling-output file. URLs are ultimately passed
  to `SaplingParameterDownloader`.
- This is done so it's possible to pass different URLs when running
  tests.
- sapling-spend file and sapling-output file are in tests bundle. And
  when running tests these files are loaded from bundle and not from
  network.
2023-02-20 10:03:16 +01:00
Michal Fousek 753e3bf605
Merge pull request #779 from Chlup/two_swiftlint_configs
[#778] Add swiflint config file only for tests
2023-02-15 09:31:41 +01:00
Michal Fousek 663a785b8f
Merge pull request #776 from Chlup/713_remove_unusedMethods_testcoordinator
[#713] Remove unused methods from TestCoordinator
2023-02-13 13:42:35 +01:00
Michal Fousek 65d6347bcf [#778] Add swiflint config file only for tests
Closes #778

- .swiftlint.yml is now used to lint only the code of the SDK.
- .swiftlint_tests.yml is now used to lint only the code of the tests.
  This config disables rules that were previously disabled in the code
  in lot of tests.
2023-02-13 13:36:58 +01:00
Michal Fousek 44732b179b Update code to to comply better with linter rules
- Removed some disabled linter rules from code and update code to comply
  with those.
- No logic was changed.
2023-02-13 12:18:08 +01:00
Michal Fousek 2718b6c19b [#713] Remove unused methods from TestCoordinator 2023-02-13 10:39:37 +01:00
Michal Fousek 34c08a3a81 [#771] Fix tests failing because of different paths passed to `FSCompactBlockRepository` and `FSMetadataStore`
Closes #771

- Renamed `cacheDirectory` param in `FSCompactBlockRepository`
  constructor to `fsBlockDbRoot`.
- Pass same paths to `FSCompactBlockRepository` and `FSMetadataStore`
  from tests.
2023-02-09 13:58:49 +01:00
Michal Fousek 385c0a7195 [#746] Modularize GRPC related code
Closes #746

- `LightWalletGRPCService` is no longer public. `LightWalletService` is no longer public.
- `LightWalletGRPCService` shouldn't be used dicrectly. Use `LightWalletServiceFactory` to create instance of the service.
- Moved sending of `blockProcessorConnectivityStateChanged` notification to `Initilizer`.
- All the errors from GRPC are mapped to `LightWalletServiceError`. Handling of `GRPCStatus` in the SDK is no longer required.
- `Service` directory (that contains GRPC code) is moved to `Modules/Service`. We can put more code to `Modules/` if we decide
to modularize more code.
2023-02-03 22:25:54 +01:00
Francisco Gindre fad3aae174
- [#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 13:58:12 -03:00
Lukas Korba f69da50ba9
[#747] Remove SampleLogger and replace it with OSLogger (#748)
- SampleLogger removed
- OSLogger used
- category default
2023-01-26 18:14:07 +01:00
Lukas Korba 372ea5af70
[#711] Add Swiftlint plug in to SDK (#722)
- plugin integrated
- errors resolved
- warnings resolved
- package.swift macos platform version 10_15 -> 12
2023-01-18 17:09:04 +01:00
Michal Fousek e01c83690f [#646] SDK sync process resumes correctly
- Previously we had one range for each sync which was used for each
  phase of sync process. Newly there is separate range for each phase of
  the sync process.
- I added `InternalSyncProgress` utility. This utility tracks progress
  of some phases. And it is able to compute right ranges which should be
  used for syncing.
- Some unused download code from `CompactBlockProcessor` is removed.

Fix tests

Address review comments

- Rebase to master
- Update how range for `processBatchFinished()` is computed.
- Refactor `InternalSyncProgress`
- Add tests for `InternalSyncProgress`

Address review comments

Change how latest downloaded block is tracked

- Cache DB is no longer used to track which block was downloaded as
  latest. `InternalSyncProgress` is used to do that.
- Thanks to that #660 is fixed. And cache DB can be completely removed
  after sync process.
- Added sleep(1) to some darkside tests when latest block height is set.
  Otherwise lightwalletd in darkside mode doesn't have time to setup and
  tests are flaky.

Fix TransactionEnhancementTests.testBasicEnhancement test
2022-12-12 14:27:30 +01:00
Lukas Korba ce6a417154
[#585] Fix RewindRescanTests (#656)
- test fixed, the saplingActivation wasn't passed to the block processor just like to the service, there's the mismatch
2022-11-29 19:59:16 -03:00
Michal Fousek a7fe75c11e
Cleanup warnings (#655)
- TestCoordinator doesn't need to be used in async manner.
2022-11-29 07:40:45 +01:00
Lukas Korba 6029a75038
[#637] Make sapling parameter download part of processing blocks (#650)
- sync process enhanced to try to download sapling params if needed
- tests fixed
- failing import Crypto -> import CryptoKit
- download params only if there are sapling funds
2022-11-29 07:38:28 +01:00
Michal Fousek 44a6970b73 [#616] Dont send notification from SDK on main thread
Closes #616

- Added small helper `NotificationSender` which is used to send
  notifications.
- No notificaiton is sent on main thread.
- Change how `status` is stored and update in `SDKSynchronizer`. It is
  now protected by lock. Before this wasn't needed because status was
  updated from main thread everywhere.
- `SyncBlocksViewController` in the sample app now uses
  `SDKSynchronizer` instead of `CompactBlockProcessor` directly.
2022-11-21 16:33:42 +01:00
Francisco Gindre 01d85f5748 Fix compiler errors 2022-10-31 09:57:10 -03:00
Francisco Gindre dbd4b8934c Merge branch 'master' into merge-master 2022-10-31 09:34:38 -03:00
Lukas Korba cfe71d5da2
[#523] Make a CompactBlockProcessor an Actor (#565)
- Sample app refactored for the processor being an actor
- tests refactored as well
- dark side tests fixed
- utilities separated to new file
- synchronizer's start and stop are no longer in async context
- updating the UI for the scan fixed
2022-10-27 12:51:38 +02:00
Francisco Gindre 7806b5114f
Use UnifiedSpendingKey for shielding and Spending (#535)
[#534] Use UnifiedSpendingKey for shielding and Spending

This commit implements the use of Unified Spending Keys for shielding
and spending as well as rolling Unified Addresses.

Users should obtain addresses by rolling them from the SDK.
USKs replace Sapling Extended Spending keys and TransparentAccountPrivKeys
when shielding or spending

Closes #534

Co-authored-by: Kris Nuttycombe <kris@nutty.land>

* Fix rebase issues

* PR Suggestion. Make `lastError` an Optional

* Fix test `testReOrgRemovesOutboundTxAndIsNeverMined`

Co-authored-by: Kris Nuttycombe <kris@nutty.land>
2022-10-02 23:11:17 -03:00
Francisco Gindre ca5221ac75 Merge branch 'master' into merge-master-to-zip-316 2022-09-30 09:53:34 -03:00
Francisco Gindre ed87a2781c [#461] Adopt a Type-Safe Keys and Addresses API
This PR creates data types for Addresses and Keys so that they are
not represented by Strings anymore. This avoids mistakenly use
the wrong keys because they are all alike for the type system.

New Protocols:
=============

StringEncoded -> Protocol that makes a type can be expressed in an
string-encoded fashion either for UI or Interchange purposes.

Undescribable -> A protocol that implements methods that override default
decriptions used by debuggers, loggers and event trackers to avoid types
conforming to it to be leaked to logs.

Deleted Protocols:
==================

UnifiedFullViewingKey --> turned into a struct.
UnifiedAddress --> turned into a struct

new Error Type:
================

````
enum KeyEncodingError: Error {
    case invalidEncoding
}
````

This error is thrown when an Address or Key type (addresses are public
keys in the end) can be decoded from their String representation,
typically upon initialization from a User input.

New Types:
=========

SaplingExtendedSpendingKey -> Type for Sapling Extended Full Viewing Keys
this type will be replaced with Unified Spending Keys soon.

SaplingExtendedFullViewingKey -> Extended Full Viewing Key for Sapling.
Maintains existing funcionality. Will be probably deprecated in favor of
UFVK.

TransparentAccountPrivKey -> Private key for transparent account. Used
only for shielding operations. Note: this will probably be deprecated soon.

UnifiedFullViewingKey -> Replaces the protocol that had the same name.

TransparentAddress -> Replaces a type alias with a struct

SaplingAddress --> Represents a Sapling receiver address. Comonly called zAddress. This address corresponds to the Zcash Sapling shielded pool.
Although this it is fully functional, we encourage developers to
choose `UnifiedAddress` before Sapling or Transparent ones.

UnifiedAddress -> Represents a UA. String-encodable and Equatable. Use of
UAs must be favored instead of individual receivers for different pools.
This type can't be decomposed into their Receiver types yet.

Recipient -> This represents all valid receiver types to be used as
inputs for outgoing transactions.

````
public enum Recipient: Equatable, StringEncoded {
    case transparent(TransparentAddress)
    case sapling(SaplingAddress)
    case unified(UnifiedAddress)
````

The wrapped concrete receiver is a valid receiver type.

Deleted Type Aliases:
=====================

The following aliases were deleted and turned into types
````
public typealias TransparentAddress = String
public typealias SaplingShieldedAddress = String

````

Changes to Derivation Tool
==========================

DerivationTool has been changed to accomodate this new types and
remove Strings whenever possible.

Changes to Synchronizer and CompactBlockProcessor
=================================================
Accordingly these to components have been modified to accept the
new types intead of strings when possible.

Changes to Demo App
===================
The demo App has been patch to compile and work with the new types.
Developers must consider that the use (and abuse) of forced_try and
forced unwrapping is a "license" that maintainers are using for the
sake of brevity. We consider that clients of this SDK do know how to
handle Errors and Optional and it is not the objective of the demo
code to show good practices on those matters.

Closes #461
2022-09-05 15:09:07 -03:00
Kris Nuttycombe 905ee401d1 Use zcash_client_sqlite to manage migrations for the wallet db.
This change removes responsibility for maintaining the state of
the wallet database from `ZcashLightClientKit` in favor of using
the migration system now provided by librustzcash. This will help
to ensure that the structure of the database is kept consistent with
the functions that query and update the database state.

Co-authored-by: Francisco Gindre <francisco.gindre@gmail.com>
2022-08-24 09:38:42 -06:00
Jack Grigg b0343d4c38 Rename `UnifiedViewingKey` to `UnifiedFullViewingKey`
The type does not yet match ZIP 316, but performing this rename first
makes the subsequent commit simpler.
2022-08-24 09:33:42 -06:00
Francisco Gindre 3be694c920
[#444] Syncing Restarts to zero when the wallet is wiped and synced from zero in one go. (#445)
This commit changes the way walletBirthday is stored in the synchronizer and intinitializer. Wallets syncing from creation/restore would have a problem where the birthday stored in the Blocks Table would be the one corresponding to the chekpoint found a the time of syncing, but the compact block downloader would start downloading blocks from the height provided by the user when the wallet was restored. This would cause a `validationFailed` error at the height checkpoint.height + 1 and restart downloading from checkpoint.height and then resume correctly.

Darksidewalletd test setUp was changed re be able to reproduce the error since injection guaranteed correctness and it was not possible to reproduce the error with it since the wallet birthday height provided matched exactly with the checkpoint on disk and that's the only case that avoided this error.

Closes #444
2022-07-29 10:33:23 -03:00
Francisco Gindre 2fcfa6fdbe
[#398] Make WalletBirthday an internal type (#414)
This commit makes Renames `WalletBirthday` to `Checkpoint` and
makes Checkpoint an internal type. Public ocurrences of this
type is replaced by `BlockHeight` (Int) and then retrieval of the
Checkpoint is deferred to the appropiate place in the code

Add an extension method to `BlockHeight` to get latest checkpoint
height present in the SDK's bundle

PR Suggestions:

Add test for integer overflow on JSON
File renamed from WalletBirthday to Checkpoint
2022-07-12 16:36:12 -03:00
Daniel Haight 86d1257ab5 Remove dependecy on rust sources 2022-02-28 17:03:20 +00:00