Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ZCash] Implement Zcash sync process and Orchard inputs spending #27018

Open
wants to merge 5 commits into
base: master
Choose a base branch
from

Conversation

cypt4
Copy link
Collaborator

@cypt4 cypt4 commented Dec 13, 2024

Resolves brave/brave-browser#42898

Sec review: https://github.com/brave/reviews/issues/1834

Implements basic sync process for the Orchard protocol.
Entry point for the sync process is the per-account ZCashShieldSyncService class.
Sync process includes:

  1. Verifying chain state. In some cases chain reorg may happen so we need to check whether latest scanned block hash hasn't been changed. Otherwise we need to clean OrchardStorage to remove notes, nullifiers and commitments that are not valid.
  2. Preparing a set of scan ranges to scan. Each scan range ends with updating of OrchardSyncState with the discovered data.
  3. Scanning ranges one-by-one. This includes reading compact blocks from the gRPC node and extracting related incoming notes and nullifiers for spends along with a set of commitment tree leafs to be inserted to the shard tree in the future. Extracting is done on a separate sequence. This is done using OrchardBlockScanner class.
  4. Inserting extracted leafs to the shard tree(OrchardSyncState::ApplyScanResults).

ZCashCreateOrchardToOrchardTransactionTask then could be used to construct shielded transaction.
ZCashCompleteTransactionTask completes transactions by calculating witness for every shielded input and signing the transaction.

Submitter Checklist:

  • I confirm that no security/privacy review is needed and no other type of reviews are needed, or that I have requested them
  • There is a ticket for my issue
  • Used Github auto-closing keywords in the PR description above
  • Wrote a good PR/commit description
  • Squashed any review feedback or "fixup" commits before merge, so that history is a record of what happened in the repo, not your PR
  • Added appropriate labels (QA/Yes or QA/No; release-notes/include or release-notes/exclude; OS/...) to the associated issue
  • Checked the PR locally:
    • npm run test -- brave_browser_tests, npm run test -- brave_unit_tests wiki
    • npm run presubmit wiki, npm run gn_check, npm run tslint
  • Ran git rebase master (if needed)

Reviewer Checklist:

  • A security review is not needed, or a link to one is included in the PR description
  • New files have MPL-2.0 license header
  • Adequate test coverage exists to prevent regressions
  • Major classes, functions and non-trivial code blocks are well-commented
  • Changes in component dependencies are properly reflected in gn
  • Code follows the style guide
  • Test plan is specified in PR before merging

After-merge Checklist:

Test Plan:

@github-actions github-actions bot added CI/storybook-url Deploy storybook and provide a unique URL for each build feature/web3/wallet feature/web3/wallet/core labels Dec 13, 2024
@brave-builds
Copy link
Collaborator

A Storybook has been deployed to preview UI for the latest push

@cypt4 cypt4 force-pushed the brave_42898 branch 2 times, most recently from 73a1e11 to 21e1e2d Compare December 16, 2024 21:15
@cypt4 cypt4 changed the title Implement Zcash sync process [ZCash] Implement Zcash sync process and Orchard inputs spending Dec 16, 2024
@cypt4 cypt4 marked this pull request as ready for review December 30, 2024 21:45
@cypt4 cypt4 requested review from a team as code owners December 30, 2024 21:45
Copy link
Contributor

@Douglashdaniel Douglashdaniel left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

++ Wallet Front-end

Comment on lines +190 to +192
auto frontier_bytes = PrefixedHexStringToBytes(
base::StrCat({"0x", frontier_tree_state_.value()->orchardTree}));
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like it should be HexStringToBytes(frontier_tree_state_.value()->orchardTree)

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PrefixedHexStringToBytes is a bit more complicated: for ex. it appends 0 if input size is odd. I'd prefer to use it instead.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PrefixedHexStringToBytes is for EVM's encoding of integers. It is not supposed to be used unless it is explictly required by format of hex string.
As afar as I can see orchardTree is just hex encoded bytes, so decoding to bytes should be done with HexStringToBytes and fail in case of odd size

Comment on lines 544 to 545
GURL request_url = MakeGetLightdInfoURL(GetNetworkURL(chain_id));

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it unintentinonal removal?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Returned

Comment on lines +87 to +90
initial_ranges_count_ =
std::ceil(static_cast<double>((to - from + 1)) / kBatchSize);
scan_ranges_ = std::deque<ScanRange>();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can it be rewritten somehow so it's easier to track if always to >= form?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

Comment on lines 39 to 47
case ZCashShieldSyncService::ErrorCode::kFailedToVerifyChainState:
return 7;
case ZCashShieldSyncService::ErrorCode::kFailedToUpdateSubtreeRoots:
return 8;
case ZCashShieldSyncService::ErrorCode::kDatabaseError:
return 9;
case ZCashShieldSyncService::ErrorCode::kScannerError:
return 10;
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

would that be enough to just return static_cast<size_t>(error); ?
And why it returns size_t?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It was enum class, reworked using simple enum

return;
} else {
verify_chain_state_task_.reset();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems verify_chain_state_task_.reset(); should be done with chain_state_verified_ = true

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is


namespace brave_wallet {

class ZCashVerifyChainStateTask {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A brief comment would be helpful for all such task classes

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

OrchardAddrRawPart receiver_;
std::optional<OrchardMemo> memo_;
uint64_t amount_;

bool started_ = false;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why we need these started_ flags for tasks?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just to ensure that Start is called only once

Comment on lines +129 to +137
orchard_output.value = zcash_transaction.TotalInputsAmount() -
zcash_transaction.fee() - pick_result->change;
orchard_output.addr = receiver_;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Needs some explanation or guards so this does not overflow

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To avoid copy paste that should be based on base::CheckedNumeric

Copy link
Contributor

github-actions bot commented Jan 8, 2025

[puLL-Merge] - brave/brave-core@27018

Description

This PR introduces significant changes to the Brave Wallet's ZCash implementation, particularly focusing on the Orchard protocol and shielded transactions. The changes include new task classes for handling various ZCash operations, improvements to the transaction creation and signing process, and updates to the user interface for ZCash-related features.

Possible Issues

  1. The complexity of the ZCash implementation has increased, which may make future maintenance and debugging more challenging.
  2. The changes to the transaction creation process may require thorough testing to ensure compatibility with existing wallet functions.

Security Hotspots

  1. The ZCashCompleteTransactionTask class handles sensitive operations like signing transactions. Ensure that proper key management and secure signing practices are implemented.
  2. The ZCashScanBlocksTask processes blockchain data. Validate that it properly handles potentially malicious or corrupted block data.
  3. The ApplyOrchardSignatures function in zcash_complete_transaction_task.cc is executed on a background thread. Ensure that this doesn't introduce any race conditions or thread safety issues.
Changes

Changes

  1. components/brave_wallet/browser/zcash/zcash_wallet_service.h/.cc:

    • Added new methods for creating Orchard-to-Orchard and Transparent-to-Orchard transactions.
    • Implemented chain tip status retrieval and sync state reset functionality.
  2. components/brave_wallet/browser/zcash/zcash_blocks_batch_scan_task.h/.cc:

    • New class for batch scanning of ZCash blocks.
  3. components/brave_wallet/browser/zcash/zcash_scan_blocks_task.h/.cc:

    • New class for managing the overall block scanning process.
  4. components/brave_wallet/browser/zcash/zcash_complete_transaction_task.h/.cc:

    • New class for completing ZCash transactions, including signing and Orchard part generation.
  5. components/brave_wallet/browser/zcash/zcash_create_orchard_to_orchard_transaction_task.h/.cc:

    • New class for creating transactions within the Orchard pool.
  6. components/brave_wallet/common/brave_wallet.mojom:

    • Updated ZCash-related structs and interfaces to support new functionality.
  7. components/brave_wallet_ui/:

    • Updated UI components to support new ZCash features and transaction types.
sequenceDiagram
    participant User
    participant UI
    participant ZCashWalletService
    participant ZCashScanBlocksTask
    participant ZCashBlocksBatchScanTask
    participant ZCashCompleteTransactionTask
    participant Blockchain

    User->>UI: Initiate ZCash operation
    UI->>ZCashWalletService: Request operation
    ZCashWalletService->>ZCashScanBlocksTask: Start block scanning
    loop For each batch
        ZCashScanBlocksTask->>ZCashBlocksBatchScanTask: Scan batch
        ZCashBlocksBatchScanTask->>Blockchain: Fetch blocks
        Blockchain-->>ZCashBlocksBatchScanTask: Return block data
        ZCashBlocksBatchScanTask-->>ZCashScanBlocksTask: Return batch result
    end
    ZCashScanBlocksTask-->>ZCashWalletService: Scanning complete
    ZCashWalletService->>ZCashCompleteTransactionTask: Complete transaction
    ZCashCompleteTransactionTask->>Blockchain: Submit transaction
    Blockchain-->>ZCashCompleteTransactionTask: Transaction result
    ZCashCompleteTransactionTask-->>ZCashWalletService: Operation result
    ZCashWalletService-->>UI: Operation complete
    UI-->>User: Display result
Loading

@cypt4 cypt4 requested a review from supermassive January 9, 2025 10:20
@@ -57,13 +70,15 @@ void ZCashCreateShieldTransactionTask::WorkOnTask() {

if (!transaction_ && !CreateTransaction()) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why transaction_ is checked here?

std::move(start_address), std::move(callback)));
task->ScheduleWorkOnTask();
auto task = base::MakeRefCounted<ZCashDiscoverNextUnusedZCashAddressTask>(
base::PassKey<class ZCashWalletService>(), weak_ptr_factory_.GetWeakPtr(),
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

don't need class here most likely

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
CI/storybook-url Deploy storybook and provide a unique URL for each build feature/web3/wallet/core feature/web3/wallet puLL-Merge
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[ZCash] Implement spending of shielded inputs
4 participants