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
11 changes: 9 additions & 2 deletions packages/rs-platform-wallet-ffi/src/asset_lock/built_callback.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,15 @@ use crate::asset_lock_persistence::outpoint_to_bytes;
/// result then tells what happened to the lock:
/// `ErrorTransactionBroadcastRejected` (26) means it was removed again; any
/// other failure leaves it tracked and resumable by this outpoint (a resume
/// may find it already consumed). Both hold for this session; the row store
/// and removal behind them are best-effort, so after a restart a failed
/// may find it already consumed), with one exception. A shielded funding
/// whose recipient cannot be made durable is abandoned before it is tracked
/// or sent, so a resume in this session finds no lock
/// (`ErrorAssetLockNotTracked`, 23). With its row removed again the call
/// fails with a persistence error. Where that removal is not known to be on
/// disk it fails with `ErrorTransactionBroadcastUnconfirmed` (20): the
/// inputs stay reserved, and a restart may still find the row and resume
/// the lock. All of this holds for this session; the row store
/// and removal behind it are best-effort, so after a restart a failed
/// store can leave no row for a broadcast lock, or the row of a removed one.
/// That holds for the exports that take this callback today: shielded
/// funding and platform-address funding from the wallet balance or an
Expand Down
6 changes: 4 additions & 2 deletions packages/rs-platform-wallet/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,8 +194,10 @@ pub enum PlatformWalletError {
/// For Core transactions, the
/// transaction may already have reached the network (transport timeout
/// after delivery, partial peer send, or an internal multi-node retry
/// whose earlier attempt may have succeeded). The spent Core inputs are
/// intentionally kept out of the selectable set, so an immediate retry
/// whose earlier attempt may have succeeded). One case was not sent but
/// may still be: a shielded funding abandoned before its broadcast whose
/// row may be on disk, where a restart resumes it. The spent Core inputs
/// are intentionally kept out of the selectable set, so an immediate retry
/// fails at input selection instead of double-spending.
///
/// A Platform state transition may instead have been accepted but its
Expand Down
783 changes: 741 additions & 42 deletions packages/rs-platform-wallet/src/wallet/asset_lock/build.rs

Large diffs are not rendered by default.

327 changes: 302 additions & 25 deletions packages/rs-platform-wallet/src/wallet/identity/network/invitation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ use key_wallet::wallet::managed_wallet_info::asset_lock_builder::AssetLockFundin

use crate::changeset::{
InvitationChangeSet, InvitationEntry, InvitationStatus, PersistenceCapabilities,
PlatformWalletChangeSet,
};

use dash_sdk::platform::transition::put_settings::PutSettings;
Expand All @@ -35,6 +36,7 @@ pub use dash_sdk::platform::dashpay::{
use crate::error::PlatformWalletError;
use crate::wallet::identity::crypto::{encode_invitation_uri, InviterInfo, ParsedInvitation};
use crate::wallet::identity::network::contact_requests::ContactCryptoProvider;
use crate::wallet::persister::NotDurable;

use super::*;

Expand Down Expand Up @@ -83,6 +85,52 @@ fn funding_index_from_path(path: &DerivationPath) -> Option<u32> {
}

impl IdentityWallet {
/// Record the inviter-side row of a voucher that is already funded, and
/// answer `Ok` only once it is on disk.
///
/// A flush that succeeded is not trusted by itself
/// (`WalletPersister::store_durably`): another flush of the wallet's
/// records may have taken the record and failed for good, dropping it,
/// and the link handed out afterwards would then be for a voucher no
/// restart could list or reclaim. The voucher is funded by now, so a
/// record another flush dropped, or still holds or put back, is stored
/// once more rather than given up: the row is keyed by outpoint, so
/// storing it again changes nothing where the first one did land, and
/// the flush that follows writes what was put back. Only when that
/// fails too is the failure reported, as a store or flush that failed
/// is.
///
/// A store or flush of this call's own that the backend failed is not
/// tried again, as it never was here. There the outcome is known: a
/// flush that failed transiently kept the record buffered for a later
/// one to write, and any other failure is the backend refusing or
/// dropping what it was given, which its contract says not to retry
/// (`PlatformWalletPersistence::flush`). The two answers stored again
/// are the ones that leave it unknown whether a record this call stored
/// and flushed without an error is on disk, and the second store is
/// what settles that.
fn record_funded_invitation(&self, entry: InvitationEntry) -> Result<(), PlatformWalletError> {
let mut inv_cs = InvitationChangeSet::default();
inv_cs.invitations.insert(entry.out_point, entry);
let record = || PlatformWalletChangeSet {
invitations: Some(inv_cs.clone()),
..Default::default()
};
let recorded = match self.persister.store_durably(record()) {
Err(NotDurable::Lost | NotDurable::OtherFlushUnsettled) => {
self.persister.store_durably(record())
}
recorded => recorded,
Comment thread
QuantumExplorer marked this conversation as resolved.
Resolved
};
recorded.map_err(|e| {
PlatformWalletError::AssetLockTransaction(format!(
"the invitation voucher is funded but its record could not be \
persisted (it would be missing from Sent invitations and \
unreclaimable): {e}"
))
})
}

/// Create a DashPay invitation: fund a one-time asset-lock voucher at the
/// DIP-13 invitation path and return a shareable `dashpay://invite` link.
///
Expand Down Expand Up @@ -198,32 +246,15 @@ impl IdentityWallet {
// for the invitation account), warn-skip: an untrackable row can't be
// reclaimed either way.
if let Some(funding_index) = funding_index_from_path(&path) {
let mut inv_cs = InvitationChangeSet::default();
inv_cs.invitations.insert(
self.record_funded_invitation(InvitationEntry {
out_point,
InvitationEntry {
out_point,
funding_index,
amount_duffs,
expiry_unix,
created_at_secs,
has_inviter: inviter.is_some(),
status: InvitationStatus::Created,
},
);
self.persister
.store(crate::changeset::PlatformWalletChangeSet {
invitations: Some(inv_cs),
..Default::default()
})
.and_then(|_| self.persister.flush())
.map_err(|e| {
PlatformWalletError::AssetLockTransaction(format!(
"the invitation voucher is funded but its record could not be \
persisted (it would be missing from Sent invitations and \
unreclaimable): {e}"
))
})?;
funding_index,
amount_duffs,
expiry_unix,
created_at_secs,
has_inviter: inviter.is_some(),
status: InvitationStatus::Created,
})?;
} else {
tracing::warn!(
"invitation funding path has no u32 index tail; \
Expand Down Expand Up @@ -560,4 +591,250 @@ mod tests {
);
}
}

// --- create_invitation: the funded voucher's record ---

mod funded_record {
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};

use dashcore::{OutPoint, Txid};
use key_wallet::mnemonic::Mnemonic;
use key_wallet::wallet::initialization::WalletAccountCreationOptions;
use key_wallet::Network;

use crate::changeset::{
ClientStartState, InvitationEntry, InvitationStatus, PersistenceError,
PersistenceErrorKind, PlatformWalletChangeSet, PlatformWalletPersistence,
};
use crate::events::{EventHandler, PlatformEventHandler};
use crate::wallet::persister::WalletPersister;
use crate::wallet::platform_wallet::WalletId;
use crate::{PlatformWallet, PlatformWalletError};

const TEST_MNEMONIC: &str = "abandon abandon abandon abandon abandon abandon \
abandon abandon abandon abandon abandon about";

struct NoopEventHandler;
impl EventHandler for NoopEventHandler {}
impl PlatformEventHandler for NoopEventHandler {}

/// A backend that buffers what is stored until a flush writes it to
/// `durable`; a flush that fails for good drops the buffer, and one
/// that fails transiently keeps it.
#[derive(Default)]
struct BufferingPersistence {
buffered: Mutex<Vec<PlatformWalletChangeSet>>,
durable: Mutex<Vec<PlatformWalletChangeSet>>,
/// One handle per flush still to be overtaken: a flush through
/// the handle, as one from another thread would, takes what was
/// buffered before such a flush writes, and fails; the overtaken
/// flush then succeeds over nothing.
overtaken_by: Mutex<Vec<WalletPersister>>,
/// Whether the overtaking flush fails transiently, putting back
/// what it took once the overtaken one is done, or for good,
/// dropping it.
overtaking_puts_back: AtomicBool,
/// While set, a flush is the overtaking one, and fails.
overtaking: AtomicBool,
}

impl BufferingPersistence {
/// The outpoints of the invitation records on disk, in order.
fn durable_invitations(&self) -> Vec<OutPoint> {
self.durable
.lock()
.expect("durable")
.iter()
.filter_map(|changeset| changeset.invitations.as_ref())
.flat_map(|invitations| invitations.invitations.keys().copied())
.collect()
}
}

impl PlatformWalletPersistence for BufferingPersistence {
fn store(
&self,
_wallet_id: WalletId,
changeset: PlatformWalletChangeSet,
) -> Result<(), PersistenceError> {
self.buffered.lock().expect("buffered").push(changeset);
Ok(())
}

fn flush(&self, _wallet_id: WalletId) -> Result<(), PersistenceError> {
let puts_back = self.overtaking_puts_back.load(Ordering::SeqCst);
if self.overtaking.load(Ordering::SeqCst) {
return Err(if puts_back {
PersistenceError::backend_with_kind(
PersistenceErrorKind::Transient,
"the disk is busy",
)
} else {
PersistenceError::backend("the database is corrupt")
});
}
// Taken in its own statement: the flush below comes back here.
let overtaking = self.overtaken_by.lock().expect("overtaken").pop();
if let Some(persister) = overtaking {
// The other flush holds what was buffered while this one
// runs, over nothing.
let taken = std::mem::take(&mut *self.buffered.lock().expect("buffered"));
self.overtaking.store(true, Ordering::SeqCst);
let overtook = persister.flush();
self.overtaking.store(false, Ordering::SeqCst);
assert!(overtook.is_err_and(|error| error.is_transient() == puts_back));
if puts_back {
self.buffered.lock().expect("buffered").extend(taken);
}
return Ok(());
}
let flushed = std::mem::take(&mut *self.buffered.lock().expect("buffered"));
self.durable.lock().expect("durable").extend(flushed);
Ok(())
}

fn load(&self) -> Result<ClientStartState, PersistenceError> {
Ok(ClientStartState::default())
}
}

async fn wallet_on(persistence: Arc<BufferingPersistence>) -> Arc<PlatformWallet> {
let sdk = Arc::new(dash_sdk::SdkBuilder::new_mock().build().expect("mock sdk"));
let handler: Arc<dyn PlatformEventHandler> = Arc::new(NoopEventHandler);
let manager = Arc::new(crate::PlatformWalletManager::new(sdk, persistence, handler));
let seed = Mnemonic::from_phrase(TEST_MNEMONIC)
.expect("valid mnemonic")
.to_seed("");
manager
.create_wallet_from_seed_bytes(
Network::Testnet,
&seed,
WalletAccountCreationOptions::None,
Some(0),
)
.await
.expect("wallet creation")
}

fn funded_voucher() -> InvitationEntry {
InvitationEntry {
out_point: OutPoint::new(Txid::from_byte_array([7; 32]), 0),
funding_index: 0,
amount_duffs: 1_000_000,
expiry_unix: 1,
created_at_secs: 1,
has_inviter: false,
status: InvitationStatus::Created,
}
}

/// A funded voucher's record is not taken as recorded on the strength
/// of a flush that succeeded over nothing, another flush of the
/// wallet's records having taken it first and failed for good: it is
/// stored once more, and is on disk when the call answers.
#[tokio::test]
async fn should_record_a_funded_invitation_again_when_another_flush_dropped_its_record() {
let persistence = Arc::new(BufferingPersistence::default());
let wallet = wallet_on(Arc::clone(&persistence)).await;
let iw = wallet.identity();
let voucher = funded_voucher();
persistence
.overtaken_by
.lock()
.expect("overtaken")
.push(iw.persister.clone());

iw.record_funded_invitation(voucher.clone())
.expect("stored once more, and durable");

assert!(
persistence
.overtaken_by
.lock()
.expect("overtaken")
.is_empty(),
"a flush was overtaken"
);
assert_eq!(
persistence.durable_invitations(),
vec![voucher.out_point],
"the record is on disk"
);
}

/// A funded voucher's record is not taken as recorded while another
/// flush of the wallet's records holds it, a flush that then fails
/// transiently and puts it back: the record is stored once more, and
/// the flush that follows writes it.
#[tokio::test]
async fn should_record_a_funded_invitation_another_flush_took_and_put_back() {
let persistence = Arc::new(BufferingPersistence::default());
let wallet = wallet_on(Arc::clone(&persistence)).await;
let iw = wallet.identity();
let voucher = funded_voucher();
persistence
.overtaking_puts_back
.store(true, Ordering::SeqCst);
persistence
.overtaken_by
.lock()
.expect("overtaken")
.push(iw.persister.clone());

iw.record_funded_invitation(voucher.clone())
.expect("stored once more, and durable");

assert!(
persistence
.overtaken_by
.lock()
.expect("overtaken")
.is_empty(),
"a flush was overtaken"
);
let on_disk = persistence.durable_invitations();
assert!(
!on_disk.is_empty()
&& on_disk
.iter()
.all(|out_point| *out_point == voucher.out_point),
"the record is on disk: {on_disk:?}"
);
}

/// When the record stored once more is dropped by another flush as
/// well, the voucher is reported funded and unrecorded, as a flush
/// that failed reports it, and no link follows: it is not reported
/// recorded while on no disk.
#[tokio::test]
async fn should_report_a_funded_invitation_unrecorded_when_another_flush_dropped_it_twice()
{
let persistence = Arc::new(BufferingPersistence::default());
let wallet = wallet_on(Arc::clone(&persistence)).await;
let iw = wallet.identity();
persistence
.overtaken_by
.lock()
.expect("overtaken")
.extend([iw.persister.clone(), iw.persister.clone()]);

let unrecorded = iw.record_funded_invitation(funded_voucher());

assert!(
matches!(&unrecorded, Err(PlatformWalletError::AssetLockTransaction(message))
if message.contains("funded but its record could not be persisted")),
"{unrecorded:?}"
);
assert!(
persistence
.overtaken_by
.lock()
.expect("overtaken")
.is_empty(),
"both flushes were overtaken"
);
assert!(persistence.durable_invitations().is_empty(), "on no disk");
}
}
}
Loading
Loading