Skip to content

Commit 061b4a1

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) * We can't have `new()` constructors for completely-transparent structs (nor should we, really) * We cannot use foo::bar::self
1 parent d2520f4 commit 061b4a1

18 files changed

+205
-128
lines changed

fuzz/src/chanmon_consistency.rs

Lines changed: 5 additions & 3 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
}
@@ -266,7 +268,7 @@ pub fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
266268
let tx = Transaction { version: $chan_id, lock_time: 0, input: Vec::new(), output: vec![TxOut {
267269
value: *channel_value_satoshis, script_pubkey: output_script.clone(),
268270
}]};
269-
funding_output = OutPoint::new(tx.txid(), 0);
271+
funding_output = OutPoint { txid: tx.txid(), index: 0 };
270272
$source.funding_transaction_generated(&temporary_channel_id, funding_output);
271273
channel_txn.push(tx);
272274
} else { panic!("Wrong event type"); }

fuzz/src/full_stack.rs

Lines changed: 2 additions & 2 deletions
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]);
@@ -474,7 +474,7 @@ pub fn do_test(data: &[u8], logger: &Arc<dyn Logger>) {
474474
let funding_output = 'search_loop: loop {
475475
let funding_txid = tx.txid();
476476
if let None = loss_detector.txids_confirmed.get(&funding_txid) {
477-
let outpoint = OutPoint::new(funding_txid, 0);
477+
let outpoint = OutPoint { txid: funding_txid, index: 0 };
478478
for chan in channelmanager.list_channels() {
479479
if chan.channel_id == outpoint.to_channel_id() {
480480
tx.version += 1;

lightning/src/chain/chaininterface.rs

Lines changed: 7 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)
@@ -220,6 +224,7 @@ impl ChainWatchedUtil {
220224
/// parameters with static lifetimes). Other times you can afford a reference, which is more
221225
/// efficient, in which case BlockNotifierRef is a more appropriate type. Defining these type
222226
/// aliases prevents issues such as overly long function definitions.
227+
/// (C-not exported)
223228
pub type BlockNotifierArc = Arc<BlockNotifier<'static, Arc<ChainListener>>>;
224229

225230
/// BlockNotifierRef is useful when you want a BlockNotifier that points to ChainListeners
@@ -238,6 +243,7 @@ pub type BlockNotifierRef<'a> = BlockNotifier<'a, &'a ChainListener>;
238243
/// or a BlockNotifierRef for conciseness. See their documentation for more details, but essentially
239244
/// you should default to using a BlockNotifierRef, and use a BlockNotifierArc instead when you
240245
/// require ChainListeners with static lifetimes, such as when you're using lightning-net-tokio.
246+
/// (C-not exported) due to ChainListener not being exported
241247
pub struct BlockNotifier<'a, CL: Deref<Target = ChainListener + 'a> + 'a> {
242248
listeners: Mutex<Vec<CL>>,
243249
chain_monitor: Arc<ChainWatchInterface>,
@@ -312,6 +318,7 @@ impl<'a, CL: Deref<Target = ChainListener + 'a> + 'a> BlockNotifier<'a, CL> {
312318
/// Utility to capture some common parts of ChainWatchInterface implementors.
313319
///
314320
/// Keeping a local copy of this in a ChainWatchInterface implementor is likely useful.
321+
/// (C-not exported)
315322
pub struct ChainWatchInterfaceUtil {
316323
network: Network,
317324
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/chain/transaction.rs

Lines changed: 1 addition & 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];
@@ -31,6 +26,7 @@ impl OutPoint {
3126
}
3227

3328
/// Converts this OutPoint into the OutPoint field as used by rust-bitcoin
29+
/// (C-not exported)
3430
pub fn into_bitcoin_outpoint(self) -> BitcoinOutPoint {
3531
BitcoinOutPoint {
3632
txid: self.txid,

lightning/src/ln/chan_utils.rs

Lines changed: 3 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};
@@ -480,6 +481,7 @@ pub fn build_htlc_transaction(prev_hash: &Txid, feerate_per_kw: u64, to_self_del
480481
/// We use this to track local commitment transactions and put off signing them until we are ready
481482
/// to broadcast. Eventually this will require a signer which is possibly external, but for now we
482483
/// just pass in the SecretKeys required.
484+
/// (C-not exported)
483485
pub struct LocalCommitmentTransaction {
484486
// TODO: We should migrate away from providing the transaction, instead providing enough to
485487
// allow the ChannelKeys to construct it from scratch. Luckily we already have HTLC data here,

lightning/src/ln/channel.rs

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

1496-
let funding_txo = OutPoint::new(msg.funding_txid, msg.funding_output_index);
1496+
let funding_txo = OutPoint{ txid: msg.funding_txid, index: msg.funding_output_index };
14971497
self.funding_txo = Some(funding_txo.clone());
14981498

14991499
let (remote_initial_commitment_tx, local_initial_commitment_tx, our_signature) = match self.funding_created_signature(&msg.signature) {
@@ -4395,7 +4395,7 @@ mod tests {
43954395
let tx = Transaction { version: 1, lock_time: 0, input: Vec::new(), output: vec![TxOut {
43964396
value: 10000000, script_pubkey: output_script.clone(),
43974397
}]};
4398-
let funding_outpoint = OutPoint::new(tx.txid(), 0);
4398+
let funding_outpoint = OutPoint{ txid: tx.txid(), index: 0 };
43994399
let funding_created_msg = node_a_chan.get_outbound_funding_created(funding_outpoint).unwrap();
44004400
let (funding_signed_msg, _) = node_b_chan.funding_created(&funding_created_msg).unwrap();
44014401

@@ -4460,7 +4460,7 @@ mod tests {
44604460
chan.their_to_self_delay = 144;
44614461
chan.our_dust_limit_satoshis = 546;
44624462

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

44664466
let their_pubkeys = ChannelPublicKeys {

0 commit comments

Comments
 (0)