Skip to content

Commit 0be8a1b

Browse files
authored
Merge pull request #116 from wpaulino/anchors
Add support for opening anchor outputs channels
2 parents d69af92 + e586047 commit 0be8a1b

File tree

4 files changed

+166
-19
lines changed

4 files changed

+166
-19
lines changed

src/bitcoind_client.rs

Lines changed: 68 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,19 @@
11
use crate::convert::{
2-
BlockchainInfo, FeeResponse, FundedTx, MempoolMinFeeResponse, NewAddress, RawTx, SignedTx,
2+
BlockchainInfo, FeeResponse, FundedTx, ListUnspentResponse, MempoolMinFeeResponse, NewAddress,
3+
RawTx, SignedTx,
34
};
45
use crate::disk::FilesystemLogger;
6+
use crate::hex_utils;
57
use base64;
8+
use bitcoin::blockdata::constants::WITNESS_SCALE_FACTOR;
69
use bitcoin::blockdata::transaction::Transaction;
7-
use bitcoin::consensus::encode;
10+
use bitcoin::consensus::{encode, Decodable, Encodable};
811
use bitcoin::hash_types::{BlockHash, Txid};
9-
use bitcoin::util::address::Address;
12+
use bitcoin::hashes::Hash;
13+
use bitcoin::util::address::{Address, Payload, WitnessVersion};
14+
use bitcoin::{OutPoint, Script, TxOut, WPubkeyHash, XOnlyPublicKey};
1015
use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator};
16+
use lightning::events::bump_transaction::{Utxo, WalletSource};
1117
use lightning::log_error;
1218
use lightning::routing::utxo::{UtxoLookup, UtxoResult};
1319
use lightning::util::logger::Logger;
@@ -250,6 +256,13 @@ impl BitcoindClient {
250256
.await
251257
.unwrap()
252258
}
259+
260+
pub async fn list_unspent(&self) -> ListUnspentResponse {
261+
self.bitcoind_rpc_client
262+
.call_method::<ListUnspentResponse>("listunspent", &vec![])
263+
.await
264+
.unwrap()
265+
}
253266
}
254267

255268
impl FeeEstimator for BitcoindClient {
@@ -308,3 +321,55 @@ impl UtxoLookup for BitcoindClient {
308321
todo!();
309322
}
310323
}
324+
325+
impl WalletSource for BitcoindClient {
326+
fn list_confirmed_utxos(&self) -> Result<Vec<Utxo>, ()> {
327+
let utxos = tokio::task::block_in_place(move || {
328+
self.handle.block_on(async move { self.list_unspent().await }).0
329+
});
330+
Ok(utxos
331+
.into_iter()
332+
.filter_map(|utxo| {
333+
let outpoint = OutPoint { txid: utxo.txid, vout: utxo.vout };
334+
match utxo.address.payload {
335+
Payload::WitnessProgram { version, ref program } => match version {
336+
WitnessVersion::V0 => WPubkeyHash::from_slice(program)
337+
.map(|wpkh| Utxo::new_v0_p2wpkh(outpoint, utxo.amount, &wpkh))
338+
.ok(),
339+
// TODO: Add `Utxo::new_v1_p2tr` upstream.
340+
WitnessVersion::V1 => XOnlyPublicKey::from_slice(program)
341+
.map(|_| Utxo {
342+
outpoint,
343+
output: TxOut {
344+
value: utxo.amount,
345+
script_pubkey: Script::new_witness_program(version, program),
346+
},
347+
satisfaction_weight: 1 /* empty script_sig */ * WITNESS_SCALE_FACTOR as u64 +
348+
1 /* witness items */ + 1 /* schnorr sig len */ + 64, /* schnorr sig */
349+
})
350+
.ok(),
351+
_ => None,
352+
},
353+
_ => None,
354+
}
355+
})
356+
.collect())
357+
}
358+
359+
fn get_change_script(&self) -> Result<Script, ()> {
360+
tokio::task::block_in_place(move || {
361+
Ok(self.handle.block_on(async move { self.get_new_address().await.script_pubkey() }))
362+
})
363+
}
364+
365+
fn sign_tx(&self, tx: Transaction) -> Result<Transaction, ()> {
366+
let mut tx_bytes = Vec::new();
367+
let _ = tx.consensus_encode(&mut tx_bytes).map_err(|_| ());
368+
let tx_hex = hex_utils::hex_str(&tx_bytes);
369+
let signed_tx = tokio::task::block_in_place(move || {
370+
self.handle.block_on(async move { self.sign_raw_transaction_with_wallet(tx_hex).await })
371+
});
372+
let signed_tx_bytes = hex_utils::to_vec(&signed_tx.hex).ok_or(())?;
373+
Transaction::consensus_decode(&mut signed_tx_bytes.as_slice()).map_err(|_| ())
374+
}
375+
}

src/cli.rs

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ pub(crate) async fn poll_for_user_input(
9393
let peer_pubkey_and_ip_addr = words.next();
9494
let channel_value_sat = words.next();
9595
if peer_pubkey_and_ip_addr.is_none() || channel_value_sat.is_none() {
96-
println!("ERROR: openchannel has 2 required arguments: `openchannel pubkey@host:port channel_amt_satoshis` [--public]");
96+
println!("ERROR: openchannel has 2 required arguments: `openchannel pubkey@host:port channel_amt_satoshis` [--public] [--with-anchors]");
9797
continue;
9898
}
9999
let peer_pubkey_and_ip_addr = peer_pubkey_and_ip_addr.unwrap();
@@ -119,20 +119,25 @@ pub(crate) async fn poll_for_user_input(
119119
continue;
120120
};
121121

122-
let announce_channel = match words.next() {
123-
Some("--public") | Some("--public=true") => true,
124-
Some("--public=false") => false,
125-
Some(_) => {
126-
println!("ERROR: invalid `--public` command format. Valid formats: `--public`, `--public=true` `--public=false`");
127-
continue;
122+
let (mut announce_channel, mut with_anchors) = (false, false);
123+
while let Some(word) = words.next() {
124+
match word {
125+
"--public" | "--public=true" => announce_channel = true,
126+
"--public=false" => announce_channel = false,
127+
"--with-anchors" | "--with-anchors=true" => with_anchors = true,
128+
"--with-anchors=false" => with_anchors = false,
129+
_ => {
130+
println!("ERROR: invalid boolean flag format. Valid formats: `--option`, `--option=true` `--option=false`");
131+
continue;
132+
}
128133
}
129-
None => false,
130-
};
134+
}
131135

132136
if open_channel(
133137
pubkey,
134138
chan_amt_sat.unwrap(),
135139
announce_channel,
140+
with_anchors,
136141
channel_manager.clone(),
137142
)
138143
.is_ok()
@@ -455,7 +460,7 @@ fn help() {
455460
println!(" help\tShows a list of commands.");
456461
println!(" quit\tClose the application.");
457462
println!("\n Channels:");
458-
println!(" openchannel pubkey@host:port <amt_satoshis> [--public]");
463+
println!(" openchannel pubkey@host:port <amt_satoshis> [--public] [--with-anchors]");
459464
println!(" closechannel <channel_id> <peer_pubkey>");
460465
println!(" forceclosechannel <channel_id> <peer_pubkey>");
461466
println!(" listchannels");
@@ -638,7 +643,7 @@ fn do_disconnect_peer(
638643
}
639644

640645
fn open_channel(
641-
peer_pubkey: PublicKey, channel_amt_sat: u64, announced_channel: bool,
646+
peer_pubkey: PublicKey, channel_amt_sat: u64, announced_channel: bool, with_anchors: bool,
642647
channel_manager: Arc<ChannelManager>,
643648
) -> Result<(), ()> {
644649
let config = UserConfig {
@@ -649,6 +654,7 @@ fn open_channel(
649654
},
650655
channel_handshake_config: ChannelHandshakeConfig {
651656
announced_channel,
657+
negotiate_anchors_zero_fee_htlc_tx: with_anchors,
652658
..Default::default()
653659
},
654660
..Default::default()

src/convert.rs

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
use bitcoin::hashes::hex::FromHex;
2-
use bitcoin::BlockHash;
2+
use bitcoin::{Address, BlockHash, Txid};
33
use lightning_block_sync::http::JsonResponse;
44
use std::convert::TryInto;
5+
use std::str::FromStr;
56

67
pub struct FundedTx {
78
pub changepos: i64,
@@ -116,3 +117,33 @@ impl TryInto<BlockchainInfo> for JsonResponse {
116117
})
117118
}
118119
}
120+
121+
pub struct ListUnspentUtxo {
122+
pub txid: Txid,
123+
pub vout: u32,
124+
pub amount: u64,
125+
pub address: Address,
126+
}
127+
128+
pub struct ListUnspentResponse(pub Vec<ListUnspentUtxo>);
129+
130+
impl TryInto<ListUnspentResponse> for JsonResponse {
131+
type Error = std::io::Error;
132+
fn try_into(self) -> Result<ListUnspentResponse, Self::Error> {
133+
let utxos = self
134+
.0
135+
.as_array()
136+
.unwrap()
137+
.iter()
138+
.map(|utxo| ListUnspentUtxo {
139+
txid: Txid::from_str(&utxo["txid"].as_str().unwrap().to_string()).unwrap(),
140+
vout: utxo["vout"].as_u64().unwrap() as u32,
141+
amount: bitcoin::Amount::from_btc(utxo["amount"].as_f64().unwrap())
142+
.unwrap()
143+
.to_sat(),
144+
address: Address::from_str(&utxo["address"].as_str().unwrap().to_string()).unwrap(),
145+
})
146+
.collect();
147+
Ok(ListUnspentResponse(utxos))
148+
}
149+
}

src/main.rs

Lines changed: 49 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ use bitcoin_bech32::WitnessProgram;
1616
use disk::{INBOUND_PAYMENTS_FNAME, OUTBOUND_PAYMENTS_FNAME};
1717
use lightning::chain::{chainmonitor, ChannelMonitorUpdateStatus};
1818
use lightning::chain::{Filter, Watch};
19+
use lightning::events::bump_transaction::{BumpTransactionEventHandler, Wallet};
1920
use lightning::events::{Event, PaymentFailureReason, PaymentPurpose};
2021
use lightning::ln::channelmanager::{self, RecentPaymentDetails};
2122
use lightning::ln::channelmanager::{
@@ -141,10 +142,17 @@ pub(crate) type NetworkGraph = gossip::NetworkGraph<Arc<FilesystemLogger>>;
141142

142143
type OnionMessenger = SimpleArcOnionMessenger<FilesystemLogger>;
143144

145+
pub(crate) type BumpTxEventHandler = BumpTransactionEventHandler<
146+
Arc<BitcoindClient>,
147+
Arc<Wallet<Arc<BitcoindClient>, Arc<FilesystemLogger>>>,
148+
Arc<KeysManager>,
149+
Arc<FilesystemLogger>,
150+
>;
151+
144152
async fn handle_ldk_events(
145153
channel_manager: &Arc<ChannelManager>, bitcoind_client: &BitcoindClient,
146154
network_graph: &NetworkGraph, keys_manager: &KeysManager,
147-
inbound_payments: Arc<Mutex<PaymentInfoStorage>>,
155+
bump_tx_event_handler: &BumpTxEventHandler, inbound_payments: Arc<Mutex<PaymentInfoStorage>>,
148156
outbound_payments: Arc<Mutex<PaymentInfoStorage>>, persister: &Arc<FilesystemPersister>,
149157
network: Network, event: Event,
150158
) {
@@ -278,8 +286,34 @@ async fn handle_ldk_events(
278286
}
279287
persister.persist(OUTBOUND_PAYMENTS_FNAME, &*outbound).unwrap();
280288
}
281-
Event::OpenChannelRequest { .. } => {
282-
// Unreachable, we don't set manually_accept_inbound_channels
289+
Event::OpenChannelRequest {
290+
ref temporary_channel_id, ref counterparty_node_id, ..
291+
} => {
292+
let mut random_bytes = [0u8; 16];
293+
random_bytes.copy_from_slice(&keys_manager.get_secure_random_bytes()[..16]);
294+
let user_channel_id = u128::from_be_bytes(random_bytes);
295+
let res = channel_manager.accept_inbound_channel(
296+
temporary_channel_id,
297+
counterparty_node_id,
298+
user_channel_id,
299+
);
300+
301+
if let Err(e) = res {
302+
print!(
303+
"\nEVENT: Failed to accept inbound channel ({}) from {}: {:?}",
304+
hex_utils::hex_str(&temporary_channel_id[..]),
305+
hex_utils::hex_str(&counterparty_node_id.serialize()),
306+
e,
307+
);
308+
} else {
309+
print!(
310+
"\nEVENT: Accepted inbound channel ({}) from {}",
311+
hex_utils::hex_str(&temporary_channel_id[..]),
312+
hex_utils::hex_str(&counterparty_node_id.serialize()),
313+
);
314+
}
315+
print!("> ");
316+
io::stdout().flush().unwrap();
283317
}
284318
Event::PaymentPathSuccessful { .. } => {}
285319
Event::PaymentPathFailed { .. } => {}
@@ -429,7 +463,7 @@ async fn handle_ldk_events(
429463
// the funding transaction either confirms, or this event is generated.
430464
}
431465
Event::HTLCIntercepted { .. } => {}
432-
Event::BumpTransaction(_) => {}
466+
Event::BumpTransaction(event) => bump_tx_event_handler.handle_event(&event),
433467
}
434468
}
435469

@@ -532,6 +566,13 @@ async fn start_ldk() {
532566
let cur = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
533567
let keys_manager = Arc::new(KeysManager::new(&keys_seed, cur.as_secs(), cur.subsec_nanos()));
534568

569+
let bump_tx_event_handler = Arc::new(BumpTransactionEventHandler::new(
570+
Arc::clone(&broadcaster),
571+
Arc::new(Wallet::new(Arc::clone(&bitcoind_client), Arc::clone(&logger))),
572+
Arc::clone(&keys_manager),
573+
Arc::clone(&logger),
574+
));
575+
535576
// Step 7: Read ChannelMonitor state from disk
536577
let mut channelmonitors =
537578
persister.read_channelmonitors(keys_manager.clone(), keys_manager.clone()).unwrap();
@@ -566,6 +607,8 @@ async fn start_ldk() {
566607
// Step 11: Initialize the ChannelManager
567608
let mut user_config = UserConfig::default();
568609
user_config.channel_handshake_limits.force_announced_channel_preference = false;
610+
user_config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
611+
user_config.manually_accept_inbound_channels = true;
569612
let mut restarting_node = true;
570613
let (channel_manager_blockhash, channel_manager) = {
571614
if let Ok(mut f) = fs::File::open(format!("{}/manager", ldk_data_dir.clone())) {
@@ -778,6 +821,7 @@ async fn start_ldk() {
778821
let bitcoind_client_event_listener = Arc::clone(&bitcoind_client_event_listener);
779822
let network_graph_event_listener = Arc::clone(&network_graph_event_listener);
780823
let keys_manager_event_listener = Arc::clone(&keys_manager_event_listener);
824+
let bump_tx_event_handler = Arc::clone(&bump_tx_event_handler);
781825
let inbound_payments_event_listener = Arc::clone(&inbound_payments_event_listener);
782826
let outbound_payments_event_listener = Arc::clone(&outbound_payments_event_listener);
783827
let persister_event_listener = Arc::clone(&persister_event_listener);
@@ -787,6 +831,7 @@ async fn start_ldk() {
787831
&bitcoind_client_event_listener,
788832
&network_graph_event_listener,
789833
&keys_manager_event_listener,
834+
&bump_tx_event_handler,
790835
inbound_payments_event_listener,
791836
outbound_payments_event_listener,
792837
&persister_event_listener,

0 commit comments

Comments
 (0)