diff --git a/packages/rs-platform-version/src/version/feature_initial_protocol_versions.rs b/packages/rs-platform-version/src/version/feature_initial_protocol_versions.rs index fd91614fd9a..92a1cf2424b 100644 --- a/packages/rs-platform-version/src/version/feature_initial_protocol_versions.rs +++ b/packages/rs-platform-version/src/version/feature_initial_protocol_versions.rs @@ -45,6 +45,10 @@ pub const YES_NO_VOTE_POLL_INITIAL_PROTOCOL_VERSION: ProtocolVersion = 15; /// exist and lookups must report it absent. Creating one of its proposals opens a yes/no vote /// poll. pub const DECISION_PROPOSALS_CONTRACT_INITIAL_PROTOCOL_VERSION: ProtocolVersion = 15; +/// A contact request's `encryptedShieldedAddress`, the sender's shielded payment address for +/// the contact, exists from protocol version 15: DashPay v3, which replaces DashPay at that +/// version, adds the property, and below it the network's contact requests have none. +pub const DASHPAY_CONTACT_REQUEST_SHIELDED_ADDRESS_INITIAL_PROTOCOL_VERSION: ProtocolVersion = 15; /// Private document entries activate with protocol version 15: a /// `PrivateDocumentCreateFromShieldedPool`, which appends entries to a private document type's /// store paying from the credit shielded pool, is not active before it, as software that diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs b/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs index e99725d64cb..04337b80b00 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs @@ -1065,6 +1065,17 @@ impl DashPayView<'_, B> { ), } + // 4e. The sender's shielded payment address for this contact, when the + // identity's shielded account was proven against the seed in this + // session and the network's contact requests carry one; the request + // goes without it otherwise. The identity's placement is held from + // here until the request is signed, so the account the address is + // derived from is still the identity's when the request commits to it. + let placement = self.identity_placement.read().await; + let shielded_address = self + .contact_shielded_address(sender_identity_id, recipient_identity_id, account_reference) + .await?; + // 5. Build the signing key reference for document signing. let identity_public_key = sender_identity // Contact-request send writes a document state transition, @@ -1120,6 +1131,7 @@ impl DashPayView<'_, B> { account_reference, account_label, auto_accept_proof, + shielded_address, shared_secret, expected_recipient_pubkey: recipient_enc_pubkey, xpub_bytes, @@ -1131,6 +1143,7 @@ impl DashPayView<'_, B> { true => PlatformWalletError::WalletRemovedBeforeSend(hex::encode(self.wallet_id)), false => error, })?; + drop(placement); // 8. Broadcast the signed bytes, keeping what every dispatch proved, // by the rule shielded spends use (`broadcast_tracking_delivery`): diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/contact_shielded_address.rs b/packages/rs-platform-wallet/src/wallet/identity/network/contact_shielded_address.rs new file mode 100644 index 00000000000..5598b2fa7b5 --- /dev/null +++ b/packages/rs-platform-wallet/src/wallet/identity/network/contact_shielded_address.rs @@ -0,0 +1,153 @@ +//! The shielded payment address a contact request carries. + +use super::identity_handle::IdentityWallet; +use crate::broadcaster::TransactionBroadcaster; +use crate::error::PlatformWalletError; +#[cfg(feature = "shielded")] +use crate::wallet::shielded::shielded_identity_account_index; +#[cfg(feature = "shielded")] +use dash_sdk::platform::Fetch; +#[cfg(feature = "shielded")] +use dpp::data_contract::accessors::v0::DataContractV0Getters; +#[cfg(feature = "shielded")] +use dpp::data_contract::document_type::accessors::DocumentTypeV0Getters; +#[cfg(feature = "shielded")] +use dpp::data_contracts::SystemDataContract; +#[cfg(feature = "shielded")] +use dpp::prelude::DataContract; +use dpp::prelude::Identifier; + +/// The DashPay document type of a contact request. +#[cfg(feature = "shielded")] +const CONTACT_REQUEST: &str = "contactRequest"; + +/// The `contactRequest` property that carries the sender's shielded address. +#[cfg(feature = "shielded")] +const ENCRYPTED_SHIELDED_ADDRESS: &str = "encryptedShieldedAddress"; + +/// Log why `owner_id`'s contact request goes without a shielded address. The +/// request is still sent, so this is the only trace of the reason. +#[cfg(feature = "shielded")] +fn without_address(owner_id: &Identifier, reason: &str) { + tracing::debug!( + identity = %owner_id, + reason, + "contact request sent without a shielded address" + ); +} + +impl IdentityWallet { + /// The shielded payment address `owner_id` gives `to_user_id` in the contact request + /// it sends under `account_reference`, or `None` when the request goes without one. + /// + /// The address is the one the identity's shielded account derives for this request + /// alone (`AccountViewingKeys::contact_address`), so every contact gets a different + /// one and a payment that arrives on it is attributed to that contact. It is `None` + /// unless all of these hold: + /// + /// - the identity's shielded account was prepared in this session, which proves with + /// the seed that the identity holds the slot the account belongs to, and it is + /// still the account of the slot the identity holds; + /// - that account's viewing keys are bound; + /// - the connected network's contact requests have the property that carries the + /// address. A bundled schema does not show the network has activated it. + /// + /// The send is refused when the address would be one this identity has given + /// another contact. That takes a collision in 87 bits of a keyed hash. + /// + /// The caller holds the identity's placement from this call until the request is + /// signed, so the account is still the identity's when the request commits to it. + pub(crate) async fn contact_shielded_address( + &self, + owner_id: &Identifier, + to_user_id: &Identifier, + account_reference: u32, + ) -> Result, PlatformWalletError> { + #[cfg(not(feature = "shielded"))] + { + let _ = (owner_id, to_user_id, account_reference); + Ok(None) + } + #[cfg(feature = "shielded")] + { + // The account of the slot the identity holds now, and the requests it has + // sent to its other contacts. + let (account, others) = { + let wm = self.wallet_manager.read().await; + let Some(managed) = wm + .get_wallet_info(&self.wallet_id) + .and_then(|info| info.identity_manager.managed_identity(owner_id)) + .filter(|identity| identity.wallet_id == Some(self.wallet_id)) + else { + without_address(owner_id, "the wallet does not hold the identity"); + return Ok(None); + }; + let Some(account) = managed + .identity_index + .and_then(|index| shielded_identity_account_index(index).ok()) + else { + without_address(owner_id, "the identity has no shielded account"); + return Ok(None); + }; + (account, managed.other_sent_account_references(to_user_id)) + }; + let Some(keys) = self + .contact_shielded_addresses + .proven_account_keys(owner_id, account) + .await + else { + without_address( + owner_id, + "the identity's shielded account is not prepared in this session, or \ + its viewing keys are not bound", + ); + return Ok(None); + }; + if !self.contact_requests_carry_shielded_address().await? { + without_address( + owner_id, + "the network's contact requests do not carry a shielded address yet", + ); + return Ok(None); + } + + let owner = owner_id.as_bytes(); + let reference = u64::from(account_reference); + let index = keys.contact_index(owner, to_user_id.as_bytes(), reference); + let taken = others.iter().any(|(other, other_reference)| { + keys.contact_index(owner, other.as_bytes(), u64::from(*other_reference)) == index + }); + if taken { + return Err(PlatformWalletError::InvalidIdentityData( + "The shielded address of this contact request is one already given to \ + another contact; send the request under another account reference" + .to_string(), + )); + } + Ok(Some( + keys.contact_address(owner, to_user_id.as_bytes(), reference) + .to_raw_address_bytes(), + )) + } + } + + /// Whether the connected network's DashPay contract gives contact requests the + /// property that carries a shielded address, which it does from DashPay v3 at + /// protocol version 15. Read from the network: the bundled schema is the latest one. + #[cfg(feature = "shielded")] + async fn contact_requests_carry_shielded_address(&self) -> Result { + let contract = DataContract::fetch(&self.sdk, SystemDataContract::Dashpay.id()) + .await? + .ok_or_else(|| { + PlatformWalletError::InvalidIdentityData( + "DashPay contract is not available".to_string(), + ) + })?; + let contact_request = contract + .document_type_for_name(CONTACT_REQUEST) + .map_err(|e| PlatformWalletError::InvalidIdentityData(e.to_string()))?; + Ok(contact_request + .properties() + .contains_key(ENCRYPTED_SHIELDED_ADDRESS)) + } +} diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs b/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs index 48a8c383901..21ea6cbecda 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs @@ -3947,6 +3947,8 @@ mod tests { dpns_operation_gate: Arc::new(tokio::sync::Mutex::new(())), dpns_sync_progress: Arc::new(std::sync::Mutex::new(BTreeMap::new())), identity_placement: Arc::new(tokio::sync::RwLock::new(())), + #[cfg(feature = "shielded")] + contact_shielded_addresses: Default::default(), } } diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/identity_handle.rs b/packages/rs-platform-wallet/src/wallet/identity/network/identity_handle.rs index a29cac1316e..852c4c661bd 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/identity_handle.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/identity_handle.rs @@ -542,6 +542,11 @@ pub struct IdentityWallet { /// tip address publication take it for reading). Taken before /// `wallet_manager`. pub(crate) identity_placement: Arc>, + /// The platform wallet's shielded viewing keys and seed-proven identity accounts, + /// from which the address a contact request carries is derived + /// ([`Self::contact_shielded_address`]). + #[cfg(feature = "shielded")] + pub(crate) contact_shielded_addresses: crate::wallet::shielded::ContactShieldedAddresses, } // Manual `Debug`: the derive would require `B: Debug`, which is not part @@ -572,6 +577,8 @@ impl Clone for IdentityWallet { dpns_operation_gate: Arc::clone(&self.dpns_operation_gate), dpns_sync_progress: Arc::clone(&self.dpns_sync_progress), identity_placement: Arc::clone(&self.identity_placement), + #[cfg(feature = "shielded")] + contact_shielded_addresses: self.contact_shielded_addresses.clone(), } } } diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs b/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs index ac7eba762cd..6ac4f603645 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs @@ -63,6 +63,7 @@ pub(crate) use withdrawal::{select_owner_withdrawal_key, select_transfer_withdra // DashPay-contract operations, namespaced behind `IdentityWallet::dashpay()`. mod contact_info; mod contact_requests; +mod contact_shielded_address; mod contacts; mod dashpay_view; mod invitation; diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/payments.rs b/packages/rs-platform-wallet/src/wallet/identity/network/payments.rs index 53092a5f078..68e703443f1 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/payments.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/payments.rs @@ -13436,6 +13436,8 @@ mod tests { dpns_operation_gate: Arc::clone(&real.dpns_operation_gate), dpns_sync_progress: Arc::clone(&real.dpns_sync_progress), identity_placement: Arc::clone(&real.identity_placement), + #[cfg(feature = "shielded")] + contact_shielded_addresses: real.contact_shielded_addresses.clone(), } } @@ -13480,6 +13482,8 @@ mod tests { dpns_operation_gate: Arc::clone(&real.dpns_operation_gate), dpns_sync_progress: Arc::clone(&real.dpns_sync_progress), identity_placement: Arc::clone(&real.identity_placement), + #[cfg(feature = "shielded")] + contact_shielded_addresses: real.contact_shielded_addresses.clone(), } } @@ -13538,6 +13542,8 @@ mod tests { dpns_operation_gate: Arc::clone(&real.dpns_operation_gate), dpns_sync_progress: Arc::clone(&real.dpns_sync_progress), identity_placement: Arc::clone(&real.identity_placement), + #[cfg(feature = "shielded")] + contact_shielded_addresses: real.contact_shielded_addresses.clone(), } } diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/sdk_writer.rs b/packages/rs-platform-wallet/src/wallet/identity/network/sdk_writer.rs index cb4bdf12651..85d7c68924d 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/sdk_writer.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/sdk_writer.rs @@ -105,6 +105,9 @@ pub(crate) struct SendContactRequestParams<'a> { pub account_label: Option, /// Optional unencrypted auto-accept proof. pub auto_accept_proof: Option>, + /// The sender's shielded payment address for this contact, 43 raw bytes, which the + /// SDK encrypts under the shared secret. `None` sends the request without one. + pub shielded_address: Option<[u8; 43]>, /// ECDH shared secret, already derived by the caller against the /// recipient's encryption key (client-side ECDH). The SDK encrypts /// the shared xpub with this directly; no private key crosses into @@ -194,6 +197,7 @@ impl SdkWriter { account_reference, account_label, auto_accept_proof, + shielded_address, shared_secret, expected_recipient_pubkey, xpub_bytes, @@ -209,6 +213,7 @@ impl SdkWriter { account_reference, account_label, auto_accept_proof, + shielded_address, }; let send_input = SendContactRequestInput { diff --git a/packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/contact_requests.rs b/packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/contact_requests.rs index ac70cc4f35a..f0aa5b90221 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/contact_requests.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/contact_requests.rs @@ -62,6 +62,40 @@ impl ManagedIdentity { }) } + /// The contact requests this identity has sent to contacts other than + /// `recipient`, as `(recipient, account reference)`. + /// + /// Both maps, as for [`Self::prior_sent_account_reference`]: a request + /// leaves `sent_contact_requests` for + /// `established_contacts[..].outgoing_request` once its contact + /// establishes, and what it issued stays issued. A request whose + /// broadcast is not settled yet counts too: it may already be on + /// Platform. + #[cfg(any(feature = "shielded", test))] + pub(crate) fn other_sent_account_references( + &self, + recipient: &Identifier, + ) -> Vec<(Identifier, u32)> { + self.dashpay + .sent_contact_requests + .values() + .chain( + self.dashpay + .established_contacts + .values() + .map(|contact| &contact.outgoing_request), + ) + .map(|request| (request.recipient_id, request.account_reference)) + .chain( + self.dashpay + .unconfirmed_public_requests + .iter() + .map(|(to, request)| (*to, request.account_reference)), + ) + .filter(|(to, _)| to != recipient) + .collect() + } + /// Add a sent contact request. /// /// If there's already an incoming request from the recipient, the @@ -1603,6 +1637,68 @@ mod tests { assert_eq!(managed.dashpay.established_contacts.len(), 0); } + /// A request's account reference stays issued once its contact + /// establishes, when the request moves out of the pending map. + #[test] + fn should_list_the_references_sent_to_pending_and_established_contacts() { + let mut managed = create_test_identity([1u8; 32]); + let our_id = Identifier::from([1u8; 32]); + let pending_id = Identifier::from([2u8; 32]); + let established_id = Identifier::from([3u8; 32]); + let p = noop_persister(); + for contact in [pending_id, established_id] { + managed + .add_sent_contact_request(create_contact_request(our_id, contact, 1), &p) + .expect("setup persists"); + } + managed + .add_incoming_contact_request(create_contact_request(established_id, our_id, 2), &p) + .expect("setup persists"); + assert!(managed + .dashpay + .established_contacts + .contains_key(&established_id)); + + let mut others = managed.other_sent_account_references(&Identifier::from([9u8; 32])); + others.sort(); + assert_eq!(others, vec![(pending_id, 0), (established_id, 0)]); + assert_eq!( + managed.other_sent_account_references(&established_id), + vec![(pending_id, 0)] + ); + assert_eq!( + managed.other_sent_account_references(&pending_id), + vec![(established_id, 0)] + ); + } + + /// A request held after its broadcast, with no proof of the outcome yet, + /// may already be on Platform: its account reference counts as issued. + #[test] + fn should_list_the_reference_of_a_request_whose_broadcast_is_not_settled() { + use dpp::state_transition::batch_transition::BatchTransition; + use key_wallet::bip32::ExtendedPrivKey; + use key_wallet::Network; + let mut managed = create_test_identity([1u8; 32]); + let unsettled_id = Identifier::from([4u8; 32]); + let master = ExtendedPrivKey::new_master(Network::Testnet, &[42u8; 32]).expect("a key"); + managed.hold_unconfirmed_public_request( + unsettled_id, + StateTransition::Batch(BatchTransition::V0(Default::default())), + 7, + 0, + ExtendedPubKey::from_priv(&master), + ); + + assert_eq!( + managed.other_sent_account_references(&Identifier::from([9u8; 32])), + vec![(unsettled_id, 7)] + ); + assert!(managed + .other_sent_account_references(&unsettled_id) + .is_empty()); + } + #[test] fn test_add_sent_then_incoming_auto_establishes() { let mut managed = create_test_identity([1u8; 32]); diff --git a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs index 9f3263167b7..9f9c954d471 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs @@ -866,6 +866,13 @@ impl PlatformWallet { .with_mined_height_locator(mined_height_locator), ); + // Shared with the identity wallet, which derives the shielded address a + // contact request carries from them. + #[cfg(feature = "shielded")] + let shielded_keys = Arc::new(RwLock::new(None)); + #[cfg(feature = "shielded")] + let prepared_tip_accounts = Arc::new(std::sync::Mutex::new(BTreeMap::new())); + let identity: IdentityWallet = IdentityWallet { sdk: Arc::clone(&sdk), wallet_manager: Arc::clone(&wallet_manager), @@ -885,6 +892,11 @@ impl PlatformWallet { dpns_operation_gate: Arc::new(tokio::sync::Mutex::new(())), dpns_sync_progress: Arc::new(std::sync::Mutex::new(BTreeMap::new())), identity_placement: Arc::new(tokio::sync::RwLock::new(())), + #[cfg(feature = "shielded")] + contact_shielded_addresses: super::shielded::ContactShieldedAddresses::new( + Arc::clone(&shielded_keys), + Arc::clone(&prepared_tip_accounts), + ), }; let platform = PlatformAddressWallet::new( @@ -907,13 +919,13 @@ impl PlatformWallet { persister: wallet_persister, generation, #[cfg(feature = "shielded")] - shielded_keys: Arc::new(RwLock::new(None)), + shielded_keys, #[cfg(feature = "shielded")] shield_guard: Arc::new(tokio::sync::Mutex::new(())), #[cfg(feature = "shielded")] shielded_config_lock: Arc::new(tokio::sync::Mutex::new(())), #[cfg(feature = "shielded")] - prepared_tip_accounts: Arc::new(std::sync::Mutex::new(BTreeMap::new())), + prepared_tip_accounts, #[cfg(feature = "shielded")] shielded_detached: Arc::new(std::sync::atomic::AtomicBool::new(false)), #[cfg(feature = "shielded")] diff --git a/packages/rs-platform-wallet/src/wallet/shielded/contact_address.rs b/packages/rs-platform-wallet/src/wallet/shielded/contact_address.rs new file mode 100644 index 00000000000..98ae3f80889 --- /dev/null +++ b/packages/rs-platform-wallet/src/wallet/shielded/contact_address.rs @@ -0,0 +1,63 @@ +//! The viewing keys a DashPay contact request's shielded address is derived from. +//! +//! The identity wallet sends contact requests and holds no shielded keys. The keys, and +//! the record of which identity's shielded account was proven against the seed in this +//! session, live with the platform wallet. [`ContactShieldedAddresses`] is the view of +//! both that the two share, so the identity wallet can derive the address a request +//! carries without the platform wallet handing it one. + +use super::tips::PreparedTipAccount; +use super::AccountViewingKeys; +use dpp::prelude::Identifier; +use std::collections::BTreeMap; +use std::sync::{Arc, Mutex, PoisonError}; +use tokio::sync::RwLock; + +/// The bound shielded viewing keys of a wallet and its seed-proven identity accounts. +/// Cloning shares both; the default holds no keys and no proven account. +#[derive(Clone, Default)] +pub(crate) struct ContactShieldedAddresses { + viewing_keys: Arc>>>, + prepared_accounts: Arc>>, +} + +impl ContactShieldedAddresses { + /// A view of the platform wallet's own maps. + pub(crate) fn new( + viewing_keys: Arc>>>, + prepared_accounts: Arc>>, + ) -> Self { + Self { + viewing_keys, + prepared_accounts, + } + } + + /// The viewing keys of `account`, the shielded account `identity_id` holds now, when + /// it is the account prepared for that identity in this session and the preparation + /// stands. `None` otherwise. + /// + /// A recorded identity index is not proof of the account: hosts restore a placeholder + /// index, and discovery can move an identity. Preparation proves the index with the + /// seed, so only a prepared account's keys derive an address that is given away. + pub(crate) async fn proven_account_keys( + &self, + identity_id: &Identifier, + account: u32, + ) -> Option { + // The keys are read first and the preparation checked under their + // lock, which a bind takes for writing: the keys returned are the ones + // bound while the preparation stood, never those of a later bind. + let viewing_keys = self.viewing_keys.read().await; + let standing = self + .prepared_accounts + .lock() + .unwrap_or_else(PoisonError::into_inner) + .get(identity_id) + .and_then(PreparedTipAccount::standing_account); + if standing != Some(account) { + return None; + } + viewing_keys.as_ref()?.get(&account).cloned() + } +} diff --git a/packages/rs-platform-wallet/src/wallet/shielded/contact_address_tests.rs b/packages/rs-platform-wallet/src/wallet/shielded/contact_address_tests.rs new file mode 100644 index 00000000000..73828bf6fa8 --- /dev/null +++ b/packages/rs-platform-wallet/src/wallet/shielded/contact_address_tests.rs @@ -0,0 +1,236 @@ +//! The shielded address a contact request carries, as the identity wallet derives it +//! from the sending identity's shielded account. + +use std::sync::Arc; + +use dashcore::Network; +use dpp::data_contracts::SystemDataContract; +use dpp::identity::{Identity, IdentityV0}; +use dpp::prelude::Identifier; +use dpp::system_data_contracts::load_system_data_contract; +use dpp::version::PlatformVersion; + +use super::viewing_key_bind_tests::{ + coordinator_at, seed_master_key, temp_dir, CapturingPersistence, +}; +use crate::wallet::platform_wallet::PlatformWallet; +use crate::wallet::shielded::keys::OrchardKeySet; +use crate::wallet::shielded::{shielded_identity_account_index, NetworkShieldedCoordinator}; + +/// The slot the fixture's identity holds. +const IDENTITY_INDEX: u32 = 2; +const BOB: [u8; 32] = [0x22; 32]; +const CAROL: [u8; 32] = [0x33; 32]; +const ACCOUNT_REFERENCE: u32 = 0x0123_4567; + +/// A wallet bound to account 0 whose identity holds slot 2, on a network that serves the +/// DashPay contract of `contract_protocol_version`. +async fn fixture( + tag: &str, + contract_protocol_version: u32, +) -> ( + PlatformWallet, + [u8; 64], + Identifier, + Arc, +) { + let phrase = crate::test_support::MESSAGE_SIGNING_TEST_MNEMONIC; + let seed = key_wallet::Mnemonic::from_phrase(phrase) + .unwrap() + .to_seed(""); + let (wallet_manager, wallet_id, _, _) = + crate::test_support::mnemonic_wallet_manager(phrase).await; + let generation = wallet_manager + .read() + .await + .get_wallet_info(&wallet_id) + .unwrap() + .generation + .clone(); + let spv = Arc::new(crate::spv::SpvRuntime::new( + Arc::clone(&wallet_manager), + Arc::new(crate::events::PlatformEventManager::new(Vec::new())), + )); + let mock_dir = temp_dir(tag); + std::fs::create_dir_all(&mock_dir).unwrap(); + let mut sdk = dash_sdk::SdkBuilder::new_mock() + .with_network(Network::Testnet) + .with_dump_dir(&mock_dir) + .with_version(PlatformVersion::latest()) + .build() + .unwrap(); + let contract = load_system_data_contract( + SystemDataContract::Dashpay, + PlatformVersion::get(contract_protocol_version).unwrap(), + ) + .unwrap(); + sdk.mock() + .expect_fetch(SystemDataContract::Dashpay.id(), Some(contract)) + .await + .unwrap(); + let wallet = PlatformWallet::new( + Arc::new(sdk), + wallet_id, + wallet_manager, + generation, + Arc::new(tokio::sync::Notify::new()), + Arc::new(CapturingPersistence::default()), + Arc::new(crate::broadcaster::SpvBroadcaster::new(spv)), + Arc::new(std::sync::atomic::AtomicBool::new(false)), + crate::changeset::DurableCursors::default(), + ); + let id = Identifier::from([0x66; 32]); + { + let mut wm = wallet.wallet_manager.write().await; + wm.get_wallet_info_mut(&wallet.wallet_id()) + .unwrap() + .identity_manager + .add_identity( + Identity::V0(IdentityV0 { + id, + public_keys: seed_master_key(&seed[..], IDENTITY_INDEX), + balance: 0, + revision: 0, + }), + IDENTITY_INDEX, + wallet.wallet_id(), + wallet.persister(), + ) + .unwrap(); + } + let coordinator = coordinator_at(&temp_dir(tag)); + wallet + .bind_shielded(&seed[..], &[0], &coordinator) + .await + .unwrap(); + (wallet, *seed, id, coordinator) +} + +async fn address_for( + wallet: &PlatformWallet, + owner: &Identifier, + to: [u8; 32], + account_reference: u32, +) -> Option<[u8; 43]> { + wallet + .identity() + .contact_shielded_address(owner, &Identifier::from(to), account_reference) + .await + .expect("the address is derived or left out") +} + +#[tokio::test] +async fn should_give_a_contact_the_address_of_the_prepared_identity_account() { + let (wallet, seed, id, coordinator) = fixture("contact_address_prepared", 15).await; + wallet + .prepare_shielded_identity_address(&seed, &id, &coordinator) + .await + .unwrap(); + + let to_bob = address_for(&wallet, &id, BOB, ACCOUNT_REFERENCE) + .await + .expect("an address for Bob"); + + // It is the address the identity's own shielded account derives for the request. + let account = shielded_identity_account_index(IDENTITY_INDEX).unwrap(); + let keys = OrchardKeySet::from_seed(&seed, Network::Testnet, account) + .unwrap() + .viewing_keys(); + assert_eq!( + to_bob, + keys.contact_address(id.as_bytes(), &BOB, u64::from(ACCOUNT_REFERENCE)) + .to_raw_address_bytes() + ); + + // The same request gives the same address; another contact, and the same contact + // under another account reference, get another. + assert_eq!( + address_for(&wallet, &id, BOB, ACCOUNT_REFERENCE).await, + Some(to_bob) + ); + let to_carol = address_for(&wallet, &id, CAROL, ACCOUNT_REFERENCE) + .await + .expect("an address for Carol"); + assert_ne!(to_carol, to_bob); + let rotated = address_for(&wallet, &id, BOB, ACCOUNT_REFERENCE + (1 << 28)) + .await + .expect("an address for the rotated request"); + assert_ne!(rotated, to_bob); +} + +#[tokio::test] +async fn should_send_no_address_until_the_identity_account_is_prepared() { + let (wallet, seed, id, coordinator) = fixture("contact_address_unprepared", 15).await; + // The account's keys are bound, but nothing in this session proved with the seed + // that the identity holds the slot the account belongs to. + let account = shielded_identity_account_index(IDENTITY_INDEX).unwrap(); + wallet + .bind_shielded(&seed[..], &[0, account], &coordinator) + .await + .unwrap(); + assert_eq!( + address_for(&wallet, &id, BOB, ACCOUNT_REFERENCE).await, + None + ); + + wallet + .prepare_shielded_identity_address(&seed, &id, &coordinator) + .await + .unwrap(); + assert!(address_for(&wallet, &id, BOB, ACCOUNT_REFERENCE) + .await + .is_some()); +} + +#[tokio::test] +async fn should_send_no_address_once_the_preparation_is_cleared() { + let (wallet, seed, id, coordinator) = fixture("contact_address_cleared", 15).await; + wallet + .prepare_shielded_identity_address(&seed, &id, &coordinator) + .await + .unwrap(); + assert!(address_for(&wallet, &id, BOB, ACCOUNT_REFERENCE) + .await + .is_some()); + + coordinator.clear().await.unwrap(); + assert_eq!( + address_for(&wallet, &id, BOB, ACCOUNT_REFERENCE).await, + None + ); +} + +#[tokio::test] +async fn should_send_no_address_where_contact_requests_cannot_carry_one() { + // Up to protocol version 14 the network's DashPay contract has no property for it. + let (wallet, seed, id, coordinator) = fixture("contact_address_before_v3", 14).await; + wallet + .prepare_shielded_identity_address(&seed, &id, &coordinator) + .await + .unwrap(); + + assert_eq!( + address_for(&wallet, &id, BOB, ACCOUNT_REFERENCE).await, + None + ); +} + +#[tokio::test] +async fn should_send_no_address_for_an_identity_the_wallet_does_not_hold() { + let (wallet, seed, id, coordinator) = fixture("contact_address_other_identity", 15).await; + wallet + .prepare_shielded_identity_address(&seed, &id, &coordinator) + .await + .unwrap(); + + assert_eq!( + address_for( + &wallet, + &Identifier::from([0x77; 32]), + BOB, + ACCOUNT_REFERENCE + ) + .await, + None + ); +} diff --git a/packages/rs-platform-wallet/src/wallet/shielded/keys.rs b/packages/rs-platform-wallet/src/wallet/shielded/keys.rs index 5fcde3530e0..cf19afcdc5a 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/keys.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/keys.rs @@ -289,12 +289,24 @@ impl AccountViewingKeys { to_user_id: &[u8; 32], account_reference: u64, ) -> PaymentAddress { - let index_key = shielded_contact_index_key(&self.to_fvk_bytes()); - let index = shielded_contact_index(&index_key, owner_id, to_user_id, account_reference); + let index = self.contact_index(owner_id, to_user_id, account_reference); self.full_viewing_key .address_at(DiversifierIndex::from(index), Scope::External) } + /// The diversifier index of [`Self::contact_address`] for the same request. Two + /// requests get the same address exactly when they get the same index, so a wallet + /// compares indices, which cost a hash, to check a new request against earlier ones. + pub fn contact_index( + &self, + owner_id: &[u8; 32], + to_user_id: &[u8; 32], + account_reference: u64, + ) -> [u8; SHIELDED_DIVERSIFIER_INDEX_LEN] { + let index_key = shielded_contact_index_key(&self.to_fvk_bytes()); + shielded_contact_index(&index_key, owner_id, to_user_id, account_reference) + } + /// The diversifier index a payment address sits at in this account, when it lies /// in the range per-contact addresses use: `None` for an address of another /// account and for one below that range, such as the profile address. diff --git a/packages/rs-platform-wallet/src/wallet/shielded/mod.rs b/packages/rs-platform-wallet/src/wallet/shielded/mod.rs index 9f4f49c2de0..4250650fb3d 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/mod.rs @@ -40,6 +40,9 @@ pub mod balance; mod balance_tests; #[cfg(test)] mod cancelled_scan_tests; +pub(crate) mod contact_address; +#[cfg(test)] +mod contact_address_tests; pub mod coordinator; pub mod file_store; #[cfg(test)] @@ -71,6 +74,7 @@ pub use balance::{ ShieldedBalanceSource, ShieldedLocalAccountBalance, ShieldedLocalBalanceSnapshot, ShieldedLocalBalanceState, }; +pub(crate) use contact_address::ContactShieldedAddresses; pub use coordinator::NetworkShieldedCoordinator; pub use file_store::{FileBackedShieldedStore, FileShieldedStoreError}; pub use keys::{AccountViewingKeys, OrchardKeySet}; diff --git a/packages/rs-platform-wallet/src/wallet/shielded/tips.rs b/packages/rs-platform-wallet/src/wallet/shielded/tips.rs index 2a4a1a54f18..f004c247bb2 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/tips.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/tips.rs @@ -24,6 +24,15 @@ pub(crate) struct PreparedTipAccount { } impl PreparedTipAccount { + /// The prepared account, while the preparation stands: its coordinator is alive + /// and has not been cleared since. + pub(crate) fn standing_account(&self) -> Option { + self.coordinator + .upgrade() + .is_some_and(|coordinator| coordinator.clear_generation() == self.clear_generation) + .then_some(self.account) + } + pub(crate) fn coordinator(&self) -> Option> { self.coordinator.upgrade() } diff --git a/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs b/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs index 770f20ec431..e5dbdb00d23 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs @@ -37,7 +37,7 @@ use crate::wallet::shielded::{ /// counted so the test can assert the seedless path actually read /// persistence rather than short-circuiting. #[derive(Default)] -struct CapturingPersistence { +pub(super) struct CapturingPersistence { stored: Mutex>, durability_events: Mutex>, fail_flush: std::sync::atomic::AtomicBool, @@ -156,7 +156,7 @@ impl PlatformWalletPersistence for CapturingPersistence { } /// Unique temp directory for a test's SQLite tree (no `tempfile` dev-dep). -fn temp_dir(tag: &str) -> PathBuf { +pub(super) fn temp_dir(tag: &str) -> PathBuf { let nanos = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() @@ -164,7 +164,7 @@ fn temp_dir(tag: &str) -> PathBuf { std::env::temp_dir().join(format!("viewing_key_bind_test_{tag}_{nanos}")) } -fn coordinator_at(dir: &std::path::Path) -> Arc { +pub(super) fn coordinator_at(dir: &std::path::Path) -> Arc { std::fs::create_dir_all(dir).expect("create temp dir"); let db_path = dir.join("tree.sqlite"); let store = FileBackedShieldedStore::open_path(&db_path, 100).expect("open file store"); @@ -1183,7 +1183,7 @@ async fn fresh_address_and_own_check_follow_the_bound_account() { /// The MASTER authentication key this seed derives for `identity_index` on /// testnet, as an identity public-key map: what discovery and registration /// leave on a wallet-owned identity, and what tip preparation verifies. -fn seed_master_key( +pub(super) fn seed_master_key( seed: &[u8], identity_index: u32, ) -> BTreeMap { diff --git a/packages/rs-sdk-cxx/src/client.rs b/packages/rs-sdk-cxx/src/client.rs index 2d37a2cf3dd..c017186019b 100644 --- a/packages/rs-sdk-cxx/src/client.rs +++ b/packages/rs-sdk-cxx/src/client.rs @@ -560,6 +560,7 @@ impl PlatformClient { recipient_key_index: input.recipient_key_index, account_reference: input.account_reference, account_label: (!input.account_label.is_empty()).then_some(input.account_label), + shielded_address: None, auto_accept_proof: None, }; let sent = sdk diff --git a/packages/rs-sdk/src/platform/dashpay/contact_request.rs b/packages/rs-sdk/src/platform/dashpay/contact_request.rs index 0859c649f01..28d295e16d1 100644 --- a/packages/rs-sdk/src/platform/dashpay/contact_request.rs +++ b/packages/rs-sdk/src/platform/dashpay/contact_request.rs @@ -9,6 +9,8 @@ use crate::platform::Document; use crate::{Error, Sdk}; use dpp::data_contract::accessors::v0::DataContractV0Getters; use dpp::data_contract::document_type::accessors::DocumentTypeV0Getters; +use dpp::data_contract::document_type::DocumentTypeRef; +use dpp::data_contract::DataContract; use dpp::document::DocumentV0; use dpp::identity::accessors::IdentityGettersV0; use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; @@ -21,10 +23,16 @@ use dpp::secp256k1::rand::rngs::StdRng; use dpp::secp256k1::rand::{Rng, RngCore, SeedableRng}; use dpp::secp256k1::{PublicKey, SecretKey}; use dpp::state_transition::StateTransition; +use dpp::version::feature_initial_protocol_versions::DASHPAY_CONTACT_REQUEST_SHIELDED_ADDRESS_INITIAL_PROTOCOL_VERSION; use platform_encryption::{ - derive_shared_key_ecdh, encrypt_account_label, encrypt_extended_public_key, COMPACT_XPUB_LEN, + derive_shared_key_ecdh, encrypt_account_label, encrypt_extended_public_key, + encrypt_shielded_address, COMPACT_XPUB_LEN, SHIELDED_ADDRESS_LEN, }; use std::collections::BTreeMap; +use std::sync::Arc; + +/// The `contactRequest` property that carries the sender's shielded payment address. +const ENCRYPTED_SHIELDED_ADDRESS: &str = "encryptedShieldedAddress"; /// ECDH provider for contact request encryption /// @@ -103,6 +111,36 @@ pub struct ContactRequestInput { pub account_label: Option, /// Optional auto-accept proof (38-102 bytes) - not encrypted pub auto_accept_proof: Option>, + /// The sender's shielded payment address for this contact: 43 raw bytes, the address + /// the sender's wallet derives for this request alone. The SDK encrypts it as + /// `encryptedShieldedAddress`. `None` sends the request without one. + pub shielded_address: Option<[u8; SHIELDED_ADDRESS_LEN]>, +} + +/// A contact request's `encryptedShieldedAddress`: `address` under the request's shared key +/// and an IV drawn for this field alone. +/// +/// Refused when the network's `contactRequest` type has no such property. It gains it with +/// DashPay v3 at protocol version 15, and consensus refuses a request that carries it before +/// then, so there the caller sends the request without an address. +fn encrypted_shielded_address( + contact_request_document_type: DocumentTypeRef, + shared_key: &[u8; 32], + address: &[u8; SHIELDED_ADDRESS_LEN], + rng: &mut impl RngCore, +) -> Result, Error> { + if !contact_request_document_type + .properties() + .contains_key(ENCRYPTED_SHIELDED_ADDRESS) + { + return Err(Error::Generic(format!( + "the DashPay contract of this network has no {ENCRYPTED_SHIELDED_ADDRESS} on \ + contact requests; it is added at protocol version 15" + ))); + } + let mut iv = [0u8; 16]; + rng.fill_bytes(&mut iv); + Ok(encrypt_shielded_address(shared_key, &iv, address).to_vec()) } /// Result of creating a contact request document @@ -417,7 +455,9 @@ impl Sdk { }; // Fetch DashPay contract - let dashpay_contract = self.fetch_dashpay_contract().await?; + let dashpay_contract = self + .dashpay_contract_for_contact_request(input.shielded_address.is_some()) + .await?; // Get contactRequest document type let contact_request_document_type = dashpay_contract @@ -430,6 +470,19 @@ impl Sdk { let mut rng = StdRng::from_os_rng(); let entropy = Bytes32::new(rng.random()); + // Encrypt the shielded address if provided, under an IV of its own + let encrypted_shielded_address = input + .shielded_address + .map(|address| { + encrypted_shielded_address( + contact_request_document_type, + &shared_key, + &address, + &mut rng, + ) + }) + .transpose()?; + // Generate document ID let sender_id = input.sender_identity.id().to_owned(); let document_id = Document::generate_document_id_v0( @@ -470,6 +523,12 @@ impl Sdk { if let Some(proof) = input.auto_accept_proof { properties.insert("autoAcceptProof".to_string(), Value::Bytes(proof)); } + if let Some(address) = encrypted_shielded_address { + properties.insert( + ENCRYPTED_SHIELDED_ADDRESS.to_string(), + Value::Bytes(address), + ); + } // Return the essential fields for the contact request, including the // entropy that derived `document_id` so the broadcast path can reuse it. @@ -481,6 +540,27 @@ impl Sdk { }) } + /// The DashPay contract a contact request is built against. + /// + /// For a request that carries a shielded address the SDK first learns the network's + /// protocol version. An unpinned SDK starts below 15 and takes the context provider's + /// DashPay at its own version, which has no property for the address, so the request + /// would be refused on a network that accepts it. A request without an address resolves + /// the contract as before, with no extra read. + async fn dashpay_contract_for_contact_request( + &self, + with_shielded_address: bool, + ) -> Result, Error> { + if with_shielded_address { + self.require_protocol_version( + DASHPAY_CONTACT_REQUEST_SHIELDED_ADDRESS_INITIAL_PROTOCOL_VERSION, + "a contact request's shielded address", + ) + .await?; + } + self.fetch_dashpay_contract().await + } + /// Send a contact request to the platform /// /// This creates a contact request document with automatic ECDH encryption and submits it @@ -638,6 +718,57 @@ mod tests { use super::*; use dpp::secp256k1; use dpp::secp256k1::rand::{self, RngCore}; + use dpp::system_data_contracts::{load_system_data_contract, SystemDataContract}; + use dpp::version::PlatformVersion; + use platform_encryption::decrypt_shielded_address; + + fn dashpay(platform_version: &PlatformVersion) -> DataContract { + load_system_data_contract(SystemDataContract::Dashpay, platform_version) + .expect("the DashPay contract loads") + } + + #[test] + fn should_encrypt_a_shielded_address_for_a_dashpay_v3_contact_request() { + let contract = dashpay(PlatformVersion::latest()); + let contact_request = contract + .document_type_for_name("contactRequest") + .expect("contactRequest"); + let shared_key = [7u8; 32]; + let address = [3u8; SHIELDED_ADDRESS_LEN]; + let mut rng = StdRng::seed_from_u64(1); + + let first = encrypted_shielded_address(contact_request, &shared_key, &address, &mut rng) + .expect("DashPay v3 carries the address"); + let second = encrypted_shielded_address(contact_request, &shared_key, &address, &mut rng) + .expect("DashPay v3 carries the address"); + + // What the contract accepts for the property: an IV and three AES blocks. + assert_eq!(first.len(), 64); + assert_eq!( + decrypt_shielded_address(&shared_key, &first).expect("the field decrypts"), + address + ); + // Each call draws its own IV, so the same address never encrypts the same way twice. + assert_ne!(first[..16], second[..16]); + assert_ne!(first, second); + } + + #[test] + fn should_refuse_a_shielded_address_where_contact_requests_have_no_such_property() { + let contract = dashpay(PlatformVersion::get(14).expect("protocol version 14")); + let contact_request = contract + .document_type_for_name("contactRequest") + .expect("contactRequest"); + let mut rng = StdRng::seed_from_u64(1); + + assert!(encrypted_shielded_address( + contact_request, + &[7u8; 32], + &[3u8; SHIELDED_ADDRESS_LEN], + &mut rng + ) + .is_err()); + } #[test] fn test_ecdh_encryption_produces_correct_size() { @@ -847,4 +978,67 @@ mod tests { "Both parties should derive the same shared secret" ); } + + /// The SDK's protocol version and whether the contract it resolves for a contact + /// request gives the request a shielded address property. + #[cfg(feature = "mocks")] + async fn resolved_schema(sdk: &Sdk, with_shielded_address: bool) -> (u32, bool) { + let contract = sdk + .dashpay_contract_for_contact_request(with_shielded_address) + .await + .expect("the DashPay contract"); + let carries_address = contract + .document_type_for_name("contactRequest") + .expect("contactRequest") + .properties() + .contains_key(ENCRYPTED_SHIELDED_ADDRESS); + (sdk.protocol_version_number(), carries_address) + } + + /// An SDK seeded below protocol version 15 on a network running the latest version: + /// asked for a request with a shielded address, it learns the network's version first, + /// so the contract it resolves has the property for the address. + #[cfg(feature = "mocks")] + #[tokio::test] + async fn should_learn_the_network_version_before_resolving_the_schema_of_a_shielded_address() { + let directory = tempfile::tempdir().expect("a mock dump directory"); + let mut sdk: Sdk = crate::SdkBuilder::new_mock() + .with_initial_version(PlatformVersion::get(14).expect("protocol version 14")) + .with_dump_dir(directory.path()) + .build() + .expect("a mock sdk"); + crate::sdk::test::expect_epoch_refresh(&mut sdk).await; + let current = dashpay(PlatformVersion::latest()); + sdk.mock() + .expect_fetch(current.id(), Some(current.clone())) + .await + .expect("the DashPay fetch is expected"); + + assert_eq!( + resolved_schema(&sdk, true).await, + (PlatformVersion::latest().protocol_version, true) + ); + } + + /// A request without an address resolves the contract as before. No answer to a + /// version lookup is staged here, so the call succeeds only if it makes none. + #[cfg(feature = "mocks")] + #[tokio::test] + async fn should_resolve_the_schema_of_a_request_without_an_address_at_the_seeded_version() { + let seeded = PlatformVersion::get(14).expect("protocol version 14"); + let directory = tempfile::tempdir().expect("a mock dump directory"); + let mut sdk: Sdk = crate::SdkBuilder::new_mock() + .with_initial_version(seeded) + .with_dump_dir(directory.path()) + .build() + .expect("a mock sdk"); + let held = dashpay(seeded); + sdk.mock() + .expect_fetch(held.id(), Some(held.clone())) + .await + .expect("the DashPay fetch is expected"); + + let (_, carries_address) = resolved_schema(&sdk, false).await; + assert!(!carries_address, "the contract resolved is the one held"); + } }