Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ pub const YES_NO_VOTE_POLL_INITIAL_PROTOCOL_VERSION: ProtocolVersion = 15;
/// exist and lookups must report it absent. Creating one of its proposals opens a yes/no vote
/// poll.
pub const DECISION_PROPOSALS_CONTRACT_INITIAL_PROTOCOL_VERSION: ProtocolVersion = 15;
/// A contact request's `encryptedShieldedAddress`, the sender's shielded payment address for
/// the contact, exists from protocol version 15: DashPay v3, which replaces DashPay at that
/// version, adds the property, and below it the network's contact requests have none.
pub const DASHPAY_CONTACT_REQUEST_SHIELDED_ADDRESS_INITIAL_PROTOCOL_VERSION: ProtocolVersion = 15;
/// Private document entries activate with protocol version 15: a
/// `PrivateDocumentCreateFromShieldedPool`, which appends entries to a private document type's
/// store paying from the credit shielded pool, is not active before it, as software that
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1065,6 +1065,17 @@ impl<B: TransactionBroadcaster + ?Sized> DashPayView<'_, B> {
),
}

// 4e. The sender's shielded payment address for this contact, when the
// identity's shielded account was proven against the seed in this
// session and the network's contact requests carry one; the request
// goes without it otherwise. The identity's placement is held from
// here until the request is signed, so the account the address is
// derived from is still the identity's when the request commits to it.
let placement = self.identity_placement.read().await;
let shielded_address = self
.contact_shielded_address(sender_identity_id, recipient_identity_id, account_reference)
.await?;
Comment thread
QuantumExplorer marked this conversation as resolved.
Resolved
Comment thread
QuantumExplorer marked this conversation as resolved.
Resolved

// 5. Build the signing key reference for document signing.
let identity_public_key = sender_identity
// Contact-request send writes a document state transition,
Expand Down Expand Up @@ -1120,6 +1131,7 @@ impl<B: TransactionBroadcaster + ?Sized> DashPayView<'_, B> {
account_reference,
account_label,
auto_accept_proof,
shielded_address,
shared_secret,
expected_recipient_pubkey: recipient_enc_pubkey,
xpub_bytes,
Expand All @@ -1131,6 +1143,7 @@ impl<B: TransactionBroadcaster + ?Sized> DashPayView<'_, B> {
true => PlatformWalletError::WalletRemovedBeforeSend(hex::encode(self.wallet_id)),
false => error,
})?;
drop(placement);

// 8. Broadcast the signed bytes, keeping what every dispatch proved,
// by the rule shielded spends use (`broadcast_tracking_delivery`):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
//! The shielded payment address a contact request carries.

use super::identity_handle::IdentityWallet;
use crate::broadcaster::TransactionBroadcaster;
use crate::error::PlatformWalletError;
#[cfg(feature = "shielded")]
use crate::wallet::shielded::shielded_identity_account_index;
#[cfg(feature = "shielded")]
use dash_sdk::platform::Fetch;
#[cfg(feature = "shielded")]
use dpp::data_contract::accessors::v0::DataContractV0Getters;
#[cfg(feature = "shielded")]
use dpp::data_contract::document_type::accessors::DocumentTypeV0Getters;
#[cfg(feature = "shielded")]
use dpp::data_contracts::SystemDataContract;
#[cfg(feature = "shielded")]
use dpp::prelude::DataContract;
use dpp::prelude::Identifier;

/// The DashPay document type of a contact request.
#[cfg(feature = "shielded")]
const CONTACT_REQUEST: &str = "contactRequest";

/// The `contactRequest` property that carries the sender's shielded address.
#[cfg(feature = "shielded")]
const ENCRYPTED_SHIELDED_ADDRESS: &str = "encryptedShieldedAddress";

/// Log why `owner_id`'s contact request goes without a shielded address. The
/// request is still sent, so this is the only trace of the reason.
#[cfg(feature = "shielded")]
fn without_address(owner_id: &Identifier, reason: &str) {
tracing::debug!(
identity = %owner_id,
reason,
"contact request sent without a shielded address"
);
}

impl<B: TransactionBroadcaster + ?Sized> IdentityWallet<B> {
/// The shielded payment address `owner_id` gives `to_user_id` in the contact request
/// it sends under `account_reference`, or `None` when the request goes without one.
///
/// The address is the one the identity's shielded account derives for this request
/// alone (`AccountViewingKeys::contact_address`), so every contact gets a different
/// one and a payment that arrives on it is attributed to that contact. It is `None`
/// unless all of these hold:
///
/// - the identity's shielded account was prepared in this session, which proves with
/// the seed that the identity holds the slot the account belongs to, and it is
/// still the account of the slot the identity holds;
/// - that account's viewing keys are bound;
/// - the connected network's contact requests have the property that carries the
/// address. A bundled schema does not show the network has activated it.
///
/// The send is refused when the address would be one this identity has given
/// another contact. That takes a collision in 87 bits of a keyed hash.
///
/// The caller holds the identity's placement from this call until the request is
/// signed, so the account is still the identity's when the request commits to it.
pub(crate) async fn contact_shielded_address(
&self,
owner_id: &Identifier,
to_user_id: &Identifier,
account_reference: u32,
) -> Result<Option<[u8; 43]>, PlatformWalletError> {
#[cfg(not(feature = "shielded"))]
{
let _ = (owner_id, to_user_id, account_reference);
Ok(None)
}
#[cfg(feature = "shielded")]
{
// The account of the slot the identity holds now, and the requests it has
// sent to its other contacts.
let (account, others) = {
let wm = self.wallet_manager.read().await;
let Some(managed) = wm
.get_wallet_info(&self.wallet_id)
.and_then(|info| info.identity_manager.managed_identity(owner_id))
.filter(|identity| identity.wallet_id == Some(self.wallet_id))
else {
without_address(owner_id, "the wallet does not hold the identity");
return Ok(None);
};
let Some(account) = managed
.identity_index
.and_then(|index| shielded_identity_account_index(index).ok())
else {
without_address(owner_id, "the identity has no shielded account");
return Ok(None);
};
(account, managed.other_sent_account_references(to_user_id))
};
let Some(keys) = self
.contact_shielded_addresses
.proven_account_keys(owner_id, account)
.await
else {
without_address(
owner_id,
"the identity's shielded account is not prepared in this session, or \
its viewing keys are not bound",
);
return Ok(None);
};
if !self.contact_requests_carry_shielded_address().await? {
without_address(
owner_id,
"the network's contact requests do not carry a shielded address yet",
);
return Ok(None);
}

let owner = owner_id.as_bytes();
let reference = u64::from(account_reference);
let index = keys.contact_index(owner, to_user_id.as_bytes(), reference);
let taken = others.iter().any(|(other, other_reference)| {
keys.contact_index(owner, other.as_bytes(), u64::from(*other_reference)) == index
});
if taken {
return Err(PlatformWalletError::InvalidIdentityData(
"The shielded address of this contact request is one already given to \
another contact; send the request under another account reference"
.to_string(),
));
}
Ok(Some(
keys.contact_address(owner, to_user_id.as_bytes(), reference)
.to_raw_address_bytes(),
))
}
}

/// Whether the connected network's DashPay contract gives contact requests the
/// property that carries a shielded address, which it does from DashPay v3 at
/// protocol version 15. Read from the network: the bundled schema is the latest one.
#[cfg(feature = "shielded")]
async fn contact_requests_carry_shielded_address(&self) -> Result<bool, PlatformWalletError> {
let contract = DataContract::fetch(&self.sdk, SystemDataContract::Dashpay.id())
.await?
.ok_or_else(|| {
PlatformWalletError::InvalidIdentityData(
"DashPay contract is not available".to_string(),
)
})?;
let contact_request = contract
.document_type_for_name(CONTACT_REQUEST)
.map_err(|e| PlatformWalletError::InvalidIdentityData(e.to_string()))?;
Ok(contact_request
.properties()
.contains_key(ENCRYPTED_SHIELDED_ADDRESS))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3947,6 +3947,8 @@ mod tests {
dpns_operation_gate: Arc::new(tokio::sync::Mutex::new(())),
dpns_sync_progress: Arc::new(std::sync::Mutex::new(BTreeMap::new())),
identity_placement: Arc::new(tokio::sync::RwLock::new(())),
#[cfg(feature = "shielded")]
contact_shielded_addresses: Default::default(),
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -542,6 +542,11 @@ pub struct IdentityWallet<B: TransactionBroadcaster + ?Sized = SpvBroadcaster> {
/// tip address publication take it for reading). Taken before
/// `wallet_manager`.
pub(crate) identity_placement: Arc<tokio::sync::RwLock<()>>,
/// The platform wallet's shielded viewing keys and seed-proven identity accounts,
/// from which the address a contact request carries is derived
/// ([`Self::contact_shielded_address`]).
#[cfg(feature = "shielded")]
pub(crate) contact_shielded_addresses: crate::wallet::shielded::ContactShieldedAddresses,
}

// Manual `Debug`: the derive would require `B: Debug`, which is not part
Expand Down Expand Up @@ -572,6 +577,8 @@ impl<B: TransactionBroadcaster + ?Sized> Clone for IdentityWallet<B> {
dpns_operation_gate: Arc::clone(&self.dpns_operation_gate),
dpns_sync_progress: Arc::clone(&self.dpns_sync_progress),
identity_placement: Arc::clone(&self.identity_placement),
#[cfg(feature = "shielded")]
contact_shielded_addresses: self.contact_shielded_addresses.clone(),
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ pub(crate) use withdrawal::{select_owner_withdrawal_key, select_transfer_withdra
// DashPay-contract operations, namespaced behind `IdentityWallet::dashpay()`.
mod contact_info;
mod contact_requests;
mod contact_shielded_address;
mod contacts;
mod dashpay_view;
mod invitation;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13436,6 +13436,8 @@ mod tests {
dpns_operation_gate: Arc::clone(&real.dpns_operation_gate),
dpns_sync_progress: Arc::clone(&real.dpns_sync_progress),
identity_placement: Arc::clone(&real.identity_placement),
#[cfg(feature = "shielded")]
contact_shielded_addresses: real.contact_shielded_addresses.clone(),
}
}

Expand Down Expand Up @@ -13480,6 +13482,8 @@ mod tests {
dpns_operation_gate: Arc::clone(&real.dpns_operation_gate),
dpns_sync_progress: Arc::clone(&real.dpns_sync_progress),
identity_placement: Arc::clone(&real.identity_placement),
#[cfg(feature = "shielded")]
contact_shielded_addresses: real.contact_shielded_addresses.clone(),
}
}

Expand Down Expand Up @@ -13538,6 +13542,8 @@ mod tests {
dpns_operation_gate: Arc::clone(&real.dpns_operation_gate),
dpns_sync_progress: Arc::clone(&real.dpns_sync_progress),
identity_placement: Arc::clone(&real.identity_placement),
#[cfg(feature = "shielded")]
contact_shielded_addresses: real.contact_shielded_addresses.clone(),
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,9 @@ pub(crate) struct SendContactRequestParams<'a> {
pub account_label: Option<String>,
/// Optional unencrypted auto-accept proof.
pub auto_accept_proof: Option<Vec<u8>>,
/// The sender's shielded payment address for this contact, 43 raw bytes, which the
/// SDK encrypts under the shared secret. `None` sends the request without one.
pub shielded_address: Option<[u8; 43]>,
/// ECDH shared secret, already derived by the caller against the
/// recipient's encryption key (client-side ECDH). The SDK encrypts
/// the shared xpub with this directly; no private key crosses into
Expand Down Expand Up @@ -194,6 +197,7 @@ impl SdkWriter {
account_reference,
account_label,
auto_accept_proof,
shielded_address,
shared_secret,
expected_recipient_pubkey,
xpub_bytes,
Expand All @@ -209,6 +213,7 @@ impl SdkWriter {
account_reference,
account_label,
auto_accept_proof,
shielded_address,
};

let send_input = SendContactRequestInput {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,40 @@ impl ManagedIdentity {
})
}

/// The contact requests this identity has sent to contacts other than
/// `recipient`, as `(recipient, account reference)`.
///
/// Both maps, as for [`Self::prior_sent_account_reference`]: a request
/// leaves `sent_contact_requests` for
/// `established_contacts[..].outgoing_request` once its contact
/// establishes, and what it issued stays issued. A request whose
/// broadcast is not settled yet counts too: it may already be on
/// Platform.
#[cfg(any(feature = "shielded", test))]
pub(crate) fn other_sent_account_references(
&self,
recipient: &Identifier,
) -> Vec<(Identifier, u32)> {
self.dashpay
.sent_contact_requests
.values()
.chain(
self.dashpay
.established_contacts
.values()
.map(|contact| &contact.outgoing_request),
)
.map(|request| (request.recipient_id, request.account_reference))
.chain(
self.dashpay
.unconfirmed_public_requests
.iter()
.map(|(to, request)| (*to, request.account_reference)),
)
.filter(|(to, _)| to != recipient)
.collect()
Comment thread
QuantumExplorer marked this conversation as resolved.
Resolved
}

/// Add a sent contact request.
///
/// If there's already an incoming request from the recipient, the
Expand Down Expand Up @@ -1603,6 +1637,68 @@ mod tests {
assert_eq!(managed.dashpay.established_contacts.len(), 0);
}

/// A request's account reference stays issued once its contact
/// establishes, when the request moves out of the pending map.
#[test]
fn should_list_the_references_sent_to_pending_and_established_contacts() {
let mut managed = create_test_identity([1u8; 32]);
let our_id = Identifier::from([1u8; 32]);
let pending_id = Identifier::from([2u8; 32]);
let established_id = Identifier::from([3u8; 32]);
let p = noop_persister();
for contact in [pending_id, established_id] {
managed
.add_sent_contact_request(create_contact_request(our_id, contact, 1), &p)
.expect("setup persists");
}
managed
.add_incoming_contact_request(create_contact_request(established_id, our_id, 2), &p)
.expect("setup persists");
assert!(managed
.dashpay
.established_contacts
.contains_key(&established_id));

let mut others = managed.other_sent_account_references(&Identifier::from([9u8; 32]));
others.sort();
assert_eq!(others, vec![(pending_id, 0), (established_id, 0)]);
assert_eq!(
managed.other_sent_account_references(&established_id),
vec![(pending_id, 0)]
);
assert_eq!(
managed.other_sent_account_references(&pending_id),
vec![(established_id, 0)]
);
}

/// A request held after its broadcast, with no proof of the outcome yet,
/// may already be on Platform: its account reference counts as issued.
#[test]
fn should_list_the_reference_of_a_request_whose_broadcast_is_not_settled() {
use dpp::state_transition::batch_transition::BatchTransition;
use key_wallet::bip32::ExtendedPrivKey;
use key_wallet::Network;
let mut managed = create_test_identity([1u8; 32]);
let unsettled_id = Identifier::from([4u8; 32]);
let master = ExtendedPrivKey::new_master(Network::Testnet, &[42u8; 32]).expect("a key");
managed.hold_unconfirmed_public_request(
unsettled_id,
StateTransition::Batch(BatchTransition::V0(Default::default())),
7,
0,
ExtendedPubKey::from_priv(&master),
);

assert_eq!(
managed.other_sent_account_references(&Identifier::from([9u8; 32])),
vec![(unsettled_id, 7)]
);
assert!(managed
.other_sent_account_references(&unsettled_id)
.is_empty());
}

#[test]
fn test_add_sent_then_incoming_auto_establishes() {
let mut managed = create_test_identity([1u8; 32]);
Expand Down
Loading
Loading