Skip to content

Commit

Permalink
Add the stfu message as well
Browse files Browse the repository at this point in the history
  • Loading branch information
optout21 committed Nov 6, 2023
1 parent 4072e8b commit e865e86
Show file tree
Hide file tree
Showing 14 changed files with 213 additions and 1 deletion.
1 change: 1 addition & 0 deletions fuzz/src/bin/gen_target.sh
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ GEN_TEST msg_tx_init_rbf msg_targets::
GEN_TEST msg_tx_ack_rbf msg_targets::
GEN_TEST msg_tx_abort msg_targets::

GEN_TEST msg_stfu msg_targets::
GEN_TEST msg_splice msg_targets::
GEN_TEST msg_splice_ack msg_targets::
GEN_TEST msg_splice_locked msg_targets::
113 changes: 113 additions & 0 deletions fuzz/src/bin/msg_stfu_target.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
// This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.

// This file is auto-generated by gen_target.sh based on target_template.txt
// To modify it, modify target_template.txt and run gen_target.sh instead.

#![cfg_attr(feature = "libfuzzer_fuzz", no_main)]

#[cfg(not(fuzzing))]
compile_error!("Fuzz targets need cfg=fuzzing");

extern crate lightning_fuzz;
use lightning_fuzz::msg_targets::msg_stfu::*;

#[cfg(feature = "afl")]
#[macro_use] extern crate afl;
#[cfg(feature = "afl")]
fn main() {
fuzz!(|data| {
msg_stfu_run(data.as_ptr(), data.len());
});
}

#[cfg(feature = "honggfuzz")]
#[macro_use] extern crate honggfuzz;
#[cfg(feature = "honggfuzz")]
fn main() {
loop {
fuzz!(|data| {
msg_stfu_run(data.as_ptr(), data.len());
});
}
}

#[cfg(feature = "libfuzzer_fuzz")]
#[macro_use] extern crate libfuzzer_sys;
#[cfg(feature = "libfuzzer_fuzz")]
fuzz_target!(|data: &[u8]| {
msg_stfu_run(data.as_ptr(), data.len());
});

#[cfg(feature = "stdin_fuzz")]
fn main() {
use std::io::Read;

let mut data = Vec::with_capacity(8192);
std::io::stdin().read_to_end(&mut data).unwrap();
msg_stfu_run(data.as_ptr(), data.len());
}

#[test]
fn run_test_cases() {
use std::fs;
use std::io::Read;
use lightning_fuzz::utils::test_logger::StringBuffer;

use std::sync::{atomic, Arc};
{
let data: Vec<u8> = vec![0];
msg_stfu_run(data.as_ptr(), data.len());
}
let mut threads = Vec::new();
let threads_running = Arc::new(atomic::AtomicUsize::new(0));
if let Ok(tests) = fs::read_dir("test_cases/msg_stfu") {
for test in tests {
let mut data: Vec<u8> = Vec::new();
let path = test.unwrap().path();
fs::File::open(&path).unwrap().read_to_end(&mut data).unwrap();
threads_running.fetch_add(1, atomic::Ordering::AcqRel);

let thread_count_ref = Arc::clone(&threads_running);
let main_thread_ref = std::thread::current();
threads.push((path.file_name().unwrap().to_str().unwrap().to_string(),
std::thread::spawn(move || {
let string_logger = StringBuffer::new();

let panic_logger = string_logger.clone();
let res = if ::std::panic::catch_unwind(move || {
msg_stfu_test(&data, panic_logger);
}).is_err() {
Some(string_logger.into_string())
} else { None };
thread_count_ref.fetch_sub(1, atomic::Ordering::AcqRel);
main_thread_ref.unpark();
res
})
));
while threads_running.load(atomic::Ordering::Acquire) > 32 {
std::thread::park();
}
}
}
let mut failed_outputs = Vec::new();
for (test, thread) in threads.drain(..) {
if let Some(output) = thread.join().unwrap() {
println!("\nOutput of {}:\n{}\n", test, output);
failed_outputs.push(test);
}
}
if !failed_outputs.is_empty() {
println!("Test cases which failed: ");
for case in failed_outputs {
println!("{}", case);
}
panic!();
}
}
1 change: 1 addition & 0 deletions fuzz/src/msg_targets/gen_target.sh
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ GEN_TEST lightning::ln::msgs::TxInitRbf test_msg_simple ""
GEN_TEST lightning::ln::msgs::TxAckRbf test_msg_simple ""
GEN_TEST lightning::ln::msgs::TxAbort test_msg_simple ""

GEN_TEST lightning::ln::msgs::Stfu test_msg_simple ""
GEN_TEST lightning::ln::msgs::Splice test_msg_simple ""
GEN_TEST lightning::ln::msgs::SpliceAck test_msg_simple ""
GEN_TEST lightning::ln::msgs::SpliceLocked test_msg_simple ""
1 change: 1 addition & 0 deletions fuzz/src/msg_targets/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ pub mod msg_tx_signatures;
pub mod msg_tx_init_rbf;
pub mod msg_tx_ack_rbf;
pub mod msg_tx_abort;
pub mod msg_stfu;
pub mod msg_splice;
pub mod msg_splice_ack;
pub mod msg_splice_locked;
25 changes: 25 additions & 0 deletions fuzz/src/msg_targets/msg_stfu.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.

// This file is auto-generated by gen_target.sh based on msg_target_template.txt
// To modify it, modify msg_target_template.txt and run gen_target.sh instead.

use crate::msg_targets::utils::VecWriter;
use crate::utils::test_logger;

#[inline]
pub fn msg_stfu_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
test_msg_simple!(lightning::ln::msgs::Stfu, data);
}

#[no_mangle]
pub extern "C" fn msg_stfu_run(data: *const u8, datalen: usize) {
let data = unsafe { std::slice::from_raw_parts(data, datalen) };
test_msg_simple!(lightning::ln::msgs::Stfu, data);
}
1 change: 1 addition & 0 deletions fuzz/targets.h
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ void msg_tx_signatures_run(const unsigned char* data, size_t data_len);
void msg_tx_init_rbf_run(const unsigned char* data, size_t data_len);
void msg_tx_ack_rbf_run(const unsigned char* data, size_t data_len);
void msg_tx_abort_run(const unsigned char* data, size_t data_len);
void msg_stfu_run(const unsigned char* data, size_t data_len);
void msg_splice_run(const unsigned char* data, size_t data_len);
void msg_splice_ack_run(const unsigned char* data, size_t data_len);
void msg_splice_locked_run(const unsigned char* data, size_t data_len);
1 change: 1 addition & 0 deletions lightning-net-tokio/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -605,6 +605,7 @@ mod tests {
fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &ChannelUpdate) {}
fn handle_open_channel_v2(&self, _their_node_id: &PublicKey, _msg: &OpenChannelV2) {}
fn handle_accept_channel_v2(&self, _their_node_id: &PublicKey, _msg: &AcceptChannelV2) {}
fn handle_stfu(&self, _their_node_id: &PublicKey, _msg: &Stfu) {}
fn handle_splice(&self, _their_node_id: &PublicKey, _msg: &Splice) {}
fn handle_splice_ack(&self, _their_node_id: &PublicKey, _msg: &SpliceAck) {}
fn handle_splice_locked(&self, _their_node_id: &PublicKey, _msg: &SpliceLocked) {}
Expand Down
7 changes: 7 additions & 0 deletions lightning/src/events/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1642,6 +1642,13 @@ pub enum MessageSendEvent {
/// The message which should be sent.
msg: msgs::FundingSigned,
},
/// Used to indicate that a stfu message should be sent to the peer with the given node id.
SendStfu {
/// The node_id of the node which should receive this message
node_id: PublicKey,
/// The message which should be sent.
msg: msgs::Stfu,
},
/// Used to indicate that a splice message should be sent to the peer with the given node id.
SendSplice {
/// The node_id of the node which should receive this message
Expand Down
7 changes: 7 additions & 0 deletions lightning/src/ln/channelmanager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8521,6 +8521,12 @@ where
});
}

fn handle_stfu(&self, counterparty_node_id: &PublicKey, msg: &msgs::Stfu) {
let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
"Splicing not supported".to_owned(),
msg.channel_id.clone())), *counterparty_node_id);
}

fn handle_splice(&self, counterparty_node_id: &PublicKey, msg: &msgs::Splice) {
let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
"Splicing not supported".to_owned(),
Expand Down Expand Up @@ -8708,6 +8714,7 @@ where
&events::MessageSendEvent::SendChannelReady { .. } => false,
&events::MessageSendEvent::SendAnnouncementSignatures { .. } => false,
// Splicing
&events::MessageSendEvent::SendStfu { .. } => false,
&events::MessageSendEvent::SendSplice { .. } => false,
&events::MessageSendEvent::SendSpliceAck { .. } => false,
&events::MessageSendEvent::SendSpliceLocked { .. } => false,
Expand Down
3 changes: 3 additions & 0 deletions lightning/src/ln/functional_test_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -814,6 +814,9 @@ pub fn remove_first_msg_event_to_node(msg_node_id: &PublicKey, msg_events: &mut
MessageSendEvent::SendOpenChannelV2 { node_id, .. } => {
node_id == msg_node_id
},
MessageSendEvent::SendStfu { node_id, .. } => {
node_id == msg_node_id
},
MessageSendEvent::SendSplice { node_id, .. } => {
node_id == msg_node_id
},
Expand Down
29 changes: 28 additions & 1 deletion lightning/src/ln/msgs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,17 @@ pub struct ChannelReady {
pub short_channel_id_alias: Option<u64>,
}

/// A splice message to be sent by or received from the splice initiator.
/// An stfu (quiescence) message to be sent by or received from the stfu initiator.
// TODO(splicing): Add spec link for `splice`; still in draft, using from https://github.com/lightning/bolts/pull/863
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Stfu {
/// The channel ID where quiescence is intended
pub channel_id: ChannelId,
/// Initiator flag, 1 if initiating, 0 if replying to an stfu.
pub initiator: u8,
}

/// A splice message to be sent by or received from the stfu initiator (splice initiator).
// TODO(splicing): Add spec link for `splice`; still in draft, using from https://github.com/lightning/bolts/pull/863
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Splice {
Expand Down Expand Up @@ -1454,6 +1464,8 @@ pub trait ChannelMessageHandler : MessageSendEventsProvider {
fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned);

// Splicing
/// Handle an incoming `stfu` message from the given peer.
fn handle_stfu(&self, their_node_id: &PublicKey, msg: &Stfu);
/// Handle an incoming `splice` message from the given peer.
fn handle_splice(&self, their_node_id: &PublicKey, msg: &Splice);
/// Handle an incoming `splice_ack` message from the given peer.
Expand Down Expand Up @@ -1865,6 +1877,11 @@ impl_writeable_msg!(AcceptChannelV2, {
(2, require_confirmed_inputs, option),
});

impl_writeable_msg!(Stfu, {
channel_id,
initiator,
}, {});

impl_writeable_msg!(Splice, {
channel_id,
chain_hash,
Expand Down Expand Up @@ -3453,6 +3470,16 @@ mod tests {
assert_eq!(hex::encode(encoded_value), "02020202020202020202020202020202020202020202020202020202020202026fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000000000000001e240000007d000000000031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f");
}

#[test]
fn encoding_stfu() {
let stfu = msgs::Stfu {
channel_id: ChannelId::from_bytes([2; 32]),
initiator: 1,
};
let encoded_value = stfu.encode();
assert_eq!(hex::encode(encoded_value), "020202020202020202020202020202020202020202020202020202020202020201");
}

#[test]
fn encoding_splice_ack() {
let secp_ctx = Secp256k1::new();
Expand Down
12 changes: 12 additions & 0 deletions lightning/src/ln/peer_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,9 @@ impl ChannelMessageHandler for ErroringMessageHandler {
fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
}
fn handle_stfu(&self, their_node_id: &PublicKey, msg: &msgs::Stfu) {
ErroringMessageHandler::push_error(&self, their_node_id, msg.channel_id);
}
fn handle_splice(&self, their_node_id: &PublicKey, msg: &msgs::Splice) {
ErroringMessageHandler::push_error(&self, their_node_id, msg.channel_id);
}
Expand Down Expand Up @@ -1653,6 +1656,9 @@ impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CM
},

// Splicing messages:
wire::Message::Stfu(msg) => {
self.message_handler.chan_handler.handle_stfu(&their_node_id, &msg);
}
wire::Message::Splice(msg) => {
self.message_handler.chan_handler.handle_splice(&their_node_id, &msg);
}
Expand Down Expand Up @@ -1980,6 +1986,12 @@ impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CM
&msg.channel_id);
self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
},
MessageSendEvent::SendStfu { ref node_id, ref msg} => {
log_debug!(self.logger, "Handling SendStfu event in peer_handler for node {} for channel {}",
log_pubkey!(node_id),
&msg.channel_id);
self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
}
MessageSendEvent::SendSplice { ref node_id, ref msg} => {
log_debug!(self.logger, "Handling SendSplice event in peer_handler for node {} for channel {}",
log_pubkey!(node_id),
Expand Down
10 changes: 10 additions & 0 deletions lightning/src/ln/wire.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ pub(crate) enum Message<T> where T: core::fmt::Debug + Type + TestEq {
AcceptChannelV2(msgs::AcceptChannelV2),
FundingCreated(msgs::FundingCreated),
FundingSigned(msgs::FundingSigned),
Stfu(msgs::Stfu),
Splice(msgs::Splice),
SpliceAck(msgs::SpliceAck),
SpliceLocked(msgs::SpliceLocked),
Expand Down Expand Up @@ -113,6 +114,7 @@ impl<T> Writeable for Message<T> where T: core::fmt::Debug + Type + TestEq {
&Message::AcceptChannelV2(ref msg) => msg.write(writer),
&Message::FundingCreated(ref msg) => msg.write(writer),
&Message::FundingSigned(ref msg) => msg.write(writer),
&Message::Stfu(ref msg) => msg.write(writer),
&Message::Splice(ref msg) => msg.write(writer),
&Message::SpliceAck(ref msg) => msg.write(writer),
&Message::SpliceLocked(ref msg) => msg.write(writer),
Expand Down Expand Up @@ -167,6 +169,7 @@ impl<T> Type for Message<T> where T: core::fmt::Debug + Type + TestEq {
&Message::AcceptChannelV2(ref msg) => msg.type_id(),
&Message::FundingCreated(ref msg) => msg.type_id(),
&Message::FundingSigned(ref msg) => msg.type_id(),
&Message::Stfu(ref msg) => msg.type_id(),
&Message::Splice(ref msg) => msg.type_id(),
&Message::SpliceAck(ref msg) => msg.type_id(),
&Message::SpliceLocked(ref msg) => msg.type_id(),
Expand Down Expand Up @@ -270,6 +273,9 @@ fn do_read<R: io::Read, T, H: core::ops::Deref>(buffer: &mut R, message_type: u1
msgs::Splice::TYPE => {
Ok(Message::Splice(Readable::read(buffer)?))
},
msgs::Stfu::TYPE => {
Ok(Message::Stfu(Readable::read(buffer)?))
},
msgs::SpliceAck::TYPE => {
Ok(Message::SpliceAck(Readable::read(buffer)?))
},
Expand Down Expand Up @@ -426,6 +432,10 @@ impl<T: core::fmt::Debug + Writeable> Type for T where T: Encode {
fn type_id(&self) -> u16 { T::TYPE }
}

impl Encode for msgs::Stfu {
const TYPE: u16 = 2;
}

impl Encode for msgs::Init {
const TYPE: u16 = 16;
}
Expand Down
3 changes: 3 additions & 0 deletions lightning/src/util/test_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -651,6 +651,9 @@ impl msgs::ChannelMessageHandler for TestChannelMessageHandler {
fn handle_closing_signed(&self, _their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
self.received_msg(wire::Message::ClosingSigned(msg.clone()));
}
fn handle_stfu(&self, _their_node_id: &PublicKey, msg: &msgs::Stfu) {
self.received_msg(wire::Message::Stfu(msg.clone()));
}
fn handle_splice(&self, _their_node_id: &PublicKey, msg: &msgs::Splice) {
self.received_msg(wire::Message::Splice(msg.clone()));
}
Expand Down

0 comments on commit e865e86

Please sign in to comment.