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

fix unconfirmed change note tracking in transactions #10

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 47 additions & 4 deletions zcash_extras/src/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,62 @@
use std::fmt::{Debug, Display};

use zcash_primitives::{
consensus::{self, BranchId},
consensus::{self, BranchId, NetworkUpgrade},
memo::MemoBytes,
sapling::prover::TxProver,
transaction::{
builder::Builder,
components::{amount::DEFAULT_FEE, Amount},
Transaction,
},
zip32::{ExtendedFullViewingKey, ExtendedSpendingKey},
};

use crate::WalletWrite;
use zcash_client_backend::{
address::RecipientAddress,
data_api::{error::Error, SentTransaction},
data_api::{error::Error, ReceivedTransaction, SentTransaction},
decrypt_transaction,
wallet::{AccountId, OvkPolicy},
};

/// Scans a [`Transaction`] for any information that can be decrypted by the accounts in
/// the wallet, and saves it to the wallet.
pub async fn decrypt_and_store_transaction<N, E, P, D>(
params: &P,
data: &mut D,
tx: &Transaction,
) -> Result<(), E>
where
E: From<Error<N>>,
P: consensus::Parameters,
D: WalletWrite<Error = E>,
{
// Fetch the ExtendedFullViewingKeys we are tracking
let extfvks = data.get_extended_full_viewing_keys().await?;

let max_height = data.block_height_extrema().await?.map(|(_, max)| max + 1);
let height = data
.get_tx_height(tx.txid())
.await?
.or(max_height)
.or_else(|| params.activation_height(NetworkUpgrade::Sapling))
.ok_or(Error::SaplingNotActive)?;

let outputs = decrypt_transaction(params, height, tx, &extfvks);
if outputs.is_empty() {
Ok(())
} else {
data.store_received_tx(&ReceivedTransaction {
tx,
outputs: &outputs,
})
.await?;

Ok(())
}
}

#[allow(clippy::needless_doctest_main)]
/// Creates a transaction paying the specified address from the given account.
///
Expand Down Expand Up @@ -182,8 +221,7 @@ where
RecipientAddress::Shielded(to) => {
builder.add_sapling_output(ovk, to.clone(), value, memo.clone())
}

RecipientAddress::Transparent(to) => builder.add_transparent_output(&to, value),
RecipientAddress::Transparent(to) => builder.add_transparent_output(to, value),
}
.map_err(Error::Builder)?;

Expand All @@ -209,6 +247,11 @@ where
}
};

// Automatically decrypt and store any outputs sent to our wallet, including change.
// This uses our viewing keys to find any outputs we can decrypt, creates decrypted
// note data for spendability, and saves them to the wallet database.
decrypt_and_store_transaction(params, wallet_db, &tx).await?;
Copy link

Choose a reason for hiding this comment

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

Without this code we would need to wait until the block is scanned, right?

Copy link
Member Author

Choose a reason for hiding this comment

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

right

Copy link
Member Author

Choose a reason for hiding this comment

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

with the case above, we need this fix in kdf directly after building txs..


wallet_db
.store_sent_tx(&SentTransaction {
Copy link

Choose a reason for hiding this comment

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

Looks like this store_sent_tx call stores the created transaction output in the walletdb.
Wouldn't the decrypt_and_store_transaction call do a similar thing?

Copy link
Member Author

@borngraced borngraced Nov 20, 2024

Choose a reason for hiding this comment

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

store_sent_tx - stores notes we created to send value to others, while decrypt_and_store_transaction calls store_received_tx(stores notes we can spend) internally

/// Scans a [`Transaction`] for any information that can be decrypted by the accounts in
/// the wallet, and saves it to the wallet.
pub async fn decrypt_and_store_transaction<N, E, P, D>(
params: &P,
data: &mut D,
tx: &Transaction,
) -> Result<(), E>
where
E: From<Error<N>>,
P: consensus::Parameters,
D: WalletWrite<Error = E>,
{
// Fetch the ExtendedFullViewingKeys we are tracking
let extfvks = data.get_extended_full_viewing_keys().await?;
let max_height = data.block_height_extrema().await?.map(|(_, max)| max + 1);
let height = data
.get_tx_height(tx.txid())
.await?
.or(max_height)
.or_else(|| params.activation_height(NetworkUpgrade::Sapling))
.ok_or(Error::SaplingNotActive)?;
let outputs = decrypt_transaction(params, height, tx, &extfvks);
if outputs.is_empty() {
Ok(())
} else {
data.store_received_tx(&ReceivedTransaction {
tx,
outputs: &outputs,
})
.await?;
Ok(())
}
}

Copy link

Choose a reason for hiding this comment

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

Aha, we need to add the change as a received output, to fix the balance

tx: &tx,
Expand Down
2 changes: 0 additions & 2 deletions zcash_primitives/src/transaction/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@
to,
note,
memo: memo.unwrap_or_else(MemoBytes::empty),
_params: PhantomData::default(),

Check warning on line 146 in zcash_primitives/src/transaction/builder.rs

View workflow job for this annotation

GitHub Actions / Clippy (nightly)

use of `default` to create a unit struct

warning: use of `default` to create a unit struct --> zcash_primitives/src/transaction/builder.rs:146:33 | 146 | _params: PhantomData::default(), | ^^^^^^^^^^^ help: remove this call to `default` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#default_constructed_unit_structs = note: `-W clippy::default-constructed-unit-structs` implied by `-W clippy::all` = help: to override `-W clippy::all` add `#[allow(clippy::default_constructed_unit_structs)]`

Check warning on line 146 in zcash_primitives/src/transaction/builder.rs

View workflow job for this annotation

GitHub Actions / Clippy (nightly)

use of `default` to create a unit struct

warning: use of `default` to create a unit struct --> zcash_primitives/src/transaction/builder.rs:146:33 | 146 | _params: PhantomData::default(), | ^^^^^^^^^^^ help: remove this call to `default` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#default_constructed_unit_structs = note: `-W clippy::default-constructed-unit-structs` implied by `-W clippy::all` = help: to override `-W clippy::all` add `#[allow(clippy::default_constructed_unit_structs)]`
})
}

Expand Down Expand Up @@ -320,7 +320,7 @@
{
self.builders.push(TzeInputInfo {
prevout: tzeout,
builder: Box::new(move |ctx| builder(&ctx).map(|x| x.to_payload())),

Check warning on line 323 in zcash_primitives/src/transaction/builder.rs

View workflow job for this annotation

GitHub Actions / Clippy (nightly)

this expression creates a reference which is immediately dereferenced by the compiler

warning: this expression creates a reference which is immediately dereferenced by the compiler --> zcash_primitives/src/transaction/builder.rs:323:50 | 323 | builder: Box::new(move |ctx| builder(&ctx).map(|x| x.to_payload())), | ^^^^ help: change this to: `ctx` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_borrow

Check warning on line 323 in zcash_primitives/src/transaction/builder.rs

View workflow job for this annotation

GitHub Actions / Clippy (nightly)

this expression creates a reference which is immediately dereferenced by the compiler

warning: this expression creates a reference which is immediately dereferenced by the compiler --> zcash_primitives/src/transaction/builder.rs:323:50 | 323 | builder: Box::new(move |ctx| builder(&ctx).map(|x| x.to_payload())), | ^^^^ help: change this to: `ctx` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_borrow
});
}
}
Expand Down Expand Up @@ -380,7 +380,7 @@
_phantom: &'a PhantomData<P>,
}

impl<'a, P: consensus::Parameters> Builder<'a, P, OsRng> {

Check warning on line 383 in zcash_primitives/src/transaction/builder.rs

View workflow job for this annotation

GitHub Actions / Clippy (nightly)

the following explicit lifetimes could be elided: 'a

warning: the following explicit lifetimes could be elided: 'a --> zcash_primitives/src/transaction/builder.rs:383:6 | 383 | impl<'a, P: consensus::Parameters> Builder<'a, P, OsRng> { | ^^ ^^ | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_lifetimes help: elide the lifetimes | 383 - impl<'a, P: consensus::Parameters> Builder<'a, P, OsRng> { 383 + impl<P: consensus::Parameters> Builder<'_, P, OsRng> { |

Check warning on line 383 in zcash_primitives/src/transaction/builder.rs

View workflow job for this annotation

GitHub Actions / Clippy (nightly)

the following explicit lifetimes could be elided: 'a

warning: the following explicit lifetimes could be elided: 'a --> zcash_primitives/src/transaction/builder.rs:383:6 | 383 | impl<'a, P: consensus::Parameters> Builder<'a, P, OsRng> { | ^^ ^^ | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_lifetimes help: elide the lifetimes | 383 - impl<'a, P: consensus::Parameters> Builder<'a, P, OsRng> { 383 + impl<P: consensus::Parameters> Builder<'_, P, OsRng> { |
/// Creates a new `Builder` targeted for inclusion in the block with the given height,
/// using default values for general transaction fields and the default OS random.
///
Expand Down Expand Up @@ -634,7 +634,6 @@
// Change output
//

/*
Copy link

Choose a reason for hiding this comment

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

As I can see, the change output is added in KDF code. I hope this won't affect that code.
Maybe some test is needed in KDF to ensure that the change is calculated correctly

Copy link
Member Author

Choose a reason for hiding this comment

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

I see. Thanks a lot..

if change.is_positive() {
// Send change to the specified change address. If no change address
// was set, send change to the first Sapling address given as input.
Expand All @@ -655,7 +654,6 @@

self.add_sapling_output(Some(change_address.0), change_address.1, change, None)?;
}
*/

//
// Record initial positions of spends and outputs
Expand Down Expand Up @@ -847,7 +845,7 @@
// witness to commit to at the time it was added to the transaction builder; here, it then computes those
// commitments.
let (mode, payload) = (tze_in.builder)(&self.mtx)?;
let mut current = self.mtx.tze_inputs.get_mut(i).unwrap();

Check warning on line 848 in zcash_primitives/src/transaction/builder.rs

View workflow job for this annotation

GitHub Actions / Clippy (nightly)

variable does not need to be mutable

warning: variable does not need to be mutable --> zcash_primitives/src/transaction/builder.rs:848:17 | 848 | let mut current = self.mtx.tze_inputs.get_mut(i).unwrap(); | ----^^^^^^^ | | | help: remove this `mut` | = note: `#[warn(unused_mut)]` on by default

Check warning on line 848 in zcash_primitives/src/transaction/builder.rs

View workflow job for this annotation

GitHub Actions / Clippy (nightly)

variable does not need to be mutable

warning: variable does not need to be mutable --> zcash_primitives/src/transaction/builder.rs:848:17 | 848 | let mut current = self.mtx.tze_inputs.get_mut(i).unwrap(); | ----^^^^^^^ | | | help: remove this `mut` | = note: `#[warn(unused_mut)]` on by default
if mode != current.witness.mode {
return Err(Error::TzeWitnessModeMismatch(current.witness.mode, mode));
}
Expand Down
Loading