diff --git a/packages/rs-platform-wallet-ffi/src/error.rs b/packages/rs-platform-wallet-ffi/src/error.rs index 5e7bc342baf..5e1abe6593a 100644 --- a/packages/rs-platform-wallet-ffi/src/error.rs +++ b/packages/rs-platform-wallet-ffi/src/error.rs @@ -977,6 +977,11 @@ impl From for PlatformWalletFFIResult { PlatformWalletError::AssetLockNotTracked(..) => { PlatformWalletFFIResultCode::ErrorAssetLockNotTracked } + // A DashPay invitation link for the other network: definitive, so + // hosts can say so instead of treating it as undetermined. + PlatformWalletError::InvitationNetworkMismatch { .. } => { + PlatformWalletFFIResultCode::ErrorInvalidNetwork + } PlatformWalletError::AssetLockAlreadyConsumed(..) => { PlatformWalletFFIResultCode::ErrorAssetLockAlreadyConsumed } diff --git a/packages/rs-platform-wallet-ffi/src/invitation.rs b/packages/rs-platform-wallet-ffi/src/invitation.rs index fc0b9a45c0a..bc258dd02ea 100644 --- a/packages/rs-platform-wallet-ffi/src/invitation.rs +++ b/packages/rs-platform-wallet-ffi/src/invitation.rs @@ -30,7 +30,7 @@ use std::os::raw::c_char; use dpp::identity::accessors::IdentityGettersV0; use platform_wallet::wallet::identity::crypto::{ - parse_invitation_uri, wif_network_matches, InviterInfo, + parse_invitation_uri, InviterInfo, ParsedInvitation, }; use rs_sdk_ffi::{MnemonicResolverCoreSigner, MnemonicResolverHandle, SignerHandle, VTableSigner}; @@ -336,6 +336,19 @@ pub unsafe extern "C" fn platform_wallet_claim_invitation( PlatformWalletFFIResult::ok() } +/// Parse a link for one of the read-only invitation queries. A malformed link +/// is definitive, not undetermined: there is no invitation to claim, so it is +/// its own code (`ErrorInvalidParameter`) and the caller can say so instead of +/// falling through the generic arm into "proceed anyway". +fn parse_invitation_for_query(uri: &str) -> Result { + parse_invitation_uri(uri).map_err(|e| { + PlatformWalletFFIResult::err( + PlatformWalletFFIResultCode::ErrorInvalidParameter, + format!("invitation link is malformed and cannot be claimed: {e}"), + ) + }) +} + /// The identity id this invitation WOULD create — a read-only probe that lets /// the UI reject an already-claimed voucher up front. /// @@ -369,8 +382,7 @@ pub unsafe extern "C" fn platform_wallet_claim_invitation( /// /// * `ErrorInvalidParameter` — the URI is malformed, so there is no invitation. /// * `ErrorInvalidNetwork` — the voucher key belongs to the other network; -/// [`platform_wallet_claim_invitation`] applies the same guard and will -/// refuse it too. +/// [`platform_wallet_claim_invitation`] refuses it with the same code. /// /// Every other failure (funding-tx not yet propagated, transport error) leaves /// usability genuinely undetermined, and only those should be treated as @@ -385,58 +397,31 @@ pub unsafe extern "C" fn platform_wallet_invitation_prospective_identity_id( uri: *const c_char, out_identity_id: *mut [u8; 32], ) -> PlatformWalletFFIResult { - check_ptr!(uri); check_ptr!(out_identity_id); // Sentinel before any fallible work, matching the claim/parse siblings. unsafe { *out_identity_id = [0u8; 32]; } + check_ptr!(uri); let uri = unwrap_result_or_return!(unsafe { CStr::from_ptr(uri) }.to_str()); - // A malformed link is definitive, not undetermined: there is no invitation - // to claim. Surfaced as its own code so the caller can say so instead of - // falling through the generic arm into "proceed anyway". - let invitation = match parse_invitation_uri(uri) { + let invitation = match parse_invitation_for_query(uri) { Ok(invitation) => invitation, - Err(e) => { - return PlatformWalletFFIResult::err( - PlatformWalletFFIResultCode::ErrorInvalidParameter, - format!("invitation link is malformed and cannot be claimed: {e}"), - ); - } + Err(e) => return e, }; - let option = PLATFORM_WALLET_STORAGE.with_item( - wallet_handle, - |wallet| -> Result { - // Also definitive: the claim applies the same guard, so a link for the - // other network can never be claimed through this wallet. Checked here - // (as the withdrawal FFI does) to give it a distinguishable code rather - // than flattening into the catch-all the library error maps to. - if !wif_network_matches(invitation.voucher_key_network, wallet.network()) { - return Err(PlatformWalletFFIResult::err( - PlatformWalletFFIResultCode::ErrorInvalidNetwork, - format!( - "invitation is for the {:?} network but this wallet is on {:?}", - invitation.voucher_key_network, - wallet.network() - ), - )); - } - let identity_wallet = wallet.identity().clone(); - block_on_worker(async move { - identity_wallet - .invitation_prospective_identity_id(&invitation) - .await - }) - .map_err(PlatformWalletFFIResult::from) - }, - ); + // A link for the other network comes back as the library's typed + // mismatch, which maps to `ErrorInvalidNetwork`. + let option = PLATFORM_WALLET_STORAGE.with_item(wallet_handle, |wallet| { + let identity_wallet = wallet.identity().clone(); + block_on_worker(async move { + identity_wallet + .invitation_prospective_identity_id(&invitation) + .await + }) + }); let result = unwrap_option_or_return!(option); - let identifier = match result { - Ok(identifier) => identifier, - Err(e) => return e, - }; + let identifier = unwrap_result_or_return!(result); unsafe { *out_identity_id = identifier.to_buffer(); } @@ -488,7 +473,9 @@ impl From for InvitationClaimStatusFFI { /// What an invitation is worth and whether it was already claimed, without /// claiming it: one funding-tx fetch (with the claim's propagation retry) and -/// one identity fetch. +/// one identity fetch. A ChainLock-only link whose funding tx is not +/// chain-locked yet is reported (`is_instant` and `is_chain_locked` both +/// false) rather than refused. /// /// Same error contract as /// [`platform_wallet_invitation_prospective_identity_id`]: @@ -509,48 +496,24 @@ pub unsafe extern "C" fn platform_wallet_invitation_claim_status( uri: *const c_char, out_status: *mut InvitationClaimStatusFFI, ) -> PlatformWalletFFIResult { - check_ptr!(uri); check_ptr!(out_status); unsafe { *out_status = InvitationClaimStatusFFI::zeroed(); } + check_ptr!(uri); let uri = unwrap_result_or_return!(unsafe { CStr::from_ptr(uri) }.to_str()); - let invitation = match parse_invitation_uri(uri) { + let invitation = match parse_invitation_for_query(uri) { Ok(invitation) => invitation, - Err(e) => { - return PlatformWalletFFIResult::err( - PlatformWalletFFIResultCode::ErrorInvalidParameter, - format!("invitation link is malformed and cannot be claimed: {e}"), - ); - } + Err(e) => return e, }; - let option = PLATFORM_WALLET_STORAGE.with_item( - wallet_handle, - |wallet| -> Result { - if !wif_network_matches(invitation.voucher_key_network, wallet.network()) { - return Err(PlatformWalletFFIResult::err( - PlatformWalletFFIResultCode::ErrorInvalidNetwork, - format!( - "invitation is for the {:?} network but this wallet is on {:?}", - invitation.voucher_key_network, - wallet.network() - ), - )); - } - let identity_wallet = wallet.identity().clone(); - block_on_worker( - async move { identity_wallet.invitation_claim_status(&invitation).await }, - ) - .map_err(PlatformWalletFFIResult::from) - }, - ); + let option = PLATFORM_WALLET_STORAGE.with_item(wallet_handle, |wallet| { + let identity_wallet = wallet.identity().clone(); + block_on_worker(async move { identity_wallet.invitation_claim_status(&invitation).await }) + }); let result = unwrap_option_or_return!(option); - let status = match result { - Ok(status) => status, - Err(e) => return e, - }; + let status = unwrap_result_or_return!(result); unsafe { *out_status = status.into(); } @@ -587,7 +550,8 @@ pub struct InvitationPreviewFFI { /// [`crate::platform_wallet_string_free`]. pub inviter_username: *mut c_char, /// Amount locked in the voucher (duffs) — always 0: unknown pre-fetch (the - /// link carries the funding txid, not the proof), resolved at claim time. + /// link carries the funding txid, not the proof). Read it with + /// [`platform_wallet_invitation_claim_status`]. pub amount_duffs: u64, /// Advisory expiry (unix seconds) — always 0: the legacy link carries no /// expiry field. @@ -637,8 +601,9 @@ fn optional_c_string(value: Option<&String>) -> *mut c_char { /// the UI can render a clean "invalid invitation" state; only a null / non-UTF-8 /// `uri` argument returns an error result. /// -/// When `out_preview.inviter_username` is non-null it is a heap C string the -/// caller frees with [`crate::platform_wallet_string_free`]. It can be null +/// `out_preview.inviter_username`, `inviter_display_name` and +/// `inviter_avatar_url` are each either null or a heap C string the caller +/// frees with [`crate::platform_wallet_string_free`]. The username can be null /// even when `has_inviter` is set (a metadata-only link) — see the field docs. /// /// # Safety @@ -959,7 +924,7 @@ mod tests { /// The inviter's display name and avatar URL travel through the preview /// (percent-decoded), and both are null for a link that carries neither. #[test] - fn parse_invitation_surfaces_inviter_display_name_and_avatar() { + fn should_surface_inviter_display_name_and_avatar_in_the_preview() { let key = SecretKey::from_slice(&[0x11u8; 32]).unwrap(); let wif = PrivateKey::new(key, Network::Testnet).to_wif(); let txid = "ab".repeat(32); @@ -1006,7 +971,7 @@ mod tests { /// A malformed link is a definitive `ErrorInvalidParameter` from the status /// call — never a zeroed "not claimed" the caller could proceed on. #[test] - fn claim_status_malformed_uri_is_invalid_parameter() { + fn should_refuse_a_malformed_link_in_claim_status_as_invalid_parameter() { let bad = std::ffi::CString::new("https://not-an-invite").unwrap(); let mut status = InvitationClaimStatusFFI::zeroed(); status.amount_duffs = 7; @@ -1015,13 +980,33 @@ mod tests { assert_eq!(status.amount_duffs, 0, "the out-param is zeroed first"); } - /// A null `uri` is rejected with `ErrorNullPointer`. + /// A null `uri` is rejected with `ErrorNullPointer`, after the out-param + /// is zeroed. #[test] - fn claim_status_null_uri_is_null_pointer() { + fn should_refuse_a_null_uri_in_claim_status_and_still_zero_the_status() { let mut status = InvitationClaimStatusFFI::zeroed(); + status.already_claimed = true; let r = unsafe { platform_wallet_invitation_claim_status(0, std::ptr::null(), &mut status) }; assert_eq!(r.code, PlatformWalletFFIResultCode::ErrorNullPointer); + assert!(!status.already_claimed, "the out-param is zeroed first"); + } + + /// A link for the other network is refused by the library with a typed + /// error that must reach hosts as the definitive `ErrorInvalidNetwork`, + /// not the undetermined catch-all. + #[test] + fn should_map_an_invitation_network_mismatch_to_invalid_network() { + let result = PlatformWalletFFIResult::from( + platform_wallet::PlatformWalletError::InvitationNetworkMismatch { + invitation: Network::Testnet, + wallet: Network::Mainnet, + }, + ); + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorInvalidNetwork + ); } /// The amount-bound getters hand back the library constants verbatim. This diff --git a/packages/rs-platform-wallet/src/error.rs b/packages/rs-platform-wallet/src/error.rs index 64515d898d9..ee3307e4623 100644 --- a/packages/rs-platform-wallet/src/error.rs +++ b/packages/rs-platform-wallet/src/error.rs @@ -67,6 +67,15 @@ pub enum PlatformWalletError { #[error("Invalid identity data: {0}")] InvalidIdentityData(String), + /// A DashPay invitation link's voucher key is for the other network (a + /// testnet link opened in a mainnet wallet, or the reverse). Definitive: + /// the claim refuses the link before any network work. + #[error("invitation is for the {invitation:?} network but this wallet is on {wallet:?}")] + InvitationNetworkMismatch { + invitation: Network, + wallet: Network, + }, + #[error("Failed to persist state: {0}")] /// A persister `store(...)` round failed. Returned (not swallowed) by /// user-initiated writes whose loss leaves a silent, non-self-healing @@ -1247,25 +1256,6 @@ pub fn is_asset_lock_already_consumed( ) } -/// Platform refused an identity create in a way that means the same create -/// was already accepted: the identical transition is still in the mempool -/// ("tx already exists in cache" — a broadcast that timed out after the node -/// took it, then retried elsewhere), or its funding outpoint is consumed. -/// -/// Neither says by whom. A caller may treat the create as done only after -/// fetching the identity and checking it carries the keys it submitted. -pub fn is_identity_create_already_landed(error: &dash_sdk::Error) -> bool { - use dpp::consensus::basic::BasicError; - - matches!(error, dash_sdk::Error::AlreadyExists(_)) - || matches!( - consensus_error_of(error), - Some(ConsensusError::BasicError( - BasicError::IdentityAssetLockTransactionOutPointAlreadyConsumedError(_) - )) - ) -} - /// Promote a document-trade consensus rejection to its typed /// [`PlatformWalletError`] so callers get structured data instead of a /// stringified verdict: diff --git a/packages/rs-platform-wallet/src/wallet/identity/crypto/invitation.rs b/packages/rs-platform-wallet/src/wallet/identity/crypto/invitation.rs index 6060013024a..ce3ba5023ce 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/crypto/invitation.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/crypto/invitation.rs @@ -43,7 +43,7 @@ use dashcore::secp256k1::{PublicKey, Secp256k1, SecretKey}; use dashcore::transaction::special_transaction::TransactionPayload; -use dashcore::{Network, PrivateKey, ScriptBuf, Transaction}; +use dashcore::{Network, PrivateKey, ScriptBuf, Transaction, TxOut}; use dpp::prelude::AssetLockProof; use crate::error::PlatformWalletError; @@ -514,6 +514,15 @@ pub fn voucher_output_index( transaction: &Transaction, voucher_key: &SecretKey, ) -> Result { + voucher_credit_output(transaction, voucher_key).map(|(index, _)| index) +} + +/// [`voucher_output_index`] plus the selected credit output itself, so a +/// caller that needs the voucher's value reads it from the same match. +pub fn voucher_credit_output<'a>( + transaction: &'a Transaction, + voucher_key: &SecretKey, +) -> Result<(u32, &'a TxOut), PlatformWalletError> { let Some(TransactionPayload::AssetLockPayloadType(payload)) = &transaction.special_transaction_payload else { @@ -525,8 +534,9 @@ pub fn voucher_output_index( payload .credit_outputs .iter() - .position(|out| out.script_pubkey == expected) - .map(|idx| idx as u32) + .enumerate() + .find(|(_, out)| out.script_pubkey == expected) + .map(|(index, out)| (index as u32, out)) .ok_or_else(|| { invalid("voucher key does not control any credit output of the funding transaction") }) @@ -768,6 +778,18 @@ mod tests { assert_eq!(voucher_output_index(&tx, &key).unwrap(), 2); } + /// The credit output comes back with its index, so its value is the + /// voucher's, not a decoy's. + #[test] + fn should_return_the_voucher_credit_output_with_its_index() { + let key = voucher(); + let tx = asset_lock_tx_paying_voucher_at(&key, 2); + let (index, output) = voucher_credit_output(&tx, &key).unwrap(); + assert_eq!(index, 2); + assert_eq!(output.value, 100_000, "the decoys before it carry 50_000"); + assert_eq!(output.script_pubkey, voucher_credit_script(&key)); + } + #[test] fn voucher_output_index_rejects_no_match() { let key = voucher(); diff --git a/packages/rs-platform-wallet/src/wallet/identity/crypto/mod.rs b/packages/rs-platform-wallet/src/wallet/identity/crypto/mod.rs index c0a0687b44b..8164e130b0b 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/crypto/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/crypto/mod.rs @@ -19,7 +19,7 @@ pub use dip14::{ derive_contact_xpub, unmask_account_reference, ContactXpubData, DEFAULT_CONTACT_GAP_LIMIT, }; pub use invitation::{ - encode_invitation_uri, parse_invitation_uri, voucher_output_index, wif_network_matches, - InviterInfo, ParsedInvitation, + encode_invitation_uri, parse_invitation_uri, voucher_credit_output, voucher_output_index, + wif_network_matches, InviterInfo, ParsedInvitation, }; pub use validation::pubkey_binds_expected_key_data; diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/invitation.rs b/packages/rs-platform-wallet/src/wallet/identity/network/invitation.rs index d65182344fa..161c0fa223a 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/invitation.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/invitation.rs @@ -17,8 +17,7 @@ use std::collections::BTreeMap; use dpp::dashcore::consensus::Decodable; -use dpp::dashcore::transaction::special_transaction::TransactionPayload; -use dpp::dashcore::{InstantLock, OutPoint, PrivateKey, Transaction}; +use dpp::dashcore::{InstantLock, Network, OutPoint, PrivateKey, Transaction}; use dpp::identity::accessors::IdentityGettersV0; use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; use dpp::identity::signer::Signer; @@ -34,15 +33,17 @@ use crate::changeset::{ InvitationChangeSet, InvitationEntry, InvitationStatus, PersistenceCapabilities, }; +use dash_sdk::core::FetchedCoreTransaction; use dash_sdk::platform::transition::put_identity::PutIdentity; use dash_sdk::platform::transition::put_settings::PutSettings; +use dash_sdk::platform::Fetch; use crate::error::{ - is_identity_create_already_landed, is_instant_lock_proof_invalid, PlatformWalletError, + is_asset_lock_already_consumed, is_instant_lock_proof_invalid, PlatformWalletError, }; -use crate::wallet::asset_lock::orchestration::submit_with_cl_height_retry; +use crate::wallet::asset_lock::orchestration::{out_point_from_proof, submit_with_cl_height_retry}; use crate::wallet::identity::crypto::{ - encode_invitation_uri, voucher_output_index, wif_network_matches, + encode_invitation_uri, voucher_credit_output, wif_network_matches, }; use crate::wallet::identity::crypto::{InviterInfo, ParsedInvitation}; use crate::wallet::identity::network::contact_requests::ContactCryptoProvider; @@ -130,7 +131,8 @@ pub struct InvitationClaimStatus { pub amount_duffs: u64, /// The claim would submit an InstantSend proof (the link carried an islock). pub is_instant: bool, - /// The funding transaction is chain-locked. + /// The funding transaction is chain-locked. `false` with `is_instant == + /// false` is a ChainLock-only invitation whose claim must wait for it. pub is_chain_locked: bool, /// An identity exists at `prospective_identity_id` — definitively claimed. /// `false` does NOT prove the voucher is unspent (see @@ -447,22 +449,8 @@ impl IdentityWallet { &self, invitation: &ParsedInvitation, ) -> Result { - if !wif_network_matches(invitation.voucher_key_network, self.sdk.network) { - return Err(PlatformWalletError::InvalidIdentityData(format!( - "invitation is for the {:?} network but this wallet is on {:?}", - invitation.voucher_key_network, self.sdk.network - ))); - } - let proof = self.reconstruct_asset_lock_proof(invitation).await?; - // The reconstruction now carries an optional ChainLock fallback for - // the claim path; the prospective id is always derived from the - // PRIMARY proof (both proofs cover the same credit output, so the - // id is identical either way). - proof.primary.create_identifier().map_err(|e| { - PlatformWalletError::InvalidIdentityData(format!( - "invitation asset lock proof yielded no identity id: {e}" - )) - }) + let funding = self.inspect_invitation_funding(invitation).await?; + Ok(identity_id_for_out_point(funding.out_point)) } /// What an invitation is worth and whether it was already claimed — the @@ -480,60 +468,33 @@ impl IdentityWallet { /// `false` does not prove the voucher is unspent (a reclaim top-up consumes /// it without creating the derived identity). /// + /// It describes the funding transaction rather than requiring a buildable + /// proof: a ChainLock-only link whose funding tx is not chain-locked yet + /// reports `is_instant == false, is_chain_locked == false` and its amount + /// instead of failing (the claim of such a link waits for the ChainLock). + /// A failed identity lookup still fails the whole call. + /// /// Costs one funding-tx fetch (with the claim's bounded propagation retry) /// and one identity fetch. Same wrong-network fail-fast as the claim. pub async fn invitation_claim_status( &self, invitation: &ParsedInvitation, ) -> Result { - use dash_sdk::platform::Fetch; - - if !wif_network_matches(invitation.voucher_key_network, self.sdk.network) { - return Err(PlatformWalletError::InvalidIdentityData(format!( - "invitation is for the {:?} network but this wallet is on {:?}", - invitation.voucher_key_network, self.sdk.network - ))); - } - let proof = self.reconstruct_asset_lock_proof(invitation).await?; - let prospective_identity_id = proof.primary.create_identifier().map_err(|e| { - PlatformWalletError::InvalidIdentityData(format!( - "invitation asset lock proof yielded no identity id: {e}" - )) - })?; - let is_instant = matches!(proof.primary, AssetLockProof::Instant(_)); - // A ChainLock primary is only ever built for a chain-locked tx, and an - // InstantSend primary carries a ChainLock fallback exactly when the tx - // is chain-locked. - let is_chain_locked = !is_instant || proof.chain_fallback.is_some(); + let funding = self.inspect_invitation_funding(invitation).await?; + let prospective_identity_id = identity_id_for_out_point(funding.out_point); let already_claimed = Identity::fetch(&self.sdk, prospective_identity_id) .await .map_err(PlatformWalletError::Sdk)? .is_some(); Ok(InvitationClaimStatus { prospective_identity_id, - amount_duffs: proof.credit_output_duffs, - is_instant, - is_chain_locked, + amount_duffs: funding.credit_output_duffs, + is_instant: funding.instant_lock.is_some(), + is_chain_locked: funding.is_chain_locked, already_claimed, }) } - /// The identity at `identity_id` when it carries exactly `expected_keys` - /// — the one a claim of ours created — or `None` when there is none or it - /// belongs to someone else. - async fn fetch_own_claimed_identity( - &self, - identity_id: Identifier, - expected_keys: &BTreeMap, - ) -> Result, PlatformWalletError> { - use dash_sdk::platform::Fetch; - - let fetched = Identity::fetch(&self.sdk, identity_id) - .await - .map_err(PlatformWalletError::Sdk)?; - Ok(fetched.filter(|identity| identity_carries_keys(identity, expected_keys))) - } - /// Claim a DashPay invitation: register a NEW identity for the invitee, /// funded by the imported voucher. /// @@ -581,16 +542,7 @@ impl IdentityWallet { S: Signer + Send + Sync, { preflight_keys_map(&keys_map)?; - - // Reject a wrong-network link before any network work: a testnet WIF is a - // valid key on the wrong chain, so it would otherwise surface as a - // confusing funding-tx fetch miss rather than a clear "wrong network". - if !wif_network_matches(invitation.voucher_key_network, self.sdk.network) { - return Err(PlatformWalletError::InvalidIdentityData(format!( - "invitation is for the {:?} network but this wallet is on {:?}", - invitation.voucher_key_network, self.sdk.network - ))); - } + ensure_invitation_network(&invitation, self.sdk.network)?; // Reconstruct the funding asset-lock proof by refetching the tx. Consensus // enforces pk↔output, islock↔tx, and identity_id↔outpoint, so the local @@ -605,15 +557,12 @@ impl IdentityWallet { let ReconstructedProof { primary, chain_fallback, - .. } = self.reconstruct_asset_lock_proof(&invitation).await?; - // Taken before `primary` moves into the submission: the identity this - // claim creates, for recognizing our own earlier submission below. - let prospective_identity_id = primary.create_identifier().map_err(|e| { - PlatformWalletError::InvalidIdentityData(format!( - "invitation asset lock proof yielded no identity id: {e}" - )) - })?; + // Taken before `primary` moves into the submission: the outpoint this + // claim spends and the identity it creates, for recognizing our own + // earlier claim below. + let out_point = out_point_from_proof(&primary); + let prospective_identity_id = identity_id_for_out_point(out_point); // The voucher key signs the asset lock's outer ST signature (ECDSA over // the credit-output pubkey hash). Convert to the SDK's `PrivateKey`, @@ -658,31 +607,16 @@ impl IdentityWallet { }) .await; - // A claim that already landed reports itself as a failure: a broadcast - // that timed out after the node accepted it is retried by the DAPI - // client and refused as "tx already exists in cache", and a claim - // repeated after that is refused because the outpoint is consumed. - // Either way the identity exists — if it carries exactly the keys we - // submitted, it is ours and the claim succeeded. - let identity = match submitted { - Ok(identity) => identity, - Err(PlatformWalletError::Sdk(error)) if is_identity_create_already_landed(&error) => { - match self - .fetch_own_claimed_identity(prospective_identity_id, placeholder.public_keys()) - .await? - { - Some(identity) => { - tracing::info!( - "invitation claim was already accepted by Platform; adopting identity {}", - prospective_identity_id - ); - identity - } - None => return Err(PlatformWalletError::Sdk(error)), - } - } - Err(error) => return Err(error), - }; + // A lost-ACK duplicate of this very submission ("already in the + // mempool / in chain") is resolved inside the SDK's result wait. What + // reaches here is a claim repeated after an earlier one landed, refused + // because its outpoint is consumed: adopt the identity when it carries + // exactly the keys we submitted. + let identity = + adopt_already_landed_claim(submitted, &out_point, placeholder.public_keys(), || { + Identity::fetch(sdk, prospective_identity_id) + }) + .await?; // Best-effort local bookkeeping — Platform has already accepted the // registration, so a local failure must NOT propagate (mirrors @@ -764,8 +698,36 @@ impl IdentityWallet { &self, invitation: &ParsedInvitation, ) -> Result { + let fetched = self.fetch_funding_tx(invitation).await?; + assemble_asset_lock_proof( + fetched.transaction, + fetched.is_chain_locked, + fetched.height, + invitation, + ) + } + + /// The wrong-network guard, the funding-tx fetch and its inspection: what + /// the invitee's read-only queries need, without requiring the tx to be + /// claimable yet (see [`inspect_funding_tx`]). + async fn inspect_invitation_funding( + &self, + invitation: &ParsedInvitation, + ) -> Result { + ensure_invitation_network(invitation, self.sdk.network)?; + let fetched = self.fetch_funding_tx(invitation).await?; + inspect_funding_tx(&fetched.transaction, fetched.is_chain_locked, invitation) + } + + /// Fetch the invitation's funding transaction with the bounded propagation + /// retry (see [`fetch_funding_tx_with_retry`]); a miss after every attempt + /// is an error. + async fn fetch_funding_tx( + &self, + invitation: &ParsedInvitation, + ) -> Result { let sdk = &self.sdk; - let fetched = fetch_funding_tx_with_retry( + fetch_funding_tx_with_retry( &invitation.funding_txid, |txid| async move { sdk.get_transaction(&txid) @@ -782,13 +744,7 @@ impl IdentityWallet { retry shortly" .to_string(), ) - })?; - assemble_asset_lock_proof( - fetched.transaction, - fetched.is_chain_locked, - fetched.height, - invitation, - ) + }) } } @@ -886,6 +842,76 @@ where } } +/// Refuse a link whose voucher key is for the other network before any +/// network work: a testnet WIF is a valid key on the wrong chain, so it would +/// otherwise surface as a confusing funding-tx fetch miss. +fn ensure_invitation_network( + invitation: &ParsedInvitation, + wallet_network: Network, +) -> Result<(), PlatformWalletError> { + if wif_network_matches(invitation.voucher_key_network, wallet_network) { + Ok(()) + } else { + Err(PlatformWalletError::InvitationNetworkMismatch { + invitation: invitation.voucher_key_network, + wallet: wallet_network, + }) + } +} + +/// The identity id Platform derives from an asset-lock outpoint. Both proof +/// kinds hash only the outpoint, so the ChainLock derivation (which ignores +/// its height) gives the id for either. +fn identity_id_for_out_point(out_point: OutPoint) -> Identifier { + ChainAssetLockProof::new(0, out_point.into()).create_identifier() +} + +/// Recognize a claim Platform already executed. A claim repeated after an +/// earlier attempt landed (reported as a failure, or interrupted) is refused +/// because its outpoint is consumed; the identity at the prospective id is +/// ours when it carries exactly the keys we submitted, and is then the +/// claim's result. Anything else (no identity, someone else's, a failed +/// lookup) reports the original rejection. +/// +/// `fetch` looks up the identity at the prospective id: the injectable seam +/// (production passes `Identity::fetch`). +async fn adopt_already_landed_claim( + submitted: Result, + out_point: &OutPoint, + submitted_keys: &BTreeMap, + fetch: F, +) -> Result +where + F: FnOnce() -> Fut, + Fut: std::future::Future, dash_sdk::Error>>, +{ + let error = match submitted { + Err(PlatformWalletError::Sdk(error)) + if is_asset_lock_already_consumed(&error, out_point) => + { + error + } + other => return other, + }; + match fetch().await { + Ok(Some(identity)) if identity_carries_keys(&identity, submitted_keys) => { + tracing::info!( + identity_id = %identity.id(), + "invitation claim was already accepted by Platform; adopting its identity" + ); + Ok(identity) + } + Ok(_) => Err(PlatformWalletError::Sdk(error)), + Err(lookup) => { + tracing::warn!( + error = %lookup, + "could not look up the identity of a consumed invitation; reporting the rejection" + ); + Err(PlatformWalletError::Sdk(error)) + } + } +} + /// The identity carries exactly `expected` public keys — same ids, same key /// data. Key data is what only our signer could have produced, so a match /// means the identity was created by our claim, not by a finder of the link. @@ -918,29 +944,32 @@ fn identity_carries_keys( struct ReconstructedProof { primary: AssetLockProof, chain_fallback: Option, - /// Value (duffs) of the credit output the voucher key controls — what the - /// invitation is worth to the invitee. Read from the same selected output - /// both proofs cover. +} + +/// What an invitation's funding transaction says before any proof is built. +#[derive(Debug)] +struct InvitationFunding { + /// The voucher's credit outpoint; the claim's identity id derives from it. + out_point: OutPoint, + /// Value of that credit output (duffs): what the invitation is worth. credit_output_duffs: u64, + /// The link's islock, decoded and checked to lock this transaction. + instant_lock: Option, + /// The funding transaction is chain-locked. + is_chain_locked: bool, } -/// Assemble the asset-lock proof from an already-fetched funding transaction — the -/// pure, testable core of the claim reconstruction (the fetch/retry lives in -/// `reconstruct_asset_lock_proof`). Validates the tx is the funding tx (either byte -/// order), selects the voucher's credit output, and builds an InstantSend proof -/// (link carried an islock) or a ChainLock proof (islock absent), requiring -/// chain-lock finality for the latter. -/// -/// When an islock is present AND the funding tx is already chain-locked, the -/// returned [`ReconstructedProof`] also carries a `chain_fallback` ChainLock proof -/// over the same credit output, so the caller can recover from a stale islock that -/// Platform rejects without refetching the tx. -fn assemble_asset_lock_proof( - transaction: Transaction, +/// Check a fetched funding transaction against the link and select the +/// voucher's credit output: the pure core shared by the claim's proof +/// assembly and the read-only queries. Validates the tx is the funding tx +/// (either byte order), selects the voucher's credit output, and decodes the +/// link's islock (checking it locks this tx). Chain-lock finality is reported, +/// not required: only building a ChainLock proof needs it. +fn inspect_funding_tx( + transaction: &Transaction, is_chain_locked: bool, - height: u32, invitation: &ParsedInvitation, -) -> Result { +) -> Result { // Fail-fast: the fetched tx must actually be the funding tx (either byte // order). DAPI returns whatever tx matches the id we asked for, so this // guards a backend that answers with an unrelated tx. @@ -956,31 +985,10 @@ fn assemble_asset_lock_proof( // Select the funded credit output the voucher key controls (not index 0 // — a legacy invite's credit output need not be first). - let output_index = voucher_output_index(&transaction, &invitation.voucher_key)?; - let credit_output_duffs = match &transaction.special_transaction_payload { - Some(TransactionPayload::AssetLockPayloadType(payload)) => payload - .credit_outputs - .get(output_index as usize) - .map(|out| out.value), - _ => None, - } - .ok_or_else(|| { - PlatformWalletError::InvalidIdentityData( - "selected voucher credit output is missing from the funding transaction".to_string(), - ) - })?; - - // A ChainLock proof over the selected credit output. Buildable only once the - // funding block is chain-locked; `height` is the tx's mined height (the - // `ChainAssetLockProof`'s `core_chain_locked_height`). Reused both as the - // primary for an islock-less invite and as the stale-islock fallback. - let chain_lock_proof = |txid| -> AssetLockProof { - let out_point = OutPoint::new(txid, output_index); - let out_point_bytes: [u8; 36] = out_point.into(); - AssetLockProof::Chain(ChainAssetLockProof::new(height, out_point_bytes)) - }; + let (output_index, credit_output) = + voucher_credit_output(transaction, &invitation.voucher_key)?; - match &invitation.islock_hex { + let instant_lock = match &invitation.islock_hex { Some(islock_hex) => { let islock_bytes = hex::decode(islock_hex).map_err(|e| { PlatformWalletError::InvalidIdentityData(format!( @@ -1001,22 +1009,64 @@ fn assemble_asset_lock_proof( "invitation islock does not lock the funding transaction".to_string(), )); } + Some(instant_lock) + } + None => None, + }; + + Ok(InvitationFunding { + out_point: OutPoint::new(transaction.txid(), output_index), + credit_output_duffs: credit_output.value, + instant_lock, + is_chain_locked, + }) +} + +/// Assemble the asset-lock proof from an already-fetched funding transaction — the +/// pure, testable core of the claim reconstruction (the fetch/retry lives in +/// `reconstruct_asset_lock_proof`). Checks the tx with [`inspect_funding_tx`], then +/// builds an InstantSend proof (link carried an islock) or a ChainLock proof +/// (islock absent), requiring chain-lock finality for the latter. +/// +/// When an islock is present AND the funding tx is already chain-locked, the +/// returned [`ReconstructedProof`] also carries a `chain_fallback` ChainLock proof +/// over the same credit output, so the caller can recover from a stale islock that +/// Platform rejects without refetching the tx. +fn assemble_asset_lock_proof( + transaction: Transaction, + is_chain_locked: bool, + height: u32, + invitation: &ParsedInvitation, +) -> Result { + let InvitationFunding { + out_point, + instant_lock, + .. + } = inspect_funding_tx(&transaction, is_chain_locked, invitation)?; + + // A ChainLock proof over the selected credit output. Buildable only once the + // funding block is chain-locked; `height` is the tx's mined height (the + // `ChainAssetLockProof`'s `core_chain_locked_height`). Reused both as the + // primary for an islock-less invite and as the stale-islock fallback. + let chain_lock_proof = + || AssetLockProof::Chain(ChainAssetLockProof::new(height, out_point.into())); + + match instant_lock { + Some(instant_lock) => { // Fast path: submit the InstantSend proof. If the islock is stale // (quorum rotated / no longer "recent") Platform rejects it, and the // claim falls back to `chain_fallback` — available only when the // funding tx is already chain-locked (the usual case by claim time, - // since the voucher was funded minutes-to-hours earlier). Computed - // from `&transaction` BEFORE it is moved into the IS proof below. - let chain_fallback = is_chain_locked.then(|| chain_lock_proof(transaction.txid())); + // since the voucher was funded minutes-to-hours earlier). + let chain_fallback = is_chain_locked.then(chain_lock_proof); let primary = AssetLockProof::Instant(InstantAssetLockProof::new( instant_lock, transaction, - output_index, + out_point.vout, )); Ok(ReconstructedProof { primary, chain_fallback, - credit_output_duffs, }) } None => { @@ -1033,9 +1083,8 @@ fn assemble_asset_lock_proof( )); } Ok(ReconstructedProof { - primary: chain_lock_proof(transaction.txid()), + primary: chain_lock_proof(), chain_fallback: None, - credit_output_duffs, }) } } @@ -1167,7 +1216,6 @@ mod tests { let inv = parsed(key, txid, None); let reconstructed = assemble_asset_lock_proof(tx, true, 100, &inv).unwrap(); assert!(matches!(reconstructed.primary, AssetLockProof::Chain(_))); - assert_eq!(reconstructed.credit_output_duffs, 100_000); assert!( reconstructed.chain_fallback.is_none(), "an islock-less chainlock invite has no separate fallback" @@ -1193,7 +1241,6 @@ mod tests { matches!(reconstructed.primary, AssetLockProof::Instant(_)), "the islock fast path must be tried first" ); - assert_eq!(reconstructed.credit_output_duffs, 100_000); assert!( matches!(reconstructed.chain_fallback, Some(AssetLockProof::Chain(_))), "a chain-locked funding tx must carry a ChainLock fallback for stale-islock recovery" @@ -1255,11 +1302,17 @@ mod tests { let txid = tx.txid(); let inv = parsed(key, txid.to_string(), None); + let funding = inspect_funding_tx(&tx, true, &inv).unwrap(); + assert_eq!( + funding.credit_output_duffs, 25_000_000, + "the amount must come from the voucher's output, not the decoy at index 0" + ); let proof = assemble_asset_lock_proof(tx, true, 100, &inv).unwrap(); let id = proof.primary.create_identifier().unwrap(); assert_eq!( - proof.credit_output_duffs, 25_000_000, - "the amount must come from the voucher's output, not the decoy at index 0" + identity_id_for_out_point(funding.out_point), + id, + "the read-only queries must derive the id the claim creates" ); let from_index_0 = @@ -1322,42 +1375,249 @@ mod tests { ); } + /// A test identity key: `byte` fills the key data, so two keys differ + /// exactly when their bytes do. + fn test_key(id: KeyID, byte: u8) -> IdentityPublicKey { + use dpp::identity::identity_public_key::v0::IdentityPublicKeyV0; + use dpp::identity::KeyType; + use dpp::platform_value::BinaryData; + + IdentityPublicKey::V0(IdentityPublicKeyV0 { + id, + purpose: Purpose::AUTHENTICATION, + security_level: SecurityLevel::MASTER, + contract_bounds: None, + key_type: KeyType::ECDSA_SECP256K1, + read_only: false, + data: BinaryData::new(vec![byte; 33]), + disabled_at: None, + }) + } + + fn identity_with_keys(keys: BTreeMap) -> Identity { + Identity::V0(IdentityV0 { + id: Identifier::default(), + public_keys: keys, + balance: 0, + revision: 0, + }) + } + + fn our_keys() -> BTreeMap { + [(0, test_key(0, 1)), (1, test_key(1, 2))].into() + } + /// A claim that already landed is recognized as ours only by its keys: /// the same key set is ours, anything else (a finder of the link claiming /// first) is not. #[test] - fn claimed_identity_is_ours_only_with_our_keys() { - use dpp::identity::identity_public_key::v0::IdentityPublicKeyV0; - use dpp::identity::KeyType; - use dpp::platform_value::BinaryData; + fn should_recognize_a_claimed_identity_only_by_our_keys() { + let ours = our_keys(); + assert!(identity_carries_keys( + &identity_with_keys(ours.clone()), + &ours + )); + let theirs: BTreeMap = + [(0, test_key(0, 9)), (1, test_key(1, 2))].into(); + assert!(!identity_carries_keys(&identity_with_keys(theirs), &ours)); + let fewer: BTreeMap = [(0, test_key(0, 1))].into(); + assert!(!identity_carries_keys(&identity_with_keys(fewer), &ours)); + } - let key = |id: KeyID, byte: u8| { - IdentityPublicKey::V0(IdentityPublicKeyV0 { - id, - purpose: Purpose::AUTHENTICATION, - security_level: SecurityLevel::MASTER, - contract_bounds: None, - key_type: KeyType::ECDSA_SECP256K1, - read_only: false, - data: BinaryData::new(vec![byte; 33]), - disabled_at: None, + /// A testnet link in a mainnet wallet is refused with the typed mismatch + /// the FFI maps to `ErrorInvalidNetwork`. + #[test] + fn should_refuse_an_invitation_for_the_other_network() { + let inv = parsed(voucher_secret(), "00".repeat(32), None); + assert!(ensure_invitation_network(&inv, Network::Testnet).is_ok()); + assert!(matches!( + ensure_invitation_network(&inv, Network::Mainnet), + Err(PlatformWalletError::InvitationNetworkMismatch { + invitation: Network::Testnet, + wallet: Network::Mainnet, }) - }; - let ours: BTreeMap = [(0, key(0, 1)), (1, key(1, 2))].into(); - let identity = |keys: BTreeMap| { - Identity::V0(IdentityV0 { - id: Identifier::default(), - public_keys: keys, - balance: 0, - revision: 0, + )); + } + + /// A ChainLock-only link whose funding tx is not chain-locked yet cannot + /// be claimed, but the read-only view still reads its amount and outpoint + /// and reports the missing ChainLock instead of failing. + #[test] + fn should_inspect_a_chainlock_invitation_before_it_is_chain_locked() { + let key = voucher_secret(); + let tx = funding_tx(&key); + let txid = tx.txid(); + let inv = parsed(key, txid.to_string(), None); + + let funding = inspect_funding_tx(&tx, false, &inv).unwrap(); + assert_eq!(funding.credit_output_duffs, 100_000); + assert_eq!(funding.out_point, OutPoint::new(txid, 0)); + assert!(funding.instant_lock.is_none()); + assert!(!funding.is_chain_locked); + assert!( + assemble_asset_lock_proof(tx, false, 100, &inv).is_err(), + "the claim itself still waits for the ChainLock" + ); + } + + /// The InstantSend read-only view carries the decoded islock, and its id + /// matches the claim's InstantSend primary. + #[test] + fn should_inspect_an_instant_invitation_with_the_claims_identity_id() { + let key = voucher_secret(); + let tx = funding_tx(&key); + let txid = tx.txid().to_string(); + let mut islock = InstantLock::default(); + islock.txid = tx.txid(); + let mut islock_bytes = Vec::new(); + islock.consensus_encode(&mut islock_bytes).unwrap(); + let inv = parsed(key, txid, Some(hex::encode(islock_bytes))); + + let funding = inspect_funding_tx(&tx, true, &inv).unwrap(); + assert!(funding.instant_lock.is_some()); + assert_eq!(funding.credit_output_duffs, 100_000); + let primary = assemble_asset_lock_proof(tx, true, 100, &inv) + .unwrap() + .primary; + assert_eq!( + identity_id_for_out_point(funding.out_point), + primary.create_identifier().unwrap() + ); + } + + // --- adopt_already_landed_claim: recognizing our own earlier claim --- + + mod claim_adoption { + use std::cell::Cell; + + use super::super::adopt_already_landed_claim; + use super::{identity_with_keys, our_keys, test_key}; + use crate::PlatformWalletError; + use dpp::consensus::basic::identity::IdentityAssetLockTransactionOutPointAlreadyConsumedError; + use dpp::consensus::basic::BasicError; + use dpp::consensus::ConsensusError; + use dpp::dashcore::hashes::Hash; + use dpp::dashcore::{OutPoint, Txid}; + use dpp::identity::{Identity, IdentityPublicKey, KeyID}; + use std::collections::BTreeMap; + + fn out_point() -> OutPoint { + OutPoint::new(Txid::from_byte_array([7u8; 32]), 1) + } + + /// Platform's consumed-outpoint rejection for `out_point`. + fn consumed(out_point: OutPoint) -> PlatformWalletError { + PlatformWalletError::Sdk(dash_sdk::Error::Protocol( + dpp::ProtocolError::ConsensusError(Box::new(ConsensusError::BasicError( + BasicError::IdentityAssetLockTransactionOutPointAlreadyConsumedError( + IdentityAssetLockTransactionOutPointAlreadyConsumedError::new( + out_point.txid, + out_point.vout as usize, + ), + ), + ))), + )) + } + + fn is_consumed(result: &Result) -> bool { + matches!( + result, + Err(PlatformWalletError::Sdk(dash_sdk::Error::Protocol(_))) + ) + } + + /// Run the seam with a scripted lookup, counting how often it is called. + async fn adopt( + submitted: Result, + lookup: Result, dash_sdk::Error>, + ) -> (Result, u32) { + let calls = Cell::new(0); + let keys = our_keys(); + let result = adopt_already_landed_claim(submitted, &out_point(), &keys, || { + calls.set(calls.get() + 1); + async { lookup } }) - }; + .await; + (result, calls.get()) + } - assert!(identity_carries_keys(&identity(ours.clone()), &ours)); - let theirs: BTreeMap = [(0, key(0, 9)), (1, key(1, 2))].into(); - assert!(!identity_carries_keys(&identity(theirs), &ours)); - let fewer: BTreeMap = [(0, key(0, 1))].into(); - assert!(!identity_carries_keys(&identity(fewer), &ours)); + #[tokio::test] + async fn should_pass_a_successful_claim_through_without_a_lookup() { + let (result, lookups) = adopt(Ok(identity_with_keys(our_keys())), Ok(None)).await; + assert!(result.is_ok()); + assert_eq!(lookups, 0); + } + + #[tokio::test] + async fn should_adopt_our_identity_behind_a_consumed_outpoint() { + let (result, lookups) = adopt( + Err(consumed(out_point())), + Ok(Some(identity_with_keys(our_keys()))), + ) + .await; + assert!(result.is_ok(), "our own landed claim is the claim's result"); + assert_eq!(lookups, 1); + } + + #[tokio::test] + async fn should_report_the_rejection_when_someone_else_claimed_first() { + let theirs: BTreeMap = [(0, test_key(0, 9))].into(); + let (result, _) = adopt( + Err(consumed(out_point())), + Ok(Some(identity_with_keys(theirs))), + ) + .await; + assert!(is_consumed(&result)); + } + + /// A reclaim top-up consumes the outpoint without creating the + /// identity: nothing to adopt. + #[tokio::test] + async fn should_report_the_rejection_when_no_identity_exists() { + let (result, _) = adopt(Err(consumed(out_point())), Ok(None)).await; + assert!(is_consumed(&result)); + } + + /// A failed lookup must not replace the rejection that explains the + /// failure. + #[tokio::test] + async fn should_keep_the_rejection_when_the_lookup_fails() { + let (result, _) = adopt( + Err(consumed(out_point())), + Err(dash_sdk::Error::Generic("timeout".to_string())), + ) + .await; + assert!(is_consumed(&result)); + } + + /// A consumed report for another outpoint is not about this claim. + #[tokio::test] + async fn should_ignore_a_consumed_report_for_another_outpoint() { + let other = OutPoint::new(Txid::from_byte_array([8u8; 32]), 1); + let (result, lookups) = adopt( + Err(consumed(other)), + Ok(Some(identity_with_keys(our_keys()))), + ) + .await; + assert!(is_consumed(&result)); + assert_eq!(lookups, 0); + } + + #[tokio::test] + async fn should_pass_unrelated_errors_through_without_a_lookup() { + let (result, lookups) = adopt( + Err(PlatformWalletError::Sdk(dash_sdk::Error::Generic( + "unrelated".to_string(), + ))), + Ok(Some(identity_with_keys(our_keys()))), + ) + .await; + assert!(matches!( + result, + Err(PlatformWalletError::Sdk(dash_sdk::Error::Generic(_))) + )); + assert_eq!(lookups, 0); + } } /// An islock that locks a DIFFERENT tx than the funding tx is rejected (the diff --git a/packages/rs-sdk/src/platform/transition/put_identity.rs b/packages/rs-sdk/src/platform/transition/put_identity.rs index e41648d0f82..e8dd5b4a905 100644 --- a/packages/rs-sdk/src/platform/transition/put_identity.rs +++ b/packages/rs-sdk/src/platform/transition/put_identity.rs @@ -22,6 +22,7 @@ use dpp::state_transition::proof_result::StateTransitionProofResult; use dpp::state_transition::StateTransition; use drive_proof_verifier::types::AddressInfos; use std::collections::{BTreeMap, BTreeSet}; +use tracing::debug; /// Trait for creating identities on the platform. #[async_trait::async_trait] @@ -45,6 +46,10 @@ pub trait PutIdentity>: Waitable { /// Creates an identity using an asset lock and waits for confirmation. /// + /// A broadcast answered with `AlreadyExists` (this exact transition is + /// already in the mempool or on chain) is not an error: the result wait + /// that follows resolves it. + /// /// In-process private-key counterpart to /// [`Self::put_to_platform_and_wait_for_response_with_signer`]. async fn put_to_platform_and_wait_for_response_with_private_key( @@ -82,7 +87,8 @@ pub trait PutIdentity>: Waitable { AS: dpp::key_wallet::signer::Signer + Send + Sync; /// Creates an identity using an asset-lock signer and waits for - /// confirmation. + /// confirmation. `AlreadyExists` from the broadcast is resolved by the + /// wait, as in the private-key variant. /// /// Signer-driven counterpart to /// [`Self::put_to_platform_and_wait_for_response_with_private_key`]. @@ -151,7 +157,7 @@ impl> PutIdentity for Identity { signer: &IS, settings: Option, ) -> Result { - put_identity_with_asset_lock_and_private_key( + let state_transition = identity_create_with_asset_lock_and_private_key( self, sdk, asset_lock_proof, @@ -159,7 +165,9 @@ impl> PutIdentity for Identity { signer, settings, ) - .await + .await?; + state_transition.broadcast(sdk, settings).await?; + Ok(state_transition) } async fn put_to_platform_and_wait_for_response_with_private_key( @@ -170,15 +178,16 @@ impl> PutIdentity for Identity { signer: &IS, settings: Option, ) -> Result { - let state_transition = self - .put_to_platform_with_private_key( - sdk, - asset_lock_proof, - asset_lock_proof_private_key, - signer, - settings, - ) - .await?; + let state_transition = identity_create_with_asset_lock_and_private_key( + self, + sdk, + asset_lock_proof, + asset_lock_proof_private_key, + signer, + settings, + ) + .await?; + already_known_is_delivered(state_transition.broadcast(sdk, settings).await)?; Self::wait_for_response(sdk, state_transition, settings).await } @@ -196,7 +205,7 @@ impl> PutIdentity for Identity { where AS: dpp::key_wallet::signer::Signer + Send + Sync, { - put_identity_with_asset_lock_and_signer( + let state_transition = identity_create_with_asset_lock_and_signer( self, sdk, asset_lock_proof, @@ -205,7 +214,9 @@ impl> PutIdentity for Identity { identity_signer, settings, ) - .await + .await?; + state_transition.broadcast(sdk, settings).await?; + Ok(state_transition) } #[cfg(feature = "core_key_wallet")] @@ -221,16 +232,17 @@ impl> PutIdentity for Identity { where AS: dpp::key_wallet::signer::Signer + Send + Sync, { - let state_transition = self - .put_to_platform_with_signer( - sdk, - asset_lock_proof, - asset_lock_proof_path, - asset_lock_signer, - identity_signer, - settings, - ) - .await?; + let state_transition = identity_create_with_asset_lock_and_signer( + self, + sdk, + asset_lock_proof, + asset_lock_proof_path, + asset_lock_signer, + identity_signer, + settings, + ) + .await?; + already_known_is_delivered(state_transition.broadcast(sdk, settings).await)?; Self::wait_for_response(sdk, state_transition, settings).await } @@ -282,7 +294,23 @@ impl> PutIdentity for Identity { } } -async fn put_identity_with_asset_lock_and_private_key>( +/// A broadcast whose result is waited for next: `AlreadyExists` counts as +/// delivered. DAPI returns it only when this exact transition is already in +/// the mempool or on chain (a broadcast that timed out after the node took it, +/// retried on another node), so the wait resolves it; failing here would +/// report an identity create that lands as a failure. +fn already_known_is_delivered(broadcast: Result<(), Error>) -> Result<(), Error> { + match broadcast { + Err(Error::AlreadyExists(message)) => { + debug!(%message, "identity create is already known to Platform; waiting for its result"); + Ok(()) + } + other => other, + } +} + +/// Build and structurally validate the identity create, without broadcasting. +async fn identity_create_with_asset_lock_and_private_key>( identity: &Identity, sdk: &Sdk, asset_lock_proof: AssetLockProof, @@ -307,13 +335,14 @@ async fn put_identity_with_asset_lock_and_private_key( +async fn identity_create_with_asset_lock_and_signer( identity: &Identity, sdk: &Sdk, asset_lock_proof: AssetLockProof, @@ -329,7 +358,7 @@ where // `broadcast_request_for_new_identity_with_signer` reads // `PutSettings::user_fee_increase` internally; thread `settings` // through to honour the CL-height retry's hash-bumping mechanism - // (see the matching block in `put_identity_with_asset_lock_and_private_key`). + // (see the matching block in `identity_create_with_asset_lock_and_private_key`). let (state_transition, _) = identity .broadcast_request_for_new_identity_with_signer( asset_lock_proof, @@ -341,7 +370,6 @@ where ) .await?; ensure_valid_state_transition_structure(&state_transition, sdk.version())?; - state_transition.broadcast(sdk, settings).await?; Ok(state_transition) } @@ -417,3 +445,23 @@ async fn put_identity_with_address_funding< ))), } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn should_treat_an_already_known_broadcast_as_delivered() { + let broadcast = Err(Error::AlreadyExists( + "state transition already in mempool".to_string(), + )); + assert!(already_known_is_delivered(broadcast).is_ok()); + } + + #[test] + fn should_keep_every_other_broadcast_outcome() { + assert!(already_known_is_delivered(Ok(())).is_ok()); + let rejected = already_known_is_delivered(Err(Error::Generic("rejected".to_string()))); + assert!(matches!(rejected, Err(Error::Generic(_)))); + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift index d3717e28ce3..af4ad3fa75a 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift @@ -2185,7 +2185,7 @@ extension ManagedPlatformWallet { /// contact-bootstrap precondition (may be nil even when `hasInviter`). public let inviterUsername: String? /// Always 0: the amount isn't in the link (it carries the funding txid, - /// not the proof) and is only known after the tx is fetched at claim time. + /// not the proof). Read it with ``invitationClaimStatus(uri:)``. public let amountDuffs: UInt64 /// Always 0: the legacy link carries no expiry field. public let expiryUnix: UInt32 @@ -2207,7 +2207,9 @@ extension ManagedPlatformWallet { public let amountDuffs: UInt64 /// The claim would submit an InstantSend proof. public let isInstant: Bool - /// The funding transaction is chain-locked. + /// The funding transaction is chain-locked. `false` together with + /// `isInstant == false` is a ChainLock-only invitation that cannot be + /// claimed until its funding transaction is chain-locked. public let isChainLocked: Bool /// An identity already exists at `prospectiveIdentityId` — the /// invitation was claimed. `false` does NOT prove the voucher is @@ -2403,26 +2405,31 @@ extension ManagedPlatformWallet { /// transaction is refetched to locate the credit output the voucher /// controls. It claims nothing and mutates no wallet state. /// - /// Throws on anything undetermined — wrong network, a funding tx that has - /// not propagated, transport failure. Callers must treat a throw as - /// "proceed", never as an answer either way. + /// Two throws are definitive: a malformed link (`invalidParameter`) and a + /// link for the other network (`invalidNetwork`) can never be claimed by + /// this wallet. Every other throw is undetermined (a funding tx that has + /// not propagated, transport failure) and must be treated as "proceed", + /// never as an answer either way. public func invitationProspectiveIdentityId(uri: String) async throws -> Data { - let handle = self.handle - return try await Task.detached(priority: .userInitiated) { () -> Data in - var idTuple: ( - UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, - UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, - UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, - UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8 - ) = ( - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 - ) - let result = uri.withCString { uriPtr in - platform_wallet_invitation_prospective_identity_id(handle, uriPtr, &idTuple) + // `self` stays alive for the whole call: a deinit mid-call would + // destroy the handle the FFI is still using. + return try await Task.detached(priority: .userInitiated) { [self] () -> Data in + try withExtendedLifetime(self) { + var idTuple: ( + UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, + UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, + UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, + UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8 + ) = ( + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + ) + let result = uri.withCString { uriPtr in + platform_wallet_invitation_prospective_identity_id(handle, uriPtr, &idTuple) + } + try result.check() + return withUnsafeBytes(of: idTuple) { Data($0) } } - try result.check() - return withUnsafeBytes(of: idTuple) { Data($0) } }.value } @@ -2435,20 +2442,23 @@ extension ManagedPlatformWallet { /// undetermined (not propagated yet, transport failure) and must not be /// read as an answer either way. public func invitationClaimStatus(uri: String) async throws -> InvitationClaimStatus { - let handle = self.handle - return try await Task.detached(priority: .userInitiated) { () -> InvitationClaimStatus in - var out = InvitationClaimStatusFFI() - let result = uri.withCString { uriPtr in - platform_wallet_invitation_claim_status(handle, uriPtr, &out) + // `self` stays alive for the whole call (up to ~12 s of funding-tx + // retries): a deinit mid-call would destroy the handle in use. + return try await Task.detached(priority: .userInitiated) { [self] () -> InvitationClaimStatus in + try withExtendedLifetime(self) { + var out = InvitationClaimStatusFFI() + let result = uri.withCString { uriPtr in + platform_wallet_invitation_claim_status(handle, uriPtr, &out) + } + try result.check() + return InvitationClaimStatus( + prospectiveIdentityId: withUnsafeBytes(of: out.prospective_identity_id) { Data($0) }, + amountDuffs: out.amount_duffs, + isInstant: out.is_instant, + isChainLocked: out.is_chain_locked, + alreadyClaimed: out.already_claimed + ) } - try result.check() - return InvitationClaimStatus( - prospectiveIdentityId: withUnsafeBytes(of: out.prospective_identity_id) { Data($0) }, - amountDuffs: out.amount_duffs, - isInstant: out.is_instant, - isChainLocked: out.is_chain_locked, - alreadyClaimed: out.already_claimed - ) }.value }