diff --git a/packages/rs-dpp/src/shielded/memo.rs b/packages/rs-dpp/src/shielded/memo.rs index babd71f3e6e..3cd45ece81e 100644 --- a/packages/rs-dpp/src/shielded/memo.rs +++ b/packages/rs-dpp/src/shielded/memo.rs @@ -12,7 +12,7 @@ //! * bytes `[4..36]` — a 32-byte payload whose meaning depends on //! `kind`. //! -//! Two kinds are defined today; unknown kinds round-trip verbatim as +//! Three kinds are defined today; unknown kinds round-trip verbatim as //! [`ShieldedMemo::Other`] so a future writer's memo is never //! corrupted by an older reader. @@ -28,6 +28,8 @@ pub const MEMO_PAYLOAD_SIZE: usize = MEMO_SIZE - 4; const KIND_EMPTY: u32 = 0; /// `kind` tag for a UTF-8 text memo (zero-padded payload). const KIND_TEXT: u32 = 1; +/// `kind` tag for a payment reference (zero-padded payload). +const KIND_PAYMENT_REF: u32 = 2; /// A decoded shielded note memo. /// @@ -42,6 +44,13 @@ pub enum ShieldedMemo { Empty, /// A UTF-8 text memo whose byte length is at most [`MEMO_PAYLOAD_SIZE`]. Text(String), + /// A payment reference: what the payment is for, in a value the payee chose and + /// gave to the payer, such as an invoice or order number, padded on the right with + /// zero bytes. The payee matches all 32 bytes against its own records. + /// + /// It never says who paid. Anyone who has seen a reference can attach it to a + /// payment, so the payee checks the amount it received against the request. + PaymentRef([u8; MEMO_PAYLOAD_SIZE]), /// Any memo whose `kind` this version does not interpret (or a /// structurally-invalid known kind). Retained verbatim so it /// round-trips unchanged. @@ -67,6 +76,38 @@ impl ShieldedMemo { Ok(ShieldedMemo::Text(s)) } + /// Build a payment reference memo from the reference the payee supplied, of 1 to + /// [`MEMO_PAYLOAD_SIZE`] bytes, padded on the right with zero bytes. A payee whose + /// own identifier is longer issues a 32-byte hash of it. + /// + /// An empty or all-zero reference is refused: 32 zero bytes are no reference. + pub fn payment_ref(reference: &[u8]) -> Result { + if reference.len() > MEMO_PAYLOAD_SIZE { + return Err(ProtocolError::Generic(format!( + "shielded payment reference is {} bytes, exceeds the {MEMO_PAYLOAD_SIZE}-byte limit", + reference.len() + ))); + } + if reference.iter().all(|&byte| byte == 0) { + return Err(ProtocolError::Generic( + "shielded payment reference is empty or all zero bytes".to_string(), + )); + } + let mut payload = [0u8; MEMO_PAYLOAD_SIZE]; + payload[..reference.len()].copy_from_slice(reference); + Ok(ShieldedMemo::PaymentRef(payload)) + } + + /// A payment reference as text, when it is valid UTF-8 once its zero padding is + /// removed. `None` for a reference that is not, a hash for example: a caller that + /// shows such a reference renders its 32 bytes in hexadecimal. + pub fn payment_ref_text(reference: &[u8; MEMO_PAYLOAD_SIZE]) -> Option<&str> { + let end = reference.iter().rposition(|&b| b != 0).map_or(0, |i| i + 1); + std::str::from_utf8(&reference[..end]) + .ok() + .filter(|text| !text.is_empty()) + } + /// Encode to the on-chain 36-byte memo layout. pub fn to_bytes(&self) -> [u8; MEMO_SIZE] { let mut out = [0u8; MEMO_SIZE]; @@ -82,6 +123,7 @@ impl ShieldedMemo { payload[..n].copy_from_slice(&bytes[..n]); (KIND_TEXT, payload) } + ShieldedMemo::PaymentRef(reference) => (KIND_PAYMENT_REF, *reference), ShieldedMemo::Other { kind, payload } => (*kind, *payload), }; out[0..4].copy_from_slice(&kind.to_le_bytes()); @@ -92,7 +134,8 @@ impl ShieldedMemo { /// Decode from the on-chain 36-byte memo layout. /// /// Decoding is total: a `KIND_TEXT` memo whose payload is not valid - /// UTF-8, or a `KIND_EMPTY` memo with a non-zero payload, falls back + /// UTF-8, a `KIND_EMPTY` memo with a non-zero payload, or a + /// `KIND_PAYMENT_REF` memo with an all-zero payload falls back /// to [`Self::Other`] so the raw bytes are preserved rather than lost. pub fn from_bytes(bytes: &[u8; MEMO_SIZE]) -> Self { let kind = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]); @@ -117,6 +160,10 @@ impl ShieldedMemo { Err(_) => ShieldedMemo::Other { kind, payload }, } } + // 32 zero bytes are no reference, so that memo is not read as one. + KIND_PAYMENT_REF if payload != [0u8; MEMO_PAYLOAD_SIZE] => { + ShieldedMemo::PaymentRef(payload) + } _ => ShieldedMemo::Other { kind, payload }, } } @@ -199,6 +246,68 @@ mod tests { ); } + #[test] + fn should_encode_a_payment_reference_padded_to_32_bytes() { + // The vector of the DashPay shielded payment addresses DIP. + let memo = ShieldedMemo::payment_ref(b"INV-2026-0042").expect("a 13-byte reference"); + let bytes = memo.to_bytes(); + let mut expected = [0u8; MEMO_SIZE]; + expected[0] = 2; + expected[4..17].copy_from_slice(b"INV-2026-0042"); + assert_eq!(bytes, expected); + assert_eq!(ShieldedMemo::from_bytes(&bytes), memo); + + let ShieldedMemo::PaymentRef(reference) = memo else { + panic!("expected a payment reference"); + }; + assert_eq!( + ShieldedMemo::payment_ref_text(&reference), + Some("INV-2026-0042") + ); + } + + #[test] + fn should_round_trip_a_32_byte_payment_reference_that_is_not_text() { + // A hash: every byte used, not UTF-8, ending in a zero byte that is part of it. + let mut reference = [0xF5u8; MEMO_PAYLOAD_SIZE]; + reference[31] = 0; + let memo = ShieldedMemo::payment_ref(&reference).expect("a 32-byte reference"); + assert_eq!(memo, ShieldedMemo::PaymentRef(reference)); + assert_eq!(ShieldedMemo::from_bytes(&memo.to_bytes()), memo); + assert_eq!(ShieldedMemo::payment_ref_text(&reference), None); + } + + #[test] + fn should_read_references_that_differ_only_in_trailing_zero_bytes_as_one() { + assert_eq!( + ShieldedMemo::payment_ref(&[1]).expect("a reference"), + ShieldedMemo::payment_ref(&[1, 0]).expect("a reference") + ); + } + + #[test] + fn should_refuse_a_payment_reference_that_is_empty_all_zero_or_too_long() { + assert!(ShieldedMemo::payment_ref(&[]).is_err()); + assert!(ShieldedMemo::payment_ref(&[0; 5]).is_err()); + assert!(ShieldedMemo::payment_ref(&[0; MEMO_PAYLOAD_SIZE]).is_err()); + assert!(ShieldedMemo::payment_ref(&[1; MEMO_PAYLOAD_SIZE + 1]).is_err()); + } + + #[test] + fn should_not_read_an_all_zero_payload_as_a_payment_reference() { + let mut bytes = [0u8; MEMO_SIZE]; + bytes[0..4].copy_from_slice(&KIND_PAYMENT_REF.to_le_bytes()); + assert_eq!( + ShieldedMemo::from_bytes(&bytes), + ShieldedMemo::Other { + kind: KIND_PAYMENT_REF, + payload: [0u8; MEMO_PAYLOAD_SIZE], + } + ); + // The bytes survive the round trip. + assert_eq!(ShieldedMemo::from_bytes(&bytes).to_bytes(), bytes); + } + #[test] fn unknown_kind_round_trips() { let payload = [7u8; MEMO_PAYLOAD_SIZE]; diff --git a/packages/rs-platform-encryption/src/error.rs b/packages/rs-platform-encryption/src/error.rs index 763aaa6ee6b..c6eb9283179 100644 --- a/packages/rs-platform-encryption/src/error.rs +++ b/packages/rs-platform-encryption/src/error.rs @@ -14,4 +14,10 @@ pub enum CryptoError { #[error("Invalid compact xpub length (DIP-15 requires exactly 69 bytes, got {0})")] InvalidCompactXpubLength(usize), + + #[error("Invalid encrypted shielded address length (expected 64 bytes, got {0})")] + InvalidEncryptedShieldedAddressLength(usize), + + #[error("Invalid shielded address length (expected 43 bytes, got {0})")] + InvalidShieldedAddressLength(usize), } diff --git a/packages/rs-platform-encryption/src/lib.rs b/packages/rs-platform-encryption/src/lib.rs index e8bf2e5f4a4..7bd3aaf2c9e 100644 --- a/packages/rs-platform-encryption/src/lib.rs +++ b/packages/rs-platform-encryption/src/lib.rs @@ -11,6 +11,7 @@ //! - [`contact_info`] — `contactInfo` (`encToUserId` + `privateData`). //! - [`account_reference`] — the masked `accountReference`. //! - [`private_document_envelope`] — the standard private document envelope (version 1). +//! - [`shielded_address`]: `encryptedShieldedAddress` and the per-contact index rule. //! - [`error`] — the shared [`CryptoError`]. //! //! Every public item is re-exported at the crate root, so the API is flat @@ -24,6 +25,7 @@ mod contact_info; mod ecdh; mod error; mod private_document_envelope; +mod shielded_address; pub use account_label::{decrypt_account_label, encrypt_account_label}; pub use account_reference::{ @@ -50,3 +52,8 @@ pub use private_document_envelope::{ PRIVATE_DOCUMENT_ENVELOPE_OVERHEAD_LEN, PRIVATE_DOCUMENT_ENVELOPE_VERSION, PRIVATE_DOCUMENT_ENVELOPE_WRAPPER_LEN, }; +pub use shielded_address::{ + decrypt_shielded_address, encrypt_shielded_address, is_shielded_contact_index, + shielded_contact_index, shielded_contact_index_key, ENCRYPTED_SHIELDED_ADDRESS_LEN, + SHIELDED_ADDRESS_LEN, SHIELDED_DIVERSIFIER_INDEX_LEN, SHIELDED_FULL_VIEWING_KEY_LEN, +}; diff --git a/packages/rs-platform-encryption/src/shielded_address.rs b/packages/rs-platform-encryption/src/shielded_address.rs new file mode 100644 index 00000000000..bcf11dfc59c --- /dev/null +++ b/packages/rs-platform-encryption/src/shielded_address.rs @@ -0,0 +1,292 @@ +//! The per-contact shielded payment address of a DashPay contact request: the +//! diversifier index a wallet derives it at, and the field that carries it. +//! +//! A DashPay identity gives every contact a different shielded payment address, each +//! a diversified address of the identity's shielded account, so a payment that +//! arrives on one is attributed to the contact it was given to. The address is never +//! allocated or stored. Its diversifier index is a keyed hash of the contact request's +//! unique key (`$ownerId`, `toUserId`, `accountReference`), under a key derived from +//! the account's full viewing key. Two devices restored from one seed derive the same +//! address for the same request, with no state to keep in step or to lose. Two +//! requests get the same address only if their indices collide in the 87 bits the +//! hash leaves free, which is negligible, and the sender checks for it before sending +//! (see [`shielded_contact_index`]). A counter cannot give that: two devices would +//! hand the same index to different contacts as a matter of course. +//! +//! This module holds what needs no shielded pool types: the index and the encoding of +//! `encryptedShieldedAddress`. The wallet turns an index into an address with the +//! account's full viewing key, and checks that a decrypted value is an address. + +use crate::aes::{decrypt_aes_256_cbc, encrypt_aes_256_cbc}; +use crate::error::CryptoError; +use hmac::{Hmac, Mac}; +use sha2::Sha256; + +/// A raw shielded payment address: an 11-byte diversifier followed by a 32-byte +/// diversified transmission key. +pub const SHIELDED_ADDRESS_LEN: usize = 43; + +/// `encryptedShieldedAddress` as this module writes it: a 16-byte IV followed by the +/// three AES blocks a 43-byte address pads to. The contract also admits 80 bytes, +/// kept for a later encoding, which [`decrypt_shielded_address`] refuses. +pub const ENCRYPTED_SHIELDED_ADDRESS_LEN: usize = 64; + +/// A raw full viewing key of a shielded account: `ak || nk || rivk`. +pub const SHIELDED_FULL_VIEWING_KEY_LEN: usize = 96; + +/// A diversifier index: an 88-bit little-endian integer. +pub const SHIELDED_DIVERSIFIER_INDEX_LEN: usize = 11; + +/// The HMAC key that turns a full viewing key into a contact index key. +const CONTACT_INDEX_KEY_LABEL: &[u8] = b"DashPay/shielded/contact-index-key/v1"; + +/// What a contact index key hashes ahead of the contact request's unique key. +const CONTACT_INDEX_LABEL: &[u8] = b"DashPay/shielded/contact-index/v1"; + +/// Bit 87 of a diversifier index, in its last byte. Every per-contact index has it +/// set, and no profile or wallet-local index does. +const CONTACT_INDEX_HIGH_BIT: u8 = 0x80; + +fn hmac_sha256(key: &[u8], parts: &[&[u8]]) -> [u8; 32] { + let mut mac = + as Mac>::new_from_slice(key).expect("HMAC takes a key of any length"); + for part in parts { + mac.update(part); + } + mac.finalize().into_bytes().into() +} + +/// The key a shielded account derives its per-contact indices under: +/// `HMAC-SHA256(key = "DashPay/shielded/contact-index-key/v1", msg = full viewing key)`. +/// +/// It needs the full viewing key, so a holder of the account's incoming viewing key +/// alone can see which index a payment arrived on but not which contact it belongs to. +pub fn shielded_contact_index_key( + full_viewing_key: &[u8; SHIELDED_FULL_VIEWING_KEY_LEN], +) -> [u8; 32] { + hmac_sha256(CONTACT_INDEX_KEY_LABEL, &[full_viewing_key]) +} + +/// The diversifier index of the shielded address a contact request carries, from the +/// request's unique key: +/// +/// ```text +/// t = HMAC-SHA256(key = index_key, +/// msg = "DashPay/shielded/contact-index/v1" || owner_id || to_user_id +/// || account_reference as u64 little-endian) +/// j = t[0..11], with bit 87 set +/// ``` +/// +/// `owner_id` is the identity that sends the request and owns the address, `to_user_id` +/// the contact, and `account_reference` the value the request publishes, never one +/// recomputed locally. The index always lies in the per-contact range, from 2^87. +/// +/// Before sending, the caller compares the index with those it has given to other +/// contacts and, on a match, sends the request under another `account_reference`. +pub fn shielded_contact_index( + index_key: &[u8; 32], + owner_id: &[u8; 32], + to_user_id: &[u8; 32], + account_reference: u64, +) -> [u8; SHIELDED_DIVERSIFIER_INDEX_LEN] { + let t = hmac_sha256( + index_key, + &[ + CONTACT_INDEX_LABEL, + owner_id, + to_user_id, + &account_reference.to_le_bytes(), + ], + ); + let mut index = [0u8; SHIELDED_DIVERSIFIER_INDEX_LEN]; + index.copy_from_slice(&t[..SHIELDED_DIVERSIFIER_INDEX_LEN]); + index[SHIELDED_DIVERSIFIER_INDEX_LEN - 1] |= CONTACT_INDEX_HIGH_BIT; + index +} + +/// Whether a diversifier index lies in the per-contact range (2^87 and above), where +/// only [`shielded_contact_index`] places addresses. An index below it is a profile +/// address or one the wallet uses for itself, never one given to a contact. +pub fn is_shielded_contact_index(index: &[u8; SHIELDED_DIVERSIFIER_INDEX_LEN]) -> bool { + index[SHIELDED_DIVERSIFIER_INDEX_LEN - 1] & CONTACT_INDEX_HIGH_BIT != 0 +} + +/// Encrypt a shielded payment address as a contact request's +/// `encryptedShieldedAddress`: the IV, then the address under AES-256-CBC with the +/// request's DIP-15 shared key, the key that encrypts its `encryptedPublicKey`. +/// +/// `iv` is drawn at random for this field alone: no two fields of a request share one. +pub fn encrypt_shielded_address( + shared_key: &[u8; 32], + iv: &[u8; 16], + address: &[u8; SHIELDED_ADDRESS_LEN], +) -> [u8; ENCRYPTED_SHIELDED_ADDRESS_LEN] { + let ciphertext = encrypt_aes_256_cbc(shared_key, iv, address); + let mut field = [0u8; ENCRYPTED_SHIELDED_ADDRESS_LEN]; + field[..16].copy_from_slice(iv); + field[16..].copy_from_slice(&ciphertext); + field +} + +/// Decrypt a contact request's `encryptedShieldedAddress` to the 43 bytes it carries. +/// +/// A value of any length but 64 is refused, the 80 bytes the contract keeps for a later +/// encoding included, and so is one whose plaintext is not exactly 43 bytes. CBC does +/// not authenticate, so a value decrypted under the wrong key can still pass: the caller +/// uses the result only if the same key decrypts the request's `encryptedPublicKey` to a +/// well-formed key and the bytes are a valid address that is neither its own nor the +/// sender's profile address. +pub fn decrypt_shielded_address( + shared_key: &[u8; 32], + field: &[u8], +) -> Result<[u8; SHIELDED_ADDRESS_LEN], CryptoError> { + let (iv, ciphertext) = field + .split_first_chunk::<16>() + .filter(|_| field.len() == ENCRYPTED_SHIELDED_ADDRESS_LEN) + .ok_or(CryptoError::InvalidEncryptedShieldedAddressLength( + field.len(), + ))?; + let plaintext = decrypt_aes_256_cbc(shared_key, iv, ciphertext)?; + plaintext + .as_slice() + .try_into() + .map_err(|_| CryptoError::InvalidShieldedAddressLength(plaintext.len())) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn hex(text: &str) -> [u8; N] { + let bytes: Vec = (0..text.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&text[i..i + 2], 16).expect("a hex digit pair")) + .collect(); + bytes.try_into().expect("the expected length") + } + + // The vectors of the DashPay shielded payment addresses DIP: mnemonic "abandon ... + // about", mainnet, the shielded account of identity index 0 (account 0x40000000). + const FULL_VIEWING_KEY: &str = + "c0120eb660f8dd2f769e199bcc540476fec169b60f3e7508ffd42a21bd274337\ + b2301310b489575eb68a8adacfed66b88fd07b961d1ca366c7e7e6e619b29a2b\ + fce2cf9cb05a6439997f6f7ad4d9eb4b3d5a0672e571036cff9c8a600439063d"; + const INDEX_KEY: &str = "7233ea974f99a772e1f7cfeef7d1626f9d24cba429b32f5ecdabed7b14867791"; + const OWNER: [u8; 32] = [0x11; 32]; + const BOB: [u8; 32] = [0x22; 32]; + const CAROL: [u8; 32] = [0x33; 32]; + const BOB_ADDRESS: &str = + "25611685f1aa7c3b7a2f7a758ea2f98ca16e32e20e0d3b403a1d81421f1185d67f47054ae98e55e05e839c"; + + #[test] + fn should_derive_the_contact_index_key_from_the_full_viewing_key() { + assert_eq!( + shielded_contact_index_key(&hex(FULL_VIEWING_KEY)), + hex::<32>(INDEX_KEY) + ); + } + + #[test] + fn should_derive_the_index_of_each_contact_request() { + let key = hex(INDEX_KEY); + for (to_user_id, account_reference, index) in [ + (BOB, 0x0123_4567, "f90d5349d8530cf76835d0"), + // Bit 87 is clear in the hash here (its eleventh byte is 0x14) and is set. + (CAROL, 0x0123_4567, "a5ca8646a33e3db572ca94"), + // The same contact under the next DIP-15 version: another address. + (BOB, 0x1123_4567, "4d2ff123168ee0a07ff5b2"), + ] { + let derived = shielded_contact_index(&key, &OWNER, &to_user_id, account_reference); + assert_eq!(derived, hex::<11>(index)); + assert!(is_shielded_contact_index(&derived)); + } + } + + #[test] + fn should_give_two_contacts_and_two_senders_different_indices() { + let key = hex(INDEX_KEY); + let to_bob = shielded_contact_index(&key, &OWNER, &BOB, 7); + assert_ne!(to_bob, shielded_contact_index(&key, &OWNER, &CAROL, 7)); + assert_ne!(to_bob, shielded_contact_index(&key, &CAROL, &BOB, 7)); + assert_ne!(to_bob, shielded_contact_index(&key, &OWNER, &BOB, 8)); + assert_ne!(to_bob, shielded_contact_index(&[9; 32], &OWNER, &BOB, 7)); + // The inputs alone decide it. + assert_eq!(to_bob, shielded_contact_index(&key, &OWNER, &BOB, 7)); + } + + #[test] + fn should_keep_profile_and_wallet_indices_out_of_the_contact_range() { + assert!(!is_shielded_contact_index(&[0; 11])); + // 2^32 - 1, an index a wallet may use for itself, and 2^87 - 1, the last below the + // range. + assert!(!is_shielded_contact_index(&hex("ffffffff00000000000000"))); + assert!(!is_shielded_contact_index(&hex("ffffffffffffffffffff7f"))); + // 2^87, the first per-contact index. + assert!(is_shielded_contact_index(&hex("0000000000000000000080"))); + } + + #[test] + fn should_encrypt_an_address_to_the_64_byte_field() { + let shared_key: [u8; 32] = core::array::from_fn(|i| i as u8); + let iv: [u8; 16] = core::array::from_fn(|i| 0xa0 + i as u8); + let field = encrypt_shielded_address(&shared_key, &iv, &hex(BOB_ADDRESS)); + assert_eq!( + field, + hex::<64>( + "a0a1a2a3a4a5a6a7a8a9aaabacadaeafb00fd785cffaf9bd43b25189363352d5\ + 4462f4fc18e0ca7108e1effc6d615026025a763f29384d39e5b0c29020d62e97" + ) + ); + assert_eq!( + decrypt_shielded_address(&shared_key, &field).expect("the field decrypts"), + hex::<43>(BOB_ADDRESS) + ); + } + + #[test] + fn should_refuse_a_field_of_any_other_length() { + let shared_key = [1u8; 32]; + let field = encrypt_shielded_address(&shared_key, &[2; 16], &[3; 43]); + for length in [0, 15, 16, 48, 63, 65, 80] { + let mut other = field.to_vec(); + other.resize(length, 0); + assert!( + matches!( + decrypt_shielded_address(&shared_key, &other), + Err(CryptoError::InvalidEncryptedShieldedAddressLength(l)) if l == length + ), + "a field of {length} bytes" + ); + } + } + + #[test] + fn should_refuse_a_plaintext_that_is_not_43_bytes() { + let shared_key = [1u8; 32]; + let iv = [2u8; 16]; + // 33 to 47 bytes all pad to three blocks, so the field length cannot tell them apart. + for length in [33, 42, 44, 47] { + let mut field = iv.to_vec(); + field.extend(encrypt_aes_256_cbc(&shared_key, &iv, &vec![3; length])); + assert_eq!(field.len(), ENCRYPTED_SHIELDED_ADDRESS_LEN); + assert!( + matches!( + decrypt_shielded_address(&shared_key, &field), + Err(CryptoError::InvalidShieldedAddressLength(l)) if l == length + ), + "a plaintext of {length} bytes" + ); + } + } + + #[test] + fn should_refuse_a_field_whose_padding_does_not_decrypt() { + let field = encrypt_shielded_address(&[1; 32], &[2; 16], &[3; 43]); + // Under another key the last block almost never ends in valid padding; this one + // does not. + assert!(matches!( + decrypt_shielded_address(&[4; 32], &field), + Err(CryptoError::DecryptionFailed) + )); + } +} diff --git a/packages/rs-platform-wallet-ffi/build.rs b/packages/rs-platform-wallet-ffi/build.rs index b8f773da8a9..142e592cbda 100644 --- a/packages/rs-platform-wallet-ffi/build.rs +++ b/packages/rs-platform-wallet-ffi/build.rs @@ -27,10 +27,14 @@ fn main() { println!("cargo:rerun-if-changed={index}"); } + // `OUT_DIR` is `target//build/-/out` up to Cargo 1.99 and + // `target//build///out` from Cargo 1.100, so the profile + // directory is the parent of `build`, whatever lies between `build` and `out`. let target_dir = Path::new(&out_dir) .ancestors() - .nth(3) // This line moves up to the target/ directory - .expect("Failed to find target dir"); + .find(|dir| dir.file_name().is_some_and(|name| name == "build")) + .and_then(Path::parent) + .expect("OUT_DIR lies under target//build"); let include_dir = target_dir.join("include").join(&crate_name); diff --git a/packages/rs-platform-wallet/src/wallet/shielded/keys.rs b/packages/rs-platform-wallet/src/wallet/shielded/keys.rs index 09870f53373..5fcde3530e0 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/keys.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/keys.rs @@ -15,7 +15,11 @@ use grovedb_commitment_tree::{ FullViewingKey, IncomingViewingKey, OutgoingViewingKey, PaymentAddress, PreparedIncomingViewingKey, Scope, SpendAuthorizingKey, SpendingKey, }; -use zip32::AccountId; +use platform_encryption::{ + is_shielded_contact_index, shielded_contact_index, shielded_contact_index_key, + SHIELDED_DIVERSIFIER_INDEX_LEN, +}; +use zip32::{AccountId, DiversifierIndex}; use crate::error::PlatformWalletError; @@ -213,9 +217,11 @@ impl AccountViewingKeys { Ok(Self::from_full_viewing_key(fvk)) } - /// An external-scope payment address at a uniformly random 11-byte - /// diversifier index drawn from the OS CSPRNG. Index 0 (the default - /// address) is redrawn, so the result is never the default address. + /// An external-scope payment address at a uniformly random diversifier + /// index below 2^87, drawn from the OS CSPRNG. Index 0 (the default + /// address) and every index of 2^87 or above (reserved for + /// [`Self::contact_address`]) are redrawn, so the result is never the + /// default address or a contact address. /// Every 11-byte Orchard diversifier index yields a valid address, so /// no other retry is needed. Writes no state: the scan finds notes to /// the returned address through the IVK, whatever its index. @@ -228,13 +234,13 @@ impl AccountViewingKeys { } /// [`Self::fresh_address`] with the index drawn from `rng`, so tests can - /// script the index-0 redraw and a randomness failure. + /// script the redraws and a randomness failure. fn fresh_address_from( &self, rng: &mut R, ) -> Result { let mut index = [0u8; 11]; - while index == [0u8; 11] { + while index == [0u8; 11] || is_shielded_contact_index(&index) { rng.try_fill_bytes(&mut index).map_err(|_| { PlatformWalletError::ShieldedKeyDerivation( "shielded fresh address: randomness unavailable".to_string(), @@ -264,6 +270,49 @@ impl AccountViewingKeys { }; self.incoming_viewing_key.diversifier_index(&addr).is_some() } + + /// The shielded payment address this account gives the contact of one DashPay + /// contact request: the external address at the diversifier index that the + /// request's unique key (`owner_id`, `to_user_id`, `account_reference`) hashes to + /// under this account's full viewing key ([`shielded_contact_index`]). + /// + /// The same request always gives the same address on every device holding the + /// seed, with no allocation stored. Two requests share an address only if their + /// 87-bit indices collide, which is negligible but not impossible: before sending + /// a request the caller compares its index with those already given to other + /// contacts and, on a match, sends it under another `account_reference` (see + /// [`shielded_contact_index`]). `owner_id` is the identity that sends the request + /// and owns this account, and `account_reference` the value the request publishes. + pub fn contact_address( + &self, + owner_id: &[u8; 32], + to_user_id: &[u8; 32], + account_reference: u64, + ) -> PaymentAddress { + let index_key = shielded_contact_index_key(&self.to_fvk_bytes()); + let index = shielded_contact_index(&index_key, owner_id, to_user_id, account_reference); + self.full_viewing_key + .address_at(DiversifierIndex::from(index), Scope::External) + } + + /// The diversifier index a payment address sits at in this account, when it lies + /// in the range per-contact addresses use: `None` for an address of another + /// account and for one below that range, such as the profile address. + /// + /// The index belongs to a contact only if [`Self::contact_address`] gives it for + /// one of this account's contact requests; [`Self::fresh_address`] never returns + /// an address in the range. A payment on a matching address is attributed to + /// that contact, which is not proof of who paid: anyone who has learned the + /// address can pay it. + pub fn contact_index_of( + &self, + address: &PaymentAddress, + ) -> Option<[u8; SHIELDED_DIVERSIFIER_INDEX_LEN]> { + self.incoming_viewing_key + .diversifier_index(address) + .map(|index| *index.as_bytes()) + .filter(is_shielded_contact_index) + } } #[cfg(test)] @@ -527,6 +576,40 @@ mod tests { ); } + /// A drawn index in the half of the index space kept for contact requests is + /// redrawn, so a fresh address is never read as a contact's. + #[test] + fn should_redraw_a_fresh_index_in_the_contact_range() { + let views = OrchardKeySet::from_seed(&[0x42u8; 64], Network::Testnet, 0) + .expect("derivation succeeds") + .viewing_keys(); + // 2^87, the first index of the range, then its last, then the last below it. + let mut first = [0u8; 11]; + first[10] = 0x80; + let mut below = [0xFFu8; 11]; + below[10] = 0x7F; + let mut rng = ScriptedRng(vec![first, [0xFFu8; 11], below]); + + let address = views.fresh_address_from(&mut rng).expect("fresh address"); + assert!(rng.0.is_empty(), "all three draws were taken"); + assert_eq!( + address.to_raw_address_bytes(), + views + .full_viewing_key + .address_at(zip32::DiversifierIndex::from(below), Scope::External) + .to_raw_address_bytes(), + "the address is the one at the first index drawn below the range" + ); + assert_eq!(views.contact_index_of(&address), None); + assert!(views.is_own_recipient(&address.to_raw_address_bytes())); + + // Nothing the OS randomness gives lands in the range either. + for _ in 0..64 { + let fresh = views.fresh_address().expect("fresh address"); + assert_eq!(views.contact_index_of(&fresh), None); + } + } + /// A randomness failure is an error, not an address. #[test] fn fresh_address_reports_a_randomness_failure() { @@ -569,4 +652,114 @@ mod tests { "off-curve pk_d is malformed" ); } + + // The vectors of the DashPay shielded payment addresses DIP: the BIP-39 seed of + // "abandon ... about" with an empty passphrase, and the shielded account of the + // identity at index 0 (account 0x40000000). + const DIP_SEED: &str = "5eb00bbddcf069084889a8ab9155568165f5c453ccb85e70811aaed6f6da5fc1\ + 9a5ac40b389cd370d086206dec8aa6c43daea6690f20ad3d8d48b2d2ce9e38e4"; + const DIP_IDENTITY_ACCOUNT: u32 = 0x4000_0000; + const DIP_OWNER: [u8; 32] = [0x11; 32]; + const DIP_BOB: [u8; 32] = [0x22; 32]; + const DIP_CAROL: [u8; 32] = [0x33; 32]; + + fn dip_account(network: Network, account: u32) -> AccountViewingKeys { + let seed = hex::decode(DIP_SEED).expect("the seed is hex"); + OrchardKeySet::from_seed(&seed, network, account) + .expect("the account derives") + .viewing_keys() + } + + #[test] + fn should_derive_the_identity_shielded_accounts_of_the_dip_vectors() { + for (network, account, fvk, profile_address) in [ + ( + Network::Mainnet, + DIP_IDENTITY_ACCOUNT, + "c0120eb660f8dd2f769e199bcc540476fec169b60f3e7508ffd42a21bd274337\ + b2301310b489575eb68a8adacfed66b88fd07b961d1ca366c7e7e6e619b29a2b\ + fce2cf9cb05a6439997f6f7ad4d9eb4b3d5a0672e571036cff9c8a600439063d", + "e126993647eb0c9a4b476e2823380ead099e803ea52c980146e6fa42cfeb9d2ef8f7b1d6e764821d706397", + ), + ( + Network::Mainnet, + DIP_IDENTITY_ACCOUNT + 1, + "5317987e38a2dd272cebe41d317c33980e53d77c14ed166abc097aaaa1612837\ + d315ce0f5dc87a85557ce30362cd330aaf0396b51c4970e2ddd7e7861dc06922\ + 4581992d96f19f367bff3f7bbfee475fd5f61e8edccc550d98d9e2f98f7fdb0c", + "936389bea5f4472a82d8c933ce9763f88ce0d8955ebc61b0cbe42914350f1c9b38978c673e4a1247b890ba", + ), + ( + Network::Testnet, + DIP_IDENTITY_ACCOUNT, + "e82418aaf0c953565e04048cedfecb0fcd0bd1f9a5ab05be2d36a4fbcc5cd404\ + 6aecdbc3837ace5abf1b727bded47346872cdee34bdd36521ae81031fd92f00e\ + cfd073865caa1e41baae4f378be748672b77c55e631f2ac2e7ccb2d205095c35", + "335feafaef3927edd1dffc09b7af7f2d14be582f5ba3a4501c691f044a4af5a881ddd3951496c6a877c32f", + ), + ] { + let keys = dip_account(network, account); + assert_eq!(hex::encode(keys.to_fvk_bytes()), fvk); + assert_eq!( + hex::encode(keys.default_address.to_raw_address_bytes()), + profile_address + ); + } + } + + #[test] + fn should_give_each_contact_request_the_address_of_the_dip_vectors() { + let keys = dip_account(Network::Mainnet, DIP_IDENTITY_ACCOUNT); + for (to_user_id, account_reference, index, address) in [ + ( + DIP_BOB, + 0x0123_4567, + "f90d5349d8530cf76835d0", + "25611685f1aa7c3b7a2f7a758ea2f98ca16e32e20e0d3b403a1d81421f1185d67f47054ae98e55e05e839c", + ), + ( + DIP_CAROL, + 0x0123_4567, + "a5ca8646a33e3db572ca94", + "a7a566b9a2ff0c79c3155371ca1936c6e0ccfd19d772e290cbf9cfb35c763f5cee6733e89c300960ade0a7", + ), + // The same contact under the next DIP-15 version: another address. + ( + DIP_BOB, + 0x1123_4567, + "4d2ff123168ee0a07ff5b2", + "8b9e1e782d79eae3c6d4420caf1bd38ef3385383d88f1a87a69a4b048f8602964e5be3b9de6fa8f289c527", + ), + ] { + let derived = keys.contact_address(&DIP_OWNER, &to_user_id, account_reference); + assert_eq!(hex::encode(derived.to_raw_address_bytes()), address); + // The account's incoming viewing key finds the index the address sits at. + assert_eq!( + keys.contact_index_of(&derived).map(hex::encode), + Some(index.to_string()) + ); + } + } + + #[test] + fn should_find_a_contact_index_only_for_this_accounts_contact_addresses() { + let keys = dip_account(Network::Mainnet, DIP_IDENTITY_ACCOUNT); + let to_bob = keys.contact_address(&DIP_OWNER, &DIP_BOB, 0x0123_4567); + + // The profile address and a wallet-local one lie below the contact range. + assert_eq!(keys.contact_index_of(&keys.default_address), None); + let wallet_local = keys.full_viewing_key.address_at(7u32, Scope::External); + assert_eq!(keys.contact_index_of(&wallet_local), None); + + // Another identity's account derives another address for the same request and + // does not recognise this one. + let other = dip_account(Network::Mainnet, DIP_IDENTITY_ACCOUNT + 1); + assert_ne!( + other + .contact_address(&DIP_OWNER, &DIP_BOB, 0x0123_4567) + .to_raw_address_bytes(), + to_bob.to_raw_address_bytes() + ); + assert_eq!(other.contact_index_of(&to_bob), None); + } } diff --git a/packages/rs-sdk-cxx/build.rs b/packages/rs-sdk-cxx/build.rs index e2f850e7abe..2bcf6dd12a0 100644 --- a/packages/rs-sdk-cxx/build.rs +++ b/packages/rs-sdk-cxx/build.rs @@ -15,10 +15,14 @@ fn main() { println!("cargo:rerun-if-changed=include/dash/sdk/callbacks.h"); let out_dir = env::var("OUT_DIR").expect("OUT_DIR"); + // `OUT_DIR` is `target//build/-/out` up to Cargo 1.99 and + // `target//build///out` from Cargo 1.100, so the profile + // directory is the parent of `build`, whatever lies between `build` and `out`. let include = Path::new(&out_dir) .ancestors() - .nth(3) - .expect("target/") + .find(|dir| dir.file_name().is_some_and(|name| name == "build")) + .and_then(Path::parent) + .expect("OUT_DIR lies under target//build") .join("include"); let generated = Path::new(&out_dir).join("cxxbridge/include"); for (from, to) in [ diff --git a/packages/rs-sdk-ffi/build.rs b/packages/rs-sdk-ffi/build.rs index 2ea7dafa889..a55bc61dd0d 100644 --- a/packages/rs-sdk-ffi/build.rs +++ b/packages/rs-sdk-ffi/build.rs @@ -9,10 +9,14 @@ fn main() { println!("cargo:rerun-if-changed=cbindgen.toml"); println!("cargo:rerun-if-changed=src/"); + // `OUT_DIR` is `target//build/-/out` up to Cargo 1.99 and + // `target//build///out` from Cargo 1.100, so the profile + // directory is the parent of `build`, whatever lies between `build` and `out`. let target_dir = Path::new(&out_dir) .ancestors() - .nth(3) // This line moves up to the target/ directory - .expect("Failed to find target dir"); + .find(|dir| dir.file_name().is_some_and(|name| name == "build")) + .and_then(Path::parent) + .expect("OUT_DIR lies under target//build"); let include_dir = target_dir.join("include").join(&crate_name);