Skip to content

Commit b1b7cc6

Browse files
committed
Tweak a few return types to make it easier to gen C wrappers
Our (naive) C wrapper generator gets easily confused, so we tweak our source in a few ways to make it easier to understand, namely: * Traits must be defined before they are referenced * For generic traits, we understand associated types, but not direct <Type: TraitBound> parameters * Non-C-bindable types in traits will fail to generate wrappers - we mark them (C-not exported) for now but will have to get them all to work to make the C bindings usable, * For constructors, we have to return "Self", not the fully-specified (generic) struct name. * When specifying generics, we must use only one token (ie ChannelMessageHandler, not msgs::ChannelMessageHandler)
1 parent d2520f4 commit b1b7cc6

14 files changed

+186
-107
lines changed

fuzz/src/chanmon_consistency.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,9 @@ impl TestChannelMonitor {
9595
}
9696
}
9797
}
98-
impl channelmonitor::ManyChannelMonitor<EnforcingChannelKeys> for TestChannelMonitor {
98+
impl channelmonitor::ManyChannelMonitor for TestChannelMonitor {
99+
type Keys = EnforcingChannelKeys;
100+
99101
fn add_monitor(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<EnforcingChannelKeys>) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
100102
let mut ser = VecWriter(Vec::new());
101103
monitor.write_for_disk(&mut ser).unwrap();
@@ -194,7 +196,7 @@ pub fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
194196
config.channel_options.fee_proportional_millionths = 0;
195197
config.channel_options.announced_channel = true;
196198
config.peer_channel_config_limits.min_dust_limit_satoshis = 0;
197-
(Arc::new(ChannelManager::new(Network::Bitcoin, fee_est.clone(), monitor.clone(), broadcast.clone(), Arc::clone(&logger), keys_manager.clone(), config, 0).unwrap()),
199+
(Arc::new(ChannelManager::new(Network::Bitcoin, fee_est.clone(), monitor.clone(), broadcast.clone(), Arc::clone(&logger), keys_manager.clone(), config, 0)),
198200
monitor)
199201
} }
200202
}

fuzz/src/full_stack.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -331,7 +331,7 @@ pub fn do_test(data: &[u8], logger: &Arc<dyn Logger>) {
331331
config.channel_options.fee_proportional_millionths = slice_to_be32(get_slice!(4));
332332
config.channel_options.announced_channel = get_slice!(1)[0] != 0;
333333
config.peer_channel_config_limits.min_dust_limit_satoshis = 0;
334-
let channelmanager = Arc::new(ChannelManager::new(Network::Bitcoin, fee_est.clone(), monitor.clone(), broadcast.clone(), Arc::clone(&logger), keys_manager.clone(), config, 0).unwrap());
334+
let channelmanager = Arc::new(ChannelManager::new(Network::Bitcoin, fee_est.clone(), monitor.clone(), broadcast.clone(), Arc::clone(&logger), keys_manager.clone(), config, 0));
335335
let router = Arc::new(Router::new(PublicKey::from_secret_key(&Secp256k1::signing_only(), &keys_manager.get_node_secret()), watch.clone(), Arc::clone(&logger)));
336336

337337
let peers = RefCell::new([false; 256]);

lightning/src/chain/chaininterface.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ pub enum ChainError {
3838
/// Note that all of the functions implemented here *must* be reentrant-safe (obviously - they're
3939
/// called from inside the library in response to ChainListener events, P2P events, or timer
4040
/// events).
41+
/// (C-not exported) due to tuples and Result<>s
4142
pub trait ChainWatchInterface: Sync + Send {
4243
/// Provides a txid/random-scriptPubKey-in-the-tx which much be watched for.
4344
fn install_watch_tx(&self, txid: &Txid, script_pub_key: &Script);
@@ -72,6 +73,7 @@ pub trait BroadcasterInterface: Sync + Send {
7273
}
7374

7475
/// A trait indicating a desire to listen for events from the chain
76+
/// (C-not exported)
7577
pub trait ChainListener: Sync + Send {
7678
/// Notifies a listener that a block was connected.
7779
///
@@ -128,6 +130,7 @@ pub trait FeeEstimator: Sync + Send {
128130
pub const MIN_RELAY_FEE_SAT_PER_1000_WEIGHT: u64 = 4000;
129131

130132
/// Utility for tracking registered txn/outpoints and checking for matches
133+
/// (C-not exported)
131134
#[cfg_attr(test, derive(PartialEq))]
132135
pub struct ChainWatchedUtil {
133136
watch_all: bool,
@@ -169,6 +172,7 @@ impl ChainWatchedUtil {
169172

170173
/// Registers an outpoint for monitoring, returning true if it was a new outpoint and false if
171174
/// we'd already been watching for it
175+
/// (C-not exported) due to tuples
172176
pub fn register_outpoint(&mut self, outpoint: (Txid, u32), _script_pub_key: &Script) -> bool {
173177
if self.watch_all { return false; }
174178
self.watched_outpoints.insert(outpoint)
@@ -238,6 +242,7 @@ pub type BlockNotifierRef<'a> = BlockNotifier<'a, &'a ChainListener>;
238242
/// or a BlockNotifierRef for conciseness. See their documentation for more details, but essentially
239243
/// you should default to using a BlockNotifierRef, and use a BlockNotifierArc instead when you
240244
/// require ChainListeners with static lifetimes, such as when you're using lightning-net-tokio.
245+
/// (C-not exported) due to ChainListener not being exported
241246
pub struct BlockNotifier<'a, CL: Deref<Target = ChainListener + 'a> + 'a> {
242247
listeners: Mutex<Vec<CL>>,
243248
chain_monitor: Arc<ChainWatchInterface>,
@@ -312,6 +317,7 @@ impl<'a, CL: Deref<Target = ChainListener + 'a> + 'a> BlockNotifier<'a, CL> {
312317
/// Utility to capture some common parts of ChainWatchInterface implementors.
313318
///
314319
/// Keeping a local copy of this in a ChainWatchInterface implementor is likely useful.
320+
/// (C-not exported)
315321
pub struct ChainWatchInterfaceUtil {
316322
network: Network,
317323
watched: Mutex<ChainWatchedUtil>,

lightning/src/chain/keysinterface.rs

Lines changed: 40 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -142,28 +142,6 @@ impl Readable for SpendableOutputDescriptor {
142142
}
143143
}
144144

145-
/// A trait to describe an object which can get user secrets and key material.
146-
pub trait KeysInterface: Send + Sync {
147-
/// A type which implements ChannelKeys which will be returned by get_channel_keys.
148-
type ChanKeySigner : ChannelKeys;
149-
150-
/// Get node secret key (aka node_id or network_key)
151-
fn get_node_secret(&self) -> SecretKey;
152-
/// Get destination redeemScript to encumber static protocol exit points.
153-
fn get_destination_script(&self) -> Script;
154-
/// Get shutdown_pubkey to use as PublicKey at channel closure
155-
fn get_shutdown_pubkey(&self) -> PublicKey;
156-
/// Get a new set of ChannelKeys for per-channel secrets. These MUST be unique even if you
157-
/// restarted with some stale data!
158-
fn get_channel_keys(&self, inbound: bool, channel_value_satoshis: u64) -> Self::ChanKeySigner;
159-
/// Get a secret and PRNG seed for construting an onion packet
160-
fn get_onion_rand(&self) -> (SecretKey, [u8; 32]);
161-
/// Get a unique temporary channel id. Channels will be referred to by this until the funding
162-
/// transaction is created, at which point they will use the outpoint in the funding
163-
/// transaction.
164-
fn get_channel_id(&self) -> [u8; 32];
165-
}
166-
167145
/// Set of lightning keys needed to operate a channel as described in BOLT 3.
168146
///
169147
/// Signing services could be implemented on a hardware wallet. In this case,
@@ -192,26 +170,34 @@ pub trait KeysInterface: Send + Sync {
192170
// TODO: We should remove Clone by instead requesting a new ChannelKeys copy when we create
193171
// ChannelMonitors instead of expecting to clone the one out of the Channel into the monitors.
194172
pub trait ChannelKeys : Send+Clone {
173+
/// (C-not exported) due to references
195174
/// Gets the private key for the anchor tx
196175
fn funding_key<'a>(&'a self) -> &'a SecretKey;
197176
/// Gets the local secret key for blinded revocation pubkey
177+
/// (C-not exported) due to references
198178
fn revocation_base_key<'a>(&'a self) -> &'a SecretKey;
199179
/// Gets the local secret key used in the to_remote output of remote commitment tx (ie the
200180
/// output to us in transactions our counterparty broadcasts).
201181
/// Also as part of obscured commitment number.
182+
/// (C-not exported) due to references
202183
fn payment_key<'a>(&'a self) -> &'a SecretKey;
203184
/// Gets the local secret key used in HTLC-Success/HTLC-Timeout txn and to_local output
185+
/// (C-not exported) due to references
204186
fn delayed_payment_base_key<'a>(&'a self) -> &'a SecretKey;
205187
/// Gets the local htlc secret key used in commitment tx htlc outputs
188+
/// (C-not exported) due to references
206189
fn htlc_base_key<'a>(&'a self) -> &'a SecretKey;
207190
/// Gets the commitment seed
191+
/// (C-not exported) due to references
208192
fn commitment_seed<'a>(&'a self) -> &'a [u8; 32];
209193
/// Gets the local channel public keys and basepoints
194+
/// (C-not exported) due to references
210195
fn pubkeys<'a>(&'a self) -> &'a ChannelPublicKeys;
211196

212197
/// Create a signature for a remote commitment transaction and associated HTLC transactions.
213198
///
214199
/// Note that if signing fails or is rejected, the channel will be force-closed.
200+
/// (C-not exported) due to references
215201
//
216202
// TODO: Document the things someone using this interface should enforce before signing.
217203
// TODO: Add more input vars to enable better checking (preferably removing commitment_tx and
@@ -221,6 +207,7 @@ pub trait ChannelKeys : Send+Clone {
221207
/// Create a signature for a local commitment transaction. This will only ever be called with
222208
/// the same local_commitment_tx (or a copy thereof), though there are currently no guarantees
223209
/// that it will not be called multiple times.
210+
/// (C-not exported) due to references
224211
//
225212
// TODO: Document the things someone using this interface should enforce before signing.
226213
// TODO: Add more input vars to enable better checking (preferably removing commitment_tx and
@@ -246,12 +233,14 @@ pub trait ChannelKeys : Send+Clone {
246233
/// (implying they were considered dust at the time the commitment transaction was negotiated),
247234
/// a corresponding None should be included in the return value. All other positions in the
248235
/// return value must contain a signature.
236+
/// (C-not exported) due to references
249237
fn sign_local_commitment_htlc_transactions<T: secp256k1::Signing + secp256k1::Verification>(&self, local_commitment_tx: &LocalCommitmentTransaction, local_csv: u16, secp_ctx: &Secp256k1<T>) -> Result<Vec<Option<Signature>>, ()>;
250238

251239
/// Create a signature for a (proposed) closing transaction.
252240
///
253241
/// Note that, due to rounding, there may be one "missing" satoshi, and either party may have
254242
/// chosen to forgo their output as dust.
243+
/// (C-not exported) due to references
255244
fn sign_closing_transaction<T: secp256k1::Signing>(&self, closing_tx: &Transaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
256245

257246
/// Signs a channel announcement message with our funding key, proving it comes from one
@@ -260,15 +249,42 @@ pub trait ChannelKeys : Send+Clone {
260249
/// Note that if this fails or is rejected, the channel will not be publicly announced and
261250
/// our counterparty may (though likely will not) close the channel on us for violating the
262251
/// protocol.
252+
/// (C-not exported) due to references
263253
fn sign_channel_announcement<T: secp256k1::Signing>(&self, msg: &msgs::UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
264254

265255
/// Set the remote channel basepoints. This is done immediately on incoming channels
266256
/// and as soon as the channel is accepted on outgoing channels.
267257
///
268258
/// Will be called before any signatures are applied.
259+
/// (C-not exported) due to references
269260
fn set_remote_channel_pubkeys(&mut self, channel_points: &ChannelPublicKeys);
270261
}
271262

263+
264+
/// A trait to describe an object which can get user secrets and key material.
265+
pub trait KeysInterface: Send + Sync {
266+
/// A type which implements ChannelKeys which will be returned by get_channel_keys.
267+
type ChanKeySigner : ChannelKeys;
268+
269+
/// Get node secret key (aka node_id or network_key)
270+
fn get_node_secret(&self) -> SecretKey;
271+
/// Get destination redeemScript to encumber static protocol exit points.
272+
fn get_destination_script(&self) -> Script;
273+
/// Get shutdown_pubkey to use as PublicKey at channel closure
274+
fn get_shutdown_pubkey(&self) -> PublicKey;
275+
/// Get a new set of ChannelKeys for per-channel secrets. These MUST be unique even if you
276+
/// restarted with some stale data!
277+
/// (C-not exported) due to Self (though it *should* work...)
278+
fn get_channel_keys(&self, inbound: bool, channel_value_satoshis: u64) -> Self::ChanKeySigner;
279+
/// Get a secret and PRNG seed for construting an onion packet
280+
/// (C-not exported) due to tuple
281+
fn get_onion_rand(&self) -> (SecretKey, [u8; 32]);
282+
/// Get a unique temporary channel id. Channels will be referred to by this until the funding
283+
/// transaction is created, at which point they will use the outpoint in the funding
284+
/// transaction.
285+
fn get_channel_id(&self) -> [u8; 32];
286+
}
287+
272288
#[derive(Clone)]
273289
/// A simple implementation of ChannelKeys that just keeps the private keys in memory.
274290
pub struct InMemoryChannelKeys {
@@ -294,6 +310,7 @@ pub struct InMemoryChannelKeys {
294310

295311
impl InMemoryChannelKeys {
296312
/// Create a new InMemoryChannelKeys
313+
/// (C-not exported) due to secp context
297314
pub fn new<C: Signing>(
298315
secp_ctx: &Secp256k1<C>,
299316
funding_key: SecretKey,
@@ -509,7 +526,7 @@ impl KeysManager {
509526
/// Note that until the 0.1 release there is no guarantee of backward compatibility between
510527
/// versions. Once the library is more fully supported, the docs will be updated to include a
511528
/// detailed description of the guarantee.
512-
pub fn new(seed: &[u8; 32], network: Network, logger: Arc<Logger>, starting_time_secs: u64, starting_time_nanos: u32) -> KeysManager {
529+
pub fn new(seed: &[u8; 32], network: Network, logger: Arc<Logger>, starting_time_secs: u64, starting_time_nanos: u32) -> Self {
513530
let secp_ctx = Secp256k1::signing_only();
514531
match ExtendedPrivKey::new_master(network.clone(), seed) {
515532
Ok(master_key) => {

lightning/src/ln/chan_utils.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -480,6 +480,7 @@ pub fn build_htlc_transaction(prev_hash: &Txid, feerate_per_kw: u64, to_self_del
480480
/// We use this to track local commitment transactions and put off signing them until we are ready
481481
/// to broadcast. Eventually this will require a signer which is possibly external, but for now we
482482
/// just pass in the SecretKeys required.
483+
/// (C-not exported)
483484
pub struct LocalCommitmentTransaction {
484485
// TODO: We should migrate away from providing the transaction, instead providing enough to
485486
// allow the ChannelKeys to construct it from scratch. Luckily we already have HTLC data here,

0 commit comments

Comments
 (0)