Skip to content

Commit 2087032

Browse files
authored
Merge pull request #620 from TheBlueMatt/2020-05-pre-bindings-cleanups
Pre-C Bindings Cleanup
2 parents 9dbce1c + ba06507 commit 2087032

14 files changed

+288
-311
lines changed

fuzz/src/chanmon_consistency.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,9 @@ impl TestChannelMonitor {
9696
}
9797
}
9898
}
99-
impl channelmonitor::ManyChannelMonitor<EnforcingChannelKeys> for TestChannelMonitor {
99+
impl channelmonitor::ManyChannelMonitor for TestChannelMonitor {
100+
type Keys = EnforcingChannelKeys;
101+
100102
fn add_monitor(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<EnforcingChannelKeys>) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
101103
let mut ser = VecWriter(Vec::new());
102104
monitor.write_for_disk(&mut ser).unwrap();
@@ -196,7 +198,7 @@ pub fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
196198
config.channel_options.fee_proportional_millionths = 0;
197199
config.channel_options.announced_channel = true;
198200
config.peer_channel_config_limits.min_dust_limit_satoshis = 0;
199-
(Arc::new(ChannelManager::new(Network::Bitcoin, fee_est.clone(), monitor.clone(), broadcast.clone(), Arc::clone(&logger), keys_manager.clone(), config, 0).unwrap()),
201+
(Arc::new(ChannelManager::new(Network::Bitcoin, fee_est.clone(), monitor.clone(), broadcast.clone(), Arc::clone(&logger), keys_manager.clone(), config, 0)),
200202
monitor)
201203
} }
202204
}
@@ -268,7 +270,7 @@ pub fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
268270
let tx = Transaction { version: $chan_id, lock_time: 0, input: Vec::new(), output: vec![TxOut {
269271
value: *channel_value_satoshis, script_pubkey: output_script.clone(),
270272
}]};
271-
funding_output = OutPoint::new(tx.txid(), 0);
273+
funding_output = OutPoint { txid: tx.txid(), index: 0 };
272274
$source.funding_transaction_generated(&temporary_channel_id, funding_output);
273275
channel_txn.push(tx);
274276
} else { panic!("Wrong event type"); }

fuzz/src/full_stack.rs

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -134,10 +134,17 @@ impl<'a> std::hash::Hash for Peer<'a> {
134134
}
135135
}
136136

137+
type ChannelMan = ChannelManager<
138+
EnforcingChannelKeys,
139+
Arc<channelmonitor::SimpleManyChannelMonitor<OutPoint, EnforcingChannelKeys, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>, Arc<ChainWatchInterfaceUtil>>>,
140+
Arc<TestBroadcaster>, Arc<KeyProvider>, Arc<FuzzEstimator>, Arc<dyn Logger>>;
141+
type PeerMan<'a> = PeerManager<Peer<'a>, Arc<ChannelMan>, Arc<NetGraphMsgHandler<Arc<ChainWatchInterfaceUtil>, Arc<dyn Logger>>>, Arc<dyn Logger>>;
142+
137143
struct MoneyLossDetector<'a> {
138-
manager: Arc<ChannelManager<EnforcingChannelKeys, Arc<channelmonitor::SimpleManyChannelMonitor<OutPoint, EnforcingChannelKeys, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>, Arc<ChainWatchInterfaceUtil>>>, Arc<TestBroadcaster>, Arc<KeyProvider>, Arc<FuzzEstimator>, Arc<dyn Logger>>>,
139-
monitor: Arc<channelmonitor::SimpleManyChannelMonitor<OutPoint, EnforcingChannelKeys, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>, Arc<ChainWatchInterfaceUtil>>>,
140-
handler: PeerManager<Peer<'a>, Arc<ChannelManager<EnforcingChannelKeys, Arc<channelmonitor::SimpleManyChannelMonitor<OutPoint, EnforcingChannelKeys, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>, Arc<ChainWatchInterfaceUtil>>>, Arc<TestBroadcaster>, Arc<KeyProvider>, Arc<FuzzEstimator>, Arc<dyn Logger>>>, Arc<dyn Logger>>,
144+
manager: Arc<ChannelMan>,
145+
monitor: Arc<channelmonitor::SimpleManyChannelMonitor<
146+
OutPoint, EnforcingChannelKeys, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>, Arc<ChainWatchInterfaceUtil>>>,
147+
handler: PeerMan<'a>,
141148

142149
peers: &'a RefCell<[bool; 256]>,
143150
funding_txn: Vec<Transaction>,
@@ -149,9 +156,9 @@ struct MoneyLossDetector<'a> {
149156
}
150157
impl<'a> MoneyLossDetector<'a> {
151158
pub fn new(peers: &'a RefCell<[bool; 256]>,
152-
manager: Arc<ChannelManager<EnforcingChannelKeys, Arc<channelmonitor::SimpleManyChannelMonitor<OutPoint, EnforcingChannelKeys, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>, Arc<ChainWatchInterfaceUtil>>>, Arc<TestBroadcaster>, Arc<KeyProvider>, Arc<FuzzEstimator>, Arc<dyn Logger>>>,
159+
manager: Arc<ChannelMan>,
153160
monitor: Arc<channelmonitor::SimpleManyChannelMonitor<OutPoint, EnforcingChannelKeys, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>, Arc<ChainWatchInterfaceUtil>>>,
154-
handler: PeerManager<Peer<'a>, Arc<ChannelManager<EnforcingChannelKeys, Arc<channelmonitor::SimpleManyChannelMonitor<OutPoint, EnforcingChannelKeys, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>, Arc<ChainWatchInterfaceUtil>>>, Arc<TestBroadcaster>, Arc<KeyProvider>, Arc<FuzzEstimator>, Arc<dyn Logger>>>, Arc<dyn Logger>>) -> Self {
161+
handler: PeerMan<'a>) -> Self {
155162
MoneyLossDetector {
156163
manager,
157164
monitor,
@@ -334,7 +341,7 @@ pub fn do_test(data: &[u8], logger: &Arc<dyn Logger>) {
334341
config.channel_options.fee_proportional_millionths = slice_to_be32(get_slice!(4));
335342
config.channel_options.announced_channel = get_slice!(1)[0] != 0;
336343
config.peer_channel_config_limits.min_dust_limit_satoshis = 0;
337-
let channelmanager = Arc::new(ChannelManager::new(Network::Bitcoin, fee_est.clone(), monitor.clone(), broadcast.clone(), Arc::clone(&logger), keys_manager.clone(), config, 0).unwrap());
344+
let channelmanager = Arc::new(ChannelManager::new(Network::Bitcoin, fee_est.clone(), monitor.clone(), broadcast.clone(), Arc::clone(&logger), keys_manager.clone(), config, 0));
338345
let our_id = PublicKey::from_secret_key(&Secp256k1::signing_only(), &keys_manager.get_node_secret());
339346
let net_graph_msg_handler = Arc::new(NetGraphMsgHandler::new(watch.clone(), Arc::clone(&logger)));
340347

@@ -478,7 +485,7 @@ pub fn do_test(data: &[u8], logger: &Arc<dyn Logger>) {
478485
let funding_output = 'search_loop: loop {
479486
let funding_txid = tx.txid();
480487
if let None = loss_detector.txids_confirmed.get(&funding_txid) {
481-
let outpoint = OutPoint::new(funding_txid, 0);
488+
let outpoint = OutPoint { txid: funding_txid, index: 0 };
482489
for chan in channelmanager.list_channels() {
483490
if chan.channel_id == outpoint.to_channel_id() {
484491
tx.version += 1;

lightning-net-tokio/src/lib.rs

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
//! type ChainWatchInterface = dyn lightning::chain::chaininterface::ChainWatchInterface;
2929
//! type ChannelMonitor = lightning::ln::channelmonitor::SimpleManyChannelMonitor<lightning::chain::transaction::OutPoint, lightning::chain::keysinterface::InMemoryChannelKeys, Arc<TxBroadcaster>, Arc<FeeEstimator>, Arc<Logger>, Arc<ChainWatchInterface>>;
3030
//! type ChannelManager = lightning::ln::channelmanager::SimpleArcChannelManager<ChannelMonitor, TxBroadcaster, FeeEstimator, Logger>;
31-
//! type PeerManager = lightning::ln::peer_handler::SimpleArcPeerManager<lightning_net_tokio::SocketDescriptor, ChannelMonitor, TxBroadcaster, FeeEstimator, Logger>;
31+
//! type PeerManager = lightning::ln::peer_handler::SimpleArcPeerManager<lightning_net_tokio::SocketDescriptor, ChannelMonitor, TxBroadcaster, FeeEstimator, ChainWatchInterface, Logger>;
3232
//!
3333
//! // Connect to node with pubkey their_node_id at addr:
3434
//! async fn connect_to_node(peer_manager: PeerManager, channel_monitor: Arc<ChannelMonitor>, channel_manager: ChannelManager, their_node_id: PublicKey, addr: SocketAddr) {
@@ -70,7 +70,7 @@ use tokio::io::{AsyncReadExt, AsyncWrite, AsyncWriteExt};
7070

7171
use lightning::ln::peer_handler;
7272
use lightning::ln::peer_handler::SocketDescriptor as LnSocketTrait;
73-
use lightning::ln::msgs::ChannelMessageHandler;
73+
use lightning::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler};
7474
use lightning::util::logger::Logger;
7575

7676
use std::{task, thread};
@@ -124,7 +124,10 @@ impl Connection {
124124
_ => panic!()
125125
}
126126
}
127-
async fn schedule_read<CMH: ChannelMessageHandler + 'static, L: Logger + 'static + ?Sized>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<L>>>, us: Arc<Mutex<Self>>, mut reader: io::ReadHalf<TcpStream>, mut read_wake_receiver: mpsc::Receiver<()>, mut write_avail_receiver: mpsc::Receiver<()>) {
127+
async fn schedule_read<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, us: Arc<Mutex<Self>>, mut reader: io::ReadHalf<TcpStream>, mut read_wake_receiver: mpsc::Receiver<()>, mut write_avail_receiver: mpsc::Receiver<()>) where
128+
CMH: ChannelMessageHandler + 'static,
129+
RMH: RoutingMessageHandler + 'static,
130+
L: Logger + 'static + ?Sized {
128131
let peer_manager_ref = peer_manager.clone();
129132
// 8KB is nice and big but also should never cause any issues with stack overflowing.
130133
let mut buf = [0; 8192];
@@ -234,7 +237,10 @@ impl Connection {
234237
/// not need to poll the provided future in order to make progress.
235238
///
236239
/// See the module-level documentation for how to handle the event_notify mpsc::Sender.
237-
pub fn setup_inbound<CMH: ChannelMessageHandler + 'static, L: Logger + 'static + ?Sized>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, stream: TcpStream) -> impl std::future::Future<Output=()> {
240+
pub fn setup_inbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, stream: TcpStream) -> impl std::future::Future<Output=()> where
241+
CMH: ChannelMessageHandler + 'static,
242+
RMH: RoutingMessageHandler + 'static,
243+
L: Logger + 'static + ?Sized {
238244
let (reader, write_receiver, read_receiver, us) = Connection::new(event_notify, stream);
239245
#[cfg(debug_assertions)]
240246
let last_us = Arc::clone(&us);
@@ -273,7 +279,10 @@ pub fn setup_inbound<CMH: ChannelMessageHandler + 'static, L: Logger + 'static +
273279
/// not need to poll the provided future in order to make progress.
274280
///
275281
/// See the module-level documentation for how to handle the event_notify mpsc::Sender.
276-
pub fn setup_outbound<CMH: ChannelMessageHandler + 'static, L: Logger + 'static + ?Sized>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, their_node_id: PublicKey, stream: TcpStream) -> impl std::future::Future<Output=()> {
282+
pub fn setup_outbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, their_node_id: PublicKey, stream: TcpStream) -> impl std::future::Future<Output=()> where
283+
CMH: ChannelMessageHandler + 'static,
284+
RMH: RoutingMessageHandler + 'static,
285+
L: Logger + 'static + ?Sized {
277286
let (reader, mut write_receiver, read_receiver, us) = Connection::new(event_notify, stream);
278287
#[cfg(debug_assertions)]
279288
let last_us = Arc::clone(&us);
@@ -342,7 +351,10 @@ pub fn setup_outbound<CMH: ChannelMessageHandler + 'static, L: Logger + 'static
342351
/// make progress.
343352
///
344353
/// See the module-level documentation for how to handle the event_notify mpsc::Sender.
345-
pub async fn connect_outbound<CMH: ChannelMessageHandler + 'static, L: Logger + 'static + ?Sized>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, their_node_id: PublicKey, addr: SocketAddr) -> Option<impl std::future::Future<Output=()>> {
354+
pub async fn connect_outbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, their_node_id: PublicKey, addr: SocketAddr) -> Option<impl std::future::Future<Output=()>> where
355+
CMH: ChannelMessageHandler + 'static,
356+
RMH: RoutingMessageHandler + 'static,
357+
L: Logger + 'static + ?Sized {
346358
if let Ok(Ok(stream)) = time::timeout(Duration::from_secs(10), TcpStream::connect(&addr)).await {
347359
Some(setup_outbound(peer_manager, event_notify, their_node_id, stream))
348360
} else { None }
@@ -568,7 +580,7 @@ mod tests {
568580
});
569581
let a_manager = Arc::new(PeerManager::new(MessageHandler {
570582
chan_handler: Arc::clone(&a_handler),
571-
route_handler: Arc::clone(&a_handler) as Arc<dyn RoutingMessageHandler>,
583+
route_handler: Arc::clone(&a_handler),
572584
}, a_key.clone(), &[1; 32], Arc::new(TestLogger())));
573585

574586
let (b_connected_sender, mut b_connected) = mpsc::channel(1);
@@ -581,7 +593,7 @@ mod tests {
581593
});
582594
let b_manager = Arc::new(PeerManager::new(MessageHandler {
583595
chan_handler: Arc::clone(&b_handler),
584-
route_handler: Arc::clone(&b_handler) as Arc<dyn RoutingMessageHandler>,
596+
route_handler: Arc::clone(&b_handler),
585597
}, b_key.clone(), &[2; 32], Arc::new(TestLogger())));
586598

587599
// We bind on localhost, hoping the environment is properly configured with a local

lightning/src/chain/keysinterface.rs

Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -167,28 +167,6 @@ impl Readable for SpendableOutputDescriptor {
167167
}
168168
}
169169

170-
/// A trait to describe an object which can get user secrets and key material.
171-
pub trait KeysInterface: Send + Sync {
172-
/// A type which implements ChannelKeys which will be returned by get_channel_keys.
173-
type ChanKeySigner : ChannelKeys;
174-
175-
/// Get node secret key (aka node_id or network_key)
176-
fn get_node_secret(&self) -> SecretKey;
177-
/// Get destination redeemScript to encumber static protocol exit points.
178-
fn get_destination_script(&self) -> Script;
179-
/// Get shutdown_pubkey to use as PublicKey at channel closure
180-
fn get_shutdown_pubkey(&self) -> PublicKey;
181-
/// Get a new set of ChannelKeys for per-channel secrets. These MUST be unique even if you
182-
/// restarted with some stale data!
183-
fn get_channel_keys(&self, inbound: bool, channel_value_satoshis: u64) -> Self::ChanKeySigner;
184-
/// Get a secret and PRNG seed for construting an onion packet
185-
fn get_onion_rand(&self) -> (SecretKey, [u8; 32]);
186-
/// Get a unique temporary channel id. Channels will be referred to by this until the funding
187-
/// transaction is created, at which point they will use the outpoint in the funding
188-
/// transaction.
189-
fn get_channel_id(&self) -> [u8; 32];
190-
}
191-
192170
/// Set of lightning keys needed to operate a channel as described in BOLT 3.
193171
///
194172
/// Signing services could be implemented on a hardware wallet. In this case,
@@ -341,6 +319,28 @@ pub trait ChannelKeys : Send+Clone {
341319
fn set_remote_channel_pubkeys(&mut self, channel_points: &ChannelPublicKeys);
342320
}
343321

322+
/// A trait to describe an object which can get user secrets and key material.
323+
pub trait KeysInterface: Send + Sync {
324+
/// A type which implements ChannelKeys which will be returned by get_channel_keys.
325+
type ChanKeySigner : ChannelKeys;
326+
327+
/// Get node secret key (aka node_id or network_key)
328+
fn get_node_secret(&self) -> SecretKey;
329+
/// Get destination redeemScript to encumber static protocol exit points.
330+
fn get_destination_script(&self) -> Script;
331+
/// Get shutdown_pubkey to use as PublicKey at channel closure
332+
fn get_shutdown_pubkey(&self) -> PublicKey;
333+
/// Get a new set of ChannelKeys for per-channel secrets. These MUST be unique even if you
334+
/// restarted with some stale data!
335+
fn get_channel_keys(&self, inbound: bool, channel_value_satoshis: u64) -> Self::ChanKeySigner;
336+
/// Get a secret and PRNG seed for constructing an onion packet
337+
fn get_onion_rand(&self) -> (SecretKey, [u8; 32]);
338+
/// Get a unique temporary channel id. Channels will be referred to by this until the funding
339+
/// transaction is created, at which point they will use the outpoint in the funding
340+
/// transaction.
341+
fn get_channel_id(&self) -> [u8; 32];
342+
}
343+
344344
#[derive(Clone)]
345345
/// A simple implementation of ChannelKeys that just keeps the private keys in memory.
346346
pub struct InMemoryChannelKeys {
@@ -642,7 +642,7 @@ impl KeysManager {
642642
/// Note that until the 0.1 release there is no guarantee of backward compatibility between
643643
/// versions. Once the library is more fully supported, the docs will be updated to include a
644644
/// detailed description of the guarantee.
645-
pub fn new(seed: &[u8; 32], network: Network, starting_time_secs: u64, starting_time_nanos: u32) -> KeysManager {
645+
pub fn new(seed: &[u8; 32], network: Network, starting_time_secs: u64, starting_time_nanos: u32) -> Self {
646646
let secp_ctx = Secp256k1::signing_only();
647647
match ExtendedPrivKey::new_master(network.clone(), seed) {
648648
Ok(master_key) => {

lightning/src/chain/transaction.rs

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,6 @@ pub struct OutPoint {
1616
}
1717

1818
impl OutPoint {
19-
/// Creates a new `OutPoint` from the txid and the index.
20-
pub fn new(txid: Txid, index: u16) -> OutPoint {
21-
OutPoint { txid, index }
22-
}
23-
2419
/// Convert an `OutPoint` to a lightning channel id.
2520
pub fn to_channel_id(&self) -> [u8; 32] {
2621
let mut res = [0; 32];

lightning/src/ln/chan_utils.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@
55
use bitcoin::blockdata::script::{Script,Builder};
66
use bitcoin::blockdata::opcodes;
77
use bitcoin::blockdata::transaction::{TxIn,TxOut,OutPoint,Transaction, SigHashType};
8-
use bitcoin::consensus::encode::{self, Decodable, Encodable};
8+
use bitcoin::consensus::encode::{Decodable, Encodable};
9+
use bitcoin::consensus::encode;
910
use bitcoin::util::bip143;
1011

1112
use bitcoin::hashes::{Hash, HashEngine};

lightning/src/ln/channel.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1486,7 +1486,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
14861486
panic!("Should not have advanced channel commitment tx numbers prior to funding_created");
14871487
}
14881488

1489-
let funding_txo = OutPoint::new(msg.funding_txid, msg.funding_output_index);
1489+
let funding_txo = OutPoint{ txid: msg.funding_txid, index: msg.funding_output_index };
14901490
self.funding_txo = Some(funding_txo.clone());
14911491

14921492
let (remote_initial_commitment_tx, local_initial_commitment_tx, our_signature) = match self.funding_created_signature(&msg.signature, logger) {
@@ -4387,7 +4387,7 @@ mod tests {
43874387
let tx = Transaction { version: 1, lock_time: 0, input: Vec::new(), output: vec![TxOut {
43884388
value: 10000000, script_pubkey: output_script.clone(),
43894389
}]};
4390-
let funding_outpoint = OutPoint::new(tx.txid(), 0);
4390+
let funding_outpoint = OutPoint{ txid: tx.txid(), index: 0 };
43914391
let funding_created_msg = node_a_chan.get_outbound_funding_created(funding_outpoint, &&logger).unwrap();
43924392
let (funding_signed_msg, _) = node_b_chan.funding_created(&funding_created_msg, &&logger).unwrap();
43934393

@@ -4453,7 +4453,7 @@ mod tests {
44534453
chan.their_to_self_delay = 144;
44544454
chan.our_dust_limit_satoshis = 546;
44554455

4456-
let funding_info = OutPoint::new(Txid::from_hex("8984484a580b825b9972d7adb15050b3ab624ccd731946b3eeddb92f4e7ef6be").unwrap(), 0);
4456+
let funding_info = OutPoint{ txid: Txid::from_hex("8984484a580b825b9972d7adb15050b3ab624ccd731946b3eeddb92f4e7ef6be").unwrap(), index: 0 };
44574457
chan.funding_txo = Some(funding_info);
44584458

44594459
let their_pubkeys = ChannelPublicKeys {

0 commit comments

Comments
 (0)