Skip to content

Commit 0bb08f5

Browse files
committed
Added config file to allow users to specify channel limits as per bolt 2
1 parent 4cb059e commit 0bb08f5

File tree

5 files changed

+158
-40
lines changed

5 files changed

+158
-40
lines changed

fuzz/fuzz_targets/full_stack_target.rs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ use lightning::util::events::{EventsProvider,Event};
2222
use lightning::util::reset_rng_state;
2323
use lightning::util::logger::Logger;
2424
use lightning::util::sha2::Sha256;
25+
use lightning::util::UserConfigurations;
2526

2627
mod utils;
2728

@@ -235,8 +236,10 @@ pub fn do_test(data: &[u8], logger: &Arc<Logger>) {
235236
let watch = Arc::new(ChainWatchInterfaceUtil::new(Network::Bitcoin, Arc::clone(&logger)));
236237
let broadcast = Arc::new(TestBroadcaster{});
237238
let monitor = channelmonitor::SimpleManyChannelMonitor::new(watch.clone(), broadcast.clone());
238-
239-
let channelmanager = ChannelManager::new(our_network_key, slice_to_be32(get_slice!(4)), get_slice!(1)[0] != 0, Network::Bitcoin, fee_est.clone(), monitor.clone(), watch.clone(), broadcast.clone(), Arc::clone(&logger)).unwrap();
239+
let mut config = UserConfigurations::new();
240+
config.channel_options.fee_proportional_millionths = slice_to_be32(get_slice!(4));
241+
config.channel_options.announced_channel = (get_slice!(1)[0] != 0);
242+
let channelmanager = ChannelManager::new(our_network_key,Network::Bitcoin, fee_est.clone(), monitor.clone(), watch.clone(), broadcast.clone(), Arc::clone(&logger), config).unwrap();
240243
let router = Arc::new(Router::new(PublicKey::from_secret_key(&secp_ctx, &our_network_key), watch.clone(), Arc::clone(&logger)));
241244

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

src/ln/channel.rs

Lines changed: 50 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ use util::ser::Writeable;
2626
use util::sha2::Sha256;
2727
use util::logger::Logger;
2828
use util::errors::APIError;
29+
use util::configurations::{UserConfigurations,ChannelLimits,ChannelOptions};
2930

3031
use std;
3132
use std::default::Default;
@@ -273,18 +274,20 @@ const MULTI_STATE_FLAGS: u32 = (BOTH_SIDES_SHUTDOWN_MASK | ChannelState::PeerDis
273274

274275
const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
275276

277+
276278
// TODO: We should refactor this to be an Inbound/OutboundChannel until initial setup handshaking
277279
// has been completed, and then turn into a Channel to get compiler-time enforcement of things like
278280
// calling channel_id() before we're set up or things like get_outbound_funding_signed on an
279281
// inbound channel.
280282
pub(super) struct Channel {
283+
config : ChannelOptions,
284+
281285
user_id: u64,
282286

283287
channel_id: [u8; 32],
284288
channel_state: u32,
285289
channel_outbound: bool,
286290
secp_ctx: Secp256k1<secp256k1::All>,
287-
announce_publicly: bool,
288291
channel_value_satoshis: u64,
289292

290293
local_keys: ChannelKeys,
@@ -453,7 +456,7 @@ impl Channel {
453456
}
454457

455458
// Constructors:
456-
pub fn new_outbound(fee_estimator: &FeeEstimator, chan_keys: ChannelKeys, their_node_id: PublicKey, channel_value_satoshis: u64, push_msat: u64, announce_publicly: bool, user_id: u64, logger: Arc<Logger>) -> Result<Channel, APIError> {
459+
pub fn new_outbound(fee_estimator: &FeeEstimator, chan_keys: ChannelKeys, their_node_id: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64, logger: Arc<Logger>, configurations: &UserConfigurations) -> Result<Channel, APIError> {
457460
if channel_value_satoshis >= MAX_FUNDING_SATOSHIS {
458461
return Err(APIError::APIMisuseError{err: "funding value > 2^24"});
459462
}
@@ -480,12 +483,12 @@ impl Channel {
480483

481484
Ok(Channel {
482485
user_id: user_id,
486+
config: configurations.channel_options.clone(),
483487

484488
channel_id: rng::rand_u832(),
485489
channel_state: ChannelState::OurInitSent as u32,
486490
channel_outbound: true,
487491
secp_ctx: secp_ctx,
488-
announce_publicly: announce_publicly,
489492
channel_value_satoshis: channel_value_satoshis,
490493

491494
local_keys: chan_keys,
@@ -555,7 +558,8 @@ impl Channel {
555558

556559
/// Creates a new channel from a remote sides' request for one.
557560
/// Assumes chain_hash has already been checked and corresponds with what we expect!
558-
pub fn new_from_req(fee_estimator: &FeeEstimator, chan_keys: ChannelKeys, their_node_id: PublicKey, msg: &msgs::OpenChannel, user_id: u64, require_announce: bool, allow_announce: bool, logger: Arc<Logger>) -> Result<Channel, ChannelError> {
561+
pub fn new_from_req(fee_estimator: &FeeEstimator, chan_keys: ChannelKeys, their_node_id: PublicKey, msg: &msgs::OpenChannel, user_id: u64, logger: Arc<Logger>, configurations : &UserConfigurations) -> Result<Channel, ChannelError> {
562+
let mut local_config = (*configurations).channel_options.clone();
559563
// Check sanity of message fields:
560564
if msg.funding_satoshis >= MAX_FUNDING_SATOSHIS {
561565
return Err(ChannelError::Close("funding value > 2^24"));
@@ -586,16 +590,40 @@ impl Channel {
586590
if msg.max_accepted_htlcs > 483 {
587591
return Err(ChannelError::Close("max_accpted_htlcs > 483"));
588592
}
593+
//optional parameter checking
594+
// MAY fail the channel if
595+
if msg.funding_satoshis < configurations.channel_limits.funding_satoshis {
596+
return Err(ChannelError::Close("funding satoshis is less than the user specified limit"));
597+
}
598+
if msg.htlc_minimum_msat > configurations.channel_limits.htlc_minimum_msat {
599+
return Err(ChannelError::Close("htlc minimum msat is higher than the user specified limit"));
600+
}
601+
if msg.max_htlc_value_in_flight_msat < configurations.channel_limits.max_htlc_value_in_flight_msat {
602+
return Err(ChannelError::Close("max htlc value in flight msat is less than the user specified limit"));
603+
}
604+
if msg.channel_reserve_satoshis > configurations.channel_limits.channel_reserve_satoshis {
605+
return Err(ChannelError::Close("channel reserve satoshis is higher than the user specified limit"));
606+
}
607+
if msg.max_accepted_htlcs < configurations.channel_limits.max_accepted_htlcs {
608+
return Err(ChannelError::Close("max accepted htlcs is less than the user specified limit"));
609+
}
610+
if msg.dust_limit_satoshis < configurations.channel_limits.dust_limit_satoshis {
611+
return Err(ChannelError::Close("dust limit satoshis is less than the user specified limit"));
612+
}
589613

590614
// Convert things into internal flags and prep our state:
591615

592616
let their_announce = if (msg.channel_flags & 1) == 1 { true } else { false };
593-
if require_announce && !their_announce {
594-
return Err(ChannelError::Close("Peer tried to open unannounced channel, but we require public ones"));
595-
}
596-
if !allow_announce && their_announce {
597-
return Err(ChannelError::Close("Peer tried to open announced channel, but we require private ones"));
617+
if local_config.force_announced_channel_preference{
618+
if local_config.announced_channel && !their_announce {
619+
return Err(ChannelError::Close("Peer tried to open unannounced channel, but we require public ones"));
620+
}
621+
if !local_config.announced_channel && their_announce {
622+
return Err(ChannelError::Close("Peer tried to open announced channel, but we require private ones"));
623+
}
598624
}
625+
//we either accept their preference or the preferences match
626+
local_config.announced_channel = their_announce;
599627

600628
let background_feerate = fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Background);
601629

@@ -636,12 +664,12 @@ impl Channel {
636664

637665
let mut chan = Channel {
638666
user_id: user_id,
667+
config: local_config,
639668

640669
channel_id: msg.temporary_channel_id,
641670
channel_state: (ChannelState::OurInitSent as u32) | (ChannelState::TheirInitSent as u32),
642671
channel_outbound: false,
643672
secp_ctx: secp_ctx,
644-
announce_publicly: their_announce,
645673

646674
local_keys: chan_keys,
647675
cur_local_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
@@ -1282,7 +1310,7 @@ impl Channel {
12821310

12831311
// Message handlers:
12841312

1285-
pub fn accept_channel(&mut self, msg: &msgs::AcceptChannel) -> Result<(), ChannelError> {
1313+
pub fn accept_channel(&mut self, msg: &msgs::AcceptChannel, config : &UserConfigurations) -> Result<(), ChannelError> {
12861314
// Check sanity of message fields:
12871315
if !self.channel_outbound {
12881316
return Err(ChannelError::Close("Got an accept_channel message from an inbound peer"));
@@ -1320,16 +1348,10 @@ impl Channel {
13201348
if msg.max_accepted_htlcs > 483 {
13211349
return Err(ChannelError::Close("max_accpted_htlcs > 483"));
13221350
}
1323-
1324-
// TODO: Optional additional constraints mentioned in the spec
1325-
// MAY fail the channel if
1326-
// funding_satoshi is too small
1327-
// htlc_minimum_msat too large
1328-
// max_htlc_value_in_flight_msat too small
1329-
// channel_reserve_satoshis too large
1330-
// max_accepted_htlcs too small
1331-
// dust_limit_satoshis too small
1332-
1351+
//Optional user definined limits
1352+
if msg.minimum_depth > config.channel_limits.minimum_depth {
1353+
return Err(ChannelError::Close("We consider the minimum depth to be unreasonably large"));
1354+
}
13331355
self.channel_monitor.set_their_base_keys(&msg.htlc_basepoint, &msg.delayed_payment_basepoint);
13341356

13351357
self.their_dust_limit_satoshis = msg.dust_limit_satoshis;
@@ -2493,7 +2515,7 @@ impl Channel {
24932515
}
24942516

24952517
pub fn should_announce(&self) -> bool {
2496-
self.announce_publicly
2518+
self.config.announced_channel
24972519
}
24982520

24992521
pub fn is_outbound(&self) -> bool {
@@ -2683,7 +2705,7 @@ impl Channel {
26832705
delayed_payment_basepoint: PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.delayed_payment_base_key),
26842706
htlc_basepoint: PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.htlc_base_key),
26852707
first_per_commitment_point: PublicKey::from_secret_key(&self.secp_ctx, &local_commitment_secret),
2686-
channel_flags: if self.announce_publicly {1} else {0},
2708+
channel_flags: if self.config.announced_channel {1} else {0},
26872709
shutdown_scriptpubkey: None,
26882710
}
26892711
}
@@ -2787,7 +2809,7 @@ impl Channel {
27872809
/// Note that the "channel must be funded" requirement is stricter than BOLT 7 requires - see
27882810
/// https://github.com/lightningnetwork/lightning-rfc/issues/468
27892811
pub fn get_channel_announcement(&self, our_node_id: PublicKey, chain_hash: Sha256dHash) -> Result<(msgs::UnsignedChannelAnnouncement, Signature), ChannelError> {
2790-
if !self.announce_publicly {
2812+
if !self.config.announced_channel {
27912813
return Err(ChannelError::Ignore("Channel is not available for public announcements"));
27922814
}
27932815
if self.channel_state & (ChannelState::ChannelFunded as u32) == 0 {
@@ -3154,6 +3176,7 @@ mod tests {
31543176

31553177
#[test]
31563178
fn outbound_commitment_test() {
3179+
use util::configurations::UserConfigurations;
31573180
// Test vectors from BOLT 3 Appendix C:
31583181
let feeest = TestFeeEstimator{fee_est: 15000};
31593182
let logger : Arc<Logger> = Arc::new(test_utils::TestLogger::new());
@@ -3175,7 +3198,9 @@ mod tests {
31753198
hex::decode("023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb").unwrap()[..]);
31763199

31773200
let their_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap());
3178-
let mut chan = Channel::new_outbound(&feeest, chan_keys, their_node_id, 10000000, 100000, false, 42, Arc::clone(&logger)).unwrap(); // Nothing uses their network key in this test
3201+
let mut config = UserConfigurations::new();
3202+
config.channel_options.announced_channel= false;
3203+
let mut chan = Channel::new_outbound(&feeest, chan_keys, their_node_id, 10000000, 100000, 42, Arc::clone(&logger), &config).unwrap(); // Nothing uses their network key in this test
31793204
chan.their_to_self_delay = 144;
31803205
chan.our_dust_limit_satoshis = 546;
31813206

src/ln/channelmanager.rs

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ use ln::channelmonitor::ManyChannelMonitor;
2727
use ln::router::{Route,RouteHop};
2828
use ln::msgs;
2929
use ln::msgs::{HandleError,ChannelMessageHandler};
30+
use util::configurations::UserConfigurations;
3031
use util::{byte_utils, events, internal_traits, rng};
3132
use util::sha2::Sha256;
3233
use util::ser::{Readable, Writeable};
@@ -271,14 +272,13 @@ const ERR: () = "You need at least 32 bit pointers (well, usize, but we'll assum
271272
/// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
272273
/// to individual Channels.
273274
pub struct ChannelManager {
275+
configuration : UserConfigurations,
274276
genesis_hash: Sha256dHash,
275277
fee_estimator: Arc<FeeEstimator>,
276278
monitor: Arc<ManyChannelMonitor>,
277279
chain_monitor: Arc<ChainWatchInterface>,
278280
tx_broadcaster: Arc<BroadcasterInterface>,
279281

280-
announce_channels_publicly: bool,
281-
fee_proportional_millionths: u32,
282282
latest_block_height: AtomicUsize,
283283
secp_ctx: Secp256k1<secp256k1::All>,
284284

@@ -335,22 +335,19 @@ impl ChannelManager {
335335
/// This is the main "logic hub" for all channel-related actions, and implements
336336
/// ChannelMessageHandler.
337337
///
338-
/// fee_proportional_millionths is an optional fee to charge any payments routed through us.
339338
/// Non-proportional fees are fixed according to our risk using the provided fee estimator.
340339
///
341340
/// panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`!
342-
pub fn new(our_network_key: SecretKey, fee_proportional_millionths: u32, announce_channels_publicly: bool, network: Network, feeest: Arc<FeeEstimator>, monitor: Arc<ManyChannelMonitor>, chain_monitor: Arc<ChainWatchInterface>, tx_broadcaster: Arc<BroadcasterInterface>, logger: Arc<Logger>) -> Result<Arc<ChannelManager>, secp256k1::Error> {
341+
pub fn new(our_network_key: SecretKey, network: Network, feeest: Arc<FeeEstimator>, monitor: Arc<ManyChannelMonitor>, chain_monitor: Arc<ChainWatchInterface>, tx_broadcaster: Arc<BroadcasterInterface>, logger: Arc<Logger>, config : UserConfigurations) -> Result<Arc<ChannelManager>, secp256k1::Error> {
343342
let secp_ctx = Secp256k1::new();
344-
345343
let res = Arc::new(ChannelManager {
344+
configuration : config.clone(),
346345
genesis_hash: genesis_block(network).header.bitcoin_hash(),
347346
fee_estimator: feeest.clone(),
348347
monitor: monitor.clone(),
349348
chain_monitor,
350349
tx_broadcaster,
351350

352-
announce_channels_publicly,
353-
fee_proportional_millionths,
354351
latest_block_height: AtomicUsize::new(0), //TODO: Get an init value (generally need to replay recent chain on chain_monitor registration)
355352
secp_ctx,
356353

@@ -404,7 +401,7 @@ impl ChannelManager {
404401
}
405402
};
406403

407-
let channel = Channel::new_outbound(&*self.fee_estimator, chan_keys, their_network_key, channel_value_satoshis, push_msat, self.announce_channels_publicly, user_id, Arc::clone(&self.logger))?;
404+
let channel = Channel::new_outbound(&*self.fee_estimator, chan_keys, their_network_key, channel_value_satoshis, push_msat, user_id, Arc::clone(&self.logger), &self.configuration)?;
408405
let res = channel.get_open_channel(self.genesis_hash.clone(), &*self.fee_estimator);
409406
let mut channel_state = self.channel_state.lock().unwrap();
410407
match channel_state.by_id.entry(channel.channel_id()) {
@@ -955,7 +952,7 @@ impl ChannelManager {
955952
if !chan.is_live() {
956953
Some(("Forwarding channel is not in a ready state.", 0x1000 | 7, self.get_channel_update(chan).unwrap()))
957954
} else {
958-
let fee = amt_to_forward.checked_mul(self.fee_proportional_millionths as u64).and_then(|prop_fee| { (prop_fee / 1000000).checked_add(chan.get_our_fee_base_msat(&*self.fee_estimator) as u64) });
955+
let fee = amt_to_forward.checked_mul(self.configuration.channel_options.fee_proportional_millionths as u64).and_then(|prop_fee| { (prop_fee / 1000000).checked_add(chan.get_our_fee_base_msat(&*self.fee_estimator) as u64) });
959956
if fee.is_none() || msg.amount_msat < fee.unwrap() || (msg.amount_msat - fee.unwrap()) < *amt_to_forward {
960957
Some(("Prior hop has deviated from specified fees parameters or origin node has obsolete ones", 0x1000 | 12, self.get_channel_update(chan).unwrap()))
961958
} else {
@@ -992,7 +989,7 @@ impl ChannelManager {
992989
cltv_expiry_delta: CLTV_EXPIRY_DELTA,
993990
htlc_minimum_msat: chan.get_our_htlc_minimum_msat(),
994991
fee_base_msat: chan.get_our_fee_base_msat(&*self.fee_estimator),
995-
fee_proportional_millionths: self.fee_proportional_millionths,
992+
fee_proportional_millionths: self.configuration.channel_options.fee_proportional_millionths,
996993
excess_data: Vec::new(),
997994
};
998995

@@ -1509,7 +1506,7 @@ impl ChannelManager {
15091506
}
15101507
};
15111508

1512-
let channel = Channel::new_from_req(&*self.fee_estimator, chan_keys, their_node_id.clone(), msg, 0, false, self.announce_channels_publicly, Arc::clone(&self.logger))
1509+
let channel = Channel::new_from_req(&*self.fee_estimator, chan_keys, their_node_id.clone(), msg, 0, Arc::clone(&self.logger), &self.configuration)
15131510
.map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id))?;
15141511
let accept_msg = channel.get_accept_channel();
15151512
channel_state.by_id.insert(channel.channel_id(), channel);
@@ -1525,7 +1522,7 @@ impl ChannelManager {
15251522
//TODO: see issue #153, need a consistent behavior on obnoxious behavior from random node
15261523
return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
15271524
}
1528-
chan.accept_channel(&msg)
1525+
chan.accept_channel(&msg, &self.configuration)
15291526
.map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.temporary_channel_id))?;
15301527
(chan.get_value_satoshis(), chan.get_funding_redeemscript().to_v0_p2wsh(), chan.get_user_id())
15311528
},
@@ -3104,6 +3101,8 @@ mod tests {
31043101
}
31053102

31063103
fn create_network(node_count: usize) -> Vec<Node> {
3104+
use util::UserConfigurations;
3105+
31073106
let mut nodes = Vec::new();
31083107
let mut rng = thread_rng();
31093108
let secp_ctx = Secp256k1::new();
@@ -3122,7 +3121,11 @@ mod tests {
31223121
rng.fill_bytes(&mut key_slice);
31233122
SecretKey::from_slice(&secp_ctx, &key_slice).unwrap()
31243123
};
3125-
let node = ChannelManager::new(node_id.clone(), 0, true, Network::Testnet, feeest.clone(), chan_monitor.clone(), chain_monitor.clone(), tx_broadcaster.clone(), Arc::clone(&logger)).unwrap();
3124+
let mut config = UserConfigurations::new();
3125+
config.channel_options.announced_channel = true;
3126+
config.channel_options.fee_proportional_millionths = 0;
3127+
config.channel_options.force_announced_channel_preference = false;
3128+
let node = ChannelManager::new(node_id.clone(), Network::Testnet, feeest.clone(), chan_monitor.clone(), chain_monitor.clone(), tx_broadcaster.clone(), Arc::clone(&logger), config).unwrap();
31263129
let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &node_id), chain_monitor.clone(), Arc::clone(&logger));
31273130
nodes.push(Node { chain_monitor, tx_broadcaster, chan_monitor, node, router,
31283131
network_payment_count: payment_count.clone(),

0 commit comments

Comments
 (0)