diff --git a/Cargo.lock b/Cargo.lock index 0e8eb8766..1bc0faa7e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2216,6 +2216,7 @@ dependencies = [ "native-dialog", "nix", "objc2 0.6.5", + "platform-encryption", "platform-wallet", "platform-wallet-storage", "qrcode", diff --git a/Cargo.toml b/Cargo.toml index 91877f0e4..ff24dda2c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -46,6 +46,9 @@ platform-wallet-storage = { git = "https://github.com/dashpay/platform", rev = " "shielded", "serde", ] } +# DIP-15 contactInfo AES primitives for the host-side `ContactCryptoProvider`; +# the same crate platform-wallet seals and opens with. +platform-encryption = { git = "https://github.com/dashpay/platform", rev = "575d961fe0c54bd7e01a3cf3823494e58c6c4fdb" } zip32 = "0.2.1" grovestark = { git = "https://www.github.com/dashpay/grovestark", rev = "5b9e289cca54c79b1305d5f4f40bf1148f1eb0e3" } rayon = "1.12.0" diff --git a/docs/user-stories.md b/docs/user-stories.md index b8ca7239b..73d24fce0 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -1120,12 +1120,14 @@ As a user, I want to edit contact details (nickname, note, hidden status) so tha - Set custom nickname and personal notes per contact. - Toggle contact visibility (hidden/visible). - Hidden contacts stay listed in a collapsed "Show hidden contacts" section of the Identity Hub - Contacts tab, and can be unhidden from there — including contacts hidden as a side effect of - declining or cancelling a request. If another client saved details this app cannot read, the app - warns that continuing will replace those details and asks for confirmation before unhiding. + Contacts tab, and can be unhidden from there. +- Declining a received request or withdrawing a sent one is recorded on this device only and + publishes nothing. - The Identity Hub contact details edit the private note, which is saved encrypted on Dash - Platform; a conservative fee estimate is shown before saving, and the saved note loads with - the contact from the network. Hub notes are not copied to the local memo: offline views and + Platform in the DashPay (DIP-0015) format other DashPay clients read; a conservative fee + estimate is shown before saving, and the saved note loads with the contact from the network. + Until the identity has two contacts, details are kept on this device only, and the app says so; + saving them again after that publishes them. Details saved by older versions of this app still show until replaced. Hub notes are not copied to the local memo: offline views and legacy DashPay screens can continue to show an older local note. - Edits made through the legacy contact-details screen persist in its local memo. @@ -1170,7 +1172,7 @@ As a user, I want to cancel a contact request I sent so that it stops sitting in - A DashPay contact request is immutable on Platform and cannot be deleted, so cancelling cannot un-send it. The UI states this plainly rather than implying a withdrawal. - Cancelling re-checks the request against the network first: it must still exist, must have been sent by the acting identity, and must not have already been answered. -- Cancelling publishes a hidden contact-info document and records the withdrawal locally, so the request leaves the sent list and stays gone across restarts. +- Cancelling records the withdrawal on this device only and publishes nothing, so the request leaves the sent list and stays gone across restarts. - A request the other person already accepted is reported as an established contact instead of being cancelled. --- diff --git a/src/backend_task/dashpay.rs b/src/backend_task/dashpay.rs index 9ecf9aba8..13de552a1 100644 --- a/src/backend_task/dashpay.rs +++ b/src/backend_task/dashpay.rs @@ -4,8 +4,6 @@ use crate::context::AppContext; use dash_sdk::Sdk; use std::sync::Arc; -pub mod auto_accept_handler; -pub mod auto_accept_proof; pub mod avatar_processing; pub mod contact_info; pub mod contact_requests; @@ -19,7 +17,7 @@ pub mod validation; pub use contacts::ContactData; -use crate::model::dashpay::{ContactInfoUpdate, UnreadableContactInfoPolicy}; +use crate::model::dashpay::ContactInfoUpdate; use crate::model::qualified_identity::QualifiedIdentity; use dash_sdk::dpp::identity::accessors::IdentityGettersV0; use dash_sdk::dpp::platform_value::string_encoding::Encoding; @@ -70,6 +68,12 @@ pub enum DashPayTask { identity: QualifiedIdentity, contact_id: Identifier, }, + /// Read the nickname, note and hidden flag shown for one contact, with + /// the same precedence as the contacts list (published first). + LoadContactDetails { + identity: QualifiedIdentity, + contact_id: Identifier, + }, /// Fetch an avatar image for a URL, consulting and populating the DET avatar /// disk cache. Off the egui frame loop; the result flows back to the /// screen's [`AvatarCache`](crate::ui::state::avatar_cache::AvatarCache). @@ -85,31 +89,32 @@ pub enum DashPayTask { to_username: String, account_label: Option, }, + /// Send a contact request to the owner of a scanned contact QR code, + /// carrying the `autoAcceptProof` the code's key signs, so the owner's + /// wallet can accept it without asking. SendContactRequestWithProof { identity: QualifiedIdentity, signing_key: IdentityPublicKey, - to_identity_id: Identifier, - account_label: Option, - qr_auto_accept: crate::backend_task::dashpay::auto_accept_proof::AutoAcceptProofData, + qr_code: crate::model::dashpay_contact_qr::ContactQrCode, }, AcceptContactRequest { identity: QualifiedIdentity, request_id: Identifier, }, + /// Decline a contact request this identity received. Local only: the + /// sender is ignored on this device and nothing is published. RejectContactRequest { identity: QualifiedIdentity, request_id: Identifier, - unreadable: UnreadableContactInfoPolicy, }, /// Withdraw a still-pending contact request this identity sent. /// /// Platform cannot delete a `contactRequest` document, so the handler - /// broadcasts a hidden `contactInfo` and records the withdrawal locally — - /// see [`contact_requests::cancel_contact_request`]. + /// records the withdrawal on this device only — see + /// [`contact_requests::cancel_contact_request`]. CancelContactRequest { identity: QualifiedIdentity, request_id: Identifier, - unreadable: UnreadableContactInfoPolicy, }, LoadPaymentHistory { identity: QualifiedIdentity, @@ -138,13 +143,12 @@ pub enum DashPayTask { DetectIncomingContactPayments { outputs: Vec, }, - /// Build an auto-accept contact QR payload. Resolves the ENCRYPTION key and - /// derives the auto-accept key through the JIT chokepoint in the backend, so - /// the UI never reads a seed. + /// Build a contact QR code (DIP-0015 auto-accept) for `identity`, valid + /// for one hour. platform-wallet builds it; the auto-accept key comes from + /// the identity's wallet seed through the secret seam, so the UI never + /// reads a seed. GenerateAutoAcceptQrCode { identity: QualifiedIdentity, - account_reference: u32, - validity_hours: u32, }, } @@ -182,6 +186,10 @@ impl AppContext { identity, contact_id, } => Ok(profile::fetch_contact_profile(self, sdk, identity, contact_id).await?), + DashPayTask::LoadContactDetails { + identity, + contact_id, + } => Ok(contact_info::load_contact_details(self, sdk, identity, contact_id).await?), DashPayTask::FetchAvatar { url } => { let bytes = avatar_processing::fetch_avatar_cached(self, &url).await; Ok(BackendTaskSuccessResult::DashPayAvatar { url, bytes }) @@ -206,20 +214,30 @@ impl AppContext { DashPayTask::SendContactRequestWithProof { identity, signing_key, - to_identity_id, - account_label, - qr_auto_accept, - } => Ok(contact_requests::send_contact_request_with_proof( - self, - sdk, - identity, - signing_key, - to_identity_id - .to_string(dash_sdk::dpp::platform_value::string_encoding::Encoding::Base58), - account_label, - Some(qr_auto_accept), - ) - .await?), + qr_code, + } => { + let current_time = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_err(|_| DashPayError::SystemClockInvalid)? + .as_secs(); + if qr_code.is_expired_at(current_time) { + return Err(DashPayError::QrCodeExpired { + expired_at: u64::from(qr_code.expires_at()), + current_time, + } + .into()); + } + Ok(contact_requests::send_contact_request_with_proof( + self, + sdk, + identity, + signing_key, + qr_code.full_username(), + None, + Some(qr_code), + ) + .await?) + } DashPayTask::AcceptContactRequest { identity, request_id, @@ -232,27 +250,21 @@ impl AppContext { DashPayTask::RejectContactRequest { identity, request_id, - unreadable, - } => contact_requests::reject_contact_request( - self, sdk, identity, request_id, unreadable, - ) - .await - .map_err(|source| TaskError::DashPayContactRequestActionFailed { - request_id, - source: Box::new(source), - }), + } => contact_requests::reject_contact_request(self, sdk, identity, request_id) + .await + .map_err(|source| TaskError::DashPayContactRequestActionFailed { + request_id, + source: Box::new(source), + }), DashPayTask::CancelContactRequest { identity, request_id, - unreadable, - } => contact_requests::cancel_contact_request( - self, sdk, identity, request_id, unreadable, - ) - .await - .map_err(|source| TaskError::DashPayContactRequestActionFailed { - request_id, - source: Box::new(source), - }), + } => contact_requests::cancel_contact_request(self, sdk, identity, request_id) + .await + .map_err(|source| TaskError::DashPayContactRequestActionFailed { + request_id, + source: Box::new(source), + }), DashPayTask::LoadPaymentHistory { identity } => { let identity_id = identity.identity.id(); // Refresh-style action: kick upstream before reading so the @@ -375,20 +387,15 @@ impl AppContext { )) } } - DashPayTask::GenerateAutoAcceptQrCode { - identity, - account_reference, - validity_hours, - } => { - let proof = auto_accept_proof::generate_auto_accept_proof( - &identity, - account_reference, - validity_hours, - ) - .await?; - Ok(BackendTaskSuccessResult::DashPayAutoAcceptQrCode( - proof.to_qr_string(), - )) + DashPayTask::GenerateAutoAcceptQrCode { identity } => { + // An empty name lets platform-wallet look the username up on + // Platform, for identities whose names are not cached here. + let username = self.main_username(&identity).unwrap_or_default(); + let qr = self + .wallet_backend()? + .dashpay_build_contact_qr(&identity, &username) + .await?; + Ok(BackendTaskSuccessResult::DashPayAutoAcceptQrCode(qr)) } } } diff --git a/src/backend_task/dashpay/auto_accept_handler.rs b/src/backend_task/dashpay/auto_accept_handler.rs deleted file mode 100644 index 95781088a..000000000 --- a/src/backend_task/dashpay/auto_accept_handler.rs +++ /dev/null @@ -1,117 +0,0 @@ -use crate::backend_task::dashpay::auto_accept_proof::verify_auto_accept_proof; -use crate::backend_task::dashpay::contact_request_query; -use crate::backend_task::dashpay::contact_requests::accept_contact_request; -use crate::backend_task::error::TaskError; -use crate::context::AppContext; -use crate::model::qualified_identity::QualifiedIdentity; -use dash_sdk::Sdk; -use dash_sdk::dpp::document::DocumentV0Getters; -use dash_sdk::dpp::identity::accessors::IdentityGettersV0; -use dash_sdk::dpp::platform_value::Value; -use dash_sdk::dpp::platform_value::string_encoding::Encoding; -use dash_sdk::drive::query::{OrderClause, WhereClause, WhereOperator}; -use dash_sdk::platform::{Document, FetchMany, Identifier}; -use std::sync::Arc; - -/// Process incoming contact requests and check for autoAcceptProof -/// -/// This function checks all incoming contact requests for valid autoAcceptProof -/// and automatically accepts and reciprocates if the proof is valid. -pub async fn process_auto_accept_requests( - app_context: &Arc, - sdk: &Sdk, - identity: QualifiedIdentity, -) -> Result, TaskError> { - let identity_id = identity.identity.id(); - - // Query for incoming contact requests - let mut incoming_query = contact_request_query(app_context)?; - - incoming_query = incoming_query.with_where(WhereClause { - field: "toUserId".to_string(), - operator: WhereOperator::Equal, - value: Value::Identifier(identity_id.to_buffer()), - }); - - // Add orderBy to avoid platform bug - incoming_query = incoming_query.with_order_by(OrderClause { - field: "$createdAt".to_string(), - ascending: true, - }); - incoming_query.limit = 100; - - let incoming_docs = Document::fetch_many(sdk, incoming_query).await?; - - // Stateless verification; no stored proofs needed - - let mut auto_accepted_requests = Vec::new(); - - for (request_id, doc) in incoming_docs { - if let Some(doc) = doc { - let from_id = doc.owner_id(); - let props = doc.properties(); - - // Check if this request has an autoAcceptProof - if let Some(Value::Bytes(proof_data)) = props.get("autoAcceptProof") { - tracing::debug!( - "Found contact request with autoAcceptProof from {}", - from_id.to_string(Encoding::Base58) - ); - - // Extract accountReference for message construction (default to 0 if missing) - let account_reference = props - .get("accountReference") - .and_then(|value| value.to_integer::().ok()) - .unwrap_or_default(); - - // Verify the proof per DIP-0015 - match verify_auto_accept_proof( - proof_data, - from_id, - identity.identity.id(), - &identity, - account_reference, - ) - .await - { - Ok(true) => { - tracing::debug!( - "Valid autoAcceptProof, auto-accepting contact request from {}", - from_id.to_string(Encoding::Base58) - ); - - // Accept the request (which sends a reciprocal request) - match accept_contact_request(app_context, sdk, identity.clone(), request_id) - .await - { - Ok(_) => { - auto_accepted_requests.push((from_id, true)); - - // Stateless: no persistence required - } - Err(e) => { - tracing::error!("Failed to auto-accept contact request: {}", e); - auto_accepted_requests.push((from_id, false)); - } - } - } - Ok(false) => { - tracing::warn!( - "Invalid or expired autoAcceptProof from {}", - from_id.to_string(Encoding::Base58) - ); - } - Err(e) => { - tracing::error!("Failed to verify autoAcceptProof: {}", e); - } - } - } - } - } - - Ok(auto_accepted_requests) -} - -// No DB persistence required - -// Proof creation moved to contact_requests::send_contact_request_with_proof diff --git a/src/backend_task/dashpay/auto_accept_proof.rs b/src/backend_task/dashpay/auto_accept_proof.rs deleted file mode 100644 index 74b3cbd3c..000000000 --- a/src/backend_task/dashpay/auto_accept_proof.rs +++ /dev/null @@ -1,365 +0,0 @@ -use crate::backend_task::error::TaskError; -use crate::model::dashpay_derivation::derive_auto_accept_key; -use crate::model::qualified_identity::QualifiedIdentity; -use dash_sdk::dpp::dashcore::ecdsa::EcdsaSecretKey; -use dash_sdk::dpp::identity::accessors::IdentityGettersV0; -use dash_sdk::dpp::identity::{KeyType, Purpose, SecurityLevel}; -use dash_sdk::dpp::secp256k1::Message; -use dash_sdk::platform::Identifier; -use serde::{Deserialize, Serialize}; -use sha2::{Digest, Sha256}; -use std::collections::HashSet; - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct AutoAcceptProofData { - pub identity_id: Identifier, - pub proof_key: [u8; 32], - pub account_reference: u32, - pub expires_at: u64, // Unix timestamp -} - -impl AutoAcceptProofData { - pub fn to_qr_string(&self) -> String { - // Format according to DIP-0015: dash:?du={username}&dapk={key_data} - // Key data format: key_type (1 byte) + timestamp (4 bytes) + key_size (1 byte) + key (32 bytes) - let mut key_data = Vec::new(); - key_data.push(0u8); // Key type 0 for ECDSA_SECP256K1 - key_data.extend_from_slice(&(self.expires_at as u32).to_be_bytes()); // Timestamp/expiration - key_data.push(32u8); // Key size - key_data.extend_from_slice(&self.proof_key); // The actual key - - // Encode key data in base58 using dashcore's base58 implementation - let key_data_base58 = dash_sdk::dpp::platform_value::string_encoding::encode( - &key_data, - dash_sdk::dpp::platform_value::string_encoding::Encoding::Base58, - ); - - // For QR codes without username (identity-based) - format!( - "dash:?di={}&dapk={}", - self.identity_id - .to_string(dash_sdk::dpp::platform_value::string_encoding::Encoding::Base58), - key_data_base58 - ) - } - - pub fn from_qr_string(qr_data: &str) -> Result { - // Parse DIP-0015 format: dash:?du={username}&dapk={key_data} or dash:?di={identity}&dapk={key_data} - if !qr_data.starts_with("dash:?") { - return Err("Invalid QR code format - must start with 'dash:?'".to_string()); - } - - let query_string = &qr_data[6..]; // Skip "dash:?" - let mut identity_id = None; - let mut key_data_base58 = None; - let mut account_reference = 0u32; // Default to account 0 - - // Parse query parameters - for param in query_string.split('&') { - let parts: Vec<&str> = param.split('=').collect(); - if parts.len() != 2 { - continue; - } - - match parts[0] { - "di" => { - identity_id = Some( - Identifier::from_string( - parts[1], - dash_sdk::dpp::platform_value::string_encoding::Encoding::Base58, - ) - .map_err(|e| format!("Invalid identity ID: {}", e))?, - ) - } - "dapk" => { - key_data_base58 = Some(parts[1].to_string()); - } - "account" => { - account_reference = parts[1] - .parse::() - .map_err(|e| format!("Invalid account reference: {}", e))?; - } - _ => {} // Ignore unknown parameters - } - } - - let identity_id = identity_id.ok_or("Missing identity ID in QR code".to_string())?; - let key_data_base58 = - key_data_base58.ok_or("Missing proof key data in QR code".to_string())?; - - // Decode the key data from base58 - let key_data = dash_sdk::dpp::dashcore::base58::decode(&key_data_base58) - .map_err(|e| format!("Invalid base58 key data: {}", e))?; - - // Parse key data format: key_type (1) + timestamp (4) + key_size (1) + key (32-64) - if key_data.len() < 38 { - return Err("Key data too short".to_string()); - } - - let _key_type = key_data[0]; - let expires_at = - u32::from_be_bytes([key_data[1], key_data[2], key_data[3], key_data[4]]) as u64; - let key_size = key_data[5] as usize; - - if key_data.len() < 6 + key_size { - return Err("Invalid key data length".to_string()); - } - - let mut proof_key = [0u8; 32]; - if key_size == 32 { - proof_key.copy_from_slice(&key_data[6..38]); - } else { - return Err(format!("Unsupported key size: {}", key_size)); - } - - Ok(Self { - identity_id, - proof_key, - account_reference, - expires_at, - }) - } -} - -/// Generate an auto-accept proof for QR code sharing -/// -/// According to DIP-0015, the autoAcceptProof is a signature that allows the recipient -/// to automatically accept the contact request and send one back without user interaction. -pub async fn generate_auto_accept_proof( - identity: &QualifiedIdentity, - account_reference: u32, - validity_hours: u32, -) -> Result { - use crate::backend_task::dashpay::errors::DashPayError; - - // Calculate expiration timestamp - let expires_at = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map_err(|_| DashPayError::SystemClockInvalid)? - .as_secs() - + (validity_hours as u64 * 3600); - - // Get wallet seed for HD derivation - use ENCRYPTION key (ECDSA_SECP256K1) as per DIP-15 - // The auto-accept proof uses HD derivation from the wallet, and ENCRYPTION keys are ECDSA_SECP256K1 - let signing_key = identity - .identity - .get_first_public_key_matching( - Purpose::ENCRYPTION, - HashSet::from([SecurityLevel::MEDIUM]), - HashSet::from([KeyType::ECDSA_SECP256K1]), - false, - ) - .ok_or(DashPayError::MissingEncryptionKey)?; - - // Resolve the ENCRYPTION private key through the JIT chokepoint — no - // parked-seed read. - let wallet_seed = identity - .resolve_private_key_bytes(signing_key) - .await? - .map(|(_, private_key)| private_key) - .ok_or(TaskError::WalletLocked)?; - - // Determine network from the identity - let network = identity.network; - - // Derive the auto-accept key using DIP-0015 path: m/9'/coin'/16'/timestamp' - // Using expiration timestamp as the derivation index - let auto_accept_xprv = derive_auto_accept_key( - &wallet_seed[..], - network, - expires_at as u32, // Truncate to u32 for derivation - ) - .map_err(|e| TaskError::DashPay(DashPayError::from(e)))?; - - // Extract the private key bytes (32 bytes) - let proof_key = *auto_accept_xprv.private_key.to_bytes(); - - Ok(AutoAcceptProofData { - identity_id: identity.identity.id(), - proof_key, - account_reference, - expires_at, - }) -} - -/// Create the autoAcceptProof bytes for inclusion in a contact request -/// -/// Format according to DIP-0015: -/// - key type (1 byte) -/// - key index (4 bytes) - the timestamp used for derivation -/// - signature size (1 byte) -/// - signature (32-96 bytes) -pub fn create_auto_accept_proof_bytes_with_key( - expires_at: u64, - signing_key_bytes: &[u8; 32], - sender_id: &Identifier, - recipient_id: &Identifier, - account_reference: u32, -) -> Result, String> { - // Derive the auto-accept key - // Sign using the provided ephemeral key from the QR - - // Create the message to sign: ownerId + toUserId + accountReference - let mut message_data = Vec::new(); - message_data.extend_from_slice(&sender_id.to_buffer()); - message_data.extend_from_slice(&recipient_id.to_buffer()); - message_data.extend_from_slice(&account_reference.to_le_bytes()); - - // Hash the message - let mut hasher = Sha256::new(); - hasher.update(&message_data); - let message_hash = hasher.finalize(); - - // Sign the digest. The key erases itself when it drops. The signature is - // low-S with a low R ground as Dash Core grinds it; any ECDSA verifier - // accepts it. - let secret_key = EcdsaSecretKey::from_bytes(signing_key_bytes) - .map_err(|e| format!("Failed to create secret key: {}", e))?; - - let sig_bytes = secret_key.sign(&message_hash.into()).to_bytes(); - - // Build the proof bytes - let mut proof_bytes = Vec::new(); - proof_bytes.push(0u8); // Key type 0 for ECDSA_SECP256K1 - proof_bytes.extend_from_slice(&(expires_at as u32).to_be_bytes()); // Key index (timestamp) - proof_bytes.push(sig_bytes.len() as u8); // Signature size - proof_bytes.extend_from_slice(&sig_bytes); // The signature - - Ok(proof_bytes) -} - -/// Verify an auto-accept proof from a contact request -/// -/// This would be called when receiving a contact request with an autoAcceptProof field -/// to determine if we should automatically accept and reciprocate. -pub async fn verify_auto_accept_proof( - proof_data: &[u8], - sender_identity_id: Identifier, - recipient_identity_id: Identifier, - our_identity: &QualifiedIdentity, - account_reference: u32, -) -> Result { - // Parse: key type (1) | key index/timestamp (4) | sig size (1) | signature - if proof_data.len() < 6 { - return Ok(false); - } - let _key_type = proof_data[0]; - let key_index = - u32::from_be_bytes([proof_data[1], proof_data[2], proof_data[3], proof_data[4]]); - let sig_len = proof_data[5] as usize; - // Compact ECDSA signatures are exactly 64 bytes - if sig_len != 64 { - return Ok(false); - } - if proof_data.len() < 6 + sig_len { - return Ok(false); - } - let signature_bytes = &proof_data[6..6 + sig_len]; - - // Expiry check - let now = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map_err(|e| format!("Time error: {}", e))? - .as_secs(); - if now > key_index as u64 { - return Ok(false); - } - - // Message: ownerId + toUserId + accountReference - let mut message_data = Vec::new(); - message_data.extend_from_slice(&sender_identity_id.to_buffer()); - message_data.extend_from_slice(&recipient_identity_id.to_buffer()); - message_data.extend_from_slice(&account_reference.to_le_bytes()); - let mut hasher = Sha256::new(); - hasher.update(&message_data); - let message_hash = hasher.finalize(); - let message = Message::from_digest(message_hash.into()); - - // Derive expected pubkey from our seed and key index (timestamp) - // Use ENCRYPTION key (ECDSA_SECP256K1) for HD derivation as per DIP-15 - let signing_key = our_identity - .identity - .get_first_public_key_matching( - Purpose::ENCRYPTION, - HashSet::from([SecurityLevel::MEDIUM]), - HashSet::from([KeyType::ECDSA_SECP256K1]), - false, - ) - .ok_or("No suitable key found. This operation requires a MEDIUM security level ECDSA_SECP256K1 ENCRYPTION key.")?; - // Resolve the ENCRYPTION private key through the JIT chokepoint — no - // parked-seed read. - let wallet_seed = our_identity - .resolve_private_key_bytes(signing_key) - .await - .map_err(|e| format!("Error resolving private key: {}", e))? - .map(|(_, private_key)| private_key) - .ok_or("Private key not found")?; - let xprv = derive_auto_accept_key(&wallet_seed[..], our_identity.network, key_index) - .map_err(|e| format!("Failed to derive auto-accept key: {}", e))?; - let pubkey = dash_sdk::dpp::secp256k1::PublicKey::from(xprv.private_key.public_key()); - let sig = dash_sdk::dpp::secp256k1::ecdsa::Signature::from_compact(signature_bytes) - .map_err(|e| format!("Invalid signature bytes: {}", e))?; - - match dash_sdk::dpp::secp256k1::ecdsa::verify(&sig, message, &pubkey) { - Ok(_) => Ok(true), - Err(_) => Ok(false), - } -} - -// No local persistence required - -#[cfg(test)] -mod tests { - use super::*; - use dash_sdk::dpp::secp256k1::{PublicKey, SecretKey, ecdsa}; - - /// The proof's signature verifies, the way `verify_auto_accept_proof` - /// checks it, against the public key of the key it was signed with. The - /// signature is low-S with a low R ground as Dash Core grinds it; R lands - /// low half the time on its own, so this signs for many accounts. - #[test] - fn proof_signature_verifies_and_has_low_r() { - let key_bytes = crate::test_support::keys::secret_bytes(); - let public_key = - PublicKey::from_secret_key(&SecretKey::from_secret_bytes(key_bytes).expect("valid")); - let sender = Identifier::from([0x01; 32]); - let recipient = Identifier::from([0x02; 32]); - let expires_at = 1_900_000_000u64; - - for account_reference in 0..32u32 { - let proof = create_auto_accept_proof_bytes_with_key( - expires_at, - &key_bytes, - &sender, - &recipient, - account_reference, - ) - .expect("proof"); - - assert_eq!(proof[0], 0, "key type"); - assert_eq!( - &proof[1..5], - &(expires_at as u32).to_be_bytes(), - "key index" - ); - assert_eq!(proof[5], 64, "signature size"); - assert_eq!(proof.len(), 6 + 64); - - let mut message_data = Vec::new(); - message_data.extend_from_slice(&sender.to_buffer()); - message_data.extend_from_slice(&recipient.to_buffer()); - message_data.extend_from_slice(&account_reference.to_le_bytes()); - let digest: [u8; 32] = Sha256::digest(&message_data).into(); - - let signature = ecdsa::Signature::from_compact(&proof[6..]).expect("compact"); - let mut normalized = signature; - normalized.normalize_s(); - assert_eq!(normalized, signature, "high S for {account_reference}"); - assert!( - ecdsa::verify(&signature, Message::from_digest(digest), &public_key).is_ok(), - "proof does not verify for {account_reference}" - ); - assert!(proof[6] < 0x80, "R is not low for {account_reference}"); - } - } -} diff --git a/src/backend_task/dashpay/contact_info.rs b/src/backend_task/dashpay/contact_info.rs index 24ccbbd6e..49988566b 100644 --- a/src/backend_task/dashpay/contact_info.rs +++ b/src/backend_task/dashpay/contact_info.rs @@ -1,457 +1,27 @@ +//! Contact details (DIP-0015 `contactInfo`). +//! +//! platform-wallet writes and syncs the identity's `contactInfo` documents. +//! This module keeps the paginated document fetch the read of older, +//! legacy-key documents uses, the reader for those documents' payloads, and +//! turns a field-level update into the full set of details platform-wallet +//! publishes. + use crate::backend_task::BackendTaskSuccessResult; -use crate::backend_task::dashpay::errors::DashPayError; -use crate::backend_task::error::{ContactInfoReadError, TaskError}; +use crate::backend_task::error::TaskError; use crate::context::AppContext; -use crate::model::dashpay::{ - AcceptedAccounts, ContactInfoField, ContactInfoUpdate, UnreadableContactInfoPolicy, - validate_contact_note, -}; -use crate::model::document::new_document_for_creation; +use crate::model::dashpay::{ContactDetails, ContactInfoUpdate, validate_contact_note}; use crate::model::qualified_identity::QualifiedIdentity; -use aes_gcm::aes::Aes256; -use aes_gcm::aes::cipher::{BlockCipherEncrypt, KeyInit}; -use bip39::rand::{SeedableRng, rngs::StdRng}; -use cbc::cipher::{BlockModeEncrypt, KeyIvInit}; +use crate::wallet_backend::WalletBackend; use dash_sdk::Sdk; -use dash_sdk::dpp::data_contract::accessors::v0::DataContractV0Getters; -use dash_sdk::dpp::document::{DocumentV0Getters, DocumentV0Setters}; use dash_sdk::dpp::identity::accessors::IdentityGettersV0; -use dash_sdk::dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; -use dash_sdk::dpp::identity::{KeyType, Purpose, SecurityLevel}; -use dash_sdk::dpp::platform_value::{Bytes32, Value}; -use dash_sdk::drive::query::{OrderClause, WhereClause, WhereOperator}; -use dash_sdk::platform::documents::transitions::DocumentCreateTransitionBuilder; use dash_sdk::platform::proto::get_documents_request::get_documents_request_v0::Start; -use dash_sdk::platform::{Document, DocumentQuery, FetchMany, Identifier}; +use dash_sdk::platform::{DocumentQuery, Identifier}; use dash_sdk::query_types::Documents; -use platform_wallet::wallet::identity::crypto::ContactInfoPrivateData as UpstreamPrivateData; +use platform_wallet::wallet::identity::crypto::ContactInfoPrivateData; use platform_wallet::wallet::identity::crypto::contact_info::encode_private_data_bounded; -use std::collections::{BTreeMap, HashSet}; +use platform_wallet::wallet::identity::network::ContactInfoPublishOutcome; use std::future::Future; use std::sync::Arc; -use zeroize::Zeroizing; - -// ContactInfo private data structure -#[derive(Debug, Clone, Default, PartialEq, Eq)] -pub struct ContactInfoPrivateData { - pub version: u32, - pub alias_name: Option, - pub note: Option, - pub display_hidden: bool, - pub accepted_accounts: Vec, -} - -impl ContactInfoPrivateData { - pub fn new() -> Self { - Self::default() - } - - /// The plaintext floor platform-wallet pads to with zero bytes, so that - /// IV (16) + AES-CBC ciphertext reaches the contract's 48-byte minimum. - const MIN_PLAINTEXT_SIZE: usize = 17; - - /// The plaintext size older versions of this client (up to - /// v1.0.0-weekly.20261020) padded to: a `0x00` sentinel, then random bytes. - const LEGACY_PLAINTEXT_SIZE: usize = 16; - - /// Encode for encryption with platform-wallet's DIP-15 codec, so every - /// client that uses it reads what this one writes. - pub fn serialize(&self) -> Result, TaskError> { - let alias_len = self.alias_name.as_deref().map_or(0, str::len); - if alias_len > u8::MAX as usize { - return Err(DashPayError::ContactInfoValidationFailed { - errors: vec![format!("Nickname too long ({alias_len} bytes, max 255)")], - } - .into()); - } - validate_contact_note(self.note.as_deref().unwrap_or_default())?; - encode_private_data_bounded(&UpstreamPrivateData { - alias_name: self.alias_name.clone(), - note: self.note.clone(), - display_hidden: self.display_hidden, - accepted_accounts: self.accepted_accounts.clone(), - }) - .map_err(|source| TaskError::DashPayContactInfoEncoding { - source: Box::new(source), - }) - } - - /// Parse the plaintext produced by [`serialize`](Self::serialize), or by - /// an older version of this client. - /// - /// Returns `None` for a truncated or non-canonical v0 payload, invalid - /// UTF-8, or an unsupported version, and for trailing bytes that are not - /// padding (see [`Self::is_padding`]). - /// Stricter than platform-wallet's reader: a write must never drop fields - /// it cannot read. - /// - /// Also returns `None` for bytes that read completely both ways with - /// different values (see [`PrivateDataReading::Ambiguous`]), so a save - /// asks before overwriting them instead of persisting a guess. - pub fn deserialize(bytes: &[u8]) -> Option { - match Self::read(bytes) { - PrivateDataReading::Read(data) => Some(data), - PrivateDataReading::Ambiguous | PrivateDataReading::Unreadable => None, - } - } - - /// Read `bytes` both as CompactSize and as the single-byte layout older - /// versions wrote, and keep a result only when it is unambiguous. - fn read(bytes: &[u8]) -> PrivateDataReading { - match ( - Self::parse(bytes, LengthPrefix::SingleByte), - Self::parse(bytes, LengthPrefix::CompactSize), - ) { - (Some(legacy), Some(compact)) if legacy != compact => PrivateDataReading::Ambiguous, - (Some(data), _) | (None, Some(data)) => PrivateDataReading::Read(data), - (None, None) => PrivateDataReading::Unreadable, - } - } - - fn parse(bytes: &[u8], prefix: LengthPrefix) -> Option { - let version = u32::from_le_bytes(bytes.get(..4)?.try_into().ok()?); - if version != 0 { - return None; - } - let mut pos = 4; - // Whether a single-byte length took a value CompactSize reserves. - let mut reserved_length = false; - - let mut take_length = |pos: &mut usize| -> Option { - let first = *bytes.get(*pos)?; - if prefix == LengthPrefix::SingleByte { - reserved_length |= first >= 0xFD; - *pos += 1; - return Some(first.into()); - } - // A Bitcoin CompactSize length, in its shortest encoding only. - let field = |width: usize| bytes.get(*pos + 1..*pos + 1 + width); - let (value, width): (u64, usize) = match first { - 0xFD => (u16::from_le_bytes(field(2)?.try_into().ok()?).into(), 3), - 0xFE => (u32::from_le_bytes(field(4)?.try_into().ok()?).into(), 5), - 0xFF => (u64::from_le_bytes(field(8)?.try_into().ok()?), 9), - n => (n.into(), 1), - }; - let shortest = match width { - 3 => 0xFD, - 5 => 0x1_0000, - 9 => 0x1_0000_0000, - _ => 0, - }; - if value < shortest { - return None; - } - *pos += width; - usize::try_from(value).ok() - }; - let mut take_string = |pos: &mut usize| -> Option> { - let len = take_length(pos)?; - let raw = bytes.get(*pos..pos.checked_add(len)?)?; - *pos += len; - if len == 0 { - Some(None) - } else { - Some(Some(std::str::from_utf8(raw).ok()?.to_owned())) - } - }; - let alias_name = take_string(&mut pos)?; - let note = take_string(&mut pos)?; - - let display_hidden = match *bytes.get(pos)? { - 0 => false, - 1 => true, - _ => return None, - }; - pos += 1; - - let count = take_length(&mut pos)?; - let accepted_accounts = (0..count) - .map(|_| { - let raw = bytes.get(pos..pos + 4)?; - pos += 4; - Some(u32::from_le_bytes(raw.try_into().ok()?)) - }) - .collect::>>()?; - - let complete = match prefix { - LengthPrefix::CompactSize => Self::is_padding(bytes, pos), - // A payload without a reserved length reads the same both ways, so - // it is left to the CompactSize reader. One with such a length is - // over 255 bytes, which older versions never padded. - LengthPrefix::SingleByte => reserved_length && pos == bytes.len(), - }; - if !complete { - return None; - } - - Some(Self { - version, - alias_name, - note, - display_hidden, - accepted_accounts, - }) - } - - /// Whether `bytes[end..]`, after the last v0 field, is padding a known - /// writer adds: none, platform-wallet's zeros up to - /// [`Self::MIN_PLAINTEXT_SIZE`], or this client's former `0x00` sentinel - /// and random bytes up to exactly [`Self::LEGACY_PLAINTEXT_SIZE`]. - fn is_padding(bytes: &[u8], end: usize) -> bool { - match bytes[end..].split_first() { - None => true, - Some((0, _)) if bytes.len() == Self::LEGACY_PLAINTEXT_SIZE => true, - Some(_) => { - bytes.len() <= Self::MIN_PLAINTEXT_SIZE && bytes[end..].iter().all(|b| *b == 0) - } - } - } -} - -/// How a payload encodes string lengths and the account count. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum LengthPrefix { - /// DIP-15 Bitcoin CompactSize, in its shortest encoding. - CompactSize, - /// One byte, which older versions of this client wrote for lengths up to - /// 255. It differs from CompactSize only for 253 to 255, the CompactSize - /// prefix markers, so it is accepted only when such a length is present - /// and the payload ends exactly after the last field. - /// - /// Some bytes read completely both ways, with different values: a legacy - /// payload can also parse as CompactSize, and a 256+ byte field from - /// another client can also form a legacy payload. Such bytes are - /// [`PrivateDataReading::Ambiguous`]. What this client writes never is: - /// a 253 to 255-byte field is `FD xx 00` with `xx` in `FD..=FF`, never - /// valid UTF-8 as the first text byte, and a 253+ account count never - /// totals the same bytes both ways. - SingleByte, -} - -/// The outcome of reading a decrypted `privateData` payload. -#[derive(Debug)] -enum PrivateDataReading { - /// Exactly one reading succeeded, or both agree. - Read(ContactInfoPrivateData), - /// The CompactSize and single-byte readings both succeed with different - /// values, so neither can be trusted. - Ambiguous, - /// Neither reading succeeds. - Unreadable, -} - -/// Decode a decrypted `privateData` payload for display. -/// -/// This client's reader comes first, so the contact list shows every payload -/// a save can read with the same values, including the long nicknames and -/// notes older versions of this client wrote, which platform-wallet can -/// misread. An ambiguous payload is shown as unreadable, never as a guess. -/// platform-wallet's tolerant reader then covers what neither reading -/// accepts and a save will not rewrite, such as a newer minor version. -pub(super) fn decode_contact_info_details(plaintext: &[u8]) -> Option { - match ContactInfoPrivateData::read(plaintext) { - PrivateDataReading::Read(data) => Some(UpstreamPrivateData { - alias_name: data.alias_name, - note: data.note, - display_hidden: data.display_hidden, - accepted_accounts: data.accepted_accounts, - }), - PrivateDataReading::Ambiguous => None, - PrivateDataReading::Unreadable => { - platform_wallet::wallet::identity::crypto::decode_private_data(plaintext).ok() - } - } -} - -/// Apply an explicit whole-document update to the payload already on Platform. -fn apply_contact_info_update( - update: ContactInfoUpdate, - existing: Option<&Document>, - private_data_key: &[u8; 32], -) -> Result { - let preserves_existing = matches!(update.display_hidden, ContactInfoField::Preserve) - || matches!(update.nickname, ContactInfoField::Preserve) - || matches!(update.note, ContactInfoField::Preserve) - || matches!(update.accepted_accounts, AcceptedAccounts::Preserve); - - let mut data = if preserves_existing { - read_contact_info_private_data(existing, private_data_key, update.unreadable)? - } else { - ContactInfoPrivateData::new() - }; - - if let ContactInfoField::Replace(nickname) = update.nickname { - data.alias_name = nickname; - } - if let ContactInfoField::Replace(note) = update.note { - data.note = note; - } - if let ContactInfoField::Replace(hidden) = update.display_hidden { - data.display_hidden = hidden; - } - if let AcceptedAccounts::Replace(accounts) = update.accepted_accounts { - data.accepted_accounts = accounts; - } - Ok(data) -} - -fn read_contact_info_private_data( - existing: Option<&Document>, - private_data_key: &[u8; 32], - unreadable: UnreadableContactInfoPolicy, -) -> Result { - let Some(existing) = existing else { - return Ok(ContactInfoPrivateData::new()); - }; - let Some(value) = existing.properties().get("privateData") else { - return Ok(ContactInfoPrivateData::new()); - }; - let result = match value { - Value::Bytes(encrypted) => { - super::contacts::decrypt_private_data(encrypted, private_data_key) - .map_err(|_| ContactInfoReadError::DecryptFailed) - .and_then(|plaintext| { - ContactInfoPrivateData::deserialize(&plaintext) - .ok_or(ContactInfoReadError::DeserializeFailed) - }) - } - _ => Err(ContactInfoReadError::UnexpectedPrivateDataType), - }; - - match (result, unreadable) { - (Ok(data), _) => Ok(data), - (Err(_), UnreadableContactInfoPolicy::Overwrite) => Ok(ContactInfoPrivateData::new()), - (Err(source), UnreadableContactInfoPolicy::Abort) => { - Err(TaskError::DashPayContactInfoRead { source }) - } - } -} - -/// Derive the DIP-0015 contactInfo encryption keys for `identity`, fetching -/// the wallet's HD seed just-in-time through the [`SecretAccess`] chokepoint. -/// -/// The seed is obtained per-operation via -/// [`SecretAccess::with_secret`](crate::wallet_backend::SecretAccess::with_secret) -/// keyed by the identity's DashPay wallet seed hash, and the BIP-32 -/// derivation runs inside the closure through the shared -/// [`derive_contact_info_encryption_keys`](crate::wallet_backend::derive_contact_info_encryption_keys) -/// helper — the raw seed never enters this layer. -#[allow(clippy::type_complexity)] -async fn derive_contact_info_keys( - app_context: &Arc, - identity: &QualifiedIdentity, - derivation_index: u32, -) -> Result<(Zeroizing<[u8; 32]>, Zeroizing<[u8; 32]>), TaskError> { - let seed_hash = identity - .dashpay_wallet_seed_hash() - .ok_or(TaskError::ContactWalletSeedUnavailable)?; - let network = identity.network; - - app_context - .wallet_backend()? - .secret_access() - .with_secret( - &crate::wallet_backend::SecretScope::HdSeed { seed_hash }, - |plaintext| { - let seed = plaintext - .expose_hd_seed() - .ok_or(TaskError::ContactWalletSeedUnavailable)?; - crate::wallet_backend::derive_contact_info_encryption_keys( - seed, - network, - derivation_index, - ) - }, - ) - .await -} - -/// Encrypt toUserId using AES-256-ECB as specified by DIP-0015. -/// -/// DIP-0015 mandates ECB mode for encToUserId encryption because: -/// 1. The toUserId is derived from SHA256, making it appear random (no patterns) -/// 2. Keys are never reused (unique per contact via hardened BIP32 derivation) -/// 3. The data is fixed-size (32 bytes = exactly 2 AES blocks) -/// -/// These properties eliminate typical ECB vulnerabilities (pattern leakage). -/// See: https://github.com/dashpay/dips/blob/master/dip-0015.md -fn encrypt_to_user_id(user_id: &[u8; 32], key: &[u8; 32]) -> Result<[u8; 32], String> { - let cipher = Aes256::new(key.into()); - - // The 32-byte ID is exactly two 16-byte AES blocks; encrypt each in place (ECB). - let mut encrypted = *user_id; - let (blocks, _) = encrypted.as_chunks_mut::<16>(); - for block in blocks { - cipher.encrypt_block(block.into()); - } - - Ok(encrypted) -} - -/// Decrypt toUserId using AES-256-ECB as specified by DIP-0015. -/// -/// See `encrypt_to_user_id` for the rationale behind ECB mode usage per DIP-0015. -fn decrypt_to_user_id(encrypted: &[u8], key: &[u8; 32]) -> Result<[u8; 32], String> { - use aes_gcm::aes::cipher::BlockCipherDecrypt; - - let mut decrypted: [u8; 32] = encrypted - .try_into() - .map_err(|_| "Invalid encrypted user ID length".to_string())?; - - let cipher = Aes256::new(key.into()); - - // The 32-byte ciphertext is exactly two 16-byte AES blocks; decrypt each in place (ECB). - let (blocks, _) = decrypted.as_chunks_mut::<16>(); - for block in blocks { - cipher.decrypt_block(block.into()); - } - - Ok(decrypted) -} - -// Encrypt private data using AES-256-CBC -fn encrypt_private_data(data: &[u8], key: &[u8; 32]) -> Result, String> { - use cbc::cipher::block_padding::Pkcs7; - type Aes256CbcEnc = cbc::Encryptor; - - // Generate random IV (16 bytes) - let mut rng = StdRng::from_entropy(); - let mut iv = [0u8; 16]; - use bip39::rand::RngCore; - rng.fill_bytes(&mut iv); - - // Pad data to multiple of 16 bytes and encrypt - let cipher = Aes256CbcEnc::new(key.into(), &iv.into()); - - // Allocate buffer with padding - let mut buffer = vec![0u8; data.len() + 16]; // Extra space for padding - buffer[..data.len()].copy_from_slice(data); - - let encrypted = cipher - .encrypt_padded::(&mut buffer, data.len()) - .map_err(|e| format!("Encryption failed: {:?}", e))?; - - // Combine IV and encrypted data - let mut result = Vec::with_capacity(16 + encrypted.len()); - result.extend_from_slice(&iv); - result.extend_from_slice(encrypted); - - Ok(result) -} - -struct ExistingContactInfo { - document: Document, - derivation_index: u32, - enc_user_id_key: Zeroizing<[u8; 32]>, - private_data_key: Zeroizing<[u8; 32]>, -} - -struct ContactInfoLookup { - existing: Option, - next_derivation_index: u32, -} - -type ContactInfoKeys = (Zeroizing<[u8; 32]>, Zeroizing<[u8; 32]>); const CONTACT_INFO_PAGE_SIZE: usize = 100; @@ -487,195 +57,17 @@ where Ok(documents) } -fn contact_info_derivation_index(document: &Document) -> Option { - document - .properties() - .get("derivationEncryptionKeyIndex") - .and_then(|value| value.to_integer::().ok()) -} - -fn has_contact_info_key_material(document: &Document) -> bool { - contact_info_derivation_index(document).is_some() - && document - .properties() - .get("rootEncryptionKeyIndex") - .and_then(|value| value.to_integer::().ok()) - .is_some() - && document - .properties() - .get("encToUserId") - .is_some_and(|value| value.as_bytes_slice().is_ok()) -} - -fn find_existing_contact_info( - documents: Vec, - contact_user_id: Identifier, - mut derive_keys: F, -) -> Option -where - F: FnMut(u32) -> Result, -{ - // Documents come oldest first; the newest match is the one the contacts - // load shows, and a rewrite keeps it the newest. - for document in documents.into_iter().rev() { - let Some(derivation_index) = contact_info_derivation_index(&document) else { - continue; - }; - if !has_contact_info_key_material(&document) { - continue; - } - - let Ok((enc_user_id_key, private_data_key)) = derive_keys(derivation_index) else { - continue; - }; - // Platform returns the fixed 32-byte field as `Value::Bytes32`. - let Some(enc_user_id) = document - .properties() - .get("encToUserId") - .and_then(|value| value.as_bytes_slice().ok()) - else { - continue; - }; - if decrypt_to_user_id(enc_user_id, &enc_user_id_key).ok() - == Some(contact_user_id.to_buffer()) - { - return Some(ExistingContactInfo { - document, - derivation_index, - enc_user_id_key, - private_data_key, - }); - } - } - - None -} - -async fn scan_contact_info_documents( - documents: Vec, - contact_user_id: Identifier, - with_key_session: F, -) -> Result -where - F: FnOnce(Vec, Identifier) -> Fut, - Fut: Future, TaskError>>, -{ - let next_derivation_index = documents - .iter() - .filter_map(contact_info_derivation_index) - .fold(0u32, |next, index| next.max(index.saturating_add(1))); - let existing = if documents.iter().any(has_contact_info_key_material) { - with_key_session(documents, contact_user_id).await? - } else { - None - }; - - Ok(ContactInfoLookup { - existing, - next_derivation_index, - }) -} - -async fn lookup_contact_info( - app_context: &Arc, - sdk: &Sdk, - identity: &QualifiedIdentity, - contact_user_id: Identifier, -) -> Result { - let dashpay_contract = app_context.dashpay_contract(); - let identity_id = identity.identity.id(); - let mut query = DocumentQuery::new(dashpay_contract, "contactInfo").map_err(|e| { - DashPayError::QueryCreation { - query_target: "DashPay contactInfo", - source: Box::new(e.into()), - } - })?; - query = query.with_where(WhereClause { - field: "$ownerId".to_string(), - operator: WhereOperator::Equal, - value: Value::Identifier(identity_id.to_buffer()), - }); - query = query.with_order_by(OrderClause { - field: "$updatedAt".to_string(), - ascending: true, - }); - let existing_docs = fetch_all_contact_info_documents(query, |page_query| async move { - Document::fetch_many(sdk, page_query) - .await - .map_err(TaskError::from) - }) - .await?; - let documents = existing_docs.into_values().flatten().collect(); - scan_contact_info_documents( - documents, - contact_user_id, - |documents, contact_user_id| async move { - let seed_hash = identity - .dashpay_wallet_seed_hash() - .ok_or(TaskError::ContactWalletSeedUnavailable)?; - let network = identity.network; - - app_context - .wallet_backend()? - .secret_access() - .with_secret_session( - &crate::wallet_backend::SecretScope::HdSeed { seed_hash }, - async |session| { - let plaintext = session.plaintext(); - let seed = plaintext - .expose_hd_seed() - .ok_or(TaskError::ContactWalletSeedUnavailable)?; - Ok(find_existing_contact_info( - documents, - contact_user_id, - |derivation_index| { - crate::wallet_backend::derive_contact_info_encryption_keys( - seed, - network, - derivation_index, - ) - }, - )) - }, - ) - .await - }, - ) - .await -} - -pub(super) async fn contact_info_is_hidden( - app_context: &Arc, - sdk: &Sdk, - identity: &QualifiedIdentity, - contact_user_id: Identifier, - unreadable: UnreadableContactInfoPolicy, -) -> Result { - let lookup = lookup_contact_info(app_context, sdk, identity, contact_user_id).await?; - let Some(existing) = lookup.existing else { - return Ok(false); - }; - Ok(read_contact_info_private_data( - Some(&existing.document), - &existing.private_data_key, - unreadable, - )? - .display_hidden) -} - -/// Write the `contactInfo` document for `contact_user_id`, creating it when the -/// identity has none yet and replacing it otherwise. +/// Save `update` for `contact_user_id` through platform-wallet. /// -/// The document is written whole, so `update` explicitly chooses which fields -/// are preserved and which fields are replaced. Nicknames and notes are limited -/// to 255 UTF-8 bytes; the encoded payload must also fit the contract size limit. +/// Every field the update preserves keeps the value the contacts list shows; +/// see [`super::contacts::shown_contact_details`]. Notes are limited to 255 UTF-8 +/// bytes, and the details must fit the document size limit. /// /// # Errors /// -/// Fails when a preserved payload is present but unreadable, when the contact's -/// encryption keys cannot be derived, when an encoded field exceeds its v0 or -/// contract limit, when the identity has no usable authentication key, or when -/// the state transition is rejected. +/// Fails when the details are too large, when the identity was not loaded +/// from its wallet, when the contact is not established, or when the sync or +/// the publish fails. pub async fn create_or_update_contact_info( app_context: &Arc, sdk: &Sdk, @@ -683,233 +75,438 @@ pub async fn create_or_update_contact_info( contact_user_id: Identifier, update: ContactInfoUpdate, ) -> Result { - let write_guard = app_context - .contact_info_writes - .acquire(identity.identity.id()) - .await; - create_or_update_contact_info_locked( + let owner = identity.identity.id(); + let _write_guard = app_context.contact_info_writes.acquire(owner).await; + let ops = PlatformSaveOps { app_context, sdk, - identity, - contact_user_id, - update, - &write_guard, - ) - .await + backend: app_context.wallet_backend()?, + identity: &identity, + contact_id: contact_user_id, + }; + let published = save_contact_details(&ops, &update).await?; + Ok(BackendTaskSuccessResult::DashPayContactInfoUpdated { + identity: owner, + contact_id: contact_user_id, + published, + }) } -/// Write while the caller holds the owner's lock across its reads and decisions. -/// Request actions acquire their request lock before this owner lock. -pub(super) async fn create_or_update_contact_info_locked( +/// Read the details shown for `contact_id`, the ones a contact details +/// editor starts from. While a save of the owner runs, the details are not +/// synced first; see [`super::contacts::unless_saving`]. +/// +/// # Errors +/// +/// The details sync fails, or as for [`shown_details_for`]. +pub async fn load_contact_details( app_context: &Arc, sdk: &Sdk, identity: QualifiedIdentity, - contact_user_id: Identifier, - update: ContactInfoUpdate, - _write_guard: &tokio::sync::OwnedMutexGuard<()>, + contact_id: Identifier, ) -> Result { - let dashpay_contract = app_context.dashpay_contract(); - let identity_id = identity.identity.id(); - let lookup = lookup_contact_info(app_context, sdk, &identity, contact_user_id).await?; - let (found_existing_doc, derivation_index, enc_user_id_key, private_data_key) = - match lookup.existing { - Some(existing) => ( - Some(existing.document), - existing.derivation_index, - existing.enc_user_id_key, - existing.private_data_key, - ), - None => { - let derivation_index = lookup.next_derivation_index; - let (enc_user_id_key, private_data_key) = - derive_contact_info_keys(app_context, &identity, derivation_index).await?; - (None, derivation_index, enc_user_id_key, private_data_key) - } - }; + let backend = app_context.wallet_backend()?; + let owner = identity.identity.id(); + if let Some(synced) = super::contacts::unless_saving( + &app_context.contact_info_writes, + owner, + backend.dashpay_sync_contact_infos(&owner), + ) + .await + { + synced?; + } + let (details, _) = + shown_details_for(app_context, sdk, &backend, &identity, &contact_id).await?; + Ok(BackendTaskSuccessResult::DashPayContactDetails { + identity: identity.identity.id(), + contact_id, + details, + }) +} + +/// The details shown for `contact_id`, with the precedence of +/// [`super::contacts::shown_contact_details`]: published, then +/// platform-wallet's on this device, then a legacy-key document; and whether +/// they stand in for saved details that could not be read. +/// +/// # Errors +/// +/// Fails when the document fetch, or reading the published or legacy +/// documents fails (a cancelled password prompt included), rather than +/// guessing: a save keeps every field it does not replace from this. Callers +/// sync platform-wallet's details first, under the owner's write lock. +async fn shown_details_for( + app_context: &Arc, + sdk: &Sdk, + backend: &WalletBackend, + identity: &QualifiedIdentity, + contact_id: &Identifier, +) -> Result<(ContactDetails, bool), TaskError> { + let owner = identity.identity.id(); + let local = backend + .dashpay_contact_details(&owner) + .await + .remove(contact_id); + let stored = super::contacts::stored_contact_details(app_context, sdk, identity).await?; + let (published, published_unreadable) = match stored.published?.take(contact_id) { + Some((details, unreadable)) => (Some(details), unreadable), + None => (None, false), + }; + let legacy = stored.legacy?; + let synced_before = backend.dashpay_details_synced(&owner, contact_id)? + || super::contacts::holds_details(published.as_ref(), local.as_ref()); + let legacy = legacy.get(contact_id); + let unreadable = baseline_unreadable( + published_unreadable, + published.as_ref(), + local.as_ref(), + synced_before, + legacy, + ); + let legacy = legacy.map(super::contacts::ContactData::details); + Ok(( + super::contacts::shown_contact_details(published, local, synced_before, legacy), + unreadable, + )) +} - // Encrypt toUserId - let encrypted_user_id = encrypt_to_user_id(&contact_user_id.to_buffer(), &enc_user_id_key) - .map_err(|e| TaskError::EncryptionError { detail: e })?; +/// Whether the shown details stand in for saved ones that could not be read: +/// a published document that did not open, or an unreadable legacy document +/// while it is the one shown. +fn baseline_unreadable( + published_unreadable: bool, + published: Option<&ContactDetails>, + local: Option<&ContactDetails>, + synced_before: bool, + legacy: Option<&super::contacts::ContactData>, +) -> bool { + published_unreadable + || super::contacts::legacy_details_shown(published, local, synced_before) + && legacy.is_some_and(|legacy| legacy.details_unreadable) +} - let private_data = - apply_contact_info_update(update, found_existing_doc.as_ref(), &private_data_key)?; +/// The reads and writes one contact details save performs, behind a trait so +/// their order and failures can be driven in tests. +trait SaveOps { + /// The details shown for the contact now, the fields an update keeps, and + /// whether they are a stand-in for saved details that could not be read. + fn current(&self) -> impl Future> + Send; + fn publish( + &self, + details: ContactDetails, + ) -> impl Future> + Send; + /// Record that platform-wallet holds the contact's details, so a legacy + /// document no longer stands in for them. + fn mark_synced(&self) -> Result<(), TaskError>; +} - // Encrypt private data - let encrypted_private_data = - encrypt_private_data(&private_data.serialize()?, &private_data_key) - .map_err(|e| TaskError::EncryptionError { detail: e })?; +/// Save `update` and return whether the details reached Platform. +/// +/// # Errors +/// +/// Nothing is written when the current details cannot be read (a cancelled +/// password prompt included): a field the update keeps would otherwise be +/// saved from a guess. Over saved details that could not be read, a save that +/// keeps a text field, other than unhiding, is refused with +/// [`TaskError::DashPayContactDetailsUnreadable`]. A save whose synced record +/// fails is reported as failed, since the old legacy details would show +/// again on reload. +async fn save_contact_details( + ops: &O, + update: &ContactInfoUpdate, +) -> Result { + let (current, unreadable) = ops.current().await?; + // Unreadable saved details are not empty ones: a text field the update + // keeps would be published as empty, and the saved one lost. Unhiding + // replaces them on purpose, as the hidden list says. + if unreadable && update.keeps_text() && !update.unhides_only() { + return Err(TaskError::DashPayContactDetailsUnreadable); + } + let details = update.apply_to(current); + + validate_contact_note(details.note.as_deref().unwrap_or_default())?; + // The bound platform-wallet enforces, checked before it saves anything. + encode_private_data_bounded(&ContactInfoPrivateData { + alias_name: details.nickname.clone(), + note: details.note.clone(), + display_hidden: details.hidden, + // TODO(upstream): https://github.com/dashpay/platform/issues/5657 — + // platform-wallet's save writes an empty list too, erasing the accepted + // accounts already stored for the contact. + accepted_accounts: Vec::new(), + }) + .map_err(|source| TaskError::DashPayContactInfoEncoding { + source: Box::new(source), + })?; - let validation = crate::backend_task::dashpay::validation::validate_contact_info_field_sizes( - &encrypted_user_id, - &encrypted_private_data, - ); - if !validation.is_valid { - return Err(TaskError::DashPay( - DashPayError::ContactInfoValidationFailed { - errors: validation.errors, - }, - )); + // A failed publish records nothing. platform-wallet stores the details + // here before it publishes, but its error does not say whether it got + // that far, and an attempt can equal details that were never stored. + // TODO(upstream): https://github.com/dashpay/platform/issues/5646 — + // platform-wallet keeps its local change when the publish fails, so this + // device can show details Platform never got (or, for a contact with only + // a legacy document, the legacy details again). Once platform-wallet rolls + // the local change back or reports it in a typed outcome, nothing here + // needs to change for the rollback; a typed outcome gets its own arm. + let outcome = ops.publish(details).await?; + match ops.mark_synced() { + Ok(()) => {} + // A deferred save published nothing, so the storage error's claim + // that the change reached the network would be false. + Err(TaskError::DashpaySidecarStorage { source }) + if outcome == ContactInfoPublishOutcome::DeferredUntilTwoContacts => + { + return Err(TaskError::DashPayContactDetailsNotRecorded { source }); + } + Err(error) => return Err(error), + } + match outcome { + ContactInfoPublishOutcome::Published => Ok(true), + ContactInfoPublishOutcome::DeferredUntilTwoContacts => Ok(false), + // The write checks for a wallet identity index before platform-wallet + // runs, so this is reached only if the two disagree. + ContactInfoPublishOutcome::SkippedWatchOnly => { + Err(TaskError::ContactInfoIdentityNotFromWallet) + } } +} - // Get signing key — accept any key type (BLS, ECDSA, EDDSA) since - // Platform accepts all for document state transitions. - let signing_key = identity - .identity - .get_first_public_key_matching( - Purpose::AUTHENTICATION, - HashSet::from([ - SecurityLevel::CRITICAL, - SecurityLevel::HIGH, - SecurityLevel::MEDIUM, - ]), - KeyType::all_key_types().into(), - false, - ) - .ok_or_else(|| TaskError::DashPay(DashPayError::MissingAuthenticationKey))?; +struct PlatformSaveOps<'a> { + app_context: &'a Arc, + sdk: &'a Sdk, + backend: Arc, + identity: &'a QualifiedIdentity, + contact_id: Identifier, +} - // Create document properties - let mut properties = BTreeMap::new(); - properties.insert( - "encToUserId".to_string(), - Value::Bytes(encrypted_user_id.to_vec()), - ); - properties.insert( - "rootEncryptionKeyIndex".to_string(), - Value::U32(signing_key.id()), - ); - properties.insert( - "derivationEncryptionKeyIndex".to_string(), - Value::U32(derivation_index), - ); - properties.insert( - "privateData".to_string(), - Value::Bytes(encrypted_private_data), - ); +impl SaveOps for PlatformSaveOps<'_> { + async fn current(&self) -> Result<(ContactDetails, bool), TaskError> { + // The save holds the owner's write lock, so this sync cannot race one. + self.backend + .dashpay_sync_contact_infos(&self.identity.identity.id()) + .await?; + shown_details_for( + self.app_context, + self.sdk, + &self.backend, + self.identity, + &self.contact_id, + ) + .await + } - if let Some(existing_doc) = found_existing_doc { - // Update existing document - let mut updated_doc = existing_doc.clone(); + async fn publish( + &self, + details: ContactDetails, + ) -> Result { + // TODO(upstream): https://github.com/dashpay/platform/issues/5545 — + // preserved fields come from `current()`'s read; upstream + // set_contact_info has no expected-revision check, so a newer edit from + // another device in between is overwritten. + self.backend + .dashpay_set_contact_info(self.identity, &self.contact_id, details) + .await + } - // Update properties - for (key, value) in properties { - updated_doc.set(&key, value); - } + fn mark_synced(&self) -> Result<(), TaskError> { + self.backend + .dashpay_mark_details_synced(&self.identity.identity.id(), &self.contact_id) + } +} - // Bump revision - updated_doc.bump_revision(); +/// The plaintext floor platform-wallet pads to with zero bytes, so that +/// IV (16) + AES-CBC ciphertext reaches the contract's 48-byte minimum. +const MIN_PLAINTEXT_SIZE: usize = 17; - // Create replacement transition - use dash_sdk::platform::documents::transitions::DocumentReplaceTransitionBuilder; - let mut builder = DocumentReplaceTransitionBuilder::new( - dashpay_contract, - "contactInfo".to_string(), - updated_doc, - ); +/// The plaintext size older versions of this client (up to +/// v1.0.0-weekly.20261020) padded to: a `0x00` sentinel, then random bytes. +const LEGACY_PLAINTEXT_SIZE: usize = 16; - // Add state transition options if available - let maybe_options = app_context.state_transition_options(); - if let Some(options) = maybe_options { - builder = builder.with_state_transition_creation_options(options); - } +/// How a payload encodes string lengths and the account count. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum LengthPrefix { + /// DIP-15 Bitcoin CompactSize, in its shortest encoding. + CompactSize, + /// One byte, which older versions of this client wrote for lengths up to + /// 255. It differs from CompactSize only for 253 to 255, the CompactSize + /// prefix markers, so it is accepted only when such a length is present + /// and the payload ends exactly after the last field. + /// + /// Some bytes read completely both ways, with different values: a legacy + /// payload can also parse as CompactSize, and a 256+ byte field from + /// another client can also form a legacy payload. Such bytes are + /// [`PrivateDataReading::Ambiguous`]. What platform-wallet writes never + /// is: a 253 to 255-byte field is `FD xx 00` with `xx` in `FD..=FF`, never + /// valid UTF-8 as the first text byte, and a 253+ account count never + /// totals the same bytes both ways. + SingleByte, +} - let result = sdk - .document_replace(builder, signing_key, &identity) - .await?; +/// The outcome of reading a decrypted `privateData` payload. +#[derive(Debug)] +enum PrivateDataReading { + /// Exactly one reading succeeded, or both agree. + Read(ContactInfoPrivateData), + /// The CompactSize and single-byte readings both succeed with different + /// values, so neither can be trusted. + Ambiguous, + /// Neither reading succeeds. + Unreadable, +} - // Log the proof-verified document for audit trail - match result { - dash_sdk::platform::documents::transitions::DocumentReplaceResult::Document(doc) => { - tracing::info!( - "Contact info updated: doc_id={}, revision={:?}", - doc.id(), - doc.revision() - ); - } +/// Decode a decrypted legacy-key `privateData` payload. +/// +/// Older versions of this client wrote single-byte lengths, which +/// platform-wallet misreads for fields of 253 to 255 bytes. So this client's +/// strict reader comes first, and an ambiguous payload is unreadable, never a +/// guess. platform-wallet's tolerant reader then covers what neither reading +/// accepts, such as a newer minor version. +pub(super) fn decode_contact_info_details(plaintext: &[u8]) -> Option { + match read_private_data(plaintext) { + PrivateDataReading::Read(data) => Some(data), + PrivateDataReading::Ambiguous => None, + PrivateDataReading::Unreadable => { + platform_wallet::wallet::identity::crypto::decode_private_data(plaintext).ok() } - } else { - // Create new contactInfo document - let mut rng = StdRng::from_entropy(); - let entropy = Bytes32::random_with_rng(&mut rng).to_buffer(); - let document_type = dashpay_contract - .document_type_for_name("contactInfo") - .map_err(|e| TaskError::DocumentPreparationFailed { - source: Box::new(e.into()), - })?; - let document = new_document_for_creation( - document_type, - identity_id, - properties, - &entropy, - sdk.version(), - ) - .map_err(|source| TaskError::DocumentPreparationFailed { source })?; + } +} - let mut builder = DocumentCreateTransitionBuilder::new( - dashpay_contract, - "contactInfo".to_string(), - document, - entropy, - ); +/// Read `bytes` both as CompactSize and as the single-byte layout older +/// versions wrote, and keep a result only when it is unambiguous. +/// +/// A reading fails for a truncated or non-canonical v0 payload, invalid +/// UTF-8, an unsupported version, or trailing bytes that are not padding +/// (see [`is_padding`]). +fn read_private_data(bytes: &[u8]) -> PrivateDataReading { + match ( + parse_private_data(bytes, LengthPrefix::SingleByte), + parse_private_data(bytes, LengthPrefix::CompactSize), + ) { + (Some(legacy), Some(compact)) if legacy != compact => PrivateDataReading::Ambiguous, + (Some(data), _) | (None, Some(data)) => PrivateDataReading::Read(data), + (None, None) => PrivateDataReading::Unreadable, + } +} - // Add state transition options if available - let maybe_options = app_context.state_transition_options(); - if let Some(options) = maybe_options { - builder = builder.with_state_transition_creation_options(options); +fn parse_private_data(bytes: &[u8], prefix: LengthPrefix) -> Option { + let version = u32::from_le_bytes(bytes.get(..4)?.try_into().ok()?); + if version != 0 { + return None; + } + let mut pos = 4; + // Whether a single-byte length took a value CompactSize reserves. + let mut reserved_length = false; + + let mut take_length = |pos: &mut usize| -> Option { + let first = *bytes.get(*pos)?; + if prefix == LengthPrefix::SingleByte { + reserved_length |= first >= 0xFD; + *pos += 1; + return Some(first.into()); } - - let result = sdk.document_create(builder, signing_key, &identity).await?; - - // Log the proof-verified document for audit trail - match result { - dash_sdk::platform::documents::transitions::DocumentCreateResult::Document(doc) => { - tracing::info!( - "Contact info created: doc_id={}, revision={:?}", - doc.id(), - doc.revision() - ); - } + // A Bitcoin CompactSize length, in its shortest encoding only. + let field = |width: usize| bytes.get(*pos + 1..*pos + 1 + width); + let (value, width): (u64, usize) = match first { + 0xFD => (u16::from_le_bytes(field(2)?.try_into().ok()?).into(), 3), + 0xFE => (u32::from_le_bytes(field(4)?.try_into().ok()?).into(), 5), + 0xFF => (u64::from_le_bytes(field(8)?.try_into().ok()?), 9), + n => (n.into(), 1), + }; + let shortest = match width { + 3 => 0xFD, + 5 => 0x1_0000, + 9 => 0x1_0000_0000, + _ => 0, + }; + if value < shortest { + return None; } + *pos += width; + usize::try_from(value).ok() + }; + let mut take_string = |pos: &mut usize| -> Option> { + let len = take_length(pos)?; + let raw = bytes.get(*pos..pos.checked_add(len)?)?; + *pos += len; + if len == 0 { + Some(None) + } else { + Some(Some(std::str::from_utf8(raw).ok()?.to_owned())) + } + }; + let alias_name = take_string(&mut pos)?; + let note = take_string(&mut pos)?; + + let display_hidden = match *bytes.get(pos)? { + 0 => false, + 1 => true, + _ => return None, + }; + pos += 1; + + let count = take_length(&mut pos)?; + let accepted_accounts = (0..count) + .map(|_| { + let raw = bytes.get(pos..pos + 4)?; + pos += 4; + Some(u32::from_le_bytes(raw.try_into().ok()?)) + }) + .collect::>>()?; + + let complete = match prefix { + LengthPrefix::CompactSize => is_padding(bytes, pos), + // A payload without a reserved length reads the same both ways, so + // it is left to the CompactSize reader. One with such a length is + // over 255 bytes, which older versions never padded. + LengthPrefix::SingleByte => reserved_length && pos == bytes.len(), + }; + if !complete { + return None; } - Ok(BackendTaskSuccessResult::DashPayContactInfoUpdated { - identity: identity_id, - contact_id: contact_user_id, + Some(ContactInfoPrivateData { + alias_name, + note, + display_hidden, + accepted_accounts, }) } +/// Whether `bytes[end..]`, after the last v0 field, is padding a known +/// writer adds: none, platform-wallet's zeros up to [`MIN_PLAINTEXT_SIZE`], +/// or this client's former `0x00` sentinel and random bytes up to exactly +/// [`LEGACY_PLAINTEXT_SIZE`]. +fn is_padding(bytes: &[u8], end: usize) -> bool { + match bytes[end..].split_first() { + None => true, + Some((0, _)) if bytes.len() == LEGACY_PLAINTEXT_SIZE => true, + Some(_) => bytes.len() <= MIN_PLAINTEXT_SIZE && bytes[end..].iter().all(|b| *b == 0), + } +} + #[cfg(test)] mod tests { use super::*; - use dash_sdk::dpp::document::{Document as DppDocument, DocumentV0}; + use dash_sdk::dpp::document::{ + Document as DppDocument, DocumentV0, DocumentV0Getters, DocumentV0Setters, + }; + use dash_sdk::dpp::platform_value::Value; use dash_sdk::dpp::system_data_contracts::{SystemDataContract, load_system_data_contract}; use dash_sdk::dpp::version::PlatformVersion; - use std::cell::Cell; - use std::collections::VecDeque; + use dash_sdk::platform::Document; + use std::collections::{BTreeMap, VecDeque}; use std::future::ready; + use zeroize::Zeroizing; - /// The contact-info encryption keys the tests encrypt and decrypt with: + /// The contact-info encryption key the tests encrypt and decrypt with: /// generated at runtime, stable for the whole test process. fn key() -> [u8; 32] { crate::test_support::keys::labelled_secret("dashpay::contact_info::tests::key", 0) } - fn other_key() -> [u8; 32] { - crate::test_support::keys::labelled_secret("dashpay::contact_info::tests::key", 1) - } - - /// DIP-15 `encToUserId` known-answer vector: AES-256-ECB(key = 00..1f, - /// pt = 40..5f), generated independently with Python `cryptography` 46 - /// (OpenSSL). Pins interoperability across `aes` / `aes-gcm` bumps. - #[test] - fn to_user_id_ecb_matches_golden_vector() { - let key: [u8; 32] = std::array::from_fn(|i| i as u8); - let user_id: [u8; 32] = std::array::from_fn(|i| 0x40 + i as u8); - let expected = "a37edf3f975abaef937b62c78d5bb157974b412738e50f45c7f9db25413f274b"; - - let encrypted = encrypt_to_user_id(&user_id, &key).expect("encrypt"); - assert_eq!(hex::encode(encrypted), expected); - let decrypted = decrypt_to_user_id(&encrypted, &key).expect("decrypt"); - assert_eq!(decrypted, user_id); + fn encrypt_to_user_id(user_id: &[u8; 32], key: &[u8; 32]) -> [u8; 32] { + platform_encryption::encrypt_enc_to_user_id(key, user_id) } fn id(byte: u8) -> Identifier { @@ -931,48 +528,6 @@ mod tests { assert_eq!(next_contact_info_page(&docs), None); } - /// A stored `contactInfo` document whose `privateData` holds `accounts`, - /// encrypted exactly the way [`create_or_update_contact_info`] writes it. - fn stored_contact_info(accounts: Vec, key: &[u8; 32]) -> Document { - let private_data = ContactInfoPrivateData { - version: 0, - alias_name: Some("Bao".to_string()), - note: None, - display_hidden: true, - accepted_accounts: accounts, - }; - let encrypted = encrypt_private_data(&private_data.serialize().expect("serialize"), key) - .expect("encrypt"); - - contact_info_document(Some(Value::Bytes(encrypted))) - } - - fn contact_info_document(private_data: Option) -> Document { - let mut properties = BTreeMap::new(); - if let Some(private_data) = private_data { - properties.insert("privateData".to_string(), private_data); - } - DppDocument::V0(DocumentV0 { - moderated_at: None, - moderated_by: None, - id: id(1), - owner_id: id(2), - creator_id: None, - properties, - revision: Some(1), - created_at: None, - updated_at: None, - transferred_at: None, - created_at_block_height: None, - updated_at_block_height: None, - transferred_at_block_height: None, - created_at_core_block_height: None, - updated_at_core_block_height: None, - transferred_at_core_block_height: None, - contract_version: None, - }) - } - fn lookup_contact_info_document( document_id: u8, derivation_index: u32, @@ -1010,105 +565,6 @@ mod tests { }) } - #[tokio::test] - async fn contact_info_scan_uses_one_secret_session_for_many_documents() { - let contact_user_id = id(200); - let encrypted_other_id = encrypt_to_user_id(&id(201).to_buffer(), &key()).expect("encrypt"); - let documents = (0..=CONTACT_INFO_PAGE_SIZE) - .map(|index| { - lookup_contact_info_document(index as u8, index as u32, encrypted_other_id) - }) - .collect(); - let sessions = Cell::new(0); - let derivations = Cell::new(0); - - let lookup = - scan_contact_info_documents(documents, contact_user_id, |documents, target| { - sessions.set(sessions.get() + 1); - ready(Ok(find_existing_contact_info(documents, target, |_| { - derivations.set(derivations.get() + 1); - Ok((Zeroizing::new(key()), Zeroizing::new(other_key()))) - }))) - }) - .await - .expect("scan"); - - assert!(lookup.existing.is_none()); - assert_eq!(lookup.next_derivation_index, 101); - assert_eq!(derivations.get(), 101); - assert_eq!(sessions.get(), 1, "the entire scan uses one unlock session"); - } - - #[test] - fn contact_info_scan_stops_deriving_after_target_match() { - let contact_user_id = id(210); - let encrypted_target = - encrypt_to_user_id(&contact_user_id.to_buffer(), &key()).expect("encrypt target"); - let encrypted_other = - encrypt_to_user_id(&id(211).to_buffer(), &key()).expect("encrypt other"); - // Newest last: the scan starts from the newest document. - let documents = vec![ - lookup_contact_info_document(2, 4, encrypted_other), - lookup_contact_info_document(1, 3, encrypted_target), - ]; - let mut derived_indices = Vec::new(); - - let existing = find_existing_contact_info(documents, contact_user_id, |index| { - derived_indices.push(index); - Ok((Zeroizing::new(key()), Zeroizing::new(other_key()))) - }); - - assert!(existing.is_some()); - assert_eq!(derived_indices, vec![3]); - } - - #[tokio::test] - async fn contact_info_scan_skips_late_hardened_index_and_keeps_high_water_mark() { - let seed = crate::test_support::keys::seed(); - const MATCH_INDEX: u32 = 7; - const UNDERIVABLE_INDEX: u32 = 1 << 31; - - let contact_user_id = id(220); - let (target_key, _) = crate::wallet_backend::derive_contact_info_encryption_keys( - &seed, - dash_sdk::dpp::dashcore::Network::Testnet, - MATCH_INDEX, - ) - .expect("derive target key"); - let encrypted_target = - encrypt_to_user_id(&contact_user_id.to_buffer(), &target_key).expect("encrypt target"); - let documents = vec![ - lookup_contact_info_document(1, MATCH_INDEX, encrypted_target), - lookup_contact_info_document(2, UNDERIVABLE_INDEX, [0; 32]), - ]; - let sessions = Cell::new(0); - - let lookup = - scan_contact_info_documents(documents, contact_user_id, |documents, target| { - sessions.set(sessions.get() + 1); - ready(Ok(find_existing_contact_info(documents, target, |index| { - crate::wallet_backend::derive_contact_info_encryption_keys( - &seed, - dash_sdk::dpp::dashcore::Network::Testnet, - index, - ) - }))) - }) - .await - .expect("the late underivable document must not abort the matched lookup"); - - assert_eq!( - lookup.existing.map(|existing| existing.derivation_index), - Some(MATCH_INDEX) - ); - assert_eq!( - lookup.next_derivation_index, - UNDERIVABLE_INDEX + 1, - "the on-chain coordinate still advances the public high-water mark" - ); - assert_eq!(sessions.get(), 1); - } - #[tokio::test] async fn contact_info_fetch_walks_every_page() { let contract = @@ -1146,71 +602,279 @@ mod tests { assert_eq!(documents.keys().last().copied(), Some(id(101))); } - /// DIP-15 writes string lengths as CompactSize, where 253 and longer take a - /// three-byte prefix. Other platform-wallet clients must read what this - /// client writes, and this client what they write. + /// The fee estimate covers the largest details platform-wallet accepts. #[test] - fn contact_details_round_trip_with_the_platform_wallet_codec() { - use platform_wallet::wallet::identity::crypto as upstream; + fn contact_info_fee_estimate_covers_the_largest_details() { + use crate::model::fee_estimation::PlatformFeeEstimator; + let estimator = PlatformFeeEstimator::latest(); for len in [0, 252, 253, 255] { let text = (len > 0).then(|| "x".repeat(len)); - let ours = ContactInfoPrivateData { - version: 0, + let encoded = encode_private_data_bounded(&ContactInfoPrivateData { alias_name: text.clone(), - note: text.clone(), + note: text, display_hidden: true, - accepted_accounts: vec![0, 3], - }; - let theirs = upstream::ContactInfoPrivateData { - alias_name: text.clone(), - note: text.clone(), - display_hidden: true, - accepted_accounts: vec![0, 3], - }; - - let decoded = upstream::decode_private_data(&ours.serialize().expect("serialize")); - assert_eq!( - decoded.ok(), - Some(theirs.clone()), - "platform-wallet reads {len} bytes" + accepted_accounts: Vec::new(), + }) + .expect("within the bound"); + let encrypted = platform_encryption::encrypt_private_data(&key(), &[0; 16], &encoded); + assert!( + estimator.estimate_contact_info_write() + >= estimator.estimate_document_create_with_size(112 + encrypted.len()), + "{len}-byte fields" ); + } + } + + struct ScriptedSave { + current: std::sync::Mutex>>, + unreadable: bool, + mark_fails: bool, + marked: std::sync::Mutex, + publish_fails: bool, + outcome: ContactInfoPublishOutcome, + published: std::sync::Mutex>, + } + + impl ScriptedSave { + fn new(current: Result, mark_fails: bool) -> Self { + Self { + current: std::sync::Mutex::new(Some(current)), + unreadable: false, + mark_fails, + marked: std::sync::Mutex::new(false), + publish_fails: false, + outcome: ContactInfoPublishOutcome::DeferredUntilTwoContacts, + published: std::sync::Mutex::new(Vec::new()), + } + } + + fn with_outcome(mut self, outcome: ContactInfoPublishOutcome) -> Self { + self.outcome = outcome; + self + } + } + + impl SaveOps for ScriptedSave { + async fn current(&self) -> Result<(ContactDetails, bool), TaskError> { + self.current + .lock() + .unwrap() + .take() + .expect("read once") + .map(|details| (details, self.unreadable)) + } - let parsed = - ContactInfoPrivateData::deserialize(&upstream::encode_private_data(&theirs)) - .unwrap_or_else(|| { - panic!("this client reads {len} bytes from platform-wallet") - }); - assert_eq!(parsed.alias_name, text); - assert_eq!(parsed.note, text); - assert!(parsed.display_hidden); - assert_eq!(parsed.accepted_accounts, vec![0, 3]); + async fn publish( + &self, + details: ContactDetails, + ) -> Result { + if self.publish_fails { + return Err(TaskError::WalletStateInconsistent); + } + self.published.lock().unwrap().push(details); + Ok(self.outcome) } + + fn mark_synced(&self) -> Result<(), TaskError> { + if self.mark_fails { + return Err(TaskError::DashpaySidecarStorage { + source: crate::wallet_backend::KvAdapterError::Truncated, + }); + } + *self.marked.lock().unwrap() = true; + Ok(()) + } + } + + /// A cancelled password prompt while reading the current details stops + /// the save: a note-only save must not overwrite the nickname or the + /// hidden flag with empty values it never read. + #[tokio::test] + async fn an_unreadable_baseline_writes_nothing() { + let ops = ScriptedSave::new(Err(TaskError::SecretPromptCancelled), false); + + let result = save_contact_details(&ops, &ContactInfoUpdate::note(Some("n".into()))).await; + + assert!(matches!(result, Err(TaskError::SecretPromptCancelled))); + assert!(ops.published.lock().unwrap().is_empty()); } + /// The baseline is unreadable when the published document did not open, + /// or when an unreadable legacy document is the one shown; not when + /// readable details shown ahead of it replace it. #[test] - fn contact_info_fee_estimate_covers_preserved_accounts() { - use crate::model::fee_estimation::PlatformFeeEstimator; - let estimator = PlatformFeeEstimator::latest(); - for len in [0, 252, 253, 255] { - for accounts in [0, 1, 16, 252, 253, 400, 500] { - let text = (len > 0).then(|| "x".repeat(len)); - let data = ContactInfoPrivateData { - alias_name: text.clone(), - note: text, - accepted_accounts: (0..accounts).collect(), + fn a_baseline_is_unreadable_only_when_unreadable_details_are_shown() { + let legacy = |details_unreadable| super::super::contacts::ContactData { + identity_id: Identifier::default(), + nickname: None, + note: None, + is_hidden: true, + details_unreadable, + account_reference: 0, + username: None, + display_name: None, + avatar_url: None, + bio: None, + }; + let saved = ContactDetails { + note: Some("n".into()), + ..Default::default() + }; + + assert!(baseline_unreadable(true, Some(&saved), None, true, None)); + assert!(baseline_unreadable( + false, + None, + None, + false, + Some(&legacy(true)) + )); + assert!(!baseline_unreadable( + false, + None, + None, + false, + Some(&legacy(false)) + )); + assert!(!baseline_unreadable( + false, + Some(&saved), + None, + false, + Some(&legacy(true)) + )); + assert!(!baseline_unreadable( + false, + None, + Some(&saved), + false, + Some(&legacy(true)) + )); + assert!(!baseline_unreadable( + false, + None, + None, + true, + Some(&legacy(true)) + )); + } + + /// A failed publish records nothing, even when this device's details + /// already equal the attempt: platform-wallet's error does not say + /// whether it stored them first, and an empty attempt equals empty + /// details that were never stored. + #[tokio::test] + async fn a_failed_publish_records_nothing() { + let ops = ScriptedSave { + publish_fails: true, + ..ScriptedSave::new(Ok(ContactDetails::default()), false) + }; + + let result = + save_contact_details(&ops, &ContactInfoUpdate::replace_all(None, None, false)).await; + + assert!(result.is_err()); + assert!(!*ops.marked.lock().unwrap()); + } + + /// Saved details that could not be read are not empty ones: a save that + /// keeps a text field would publish it as empty and lose it. Unhiding is + /// the one such save allowed, since the hidden list says it clears them; + /// the backend decides from the details it reads, not the list's flag. + #[tokio::test] + async fn unreadable_saved_details_are_replaced_only_by_unhiding() { + let unreadable = || ScriptedSave { + unreadable: true, + ..ScriptedSave::new( + Ok(ContactDetails { + hidden: true, ..Default::default() - }; - let Ok(encoded) = data.serialize() else { - continue; - }; - let encrypted = encrypt_private_data(&encoded, &key()).unwrap(); - assert!( - estimator.estimate_contact_info_write() - >= estimator.estimate_document_create_with_size(112 + encrypted.len()), - "{len}-byte fields and {accounts} accounts" - ); - } + }), + false, + ) + }; + + for update in [ + ContactInfoUpdate::note(Some("n".into())), + ContactInfoUpdate::visibility(true), + ] { + let ops = unreadable(); + let result = save_contact_details(&ops, &update).await; + assert!( + matches!(result, Err(TaskError::DashPayContactDetailsUnreadable)), + "{update:?}" + ); + assert!(ops.published.lock().unwrap().is_empty()); } + + let ops = unreadable(); + save_contact_details(&ops, &ContactInfoUpdate::visibility(false)) + .await + .expect("unhiding replaces them"); + assert_eq!( + *ops.published.lock().unwrap(), + vec![ContactDetails::default()] + ); + } + + /// A published save whose synced record fails is not reported as saved: + /// on reload the old legacy details would show again. The details did + /// reach the network, and the error says so. + #[tokio::test] + async fn a_failed_synced_record_fails_the_save() { + let ops = ScriptedSave::new(Ok(ContactDetails::default()), true) + .with_outcome(ContactInfoPublishOutcome::Published); + + let result = + save_contact_details(&ops, &ContactInfoUpdate::replace_all(None, None, false)).await; + + assert!(matches!( + result, + Err(TaskError::DashpaySidecarStorage { .. }) + )); + } + + /// A save kept on this device until a second contact exists published + /// nothing, so a failed synced record must not claim the change reached + /// the network; the user is asked to save again. + #[tokio::test] + async fn a_failed_synced_record_of_a_deferred_save_claims_no_publish() { + let ops = ScriptedSave::new(Ok(ContactDetails::default()), true); + + let result = + save_contact_details(&ops, &ContactInfoUpdate::replace_all(None, None, false)).await; + + let Err(error) = result else { + panic!("a failed synced record fails the save"); + }; + assert!( + matches!(error, TaskError::DashPayContactDetailsNotRecorded { .. }), + "got {error:?}" + ); + assert!(!error.to_string().contains("reached the network")); + } + + #[tokio::test] + async fn a_save_keeps_the_fields_it_does_not_replace() { + let current = ContactDetails { + nickname: Some("Bao".into()), + note: None, + hidden: true, + }; + let ops = ScriptedSave::new(Ok(current.clone()), false); + + let published = save_contact_details(&ops, &ContactInfoUpdate::note(Some("n".into()))) + .await + .expect("saved"); + + assert!(!published, "deferred until two contacts"); + assert_eq!( + *ops.published.lock().unwrap(), + vec![ContactDetails { + note: Some("n".into()), + ..current + }] + ); } fn contact_details_page(documents: impl IntoIterator) -> Documents { @@ -1223,17 +887,80 @@ mod tests { /// A stored contactInfo for `contact` whose note platform-wallet wrote. fn saved_note_document(document_id: u8, contact: Identifier, note: &str) -> Document { use platform_wallet::wallet::identity::crypto as upstream; - let user_id = encrypt_to_user_id(&contact.to_buffer(), &key()).expect("encrypt"); + let user_id = encrypt_to_user_id(&contact.to_buffer(), &key()); let mut document = lookup_contact_info_document(document_id, document_id.into(), user_id); let plaintext = upstream::encode_private_data(&upstream::ContactInfoPrivateData { note: Some(note.to_string()), ..Default::default() }); - let private_data = encrypt_private_data(&plaintext, &key()).expect("encrypt"); + let private_data = platform_encryption::encrypt_private_data(&key(), &[5; 16], &plaintext); document.set("privateData", Value::Bytes(private_data)); document } + /// The legacy details read from `documents` with keys from `derive_keys`. + async fn legacy_load( + documents: Vec, + derive_keys: D, + ) -> Result, TaskError> + where + D: FnMut(u32) -> DF, + DF: Future, Zeroizing<[u8; 32]>), TaskError>>, + { + let contract = + load_system_data_contract(SystemDataContract::Dashpay, PlatformVersion::latest()) + .expect("DashPay contract fixture"); + let query = DocumentQuery::new(contract, "contactInfo").expect("contactInfo query"); + let mut page = Some(contact_details_page(documents)); + super::super::contacts::load_contact_details( + query, + |_| ready(Ok::<_, TaskError>(page.take().unwrap_or_default())), + derive_keys, + ) + .await + } + + /// A cancelled password prompt for the legacy keys fails the read, so a + /// save does not keep a legacy-only nickname or hidden flag as empty. + #[tokio::test] + async fn a_cancelled_legacy_key_prompt_fails_the_read() { + let result = legacy_load(vec![saved_note_document(1, id(201), "n")], |_| { + ready(Err(TaskError::SecretPromptCancelled)) + }) + .await; + + assert!(matches!(result, Err(TaskError::SecretPromptCancelled))); + } + + /// A document whose own key index cannot be derived is skipped; the rest + /// still load. + #[tokio::test] + async fn an_underivable_legacy_document_is_skipped() { + let (readable, unreadable) = (id(201), id(202)); + let mut bad = saved_note_document(2, unreadable, "x"); + bad.set("derivationEncryptionKeyIndex", Value::U32(u32::MAX)); + let details = legacy_load(vec![saved_note_document(1, readable, "n"), bad], |index| { + ready(if index == u32::MAX { + Err(TaskError::ContactKeyDerivationFailed { + source: Box::new( + dash_sdk::dpp::key_wallet::bip32::ChildNumber::from_hardened_idx(index) + .expect_err("out of range"), + ), + }) + } else { + Ok((Zeroizing::new(key()), Zeroizing::new(key()))) + }) + }) + .await + .expect("loaded"); + + assert_eq!( + details.get(&readable).and_then(|c| c.note.as_deref()), + Some("n") + ); + assert!(!details.contains_key(&unreadable)); + } + /// The details loaded from `pages`, and whether every page was asked for /// in the order the write lookup uses. async fn load_details( @@ -1269,7 +996,7 @@ mod tests { #[tokio::test] async fn the_contact_details_load_reads_every_page() { let contact = id(201); - let other = encrypt_to_user_id(&id(202).to_buffer(), &key()).expect("encrypt"); + let other = encrypt_to_user_id(&id(202).to_buffer(), &key()); let first_page = contact_details_page( (1..=100).map(|byte| lookup_contact_info_document(byte, byte.into(), other)), ); @@ -1333,17 +1060,21 @@ mod tests { let mut first = lookup_contact_info_document( 1, 1, - encrypt_to_user_id(&undecryptable.to_buffer(), &key()).expect("encrypt"), + encrypt_to_user_id(&undecryptable.to_buffer(), &key()), ); first.set("privateData", Value::Bytes(vec![0xA5; 48])); let mut second = lookup_contact_info_document( 2, 2, - encrypt_to_user_id(&undecodable.to_buffer(), &key()).expect("encrypt"), + encrypt_to_user_id(&undecodable.to_buffer(), &key()), ); second.set( "privateData", - Value::Bytes(encrypt_private_data(&[0xFF; 40], &key()).expect("encrypt")), + Value::Bytes(platform_encryption::encrypt_private_data( + &key(), + &[5; 16], + &[0xFF; 40], + )), ); let (details, _) = load_details(vec![contact_details_page([first, second])]).await; @@ -1368,168 +1099,137 @@ mod tests { assert!(!details.get(&contact).expect("listed").details_unreadable); } - /// With two documents for one contact, the load shows the newest, the - /// one a save rewrites. A rewrite keeps it the newest, so the load and - /// the save stay on the same document; with the oldest, a rewrite would - /// move it to the end and the load would show the untouched one. + /// With two readable documents for one contact, the newer one is shown: + /// pages are ordered by `$updatedAt`, oldest first. #[tokio::test] - async fn the_contact_details_load_shows_the_document_a_save_rewrites() { + async fn the_contact_details_load_shows_the_newest_document() { let contact = id(201); let page = contact_details_page([ - saved_note_document(1, contact, "stale"), - saved_note_document(2, contact, "kept"), + saved_note_document(1, contact, "older"), + saved_note_document(2, contact, "newer"), ]); let (details, _) = load_details(vec![page]).await; assert_eq!( details.get(&contact).and_then(|c| c.note.as_deref()), - Some("kept") + Some("newer") ); - - let documents = vec![ - saved_note_document(1, contact, "stale"), - saved_note_document(2, contact, "kept"), - ]; - let existing = find_existing_contact_info(documents, contact, |_| { - Ok((Zeroizing::new(key()), Zeroizing::new(key()))) - }); - assert_eq!(existing.map(|existing| existing.derivation_index), Some(2)); } - /// Platform returns the fixed 32-byte `encToUserId` as `Value::Bytes32`; - /// a save must still find the contact's document instead of creating a - /// second one. - #[tokio::test] - async fn a_save_finds_a_document_as_platform_returns_it() { - let contact = id(230); - let encrypted = encrypt_to_user_id(&contact.to_buffer(), &key()).expect("encrypt"); - let mut document = lookup_contact_info_document(1, 5, encrypted); - document.set("encToUserId", Value::Bytes32(encrypted)); - - let lookup = scan_contact_info_documents(vec![document], contact, |documents, target| { - ready(Ok(find_existing_contact_info(documents, target, |_| { - Ok((Zeroizing::new(key()), Zeroizing::new(other_key()))) - }))) - }) - .await - .expect("scan"); - - assert_eq!( - lookup.existing.map(|existing| existing.derivation_index), - Some(5) - ); + /// What this client's strict reader accepts, without platform-wallet's + /// tolerant fallback. + fn strict_read(bytes: &[u8]) -> Option { + match read_private_data(bytes) { + PrivateDataReading::Read(data) => Some(data), + PrivateDataReading::Ambiguous | PrivateDataReading::Unreadable => None, + } } - #[test] - fn private_data_round_trips_every_accepted_account() { - let original = ContactInfoPrivateData { - version: 0, - alias_name: Some("Bao".to_string()), - note: Some("Met at the meetup".to_string()), - display_hidden: true, - accepted_accounts: vec![0, 3, 17], - }; - - let parsed = ContactInfoPrivateData::deserialize(&original.serialize().expect("serialize")) - .expect("a document this client wrote must parse back"); - - assert_eq!(parsed.alias_name.as_deref(), Some("Bao")); - assert_eq!(parsed.note.as_deref(), Some("Met at the meetup")); - assert!(parsed.display_hidden); - assert_eq!( - parsed.accepted_accounts, - vec![0, 3, 17], - "every accepted account must survive the round trip, not just the first" - ); + /// The bytes platform-wallet writes for `data`. + fn upstream_plaintext(data: &ContactInfoPrivateData) -> Vec { + platform_wallet::wallet::identity::crypto::encode_private_data(data) } - #[test] - fn private_data_round_trips_through_the_minimum_size_padding() { - // An empty private data is padded up to the contract's minimum size — - // the padding must not be mistaken for a field. - let original = ContactInfoPrivateData::new(); - let parsed = ContactInfoPrivateData::deserialize(&original.serialize().expect("serialize")) - .expect("padded plaintext must parse"); - - assert_eq!(parsed.alias_name, None); - assert_eq!(parsed.note, None); - assert!(!parsed.display_hidden); - assert!(parsed.accepted_accounts.is_empty()); + fn contact( + alias_name: Option<&str>, + note: Option<&str>, + display_hidden: bool, + accepted_accounts: Vec, + ) -> ContactInfoPrivateData { + ContactInfoPrivateData { + alias_name: alias_name.map(str::to_owned), + note: note.map(str::to_owned), + display_hidden, + accepted_accounts, + } } - #[test] - fn truncated_private_data_is_not_parsed_as_a_shorter_list() { - let bytes = ContactInfoPrivateData { - version: 0, - alias_name: None, - note: None, - display_hidden: false, - accepted_accounts: vec![1, 2, 3], + /// Byte-exact copy of the serializer older versions of this client used + /// (v1.0.0-weekly.20261020 and earlier, back to #810): single-byte + /// lengths, and a payload under 16 bytes padded with `0x00` and then + /// random bytes up to 16. `fill` stands in for the random bytes. + fn legacy_det_plaintext(data: &ContactInfoPrivateData, fill: u8) -> Vec { + let mut bytes = 0_u32.to_le_bytes().to_vec(); + for text in [&data.alias_name, &data.note] { + let text = text.as_deref().unwrap_or_default().as_bytes(); + bytes.push(u8::try_from(text.len()).expect("the old writer capped at 255")); + bytes.extend_from_slice(text); } - .serialize() - .expect("serialize"); - - // Chop the final account in half: the list declares three, so a parser - // that returned the two it could read would silently drop an account. - assert!( - ContactInfoPrivateData::deserialize(&bytes[..bytes.len() - 2]).is_none(), - "a truncated account list must not parse as a shorter one" - ); + bytes.push(u8::from(data.display_hidden)); + bytes.push(u8::try_from(data.accepted_accounts.len()).expect("at most 255")); + for account in &data.accepted_accounts { + bytes.extend_from_slice(&account.to_le_bytes()); + } + if bytes.len() < LEGACY_PLAINTEXT_SIZE { + bytes.push(0x00); + bytes.resize(LEGACY_PLAINTEXT_SIZE, fill); + } + bytes } - #[test] - fn unsupported_private_data_version_requires_confirmation() { - let mut bytes = ContactInfoPrivateData::new() - .serialize() - .expect("serialize"); - bytes[..4].copy_from_slice(&1_u32.to_le_bytes()); - - assert!( - ContactInfoPrivateData::deserialize(&bytes).is_none(), - "a future payload version must not be rewritten as though it were version zero" - ); + /// A legacy-key contactInfo for `contact` holding `plaintext`. + fn legacy_plaintext_document( + document_id: u8, + contact: Identifier, + plaintext: &[u8], + ) -> Document { + let user_id = encrypt_to_user_id(&contact.to_buffer(), &key()); + let mut document = lookup_contact_info_document(document_id, document_id.into(), user_id); + let private_data = platform_encryption::encrypt_private_data(&key(), &[5; 16], plaintext); + document.set("privateData", Value::Bytes(private_data)); + document } #[test] - fn invalid_utf8_is_not_treated_as_an_absent_contact_detail() { - let mut bytes = ContactInfoPrivateData::new() - .serialize() - .expect("serialize"); - bytes[4] = 1; - bytes[5] = 0xff; + fn private_data_round_trips_every_accepted_account() { + let original = contact(Some("Bao"), Some("Met at the meetup"), true, vec![0, 3, 17]); - assert!( - ContactInfoPrivateData::deserialize(&bytes).is_none(), - "an unreadable nickname must not silently become an empty nickname" + assert_eq!( + strict_read(&upstream_plaintext(&original)), + Some(original), + "every accepted account must survive the round trip, not just the first" ); } #[test] - fn unknown_visibility_encoding_requires_confirmation() { - let mut bytes = ContactInfoPrivateData::new() - .serialize() - .expect("serialize"); - bytes[6] = 2; - - assert!(ContactInfoPrivateData::deserialize(&bytes).is_none()); + fn private_data_round_trips_through_the_minimum_size_padding() { + // Empty details are padded up to the contract's minimum size; the + // padding must not be mistaken for a field. + let bytes = upstream_plaintext(&ContactInfoPrivateData::default()); + assert_eq!(bytes.len(), MIN_PLAINTEXT_SIZE); + assert_eq!(strict_read(&bytes), Some(ContactInfoPrivateData::default())); } #[test] - fn trailing_extension_bytes_require_confirmation() { - let mut bytes = ContactInfoPrivateData { - version: 0, - alias_name: Some("123456789".to_string()), - note: None, - display_hidden: false, - accepted_accounts: Vec::new(), + fn malformed_private_data_is_not_read_strictly() { + let accounts = upstream_plaintext(&contact(None, None, false, vec![1, 2, 3])); + // A list that declares three accounts must not parse as a shorter one. + assert!(strict_read(&accounts[..accounts.len() - 2]).is_none()); + + let empty = upstream_plaintext(&ContactInfoPrivateData::default()); + let mut future_version = empty.clone(); + future_version[..4].copy_from_slice(&1_u32.to_le_bytes()); + let mut invalid_utf8 = empty.clone(); + invalid_utf8[4] = 1; + invalid_utf8[5] = 0xff; + let mut unknown_visibility = empty.clone(); + unknown_visibility[6] = 2; + let mut no_sentinel = empty; + no_sentinel[8] = 1; + let mut extended = upstream_plaintext(&contact(Some("123456789"), None, false, Vec::new())); + assert_eq!(extended.len(), MIN_PLAINTEXT_SIZE); + extended.push(42); + + for bytes in [ + future_version, + invalid_utf8, + unknown_visibility, + no_sentinel, + extended, + ] { + assert!(strict_read(&bytes).is_none(), "{bytes:02x?}"); } - .serialize() - .expect("serialize without minimum-size padding"); - assert_eq!(bytes.len(), ContactInfoPrivateData::MIN_PLAINTEXT_SIZE); - bytes.push(42); - - assert!(ContactInfoPrivateData::deserialize(&bytes).is_none()); } /// Only the 16-byte layout older versions of this client wrote may hold @@ -1537,191 +1237,108 @@ mod tests { /// must be all zeros. #[test] fn contact_info_padding_rejects_nonzero_bytes_after_the_sentinel() { - let canonical = ContactInfoPrivateData::new() - .serialize() - .expect("serialize"); - for length in (9..=ContactInfoPrivateData::MIN_PLAINTEXT_SIZE) - .filter(|length| *length != ContactInfoPrivateData::LEGACY_PLAINTEXT_SIZE) - { - assert!(ContactInfoPrivateData::deserialize(&canonical[..length]).is_some()); + let canonical = upstream_plaintext(&ContactInfoPrivateData::default()); + for length in (9..=MIN_PLAINTEXT_SIZE).filter(|length| *length != LEGACY_PLAINTEXT_SIZE) { + assert!(strict_read(&canonical[..length]).is_some()); for offset in 9..length { let mut malformed = canonical[..length].to_vec(); malformed[offset] = 42; assert!( - ContactInfoPrivateData::deserialize(&malformed).is_none(), - "nonzero padding at {offset} in {length} bytes must require confirmation" + strict_read(&malformed).is_none(), + "nonzero padding at {offset} in {length} bytes must not be read" ); } } } - /// Byte-exact copy of the serializer older versions of this client used - /// (v1.0.0-weekly.20261020 and earlier, back to #810): single-byte - /// lengths, and a payload under 16 bytes padded with `0x00` and then - /// random bytes up to 16. `fill` stands in for the random bytes. - fn legacy_det_plaintext(data: &ContactInfoPrivateData, fill: u8) -> Vec { - let mut bytes = data.version.to_le_bytes().to_vec(); - for text in [&data.alias_name, &data.note] { - let text = text.as_deref().unwrap_or_default().as_bytes(); - bytes.push(u8::try_from(text.len()).expect("the old writer capped at 255")); - bytes.extend_from_slice(text); - } - bytes.push(u8::from(data.display_hidden)); - bytes.push(u8::try_from(data.accepted_accounts.len()).expect("at most 255")); - for account in &data.accepted_accounts { - bytes.extend_from_slice(&account.to_le_bytes()); - } - if bytes.len() < ContactInfoPrivateData::LEGACY_PLAINTEXT_SIZE { - bytes.push(0x00); - bytes.resize(ContactInfoPrivateData::LEGACY_PLAINTEXT_SIZE, fill); - } - bytes - } - - fn legacy_contact( - alias_name: Option<&str>, - note: Option<&str>, - display_hidden: bool, - accepted_accounts: Vec, - ) -> ContactInfoPrivateData { - ContactInfoPrivateData { - version: 0, - alias_name: alias_name.map(str::to_owned), - note: note.map(str::to_owned), - display_hidden, - accepted_accounts, - } - } - - fn assert_same_details(parsed: &ContactInfoPrivateData, expected: &ContactInfoPrivateData) { - assert_eq!(parsed.alias_name, expected.alias_name); - assert_eq!(parsed.note, expected.note); - assert_eq!(parsed.display_hidden, expected.display_hidden); - assert_eq!(parsed.accepted_accounts, expected.accepted_accounts); - } - /// Details an older version of this client saved for a hidden contact, or - /// with a short nickname or note, are padded with random bytes. A save - /// must read them, not report them unreadable and offer to wipe them. + /// with a short nickname or note, are padded with random bytes, and long + /// ones carry single-byte lengths of 253 to 255, which CompactSize + /// reserves. Both are read with every field. #[test] - fn a_save_reads_details_padded_by_older_versions() { - let contacts = [ - legacy_contact(None, None, true, Vec::new()), - legacy_contact(Some("Bob"), None, false, Vec::new()), - legacy_contact(None, Some("hi"), true, Vec::new()), - legacy_contact(Some("Al"), None, true, vec![0]), - legacy_contact(Some("Bao"), Some("Met"), false, Vec::new()), + fn details_written_by_older_versions_are_read() { + let long = "y".repeat(254); + let mut contacts = vec![ + contact(None, None, true, Vec::new()), + contact(Some("Bob"), None, false, Vec::new()), + contact(None, Some("hi"), true, Vec::new()), + contact(Some("Al"), None, true, vec![0]), + contact(Some("Bao"), Some("Met"), false, Vec::new()), + contact(Some(&long), Some("Met"), false, vec![1]), ]; + for len in [253, 254, 255] { + let text = "x".repeat(len); + contacts.push(contact(Some(&text), None, false, vec![2])); + contacts.push(contact(None, Some(&text), true, Vec::new())); + contacts.push(contact(Some(&text), Some(&text), true, vec![0, 3])); + } for expected in &contacts { for fill in [0x01, 0x5A, 0xFF] { let plaintext = legacy_det_plaintext(expected, fill); + assert_eq!(strict_read(&plaintext).as_ref(), Some(expected)); assert_eq!( - plaintext.len(), - ContactInfoPrivateData::LEGACY_PLAINTEXT_SIZE + decode_contact_info_details(&plaintext).as_ref(), + Some(expected) ); - let stored = contact_info_document(Some(Value::Bytes( - encrypt_private_data(&plaintext, &key()).expect("encrypt"), - ))); - - let parsed = read_contact_info_private_data( - Some(&stored), - &key(), - UnreadableContactInfoPolicy::Abort, - ) - .unwrap_or_else(|error| panic!("{expected:?} padded with {fill:#x}: {error:?}")); - assert_same_details(&parsed, expected); - - let unhidden = apply_contact_info_update( - ContactInfoUpdate::visibility(false), - Some(&stored), - &key(), - ) - .expect("unhiding keeps the saved details"); - assert!(!unhidden.display_hidden); - assert_eq!(unhidden.alias_name, expected.alias_name); - assert_eq!(unhidden.note, expected.note); - assert_eq!(unhidden.accepted_accounts, expected.accepted_accounts); } } } - /// Older versions of this client wrote every length as one byte, up to - /// 255. In CompactSize, 253 to 255 are prefix markers instead. - #[test] - fn a_save_reads_long_details_written_with_single_byte_lengths() { - for len in [253, 254, 255] { - let text = "x".repeat(len); - for expected in [ - legacy_contact(Some(&text), None, false, vec![2]), - legacy_contact(None, Some(&text), true, Vec::new()), - legacy_contact(Some(&text), Some(&text), true, vec![0, 3]), - ] { - let parsed = - ContactInfoPrivateData::deserialize(&legacy_det_plaintext(&expected, 0xAA)) - .unwrap_or_else(|| panic!("{len}-byte details must stay readable")); - assert_same_details(&parsed, &expected); - } - } - } + /// A legacy document with a 254-byte nickname loads with that nickname, + /// which platform-wallet's reader alone misreads. + #[tokio::test] + async fn a_legacy_document_with_a_long_nickname_is_shown() { + let owner = id(201); + let nickname = "z".repeat(254); + let plaintext = legacy_det_plaintext(&contact(Some(&nickname), None, false, vec![]), 0); + assert_ne!( + platform_wallet::wallet::identity::crypto::decode_private_data(&plaintext) + .ok() + .and_then(|data| data.alias_name), + Some(nickname.clone()) + ); - /// The contact list reads the same older layouts a save reads, so such a - /// contact is shown with its details instead of hidden as unreadable. - #[test] - fn the_contact_list_reads_details_written_by_older_versions() { - let long = "y".repeat(254); - for expected in [ - legacy_contact(None, None, true, Vec::new()), - legacy_contact(Some("Bob"), Some("hi"), false, Vec::new()), - legacy_contact(Some(&long), Some("Met"), false, vec![1]), - ] { - let shown = decode_contact_info_details(&legacy_det_plaintext(&expected, 0xC3)) - .unwrap_or_else(|| panic!("{expected:?} must be shown")); - assert_eq!(shown.alias_name, expected.alias_name); - assert_eq!(shown.note, expected.note); - assert_eq!(shown.display_hidden, expected.display_hidden); - assert_eq!(shown.accepted_accounts, expected.accepted_accounts); - } + let details = legacy_load( + vec![legacy_plaintext_document(1, owner, &plaintext)], + |_| ready(Ok((Zeroizing::new(key()), Zeroizing::new(key())))), + ) + .await + .expect("loaded"); + + let shown = details.get(&owner).expect("listed"); + assert_eq!(shown.nickname.as_deref(), Some(nickname.as_str())); + assert!(!shown.details_unreadable); } /// Tolerating the older layouts must not let corrupt payloads through. #[test] fn legacy_layouts_do_not_hide_corruption() { - let hidden = legacy_contact(None, None, true, Vec::new()); - let legacy = legacy_det_plaintext(&hidden, 0x5A); + let legacy = legacy_det_plaintext(&contact(None, None, true, Vec::new()), 0x5A); let mut no_sentinel = legacy.clone(); no_sentinel[8] = 0x5A; - assert!(ContactInfoPrivateData::deserialize(&no_sentinel).is_none()); + assert!(strict_read(&no_sentinel).is_none()); for length in (10..legacy.len()).chain([legacy.len() + 1]) { let mut resized = legacy.clone(); resized.resize(length, 0x5A); assert!( - ContactInfoPrivateData::deserialize(&resized).is_none(), + strict_read(&resized).is_none(), "random padding over {length} bytes is not a layout any client wrote" ); } + let long = + legacy_det_plaintext(&contact(Some(&"x".repeat(253)), None, false, Vec::new()), 0); // A single-byte length that runs past the end of the payload. - let mut overrun = legacy_det_plaintext( - &legacy_contact(Some(&"x".repeat(253)), None, false, Vec::new()), - 0, - ); - overrun.truncate(overrun.len() - 1); - assert!(ContactInfoPrivateData::deserialize(&overrun).is_none()); - assert!(decode_contact_info_details(&overrun).is_none()); - + let overrun = long[..long.len() - 1].to_vec(); // Single-byte lengths still need valid text and no trailing data. - let long = legacy_det_plaintext( - &legacy_contact(Some(&"x".repeat(253)), None, false, Vec::new()), - 0, - ); let mut invalid_utf8 = long.clone(); invalid_utf8[5] = 0xFF; - let mut extended = long.clone(); + let mut extended = long; extended.push(0); - for corrupt in [invalid_utf8, extended] { - assert!(ContactInfoPrivateData::deserialize(&corrupt).is_none()); + for corrupt in [overrun, invalid_utf8, extended] { + assert!(strict_read(&corrupt).is_none()); assert!(decode_contact_info_details(&corrupt).is_none()); } } @@ -1735,41 +1352,37 @@ mod tests { note } - /// Whatever a save reads, the contact list shows with the same values, - /// including legacy text with control characters, which platform-wallet - /// reads as different fields. + /// The details shown are what the strict reader reads, including legacy + /// text with control characters, which platform-wallet reads as different + /// fields. #[test] - fn the_contact_list_shows_what_a_save_reads() { + fn shown_details_match_the_strict_reading() { let mut payloads = Vec::new(); for len in [0, 3, 252, 253, 254, 255] { let text = "x".repeat(len); let text = (len > 0).then_some(text.as_str()); for hidden in [false, true] { - let contact = legacy_contact(text, text, hidden, vec![0, 7]); - payloads.push(legacy_det_plaintext(&contact, 0x9C)); - payloads.push(contact.serialize().expect("serialize")); + let details = contact(text, text, hidden, vec![0, 7]); + payloads.push(legacy_det_plaintext(&details, 0x9C)); + payloads.push(upstream_plaintext(&details)); } } let control = control_character_note(); - for contact in [ - legacy_contact(None, Some(&control), false, Vec::new()), - legacy_contact(Some(&control), Some("Met"), true, vec![4]), - legacy_contact(Some("\u{0}\u{1}"), Some(&control), false, vec![1]), + for details in [ + contact(None, Some(&control), false, Vec::new()), + contact(Some(&control), Some("Met"), true, vec![4]), + contact(Some("\u{0}\u{1}"), Some(&control), false, vec![1]), ] { - payloads.push(legacy_det_plaintext(&contact, 0)); - payloads.push(contact.serialize().expect("serialize")); + payloads.push(legacy_det_plaintext(&details, 0)); + payloads.push(upstream_plaintext(&details)); } for payload in &payloads { - let saved = ContactInfoPrivateData::deserialize(payload) - .unwrap_or_else(|| panic!("a save must read {payload:02x?}")); - let shown = decode_contact_info_details(payload) - .unwrap_or_else(|| panic!("the contact list must show {payload:02x?}")); - assert_eq!(shown.alias_name, saved.alias_name, "{payload:02x?}"); - assert_eq!(shown.note, saved.note, "{payload:02x?}"); - assert_eq!(shown.display_hidden, saved.display_hidden, "{payload:02x?}"); + let strict = strict_read(payload) + .unwrap_or_else(|| panic!("the strict reader must read {payload:02x?}")); assert_eq!( - shown.accepted_accounts, saved.accepted_accounts, + decode_contact_info_details(payload), + Some(strict), "{payload:02x?}" ); } @@ -1781,24 +1394,21 @@ mod tests { fn control_characters_in_long_fields_do_not_hide_corruption() { let control = control_character_note(); let long_control = format!("\u{0}\u{1}{}", "x".repeat(252)); - for contact in [ - legacy_contact(None, Some(&control), true, Vec::new()), - legacy_contact(Some(&long_control), None, false, vec![2]), - legacy_contact(Some(&control), Some(&long_control), false, Vec::new()), + for details in [ + contact(None, Some(&control), true, Vec::new()), + contact(Some(&long_control), None, false, vec![2]), + contact(Some(&control), Some(&long_control), false, Vec::new()), ] { for payload in [ - legacy_det_plaintext(&contact, 0), - contact.serialize().expect("serialize"), + legacy_det_plaintext(&details, 0), + upstream_plaintext(&details), ] { let mut appended = payload.clone(); appended.push(0); - let mut truncated = payload.clone(); + let mut truncated = payload; truncated.pop(); for corrupt in [appended, truncated] { - assert!( - ContactInfoPrivateData::deserialize(&corrupt).is_none(), - "a save must not read {corrupt:02x?}" - ); + assert!(strict_read(&corrupt).is_none(), "{corrupt:02x?}"); } } } @@ -1812,11 +1422,11 @@ mod tests { let mut bytes = vec![0, 0, 0, 0, 0xFD, 5, 0]; bytes.extend_from_slice(b"hello"); bytes.extend_from_slice(&[0, 0, 0]); - assert!(ContactInfoPrivateData::deserialize(&bytes).is_none()); + assert!(strict_read(&bytes).is_none()); // A truncated payload without reserved lengths stays rejected. - let short = legacy_det_plaintext(&legacy_contact(Some("Bob"), None, false, vec![1]), 0); - assert!(ContactInfoPrivateData::deserialize(&short[..short.len() - 2]).is_none()); + let short = legacy_det_plaintext(&contact(Some("Bob"), None, false, vec![1]), 0); + assert!(strict_read(&short[..short.len() - 2]).is_none()); } /// An older version's 253-byte note starting with `03 01`, which a @@ -1824,12 +1434,12 @@ mod tests { /// a complete payload with other values. fn legacy_note_that_also_reads_as_compact_size() -> Vec { let note = format!("\u{3}\u{1}{}", "x".repeat(251)); - let contact = legacy_contact(None, Some(¬e), true, vec![0, 0]); + let details = contact(None, Some(¬e), true, vec![0, 0]); let mut payload = vec![0, 0, 0, 0, 0x00, 0xFD]; payload.extend_from_slice(note.as_bytes()); payload.extend_from_slice(&[0x01, 0x02]); payload.extend_from_slice(&[0; 8]); - assert_eq!(payload, legacy_det_plaintext(&contact, 0)); + assert_eq!(payload, legacy_det_plaintext(&details, 0)); payload } @@ -1837,273 +1447,86 @@ mod tests { /// is `1` (49). The legacy reading takes 253 bytes of nickname, then a /// 49-byte note that ends exactly at the real visibility byte. fn upstream_alias_that_also_reads_as_legacy() -> Vec { - use platform_wallet::wallet::identity::crypto as upstream; let mut alias = "x".repeat(300); alias.replace_range(251..252, "1"); - upstream::encode_private_data(&upstream::ContactInfoPrivateData { - alias_name: Some(alias), - note: None, - display_hidden: true, - accepted_accounts: vec![7], - }) + upstream_plaintext(&contact(Some(&alias), None, true, vec![7])) } /// Bytes that read completely both as an older version's layout and as - /// CompactSize, with different values, are unreadable. A save prompts - /// instead of guessing and persisting the guess, and the contact list - /// shows no guess either. - #[test] - fn details_that_read_two_ways_are_unreadable() { - use platform_wallet::wallet::identity::crypto as upstream; + /// CompactSize, with different values, are unreadable: no guess is shown, + /// and a legacy document holding them keeps its contact hidden. + #[tokio::test] + async fn details_that_read_two_ways_are_unreadable() { for payload in [ legacy_note_that_also_reads_as_compact_size(), upstream_alias_that_also_reads_as_legacy(), ] { - let legacy = ContactInfoPrivateData::parse(&payload, LengthPrefix::SingleByte) + let legacy = parse_private_data(&payload, LengthPrefix::SingleByte) .expect("a complete legacy reading"); - let compact = ContactInfoPrivateData::parse(&payload, LengthPrefix::CompactSize) + let compact = parse_private_data(&payload, LengthPrefix::CompactSize) .expect("a complete CompactSize reading"); assert_ne!(legacy, compact); - assert!(upstream::decode_private_data(&payload).is_ok()); - - assert!(ContactInfoPrivateData::deserialize(&payload).is_none()); assert!( - decode_contact_info_details(&payload).is_none(), - "the contact list must not show a guess" + platform_wallet::wallet::identity::crypto::decode_private_data(&payload).is_ok() ); - let stored = contact_info_document(Some(Value::Bytes( - encrypt_private_data(&payload, &key()).expect("encrypt"), - ))); assert!(matches!( - read_contact_info_private_data( - Some(&stored), - &key(), - UnreadableContactInfoPolicy::Abort, - ), - Err(TaskError::DashPayContactInfoRead { - source: ContactInfoReadError::DeserializeFailed, - }) + read_private_data(&payload), + PrivateDataReading::Ambiguous )); + assert!( + decode_contact_info_details(&payload).is_none(), + "no guess may be shown" + ); + + let owner = id(202); + let details = legacy_load(vec![legacy_plaintext_document(1, owner, &payload)], |_| { + ready(Ok((Zeroizing::new(key()), Zeroizing::new(key())))) + }) + .await + .expect("loaded"); + let shown = details.get(&owner).expect("listed"); + assert!(shown.details_unreadable); + assert!(shown.is_hidden); } } - /// What this client writes now still reads back when a length is 253 to - /// 255: its `FD xx 00` prefix has `xx` in `FD..=FF`, which the legacy + /// What platform-wallet writes reads back unchanged when a length is 253 + /// to 255: its `FD xx 00` prefix has `xx` in `FD..=FF`, which the legacy /// reading takes as text that is not valid UTF-8. #[test] - fn current_details_with_reserved_lengths_read_back_unchanged() { + fn upstream_details_with_reserved_lengths_read_back_unchanged() { let reviewer_shaped = |len: usize| format!("\u{3}\u{1}{}", "x".repeat(len - 2)); for len in [253, 254, 255] { for text in ["x".repeat(len), reviewer_shaped(len)] { for expected in [ - legacy_contact(Some(&text), None, false, vec![2]), - legacy_contact(None, Some(&text), true, vec![0, 0]), - legacy_contact(Some(&text), Some(&text), true, vec![0, 3]), + contact(Some(&text), None, false, vec![2]), + contact(None, Some(&text), true, vec![0, 0]), + contact(Some(&text), Some(&text), true, vec![0, 3]), ] { - let payload = expected.serialize().expect("serialize"); - let parsed = ContactInfoPrivateData::deserialize(&payload) - .unwrap_or_else(|| panic!("{len}-byte details must read back")); - assert_same_details(&parsed, &expected); + let payload = upstream_plaintext(&expected); + assert_eq!(strict_read(&payload).as_ref(), Some(&expected)); + assert_eq!(decode_contact_info_details(&payload), Some(expected)); } } } } - /// Another client may write a nickname or note of 256 bytes or more, - /// which this client never writes. Unless its bytes also form a complete - /// older layout, it reads back. + /// Another client may write a nickname or note of 256 bytes or more. + /// Unless its bytes also form a complete older layout, it reads back. #[test] fn upstream_details_over_255_bytes_read_back() { - use platform_wallet::wallet::identity::crypto as upstream; for len in [256, 259, 300, 1000] { - let text = Some("x".repeat(len)); - for (alias_name, note) in [ - (None, text.clone()), - (text.clone(), None), - (text.clone(), text.clone()), - ] { + let text = "x".repeat(len); + let text = Some(text.as_str()); + for (alias_name, note) in [(None, text), (text, None), (text, text)] { for hidden in [false, true] { - let theirs = upstream::ContactInfoPrivateData { - alias_name: alias_name.clone(), - note: note.clone(), - display_hidden: hidden, - accepted_accounts: vec![0, 0], - }; - let payload = upstream::encode_private_data(&theirs); - let parsed = ContactInfoPrivateData::deserialize(&payload) - .unwrap_or_else(|| panic!("{len}-byte details must read back")); - assert_eq!(parsed.alias_name, theirs.alias_name); - assert_eq!(parsed.note, theirs.note); - assert_eq!(parsed.display_hidden, hidden); - assert_eq!(parsed.accepted_accounts, theirs.accepted_accounts); + let theirs = contact(alias_name, note, hidden, vec![0, 0]); + let payload = upstream_plaintext(&theirs); + assert_eq!(strict_read(&payload).as_ref(), Some(&theirs)); assert_eq!(decode_contact_info_details(&payload), Some(theirs)); } } } } - - #[test] - fn minimum_size_padding_requires_the_sentinel() { - let mut bytes = ContactInfoPrivateData::new() - .serialize() - .expect("serialize"); - bytes[8] = 1; - - assert!(ContactInfoPrivateData::deserialize(&bytes).is_none()); - } - - #[test] - fn contact_info_note_preserves_a_concurrent_visibility_change() { - let existing = stored_contact_info(vec![0, 4, 9], &key()); - let data = apply_contact_info_update( - ContactInfoUpdate::note(Some("New note".into())), - Some(&existing), - &key(), - ) - .unwrap(); - assert!( - data.display_hidden, - "note edits must keep the latest stored visibility" - ); - assert_eq!(data.note.as_deref(), Some("New note")); - assert_eq!(data.alias_name.as_deref(), Some("Bao")); - assert_eq!(data.accepted_accounts, vec![0, 4, 9]); - } - - #[test] - fn visibility_update_preserves_every_unrelated_stored_field() { - let existing = stored_contact_info(vec![0, 4, 9], &key()); - let data = apply_contact_info_update( - ContactInfoUpdate::visibility(false), - Some(&existing), - &key(), - ) - .expect("stored details must be readable"); - - assert_eq!(data.alias_name.as_deref(), Some("Bao")); - assert_eq!(data.note, None); - assert!(!data.display_hidden); - assert_eq!(data.accepted_accounts, vec![0, 4, 9]); - } - - #[test] - fn replace_overwrites_whatever_the_document_stored() { - let existing = stored_contact_info(vec![0, 4, 9], &key()); - - let data = apply_contact_info_update( - ContactInfoUpdate::replace_all(None, None, false, vec![2]), - Some(&existing), - &other_key(), - ) - .expect("an explicit full replacement does not read stored data"); - - assert_eq!(data.accepted_accounts, vec![2]); - assert_eq!(data.alias_name, None); - } - - #[test] - fn preserving_a_contact_with_no_stored_document_yields_no_accounts() { - let data = apply_contact_info_update(ContactInfoUpdate::visibility(false), None, &key()) - .expect("a first-ever contactInfo has nothing to preserve"); - - assert!(data.accepted_accounts.is_empty()); - } - - #[test] - fn unreadable_private_data_aborts_the_write() { - let existing = stored_contact_info(vec![0, 4, 9], &other_key()); - - // A wrong-key AES-CBC decrypt is unauthenticated: PKCS7 unpadding usually - // rejects it (DecryptFailed), but ~1/256 the random IV yields valid - // padding and the garbage plaintext fails to parse (DeserializeFailed). - // Both are the "present but unreadable" abort this test asserts. - assert!( - matches!( - apply_contact_info_update( - ContactInfoUpdate::visibility(false), - Some(&existing), - &key(), - ), - Err(TaskError::DashPayContactInfoRead { - source: ContactInfoReadError::DecryptFailed - | ContactInfoReadError::DeserializeFailed, - }) - ), - "an undecryptable present payload must abort before it can be overwritten" - ); - } - - #[test] - fn confirmed_overwrite_is_the_only_escape_hatch_for_unreadable_private_data() { - use crate::model::dashpay::ContactInfoUpdate; - - let existing = stored_contact_info(vec![0, 4, 9], &other_key()); - let update = ContactInfoUpdate::visibility(false); - - // Wrong-key decrypt aborts as either DecryptFailed or (≈1/256, on a - // random IV that passes PKCS7 unpadding) DeserializeFailed. - assert!(matches!( - apply_contact_info_update(update.clone(), Some(&existing), &key()), - Err(TaskError::DashPayContactInfoRead { - source: ContactInfoReadError::DecryptFailed - | ContactInfoReadError::DeserializeFailed, - }) - )); - - let replaced = - apply_contact_info_update(update.overwrite_unreadable(), Some(&existing), &key()) - .expect("a confirmed overwrite must let the contact be unhidden"); - assert_eq!(replaced.alias_name, None); - assert_eq!(replaced.note, None); - assert!(!replaced.display_hidden); - assert!(replaced.accepted_accounts.is_empty()); - } - - #[test] - fn missing_private_data_is_safe_to_treat_as_empty() { - let existing = contact_info_document(None); - let data = apply_contact_info_update( - ContactInfoUpdate::visibility(false), - Some(&existing), - &key(), - ) - .expect("an absent payload contains no details to lose"); - - assert!(data.accepted_accounts.is_empty()); - } - - #[test] - fn unexpected_private_data_type_requires_confirmation() { - let existing = contact_info_document(Some(Value::Text("unknown".to_string()))); - - assert!(matches!( - apply_contact_info_update( - ContactInfoUpdate::visibility(false), - Some(&existing), - &key(), - ), - Err(TaskError::DashPayContactInfoRead { - source: ContactInfoReadError::UnexpectedPrivateDataType, - }) - )); - } - - #[test] - fn undecodable_private_data_aborts_the_write() { - let encrypted = - encrypt_private_data(&[0, 0, 0, 0], &key()).expect("encrypt malformed data"); - let existing = contact_info_document(Some(Value::Bytes(encrypted))); - - assert!(matches!( - apply_contact_info_update( - ContactInfoUpdate::visibility(false), - Some(&existing), - &key(), - ), - Err(TaskError::DashPayContactInfoRead { - source: ContactInfoReadError::DeserializeFailed, - }) - )); - } } diff --git a/src/backend_task/dashpay/contact_requests.rs b/src/backend_task/dashpay/contact_requests.rs index 04ff69481..e11b5ad75 100644 --- a/src/backend_task/dashpay/contact_requests.rs +++ b/src/backend_task/dashpay/contact_requests.rs @@ -5,17 +5,12 @@ use super::encryption::{ use super::errors::DashPayError; use super::validation::validate_contact_request_before_send; use crate::backend_task::BackendTaskSuccessResult; -use crate::backend_task::dashpay::auto_accept_proof::{ - AutoAcceptProofData, create_auto_accept_proof_bytes_with_key, -}; use crate::backend_task::error::TaskError; use crate::context::AppContext; -use crate::model::dashpay::{ - ContactInfoUpdate, UnreadableContactInfoPolicy, contact_request_recipient, -}; +use crate::model::dashpay::contact_request_recipient; use crate::model::document::new_document_for_creation; use crate::model::qualified_identity::QualifiedIdentity; -use crate::wallet_backend::{ContactRequestActionKind, ContactRequestActionPhase}; +use crate::wallet_backend::{ContactRequestActionKind, HeldPeerLock}; // Upstream contact-request type: used to record the sent request in the // local wallet-manager so dashpay_sync can auto-establish the contact. use bip39::rand::{SeedableRng, rngs::StdRng}; @@ -102,33 +97,8 @@ pub async fn load_contact_requests( .filter_map(|(id, doc)| doc.map(|d| (id, d))) .collect(); - // Filter out mutual requests (where both parties have sent requests to each other) - // These are now contacts, not pending requests - let contacts_established: HashSet = incoming - .iter() - .map(|(_, doc)| doc.owner_id()) - .filter(|from_id| { - outgoing - .iter() - .any(|(_, doc)| contact_request_recipient(doc).as_ref() == Some(from_id)) - }) - .collect(); - - // Filter out established contacts from both lists. An outgoing document - // with an unreadable recipient is kept: it cannot be attributed, and hiding - // a request the user may still be waiting on is the worse failure. - incoming.retain(|(_, doc)| !contacts_established.contains(&doc.owner_id())); - - outgoing.retain(|(_, doc)| match contact_request_recipient(doc) { - Some(to_id) => !contacts_established.contains(&to_id), - None => true, - }); - - // Drop requests the user has already resolved locally (declined an incoming - // one, or withdrawn a sent one). Platform keeps contactRequest documents - // forever, so without this the resolved row reappears on every reload. let backend = app_context.wallet_backend().ok(); - retain_unresolved( + pending_requests( &mut incoming, &mut outgoing, |sender| match &backend { @@ -154,6 +124,33 @@ pub async fn load_contact_requests( }) } +/// Keep only the requests still waiting for an answer: drop the pairs that +/// are contacts (both sides sent a request, unless the owner withdrew theirs +/// or declined the other's — a reply to a withdrawn request is a new request +/// to answer), then every request the user resolved on this device; see +/// [`retain_unresolved`]. +fn pending_requests( + incoming: &mut Vec<(Identifier, Document)>, + outgoing: &mut Vec<(Identifier, Document)>, + is_declined: impl Fn(&Identifier) -> bool, + is_withdrawn: impl Fn(&Identifier) -> bool, +) { + // A sender the owner declined is not a contact until the owner + // re-engages, which clears the decline. + let contacts_established = super::contacts::mutual_contacts(incoming, outgoing, |peer| { + is_withdrawn(peer) || is_declined(peer) + }); + // An outgoing document with an unreadable recipient is kept: it cannot be + // attributed, and hiding a request the user may still be waiting on is + // the worse failure. + incoming.retain(|(_, doc)| !contacts_established.contains(&doc.owner_id())); + outgoing.retain(|(_, doc)| match contact_request_recipient(doc) { + Some(to_id) => !contacts_established.contains(&to_id), + None => true, + }); + retain_unresolved(incoming, outgoing, is_declined, is_withdrawn); +} + /// Drop every request the user has already resolved: an incoming one they /// declined (per `is_declined`, keyed on the sender) or a sent one they withdrew /// (per `is_withdrawn`, keyed on the recipient). @@ -239,7 +236,33 @@ pub async fn send_contact_request_with_proof( signing_key: IdentityPublicKey, to_username_or_id: String, account_label: Option, - qr_auto_accept: Option, + qr_code: Option, +) -> Result { + send_contact_request_inner( + app_context, + sdk, + identity, + signing_key, + to_username_or_id, + account_label, + qr_code, + None, + ) + .await +} + +/// Body of [`send_contact_request_with_proof`]; `held` is the request-action +/// lock a caller already holds for the recipient, if any. +#[allow(clippy::too_many_arguments)] +async fn send_contact_request_inner( + app_context: &Arc, + sdk: &Sdk, + identity: QualifiedIdentity, + signing_key: IdentityPublicKey, + to_username_or_id: String, + account_label: Option, + qr_code: Option, + held: Option<&HeldPeerLock>, ) -> Result { if let Some(label) = account_label.as_deref() && let Err(error) = crate::model::dashpay::validate_account_label(label) @@ -309,6 +332,17 @@ pub async fn send_contact_request_with_proof( let existing = Document::fetch_many(sdk, existing_query).await?; if !existing.is_empty() { + // A withdrawn request still stands on Platform: sending again restores + // it instead of publishing a duplicate. This also finishes a send whose + // re-engagement failed after it was published. + if let Ok(backend) = app_context.wallet_backend() + && restore_under_peer_lock(&backend, identity.identity.id(), to_identity_id, held) + .await? + { + return Ok(BackendTaskSuccessResult::DashPayContactRequestSent( + to_username_or_id.to_string(), + )); + } return Err(DashPayError::ContactRequestAlreadySent { to: to_username_or_id.to_string(), } @@ -492,23 +526,11 @@ pub async fn send_contact_request_with_proof( ); } - // If QR auto-accept data is provided, create the proof bytes now to match the final accountReference - if let Some(qr) = qr_auto_accept { - // Ensure the QR target matches the resolved recipient - if qr.identity_id != to_identity_id { - return Err(DashPayError::InvalidQrCode { - reason: "QR code target identity does not match recipient".to_string(), - } - .into()); - } - let proof = create_auto_accept_proof_bytes_with_key( - qr.expires_at, - &qr.proof_key, - &identity.identity.id(), - &to_identity_id, - account_reference, - ) - .map_err(|e| TaskError::EncryptionError { detail: e })?; + // A scanned contact QR code signs the autoAcceptProof over the final + // accountReference. The recipient was resolved from the code's own + // username, so the proof is always addressed to the code's owner. + if let Some(qr) = qr_code { + let proof = qr.sign_proof(&identity.identity.id(), &to_identity_id, account_reference); tracing::debug!( "Including autoAcceptProof in contact request ({} bytes)", proof.len() @@ -592,31 +614,15 @@ pub async fn send_contact_request_with_proof( created_at_ts, ); if let Ok(backend) = app_context.wallet_backend() { - if let Err(err) = backend - .record_sent_contact_request(&seed_hash, &owner_id, contact_record) - .await - { - tracing::warn!( - %err, - "record_sent_contact_request failed; contact was sent but \ - local wallet-manager state not updated", - ); - } - - // Sending to someone retires an earlier decline of their request and an - // earlier withdrawal of ours: the user has deliberately re-engaged, so - // neither direction may stay filtered out of the list. - // Both markers are cleared unconditionally — a failure on one must not - // leave the other standing. - let declined = backend.dashpay_unmark_declined(&owner_id, &to_identity_id); - let withdrawn = backend.dashpay_unmark_withdrawn(&owner_id, &to_identity_id); - if let Err(err) = declined.and(withdrawn) { - tracing::debug!( - %err, - "Clearing the stale resolution markers failed; an earlier declined or \ - withdrawn request involving this person may stay hidden", - ); - } + finish_send( + &backend, + &seed_hash, + owner_id, + to_identity_id, + contact_record, + held, + ) + .await?; } Ok(BackendTaskSuccessResult::DashPayContactRequestSent( @@ -624,6 +630,80 @@ pub async fn send_contact_request_with_proof( )) } +/// Record a just-published request locally and re-engage its recipient. +async fn finish_send( + backend: &crate::wallet_backend::WalletBackend, + seed_hash: &crate::model::wallet::WalletSeedHash, + owner_id: Identifier, + to_identity_id: Identifier, + contact_record: UpstreamContactRequest, + held: Option<&HeldPeerLock>, +) -> Result<(), TaskError> { + // A cancel ignores the person and then records the withdrawal; a + // re-engagement landing in between would leave this fresh request + // withdrawn, so it waits for the person's lock. + let _peer_guard = lock_peer_unless_held(backend, owner_id, to_identity_id, held).await; + + if let Err(err) = backend + .record_sent_contact_request(seed_hash, &owner_id, contact_record) + .await + { + tracing::warn!( + %err, + "record_sent_contact_request failed; contact was sent but \ + local wallet-manager state not updated", + ); + } + + // Sending to someone retires an earlier decline of their request and an + // earlier withdrawal of ours: the user has deliberately re-engaged, so + // neither direction may stay filtered out of the list. + re_engage_after_send(&PlatformReEngage { + backend, + owner: owner_id, + peer: to_identity_id, + }) + .await +} + +/// `owner`'s request-action lock for `peer`, or `None` when `held` already +/// is that lock: it is not reentrant, so a caller holding it hands it down. +/// Callers take it only around local writes, never across a network call. +async fn lock_peer_unless_held( + backend: &crate::wallet_backend::WalletBackend, + owner: Identifier, + peer: Identifier, + held: Option<&HeldPeerLock>, +) -> Option> { + match held { + Some(held) if held.covers(&owner, &peer) => None, + _ => Some( + backend + .dashpay_lock_contact_request_action(&owner, &peer) + .await, + ), + } +} + +/// [`restore_withdrawn_request`] under `owner`'s lock for `peer`. A cancel +/// ignores the person and then records the withdrawal under that lock; a +/// restore landing in between would lift the ignore and leave the request +/// withdrawn while reporting it sent. +async fn restore_under_peer_lock( + backend: &crate::wallet_backend::WalletBackend, + owner: Identifier, + peer: Identifier, + held: Option<&HeldPeerLock>, +) -> Result { + let _peer_guard = lock_peer_unless_held(backend, owner, peer, held).await; + restore_withdrawn_request(&PlatformReEngage { + backend, + owner, + peer, + }) + .await +} + async fn resolve_username_to_identity(sdk: &Sdk, username: &str) -> Result { // The name's own record names its identity, which after a transfer is not // the document's owner. @@ -667,6 +747,13 @@ pub async fn accept_contact_request( // Verify the request was addressed to us before acting on it, and get the // sender's identity (the owner of the incoming request). let from_identity_id = sender_of_received_request(&doc, &identity.identity.id())?; + // Accept, decline and cancel lock on the person too: a cancel of the + // owner's request to them must not record a withdrawal while this accept + // establishes the contact. + let peer_lock = app_context + .wallet_backend()? + .dashpay_lock_contact_peer(&owner_id, &from_identity_id) + .await; // Check if we already sent a contact request to this identity let mut existing_query = contact_request_query(app_context)?; @@ -687,9 +774,23 @@ pub async fn accept_contact_request( let existing = Document::fetch_many(sdk, existing_query).await?; if !existing.is_empty() { - return Ok(BackendTaskSuccessResult::DashPayContactAlreadyEstablished { - request_id, - contact_id: from_identity_id, + // Our earlier request still stands on Platform. If it was withdrawn, + // accepting restores it, and with it the contact. + let backend = app_context.wallet_backend()?; + let restored = restore_under_peer_lock( + &backend, + identity.identity.id(), + from_identity_id, + Some(&peer_lock), + ) + .await?; + return Ok(if restored { + BackendTaskSuccessResult::DashPayContactRequestAccepted(request_id) + } else { + BackendTaskSuccessResult::DashPayContactAlreadyEstablished { + request_id, + contact_id: from_identity_id, + } }); } @@ -763,13 +864,17 @@ pub async fn accept_contact_request( } } - let result = send_contact_request( + // The reply is sent under the person's lock taken above, which the send + // would otherwise wait on forever. + let result = send_contact_request_inner( app_context, sdk, identity, signing_key, from_identity_id.to_string(Encoding::Base58), Some("Accepted contact".to_string()), + None, + Some(&peer_lock), ) .await; @@ -781,17 +886,103 @@ pub async fn accept_contact_request( } } +/// The local state that re-engages someone the owner withdrew a request +/// from, behind a trait so the decision can be driven in tests. +trait ReEngageOps { + /// # Errors + /// + /// The withdrawal record could not be read. + fn is_withdrawn(&self) -> Result; + /// # Errors + /// + /// The decline record could not be read. + fn is_declined(&self) -> Result; + /// Whether platform-wallet still ignores the person. A decline or + /// withdrawal ignores them before writing its marker, so an ignore can + /// outlive a marker write that failed (and a rollback that failed too). + fn is_ignored(&self) -> impl Future + Send; + /// Lift the ignore and clear the withdrawal and decline markers. + fn re_engage(&self) -> impl Future> + Send; +} + +/// Restore a request the owner sent earlier, which still stands on Platform, +/// when this device still hides the person; returns whether it did. Nothing +/// is published. +/// +/// The person is hidden after a withdrawal, or after a decline that a send +/// could not clear (see [`re_engage_after_send`]), so sending again retries. +/// An ignore left in platform-wallet without either marker is lifted the same +/// way; otherwise their reply would never establish the contact. +async fn restore_withdrawn_request(ops: &O) -> Result { + if !(ops.is_withdrawn()? || ops.is_declined()? || ops.is_ignored().await) { + return Ok(false); + } + ops.re_engage().await?; + Ok(true) +} + +/// Re-engage the recipient of a request that was just published. +/// +/// # Errors +/// +/// [`TaskError::DashPayContactRequestSentNotUpdated`] when this device could +/// not be updated. The ignore is lifted before the markers are cleared, so a +/// failure leaves a marker standing and sending again finishes the update +/// through [`restore_withdrawn_request`]. +async fn re_engage_after_send(ops: &O) -> Result<(), TaskError> { + ops.re_engage() + .await + .map_err(|source| TaskError::DashPayContactRequestSentNotUpdated { + source: Box::new(source), + }) +} + +struct PlatformReEngage<'a> { + backend: &'a crate::wallet_backend::WalletBackend, + owner: Identifier, + peer: Identifier, +} + +impl ReEngageOps for PlatformReEngage<'_> { + fn is_withdrawn(&self) -> Result { + self.backend + .dashpay_withdrawal_recorded(&self.owner, &self.peer) + } + + fn is_declined(&self) -> Result { + self.backend + .dashpay_decline_recorded(&self.owner, &self.peer) + } + + async fn is_ignored(&self) -> bool { + self.backend + .dashpay_sender_ignored(&self.owner, &self.peer) + .await + } + + async fn re_engage(&self) -> Result<(), TaskError> { + // The ignore first: the withdrawal keeps the person out of the lists + // until it is lifted, so a failure here leaves a retry possible. + self.backend + .dashpay_unignore_contact_sender(&self.owner, &self.peer) + .await?; + self.backend + .dashpay_unmark_declined(&self.owner, &self.peer)?; + self.backend + .dashpay_unmark_withdrawn(&self.owner, &self.peer) + } +} + pub async fn reject_contact_request( app_context: &Arc, sdk: &Sdk, identity: QualifiedIdentity, request_id: Identifier, - unreadable: UnreadableContactInfoPolicy, ) -> Result { - // According to DashPay DIP, rejecting doesn't delete the request (they're immutable) - // Instead, we should update our contactInfo document to mark this contact as hidden - - // First, fetch the contact request to get the sender's identity + // A contactRequest document is immutable, and a contactInfo about someone + // who is not a contact would publish whom this identity turned down, so + // declining is local only: platform-wallet ignores the sender and the DET + // marker retires the request. let query_with_id = DocumentQuery::with_document_id(contact_request_query(app_context)?, &request_id); @@ -799,8 +990,6 @@ pub async fn reject_contact_request( .await? .ok_or(TaskError::DocumentNotFound)?; - // Captured before `identity` is moved into `create_or_update_contact_info`; - // the decline marker is scoped to this acting identity. let owner_id = identity.identity.id(); // Verify the request was addressed to us before declining it. @@ -808,67 +997,98 @@ pub async fn reject_contact_request( let ops = PlatformRejectOps { app_context, - sdk, - identity, owner_id, from_identity_id, request_id, }; - reject_flow(&ops, unreadable).await + reject_flow(&ops).await } +/// The local writes a decline performs, behind a trait so their order can be +/// driven in tests. trait RejectOps { fn lock_action( &self, ) -> impl Future, TaskError>> + Send; - fn lock_contact_info(&self) -> impl Future> + Send; - fn phase(&self) -> Result, TaskError>; - fn set_phase(&self, phase: ContactRequestActionPhase) -> Result<(), TaskError>; + /// Forget the progress record an older version kept for this action. fn clear_phase(&self) -> Result<(), TaskError>; - fn contact_is_hidden( - &self, - unreadable: UnreadableContactInfoPolicy, - ) -> impl Future> + Send; - fn update_contact_info( - &self, - update: ContactInfoUpdate, - write_guard: &tokio::sync::OwnedMutexGuard<()>, - ) -> impl Future> + Send; + /// Ignore the sender in platform-wallet (local only), unless the contact + /// is already established there; returns whether the ignore stands. + fn ignore_sender(&self) -> impl Future> + Send; + /// Undo [`Self::ignore_sender`] when the decline cannot be recorded. + fn unignore_sender(&self) -> impl Future> + Send; fn mark_declined(&self) -> Result<(), TaskError>; fn request_id(&self) -> Identifier; + fn sender_id(&self) -> Identifier; } -async fn reject_flow( - ops: &O, - unreadable: UnreadableContactInfoPolicy, -) -> Result { - let _action_guard = ops.lock_action().await?; - let contact_info_guard = ops.lock_contact_info().await; - let phase = match ops.phase()? { - Some(phase) => phase, - None => { - ops.set_phase(ContactRequestActionPhase::HideIntent)?; - ContactRequestActionPhase::HideIntent +/// A decline or withdrawal changes only this device, so a failed local +/// record must not be reported as one whose change reached the network. +fn recorded_on_this_device(error: TaskError) -> TaskError { + match error { + TaskError::DashpaySidecarStorage { source } => { + TaskError::DashPayRequestDecisionNotRecorded { source } } + error => error, + } +} + +/// Record a decline or withdrawal whose ignore already stands; if the record +/// cannot be written, lift the ignore again so no half-done decision is left. +/// +/// The ignore and the marker live in different stores (platform-wallet's and +/// DET's), so they cannot change together. A rollback that fails too is only +/// logged: the user is told the decision was not recorded, and the next send +/// or accept lifts the leftover ignore (see [`restore_withdrawn_request`]). +async fn record_or_unignore( + mark: Result<(), TaskError>, + unignore: impl FnOnce() -> U, +) -> Result<(), TaskError> +where + U: Future>, +{ + let Err(error) = mark else { + return Ok(()); }; + if let Err(rollback) = unignore().await { + tracing::warn!( + ?rollback, + "could not lift the ignore of a decision that was not recorded" + ); + } + Err(recorded_on_this_device(error)) +} - if phase == ContactRequestActionPhase::HideIntent { - if !ops.contact_is_hidden(unreadable).await? { - ops.update_contact_info(hidden_contact_update(true, unreadable), &contact_info_guard) - .await?; - } - ops.set_phase(ContactRequestActionPhase::MarkerPending)?; +/// The progress record an older version kept is read by nothing once the +/// decision is recorded, so failing to forget it leaves an inert entry and +/// does not fail the action. +fn forget_phase(cleared: Result<(), TaskError>) { + if let Err(error) = cleared { + tracing::warn!( + ?error, + "could not forget an old contact request progress record" + ); } +} - let result = complete_rejection(ops.request_id(), || ops.mark_declined())?; - ops.clear_phase()?; +async fn reject_flow(ops: &O) -> Result { + let _action_guard = ops.lock_action().await?; + let result = if ops.ignore_sender().await? { + let recorded = record_or_unignore(ops.mark_declined(), || ops.unignore_sender()).await; + complete_rejection(ops.request_id(), || recorded)? + } else { + // The contact was established before the ignore took effect. + BackendTaskSuccessResult::DashPayContactAlreadyEstablished { + request_id: ops.request_id(), + contact_id: ops.sender_id(), + } + }; + forget_phase(ops.clear_phase()); Ok(result) } struct PlatformRejectOps<'a> { app_context: &'a Arc, - sdk: &'a Sdk, - identity: QualifiedIdentity, owner_id: Identifier, from_identity_id: Identifier, request_id: Identifier, @@ -879,77 +1099,32 @@ impl RejectOps for PlatformRejectOps<'_> { Ok(self .app_context .wallet_backend()? - .dashpay_lock_contact_request_action(&self.owner_id, &self.request_id) + .dashpay_lock_contact_request_action(&self.owner_id, &self.from_identity_id) .await) } - async fn lock_contact_info(&self) -> tokio::sync::OwnedMutexGuard<()> { - self.app_context - .contact_info_writes - .acquire(self.owner_id) - .await - } - - fn phase(&self) -> Result, TaskError> { + fn clear_phase(&self) -> Result<(), TaskError> { self.app_context .wallet_backend()? - .dashpay_contact_request_action_phase( + .dashpay_clear_contact_request_action( &self.owner_id, &self.request_id, ContactRequestActionKind::Decline, ) } - fn set_phase(&self, phase: ContactRequestActionPhase) -> Result<(), TaskError> { + async fn ignore_sender(&self) -> Result { self.app_context .wallet_backend()? - .dashpay_set_contact_request_action_phase( - &self.owner_id, - &self.request_id, - ContactRequestActionKind::Decline, - phase, - ) + .dashpay_ignore_unless_established(&self.owner_id, &self.from_identity_id) + .await } - fn clear_phase(&self) -> Result<(), TaskError> { + async fn unignore_sender(&self) -> Result<(), TaskError> { self.app_context .wallet_backend()? - .dashpay_clear_contact_request_action( - &self.owner_id, - &self.request_id, - ContactRequestActionKind::Decline, - ) - } - - async fn contact_is_hidden( - &self, - unreadable: UnreadableContactInfoPolicy, - ) -> Result { - super::contact_info::contact_info_is_hidden( - self.app_context, - self.sdk, - &self.identity, - self.from_identity_id, - unreadable, - ) - .await - } - - async fn update_contact_info( - &self, - update: ContactInfoUpdate, - write_guard: &tokio::sync::OwnedMutexGuard<()>, - ) -> Result<(), TaskError> { - super::contact_info::create_or_update_contact_info_locked( - self.app_context, - self.sdk, - self.identity.clone(), - self.from_identity_id, - update, - write_guard, - ) - .await - .map(|_| ()) + .dashpay_unignore_contact_sender(&self.owner_id, &self.from_identity_id) + .await } fn mark_declined(&self) -> Result<(), TaskError> { @@ -961,17 +1136,10 @@ impl RejectOps for PlatformRejectOps<'_> { fn request_id(&self) -> Identifier { self.request_id } -} -/// The visibility flip that declining and withdrawing both write. Every other -/// stored detail is preserved: these actions hide a contact, they do not edit it. -fn hidden_contact_update( - hidden: bool, - unreadable: UnreadableContactInfoPolicy, -) -> ContactInfoUpdate { - let mut update = ContactInfoUpdate::visibility(hidden); - update.unreadable = unreadable; - update + fn sender_id(&self) -> Identifier { + self.from_identity_id + } } /// Return rejection success only after storing the local marker that retires the row. @@ -995,41 +1163,33 @@ fn complete_rejection( /// What a cancellation attempt resolved to. #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum CancelOutcome { - /// The request was pending throughout; it is now withdrawn. + /// The request was pending; it is now withdrawn. Withdrawn, /// The recipient had answered — there was nothing left to cancel. AlreadyEstablished, } -/// The Platform reads and writes a cancellation performs. -/// -/// Behind a trait so [`cancel_flow`]'s ordering — and the race window between -/// the reciprocal check and the hide broadcast — can be driven deterministically -/// in tests, which is impossible against a live Platform. +/// The reads and local writes a cancellation performs, behind a trait so +/// their order can be driven in tests. trait CancelOps { fn lock_action( &self, ) -> impl Future, TaskError>> + Send; - fn lock_contact_info(&self) -> impl Future> + Send; - fn phase(&self) -> Result, TaskError>; - fn set_phase(&self, phase: ContactRequestActionPhase) -> Result<(), TaskError>; + /// Forget the progress record an older version kept for this action. fn clear_phase(&self) -> Result<(), TaskError>; /// `true` when the recipient has already sent a contact request back, which /// makes the pending request an established contact instead. fn reciprocal_request_exists(&self) -> impl Future> + Send; - fn contact_is_hidden( - &self, - unreadable: UnreadableContactInfoPolicy, - ) -> impl Future> + Send; + /// Ignore the recipient in platform-wallet (local only), so a reply to + /// the withdrawn request cannot establish the contact on its own; returns + /// whether the ignore stands, which it does not when the reply was taken + /// in first and the contact is already established. + fn ignore_recipient(&self) -> impl Future> + Send; - /// Broadcast the complete visibility update for the recipient. - fn update_contact_info( - &self, - update: ContactInfoUpdate, - write_guard: &tokio::sync::OwnedMutexGuard<()>, - ) -> impl Future> + Send; + /// Undo [`Self::ignore_recipient`] when the withdrawal cannot be recorded. + fn unignore_recipient(&self) -> impl Future> + Send; /// Record the withdrawal in the DET sidecar so the request stops being /// listed as pending. @@ -1042,85 +1202,27 @@ trait CancelOps { fn mark_withdrawn(&self) -> Result<(), TaskError>; } -/// Check, hide, then re-check and undo the hide if the recipient answered inside -/// the window. -/// -/// Platform has no conditional write, so the reciprocal check and the hide -/// broadcast cannot be one atomic step: they are two round-trips against two -/// different documents. The check is therefore the last read before the write, -/// and a second read straight after the write closes the gap retroactively — a -/// reciprocal request that lands mid-flight is detected and the hide is -/// reverted, leaving the freshly-established contact visible. That is the same -/// end state the caller would have reached had the reciprocal arrived a moment -/// earlier. -/// -/// Residual risk: a reciprocal request landing *after* the second read still -/// leaves the contact hidden. It is not detectable from here at any window -/// width; recovery is the Contacts tab's hidden-contacts section, which can -/// unhide the contact. -async fn cancel_flow( - ops: &O, - unreadable: UnreadableContactInfoPolicy, -) -> Result { +/// Withdraw the request unless the recipient has answered it. Local only: +/// nothing is published. +async fn cancel_flow(ops: &O) -> Result { let _action_guard = ops.lock_action().await?; - let contact_info_guard = ops.lock_contact_info().await; - let mut phase = match ops.phase()? { - Some(phase) => phase, - None => { - if ops.reciprocal_request_exists().await? { - return Ok(CancelOutcome::AlreadyEstablished); - } - ops.set_phase(ContactRequestActionPhase::HideIntent)?; - ContactRequestActionPhase::HideIntent - } + let outcome = if ops.reciprocal_request_exists().await? { + CancelOutcome::AlreadyEstablished + } else if ops.ignore_recipient().await? { + record_or_unignore(ops.mark_withdrawn(), || ops.unignore_recipient()).await?; + CancelOutcome::Withdrawn + } else { + // The reply was taken in after the query, before the ignore. + CancelOutcome::AlreadyEstablished }; - - if phase == ContactRequestActionPhase::HideIntent { - if !ops.contact_is_hidden(unreadable).await? { - ops.update_contact_info(hidden_contact_update(true, unreadable), &contact_info_guard) - .await?; - } - ops.set_phase(ContactRequestActionPhase::HideCommitted)?; - phase = ContactRequestActionPhase::HideCommitted; - } - - if phase == ContactRequestActionPhase::HideCommitted { - if ops.reciprocal_request_exists().await? { - ops.set_phase(ContactRequestActionPhase::CorrectiveUnhideIntent)?; - phase = ContactRequestActionPhase::CorrectiveUnhideIntent; - } else { - ops.set_phase(ContactRequestActionPhase::MarkerPending)?; - phase = ContactRequestActionPhase::MarkerPending; - } - } - - if phase == ContactRequestActionPhase::CorrectiveUnhideIntent { - if ops.contact_is_hidden(unreadable).await? { - ops.update_contact_info( - hidden_contact_update(false, unreadable), - &contact_info_guard, - ) - .await?; - } - ops.set_phase(ContactRequestActionPhase::CorrectiveUnhideComplete)?; - phase = ContactRequestActionPhase::CorrectiveUnhideComplete; - } - - if phase == ContactRequestActionPhase::CorrectiveUnhideComplete { - ops.clear_phase()?; - return Ok(CancelOutcome::AlreadyEstablished); - } - - ops.mark_withdrawn()?; - ops.clear_phase()?; - Ok(CancelOutcome::Withdrawn) + forget_phase(ops.clear_phase()); + Ok(outcome) } /// [`CancelOps`] against the live Platform, for one sender/recipient pair. struct PlatformCancelOps<'a> { app_context: &'a Arc, sdk: &'a Sdk, - identity: QualifiedIdentity, /// The cancelling identity — the sender of the request being withdrawn. owner_id: Identifier, /// The recipient of the request being withdrawn. @@ -1133,38 +1235,10 @@ impl CancelOps for PlatformCancelOps<'_> { Ok(self .app_context .wallet_backend()? - .dashpay_lock_contact_request_action(&self.owner_id, &self.request_id) + .dashpay_lock_contact_request_action(&self.owner_id, &self.to_identity_id) .await) } - async fn lock_contact_info(&self) -> tokio::sync::OwnedMutexGuard<()> { - self.app_context - .contact_info_writes - .acquire(self.owner_id) - .await - } - - fn phase(&self) -> Result, TaskError> { - self.app_context - .wallet_backend()? - .dashpay_contact_request_action_phase( - &self.owner_id, - &self.request_id, - ContactRequestActionKind::Cancel, - ) - } - - fn set_phase(&self, phase: ContactRequestActionPhase) -> Result<(), TaskError> { - self.app_context - .wallet_backend()? - .dashpay_set_contact_request_action_phase( - &self.owner_id, - &self.request_id, - ContactRequestActionKind::Cancel, - phase, - ) - } - fn clear_phase(&self) -> Result<(), TaskError> { self.app_context .wallet_backend()? @@ -1193,41 +1267,24 @@ impl CancelOps for PlatformCancelOps<'_> { Ok(!Document::fetch_many(self.sdk, query).await?.is_empty()) } - async fn update_contact_info( - &self, - update: ContactInfoUpdate, - write_guard: &tokio::sync::OwnedMutexGuard<()>, - ) -> Result<(), TaskError> { - super::contact_info::create_or_update_contact_info_locked( - self.app_context, - self.sdk, - self.identity.clone(), - self.to_identity_id, - update, - write_guard, - ) - .await - .map(|_| ()) + fn mark_withdrawn(&self) -> Result<(), TaskError> { + self.app_context + .wallet_backend()? + .dashpay_mark_withdrawn(&self.owner_id, &self.to_identity_id) } - async fn contact_is_hidden( - &self, - unreadable: UnreadableContactInfoPolicy, - ) -> Result { - super::contact_info::contact_info_is_hidden( - self.app_context, - self.sdk, - &self.identity, - self.to_identity_id, - unreadable, - ) - .await + async fn ignore_recipient(&self) -> Result { + self.app_context + .wallet_backend()? + .dashpay_ignore_unless_established(&self.owner_id, &self.to_identity_id) + .await } - fn mark_withdrawn(&self) -> Result<(), TaskError> { + async fn unignore_recipient(&self) -> Result<(), TaskError> { self.app_context .wallet_backend()? - .dashpay_mark_withdrawn(&self.owner_id, &self.to_identity_id) + .dashpay_unignore_contact_sender(&self.owner_id, &self.to_identity_id) + .await } } @@ -1235,21 +1292,18 @@ impl CancelOps for PlatformCancelOps<'_> { /// /// DashPay `contactRequest` documents are immutable and cannot be deleted /// (`documentsMutable: false`, `canBeDeleted: false` in the DashPay contract), -/// so the request cannot be un-sent from Platform. Cancelling therefore does -/// what `reject_contact_request` does for the incoming direction: it broadcasts -/// a `contactInfo` document marking the recipient hidden — a real, persisted -/// state transition — and records the withdrawal in the DET sidecar so the -/// request stops being listed as pending. +/// so the request cannot be un-sent from Platform. Cancelling records the +/// withdrawal on this device only, so the request stops being listed as +/// pending; nothing is published. /// /// State is re-verified against Platform before acting: the request must still /// exist, must have been sent by `identity`, and must not have been answered in -/// the meantime. See [`cancel_flow`] for how the answer race is handled. +/// the meantime. pub async fn cancel_contact_request( app_context: &Arc, sdk: &Sdk, identity: QualifiedIdentity, request_id: Identifier, - unreadable: UnreadableContactInfoPolicy, ) -> Result { let owner_id = identity.identity.id(); @@ -1268,13 +1322,12 @@ pub async fn cancel_contact_request( let ops = PlatformCancelOps { app_context, sdk, - identity, owner_id, to_identity_id, request_id, }; - match cancel_flow(&ops, unreadable).await? { + match cancel_flow(&ops).await? { CancelOutcome::Withdrawn => Ok(BackendTaskSuccessResult::DashPayContactRequestCancelled( request_id, )), @@ -1292,7 +1345,6 @@ pub async fn cancel_contact_request( #[cfg(test)] mod tests { use super::*; - use crate::model::dashpay::ContactInfoField; use dash_sdk::dpp::document::{Document as DppDocument, DocumentV0}; fn id(byte: u8) -> Identifier { @@ -1457,52 +1509,460 @@ mod tests { )); } + /// After the owner withdraws their request to + /// id(3), id(3)'s later request is listed for the owner to answer; the + /// pair is not taken for a contact and both rows dropped. #[test] - fn retain_unresolved_drops_declined_and_withdrawn_rows() { - // Incoming from id(1) — declined. Incoming from id(2) — still pending. + fn a_reply_to_a_withdrawn_request_is_listed_to_answer() { + let owner = id(9); let mut incoming = vec![ - (id(10), request_doc(id(1), Some(id(9)))), - (id(11), request_doc(id(2), Some(id(9)))), + (id(10), request_doc(id(3), Some(owner))), + (id(11), request_doc(id(4), Some(owner))), ]; - // Outgoing to id(3) — withdrawn. Outgoing to id(4) — still pending. let mut outgoing = vec![ - (id(12), request_doc(id(9), Some(id(3)))), - (id(13), request_doc(id(9), Some(id(4)))), + (id(12), request_doc(owner, Some(id(3)))), + (id(13), request_doc(owner, Some(id(4)))), ]; - retain_unresolved( + pending_requests( &mut incoming, &mut outgoing, - |sender| *sender == id(1), - |recipient| *recipient == id(3), + |_| false, + |peer| *peer == id(3), ); - assert_eq!(incoming.len(), 1, "the declined request must not be listed"); - assert_eq!(incoming[0].0, id(11)); assert_eq!( - outgoing.len(), - 1, - "the withdrawn request must not be listed" + incoming.iter().map(|(id, _)| *id).collect::>(), + vec![id(10)], + "id(3)'s reply waits for an answer; id(4) is a contact" ); - assert_eq!(outgoing[0].0, id(13)); + assert!(outgoing.is_empty(), "the withdrawn request is not listed"); } + /// A declined sender is not a contact until the owner re-engages, even + /// when the owner's own request to them is still on Platform: that sent + /// request stays listed, so sending it again can finish the update. #[test] - fn retain_unresolved_keeps_rows_with_unreadable_recipients() { - let mut incoming = Vec::new(); - let mut outgoing = vec![(id(12), request_doc(id(9), None))]; + fn a_declined_sender_with_a_sent_request_is_not_a_contact() { + let owner = id(9); + let mut incoming = vec![(id(10), request_doc(id(3), Some(owner)))]; + let mut outgoing = vec![(id(12), request_doc(owner, Some(id(3))))]; - retain_unresolved(&mut incoming, &mut outgoing, |_| true, |_| true); + pending_requests( + &mut incoming, + &mut outgoing, + |peer| *peer == id(3), + |_| false, + ); + assert!(incoming.is_empty(), "the declined request stays declined"); assert_eq!( - outgoing.len(), - 1, - "a request we cannot attribute must stay visible rather than be silently hidden" + outgoing.iter().map(|(id, _)| *id).collect::>(), + vec![id(12)] ); } - #[test] - fn a_withdrawn_outgoing_request_does_not_hide_a_later_incoming_one() { + /// A request record for `finish_send`; this test wallet has no such + /// identity, so recording it only logs. + fn sent_record(owner: Identifier, peer: Identifier) -> UpstreamContactRequest { + UpstreamContactRequest::new( + owner, + peer, + 0, + 0, + 0, + bip39::rand::random::<[u8; 32]>().to_vec(), + 0, + 0, + ) + } + + /// A cancel holding the person's lock is not undone halfway: the send + /// waits for it, then retires the withdrawal it recorded, so the fresh + /// request stays listed. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_send_finishing_during_a_cancel_waits_and_then_retires_the_withdrawal() { + let dir = tempfile::tempdir().expect("temp dir"); + let app_context = crate::context::test_support::wired_test_app_context(dir.path()).await; + let backend = app_context.wallet_backend().expect("backend"); + let (owner, peer) = (id(1), id(2)); + let cancel_guard = backend + .dashpay_lock_contact_request_action(&owner, &peer) + .await; + + // Driven on this task, not spawned, so it has run before the cancel + // records its withdrawal whether or not it waits. + let seed_hash = bip39::rand::random::<[u8; 32]>(); + let mut send = Box::pin(finish_send( + &backend, + &seed_hash, + owner, + peer, + sent_record(owner, peer), + None, + )); + assert_waits(&mut send).await; + + backend + .dashpay_mark_withdrawn(&owner, &peer) + .expect("withdraw"); + drop(cancel_guard); + send.await.expect("send finished"); + + assert!(!backend.dashpay_disengaged_from(&owner, &peer)); + } + + /// Drive `fut` long enough for it to finish if nothing blocks it, and + /// assert it did not: it waits on a lock held by the test. + async fn assert_waits(fut: &mut F) { + assert!( + tokio::time::timeout(std::time::Duration::from_millis(300), fut) + .await + .is_err(), + "it must wait for the cancel" + ); + } + + /// Sending again to someone whose request still stands restores it, and + /// waits for a cancel holding the person's lock: restoring between the + /// cancel's ignore and its withdrawal record would report the request + /// sent while leaving it withdrawn. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_restore_during_a_cancel_waits_and_then_retires_the_withdrawal() { + let dir = tempfile::tempdir().expect("temp dir"); + let app_context = crate::context::test_support::wired_test_app_context(dir.path()).await; + let backend = app_context.wallet_backend().expect("backend"); + let (owner, peer) = (id(1), id(2)); + let cancel_guard = backend + .dashpay_lock_contact_request_action(&owner, &peer) + .await; + + let mut restore = Box::pin(restore_under_peer_lock(&backend, owner, peer, None)); + assert_waits(&mut restore).await; + + backend + .dashpay_mark_withdrawn(&owner, &peer) + .expect("withdraw"); + drop(cancel_guard); + + assert!(restore.await.expect("restore finished"), "restored"); + assert!(!backend.dashpay_disengaged_from(&owner, &peer)); + } + + /// An accept restores its earlier request under the person's lock it + /// already holds; the restore must not wait on that lock. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn an_accepts_restore_under_its_own_peer_lock_finishes() { + let dir = tempfile::tempdir().expect("temp dir"); + let app_context = crate::context::test_support::wired_test_app_context(dir.path()).await; + let backend = app_context.wallet_backend().expect("backend"); + let (owner, peer) = (id(1), id(2)); + backend + .dashpay_mark_withdrawn(&owner, &peer) + .expect("withdraw"); + let peer_lock = backend.dashpay_lock_contact_peer(&owner, &peer).await; + + let restored = tokio::time::timeout( + std::time::Duration::from_secs(5), + restore_under_peer_lock(&backend, owner, peer, Some(&peer_lock)), + ) + .await + .expect("the restore must not wait on its caller's lock"); + + assert!(restored.expect("restore finished"), "restored"); + assert!(!backend.dashpay_disengaged_from(&owner, &peer)); + } + + /// An accept sends its reply under the person's lock it already holds and + /// hands that lock down; `finish_send` is the only place the send path + /// takes the lock, so the reply finishes instead of waiting on itself. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn an_accepts_reply_under_its_own_peer_lock_finishes() { + let dir = tempfile::tempdir().expect("temp dir"); + let app_context = crate::context::test_support::wired_test_app_context(dir.path()).await; + let backend = app_context.wallet_backend().expect("backend"); + let (owner, peer) = (id(1), id(2)); + backend + .dashpay_mark_withdrawn(&owner, &peer) + .expect("withdraw"); + let peer_lock = backend.dashpay_lock_contact_peer(&owner, &peer).await; + + let finished = tokio::time::timeout( + std::time::Duration::from_secs(5), + finish_send( + &backend, + &bip39::rand::random::<[u8; 32]>(), + owner, + peer, + sent_record(owner, peer), + Some(&peer_lock), + ), + ) + .await + .expect("the send must not wait on its caller's lock"); + + finished.expect("send finished"); + assert!(!backend.dashpay_disengaged_from(&owner, &peer)); + } + + /// A lock held for someone else does not stand in for the recipient's: + /// the send still waits for a cancel holding the recipient's lock. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_lock_held_for_another_person_does_not_skip_the_wait() { + let dir = tempfile::tempdir().expect("temp dir"); + let app_context = crate::context::test_support::wired_test_app_context(dir.path()).await; + let backend = app_context.wallet_backend().expect("backend"); + let (owner, peer, other) = (id(1), id(2), id(3)); + let other_lock = backend.dashpay_lock_contact_peer(&owner, &other).await; + let cancel_guard = backend + .dashpay_lock_contact_request_action(&owner, &peer) + .await; + + let waited = tokio::time::timeout( + std::time::Duration::from_millis(300), + finish_send( + &backend, + &bip39::rand::random::<[u8; 32]>(), + owner, + peer, + sent_record(owner, peer), + Some(&other_lock), + ), + ) + .await; + + assert!(waited.is_err(), "the send must wait for the cancel"); + drop(cancel_guard); + } + + /// Every send re-engages, a first one included: a declined or withdrawn + /// person is a contact again once the owner sends them a request. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_send_retires_a_decline_and_a_withdrawal() { + let dir = tempfile::tempdir().expect("temp dir"); + let app_context = crate::context::test_support::wired_test_app_context(dir.path()).await; + let backend = app_context.wallet_backend().expect("backend"); + let (owner, peer) = (id(1), id(2)); + backend + .dashpay_mark_declined(&owner, &peer) + .expect("decline"); + backend + .dashpay_mark_withdrawn(&owner, &peer) + .expect("withdraw"); + assert!(backend.dashpay_disengaged_from(&owner, &peer)); + + re_engage_after_send(&PlatformReEngage { + backend: &backend, + owner, + peer, + }) + .await + .expect("re-engaged"); + + assert!(!backend.dashpay_disengaged_from(&owner, &peer)); + } + + /// Actions on requests with the same person run one at a time, whichever + /// request they act on: a cancel must not record a withdrawal while an + /// accept of that person's request establishes the contact. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn request_actions_with_one_person_run_one_at_a_time() { + let dir = tempfile::tempdir().expect("temp dir"); + let app_context = crate::context::test_support::wired_test_app_context(dir.path()).await; + let sdk = app_context.sdk(); + let (owner, peer) = (id(1), id(2)); + let cancel = PlatformCancelOps { + app_context: &app_context, + sdk: &sdk, + owner_id: owner, + to_identity_id: peer, + request_id: id(10), + }; + let decline = PlatformRejectOps { + app_context: &app_context, + owner_id: owner, + from_identity_id: peer, + request_id: id(11), + }; + + let held = cancel.lock_action().await.expect("lock"); + let mut waiting = Box::pin(decline.lock_action()); + assert!(futures::poll!(&mut waiting).is_pending()); + drop(held); + drop(waiting.await.expect("lock")); + } + + #[derive(Default)] + struct ScriptedReEngage { + withdrawn: bool, + declined: bool, + /// platform-wallet still ignores the person, with no DET marker. + ignored: bool, + unreadable: bool, + re_engage_fails: bool, + re_engaged: std::sync::Mutex, + } + + impl ReEngageOps for ScriptedReEngage { + fn is_withdrawn(&self) -> Result { + if self.unreadable { + return Err(TaskError::DashPayLocalStateRead { + source: crate::wallet_backend::KvAdapterError::Truncated, + }); + } + Ok(self.withdrawn) + } + + fn is_declined(&self) -> Result { + Ok(self.declined) + } + + async fn is_ignored(&self) -> bool { + self.ignored + } + + async fn re_engage(&self) -> Result<(), TaskError> { + if self.re_engage_fails { + return Err(TaskError::DashpaySidecarStorage { + source: crate::wallet_backend::KvAdapterError::Truncated, + }); + } + *self.re_engaged.lock().unwrap() = true; + Ok(()) + } + } + + /// A send that reached Platform but could not update this device is + /// reported, not shown as complete: the person could stay hidden here. + #[tokio::test] + async fn a_failed_re_engagement_after_a_send_is_reported() { + let ops = ScriptedReEngage { + re_engage_fails: true, + ..Default::default() + }; + + assert!(matches!( + re_engage_after_send(&ops).await, + Err(TaskError::DashPayContactRequestSentNotUpdated { .. }) + )); + assert!( + re_engage_after_send(&ScriptedReEngage::default()) + .await + .is_ok() + ); + } + + /// Sending again retries a re-engagement a failed send left unfinished: + /// the decline it did not clear is cleared now, with nothing published. + #[tokio::test] + async fn a_decline_left_by_a_failed_send_is_retried_on_the_next_send() { + let ops = ScriptedReEngage { + declined: true, + ..Default::default() + }; + + assert!(restore_withdrawn_request(&ops).await.expect("restored")); + assert!(*ops.re_engaged.lock().unwrap()); + } + + /// A decline or withdrawal whose marker write failed after the ignore + /// stood (and whose rollback failed too) leaves only platform-wallet's + /// ignore. Sending or accepting again still lifts it, rather than + /// reporting the request as already sent while the person stays ignored. + #[tokio::test] + async fn an_ignore_left_without_a_marker_is_lifted_on_re_engagement() { + let ops = ScriptedReEngage { + ignored: true, + ..Default::default() + }; + + assert!(restore_withdrawn_request(&ops).await.expect("restored")); + assert!(*ops.re_engaged.lock().unwrap()); + } + + /// Accepting (or sending again) where the owner's + /// withdrawn request still stands restores it without a new publish. + #[tokio::test] + async fn an_existing_withdrawn_request_is_restored() { + let ops = ScriptedReEngage { + withdrawn: true, + ..Default::default() + }; + assert!(restore_withdrawn_request(&ops).await.expect("restored")); + assert!(*ops.re_engaged.lock().unwrap()); + + let pending = ScriptedReEngage::default(); + assert!( + !restore_withdrawn_request(&pending) + .await + .expect("nothing to restore") + ); + assert!(!*pending.re_engaged.lock().unwrap()); + } + + /// An unreadable withdrawal record fails the + /// accept or send instead of reporting success with the withdrawal still + /// in force. + #[tokio::test] + async fn an_unreadable_withdrawal_record_fails_the_restore() { + let ops = ScriptedReEngage { + unreadable: true, + ..Default::default() + }; + + assert!(matches!( + restore_withdrawn_request(&ops).await, + Err(TaskError::DashPayLocalStateRead { .. }) + )); + assert!(!*ops.re_engaged.lock().unwrap()); + } + + #[test] + fn retain_unresolved_drops_declined_and_withdrawn_rows() { + // Incoming from id(1) — declined. Incoming from id(2) — still pending. + let mut incoming = vec![ + (id(10), request_doc(id(1), Some(id(9)))), + (id(11), request_doc(id(2), Some(id(9)))), + ]; + // Outgoing to id(3) — withdrawn. Outgoing to id(4) — still pending. + let mut outgoing = vec![ + (id(12), request_doc(id(9), Some(id(3)))), + (id(13), request_doc(id(9), Some(id(4)))), + ]; + + retain_unresolved( + &mut incoming, + &mut outgoing, + |sender| *sender == id(1), + |recipient| *recipient == id(3), + ); + + assert_eq!(incoming.len(), 1, "the declined request must not be listed"); + assert_eq!(incoming[0].0, id(11)); + assert_eq!( + outgoing.len(), + 1, + "the withdrawn request must not be listed" + ); + assert_eq!(outgoing[0].0, id(13)); + } + + #[test] + fn retain_unresolved_keeps_rows_with_unreadable_recipients() { + let mut incoming = Vec::new(); + let mut outgoing = vec![(id(12), request_doc(id(9), None))]; + + retain_unresolved(&mut incoming, &mut outgoing, |_| true, |_| true); + + assert_eq!( + outgoing.len(), + 1, + "a request we cannot attribute must stay visible rather than be silently hidden" + ); + } + + #[test] + fn a_withdrawn_outgoing_request_does_not_hide_a_later_incoming_one() { // We (id 9) withdrew a request to id(2), so id(2) carries a withdrawal // marker. Later id(2) sends us a genuine request: it is new, unresolved // business and must be listed. @@ -1545,70 +2005,24 @@ mod tests { } // ----------------------------------------------------------------- - // Cancellation flow — the reciprocal check and the hide broadcast are - // separate Platform round-trips, so the window between them is where a - // reciprocal request can slip in and get a fresh contact hidden. + // Decline and withdraw — both are local only: no contact details are + // written for someone who is not a contact. // ----------------------------------------------------------------- - use std::collections::VecDeque; use std::sync::Mutex; - /// Scriptable [`CancelOps`]. `reciprocal` is consumed one answer per probe, - /// which is how a reciprocal request is injected *inside* the window: - /// `[false, true]` means "pending when we checked, established by the time - /// the hide landed". #[derive(Default)] struct ScriptedOps { action_lock: Arc>, - contact_info_lock: Arc>, - reciprocal: Mutex>>, - /// Every contact-info update, in call order. - contact_updates: Mutex>, - contact_hidden: Mutex, - phase: Mutex>, + reciprocal: bool, withdrawn: Mutex, - /// When set, the first hide broadcast fails. - hide_fails: bool, - /// When set, recording the withdrawal in the sidecar fails. - withdraw_failures: Mutex, - } - - impl ScriptedOps { - fn with_reciprocal(answers: [bool; 2]) -> Self { - Self { - reciprocal: Mutex::new(answers.map(Ok).into()), - ..Default::default() - } - } - - fn with_reciprocal_results( - answers: impl IntoIterator>, - ) -> Self { - Self { - reciprocal: Mutex::new(answers.into_iter().collect()), - ..Default::default() - } - } - - fn hidden_writes(&self) -> Vec { - self.contact_updates - .lock() - .expect("not poisoned") - .iter() - .map(|update| match update.display_hidden { - ContactInfoField::Replace(hidden) => hidden, - ContactInfoField::Preserve => panic!("expected an explicit visibility change"), - }) - .collect() - } - - fn contact_updates(&self) -> Vec { - self.contact_updates.lock().expect("not poisoned").clone() - } - - fn was_withdrawn(&self) -> bool { - *self.withdrawn.lock().expect("not poisoned") - } + withdraw_fails: bool, + phase_cleared: Mutex, + phase_fails: bool, + ignored: Mutex, + unignore_fails: bool, + /// The reply is taken in between the reciprocal query and the ignore. + established_meanwhile: bool, } impl CancelOps for ScriptedOps { @@ -1616,160 +2030,96 @@ mod tests { Ok(self.action_lock.clone().lock_owned().await) } - async fn lock_contact_info(&self) -> tokio::sync::OwnedMutexGuard<()> { - self.contact_info_lock.clone().lock_owned().await - } - - fn phase(&self) -> Result, TaskError> { - Ok(*self.phase.lock().expect("not poisoned")) - } - - fn set_phase(&self, phase: ContactRequestActionPhase) -> Result<(), TaskError> { - *self.phase.lock().expect("not poisoned") = Some(phase); - Ok(()) - } - fn clear_phase(&self) -> Result<(), TaskError> { - *self.phase.lock().expect("not poisoned") = None; + if self.phase_fails { + return Err(TaskError::DashpaySidecarStorage { + source: crate::wallet_backend::KvAdapterError::Truncated, + }); + } + *self.phase_cleared.lock().unwrap() = true; Ok(()) } async fn reciprocal_request_exists(&self) -> Result { - self.reciprocal - .lock() - .expect("not poisoned") - .pop_front() - .unwrap_or(Ok(false)) + Ok(self.reciprocal) } - async fn contact_is_hidden( - &self, - _unreadable: UnreadableContactInfoPolicy, - ) -> Result { - let hidden = *self.contact_hidden.lock().expect("not poisoned"); - tokio::task::yield_now().await; - Ok(hidden) + async fn ignore_recipient(&self) -> Result { + *self.ignored.lock().unwrap() = !self.established_meanwhile; + Ok(!self.established_meanwhile) } - async fn update_contact_info( - &self, - update: ContactInfoUpdate, - _write_guard: &tokio::sync::OwnedMutexGuard<()>, - ) -> Result<(), TaskError> { - if self.hide_fails { - return Err(TaskError::DocumentNotFound); - } - self.contact_updates - .lock() - .expect("not poisoned") - .push(update.clone()); - if let ContactInfoField::Replace(hidden) = update.display_hidden { - *self.contact_hidden.lock().expect("not poisoned") = hidden; + async fn unignore_recipient(&self) -> Result<(), TaskError> { + if self.unignore_fails { + return Err(TaskError::WalletStateInconsistent); } + *self.ignored.lock().unwrap() = false; Ok(()) } fn mark_withdrawn(&self) -> Result<(), TaskError> { - let mut failures = self.withdraw_failures.lock().expect("not poisoned"); - if *failures > 0 { - *failures -= 1; - return Err(TaskError::WalletBackendNotYetWired); + if self.withdraw_fails { + return Err(TaskError::DashpaySidecarStorage { + source: crate::wallet_backend::KvAdapterError::Truncated, + }); } - *self.withdrawn.lock().expect("not poisoned") = true; + *self.withdrawn.lock().unwrap() = true; Ok(()) } } - fn assert_preserving_visibility_update(update: &ContactInfoUpdate, hidden: bool) { - use crate::model::dashpay::{AcceptedAccounts, ContactInfoField}; - - assert_eq!(update.nickname, ContactInfoField::Preserve); - assert_eq!(update.note, ContactInfoField::Preserve); - assert_eq!(update.accepted_accounts, AcceptedAccounts::Preserve); - assert_eq!(update.display_hidden, ContactInfoField::Replace(hidden)); - } - + /// The reply is taken in and the contact + /// established after the reciprocal query; the cancellation then reports + /// the contact and records no withdrawal. #[tokio::test] - async fn cancelling_a_pending_request_preserves_unrelated_contact_details() { - let ops = ScriptedOps::with_reciprocal([false, false]); - - let outcome = cancel_flow(&ops, UnreadableContactInfoPolicy::Abort) - .await - .expect("cancellation succeeds"); + async fn a_reply_taken_in_during_the_cancel_wins() { + let ops = ScriptedOps { + established_meanwhile: true, + ..Default::default() + }; - assert_eq!(outcome, CancelOutcome::Withdrawn); assert_eq!( - ops.hidden_writes(), - vec![true], - "a pending request must be hidden exactly once" - ); - assert_preserving_visibility_update(&ops.contact_updates()[0], true); - assert!( - ops.was_withdrawn(), - "the withdrawal must be recorded so the row stops being listed" - ); - } - - #[tokio::test] - async fn cancelling_an_answered_request_hides_nothing() { - // The recipient answered before the user clicked Cancel. - let ops = ScriptedOps::with_reciprocal([true, true]); - - let outcome = cancel_flow(&ops, UnreadableContactInfoPolicy::Abort) - .await - .expect("cancellation succeeds"); - - assert_eq!(outcome, CancelOutcome::AlreadyEstablished); - assert!( - ops.hidden_writes().is_empty(), - "an established contact must never be hidden by a cancellation" + cancel_flow(&ops).await.expect("cancel"), + CancelOutcome::AlreadyEstablished ); - assert!(!ops.was_withdrawn()); + assert!(!*ops.withdrawn.lock().unwrap()); + assert!(!*ops.ignored.lock().unwrap(), "the ignore is lifted again"); } #[tokio::test] - async fn a_reciprocal_request_landing_inside_the_window_leaves_the_contact_visible() { - // Pending when checked, established by the time the hide broadcast - // landed — the exact race the check-then-write ordering cannot prevent. - let ops = ScriptedOps::with_reciprocal([false, true]); - - let outcome = cancel_flow(&ops, UnreadableContactInfoPolicy::Abort) - .await - .expect("cancellation succeeds"); + async fn withdrawing_a_pending_request_records_it_on_this_device() { + let ops = ScriptedOps::default(); assert_eq!( - outcome, - CancelOutcome::AlreadyEstablished, - "the caller must be told the pair is a contact, not that a request was cancelled" + cancel_flow(&ops).await.expect("cancel"), + CancelOutcome::Withdrawn ); - assert_eq!( - ops.hidden_writes(), - vec![true, false], - "the hide must be undone once the reciprocal request is detected, so the \ - freshly-established contact does not vanish" + assert!(*ops.withdrawn.lock().unwrap()); + assert!( + *ops.ignored.lock().unwrap(), + "SEC-001: a later reply must not establish the contact on its own" ); assert!( - !ops.was_withdrawn(), - "an established contact must not be marked as a withdrawn request" + *ops.phase_cleared.lock().unwrap(), + "an older version's record is retired" ); } #[tokio::test] - async fn a_failed_hide_broadcast_records_no_withdrawal() { + async fn withdrawing_an_answered_request_changes_nothing() { let ops = ScriptedOps { - hide_fails: true, - ..ScriptedOps::with_reciprocal([false, false]) + reciprocal: true, + ..Default::default() }; - assert!( - cancel_flow(&ops, UnreadableContactInfoPolicy::Abort) - .await - .is_err(), - "a failed broadcast must surface, not be swallowed" + assert_eq!( + cancel_flow(&ops).await.expect("cancel"), + CancelOutcome::AlreadyEstablished ); + assert!(!*ops.withdrawn.lock().unwrap()); assert!( - !ops.was_withdrawn(), - "the request is still pending on Platform, so it must keep being listed" + !*ops.ignored.lock().unwrap(), + "an established contact is not ignored" ); } @@ -1779,16 +2129,70 @@ mod tests { // request comes back as pending on the next reload, so announcing a // successful cancellation would be a lie. let ops = ScriptedOps { - withdraw_failures: Mutex::new(1), - ..ScriptedOps::with_reciprocal([false, false]) + withdraw_fails: true, + ..Default::default() }; - assert!( - cancel_flow(&ops, UnreadableContactInfoPolicy::Abort) - .await - .is_err(), - "a withdrawal the sidecar refused must surface as an error, not as success" - ); + assert!(cancel_flow(&ops).await.is_err()); + } + + /// A withdrawal whose marker cannot be written lifts the ignore it just + /// set, so nothing is left half-done: no marker means no ignore. + #[tokio::test] + async fn a_failed_withdrawal_record_lifts_the_ignore_again() { + let ops = ScriptedOps { + withdraw_fails: true, + ..Default::default() + }; + + assert!(matches!( + cancel_flow(&ops).await, + Err(TaskError::DashPayRequestDecisionNotRecorded { .. }) + )); + assert!(!*ops.ignored.lock().unwrap()); + } + + /// The decline twin of `a_failed_withdrawal_record_lifts_the_ignore_again`. + #[tokio::test] + async fn a_failed_decline_record_lifts_the_ignore_again() { + let ops = ScriptedRejectOps { + decline_fails: true, + ..Default::default() + }; + + assert!(matches!( + reject_flow(&ops).await, + Err(TaskError::DashPayRequestDecisionNotRecorded { .. }) + )); + assert!(*ops.unignored.lock().unwrap()); + } + + /// When the rollback fails too, the user still sees why the decision + /// was not recorded, not the rollback's error; the ignore left behind is + /// lifted by the next send or accept + /// (`an_ignore_left_without_a_marker_is_lifted_on_re_engagement`). + #[tokio::test] + async fn a_failed_rollback_reports_the_unrecorded_decision() { + let decline = ScriptedRejectOps { + decline_fails: true, + unignore_fails: true, + ..Default::default() + }; + let withdraw = ScriptedOps { + withdraw_fails: true, + unignore_fails: true, + ..Default::default() + }; + + assert!(matches!( + reject_flow(&decline).await, + Err(TaskError::DashPayRequestDecisionNotRecorded { .. }) + )); + assert!(matches!( + cancel_flow(&withdraw).await, + Err(TaskError::DashPayRequestDecisionNotRecorded { .. }) + )); + assert!(*withdraw.ignored.lock().unwrap()); } #[test] @@ -1808,12 +2212,14 @@ mod tests { #[derive(Default)] struct ScriptedRejectOps { action_lock: Arc>, - contact_info_lock: Arc>, - phase: Mutex>, - hidden: Mutex, - hidden_writes: Mutex, - mark_attempts: Mutex, - mark_failures: Mutex, + ignore_fails: bool, + decline_fails: bool, + phase_fails: bool, + established_meanwhile: bool, + ignored: Mutex, + unignore_fails: bool, + unignored: Mutex, + declined: Mutex, } impl RejectOps for ScriptedRejectOps { @@ -1821,262 +2227,143 @@ mod tests { Ok(self.action_lock.clone().lock_owned().await) } - async fn lock_contact_info(&self) -> tokio::sync::OwnedMutexGuard<()> { - self.contact_info_lock.clone().lock_owned().await - } - - fn phase(&self) -> Result, TaskError> { - Ok(*self.phase.lock().expect("not poisoned")) - } - - fn set_phase(&self, phase: ContactRequestActionPhase) -> Result<(), TaskError> { - *self.phase.lock().expect("not poisoned") = Some(phase); - Ok(()) - } - fn clear_phase(&self) -> Result<(), TaskError> { - *self.phase.lock().expect("not poisoned") = None; + if self.phase_fails { + return Err(TaskError::DashpaySidecarStorage { + source: crate::wallet_backend::KvAdapterError::Truncated, + }); + } Ok(()) } - async fn contact_is_hidden( - &self, - _unreadable: UnreadableContactInfoPolicy, - ) -> Result { - let hidden = *self.hidden.lock().expect("not poisoned"); - tokio::task::yield_now().await; - Ok(hidden) + async fn ignore_sender(&self) -> Result { + if self.ignore_fails { + return Err(TaskError::WalletStateInconsistent); + } + if self.established_meanwhile { + return Ok(false); + } + *self.ignored.lock().unwrap() += 1; + Ok(true) } - async fn update_contact_info( - &self, - update: ContactInfoUpdate, - _write_guard: &tokio::sync::OwnedMutexGuard<()>, - ) -> Result<(), TaskError> { - assert_eq!(update.display_hidden, ContactInfoField::Replace(true)); - *self.hidden.lock().expect("not poisoned") = true; - *self.hidden_writes.lock().expect("not poisoned") += 1; + async fn unignore_sender(&self) -> Result<(), TaskError> { + if self.unignore_fails { + return Err(TaskError::WalletStateInconsistent); + } + *self.unignored.lock().unwrap() = true; Ok(()) } fn mark_declined(&self) -> Result<(), TaskError> { - *self.mark_attempts.lock().expect("not poisoned") += 1; - let mut failures = self.mark_failures.lock().expect("not poisoned"); - if *failures > 0 { - *failures -= 1; - return Err(TaskError::WalletBackendNotYetWired); + if self.decline_fails { + return Err(TaskError::DashpaySidecarStorage { + source: crate::wallet_backend::KvAdapterError::Truncated, + }); } + *self.declined.lock().unwrap() = true; Ok(()) } fn request_id(&self) -> Identifier { id(7) } - } - - #[tokio::test] - async fn contact_info_decline_waits_for_unhide_before_reading_visibility() { - let ops = ScriptedRejectOps { - hidden: Mutex::new(true), - ..Default::default() - }; - let unhide = ops.contact_info_lock.clone().lock_owned().await; - let mut decline = Box::pin(reject_flow(&ops, UnreadableContactInfoPolicy::Abort)); - assert!(futures::poll!(&mut decline).is_pending()); - assert_eq!( - *ops.phase.lock().unwrap(), - None, - "wait before reading or deciding" - ); - *ops.hidden.lock().unwrap() = false; - drop(unhide); - assert!(futures::poll!(&mut decline).is_pending()); - let mut competing_write = Box::pin(ops.contact_info_lock.clone().lock_owned()); - assert!( - futures::poll!(&mut competing_write).is_pending(), - "hold through the hide decision" - ); - decline.await.expect("decline completes"); - assert!(*ops.hidden.lock().unwrap()); - assert_eq!(*ops.hidden_writes.lock().unwrap(), 1); - drop(competing_write.await); - } - #[tokio::test] - async fn contact_info_cancel_waits_for_unhide_before_reading_visibility() { - let ops = ScriptedOps { - contact_hidden: Mutex::new(true), - ..Default::default() - }; - let unhide = ops.contact_info_lock.clone().lock_owned().await; - let mut cancel = Box::pin(cancel_flow(&ops, UnreadableContactInfoPolicy::Abort)); - assert!(futures::poll!(&mut cancel).is_pending()); - assert_eq!( - *ops.phase.lock().unwrap(), - None, - "wait before reading or deciding" - ); - *ops.contact_hidden.lock().unwrap() = false; - drop(unhide); - assert!(futures::poll!(&mut cancel).is_pending()); - let mut competing_write = Box::pin(ops.contact_info_lock.clone().lock_owned()); - assert!( - futures::poll!(&mut competing_write).is_pending(), - "hold through the hide decision" - ); - assert_eq!(cancel.await.unwrap(), CancelOutcome::Withdrawn); - assert!(*ops.contact_hidden.lock().unwrap()); - assert_eq!(ops.hidden_writes(), vec![true]); - drop(competing_write.await); + fn sender_id(&self) -> Identifier { + id(8) + } } + /// The decline twin of `a_reply_taken_in_during_the_cancel_wins`: the + /// owner's own request (sent from another device) is taken in first, so + /// the contact is established and nothing is declined. #[tokio::test] - async fn decline_retry_after_marker_failure_does_not_rebroadcast_hide() { + async fn a_contact_established_during_the_decline_wins() { let ops = ScriptedRejectOps { - mark_failures: Mutex::new(1), + established_meanwhile: true, ..Default::default() }; - assert!( - reject_flow(&ops, UnreadableContactInfoPolicy::Abort) - .await - .is_err() - ); - assert!( - reject_flow(&ops, UnreadableContactInfoPolicy::Abort) - .await - .is_ok() - ); - assert_eq!(*ops.hidden_writes.lock().expect("not poisoned"), 1); - assert_eq!(*ops.mark_attempts.lock().expect("not poisoned"), 2); + assert!(matches!( + reject_flow(&ops).await, + Ok(BackendTaskSuccessResult::DashPayContactAlreadyEstablished { request_id, contact_id }) + if request_id == id(7) && contact_id == id(8) + )); + assert!(!*ops.declined.lock().unwrap()); } #[tokio::test] - async fn concurrent_declines_share_one_paid_hide() { + async fn declining_ignores_the_sender_and_records_the_decline() { let ops = ScriptedRejectOps::default(); - let (first, second) = tokio::join!( - reject_flow(&ops, UnreadableContactInfoPolicy::Abort), - reject_flow(&ops, UnreadableContactInfoPolicy::Abort), - ); - - assert!(first.is_ok()); - assert!(second.is_ok()); - assert_eq!( - *ops.hidden_writes.lock().expect("not poisoned"), - 1, - "backend serialization must permit only one paid hide" - ); + assert!(matches!( + reject_flow(&ops).await, + Ok(BackendTaskSuccessResult::DashPayContactRequestRejected(request)) if request == id(7) + )); + assert_eq!(*ops.ignored.lock().unwrap(), 1); + assert!(*ops.declined.lock().unwrap()); } + /// The old progress record is inert once the decision is recorded, so + /// failing to forget it does not fail a decline or a withdrawal. #[tokio::test] - async fn cancel_retry_after_marker_failure_does_not_rebroadcast_hide() { - let ops = ScriptedOps { - withdraw_failures: Mutex::new(1), - ..ScriptedOps::with_reciprocal([false, false]) + async fn a_leftover_progress_record_does_not_fail_a_recorded_decision() { + let decline = ScriptedRejectOps { + phase_fails: true, + ..Default::default() + }; + let withdraw = ScriptedOps { + phase_fails: true, + ..Default::default() }; - assert!( - cancel_flow(&ops, UnreadableContactInfoPolicy::Abort) - .await - .is_err() - ); - assert_eq!( - cancel_flow(&ops, UnreadableContactInfoPolicy::Abort) - .await - .expect("marker repair succeeds"), - CancelOutcome::Withdrawn - ); - assert_eq!(ops.hidden_writes(), vec![true]); - assert!(ops.reciprocal.lock().expect("not poisoned").is_empty()); - } - - #[tokio::test] - async fn concurrent_cancellations_share_one_paid_hide() { - let ops = ScriptedOps::with_reciprocal([false, false]); - - let (first, second) = tokio::join!( - cancel_flow(&ops, UnreadableContactInfoPolicy::Abort), - cancel_flow(&ops, UnreadableContactInfoPolicy::Abort), - ); - - assert_eq!(first.expect("first cancellation"), CancelOutcome::Withdrawn); + assert!(matches!( + reject_flow(&decline).await, + Ok(BackendTaskSuccessResult::DashPayContactRequestRejected(_)) + )); + assert!(*decline.declined.lock().unwrap()); assert_eq!( - second.expect("second cancellation"), + cancel_flow(&withdraw).await.expect("withdrawn"), CancelOutcome::Withdrawn ); - assert_eq!( - ops.hidden_writes(), - vec![true], - "backend serialization must permit only one paid hide" - ); } + /// Declining and withdrawing publish nothing, so a failed local record + /// must not tell the user that the change reached the network. #[tokio::test] - async fn cancel_retry_after_post_hide_probe_failure_does_not_rehide() { - let ops = ScriptedOps::with_reciprocal_results([ - Ok(false), - Err(TaskError::DocumentNotFound), - Ok(false), - ]); + async fn a_failed_local_decision_record_does_not_claim_the_network() { + let decline = ScriptedRejectOps { + decline_fails: true, + ..Default::default() + }; + let withdraw = ScriptedOps { + withdraw_fails: true, + ..Default::default() + }; - assert!( - cancel_flow(&ops, UnreadableContactInfoPolicy::Abort) + for error in [ + reject_flow(&decline) .await - .is_err() - ); - assert_eq!( - cancel_flow(&ops, UnreadableContactInfoPolicy::Abort) + .expect_err("decline record fails"), + cancel_flow(&withdraw) .await - .expect("post-hide probe resumes"), - CancelOutcome::Withdrawn - ); - assert_eq!(ops.hidden_writes(), vec![true]); + .expect_err("withdrawal record fails"), + ] { + assert!( + matches!(error, TaskError::DashPayRequestDecisionNotRecorded { .. }), + "{error:?}" + ); + } } #[tokio::test] - async fn cancel_retry_that_discovers_reciprocal_unhides_once() { - let ops = ScriptedOps::with_reciprocal_results([ - Ok(false), - Err(TaskError::DocumentNotFound), - Ok(true), - ]); - - assert!( - cancel_flow(&ops, UnreadableContactInfoPolicy::Abort) - .await - .is_err() - ); - assert_eq!( - cancel_flow(&ops, UnreadableContactInfoPolicy::Abort) - .await - .expect("reciprocal retry succeeds"), - CancelOutcome::AlreadyEstablished - ); - assert_eq!(ops.hidden_writes(), vec![true, false]); - assert!(!ops.was_withdrawn()); - } - - #[test] - fn declining_preserves_unrelated_contact_details() { - // The write `reject_contact_request` broadcasts. Declining hides the - // sender; it must not volunteer empty details over what they stored. - let update = hidden_contact_update(true, UnreadableContactInfoPolicy::Abort); - - assert_preserving_visibility_update(&update, true); - } - - #[test] - fn a_confirmed_overwrite_carries_the_users_choice_into_the_write() { - use crate::model::dashpay::AcceptedAccounts; - - let update = hidden_contact_update(true, UnreadableContactInfoPolicy::Overwrite); + async fn a_failed_ignore_records_no_decline() { + let ops = ScriptedRejectOps { + ignore_fails: true, + ..Default::default() + }; - assert_eq!(update.unreadable, UnreadableContactInfoPolicy::Overwrite); - assert_eq!( - update.accepted_accounts, - AcceptedAccounts::Preserve, - "confirming an overwrite of unreadable data must not also volunteer an empty account list" - ); + assert!(reject_flow(&ops).await.is_err()); + assert!(!*ops.declined.lock().unwrap(), "a retry starts over"); } } diff --git a/src/backend_task/dashpay/contacts.rs b/src/backend_task/dashpay/contacts.rs index 871e94676..5895b5025 100644 --- a/src/backend_task/dashpay/contacts.rs +++ b/src/backend_task/dashpay/contacts.rs @@ -3,7 +3,7 @@ use crate::backend_task::dashpay::contact_request_query; use crate::backend_task::dashpay::errors::DashPayError; use crate::backend_task::error::TaskError; use crate::context::AppContext; -use crate::model::dashpay::contact_request_recipient; +use crate::model::dashpay::{ContactDetails, contact_request_recipient}; use crate::model::qualified_identity::QualifiedIdentity; use dash_sdk::Sdk; use dash_sdk::dpp::data_contract::DataContract; @@ -128,22 +128,38 @@ pub(super) fn decrypt_private_data( Ok(decrypted.to_vec()) } -/// The nickname, note and visibility the owner stored for each contact, read -/// from every page of the owner's `contactInfo` documents. +/// The nickname, note and visibility the owner stored for each contact in +/// `contactInfo` documents sealed under the legacy key root, read from every +/// page of the owner's documents. /// -/// Documents come oldest first, the order the write lookup scans, and the -/// newest document for a contact wins, so the load shows the document a save -/// rewrites. +/// Pages are ordered by `$updatedAt`, oldest first, and a later document for +/// a contact replaces an earlier one, so the newest document wins. The test +/// seam over [`stored_contact_details`]'s legacy half. +#[cfg(test)] pub(super) async fn load_contact_details( query: DocumentQuery, fetch_page: P, - mut derive_keys: D, + derive_keys: D, ) -> Result, TaskError> where P: FnMut(DocumentQuery) -> PF, PF: Future>, D: FnMut(u32) -> DF, DF: Future, Zeroizing<[u8; 32]>), TaskError>>, +{ + let documents = fetch_contact_info_documents(query, fetch_page).await?; + legacy_details_from(&documents, derive_keys).await +} + +/// Every page of the owner's `contactInfo` documents, oldest first by +/// `$updatedAt`. +async fn fetch_contact_info_documents( + query: DocumentQuery, + fetch_page: P, +) -> Result, TaskError> +where + P: FnMut(DocumentQuery) -> PF, + PF: Future>, { let query = query.with_order_by(OrderClause { field: "$updatedAt".to_string(), @@ -151,9 +167,29 @@ where }); let documents = super::contact_info::fetch_all_contact_info_documents(query, fetch_page).await?; + Ok(documents.into_values().flatten().collect()) +} +/// The details `documents` (oldest first) hold under the legacy key root; +/// a later document for a contact replaces an earlier one. A document whose +/// keys or contact id do not open is skipped, since nothing tells whose it +/// is. One whose details do not decrypt or decode marks its contact +/// unreadable and hidden. +/// +/// # Errors +/// +/// The keys could not be derived for a reason that holds for every +/// document, such as a cancelled password prompt. +async fn legacy_details_from( + documents: &[Document], + mut derive_keys: D, +) -> Result, TaskError> +where + D: FnMut(u32) -> DF, + DF: Future, Zeroizing<[u8; 32]>), TaskError>>, +{ let mut contact_info_map: HashMap = HashMap::new(); - for doc in documents.into_values().flatten() { + for doc in documents { let props = doc.properties(); let Some(deriv_idx) = props .get("derivationEncryptionKeyIndex") @@ -161,8 +197,11 @@ where else { continue; }; - let Ok((enc_user_id_key, private_data_key)) = derive_keys(deriv_idx).await else { - continue; + let (enc_user_id_key, private_data_key) = match derive_keys(deriv_idx).await { + Ok(keys) => keys, + // The document's own index cannot be derived. + Err(TaskError::ContactKeyDerivationFailed { .. }) => continue, + Err(error) => return Err(error), }; // Platform returns the fixed 32-byte field as `Value::Bytes32`; a // document built locally carries `Value::Bytes`. @@ -182,9 +221,10 @@ where ); continue; }; - // The DIP-15 codec platform-wallet writes with. A payload that is - // present but cannot be opened is not "no details": its hidden flag - // is unknown, so the contact stays hidden. + // Read with both the DIP-15 codec and the layout older versions of + // this client wrote. A payload that is present but cannot be opened + // is not "no details": its hidden flag is unknown, so the contact + // stays hidden. let private_data = match props.get("privateData") { None => Some(ContactInfoPrivateData::default()), Some(value) => value @@ -199,8 +239,6 @@ where ..Default::default() }); - // Documents come oldest first, so the newest replaces older ones: it - // is the one a save rewrites, and the rewrite keeps it the newest. contact_info_map.insert( contact_id, ContactData { @@ -221,6 +259,158 @@ where Ok(contact_info_map) } +/// Run `sync` unless a contact details save of `owner` is in flight; `None` +/// when one is. +/// +/// A save stores its details on this device before it publishes them; a +/// sync in between would put the older published details back over them. +/// A read does not wait for the save, which can sit behind a password prompt +/// or a slow publish. Until the save lands, the read can show the details as +/// they were before it; the contacts list reloads once it does. +pub(super) async fn unless_saving( + writes: &crate::context::ContactInfoWrites, + owner: Identifier, + sync: impl Future, +) -> Option { + let _write_guard = writes.try_acquire(owner)?; + Some(sync.await) +} + +/// The details the owner's stored `contactInfo` documents hold. +pub(super) struct StoredContactDetails { + /// From DIP-0015 documents platform-wallet can read, newest per contact; + /// an error when the seed could not be used to read them. A save must not + /// guess past that error; the contacts list may. + pub(super) published: Result, + /// From documents older versions of this app wrote under the legacy + /// key root, newest per contact; an error as for `published`. + pub(super) legacy: Result, TaskError>, +} + +/// Read every `contactInfo` document the owner stored, both as DIP-0015 +/// documents and as legacy-key ones. +/// +/// platform-wallet does not read DIP-0015 documents back for a wallet loaded +/// without its seed, which is how wallets load after a restart, so they are +/// opened here with platform-wallet's keys and codec. +pub(super) async fn stored_contact_details( + app_context: &Arc, + sdk: &Sdk, + identity: &QualifiedIdentity, +) -> Result { + let query = DocumentQuery::new(app_context.dashpay_contract(), "contactInfo") + .map_err(|e| DashPayError::QueryCreation { + query_target: "DashPay contactInfo", + source: Box::new(e.into()), + })? + .with_where(WhereClause { + field: "$ownerId".to_string(), + operator: WhereOperator::Equal, + value: Value::Identifier(identity.identity.id().to_buffer()), + }); + let documents = fetch_contact_info_documents(query, |query| async move { + Document::fetch_many(sdk, query) + .await + .map_err(TaskError::from) + }) + .await?; + let published = match app_context.wallet_backend() { + Ok(backend) => { + backend + .dashpay_open_contact_infos(identity, &documents) + .await + } + Err(_) => Ok(crate::wallet_backend::PublishedContactInfos::default()), + }; + // Without a wallet seed no legacy key exists, so no document opens. + let legacy = if identity.dashpay_wallet_seed_hash().is_some() { + legacy_details_from(&documents, |derivation_index| { + derive_contact_info_keys(app_context, identity, derivation_index) + }) + .await + } else { + Ok(HashMap::new()) + }; + Ok(StoredContactDetails { published, legacy }) +} + +/// The details the contacts list shows for one contact, and that a save +/// keeps for every field it does not replace. +/// +/// A published DIP-0015 document wins: Platform holds the latest saved state +/// from any device. Without one, platform-wallet's details on this device +/// win; a legacy-key document stands in only while platform-wallet has never +/// held details for the contact (`synced_before` false). Once it has, its +/// details win even when empty, so a cleared note or an unhide is never +/// undone by an old legacy document. +pub(super) fn shown_contact_details( + published: Option, + local: Option, + synced_before: bool, + legacy: Option, +) -> ContactDetails { + if let Some(published) = published { + return published; + } + if synced_before { + return local.unwrap_or_default(); + } + local + .filter(|details| !details.is_empty()) + .or(legacy) + .unwrap_or_default() +} + +/// Whether [`shown_contact_details`] shows the legacy document's details: +/// only then can unreadable legacy details mark the contact unreadable. +pub(super) fn legacy_details_shown( + published: Option<&ContactDetails>, + local: Option<&ContactDetails>, + synced_before: bool, +) -> bool { + published.is_none() && !synced_before && local.is_none_or(ContactDetails::is_empty) +} + +/// Whether platform-wallet's side holds details worth recording as its own: +/// a published DIP-0015 document (even an empty one), or non-empty details on +/// this device. +pub(super) fn holds_details( + published: Option<&ContactDetails>, + local: Option<&ContactDetails>, +) -> bool { + published.is_some() || local.is_some_and(|details| !details.is_empty()) +} + +/// The people both sides have sent a contact request to, minus anyone the +/// owner withdrew their request from: a reply to a withdrawn request is a new +/// request for the owner to answer, not an established contact. +pub(super) fn mutual_contacts( + incoming: &[(Identifier, Document)], + outgoing: &[(Identifier, Document)], + is_withdrawn: impl Fn(&Identifier) -> bool, +) -> HashSet { + incoming + .iter() + .map(|(_, doc)| doc.owner_id()) + .filter(|from_id| !is_withdrawn(from_id)) + .filter(|from_id| { + outgoing + .iter() + .any(|(_, doc)| contact_request_recipient(doc).as_ref() == Some(from_id)) + }) + .collect() +} + +impl ContactData { + pub(super) fn details(&self) -> ContactDetails { + ContactDetails { + nickname: self.nickname.clone(), + note: self.note.clone(), + hidden: self.is_hidden, + } + } +} + #[derive(Debug, Clone, PartialEq)] pub struct ContactData { pub identity_id: Identifier, @@ -289,60 +479,115 @@ pub async fn load_contacts( .collect(); // Find mutual contacts (where both parties have sent requests to each other) - let contacts: HashSet = incoming - .iter() - .map(|(_, doc)| doc.owner_id()) - .filter(|from_id| { - outgoing - .iter() - .any(|(_, doc)| contact_request_recipient(doc).as_ref() == Some(from_id)) - }) - .collect(); - - // Now query for contact info documents - let mut contact_info_query = DocumentQuery::new(dashpay_contract.clone(), "contactInfo") - .map_err(|e| DashPayError::QueryCreation { - query_target: "DashPay contactInfo", - source: Box::new(e.into()), - })?; + let backend = app_context.wallet_backend().ok(); + // As for the request lists: withdrawn and declined people are not + // contacts until the owner re-engages. + let contacts = mutual_contacts(&incoming, &outgoing, |peer| { + backend + .as_ref() + .is_some_and(|backend| backend.dashpay_disengaged_from(&identity_id, peer)) + }); - contact_info_query = contact_info_query.with_where(WhereClause { - field: "$ownerId".to_string(), - operator: WhereOperator::Equal, - value: Value::Identifier(identity_id.to_buffer()), + // platform-wallet's synced details first; a refresh failure leaves the + // last synced details in place. + let mut synced = match &backend { + Some(backend) => { + if let Err(error) = backend.dashpay_sync(&identity_id).await { + tracing::debug!( + ?error, + "LoadContacts: DashPay sync degraded; using cached state" + ); + } + match unless_saving( + &app_context.contact_info_writes, + identity_id, + backend.dashpay_sync_contact_infos(&identity_id), + ) + .await + { + Some(Ok(())) => {} + Some(Err(error)) => tracing::debug!( + ?error, + "LoadContacts: contact details sync degraded; using cached state" + ), + None => tracing::debug!( + "LoadContacts: a contact details save is running; using cached state" + ), + } + backend.dashpay_contact_details(&identity_id).await + } + None => { + tracing::debug!("LoadContacts: no wallet backend; showing legacy details"); + Default::default() + } + }; + let StoredContactDetails { published, legacy } = + stored_contact_details(app_context, sdk, &identity).await?; + let mut published = published.unwrap_or_else(|error| { + tracing::debug!(?error, "LoadContacts: published contact details not read"); + crate::wallet_backend::PublishedContactInfos::default() + }); + let legacy = legacy.unwrap_or_else(|error| { + tracing::debug!(?error, "LoadContacts: legacy contact details not read"); + HashMap::new() }); - let contact_info_map = load_contact_details( - contact_info_query, - |query| async move { - Document::fetch_many(sdk, query) - .await - .map_err(TaskError::from) - }, - |derivation_index| derive_contact_info_keys(app_context, &identity, derivation_index), - ) - .await?; + // Recording which details platform-wallet holds must not race a save, + // which stores its details here before it publishes them: with a save + // running, nothing is recorded this time. + let record_guard = app_context.contact_info_writes.try_acquire(identity_id); // Build enriched contact list with basic data let mut contact_list: Vec = contacts .into_iter() .map(|contact_id| { - contact_info_map - .get(&contact_id) - .cloned() - .unwrap_or(ContactData { - identity_id: contact_id, - nickname: None, - note: None, - is_hidden: false, - details_unreadable: false, - account_reference: 0, - username: None, - display_name: None, - avatar_url: None, - bio: None, - }) + let legacy = legacy.get(&contact_id); + let synced = synced.remove(&contact_id); + let (published, published_unreadable) = match published.take(&contact_id) { + Some((details, unreadable)) => (Some(details), unreadable), + None => (None, false), + }; + let synced_before = backend.as_ref().is_some_and(|backend| { + let synced_before = backend + .dashpay_details_synced(&identity_id, &contact_id) + .unwrap_or_else(|error| { + tracing::debug!(?error, "LoadContacts: synced record not read"); + false + }); + if !synced_before + && record_guard.is_some() + && holds_details(published.as_ref(), synced.as_ref()) + && let Err(error) = + backend.dashpay_mark_details_synced(&identity_id, &contact_id) + { + tracing::debug!(?error, "LoadContacts: could not record synced details"); + } + synced_before + }); + let details_unreadable = published_unreadable + || legacy_details_shown(published.as_ref(), synced.as_ref(), synced_before) + && legacy.is_some_and(|legacy| legacy.details_unreadable); + let details = shown_contact_details( + published, + synced, + synced_before, + legacy.map(ContactData::details), + ); + ContactData { + identity_id: contact_id, + nickname: details.nickname, + note: details.note, + is_hidden: details.hidden, + details_unreadable, + account_reference: legacy.map_or(0, |legacy| legacy.account_reference), + username: None, + display_name: None, + avatar_url: None, + bio: None, + } }) .collect(); + // Saves wait on this guard: it must not be held through the profile reads. + drop(record_guard); // Fetch profiles and usernames for all contacts in parallel with bounded concurrency. // Each contact requires two network queries (profile + DPNS username), so parallelizing @@ -428,9 +673,11 @@ pub async fn load_contacts( } /// Read the contact list for `identity` entirely from offline state: contact -/// relationships and private memos come from the upstream-rehydrated -/// `ManagedIdentity` (via [`crate::wallet_backend::DashpayView`]), and each -/// contact's display profile is served from the DET contact-profile cache. +/// relationships and contact details come from the upstream-rehydrated +/// `ManagedIdentity` (via [`crate::wallet_backend::DashpayView`]), with this +/// device's private-info copy as a fallback (see [`shown_contact_details`]), +/// and each contact's display profile is served from the DET contact-profile +/// cache. /// /// No network round-trip — a view rendered from this result does not require /// connectivity. Profiles a contact has not yet been fetched for are returned @@ -444,6 +691,9 @@ pub async fn load_contacts_offline( let backend = app_context.wallet_backend()?; let stored = backend.dashpay_view().contacts(&owner_id).await; + // The details platform-wallet holds win, as in the network list; this + // device's private-info copy only stands in where it never held any. + let mut synced = backend.dashpay_contact_details(&owner_id).await; let mut contact_list = Vec::with_capacity(stored.len()); for sc in stored { @@ -455,23 +705,39 @@ pub async fn load_contacts_offline( if contact_id == owner_id { continue; } + // Withdrawn and declined people stay hidden, as in the network list + // (`mutual_contacts`). Filtered here rather than in + // `DashpayView::contacts`, whose other callers register payment + // addresses and must keep every contact. + if backend.dashpay_disengaged_from(&owner_id, &contact_id) { + continue; + } let cached = backend.contact_profile_cache().get(&contact_id); let memo = backend .dashpay_get_private_info(&owner_id, &contact_id) - .unwrap_or(None); + .unwrap_or_else(|error| { + tracing::debug!(?error, "LoadContactsOffline: private info not read"); + None + }) + .map(|memo| ContactDetails { + nickname: Some(memo.nickname).filter(|s| !s.is_empty()), + note: Some(memo.notes).filter(|s| !s.is_empty()), + hidden: memo.is_hidden, + }); + let synced_before = backend + .dashpay_details_synced(&owner_id, &contact_id) + .unwrap_or_else(|error| { + tracing::debug!(?error, "LoadContactsOffline: synced record not read"); + false + }); + let details = shown_contact_details(None, synced.remove(&contact_id), synced_before, memo); contact_list.push(ContactData { identity_id: contact_id, - nickname: memo - .as_ref() - .map(|m| m.nickname.clone()) - .filter(|s| !s.is_empty()), - note: memo - .as_ref() - .map(|m| m.notes.clone()) - .filter(|s| !s.is_empty()), - is_hidden: memo.as_ref().map(|m| m.is_hidden).unwrap_or(false), + nickname: details.nickname, + note: details.note, + is_hidden: details.hidden, details_unreadable: false, // Carry the cached account reference so the "Account #N" badge shows // and offline ordering matches the post-refresh view. Falls back to @@ -534,6 +800,421 @@ fn cache_contact_profiles(app_context: &Arc, contacts: &[ContactData #[cfg(test)] mod tests { use super::*; + use std::collections::BTreeMap; + + /// A details sync is skipped, not queued, while a save of the same owner + /// runs: it would put older published details over the save's own, and + /// waiting would hold the contacts behind the save's password prompt. + #[tokio::test] + async fn a_details_sync_is_skipped_while_a_save_runs() { + use std::sync::atomic::{AtomicBool, Ordering}; + use std::task::Poll; + let writes = crate::context::ContactInfoWrites::default(); + let owner = Identifier::from([1; 32]); + let ran = AtomicBool::new(false); + let sync = || async { + ran.store(true, Ordering::SeqCst); + }; + let save = writes.acquire(owner).await; + + let mut skipped = Box::pin(unless_saving(&writes, owner, sync())); + assert!(matches!(futures::poll!(&mut skipped), Poll::Ready(None))); + assert!( + !ran.load(Ordering::SeqCst), + "nothing synced during the save" + ); + + drop(save); + assert_eq!(unless_saving(&writes, owner, sync()).await, Some(())); + assert!(ran.load(Ordering::SeqCst)); + } + + /// After a restart the offline list shows the details platform-wallet + /// holds (synced from Platform) rather than this device's older copy, so + /// a contact hidden on another device is not listed as visible here. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn the_offline_list_shows_platform_wallets_details() { + use crate::model::wallet::Wallet; + use crate::model::wallet::birth_height::WalletOrigin; + use dash_sdk::dpp::dashcore::Network; + use dash_sdk::dpp::identity::Identity; + use dash_sdk::dpp::version::PlatformVersion; + + let dir = tempfile::tempdir().expect("temp dir"); + let context = crate::context::test_support::wired_test_app_context(dir.path()).await; + let backend = context.wallet_backend().expect("backend wired"); + let seed: [u8; 64] = rand::random(); + let wallet = + Wallet::new_from_seed(seed, Network::Testnet, Some("w".into()), None).expect("wallet"); + let (seed_hash, wallet) = context + .register_wallet(wallet, &seed, WalletOrigin::Fresh) + .expect("register wallet"); + backend + .register_wallet_from_seed(&seed_hash, &seed, Some(0)) + .await + .expect("register upstream"); + let owner = Identifier::from([0x11; 32]); + let contact = Identifier::from([0x22; 32]); + let identity = + Identity::create_basic_identity(owner, PlatformVersion::latest()).expect("identity"); + backend + .ensure_identity_managed(&seed_hash, &identity, 0) + .await + .expect("manage identity"); + let request = |from, to| { + platform_wallet::ContactRequest::new(from, to, 0, 0, 0, vec![0u8; 96], 100_000, 1) + }; + backend + .record_sent_contact_request(&seed_hash, &owner, request(owner, contact)) + .await + .expect("record sent request"); + backend + .record_incoming_contact_request(&seed_hash, &owner, request(contact, owner)) + .await + .expect("record incoming request"); + // This device's older copy. + backend + .dashpay_set_private_info( + &owner, + &contact, + &crate::model::dashpay::ContactPrivateInfo { + nickname: "Old".to_string(), + notes: "old note".to_string(), + is_hidden: false, + }, + ) + .expect("sidecar written"); + let synced = ContactDetails { + nickname: Some("Bao".into()), + note: None, + hidden: true, + }; + backend + .set_contact_details_for_tests(&seed_hash, &owner, &contact, synced.clone()) + .await; + let mut qualified = + crate::context::test_support::bare_user_identity(owner, Network::Testnet); + qualified.associated_wallets = BTreeMap::from([(seed_hash, wallet)]); + + let result = load_contacts_offline(&context, qualified) + .await + .expect("offline list"); + + let BackendTaskSuccessResult::DashPayContactsWithInfo { contacts, .. } = result else { + panic!("expected DashPayContactsWithInfo, got {result:?}"); + }; + let [row] = contacts.as_slice() else { + panic!("expected one contact, got {contacts:?}"); + }; + assert_eq!(row.details(), synced); + } + + /// After a restart the contacts list is built offline; a request the + /// owner withdrew stays hidden there, as it does in the network list. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn the_offline_list_hides_a_withdrawn_request() { + use crate::model::wallet::Wallet; + use crate::model::wallet::birth_height::WalletOrigin; + use dash_sdk::dpp::dashcore::Network; + use dash_sdk::dpp::identity::Identity; + use dash_sdk::dpp::version::PlatformVersion; + + let dir = tempfile::tempdir().expect("temp dir"); + let context = crate::context::test_support::wired_test_app_context(dir.path()).await; + let backend = context.wallet_backend().expect("backend wired"); + let seed: [u8; 64] = rand::random(); + let wallet = + Wallet::new_from_seed(seed, Network::Testnet, Some("w".into()), None).expect("wallet"); + let (seed_hash, wallet) = context + .register_wallet(wallet, &seed, WalletOrigin::Fresh) + .expect("register wallet"); + backend + .register_wallet_from_seed(&seed_hash, &seed, Some(0)) + .await + .expect("register upstream"); + let owner = Identifier::from([0x11; 32]); + let withdrawn = Identifier::from([0x22; 32]); + let pending = Identifier::from([0x33; 32]); + let identity = + Identity::create_basic_identity(owner, PlatformVersion::latest()).expect("identity"); + backend + .ensure_identity_managed(&seed_hash, &identity, 0) + .await + .expect("manage identity"); + for recipient in [withdrawn, pending] { + backend + .record_sent_contact_request( + &seed_hash, + &owner, + platform_wallet::ContactRequest::new( + owner, + recipient, + 0, + 0, + 0, + vec![0u8; 96], + 100_000, + 1, + ), + ) + .await + .expect("record sent request"); + } + backend + .dashpay_mark_withdrawn(&owner, &withdrawn) + .expect("withdraw"); + let mut qualified = + crate::context::test_support::bare_user_identity(owner, Network::Testnet); + qualified.associated_wallets = BTreeMap::from([(seed_hash, wallet)]); + + let result = load_contacts_offline(&context, qualified) + .await + .expect("offline list"); + + let BackendTaskSuccessResult::DashPayContactsWithInfo { contacts, .. } = result else { + panic!("expected DashPayContactsWithInfo, got {result:?}"); + }; + assert_eq!( + contacts.iter().map(|c| c.identity_id).collect::>(), + vec![pending] + ); + } + + /// Declining someone's request hides them from the offline list even + /// while the owner's own request to them still stands, as in the network + /// list (`dashpay_disengaged_from`). + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn the_offline_list_hides_a_declined_person() { + use crate::model::wallet::Wallet; + use crate::model::wallet::birth_height::WalletOrigin; + use dash_sdk::dpp::dashcore::Network; + use dash_sdk::dpp::identity::Identity; + use dash_sdk::dpp::version::PlatformVersion; + + let dir = tempfile::tempdir().expect("temp dir"); + let context = crate::context::test_support::wired_test_app_context(dir.path()).await; + let backend = context.wallet_backend().expect("backend wired"); + let seed: [u8; 64] = rand::random(); + let wallet = + Wallet::new_from_seed(seed, Network::Testnet, Some("w".into()), None).expect("wallet"); + let (seed_hash, wallet) = context + .register_wallet(wallet, &seed, WalletOrigin::Fresh) + .expect("register wallet"); + backend + .register_wallet_from_seed(&seed_hash, &seed, Some(0)) + .await + .expect("register upstream"); + let owner = Identifier::from([0x11; 32]); + let declined = Identifier::from([0x22; 32]); + let kept = Identifier::from([0x33; 32]); + let identity = + Identity::create_basic_identity(owner, PlatformVersion::latest()).expect("identity"); + backend + .ensure_identity_managed(&seed_hash, &identity, 0) + .await + .expect("manage identity"); + let request = |from, to| { + platform_wallet::ContactRequest::new(from, to, 0, 0, 0, vec![0u8; 96], 100_000, 1) + }; + for peer in [declined, kept] { + backend + .record_sent_contact_request(&seed_hash, &owner, request(owner, peer)) + .await + .expect("record sent request"); + } + backend + .record_incoming_contact_request(&seed_hash, &owner, request(declined, owner)) + .await + .expect("record incoming request"); + // Only the decline marker: the owner's own request still stands. + backend + .dashpay_mark_declined(&owner, &declined) + .expect("decline"); + assert!(!backend.dashpay_is_withdrawn(&owner, &declined)); + let mut qualified = + crate::context::test_support::bare_user_identity(owner, Network::Testnet); + qualified.associated_wallets = BTreeMap::from([(seed_hash, wallet)]); + + let result = load_contacts_offline(&context, qualified) + .await + .expect("offline list"); + + let BackendTaskSuccessResult::DashPayContactsWithInfo { contacts, .. } = result else { + panic!("expected DashPayContactsWithInfo, got {result:?}"); + }; + assert_eq!( + contacts.iter().map(|c| c.identity_id).collect::>(), + vec![kept] + ); + } + + fn details(note: &str) -> ContactDetails { + ContactDetails { + nickname: None, + note: Some(note.to_string()), + hidden: false, + } + } + + #[test] + fn synced_contact_details_win_over_legacy_ones() { + assert_eq!( + shown_contact_details( + None, + Some(details("synced")), + false, + Some(details("legacy")) + ), + details("synced") + ); + } + + #[test] + fn legacy_contact_details_show_when_none_were_ever_synced() { + assert_eq!( + shown_contact_details(None, None, false, Some(details("legacy"))), + details("legacy") + ); + assert_eq!( + shown_contact_details( + None, + Some(ContactDetails::default()), + false, + Some(details("legacy")) + ), + details("legacy"), + "a contact platform-wallet never held details for shows the legacy ones" + ); + assert_eq!( + shown_contact_details(None, None, false, None), + ContactDetails::default() + ); + } + + /// SEC-002: a note the user cleared, or a contact they unhid, must not + /// come back from an old legacy document — nor be saved again by the + /// next edit, which keeps these details for every field it leaves alone. + #[test] + fn cleared_details_do_not_come_back_from_a_legacy_document() { + let legacy = ContactDetails { + nickname: None, + note: Some("old".into()), + hidden: true, + }; + assert_eq!( + shown_contact_details( + None, + Some(ContactDetails::default()), + true, + Some(legacy.clone()) + ), + ContactDetails::default() + ); + assert_eq!( + shown_contact_details(None, None, true, Some(legacy)), + ContactDetails::default() + ); + } + + /// Unreadable legacy details mark a contact unreadable only while they + /// stand in for its details, exactly when `shown_contact_details` shows + /// them. + #[test] + fn legacy_details_are_shown_only_when_nothing_newer_holds_details() { + let empty = ContactDetails::default(); + let note = details("note"); + for (published, local, synced_before) in [ + (None, None, false), + (None, Some(&empty), false), + (None, Some(¬e), false), + (None, None, true), + (None, Some(&empty), true), + (None, Some(¬e), true), + (Some(&empty), None, false), + (Some(¬e), None, false), + (Some(¬e), Some(¬e), true), + ] { + let legacy = details("legacy"); + assert_eq!( + legacy_details_shown(published, local, synced_before), + shown_contact_details( + published.cloned(), + local.cloned(), + synced_before, + Some(legacy.clone()) + ) == legacy, + "{published:?} {local:?} {synced_before}" + ); + } + } + + #[test] + fn only_non_empty_synced_details_are_recorded_as_synced() { + assert!(holds_details(None, Some(&details("note")))); + assert!(!holds_details(None, Some(&ContactDetails::default()))); + assert!(!holds_details(None, None)); + } + + /// SEC-003: Platform's DIP-0015 document is the latest saved state from + /// any device, so it wins over this device's details and legacy ones — + /// and a save keeps it for the fields it does not replace. + #[test] + fn a_published_document_wins_over_local_and_legacy_details() { + assert_eq!( + shown_contact_details( + Some(details("published")), + Some(details("local")), + true, + Some(details("legacy")) + ), + details("published") + ); + assert_eq!( + shown_contact_details( + Some(ContactDetails::default()), + None, + false, + Some(details("legacy")) + ), + ContactDetails::default(), + "details cleared on another device stay cleared" + ); + } + + #[test] + fn an_empty_published_document_counts_as_held_details() { + assert!(holds_details(Some(&ContactDetails::default()), None)); + } + + fn request(document_id: u8, owner: Identifier, to: Identifier) -> (Identifier, Document) { + use dash_sdk::dpp::document::DocumentV0; + let id = Identifier::from([document_id; 32]); + let document = Document::V0(DocumentV0 { + id, + owner_id: owner, + properties: std::collections::BTreeMap::from([( + "toUserId".to_string(), + Value::Identifier(to.to_buffer()), + )]), + ..Default::default() + }); + (id, document) + } + + /// SEC-001: after the owner withdraws their request, a reply from the + /// other person does not make them a contact. + #[test] + fn a_reply_to_a_withdrawn_request_is_not_a_contact() { + let owner = Identifier::from([1; 32]); + let bob = Identifier::from([2; 32]); + let carol = Identifier::from([3; 32]); + let incoming = [request(10, bob, owner), request(11, carol, owner)]; + let outgoing = [request(20, owner, bob), request(21, owner, carol)]; + + let contacts = mutual_contacts(&incoming, &outgoing, |peer| *peer == bob); + + assert_eq!(contacts, HashSet::from([carol])); + } /// Known-answer vectors generated independently with Python /// `cryptography` 46 (OpenSSL). They pin DIP-15 interoperability with other diff --git a/src/backend_task/dashpay/errors.rs b/src/backend_task/dashpay/errors.rs index a8561ed0c..c970ca4d0 100644 --- a/src/backend_task/dashpay/errors.rs +++ b/src/backend_task/dashpay/errors.rs @@ -66,13 +66,31 @@ pub enum DashPayError { #[error("The contact request could not be verified. Please check the details and try again.")] ValidationFailed { errors: Vec }, - // Auto Accept Proof Errors - #[error("The QR code format is not recognized. Please scan a valid contact QR code.")] - InvalidQrCode { reason: String }, - + // Contact QR code (DIP-0015 auto-accept) errors #[error("This QR code has expired. Please ask for a new one.")] QrCodeExpired { expired_at: u64, current_time: u64 }, + /// Contact QR codes are built from the identity's wallet, which an + /// identity added without its wallet does not have here. + #[error( + "Contact QR codes can be created only for an identity loaded from its wallet. Load this identity from the wallet that created it, then try again." + )] + ContactQrIdentityNotFromWallet, + + /// The secret seam lent something other than the wallet's recovery + /// phrase for the identity's wallet. + #[error("Unlock the wallet for this identity, then create the contact QR code again.")] + ContactQrWalletSeedUnavailable, + + /// platform-wallet could not build the contact QR code. + #[error( + "The contact QR code could not be created. Make sure this identity has a username, then try again." + )] + ContactQrBuildFailed { + #[source] + source: std::sync::Arc, + }, + // Network/SDK Errors #[error("Network connection failed. Please check your internet connection and retry.")] NetworkError, @@ -177,7 +195,6 @@ impl DashPayError { matches!( self, DashPayError::UsernameResolutionFailed { .. } - | DashPayError::InvalidQrCode { .. } | DashPayError::QrCodeExpired { .. } | DashPayError::ValidationFailed { .. } | DashPayError::AccountLabelTooLong { .. } diff --git a/src/backend_task/error.rs b/src/backend_task/error.rs index e2f503b49..22a8d3b0e 100644 --- a/src/backend_task/error.rs +++ b/src/backend_task/error.rs @@ -146,20 +146,6 @@ impl TokenOperationKind { } } -/// Why an existing DashPay `contactInfo` payload could not be preserved. -#[derive(Debug, Error)] -pub enum ContactInfoReadError { - /// The private payload was present with a shape this client does not understand. - #[error("contactInfo privateData has an unexpected type")] - UnexpectedPrivateDataType, - /// The private payload was present but could not be decrypted with its derived key. - #[error("contactInfo privateData decryption failed")] - DecryptFailed, - /// Decryption succeeded, but the plaintext is not a format this client understands. - #[error("contactInfo privateData deserialization failed")] - DeserializeFailed, -} - /// Typed failures while restoring persisted Core transaction history. #[derive(Debug, Error)] pub enum WalletTransactionHistoryError { @@ -1535,6 +1521,50 @@ pub enum TaskError { source: crate::wallet_backend::KvAdapterError, }, + /// A decline or a withdrawal, which only change this device, could not be + /// recorded here; the request would be listed again on reload. + #[error("Could not save this change on this device. Nothing was sent to the network. Try again.")] + DashPayRequestDecisionNotRecorded { + #[source] + source: crate::wallet_backend::KvAdapterError, + }, + + /// The details saved for a contact could not be read, and a save would + /// keep some of them: it would publish them as empty. Nothing was saved. + #[error( + "The details saved for this contact could not be read, so nothing was changed. Unhide the contact in the Contacts tab to replace them, then edit it." + )] + DashPayContactDetailsUnreadable, + + /// A contact-details save that stayed on this device, because publishing + /// waits for a second contact, could not record which details this device + /// holds; on reload the older details would show again. + #[error("Could not finish saving your contact details on this device. Try saving them again.")] + DashPayContactDetailsNotRecorded { + #[source] + source: crate::wallet_backend::KvAdapterError, + }, + + /// A DashPay record this device keeps (which contact details it holds, + /// which requests were withdrawn) could not be read, so an action that + /// depends on it cannot tell what to do. + #[error("Could not read your DashPay records on this device. Try again in a moment.")] + DashPayLocalStateRead { + #[source] + source: crate::wallet_backend::KvAdapterError, + }, + + /// A contact request was published, but this device could not stop + /// hiding the person it was sent to (an earlier decline or withdrawal). + /// Sending the request again finishes the update without publishing. + #[error( + "Your contact request was sent, but this device could not update your contacts. Send the request to this person again to finish." + )] + DashPayContactRequestSentNotUpdated { + #[source] + source: Box, + }, + /// A private contact note exceeds the application's byte limit. #[error("This note is too long. Shorten it to save it.")] DashPayContactNoteTooLong { @@ -1549,15 +1579,26 @@ pub enum TaskError { source: Box, }, - /// An existing contact's encrypted details could not be read safely. - #[error( - "Your saved contact details could not be read, so no changes were made. Use a compatible DashPay client, or try again and confirm replacing the saved details when asked." - )] - DashPayContactInfoRead { + /// Publishing contact details through platform-wallet failed. + #[error("Your contact details could not be saved. Check your connection, then try again.")] + DashPayContactInfoWriteFailed { #[source] - source: ContactInfoReadError, + source: std::sync::Arc, }, + /// Saving contact details needs the identity's index in its wallet, which + /// an identity added without its wallet does not have. + #[error( + "Contact details can be saved only for an identity loaded from its wallet. Load this identity from the wallet that created it, then try again." + )] + ContactInfoIdentityNotFromWallet, + + /// Contact details are kept only for established contacts. + #[error( + "You can save details only for people in your contacts. Wait until they accept your contact request, then try again." + )] + ContactInfoContactNotEstablished, + /// A direct contact-details update failed. The identity/contact envelope /// lets screens correlate a delayed failure with the exact pending write. #[error("{source}")] @@ -5483,15 +5524,11 @@ mod tests { #[test] fn a_contact_info_action_failure_shows_the_underlying_reason_to_the_user() { - let cause = TaskError::DashPayContactInfoRead { - source: ContactInfoReadError::DeserializeFailed, - }; + let cause = TaskError::ContactInfoContactNotEstablished; let wrapped = TaskError::DashPayContactInfoActionFailed { identity_id: Identifier::from([6; 32]), contact_id: Identifier::from([7; 32]), - source: Box::new(TaskError::DashPayContactInfoRead { - source: ContactInfoReadError::DeserializeFailed, - }), + source: Box::new(TaskError::ContactInfoContactNotEstablished), }; assert_eq!(wrapped.to_string(), cause.to_string()); diff --git a/src/backend_task/mod.rs b/src/backend_task/mod.rs index f02bde1b2..7d60ab0e9 100644 --- a/src/backend_task/mod.rs +++ b/src/backend_task/mod.rs @@ -420,6 +420,7 @@ impl BackendTask { | DashPayTask::LoadContacts { .. } | DashPayTask::LoadContactsOffline { .. } | DashPayTask::LoadContactRequests { .. } + | DashPayTask::LoadContactDetails { .. } | DashPayTask::FetchContactProfile { .. } | DashPayTask::FetchAvatar { .. } | DashPayTask::SearchProfiles { .. } @@ -473,6 +474,11 @@ pub enum BackendTaskContext { identity_id: Identifier, contact_id: Identifier, }, + /// A read of the details shown for one contact. + DashPayContactDetailsLoad { + identity_id: Identifier, + contact_id: Identifier, + }, /// A read of an identity's contacts or contact requests. DashPayContactsLoad { network: Network, @@ -709,6 +715,17 @@ impl BackendTaskContext { } } + /// Identify a contact-details read through dispatch wrappers. + pub(crate) fn dashpay_contact_details_target(&self) -> Option<(Identifier, Identifier)> { + match self.operation() { + Self::DashPayContactDetailsLoad { + identity_id, + contact_id, + } => Some((*identity_id, *contact_id)), + _ => None, + } + } + pub(crate) fn dashpay_profile_update_identity(&self) -> Option { match self.operation() { Self::DashPayProfileUpdate(identity_id) => Some(*identity_id), @@ -858,6 +875,13 @@ impl From<&BackendTask> for BackendTaskContext { identity_id: identity.identity.id(), kind: crate::model::dashpay::ContactsLoadKind::Requests, }, + DashPayTask::LoadContactDetails { + identity, + contact_id, + } => Self::DashPayContactDetailsLoad { + identity_id: identity.identity.id(), + contact_id: *contact_id, + }, DashPayTask::UpdateProfile { identity, .. } => { Self::DashPayProfileUpdate(identity.identity.id()) } @@ -1075,11 +1099,20 @@ pub enum BackendTaskSuccessResult { request_id: Identifier, contact_id: Identifier, }, + /// The details shown for one contact; see `DashPayTask::LoadContactDetails`. + DashPayContactDetails { + identity: Identifier, + contact_id: Identifier, + details: crate::model::dashpay::ContactDetails, + }, DashPayContactInfoUpdated { /// Identity that owns the encrypted `contactInfo` document. identity: Identifier, /// Contact whose private details were updated. contact_id: Identifier, + /// Whether the details reached Platform. `false` when they are saved on + /// this device only, until the identity has two contacts (DIP-0015). + published: bool, }, DashPayPaymentSent(String, String, u64), // (recipient, address, amount in duffs) /// Result of a [`FetchAvatar`](crate::backend_task::dashpay::DashPayTask::FetchAvatar): @@ -1101,9 +1134,10 @@ pub enum BackendTaskSuccessResult { /// fire; the app responds by calling /// [`queue_all_wallets_identity_discovery`](crate::context::AppContext::queue_all_wallets_identity_discovery). PlatformReadyDiscoverIdentities, - /// Auto-accept contact QR payload, ready to render. The proof is built - /// through the JIT chokepoint in the backend so the UI never touches a seed. - DashPayAutoAcceptQrCode(String), + /// Contact QR code (DIP-0015 auto-accept), ready to render. The key comes + /// from the wallet seed through the secret seam in the backend, so the UI + /// never touches a seed; `Debug` hides the code, which carries that key. + DashPayAutoAcceptQrCode(crate::model::dashpay_contact_qr::ContactQrUri), GeneratedZKProof(ProofDataOutput), VerifiedZKProof(bool, ProofDataOutput), GeneratedReceiveAddress { @@ -2819,9 +2853,9 @@ mod tests { /// its stored balance is read back after the task; reads name nobody. #[test] fn paid_tasks_name_the_identity_that_pays_for_them() { - use crate::backend_task::dashpay::auto_accept_proof::AutoAcceptProofData; use crate::backend_task::tokens::TokenContractParams; - use crate::model::dashpay::{ContactInfoUpdate, UnreadableContactInfoPolicy}; + use crate::model::dashpay::ContactInfoUpdate; + use crate::model::dashpay_contact_qr::ContactQrCode; use crate::model::qualified_contract::QualifiedContract; use crate::ui::tokens::tokens_screen::IdentityTokenInfo; use dash_sdk::dpp::data_contract::TokenConfiguration; @@ -2835,6 +2869,9 @@ mod tests { use dash_sdk::dpp::system_data_contracts::load_system_data_contract; use dash_sdk::dpp::version::PlatformVersion; use dash_sdk::platform::IdentityPublicKey; + use platform_wallet::wallet::identity::crypto::auto_accept::{ + encode_auto_accept_key_blob, encode_dashpay_contact_uri, + }; // Every other identity-typed field holds a different identity, so a // payer read from the wrong field fails the comparison. @@ -3082,14 +3119,14 @@ mod tests { dashpay(DashPayTask::SendContactRequestWithProof { identity: payer.clone(), signing_key: key.clone(), - to_identity_id: other, - account_label: None, - qr_auto_accept: AutoAcceptProofData { - identity_id: other, - proof_key: [0; 32], - account_reference: 0, - expires_at: 0, - }, + qr_code: ContactQrCode::parse(&encode_dashpay_contact_uri( + "bob", + &encode_auto_accept_key_blob( + &crate::test_support::keys::secret_key(), + 1_900_000_000, + ), + )) + .expect("contact QR code"), }), dashpay(DashPayTask::AcceptContactRequest { identity: payer.clone(), @@ -3098,12 +3135,10 @@ mod tests { dashpay(DashPayTask::RejectContactRequest { identity: payer.clone(), request_id: other, - unreadable: UnreadableContactInfoPolicy::Abort, }), dashpay(DashPayTask::CancelContactRequest { identity: payer.clone(), request_id: other, - unreadable: UnreadableContactInfoPolicy::Abort, }), dashpay(DashPayTask::UpdateContactInfo { identity: payer.clone(), @@ -3128,6 +3163,10 @@ mod tests { dashpay(DashPayTask::LoadProfile { identity: payer.clone(), }), + dashpay(DashPayTask::LoadContactDetails { + identity: payer.clone(), + contact_id: other, + }), dashpay(DashPayTask::SendPaymentToContact { identity: payer.clone(), contact_id: other, @@ -3358,7 +3397,6 @@ mod tests { #[test] fn dashpay_request_id_extracts_only_the_three_contact_actions() { use crate::backend_task::dashpay::DashPayTask; - use crate::model::dashpay::UnreadableContactInfoPolicy; let request_id = Identifier::from([0x11; 32]); let dashpay = |t: DashPayTask| BackendTask::DashPayTask(Box::new(t)); @@ -3374,7 +3412,6 @@ mod tests { dashpay_request_id(&dashpay(DashPayTask::RejectContactRequest { identity: qualified_identity(1), request_id, - unreadable: UnreadableContactInfoPolicy::Abort, })), Some(request_id) ); @@ -3382,7 +3419,6 @@ mod tests { dashpay_request_id(&dashpay(DashPayTask::CancelContactRequest { identity: qualified_identity(1), request_id, - unreadable: UnreadableContactInfoPolicy::Abort, })), Some(request_id) ); diff --git a/src/context/contact_info_writes.rs b/src/context/contact_info_writes.rs index 8d6e17c99..59cd31067 100644 --- a/src/context/contact_info_writes.rs +++ b/src/context/contact_info_writes.rs @@ -14,22 +14,30 @@ pub(crate) struct ContactInfoWrites { impl ContactInfoWrites { /// Hold through the network read, merge and confirmed document write. pub(crate) async fn acquire(&self, owner: Identifier) -> OwnedMutexGuard<()> { - let gate = { - let mut owners = self - .owners - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - owners.retain(|_, gate| gate.strong_count() > 0); - match owners.get(&owner).and_then(Weak::upgrade) { - Some(gate) => gate, - None => { - let gate = Arc::new(AsyncMutex::new(())); - owners.insert(owner, Arc::downgrade(&gate)); - gate - } + self.gate(owner).lock_owned().await + } + + /// [`Self::acquire`] without waiting: `None` while a write holds it. + pub(crate) fn try_acquire(&self, owner: Identifier) -> Option> { + self.gate(owner).try_lock_owned().ok() + } + + /// The owner's gate. The map's std mutex is released on return, never + /// held across an await. + fn gate(&self, owner: Identifier) -> Arc> { + let mut owners = self + .owners + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + owners.retain(|_, gate| gate.strong_count() > 0); + match owners.get(&owner).and_then(Weak::upgrade) { + Some(gate) => gate, + None => { + let gate = Arc::new(AsyncMutex::new(())); + owners.insert(owner, Arc::downgrade(&gate)); + gate } - }; - gate.lock_owned().await + } } } diff --git a/src/context/mod.rs b/src/context/mod.rs index 01d8501fe..7f6e2030e 100644 --- a/src/context/mod.rs +++ b/src/context/mod.rs @@ -1,5 +1,6 @@ pub mod connection_status; mod contact_info_writes; +pub(crate) use contact_info_writes::ContactInfoWrites; mod contested_names_db; mod contract_token_db; mod dapi_addresses; diff --git a/src/model/dashpay.rs b/src/model/dashpay.rs index 7e6f1c4e5..f02fe1893 100644 --- a/src/model/dashpay.rs +++ b/src/model/dashpay.rs @@ -58,6 +58,16 @@ pub fn validate_contact_note(note: &str) -> Result<(), ContactNoteTooLong> { Ok(()) } +/// DIP-0015 publishes contact details only once the owner has this many +/// established contacts; until then a save stays on this device and is free. +pub const MIN_CONTACTS_TO_PUBLISH_DETAILS: usize = 2; + +/// Whether saving contact details publishes them to Platform, and so pays a +/// fee, for an owner with `contacts` established contacts. +pub fn contact_details_save_publishes(contacts: usize) -> bool { + contacts >= MIN_CONTACTS_TO_PUBLISH_DETAILS +} + /// The recipient (`toUserId`) of a DashPay `contactRequest` document. /// /// Returns `None` when the field is absent or does not hold a readable @@ -96,45 +106,33 @@ pub struct StoredProfile { pub updated_at: i64, } -/// What a `contactInfo` write does to the contact's accepted-accounts list. -/// -/// A `contactInfo` document is always written whole, so every write decides the -/// fate of the accounts the user has already accepted. A caller with no opinion -/// on them — unhiding a contact, renaming one — says [`Preserve`] and keeps the -/// stored list; only a caller that owns the list says [`Replace`]. -/// -/// [`Preserve`]: AcceptedAccounts::Preserve -/// [`Replace`]: AcceptedAccounts::Replace -#[derive(Debug, Clone, PartialEq, Eq, Default)] -pub enum AcceptedAccounts { - /// Keep the accounts already stored in the contact's `contactInfo`. - #[default] - Preserve, - /// Overwrite the stored accounts with exactly these. - Replace(Vec), -} - -/// What a whole-document write does to one optional contact detail. +/// What a contact details write does to one optional detail. #[derive(Debug, Clone, PartialEq, Eq, Default)] pub enum ContactInfoField { - /// Keep the value already stored in the encrypted payload. + /// Keep the value currently saved for the contact. #[default] Preserve, /// Store this value, including `None` when clearing an optional field. Replace(T), } -/// How a write handles a present encrypted payload this client cannot read. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub enum UnreadableContactInfoPolicy { - /// Abort before overwriting data this client cannot preserve. - #[default] - Abort, - /// Replace the unreadable payload after the user explicitly confirms. - Overwrite, +/// The private details an identity keeps about one contact: its nickname, +/// note, and whether it is hidden. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct ContactDetails { + pub nickname: Option, + pub note: Option, + pub hidden: bool, } -/// Explicit field-by-field intent for a whole encrypted `contactInfo` write. +impl ContactDetails { + /// Whether nothing is saved for the contact. + pub fn is_empty(&self) -> bool { + self.nickname.is_none() && self.note.is_none() && !self.hidden + } +} + +/// Explicit field-by-field intent for a contact details write. #[derive(Debug, Clone, PartialEq, Eq)] pub struct ContactInfoUpdate { /// Nickname update intent. @@ -143,10 +141,6 @@ pub struct ContactInfoUpdate { pub note: ContactInfoField>, /// Visibility update intent. pub display_hidden: ContactInfoField, - /// Accepted-account update intent. - pub accepted_accounts: AcceptedAccounts, - /// Policy for a present payload that cannot be read. - pub unreadable: UnreadableContactInfoPolicy, } impl ContactInfoUpdate { @@ -156,8 +150,6 @@ impl ContactInfoUpdate { nickname: ContactInfoField::Preserve, note: ContactInfoField::Preserve, display_hidden: ContactInfoField::Replace(display_hidden), - accepted_accounts: AcceptedAccounts::Preserve, - unreadable: UnreadableContactInfoPolicy::Abort, } } @@ -175,21 +167,62 @@ impl ContactInfoUpdate { nickname: Option, note: Option, display_hidden: bool, - accepted_accounts: Vec, ) -> Self { Self { nickname: ContactInfoField::Replace(nickname), note: ContactInfoField::Replace(note), display_hidden: ContactInfoField::Replace(display_hidden), - accepted_accounts: AcceptedAccounts::Replace(accepted_accounts), - unreadable: UnreadableContactInfoPolicy::Abort, } } - /// Allow replacement of unreadable stored data after explicit confirmation. - pub fn overwrite_unreadable(mut self) -> Self { - self.unreadable = UnreadableContactInfoPolicy::Overwrite; - self + /// Whether the update keeps the saved nickname or note. + pub fn keeps_text(&self) -> bool { + matches!(self.nickname, ContactInfoField::Preserve) + || matches!(self.note, ContactInfoField::Preserve) + } + + /// Whether the update only unhides the contact. + pub fn unhides_only(&self) -> bool { + matches!(self.nickname, ContactInfoField::Preserve) + && matches!(self.note, ContactInfoField::Preserve) + && matches!(self.display_hidden, ContactInfoField::Replace(false)) + } + + /// Replace only the fields that differ between `opened`, the details an + /// editor started from, and `edited`, what the user left in it; every + /// other field keeps the latest saved value. + /// + /// An editor that starts from a local copy must save this way: replacing + /// a field the user did not touch would overwrite a newer value saved + /// from another device with the local copy's older one. + pub fn edits(opened: &ContactDetails, edited: ContactDetails) -> Self { + fn field(opened: &T, edited: T) -> ContactInfoField { + if *opened == edited { + ContactInfoField::Preserve + } else { + ContactInfoField::Replace(edited) + } + } + Self { + nickname: field(&opened.nickname, edited.nickname), + note: field(&opened.note, edited.note), + display_hidden: field(&opened.hidden, edited.hidden), + } + } + + /// The details to save: `current` with this update's replacements. + pub fn apply_to(&self, current: ContactDetails) -> ContactDetails { + fn pick(field: &ContactInfoField, current: T) -> T { + match field { + ContactInfoField::Preserve => current, + ContactInfoField::Replace(value) => value.clone(), + } + } + ContactDetails { + nickname: pick(&self.nickname, current.nickname), + note: pick(&self.note, current.note), + hidden: pick(&self.display_hidden, current.hidden), + } } } @@ -473,6 +506,14 @@ mod tests { Identifier::from_bytes(&[byte; 32]).expect("32-byte identifier") } + #[test] + fn contact_details_publish_from_two_contacts() { + assert!(!contact_details_save_publishes(0)); + assert!(!contact_details_save_publishes(1)); + assert!(contact_details_save_publishes(2)); + assert!(contact_details_save_publishes(3)); + } + /// A `contactRequest`-shaped document. `to` of `None` omits `toUserId` /// entirely, modelling a malformed document. fn request_doc(to: Option) -> Document { @@ -531,15 +572,74 @@ mod tests { ContactInfoField::Replace(Some("Met at the meetup".into())) ); assert_eq!(update.nickname, ContactInfoField::Preserve); - assert_eq!(update.accepted_accounts, AcceptedAccounts::Preserve); assert_eq!(update.display_hidden, ContactInfoField::Preserve); - assert_eq!(update.unreadable, UnreadableContactInfoPolicy::Abort); let cleared = ContactInfoUpdate::note(None); assert_eq!(cleared.note, ContactInfoField::Replace(None)); assert_eq!(cleared.display_hidden, ContactInfoField::Preserve); } + /// A write keeps every detail it does not replace. + #[test] + fn an_update_keeps_the_details_it_does_not_replace() { + let current = ContactDetails { + nickname: Some("Bao".into()), + note: Some("old".into()), + hidden: true, + }; + assert_eq!( + ContactInfoUpdate::note(Some("new".into())).apply_to(current.clone()), + ContactDetails { + note: Some("new".into()), + ..current.clone() + } + ); + assert_eq!( + ContactInfoUpdate::visibility(false).apply_to(current.clone()), + ContactDetails { + hidden: false, + ..current.clone() + } + ); + assert_eq!( + ContactInfoUpdate::replace_all(None, None, false).apply_to(current), + ContactDetails::default() + ); + } + + /// Only the fields an editor changed are replaced. + #[test] + fn edits_replace_only_the_changed_fields() { + let opened = ContactDetails { + nickname: Some("Bao".into()), + note: None, + hidden: false, + }; + assert_eq!( + ContactInfoUpdate::edits(&opened, opened.clone()), + ContactInfoUpdate { + nickname: ContactInfoField::Preserve, + note: ContactInfoField::Preserve, + display_hidden: ContactInfoField::Preserve, + } + ); + assert_eq!( + ContactInfoUpdate::edits( + &opened, + ContactDetails { + nickname: None, + note: Some("n".into()), + hidden: false, + } + ), + ContactInfoUpdate { + nickname: ContactInfoField::Replace(None), + note: ContactInfoField::Replace(Some("n".into())), + display_hidden: ContactInfoField::Preserve, + } + ); + } + #[test] fn contact_request_recipient_reads_the_to_user_id() { assert_eq!( diff --git a/src/model/dashpay_contact_qr.rs b/src/model/dashpay_contact_qr.rs new file mode 100644 index 000000000..c5c1e57c7 --- /dev/null +++ b/src/model/dashpay_contact_qr.rs @@ -0,0 +1,316 @@ +//! DashPay contact QR codes (DIP-0015 `dash:?du=&dapk=`). +//! +//! The format, the key blob and the proof all come from platform-wallet's +//! `auto_accept` module; this type only validates a scanned code once and +//! carries the result to the backend. The `dapk` key is the QR owner's +//! auto-accept key, a short-lived bearer credential: it lets the scanner sign +//! the `autoAcceptProof` of its contact request, nothing else. + +use std::sync::Arc; + +use dash_sdk::dpp::secp256k1::SecretKey; +use dash_sdk::platform::Identifier; +use platform_wallet::error::PlatformWalletError; +use platform_wallet::wallet::identity::crypto::auto_accept::{ + decode_auto_accept_key_blob, parse_dashpay_contact_uri, sign_auto_accept_proof, +}; + +/// A scanned contact QR code that passed validation. +#[derive(Clone, PartialEq)] +pub struct ContactQrCode { + username: String, + key: SecretKey, + expires_at: u32, +} + +/// Why a scanned text is not a usable contact QR code. +#[derive(Debug, Clone, thiserror::Error)] +pub enum ContactQrCodeError { + /// The text is not a DIP-0015 contact code, or its key cannot be read. + /// Codes from older Dash Evo Tool versions (`dash:?di=…`) land here. + #[error( + "This is not a DashPay contact QR code. Ask your contact for a new code and try again." + )] + Unreadable { + #[source] + source: Arc, + }, + /// The code's `du` is not a DPNS label (`[a-zA-Z0-9-]`, 3 to 63 + /// characters, no leading or trailing hyphen), with or without `.dash`. + #[error( + "This QR code does not contain a valid Dash username. Ask your contact for a new code and try again." + )] + NotADashUsername, +} + +impl ContactQrCode { + /// Parse and validate a scanned or pasted contact QR code. + pub fn parse(text: &str) -> Result { + let unreadable = |source| ContactQrCodeError::Unreadable { + source: Arc::new(source), + }; + let (username, key_blob) = parse_dashpay_contact_uri(text.trim()).map_err(unreadable)?; + let username = dpns_label(&username) + .ok_or(ContactQrCodeError::NotADashUsername)? + .to_string(); + let (key, expires_at) = decode_auto_accept_key_blob(&key_blob).map_err(unreadable)?; + Ok(Self { + username, + key, + expires_at, + }) + } + + /// The QR owner's Dash username, without the `.dash` suffix. + pub fn username(&self) -> &str { + &self.username + } + + /// The username in its full `.dash` form, so a lookup always resolves it + /// through DPNS and never mistakes it for an identity ID. + pub fn full_username(&self) -> String { + format!("{}.dash", self.username) + } + + /// The Unix time (seconds) after which the code no longer auto-accepts. + pub fn expires_at(&self) -> u32 { + self.expires_at + } + + /// Whether the code has expired at `now_secs` (Unix seconds). + pub fn is_expired_at(&self, now_secs: u64) -> bool { + now_secs > u64::from(self.expires_at) + } + + /// The `autoAcceptProof` for a contact request from `sender` to + /// `recipient` (the QR owner) carrying `account_reference`. + pub fn sign_proof( + &self, + sender: &Identifier, + recipient: &Identifier, + account_reference: u32, + ) -> Vec { + sign_auto_accept_proof( + &self.key, + sender, + recipient, + account_reference, + self.expires_at, + ) + } +} + +/// The DPNS label `username` names, with an optional `.dash` suffix +/// (any case) removed; `None` unless the label is a valid DPNS label. +fn dpns_label(username: &str) -> Option<&str> { + const SUFFIX: &str = ".dash"; + let label = match username.len().checked_sub(SUFFIX.len()) { + Some(at) + if username.is_char_boundary(at) && username[at..].eq_ignore_ascii_case(SUFFIX) => + { + &username[..at] + } + _ => username, + }; + (crate::model::dpns::validate_dpns_name(label) + == crate::model::dpns::DpnsNameValidationResult::Valid) + .then_some(label) +} + +/// A contact QR code built for this app's identity. The text carries the +/// owner's auto-accept key, so `Debug` never prints it. +#[derive(Clone, PartialEq, Eq)] +pub struct ContactQrUri(String); + +impl ContactQrUri { + pub fn new(uri: String) -> Self { + Self(uri) + } + + /// The code's text, to render as a QR image or copy. + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Debug for ContactQrUri { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("ContactQrUri()") + } +} + +impl std::fmt::Debug for ContactQrCode { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ContactQrCode") + .field("username", &self.username) + .field("key", &"") + .field("expires_at", &self.expires_at) + .finish() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use dash_sdk::dpp::secp256k1::PublicKey; + use platform_wallet::wallet::identity::crypto::auto_accept::{ + encode_auto_accept_key_blob, encode_dashpay_contact_uri, + verify_auto_accept_proof_with_pubkey, + }; + + const EXPIRY: u32 = 1_900_000_000; + + fn key() -> SecretKey { + SecretKey::from_secret_bytes(rand::random()).expect("key") + } + + fn uri(username: &str, key: &SecretKey) -> String { + encode_dashpay_contact_uri(username, &encode_auto_accept_key_blob(key, EXPIRY)) + } + + /// A code platform-wallet builds parses back to its username, expiry and + /// key, and the proof it signs verifies against the owner's public key + /// for exactly that sender, recipient and account reference. + #[test] + fn a_platform_wallet_code_parses_and_signs_a_verifiable_proof() { + let key = key(); + let qr = ContactQrCode::parse(&uri("alice", &key)).expect("parse"); + assert_eq!(qr.username(), "alice"); + assert_eq!(qr.full_username(), "alice.dash"); + assert_eq!(qr.expires_at(), EXPIRY); + + let (scanner, owner) = (Identifier::from([1; 32]), Identifier::from([2; 32])); + let proof = qr.sign_proof(&scanner, &owner, 7); + let public = PublicKey::from_secret_key(&key); + assert!(verify_auto_accept_proof_with_pubkey( + &public, &proof, &scanner, &owner, 7 + )); + assert!(!verify_auto_accept_proof_with_pubkey( + &public, &proof, &scanner, &owner, 8 + )); + assert!(!verify_auto_accept_proof_with_pubkey( + &public, + &proof, + &Identifier::from([3; 32]), + &owner, + 7 + )); + } + + /// Codes from older Dash Evo Tool versions named the identity (`di=`) + /// instead of the username (`du=`) and are refused. + #[test] + fn an_old_identity_id_code_is_refused() { + let blob = encode_auto_accept_key_blob(&key(), EXPIRY); + let old = format!( + "dash:?di={}&dapk={}", + Identifier::from([9; 32]) + .to_string(dash_sdk::dpp::platform_value::string_encoding::Encoding::Base58), + dash_sdk::dpp::platform_value::string_encoding::encode( + &blob, + dash_sdk::dpp::platform_value::string_encoding::Encoding::Base58 + ) + ); + assert!(matches!( + ContactQrCode::parse(&old), + Err(ContactQrCodeError::Unreadable { .. }) + )); + } + + #[test] + fn malformed_codes_are_refused() { + for text in [ + "", + "hello", + "http:?du=alice&dapk=abc", + "dash:?du=alice", + "dash:?du=alice&dapk=0OIl", + "dash:?du=alice&dapk=abc", + ] { + assert!( + matches!( + ContactQrCode::parse(text), + Err(ContactQrCodeError::Unreadable { .. }) + ), + "{text}" + ); + } + } + + /// Only a DPNS label (`[a-zA-Z0-9-]`, 3 to 63 characters) is accepted, so + /// a hostile code cannot smuggle bidi overrides, invisible or control + /// characters, or a huge string into the screen and the name lookup. + #[test] + fn a_code_without_a_dash_username_is_refused() { + let too_long = "a".repeat(64); + for username in [ + "", + " ", + " alice", + "ab", + "-alice", + "alice-", + "alice.com", + "a.b.dash", + "ali\u{202E}ce", + "ali\u{200B}ce", + "ali\nce", + "alice\u{0}", + "äli", + too_long.as_str(), + ] { + assert!( + matches!( + ContactQrCode::parse(&uri(username, &key())), + Err(ContactQrCodeError::NotADashUsername) + ), + "{username:?}" + ); + } + } + + #[test] + fn the_longest_dpns_label_is_accepted() { + let longest = "a".repeat(63); + let qr = ContactQrCode::parse(&uri(&longest, &key())).expect("parse"); + assert_eq!(qr.username(), longest); + } + + #[test] + fn a_full_username_is_read_as_its_label() { + for username in ["alice.dash", "alice.DASH"] { + let qr = ContactQrCode::parse(&uri(username, &key())).expect("parse"); + assert_eq!(qr.username(), "alice"); + assert_eq!(qr.full_username(), "alice.dash"); + } + } + + /// The built code reaches results and logs only through `ContactQrUri`, + /// whose `Debug` hides it. + #[test] + fn a_built_code_is_hidden_from_debug_output() { + let text = uri("alice", &key()); + let built = ContactQrUri::new(text.clone()); + assert_eq!(built.as_str(), text); + let debug = format!("{built:?}"); + assert!(debug.contains("")); + assert!(!debug.contains("dapk")); + } + + #[test] + fn expiry_is_inclusive_of_the_last_second() { + let qr = ContactQrCode::parse(&uri("alice", &key())).expect("parse"); + assert!(!qr.is_expired_at(u64::from(EXPIRY))); + assert!(qr.is_expired_at(u64::from(EXPIRY) + 1)); + } + + /// The bearer key never reaches logs through `Debug`. + #[test] + fn debug_output_hides_the_key() { + let key = key(); + let qr = ContactQrCode::parse(&uri("alice", &key)).expect("parse"); + let debug = format!("{qr:?}"); + assert!(debug.contains("")); + assert!(!debug.contains(&hex::encode(key.to_secret_bytes()))); + } +} diff --git a/src/model/dashpay_derivation/hd.rs b/src/model/dashpay_derivation/hd.rs index 54115c3ac..153b52bc4 100644 --- a/src/model/dashpay_derivation/hd.rs +++ b/src/model/dashpay_derivation/hd.rs @@ -1,17 +1,11 @@ use dash_sdk::dpp::dashcore::Network; use dash_sdk::dpp::dashcore::hashes::{Hash, HashEngine}; -use dash_sdk::dpp::key_wallet::bip32::{ - ChildNumber, DerivationPath, ExtendedPrivKey, ExtendedPubKey, -}; +use dash_sdk::dpp::key_wallet::bip32::{ChildNumber, ExtendedPubKey}; use dash_sdk::platform::Identifier; -use std::str::FromStr; use super::DerivationError; use super::dip14::derive_dashpay_incoming_xpub_dip14; -/// DashPay auto-accept proof feature index - use the constant from dip9 if available -const DASHPAY_AUTO_ACCEPT_FEATURE: u32 = 16; - /// Derive the DashPay incoming funds extended public key for a contact relationship /// Path: m/9'/coin'/15'/account'/(sender_id)/(recipient_id) /// @@ -75,30 +69,6 @@ pub fn generate_contact_xpub_data( Ok((parent_fingerprint, chain_code, public_key_bytes)) } -/// Derive auto-accept proof key according to DIP-0015 -/// Path: m/9'/coin'/16'/timestamp' -pub fn derive_auto_accept_key( - master_seed: &[u8], - network: Network, - timestamp: u32, -) -> Result { - use crate::model::wallet::coin_type_for_network; - - // Create extended private key from seed - let master_xprv = ExtendedPrivKey::new_master(network, master_seed)?; - - // Build derivation path: m/9'/coin'/16'/timestamp' - let coin_type = coin_type_for_network(network); - let path = DerivationPath::from_str(&format!( - "m/9'/{coin_type}'/{DASHPAY_AUTO_ACCEPT_FEATURE}'/{timestamp}'" - ))?; - - // Derive the key - let auto_accept_key = master_xprv.derive_priv(&path)?; - - Ok(auto_accept_key) -} - /// Calculate account reference as specified in DIP-0015 pub fn calculate_account_reference( sender_secret_key: &[u8], @@ -132,6 +102,8 @@ pub fn calculate_account_reference( #[cfg(test)] mod tests { use super::*; + use dash_sdk::dpp::key_wallet::bip32::{DerivationPath, ExtendedPrivKey}; + use std::str::FromStr; #[test] fn test_dashpay_derivation_path() { @@ -221,40 +193,6 @@ mod tests { ); } - #[test] - fn test_auto_accept_key_derivation() { - // Test auto-accept key derivation - let network = Network::Testnet; - let master_seed = crate::test_support::keys::seed(); - let timestamp = 1700000000u32; - - let key = derive_auto_accept_key(&master_seed, network, timestamp) - .expect("Should derive auto-accept key"); - - // Verify the key was derived correctly - assert_eq!(key.network, network); - assert_eq!(key.depth, 4); // m/9'/1'/16'/timestamp' on testnet = depth 4 - } - - #[test] - fn test_auto_accept_key_different_timestamps() { - // Different timestamps should produce different keys - let network = Network::Testnet; - let master_seed = crate::test_support::keys::seed(); - - let key1 = - derive_auto_accept_key(&master_seed, network, 1700000000).expect("Should derive key 1"); - let key2 = - derive_auto_accept_key(&master_seed, network, 1700000001).expect("Should derive key 2"); - - // Different timestamps should produce different keys - assert_ne!( - key1.private_key.to_bytes(), - key2.private_key.to_bytes(), - "Different timestamps should produce different keys" - ); - } - #[test] fn test_generate_contact_xpub_data() { // Test generating contact xpub data diff --git a/src/model/dashpay_derivation/mod.rs b/src/model/dashpay_derivation/mod.rs index 5ed877885..b8d8bb6d5 100644 --- a/src/model/dashpay_derivation/mod.rs +++ b/src/model/dashpay_derivation/mod.rs @@ -1,15 +1,16 @@ //! Pure DashPay HD key derivation (DIP-14 / DIP-15). //! -//! Stateless derivation of contact payment keys and auto-accept proof keys -//! from a wallet seed. No `AppContext`, `Sdk`, database, or `BackendTask` +//! Stateless derivation of contact payment keys from a wallet seed. The +//! auto-accept (QR) key comes from platform-wallet; see +//! `wallet_backend::auto_accept`. No `AppContext`, `Sdk`, database, or `BackendTask` //! dependency — the single source of truth for DashPay derivation math. pub mod dip14; pub mod hd; pub use hd::{ - calculate_account_reference, derive_auto_accept_key, derive_dashpay_incoming_xpub, - derive_payment_address, generate_contact_xpub_data, + calculate_account_reference, derive_dashpay_incoming_xpub, derive_payment_address, + generate_contact_xpub_data, }; use thiserror::Error; diff --git a/src/model/mod.rs b/src/model/mod.rs index 8b790fd49..b354f33c8 100644 --- a/src/model/mod.rs +++ b/src/model/mod.rs @@ -5,6 +5,7 @@ pub mod avatar; pub mod backup_retention; pub mod contested_name; pub mod dashpay; +pub mod dashpay_contact_qr; pub mod dashpay_derivation; pub(crate) mod data_migration; pub mod datetime; diff --git a/src/ui/dashpay/contact_details.rs b/src/ui/dashpay/contact_details.rs index 8289eb575..91b06b2c7 100644 --- a/src/ui/dashpay/contact_details.rs +++ b/src/ui/dashpay/contact_details.rs @@ -1,15 +1,13 @@ -use crate::app::AppAction; +use crate::app::{AppAction, BackendTasksExecutionMode}; use crate::backend_task::dashpay::DashPayTask; use crate::backend_task::error::TaskError; -use crate::backend_task::{BackendTask, BackendTaskSuccessResult}; +use crate::backend_task::{BackendTask, BackendTaskContext, BackendTaskSuccessResult}; use crate::context::AppContext; use crate::context::feature_gate::FeatureGate; -use crate::model::dashpay::{AcceptedAccounts, ContactInfoField, ContactInfoUpdate}; +use crate::model::dashpay::{ContactDetails, ContactInfoField, ContactInfoUpdate}; use crate::model::fee_estimation::format_duffs_as_dash; use crate::model::qualified_identity::QualifiedIdentity; use crate::ui::components::MessageBanner; -use crate::ui::components::component_trait::Component; -use crate::ui::components::confirmation_dialog::{ConfirmationDialog, ConfirmationStatus}; use crate::ui::components::dashpay_subscreen_chooser_panel::add_dashpay_subscreen_chooser_panel; use crate::ui::components::info_popup::InfoPopup; use crate::ui::components::left_panel::add_left_panel; @@ -65,10 +63,18 @@ pub struct ContactDetailsScreen { edit_nickname: String, edit_note: String, edit_hidden: bool, + /// The details the editor opened with, so a save replaces only the + /// fields the user changed. + edit_opened: ContactDetails, loading: bool, + /// The details read is running; editing waits for it so the editor opens + /// from the published details rather than this device's copy. + details_loading: bool, + /// `contact_info`'s nickname, note and hidden flag came from the details + /// read, so a reread of this device's copy keeps them. + details_read: bool, show_info_popup: bool, needs_backend_fetch: bool, - overwrite_dialog: Option, pending_update: Option, } @@ -88,19 +94,23 @@ impl ContactDetailsScreen { edit_nickname: String::new(), edit_note: String::new(), edit_hidden: false, + edit_opened: ContactDetails::default(), loading: false, + details_loading: false, + details_read: false, show_info_popup: false, needs_backend_fetch: true, - overwrite_dialog: None, pending_update: None, }; screen.load_from_database(); screen } - /// Initialise `contact_info` from local-only data (private notes / hidden flag). - /// Public profile fields (username, display_name, avatar, bio) are populated - /// asynchronously by `FetchContactProfile` — see `display_task_result`. + /// Initialise `contact_info` from this device's copy of the nickname, note + /// and hidden flag, until `LoadContactDetails` returns the details shown + /// everywhere else. Public profile fields (username, display_name, avatar, + /// bio) are populated asynchronously by `FetchContactProfile` — see + /// `display_task_result`. fn load_from_database(&mut self) { let identity_id = self.identity.identity.id(); @@ -126,6 +136,15 @@ impl ContactDetailsScreen { Some(nickname) }; let note = if note.is_empty() { None } else { Some(note) }; + // Details read from the backend outrank this device's copy. + let (nickname, note, is_hidden) = match self.contact_info.as_ref() { + Some(existing) if self.details_read => ( + existing.nickname.clone(), + existing.note.clone(), + existing.is_hidden, + ), + _ => (nickname, note, is_hidden), + }; // Preserve any public profile fields already in `contact_info`; otherwise // start empty and let the async fetch fill them in. @@ -154,43 +173,57 @@ impl ContactDetailsScreen { }); } - /// Trigger a backend fetch to refresh contact profile data from Platform. + /// Trigger backend reads of the contact's public profile and of the + /// details shown for it (published first; see `LoadContactDetails`). fn trigger_backend_fetch(&mut self) -> AppAction { self.loading = true; + self.details_loading = true; - AppAction::BackendTask(BackendTask::DashPayTask(Box::new( - DashPayTask::FetchContactProfile { - identity: self.identity.clone(), - contact_id: self.contact_id, - }, - ))) + let task = |task| BackendTask::DashPayTask(Box::new(task)); + AppAction::BackendTasks( + vec![ + task(DashPayTask::FetchContactProfile { + identity: self.identity.clone(), + contact_id: self.contact_id, + }), + task(DashPayTask::LoadContactDetails { + identity: self.identity.clone(), + contact_id: self.contact_id, + }), + ], + BackendTasksExecutionMode::Concurrent, + ) } fn start_editing(&mut self) { + if self.details_loading { + return; + } if let Some(info) = &self.contact_info { self.edit_nickname = info.nickname.clone().unwrap_or_default(); self.edit_note = info.note.clone().unwrap_or_default(); self.edit_hidden = info.is_hidden; + self.edit_opened = ContactDetails { + nickname: info.nickname.clone(), + note: info.note.clone(), + hidden: info.is_hidden, + }; self.editing_info = true; } } fn save_contact_info(&mut self) -> AppAction { - let update = ContactInfoUpdate { - nickname: ContactInfoField::Replace(if self.edit_nickname.is_empty() { - None - } else { - Some(self.edit_nickname.clone()) - }), - note: ContactInfoField::Replace(if self.edit_note.is_empty() { - None - } else { - Some(self.edit_note.clone()) - }), - display_hidden: ContactInfoField::Replace(self.edit_hidden), - accepted_accounts: AcceptedAccounts::Preserve, - unreadable: Default::default(), - }; + let non_empty = |text: &str| (!text.is_empty()).then(|| text.to_string()); + // The editor opens from this device's copy, which can be older than + // the published details; untouched fields keep the published ones. + let update = ContactInfoUpdate::edits( + &self.edit_opened, + ContactDetails { + nickname: non_empty(&self.edit_nickname), + note: non_empty(&self.edit_note), + hidden: self.edit_hidden, + }, + ); self.pending_update = Some(update.clone()); self.loading = true; @@ -365,7 +398,10 @@ impl ContactDetailsScreen { if ui.button("Save").clicked() { action = self.save_contact_info(); } - } else if ui.button("Edit").clicked() { + } else if ui + .add_enabled(!self.details_loading, egui::Button::new("Edit")) + .clicked() + { self.start_editing(); } }); @@ -575,29 +611,6 @@ impl ScreenLike for ContactDetailsScreen { action |= island_central_panel(ui, |ui| self.render(ui)); - if let Some(dialog) = &mut self.overwrite_dialog { - match dialog.show(ui).inner.dialog_response { - Some(ConfirmationStatus::Confirmed) => { - if let Some(update) = self.pending_update.clone() { - self.loading = true; - action |= AppAction::BackendTask(BackendTask::DashPayTask(Box::new( - DashPayTask::UpdateContactInfo { - identity: self.identity.clone(), - contact_id: self.contact_id, - update: update.overwrite_unreadable(), - }, - ))); - } - self.overwrite_dialog = None; - } - Some(ConfirmationStatus::Canceled) => { - self.pending_update = None; - self.overwrite_dialog = None; - } - None => {} - } - } - // Show info popup if requested if self.show_info_popup { egui::CentralPanel::default() @@ -622,10 +635,37 @@ impl ScreenLike for ContactDetailsScreen { self.loading = false; } + fn display_backend_task_error(&mut self, context: &BackendTaskContext, _error: &TaskError) { + // Only this screen's own details read reopens the editor: a failed + // profile read must not unlock it from this device's older copy while + // the details read is still pending. A failed details read leaves that + // copy in place; a save from it still replaces only the edited fields. + if context.dashpay_contact_details_target() + == Some((self.identity.identity.id(), self.contact_id)) + { + self.details_loading = false; + } + } + fn display_task_result(&mut self, result: BackendTaskSuccessResult) { self.loading = false; match result { + BackendTaskSuccessResult::DashPayContactDetails { + identity, + contact_id, + details, + } => { + if identity == self.identity.identity.id() && contact_id == self.contact_id { + self.details_loading = false; + self.details_read = true; + if let Some(info) = &mut self.contact_info { + info.nickname = details.nickname; + info.note = details.note; + info.is_hidden = details.hidden; + } + } + } BackendTaskSuccessResult::DashPayContactProfile(Some(doc)) => { // Update contact info with fresh profile data from Platform use dash_sdk::dpp::document::DocumentV0Getters; @@ -680,14 +720,19 @@ impl ScreenLike for ContactDetailsScreen { BackendTaskSuccessResult::DashPayContactInfoUpdated { identity, contact_id, + published, } => { if identity == self.identity.identity.id() && contact_id == self.contact_id { self.commit_pending_update(); - MessageBanner::set_global( - self.app_context.egui_ctx(), - "Contact information saved.", - MessageType::Success, - ); + let (message, kind) = if published { + ("Contact information saved.", MessageType::Success) + } else { + ( + crate::ui::identity::contacts::DETAILS_SAVED_ON_THIS_DEVICE, + MessageType::Info, + ) + }; + MessageBanner::set_global(self.app_context.egui_ctx(), message, kind); } } BackendTaskSuccessResult::DashPayContactsWithInfo { @@ -732,27 +777,6 @@ impl ScreenLike for ContactDetailsScreen { fn display_task_error(&mut self, error: &TaskError) -> bool { self.loading = false; - let is_matching_read_error = matches!( - error, - TaskError::DashPayContactInfoActionFailed { - identity_id, - contact_id, - source, - } if *identity_id == self.identity.identity.id() - && *contact_id == self.contact_id - && matches!(source.as_ref(), TaskError::DashPayContactInfoRead { .. }) - ); - if is_matching_read_error && self.pending_update.is_some() { - self.overwrite_dialog = Some( - ConfirmationDialog::new( - "Replace saved contact details?", - "This contact's saved details cannot be read. Continuing will save the nickname and note shown here and clear the accepted-account settings. You cannot undo this change.", - ) - .confirm_text(Some("Replace saved details")) - .danger_mode(true), - ); - return true; - } if matches!( error, TaskError::DashPayContactInfoActionFailed { @@ -766,3 +790,173 @@ impl ScreenLike for ContactDetailsScreen { false } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::context::test_support::{bare_user_identity, test_app_context}; + use dash_sdk::dpp::dashcore::Network; + + fn dispatched_update(action: AppAction) -> ContactInfoUpdate { + match action { + AppAction::BackendTask(BackendTask::DashPayTask(task)) => match *task { + DashPayTask::UpdateContactInfo { update, .. } => update, + other => panic!("expected UpdateContactInfo, got {other:?}"), + }, + _ => panic!("expected a DashPay backend task"), + } + } + + /// This screen opens from this device's copy of the details, which can be + /// older than what another device or the Identity Hub published. Saving + /// an edited note must keep the published nickname and visibility rather + /// than republish the stale local ones. + #[test] + fn saving_one_edited_field_keeps_the_published_others() { + let dir = tempfile::tempdir().expect("temp dir"); + let context = test_app_context(dir.path()); + let identity = bare_user_identity(Identifier::from([1; 32]), Network::Testnet); + let mut screen = ContactDetailsScreen::new(context, identity, Identifier::from([2; 32])); + + screen.start_editing(); + screen.edit_note = "Met at the meetup".to_string(); + let update = dispatched_update(screen.save_contact_info()); + + assert_eq!( + update, + ContactInfoUpdate { + nickname: ContactInfoField::Preserve, + note: ContactInfoField::Replace(Some("Met at the meetup".into())), + display_hidden: ContactInfoField::Preserve, + } + ); + } + + /// The editor opens from the details shown for the contact everywhere + /// else (published first), read by the backend when the screen opens, + /// not from this device's older copy. It stays closed until that read + /// returns. + #[test] + fn the_editor_opens_from_the_published_details() { + let dir = tempfile::tempdir().expect("temp dir"); + let context = test_app_context(dir.path()); + let owner = Identifier::from([1; 32]); + let contact = Identifier::from([2; 32]); + let identity = bare_user_identity(owner, Network::Testnet); + let mut screen = ContactDetailsScreen::new(context, identity, contact); + + let AppAction::BackendTasks(tasks, _) = screen.trigger_backend_fetch() else { + panic!("expected the profile and details reads"); + }; + assert!(tasks.iter().any(|task| matches!( + task, + BackendTask::DashPayTask(task) if matches!( + task.as_ref(), + DashPayTask::LoadContactDetails { contact_id, .. } if *contact_id == contact + ) + ))); + screen.start_editing(); + assert!( + !screen.editing_info, + "the editor waits for the details read" + ); + + screen.display_task_result(BackendTaskSuccessResult::DashPayContactDetails { + identity: owner, + contact_id: contact, + details: ContactDetails { + nickname: Some("Bao".into()), + note: Some("published".into()), + hidden: true, + }, + }); + // A refresh rereads this device's copy, which must not replace them. + screen.refresh(); + screen.start_editing(); + + assert!(screen.editing_info); + assert_eq!(screen.edit_nickname, "Bao"); + assert_eq!(screen.edit_note, "published"); + assert!(screen.edit_hidden); + } + + /// A failed profile read does not open the editor while the details read + /// is still pending; only the details read's own failure does, leaving + /// this device's copy in place. + #[test] + fn a_failed_profile_read_keeps_the_editor_closed_until_the_details_read_ends() { + let dir = tempfile::tempdir().expect("temp dir"); + let context = test_app_context(dir.path()); + let owner = Identifier::from([1; 32]); + let contact = Identifier::from([2; 32]); + let identity = bare_user_identity(owner, Network::Testnet); + let mut screen = ContactDetailsScreen::new(context, identity, contact); + + let AppAction::BackendTasks(tasks, _) = screen.trigger_backend_fetch() else { + panic!("expected the profile and details reads"); + }; + let is_details_read = |task: &BackendTask| { + matches!( + task, + BackendTask::DashPayTask(task) + if matches!(task.as_ref(), DashPayTask::LoadContactDetails { .. }) + ) + }; + let profile = tasks + .iter() + .find(|task| !is_details_read(task)) + .expect("profile read"); + let details = tasks + .iter() + .find(|task| is_details_read(task)) + .expect("details read"); + // What AppState delivers for a failure the screen does not handle. + let fail = |screen: &mut ContactDetailsScreen, task: &BackendTask| { + let error = TaskError::ContactWalletSeedUnavailable; + screen.display_backend_task_error(&BackendTaskContext::for_dispatch(task), &error); + assert!(!screen.display_task_error(&error)); + screen.display_message(&error.to_string(), MessageType::Error); + }; + + fail(&mut screen, profile); + screen.start_editing(); + assert!( + !screen.editing_info, + "the editor still waits for the details read" + ); + + fail(&mut screen, details); + screen.start_editing(); + assert!( + screen.editing_info, + "a failed details read opens the editor" + ); + } + + /// Clearing a field is an edit too: it is sent as a replacement with no + /// value, not dropped. + #[test] + fn clearing_and_hiding_are_sent_as_edits() { + let dir = tempfile::tempdir().expect("temp dir"); + let context = test_app_context(dir.path()); + let identity = bare_user_identity(Identifier::from([1; 32]), Network::Testnet); + let mut screen = ContactDetailsScreen::new(context, identity, Identifier::from([2; 32])); + if let Some(info) = &mut screen.contact_info { + info.nickname = Some("Bao".into()); + } + + screen.start_editing(); + screen.edit_nickname.clear(); + screen.edit_hidden = true; + let update = dispatched_update(screen.save_contact_info()); + + assert_eq!( + update, + ContactInfoUpdate { + nickname: ContactInfoField::Replace(None), + note: ContactInfoField::Preserve, + display_hidden: ContactInfoField::Replace(true), + } + ); + } +} diff --git a/src/ui/dashpay/contact_requests.rs b/src/ui/dashpay/contact_requests.rs index eaeb72e54..772268f12 100644 --- a/src/ui/dashpay/contact_requests.rs +++ b/src/ui/dashpay/contact_requests.rs @@ -4,7 +4,7 @@ use crate::backend_task::dashpay::errors::DashPayError; use crate::backend_task::error::TaskError; use crate::backend_task::{BackendTask, BackendTaskSuccessResult}; use crate::context::AppContext; -use crate::model::dashpay::{UnreadableContactInfoPolicy, contact_request_recipient}; +use crate::model::dashpay::contact_request_recipient; use crate::model::qualified_identity::QualifiedIdentity; use crate::model::wallet::Wallet; use crate::ui::components::component_trait::Component; @@ -65,7 +65,6 @@ pub struct ContactRequests { has_fetched_requests: bool, accept_confirmation_dialog: Option<(ConfirmationDialog, ContactRequest)>, reject_confirmation_dialog: Option<(ConfirmationDialog, ContactRequest)>, - overwrite_confirmation_dialog: Option, pub selected_wallet: Option>>, pub wallet_unlock_popup: WalletUnlockPopup, wallet_open_attempted: bool, @@ -92,7 +91,6 @@ impl ContactRequests { has_fetched_requests: false, accept_confirmation_dialog: None, reject_confirmation_dialog: None, - overwrite_confirmation_dialog: None, selected_wallet: None, wallet_unlock_popup: WalletUnlockPopup::new(), wallet_open_attempted: false, @@ -159,7 +157,6 @@ impl ContactRequests { self.pending_profile_fetches.clear(); self.request_in_flight = None; self.request_task_in_flight = None; - self.overwrite_confirmation_dialog = None; self.loading = false; } } @@ -382,7 +379,6 @@ impl ContactRequests { let request_task = DashPayTask::RejectContactRequest { identity: identity.clone(), request_id: request.request_id, - unreadable: UnreadableContactInfoPolicy::Abort, }; self.request_task_in_flight = Some(request_task.clone()); let task = BackendTask::DashPayTask(Box::new(request_task)); @@ -395,36 +391,6 @@ impl ContactRequests { } } - if let Some(dialog) = &mut self.overwrite_confirmation_dialog { - match dialog.show(ui).inner.dialog_response { - Some(ConfirmationStatus::Confirmed) => { - if let Some(DashPayTask::RejectContactRequest { - identity, - request_id, - .. - }) = self.request_task_in_flight.take() - { - let retry = DashPayTask::RejectContactRequest { - identity, - request_id, - unreadable: UnreadableContactInfoPolicy::Overwrite, - }; - self.request_task_in_flight = Some(retry.clone()); - self.loading = true; - action |= AppAction::BackendTask(BackendTask::DashPayTask(Box::new(retry))); - } - self.overwrite_confirmation_dialog = None; - } - Some(ConfirmationStatus::Canceled) => { - self.request_in_flight = None; - self.request_task_in_flight = None; - self.loading = false; - self.overwrite_confirmation_dialog = None; - } - None => {} - } - } - // Identity selector or no identities message let identities = self .app_context @@ -907,23 +873,6 @@ impl ScreenLike for ContactRequests { fn display_task_error(&mut self, error: &TaskError) -> bool { let matches_request = request_error_id(error).is_some_and(|id| self.request_in_flight.as_ref() == Some(id)); - if matches_request - && is_contact_info_read_error(error) - && matches!( - self.request_task_in_flight, - Some(DashPayTask::RejectContactRequest { .. }) - ) - { - self.overwrite_confirmation_dialog = Some( - ConfirmationDialog::new( - "Replace saved contact details?", - "This contact's saved details cannot be read. Continuing will decline the request and clear the saved nickname, note, and accepted-account settings. You cannot undo this change.", - ) - .confirm_text(Some("Replace saved details")) - .danger_mode(true), - ); - return true; - } if matches_request { self.request_in_flight = None; self.request_task_in_flight = None; @@ -1114,14 +1063,6 @@ fn request_error_id(error: &TaskError) -> Option<&Identifier> { } } -fn is_contact_info_read_error(error: &TaskError) -> bool { - matches!( - error, - TaskError::DashPayContactRequestActionFailed { source, .. } - if matches!(source.as_ref(), TaskError::DashPayContactInfoRead { .. }) - ) -} - /// Map a typed accept/reject error onto the screen-local error category that /// drives a dedicated affordance (the "Add Encryption Key" button). Returns /// `None` when no request-specific UI applies, leaving the global banner to diff --git a/src/ui/dashpay/qr_code_generator.rs b/src/ui/dashpay/qr_code_generator.rs index 2f2a22ede..02808fba1 100644 --- a/src/ui/dashpay/qr_code_generator.rs +++ b/src/ui/dashpay/qr_code_generator.rs @@ -19,33 +19,28 @@ use crate::ui::dashpay::dashpay_screen::DashPaySubscreen; use crate::ui::identity::get_selected_wallet; use crate::ui::theme::DashColors; use crate::ui::{MessageType, RootScreenType, ScreenLike}; -use egui::{RichText, ScrollArea, TextEdit, Ui}; +use egui::{RichText, ScrollArea, Ui}; use std::sync::{Arc, RwLock}; const QR_CODE_INFO_TEXT: &str = "About Contact QR Codes:\n\n\ - QR codes allow instant mutual contact establishment.\n\n\ - The recipient can scan to automatically send and accept contact requests.\n\n\ - QR codes expire after the specified validity period.\n\n\ - Each QR code is unique and can only be used once.\n\n\ - WARNING: Anyone with this QR code can automatically become your contact."; - -const ACCOUNT_INDEX_INFO_TEXT: &str = "Account Index:\n\n\ - The account index determines which HD wallet account is used for this contact relationship.\n\n\ - Most users should leave this at 0 (the default).\n\n\ - Advanced users may use different account indices to segregate contacts \ - (e.g., separate personal and business contacts into different wallet accounts).\n\n\ - The account index is used in the derivation path: m/9'/5'/15'/account'/..."; + A contact QR code lets someone send you a contact request without typing your username.\n\n\ + Someone who scans your code sends you a contact request that proves you invited them.\n\n\ + Each QR code is valid for 1 hour. Create a new one when it expires.\n\n\ + The code shows your username, so your identity needs a username.\n\n\ + Other Dash apps that use this identity may accept such requests automatically. Dash Evo Tool does not yet accept them automatically, so requests from your code wait for you to accept them.\n\n\ + WARNING: Share this code only with people you want as contacts. Anyone who has it can use it until it expires."; + +/// How long a contact QR code stays valid, in plain words. platform-wallet +/// fixes it (`AUTO_ACCEPT_TTL_SECS`): the code carries a usable key. +const QR_CODE_VALIDITY_TEXT: &str = "Valid for 1 hour."; pub struct QRCodeGeneratorScreen { pub app_context: Arc, pub selected_identity: Option, selected_identity_string: String, - account_index: String, - validity_hours: String, generated_qr_data: Option, qr_code: Option, show_info_popup: bool, - show_advanced_options: bool, selected_wallet: Option>>, wallet_unlock_popup: WalletUnlockPopup, wallet_open_attempted: bool, @@ -57,12 +52,9 @@ impl QRCodeGeneratorScreen { app_context: app_context.clone(), selected_identity: None, selected_identity_string: String::new(), - account_index: "0".to_string(), - validity_hours: "24".to_string(), generated_qr_data: None, qr_code: None, show_info_popup: false, - show_advanced_options: false, selected_wallet: None, wallet_unlock_popup: WalletUnlockPopup::new(), wallet_open_attempted: false, @@ -92,8 +84,9 @@ impl QRCodeGeneratorScreen { new_self } - /// Dispatch the auto-accept QR build to the backend, which resolves the key - /// and derives the proof through the JIT chokepoint (no seed in the UI). + /// Dispatch the contact QR build to the backend, which derives the + /// auto-accept key from the wallet seed through the secret seam (no seed + /// in the UI). fn generate_qr_code(&mut self) -> AppAction { let Some(identity) = &self.selected_identity else { MessageBanner::set_global( @@ -104,35 +97,9 @@ impl QRCodeGeneratorScreen { return AppAction::None; }; - let account_idx = match self.account_index.parse::() { - Ok(v) => v, - Err(_) => { - MessageBanner::set_global( - self.app_context.egui_ctx(), - "Invalid account index number", - MessageType::Error, - ); - return AppAction::None; - } - }; - - let validity = match self.validity_hours.parse::() { - Ok(v) if v > 0 && v <= 720 => v, // Max 30 days - _ => { - MessageBanner::set_global( - self.app_context.egui_ctx(), - "Validity hours must be between 1 and 720", - MessageType::Error, - ); - return AppAction::None; - } - }; - AppAction::BackendTask(BackendTask::DashPayTask(Box::new( DashPayTask::GenerateAutoAcceptQrCode { identity: identity.clone(), - account_reference: account_idx, - validity_hours: validity, }, ))) } @@ -151,9 +118,6 @@ impl QRCodeGeneratorScreen { if crate::ui::helpers::info_icon_button(ui, QR_CODE_INFO_TEXT).clicked() { self.show_info_popup = true; } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.checkbox(&mut self.show_advanced_options, "Advanced Options"); - }); }); ui.separator(); @@ -223,47 +187,6 @@ impl QRCodeGeneratorScreen { ui.end_row(); }); - // Advanced options (only shown when checkbox is checked) - if self.show_advanced_options { - ui.add_space(10.0); - egui::Grid::new("qr_advanced_config_grid") - .num_columns(2) - .spacing([10.0, 10.0]) - .show(ui, |ui| { - ui.horizontal(|ui| { - ui.label( - RichText::new("Account Index:") - .color(DashColors::text_primary(dark_mode)), - ); - crate::ui::helpers::info_icon_button(ui, ACCOUNT_INDEX_INFO_TEXT); - }); - ui.add( - TextEdit::singleline(&mut self.account_index) - .hint_text("0") - .desired_width(100.0), - ); - ui.end_row(); - - ui.label( - RichText::new("Validity (hours):") - .color(DashColors::text_primary(dark_mode)), - ); - ui.horizontal(|ui| { - ui.add( - TextEdit::singleline(&mut self.validity_hours) - .hint_text("24") - .desired_width(100.0), - ); - ui.label( - RichText::new("How long the QR code remains valid (default: 24)") - .small() - .color(DashColors::text_secondary(dark_mode)), - ); - }); - ui.end_row(); - }); - } - ui.add_space(10.0); // Check wallet lock status before showing generate button @@ -349,16 +272,21 @@ impl QRCodeGeneratorScreen { ui.add_space(10.0); + ui.label( + RichText::new(QR_CODE_VALIDITY_TEXT) + .small() + .color(DashColors::text_secondary(dark_mode)), + ); ui.label( RichText::new( - "Share this QR code with someone to establish a mutual contact", + "Share this QR code with someone you want as a contact.", ) .small() .color(DashColors::text_secondary(dark_mode)), ); ui.label( RichText::new( - "WARNING: Anyone with this QR code can automatically become your contact", + "WARNING: Anyone who has this QR code can use it until it expires.", ) .small() .color(DashColors::warning_color(dark_mode)), @@ -443,8 +371,8 @@ impl ScreenLike for QRCodeGeneratorScreen { } fn display_task_result(&mut self, result: BackendTaskSuccessResult) { - if let BackendTaskSuccessResult::DashPayAutoAcceptQrCode(qr_string) = result { - self.generated_qr_data = Some(qr_string); + if let BackendTaskSuccessResult::DashPayAutoAcceptQrCode(qr) = result { + self.generated_qr_data = Some(qr.as_str().to_string()); } } } diff --git a/src/ui/dashpay/qr_scanner.rs b/src/ui/dashpay/qr_scanner.rs index 6730a1e3c..9f0dc70c6 100644 --- a/src/ui/dashpay/qr_scanner.rs +++ b/src/ui/dashpay/qr_scanner.rs @@ -1,8 +1,8 @@ use crate::app::AppAction; use crate::backend_task::dashpay::DashPayTask; -use crate::backend_task::dashpay::auto_accept_proof::AutoAcceptProofData; use crate::backend_task::{BackendTask, BackendTaskSuccessResult}; use crate::context::AppContext; +use crate::model::dashpay_contact_qr::ContactQrCode; use crate::model::qualified_identity::QualifiedIdentity; use crate::model::wallet::Wallet; use crate::ui::components::dashpay_subscreen_chooser_panel::add_dashpay_subscreen_chooser_panel; @@ -28,7 +28,7 @@ pub struct QRScannerScreen { pub selected_identity: Option, selected_identity_string: String, qr_data_input: String, - parsed_qr_data: Option, + parsed_qr_data: Option, sending: bool, selected_wallet: Option>>, wallet_unlock_popup: WalletUnlockPopup, @@ -80,7 +80,7 @@ impl QRScannerScreen { return; } - match AutoAcceptProofData::from_qr_string(&self.qr_data_input) { + match ContactQrCode::parse(&self.qr_data_input) { Ok(data) => { self.parsed_qr_data = Some(data); MessageBanner::set_global( @@ -93,7 +93,7 @@ impl QRScannerScreen { self.parsed_qr_data = None; MessageBanner::set_global( self.app_context.egui_ctx(), - "The QR code is not valid for DashPay. Scan a DashPay code and try again.", + error.to_string(), MessageType::Error, ) .with_details(error); @@ -133,12 +133,7 @@ impl QRScannerScreen { BackendTask::DashPayTask(Box::new(DashPayTask::SendContactRequestWithProof { identity: identity.clone(), signing_key: signing_key.clone(), - to_identity_id: qr_data.identity_id, - account_label: Some(format!( - "QR Contact (Account #{})", - qr_data.account_reference - )), - qr_auto_accept: qr_data.clone(), + qr_code: qr_data.clone(), })); return AppAction::BackendTask(task); @@ -233,7 +228,7 @@ impl QRScannerScreen { ui.add( TextEdit::multiline(&mut self.qr_data_input) - .hint_text("dash:?di=...") + .hint_text("dash:?du=...") .desired_rows(3) .desired_width(f32::INFINITY) ); @@ -262,19 +257,18 @@ impl QRScannerScreen { .num_columns(2) .spacing([10.0, 5.0]) .show(ui, |ui| { - ui.label("Contact Identity:"); - ui.label(qr_data.identity_id.to_string( - dash_sdk::dpp::platform_value::string_encoding::Encoding::Base58 - )); - ui.end_row(); - - ui.label("Account Reference:"); - ui.label(format!("{}", qr_data.account_reference)); + ui.label("Contact Username:"); + ui.label(qr_data.full_username()); ui.end_row(); ui.label("Expires:"); - let expiry_time = std::time::UNIX_EPOCH + std::time::Duration::from_secs(qr_data.expires_at); - ui.label(format!("{:?}", expiry_time)); + ui.label( + crate::model::datetime::instant_from_unix_secs(u64::from( + qr_data.expires_at(), + )) + .map(crate::model::datetime::local_date_time) + .unwrap_or_default(), + ); ui.end_row(); }); @@ -316,8 +310,8 @@ impl QRScannerScreen { ui.add_space(10.0); - ui.label(RichText::new("ℹ️ This will send a contact request that will be automatically accepted").small()); - ui.label(RichText::new("⚡ Both you and the contact will become mutual contacts instantly").small()); + ui.label(RichText::new("This sends a contact request that proves your contact invited you.").small()); + ui.label(RichText::new("Your contact's app can accept it automatically. Otherwise, your contact accepts it like any other request.").small()); }); } @@ -327,11 +321,10 @@ impl QRScannerScreen { ui.group(|ui| { ui.label(RichText::new("ℹ️ About QR Code Scanning").strong()); ui.separator(); - ui.label("• QR codes enable instant mutual contact establishment"); - ui.label("• The contact request is automatically accepted by both parties"); - ui.label("• No manual approval is needed when using valid QR codes"); - ui.label("• QR codes expire after the specified time period"); - ui.label("• Each QR code can only be used once"); + ui.label("• Scanning a contact QR code sends a contact request to the person who shared it."); + ui.label("• Their app can accept the request automatically, without asking them."); + ui.label("• Dash Evo Tool does not yet accept such requests automatically. Requests you receive this way wait for you to accept them."); + ui.label("• Contact QR codes are valid for 1 hour after they are created."); }); }); diff --git a/src/ui/identity/contacts.rs b/src/ui/identity/contacts.rs index db5e9da70..a5c5c3a97 100644 --- a/src/ui/identity/contacts.rs +++ b/src/ui/identity/contacts.rs @@ -25,7 +25,8 @@ use crate::backend_task::{BackendTask, BackendTaskContext}; use crate::context::AppContext; use crate::context::feature_gate::FeatureGate; use crate::model::dashpay::{ - ContactInfoUpdate, MAX_CONTACT_NOTE_BYTES, UnreadableContactInfoPolicy, validate_contact_note, + ContactInfoUpdate, MAX_CONTACT_NOTE_BYTES, contact_details_save_publishes, + validate_contact_note, }; use crate::model::fee_estimation::format_credits_as_dash; use crate::model::qualified_identity::QualifiedIdentity; @@ -56,12 +57,21 @@ pub const DETAIL_HEADING: &str = "Contact details"; pub const NO_SELECTION: &str = "Select a contact to see their details."; pub const NOTE_HEADING: &str = "Private note"; pub const NOTE_HINT: &str = "Only you can see this note. It is stored encrypted on Dash Platform."; +/// [`NOTE_HINT`] while DIP-0015 keeps contact details on this device. +pub const NOTE_HINT_ON_THIS_DEVICE: &str = "Only you can see this note. Until this identity has two contacts, it is stored on this device only."; pub const NOTE_PLACEHOLDER: &str = "Add a note that only you can see"; pub const SAVE_NOTE_LABEL: &str = "Save note"; pub const SAVING_NOTE_LABEL: &str = "Saving…"; pub const NOTE_UNCHANGED_TOOLTIP: &str = "There are no changes to save."; pub const NOTE_SAVE_TOOLTIP: &str = "Save this note on Dash Platform. Saving costs a small fee."; +/// [`NOTE_SAVE_TOOLTIP`] while DIP-0015 keeps contact details on this device. +pub const NOTE_SAVE_ON_THIS_DEVICE_TOOLTIP: &str = + "Save this note on this device. Saving is free until this identity has two contacts."; pub const NOTE_SAVED: &str = "Your note is saved."; +/// Shown when contact details are kept on this device only: DIP-0015 holds +/// them back until the identity has two contacts, and nothing publishes them +/// later on its own. +pub const DETAILS_SAVED_ON_THIS_DEVICE: &str = "Your contact details are saved on this device only. After this identity has two contacts, edit and save these details again to sync them to your other devices."; const NOTE_SAVING_TOOLTIP: &str = "This contact's details are being saved."; pub const RECEIVED_HEADING: &str = "Received requests"; pub const ACTIVE_HEADING_PREFIX: &str = "Active contacts"; @@ -87,19 +97,17 @@ pub const SHOW_HIDDEN_LABEL: &str = "Show hidden contacts"; /// Shown under a hidden contact whose saved details could not be read: its /// hidden flag is unknown, so it stays hidden until the user unhides it. pub const UNREADABLE_DETAILS_NOTE: &str = "The details you saved for this contact could not be read, so it stays \ - hidden. Unhide it to show it in your list again."; + hidden. Unhide it to show it in your list again; this clears the unreadable details."; -/// Why a contact the user never hid by hand can still be in this section: -/// declining or cancelling a request hides that person, and a contact that is -/// later established with them stays hidden until it is unhidden here. -pub const HIDDEN_EXPLAINER: &str = "Hidden contacts are kept out of your list. Declining or cancelling a request also hides that \ - person. Unhide anyone you want back."; +/// Hidden-section caption. Only an explicit hide puts a contact here; +/// declining or cancelling a request writes no contact details. +pub const HIDDEN_EXPLAINER: &str = + "Hidden contacts are kept out of your list. Unhide anyone you want back."; /// Sent-section caption. A DashPay contact request cannot be deleted from the -/// network once sent, so the copy states plainly what Cancel really does -/// instead of promising a withdrawal the protocol cannot deliver. -pub const CANCEL_EXPLAINER: &str = "Cancelling a request hides it and tells the other person you are no longer waiting. The \ - original request stays on the network."; +/// network once sent, and Cancel publishes nothing, so the copy states plainly +/// that it only hides the request on this device. +pub const CANCEL_EXPLAINER: &str = "Cancelling a request hides it on this device only. The other person is not notified, and the original request stays on the network."; /// Below this tab width the detail pane stacks under the contact list. Home /// and Profile switch to one column at the same width. @@ -292,23 +300,17 @@ pub fn request_task( RequestAction::Declined => DashPayTask::RejectContactRequest { identity, request_id, - unreadable: UnreadableContactInfoPolicy::Abort, }, RequestAction::Cancelled => DashPayTask::CancelContactRequest { identity, request_id, - unreadable: UnreadableContactInfoPolicy::Abort, }, } } -/// Backend task that makes a hidden contact visible again. -/// -/// Unhiding is a `contactInfo` broadcast with `display_hidden` cleared — the -/// same document the decline / cancel paths set it on. The whole document is -/// rewritten, so everything unhiding has no opinion about rides along untouched: -/// the nickname and note are carried over, and the accepted accounts are -/// preserved rather than replaced with an empty list. +/// Backend task that makes a hidden contact visible again, keeping its +/// nickname and note. Details that could not be read cannot be kept: the +/// backend replaces them when it reads them so, as the hidden list says. pub fn unhide_task(identity: QualifiedIdentity, contact: &ContactData) -> DashPayTask { DashPayTask::UpdateContactInfo { identity, @@ -741,6 +743,8 @@ fn note_editor( dark_mode: bool, ) -> bool { let contact_id = contact.identity_id; + // With fewer than two contacts the save stays on this device: no fee. + let publishes = contact_details_save_publishes(state.contacts_len()); let saving = state .detail() .is_writing(&identity.identity.id(), &contact_id); @@ -755,9 +759,13 @@ fn note_editor( .color(DashColors::text_primary(dark_mode)), ); ui.label( - RichText::new(NOTE_HINT) - .small() - .color(DashColors::text_secondary(dark_mode)), + RichText::new(if publishes { + NOTE_HINT + } else { + NOTE_HINT_ON_THIS_DEVICE + }) + .small() + .color(DashColors::text_secondary(dark_mode)), ); ui.add_space(6.0); ui.add_enabled( @@ -779,13 +787,15 @@ fn note_editor( } ui.add_space(8.0); - let fee = app_context.fee_estimator().estimate_contact_info_write(); - ui.label( - RichText::new(note_fee_text(&format_credits_as_dash(fee))) - .small() - .color(DashColors::text_secondary(dark_mode)), - ); - ui.add_space(6.0); + if publishes { + let fee = app_context.fee_estimator().estimate_contact_info_write(); + ui.label( + RichText::new(note_fee_text(&format_credits_as_dash(fee))) + .small() + .color(DashColors::text_secondary(dark_mode)), + ); + ui.add_space(6.0); + } let dirty = detail.is_dirty(&contact_id); let can_save = dirty && invalid.is_none() && !saving; @@ -796,7 +806,11 @@ fn note_editor( }; let save = ComponentStyles::add_primary_button_enabled(ui, can_save, label); let save = if can_save { - save.clickable_tooltip(NOTE_SAVE_TOOLTIP) + save.clickable_tooltip(if publishes { + NOTE_SAVE_TOOLTIP + } else { + NOTE_SAVE_ON_THIS_DEVICE_TOOLTIP + }) } else if saving { save.disabled_tooltip(NOTE_SAVING_TOOLTIP) } else if let Some(error) = invalid { @@ -1603,7 +1617,7 @@ mod tests { "the note save must wait for the unhide" ); - assert!(state.finish_contact_info_write(Network::Testnet, &id(1), &id(5))); + assert!(state.finish_contact_info_write(Network::Testnet, &id(1), &id(5), true)); assert_eq!( state.selected_contact().and_then(|c| c.note.as_deref()), None, @@ -1663,8 +1677,10 @@ mod tests { for line in [ NO_SELECTION, NOTE_HINT, + NOTE_HINT_ON_THIS_DEVICE, NOTE_UNCHANGED_TOOLTIP, NOTE_SAVE_TOOLTIP, + NOTE_SAVE_ON_THIS_DEVICE_TOOLTIP, NOTE_SAVED, SELECT_CONTACT_TOOLTIP, NO_RECEIVED_EMPTY, @@ -1850,22 +1866,6 @@ mod tests { } } - #[test] - fn unhide_leaves_the_accepted_accounts_alone() { - // The write replaces the whole contactInfo document. Unhiding says - // nothing about which accounts the user accepted, so it must not - // volunteer an empty list — that would erase every one of them. - let task = unhide_task(qualified_identity(id(1)), &hidden_contact(None, None)); - match task { - DashPayTask::UpdateContactInfo { update, .. } => assert_eq!( - update.accepted_accounts, - crate::model::dashpay::AcceptedAccounts::Preserve, - "unhiding must preserve the contact's accepted accounts, not overwrite them" - ), - other => panic!("expected UpdateContactInfo, got {other:?}"), - } - } - // --------------------------------------------------------------- // Hydration — both loads must survive the trip to `AppState`. // `AppAction`'s `|=` is last-writer-wins, so two separate diff --git a/src/ui/identity/hub_screen.rs b/src/ui/identity/hub_screen.rs index cfef36a41..501f52261 100644 --- a/src/ui/identity/hub_screen.rs +++ b/src/ui/identity/hub_screen.rs @@ -14,9 +14,7 @@ use crate::backend_task::error::TaskError; use crate::backend_task::identity::IdentityTask; use crate::backend_task::{BackendTask, BackendTaskContext, BackendTaskSuccessResult}; use crate::context::AppContext; -use crate::model::dashpay::{ContactInfoField, UnreadableContactInfoPolicy}; -use crate::ui::components::component_trait::Component; -use crate::ui::components::confirmation_dialog::{ConfirmationDialog, ConfirmationStatus}; +use crate::model::dashpay::ContactInfoField; use crate::ui::components::left_panel::add_left_panel; use crate::ui::components::message_banner::{BannerHandle, MessageBanner, OptionBannerExt}; use crate::ui::components::styled::island_central_panel; @@ -27,7 +25,7 @@ use dash_sdk::dpp::dashcore::Network; use dash_sdk::dpp::identity::accessors::IdentityGettersV0; use dash_sdk::platform::Identifier; use eframe::egui::{self, Context}; -use std::collections::{BTreeSet, HashMap, VecDeque}; +use std::collections::{BTreeSet, HashMap}; use std::sync::Arc; use super::home::HomeState; @@ -100,7 +98,6 @@ pub struct IdentityHubScreen { /// Breadcrumb-switcher view state (picker override + dropdown search /// buffers). The active identity itself is app-scoped on `AppContext`. selection: HubSelection, - contact_info_overwrite_dialog: Option<(ConfirmationDialog, ContactInfoTaskKey)>, pending_contact_info_tasks: HashMap, /// The dispatch each direct contact details write was sent under, and the /// network it runs on. Another screen can write the same contact while the @@ -111,7 +108,6 @@ pub struct IdentityHubScreen { /// Set by `display_backend_task_error` when the error belongs to another /// screen's write, so the context-free handler that follows it ignores it. foreign_contact_info_error: bool, - pending_contact_info_confirmations: VecDeque, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] @@ -180,11 +176,9 @@ impl IdentityHubScreen { avatar_cache: crate::ui::state::AvatarCache::default(), pending_avatars: Vec::new(), selection: HubSelection::default(), - contact_info_overwrite_dialog: None, pending_contact_info_tasks: HashMap::new(), contact_info_dispatches: HashMap::new(), foreign_contact_info_error: false, - pending_contact_info_confirmations: VecDeque::new(), } } @@ -192,9 +186,7 @@ impl IdentityHubScreen { let AppAction::BackendTask(BackendTask::DashPayTask(task)) = action else { return; }; - if can_confirm_contact_info_overwrite(task) - && let Some(key) = contact_info_task_key(task) - { + if let Some(key) = contact_info_task_key(task) { self.pending_contact_info_tasks .insert(key, task.as_ref().clone()); } @@ -274,15 +266,6 @@ impl IdentityHubScreen { } fn reset_contacts_for_identity_change(&mut self) { - release_guards_for_abandoned_confirmations( - &mut self.contacts_state, - self.app_context.network, - self.pending_contact_info_confirmations.iter().chain( - self.contact_info_overwrite_dialog - .iter() - .map(|(_, key)| key), - ), - ); self.home_state = HomeState::default(); self.contacts_state.reset_for_identity_change(); // A write still running keeps its guard across the change, so it keeps @@ -294,38 +277,6 @@ impl IdentityHubScreen { }; self.pending_contact_info_tasks.retain(|key, _| live(key)); self.contact_info_dispatches.retain(|key, _| live(key)); - self.pending_contact_info_confirmations.clear(); - self.contact_info_overwrite_dialog = None; - } - - fn queue_contact_info_confirmation(&mut self, key: ContactInfoTaskKey) { - let already_showing = self - .contact_info_overwrite_dialog - .as_ref() - .is_some_and(|(_, shown_key)| *shown_key == key); - if already_showing || self.pending_contact_info_confirmations.contains(&key) { - return; - } - - self.pending_contact_info_confirmations.push_back(key); - } - - fn prepare_contact_info_dialog(&mut self) { - if self.contact_info_overwrite_dialog.is_some() { - return; - } - while let Some(key) = self.pending_contact_info_confirmations.pop_front() { - if let Some(task) = self.pending_contact_info_tasks.get(&key) { - let (title, message) = contact_info_confirmation_copy(task); - self.contact_info_overwrite_dialog = Some(( - ConfirmationDialog::new(title, message) - .confirm_text(Some("Replace saved details")) - .danger_mode(true), - key, - )); - break; - } - } } /// Clear the stale load-error banner so the next `landing()` call can try @@ -349,8 +300,8 @@ impl IdentityHubScreen { } /// Reset all identity-scoped state after the owning application context - /// changes. Abandoned confirmations release their guards; live paid actions - /// remain guarded, and stale guards are pruned during the contacts reset. + /// changes. Live paid actions remain guarded, and stale guards are pruned + /// during the contacts reset. pub(crate) fn reset_for_context_change(&mut self) { self.reset_contacts_for_identity_change(); self.settings_tab = SettingsTab::new(); @@ -463,13 +414,6 @@ impl IdentityHubScreen { if !matches!(error, TaskError::DashPayContactRequestActionFailed { .. }) { return false; } - if let Some(key) = contact_info_read_error_key(error) - && self.pending_contact_info_tasks.contains_key(&key) - { - self.contacts_state.invalidate(); - self.queue_contact_info_confirmation(key); - return true; - } if let Some(key) = contact_info_error_key(error) { self.forget_contact_info_task(&key); } @@ -477,9 +421,8 @@ impl IdentityHubScreen { true } - /// Settle a failed direct contact details write: ask before overwriting - /// unreadable details, otherwise drop the pending write and release its - /// guard. Returns whether the hub took over telling the user. + /// Settle a failed direct contact details write: drop the pending write + /// and release its guard. The error banner tells the user. pub(crate) fn handle_contact_info_error(&mut self, error: &TaskError) -> bool { // Another screen's write failed; the hub's own write is still running. if std::mem::take(&mut self.foreign_contact_info_error) @@ -487,13 +430,6 @@ impl IdentityHubScreen { { return false; } - if let Some(key) = contact_info_read_error_key(error) - && self.pending_contact_info_tasks.contains_key(&key) - { - self.contacts_state.invalidate(); - self.queue_contact_info_confirmation(key); - return true; - } if let TaskError::DashPayContactInfoActionFailed { identity_id, contact_id, @@ -833,38 +769,6 @@ impl ScreenLike for IdentityHubScreen { action = self.apply_breadcrumb_effect(effect); } - self.prepare_contact_info_dialog(); - if let Some((dialog, key)) = &mut self.contact_info_overwrite_dialog { - let key = *key; - match dialog.show(ui).inner.dialog_response { - Some(ConfirmationStatus::Confirmed) => { - if let Some(task) = self - .pending_contact_info_tasks - .get(&key) - .cloned() - .and_then(overwrite_unreadable_task) - { - self.pending_contact_info_tasks.insert(key, task.clone()); - action = self.bind_contact_info_dispatch(AppAction::BackendTask( - BackendTask::DashPayTask(Box::new(task)), - )); - } - self.contact_info_overwrite_dialog = None; - } - Some(ConfirmationStatus::Canceled) => { - release_guards_for_abandoned_confirmations( - &mut self.contacts_state, - self.app_context.network, - [&key], - ); - self.forget_contact_info_task(&key); - self.contacts_state.invalidate(); - self.contact_info_overwrite_dialog = None; - } - None => {} - } - } - // Every part of the frame above has had its say; this is where the // action that leaves the frame is settled. A data load claims its one // dispatch slot when it is asked for, so it is asked for only here and @@ -961,6 +865,7 @@ impl ScreenLike for IdentityHubScreen { if let BackendTaskSuccessResult::DashPayContactInfoUpdated { identity, contact_id, + .. } = &result && !self.is_own_contact_info_dispatch(context) { @@ -1026,6 +931,7 @@ impl ScreenLike for IdentityHubScreen { BackendTaskSuccessResult::DashPayContactInfoUpdated { identity, contact_id, + published, } => { let key = ContactInfoTaskKey::Direct { identity_id: *identity, @@ -1033,14 +939,18 @@ impl ScreenLike for IdentityHubScreen { }; let network = self.contact_info_write_network(identity, contact_id); self.contacts_state - .finish_contact_info_write(network, identity, contact_id); + .finish_contact_info_write(network, identity, contact_id, *published); if let Some(task) = self.forget_contact_info_task(&key) { self.contacts_state.invalidate(); - MessageBanner::set_global( - self.app_context.egui_ctx(), - contact_info_saved_message(&task), - MessageType::Success, - ); + let (message, kind) = if *published { + (contact_info_saved_message(&task), MessageType::Success) + } else { + ( + super::contacts::DETAILS_SAVED_ON_THIS_DEVICE, + MessageType::Info, + ) + }; + MessageBanner::set_global(self.app_context.egui_ctx(), message, kind); } } // Reaches this root as its own result or as an observer of another @@ -1091,7 +1001,7 @@ impl ScreenLike for IdentityHubScreen { fn display_backend_task_error(&mut self, context: &BackendTaskContext, error: &TaskError) { self.foreign_contact_info_error = context.dashpay_contact_info_target().is_some() && !self.is_own_contact_info_dispatch(context); - // Wrapped errors retain the unreadable-details confirmation flow. + // Wrapped errors are settled by `handle_contact_info_error`. if !self.foreign_contact_info_error && !matches!(error, TaskError::DashPayContactInfoActionFailed { .. }) && let Some((identity_id, contact_id)) = context.dashpay_contact_info_target() @@ -1144,10 +1054,7 @@ impl ScreenLike for IdentityHubScreen { return true; } if self.handle_contact_request_error(error) { - return matches!( - contact_info_read_error_key(error), - Some(key) if self.pending_contact_info_tasks.contains_key(&key) - ); + return false; } if self.handle_contact_info_error(error) { return true; @@ -1181,24 +1088,6 @@ fn release_request_guard_for_error(state: &mut super::contacts::ContactsState, e } } -/// Release the request and note-save guards of confirmations that will never -/// be answered: no task is left running for them. -fn release_guards_for_abandoned_confirmations<'a>( - state: &mut super::contacts::ContactsState, - network: Network, - keys: impl IntoIterator, -) { - for key in keys { - match key { - ContactInfoTaskKey::Request(request_id) => state.release_request(request_id), - ContactInfoTaskKey::Direct { - identity_id, - contact_id, - } => state.release_contact_info_write(network, identity_id, contact_id), - } - } -} - /// Whether a captured contactInfo write is a private-note save rather than an /// unhide. fn is_note_save(task: &DashPayTask) -> bool { @@ -1218,61 +1107,6 @@ fn contact_info_saved_message(task: &DashPayTask) -> &'static str { } } -fn can_confirm_contact_info_overwrite(task: &DashPayTask) -> bool { - match task { - DashPayTask::UpdateContactInfo { update, .. } => { - update.unreadable == UnreadableContactInfoPolicy::Abort - } - DashPayTask::RejectContactRequest { unreadable, .. } - | DashPayTask::CancelContactRequest { unreadable, .. } => { - *unreadable == UnreadableContactInfoPolicy::Abort - } - _ => false, - } -} - -/// Title and body for the overwrite confirmation, one complete message per -/// action so each stays a single translatable sentence group. Only the contact -/// case names an identifier: a request ID is not something the user has seen, -/// and the details at risk belong to the contact, not to the request. -fn contact_info_confirmation_copy(task: &DashPayTask) -> (&'static str, String) { - use crate::ui::identity::identity_pill::shorten_id; - use dash_sdk::dpp::platform_value::string_encoding::Encoding; - - match task { - DashPayTask::UpdateContactInfo { contact_id, .. } if is_note_save(task) => { - let contact = shorten_id(&contact_id.to_string(Encoding::Base58)); - ( - "Save note and replace saved details?", - format!( - "The saved details for contact {contact} cannot be read. Saving this note will clear the contact's saved nickname and accepted-account settings. You cannot undo this change." - ), - ) - } - DashPayTask::UpdateContactInfo { contact_id, .. } => { - let contact = shorten_id(&contact_id.to_string(Encoding::Base58)); - ( - "Unhide contact and replace saved details?", - format!( - "The saved details for contact {contact} cannot be read. Unhiding this contact will clear its saved nickname, note, and accepted-account settings. You cannot undo this change." - ), - ) - } - DashPayTask::RejectContactRequest { .. } => ( - "Decline request and replace saved details?", - "The saved details for this contact cannot be read. Declining the request will clear the contact's saved nickname, note, and accepted-account settings. You cannot undo this change.".to_string(), - ), - DashPayTask::CancelContactRequest { .. } => ( - "Cancel request and replace saved details?", - "The saved details for this contact cannot be read. Withdrawing the request will clear the contact's saved nickname, note, and accepted-account settings. You cannot undo this change.".to_string(), - ), - _ => ( - "Replace saved contact details?", - "The saved details for this contact cannot be read. Continuing will clear the contact's saved nickname, note, and accepted-account settings. You cannot undo this change.".to_string(), - ), - } -} - fn contact_info_task_key(task: &DashPayTask) -> Option { match task { DashPayTask::UpdateContactInfo { @@ -1291,39 +1125,6 @@ fn contact_info_task_key(task: &DashPayTask) -> Option { } } -fn overwrite_unreadable_task(task: DashPayTask) -> Option { - match task { - DashPayTask::UpdateContactInfo { - identity, - contact_id, - update, - } => Some(DashPayTask::UpdateContactInfo { - identity, - contact_id, - update: update.overwrite_unreadable(), - }), - DashPayTask::RejectContactRequest { - identity, - request_id, - .. - } => Some(DashPayTask::RejectContactRequest { - identity, - request_id, - unreadable: UnreadableContactInfoPolicy::Overwrite, - }), - DashPayTask::CancelContactRequest { - identity, - request_id, - .. - } => Some(DashPayTask::CancelContactRequest { - identity, - request_id, - unreadable: UnreadableContactInfoPolicy::Overwrite, - }), - _ => None, - } -} - fn contact_info_error_key(error: &TaskError) -> Option { match error { TaskError::DashPayContactInfoActionFailed { @@ -1341,18 +1142,6 @@ fn contact_info_error_key(error: &TaskError) -> Option { } } -fn contact_info_read_error_key(error: &TaskError) -> Option { - match error { - TaskError::DashPayContactInfoActionFailed { source, .. } - | TaskError::DashPayContactRequestActionFailed { source, .. } - if matches!(source.as_ref(), TaskError::DashPayContactInfoRead { .. }) => - { - contact_info_error_key(error) - } - _ => None, - } -} - /// Whether a backend result loaded for `result_identity` may still be applied /// while `selected` is the identity on screen. /// @@ -2652,28 +2441,6 @@ mod tests { assert!(state.is_in_flight(&id(3))); } - #[test] - fn abandoning_confirmations_releases_only_their_request_guards() { - let mut state = ContactsState::default(); - assert!(state.begin_request(id(1))); - assert!(state.begin_request(id(2))); - let keys = [ - ContactInfoTaskKey::Request(id(2)), - ContactInfoTaskKey::Direct { - identity_id: id(3), - contact_id: id(4), - }, - ]; - - release_guards_for_abandoned_confirmations(&mut state, Network::Testnet, &keys); - - assert!(state.is_in_flight(&id(1))); - assert!( - !state.is_in_flight(&id(2)), - "a discarded confirmation has no running task left to protect" - ); - } - fn contact_info_task(update: crate::model::dashpay::ContactInfoUpdate) -> DashPayTask { DashPayTask::UpdateContactInfo { identity: hub_identity(id(1)), @@ -2703,7 +2470,7 @@ mod tests { } #[test] - fn a_saved_note_and_an_unhide_confirm_differently() { + fn a_saved_note_and_an_unhide_report_differently() { use crate::model::dashpay::ContactInfoUpdate; let note = contact_info_task(ContactInfoUpdate::note(Some("Bao".into()))); @@ -2718,48 +2485,6 @@ mod tests { contact_info_saved_message(&unhide), "This contact is back in your list." ); - - let (title, message) = contact_info_confirmation_copy(¬e); - assert_eq!(title, "Save note and replace saved details?"); - assert!( - message.contains("nickname") && !message.contains("Unhiding"), - "the overwrite warning names what a note save clears: {message}" - ); - let (title, _) = contact_info_confirmation_copy(&unhide); - assert_eq!(title, "Unhide contact and replace saved details?"); - } - - #[test] - fn abandoning_a_note_save_confirmation_releases_its_guard() { - let mut state = ContactsState::default(); - assert!(state.begin_request(id(2))); - state.record_contacts(vec![crate::backend_task::dashpay::ContactData { - identity_id: id(4), - nickname: None, - note: None, - is_hidden: false, - details_unreadable: false, - account_reference: 0, - username: None, - display_name: None, - avatar_url: None, - bio: None, - }]); - state.select_contact(&id(4)); - *state.detail_mut().note_mut(&id(4)).expect("draft") = "Bao".into(); - assert!(state.detail_mut().begin_save(id(3), id(4)).is_some()); - - release_guards_for_abandoned_confirmations( - &mut state, - Network::Testnet, - &[ContactInfoTaskKey::Direct { - identity_id: id(3), - contact_id: id(4), - }], - ); - - assert!(!state.detail().is_writing(&id(3), &id(4))); - assert!(state.is_in_flight(&id(2)), "unrelated request guards stay"); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] @@ -2861,6 +2586,7 @@ mod tests { BackendTaskSuccessResult::DashPayContactInfoUpdated { identity: owner, contact_id: contact, + published: true, }, ), "wrapped failure" => { @@ -2970,6 +2696,7 @@ mod tests { BackendTaskSuccessResult::DashPayContactInfoUpdated { identity: owner, contact_id: contact, + published: true, }, ); let load_b = contacts_load(&mut screen); @@ -3004,6 +2731,8 @@ mod tests { enum NoteEvent { /// The hub's write succeeds. Saved, + /// The hub's write succeeds and is kept on this device only. + SavedOnThisDevice, /// The hub's write fails. Failed, /// The hub's write succeeds after the hub moved to another network. @@ -3031,6 +2760,16 @@ mod tests { &[Saved, ListFromBefore("Old")], "Mine", ), + ( + "a list from before a save kept on this device", + &[SavedOnThisDevice, ListFromBefore("Old")], + "Mine", + ), + ( + "a published note wins over a save kept on this device", + &[SavedOnThisDevice, ListFromAfter("Old")], + "Old", + ), ( "a read lagging behind the save", &[Saved, ListFromAfter("Old")], @@ -3170,11 +2909,20 @@ mod tests { let saved = BackendTaskSuccessResult::DashPayContactInfoUpdated { identity: owner, contact_id: contact, + published: true, }; for event in events { match *event { NoteEvent::Saved => screen.display_backend_task_result(&write, saved.clone()), + NoteEvent::SavedOnThisDevice => screen.display_backend_task_result( + &write, + BackendTaskSuccessResult::DashPayContactInfoUpdated { + identity: owner, + contact_id: contact, + published: false, + }, + ), NoteEvent::Failed => { let error = TaskError::DashPayContactInfoActionFailed { identity_id: owner, @@ -3233,35 +2981,4 @@ mod tests { async fn a_write_failing_bare_after_an_identity_switch_is_released() { settle_after_an_identity_switch("bare failure").await; } - - #[test] - fn concurrent_contact_info_errors_keep_distinct_retry_keys() { - use crate::backend_task::error::ContactInfoReadError; - - let request_error = TaskError::DashPayContactRequestActionFailed { - request_id: id(2), - source: Box::new(TaskError::DashPayContactInfoRead { - source: ContactInfoReadError::DeserializeFailed, - }), - }; - let direct_error = TaskError::DashPayContactInfoActionFailed { - identity_id: id(3), - contact_id: id(4), - source: Box::new(TaskError::DashPayContactInfoRead { - source: ContactInfoReadError::DeserializeFailed, - }), - }; - - assert_eq!( - contact_info_read_error_key(&request_error), - Some(ContactInfoTaskKey::Request(id(2))) - ); - assert_eq!( - contact_info_read_error_key(&direct_error), - Some(ContactInfoTaskKey::Direct { - identity_id: id(3), - contact_id: id(4), - }) - ); - } } diff --git a/src/ui/state/contacts_view.rs b/src/ui/state/contacts_view.rs index ec8c168ac..f2ffdc0f9 100644 --- a/src/ui/state/contacts_view.rs +++ b/src/ui/state/contacts_view.rs @@ -69,9 +69,8 @@ pub struct ContactsState { /// Notes the hub saved, shown over lists that may not hold them yet. confirmed_notes: HashMap<(Network, Identifier, Identifier), ConfirmedNote>, /// Established contacts flagged `display_hidden`, kept aside so the tab can - /// offer a way back. Declining or cancelling a request hides that person, - /// so without this list a contact could only be recovered from the legacy - /// DashPay screen. + /// offer a way back; without this list a hidden contact could only be + /// recovered from the legacy DashPay screen. hidden: Vec, /// Whether the hidden-contacts section is expanded. show_hidden: bool, @@ -104,7 +103,9 @@ pub struct ContactsState { /// was confirmed. A list from that load or an earlier one, or from no load, /// predates the save: it shows `note` whatever it holds. /// - A list from a later load shows `note` only while it still holds -/// `lagging`, the note a read behind the save can return. +/// `lagging`, the note a read behind the save can return. A save kept on +/// this device has none: a later list already reflects it, so a different +/// note there is a published one, which wins. /// - Retired by: a list holding `note`; a later list holding anything other /// than `lagging`; another screen's successful write to the contact; the /// hub's next confirmed save of it (replaced). @@ -486,8 +487,9 @@ impl ContactsState { &mut self.detail } - /// Settle a confirmed contact details write `owner` ran on `network`. - /// Returns whether one was running. After a note save the listed contact + /// Settle a confirmed contact details write `owner` ran on `network`; + /// `published` when it reached Platform rather than staying on this + /// device. Returns whether one was running. After a note save the listed contact /// shows the stored note right away when the lists belong to that owner on /// that network, without waiting for the reload; see [`ConfirmedNote`]. pub fn finish_contact_info_write( @@ -495,6 +497,7 @@ impl ContactsState { network: Network, owner: &Identifier, contact_id: &Identifier, + published: bool, ) -> bool { let Some(write) = self.detail.finish_write(owner, contact_id) else { return false; @@ -511,12 +514,13 @@ impl ContactsState { None }; // The list read last, else the note the edit started from: lists of - // another identity are on screen when the save lands. - let lagging = Some( + // another identity are on screen when the save lands. A save kept on + // this device has none; no read lags behind it. + let lagging = published.then(|| { listed .as_ref() - .map_or(before, |contact| contact.note.clone()), - ); + .map_or(before, |contact| contact.note.clone()) + }); self.confirmed_notes.insert( (network, *owner, *contact_id), ConfirmedNote { @@ -743,7 +747,7 @@ mod tests { *state.detail_mut().note_mut(&id(7)).expect("draft") = "Met at the meetup".into(); assert!(state.detail_mut().begin_save(id(1), id(7)).is_some()); - assert!(state.finish_contact_info_write(Network::Testnet, &id(1), &id(7))); + assert!(state.finish_contact_info_write(Network::Testnet, &id(1), &id(7), true)); assert_eq!( state.selected_contact().and_then(|c| c.note.as_deref()), @@ -751,7 +755,7 @@ mod tests { ); assert!(!state.detail().is_dirty(&id(7))); assert!( - !state.finish_contact_info_write(Network::Testnet, &id(1), &id(7)), + !state.finish_contact_info_write(Network::Testnet, &id(1), &id(7), true), "a save settles only once" ); } @@ -768,7 +772,7 @@ mod tests { state.select_contact(&id(7)); *state.detail_mut().note_mut(&id(7)).unwrap() = note.unwrap_or_default().into(); assert!(state.detail_mut().begin_save(id(1), id(7)).is_some()); - assert!(state.finish_contact_info_write(Network::Testnet, &id(1), &id(7))); + assert!(state.finish_contact_info_write(Network::Testnet, &id(1), &id(7), true)); state.reset(); state.record_contacts(vec![stale.clone()]); state.select_contact(&id(7)); @@ -797,7 +801,7 @@ mod tests { *state.detail_mut().note_mut(&id(7)).expect("draft") = "Theirs".into(); assert!(state.detail_mut().begin_save(id(2), id(7)).is_some()); - assert!(state.finish_contact_info_write(Network::Testnet, &id(2), &id(7))); + assert!(state.finish_contact_info_write(Network::Testnet, &id(2), &id(7), true)); assert_eq!( state.selected_contact().and_then(|c| c.note.as_deref()), diff --git a/src/wallet_backend/auto_accept.rs b/src/wallet_backend/auto_accept.rs new file mode 100644 index 000000000..15187a8c7 --- /dev/null +++ b/src/wallet_backend/auto_accept.rs @@ -0,0 +1,445 @@ +//! DashPay contact QR codes (DIP-0015 auto-accept) through platform-wallet. +//! +//! platform-wallet builds the QR (`dash:?du=&dapk=`) and picks +//! its expiry; it asks the host for one thing only, the auto-accept private key +//! at `m/9'/coin'/16'/expiry'`. [`AutoAcceptKeyExport`] derives that key from +//! the wallet seed the secret seam lends for one operation, and refuses every +//! other path and every other crypto request. + +use std::sync::Arc; + +use dash_sdk::dpp::dashcore::Network; +use dash_sdk::dpp::identity::accessors::IdentityGettersV0; +use dash_sdk::dpp::key_wallet::bip32::{ChildNumber, DerivationPath, ExtendedPubKey}; +use dash_sdk::dpp::key_wallet::wallet::Wallet; +use dash_sdk::dpp::key_wallet::wallet::initialization::WalletAccountCreationOptions; +use dash_sdk::dpp::secp256k1::{PublicKey, SecretKey}; +use platform_wallet::error::PlatformWalletError; +use platform_wallet::wallet::identity::crypto::auto_accept::{ + AUTO_ACCEPT_TTL_SECS, auto_accept_derivation_path, derive_auto_accept_private_key, +}; +use platform_wallet::wallet::identity::network::{ + ContactCryptoProvider, ContactInfoOpened, ContactInfoSealed, +}; +use zeroize::Zeroizing; + +use crate::backend_task::dashpay::errors::DashPayError; +use crate::backend_task::error::TaskError; +use crate::model::dashpay_contact_qr::ContactQrUri; +use crate::model::qualified_identity::QualifiedIdentity; +use crate::wallet_backend::{SecretScope, WalletBackend}; + +impl WalletBackend { + /// Build a contact QR code for `identity`, valid for one hour. + /// + /// `username` is the identity's DPNS name to put in the code; pass an + /// empty string to have platform-wallet look it up on Platform. + /// + /// # Errors + /// + /// The identity has no wallet in this app + /// ([`DashPayError::ContactQrIdentityNotFromWallet`]) or its wallet is not + /// loaded; the user cancels the wallet password prompt; or + /// platform-wallet cannot build the code, typically because the identity + /// has no username ([`DashPayError::ContactQrBuildFailed`]). + pub(crate) async fn dashpay_build_contact_qr( + &self, + identity: &QualifiedIdentity, + username: &str, + ) -> Result { + let owner = identity.identity.id(); + let seed_hash = identity + .dashpay_wallet_seed_hash() + .ok_or(DashPayError::ContactQrIdentityNotFromWallet)?; + let wallet = self.resolve_wallet(&seed_hash).await?; + let network = identity.network; + let identity_wallet = wallet.identity(); + let dashpay = identity_wallet.dashpay(); + + self.secret_access() + .with_secret_session(&SecretScope::HdSeed { seed_hash }, async |session| { + let plaintext = session.plaintext(); + let seed = plaintext + .expose_hd_seed() + .ok_or(DashPayError::ContactQrWalletSeedUnavailable)?; + let provider = AutoAcceptKeyExport::new(seed, network); + dashpay + .build_auto_accept_qr(&owner, username, &provider) + .await + .map(ContactQrUri::new) + .map_err(|source| { + DashPayError::ContactQrBuildFailed { + source: Arc::new(source), + } + .into() + }) + }) + .await + } +} + +/// How far the device clock may lag platform-wallet's when it picks a QR +/// expiry, in seconds. +const CLOCK_SKEW_SECS: u64 = 300; + +/// Serves platform-wallet the DIP-0015 auto-accept key, and nothing else. +/// +/// Holds a borrow of the seed for one operation only; it never copies the +/// seed out of that operation. +pub(crate) struct AutoAcceptKeyExport<'a> { + seed: &'a [u8; 64], + network: Network, + /// The latest expiry (Unix seconds) a key is exported for: one QR + /// lifetime from now, plus [`CLOCK_SKEW_SECS`]. A key for a later expiry + /// would be a bearer credential that outlives the code it was built for. + latest_expiry: u64, +} + +/// Why [`AutoAcceptKeyExport`] refused a request. Crosses platform-wallet's +/// `ContactCryptoProvider` boundary as [`PlatformWalletError::InvalidParameter`], +/// the only shape that trait allows; the user sees +/// [`DashPayError::ContactQrBuildFailed`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +pub(crate) enum AutoAcceptKeyRefusal { + /// The request is not for this network's `m/9'/coin'/16'/expiry'`. + #[error("this crypto provider serves the DashPay auto-accept key only")] + NotServed, + /// The requested key would stay valid longer than one QR lifetime. + #[error("an auto-accept key expiring at {expiry} outlives the latest allowed {latest}")] + ExpiryTooFar { expiry: u32, latest: u64 }, +} + +impl From for PlatformWalletError { + fn from(refusal: AutoAcceptKeyRefusal) -> Self { + PlatformWalletError::InvalidParameter(refusal.to_string()) + } +} + +impl<'a> AutoAcceptKeyExport<'a> { + pub(crate) fn new(seed: &'a [u8; 64], network: Network) -> Self { + // A clock before 1970 refuses every key rather than any key. + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|elapsed| elapsed.as_secs()) + .unwrap_or_default(); + Self::at(seed, network, now) + } + + /// The provider as it would be at Unix time `now_secs`. + fn at(seed: &'a [u8; 64], network: Network, now_secs: u64) -> Self { + Self { + seed, + network, + latest_expiry: now_secs + .saturating_add(u64::from(AUTO_ACCEPT_TTL_SECS)) + .saturating_add(CLOCK_SKEW_SECS), + } + } + + /// The expiry index of `path` when it is exactly this network's + /// auto-accept path `m/9'/coin'/16'/expiry'`, all hardened, and the expiry + /// is no later than [`Self::latest_expiry`](AutoAcceptKeyExport). + fn auto_accept_expiry(&self, path: &DerivationPath) -> Result { + let expected = auto_accept_derivation_path(self.network, 0) + .map_err(|_| AutoAcceptKeyRefusal::NotServed)?; + let (path, expected) = (path.as_ref(), expected.as_ref()); + let expiry = match path { + [feature @ .., ChildNumber::Hardened { index }] + if path.len() == expected.len() && feature == &expected[..expected.len() - 1] => + { + *index + } + _ => return Err(AutoAcceptKeyRefusal::NotServed), + }; + if u64::from(expiry) > self.latest_expiry { + return Err(AutoAcceptKeyRefusal::ExpiryTooFar { + expiry, + latest: self.latest_expiry, + }); + } + Ok(expiry) + } +} + +fn not_auto_accept() -> PlatformWalletError { + AutoAcceptKeyRefusal::NotServed.into() +} + +#[async_trait::async_trait] +impl ContactCryptoProvider for AutoAcceptKeyExport<'_> { + async fn receiving_xpub( + &self, + _path: &DerivationPath, + ) -> Result { + Err(not_auto_accept()) + } + + async fn ecdh_shared_secret( + &self, + _path: &DerivationPath, + _peer: &PublicKey, + ) -> Result, PlatformWalletError> { + Err(not_auto_accept()) + } + + async fn export_auto_accept_private_key( + &self, + path: &DerivationPath, + ) -> Result { + let expiry = self.auto_accept_expiry(path)?; + let wallet = + Wallet::from_seed_bytes(*self.seed, self.network, WalletAccountCreationOptions::None) + .map_err(|error| PlatformWalletError::KeyDerivation(error.to_string()))?; + derive_auto_accept_private_key(&wallet, self.network, expiry) + } + + async fn export_invitation_private_key( + &self, + _path: &DerivationPath, + ) -> Result { + Err(not_auto_accept()) + } + + async fn account_reference( + &self, + _path: &DerivationPath, + _compact_xpub: &[u8], + _account_index: u32, + _version: u32, + ) -> Result { + Err(not_auto_accept()) + } + + async fn unmask_account_reference( + &self, + _path: &DerivationPath, + _compact_xpub: &[u8], + _account_reference: u32, + ) -> Result<(u32, u32), PlatformWalletError> { + Err(not_auto_accept()) + } + + async fn contact_info_seal( + &self, + _root_path: &DerivationPath, + _derivation_index: u32, + _contact_id: &[u8; 32], + _private_data_plaintext: &[u8], + _private_data_iv: &[u8; 16], + ) -> Result { + Err(not_auto_accept()) + } + + async fn contact_info_open( + &self, + _root_path: &DerivationPath, + _derivation_index: u32, + _enc_to_user_id: &[u8; 32], + _private_data_blob: &[u8], + ) -> Result { + Err(not_auto_accept()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::dashpay_contact_qr::ContactQrCode; + use dash_sdk::platform::Identifier; + use platform_wallet::wallet::identity::crypto::auto_accept::verify_auto_accept_proof_with_pubkey; + use std::str::FromStr; + + /// Generated each run, so no seed bytes are committed. + static SEED: std::sync::LazyLock<[u8; 64]> = std::sync::LazyLock::new(rand::random); + const NETWORK: Network = Network::Testnet; + const EXPIRY: u32 = 1_900_000_000; + /// A moment at which a QR built now expires at [`EXPIRY`]. + const NOW: u64 = EXPIRY as u64 - AUTO_ACCEPT_TTL_SECS as u64; + + fn provider() -> AutoAcceptKeyExport<'static> { + AutoAcceptKeyExport::at(&SEED, NETWORK, NOW) + } + + /// The key the wallet seed itself yields at `expiry`, derived by + /// platform-wallet with no DET code in between. + fn seed_key(seed: &[u8; 64], network: Network, expiry: u32) -> SecretKey { + let wallet = Wallet::from_seed_bytes(*seed, network, WalletAccountCreationOptions::None) + .expect("wallet"); + derive_auto_accept_private_key(&wallet, network, expiry).expect("derive") + } + + #[tokio::test] + async fn exports_the_key_the_wallet_seed_derives() { + let provider = provider(); + let path = auto_accept_derivation_path(NETWORK, EXPIRY).expect("path"); + let key = provider + .export_auto_accept_private_key(&path) + .await + .expect("export"); + assert_eq!(key, seed_key(&SEED, NETWORK, EXPIRY)); + } + + /// Only this network's `m/9'/coin'/16'/expiry'` is served: no other + /// feature, coin, depth or a non-hardened expiry. + #[tokio::test] + async fn refuses_every_path_but_the_auto_accept_one() { + let provider = provider(); + for path in [ + "m", + "m/9'/1'/16'", + "m/9'/1'/16'/5", + "m/9'/1'/16'/5'/0'", + "m/9'/1'/15'/5'", + "m/9'/1'/5'/5'", + "m/9'/5'/16'/5'", + "m/44'/1'/16'/5'", + "m/9/1'/16'/5'", + ] { + let path = DerivationPath::from_str(path).expect("path"); + assert!( + provider + .export_auto_accept_private_key(&path) + .await + .is_err(), + "{path}" + ); + } + } + + /// A key that would outlive one QR lifetime (plus clock skew) is refused, + /// so the provider cannot mint a long-lived bearer credential. + #[tokio::test] + async fn refuses_a_key_that_outlives_one_qr_lifetime() { + let provider = provider(); + let latest = NOW + u64::from(AUTO_ACCEPT_TTL_SECS) + CLOCK_SKEW_SECS; + let latest_index = u32::try_from(latest).expect("index"); + let at = |expiry| auto_accept_derivation_path(NETWORK, expiry).expect("path"); + + assert_eq!( + provider.auto_accept_expiry(&at(latest_index)), + Ok(latest_index) + ); + assert!( + provider + .export_auto_accept_private_key(&at(latest_index)) + .await + .is_ok() + ); + assert_eq!( + provider.auto_accept_expiry(&at(latest_index + 1)), + Err(AutoAcceptKeyRefusal::ExpiryTooFar { + expiry: latest_index + 1, + latest, + }) + ); + assert!( + provider + .export_auto_accept_private_key(&at(latest_index + 1)) + .await + .is_err() + ); + } + + #[tokio::test] + async fn refuses_every_other_crypto_request() { + let provider = provider(); + let path = auto_accept_derivation_path(NETWORK, EXPIRY).expect("path"); + assert!(provider.receiving_xpub(&path).await.is_err()); + let peer = PublicKey::from_secret_key(&seed_key(&SEED, NETWORK, EXPIRY)); + assert!(provider.ecdh_shared_secret(&path, &peer).await.is_err()); + assert!(provider.export_invitation_private_key(&path).await.is_err()); + assert!(provider.account_reference(&path, &[], 0, 0).await.is_err()); + assert!( + provider + .unmask_account_reference(&path, &[], 0) + .await + .is_err() + ); + assert!( + provider + .contact_info_seal(&path, 0, &[0; 32], b"", &[0; 16]) + .await + .is_err() + ); + assert!( + provider + .contact_info_open(&path, 0, &[0; 32], b"") + .await + .is_err() + ); + } + + /// The QR the backend builds carries the identity's username and the key + /// its wallet seed derives, expires in one hour, and a scanner's proof + /// made with it verifies against that seed's public key. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn the_qr_carries_the_wallet_seed_auto_accept_key() { + use crate::model::wallet::Wallet as DetWallet; + use crate::model::wallet::birth_height::WalletOrigin; + use std::collections::BTreeMap; + + let dir = tempfile::tempdir().expect("temp dir"); + let context = crate::context::test_support::wired_test_app_context(dir.path()).await; + let backend = context.wallet_backend().expect("backend wired"); + let seed: [u8; 64] = rand::random(); + let wallet = DetWallet::new_from_seed(seed, NETWORK, Some("w".into()), None).expect("w"); + let (seed_hash, wallet) = context + .register_wallet(wallet, &seed, WalletOrigin::Fresh) + .expect("register wallet"); + backend + .register_wallet_from_seed(&seed_hash, &seed, Some(0)) + .await + .expect("register upstream"); + let owner = Identifier::from([0x11; 32]); + let mut identity = crate::context::test_support::bare_user_identity(owner, NETWORK); + identity.associated_wallets = BTreeMap::from([(seed_hash, wallet)]); + + let before = now_secs(); + let uri = backend + .dashpay_build_contact_qr(&identity, "alice") + .await + .expect("build QR"); + let qr = ContactQrCode::parse(uri.as_str()).expect("parse"); + + assert!(uri.as_str().starts_with("dash:?du=alice&dapk=")); + assert_eq!(qr.username(), "alice"); + let expiry = u64::from(qr.expires_at()); + let ttl = u64::from(AUTO_ACCEPT_TTL_SECS); + assert!((before + ttl..=now_secs() + ttl).contains(&expiry)); + + let scanner = Identifier::from([0x22; 32]); + let proof = qr.sign_proof(&scanner, &owner, 3); + let owner_key = PublicKey::from_secret_key(&seed_key(&seed, NETWORK, qr.expires_at())); + assert!(verify_auto_accept_proof_with_pubkey( + &owner_key, &proof, &scanner, &owner, 3 + )); + } + + #[tokio::test] + async fn an_identity_without_a_wallet_cannot_build_a_qr() { + let dir = tempfile::tempdir().expect("temp dir"); + let context = crate::context::test_support::wired_test_app_context(dir.path()).await; + let backend = context.wallet_backend().expect("backend wired"); + let identity = + crate::context::test_support::bare_user_identity(Identifier::from([5; 32]), NETWORK); + + let result = backend.dashpay_build_contact_qr(&identity, "alice").await; + + assert!( + matches!( + result, + Err(TaskError::DashPay( + DashPayError::ContactQrIdentityNotFromWallet + )) + ), + "{result:?}" + ); + } + + fn now_secs() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .expect("clock") + .as_secs() + } +} diff --git a/src/wallet_backend/contact_info.rs b/src/wallet_backend/contact_info.rs new file mode 100644 index 000000000..adc6d88be --- /dev/null +++ b/src/wallet_backend/contact_info.rs @@ -0,0 +1,859 @@ +//! DashPay `contactInfo` (DIP-0015) through platform-wallet. +//! +//! platform-wallet fetches, matches, encodes and publishes `contactInfo` +//! documents itself; it asks the host only to seal and open their two +//! ciphertexts. [`ContactInfoCrypto`] answers those two calls from the wallet +//! seed the secret seam lends for one operation. The child keys come from +//! platform-wallet's own `derive_contact_info_keys`, the AES steps from the +//! `platform-encryption` crate it uses, so both sides always agree. + +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; + +use dash_sdk::dpp::dashcore::Network; +use dash_sdk::dpp::identity::accessors::IdentityGettersV0; +use dash_sdk::dpp::key_wallet::bip32::{ + ChildNumber, DerivationPath, ExtendedPubKey, KeyDerivationType, +}; +use dash_sdk::dpp::key_wallet::wallet::Wallet; +use dash_sdk::dpp::key_wallet::wallet::initialization::WalletAccountCreationOptions; +use dash_sdk::dpp::secp256k1::{PublicKey, SecretKey}; +use dash_sdk::platform::{Document, Identifier}; +use platform_wallet::error::PlatformWalletError; +use platform_wallet::wallet::identity::crypto::contact_info::{ + ContactInfoKeys, derive_contact_info_keys, +}; +use platform_wallet::wallet::identity::crypto::decode_private_data; +use platform_wallet::wallet::identity::network::{ + ContactCryptoProvider, ContactInfoOpened, ContactInfoPublishOutcome, ContactInfoSealed, + identity_auth_derivation_path_for_type, +}; +use zeroize::Zeroizing; + +use crate::backend_task::error::TaskError; +use crate::model::dashpay::ContactDetails; +use crate::model::qualified_identity::QualifiedIdentity; +use crate::wallet_backend::{SecretScope, WalletBackend}; + +impl WalletBackend { + /// Refresh the contact details platform-wallet holds for the identities + /// of the wallet that manages `owner`. Does nothing when no wallet does. + pub(crate) async fn dashpay_sync_contact_infos( + &self, + owner: &Identifier, + ) -> Result<(), TaskError> { + let Some(wallet) = self.find_wallet_for_identity(owner).await else { + return Ok(()); + }; + wallet + .identity() + .dashpay() + .sync_contact_infos() + .await + .map(|_| ()) + .map_err(|source| TaskError::WalletBackend { + source: Arc::new(source), + }) + } + + /// The details platform-wallet holds for each of `owner`'s established + /// contacts. Empty when no wallet manages `owner`. + pub(crate) async fn dashpay_contact_details( + &self, + owner: &Identifier, + ) -> BTreeMap { + let Some(wallet) = self.find_wallet_for_identity(owner).await else { + return BTreeMap::new(); + }; + let state = wallet.state().await; + let Some(managed) = state.identity_manager.managed_identity(owner) else { + return BTreeMap::new(); + }; + managed + .dashpay() + .established_contacts() + .values() + .map(|contact| { + ( + contact.contact_identity_id, + ContactDetails { + nickname: contact.alias.clone(), + note: contact.note.clone(), + hidden: contact.is_hidden, + }, + ) + }) + .collect() + } + + /// Save `details` for `contact_id` and publish them through + /// platform-wallet, which writes the identity's `contactInfo` document. + /// + /// # Errors + /// + /// Before platform-wallet changes anything: the identity is not managed + /// by its DashPay wallet or has no wallet identity index + /// ([`TaskError::ContactInfoIdentityNotFromWallet`]), or `contact_id` is + /// not an established contact + /// ([`TaskError::ContactInfoContactNotEstablished`]). A failed publish is + /// [`TaskError::DashPayContactInfoWriteFailed`]. + pub(crate) async fn dashpay_set_contact_info( + &self, + identity: &QualifiedIdentity, + contact_id: &Identifier, + details: ContactDetails, + ) -> Result { + let owner = identity.identity.id(); + let seed_hash = identity + .dashpay_wallet_seed_hash() + .ok_or(TaskError::ContactInfoIdentityNotFromWallet)?; + let wallet = self.resolve_wallet(&seed_hash).await?; + let identity_index = { + let state = wallet.state().await; + let managed = state.identity_manager.managed_identity(&owner); + contact_info_write_index( + managed.and_then(|managed| managed.identity_index), + managed.is_some_and(|managed| { + managed + .dashpay() + .established_contacts() + .contains_key(contact_id) + }), + )? + }; + let network = identity.network; + let identity_wallet = wallet.identity(); + let dashpay = identity_wallet.dashpay(); + + self.secret_access() + .with_secret_session(&SecretScope::HdSeed { seed_hash }, async |session| { + let plaintext = session.plaintext(); + let seed = plaintext + .expose_hd_seed() + .ok_or(TaskError::ContactWalletSeedUnavailable)?; + let crypto = ContactInfoCrypto::new(seed, network, identity_index); + dashpay + .set_contact_info_with_external_signer( + &owner, + contact_id, + details.nickname, + details.note, + details.hidden, + identity, + &crypto, + ) + .await + .map_err(|source| TaskError::DashPayContactInfoWriteFailed { + source: Arc::new(source), + }) + }) + .await + } +} + +#[cfg(test)] +impl WalletBackend { + /// Set the details platform-wallet holds for `contact_id`, as a sync from + /// another device would, without publishing anything. + pub(crate) async fn set_contact_details_for_tests( + &self, + seed_hash: &crate::model::wallet::WalletSeedHash, + owner: &Identifier, + contact_id: &Identifier, + details: ContactDetails, + ) { + use platform_wallet::wallet::identity::crypto::ContactInfoPrivateData; + let wallet = self.resolve_wallet(seed_hash).await.expect("wallet"); + let persister = wallet.persister().clone(); + let mut manager = wallet.wallet_manager().write().await; + let applied = manager + .get_wallet_info_mut(&wallet.wallet_id()) + .and_then(|info| info.identity_manager.managed_identity_mut(owner)) + .expect("managed identity") + .set_contact_metadata( + contact_id, + ContactInfoPrivateData { + alias_name: details.nickname, + note: details.note, + display_hidden: details.hidden, + accepted_accounts: Vec::new(), + }, + &persister, + ) + .expect("metadata saved"); + assert!(applied, "the contact must be established"); + } +} + +impl WalletBackend { + /// The details `identity`'s DIP-0015 `contactInfo` documents hold, read + /// with platform-wallet's keys and codec; `documents` are oldest first and + /// the newest per contact wins. Documents that do not open — legacy-key + /// ones, or another client's — are skipped. Empty when the identity has + /// no wallet or wallet identity index, so none can be DIP-0015 ones. + /// + /// # Errors + /// + /// The identity's wallet is not loaded or not registered + /// ([`TaskError::WalletNotLoaded`], [`TaskError::WalletLockedNotLoaded`], + /// [`TaskError::WalletStateInconsistent`]), or the seed could not be used, + /// for example because the password prompt was cancelled. + pub(crate) async fn dashpay_open_contact_infos( + &self, + identity: &QualifiedIdentity, + documents: &[Document], + ) -> Result { + if documents.is_empty() { + return Ok(PublishedContactInfos::default()); + } + let Some(seed_hash) = identity.dashpay_wallet_seed_hash() else { + return Ok(PublishedContactInfos::default()); + }; + // A wallet that cannot be resolved is an error: a save keeps every + // field it does not replace from this read, so an empty result here + // would publish empty fields. Display callers degrade explicitly. + let wallet = self.resolve_wallet(&seed_hash).await?; + let owner = identity.identity.id(); + let identity_index = { + let state = wallet.state().await; + state + .identity_manager + .managed_identity(&owner) + .and_then(|managed| managed.identity_index) + }; + let Some(identity_index) = identity_index else { + return Ok(PublishedContactInfos::default()); + }; + let network = identity.network; + self.secret_access() + .with_secret_session(&SecretScope::HdSeed { seed_hash }, async |session| { + let plaintext = session.plaintext(); + let seed = plaintext + .expose_hd_seed() + .ok_or(TaskError::ContactWalletSeedUnavailable)?; + let crypto = ContactInfoCrypto::new(seed, network, identity_index); + Ok(open_contact_info_documents(&crypto, documents).await) + }) + .await + } +} + +/// The details published `contactInfo` documents hold, from the newest +/// document per contact. +#[derive(Debug, Default, PartialEq)] +pub(crate) struct PublishedContactInfos { + details: BTreeMap, + /// Contacts whose newest document opens to their id but whose details do + /// not decrypt or decode. It may also hold ids of no contact, from + /// documents sealed under another key. + unreadable: BTreeSet, +} + +impl PublishedContactInfos { + /// Take the published details for `contact_id`, and whether they are + /// unreadable. Unreadable details stand in as hidden: their hidden flag + /// cannot be read, and must not be taken as cleared. + pub(crate) fn take(&mut self, contact_id: &Identifier) -> Option<(ContactDetails, bool)> { + if self.unreadable.remove(contact_id) { + let hidden = ContactDetails { + hidden: true, + ..Default::default() + }; + return Some((hidden, true)); + } + self.details + .remove(contact_id) + .map(|details| (details, false)) + } +} + +/// Open `documents` (oldest first) through `crypto`; the newest document per +/// contact wins, readable or not. +// TODO(upstream): https://github.com/dashpay/platform/issues/5595 — replace +// with a platform-wallet contactInfo-only, provider-backed read for seedless +// wallets once one exists; platform-wallet's own drain is crate-private and +// runs unrelated contact work. +async fn open_contact_info_documents( + crypto: &ContactInfoCrypto<'_>, + documents: &[Document], +) -> PublishedContactInfos { + let mut opened = PublishedContactInfos::default(); + for document in documents { + let Some(stored) = StoredContactInfo::of(document) else { + continue; + }; + let Ok(root_path) = identity_auth_derivation_path_for_type( + crypto.network, + KeyDerivationType::ECDSA, + crypto.identity_index, + stored.root_index, + ) else { + continue; + }; + let (contact_id, data) = match crypto + .contact_info_open( + &root_path, + stored.derivation_index, + &stored.enc_to_user_id, + stored.private_data, + ) + .await + { + Ok(contact) => ( + contact.contact_id, + decode_private_data(&contact.private_data).ok(), + ), + // The contact id still opens: the document is that contact's, + // with details that do not decrypt. + Err(_) => match crypto.keys(&root_path, stored.derivation_index) { + Ok(keys) => ( + platform_encryption::decrypt_enc_to_user_id( + &keys.enc_to_user_id_key, + &stored.enc_to_user_id, + ), + None, + ), + Err(_) => continue, + }, + }; + let contact_id = Identifier::from(contact_id); + match data { + Some(data) => { + opened.unreadable.remove(&contact_id); + opened.details.insert( + contact_id, + ContactDetails { + nickname: data.alias_name, + note: data.note, + hidden: data.display_hidden, + }, + ); + } + None => { + opened.details.remove(&contact_id); + opened.unreadable.insert(contact_id); + } + } + } + opened +} + +/// The `contactInfo` fields a read needs. +struct StoredContactInfo<'a> { + root_index: u32, + derivation_index: u32, + enc_to_user_id: [u8; 32], + private_data: &'a [u8], +} + +impl<'a> StoredContactInfo<'a> { + fn of(document: &'a Document) -> Option { + use dash_sdk::dpp::document::DocumentV0Getters; + use dash_sdk::dpp::platform_value::Value; + let properties = document.properties(); + let index = |name: &str| properties.get(name)?.to_integer::().ok(); + let bytes = |name: &str| match properties.get(name)? { + Value::Bytes(bytes) => Some(bytes.as_slice()), + Value::Bytes32(bytes) => Some(bytes.as_slice()), + _ => None, + }; + Some(Self { + root_index: index("rootEncryptionKeyIndex")?, + derivation_index: index("derivationEncryptionKeyIndex")?, + enc_to_user_id: bytes("encToUserId")?.try_into().ok()?, + private_data: bytes("privateData")?, + }) + } +} + +/// The wallet identity index a contact details write derives beneath, +/// checked before platform-wallet changes any local state. +fn contact_info_write_index( + identity_index: Option, + contact_is_established: bool, +) -> Result { + let identity_index = identity_index.ok_or(TaskError::ContactInfoIdentityNotFromWallet)?; + if !contact_is_established { + return Err(TaskError::ContactInfoContactNotEstablished); + } + Ok(identity_index) +} + +/// Seals and opens `contactInfo` ciphertexts for one wallet identity. +/// +/// Holds a borrow of the seed for one operation only; it never copies the +/// seed out of that operation. +pub(crate) struct ContactInfoCrypto<'a> { + seed: &'a [u8; 64], + network: Network, + identity_index: u32, +} + +impl<'a> ContactInfoCrypto<'a> { + pub(crate) fn new(seed: &'a [u8; 64], network: Network, identity_index: u32) -> Self { + Self { + seed, + network, + identity_index, + } + } + + /// The two AES keys beneath `root_path`, derived by platform-wallet. + /// + /// `root_path` must be one of this identity's key paths: any other root is + /// refused, so a request can never select another identity's keys. + #[expect( + clippy::result_large_err, + reason = "ContactCryptoProvider fixes PlatformWalletError as the error type" + )] + fn keys( + &self, + root_path: &DerivationPath, + derivation_index: u32, + ) -> Result { + let key_id = match root_path.len().checked_sub(1).map(|last| root_path[last]) { + Some(ChildNumber::Hardened { index }) => index, + _ => return Err(foreign_root()), + }; + let own_root = identity_auth_derivation_path_for_type( + self.network, + KeyDerivationType::ECDSA, + self.identity_index, + key_id, + )?; + if own_root != *root_path { + return Err(foreign_root()); + } + let wallet = + Wallet::from_seed_bytes(*self.seed, self.network, WalletAccountCreationOptions::None) + .map_err(|error| PlatformWalletError::KeyDerivation(error.to_string()))?; + derive_contact_info_keys( + &wallet, + self.network, + self.identity_index, + key_id, + derivation_index, + ) + } +} + +fn foreign_root() -> PlatformWalletError { + PlatformWalletError::InvalidParameter( + "contactInfo root is not a key path of this identity".to_string(), + ) +} + +/// The provider serves `contactInfo` only; contact requests, invitations and +/// auto-accept keys go through their own paths. +fn not_contact_info() -> PlatformWalletError { + PlatformWalletError::InvalidParameter( + "this crypto provider serves contactInfo only".to_string(), + ) +} + +#[async_trait::async_trait] +impl ContactCryptoProvider for ContactInfoCrypto<'_> { + async fn receiving_xpub( + &self, + _path: &DerivationPath, + ) -> Result { + Err(not_contact_info()) + } + + async fn ecdh_shared_secret( + &self, + _path: &DerivationPath, + _peer: &PublicKey, + ) -> Result, PlatformWalletError> { + Err(not_contact_info()) + } + + async fn export_auto_accept_private_key( + &self, + _path: &DerivationPath, + ) -> Result { + Err(not_contact_info()) + } + + async fn export_invitation_private_key( + &self, + _path: &DerivationPath, + ) -> Result { + Err(not_contact_info()) + } + + async fn account_reference( + &self, + _path: &DerivationPath, + _compact_xpub: &[u8], + _account_index: u32, + _version: u32, + ) -> Result { + Err(not_contact_info()) + } + + async fn unmask_account_reference( + &self, + _path: &DerivationPath, + _compact_xpub: &[u8], + _account_reference: u32, + ) -> Result<(u32, u32), PlatformWalletError> { + Err(not_contact_info()) + } + + async fn contact_info_seal( + &self, + root_path: &DerivationPath, + derivation_index: u32, + contact_id: &[u8; 32], + private_data_plaintext: &[u8], + private_data_iv: &[u8; 16], + ) -> Result { + let keys = self.keys(root_path, derivation_index)?; + Ok(ContactInfoSealed { + enc_to_user_id: platform_encryption::encrypt_enc_to_user_id( + &keys.enc_to_user_id_key, + contact_id, + ), + private_data: platform_encryption::encrypt_private_data( + &keys.private_data_key, + private_data_iv, + private_data_plaintext, + ), + }) + } + + async fn contact_info_open( + &self, + root_path: &DerivationPath, + derivation_index: u32, + enc_to_user_id: &[u8; 32], + private_data_blob: &[u8], + ) -> Result { + let keys = self.keys(root_path, derivation_index)?; + let private_data = + platform_encryption::decrypt_private_data(&keys.private_data_key, private_data_blob) + .map_err(|error| { + PlatformWalletError::InvalidIdentityData(format!( + "contactInfo privateData could not be decrypted: {error}" + )) + })?; + Ok(ContactInfoOpened { + contact_id: platform_encryption::decrypt_enc_to_user_id( + &keys.enc_to_user_id_key, + enc_to_user_id, + ), + private_data, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Generated each run, so no seed bytes are committed. + static SEED: std::sync::LazyLock<[u8; 64]> = std::sync::LazyLock::new(rand::random); + const NETWORK: Network = Network::Testnet; + const IDENTITY_INDEX: u32 = 1; + + fn root(identity_index: u32, key_id: u32) -> DerivationPath { + identity_auth_derivation_path_for_type( + NETWORK, + KeyDerivationType::ECDSA, + identity_index, + key_id, + ) + .expect("root path") + } + + fn upstream_keys(key_id: u32, derivation_index: u32) -> ContactInfoKeys { + let wallet = Wallet::from_seed_bytes(*SEED, NETWORK, WalletAccountCreationOptions::None) + .expect("wallet"); + derive_contact_info_keys(&wallet, NETWORK, IDENTITY_INDEX, key_id, derivation_index) + .expect("upstream keys") + } + + /// What this provider seals, platform-wallet's own keys open: the + /// documents are readable by every client that uses platform-wallet. + #[tokio::test] + async fn sealed_details_open_with_platform_wallet_keys() { + let crypto = ContactInfoCrypto::new(&SEED, NETWORK, IDENTITY_INDEX); + let contact = [7u8; 32]; + let iv = [3u8; 16]; + + let sealed = crypto + .contact_info_seal(&root(IDENTITY_INDEX, 2), 5, &contact, b"note", &iv) + .await + .expect("seal"); + + let keys = upstream_keys(2, 5); + assert_eq!( + platform_encryption::decrypt_enc_to_user_id( + &keys.enc_to_user_id_key, + &sealed.enc_to_user_id + ), + contact + ); + assert_eq!( + platform_encryption::decrypt_private_data(&keys.private_data_key, &sealed.private_data) + .expect("decrypt"), + b"note" + ); + } + + /// A document platform-wallet sealed opens here. + #[tokio::test] + async fn opens_what_platform_wallet_sealed() { + let crypto = ContactInfoCrypto::new(&SEED, NETWORK, IDENTITY_INDEX); + let keys = upstream_keys(2, 0); + let contact = [9u8; 32]; + let enc = platform_encryption::encrypt_enc_to_user_id(&keys.enc_to_user_id_key, &contact); + let blob = + platform_encryption::encrypt_private_data(&keys.private_data_key, &[1; 16], b"alias"); + + let opened = crypto + .contact_info_open(&root(IDENTITY_INDEX, 2), 0, &enc, &blob) + .await + .expect("open"); + + assert_eq!(opened.contact_id, contact); + assert_eq!(opened.private_data, b"alias"); + } + + fn stored_document( + id: u8, + key_id: u32, + derivation_index: u32, + sealed: &ContactInfoSealed, + ) -> Document { + use dash_sdk::dpp::document::DocumentV0; + use dash_sdk::dpp::platform_value::Value; + Document::V0(DocumentV0 { + id: Identifier::from([id; 32]), + properties: BTreeMap::from([ + ("rootEncryptionKeyIndex".to_string(), Value::U32(key_id)), + ( + "derivationEncryptionKeyIndex".to_string(), + Value::U32(derivation_index), + ), + ( + "encToUserId".to_string(), + Value::Bytes(sealed.enc_to_user_id.to_vec()), + ), + ( + "privateData".to_string(), + Value::Bytes(sealed.private_data.clone()), + ), + ]), + ..Default::default() + }) + } + + async fn sealed( + crypto: &ContactInfoCrypto<'_>, + derivation_index: u32, + contact: [u8; 32], + details: ContactDetails, + ) -> ContactInfoSealed { + use platform_wallet::wallet::identity::crypto::{ + ContactInfoPrivateData, encode_private_data, + }; + let plaintext = encode_private_data(&ContactInfoPrivateData { + alias_name: details.nickname, + note: details.note, + display_hidden: details.hidden, + accepted_accounts: Vec::new(), + }); + crypto + .contact_info_seal( + &root(IDENTITY_INDEX, 2), + derivation_index, + &contact, + &plaintext, + &[4; 16], + ) + .await + .expect("seal") + } + + /// SEC-003: DIP-0015 documents are read back without platform-wallet + /// holding the seed; the newest per contact wins, and documents that do + /// not open (another key root, or garbage) give no details and are not + /// fatal. + #[tokio::test] + async fn dip15_documents_are_read_back_newest_first() { + let crypto = ContactInfoCrypto::new(&SEED, NETWORK, IDENTITY_INDEX); + let note = |text: &str| ContactDetails { + note: Some(text.into()), + ..Default::default() + }; + let older = sealed(&crypto, 0, [7; 32], note("older")).await; + let newer = sealed(&crypto, 1, [7; 32], note("newer")).await; + let hidden = sealed( + &crypto, + 2, + [8; 32], + ContactDetails { + hidden: true, + ..Default::default() + }, + ) + .await; + let unreadable = ContactInfoSealed { + enc_to_user_id: [1; 32], + private_data: vec![9; 48], + }; + let documents = [ + stored_document(1, 2, 0, &older), + stored_document(2, 2, 9, &unreadable), + stored_document(3, 2, 1, &newer), + stored_document(4, 2, 2, &hidden), + ]; + + let opened = open_contact_info_documents(&crypto, &documents).await; + + assert_eq!( + opened.details, + BTreeMap::from([ + (Identifier::from([7; 32]), note("newer")), + ( + Identifier::from([8; 32]), + ContactDetails { + hidden: true, + ..Default::default() + } + ), + ]) + ); + } + + /// A newest document that names its contact but whose details do not + /// decrypt or decode is not skipped in favour of an older readable one: + /// the contact stays hidden, marked unreadable, since its hidden flag + /// cannot be read. + #[tokio::test] + async fn an_unreadable_newest_document_keeps_its_contact_hidden() { + let crypto = ContactInfoCrypto::new(&SEED, NETWORK, IDENTITY_INDEX); + let shown = ContactDetails { + note: Some("older".into()), + ..Default::default() + }; + let older = sealed(&crypto, 0, [7; 32], shown.clone()).await; + let mut undecryptable = sealed(&crypto, 1, [7; 32], shown.clone()).await; + undecryptable.private_data = vec![9; 48]; + let older_other = sealed(&crypto, 2, [8; 32], shown.clone()).await; + let undecodable = { + let keys = crypto + .keys(&root(IDENTITY_INDEX, 2), 3) + .expect("own root keys"); + ContactInfoSealed { + enc_to_user_id: platform_encryption::encrypt_enc_to_user_id( + &keys.enc_to_user_id_key, + &[8; 32], + ), + private_data: platform_encryption::encrypt_private_data( + &keys.private_data_key, + &[4; 16], + &[0xFF; 40], + ), + } + }; + let documents = [ + stored_document(1, 2, 0, &older), + stored_document(2, 2, 1, &undecryptable), + stored_document(3, 2, 2, &older_other), + stored_document(4, 2, 3, &undecodable), + ]; + + let mut opened = open_contact_info_documents(&crypto, &documents).await; + + let hidden = ContactDetails { + hidden: true, + ..Default::default() + }; + for contact in [[7; 32], [8; 32]] { + assert_eq!( + opened.take(&Identifier::from(contact)), + Some((hidden.clone(), true)), + "{contact:?}" + ); + } + } + + /// A root that belongs to another wallet identity is refused. + #[tokio::test] + async fn another_identitys_root_is_refused() { + let crypto = ContactInfoCrypto::new(&SEED, NETWORK, IDENTITY_INDEX); + let result = crypto + .contact_info_seal(&root(IDENTITY_INDEX + 1, 2), 0, &[0; 32], b"", &[0; 16]) + .await; + assert!(matches!( + result, + Err(PlatformWalletError::InvalidParameter(_)) + )); + } + + /// A write is refused before platform-wallet runs when the identity has no + /// wallet index or the contact is not established. + #[test] + fn a_write_needs_a_wallet_identity_and_an_established_contact() { + assert!(matches!( + contact_info_write_index(None, true), + Err(TaskError::ContactInfoIdentityNotFromWallet) + )); + assert!(matches!( + contact_info_write_index(Some(3), false), + Err(TaskError::ContactInfoContactNotEstablished) + )); + assert_eq!(contact_info_write_index(Some(3), true).expect("index"), 3); + } + + /// An identity whose wallet cannot be resolved is + /// an error, not "no details published". A save reads this baseline for + /// every field it keeps, so an empty one would publish empty fields. + #[tokio::test] + async fn an_unresolved_wallet_is_an_error_not_an_empty_baseline() { + use crate::model::wallet::Wallet as DetWallet; + use std::sync::RwLock; + let dir = tempfile::tempdir().expect("temp dir"); + let context = crate::context::test_support::wired_test_app_context(dir.path()).await; + let backend = context.wallet_backend().expect("backend wired"); + let wallet = DetWallet::new_from_seed(*SEED, NETWORK, None, None).expect("wallet"); + let mut identity = + crate::context::test_support::bare_user_identity(Identifier::from([5; 32]), NETWORK); + identity.associated_wallets = + BTreeMap::from([(wallet.seed_hash(), Arc::new(RwLock::new(wallet)))]); + let crypto = ContactInfoCrypto::new(&SEED, NETWORK, IDENTITY_INDEX); + let sealed = crypto + .contact_info_seal(&root(IDENTITY_INDEX, 2), 0, &[7; 32], b"", &[0; 16]) + .await + .expect("seal"); + + let result = backend + .dashpay_open_contact_infos(&identity, &[stored_document(1, 2, 0, &sealed)]) + .await; + + assert!( + matches!(result, Err(TaskError::WalletNotLoaded { .. })), + "{result:?}" + ); + } + + /// Everything other than contactInfo is refused rather than served. + #[tokio::test] + async fn other_crypto_requests_are_refused() { + let crypto = ContactInfoCrypto::new(&SEED, NETWORK, IDENTITY_INDEX); + let path = root(IDENTITY_INDEX, 0); + assert!(crypto.receiving_xpub(&path).await.is_err()); + assert!(crypto.export_auto_accept_private_key(&path).await.is_err()); + assert!(crypto.export_invitation_private_key(&path).await.is_err()); + assert!(crypto.account_reference(&path, &[], 0, 0).await.is_err()); + assert!( + crypto + .unmask_account_reference(&path, &[], 0) + .await + .is_err() + ); + } +} diff --git a/src/wallet_backend/dashpay.rs b/src/wallet_backend/dashpay.rs index 73a35aeec..d6fabf10e 100644 --- a/src/wallet_backend/dashpay.rs +++ b/src/wallet_backend/dashpay.rs @@ -36,7 +36,6 @@ use dash_sdk::dpp::dashcore::Network; use dash_sdk::dpp::key_wallet::wallet::Wallet; use dash_sdk::dpp::key_wallet::wallet::initialization::WalletAccountCreationOptions; use dash_sdk::platform::Identifier; -use serde::{Deserialize, Serialize}; use zeroize::Zeroizing; use platform_wallet::wallet::identity::types::dashpay::contact_request::ContactRequest; @@ -222,8 +221,14 @@ const KV_PREFIX_DECLINED: &str = "det:dashpay:declined:"; /// opposite directions: withdrawing our request to Bob says nothing about a /// request Bob later sends us, and a single marker would silently hide it. const KV_PREFIX_WITHDRAWN: &str = "det:dashpay:withdrawn:"; -/// Durable recovery journal for paid decline/cancel visibility transitions. -/// Value: [`ContactRequestActionPhase`]. Scope: the acting identity. +/// Presence marker: platform-wallet holds `owner`'s details for this contact, +/// so a legacy-key `contactInfo` document no longer stands in for them — not +/// even when those details are empty because the user cleared them. +/// Scope: the owner identity. +const KV_PREFIX_DETAILS_SYNCED: &str = "det:dashpay:details_synced:"; +/// Recovery journal older versions kept while a decline or withdrawal wrote +/// contact details. Declines and withdrawals only clear it. Scope: the +/// acting identity. const KV_PREFIX_REQUEST_ACTION: &str = "det:dashpay:request_action:"; /// DET-local `(created_at, updated_at)` timestamps for an entity (contact, request). /// Value: `(i64, i64)` encoded by the [`DetKv`] schema. Scope: [`DetScope::Global`]. @@ -324,7 +329,9 @@ impl ContactRequestActionKind { } } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +/// The journal value older versions stored; tests seed such records. +#[cfg(test)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub(crate) enum ContactRequestActionPhase { HideIntent, HideCommitted, @@ -382,6 +389,23 @@ impl ContactRequestActionLocks { } } +/// `owner`'s request-action lock for `peer`, held while this lives. The lock +/// is not reentrant, so code running under it is handed this instead of +/// locking again. Only [`WalletBackend::dashpay_lock_contact_peer`] mints it, +/// so the pair it names is the pair it locks. +pub(crate) struct HeldPeerLock { + owner: Identifier, + peer: Identifier, + _guard: tokio::sync::OwnedMutexGuard<()>, +} + +impl HeldPeerLock { + /// Whether this is `owner`'s lock for `peer`. + pub(crate) fn covers(&self, owner: &Identifier, peer: &Identifier) -> bool { + self.owner == *owner && self.peer == *peer + } +} + /// Contact-request expiry threshold. A pending outgoing request older /// than this is surfaced as `"expired"` rather than `"pending"`. DET /// has no protocol-level expiry — this is purely a UX gate so the @@ -899,6 +923,21 @@ fn kv_contains(kv: &DetKv, owner: &Identifier, prefix: &str, counterparty: &Iden ) } +/// Whether `owner`'s marker for `counterparty` exists, whatever its value +/// encodes. Unlike [`kv_contains`], a failed read is an error, not absence. +fn kv_marker_present( + kv: &DetKv, + owner: &Identifier, + prefix: &str, + counterparty: &Identifier, +) -> Result { + let owner_buf = owner.to_buffer(); + kv.contains( + DetScope::Identity(&owner_buf), + &sidecar_key(prefix, counterparty), + ) +} + fn kv_timestamps(kv: &DetKv, id: &Identifier) -> (i64, i64) { let key = sidecar_key(KV_PREFIX_TIMESTAMPS, id); kv_get_or_default(kv, DetScope::Global, &key, "dashpay_contact_timestamps") @@ -1051,6 +1090,14 @@ impl WalletBackend { }; let identity = wallet.identity(); let dashpay = identity.dashpay(); + // TODO(dashpay auto-accept): `sync_contact_requests` queues an + // `AutoAccept` op for every incoming request that carries a DIP-0015 + // `autoAcceptProof`, but DET never drains that queue, so requests + // from scanned contact QR codes wait for a manual accept. Wire + // `PlatformWallet::drain_pending_contact_crypto_verified(provider, + // Some(signer), deadline)` after this sync; it needs a full + // seed-backed `ContactCryptoProvider` (receiving xpub, ECDH, + // accountReference), not the narrow `AutoAcceptKeyExport`. dashpay.sync_contact_requests().await.map_err(|e| { crate::backend_task::error::TaskError::WalletBackend { source: Arc::new(e), @@ -1174,6 +1221,66 @@ impl WalletBackend { self.put_marker(owner, KV_PREFIX_DECLINED, counterparty_id) } + /// Ignore `sender`'s contact requests in platform-wallet, as declining + /// does. Local only: nothing is published, so the decline stays on this + /// device. Does nothing when no wallet manages `owner`. + pub(crate) async fn dashpay_ignore_contact_sender( + &self, + owner: &Identifier, + sender: &Identifier, + ) -> Result<(), TaskError> { + let Some(wallet) = self.find_wallet_for_identity(owner).await else { + return Ok(()); + }; + wallet + .identity() + .dashpay() + .ignore_contact_sender(owner, sender) + .await + .map_err(|source| TaskError::WalletBackend { + source: Arc::new(source), + }) + } + + /// Whether platform-wallet ignores `sender`'s contact requests for + /// `owner`. `false` when no wallet manages `owner`. + pub(crate) async fn dashpay_sender_ignored( + &self, + owner: &Identifier, + sender: &Identifier, + ) -> bool { + let Some(wallet) = self.find_wallet_for_identity(owner).await else { + return false; + }; + wallet + .state() + .await + .identity_manager + .managed_identity(owner) + .is_some_and(|managed| managed.is_sender_ignored(sender)) + } + + /// Undo [`Self::dashpay_ignore_contact_sender`]: platform-wallet skips an + /// ignored sender's requests entirely, so re-engaging with them must + /// lift the ignore or their reply never establishes the contact. + pub(crate) async fn dashpay_unignore_contact_sender( + &self, + owner: &Identifier, + sender: &Identifier, + ) -> Result<(), TaskError> { + let Some(wallet) = self.find_wallet_for_identity(owner).await else { + return Ok(()); + }; + wallet + .identity() + .dashpay() + .unignore_contact_sender(owner, sender) + .await + .map_err(|source| TaskError::WalletBackend { + source: Arc::new(source), + }) + } + /// Whether `owner` declined the incoming contact request from /// `counterparty_id`. Reads the same owner-scoped marker /// [`dashpay_mark_declined`](Self::dashpay_mark_declined) writes. @@ -1185,6 +1292,23 @@ impl WalletBackend { kv_contains(&self.kv(), owner, KV_PREFIX_DECLINED, counterparty_id) } + /// [`Self::dashpay_is_declined`] for a decision that changes state: a + /// failed read is an error, not "not declined". + pub(crate) fn dashpay_decline_recorded( + &self, + owner: &Identifier, + counterparty_id: &Identifier, + ) -> Result { + kv_marker_present(&self.kv(), owner, KV_PREFIX_DECLINED, counterparty_id) + .map_err(|source| TaskError::DashPayLocalStateRead { source }) + } + + /// Whether `owner` withdrew their request to `peer` or declined `peer`'s: + /// either keeps the pair from being contacts until the owner re-engages. + pub fn dashpay_disengaged_from(&self, owner: &Identifier, peer: &Identifier) -> bool { + self.dashpay_is_withdrawn(owner, peer) || self.dashpay_is_declined(owner, peer) + } + /// Clear `owner`'s decline marker for `counterparty_id`. Idempotent — /// clearing an absent marker is `Ok(())`. /// @@ -1222,6 +1346,46 @@ impl WalletBackend { kv_contains(&self.kv(), owner, KV_PREFIX_WITHDRAWN, counterparty_id) } + /// [`Self::dashpay_is_withdrawn`] for a decision that changes state: a + /// failed read is an error, not "not withdrawn". + pub(crate) fn dashpay_withdrawal_recorded( + &self, + owner: &Identifier, + counterparty_id: &Identifier, + ) -> Result { + kv_marker_present(&self.kv(), owner, KV_PREFIX_WITHDRAWN, counterparty_id) + .map_err(|source| TaskError::DashPayLocalStateRead { source }) + } + + /// Ignore `peer` for `owner` unless platform-wallet has established the + /// contact; returns whether the ignore stands. + /// + /// Establishing a contact and ignoring a sender each take platform-wallet's + /// wallet lock, and once `peer` is ignored their requests are no longer + /// ingested and their pending one is dropped. So a contact found + /// established after the ignore was established before it: the ignore lost + /// the race, and is lifted again. + pub(crate) async fn dashpay_ignore_unless_established( + &self, + owner: &Identifier, + peer: &Identifier, + ) -> Result { + self.dashpay_ignore_contact_sender(owner, peer).await?; + let Some(wallet) = self.find_wallet_for_identity(owner).await else { + return Ok(true); + }; + let established = wallet + .state() + .await + .identity_manager + .managed_identity(owner) + .is_some_and(|managed| managed.dashpay().established_contacts().contains_key(peer)); + if established { + self.dashpay_unignore_contact_sender(owner, peer).await?; + } + Ok(!established) + } + /// Clear `owner`'s withdrawal marker for `counterparty_id`. Idempotent — /// clearing an absent marker is `Ok(())`. Re-sending a request to the same /// person retires the earlier withdrawal, so the fresh request lists. @@ -1233,21 +1397,33 @@ impl WalletBackend { self.delete_marker(owner, KV_PREFIX_WITHDRAWN, counterparty_id) } - pub(crate) fn dashpay_contact_request_action_phase( + /// Record that platform-wallet holds `owner`'s details for `contact_id`; + /// see [`KV_PREFIX_DETAILS_SYNCED`]. Idempotent. + pub(crate) fn dashpay_mark_details_synced( &self, owner: &Identifier, - request_id: &Identifier, - kind: ContactRequestActionKind, - ) -> Result, TaskError> { - let owner_buf = owner.to_buffer(); - self.kv() - .get( - DetScope::Identity(&owner_buf), - &request_action_key(kind, request_id), - ) - .map_err(|source| TaskError::DashpaySidecarStorage { source }) + contact_id: &Identifier, + ) -> Result<(), TaskError> { + self.put_marker(owner, KV_PREFIX_DETAILS_SYNCED, contact_id) + } + + /// Whether platform-wallet holds `owner`'s details for `contact_id`. + /// + /// # Errors + /// + /// The marker could not be read; a save must not take that for absence, + /// or legacy details would stand in for ones the user cleared. + pub(crate) fn dashpay_details_synced( + &self, + owner: &Identifier, + contact_id: &Identifier, + ) -> Result { + kv_marker_present(&self.kv(), owner, KV_PREFIX_DETAILS_SYNCED, contact_id) + .map_err(|source| TaskError::DashPayLocalStateRead { source }) } + /// Serialize `owner`'s request actions keyed by `request_id`: a request + /// id, or the id of the person the requests are with. pub(crate) async fn dashpay_lock_contact_request_action( &self, owner: &Identifier, @@ -1259,21 +1435,19 @@ impl WalletBackend { .await } - pub(crate) fn dashpay_set_contact_request_action_phase( + /// [`Self::dashpay_lock_contact_request_action`] keyed by the person, + /// returned as a [`HeldPeerLock`] that code running under it is handed + /// instead of locking again. + pub(crate) async fn dashpay_lock_contact_peer( &self, owner: &Identifier, - request_id: &Identifier, - kind: ContactRequestActionKind, - phase: ContactRequestActionPhase, - ) -> Result<(), TaskError> { - let owner_buf = owner.to_buffer(); - self.kv() - .put( - DetScope::Identity(&owner_buf), - &request_action_key(kind, request_id), - &phase, - ) - .map_err(|source| TaskError::DashpaySidecarStorage { source }) + peer: &Identifier, + ) -> HeldPeerLock { + HeldPeerLock { + owner: *owner, + peer: *peer, + _guard: self.dashpay_lock_contact_request_action(owner, peer).await, + } } pub(crate) fn dashpay_clear_contact_request_action( @@ -1504,6 +1678,7 @@ impl WalletBackend { KV_PREFIX_DECLINED, KV_PREFIX_WITHDRAWN, KV_PREFIX_REQUEST_ACTION, + KV_PREFIX_DETAILS_SYNCED, ] { let keys = kv.list(scope, Some(prefix)).map_err(sidecar_err)?; for key in keys { @@ -1526,7 +1701,7 @@ impl WalletBackend { /// `identity_manager` for the id. `None` if no registered wallet /// knows about it (e.g. pre-registration, wrong network, observed- /// only identities that were never indexed). - async fn find_wallet_for_identity( + pub(super) async fn find_wallet_for_identity( &self, identity_id: &Identifier, ) -> Option> { @@ -2582,6 +2757,53 @@ mod tests { ); } + /// The synced and withdrawn markers are + /// read for presence only, so + /// a value in an unknown encoding still counts; a failed read is an error. + #[test] + fn a_marker_read_tells_failure_from_absence() { + for prefix in [KV_PREFIX_DETAILS_SYNCED, KV_PREFIX_WITHDRAWN] { + use platform_wallet_storage::{KvError, KvStore, ObjectId}; + + let store = Arc::new(crate::wallet_backend::kv_test_support::InMemoryKv::default()); + let kv = DetKv::from_store(store.clone()); + let (owner, contact) = (id_from_byte(1), id_from_byte(2)); + assert!(!kv_marker_present(&kv, &owner, prefix, &contact).unwrap()); + store + .put( + &ObjectId::Identity(owner.to_buffer()), + &sidecar_key(prefix, &contact), + &[crate::wallet_backend::kv::SCHEMA_VERSION.wrapping_add(1), 0], + ) + .unwrap(); + assert!( + kv_marker_present(&kv, &owner, prefix, &contact).unwrap(), + "a marker in an unknown encoding is still present" + ); + + struct UnreadableKv; + impl KvStore for UnreadableKv { + fn get(&self, _: &ObjectId, _: &str) -> Result>, KvError> { + Err(KvError::LockPoisoned) + } + fn put(&self, _: &ObjectId, _: &str, _: &[u8]) -> Result<(), KvError> { + Ok(()) + } + fn delete(&self, _: &ObjectId, _: &str) -> Result<(), KvError> { + Ok(()) + } + fn list_keys(&self, _: &ObjectId, _: Option<&str>) -> Result, KvError> { + Ok(Vec::new()) + } + } + let unreadable = DetKv::from_store(Arc::new(UnreadableKv)); + assert!( + kv_marker_present(&unreadable, &owner, prefix, &contact).is_err(), + "a failed read is not absence" + ); + } + } + /// F40: two identities that share a wallet must not see each other's /// blocked / declined markers. Identity A blocks/declines a counterparty; /// identity B's view of that same counterparty stays clean. @@ -3050,6 +3272,7 @@ mod tests { KV_PREFIX_DECLINED, KV_PREFIX_WITHDRAWN, KV_PREFIX_REQUEST_ACTION, + KV_PREFIX_DETAILS_SYNCED, ] { for k in kv.list(DetScope::Identity(&owner), Some(prefix)).unwrap() { kv.delete(DetScope::Identity(&owner), &k).unwrap(); @@ -3581,4 +3804,55 @@ mod tests { "the unselected wallet's seed must derive a different xpub" ); } + + /// `dashpay_sender_ignored` reads platform-wallet's ignore as decline, + /// withdrawal and their rollback leave it, and is `false` for an identity + /// no wallet manages. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn the_ignore_query_follows_ignore_and_unignore() { + use crate::model::wallet::Wallet; + use crate::model::wallet::birth_height::WalletOrigin; + use dash_sdk::dpp::dashcore::Network; + use dash_sdk::dpp::identity::Identity; + use dash_sdk::dpp::version::PlatformVersion; + + let dir = tempfile::tempdir().expect("temp dir"); + let context = crate::context::test_support::wired_test_app_context(dir.path()).await; + let backend = context.wallet_backend().expect("backend wired"); + let seed: [u8; 64] = rand::random(); + let wallet = + Wallet::new_from_seed(seed, Network::Testnet, Some("w".into()), None).expect("wallet"); + let (seed_hash, _wallet) = context + .register_wallet(wallet, &seed, WalletOrigin::Fresh) + .expect("register wallet"); + backend + .register_wallet_from_seed(&seed_hash, &seed, Some(0)) + .await + .expect("register upstream"); + let owner = id_from_byte(0x11); + let peer = id_from_byte(0x22); + let identity = + Identity::create_basic_identity(owner, PlatformVersion::latest()).expect("identity"); + backend + .ensure_identity_managed(&seed_hash, &identity, 0) + .await + .expect("manage identity"); + + assert!(!backend.dashpay_sender_ignored(&owner, &peer).await); + backend + .dashpay_ignore_contact_sender(&owner, &peer) + .await + .expect("ignore"); + assert!(backend.dashpay_sender_ignored(&owner, &peer).await); + backend + .dashpay_unignore_contact_sender(&owner, &peer) + .await + .expect("unignore"); + assert!(!backend.dashpay_sender_ignored(&owner, &peer).await); + assert!( + !backend + .dashpay_sender_ignored(&id_from_byte(0x33), &peer) + .await + ); + } } diff --git a/src/wallet_backend/mod.rs b/src/wallet_backend/mod.rs index 92d479605..438ec8be2 100644 --- a/src/wallet_backend/mod.rs +++ b/src/wallet_backend/mod.rs @@ -23,7 +23,9 @@ pub mod auth_pubkey_cache; #[cfg(not(any(test, feature = "bench")))] pub(crate) mod auth_pubkey_cache; +mod auto_accept; mod avatar_cache; +mod contact_info; mod contact_profile_cache; mod coordinator_gate; mod dashpay; @@ -80,10 +82,11 @@ pub(crate) mod wallet_seed_store; pub use dashpay::DashpayView; pub(crate) use dashpay::{ - ContactRequestActionKind, ContactRequestActionPhase, derive_contact_info_encryption_keys, + ContactRequestActionKind, HeldPeerLock, derive_contact_info_encryption_keys, derive_contact_xpub_material, }; +pub(crate) use contact_info::PublishedContactInfos; pub(crate) use det_platform_signer::{DetPlatformSigner, PlatformPathIndex}; pub(crate) use det_signer::{DetSigner, DetSignerError}; pub use identity_key_store::IdentityKeyView; diff --git a/tests/backend-e2e/dashpay_tasks.rs b/tests/backend-e2e/dashpay_tasks.rs index e2b2205dd..f497b86a9 100644 --- a/tests/backend-e2e/dashpay_tasks.rs +++ b/tests/backend-e2e/dashpay_tasks.rs @@ -19,9 +19,7 @@ use crate::framework::task_runner::{run_task, run_task_with_nonce_retry}; use dash_evo_tool::backend_task::dashpay::DashPayTask; use dash_evo_tool::backend_task::identity::IdentityTask; use dash_evo_tool::backend_task::{BackendTask, BackendTaskSuccessResult}; -use dash_evo_tool::model::dashpay::{ - ContactInfoUpdate, ProfileSnapshot, UnreadableContactInfoPolicy, -}; +use dash_evo_tool::model::dashpay::{ContactInfoUpdate, ProfileSnapshot}; use dash_evo_tool::model::qualified_identity::qualified_identity_public_key::QualifiedIdentityPublicKey; use dash_sdk::dpp::identity::accessors::IdentityGettersV0; use dash_sdk::dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeySettersV0; @@ -700,7 +698,6 @@ async fn step_update_contact_info( Some("Test Nickname".into()), Some("E2E note".into()), false, - vec![0], ), })); @@ -712,6 +709,7 @@ async fn step_update_contact_info( BackendTaskSuccessResult::DashPayContactInfoUpdated { identity, contact_id: id, + .. } => { assert_eq!(identity, identity_b_id, "update should belong to B"); assert_eq!( @@ -1111,7 +1109,6 @@ async fn tc_043_reject_contact_request() { let reject_task = BackendTask::DashPayTask(Box::new(DashPayTask::RejectContactRequest { identity: qi_c, request_id, - unreadable: UnreadableContactInfoPolicy::Abort, })); let reject_result = run_task(&ctx.app_context, reject_task) .await diff --git a/tests/kittest/identity_hub_contact_detail.rs b/tests/kittest/identity_hub_contact_detail.rs index ae70f0e17..d9adb4f77 100644 --- a/tests/kittest/identity_hub_contact_detail.rs +++ b/tests/kittest/identity_hub_contact_detail.rs @@ -12,9 +12,11 @@ use dash_evo_tool::backend_task::dashpay::{ContactData, DashPayTask}; use dash_evo_tool::backend_task::{BackendTask, BackendTaskContext, BackendTaskSuccessResult}; use dash_evo_tool::model::dashpay::ContactInfoField; use dash_evo_tool::ui::ScreenLike; +use dash_evo_tool::ui::components::MessageBanner; use dash_evo_tool::ui::identity::IdentityHubTab; use dash_evo_tool::ui::identity::contacts::{ - DETAIL_HEADING, NO_SELECTION, NOTE_HEADING, SAVE_NOTE_LABEL, SAVING_NOTE_LABEL, + DETAIL_HEADING, DETAILS_SAVED_ON_THIS_DEVICE, NO_SELECTION, NOTE_HEADING, NOTE_HINT, + NOTE_HINT_ON_THIS_DEVICE, NOTE_SAVED, SAVE_NOTE_LABEL, SAVING_NOTE_LABEL, }; use dash_sdk::platform::Identifier; use egui::accesskit::Role; @@ -57,11 +59,31 @@ fn deliver_all(hub: &mut HubHarness, owner: Identifier, contacts: Vec ContactData { + ContactData { + identity_id: Identifier::from([0xC4; 32]), + username: Some("cai".into()), + display_name: Some("Cai Lin".into()), + bio: None, + ..bao(None) + } +} + /// The Contacts tab with Bao listed, then Bao selected. fn hub_with_bao_selected( app_context: &std::sync::Arc, width: f32, note: Option<&'static str>, +) -> (HubHarness, Identifier) { + hub_with_bao_selected_among(app_context, width, vec![bao(note)]) +} + +/// The Contacts tab with `contacts` listed, then Bao selected. +fn hub_with_bao_selected_among( + app_context: &std::sync::Arc, + width: f32, + contacts: Vec, ) -> (HubHarness, Identifier) { let owner = seed_identity_with_usernames(app_context); let mut hub = hub_for( @@ -69,7 +91,7 @@ fn hub_with_bao_selected( owner, width, IdentityHubTab::Contacts, - move |hub, owner| deliver(hub, owner, bao(note)), + move |hub, owner| deliver_all(hub, owner, contacts), ); hub.get_by_role_and_label(Role::Button, "Bao Nguyen") .click(); @@ -238,7 +260,9 @@ fn selecting_a_contact_shows_its_details_beside_the_list() { fn save_note_shows_the_fee_first_and_sends_the_note_once() { with_isolated_data_dir(|| { let (_runtime, app_context) = fresh_app_context(); - let (mut hub, owner) = hub_with_bao_selected(&app_context, WIDE, None); + let (mut hub, owner) = + hub_with_bao_selected_among(&app_context, WIDE, vec![bao(None), cai()]); + assert!(hub.query_by_label(NOTE_HINT).is_some()); assert!( hub.query_by_label_contains("Estimated fee for saving this note: up to") @@ -282,6 +306,7 @@ fn save_note_shows_the_fee_first_and_sends_the_note_once() { BackendTaskSuccessResult::DashPayContactInfoUpdated { identity: owner, contact_id: Identifier::from(CONTACT), + published: true, }, ); hub.run_steps(4); @@ -301,6 +326,65 @@ fn save_note_shows_the_fee_first_and_sends_the_note_once() { }); } +/// With one contact the note is kept on this device: no fee is shown, and +/// the hint does not claim it is stored on Dash Platform. +#[test] +fn a_note_with_one_contact_shows_no_fee() { + with_isolated_data_dir(|| { + let (_runtime, app_context) = fresh_app_context(); + let (hub, _owner) = hub_with_bao_selected(&app_context, WIDE, None); + assert!( + hub.query_by_label_contains("Estimated fee for saving this note") + .is_none(), + "a device-only save costs nothing" + ); + assert!(hub.query_by_label(NOTE_HINT_ON_THIS_DEVICE).is_some()); + assert!(hub.query_by_label(NOTE_HINT).is_none()); + }); +} + +/// DIP-0015 holds contact details back until the identity has two contacts; +/// the user is told the note is kept on this device instead of "saved". +#[test] +fn a_note_kept_on_this_device_says_so() { + with_isolated_data_dir(|| { + let (_runtime, app_context) = fresh_app_context(); + let (mut hub, owner) = hub_with_bao_selected(&app_context, WIDE, None); + note_editor(&hub).focus(); + hub.run(); + note_editor(&hub).type_text("Met at the meetup"); + hub.run(); + hub.get_by_role_and_label(Role::Button, SAVE_NOTE_LABEL) + .click(); + hub.run_steps(2); + assert_eq!(saved_notes(&hub).len(), 1); + + // The hub harness does not draw global banners; read them instead. + let ctx = app_context.egui_ctx(); + MessageBanner::clear_all_global(ctx); + hub.state_mut().0.display_task_result( + BackendTaskSuccessResult::DashPayContactInfoUpdated { + identity: owner, + contact_id: Identifier::from(CONTACT), + published: false, + }, + ); + hub.run_steps(4); + assert!(hub.query_by_label(SAVING_NOTE_LABEL).is_none()); + + MessageBanner::clear_global_message(ctx, NOTE_SAVED); + assert!( + MessageBanner::has_global(ctx), + "the user is told the note is kept on this device" + ); + MessageBanner::clear_global_message(ctx, DETAILS_SAVED_ON_THIS_DEVICE); + assert!( + !MessageBanner::has_global(ctx), + "the only banner is the on-this-device one" + ); + }); +} + #[test] fn a_narrow_window_stacks_the_details_under_the_contact() { with_isolated_data_dir(|| { @@ -438,6 +522,7 @@ fn a_note_saved_behind_another_screen_is_settled_on_return() { result: Box::new(BackendTaskSuccessResult::DashPayContactInfoUpdated { identity: owner, contact_id: Identifier::from(CONTACT), + published: true, }), }], ); @@ -523,40 +608,6 @@ fn bare_contact_info_failure_behind_another_screen_releases_only_its_save() { }); } -#[test] -fn unreadable_details_found_behind_another_screen_still_ask_first() { - use dash_evo_tool::backend_task::error::{ContactInfoReadError, TaskError}; - with_isolated_data_dir(|| { - let runtime = tokio::runtime::Runtime::new().expect("runtime"); - let _guard = runtime.enter(); - let mut app = - crate::support::mount_app(dash_evo_tool::ui::RootScreenType::RootScreenWalletsBalances); - let (mut hub, owner, context) = hub_saving_a_note(&app); - - crate::identity_hub::loads::receive_task_results_behind_the_send_screen( - &runtime, - &mut app, - &mut hub, - vec![dash_evo_tool::app::TaskResult::Error { - context, - error: contact_info_failure( - owner, - TaskError::DashPayContactInfoRead { - source: ContactInfoReadError::DeserializeFailed, - }, - ), - }], - ); - hub.run_steps(2); - - assert!( - hub.query_by_label("Save note and replace saved details?") - .is_some(), - "the overwrite question must be asked once the hub is back in view" - ); - }); -} - /// The outcome of a same-contact write another screen dispatched: the /// legacy Contact Details screen sends plain tasks, so its context names the /// contact but no dispatch. @@ -588,6 +639,7 @@ fn a_foreign_same_contact_save_does_not_settle_the_hubs_note() { let updated = || BackendTaskSuccessResult::DashPayContactInfoUpdated { identity: owner, contact_id: Identifier::from(CONTACT), + published: true, }; hub.state_mut() @@ -621,6 +673,7 @@ fn a_foreign_same_contact_save_behind_another_screen_retires_the_hubs_note() { let updated = || BackendTaskSuccessResult::DashPayContactInfoUpdated { identity: owner, contact_id: Identifier::from(CONTACT), + published: true, }; hub.state_mut() .0