Skip to content

Commit 6bae489

Browse files
committed
Merge branch 'master' into modular_handshake
2 parents c2227b6 + a4e4056 commit 6bae489

15 files changed

+1290
-847
lines changed

ARCH.md

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
Rust-Lightning is broken into a number of high-level structures with APIs to hook them
2+
together, as well as APIs for you, the user, to provide external data.
3+
4+
The two most important structures which nearly every application of Rust-Lightning will
5+
need to use are `ChannelManager` and `ChannelMonitor`. `ChannelManager` holds multiple
6+
channels, routes payments between them, and exposes a simple API to make and receive
7+
payments. Individual `ChannelMonitor`s monitor the on-chain state of a channel, punish
8+
counterparties if they misbehave, and force-close channels if they contain unresolved
9+
HTLCs which are near expiration. The `ManyChannelMonitor` API provides a way for you to
10+
receive `ChannelMonitorUpdate`s from `ChannelManager` and persist them to disk before the
11+
channel steps forward.
12+
13+
There are two additional important structures that you may use either on the same device
14+
as the `ChannelManager` or on a separate one. `Router` handles receiving channel and node
15+
node announcements and calculates routes for sending payments. `PeerManager` handles the
16+
authenticated and encrypted communication protocol, monitoring for liveness of peers,
17+
routing messages to `ChannelManager` and `Router` instances directly, and receiving
18+
messages from them via the `EventsProvider` interface.
19+
20+
These structs communicate with each other using a public API, so that you can easily add
21+
a proxy in between for special handling. Further, APIs for key generation, transaction
22+
broadcasting, block fetching, and fee estimation must be implemented and the data
23+
provided by you, the user.
24+
25+
The library does not rely on the presence of a runtime environment outside of access to
26+
heap, atomic integers, and basic Mutex primitives. This means the library will never
27+
spawn threads or take any action whatsoever except when you call into it. Thus,
28+
`ChannelManager` and `PeerManager` have public functions which you should call on a timer,
29+
network reads and writes are external and provided by you, and the library relies only on
30+
block time for current time knowledge.
31+
32+
At a high level, some of the common interfaces fit together as follows:
33+
34+
35+
```
36+
37+
-----------------
38+
| KeysInterface | --------------
39+
----------------- | UserConfig |
40+
-------------------- | --------------
41+
/------| MessageSendEvent | | | ----------------
42+
| -------------------- | | | FeeEstimator |
43+
| (as MessageSendEventsProvider) | | ----------------
44+
| ^ | | / | ------------------------
45+
| \ | | / ---------> | BroadcasterInterface |
46+
| \ | | / / | ------------------------
47+
| \ v v v / v ^
48+
| (as ------------------ ----------------------
49+
| ChannelMessageHandler)-> | ChannelManager | ----> | ManyChannelMonitor |
50+
v / ------------------ ----------------------
51+
--------------- / ^ (as EventsProvider) ^
52+
| PeerManager |- | \ / /
53+
--------------- | -------\---/----------
54+
| ----------------------- / \ /
55+
| | ChainWatchInterface | - v
56+
| ----------------------- ---------
57+
| | | Event |
58+
(as RoutingMessageHandler) v ---------
59+
\ ----------
60+
-----------------> | Router |
61+
----------
62+
```

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,6 @@ Contributors are warmly welcome, see [CONTRIBUTING.md](CONTRIBUTING.md).
4646
Project Architecture
4747
---------------------
4848

49-
COMING SOON.
49+
For a Rust-Lightning high-level API introduction, see [ARCH.md](ARCH.md).
5050

5151
License is Apache-2.0.

fuzz/src/chanmon_consistency.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ impl channelmonitor::ManyChannelMonitor<EnforcingChannelKeys> for TestChannelMon
116116
};
117117
let mut deserialized_monitor = <(Sha256d, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::
118118
read(&mut Cursor::new(&map_entry.get().1), Arc::clone(&self.logger)).unwrap().1;
119-
deserialized_monitor.update_monitor(update.clone()).unwrap();
119+
deserialized_monitor.update_monitor(update.clone(), &&TestBroadcaster {}).unwrap();
120120
let mut ser = VecWriter(Vec::new());
121121
deserialized_monitor.write_for_disk(&mut ser).unwrap();
122122
map_entry.insert((update.update_id, ser.0));

fuzz/src/full_stack.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ impl FeeEstimator for FuzzEstimator {
9999
//TODO: We should actually be testing at least much more than 64k...
100100
match self.input.get_slice(2) {
101101
Some(slice) => cmp::max(slice_to_be16(slice) as u64, 253),
102-
None => 0
102+
None => 253
103103
}
104104
}
105105
}

lightning/src/chain/keysinterface.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ use ln::msgs::DecodeError;
3737
/// spend on-chain. The information needed to do this is provided in this enum, including the
3838
/// outpoint describing which txid and output index is available, the full output which exists at
3939
/// that txid/index, and any keys or other information required to sign.
40+
#[derive(Clone, PartialEq)]
4041
pub enum SpendableOutputDescriptor {
4142
/// An output to a script which was provided via KeysInterface, thus you should already know
4243
/// how to spend it. No keys are provided as rust-lightning was never given any keys - only the
@@ -53,7 +54,7 @@ pub enum SpendableOutputDescriptor {
5354
/// The private key which should be used to sign the transaction is provided, as well as the
5455
/// full witness redeemScript which is hashed in the output script_pubkey.
5556
/// The witness in the spending input should be:
56-
/// <BIP 143 signature generated with the given key> <one zero byte aka OP_0>
57+
/// <BIP 143 signature generated with the given key> <empty vector> (MINIMALIF standard rule)
5758
/// <witness_script as provided>
5859
/// Note that the nSequence field in the input must be set to_self_delay (which corresponds to
5960
/// the transaction not being broadcastable until at least to_self_delay blocks after the input

lightning/src/ln/chanmon_update_fail_tests.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ fn test_simple_monitor_permanent_update_fail() {
3131

3232
*nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
3333
if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route, payment_hash_1) {} else { panic!(); }
34-
check_added_monitors!(nodes[0], 1);
34+
check_added_monitors!(nodes[0], 2);
3535

3636
let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3737
assert_eq!(events_1.len(), 2);
@@ -120,7 +120,7 @@ fn do_test_simple_monitor_temporary_update_fail(disconnect: bool) {
120120

121121
// ...and make sure we can force-close a frozen channel
122122
nodes[0].node.force_close_channel(&channel_id);
123-
check_added_monitors!(nodes[0], 0);
123+
check_added_monitors!(nodes[0], 1);
124124
check_closed_broadcast!(nodes[0], false);
125125

126126
// TODO: Once we hit the chain with the failure transaction we should check that we get a

lightning/src/ln/channel.rs

Lines changed: 98 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1138,8 +1138,11 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
11381138
}
11391139

11401140
/// Per HTLC, only one get_update_fail_htlc or get_update_fulfill_htlc call may be made.
1141-
/// In such cases we debug_assert!(false) and return an IgnoreError. Thus, will always return
1142-
/// Ok(_) if debug assertions are turned on and preconditions are met.
1141+
/// In such cases we debug_assert!(false) and return a ChannelError::Ignore. Thus, will always
1142+
/// return Ok(_) if debug assertions are turned on or preconditions are met.
1143+
///
1144+
/// Note that it is still possible to hit these assertions in case we find a preimage on-chain
1145+
/// but then have a reorg which settles on an HTLC-failure on chain.
11431146
fn get_update_fulfill_htlc(&mut self, htlc_id_arg: u64, payment_preimage_arg: PaymentPreimage) -> Result<(Option<msgs::UpdateFulfillHTLC>, Option<ChannelMonitorUpdate>), ChannelError> {
11441147
// Either ChannelFunded got set (which means it won't be unset) or there is no way any
11451148
// caller thought we could have something claimed (cause we wouldn't have accepted in an
@@ -1167,6 +1170,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
11671170
} else {
11681171
log_warn!(self, "Have preimage and want to fulfill HTLC with payment hash {} we already failed against channel {}", log_bytes!(htlc.payment_hash.0), log_bytes!(self.channel_id()));
11691172
}
1173+
debug_assert!(false, "Tried to fulfill an HTLC that was already fail/fulfilled");
11701174
return Ok((None, None));
11711175
},
11721176
_ => {
@@ -1200,6 +1204,9 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
12001204
match pending_update {
12011205
&HTLCUpdateAwaitingACK::ClaimHTLC { htlc_id, .. } => {
12021206
if htlc_id_arg == htlc_id {
1207+
// Make sure we don't leave latest_monitor_update_id incremented here:
1208+
self.latest_monitor_update_id -= 1;
1209+
debug_assert!(false, "Tried to fulfill an HTLC that was already fulfilled");
12031210
return Ok((None, None));
12041211
}
12051212
},
@@ -1208,6 +1215,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
12081215
log_warn!(self, "Have preimage and want to fulfill HTLC with pending failure against channel {}", log_bytes!(self.channel_id()));
12091216
// TODO: We may actually be able to switch to a fulfill here, though its
12101217
// rare enough it may not be worth the complexity burden.
1218+
debug_assert!(false, "Tried to fulfill an HTLC that was already failed");
12111219
return Ok((None, Some(monitor_update)));
12121220
}
12131221
},
@@ -1259,8 +1267,11 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
12591267
}
12601268

12611269
/// Per HTLC, only one get_update_fail_htlc or get_update_fulfill_htlc call may be made.
1262-
/// In such cases we debug_assert!(false) and return an IgnoreError. Thus, will always return
1263-
/// Ok(_) if debug assertions are turned on and preconditions are met.
1270+
/// In such cases we debug_assert!(false) and return a ChannelError::Ignore. Thus, will always
1271+
/// return Ok(_) if debug assertions are turned on or preconditions are met.
1272+
///
1273+
/// Note that it is still possible to hit these assertions in case we find a preimage on-chain
1274+
/// but then have a reorg which settles on an HTLC-failure on chain.
12641275
pub fn get_update_fail_htlc(&mut self, htlc_id_arg: u64, err_packet: msgs::OnionErrorPacket) -> Result<Option<msgs::UpdateFailHTLC>, ChannelError> {
12651276
if (self.channel_state & (ChannelState::ChannelFunded as u32)) != (ChannelState::ChannelFunded as u32) {
12661277
panic!("Was asked to fail an HTLC when channel was not in an operational state");
@@ -1277,6 +1288,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
12771288
match htlc.state {
12781289
InboundHTLCState::Committed => {},
12791290
InboundHTLCState::LocalRemoved(_) => {
1291+
debug_assert!(false, "Tried to fail an HTLC that was already fail/fulfilled");
12801292
return Ok(None);
12811293
},
12821294
_ => {
@@ -1297,11 +1309,13 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
12971309
match pending_update {
12981310
&HTLCUpdateAwaitingACK::ClaimHTLC { htlc_id, .. } => {
12991311
if htlc_id_arg == htlc_id {
1312+
debug_assert!(false, "Tried to fail an HTLC that was already fulfilled");
13001313
return Err(ChannelError::Ignore("Unable to find a pending HTLC which matched the given HTLC ID"));
13011314
}
13021315
},
13031316
&HTLCUpdateAwaitingACK::FailHTLC { htlc_id, .. } => {
13041317
if htlc_id_arg == htlc_id {
1318+
debug_assert!(false, "Tried to fail an HTLC that was already failed");
13051319
return Err(ChannelError::Ignore("Unable to find a pending HTLC which matched the given HTLC ID"));
13061320
}
13071321
},
@@ -3444,10 +3458,10 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
34443458
my_current_per_commitment_point: PublicKey::from_secret_key(&self.secp_ctx, &self.build_local_commitment_secret(self.cur_local_commitment_transaction_number + 1))
34453459
})
34463460
} else {
3447-
log_debug!(self, "We don't seen yet any revoked secret, if this channnel has already been updated it means we are fallen-behind, you should wait for other peer closing");
3461+
log_info!(self, "Sending a data_loss_protect with no previous remote per_commitment_secret");
34483462
OptionalField::Present(DataLossProtect {
34493463
your_last_per_commitment_secret: [0;32],
3450-
my_current_per_commitment_point: PublicKey::from_secret_key(&self.secp_ctx, &self.build_local_commitment_secret(self.cur_local_commitment_transaction_number))
3464+
my_current_per_commitment_point: PublicKey::from_secret_key(&self.secp_ctx, &self.build_local_commitment_secret(self.cur_local_commitment_transaction_number + 1))
34513465
})
34523466
};
34533467
msgs::ChannelReestablish {
@@ -3760,7 +3774,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
37603774
/// those explicitly stated to be allowed after shutdown completes, eg some simple getters).
37613775
/// Also returns the list of payment_hashes for channels which we can safely fail backwards
37623776
/// immediately (others we will have to allow to time out).
3763-
pub fn force_shutdown(&mut self) -> (Vec<Transaction>, Vec<(HTLCSource, PaymentHash)>) {
3777+
pub fn force_shutdown(&mut self, should_broadcast: bool) -> (Option<OutPoint>, ChannelMonitorUpdate, Vec<(HTLCSource, PaymentHash)>) {
37643778
assert!(self.channel_state != ChannelState::ShutdownComplete as u32);
37653779

37663780
// We go ahead and "free" any holding cell HTLCs or HTLCs we haven't yet committed to and
@@ -3783,12 +3797,11 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
37833797

37843798
self.channel_state = ChannelState::ShutdownComplete as u32;
37853799
self.update_time_counter += 1;
3786-
if self.channel_monitor.is_some() {
3787-
(self.channel_monitor.as_mut().unwrap().get_latest_local_commitment_txn(), dropped_outbound_htlcs)
3788-
} else {
3789-
// We aren't even signed funding yet, so can't broadcast anything
3790-
(Vec::new(), dropped_outbound_htlcs)
3791-
}
3800+
self.latest_monitor_update_id += 1;
3801+
(self.funding_txo.clone(), ChannelMonitorUpdate {
3802+
update_id: self.latest_monitor_update_id,
3803+
updates: vec![ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast }],
3804+
}, dropped_outbound_htlcs)
37923805
}
37933806
}
37943807

@@ -4255,22 +4268,28 @@ impl<ChanSigner: ChannelKeys + Readable> ReadableArgs<Arc<Logger>> for Channel<C
42554268

42564269
#[cfg(test)]
42574270
mod tests {
4271+
use bitcoin::BitcoinHash;
42584272
use bitcoin::util::bip143;
42594273
use bitcoin::consensus::encode::serialize;
42604274
use bitcoin::blockdata::script::{Script, Builder};
4261-
use bitcoin::blockdata::transaction::Transaction;
4275+
use bitcoin::blockdata::transaction::{Transaction, TxOut};
4276+
use bitcoin::blockdata::constants::genesis_block;
42624277
use bitcoin::blockdata::opcodes;
4278+
use bitcoin::network::constants::Network;
42634279
use bitcoin_hashes::hex::FromHex;
42644280
use hex;
42654281
use ln::channelmanager::{HTLCSource, PaymentPreimage, PaymentHash};
42664282
use ln::channel::{Channel,ChannelKeys,InboundHTLCOutput,OutboundHTLCOutput,InboundHTLCState,OutboundHTLCState,HTLCOutputInCommitment,TxCreationKeys};
42674283
use ln::channel::MAX_FUNDING_SATOSHIS;
4284+
use ln::features::InitFeatures;
4285+
use ln::msgs::{OptionalField, DataLossProtect};
42684286
use ln::chan_utils;
42694287
use ln::chan_utils::{LocalCommitmentTransaction, ChannelPublicKeys};
42704288
use chain::chaininterface::{FeeEstimator,ConfirmationTarget};
42714289
use chain::keysinterface::{InMemoryChannelKeys, KeysInterface};
42724290
use chain::transaction::OutPoint;
42734291
use util::config::UserConfig;
4292+
use util::enforcing_trait_impls::EnforcingChannelKeys;
42744293
use util::test_utils;
42754294
use util::logger::Logger;
42764295
use secp256k1::{Secp256k1, Message, Signature, All};
@@ -4280,6 +4299,7 @@ mod tests {
42804299
use bitcoin_hashes::hash160::Hash as Hash160;
42814300
use bitcoin_hashes::Hash;
42824301
use std::sync::Arc;
4302+
use rand::{thread_rng,Rng};
42834303

42844304
struct TestFeeEstimator {
42854305
fee_est: u64
@@ -4327,6 +4347,70 @@ mod tests {
43274347
PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode(hex).unwrap()[..]).unwrap())
43284348
}
43294349

4350+
#[test]
4351+
fn channel_reestablish_no_updates() {
4352+
let feeest = TestFeeEstimator{fee_est: 15000};
4353+
let logger : Arc<Logger> = Arc::new(test_utils::TestLogger::new());
4354+
let secp_ctx = Secp256k1::new();
4355+
let mut seed = [0; 32];
4356+
let mut rng = thread_rng();
4357+
rng.fill_bytes(&mut seed);
4358+
let network = Network::Testnet;
4359+
let keys_provider = test_utils::TestKeysInterface::new(&seed, network, logger.clone() as Arc<Logger>);
4360+
4361+
// Go through the flow of opening a channel between two nodes.
4362+
4363+
// Create Node A's channel
4364+
let node_a_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
4365+
let config = UserConfig::default();
4366+
let mut node_a_chan = Channel::<EnforcingChannelKeys>::new_outbound(&&feeest, &&keys_provider, node_a_node_id, 10000000, 100000, 42, Arc::clone(&logger), &config).unwrap();
4367+
4368+
// Create Node B's channel by receiving Node A's open_channel message
4369+
let open_channel_msg = node_a_chan.get_open_channel(genesis_block(network).header.bitcoin_hash(), &&feeest);
4370+
let node_b_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[7; 32]).unwrap());
4371+
let mut node_b_chan = Channel::<EnforcingChannelKeys>::new_from_req(&&feeest, &&keys_provider, node_b_node_id, InitFeatures::supported(), &open_channel_msg, 7, logger, &config).unwrap();
4372+
4373+
// Node B --> Node A: accept channel
4374+
let accept_channel_msg = node_b_chan.get_accept_channel();
4375+
node_a_chan.accept_channel(&accept_channel_msg, &config, InitFeatures::supported()).unwrap();
4376+
4377+
// Node A --> Node B: funding created
4378+
let output_script = node_a_chan.get_funding_redeemscript();
4379+
let tx = Transaction { version: 1, lock_time: 0, input: Vec::new(), output: vec![TxOut {
4380+
value: 10000000, script_pubkey: output_script.clone(),
4381+
}]};
4382+
let funding_outpoint = OutPoint::new(tx.txid(), 0);
4383+
let (funding_created_msg, _) = node_a_chan.get_outbound_funding_created(funding_outpoint).unwrap();
4384+
let (funding_signed_msg, _) = node_b_chan.funding_created(&funding_created_msg).unwrap();
4385+
4386+
// Node B --> Node A: funding signed
4387+
let _ = node_a_chan.funding_signed(&funding_signed_msg);
4388+
4389+
// Now disconnect the two nodes and check that the commitment point in
4390+
// Node B's channel_reestablish message is sane.
4391+
node_b_chan.remove_uncommitted_htlcs_and_mark_paused();
4392+
let expected_commitment_point = PublicKey::from_secret_key(&secp_ctx, &node_b_chan.build_local_commitment_secret(node_b_chan.cur_local_commitment_transaction_number + 1));
4393+
let msg = node_b_chan.get_channel_reestablish();
4394+
match msg.data_loss_protect {
4395+
OptionalField::Present(DataLossProtect { my_current_per_commitment_point, .. }) => {
4396+
assert_eq!(expected_commitment_point, my_current_per_commitment_point);
4397+
},
4398+
_ => panic!()
4399+
}
4400+
4401+
// Check that the commitment point in Node A's channel_reestablish message
4402+
// is sane.
4403+
node_a_chan.remove_uncommitted_htlcs_and_mark_paused();
4404+
let expected_commitment_point = PublicKey::from_secret_key(&secp_ctx, &node_a_chan.build_local_commitment_secret(node_a_chan.cur_local_commitment_transaction_number + 1));
4405+
let msg = node_a_chan.get_channel_reestablish();
4406+
match msg.data_loss_protect {
4407+
OptionalField::Present(DataLossProtect { my_current_per_commitment_point, .. }) => {
4408+
assert_eq!(expected_commitment_point, my_current_per_commitment_point);
4409+
},
4410+
_ => panic!()
4411+
}
4412+
}
4413+
43304414
#[test]
43314415
fn outbound_commitment_test() {
43324416
// Test vectors from BOLT 3 Appendix C:

0 commit comments

Comments
 (0)