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 15, 2024
1 parent 8dd3790 commit a7779e0
Show file tree
Hide file tree
Showing 14 changed files with 985 additions and 6 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,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 Down
32 changes: 32 additions & 0 deletions bindings/ldk_node.udl
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ interface Node {
Bolt12Payment bolt12_payment();
SpontaneousPayment spontaneous_payment();
OnchainPayment onchain_payment();
PayjoinPayment payjoin_payment();
[Throws=NodeError]
void connect(PublicKey node_id, SocketAddress address, boolean persist);
[Throws=NodeError]
Expand Down Expand Up @@ -148,6 +149,13 @@ interface OnchainPayment {
Txid send_all_to_address([ByRef]Address address);
};

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 @@ -196,6 +204,12 @@ enum NodeError {
"InsufficientFunds",
"LiquiditySourceUnavailable",
"LiquidityFeeTooHigh",
"PayjoinUnavailable",
"PayjoinUriInvalid",
"PayjoinRequestMissingAmount",
"PayjoinRequestCreationFailed",
"PayjoinRequestSendingFailed",
"PayjoinResponseProcessingFailed",
};

dictionary NodeStatus {
Expand Down Expand Up @@ -227,6 +241,7 @@ enum BuildError {
"KVStoreSetupFailed",
"WalletSetupFailed",
"LoggerSetupFailed",
"InvalidPayjoinConfig",
};

[Enum]
Expand All @@ -238,6 +253,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, ScriptBuf receipient);
PayjoinPaymentBroadcasted(Txid txid, u64 amount, ScriptBuf receipient);
PayjoinPaymentSuccess(Txid txid, u64 amount, ScriptBuf receipient);
PayjoinPaymentFailed(Txid txid, u64 amount, ScriptBuf receipient, PayjoinPaymentFailureReason reason);
PayjoinPaymentBroadcastedByReceiver(Txid txid, u64 amount, ScriptBuf receipient);
};

enum PaymentFailureReason {
Expand All @@ -249,6 +269,14 @@ enum PaymentFailureReason {
"UnexpectedError",
};

enum PayjoinPaymentFailureReason {
"Timeout",
"TransactionFinalisationFailed",
"InvalidReceiverResponse",
"RequestFailed",
"ResponseProcessingFailed"
};

[Enum]
interface ClosureReason {
CounterpartyForceClosed(UntrustedString peer_msg);
Expand All @@ -274,6 +302,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 PaymentDirection {
Expand Down Expand Up @@ -499,3 +528,6 @@ typedef string Mnemonic;

[Custom]
typedef string UntrustedString;

[Custom]
typedef string ScriptBuf;
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 payjoin sender requests timeout.
pub(crate) const PAYJOIN_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);

// The time before payjoin sender try to send the next request.
pub(crate) const PAYJOIN_RETRY_INTERVAL: Duration = Duration::from_secs(3);

// The total time payjoin sender try to send a 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
33 changes: 33 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,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 @@ -162,6 +174,27 @@ 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 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 that was ignored")
},
}
}
}
Expand Down
Loading

0 comments on commit a7779e0

Please sign in to comment.