Add log_iter utility macro
[rust-lightning] / lightning / src / 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
10 use crate::chain::transaction::OutPoint;
11 use crate::sign::SpendableOutputDescriptor;
12
13 use bitcoin::hash_types::Txid;
14 use bitcoin::blockdata::transaction::Transaction;
15
16 use crate::routing::router::Route;
17 use crate::ln::chan_utils::HTLCClaim;
18 use crate::util::logger::DebugBytes;
19
20 macro_rules! log_iter {
21         ($obj: expr) => {
22                 $crate::util::logger::DebugIter(core::cell::RefCell::new($obj))
23         }
24 }
25
26 /// Logs a pubkey in hex format.
27 #[macro_export]
28 macro_rules! log_pubkey {
29         ($obj: expr) => {
30                 $crate::util::logger::DebugPubKey(&$obj)
31         }
32 }
33
34 /// Logs a byte slice in hex format.
35 #[macro_export]
36 macro_rules! log_bytes {
37         ($obj: expr) => {
38                 $crate::util::logger::DebugBytes(&$obj)
39         }
40 }
41
42 pub(crate) struct DebugFundingChannelId<'a>(pub &'a Txid, pub u16);
43 impl<'a> core::fmt::Display for DebugFundingChannelId<'a> {
44         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
45                 for i in (OutPoint { txid: self.0.clone(), index: self.1 }).to_channel_id().iter() {
46                         write!(f, "{:02x}", i)?;
47                 }
48                 Ok(())
49         }
50 }
51 macro_rules! log_funding_channel_id {
52         ($funding_txid: expr, $funding_txo: expr) => {
53                 $crate::util::macro_logger::DebugFundingChannelId(&$funding_txid, $funding_txo)
54         }
55 }
56
57 pub(crate) struct DebugFundingInfo<'a, T: 'a>(pub &'a (OutPoint, T));
58 impl<'a, T> core::fmt::Display for DebugFundingInfo<'a, T> {
59         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
60                 DebugBytes(&(self.0).0.to_channel_id()[..]).fmt(f)
61         }
62 }
63 macro_rules! log_funding_info {
64         ($key_storage: expr) => {
65                 $crate::util::macro_logger::DebugFundingInfo(&$key_storage.get_funding_txo())
66         }
67 }
68
69 pub(crate) struct DebugRoute<'a>(pub &'a Route);
70 impl<'a> core::fmt::Display for DebugRoute<'a> {
71         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
72                 for (idx, p) in self.0.paths.iter().enumerate() {
73                         writeln!(f, "path {}:", idx)?;
74                         for h in p.hops.iter() {
75                                 writeln!(f, " node_id: {}, short_channel_id: {}, fee_msat: {}, cltv_expiry_delta: {}", log_pubkey!(h.pubkey), h.short_channel_id, h.fee_msat, h.cltv_expiry_delta)?;
76                         }
77                         writeln!(f, " blinded_tail: {:?}", p.blinded_tail)?;
78                 }
79                 Ok(())
80         }
81 }
82 macro_rules! log_route {
83         ($obj: expr) => {
84                 $crate::util::macro_logger::DebugRoute(&$obj)
85         }
86 }
87
88 pub(crate) struct DebugTx<'a>(pub &'a Transaction);
89 impl<'a> core::fmt::Display for DebugTx<'a> {
90         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
91                 if self.0.input.len() >= 1 && self.0.input.iter().any(|i| !i.witness.is_empty()) {
92                         let first_input = &self.0.input[0];
93                         let witness_script_len = first_input.witness.last().unwrap_or(&[]).len();
94                         if self.0.input.len() == 1 && witness_script_len == 71 &&
95                                         (first_input.sequence.0 >> 8*3) as u8 == 0x80 {
96                                 write!(f, "commitment tx ")?;
97                         } else if self.0.input.len() == 1 && witness_script_len == 71 {
98                                 write!(f, "closing tx ")?;
99                         } else if self.0.input.len() == 1 && HTLCClaim::from_witness(&first_input.witness) == Some(HTLCClaim::OfferedTimeout) {
100                                 write!(f, "HTLC-timeout tx ")?;
101                         } else if self.0.input.len() == 1 && HTLCClaim::from_witness(&first_input.witness) == Some(HTLCClaim::AcceptedPreimage) {
102                                 write!(f, "HTLC-success tx ")?;
103                         } else {
104                                 let mut num_preimage = 0;
105                                 let mut num_timeout = 0;
106                                 let mut num_revoked = 0;
107                                 for inp in &self.0.input {
108                                         let htlc_claim = HTLCClaim::from_witness(&inp.witness);
109                                         match htlc_claim {
110                                                 Some(HTLCClaim::AcceptedPreimage)|Some(HTLCClaim::OfferedPreimage) => num_preimage += 1,
111                                                 Some(HTLCClaim::AcceptedTimeout)|Some(HTLCClaim::OfferedTimeout) => num_timeout += 1,
112                                                 Some(HTLCClaim::Revocation) => num_revoked += 1,
113                                                 None => continue,
114                                         }
115                                 }
116                                 if num_preimage > 0 || num_timeout > 0 || num_revoked > 0 {
117                                         write!(f, "HTLC claim tx ({} preimage, {} timeout, {} revoked) ",
118                                                 num_preimage, num_timeout, num_revoked)?;
119                                 }
120                         }
121                 } else {
122                         debug_assert!(false, "We should never generate unknown transaction types");
123                         write!(f, "unknown tx type ").unwrap();
124                 }
125                 write!(f, "with txid {}", self.0.txid())?;
126                 Ok(())
127         }
128 }
129
130 macro_rules! log_tx {
131         ($obj: expr) => {
132                 $crate::util::macro_logger::DebugTx(&$obj)
133         }
134 }
135
136 pub(crate) struct DebugSpendable<'a>(pub &'a SpendableOutputDescriptor);
137 impl<'a> core::fmt::Display for DebugSpendable<'a> {
138         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
139                 match self.0 {
140                         &SpendableOutputDescriptor::StaticOutput { ref outpoint, .. } => {
141                                 write!(f, "StaticOutput {}:{} marked for spending", outpoint.txid, outpoint.index)?;
142                         }
143                         &SpendableOutputDescriptor::DelayedPaymentOutput(ref descriptor) => {
144                                 write!(f, "DelayedPaymentOutput {}:{} marked for spending", descriptor.outpoint.txid, descriptor.outpoint.index)?;
145                         }
146                         &SpendableOutputDescriptor::StaticPaymentOutput(ref descriptor) => {
147                                 write!(f, "StaticPaymentOutput {}:{} marked for spending", descriptor.outpoint.txid, descriptor.outpoint.index)?;
148                         }
149                 }
150                 Ok(())
151         }
152 }
153
154 macro_rules! log_spendable {
155         ($obj: expr) => {
156                 $crate::util::macro_logger::DebugSpendable(&$obj)
157         }
158 }
159
160 /// Create a new Record and log it. You probably don't want to use this macro directly,
161 /// but it needs to be exported so `log_trace` etc can use it in external crates.
162 #[doc(hidden)]
163 #[macro_export]
164 macro_rules! log_internal {
165         ($logger: expr, $lvl:expr, $($arg:tt)+) => (
166                 $logger.log(&$crate::util::logger::Record::new($lvl, format_args!($($arg)+), module_path!(), file!(), line!()))
167         );
168 }
169
170 /// Logs an entry at the given level.
171 #[doc(hidden)]
172 #[macro_export]
173 macro_rules! log_given_level {
174         ($logger: expr, $lvl:expr, $($arg:tt)+) => (
175                 match $lvl {
176                         #[cfg(not(any(feature = "max_level_off")))]
177                         $crate::util::logger::Level::Error => $crate::log_internal!($logger, $lvl, $($arg)*),
178                         #[cfg(not(any(feature = "max_level_off", feature = "max_level_error")))]
179                         $crate::util::logger::Level::Warn => $crate::log_internal!($logger, $lvl, $($arg)*),
180                         #[cfg(not(any(feature = "max_level_off", feature = "max_level_error", feature = "max_level_warn")))]
181                         $crate::util::logger::Level::Info => $crate::log_internal!($logger, $lvl, $($arg)*),
182                         #[cfg(not(any(feature = "max_level_off", feature = "max_level_error", feature = "max_level_warn", feature = "max_level_info")))]
183                         $crate::util::logger::Level::Debug => $crate::log_internal!($logger, $lvl, $($arg)*),
184                         #[cfg(not(any(feature = "max_level_off", feature = "max_level_error", feature = "max_level_warn", feature = "max_level_info", feature = "max_level_debug")))]
185                         $crate::util::logger::Level::Trace => $crate::log_internal!($logger, $lvl, $($arg)*),
186                         #[cfg(not(any(feature = "max_level_off", feature = "max_level_error", feature = "max_level_warn", feature = "max_level_info", feature = "max_level_debug", feature = "max_level_trace")))]
187                         $crate::util::logger::Level::Gossip => $crate::log_internal!($logger, $lvl, $($arg)*),
188
189                         #[cfg(any(feature = "max_level_off", feature = "max_level_error", feature = "max_level_warn", feature = "max_level_info", feature = "max_level_debug", feature = "max_level_trace"))]
190                         _ => {
191                                 // The level is disabled at compile-time
192                         },
193                 }
194         );
195 }
196
197 /// Log at the `ERROR` level.
198 #[macro_export]
199 macro_rules! log_error {
200         ($logger: expr, $($arg:tt)*) => (
201                 $crate::log_given_level!($logger, $crate::util::logger::Level::Error, $($arg)*);
202         )
203 }
204
205 /// Log at the `WARN` level.
206 #[macro_export]
207 macro_rules! log_warn {
208         ($logger: expr, $($arg:tt)*) => (
209                 $crate::log_given_level!($logger, $crate::util::logger::Level::Warn, $($arg)*);
210         )
211 }
212
213 /// Log at the `INFO` level.
214 #[macro_export]
215 macro_rules! log_info {
216         ($logger: expr, $($arg:tt)*) => (
217                 $crate::log_given_level!($logger, $crate::util::logger::Level::Info, $($arg)*);
218         )
219 }
220
221 /// Log at the `DEBUG` level.
222 #[macro_export]
223 macro_rules! log_debug {
224         ($logger: expr, $($arg:tt)*) => (
225                 $crate::log_given_level!($logger, $crate::util::logger::Level::Debug, $($arg)*);
226         )
227 }
228
229 /// Log at the `TRACE` level.
230 #[macro_export]
231 macro_rules! log_trace {
232         ($logger: expr, $($arg:tt)*) => (
233                 $crate::log_given_level!($logger, $crate::util::logger::Level::Trace, $($arg)*)
234         )
235 }
236
237 /// Log at the `GOSSIP` level.
238 #[macro_export]
239 macro_rules! log_gossip {
240         ($logger: expr, $($arg:tt)*) => (
241                 $crate::log_given_level!($logger, $crate::util::logger::Level::Gossip, $($arg)*);
242         )
243 }