1 // Imports that need to be added manually
3 use bitcoin::blockdata::script::ScriptBuf;
4 use bitcoin::secp256k1::ecdh::SharedSecret;
5 use bitcoin::secp256k1::ecdsa::RecoverableSignature;
6 use bitcoin::secp256k1::schnorr;
7 use bitcoin::secp256k1::{self, PublicKey, Scalar, Secp256k1, SecretKey};
9 use lightning::blinded_path::{BlindedPath, EmptyNodeIdLookUp};
10 use lightning::ln::features::InitFeatures;
11 use lightning::ln::msgs::{self, DecodeError, OnionMessageHandler};
12 use lightning::ln::script::ShutdownScript;
13 use lightning::offers::invoice::UnsignedBolt12Invoice;
14 use lightning::offers::invoice_request::UnsignedInvoiceRequest;
15 use lightning::onion_message::async_payments::{
16 AsyncPaymentsMessageHandler, HeldHtlcAvailable, ReleaseHeldHtlc,
18 use lightning::onion_message::messenger::{
19 CustomOnionMessageHandler, Destination, MessageRouter, OnionMessagePath, OnionMessenger,
20 PendingOnionMessage, Responder, ResponseInstruction,
22 use lightning::onion_message::offers::{OffersMessage, OffersMessageHandler};
23 use lightning::onion_message::packet::OnionMessageContents;
24 use lightning::sign::{EntropySource, KeyMaterial, NodeSigner, Recipient, SignerProvider};
25 use lightning::util::logger::Logger;
26 use lightning::util::ser::{Readable, Writeable, Writer};
27 use lightning::util::test_channel_signer::TestChannelSigner;
29 use crate::utils::test_logger;
31 use std::io::{self, Cursor};
32 use std::sync::atomic::{AtomicU64, Ordering};
35 /// Actual fuzz test, method signature and name are fixed
36 pub fn do_test<L: Logger>(data: &[u8], logger: &L) {
37 if let Ok(msg) = <msgs::OnionMessage as Readable>::read(&mut Cursor::new(data)) {
38 let mut secret_bytes = [1; 32];
40 let secret = SecretKey::from_slice(&secret_bytes).unwrap();
41 let keys_manager = KeyProvider { node_secret: secret, counter: AtomicU64::new(0) };
42 let node_id_lookup = EmptyNodeIdLookUp {};
43 let message_router = TestMessageRouter {};
44 let offers_msg_handler = TestOffersMessageHandler {};
45 let async_payments_msg_handler = TestAsyncPaymentsMessageHandler {};
46 let custom_msg_handler = TestCustomMessageHandler {};
47 let onion_messenger = OnionMessenger::new(
54 &async_payments_msg_handler,
59 let mut secret_bytes = [0; 32];
61 let secret = SecretKey::from_slice(&secret_bytes).unwrap();
62 PublicKey::from_secret_key(&Secp256k1::signing_only(), &secret)
65 let mut features = InitFeatures::empty();
66 features.set_onion_messages_optional();
67 let init = msgs::Init { features, networks: None, remote_network_address: None };
69 onion_messenger.peer_connected(&peer_node_id, &init, false).unwrap();
70 onion_messenger.handle_onion_message(&peer_node_id, &msg);
74 /// Method that needs to be added manually, {name}_test
75 pub fn onion_message_test<Out: test_logger::Output>(data: &[u8], out: Out) {
76 let logger = test_logger::TestLogger::new("".to_owned(), out);
77 do_test(data, &logger);
80 /// Method that needs to be added manually, {name}_run
82 pub extern "C" fn onion_message_run(data: *const u8, datalen: usize) {
83 let logger = test_logger::TestLogger::new("".to_owned(), test_logger::DevNull {});
84 do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, &logger);
87 struct TestMessageRouter {}
89 impl MessageRouter for TestMessageRouter {
91 &self, _sender: PublicKey, _peers: Vec<PublicKey>, destination: Destination,
92 ) -> Result<OnionMessagePath, ()> {
93 Ok(OnionMessagePath { intermediate_nodes: vec![], destination, first_node_addresses: None })
96 fn create_blinded_paths<T: secp256k1::Signing + secp256k1::Verification>(
97 &self, _recipient: PublicKey, _peers: Vec<PublicKey>, _secp_ctx: &Secp256k1<T>,
98 ) -> Result<Vec<BlindedPath>, ()> {
103 struct TestOffersMessageHandler {}
105 impl OffersMessageHandler for TestOffersMessageHandler {
107 &self, _message: OffersMessage, _responder: Option<Responder>,
108 ) -> ResponseInstruction<OffersMessage> {
109 ResponseInstruction::NoResponse
113 struct TestAsyncPaymentsMessageHandler {}
115 impl AsyncPaymentsMessageHandler for TestAsyncPaymentsMessageHandler {
116 fn held_htlc_available(
117 &self, message: HeldHtlcAvailable, responder: Option<Responder>,
118 ) -> ResponseInstruction<ReleaseHeldHtlc> {
119 let responder = match responder {
121 None => return ResponseInstruction::NoResponse,
124 .respond(ReleaseHeldHtlc { payment_release_secret: message.payment_release_secret })
126 fn release_held_htlc(&self, _message: ReleaseHeldHtlc) {}
130 struct TestCustomMessage {}
132 const CUSTOM_MESSAGE_TYPE: u64 = 4242;
133 const CUSTOM_MESSAGE_CONTENTS: [u8; 32] = [42; 32];
135 impl OnionMessageContents for TestCustomMessage {
136 fn tlv_type(&self) -> u64 {
139 fn msg_type(&self) -> &'static str {
144 impl Writeable for TestCustomMessage {
145 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
146 Ok(CUSTOM_MESSAGE_CONTENTS.write(w)?)
150 struct TestCustomMessageHandler {}
152 impl CustomOnionMessageHandler for TestCustomMessageHandler {
153 type CustomMessage = TestCustomMessage;
154 fn handle_custom_message(
155 &self, message: Self::CustomMessage, responder: Option<Responder>,
156 ) -> ResponseInstruction<Self::CustomMessage> {
158 Some(responder) => responder.respond(message),
159 None => ResponseInstruction::NoResponse,
162 fn read_custom_message<R: io::Read>(
163 &self, _message_type: u64, buffer: &mut R,
164 ) -> Result<Option<Self::CustomMessage>, msgs::DecodeError> {
165 let mut buf = Vec::new();
166 buffer.read_to_end(&mut buf)?;
167 return Ok(Some(TestCustomMessage {}));
169 fn release_pending_custom_messages(&self) -> Vec<PendingOnionMessage<Self::CustomMessage>> {
174 pub struct VecWriter(pub Vec<u8>);
175 impl Writer for VecWriter {
176 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
177 self.0.extend_from_slice(buf);
182 node_secret: SecretKey,
186 impl EntropySource for KeyProvider {
187 fn get_secure_random_bytes(&self) -> [u8; 32] {
188 let ctr = self.counter.fetch_add(1, Ordering::Relaxed);
190 let random_bytes = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
191 (ctr >> 8*7) as u8, (ctr >> 8*6) as u8, (ctr >> 8*5) as u8, (ctr >> 8*4) as u8,
192 (ctr >> 8*3) as u8, (ctr >> 8*2) as u8, (ctr >> 8*1) as u8, 14, (ctr >> 8*0) as u8];
197 impl NodeSigner for KeyProvider {
198 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
199 let node_secret = match recipient {
200 Recipient::Node => Ok(&self.node_secret),
201 Recipient::PhantomNode => Err(()),
203 Ok(PublicKey::from_secret_key(&Secp256k1::signing_only(), node_secret))
207 &self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>,
208 ) -> Result<SharedSecret, ()> {
209 let mut node_secret = match recipient {
210 Recipient::Node => Ok(self.node_secret.clone()),
211 Recipient::PhantomNode => Err(()),
213 if let Some(tweak) = tweak {
214 node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?;
216 Ok(SharedSecret::new(other_key, &node_secret))
219 fn get_inbound_payment_key_material(&self) -> KeyMaterial {
224 &self, _hrp_bytes: &[u8], _invoice_data: &[u5], _recipient: Recipient,
225 ) -> Result<RecoverableSignature, ()> {
229 fn sign_bolt12_invoice_request(
230 &self, _invoice_request: &UnsignedInvoiceRequest,
231 ) -> Result<schnorr::Signature, ()> {
235 fn sign_bolt12_invoice(
236 &self, _invoice: &UnsignedBolt12Invoice,
237 ) -> Result<schnorr::Signature, ()> {
241 fn sign_gossip_message(
242 &self, _msg: lightning::ln::msgs::UnsignedGossipMessage,
243 ) -> Result<bitcoin::secp256k1::ecdsa::Signature, ()> {
248 impl SignerProvider for KeyProvider {
249 type EcdsaSigner = TestChannelSigner;
251 type TaprootSigner = TestChannelSigner;
253 fn generate_channel_keys_id(
254 &self, _inbound: bool, _channel_value_satoshis: u64, _user_channel_id: u128,
259 fn derive_channel_signer(
260 &self, _channel_value_satoshis: u64, _channel_keys_id: [u8; 32],
261 ) -> Self::EcdsaSigner {
265 fn read_chan_signer(&self, _data: &[u8]) -> Result<TestChannelSigner, DecodeError> {
269 fn get_destination_script(&self, _channel_keys_id: [u8; 32]) -> Result<ScriptBuf, ()> {
273 fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
280 use bitcoin::hashes::hex::FromHex;
281 use lightning::util::logger::{Logger, Record};
282 use std::collections::HashMap;
283 use std::sync::Mutex;
285 struct TrackingLogger {
286 /// (module, message) -> count
287 pub lines: Mutex<HashMap<(String, String), usize>>,
289 impl Logger for TrackingLogger {
290 fn log(&self, record: Record) {
291 let mut lines_lock = self.lines.lock().unwrap();
292 let key = (record.module_path.to_string(), format!("{}", record.args));
293 *lines_lock.entry(key).or_insert(0) += 1;
295 "{:<5} [{} : {}, {}] {}",
296 record.level.to_string(),
306 fn test_no_onion_message_breakage() {
308 020000000000000000000000000000000000000000000000000000000000000e01055600020000000000000\
309 000000000000000000000000000000000000000000000000e01ae0276020000000000000000000000000000\
310 000000000000000000000000000000000002020000000000000000000000000000000000000000000000000\
311 000000000000e0101022a0000000000000000000000000000014551231950b75fc4402da1732fc9bebf0010\
312 9500000000000000000000000000000004106d000000000000000000000000000000fd1092202a2a2a2a2a2\
313 a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a0000000000000000000000000000000000\
314 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
315 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
316 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
317 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
318 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
319 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
320 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
321 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
322 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
323 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
324 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
325 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
326 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
327 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
328 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
329 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
330 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
331 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
332 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
333 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
334 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
335 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
336 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
337 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
338 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
339 000000000000000000000000000000000000000005600000000000000000000000000000000000000000000\
341 let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
342 super::do_test(&<Vec<u8>>::from_hex(one_hop_om).unwrap(), &logger);
344 let log_entries = logger.lines.lock().unwrap();
345 assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(),
346 "Received an onion message with path_id None and a reply_path: Custom(TestCustomMessage)"
347 .to_string())), Some(&1));
348 assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(),
349 "Constructing onion message when responding with Custom Message to an onion message with path_id None: TestCustomMessage".to_string())), Some(&1));
350 assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(),
351 "Buffered onion message when responding with Custom Message to an onion message with path_id None".to_string())), Some(&1));
354 let two_unblinded_hops_om = "\
355 020000000000000000000000000000000000000000000000000000000000000e01055600020000000000000\
356 000000000000000000000000000000000000000000000000e01350433042102020202020202020202020202\
357 02020202020202020202020202020202020202026d000000000000000000000000000000eb0000000000000\
358 000000000000000000000000000000000000000000000000036041096000000000000000000000000000000\
359 fd1092202a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a000000000000000\
360 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
361 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
362 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
363 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
364 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
365 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
366 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
367 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
368 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
369 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
370 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
371 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
372 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
373 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
374 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
375 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
376 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
377 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
378 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
379 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
380 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
381 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
382 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
383 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
384 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
385 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
386 000000000000000000000000000000000000000004800000000000000000000000000000000000000000000\
388 let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
389 super::do_test(&<Vec<u8>>::from_hex(two_unblinded_hops_om).unwrap(), &logger);
391 let log_entries = logger.lines.lock().unwrap();
392 assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(), "Forwarding an onion message to peer 020202020202020202020202020202020202020202020202020202020202020202".to_string())), Some(&1));
395 let two_unblinded_two_blinded_om = "\
396 020000000000000000000000000000000000000000000000000000000000000e01055600020000000000000\
397 000000000000000000000000000000000000000000000000e01350433042102020202020202020202020202\
398 02020202020202020202020202020202020202026d0000000000000000000000000000009e0000000000000\
399 000000000000000000000000000000000000000000000000058045604210203030303030303030303030303\
400 030303030303030303030303030303030303020821020000000000000000000000000000000000000000000\
401 000000000000000000e0196000000000000000000000000000000e900000000000000000000000000000000\
402 000000000000000000000000000000350433042102040404040404040404040404040404040404040404040\
403 4040404040404040402ca000000000000000000000000000000420000000000000000000000000000000000\
404 00000000000000000000000000003604103f000000000000000000000000000000fd1092202a2a2a2a2a2a2\
405 a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a000000000000000000000000000000000000\
406 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
407 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
408 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
409 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
410 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
411 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
412 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
413 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
414 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
415 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
416 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
417 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
418 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
419 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
420 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
421 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
422 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
423 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
424 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
425 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
426 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
427 000000000000000000000000000000000000000004800000000000000000000000000000000000000000000\
429 let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
430 super::do_test(&<Vec<u8>>::from_hex(two_unblinded_two_blinded_om).unwrap(), &logger);
432 let log_entries = logger.lines.lock().unwrap();
433 assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(), "Forwarding an onion message to peer 020202020202020202020202020202020202020202020202020202020202020202".to_string())), Some(&1));
436 let three_blinded_om = "\
437 020000000000000000000000000000000000000000000000000000000000000e01055600020000000000000\
438 000000000000000000000000000000000000000000000000e01350433042102020202020202020202020202\
439 02020202020202020202020202020202020202026d000000000000000000000000000000b20000000000000\
440 000000000000000000000000000000000000000000000000035043304210203030303030303030303030303\
441 030303030303030303030303030303030303029600000000000000000000000000000033000000000000000\
442 000000000000000000000000000000000000000000000003604104e000000000000000000000000000000fd\
443 1092202a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a00000000000000000\
444 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
445 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
446 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
447 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
448 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
449 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
450 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
451 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
452 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
453 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
454 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
455 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
456 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
457 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
458 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
459 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
460 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
461 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
462 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
463 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
464 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
465 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
466 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
467 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\
468 000000000000000000000000000000000000000004800000000000000000000000000000000000000000000\
470 let logger = TrackingLogger { lines: Mutex::new(HashMap::new()) };
471 super::do_test(&<Vec<u8>>::from_hex(three_blinded_om).unwrap(), &logger);
473 let log_entries = logger.lines.lock().unwrap();
474 assert_eq!(log_entries.get(&("lightning::onion_message::messenger".to_string(), "Forwarding an onion message to peer 020202020202020202020202020202020202020202020202020202020202020202".to_string())), Some(&1));