From f6c05345f4a80a6f0e542090125c120dc1f4a65c Mon Sep 17 00:00:00 2001 From: Kris Nuttycombe Date: Thu, 19 Dec 2024 08:25:42 -0700 Subject: [PATCH] Remove internal use of reexports of types have been moved to other crates. This commit temporarily removes the reexported types to simplify the removal process; the reexports will be reintroduced with deprecation annotations in the subsequent commit. --- Cargo.lock | 3 + components/zcash_address/src/convert.rs | 104 +++++---- components/zcash_address/src/encoding.rs | 39 ++-- components/zcash_address/src/kind/unified.rs | 24 +- .../zcash_address/src/kind/unified/address.rs | 4 +- .../zcash_address/src/kind/unified/fvk.rs | 12 +- .../zcash_address/src/kind/unified/ivk.rs | 14 +- components/zcash_address/src/lib.rs | 15 +- components/zcash_address/src/test_vectors.rs | 6 +- devtools/Cargo.toml | 1 + devtools/src/bin/inspect/address.rs | 29 ++- devtools/src/bin/inspect/block.rs | 8 +- devtools/src/bin/inspect/context.rs | 23 +- devtools/src/bin/inspect/keys.rs | 12 +- devtools/src/bin/inspect/main.rs | 9 +- devtools/src/bin/inspect/transaction.rs | 28 ++- pczt/src/roles/creator/mod.rs | 2 +- pczt/src/roles/signer/mod.rs | 8 +- pczt/src/roles/tx_extractor/mod.rs | 14 +- pczt/tests/end_to_end.rs | 16 +- zcash_client_backend/Cargo.toml | 1 + .../examples/diversify-address.rs | 8 +- zcash_client_backend/src/data_api.rs | 154 ++++++------- zcash_client_backend/src/data_api/chain.rs | 8 +- zcash_client_backend/src/data_api/error.rs | 28 ++- zcash_client_backend/src/data_api/scanning.rs | 2 +- .../src/data_api/scanning/spanning_tree.rs | 6 +- zcash_client_backend/src/data_api/testing.rs | 83 +++---- .../src/data_api/testing/pool.rs | 214 +++++++++--------- .../src/data_api/testing/transparent.rs | 29 +-- zcash_client_backend/src/data_api/wallet.rs | 70 +++--- .../src/data_api/wallet/input_selection.rs | 48 ++-- zcash_client_backend/src/decrypt.rs | 19 +- zcash_client_backend/src/fees.rs | 98 ++++---- zcash_client_backend/src/fees/common.rs | 48 ++-- zcash_client_backend/src/fees/fixed.rs | 44 ++-- zcash_client_backend/src/fees/orchard.rs | 10 +- zcash_client_backend/src/fees/sapling.rs | 18 +- zcash_client_backend/src/fees/zip317.rs | 156 ++++++------- zcash_client_backend/src/lib.rs | 10 +- zcash_client_backend/src/proposal.rs | 25 +- zcash_client_backend/src/proto.rs | 17 +- zcash_client_backend/src/scanning.rs | 28 +-- zcash_client_backend/src/sync.rs | 16 +- zcash_client_backend/src/wallet.rs | 43 ++-- zcash_client_sqlite/Cargo.toml | 1 + zcash_client_sqlite/src/chain.rs | 2 +- zcash_client_sqlite/src/error.rs | 15 +- zcash_client_sqlite/src/lib.rs | 43 ++-- zcash_client_sqlite/src/testing/db.rs | 13 +- zcash_client_sqlite/src/wallet.rs | 47 ++-- .../src/wallet/commitment_tree.rs | 12 +- zcash_client_sqlite/src/wallet/common.rs | 31 ++- zcash_client_sqlite/src/wallet/init.rs | 27 +-- .../init/migrations/add_account_birthdays.rs | 2 +- .../init/migrations/add_transaction_views.rs | 47 ++-- .../init/migrations/add_utxo_account.rs | 16 +- .../wallet/init/migrations/addresses_table.rs | 6 +- .../migrations/ensure_orchard_ua_receiver.rs | 10 +- .../init/migrations/ephemeral_addresses.rs | 23 +- .../migrations/fix_bad_change_flagging.rs | 6 +- .../init/migrations/full_account_ids.rs | 12 +- .../init/migrations/orchard_received_notes.rs | 3 +- .../migrations/received_notes_nullable_nf.rs | 5 +- .../init/migrations/receiving_key_scopes.rs | 54 ++--- .../migrations/sapling_memo_consistency.rs | 7 +- .../init/migrations/shardtree_support.rs | 6 +- .../init/migrations/tx_retrieval_queue.rs | 18 +- .../wallet/init/migrations/ufvk_support.rs | 13 +- .../v_sapling_shard_unscanned_ranges.rs | 3 +- .../init/migrations/v_transactions_net.rs | 8 +- .../v_transactions_note_uniqueness.rs | 5 +- zcash_client_sqlite/src/wallet/orchard.rs | 3 +- zcash_client_sqlite/src/wallet/sapling.rs | 8 +- zcash_client_sqlite/src/wallet/scanning.rs | 53 ++--- zcash_client_sqlite/src/wallet/transparent.rs | 36 +-- .../src/wallet/transparent/ephemeral.rs | 12 +- zcash_primitives/benches/note_decryption.rs | 7 +- zcash_primitives/src/lib.rs | 19 +- zcash_primitives/src/merkle_tree.rs | 4 +- zcash_primitives/src/transaction/builder.rs | 154 ++++++------- .../src/transaction/components.rs | 42 ++-- .../src/transaction/components/orchard.rs | 19 +- .../src/transaction/components/sapling.rs | 67 +++--- .../src/transaction/components/sprout.rs | 17 +- zcash_primitives/src/transaction/fees.rs | 9 +- .../src/transaction/fees/fixed.rs | 17 +- .../src/transaction/fees/transparent.rs | 17 +- .../src/transaction/fees/zip317.rs | 25 +- zcash_primitives/src/transaction/mod.rs | 78 +++---- zcash_primitives/src/transaction/sighash.rs | 14 +- .../src/transaction/sighash_v4.rs | 22 +- .../src/transaction/sighash_v5.rs | 15 +- zcash_primitives/src/transaction/tests.rs | 17 +- .../src/transaction/tests/data.rs | 6 +- zcash_primitives/src/transaction/txid.rs | 29 ++- zcash_transparent/src/builder.rs | 22 +- 97 files changed, 1316 insertions(+), 1385 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index fe3cefaeb8..96720b09a3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1250,6 +1250,7 @@ dependencies = [ "zcash_proofs", "zcash_protocol", "zcash_transparent", + "zip32", ] [[package]] @@ -6248,6 +6249,7 @@ dependencies = [ "zcash_primitives", "zcash_proofs", "zcash_protocol", + "zcash_transparent", "zip32", "zip321", ] @@ -6297,6 +6299,7 @@ dependencies = [ "zcash_primitives", "zcash_proofs", "zcash_protocol", + "zcash_transparent", "zip32", "zip321", ] diff --git a/components/zcash_address/src/convert.rs b/components/zcash_address/src/convert.rs index f49ab2e4c6..5e0277b2bd 100644 --- a/components/zcash_address/src/convert.rs +++ b/components/zcash_address/src/convert.rs @@ -3,7 +3,9 @@ use core::fmt; #[cfg(feature = "std")] use std::error::Error; -use crate::{kind::*, AddressKind, Network, ZcashAddress}; +use zcash_protocol::consensus::NetworkType; + +use crate::{kind::*, AddressKind, ZcashAddress}; /// An error indicating that an address type is not supported for conversion. #[derive(Debug)] @@ -19,7 +21,10 @@ impl fmt::Display for UnsupportedAddress { #[derive(Debug)] pub enum ConversionError { /// The address is for the wrong network. - IncorrectNetwork { expected: Network, actual: Network }, + IncorrectNetwork { + expected: NetworkType, + actual: NetworkType, + }, /// The address type is not supported by the target type. Unsupported(UnsupportedAddress), /// A conversion error returned by the target type. @@ -60,7 +65,7 @@ impl Error for ConversionError { /// A helper trait for converting a [`ZcashAddress`] into a network-agnostic type. /// -/// A blanket implementation of [`TryFromAddress`] is provided for `(Network, T)` where +/// A blanket implementation of [`TryFromAddress`] is provided for `(NetworkType, T)` where /// `T: TryFromRawAddress`. /// /// [`ZcashAddress`]: crate::ZcashAddress @@ -68,7 +73,8 @@ impl Error for ConversionError { /// # Examples /// /// ``` -/// use zcash_address::{ConversionError, Network, TryFromRawAddress, UnsupportedAddress, ZcashAddress}; +/// use zcash_address::{ConversionError, TryFromRawAddress, UnsupportedAddress, ZcashAddress}; +/// use zcash_protocol::consensus::NetworkType; /// /// #[derive(Debug, PartialEq)] /// struct MySapling([u8; 43]); @@ -90,7 +96,7 @@ impl Error for ConversionError { /// /// // You can use `ZcashAddress::convert_if_network` to get your type directly. /// let addr: ZcashAddress = addr_string.parse().unwrap(); -/// let converted = addr.convert_if_network::(Network::Main); +/// let converted = addr.convert_if_network::(NetworkType::Main); /// assert!(converted.is_ok()); /// assert_eq!(converted.unwrap(), MySapling([0; 43])); /// @@ -98,7 +104,7 @@ impl Error for ConversionError { /// let addr: ZcashAddress = addr_string.parse().unwrap(); /// let converted = addr.convert::<(_, MySapling)>(); /// assert!(converted.is_ok()); -/// assert_eq!(converted.unwrap(), (Network::Main, MySapling([0; 43]))); +/// assert_eq!(converted.unwrap(), (NetworkType::Main, MySapling([0; 43]))); /// /// // For an unsupported address type, we get an error. /// let addr: ZcashAddress = "t1Hsc1LR8yKnbbe3twRp88p6vFfC5t7DLbs".parse().unwrap(); @@ -158,7 +164,8 @@ pub trait TryFromRawAddress: Sized { /// # Examples /// /// ``` -/// use zcash_address::{ConversionError, Network, TryFromAddress, UnsupportedAddress, ZcashAddress}; +/// use zcash_address::{ConversionError, TryFromAddress, UnsupportedAddress, ZcashAddress}; +/// use zcash_protocol::consensus::NetworkType; /// /// #[derive(Debug)] /// struct MySapling([u8; 43]); @@ -171,7 +178,7 @@ pub trait TryFromRawAddress: Sized { /// type Error = &'static str; /// /// fn try_from_sapling( -/// net: Network, +/// net: NetworkType, /// data: [u8; 43], /// ) -> Result> { /// Ok(MySapling(data)) @@ -197,13 +204,16 @@ pub trait TryFromAddress: Sized { /// [`Self::try_from_sapling`] as a valid Sapling address). type Error; - fn try_from_sprout(net: Network, data: [u8; 64]) -> Result> { + fn try_from_sprout( + net: NetworkType, + data: [u8; 64], + ) -> Result> { let _ = (net, data); Err(ConversionError::Unsupported(UnsupportedAddress("Sprout"))) } fn try_from_sapling( - net: Network, + net: NetworkType, data: [u8; 43], ) -> Result> { let _ = (net, data); @@ -211,7 +221,7 @@ pub trait TryFromAddress: Sized { } fn try_from_unified( - net: Network, + net: NetworkType, data: unified::Address, ) -> Result> { let _ = (net, data); @@ -219,7 +229,7 @@ pub trait TryFromAddress: Sized { } fn try_from_transparent_p2pkh( - net: Network, + net: NetworkType, data: [u8; 20], ) -> Result> { let _ = (net, data); @@ -229,7 +239,7 @@ pub trait TryFromAddress: Sized { } fn try_from_transparent_p2sh( - net: Network, + net: NetworkType, data: [u8; 20], ) -> Result> { let _ = (net, data); @@ -238,7 +248,10 @@ pub trait TryFromAddress: Sized { ))) } - fn try_from_tex(net: Network, data: [u8; 20]) -> Result> { + fn try_from_tex( + net: NetworkType, + data: [u8; 20], + ) -> Result> { let _ = (net, data); Err(ConversionError::Unsupported(UnsupportedAddress( "transparent-source restricted P2PKH", @@ -246,42 +259,48 @@ pub trait TryFromAddress: Sized { } } -impl TryFromAddress for (Network, T) { +impl TryFromAddress for (NetworkType, T) { type Error = T::Error; - fn try_from_sprout(net: Network, data: [u8; 64]) -> Result> { + fn try_from_sprout( + net: NetworkType, + data: [u8; 64], + ) -> Result> { T::try_from_raw_sprout(data).map(|addr| (net, addr)) } fn try_from_sapling( - net: Network, + net: NetworkType, data: [u8; 43], ) -> Result> { T::try_from_raw_sapling(data).map(|addr| (net, addr)) } fn try_from_unified( - net: Network, + net: NetworkType, data: unified::Address, ) -> Result> { T::try_from_raw_unified(data).map(|addr| (net, addr)) } fn try_from_transparent_p2pkh( - net: Network, + net: NetworkType, data: [u8; 20], ) -> Result> { T::try_from_raw_transparent_p2pkh(data).map(|addr| (net, addr)) } fn try_from_transparent_p2sh( - net: Network, + net: NetworkType, data: [u8; 20], ) -> Result> { T::try_from_raw_transparent_p2sh(data).map(|addr| (net, addr)) } - fn try_from_tex(net: Network, data: [u8; 20]) -> Result> { + fn try_from_tex( + net: NetworkType, + data: [u8; 20], + ) -> Result> { T::try_from_raw_tex(data).map(|addr| (net, addr)) } } @@ -298,44 +317,45 @@ impl TryFromAddress for (Network, T) { /// # Examples /// /// ``` -/// use zcash_address::{ToAddress, Network, ZcashAddress}; +/// use zcash_address::{ToAddress, ZcashAddress}; +/// use zcash_protocol::consensus::NetworkType; /// /// #[derive(Debug)] /// struct MySapling([u8; 43]); /// /// impl MySapling { /// /// Encodes this Sapling address for the given network. -/// fn encode(&self, net: Network) -> ZcashAddress { +/// fn encode(&self, net: NetworkType) -> ZcashAddress { /// ZcashAddress::from_sapling(net, self.0) /// } /// } /// /// let addr = MySapling([0; 43]); -/// let encoded = addr.encode(Network::Main); +/// let encoded = addr.encode(NetworkType::Main); /// assert_eq!( /// encoded.to_string(), /// "zs1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqpq6d8g", /// ); /// ``` pub trait ToAddress: private::Sealed { - fn from_sprout(net: Network, data: [u8; 64]) -> Self; + fn from_sprout(net: NetworkType, data: [u8; 64]) -> Self; - fn from_sapling(net: Network, data: [u8; 43]) -> Self; + fn from_sapling(net: NetworkType, data: [u8; 43]) -> Self; - fn from_unified(net: Network, data: unified::Address) -> Self; + fn from_unified(net: NetworkType, data: unified::Address) -> Self; - fn from_transparent_p2pkh(net: Network, data: [u8; 20]) -> Self; + fn from_transparent_p2pkh(net: NetworkType, data: [u8; 20]) -> Self; - fn from_transparent_p2sh(net: Network, data: [u8; 20]) -> Self; + fn from_transparent_p2sh(net: NetworkType, data: [u8; 20]) -> Self; - fn from_tex(net: Network, data: [u8; 20]) -> Self; + fn from_tex(net: NetworkType, data: [u8; 20]) -> Self; } impl ToAddress for ZcashAddress { - fn from_sprout(net: Network, data: [u8; 64]) -> Self { + fn from_sprout(net: NetworkType, data: [u8; 64]) -> Self { ZcashAddress { - net: if let Network::Regtest = net { - Network::Test + net: if let NetworkType::Regtest = net { + NetworkType::Test } else { net }, @@ -343,24 +363,24 @@ impl ToAddress for ZcashAddress { } } - fn from_sapling(net: Network, data: [u8; 43]) -> Self { + fn from_sapling(net: NetworkType, data: [u8; 43]) -> Self { ZcashAddress { net, kind: AddressKind::Sapling(data), } } - fn from_unified(net: Network, data: unified::Address) -> Self { + fn from_unified(net: NetworkType, data: unified::Address) -> Self { ZcashAddress { net, kind: AddressKind::Unified(data), } } - fn from_transparent_p2pkh(net: Network, data: [u8; 20]) -> Self { + fn from_transparent_p2pkh(net: NetworkType, data: [u8; 20]) -> Self { ZcashAddress { - net: if let Network::Regtest = net { - Network::Test + net: if let NetworkType::Regtest = net { + NetworkType::Test } else { net }, @@ -368,10 +388,10 @@ impl ToAddress for ZcashAddress { } } - fn from_transparent_p2sh(net: Network, data: [u8; 20]) -> Self { + fn from_transparent_p2sh(net: NetworkType, data: [u8; 20]) -> Self { ZcashAddress { - net: if let Network::Regtest = net { - Network::Test + net: if let NetworkType::Regtest = net { + NetworkType::Test } else { net }, @@ -379,7 +399,7 @@ impl ToAddress for ZcashAddress { } } - fn from_tex(net: Network, data: [u8; 20]) -> Self { + fn from_tex(net: NetworkType, data: [u8; 20]) -> Self { ZcashAddress { net, kind: AddressKind::Tex(data), diff --git a/components/zcash_address/src/encoding.rs b/components/zcash_address/src/encoding.rs index 0a28d60046..b514c21e32 100644 --- a/components/zcash_address/src/encoding.rs +++ b/components/zcash_address/src/encoding.rs @@ -186,7 +186,8 @@ mod tests { use assert_matches::assert_matches; use super::*; - use crate::{kind::unified, Network}; + use crate::kind::unified; + use zcash_protocol::consensus::NetworkType; fn encoding(encoded: &str, decoded: ZcashAddress) { assert_eq!(decoded.to_string(), encoded); @@ -197,11 +198,11 @@ mod tests { fn sprout() { encoding( "zc8E5gYid86n4bo2Usdq1cpr7PpfoJGzttwBHEEgGhGkLUg7SPPVFNB2AkRFXZ7usfphup5426dt1buMmY3fkYeRrQGLa8y", - ZcashAddress { net: Network::Main, kind: AddressKind::Sprout([0; 64]) }, + ZcashAddress { net: NetworkType::Main, kind: AddressKind::Sprout([0; 64]) }, ); encoding( "ztJ1EWLKcGwF2S4NA17pAJVdco8Sdkz4AQPxt1cLTEfNuyNswJJc2BbBqYrsRZsp31xbVZwhF7c7a2L9jsF3p3ZwRWpqqyS", - ZcashAddress { net: Network::Test, kind: AddressKind::Sprout([0; 64]) }, + ZcashAddress { net: NetworkType::Test, kind: AddressKind::Sprout([0; 64]) }, ); } @@ -210,21 +211,21 @@ mod tests { encoding( "zs1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqpq6d8g", ZcashAddress { - net: Network::Main, + net: NetworkType::Main, kind: AddressKind::Sapling([0; 43]), }, ); encoding( "ztestsapling1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqfhgwqu", ZcashAddress { - net: Network::Test, + net: NetworkType::Test, kind: AddressKind::Sapling([0; 43]), }, ); encoding( "zregtestsapling1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqknpr3m", ZcashAddress { - net: Network::Regtest, + net: NetworkType::Regtest, kind: AddressKind::Sapling([0; 43]), }, ); @@ -235,21 +236,21 @@ mod tests { encoding( "u1qpatys4zruk99pg59gcscrt7y6akvl9vrhcfyhm9yxvxz7h87q6n8cgrzzpe9zru68uq39uhmlpp5uefxu0su5uqyqfe5zp3tycn0ecl", ZcashAddress { - net: Network::Main, + net: NetworkType::Main, kind: AddressKind::Unified(unified::Address(vec![unified::address::Receiver::Sapling([0; 43])])), }, ); encoding( "utest10c5kutapazdnf8ztl3pu43nkfsjx89fy3uuff8tsmxm6s86j37pe7uz94z5jhkl49pqe8yz75rlsaygexk6jpaxwx0esjr8wm5ut7d5s", ZcashAddress { - net: Network::Test, + net: NetworkType::Test, kind: AddressKind::Unified(unified::Address(vec![unified::address::Receiver::Sapling([0; 43])])), }, ); encoding( "uregtest15xk7vj4grjkay6mnfl93dhsflc2yeunhxwdh38rul0rq3dfhzzxgm5szjuvtqdha4t4p2q02ks0jgzrhjkrav70z9xlvq0plpcjkd5z3", ZcashAddress { - net: Network::Regtest, + net: NetworkType::Regtest, kind: AddressKind::Unified(unified::Address(vec![unified::address::Receiver::Sapling([0; 43])])), }, ); @@ -266,28 +267,28 @@ mod tests { encoding( "t1Hsc1LR8yKnbbe3twRp88p6vFfC5t7DLbs", ZcashAddress { - net: Network::Main, + net: NetworkType::Main, kind: AddressKind::P2pkh([0; 20]), }, ); encoding( "tm9iMLAuYMzJ6jtFLcA7rzUmfreGuKvr7Ma", ZcashAddress { - net: Network::Test, + net: NetworkType::Test, kind: AddressKind::P2pkh([0; 20]), }, ); encoding( "t3JZcvsuaXE6ygokL4XUiZSTrQBUoPYFnXJ", ZcashAddress { - net: Network::Main, + net: NetworkType::Main, kind: AddressKind::P2sh([0; 20]), }, ); encoding( "t26YoyZ1iPgiMEWL4zGUm74eVWfhyDMXzY2", ZcashAddress { - net: Network::Test, + net: NetworkType::Test, kind: AddressKind::P2sh([0; 20]), }, ); @@ -300,7 +301,7 @@ mod tests { // Transcode P2PKH to TEX let p2pkh_zaddr: ZcashAddress = p2pkh_str.parse().unwrap(); - assert_matches!(p2pkh_zaddr.net, Network::Main); + assert_matches!(p2pkh_zaddr.net, NetworkType::Main); if let AddressKind::P2pkh(zaddr_data) = p2pkh_zaddr.kind { let tex_zaddr = ZcashAddress { net: p2pkh_zaddr.net, @@ -314,7 +315,7 @@ mod tests { // Transcode TEX to P2PKH let tex_zaddr: ZcashAddress = tex_str.parse().unwrap(); - assert_matches!(tex_zaddr.net, Network::Main); + assert_matches!(tex_zaddr.net, NetworkType::Main); if let AddressKind::Tex(zaddr_data) = tex_zaddr.kind { let p2pkh_zaddr = ZcashAddress { net: tex_zaddr.net, @@ -334,7 +335,7 @@ mod tests { // Transcode P2PKH to TEX let p2pkh_zaddr: ZcashAddress = p2pkh_str.parse().unwrap(); - assert_matches!(p2pkh_zaddr.net, Network::Test); + assert_matches!(p2pkh_zaddr.net, NetworkType::Test); if let AddressKind::P2pkh(zaddr_data) = p2pkh_zaddr.kind { let tex_zaddr = ZcashAddress { net: p2pkh_zaddr.net, @@ -348,7 +349,7 @@ mod tests { // Transcode TEX to P2PKH let tex_zaddr: ZcashAddress = tex_str.parse().unwrap(); - assert_matches!(tex_zaddr.net, Network::Test); + assert_matches!(tex_zaddr.net, NetworkType::Test); if let AddressKind::Tex(zaddr_data) = tex_zaddr.kind { let p2pkh_zaddr = ZcashAddress { net: tex_zaddr.net, @@ -366,14 +367,14 @@ mod tests { assert_eq!( " t1Hsc1LR8yKnbbe3twRp88p6vFfC5t7DLbs".parse(), Ok(ZcashAddress { - net: Network::Main, + net: NetworkType::Main, kind: AddressKind::P2pkh([0; 20]) }), ); assert_eq!( "t1Hsc1LR8yKnbbe3twRp88p6vFfC5t7DLbs ".parse(), Ok(ZcashAddress { - net: Network::Main, + net: NetworkType::Main, kind: AddressKind::P2pkh([0; 20]) }), ); diff --git a/components/zcash_address/src/kind/unified.rs b/components/zcash_address/src/kind/unified.rs index b92d572d33..ec5c79e160 100644 --- a/components/zcash_address/src/kind/unified.rs +++ b/components/zcash_address/src/kind/unified.rs @@ -12,7 +12,7 @@ use std::error::Error; use bech32::{primitives::decode::CheckedHrpstring, Bech32m, Checksum, Hrp}; -use crate::Network; +use zcash_protocol::consensus::NetworkType; pub(crate) mod address; pub(crate) mod fvk; @@ -171,8 +171,8 @@ pub(crate) mod private { use core2::io::Write; use super::{ParseError, Typecode, PADDING_LEN}; - use crate::Network; use zcash_encoding::CompactSize; + use zcash_protocol::consensus::NetworkType; /// A raw address or viewing key. pub trait SealedItem: for<'a> TryFrom<(u32, &'a [u8]), Error = ParseError> + Clone { @@ -205,21 +205,21 @@ pub(crate) mod private { /// general invariants that apply to all unified containers. fn from_inner(items: Vec) -> Self; - fn network_hrp(network: &Network) -> &'static str { + fn network_hrp(network: &NetworkType) -> &'static str { match network { - Network::Main => Self::MAINNET, - Network::Test => Self::TESTNET, - Network::Regtest => Self::REGTEST, + NetworkType::Main => Self::MAINNET, + NetworkType::Test => Self::TESTNET, + NetworkType::Regtest => Self::REGTEST, } } - fn hrp_network(hrp: &str) -> Option { + fn hrp_network(hrp: &str) -> Option { if hrp == Self::MAINNET { - Some(Network::Main) + Some(NetworkType::Main) } else if hrp == Self::TESTNET { - Some(Network::Test) + Some(NetworkType::Test) } else if hrp == Self::REGTEST { - Some(Network::Regtest) + Some(NetworkType::Regtest) } else { None } @@ -400,7 +400,7 @@ pub trait Encoding: private::SealedContainer { /// Decodes a unified container from its string representation, preserving /// the order of its components so that it correctly obeys round-trip /// serialization invariants. - fn decode(s: &str) -> Result<(Network, Self), ParseError> { + fn decode(s: &str) -> Result<(NetworkType, Self), ParseError> { if let Ok(parsed) = CheckedHrpstring::new::(s) { let hrp = parsed.hrp(); let hrp = hrp.as_str(); @@ -420,7 +420,7 @@ pub trait Encoding: private::SealedContainer { /// using the correct constants for the specified network, preserving the /// ordering of the contained items such that it correctly obeys round-trip /// serialization invariants. - fn encode(&self, network: &Network) -> String { + fn encode(&self, network: &NetworkType) -> String { let hrp = Self::network_hrp(network); bech32::encode::(Hrp::parse_unchecked(hrp), &self.to_jumbled_bytes(hrp)) .expect("F4Jumble ensures length is short enough by construction") diff --git a/components/zcash_address/src/kind/unified/address.rs b/components/zcash_address/src/kind/unified/address.rs index 6ff2958aa1..0a4423bf0c 100644 --- a/components/zcash_address/src/kind/unified/address.rs +++ b/components/zcash_address/src/kind/unified/address.rs @@ -254,11 +254,11 @@ mod tests { use alloc::borrow::ToOwned; use assert_matches::assert_matches; + use zcash_protocol::consensus::NetworkType; use crate::{ kind::unified::{private::SealedContainer, Container, Encoding}, unified::address::testing::arb_unified_address, - Network, }; use proptest::{prelude::*, sample::select}; @@ -268,7 +268,7 @@ mod tests { proptest! { #[test] fn ua_roundtrip( - network in select(vec![Network::Main, Network::Test, Network::Regtest]), + network in select(vec![NetworkType::Main, NetworkType::Test, NetworkType::Regtest]), ua in arb_unified_address(), ) { let encoded = ua.encode(&network); diff --git a/components/zcash_address/src/kind/unified/fvk.rs b/components/zcash_address/src/kind/unified/fvk.rs index 50131898f2..52655dc703 100644 --- a/components/zcash_address/src/kind/unified/fvk.rs +++ b/components/zcash_address/src/kind/unified/fvk.rs @@ -155,13 +155,11 @@ mod tests { use proptest::{array::uniform1, array::uniform32, prelude::*, sample::select}; use super::{Fvk, ParseError, Typecode, Ufvk}; - use crate::{ - kind::unified::{ - private::{SealedContainer, SealedItem}, - Container, Encoding, - }, - Network, + use crate::kind::unified::{ + private::{SealedContainer, SealedItem}, + Container, Encoding, }; + use zcash_protocol::consensus::NetworkType; prop_compose! { fn uniform128()(a in uniform96(), b in uniform32(0u8..)) -> [u8; 128] { @@ -226,7 +224,7 @@ mod tests { proptest! { #[test] fn ufvk_roundtrip( - network in select(vec![Network::Main, Network::Test, Network::Regtest]), + network in select(vec![NetworkType::Main, NetworkType::Test, NetworkType::Regtest]), ufvk in arb_unified_fvk(), ) { let encoded = ufvk.encode(&network); diff --git a/components/zcash_address/src/kind/unified/ivk.rs b/components/zcash_address/src/kind/unified/ivk.rs index 2024427aac..138c44fb09 100644 --- a/components/zcash_address/src/kind/unified/ivk.rs +++ b/components/zcash_address/src/kind/unified/ivk.rs @@ -164,13 +164,11 @@ mod tests { }; use super::{Ivk, ParseError, Typecode, Uivk}; - use crate::{ - kind::unified::{ - private::{SealedContainer, SealedItem}, - Container, Encoding, - }, - Network, + use crate::kind::unified::{ + private::{SealedContainer, SealedItem}, + Container, Encoding, }; + use zcash_protocol::consensus::NetworkType; prop_compose! { fn uniform64()(a in uniform32(0u8..), b in uniform32(0u8..)) -> [u8; 64] { @@ -219,7 +217,7 @@ mod tests { proptest! { #[test] fn uivk_roundtrip( - network in select(vec![Network::Main, Network::Test, Network::Regtest]), + network in select(vec![NetworkType::Main, NetworkType::Test, NetworkType::Regtest]), uivk in arb_unified_ivk(), ) { let encoded = uivk.encode(&network); @@ -308,7 +306,7 @@ mod tests { fn duplicate_typecode() { // Construct and serialize an invalid UIVK. let uivk = Uivk(vec![Ivk::Sapling([1; 64]), Ivk::Sapling([2; 64])]); - let encoded = uivk.encode(&Network::Main); + let encoded = uivk.encode(&NetworkType::Main); assert_eq!( Uivk::decode(&encoded), Err(ParseError::DuplicateTypecode(Typecode::Sapling)) diff --git a/components/zcash_address/src/lib.rs b/components/zcash_address/src/lib.rs index b2bb614927..110e8c7387 100644 --- a/components/zcash_address/src/lib.rs +++ b/components/zcash_address/src/lib.rs @@ -63,7 +63,8 @@ //! use std::ffi::{CStr, c_char, c_void}; //! use std::ptr; //! -//! use zcash_address::{ConversionError, Network, TryFromRawAddress, ZcashAddress}; +//! use zcash_address::{ConversionError, TryFromRawAddress, ZcashAddress}; +//! use zcash_protocol::consensus::NetworkType; //! //! // Functions that return a pointer to a heap-allocated address of the given kind in //! // the target language. These should be augmented to return any relevant errors. @@ -112,7 +113,7 @@ //! } //! }; //! -//! match addr.convert_if_network::(Network::Main) { +//! match addr.convert_if_network::(NetworkType::Main) { //! Ok(parsed) => parsed.0, //! Err(e) => { //! // We didn't implement all of the methods of `TryFromRawAddress`, so if an @@ -151,13 +152,13 @@ pub use convert::{ pub use encoding::ParseError; pub use kind::unified; use kind::unified::Receiver; -pub use zcash_protocol::consensus::NetworkType as Network; -use zcash_protocol::PoolType; +//pub use zcash_protocol::consensus::NetworkType as Network; +use zcash_protocol::{consensus::NetworkType, PoolType}; /// A Zcash address. #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct ZcashAddress { - net: Network, + net: NetworkType, kind: AddressKind, } @@ -254,13 +255,13 @@ impl ZcashAddress { /// [`address.to_string()`]: std::string::ToString pub fn convert_if_network( self, - net: Network, + net: NetworkType, ) -> Result> { let network_matches = self.net == net; // The Sprout and transparent address encodings use the same prefix for testnet // and regtest, so we need to allow parsing testnet addresses as regtest. let regtest_exception = - network_matches || (self.net == Network::Test && net == Network::Regtest); + network_matches || (self.net == NetworkType::Test && net == NetworkType::Regtest); match self.kind { AddressKind::Sprout(data) if regtest_exception => T::try_from_raw_sprout(data), diff --git a/components/zcash_address/src/test_vectors.rs b/components/zcash_address/src/test_vectors.rs index a502f266eb..a7278734eb 100644 --- a/components/zcash_address/src/test_vectors.rs +++ b/components/zcash_address/src/test_vectors.rs @@ -9,10 +9,11 @@ use { self, address::{test_vectors::TEST_VECTORS, Receiver}, }, - Network, ToAddress, ZcashAddress, + ToAddress, ZcashAddress, }, alloc::string::ToString, core::iter, + zcash_protocol::consensus::NetworkType, }; #[test] @@ -39,7 +40,8 @@ fn unified() { })) .collect(); - let expected_addr = ZcashAddress::from_unified(Network::Main, unified::Address(receivers)); + let expected_addr = + ZcashAddress::from_unified(NetworkType::Main, unified::Address(receivers)); // Test parsing let addr: ZcashAddress = tv.unified_addr.parse().unwrap(); diff --git a/devtools/Cargo.toml b/devtools/Cargo.toml index 56917a21ad..3f0095b308 100644 --- a/devtools/Cargo.toml +++ b/devtools/Cargo.toml @@ -24,6 +24,7 @@ zcash_note_encryption.workspace = true zcash_primitives = { workspace = true, features = ["transparent-inputs"] } zcash_proofs = { workspace = true, features = ["directories"] } zcash_protocol = {workspace = true, features = ["local-consensus"] } +zip32.workspace = true # Transparent secp256k1.workspace = true diff --git a/devtools/src/bin/inspect/address.rs b/devtools/src/bin/inspect/address.rs index 1c5aca0333..5f47d4e0d1 100644 --- a/devtools/src/bin/inspect/address.rs +++ b/devtools/src/bin/inspect/address.rs @@ -1,7 +1,8 @@ use zcash_address::{ unified::{self, Container, Encoding}, - ConversionError, Network, ToAddress, ZcashAddress, + ConversionError, ToAddress, ZcashAddress, }; +use zcash_protocol::consensus::NetworkType; #[allow(dead_code)] enum AddressKind { @@ -14,14 +15,17 @@ enum AddressKind { } struct Address { - net: Network, + net: NetworkType, kind: AddressKind, } impl zcash_address::TryFromAddress for Address { type Error = (); - fn try_from_sprout(net: Network, data: [u8; 64]) -> Result> { + fn try_from_sprout( + net: NetworkType, + data: [u8; 64], + ) -> Result> { Ok(Address { net, kind: AddressKind::Sprout(data), @@ -29,7 +33,7 @@ impl zcash_address::TryFromAddress for Address { } fn try_from_sapling( - net: Network, + net: NetworkType, data: [u8; 43], ) -> Result> { Ok(Address { @@ -39,7 +43,7 @@ impl zcash_address::TryFromAddress for Address { } fn try_from_unified( - net: Network, + net: NetworkType, data: unified::Address, ) -> Result> { Ok(Address { @@ -49,7 +53,7 @@ impl zcash_address::TryFromAddress for Address { } fn try_from_transparent_p2pkh( - net: Network, + net: NetworkType, data: [u8; 20], ) -> Result> { Ok(Address { @@ -59,7 +63,7 @@ impl zcash_address::TryFromAddress for Address { } fn try_from_transparent_p2sh( - net: Network, + net: NetworkType, data: [u8; 20], ) -> Result> { Ok(Address { @@ -68,7 +72,10 @@ impl zcash_address::TryFromAddress for Address { }) } - fn try_from_tex(net: Network, data: [u8; 20]) -> Result> { + fn try_from_tex( + net: NetworkType, + data: [u8; 20], + ) -> Result> { Ok(Address { net, kind: AddressKind::Tex(data), @@ -87,9 +94,9 @@ pub(crate) fn inspect(addr: ZcashAddress) { eprintln!( " - Network: {}", match addr.net { - Network::Main => "main", - Network::Test => "testnet", - Network::Regtest => "regtest", + NetworkType::Main => "main", + NetworkType::Test => "testnet", + NetworkType::Regtest => "regtest", } ); eprintln!( diff --git a/devtools/src/bin/inspect/block.rs b/devtools/src/bin/inspect/block.rs index f6a79b73c7..2c336d5f5c 100644 --- a/devtools/src/bin/inspect/block.rs +++ b/devtools/src/bin/inspect/block.rs @@ -7,12 +7,10 @@ use std::convert::{TryFrom, TryInto}; use std::io::{self, Read}; use sha2::{Digest, Sha256}; + use zcash_encoding::Vector; -use zcash_primitives::{ - block::BlockHeader, - consensus::{BlockHeight, BranchId, Network, NetworkUpgrade, Parameters}, - transaction::Transaction, -}; +use zcash_primitives::{block::BlockHeader, transaction::Transaction}; +use zcash_protocol::consensus::{BlockHeight, BranchId, Network, NetworkUpgrade, Parameters}; use crate::{ transaction::{extract_height_from_coinbase, is_coinbase}, diff --git a/devtools/src/bin/inspect/context.rs b/devtools/src/bin/inspect/context.rs index 9f78cd42cb..788c6c8f8e 100644 --- a/devtools/src/bin/inspect/context.rs +++ b/devtools/src/bin/inspect/context.rs @@ -2,16 +2,19 @@ use std::convert::TryFrom; use std::fmt; use std::str::FromStr; +use ::transparent::{ + address::Script, + bundle::{self as transparent, TxOut}, +}; use serde::{ de::{Unexpected, Visitor}, Deserialize, Serialize, Serializer, }; -use zcash_primitives::{ - consensus::Network, - legacy::Script, - transaction::components::{amount::NonNegativeAmount, transparent, TxOut}, - zip32::AccountId, +use zcash_protocol::{ + consensus::{Network, NetworkType}, + value::Zatoshis, }; +use zip32::AccountId; #[derive(Clone, Copy, Debug)] pub(crate) struct JsonNetwork(Network); @@ -170,7 +173,7 @@ impl fmt::Display for ZUint256 { } #[derive(Clone, Debug)] -struct ZOutputValue(NonNegativeAmount); +struct ZOutputValue(Zatoshis); struct ZOutputValueVisitor; @@ -185,7 +188,7 @@ impl<'de> Visitor<'de> for ZOutputValueVisitor { where E: serde::de::Error, { - NonNegativeAmount::from_u64(v) + Zatoshis::from_u64(v) .map(ZOutputValue) .map_err(|e| match e { zcash_protocol::value::BalanceError::Overflow => serde::de::Error::invalid_type( @@ -297,10 +300,10 @@ impl Context { self.network.map(|n| n.0) } - pub(crate) fn addr_network(&self) -> Option { + pub(crate) fn addr_network(&self) -> Option { self.network().map(|params| match params { - Network::MainNetwork => zcash_address::Network::Main, - Network::TestNetwork => zcash_address::Network::Test, + Network::MainNetwork => NetworkType::Main, + Network::TestNetwork => NetworkType::Test, }) } diff --git a/devtools/src/bin/inspect/keys.rs b/devtools/src/bin/inspect/keys.rs index a828931751..969adf19d6 100644 --- a/devtools/src/bin/inspect/keys.rs +++ b/devtools/src/bin/inspect/keys.rs @@ -3,18 +3,16 @@ use std::iter; use bech32::{Bech32, Hrp}; use secrecy::Zeroize; + +use ::transparent::{ + address::TransparentAddress, + keys::{AccountPrivKey, IncomingViewingKey}, +}; use zcash_address::{ unified::{self, Encoding}, ToAddress, ZcashAddress, }; use zcash_keys::keys::UnifiedFullViewingKey; -use zcash_primitives::{ - legacy::{ - keys::{AccountPrivKey, IncomingViewingKey}, - TransparentAddress, - }, - zip32, -}; use zcash_protocol::{ consensus::{Network, NetworkConstants, NetworkType}, local_consensus::LocalNetwork, diff --git a/devtools/src/bin/inspect/main.rs b/devtools/src/bin/inspect/main.rs index 2540fbb6da..72acea932c 100644 --- a/devtools/src/bin/inspect/main.rs +++ b/devtools/src/bin/inspect/main.rs @@ -9,17 +9,20 @@ use gumdrop::{Options, ParsingStyle}; use lazy_static::lazy_static; use secrecy::Zeroize; use tokio::runtime::Runtime; + use zcash_address::{ unified::{self, Encoding}, ZcashAddress, }; -use zcash_primitives::{block::BlockHeader, consensus::BranchId, transaction::Transaction}; +use zcash_primitives::{block::BlockHeader, transaction::Transaction}; use zcash_proofs::{default_params_folder, load_parameters, ZcashParameters}; -use zcash_protocol::consensus::NetworkType; +use zcash_protocol::{ + consensus::{BranchId, NetworkType}, + constants, +}; mod context; use context::{Context, ZUint256}; -use zcash_protocol::constants; mod address; mod block; diff --git a/devtools/src/bin/inspect/transaction.rs b/devtools/src/bin/inspect/transaction.rs index bfb8bbc3aa..e259a17b0c 100644 --- a/devtools/src/bin/inspect/transaction.rs +++ b/devtools/src/bin/inspect/transaction.rs @@ -3,28 +3,34 @@ use std::{ convert::{TryFrom, TryInto}, }; -use ::transparent::sighash::SighashType; use bellman::groth16; use group::GroupEncoding; use orchard::note_encryption::OrchardDomain; use sapling::{note_encryption::SaplingDomain, SaplingVerificationContext}; use secp256k1::{Secp256k1, VerifyOnly}; + +#[allow(deprecated)] +use ::transparent::{ + address::{Script, TransparentAddress}, + bundle as transparent, + keys::pubkey_to_address, + sighash::{SighashType, TransparentAuthorizingContext}, +}; use zcash_address::{ unified::{self, Encoding}, ToAddress, ZcashAddress, }; use zcash_note_encryption::try_output_recovery_with_ovk; -#[allow(deprecated)] -use zcash_primitives::{ +use zcash_primitives::transaction::{ + components::sapling as sapling_serialization, + sighash::{signature_hash, SignableInput}, + txid::TxIdDigester, + Authorization, Transaction, TransactionData, TxId, TxVersion, +}; +use zcash_protocol::{ consensus::BlockHeight, - legacy::{keys::pubkey_to_address, Script, TransparentAddress}, memo::{Memo, MemoBytes}, - transaction::{ - components::{amount::NonNegativeAmount, sapling as sapling_serialization, transparent}, - sighash::{signature_hash, SignableInput, TransparentAuthorizingContext}, - txid::TxIdDigester, - Authorization, Transaction, TransactionData, TxId, TxVersion, - }, + value::Zatoshis, }; use crate::{ @@ -109,7 +115,7 @@ impl transparent::Authorization for TransparentAuth { } impl TransparentAuthorizingContext for TransparentAuth { - fn input_amounts(&self) -> Vec { + fn input_amounts(&self) -> Vec { self.all_prev_outputs .iter() .map(|prevout| prevout.value) diff --git a/pczt/src/roles/creator/mod.rs b/pczt/src/roles/creator/mod.rs index 639d72055d..dd6b8dd386 100644 --- a/pczt/src/roles/creator/mod.rs +++ b/pczt/src/roles/creator/mod.rs @@ -103,7 +103,7 @@ impl Creator { pub fn build_from_parts( parts: zcash_primitives::transaction::builder::PcztParts

, ) -> Option { - use zcash_primitives::transaction::sighash::{SIGHASH_ANYONECANPAY, SIGHASH_SINGLE}; + use ::transparent::sighash::{SIGHASH_ANYONECANPAY, SIGHASH_SINGLE}; use zcash_protocol::consensus::NetworkConstants; use crate::{common::FLAG_HAS_SIGHASH_SINGLE, SAPLING_TX_VERSION}; diff --git a/pczt/src/roles/signer/mod.rs b/pczt/src/roles/signer/mod.rs index a75b86dcf2..456ac2be89 100644 --- a/pczt/src/roles/signer/mod.rs +++ b/pczt/src/roles/signer/mod.rs @@ -1,10 +1,10 @@ use blake2b_simd::Hash as Blake2bHash; use rand_core::OsRng; + +use ::transparent::sighash::{SIGHASH_ANYONECANPAY, SIGHASH_NONE, SIGHASH_SINGLE}; use zcash_primitives::transaction::{ - sighash::{SignableInput, SIGHASH_ANYONECANPAY, SIGHASH_NONE, SIGHASH_SINGLE}, - sighash_v5::v5_signature_hash, - txid::TxIdDigester, - Authorization, TransactionData, TxDigests, TxVersion, + sighash::SignableInput, sighash_v5::v5_signature_hash, txid::TxIdDigester, Authorization, + TransactionData, TxDigests, TxVersion, }; use zcash_protocol::consensus::BranchId; diff --git a/pczt/src/roles/tx_extractor/mod.rs b/pczt/src/roles/tx_extractor/mod.rs index bb104b2337..950a419bd5 100644 --- a/pczt/src/roles/tx_extractor/mod.rs +++ b/pczt/src/roles/tx_extractor/mod.rs @@ -1,14 +1,12 @@ use core::marker::PhantomData; - use rand_core::OsRng; -use zcash_primitives::{ - consensus::BranchId, - transaction::{ - sighash::{signature_hash, SignableInput}, - txid::TxIdDigester, - Authorization, Transaction, TransactionData, TxVersion, - }, + +use zcash_primitives::transaction::{ + sighash::{signature_hash, SignableInput}, + txid::TxIdDigester, + Authorization, Transaction, TransactionData, TxVersion, }; +use zcash_protocol::consensus::BranchId; use crate::{Pczt, V5_TX_VERSION, V5_VERSION_GROUP_ID}; diff --git a/pczt/tests/end_to_end.rs b/pczt/tests/end_to_end.rs index 69da339eff..1a8965d113 100644 --- a/pczt/tests/end_to_end.rs +++ b/pczt/tests/end_to_end.rs @@ -1,5 +1,10 @@ +use rand_core::OsRng; use std::sync::OnceLock; +use ::transparent::{ + bundle as transparent, + keys::{AccountPrivKey, IncomingViewingKey}, +}; use orchard::tree::MerkleHashOrchard; use pczt::{ roles::{ @@ -9,16 +14,11 @@ use pczt::{ }, Pczt, }; -use rand_core::OsRng; use shardtree::{store::memory::MemoryShardStore, ShardTree}; use zcash_note_encryption::try_note_decryption; -use zcash_primitives::{ - legacy::keys::{AccountPrivKey, IncomingViewingKey}, - transaction::{ - builder::{BuildConfig, Builder, PcztResult}, - components::transparent, - fees::zip317, - }, +use zcash_primitives::transaction::{ + builder::{BuildConfig, Builder, PcztResult}, + fees::zip317, }; use zcash_proofs::prover::LocalTxProver; use zcash_protocol::{consensus::MainNetwork, memo::MemoBytes, value::Zatoshis}; diff --git a/zcash_client_backend/Cargo.toml b/zcash_client_backend/Cargo.toml index 1266e58aef..110012c48e 100644 --- a/zcash_client_backend/Cargo.toml +++ b/zcash_client_backend/Cargo.toml @@ -33,6 +33,7 @@ zcash_primitives.workspace = true zcash_protocol.workspace = true zip32.workspace = true zip321.workspace = true +transparent.workspace = true pczt = { workspace = true, optional = true } # Dependencies exposed in a public API: diff --git a/zcash_client_backend/examples/diversify-address.rs b/zcash_client_backend/examples/diversify-address.rs index 809b109e8c..6e0b35ec21 100644 --- a/zcash_client_backend/examples/diversify-address.rs +++ b/zcash_client_backend/examples/diversify-address.rs @@ -1,10 +1,8 @@ use gumdrop::Options; use sapling::zip32::ExtendedFullViewingKey; -use zcash_client_backend::encoding::{decode_extended_full_viewing_key, encode_payment_address}; -use zcash_primitives::{ - constants::{mainnet, testnet}, - zip32::DiversifierIndex, -}; +use zcash_keys::encoding::{decode_extended_full_viewing_key, encode_payment_address}; +use zcash_protocol::constants::{mainnet, testnet}; +use zip32::DiversifierIndex; fn parse_viewing_key(s: &str) -> Result<(ExtendedFullViewingKey, bool), &'static str> { decode_extended_full_viewing_key(mainnet::HRP_SAPLING_EXTENDED_FULL_VIEWING_KEY, s) diff --git a/zcash_client_backend/src/data_api.rs b/zcash_client_backend/src/data_api.rs index 715624c19e..c10df8cdfe 100644 --- a/zcash_client_backend/src/data_api.rs +++ b/zcash_client_backend/src/data_api.rs @@ -55,6 +55,8 @@ //! [`TransactionRequest`]: crate::zip321::TransactionRequest //! [`propose_shielding`]: crate::data_api::wallet::propose_shielding +use nonempty::NonEmpty; +use secrecy::SecretVec; use std::{ collections::HashMap, fmt::Debug, @@ -64,49 +66,48 @@ use std::{ }; use incrementalmerkletree::{frontier::Frontier, Retention}; -use nonempty::NonEmpty; -use secrecy::SecretVec; use shardtree::{error::ShardTreeError, store::ShardStore, ShardTree}; -use zip32::fingerprint::SeedFingerprint; -use self::{ - chain::{ChainState, CommitmentTreeRoot}, - scanning::ScanRange, -}; -use crate::{ +use ::transparent::bundle::OutPoint; +use zcash_keys::{ address::UnifiedAddress, - decrypt::DecryptedOutput, keys::{ UnifiedAddressRequest, UnifiedFullViewingKey, UnifiedIncomingViewingKey, UnifiedSpendingKey, }, - proto::service::TreeState, - wallet::{Note, NoteId, ReceivedNote, Recipient, WalletTransparentOutput, WalletTx}, - ShieldedProtocol, }; use zcash_primitives::{ block::BlockHash, + transaction::{Transaction, TxId}, +}; +use zcash_protocol::{ consensus::BlockHeight, memo::{Memo, MemoBytes}, - transaction::{ - components::{ - amount::{BalanceError, NonNegativeAmount}, - OutPoint, - }, - Transaction, TxId, - }, + value::{BalanceError, Zatoshis}, + ShieldedProtocol, +}; +use zip32::fingerprint::SeedFingerprint; + +use self::{ + chain::{ChainState, CommitmentTreeRoot}, + scanning::ScanRange, +}; +use crate::{ + decrypt::DecryptedOutput, + proto::service::TreeState, + wallet::{Note, NoteId, ReceivedNote, Recipient, WalletTransparentOutput, WalletTx}, }; #[cfg(feature = "transparent-inputs")] use { - crate::wallet::TransparentAddressMetadata, std::ops::Range, - zcash_primitives::legacy::TransparentAddress, + crate::wallet::TransparentAddressMetadata, ::transparent::address::TransparentAddress, + std::ops::Range, }; #[cfg(feature = "test-dependencies")] use ambassador::delegatable_trait; #[cfg(any(test, feature = "test-dependencies"))] -use {zcash_keys::address::Address, zcash_primitives::consensus::NetworkUpgrade}; +use {zcash_keys::address::Address, zcash_protocol::consensus::NetworkUpgrade}; pub mod chain; pub mod error; @@ -143,23 +144,20 @@ pub enum NullifierQuery { /// Balance information for a value within a single pool in an account. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Balance { - spendable_value: NonNegativeAmount, - change_pending_confirmation: NonNegativeAmount, - value_pending_spendability: NonNegativeAmount, + spendable_value: Zatoshis, + change_pending_confirmation: Zatoshis, + value_pending_spendability: Zatoshis, } impl Balance { /// The [`Balance`] value having zero values for all its fields. pub const ZERO: Self = Self { - spendable_value: NonNegativeAmount::ZERO, - change_pending_confirmation: NonNegativeAmount::ZERO, - value_pending_spendability: NonNegativeAmount::ZERO, + spendable_value: Zatoshis::ZERO, + change_pending_confirmation: Zatoshis::ZERO, + value_pending_spendability: Zatoshis::ZERO, }; - fn check_total_adding( - &self, - value: NonNegativeAmount, - ) -> Result { + fn check_total_adding(&self, value: Zatoshis) -> Result { (self.spendable_value + self.change_pending_confirmation + self.value_pending_spendability @@ -170,12 +168,12 @@ impl Balance { /// Returns the value in the account that may currently be spent; it is possible to compute /// witnesses for all the notes that comprise this value, and all of this value is confirmed to /// the required confirmation depth. - pub fn spendable_value(&self) -> NonNegativeAmount { + pub fn spendable_value(&self) -> Zatoshis { self.spendable_value } /// Adds the specified value to the spendable total, checking for overflow. - pub fn add_spendable_value(&mut self, value: NonNegativeAmount) -> Result<(), BalanceError> { + pub fn add_spendable_value(&mut self, value: Zatoshis) -> Result<(), BalanceError> { self.check_total_adding(value)?; self.spendable_value = (self.spendable_value + value).unwrap(); Ok(()) @@ -183,15 +181,12 @@ impl Balance { /// Returns the value in the account of shielded change notes that do not yet have sufficient /// confirmations to be spendable. - pub fn change_pending_confirmation(&self) -> NonNegativeAmount { + pub fn change_pending_confirmation(&self) -> Zatoshis { self.change_pending_confirmation } /// Adds the specified value to the pending change total, checking for overflow. - pub fn add_pending_change_value( - &mut self, - value: NonNegativeAmount, - ) -> Result<(), BalanceError> { + pub fn add_pending_change_value(&mut self, value: Zatoshis) -> Result<(), BalanceError> { self.check_total_adding(value)?; self.change_pending_confirmation = (self.change_pending_confirmation + value).unwrap(); Ok(()) @@ -200,22 +195,19 @@ impl Balance { /// Returns the value in the account of all remaining received notes that either do not have /// sufficient confirmations to be spendable, or for which witnesses cannot yet be constructed /// without additional scanning. - pub fn value_pending_spendability(&self) -> NonNegativeAmount { + pub fn value_pending_spendability(&self) -> Zatoshis { self.value_pending_spendability } /// Adds the specified value to the pending spendable total, checking for overflow. - pub fn add_pending_spendable_value( - &mut self, - value: NonNegativeAmount, - ) -> Result<(), BalanceError> { + pub fn add_pending_spendable_value(&mut self, value: Zatoshis) -> Result<(), BalanceError> { self.check_total_adding(value)?; self.value_pending_spendability = (self.value_pending_spendability + value).unwrap(); Ok(()) } /// Returns the total value of funds represented by this [`Balance`]. - pub fn total(&self) -> NonNegativeAmount { + pub fn total(&self) -> Zatoshis { (self.spendable_value + self.change_pending_confirmation + self.value_pending_spendability) .expect("Balance cannot overflow MAX_MONEY") } @@ -243,7 +235,7 @@ impl AccountBalance { unshielded_balance: Balance::ZERO, }; - fn check_total(&self) -> Result { + fn check_total(&self) -> Result { (self.sapling_balance.total() + self.orchard_balance.total() + self.unshielded_balance.total()) @@ -288,7 +280,7 @@ impl AccountBalance { #[deprecated( note = "this function is deprecated. Please use [`AccountBalance::unshielded_balance`] instead." )] - pub fn unshielded(&self) -> NonNegativeAmount { + pub fn unshielded(&self) -> Zatoshis { self.unshielded_balance.total() } @@ -310,7 +302,7 @@ impl AccountBalance { } /// Returns the total value of funds belonging to the account. - pub fn total(&self) -> NonNegativeAmount { + pub fn total(&self) -> Zatoshis { (self.sapling_balance.total() + self.orchard_balance.total() + self.unshielded_balance.total()) @@ -319,14 +311,14 @@ impl AccountBalance { /// Returns the total value of shielded (Sapling and Orchard) funds that may immediately be /// spent. - pub fn spendable_value(&self) -> NonNegativeAmount { + pub fn spendable_value(&self) -> Zatoshis { (self.sapling_balance.spendable_value + self.orchard_balance.spendable_value) .expect("Account balance cannot overflow MAX_MONEY") } /// Returns the total value of change and/or shielding transaction outputs that are awaiting /// sufficient confirmations for spendability. - pub fn change_pending_confirmation(&self) -> NonNegativeAmount { + pub fn change_pending_confirmation(&self) -> Zatoshis { (self.sapling_balance.change_pending_confirmation + self.orchard_balance.change_pending_confirmation) .expect("Account balance cannot overflow MAX_MONEY") @@ -334,7 +326,7 @@ impl AccountBalance { /// Returns the value of shielded funds that are not yet spendable because additional scanning /// is required before it will be possible to derive witnesses for the associated notes. - pub fn value_pending_spendability(&self) -> NonNegativeAmount { + pub fn value_pending_spendability(&self) -> Zatoshis { (self.sapling_balance.value_pending_spendability + self.orchard_balance.value_pending_spendability) .expect("Account balance cannot overflow MAX_MONEY") @@ -821,26 +813,22 @@ impl SpendableNotes { } /// Computes the total value of Sapling notes. - pub fn sapling_value(&self) -> Result { - self.sapling - .iter() - .try_fold(NonNegativeAmount::ZERO, |acc, n| { - (acc + n.note_value()?).ok_or(BalanceError::Overflow) - }) + pub fn sapling_value(&self) -> Result { + self.sapling.iter().try_fold(Zatoshis::ZERO, |acc, n| { + (acc + n.note_value()?).ok_or(BalanceError::Overflow) + }) } /// Computes the total value of Sapling notes. #[cfg(feature = "orchard")] - pub fn orchard_value(&self) -> Result { - self.orchard - .iter() - .try_fold(NonNegativeAmount::ZERO, |acc, n| { - (acc + n.note_value()?).ok_or(BalanceError::Overflow) - }) + pub fn orchard_value(&self) -> Result { + self.orchard.iter().try_fold(Zatoshis::ZERO, |acc, n| { + (acc + n.note_value()?).ok_or(BalanceError::Overflow) + }) } /// Computes the total value of spendable inputs - pub fn total_value(&self) -> Result { + pub fn total_value(&self) -> Result { #[cfg(not(feature = "orchard"))] return self.sapling_value(); @@ -878,12 +866,12 @@ impl SpendableNotes { #[derive(Debug, Clone)] pub struct PoolMeta { note_count: usize, - value: NonNegativeAmount, + value: Zatoshis, } impl PoolMeta { /// Constructs a new [`PoolMeta`] value from its constituent parts. - pub fn new(note_count: usize, value: NonNegativeAmount) -> Self { + pub fn new(note_count: usize, value: Zatoshis) -> Self { Self { note_count, value } } @@ -895,7 +883,7 @@ impl PoolMeta { /// Returns the total value of unspent outputs in the account that are accounted for in /// [`Self::note_count`]. - pub fn value(&self) -> NonNegativeAmount { + pub fn value(&self) -> Zatoshis { self.value } } @@ -967,11 +955,11 @@ impl AccountMeta { s.zip(o).map(|(s, o)| s + o).or(s).or(o) } - fn sapling_value(&self) -> Option { + fn sapling_value(&self) -> Option { self.sapling.as_ref().map(|m| m.value) } - fn orchard_value(&self) -> Option { + fn orchard_value(&self) -> Option { self.orchard.as_ref().map(|m| m.value) } @@ -980,7 +968,7 @@ impl AccountMeta { /// Returns [`None`] if no metadata is available or it was not possible to evaluate the query /// described by a [`NoteFilter`] given the available wallet data. If metadata is available /// only for a single pool, the metadata for that pool will be returned. - pub fn total_value(&self) -> Option { + pub fn total_value(&self) -> Option { let s = self.sapling_value(); let o = self.orchard_value(); s.zip(o) @@ -1041,7 +1029,7 @@ impl From> for usize { #[derive(Clone, Debug, PartialEq, Eq)] pub enum NoteFilter { /// Selects notes having value greater than or equal to the provided value. - ExceedsMinValue(NonNegativeAmount), + ExceedsMinValue(Zatoshis), /// Selects notes having value greater than or equal to approximately the n'th percentile of /// previously sent notes in the account, irrespective of pool. The wrapped value must be in /// the range `1..=99`. The value `n` is respected in a best-effort fashion; results are likely @@ -1123,7 +1111,7 @@ pub trait InputSource { fn select_spendable_notes( &self, account: Self::AccountId, - target_value: NonNegativeAmount, + target_value: Zatoshis, sources: &[ShieldedProtocol], anchor_height: BlockHeight, exclude: &[Self::NoteRef], @@ -1398,7 +1386,7 @@ pub trait WalletRead { &self, _account: Self::AccountId, _max_height: BlockHeight, - ) -> Result, Self::Error> { + ) -> Result, Self::Error> { Ok(HashMap::new()) } @@ -1600,7 +1588,7 @@ pub trait WalletTest: InputSource + WalletRead { #[allow(dead_code)] #[derive(Clone, Debug)] pub struct OutputOfSentTx { - value: NonNegativeAmount, + value: Zatoshis, external_recipient: Option

, ephemeral_address: Option<(Address, u32)>, } @@ -1613,7 +1601,7 @@ impl OutputOfSentTx { /// address along with the `address_index` it was derived from under the BIP 32 path /// `m/44'/'/'/2/`. pub fn from_parts( - value: NonNegativeAmount, + value: Zatoshis, external_recipient: Option
, ephemeral_address: Option<(Address, u32)>, ) -> Self { @@ -1903,7 +1891,7 @@ pub struct SentTransaction<'a, AccountId> { target_height: BlockHeight, account: AccountId, outputs: &'a [SentTransactionOutput], - fee_amount: NonNegativeAmount, + fee_amount: Zatoshis, #[cfg(feature = "transparent-inputs")] utxos_spent: &'a [OutPoint], } @@ -1926,7 +1914,7 @@ impl<'a, AccountId> SentTransaction<'a, AccountId> { target_height: BlockHeight, account: AccountId, outputs: &'a [SentTransactionOutput], - fee_amount: NonNegativeAmount, + fee_amount: Zatoshis, #[cfg(feature = "transparent-inputs")] utxos_spent: &'a [OutPoint], ) -> Self { Self { @@ -1958,7 +1946,7 @@ impl<'a, AccountId> SentTransaction<'a, AccountId> { self.outputs } /// Returns the fee paid by the transaction. - pub fn fee_amount(&self) -> NonNegativeAmount { + pub fn fee_amount(&self) -> Zatoshis { self.fee_amount } /// Returns the list of UTXOs spent in the created transaction. @@ -1979,7 +1967,7 @@ impl<'a, AccountId> SentTransaction<'a, AccountId> { pub struct SentTransactionOutput { output_index: usize, recipient: Recipient, - value: NonNegativeAmount, + value: Zatoshis, memo: Option, } @@ -1996,7 +1984,7 @@ impl SentTransactionOutput { pub fn from_parts( output_index: usize, recipient: Recipient, - value: NonNegativeAmount, + value: Zatoshis, memo: Option, ) -> Self { Self { @@ -2022,7 +2010,7 @@ impl SentTransactionOutput { &self.recipient } /// Returns the value of the newly created output. - pub fn value(&self) -> NonNegativeAmount { + pub fn value(&self) -> Zatoshis { self.value } /// Returns the memo that was attached to the output, if any. This will only be `None` @@ -2136,7 +2124,7 @@ impl AccountBirthday { /// # Panics /// /// Panics if the activation height for the given network upgrade is not set. - pub fn from_activation( + pub fn from_activation( params: &P, network_upgrade: NetworkUpgrade, prior_block_hash: BlockHash, @@ -2157,7 +2145,7 @@ impl AccountBirthday { /// # Panics /// /// Panics if the Sapling activation height is not set. - pub fn from_sapling_activation( + pub fn from_sapling_activation( params: &P, prior_block_hash: BlockHash, ) -> AccountBirthday { diff --git a/zcash_client_backend/src/data_api/chain.rs b/zcash_client_backend/src/data_api/chain.rs index f05394fe42..d64392e288 100644 --- a/zcash_client_backend/src/data_api/chain.rs +++ b/zcash_client_backend/src/data_api/chain.rs @@ -155,10 +155,8 @@ use std::ops::Range; use incrementalmerkletree::frontier::Frontier; use subtle::ConditionallySelectable; -use zcash_primitives::{ - block::BlockHash, - consensus::{self, BlockHeight}, -}; +use zcash_primitives::block::BlockHash; +use zcash_protocol::consensus::{self, BlockHeight}; use crate::{ data_api::{NullifierQuery, WalletWrite}, @@ -701,7 +699,7 @@ where #[cfg(feature = "test-dependencies")] pub mod testing { use std::convert::Infallible; - use zcash_primitives::consensus::BlockHeight; + use zcash_protocol::consensus::BlockHeight; use crate::proto::compact_formats::CompactBlock; diff --git a/zcash_client_backend/src/data_api/error.rs b/zcash_client_backend/src/data_api/error.rs index e5a26a9a41..90284563ba 100644 --- a/zcash_client_backend/src/data_api/error.rs +++ b/zcash_client_backend/src/data_api/error.rs @@ -5,22 +5,20 @@ use std::fmt::{self, Debug, Display}; use shardtree::error::ShardTreeError; use zcash_address::ConversionError; -use zcash_primitives::transaction::components::amount::NonNegativeAmount; -use zcash_primitives::transaction::{ - builder, - components::{amount::BalanceError, transparent}, +use zcash_keys::address::UnifiedAddress; +use zcash_primitives::transaction::builder; +use zcash_protocol::{ + value::{BalanceError, Zatoshis}, + PoolType, }; -use crate::address::UnifiedAddress; -use crate::data_api::wallet::input_selection::InputSelectorError; -use crate::fees::ChangeError; -use crate::proposal::ProposalError; -use crate::PoolType; +use crate::{ + data_api::wallet::input_selection::InputSelectorError, fees::ChangeError, + proposal::ProposalError, wallet::NoteId, +}; #[cfg(feature = "transparent-inputs")] -use zcash_primitives::legacy::TransparentAddress; - -use crate::wallet::NoteId; +use ::transparent::address::TransparentAddress; /// Errors that can occur as a consequence of wallet operations. #[derive(Debug)] @@ -62,8 +60,8 @@ pub enum Error From for Error From for Error { - fn from(e: transparent::builder::Error) -> Self { + fn from(e: ::transparent::builder::Error) -> Self { Error::Builder(builder::Error::TransparentBuild(e)) } } diff --git a/zcash_client_backend/src/data_api/scanning.rs b/zcash_client_backend/src/data_api/scanning.rs index a03abd62f8..0ab42f2df8 100644 --- a/zcash_client_backend/src/data_api/scanning.rs +++ b/zcash_client_backend/src/data_api/scanning.rs @@ -3,7 +3,7 @@ use std::fmt; use std::ops::Range; -use zcash_primitives::consensus::BlockHeight; +use zcash_protocol::consensus::BlockHeight; #[cfg(feature = "unstable-spanning-tree")] pub mod spanning_tree; diff --git a/zcash_client_backend/src/data_api/scanning/spanning_tree.rs b/zcash_client_backend/src/data_api/scanning/spanning_tree.rs index 58631de8fb..a0dd5c826f 100644 --- a/zcash_client_backend/src/data_api/scanning/spanning_tree.rs +++ b/zcash_client_backend/src/data_api/scanning/spanning_tree.rs @@ -1,7 +1,7 @@ use std::cmp::{max, Ordering}; use std::ops::{Not, Range}; -use zcash_primitives::consensus::BlockHeight; +use zcash_protocol::consensus::BlockHeight; use super::{ScanPriority, ScanRange}; @@ -397,7 +397,7 @@ impl SpanningTree { pub mod testing { use std::ops::Range; - use zcash_primitives::consensus::BlockHeight; + use zcash_protocol::consensus::BlockHeight; use crate::data_api::scanning::{ScanPriority, ScanRange}; @@ -413,7 +413,7 @@ pub mod testing { mod tests { use std::ops::Range; - use zcash_primitives::consensus::BlockHeight; + use zcash_protocol::consensus::BlockHeight; use super::{join_nonoverlapping, testing::scan_range, Joined, RangeOrdering, SpanningTree}; use crate::data_api::scanning::{ScanPriority, ScanRange}; diff --git a/zcash_client_backend/src/data_api/testing.rs b/zcash_client_backend/src/data_api/testing.rs index 4eb469994f..27c845e0bf 100644 --- a/zcash_client_backend/src/data_api/testing.rs +++ b/zcash_client_backend/src/data_api/testing.rs @@ -24,41 +24,36 @@ use shardtree::{error::ShardTreeError, store::memory::MemoryShardStore, ShardTre use subtle::ConditionallySelectable; use zcash_address::ZcashAddress; -use zcash_keys::address::Address; +use zcash_keys::{ + address::{Address, UnifiedAddress}, + keys::{UnifiedAddressRequest, UnifiedFullViewingKey, UnifiedSpendingKey}, +}; use zcash_note_encryption::Domain; use zcash_primitives::{ block::BlockHash, - consensus::{BlockHeight, Network}, - memo::Memo, - transaction::{ - components::{amount::NonNegativeAmount, sapling::zip212_enforcement}, - fees::FeeRule, - Transaction, TxId, - }, + transaction::{components::sapling::zip212_enforcement, fees::FeeRule, Transaction, TxId}, }; use zcash_proofs::prover::LocalTxProver; use zcash_protocol::{ - consensus::{self, NetworkUpgrade, Parameters as _}, + consensus::{self, BlockHeight, Network, NetworkUpgrade, Parameters as _}, local_consensus::LocalNetwork, - memo::MemoBytes, + memo::{Memo, MemoBytes}, value::{ZatBalance, Zatoshis}, + ShieldedProtocol, }; use zip32::{fingerprint::SeedFingerprint, DiversifierIndex}; use zip321::Payment; use crate::{ - address::UnifiedAddress, fees::{ standard::{self, SingleOutputChangeStrategy}, ChangeStrategy, DustOutputPolicy, StandardFeeRule, }, - keys::{UnifiedAddressRequest, UnifiedFullViewingKey, UnifiedSpendingKey}, proposal::Proposal, proto::compact_formats::{ self, CompactBlock, CompactSaplingOutput, CompactSaplingSpend, CompactTx, }, wallet::{Note, NoteId, OvkPolicy, ReceivedNote, WalletTransparentOutput}, - ShieldedProtocol, }; use super::{ @@ -80,7 +75,7 @@ use super::{error::Error, NoteFilter}; #[cfg(feature = "transparent-inputs")] use { super::wallet::input_selection::ShieldingSelector, crate::wallet::TransparentAddressMetadata, - std::ops::Range, zcash_primitives::legacy::TransparentAddress, + ::transparent::address::TransparentAddress, std::ops::Range, }; #[cfg(feature = "orchard")] @@ -525,7 +520,7 @@ where &mut self, fvk: &Fvk, address_type: AddressType, - value: NonNegativeAmount, + value: Zatoshis, ) -> (BlockHeight, Cache::InsertResult, Fvk::Nullifier) { let pre_activation_block = CachedBlock::none(self.sapling_activation_height() - 1); let prior_cached_block = self.latest_cached_block().unwrap_or(&pre_activation_block); @@ -691,9 +686,9 @@ where pub fn generate_next_block_spending( &mut self, fvk: &Fvk, - note: (Fvk::Nullifier, NonNegativeAmount), + note: (Fvk::Nullifier, Zatoshis), to: impl Into
, - value: NonNegativeAmount, + value: Zatoshis, ) -> (BlockHeight, Cache::InsertResult) { let prior_cached_block = self .latest_cached_block() @@ -875,7 +870,7 @@ where &mut self, from_account: &TestAccount, to: ZcashAddress, - value: NonNegativeAmount, + value: Zatoshis, ) -> Result< NonEmpty, super::wallet::TransferErrT< @@ -994,7 +989,7 @@ where fee_rule: StandardFeeRule, min_confirmations: NonZeroU32, to: &Address, - amount: NonNegativeAmount, + amount: Zatoshis, memo: Option, change_memo: Option, fallback_change_pool: ShieldedProtocol, @@ -1038,7 +1033,7 @@ where &mut self, input_selector: &InputsT, change_strategy: &ChangeT, - shielding_threshold: NonNegativeAmount, + shielding_threshold: Zatoshis, from_addrs: &[TransparentAddress], to_account: ::AccountId, min_confirmations: u32, @@ -1160,7 +1155,7 @@ where &mut self, input_selector: &InputsT, change_strategy: &ChangeT, - shielding_threshold: NonNegativeAmount, + shielding_threshold: Zatoshis, usk: &UnifiedSpendingKey, from_addrs: &[TransparentAddress], to_account: ::AccountId, @@ -1204,17 +1199,13 @@ where } /// Returns the total balance in the given account at this point in the test. - pub fn get_total_balance(&self, account: AccountIdT) -> NonNegativeAmount { + pub fn get_total_balance(&self, account: AccountIdT) -> Zatoshis { self.with_account_balance(account, 0, |balance| balance.total()) } /// Returns the balance in the given account that is spendable with the given number /// of confirmations at this point in the test. - pub fn get_spendable_balance( - &self, - account: AccountIdT, - min_confirmations: u32, - ) -> NonNegativeAmount { + pub fn get_spendable_balance(&self, account: AccountIdT, min_confirmations: u32) -> Zatoshis { self.with_account_balance(account, min_confirmations, |balance| { balance.spendable_value() }) @@ -1226,7 +1217,7 @@ where &self, account: AccountIdT, min_confirmations: u32, - ) -> NonNegativeAmount { + ) -> Zatoshis { self.with_account_balance(account, min_confirmations, |balance| { balance.value_pending_spendability() + balance.change_pending_confirmation() }) @@ -1236,11 +1227,7 @@ where /// Returns the amount of change in the given account that is not yet spendable with /// the given number of confirmations at this point in the test. #[allow(dead_code)] - pub fn get_pending_change( - &self, - account: AccountIdT, - min_confirmations: u32, - ) -> NonNegativeAmount { + pub fn get_pending_change(&self, account: AccountIdT, min_confirmations: u32) -> Zatoshis { self.with_account_balance(account, min_confirmations, |balance| { balance.change_pending_confirmation() }) @@ -1727,7 +1714,7 @@ pub trait TestFvk: Clone { params: &P, height: BlockHeight, req: AddressType, - value: NonNegativeAmount, + value: Zatoshis, initial_sapling_tree_size: u32, // we don't require an initial Orchard tree size because we don't need it to compute // the nullifier. @@ -1749,7 +1736,7 @@ pub trait TestFvk: Clone { height: BlockHeight, nf: Self::Nullifier, req: AddressType, - value: NonNegativeAmount, + value: Zatoshis, initial_sapling_tree_size: u32, // we don't require an initial Orchard tree size because we don't need it to compute // the nullifier. @@ -1855,7 +1842,7 @@ impl TestFvk for DiversifiableFullViewingKey { params: &P, height: BlockHeight, req: AddressType, - value: NonNegativeAmount, + value: Zatoshis, initial_sapling_tree_size: u32, rng: &mut R, ) -> Self::Nullifier { @@ -1882,7 +1869,7 @@ impl TestFvk for DiversifiableFullViewingKey { height: BlockHeight, nf: Self::Nullifier, req: AddressType, - value: NonNegativeAmount, + value: Zatoshis, initial_sapling_tree_size: u32, rng: &mut R, ) -> Self::Nullifier { @@ -1931,7 +1918,7 @@ impl TestFvk for ::orchard::keys::FullViewingKey { let (cact, _) = compact_orchard_action( revealed_spent_note_nullifier, recipient, - NonNegativeAmount::ZERO, + Zatoshis::ZERO, self.orchard_ovk(zip32::Scope::Internal), rng, ); @@ -1944,7 +1931,7 @@ impl TestFvk for ::orchard::keys::FullViewingKey { _: &P, _: BlockHeight, req: AddressType, - value: NonNegativeAmount, + value: Zatoshis, _: u32, // the position is not required for computing the Orchard nullifier mut rng: &mut R, ) -> Self::Nullifier { @@ -1979,7 +1966,7 @@ impl TestFvk for ::orchard::keys::FullViewingKey { _: BlockHeight, revealed_spent_note_nullifier: Self::Nullifier, address_type: AddressType, - value: NonNegativeAmount, + value: Zatoshis, _: u32, // the position is not required for computing the Orchard nullifier rng: &mut R, ) -> Self::Nullifier { @@ -2028,7 +2015,7 @@ fn compact_sapling_output( params: &P, height: BlockHeight, recipient: ::sapling::PaymentAddress, - value: NonNegativeAmount, + value: Zatoshis, ovk: Option<::sapling::keys::OutgoingViewingKey>, rng: &mut R, ) -> (CompactSaplingOutput, ::sapling::Note) { @@ -2060,7 +2047,7 @@ fn compact_sapling_output( fn compact_orchard_action( nf_old: ::orchard::note::Nullifier, recipient: ::orchard::Address, - value: NonNegativeAmount, + value: Zatoshis, ovk: Option<::orchard::keys::OutgoingViewingKey>, rng: &mut R, ) -> (CompactOrchardAction, ::orchard::Note) { @@ -2104,12 +2091,12 @@ fn fake_compact_tx(rng: &mut R) -> CompactTx { pub struct FakeCompactOutput { fvk: Fvk, address_type: AddressType, - value: NonNegativeAmount, + value: Zatoshis, } impl FakeCompactOutput { /// Constructs a new fake output with the given properties. - pub fn new(fvk: Fvk, address_type: AddressType, value: NonNegativeAmount) -> Self { + pub fn new(fvk: Fvk, address_type: AddressType, value: Zatoshis) -> Self { Self { fvk, address_type, @@ -2219,10 +2206,10 @@ fn fake_compact_block_spending( params: &P, height: BlockHeight, prev_hash: BlockHash, - (nf, in_value): (Fvk::Nullifier, NonNegativeAmount), + (nf, in_value): (Fvk::Nullifier, Zatoshis), fvk: &Fvk, to: Address, - value: NonNegativeAmount, + value: Zatoshis, initial_sapling_tree_size: u32, initial_orchard_tree_size: u32, mut rng: impl RngCore + CryptoRng, @@ -2453,7 +2440,7 @@ impl InputSource for MockWalletDb { fn select_spendable_notes( &self, _account: Self::AccountId, - _target_value: NonNegativeAmount, + _target_value: Zatoshis, _sources: &[ShieldedProtocol], _anchor_height: BlockHeight, _exclude: &[Self::NoteRef], @@ -2620,7 +2607,7 @@ impl WalletRead for MockWalletDb { &self, _account: Self::AccountId, _max_height: BlockHeight, - ) -> Result, Self::Error> { + ) -> Result, Self::Error> { Ok(HashMap::new()) } diff --git a/zcash_client_backend/src/data_api/testing/pool.rs b/zcash_client_backend/src/data_api/testing/pool.rs index 0cacac946b..e74ce69a7c 100644 --- a/zcash_client_backend/src/data_api/testing/pool.rs +++ b/zcash_client_backend/src/data_api/testing/pool.rs @@ -11,12 +11,11 @@ use rand::{Rng, RngCore}; use secrecy::Secret; use shardtree::error::ShardTreeError; +use ::transparent::address::TransparentAddress; use zcash_keys::{address::Address, keys::UnifiedSpendingKey}; use zcash_primitives::{ block::BlockHash, - legacy::TransparentAddress, transaction::{ - components::amount::NonNegativeAmount, fees::zip317::{FeeRule as Zip317FeeRule, MARGINAL_FEE, MINIMUM_FEE}, Transaction, }, @@ -66,23 +65,23 @@ use { proposal::{Proposal, ProposalError, StepOutput, StepOutputIndex}, wallet::{TransparentAddressMetadata, WalletTransparentOutput}, }, + ::transparent::{ + bundle::{OutPoint, TxOut}, + keys::{NonHardenedChildIndex, TransparentKeyScope}, + }, nonempty::NonEmpty, rand_core::OsRng, std::{collections::HashSet, str::FromStr}, - zcash_primitives::{ - legacy::keys::{NonHardenedChildIndex, TransparentKeyScope}, - transaction::{ - builder::{BuildConfig, Builder}, - components::{OutPoint, TxOut}, - fees::zip317, - }, + zcash_primitives::transaction::{ + builder::{BuildConfig, Builder}, + fees::zip317, }, zcash_proofs::prover::LocalTxProver, zcash_protocol::value::ZatBalance, }; #[cfg(feature = "orchard")] -use crate::PoolType; +use zcash_protocol::PoolType; #[cfg(feature = "pczt")] use pczt::roles::{prover::Prover, signer::Signer}; @@ -379,7 +378,7 @@ pub fn send_with_multiple_change_outputs( DustOutputPolicy::default(), SplitPolicy::with_min_output_value( NonZeroUsize::new(2).unwrap(), - NonNegativeAmount::const_from_u64(100_0000), + Zatoshis::const_from_u64(100_0000), ), ); @@ -482,7 +481,7 @@ pub fn send_with_multiple_change_outputs( DustOutputPolicy::default(), SplitPolicy::with_min_output_value( NonZeroUsize::new(8).unwrap(), - NonNegativeAmount::const_from_u64(10_0000), + Zatoshis::const_from_u64(10_0000), ), ); @@ -509,7 +508,7 @@ pub fn send_multi_step_proposed_transfer( DSF: DataStoreFactory, ::AccountId: std::fmt::Debug, { - use zcash_primitives::transaction::components::transparent::builder::TransparentSigningSet; + use ::transparent::builder::TransparentSigningSet; use crate::data_api::{OutputOfSentTx, GAP_LIMIT}; @@ -540,8 +539,8 @@ pub fn send_multi_step_proposed_transfer( h }; - let value = NonNegativeAmount::const_from_u64(100000); - let transfer_amount = NonNegativeAmount::const_from_u64(50000); + let value = Zatoshis::const_from_u64(100000); + let transfer_amount = Zatoshis::const_from_u64(50000); let run_test = |st: &mut TestState<_, DSF::DataStore, _>, expected_index| { // Add funds to the wallet. @@ -929,8 +928,8 @@ pub fn proposal_fails_if_not_all_ephemeral_outputs_consumed( let dfvk = T::test_account_fvk(&st); // Add funds to the wallet in a single note - let value = NonNegativeAmount::const_from_u64(50000); + let value = Zatoshis::const_from_u64(50000); let (h1, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value); st.scan_cached_blocks(h1, 1); @@ -1082,10 +1081,7 @@ pub fn spend_fails_on_unverified_notes( // Value is considered pending at 10 confirmations. assert_eq!(st.get_pending_shielded_balance(account_id, 10), value); - assert_eq!( - st.get_spendable_balance(account_id, 10), - NonNegativeAmount::ZERO - ); + assert_eq!(st.get_spendable_balance(account_id, 10), Zatoshis::ZERO); // If none of the wallet's accounts have a recover-until height, then there // is no recovery phase for the wallet, and therefore the denominator in the @@ -1127,7 +1123,7 @@ pub fn spend_fails_on_unverified_notes( StandardFeeRule::Zip317, NonZeroU32::new(2).unwrap(), &to, - NonNegativeAmount::const_from_u64(70000), + Zatoshis::const_from_u64(70000), None, None, T::SHIELDED_PROTOCOL, @@ -1136,8 +1132,8 @@ pub fn spend_fails_on_unverified_notes( available, required }) - if available == NonNegativeAmount::const_from_u64(50000) - && required == NonNegativeAmount::const_from_u64(80000) + if available == Zatoshis::const_from_u64(50000) + && required == Zatoshis::const_from_u64(80000) ); // Mine blocks SAPLING_ACTIVATION_HEIGHT + 2 to 9 until just before the second @@ -1157,7 +1153,7 @@ pub fn spend_fails_on_unverified_notes( StandardFeeRule::Zip317, NonZeroU32::new(10).unwrap(), &to, - NonNegativeAmount::const_from_u64(70000), + Zatoshis::const_from_u64(70000), None, None, T::SHIELDED_PROTOCOL, @@ -1166,8 +1162,8 @@ pub fn spend_fails_on_unverified_notes( available, required }) - if available == NonNegativeAmount::const_from_u64(50000) - && required == NonNegativeAmount::const_from_u64(80000) + if available == Zatoshis::const_from_u64(50000) + && required == Zatoshis::const_from_u64(80000) ); // Mine block 11 so that the second note becomes verified @@ -1187,7 +1183,7 @@ pub fn spend_fails_on_unverified_notes( ); // Should now be able to generate a proposal - let amount_sent = NonNegativeAmount::from_u64(70000).unwrap(); + let amount_sent = Zatoshis::from_u64(70000).unwrap(); let min_confirmations = NonZeroU32::new(10).unwrap(); let proposal = st .propose_standard_transfer::( @@ -1217,9 +1213,8 @@ pub fn spend_fails_on_unverified_notes( // TODO: send to an account so that we can check its balance. assert_eq!( st.get_total_balance(account_id), - ((value * 11u64).unwrap() - - (amount_sent + NonNegativeAmount::from_u64(10000).unwrap()).unwrap()) - .unwrap() + ((value * 11u64).unwrap() - (amount_sent + Zatoshis::from_u64(10000).unwrap()).unwrap()) + .unwrap() ); } @@ -1240,7 +1235,7 @@ pub fn spend_fails_on_locked_notes( let fee_rule = StandardFeeRule::Zip317; // Add funds to the wallet in a single note - let value = NonNegativeAmount::const_from_u64(50000); + let value = Zatoshis::const_from_u64(50000); let (h1, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value); st.scan_cached_blocks(h1, 1); @@ -1258,7 +1253,7 @@ pub fn spend_fails_on_locked_notes( fee_rule, min_confirmations, &to, - NonNegativeAmount::const_from_u64(15000), + Zatoshis::const_from_u64(15000), None, None, T::SHIELDED_PROTOCOL, @@ -1278,7 +1273,7 @@ pub fn spend_fails_on_locked_notes( fee_rule, NonZeroU32::new(1).unwrap(), &to, - NonNegativeAmount::const_from_u64(2000), + Zatoshis::const_from_u64(2000), None, None, T::SHIELDED_PROTOCOL, @@ -1287,7 +1282,7 @@ pub fn spend_fails_on_locked_notes( available, required }) - if available == NonNegativeAmount::ZERO && required == NonNegativeAmount::const_from_u64(12000) + if available == Zatoshis::ZERO && required == Zatoshis::const_from_u64(12000) ); // Mine blocks SAPLING_ACTIVATION_HEIGHT + 1 to 41 (that don't send us funds) @@ -1308,7 +1303,7 @@ pub fn spend_fails_on_locked_notes( fee_rule, NonZeroU32::new(1).unwrap(), &to, - NonNegativeAmount::const_from_u64(2000), + Zatoshis::const_from_u64(2000), None, None, T::SHIELDED_PROTOCOL, @@ -1317,7 +1312,7 @@ pub fn spend_fails_on_locked_notes( available, required }) - if available == NonNegativeAmount::ZERO && required == NonNegativeAmount::const_from_u64(12000) + if available == Zatoshis::ZERO && required == Zatoshis::const_from_u64(12000) ); // Mine block SAPLING_ACTIVATION_HEIGHT + 42 so that the first transaction expires @@ -1333,7 +1328,7 @@ pub fn spend_fails_on_locked_notes( assert_eq!(st.get_spendable_balance(account_id, 1), value); // Second spend should now succeed - let amount_sent2 = NonNegativeAmount::const_from_u64(2000); + let amount_sent2 = Zatoshis::const_from_u64(2000); let min_confirmations = NonZeroU32::new(1).unwrap(); let proposal = st .propose_standard_transfer::( @@ -1362,7 +1357,7 @@ pub fn spend_fails_on_locked_notes( // TODO: send to an account so that we can check its balance. assert_eq!( st.get_total_balance(account_id), - (value - (amount_sent2 + NonNegativeAmount::from_u64(10000).unwrap()).unwrap()).unwrap() + (value - (amount_sent2 + Zatoshis::from_u64(10000).unwrap()).unwrap()).unwrap() ); } @@ -1383,7 +1378,7 @@ pub fn ovk_policy_prevents_recovery_from_chain( let dfvk = T::test_account_fvk(&st); // Add funds to the wallet in a single note - let value = NonNegativeAmount::const_from_u64(50000); + let value = Zatoshis::const_from_u64(50000); let (h1, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value); st.scan_cached_blocks(h1, 1); @@ -1413,7 +1408,7 @@ pub fn ovk_policy_prevents_recovery_from_chain( fee_rule, min_confirmations, &addr2, - NonNegativeAmount::const_from_u64(15000), + Zatoshis::const_from_u64(15000), None, None, T::SHIELDED_PROTOCOL, @@ -1473,7 +1468,7 @@ pub fn spend_succeeds_to_t_addr_zero_change( let dfvk = T::test_account_fvk(&st); // Add funds to the wallet in a single note - let value = NonNegativeAmount::const_from_u64(70000); + let value = Zatoshis::const_from_u64(70000); let (h, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value); st.scan_cached_blocks(h, 1); @@ -1492,7 +1487,7 @@ pub fn spend_succeeds_to_t_addr_zero_change( fee_rule, min_confirmations, &to, - NonNegativeAmount::const_from_u64(50000), + Zatoshis::const_from_u64(50000), None, None, T::SHIELDED_PROTOCOL, @@ -1521,7 +1516,7 @@ pub fn change_note_spends_succeed( let dfvk = T::test_account_fvk(&st); // Add funds to the wallet in a single note owned by the internal spending key - let value = NonNegativeAmount::const_from_u64(70000); + let value = Zatoshis::const_from_u64(70000); let (h, _, _) = st.generate_next_block(&dfvk, AddressType::Internal, value); st.scan_cached_blocks(h, 1); @@ -1531,10 +1526,7 @@ pub fn change_note_spends_succeed( // Value is considered pending at 10 confirmations. assert_eq!(st.get_pending_shielded_balance(account_id, 10), value); - assert_eq!( - st.get_spendable_balance(account_id, 10), - NonNegativeAmount::ZERO - ); + assert_eq!(st.get_spendable_balance(account_id, 10), Zatoshis::ZERO); let change_note_scope = st .wallet() @@ -1555,7 +1547,7 @@ pub fn change_note_spends_succeed( fee_rule, min_confirmations, &to, - NonNegativeAmount::const_from_u64(50000), + Zatoshis::const_from_u64(50000), None, None, T::SHIELDED_PROTOCOL, @@ -1597,17 +1589,17 @@ pub fn external_address_change_spends_detected_in_restore_from_seed( let (h1, _, _) = st.generate_next_block( &dfvk, AddressType::Internal, - NonNegativeAmount::const_from_u64(50000), + Zatoshis::const_from_u64(50000), ); // Add 10 dust notes to the wallet @@ -1705,14 +1697,14 @@ pub fn zip317_spend( st.generate_next_block( &dfvk, AddressType::DefaultExternal, - NonNegativeAmount::const_from_u64(1000), + Zatoshis::const_from_u64(1000), ); } st.scan_cached_blocks(h1, 11); // Spendable balance matches total balance - let total = NonNegativeAmount::const_from_u64(60000); + let total = Zatoshis::const_from_u64(60000); assert_eq!(st.get_total_balance(account_id), total); assert_eq!(st.get_spendable_balance(account_id, 1), total); @@ -1723,7 +1715,7 @@ pub fn zip317_spend( // This first request will fail due to insufficient non-dust funds let req = TransactionRequest::new(vec![Payment::without_memo( T::fvk_default_address(&dfvk).to_zcash_address(st.network()), - NonNegativeAmount::const_from_u64(50000), + Zatoshis::const_from_u64(50000), )]) .unwrap(); @@ -1737,15 +1729,15 @@ pub fn zip317_spend( NonZeroU32::new(1).unwrap(), ), Err(Error::InsufficientFunds { available, required }) - if available == NonNegativeAmount::const_from_u64(51000) - && required == NonNegativeAmount::const_from_u64(60000) + if available == Zatoshis::const_from_u64(51000) + && required == Zatoshis::const_from_u64(60000) ); // This request will succeed, spending a single dust input to pay the 10000 // ZAT fee in addition to the 41000 ZAT output to the recipient let req = TransactionRequest::new(vec![Payment::without_memo( T::fvk_default_address(&dfvk).to_zcash_address(st.network()), - NonNegativeAmount::const_from_u64(41000), + Zatoshis::const_from_u64(41000), )]) .unwrap(); @@ -1768,7 +1760,7 @@ pub fn zip317_spend( // in the total balance. assert_eq!( st.get_total_balance(account_id), - (total - NonNegativeAmount::const_from_u64(10000)).unwrap() + (total - Zatoshis::const_from_u64(10000)).unwrap() ); } @@ -1798,14 +1790,14 @@ where let (h, _, _) = st.generate_next_block( &dfvk, AddressType::Internal, - NonNegativeAmount::const_from_u64(50000), + Zatoshis::const_from_u64(50000), ); st.scan_cached_blocks(h, 1); let utxo = WalletTransparentOutput::from_parts( OutPoint::fake(), TxOut { - value: NonNegativeAmount::const_from_u64(100000), + value: Zatoshis::const_from_u64(100000), script_pubkey: taddr.script(), }, Some(h), @@ -1823,7 +1815,7 @@ where .shield_transparent_funds( &input_selector, &change_strategy, - NonNegativeAmount::from_u64(10000).unwrap(), + Zatoshis::from_u64(10000).unwrap(), account.usk(), &[*taddr], account.id(), @@ -1917,7 +1909,7 @@ pub fn birthday_in_anchor_shard( .build(); // Generate 9 blocks that have no value for us, starting at the birthday height. - let not_our_value = NonNegativeAmount::const_from_u64(10000); + let not_our_value = Zatoshis::const_from_u64(10000); let not_our_key = T::random_fvk(st.rng_mut()); let (initial_height, _, _) = st.generate_next_block(¬_our_key, AddressType::DefaultExternal, not_our_value); @@ -1929,7 +1921,7 @@ pub fn birthday_in_anchor_shard( let (received_tx_height, _, _) = st.generate_next_block( &T::test_account_fvk(&st), AddressType::DefaultExternal, - NonNegativeAmount::const_from_u64(500000), + Zatoshis::const_from_u64(500000), ); // Generate some more blocks to get above our anchor height @@ -1947,7 +1939,7 @@ pub fn birthday_in_anchor_shard( let spendable = T::select_spendable_notes( &st, account_id, - NonNegativeAmount::const_from_u64(300000), + Zatoshis::const_from_u64(300000), received_tx_height + 10, &[], ) @@ -1962,7 +1954,7 @@ pub fn birthday_in_anchor_shard( let spendable = T::select_spendable_notes( &st, account_id, - NonNegativeAmount::const_from_u64(300000), + Zatoshis::const_from_u64(300000), received_tx_height + 10, &[], ) @@ -1988,14 +1980,14 @@ pub fn checkpoint_gaps( st.generate_next_block( &dfvk, AddressType::DefaultExternal, - NonNegativeAmount::const_from_u64(500000), + Zatoshis::const_from_u64(500000), ); st.scan_cached_blocks(account.birthday().height(), 1); // Create a gap of 10 blocks having no shielded outputs, then add a block that doesn't // belong to us so that we can get a checkpoint in the tree. let not_our_key = T::sk_to_fvk(&T::sk(&[0xf5; 32])); - let not_our_value = NonNegativeAmount::const_from_u64(10000); + let not_our_value = Zatoshis::const_from_u64(10000); st.generate_block_at( account.birthday().height() + 10, BlockHash([0; 32]), @@ -2016,7 +2008,7 @@ pub fn checkpoint_gaps( let spendable = T::select_spendable_notes( &st, account.id(), - NonNegativeAmount::const_from_u64(300000), + Zatoshis::const_from_u64(300000), account.birthday().height() + 5, &[], ) @@ -2030,7 +2022,7 @@ pub fn checkpoint_gaps( let to = T::fvk_default_address(¬_our_key); let req = TransactionRequest::new(vec![Payment::without_memo( to.to_zcash_address(st.network()), - NonNegativeAmount::const_from_u64(10000), + Zatoshis::const_from_u64(10000), )]) .unwrap(); @@ -2067,7 +2059,7 @@ pub fn pool_crossing_required( let p1_fvk = P1::test_account_fvk(&st); let p1_to = P1::fvk_default_address(&p1_fvk); - let note_value = NonNegativeAmount::const_from_u64(350000); + let note_value = Zatoshis::const_from_u64(350000); st.generate_next_block(&p0_fvk, AddressType::DefaultExternal, note_value); st.scan_cached_blocks(account.birthday().height(), 2); @@ -2075,7 +2067,7 @@ pub fn pool_crossing_required( assert_eq!(st.get_total_balance(account.id()), initial_balance); assert_eq!(st.get_spendable_balance(account.id(), 1), initial_balance); - let transfer_amount = NonNegativeAmount::const_from_u64(200000); + let transfer_amount = Zatoshis::const_from_u64(200000); let p0_to_p1 = TransactionRequest::new(vec![Payment::without_memo( p1_to.to_zcash_address(st.network()), transfer_amount, @@ -2100,7 +2092,7 @@ pub fn pool_crossing_required( let step0 = &proposal0.steps().head; // We expect 4 logical actions, two per pool (due to padding). - let expected_fee = NonNegativeAmount::const_from_u64(20000); + let expected_fee = Zatoshis::const_from_u64(20000); assert_eq!(step0.balance().fee_required(), expected_fee); let expected_change = (note_value - transfer_amount - expected_fee).unwrap(); @@ -2156,7 +2148,7 @@ pub fn fully_funded_fully_private( let p1_fvk = P1::test_account_fvk(&st); let (p1_to, _) = account.usk().default_transparent_address(); - let note_value = NonNegativeAmount::const_from_u64(350000); + let note_value = Zatoshis::const_from_u64(350000); st.generate_next_block(&p0_fvk, AddressType::DefaultExternal, note_value); st.generate_next_block(&p1_fvk, AddressType::DefaultExternal, note_value); st.scan_cached_blocks(account.birthday().height(), 2); @@ -2255,7 +2247,7 @@ pub fn fully_funded_send_to_t( assert_eq!(st.get_total_balance(account.id()), initial_balance); assert_eq!(st.get_spendable_balance(account.id(), 1), initial_balance); - let transfer_amount = NonNegativeAmount::const_from_u64(200000); + let transfer_amount = Zatoshis::const_from_u64(200000); let p0_to_p1 = TransactionRequest::new(vec![Payment::without_memo( Address::Transparent(p1_to).to_zcash_address(st.network()), transfer_amount, @@ -2282,7 +2274,7 @@ pub fn fully_funded_send_to_t( let step0 = &proposal0.steps().head; // We expect 3 logical actions, one for the transparent output and two for the source pool. - let expected_fee = NonNegativeAmount::const_from_u64(15000); + let expected_fee = Zatoshis::const_from_u64(15000); assert_eq!(step0.balance().fee_required(), expected_fee); let expected_change = (note_value - transfer_amount - expected_fee).unwrap(); @@ -2335,7 +2327,7 @@ pub fn multi_pool_checkpoint( // Add some funds to the wallet; we add two notes to allow successive spends. Also, // we will generate a note in the P1 pool to ensure that we have some tree state. - let note_value = NonNegativeAmount::const_from_u64(500000); + let note_value = Zatoshis::const_from_u64(500000); let (start_height, _, _) = st.generate_next_block(&p0_fvk, AddressType::DefaultExternal, note_value); st.generate_next_block(&p0_fvk, AddressType::DefaultExternal, note_value); @@ -2367,7 +2359,7 @@ pub fn multi_pool_checkpoint( single_output_change_strategy(StandardFeeRule::Zip317, None, P1::SHIELDED_PROTOCOL); // First, send funds just to P0 - let transfer_amount = NonNegativeAmount::const_from_u64(200000); + let transfer_amount = Zatoshis::const_from_u64(200000); let p0_transfer = TransactionRequest::new(vec![Payment::without_memo( P0::random_address(st.rng_mut()).to_zcash_address(st.network()), transfer_amount, @@ -2385,7 +2377,7 @@ pub fn multi_pool_checkpoint( .unwrap(); st.generate_next_block_including(*res.first()); - let expected_fee = NonNegativeAmount::const_from_u64(10000); + let expected_fee = Zatoshis::const_from_u64(10000); let expected_change = (note_value - transfer_amount - expected_fee).unwrap(); assert_eq!( st.get_total_balance(acct_id), @@ -2496,7 +2488,7 @@ pub fn multi_pool_checkpoints_with_pruning( let (h1, _, _) = st.generate_next_block( &dfvk, AddressType::DefaultExternal, - NonNegativeAmount::const_from_u64(5), + Zatoshis::const_from_u64(5), ); // Scan the cache @@ -2543,7 +2535,7 @@ pub fn valid_chain_states( let (h2, _, _) = st.generate_next_block( &dfvk, AddressType::DefaultExternal, - NonNegativeAmount::const_from_u64(7), + Zatoshis::const_from_u64(7), ); // Scanning should detect no inconsistencies @@ -2568,12 +2560,12 @@ pub fn invalid_chain_cache_disconnected( let (h, _, _) = st.generate_next_block( &dfvk, AddressType::DefaultExternal, - NonNegativeAmount::const_from_u64(5), + Zatoshis::const_from_u64(5), ); let (last_contiguous_height, _, _) = st.generate_next_block( &dfvk, AddressType::DefaultExternal, - NonNegativeAmount::const_from_u64(7), + Zatoshis::const_from_u64(7), ); // Scanning the cache should find no inconsistencies @@ -2587,7 +2579,7 @@ pub fn invalid_chain_cache_disconnected( &[FakeCompactOutput::new( &dfvk, AddressType::DefaultExternal, - NonNegativeAmount::const_from_u64(8), + Zatoshis::const_from_u64(8), )], 2, 2, @@ -2596,7 +2588,7 @@ pub fn invalid_chain_cache_disconnected( st.generate_next_block( &dfvk, AddressType::DefaultExternal, - NonNegativeAmount::const_from_u64(3), + Zatoshis::const_from_u64(3), ); // Data+cache chain should be invalid at the data/cache boundary @@ -2628,8 +2620,8 @@ where assert_eq!(st.get_wallet_summary(0), None); // Create fake CompactBlocks sending value to the address - let value = NonNegativeAmount::const_from_u64(5); - let value2 = NonNegativeAmount::const_from_u64(7); + let value = Zatoshis::const_from_u64(5); + let value2 = Zatoshis::const_from_u64(7); let (h, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value); st.generate_next_block(&dfvk, AddressType::DefaultExternal, value2); @@ -2822,7 +2814,7 @@ pub fn scan_cached_blocks_allows_blocks_out_of_order( let account = st.test_account().cloned().unwrap(); let dfvk = T::test_account_fvk(&st); - let value = NonNegativeAmount::const_from_u64(50000); + let value = Zatoshis::const_from_u64(50000); let (h1, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value); st.scan_cached_blocks(h1, 1); assert_eq!(st.get_total_balance(account.id()), value); @@ -2838,13 +2830,13 @@ pub fn scan_cached_blocks_allows_blocks_out_of_order( st.scan_cached_blocks(h2, 1); assert_eq!( st.get_total_balance(account.id()), - NonNegativeAmount::const_from_u64(150_000) + Zatoshis::const_from_u64(150_000) ); // We can spend the received notes let req = TransactionRequest::new(vec![Payment::without_memo( T::fvk_default_address(&dfvk).to_zcash_address(st.network()), - NonNegativeAmount::const_from_u64(110_000), + Zatoshis::const_from_u64(110_000), )]) .unwrap(); @@ -2885,7 +2877,7 @@ pub fn scan_cached_blocks_finds_received_notes( assert_eq!(st.get_wallet_summary(0), None); // Create a fake CompactBlock sending value to the address - let value = NonNegativeAmount::const_from_u64(5); + let value = Zatoshis::const_from_u64(5); let (h1, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value); // Scan the cache @@ -2898,7 +2890,7 @@ pub fn scan_cached_blocks_finds_received_notes( assert_eq!(st.get_total_balance(account.id()), value); // Create a second fake CompactBlock sending more value to the address - let value2 = NonNegativeAmount::const_from_u64(7); + let value2 = Zatoshis::const_from_u64(7); let (h2, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value2); // Scan the cache again @@ -2935,7 +2927,7 @@ pub fn scan_cached_blocks_finds_change_notes( assert_eq!(st.get_wallet_summary(0), None); // Create a fake CompactBlock sending value to the address - let value = NonNegativeAmount::const_from_u64(5); + let value = Zatoshis::const_from_u64(5); let (received_height, _, nf) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value); @@ -2948,7 +2940,7 @@ pub fn scan_cached_blocks_finds_change_notes( // Create a second fake CompactBlock spending value from the address let not_our_key = T::sk_to_fvk(&T::sk(&[0xf5; 32])); let to2 = T::fvk_default_address(¬_our_key); - let value2 = NonNegativeAmount::const_from_u64(2); + let value2 = Zatoshis::const_from_u64(2); let (spent_height, _) = st.generate_next_block_spending(&dfvk, (nf, value), to2, value2); // Scan the cache again @@ -2981,14 +2973,14 @@ pub fn scan_cached_blocks_detects_spends_out_of_order( let dfvk = T::test_account_fvk(&st); // Create 10 blocks with successively increasing value - let value = NonNegativeAmount::const_from_u64(100_0000); + let value = Zatoshis::const_from_u64(100_0000); let (h0, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value); let mut note_values = vec![value]; for i in 2..=10 { - let value = NonNegativeAmount::const_from_u64(i * 100_0000); + let value = Zatoshis::const_from_u64(i * 100_0000); st.generate_next_block(&dfvk, AddressType::DefaultExternal, value); note_values.push(value); } @@ -3049,12 +3041,12 @@ pub fn metadata_queries_exclude_unwanted_notes( test_meta( &st, - NoteFilter::ExceedsMinValue(NonNegativeAmount::const_from_u64(1000_0000)), + NoteFilter::ExceedsMinValue(Zatoshis::const_from_u64(1000_0000)), Some(1), ); test_meta( &st, - NoteFilter::ExceedsMinValue(NonNegativeAmount::const_from_u64(500_0000)), + NoteFilter::ExceedsMinValue(Zatoshis::const_from_u64(500_0000)), Some(6), ); test_meta( @@ -3140,14 +3132,14 @@ pub fn pczt_single_step( let p1_to = P1::fvk_default_address(&p1_fvk); // Only mine a block in P0 to ensure the transactions source is there. - let note_value = NonNegativeAmount::const_from_u64(350000); + let note_value = Zatoshis::const_from_u64(350000); st.generate_next_block(&p0_fvk, AddressType::DefaultExternal, note_value); st.scan_cached_blocks(account.birthday().height(), 1); assert_eq!(st.get_total_balance(account.id()), note_value); assert_eq!(st.get_spendable_balance(account.id(), 1), note_value); - let transfer_amount = NonNegativeAmount::const_from_u64(200000); + let transfer_amount = Zatoshis::const_from_u64(200000); let p0_to_p1 = TransactionRequest::new(vec![Payment::without_memo( p1_to.to_zcash_address(st.network()), transfer_amount, diff --git a/zcash_client_backend/src/data_api/testing/transparent.rs b/zcash_client_backend/src/data_api/testing/transparent.rs index acba1c0997..5bacc88b04 100644 --- a/zcash_client_backend/src/data_api/testing/transparent.rs +++ b/zcash_client_backend/src/data_api/testing/transparent.rs @@ -10,13 +10,14 @@ use crate::{ wallet::WalletTransparentOutput, }; use assert_matches::assert_matches; -use sapling::zip32::ExtendedSpendingKey; -use zcash_primitives::{ - block::BlockHash, - legacy::TransparentAddress, - transaction::components::{amount::NonNegativeAmount, OutPoint, TxOut}, + +use ::transparent::{ + address::TransparentAddress, + bundle::{OutPoint, TxOut}, }; -use zcash_protocol::local_consensus::LocalNetwork; +use sapling::zip32::ExtendedSpendingKey; +use zcash_primitives::block::BlockHash; +use zcash_protocol::{local_consensus::LocalNetwork, value::Zatoshis}; use super::TestAccount; @@ -54,7 +55,7 @@ fn check_balance( .unwrap() .get(taddr) .cloned() - .unwrap_or(NonNegativeAmount::ZERO), + .unwrap_or(Zatoshis::ZERO), expected.total(), ); assert_eq!( @@ -63,7 +64,7 @@ fn check_balance( .unwrap() .into_iter() .map(|utxo| utxo.value()) - .sum::>(), + .sum::>(), Some(expected.spendable_value()), ); @@ -78,7 +79,7 @@ fn check_balance( .unwrap() .into_iter() .map(|utxo| utxo.value()) - .sum::>(), + .sum::>(), Some(expected.spendable_value()), ); } @@ -113,7 +114,7 @@ where assert!(bal_absent.is_empty()); // Create a fake transparent output. - let value = NonNegativeAmount::const_from_u64(100000); + let value = Zatoshis::const_from_u64(100000); let outpoint = OutPoint::fake(); let txout = TxOut { value, @@ -196,7 +197,7 @@ where // Initialize the wallet with chain data that has no shielded notes for us. let not_our_key = ExtendedSpendingKey::master(&[]).to_diversifiable_full_viewing_key(); - let not_our_value = NonNegativeAmount::const_from_u64(10000); + let not_our_value = Zatoshis::const_from_u64(10000); let (start_height, _, _) = st.generate_next_block(¬_our_key, AddressType::DefaultExternal, not_our_value); for _ in 1..10 { @@ -208,7 +209,7 @@ where check_balance::(&st, &account, taddr, 0, &Balance::ZERO); // Create a fake transparent output. - let value = NonNegativeAmount::from_u64(100000).unwrap(); + let value = Zatoshis::from_u64(100000).unwrap(); let txout = TxOut { value, script_pubkey: taddr.script(), @@ -304,7 +305,7 @@ where // Initialize the wallet with chain data that has no shielded notes for us. let not_our_key = ExtendedSpendingKey::master(&[]).to_diversifiable_full_viewing_key(); - let not_our_value = NonNegativeAmount::const_from_u64(10000); + let not_our_value = Zatoshis::const_from_u64(10000); let (start_height, _, _) = st.generate_next_block(¬_our_key, AddressType::DefaultExternal, not_our_value); for _ in 1..10 { @@ -322,7 +323,7 @@ where ); // Create a fake transparent output. - let value = NonNegativeAmount::from_u64(100000).unwrap(); + let value = Zatoshis::from_u64(100000).unwrap(); let txout = TxOut { value, script_pubkey: taddr.script(), diff --git a/zcash_client_backend/src/data_api/wallet.rs b/zcash_client_backend/src/data_api/wallet.rs index 669eac78a7..757b1ca35a 100644 --- a/zcash_client_backend/src/data_api/wallet.rs +++ b/zcash_client_backend/src/data_api/wallet.rs @@ -41,11 +41,15 @@ use sapling::{ }; use shardtree::error::{QueryError, ShardTreeError}; use std::num::NonZeroU32; -use zcash_keys::keys::UnifiedFullViewingKey; +use zcash_keys::{ + address::Address, + keys::{UnifiedFullViewingKey, UnifiedSpendingKey}, +}; +use zcash_protocol::{PoolType, ShieldedProtocol}; +use zip321::{self, Payment}; use super::InputSource; use crate::{ - address::Address, data_api::{ error::Error, Account, SentTransaction, SentTransactionOutput, WalletCommitmentTrees, WalletRead, WalletWrite, @@ -54,43 +58,40 @@ use crate::{ fees::{ standard::SingleOutputChangeStrategy, ChangeStrategy, DustOutputPolicy, StandardFeeRule, }, - keys::UnifiedSpendingKey, proposal::{Proposal, ProposalError, Step, StepOutputIndex}, wallet::{Note, OvkPolicy, Recipient}, - zip321::{self, Payment}, - PoolType, ShieldedProtocol, }; -use zcash_primitives::{ - legacy::TransparentAddress, - transaction::{ - builder::{BuildConfig, BuildResult, Builder}, - components::{ - amount::NonNegativeAmount, sapling::zip212_enforcement, - transparent::builder::TransparentSigningSet, OutPoint, - }, - fees::FeeRule, - Transaction, TxId, - }, + +use ::transparent::{ + address::TransparentAddress, builder::TransparentSigningSet, bundle::OutPoint, +}; +use zcash_primitives::transaction::{ + builder::{BuildConfig, BuildResult, Builder}, + components::sapling::zip212_enforcement, + fees::FeeRule, + Transaction, TxId, }; use zcash_protocol::{ consensus::{self, BlockHeight, NetworkUpgrade}, memo::MemoBytes, + value::Zatoshis, }; use zip32::Scope; #[cfg(feature = "transparent-inputs")] use { crate::{fees::ChangeValue, proposal::StepOutput, wallet::TransparentAddressMetadata}, + ::transparent::bundle::TxOut, core::convert::Infallible, input_selection::ShieldingSelector, std::collections::HashMap, zcash_keys::encoding::AddressCodec, - zcash_primitives::transaction::components::TxOut, }; #[cfg(feature = "pczt")] use { crate::data_api::error::PcztError, + ::transparent::pczt::Bip32Derivation, bip32::ChildNumber, orchard::note_encryption::OrchardDomain, pczt::roles::{ @@ -101,7 +102,6 @@ use { serde::{Deserialize, Serialize}, zcash_address::ZcashAddress, zcash_note_encryption::try_output_recovery_with_pkd_esk, - zcash_primitives::transaction::components::transparent::pczt::Bip32Derivation, zcash_protocol::{ consensus::NetworkConstants, value::{BalanceError, ZatBalance}, @@ -331,7 +331,7 @@ pub fn propose_standard_transfer_to_address( spend_from_account: ::AccountId, min_confirmations: NonZeroU32, to: &Address, - amount: NonNegativeAmount, + amount: Zatoshis, memo: Option, change_memo: Option, fallback_change_pool: ShieldedProtocol, @@ -395,7 +395,7 @@ pub fn propose_shielding( params: &ParamsT, input_selector: &InputsT, change_strategy: &ChangeT, - shielding_threshold: NonNegativeAmount, + shielding_threshold: Zatoshis, from_addrs: &[TransparentAddress], to_account: ::AccountId, min_confirmations: u32, @@ -431,7 +431,7 @@ where struct StepResult { build_result: BuildResult, outputs: Vec>, - fee_amount: NonNegativeAmount, + fee_amount: Zatoshis, #[cfg(feature = "transparent-inputs")] utxos_spent: Vec, } @@ -546,18 +546,18 @@ struct BuildState<'a, P, AccountId> { #[cfg(feature = "orchard")] orchard_output_meta: Vec<( Recipient, - NonNegativeAmount, + Zatoshis, Option, )>, sapling_output_meta: Vec<( Recipient, - NonNegativeAmount, + Zatoshis, Option, )>, transparent_output_meta: Vec<( Recipient, TransparentAddress, - NonNegativeAmount, + Zatoshis, StepOutputIndex, )>, #[cfg(feature = "transparent-inputs")] @@ -884,20 +884,14 @@ where }; #[cfg(feature = "orchard")] - let mut orchard_output_meta: Vec<( - Recipient<_, PoolType, _>, - NonNegativeAmount, - Option, - )> = vec![]; - let mut sapling_output_meta: Vec<( - Recipient<_, PoolType, _>, - NonNegativeAmount, - Option, - )> = vec![]; + let mut orchard_output_meta: Vec<(Recipient<_, PoolType, _>, Zatoshis, Option)> = + vec![]; + let mut sapling_output_meta: Vec<(Recipient<_, PoolType, _>, Zatoshis, Option)> = + vec![]; let mut transparent_output_meta: Vec<( Recipient<_, _, ()>, TransparentAddress, - NonNegativeAmount, + Zatoshis, StepOutputIndex, )> = vec![]; @@ -1823,7 +1817,7 @@ where MemoBytes::from_bytes(memo_bytes(&m)).expect("Memo is the correct length.") }); - let note_value = NonNegativeAmount::try_from(note_value(¬e))?; + let note_value = Zatoshis::try_from(note_value(¬e))?; let recipient = match (pczt_recipient, external_address) { (PcztRecipient::External, Some(addr)) => { Ok(Recipient::External(addr, PoolType::Shielded(output_pool))) @@ -1977,7 +1971,7 @@ where outputs.extend(sapling_outputs.into_iter().flatten()); outputs.extend(transparent_outputs.into_iter().flatten()); - let fee_amount = NonNegativeAmount::try_from(transaction.fee_paid(|outpoint| { + let fee_amount = Zatoshis::try_from(transaction.fee_paid(|outpoint| { utxos_map .get(outpoint) .copied() @@ -2052,7 +2046,7 @@ pub fn shield_transparent_funds( output_prover: &impl OutputProver, input_selector: &InputsT, change_strategy: &ChangeT, - shielding_threshold: NonNegativeAmount, + shielding_threshold: Zatoshis, usk: &UnifiedSpendingKey, from_addrs: &[TransparentAddress], to_account: ::AccountId, diff --git a/zcash_client_backend/src/data_api/wallet/input_selection.rs b/zcash_client_backend/src/data_api/wallet/input_selection.rs index 09cbf7e99d..0e5debcde0 100644 --- a/zcash_client_backend/src/data_api/wallet/input_selection.rs +++ b/zcash_client_backend/src/data_api/wallet/input_selection.rs @@ -7,24 +7,22 @@ use std::{ fmt::{self, Debug, Display}, }; +use ::transparent::bundle::TxOut; use nonempty::NonEmpty; use zcash_address::ConversionError; -use zcash_primitives::{ +use zcash_keys::address::{Address, UnifiedAddress}; +use zcash_protocol::{ consensus::{self, BlockHeight}, - transaction::components::{ - amount::{BalanceError, NonNegativeAmount}, - TxOut, - }, + value::{BalanceError, Zatoshis}, + PoolType, ShieldedProtocol, }; +use zip321::TransactionRequest; use crate::{ - address::{Address, UnifiedAddress}, data_api::{InputSource, SimpleNoteRetention, SpendableNotes}, fees::{sapling, ChangeError, ChangeStrategy}, proposal::{Proposal, ProposalError, ShieldedInputs}, wallet::WalletTransparentOutput, - zip321::TransactionRequest, - PoolType, ShieldedProtocol, }; #[cfg(feature = "transparent-inputs")] @@ -32,11 +30,11 @@ use { crate::{ fees::EphemeralBalance, proposal::{Step, StepOutput, StepOutputIndex}, - zip321::Payment, }, + ::transparent::{address::TransparentAddress, bundle::OutPoint}, std::collections::BTreeSet, std::convert::Infallible, - zcash_primitives::{legacy::TransparentAddress, transaction::components::OutPoint}, + zip321::Payment, }; #[cfg(feature = "orchard")] @@ -58,8 +56,8 @@ pub enum InputSelectorError { /// Insufficient funds were available to satisfy the payment request that inputs were being /// selected to attempt to satisfy. InsufficientFunds { - available: NonNegativeAmount, - required: NonNegativeAmount, + available: Zatoshis, + required: Zatoshis, }, /// The data source does not have enough information to choose an expiry height /// for the transaction. @@ -230,7 +228,7 @@ pub trait ShieldingSelector { params: &ParamsT, wallet_db: &Self::InputSource, change_strategy: &ChangeT, - shielding_threshold: NonNegativeAmount, + shielding_threshold: Zatoshis, source_addrs: &[TransparentAddress], to_account: ::AccountId, target_height: BlockHeight, @@ -296,35 +294,35 @@ impl From } } -pub(crate) struct SaplingPayment(NonNegativeAmount); +pub(crate) struct SaplingPayment(Zatoshis); #[cfg(test)] impl SaplingPayment { - pub(crate) fn new(amount: NonNegativeAmount) -> Self { + pub(crate) fn new(amount: Zatoshis) -> Self { SaplingPayment(amount) } } impl sapling::OutputView for SaplingPayment { - fn value(&self) -> NonNegativeAmount { + fn value(&self) -> Zatoshis { self.0 } } #[cfg(feature = "orchard")] -pub(crate) struct OrchardPayment(NonNegativeAmount); +pub(crate) struct OrchardPayment(Zatoshis); #[cfg(test)] #[cfg(feature = "orchard")] impl OrchardPayment { - pub(crate) fn new(amount: NonNegativeAmount) -> Self { + pub(crate) fn new(amount: Zatoshis) -> Self { OrchardPayment(amount) } } #[cfg(feature = "orchard")] impl orchard_fees::OutputView for OrchardPayment { - fn value(&self) -> NonNegativeAmount { + fn value(&self) -> Zatoshis { self.0 } } @@ -403,7 +401,7 @@ impl InputSelector for GreedyInputSelector { // outputs will be computed from the constructed `tr1_transparent_outputs` value // constructed below. #[cfg(feature = "transparent-inputs")] - let mut total_ephemeral = NonNegativeAmount::ZERO; + let mut total_ephemeral = Zatoshis::ZERO; for (idx, payment) in transaction_request.payments() { let recipient_address: Address = payment @@ -483,8 +481,8 @@ impl InputSelector for GreedyInputSelector { } let mut shielded_inputs = SpendableNotes::empty(); - let mut prior_available = NonNegativeAmount::ZERO; - let mut amount_required = NonNegativeAmount::ZERO; + let mut prior_available = Zatoshis::ZERO; + let mut amount_required = Zatoshis::ZERO; let mut exclude: Vec = vec![]; // This loop is guaranteed to terminate because on each iteration we check that the amount @@ -567,7 +565,7 @@ impl InputSelector for GreedyInputSelector { &sapling::EmptyBundleView, #[cfg(feature = "orchard")] &orchard_fees::EmptyBundleView, - Some(&EphemeralBalance::Input(NonNegativeAmount::ZERO)), + Some(&EphemeralBalance::Input(Zatoshis::ZERO)), &wallet_meta, ) { Err(ChangeError::InsufficientFunds { required, .. }) => required, @@ -575,7 +573,7 @@ impl InputSelector for GreedyInputSelector { unreachable!("no inputs were supplied") } Err(other) => return Err(InputSelectorError::Change(other)), - Ok(_) => NonNegativeAmount::ZERO, // shouldn't happen + Ok(_) => Zatoshis::ZERO, // shouldn't happen }; // Now recompute to obtain the `TransactionBalance` and verify that it @@ -784,7 +782,7 @@ impl ShieldingSelector for GreedyInputSelector { params: &ParamsT, wallet_db: &Self::InputSource, change_strategy: &ChangeT, - shielding_threshold: NonNegativeAmount, + shielding_threshold: Zatoshis, source_addrs: &[TransparentAddress], to_account: ::AccountId, target_height: BlockHeight, diff --git a/zcash_client_backend/src/decrypt.rs b/zcash_client_backend/src/decrypt.rs index da3749ea65..d2d4ef8781 100644 --- a/zcash_client_backend/src/decrypt.rs +++ b/zcash_client_backend/src/decrypt.rs @@ -1,16 +1,19 @@ use std::collections::HashMap; use sapling::note_encryption::{PreparedIncomingViewingKey, SaplingDomain}; +use zcash_keys::keys::UnifiedFullViewingKey; use zcash_note_encryption::{try_note_decryption, try_output_recovery_with_ovk}; use zcash_primitives::{ + transaction::components::sapling::zip212_enforcement, transaction::Transaction, +}; +use zcash_protocol::{ consensus::{self, BlockHeight}, memo::MemoBytes, - transaction::components::{amount::NonNegativeAmount, sapling::zip212_enforcement}, - transaction::Transaction, - zip32::Scope, + value::Zatoshis, }; +use zip32::Scope; -use crate::{data_api::DecryptedTransaction, keys::UnifiedFullViewingKey}; +use crate::data_api::DecryptedTransaction; #[cfg(feature = "orchard")] use orchard::note_encryption::OrchardDomain; @@ -84,16 +87,16 @@ impl DecryptedOutput { } impl DecryptedOutput { - pub fn note_value(&self) -> NonNegativeAmount { - NonNegativeAmount::from_u64(self.note.value().inner()) + pub fn note_value(&self) -> Zatoshis { + Zatoshis::from_u64(self.note.value().inner()) .expect("Sapling note value is expected to have been validated by consensus.") } } #[cfg(feature = "orchard")] impl DecryptedOutput { - pub fn note_value(&self) -> NonNegativeAmount { - NonNegativeAmount::from_u64(self.note.value().inner()) + pub fn note_value(&self) -> Zatoshis { + Zatoshis::from_u64(self.note.value().inner()) .expect("Orchard note value is expected to have been validated by consensus.") } } diff --git a/zcash_client_backend/src/fees.rs b/zcash_client_backend/src/fees.rs index 1950c05092..4591ef740e 100644 --- a/zcash_client_backend/src/fees.rs +++ b/zcash_client_backend/src/fees.rs @@ -3,19 +3,18 @@ use std::{ num::{NonZeroU64, NonZeroUsize}, }; -use zcash_primitives::{ +use ::transparent::bundle::OutPoint; +use zcash_primitives::transaction::fees::{ + transparent::{self, InputSize}, + zip317::{self as prim_zip317}, + FeeRule, +}; +use zcash_protocol::{ consensus::{self, BlockHeight}, memo::MemoBytes, - transaction::{ - components::{amount::NonNegativeAmount, OutPoint}, - fees::{ - transparent::{self, InputSize}, - zip317::{self as prim_zip317}, - FeeRule, - }, - }, + value::Zatoshis, + PoolType, ShieldedProtocol, }; -use zcash_protocol::{PoolType, ShieldedProtocol}; use crate::data_api::InputSource; @@ -46,7 +45,7 @@ impl FeeRule for StandardFeeRule { sapling_input_count: usize, sapling_output_count: usize, orchard_action_count: usize, - ) -> Result { + ) -> Result { #[allow(deprecated)] match self { Self::Zip317 => prim_zip317::FeeRule::standard().fee_required( @@ -72,26 +71,22 @@ pub struct ChangeValue(ChangeValueInner); enum ChangeValueInner { Shielded { protocol: ShieldedProtocol, - value: NonNegativeAmount, + value: Zatoshis, memo: Option, }, #[cfg(feature = "transparent-inputs")] - EphemeralTransparent { value: NonNegativeAmount }, + EphemeralTransparent { value: Zatoshis }, } impl ChangeValue { /// Constructs a new ephemeral transparent output value. #[cfg(feature = "transparent-inputs")] - pub fn ephemeral_transparent(value: NonNegativeAmount) -> Self { + pub fn ephemeral_transparent(value: Zatoshis) -> Self { Self(ChangeValueInner::EphemeralTransparent { value }) } /// Constructs a new change value that will be created as a shielded output. - pub fn shielded( - protocol: ShieldedProtocol, - value: NonNegativeAmount, - memo: Option, - ) -> Self { + pub fn shielded(protocol: ShieldedProtocol, value: Zatoshis, memo: Option) -> Self { Self(ChangeValueInner::Shielded { protocol, value, @@ -100,13 +95,13 @@ impl ChangeValue { } /// Constructs a new change value that will be created as a Sapling output. - pub fn sapling(value: NonNegativeAmount, memo: Option) -> Self { + pub fn sapling(value: Zatoshis, memo: Option) -> Self { Self::shielded(ShieldedProtocol::Sapling, value, memo) } /// Constructs a new change value that will be created as an Orchard output. #[cfg(feature = "orchard")] - pub fn orchard(value: NonNegativeAmount, memo: Option) -> Self { + pub fn orchard(value: Zatoshis, memo: Option) -> Self { Self::shielded(ShieldedProtocol::Orchard, value, memo) } @@ -120,7 +115,7 @@ impl ChangeValue { } /// Returns the value of the change or ephemeral output to be created, in zatoshis. - pub fn value(&self) -> NonNegativeAmount { + pub fn value(&self) -> Zatoshis { match &self.0 { ChangeValueInner::Shielded { value, .. } => *value, #[cfg(feature = "transparent-inputs")] @@ -158,24 +153,21 @@ impl ChangeValue { #[derive(Clone, Debug, PartialEq, Eq)] pub struct TransactionBalance { proposed_change: Vec, - fee_required: NonNegativeAmount, + fee_required: Zatoshis, // A cache for the sum of proposed change and fee; we compute it on construction anyway, so we // cache the resulting value. - total: NonNegativeAmount, + total: Zatoshis, } impl TransactionBalance { /// Constructs a new balance from its constituent parts. - pub fn new( - proposed_change: Vec, - fee_required: NonNegativeAmount, - ) -> Result { + pub fn new(proposed_change: Vec, fee_required: Zatoshis) -> Result { let total = proposed_change .iter() .map(|c| c.value()) .chain(Some(fee_required).into_iter()) - .sum::>() + .sum::>() .ok_or(())?; Ok(Self { @@ -192,12 +184,12 @@ impl TransactionBalance { /// Returns the fee computed for the transaction, assuming that the suggested /// change outputs are added to the transaction. - pub fn fee_required(&self) -> NonNegativeAmount { + pub fn fee_required(&self) -> Zatoshis { self.fee_required } /// Returns the sum of the proposed change outputs and the required fee. - pub fn total(&self) -> NonNegativeAmount { + pub fn total(&self) -> Zatoshis { self.total } } @@ -209,10 +201,10 @@ pub enum ChangeError { /// required outputs and fees. InsufficientFunds { /// The total of the inputs provided to change selection - available: NonNegativeAmount, + available: Zatoshis, /// The total amount of input value required to fund the requested outputs, /// including the required fees. - required: NonNegativeAmount, + required: Zatoshis, }, /// Some of the inputs provided to the transaction have value less than the /// marginal fee, and could not be determined to have any economic value in @@ -317,7 +309,7 @@ pub enum DustAction { #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct DustOutputPolicy { action: DustAction, - dust_threshold: Option, + dust_threshold: Option, } impl DustOutputPolicy { @@ -327,7 +319,7 @@ impl DustOutputPolicy { /// of the dust threshold to the change strategy that is evaluating the strategy; this /// is recommended, but an explicit value (including zero) may be provided to explicitly /// override the determination of the change strategy. - pub fn new(action: DustAction, dust_threshold: Option) -> Self { + pub fn new(action: DustAction, dust_threshold: Option) -> Self { Self { action, dust_threshold, @@ -340,7 +332,7 @@ impl DustOutputPolicy { } /// Returns a value that will be used to override the dust determination logic of the /// change policy, if any. - pub fn dust_threshold(&self) -> Option { + pub fn dust_threshold(&self) -> Option { self.dust_threshold } } @@ -361,7 +353,7 @@ impl Default for DustOutputPolicy { #[derive(Clone, Copy, Debug)] pub struct SplitPolicy { target_output_count: NonZeroUsize, - min_split_output_value: Option, + min_split_output_value: Option, } impl SplitPolicy { @@ -370,13 +362,13 @@ impl SplitPolicy { /// when retrieving wallet metadata. /// /// [`MARGINAL_FEE`]: zcash_primitives::transaction::fees::zip317::MARGINAL_FEE - pub(crate) const MIN_NOTE_VALUE: NonNegativeAmount = NonNegativeAmount::const_from_u64(500000); + pub(crate) const MIN_NOTE_VALUE: Zatoshis = Zatoshis::const_from_u64(500000); /// Constructs a new [`SplitPolicy`] that splits change to ensure the given number of spendable /// outputs exists within an account, each having at least the specified minimum note value. pub fn with_min_output_value( target_output_count: NonZeroUsize, - min_split_output_value: NonNegativeAmount, + min_split_output_value: Zatoshis, ) -> Self { Self { target_output_count, @@ -399,7 +391,7 @@ impl SplitPolicy { } /// Returns the minimum value for a note resulting from splitting of change. - pub fn min_split_output_value(&self) -> Option { + pub fn min_split_output_value(&self) -> Option { self.min_split_output_value } @@ -412,8 +404,8 @@ impl SplitPolicy { pub fn split_count( &self, existing_notes: Option, - existing_notes_total: Option, - total_change: NonNegativeAmount, + existing_notes_total: Option, + total_change: Zatoshis, ) -> NonZeroUsize { fn to_nonzero_u64(value: usize) -> NonZeroU64 { NonZeroU64::new(u64::try_from(value).expect("usize fits into u64")) @@ -464,8 +456,8 @@ impl SplitPolicy { /// [ZIP 320]: https://zips.z.cash/zip-0320 #[derive(Clone, Debug, PartialEq, Eq)] pub enum EphemeralBalance { - Input(NonNegativeAmount), - Output(NonNegativeAmount), + Input(Zatoshis), + Output(Zatoshis), } impl EphemeralBalance { @@ -477,14 +469,14 @@ impl EphemeralBalance { matches!(self, EphemeralBalance::Output(_)) } - pub fn ephemeral_input_amount(&self) -> Option { + pub fn ephemeral_input_amount(&self) -> Option { match self { EphemeralBalance::Input(v) => Some(*v), EphemeralBalance::Output(_) => None, } } - pub fn ephemeral_output_amount(&self) -> Option { + pub fn ephemeral_output_amount(&self) -> Option { match self { EphemeralBalance::Input(_) => None, EphemeralBalance::Output(v) => Some(*v), @@ -563,13 +555,9 @@ pub trait ChangeStrategy { #[cfg(test)] pub(crate) mod tests { - use zcash_primitives::transaction::{ - components::{ - amount::NonNegativeAmount, - transparent::{OutPoint, TxOut}, - }, - fees::transparent, - }; + use ::transparent::bundle::{OutPoint, TxOut}; + use zcash_primitives::transaction::fees::transparent; + use zcash_protocol::value::Zatoshis; use super::sapling; @@ -590,14 +578,14 @@ pub(crate) mod tests { pub(crate) struct TestSaplingInput { pub note_id: u32, - pub value: NonNegativeAmount, + pub value: Zatoshis, } impl sapling::InputView for TestSaplingInput { fn note_id(&self) -> &u32 { &self.note_id } - fn value(&self) -> NonNegativeAmount { + fn value(&self) -> Zatoshis { self.value } } diff --git a/zcash_client_backend/src/fees/common.rs b/zcash_client_backend/src/fees/common.rs index 8aa7f38f40..99a585e65a 100644 --- a/zcash_client_backend/src/fees/common.rs +++ b/zcash_client_backend/src/fees/common.rs @@ -1,15 +1,15 @@ use core::cmp::{max, min}; use std::num::{NonZeroU64, NonZeroUsize}; -use zcash_primitives::{ +use zcash_primitives::transaction::fees::{ + transparent, zip317::MINIMUM_FEE, zip317::P2PKH_STANDARD_OUTPUT_SIZE, FeeRule, +}; +use zcash_protocol::{ consensus::{self, BlockHeight}, memo::MemoBytes, - transaction::{ - components::amount::{BalanceError, NonNegativeAmount}, - fees::{transparent, zip317::MINIMUM_FEE, zip317::P2PKH_STANDARD_OUTPUT_SIZE, FeeRule}, - }, + value::{BalanceError, Zatoshis}, + ShieldedProtocol, }; -use zcash_protocol::ShieldedProtocol; use crate::data_api::AccountMeta; @@ -22,19 +22,19 @@ use super::{ use super::orchard as orchard_fees; pub(crate) struct NetFlows { - t_in: NonNegativeAmount, - t_out: NonNegativeAmount, - sapling_in: NonNegativeAmount, - sapling_out: NonNegativeAmount, - orchard_in: NonNegativeAmount, - orchard_out: NonNegativeAmount, + t_in: Zatoshis, + t_out: Zatoshis, + sapling_in: Zatoshis, + sapling_out: Zatoshis, + orchard_in: Zatoshis, + orchard_out: Zatoshis, } impl NetFlows { - fn total_in(&self) -> Result { + fn total_in(&self) -> Result { (self.t_in + self.sapling_in + self.orchard_in).ok_or(BalanceError::Overflow) } - fn total_out(&self) -> Result { + fn total_out(&self) -> Result { (self.t_out + self.sapling_out + self.orchard_out).ok_or(BalanceError::Overflow) } /// Returns true iff the flows excluding change are fully transparent. @@ -92,7 +92,7 @@ where .sum::>() .ok_or_else(overflow)?; #[cfg(not(feature = "orchard"))] - let orchard_in = NonNegativeAmount::ZERO; + let orchard_in = Zatoshis::ZERO; #[cfg(feature = "orchard")] let orchard_out = orchard @@ -102,7 +102,7 @@ where .sum::>() .ok_or_else(overflow)?; #[cfg(not(feature = "orchard"))] - let orchard_out = NonNegativeAmount::ZERO; + let orchard_out = Zatoshis::ZERO; Ok(NetFlows { t_in, @@ -168,10 +168,10 @@ pub(crate) struct SinglePoolBalanceConfig<'a, P, F> { params: &'a P, fee_rule: &'a F, dust_output_policy: &'a DustOutputPolicy, - default_dust_threshold: NonNegativeAmount, + default_dust_threshold: Zatoshis, split_policy: &'a SplitPolicy, fallback_change_pool: ShieldedProtocol, - marginal_fee: NonNegativeAmount, + marginal_fee: Zatoshis, grace_actions: usize, } @@ -181,10 +181,10 @@ impl<'a, P, F> SinglePoolBalanceConfig<'a, P, F> { params: &'a P, fee_rule: &'a F, dust_output_policy: &'a DustOutputPolicy, - default_dust_threshold: NonNegativeAmount, + default_dust_threshold: Zatoshis, split_policy: &'a SplitPolicy, fallback_change_pool: ShieldedProtocol, - marginal_fee: NonNegativeAmount, + marginal_fee: Zatoshis, grace_actions: usize, ) -> Self { Self { @@ -468,10 +468,10 @@ where .map_err(|fee_error| ChangeError::StrategyError(E::from(fee_error)))?; ( new_fee_with_change, - (fee_with_change - new_fee_with_change).unwrap_or(NonNegativeAmount::ZERO), + (fee_with_change - new_fee_with_change).unwrap_or(Zatoshis::ZERO), ) } else { - (fee_with_change, NonNegativeAmount::ZERO) + (fee_with_change, Zatoshis::ZERO) }; let simple_case = || { @@ -546,7 +546,7 @@ where ( vec![ChangeValue::shielded( change_pool, - NonNegativeAmount::ZERO, + Zatoshis::ZERO, change_memo.cloned(), )], fee_with_dust, @@ -590,7 +590,7 @@ pub(crate) fn check_for_uneconomic_inputs( transparent_outputs: &[impl transparent::OutputView], sapling: &impl sapling_fees::BundleView, #[cfg(feature = "orchard")] orchard: &impl orchard_fees::BundleView, - marginal_fee: NonNegativeAmount, + marginal_fee: Zatoshis, grace_actions: usize, possible_change: &[OutputManifest], ephemeral_balance: Option<&EphemeralBalance>, diff --git a/zcash_client_backend/src/fees/fixed.rs b/zcash_client_backend/src/fees/fixed.rs index b755d653b3..eaa6207787 100644 --- a/zcash_client_backend/src/fees/fixed.rs +++ b/zcash_client_backend/src/fees/fixed.rs @@ -2,16 +2,15 @@ use std::marker::PhantomData; -use zcash_primitives::{ +use zcash_primitives::transaction::fees::{fixed::FeeRule as FixedFeeRule, transparent}; +use zcash_protocol::{ consensus::{self, BlockHeight}, memo::MemoBytes, - transaction::{ - components::amount::{BalanceError, NonNegativeAmount}, - fees::{fixed::FeeRule as FixedFeeRule, transparent}, - }, + value::{BalanceError, Zatoshis}, + ShieldedProtocol, }; -use crate::{data_api::InputSource, ShieldedProtocol}; +use crate::data_api::InputSource; use super::{ common::{single_pool_output_balance, SinglePoolBalanceConfig}, @@ -94,7 +93,7 @@ impl ChangeStrategy for SingleOutputChangeStrategy { self.fee_rule.fixed_fee(), &split_policy, self.fallback_change_pool, - NonNegativeAmount::ZERO, + Zatoshis::ZERO, 0, ); @@ -115,12 +114,14 @@ impl ChangeStrategy for SingleOutputChangeStrategy { #[cfg(test)] mod tests { - use zcash_primitives::{ + use ::transparent::bundle::TxOut; + use zcash_primitives::transaction::fees::{ + fixed::FeeRule as FixedFeeRule, zip317::MINIMUM_FEE, + }; + use zcash_protocol::{ consensus::{Network, NetworkUpgrade, Parameters}, - transaction::{ - components::{amount::NonNegativeAmount, transparent::TxOut}, - fees::{fixed::FeeRule as FixedFeeRule, zip317::MINIMUM_FEE}, - }, + value::Zatoshis, + ShieldedProtocol, }; use super::SingleOutputChangeStrategy; @@ -130,7 +131,6 @@ mod tests { tests::{TestSaplingInput, TestTransparentInput}, ChangeError, ChangeStrategy, ChangeValue, DustOutputPolicy, }, - ShieldedProtocol, }; #[cfg(feature = "orchard")] @@ -158,11 +158,9 @@ mod tests { sapling::builder::BundleType::DEFAULT, &[TestSaplingInput { note_id: 0, - value: NonNegativeAmount::const_from_u64(60000), + value: Zatoshis::const_from_u64(60000), }][..], - &[SaplingPayment::new(NonNegativeAmount::const_from_u64( - 40000, - ))][..], + &[SaplingPayment::new(Zatoshis::const_from_u64(40000))][..], ), #[cfg(feature = "orchard")] &orchard_fees::EmptyBundleView, @@ -173,7 +171,7 @@ mod tests { assert_matches!( result, Ok(balance) if - balance.proposed_change() == [ChangeValue::sapling(NonNegativeAmount::const_from_u64(10000), None)] && + balance.proposed_change() == [ChangeValue::sapling(Zatoshis::const_from_u64(10000), None)] && balance.fee_required() == MINIMUM_FEE ); } @@ -201,17 +199,15 @@ mod tests { &[ TestSaplingInput { note_id: 0, - value: NonNegativeAmount::const_from_u64(40000), + value: Zatoshis::const_from_u64(40000), }, // enough to pay a fee, plus dust TestSaplingInput { note_id: 0, - value: NonNegativeAmount::const_from_u64(10100), + value: Zatoshis::const_from_u64(10100), }, ][..], - &[SaplingPayment::new(NonNegativeAmount::const_from_u64( - 40000, - ))][..], + &[SaplingPayment::new(Zatoshis::const_from_u64(40000))][..], ), #[cfg(feature = "orchard")] &orchard_fees::EmptyBundleView, @@ -222,7 +218,7 @@ mod tests { assert_matches!( result, Err(ChangeError::InsufficientFunds { available, required }) - if available == NonNegativeAmount::const_from_u64(50100) && required == NonNegativeAmount::const_from_u64(60000) + if available == Zatoshis::const_from_u64(50100) && required == Zatoshis::const_from_u64(60000) ); } } diff --git a/zcash_client_backend/src/fees/orchard.rs b/zcash_client_backend/src/fees/orchard.rs index b4a9278519..ec9c5d0b32 100644 --- a/zcash_client_backend/src/fees/orchard.rs +++ b/zcash_client_backend/src/fees/orchard.rs @@ -2,9 +2,9 @@ //! of a transaction. use std::convert::Infallible; -use zcash_primitives::transaction::components::amount::NonNegativeAmount; use orchard::builder::BundleType; +use zcash_protocol::value::Zatoshis; /// A trait that provides a minimized view of Orchard bundle configuration /// suitable for use in fee and change calculation. @@ -67,14 +67,14 @@ pub trait InputView { /// An identifier for the input being spent. fn note_id(&self) -> &NoteRef; /// The value of the input being spent. - fn value(&self) -> NonNegativeAmount; + fn value(&self) -> Zatoshis; } impl InputView for Infallible { fn note_id(&self) -> &N { unreachable!() } - fn value(&self) -> NonNegativeAmount { + fn value(&self) -> Zatoshis { unreachable!() } } @@ -83,11 +83,11 @@ impl InputView for Infallible { /// calculation. pub trait OutputView { /// The value of the output being produced. - fn value(&self) -> NonNegativeAmount; + fn value(&self) -> Zatoshis; } impl OutputView for Infallible { - fn value(&self) -> NonNegativeAmount { + fn value(&self) -> Zatoshis { unreachable!() } } diff --git a/zcash_client_backend/src/fees/sapling.rs b/zcash_client_backend/src/fees/sapling.rs index 9f17f53a61..f4e282e8e2 100644 --- a/zcash_client_backend/src/fees/sapling.rs +++ b/zcash_client_backend/src/fees/sapling.rs @@ -4,7 +4,7 @@ use std::convert::Infallible; use sapling::builder::{BundleType, OutputInfo, SpendInfo}; -use zcash_primitives::transaction::components::amount::NonNegativeAmount; +use zcash_protocol::value::Zatoshis; /// A trait that provides a minimized view of Sapling bundle configuration /// suitable for use in fee and change calculation. @@ -67,14 +67,14 @@ pub trait InputView { /// An identifier for the input being spent. fn note_id(&self) -> &NoteRef; /// The value of the input being spent. - fn value(&self) -> NonNegativeAmount; + fn value(&self) -> Zatoshis; } impl InputView for Infallible { fn note_id(&self) -> &N { unreachable!() } - fn value(&self) -> NonNegativeAmount { + fn value(&self) -> Zatoshis { unreachable!() } } @@ -86,8 +86,8 @@ impl InputView<()> for SpendInfo { &() } - fn value(&self) -> NonNegativeAmount { - NonNegativeAmount::try_from(self.value().inner()) + fn value(&self) -> Zatoshis { + Zatoshis::try_from(self.value().inner()) .expect("An existing note to be spent must have a valid amount value.") } } @@ -96,18 +96,18 @@ impl InputView<()> for SpendInfo { /// fee and change calculation. pub trait OutputView { /// The value of the output being produced. - fn value(&self) -> NonNegativeAmount; + fn value(&self) -> Zatoshis; } impl OutputView for OutputInfo { - fn value(&self) -> NonNegativeAmount { - NonNegativeAmount::try_from(self.value().inner()) + fn value(&self) -> Zatoshis { + Zatoshis::try_from(self.value().inner()) .expect("Output values should be checked at construction.") } } impl OutputView for Infallible { - fn value(&self) -> NonNegativeAmount { + fn value(&self) -> Zatoshis { unreachable!() } } diff --git a/zcash_client_backend/src/fees/zip317.rs b/zcash_client_backend/src/fees/zip317.rs index e654bb56d7..3a77f6b1f7 100644 --- a/zcash_client_backend/src/fees/zip317.rs +++ b/zcash_client_backend/src/fees/zip317.rs @@ -6,17 +6,17 @@ use std::marker::PhantomData; -use zcash_primitives::{ +use zcash_primitives::transaction::fees::{transparent, zip317 as prim_zip317, FeeRule}; +use zcash_protocol::{ consensus::{self, BlockHeight}, memo::MemoBytes, - transaction::fees::{transparent, zip317 as prim_zip317, FeeRule}, + value::{BalanceError, Zatoshis}, + ShieldedProtocol, }; -use zcash_protocol::value::{BalanceError, Zatoshis}; use crate::{ data_api::{AccountMeta, InputSource, NoteFilter}, fees::StandardFeeRule, - ShieldedProtocol, }; use super::{ @@ -266,13 +266,12 @@ where mod tests { use std::{convert::Infallible, num::NonZeroUsize}; - use zcash_primitives::{ + use ::transparent::{address::Script, bundle::TxOut}; + use zcash_primitives::transaction::fees::zip317::FeeRule as Zip317FeeRule; + use zcash_protocol::{ consensus::{Network, NetworkUpgrade, Parameters}, - legacy::Script, - transaction::{ - components::{amount::NonNegativeAmount, transparent::TxOut}, - fees::zip317::FeeRule as Zip317FeeRule, - }, + value::Zatoshis, + ShieldedProtocol, }; use super::SingleOutputChangeStrategy; @@ -285,7 +284,6 @@ mod tests { zip317::MultiOutputChangeStrategy, ChangeError, ChangeStrategy, ChangeValue, DustAction, DustOutputPolicy, SplitPolicy, }, - ShieldedProtocol, }; #[cfg(feature = "orchard")] @@ -315,11 +313,9 @@ mod tests { sapling::builder::BundleType::DEFAULT, &[TestSaplingInput { note_id: 0, - value: NonNegativeAmount::const_from_u64(55000), + value: Zatoshis::const_from_u64(55000), }][..], - &[SaplingPayment::new(NonNegativeAmount::const_from_u64( - 40000, - ))][..], + &[SaplingPayment::new(Zatoshis::const_from_u64(40000))][..], ), #[cfg(feature = "orchard")] &orchard_fees::EmptyBundleView, @@ -330,8 +326,8 @@ mod tests { assert_matches!( result, Ok(balance) if - balance.proposed_change() == [ChangeValue::sapling(NonNegativeAmount::const_from_u64(5000), None)] && - balance.fee_required() == NonNegativeAmount::const_from_u64(10000) + balance.proposed_change() == [ChangeValue::sapling(Zatoshis::const_from_u64(5000), None)] && + balance.fee_required() == Zatoshis::const_from_u64(10000) ); } @@ -344,7 +340,7 @@ mod tests { DustOutputPolicy::default(), SplitPolicy::with_min_output_value( NonZeroUsize::new(5).unwrap(), - NonNegativeAmount::const_from_u64(100_0000), + Zatoshis::const_from_u64(100_0000), ), ); @@ -362,11 +358,9 @@ mod tests { sapling::builder::BundleType::DEFAULT, &[TestSaplingInput { note_id: 0, - value: NonNegativeAmount::const_from_u64(750_0000), + value: Zatoshis::const_from_u64(750_0000), }][..], - &[SaplingPayment::new(NonNegativeAmount::const_from_u64( - 100_0000, - ))][..], + &[SaplingPayment::new(Zatoshis::const_from_u64(100_0000))][..], ), #[cfg(feature = "orchard")] &orchard_fees::EmptyBundleView, @@ -376,27 +370,27 @@ mod tests { }; assert_matches!( - balance(0, NonNegativeAmount::ZERO), + balance(0, Zatoshis::ZERO), Ok(balance) if balance.proposed_change() == [ - ChangeValue::sapling(NonNegativeAmount::const_from_u64(129_4000), None), - ChangeValue::sapling(NonNegativeAmount::const_from_u64(129_4000), None), - ChangeValue::sapling(NonNegativeAmount::const_from_u64(129_4000), None), - ChangeValue::sapling(NonNegativeAmount::const_from_u64(129_4000), None), - ChangeValue::sapling(NonNegativeAmount::const_from_u64(129_4000), None), + ChangeValue::sapling(Zatoshis::const_from_u64(129_4000), None), + ChangeValue::sapling(Zatoshis::const_from_u64(129_4000), None), + ChangeValue::sapling(Zatoshis::const_from_u64(129_4000), None), + ChangeValue::sapling(Zatoshis::const_from_u64(129_4000), None), + ChangeValue::sapling(Zatoshis::const_from_u64(129_4000), None), ] && - balance.fee_required() == NonNegativeAmount::const_from_u64(30000) + balance.fee_required() == Zatoshis::const_from_u64(30000) ); assert_matches!( - balance(2, NonNegativeAmount::const_from_u64(100_0000)), + balance(2, Zatoshis::const_from_u64(100_0000)), Ok(balance) if balance.proposed_change() == [ - ChangeValue::sapling(NonNegativeAmount::const_from_u64(216_0000), None), - ChangeValue::sapling(NonNegativeAmount::const_from_u64(216_0000), None), - ChangeValue::sapling(NonNegativeAmount::const_from_u64(216_0000), None), + ChangeValue::sapling(Zatoshis::const_from_u64(216_0000), None), + ChangeValue::sapling(Zatoshis::const_from_u64(216_0000), None), + ChangeValue::sapling(Zatoshis::const_from_u64(216_0000), None), ] && - balance.fee_required() == NonNegativeAmount::const_from_u64(20000) + balance.fee_required() == Zatoshis::const_from_u64(20000) ); } @@ -414,18 +408,16 @@ mod tests { sapling::builder::BundleType::DEFAULT, &[TestSaplingInput { note_id: 0, - value: NonNegativeAmount::const_from_u64(600_0000), + value: Zatoshis::const_from_u64(600_0000), }][..], - &[SaplingPayment::new(NonNegativeAmount::const_from_u64( - 100_0000, - ))][..], + &[SaplingPayment::new(Zatoshis::const_from_u64(100_0000))][..], ), #[cfg(feature = "orchard")] &orchard_fees::EmptyBundleView, None, &AccountMeta::new( - Some(PoolMeta::new(0, NonNegativeAmount::ZERO)), - Some(PoolMeta::new(0, NonNegativeAmount::ZERO)), + Some(PoolMeta::new(0, Zatoshis::ZERO)), + Some(PoolMeta::new(0, Zatoshis::ZERO)), ), ); @@ -433,12 +425,12 @@ mod tests { result, Ok(balance) if balance.proposed_change() == [ - ChangeValue::sapling(NonNegativeAmount::const_from_u64(124_7500), None), - ChangeValue::sapling(NonNegativeAmount::const_from_u64(124_2500), None), - ChangeValue::sapling(NonNegativeAmount::const_from_u64(124_2500), None), - ChangeValue::sapling(NonNegativeAmount::const_from_u64(124_2500), None), + ChangeValue::sapling(Zatoshis::const_from_u64(124_7500), None), + ChangeValue::sapling(Zatoshis::const_from_u64(124_2500), None), + ChangeValue::sapling(Zatoshis::const_from_u64(124_2500), None), + ChangeValue::sapling(Zatoshis::const_from_u64(124_2500), None), ] && - balance.fee_required() == NonNegativeAmount::const_from_u64(25000) + balance.fee_required() == Zatoshis::const_from_u64(25000) ); } } @@ -465,16 +457,14 @@ mod tests { sapling::builder::BundleType::DEFAULT, &[TestSaplingInput { note_id: 0, - value: NonNegativeAmount::const_from_u64(55000), + value: Zatoshis::const_from_u64(55000), }][..], &[] as &[Infallible], ), &( orchard::builder::BundleType::DEFAULT, &[] as &[Infallible], - &[OrchardPayment::new(NonNegativeAmount::const_from_u64( - 30000, - ))][..], + &[OrchardPayment::new(Zatoshis::const_from_u64(30000))][..], ), None, &(), @@ -483,8 +473,8 @@ mod tests { assert_matches!( result, Ok(balance) if - balance.proposed_change() == [ChangeValue::orchard(NonNegativeAmount::const_from_u64(5000), None)] && - balance.fee_required() == NonNegativeAmount::const_from_u64(20000) + balance.proposed_change() == [ChangeValue::orchard(Zatoshis::const_from_u64(5000), None)] && + balance.fee_required() == Zatoshis::const_from_u64(20000) ); } @@ -497,7 +487,7 @@ mod tests { fn change_with_transparent_payments_explicitly_allowing_zero_change() { change_with_transparent_payments(DustOutputPolicy::new( DustAction::AllowDustChange, - Some(NonNegativeAmount::ZERO), + Some(Zatoshis::ZERO), )) } @@ -517,14 +507,14 @@ mod tests { .unwrap(), &[] as &[TestTransparentInput], &[TxOut { - value: NonNegativeAmount::const_from_u64(40000), + value: Zatoshis::const_from_u64(40000), script_pubkey: Script(vec![]), }], &( sapling::builder::BundleType::DEFAULT, &[TestSaplingInput { note_id: 0, - value: NonNegativeAmount::const_from_u64(55000), + value: Zatoshis::const_from_u64(55000), }][..], &[] as &[Infallible], ), @@ -537,8 +527,8 @@ mod tests { assert_matches!( result, Ok(balance) if - balance.proposed_change() == [ChangeValue::sapling(NonNegativeAmount::ZERO, None)] - && balance.fee_required() == NonNegativeAmount::const_from_u64(15000) + balance.proposed_change() == [ChangeValue::sapling(Zatoshis::ZERO, None)] + && balance.fee_required() == Zatoshis::const_from_u64(15000) ); } @@ -546,7 +536,7 @@ mod tests { #[cfg(feature = "transparent-inputs")] fn change_fully_transparent_no_change() { use crate::fees::sapling as sapling_fees; - use zcash_primitives::{legacy::TransparentAddress, transaction::components::OutPoint}; + use ::transparent::{address::TransparentAddress, bundle::OutPoint}; let change_strategy = SingleOutputChangeStrategy::<_, MockWalletDb>::new( Zip317FeeRule::standard(), @@ -564,12 +554,12 @@ mod tests { &[TestTransparentInput { outpoint: OutPoint::fake(), coin: TxOut { - value: NonNegativeAmount::const_from_u64(50000), + value: Zatoshis::const_from_u64(50000), script_pubkey: TransparentAddress::PublicKeyHash([0u8; 20]).script(), }, }], &[TxOut { - value: NonNegativeAmount::const_from_u64(40000), + value: Zatoshis::const_from_u64(40000), script_pubkey: Script(vec![]), }], &sapling_fees::EmptyBundleView, @@ -583,7 +573,7 @@ mod tests { result, Ok(balance) if balance.proposed_change().is_empty() && - balance.fee_required() == NonNegativeAmount::const_from_u64(10000) + balance.fee_required() == Zatoshis::const_from_u64(10000) ); } @@ -591,7 +581,7 @@ mod tests { #[cfg(feature = "transparent-inputs")] fn change_transparent_flows_with_shielded_change() { use crate::fees::sapling as sapling_fees; - use zcash_primitives::{legacy::TransparentAddress, transaction::components::OutPoint}; + use ::transparent::{address::TransparentAddress, bundle::OutPoint}; let change_strategy = SingleOutputChangeStrategy::<_, MockWalletDb>::new( Zip317FeeRule::standard(), @@ -609,12 +599,12 @@ mod tests { &[TestTransparentInput { outpoint: OutPoint::fake(), coin: TxOut { - value: NonNegativeAmount::const_from_u64(63000), + value: Zatoshis::const_from_u64(63000), script_pubkey: TransparentAddress::PublicKeyHash([0u8; 20]).script(), }, }], &[TxOut { - value: NonNegativeAmount::const_from_u64(40000), + value: Zatoshis::const_from_u64(40000), script_pubkey: Script(vec![]), }], &sapling_fees::EmptyBundleView, @@ -627,8 +617,8 @@ mod tests { assert_matches!( result, Ok(balance) if - balance.proposed_change() == [ChangeValue::sapling(NonNegativeAmount::const_from_u64(8000), None)] && - balance.fee_required() == NonNegativeAmount::const_from_u64(15000) + balance.proposed_change() == [ChangeValue::sapling(Zatoshis::const_from_u64(8000), None)] && + balance.fee_required() == Zatoshis::const_from_u64(15000) ); } @@ -636,7 +626,7 @@ mod tests { #[cfg(feature = "transparent-inputs")] fn change_transparent_flows_with_shielded_dust_change() { use crate::fees::sapling as sapling_fees; - use zcash_primitives::{legacy::TransparentAddress, transaction::components::OutPoint}; + use ::transparent::{address::TransparentAddress, bundle::OutPoint}; let change_strategy = SingleOutputChangeStrategy::<_, MockWalletDb>::new( Zip317FeeRule::standard(), @@ -644,7 +634,7 @@ mod tests { ShieldedProtocol::Sapling, DustOutputPolicy::new( DustAction::AllowDustChange, - Some(NonNegativeAmount::const_from_u64(1000)), + Some(Zatoshis::const_from_u64(1000)), ), ); @@ -660,12 +650,12 @@ mod tests { &[TestTransparentInput { outpoint: OutPoint::fake(), coin: TxOut { - value: NonNegativeAmount::const_from_u64(56000), + value: Zatoshis::const_from_u64(56000), script_pubkey: TransparentAddress::PublicKeyHash([0u8; 20]).script(), }, }], &[TxOut { - value: NonNegativeAmount::const_from_u64(40000), + value: Zatoshis::const_from_u64(40000), script_pubkey: Script(vec![]), }], &sapling_fees::EmptyBundleView, @@ -678,8 +668,8 @@ mod tests { assert_matches!( result, Ok(balance) if - balance.proposed_change() == [ChangeValue::sapling(NonNegativeAmount::const_from_u64(1000), None)] && - balance.fee_required() == NonNegativeAmount::const_from_u64(15000) + balance.proposed_change() == [ChangeValue::sapling(Zatoshis::const_from_u64(1000), None)] && + balance.fee_required() == Zatoshis::const_from_u64(15000) ); } @@ -692,7 +682,7 @@ mod tests { fn change_with_allowable_dust_explicitly_allowing_zero_change() { change_with_allowable_dust(DustOutputPolicy::new( DustAction::AllowDustChange, - Some(NonNegativeAmount::ZERO), + Some(Zatoshis::ZERO), )) } @@ -720,16 +710,14 @@ mod tests { &[ TestSaplingInput { note_id: 0, - value: NonNegativeAmount::const_from_u64(49000), + value: Zatoshis::const_from_u64(49000), }, TestSaplingInput { note_id: 1, - value: NonNegativeAmount::const_from_u64(1000), + value: Zatoshis::const_from_u64(1000), }, ][..], - &[SaplingPayment::new(NonNegativeAmount::const_from_u64( - 40000, - ))][..], + &[SaplingPayment::new(Zatoshis::const_from_u64(40000))][..], ), #[cfg(feature = "orchard")] &orchard_fees::EmptyBundleView, @@ -740,8 +728,8 @@ mod tests { assert_matches!( result, Ok(balance) if - balance.proposed_change() == [ChangeValue::sapling(NonNegativeAmount::ZERO, None)] && - balance.fee_required() == NonNegativeAmount::const_from_u64(10000) + balance.proposed_change() == [ChangeValue::sapling(Zatoshis::ZERO, None)] && + balance.fee_required() == Zatoshis::const_from_u64(10000) ); } @@ -768,20 +756,18 @@ mod tests { &[ TestSaplingInput { note_id: 0, - value: NonNegativeAmount::const_from_u64(29000), + value: Zatoshis::const_from_u64(29000), }, TestSaplingInput { note_id: 1, - value: NonNegativeAmount::const_from_u64(20000), + value: Zatoshis::const_from_u64(20000), }, TestSaplingInput { note_id: 2, - value: NonNegativeAmount::const_from_u64(1000), + value: Zatoshis::const_from_u64(1000), }, ][..], - &[SaplingPayment::new(NonNegativeAmount::const_from_u64( - 30000, - ))][..], + &[SaplingPayment::new(Zatoshis::const_from_u64(30000))][..], ), #[cfg(feature = "orchard")] &orchard_fees::EmptyBundleView, diff --git a/zcash_client_backend/src/lib.rs b/zcash_client_backend/src/lib.rs index 2dfd599562..5f19e856d6 100644 --- a/zcash_client_backend/src/lib.rs +++ b/zcash_client_backend/src/lib.rs @@ -61,18 +61,18 @@ // Temporary until we have addressed all Result cases. #![allow(clippy::result_unit_err)] -pub use zcash_keys::address; +//pub use zcash_keys::address; pub mod data_api; mod decrypt; -pub use zcash_keys::encoding; +//pub use zcash_keys::encoding; pub mod fees; -pub use zcash_keys::keys; +//pub use zcash_keys::keys; pub mod proposal; pub mod proto; pub mod scan; pub mod scanning; pub mod wallet; -pub use zip321; +//pub use zip321; #[cfg(feature = "sync")] pub mod sync; @@ -84,7 +84,7 @@ pub mod serialization; pub mod tor; pub use decrypt::{decrypt_transaction, DecryptedOutput, TransferType}; -pub use zcash_protocol::{PoolType, ShieldedProtocol}; +//pub use zcash_protocol::{PoolType, ShieldedProtocol}; #[cfg(test)] #[macro_use] diff --git a/zcash_client_backend/src/proposal.rs b/zcash_client_backend/src/proposal.rs index 45391cb2b7..ff004cdf80 100644 --- a/zcash_client_backend/src/proposal.rs +++ b/zcash_client_backend/src/proposal.rs @@ -6,16 +6,13 @@ use std::{ }; use nonempty::NonEmpty; -use zcash_primitives::{ - consensus::BlockHeight, - transaction::{components::amount::NonNegativeAmount, TxId}, -}; +use zcash_primitives::transaction::TxId; +use zcash_protocol::{consensus::BlockHeight, value::Zatoshis, PoolType, ShieldedProtocol}; +use zip321::TransactionRequest; use crate::{ fees::TransactionBalance, wallet::{Note, ReceivedNote, WalletTransparentOutput}, - zip321::TransactionRequest, - PoolType, ShieldedProtocol, }; /// Errors that can occur in construction of a [`Step`]. @@ -29,8 +26,8 @@ pub enum ProposalError { /// sum of transaction outputs, change, and fees is required to be exactly equal to the value /// of provided inputs. BalanceError { - input_total: NonNegativeAmount, - output_total: NonNegativeAmount, + input_total: Zatoshis, + output_total: Zatoshis, }, /// The `is_shielding` flag may only be set to `true` under the following conditions: /// * The total of transparent inputs is nonzero @@ -424,7 +421,7 @@ impl Step { let transparent_input_total = transparent_inputs .iter() .map(|out| out.txout().value) - .try_fold(NonNegativeAmount::ZERO, |acc, a| { + .try_fold(Zatoshis::ZERO, |acc, a| { (acc + a).ok_or(ProposalError::Overflow) })?; @@ -432,7 +429,7 @@ impl Step { .iter() .flat_map(|s_in| s_in.notes().iter()) .map(|out| out.note().value()) - .try_fold(NonNegativeAmount::ZERO, |acc, a| (acc + a)) + .try_fold(Zatoshis::ZERO, |acc, a| (acc + a)) .ok_or(ProposalError::Overflow)?; let prior_step_input_total = prior_step_inputs @@ -458,7 +455,7 @@ impl Step { }) .collect::, _>>()? .into_iter() - .try_fold(NonNegativeAmount::ZERO, |acc, a| (acc + a)) + .try_fold(Zatoshis::ZERO, |acc, a| (acc + a)) .ok_or(ProposalError::Overflow)?; let input_total = (transparent_input_total + shielded_input_total + prior_step_input_total) @@ -470,9 +467,9 @@ impl Step { let output_total = (request_total + balance.total()).ok_or(ProposalError::Overflow)?; if is_shielding - && (transparent_input_total == NonNegativeAmount::ZERO - || shielded_input_total > NonNegativeAmount::ZERO - || request_total > NonNegativeAmount::ZERO) + && (transparent_input_total == Zatoshis::ZERO + || shielded_input_total > Zatoshis::ZERO + || request_total > Zatoshis::ZERO) { return Err(ProposalError::ShieldingInvalid); } diff --git a/zcash_client_backend/src/proto.rs b/zcash_client_backend/src/proto.rs index 79813d7c4c..783c9d5a6e 100644 --- a/zcash_client_backend/src/proto.rs +++ b/zcash_client_backend/src/proto.rs @@ -13,22 +13,25 @@ use sapling::{self, note::ExtractedNoteCommitment, Node}; use zcash_note_encryption::{EphemeralKeyBytes, COMPACT_NOTE_SIZE}; use zcash_primitives::{ block::{BlockHash, BlockHeader}, + merkle_tree::read_commitment_tree, + transaction::TxId, +}; +use zcash_protocol::{ consensus::BlockHeight, memo::{self, MemoBytes}, - merkle_tree::read_commitment_tree, - transaction::{components::amount::NonNegativeAmount, TxId}, + value::Zatoshis, + PoolType, ShieldedProtocol, }; +use zip321::{TransactionRequest, Zip321Error}; use crate::{ data_api::{chain::ChainState, InputSource}, fees::{ChangeValue, StandardFeeRule, TransactionBalance}, proposal::{Proposal, ProposalError, ShieldedInputs, Step, StepOutput, StepOutputIndex}, - zip321::{TransactionRequest, Zip321Error}, - PoolType, ShieldedProtocol, }; #[cfg(feature = "transparent-inputs")] -use zcash_primitives::transaction::components::OutPoint; +use transparent::bundle::OutPoint; #[cfg(feature = "orchard")] use orchard::tree::MerkleHashOrchard; @@ -745,7 +748,7 @@ impl proposal::Proposal { .proposed_change .iter() .map(|cv| -> Result> { - let value = NonNegativeAmount::from_u64(cv.value) + let value = Zatoshis::from_u64(cv.value) .map_err(|_| ProposalDecodingError::BalanceInvalid)?; let memo = cv .memo @@ -779,7 +782,7 @@ impl proposal::Proposal { } }) .collect::, _>>()?, - NonNegativeAmount::from_u64(proto_balance.fee_required) + Zatoshis::from_u64(proto_balance.fee_required) .map_err(|_| ProposalDecodingError::BalanceInvalid)?, ) .map_err(|_| ProposalDecodingError::BalanceInvalid)?; diff --git a/zcash_client_backend/src/scanning.rs b/zcash_client_backend/src/scanning.rs index 1967b9ff5e..22cc0e3ec2 100644 --- a/zcash_client_backend/src/scanning.rs +++ b/zcash_client_backend/src/scanning.rs @@ -15,9 +15,10 @@ use subtle::{ConditionallySelectable, ConstantTimeEq, CtOption}; use tracing::{debug, trace}; use zcash_keys::keys::UnifiedFullViewingKey; use zcash_note_encryption::{batch, BatchDomain, Domain, ShieldedOutput, COMPACT_NOTE_SIZE}; -use zcash_primitives::{ +use zcash_primitives::transaction::{components::sapling::zip212_enforcement, TxId}; +use zcash_protocol::{ consensus::{self, BlockHeight, NetworkUpgrade}, - transaction::{components::sapling::zip212_enforcement, TxId}, + ShieldedProtocol, }; use zip32::Scope; @@ -26,7 +27,6 @@ use crate::{ proto::compact_formats::CompactBlock, scan::{Batch, BatchRunner, CompactDecryptor, DecryptedOutput, Tasks}, wallet::{WalletOutput, WalletSpend, WalletTx}, - ShieldedProtocol, }; #[cfg(feature = "orchard")] @@ -1167,10 +1167,12 @@ pub mod testing { }; use zcash_note_encryption::{Domain, COMPACT_NOTE_SIZE}; use zcash_primitives::{ - block::BlockHash, + block::BlockHash, transaction::components::sapling::zip212_enforcement, + }; + use zcash_protocol::{ consensus::{BlockHeight, Network}, memo::MemoBytes, - transaction::components::{amount::NonNegativeAmount, sapling::zip212_enforcement}, + value::Zatoshis, }; use crate::proto::compact_formats::{ @@ -1220,7 +1222,7 @@ pub mod testing { prev_hash: BlockHash, nf: Nullifier, dfvk: &DiversifiableFullViewingKey, - value: NonNegativeAmount, + value: Zatoshis, tx_after: bool, initial_tree_sizes: Option<(u32, u32)>, ) -> CompactBlock { @@ -1304,12 +1306,12 @@ mod tests { use incrementalmerkletree::{Marking, Position, Retention}; use sapling::Nullifier; use zcash_keys::keys::UnifiedSpendingKey; - use zcash_primitives::{ - block::BlockHash, + use zcash_primitives::block::BlockHash; + use zcash_protocol::{ consensus::{BlockHeight, Network}, - transaction::components::amount::NonNegativeAmount, - zip32::AccountId, + value::Zatoshis, }; + use zip32::AccountId; use crate::{ data_api::BlockMetadata, @@ -1334,7 +1336,7 @@ mod tests { BlockHash([0; 32]), Nullifier([0; 32]), &sapling_dfvk, - NonNegativeAmount::const_from_u64(5), + Zatoshis::const_from_u64(5), false, None, ); @@ -1420,7 +1422,7 @@ mod tests { BlockHash([0; 32]), Nullifier([0; 32]), &sapling_dfvk, - NonNegativeAmount::const_from_u64(5), + Zatoshis::const_from_u64(5), true, Some((0, 0)), ); @@ -1500,7 +1502,7 @@ mod tests { BlockHash([0; 32]), nf, ufvk.sapling().unwrap(), - NonNegativeAmount::const_from_u64(5), + Zatoshis::const_from_u64(5), false, Some((0, 0)), ); diff --git a/zcash_client_backend/src/sync.rs b/zcash_client_backend/src/sync.rs index 2ddce5fbec..e2a8681544 100644 --- a/zcash_client_backend/src/sync.rs +++ b/zcash_client_backend/src/sync.rs @@ -20,10 +20,10 @@ use tonic::{ codegen::{Body, Bytes, StdError}, }; use tracing::{debug, info}; -use zcash_primitives::{ - consensus::{BlockHeight, Parameters}, - merkle_tree::HashSer, -}; + +use zcash_keys::encoding::AddressCodec as _; +use zcash_primitives::merkle_tree::HashSer; +use zcash_protocol::consensus::{BlockHeight, Parameters}; use crate::{ data_api::{ @@ -43,10 +43,10 @@ use orchard::tree::MerkleHashOrchard; #[cfg(feature = "transparent-inputs")] use { - crate::{encoding::AddressCodec, wallet::WalletTransparentOutput}, - zcash_primitives::{ - legacy::Script, - transaction::components::transparent::{OutPoint, TxOut}, + crate::wallet::WalletTransparentOutput, + ::transparent::{ + address::Script, + bundle::{OutPoint, TxOut}, }, zcash_protocol::{consensus::NetworkUpgrade, value::Zatoshis}, }; diff --git a/zcash_client_backend/src/wallet.rs b/zcash_client_backend/src/wallet.rs index f3bca04baa..1bb51954e2 100644 --- a/zcash_client_backend/src/wallet.rs +++ b/zcash_client_backend/src/wallet.rs @@ -1,31 +1,28 @@ //! Structs representing transaction data scanned from the block chain by a wallet or //! light client. +use ::transparent::{ + address::TransparentAddress, + bundle::{OutPoint, TxOut}, +}; use incrementalmerkletree::Position; use zcash_address::ZcashAddress; use zcash_note_encryption::EphemeralKeyBytes; -use zcash_primitives::{ +use zcash_primitives::transaction::{fees::transparent as transparent_fees, TxId}; +use zcash_protocol::{ consensus::BlockHeight, - legacy::TransparentAddress, - transaction::{ - components::{ - amount::NonNegativeAmount, - transparent::{OutPoint, TxOut}, - }, - fees::transparent as transparent_fees, - TxId, - }, - zip32::Scope, + value::{BalanceError, Zatoshis}, + PoolType, ShieldedProtocol, }; -use zcash_protocol::value::BalanceError; +use zip32::Scope; -use crate::{fees::sapling as sapling_fees, PoolType, ShieldedProtocol}; +use crate::fees::sapling as sapling_fees; #[cfg(feature = "orchard")] use crate::fees::orchard as orchard_fees; #[cfg(feature = "transparent-inputs")] -use zcash_primitives::legacy::keys::{NonHardenedChildIndex, TransparentKeyScope}; +use ::transparent::keys::{NonHardenedChildIndex, TransparentKeyScope}; /// A unique identifier for a shielded transaction output #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] @@ -285,7 +282,7 @@ impl WalletTransparentOutput { &self.recipient_address } - pub fn value(&self) -> NonNegativeAmount { + pub fn value(&self) -> Zatoshis { self.txout.value } } @@ -433,13 +430,13 @@ pub enum Note { } impl Note { - pub fn value(&self) -> NonNegativeAmount { + pub fn value(&self) -> Zatoshis { match self { Note::Sapling(n) => n.value().inner().try_into().expect( "Sapling notes must have values in the range of valid non-negative ZEC values.", ), #[cfg(feature = "orchard")] - Note::Orchard(n) => NonNegativeAmount::from_u64(n.value().inner()).expect( + Note::Orchard(n) => Zatoshis::from_u64(n.value().inner()).expect( "Orchard notes must have values in the range of valid non-negative ZEC values.", ), } @@ -522,14 +519,14 @@ impl ReceivedNote { } impl ReceivedNote { - pub fn note_value(&self) -> Result { + pub fn note_value(&self) -> Result { self.note.value().inner().try_into() } } #[cfg(feature = "orchard")] impl ReceivedNote { - pub fn note_value(&self) -> Result { + pub fn note_value(&self) -> Result { self.note.value().inner().try_into() } } @@ -539,7 +536,7 @@ impl sapling_fees::InputView for (NoteRef, sapling::value::Not &self.0 } - fn value(&self) -> NonNegativeAmount { + fn value(&self) -> Zatoshis { self.1 .inner() .try_into() @@ -552,7 +549,7 @@ impl sapling_fees::InputView for ReceivedNote NonNegativeAmount { + fn value(&self) -> Zatoshis { self.note .value() .inner() @@ -567,7 +564,7 @@ impl orchard_fees::InputView for (NoteRef, orchard::value::Not &self.0 } - fn value(&self) -> NonNegativeAmount { + fn value(&self) -> Zatoshis { self.1 .inner() .try_into() @@ -581,7 +578,7 @@ impl orchard_fees::InputView for ReceivedNote NonNegativeAmount { + fn value(&self) -> Zatoshis { self.note .value() .inner() diff --git a/zcash_client_sqlite/Cargo.toml b/zcash_client_sqlite/Cargo.toml index fbe2f20204..5c0a5339a9 100644 --- a/zcash_client_sqlite/Cargo.toml +++ b/zcash_client_sqlite/Cargo.toml @@ -33,6 +33,7 @@ zcash_keys = { workspace = true, features = ["sapling"] } zcash_primitives.workspace = true zcash_protocol.workspace = true zip32.workspace = true +transparent.workspace = true # Dependencies exposed in a public API: # (Breaking upgrades to these require a breaking upgrade to this crate.) diff --git a/zcash_client_sqlite/src/chain.rs b/zcash_client_sqlite/src/chain.rs index 42e111d629..a8835e2324 100644 --- a/zcash_client_sqlite/src/chain.rs +++ b/zcash_client_sqlite/src/chain.rs @@ -3,7 +3,7 @@ use prost::Message; use rusqlite::params; -use zcash_primitives::consensus::BlockHeight; +use zcash_protocol::consensus::BlockHeight; use zcash_client_backend::{data_api::chain::error::Error, proto::compact_formats::CompactBlock}; diff --git a/zcash_client_sqlite/src/error.rs b/zcash_client_sqlite/src/error.rs index 407358eb95..622bcc0077 100644 --- a/zcash_client_sqlite/src/error.rs +++ b/zcash_client_sqlite/src/error.rs @@ -6,17 +6,16 @@ use std::fmt; use shardtree::error::ShardTreeError; use zcash_address::ParseError; use zcash_client_backend::data_api::NoteFilter; -use zcash_client_backend::PoolType; use zcash_keys::keys::AddressGenerationError; -use zcash_primitives::zip32; -use zcash_primitives::{consensus::BlockHeight, transaction::components::amount::BalanceError}; +use zcash_protocol::{consensus::BlockHeight, value::BalanceError, PoolType}; +use zip32; use crate::{wallet::commitment_tree, AccountUuid}; #[cfg(feature = "transparent-inputs")] use { - zcash_client_backend::encoding::TransparentCodecError, - zcash_primitives::{legacy::TransparentAddress, transaction::TxId}, + ::transparent::address::TransparentAddress, zcash_keys::encoding::TransparentCodecError, + zcash_primitives::transaction::TxId, }; /// The primary error type for the SQLite wallet backend. @@ -53,7 +52,7 @@ pub enum SqliteClientError { Io(std::io::Error), /// A received memo cannot be interpreted as a UTF-8 string. - InvalidMemo(zcash_primitives::memo::Error), + InvalidMemo(zcash_protocol::memo::Error), /// An attempt to update block data would overwrite the current hash for a block with a /// different hash. This indicates that a required rewind was not performed. @@ -234,8 +233,8 @@ impl From for SqliteClientError { } } -impl From for SqliteClientError { - fn from(e: zcash_primitives::memo::Error) -> Self { +impl From for SqliteClientError { + fn from(e: zcash_protocol::memo::Error) -> Self { SqliteClientError::InvalidMemo(e) } } diff --git a/zcash_client_sqlite/src/lib.rs b/zcash_client_sqlite/src/lib.rs index a6f02d51e1..ecbbfbbd68 100644 --- a/zcash_client_sqlite/src/lib.rs +++ b/zcash_client_sqlite/src/lib.rs @@ -46,7 +46,6 @@ use tracing::{debug, trace, warn}; use uuid::Uuid; use zcash_client_backend::{ - address::UnifiedAddress, data_api::{ self, chain::{BlockSource, ChainState, CommitmentTreeRoot}, @@ -56,22 +55,27 @@ use zcash_client_backend::{ SentTransaction, SpendableNotes, TransactionDataRequest, WalletCommitmentTrees, WalletRead, WalletSummary, WalletWrite, Zip32Derivation, SAPLING_SHARD_HEIGHT, }, + proto::compact_formats::CompactBlock, + wallet::{Note, NoteId, ReceivedNote, WalletTransparentOutput}, + TransferType, +}; +use zcash_keys::{ + address::UnifiedAddress, keys::{ AddressGenerationError, UnifiedAddressRequest, UnifiedFullViewingKey, UnifiedSpendingKey, }, - proto::compact_formats::CompactBlock, - wallet::{Note, NoteId, ReceivedNote, WalletTransparentOutput}, - ShieldedProtocol, TransferType, }; - use zcash_primitives::{ block::BlockHash, + transaction::{Transaction, TxId}, +}; +use zcash_protocol::{ consensus::{self, BlockHeight}, memo::Memo, - transaction::{components::amount::NonNegativeAmount, Transaction, TxId}, - zip32::{self, DiversifierIndex}, + value::Zatoshis, + ShieldedProtocol, }; -use zip32::fingerprint::SeedFingerprint; +use zip32::{self, fingerprint::SeedFingerprint, DiversifierIndex}; use crate::{error::SqliteClientError, wallet::commitment_tree::SqliteShardStore}; @@ -88,9 +92,9 @@ use { #[cfg(feature = "transparent-inputs")] use { + ::transparent::{address::TransparentAddress, bundle::OutPoint}, zcash_client_backend::wallet::TransparentAddressMetadata, - zcash_keys::encoding::AddressCodec, - zcash_primitives::{legacy::TransparentAddress, transaction::components::OutPoint}, + zcash_keys::encoding::AddressCodec as _, }; #[cfg(feature = "multicore")] @@ -317,7 +321,7 @@ impl, P: consensus::Parameters> InputSource for fn select_spendable_notes( &self, account: Self::AccountId, - target_value: NonNegativeAmount, + target_value: Zatoshis, sources: &[ShieldedProtocol], anchor_height: BlockHeight, exclude: &[Self::NoteRef], @@ -628,7 +632,7 @@ impl, P: consensus::Parameters> WalletRead for W &self, account: Self::AccountId, max_height: BlockHeight, - ) -> Result, Self::Error> { + ) -> Result, Self::Error> { wallet::transparent::get_transparent_balances( self.conn.borrow(), &self.params, @@ -758,7 +762,7 @@ impl, P: consensus::Parameters> WalletTest for W .map(|res| { let (amount, external_recipient, ephemeral_address) = res?; Ok::<_, ::Error>(OutputOfSentTx::from_parts( - NonNegativeAmount::from_u64(amount)?, + Zatoshis::from_u64(amount)?, external_recipient, ephemeral_address, )) @@ -1941,10 +1945,7 @@ mod tests { use crate::{error::SqliteClientError, testing::db::TestDbFactory, AccountUuid}; #[cfg(feature = "unstable")] - use { - zcash_client_backend::keys::sapling, - zcash_primitives::transaction::components::amount::NonNegativeAmount, - }; + use zcash_keys::keys::sapling; #[test] fn validate_seed() { @@ -2255,8 +2256,8 @@ mod tests { #[test] pub(crate) fn fsblockdb_api() { use zcash_client_backend::data_api::testing::AddressType; - use zcash_primitives::zip32; - use zcash_protocol::consensus::NetworkConstants; + use zcash_protocol::{consensus::NetworkConstants, value::Zatoshis}; + use zip32; use crate::testing::FsBlockCache; @@ -2276,12 +2277,12 @@ mod tests { let (h1, meta1, _) = st.generate_next_block( &dfvk, AddressType::DefaultExternal, - NonNegativeAmount::const_from_u64(5), + Zatoshis::const_from_u64(5), ); let (h2, meta2, _) = st.generate_next_block( &dfvk, AddressType::DefaultExternal, - NonNegativeAmount::const_from_u64(10), + Zatoshis::const_from_u64(10), ); // The BlockMeta DB is not updated until we do so explicitly. diff --git a/zcash_client_sqlite/src/testing/db.rs b/zcash_client_sqlite/src/testing/db.rs index e11cc9f975..2675dff877 100644 --- a/zcash_client_sqlite/src/testing/db.rs +++ b/zcash_client_sqlite/src/testing/db.rs @@ -18,19 +18,20 @@ use zcash_client_backend::{ testing::{DataStoreFactory, Reset, TestState}, *, }, - keys::UnifiedFullViewingKey, wallet::{Note, NoteId, ReceivedNote, WalletTransparentOutput}, - ShieldedProtocol, }; use zcash_keys::{ address::UnifiedAddress, - keys::{UnifiedAddressRequest, UnifiedSpendingKey}, + keys::{UnifiedAddressRequest, UnifiedFullViewingKey, UnifiedSpendingKey}, }; use zcash_primitives::{ block::BlockHash, - transaction::{components::amount::NonNegativeAmount, Transaction, TxId}, + transaction::{Transaction, TxId}, +}; +use zcash_protocol::{ + consensus::BlockHeight, local_consensus::LocalNetwork, memo::Memo, value::Zatoshis, + ShieldedProtocol, }; -use zcash_protocol::{consensus::BlockHeight, local_consensus::LocalNetwork, memo::Memo}; use crate::{ error::SqliteClientError, @@ -41,8 +42,8 @@ use crate::{ #[cfg(feature = "transparent-inputs")] use { crate::TransparentAddressMetadata, + ::transparent::{address::TransparentAddress, bundle::OutPoint}, core::ops::Range, - zcash_primitives::{legacy::TransparentAddress, transaction::components::OutPoint}, }; #[derive(Delegate)] diff --git a/zcash_client_sqlite/src/wallet.rs b/zcash_client_sqlite/src/wallet.rs index 532b4f7cec..a3cd7d224c 100644 --- a/zcash_client_sqlite/src/wallet.rs +++ b/zcash_client_sqlite/src/wallet.rs @@ -84,6 +84,7 @@ use std::ops::RangeInclusive; use tracing::{debug, warn}; +use ::transparent::bundle::OutPoint; use zcash_address::ZcashAddress; use zcash_client_backend::{ data_api::{ @@ -91,27 +92,27 @@ use zcash_client_backend::{ Account as _, AccountBalance, AccountBirthday, AccountSource, BlockMetadata, Ratio, SentTransaction, SentTransactionOutput, WalletSummary, SAPLING_SHARD_HEIGHT, }, - encoding::AddressCodec, - keys::UnifiedFullViewingKey, wallet::{Note, NoteId, Recipient, WalletTx}, - DecryptedOutput, PoolType, ShieldedProtocol, + DecryptedOutput, }; use zcash_keys::{ address::{Address, Receiver, UnifiedAddress}, + encoding::AddressCodec, keys::{ - AddressGenerationError, UnifiedAddressRequest, UnifiedIncomingViewingKey, - UnifiedSpendingKey, + AddressGenerationError, UnifiedAddressRequest, UnifiedFullViewingKey, + UnifiedIncomingViewingKey, UnifiedSpendingKey, }, }; use zcash_primitives::{ block::BlockHash, + merkle_tree::read_commitment_tree, + transaction::{Transaction, TransactionData, TxId}, +}; +use zcash_protocol::{ consensus::{self, BlockHeight, BranchId, NetworkUpgrade, Parameters}, memo::{Memo, MemoBytes}, - merkle_tree::read_commitment_tree, - transaction::{ - components::{amount::NonNegativeAmount, Amount, OutPoint}, - Transaction, TransactionData, TxId, - }, + value::{ZatBalance, Zatoshis}, + PoolType, ShieldedProtocol, }; use zip32::{self, DiversifierIndex, Scope}; @@ -124,7 +125,7 @@ use crate::{ use crate::{AccountUuid, TxRef, VERIFY_LOOKAHEAD}; #[cfg(feature = "transparent-inputs")] -use zcash_primitives::transaction::components::TxOut; +use ::transparent::bundle::TxOut; use self::scanning::{parse_priority_code, priority_code, replace_queue_entries}; @@ -1432,12 +1433,7 @@ pub(crate) fn get_wallet_summary( with_pool_balance: F, ) -> Result<(), SqliteClientError> where - F: Fn( - &mut AccountBalance, - NonNegativeAmount, - NonNegativeAmount, - NonNegativeAmount, - ) -> Result<(), SqliteClientError>, + F: Fn(&mut AccountBalance, Zatoshis, Zatoshis, Zatoshis) -> Result<(), SqliteClientError>, { // If the shard containing the summary height contains any unscanned ranges that start below or // including that height, none of our shielded balance is currently spendable. @@ -1494,7 +1490,7 @@ pub(crate) fn get_wallet_summary( let account = AccountUuid(row.get::<_, Uuid>(0)?); let value_raw = row.get::<_, i64>(1)?; - let value = NonNegativeAmount::from_nonnegative_i64(value_raw).map_err(|_| { + let value = Zatoshis::from_nonnegative_i64(value_raw).map_err(|_| { SqliteClientError::CorruptedData(format!( "Negative received note value: {}", value_raw @@ -1529,7 +1525,7 @@ pub(crate) fn get_wallet_summary( is_change && received_height.iter().all(|h| h > &summary_height); let (spendable_value, change_pending_confirmation, value_pending_spendability) = { - let zero = NonNegativeAmount::ZERO; + let zero = Zatoshis::ZERO; if is_spendable { (value, zero, zero) } else if is_pending_change { @@ -3142,7 +3138,7 @@ pub(crate) fn select_receiving_address( pub(crate) fn put_tx_data( conn: &rusqlite::Connection, tx: &Transaction, - fee: Option, + fee: Option, created_at: Option, target_height: Option, ) -> Result { @@ -3403,7 +3399,7 @@ pub(crate) fn insert_sent_output( ":from_account_id": from_account_id.0, ":to_address": &to_address, ":to_account_id": to_account_id.map(|a| a.0), - ":value": &i64::from(Amount::from(output.value())), + ":value": &i64::from(ZatBalance::from(output.value())), ":memo": memo_repr(output.memo()) ]; @@ -3432,7 +3428,7 @@ pub(crate) fn put_sent_output( tx_ref: TxRef, output_index: usize, recipient: &Recipient, - value: NonNegativeAmount, + value: Zatoshis, memo: Option<&MemoBytes>, ) -> Result<(), SqliteClientError> { let mut stmt_upsert_sent_output = conn.prepare_cached( @@ -3459,7 +3455,7 @@ pub(crate) fn put_sent_output( ":from_account_id": from_account_id.0, ":to_address": &to_address, ":to_account_id": &to_account_id.map(|a| a.0), - ":value": &i64::from(Amount::from(value)), + ":value": &i64::from(ZatBalance::from(value)), ":memo": memo_repr(memo) ]; @@ -3734,7 +3730,8 @@ mod tests { testing::{AddressType, DataStoreFactory, FakeCompactOutput, TestBuilder, TestState}, Account as _, AccountSource, WalletRead, WalletWrite, }; - use zcash_primitives::{block::BlockHash, transaction::components::amount::NonNegativeAmount}; + use zcash_primitives::block::BlockHash; + use zcash_protocol::value::Zatoshis; use crate::{ testing::{db::TestDbFactory, BlockCache}, @@ -3831,7 +3828,7 @@ mod tests { // Scan a block above the wallet's birthday height. let not_our_key = ExtendedSpendingKey::master(&[]).to_diversifiable_full_viewing_key(); - let not_our_value = NonNegativeAmount::const_from_u64(10000); + let not_our_value = Zatoshis::const_from_u64(10000); let start_height = st.sapling_activation_height(); let _ = st.generate_block_at( start_height, diff --git a/zcash_client_sqlite/src/wallet/commitment_tree.rs b/zcash_client_sqlite/src/wallet/commitment_tree.rs index 71b34f83c9..8589c1d6ab 100644 --- a/zcash_client_sqlite/src/wallet/commitment_tree.rs +++ b/zcash_client_sqlite/src/wallet/commitment_tree.rs @@ -8,7 +8,6 @@ use std::{ ops::Range, sync::Arc, }; -use zcash_client_backend::data_api::chain::CommitmentTreeRoot; use incrementalmerkletree::{Address, Hashable, Level, Position, Retention}; use shardtree::{ @@ -17,9 +16,12 @@ use shardtree::{ LocatedPrunableTree, LocatedTree, PrunableTree, RetentionFlags, }; -use zcash_primitives::{consensus::BlockHeight, merkle_tree::HashSer}; - -use zcash_client_backend::serialization::shardtree::{read_shard, write_shard}; +use zcash_client_backend::{ + data_api::chain::CommitmentTreeRoot, + serialization::shardtree::{read_shard, write_shard}, +}; +use zcash_primitives::merkle_tree::HashSer; +use zcash_protocol::consensus::BlockHeight; /// Errors that can appear in SQLite-back [`ShardStore`] implementation operations. #[derive(Debug)] @@ -1107,7 +1109,7 @@ mod tests { chain::CommitmentTreeRoot, testing::{pool::ShieldedPoolTester, sapling::SaplingPoolTester}, }; - use zcash_primitives::consensus::{BlockHeight, Network}; + use zcash_protocol::consensus::{BlockHeight, Network}; use super::SqliteShardStore; use crate::{testing::pool::ShieldedPoolPersistence, wallet::init::init_wallet_db, WalletDb}; diff --git a/zcash_client_sqlite/src/wallet/common.rs b/zcash_client_sqlite/src/wallet/common.rs index ac9e3834ee..b3fdd569ce 100644 --- a/zcash_client_sqlite/src/wallet/common.rs +++ b/zcash_client_sqlite/src/wallet/common.rs @@ -6,13 +6,12 @@ use std::{num::NonZeroU64, rc::Rc}; use zcash_client_backend::{ data_api::{NoteFilter, PoolMeta}, wallet::ReceivedNote, - ShieldedProtocol, }; -use zcash_primitives::transaction::{components::amount::NonNegativeAmount, TxId}; +use zcash_primitives::transaction::TxId; use zcash_protocol::{ consensus::{self, BlockHeight}, - value::BalanceError, - PoolType, + value::{BalanceError, Zatoshis}, + PoolType, ShieldedProtocol, }; use super::wallet_birthday; @@ -119,7 +118,7 @@ pub(crate) fn select_spendable_notes( conn: &Connection, params: &P, account: AccountUuid, - target_value: NonNegativeAmount, + target_value: Zatoshis, anchor_height: BlockHeight, exclude: &[ReceivedNoteId], protocol: ShieldedProtocol, @@ -259,8 +258,8 @@ pub(crate) fn spendable_notes_meta( .collect(); let excluded_ptr = Rc::new(excluded); - fn zatoshis(value: i64) -> Result { - NonNegativeAmount::from_nonnegative_i64(value).map_err(|_| { + fn zatoshis(value: i64) -> Result { + Zatoshis::from_nonnegative_i64(value).map_err(|_| { SqliteClientError::CorruptedData(format!("Negative received note value: {}", value)) }) } @@ -308,7 +307,7 @@ pub(crate) fn spendable_notes_meta( account: AccountUuid, filter: &NoteFilter, chain_tip_height: BlockHeight, - ) -> Result, SqliteClientError> { + ) -> Result, SqliteClientError> { match filter { NoteFilter::ExceedsMinValue(v) => Ok(Some(*v)), NoteFilter::ExceedsPriorSendPercentile(n) => { @@ -334,14 +333,12 @@ pub(crate) fn spendable_notes_meta( .query_and_then::<_, SqliteClientError, _, _>( named_params![":account_uuid": account.0], |row| { - NonNegativeAmount::from_nonnegative_i64(row.get::<_, i64>(0)?).map_err( - |_| { - SqliteClientError::CorruptedData(format!( - "Negative received note value: {}", - n.value() - )) - }, - ) + Zatoshis::from_nonnegative_i64(row.get::<_, i64>(0)?).map_err(|_| { + SqliteClientError::CorruptedData(format!( + "Negative received note value: {}", + n.value() + )) + }) }, )? .collect::, _>>()?; @@ -418,7 +415,7 @@ pub(crate) fn spendable_notes_meta( Ok(Some(PoolMeta::new( note_count, - total_value.unwrap_or(NonNegativeAmount::ZERO), + total_value.unwrap_or(Zatoshis::ZERO), ))) } else { Ok(None) diff --git a/zcash_client_sqlite/src/wallet/init.rs b/zcash_client_sqlite/src/wallet/init.rs index 3b1dacf8f9..80947101b7 100644 --- a/zcash_client_sqlite/src/wallet/init.rs +++ b/zcash_client_sqlite/src/wallet/init.rs @@ -10,11 +10,9 @@ use secrecy::SecretVec; use shardtree::error::ShardTreeError; use uuid::Uuid; -use zcash_client_backend::{ - data_api::{SeedRelevance, WalletRead}, - keys::AddressGenerationError, -}; -use zcash_primitives::{consensus, transaction::components::amount::BalanceError}; +use zcash_client_backend::data_api::{SeedRelevance, WalletRead}; +use zcash_keys::keys::AddressGenerationError; +use zcash_protocol::{consensus, value::BalanceError}; use self::migrations::verify_network_compatibility; @@ -279,7 +277,7 @@ fn sqlite_client_error_to_wallet_migration_error(e: SqliteClientError) -> Wallet /// # use std::error::Error; /// # use secrecy::SecretVec; /// # use tempfile::NamedTempFile; -/// use zcash_primitives::consensus::Network; +/// use zcash_protocol::consensus::Network; /// use zcash_client_sqlite::{ /// WalletDb, /// wallet::init::{WalletMigrationError, init_wallet_db}, @@ -440,19 +438,16 @@ mod tests { use tempfile::NamedTempFile; - use zcash_client_backend::{ + use ::sapling::zip32::ExtendedFullViewingKey; + use zcash_client_backend::data_api::testing::TestBuilder; + use zcash_keys::{ address::Address, - data_api::testing::TestBuilder, encoding::{encode_extended_full_viewing_key, encode_payment_address}, keys::{sapling, UnifiedAddressRequest, UnifiedFullViewingKey, UnifiedSpendingKey}, }; - - use ::sapling::zip32::ExtendedFullViewingKey; - use zcash_primitives::{ - consensus::{self, BlockHeight, BranchId, Network, NetworkConstants}, - transaction::{TransactionData, TxVersion}, - zip32::AccountId, - }; + use zcash_primitives::transaction::{TransactionData, TxVersion}; + use zcash_protocol::consensus::{self, BlockHeight, BranchId, Network, NetworkConstants}; + use zip32::AccountId; use crate::{testing::db::TestDbFactory, wallet::db, WalletDb, UA_TRANSPARENT}; @@ -464,7 +459,7 @@ mod tests { crate::wallet::{self, pool_code, PoolType}, zcash_address::test_vectors, zcash_client_backend::data_api::WalletWrite, - zcash_primitives::zip32::DiversifierIndex, + zip32::DiversifierIndex, }; pub(crate) fn describe_tables(conn: &Connection) -> Result, rusqlite::Error> { diff --git a/zcash_client_sqlite/src/wallet/init/migrations/add_account_birthdays.rs b/zcash_client_sqlite/src/wallet/init/migrations/add_account_birthdays.rs index 89b08448a9..a094e8ff3a 100644 --- a/zcash_client_sqlite/src/wallet/init/migrations/add_account_birthdays.rs +++ b/zcash_client_sqlite/src/wallet/init/migrations/add_account_birthdays.rs @@ -4,7 +4,7 @@ use std::collections::HashSet; use schemerz_rusqlite::RusqliteMigration; use uuid::Uuid; -use zcash_primitives::consensus::{self, NetworkUpgrade}; +use zcash_protocol::consensus::{self, NetworkUpgrade}; use crate::wallet::init::WalletMigrationError; diff --git a/zcash_client_sqlite/src/wallet/init/migrations/add_transaction_views.rs b/zcash_client_sqlite/src/wallet/init/migrations/add_transaction_views.rs index 99c8681575..5b092e9bc3 100644 --- a/zcash_client_sqlite/src/wallet/init/migrations/add_transaction_views.rs +++ b/zcash_client_sqlite/src/wallet/init/migrations/add_transaction_views.rs @@ -5,12 +5,10 @@ use rusqlite::{self, types::ToSql, OptionalExtension}; use schemerz_rusqlite::RusqliteMigration; use uuid::Uuid; -use zcash_primitives::{ +use zcash_primitives::transaction::Transaction; +use zcash_protocol::{ consensus::BranchId, - transaction::{ - components::amount::{Amount, BalanceError}, - Transaction, - }, + value::{BalanceError, ZatBalance}, }; use super::{add_utxo_account, sent_notes_to_internal}; @@ -105,7 +103,7 @@ impl RusqliteMigration for Migration { op_amount.map_or_else( || Err(FeeError::UtxoNotFound), |i| { - Amount::from_i64(i).map_err(|_| { + ZatBalance::from_i64(i).map_err(|_| { FeeError::CorruptedData(format!( "UTXO amount out of range in outpoint {:?}", op @@ -275,8 +273,9 @@ mod tests { use rusqlite::{self, params}; use tempfile::NamedTempFile; - use zcash_client_backend::keys::UnifiedSpendingKey; - use zcash_primitives::{consensus::Network, zip32::AccountId}; + use zcash_keys::keys::UnifiedSpendingKey; + use zcash_protocol::consensus::Network; + use zip32::AccountId; use crate::{ wallet::init::{init_wallet_db_internal, migrations::addresses_table}, @@ -286,17 +285,16 @@ mod tests { #[cfg(feature = "transparent-inputs")] use { crate::wallet::init::migrations::{ufvk_support, utxos_table}, - zcash_client_backend::encoding::AddressCodec, - zcash_primitives::{ + ::transparent::{ + address::Script, + bundle::{self as transparent, Authorized, OutPoint, TxIn, TxOut}, + keys::IncomingViewingKey, + }, + zcash_keys::encoding::AddressCodec, + zcash_primitives::transaction::{TransactionData, TxVersion}, + zcash_protocol::{ consensus::{BlockHeight, BranchId}, - legacy::{keys::IncomingViewingKey, Script}, - transaction::{ - components::{ - transparent::{self, Authorized, OutPoint}, - Amount, TxIn, TxOut, - }, - TransactionData, TxVersion, - }, + value::ZatBalance, }, }; @@ -394,10 +392,9 @@ mod tests { #[test] #[cfg(feature = "transparent-inputs")] fn migrate_from_wm2() { - use zcash_client_backend::keys::UnifiedAddressRequest; - use zcash_primitives::{ - legacy::keys::NonHardenedChildIndex, transaction::components::amount::NonNegativeAmount, - }; + use ::transparent::keys::NonHardenedChildIndex; + use zcash_keys::keys::UnifiedAddressRequest; + use zcash_protocol::value::Zatoshis; use crate::UA_TRANSPARENT; @@ -425,7 +422,7 @@ mod tests { sequence: 0, }], vout: vec![TxOut { - value: NonNegativeAmount::const_from_u64(1100000000), + value: Zatoshis::const_from_u64(1100000000), script_pubkey: Script(vec![]), }], authorization: Authorized, @@ -486,10 +483,10 @@ mod tests { let fee = db_data .conn .query_row("SELECT fee FROM transactions WHERE id_tx = 0", [], |row| { - Ok(Amount::from_i64(row.get(0)?).unwrap()) + Ok(ZatBalance::from_i64(row.get(0)?).unwrap()) }) .unwrap(); - assert_eq!(fee, Amount::from_i64(300000000).unwrap()); + assert_eq!(fee, ZatBalance::from_i64(300000000).unwrap()); } } diff --git a/zcash_client_sqlite/src/wallet/init/migrations/add_utxo_account.rs b/zcash_client_sqlite/src/wallet/init/migrations/add_utxo_account.rs index d3c62b7d3f..6c737247d7 100644 --- a/zcash_client_sqlite/src/wallet/init/migrations/add_utxo_account.rs +++ b/zcash_client_sqlite/src/wallet/init/migrations/add_utxo_account.rs @@ -3,7 +3,7 @@ use schemerz_rusqlite::RusqliteMigration; use std::collections::HashSet; use uuid::Uuid; -use zcash_primitives::consensus; +use zcash_protocol::consensus; use super::{addresses_table, utxos_table}; use crate::wallet::init::WalletMigrationError; @@ -11,16 +11,14 @@ use crate::wallet::init::WalletMigrationError; #[cfg(feature = "transparent-inputs")] use { crate::error::SqliteClientError, - rusqlite::{named_params, OptionalExtension}, - std::collections::HashMap, - zcash_client_backend::{ - encoding::AddressCodec, keys::UnifiedFullViewingKey, wallet::TransparentAddressMetadata, - }, - zcash_keys::address::Address, - zcash_primitives::legacy::{ + ::transparent::{ + address::TransparentAddress, keys::{IncomingViewingKey, NonHardenedChildIndex}, - TransparentAddress, }, + rusqlite::{named_params, OptionalExtension}, + std::collections::HashMap, + zcash_client_backend::wallet::TransparentAddressMetadata, + zcash_keys::{address::Address, encoding::AddressCodec, keys::UnifiedFullViewingKey}, zip32::{AccountId, DiversifierIndex, Scope}, }; diff --git a/zcash_client_sqlite/src/wallet/init/migrations/addresses_table.rs b/zcash_client_sqlite/src/wallet/init/migrations/addresses_table.rs index 25e0cf5c63..a1edabde5e 100644 --- a/zcash_client_sqlite/src/wallet/init/migrations/addresses_table.rs +++ b/zcash_client_sqlite/src/wallet/init/migrations/addresses_table.rs @@ -3,15 +3,15 @@ use std::collections::HashSet; use rusqlite::{named_params, Transaction}; use schemerz_rusqlite::RusqliteMigration; use uuid::Uuid; -use zcash_client_backend::{address::Address, keys::UnifiedFullViewingKey}; +use zcash_keys::{address::Address, keys::UnifiedFullViewingKey}; use zcash_keys::{address::UnifiedAddress, encoding::AddressCodec, keys::UnifiedAddressRequest}; -use zcash_primitives::consensus; +use zcash_protocol::consensus; use zip32::{AccountId, DiversifierIndex}; use crate::{wallet::init::WalletMigrationError, UA_TRANSPARENT}; #[cfg(feature = "transparent-inputs")] -use zcash_primitives::legacy::keys::IncomingViewingKey; +use ::transparent::keys::IncomingViewingKey; use super::ufvk_support; diff --git a/zcash_client_sqlite/src/wallet/init/migrations/ensure_orchard_ua_receiver.rs b/zcash_client_sqlite/src/wallet/init/migrations/ensure_orchard_ua_receiver.rs index 982f8c67e2..66d6a5201c 100644 --- a/zcash_client_sqlite/src/wallet/init/migrations/ensure_orchard_ua_receiver.rs +++ b/zcash_client_sqlite/src/wallet/init/migrations/ensure_orchard_ua_receiver.rs @@ -5,10 +5,8 @@ use rusqlite::named_params; use schemerz_rusqlite::RusqliteMigration; use uuid::Uuid; -use zcash_client_backend::keys::{ - UnifiedAddressRequest, UnifiedFullViewingKey, UnifiedIncomingViewingKey, -}; -use zcash_primitives::consensus; +use zcash_keys::keys::{UnifiedAddressRequest, UnifiedFullViewingKey, UnifiedIncomingViewingKey}; +use zcash_protocol::consensus; use super::orchard_received_notes; use crate::{wallet::init::WalletMigrationError, UA_ORCHARD, UA_TRANSPARENT}; @@ -92,9 +90,9 @@ mod tests { use secrecy::SecretVec; use tempfile::NamedTempFile; - use zcash_client_backend::keys::{UnifiedAddressRequest, UnifiedSpendingKey}; use zcash_keys::address::Address; - use zcash_primitives::consensus::Network; + use zcash_keys::keys::{UnifiedAddressRequest, UnifiedSpendingKey}; + use zcash_protocol::consensus::Network; use crate::{ wallet::init::{init_wallet_db, init_wallet_db_internal, migrations::addresses_table}, diff --git a/zcash_client_sqlite/src/wallet/init/migrations/ephemeral_addresses.rs b/zcash_client_sqlite/src/wallet/init/migrations/ephemeral_addresses.rs index 196c922ec3..802be4a7f9 100644 --- a/zcash_client_sqlite/src/wallet/init/migrations/ephemeral_addresses.rs +++ b/zcash_client_sqlite/src/wallet/init/migrations/ephemeral_addresses.rs @@ -87,31 +87,28 @@ mod tests { #[cfg(feature = "transparent-inputs")] use { + crate::{ + error::SqliteClientError, + wallet::{ + self, account_kind_code, init::init_wallet_db_internal, transparent::ephemeral, + }, + AccountRef, WalletDb, + }, + ::transparent::keys::NonHardenedChildIndex, rusqlite::{named_params, Connection}, secrecy::{ExposeSecret, Secret, SecretVec}, tempfile::NamedTempFile, + zcash_client_backend::data_api::GAP_LIMIT, zcash_client_backend::{ data_api::{AccountBirthday, AccountSource}, wallet::TransparentAddressMetadata, }, zcash_keys::keys::UnifiedSpendingKey, - zcash_primitives::{block::BlockHash, legacy::keys::NonHardenedChildIndex}, + zcash_primitives::block::BlockHash, zcash_protocol::consensus::Network, zip32::{fingerprint::SeedFingerprint, AccountId as Zip32AccountId}, }; - #[cfg(feature = "transparent-inputs")] - use { - crate::{ - error::SqliteClientError, - wallet::{ - self, account_kind_code, init::init_wallet_db_internal, transparent::ephemeral, - }, - AccountRef, WalletDb, - }, - zcash_client_backend::data_api::GAP_LIMIT, - }; - /// This is a minimized copy of [`wallet::create_account`] as of the time of the /// creation of this migration. #[cfg(feature = "transparent-inputs")] diff --git a/zcash_client_sqlite/src/wallet/init/migrations/fix_bad_change_flagging.rs b/zcash_client_sqlite/src/wallet/init/migrations/fix_bad_change_flagging.rs index 0923b16307..056070fe09 100644 --- a/zcash_client_sqlite/src/wallet/init/migrations/fix_bad_change_flagging.rs +++ b/zcash_client_sqlite/src/wallet/init/migrations/fix_bad_change_flagging.rs @@ -78,6 +78,7 @@ mod tests { testing::{db::TestDbFactory, BlockCache}, wallet::init::init_wallet_db, }, + ::transparent::bundle::{OutPoint, TxOut}, zcash_client_backend::{ data_api::{ testing::{ @@ -89,10 +90,7 @@ mod tests { fees::{standard, DustOutputPolicy, StandardFeeRule}, wallet::WalletTransparentOutput, }, - zcash_primitives::{ - block::BlockHash, - transaction::components::{OutPoint, TxOut}, - }, + zcash_primitives::block::BlockHash, zcash_protocol::value::Zatoshis, }; diff --git a/zcash_client_sqlite/src/wallet/init/migrations/full_account_ids.rs b/zcash_client_sqlite/src/wallet/init/migrations/full_account_ids.rs index e8df8b216f..9d2abc5662 100644 --- a/zcash_client_sqlite/src/wallet/init/migrations/full_account_ids.rs +++ b/zcash_client_sqlite/src/wallet/init/migrations/full_account_ids.rs @@ -1,21 +1,19 @@ use std::{collections::HashSet, rc::Rc}; -use crate::wallet::{account_kind_code, init::WalletMigrationError}; use rusqlite::{named_params, OptionalExtension, Transaction}; use schemerz_rusqlite::RusqliteMigration; use secrecy::{ExposeSecret, SecretVec}; use uuid::Uuid; -use zcash_client_backend::{ - data_api::{AccountPurpose, AccountSource, Zip32Derivation}, - keys::UnifiedSpendingKey, -}; -use zcash_keys::keys::UnifiedFullViewingKey; -use zcash_primitives::consensus; + +use zcash_client_backend::data_api::{AccountPurpose, AccountSource, Zip32Derivation}; +use zcash_keys::keys::{UnifiedFullViewingKey, UnifiedSpendingKey}; +use zcash_protocol::consensus; use zip32::fingerprint::SeedFingerprint; use super::{ add_account_birthdays, receiving_key_scopes, v_transactions_note_uniqueness, wallet_summaries, }; +use crate::wallet::{account_kind_code, init::WalletMigrationError}; /// The migration that switched from presumed seed-derived account IDs to supporting /// HD accounts and all sorts of imported keys. diff --git a/zcash_client_sqlite/src/wallet/init/migrations/orchard_received_notes.rs b/zcash_client_sqlite/src/wallet/init/migrations/orchard_received_notes.rs index d3be54599d..2a2acd7467 100644 --- a/zcash_client_sqlite/src/wallet/init/migrations/orchard_received_notes.rs +++ b/zcash_client_sqlite/src/wallet/init/migrations/orchard_received_notes.rs @@ -5,7 +5,8 @@ use std::collections::HashSet; use schemerz_rusqlite::RusqliteMigration; use uuid::Uuid; -use zcash_client_backend::PoolType; + +use zcash_protocol::PoolType; use super::full_account_ids; use crate::wallet::{init::WalletMigrationError, pool_code}; diff --git a/zcash_client_sqlite/src/wallet/init/migrations/received_notes_nullable_nf.rs b/zcash_client_sqlite/src/wallet/init/migrations/received_notes_nullable_nf.rs index 16d505f25f..f05bb57f4c 100644 --- a/zcash_client_sqlite/src/wallet/init/migrations/received_notes_nullable_nf.rs +++ b/zcash_client_sqlite/src/wallet/init/migrations/received_notes_nullable_nf.rs @@ -226,8 +226,9 @@ mod tests { use rusqlite::{self, params}; use tempfile::NamedTempFile; - use zcash_client_backend::keys::UnifiedSpendingKey; - use zcash_primitives::{consensus::Network, zip32::AccountId}; + use zcash_keys::keys::UnifiedSpendingKey; + use zcash_protocol::consensus::Network; + use zip32::AccountId; use crate::{ wallet::init::{init_wallet_db_internal, migrations::v_transactions_net}, diff --git a/zcash_client_sqlite/src/wallet/init/migrations/receiving_key_scopes.rs b/zcash_client_sqlite/src/wallet/init/migrations/receiving_key_scopes.rs index 7822a076ca..4269a0813f 100644 --- a/zcash_client_sqlite/src/wallet/init/migrations/receiving_key_scopes.rs +++ b/zcash_client_sqlite/src/wallet/init/migrations/receiving_key_scopes.rs @@ -15,15 +15,14 @@ use sapling::{ zip32::DiversifiableFullViewingKey, Diversifier, Node, Rseed, }; -use zcash_client_backend::{data_api::SAPLING_SHARD_HEIGHT, keys::UnifiedFullViewingKey}; -use zcash_primitives::{ +use zcash_client_backend::data_api::SAPLING_SHARD_HEIGHT; +use zcash_keys::keys::UnifiedFullViewingKey; +use zcash_primitives::transaction::{components::sapling::zip212_enforcement, Transaction}; +use zcash_protocol::{ consensus::{self, BlockHeight, BranchId}, - transaction::{ - components::{amount::NonNegativeAmount, sapling::zip212_enforcement}, - Transaction, - }, - zip32::Scope, + value::Zatoshis, }; +use zip32::Scope; use crate::{ wallet::{ @@ -218,12 +217,11 @@ impl RusqliteMigration for Migration

{ })?) }; - let note_value = - NonNegativeAmount::from_nonnegative_i64(row.get(7)?).map_err(|_e| { - WalletMigrationError::CorruptedData( - "Note values must be nonnegative".to_string(), - ) - })?; + let note_value = Zatoshis::from_nonnegative_i64(row.get(7)?).map_err(|_e| { + WalletMigrationError::CorruptedData( + "Note values must be nonnegative".to_string(), + ) + })?; let rseed = { let rcm_bytes: [u8; 32] = @@ -290,6 +288,12 @@ mod tests { use rand_core::OsRng; use rusqlite::{named_params, params, Connection, OptionalExtension}; use tempfile::NamedTempFile; + + use ::transparent::{ + builder::TransparentSigningSet, + bundle as transparent, + keys::{IncomingViewingKey, NonHardenedChildIndex}, + }; use zcash_client_backend::{ data_api::{BlockMetadata, WalletCommitmentTrees, SAPLING_SHARD_HEIGHT}, decrypt_transaction, @@ -301,21 +305,19 @@ mod tests { use zcash_keys::keys::{UnifiedFullViewingKey, UnifiedSpendingKey}; use zcash_primitives::{ block::BlockHash, - consensus::{BlockHeight, Network, NetworkUpgrade, Parameters}, - legacy::keys::{IncomingViewingKey, NonHardenedChildIndex}, - memo::MemoBytes, transaction::{ builder::{BuildConfig, BuildResult, Builder}, - components::{ - amount::NonNegativeAmount, - transparent::{self, builder::TransparentSigningSet}, - }, fees::fixed, Transaction, }, - zip32::{self, Scope}, }; use zcash_proofs::prover::LocalTxProver; + use zcash_protocol::{ + consensus::{BlockHeight, Network, NetworkUpgrade, Parameters}, + memo::MemoBytes, + value::Zatoshis, + }; + use zip32::{self, Scope}; use crate::{ error::SqliteClientError, @@ -377,7 +379,7 @@ mod tests { ), transparent::OutPoint::fake(), transparent::TxOut { - value: NonNegativeAmount::const_from_u64(EXTERNAL_VALUE + INTERNAL_VALUE), + value: Zatoshis::const_from_u64(EXTERNAL_VALUE + INTERNAL_VALUE), script_pubkey: usk0 .transparent() .to_account_pubkey() @@ -393,7 +395,7 @@ mod tests { .add_sapling_output::( Some(ovk), external_addr, - NonNegativeAmount::const_from_u64(EXTERNAL_VALUE), + Zatoshis::const_from_u64(EXTERNAL_VALUE), MemoBytes::empty(), ) .unwrap(); @@ -401,7 +403,7 @@ mod tests { .add_sapling_output::( Some(ovk), internal_addr, - NonNegativeAmount::const_from_u64(INTERNAL_VALUE), + Zatoshis::const_from_u64(INTERNAL_VALUE), MemoBytes::empty(), ) .unwrap(); @@ -415,7 +417,7 @@ mod tests { &prover, &prover, #[allow(deprecated)] - &fixed::FeeRule::non_standard(NonNegativeAmount::ZERO), + &fixed::FeeRule::non_standard(Zatoshis::ZERO), ) .unwrap(); @@ -488,7 +490,7 @@ mod tests { fn put_tx_data( conn: &rusqlite::Connection, tx: &Transaction, - fee: Option, + fee: Option, created_at: Option, ) -> Result { let mut stmt_upsert_tx_data = conn.prepare_cached( diff --git a/zcash_client_sqlite/src/wallet/init/migrations/sapling_memo_consistency.rs b/zcash_client_sqlite/src/wallet/init/migrations/sapling_memo_consistency.rs index 4e81b5fc6c..2413eceb17 100644 --- a/zcash_client_sqlite/src/wallet/init/migrations/sapling_memo_consistency.rs +++ b/zcash_client_sqlite/src/wallet/init/migrations/sapling_memo_consistency.rs @@ -7,8 +7,11 @@ use std::collections::{BTreeMap, HashMap, HashSet}; use rusqlite::named_params; use schemerz_rusqlite::RusqliteMigration; use uuid::Uuid; -use zcash_client_backend::{decrypt_transaction, keys::UnifiedFullViewingKey}; -use zcash_primitives::{consensus, transaction::TxId, zip32::AccountId}; + +use zcash_client_backend::decrypt_transaction; +use zcash_keys::keys::UnifiedFullViewingKey; +use zcash_protocol::{consensus, TxId}; +use zip32::AccountId; use crate::{ error::SqliteClientError, diff --git a/zcash_client_sqlite/src/wallet/init/migrations/shardtree_support.rs b/zcash_client_sqlite/src/wallet/init/migrations/shardtree_support.rs index 7eaec4f210..88d8ba2f89 100644 --- a/zcash_client_sqlite/src/wallet/init/migrations/shardtree_support.rs +++ b/zcash_client_sqlite/src/wallet/init/migrations/shardtree_support.rs @@ -15,10 +15,8 @@ use zcash_client_backend::data_api::{ scanning::{ScanPriority, ScanRange}, SAPLING_SHARD_HEIGHT, }; -use zcash_primitives::{ - consensus::{self, BlockHeight, NetworkUpgrade}, - merkle_tree::{read_commitment_tree, read_incremental_witness}, -}; +use zcash_primitives::merkle_tree::{read_commitment_tree, read_incremental_witness}; +use zcash_protocol::consensus::{self, BlockHeight, NetworkUpgrade}; use crate::{ wallet::{ diff --git a/zcash_client_sqlite/src/wallet/init/migrations/tx_retrieval_queue.rs b/zcash_client_sqlite/src/wallet/init/migrations/tx_retrieval_queue.rs index 9b6eb5ce55..1240388a58 100644 --- a/zcash_client_sqlite/src/wallet/init/migrations/tx_retrieval_queue.rs +++ b/zcash_client_sqlite/src/wallet/init/migrations/tx_retrieval_queue.rs @@ -222,10 +222,12 @@ mod tests { use rusqlite::named_params; use secrecy::Secret; use tempfile::NamedTempFile; - use zcash_primitives::{ - legacy::{Script, TransparentAddress}, - transaction::{components::transparent, Authorized, TransactionData, TxVersion}, + + use ::transparent::{ + address::{Script, TransparentAddress}, + bundle::{OutPoint, TxIn, TxOut}, }; + use zcash_primitives::transaction::{Authorized, TransactionData, TxVersion}; use zcash_protocol::{ consensus::{BranchId, Network}, value::Zatoshis, @@ -278,17 +280,17 @@ mod tests { BranchId::Nu5, 0, 12345678.into(), - Some(transparent::Bundle { - vin: vec![transparent::TxIn { - prevout: transparent::OutPoint::fake(), + Some(transparent::bundle::Bundle { + vin: vec![TxIn { + prevout: OutPoint::fake(), script_sig: Script(vec![]), sequence: 0, }], - vout: vec![transparent::TxOut { + vout: vec![TxOut { value: Zatoshis::const_from_u64(10_000), script_pubkey: TransparentAddress::PublicKeyHash([7; 20]).script(), }], - authorization: transparent::Authorized, + authorization: transparent::bundle::Authorized, }), None, None, diff --git a/zcash_client_sqlite/src/wallet/init/migrations/ufvk_support.rs b/zcash_client_sqlite/src/wallet/init/migrations/ufvk_support.rs index 2881c9410c..895f1b08bd 100644 --- a/zcash_client_sqlite/src/wallet/init/migrations/ufvk_support.rs +++ b/zcash_client_sqlite/src/wallet/init/migrations/ufvk_support.rs @@ -6,15 +6,18 @@ use schemerz_rusqlite::RusqliteMigration; use secrecy::{ExposeSecret, SecretVec}; use uuid::Uuid; -use zcash_client_backend::{address::Address, keys::UnifiedSpendingKey, PoolType}; -use zcash_keys::keys::UnifiedAddressRequest; -use zcash_primitives::{consensus, zip32::AccountId}; +use zcash_keys::{ + address::Address, + keys::{UnifiedAddressRequest, UnifiedSpendingKey}, +}; +use zcash_protocol::{consensus, PoolType}; +use zip32::AccountId; #[cfg(feature = "transparent-inputs")] -use zcash_primitives::legacy::keys::IncomingViewingKey; +use ::transparent::keys::IncomingViewingKey; #[cfg(feature = "transparent-inputs")] -use zcash_client_backend::encoding::AddressCodec; +use zcash_keys::encoding::AddressCodec; use crate::{ wallet::{ diff --git a/zcash_client_sqlite/src/wallet/init/migrations/v_sapling_shard_unscanned_ranges.rs b/zcash_client_sqlite/src/wallet/init/migrations/v_sapling_shard_unscanned_ranges.rs index 9e64f65d1c..c4657aac86 100644 --- a/zcash_client_sqlite/src/wallet/init/migrations/v_sapling_shard_unscanned_ranges.rs +++ b/zcash_client_sqlite/src/wallet/init/migrations/v_sapling_shard_unscanned_ranges.rs @@ -5,8 +5,9 @@ use std::collections::HashSet; use schemerz_rusqlite::RusqliteMigration; use uuid::Uuid; + use zcash_client_backend::data_api::{scanning::ScanPriority, SAPLING_SHARD_HEIGHT}; -use zcash_primitives::consensus::{self, NetworkUpgrade}; +use zcash_protocol::consensus::{self, NetworkUpgrade}; use crate::wallet::{init::WalletMigrationError, scanning::priority_code}; diff --git a/zcash_client_sqlite/src/wallet/init/migrations/v_transactions_net.rs b/zcash_client_sqlite/src/wallet/init/migrations/v_transactions_net.rs index c364523487..f0670ac22b 100644 --- a/zcash_client_sqlite/src/wallet/init/migrations/v_transactions_net.rs +++ b/zcash_client_sqlite/src/wallet/init/migrations/v_transactions_net.rs @@ -5,7 +5,8 @@ use std::collections::HashSet; use rusqlite::named_params; use schemerz_rusqlite::RusqliteMigration; use uuid::Uuid; -use zcash_client_backend::PoolType; + +use zcash_protocol::PoolType; use super::add_transaction_views; use crate::wallet::{init::WalletMigrationError, pool_code}; @@ -206,8 +207,9 @@ mod tests { use rusqlite::{self, params}; use tempfile::NamedTempFile; - use zcash_client_backend::keys::UnifiedSpendingKey; - use zcash_primitives::{consensus::Network, zip32::AccountId}; + use zcash_keys::keys::UnifiedSpendingKey; + use zcash_protocol::consensus::Network; + use zip32::AccountId; use crate::{ wallet::init::{init_wallet_db_internal, migrations::add_transaction_views}, diff --git a/zcash_client_sqlite/src/wallet/init/migrations/v_transactions_note_uniqueness.rs b/zcash_client_sqlite/src/wallet/init/migrations/v_transactions_note_uniqueness.rs index 6149ecf025..d5770e5124 100644 --- a/zcash_client_sqlite/src/wallet/init/migrations/v_transactions_note_uniqueness.rs +++ b/zcash_client_sqlite/src/wallet/init/migrations/v_transactions_note_uniqueness.rs @@ -163,8 +163,9 @@ mod tests { use rusqlite::{self, params}; use tempfile::NamedTempFile; - use zcash_client_backend::keys::UnifiedSpendingKey; - use zcash_primitives::{consensus::Network, zip32::AccountId}; + use zcash_keys::keys::UnifiedSpendingKey; + use zcash_protocol::consensus::Network; + use zip32::AccountId; use crate::{ wallet::init::{init_wallet_db_internal, migrations::v_transactions_net}, diff --git a/zcash_client_sqlite/src/wallet/orchard.rs b/zcash_client_sqlite/src/wallet/orchard.rs index e2c6015f36..41f9572020 100644 --- a/zcash_client_sqlite/src/wallet/orchard.rs +++ b/zcash_client_sqlite/src/wallet/orchard.rs @@ -10,7 +10,7 @@ use rusqlite::{named_params, types::Value, Connection, Row, Transaction}; use zcash_client_backend::{ data_api::NullifierQuery, wallet::{ReceivedNote, WalletOrchardOutput}, - DecryptedOutput, ShieldedProtocol, TransferType, + DecryptedOutput, TransferType, }; use zcash_keys::keys::UnifiedFullViewingKey; use zcash_primitives::transaction::TxId; @@ -18,6 +18,7 @@ use zcash_protocol::{ consensus::{self, BlockHeight}, memo::MemoBytes, value::Zatoshis, + ShieldedProtocol, }; use zip32::Scope; diff --git a/zcash_client_sqlite/src/wallet/sapling.rs b/zcash_client_sqlite/src/wallet/sapling.rs index 91b5f6e8c0..490112889a 100644 --- a/zcash_client_sqlite/src/wallet/sapling.rs +++ b/zcash_client_sqlite/src/wallet/sapling.rs @@ -10,13 +10,15 @@ use sapling::{self, Diversifier, Nullifier, Rseed}; use zcash_client_backend::{ data_api::NullifierQuery, wallet::{ReceivedNote, WalletSaplingOutput}, - DecryptedOutput, ShieldedProtocol, TransferType, + DecryptedOutput, TransferType, }; use zcash_keys::keys::UnifiedFullViewingKey; -use zcash_primitives::transaction::{components::amount::NonNegativeAmount, TxId}; +use zcash_primitives::transaction::TxId; use zcash_protocol::{ consensus::{self, BlockHeight}, memo::MemoBytes, + value::Zatoshis, + ShieldedProtocol, }; use zip32::Scope; @@ -219,7 +221,7 @@ pub(crate) fn select_spendable_sapling_notes( conn: &Connection, params: &P, account: AccountUuid, - target_value: NonNegativeAmount, + target_value: Zatoshis, anchor_height: BlockHeight, exclude: &[ReceivedNoteId], ) -> Result>, SqliteClientError> { diff --git a/zcash_client_sqlite/src/wallet/scanning.rs b/zcash_client_sqlite/src/wallet/scanning.rs index 041f7482d6..9c69751211 100644 --- a/zcash_client_sqlite/src/wallet/scanning.rs +++ b/zcash_client_sqlite/src/wallet/scanning.rs @@ -6,14 +6,14 @@ use std::ops::Range; use std::rc::Rc; use tracing::{debug, trace}; -use zcash_client_backend::{ - data_api::{ - scanning::{spanning_tree::SpanningTree, ScanPriority, ScanRange}, - SAPLING_SHARD_HEIGHT, - }, +use zcash_client_backend::data_api::{ + scanning::{spanning_tree::SpanningTree, ScanPriority, ScanRange}, + SAPLING_SHARD_HEIGHT, +}; +use zcash_protocol::{ + consensus::{self, BlockHeight, NetworkUpgrade}, ShieldedProtocol, }; -use zcash_primitives::consensus::{self, BlockHeight, NetworkUpgrade}; use crate::{ error::SqliteClientError, @@ -27,7 +27,7 @@ use super::wallet_birthday; use {crate::ORCHARD_TABLES_PREFIX, zcash_client_backend::data_api::ORCHARD_SHARD_HEIGHT}; #[cfg(not(feature = "orchard"))] -use zcash_client_backend::PoolType; +use zcash_protocol::PoolType; pub(crate) fn priority_code(priority: &ScanPriority) -> i64 { use ScanPriority::*; @@ -572,12 +572,12 @@ pub(crate) mod tests { }, AccountBirthday, Ratio, WalletRead, WalletWrite, }; - use zcash_primitives::{ - block::BlockHash, + use zcash_primitives::block::BlockHash; + use zcash_protocol::{ consensus::{BlockHeight, NetworkUpgrade, Parameters}, - transaction::components::amount::NonNegativeAmount, + local_consensus::LocalNetwork, + value::Zatoshis, }; - use zcash_protocol::local_consensus::LocalNetwork; use crate::{ error::SqliteClientError, @@ -602,7 +602,7 @@ pub(crate) mod tests { fees::{standard, DustOutputPolicy, StandardFeeRule}, wallet::OvkPolicy, }, - zcash_primitives::memo::Memo, + zcash_protocol::memo::Memo, }; #[test] @@ -684,7 +684,7 @@ pub(crate) mod tests { let sapling_activation_height = st.sapling_activation_height(); let dfvk = T::test_account_fvk(&st); - let value = NonNegativeAmount::const_from_u64(50000); + let value = Zatoshis::const_from_u64(50000); let initial_height = sapling_activation_height + initial_height_offset; st.generate_block_at( initial_height, @@ -703,7 +703,7 @@ pub(crate) mod tests { st.generate_next_block( &dfvk, AddressType::DefaultExternal, - NonNegativeAmount::const_from_u64(10000), + Zatoshis::const_from_u64(10000), ); } @@ -1131,7 +1131,7 @@ pub(crate) mod tests { &dfvk, AddressType::DefaultExternal, // 1235 notes into the second shard - NonNegativeAmount::const_from_u64(10000), + Zatoshis::const_from_u64(10000), )], frontier_tree_size + 10, frontier_tree_size + 10, @@ -1335,7 +1335,7 @@ pub(crate) mod tests { &[FakeCompactOutput::new( &dfvk, AddressType::DefaultExternal, - NonNegativeAmount::const_from_u64(10000), + Zatoshis::const_from_u64(10000), )], frontier_tree_size + 10, frontier_tree_size + 10, @@ -1638,7 +1638,7 @@ pub(crate) mod tests { ofvk.clone() }, AddressType::DefaultExternal, - NonNegativeAmount::const_from_u64(100000), + Zatoshis::const_from_u64(100000), ) }; @@ -1751,18 +1751,18 @@ pub(crate) mod tests { st.scan_cached_blocks(birthday.height() + 12, 112); // We haven't yet discovered our note, so balances should still be zero - assert_eq!(st.get_total_balance(account.id()), NonNegativeAmount::ZERO); + assert_eq!(st.get_total_balance(account.id()), Zatoshis::ZERO); // Now scan the historic range; this should discover our note, which should now be // spendable. st.scan_cached_blocks(birthday.height(), 12); assert_eq!( st.get_total_balance(account.id()), - NonNegativeAmount::const_from_u64(100000) + Zatoshis::const_from_u64(100000) ); assert_eq!( st.get_spendable_balance(account.id(), 10), - NonNegativeAmount::const_from_u64(100000) + Zatoshis::const_from_u64(100000) ); // Spend the note. @@ -1770,7 +1770,7 @@ pub(crate) mod tests { let to = OrchardPoolTester::sk_default_address(&to_extsk); let request = zip321::TransactionRequest::new(vec![zip321::Payment::without_memo( to.to_zcash_address(st.network()), - NonNegativeAmount::const_from_u64(10000), + Zatoshis::const_from_u64(10000), )]) .unwrap(); @@ -1840,26 +1840,23 @@ pub(crate) mod tests { st.scan_cached_blocks(birthday.height() + 13, 112); // We haven't yet discovered our note, so balances should still be zero - assert_eq!(st.get_total_balance(account.id()), NonNegativeAmount::ZERO); + assert_eq!(st.get_total_balance(account.id()), Zatoshis::ZERO); // Now scan the historic range; this should discover our note but not // complete the tree. The note should not be considered spendable. st.scan_cached_blocks(birthday.height(), 12); assert_eq!( st.get_total_balance(account.id()), - NonNegativeAmount::const_from_u64(100000) - ); - assert_eq!( - st.get_spendable_balance(account.id(), 10), - NonNegativeAmount::ZERO + Zatoshis::const_from_u64(100000) ); + assert_eq!(st.get_spendable_balance(account.id(), 10), Zatoshis::ZERO); // Attempting to spend the note should fail to generate a proposal let to_extsk = OrchardPoolTester::sk(&[0xf5; 32]); let to = OrchardPoolTester::sk_default_address(&to_extsk); let request = zip321::TransactionRequest::new(vec![zip321::Payment::without_memo( to.to_zcash_address(st.network()), - NonNegativeAmount::const_from_u64(10000), + Zatoshis::const_from_u64(10000), )]) .unwrap(); diff --git a/zcash_client_sqlite/src/wallet/transparent.rs b/zcash_client_sqlite/src/wallet/transparent.rs index 1270f5dfb1..13f7dfe7c5 100644 --- a/zcash_client_sqlite/src/wallet/transparent.rs +++ b/zcash_client_sqlite/src/wallet/transparent.rs @@ -3,24 +3,24 @@ use std::collections::{HashMap, HashSet}; use rusqlite::OptionalExtension; use rusqlite::{named_params, Connection, Row}; -use zcash_client_backend::data_api::TransactionDataRequest; -use zcash_primitives::transaction::builder::DEFAULT_TX_EXPIRY_DELTA; -use zip32::{DiversifierIndex, Scope}; +use ::transparent::{ + address::{Script, TransparentAddress}, + bundle::{OutPoint, TxOut}, + keys::{IncomingViewingKey, NonHardenedChildIndex}, +}; use zcash_address::unified::{Ivk, Uivk}; use zcash_client_backend::{ - data_api::AccountBalance, + data_api::{AccountBalance, TransactionDataRequest}, wallet::{TransparentAddressMetadata, WalletTransparentOutput}, }; use zcash_keys::{address::Address, encoding::AddressCodec}; -use zcash_primitives::{ - legacy::{ - keys::{IncomingViewingKey, NonHardenedChildIndex}, - Script, TransparentAddress, - }, - transaction::components::{amount::NonNegativeAmount, Amount, OutPoint, TxOut}, +use zcash_primitives::transaction::builder::DEFAULT_TX_EXPIRY_DELTA; +use zcash_protocol::{ + consensus::{self, BlockHeight}, + value::{ZatBalance, Zatoshis}, }; -use zcash_protocol::consensus::{self, BlockHeight}; +use zip32::{DiversifierIndex, Scope}; use super::{chain_tip_height, get_account_ids}; use crate::AccountUuid; @@ -132,8 +132,8 @@ pub(crate) fn uivk_legacy_transparent_address( params: &P, uivk_str: &str, ) -> Result, SqliteClientError> { + use ::transparent::keys::ExternalIvk; use zcash_address::unified::{Container as _, Encoding as _}; - use zcash_primitives::legacy::keys::ExternalIvk; let (network, uivk) = Uivk::decode(uivk_str) .map_err(|e| SqliteClientError::CorruptedData(format!("Unable to parse UIVK: {e}")))?; @@ -191,7 +191,7 @@ fn to_unspent_transparent_output(row: &Row) -> Result = row.get("received_height")?; @@ -353,7 +353,7 @@ pub(crate) fn get_transparent_balances( params: &P, account_uuid: AccountUuid, summary_height: BlockHeight, -) -> Result, SqliteClientError> { +) -> Result, SqliteClientError> { let chain_tip_height = chain_tip_height(conn)?.ok_or(SqliteClientError::ChainHeightUnknown)?; let mut stmt_address_balances = conn.prepare( @@ -395,7 +395,7 @@ pub(crate) fn get_transparent_balances( while let Some(row) = rows.next()? { let taddr_str: String = row.get(0)?; let taddr = TransparentAddress::decode(params, &taddr_str)?; - let value = NonNegativeAmount::from_nonnegative_i64(row.get(1)?)?; + let value = Zatoshis::from_nonnegative_i64(row.get(1)?)?; res.insert(taddr, value); } @@ -441,7 +441,7 @@ pub(crate) fn add_transparent_account_balances( while let Some(row) = rows.next()? { let account = AccountUuid(row.get(0)?); let raw_value = row.get(1)?; - let value = NonNegativeAmount::from_nonnegative_i64(raw_value).map_err(|_| { + let value = Zatoshis::from_nonnegative_i64(raw_value).map_err(|_| { SqliteClientError::CorruptedData(format!("Negative UTXO value {:?}", raw_value)) })?; @@ -484,7 +484,7 @@ pub(crate) fn add_transparent_account_balances( while let Some(row) = rows.next()? { let account = AccountUuid(row.get(0)?); let raw_value = row.get(1)?; - let value = NonNegativeAmount::from_nonnegative_i64(raw_value).map_err(|_| { + let value = Zatoshis::from_nonnegative_i64(raw_value).map_err(|_| { SqliteClientError::CorruptedData(format!("Negative UTXO value {:?}", raw_value)) })?; @@ -833,7 +833,7 @@ pub(crate) fn put_transparent_output( ":account_id": receiving_account_id.0, ":address": &address.encode(params), ":script": &txout.script_pubkey.0, - ":value_zat": &i64::from(Amount::from(txout.value)), + ":value_zat": &i64::from(ZatBalance::from(txout.value)), ":max_observed_unspent_height": max_observed_unspent.map(u32::from), ]; diff --git a/zcash_client_sqlite/src/wallet/transparent/ephemeral.rs b/zcash_client_sqlite/src/wallet/transparent/ephemeral.rs index 21b2f9d371..293eaa9550 100644 --- a/zcash_client_sqlite/src/wallet/transparent/ephemeral.rs +++ b/zcash_client_sqlite/src/wallet/transparent/ephemeral.rs @@ -4,16 +4,14 @@ use std::ops::Range; use rusqlite::{named_params, OptionalExtension}; +use ::transparent::{ + address::TransparentAddress, + keys::{EphemeralIvk, NonHardenedChildIndex, TransparentKeyScope}, +}; use zcash_client_backend::{data_api::GAP_LIMIT, wallet::TransparentAddressMetadata}; use zcash_keys::keys::UnifiedFullViewingKey; use zcash_keys::{encoding::AddressCodec, keys::AddressGenerationError}; -use zcash_primitives::{ - legacy::{ - keys::{EphemeralIvk, NonHardenedChildIndex, TransparentKeyScope}, - TransparentAddress, - }, - transaction::TxId, -}; +use zcash_primitives::transaction::TxId; use zcash_protocol::consensus; use crate::wallet::{self, get_account_ref}; diff --git a/zcash_primitives/benches/note_decryption.rs b/zcash_primitives/benches/note_decryption.rs index c18b7328e3..9cc1424b1c 100644 --- a/zcash_primitives/benches/note_decryption.rs +++ b/zcash_primitives/benches/note_decryption.rs @@ -14,9 +14,10 @@ use sapling::{ Diversifier, SaplingIvk, }; use zcash_note_encryption::batch; -use zcash_primitives::{ +use zcash_primitives::transaction::components::sapling::zip212_enforcement; +use zcash_protocol::{ consensus::{NetworkUpgrade::Canopy, Parameters, TEST_NETWORK}, - transaction::components::{sapling::zip212_enforcement, Amount}, + value::ZatBalance, }; #[cfg(unix)] @@ -46,7 +47,7 @@ fn bench_note_decryption(c: &mut Criterion) { .add_output(None, pa, NoteValue::from_raw(100), None) .unwrap(); let (bundle, _) = builder - .build::(&[], &mut rng) + .build::(&[], &mut rng) .unwrap() .unwrap(); bundle.shielded_outputs()[0].clone() diff --git a/zcash_primitives/src/lib.rs b/zcash_primitives/src/lib.rs index 00f338311f..9584f8254e 100644 --- a/zcash_primitives/src/lib.rs +++ b/zcash_primitives/src/lib.rs @@ -18,18 +18,17 @@ #![allow(clippy::single_component_path_imports)] pub mod block; -pub use zcash_protocol::consensus; -pub use zcash_protocol::constants; -pub use zcash_protocol::memo; +//pub use zcash_protocol::consensus; +//pub use zcash_protocol::constants; +//pub use zcash_protocol::memo; pub mod merkle_tree; -use sapling; pub mod transaction; -pub use zip32; +//pub use zip32; #[cfg(zcash_unstable = "zfuture")] pub mod extensions; -pub mod legacy { - pub use transparent::address::*; - #[cfg(feature = "transparent-inputs")] - pub use transparent::keys; -} +//pub mod legacy { +// pub use transparent::address::*; +// #[cfg(feature = "transparent-inputs")] +// pub use transparent::keys; +//} diff --git a/zcash_primitives/src/merkle_tree.rs b/zcash_primitives/src/merkle_tree.rs index 98391c91e2..74888c38da 100644 --- a/zcash_primitives/src/merkle_tree.rs +++ b/zcash_primitives/src/merkle_tree.rs @@ -10,8 +10,6 @@ use orchard::tree::MerkleHashOrchard; use std::io::{self, Read, Write}; use zcash_encoding::{Optional, Vector}; -use crate::sapling; - /// A hashable node within a Merkle tree. pub trait HashSer { /// Parses a node from the given byte source. @@ -350,7 +348,7 @@ mod tests { read_incremental_witness, write_commitment_tree, write_frontier_v1, write_incremental_witness, CommitmentTree, HashSer, }; - use crate::sapling::{self, Node}; + use ::sapling::{self, Node}; proptest! { #[test] diff --git a/zcash_primitives/src/transaction/builder.rs b/zcash_primitives/src/transaction/builder.rs index 61b323bb41..67dad9ed5b 100644 --- a/zcash_primitives/src/transaction/builder.rs +++ b/zcash_primitives/src/transaction/builder.rs @@ -1,40 +1,36 @@ //! Structs for building transactions. +use rand::{CryptoRng, RngCore}; use std::cmp::Ordering; use std::error; use std::fmt; use std::sync::mpsc::Sender; -use rand::{CryptoRng, RngCore}; -use zcash_protocol::consensus::Parameters; - -use crate::{ - consensus::{self, BlockHeight, BranchId, NetworkUpgrade}, - legacy::TransparentAddress, +use ::sapling::{ + self, + builder::SaplingMetadata, + prover::{OutputProver, SpendProver}, + Note, PaymentAddress, +}; +use ::transparent::{address::TransparentAddress, builder::TransparentBuilder, bundle::TxOut}; +use zcash_protocol::{ + consensus::{self, BlockHeight, BranchId, NetworkUpgrade, Parameters}, memo::MemoBytes, - sapling::{ - self, - builder::SaplingMetadata, - prover::{OutputProver, SpendProver}, - Note, PaymentAddress, - }, - transaction::{ - components::{ - amount::{Amount, BalanceError}, - transparent::{builder::TransparentBuilder, TxOut}, - }, - fees::{ - transparent::{InputView, OutputView}, - FeeRule, - }, - sighash::{signature_hash, SignableInput}, - txid::TxIdDigester, - Transaction, TransactionData, TxVersion, Unauthorized, + value::{BalanceError, ZatBalance, Zatoshis}, +}; + +use crate::transaction::{ + fees::{ + transparent::{InputView, OutputView}, + FeeRule, }, + sighash::{signature_hash, SignableInput}, + txid::TxIdDigester, + Transaction, TransactionData, TxVersion, Unauthorized, }; #[cfg(feature = "transparent-inputs")] -use crate::transaction::components::transparent::builder::TransparentInputInfo; +use ::transparent::builder::TransparentInputInfo; #[cfg(not(feature = "transparent-inputs"))] use std::convert::Infallible; @@ -51,9 +47,8 @@ use crate::{ }, }; -use super::components::amount::NonNegativeAmount; use super::components::sapling::zip212_enforcement; -use super::components::transparent::builder::TransparentSigningSet; +use ::transparent::builder::TransparentSigningSet; /// Since Blossom activation, the default transaction expiry delta should be 40 blocks. /// @@ -80,10 +75,10 @@ impl fmt::Display for FeeError { pub enum Error { /// Insufficient funds were provided to the transaction builder; the given /// additional amount is required in order to construct the transaction. - InsufficientFunds(Amount), + InsufficientFunds(ZatBalance), /// The transaction has inputs in excess of outputs and fees; the user must /// add a change output. - ChangeRequired(Amount), + ChangeRequired(ZatBalance), /// An error occurred in computing the fees for a transaction. Fee(FeeError), /// An overflow or underflow occurred when computing value balances @@ -484,7 +479,7 @@ impl<'a, P: consensus::Parameters, U: sapling::builder::ProverProgress> Builder< &mut self, ovk: Option, to: PaymentAddress, - value: NonNegativeAmount, + value: Zatoshis, memo: MemoBytes, ) -> Result<(), Error> { self.sapling_builder @@ -514,23 +509,25 @@ impl<'a, P: consensus::Parameters, U: sapling::builder::ProverProgress> Builder< pub fn add_transparent_output( &mut self, to: &TransparentAddress, - value: NonNegativeAmount, + value: Zatoshis, ) -> Result<(), transparent::builder::Error> { self.transparent_builder.add_output(to, value) } /// Returns the sum of the transparent, Sapling, Orchard, and TZE value balances. - fn value_balance(&self) -> Result { + fn value_balance(&self) -> Result { let value_balances = [ self.transparent_builder.value_balance()?, self.sapling_builder .as_ref() - .map_or_else(Amount::zero, |builder| builder.value_balance::()), + .map_or_else(ZatBalance::zero, |builder| { + builder.value_balance::() + }), self.orchard_builder.as_ref().map_or_else( - || Ok(Amount::zero()), + || Ok(ZatBalance::zero()), |builder| { builder - .value_balance::() + .value_balance::() .map_err(|_| BalanceError::Overflow) }, )?, @@ -548,10 +545,7 @@ impl<'a, P: consensus::Parameters, U: sapling::builder::ProverProgress> Builder< /// /// This fee is a function of the spends and outputs that have been added to the builder, /// pursuant to the specified [`FeeRule`]. - pub fn get_fee( - &self, - fee_rule: &FR, - ) -> Result> { + pub fn get_fee(&self, fee_rule: &FR) -> Result> { #[cfg(feature = "transparent-inputs")] let transparent_inputs = self.transparent_builder.inputs(); @@ -597,7 +591,7 @@ impl<'a, P: consensus::Parameters, U: sapling::builder::ProverProgress> Builder< pub fn get_fee_zfuture( &self, fee_rule: &FR, - ) -> Result> { + ) -> Result> { #[cfg(feature = "transparent-inputs")] let transparent_inputs = self.transparent_builder.inputs(); @@ -709,7 +703,7 @@ impl<'a, P: consensus::Parameters, U: sapling::builder::ProverProgress> Builder< mut rng: R, spend_prover: &SP, output_prover: &OP, - fee: NonNegativeAmount, + fee: Zatoshis, ) -> Result> { let consensus_branch_id = BranchId::for_height(&self.params, self.target_height); @@ -724,7 +718,7 @@ impl<'a, P: consensus::Parameters, U: sapling::builder::ProverProgress> Builder< let balance_after_fees = (self.value_balance()? - fee.into()).ok_or(BalanceError::Underflow)?; - match balance_after_fees.cmp(&Amount::zero()) { + match balance_after_fees.cmp(&ZatBalance::zero()) { Ordering::Less => { return Err(Error::InsufficientFunds(-balance_after_fees)); } @@ -907,7 +901,7 @@ impl<'a, P: consensus::Parameters, U: sapling::builder::ProverProgress> Builder< let balance_after_fees = (self.value_balance()? - fee.into()).ok_or(BalanceError::Underflow)?; - match balance_after_fees.cmp(&Amount::zero()) { + match balance_after_fees.cmp(&ZatBalance::zero()) { Ordering::Less => { return Err(Error::InsufficientFunds(-balance_after_fees)); } @@ -988,7 +982,7 @@ impl<'a, P: consensus::Parameters, U: sapling::builder::ProverProgress> Extensio fn add_tze_output( &mut self, extension_id: u32, - value: Amount, + value: ZatBalance, guarded_by: &G, ) -> Result<(), Self::BuildError> { self.tze_builder.add_output(extension_id, value, guarded_by) @@ -1000,15 +994,15 @@ mod testing { use rand::RngCore; use rand_core::CryptoRng; - use super::{BuildResult, Builder, Error}; - use crate::{ - consensus, - sapling::{ - self, - prover::mock::{MockOutputProver, MockSpendProver}, - }, - transaction::{components::transparent::builder::TransparentSigningSet, fees::zip317}, + use ::sapling::{ + self, + prover::mock::{MockOutputProver, MockSpendProver}, }; + use ::transparent::builder::TransparentSigningSet; + use zcash_protocol::consensus; + + use super::{BuildResult, Builder, Error}; + use crate::transaction::fees::zip317; impl<'a, P: consensus::Parameters, U: sapling::builder::ProverProgress> Builder<'a, P, U> { /// Build the transaction using mocked randomness and proving capabilities. @@ -1063,30 +1057,25 @@ mod tests { use incrementalmerkletree::{frontier::CommitmentTree, witness::IncrementalWitness}; use rand_core::OsRng; - use crate::{ + use super::{Builder, Error}; + use crate::transaction::builder::BuildConfig; + + use ::sapling::{self, zip32::ExtendedSpendingKey, Node, Rseed}; + use ::transparent::{address::TransparentAddress, builder::TransparentSigningSet}; + use zcash_protocol::{ consensus::{NetworkUpgrade, Parameters, TEST_NETWORK}, - legacy::TransparentAddress, memo::MemoBytes, - sapling::{self, zip32::ExtendedSpendingKey, Node, Rseed}, - transaction::{ - builder::BuildConfig, - components::{ - amount::{Amount, BalanceError, NonNegativeAmount}, - transparent::builder::TransparentSigningSet, - }, - }, + value::{BalanceError, ZatBalance, Zatoshis}, }; - use super::{Builder, Error}; - #[cfg(zcash_unstable = "zfuture")] #[cfg(feature = "transparent-inputs")] use super::TzeBuilder; #[cfg(feature = "transparent-inputs")] - use crate::{ - legacy::keys::{AccountPrivKey, IncomingViewingKey}, - transaction::{builder::DEFAULT_TX_EXPIRY_DELTA, OutPoint, TxOut}, + use { + crate::transaction::{builder::DEFAULT_TX_EXPIRY_DELTA, OutPoint, TxOut}, + ::transparent::keys::{AccountPrivKey, IncomingViewingKey}, zip32::AccountId, }; @@ -1095,10 +1084,9 @@ mod tests { #[test] #[cfg(feature = "transparent-inputs")] fn binding_sig_absent_if_no_shielded_spend_or_output() { - use crate::consensus::NetworkUpgrade; - use crate::legacy::keys::NonHardenedChildIndex; use crate::transaction::builder::{self, TransparentBuilder}; - use crate::transaction::components::transparent::builder::TransparentSigningSet; + use ::transparent::{builder::TransparentSigningSet, keys::NonHardenedChildIndex}; + use zcash_protocol::consensus::NetworkUpgrade; let sapling_activation_height = TEST_NETWORK .activation_height(NetworkUpgrade::Sapling) @@ -1130,7 +1118,7 @@ mod tests { .unwrap(); let pubkey = transparent_signing_set.add_key(sk); let prev_coin = TxOut { - value: NonNegativeAmount::const_from_u64(50000), + value: Zatoshis::const_from_u64(50000), script_pubkey: tsk .to_account_pubkey() .derive_external_ivk() @@ -1147,7 +1135,7 @@ mod tests { builder .add_transparent_output( &TransparentAddress::PublicKeyHash([0; 20]), - NonNegativeAmount::const_from_u64(40000), + Zatoshis::const_from_u64(40000), ) .unwrap(); @@ -1193,7 +1181,7 @@ mod tests { builder .add_transparent_output( &TransparentAddress::PublicKeyHash([0; 20]), - NonNegativeAmount::const_from_u64(35000), + Zatoshis::const_from_u64(35000), ) .unwrap(); @@ -1248,14 +1236,14 @@ mod tests { .add_sapling_output::( ovk, to, - NonNegativeAmount::const_from_u64(50000), + Zatoshis::const_from_u64(50000), MemoBytes::empty(), ) .unwrap(); assert_matches!( builder.mock_build(&TransparentSigningSet::new(), extsks, &[], OsRng), Err(Error::InsufficientFunds(expected)) if - expected == (NonNegativeAmount::const_from_u64(50000) + MINIMUM_FEE).unwrap().into() + expected == (Zatoshis::const_from_u64(50000) + MINIMUM_FEE).unwrap().into() ); } @@ -1270,13 +1258,13 @@ mod tests { builder .add_transparent_output( &TransparentAddress::PublicKeyHash([0; 20]), - NonNegativeAmount::const_from_u64(50000), + Zatoshis::const_from_u64(50000), ) .unwrap(); assert_matches!( builder.mock_build(&TransparentSigningSet::new(), extsks, &[], OsRng), Err(Error::InsufficientFunds(expected)) if expected == - (NonNegativeAmount::const_from_u64(50000) + MINIMUM_FEE).unwrap().into() + (Zatoshis::const_from_u64(50000) + MINIMUM_FEE).unwrap().into() ); } @@ -1308,19 +1296,19 @@ mod tests { .add_sapling_output::( ovk, to, - NonNegativeAmount::const_from_u64(30000), + Zatoshis::const_from_u64(30000), MemoBytes::empty(), ) .unwrap(); builder .add_transparent_output( &TransparentAddress::PublicKeyHash([0; 20]), - NonNegativeAmount::const_from_u64(15000), + Zatoshis::const_from_u64(15000), ) .unwrap(); assert_matches!( builder.mock_build(&TransparentSigningSet::new(), extsks, &[], OsRng), - Err(Error::InsufficientFunds(expected)) if expected == Amount::const_from_i64(1) + Err(Error::InsufficientFunds(expected)) if expected == ZatBalance::const_from_i64(1) ); } @@ -1359,14 +1347,14 @@ mod tests { .add_sapling_output::( ovk, to, - NonNegativeAmount::const_from_u64(30000), + Zatoshis::const_from_u64(30000), MemoBytes::empty(), ) .unwrap(); builder .add_transparent_output( &TransparentAddress::PublicKeyHash([0; 20]), - NonNegativeAmount::const_from_u64(15000), + Zatoshis::const_from_u64(15000), ) .unwrap(); let res = builder @@ -1376,7 +1364,7 @@ mod tests { res.transaction() .fee_paid(|_| Err(BalanceError::Overflow)) .unwrap(), - Amount::const_from_i64(15_000) + ZatBalance::const_from_i64(15_000) ); } } diff --git a/zcash_primitives/src/transaction/components.rs b/zcash_primitives/src/transaction/components.rs index 1665ec2e6f..d3faa4e438 100644 --- a/zcash_primitives/src/transaction/components.rs +++ b/zcash_primitives/src/transaction/components.rs @@ -1,35 +1,35 @@ //! Structs representing the components within Zcash transactions. -pub mod amount { - pub use zcash_protocol::value::{ - BalanceError, ZatBalance as Amount, Zatoshis as NonNegativeAmount, COIN, - }; - - #[cfg(any(test, feature = "test-dependencies"))] - pub mod testing { - pub use zcash_protocol::value::testing::{ - arb_positive_zat_balance as arb_positive_amount, arb_zat_balance as arb_amount, - arb_zatoshis as arb_nonnegative_amount, - }; - } -} +//pub mod amount { +// pub use zcash_protocol::value::{ +// BalanceError, ZatBalance as Amount, Zatoshis as NonNegativeAmount, COIN, +// }; +// +// #[cfg(any(test, feature = "test-dependencies"))] +// pub mod testing { +// pub use zcash_protocol::value::testing::{ +// arb_positive_zat_balance as arb_positive_amount, arb_zat_balance as arb_amount, +// arb_zatoshis as arb_nonnegative_amount, +// }; +// } +//} pub mod orchard; pub mod sapling; pub mod sprout; #[cfg(zcash_unstable = "zfuture")] pub mod tze; -pub mod transparent { - pub use transparent::builder; - pub use transparent::bundle::*; - pub use transparent::pczt; -} +//pub mod transparent { +// pub use transparent::builder; +// pub use transparent::bundle::*; +// pub use transparent::pczt; +//} pub use self::{ - amount::Amount, + // amount::Amount, sprout::JsDescription, - transparent::{OutPoint, TxIn, TxOut}, + // transparent::{OutPoint, TxIn, TxOut}, }; -pub use crate::sapling::bundle::{OutputDescription, SpendDescription}; +//pub use crate::sapling::bundle::{OutputDescription, SpendDescription}; #[cfg(zcash_unstable = "zfuture")] pub use self::tze::{TzeIn, TzeOut}; diff --git a/zcash_primitives/src/transaction/components/orchard.rs b/zcash_primitives/src/transaction/components/orchard.rs index 9f7df66b6a..70fb5b6d15 100644 --- a/zcash_primitives/src/transaction/components/orchard.rs +++ b/zcash_primitives/src/transaction/components/orchard.rs @@ -4,6 +4,7 @@ use std::io::{self, Read, Write}; use byteorder::{ReadBytesExt, WriteBytesExt}; use nonempty::NonEmpty; + use orchard::{ bundle::{Authorization, Authorized, Flags}, note::{ExtractedNoteCommitment, Nullifier, TransmittedNoteCiphertext}, @@ -12,8 +13,8 @@ use orchard::{ Action, Anchor, }; use zcash_encoding::{Array, CompactSize, Vector}; +use zcash_protocol::value::ZatBalance; -use super::Amount; use crate::transaction::Transaction; pub const FLAG_SPENDS_ENABLED: u8 = 0b0000_0001; @@ -47,7 +48,7 @@ impl MapAuth for () { /// Reads an [`orchard::Bundle`] from a v5 transaction format. pub fn read_v5_bundle( mut reader: R, -) -> io::Result>> { +) -> io::Result>> { #[allow(clippy::redundant_closure)] let actions_without_auth = Vector::read(&mut reader, |r| read_action_without_auth(r))?; if actions_without_auth.is_empty() { @@ -194,7 +195,7 @@ pub fn read_signature(mut reader: R) -> io::Result( - bundle: Option<&orchard::Bundle>, + bundle: Option<&orchard::Bundle>, mut writer: W, ) -> io::Result<()> { if let Some(bundle) = &bundle { @@ -273,17 +274,15 @@ pub mod testing { testing::{self as t_orch}, Authorized, Bundle, }; + use zcash_protocol::value::{testing::arb_zat_balance, ZatBalance}; - use crate::transaction::{ - components::amount::{testing::arb_amount, Amount}, - TxVersion, - }; + use crate::transaction::TxVersion; prop_compose! { pub fn arb_bundle(n_actions: usize)( - orchard_value_balance in arb_amount(), + orchard_value_balance in arb_zat_balance(), bundle in t_orch::arb_bundle(n_actions) - ) -> Bundle { + ) -> Bundle { // overwrite the value balance, as we can't guarantee that the // value doesn't exceed the MAX_MONEY bounds. bundle.try_map_value_balance::<_, (), _>(|_| Ok(orchard_value_balance)).unwrap() @@ -292,7 +291,7 @@ pub mod testing { pub fn arb_bundle_for_version( v: TxVersion, - ) -> impl Strategy>> { + ) -> impl Strategy>> { if v.has_orchard() { Strategy::boxed((1usize..100).prop_flat_map(|n| prop::option::of(arb_bundle(n)))) } else { diff --git a/zcash_primitives/src/transaction/components/sapling.rs b/zcash_primitives/src/transaction/components/sapling.rs index 2eb1c90108..82e1e01890 100644 --- a/zcash_primitives/src/transaction/components/sapling.rs +++ b/zcash_primitives/src/transaction/components/sapling.rs @@ -1,27 +1,26 @@ use ff::PrimeField; -use redjubjub::SpendAuth; -use sapling::note_encryption::Zip212Enforcement; -use zcash_protocol::consensus::{BlockHeight, NetworkUpgrade, Parameters, ZIP212_GRACE_PERIOD}; - use std::io::{self, Read, Write}; +use ::sapling::{ + bundle::{ + Authorization, Authorized, Bundle, GrothProofBytes, OutputDescription, OutputDescriptionV5, + SpendDescription, SpendDescriptionV5, + }, + note::ExtractedNoteCommitment, + note_encryption::Zip212Enforcement, + value::ValueCommitment, + Nullifier, +}; +use redjubjub::SpendAuth; use zcash_encoding::{Array, CompactSize, Vector}; use zcash_note_encryption::{EphemeralKeyBytes, ENC_CIPHERTEXT_SIZE, OUT_CIPHERTEXT_SIZE}; - -use crate::{ - sapling::{ - bundle::{ - Authorization, Authorized, Bundle, GrothProofBytes, OutputDescription, - OutputDescriptionV5, SpendDescription, SpendDescriptionV5, - }, - note::ExtractedNoteCommitment, - value::ValueCommitment, - Nullifier, - }, - transaction::Transaction, +use zcash_protocol::{ + consensus::{BlockHeight, NetworkUpgrade, Parameters, ZIP212_GRACE_PERIOD}, + value::ZatBalance, }; -use super::{Amount, GROTH_PROOF_SIZE}; +use super::GROTH_PROOF_SIZE; +use crate::transaction::Transaction; /// Returns the enforcement policy for ZIP 212 at the given height. pub fn zip212_enforcement(params: &impl Parameters, height: BlockHeight) -> Zip212Enforcement { @@ -317,7 +316,7 @@ pub fn temporary_zcashd_read_v4_components( reader: R, tx_has_sapling: bool, ) -> io::Result<( - Amount, + ZatBalance, Vec>, Vec>, )> { @@ -330,7 +329,7 @@ pub(crate) fn read_v4_components( mut reader: R, tx_has_sapling: bool, ) -> io::Result<( - Amount, + ZatBalance, Vec>, Vec>, )> { @@ -344,7 +343,7 @@ pub(crate) fn read_v4_components( Vector::read(&mut reader, |r| read_output_v4(r))?; Ok((vb, ss, so)) } else { - Ok((Amount::zero(), vec![], vec![])) + Ok((ZatBalance::zero(), vec![], vec![])) } } @@ -352,7 +351,7 @@ pub(crate) fn read_v4_components( #[cfg(feature = "temporary-zcashd")] pub fn temporary_zcashd_write_v4_components( writer: W, - bundle: Option<&Bundle>, + bundle: Option<&Bundle>, tx_has_sapling: bool, ) -> io::Result<()> { write_v4_components(writer, bundle, tx_has_sapling) @@ -361,13 +360,13 @@ pub fn temporary_zcashd_write_v4_components( /// Writes the Sapling components of a v4 transaction. pub(crate) fn write_v4_components( mut writer: W, - bundle: Option<&Bundle>, + bundle: Option<&Bundle>, tx_has_sapling: bool, ) -> io::Result<()> { if tx_has_sapling { writer.write_all( &bundle - .map_or(Amount::zero(), |b| *b.value_balance()) + .map_or(ZatBalance::zero(), |b| *b.value_balance()) .to_i64_le_bytes(), )?; Vector::write( @@ -394,7 +393,7 @@ pub(crate) fn write_v4_components( #[allow(clippy::redundant_closure)] pub(crate) fn read_v5_bundle( mut reader: R, -) -> io::Result>> { +) -> io::Result>> { let sd_v5s = Vector::read(&mut reader, read_spend_v5)?; let od_v5s = Vector::read(&mut reader, read_output_v5)?; let n_spends = sd_v5s.len(); @@ -402,7 +401,7 @@ pub(crate) fn read_v5_bundle( let value_balance = if n_spends > 0 || n_outputs > 0 { Transaction::read_amount(&mut reader)? } else { - Amount::zero() + ZatBalance::zero() }; let anchor = if n_spends > 0 { @@ -451,7 +450,7 @@ pub(crate) fn read_v5_bundle( /// Writes a [`Bundle`] in the v5 transaction format. pub(crate) fn write_v5_bundle( mut writer: W, - sapling_bundle: Option<&Bundle>, + sapling_bundle: Option<&Bundle>, ) -> io::Result<()> { if let Some(bundle) = sapling_bundle { Vector::write(&mut writer, bundle.shielded_spends(), |w, e| { @@ -501,27 +500,23 @@ pub(crate) fn write_v5_bundle( pub mod testing { use proptest::prelude::*; - use crate::{ - sapling::bundle::{testing as t_sap, Authorized, Bundle}, - transaction::{ - components::{amount::testing::arb_amount, Amount}, - TxVersion, - }, - }; + use crate::transaction::TxVersion; + use ::sapling::bundle::{testing as t_sap, Authorized, Bundle}; + use zcash_protocol::value::{testing::arb_zat_balance, ZatBalance}; prop_compose! { fn arb_bundle()( - value_balance in arb_amount() + value_balance in arb_zat_balance() )( bundle in t_sap::arb_bundle(value_balance) - ) -> Option> { + ) -> Option> { bundle } } pub fn arb_bundle_for_version( v: TxVersion, - ) -> impl Strategy>> { + ) -> impl Strategy>> { if v.has_sapling() { Strategy::boxed(arb_bundle()) } else { diff --git a/zcash_primitives/src/transaction/components/sprout.rs b/zcash_primitives/src/transaction/components/sprout.rs index b3e2370f71..c85c8c0d64 100644 --- a/zcash_primitives/src/transaction/components/sprout.rs +++ b/zcash_primitives/src/transaction/components/sprout.rs @@ -2,7 +2,8 @@ use std::io::{self, Read, Write}; -use super::{amount::Amount, GROTH_PROOF_SIZE}; +use super::GROTH_PROOF_SIZE; +use zcash_protocol::value::ZatBalance; // π_A + π_A' + π_B + π_B' + π_C + π_C' + π_K + π_H const PHGR_PROOF_SIZE: usize = 33 + 33 + 65 + 33 + 33 + 33 + 33 + 33; @@ -22,10 +23,10 @@ impl Bundle { /// its value is added to the transparent value pool; when it /// is negative, its value is subtracted from the transparent /// value pool. - pub fn value_balance(&self) -> Option { + pub fn value_balance(&self) -> Option { self.joinsplits .iter() - .try_fold(Amount::zero(), |total, js| total + js.net_value()) + .try_fold(ZatBalance::zero(), |total, js| total + js.net_value()) } } @@ -47,8 +48,8 @@ impl std::fmt::Debug for SproutProof { #[derive(Clone)] pub struct JsDescription { - pub(crate) vpub_old: Amount, - pub(crate) vpub_new: Amount, + pub(crate) vpub_old: ZatBalance, + pub(crate) vpub_new: ZatBalance, pub(crate) anchor: [u8; 32], pub(crate) nullifiers: [[u8; 32]; ZC_NUM_JS_INPUTS], pub(crate) commitments: [[u8; 32]; ZC_NUM_JS_OUTPUTS], @@ -89,7 +90,7 @@ impl JsDescription { let vpub_old = { let mut tmp = [0u8; 8]; reader.read_exact(&mut tmp)?; - Amount::from_u64_le_bytes(tmp) + ZatBalance::from_u64_le_bytes(tmp) } .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "vpub_old out of range"))?; @@ -97,7 +98,7 @@ impl JsDescription { let vpub_new = { let mut tmp = [0u8; 8]; reader.read_exact(&mut tmp)?; - Amount::from_u64_le_bytes(tmp) + ZatBalance::from_u64_le_bytes(tmp) } .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "vpub_new out of range"))?; @@ -189,7 +190,7 @@ impl JsDescription { /// its value is added to the transparent value pool; when it /// is negative, its value is subtracted from the transparent /// value pool. - pub fn net_value(&self) -> Amount { + pub fn net_value(&self) -> ZatBalance { (self.vpub_new - self.vpub_old).expect("difference is in range [-MAX_MONEY..=MAX_MONEY]") } } diff --git a/zcash_primitives/src/transaction/fees.rs b/zcash_primitives/src/transaction/fees.rs index 4a4cb6aa8b..353bce8eb4 100644 --- a/zcash_primitives/src/transaction/fees.rs +++ b/zcash_primitives/src/transaction/fees.rs @@ -1,8 +1,9 @@ //! Abstractions and types related to fee calculations. -use crate::{ +use crate::transaction::fees::transparent::InputSize; +use zcash_protocol::{ consensus::{self, BlockHeight}, - transaction::{components::amount::NonNegativeAmount, fees::transparent::InputSize}, + value::Zatoshis, }; #[cfg(feature = "non-standard-fees")] @@ -33,7 +34,7 @@ pub trait FeeRule { sapling_input_count: usize, sapling_output_count: usize, orchard_action_count: usize, - ) -> Result; + ) -> Result; } /// A trait that represents the ability to compute the fees that must be paid by a transaction @@ -57,5 +58,5 @@ pub trait FutureFeeRule: FeeRule { orchard_action_count: usize, tze_inputs: &[impl tze::InputView], tze_outputs: &[impl tze::OutputView], - ) -> Result; + ) -> Result; } diff --git a/zcash_primitives/src/transaction/fees/fixed.rs b/zcash_primitives/src/transaction/fees/fixed.rs index 56fc9a1ecd..c69dd38940 100644 --- a/zcash_primitives/src/transaction/fees/fixed.rs +++ b/zcash_primitives/src/transaction/fees/fixed.rs @@ -1,7 +1,8 @@ -use crate::{ +use crate::transaction::fees::transparent; + +use zcash_protocol::{ consensus::{self, BlockHeight}, - transaction::components::amount::NonNegativeAmount, - transaction::fees::transparent, + value::Zatoshis, }; #[cfg(zcash_unstable = "zfuture")] @@ -11,17 +12,17 @@ use crate::transaction::fees::tze; /// the transaction being constructed. #[derive(Clone, Copy, Debug)] pub struct FeeRule { - fixed_fee: NonNegativeAmount, + fixed_fee: Zatoshis, } impl FeeRule { /// Creates a new nonstandard fixed fee rule with the specified fixed fee. - pub fn non_standard(fixed_fee: NonNegativeAmount) -> Self { + pub fn non_standard(fixed_fee: Zatoshis) -> Self { Self { fixed_fee } } /// Returns the fixed fee amount which this rule was configured. - pub fn fixed_fee(&self) -> NonNegativeAmount { + pub fn fixed_fee(&self) -> Zatoshis { self.fixed_fee } } @@ -38,7 +39,7 @@ impl super::FeeRule for FeeRule { _sapling_input_count: usize, _sapling_output_count: usize, _orchard_action_count: usize, - ) -> Result { + ) -> Result { Ok(self.fixed_fee) } } @@ -56,7 +57,7 @@ impl super::FutureFeeRule for FeeRule { _orchard_action_count: usize, _tze_inputs: &[impl tze::InputView], _tze_outputs: &[impl tze::OutputView], - ) -> Result { + ) -> Result { Ok(self.fixed_fee) } } diff --git a/zcash_primitives/src/transaction/fees/transparent.rs b/zcash_primitives/src/transaction/fees/transparent.rs index a2fbfd4526..4ee98977f9 100644 --- a/zcash_primitives/src/transaction/fees/transparent.rs +++ b/zcash_primitives/src/transaction/fees/transparent.rs @@ -3,16 +3,15 @@ use std::convert::Infallible; -use crate::{ - legacy::{Script, TransparentAddress}, - transaction::{ - components::{amount::NonNegativeAmount, transparent::TxOut, OutPoint}, - fees::zip317::P2PKH_STANDARD_INPUT_SIZE, - }, +use crate::transaction::fees::zip317::P2PKH_STANDARD_INPUT_SIZE; +use transparent::{ + address::{Script, TransparentAddress}, + bundle::{OutPoint, TxOut}, }; +use zcash_protocol::value::Zatoshis; #[cfg(feature = "transparent-inputs")] -use crate::transaction::components::transparent::builder::TransparentInputInfo; +use transparent::builder::TransparentInputInfo; /// The size of a transparent input, or the outpoint corresponding to the input /// if the size of the script required to spend that input is unknown. @@ -72,7 +71,7 @@ impl InputView for Infallible { /// fee and change computation. pub trait OutputView: std::fmt::Debug { /// Returns the value of the output being created. - fn value(&self) -> NonNegativeAmount; + fn value(&self) -> Zatoshis; /// Returns the script corresponding to the newly created output. fn script_pubkey(&self) -> &Script; @@ -86,7 +85,7 @@ pub trait OutputView: std::fmt::Debug { } impl OutputView for TxOut { - fn value(&self) -> NonNegativeAmount { + fn value(&self) -> Zatoshis { self.value } diff --git a/zcash_primitives/src/transaction/fees/zip317.rs b/zcash_primitives/src/transaction/fees/zip317.rs index 7ea41415c4..24c7f77d97 100644 --- a/zcash_primitives/src/transaction/fees/zip317.rs +++ b/zcash_primitives/src/transaction/fees/zip317.rs @@ -4,21 +4,18 @@ //! [ZIP 317]: https//zips.z.cash/zip-0317 use core::cmp::max; -use crate::{ +use ::transparent::bundle::OutPoint; +use zcash_protocol::{ consensus::{self, BlockHeight}, - transaction::{ - components::{ - amount::{BalanceError, NonNegativeAmount}, - transparent::OutPoint, - }, - fees::transparent, - }, + value::{BalanceError, Zatoshis}, }; +use crate::transaction::fees::transparent; + /// The standard [ZIP 317] marginal fee. /// /// [ZIP 317]: https//zips.z.cash/zip-0317 -pub const MARGINAL_FEE: NonNegativeAmount = NonNegativeAmount::const_from_u64(5_000); +pub const MARGINAL_FEE: Zatoshis = Zatoshis::const_from_u64(5_000); /// The minimum number of logical actions that must be paid according to [ZIP 317]. /// @@ -39,7 +36,7 @@ pub const P2PKH_STANDARD_OUTPUT_SIZE: usize = 34; /// `MARGINAL_FEE * GRACE_ACTIONS`. /// /// [ZIP 317]: https//zips.z.cash/zip-0317 -pub const MINIMUM_FEE: NonNegativeAmount = NonNegativeAmount::const_from_u64(10_000); +pub const MINIMUM_FEE: Zatoshis = Zatoshis::const_from_u64(10_000); /// A [`FeeRule`] implementation that implements the [ZIP 317] fee rule. /// @@ -55,7 +52,7 @@ pub const MINIMUM_FEE: NonNegativeAmount = NonNegativeAmount::const_from_u64(10_ /// [ZIP 317]: https//zips.z.cash/zip-0317 #[derive(Clone, Debug)] pub struct FeeRule { - marginal_fee: NonNegativeAmount, + marginal_fee: Zatoshis, grace_actions: usize, p2pkh_standard_input_size: usize, p2pkh_standard_output_size: usize, @@ -88,7 +85,7 @@ impl FeeRule { /// zero. #[cfg(feature = "non-standard-fees")] pub fn non_standard( - marginal_fee: NonNegativeAmount, + marginal_fee: Zatoshis, grace_actions: usize, p2pkh_standard_input_size: usize, p2pkh_standard_output_size: usize, @@ -106,7 +103,7 @@ impl FeeRule { } /// Returns the ZIP 317 marginal fee. - pub fn marginal_fee(&self) -> NonNegativeAmount { + pub fn marginal_fee(&self) -> Zatoshis { self.marginal_fee } /// Returns the ZIP 317 number of grace actions @@ -164,7 +161,7 @@ impl super::FeeRule for FeeRule { sapling_input_count: usize, sapling_output_count: usize, orchard_action_count: usize, - ) -> Result { + ) -> Result { let mut t_in_total_size: usize = 0; let mut non_p2pkh_outpoints = vec![]; for sz in transparent_input_sizes.into_iter() { diff --git a/zcash_primitives/src/transaction/mod.rs b/zcash_primitives/src/transaction/mod.rs index 14f4d654a9..63c3bc262b 100644 --- a/zcash_primitives/src/transaction/mod.rs +++ b/zcash_primitives/src/transaction/mod.rs @@ -17,20 +17,19 @@ use std::convert::TryFrom; use std::fmt::Debug; use std::io::{self, Read, Write}; use std::ops::Deref; -use zcash_encoding::{CompactSize, Vector}; -use crate::{ +use ::sapling::{self, builder as sapling_builder}; +use ::transparent::bundle::{self as transparent, OutPoint, TxIn, TxOut}; +use zcash_encoding::{CompactSize, Vector}; +use zcash_protocol::{ consensus::{BlockHeight, BranchId}, - sapling::{self, builder as sapling_builder}, + value::{BalanceError, ZatBalance}, }; use self::{ components::{ - amount::{Amount, BalanceError}, orchard as orchard_serialization, sapling as sapling_serialization, sprout::{self, JsDescription}, - transparent::{self, TxIn, TxOut}, - OutPoint, }, txid::{to_txid, BlockTxCommitmentDigester, TxIdDigester}, util::sha256d::{HashReader, HashWriter}, @@ -229,7 +228,7 @@ impl Authorization for Authorized { pub struct Unauthorized; impl Authorization for Unauthorized { - type TransparentAuth = transparent::builder::Unauthorized; + type TransparentAuth = ::transparent::builder::Unauthorized; type SaplingAuth = sapling_builder::InProgress; type OrchardAuth = @@ -269,8 +268,8 @@ pub struct TransactionData { expiry_height: BlockHeight, transparent_bundle: Option>, sprout_bundle: Option, - sapling_bundle: Option>, - orchard_bundle: Option>, + sapling_bundle: Option>, + orchard_bundle: Option>, #[cfg(zcash_unstable = "zfuture")] tze_bundle: Option>, } @@ -285,8 +284,8 @@ impl TransactionData { expiry_height: BlockHeight, transparent_bundle: Option>, sprout_bundle: Option, - sapling_bundle: Option>, - orchard_bundle: Option>, + sapling_bundle: Option>, + orchard_bundle: Option>, ) -> Self { TransactionData { version, @@ -313,8 +312,8 @@ impl TransactionData { expiry_height: BlockHeight, transparent_bundle: Option>, sprout_bundle: Option, - sapling_bundle: Option>, - orchard_bundle: Option>, + sapling_bundle: Option>, + orchard_bundle: Option>, tze_bundle: Option>, ) -> Self { TransactionData { @@ -356,11 +355,11 @@ impl TransactionData { self.sprout_bundle.as_ref() } - pub fn sapling_bundle(&self) -> Option<&sapling::Bundle> { + pub fn sapling_bundle(&self) -> Option<&sapling::Bundle> { self.sapling_bundle.as_ref() } - pub fn orchard_bundle(&self) -> Option<&orchard::Bundle> { + pub fn orchard_bundle(&self) -> Option<&orchard::Bundle> { self.orchard_bundle.as_ref() } @@ -372,25 +371,25 @@ impl TransactionData { /// Returns the total fees paid by the transaction, given a function that can be used to /// retrieve the value of previous transactions' transparent outputs that are being spent in /// this transaction. - pub fn fee_paid(&self, get_prevout: F) -> Result + pub fn fee_paid(&self, get_prevout: F) -> Result where E: From, - F: FnMut(&OutPoint) -> Result, + F: FnMut(&OutPoint) -> Result, { let value_balances = [ self.transparent_bundle .as_ref() - .map_or_else(|| Ok(Amount::zero()), |b| b.value_balance(get_prevout))?, + .map_or_else(|| Ok(ZatBalance::zero()), |b| b.value_balance(get_prevout))?, self.sprout_bundle.as_ref().map_or_else( - || Ok(Amount::zero()), + || Ok(ZatBalance::zero()), |b| b.value_balance().ok_or(BalanceError::Overflow), )?, self.sapling_bundle .as_ref() - .map_or_else(Amount::zero, |b| *b.value_balance()), + .map_or_else(ZatBalance::zero, |b| *b.value_balance()), self.orchard_bundle .as_ref() - .map_or_else(Amount::zero, |b| *b.value_balance()), + .map_or_else(ZatBalance::zero, |b| *b.value_balance()), ]; value_balances @@ -425,11 +424,11 @@ impl TransactionData { Option>, ) -> Option>, f_sapling: impl FnOnce( - Option>, - ) -> Option>, + Option>, + ) -> Option>, f_orchard: impl FnOnce( - Option>, - ) -> Option>, + Option>, + ) -> Option>, #[cfg(zcash_unstable = "zfuture")] f_tze: impl FnOnce( Option>, ) @@ -460,12 +459,13 @@ impl TransactionData { ) -> Result>, E>, f_sapling: impl FnOnce( - Option>, - ) -> Result>, E>, + Option>, + ) + -> Result>, E>, f_orchard: impl FnOnce( - Option>, + Option>, ) - -> Result>, E>, + -> Result>, E>, #[cfg(zcash_unstable = "zfuture")] f_tze: impl FnOnce( Option>, ) -> Result< @@ -526,10 +526,10 @@ impl TransactionData { } impl TransactionData { - pub fn sapling_value_balance(&self) -> Amount { + pub fn sapling_value_balance(&self) -> ZatBalance { self.sapling_bundle .as_ref() - .map_or(Amount::zero(), |b| *b.value_balance()) + .map_or(ZatBalance::zero(), |b| *b.value_balance()) } } @@ -687,10 +687,10 @@ impl Transaction { }) } - fn read_amount(mut reader: R) -> io::Result { + fn read_amount(mut reader: R) -> io::Result { let mut tmp = [0; 8]; reader.read_exact(&mut tmp)?; - Amount::from_i64_le_bytes(tmp) + ZatBalance::from_i64_le_bytes(tmp) .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "valueBalance out of range")) } @@ -741,7 +741,7 @@ impl Transaction { #[cfg(feature = "temporary-zcashd")] pub fn temporary_zcashd_read_v5_sapling( reader: R, - ) -> io::Result>> { + ) -> io::Result>> { sapling_serialization::read_v5_bundle(reader) } @@ -850,7 +850,7 @@ impl Transaction { #[cfg(feature = "temporary-zcashd")] pub fn temporary_zcashd_write_v5_sapling( - sapling_bundle: Option<&sapling::Bundle>, + sapling_bundle: Option<&sapling::Bundle>, writer: W, ) -> io::Result<()> { sapling_serialization::write_v5_bundle(writer, sapling_bundle) @@ -929,12 +929,12 @@ pub trait TransactionDigest { fn digest_sapling( &self, - sapling_bundle: Option<&sapling::Bundle>, + sapling_bundle: Option<&sapling::Bundle>, ) -> Self::SaplingDigest; fn digest_orchard( &self, - orchard_bundle: Option<&orchard::Bundle>, + orchard_bundle: Option<&orchard::Bundle>, ) -> Self::OrchardDigest; #[cfg(zcash_unstable = "zfuture")] @@ -958,13 +958,13 @@ pub enum DigestError { pub mod testing { use proptest::prelude::*; - use crate::consensus::BranchId; + use ::transparent::bundle::testing::{self as transparent}; + use zcash_protocol::consensus::BranchId; use super::{ components::{ orchard::testing::{self as orchard}, sapling::testing::{self as sapling}, - transparent::testing::{self as transparent}, }, Authorized, Transaction, TransactionData, TxId, TxVersion, }; diff --git a/zcash_primitives/src/transaction/sighash.rs b/zcash_primitives/src/transaction/sighash.rs index ff379eda48..0c49b985ff 100644 --- a/zcash_primitives/src/transaction/sighash.rs +++ b/zcash_primitives/src/transaction/sighash.rs @@ -4,12 +4,12 @@ use super::{ sighash_v4::v4_signature_hash, sighash_v5::v5_signature_hash, Authorization, TransactionData, TxDigests, TxVersion, }; -use crate::sapling::{self, bundle::GrothProofBytes}; +use ::sapling::{self, bundle::GrothProofBytes}; #[cfg(zcash_unstable = "zfuture")] -use {super::components::Amount, crate::extensions::transparent::Precondition}; +use {crate::extensions::transparent::Precondition, zcash_protocol::value::Zatoshis}; -pub use transparent::sighash::*; +//pub use transparent::sighash::*; pub enum SignableInput<'a> { Shielded, @@ -18,17 +18,17 @@ pub enum SignableInput<'a> { Tze { index: usize, precondition: &'a Precondition, - value: Amount, + value: Zatoshis, }, } impl<'a> SignableInput<'a> { pub fn hash_type(&self) -> u8 { match self { - SignableInput::Shielded => SIGHASH_ALL, + SignableInput::Shielded => ::transparent::sighash::SIGHASH_ALL, SignableInput::Transparent(input) => input.hash_type().encode(), #[cfg(zcash_unstable = "zfuture")] - SignableInput::Tze { .. } => SIGHASH_ALL, + SignableInput::Tze { .. } => ::transparent::sighash::SIGHASH_ALL, } } } @@ -46,7 +46,7 @@ impl AsRef<[u8; 32]> for SignatureHash { /// set of precomputed hashes produced in the construction of the /// transaction ID. pub fn signature_hash< - TA: TransparentAuthorizingContext, + TA: ::transparent::sighash::TransparentAuthorizingContext, SA: sapling::bundle::Authorization, A: Authorization, >( diff --git a/zcash_primitives/src/transaction/sighash_v4.rs b/zcash_primitives/src/transaction/sighash_v4.rs index 3d9e47a5ce..2fa95ae5b3 100644 --- a/zcash_primitives/src/transaction/sighash_v4.rs +++ b/zcash_primitives/src/transaction/sighash_v4.rs @@ -1,21 +1,19 @@ use blake2b_simd::{Hash as Blake2bHash, Params as Blake2bParams}; use ff::PrimeField; -use crate::{ - consensus::BranchId, - sapling::{ - self, - bundle::{GrothProofBytes, OutputDescription, SpendDescription}, - }, +use ::sapling::{ + self, + bundle::{GrothProofBytes, OutputDescription, SpendDescription}, }; +use ::transparent::{ + bundle::{self as transparent, TxIn, TxOut}, + sighash::{SIGHASH_ANYONECANPAY, SIGHASH_MASK, SIGHASH_NONE, SIGHASH_SINGLE}, +}; +use zcash_protocol::consensus::BranchId; use super::{ - components::{ - sapling as sapling_serialization, - sprout::JsDescription, - transparent::{self, TxIn, TxOut}, - }, - sighash::{SignableInput, SIGHASH_ANYONECANPAY, SIGHASH_MASK, SIGHASH_NONE, SIGHASH_SINGLE}, + components::{sapling as sapling_serialization, sprout::JsDescription}, + sighash::SignableInput, Authorization, TransactionData, }; diff --git a/zcash_primitives/src/transaction/sighash_v5.rs b/zcash_primitives/src/transaction/sighash_v5.rs index 410feb638d..bc7c6f442b 100644 --- a/zcash_primitives/src/transaction/sighash_v5.rs +++ b/zcash_primitives/src/transaction/sighash_v5.rs @@ -1,14 +1,17 @@ +use blake2b_simd::{Hash as Blake2bHash, Params, State}; use std::io::Write; -use blake2b_simd::{Hash as Blake2bHash, Params, State}; +use ::transparent::{ + bundle::{self as transparent, TxOut}, + sighash::{ + TransparentAuthorizingContext, SIGHASH_ANYONECANPAY, SIGHASH_MASK, SIGHASH_NONE, + SIGHASH_SINGLE, + }, +}; use zcash_encoding::Array; use crate::transaction::{ - components::transparent::{self, TxOut}, - sighash::{ - SignableInput, TransparentAuthorizingContext, SIGHASH_ANYONECANPAY, SIGHASH_MASK, - SIGHASH_NONE, SIGHASH_SINGLE, - }, + sighash::SignableInput, txid::{ hash_transparent_txid_data, to_hash, transparent_outputs_hash, transparent_prevout_hash, transparent_sequence_hash, ZCASH_TRANSPARENT_HASH_PERSONALIZATION, diff --git a/zcash_primitives/src/transaction/tests.rs b/zcash_primitives/src/transaction/tests.rs index fed4a1e799..a2514ed383 100644 --- a/zcash_primitives/src/transaction/tests.rs +++ b/zcash_primitives/src/transaction/tests.rs @@ -4,13 +4,12 @@ use std::ops::Deref; use proptest::prelude::*; -use crate::{ - consensus::BranchId, legacy::Script, transaction::components::amount::NonNegativeAmount, -}; +use ::transparent::{address::Script, sighash::TransparentAuthorizingContext}; +use zcash_protocol::{consensus::BranchId, value::Zatoshis}; use super::{ sapling, - sighash::{SignableInput, TransparentAuthorizingContext}, + sighash::SignableInput, sighash_v4::v4_signature_hash, sighash_v5::v5_signature_hash, testing::arb_tx, @@ -140,7 +139,7 @@ fn zip_0143() { n as usize, &tv.script_code, &tv.script_code, - NonNegativeAmount::from_nonnegative_i64(tv.amount).unwrap(), + Zatoshis::from_nonnegative_i64(tv.amount).unwrap(), )) } _ => SignableInput::Shielded, @@ -164,7 +163,7 @@ fn zip_0243() { n as usize, &tv.script_code, &tv.script_code, - NonNegativeAmount::from_nonnegative_i64(tv.amount).unwrap(), + Zatoshis::from_nonnegative_i64(tv.amount).unwrap(), )) } _ => SignableInput::Shielded, @@ -179,7 +178,7 @@ fn zip_0243() { #[derive(Debug)] struct TestTransparentAuth { - input_amounts: Vec, + input_amounts: Vec, input_scriptpubkeys: Vec