af9ceefcd03a5d6dad799d52ce0d806a77e8090c
[ldk-c-bindings] / lightning-c-bindings / src / lightning / util / logger.rs
1 // This file is Copyright its original authors, visible in version control
2 // history and in the source files from which this was generated.
3 //
4 // This file is licensed under the license available in the LICENSE or LICENSE.md
5 // file in the root of this repository or, if no such file exists, the same
6 // license as that which applies to the original source files from which this
7 // source was automatically generated.
8
9 //! Log traits live here, which are called throughout the library to provide useful information for
10 //! debugging purposes.
11 //!
12 //! There is currently 2 ways to filter log messages. First one, by using compilation features, e.g \"max_level_off\".
13 //! The second one, client-side by implementing check against Record Level field.
14 //! Each module may have its own Logger or share one.
15
16 use alloc::str::FromStr;
17 use alloc::string::String;
18 use core::ffi::c_void;
19 use core::convert::Infallible;
20 use bitcoin::hashes::Hash;
21 use crate::c_types::*;
22 #[cfg(feature="no-std")]
23 use alloc::{vec::Vec, boxed::Box};
24
25 /// An enum representing the available verbosity levels of the logger.
26 #[derive(Clone)]
27 #[must_use]
28 #[repr(C)]
29 pub enum Level {
30         /// Designates extremely verbose information, including gossip-induced messages
31         Gossip,
32         /// Designates very low priority, often extremely verbose, information
33         Trace,
34         /// Designates lower priority information
35         Debug,
36         /// Designates useful information
37         Info,
38         /// Designates hazardous situations
39         Warn,
40         /// Designates very serious errors
41         Error,
42 }
43 use lightning::util::logger::Level as LevelImport;
44 pub(crate) type nativeLevel = LevelImport;
45
46 impl Level {
47         #[allow(unused)]
48         pub(crate) fn to_native(&self) -> nativeLevel {
49                 match self {
50                         Level::Gossip => nativeLevel::Gossip,
51                         Level::Trace => nativeLevel::Trace,
52                         Level::Debug => nativeLevel::Debug,
53                         Level::Info => nativeLevel::Info,
54                         Level::Warn => nativeLevel::Warn,
55                         Level::Error => nativeLevel::Error,
56                 }
57         }
58         #[allow(unused)]
59         pub(crate) fn into_native(self) -> nativeLevel {
60                 match self {
61                         Level::Gossip => nativeLevel::Gossip,
62                         Level::Trace => nativeLevel::Trace,
63                         Level::Debug => nativeLevel::Debug,
64                         Level::Info => nativeLevel::Info,
65                         Level::Warn => nativeLevel::Warn,
66                         Level::Error => nativeLevel::Error,
67                 }
68         }
69         #[allow(unused)]
70         pub(crate) fn from_native(native: &LevelImport) -> Self {
71                 let native = unsafe { &*(native as *const _ as *const c_void as *const nativeLevel) };
72                 match native {
73                         nativeLevel::Gossip => Level::Gossip,
74                         nativeLevel::Trace => Level::Trace,
75                         nativeLevel::Debug => Level::Debug,
76                         nativeLevel::Info => Level::Info,
77                         nativeLevel::Warn => Level::Warn,
78                         nativeLevel::Error => Level::Error,
79                 }
80         }
81         #[allow(unused)]
82         pub(crate) fn native_into(native: nativeLevel) -> Self {
83                 match native {
84                         nativeLevel::Gossip => Level::Gossip,
85                         nativeLevel::Trace => Level::Trace,
86                         nativeLevel::Debug => Level::Debug,
87                         nativeLevel::Info => Level::Info,
88                         nativeLevel::Warn => Level::Warn,
89                         nativeLevel::Error => Level::Error,
90                 }
91         }
92 }
93 /// Creates a copy of the Level
94 #[no_mangle]
95 pub extern "C" fn Level_clone(orig: &Level) -> Level {
96         orig.clone()
97 }
98 #[allow(unused)]
99 /// Used only if an object of this type is returned as a trait impl by a method
100 pub(crate) extern "C" fn Level_clone_void(this_ptr: *const c_void) -> *mut c_void {
101         Box::into_raw(Box::new(unsafe { (*(this_ptr as *const Level)).clone() })) as *mut c_void
102 }
103 #[allow(unused)]
104 /// Used only if an object of this type is returned as a trait impl by a method
105 pub(crate) extern "C" fn Level_free_void(this_ptr: *mut c_void) {
106         let _ = unsafe { Box::from_raw(this_ptr as *mut Level) };
107 }
108 #[no_mangle]
109 /// Utility method to constructs a new Gossip-variant Level
110 pub extern "C" fn Level_gossip() -> Level {
111         Level::Gossip}
112 #[no_mangle]
113 /// Utility method to constructs a new Trace-variant Level
114 pub extern "C" fn Level_trace() -> Level {
115         Level::Trace}
116 #[no_mangle]
117 /// Utility method to constructs a new Debug-variant Level
118 pub extern "C" fn Level_debug() -> Level {
119         Level::Debug}
120 #[no_mangle]
121 /// Utility method to constructs a new Info-variant Level
122 pub extern "C" fn Level_info() -> Level {
123         Level::Info}
124 #[no_mangle]
125 /// Utility method to constructs a new Warn-variant Level
126 pub extern "C" fn Level_warn() -> Level {
127         Level::Warn}
128 #[no_mangle]
129 /// Utility method to constructs a new Error-variant Level
130 pub extern "C" fn Level_error() -> Level {
131         Level::Error}
132 /// Checks if two Levels contain equal inner contents.
133 /// This ignores pointers and is_owned flags and looks at the values in fields.
134 #[no_mangle]
135 pub extern "C" fn Level_eq(a: &Level, b: &Level) -> bool {
136         if &a.to_native() == &b.to_native() { true } else { false }
137 }
138 /// Get a string which allows debug introspection of a Level object
139 pub extern "C" fn Level_debug_str_void(o: *const c_void) -> Str {
140         alloc::format!("{:?}", unsafe { o as *const crate::lightning::util::logger::Level }).into()}
141 /// Generates a non-cryptographic 64-bit hash of the Level.
142 #[no_mangle]
143 pub extern "C" fn Level_hash(o: &Level) -> u64 {
144         // Note that we'd love to use alloc::collections::hash_map::DefaultHasher but it's not in core
145         #[allow(deprecated)]
146         let mut hasher = core::hash::SipHasher::new();
147         core::hash::Hash::hash(&o.to_native(), &mut hasher);
148         core::hash::Hasher::finish(&hasher)
149 }
150 #[no_mangle]
151 /// Get the string representation of a Level object
152 pub extern "C" fn Level_to_str(o: &crate::lightning::util::logger::Level) -> Str {
153         alloc::format!("{}", &o.to_native()).into()
154 }
155 /// Returns the most verbose logging level.
156 #[must_use]
157 #[no_mangle]
158 pub extern "C" fn Level_max() -> crate::lightning::util::logger::Level {
159         let mut ret = lightning::util::logger::Level::max();
160         crate::lightning::util::logger::Level::native_into(ret)
161 }
162
163
164 use lightning::util::logger::Record as nativeRecordImport;
165 pub(crate) type nativeRecord = nativeRecordImport;
166
167 /// A Record, unit of logging output with Metadata to enable filtering
168 /// Module_path, file, line to inform on log's source
169 #[must_use]
170 #[repr(C)]
171 pub struct Record {
172         /// A pointer to the opaque Rust object.
173
174         /// Nearly everywhere, inner must be non-null, however in places where
175         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
176         pub inner: *mut nativeRecord,
177         /// Indicates that this is the only struct which contains the same pointer.
178
179         /// Rust functions which take ownership of an object provided via an argument require
180         /// this to be true and invalidate the object pointed to by inner.
181         pub is_owned: bool,
182 }
183
184 impl Drop for Record {
185         fn drop(&mut self) {
186                 if self.is_owned && !<*mut nativeRecord>::is_null(self.inner) {
187                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
188                 }
189         }
190 }
191 /// Frees any resources used by the Record, if is_owned is set and inner is non-NULL.
192 #[no_mangle]
193 pub extern "C" fn Record_free(this_obj: Record) { }
194 #[allow(unused)]
195 /// Used only if an object of this type is returned as a trait impl by a method
196 pub(crate) extern "C" fn Record_free_void(this_ptr: *mut c_void) {
197         let _ = unsafe { Box::from_raw(this_ptr as *mut nativeRecord) };
198 }
199 #[allow(unused)]
200 impl Record {
201         pub(crate) fn get_native_ref(&self) -> &'static nativeRecord {
202                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
203         }
204         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeRecord {
205                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
206         }
207         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
208         pub(crate) fn take_inner(mut self) -> *mut nativeRecord {
209                 assert!(self.is_owned);
210                 let ret = ObjOps::untweak_ptr(self.inner);
211                 self.inner = core::ptr::null_mut();
212                 ret
213         }
214 }
215 /// The verbosity level of the message.
216 #[no_mangle]
217 pub extern "C" fn Record_get_level(this_ptr: &Record) -> crate::lightning::util::logger::Level {
218         let mut inner_val = &mut this_ptr.get_native_mut_ref().level;
219         crate::lightning::util::logger::Level::from_native(inner_val)
220 }
221 /// The verbosity level of the message.
222 #[no_mangle]
223 pub extern "C" fn Record_set_level(this_ptr: &mut Record, mut val: crate::lightning::util::logger::Level) {
224         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.level = val.into_native();
225 }
226 /// The node id of the peer pertaining to the logged record.
227 ///
228 /// Note that in some cases a [`Self::channel_id`] may be filled in but this may still be
229 /// `None`, depending on if the peer information is readily available in LDK when the log is
230 /// generated.
231 ///
232 /// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
233 #[no_mangle]
234 pub extern "C" fn Record_get_peer_id(this_ptr: &Record) -> crate::c_types::PublicKey {
235         let mut inner_val = &mut this_ptr.get_native_mut_ref().peer_id;
236         let mut local_inner_val = if inner_val.is_none() { crate::c_types::PublicKey::null() } else {  { crate::c_types::PublicKey::from_rust(&(inner_val.unwrap())) } };
237         local_inner_val
238 }
239 /// The node id of the peer pertaining to the logged record.
240 ///
241 /// Note that in some cases a [`Self::channel_id`] may be filled in but this may still be
242 /// `None`, depending on if the peer information is readily available in LDK when the log is
243 /// generated.
244 ///
245 /// Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None
246 #[no_mangle]
247 pub extern "C" fn Record_set_peer_id(this_ptr: &mut Record, mut val: crate::c_types::PublicKey) {
248         let mut local_val = if val.is_null() { None } else { Some( { val.into_rust() }) };
249         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.peer_id = local_val;
250 }
251 /// The channel id of the channel pertaining to the logged record. May be a temporary id before
252 /// the channel has been funded.
253 ///
254 /// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
255 #[no_mangle]
256 pub extern "C" fn Record_get_channel_id(this_ptr: &Record) -> crate::lightning::ln::types::ChannelId {
257         let mut inner_val = &mut this_ptr.get_native_mut_ref().channel_id;
258         let mut local_inner_val = crate::lightning::ln::types::ChannelId { inner: unsafe { (if inner_val.is_none() { core::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (inner_val.as_ref().unwrap()) }) } as *const lightning::ln::types::ChannelId<>) as *mut _ }, is_owned: false };
259         local_inner_val
260 }
261 /// The channel id of the channel pertaining to the logged record. May be a temporary id before
262 /// the channel has been funded.
263 ///
264 /// Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None
265 #[no_mangle]
266 pub extern "C" fn Record_set_channel_id(this_ptr: &mut Record, mut val: crate::lightning::ln::types::ChannelId) {
267         let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) };
268         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.channel_id = local_val;
269 }
270 /// The message body.
271 #[no_mangle]
272 pub extern "C" fn Record_get_args(this_ptr: &Record) -> crate::c_types::Str {
273         let mut inner_val = &mut this_ptr.get_native_mut_ref().args;
274         inner_val.as_str().into()
275 }
276 /// The message body.
277 #[no_mangle]
278 pub extern "C" fn Record_set_args(this_ptr: &mut Record, mut val: crate::c_types::Str) {
279         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.args = val.into_string();
280 }
281 /// The module path of the message.
282 #[no_mangle]
283 pub extern "C" fn Record_get_module_path(this_ptr: &Record) -> crate::c_types::Str {
284         let mut inner_val = &mut this_ptr.get_native_mut_ref().module_path;
285         inner_val.into()
286 }
287 /// The module path of the message.
288 #[no_mangle]
289 pub extern "C" fn Record_set_module_path(this_ptr: &mut Record, mut val: crate::c_types::Str) {
290         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.module_path = val.into_str();
291 }
292 /// The source file containing the message.
293 #[no_mangle]
294 pub extern "C" fn Record_get_file(this_ptr: &Record) -> crate::c_types::Str {
295         let mut inner_val = &mut this_ptr.get_native_mut_ref().file;
296         inner_val.into()
297 }
298 /// The source file containing the message.
299 #[no_mangle]
300 pub extern "C" fn Record_set_file(this_ptr: &mut Record, mut val: crate::c_types::Str) {
301         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.file = val.into_str();
302 }
303 /// The line containing the message.
304 #[no_mangle]
305 pub extern "C" fn Record_get_line(this_ptr: &Record) -> u32 {
306         let mut inner_val = &mut this_ptr.get_native_mut_ref().line;
307         *inner_val
308 }
309 /// The line containing the message.
310 #[no_mangle]
311 pub extern "C" fn Record_set_line(this_ptr: &mut Record, mut val: u32) {
312         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.line = val;
313 }
314 /// Constructs a new Record given each field
315 ///
316 /// Note that peer_id_arg (or a relevant inner pointer) may be NULL or all-0s to represent None
317 /// Note that channel_id_arg (or a relevant inner pointer) may be NULL or all-0s to represent None
318 #[must_use]
319 #[no_mangle]
320 pub extern "C" fn Record_new(mut level_arg: crate::lightning::util::logger::Level, mut peer_id_arg: crate::c_types::PublicKey, mut channel_id_arg: crate::lightning::ln::types::ChannelId, mut args_arg: crate::c_types::Str, mut module_path_arg: crate::c_types::Str, mut file_arg: crate::c_types::Str, mut line_arg: u32) -> Record {
321         let mut local_peer_id_arg = if peer_id_arg.is_null() { None } else { Some( { peer_id_arg.into_rust() }) };
322         let mut local_channel_id_arg = if channel_id_arg.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(channel_id_arg.take_inner()) } }) };
323         Record { inner: ObjOps::heap_alloc(nativeRecord {
324                 level: level_arg.into_native(),
325                 peer_id: local_peer_id_arg,
326                 channel_id: local_channel_id_arg,
327                 args: args_arg.into_string(),
328                 module_path: module_path_arg.into_str(),
329                 file: file_arg.into_str(),
330                 line: line_arg,
331         }), is_owned: true }
332 }
333 impl Clone for Record {
334         fn clone(&self) -> Self {
335                 Self {
336                         inner: if <*mut nativeRecord>::is_null(self.inner) { core::ptr::null_mut() } else {
337                                 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
338                         is_owned: true,
339                 }
340         }
341 }
342 #[allow(unused)]
343 /// Used only if an object of this type is returned as a trait impl by a method
344 pub(crate) extern "C" fn Record_clone_void(this_ptr: *const c_void) -> *mut c_void {
345         Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativeRecord)).clone() })) as *mut c_void
346 }
347 #[no_mangle]
348 /// Creates a copy of the Record
349 pub extern "C" fn Record_clone(orig: &Record) -> Record {
350         orig.clone()
351 }
352 /// Get a string which allows debug introspection of a Record object
353 pub extern "C" fn Record_debug_str_void(o: *const c_void) -> Str {
354         alloc::format!("{:?}", unsafe { o as *const crate::lightning::util::logger::Record }).into()}
355 /// A trait encapsulating the operations required of a logger.
356 #[repr(C)]
357 pub struct Logger {
358         /// An opaque pointer which is passed to your function implementations as an argument.
359         /// This has no meaning in the LDK, and can be NULL or any other value.
360         pub this_arg: *mut c_void,
361         /// Logs the [`Record`].
362         pub log: extern "C" fn (this_arg: *const c_void, record: crate::lightning::util::logger::Record),
363         /// Frees any resources associated with this object given its this_arg pointer.
364         /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
365         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
366 }
367 unsafe impl Send for Logger {}
368 unsafe impl Sync for Logger {}
369 #[allow(unused)]
370 pub(crate) fn Logger_clone_fields(orig: &Logger) -> Logger {
371         Logger {
372                 this_arg: orig.this_arg,
373                 log: Clone::clone(&orig.log),
374                 free: Clone::clone(&orig.free),
375         }
376 }
377
378 use lightning::util::logger::Logger as rustLogger;
379 impl rustLogger for Logger {
380         fn log(&self, mut record: lightning::util::logger::Record) {
381                 (self.log)(self.this_arg, crate::lightning::util::logger::Record { inner: ObjOps::heap_alloc(record), is_owned: true })
382         }
383 }
384
385 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
386 // directly as a Deref trait in higher-level structs:
387 impl core::ops::Deref for Logger {
388         type Target = Self;
389         fn deref(&self) -> &Self {
390                 self
391         }
392 }
393 impl core::ops::DerefMut for Logger {
394         fn deref_mut(&mut self) -> &mut Self {
395                 self
396         }
397 }
398 /// Calls the free function if one is set
399 #[no_mangle]
400 pub extern "C" fn Logger_free(this_ptr: Logger) { }
401 impl Drop for Logger {
402         fn drop(&mut self) {
403                 if let Some(f) = self.free {
404                         f(self.this_arg);
405                 }
406         }
407 }