Skip to content

Commit

Permalink
Allow to send payjoin transactions
Browse files Browse the repository at this point in the history
Implements the payjoin sender as describe in BIP77.

This would allow the on chain wallet linked to LDK node to send payjoin
transactions.
  • Loading branch information
jbesraa committed Jul 23, 2024
1 parent 77a0bbe commit ac0e23e
Show file tree
Hide file tree
Showing 15 changed files with 1,137 additions and 13 deletions.
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ tokio = { version = "1.37", default-features = false, features = [ "rt-multi-thr
esplora-client = { version = "0.6", default-features = false }
libc = "0.2"
uniffi = { version = "0.26.0", features = ["build"], optional = true }
payjoin = { version = "0.16.0", default-features = false, features = ["send", "v2"] }

[target.'cfg(vss)'.dependencies]
vss-client = "0.2"
Expand All @@ -85,6 +86,9 @@ bitcoincore-rpc = { version = "0.17.0", default-features = false }
proptest = "1.0.0"
regex = "1.5.6"

payjoin = { version = "0.16.0", default-features = false, features = ["send", "v2", "receive"] }
reqwest = { version = "0.11", default-features = false, features = ["json", "rustls-tls", "blocking"] }

[target.'cfg(not(no_download))'.dev-dependencies]
electrsd = { version = "0.26.0", features = ["legacy", "esplora_a33e97e1", "bitcoind_25_0"] }

Expand Down
29 changes: 29 additions & 0 deletions bindings/ldk_node.udl
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ interface Node {
SpontaneousPayment spontaneous_payment();
OnchainPayment onchain_payment();
UnifiedQrPayment unified_qr_payment();
PayjoinPayment payjoin_payment();
[Throws=NodeError]
void connect(PublicKey node_id, SocketAddress address, boolean persist);
[Throws=NodeError]
Expand Down Expand Up @@ -156,6 +157,13 @@ interface UnifiedQrPayment {
QrPaymentResult send([ByRef]string uri_str);
};

interface PayjoinPayment {
[Throws=NodeError]
void send(string payjoin_uri);
[Throws=NodeError]
void send_with_amount(string payjoin_uri, u64 amount_sats);
};

[Error]
enum NodeError {
"AlreadyRunning",
Expand Down Expand Up @@ -206,6 +214,12 @@ enum NodeError {
"InsufficientFunds",
"LiquiditySourceUnavailable",
"LiquidityFeeTooHigh",
"PayjoinUnavailable",
"PayjoinUriInvalid",
"PayjoinRequestMissingAmount",
"PayjoinRequestCreationFailed",
"PayjoinRequestSendingFailed",
"PayjoinResponseProcessingFailed",
};

dictionary NodeStatus {
Expand All @@ -231,6 +245,7 @@ enum BuildError {
"InvalidSystemTime",
"InvalidChannelMonitor",
"InvalidListeningAddresses",
"InvalidPayjoinConfig",
"ReadFailed",
"WriteFailed",
"StoragePathAccessFailed",
Expand All @@ -248,6 +263,11 @@ interface Event {
ChannelPending(ChannelId channel_id, UserChannelId user_channel_id, ChannelId former_temporary_channel_id, PublicKey counterparty_node_id, OutPoint funding_txo);
ChannelReady(ChannelId channel_id, UserChannelId user_channel_id, PublicKey? counterparty_node_id);
ChannelClosed(ChannelId channel_id, UserChannelId user_channel_id, PublicKey? counterparty_node_id, ClosureReason? reason);
PayjoinPaymentPending(Txid txid, u64 amount_sats);
PayjoinPaymentBroadcasted(Txid txid, u64 amount_sats);
PayjoinPaymentSuccessful(Txid txid, u64 amount_sats, boolean is_original_psbt_modified);
PayjoinPaymentFailed(Txid txid, u64 amount_sats, PayjoinPaymentFailureReason reason);
PayjoinPaymentOriginalPsbtBroadcasted(Txid txid, u64 amount_sats);
};

enum PaymentFailureReason {
Expand All @@ -259,6 +279,12 @@ enum PaymentFailureReason {
"UnexpectedError",
};

enum PayjoinPaymentFailureReason {
"Timeout",
"RequestSendingFailed",
"ResponseProcessingFailed",
};

[Enum]
interface ClosureReason {
CounterpartyForceClosed(UntrustedString peer_msg);
Expand All @@ -284,6 +310,7 @@ interface PaymentKind {
Bolt12Offer(PaymentHash? hash, PaymentPreimage? preimage, PaymentSecret? secret, OfferId offer_id);
Bolt12Refund(PaymentHash? hash, PaymentPreimage? preimage, PaymentSecret? secret);
Spontaneous(PaymentHash hash, PaymentPreimage? preimage);
Payjoin();
};

[Enum]
Expand Down Expand Up @@ -316,6 +343,8 @@ dictionary PaymentDetails {
PaymentDirection direction;
PaymentStatus status;
u64 latest_update_timestamp;
Txid? txid;
BestBlock? best_block;
};

[NonExhaustive]
Expand Down
47 changes: 45 additions & 2 deletions src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use crate::io::sqlite_store::SqliteStore;
use crate::liquidity::LiquiditySource;
use crate::logger::{log_error, log_info, FilesystemLogger, Logger};
use crate::message_handler::NodeCustomMessageHandler;
use crate::payment::payjoin::handler::PayjoinHandler;
use crate::payment::store::PaymentStore;
use crate::peer_store::PeerStore;
use crate::tx_broadcaster::TransactionBroadcaster;
Expand Down Expand Up @@ -93,6 +94,11 @@ struct LiquiditySourceConfig {
lsps2_service: Option<(SocketAddress, PublicKey, Option<String>)>,
}

#[derive(Debug, Clone)]
struct PayjoinConfig {
payjoin_relay: payjoin::Url,
}

impl Default for LiquiditySourceConfig {
fn default() -> Self {
Self { lsps2_service: None }
Expand Down Expand Up @@ -132,6 +138,8 @@ pub enum BuildError {
WalletSetupFailed,
/// We failed to setup the logger.
LoggerSetupFailed,
/// Invalid Payjoin configuration.
InvalidPayjoinConfig,
}

impl fmt::Display for BuildError {
Expand All @@ -152,6 +160,10 @@ impl fmt::Display for BuildError {
Self::KVStoreSetupFailed => write!(f, "Failed to setup KVStore."),
Self::WalletSetupFailed => write!(f, "Failed to setup onchain wallet."),
Self::LoggerSetupFailed => write!(f, "Failed to setup the logger."),
Self::InvalidPayjoinConfig => write!(
f,
"Invalid Payjoin configuration. Make sure the provided arguments are valid URLs."
),
}
}
}
Expand All @@ -172,6 +184,7 @@ pub struct NodeBuilder {
chain_data_source_config: Option<ChainDataSourceConfig>,
gossip_source_config: Option<GossipSourceConfig>,
liquidity_source_config: Option<LiquiditySourceConfig>,
payjoin_config: Option<PayjoinConfig>,
}

impl NodeBuilder {
Expand All @@ -187,12 +200,14 @@ impl NodeBuilder {
let chain_data_source_config = None;
let gossip_source_config = None;
let liquidity_source_config = None;
let payjoin_config = None;
Self {
config,
entropy_source_config,
chain_data_source_config,
gossip_source_config,
liquidity_source_config,
payjoin_config,
}
}

Expand Down Expand Up @@ -247,6 +262,14 @@ impl NodeBuilder {
self
}

/// Configures the [`Node`] instance to enable payjoin transactions.
pub fn set_payjoin_config(&mut self, payjoin_relay: String) -> Result<&mut Self, BuildError> {
let payjoin_relay =
payjoin::Url::parse(&payjoin_relay).map_err(|_| BuildError::InvalidPayjoinConfig)?;
self.payjoin_config = Some(PayjoinConfig { payjoin_relay });
Ok(self)
}

/// Configures the [`Node`] instance to source its inbound liquidity from the given
/// [LSPS2](https://github.com/BitcoinAndLightningLayerSpecs/lsp/blob/main/LSPS2/README.md)
/// service.
Expand Down Expand Up @@ -365,6 +388,7 @@ impl NodeBuilder {
self.chain_data_source_config.as_ref(),
self.gossip_source_config.as_ref(),
self.liquidity_source_config.as_ref(),
self.payjoin_config.as_ref(),
seed_bytes,
logger,
vss_store,
Expand All @@ -386,6 +410,7 @@ impl NodeBuilder {
self.chain_data_source_config.as_ref(),
self.gossip_source_config.as_ref(),
self.liquidity_source_config.as_ref(),
self.payjoin_config.as_ref(),
seed_bytes,
logger,
kv_store,
Expand Down Expand Up @@ -453,6 +478,11 @@ impl ArcedNodeBuilder {
self.inner.write().unwrap().set_gossip_source_p2p();
}

/// Configures the [`Node`] instance to enable payjoin transactions.
pub fn set_payjoin_config(&self, payjoin_relay: String) -> Result<(), BuildError> {
self.inner.write().unwrap().set_payjoin_config(payjoin_relay).map(|_| ())
}

/// Configures the [`Node`] instance to source its gossip data from the given RapidGossipSync
/// server.
pub fn set_gossip_source_rgs(&self, rgs_server_url: String) {
Expand Down Expand Up @@ -521,8 +551,9 @@ impl ArcedNodeBuilder {
fn build_with_store_internal(
config: Arc<Config>, chain_data_source_config: Option<&ChainDataSourceConfig>,
gossip_source_config: Option<&GossipSourceConfig>,
liquidity_source_config: Option<&LiquiditySourceConfig>, seed_bytes: [u8; 64],
logger: Arc<FilesystemLogger>, kv_store: Arc<DynStore>,
liquidity_source_config: Option<&LiquiditySourceConfig>,
payjoin_config: Option<&PayjoinConfig>, seed_bytes: [u8; 64], logger: Arc<FilesystemLogger>,
kv_store: Arc<DynStore>,
) -> Result<Node, BuildError> {
// Initialize the on-chain wallet and chain access
let xprv = bitcoin::bip32::ExtendedPrivKey::new_master(config.network.into(), &seed_bytes)
Expand Down Expand Up @@ -966,6 +997,17 @@ fn build_with_store_internal(
let (stop_sender, _) = tokio::sync::watch::channel(());
let (event_handling_stopped_sender, _) = tokio::sync::watch::channel(());

let payjoin_handler = payjoin_config.map(|pj_config| {
Arc::new(PayjoinHandler::new(
Arc::clone(&tx_sync),
Arc::clone(&event_queue),
Arc::clone(&logger),
pj_config.payjoin_relay.clone(),
Arc::clone(&payment_store),
Arc::clone(&wallet),
))
});

let is_listening = Arc::new(AtomicBool::new(false));
let latest_wallet_sync_timestamp = Arc::new(RwLock::new(None));
let latest_onchain_wallet_sync_timestamp = Arc::new(RwLock::new(None));
Expand All @@ -987,6 +1029,7 @@ fn build_with_store_internal(
channel_manager,
chain_monitor,
output_sweeper,
payjoin_handler,
peer_manager,
connection_manager,
keys_manager,
Expand Down
9 changes: 9 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,15 @@ pub(crate) const RESOLVED_CHANNEL_MONITOR_ARCHIVAL_INTERVAL: u32 = 6;
// The time in-between peer reconnection attempts.
pub(crate) const PEER_RECONNECTION_INTERVAL: Duration = Duration::from_secs(10);

// The time before a payjoin http request is considered timed out.
pub(crate) const PAYJOIN_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);

// The duration between retries of a payjoin http request.
pub(crate) const PAYJOIN_RETRY_INTERVAL: Duration = Duration::from_secs(3);

// The total duration of retrying to send a payjoin http request.
pub(crate) const PAYJOIN_REQUEST_TOTAL_DURATION: Duration = Duration::from_secs(24 * 60 * 60);

// The time in-between RGS sync attempts.
pub(crate) const RGS_SYNC_INTERVAL: Duration = Duration::from_secs(60 * 60);

Expand Down
36 changes: 36 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,18 @@ pub enum Error {
LiquiditySourceUnavailable,
/// The given operation failed due to the LSP's required opening fee being too high.
LiquidityFeeTooHigh,
/// Failed to access Payjoin object.
PayjoinUnavailable,
/// Payjoin URI is invalid.
PayjoinUriInvalid,
/// Amount is neither user-provided nor defined in the URI.
PayjoinRequestMissingAmount,
/// Failed to build a Payjoin request.
PayjoinRequestCreationFailed,
/// Failed to send Payjoin request.
PayjoinRequestSendingFailed,
/// Payjoin response processing failed.
PayjoinResponseProcessingFailed,
}

impl fmt::Display for Error {
Expand Down Expand Up @@ -168,6 +180,30 @@ impl fmt::Display for Error {
Self::LiquidityFeeTooHigh => {
write!(f, "The given operation failed due to the LSP's required opening fee being too high.")
},
Self::PayjoinUnavailable => {
write!(
f,
"Failed to access Payjoin object. Make sure you have enabled Payjoin support."
)
},
Self::PayjoinRequestMissingAmount => {
write!(
f,
"Amount is neither user-provided nor defined in the provided Payjoin URI."
)
},
Self::PayjoinRequestCreationFailed => {
write!(f, "Failed construct a Payjoin request")
},
Self::PayjoinUriInvalid => {
write!(f, "The provided Payjoin URI is invalid")
},
Self::PayjoinRequestSendingFailed => {
write!(f, "Failed to send Payjoin request")
},
Self::PayjoinResponseProcessingFailed => {
write!(f, "Payjoin receiver responded to our request with an invalid response")
},
}
}
}
Expand Down
Loading

0 comments on commit ac0e23e

Please sign in to comment.