Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Payjoin integration #257

Closed
wants to merge 11 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 28 additions & 12 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,28 @@ panic = 'abort' # Abort on panic
default = []

[dependencies]
lightning = { version = "0.0.123", features = ["std"] }
lightning-invoice = { version = "0.31.0" }
lightning-net-tokio = { version = "0.0.123" }
lightning-persister = { version = "0.0.123" }
lightning-background-processor = { version = "0.0.123", features = ["futures"] }
lightning-rapid-gossip-sync = { version = "0.0.123" }
lightning-transaction-sync = { version = "0.0.123", features = ["esplora-async-https", "time"] }
lightning-liquidity = { version = "0.1.0-alpha.4", features = ["std"] }

# lightning = { version = "0.0.123", features = ["std"] }
# lightning-invoice = { version = "0.31.0" }
# lightning-net-tokio = { version = "0.0.123" }
# lightning-persister = { version = "0.0.123" }
# lightning-background-processor = { version = "0.0.123", features = ["futures"] }
# lightning-rapid-gossip-sync = { version = "0.0.123" }
# lightning-transaction-sync = { version = "0.0.123", features = ["esplora-async-https", "time"] }
# lightning-liquidity = { version = "0.1.0-alpha.4", features = ["std"] }
lightning = { git = "https://github.com/jbesraa/rust-lightning", branch = "danger-funding-generated", features = ["std"] }
lightning-invoice = { git = "https://github.com/jbesraa/rust-lightning", branch = "danger-funding-generated" }
lightning-net-tokio = { git = "https://github.com/jbesraa/rust-lightning", branch = "danger-funding-generated" }
lightning-persister = { git = "https://github.com/jbesraa/rust-lightning", branch = "danger-funding-generated" }
lightning-background-processor = { git = "https://github.com/jbesraa/rust-lightning", branch = "danger-funding-generated", features = ["futures"] }
lightning-rapid-gossip-sync = { git = "https://github.com/jbesraa/rust-lightning", branch = "danger-funding-generated" }
lightning-transaction-sync = { git = "https://github.com/jbesraa/rust-lightning", branch = "danger-funding-generated", features = ["esplora-async-https", "time"] }
#lightning-liquidity = { version = "0.1.0-alpha.1", features = ["std"] }

# lightning-liquidity = {path = "../../lightning-liquidity" git = "https://github.com/jbesraa/lightning-liquidity", rev = "b6ac60d", features = ["std"] }
lightning-liquidity = { git = "https://github.com/jbesraa/lightning-liquidity", branch = "pj-fixes", features = ["std"] }
# lightning-liquidity = { git = "https://github.com/tnull/lightning-liquidity", rev = "abf7088c0e03221c0f122e797f34802c9e99a3d4", features = ["std"] }

# payjoin = { git = "https://github.com/jbesraa/rust-payjoin.git", rev = "9e4f454", features = ["v2", "receive", "send"] }
#lightning = { git = "https://github.com/lightningdevkit/rust-lightning", branch="main", features = ["std"] }
#lightning-invoice = { git = "https://github.com/lightningdevkit/rust-lightning", branch="main" }
#lightning-net-tokio = { git = "https://github.com/lightningdevkit/rust-lightning", branch="main" }
Expand All @@ -57,9 +70,9 @@ lightning-liquidity = { version = "0.1.0-alpha.4", features = ["std"] }

bdk = { version = "0.29.0", default-features = false, features = ["std", "async-interface", "use-esplora-async", "sqlite-bundled", "keys-bip39"]}

reqwest = { version = "0.11", default-features = false, features = ["json", "rustls-tls"] }
reqwest = { version = "0.11", default-features = false, features = ["json", "rustls-tls", "blocking"] }
rusqlite = { version = "0.28.0", features = ["bundled"] }
bitcoin = "0.30.2"
bitcoin = { version = "0.30.2", features = ["bitcoinconsensus"] }
bip39 = "2.0.0"

rand = "0.8.5"
Expand All @@ -68,6 +81,7 @@ tokio = { version = "1", default-features = false, features = [ "rt-multi-thread
esplora-client = { version = "0.6", default-features = false }
libc = "0.2"
uniffi = { version = "0.26.0", features = ["build"], optional = true }
payjoin = { version = "0.15.0", features = ["v2", "send", "receive"] }

[target.'cfg(vss)'.dependencies]
vss-client = "0.2"
Expand All @@ -77,12 +91,14 @@ prost = { version = "0.11.6", default-features = false}
winapi = { version = "0.3", features = ["winbase"] }

[dev-dependencies]
lightning = { version = "0.0.123", features = ["std", "_test_utils"] }
# lightning = { version = "0.0.123", features = ["std", "_test_utils"] }
lightning = { git = "https://github.com/jbesraa/rust-lightning", branch = "danger-funding-generated", features = ["std", "_test_utils"] }
#lightning = { git = "https://github.com/lightningdevkit/rust-lightning", branch="main", features = ["std", "_test_utils"] }
electrum-client = { version = "0.15.1", default-features = true }
bitcoincore-rpc = { version = "0.17.0", default-features = false }
proptest = "1.0.0"
regex = "1.5.6"
reqwest = { version = "0.11", default-features = false, features = ["blocking"] }

[target.'cfg(not(no_download))'.dev-dependencies]
electrsd = { version = "0.26.0", features = ["legacy", "esplora_a33e97e1", "bitcoind_25_0"] }
Expand Down
7 changes: 7 additions & 0 deletions bindings/ldk_node.udl
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,13 @@ enum NodeError {
"InsufficientFunds",
"LiquiditySourceUnavailable",
"LiquidityFeeTooHigh",
"PayjoinReqwest",
"PayjoinValidation",
"PayjoinEnrollment",
"PayjoinUri",
"PayjoinReceiver",
"PayjoinSender",
"BitcoinConsensusFailed",
};

dictionary NodeStatus {
Expand Down
113 changes: 113 additions & 0 deletions src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ 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::payjoin_receiver::{
enroll_payjoin_receivers, PayjoinLightningReceiver, PayjoinReceiver,
};
use crate::payjoin_scheduler::PayjoinScheduler;
use crate::payjoin_sender::PayjoinSender;
use crate::payment::store::PaymentStore;
use crate::peer_store::PeerStore;
use crate::tx_broadcaster::TransactionBroadcaster;
Expand Down Expand Up @@ -94,6 +99,18 @@ struct LiquiditySourceConfig {
lsps2_service: Option<(SocketAddress, PublicKey, Option<String>)>,
}

#[derive(Debug, Clone)]
struct PayjoinReceiverConfig {
payjoin_directory: payjoin::Url,
payjoin_relay: payjoin::Url,
ohttp_keys: Option<payjoin::OhttpKeys>,
}

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

impl Default for LiquiditySourceConfig {
fn default() -> Self {
Self { lsps2_service: None }
Expand Down Expand Up @@ -173,6 +190,8 @@ pub struct NodeBuilder {
chain_data_source_config: Option<ChainDataSourceConfig>,
gossip_source_config: Option<GossipSourceConfig>,
liquidity_source_config: Option<LiquiditySourceConfig>,
payjoin_receiver_config: Option<PayjoinReceiverConfig>,
payjoin_sender_config: Option<PayjoinSenderConfig>,
}

impl NodeBuilder {
Expand All @@ -188,12 +207,16 @@ impl NodeBuilder {
let chain_data_source_config = None;
let gossip_source_config = None;
let liquidity_source_config = None;
let payjoin_receiver_config = None;
let payjoin_sender_config = None;
Self {
config,
entropy_source_config,
chain_data_source_config,
gossip_source_config,
liquidity_source_config,
payjoin_receiver_config,
payjoin_sender_config,
}
}

Expand Down Expand Up @@ -248,6 +271,24 @@ impl NodeBuilder {
self
}

/// Configures the [`Node`] instance to source its gossip data from the given RapidGossipSync
/// server.
pub fn set_payjoin_sender_config(&mut self, payjoin_relay: payjoin::Url) -> &mut Self {
self.payjoin_sender_config = Some(PayjoinSenderConfig { payjoin_relay });
self
}

/// Configures the [`Node`] instance to source its gossip data from the given RapidGossipSync
/// server.
pub fn set_payjoin_receiver_config(
&mut self, payjoin_directory: payjoin::Url, payjoin_relay: payjoin::Url,
ohttp_keys: Option<payjoin::OhttpKeys>,
) -> &mut Self {
self.payjoin_receiver_config =
Some(PayjoinReceiverConfig { payjoin_directory, payjoin_relay, ohttp_keys });
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 @@ -369,6 +410,8 @@ impl NodeBuilder {
seed_bytes,
logger,
vss_store,
self.payjoin_receiver_config.as_ref(),
self.payjoin_sender_config.as_ref(),
)
}

Expand All @@ -390,6 +433,8 @@ impl NodeBuilder {
seed_bytes,
logger,
kv_store,
self.payjoin_receiver_config.as_ref(),
self.payjoin_sender_config.as_ref(),
)
}
}
Expand Down Expand Up @@ -454,6 +499,23 @@ impl ArcedNodeBuilder {
self.inner.write().unwrap().set_gossip_source_p2p();
}

/// payjoin sender config
pub fn set_payjoin_sender_config(&self, payjoin_relay: payjoin::Url) {
self.inner.write().unwrap().set_payjoin_sender_config(payjoin_relay);
}

/// payjoin receiver config
pub fn set_payjoin_receiver_config(
&self, payjoin_directory: payjoin::Url, payjoin_relay: payjoin::Url,
ohttp_keys: Option<payjoin::OhttpKeys>,
) {
self.inner.write().unwrap().set_payjoin_receiver_config(
payjoin_directory,
payjoin_relay,
ohttp_keys,
);
}

/// 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 @@ -524,6 +586,8 @@ fn build_with_store_internal(
gossip_source_config: Option<&GossipSourceConfig>,
liquidity_source_config: Option<&LiquiditySourceConfig>, seed_bytes: [u8; 64],
logger: Arc<FilesystemLogger>, kv_store: Arc<DynStore>,
payjoin_receiver_config: Option<&PayjoinReceiverConfig>,
payjoin_sender_config: Option<&PayjoinSenderConfig>,
) -> 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 @@ -556,6 +620,7 @@ fn build_with_store_internal(
log_error!(logger, "Failed to set up wallet: {}", e);
BuildError::WalletSetupFailed
})?;
let payjoin_scheduler = Arc::new(tokio::sync::Mutex::new(PayjoinScheduler::new()));

let (blockchain, tx_sync, tx_broadcaster, fee_estimator) = match chain_data_source_config {
Some(ChainDataSourceConfig::Esplora(server_url)) => {
Expand All @@ -566,6 +631,7 @@ fn build_with_store_internal(
let tx_broadcaster = Arc::new(TransactionBroadcaster::new(
tx_sync.client().clone(),
Arc::clone(&logger),
Arc::clone(&payjoin_scheduler),
));
let fee_estimator = Arc::new(OnchainFeeEstimator::new(
tx_sync.client().clone(),
Expand All @@ -584,6 +650,7 @@ fn build_with_store_internal(
let tx_broadcaster = Arc::new(TransactionBroadcaster::new(
tx_sync.client().clone(),
Arc::clone(&logger),
Arc::clone(&payjoin_scheduler),
));
let fee_estimator = Arc::new(OnchainFeeEstimator::new(
tx_sync.client().clone(),
Expand Down Expand Up @@ -973,6 +1040,49 @@ fn build_with_store_internal(
};

let (stop_sender, _) = tokio::sync::watch::channel(());
let payjoin_sender = if let Some(payjoin_sender_config) = payjoin_sender_config {
let payjoin_sender = PayjoinSender::new(
Arc::clone(&logger),
Arc::clone(&wallet),
&payjoin_sender_config.payjoin_relay,
);
Some(Arc::new(payjoin_sender))
} else {
None
};
let (payjoin_receiver, payjoin_lightning_receiver) =
if let Some(payjoin_receiver_config) = payjoin_receiver_config {
let enrollement = enroll_payjoin_receivers(
&payjoin_receiver_config.ohttp_keys,
&payjoin_receiver_config.payjoin_directory,
&payjoin_receiver_config.payjoin_relay,
)
.ok();
if let Some(enrollement) = enrollement {
let (payjoin_enrollement, lightning_enrollement, ohttp_keys) = enrollement;
dbg!("Enrolled payjoin receiver");
let payjoin_receiver = PayjoinReceiver::new(
Arc::clone(&logger),
Arc::clone(&wallet),
payjoin_enrollement,
ohttp_keys.clone(),
);

let payjoin_lightning_receiver = PayjoinLightningReceiver::new(
Arc::clone(&logger),
Arc::clone(&wallet),
Arc::clone(&channel_manager),
Arc::clone(&payjoin_scheduler),
lightning_enrollement,
ohttp_keys,
);
(Some(Arc::new(payjoin_receiver)), Some(Arc::new(payjoin_lightning_receiver)))
} else {
(None, None)
}
} else {
(None, None)
};

let is_listening = Arc::new(AtomicBool::new(false));
let latest_wallet_sync_timestamp = Arc::new(RwLock::new(None));
Expand All @@ -993,6 +1103,9 @@ fn build_with_store_internal(
channel_manager,
chain_monitor,
output_sweeper,
payjoin_receiver,
payjoin_sender,
payjoin_lightning_receiver,
peer_manager,
connection_manager,
keys_manager,
Expand Down
27 changes: 27 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,20 @@ pub enum Error {
LiquiditySourceUnavailable,
/// The given operation failed due to the LSP's required opening fee being too high.
LiquidityFeeTooHigh,
/// Payjoin errors
PayjoinReqwest,
/// Payjoin errors
PayjoinValidation,
/// Payjoin errors
PayjoinEnrollment,
/// Payjoin errors
PayjoinUri,
/// Payjoin errors
PayjoinReceiver,
/// Payjoin errors
PayjoinSender,
/// Payjoin errors
BitcoinConsensusFailed,
}

impl fmt::Display for Error {
Expand Down Expand Up @@ -122,10 +136,23 @@ 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::PayjoinReqwest => write!(f, "PayjoinLightning: http error"),
Self::PayjoinValidation => write!(f, "PayjoinLightning: payjoin request validation failed."),
Self::PayjoinEnrollment => write!(f, "PayjoinLightning: payjoin enrollment failed. Maybe the configured payjoin directory or payjoin relay are not valid?"),
Self::PayjoinUri => write!(f, "PayjoinLightning: Failed to construct payjoin URI."),
Self::PayjoinSender => write!(f, "Failed to send payjoin."),
Self::PayjoinReceiver => write!(f, "Failed to receive payjoin."),
Self::BitcoinConsensusFailed => write!(f, "Bitcoin consensus failed."),
}
}
}

impl From<payjoin::Error> for Error {
fn from(_e: payjoin::Error) -> Self {
return Self::PayjoinValidation;
}
}

impl std::error::Error for Error {}

impl From<bdk::Error> for Error {
Expand Down
Loading
Loading