Skip to content

Commit 83c9eb4

Browse files
authored
Merge pull request #435 from TheBlueMatt/2020-01-node_announce
Add ability to broadcast our own node_announcement
2 parents d850e12 + 78c48f7 commit 83c9eb4

File tree

8 files changed

+192
-72
lines changed

8 files changed

+192
-72
lines changed

fuzz/src/router.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,6 @@ pub fn do_test(data: &[u8]) {
124124
msgs::DecodeError::UnknownVersion => return,
125125
msgs::DecodeError::UnknownRequiredFeature => return,
126126
msgs::DecodeError::InvalidValue => return,
127-
msgs::DecodeError::ExtraAddressesPerType => return,
128127
msgs::DecodeError::BadLengthDescriptor => return,
129128
msgs::DecodeError::ShortRead => panic!("We picked the length..."),
130129
msgs::DecodeError::Io(e) => panic!(format!("{}", e)),

lightning/src/ln/channel.rs

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -295,7 +295,7 @@ pub(super) struct Channel<ChanSigner: ChannelKeys> {
295295
holding_cell_update_fee: Option<u64>,
296296
next_local_htlc_id: u64,
297297
next_remote_htlc_id: u64,
298-
channel_update_count: u32,
298+
update_time_counter: u32,
299299
feerate_per_kw: u64,
300300

301301
#[cfg(debug_assertions)]
@@ -490,7 +490,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
490490
holding_cell_update_fee: None,
491491
next_local_htlc_id: 0,
492492
next_remote_htlc_id: 0,
493-
channel_update_count: 1,
493+
update_time_counter: 1,
494494

495495
resend_order: RAACommitmentOrder::CommitmentFirst,
496496

@@ -714,7 +714,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
714714
holding_cell_update_fee: None,
715715
next_local_htlc_id: 0,
716716
next_remote_htlc_id: 0,
717-
channel_update_count: 1,
717+
update_time_counter: 1,
718718

719719
resend_order: RAACommitmentOrder::CommitmentFirst,
720720

@@ -1586,7 +1586,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
15861586
self.channel_state |= ChannelState::TheirFundingLocked as u32;
15871587
} else if non_shutdown_state == (ChannelState::FundingSent as u32 | ChannelState::OurFundingLocked as u32) {
15881588
self.channel_state = ChannelState::ChannelFunded as u32 | (self.channel_state & MULTI_STATE_FLAGS);
1589-
self.channel_update_count += 1;
1589+
self.update_time_counter += 1;
15901590
} else if (self.channel_state & (ChannelState::ChannelFunded as u32) != 0 &&
15911591
// Note that funding_signed/funding_created will have decremented both by 1!
15921592
self.cur_local_commitment_transaction_number == INITIAL_COMMITMENT_NUMBER - 1 &&
@@ -2480,7 +2480,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
24802480
}
24812481
Channel::<ChanSigner>::check_remote_fee(fee_estimator, msg.feerate_per_kw)?;
24822482
self.pending_update_fee = Some(msg.feerate_per_kw as u64);
2483-
self.channel_update_count += 1;
2483+
self.update_time_counter += 1;
24842484
Ok(())
24852485
}
24862486

@@ -2763,7 +2763,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
27632763
// From here on out, we may not fail!
27642764

27652765
self.channel_state |= ChannelState::RemoteShutdownSent as u32;
2766-
self.channel_update_count += 1;
2766+
self.update_time_counter += 1;
27672767

27682768
// We can't send our shutdown until we've committed all of our pending HTLCs, but the
27692769
// remote side is unlikely to accept any new HTLCs, so we go ahead and "free" any holding
@@ -2793,7 +2793,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
27932793
};
27942794

27952795
self.channel_state |= ChannelState::LocalShutdownSent as u32;
2796-
self.channel_update_count += 1;
2796+
self.update_time_counter += 1;
27972797

27982798
Ok((our_shutdown, self.maybe_propose_first_closing_signed(fee_estimator), dropped_outbound_htlcs))
27992799
}
@@ -2860,7 +2860,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
28602860
if last_fee == msg.fee_satoshis {
28612861
self.build_signed_closing_transaction(&mut closing_tx, &msg.signature, &our_sig);
28622862
self.channel_state = ChannelState::ShutdownComplete as u32;
2863-
self.channel_update_count += 1;
2863+
self.update_time_counter += 1;
28642864
return Ok((None, Some(closing_tx)));
28652865
}
28662866
}
@@ -2910,7 +2910,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
29102910
self.build_signed_closing_transaction(&mut closing_tx, &msg.signature, &our_sig);
29112911

29122912
self.channel_state = ChannelState::ShutdownComplete as u32;
2913-
self.channel_update_count += 1;
2913+
self.update_time_counter += 1;
29142914

29152915
Ok((Some(msgs::ClosingSigned {
29162916
channel_id: self.channel_id,
@@ -3022,8 +3022,8 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
30223022
}
30233023

30243024
/// Allowed in any state (including after shutdown)
3025-
pub fn get_channel_update_count(&self) -> u32 {
3026-
self.channel_update_count
3025+
pub fn get_update_time_counter(&self) -> u32 {
3026+
self.update_time_counter
30273027
}
30283028

30293029
pub fn get_latest_monitor_update_id(&self) -> u64 {
@@ -3149,7 +3149,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
31493149
panic!("Client called ChannelManager::funding_transaction_generated with bogus transaction!");
31503150
}
31513151
self.channel_state = ChannelState::ShutdownComplete as u32;
3152-
self.channel_update_count += 1;
3152+
self.update_time_counter += 1;
31533153
return Err(msgs::ErrorMessage {
31543154
channel_id: self.channel_id(),
31553155
data: "funding tx had wrong script/value".to_owned()
@@ -3175,6 +3175,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
31753175
}
31763176
if header.bitcoin_hash() != self.last_block_connected {
31773177
self.last_block_connected = header.bitcoin_hash();
3178+
self.update_time_counter = cmp::max(self.update_time_counter, header.time);
31783179
if let Some(channel_monitor) = self.channel_monitor.as_mut() {
31793180
channel_monitor.last_block_hash = self.last_block_connected;
31803181
}
@@ -3185,7 +3186,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
31853186
true
31863187
} else if non_shutdown_state == (ChannelState::FundingSent as u32 | ChannelState::TheirFundingLocked as u32) {
31873188
self.channel_state = ChannelState::ChannelFunded as u32 | (self.channel_state & MULTI_STATE_FLAGS);
3188-
self.channel_update_count += 1;
3189+
self.update_time_counter += 1;
31893190
true
31903191
} else if non_shutdown_state == (ChannelState::FundingSent as u32 | ChannelState::OurFundingLocked as u32) {
31913192
// We got a reorg but not enough to trigger a force close, just update
@@ -3728,7 +3729,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
37283729
} else {
37293730
self.channel_state |= ChannelState::LocalShutdownSent as u32;
37303731
}
3731-
self.channel_update_count += 1;
3732+
self.update_time_counter += 1;
37323733

37333734
// Go ahead and drop holding cell updates as we'd rather fail payments than wait to send
37343735
// our shutdown until we've committed all of the pending changes.
@@ -3777,7 +3778,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
37773778
}
37783779

37793780
self.channel_state = ChannelState::ShutdownComplete as u32;
3780-
self.channel_update_count += 1;
3781+
self.update_time_counter += 1;
37813782
if self.channel_monitor.is_some() {
37823783
(self.channel_monitor.as_mut().unwrap().get_latest_local_commitment_txn(), dropped_outbound_htlcs)
37833784
} else {
@@ -3964,7 +3965,7 @@ impl<ChanSigner: ChannelKeys + Writeable> Writeable for Channel<ChanSigner> {
39643965

39653966
self.next_local_htlc_id.write(writer)?;
39663967
(self.next_remote_htlc_id - dropped_inbound_htlcs).write(writer)?;
3967-
self.channel_update_count.write(writer)?;
3968+
self.update_time_counter.write(writer)?;
39683969
self.feerate_per_kw.write(writer)?;
39693970

39703971
match self.last_sent_closing_fee {
@@ -4124,7 +4125,7 @@ impl<ChanSigner: ChannelKeys + Readable> ReadableArgs<Arc<Logger>> for Channel<C
41244125

41254126
let next_local_htlc_id = Readable::read(reader)?;
41264127
let next_remote_htlc_id = Readable::read(reader)?;
4127-
let channel_update_count = Readable::read(reader)?;
4128+
let update_time_counter = Readable::read(reader)?;
41284129
let feerate_per_kw = Readable::read(reader)?;
41294130

41304131
let last_sent_closing_fee = match <u8 as Readable>::read(reader)? {
@@ -4203,7 +4204,7 @@ impl<ChanSigner: ChannelKeys + Readable> ReadableArgs<Arc<Logger>> for Channel<C
42034204
holding_cell_update_fee,
42044205
next_local_htlc_id,
42054206
next_remote_htlc_id,
4206-
channel_update_count,
4207+
update_time_counter,
42074208
feerate_per_kw,
42084209

42094210
#[cfg(debug_assertions)]

lightning/src/ln/channelmanager.rs

Lines changed: 78 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,8 @@ use chain::chaininterface::{BroadcasterInterface,ChainListener,FeeEstimator};
2929
use chain::transaction::OutPoint;
3030
use ln::channel::{Channel, ChannelError};
3131
use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, ManyChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
32+
use ln::features::{InitFeatures, NodeFeatures};
3233
use ln::router::Route;
33-
use ln::features::InitFeatures;
3434
use ln::msgs;
3535
use ln::onion_utils;
3636
use ln::msgs::{ChannelMessageHandler, DecodeError, LightningError};
@@ -368,6 +368,10 @@ pub struct ChannelManager<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref,
368368
channel_state: Mutex<ChannelHolder<ChanSigner>>,
369369
our_network_key: SecretKey,
370370

371+
/// Used to track the last value sent in a node_announcement "timestamp" field. We ensure this
372+
/// value increases strictly since we don't assume access to a time source.
373+
last_node_announcement_serial: AtomicUsize,
374+
371375
/// The bulk of our storage will eventually be here (channels and message queues and the like).
372376
/// If we are connected to a peer we always at least have an entry here, even if no channels
373377
/// are currently open with that peer.
@@ -665,6 +669,8 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref> ChannelMan
665669
}),
666670
our_network_key: keys_manager.get_node_secret(),
667671

672+
last_node_announcement_serial: AtomicUsize::new(0),
673+
668674
per_peer_state: RwLock::new(HashMap::new()),
669675

670676
pending_events: Mutex::new(Vec::new()),
@@ -1118,7 +1124,7 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref> ChannelMan
11181124
let unsigned = msgs::UnsignedChannelUpdate {
11191125
chain_hash: self.genesis_hash,
11201126
short_channel_id: short_channel_id,
1121-
timestamp: chan.get_channel_update_count(),
1127+
timestamp: chan.get_update_time_counter(),
11221128
flags: (!were_node_one) as u16 | ((!chan.is_live() as u16) << 1),
11231129
cltv_expiry_delta: CLTV_EXPIRY_DELTA,
11241130
htlc_minimum_msat: chan.get_our_htlc_minimum_msat(),
@@ -1334,6 +1340,57 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref> ChannelMan
13341340
})
13351341
}
13361342

1343+
#[allow(dead_code)]
1344+
// Messages of up to 64KB should never end up more than half full with addresses, as that would
1345+
// be absurd. We ensure this by checking that at least 500 (our stated public contract on when
1346+
// broadcast_node_announcement panics) of the maximum-length addresses would fit in a 64KB
1347+
// message...
1348+
const HALF_MESSAGE_IS_ADDRS: u32 = ::std::u16::MAX as u32 / (msgs::NetAddress::MAX_LEN as u32 + 1) / 2;
1349+
#[deny(const_err)]
1350+
#[allow(dead_code)]
1351+
// ...by failing to compile if the number of addresses that would be half of a message is
1352+
// smaller than 500:
1353+
const STATIC_ASSERT: u32 = Self::HALF_MESSAGE_IS_ADDRS - 500;
1354+
1355+
/// Generates a signed node_announcement from the given arguments and creates a
1356+
/// BroadcastNodeAnnouncement event. Note that such messages will be ignored unless peers have
1357+
/// seen a channel_announcement from us (ie unless we have public channels open).
1358+
///
1359+
/// RGB is a node "color" and alias is a printable human-readable string to describe this node
1360+
/// to humans. They carry no in-protocol meaning.
1361+
///
1362+
/// addresses represent the set (possibly empty) of socket addresses on which this node accepts
1363+
/// incoming connections. These will be broadcast to the network, publicly tying these
1364+
/// addresses together. If you wish to preserve user privacy, addresses should likely contain
1365+
/// only Tor Onion addresses.
1366+
///
1367+
/// Panics if addresses is absurdly large (more than 500).
1368+
pub fn broadcast_node_announcement(&self, rgb: [u8; 3], alias: [u8; 32], addresses: Vec<msgs::NetAddress>) {
1369+
let _ = self.total_consistency_lock.read().unwrap();
1370+
1371+
if addresses.len() > 500 {
1372+
panic!("More than half the message size was taken up by public addresses!");
1373+
}
1374+
1375+
let announcement = msgs::UnsignedNodeAnnouncement {
1376+
features: NodeFeatures::supported(),
1377+
timestamp: self.last_node_announcement_serial.fetch_add(1, Ordering::AcqRel) as u32,
1378+
node_id: self.get_our_node_id(),
1379+
rgb, alias, addresses,
1380+
excess_address_data: Vec::new(),
1381+
excess_data: Vec::new(),
1382+
};
1383+
let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
1384+
1385+
let mut channel_state = self.channel_state.lock().unwrap();
1386+
channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastNodeAnnouncement {
1387+
msg: msgs::NodeAnnouncement {
1388+
signature: self.secp_ctx.sign(&msghash, &self.our_network_key),
1389+
contents: announcement
1390+
},
1391+
});
1392+
}
1393+
13371394
/// Processes HTLCs which are pending waiting on random forward delay.
13381395
///
13391396
/// Should only really ever be called in response to a PendingHTLCsForwardable event.
@@ -2719,6 +2776,18 @@ impl<ChanSigner: ChannelKeys, M: Deref + Sync + Send, T: Deref + Sync + Send, K:
27192776
}
27202777
self.latest_block_height.store(height as usize, Ordering::Release);
27212778
*self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header_hash;
2779+
loop {
2780+
// Update last_node_announcement_serial to be the max of its current value and the
2781+
// block timestamp. This should keep us close to the current time without relying on
2782+
// having an explicit local time source.
2783+
// Just in case we end up in a race, we loop until we either successfully update
2784+
// last_node_announcement_serial or decide we don't need to.
2785+
let old_serial = self.last_node_announcement_serial.load(Ordering::Acquire);
2786+
if old_serial >= header.time as usize { break; }
2787+
if self.last_node_announcement_serial.compare_exchange(old_serial, header.time as usize, Ordering::AcqRel, Ordering::Relaxed).is_ok() {
2788+
break;
2789+
}
2790+
}
27222791
}
27232792

27242793
/// We force-close the channel without letting our counterparty participate in the shutdown
@@ -2970,6 +3039,7 @@ impl<ChanSigner: ChannelKeys, M: Deref + Sync + Send, T: Deref + Sync + Send, K:
29703039
&events::MessageSendEvent::SendShutdown { ref node_id, .. } => node_id != their_node_id,
29713040
&events::MessageSendEvent::SendChannelReestablish { ref node_id, .. } => node_id != their_node_id,
29723041
&events::MessageSendEvent::BroadcastChannelAnnouncement { .. } => true,
3042+
&events::MessageSendEvent::BroadcastNodeAnnouncement { .. } => true,
29733043
&events::MessageSendEvent::BroadcastChannelUpdate { .. } => true,
29743044
&events::MessageSendEvent::HandleError { ref node_id, .. } => node_id != their_node_id,
29753045
&events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => true,
@@ -3288,6 +3358,8 @@ impl<ChanSigner: ChannelKeys + Writeable, M: Deref, T: Deref, K: Deref, F: Deref
32883358
peer_state.latest_features.write(writer)?;
32893359
}
32903360

3361+
(self.last_node_announcement_serial.load(Ordering::Acquire) as u32).write(writer)?;
3362+
32913363
Ok(())
32923364
}
32933365
}
@@ -3459,6 +3531,8 @@ impl<'a, ChanSigner: ChannelKeys + Readable, M: Deref, T: Deref, K: Deref, F: De
34593531
per_peer_state.insert(peer_pubkey, Mutex::new(peer_state));
34603532
}
34613533

3534+
let last_node_announcement_serial: u32 = Readable::read(reader)?;
3535+
34623536
let channel_manager = ChannelManager {
34633537
genesis_hash,
34643538
fee_estimator: args.fee_estimator,
@@ -3478,6 +3552,8 @@ impl<'a, ChanSigner: ChannelKeys + Readable, M: Deref, T: Deref, K: Deref, F: De
34783552
}),
34793553
our_network_key: args.keys_manager.get_node_secret(),
34803554

3555+
last_node_announcement_serial: AtomicUsize::new(last_node_announcement_serial as usize),
3556+
34813557
per_peer_state: RwLock::new(per_peer_state),
34823558

34833559
pending_events: Mutex::new(Vec::new()),

lightning/src/ln/functional_test_utils.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -394,10 +394,33 @@ pub fn create_announced_chan_between_nodes<'a, 'b, 'c, 'd>(nodes: &'a Vec<Node<'
394394

395395
pub fn create_announced_chan_between_nodes_with_value<'a, 'b, 'c, 'd>(nodes: &'a Vec<Node<'b, 'c, 'd>>, a: usize, b: usize, channel_value: u64, push_msat: u64, a_flags: InitFeatures, b_flags: InitFeatures) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
396396
let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat, a_flags, b_flags);
397+
398+
nodes[a].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
399+
let a_events = nodes[a].node.get_and_clear_pending_msg_events();
400+
assert_eq!(a_events.len(), 1);
401+
let a_node_announcement = match a_events[0] {
402+
MessageSendEvent::BroadcastNodeAnnouncement { ref msg } => {
403+
(*msg).clone()
404+
},
405+
_ => panic!("Unexpected event"),
406+
};
407+
408+
nodes[b].node.broadcast_node_announcement([1, 1, 1], [1; 32], Vec::new());
409+
let b_events = nodes[b].node.get_and_clear_pending_msg_events();
410+
assert_eq!(b_events.len(), 1);
411+
let b_node_announcement = match b_events[0] {
412+
MessageSendEvent::BroadcastNodeAnnouncement { ref msg } => {
413+
(*msg).clone()
414+
},
415+
_ => panic!("Unexpected event"),
416+
};
417+
397418
for node in nodes {
398419
assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
399420
node.router.handle_channel_update(&chan_announcement.1).unwrap();
400421
node.router.handle_channel_update(&chan_announcement.2).unwrap();
422+
node.router.handle_node_announcement(&a_node_announcement).unwrap();
423+
node.router.handle_node_announcement(&b_node_announcement).unwrap();
401424
}
402425
(chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
403426
}

0 commit comments

Comments
 (0)