Registry Mirror
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter
Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"] }

Expand Down
9 changes: 9 additions & 0 deletions bindings/ldk_node.udl
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -145,6 +146,8 @@ interface FeeRate {
u64 to_sat_per_vb_ceil();
};

typedef interface PayjoinPayment;

typedef interface Liquidity;

typedef interface ForwardingAnalytics;
Expand Down Expand Up @@ -177,6 +180,8 @@ enum NodeError {
"OnchainTxSigningFailed",
"TxSyncFailed",
"TxSyncTimeout",
"TxLookupFailed",
"TxLookupTimeout",
"GossipUpdateFailed",
"GossipUpdateTimeout",
"LiquidityRequestFailed",
Expand Down Expand Up @@ -220,6 +225,10 @@ enum NodeError {
"InvalidLnurl",
"ChainSourceNotSupported",
"InvalidPayerProof",
"PayjoinNotConfigured",
"PayjoinSessionCreationFailed",
"PayjoinSessionFailed",
"PayjoinSessionNotCancellable",
};

typedef dictionary NodeStatus;
Expand Down
142 changes: 138 additions & 4 deletions src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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};
Expand All @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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.")
},
}
}
}
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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());

Expand All @@ -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(
Expand Down Expand Up @@ -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),
),
)
});

Expand Down Expand Up @@ -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<dyn ProbingStrategy> = match &probing_cfg.kind {
ProbingStrategyKind::HighDegree { top_node_count } => {
Expand Down Expand Up @@ -2685,6 +2798,7 @@ fn build_with_store_internal(
prober,
#[cfg(cycle_tests)]
_leak_checker,
payjoin_manager,
})
}

Expand Down Expand Up @@ -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;
Expand Down
Loading