From 30a1374dc1fed720fd9e2bbb6a5ef1bf267c7e17 Mon Sep 17 00:00:00 2001 From: Camillarhi Date: Tue, 6 Jan 2026 00:28:21 +0100 Subject: [PATCH] Add payjoin v2 receiver flow Implements the receiver side of BIP 77 (Payjoin v2), letting LDK Node users receive payjoin payments through a payjoin directory and OHTTP relays. - `PayjoinPayment::receive()` opens a receive session and returns a BIP 21 URI for the sender. The receiver state machine covers every `ReceiveSession` state: polling the directory, checking the sender's original, contributing an input, finalizing and posting the proposal, and waiting for the sender to broadcast. - Sessions are persisted as an event log by `KVStorePayjoinReceiverPersister` and resumed every 15 seconds, including after a restart. Sender inputs are recorded across sessions so a sender can't reuse them to probe our UTXOs. They're forgotten once a spend of them is buried, or after 30 days. - A session settles on what wallet sync sees spending the sender's inputs, classified with payjoin's `classify_tx` as the payjoin, the fallback or neither. The payjoin is tagged `TransactionType::Payjoin` on its payment once the session sees it, and the session closes once the spend is `ANTI_REORG_DELAY` deep. A fallback or other spend that replaces a tagged payjoin has the tag removed. - If a session fails, expires or is cancelled after getting the sender's original, its fallback is broadcast and the session is kept as `FallbackPending`. The fallback is rebroadcast on each new chain tip until a spend of the sender's inputs is buried, for at most a week. The payjoin's txid is recorded before the proposal is posted, so a payjoin that confirms after its session expired still completes it. - `list_payjoin_sessions()`, `payjoin_session(id)` and `cancel_payjoin_session(id)` let users follow and cancel sessions. Cancelling is refused once a spend of the sender's inputs has been seen. - `Builder::set_payjoin_config` validates the directory and relay URLs. The receive address is only revealed once the OHTTP keys are fetched. Completed and failed sessions are cleaned up after 24 hours. Parts of this were written with the help of Claude Code (Claude Opus 5.5). Co-authored-by: xstoicunicornx --- Cargo.toml | 2 + bindings/ldk_node.udl | 9 + src/builder.rs | 142 +- src/chain/bitcoind.rs | 80 +- src/chain/mod.rs | 27 +- src/config.rs | 84 +- src/error.rs | 20 + src/io/mod.rs | 8 + src/lib.rs | 106 +- src/payment/mod.rs | 5 + src/payment/payjoin/manager.rs | 2134 ++++++++++++++++++++++++ src/payment/payjoin/mod.rs | 196 +++ src/payment/payjoin/payjoin_session.rs | 478 ++++++ src/payment/payjoin/persist.rs | 128 ++ src/payment/payjoin/seen_inputs.rs | 238 +++ src/payment/store.rs | 6 +- src/types.rs | 5 + src/wallet/mod.rs | 440 ++++- 18 files changed, 4088 insertions(+), 20 deletions(-) create mode 100644 src/payment/payjoin/manager.rs create mode 100644 src/payment/payjoin/mod.rs create mode 100644 src/payment/payjoin/payjoin_session.rs create mode 100644 src/payment/payjoin/persist.rs create mode 100644 src/payment/payjoin/seen_inputs.rs diff --git a/Cargo.toml b/Cargo.toml index 24f5a9ce0e..adaa5fc8fa 100755 --- a/Cargo.toml +++ b/Cargo.toml @@ -134,6 +134,8 @@ prost = { version = "0.11.6", default-features = false, optional = true} #bitcoin-payment-instructions = { version = "0.6" } bitcoin-payment-instructions = { git = "https://github.com/benthecarman/bitcoin-payment-instructions", rev = "3dbe11bdf8916639df42476501fb40f87b253e84", optional = true } +payjoin = { version = "1.3.0", default-features = false, features = ["v2", "io"] } + [target.'cfg(windows)'.dependencies] winapi = { version = "0.3", features = ["winbase"] } diff --git a/bindings/ldk_node.udl b/bindings/ldk_node.udl index 2344451b64..5dc1f7beb5 100644 --- a/bindings/ldk_node.udl +++ b/bindings/ldk_node.udl @@ -71,6 +71,7 @@ interface Node { Bolt12Payment bolt12_payment(); SpontaneousPayment spontaneous_payment(); OnchainPayment onchain_payment(); + PayjoinPayment payjoin_payment(); Liquidity liquidity(); ForwardingAnalytics forwarding_analytics(); Prober? prober(); @@ -145,6 +146,8 @@ interface FeeRate { u64 to_sat_per_vb_ceil(); }; +typedef interface PayjoinPayment; + typedef interface Liquidity; typedef interface ForwardingAnalytics; @@ -177,6 +180,8 @@ enum NodeError { "OnchainTxSigningFailed", "TxSyncFailed", "TxSyncTimeout", + "TxLookupFailed", + "TxLookupTimeout", "GossipUpdateFailed", "GossipUpdateTimeout", "LiquidityRequestFailed", @@ -220,6 +225,10 @@ enum NodeError { "InvalidLnurl", "ChainSourceNotSupported", "InvalidPayerProof", + "PayjoinNotConfigured", + "PayjoinSessionCreationFailed", + "PayjoinSessionFailed", + "PayjoinSessionNotCancellable", }; typedef dictionary NodeStatus; diff --git a/src/builder.rs b/src/builder.rs index a280609848..1c6dcdc3b5 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -59,7 +59,7 @@ use crate::chain::ChainSource; use crate::config::BitcoindRestClientConfig; use crate::config::{ default_user_config, may_announce_channel, AnnounceError, AsyncPaymentsRole, Config, - ElectrumSyncConfig, EsploraSyncConfig, HRNResolverConfig, TorConfig, + ElectrumSyncConfig, EsploraSyncConfig, HRNResolverConfig, PayjoinConfig, TorConfig, CHANNEL_TX_FACTS_CACHE_CAPACITY, CHANNEL_TX_FACTS_CACHE_WARMUP_COUNT, DEFAULT_ESPLORA_SERVER_URL, DEFAULT_LOG_FILENAME, DEFAULT_LOG_LEVEL, PAYMENT_CACHE_CAPACITY, PAYMENT_CACHE_WARMUP_COUNT, @@ -89,8 +89,10 @@ use crate::io::{ CHANNEL_TX_FACTS_PERSISTENCE_SECONDARY_NAMESPACE, FORWARDED_PAYMENT_PERSISTENCE_PRIMARY_NAMESPACE, ONCHAIN_PAYMENT_TRACKER_PERSISTENCE_PRIMARY_NAMESPACE, - ONCHAIN_PAYMENT_TRACKER_PERSISTENCE_SECONDARY_NAMESPACE, - PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE, PAYMENT_INFO_PERSISTENCE_SECONDARY_NAMESPACE, + ONCHAIN_PAYMENT_TRACKER_PERSISTENCE_SECONDARY_NAMESPACE, PAYJOIN_SEEN_INPUTS_PRIMARY_NAMESPACE, + PAYJOIN_SEEN_INPUTS_SECONDARY_NAMESPACE, PAYJOIN_SESSION_STORE_PRIMARY_NAMESPACE, + PAYJOIN_SESSION_STORE_SECONDARY_NAMESPACE, PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE, + PAYMENT_INFO_PERSISTENCE_SECONDARY_NAMESPACE, }; use crate::liquidity::client::lsps2::router::LSPS2Router; use crate::liquidity::{LSPS2ServiceConfig, LiquiditySourceBuilder, LspConfig}; @@ -99,6 +101,7 @@ use crate::logger::{log_error, LdkLogger, LogLevel, LogWriter, Logger}; use crate::message_handler::NodeCustomMessageHandler; use crate::payment::asynchronous::om_mailbox::OnionMessageMailbox; use crate::payment::forwarding_store::ForwardingStore; +use crate::payment::payjoin::manager::PayjoinManager; #[cfg(feature = "unified-payments")] use crate::payment::HRNResolver; use crate::payment::NodeOffersMessageHandler; @@ -112,7 +115,7 @@ use crate::tx_broadcaster::TransactionBroadcaster; use crate::types::{ AsyncPersister, ChainMonitor, ChannelManager, ChannelTxFactsStore, DynStore, DynStoreRef, DynStoreWrapper, GossipSync, Graph, KeysManager, MessageRouter, OnchainPaymentTracker, - OnionMessenger, PaymentStore, PeerManager, + OnionMessenger, PayjoinSeenInputsStore, PayjoinSessionStore, PaymentStore, PeerManager, }; use crate::wallet::persist::{read_address_pool, KVStoreWalletPersister}; use crate::wallet::provenance::NodeChannelLiveness; @@ -203,6 +206,9 @@ pub enum BuildError { InvalidTorProxyAddress, /// The provided alias is invalid. InvalidNodeAlias, + /// The given payjoin configuration is invalid, e.g. no OHTTP relay or a URL that isn't + /// `http` or `https` was passed. + InvalidPayjoinConfig, /// An attempt to setup a runtime has failed. RuntimeSetupFailed, /// We failed to read data from the [`KVStore`], or data read from it could not be decoded. @@ -242,6 +248,8 @@ pub enum BuildError { ChainTipFetchFailed, /// The configured wallet rescan height is above the current chain tip. WalletRescanHeightTooHigh, + /// The payjoin configuration requires a Bitcoin Core backend, but a different chain source was configured. + PayjoinConfigMismatch, } impl fmt::Display for BuildError { @@ -289,6 +297,10 @@ impl fmt::Display for BuildError { Self::WalletRescanHeightTooHigh => { write!(f, "Wallet rescan height is above the current chain tip.") }, + Self::InvalidPayjoinConfig => write!(f, "Given payjoin configuration is invalid."), + Self::PayjoinConfigMismatch => { + write!(f, "Payjoin requires a Bitcoin Core chain source, but a different one was configured.") + }, } } } @@ -698,6 +710,24 @@ impl NodeBuilder { Ok(self) } + /// Configures the [`Node`] instance to enable Payjoin payments. + /// + /// The `payjoin_config` specifies the Payjoin directory and OHTTP relay URLs required + /// by the Payjoin v2 protocol. + /// + /// Returns [`BuildError::InvalidPayjoinConfig`] unless the directory and at least one relay + /// are given, all as `http` or `https` URLs. + pub fn set_payjoin_config( + &mut self, payjoin_config: PayjoinConfig, + ) -> Result<&mut Self, BuildError> { + if !payjoin_config.is_valid() { + return Err(BuildError::InvalidPayjoinConfig); + } + + self.config.payjoin_config = Some(payjoin_config); + Ok(self) + } + /// Sets background probing config. /// /// Use [`ProbingConfigBuilder`] to build the configuration: @@ -1328,6 +1358,17 @@ impl Builder { self.inner.write().expect("lock").set_async_payments_role(role).map(|_| ()) } + /// Configures the [`Node`] instance to enable Payjoin payments. + /// + /// The `payjoin_config` specifies the Payjoin directory and OHTTP relay URLs required + /// by the Payjoin v2 protocol. + /// + /// Returns [`BuildError::InvalidPayjoinConfig`] unless the directory and at least one relay + /// are given, all as `http` or `https` URLs. + pub fn set_payjoin_config(&self, payjoin_config: PayjoinConfig) -> Result<(), BuildError> { + self.inner.write().expect("lock").set_payjoin_config(payjoin_config).map(|_| ()) + } + /// Configures background probing. /// /// Use [`ProbingConfigBuilder`] to build the configuration. @@ -1590,6 +1631,13 @@ fn build_with_store_internal( } } + if let Some(payjoin_config) = &config.payjoin_config { + if !payjoin_config.is_valid() { + log_error!(logger, "Given payjoin configuration is invalid."); + return Err(BuildError::InvalidPayjoinConfig); + } + } + let tx_broadcaster = Arc::new(TransactionBroadcaster::new(Arc::clone(&logger))); let fee_estimator = Arc::new(OnchainFeeEstimator::new()); @@ -1602,6 +1650,8 @@ fn build_with_store_internal( payment_tracker_res, channel_tx_facts_store_res, address_pool_res, + payjoin_session_store_res, + payjoin_seen_inputs_res, ) = runtime.block_on(async move { tokio::join!( read_n_objects( @@ -1632,6 +1682,18 @@ fn build_with_store_internal( Arc::clone(&logger_ref), ), read_address_pool(&*kv_store_ref, &*logger_ref), + read_all_objects( + &*kv_store_ref, + PAYJOIN_SESSION_STORE_PRIMARY_NAMESPACE, + PAYJOIN_SESSION_STORE_SECONDARY_NAMESPACE, + Arc::clone(&logger_ref), + ), + read_all_objects( + &*kv_store_ref, + PAYJOIN_SEEN_INPUTS_PRIMARY_NAMESPACE, + PAYJOIN_SEEN_INPUTS_SECONDARY_NAMESPACE, + Arc::clone(&logger_ref), + ), ) }); @@ -2573,6 +2635,57 @@ fn build_with_store_internal( let pathfinding_scores_sync_url = pathfinding_scores_sync_config.map(|c| c.url.clone()); + let payjoin_manager = if config.payjoin_config.is_some() { + if !chain_source.supports_payjoin() { + return Err(BuildError::PayjoinConfigMismatch); + } + + let payjoin_session_store = match payjoin_session_store_res { + Ok(payjoin_sessions) => Arc::new(PayjoinSessionStore::new( + payjoin_sessions, + KeepAllEntries, + PAYJOIN_SESSION_STORE_PRIMARY_NAMESPACE.to_string(), + PAYJOIN_SESSION_STORE_SECONDARY_NAMESPACE.to_string(), + Arc::clone(&kv_store), + Arc::clone(&logger), + )), + Err(e) => { + log_error!(logger, "Failed to read payjoin session data from store: {}", e); + return Err(BuildError::ReadFailed); + }, + }; + + // Pruning keeps this to the inputs of the last `PAYJOIN_SEEN_INPUT_RETENTION_SECS` whose + // spend isn't buried yet, so it's all kept in memory. + let payjoin_seen_inputs_store = match payjoin_seen_inputs_res { + Ok(seen_inputs) => Arc::new(PayjoinSeenInputsStore::new( + seen_inputs, + KeepAllEntries, + PAYJOIN_SEEN_INPUTS_PRIMARY_NAMESPACE.to_string(), + PAYJOIN_SEEN_INPUTS_SECONDARY_NAMESPACE.to_string(), + Arc::clone(&kv_store), + Arc::clone(&logger), + )), + Err(e) => { + log_error!(logger, "Failed to read payjoin seen inputs from store: {}", e); + return Err(BuildError::ReadFailed); + }, + }; + + Some(Arc::new(PayjoinManager::new( + Arc::clone(&payjoin_session_store), + payjoin_seen_inputs_store, + Arc::clone(&logger), + Arc::clone(&config), + Arc::clone(&wallet), + Arc::clone(&fee_estimator), + Arc::clone(&chain_source), + Arc::clone(&tx_broadcaster), + ))) + } else { + None + }; + let prober = probing_config.map(|probing_cfg| { let strategy: Arc = match &probing_cfg.kind { ProbingStrategyKind::HighDegree { top_node_count } => { @@ -2685,6 +2798,7 @@ fn build_with_store_internal( prober, #[cfg(cycle_tests)] _leak_checker, + payjoin_manager, }) } @@ -2855,6 +2969,26 @@ mod tests { assert!(matches!(result, Err(BuildError::ReadFailed))); } + #[test] + fn invalid_payjoin_config_from_config_fails_build() { + let mut config = crate::config::Config::default(); + config.payjoin_config = Some(crate::config::PayjoinConfig { + payjoin_directory: "https://payjo.in".to_string(), + ohttp_relays: vec![], + }); + let builder = NodeBuilder::from_config(config); + let logger = Arc::new(Logger::new_log_facade()); + #[cfg(not(feature = "uniffi"))] + let node_entropy = NodeEntropy::from_seed_bytes([42; 64]); + #[cfg(feature = "uniffi")] + let node_entropy = NodeEntropy::from_seed_bytes(vec![42; 64]).unwrap(); + + let result = + builder.build_with_store_and_logger(node_entropy, InMemoryStore::new(), logger); + + assert!(matches!(result, Err(BuildError::InvalidPayjoinConfig))); + } + #[test] fn unstarted_node_rejects_live_node_apis() { use std::str::FromStr; diff --git a/src/chain/bitcoind.rs b/src/chain/bitcoind.rs index ea32aac901..2cf7175784 100644 --- a/src/chain/bitcoind.rs +++ b/src/chain/bitcoind.rs @@ -36,7 +36,7 @@ use serde::Serialize; use super::{ChainListener, WalletSyncGuard, WalletSyncStatus}; use crate::config::{ BitcoindRestClientConfig, Config, DEFAULT_FEE_RATE_CACHE_UPDATE_TIMEOUT_SECS, - DEFAULT_TX_BROADCAST_TIMEOUT_SECS, + DEFAULT_TX_BROADCAST_TIMEOUT_SECS, DEFAULT_TX_LOOKUP_TIMEOUT_SECS, }; use crate::fee_estimator::{ apply_post_estimation_adjustments, get_all_conf_targets, get_num_block_defaults_for_target, @@ -753,6 +753,39 @@ impl BitcoindChainSource { }, } } + + pub(crate) async fn can_broadcast_transaction(&self, tx: &Transaction) -> Result { + let timeout_fut = tokio::time::timeout( + Duration::from_secs(DEFAULT_TX_LOOKUP_TIMEOUT_SECS), + self.api_client.test_mempool_accept(tx), + ); + + match timeout_fut.await { + Ok(res) => res.map_err(|e| { + log_error!( + self.logger, + "Failed to test mempool accept for transaction {}: {}", + tx.compute_txid(), + e + ); + Error::TxLookupFailed + }), + Err(e) => { + log_error!( + self.logger, + "Failed to test mempool accept for transaction {} due to timeout: {}", + tx.compute_txid(), + e + ); + log_trace!( + self.logger, + "Failed test mempool accept transaction bytes: {}", + log_bytes!(tx.encode()) + ); + Err(Error::TxLookupTimeout) + }, + } + } } #[derive(Clone)] @@ -1348,6 +1381,34 @@ impl BitcoindClient { .collect(); Ok(evicted_txids) } + + /// Tests whether the provided transaction would be accepted by the mempool. + pub(crate) async fn test_mempool_accept( + &self, tx: &Transaction, + ) -> Result { + match self { + BitcoindClient::Rpc { rpc_client, .. } => { + Self::test_mempool_accept_inner(Arc::clone(rpc_client), tx).await + }, + BitcoindClient::Rest { rpc_client, .. } => { + // We rely on the internal RPC client to make this call, as this + // operation is not supported by Bitcoin Core's REST interface. + Self::test_mempool_accept_inner(Arc::clone(rpc_client), tx).await + }, + } + } + + async fn test_mempool_accept_inner( + rpc_client: Arc, tx: &Transaction, + ) -> Result { + let tx_serialized = bitcoin::consensus::encode::serialize_hex(tx); + let tx_array = serde_json::json!([tx_serialized]); + + rpc_client + .call_method::("testmempoolaccept", &[tx_array]) + .await + .map(|resp| resp.0) + } } impl BlockSource for BitcoindClient { @@ -1529,6 +1590,23 @@ impl TryInto for JsonResponse { } } +pub(crate) struct TestMempoolAcceptResponse(pub bool); + +impl TryInto for JsonResponse { + type Error = String; + fn try_into(self) -> Result { + let array = + self.0.as_array().ok_or("Failed to parse testmempoolaccept response".to_string())?; + let first = + array.first().ok_or("Empty array response from testmempoolaccept".to_string())?; + let allowed = first + .get("allowed") + .and_then(|v| v.as_bool()) + .ok_or("Missing 'allowed' field in testmempoolaccept response".to_string())?; + Ok(TestMempoolAcceptResponse(allowed)) + } +} + /// Returns the mempool transactions we haven't handed out yet, and marks them as emitted. /// /// Entry times only have second resolution, so we track what we emitted per entry rather than diff --git a/src/chain/mod.rs b/src/chain/mod.rs index 36325cf3c5..f6bc12ae2c 100644 --- a/src/chain/mod.rs +++ b/src/chain/mod.rs @@ -18,7 +18,7 @@ use std::collections::HashSet; use std::sync::{Arc, Mutex}; use std::time::Duration; -use bitcoin::{Script, Txid}; +use bitcoin::{Script, Transaction, Txid}; #[cfg(feature = "chain-bitcoind")] use lightning::chain::Listen; use lightning::chain::{BlockLocator, Filter}; @@ -774,6 +774,31 @@ impl ChainSource { self.broadcast(package).await; } } + + /// Whether this chain source provides everything the payjoin receiver needs: a + /// `testmempoolaccept`-style broadcast check. + pub(crate) fn supports_payjoin(&self) -> bool { + match &self.kind { + #[cfg(feature = "chain-esplora")] + ChainSourceKind::Esplora(_) => false, + #[cfg(feature = "chain-electrum")] + ChainSourceKind::Electrum(_) => false, + #[cfg(feature = "chain-bitcoind")] + ChainSourceKind::Bitcoind(_) => true, + } + } + + #[cfg_attr(not(feature = "chain-bitcoind"), allow(unused_variables))] + pub(crate) async fn can_broadcast_transaction(&self, tx: &Transaction) -> Result { + match &self.kind { + #[cfg(feature = "chain-esplora")] + ChainSourceKind::Esplora(_) => Err(Error::ChainSourceNotSupported), + #[cfg(feature = "chain-electrum")] + ChainSourceKind::Electrum(_) => Err(Error::ChainSourceNotSupported), + #[cfg(feature = "chain-bitcoind")] + ChainSourceKind::Bitcoind(b) => b.can_broadcast_transaction(tx).await, + } + } } impl Filter for ChainSource { diff --git a/src/config.rs b/src/config.rs index b7a63b94f1..3c2762f827 100644 --- a/src/config.rs +++ b/src/config.rs @@ -224,6 +224,37 @@ pub(crate) const LIQUIDITY_DISCOVERY_RETRY_INITIAL_DELAY: Duration = Duration::f // thereafter until every configured LSP has been discovered. pub(crate) const LIQUIDITY_DISCOVERY_RETRY_MAX_DELAY: Duration = Duration::from_secs(60 * 60); +// The time interval at which we resume persisted payjoin sessions. +pub(crate) const PAYJOIN_RESUME_INTERVAL: Duration = Duration::from_secs(15); + +// How long we hold back a payjoin session that failed to advance. +pub(crate) const PAYJOIN_RETRY_DELAY: Duration = Duration::from_secs(5 * 60); + +// The duration after which completed or failed payjoin sessions are cleaned up (24 hours). +pub(crate) const PAYJOIN_SESSION_CLEANUP_AGE_SECS: u64 = 24 * 60 * 60; + +// How long we remember a payjoin sender's input whose spend we never saw buried (30 days). Until +// then, a sender reusing it to probe our UTXOs is declined. +pub(crate) const PAYJOIN_SEEN_INPUT_RETENTION_SECS: u64 = 30 * 24 * 60 * 60; + +// How long we keep rebroadcasting a payjoin fallback transaction that neither confirms nor is seen +// double-spent (1 week). The sender may have double-spent it to someone else, which the wallet +// never sees. +pub(crate) const PAYJOIN_FALLBACK_REBROADCAST_TIMEOUT_SECS: u64 = 7 * 24 * 60 * 60; + +// The interval at which we check for old payjoin sessions to clean up (1 hour). +pub(crate) const PAYJOIN_SESSION_CLEANUP_INTERVAL: Duration = Duration::from_secs(60 * 60); + +// Payjoin directory responses are OHTTP-encapsulated and small. +pub(crate) const PAYJOIN_MAX_RESPONSE_BYTES: usize = 64 * 1024; + +// The timeout after which we abort a payjoin relay operation. +pub(crate) const PAYJOIN_RELAY_TIMEOUT_SECS: u64 = 60; + +// The default timeout after which we abort a transaction lookup operation. +#[cfg(feature = "chain-bitcoind")] +pub(crate) const DEFAULT_TX_LOOKUP_TIMEOUT_SECS: u64 = 10; + /// The mode used for tracking forwarded payments. /// /// In either mode, a forward is tracked only when it has exactly one incoming HTLC and one outgoing @@ -273,8 +304,9 @@ impl Default for ForwardedPaymentTrackingMode { feature = "unified-payments", doc = "| `hrn_config` | HumanReadableNamesConfig::default() |" )] -/// | `manually_handle_unknown_bolt11_payments` | false | +/// | `manually_handle_unknown_bolt11_payments` | false | /// | `forwarded_payment_tracking_mode` | Stats | +/// | `payjoin_config` | None | /// /// See [`AnchorChannelsConfig`], [`RouteParametersConfig`], and /// [`ForwardedPaymentTrackingMode`] for more information regarding their respective default values. @@ -378,6 +410,8 @@ pub struct Config { pub manually_handle_unknown_bolt11_payments: bool, /// The mode used for tracking forwarded payments. pub forwarded_payment_tracking_mode: ForwardedPaymentTrackingMode, + /// Configuration options for Payjoin payments. + pub payjoin_config: Option, } impl Default for Config { @@ -402,6 +436,7 @@ impl Default for Config { hrn_config: HumanReadableNamesConfig::default(), manually_handle_unknown_bolt11_payments: false, forwarded_payment_tracking_mode: ForwardedPaymentTrackingMode::default(), + payjoin_config: None, } } } @@ -959,13 +994,39 @@ pub enum AsyncPaymentsRole { Server, } +/// Configuration options for PayJoin payments. +#[derive(Debug, Clone)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] +pub struct PayjoinConfig { + /// The URL of the Payjoin directory + pub payjoin_directory: String, + /// The URLs of the OHTTP relays to use when reaching the Payjoin directory. + pub ohttp_relays: Vec, +} + +impl PayjoinConfig { + /// Whether the directory and at least one relay are given, all as `http` or `https` URLs. + /// + /// Parsed as payjoin parses them when it uses them, so whatever passes here, payjoin accepts. + pub(crate) fn is_valid(&self) -> bool { + let is_http_url = |url: &str| { + payjoin::Url::parse(url) + .map(|url| url.scheme() == "http" || url.scheme() == "https") + .unwrap_or(false) + }; + is_http_url(&self.payjoin_directory) + && !self.ohttp_relays.is_empty() + && self.ohttp_relays.iter().all(|relay| is_http_url(relay)) + } +} + #[cfg(test)] mod tests { use std::str::FromStr; use super::{ clamp_full_scan_stop_gap, default_user_config, may_announce_channel, AnnounceError, Config, - ElectrumSyncConfig, EsploraSyncConfig, NodeAlias, SocketAddress, + ElectrumSyncConfig, EsploraSyncConfig, NodeAlias, PayjoinConfig, SocketAddress, DEFAULT_FULL_SCAN_STOP_GAP, MAX_FULL_SCAN_STOP_GAP, MIN_FULL_SCAN_STOP_GAP, }; @@ -1063,4 +1124,23 @@ mod tests { assert_eq!(clamp_full_scan_stop_gap(0), MIN_FULL_SCAN_STOP_GAP); assert_eq!(clamp_full_scan_stop_gap(MAX_FULL_SCAN_STOP_GAP + 1), MAX_FULL_SCAN_STOP_GAP); } + + #[test] + fn payjoin_config_needs_http_urls_and_a_relay() { + let config = |directory: &str, relays: &[&str]| PayjoinConfig { + payjoin_directory: directory.to_string(), + ohttp_relays: relays.iter().map(|relay| relay.to_string()).collect(), + }; + + assert!(config("https://payjo.in", &["https://pj.bobspacebkk.com"]).is_valid()); + // Plain http, as for a local directory and relay on regtest. + assert!(config("http://127.0.0.1:8080", &["http://localhost:3000"]).is_valid()); + + assert!(!config("https://payjo.in", &[]).is_valid()); + assert!(!config("ftp://payjo.in", &["https://pj.bobspacebkk.com"]).is_valid()); + assert!(!config("https://payjo.in", &["https://pj.bobspacebkk.com", "socks5://relay"]) + .is_valid()); + assert!(!config("not a url", &["https://pj.bobspacebkk.com"]).is_valid()); + assert!(!config("https://payjo.in", &["payjo.in"]).is_valid()); + } } diff --git a/src/error.rs b/src/error.rs index 202cb38878..2020c72b47 100644 --- a/src/error.rs +++ b/src/error.rs @@ -64,6 +64,10 @@ pub enum Error { TxSyncFailed, /// A transaction sync operation timed out. TxSyncTimeout, + /// A transaction lookup operation failed. + TxLookupFailed, + /// A transaction lookup operation timed out. + TxLookupTimeout, /// A gossip updating operation failed. GossipUpdateFailed, /// A gossip updating operation timed out. @@ -150,6 +154,14 @@ pub enum Error { ChainSourceNotSupported, /// The provided payer proof is invalid. InvalidPayerProof, + /// Payjoin is not configured. + PayjoinNotConfigured, + /// Payjoin session creation failed. + PayjoinSessionCreationFailed, + /// Payjoin session failed. + PayjoinSessionFailed, + /// The payjoin session can no longer be cancelled. + PayjoinSessionNotCancellable, } impl fmt::Display for Error { @@ -185,6 +197,8 @@ impl fmt::Display for Error { Self::OnchainTxSigningFailed => write!(f, "Failed to sign given transaction."), Self::TxSyncFailed => write!(f, "Failed to sync transactions."), Self::TxSyncTimeout => write!(f, "Syncing transactions timed out."), + Self::TxLookupFailed => write!(f, "Failed to look up transaction."), + Self::TxLookupTimeout => write!(f, "Transaction lookup timed out."), Self::GossipUpdateFailed => write!(f, "Failed to update gossip data."), Self::GossipUpdateTimeout => write!(f, "Updating gossip data timed out."), Self::LiquidityRequestFailed => write!(f, "Failed to request inbound liquidity."), @@ -248,6 +262,12 @@ impl fmt::Display for Error { write!(f, "The configured chain source is not supported.") }, Self::InvalidPayerProof => write!(f, "The provided payer proof is invalid."), + Self::PayjoinNotConfigured => write!(f, "Payjoin is not configured."), + Self::PayjoinSessionCreationFailed => write!(f, "Payjoin session creation failed."), + Self::PayjoinSessionFailed => write!(f, "Payjoin session failed."), + Self::PayjoinSessionNotCancellable => { + write!(f, "The payjoin session can no longer be cancelled.") + }, } } } diff --git a/src/io/mod.rs b/src/io/mod.rs index 1388005cc4..28446dbe50 100644 --- a/src/io/mod.rs +++ b/src/io/mod.rs @@ -122,3 +122,11 @@ pub(crate) const BDK_WALLET_ADDRESS_POOL_KEY: &str = "address_pool"; /// /// [`StaticInvoice`]: lightning::offers::static_invoice::StaticInvoice pub(crate) const STATIC_INVOICE_STORE_PRIMARY_NAMESPACE: &str = "static_invoices"; + +/// The payjoin sessions will be persisted under this key. +pub(crate) const PAYJOIN_SESSION_STORE_PRIMARY_NAMESPACE: &str = "payjoin_sessions"; +pub(crate) const PAYJOIN_SESSION_STORE_SECONDARY_NAMESPACE: &str = ""; + +/// The inputs seen in payjoin receive sessions will be persisted under this key. +pub(crate) const PAYJOIN_SEEN_INPUTS_PRIMARY_NAMESPACE: &str = "payjoin_seen_inputs"; +pub(crate) const PAYJOIN_SEEN_INPUTS_SECONDARY_NAMESPACE: &str = ""; diff --git a/src/lib.rs b/src/lib.rs index 20e7fd28b2..97952a9f50 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -134,8 +134,8 @@ pub use builder::{BuildError, Builder}; use chain::ChainSource; use config::{ default_user_config, may_announce_channel, AsyncPaymentsRole, ChannelConfig, Config, - LNURL_AUTH_TIMEOUT_SECS, NODE_ANN_BCAST_INTERVAL, PEER_RECONNECTION_INTERVAL, - RGS_SYNC_INTERVAL, + LNURL_AUTH_TIMEOUT_SECS, NODE_ANN_BCAST_INTERVAL, PAYJOIN_RESUME_INTERVAL, + PAYJOIN_SESSION_CLEANUP_INTERVAL, PEER_RECONNECTION_INTERVAL, RGS_SYNC_INTERVAL, }; use connection::ConnectionManager; pub use error::Error as NodeError; @@ -209,6 +209,8 @@ pub use vss_client; use crate::config::{LIQUIDITY_DISCOVERY_RETRY_INITIAL_DELAY, LIQUIDITY_DISCOVERY_RETRY_MAX_DELAY}; use crate::ffi::{maybe_deref, maybe_map_fee_rate_opt, maybe_wrap, FfiFeeRate}; use crate::liquidity::Liquidity; +use crate::payment::payjoin::manager::PayjoinManager; +use crate::payment::PayjoinPayment; use crate::scoring::setup_background_pathfinding_scores_sync; use crate::wallet::{FundingAmount, DUST_LIMIT_SATS}; @@ -294,6 +296,7 @@ pub struct Node { prober: Option>, #[cfg(cycle_tests)] _leak_checker: LeakChecker, + payjoin_manager: Option>, } impl Node { @@ -960,6 +963,73 @@ impl Node { }); } + if let Some(payjoin_manager) = self.payjoin_manager.as_ref() { + // Periodically resume payjoin sessions. + let resume_payjoin_manager = Arc::clone(payjoin_manager); + let resume_logger = Arc::clone(&self.logger); + let mut stop_resume = self.stop_sender.subscribe(); + self.runtime.spawn_cancellable_background_task(async move { + let mut interval = tokio::time::interval(PAYJOIN_RESUME_INTERVAL); + interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + loop { + tokio::select! { + _ = stop_resume.changed() => { + log_debug!(resume_logger, "Stopping payjoin session resume task."); + return; + } + _ = interval.tick() => { + if let Err(e) = resume_payjoin_manager.resume_payjoin_sessions(stop_resume.clone()).await { + log_error!(resume_logger, "Failed to resume payjoin sessions: {:?}", e); + } + } + } + } + }); + + // Rebroadcast pending payjoin fallbacks on chain tip changes. Kept apart from the resume + // task so a session that holds up resumption can't hold up the fallbacks too. + let fallback_payjoin_manager = Arc::clone(payjoin_manager); + let fallback_logger = Arc::clone(&self.logger); + let mut stop_fallback = self.stop_sender.subscribe(); + self.runtime.spawn_cancellable_background_task(async move { + let mut interval = tokio::time::interval(PAYJOIN_RESUME_INTERVAL); + interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + loop { + tokio::select! { + _ = stop_fallback.changed() => { + log_debug!(fallback_logger, "Stopping payjoin fallback rebroadcast task."); + return; + } + _ = interval.tick() => { + fallback_payjoin_manager.rebroadcast_pending_fallbacks().await; + } + } + } + }); + + // Periodically clean up old completed/failed payjoin sessions. + let cleanup_payjoin_manager = Arc::clone(payjoin_manager); + let cleanup_logger = Arc::clone(&self.logger); + let mut stop_cleanup = self.stop_sender.subscribe(); + self.runtime.spawn_cancellable_background_task(async move { + let mut interval = tokio::time::interval(PAYJOIN_SESSION_CLEANUP_INTERVAL); + interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + loop { + tokio::select! { + _ = stop_cleanup.changed() => { + log_debug!(cleanup_logger, "Stopping payjoin session cleanup task."); + return; + } + _ = interval.tick() => { + if let Err(e) = cleanup_payjoin_manager.cleanup_old_sessions().await { + log_error!(cleanup_logger, "Failed to cleanup old payjoin sessions: {:?}", e); + } + } + } + } + }); + } + log_info!(self.logger, "Startup complete."); *is_running_lock = true; Ok(()) @@ -1294,6 +1364,38 @@ impl Node { self.hrn_resolver.clone(), ) } + + /// Returns a payment handler allowing to receive [Payjoin] payments. + /// + /// If no [`PayjoinConfig`] was set via [`Builder::set_payjoin_config`], the handler's methods + /// return [`Error::PayjoinNotConfigured`]. + /// + /// [Payjoin]: https://payjoin.org + /// [`PayjoinConfig`]: crate::config::PayjoinConfig + #[cfg(not(feature = "uniffi"))] + pub fn payjoin_payment(&self) -> PayjoinPayment { + PayjoinPayment::new( + self.payjoin_manager.clone(), + Arc::clone(&self.runtime), + Arc::clone(&self.is_running), + ) + } + + /// Returns a payment handler allowing to receive [Payjoin] payments. + /// + /// If no [`PayjoinConfig`] was set via [`Builder::set_payjoin_config`], the handler's methods + /// return [`Error::PayjoinNotConfigured`]. + /// + /// [Payjoin]: https://payjoin.org + /// [`PayjoinConfig`]: crate::config::PayjoinConfig + #[cfg(feature = "uniffi")] + pub fn payjoin_payment(&self) -> Arc { + Arc::new(PayjoinPayment::new( + self.payjoin_manager.clone(), + Arc::clone(&self.runtime), + Arc::clone(&self.is_running), + )) + } } #[cfg(all(feature = "unified-payments", feature = "uniffi"))] diff --git a/src/payment/mod.rs b/src/payment/mod.rs index ade8c2a85e..727f3b2919 100644 --- a/src/payment/mod.rs +++ b/src/payment/mod.rs @@ -16,6 +16,7 @@ pub(crate) mod forwarding_store; mod hrn; mod metadata; mod onchain; +pub(crate) mod payjoin; mod spontaneous; pub(crate) mod store; #[cfg(feature = "unified-payments")] @@ -33,6 +34,10 @@ pub use forwarding::{ pub(crate) use hrn::HRNResolver; pub(crate) use metadata::PaymentMetadata; pub use onchain::OnchainPayment; +pub use payjoin::{ + PayjoinPayment, PayjoinReceiveSession, PayjoinSessionDetails, PayjoinSessionKind, + PayjoinSessionStatus, +}; pub use spontaneous::SpontaneousPayment; pub use store::{ Channel, ConfirmationStatus, LSPS2Parameters, PageToken, PaymentDetails, PaymentDetailsPage, diff --git a/src/payment/payjoin/manager.rs b/src/payment/payjoin/manager.rs new file mode 100644 index 0000000000..0d4d326fe4 --- /dev/null +++ b/src/payment/payjoin/manager.rs @@ -0,0 +1,2134 @@ +// This file is Copyright its original authors, visible in version control history. +// +// This file is licensed under the Apache License, Version 2.0 or the MIT license , at your option. You may not use this file except in +// accordance with one or both of these licenses. + +use std::collections::{HashMap, HashSet}; +use std::fmt; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use bitcoin::{psbt::Input, Amount, BlockHash, FeeRate, Transaction, TxIn, Txid}; + +use lightning::chain::channelmonitor::ANTI_REORG_DELAY; +use lightning::ln::channelmanager::PaymentId; +use lightning::log_warn; + +use payjoin::io::fetch_ohttp_keys; +use payjoin::persist::{OptionalTransitionOutcome, PersistedError}; +use payjoin::receive::v2::{ + replay_event_log_async as replay_receiver_event_log_async, CreateRequestError, + HasReplyableError, Initialized, MaybeInputsOwned, MaybeInputsSeen, OutputsUnknown, + PayjoinProposal, ProvisionalProposal, ReceiveSession, Receiver, ReceiverBuilder, ResolvedBy, + SessionOutcome as ReceiverSessionOutcome, UncheckedOriginalPayload, WantsFeeRange, WantsInputs, + WantsOutputs, +}; +use payjoin::receive::InputPair; + +use crate::chain::ChainSource; +use crate::config::{ + Config, PayjoinConfig, PAYJOIN_FALLBACK_REBROADCAST_TIMEOUT_SECS, PAYJOIN_MAX_RESPONSE_BYTES, + PAYJOIN_RELAY_TIMEOUT_SECS, PAYJOIN_RETRY_DELAY, PAYJOIN_SEEN_INPUT_RETENTION_SECS, + PAYJOIN_SESSION_CLEANUP_AGE_SECS, +}; +use crate::fee_estimator::{ConfirmationTarget, FeeEstimator, OnchainFeeEstimator}; +use crate::logger::{log_debug, log_error, log_info, LdkLogger, Logger}; +use crate::payment::payjoin::payjoin_session::{PayjoinSession, PayjoinSessionKind, PayjoinStatus}; +use crate::payment::payjoin::persist::KVStorePayjoinReceiverPersister; +use crate::payment::payjoin::seen_inputs::{ + check_and_record_seen_input, forget_seen_inputs, prune_seen_inputs, +}; +use crate::payment::payjoin::PayjoinSessionDetails; + +use crate::types::{Broadcaster, PayjoinSeenInputsStore, PayjoinSessionStore}; +use crate::wallet::{PayjoinFallbackStatus, Wallet}; +use crate::Error; + +/// The result of opening a Payjoin receive session. +#[derive(Debug, Clone)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] +pub struct PayjoinReceiveSession { + /// The BIP 21 URI to share with the sender. + pub uri: String, + /// The identifier of this session, to be passed to [`PayjoinPayment::payjoin_session`] and + /// [`PayjoinPayment::cancel_payjoin_session`]. + /// + /// This is not the [`PaymentId`] of the resulting on-chain payment, which is derived from the + /// txid of the transaction that settles the session. + /// + /// [`PayjoinPayment::payjoin_session`]: crate::payment::PayjoinPayment::payjoin_session + /// [`PayjoinPayment::cancel_payjoin_session`]: crate::payment::PayjoinPayment::cancel_payjoin_session + pub session_id: PaymentId, +} + +#[derive(Clone)] +pub(crate) struct PayjoinManager { + payjoin_session_store: Arc, + payjoin_seen_inputs_store: Arc, + logger: Arc, + config: Arc, + wallet: Arc, + fee_estimator: Arc, + chain_source: Arc, + broadcaster: Arc, + session_retry_at: Arc>>, + /// The wallet's chain tip when pending fallbacks were last rebroadcast. `None` until the + /// first pass after startup, which rebroadcasts what a restart dropped from the queue. + fallback_rebroadcast_tip: Arc>>, +} + +impl PayjoinManager { + pub(crate) fn new( + payjoin_session_store: Arc, + payjoin_seen_inputs_store: Arc, logger: Arc, + config: Arc, wallet: Arc, fee_estimator: Arc, + chain_source: Arc, broadcaster: Arc, + ) -> Self { + Self { + payjoin_session_store, + payjoin_seen_inputs_store, + logger, + config, + wallet, + fee_estimator, + chain_source, + broadcaster, + session_retry_at: Arc::new(Mutex::new(HashMap::new())), + fallback_rebroadcast_tip: Arc::new(Mutex::new(None)), + } + } + + pub(crate) async fn receive_payjoin( + &self, amount_sats: u64, fee_rate: Option, + ) -> Result { + let payjoin_config = + self.config.payjoin_config.as_ref().ok_or(Error::PayjoinNotConfigured)?; + + // Generate a new session ID + let mut random_bytes = [0u8; 32]; + getrandom::fill(&mut random_bytes).map_err(|e| { + log_error!(self.logger, "Failed to generate random session ID: {}", e); + Error::PayjoinSessionCreationFailed + })?; + let session_id = PaymentId(random_bytes); + + let confirmation_target = ConfirmationTarget::OnchainPayment; + let fee_rate = + fee_rate.unwrap_or_else(|| self.fee_estimator.estimate_fee_rate(confirmation_target)); + + let ohttp_keys = { + let mut result = Err(Error::ConnectionFailed); + for relay in self.relay_order(payjoin_config)? { + match fetch_ohttp_keys(relay, payjoin_config.payjoin_directory.as_str()).await { + Ok(keys) => { + result = Ok(keys); + break; + }, + Err(e) => { + log_error!( + self.logger, + "Failed to fetch OHTTP keys via {}: {}. Trying next relay.", + relay, + e + ); + }, + } + } + result + }?; + log_debug!(self.logger, "Fetched OHTTP keys: {:?}", ohttp_keys); + + let address = self.wallet.get_new_address().await?; + + let amount = Amount::from_sat(amount_sats); + + // Create a new persister for this session + let persister = KVStorePayjoinReceiverPersister::new( + session_id, + Arc::clone(&self.payjoin_session_store), + ); + + let session = + ReceiverBuilder::new(address, payjoin_config.payjoin_directory.as_str(), ohttp_keys) + .map_err(|e| { + log_error!(self.logger, "Failed to create receiver builder: {}", e); + Error::PayjoinSessionCreationFailed + })? + .with_amount(amount) + .with_max_fee_rate(fee_rate) + .build() + .save_async(&persister) + .await + .map_err(|e| { + log_error!(self.logger, "Failed to persist the new payjoin session: {:?}", e); + Error::PersistenceFailed + })?; + + log_info!(self.logger, "Receive session established"); + let uri = session.pj_uri().to_string(); + + // Without its URI the session isn't listed, which suits one whose URI the caller never got. + let mut payjoin_session = persister.get_session().await?; + payjoin_session.uri = Some(uri.clone()); + payjoin_session.amount_sats = Some(amount_sats); + self.payjoin_session_store.insert_or_update(payjoin_session).await?; + + Ok(PayjoinReceiveSession { uri, session_id }) + } + + fn relay_order<'a>(&self, payjoin_config: &'a PayjoinConfig) -> Result, Error> { + let count = payjoin_config.ohttp_relays.len(); + let start = if count > 0 { + let mut bytes = [0u8; 8]; + getrandom::fill(&mut bytes).map_err(|e| { + log_error!(self.logger, "Failed to generate random relay index: {}", e); + Error::PayjoinSessionFailed + })?; + u64::from_ne_bytes(bytes) as usize % count + } else { + 0 + }; + Ok((0..count).map(|i| payjoin_config.ohttp_relays[(start + i) % count].as_str()).collect()) + } + + async fn process_receiver_session( + &self, session: ReceiveSession, persister: &KVStorePayjoinReceiverPersister, + ) -> Result<(), Error> { + let Some(mut session) = self.settle_session(session, persister).await? else { + return Ok(()); + }; + if persister.get_session().await?.cancel_requested { + let Some(next) = self.apply_cancel(session, persister).await? else { + return Ok(()); + }; + session = next; + } + loop { + session = match session { + ReceiveSession::Initialized(proposal) => { + match self.read_from_directory(proposal, persister).await? { + // No sender yet. Yield so the resume task can service other sessions; + // the next tick re-enters this session where it left off. + ReceiveSession::Initialized(_) => return Ok(()), + next => next, + } + }, + ReceiveSession::UncheckedOriginalPayload(proposal) => { + self.check_original_payload(proposal, persister).await? + }, + ReceiveSession::MaybeInputsOwned(proposal) => { + self.check_inputs_not_owned(proposal, persister).await? + }, + ReceiveSession::MaybeInputsSeen(proposal) => { + self.check_no_inputs_seen_before(proposal, persister).await? + }, + ReceiveSession::OutputsUnknown(proposal) => { + self.identify_receiver_outputs(proposal, persister).await? + }, + ReceiveSession::WantsOutputs(proposal) => { + self.commit_outputs(proposal, persister).await? + }, + ReceiveSession::WantsInputs(proposal) => { + self.contribute_inputs(proposal, persister).await? + }, + ReceiveSession::WantsFeeRange(proposal) => { + self.apply_fee_range(proposal, persister).await? + }, + ReceiveSession::ProvisionalProposal(proposal) => { + self.finalize_proposal(proposal, persister).await? + }, + ReceiveSession::PayjoinProposal(proposal) => { + match self.send_payjoin_proposal(proposal, persister).await? { + // Retry on the next tick instead of hammering the directory + // when a transient failure occurs. + ReceiveSession::PayjoinProposal(_) => return Ok(()), + next => next, + } + }, + ReceiveSession::HasReplyableError(error) => { + match self.handle_error(error, persister).await? { + // Retry on the next tick instead of hammering the relay + // when a transient failure occurs. + ReceiveSession::HasReplyableError(_) => return Ok(()), + next => next, + } + }, + ReceiveSession::Monitor(_) => { + // `settle_session` closes the session once wallet sync sees a transaction + // spending the sender's inputs, so there is nothing to do until then. + log_debug!( + self.logger, + "Payjoin session {} is waiting for the sender to broadcast.", + persister.session_id() + ); + return Ok(()); + }, + ReceiveSession::PendingFallback(pending) => { + let fallback_tx = pending.fallback_tx().clone(); + let mut payjoin_session = persister.get_session().await?; + self.close_session_with_fallback(&mut payjoin_session, Some(&fallback_tx)) + .await; + + pending.close().save_async(persister).await?; + return Ok(()); + }, + ReceiveSession::Closed(outcome) => { + return self.handle_closed_session(outcome, persister).await; + }, + } + } + } + + /// Applies a cancellation requested through [`Self::cancel_session`]. + /// + /// Runs after [`Self::settle_session`], so only for a session nothing spends the sender's + /// inputs of yet. Returns the session to keep processing: [`ReceiveSession::PendingFallback`] + /// if the session had the sender's fallback, so it is broadcast like that of a failed payjoin, + /// or the session unchanged if it is ending already. Returns `None` if the session closed. + async fn apply_cancel( + &self, session: ReceiveSession, persister: &KVStorePayjoinReceiverPersister, + ) -> Result, Error> { + let pending = match session { + ReceiveSession::Initialized(r) => { + self.close_cancelled_session(persister).await?; + r.cancel().save_async(persister).await?; + return Ok(None); + }, + ReceiveSession::UncheckedOriginalPayload(r) => { + self.close_cancelled_session(persister).await?; + r.cancel().save_async(persister).await?; + return Ok(None); + }, + // Whether there's a fallback to broadcast is only known from the transition. + ReceiveSession::HasReplyableError(r) => match r.cancel().save_async(persister).await? { + Some(pending) => pending, + None => { + self.close_cancelled_session(persister).await?; + return Ok(None); + }, + }, + ReceiveSession::MaybeInputsOwned(r) => r.cancel().save_async(persister).await?, + ReceiveSession::MaybeInputsSeen(r) => r.cancel().save_async(persister).await?, + ReceiveSession::OutputsUnknown(r) => r.cancel().save_async(persister).await?, + ReceiveSession::WantsOutputs(r) => r.cancel().save_async(persister).await?, + ReceiveSession::WantsInputs(r) => r.cancel().save_async(persister).await?, + ReceiveSession::WantsFeeRange(r) => r.cancel().save_async(persister).await?, + ReceiveSession::ProvisionalProposal(r) => r.cancel().save_async(persister).await?, + ReceiveSession::PayjoinProposal(r) => r.cancel().save_async(persister).await?, + ReceiveSession::Monitor(r) => r.cancel().save_async(persister).await?, + session @ (ReceiveSession::PendingFallback(_) | ReceiveSession::Closed(_)) => { + return Ok(Some(session)); + }, + }; + log_info!( + self.logger, + "Cancelled payjoin session {}. Broadcasting the sender's fallback transaction.", + persister.session_id() + ); + Ok(Some(ReceiveSession::PendingFallback(pending))) + } + + /// Marks a cancelled session that has no fallback to broadcast as [`PayjoinStatus::Failed`]. + /// + /// Our record goes first, as in [`Self::settle_session`]: a session that isn't active is never + /// replayed, so it doesn't matter if persisting the close event fails afterwards. + async fn close_cancelled_session( + &self, persister: &KVStorePayjoinReceiverPersister, + ) -> Result<(), Error> { + let mut session = persister.get_session().await?; + session.status = PayjoinStatus::Failed; + session.completed_at.get_or_insert_with(|| { + SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or(Duration::from_secs(0)).as_secs() + }); + self.payjoin_session_store.insert_or_update(session).await?; + log_info!(self.logger, "Cancelled payjoin session {}.", persister.session_id()); + Ok(()) + } + + /// Returns the details of the session `session_id`, or `None` if there is no such session. + /// + /// See [`PayjoinPayment::payjoin_session`]. + /// + /// [`PayjoinPayment::payjoin_session`]: crate::payment::PayjoinPayment::payjoin_session + pub(crate) async fn session( + &self, session_id: PaymentId, + ) -> Result, Error> { + Ok(self.payjoin_session_store.get(&session_id).await?.and_then(|s| s.details())) + } + + /// Returns the details of all known sessions. + /// + /// See [`PayjoinPayment::list_payjoin_sessions`]. + /// + /// [`PayjoinPayment::list_payjoin_sessions`]: crate::payment::PayjoinPayment::list_payjoin_sessions + pub(crate) async fn list_sessions(&self) -> Vec { + self.payjoin_session_store + .list_filter(|_| true) + .await + .iter() + .filter_map(|session| session.details()) + .collect() + } + + /// Requests the cancellation of the session `session_id`, which the resume task applies. + /// + /// See [`PayjoinPayment::cancel_payjoin_session`]. + /// + /// [`PayjoinPayment::cancel_payjoin_session`]: crate::payment::PayjoinPayment::cancel_payjoin_session + pub(crate) async fn cancel_session(&self, session_id: PaymentId) -> Result<(), Error> { + let session = + self.payjoin_session_store.get(&session_id).await?.ok_or(Error::InvalidPaymentId)?; + if session.cancel_requested { + return Ok(()); + } + if session.status != PayjoinStatus::Active { + return Err(Error::PayjoinSessionNotCancellable); + } + // Once something spends the sender's inputs, the session settles on that, so cancelling + // would change nothing. + if let Some(fallback_tx) = session.fallback_tx() { + let inputs = fallback_tx.input.iter().map(|txin| txin.previous_output); + if !self.wallet.spends_of_outpoints(inputs).is_empty() { + return Err(Error::PayjoinSessionNotCancellable); + } + } + + // Set atomically, so a session ending meanwhile isn't flagged. + let mut outcome = Err(Error::InvalidPaymentId); + self.payjoin_session_store + .mutate(&session_id, |existing| { + let existing = existing?; + if existing.cancel_requested { + outcome = Ok(()); + return None; + } + if existing.status != PayjoinStatus::Active { + outcome = Err(Error::PayjoinSessionNotCancellable); + return None; + } + outcome = Ok(()); + let mut session = existing.clone(); + session.cancel_requested = true; + Some(session) + }) + .await?; + outcome?; + + // Apply it on the next resume rather than after a backoff. + self.session_retry_at.lock().expect("lock").remove(&session_id); + log_info!(self.logger, "Requested the cancellation of payjoin session {}.", session_id); + Ok(()) + } + + /// Settles a session against the transactions wallet sync has seen spending the sender's + /// inputs. + /// + /// [`ReceiveSession::classify_tx`] tells whether such a spend is the payjoin, the sender's + /// fallback, or neither. The payment of the spend is classified to match as soon as it is + /// seen. The session closes once the spend is confirmed through [`ANTI_REORG_DELAY`], and + /// until then the protocol isn't advanced any further, as a proposal could no longer confirm. + /// + /// Returns the session if nothing spends the sender's inputs yet, so the protocol should + /// continue, or `None` if something does. + async fn settle_session( + &self, session: ReceiveSession, persister: &KVStorePayjoinReceiverPersister, + ) -> Result, Error> { + // Recorded once the sender's original transaction passed the broadcast suitability check, + // which is the first state `classify_tx` supports. + let Some(fallback_tx) = persister.get_session().await?.fallback_tx().cloned() else { + return Ok(Some(session)); + }; + + let spends = self + .wallet + .spends_of_outpoints(fallback_tx.input.iter().map(|txin| txin.previous_output)); + // Spends come most confirmed first, which is the one `classify_tx` asks to classify. + let Some((tx, confirmations, resolution)) = spends.into_iter().find_map(|(tx, confs)| { + session.classify_tx(&tx).map(|resolution| (tx, confs, resolution)) + }) else { + return Ok(Some(session)); + }; + + let session_id = persister.session_id(); + let txid = tx.compute_txid(); + let resolved_by = resolution.resolved_by(); + // Wallet sync keeps the payjoin and a spend that replaces it, or that it replaces, as one + // payment, which moves to whichever transaction won. Keep its classification in step with + // that transaction, as a reorg may swap the winner. + if resolved_by == ResolvedBy::Payjoin { + self.wallet.classify_payjoin(txid, Some(&tx)).await?; + } else { + self.wallet.unclassify_payjoin(txid).await?; + } + + if confirmations < ANTI_REORG_DELAY { + log_debug!( + self.logger, + "Payjoin session {} was resolved by {:?} transaction {} with {} confirmations. Closing it at {}.", + session_id, + resolved_by, + txid, + confirmations, + ANTI_REORG_DELAY + ); + return Ok(None); + } + + self.forget_spent_sender_inputs(&tx, &fallback_tx).await; + + // Our record goes first: resumption only picks up active sessions, so if persisting the + // close event fails afterwards, the session is still never replayed. + let mut payjoin_session = persister.get_session().await?; + payjoin_session.status = match resolved_by { + ResolvedBy::Payjoin => { + log_info!( + self.logger, + "Payjoin session {} completed: payjoin transaction {} confirmed.", + session_id, + txid + ); + PayjoinStatus::Completed + }, + ResolvedBy::Fallback => { + log_info!( + self.logger, + "Payjoin session {} failed: the sender's fallback transaction {} confirmed.", + session_id, + txid + ); + PayjoinStatus::Failed + }, + _ => { + log_warn!( + self.logger, + "Payjoin session {} failed: the sender's inputs were spent by unrecognized transaction {}.", + session_id, + txid + ); + PayjoinStatus::Failed + }, + }; + payjoin_session.resolution_txid = Some(txid); + payjoin_session.completed_at.get_or_insert_with(|| { + SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or(Duration::from_secs(0)).as_secs() + }); + self.payjoin_session_store.insert_or_update(payjoin_session).await?; + + if let Err(e) = session.close(resolution).save_async(persister).await { + log_error!( + self.logger, + "Failed to record the close of payjoin session {}: {:?}", + session_id, + e + ); + } + Ok(None) + } + + async fn read_from_directory( + &self, session: Receiver, persister: &KVStorePayjoinReceiverPersister, + ) -> Result { + let Some((ohttp_response, context)) = + self.post_via_relay(|relay| session.create_poll_request(relay)).await? + else { + log_info!(self.logger, "Payjoin session {} expired.", persister.session_id()); + return Ok(ReceiveSession::Closed(ReceiverSessionOutcome::Aborted)); + }; + + let state_transition = session + .process_response(ohttp_response.as_bytes(), context) + .save_async(persister) + .await; + + match state_transition { + Ok(OptionalTransitionOutcome::Progress(next_state)) => { + log_info!( + self.logger, + "Got a request from the sender. Responding with a Payjoin proposal." + ); + Ok(ReceiveSession::UncheckedOriginalPayload(next_state)) + }, + Ok(OptionalTransitionOutcome::Stasis(current_state)) => { + Ok(ReceiveSession::Initialized(current_state)) + }, + Err(e) if e.is_transient() => { + log_debug!(self.logger, "Transient error polling for request, retrying: {e:?}"); + let session = e.transient_state().expect("transient error carries current state"); + Ok(ReceiveSession::Initialized(session)) + }, + // The directory's response was fatal, so payjoin closed the session's log. + Err(e) if e.is_fatal() => { + log_error!(self.logger, "Payjoin directory rejected the session: {:?}", e); + Ok(ReceiveSession::Closed(ReceiverSessionOutcome::Aborted)) + }, + Err(e) => Err(self.step_error("process the sender's directory response", &e)), + } + } + + async fn post_request(&self, req: payjoin::Request) -> Result { + let response = bitreq::post(req.url) + .with_header("Content-Type", req.content_type) + .with_body(req.body) + .with_timeout(PAYJOIN_RELAY_TIMEOUT_SECS) + .with_max_body_size(PAYJOIN_MAX_RESPONSE_BYTES) + .send_async() + .await + .map_err(|e| { + log_error!(self.logger, "HTTP request failed: {}", e); + Error::ConnectionFailed + })?; + + if !(200..300).contains(&response.status_code) { + log_error!( + self.logger, + "Relay returned status {} for payjoin request.", + response.status_code + ); + return Err(Error::ConnectionFailed); + } + + Ok(response) + } + + /// Handles a validation step whose transition failed. A rejection of the sender's proposal + /// was saved as [`ReceiveSession::HasReplyableError`], so the session goes on from there to + /// tell the sender. Any other failure is returned as [`Self::step_error`] maps it. + fn validation_failed( + &self, step: &str, + e: PersistedError, CurrentState>, + ) -> Result { + if e.storage_error_ref().is_some() || !e.is_fatal() { + return Err(self.step_error(step, &e)); + } + if let Some(api_error) = e.api_error_ref() { + log_info!( + self.logger, + "Rejected the sender's proposal. Failed to {}: {}", + step, + api_error + ); + } + e.fatal_state().map(ReceiveSession::HasReplyableError).ok_or(Error::PayjoinSessionFailed) + } + + /// The error to return for a step whose transition failed: the persister's error if saving + /// it failed, or [`Error::PayjoinSessionFailed`] if payjoin rejected it. + fn step_error( + &self, step: &str, e: &PersistedError, + ) -> Error { + log_error!(self.logger, "Failed to {}: {:?}", step, e); + match e.storage_error_ref() { + Some(storage_error) => *storage_error, + None => Error::PayjoinSessionFailed, + } + } + + async fn check_original_payload( + &self, proposal: Receiver, + persister: &KVStorePayjoinReceiverPersister, + ) -> Result { + let transaction = proposal.extract_tx_to_check_broadcast_suitability(); + let is_broadcast_suitable = + self.chain_source.can_broadcast_transaction(&transaction).await.map_err(|e| { + log_error!( + self.logger, + "Failed to check broadcast suitability of the sender's original transaction: {:?}", + e + ); + Error::PayjoinSessionFailed + })?; + + let proposal = match proposal + .apply_broadcast_suitability(None, is_broadcast_suitable) + .save_async(persister) + .await + { + Ok(proposal) => proposal, + Err(e) => { + return self.validation_failed( + "check the sender's original transaction for broadcast suitability", + e, + ) + }, + }; + + // The sender's original transaction is the fallback: if the payjoin fails or times out, + // broadcast it to ensure the receiver still gets paid. Its inputs are also what + // `settle_session` looks for spends of. + let mut session = persister.get_session().await?; + + session.set_fallback_tx(transaction); + self.payjoin_session_store.insert_or_update(session).await?; + + log_info!( + self.logger, + "Fallback transaction received. This will be broadcast if the Payjoin fails" + ); + + Ok(ReceiveSession::MaybeInputsOwned(proposal)) + } + + async fn check_inputs_not_owned( + &self, proposal: Receiver, persister: &KVStorePayjoinReceiverPersister, + ) -> Result { + let mut marked_checklist = Vec::new(); + for item in proposal.inputs_owned_checklist() { + let owned = self.wallet.is_my_outpoint(item.value()).map_err(|e| { + log_error!(self.logger, "Failed to check whether a sender input is ours: {}", e); + e + })?; + marked_checklist.push(item.mark(owned)); + } + + let proposal = match proposal + .apply_inputs_owned_checklist(marked_checklist) + .save_async(persister) + .await + { + Ok(proposal) => proposal, + Err(e) => { + return self.validation_failed("check whether the sender's inputs belong to us", e) + }, + }; + + Ok(ReceiveSession::MaybeInputsSeen(proposal)) + } + + async fn check_no_inputs_seen_before( + &self, proposal: Receiver, persister: &KVStorePayjoinReceiverPersister, + ) -> Result { + let session_id = persister.session_id(); + + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or(Duration::from_secs(0)) + .as_secs(); + + let mut marked_checklist = Vec::new(); + for item in proposal.inputs_seen_checklist() { + let seen = check_and_record_seen_input( + &self.payjoin_seen_inputs_store, + *item.value(), + session_id, + now, + ) + .await?; + marked_checklist.push(item.mark(seen)); + } + + let transition = proposal.apply_inputs_seen_checklist(marked_checklist); + let proposal = match transition.save_async(persister).await { + Ok(proposal) => proposal, + Err(e) => return self.validation_failed("check the sender's inputs for reuse", e), + }; + + Ok(ReceiveSession::OutputsUnknown(proposal)) + } + + async fn identify_receiver_outputs( + &self, proposal: Receiver, persister: &KVStorePayjoinReceiverPersister, + ) -> Result { + let mut marked_checklist = Vec::new(); + for item in proposal.outputs_owned_checklist() { + let owned = self.wallet.is_mine(item.value().clone()).map_err(|e| { + log_error!(self.logger, "Failed to check whether a proposal output is ours: {}", e); + e + })?; + marked_checklist.push(item.mark(owned)); + } + + let proposal = match proposal + .apply_outputs_owned_checklist(marked_checklist) + .save_async(persister) + .await + { + Ok(proposal) => proposal, + Err(e) => { + return self.validation_failed("identify our outputs in the sender's proposal", e) + }, + }; + Ok(ReceiveSession::WantsOutputs(proposal)) + } + + async fn commit_outputs( + &self, proposal: Receiver, persister: &KVStorePayjoinReceiverPersister, + ) -> Result { + let proposal = proposal.commit_outputs().save_async(persister).await.map_err(|e| { + log_error!(self.logger, "Failed to commit the payjoin outputs: {:?}", e); + Error::PersistenceFailed + })?; + Ok(ReceiveSession::WantsInputs(proposal)) + } + + async fn contribute_inputs( + &self, proposal: Receiver, persister: &KVStorePayjoinReceiverPersister, + ) -> Result { + let candidate_inputs = self.list_input_pairs()?; + + if candidate_inputs.is_empty() { + log_error!( + self.logger, + "No spendable UTXOs available in wallet. Cannot contribute inputs to payjoin." + ); + return Err(Error::InsufficientFunds); + } + + let selected_input = proposal.try_preserving_privacy(candidate_inputs).map_err(|e| { + log_error!(self.logger, "Failed to select input for payjoin contribution: {}", e); + Error::PayjoinSessionFailed + })?; + let proposal = proposal + .contribute_inputs(vec![selected_input]) + .map_err(|e| { + log_error!(self.logger, "Failed to contribute inputs to payjoin: {}", e); + Error::PayjoinSessionFailed + })? + .commit_inputs() + .save_async(persister) + .await + .map_err(|e| { + log_error!(self.logger, "Failed to commit our contributed payjoin inputs: {:?}", e); + Error::PersistenceFailed + })?; + Ok(ReceiveSession::WantsFeeRange(proposal)) + } + + fn list_input_pairs(&self) -> Result, Error> { + let unspent = self.wallet.list_unspent_confirmed_utxos()?; + + let mut input_pairs = Vec::with_capacity(unspent.len()); + + for u in unspent { + let txin = TxIn { previous_output: u.outpoint, ..Default::default() }; + let psbtin = Input { witness_utxo: Some(u.output.clone()), ..Default::default() }; + + let input_pair = InputPair::new(txin, psbtin, None).map_err(|e| { + log_error!(self.logger, "Failed to create InputPair: {}", e); + Error::PayjoinSessionFailed + })?; + + input_pairs.push(input_pair); + } + + Ok(input_pairs) + } + + async fn apply_fee_range( + &self, proposal: Receiver, persister: &KVStorePayjoinReceiverPersister, + ) -> Result { + let proposal = proposal + .apply_fee_range(None, None) + .save_async(persister) + .await + .map_err(|e| self.step_error("apply the payjoin fee range", &e))?; + + Ok(ReceiveSession::ProvisionalProposal(proposal)) + } + + async fn finalize_proposal( + &self, proposal: Receiver, persister: &KVStorePayjoinReceiverPersister, + ) -> Result { + let signed_psbt = self.wallet.process_psbt(proposal.psbt_to_sign())?; + + let proposal = proposal + .finalize_signed_proposal(&signed_psbt) + .save_async(persister) + .await + .map_err(|e| self.step_error("finalize the payjoin proposal", &e))?; + Ok(ReceiveSession::PayjoinProposal(proposal)) + } + + async fn send_payjoin_proposal( + &self, proposal: Receiver, persister: &KVStorePayjoinReceiverPersister, + ) -> Result { + // Recorded before the proposal can reach the sender, so a session that expires before + // `settle_session` closes it can still recognize the payjoin once it confirms. That a + // proposal never sent is recorded does no harm, as nothing can confirm with its txid. + let payjoin_txid = proposal.psbt().unsigned_tx.compute_txid(); + let mut session = persister.get_session().await?; + if session.payjoin_txid != Some(payjoin_txid) { + session.payjoin_txid = Some(payjoin_txid); + self.payjoin_session_store.insert_or_update(session).await?; + } + + let Some((ohttp_response, context)) = + self.post_via_relay(|relay| proposal.create_post_request(relay)).await? + else { + log_info!(self.logger, "Payjoin session {} expired.", persister.session_id()); + return Ok(ReceiveSession::Closed(ReceiverSessionOutcome::Aborted)); + }; + + let payjoin_psbt = proposal.psbt().clone(); + + match proposal + .process_response(ohttp_response.as_bytes(), context) + .save_async(persister) + .await + { + Ok(session) => { + // At this point we will persist the fee and txid to the session store + let payjoin_tx = payjoin_psbt.extract_tx_unchecked_fee_rate(); + let txid = payjoin_tx.compute_txid(); + + log_info!( + self.logger, + "Payjoin proposal sent. Waiting for the sender to broadcast it. TXID, unless the sender's signatures change it: {}", + txid + ); + Ok(ReceiveSession::Monitor(session)) + }, + Err(e) if e.is_transient() => { + log_debug!( + self.logger, + "Transient error sending payjoin proposal, retrying: {e:?}" + ); + let proposal = e.transient_state().expect("transient error carries current state"); + Ok(ReceiveSession::PayjoinProposal(proposal)) + }, + // The directory's response was fatal, so payjoin saved the session as pending its + // fallback, which goes out now. + Err(e) if e.is_fatal() => { + log_error!(self.logger, "Payjoin directory rejected our proposal: {:?}", e); + e.fatal_state() + .map(ReceiveSession::PendingFallback) + .ok_or(Error::PayjoinSessionFailed) + }, + Err(e) => Err(self.step_error("process the directory's response to our proposal", &e)), + } + } + + async fn post_via_relay( + &self, mut build: F, + ) -> Result, Error> + where + F: FnMut(&str) -> Result<(payjoin::Request, payjoin::OhttpResponse), CreateRequestError>, + { + let payjoin_config = + self.config.payjoin_config.as_ref().ok_or(Error::PayjoinNotConfigured)?; + + for relay in self.relay_order(payjoin_config)? { + let (req, ctx) = match build(relay) { + Ok(r) => r, + Err(e) if e.is_expired() => return Ok(None), + Err(e) => { + // Building the request doesn't depend on the relay, so this would fail + // the same way for every remaining relay. + log_error!(self.logger, "Failed to build payjoin request: {}", e); + return Err(Error::PayjoinSessionFailed); + }, + }; + + match self.post_request(req).await { + Ok(resp) => return Ok(Some((resp, ctx))), + Err(e) => { + log_debug!( + self.logger, + "Request via relay {} failed, trying next: {:?}", + relay, + e + ); + }, + } + } + + log_error!(self.logger, "All configured OHTTP relays failed."); + Err(Error::ConnectionFailed) + } + + async fn handle_error( + &self, session: Receiver, persister: &KVStorePayjoinReceiverPersister, + ) -> Result { + let Some((err_response, err_ctx)) = + self.post_via_relay(|relay| session.create_error_request(relay)).await? + else { + log_info!(self.logger, "Payjoin session {} expired.", persister.session_id()); + return Ok(ReceiveSession::Closed(ReceiverSessionOutcome::Aborted)); + }; + + let err_bytes = err_response.as_bytes(); + + match session.process_error_response(err_bytes, err_ctx).save_async(persister).await { + Ok(Some(pending)) => { + log_info!( + self.logger, + "Session delivered error reply. Broadcast the fallback transaction." + ); + Ok(ReceiveSession::PendingFallback(pending)) + }, + Ok(None) => Ok(ReceiveSession::Closed(ReceiverSessionOutcome::Aborted)), + Err(e) if e.is_transient() => { + log_debug!(self.logger, "Transient error posting error response, retrying: {e:?}"); + let session = e.transient_state().expect("transient error carries current state"); + Ok(ReceiveSession::HasReplyableError(session)) + }, + Err(e) => { + if let Some(api_err) = e.api_error_ref() { + log_warn!(self.logger, "Failed to confirm error response delivery: {api_err}"); + } + match e.fatal_state() { + Some(pending) => { + log_error!(self.logger, "Session failed to deliver error reply. Broadcast the fallback transaction"); + Ok(ReceiveSession::PendingFallback(pending)) + }, + None => Err(Error::PayjoinSessionFailed), + } + }, + } + } + + async fn handle_closed_session( + &self, outcome: ReceiverSessionOutcome, persister: &KVStorePayjoinReceiverPersister, + ) -> Result<(), Error> { + let session_id = persister.session_id(); + let mut session = persister.get_session().await?; + session.completed_at.get_or_insert_with(|| { + SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or(Duration::from_secs(0)).as_secs() + }); + + // `settle_session` updates our record before it closes a session, which then isn't replayed, + // so its closes don't come through here. `Success` and `FallbackBroadcasted` are only + // recorded by the deprecated `check_for_transaction`, which we don't call. + match outcome { + ReceiverSessionOutcome::Success(txid) => { + log_info!(self.logger, "Payjoin session completed with transaction {}.", txid); + // Wallet sync fills in the payment's amount and fee. + self.wallet.classify_payjoin(txid, None).await?; + + session.status = PayjoinStatus::Completed; + session.resolution_txid = Some(txid); + + self.payjoin_session_store.insert_or_update(session).await?; + }, + ReceiverSessionOutcome::PayjoinProposalSent => { + log_info!(self.logger, "Payjoin session closed after its proposal was sent."); + session.status = PayjoinStatus::Completed; + + self.payjoin_session_store.insert_or_update(session).await?; + }, + ReceiverSessionOutcome::FallbackBroadcasted => { + log_info!(self.logger, "Payjoin failed. Fallback transaction was broadcasted."); + session.status = PayjoinStatus::Failed; + session.resolution_txid = session.fallback_tx().map(|tx| tx.compute_txid()); + + self.payjoin_session_store.insert_or_update(session).await?; + }, + ReceiverSessionOutcome::Aborted => { + log_info!(self.logger, "Payjoin session was aborted."); + self.close_session_with_fallback(&mut session, None).await; + }, + ReceiverSessionOutcome::Unrecognized(txid) => { + log_error!( + self.logger, + "Payjoin session {} was settled by an unrecognized transaction {}.", + session_id, + txid + ); + session.status = PayjoinStatus::Failed; + session.resolution_txid = Some(txid); + + self.payjoin_session_store.insert_or_update(session).await?; + }, + } + Ok(()) + } + + pub(crate) async fn resume_payjoin_sessions( + &self, mut stop_receiver: tokio::sync::watch::Receiver<()>, + ) -> Result<(), Error> { + let now = Instant::now(); + let backing_off: HashSet = { + let retry_at = self.session_retry_at.lock().expect("lock"); + retry_at.iter().filter(|(_, at)| now < **at).map(|(id, _)| *id).collect() + }; + + let recv_session_ids = self + .payjoin_session_store + .list_filter(|p| { + matches!(p.kind, PayjoinSessionKind::Receive) + && p.status == PayjoinStatus::Active + && !backing_off.contains(&p.session_id) + }) + .await + .into_iter() + .map(|s| s.session_id) + .collect::>(); + + if recv_session_ids.is_empty() { + log_debug!(self.logger, "No sessions to resume."); + return Ok(()); + } + + let mut join_set: tokio::task::JoinSet> = tokio::task::JoinSet::new(); + + // Process receiver sessions + for session_id in recv_session_ids { + let self_clone = self.clone(); + // Create a persister for this session + let recv_persister = match KVStorePayjoinReceiverPersister::from_session( + session_id, + Arc::clone(&self.payjoin_session_store), + ) + .await + { + Ok(p) => p, + Err(e) => { + log_error!( + self.logger, + "Failed to create persister for session {:?}: {:?}", + session_id, + e + ); + self.session_retry_at + .lock() + .expect("lock") + .insert(session_id, Instant::now() + PAYJOIN_RETRY_DELAY); + continue; + }, + }; + + match replay_receiver_event_log_async(&recv_persister).await { + Ok((receiver_state, _)) => { + join_set.spawn(async move { + let res = self_clone + .process_receiver_session(receiver_state, &recv_persister) + .await; + { + let mut retry_at = self_clone.session_retry_at.lock().expect("lock"); + if res.is_err() { + retry_at.insert(session_id, Instant::now() + PAYJOIN_RETRY_DELAY); + } else { + retry_at.remove(&session_id); + } + } + res + }); + }, + Err(e) if e.is_expired() => match recv_persister.get_session().await { + Ok(mut session) => { + self.close_session_with_fallback(&mut session, e.expiry_fallback_tx()).await + }, + Err(err) => { + log_error!( + self.logger, + "Failed to close expired receiver session {session_id}: {err:?}" + ); + }, + }, + Err(e) => { + log_error!( + self.logger, + "An error {:?} occurred while replaying receiver session", + e + ); + match self.payjoin_session_store.get(&session_id).await { + Ok(Some(mut session)) => { + self.close_session_with_fallback(&mut session, None).await; + }, + Ok(None) => { + log_error!( + self.logger, + "Payjoin session {} disappeared before it could be closed.", + session_id + ); + }, + Err(e) => { + log_error!( + self.logger, + "Failed to read payjoin session {} while closing it: {:?}", + session_id, + e + ); + }, + } + }, + } + } + + tokio::select! { + _ = async { + while let Some(result) = join_set.join_next().await { + match result { + Ok(Ok(())) => { + log_debug!(self.logger, "A payjoin session task finished."); + }, + Ok(Err(e)) => { + log_error!(self.logger, "A payjoin session failed: {:?}", e); + }, + Err(e) => { + log_error!(self.logger, "A payjoin session task panicked: {:?}", e); + }, + } + } + } => { + log_debug!(self.logger, "All payjoin resumed sessions completed."); + } + _ = stop_receiver.changed() => { + join_set.abort_all(); + log_info!(self.logger, "Resumed payjoin sessions were interrupted."); + } + } + Ok(()) + } + + /// Closes a session whose payjoin didn't complete and broadcasts its fallback transaction. + /// + /// The broadcast queue doesn't survive a restart, so the session is persisted as + /// [`PayjoinStatus::FallbackPending`] with its fallback before the fallback is queued, and + /// [`Self::rebroadcast_pending_fallbacks`] keeps broadcasting it until it resolves. + async fn close_session_with_fallback( + &self, session: &mut PayjoinSession, fallback_tx: Option<&Transaction>, + ) { + // Keep an earlier timestamp if payjoin's `close()` already ran + session.completed_at.get_or_insert_with(|| { + SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or(Duration::from_secs(0)).as_secs() + }); + + let fallback_tx = fallback_tx.cloned().or_else(|| session.fallback_tx().cloned()); + + if let Some(fallback_tx) = &fallback_tx { + session.set_fallback_tx(fallback_tx.clone()); + session.status = PayjoinStatus::FallbackPending; + } else { + log_warn!( + self.logger, + "Payjoin session {} missing fallback transaction; closing as Failed without broadcast.", + session.session_id + ); + session.status = PayjoinStatus::Failed; + } + + if let Err(close_err) = self.payjoin_session_store.insert_or_update(session.clone()).await { + log_error!( + self.logger, + "Failed to close receiver session {}: {:?}", + session.session_id, + close_err + ); + } else { + log_info!(self.logger, "Closed failed receiver session: {}", session.session_id); + } + + // Broadcast even if persisting failed: a broadcast that may not be retried beats none. + if let Some(fallback_tx) = fallback_tx { + self.broadcaster.broadcast(fallback_tx); + } + } + + /// Rebroadcasts the fallback transaction of every [`PayjoinStatus::FallbackPending`] session + /// once per chain tip, and resolves a session once the wallet sees its fallback, or a + /// transaction double-spending it, confirmed through [`ANTI_REORG_DELAY`]. + /// + /// Like the wallet's handling of its own unconfirmed transactions, this runs on chain tip + /// changes, and its first pass after startup rebroadcasts what a restart dropped from the + /// broadcast queue. + pub(crate) async fn rebroadcast_pending_fallbacks(&self) { + // Compared by hash, so a reorg replacing the tip at the same height counts as a change. + let tip = self.wallet.best_block_hash(); + { + let mut last_tip = self.fallback_rebroadcast_tip.lock().expect("lock"); + if *last_tip == Some(tip) { + return; + } + *last_tip = Some(tip); + } + + let pending_sessions = self + .payjoin_session_store + .list_filter(|s| s.status == PayjoinStatus::FallbackPending) + .await; + + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or(Duration::from_secs(0)) + .as_secs(); + + for session in pending_sessions { + let session_id = session.session_id; + let Some(fallback_tx) = session.fallback_tx() else { + log_warn!( + self.logger, + "Payjoin session {} is pending a fallback it doesn't have; marking it Failed.", + session_id + ); + self.resolve_pending_fallback(session_id, PayjoinStatus::Failed, None).await; + continue; + }; + let fallback_txid = fallback_tx.compute_txid(); + + match self.wallet.payjoin_fallback_status(fallback_tx) { + PayjoinFallbackStatus::Confirmed => { + log_info!( + self.logger, + "Fallback transaction {} of payjoin session {} confirmed.", + fallback_txid, + session_id + ); + self.forget_spent_sender_inputs(fallback_tx, fallback_tx).await; + // A payjoin seen before the session expired was tagged on the payment, which + // wallet sync then moved to the fallback that replaced it. + if let Err(e) = self.wallet.unclassify_payjoin(fallback_txid).await { + log_error!( + self.logger, + "Failed to clear the payjoin classification of fallback transaction {}: {:?}. Will retry on the next chain tip.", + fallback_txid, + e + ); + continue; + } + self.resolve_pending_fallback(session_id, PayjoinStatus::Failed, Some(fallback_txid)) + .await; + }, + // The session expired before `settle_session` could close it, but the payjoin + // confirmed anyway. + PayjoinFallbackStatus::Conflicted(winner) if session.is_payjoin_tx(&winner) => { + let winner_txid = winner.compute_txid(); + log_info!( + self.logger, + "Payjoin session {} completed: payjoin transaction {} confirmed after the session expired.", + session_id, + winner_txid + ); + self.forget_spent_sender_inputs(&winner, fallback_tx).await; + // `settle_session` only tags a payjoin it saw before the session expired. + if let Err(e) = self.wallet.classify_payjoin(winner_txid, Some(&winner)).await + { + log_error!( + self.logger, + "Failed to classify payjoin transaction {}: {:?}. Will retry on the next chain tip.", + winner_txid, + e + ); + continue; + } + self.resolve_pending_fallback(session_id, PayjoinStatus::Completed, Some(winner_txid)) + .await; + }, + PayjoinFallbackStatus::Conflicted(winner) => { + log_info!( + self.logger, + "Fallback transaction {} of payjoin session {} was double-spent by {}.", + fallback_txid, + session_id, + winner.compute_txid() + ); + self.forget_spent_sender_inputs(&winner, fallback_tx).await; + self.resolve_pending_fallback( + session_id, + PayjoinStatus::Failed, + Some(winner.compute_txid()), + ) + .await; + }, + PayjoinFallbackStatus::Unresolved => { + let closed_at = session.completed_at.unwrap_or(session.latest_update_timestamp); + if now.saturating_sub(closed_at) > PAYJOIN_FALLBACK_REBROADCAST_TIMEOUT_SECS { + log_warn!( + self.logger, + "Giving up on fallback transaction {} of payjoin session {}: not confirmed after {}s.", + fallback_txid, + session_id, + PAYJOIN_FALLBACK_REBROADCAST_TIMEOUT_SECS + ); + self.resolve_pending_fallback(session_id, PayjoinStatus::Failed, None).await; + } else { + log_debug!( + self.logger, + "Rebroadcasting fallback transaction {} of payjoin session {}.", + fallback_txid, + session_id + ); + self.broadcaster.broadcast(fallback_tx.clone()); + } + }, + } + } + } + + /// Forgets the seen sender inputs, which `fallback_tx` spends, that `winner` spends, now that + /// it's confirmed through [`ANTI_REORG_DELAY`]. An unrecognized `winner` may spend only some of + /// them, and the rest can still be reused to probe us. + /// + /// Best effort: [`Self::cleanup_old_sessions`] forgets what this misses after + /// [`PAYJOIN_SEEN_INPUT_RETENTION_SECS`]. + async fn forget_spent_sender_inputs(&self, winner: &Transaction, fallback_tx: &Transaction) { + let spent = fallback_tx + .input + .iter() + .map(|txin| txin.previous_output) + .filter(|sender| winner.input.iter().any(|txin| txin.previous_output == *sender)) + .collect::>(); + if let Err(e) = forget_seen_inputs(&self.payjoin_seen_inputs_store, spent).await { + log_warn!( + self.logger, + "Failed to forget the payjoin sender inputs spent by {}: {:?}", + winner.compute_txid(), + e + ); + } + } + + /// Moves a [`PayjoinStatus::FallbackPending`] session to `status`, ending the rebroadcast of + /// its fallback, and records `resolution_txid` as what settled it. + async fn resolve_pending_fallback( + &self, session_id: PaymentId, status: PayjoinStatus, resolution_txid: Option, + ) { + let res = self + .payjoin_session_store + .mutate(&session_id, |existing| { + let mut session = existing?.clone(); + (session.status == PayjoinStatus::FallbackPending).then(|| { + session.status = status; + session.resolution_txid = resolution_txid; + session + }) + }) + .await; + if let Err(e) = res { + log_error!( + self.logger, + "Failed to mark payjoin session {} as {:?}: {:?}. Will retry on the next chain tip.", + session_id, + status, + e + ); + } + } + + /// Cleans up old payjoin sessions that are completed or failed. + /// Sessions older than `PAYJOIN_SESSION_CLEANUP_AGE_SECS` will be removed. + pub(crate) async fn cleanup_old_sessions(&self) -> Result<(), Error> { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or(std::time::Duration::from_secs(0)) + .as_secs(); + + match prune_seen_inputs( + &self.payjoin_seen_inputs_store, + now, + PAYJOIN_SEEN_INPUT_RETENTION_SECS, + ) + .await + { + Ok(0) => {}, + Ok(pruned) => { + log_info!(self.logger, "Forgot {} old payjoin sender inputs", pruned); + }, + Err(e) => { + log_error!(self.logger, "Failed to forget old payjoin sender inputs: {:?}", e); + }, + } + + let sessions_to_remove: Vec = self + .payjoin_session_store + .list_filter(|s| { + let is_terminal = + s.status == PayjoinStatus::Completed || s.status == PayjoinStatus::Failed; + let completed_at = s.completed_at.unwrap_or(s.latest_update_timestamp); + is_terminal && now.saturating_sub(completed_at) > PAYJOIN_SESSION_CLEANUP_AGE_SECS + }) + .await + .into_iter() + .map(|s| s.session_id) + .collect(); + + if sessions_to_remove.is_empty() { + return Ok(()); + } + + log_info!(self.logger, "Cleaning up {} old payjoin sessions", sessions_to_remove.len()); + + for session_id in sessions_to_remove { + if let Err(e) = self.payjoin_session_store.remove(&session_id).await { + log_error!( + self.logger, + "Failed to remove old payjoin session {:?}: {:?}", + session_id, + e + ); + } + self.session_retry_at.lock().expect("lock").remove(&session_id); + } + + Ok(()) + } +} + +#[cfg(all(test, feature = "chain-esplora"))] +mod tests { + use std::sync::atomic::{AtomicU8, Ordering}; + + use bitcoin::absolute::LockTime; + use bitcoin::hashes::Hash; + use bitcoin::transaction::Version; + use bitcoin::{ + Address, Network, OutPoint, Psbt, ScriptBuf, Sequence, TxOut, WPubkeyHash, Witness, + }; + use payjoin::persist::AsyncSessionPersister; + use payjoin::receive::v2::SessionEvent; + use serde_json::json; + + use super::*; + use crate::config::EsploraSyncConfig; + use crate::data_store::KeepAllEntries; + use crate::io::test_utils::InMemoryStore; + use crate::payment::payjoin::PayjoinSessionStatus; + use crate::payment::store::TransactionType; + use crate::types::{DynStore, DynStoreWrapper}; + use crate::wallet::tests::{ + insert_confirmed_tx, insert_unconfirmed_tx, new_test_wallet, observe_confirmed, + observe_unconfirmed, onchain_txid, record_of, set_chain_tip, tx_spending, tx_type_of, + }; + use crate::{NodeMetrics, PersistedNodeMetrics}; + + // Keys of a payjoin receiver session, from rust-payjoin's fuzzing seeds. Nothing in these tests + // encrypts with them. + const OHTTP_KEYS: [u8; 74] = [ + 1, 0, 22, 4, 49, 201, 65, 129, 251, 247, 128, 36, 159, 34, 170, 43, 131, 131, 10, 85, 25, + 245, 236, 35, 252, 37, 128, 98, 22, 235, 48, 68, 122, 8, 134, 133, 12, 23, 164, 215, 191, + 143, 99, 200, 11, 214, 16, 10, 31, 15, 91, 223, 101, 248, 218, 98, 90, 235, 190, 123, 14, + 75, 237, 98, 32, 13, 77, 94, 0, 4, 0, 1, 0, 3, + ]; + const RECEIVER_SECRET_KEY: [u8; 32] = [ + 55, 181, 82, 181, 118, 112, 72, 22, 165, 165, 27, 49, 174, 138, 173, 154, 94, 222, 82, 73, + 223, 101, 59, 62, 77, 184, 180, 205, 246, 246, 71, 92, + ]; + const RECEIVER_PUBLIC_KEY: [u8; 65] = [ + 4, 169, 112, 179, 223, 102, 152, 248, 70, 179, 203, 202, 47, 218, 92, 121, 173, 239, 35, + 126, 66, 223, 96, 202, 36, 252, 93, 204, 223, 174, 107, 245, 243, 121, 135, 94, 243, 11, + 133, 76, 46, 112, 47, 231, 239, 225, 227, 244, 123, 81, 171, 166, 150, 132, 192, 70, 169, + 147, 114, 34, 202, 177, 177, 11, 236, + ]; + const SENDER_REPLY_KEY: [u8; 65] = [ + 4, 194, 221, 118, 65, 156, 207, 82, 35, 217, 201, 43, 116, 24, 169, 42, 61, 39, 244, 255, + 112, 83, 209, 162, 36, 150, 230, 77, 40, 133, 173, 247, 186, 16, 202, 172, 58, 122, 210, + 166, 77, 90, 183, 98, 94, 37, 82, 127, 92, 242, 127, 14, 208, 130, 137, 57, 186, 17, 229, + 87, 40, 223, 13, 196, 243, + ]; + + /// An expiration far enough out that sessions never expire mid-test (2100-01-01). + const NEVER_EXPIRES: u64 = 4_102_444_800; + + /// What the sender pays us, out of each 200 000 sat input of theirs. + const PAYMENT_SATS: u64 = 100_000; + const SENDER_INPUT_SATS: u64 = 200_000; + + struct Harness { + manager: PayjoinManager, + wallet: Arc, + broadcaster: Arc, + session_store: Arc, + } + + /// A manager over a test wallet holding one confirmed UTXO, at chain tip 10, to contribute. + async fn harness() -> Harness { + let store: Arc = Arc::new(DynStoreWrapper(InMemoryStore::new())); + let wallet = new_test_wallet(Arc::clone(&store), false).await; + let funding = tx_spending(&wallet, outpoint(0xf0, 0)); + insert_confirmed_tx(&wallet, funding, 1); + set_chain_tip(&wallet, 10); + + let logger = Arc::new(Logger::new_log_facade()); + let mut config = Config::default(); + config.network = Network::Regtest; + // Nothing listens on the relay, so a session that gets to posting fails to. + config.payjoin_config = Some(PayjoinConfig { + payjoin_directory: "https://example.com".to_string(), + ohttp_relays: vec!["http://127.0.0.1:1".to_string()], + }); + let config = Arc::new(config); + let fee_estimator = Arc::new(OnchainFeeEstimator::new()); + let broadcaster = Arc::new(Broadcaster::new(Arc::clone(&logger))); + // Only consulted for the broadcast suitability check, which these tests record directly. + let (chain_source, _) = ChainSource::new_esplora( + "http://localhost:1".to_string(), + HashMap::new(), + EsploraSyncConfig::default(), + Arc::clone(&fee_estimator), + Arc::clone(&broadcaster), + Arc::clone(&store), + Arc::clone(&config), + Arc::clone(&logger), + Arc::new(PersistedNodeMetrics::new(NodeMetrics::default())), + ) + .unwrap(); + let session_store = Arc::new(PayjoinSessionStore::new( + Vec::new(), + KeepAllEntries, + "payjoin_sessions".to_string(), + String::new(), + Arc::clone(&store), + Arc::clone(&logger), + )); + let seen_inputs_store = Arc::new(PayjoinSeenInputsStore::new( + Vec::new(), + KeepAllEntries, + "payjoin_seen_inputs".to_string(), + String::new(), + Arc::clone(&store), + Arc::clone(&logger), + )); + let manager = PayjoinManager::new( + Arc::clone(&session_store), + seen_inputs_store, + logger, + config, + Arc::clone(&wallet), + fee_estimator, + Arc::new(chain_source), + Arc::clone(&broadcaster), + ); + Harness { manager, wallet, broadcaster, session_store } + } + + fn outpoint(byte: u8, vout: u32) -> OutPoint { + OutPoint { txid: Txid::from_byte_array([byte; 32]), vout } + } + + fn sender_script() -> ScriptBuf { + ScriptBuf::new_p2wpkh(&WPubkeyHash::from_byte_array([7; 20])) + } + + fn now_secs() -> u64 { + SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() + } + + /// The sender's original transaction, paying us [`PAYMENT_SATS`] from `sender_inputs`, as a + /// finalized PSBT. Its signatures are placeholders: the receiver doesn't verify them. + fn original_psbt(address: &Address, sender_inputs: &[OutPoint]) -> Psbt { + let input_sats = SENDER_INPUT_SATS * sender_inputs.len() as u64; + let fee_sats = 1_000 * sender_inputs.len() as u64; + let tx = Transaction { + version: Version::TWO, + lock_time: LockTime::ZERO, + input: sender_inputs + .iter() + .map(|previous_output| TxIn { + previous_output: *previous_output, + sequence: Sequence::ENABLE_LOCKTIME_NO_RBF, + ..Default::default() + }) + .collect(), + output: vec![ + TxOut { + value: Amount::from_sat(PAYMENT_SATS), + script_pubkey: address.script_pubkey(), + }, + TxOut { + value: Amount::from_sat(input_sats - PAYMENT_SATS - fee_sats), + script_pubkey: sender_script(), + }, + ], + }; + let mut psbt = Psbt::from_unsigned_tx(tx).unwrap(); + for input in psbt.inputs.iter_mut() { + input.witness_utxo = Some(TxOut { + value: Amount::from_sat(SENDER_INPUT_SATS), + script_pubkey: sender_script(), + }); + input.final_script_witness = Some(Witness::from_slice(&[vec![0x30; 72], vec![2; 33]])); + } + psbt + } + + /// `tx` without its witnesses, as the wallet test helpers that let the wallet see a + /// transaction in the mempool take it: they sign its spends of the wallet's outputs anew, + /// which leaves its txid unchanged. + fn without_witnesses(tx: &Transaction) -> Transaction { + let mut tx = tx.clone(); + for txin in &mut tx.input { + txin.witness = Witness::new(); + } + tx + } + + fn event(value: serde_json::Value) -> SessionEvent { + serde_json::from_value(value).unwrap() + } + + /// An event without data, e.g. `CheckedBroadcastSuitability()`. + fn unit_event(name: &str) -> SessionEvent { + serde_json::from_str(&format!("{{\"{}\":[]}}", name)).unwrap() + } + + fn created_event(address: &Address, expiration: u64) -> SessionEvent { + event(json!({ "Created": { + "address": address.to_string(), + "directory": "https://example.com/", + "ohttp_keys": OHTTP_KEYS.to_vec(), + "expiration": expiration, + "amount": null, + "receiver_key": [RECEIVER_SECRET_KEY.to_vec(), RECEIVER_PUBLIC_KEY.to_vec()], + "reply_key": null, + // 100 sat/vB, so the fee for the input we contribute is never capped. + "max_fee_rate": 25_000, + }})) + } + + fn retrieved_original_event(original: &Psbt) -> SessionEvent { + event(json!({ "RetrievedOriginalPayload": { + "original": { + "psbt": original, + "params": { + "v": 2, + "output_substitution": "Enabled", + "additional_fee_contribution": null, + "min_fee_rate": 250, + }, + }, + "reply_key": SENDER_REPLY_KEY.to_vec(), + }})) + } + + /// A receive session the sender sent its original transaction to. + struct TestSession { + session_id: PaymentId, + persister: KVStorePayjoinReceiverPersister, + fallback: Transaction, + } + + fn new_session_id() -> PaymentId { + static NEXT: AtomicU8 = AtomicU8::new(1); + PaymentId([NEXT.fetch_add(1, Ordering::Relaxed); 32]) + } + + /// Creates a session paying to `address`, with the URI and amount + /// [`PayjoinManager::receive_payjoin`] records, which a session needs to be listed. + async fn created_session( + h: &Harness, address: &Address, expiration: u64, + ) -> (PaymentId, KVStorePayjoinReceiverPersister) { + let session_id = new_session_id(); + let persister = + KVStorePayjoinReceiverPersister::new(session_id, Arc::clone(&h.session_store)); + persister.save_event(created_event(address, expiration)).await.unwrap(); + let mut session = persister.get_session().await.unwrap(); + session.uri = Some(format!("bitcoin:{}?amount=0.001", address)); + session.amount_sats = Some(PAYMENT_SATS); + h.session_store.insert_or_update(session).await.unwrap(); + (session_id, persister) + } + + /// A session still waiting for the sender. + async fn initialized_session(h: &Harness) -> (PaymentId, KVStorePayjoinReceiverPersister) { + let address = h.wallet.get_new_address().await.unwrap(); + created_session(h, &address, NEVER_EXPIRES).await + } + + /// A session that received an original spending `sender_inputs` and passed the broadcast + /// suitability check, so it's in [`ReceiveSession::MaybeInputsOwned`], with its fallback + /// recorded as [`PayjoinManager::check_original_payload`] does. + async fn session_with_original( + h: &Harness, sender_inputs: &[OutPoint], expiration: u64, + ) -> TestSession { + let address = h.wallet.get_new_address().await.unwrap(); + let (session_id, persister) = created_session(h, &address, expiration).await; + let original = original_psbt(&address, sender_inputs); + for event in + [retrieved_original_event(&original), unit_event("CheckedBroadcastSuitability")] + { + persister.save_event(event).await.unwrap(); + } + let fallback = original.extract_tx_unchecked_fee_rate(); + let mut session = persister.get_session().await.unwrap(); + session.set_fallback_tx(fallback.clone()); + h.session_store.insert_or_update(session).await.unwrap(); + TestSession { session_id, persister, fallback } + } + + async fn replay(persister: &KVStorePayjoinReceiverPersister) -> ReceiveSession { + replay_receiver_event_log_async(persister).await.unwrap().0 + } + + /// Takes a session from [`ReceiveSession::MaybeInputsOwned`] through the manager's steps to + /// the proposal, then records it as posted, with its txid as + /// [`PayjoinManager::send_payjoin_proposal`] records it, so it's in [`ReceiveSession::Monitor`]. + /// Returns the payjoin transaction as the sender would broadcast it. + async fn propose(h: &Harness, session: &TestSession) -> Transaction { + let persister = &session.persister; + let mut state = replay(persister).await; + assert!(matches!(state, ReceiveSession::MaybeInputsOwned(_))); + let payjoin_psbt = loop { + state = match state { + ReceiveSession::MaybeInputsOwned(p) => { + h.manager.check_inputs_not_owned(p, persister).await.unwrap() + }, + ReceiveSession::MaybeInputsSeen(p) => { + h.manager.check_no_inputs_seen_before(p, persister).await.unwrap() + }, + ReceiveSession::OutputsUnknown(p) => { + h.manager.identify_receiver_outputs(p, persister).await.unwrap() + }, + ReceiveSession::WantsOutputs(p) => { + h.manager.commit_outputs(p, persister).await.unwrap() + }, + ReceiveSession::WantsInputs(p) => { + h.manager.contribute_inputs(p, persister).await.unwrap() + }, + ReceiveSession::WantsFeeRange(p) => { + h.manager.apply_fee_range(p, persister).await.unwrap() + }, + ReceiveSession::ProvisionalProposal(p) => { + h.manager.finalize_proposal(p, persister).await.unwrap() + }, + ReceiveSession::PayjoinProposal(p) => break p.psbt().clone(), + other => panic!("unexpected state {:?}", other), + }; + }; + let mut recorded = persister.get_session().await.unwrap(); + recorded.payjoin_txid = Some(payjoin_psbt.unsigned_tx.compute_txid()); + h.session_store.insert_or_update(recorded).await.unwrap(); + persister.save_event(unit_event("PostedPayjoinProposal")).await.unwrap(); + assert!(matches!(replay(persister).await, ReceiveSession::Monitor(_))); + payjoin_psbt.extract_tx_unchecked_fee_rate() + } + + /// The status the session is listed with. + async fn status(h: &Harness, session_id: PaymentId) -> PayjoinSessionStatus { + h.manager.session(session_id).await.unwrap().expect("listed").status + } + + /// Resumes the session as the resume task does. + async fn resume(h: &Harness, persister: &KVStorePayjoinReceiverPersister) -> Result<(), Error> { + let state = replay(persister).await; + h.manager.process_receiver_session(state, persister).await + } + + /// The transactions queued for broadcast. + async fn broadcast_txs(h: &Harness) -> Vec { + let mut txs = Vec::new(); + while let Ok(package) = + tokio::time::timeout(Duration::from_millis(10), h.broadcaster.next_package()).await + { + txs.extend(package.into_sorted_transactions().into_inner()); + } + txs + } + + async fn is_seen(h: &Harness, input: OutPoint) -> bool { + h.manager.payjoin_seen_inputs_store.get(&input).await.unwrap().is_some() + } + + fn payment_id(txid: Txid) -> PaymentId { + PaymentId(txid.to_byte_array()) + } + + #[tokio::test] + async fn payjoin_settles_once_buried() { + let h = harness().await; + let session = session_with_original(&h, &[outpoint(1, 0)], NEVER_EXPIRES).await; + let payjoin = propose(&h, &session).await; + let payjoin_txid = payjoin.compute_txid(); + // We contributed an input of ours. + assert_eq!(payjoin.input.len(), 2); + + // Confirmed but not yet buried: tagged, but the session stays open. + insert_confirmed_tx(&h.wallet, payjoin, 11); + set_chain_tip(&h.wallet, 11 + ANTI_REORG_DELAY - 2); + resume(&h, &session.persister).await.unwrap(); + assert_eq!(status(&h, session.session_id).await, PayjoinSessionStatus::Active); + let payment = record_of(&h.wallet, &payment_id(payjoin_txid)).await.unwrap(); + assert_eq!(tx_type_of(&payment), Some(TransactionType::Payjoin)); + + set_chain_tip(&h.wallet, 11 + ANTI_REORG_DELAY - 1); + resume(&h, &session.persister).await.unwrap(); + assert_eq!( + status(&h, session.session_id).await, + PayjoinSessionStatus::Completed { txid: Some(payjoin_txid) } + ); + assert!(matches!( + replay(&session.persister).await, + ReceiveSession::Closed(ReceiverSessionOutcome::PayjoinProposalSent) + )); + // The sender's input is spent past the reorg bar, so it's forgotten. + assert!(!is_seen(&h, outpoint(1, 0)).await); + assert!(broadcast_txs(&h).await.is_empty()); + } + + #[tokio::test] + async fn proposal_that_cant_be_posted_is_kept_with_its_txid() { + let h = harness().await; + let session = session_with_original(&h, &[outpoint(1, 0)], NEVER_EXPIRES).await; + + // The relay is unreachable, so the session fails at posting the proposal it got to. + assert!(resume(&h, &session.persister).await.is_err()); + let ReceiveSession::PayjoinProposal(proposal) = replay(&session.persister).await else { + panic!("expected the proposal to be kept for a retry"); + }; + assert_eq!(status(&h, session.session_id).await, PayjoinSessionStatus::Active); + assert!(is_seen(&h, outpoint(1, 0)).await); + // Recorded before posting, in case the session expires before it settles. + let recorded = h.session_store.get(&session.session_id).await.unwrap().unwrap(); + assert_eq!(recorded.payjoin_txid, Some(proposal.psbt().unsigned_tx.compute_txid())); + } + + #[tokio::test] + async fn session_pauses_while_the_senders_inputs_are_spent_shallowly() { + let h = harness().await; + let session = session_with_original(&h, &[outpoint(1, 0)], NEVER_EXPIRES).await; + // The sender gave up on the payjoin and broadcast its original. + insert_unconfirmed_tx(&h.wallet, without_witnesses(&session.fallback)); + + resume(&h, &session.persister).await.unwrap(); + // Nothing advanced: a proposal could no longer confirm. + assert!(matches!(replay(&session.persister).await, ReceiveSession::MaybeInputsOwned(_))); + assert_eq!(status(&h, session.session_id).await, PayjoinSessionStatus::Active); + } + + #[tokio::test] + async fn buried_fallback_fails_the_session() { + let h = harness().await; + let session = session_with_original(&h, &[outpoint(1, 0)], NEVER_EXPIRES).await; + propose(&h, &session).await; + let fallback_txid = session.fallback.compute_txid(); + + insert_confirmed_tx(&h.wallet, session.fallback.clone(), 11); + set_chain_tip(&h.wallet, 11 + ANTI_REORG_DELAY - 1); + resume(&h, &session.persister).await.unwrap(); + + assert_eq!( + status(&h, session.session_id).await, + PayjoinSessionStatus::Failed { txid: Some(fallback_txid) } + ); + assert!(matches!(replay(&session.persister).await, ReceiveSession::Closed(_))); + let payment = record_of(&h.wallet, &payment_id(fallback_txid)).await; + assert!(payment.map_or(true, |payment| tx_type_of(&payment).is_none())); + assert!(!is_seen(&h, outpoint(1, 0)).await); + assert!(broadcast_txs(&h).await.is_empty()); + } + + #[tokio::test] + async fn unrecognized_spend_forgets_only_the_inputs_it_spends() { + let h = harness().await; + let (spent, unspent) = (outpoint(1, 0), outpoint(2, 0)); + let session = session_with_original(&h, &[spent, unspent], NEVER_EXPIRES).await; + propose(&h, &session).await; + + // The sender double-spent one of its inputs to us in some other transaction. + let double_spend = tx_spending(&h.wallet, spent); + insert_confirmed_tx(&h.wallet, double_spend.clone(), 11); + set_chain_tip(&h.wallet, 11 + ANTI_REORG_DELAY - 1); + resume(&h, &session.persister).await.unwrap(); + + assert_eq!( + status(&h, session.session_id).await, + PayjoinSessionStatus::Failed { txid: Some(double_spend.compute_txid()) } + ); + assert!(!is_seen(&h, spent).await); + assert!(is_seen(&h, unspent).await); + } + + /// The payjoin was seen and tagged, but the fallback confirmed in its place, e.g. after a + /// reorg. Wallet sync moves the payjoin's record to the fallback, and settling removes the + /// tag, so the payment is recorded once, untagged. + #[tokio::test] + async fn fallback_replacing_the_payjoin_takes_over_its_payment_untagged() { + let h = harness().await; + let session = session_with_original(&h, &[outpoint(1, 0)], NEVER_EXPIRES).await; + let payjoin = propose(&h, &session).await; + let payjoin_id = payment_id(payjoin.compute_txid()); + let fallback_txid = session.fallback.compute_txid(); + + observe_unconfirmed(&h.wallet, &without_witnesses(&payjoin)).await; + resume(&h, &session.persister).await.unwrap(); + let payment = record_of(&h.wallet, &payjoin_id).await.unwrap(); + assert_eq!(tx_type_of(&payment), Some(TransactionType::Payjoin)); + + observe_confirmed(&h.wallet, &session.fallback, 11, Some(&payjoin)).await; + set_chain_tip(&h.wallet, 11 + ANTI_REORG_DELAY - 1); + resume(&h, &session.persister).await.unwrap(); + + assert_eq!( + status(&h, session.session_id).await, + PayjoinSessionStatus::Failed { txid: Some(fallback_txid) } + ); + let payment = record_of(&h.wallet, &payjoin_id).await.unwrap(); + assert_eq!(onchain_txid(&payment), fallback_txid); + assert_eq!(tx_type_of(&payment), None); + assert!(record_of(&h.wallet, &payment_id(fallback_txid)).await.is_none()); + } + + #[tokio::test] + async fn cancelled_session_without_original_closes_without_broadcast() { + let h = harness().await; + let (session_id, persister) = initialized_session(&h).await; + + h.manager.cancel_session(session_id).await.unwrap(); + // Applied by the resume task, not by the request. + assert_eq!(status(&h, session_id).await, PayjoinSessionStatus::Active); + + resume(&h, &persister).await.unwrap(); + assert_eq!( + status(&h, session_id).await, + PayjoinSessionStatus::Cancelled { fallback_txid: None } + ); + assert!(matches!( + replay(&persister).await, + ReceiveSession::Closed(ReceiverSessionOutcome::Aborted) + )); + assert!(broadcast_txs(&h).await.is_empty()); + } + + #[tokio::test] + async fn cancelled_session_after_proposal_broadcasts_the_fallback() { + let h = harness().await; + let session = session_with_original(&h, &[outpoint(1, 0)], NEVER_EXPIRES).await; + propose(&h, &session).await; + + h.manager.cancel_session(session.session_id).await.unwrap(); + // Cancelling again is a no-op. + h.manager.cancel_session(session.session_id).await.unwrap(); + resume(&h, &session.persister).await.unwrap(); + + assert_eq!( + status(&h, session.session_id).await, + PayjoinSessionStatus::Cancelled { + fallback_txid: Some(session.fallback.compute_txid()) + } + ); + assert_eq!(broadcast_txs(&h).await, vec![session.fallback.clone()]); + assert!(matches!(replay(&session.persister).await, ReceiveSession::Closed(_))); + } + + #[tokio::test] + async fn cancel_is_refused_once_it_cant_change_the_outcome() { + let h = harness().await; + assert!(matches!( + h.manager.cancel_session(new_session_id()).await, + Err(Error::InvalidPaymentId) + )); + + // A spend of the sender's inputs was seen. + let session = session_with_original(&h, &[outpoint(1, 0)], NEVER_EXPIRES).await; + insert_unconfirmed_tx(&h.wallet, without_witnesses(&session.fallback)); + assert!(matches!( + h.manager.cancel_session(session.session_id).await, + Err(Error::PayjoinSessionNotCancellable) + )); + + // The session ended. + let session = session_with_original(&h, &[outpoint(2, 0)], NEVER_EXPIRES).await; + let payjoin = propose(&h, &session).await; + insert_confirmed_tx(&h.wallet, payjoin, 11); + set_chain_tip(&h.wallet, 11 + ANTI_REORG_DELAY - 1); + resume(&h, &session.persister).await.unwrap(); + assert!(matches!( + h.manager.cancel_session(session.session_id).await, + Err(Error::PayjoinSessionNotCancellable) + )); + } + + #[tokio::test] + async fn expired_session_rebroadcasts_its_fallback_until_buried() { + let h = harness().await; + // Expired in 2020. + let session = session_with_original(&h, &[outpoint(1, 0)], 1_600_000_000).await; + let fallback_txid = session.fallback.compute_txid(); + + let (_stop_sender, stop_receiver) = tokio::sync::watch::channel(()); + h.manager.resume_payjoin_sessions(stop_receiver).await.unwrap(); + assert_eq!( + status(&h, session.session_id).await, + PayjoinSessionStatus::FallbackPending { fallback_txid } + ); + assert_eq!(broadcast_txs(&h).await, vec![session.fallback.clone()]); + + // The first pass after startup rebroadcasts, and then once per chain tip. + h.manager.rebroadcast_pending_fallbacks().await; + assert_eq!(broadcast_txs(&h).await, vec![session.fallback.clone()]); + h.manager.rebroadcast_pending_fallbacks().await; + assert!(broadcast_txs(&h).await.is_empty()); + + insert_confirmed_tx(&h.wallet, session.fallback.clone(), 11); + set_chain_tip(&h.wallet, 11 + ANTI_REORG_DELAY - 1); + h.manager.rebroadcast_pending_fallbacks().await; + assert_eq!( + status(&h, session.session_id).await, + PayjoinSessionStatus::Failed { txid: Some(fallback_txid) } + ); + assert!(!is_seen(&h, outpoint(1, 0)).await); + assert!(broadcast_txs(&h).await.is_empty()); + } + + /// The session expired after the proposal was posted but before the sender broadcast the + /// payjoin, which then confirmed. `settle_session` never saw it, so recognizing it by the + /// txid recorded at posting is what completes the session and tags the payment. + #[tokio::test] + async fn expired_session_whose_payjoin_confirms_completes() { + let h = harness().await; + let expiration = now_secs() + 2; + let session = session_with_original(&h, &[outpoint(1, 0)], expiration).await; + let payjoin = propose(&h, &session).await; + let payjoin_txid = payjoin.compute_txid(); + while now_secs() <= expiration { + tokio::time::sleep(Duration::from_millis(200)).await; + } + + let (_stop_sender, stop_receiver) = tokio::sync::watch::channel(()); + h.manager.resume_payjoin_sessions(stop_receiver).await.unwrap(); + assert_eq!( + status(&h, session.session_id).await, + PayjoinSessionStatus::FallbackPending { fallback_txid: session.fallback.compute_txid() } + ); + assert_eq!(broadcast_txs(&h).await, vec![session.fallback.clone()]); + + observe_confirmed(&h.wallet, &payjoin, 11, None).await; + set_chain_tip(&h.wallet, 11 + ANTI_REORG_DELAY - 1); + h.manager.rebroadcast_pending_fallbacks().await; + + assert_eq!( + status(&h, session.session_id).await, + PayjoinSessionStatus::Completed { txid: Some(payjoin_txid) } + ); + let payment = record_of(&h.wallet, &payment_id(payjoin_txid)).await.unwrap(); + assert_eq!(tx_type_of(&payment), Some(TransactionType::Payjoin)); + assert!(!is_seen(&h, outpoint(1, 0)).await); + assert!(broadcast_txs(&h).await.is_empty()); + } + + /// Cancelled after the proposal was posted, so we broadcast the fallback, but the sender + /// broadcast the payjoin it had, which confirmed. Wallet sync moves the fallback's record to + /// the payjoin, which is tagged there, and the session completes despite the cancellation. + #[tokio::test] + async fn payjoin_beating_a_cancelled_sessions_fallback_completes_it() { + let h = harness().await; + let session = session_with_original(&h, &[outpoint(1, 0)], NEVER_EXPIRES).await; + let payjoin = propose(&h, &session).await; + let payjoin_txid = payjoin.compute_txid(); + let fallback_id = payment_id(session.fallback.compute_txid()); + + h.manager.cancel_session(session.session_id).await.unwrap(); + resume(&h, &session.persister).await.unwrap(); + assert_eq!(broadcast_txs(&h).await, vec![session.fallback.clone()]); + observe_unconfirmed(&h.wallet, &without_witnesses(&session.fallback)).await; + + observe_confirmed(&h.wallet, &payjoin, 11, Some(&session.fallback)).await; + set_chain_tip(&h.wallet, 11 + ANTI_REORG_DELAY - 1); + h.manager.rebroadcast_pending_fallbacks().await; + + assert_eq!( + status(&h, session.session_id).await, + PayjoinSessionStatus::Completed { txid: Some(payjoin_txid) } + ); + let payment = record_of(&h.wallet, &fallback_id).await.unwrap(); + assert_eq!(onchain_txid(&payment), payjoin_txid); + assert_eq!(tx_type_of(&payment), Some(TransactionType::Payjoin)); + assert!(record_of(&h.wallet, &payment_id(payjoin_txid)).await.is_none()); + assert!(!is_seen(&h, outpoint(1, 0)).await); + } + + #[tokio::test] + async fn cleanup_forgets_seen_inputs_past_retention() { + let h = harness().await; + let (old, recent) = (outpoint(1, 0), outpoint(2, 0)); + let now = now_secs(); + let store = &h.manager.payjoin_seen_inputs_store; + let first_seen = now - PAYJOIN_SEEN_INPUT_RETENTION_SECS - 1; + check_and_record_seen_input(store, old, new_session_id(), first_seen).await.unwrap(); + check_and_record_seen_input(store, recent, new_session_id(), now).await.unwrap(); + + h.manager.cleanup_old_sessions().await.unwrap(); + assert!(!is_seen(&h, old).await); + assert!(is_seen(&h, recent).await); + } +} diff --git a/src/payment/payjoin/mod.rs b/src/payment/payjoin/mod.rs new file mode 100644 index 0000000000..de9617c2f6 --- /dev/null +++ b/src/payment/payjoin/mod.rs @@ -0,0 +1,196 @@ +// This file is Copyright its original authors, visible in version control history. +// +// This file is licensed under the Apache License, Version 2.0 or the MIT license , at your option. You may not use this file except in +// accordance with one or both of these licenses. + +//! Holds a payment handler for sending and receiving Payjoin payments. + +pub(crate) mod manager; +pub(crate) mod payjoin_session; +pub(crate) mod persist; +pub(crate) mod seen_inputs; + +use std::sync::{Arc, RwLock}; + +use bitcoin::Txid; +use lightning::ln::channelmanager::PaymentId; +pub use manager::PayjoinReceiveSession; +pub use payjoin_session::PayjoinSessionKind; + +use crate::runtime::Runtime; +use crate::{error::Error, payment::payjoin::manager::PayjoinManager}; + +#[cfg(not(feature = "uniffi"))] +type FeeRate = bitcoin::FeeRate; +#[cfg(feature = "uniffi")] +type FeeRate = Arc; + +macro_rules! maybe_map_fee_rate_opt { + ($fee_rate_opt:expr) => {{ + #[cfg(not(feature = "uniffi"))] + { + $fee_rate_opt + } + #[cfg(feature = "uniffi")] + { + $fee_rate_opt.map(|f| *f) + } + }}; +} + +/// A payment handler allowing to receive [Payjoin] payments. +/// +/// Should be retrieved by calling [`Node::payjoin_payment`]. +/// +/// [Payjoin]: https://payjoin.org +/// [`Node::payjoin_payment`]: crate::Node::payjoin_payment +#[cfg_attr(feature = "uniffi", derive(uniffi::Object))] +pub struct PayjoinPayment { + /// `None` if no [`PayjoinConfig`] was set, in which case all methods fail. + /// + /// [`PayjoinConfig`]: crate::config::PayjoinConfig + manager: Option>, + runtime: Arc, + is_running: Arc>, +} + +impl PayjoinPayment { + pub(crate) fn new( + manager: Option>, runtime: Arc, is_running: Arc>, + ) -> Self { + Self { manager, runtime, is_running } + } +} + +#[cfg_attr(feature = "uniffi", uniffi::export)] +impl PayjoinPayment { + /// Opens a Payjoin receive session, returning the BIP 21 URI to share with the sender and + /// the identifier of the session. + /// + /// `fee_rate` caps what we are willing to pay for the input we contribute. It defaults to + /// the current on-chain fee estimate. The cap is fixed when the URI is created and the + /// session may last up to 24 hours, so if fees rise above it before the sender responds, + /// the payjoin is declined and the sender's original transaction pays instead. + /// + /// Returns [`Error::PayjoinNotConfigured`] if no [`PayjoinConfig`] was set. + /// + /// [`PayjoinConfig`]: crate::config::PayjoinConfig + pub async fn receive( + &self, amount_sats: u64, fee_rate: Option, + ) -> Result { + let manager = self.manager.as_ref().ok_or(Error::PayjoinNotConfigured)?; + + if !*self.is_running.read().expect("lock") { + return Err(Error::NotRunning); + } + + let fee_rate_opt = maybe_map_fee_rate_opt!(fee_rate); + manager.receive_payjoin(amount_sats, fee_rate_opt).await + } + + /// Retrieves the details of the session with the given id, as returned by [`Self::receive`]. + /// + /// Returns `Ok(None)` for an unknown session. A session that completed, failed or was + /// cancelled is forgotten a day after it ended, while the payment it settled into stays in + /// the payment store, found through the txid in its [`PayjoinSessionStatus`]. + /// + /// Returns [`Error::PayjoinNotConfigured`] if no [`PayjoinConfig`] was set. + /// + /// [`PayjoinConfig`]: crate::config::PayjoinConfig + pub fn payjoin_session( + &self, session_id: PaymentId, + ) -> Result, Error> { + let manager = self.manager.as_ref().ok_or(Error::PayjoinNotConfigured)?; + self.runtime.block_on(manager.session(session_id)) + } + + /// Retrieves the details of all known sessions. + /// + /// This lists the sessions in progress, and those that ended within the last day. The + /// payments sessions settled into are listed by [`Node::list_payments`]. + /// + /// Returns [`Error::PayjoinNotConfigured`] if no [`PayjoinConfig`] was set. + /// + /// [`PayjoinConfig`]: crate::config::PayjoinConfig + /// [`Node::list_payments`]: crate::Node::list_payments + pub fn list_payjoin_sessions(&self) -> Result, Error> { + let manager = self.manager.as_ref().ok_or(Error::PayjoinNotConfigured)?; + Ok(self.runtime.block_on(manager.list_sessions())) + } + + /// Cancels the session with the given id, as returned by [`Self::receive`]. + /// + /// The cancellation is applied in the background, so the session is reported as + /// [`PayjoinSessionStatus::Active`] until it is, and as [`PayjoinSessionStatus::Cancelled`] + /// afterwards. If the session already received the sender's original transaction, that + /// transaction is broadcast so that we still get paid. Cancelling a session again has no + /// further effect. + /// + /// Returns [`Error::InvalidPaymentId`] for an unknown session, and + /// [`Error::PayjoinSessionNotCancellable`] if the session already ended, or if a transaction + /// spending the sender's inputs was already seen, so that cancelling can't change how it + /// settles. + /// + /// Returns [`Error::PayjoinNotConfigured`] if no [`PayjoinConfig`] was set. + /// + /// [`PayjoinConfig`]: crate::config::PayjoinConfig + pub fn cancel_payjoin_session(&self, session_id: PaymentId) -> Result<(), Error> { + let manager = self.manager.as_ref().ok_or(Error::PayjoinNotConfigured)?; + self.runtime.block_on(manager.cancel_session(session_id)) + } +} + +/// The details of a Payjoin session, as returned by [`PayjoinPayment::payjoin_session`] and +/// [`PayjoinPayment::list_payjoin_sessions`]. +#[derive(Clone, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] +pub struct PayjoinSessionDetails { + /// The identifier of the session, as returned when it was created. + pub session_id: PaymentId, + /// Whether the session receives or sends a payment. + pub kind: PayjoinSessionKind, + /// The BIP 21 URI of the session. + pub uri: String, + /// The amount the session asks for. + pub amount_sats: u64, + /// Where the session stands. + pub status: PayjoinSessionStatus, + /// The timestamp, in seconds since start of the UNIX epoch, when the session was created. + pub created_at: u64, +} + +/// The status of a Payjoin session, as reported in [`PayjoinSessionDetails`]. +#[derive(Clone, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))] +pub enum PayjoinSessionStatus { + /// The session is waiting on the sender, or on a transaction spending the sender's inputs to + /// confirm. A session whose cancellation was requested stays active until it is applied. + Active, + /// The payjoin transaction confirmed and the session completed. + Completed { + /// The payjoin transaction, if known. It is only unknown for a session closed by an + /// outcome that doesn't name the transaction, which this node doesn't record. + txid: Option, + }, + /// The payjoin didn't complete, so the sender's fallback transaction pays instead. It is + /// rebroadcast until it, or another spend of the sender's inputs, confirms. + FallbackPending { + /// The sender's fallback transaction. + fallback_txid: Txid, + }, + /// The payjoin didn't complete. + Failed { + /// The transaction that settled the session: the sender's fallback, or another spend of + /// the sender's inputs. `None` if none was seen, e.g. because the session ended before + /// the sender sent its original transaction, or the fallback was given up on. + txid: Option, + }, + /// The session was cancelled through [`PayjoinPayment::cancel_payjoin_session`] and didn't complete. + Cancelled { + /// The sender's fallback transaction, if the session had received it. It is then + /// broadcast and rebroadcast until it, or another spend of the sender's inputs, confirms. + fallback_txid: Option, + }, +} diff --git a/src/payment/payjoin/payjoin_session.rs b/src/payment/payjoin/payjoin_session.rs new file mode 100644 index 0000000000..275cd4f5c6 --- /dev/null +++ b/src/payment/payjoin/payjoin_session.rs @@ -0,0 +1,478 @@ +// This file is Copyright its original authors, visible in version control history. +// +// This file is licensed under the Apache License, Version 2.0 or the MIT license , at your option. You may not use this file except in +// accordance with one or both of these licenses. + +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use bitcoin::{Transaction, Txid}; +use lightning::ln::channelmanager::PaymentId; +use lightning::{impl_writeable_tlv_based, impl_writeable_tlv_based_enum}; + +use crate::data_store::{StorableObject, StorableObjectUpdate, UpdatableObject}; +use crate::payment::payjoin::{PayjoinSessionDetails, PayjoinSessionStatus}; + +/// Represents a payjoin session with persisted events +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PayjoinSession { + /// Session identifier (uses PaymentId from PaymentDetails) + pub session_id: PaymentId, + + /// The kind of session. + pub kind: PayjoinSessionKind, + + /// The transaction to broadcast if the payjoin session fails or is aborted. + pub fallback_tx: Option, + + /// The txid of the payjoin proposal we sent, without the sender's signatures, once sent. + pub payjoin_txid: Option, + + /// The BIP 21 URI handed out for this session, once it was created. + pub uri: Option, + + /// The amount the session asks for, once it was created. + pub amount_sats: Option, + + /// The transaction that settled the session, once known: the payjoin, the fallback, or another + /// spend of the sender's inputs. + pub resolution_txid: Option, + + /// Whether the user asked to cancel the session. The resume task applies the request, so it + /// alone writes the session's event log. + /// + /// Only ever set through [`DataStore::mutate`], and left out of [`PayjoinSessionUpdate`], so a + /// write of a copy read before the request can't undo it. + /// + /// [`DataStore::mutate`]: crate::data_store::DataStore::mutate + pub cancel_requested: bool, + + /// The timestamp, in seconds since start of the UNIX epoch, when this session was created. + pub created_at: u64, + + /// Serialized session events + pub events: Vec, + + /// Current status of the session + pub status: PayjoinStatus, + + /// Unix timestamp of session completion (if completed) + pub completed_at: Option, + + /// The timestamp, in seconds since start of the UNIX epoch, when this entry was last updated. + pub latest_update_timestamp: u64, +} + +impl PayjoinSession { + pub fn new(session_id: PaymentId, kind: PayjoinSessionKind) -> Self { + let latest_update_timestamp = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or(Duration::from_secs(0)) + .as_secs(); + Self { + session_id, + kind, + fallback_tx: None, + payjoin_txid: None, + uri: None, + amount_sats: None, + resolution_txid: None, + cancel_requested: false, + created_at: latest_update_timestamp, + events: Vec::new(), + status: PayjoinStatus::Active, + completed_at: None, + latest_update_timestamp, + } + } + + /// The session as reported to the user, or `None` if its creation never completed, so its URI + /// was never handed out. + pub(crate) fn details(&self) -> Option { + Some(PayjoinSessionDetails { + session_id: self.session_id, + kind: self.kind.clone(), + uri: self.uri.clone()?, + amount_sats: self.amount_sats?, + status: self.user_status(), + created_at: self.created_at, + }) + } + + /// The session's status as reported to the user. + pub(crate) fn user_status(&self) -> PayjoinSessionStatus { + let fallback_txid = self.fallback_tx().map(|tx| tx.compute_txid()); + match self.status { + PayjoinStatus::Active => PayjoinSessionStatus::Active, + PayjoinStatus::Completed => { + PayjoinSessionStatus::Completed { txid: self.resolution_txid } + }, + PayjoinStatus::FallbackPending | PayjoinStatus::Failed if self.cancel_requested => { + PayjoinSessionStatus::Cancelled { fallback_txid } + }, + // A session only becomes pending a fallback it has. + PayjoinStatus::FallbackPending => match fallback_txid { + Some(fallback_txid) => PayjoinSessionStatus::FallbackPending { fallback_txid }, + None => PayjoinSessionStatus::Failed { txid: None }, + }, + PayjoinStatus::Failed => PayjoinSessionStatus::Failed { txid: self.resolution_txid }, + } + } + + /// Returns the fallback transaction to broadcast if the payjoin doesn't complete, if known. + pub(crate) fn fallback_tx(&self) -> Option<&Transaction> { + self.fallback_tx.as_ref() + } + + /// Records the fallback transaction to broadcast if the payjoin doesn't complete. + pub(crate) fn set_fallback_tx(&mut self, tx: Transaction) { + self.fallback_tx = Some(tx); + } + + /// Whether `tx` is the payjoin proposal we sent, as the sender signed and broadcast it. + /// + /// Compared without `script_sig`s, as [`ReceiveSession::classify_tx`] does: the sender's + /// signatures of non-SegWit inputs change the txid. Lets a session be settled once payjoin's + /// own session is gone, as it is once the session expired. + /// + /// [`ReceiveSession::classify_tx`]: payjoin::receive::v2::ReceiveSession::classify_tx + pub(crate) fn is_payjoin_tx(&self, tx: &Transaction) -> bool { + let Some(payjoin_txid) = self.payjoin_txid else { + return false; + }; + let mut unsigned_tx = tx.clone(); + for txin in &mut unsigned_tx.input { + txin.script_sig = bitcoin::ScriptBuf::new(); + } + unsigned_tx.compute_txid() == payjoin_txid + } +} + +impl_writeable_tlv_based!(PayjoinSession, { + (0, session_id, required), + (2, kind, required), + (4, fallback_tx, option), + (6, events, required_vec), + (8, status, required), + (10, completed_at, option), + (12, latest_update_timestamp, (default_value, 0u64)), + (14, payjoin_txid, option), + (16, uri, option), + (18, amount_sats, option), + (20, resolution_txid, option), + (22, cancel_requested, (default_value, false)), + (24, created_at, (default_value, 0u64)), +}); + +/// Whether a payjoin session receives or sends a payment. +#[derive(Clone, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))] +pub enum PayjoinSessionKind { + /// We are receiving a payjoin. + Receive, +} + +impl_writeable_tlv_based_enum!(PayjoinSessionKind, + (0, Receive) => {} +); + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub enum PayjoinStatus { + /// The session is active + Active, + /// The session has completed successfully + Completed, + /// The session has failed + Failed, + /// The payjoin didn't complete and the sender's fallback transaction is rebroadcast until it, + /// or a transaction double-spending it, confirms + FallbackPending, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SerializedSessionEvent { + /// Serialized event bytes. + pub event_bytes: Vec, + /// Unix timestamp of when the event occurred + pub created_at: u64, +} + +impl_writeable_tlv_based!(SerializedSessionEvent, { + (0, event_bytes, required), + (2, created_at, required), +}); + +impl_writeable_tlv_based_enum!(PayjoinStatus, + (0, Active) => {}, + (2, Completed) => {}, + (4, Failed) => {}, + (6, FallbackPending) => {} +); + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct PayjoinSessionUpdate { + pub session_id: PaymentId, + pub fallback_tx: Option>, + pub payjoin_txid: Option>, + pub uri: Option>, + pub amount_sats: Option>, + pub resolution_txid: Option>, + pub events: Option>, + pub status: Option, + pub completed_at: Option>, +} + +impl From<&PayjoinSession> for PayjoinSessionUpdate { + fn from(value: &PayjoinSession) -> Self { + Self { + session_id: value.session_id, + fallback_tx: Some(value.fallback_tx.clone()), + payjoin_txid: Some(value.payjoin_txid), + uri: Some(value.uri.clone()), + amount_sats: Some(value.amount_sats), + resolution_txid: Some(value.resolution_txid), + events: Some(value.events.clone()), + status: Some(value.status), + completed_at: Some(value.completed_at), + } + } +} + +impl StorableObject for PayjoinSession { + type Id = PaymentId; + + fn id(&self) -> Self::Id { + self.session_id + } +} + +impl UpdatableObject for PayjoinSession { + type Update = PayjoinSessionUpdate; + + fn update(&mut self, update: Self::Update) -> bool { + debug_assert_eq!( + self.session_id, update.session_id, + "We should only ever override data for the same id" + ); + + let mut updated = false; + + macro_rules! update_if_necessary { + ($val:expr, $update:expr) => { + if $val != $update { + $val = $update; + updated = true; + } + }; + } + + if let Some(fallback_tx_opt) = update.fallback_tx { + update_if_necessary!(self.fallback_tx, fallback_tx_opt); + } + if let Some(payjoin_txid_opt) = update.payjoin_txid { + update_if_necessary!(self.payjoin_txid, payjoin_txid_opt); + } + if let Some(uri_opt) = update.uri { + update_if_necessary!(self.uri, uri_opt); + } + if let Some(amount_sats_opt) = update.amount_sats { + update_if_necessary!(self.amount_sats, amount_sats_opt); + } + if let Some(resolution_txid_opt) = update.resolution_txid { + update_if_necessary!(self.resolution_txid, resolution_txid_opt); + } + if let Some(events_opt) = &update.events { + update_if_necessary!(self.events, events_opt.clone()); + } + if let Some(status_opt) = update.status { + update_if_necessary!(self.status, status_opt); + } + if let Some(completed_at_opt) = update.completed_at { + update_if_necessary!(self.completed_at, completed_at_opt); + } + + if updated { + self.latest_update_timestamp = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or(Duration::from_secs(0)) + .as_secs(); + } + + updated + } + + fn to_update(&self) -> Self::Update { + self.into() + } +} + +impl StorableObjectUpdate for PayjoinSessionUpdate { + fn id(&self) -> ::Id { + self.session_id + } +} + +#[cfg(test)] +mod tests { + use bitcoin::absolute::LockTime; + use bitcoin::hashes::Hash; + use bitcoin::transaction::Version; + use bitcoin::{Amount, ScriptBuf, TxIn, TxOut}; + use lightning::util::ser::{Readable, Writeable}; + + use super::*; + + fn dummy_tx() -> Transaction { + Transaction { + version: Version::TWO, + lock_time: LockTime::ZERO, + input: vec![TxIn::default()], + output: vec![TxOut { + value: Amount::from_sat(10_000), + script_pubkey: ScriptBuf::new(), + }], + } + } + + #[test] + fn receive_session_round_trips() { + let mut session = PayjoinSession::new(PaymentId([7; 32]), PayjoinSessionKind::Receive); + assert_eq!(session.fallback_tx(), None); + + session.set_fallback_tx(dummy_tx()); + session.events.push(SerializedSessionEvent { event_bytes: vec![1, 2, 3], created_at: 42 }); + session.status = PayjoinStatus::Completed; + session.completed_at = Some(43); + + let decoded = PayjoinSession::read(&mut &session.encode()[..]).unwrap(); + assert_eq!(decoded, session); + assert_eq!(decoded.fallback_tx(), Some(&dummy_tx())); + } + + #[test] + fn fallback_pending_session_round_trips() { + let mut session = PayjoinSession::new(PaymentId([8; 32]), PayjoinSessionKind::Receive); + session.set_fallback_tx(dummy_tx()); + session.payjoin_txid = Some(dummy_tx().compute_txid()); + session.status = PayjoinStatus::FallbackPending; + session.completed_at = Some(44); + + let decoded = PayjoinSession::read(&mut &session.encode()[..]).unwrap(); + assert_eq!(decoded, session); + assert_eq!(decoded.status, PayjoinStatus::FallbackPending); + assert_eq!(decoded.fallback_tx(), Some(&dummy_tx())); + } + + #[test] + fn session_details_round_trip() { + let mut session = PayjoinSession::new(PaymentId([10; 32]), PayjoinSessionKind::Receive); + session.uri = Some("bitcoin:bc1q?amount=0.001&pj=https://example.com".to_string()); + session.amount_sats = Some(100_000); + session.resolution_txid = Some(dummy_tx().compute_txid()); + session.cancel_requested = true; + + let decoded = PayjoinSession::read(&mut &session.encode()[..]).unwrap(); + assert_eq!(decoded, session); + } + + #[test] + fn session_without_its_uri_is_not_listed() { + let mut session = PayjoinSession::new(PaymentId([11; 32]), PayjoinSessionKind::Receive); + session.amount_sats = Some(100_000); + assert_eq!(session.details(), None); + + session.uri = Some("bitcoin:bc1q".to_string()); + let details = session.details().unwrap(); + assert_eq!(details.session_id, PaymentId([11; 32])); + assert_eq!(details.kind, PayjoinSessionKind::Receive); + assert_eq!(details.amount_sats, 100_000); + assert_eq!(details.status, PayjoinSessionStatus::Active); + assert_eq!(details.created_at, session.created_at); + } + + #[test] + fn user_status_reflects_the_session() { + let mut session = PayjoinSession::new(PaymentId([12; 32]), PayjoinSessionKind::Receive); + let fallback_txid = dummy_tx().compute_txid(); + let other_txid = Txid::from_byte_array([13; 32]); + assert_eq!(session.user_status(), PayjoinSessionStatus::Active); + + // Requested but not yet applied. + session.cancel_requested = true; + assert_eq!(session.user_status(), PayjoinSessionStatus::Active); + session.cancel_requested = false; + + session.status = PayjoinStatus::Completed; + session.resolution_txid = Some(other_txid); + assert_eq!( + session.user_status(), + PayjoinSessionStatus::Completed { txid: Some(other_txid) } + ); + + session.set_fallback_tx(dummy_tx()); + session.status = PayjoinStatus::FallbackPending; + assert_eq!(session.user_status(), PayjoinSessionStatus::FallbackPending { fallback_txid }); + + session.status = PayjoinStatus::Failed; + session.resolution_txid = Some(fallback_txid); + assert_eq!( + session.user_status(), + PayjoinSessionStatus::Failed { txid: Some(fallback_txid) } + ); + + // A cancelled session reports as such whether its fallback is still pending or settled. + session.cancel_requested = true; + assert_eq!( + session.user_status(), + PayjoinSessionStatus::Cancelled { fallback_txid: Some(fallback_txid) } + ); + session.status = PayjoinStatus::FallbackPending; + assert_eq!( + session.user_status(), + PayjoinSessionStatus::Cancelled { fallback_txid: Some(fallback_txid) } + ); + + // A payjoin that confirmed anyway completed the session. + session.status = PayjoinStatus::Completed; + session.resolution_txid = Some(other_txid); + assert_eq!( + session.user_status(), + PayjoinSessionStatus::Completed { txid: Some(other_txid) } + ); + } + + #[test] + fn stale_write_does_not_undo_a_cancellation() { + let stale = PayjoinSession::new(PaymentId([14; 32]), PayjoinSessionKind::Receive); + let mut stored = stale.clone(); + stored.cancel_requested = true; + + let mut stale_with_progress = stale; + stale_with_progress.status = PayjoinStatus::Failed; + stored.update(stale_with_progress.to_update()); + assert!(stored.cancel_requested); + assert_eq!(stored.status, PayjoinStatus::Failed); + } + + #[test] + fn payjoin_tx_is_recognized_whatever_its_script_sigs() { + let mut session = PayjoinSession::new(PaymentId([9; 32]), PayjoinSessionKind::Receive); + let proposal = dummy_tx(); + assert!(!session.is_payjoin_tx(&proposal)); + + session.payjoin_txid = Some(proposal.compute_txid()); + assert!(session.is_payjoin_tx(&proposal)); + + // A non-SegWit sender signs in the script_sig, which changes the broadcast txid. + let mut signed = proposal.clone(); + signed.input[0].script_sig = ScriptBuf::from_bytes(vec![0x51]); + assert_ne!(signed.compute_txid(), proposal.compute_txid()); + assert!(session.is_payjoin_tx(&signed)); + + // Any other change is a different transaction. + let mut other = proposal; + other.output[0].value = Amount::from_sat(9_000); + assert!(!session.is_payjoin_tx(&other)); + } +} diff --git a/src/payment/payjoin/persist.rs b/src/payment/payjoin/persist.rs new file mode 100644 index 0000000000..9532e63b07 --- /dev/null +++ b/src/payment/payjoin/persist.rs @@ -0,0 +1,128 @@ +// This file is Copyright its original authors, visible in version control history. +// +// This file is licensed under the Apache License, Version 2.0 or the MIT license , at your option. You may not use this file except in +// accordance with one or both of these licenses. + +use std::sync::Arc; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use lightning::ln::channelmanager::PaymentId; +use payjoin::persist::AsyncSessionPersister; +use payjoin::receive::v2::SessionEvent as ReceiverSessionEvent; + +use crate::payment::payjoin::payjoin_session::{ + PayjoinSession, PayjoinSessionKind, SerializedSessionEvent, +}; +use crate::types::PayjoinSessionStore; +use crate::Error; + +pub(crate) struct KVStorePayjoinReceiverPersister { + session_id: PaymentId, + payjoin_session_store: Arc, + /// For a new session.`None` when resuming a session that already exists. + new_session: Option, +} + +impl KVStorePayjoinReceiverPersister { + pub fn new(session_id: PaymentId, payjoin_session_store: Arc) -> Self { + let new_session = PayjoinSession::new(session_id, PayjoinSessionKind::Receive); + + Self { session_id, payjoin_session_store, new_session: Some(new_session) } + } + + pub fn session_id(&self) -> PaymentId { + self.session_id + } + + pub async fn get_session(&self) -> Result { + self.payjoin_session_store.get(&self.session_id).await?.ok_or(Error::InvalidPaymentId) + } + + /// Reconstruct persister from existing session + pub async fn from_session( + session_id: PaymentId, payjoin_session_store: Arc, + ) -> Result { + if payjoin_session_store.get(&session_id).await?.is_none() { + return Err(Error::InvalidPaymentId); + } + + Ok(Self { session_id, payjoin_session_store, new_session: None }) + } +} + +impl AsyncSessionPersister for KVStorePayjoinReceiverPersister { + type SessionEvent = ReceiverSessionEvent; + type InternalStorageError = Error; + + fn save_event( + &self, event: Self::SessionEvent, + ) -> impl std::future::Future> + Send { + async move { + let event_bytes = serde_json::to_vec(&event).map_err(|_| Error::PersistenceFailed)?; + + let event = SerializedSessionEvent { + event_bytes, + created_at: SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or(Duration::from_secs(0)) + .as_secs(), + }; + + let new_session = self.new_session.clone(); + self.payjoin_session_store + .mutate(&self.session_id, |existing| { + // Create the record with its first event if it doesn't exist yet + let mut session = existing.cloned().or(new_session)?; + session.events.push(event); + Some(session) + }) + .await? + .ok_or(Error::InvalidPaymentId)?; + + Ok(()) + } + } + + fn load( + &self, + ) -> impl std::future::Future< + Output = Result< + Box + Send>, + Self::InternalStorageError, + >, + > + Send { + async move { + let session = self.get_session().await?; + + let events: Vec = session + .events + .iter() + .map(|e| serde_json::from_slice(&e.event_bytes)) + .collect::, _>>() + .map_err(|_| Error::PersistenceFailed)?; + + Ok(Box::new(events.into_iter()) as Box + Send>) + } + } + + fn close( + &self, + ) -> impl std::future::Future> + Send { + async move { + let mut session = self.get_session().await?; + + session.completed_at = Some( + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or(Duration::from_secs(0)) + .as_secs(), + ); + + self.payjoin_session_store.insert_or_update(session).await?; + + Ok(()) + } + } +} diff --git a/src/payment/payjoin/seen_inputs.rs b/src/payment/payjoin/seen_inputs.rs new file mode 100644 index 0000000000..93be56a9ab --- /dev/null +++ b/src/payment/payjoin/seen_inputs.rs @@ -0,0 +1,238 @@ +// This file is Copyright its original authors, visible in version control history. +// +// This file is licensed under the Apache License, Version 2.0 or the MIT license , at your option. You may not use this file except in +// accordance with one or both of these licenses. + +use std::ops::Deref; +use std::str::FromStr; + +use bitcoin::{OutPoint, Txid}; +use lightning::impl_writeable_tlv_based; +use lightning::ln::channelmanager::PaymentId; + +use crate::data_store::{CachePolicy, DataStore, KeepAllEntries, StorableObject, StorableObjectId}; +use crate::logger::LdkLogger; +use crate::Error; + +/// A sender input we have seen in the original proposal of a receive session. +/// +/// These are kept independently of [`PayjoinSession`]s, which are cleaned up after they +/// complete, so that a sender can't reuse inputs across sessions to probe our UTXOs. +/// +/// [`PayjoinSession`]: crate::payment::payjoin::payjoin_session::PayjoinSession +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct SeenInput { + /// The sender's input. + pub outpoint: OutPoint, + /// The session that first recorded this input. + pub session_id: PaymentId, + /// The time, in seconds since start of the UNIX epoch, the input was first seen. + pub first_seen_at: u64, +} + +impl_writeable_tlv_based!(SeenInput, { + (0, outpoint, required), + (2, session_id, required), + (4, first_seen_at, required), +}); + +impl StorableObjectId for OutPoint { + fn encode_to_hex_str(&self) -> String { + format!("{}_{}", self.txid, self.vout) + } + + fn decode_from_hex_str(s: &str) -> Option { + let (txid, vout) = s.split_once('_')?; + Some(OutPoint { txid: Txid::from_str(txid).ok()?, vout: vout.parse().ok()? }) + } +} + +impl StorableObject for SeenInput { + type Id = OutPoint; + + fn id(&self) -> Self::Id { + self.outpoint + } +} + +/// Returns whether `outpoint` was already seen by a session other than `session_id`, recording +/// it as seen by `session_id` if it wasn't seen before. +/// +/// An input recorded by `session_id` itself is not considered seen, so that a session retried +/// after the input was recorded but before its state transition was persisted doesn't reject +/// itself. +/// +/// The check and the insert happen atomically, so concurrent sessions racing on the same input +/// can't both consider it unseen. +pub(crate) async fn check_and_record_seen_input( + store: &DataStore, outpoint: OutPoint, session_id: PaymentId, now: u64, +) -> Result +where + L::Target: LdkLogger, +{ + let mut seen = false; + store + .mutate(&outpoint, |existing| match existing { + // Already recorded: keep the original record and don't write. + Some(seen_input) => { + seen = seen_input.session_id != session_id; + None + }, + // First sighting: record it. + None => Some(SeenInput { outpoint, session_id, first_seen_at: now }), + }) + .await?; + Ok(seen) +} + +/// Forgets the sender inputs among `outpoints`, once a transaction spending them is buried. +/// +/// A sender can't reuse a spent input to probe us any more: an original transaction spending it +/// fails the broadcast suitability check, which comes before the check for seen inputs. +pub(crate) async fn forget_seen_inputs( + store: &DataStore, outpoints: impl IntoIterator, +) -> Result<(), Error> +where + L::Target: LdkLogger, +{ + for outpoint in outpoints { + store.remove(&outpoint).await?; + } + Ok(()) +} + +/// Forgets the sender inputs first seen more than `retention_secs` before `now`, whose spend was +/// never seen buried, e.g. because the sender never broadcast or spent them to someone else. +/// +/// Returns how many were forgotten. +pub(crate) async fn prune_seen_inputs( + store: &DataStore, now: u64, retention_secs: u64, +) -> Result +where + L::Target: LdkLogger, +{ + let is_old = + |seen_input: &SeenInput| now.saturating_sub(seen_input.first_seen_at) > retention_secs; + let mut pruned = 0; + for seen_input in store.list_filter(|seen_input| is_old(seen_input)).await { + // Checked again under the lock, in case the input was forgotten and seen anew meanwhile. + if store.remove_if(&seen_input.outpoint, is_old).await? { + pruned += 1; + } + } + Ok(pruned) +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use bitcoin::hashes::Hash; + use lightning::util::test_utils::TestLogger; + + use super::*; + use crate::io::test_utils::InMemoryStore; + use crate::types::{DynStore, DynStoreWrapper}; + + fn new_store() -> DataStore, KeepAllEntries> { + let kv_store: Arc = Arc::new(DynStoreWrapper(InMemoryStore::new())); + DataStore::new( + Vec::new(), + KeepAllEntries, + "payjoin_seen_inputs_test".to_string(), + String::new(), + kv_store, + Arc::new(TestLogger::new()), + ) + } + + fn outpoint(byte: u8, vout: u32) -> OutPoint { + OutPoint { txid: Txid::from_byte_array([byte; 32]), vout } + } + + #[test] + fn outpoint_id_round_trips() { + for op in [outpoint(0xab, 0), outpoint(0x01, u32::MAX)] { + let encoded = op.encode_to_hex_str(); + assert_eq!(OutPoint::decode_from_hex_str(&encoded), Some(op)); + } + assert_eq!(OutPoint::decode_from_hex_str("not_an_outpoint"), None); + assert_eq!(OutPoint::decode_from_hex_str(&"00".repeat(32)), None); + } + + #[tokio::test] + async fn inputs_are_only_seen_by_other_sessions() { + let store = new_store(); + let session_a = PaymentId([1; 32]); + let session_b = PaymentId([2; 32]); + let input = outpoint(0x42, 1); + + // First sighting is recorded and not considered seen. + assert!(!check_and_record_seen_input(&store, input, session_a, 100).await.unwrap()); + let recorded = store.get(&input).await.unwrap().unwrap(); + assert_eq!( + recorded, + SeenInput { outpoint: input, session_id: session_a, first_seen_at: 100 } + ); + + // Retrying the same session doesn't reject itself. + assert!(!check_and_record_seen_input(&store, input, session_a, 200).await.unwrap()); + + // Another session reusing the input is rejected, and the original record is kept. + assert!(check_and_record_seen_input(&store, input, session_b, 300).await.unwrap()); + assert_eq!(store.get(&input).await.unwrap().unwrap(), recorded); + + // Other inputs are unaffected. + assert!(!check_and_record_seen_input(&store, outpoint(0x42, 2), session_b, 300) + .await + .unwrap()); + } + + #[tokio::test] + async fn concurrent_sessions_cannot_both_claim_an_input() { + let store = new_store(); + let input = outpoint(0x42, 1); + let (a, b) = tokio::join!( + check_and_record_seen_input(&store, input, PaymentId([1; 32]), 100), + check_and_record_seen_input(&store, input, PaymentId([2; 32]), 100), + ); + // Exactly one session gets to use the input. + assert_ne!(a.unwrap(), b.unwrap()); + } + + #[tokio::test] + async fn forgotten_inputs_can_be_seen_anew() { + let store = new_store(); + let (spent, unspent) = (outpoint(0x42, 1), outpoint(0x42, 2)); + for input in [spent, unspent] { + check_and_record_seen_input(&store, input, PaymentId([1; 32]), 100).await.unwrap(); + } + + forget_seen_inputs(&store, [spent]).await.unwrap(); + assert_eq!(store.get(&spent).await.unwrap(), None); + // Another session may use the forgotten input, but not the one still remembered. + assert!(!check_and_record_seen_input(&store, spent, PaymentId([2; 32]), 200) + .await + .unwrap()); + assert!(check_and_record_seen_input(&store, unspent, PaymentId([2; 32]), 200) + .await + .unwrap()); + } + + #[tokio::test] + async fn only_inputs_past_retention_are_pruned() { + let store = new_store(); + let (old, recent) = (outpoint(0x42, 1), outpoint(0x42, 2)); + check_and_record_seen_input(&store, old, PaymentId([1; 32]), 100).await.unwrap(); + check_and_record_seen_input(&store, recent, PaymentId([1; 32]), 150).await.unwrap(); + + // Exactly at the retention age isn't past it yet. + assert_eq!(prune_seen_inputs(&store, 200, 100).await.unwrap(), 0); + + assert_eq!(prune_seen_inputs(&store, 201, 100).await.unwrap(), 1); + assert_eq!(store.get(&old).await.unwrap(), None); + assert!(store.get(&recent).await.unwrap().is_some()); + } +} diff --git a/src/payment/store.rs b/src/payment/store.rs index 99ac6a7725..87ab54d66b 100644 --- a/src/payment/store.rs +++ b/src/payment/store.rs @@ -479,6 +479,9 @@ pub enum TransactionType { /// The channels participating in the negotiation. channels: Vec, }, + /// A transaction settling a payjoin, i.e., one to which both we and our counterparty + /// contributed inputs. + Payjoin, } impl_writeable_tlv_based_enum!(TransactionType, @@ -506,7 +509,8 @@ impl_writeable_tlv_based_enum!(TransactionType, }, (12, InteractiveFunding) => { (0, channels, optional_vec), - } + }, + (14, Payjoin) => {} ); /// Represents the kind of a payment. diff --git a/src/types.rs b/src/types.rs index 91bd872bc7..8391b92e36 100644 --- a/src/types.rs +++ b/src/types.rs @@ -44,6 +44,8 @@ use crate::ffi::maybe_wrap; use crate::liquidity::client::lsps2::router::LSPS2Router; use crate::logger::Logger; use crate::message_handler::NodeCustomMessageHandler; +use crate::payment::payjoin::payjoin_session::PayjoinSession; +use crate::payment::payjoin::seen_inputs::SeenInput; use crate::payment::NodeOffersMessageHandler; use crate::payment::{ChannelPairForwardingStats, ForwardedPaymentDetails, PaymentDetails}; use crate::runtime::RuntimeSpawner; @@ -350,6 +352,9 @@ pub(crate) type ChannelPairForwardingStatsStore = DataStore, KeepNoEntries>; pub(crate) type ChannelTxFactsStore = DataStore, KeepLeastRecentlyUsed>; +pub(crate) type PayjoinSessionStore = DataStore>; +pub(crate) type PayjoinSeenInputsStore = DataStore, KeepAllEntries>; + /// A local, potentially user-provided, identifier of a channel. /// /// By default, this will be randomly generated for the user to ensure local uniqueness. diff --git a/src/wallet/mod.rs b/src/wallet/mod.rs index 58036e60cf..fffb07f0d5 100644 --- a/src/wallet/mod.rs +++ b/src/wallet/mod.rs @@ -92,6 +92,19 @@ pub(crate) enum FundingAmount { Max, } +/// Where a payjoin fallback transaction stands, as returned by +/// [`Wallet::payjoin_fallback_status`]. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum PayjoinFallbackStatus { + /// Neither the fallback nor a transaction double-spending it has confirmed through + /// [`ANTI_REORG_DELAY`], so the fallback may still need broadcasting. + Unresolved, + /// The fallback confirmed through [`ANTI_REORG_DELAY`]. + Confirmed, + /// This transaction, double-spending the fallback, confirmed through [`ANTI_REORG_DELAY`]. + Conflicted(Transaction), +} + /// What recording an interactive funding round this node is about to sign came to, as it decides /// whether the round may be signed. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -3650,6 +3663,163 @@ impl Wallet { Ok(()) } + /// Tags an incoming payjoin transaction as [`TransactionType::Payjoin`]. + /// + /// The sender broadcasts a payjoin, so we only learn the outcome once monitoring finds the + /// transaction, possibly after wallet sync has already recorded or even graduated it. Like a + /// late funding classification, this merges only the classification into an existing record + /// and leaves its figures, status and confirmation state to wallet sync. If no record exists + /// yet, one is created from `tx` and marked as pending. + pub(crate) async fn classify_payjoin( + &self, txid: Txid, tx: Option<&Transaction>, + ) -> Result<(), Error> { + // Held across both stores, as wallet sync and the other classifiers do, so neither sees + // the record and its tracker entry out of step. + let stores = self.payment_stores.lock().await; + + // Wallet sync keeps a transaction that replaced another, as a payjoin replacing a + // fallback the sender broadcast first, in the record of the one it replaced. + let id = self.find_payment_by_txid(txid).await?.unwrap_or(PaymentId(txid.to_byte_array())); + let (amount_msat, fee_paid_msat, direction) = match tx { + Some(tx) => self.onchain_payment_fields(tx), + // Wallet sync fills the values in on its next event for this txid. + None => (None, None, PaymentDirection::Inbound), + }; + let details = PaymentDetails::new( + id, + PaymentKind::Onchain { + txid, + status: ConfirmationStatus::Unconfirmed, + tx_type: Some(TransactionType::Payjoin), + }, + amount_msat, + fee_paid_msat, + direction, + PaymentStatus::Pending, + ); + + let mut classification = PaymentDetailsUpdate::new(id); + classification.tx_type = Some(Some(TransactionType::Payjoin)); + + stores + .mutate_payment(&id, |existing| match existing { + None => Some(details.clone()), + // A record found through its conflicts has moved on to another transaction. + Some(PaymentDetails { kind: PaymentKind::Onchain { txid: record_txid, .. }, .. }) + if *record_txid != txid => + { + None + }, + Some(current) => { + let mut updated = current.clone(); + updated.update(classification).then_some(updated) + }, + }) + .await?; + + // The record carries the classification, so the tracker entry only needs to exist while + // the payment is pending. + self.upsert_tracked_payment(&stores, details, Vec::new()).await + } + + /// Removes the payjoin classification from the payment of `txid`, a spend of a payjoin + /// sender's inputs that isn't the payjoin. + /// + /// Wallet sync keeps the payjoin and a spend that replaced it in one record, which moves to + /// the spend but keeps the classification [`Self::classify_payjoin`] gave the payjoin, as when + /// a reorg lets the sender's fallback confirm in its place. + pub(crate) async fn unclassify_payjoin(&self, txid: Txid) -> Result<(), Error> { + let stores = self.payment_stores.lock().await; + + let Some(id) = self.find_payment_by_txid(txid).await? else { + return Ok(()); + }; + stores + .mutate_payment(&id, |existing| { + let current = existing?; + match current.kind { + PaymentKind::Onchain { + txid: record_txid, + tx_type: Some(TransactionType::Payjoin), + .. + } if record_txid == txid => { + let mut updated = current.clone(); + if let PaymentKind::Onchain { ref mut tx_type, .. } = updated.kind { + *tx_type = None; + } + Some(updated) + }, + _ => None, + } + }) + .await?; + Ok(()) + } + + /// The hash of the wallet's chain tip. + pub(crate) fn best_block_hash(&self) -> bitcoin::BlockHash { + self.inner.lock().expect("lock").latest_checkpoint().hash() + } + + /// Reports whether a payjoin fallback transaction still needs broadcasting. + /// + /// The fallback spends the sender's inputs and pays us, so wallet sync picks it up, as it does + /// any competing spend of the sender's inputs that also pays us, such as the payjoin itself. A + /// competing spend paying only others never enters the wallet's graph, so to the wallet it + /// leaves the fallback unresolved. + pub(crate) fn payjoin_fallback_status( + &self, fallback_tx: &Transaction, + ) -> PayjoinFallbackStatus { + let spends = self.spends_of_outpoints(fallback_tx.input.iter().map(|i| i.previous_output)); + // Most confirmed first, so only the first can be buried deep enough. + match spends.into_iter().next() { + Some((tx, confirmations)) if confirmations >= ANTI_REORG_DELAY => { + if tx.compute_txid() == fallback_tx.compute_txid() { + PayjoinFallbackStatus::Confirmed + } else { + PayjoinFallbackStatus::Conflicted(tx) + } + }, + _ => PayjoinFallbackStatus::Unresolved, + } + } + + /// Returns the transactions in the wallet that spend any of `outpoints`, each with its number + /// of confirmations (0 while unconfirmed), most confirmed first. + /// + /// Used to settle a payjoin: the payjoin, the sender's fallback, and any other spend of the + /// sender's inputs that pays us all reach the wallet through sync. A spend paying only others + /// never does. + pub(crate) fn spends_of_outpoints( + &self, outpoints: impl IntoIterator, + ) -> Vec<(Transaction, u32)> { + let locked_wallet = self.inner.lock().expect("lock"); + let tip_height = locked_wallet.latest_checkpoint().height(); + + let mut seen = HashSet::new(); + let mut spends = Vec::new(); + for outpoint in outpoints { + for spender in locked_wallet.tx_graph().outspends(outpoint) { + if !seen.insert(*spender) { + continue; + } + // `get_tx` is canonical-only, so a spend that lost a conflict doesn't count. + let Some(wallet_tx) = locked_wallet.get_tx(*spender) else { + continue; + }; + let confirmations = match wallet_tx.chain_position { + ChainPosition::Confirmed { anchor, .. } => { + tip_height.saturating_sub(anchor.block_id.height).saturating_add(1) + }, + ChainPosition::Unconfirmed { .. } => 0, + }; + spends.push((wallet_tx.tx_node.tx.as_ref().clone(), confirmations)); + } + } + spends.sort_by(|a, b| b.1.cmp(&a.1)); + spends + } + /// Merges duplicate records wallet sync created for this funding payment's candidates before /// they were recorded as such. Sync re-keys an event for a round it cannot attribute to the /// funding record — not yet a candidate, so the funding-status gate reports it foreign — to @@ -4399,6 +4569,46 @@ impl Wallet { Ok(new_txid) } + + /// Check if a script belongs to this wallet + pub(crate) fn is_mine(&self, script: ScriptBuf) -> Result { + let locked_wallet = self.inner.lock().expect("lock"); + Ok(locked_wallet.is_mine(script)) + } + + /// Check if an outpoint belongs to this wallet. + pub(crate) fn is_my_outpoint(&self, outpoint: &OutPoint) -> Result { + let locked_wallet = self.inner.lock().expect("lock"); + + let script_pubkey = match locked_wallet.tx_details(outpoint.txid) { + Some(details) => match details.tx.output.get(outpoint.vout as usize) { + Some(txout) => txout.script_pubkey.clone(), + None => return Ok(false), + }, + None => return Ok(false), + }; + + Ok(locked_wallet.is_mine(script_pubkey)) + } + + #[allow(deprecated)] + pub(crate) fn process_psbt(&self, mut psbt: Psbt) -> Result { + let locked_wallet = self.inner.lock().expect("lock"); + + let sign_options = SignOptions { trust_witness_utxo: true, ..Default::default() }; + + locked_wallet.sign(&mut psbt, sign_options).map_err(|e| { + log_error!(self.logger, "Failed to sign PSBT: {}", e); + Error::WalletOperationFailed + })?; + + // Return the signed PSBT (not extracted transaction) + Ok(psbt) + } + + pub(crate) fn list_unspent_confirmed_utxos(&self) -> Result, Error> { + self.list_confirmed_utxos_inner().map_err(|()| Error::WalletOperationFailed) + } } /// Whether a `tx_add_input` message carrying `prevtx` fits a Lightning message. @@ -4928,7 +5138,7 @@ fn ldk_to_bdk_satisfaction_weight(ldk_satisfaction_weight: u64) -> Weight { } #[cfg(all(test, any(feature = "chain-esplora", feature = "chain-electrum")))] -mod tests { +pub(crate) mod tests { use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use bdk_chain::{BlockId, CheckPoint, ConfirmationBlockTime, TxUpdate}; @@ -5240,7 +5450,7 @@ mod tests { /// Constructs a `Wallet` around the given store, either creating a fresh BDK wallet or /// loading the one the store already holds. - async fn new_test_wallet(store: Arc, load_existing: bool) -> Arc { + pub(crate) async fn new_test_wallet(store: Arc, load_existing: bool) -> Arc { let logger = Arc::new(Logger::new_log_facade()); let mut config = Config::default(); config.network = Network::Regtest; @@ -5354,7 +5564,7 @@ mod tests { wallet.payment_stores.payment_tracker().get(id).await.unwrap() } - async fn record_of(wallet: &Wallet, id: &PaymentId) -> Option { + pub(crate) async fn record_of(wallet: &Wallet, id: &PaymentId) -> Option { wallet.payment_stores.payment_store().get(id).await.unwrap() } @@ -5393,7 +5603,7 @@ mod tests { } /// The transaction of the on-chain payment `details`. - fn onchain_txid(details: &PaymentDetails) -> Txid { + pub(crate) fn onchain_txid(details: &PaymentDetails) -> Txid { match details.kind { PaymentKind::Onchain { txid, .. } => txid, _ => panic!("not an on-chain payment: {:?}", details.kind), @@ -6399,7 +6609,7 @@ mod tests { /// Inserts `tx` into the BDK wallet as canonically confirmed at `height`, extending the /// local chain to that height. - fn insert_confirmed_tx(wallet: &Wallet, tx: Transaction, height: u32) { + pub(crate) fn insert_confirmed_tx(wallet: &Wallet, tx: Transaction, height: u32) { let txid = tx.compute_txid(); let mut locked = wallet.inner.lock().unwrap(); let block = @@ -6442,7 +6652,7 @@ mod tests { /// Inserts `tx` into the BDK wallet as canonically unconfirmed (seen in the mempool), with /// its spends of the wallet's outputs signed. - fn insert_unconfirmed_tx(wallet: &Wallet, tx: Transaction) { + pub(crate) fn insert_unconfirmed_tx(wallet: &Wallet, tx: Transaction) { let tx = sign_wallet_inputs(wallet, tx); let txid = tx.compute_txid(); let mut locked = wallet.inner.lock().unwrap(); @@ -6536,7 +6746,7 @@ mod tests { /// Lets wallet sync observe `tx` as an unconfirmed wallet transaction: the wallet takes it in /// and the sync event it yields is handled. - async fn observe_unconfirmed(wallet: &Wallet, tx: &Transaction) { + pub(crate) async fn observe_unconfirmed(wallet: &Wallet, tx: &Transaction) { insert_unconfirmed_tx(wallet, tx.clone()); let event = WalletEvent::TxUnconfirmed { txid: tx.compute_txid(), @@ -6546,6 +6756,39 @@ mod tests { wallet.update_payment_store(vec![event]).await.unwrap(); } + /// Lets wallet sync observe `tx` confirmed at `height`, replacing `replaced` if given: the + /// wallet takes it in and the sync events it yields are handled. + #[cfg(feature = "chain-esplora")] + pub(crate) async fn observe_confirmed( + wallet: &Wallet, tx: &Transaction, height: u32, replaced: Option<&Transaction>, + ) { + insert_confirmed_tx(wallet, tx.clone(), height); + let txid = tx.compute_txid(); + let mut events = vec![WalletEvent::TxConfirmed { + txid, + tx: Arc::new(tx.clone()), + block_time: confirmed_block_time(height), + old_block_time: None, + }]; + if let Some(replaced) = replaced { + let conflicts = replaced + .input + .iter() + .enumerate() + .filter(|(_, txin)| { + tx.input.iter().any(|spend| spend.previous_output == txin.previous_output) + }) + .map(|(vin, _)| (vin, txid)) + .collect(); + events.push(WalletEvent::TxReplaced { + txid: replaced.compute_txid(), + tx: Arc::new(replaced.clone()), + conflicts, + }); + } + wallet.update_payment_store(events).await.unwrap(); + } + /// Records the payment wallet sync creates for `tx` without the wallet taking the transaction /// in, for the tests that need the record of a round while the wallet's graph must not contain /// it: a round the wallet has seen is a round no drop may take back. @@ -12388,7 +12631,7 @@ mod tests { } /// Builds a transaction spending `outpoint` into the wallet. - fn tx_spending(wallet: &Wallet, outpoint: OutPoint) -> Transaction { + pub(crate) fn tx_spending(wallet: &Wallet, outpoint: OutPoint) -> Transaction { let script_pubkey = wallet .inner .lock() @@ -12428,7 +12671,7 @@ mod tests { } /// Moves the wallet's chain tip to `height` without running the chain tip pass. - fn set_chain_tip(wallet: &Wallet, height: u32) { + pub(crate) fn set_chain_tip(wallet: &Wallet, height: u32) { let mut locked = wallet.inner.lock().unwrap(); let chain = locked.latest_checkpoint().insert(block_id_at(height)); locked.apply_update(Update { chain: Some(chain), ..Default::default() }).unwrap(); @@ -13779,4 +14022,183 @@ mod tests { .await .is_ok()); } + + /// Two inputs of a payjoin sender, unknown to the wallet. + fn payjoin_sender_outpoints() -> [OutPoint; 2] { + [ + OutPoint { txid: Txid::from_byte_array([50u8; 32]), vout: 0 }, + OutPoint { txid: Txid::from_byte_array([51u8; 32]), vout: 1 }, + ] + } + + pub(crate) fn tx_type_of(payment: &PaymentDetails) -> Option { + match &payment.kind { + PaymentKind::Onchain { tx_type, .. } => tx_type.clone(), + _ => panic!("not an on-chain payment: {:?}", payment.kind), + } + } + + #[tokio::test] + async fn spends_of_outpoints_lists_most_confirmed_first() { + let store: Arc = Arc::new(DynStoreWrapper(InMemoryStore::new())); + let wallet = new_test_wallet(store, false).await; + let [first, second] = payjoin_sender_outpoints(); + assert!(wallet.spends_of_outpoints([first, second]).is_empty()); + + let unconfirmed = tx_spending(&wallet, first); + insert_unconfirmed_tx(&wallet, unconfirmed.clone()); + assert_eq!(wallet.spends_of_outpoints([first, second]), vec![(unconfirmed.clone(), 0)]); + + let confirmed = tx_spending(&wallet, second); + insert_confirmed_tx(&wallet, confirmed.clone(), 10); + set_chain_tip(&wallet, 12); + assert_eq!( + wallet.spends_of_outpoints([first, second]), + vec![(confirmed, 3), (unconfirmed.clone(), 0)] + ); + + // Only spends of the given outpoints count. + assert_eq!(wallet.spends_of_outpoints([first]), vec![(unconfirmed, 0)]); + } + + #[tokio::test] + async fn spends_of_outpoints_lists_a_spend_once_and_skips_non_canonical() { + let store: Arc = Arc::new(DynStoreWrapper(InMemoryStore::new())); + let wallet = new_test_wallet(store, false).await; + let [first, second] = payjoin_sender_outpoints(); + + let mut spend = tx_spending(&wallet, first); + spend.input.push(bitcoin::TxIn { previous_output: second, ..Default::default() }); + insert_unconfirmed_tx(&wallet, spend.clone()); + assert_eq!(wallet.spends_of_outpoints([first, second]), vec![(spend.clone(), 0)]); + + evict_tx(&wallet, spend.compute_txid()); + assert!(wallet.spends_of_outpoints([first, second]).is_empty()); + } + + /// A reorg lets the sender's fallback confirm in place of the payjoin. Wallet sync moves the + /// payjoin's record to the fallback rather than leaving it pending beside a new one, and + /// settling the session then drops the payjoin classification from it. + #[tokio::test] + async fn fallback_replacing_a_payjoin_takes_over_its_record_unclassified() { + let store: Arc = Arc::new(DynStoreWrapper(InMemoryStore::new())); + let wallet = new_test_wallet(store, false).await; + let [sender_outpoint, _] = payjoin_sender_outpoints(); + + let payjoin = tx_spending(&wallet, sender_outpoint); + let payjoin_txid = payjoin.compute_txid(); + observe_unconfirmed(&wallet, &payjoin).await; + wallet.classify_payjoin(payjoin_txid, Some(&payjoin)).await.unwrap(); + + let fallback = tx_spending(&wallet, sender_outpoint); + let fallback_txid = fallback.compute_txid(); + insert_confirmed_tx(&wallet, fallback.clone(), 10); + let events = vec![ + WalletEvent::TxReplaced { + txid: payjoin_txid, + tx: Arc::new(payjoin), + conflicts: vec![(0, fallback_txid)], + }, + WalletEvent::TxConfirmed { + txid: fallback_txid, + tx: Arc::new(fallback), + block_time: confirmed_block_time(10), + old_block_time: None, + }, + ]; + wallet.update_payment_store(events).await.unwrap(); + + let payjoin_id = PaymentId(payjoin_txid.to_byte_array()); + let payment = record_of(&wallet, &payjoin_id).await.expect("record"); + assert_eq!(onchain_txid(&payment), fallback_txid); + assert_eq!(tx_type_of(&payment), Some(TransactionType::Payjoin)); + assert!(record_of(&wallet, &PaymentId(fallback_txid.to_byte_array())).await.is_none()); + + wallet.unclassify_payjoin(fallback_txid).await.unwrap(); + let payment = record_of(&wallet, &payjoin_id).await.expect("record"); + assert_eq!(onchain_txid(&payment), fallback_txid); + assert_eq!(tx_type_of(&payment), None); + + // The payjoin it replaced no longer owns the record, so it isn't classified again. + wallet.classify_payjoin(payjoin_txid, None).await.unwrap(); + let payment = record_of(&wallet, &payjoin_id).await.expect("record"); + assert_eq!(tx_type_of(&payment), None); + } + + /// The sender broadcast its fallback and then the payjoin, which replaced it. The payjoin is + /// classified on the record wallet sync moved to it, rather than on a second record of its own. + #[tokio::test] + async fn payjoin_replacing_a_fallback_is_classified_on_its_record() { + let store: Arc = Arc::new(DynStoreWrapper(InMemoryStore::new())); + let wallet = new_test_wallet(store, false).await; + let [sender_outpoint, _] = payjoin_sender_outpoints(); + + let fallback = tx_spending(&wallet, sender_outpoint); + let fallback_txid = fallback.compute_txid(); + observe_unconfirmed(&wallet, &fallback).await; + + let payjoin = tx_spending(&wallet, sender_outpoint); + let payjoin_txid = payjoin.compute_txid(); + apply_unconfirmed_txs(&wallet, [(payjoin.clone(), 200)]); + let events = vec![ + WalletEvent::TxReplaced { + txid: fallback_txid, + tx: Arc::new(fallback), + conflicts: vec![(0, payjoin_txid)], + }, + WalletEvent::TxUnconfirmed { + txid: payjoin_txid, + tx: Arc::new(payjoin.clone()), + old_block_time: None, + }, + ]; + wallet.update_payment_store(events).await.unwrap(); + wallet.classify_payjoin(payjoin_txid, Some(&payjoin)).await.unwrap(); + + let fallback_id = PaymentId(fallback_txid.to_byte_array()); + let payment = record_of(&wallet, &fallback_id).await.expect("record"); + assert_eq!(onchain_txid(&payment), payjoin_txid); + assert_eq!(tx_type_of(&payment), Some(TransactionType::Payjoin)); + assert!(record_of(&wallet, &PaymentId(payjoin_txid.to_byte_array())).await.is_none()); + } + + #[tokio::test] + async fn payjoin_fallback_stays_unresolved_until_buried() { + let store: Arc = Arc::new(DynStoreWrapper(InMemoryStore::new())); + let wallet = new_test_wallet(store, false).await; + let fallback = tx_spending(&wallet, payjoin_sender_outpoints()[0]); + + // Not yet seen by wallet sync. + assert_eq!(wallet.payjoin_fallback_status(&fallback), PayjoinFallbackStatus::Unresolved); + + insert_unconfirmed_tx(&wallet, fallback.clone()); + assert_eq!(wallet.payjoin_fallback_status(&fallback), PayjoinFallbackStatus::Unresolved); + + insert_confirmed_tx(&wallet, fallback.clone(), 10); + set_chain_tip(&wallet, 10 + ANTI_REORG_DELAY - 2); + assert_eq!(wallet.payjoin_fallback_status(&fallback), PayjoinFallbackStatus::Unresolved); + + set_chain_tip(&wallet, 10 + ANTI_REORG_DELAY - 1); + assert_eq!(wallet.payjoin_fallback_status(&fallback), PayjoinFallbackStatus::Confirmed); + } + + #[tokio::test] + async fn payjoin_fallback_is_conflicted_by_a_buried_double_spend() { + let store: Arc = Arc::new(DynStoreWrapper(InMemoryStore::new())); + let wallet = new_test_wallet(store, false).await; + let fallback = tx_spending(&wallet, payjoin_sender_outpoints()[0]); + // A different transaction spending the same sender input, such as the payjoin. + let payjoin = tx_spending(&wallet, payjoin_sender_outpoints()[0]); + assert_ne!(payjoin.compute_txid(), fallback.compute_txid()); + + insert_confirmed_tx(&wallet, payjoin.clone(), 10); + set_chain_tip(&wallet, 10 + ANTI_REORG_DELAY - 2); + assert_eq!(wallet.payjoin_fallback_status(&fallback), PayjoinFallbackStatus::Unresolved); + + set_chain_tip(&wallet, 10 + ANTI_REORG_DELAY - 1); + assert_eq!( + wallet.payjoin_fallback_status(&fallback), + PayjoinFallbackStatus::Conflicted(payjoin) + ); + } }