Skip to main content

lightning/util/
macro_logger.rs

1// This file is Copyright its original authors, visible in version control
2// history.
3//
4// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7// You may not use this file except in accordance with one or both of these
8// licenses.
9
10use crate::ln::types::ChannelId;
11use crate::sign::SpendableOutputDescriptor;
12
13use bitcoin::transaction::Transaction;
14
15use crate::ln::chan_utils::HTLCClaim;
16use crate::routing::router::Route;
17
18macro_rules! log_iter {
19	($obj: expr) => {
20		$crate::util::logger::DebugIter($obj)
21	};
22}
23
24/// Logs a pubkey in hex format.
25#[macro_export]
26macro_rules! log_pubkey {
27	($obj: expr) => {
28		$crate::util::logger::DebugPubKey(&$obj)
29	};
30}
31
32/// Logs a byte slice in hex format.
33#[macro_export]
34macro_rules! log_bytes {
35	($obj: expr) => {
36		$crate::util::logger::DebugBytes(&$obj)
37	};
38}
39
40pub(crate) struct DebugFundingInfo<'a>(pub &'a ChannelId);
41impl<'a> core::fmt::Display for DebugFundingInfo<'a> {
42	fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
43		self.0.fmt(f)
44	}
45}
46macro_rules! log_funding_info {
47	($key_storage: expr) => {
48		$crate::util::macro_logger::DebugFundingInfo(&$key_storage.channel_id())
49	};
50}
51
52pub(crate) struct DebugRoute<'a>(pub &'a Route);
53impl<'a> core::fmt::Display for DebugRoute<'a> {
54	fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
55		for (idx, p) in self.0.paths.iter().enumerate() {
56			writeln!(f, "path {}:", idx)?;
57			for h in p.hops.iter() {
58				writeln!(
59					f,
60					" node_id: {}, short_channel_id: {}, fee_msat: {}, cltv_expiry_delta: {}",
61					log_pubkey!(h.pubkey),
62					h.short_channel_id,
63					h.fee_msat,
64					h.cltv_expiry_delta
65				)?;
66			}
67			writeln!(f, " blinded_tail: {:?}", p.blinded_tail)?;
68		}
69		Ok(())
70	}
71}
72macro_rules! log_route {
73	($obj: expr) => {
74		$crate::util::macro_logger::DebugRoute(&$obj)
75	};
76}
77
78pub(crate) struct DebugTx<'a>(pub &'a Transaction);
79impl<'a> core::fmt::Display for DebugTx<'a> {
80	fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
81		if self.0.input.len() >= 1 && self.0.input.iter().any(|i| !i.witness.is_empty()) {
82			let first_input = &self.0.input[0];
83			let witness_script_len = first_input.witness.last().unwrap_or(&[]).len();
84			if self.0.input.len() == 1
85				&& witness_script_len == 71
86				&& (first_input.sequence.0 >> 8 * 3) as u8 == 0x80
87			{
88				write!(f, "commitment tx ")?;
89			} else if self.0.input.len() == 1 && witness_script_len == 71 {
90				write!(f, "closing tx ")?;
91			} else if self.0.input.len() == 1
92				&& HTLCClaim::from_witness(&first_input.witness) == Some(HTLCClaim::OfferedTimeout)
93			{
94				write!(f, "HTLC-timeout tx ")?;
95			} else if self.0.input.len() == 1
96				&& HTLCClaim::from_witness(&first_input.witness)
97					== Some(HTLCClaim::AcceptedPreimage)
98			{
99				write!(f, "HTLC-success tx ")?;
100			} else {
101				let mut num_preimage = 0;
102				let mut num_timeout = 0;
103				let mut num_revoked = 0;
104				for inp in &self.0.input {
105					let htlc_claim = HTLCClaim::from_witness(&inp.witness);
106					match htlc_claim {
107						Some(HTLCClaim::AcceptedPreimage) | Some(HTLCClaim::OfferedPreimage) => {
108							num_preimage += 1
109						},
110						Some(HTLCClaim::AcceptedTimeout) | Some(HTLCClaim::OfferedTimeout) => {
111							num_timeout += 1
112						},
113						Some(HTLCClaim::Revocation) => num_revoked += 1,
114						None => continue,
115					}
116				}
117				if num_preimage > 0 || num_timeout > 0 || num_revoked > 0 {
118					write!(
119						f,
120						"HTLC claim tx ({} preimage, {} timeout, {} revoked) ",
121						num_preimage, num_timeout, num_revoked
122					)?;
123				}
124			}
125		} else {
126			debug_assert!(false, "We should never generate unknown transaction types");
127			write!(f, "unknown tx type ").unwrap();
128		}
129		write!(f, "with txid {}", self.0.compute_txid())?;
130		Ok(())
131	}
132}
133
134macro_rules! log_tx {
135	($obj: expr) => {
136		$crate::util::macro_logger::DebugTx(&$obj)
137	};
138}
139
140pub(crate) struct DebugSpendable<'a>(pub &'a SpendableOutputDescriptor);
141impl<'a> core::fmt::Display for DebugSpendable<'a> {
142	fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
143		match self.0 {
144			&SpendableOutputDescriptor::StaticOutput { ref outpoint, .. } => {
145				write!(f, "StaticOutput {}:{} marked for spending", outpoint.txid, outpoint.index)?;
146			},
147			&SpendableOutputDescriptor::DelayedPaymentOutput(ref descriptor) => {
148				write!(
149					f,
150					"DelayedPaymentOutput {}:{} marked for spending",
151					descriptor.outpoint.txid, descriptor.outpoint.index
152				)?;
153			},
154			&SpendableOutputDescriptor::StaticPaymentOutput(ref descriptor) => {
155				write!(
156					f,
157					"StaticPaymentOutput {}:{} marked for spending",
158					descriptor.outpoint.txid, descriptor.outpoint.index
159				)?;
160			},
161		}
162		Ok(())
163	}
164}
165
166macro_rules! log_spendable {
167	($obj: expr) => {
168		$crate::util::macro_logger::DebugSpendable(&$obj)
169	};
170}
171
172/// The maximum number of characters to display in a network message log entry.
173pub(crate) const LOG_MSG_MAX_LEN: usize = 512;
174
175/// Wraps a string slice for Display, truncating to [`LOG_MSG_MAX_LEN`] characters and
176/// delegating sanitization to [`crate::types::string::PrintableString`].
177/// Useful for logging counterparty-provided messages.
178pub(crate) struct DebugMsg<'a>(pub &'a str);
179impl<'a> core::fmt::Display for DebugMsg<'a> {
180	fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
181		let (msg, was_truncated) = match self.0.char_indices().nth(LOG_MSG_MAX_LEN) {
182			Some((idx, _)) => (&self.0[..idx], true),
183			None => (self.0, false),
184		};
185		core::fmt::Display::fmt(&crate::types::string::PrintableString(msg), f)?;
186		if was_truncated {
187			f.write_str("...")?;
188		}
189		Ok(())
190	}
191}
192
193macro_rules! log_msg {
194	($obj: expr) => {
195		$crate::util::macro_logger::DebugMsg(&$obj)
196	};
197}
198
199/// Create a new Record and log it. You probably don't want to use this macro directly,
200/// but it needs to be exported so `log_trace` etc can use it in external crates.
201#[doc(hidden)]
202#[macro_export]
203macro_rules! log_given_level {
204	($logger: expr, $lvl:expr, $($arg:tt)+) => (
205		$logger.log($crate::util::logger::Record::new($lvl, None, None, format_args!($($arg)+), module_path!(), file!(), line!(), None))
206	);
207}
208
209/// Log at the `ERROR` level.
210#[macro_export]
211macro_rules! log_error {
212	($logger: expr, $($arg:tt)*) => (
213		$crate::log_given_level!($logger, $crate::util::logger::Level::Error, $($arg)*);
214	)
215}
216
217/// Log at the `WARN` level.
218#[macro_export]
219macro_rules! log_warn {
220	($logger: expr, $($arg:tt)*) => (
221		$crate::log_given_level!($logger, $crate::util::logger::Level::Warn, $($arg)*);
222	)
223}
224
225/// Log at the `INFO` level.
226#[macro_export]
227macro_rules! log_info {
228	($logger: expr, $($arg:tt)*) => (
229		$crate::log_given_level!($logger, $crate::util::logger::Level::Info, $($arg)*);
230	)
231}
232
233/// Log at the `DEBUG` level.
234#[macro_export]
235macro_rules! log_debug {
236	($logger: expr, $($arg:tt)*) => (
237		$crate::log_given_level!($logger, $crate::util::logger::Level::Debug, $($arg)*);
238	)
239}
240
241/// Log at the `TRACE` level.
242#[macro_export]
243macro_rules! log_trace {
244	($logger: expr, $($arg:tt)*) => (
245		$crate::log_given_level!($logger, $crate::util::logger::Level::Trace, $($arg)*)
246	)
247}
248
249/// Log at the `GOSSIP` level.
250#[macro_export]
251macro_rules! log_gossip {
252	($logger: expr, $($arg:tt)*) => (
253		$crate::log_given_level!($logger, $crate::util::logger::Level::Gossip, $($arg)*);
254	)
255}
256
257#[cfg(test)]
258mod tests {
259	use super::*;
260	use alloc::string::ToString;
261
262	#[test]
263	fn debug_msg_short_string() {
264		let s = "hello world";
265		assert_eq!(DebugMsg(s).to_string(), "hello world");
266	}
267
268	#[test]
269	fn debug_msg_truncates_at_limit() {
270		let s: String = core::iter::repeat('a').take(LOG_MSG_MAX_LEN + 100).collect();
271		let result = DebugMsg(&s).to_string();
272		// Should be exactly LOG_MSG_MAX_LEN 'a's followed by "..."
273		assert_eq!(result.len(), LOG_MSG_MAX_LEN + 3);
274		assert!(result.ends_with("..."));
275	}
276
277	#[test]
278	fn debug_msg_no_truncation_at_exact_limit() {
279		let s: String = core::iter::repeat('a').take(LOG_MSG_MAX_LEN).collect();
280		let result = DebugMsg(&s).to_string();
281		assert_eq!(result.len(), LOG_MSG_MAX_LEN);
282		assert!(!result.ends_with("..."));
283	}
284
285	#[test]
286	fn debug_msg_replaces_control_characters() {
287		let s = "hello\x00world\nfoo";
288		let result = DebugMsg(s).to_string();
289		assert_eq!(result, "hello\u{FFFD}world\u{FFFD}foo");
290	}
291
292	#[test]
293	fn debug_msg_uses_printable_string_sanitization() {
294		let s = "safe\u{202E}cipsxe.exe";
295		assert_eq!(DebugMsg(s).to_string(), crate::types::string::PrintableString(s).to_string());
296	}
297
298	#[test]
299	fn debug_msg_multibyte_unicode() {
300		// Each emoji is multiple bytes but one character
301		let s: String = core::iter::repeat('\u{1F600}').take(LOG_MSG_MAX_LEN + 10).collect();
302		let result = DebugMsg(&s).to_string();
303		let char_count: usize = result.chars().count();
304		// LOG_MSG_MAX_LEN emoji chars + 3 chars for "..."
305		assert_eq!(char_count, LOG_MSG_MAX_LEN + 3);
306		assert!(result.ends_with("..."));
307	}
308
309	#[test]
310	fn debug_msg_empty_string() {
311		assert_eq!(DebugMsg("").to_string(), "");
312	}
313}