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