Skip to content

Commit 3defcc8

Browse files
authored
Merge pull request #676 from TheBlueMatt/2020-08-c-bindings-cleanups-3
Pre-C-Bindings Cleanups #3
2 parents af69fae + d224c1d commit 3defcc8

16 files changed

+171
-101
lines changed

fuzz/src/chanmon_consistency.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -235,7 +235,7 @@ pub fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
235235
tx_broadcaster: broadcast.clone(),
236236
logger,
237237
default_config: config,
238-
channel_monitors: &mut monitor_refs,
238+
channel_monitors: monitor_refs,
239239
};
240240

241241
(<(BlockHash, ChannelManager<EnforcingChannelKeys, Arc<TestChannelMonitor>, Arc<TestBroadcaster>, Arc<KeyProvider>, Arc<FuzzEstimator>, Arc<dyn Logger>>)>::read(&mut Cursor::new(&$ser.0), read_args).expect("Failed to read manager").1, monitor)

fuzz/src/router.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -236,7 +236,10 @@ pub fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
236236
}
237237
&last_hops_vec[..]
238238
};
239-
let _ = get_route(&our_pubkey, &net_graph_msg_handler.network_graph.read().unwrap(), &target, first_hops, last_hops, slice_to_be64(get_slice!(8)), slice_to_be32(get_slice!(4)), Arc::clone(&logger));
239+
let _ = get_route(&our_pubkey, &net_graph_msg_handler.network_graph.read().unwrap(), &target,
240+
first_hops.map(|c| c.iter().collect::<Vec<_>>()).as_ref().map(|a| a.as_slice()),
241+
&last_hops.iter().collect::<Vec<_>>(),
242+
slice_to_be64(get_slice!(8)), slice_to_be32(get_slice!(4)), Arc::clone(&logger));
240243
},
241244
_ => return,
242245
}

lightning/src/chain/chaininterface.rs

+4-2
Original file line numberDiff line numberDiff line change
@@ -245,13 +245,15 @@ pub type BlockNotifierRef<'a, C> = BlockNotifier<'a, &'a ChainListener, C>;
245245
/// or a BlockNotifierRef for conciseness. See their documentation for more details, but essentially
246246
/// you should default to using a BlockNotifierRef, and use a BlockNotifierArc instead when you
247247
/// require ChainListeners with static lifetimes, such as when you're using lightning-net-tokio.
248-
pub struct BlockNotifier<'a, CL: Deref<Target = ChainListener + 'a> + 'a, C: Deref> where C::Target: ChainWatchInterface {
248+
pub struct BlockNotifier<'a, CL: Deref + 'a, C: Deref>
249+
where CL::Target: ChainListener + 'a, C::Target: ChainWatchInterface {
249250
listeners: Mutex<Vec<CL>>,
250251
chain_monitor: C,
251252
phantom: PhantomData<&'a ()>,
252253
}
253254

254-
impl<'a, CL: Deref<Target = ChainListener + 'a> + 'a, C: Deref> BlockNotifier<'a, CL, C> where C::Target: ChainWatchInterface {
255+
impl<'a, CL: Deref + 'a, C: Deref> BlockNotifier<'a, CL, C>
256+
where CL::Target: ChainListener + 'a, C::Target: ChainWatchInterface {
255257
/// Constructs a new BlockNotifier without any listeners.
256258
pub fn new(chain_monitor: C) -> BlockNotifier<'a, CL, C> {
257259
BlockNotifier {

lightning/src/chain/keysinterface.rs

+6-5
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
//! spendable on-chain outputs which the user owns and is responsible for using just as any other
1212
//! on-chain output which is theirs.
1313
14-
use bitcoin::blockdata::transaction::{Transaction, OutPoint, TxOut};
14+
use bitcoin::blockdata::transaction::{Transaction, TxOut};
1515
use bitcoin::blockdata::script::{Script, Builder};
1616
use bitcoin::blockdata::opcodes;
1717
use bitcoin::network::constants::Network;
@@ -31,9 +31,10 @@ use bitcoin::secp256k1;
3131
use util::byte_utils;
3232
use util::ser::{Writeable, Writer, Readable};
3333

34+
use chain::transaction::OutPoint;
3435
use ln::chan_utils;
3536
use ln::chan_utils::{HTLCOutputInCommitment, make_funding_redeemscript, ChannelPublicKeys, LocalCommitmentTransaction, PreCalculatedTxCreationKeys};
36-
use ln::msgs;
37+
use ln::msgs::UnsignedChannelAnnouncement;
3738

3839
use std::sync::atomic::{AtomicUsize, Ordering};
3940
use std::io::Error;
@@ -316,7 +317,7 @@ pub trait ChannelKeys : Send+Clone {
316317
/// Note that if this fails or is rejected, the channel will not be publicly announced and
317318
/// our counterparty may (though likely will not) close the channel on us for violating the
318319
/// protocol.
319-
fn sign_channel_announcement<T: secp256k1::Signing>(&self, msg: &msgs::UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
320+
fn sign_channel_announcement<T: secp256k1::Signing>(&self, msg: &UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
320321

321322
/// Set the remote channel basepoints and remote/local to_self_delay.
322323
/// This is done immediately on incoming channels and as soon as the channel is accepted on outgoing channels.
@@ -582,7 +583,7 @@ impl ChannelKeys for InMemoryChannelKeys {
582583
Ok(secp_ctx.sign(&sighash, &self.funding_key))
583584
}
584585

585-
fn sign_channel_announcement<T: secp256k1::Signing>(&self, msg: &msgs::UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
586+
fn sign_channel_announcement<T: secp256k1::Signing>(&self, msg: &UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
586587
let msghash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
587588
Ok(secp_ctx.sign(&msghash, &self.funding_key))
588589
}
@@ -808,7 +809,7 @@ impl KeysInterface for KeysManager {
808809
self.shutdown_pubkey.clone()
809810
}
810811

811-
fn get_channel_keys(&self, _inbound: bool, channel_value_satoshis: u64) -> InMemoryChannelKeys {
812+
fn get_channel_keys(&self, _inbound: bool, channel_value_satoshis: u64) -> Self::ChanKeySigner {
812813
let child_ix = self.channel_child_index.fetch_add(1, Ordering::AcqRel);
813814
let ix_and_nanos: u64 = (child_ix as u64) << 32 | (self.starting_time_nanos as u64);
814815
self.derive_channel_keys(channel_value_satoshis, ix_and_nanos, self.starting_time_secs)

lightning/src/ln/chan_utils.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ use util::byte_utils;
3030

3131
use bitcoin::secp256k1::key::{SecretKey, PublicKey};
3232
use bitcoin::secp256k1::{Secp256k1, Signature};
33+
use bitcoin::secp256k1::Error as SecpError;
3334
use bitcoin::secp256k1;
3435

3536
use std::{cmp, mem};
@@ -357,7 +358,7 @@ impl_writeable!(ChannelPublicKeys, 33*5, {
357358

358359
impl TxCreationKeys {
359360
/// Create a new TxCreationKeys from channel base points and the per-commitment point
360-
pub fn new<T: secp256k1::Signing + secp256k1::Verification>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, a_delayed_payment_base: &PublicKey, a_htlc_base: &PublicKey, b_revocation_base: &PublicKey, b_htlc_base: &PublicKey) -> Result<TxCreationKeys, secp256k1::Error> {
361+
pub fn derive_new<T: secp256k1::Signing + secp256k1::Verification>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, a_delayed_payment_base: &PublicKey, a_htlc_base: &PublicKey, b_revocation_base: &PublicKey, b_htlc_base: &PublicKey) -> Result<TxCreationKeys, SecpError> {
361362
Ok(TxCreationKeys {
362363
per_commitment_point: per_commitment_point.clone(),
363364
revocation_key: derive_public_revocation_key(&secp_ctx, &per_commitment_point, &b_revocation_base)?,

lightning/src/ln/channel.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -1126,7 +1126,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
11261126
let htlc_basepoint = &self.local_keys.pubkeys().htlc_basepoint;
11271127
let their_pubkeys = self.their_pubkeys.as_ref().unwrap();
11281128

1129-
Ok(secp_check!(TxCreationKeys::new(&self.secp_ctx, &per_commitment_point, delayed_payment_base, htlc_basepoint, &their_pubkeys.revocation_basepoint, &their_pubkeys.htlc_basepoint), "Local tx keys generation got bogus keys".to_owned()))
1129+
Ok(secp_check!(TxCreationKeys::derive_new(&self.secp_ctx, &per_commitment_point, delayed_payment_base, htlc_basepoint, &their_pubkeys.revocation_basepoint, &their_pubkeys.htlc_basepoint), "Local tx keys generation got bogus keys".to_owned()))
11301130
}
11311131

11321132
#[inline]
@@ -1140,7 +1140,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
11401140
let htlc_basepoint = &self.local_keys.pubkeys().htlc_basepoint;
11411141
let their_pubkeys = self.their_pubkeys.as_ref().unwrap();
11421142

1143-
Ok(secp_check!(TxCreationKeys::new(&self.secp_ctx, &self.their_cur_commitment_point.unwrap(), &their_pubkeys.delayed_payment_basepoint, &their_pubkeys.htlc_basepoint, revocation_basepoint, htlc_basepoint), "Remote tx keys generation got bogus keys".to_owned()))
1143+
Ok(secp_check!(TxCreationKeys::derive_new(&self.secp_ctx, &self.their_cur_commitment_point.unwrap(), &their_pubkeys.delayed_payment_basepoint, &their_pubkeys.htlc_basepoint, revocation_basepoint, htlc_basepoint), "Remote tx keys generation got bogus keys".to_owned()))
11441144
}
11451145

11461146
/// Gets the redeemscript for the funding transaction output (ie the funding transaction output
@@ -4673,7 +4673,7 @@ mod tests {
46734673
let per_commitment_secret = SecretKey::from_slice(&hex::decode("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100").unwrap()[..]).unwrap();
46744674
let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
46754675
let htlc_basepoint = &chan.local_keys.pubkeys().htlc_basepoint;
4676-
let keys = TxCreationKeys::new(&secp_ctx, &per_commitment_point, delayed_payment_base, htlc_basepoint, &their_pubkeys.revocation_basepoint, &their_pubkeys.htlc_basepoint).unwrap();
4676+
let keys = TxCreationKeys::derive_new(&secp_ctx, &per_commitment_point, delayed_payment_base, htlc_basepoint, &their_pubkeys.revocation_basepoint, &their_pubkeys.htlc_basepoint).unwrap();
46774677

46784678
chan.their_pubkeys = Some(their_pubkeys);
46794679

lightning/src/ln/channelmanager.rs

+31-9
Original file line numberDiff line numberDiff line change
@@ -42,10 +42,12 @@ use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpd
4242
use ln::features::{InitFeatures, NodeFeatures};
4343
use routing::router::{Route, RouteHop};
4444
use ln::msgs;
45+
use ln::msgs::NetAddress;
4546
use ln::onion_utils;
4647
use ln::msgs::{ChannelMessageHandler, DecodeError, LightningError, OptionalField};
4748
use chain::keysinterface::{ChannelKeys, KeysInterface, KeysManager, InMemoryChannelKeys};
4849
use util::config::UserConfig;
50+
use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
4951
use util::{byte_utils, events};
5052
use util::ser::{Readable, ReadableArgs, MaybeReadable, Writeable, Writer};
5153
use util::chacha20::{ChaCha20, ChaChaReader};
@@ -312,7 +314,7 @@ pub(super) struct ChannelHolder<ChanSigner: ChannelKeys> {
312314
claimable_htlcs: HashMap<(PaymentHash, Option<PaymentSecret>), Vec<ClaimableHTLC>>,
313315
/// Messages to send to peers - pushed to in the same lock that they are generated in (except
314316
/// for broadcast messages, where ordering isn't as strict).
315-
pub(super) pending_msg_events: Vec<events::MessageSendEvent>,
317+
pub(super) pending_msg_events: Vec<MessageSendEvent>,
316318
}
317319

318320
/// State we hold per-peer. In the future we should put channels in here, but for now we only hold
@@ -1484,7 +1486,7 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
14841486
// be absurd. We ensure this by checking that at least 500 (our stated public contract on when
14851487
// broadcast_node_announcement panics) of the maximum-length addresses would fit in a 64KB
14861488
// message...
1487-
const HALF_MESSAGE_IS_ADDRS: u32 = ::std::u16::MAX as u32 / (msgs::NetAddress::MAX_LEN as u32 + 1) / 2;
1489+
const HALF_MESSAGE_IS_ADDRS: u32 = ::std::u16::MAX as u32 / (NetAddress::MAX_LEN as u32 + 1) / 2;
14881490
#[deny(const_err)]
14891491
#[allow(dead_code)]
14901492
// ...by failing to compile if the number of addresses that would be half of a message is
@@ -1504,7 +1506,7 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
15041506
/// only Tor Onion addresses.
15051507
///
15061508
/// Panics if addresses is absurdly large (more than 500).
1507-
pub fn broadcast_node_announcement(&self, rgb: [u8; 3], alias: [u8; 32], addresses: Vec<msgs::NetAddress>) {
1509+
pub fn broadcast_node_announcement(&self, rgb: [u8; 3], alias: [u8; 32], addresses: Vec<NetAddress>) {
15081510
let _ = self.total_consistency_lock.read().unwrap();
15091511

15101512
if addresses.len() > 500 {
@@ -3011,14 +3013,14 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
30113013
}
30123014
}
30133015

3014-
impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> events::MessageSendEventsProvider for ChannelManager<ChanSigner, M, T, K, F, L>
3016+
impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> MessageSendEventsProvider for ChannelManager<ChanSigner, M, T, K, F, L>
30153017
where M::Target: ManyChannelMonitor<Keys=ChanSigner>,
30163018
T::Target: BroadcasterInterface,
30173019
K::Target: KeysInterface<ChanKeySigner = ChanSigner>,
30183020
F::Target: FeeEstimator,
30193021
L::Target: Logger,
30203022
{
3021-
fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
3023+
fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
30223024
//TODO: This behavior should be documented. It's non-intuitive that we query
30233025
// ChannelMonitors when clearing other events.
30243026
self.process_pending_monitor_events();
@@ -3030,14 +3032,14 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
30303032
}
30313033
}
30323034

3033-
impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> events::EventsProvider for ChannelManager<ChanSigner, M, T, K, F, L>
3035+
impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> EventsProvider for ChannelManager<ChanSigner, M, T, K, F, L>
30343036
where M::Target: ManyChannelMonitor<Keys=ChanSigner>,
30353037
T::Target: BroadcasterInterface,
30363038
K::Target: KeysInterface<ChanKeySigner = ChanSigner>,
30373039
F::Target: FeeEstimator,
30383040
L::Target: Logger,
30393041
{
3040-
fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
3042+
fn get_and_clear_pending_events(&self) -> Vec<Event> {
30413043
//TODO: This behavior should be documented. It's non-intuitive that we query
30423044
// ChannelMonitors when clearing other events.
30433045
self.process_pending_monitor_events();
@@ -3774,7 +3776,27 @@ pub struct ChannelManagerReadArgs<'a, ChanSigner: 'a + ChannelKeys, M: Deref, T:
37743776
///
37753777
/// In such cases the latest local transactions will be sent to the tx_broadcaster included in
37763778
/// this struct.
3777-
pub channel_monitors: &'a mut HashMap<OutPoint, &'a mut ChannelMonitor<ChanSigner>>,
3779+
pub channel_monitors: HashMap<OutPoint, &'a mut ChannelMonitor<ChanSigner>>,
3780+
}
3781+
3782+
impl<'a, ChanSigner: 'a + ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
3783+
ChannelManagerReadArgs<'a, ChanSigner, M, T, K, F, L>
3784+
where M::Target: ManyChannelMonitor<Keys=ChanSigner>,
3785+
T::Target: BroadcasterInterface,
3786+
K::Target: KeysInterface<ChanKeySigner = ChanSigner>,
3787+
F::Target: FeeEstimator,
3788+
L::Target: Logger,
3789+
{
3790+
/// Simple utility function to create a ChannelManagerReadArgs which creates the monitor
3791+
/// HashMap for you. This is primarily useful for C bindings where it is not practical to
3792+
/// populate a HashMap directly from C.
3793+
pub fn new(keys_manager: K, fee_estimator: F, monitor: M, tx_broadcaster: T, logger: L, default_config: UserConfig,
3794+
mut channel_monitors: Vec<&'a mut ChannelMonitor<ChanSigner>>) -> Self {
3795+
Self {
3796+
keys_manager, fee_estimator, monitor, tx_broadcaster, logger, default_config,
3797+
channel_monitors: channel_monitors.drain(..).map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect()
3798+
}
3799+
}
37783800
}
37793801

37803802
// Implement ReadableArgs for an Arc'd ChannelManager to make it a bit easier to work with the
@@ -3801,7 +3823,7 @@ impl<'a, ChanSigner: ChannelKeys + Readable, M: Deref, T: Deref, K: Deref, F: De
38013823
F::Target: FeeEstimator,
38023824
L::Target: Logger,
38033825
{
3804-
fn read<R: ::std::io::Read>(reader: &mut R, args: ChannelManagerReadArgs<'a, ChanSigner, M, T, K, F, L>) -> Result<Self, DecodeError> {
3826+
fn read<R: ::std::io::Read>(reader: &mut R, mut args: ChannelManagerReadArgs<'a, ChanSigner, M, T, K, F, L>) -> Result<Self, DecodeError> {
38053827
let _ver: u8 = Readable::read(reader)?;
38063828
let min_ver: u8 = Readable::read(reader)?;
38073829
if min_ver > SERIALIZATION_VERSION {

0 commit comments

Comments
 (0)