Merge pull request #38 from TheBlueMatt/main
authorMatt Corallo <649246+TheBlueMatt@users.noreply.github.com>
Sun, 8 Aug 2021 18:16:10 +0000 (18:16 +0000)
committerGitHub <noreply@github.com>
Sun, 8 Aug 2021 18:16:10 +0000 (18:16 +0000)
Provide full (new) struct to trait clone functions

29 files changed:
c-bindings-gen/src/blocks.rs
c-bindings-gen/src/main.rs
c-bindings-gen/src/types.rs
genbindings.sh
ldk-net/ldk_net.c
ldk-net/ldk_net.h
lightning-c-bindings/Cargo.toml
lightning-c-bindings/cbindgen.toml
lightning-c-bindings/demo.cpp
lightning-c-bindings/include/lightning.h
lightning-c-bindings/include/lightningpp.hpp
lightning-c-bindings/src/c_types/derived.rs
lightning-c-bindings/src/c_types/mod.rs
lightning-c-bindings/src/lightning/chain/chaininterface.rs
lightning-c-bindings/src/lightning/chain/chainmonitor.rs
lightning-c-bindings/src/lightning/chain/channelmonitor.rs
lightning-c-bindings/src/lightning/chain/keysinterface.rs
lightning-c-bindings/src/lightning/chain/mod.rs
lightning-c-bindings/src/lightning/ln/chan_utils.rs
lightning-c-bindings/src/lightning/ln/channelmanager.rs
lightning-c-bindings/src/lightning/ln/msgs.rs
lightning-c-bindings/src/lightning/ln/peer_handler.rs
lightning-c-bindings/src/lightning/routing/network_graph.rs
lightning-c-bindings/src/lightning/routing/router.rs
lightning-c-bindings/src/lightning/util/errors.rs
lightning-c-bindings/src/lightning/util/events.rs
lightning-c-bindings/src/lightning/util/logger.rs
lightning-c-bindings/src/lightning_background_processor.rs
lightning-c-bindings/src/lightning_invoice/mod.rs

index 82b10ad831bd4ca2ef21ec3c1d9804d5dbe6e26c..9c404411a2719d4b979e8b920d1f0ef516e7b3c8 100644 (file)
@@ -20,7 +20,7 @@ use crate::types::*;
 /// Writes out a C++ wrapper class for the given type, which contains various utilities to access
 /// the underlying C-mapped type safely avoiding some common memory management issues by handling
 /// resource-freeing and prevending accidental raw copies.
-pub fn write_cpp_wrapper(cpp_header_file: &mut File, ty: &str, has_destructor: bool) {
+pub fn write_cpp_wrapper(cpp_header_file: &mut File, ty: &str, has_destructor: bool, trait_methods: Option<Vec<(String, String)>>) {
        writeln!(cpp_header_file, "class {} {{", ty).unwrap();
        writeln!(cpp_header_file, "private:").unwrap();
        writeln!(cpp_header_file, "\tLDK{} self;", ty).unwrap();
@@ -39,6 +39,14 @@ pub fn write_cpp_wrapper(cpp_header_file: &mut File, ty: &str, has_destructor: b
        writeln!(cpp_header_file, "\tLDK{}* operator ->() {{ return &self; }}", ty).unwrap();
        writeln!(cpp_header_file, "\tconst LDK{}* operator &() const {{ return &self; }}", ty).unwrap();
        writeln!(cpp_header_file, "\tconst LDK{}* operator ->() const {{ return &self; }}", ty).unwrap();
+       if let Some(methods) = trait_methods {
+               for (meth_name, meth_docs) in methods {
+                       cpp_header_file.write_all(meth_docs.as_bytes()).unwrap();
+                       // Note that we have zero logic to print C/C__ code for a given function. Instead, we
+                       // simply use sed to replace the following in genbindings.sh
+                       writeln!(cpp_header_file, "XXX {} {}", ty, meth_name).unwrap();
+               }
+       }
        writeln!(cpp_header_file, "}};").unwrap();
 }
 
@@ -369,8 +377,34 @@ pub fn write_option_block<W: std::io::Write>(w: &mut W, mangled_container: &str,
        }
 }
 
+/// Prints the docs from a given attribute list unless its tagged no export
+pub fn writeln_fn_docs<'a, W: std::io::Write, I>(w: &mut W, attrs: &[syn::Attribute], prefix: &str, types: &mut TypeResolver, generics: Option<&GenericTypes>, args: I, ret: &syn::ReturnType) where I: Iterator<Item = &'a syn::FnArg> {
+       writeln_docs_impl(w, attrs, prefix, Some((types, generics,
+               args.filter_map(|arg| if let syn::FnArg::Typed(ty) = arg {
+                               if let syn::Pat::Ident(id) = &*ty.pat {
+                                       Some((id.ident.to_string(), &*ty.ty))
+                               } else { unimplemented!() }
+                       } else { None }),
+               if let syn::ReturnType::Type(_, ty) = ret { Some(&**ty) } else { None },
+               None
+       )));
+}
+
 /// Prints the docs from a given attribute list unless its tagged no export
 pub fn writeln_docs<W: std::io::Write>(w: &mut W, attrs: &[syn::Attribute], prefix: &str) {
+       writeln_docs_impl(w, attrs, prefix, None::<(_, _, std::vec::Drain<'_, (String, &syn::Type)>, _, _)>);
+}
+
+pub fn writeln_arg_docs<'a, W: std::io::Write, I>(w: &mut W, attrs: &[syn::Attribute], prefix: &str, types: &mut TypeResolver, generics: Option<&GenericTypes>, args: I, ret: Option<&syn::Type>) where I: Iterator<Item = (String, &'a syn::Type)> {
+       writeln_docs_impl(w, attrs, prefix, Some((types, generics, args, ret, None)))
+}
+
+pub fn writeln_field_docs<W: std::io::Write>(w: &mut W, attrs: &[syn::Attribute], prefix: &str, types: &mut TypeResolver, generics: Option<&GenericTypes>, field: &syn::Type) {
+       writeln_docs_impl(w, attrs, prefix, Some((types, generics, vec![].drain(..), None, Some(field))))
+}
+
+/// Prints the docs from a given attribute list unless its tagged no export
+fn writeln_docs_impl<'a, W: std::io::Write, I>(w: &mut W, attrs: &[syn::Attribute], prefix: &str, method_args_ret: Option<(&mut TypeResolver, Option<&GenericTypes>, I, Option<&syn::Type>, Option<&syn::Type>)>) where I: Iterator<Item = (String, &'a syn::Type)> {
        for attr in attrs.iter() {
                let tokens_clone = attr.tokens.clone();
                let mut token_iter = tokens_clone.into_iter();
@@ -406,6 +440,51 @@ pub fn writeln_docs<W: std::io::Write>(w: &mut W, attrs: &[syn::Attribute], pref
                        },
                }
        }
+       if let Some((types, generics, inp, outp, field)) = method_args_ret {
+               let mut nullable_found = false;
+               for (name, inp) in inp {
+                       if types.skip_arg(inp, generics) { continue; }
+                       if if let syn::Type::Reference(syn::TypeReference { elem, .. }) = inp {
+                               if let syn::Type::Path(syn::TypePath { ref path, .. }) = &**elem {
+                                       types.is_path_transparent_container(path, generics, true)
+                               } else { false }
+                       } else if let syn::Type::Path(syn::TypePath { ref path, .. }) = inp {
+                               types.is_path_transparent_container(path, generics, true)
+                       } else { false } {
+                               // Note downstream clients match this text exactly so any changes may require
+                               // changes in the Java and Swift bindings, at least.
+                               if !nullable_found { writeln!(w, "{}///", prefix).unwrap(); }
+                               nullable_found = true;
+                               writeln!(w, "{}/// Note that {} (or a relevant inner pointer) may be NULL or all-0s to represent None", prefix, name).unwrap();
+                       }
+               }
+               if if let Some(syn::Type::Reference(syn::TypeReference { elem, .. })) = outp {
+                       if let syn::Type::Path(syn::TypePath { ref path, .. }) = &**elem {
+                               types.is_path_transparent_container(path, generics, true)
+                       } else { false }
+               } else if let Some(syn::Type::Path(syn::TypePath { ref path, .. })) = outp {
+                       types.is_path_transparent_container(path, generics, true)
+               } else { false } {
+                       // Note downstream clients match this text exactly so any changes may require
+                       // changes in the Java and Swift bindings, at least.
+                       if !nullable_found { writeln!(w, "{}///", prefix).unwrap(); }
+                       nullable_found = true;
+                       writeln!(w, "{}/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None", prefix).unwrap();
+               }
+               if if let Some(syn::Type::Reference(syn::TypeReference { elem, .. })) = field {
+                       if let syn::Type::Path(syn::TypePath { ref path, .. }) = &**elem {
+                               types.is_path_transparent_container(path, generics, true)
+                       } else { false }
+               } else if let Some(syn::Type::Path(syn::TypePath { ref path, .. })) = field {
+                       types.is_path_transparent_container(path, generics, true)
+               } else { false } {
+                       // Note downstream clients match this text exactly so any changes may require
+                       // changes in the Java and Swift bindings, at least.
+                       if !nullable_found { writeln!(w, "{}///", prefix).unwrap(); }
+                       writeln!(w, "{}/// Note that this (or a relevant inner pointer) may be NULL or all-0s to represent None", prefix).unwrap();
+               }
+       }
+
 }
 
 /// Print the parameters in a method declaration, starting after the open parenthesis, through and
index 9693e3d560a04575cf51863ec180ce1d37956434..2f94e432e4f351c36e8f975cb531d1d57258f7ba 100644 (file)
@@ -237,7 +237,9 @@ fn writeln_trait<'a, 'b, W: std::io::Write>(w: &mut W, t: &'a syn::ItemTrait, ty
        writeln!(w, "\t/// An opaque pointer which is passed to your function implementations as an argument.").unwrap();
        writeln!(w, "\t/// This has no meaning in the LDK, and can be NULL or any other value.").unwrap();
        writeln!(w, "\tpub this_arg: *mut c_void,").unwrap();
-       let mut generated_fields = Vec::new(); // Every field's (name, is_clonable) except this_arg, used in Clone generation
+       // We store every field's (name, Option<clone_fn>, docs) except this_arg, used in Clone generation
+       // docs is only set if its a function which should be callable on the object itself in C++
+       let mut generated_fields = Vec::new();
        for item in t.items.iter() {
                match item {
                        &syn::TraitItem::Method(ref m) => {
@@ -256,7 +258,7 @@ fn writeln_trait<'a, 'b, W: std::io::Write>(w: &mut W, t: &'a syn::ItemTrait, ty
                                let mut meth_gen_types = gen_types.push_ctx();
                                assert!(meth_gen_types.learn_generics(&m.sig.generics, types));
 
-                               writeln_docs(w, &m.attrs, "\t");
+                               writeln_fn_docs(w, &m.attrs, "\t", types, Some(&meth_gen_types), m.sig.inputs.iter(), &m.sig.output);
 
                                if let syn::ReturnType::Type(_, rtype) = &m.sig.output {
                                        if let syn::Type::Reference(r) = &**rtype {
@@ -271,14 +273,14 @@ fn writeln_trait<'a, 'b, W: std::io::Write>(w: &mut W, t: &'a syn::ItemTrait, ty
                                                // happen) as well as provide an Option<>al function pointer which is
                                                // called when the trait method is called which allows updating on the fly.
                                                write!(w, "\tpub {}: ", m.sig.ident).unwrap();
-                                               generated_fields.push((format!("{}", m.sig.ident), true));
+                                               generated_fields.push((format!("{}", m.sig.ident), None, None));
                                                types.write_c_type(w, &*r.elem, Some(&meth_gen_types), false);
                                                writeln!(w, ",").unwrap();
                                                writeln!(w, "\t/// Fill in the {} field as a reference to it will be given to Rust after this returns", m.sig.ident).unwrap();
                                                writeln!(w, "\t/// Note that this takes a pointer to this object, not the this_ptr like other methods do").unwrap();
                                                writeln!(w, "\t/// This function pointer may be NULL if {} is filled in when this object is created and never needs updating.", m.sig.ident).unwrap();
                                                writeln!(w, "\tpub set_{}: Option<extern \"C\" fn(&{})>,", m.sig.ident, trait_name).unwrap();
-                                               generated_fields.push((format!("set_{}", m.sig.ident), true));
+                                               generated_fields.push((format!("set_{}", m.sig.ident), None, None));
                                                // Note that cbindgen will now generate
                                                // typedef struct Thing {..., set_thing: (const struct Thing*), ...} Thing;
                                                // which does not compile since Thing is not defined before it is used.
@@ -290,8 +292,12 @@ fn writeln_trait<'a, 'b, W: std::io::Write>(w: &mut W, t: &'a syn::ItemTrait, ty
                                        writeln!(w, "\t#[must_use]").unwrap();
                                }
 
+                               let mut cpp_docs = Vec::new();
+                               writeln_fn_docs(&mut cpp_docs, &m.attrs, "\t * ", types, Some(&meth_gen_types), m.sig.inputs.iter(), &m.sig.output);
+                               let docs_string = "\t/**\n".to_owned() + &String::from_utf8(cpp_docs).unwrap().replace("///", "") + "\t */\n";
+
                                write!(w, "\tpub {}: extern \"C\" fn (", m.sig.ident).unwrap();
-                               generated_fields.push((format!("{}", m.sig.ident), true));
+                               generated_fields.push((format!("{}", m.sig.ident), None, Some(docs_string)));
                                write_method_params(w, &m.sig, "c_void", types, Some(&meth_gen_types), true, false);
                                writeln!(w, ",").unwrap();
                        },
@@ -300,55 +306,53 @@ fn writeln_trait<'a, 'b, W: std::io::Write>(w: &mut W, t: &'a syn::ItemTrait, ty
                }
        }
        // Add functions which may be required for supertrait implementations.
-       let mut requires_clone = false;
-       walk_supertraits!(t, Some(&types), (
-               ("Clone", _) => requires_clone = true,
-               (_, _) => {}
-       ) );
        walk_supertraits!(t, Some(&types), (
                ("Clone", _) => {
-                       writeln!(w, "\t/// Creates a copy of the object pointed to by this_arg, for a copy of this {}.", trait_name).unwrap();
-                       writeln!(w, "\t/// Note that the ultimate copy of the {} will have all function pointers the same as the original.", trait_name).unwrap();
-                       writeln!(w, "\t/// May be NULL if no action needs to be taken, the this_arg pointer will be copied into the new {}.", trait_name).unwrap();
-                       writeln!(w, "\tpub clone: Option<extern \"C\" fn (this_arg: *const c_void) -> *mut c_void>,").unwrap();
-                       generated_fields.push(("clone".to_owned(), true));
+                       writeln!(w, "\t/// Called, if set, after this {} has been cloned into a duplicate object.", trait_name).unwrap();
+                       writeln!(w, "\t/// The new {} is provided, and should be mutated as needed to perform a", trait_name).unwrap();
+                       writeln!(w, "\t/// deep copy of the object pointed to by this_arg or avoid any double-freeing.").unwrap();
+                       writeln!(w, "\tpub cloned: Option<extern \"C\" fn (new_{}: &mut {})>,", trait_name, trait_name).unwrap();
+                       generated_fields.push(("cloned".to_owned(), None, None));
                },
                ("std::cmp::Eq", _)|("core::cmp::Eq", _) => {
-                       writeln!(w, "\t/// Checks if two objects are equal given this object's this_arg pointer and another object.").unwrap();
+                       let eq_docs = "Checks if two objects are equal given this object's this_arg pointer and another object.";
+                       writeln!(w, "\t/// {}", eq_docs).unwrap();
                        writeln!(w, "\tpub eq: extern \"C\" fn (this_arg: *const c_void, other_arg: &{}) -> bool,", trait_name).unwrap();
-                       generated_fields.push(("eq".to_owned(), true));
+                       generated_fields.push(("eq".to_owned(), None, Some(format!("\t/** {} */\n", eq_docs))));
                },
                ("std::hash::Hash", _)|("core::hash::Hash", _) => {
-                       writeln!(w, "\t/// Calculate a succinct non-cryptographic hash for an object given its this_arg pointer.").unwrap();
-                       writeln!(w, "\t/// This is used, for example, for inclusion of this object in a hash map.").unwrap();
+                       let hash_docs_a = "Calculate a succinct non-cryptographic hash for an object given its this_arg pointer.";
+                       let hash_docs_b = "This is used, for example, for inclusion of this object in a hash map.";
+                       writeln!(w, "\t/// {}", hash_docs_a).unwrap();
+                       writeln!(w, "\t/// {}", hash_docs_b).unwrap();
                        writeln!(w, "\tpub hash: extern \"C\" fn (this_arg: *const c_void) -> u64,").unwrap();
-                       generated_fields.push(("hash".to_owned(), true));
+                       generated_fields.push(("hash".to_owned(), None,
+                               Some(format!("\t/**\n\t * {}\n\t * {}\n\t */\n", hash_docs_a, hash_docs_b))));
                },
                ("Send", _) => {}, ("Sync", _) => {},
                (s, i) => {
+                       // TODO: Both of the below should expose supertrait methods in C++, but doing so is
+                       // nontrivial.
                        generated_fields.push(if types.crate_types.traits.get(s).is_none() {
                                let (docs, name, ret) = convert_trait_impl_field(s);
                                writeln!(w, "\t/// {}", docs).unwrap();
                                writeln!(w, "\tpub {}: extern \"C\" fn (this_arg: *const c_void) -> {},", name, ret).unwrap();
-                               (name, true) // Assume clonable
+                               (name, None, None) // Assume clonable
                        } else {
                                // For in-crate supertraits, just store a C-mapped copy of the supertrait as a member.
                                writeln!(w, "\t/// Implementation of {} for this object.", i).unwrap();
-                               writeln!(w, "\tpub {}: crate::{},", i, s).unwrap();
                                let is_clonable = types.is_clonable(s);
-                               if !is_clonable && requires_clone {
-                                       writeln!(w, "\t/// Creates a copy of the {}, for a copy of this {}.", i, trait_name).unwrap();
-                                       writeln!(w, "\t/// Because {} doesn't natively support copying itself, you have to provide a full copy implementation here.", i).unwrap();
-                                       writeln!(w, "\tpub {}_clone: extern \"C\" fn (orig_{}: &{}) -> {},", i, i, i, i).unwrap();
-                               }
-                               (format!("{}", i), is_clonable)
+                               writeln!(w, "\tpub {}: crate::{},", i, s).unwrap();
+                               (format!("{}", i), if !is_clonable {
+                                       Some(format!("crate::{}_clone_fields", s))
+                               } else { None }, None)
                        });
                }
        ) );
        writeln!(w, "\t/// Frees any resources associated with this object given its this_arg pointer.").unwrap();
        writeln!(w, "\t/// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.").unwrap();
        writeln!(w, "\tpub free: Option<extern \"C\" fn(this_arg: *mut c_void)>,").unwrap();
-       generated_fields.push(("free".to_owned(), true));
+       generated_fields.push(("free".to_owned(), None, None));
        writeln!(w, "}}").unwrap();
 
        macro_rules! impl_trait_for_c {
@@ -427,7 +431,9 @@ fn writeln_trait<'a, 'b, W: std::io::Write>(w: &mut W, t: &'a syn::ItemTrait, ty
                                                }
                                                write_method_var_decl_body(w, &m.sig, "\t", $type_resolver, Some(&meth_gen_types), true);
                                                write!(w, "(self{}.{})(", $impl_accessor, m.sig.ident).unwrap();
-                                               write_method_call_params(w, &m.sig, "\t", $type_resolver, Some(&meth_gen_types), "", true);
+                                               let mut args = Vec::new();
+                                               write_method_call_params(&mut args, &m.sig, "\t", $type_resolver, Some(&meth_gen_types), "", true);
+                                               w.write_all(String::from_utf8(args).unwrap().replace("self", &format!("self{}", $impl_accessor)).as_bytes()).unwrap();
 
                                                writeln!(w, "\n\t}}").unwrap();
                                        },
@@ -451,6 +457,20 @@ fn writeln_trait<'a, 'b, W: std::io::Write>(w: &mut W, t: &'a syn::ItemTrait, ty
        writeln!(w, "unsafe impl Send for {} {{}}", trait_name).unwrap();
        writeln!(w, "unsafe impl Sync for {} {{}}", trait_name).unwrap();
 
+       writeln!(w, "#[no_mangle]").unwrap();
+       writeln!(w, "pub(crate) extern \"C\" fn {}_clone_fields(orig: &{}) -> {} {{", trait_name, trait_name, trait_name).unwrap();
+       writeln!(w, "\t{} {{", trait_name).unwrap();
+       writeln!(w, "\t\tthis_arg: orig.this_arg,").unwrap();
+       for (field, clone_fn, _) in generated_fields.iter() {
+               if let Some(f) = clone_fn {
+                       // If the field isn't clonable, blindly assume its a trait and hope for the best.
+                       writeln!(w, "\t\t{}: {}(&orig.{}),", field, f, field).unwrap();
+               } else {
+                       writeln!(w, "\t\t{}: Clone::clone(&orig.{}),", field, field).unwrap();
+               }
+       }
+       writeln!(w, "\t}}\n}}").unwrap();
+
        // Implement supertraits for the C-mapped struct.
        walk_supertraits!(t, Some(&types), (
                ("std::cmp::Eq", _)|("core::cmp::Eq", _) => {
@@ -467,17 +487,9 @@ fn writeln_trait<'a, 'b, W: std::io::Write>(w: &mut W, t: &'a syn::ItemTrait, ty
                        writeln!(w, "#[no_mangle]").unwrap();
                        writeln!(w, "/// Creates a copy of a {}", trait_name).unwrap();
                        writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", trait_name, trait_name, trait_name).unwrap();
-                       writeln!(w, "\t{} {{", trait_name).unwrap();
-                       writeln!(w, "\t\tthis_arg: if let Some(f) = orig.clone {{ (f)(orig.this_arg) }} else {{ orig.this_arg }},").unwrap();
-                       for (field, clonable) in generated_fields.iter() {
-                               if *clonable {
-                                       writeln!(w, "\t\t{}: Clone::clone(&orig.{}),", field, field).unwrap();
-                               } else {
-                                       writeln!(w, "\t\t{}: (orig.{}_clone)(&orig.{}),", field, field, field).unwrap();
-                                       writeln!(w, "\t\t{}_clone: orig.{}_clone,", field, field).unwrap();
-                               }
-                       }
-                       writeln!(w, "\t}}\n}}").unwrap();
+                       writeln!(w, "\tlet mut res = {}_clone_fields(orig);", trait_name).unwrap();
+                       writeln!(w, "\tif let Some(f) = orig.cloned {{ (f)(&mut res) }};").unwrap();
+                       writeln!(w, "\tres\n}}").unwrap();
                        writeln!(w, "impl Clone for {} {{", trait_name).unwrap();
                        writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
                        writeln!(w, "\t\t{}_clone(self)", trait_name).unwrap();
@@ -522,7 +534,8 @@ fn writeln_trait<'a, 'b, W: std::io::Write>(w: &mut W, t: &'a syn::ItemTrait, ty
        writeln!(w, "\t\t\tf(self.this_arg);").unwrap();
        writeln!(w, "\t\t}}\n\t}}\n}}").unwrap();
 
-       write_cpp_wrapper(cpp_headers, &trait_name, true);
+       write_cpp_wrapper(cpp_headers, &trait_name, true, Some(generated_fields.drain(..)
+               .filter_map(|(name, _, docs)| if let Some(docs) = docs { Some((name, docs)) } else { None }).collect()));
 }
 
 /// Write out a simple "opaque" type (eg structs) which contain a pointer to the native Rust type
@@ -567,7 +580,7 @@ fn writeln_opaque<W: std::io::Write>(w: &mut W, ident: &syn::Ident, struct_name:
        writeln!(w, "\t\tret").unwrap();
        writeln!(w, "\t}}\n}}").unwrap();
 
-       write_cpp_wrapper(cpp_headers, &format!("{}", ident), true);
+       write_cpp_wrapper(cpp_headers, &format!("{}", ident), true, None);
 }
 
 /// Writes out all the relevant mappings for a Rust struct, deferring to writeln_opaque to generate
@@ -604,7 +617,7 @@ fn writeln_struct<'a, 'b, W: std::io::Write>(w: &mut W, s: &'a syn::ItemStruct,
                                                and_token: syn::Token!(&)(Span::call_site()), lifetime: None, mutability: None,
                                                elem: Box::new(field.ty.clone()) });
                                        if types.understood_c_type(&ref_type, Some(&gen_types)) {
-                                               writeln_docs(w, &field.attrs, "");
+                                               writeln_arg_docs(w, &field.attrs, "", types, Some(&gen_types), vec![].drain(..), Some(&ref_type));
                                                write!(w, "#[no_mangle]\npub extern \"C\" fn {}_get_{}(this_ptr: &{}) -> ", struct_name, ident, struct_name).unwrap();
                                                types.write_c_type(w, &ref_type, Some(&gen_types), true);
                                                write!(w, " {{\n\tlet mut inner_val = &mut unsafe {{ &mut *this_ptr.inner }}.{};\n\t", ident).unwrap();
@@ -617,7 +630,7 @@ fn writeln_struct<'a, 'b, W: std::io::Write>(w: &mut W, s: &'a syn::ItemStruct,
                                        }
 
                                        if types.understood_c_type(&field.ty, Some(&gen_types)) {
-                                               writeln_docs(w, &field.attrs, "");
+                                               writeln_arg_docs(w, &field.attrs, "", types, Some(&gen_types), vec![("val".to_owned(), &field.ty)].drain(..), None);
                                                write!(w, "#[no_mangle]\npub extern \"C\" fn {}_set_{}(this_ptr: &mut {}, mut val: ", struct_name, ident, struct_name).unwrap();
                                                types.write_c_type(w, &field.ty, Some(&gen_types), false);
                                                write!(w, ") {{\n\t").unwrap();
@@ -803,13 +816,10 @@ fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut Typ
                                                        }
                                                }
                                                let mut requires_clone = false;
-                                               walk_supertraits!(trait_obj, Some(&types), (
-                                                       ("Clone", _) => requires_clone = true,
-                                                       (_, _) => {}
-                                               ) );
                                                walk_supertraits!(trait_obj, Some(&types), (
                                                        ("Clone", _) => {
-                                                               writeln!(w, "\t\tclone: Some({}_clone_void),", ident).unwrap();
+                                                               requires_clone = true;
+                                                               writeln!(w, "\t\tcloned: Some({}_{}_cloned),", trait_obj.ident, ident).unwrap();
                                                        },
                                                        ("Sync", _) => {}, ("Send", _) => {},
                                                        ("std::marker::Sync", _) => {}, ("std::marker::Send", _) => {},
@@ -827,9 +837,6 @@ fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut Typ
                                                                                }
                                                                        }
                                                                        write!(w, "\t\t}},\n").unwrap();
-                                                                       if !types.is_clonable(s) && requires_clone {
-                                                                               writeln!(w, "\t\t{}_clone: {}_{}_clone,", t, ident, t).unwrap();
-                                                                       }
                                                                } else {
                                                                        write_trait_impl_field_assign(w, s, ident);
                                                                }
@@ -914,27 +921,21 @@ fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut Typ
                                                                _ => unimplemented!(),
                                                        }
                                                }
-                                               walk_supertraits!(trait_obj, Some(&types), (
-                                                       (s, t) => {
-                                                               if let Some(supertrait_obj) = types.crate_types.traits.get(s) {
-                                                                       if !types.is_clonable(s) && requires_clone {
-                                                                               writeln!(w, "extern \"C\" fn {}_{}_clone(orig: &crate::{}) -> crate::{} {{", ident, t, s, s).unwrap();
-                                                                               writeln!(w, "\tcrate::{} {{", s).unwrap();
-                                                                               writeln!(w, "\t\tthis_arg: orig.this_arg,").unwrap();
-                                                                               writeln!(w, "\t\tfree: None,").unwrap();
-                                                                               for item in supertrait_obj.items.iter() {
-                                                                                       match item {
-                                                                                               syn::TraitItem::Method(m) => {
-                                                                                                       write_meth!(m, supertrait_obj, "");
-                                                                                               },
-                                                                                               _ => {},
-                                                                                       }
-                                                                               }
-                                                                               write!(w, "\t}}\n}}\n").unwrap();
+                                               if requires_clone {
+                                                       writeln!(w, "extern \"C\" fn {}_{}_cloned(new_obj: &mut crate::{}) {{", trait_obj.ident, ident, full_trait_path).unwrap();
+                                                       writeln!(w, "\tnew_obj.this_arg = {}_clone_void(new_obj.this_arg);", ident).unwrap();
+                                                       writeln!(w, "\tnew_obj.free = Some({}_free_void);", ident).unwrap();
+                                                       walk_supertraits!(trait_obj, Some(&types), (
+                                                               (s, t) => {
+                                                                       if types.crate_types.traits.get(s).is_some() {
+                                                                               assert!(!types.is_clonable(s)); // We don't currently support cloning with a clonable supertrait
+                                                                               writeln!(w, "\tnew_obj.{}.this_arg = new_obj.this_arg;", t).unwrap();
+                                                                               writeln!(w, "\tnew_obj.{}.free = None;", t).unwrap();
                                                                        }
                                                                }
-                                                       }
-                                               ) );
+                                                       ) );
+                                                       writeln!(w, "}}").unwrap();
+                                               }
                                                write!(w, "\n").unwrap();
                                        } else if path_matches_nongeneric(&trait_path.1, &["From"]) {
                                        } else if path_matches_nongeneric(&trait_path.1, &["Default"]) {
@@ -1057,8 +1058,10 @@ fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut Typ
                                                                                ExportStatus::NoExport|ExportStatus::TestOnly => continue,
                                                                                ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
                                                                        }
+                                                                       let mut meth_gen_types = gen_types.push_ctx();
+                                                                       assert!(meth_gen_types.learn_generics(&m.sig.generics, types));
                                                                        if m.defaultness.is_some() { unimplemented!(); }
-                                                                       writeln_docs(w, &m.attrs, "");
+                                                                       writeln_fn_docs(w, &m.attrs, "", types, Some(&meth_gen_types), m.sig.inputs.iter(), &m.sig.output);
                                                                        if let syn::ReturnType::Type(_, _) = &m.sig.output {
                                                                                writeln!(w, "#[must_use]").unwrap();
                                                                        }
@@ -1068,8 +1071,6 @@ fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut Typ
                                                                                DeclType::StructImported => format!("{}", ident),
                                                                                _ => unimplemented!(),
                                                                        };
-                                                                       let mut meth_gen_types = gen_types.push_ctx();
-                                                                       assert!(meth_gen_types.learn_generics(&m.sig.generics, types));
                                                                        write_method_params(w, &m.sig, &ret_type, types, Some(&meth_gen_types), false, true);
                                                                        write!(w, " {{\n\t").unwrap();
                                                                        write_method_var_decl_body(w, &m.sig, "", types, Some(&meth_gen_types), false);
@@ -1169,6 +1170,23 @@ fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut Typ
        }
 }
 
+/// Replaces upper case charachters with underscore followed by lower case except the first
+/// charachter and repeated upper case characthers (which are only made lower case).
+fn camel_to_snake_case(camel: &str) -> String {
+       let mut res = "".to_string();
+       let mut last_upper = -1;
+       for (idx, c) in camel.chars().enumerate() {
+               if c.is_uppercase() {
+                       if last_upper != idx as isize - 1 { res.push('_'); }
+                       res.push(c.to_lowercase().next().unwrap());
+                       last_upper = idx as isize;
+               } else {
+                       res.push(c);
+               }
+       }
+       res
+}
+
 
 /// Print a mapping of an enum. If all of the enum's fields are C-mapped in some form (or the enum
 /// is unitary), we generate an equivalent enum with all types replaced with their C mapped
@@ -1192,25 +1210,31 @@ fn writeln_enum<'a, 'b, W: std::io::Write>(w: &mut W, e: &'a syn::ItemEnum, type
        assert!(gen_types.learn_generics(&e.generics, types));
 
        let mut needs_free = false;
+       let mut constr = Vec::new();
 
        writeln!(w, "#[must_use]\n#[derive(Clone)]\n#[repr(C)]\npub enum {} {{", e.ident).unwrap();
        for var in e.variants.iter() {
                assert_eq!(export_status(&var.attrs), ExportStatus::Export); // We can't partially-export a mirrored enum
                writeln_docs(w, &var.attrs, "\t");
                write!(w, "\t{}", var.ident).unwrap();
+               writeln!(&mut constr, "#[no_mangle]\n/// Utility method to constructs a new {}-variant {}", var.ident, e.ident).unwrap();
+               let constr_name = camel_to_snake_case(&format!("{}", var.ident));
+               write!(&mut constr, "pub extern \"C\" fn {}_{}(", e.ident, constr_name).unwrap();
+               let mut empty_tuple_variant = false;
                if let syn::Fields::Named(fields) = &var.fields {
                        needs_free = true;
                        writeln!(w, " {{").unwrap();
-                       for field in fields.named.iter() {
+                       for (idx, field) in fields.named.iter().enumerate() {
                                if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
-                               writeln_docs(w, &field.attrs, "\t\t");
+                               writeln_field_docs(w, &field.attrs, "\t\t", types, Some(&gen_types), &field.ty);
                                write!(w, "\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
+                               write!(&mut constr, "{}{}: ", if idx != 0 { ", " } else { "" }, field.ident.as_ref().unwrap()).unwrap();
                                types.write_c_type(w, &field.ty, Some(&gen_types), false);
+                               types.write_c_type(&mut constr, &field.ty, Some(&gen_types), false);
                                writeln!(w, ",").unwrap();
                        }
                        write!(w, "\t}}").unwrap();
                } else if let syn::Fields::Unnamed(fields) = &var.fields {
-                       let mut empty_tuple_variant = false;
                        if fields.unnamed.len() == 1 {
                                let mut empty_check = Vec::new();
                                types.write_c_type(&mut empty_check, &fields.unnamed[0].ty, Some(&gen_types), false);
@@ -1223,15 +1247,37 @@ fn writeln_enum<'a, 'b, W: std::io::Write>(w: &mut W, e: &'a syn::ItemEnum, type
                                write!(w, "(").unwrap();
                                for (idx, field) in fields.unnamed.iter().enumerate() {
                                        if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
+                                       write!(&mut constr, "{}: ", ('a' as u8 + idx as u8) as char).unwrap();
                                        types.write_c_type(w, &field.ty, Some(&gen_types), false);
+                                       types.write_c_type(&mut constr, &field.ty, Some(&gen_types), false);
                                        if idx != fields.unnamed.len() - 1 {
                                                write!(w, ",").unwrap();
+                                               write!(&mut constr, ",").unwrap();
                                        }
                                }
                                write!(w, ")").unwrap();
                        }
                }
                if var.discriminant.is_some() { unimplemented!(); }
+               write!(&mut constr, ") -> {} {{\n\t{}::{}", e.ident, e.ident, var.ident).unwrap();
+               if let syn::Fields::Named(fields) = &var.fields {
+                       writeln!(&mut constr, " {{").unwrap();
+                       for field in fields.named.iter() {
+                               writeln!(&mut constr, "\t\t{},", field.ident.as_ref().unwrap()).unwrap();
+                       }
+                       writeln!(&mut constr, "\t}}").unwrap();
+               } else if let syn::Fields::Unnamed(fields) = &var.fields {
+                       if !empty_tuple_variant {
+                               write!(&mut constr, "(").unwrap();
+                               for idx in 0..fields.unnamed.len() {
+                                       write!(&mut constr, "{}, ", ('a' as u8 + idx as u8) as char).unwrap();
+                               }
+                               writeln!(&mut constr, ")").unwrap();
+                       } else {
+                               writeln!(&mut constr, "").unwrap();
+                       }
+               }
+               writeln!(&mut constr, "}}").unwrap();
                writeln!(w, ",").unwrap();
        }
        writeln!(w, "}}\nuse {}::{} as native{};\nimpl {} {{", types.module_path, e.ident, e.ident, e.ident).unwrap();
@@ -1372,7 +1418,8 @@ fn writeln_enum<'a, 'b, W: std::io::Write>(w: &mut W, e: &'a syn::ItemEnum, type
        writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", e.ident, e.ident, e.ident).unwrap();
        writeln!(w, "\torig.clone()").unwrap();
        writeln!(w, "}}").unwrap();
-       write_cpp_wrapper(cpp_headers, &format!("{}", e.ident), needs_free);
+       w.write_all(&constr).unwrap();
+       write_cpp_wrapper(cpp_headers, &format!("{}", e.ident), needs_free, None);
 }
 
 fn writeln_fn<'a, 'b, W: std::io::Write>(w: &mut W, f: &'a syn::ItemFn, types: &mut TypeResolver<'b, 'a>) {
@@ -1381,11 +1428,11 @@ fn writeln_fn<'a, 'b, W: std::io::Write>(w: &mut W, f: &'a syn::ItemFn, types: &
                ExportStatus::NoExport|ExportStatus::TestOnly => return,
                ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
        }
-       writeln_docs(w, &f.attrs, "");
-
        let mut gen_types = GenericTypes::new(None);
        if !gen_types.learn_generics(&f.sig.generics, types) { return; }
 
+       writeln_fn_docs(w, &f.attrs, "", types, Some(&gen_types), f.sig.inputs.iter(), &f.sig.output);
+
        write!(w, "#[no_mangle]\npub extern \"C\" fn {}(", f.sig.ident).unwrap();
        write_method_params(w, &f.sig, "", types, Some(&gen_types), false, true);
        write!(w, " {{\n\t").unwrap();
@@ -1521,7 +1568,7 @@ fn convert_file<'a, 'b>(libast: &'a FullLibraryAST, crate_types: &CrateTypes<'a>
                                                if let syn::Type::Path(p) = &*c.ty {
                                                        let resolved_path = type_resolver.resolve_path(&p.path, None);
                                                        if type_resolver.is_primitive(&resolved_path) {
-                                                               writeln_docs(&mut out, &c.attrs, "");
+                                                               writeln_field_docs(&mut out, &c.attrs, "", &mut type_resolver, None, &*c.ty);
                                                                writeln!(out, "\n#[no_mangle]").unwrap();
                                                                writeln!(out, "pub static {}: {} = {}::{};", c.ident, resolved_path, module, c.ident).unwrap();
                                                        }
@@ -1756,7 +1803,7 @@ fn main() {
        // For container templates which we created while walking the crate, make sure we add C++
        // mapped types so that C++ users can utilize the auto-destructors available.
        for (ty, has_destructor) in libtypes.templates_defined.borrow().iter() {
-               write_cpp_wrapper(&mut cpp_header_file, ty, *has_destructor);
+               write_cpp_wrapper(&mut cpp_header_file, ty, *has_destructor, None);
        }
        writeln!(cpp_header_file, "}}").unwrap();
 
index ff1d4b833581602d523e0fce0b46fb6ddc68d511..13c3b0ed0c2b7b3b00b4af8e58728a117614d6cb 100644 (file)
@@ -1263,7 +1263,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
        }
        /// Returns true if the path is a "transparent" container, ie an Option or a container which does
        /// not require a generated continer class.
-       fn is_path_transparent_container(&self, full_path: &syn::Path, generics: Option<&GenericTypes>, is_ref: bool) -> bool {
+       pub fn is_path_transparent_container(&self, full_path: &syn::Path, generics: Option<&GenericTypes>, is_ref: bool) -> bool {
                let inner_iter = match &full_path.segments.last().unwrap().arguments {
                        syn::PathArguments::None => return false,
                        syn::PathArguments::AngleBracketed(args) => args.args.iter().map(|arg| {
index cd100f6a86f1fd00d81de86bc3a5df28435f910d..c1bfc8dde3cc6b993c7ba1de73f0cd0af7bf8074 100755 (executable)
@@ -198,15 +198,79 @@ if [ "$HOST_PLATFORM" = "host: x86_64-apple-darwin" ]; then
 
        # stdlib.h doesn't exist in clang's wasm sysroot, and cbindgen
        # doesn't actually use it anyway, so drop the import.
-       sed -i '' 's/#include <stdlib.h>/#include <ldk_rust_types.h>/g' include/lightning.h
+       sed -i '' 's/#include <stdlib.h>/#include "ldk_rust_types.h"/g' include/lightning.h
 else
        sed -i 's/typedef LDKnative.*Import.*LDKnative.*;//g' include/lightning.h
 
        # stdlib.h doesn't exist in clang's wasm sysroot, and cbindgen
        # doesn't actually use it anyway, so drop the import.
-       sed -i 's/#include <stdlib.h>/#include <ldk_rust_types.h>/g' include/lightning.h
+       sed -i 's/#include <stdlib.h>/#include "ldk_rust_types.h"/g' include/lightning.h
 fi
 
+# Build C++ class methods which call trait methods
+set +x # Echoing every command is very verbose here
+OLD_IFS="$IFS"
+export IFS=''
+echo '#include <string.h>' > include/lightningpp_new.hpp
+echo 'namespace LDK {' >> include/lightningpp_new.hpp
+echo '// Forward declarations' >> include/lightningpp_new.hpp
+cat include/lightningpp.hpp | sed -n 's/class \(.*\) {/class \1;/p' >> include/lightningpp_new.hpp
+echo '' >> include/lightningpp_new.hpp
+
+DECLS=""
+while read LINE; do
+       case "$LINE" in
+               "#include <string.h>")
+                       # We already printed this above.
+                       ;;
+               "namespace LDK {")
+                       # We already printed this above.
+                       ;;
+               "}")
+                       # We'll print this at the end
+                       ;;
+               "XXX"*)
+                       STRUCT_NAME="$(echo "$LINE" | awk '{ print $2 }')"
+                       METHOD_NAME="$(echo "$LINE" | awk '{ print $3 }')"
+                       STRUCT_CONTENTS="$(cat include/lightning.h  | sed -n -e "/struct LDK$STRUCT_NAME/{:s" -e "/\} LDK$STRUCT_NAME;/!{N" -e "b s" -e "}" -e p -e "}")"
+                       METHOD="$(echo "$STRUCT_CONTENTS" | grep "(\*$METHOD_NAME)")"
+                       if [ "$METHOD" = "" ]; then
+                               echo "Unable to find method declaration for $LINE"
+                               exit 1
+                       fi
+                       RETVAL="$(echo "$METHOD" | sed 's/[ ]*\([A-Za-z0-9 _]*\)(\*\(.*\)).*/\1/' | sed 's/^struct LDK/LDK::/g' | tr -d ' ')"
+                       [ "$RETVAL" = "LDK::SecretKey" ] && RETVAL="LDKSecretKey"
+                       [ "$RETVAL" = "LDK::PublicKey" ] && RETVAL="LDKPublicKey"
+                       [ "$RETVAL" = "LDK::ThirtyTwoBytes" ] && RETVAL="LDKThirtyTwoBytes"
+                       PARAMS="$(echo "$METHOD" | sed 's/.*(\*.*)(\(const \)*void \*this_arg\(, \)*\(.*\));/\3/')"
+
+                       echo -e "\tinline $RETVAL $METHOD_NAME($PARAMS);" >> include/lightningpp_new.hpp
+                       DECLS="$DECLS"$'\n'"inline $RETVAL $STRUCT_NAME::$METHOD_NAME($PARAMS) {"
+
+                       DECLS="$DECLS"$'\n'$'\t'
+                       [ "$RETVAL" != "void" ] && DECLS="$DECLS$RETVAL ret = "
+                       DECLS="$DECLS(self.$METHOD_NAME)(self.this_arg"
+
+                       IFS=','; for PARAM in $PARAMS; do
+                               DECLS="$DECLS, "
+                               DECLS="$DECLS$(echo $PARAM | sed 's/.* (*\**\([a-zA-Z0-9_]*\)\()[\[0-9\]*]\)*/\1/')"
+                       done
+                       IFS=''
+
+                       DECLS="$DECLS);"
+                       [ "$RETVAL" != "void" ] && DECLS="$DECLS"$'\n'$'\t'"return ret;"
+                       DECLS="$DECLS"$'\n'"}"
+                       ;;
+               *)
+                       echo "$LINE" >> include/lightningpp_new.hpp
+       esac
+done < include/lightningpp.hpp
+echo "$DECLS" >> include/lightningpp_new.hpp
+echo "}" >> include/lightningpp_new.hpp
+export IFS="$OLD_IFS"
+set -x
+mv include/lightningpp_new.hpp include/lightningpp.hpp
+
 # Finally, sanity-check the generated C and C++ bindings with demo apps:
 # Naively run the C demo app:
 gcc $LOCAL_CFLAGS -Wall -g -pthread demo.c target/debug/libldk.a -ldl
@@ -218,7 +282,7 @@ LD_LIBRARY_PATH=target/debug/ ./a.out > /dev/null
 
 # Finally, run the C++ demo app with our native networking library
 # in valgrind to test memory model correctness and lack of leaks.
-gcc $LOCAL_CFLAGS -std=c99 -Wall -g -pthread -I../ldk-net ../ldk-net/ldk_net.c -c -o ldk_net.o
+gcc $LOCAL_CFLAGS -fPIC -std=c99 -Wall -g -pthread -I../ldk-net ../ldk-net/ldk_net.c -c -o ldk_net.o
 g++ $LOCAL_CFLAGS -std=c++11 -Wall -g -pthread -DREAL_NET -I../ldk-net ldk_net.o demo.cpp target/debug/libldk.a -ldl
 if [ -x "`which valgrind`" ]; then
        valgrind --error-exitcode=4 --memcheck:leak-check=full --show-leak-kinds=all ./a.out
@@ -276,7 +340,7 @@ else
        echo "WARNING: Can't use memory sanitizer on non-Linux, non-x86 platforms"
 fi
 
-RUSTC_LLVM_V=$(rustc --version --verbose | grep "LLVM version" | awk '{ print substr($3, 0, 4); }')
+RUSTC_LLVM_V=$(rustc --version --verbose | grep "LLVM version" | awk '{ print substr($3, 0, 2); }')
 
 if [ "$HOST_PLATFORM" = "host: x86_64-apple-darwin" ]; then
        # Apple is special, as always, and their versions of clang aren't
@@ -285,15 +349,15 @@ if [ "$HOST_PLATFORM" = "host: x86_64-apple-darwin" ]; then
                echo "Apple clang isn't compatible with upstream clang, install upstream clang"
                CLANG_LLVM_V="0"
        else
-               CLANG_LLVM_V=$(clang --version | head -n1 | awk '{ print substr($4, 0, 4); }')
+               CLANG_LLVM_V=$(clang --version | head -n1 | awk '{ print substr($4, 0, 2); }')
                if [ -x "$(which ld64.lld)" ]; then
-                       LLD_LLVM_V="$(ld64.lld --version | awk '{ print substr($2, 0, 4); }')"
+                       LLD_LLVM_V="$(ld64.lld --version | awk '{ print substr($2, 0, 2); }')"
                fi
        fi
 else
-       CLANG_LLVM_V=$(clang --version | head -n1 | awk '{ print substr($4, 0, 4); }')
+       CLANG_LLVM_V=$(clang --version | head -n1 | awk '{ print substr($4, 0, 2); }')
        if [ -x "$(which ld.lld)" ]; then
-               LLD_LLVM_V="$(ld.lld --version | awk '{ print substr($2, 0, 4); }')"
+               LLD_LLVM_V="$(ld.lld --version | awk '{ print substr($2, 0, 2); }')"
        fi
 fi
 
@@ -314,7 +378,7 @@ elif [ -x "$(which clang-$RUSTC_LLVM_V)" ]; then
        fi
        if [ "$LLD_LLVM_V" != "$RUSTC_LLVM_V" ]; then
                LLD="$(which lld-$RUSTC_LLVM_V || echo lld)"
-               LLD_LLVM_V="$(ld.$LLD --version | awk '{ print substr($2, 0, 4); }')"
+               LLD_LLVM_V="$(ld.$LLD --version | awk '{ print substr($2, 0, 2); }')"
                if [ "$LLD_LLVM_V" != "$RUSTC_LLVM_V" ]; then
                        echo "Could not find a workable version of lld, not using cross-language LTO"
                        unset LLD
@@ -351,7 +415,7 @@ if [ "$HOST_PLATFORM" = "host: x86_64-unknown-linux-gnu" -o "$HOST_PLATFORM" = "
                ASAN_OPTIONS='detect_leaks=1 detect_invalid_pointer_pairs=1 detect_stack_use_after_return=1' ./a.out >/dev/null
 
                # ...then the C++ demo app with the ldk_net network implementation
-               $CLANG $LOCAL_CFLAGS -fsanitize=address -g -I../ldk-net ../ldk-net/ldk_net.c -c -o ldk_net.o
+               $CLANG $LOCAL_CFLAGS -fPIC -fsanitize=address -g -I../ldk-net ../ldk-net/ldk_net.c -c -o ldk_net.o
                $CLANGPP $LOCAL_CFLAGS -std=c++11 -fsanitize=address -g -DREAL_NET -I../ldk-net ldk_net.o demo.cpp target/debug/libldk.a -ldl
                ASAN_OPTIONS='detect_leaks=1 detect_invalid_pointer_pairs=1 detect_stack_use_after_return=1' ./a.out >/dev/null
        else
index fb349ae1368ccddba0da8b242bdbfcb5802d0236..dc19e8ee6794a900b1a2a3939940cd333c6d8a85 100644 (file)
@@ -38,7 +38,7 @@
 
 #define MAX_CONNS 1024
 struct SocketHandler {
-       const struct LDKPeerManager *ldk_peer_manager;
+       struct LDKPeerManager ldk_peer_manager;
        pthread_t socket_thread;
        bool should_exit;
        int pipefds[2];
@@ -142,12 +142,12 @@ static uint64_t sock_hash(const void* desc) {
        const struct Descriptor *descriptor = (const struct Descriptor*)desc;
        return (uint64_t)descriptor->fd;
 }
-static void* sock_clone(const void* desc) {
-       const struct Descriptor *descriptor = (const struct Descriptor*)desc;
+static void sock_cloned(LDKSocketDescriptor *NONNULL_PTR ldk_desc) {
+       const struct Descriptor *descriptor = (const struct Descriptor*)ldk_desc->this_arg;
        struct Descriptor *new_desc = malloc(sizeof(struct Descriptor));
        new_desc->handler = descriptor->handler;
        new_desc->fd = descriptor->fd;
-       return new_desc;
+       ldk_desc->this_arg = (void*) new_desc;
 }
 static void sock_free(void* desc) {
        free(desc);
@@ -163,7 +163,7 @@ static inline LDKSocketDescriptor get_descriptor(struct SocketHandler *handler,
                .disconnect_socket = sock_disconnect,
                .eq = sock_eq,
                .hash = sock_hash,
-               .clone = sock_clone,
+               .cloned = sock_cloned,
                .free = sock_free,
        };
        return ret;
@@ -215,7 +215,7 @@ static void *sock_thread_fn(void* arg) {
                                                                if (newfd >= 0) {
                                                                        // Received a new connection, register it!
                                                                        LDKSocketDescriptor new_descriptor = get_descriptor(handler, newfd);
-                                                                       LDKCResult_NonePeerHandleErrorZ con_res = PeerManager_new_inbound_connection(handler->ldk_peer_manager, new_descriptor);
+                                                                       LDKCResult_NonePeerHandleErrorZ con_res = PeerManager_new_inbound_connection(&handler->ldk_peer_manager, new_descriptor);
                                                                        if (con_res.result_ok) {
                                                                                if (register_socket(handler, newfd, 0))
                                                                                        shutdown(newfd, SHUT_RDWR);
@@ -237,7 +237,7 @@ static void *sock_thread_fn(void* arg) {
                                                                .data = readbuf,
                                                                .datalen = readlen,
                                                        };
-                                                       LDKCResult_boolPeerHandleErrorZ res = PeerManager_read_event(handler->ldk_peer_manager, &descriptor, data);
+                                                       LDKCResult_boolPeerHandleErrorZ res = PeerManager_read_event(&handler->ldk_peer_manager, &descriptor, data);
                                                        if (res.result_ok) {
                                                                if (*res.contents.result) {
                                                                        lockres = pthread_mutex_lock(&handler->sockets_mutex);
@@ -255,7 +255,7 @@ static void *sock_thread_fn(void* arg) {
                                                }
                                        }
                                        if (pollfds[i].revents & POLLOUT) {
-                                               LDKCResult_NonePeerHandleErrorZ res = PeerManager_write_buffer_space_avail(handler->ldk_peer_manager, &descriptor);
+                                               LDKCResult_NonePeerHandleErrorZ res = PeerManager_write_buffer_space_avail(&handler->ldk_peer_manager, &descriptor);
                                                if (!res.result_ok) {
                                                        close_socks[close_socks_count++] = i;
                                                }
@@ -274,7 +274,7 @@ static void *sock_thread_fn(void* arg) {
                // as we walk.
                for (int i = 0; i < close_socks_count; i++) {
                        LDKSocketDescriptor descriptor = get_descriptor(handler, handler->pollfds[close_socks[i]].fd);
-                       PeerManager_socket_disconnected(handler->ldk_peer_manager, &descriptor);
+                       PeerManager_socket_disconnected(&handler->ldk_peer_manager, &descriptor);
                        SocketDescriptor_free(descriptor);
                }
 
@@ -294,14 +294,14 @@ static void *sock_thread_fn(void* arg) {
                lockres = pthread_mutex_unlock(&handler->sockets_mutex);
                assert(lockres == 0);
 
-               PeerManager_process_events(handler->ldk_peer_manager);
+               PeerManager_process_events(&handler->ldk_peer_manager);
        }
 
        lockres = pthread_mutex_lock(&handler->sockets_mutex);
        assert(lockres == 0);
        for (int i = 0; i < handler->sockcount; i++) {
                LDKSocketDescriptor descriptor = get_descriptor(handler, handler->pollfds[i].fd);
-               PeerManager_socket_disconnected(handler->ldk_peer_manager, &descriptor);
+               PeerManager_socket_disconnected(&handler->ldk_peer_manager, &descriptor);
                SocketDescriptor_free(descriptor);
        }
 
@@ -326,7 +326,7 @@ void* init_socket_handling(const struct LDKPeerManager *NONNULL_PTR ldk_peer_man
        handler->pipefds[0] = -1;
        handler->pipefds[1] = -1;
 
-       handler->ldk_peer_manager = ldk_peer_manager;
+       handler->ldk_peer_manager = *ldk_peer_manager;
        handler->should_exit = false;
 
        if (pipe(handler->pipefds) != 0) goto err;
@@ -380,7 +380,7 @@ int socket_connect(void* arg, LDKPublicKey pubkey, struct sockaddr *addr, size_t
        if (register_socket(handler, fd, 0)) return -4;
 
        LDKSocketDescriptor descriptor = get_descriptor(handler, fd);
-       LDKCResult_CVec_u8ZPeerHandleErrorZ con_res = PeerManager_new_outbound_connection(handler->ldk_peer_manager, pubkey, descriptor);
+       LDKCResult_CVec_u8ZPeerHandleErrorZ con_res = PeerManager_new_outbound_connection(&handler->ldk_peer_manager, pubkey, descriptor);
        if (con_res.result_ok) {
                ssize_t write_count = send(fd, con_res.contents.result->data, con_res.contents.result->datalen, MSG_NOSIGNAL);
                if (write_count != con_res.contents.result->datalen)
index 258b5bab2cfb308bdcc43df647885453e4989051..f8b3edb05577d540671a2214fd0afe39b1e8576a 100644 (file)
@@ -1,4 +1,4 @@
-#include <lightning.h>
+#include "lightning.h"
 #include <sys/socket.h>
 /**
  * Initializes socket handling and spawns a background thread to handle socket
index ab108810a182ebfcdc1be85f766ce5f1e1df011c..523806498b11a2b3320bc820b1882089994e357e 100644 (file)
@@ -15,13 +15,13 @@ crate-type = ["staticlib"
 ,"cdylib"]
 
 [dependencies]
-bitcoin = "0.26"
+bitcoin = "0.27"
 secp256k1 = { version = "0.20.3", features = ["global-context-less-secure"] }
 # Note that the following line is matched by genbindings to update the path
-lightning = { git = "https://github.com/rust-bitcoin/rust-lightning", rev = "afae12ea1e610634f90335443e3fe9f126bf5551", features = ["allow_wallclock_use"] }
-lightning-persister = { git = "https://github.com/rust-bitcoin/rust-lightning", rev = "afae12ea1e610634f90335443e3fe9f126bf5551" }
-lightning-invoice = { git = "https://github.com/rust-bitcoin/rust-lightning", rev = "afae12ea1e610634f90335443e3fe9f126bf5551" }
-lightning-background-processor = { git = "https://github.com/rust-bitcoin/rust-lightning", rev = "afae12ea1e610634f90335443e3fe9f126bf5551" }
+lightning = { git = "https://github.com/rust-bitcoin/rust-lightning", rev = "853007800ebb433f53b5b10e1a941cc65c04e829", features = ["allow_wallclock_use"] }
+lightning-persister = { git = "https://github.com/rust-bitcoin/rust-lightning", rev = "853007800ebb433f53b5b10e1a941cc65c04e829" }
+lightning-invoice = { git = "https://github.com/rust-bitcoin/rust-lightning", rev = "853007800ebb433f53b5b10e1a941cc65c04e829" }
+lightning-background-processor = { git = "https://github.com/rust-bitcoin/rust-lightning", rev = "853007800ebb433f53b5b10e1a941cc65c04e829" }
 
 # Always force panic=abort, further options are set in the genbindings.sh build script
 [profile.dev]
index bcbe2641dc4a39e161d877b98f14d22253c1a014..ec6c74d97cb08ee5fadb86fc9f28150be38d11e3 100644 (file)
@@ -1,7 +1,7 @@
 language = "C"
 include_guard = "LDK_C_BINDINGS_H"
 autogen_warning = "/* Warning, this file is autogenerated by cbindgen. Don't modify this manually. */"
-trailer = "#include <ldk_ver.h>"
+trailer = "#include \"ldk_ver.h\""
 include_version = true
 namespace = "LDK"
 
index b71edc324581052dc102f17d3a0dcbe331a055f2..7c6dfda2e0f1c93ffbe83ba0a7dfbc9c0943ff53 100644 (file)
@@ -308,7 +308,7 @@ public:
                        .disconnect_socket = sock_disconnect_socket,
                        .eq = sock_eq,
                        .hash = sock_hash,
-                       .clone = NULL,
+                       .cloned = NULL,
                        .free = NULL,
                };
 
@@ -318,7 +318,7 @@ public:
                        .disconnect_socket = sock_disconnect_socket,
                        .eq = sock_eq,
                        .hash = sock_hash,
-                       .clone = NULL,
+                       .cloned = NULL,
                        .free = NULL,
                };
 
@@ -637,9 +637,11 @@ int main() {
                        assert(queue.events.size() == 1);
                        assert(queue.events[0]->tag == LDKEvent_PaymentReceived);
                        assert(!memcmp(queue.events[0]->payment_received.payment_hash.data, payment_hash.data, 32));
-                       assert(!memcmp(queue.events[0]->payment_received.payment_secret.data, Invoice_payment_secret(invoice->contents.result).data, 32));
+                       assert(queue.events[0]->payment_received.purpose.tag == LDKPaymentPurpose_InvoicePayment);
+                       assert(!memcmp(queue.events[0]->payment_received.purpose.invoice_payment.payment_secret.data,
+                                       Invoice_payment_secret(invoice->contents.result).data, 32));
                        assert(queue.events[0]->payment_received.amt == 5000);
-                       memcpy(payment_preimage.data, queue.events[0]->payment_received.payment_preimage.data, 32);
+                       memcpy(payment_preimage.data, queue.events[0]->payment_received.purpose.invoice_payment.payment_preimage.data, 32);
                        assert(ChannelManager_claim_funds(&cm2, payment_preimage));
                }
                PeerManager_process_events(&net2);
index 55957788957f941d51f015cc93ab7242eb3a6d83..2a5f617dbc4d165414bdf922c3058ecd482d23ec 100644 (file)
@@ -8,7 +8,7 @@
 #include <stdarg.h>
 #include <stdbool.h>
 #include <stdint.h>
-#include <ldk_rust_types.h>
+#include "ldk_rust_types.h"
 
 /**
  * An error when accessing the chain via [`Access`].
@@ -2223,6 +2223,8 @@ typedef enum LDKErrorAction_Tag {
 typedef struct LDKErrorAction_LDKDisconnectPeer_Body {
    /**
     * An error message which we should make an effort to send before we disconnect.
+    *
+    * Note that this (or a relevant inner pointer) may be NULL or all-0s to represent None
     */
    struct LDKErrorMessage msg;
 } LDKErrorAction_LDKDisconnectPeer_Body;
@@ -3340,21 +3342,16 @@ typedef struct LDKSign {
     * Implementation of BaseSign for this object.
     */
    struct LDKBaseSign BaseSign;
-   /**
-    * Creates a copy of the BaseSign, for a copy of this Sign.
-    * Because BaseSign doesn't natively support copying itself, you have to provide a full copy implementation here.
-    */
-   struct LDKBaseSign (*BaseSign_clone)(const struct LDKBaseSign *NONNULL_PTR orig_BaseSign);
    /**
     * Serialize the object into a byte array
     */
    struct LDKCVec_u8Z (*write)(const void *this_arg);
    /**
-    * Creates a copy of the object pointed to by this_arg, for a copy of this Sign.
-    * Note that the ultimate copy of the Sign will have all function pointers the same as the original.
-    * May be NULL if no action needs to be taken, the this_arg pointer will be copied into the new Sign.
+    * Called, if set, after this Sign has been cloned into a duplicate object.
+    * The new Sign is provided, and should be mutated as needed to perform a
+    * deep copy of the object pointed to by this_arg or avoid any double-freeing.
     */
-   void *(*clone)(const void *this_arg);
+   void (*cloned)(struct LDKSign *NONNULL_PTR new_Sign);
    /**
     * Frees any resources associated with this object given its this_arg pointer.
     * Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
@@ -3959,6 +3956,39 @@ typedef struct LDKCResult_NonePaymentSendFailureZ {
    bool result_ok;
 } LDKCResult_NonePaymentSendFailureZ;
 
+/**
+ * The contents of CResult_PaymentHashPaymentSendFailureZ
+ */
+typedef union LDKCResult_PaymentHashPaymentSendFailureZPtr {
+   /**
+    * A pointer to the contents in the success state.
+    * Reading from this pointer when `result_ok` is not set is undefined.
+    */
+   struct LDKThirtyTwoBytes *result;
+   /**
+    * A pointer to the contents in the error state.
+    * Reading from this pointer when `result_ok` is set is undefined.
+    */
+   struct LDKPaymentSendFailure *err;
+} LDKCResult_PaymentHashPaymentSendFailureZPtr;
+
+/**
+ * A CResult_PaymentHashPaymentSendFailureZ represents the result of a fallible operation,
+ * containing a crate::c_types::ThirtyTwoBytes on success and a crate::lightning::ln::channelmanager::PaymentSendFailure on failure.
+ * `result_ok` indicates the overall state, and the contents are provided via `contents`.
+ */
+typedef struct LDKCResult_PaymentHashPaymentSendFailureZ {
+   /**
+    * The contents of this CResult_PaymentHashPaymentSendFailureZ, accessible via either
+    * `err` or `result` depending on the state of `result_ok`.
+    */
+   union LDKCResult_PaymentHashPaymentSendFailureZPtr contents;
+   /**
+    * Whether this CResult_PaymentHashPaymentSendFailureZ represents a success state.
+    */
+   bool result_ok;
+} LDKCResult_PaymentHashPaymentSendFailureZ;
+
 /**
  * A 4-byte byte array.
  */
@@ -5385,6 +5415,74 @@ typedef struct LDKCVec_C2Tuple_TxidCVec_C2Tuple_u32ScriptZZZZ {
    uintptr_t datalen;
 } LDKCVec_C2Tuple_TxidCVec_C2Tuple_u32ScriptZZZZ;
 
+/**
+ * Some information provided on receipt of payment depends on whether the payment received is a
+ * spontaneous payment or a \"conventional\" lightning payment that's paying an invoice.
+ */
+typedef enum LDKPaymentPurpose_Tag {
+   /**
+    * Information for receiving a payment that we generated an invoice for.
+    */
+   LDKPaymentPurpose_InvoicePayment,
+   /**
+    * Because this is a spontaneous payment, the payer generated their own preimage rather than us
+    * (the payee) providing a preimage.
+    */
+   LDKPaymentPurpose_SpontaneousPayment,
+   /**
+    * Must be last for serialization purposes
+    */
+   LDKPaymentPurpose_Sentinel,
+} LDKPaymentPurpose_Tag;
+
+typedef struct LDKPaymentPurpose_LDKInvoicePayment_Body {
+   /**
+    * The preimage to the payment_hash, if the payment hash (and secret) were fetched via
+    * [`ChannelManager::create_inbound_payment`]. If provided, this can be handed directly to
+    * [`ChannelManager::claim_funds`].
+    *
+    * [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
+    * [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
+    *
+    * Note that this (or a relevant inner pointer) may be NULL or all-0s to represent None
+    */
+   struct LDKThirtyTwoBytes payment_preimage;
+   /**
+    * The \"payment secret\". This authenticates the sender to the recipient, preventing a
+    * number of deanonymization attacks during the routing process.
+    * It is provided here for your reference, however its accuracy is enforced directly by
+    * [`ChannelManager`] using the values you previously provided to
+    * [`ChannelManager::create_inbound_payment`] or
+    * [`ChannelManager::create_inbound_payment_for_hash`].
+    *
+    * [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
+    * [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
+    * [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
+    */
+   struct LDKThirtyTwoBytes payment_secret;
+   /**
+    * This is the `user_payment_id` which was provided to
+    * [`ChannelManager::create_inbound_payment_for_hash`] or
+    * [`ChannelManager::create_inbound_payment`]. It has no meaning inside of LDK and is
+    * simply copied here. It may be used to correlate PaymentReceived events with invoice
+    * metadata stored elsewhere.
+    *
+    * [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
+    * [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
+    */
+   uint64_t user_payment_id;
+} LDKPaymentPurpose_LDKInvoicePayment_Body;
+
+typedef struct MUST_USE_STRUCT LDKPaymentPurpose {
+   LDKPaymentPurpose_Tag tag;
+   union {
+      LDKPaymentPurpose_LDKInvoicePayment_Body invoice_payment;
+      struct {
+         struct LDKThirtyTwoBytes spontaneous_payment;
+      };
+   };
+} LDKPaymentPurpose;
+
 /**
  * An Event which you should probably take some action in response to.
  *
@@ -5437,6 +5535,11 @@ typedef enum LDKEvent_Tag {
     * somewhere and spend them when you create on-chain transactions.
     */
    LDKEvent_SpendableOutputs,
+   /**
+    * This event is generated when a payment has been successfully forwarded through us and a
+    * forwarding fee earned.
+    */
+   LDKEvent_PaymentForwarded,
    /**
     * Must be last for serialization purposes
     */
@@ -5468,28 +5571,6 @@ typedef struct LDKEvent_LDKPaymentReceived_Body {
     * The hash for which the preimage should be handed to the ChannelManager.
     */
    struct LDKThirtyTwoBytes payment_hash;
-   /**
-    * The preimage to the payment_hash, if the payment hash (and secret) were fetched via
-    * [`ChannelManager::create_inbound_payment`]. If provided, this can be handed directly to
-    * [`ChannelManager::claim_funds`].
-    *
-    * [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
-    * [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
-    */
-   struct LDKThirtyTwoBytes payment_preimage;
-   /**
-    * The \"payment secret\". This authenticates the sender to the recipient, preventing a
-    * number of deanonymization attacks during the routing process.
-    * It is provided here for your reference, however its accuracy is enforced directly by
-    * [`ChannelManager`] using the values you previously provided to
-    * [`ChannelManager::create_inbound_payment`] or
-    * [`ChannelManager::create_inbound_payment_for_hash`].
-    *
-    * [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
-    * [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
-    * [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
-    */
-   struct LDKThirtyTwoBytes payment_secret;
    /**
     * The value, in thousandths of a satoshi, that this payment is for. Note that you must
     * compare this to the expected value before accepting the payment (as otherwise you are
@@ -5497,16 +5578,10 @@ typedef struct LDKEvent_LDKPaymentReceived_Body {
     */
    uint64_t amt;
    /**
-    * This is the `user_payment_id` which was provided to
-    * [`ChannelManager::create_inbound_payment_for_hash`] or
-    * [`ChannelManager::create_inbound_payment`]. It has no meaning inside of LDK and is
-    * simply copied here. It may be used to correlate PaymentReceived events with invoice
-    * metadata stored elsewhere.
-    *
-    * [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
-    * [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
+    * Information for claiming this received payment, based on whether the purpose of the
+    * payment is to pay an invoice or to send a spontaneous payment.
     */
-   uint64_t user_payment_id;
+   struct LDKPaymentPurpose purpose;
 } LDKEvent_LDKPaymentReceived_Body;
 
 typedef struct LDKEvent_LDKPaymentSent_Body {
@@ -5548,6 +5623,30 @@ typedef struct LDKEvent_LDKSpendableOutputs_Body {
    struct LDKCVec_SpendableOutputDescriptorZ outputs;
 } LDKEvent_LDKSpendableOutputs_Body;
 
+typedef struct LDKEvent_LDKPaymentForwarded_Body {
+   /**
+    * The fee, in milli-satoshis, which was earned as a result of the payment.
+    *
+    * Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
+    * was pending, the amount the next hop claimed will have been rounded down to the nearest
+    * whole satoshi. Thus, the fee calculated here may be higher than expected as we still
+    * claimed the full value in millisatoshis from the source. In this case,
+    * `claim_from_onchain_tx` will be set.
+    *
+    * If the channel which sent us the payment has been force-closed, we will claim the funds
+    * via an on-chain transaction. In that case we do not yet know the on-chain transaction
+    * fees which we will spend and will instead set this to `None`. It is possible duplicate
+    * `PaymentForwarded` events are generated for the same payment iff `fee_earned_msat` is
+    * `None`.
+    */
+   struct LDKCOption_u64Z fee_earned_msat;
+   /**
+    * If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
+    * transaction.
+    */
+   bool claim_from_onchain_tx;
+} LDKEvent_LDKPaymentForwarded_Body;
+
 typedef struct MUST_USE_STRUCT LDKEvent {
    LDKEvent_Tag tag;
    union {
@@ -5557,6 +5656,7 @@ typedef struct MUST_USE_STRUCT LDKEvent {
       LDKEvent_LDKPaymentFailed_Body payment_failed;
       LDKEvent_LDKPendingHTLCsForwardable_Body pending_htl_cs_forwardable;
       LDKEvent_LDKSpendableOutputs_Body spendable_outputs;
+      LDKEvent_LDKPaymentForwarded_Body payment_forwarded;
    };
 } LDKEvent;
 
@@ -8592,6 +8692,8 @@ typedef struct LDKRoutingMessageHandler {
     * starting at the node *after* the provided publickey and including batch_amount entries
     * immediately higher (as defined by <PublicKey as Ord>::cmp) than starting_point.
     * If None is provided for starting_point, we start at the first node.
+    *
+    * Note that starting_point (or a relevant inner pointer) may be NULL or all-0s to represent None
     */
    struct LDKCVec_NodeAnnouncementZ (*get_next_node_announcements)(const void *this_arg, struct LDKPublicKey starting_point, uint8_t batch_amount);
    /**
@@ -8753,11 +8855,11 @@ typedef struct LDKSocketDescriptor {
     */
    uint64_t (*hash)(const void *this_arg);
    /**
-    * Creates a copy of the object pointed to by this_arg, for a copy of this SocketDescriptor.
-    * Note that the ultimate copy of the SocketDescriptor will have all function pointers the same as the original.
-    * May be NULL if no action needs to be taken, the this_arg pointer will be copied into the new SocketDescriptor.
+    * Called, if set, after this SocketDescriptor has been cloned into a duplicate object.
+    * The new SocketDescriptor is provided, and should be mutated as needed to perform a
+    * deep copy of the object pointed to by this_arg or avoid any double-freeing.
     */
-   void *(*clone)(const void *this_arg);
+   void (*cloned)(struct LDKSocketDescriptor *NONNULL_PTR new_SocketDescriptor);
    /**
     * Frees any resources associated with this object given its this_arg pointer.
     * Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
@@ -8941,6 +9043,7 @@ typedef struct MUST_USE_STRUCT LDKFilesystemPersister {
  * then there is a risk of channels force-closing on startup when the manager realizes it's
  * outdated. However, as long as `ChannelMonitor` backups are sound, no funds besides those used
  * for unilateral chain closure fees are at risk.
+ *BackgroundProcessor will immediately stop on drop. It should be stored until shutdown.
  */
 typedef struct MUST_USE_STRUCT LDKBackgroundProcessor {
    /**
@@ -9139,6 +9242,11 @@ struct LDKStr _ldk_c_bindings_get_compiled_version(void);
  */
 void Transaction_free(struct LDKTransaction _res);
 
+/**
+ * Convenience function for constructing a new TxOut
+ */
+struct LDKTxOut TxOut_new(struct LDKCVec_u8Z script_pubkey, uint64_t value);
+
 /**
  * Frees the data pointed to by script_pubkey.
  */
@@ -10074,6 +10182,27 @@ void CResult_NonePaymentSendFailureZ_free(struct LDKCResult_NonePaymentSendFailu
  */
 struct LDKCResult_NonePaymentSendFailureZ CResult_NonePaymentSendFailureZ_clone(const struct LDKCResult_NonePaymentSendFailureZ *NONNULL_PTR orig);
 
+/**
+ * Creates a new CResult_PaymentHashPaymentSendFailureZ in the success state.
+ */
+struct LDKCResult_PaymentHashPaymentSendFailureZ CResult_PaymentHashPaymentSendFailureZ_ok(struct LDKThirtyTwoBytes o);
+
+/**
+ * Creates a new CResult_PaymentHashPaymentSendFailureZ in the error state.
+ */
+struct LDKCResult_PaymentHashPaymentSendFailureZ CResult_PaymentHashPaymentSendFailureZ_err(struct LDKPaymentSendFailure e);
+
+/**
+ * Frees any resources used by the CResult_PaymentHashPaymentSendFailureZ.
+ */
+void CResult_PaymentHashPaymentSendFailureZ_free(struct LDKCResult_PaymentHashPaymentSendFailureZ _res);
+
+/**
+ * Creates a new CResult_PaymentHashPaymentSendFailureZ which has the same data as `orig`
+ * but with all dynamically-allocated buffers duplicated in new buffers.
+ */
+struct LDKCResult_PaymentHashPaymentSendFailureZ CResult_PaymentHashPaymentSendFailureZ_clone(const struct LDKCResult_PaymentHashPaymentSendFailureZ *NONNULL_PTR orig);
+
 /**
  * Frees the buffer pointed to by `data` if `datalen` is non-0.
  */
@@ -11644,6 +11773,26 @@ void CResult_InvoiceSignOrCreationErrorZ_free(struct LDKCResult_InvoiceSignOrCre
  */
 struct LDKCResult_InvoiceSignOrCreationErrorZ CResult_InvoiceSignOrCreationErrorZ_clone(const struct LDKCResult_InvoiceSignOrCreationErrorZ *NONNULL_PTR orig);
 
+/**
+ * Frees any resources used by the PaymentPurpose
+ */
+void PaymentPurpose_free(struct LDKPaymentPurpose this_ptr);
+
+/**
+ * Creates a copy of the PaymentPurpose
+ */
+struct LDKPaymentPurpose PaymentPurpose_clone(const struct LDKPaymentPurpose *NONNULL_PTR orig);
+
+/**
+ * Utility method to constructs a new InvoicePayment-variant PaymentPurpose
+ */
+struct LDKPaymentPurpose PaymentPurpose_invoice_payment(struct LDKThirtyTwoBytes payment_preimage, struct LDKThirtyTwoBytes payment_secret, uint64_t user_payment_id);
+
+/**
+ * Utility method to constructs a new SpontaneousPayment-variant PaymentPurpose
+ */
+struct LDKPaymentPurpose PaymentPurpose_spontaneous_payment(struct LDKThirtyTwoBytes a);
+
 /**
  * Frees any resources used by the Event
  */
@@ -11654,6 +11803,41 @@ void Event_free(struct LDKEvent this_ptr);
  */
 struct LDKEvent Event_clone(const struct LDKEvent *NONNULL_PTR orig);
 
+/**
+ * Utility method to constructs a new FundingGenerationReady-variant Event
+ */
+struct LDKEvent Event_funding_generation_ready(struct LDKThirtyTwoBytes temporary_channel_id, uint64_t channel_value_satoshis, struct LDKCVec_u8Z output_script, uint64_t user_channel_id);
+
+/**
+ * Utility method to constructs a new PaymentReceived-variant Event
+ */
+struct LDKEvent Event_payment_received(struct LDKThirtyTwoBytes payment_hash, uint64_t amt, struct LDKPaymentPurpose purpose);
+
+/**
+ * Utility method to constructs a new PaymentSent-variant Event
+ */
+struct LDKEvent Event_payment_sent(struct LDKThirtyTwoBytes payment_preimage);
+
+/**
+ * Utility method to constructs a new PaymentFailed-variant Event
+ */
+struct LDKEvent Event_payment_failed(struct LDKThirtyTwoBytes payment_hash, bool rejected_by_dest);
+
+/**
+ * Utility method to constructs a new PendingHTLCsForwardable-variant Event
+ */
+struct LDKEvent Event_pending_htlcs_forwardable(uint64_t time_forwardable);
+
+/**
+ * Utility method to constructs a new SpendableOutputs-variant Event
+ */
+struct LDKEvent Event_spendable_outputs(struct LDKCVec_SpendableOutputDescriptorZ outputs);
+
+/**
+ * Utility method to constructs a new PaymentForwarded-variant Event
+ */
+struct LDKEvent Event_payment_forwarded(struct LDKCOption_u64Z fee_earned_msat, bool claim_from_onchain_tx);
+
 /**
  * Serialize the Event object into a byte array which can be read by Event_read
  */
@@ -11669,6 +11853,106 @@ void MessageSendEvent_free(struct LDKMessageSendEvent this_ptr);
  */
 struct LDKMessageSendEvent MessageSendEvent_clone(const struct LDKMessageSendEvent *NONNULL_PTR orig);
 
+/**
+ * Utility method to constructs a new SendAcceptChannel-variant MessageSendEvent
+ */
+struct LDKMessageSendEvent MessageSendEvent_send_accept_channel(struct LDKPublicKey node_id, struct LDKAcceptChannel msg);
+
+/**
+ * Utility method to constructs a new SendOpenChannel-variant MessageSendEvent
+ */
+struct LDKMessageSendEvent MessageSendEvent_send_open_channel(struct LDKPublicKey node_id, struct LDKOpenChannel msg);
+
+/**
+ * Utility method to constructs a new SendFundingCreated-variant MessageSendEvent
+ */
+struct LDKMessageSendEvent MessageSendEvent_send_funding_created(struct LDKPublicKey node_id, struct LDKFundingCreated msg);
+
+/**
+ * Utility method to constructs a new SendFundingSigned-variant MessageSendEvent
+ */
+struct LDKMessageSendEvent MessageSendEvent_send_funding_signed(struct LDKPublicKey node_id, struct LDKFundingSigned msg);
+
+/**
+ * Utility method to constructs a new SendFundingLocked-variant MessageSendEvent
+ */
+struct LDKMessageSendEvent MessageSendEvent_send_funding_locked(struct LDKPublicKey node_id, struct LDKFundingLocked msg);
+
+/**
+ * Utility method to constructs a new SendAnnouncementSignatures-variant MessageSendEvent
+ */
+struct LDKMessageSendEvent MessageSendEvent_send_announcement_signatures(struct LDKPublicKey node_id, struct LDKAnnouncementSignatures msg);
+
+/**
+ * Utility method to constructs a new UpdateHTLCs-variant MessageSendEvent
+ */
+struct LDKMessageSendEvent MessageSendEvent_update_htlcs(struct LDKPublicKey node_id, struct LDKCommitmentUpdate updates);
+
+/**
+ * Utility method to constructs a new SendRevokeAndACK-variant MessageSendEvent
+ */
+struct LDKMessageSendEvent MessageSendEvent_send_revoke_and_ack(struct LDKPublicKey node_id, struct LDKRevokeAndACK msg);
+
+/**
+ * Utility method to constructs a new SendClosingSigned-variant MessageSendEvent
+ */
+struct LDKMessageSendEvent MessageSendEvent_send_closing_signed(struct LDKPublicKey node_id, struct LDKClosingSigned msg);
+
+/**
+ * Utility method to constructs a new SendShutdown-variant MessageSendEvent
+ */
+struct LDKMessageSendEvent MessageSendEvent_send_shutdown(struct LDKPublicKey node_id, struct LDKShutdown msg);
+
+/**
+ * Utility method to constructs a new SendChannelReestablish-variant MessageSendEvent
+ */
+struct LDKMessageSendEvent MessageSendEvent_send_channel_reestablish(struct LDKPublicKey node_id, struct LDKChannelReestablish msg);
+
+/**
+ * Utility method to constructs a new BroadcastChannelAnnouncement-variant MessageSendEvent
+ */
+struct LDKMessageSendEvent MessageSendEvent_broadcast_channel_announcement(struct LDKChannelAnnouncement msg, struct LDKChannelUpdate update_msg);
+
+/**
+ * Utility method to constructs a new BroadcastNodeAnnouncement-variant MessageSendEvent
+ */
+struct LDKMessageSendEvent MessageSendEvent_broadcast_node_announcement(struct LDKNodeAnnouncement msg);
+
+/**
+ * Utility method to constructs a new BroadcastChannelUpdate-variant MessageSendEvent
+ */
+struct LDKMessageSendEvent MessageSendEvent_broadcast_channel_update(struct LDKChannelUpdate msg);
+
+/**
+ * Utility method to constructs a new SendChannelUpdate-variant MessageSendEvent
+ */
+struct LDKMessageSendEvent MessageSendEvent_send_channel_update(struct LDKPublicKey node_id, struct LDKChannelUpdate msg);
+
+/**
+ * Utility method to constructs a new HandleError-variant MessageSendEvent
+ */
+struct LDKMessageSendEvent MessageSendEvent_handle_error(struct LDKPublicKey node_id, struct LDKErrorAction action);
+
+/**
+ * Utility method to constructs a new PaymentFailureNetworkUpdate-variant MessageSendEvent
+ */
+struct LDKMessageSendEvent MessageSendEvent_payment_failure_network_update(struct LDKHTLCFailChannelUpdate update);
+
+/**
+ * Utility method to constructs a new SendChannelRangeQuery-variant MessageSendEvent
+ */
+struct LDKMessageSendEvent MessageSendEvent_send_channel_range_query(struct LDKPublicKey node_id, struct LDKQueryChannelRange msg);
+
+/**
+ * Utility method to constructs a new SendShortIdsQuery-variant MessageSendEvent
+ */
+struct LDKMessageSendEvent MessageSendEvent_send_short_ids_query(struct LDKPublicKey node_id, struct LDKQueryShortChannelIds msg);
+
+/**
+ * Utility method to constructs a new SendReplyChannelRange-variant MessageSendEvent
+ */
+struct LDKMessageSendEvent MessageSendEvent_send_reply_channel_range(struct LDKPublicKey node_id, struct LDKReplyChannelRange msg);
+
 /**
  * Calls the free function if one is set
  */
@@ -11694,6 +11978,31 @@ void APIError_free(struct LDKAPIError this_ptr);
  */
 struct LDKAPIError APIError_clone(const struct LDKAPIError *NONNULL_PTR orig);
 
+/**
+ * Utility method to constructs a new APIMisuseError-variant APIError
+ */
+struct LDKAPIError APIError_apimisuse_error(struct LDKStr err);
+
+/**
+ * Utility method to constructs a new FeeRateTooHigh-variant APIError
+ */
+struct LDKAPIError APIError_fee_rate_too_high(struct LDKStr err, uint32_t feerate);
+
+/**
+ * Utility method to constructs a new RouteError-variant APIError
+ */
+struct LDKAPIError APIError_route_error(struct LDKStr err);
+
+/**
+ * Utility method to constructs a new ChannelUnavailable-variant APIError
+ */
+struct LDKAPIError APIError_channel_unavailable(struct LDKStr err);
+
+/**
+ * Utility method to constructs a new MonitorUpdateFailed-variant APIError
+ */
+struct LDKAPIError APIError_monitor_update_failed(void);
+
 /**
  * Creates a digital signature of a message given a SecretKey, like the node's secret.
  * A receiver knowing the PublicKey (e.g. the node's id) and the message can be sure that the signature was generated by the caller.
@@ -11717,6 +12026,31 @@ bool verify(struct LDKu8slice msg, struct LDKStr sig, struct LDKPublicKey pk);
  */
 enum LDKLevel Level_clone(const enum LDKLevel *NONNULL_PTR orig);
 
+/**
+ * Utility method to constructs a new Trace-variant Level
+ */
+enum LDKLevel Level_trace(void);
+
+/**
+ * Utility method to constructs a new Debug-variant Level
+ */
+enum LDKLevel Level_debug(void);
+
+/**
+ * Utility method to constructs a new Info-variant Level
+ */
+enum LDKLevel Level_info(void);
+
+/**
+ * Utility method to constructs a new Warn-variant Level
+ */
+enum LDKLevel Level_warn(void);
+
+/**
+ * Utility method to constructs a new Error-variant Level
+ */
+enum LDKLevel Level_error(void);
+
 /**
  * Checks if two Levels contain equal inner contents.
  * This ignores pointers and is_owned flags and looks at the values in fields.
@@ -12318,6 +12652,16 @@ MUST_USE_RES uint32_t BestBlock_height(const struct LDKBestBlock *NONNULL_PTR th
  */
 enum LDKAccessError AccessError_clone(const enum LDKAccessError *NONNULL_PTR orig);
 
+/**
+ * Utility method to constructs a new UnknownChain-variant AccessError
+ */
+enum LDKAccessError AccessError_unknown_chain(void);
+
+/**
+ * Utility method to constructs a new UnknownTx-variant AccessError
+ */
+enum LDKAccessError AccessError_unknown_tx(void);
+
 /**
  * Calls the free function if one is set
  */
@@ -12350,11 +12694,15 @@ void WatchedOutput_free(struct LDKWatchedOutput this_obj);
 
 /**
  * First block where the transaction output may have been spent.
+ *
+ * Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
  */
 struct LDKThirtyTwoBytes WatchedOutput_get_block_hash(const struct LDKWatchedOutput *NONNULL_PTR this_ptr);
 
 /**
  * First block where the transaction output may have been spent.
+ *
+ * Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None
  */
 void WatchedOutput_set_block_hash(struct LDKWatchedOutput *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
 
@@ -12403,6 +12751,21 @@ void BroadcasterInterface_free(struct LDKBroadcasterInterface this_ptr);
  */
 enum LDKConfirmationTarget ConfirmationTarget_clone(const enum LDKConfirmationTarget *NONNULL_PTR orig);
 
+/**
+ * Utility method to constructs a new Background-variant ConfirmationTarget
+ */
+enum LDKConfirmationTarget ConfirmationTarget_background(void);
+
+/**
+ * Utility method to constructs a new Normal-variant ConfirmationTarget
+ */
+enum LDKConfirmationTarget ConfirmationTarget_normal(void);
+
+/**
+ * Utility method to constructs a new HighPriority-variant ConfirmationTarget
+ */
+enum LDKConfirmationTarget ConfirmationTarget_high_priority(void);
+
 /**
  * Calls the free function if one is set
  */
@@ -12421,6 +12784,8 @@ void ChainMonitor_free(struct LDKChainMonitor this_obj);
  * pre-filter blocks or only fetch blocks matching a compact filter. Otherwise, clients may
  * always need to fetch full blocks absent another means for determining which blocks contain
  * transactions relevant to the watched channels.
+ *
+ * Note that chain_source (or a relevant inner pointer) may be NULL or all-0s to represent None
  */
 MUST_USE_RES struct LDKChainMonitor ChainMonitor_new(struct LDKFilter *chain_source, struct LDKBroadcasterInterface broadcaster, struct LDKLogger logger, struct LDKFeeEstimator feeest, struct LDKPersist persister);
 
@@ -12503,6 +12868,16 @@ struct LDKCResult_ChannelMonitorUpdateDecodeErrorZ ChannelMonitorUpdate_read(str
  */
 enum LDKChannelMonitorUpdateErr ChannelMonitorUpdateErr_clone(const enum LDKChannelMonitorUpdateErr *NONNULL_PTR orig);
 
+/**
+ * Utility method to constructs a new TemporaryFailure-variant ChannelMonitorUpdateErr
+ */
+enum LDKChannelMonitorUpdateErr ChannelMonitorUpdateErr_temporary_failure(void);
+
+/**
+ * Utility method to constructs a new PermanentFailure-variant ChannelMonitorUpdateErr
+ */
+enum LDKChannelMonitorUpdateErr ChannelMonitorUpdateErr_permanent_failure(void);
+
 /**
  * Frees any resources used by the MonitorUpdateError, if is_owned is set and inner is non-NULL.
  */
@@ -12523,6 +12898,16 @@ void MonitorEvent_free(struct LDKMonitorEvent this_ptr);
  */
 struct LDKMonitorEvent MonitorEvent_clone(const struct LDKMonitorEvent *NONNULL_PTR orig);
 
+/**
+ * Utility method to constructs a new HTLCEvent-variant MonitorEvent
+ */
+struct LDKMonitorEvent MonitorEvent_htlcevent(struct LDKHTLCUpdate a);
+
+/**
+ * Utility method to constructs a new CommitmentTxBroadcasted-variant MonitorEvent
+ */
+struct LDKMonitorEvent MonitorEvent_commitment_tx_broadcasted(struct LDKOutPoint a);
+
 /**
  * Frees any resources used by the HTLCUpdate, if is_owned is set and inner is non-NULL.
  */
@@ -12922,6 +13307,21 @@ void SpendableOutputDescriptor_free(struct LDKSpendableOutputDescriptor this_ptr
  */
 struct LDKSpendableOutputDescriptor SpendableOutputDescriptor_clone(const struct LDKSpendableOutputDescriptor *NONNULL_PTR orig);
 
+/**
+ * Utility method to constructs a new StaticOutput-variant SpendableOutputDescriptor
+ */
+struct LDKSpendableOutputDescriptor SpendableOutputDescriptor_static_output(struct LDKOutPoint outpoint, struct LDKTxOut output);
+
+/**
+ * Utility method to constructs a new DelayedPaymentOutput-variant SpendableOutputDescriptor
+ */
+struct LDKSpendableOutputDescriptor SpendableOutputDescriptor_delayed_payment_output(struct LDKDelayedPaymentOutputDescriptor a);
+
+/**
+ * Utility method to constructs a new StaticPaymentOutput-variant SpendableOutputDescriptor
+ */
+struct LDKSpendableOutputDescriptor SpendableOutputDescriptor_static_payment_output(struct LDKStaticPaymentOutputDescriptor a);
+
 /**
  * Serialize the SpendableOutputDescriptor object into a byte array which can be read by SpendableOutputDescriptor_read
  */
@@ -13305,6 +13705,8 @@ void ChannelDetails_set_counterparty(struct LDKChannelDetails *NONNULL_PTR this_
  *
  * Note that, if this has been set, `channel_id` will be equivalent to
  * `funding_txo.unwrap().to_channel_id()`.
+ *
+ * Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
  */
 struct LDKOutPoint ChannelDetails_get_funding_txo(const struct LDKChannelDetails *NONNULL_PTR this_ptr);
 
@@ -13314,6 +13716,8 @@ struct LDKOutPoint ChannelDetails_get_funding_txo(const struct LDKChannelDetails
  *
  * Note that, if this has been set, `channel_id` will be equivalent to
  * `funding_txo.unwrap().to_channel_id()`.
+ *
+ * Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None
  */
 void ChannelDetails_set_funding_txo(struct LDKChannelDetails *NONNULL_PTR this_ptr, struct LDKOutPoint val);
 
@@ -13555,6 +13959,26 @@ void PaymentSendFailure_free(struct LDKPaymentSendFailure this_ptr);
  */
 struct LDKPaymentSendFailure PaymentSendFailure_clone(const struct LDKPaymentSendFailure *NONNULL_PTR orig);
 
+/**
+ * Utility method to constructs a new ParameterError-variant PaymentSendFailure
+ */
+struct LDKPaymentSendFailure PaymentSendFailure_parameter_error(struct LDKAPIError a);
+
+/**
+ * Utility method to constructs a new PathParameterError-variant PaymentSendFailure
+ */
+struct LDKPaymentSendFailure PaymentSendFailure_path_parameter_error(struct LDKCVec_CResult_NoneAPIErrorZZ a);
+
+/**
+ * Utility method to constructs a new AllFailedRetrySafe-variant PaymentSendFailure
+ */
+struct LDKPaymentSendFailure PaymentSendFailure_all_failed_retry_safe(struct LDKCVec_APIErrorZ a);
+
+/**
+ * Utility method to constructs a new PartialFailure-variant PaymentSendFailure
+ */
+struct LDKPaymentSendFailure PaymentSendFailure_partial_failure(struct LDKCVec_CResult_NoneAPIErrorZZ a);
+
 /**
  * Constructs a new ChannelManager to hold several channels and route between them.
  *
@@ -13594,6 +14018,8 @@ MUST_USE_RES struct LDKUserConfig ChannelManager_get_current_default_configurati
  * Note that we do not check if you are currently connected to the given peer. If no
  * connection is available, the outbound `open_channel` message may fail to send, resulting in
  * the channel eventually being silently forgotten.
+ *
+ * Note that override_config (or a relevant inner pointer) may be NULL or all-0s to represent None
  */
 MUST_USE_RES struct LDKCResult_NoneAPIErrorZ ChannelManager_create_channel(const struct LDKChannelManager *NONNULL_PTR this_arg, struct LDKPublicKey their_network_key, uint64_t channel_value_satoshis, uint64_t push_msat, uint64_t user_id, struct LDKUserConfig override_config);
 
@@ -13674,9 +14100,27 @@ void ChannelManager_force_close_all_channels(const struct LDKChannelManager *NON
  * If a payment_secret *is* provided, we assume that the invoice had the payment_secret feature
  * bit set (either as required or as available). If multiple paths are present in the Route,
  * we assume the invoice had the basic_mpp feature set.
+ *
+ * Note that payment_secret (or a relevant inner pointer) may be NULL or all-0s to represent None
  */
 MUST_USE_RES struct LDKCResult_NonePaymentSendFailureZ ChannelManager_send_payment(const struct LDKChannelManager *NONNULL_PTR this_arg, const struct LDKRoute *NONNULL_PTR route, struct LDKThirtyTwoBytes payment_hash, struct LDKThirtyTwoBytes payment_secret);
 
+/**
+ * Send a spontaneous payment, which is a payment that does not require the recipient to have
+ * generated an invoice. Optionally, you may specify the preimage. If you do choose to specify
+ * the preimage, it must be a cryptographically secure random value that no intermediate node
+ * would be able to guess -- otherwise, an intermediate node may claim the payment and it will
+ * never reach the recipient.
+ *
+ * Similar to regular payments, you MUST NOT reuse a `payment_preimage` value. See
+ * [`send_payment`] for more information about the risks of duplicate preimage usage.
+ *
+ * [`send_payment`]: Self::send_payment
+ *
+ * Note that payment_preimage (or a relevant inner pointer) may be NULL or all-0s to represent None
+ */
+MUST_USE_RES struct LDKCResult_PaymentHashPaymentSendFailureZ ChannelManager_send_spontaneous_payment(const struct LDKChannelManager *NONNULL_PTR this_arg, const struct LDKRoute *NONNULL_PTR route, struct LDKThirtyTwoBytes payment_preimage);
+
 /**
  * Call this upon creation of a funding transaction for the given channel.
  *
@@ -13828,7 +14272,7 @@ MUST_USE_RES struct LDKC2Tuple_PaymentHashPaymentSecretZ ChannelManager_create_i
  * The [`PaymentHash`] (and corresponding [`PaymentPreimage`]) must be globally unique. This
  * method may return an Err if another payment with the same payment_hash is still pending.
  *
- * `user_payment_id` will be provided back in [`PaymentReceived::user_payment_id`] events to
+ * `user_payment_id` will be provided back in [`PaymentPurpose::InvoicePayment::user_payment_id`] events to
  * allow tracking of which events correspond with which calls to this and
  * [`create_inbound_payment`]. `user_payment_id` has no meaning inside of LDK, it is simply
  * copied to events and otherwise ignored. It may be used to correlate PaymentReceived events
@@ -13862,7 +14306,7 @@ MUST_USE_RES struct LDKC2Tuple_PaymentHashPaymentSecretZ ChannelManager_create_i
  *
  * [`create_inbound_payment`]: Self::create_inbound_payment
  * [`PaymentReceived`]: events::Event::PaymentReceived
- * [`PaymentReceived::user_payment_id`]: events::Event::PaymentReceived::user_payment_id
+ * [`PaymentPurpose::InvoicePayment::user_payment_id`]: events::PaymentPurpose::InvoicePayment::user_payment_id
  */
 MUST_USE_RES struct LDKCResult_PaymentSecretAPIErrorZ ChannelManager_create_inbound_payment_for_hash(const struct LDKChannelManager *NONNULL_PTR this_arg, struct LDKThirtyTwoBytes payment_hash, struct LDKCOption_u64Z min_value_msat, uint32_t invoice_expiry_delta_secs, uint64_t user_payment_id);
 
@@ -15148,6 +15592,26 @@ void NetAddress_free(struct LDKNetAddress this_ptr);
  */
 struct LDKNetAddress NetAddress_clone(const struct LDKNetAddress *NONNULL_PTR orig);
 
+/**
+ * Utility method to constructs a new IPv4-variant NetAddress
+ */
+struct LDKNetAddress NetAddress_ipv4(struct LDKFourBytes addr, uint16_t port);
+
+/**
+ * Utility method to constructs a new IPv6-variant NetAddress
+ */
+struct LDKNetAddress NetAddress_ipv6(struct LDKSixteenBytes addr, uint16_t port);
+
+/**
+ * Utility method to constructs a new OnionV2-variant NetAddress
+ */
+struct LDKNetAddress NetAddress_onion_v2(struct LDKTenBytes addr, uint16_t port);
+
+/**
+ * Utility method to constructs a new OnionV3-variant NetAddress
+ */
+struct LDKNetAddress NetAddress_onion_v3(struct LDKThirtyTwoBytes ed25519_pubkey, uint16_t checksum, uint8_t version, uint16_t port);
+
 /**
  * Serialize the NetAddress object into a byte array which can be read by NetAddress_read
  */
@@ -15778,6 +16242,26 @@ void ErrorAction_free(struct LDKErrorAction this_ptr);
  */
 struct LDKErrorAction ErrorAction_clone(const struct LDKErrorAction *NONNULL_PTR orig);
 
+/**
+ * Utility method to constructs a new DisconnectPeer-variant ErrorAction
+ */
+struct LDKErrorAction ErrorAction_disconnect_peer(struct LDKErrorMessage msg);
+
+/**
+ * Utility method to constructs a new IgnoreError-variant ErrorAction
+ */
+struct LDKErrorAction ErrorAction_ignore_error(void);
+
+/**
+ * Utility method to constructs a new IgnoreAndLog-variant ErrorAction
+ */
+struct LDKErrorAction ErrorAction_ignore_and_log(enum LDKLevel a);
+
+/**
+ * Utility method to constructs a new SendErrorMessage-variant ErrorAction
+ */
+struct LDKErrorAction ErrorAction_send_error_message(struct LDKErrorMessage msg);
+
 /**
  * Frees any resources used by the LightningError, if is_owned is set and inner is non-NULL.
  */
@@ -15840,11 +16324,15 @@ void CommitmentUpdate_set_update_fail_malformed_htlcs(struct LDKCommitmentUpdate
 
 /**
  * An update_fee message which should be sent
+ *
+ * Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
  */
 struct LDKUpdateFee CommitmentUpdate_get_update_fee(const struct LDKCommitmentUpdate *NONNULL_PTR this_ptr);
 
 /**
  * An update_fee message which should be sent
+ *
+ * Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None
  */
 void CommitmentUpdate_set_update_fee(struct LDKCommitmentUpdate *NONNULL_PTR this_ptr, struct LDKUpdateFee val);
 
@@ -15878,6 +16366,21 @@ void HTLCFailChannelUpdate_free(struct LDKHTLCFailChannelUpdate this_ptr);
  */
 struct LDKHTLCFailChannelUpdate HTLCFailChannelUpdate_clone(const struct LDKHTLCFailChannelUpdate *NONNULL_PTR orig);
 
+/**
+ * Utility method to constructs a new ChannelUpdateMessage-variant HTLCFailChannelUpdate
+ */
+struct LDKHTLCFailChannelUpdate HTLCFailChannelUpdate_channel_update_message(struct LDKChannelUpdate msg);
+
+/**
+ * Utility method to constructs a new ChannelClosed-variant HTLCFailChannelUpdate
+ */
+struct LDKHTLCFailChannelUpdate HTLCFailChannelUpdate_channel_closed(uint64_t short_channel_id, bool is_permanent);
+
+/**
+ * Utility method to constructs a new NodeFailure-variant HTLCFailChannelUpdate
+ */
+struct LDKHTLCFailChannelUpdate HTLCFailChannelUpdate_node_failure(struct LDKPublicKey node_id, bool is_permanent);
+
 /**
  * Calls the free function if one is set
  */
@@ -16849,22 +17352,30 @@ void ChannelTransactionParameters_set_is_outbound_from_holder(struct LDKChannelT
 /**
  * The late-bound counterparty channel transaction parameters.
  * These parameters are populated at the point in the protocol where the counterparty provides them.
+ *
+ * Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
  */
 struct LDKCounterpartyChannelTransactionParameters ChannelTransactionParameters_get_counterparty_parameters(const struct LDKChannelTransactionParameters *NONNULL_PTR this_ptr);
 
 /**
  * The late-bound counterparty channel transaction parameters.
  * These parameters are populated at the point in the protocol where the counterparty provides them.
+ *
+ * Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None
  */
 void ChannelTransactionParameters_set_counterparty_parameters(struct LDKChannelTransactionParameters *NONNULL_PTR this_ptr, struct LDKCounterpartyChannelTransactionParameters val);
 
 /**
  * The late-bound funding outpoint
+ *
+ * Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
  */
 struct LDKOutPoint ChannelTransactionParameters_get_funding_outpoint(const struct LDKChannelTransactionParameters *NONNULL_PTR this_ptr);
 
 /**
  * The late-bound funding outpoint
+ *
+ * Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None
  */
 void ChannelTransactionParameters_set_funding_outpoint(struct LDKChannelTransactionParameters *NONNULL_PTR this_ptr, struct LDKOutPoint val);
 
@@ -17583,6 +18094,15 @@ bool RouteHintHop_eq(const struct LDKRouteHintHop *NONNULL_PTR a, const struct L
  */
 struct LDKRouteHintHop RouteHintHop_clone(const struct LDKRouteHintHop *NONNULL_PTR orig);
 
+/**
+ * Gets a keysend route from us (payer) to the given target node (payee). This is needed because
+ * keysend payments do not have an invoice from which to pull the payee's supported features, which
+ * makes it tricky to otherwise supply the `payee_features` parameter of `get_route`.
+ *
+ * Note that first_hops (or a relevant inner pointer) may be NULL or all-0s to represent None
+ */
+struct LDKCResult_RouteLightningErrorZ get_keysend_route(struct LDKPublicKey our_node_id, const struct LDKNetworkGraph *NONNULL_PTR network, struct LDKPublicKey payee, struct LDKCVec_ChannelDetailsZ *first_hops, struct LDKCVec_RouteHintZ last_hops, uint64_t final_value_msat, uint32_t final_cltv, struct LDKLogger logger);
+
 /**
  * Gets a route from us (payer) to the given target node (payee).
  *
@@ -17603,6 +18123,9 @@ struct LDKRouteHintHop RouteHintHop_clone(const struct LDKRouteHintHop *NONNULL_
  * The fees on channels from us to next-hops are ignored (as they are assumed to all be
  * equal), however the enabled/disabled bit on such channels as well as the
  * htlc_minimum_msat/htlc_maximum_msat *are* checked as they may change based on the receiving node.
+ *
+ * Note that payee_features (or a relevant inner pointer) may be NULL or all-0s to represent None
+ * Note that first_hops (or a relevant inner pointer) may be NULL or all-0s to represent None
  */
 struct LDKCResult_RouteLightningErrorZ get_route(struct LDKPublicKey our_node_id, const struct LDKNetworkGraph *NONNULL_PTR network, struct LDKPublicKey payee, struct LDKInvoiceFeatures payee_features, struct LDKCVec_ChannelDetailsZ *first_hops, struct LDKCVec_RouteHintZ last_hops, uint64_t final_value_msat, uint32_t final_cltv, struct LDKLogger logger);
 
@@ -17632,12 +18155,16 @@ void NetGraphMsgHandler_free(struct LDKNetGraphMsgHandler this_obj);
  * Chain monitor is used to make sure announced channels exist on-chain,
  * channel data is correct, and that the announcement is signed with
  * channel owners' keys.
+ *
+ * Note that chain_access (or a relevant inner pointer) may be NULL or all-0s to represent None
  */
 MUST_USE_RES struct LDKNetGraphMsgHandler NetGraphMsgHandler_new(struct LDKThirtyTwoBytes genesis_hash, struct LDKAccess *chain_access, struct LDKLogger logger);
 
 /**
  * Creates a new tracker of the actual state of the network of channels and nodes,
  * assuming an existing Network Graph.
+ *
+ * Note that chain_access (or a relevant inner pointer) may be NULL or all-0s to represent None
  */
 MUST_USE_RES struct LDKNetGraphMsgHandler NetGraphMsgHandler_from_net_graph(struct LDKAccess *chain_access, struct LDKLogger logger, struct LDKNetworkGraph network_graph);
 
@@ -17645,6 +18172,8 @@ MUST_USE_RES struct LDKNetGraphMsgHandler NetGraphMsgHandler_from_net_graph(stru
  * Adds a provider used to check new announcements. Does not affect
  * existing announcements unless they are updated.
  * Add, update or remove the provider would replace the current one.
+ *
+ * Note that chain_access (or a relevant inner pointer) may be NULL or all-0s to represent None
  */
 void NetGraphMsgHandler_add_chain_access(struct LDKNetGraphMsgHandler *NONNULL_PTR this_arg, struct LDKAccess *chain_access);
 
@@ -17745,6 +18274,8 @@ void DirectionalChannelInfo_set_fees(struct LDKDirectionalChannelInfo *NONNULL_P
  * Mostly redundant with the data we store in fields explicitly.
  * Everything else is useful only for sending out for initial routing sync.
  * Not stored if contains excess data to prevent DoS.
+ *
+ * Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
  */
 struct LDKChannelUpdate DirectionalChannelInfo_get_last_update_message(const struct LDKDirectionalChannelInfo *NONNULL_PTR this_ptr);
 
@@ -17753,6 +18284,8 @@ struct LDKChannelUpdate DirectionalChannelInfo_get_last_update_message(const str
  * Mostly redundant with the data we store in fields explicitly.
  * Everything else is useful only for sending out for initial routing sync.
  * Not stored if contains excess data to prevent DoS.
+ *
+ * Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None
  */
 void DirectionalChannelInfo_set_last_update_message(struct LDKDirectionalChannelInfo *NONNULL_PTR this_ptr, struct LDKChannelUpdate val);
 
@@ -17803,11 +18336,15 @@ void ChannelInfo_set_node_one(struct LDKChannelInfo *NONNULL_PTR this_ptr, struc
 
 /**
  * Details about the first direction of a channel
+ *
+ * Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
  */
 struct LDKDirectionalChannelInfo ChannelInfo_get_one_to_two(const struct LDKChannelInfo *NONNULL_PTR this_ptr);
 
 /**
  * Details about the first direction of a channel
+ *
+ * Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None
  */
 void ChannelInfo_set_one_to_two(struct LDKChannelInfo *NONNULL_PTR this_ptr, struct LDKDirectionalChannelInfo val);
 
@@ -17823,11 +18360,15 @@ void ChannelInfo_set_node_two(struct LDKChannelInfo *NONNULL_PTR this_ptr, struc
 
 /**
  * Details about the second direction of a channel
+ *
+ * Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
  */
 struct LDKDirectionalChannelInfo ChannelInfo_get_two_to_one(const struct LDKChannelInfo *NONNULL_PTR this_ptr);
 
 /**
  * Details about the second direction of a channel
+ *
+ * Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None
  */
 void ChannelInfo_set_two_to_one(struct LDKChannelInfo *NONNULL_PTR this_ptr, struct LDKDirectionalChannelInfo val);
 
@@ -17846,6 +18387,8 @@ void ChannelInfo_set_capacity_sats(struct LDKChannelInfo *NONNULL_PTR this_ptr,
  * Mostly redundant with the data we store in fields explicitly.
  * Everything else is useful only for sending out for initial routing sync.
  * Not stored if contains excess data to prevent DoS.
+ *
+ * Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
  */
 struct LDKChannelAnnouncement ChannelInfo_get_announcement_message(const struct LDKChannelInfo *NONNULL_PTR this_ptr);
 
@@ -17854,6 +18397,8 @@ struct LDKChannelAnnouncement ChannelInfo_get_announcement_message(const struct
  * Mostly redundant with the data we store in fields explicitly.
  * Everything else is useful only for sending out for initial routing sync.
  * Not stored if contains excess data to prevent DoS.
+ *
+ * Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None
  */
 void ChannelInfo_set_announcement_message(struct LDKChannelInfo *NONNULL_PTR this_ptr, struct LDKChannelAnnouncement val);
 
@@ -17992,6 +18537,8 @@ void NodeAnnouncementInfo_set_addresses(struct LDKNodeAnnouncementInfo *NONNULL_
  * Mostly redundant with the data we store in fields explicitly.
  * Everything else is useful only for sending out for initial routing sync.
  * Not stored if contains excess data to prevent DoS.
+ *
+ * Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
  */
 struct LDKNodeAnnouncement NodeAnnouncementInfo_get_announcement_message(const struct LDKNodeAnnouncementInfo *NONNULL_PTR this_ptr);
 
@@ -18000,6 +18547,8 @@ struct LDKNodeAnnouncement NodeAnnouncementInfo_get_announcement_message(const s
  * Mostly redundant with the data we store in fields explicitly.
  * Everything else is useful only for sending out for initial routing sync.
  * Not stored if contains excess data to prevent DoS.
+ *
+ * Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None
  */
 void NodeAnnouncementInfo_set_announcement_message(struct LDKNodeAnnouncementInfo *NONNULL_PTR this_ptr, struct LDKNodeAnnouncement val);
 
@@ -18037,6 +18586,8 @@ void NodeInfo_set_channels(struct LDKNodeInfo *NONNULL_PTR this_ptr, struct LDKC
  * Lowest fees enabling routing via any of the enabled, known channels to a node.
  * The two fields (flat and proportional fee) are independent,
  * meaning they don't have to refer to the same channel.
+ *
+ * Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
  */
 struct LDKRoutingFees NodeInfo_get_lowest_inbound_channel_fees(const struct LDKNodeInfo *NONNULL_PTR this_ptr);
 
@@ -18044,6 +18595,8 @@ struct LDKRoutingFees NodeInfo_get_lowest_inbound_channel_fees(const struct LDKN
  * Lowest fees enabling routing via any of the enabled, known channels to a node.
  * The two fields (flat and proportional fee) are independent,
  * meaning they don't have to refer to the same channel.
+ *
+ * Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None
  */
 void NodeInfo_set_lowest_inbound_channel_fees(struct LDKNodeInfo *NONNULL_PTR this_ptr, struct LDKRoutingFees val);
 
@@ -18051,6 +18604,8 @@ void NodeInfo_set_lowest_inbound_channel_fees(struct LDKNodeInfo *NONNULL_PTR th
  * More information about a node from node_announcement.
  * Optional because we store a Node entry after learning about it from
  * a channel announcement, but before receiving a node announcement.
+ *
+ * Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
  */
 struct LDKNodeAnnouncementInfo NodeInfo_get_announcement_info(const struct LDKNodeInfo *NONNULL_PTR this_ptr);
 
@@ -18058,6 +18613,8 @@ struct LDKNodeAnnouncementInfo NodeInfo_get_announcement_info(const struct LDKNo
  * More information about a node from node_announcement.
  * Optional because we store a Node entry after learning about it from
  * a channel announcement, but before receiving a node announcement.
+ *
+ * Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None
  */
 void NodeInfo_set_announcement_info(struct LDKNodeInfo *NONNULL_PTR this_ptr, struct LDKNodeAnnouncementInfo val);
 
@@ -18123,6 +18680,8 @@ MUST_USE_RES struct LDKCResult_NoneLightningErrorZ NetworkGraph_update_node_from
  *
  * If a `chain::Access` object is provided via `chain_access`, it will be called to verify
  * the corresponding UTXO exists on chain and is correctly-formatted.
+ *
+ * Note that chain_access (or a relevant inner pointer) may be NULL or all-0s to represent None
  */
 MUST_USE_RES struct LDKCResult_NoneLightningErrorZ NetworkGraph_update_channel_from_announcement(struct LDKNetworkGraph *NONNULL_PTR this_arg, const struct LDKChannelAnnouncement *NONNULL_PTR msg, struct LDKAccess *chain_access);
 
@@ -18133,6 +18692,8 @@ MUST_USE_RES struct LDKCResult_NoneLightningErrorZ NetworkGraph_update_channel_f
  *
  * If a `chain::Access` object is provided via `chain_access`, it will be called to verify
  * the corresponding UTXO exists on chain and is correctly-formatted.
+ *
+ * Note that chain_access (or a relevant inner pointer) may be NULL or all-0s to represent None
  */
 MUST_USE_RES struct LDKCResult_NoneLightningErrorZ NetworkGraph_update_channel_from_unsigned_announcement(struct LDKNetworkGraph *NONNULL_PTR this_arg, const struct LDKUnsignedChannelAnnouncement *NONNULL_PTR msg, struct LDKAccess *chain_access);
 
@@ -18205,21 +18766,25 @@ void BackgroundProcessor_free(struct LDKBackgroundProcessor this_obj);
 void ChannelManagerPersister_free(struct LDKChannelManagerPersister this_ptr);
 
 /**
- * Start a background thread that takes care of responsibilities enumerated in the top-level
- * documentation.
+ * Start a background thread that takes care of responsibilities enumerated in the [top-level
+ * documentation].
+ *
+ * The thread runs indefinitely unless the object is dropped, [`stop`] is called, or
+ * `persist_manager` returns an error. In case of an error, the error is retrieved by calling
+ * either [`join`] or [`stop`].
  *
- * If `persist_manager` returns an error, then this thread will return said error (and
- * `start()` will need to be called again to restart the `BackgroundProcessor`). Users should
- * wait on [`thread_handle`]'s `join()` method to be able to tell if and when an error is
- * returned, or implement `persist_manager` such that an error is never returned to the
- * `BackgroundProcessor`
+ * Typically, users should either implement [`ChannelManagerPersister`] to never return an
+ * error or call [`join`] and handle any error that may arise. For the latter case, the
+ * `BackgroundProcessor` must be restarted by calling `start` again after handling the error.
  *
  * `persist_manager` is responsible for writing out the [`ChannelManager`] to disk, and/or
  * uploading to one or more backup services. See [`ChannelManager::write`] for writing out a
  * [`ChannelManager`]. See [`FilesystemPersister::persist_manager`] for Rust-Lightning's
  * provided implementation.
  *
- * [`thread_handle`]: BackgroundProcessor::thread_handle
+ * [top-level documentation]: Self
+ * [`join`]: Self::join
+ * [`stop`]: Self::stop
  * [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
  * [`ChannelManager::write`]: lightning::ln::channelmanager::ChannelManager#impl-Writeable
  * [`FilesystemPersister::persist_manager`]: lightning_persister::FilesystemPersister::persist_manager
@@ -18227,7 +18792,28 @@ void ChannelManagerPersister_free(struct LDKChannelManagerPersister this_ptr);
 MUST_USE_RES struct LDKBackgroundProcessor BackgroundProcessor_start(struct LDKChannelManagerPersister persister, struct LDKEventHandler event_handler, const struct LDKChainMonitor *NONNULL_PTR chain_monitor, const struct LDKChannelManager *NONNULL_PTR channel_manager, const struct LDKPeerManager *NONNULL_PTR peer_manager, struct LDKLogger logger);
 
 /**
- * Stop `BackgroundProcessor`'s thread.
+ * Join `BackgroundProcessor`'s thread, returning any error that occurred while persisting
+ * [`ChannelManager`].
+ *
+ * # Panics
+ *
+ * This function panics if the background thread has panicked such as while persisting or
+ * handling events.
+ *
+ * [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
+ */
+MUST_USE_RES struct LDKCResult_NoneErrorZ BackgroundProcessor_join(struct LDKBackgroundProcessor this_arg);
+
+/**
+ * Stop `BackgroundProcessor`'s thread, returning any error that occurred while persisting
+ * [`ChannelManager`].
+ *
+ * # Panics
+ *
+ * This function panics if the background thread has panicked such as while persisting or
+ * handling events.
+ *
+ * [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
  */
 MUST_USE_RES struct LDKCResult_NoneErrorZ BackgroundProcessor_stop(struct LDKBackgroundProcessor this_arg);
 
@@ -18358,6 +18944,26 @@ struct LDKPositiveTimestamp PositiveTimestamp_clone(const struct LDKPositiveTime
  */
 enum LDKSiPrefix SiPrefix_clone(const enum LDKSiPrefix *NONNULL_PTR orig);
 
+/**
+ * Utility method to constructs a new Milli-variant SiPrefix
+ */
+enum LDKSiPrefix SiPrefix_milli(void);
+
+/**
+ * Utility method to constructs a new Micro-variant SiPrefix
+ */
+enum LDKSiPrefix SiPrefix_micro(void);
+
+/**
+ * Utility method to constructs a new Nano-variant SiPrefix
+ */
+enum LDKSiPrefix SiPrefix_nano(void);
+
+/**
+ * Utility method to constructs a new Pico-variant SiPrefix
+ */
+enum LDKSiPrefix SiPrefix_pico(void);
+
 /**
  * Checks if two SiPrefixs contain equal inner contents.
  * This ignores pointers and is_owned flags and looks at the values in fields.
@@ -18375,6 +18981,31 @@ MUST_USE_RES uint64_t SiPrefix_multiplier(const enum LDKSiPrefix *NONNULL_PTR th
  */
 enum LDKCurrency Currency_clone(const enum LDKCurrency *NONNULL_PTR orig);
 
+/**
+ * Utility method to constructs a new Bitcoin-variant Currency
+ */
+enum LDKCurrency Currency_bitcoin(void);
+
+/**
+ * Utility method to constructs a new BitcoinTestnet-variant Currency
+ */
+enum LDKCurrency Currency_bitcoin_testnet(void);
+
+/**
+ * Utility method to constructs a new Regtest-variant Currency
+ */
+enum LDKCurrency Currency_regtest(void);
+
+/**
+ * Utility method to constructs a new Simnet-variant Currency
+ */
+enum LDKCurrency Currency_simnet(void);
+
+/**
+ * Utility method to constructs a new Signet-variant Currency
+ */
+enum LDKCurrency Currency_signet(void);
+
 /**
  * Checks if two Currencys contain equal inner contents.
  * This ignores pointers and is_owned flags and looks at the values in fields.
@@ -18476,6 +19107,21 @@ void Fallback_free(struct LDKFallback this_ptr);
  */
 struct LDKFallback Fallback_clone(const struct LDKFallback *NONNULL_PTR orig);
 
+/**
+ * Utility method to constructs a new SegWitProgram-variant Fallback
+ */
+struct LDKFallback Fallback_seg_wit_program(struct LDKu5 version, struct LDKCVec_u8Z program);
+
+/**
+ * Utility method to constructs a new PubKeyHash-variant Fallback
+ */
+struct LDKFallback Fallback_pub_key_hash(struct LDKTwentyBytes a);
+
+/**
+ * Utility method to constructs a new ScriptHash-variant Fallback
+ */
+struct LDKFallback Fallback_script_hash(struct LDKTwentyBytes a);
+
 /**
  * Checks if two Fallbacks contain equal inner contents.
  * This ignores pointers and is_owned flags and looks at the values in fields.
@@ -18555,20 +19201,52 @@ MUST_USE_RES bool SignedRawInvoice_check_signature(const struct LDKSignedRawInvo
  */
 MUST_USE_RES struct LDKThirtyTwoBytes RawInvoice_hash(const struct LDKRawInvoice *NONNULL_PTR this_arg);
 
+/**
+ *
+ * Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
+ */
 MUST_USE_RES struct LDKSha256 RawInvoice_payment_hash(const struct LDKRawInvoice *NONNULL_PTR this_arg);
 
+/**
+ *
+ * Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
+ */
 MUST_USE_RES struct LDKDescription RawInvoice_description(const struct LDKRawInvoice *NONNULL_PTR this_arg);
 
+/**
+ *
+ * Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
+ */
 MUST_USE_RES struct LDKPayeePubKey RawInvoice_payee_pub_key(const struct LDKRawInvoice *NONNULL_PTR this_arg);
 
+/**
+ *
+ * Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
+ */
 MUST_USE_RES struct LDKSha256 RawInvoice_description_hash(const struct LDKRawInvoice *NONNULL_PTR this_arg);
 
+/**
+ *
+ * Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
+ */
 MUST_USE_RES struct LDKExpiryTime RawInvoice_expiry_time(const struct LDKRawInvoice *NONNULL_PTR this_arg);
 
+/**
+ *
+ * Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
+ */
 MUST_USE_RES struct LDKMinFinalCltvExpiry RawInvoice_min_final_cltv_expiry(const struct LDKRawInvoice *NONNULL_PTR this_arg);
 
+/**
+ *
+ * Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
+ */
 MUST_USE_RES struct LDKThirtyTwoBytes RawInvoice_payment_secret(const struct LDKRawInvoice *NONNULL_PTR this_arg);
 
+/**
+ *
+ * Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
+ */
 MUST_USE_RES struct LDKInvoiceFeatures RawInvoice_features(const struct LDKRawInvoice *NONNULL_PTR this_arg);
 
 MUST_USE_RES struct LDKCVec_PrivateRouteZ RawInvoice_private_routes(const struct LDKRawInvoice *NONNULL_PTR this_arg);
@@ -18640,16 +19318,22 @@ MUST_USE_RES const uint8_t (*Invoice_payment_hash(const struct LDKInvoice *NONNU
 
 /**
  * Get the payee's public key if one was included in the invoice
+ *
+ * Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
  */
 MUST_USE_RES struct LDKPublicKey Invoice_payee_pub_key(const struct LDKInvoice *NONNULL_PTR this_arg);
 
 /**
  * Get the payment secret if one was included in the invoice
+ *
+ * Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
  */
 MUST_USE_RES struct LDKThirtyTwoBytes Invoice_payment_secret(const struct LDKInvoice *NONNULL_PTR this_arg);
 
 /**
  * Get the invoice features if they were included in the invoice
+ *
+ * Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
  */
 MUST_USE_RES struct LDKInvoiceFeatures Invoice_features(const struct LDKInvoice *NONNULL_PTR this_arg);
 
@@ -18741,6 +19425,26 @@ MUST_USE_RES struct LDKRouteHint PrivateRoute_into_inner(struct LDKPrivateRoute
  */
 enum LDKCreationError CreationError_clone(const enum LDKCreationError *NONNULL_PTR orig);
 
+/**
+ * Utility method to constructs a new DescriptionTooLong-variant CreationError
+ */
+enum LDKCreationError CreationError_description_too_long(void);
+
+/**
+ * Utility method to constructs a new RouteTooLong-variant CreationError
+ */
+enum LDKCreationError CreationError_route_too_long(void);
+
+/**
+ * Utility method to constructs a new TimestampOutOfBounds-variant CreationError
+ */
+enum LDKCreationError CreationError_timestamp_out_of_bounds(void);
+
+/**
+ * Utility method to constructs a new ExpiryTimeOutOfBounds-variant CreationError
+ */
+enum LDKCreationError CreationError_expiry_time_out_of_bounds(void);
+
 /**
  * Checks if two CreationErrors contain equal inner contents.
  * This ignores pointers and is_owned flags and looks at the values in fields.
@@ -18757,6 +19461,46 @@ struct LDKStr CreationError_to_str(const enum LDKCreationError *NONNULL_PTR o);
  */
 enum LDKSemanticError SemanticError_clone(const enum LDKSemanticError *NONNULL_PTR orig);
 
+/**
+ * Utility method to constructs a new NoPaymentHash-variant SemanticError
+ */
+enum LDKSemanticError SemanticError_no_payment_hash(void);
+
+/**
+ * Utility method to constructs a new MultiplePaymentHashes-variant SemanticError
+ */
+enum LDKSemanticError SemanticError_multiple_payment_hashes(void);
+
+/**
+ * Utility method to constructs a new NoDescription-variant SemanticError
+ */
+enum LDKSemanticError SemanticError_no_description(void);
+
+/**
+ * Utility method to constructs a new MultipleDescriptions-variant SemanticError
+ */
+enum LDKSemanticError SemanticError_multiple_descriptions(void);
+
+/**
+ * Utility method to constructs a new MultiplePaymentSecrets-variant SemanticError
+ */
+enum LDKSemanticError SemanticError_multiple_payment_secrets(void);
+
+/**
+ * Utility method to constructs a new InvalidFeatures-variant SemanticError
+ */
+enum LDKSemanticError SemanticError_invalid_features(void);
+
+/**
+ * Utility method to constructs a new InvalidRecoveryId-variant SemanticError
+ */
+enum LDKSemanticError SemanticError_invalid_recovery_id(void);
+
+/**
+ * Utility method to constructs a new InvalidSignature-variant SemanticError
+ */
+enum LDKSemanticError SemanticError_invalid_signature(void);
+
 /**
  * Checks if two SemanticErrors contain equal inner contents.
  * This ignores pointers and is_owned flags and looks at the values in fields.
@@ -18778,6 +19522,16 @@ void SignOrCreationError_free(struct LDKSignOrCreationError this_ptr);
  */
 struct LDKSignOrCreationError SignOrCreationError_clone(const struct LDKSignOrCreationError *NONNULL_PTR orig);
 
+/**
+ * Utility method to constructs a new SignError-variant SignOrCreationError
+ */
+struct LDKSignOrCreationError SignOrCreationError_sign_error(void);
+
+/**
+ * Utility method to constructs a new CreationError-variant SignOrCreationError
+ */
+struct LDKSignOrCreationError SignOrCreationError_creation_error(enum LDKCreationError a);
+
 /**
  * Checks if two SignOrCreationErrors contain equal inner contents.
  * This ignores pointers and is_owned flags and looks at the values in fields.
@@ -18835,4 +19589,4 @@ struct LDKStr SiPrefix_to_str(const enum LDKSiPrefix *NONNULL_PTR o);
 
 #endif /* LDK_C_BINDINGS_H */
 
-#include <ldk_ver.h>
+#include "ldk_ver.h"
index e59512b0c400aae4cccf072acec4191b65cc0926..8d5318643a4ad7cfbe93133efc90c92551e5cfa2 100644 (file)
@@ -1,5 +1,298 @@
 #include <string.h>
 namespace LDK {
+// Forward declarations
+class TxCreationKeys;
+class ChannelPublicKeys;
+class HTLCOutputInCommitment;
+class ChannelTransactionParameters;
+class CounterpartyChannelTransactionParameters;
+class DirectedChannelTransactionParameters;
+class HolderCommitmentTransaction;
+class BuiltCommitmentTransaction;
+class CommitmentTransaction;
+class TrustedCommitmentTransaction;
+class BackgroundProcessor;
+class ChannelManagerPersister;
+class RouteHop;
+class Route;
+class RouteHint;
+class RouteHintHop;
+class BroadcasterInterface;
+class ConfirmationTarget;
+class FeeEstimator;
+class BestBlock;
+class AccessError;
+class Access;
+class Listen;
+class Confirm;
+class Watch;
+class Filter;
+class WatchedOutput;
+class PaymentPurpose;
+class Event;
+class MessageSendEvent;
+class MessageSendEventsProvider;
+class EventsProvider;
+class EventHandler;
+class InitFeatures;
+class NodeFeatures;
+class ChannelFeatures;
+class InvoiceFeatures;
+class DelayedPaymentOutputDescriptor;
+class StaticPaymentOutputDescriptor;
+class SpendableOutputDescriptor;
+class BaseSign;
+class Sign;
+class KeysInterface;
+class InMemorySigner;
+class KeysManager;
+class FilesystemPersister;
+class ChannelManager;
+class ChainParameters;
+class ChannelCounterparty;
+class ChannelDetails;
+class PaymentSendFailure;
+class ChannelManagerReadArgs;
+class ChannelHandshakeConfig;
+class ChannelHandshakeLimits;
+class ChannelConfig;
+class UserConfig;
+class APIError;
+class OutPoint;
+class Invoice;
+class SignedRawInvoice;
+class RawInvoice;
+class RawDataPart;
+class PositiveTimestamp;
+class SiPrefix;
+class Currency;
+class Sha256;
+class Description;
+class PayeePubKey;
+class ExpiryTime;
+class MinFinalCltvExpiry;
+class Fallback;
+class InvoiceSignature;
+class PrivateRoute;
+class CreationError;
+class SemanticError;
+class SignOrCreationError;
+class ChannelMonitorUpdate;
+class ChannelMonitorUpdateErr;
+class MonitorUpdateError;
+class MonitorEvent;
+class HTLCUpdate;
+class ChannelMonitor;
+class Persist;
+class IgnoringMessageHandler;
+class ErroringMessageHandler;
+class MessageHandler;
+class SocketDescriptor;
+class PeerHandleError;
+class PeerManager;
+class NetworkGraph;
+class LockedNetworkGraph;
+class NetGraphMsgHandler;
+class DirectionalChannelInfo;
+class ChannelInfo;
+class RoutingFees;
+class NodeAnnouncementInfo;
+class NodeInfo;
+class DecodeError;
+class Init;
+class ErrorMessage;
+class Ping;
+class Pong;
+class OpenChannel;
+class AcceptChannel;
+class FundingCreated;
+class FundingSigned;
+class FundingLocked;
+class Shutdown;
+class ClosingSigned;
+class UpdateAddHTLC;
+class UpdateFulfillHTLC;
+class UpdateFailHTLC;
+class UpdateFailMalformedHTLC;
+class CommitmentSigned;
+class RevokeAndACK;
+class UpdateFee;
+class DataLossProtect;
+class ChannelReestablish;
+class AnnouncementSignatures;
+class NetAddress;
+class UnsignedNodeAnnouncement;
+class NodeAnnouncement;
+class UnsignedChannelAnnouncement;
+class ChannelAnnouncement;
+class UnsignedChannelUpdate;
+class ChannelUpdate;
+class QueryChannelRange;
+class ReplyChannelRange;
+class QueryShortChannelIds;
+class ReplyShortChannelIdsEnd;
+class GossipTimestampFilter;
+class ErrorAction;
+class LightningError;
+class CommitmentUpdate;
+class HTLCFailChannelUpdate;
+class ChannelMessageHandler;
+class RoutingMessageHandler;
+class Level;
+class Logger;
+class ChainMonitor;
+class CVec_SpendableOutputDescriptorZ;
+class CResult_CVec_C2Tuple_BlockHashChannelMonitorZZErrorZ;
+class CVec_C2Tuple_TxidCVec_C2Tuple_u32ScriptZZZZ;
+class CResult_HTLCUpdateDecodeErrorZ;
+class C2Tuple_SignatureCVec_SignatureZZ;
+class CVec_C2Tuple_u32TxOutZZ;
+class CResult_ChannelInfoDecodeErrorZ;
+class CResult_FundingCreatedDecodeErrorZ;
+class CResult_ChannelAnnouncementDecodeErrorZ;
+class CResult_PositiveTimestampCreationErrorZ;
+class CResult_CVec_u8ZPeerHandleErrorZ;
+class CResult_InvoiceFeaturesDecodeErrorZ;
+class CResult_ChannelMonitorUpdateDecodeErrorZ;
+class COption_u64Z;
+class CResult_TxOutAccessErrorZ;
+class CResult_NetAddressDecodeErrorZ;
+class CResult_UnsignedNodeAnnouncementDecodeErrorZ;
+class CResult_ReplyChannelRangeDecodeErrorZ;
+class CResult_ChannelReestablishDecodeErrorZ;
+class CResult_GossipTimestampFilterDecodeErrorZ;
+class CResult_InvoiceSignOrCreationErrorZ;
+class CResult_CommitmentSignedDecodeErrorZ;
+class CVec_UpdateAddHTLCZ;
+class COption_u32Z;
+class CResult_InitFeaturesDecodeErrorZ;
+class CResult_StaticPaymentOutputDescriptorDecodeErrorZ;
+class CResult_CommitmentTransactionDecodeErrorZ;
+class COption_C2Tuple_usizeTransactionZZ;
+class CResult_TransactionNoneZ;
+class CResult_SignedRawInvoiceNoneZ;
+class CResult_ExpiryTimeCreationErrorZ;
+class CResult_PingDecodeErrorZ;
+class CVec_TransactionOutputsZ;
+class CResult_ErrorMessageDecodeErrorZ;
+class CResult_OpenChannelDecodeErrorZ;
+class CVec_CVec_u8ZZ;
+class CResult_SecretKeyErrorZ;
+class CResult_InvoiceNoneZ;
+class CResult_QueryChannelRangeDecodeErrorZ;
+class C2Tuple_usizeTransactionZ;
+class CResult_TxCreationKeysDecodeErrorZ;
+class CResult_ChannelFeaturesDecodeErrorZ;
+class CVec_ChannelMonitorZ;
+class CVec_TransactionZ;
+class CResult_UpdateFeeDecodeErrorZ;
+class CResult_RouteHopDecodeErrorZ;
+class CResult_NodeAnnouncementDecodeErrorZ;
+class CResult_HTLCOutputInCommitmentDecodeErrorZ;
+class CResult_boolLightningErrorZ;
+class CResult_TxCreationKeysErrorZ;
+class C2Tuple_BlockHashChannelMonitorZ;
+class CResult_FundingSignedDecodeErrorZ;
+class CResult_RecoverableSignatureNoneZ;
+class CResult_NodeAnnouncementInfoDecodeErrorZ;
+class CResult_NetAddressu8Z;
+class CVec_UpdateFailMalformedHTLCZ;
+class C3Tuple_RawInvoice_u832InvoiceSignatureZ;
+class CResult_NetworkGraphDecodeErrorZ;
+class CVec_RouteHopZ;
+class CVec_C2Tuple_BlockHashChannelMonitorZZ;
+class CResult_NonePaymentSendFailureZ;
+class CResult_RouteLightningErrorZ;
+class CResult_ChannelPublicKeysDecodeErrorZ;
+class CVec_u8Z;
+class CResult_NodeInfoDecodeErrorZ;
+class CResult_ClosingSignedDecodeErrorZ;
+class CResult_HolderCommitmentTransactionDecodeErrorZ;
+class CVec_CResult_NoneAPIErrorZZ;
+class CResult_SignatureNoneZ;
+class C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ;
+class CResult_InitDecodeErrorZ;
+class CResult_OutPointDecodeErrorZ;
+class CVec_ChannelDetailsZ;
+class CResult_SignDecodeErrorZ;
+class CVec_MessageSendEventZ;
+class C2Tuple_OutPointScriptZ;
+class CResult_UpdateFailMalformedHTLCDecodeErrorZ;
+class CVec_NodeAnnouncementZ;
+class CResult_UnsignedChannelAnnouncementDecodeErrorZ;
+class CVec_TxidZ;
+class CResult_NoneMonitorUpdateErrorZ;
+class CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ;
+class CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ;
+class CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ;
+class CResult_CVec_CVec_u8ZZNoneZ;
+class C2Tuple_PaymentHashPaymentSecretZ;
+class CResult_AcceptChannelDecodeErrorZ;
+class C2Tuple_BlockHashChannelManagerZ;
+class CResult_ChannelTransactionParametersDecodeErrorZ;
+class CResult_PongDecodeErrorZ;
+class CVec_SignatureZ;
+class CVec_u64Z;
+class CResult_DelayedPaymentOutputDescriptorDecodeErrorZ;
+class CResult_StringErrorZ;
+class CResult_NoneErrorZ;
+class C2Tuple_TxidCVec_C2Tuple_u32ScriptZZZ;
+class CVec_RouteHintZ;
+class COption_u16Z;
+class CVec_CVec_RouteHopZZ;
+class CResult_TrustedCommitmentTransactionNoneZ;
+class CResult_NoneLightningErrorZ;
+class CResult_NonePeerHandleErrorZ;
+class CResult_CVec_SignatureZNoneZ;
+class CResult_DescriptionCreationErrorZ;
+class CResult_RoutingFeesDecodeErrorZ;
+class CResult_PayeePubKeyErrorZ;
+class CResult_QueryShortChannelIdsDecodeErrorZ;
+class CResult_InvoiceSemanticErrorZ;
+class CResult_UpdateAddHTLCDecodeErrorZ;
+class CResult_NoneAPIErrorZ;
+class CResult_CounterpartyChannelTransactionParametersDecodeErrorZ;
+class CVec_NetAddressZ;
+class CVec_C2Tuple_usizeTransactionZZ;
+class CVec_PublicKeyZ;
+class CResult_DirectionalChannelInfoDecodeErrorZ;
+class C2Tuple_u32TxOutZ;
+class CResult_UpdateFailHTLCDecodeErrorZ;
+class CResult_ChannelConfigDecodeErrorZ;
+class CVec_PrivateRouteZ;
+class CResult_SpendableOutputDescriptorDecodeErrorZ;
+class CResult_RevokeAndACKDecodeErrorZ;
+class CResult_UnsignedChannelUpdateDecodeErrorZ;
+class CResult_ShutdownDecodeErrorZ;
+class CVec_EventZ;
+class CResult_NoneSemanticErrorZ;
+class CVec_MonitorEventZ;
+class CVec_C2Tuple_u32ScriptZZ;
+class CResult_NoneChannelMonitorUpdateErrZ;
+class CResult_PaymentHashPaymentSendFailureZ;
+class CResult_SiPrefixNoneZ;
+class CResult_PublicKeyErrorZ;
+class C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ;
+class CResult_PrivateRouteCreationErrorZ;
+class CResult_boolPeerHandleErrorZ;
+class CResult_ChannelUpdateDecodeErrorZ;
+class CVec_APIErrorZ;
+class CVec_UpdateFulfillHTLCZ;
+class CResult_AnnouncementSignaturesDecodeErrorZ;
+class CResult_UpdateFulfillHTLCDecodeErrorZ;
+class CResult_NodeFeaturesDecodeErrorZ;
+class CResult_InMemorySignerDecodeErrorZ;
+class CResult_PaymentSecretAPIErrorZ;
+class C2Tuple_u32ScriptZ;
+class CResult_CResult_NetAddressu8ZDecodeErrorZ;
+class CResult_ReplyShortChannelIdsEndDecodeErrorZ;
+class CResult_RouteDecodeErrorZ;
+class CResult_BuiltCommitmentTransactionDecodeErrorZ;
+class CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ;
+class CVec_TxOutZ;
+class CVec_UpdateFailHTLCZ;
+class CResult_FundingLockedDecodeErrorZ;
+
 class TxCreationKeys {
 private:
        LDKTxCreationKeys self;
@@ -179,6 +472,13 @@ public:
        LDKChannelManagerPersister* operator ->() { return &self; }
        const LDKChannelManagerPersister* operator &() const { return &self; }
        const LDKChannelManagerPersister* operator ->() const { return &self; }
+       /**
+        *  Persist the given [`ChannelManager`] to disk, returning an error if persistence failed
+        *  (which will cause the [`BackgroundProcessor`] which called this method to exit.
+        * 
+        *  [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
+        */
+       inline LDK::CResult_NoneErrorZ persist_manager(const struct LDKChannelManager *NONNULL_PTR channel_manager);
 };
 class RouteHop {
 private:
@@ -254,6 +554,10 @@ public:
        LDKBroadcasterInterface* operator ->() { return &self; }
        const LDKBroadcasterInterface* operator &() const { return &self; }
        const LDKBroadcasterInterface* operator ->() const { return &self; }
+       /**
+        *  Sends a transaction out to (hopefully) be mined.
+        */
+       inline void broadcast_transaction(struct LDKTransaction tx);
 };
 class ConfirmationTarget {
 private:
@@ -283,6 +587,17 @@ public:
        LDKFeeEstimator* operator ->() { return &self; }
        const LDKFeeEstimator* operator &() const { return &self; }
        const LDKFeeEstimator* operator ->() const { return &self; }
+       /**
+        *  Gets estimated satoshis of fee required per 1000 Weight-Units.
+        * 
+        *  Must be no smaller than 253 (ie 1 satoshi-per-byte rounded up to ensure later round-downs
+        *  don't put us below 1 satoshi-per-byte).
+        * 
+        *  This translates to:
+        *   * satoshis-per-byte * 250
+        *   * ceil(satoshis-per-kbyte / 4)
+        */
+       inline uint32_t get_est_sat_per_1000_weight(enum LDKConfirmationTarget confirmation_target);
 };
 class BestBlock {
 private:
@@ -327,6 +642,14 @@ public:
        LDKAccess* operator ->() { return &self; }
        const LDKAccess* operator &() const { return &self; }
        const LDKAccess* operator ->() const { return &self; }
+       /**
+        *  Returns the transaction output of a funding transaction encoded by [`short_channel_id`].
+        *  Returns an error if `genesis_hash` is for a different chain or if such a transaction output
+        *  is unknown.
+        * 
+        *  [`short_channel_id`]: https://github.com/lightningnetwork/lightning-rfc/blob/master/07-routing-gossip.md#definition-of-short_channel_id
+        */
+       inline LDK::CResult_TxOutAccessErrorZ get_utxo(const uint8_t (*genesis_hash)[32], uint64_t short_channel_id);
 };
 class Listen {
 private:
@@ -342,6 +665,14 @@ public:
        LDKListen* operator ->() { return &self; }
        const LDKListen* operator &() const { return &self; }
        const LDKListen* operator ->() const { return &self; }
+       /**
+        *  Notifies the listener that a block was added at the given height.
+        */
+       inline void block_connected(struct LDKu8slice block, uint32_t height);
+       /**
+        *  Notifies the listener that a block was removed at the given height.
+        */
+       inline void block_disconnected(const uint8_t (*header)[80], uint32_t height);
 };
 class Confirm {
 private:
@@ -357,6 +688,56 @@ public:
        LDKConfirm* operator ->() { return &self; }
        const LDKConfirm* operator &() const { return &self; }
        const LDKConfirm* operator ->() const { return &self; }
+       /**
+        *  Processes transactions confirmed in a block with a given header and height.
+        * 
+        *  Should be called for any transactions registered by [`Filter::register_tx`] or any
+        *  transactions spending an output registered by [`Filter::register_output`]. Such transactions
+        *  appearing in the same block do not need to be included in the same call; instead, multiple
+        *  calls with additional transactions may be made so long as they are made in [chain order].
+        * 
+        *  May be called before or after [`best_block_updated`] for the corresponding block. However,
+        *  in the event of a chain reorganization, it must not be called with a `header` that is no
+        *  longer in the chain as of the last call to [`best_block_updated`].
+        * 
+        *  [chain order]: Confirm#Order
+        *  [`best_block_updated`]: Self::best_block_updated
+        */
+       inline void transactions_confirmed(const uint8_t (*header)[80], struct LDKCVec_C2Tuple_usizeTransactionZZ txdata, uint32_t height);
+       /**
+        *  Processes a transaction that is no longer confirmed as result of a chain reorganization.
+        * 
+        *  Should be called for any transaction returned by [`get_relevant_txids`] if it has been
+        *  reorganized out of the best chain. Once called, the given transaction should not be returned
+        *  by [`get_relevant_txids`] unless it has been reconfirmed via [`transactions_confirmed`].
+        * 
+        *  [`get_relevant_txids`]: Self::get_relevant_txids
+        *  [`transactions_confirmed`]: Self::transactions_confirmed
+        */
+       inline void transaction_unconfirmed(const uint8_t (*txid)[32]);
+       /**
+        *  Processes an update to the best header connected at the given height.
+        * 
+        *  Should be called when a new header is available but may be skipped for intermediary blocks
+        *  if they become available at the same time.
+        */
+       inline void best_block_updated(const uint8_t (*header)[80], uint32_t height);
+       /**
+        *  Returns transactions that should be monitored for reorganization out of the chain.
+        * 
+        *  Should include any transactions passed to [`transactions_confirmed`] that have insufficient
+        *  confirmations to be safe from a chain reorganization. Should not include any transactions
+        *  passed to [`transaction_unconfirmed`] unless later reconfirmed.
+        * 
+        *  May be called to determine the subset of transactions that must still be monitored for
+        *  reorganization. Will be idempotent between calls but may change as a result of calls to the
+        *  other interface methods. Thus, this is useful to determine which transactions may need to be
+        *  given to [`transaction_unconfirmed`].
+        * 
+        *  [`transactions_confirmed`]: Self::transactions_confirmed
+        *  [`transaction_unconfirmed`]: Self::transaction_unconfirmed
+        */
+       inline LDK::CVec_TxidZ get_relevant_txids();
 };
 class Watch {
 private:
@@ -372,6 +753,33 @@ public:
        LDKWatch* operator ->() { return &self; }
        const LDKWatch* operator &() const { return &self; }
        const LDKWatch* operator ->() const { return &self; }
+       /**
+        *  Watches a channel identified by `funding_txo` using `monitor`.
+        * 
+        *  Implementations are responsible for watching the chain for the funding transaction along
+        *  with any spends of outputs returned by [`get_outputs_to_watch`]. In practice, this means
+        *  calling [`block_connected`] and [`block_disconnected`] on the monitor.
+        * 
+        *  [`get_outputs_to_watch`]: channelmonitor::ChannelMonitor::get_outputs_to_watch
+        *  [`block_connected`]: channelmonitor::ChannelMonitor::block_connected
+        *  [`block_disconnected`]: channelmonitor::ChannelMonitor::block_disconnected
+        */
+       inline LDK::CResult_NoneChannelMonitorUpdateErrZ watch_channel(struct LDKOutPoint funding_txo, struct LDKChannelMonitor monitor);
+       /**
+        *  Updates a channel identified by `funding_txo` by applying `update` to its monitor.
+        * 
+        *  Implementations must call [`update_monitor`] with the given update. See
+        *  [`ChannelMonitorUpdateErr`] for invariants around returning an error.
+        * 
+        *  [`update_monitor`]: channelmonitor::ChannelMonitor::update_monitor
+        *  [`ChannelMonitorUpdateErr`]: channelmonitor::ChannelMonitorUpdateErr
+        */
+       inline LDK::CResult_NoneChannelMonitorUpdateErrZ update_channel(struct LDKOutPoint funding_txo, struct LDKChannelMonitorUpdate update);
+       /**
+        *  Returns any monitor events since the last call. Subsequent calls must only return new
+        *  events.
+        */
+       inline LDK::CVec_MonitorEventZ release_pending_monitor_events();
 };
 class Filter {
 private:
@@ -387,6 +795,23 @@ public:
        LDKFilter* operator ->() { return &self; }
        const LDKFilter* operator &() const { return &self; }
        const LDKFilter* operator ->() const { return &self; }
+       /**
+        *  Registers interest in a transaction with `txid` and having an output with `script_pubkey` as
+        *  a spending condition.
+        */
+       inline void register_tx(const uint8_t (*txid)[32], struct LDKu8slice script_pubkey);
+       /**
+        *  Registers interest in spends of a transaction output.
+        * 
+        *  Optionally, when `output.block_hash` is set, should return any transaction spending the
+        *  output that is found in the corresponding block along with its index.
+        * 
+        *  This return value is useful for Electrum clients in order to supply in-block descendant
+        *  transactions which otherwise were not included. This is not necessary for other clients if
+        *  such descendant transactions were already included (e.g., when a BIP 157 client provides the
+        *  full block).
+        */
+       inline LDK::COption_C2Tuple_usizeTransactionZZ register_output(struct LDKWatchedOutput output);
 };
 class WatchedOutput {
 private:
@@ -403,6 +828,21 @@ public:
        const LDKWatchedOutput* operator &() const { return &self; }
        const LDKWatchedOutput* operator ->() const { return &self; }
 };
+class PaymentPurpose {
+private:
+       LDKPaymentPurpose self;
+public:
+       PaymentPurpose(const PaymentPurpose&) = delete;
+       PaymentPurpose(PaymentPurpose&& o) : self(o.self) { memset(&o, 0, sizeof(PaymentPurpose)); }
+       PaymentPurpose(LDKPaymentPurpose&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKPaymentPurpose)); }
+       operator LDKPaymentPurpose() && { LDKPaymentPurpose res = self; memset(&self, 0, sizeof(LDKPaymentPurpose)); return res; }
+       ~PaymentPurpose() { PaymentPurpose_free(self); }
+       PaymentPurpose& operator=(PaymentPurpose&& o) { PaymentPurpose_free(self); self = o.self; memset(&o, 0, sizeof(PaymentPurpose)); return *this; }
+       LDKPaymentPurpose* operator &() { return &self; }
+       LDKPaymentPurpose* operator ->() { return &self; }
+       const LDKPaymentPurpose* operator &() const { return &self; }
+       const LDKPaymentPurpose* operator ->() const { return &self; }
+};
 class Event {
 private:
        LDKEvent self;
@@ -447,6 +887,11 @@ public:
        LDKMessageSendEventsProvider* operator ->() { return &self; }
        const LDKMessageSendEventsProvider* operator &() const { return &self; }
        const LDKMessageSendEventsProvider* operator ->() const { return &self; }
+       /**
+        *  Gets the list of pending events which were generated by previous actions, clearing the list
+        *  in the process.
+        */
+       inline LDK::CVec_MessageSendEventZ get_and_clear_pending_msg_events();
 };
 class EventsProvider {
 private:
@@ -462,6 +907,14 @@ public:
        LDKEventsProvider* operator ->() { return &self; }
        const LDKEventsProvider* operator &() const { return &self; }
        const LDKEventsProvider* operator ->() const { return &self; }
+       /**
+        *  Processes any events generated since the last call using the given event handler.
+        * 
+        *  Subsequent calls must only process new events. However, handlers must be capable of handling
+        *  duplicate events across process restarts. This may occur if the provider was recovered from
+        *  an old state (i.e., it hadn't been successfully persisted after processing pending events).
+        */
+       inline void process_pending_events(struct LDKEventHandler handler);
 };
 class EventHandler {
 private:
@@ -477,6 +930,12 @@ public:
        LDKEventHandler* operator ->() { return &self; }
        const LDKEventHandler* operator &() const { return &self; }
        const LDKEventHandler* operator ->() const { return &self; }
+       /**
+        *  Handles the given [`Event`].
+        * 
+        *  See [`EventsProvider`] for details that must be considered when implementing this method.
+        */
+       inline void handle_event(struct LDKEvent event);
 };
 class InitFeatures {
 private:
@@ -597,6 +1056,135 @@ public:
        LDKBaseSign* operator ->() { return &self; }
        const LDKBaseSign* operator &() const { return &self; }
        const LDKBaseSign* operator ->() const { return &self; }
+       /**
+        *  Gets the per-commitment point for a specific commitment number
+        * 
+        *  Note that the commitment number starts at (1 << 48) - 1 and counts backwards.
+        */
+       inline LDKPublicKey get_per_commitment_point(uint64_t idx);
+       /**
+        *  Gets the commitment secret for a specific commitment number as part of the revocation process
+        * 
+        *  An external signer implementation should error here if the commitment was already signed
+        *  and should refuse to sign it in the future.
+        * 
+        *  May be called more than once for the same index.
+        * 
+        *  Note that the commitment number starts at (1 << 48) - 1 and counts backwards.
+        */
+       inline LDKThirtyTwoBytes release_commitment_secret(uint64_t idx);
+       /**
+        *  Gets an arbitrary identifier describing the set of keys which are provided back to you in
+        *  some SpendableOutputDescriptor types. This should be sufficient to identify this
+        *  Sign object uniquely and lookup or re-derive its keys.
+        */
+       inline LDKThirtyTwoBytes channel_keys_id();
+       /**
+        *  Create a signature for a counterparty's commitment transaction and associated HTLC transactions.
+        * 
+        *  Note that if signing fails or is rejected, the channel will be force-closed.
+        */
+       inline LDK::CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ sign_counterparty_commitment(const struct LDKCommitmentTransaction *NONNULL_PTR commitment_tx);
+       /**
+        *  Create a signatures for a holder's commitment transaction and its claiming HTLC transactions.
+        *  This will only ever be called with a non-revoked commitment_tx.  This will be called with the
+        *  latest commitment_tx when we initiate a force-close.
+        *  This will be called with the previous latest, just to get claiming HTLC signatures, if we are
+        *  reacting to a ChannelMonitor replica that decided to broadcast before it had been updated to
+        *  the latest.
+        *  This may be called multiple times for the same transaction.
+        * 
+        *  An external signer implementation should check that the commitment has not been revoked.
+        * 
+        *  May return Err if key derivation fails.  Callers, such as ChannelMonitor, will panic in such a case.
+        */
+       inline LDK::CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ sign_holder_commitment_and_htlcs(const struct LDKHolderCommitmentTransaction *NONNULL_PTR commitment_tx);
+       /**
+        *  Create a signature for the given input in a transaction spending an HTLC transaction output
+        *  or a commitment transaction `to_local` output when our counterparty broadcasts an old state.
+        * 
+        *  A justice transaction may claim multiple outputs at the same time if timelocks are
+        *  similar, but only a signature for the input at index `input` should be signed for here.
+        *  It may be called multiple times for same output(s) if a fee-bump is needed with regards
+        *  to an upcoming timelock expiration.
+        * 
+        *  Amount is value of the output spent by this input, committed to in the BIP 143 signature.
+        * 
+        *  per_commitment_key is revocation secret which was provided by our counterparty when they
+        *  revoked the state which they eventually broadcast. It's not a _holder_ secret key and does
+        *  not allow the spending of any funds by itself (you need our holder revocation_secret to do
+        *  so).
+        */
+       inline LDK::CResult_SignatureNoneZ sign_justice_revoked_output(struct LDKTransaction justice_tx, uintptr_t input, uint64_t amount, const uint8_t (*per_commitment_key)[32]);
+       /**
+        *  Create a signature for the given input in a transaction spending a commitment transaction
+        *  HTLC output when our counterparty broadcasts an old state.
+        * 
+        *  A justice transaction may claim multiple outputs at the same time if timelocks are
+        *  similar, but only a signature for the input at index `input` should be signed for here.
+        *  It may be called multiple times for same output(s) if a fee-bump is needed with regards
+        *  to an upcoming timelock expiration.
+        * 
+        *  Amount is value of the output spent by this input, committed to in the BIP 143 signature.
+        * 
+        *  per_commitment_key is revocation secret which was provided by our counterparty when they
+        *  revoked the state which they eventually broadcast. It's not a _holder_ secret key and does
+        *  not allow the spending of any funds by itself (you need our holder revocation_secret to do
+        *  so).
+        * 
+        *  htlc holds HTLC elements (hash, timelock), thus changing the format of the witness script
+        *  (which is committed to in the BIP 143 signatures).
+        */
+       inline LDK::CResult_SignatureNoneZ sign_justice_revoked_htlc(struct LDKTransaction justice_tx, uintptr_t input, uint64_t amount, const uint8_t (*per_commitment_key)[32], const struct LDKHTLCOutputInCommitment *NONNULL_PTR htlc);
+       /**
+        *  Create a signature for a claiming transaction for a HTLC output on a counterparty's commitment
+        *  transaction, either offered or received.
+        * 
+        *  Such a transaction may claim multiples offered outputs at same time if we know the
+        *  preimage for each when we create it, but only the input at index `input` should be
+        *  signed for here. It may be called multiple times for same output(s) if a fee-bump is
+        *  needed with regards to an upcoming timelock expiration.
+        * 
+        *  Witness_script is either a offered or received script as defined in BOLT3 for HTLC
+        *  outputs.
+        * 
+        *  Amount is value of the output spent by this input, committed to in the BIP 143 signature.
+        * 
+        *  Per_commitment_point is the dynamic point corresponding to the channel state
+        *  detected onchain. It has been generated by our counterparty and is used to derive
+        *  channel state keys, which are then included in the witness script and committed to in the
+        *  BIP 143 signature.
+        */
+       inline LDK::CResult_SignatureNoneZ sign_counterparty_htlc_transaction(struct LDKTransaction htlc_tx, uintptr_t input, uint64_t amount, struct LDKPublicKey per_commitment_point, const struct LDKHTLCOutputInCommitment *NONNULL_PTR htlc);
+       /**
+        *  Create a signature for a (proposed) closing transaction.
+        * 
+        *  Note that, due to rounding, there may be one "missing" satoshi, and either party may have
+        *  chosen to forgo their output as dust.
+        */
+       inline LDK::CResult_SignatureNoneZ sign_closing_transaction(struct LDKTransaction closing_tx);
+       /**
+        *  Signs a channel announcement message with our funding key, proving it comes from one
+        *  of the channel participants.
+        * 
+        *  Note that if this fails or is rejected, the channel will not be publicly announced and
+        *  our counterparty may (though likely will not) close the channel on us for violating the
+        *  protocol.
+        */
+       inline LDK::CResult_SignatureNoneZ sign_channel_announcement(const struct LDKUnsignedChannelAnnouncement *NONNULL_PTR msg);
+       /**
+        *  Set the counterparty static channel data, including basepoints,
+        *  counterparty_selected/holder_selected_contest_delay and funding outpoint.
+        *  This is done as soon as the funding outpoint is known.  Since these are static channel data,
+        *  they MUST NOT be allowed to change to different values once set.
+        * 
+        *  channel_parameters.is_populated() MUST be true.
+        * 
+        *  We bind holder_selected_contest_delay late here for API convenience.
+        * 
+        *  Will be called before any signatures are applied.
+        */
+       inline void ready_channel(const struct LDKChannelTransactionParameters *NONNULL_PTR channel_parameters);
 };
 class Sign {
 private:
@@ -627,6 +1215,58 @@ public:
        LDKKeysInterface* operator ->() { return &self; }
        const LDKKeysInterface* operator &() const { return &self; }
        const LDKKeysInterface* operator ->() const { return &self; }
+       /**
+        *  Get node secret key (aka node_id or network_key).
+        * 
+        *  This method must return the same value each time it is called.
+        */
+       inline LDKSecretKey get_node_secret();
+       /**
+        *  Get a script pubkey which we send funds to when claiming on-chain contestable outputs.
+        * 
+        *  This method should return a different value each time it is called, to avoid linking
+        *  on-chain funds across channels as controlled to the same user.
+        */
+       inline LDK::CVec_u8Z get_destination_script();
+       /**
+        *  Get a public key which we will send funds to (in the form of a P2WPKH output) when closing
+        *  a channel.
+        * 
+        *  This method should return a different value each time it is called, to avoid linking
+        *  on-chain funds across channels as controlled to the same user.
+        */
+       inline LDKPublicKey get_shutdown_pubkey();
+       /**
+        *  Get a new set of Sign for per-channel secrets. These MUST be unique even if you
+        *  restarted with some stale data!
+        * 
+        *  This method must return a different value each time it is called.
+        */
+       inline LDK::Sign get_channel_signer(bool inbound, uint64_t channel_value_satoshis);
+       /**
+        *  Gets a unique, cryptographically-secure, random 32 byte value. This is used for encrypting
+        *  onion packets and for temporary channel IDs. There is no requirement that these be
+        *  persisted anywhere, though they must be unique across restarts.
+        * 
+        *  This method must return a different value each time it is called.
+        */
+       inline LDKThirtyTwoBytes get_secure_random_bytes();
+       /**
+        *  Reads a `Signer` for this `KeysInterface` from the given input stream.
+        *  This is only called during deserialization of other objects which contain
+        *  `Sign`-implementing objects (ie `ChannelMonitor`s and `ChannelManager`s).
+        *  The bytes are exactly those which `<Self::Signer as Writeable>::write()` writes, and
+        *  contain no versioning scheme. You may wish to include your own version prefix and ensure
+        *  you've read all of the provided bytes to ensure no corruption occurred.
+        */
+       inline LDK::CResult_SignDecodeErrorZ read_chan_signer(struct LDKu8slice reader);
+       /**
+        *  Sign an invoice's preimage (note that this is the preimage of the invoice, not the HTLC's
+        *  preimage). By parameterizing by the preimage instead of the hash, we allow implementors of
+        *  this trait to parse the invoice and make sure they're signing what they expect, rather than
+        *  blindly signing the hash.
+        */
+       inline LDK::CResult_RecoverableSignatureNoneZ sign_invoice(struct LDKCVec_u8Z invoice_preimage);
 };
 class InMemorySigner {
 private:
@@ -1222,6 +1862,42 @@ public:
        LDKPersist* operator ->() { return &self; }
        const LDKPersist* operator &() const { return &self; }
        const LDKPersist* operator ->() const { return &self; }
+       /**
+        *  Persist a new channel's data. The data can be stored any way you want, but
+        *  the identifier provided by Rust-Lightning is the channel's outpoint (and
+        *  it is up to you to maintain a correct mapping between the outpoint and the
+        *  stored channel data). Note that you **must** persist every new monitor to
+        *  disk. See the `Persist` trait documentation for more details.
+        * 
+        *  See [`ChannelMonitor::write`] for writing out a `ChannelMonitor`,
+        *  and [`ChannelMonitorUpdateErr`] for requirements when returning errors.
+        */
+       inline LDK::CResult_NoneChannelMonitorUpdateErrZ persist_new_channel(struct LDKOutPoint id, const struct LDKChannelMonitor *NONNULL_PTR data);
+       /**
+        *  Update one channel's data. The provided `ChannelMonitor` has already
+        *  applied the given update.
+        * 
+        *  Note that on every update, you **must** persist either the
+        *  `ChannelMonitorUpdate` or the updated monitor itself to disk/backups. See
+        *  the `Persist` trait documentation for more details.
+        * 
+        *  If an implementer chooses to persist the updates only, they need to make
+        *  sure that all the updates are applied to the `ChannelMonitors` *before*
+        *  the set of channel monitors is given to the `ChannelManager`
+        *  deserialization routine. See [`ChannelMonitor::update_monitor`] for
+        *  applying a monitor update to a monitor. If full `ChannelMonitors` are
+        *  persisted, then there is no need to persist individual updates.
+        * 
+        *  Note that there could be a performance tradeoff between persisting complete
+        *  channel monitors on every update vs. persisting only updates and applying
+        *  them in batches. The size of each monitor grows `O(number of state updates)`
+        *  whereas updates are small and `O(1)`.
+        * 
+        *  See [`ChannelMonitor::write`] for writing out a `ChannelMonitor`,
+        *  [`ChannelMonitorUpdate::write`] for writing out an update, and
+        *  [`ChannelMonitorUpdateErr`] for requirements when returning errors.
+        */
+       inline LDK::CResult_NoneChannelMonitorUpdateErrZ update_persisted_channel(struct LDKOutPoint id, const struct LDKChannelMonitorUpdate *NONNULL_PTR update, const struct LDKChannelMonitor *NONNULL_PTR data);
 };
 class IgnoringMessageHandler {
 private:
@@ -1282,6 +1958,40 @@ public:
        LDKSocketDescriptor* operator ->() { return &self; }
        const LDKSocketDescriptor* operator &() const { return &self; }
        const LDKSocketDescriptor* operator ->() const { return &self; }
+       /**
+        *  Attempts to send some data from the given slice to the peer.
+        * 
+        *  Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
+        *  Note that in the disconnected case, [`PeerManager::socket_disconnected`] must still be
+        *  called and further write attempts may occur until that time.
+        * 
+        *  If the returned size is smaller than `data.len()`, a
+        *  [`PeerManager::write_buffer_space_avail`] call must be made the next time more data can be
+        *  written. Additionally, until a `send_data` event completes fully, no further
+        *  [`PeerManager::read_event`] calls should be made for the same peer! Because this is to
+        *  prevent denial-of-service issues, you should not read or buffer any data from the socket
+        *  until then.
+        * 
+        *  If a [`PeerManager::read_event`] call on this descriptor had previously returned true
+        *  (indicating that read events should be paused to prevent DoS in the send buffer),
+        *  `resume_read` may be set indicating that read events on this descriptor should resume. A
+        *  `resume_read` of false carries no meaning, and should not cause any action.
+        */
+       inline uintptr_t send_data(struct LDKu8slice data, bool resume_read);
+       /**
+        *  Disconnect the socket pointed to by this SocketDescriptor.
+        * 
+        *  You do *not* need to call [`PeerManager::socket_disconnected`] with this socket after this
+        *  call (doing so is a noop).
+        */
+       inline void disconnect_socket();
+       /** Checks if two objects are equal given this object's this_arg pointer and another object. */
+       inline bool eq(const struct LDKSocketDescriptor *NONNULL_PTR other_arg);
+       /**
+        * Calculate a succinct non-cryptographic hash for an object given its this_arg pointer.
+        * This is used, for example, for inclusion of this object in a hash map.
+        */
+       inline uint64_t hash();
 };
 class PeerHandleError {
 private:
@@ -2017,6 +2727,89 @@ public:
        LDKChannelMessageHandler* operator ->() { return &self; }
        const LDKChannelMessageHandler* operator &() const { return &self; }
        const LDKChannelMessageHandler* operator ->() const { return &self; }
+       /**
+        *  Handle an incoming open_channel message from the given peer.
+        */
+       inline void handle_open_channel(struct LDKPublicKey their_node_id, struct LDKInitFeatures their_features, const struct LDKOpenChannel *NONNULL_PTR msg);
+       /**
+        *  Handle an incoming accept_channel message from the given peer.
+        */
+       inline void handle_accept_channel(struct LDKPublicKey their_node_id, struct LDKInitFeatures their_features, const struct LDKAcceptChannel *NONNULL_PTR msg);
+       /**
+        *  Handle an incoming funding_created message from the given peer.
+        */
+       inline void handle_funding_created(struct LDKPublicKey their_node_id, const struct LDKFundingCreated *NONNULL_PTR msg);
+       /**
+        *  Handle an incoming funding_signed message from the given peer.
+        */
+       inline void handle_funding_signed(struct LDKPublicKey their_node_id, const struct LDKFundingSigned *NONNULL_PTR msg);
+       /**
+        *  Handle an incoming funding_locked message from the given peer.
+        */
+       inline void handle_funding_locked(struct LDKPublicKey their_node_id, const struct LDKFundingLocked *NONNULL_PTR msg);
+       /**
+        *  Handle an incoming shutdown message from the given peer.
+        */
+       inline void handle_shutdown(struct LDKPublicKey their_node_id, const struct LDKInitFeatures *NONNULL_PTR their_features, const struct LDKShutdown *NONNULL_PTR msg);
+       /**
+        *  Handle an incoming closing_signed message from the given peer.
+        */
+       inline void handle_closing_signed(struct LDKPublicKey their_node_id, const struct LDKClosingSigned *NONNULL_PTR msg);
+       /**
+        *  Handle an incoming update_add_htlc message from the given peer.
+        */
+       inline void handle_update_add_htlc(struct LDKPublicKey their_node_id, const struct LDKUpdateAddHTLC *NONNULL_PTR msg);
+       /**
+        *  Handle an incoming update_fulfill_htlc message from the given peer.
+        */
+       inline void handle_update_fulfill_htlc(struct LDKPublicKey their_node_id, const struct LDKUpdateFulfillHTLC *NONNULL_PTR msg);
+       /**
+        *  Handle an incoming update_fail_htlc message from the given peer.
+        */
+       inline void handle_update_fail_htlc(struct LDKPublicKey their_node_id, const struct LDKUpdateFailHTLC *NONNULL_PTR msg);
+       /**
+        *  Handle an incoming update_fail_malformed_htlc message from the given peer.
+        */
+       inline void handle_update_fail_malformed_htlc(struct LDKPublicKey their_node_id, const struct LDKUpdateFailMalformedHTLC *NONNULL_PTR msg);
+       /**
+        *  Handle an incoming commitment_signed message from the given peer.
+        */
+       inline void handle_commitment_signed(struct LDKPublicKey their_node_id, const struct LDKCommitmentSigned *NONNULL_PTR msg);
+       /**
+        *  Handle an incoming revoke_and_ack message from the given peer.
+        */
+       inline void handle_revoke_and_ack(struct LDKPublicKey their_node_id, const struct LDKRevokeAndACK *NONNULL_PTR msg);
+       /**
+        *  Handle an incoming update_fee message from the given peer.
+        */
+       inline void handle_update_fee(struct LDKPublicKey their_node_id, const struct LDKUpdateFee *NONNULL_PTR msg);
+       /**
+        *  Handle an incoming announcement_signatures message from the given peer.
+        */
+       inline void handle_announcement_signatures(struct LDKPublicKey their_node_id, const struct LDKAnnouncementSignatures *NONNULL_PTR msg);
+       /**
+        *  Indicates a connection to the peer failed/an existing connection was lost. If no connection
+        *  is believed to be possible in the future (eg they're sending us messages we don't
+        *  understand or indicate they require unknown feature bits), no_connection_possible is set
+        *  and any outstanding channels should be failed.
+        */
+       inline void peer_disconnected(struct LDKPublicKey their_node_id, bool no_connection_possible);
+       /**
+        *  Handle a peer reconnecting, possibly generating channel_reestablish message(s).
+        */
+       inline void peer_connected(struct LDKPublicKey their_node_id, const struct LDKInit *NONNULL_PTR msg);
+       /**
+        *  Handle an incoming channel_reestablish message from the given peer.
+        */
+       inline void handle_channel_reestablish(struct LDKPublicKey their_node_id, const struct LDKChannelReestablish *NONNULL_PTR msg);
+       /**
+        *  Handle an incoming channel update from the given peer.
+        */
+       inline void handle_channel_update(struct LDKPublicKey their_node_id, const struct LDKChannelUpdate *NONNULL_PTR msg);
+       /**
+        *  Handle an incoming error message from the given peer.
+        */
+       inline void handle_error(struct LDKPublicKey their_node_id, const struct LDKErrorMessage *NONNULL_PTR msg);
 };
 class RoutingMessageHandler {
 private:
@@ -2032,6 +2825,69 @@ public:
        LDKRoutingMessageHandler* operator ->() { return &self; }
        const LDKRoutingMessageHandler* operator &() const { return &self; }
        const LDKRoutingMessageHandler* operator ->() const { return &self; }
+       /**
+        *  Handle an incoming node_announcement message, returning true if it should be forwarded on,
+        *  false or returning an Err otherwise.
+        */
+       inline LDK::CResult_boolLightningErrorZ handle_node_announcement(const struct LDKNodeAnnouncement *NONNULL_PTR msg);
+       /**
+        *  Handle a channel_announcement message, returning true if it should be forwarded on, false
+        *  or returning an Err otherwise.
+        */
+       inline LDK::CResult_boolLightningErrorZ handle_channel_announcement(const struct LDKChannelAnnouncement *NONNULL_PTR msg);
+       /**
+        *  Handle an incoming channel_update message, returning true if it should be forwarded on,
+        *  false or returning an Err otherwise.
+        */
+       inline LDK::CResult_boolLightningErrorZ handle_channel_update(const struct LDKChannelUpdate *NONNULL_PTR msg);
+       /**
+        *  Handle some updates to the route graph that we learned due to an outbound failed payment.
+        */
+       inline void handle_htlc_fail_channel_update(const struct LDKHTLCFailChannelUpdate *NONNULL_PTR update);
+       /**
+        *  Gets a subset of the channel announcements and updates required to dump our routing table
+        *  to a remote node, starting at the short_channel_id indicated by starting_point and
+        *  including the batch_amount entries immediately higher in numerical value than starting_point.
+        */
+       inline LDK::CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ get_next_channel_announcements(uint64_t starting_point, uint8_t batch_amount);
+       /**
+        *  Gets a subset of the node announcements required to dump our routing table to a remote node,
+        *  starting at the node *after* the provided publickey and including batch_amount entries
+        *  immediately higher (as defined by <PublicKey as Ord>::cmp) than starting_point.
+        *  If None is provided for starting_point, we start at the first node.
+        * 
+        *  Note that starting_point (or a relevant inner pointer) may be NULL or all-0s to represent None
+        */
+       inline LDK::CVec_NodeAnnouncementZ get_next_node_announcements(struct LDKPublicKey starting_point, uint8_t batch_amount);
+       /**
+        *  Called when a connection is established with a peer. This can be used to
+        *  perform routing table synchronization using a strategy defined by the
+        *  implementor.
+        */
+       inline void sync_routing_table(struct LDKPublicKey their_node_id, const struct LDKInit *NONNULL_PTR init);
+       /**
+        *  Handles the reply of a query we initiated to learn about channels
+        *  for a given range of blocks. We can expect to receive one or more
+        *  replies to a single query.
+        */
+       inline LDK::CResult_NoneLightningErrorZ handle_reply_channel_range(struct LDKPublicKey their_node_id, struct LDKReplyChannelRange msg);
+       /**
+        *  Handles the reply of a query we initiated asking for routing gossip
+        *  messages for a list of channels. We should receive this message when
+        *  a node has completed its best effort to send us the pertaining routing
+        *  gossip messages.
+        */
+       inline LDK::CResult_NoneLightningErrorZ handle_reply_short_channel_ids_end(struct LDKPublicKey their_node_id, struct LDKReplyShortChannelIdsEnd msg);
+       /**
+        *  Handles when a peer asks us to send a list of short_channel_ids
+        *  for the requested range of blocks.
+        */
+       inline LDK::CResult_NoneLightningErrorZ handle_query_channel_range(struct LDKPublicKey their_node_id, struct LDKQueryChannelRange msg);
+       /**
+        *  Handles when a peer asks us to send routing gossip messages for a
+        *  list of short_channel_ids.
+        */
+       inline LDK::CResult_NoneLightningErrorZ handle_query_short_channel_ids(struct LDKPublicKey their_node_id, struct LDKQueryShortChannelIds msg);
 };
 class Level {
 private:
@@ -2061,6 +2917,10 @@ public:
        LDKLogger* operator ->() { return &self; }
        const LDKLogger* operator &() const { return &self; }
        const LDKLogger* operator ->() const { return &self; }
+       /**
+        *  Logs the `Record`
+        */
+       inline void log(const char *record);
 };
 class ChainMonitor {
 private:
@@ -3997,6 +4857,21 @@ public:
        const LDKCResult_NoneChannelMonitorUpdateErrZ* operator &() const { return &self; }
        const LDKCResult_NoneChannelMonitorUpdateErrZ* operator ->() const { return &self; }
 };
+class CResult_PaymentHashPaymentSendFailureZ {
+private:
+       LDKCResult_PaymentHashPaymentSendFailureZ self;
+public:
+       CResult_PaymentHashPaymentSendFailureZ(const CResult_PaymentHashPaymentSendFailureZ&) = delete;
+       CResult_PaymentHashPaymentSendFailureZ(CResult_PaymentHashPaymentSendFailureZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_PaymentHashPaymentSendFailureZ)); }
+       CResult_PaymentHashPaymentSendFailureZ(LDKCResult_PaymentHashPaymentSendFailureZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_PaymentHashPaymentSendFailureZ)); }
+       operator LDKCResult_PaymentHashPaymentSendFailureZ() && { LDKCResult_PaymentHashPaymentSendFailureZ res = self; memset(&self, 0, sizeof(LDKCResult_PaymentHashPaymentSendFailureZ)); return res; }
+       ~CResult_PaymentHashPaymentSendFailureZ() { CResult_PaymentHashPaymentSendFailureZ_free(self); }
+       CResult_PaymentHashPaymentSendFailureZ& operator=(CResult_PaymentHashPaymentSendFailureZ&& o) { CResult_PaymentHashPaymentSendFailureZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_PaymentHashPaymentSendFailureZ)); return *this; }
+       LDKCResult_PaymentHashPaymentSendFailureZ* operator &() { return &self; }
+       LDKCResult_PaymentHashPaymentSendFailureZ* operator ->() { return &self; }
+       const LDKCResult_PaymentHashPaymentSendFailureZ* operator &() const { return &self; }
+       const LDKCResult_PaymentHashPaymentSendFailureZ* operator ->() const { return &self; }
+};
 class CResult_SiPrefixNoneZ {
 private:
        LDKCResult_SiPrefixNoneZ self;
@@ -4327,4 +5202,267 @@ public:
        const LDKCResult_FundingLockedDecodeErrorZ* operator &() const { return &self; }
        const LDKCResult_FundingLockedDecodeErrorZ* operator ->() const { return &self; }
 };
+
+inline LDK::CResult_NoneErrorZ ChannelManagerPersister::persist_manager(const struct LDKChannelManager *NONNULL_PTR channel_manager) {
+       LDK::CResult_NoneErrorZ ret = (self.persist_manager)(self.this_arg, channel_manager);
+       return ret;
+}
+inline void BroadcasterInterface::broadcast_transaction(struct LDKTransaction tx) {
+       (self.broadcast_transaction)(self.this_arg, tx);
+}
+inline uint32_t FeeEstimator::get_est_sat_per_1000_weight(enum LDKConfirmationTarget confirmation_target) {
+       uint32_t ret = (self.get_est_sat_per_1000_weight)(self.this_arg, confirmation_target);
+       return ret;
+}
+inline LDK::CResult_TxOutAccessErrorZ Access::get_utxo(const uint8_t (*genesis_hash)[32], uint64_t short_channel_id) {
+       LDK::CResult_TxOutAccessErrorZ ret = (self.get_utxo)(self.this_arg, genesis_hash, short_channel_id);
+       return ret;
+}
+inline void Listen::block_connected(struct LDKu8slice block, uint32_t height) {
+       (self.block_connected)(self.this_arg, block, height);
+}
+inline void Listen::block_disconnected(const uint8_t (*header)[80], uint32_t height) {
+       (self.block_disconnected)(self.this_arg, header, height);
+}
+inline void Confirm::transactions_confirmed(const uint8_t (*header)[80], struct LDKCVec_C2Tuple_usizeTransactionZZ txdata, uint32_t height) {
+       (self.transactions_confirmed)(self.this_arg, header, txdata, height);
+}
+inline void Confirm::transaction_unconfirmed(const uint8_t (*txid)[32]) {
+       (self.transaction_unconfirmed)(self.this_arg, txid);
+}
+inline void Confirm::best_block_updated(const uint8_t (*header)[80], uint32_t height) {
+       (self.best_block_updated)(self.this_arg, header, height);
+}
+inline LDK::CVec_TxidZ Confirm::get_relevant_txids() {
+       LDK::CVec_TxidZ ret = (self.get_relevant_txids)(self.this_arg);
+       return ret;
+}
+inline LDK::CResult_NoneChannelMonitorUpdateErrZ Watch::watch_channel(struct LDKOutPoint funding_txo, struct LDKChannelMonitor monitor) {
+       LDK::CResult_NoneChannelMonitorUpdateErrZ ret = (self.watch_channel)(self.this_arg, funding_txo, monitor);
+       return ret;
+}
+inline LDK::CResult_NoneChannelMonitorUpdateErrZ Watch::update_channel(struct LDKOutPoint funding_txo, struct LDKChannelMonitorUpdate update) {
+       LDK::CResult_NoneChannelMonitorUpdateErrZ ret = (self.update_channel)(self.this_arg, funding_txo, update);
+       return ret;
+}
+inline LDK::CVec_MonitorEventZ Watch::release_pending_monitor_events() {
+       LDK::CVec_MonitorEventZ ret = (self.release_pending_monitor_events)(self.this_arg);
+       return ret;
+}
+inline void Filter::register_tx(const uint8_t (*txid)[32], struct LDKu8slice script_pubkey) {
+       (self.register_tx)(self.this_arg, txid, script_pubkey);
+}
+inline LDK::COption_C2Tuple_usizeTransactionZZ Filter::register_output(struct LDKWatchedOutput output) {
+       LDK::COption_C2Tuple_usizeTransactionZZ ret = (self.register_output)(self.this_arg, output);
+       return ret;
+}
+inline LDK::CVec_MessageSendEventZ MessageSendEventsProvider::get_and_clear_pending_msg_events() {
+       LDK::CVec_MessageSendEventZ ret = (self.get_and_clear_pending_msg_events)(self.this_arg);
+       return ret;
+}
+inline void EventsProvider::process_pending_events(struct LDKEventHandler handler) {
+       (self.process_pending_events)(self.this_arg, handler);
+}
+inline void EventHandler::handle_event(struct LDKEvent event) {
+       (self.handle_event)(self.this_arg, event);
+}
+inline LDKPublicKey BaseSign::get_per_commitment_point(uint64_t idx) {
+       LDKPublicKey ret = (self.get_per_commitment_point)(self.this_arg, idx);
+       return ret;
+}
+inline LDKThirtyTwoBytes BaseSign::release_commitment_secret(uint64_t idx) {
+       LDKThirtyTwoBytes ret = (self.release_commitment_secret)(self.this_arg, idx);
+       return ret;
+}
+inline LDKThirtyTwoBytes BaseSign::channel_keys_id() {
+       LDKThirtyTwoBytes ret = (self.channel_keys_id)(self.this_arg);
+       return ret;
+}
+inline LDK::CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ BaseSign::sign_counterparty_commitment(const struct LDKCommitmentTransaction *NONNULL_PTR commitment_tx) {
+       LDK::CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ ret = (self.sign_counterparty_commitment)(self.this_arg, commitment_tx);
+       return ret;
+}
+inline LDK::CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ BaseSign::sign_holder_commitment_and_htlcs(const struct LDKHolderCommitmentTransaction *NONNULL_PTR commitment_tx) {
+       LDK::CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ ret = (self.sign_holder_commitment_and_htlcs)(self.this_arg, commitment_tx);
+       return ret;
+}
+inline LDK::CResult_SignatureNoneZ BaseSign::sign_justice_revoked_output(struct LDKTransaction justice_tx, uintptr_t input, uint64_t amount, const uint8_t (*per_commitment_key)[32]) {
+       LDK::CResult_SignatureNoneZ ret = (self.sign_justice_revoked_output)(self.this_arg, justice_tx, input, amount, per_commitment_key);
+       return ret;
+}
+inline LDK::CResult_SignatureNoneZ BaseSign::sign_justice_revoked_htlc(struct LDKTransaction justice_tx, uintptr_t input, uint64_t amount, const uint8_t (*per_commitment_key)[32], const struct LDKHTLCOutputInCommitment *NONNULL_PTR htlc) {
+       LDK::CResult_SignatureNoneZ ret = (self.sign_justice_revoked_htlc)(self.this_arg, justice_tx, input, amount, per_commitment_key, htlc);
+       return ret;
+}
+inline LDK::CResult_SignatureNoneZ BaseSign::sign_counterparty_htlc_transaction(struct LDKTransaction htlc_tx, uintptr_t input, uint64_t amount, struct LDKPublicKey per_commitment_point, const struct LDKHTLCOutputInCommitment *NONNULL_PTR htlc) {
+       LDK::CResult_SignatureNoneZ ret = (self.sign_counterparty_htlc_transaction)(self.this_arg, htlc_tx, input, amount, per_commitment_point, htlc);
+       return ret;
+}
+inline LDK::CResult_SignatureNoneZ BaseSign::sign_closing_transaction(struct LDKTransaction closing_tx) {
+       LDK::CResult_SignatureNoneZ ret = (self.sign_closing_transaction)(self.this_arg, closing_tx);
+       return ret;
+}
+inline LDK::CResult_SignatureNoneZ BaseSign::sign_channel_announcement(const struct LDKUnsignedChannelAnnouncement *NONNULL_PTR msg) {
+       LDK::CResult_SignatureNoneZ ret = (self.sign_channel_announcement)(self.this_arg, msg);
+       return ret;
+}
+inline void BaseSign::ready_channel(const struct LDKChannelTransactionParameters *NONNULL_PTR channel_parameters) {
+       (self.ready_channel)(self.this_arg, channel_parameters);
+}
+inline LDKSecretKey KeysInterface::get_node_secret() {
+       LDKSecretKey ret = (self.get_node_secret)(self.this_arg);
+       return ret;
+}
+inline LDK::CVec_u8Z KeysInterface::get_destination_script() {
+       LDK::CVec_u8Z ret = (self.get_destination_script)(self.this_arg);
+       return ret;
+}
+inline LDKPublicKey KeysInterface::get_shutdown_pubkey() {
+       LDKPublicKey ret = (self.get_shutdown_pubkey)(self.this_arg);
+       return ret;
+}
+inline LDK::Sign KeysInterface::get_channel_signer(bool inbound, uint64_t channel_value_satoshis) {
+       LDK::Sign ret = (self.get_channel_signer)(self.this_arg, inbound, channel_value_satoshis);
+       return ret;
+}
+inline LDKThirtyTwoBytes KeysInterface::get_secure_random_bytes() {
+       LDKThirtyTwoBytes ret = (self.get_secure_random_bytes)(self.this_arg);
+       return ret;
+}
+inline LDK::CResult_SignDecodeErrorZ KeysInterface::read_chan_signer(struct LDKu8slice reader) {
+       LDK::CResult_SignDecodeErrorZ ret = (self.read_chan_signer)(self.this_arg, reader);
+       return ret;
+}
+inline LDK::CResult_RecoverableSignatureNoneZ KeysInterface::sign_invoice(struct LDKCVec_u8Z invoice_preimage) {
+       LDK::CResult_RecoverableSignatureNoneZ ret = (self.sign_invoice)(self.this_arg, invoice_preimage);
+       return ret;
+}
+inline LDK::CResult_NoneChannelMonitorUpdateErrZ Persist::persist_new_channel(struct LDKOutPoint id, const struct LDKChannelMonitor *NONNULL_PTR data) {
+       LDK::CResult_NoneChannelMonitorUpdateErrZ ret = (self.persist_new_channel)(self.this_arg, id, data);
+       return ret;
+}
+inline LDK::CResult_NoneChannelMonitorUpdateErrZ Persist::update_persisted_channel(struct LDKOutPoint id, const struct LDKChannelMonitorUpdate *NONNULL_PTR update, const struct LDKChannelMonitor *NONNULL_PTR data) {
+       LDK::CResult_NoneChannelMonitorUpdateErrZ ret = (self.update_persisted_channel)(self.this_arg, id, update, data);
+       return ret;
+}
+inline uintptr_t SocketDescriptor::send_data(struct LDKu8slice data, bool resume_read) {
+       uintptr_t ret = (self.send_data)(self.this_arg, data, resume_read);
+       return ret;
+}
+inline void SocketDescriptor::disconnect_socket() {
+       (self.disconnect_socket)(self.this_arg);
+}
+inline bool SocketDescriptor::eq(const struct LDKSocketDescriptor *NONNULL_PTR other_arg) {
+       bool ret = (self.eq)(self.this_arg, other_arg);
+       return ret;
+}
+inline uint64_t SocketDescriptor::hash() {
+       uint64_t ret = (self.hash)(self.this_arg);
+       return ret;
+}
+inline void ChannelMessageHandler::handle_open_channel(struct LDKPublicKey their_node_id, struct LDKInitFeatures their_features, const struct LDKOpenChannel *NONNULL_PTR msg) {
+       (self.handle_open_channel)(self.this_arg, their_node_id, their_features, msg);
+}
+inline void ChannelMessageHandler::handle_accept_channel(struct LDKPublicKey their_node_id, struct LDKInitFeatures their_features, const struct LDKAcceptChannel *NONNULL_PTR msg) {
+       (self.handle_accept_channel)(self.this_arg, their_node_id, their_features, msg);
+}
+inline void ChannelMessageHandler::handle_funding_created(struct LDKPublicKey their_node_id, const struct LDKFundingCreated *NONNULL_PTR msg) {
+       (self.handle_funding_created)(self.this_arg, their_node_id, msg);
+}
+inline void ChannelMessageHandler::handle_funding_signed(struct LDKPublicKey their_node_id, const struct LDKFundingSigned *NONNULL_PTR msg) {
+       (self.handle_funding_signed)(self.this_arg, their_node_id, msg);
+}
+inline void ChannelMessageHandler::handle_funding_locked(struct LDKPublicKey their_node_id, const struct LDKFundingLocked *NONNULL_PTR msg) {
+       (self.handle_funding_locked)(self.this_arg, their_node_id, msg);
+}
+inline void ChannelMessageHandler::handle_shutdown(struct LDKPublicKey their_node_id, const struct LDKInitFeatures *NONNULL_PTR their_features, const struct LDKShutdown *NONNULL_PTR msg) {
+       (self.handle_shutdown)(self.this_arg, their_node_id, their_features, msg);
+}
+inline void ChannelMessageHandler::handle_closing_signed(struct LDKPublicKey their_node_id, const struct LDKClosingSigned *NONNULL_PTR msg) {
+       (self.handle_closing_signed)(self.this_arg, their_node_id, msg);
+}
+inline void ChannelMessageHandler::handle_update_add_htlc(struct LDKPublicKey their_node_id, const struct LDKUpdateAddHTLC *NONNULL_PTR msg) {
+       (self.handle_update_add_htlc)(self.this_arg, their_node_id, msg);
+}
+inline void ChannelMessageHandler::handle_update_fulfill_htlc(struct LDKPublicKey their_node_id, const struct LDKUpdateFulfillHTLC *NONNULL_PTR msg) {
+       (self.handle_update_fulfill_htlc)(self.this_arg, their_node_id, msg);
+}
+inline void ChannelMessageHandler::handle_update_fail_htlc(struct LDKPublicKey their_node_id, const struct LDKUpdateFailHTLC *NONNULL_PTR msg) {
+       (self.handle_update_fail_htlc)(self.this_arg, their_node_id, msg);
+}
+inline void ChannelMessageHandler::handle_update_fail_malformed_htlc(struct LDKPublicKey their_node_id, const struct LDKUpdateFailMalformedHTLC *NONNULL_PTR msg) {
+       (self.handle_update_fail_malformed_htlc)(self.this_arg, their_node_id, msg);
+}
+inline void ChannelMessageHandler::handle_commitment_signed(struct LDKPublicKey their_node_id, const struct LDKCommitmentSigned *NONNULL_PTR msg) {
+       (self.handle_commitment_signed)(self.this_arg, their_node_id, msg);
+}
+inline void ChannelMessageHandler::handle_revoke_and_ack(struct LDKPublicKey their_node_id, const struct LDKRevokeAndACK *NONNULL_PTR msg) {
+       (self.handle_revoke_and_ack)(self.this_arg, their_node_id, msg);
+}
+inline void ChannelMessageHandler::handle_update_fee(struct LDKPublicKey their_node_id, const struct LDKUpdateFee *NONNULL_PTR msg) {
+       (self.handle_update_fee)(self.this_arg, their_node_id, msg);
+}
+inline void ChannelMessageHandler::handle_announcement_signatures(struct LDKPublicKey their_node_id, const struct LDKAnnouncementSignatures *NONNULL_PTR msg) {
+       (self.handle_announcement_signatures)(self.this_arg, their_node_id, msg);
+}
+inline void ChannelMessageHandler::peer_disconnected(struct LDKPublicKey their_node_id, bool no_connection_possible) {
+       (self.peer_disconnected)(self.this_arg, their_node_id, no_connection_possible);
+}
+inline void ChannelMessageHandler::peer_connected(struct LDKPublicKey their_node_id, const struct LDKInit *NONNULL_PTR msg) {
+       (self.peer_connected)(self.this_arg, their_node_id, msg);
+}
+inline void ChannelMessageHandler::handle_channel_reestablish(struct LDKPublicKey their_node_id, const struct LDKChannelReestablish *NONNULL_PTR msg) {
+       (self.handle_channel_reestablish)(self.this_arg, their_node_id, msg);
+}
+inline void ChannelMessageHandler::handle_channel_update(struct LDKPublicKey their_node_id, const struct LDKChannelUpdate *NONNULL_PTR msg) {
+       (self.handle_channel_update)(self.this_arg, their_node_id, msg);
+}
+inline void ChannelMessageHandler::handle_error(struct LDKPublicKey their_node_id, const struct LDKErrorMessage *NONNULL_PTR msg) {
+       (self.handle_error)(self.this_arg, their_node_id, msg);
+}
+inline LDK::CResult_boolLightningErrorZ RoutingMessageHandler::handle_node_announcement(const struct LDKNodeAnnouncement *NONNULL_PTR msg) {
+       LDK::CResult_boolLightningErrorZ ret = (self.handle_node_announcement)(self.this_arg, msg);
+       return ret;
+}
+inline LDK::CResult_boolLightningErrorZ RoutingMessageHandler::handle_channel_announcement(const struct LDKChannelAnnouncement *NONNULL_PTR msg) {
+       LDK::CResult_boolLightningErrorZ ret = (self.handle_channel_announcement)(self.this_arg, msg);
+       return ret;
+}
+inline LDK::CResult_boolLightningErrorZ RoutingMessageHandler::handle_channel_update(const struct LDKChannelUpdate *NONNULL_PTR msg) {
+       LDK::CResult_boolLightningErrorZ ret = (self.handle_channel_update)(self.this_arg, msg);
+       return ret;
+}
+inline void RoutingMessageHandler::handle_htlc_fail_channel_update(const struct LDKHTLCFailChannelUpdate *NONNULL_PTR update) {
+       (self.handle_htlc_fail_channel_update)(self.this_arg, update);
+}
+inline LDK::CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ RoutingMessageHandler::get_next_channel_announcements(uint64_t starting_point, uint8_t batch_amount) {
+       LDK::CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ ret = (self.get_next_channel_announcements)(self.this_arg, starting_point, batch_amount);
+       return ret;
+}
+inline LDK::CVec_NodeAnnouncementZ RoutingMessageHandler::get_next_node_announcements(struct LDKPublicKey starting_point, uint8_t batch_amount) {
+       LDK::CVec_NodeAnnouncementZ ret = (self.get_next_node_announcements)(self.this_arg, starting_point, batch_amount);
+       return ret;
+}
+inline void RoutingMessageHandler::sync_routing_table(struct LDKPublicKey their_node_id, const struct LDKInit *NONNULL_PTR init) {
+       (self.sync_routing_table)(self.this_arg, their_node_id, init);
+}
+inline LDK::CResult_NoneLightningErrorZ RoutingMessageHandler::handle_reply_channel_range(struct LDKPublicKey their_node_id, struct LDKReplyChannelRange msg) {
+       LDK::CResult_NoneLightningErrorZ ret = (self.handle_reply_channel_range)(self.this_arg, their_node_id, msg);
+       return ret;
+}
+inline LDK::CResult_NoneLightningErrorZ RoutingMessageHandler::handle_reply_short_channel_ids_end(struct LDKPublicKey their_node_id, struct LDKReplyShortChannelIdsEnd msg) {
+       LDK::CResult_NoneLightningErrorZ ret = (self.handle_reply_short_channel_ids_end)(self.this_arg, their_node_id, msg);
+       return ret;
+}
+inline LDK::CResult_NoneLightningErrorZ RoutingMessageHandler::handle_query_channel_range(struct LDKPublicKey their_node_id, struct LDKQueryChannelRange msg) {
+       LDK::CResult_NoneLightningErrorZ ret = (self.handle_query_channel_range)(self.this_arg, their_node_id, msg);
+       return ret;
+}
+inline LDK::CResult_NoneLightningErrorZ RoutingMessageHandler::handle_query_short_channel_ids(struct LDKPublicKey their_node_id, struct LDKQueryShortChannelIds msg) {
+       LDK::CResult_NoneLightningErrorZ ret = (self.handle_query_short_channel_ids)(self.this_arg, their_node_id, msg);
+       return ret;
+}
+inline void Logger::log(const char *record) {
+       (self.log)(self.this_arg, record);
+}
 }
index c9d57ee472888560d5a470b9ee28c8168970690a..fef1837b07cc9f80a4514c3c864191d6d60bdeeb 100644 (file)
@@ -4090,6 +4090,97 @@ impl Clone for CResult_NonePaymentSendFailureZ {
 /// but with all dynamically-allocated buffers duplicated in new buffers.
 pub extern "C" fn CResult_NonePaymentSendFailureZ_clone(orig: &CResult_NonePaymentSendFailureZ) -> CResult_NonePaymentSendFailureZ { orig.clone() }
 #[repr(C)]
+/// The contents of CResult_PaymentHashPaymentSendFailureZ
+pub union CResult_PaymentHashPaymentSendFailureZPtr {
+       /// A pointer to the contents in the success state.
+       /// Reading from this pointer when `result_ok` is not set is undefined.
+       pub result: *mut crate::c_types::ThirtyTwoBytes,
+       /// A pointer to the contents in the error state.
+       /// Reading from this pointer when `result_ok` is set is undefined.
+       pub err: *mut crate::lightning::ln::channelmanager::PaymentSendFailure,
+}
+#[repr(C)]
+/// A CResult_PaymentHashPaymentSendFailureZ represents the result of a fallible operation,
+/// containing a crate::c_types::ThirtyTwoBytes on success and a crate::lightning::ln::channelmanager::PaymentSendFailure on failure.
+/// `result_ok` indicates the overall state, and the contents are provided via `contents`.
+pub struct CResult_PaymentHashPaymentSendFailureZ {
+       /// The contents of this CResult_PaymentHashPaymentSendFailureZ, accessible via either
+       /// `err` or `result` depending on the state of `result_ok`.
+       pub contents: CResult_PaymentHashPaymentSendFailureZPtr,
+       /// Whether this CResult_PaymentHashPaymentSendFailureZ represents a success state.
+       pub result_ok: bool,
+}
+#[no_mangle]
+/// Creates a new CResult_PaymentHashPaymentSendFailureZ in the success state.
+pub extern "C" fn CResult_PaymentHashPaymentSendFailureZ_ok(o: crate::c_types::ThirtyTwoBytes) -> CResult_PaymentHashPaymentSendFailureZ {
+       CResult_PaymentHashPaymentSendFailureZ {
+               contents: CResult_PaymentHashPaymentSendFailureZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+/// Creates a new CResult_PaymentHashPaymentSendFailureZ in the error state.
+pub extern "C" fn CResult_PaymentHashPaymentSendFailureZ_err(e: crate::lightning::ln::channelmanager::PaymentSendFailure) -> CResult_PaymentHashPaymentSendFailureZ {
+       CResult_PaymentHashPaymentSendFailureZ {
+               contents: CResult_PaymentHashPaymentSendFailureZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+/// Frees any resources used by the CResult_PaymentHashPaymentSendFailureZ.
+pub extern "C" fn CResult_PaymentHashPaymentSendFailureZ_free(_res: CResult_PaymentHashPaymentSendFailureZ) { }
+impl Drop for CResult_PaymentHashPaymentSendFailureZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::c_types::ThirtyTwoBytes, crate::lightning::ln::channelmanager::PaymentSendFailure>> for CResult_PaymentHashPaymentSendFailureZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::c_types::ThirtyTwoBytes, crate::lightning::ln::channelmanager::PaymentSendFailure>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_PaymentHashPaymentSendFailureZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_PaymentHashPaymentSendFailureZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_PaymentHashPaymentSendFailureZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_PaymentHashPaymentSendFailureZPtr {
+                               result: Box::into_raw(Box::new(<crate::c_types::ThirtyTwoBytes>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_PaymentHashPaymentSendFailureZPtr {
+                               err: Box::into_raw(Box::new(<crate::lightning::ln::channelmanager::PaymentSendFailure>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
+#[no_mangle]
+/// Creates a new CResult_PaymentHashPaymentSendFailureZ which has the same data as `orig`
+/// but with all dynamically-allocated buffers duplicated in new buffers.
+pub extern "C" fn CResult_PaymentHashPaymentSendFailureZ_clone(orig: &CResult_PaymentHashPaymentSendFailureZ) -> CResult_PaymentHashPaymentSendFailureZ { orig.clone() }
+#[repr(C)]
 /// A dynamically-allocated array of crate::lightning::ln::msgs::NetAddresss of arbitrary size.
 /// This corresponds to std::vector in C++
 pub struct CVec_NetAddressZ {
index 83dae2b0c268a8f00553ee95092c1f967059931c..2648a9b39092dbdf96576e4dc998cae10eaf8282 100644 (file)
@@ -315,6 +315,12 @@ impl TxOut {
                }
        }
 }
+
+#[no_mangle]
+/// Convenience function for constructing a new TxOut
+pub extern "C" fn TxOut_new(script_pubkey: derived::CVec_u8Z, value: u64) -> TxOut {
+       TxOut { script_pubkey, value }
+}
 #[no_mangle]
 /// Frees the data pointed to by script_pubkey.
 pub extern "C" fn TxOut_free(_res: TxOut) { }
index e6494e26bac7c55fdd7ed911f8204ee3ab788351..9ba2256e9b915b7ee25ef6a385a34b73ba6cb346 100644 (file)
@@ -31,6 +31,14 @@ pub struct BroadcasterInterface {
 }
 unsafe impl Send for BroadcasterInterface {}
 unsafe impl Sync for BroadcasterInterface {}
+#[no_mangle]
+pub(crate) extern "C" fn BroadcasterInterface_clone_fields(orig: &BroadcasterInterface) -> BroadcasterInterface {
+       BroadcasterInterface {
+               this_arg: orig.this_arg,
+               broadcast_transaction: Clone::clone(&orig.broadcast_transaction),
+               free: Clone::clone(&orig.free),
+       }
+}
 
 use lightning::chain::chaininterface::BroadcasterInterface as rustBroadcasterInterface;
 impl rustBroadcasterInterface for BroadcasterInterface {
@@ -110,6 +118,18 @@ impl ConfirmationTarget {
 pub extern "C" fn ConfirmationTarget_clone(orig: &ConfirmationTarget) -> ConfirmationTarget {
        orig.clone()
 }
+#[no_mangle]
+/// Utility method to constructs a new Background-variant ConfirmationTarget
+pub extern "C" fn ConfirmationTarget_background() -> ConfirmationTarget {
+       ConfirmationTarget::Background}
+#[no_mangle]
+/// Utility method to constructs a new Normal-variant ConfirmationTarget
+pub extern "C" fn ConfirmationTarget_normal() -> ConfirmationTarget {
+       ConfirmationTarget::Normal}
+#[no_mangle]
+/// Utility method to constructs a new HighPriority-variant ConfirmationTarget
+pub extern "C" fn ConfirmationTarget_high_priority() -> ConfirmationTarget {
+       ConfirmationTarget::HighPriority}
 /// A trait which should be implemented to provide feerate information on a number of time
 /// horizons.
 ///
@@ -136,6 +156,14 @@ pub struct FeeEstimator {
 }
 unsafe impl Send for FeeEstimator {}
 unsafe impl Sync for FeeEstimator {}
+#[no_mangle]
+pub(crate) extern "C" fn FeeEstimator_clone_fields(orig: &FeeEstimator) -> FeeEstimator {
+       FeeEstimator {
+               this_arg: orig.this_arg,
+               get_est_sat_per_1000_weight: Clone::clone(&orig.get_est_sat_per_1000_weight),
+               free: Clone::clone(&orig.free),
+       }
+}
 
 use lightning::chain::chaininterface::FeeEstimator as rustFeeEstimator;
 impl rustFeeEstimator for FeeEstimator {
index 2e65f47b551077d9383142907b52da748d6271dd..311c2f397cd432025d14db3dfd2c0e2dea71f470 100644 (file)
@@ -87,6 +87,8 @@ impl ChainMonitor {
 /// pre-filter blocks or only fetch blocks matching a compact filter. Otherwise, clients may
 /// always need to fetch full blocks absent another means for determining which blocks contain
 /// transactions relevant to the watched channels.
+///
+/// Note that chain_source (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[must_use]
 #[no_mangle]
 pub extern "C" fn ChainMonitor_new(chain_source: *mut crate::lightning::chain::Filter, mut broadcaster: crate::lightning::chain::chaininterface::BroadcasterInterface, mut logger: crate::lightning::util::logger::Logger, mut feeest: crate::lightning::chain::chaininterface::FeeEstimator, mut persister: crate::lightning::chain::channelmonitor::Persist) -> ChainMonitor {
index a5429bcba4a320ae57653cffbe18ea64843e1b1c..11612160ec4b3c78d551a2ab7565a2e002fbf9dc 100644 (file)
@@ -244,6 +244,14 @@ impl ChannelMonitorUpdateErr {
 pub extern "C" fn ChannelMonitorUpdateErr_clone(orig: &ChannelMonitorUpdateErr) -> ChannelMonitorUpdateErr {
        orig.clone()
 }
+#[no_mangle]
+/// Utility method to constructs a new TemporaryFailure-variant ChannelMonitorUpdateErr
+pub extern "C" fn ChannelMonitorUpdateErr_temporary_failure() -> ChannelMonitorUpdateErr {
+       ChannelMonitorUpdateErr::TemporaryFailure}
+#[no_mangle]
+/// Utility method to constructs a new PermanentFailure-variant ChannelMonitorUpdateErr
+pub extern "C" fn ChannelMonitorUpdateErr_permanent_failure() -> ChannelMonitorUpdateErr {
+       ChannelMonitorUpdateErr::PermanentFailure}
 
 use lightning::chain::channelmonitor::MonitorUpdateError as nativeMonitorUpdateErrorImport;
 type nativeMonitorUpdateError = nativeMonitorUpdateErrorImport;
@@ -397,6 +405,16 @@ pub extern "C" fn MonitorEvent_free(this_ptr: MonitorEvent) { }
 pub extern "C" fn MonitorEvent_clone(orig: &MonitorEvent) -> MonitorEvent {
        orig.clone()
 }
+#[no_mangle]
+/// Utility method to constructs a new HTLCEvent-variant MonitorEvent
+pub extern "C" fn MonitorEvent_htlcevent(a: crate::lightning::chain::channelmonitor::HTLCUpdate) -> MonitorEvent {
+       MonitorEvent::HTLCEvent(a, )
+}
+#[no_mangle]
+/// Utility method to constructs a new CommitmentTxBroadcasted-variant MonitorEvent
+pub extern "C" fn MonitorEvent_commitment_tx_broadcasted(a: crate::lightning::chain::transaction::OutPoint) -> MonitorEvent {
+       MonitorEvent::CommitmentTxBroadcasted(a, )
+}
 
 use lightning::chain::channelmonitor::HTLCUpdate as nativeHTLCUpdateImport;
 type nativeHTLCUpdate = nativeHTLCUpdateImport;
@@ -785,6 +803,15 @@ pub struct Persist {
 }
 unsafe impl Send for Persist {}
 unsafe impl Sync for Persist {}
+#[no_mangle]
+pub(crate) extern "C" fn Persist_clone_fields(orig: &Persist) -> Persist {
+       Persist {
+               this_arg: orig.this_arg,
+               persist_new_channel: Clone::clone(&orig.persist_new_channel),
+               update_persisted_channel: Clone::clone(&orig.update_persisted_channel),
+               free: Clone::clone(&orig.free),
+       }
+}
 
 use lightning::chain::channelmonitor::Persist as rustPersist;
 impl rustPersist<crate::lightning::chain::keysinterface::Sign> for Persist {
index b043fccf02ab6967a1c9775039da1df465bbd003..812d51ac9992d5281fd4a0e120f7850a265a230f 100644 (file)
@@ -485,6 +485,24 @@ pub extern "C" fn SpendableOutputDescriptor_clone(orig: &SpendableOutputDescript
        orig.clone()
 }
 #[no_mangle]
+/// Utility method to constructs a new StaticOutput-variant SpendableOutputDescriptor
+pub extern "C" fn SpendableOutputDescriptor_static_output(outpoint: crate::lightning::chain::transaction::OutPoint, output: crate::c_types::TxOut) -> SpendableOutputDescriptor {
+       SpendableOutputDescriptor::StaticOutput {
+               outpoint,
+               output,
+       }
+}
+#[no_mangle]
+/// Utility method to constructs a new DelayedPaymentOutput-variant SpendableOutputDescriptor
+pub extern "C" fn SpendableOutputDescriptor_delayed_payment_output(a: crate::lightning::chain::keysinterface::DelayedPaymentOutputDescriptor) -> SpendableOutputDescriptor {
+       SpendableOutputDescriptor::DelayedPaymentOutput(a, )
+}
+#[no_mangle]
+/// Utility method to constructs a new StaticPaymentOutput-variant SpendableOutputDescriptor
+pub extern "C" fn SpendableOutputDescriptor_static_payment_output(a: crate::lightning::chain::keysinterface::StaticPaymentOutputDescriptor) -> SpendableOutputDescriptor {
+       SpendableOutputDescriptor::StaticPaymentOutput(a, )
+}
+#[no_mangle]
 /// Serialize the SpendableOutputDescriptor object into a byte array which can be read by SpendableOutputDescriptor_read
 pub extern "C" fn SpendableOutputDescriptor_write(obj: &SpendableOutputDescriptor) -> crate::c_types::derived::CVec_u8Z {
        crate::c_types::serialize_obj(&unsafe { &*obj }.to_native())
@@ -647,6 +665,26 @@ pub struct BaseSign {
 }
 unsafe impl Send for BaseSign {}
 unsafe impl Sync for BaseSign {}
+#[no_mangle]
+pub(crate) extern "C" fn BaseSign_clone_fields(orig: &BaseSign) -> BaseSign {
+       BaseSign {
+               this_arg: orig.this_arg,
+               get_per_commitment_point: Clone::clone(&orig.get_per_commitment_point),
+               release_commitment_secret: Clone::clone(&orig.release_commitment_secret),
+               pubkeys: Clone::clone(&orig.pubkeys),
+               set_pubkeys: Clone::clone(&orig.set_pubkeys),
+               channel_keys_id: Clone::clone(&orig.channel_keys_id),
+               sign_counterparty_commitment: Clone::clone(&orig.sign_counterparty_commitment),
+               sign_holder_commitment_and_htlcs: Clone::clone(&orig.sign_holder_commitment_and_htlcs),
+               sign_justice_revoked_output: Clone::clone(&orig.sign_justice_revoked_output),
+               sign_justice_revoked_htlc: Clone::clone(&orig.sign_justice_revoked_htlc),
+               sign_counterparty_htlc_transaction: Clone::clone(&orig.sign_counterparty_htlc_transaction),
+               sign_closing_transaction: Clone::clone(&orig.sign_closing_transaction),
+               sign_channel_announcement: Clone::clone(&orig.sign_channel_announcement),
+               ready_channel: Clone::clone(&orig.ready_channel),
+               free: Clone::clone(&orig.free),
+       }
+}
 
 use lightning::chain::keysinterface::BaseSign as rustBaseSign;
 impl rustBaseSign for BaseSign {
@@ -738,28 +776,35 @@ pub struct Sign {
        pub this_arg: *mut c_void,
        /// Implementation of BaseSign for this object.
        pub BaseSign: crate::lightning::chain::keysinterface::BaseSign,
-       /// Creates a copy of the BaseSign, for a copy of this Sign.
-       /// Because BaseSign doesn't natively support copying itself, you have to provide a full copy implementation here.
-       pub BaseSign_clone: extern "C" fn (orig_BaseSign: &BaseSign) -> BaseSign,
        /// Serialize the object into a byte array
        pub write: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_u8Z,
-       /// Creates a copy of the object pointed to by this_arg, for a copy of this Sign.
-       /// Note that the ultimate copy of the Sign will have all function pointers the same as the original.
-       /// May be NULL if no action needs to be taken, the this_arg pointer will be copied into the new Sign.
-       pub clone: Option<extern "C" fn (this_arg: *const c_void) -> *mut c_void>,
+       /// Called, if set, after this Sign has been cloned into a duplicate object.
+       /// The new Sign is provided, and should be mutated as needed to perform a
+       /// deep copy of the object pointed to by this_arg or avoid any double-freeing.
+       pub cloned: Option<extern "C" fn (new_Sign: &mut Sign)>,
        /// Frees any resources associated with this object given its this_arg pointer.
        /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
        pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
 }
 unsafe impl Send for Sign {}
 unsafe impl Sync for Sign {}
+#[no_mangle]
+pub(crate) extern "C" fn Sign_clone_fields(orig: &Sign) -> Sign {
+       Sign {
+               this_arg: orig.this_arg,
+               BaseSign: crate::lightning::chain::keysinterface::BaseSign_clone_fields(&orig.BaseSign),
+               write: Clone::clone(&orig.write),
+               cloned: Clone::clone(&orig.cloned),
+               free: Clone::clone(&orig.free),
+       }
+}
 impl lightning::chain::keysinterface::BaseSign for Sign {
        fn get_per_commitment_point(&self, mut idx: u64, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1<bitcoin::secp256k1::All>) -> bitcoin::secp256k1::key::PublicKey {
-               let mut ret = (self.BaseSign.get_per_commitment_point)(self.this_arg, idx);
+               let mut ret = (self.BaseSign.get_per_commitment_point)(self.BaseSign.this_arg, idx);
                ret.into_rust()
        }
        fn release_commitment_secret(&self, mut idx: u64) -> [u8; 32] {
-               let mut ret = (self.BaseSign.release_commitment_secret)(self.this_arg, idx);
+               let mut ret = (self.BaseSign.release_commitment_secret)(self.BaseSign.this_arg, idx);
                ret.data
        }
        fn pubkeys(&self) -> &lightning::ln::chan_utils::ChannelPublicKeys {
@@ -769,46 +814,46 @@ impl lightning::chain::keysinterface::BaseSign for Sign {
                unsafe { &*self.BaseSign.pubkeys.inner }
        }
        fn channel_keys_id(&self) -> [u8; 32] {
-               let mut ret = (self.BaseSign.channel_keys_id)(self.this_arg);
+               let mut ret = (self.BaseSign.channel_keys_id)(self.BaseSign.this_arg);
                ret.data
        }
        fn sign_counterparty_commitment(&self, mut commitment_tx: &lightning::ln::chan_utils::CommitmentTransaction, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1<bitcoin::secp256k1::All>) -> Result<(bitcoin::secp256k1::Signature, Vec<bitcoin::secp256k1::Signature>), ()> {
-               let mut ret = (self.BaseSign.sign_counterparty_commitment)(self.this_arg, &crate::lightning::ln::chan_utils::CommitmentTransaction { inner: unsafe { (commitment_tx as *const _) as *mut _ }, is_owned: false });
+               let mut ret = (self.BaseSign.sign_counterparty_commitment)(self.BaseSign.this_arg, &crate::lightning::ln::chan_utils::CommitmentTransaction { inner: unsafe { (commitment_tx as *const _) as *mut _ }, is_owned: false });
                let mut local_ret = match ret.result_ok { true => Ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).to_rust(); let mut local_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.into_rust().drain(..) { local_orig_ret_0_1.push( { item.into_rust() }); }; let mut local_ret_0 = (orig_ret_0_0.into_rust(), local_orig_ret_0_1); local_ret_0 }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })};
                local_ret
        }
        fn sign_holder_commitment_and_htlcs(&self, mut commitment_tx: &lightning::ln::chan_utils::HolderCommitmentTransaction, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1<bitcoin::secp256k1::All>) -> Result<(bitcoin::secp256k1::Signature, Vec<bitcoin::secp256k1::Signature>), ()> {
-               let mut ret = (self.BaseSign.sign_holder_commitment_and_htlcs)(self.this_arg, &crate::lightning::ln::chan_utils::HolderCommitmentTransaction { inner: unsafe { (commitment_tx as *const _) as *mut _ }, is_owned: false });
+               let mut ret = (self.BaseSign.sign_holder_commitment_and_htlcs)(self.BaseSign.this_arg, &crate::lightning::ln::chan_utils::HolderCommitmentTransaction { inner: unsafe { (commitment_tx as *const _) as *mut _ }, is_owned: false });
                let mut local_ret = match ret.result_ok { true => Ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).to_rust(); let mut local_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.into_rust().drain(..) { local_orig_ret_0_1.push( { item.into_rust() }); }; let mut local_ret_0 = (orig_ret_0_0.into_rust(), local_orig_ret_0_1); local_ret_0 }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })};
                local_ret
        }
        fn sign_justice_revoked_output(&self, mut justice_tx: &bitcoin::blockdata::transaction::Transaction, mut input: usize, mut amount: u64, mut per_commitment_key: &bitcoin::secp256k1::key::SecretKey, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1<bitcoin::secp256k1::All>) -> Result<bitcoin::secp256k1::Signature, ()> {
-               let mut ret = (self.BaseSign.sign_justice_revoked_output)(self.this_arg, crate::c_types::Transaction::from_bitcoin(justice_tx), input, amount, per_commitment_key.as_ref());
+               let mut ret = (self.BaseSign.sign_justice_revoked_output)(self.BaseSign.this_arg, crate::c_types::Transaction::from_bitcoin(justice_tx), input, amount, per_commitment_key.as_ref());
                let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })};
                local_ret
        }
        fn sign_justice_revoked_htlc(&self, mut justice_tx: &bitcoin::blockdata::transaction::Transaction, mut input: usize, mut amount: u64, mut per_commitment_key: &bitcoin::secp256k1::key::SecretKey, mut htlc: &lightning::ln::chan_utils::HTLCOutputInCommitment, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1<bitcoin::secp256k1::All>) -> Result<bitcoin::secp256k1::Signature, ()> {
-               let mut ret = (self.BaseSign.sign_justice_revoked_htlc)(self.this_arg, crate::c_types::Transaction::from_bitcoin(justice_tx), input, amount, per_commitment_key.as_ref(), &crate::lightning::ln::chan_utils::HTLCOutputInCommitment { inner: unsafe { (htlc as *const _) as *mut _ }, is_owned: false });
+               let mut ret = (self.BaseSign.sign_justice_revoked_htlc)(self.BaseSign.this_arg, crate::c_types::Transaction::from_bitcoin(justice_tx), input, amount, per_commitment_key.as_ref(), &crate::lightning::ln::chan_utils::HTLCOutputInCommitment { inner: unsafe { (htlc as *const _) as *mut _ }, is_owned: false });
                let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })};
                local_ret
        }
        fn sign_counterparty_htlc_transaction(&self, mut htlc_tx: &bitcoin::blockdata::transaction::Transaction, mut input: usize, mut amount: u64, mut per_commitment_point: &bitcoin::secp256k1::key::PublicKey, mut htlc: &lightning::ln::chan_utils::HTLCOutputInCommitment, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1<bitcoin::secp256k1::All>) -> Result<bitcoin::secp256k1::Signature, ()> {
-               let mut ret = (self.BaseSign.sign_counterparty_htlc_transaction)(self.this_arg, crate::c_types::Transaction::from_bitcoin(htlc_tx), input, amount, crate::c_types::PublicKey::from_rust(&per_commitment_point), &crate::lightning::ln::chan_utils::HTLCOutputInCommitment { inner: unsafe { (htlc as *const _) as *mut _ }, is_owned: false });
+               let mut ret = (self.BaseSign.sign_counterparty_htlc_transaction)(self.BaseSign.this_arg, crate::c_types::Transaction::from_bitcoin(htlc_tx), input, amount, crate::c_types::PublicKey::from_rust(&per_commitment_point), &crate::lightning::ln::chan_utils::HTLCOutputInCommitment { inner: unsafe { (htlc as *const _) as *mut _ }, is_owned: false });
                let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })};
                local_ret
        }
        fn sign_closing_transaction(&self, mut closing_tx: &bitcoin::blockdata::transaction::Transaction, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1<bitcoin::secp256k1::All>) -> Result<bitcoin::secp256k1::Signature, ()> {
-               let mut ret = (self.BaseSign.sign_closing_transaction)(self.this_arg, crate::c_types::Transaction::from_bitcoin(closing_tx));
+               let mut ret = (self.BaseSign.sign_closing_transaction)(self.BaseSign.this_arg, crate::c_types::Transaction::from_bitcoin(closing_tx));
                let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })};
                local_ret
        }
        fn sign_channel_announcement(&self, mut msg: &lightning::ln::msgs::UnsignedChannelAnnouncement, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1<bitcoin::secp256k1::All>) -> Result<bitcoin::secp256k1::Signature, ()> {
-               let mut ret = (self.BaseSign.sign_channel_announcement)(self.this_arg, &crate::lightning::ln::msgs::UnsignedChannelAnnouncement { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false });
+               let mut ret = (self.BaseSign.sign_channel_announcement)(self.BaseSign.this_arg, &crate::lightning::ln::msgs::UnsignedChannelAnnouncement { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false });
                let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })};
                local_ret
        }
        fn ready_channel(&mut self, mut channel_parameters: &lightning::ln::chan_utils::ChannelTransactionParameters) {
-               (self.BaseSign.ready_channel)(self.this_arg, &crate::lightning::ln::chan_utils::ChannelTransactionParameters { inner: unsafe { (channel_parameters as *const _) as *mut _ }, is_owned: false })
+               (self.BaseSign.ready_channel)(self.BaseSign.this_arg, &crate::lightning::ln::chan_utils::ChannelTransactionParameters { inner: unsafe { (channel_parameters as *const _) as *mut _ }, is_owned: false })
        }
 }
 impl lightning::util::ser::Writeable for Sign {
@@ -820,14 +865,9 @@ impl lightning::util::ser::Writeable for Sign {
 #[no_mangle]
 /// Creates a copy of a Sign
 pub extern "C" fn Sign_clone(orig: &Sign) -> Sign {
-       Sign {
-               this_arg: if let Some(f) = orig.clone { (f)(orig.this_arg) } else { orig.this_arg },
-               BaseSign: (orig.BaseSign_clone)(&orig.BaseSign),
-               BaseSign_clone: orig.BaseSign_clone,
-               write: Clone::clone(&orig.write),
-               clone: Clone::clone(&orig.clone),
-               free: Clone::clone(&orig.free),
-       }
+       let mut res = Sign_clone_fields(orig);
+       if let Some(f) = orig.cloned { (f)(&mut res) };
+       res
 }
 impl Clone for Sign {
        fn clone(&self) -> Self {
@@ -914,6 +954,20 @@ pub struct KeysInterface {
 }
 unsafe impl Send for KeysInterface {}
 unsafe impl Sync for KeysInterface {}
+#[no_mangle]
+pub(crate) extern "C" fn KeysInterface_clone_fields(orig: &KeysInterface) -> KeysInterface {
+       KeysInterface {
+               this_arg: orig.this_arg,
+               get_node_secret: Clone::clone(&orig.get_node_secret),
+               get_destination_script: Clone::clone(&orig.get_destination_script),
+               get_shutdown_pubkey: Clone::clone(&orig.get_shutdown_pubkey),
+               get_channel_signer: Clone::clone(&orig.get_channel_signer),
+               get_secure_random_bytes: Clone::clone(&orig.get_secure_random_bytes),
+               read_chan_signer: Clone::clone(&orig.read_chan_signer),
+               sign_invoice: Clone::clone(&orig.sign_invoice),
+               free: Clone::clone(&orig.free),
+       }
+}
 
 use lightning::chain::keysinterface::KeysInterface as rustKeysInterface;
 impl rustKeysInterface for KeysInterface {
@@ -1340,31 +1394,16 @@ pub extern "C" fn InMemorySigner_as_Sign(this_arg: &InMemorySigner) -> crate::li
                        sign_channel_announcement: InMemorySigner_BaseSign_sign_channel_announcement,
                        ready_channel: InMemorySigner_BaseSign_ready_channel,
                },
-               BaseSign_clone: InMemorySigner_BaseSign_clone,
                write: InMemorySigner_write_void,
-               clone: Some(InMemorySigner_clone_void),
+               cloned: Some(Sign_InMemorySigner_cloned),
        }
 }
 
-extern "C" fn InMemorySigner_BaseSign_clone(orig: &crate::lightning::chain::keysinterface::BaseSign) -> crate::lightning::chain::keysinterface::BaseSign {
-       crate::lightning::chain::keysinterface::BaseSign {
-               this_arg: orig.this_arg,
-               free: None,
-               get_per_commitment_point: InMemorySigner_BaseSign_get_per_commitment_point,
-               release_commitment_secret: InMemorySigner_BaseSign_release_commitment_secret,
-
-               pubkeys: crate::lightning::ln::chan_utils::ChannelPublicKeys { inner: std::ptr::null_mut(), is_owned: true },
-               set_pubkeys: Some(InMemorySigner_BaseSign_set_pubkeys),
-               channel_keys_id: InMemorySigner_BaseSign_channel_keys_id,
-               sign_counterparty_commitment: InMemorySigner_BaseSign_sign_counterparty_commitment,
-               sign_holder_commitment_and_htlcs: InMemorySigner_BaseSign_sign_holder_commitment_and_htlcs,
-               sign_justice_revoked_output: InMemorySigner_BaseSign_sign_justice_revoked_output,
-               sign_justice_revoked_htlc: InMemorySigner_BaseSign_sign_justice_revoked_htlc,
-               sign_counterparty_htlc_transaction: InMemorySigner_BaseSign_sign_counterparty_htlc_transaction,
-               sign_closing_transaction: InMemorySigner_BaseSign_sign_closing_transaction,
-               sign_channel_announcement: InMemorySigner_BaseSign_sign_channel_announcement,
-               ready_channel: InMemorySigner_BaseSign_ready_channel,
-       }
+extern "C" fn Sign_InMemorySigner_cloned(new_obj: &mut crate::lightning::chain::keysinterface::Sign) {
+       new_obj.this_arg = InMemorySigner_clone_void(new_obj.this_arg);
+       new_obj.free = Some(InMemorySigner_free_void);
+       new_obj.BaseSign.this_arg = new_obj.this_arg;
+       new_obj.BaseSign.free = None;
 }
 
 #[no_mangle]
index 21a6b8ad78ba92654663f021c909342e670815eb..7db473226e706d9756b77edb55daf523e3296b03 100644 (file)
@@ -177,6 +177,14 @@ impl AccessError {
 pub extern "C" fn AccessError_clone(orig: &AccessError) -> AccessError {
        orig.clone()
 }
+#[no_mangle]
+/// Utility method to constructs a new UnknownChain-variant AccessError
+pub extern "C" fn AccessError_unknown_chain() -> AccessError {
+       AccessError::UnknownChain}
+#[no_mangle]
+/// Utility method to constructs a new UnknownTx-variant AccessError
+pub extern "C" fn AccessError_unknown_tx() -> AccessError {
+       AccessError::UnknownTx}
 /// The `Access` trait defines behavior for accessing chain data and state, such as blocks and
 /// UTXOs.
 #[repr(C)]
@@ -197,6 +205,14 @@ pub struct Access {
 }
 unsafe impl Send for Access {}
 unsafe impl Sync for Access {}
+#[no_mangle]
+pub(crate) extern "C" fn Access_clone_fields(orig: &Access) -> Access {
+       Access {
+               this_arg: orig.this_arg,
+               get_utxo: Clone::clone(&orig.get_utxo),
+               free: Clone::clone(&orig.free),
+       }
+}
 
 use lightning::chain::Access as rustAccess;
 impl rustAccess for Access {
@@ -247,6 +263,15 @@ pub struct Listen {
 }
 unsafe impl Send for Listen {}
 unsafe impl Sync for Listen {}
+#[no_mangle]
+pub(crate) extern "C" fn Listen_clone_fields(orig: &Listen) -> Listen {
+       Listen {
+               this_arg: orig.this_arg,
+               block_connected: Clone::clone(&orig.block_connected),
+               block_disconnected: Clone::clone(&orig.block_disconnected),
+               free: Clone::clone(&orig.free),
+       }
+}
 
 use lightning::chain::Listen as rustListen;
 impl rustListen for Listen {
@@ -364,6 +389,17 @@ pub struct Confirm {
 }
 unsafe impl Send for Confirm {}
 unsafe impl Sync for Confirm {}
+#[no_mangle]
+pub(crate) extern "C" fn Confirm_clone_fields(orig: &Confirm) -> Confirm {
+       Confirm {
+               this_arg: orig.this_arg,
+               transactions_confirmed: Clone::clone(&orig.transactions_confirmed),
+               transaction_unconfirmed: Clone::clone(&orig.transaction_unconfirmed),
+               best_block_updated: Clone::clone(&orig.best_block_updated),
+               get_relevant_txids: Clone::clone(&orig.get_relevant_txids),
+               free: Clone::clone(&orig.free),
+       }
+}
 
 use lightning::chain::Confirm as rustConfirm;
 impl rustConfirm for Confirm {
@@ -460,6 +496,16 @@ pub struct Watch {
 }
 unsafe impl Send for Watch {}
 unsafe impl Sync for Watch {}
+#[no_mangle]
+pub(crate) extern "C" fn Watch_clone_fields(orig: &Watch) -> Watch {
+       Watch {
+               this_arg: orig.this_arg,
+               watch_channel: Clone::clone(&orig.watch_channel),
+               update_channel: Clone::clone(&orig.update_channel),
+               release_pending_monitor_events: Clone::clone(&orig.release_pending_monitor_events),
+               free: Clone::clone(&orig.free),
+       }
+}
 
 use lightning::chain::Watch as rustWatch;
 impl rustWatch<crate::lightning::chain::keysinterface::Sign> for Watch {
@@ -543,6 +589,15 @@ pub struct Filter {
 }
 unsafe impl Send for Filter {}
 unsafe impl Sync for Filter {}
+#[no_mangle]
+pub(crate) extern "C" fn Filter_clone_fields(orig: &Filter) -> Filter {
+       Filter {
+               this_arg: orig.this_arg,
+               register_tx: Clone::clone(&orig.register_tx),
+               register_output: Clone::clone(&orig.register_output),
+               free: Clone::clone(&orig.free),
+       }
+}
 
 use lightning::chain::Filter as rustFilter;
 impl rustFilter for Filter {
@@ -630,6 +685,8 @@ impl WatchedOutput {
        }
 }
 /// First block where the transaction output may have been spent.
+///
+/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[no_mangle]
 pub extern "C" fn WatchedOutput_get_block_hash(this_ptr: &WatchedOutput) -> crate::c_types::ThirtyTwoBytes {
        let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.block_hash;
@@ -637,6 +694,8 @@ pub extern "C" fn WatchedOutput_get_block_hash(this_ptr: &WatchedOutput) -> crat
        local_inner_val
 }
 /// First block where the transaction output may have been spent.
+///
+/// Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[no_mangle]
 pub extern "C" fn WatchedOutput_set_block_hash(this_ptr: &mut WatchedOutput, mut val: crate::c_types::ThirtyTwoBytes) {
        let mut local_val = if val.data == [0; 32] { None } else { Some( { ::bitcoin::hash_types::BlockHash::from_slice(&val.data[..]).unwrap() }) };
index 90dd91fe4e63967bb66a1322f62ff7ce0378ccf5..5cf8b63069a6870372c370ff85ef4e49b7b9b922 100644 (file)
@@ -716,6 +716,8 @@ pub extern "C" fn ChannelTransactionParameters_set_is_outbound_from_holder(this_
 }
 /// The late-bound counterparty channel transaction parameters.
 /// These parameters are populated at the point in the protocol where the counterparty provides them.
+///
+/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[no_mangle]
 pub extern "C" fn ChannelTransactionParameters_get_counterparty_parameters(this_ptr: &ChannelTransactionParameters) -> crate::lightning::ln::chan_utils::CounterpartyChannelTransactionParameters {
        let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.counterparty_parameters;
@@ -724,12 +726,16 @@ pub extern "C" fn ChannelTransactionParameters_get_counterparty_parameters(this_
 }
 /// The late-bound counterparty channel transaction parameters.
 /// These parameters are populated at the point in the protocol where the counterparty provides them.
+///
+/// Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[no_mangle]
 pub extern "C" fn ChannelTransactionParameters_set_counterparty_parameters(this_ptr: &mut ChannelTransactionParameters, mut val: crate::lightning::ln::chan_utils::CounterpartyChannelTransactionParameters) {
        let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) };
        unsafe { &mut *this_ptr.inner }.counterparty_parameters = local_val;
 }
 /// The late-bound funding outpoint
+///
+/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[no_mangle]
 pub extern "C" fn ChannelTransactionParameters_get_funding_outpoint(this_ptr: &ChannelTransactionParameters) -> crate::lightning::chain::transaction::OutPoint {
        let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.funding_outpoint;
@@ -737,6 +743,8 @@ pub extern "C" fn ChannelTransactionParameters_get_funding_outpoint(this_ptr: &C
        local_inner_val
 }
 /// The late-bound funding outpoint
+///
+/// Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[no_mangle]
 pub extern "C" fn ChannelTransactionParameters_set_funding_outpoint(this_ptr: &mut ChannelTransactionParameters, mut val: crate::lightning::chain::transaction::OutPoint) {
        let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) };
index 62b675e076969162474168a514915172da21496f..afdcaa916cfba81ef6ad7c579385dcd8b6ecd659 100644 (file)
@@ -421,6 +421,8 @@ pub extern "C" fn ChannelDetails_set_counterparty(this_ptr: &mut ChannelDetails,
 ///
 /// Note that, if this has been set, `channel_id` will be equivalent to
 /// `funding_txo.unwrap().to_channel_id()`.
+///
+/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[no_mangle]
 pub extern "C" fn ChannelDetails_get_funding_txo(this_ptr: &ChannelDetails) -> crate::lightning::chain::transaction::OutPoint {
        let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.funding_txo;
@@ -432,6 +434,8 @@ pub extern "C" fn ChannelDetails_get_funding_txo(this_ptr: &ChannelDetails) -> c
 ///
 /// Note that, if this has been set, `channel_id` will be equivalent to
 /// `funding_txo.unwrap().to_channel_id()`.
+///
+/// Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[no_mangle]
 pub extern "C" fn ChannelDetails_set_funding_txo(this_ptr: &mut ChannelDetails, mut val: crate::lightning::chain::transaction::OutPoint) {
        let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) };
@@ -889,6 +893,26 @@ pub extern "C" fn PaymentSendFailure_free(this_ptr: PaymentSendFailure) { }
 pub extern "C" fn PaymentSendFailure_clone(orig: &PaymentSendFailure) -> PaymentSendFailure {
        orig.clone()
 }
+#[no_mangle]
+/// Utility method to constructs a new ParameterError-variant PaymentSendFailure
+pub extern "C" fn PaymentSendFailure_parameter_error(a: crate::lightning::util::errors::APIError) -> PaymentSendFailure {
+       PaymentSendFailure::ParameterError(a, )
+}
+#[no_mangle]
+/// Utility method to constructs a new PathParameterError-variant PaymentSendFailure
+pub extern "C" fn PaymentSendFailure_path_parameter_error(a: crate::c_types::derived::CVec_CResult_NoneAPIErrorZZ) -> PaymentSendFailure {
+       PaymentSendFailure::PathParameterError(a, )
+}
+#[no_mangle]
+/// Utility method to constructs a new AllFailedRetrySafe-variant PaymentSendFailure
+pub extern "C" fn PaymentSendFailure_all_failed_retry_safe(a: crate::c_types::derived::CVec_APIErrorZ) -> PaymentSendFailure {
+       PaymentSendFailure::AllFailedRetrySafe(a, )
+}
+#[no_mangle]
+/// Utility method to constructs a new PartialFailure-variant PaymentSendFailure
+pub extern "C" fn PaymentSendFailure_partial_failure(a: crate::c_types::derived::CVec_CResult_NoneAPIErrorZZ) -> PaymentSendFailure {
+       PaymentSendFailure::PartialFailure(a, )
+}
 /// Constructs a new ChannelManager to hold several channels and route between them.
 ///
 /// This is the main \"logic hub\" for all channel-related actions, and implements
@@ -933,6 +957,8 @@ pub extern "C" fn ChannelManager_get_current_default_configuration(this_arg: &Ch
 /// Note that we do not check if you are currently connected to the given peer. If no
 /// connection is available, the outbound `open_channel` message may fail to send, resulting in
 /// the channel eventually being silently forgotten.
+///
+/// Note that override_config (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[must_use]
 #[no_mangle]
 pub extern "C" fn ChannelManager_create_channel(this_arg: &ChannelManager, mut their_network_key: crate::c_types::PublicKey, mut channel_value_satoshis: u64, mut push_msat: u64, mut user_id: u64, mut override_config: crate::lightning::util::config::UserConfig) -> crate::c_types::derived::CResult_NoneAPIErrorZ {
@@ -1035,6 +1061,8 @@ pub extern "C" fn ChannelManager_force_close_all_channels(this_arg: &ChannelMana
 /// If a payment_secret *is* provided, we assume that the invoice had the payment_secret feature
 /// bit set (either as required or as available). If multiple paths are present in the Route,
 /// we assume the invoice had the basic_mpp feature set.
+///
+/// Note that payment_secret (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[must_use]
 #[no_mangle]
 pub extern "C" fn ChannelManager_send_payment(this_arg: &ChannelManager, route: &crate::lightning::routing::router::Route, mut payment_hash: crate::c_types::ThirtyTwoBytes, mut payment_secret: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_NonePaymentSendFailureZ {
@@ -1044,6 +1072,27 @@ pub extern "C" fn ChannelManager_send_payment(this_arg: &ChannelManager, route:
        local_ret
 }
 
+/// Send a spontaneous payment, which is a payment that does not require the recipient to have
+/// generated an invoice. Optionally, you may specify the preimage. If you do choose to specify
+/// the preimage, it must be a cryptographically secure random value that no intermediate node
+/// would be able to guess -- otherwise, an intermediate node may claim the payment and it will
+/// never reach the recipient.
+///
+/// Similar to regular payments, you MUST NOT reuse a `payment_preimage` value. See
+/// [`send_payment`] for more information about the risks of duplicate preimage usage.
+///
+/// [`send_payment`]: Self::send_payment
+///
+/// Note that payment_preimage (or a relevant inner pointer) may be NULL or all-0s to represent None
+#[must_use]
+#[no_mangle]
+pub extern "C" fn ChannelManager_send_spontaneous_payment(this_arg: &ChannelManager, route: &crate::lightning::routing::router::Route, mut payment_preimage: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_PaymentHashPaymentSendFailureZ {
+       let mut local_payment_preimage = if payment_preimage.data == [0; 32] { None } else { Some( { ::lightning::ln::PaymentPreimage(payment_preimage.data) }) };
+       let mut ret = unsafe { &*this_arg.inner }.send_spontaneous_payment(unsafe { &*route.inner }, local_payment_preimage);
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::ThirtyTwoBytes { data: o.0 } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::channelmanager::PaymentSendFailure::native_into(e) }).into() };
+       local_ret
+}
+
 /// Call this upon creation of a funding transaction for the given channel.
 ///
 /// Returns an [`APIError::APIMisuseError`] if the funding_transaction spent non-SegWit outputs
@@ -1217,7 +1266,7 @@ pub extern "C" fn ChannelManager_create_inbound_payment(this_arg: &ChannelManage
 /// The [`PaymentHash`] (and corresponding [`PaymentPreimage`]) must be globally unique. This
 /// method may return an Err if another payment with the same payment_hash is still pending.
 ///
-/// `user_payment_id` will be provided back in [`PaymentReceived::user_payment_id`] events to
+/// `user_payment_id` will be provided back in [`PaymentPurpose::InvoicePayment::user_payment_id`] events to
 /// allow tracking of which events correspond with which calls to this and
 /// [`create_inbound_payment`]. `user_payment_id` has no meaning inside of LDK, it is simply
 /// copied to events and otherwise ignored. It may be used to correlate PaymentReceived events
@@ -1251,7 +1300,7 @@ pub extern "C" fn ChannelManager_create_inbound_payment(this_arg: &ChannelManage
 ///
 /// [`create_inbound_payment`]: Self::create_inbound_payment
 /// [`PaymentReceived`]: events::Event::PaymentReceived
-/// [`PaymentReceived::user_payment_id`]: events::Event::PaymentReceived::user_payment_id
+/// [`PaymentPurpose::InvoicePayment::user_payment_id`]: events::PaymentPurpose::InvoicePayment::user_payment_id
 #[must_use]
 #[no_mangle]
 pub extern "C" fn ChannelManager_create_inbound_payment_for_hash(this_arg: &ChannelManager, mut payment_hash: crate::c_types::ThirtyTwoBytes, mut min_value_msat: crate::c_types::derived::COption_u64Z, mut invoice_expiry_delta_secs: u32, mut user_payment_id: u64) -> crate::c_types::derived::CResult_PaymentSecretAPIErrorZ {
index 034f30763f889973232a585a93c5ee97db52dacc..619a41d2bca98b6bcc5a95cd5f7491ac568a7a2a 100644 (file)
@@ -2677,6 +2677,40 @@ pub extern "C" fn NetAddress_clone(orig: &NetAddress) -> NetAddress {
        orig.clone()
 }
 #[no_mangle]
+/// Utility method to constructs a new IPv4-variant NetAddress
+pub extern "C" fn NetAddress_ipv4(addr: crate::c_types::FourBytes, port: u16) -> NetAddress {
+       NetAddress::IPv4 {
+               addr,
+               port,
+       }
+}
+#[no_mangle]
+/// Utility method to constructs a new IPv6-variant NetAddress
+pub extern "C" fn NetAddress_ipv6(addr: crate::c_types::SixteenBytes, port: u16) -> NetAddress {
+       NetAddress::IPv6 {
+               addr,
+               port,
+       }
+}
+#[no_mangle]
+/// Utility method to constructs a new OnionV2-variant NetAddress
+pub extern "C" fn NetAddress_onion_v2(addr: crate::c_types::TenBytes, port: u16) -> NetAddress {
+       NetAddress::OnionV2 {
+               addr,
+               port,
+       }
+}
+#[no_mangle]
+/// Utility method to constructs a new OnionV3-variant NetAddress
+pub extern "C" fn NetAddress_onion_v3(ed25519_pubkey: crate::c_types::ThirtyTwoBytes, checksum: u16, version: u8, port: u16) -> NetAddress {
+       NetAddress::OnionV3 {
+               ed25519_pubkey,
+               checksum,
+               version,
+               port,
+       }
+}
+#[no_mangle]
 /// Serialize the NetAddress object into a byte array which can be read by NetAddress_read
 pub extern "C" fn NetAddress_write(obj: &NetAddress) -> crate::c_types::derived::CVec_u8Z {
        crate::c_types::serialize_obj(&unsafe { &*obj }.to_native())
@@ -4010,6 +4044,8 @@ pub enum ErrorAction {
        /// The peer took some action which made us think they were useless. Disconnect them.
        DisconnectPeer {
                /// An error message which we should make an effort to send before we disconnect.
+               ///
+               /// Note that this (or a relevant inner pointer) may be NULL or all-0s to represent None
                msg: crate::lightning::ln::msgs::ErrorMessage,
        },
        /// The peer did something harmless that we weren't able to process, just log and ignore
@@ -4128,6 +4164,29 @@ pub extern "C" fn ErrorAction_free(this_ptr: ErrorAction) { }
 pub extern "C" fn ErrorAction_clone(orig: &ErrorAction) -> ErrorAction {
        orig.clone()
 }
+#[no_mangle]
+/// Utility method to constructs a new DisconnectPeer-variant ErrorAction
+pub extern "C" fn ErrorAction_disconnect_peer(msg: crate::lightning::ln::msgs::ErrorMessage) -> ErrorAction {
+       ErrorAction::DisconnectPeer {
+               msg,
+       }
+}
+#[no_mangle]
+/// Utility method to constructs a new IgnoreError-variant ErrorAction
+pub extern "C" fn ErrorAction_ignore_error() -> ErrorAction {
+       ErrorAction::IgnoreError}
+#[no_mangle]
+/// Utility method to constructs a new IgnoreAndLog-variant ErrorAction
+pub extern "C" fn ErrorAction_ignore_and_log(a: crate::lightning::util::logger::Level) -> ErrorAction {
+       ErrorAction::IgnoreAndLog(a, )
+}
+#[no_mangle]
+/// Utility method to constructs a new SendErrorMessage-variant ErrorAction
+pub extern "C" fn ErrorAction_send_error_message(msg: crate::lightning::ln::msgs::ErrorMessage) -> ErrorAction {
+       ErrorAction::SendErrorMessage {
+               msg,
+       }
+}
 
 use lightning::ln::msgs::LightningError as nativeLightningErrorImport;
 type nativeLightningError = nativeLightningErrorImport;
@@ -4294,6 +4353,8 @@ pub extern "C" fn CommitmentUpdate_set_update_fail_malformed_htlcs(this_ptr: &mu
        unsafe { &mut *this_ptr.inner }.update_fail_malformed_htlcs = local_val;
 }
 /// An update_fee message which should be sent
+///
+/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[no_mangle]
 pub extern "C" fn CommitmentUpdate_get_update_fee(this_ptr: &CommitmentUpdate) -> crate::lightning::ln::msgs::UpdateFee {
        let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.update_fee;
@@ -4301,6 +4362,8 @@ pub extern "C" fn CommitmentUpdate_get_update_fee(this_ptr: &CommitmentUpdate) -
        local_inner_val
 }
 /// An update_fee message which should be sent
+///
+/// Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[no_mangle]
 pub extern "C" fn CommitmentUpdate_set_update_fee(this_ptr: &mut CommitmentUpdate, mut val: crate::lightning::ln::msgs::UpdateFee) {
        let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) };
@@ -4493,6 +4556,29 @@ pub extern "C" fn HTLCFailChannelUpdate_free(this_ptr: HTLCFailChannelUpdate) {
 pub extern "C" fn HTLCFailChannelUpdate_clone(orig: &HTLCFailChannelUpdate) -> HTLCFailChannelUpdate {
        orig.clone()
 }
+#[no_mangle]
+/// Utility method to constructs a new ChannelUpdateMessage-variant HTLCFailChannelUpdate
+pub extern "C" fn HTLCFailChannelUpdate_channel_update_message(msg: crate::lightning::ln::msgs::ChannelUpdate) -> HTLCFailChannelUpdate {
+       HTLCFailChannelUpdate::ChannelUpdateMessage {
+               msg,
+       }
+}
+#[no_mangle]
+/// Utility method to constructs a new ChannelClosed-variant HTLCFailChannelUpdate
+pub extern "C" fn HTLCFailChannelUpdate_channel_closed(short_channel_id: u64, is_permanent: bool) -> HTLCFailChannelUpdate {
+       HTLCFailChannelUpdate::ChannelClosed {
+               short_channel_id,
+               is_permanent,
+       }
+}
+#[no_mangle]
+/// Utility method to constructs a new NodeFailure-variant HTLCFailChannelUpdate
+pub extern "C" fn HTLCFailChannelUpdate_node_failure(node_id: crate::c_types::PublicKey, is_permanent: bool) -> HTLCFailChannelUpdate {
+       HTLCFailChannelUpdate::NodeFailure {
+               node_id,
+               is_permanent,
+       }
+}
 /// A trait to describe an object which can receive channel messages.
 ///
 /// Messages MAY be called in parallel when they originate from different their_node_ids, however
@@ -4553,9 +4639,37 @@ pub struct ChannelMessageHandler {
 }
 unsafe impl Send for ChannelMessageHandler {}
 unsafe impl Sync for ChannelMessageHandler {}
+#[no_mangle]
+pub(crate) extern "C" fn ChannelMessageHandler_clone_fields(orig: &ChannelMessageHandler) -> ChannelMessageHandler {
+       ChannelMessageHandler {
+               this_arg: orig.this_arg,
+               handle_open_channel: Clone::clone(&orig.handle_open_channel),
+               handle_accept_channel: Clone::clone(&orig.handle_accept_channel),
+               handle_funding_created: Clone::clone(&orig.handle_funding_created),
+               handle_funding_signed: Clone::clone(&orig.handle_funding_signed),
+               handle_funding_locked: Clone::clone(&orig.handle_funding_locked),
+               handle_shutdown: Clone::clone(&orig.handle_shutdown),
+               handle_closing_signed: Clone::clone(&orig.handle_closing_signed),
+               handle_update_add_htlc: Clone::clone(&orig.handle_update_add_htlc),
+               handle_update_fulfill_htlc: Clone::clone(&orig.handle_update_fulfill_htlc),
+               handle_update_fail_htlc: Clone::clone(&orig.handle_update_fail_htlc),
+               handle_update_fail_malformed_htlc: Clone::clone(&orig.handle_update_fail_malformed_htlc),
+               handle_commitment_signed: Clone::clone(&orig.handle_commitment_signed),
+               handle_revoke_and_ack: Clone::clone(&orig.handle_revoke_and_ack),
+               handle_update_fee: Clone::clone(&orig.handle_update_fee),
+               handle_announcement_signatures: Clone::clone(&orig.handle_announcement_signatures),
+               peer_disconnected: Clone::clone(&orig.peer_disconnected),
+               peer_connected: Clone::clone(&orig.peer_connected),
+               handle_channel_reestablish: Clone::clone(&orig.handle_channel_reestablish),
+               handle_channel_update: Clone::clone(&orig.handle_channel_update),
+               handle_error: Clone::clone(&orig.handle_error),
+               MessageSendEventsProvider: crate::lightning::util::events::MessageSendEventsProvider_clone_fields(&orig.MessageSendEventsProvider),
+               free: Clone::clone(&orig.free),
+       }
+}
 impl lightning::util::events::MessageSendEventsProvider for ChannelMessageHandler {
        fn get_and_clear_pending_msg_events(&self) -> Vec<lightning::util::events::MessageSendEvent> {
-               let mut ret = (self.MessageSendEventsProvider.get_and_clear_pending_msg_events)(self.this_arg);
+               let mut ret = (self.MessageSendEventsProvider.get_and_clear_pending_msg_events)(self.MessageSendEventsProvider.this_arg);
                let mut local_ret = Vec::new(); for mut item in ret.into_rust().drain(..) { local_ret.push( { item.into_native() }); };
                local_ret
        }
@@ -4678,6 +4792,8 @@ pub struct RoutingMessageHandler {
        /// starting at the node *after* the provided publickey and including batch_amount entries
        /// immediately higher (as defined by <PublicKey as Ord>::cmp) than starting_point.
        /// If None is provided for starting_point, we start at the first node.
+       ///
+       /// Note that starting_point (or a relevant inner pointer) may be NULL or all-0s to represent None
        #[must_use]
        pub get_next_node_announcements: extern "C" fn (this_arg: *const c_void, starting_point: crate::c_types::PublicKey, batch_amount: u8) -> crate::c_types::derived::CVec_NodeAnnouncementZ,
        /// Called when a connection is established with a peer. This can be used to
@@ -4711,9 +4827,28 @@ pub struct RoutingMessageHandler {
 }
 unsafe impl Send for RoutingMessageHandler {}
 unsafe impl Sync for RoutingMessageHandler {}
+#[no_mangle]
+pub(crate) extern "C" fn RoutingMessageHandler_clone_fields(orig: &RoutingMessageHandler) -> RoutingMessageHandler {
+       RoutingMessageHandler {
+               this_arg: orig.this_arg,
+               handle_node_announcement: Clone::clone(&orig.handle_node_announcement),
+               handle_channel_announcement: Clone::clone(&orig.handle_channel_announcement),
+               handle_channel_update: Clone::clone(&orig.handle_channel_update),
+               handle_htlc_fail_channel_update: Clone::clone(&orig.handle_htlc_fail_channel_update),
+               get_next_channel_announcements: Clone::clone(&orig.get_next_channel_announcements),
+               get_next_node_announcements: Clone::clone(&orig.get_next_node_announcements),
+               sync_routing_table: Clone::clone(&orig.sync_routing_table),
+               handle_reply_channel_range: Clone::clone(&orig.handle_reply_channel_range),
+               handle_reply_short_channel_ids_end: Clone::clone(&orig.handle_reply_short_channel_ids_end),
+               handle_query_channel_range: Clone::clone(&orig.handle_query_channel_range),
+               handle_query_short_channel_ids: Clone::clone(&orig.handle_query_short_channel_ids),
+               MessageSendEventsProvider: crate::lightning::util::events::MessageSendEventsProvider_clone_fields(&orig.MessageSendEventsProvider),
+               free: Clone::clone(&orig.free),
+       }
+}
 impl lightning::util::events::MessageSendEventsProvider for RoutingMessageHandler {
        fn get_and_clear_pending_msg_events(&self) -> Vec<lightning::util::events::MessageSendEvent> {
-               let mut ret = (self.MessageSendEventsProvider.get_and_clear_pending_msg_events)(self.this_arg);
+               let mut ret = (self.MessageSendEventsProvider.get_and_clear_pending_msg_events)(self.MessageSendEventsProvider.this_arg);
                let mut local_ret = Vec::new(); for mut item in ret.into_rust().drain(..) { local_ret.push( { item.into_native() }); };
                local_ret
        }
index c9d1e4835f9e1d68b864cc14e14830c2980a288d..cad056099405deca31539f1f0c5f87885553eb26 100644 (file)
@@ -522,16 +522,28 @@ pub struct SocketDescriptor {
        /// Calculate a succinct non-cryptographic hash for an object given its this_arg pointer.
        /// This is used, for example, for inclusion of this object in a hash map.
        pub hash: extern "C" fn (this_arg: *const c_void) -> u64,
-       /// Creates a copy of the object pointed to by this_arg, for a copy of this SocketDescriptor.
-       /// Note that the ultimate copy of the SocketDescriptor will have all function pointers the same as the original.
-       /// May be NULL if no action needs to be taken, the this_arg pointer will be copied into the new SocketDescriptor.
-       pub clone: Option<extern "C" fn (this_arg: *const c_void) -> *mut c_void>,
+       /// Called, if set, after this SocketDescriptor has been cloned into a duplicate object.
+       /// The new SocketDescriptor is provided, and should be mutated as needed to perform a
+       /// deep copy of the object pointed to by this_arg or avoid any double-freeing.
+       pub cloned: Option<extern "C" fn (new_SocketDescriptor: &mut SocketDescriptor)>,
        /// Frees any resources associated with this object given its this_arg pointer.
        /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
        pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
 }
 unsafe impl Send for SocketDescriptor {}
 unsafe impl Sync for SocketDescriptor {}
+#[no_mangle]
+pub(crate) extern "C" fn SocketDescriptor_clone_fields(orig: &SocketDescriptor) -> SocketDescriptor {
+       SocketDescriptor {
+               this_arg: orig.this_arg,
+               send_data: Clone::clone(&orig.send_data),
+               disconnect_socket: Clone::clone(&orig.disconnect_socket),
+               eq: Clone::clone(&orig.eq),
+               hash: Clone::clone(&orig.hash),
+               cloned: Clone::clone(&orig.cloned),
+               free: Clone::clone(&orig.free),
+       }
+}
 impl std::cmp::Eq for SocketDescriptor {}
 impl std::cmp::PartialEq for SocketDescriptor {
        fn eq(&self, o: &Self) -> bool { (self.eq)(self.this_arg, o) }
@@ -542,15 +554,9 @@ impl std::hash::Hash for SocketDescriptor {
 #[no_mangle]
 /// Creates a copy of a SocketDescriptor
 pub extern "C" fn SocketDescriptor_clone(orig: &SocketDescriptor) -> SocketDescriptor {
-       SocketDescriptor {
-               this_arg: if let Some(f) = orig.clone { (f)(orig.this_arg) } else { orig.this_arg },
-               send_data: Clone::clone(&orig.send_data),
-               disconnect_socket: Clone::clone(&orig.disconnect_socket),
-               eq: Clone::clone(&orig.eq),
-               hash: Clone::clone(&orig.hash),
-               clone: Clone::clone(&orig.clone),
-               free: Clone::clone(&orig.free),
-       }
+       let mut res = SocketDescriptor_clone_fields(orig);
+       if let Some(f) = orig.cloned { (f)(&mut res) };
+       res
 }
 impl Clone for SocketDescriptor {
        fn clone(&self) -> Self {
index 7ce133aa1aca188b7d8728b2657a94cc3fb20218..894d0528a089b2961afb49665e642978f97146dc 100644 (file)
@@ -178,6 +178,8 @@ impl NetGraphMsgHandler {
 /// Chain monitor is used to make sure announced channels exist on-chain,
 /// channel data is correct, and that the announcement is signed with
 /// channel owners' keys.
+///
+/// Note that chain_access (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[must_use]
 #[no_mangle]
 pub extern "C" fn NetGraphMsgHandler_new(mut genesis_hash: crate::c_types::ThirtyTwoBytes, chain_access: *mut crate::lightning::chain::Access, mut logger: crate::lightning::util::logger::Logger) -> NetGraphMsgHandler {
@@ -188,6 +190,8 @@ pub extern "C" fn NetGraphMsgHandler_new(mut genesis_hash: crate::c_types::Thirt
 
 /// Creates a new tracker of the actual state of the network of channels and nodes,
 /// assuming an existing Network Graph.
+///
+/// Note that chain_access (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[must_use]
 #[no_mangle]
 pub extern "C" fn NetGraphMsgHandler_from_net_graph(chain_access: *mut crate::lightning::chain::Access, mut logger: crate::lightning::util::logger::Logger, mut network_graph: crate::lightning::routing::network_graph::NetworkGraph) -> NetGraphMsgHandler {
@@ -199,6 +203,8 @@ pub extern "C" fn NetGraphMsgHandler_from_net_graph(chain_access: *mut crate::li
 /// Adds a provider used to check new announcements. Does not affect
 /// existing announcements unless they are updated.
 /// Add, update or remove the provider would replace the current one.
+///
+/// Note that chain_access (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[no_mangle]
 pub extern "C" fn NetGraphMsgHandler_add_chain_access(this_arg: &mut NetGraphMsgHandler, chain_access: *mut crate::lightning::chain::Access) {
        let mut local_chain_access = if chain_access == std::ptr::null_mut() { None } else { Some( { unsafe { *Box::from_raw(chain_access) } }) };
@@ -470,6 +476,8 @@ pub extern "C" fn DirectionalChannelInfo_set_fees(this_ptr: &mut DirectionalChan
 /// Mostly redundant with the data we store in fields explicitly.
 /// Everything else is useful only for sending out for initial routing sync.
 /// Not stored if contains excess data to prevent DoS.
+///
+/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[no_mangle]
 pub extern "C" fn DirectionalChannelInfo_get_last_update_message(this_ptr: &DirectionalChannelInfo) -> crate::lightning::ln::msgs::ChannelUpdate {
        let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.last_update_message;
@@ -480,6 +488,8 @@ pub extern "C" fn DirectionalChannelInfo_get_last_update_message(this_ptr: &Dire
 /// Mostly redundant with the data we store in fields explicitly.
 /// Everything else is useful only for sending out for initial routing sync.
 /// Not stored if contains excess data to prevent DoS.
+///
+/// Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[no_mangle]
 pub extern "C" fn DirectionalChannelInfo_set_last_update_message(this_ptr: &mut DirectionalChannelInfo, mut val: crate::lightning::ln::msgs::ChannelUpdate) {
        let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) };
@@ -605,6 +615,8 @@ pub extern "C" fn ChannelInfo_set_node_one(this_ptr: &mut ChannelInfo, mut val:
        unsafe { &mut *this_ptr.inner }.node_one = val.into_rust();
 }
 /// Details about the first direction of a channel
+///
+/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[no_mangle]
 pub extern "C" fn ChannelInfo_get_one_to_two(this_ptr: &ChannelInfo) -> crate::lightning::routing::network_graph::DirectionalChannelInfo {
        let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.one_to_two;
@@ -612,6 +624,8 @@ pub extern "C" fn ChannelInfo_get_one_to_two(this_ptr: &ChannelInfo) -> crate::l
        local_inner_val
 }
 /// Details about the first direction of a channel
+///
+/// Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[no_mangle]
 pub extern "C" fn ChannelInfo_set_one_to_two(this_ptr: &mut ChannelInfo, mut val: crate::lightning::routing::network_graph::DirectionalChannelInfo) {
        let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) };
@@ -629,6 +643,8 @@ pub extern "C" fn ChannelInfo_set_node_two(this_ptr: &mut ChannelInfo, mut val:
        unsafe { &mut *this_ptr.inner }.node_two = val.into_rust();
 }
 /// Details about the second direction of a channel
+///
+/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[no_mangle]
 pub extern "C" fn ChannelInfo_get_two_to_one(this_ptr: &ChannelInfo) -> crate::lightning::routing::network_graph::DirectionalChannelInfo {
        let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.two_to_one;
@@ -636,6 +652,8 @@ pub extern "C" fn ChannelInfo_get_two_to_one(this_ptr: &ChannelInfo) -> crate::l
        local_inner_val
 }
 /// Details about the second direction of a channel
+///
+/// Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[no_mangle]
 pub extern "C" fn ChannelInfo_set_two_to_one(this_ptr: &mut ChannelInfo, mut val: crate::lightning::routing::network_graph::DirectionalChannelInfo) {
        let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) };
@@ -658,6 +676,8 @@ pub extern "C" fn ChannelInfo_set_capacity_sats(this_ptr: &mut ChannelInfo, mut
 /// Mostly redundant with the data we store in fields explicitly.
 /// Everything else is useful only for sending out for initial routing sync.
 /// Not stored if contains excess data to prevent DoS.
+///
+/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[no_mangle]
 pub extern "C" fn ChannelInfo_get_announcement_message(this_ptr: &ChannelInfo) -> crate::lightning::ln::msgs::ChannelAnnouncement {
        let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.announcement_message;
@@ -668,6 +688,8 @@ pub extern "C" fn ChannelInfo_get_announcement_message(this_ptr: &ChannelInfo) -
 /// Mostly redundant with the data we store in fields explicitly.
 /// Everything else is useful only for sending out for initial routing sync.
 /// Not stored if contains excess data to prevent DoS.
+///
+/// Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[no_mangle]
 pub extern "C" fn ChannelInfo_set_announcement_message(this_ptr: &mut ChannelInfo, mut val: crate::lightning::ln::msgs::ChannelAnnouncement) {
        let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) };
@@ -953,6 +975,8 @@ pub extern "C" fn NodeAnnouncementInfo_set_addresses(this_ptr: &mut NodeAnnounce
 /// Mostly redundant with the data we store in fields explicitly.
 /// Everything else is useful only for sending out for initial routing sync.
 /// Not stored if contains excess data to prevent DoS.
+///
+/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[no_mangle]
 pub extern "C" fn NodeAnnouncementInfo_get_announcement_message(this_ptr: &NodeAnnouncementInfo) -> crate::lightning::ln::msgs::NodeAnnouncement {
        let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.announcement_message;
@@ -963,6 +987,8 @@ pub extern "C" fn NodeAnnouncementInfo_get_announcement_message(this_ptr: &NodeA
 /// Mostly redundant with the data we store in fields explicitly.
 /// Everything else is useful only for sending out for initial routing sync.
 /// Not stored if contains excess data to prevent DoS.
+///
+/// Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[no_mangle]
 pub extern "C" fn NodeAnnouncementInfo_set_announcement_message(this_ptr: &mut NodeAnnouncementInfo, mut val: crate::lightning::ln::msgs::NodeAnnouncement) {
        let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) };
@@ -1072,6 +1098,8 @@ pub extern "C" fn NodeInfo_set_channels(this_ptr: &mut NodeInfo, mut val: crate:
 /// Lowest fees enabling routing via any of the enabled, known channels to a node.
 /// The two fields (flat and proportional fee) are independent,
 /// meaning they don't have to refer to the same channel.
+///
+/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[no_mangle]
 pub extern "C" fn NodeInfo_get_lowest_inbound_channel_fees(this_ptr: &NodeInfo) -> crate::lightning::routing::network_graph::RoutingFees {
        let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.lowest_inbound_channel_fees;
@@ -1081,6 +1109,8 @@ pub extern "C" fn NodeInfo_get_lowest_inbound_channel_fees(this_ptr: &NodeInfo)
 /// Lowest fees enabling routing via any of the enabled, known channels to a node.
 /// The two fields (flat and proportional fee) are independent,
 /// meaning they don't have to refer to the same channel.
+///
+/// Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[no_mangle]
 pub extern "C" fn NodeInfo_set_lowest_inbound_channel_fees(this_ptr: &mut NodeInfo, mut val: crate::lightning::routing::network_graph::RoutingFees) {
        let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) };
@@ -1089,6 +1119,8 @@ pub extern "C" fn NodeInfo_set_lowest_inbound_channel_fees(this_ptr: &mut NodeIn
 /// More information about a node from node_announcement.
 /// Optional because we store a Node entry after learning about it from
 /// a channel announcement, but before receiving a node announcement.
+///
+/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[no_mangle]
 pub extern "C" fn NodeInfo_get_announcement_info(this_ptr: &NodeInfo) -> crate::lightning::routing::network_graph::NodeAnnouncementInfo {
        let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.announcement_info;
@@ -1098,6 +1130,8 @@ pub extern "C" fn NodeInfo_get_announcement_info(this_ptr: &NodeInfo) -> crate::
 /// More information about a node from node_announcement.
 /// Optional because we store a Node entry after learning about it from
 /// a channel announcement, but before receiving a node announcement.
+///
+/// Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[no_mangle]
 pub extern "C" fn NodeInfo_set_announcement_info(this_ptr: &mut NodeInfo, mut val: crate::lightning::routing::network_graph::NodeAnnouncementInfo) {
        let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) };
@@ -1209,6 +1243,8 @@ pub extern "C" fn NetworkGraph_update_node_from_unsigned_announcement(this_arg:
 ///
 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
 /// the corresponding UTXO exists on chain and is correctly-formatted.
+///
+/// Note that chain_access (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[must_use]
 #[no_mangle]
 pub extern "C" fn NetworkGraph_update_channel_from_announcement(this_arg: &mut NetworkGraph, msg: &crate::lightning::ln::msgs::ChannelAnnouncement, chain_access: *mut crate::lightning::chain::Access) -> crate::c_types::derived::CResult_NoneLightningErrorZ {
@@ -1224,6 +1260,8 @@ pub extern "C" fn NetworkGraph_update_channel_from_announcement(this_arg: &mut N
 ///
 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
 /// the corresponding UTXO exists on chain and is correctly-formatted.
+///
+/// Note that chain_access (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[must_use]
 #[no_mangle]
 pub extern "C" fn NetworkGraph_update_channel_from_unsigned_announcement(this_arg: &mut NetworkGraph, msg: &crate::lightning::ln::msgs::UnsignedChannelAnnouncement, chain_access: *mut crate::lightning::chain::Access) -> crate::c_types::derived::CResult_NoneLightningErrorZ {
index 7022f5033802ab34eb06a9067bba740b0691df37..ad15a3513c3b472bffd43b1d89f1a173b079cb63 100644 (file)
@@ -517,6 +517,20 @@ pub(crate) extern "C" fn RouteHintHop_clone_void(this_ptr: *const c_void) -> *mu
 pub extern "C" fn RouteHintHop_clone(orig: &RouteHintHop) -> RouteHintHop {
        orig.clone()
 }
+/// Gets a keysend route from us (payer) to the given target node (payee). This is needed because
+/// keysend payments do not have an invoice from which to pull the payee's supported features, which
+/// makes it tricky to otherwise supply the `payee_features` parameter of `get_route`.
+///
+/// Note that first_hops (or a relevant inner pointer) may be NULL or all-0s to represent None
+#[no_mangle]
+pub extern "C" fn get_keysend_route(mut our_node_id: crate::c_types::PublicKey, network: &crate::lightning::routing::network_graph::NetworkGraph, mut payee: crate::c_types::PublicKey, first_hops: *mut crate::c_types::derived::CVec_ChannelDetailsZ, mut last_hops: crate::c_types::derived::CVec_RouteHintZ, mut final_value_msat: u64, mut final_cltv: u32, mut logger: crate::lightning::util::logger::Logger) -> crate::c_types::derived::CResult_RouteLightningErrorZ {
+       let mut local_first_hops_base = if first_hops == std::ptr::null_mut() { None } else { Some( { let mut local_first_hops_0 = Vec::new(); for mut item in unsafe { &mut *first_hops }.as_slice().iter() { local_first_hops_0.push( { unsafe { &*item.inner } }); }; local_first_hops_0 }) }; let mut local_first_hops = local_first_hops_base.as_ref().map(|a| &a[..]);
+       let mut local_last_hops = Vec::new(); for mut item in last_hops.as_slice().iter() { local_last_hops.push( { unsafe { &*item.inner } }); };
+       let mut ret = lightning::routing::router::get_keysend_route(&our_node_id.into_rust(), unsafe { &*network.inner }, &payee.into_rust(), local_first_hops, &local_last_hops[..], final_value_msat, final_cltv, logger);
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::routing::router::Route { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_ret
+}
+
 /// Gets a route from us (payer) to the given target node (payee).
 ///
 /// If the payee provided features in their invoice, they should be provided via payee_features.
@@ -536,6 +550,9 @@ pub extern "C" fn RouteHintHop_clone(orig: &RouteHintHop) -> RouteHintHop {
 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
 /// equal), however the enabled/disabled bit on such channels as well as the
 /// htlc_minimum_msat/htlc_maximum_msat *are* checked as they may change based on the receiving node.
+///
+/// Note that payee_features (or a relevant inner pointer) may be NULL or all-0s to represent None
+/// Note that first_hops (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[no_mangle]
 pub extern "C" fn get_route(mut our_node_id: crate::c_types::PublicKey, network: &crate::lightning::routing::network_graph::NetworkGraph, mut payee: crate::c_types::PublicKey, mut payee_features: crate::lightning::ln::features::InvoiceFeatures, first_hops: *mut crate::c_types::derived::CVec_ChannelDetailsZ, mut last_hops: crate::c_types::derived::CVec_RouteHintZ, mut final_value_msat: u64, mut final_cltv: u32, mut logger: crate::lightning::util::logger::Logger) -> crate::c_types::derived::CResult_RouteLightningErrorZ {
        let mut local_payee_features = if payee_features.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(payee_features.take_inner()) } }) };
index 81faa98f461e08b9e4f2091e9cf28229dbf960bd..27d79c2bf72c32f456a00b97e99b626d24bc21a6 100644 (file)
@@ -180,3 +180,36 @@ pub extern "C" fn APIError_free(this_ptr: APIError) { }
 pub extern "C" fn APIError_clone(orig: &APIError) -> APIError {
        orig.clone()
 }
+#[no_mangle]
+/// Utility method to constructs a new APIMisuseError-variant APIError
+pub extern "C" fn APIError_apimisuse_error(err: crate::c_types::Str) -> APIError {
+       APIError::APIMisuseError {
+               err,
+       }
+}
+#[no_mangle]
+/// Utility method to constructs a new FeeRateTooHigh-variant APIError
+pub extern "C" fn APIError_fee_rate_too_high(err: crate::c_types::Str, feerate: u32) -> APIError {
+       APIError::FeeRateTooHigh {
+               err,
+               feerate,
+       }
+}
+#[no_mangle]
+/// Utility method to constructs a new RouteError-variant APIError
+pub extern "C" fn APIError_route_error(err: crate::c_types::Str) -> APIError {
+       APIError::RouteError {
+               err,
+       }
+}
+#[no_mangle]
+/// Utility method to constructs a new ChannelUnavailable-variant APIError
+pub extern "C" fn APIError_channel_unavailable(err: crate::c_types::Str) -> APIError {
+       APIError::ChannelUnavailable {
+               err,
+       }
+}
+#[no_mangle]
+/// Utility method to constructs a new MonitorUpdateFailed-variant APIError
+pub extern "C" fn APIError_monitor_update_failed() -> APIError {
+       APIError::MonitorUpdateFailed}
index 7961f623bbc456c5ab50b8398cc3ddd0feca46fa..491812dc9e5dabf86ee8d4828b64ab8ddc7acede 100644 (file)
@@ -18,6 +18,153 @@ use std::ffi::c_void;
 use bitcoin::hashes::Hash;
 use crate::c_types::*;
 
+/// Some information provided on receipt of payment depends on whether the payment received is a
+/// spontaneous payment or a \"conventional\" lightning payment that's paying an invoice.
+#[must_use]
+#[derive(Clone)]
+#[repr(C)]
+pub enum PaymentPurpose {
+       /// Information for receiving a payment that we generated an invoice for.
+       InvoicePayment {
+               /// The preimage to the payment_hash, if the payment hash (and secret) were fetched via
+               /// [`ChannelManager::create_inbound_payment`]. If provided, this can be handed directly to
+               /// [`ChannelManager::claim_funds`].
+               ///
+               /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
+               /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
+               ///
+               /// Note that this (or a relevant inner pointer) may be NULL or all-0s to represent None
+               payment_preimage: crate::c_types::ThirtyTwoBytes,
+               /// The \"payment secret\". This authenticates the sender to the recipient, preventing a
+               /// number of deanonymization attacks during the routing process.
+               /// It is provided here for your reference, however its accuracy is enforced directly by
+               /// [`ChannelManager`] using the values you previously provided to
+               /// [`ChannelManager::create_inbound_payment`] or
+               /// [`ChannelManager::create_inbound_payment_for_hash`].
+               ///
+               /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
+               /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
+               /// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
+               payment_secret: crate::c_types::ThirtyTwoBytes,
+               /// This is the `user_payment_id` which was provided to
+               /// [`ChannelManager::create_inbound_payment_for_hash`] or
+               /// [`ChannelManager::create_inbound_payment`]. It has no meaning inside of LDK and is
+               /// simply copied here. It may be used to correlate PaymentReceived events with invoice
+               /// metadata stored elsewhere.
+               ///
+               /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
+               /// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
+               user_payment_id: u64,
+       },
+       /// Because this is a spontaneous payment, the payer generated their own preimage rather than us
+       /// (the payee) providing a preimage.
+       SpontaneousPayment(crate::c_types::ThirtyTwoBytes),
+}
+use lightning::util::events::PaymentPurpose as nativePaymentPurpose;
+impl PaymentPurpose {
+       #[allow(unused)]
+       pub(crate) fn to_native(&self) -> nativePaymentPurpose {
+               match self {
+                       PaymentPurpose::InvoicePayment {ref payment_preimage, ref payment_secret, ref user_payment_id, } => {
+                               let mut payment_preimage_nonref = (*payment_preimage).clone();
+                               let mut local_payment_preimage_nonref = if payment_preimage_nonref.data == [0; 32] { None } else { Some( { ::lightning::ln::PaymentPreimage(payment_preimage_nonref.data) }) };
+                               let mut payment_secret_nonref = (*payment_secret).clone();
+                               let mut user_payment_id_nonref = (*user_payment_id).clone();
+                               nativePaymentPurpose::InvoicePayment {
+                                       payment_preimage: local_payment_preimage_nonref,
+                                       payment_secret: ::lightning::ln::PaymentSecret(payment_secret_nonref.data),
+                                       user_payment_id: user_payment_id_nonref,
+                               }
+                       },
+                       PaymentPurpose::SpontaneousPayment (ref a, ) => {
+                               let mut a_nonref = (*a).clone();
+                               nativePaymentPurpose::SpontaneousPayment (
+                                       ::lightning::ln::PaymentPreimage(a_nonref.data),
+                               )
+                       },
+               }
+       }
+       #[allow(unused)]
+       pub(crate) fn into_native(self) -> nativePaymentPurpose {
+               match self {
+                       PaymentPurpose::InvoicePayment {mut payment_preimage, mut payment_secret, mut user_payment_id, } => {
+                               let mut local_payment_preimage = if payment_preimage.data == [0; 32] { None } else { Some( { ::lightning::ln::PaymentPreimage(payment_preimage.data) }) };
+                               nativePaymentPurpose::InvoicePayment {
+                                       payment_preimage: local_payment_preimage,
+                                       payment_secret: ::lightning::ln::PaymentSecret(payment_secret.data),
+                                       user_payment_id: user_payment_id,
+                               }
+                       },
+                       PaymentPurpose::SpontaneousPayment (mut a, ) => {
+                               nativePaymentPurpose::SpontaneousPayment (
+                                       ::lightning::ln::PaymentPreimage(a.data),
+                               )
+                       },
+               }
+       }
+       #[allow(unused)]
+       pub(crate) fn from_native(native: &nativePaymentPurpose) -> Self {
+               match native {
+                       nativePaymentPurpose::InvoicePayment {ref payment_preimage, ref payment_secret, ref user_payment_id, } => {
+                               let mut payment_preimage_nonref = (*payment_preimage).clone();
+                               let mut local_payment_preimage_nonref = if payment_preimage_nonref.is_none() { crate::c_types::ThirtyTwoBytes::null() } else {  { crate::c_types::ThirtyTwoBytes { data: (payment_preimage_nonref.unwrap()).0 } } };
+                               let mut payment_secret_nonref = (*payment_secret).clone();
+                               let mut user_payment_id_nonref = (*user_payment_id).clone();
+                               PaymentPurpose::InvoicePayment {
+                                       payment_preimage: local_payment_preimage_nonref,
+                                       payment_secret: crate::c_types::ThirtyTwoBytes { data: payment_secret_nonref.0 },
+                                       user_payment_id: user_payment_id_nonref,
+                               }
+                       },
+                       nativePaymentPurpose::SpontaneousPayment (ref a, ) => {
+                               let mut a_nonref = (*a).clone();
+                               PaymentPurpose::SpontaneousPayment (
+                                       crate::c_types::ThirtyTwoBytes { data: a_nonref.0 },
+                               )
+                       },
+               }
+       }
+       #[allow(unused)]
+       pub(crate) fn native_into(native: nativePaymentPurpose) -> Self {
+               match native {
+                       nativePaymentPurpose::InvoicePayment {mut payment_preimage, mut payment_secret, mut user_payment_id, } => {
+                               let mut local_payment_preimage = if payment_preimage.is_none() { crate::c_types::ThirtyTwoBytes::null() } else {  { crate::c_types::ThirtyTwoBytes { data: (payment_preimage.unwrap()).0 } } };
+                               PaymentPurpose::InvoicePayment {
+                                       payment_preimage: local_payment_preimage,
+                                       payment_secret: crate::c_types::ThirtyTwoBytes { data: payment_secret.0 },
+                                       user_payment_id: user_payment_id,
+                               }
+                       },
+                       nativePaymentPurpose::SpontaneousPayment (mut a, ) => {
+                               PaymentPurpose::SpontaneousPayment (
+                                       crate::c_types::ThirtyTwoBytes { data: a.0 },
+                               )
+                       },
+               }
+       }
+}
+/// Frees any resources used by the PaymentPurpose
+#[no_mangle]
+pub extern "C" fn PaymentPurpose_free(this_ptr: PaymentPurpose) { }
+/// Creates a copy of the PaymentPurpose
+#[no_mangle]
+pub extern "C" fn PaymentPurpose_clone(orig: &PaymentPurpose) -> PaymentPurpose {
+       orig.clone()
+}
+#[no_mangle]
+/// Utility method to constructs a new InvoicePayment-variant PaymentPurpose
+pub extern "C" fn PaymentPurpose_invoice_payment(payment_preimage: crate::c_types::ThirtyTwoBytes, payment_secret: crate::c_types::ThirtyTwoBytes, user_payment_id: u64) -> PaymentPurpose {
+       PaymentPurpose::InvoicePayment {
+               payment_preimage,
+               payment_secret,
+               user_payment_id,
+       }
+}
+#[no_mangle]
+/// Utility method to constructs a new SpontaneousPayment-variant PaymentPurpose
+pub extern "C" fn PaymentPurpose_spontaneous_payment(a: crate::c_types::ThirtyTwoBytes) -> PaymentPurpose {
+       PaymentPurpose::SpontaneousPayment(a, )
+}
 /// An Event which you should probably take some action in response to.
 ///
 /// Note that while Writeable and Readable are implemented for Event, you probably shouldn't use
@@ -56,37 +203,13 @@ pub enum Event {
        PaymentReceived {
                /// The hash for which the preimage should be handed to the ChannelManager.
                payment_hash: crate::c_types::ThirtyTwoBytes,
-               /// The preimage to the payment_hash, if the payment hash (and secret) were fetched via
-               /// [`ChannelManager::create_inbound_payment`]. If provided, this can be handed directly to
-               /// [`ChannelManager::claim_funds`].
-               ///
-               /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
-               /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
-               payment_preimage: crate::c_types::ThirtyTwoBytes,
-               /// The \"payment secret\". This authenticates the sender to the recipient, preventing a
-               /// number of deanonymization attacks during the routing process.
-               /// It is provided here for your reference, however its accuracy is enforced directly by
-               /// [`ChannelManager`] using the values you previously provided to
-               /// [`ChannelManager::create_inbound_payment`] or
-               /// [`ChannelManager::create_inbound_payment_for_hash`].
-               ///
-               /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
-               /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
-               /// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
-               payment_secret: crate::c_types::ThirtyTwoBytes,
                /// The value, in thousandths of a satoshi, that this payment is for. Note that you must
                /// compare this to the expected value before accepting the payment (as otherwise you are
                /// providing proof-of-payment for less than the value you expected!).
                amt: u64,
-               /// This is the `user_payment_id` which was provided to
-               /// [`ChannelManager::create_inbound_payment_for_hash`] or
-               /// [`ChannelManager::create_inbound_payment`]. It has no meaning inside of LDK and is
-               /// simply copied here. It may be used to correlate PaymentReceived events with invoice
-               /// metadata stored elsewhere.
-               ///
-               /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
-               /// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
-               user_payment_id: u64,
+               /// Information for claiming this received payment, based on whether the purpose of the
+               /// payment is to pay an invoice or to send a spontaneous payment.
+               purpose: crate::lightning::util::events::PaymentPurpose,
        },
        /// Indicates an outbound payment we made succeeded (ie it made it all the way to its target
        /// and we got back the payment preimage for it).
@@ -124,6 +247,27 @@ pub enum Event {
                /// The outputs which you should store as spendable by you.
                outputs: crate::c_types::derived::CVec_SpendableOutputDescriptorZ,
        },
+       /// This event is generated when a payment has been successfully forwarded through us and a
+       /// forwarding fee earned.
+       PaymentForwarded {
+               /// The fee, in milli-satoshis, which was earned as a result of the payment.
+               ///
+               /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
+               /// was pending, the amount the next hop claimed will have been rounded down to the nearest
+               /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
+               /// claimed the full value in millisatoshis from the source. In this case,
+               /// `claim_from_onchain_tx` will be set.
+               ///
+               /// If the channel which sent us the payment has been force-closed, we will claim the funds
+               /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
+               /// fees which we will spend and will instead set this to `None`. It is possible duplicate
+               /// `PaymentForwarded` events are generated for the same payment iff `fee_earned_msat` is
+               /// `None`.
+               fee_earned_msat: crate::c_types::derived::COption_u64Z,
+               /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
+               /// transaction.
+               claim_from_onchain_tx: bool,
+       },
 }
 use lightning::util::events::Event as nativeEvent;
 impl Event {
@@ -142,19 +286,14 @@ impl Event {
                                        user_channel_id: user_channel_id_nonref,
                                }
                        },
-                       Event::PaymentReceived {ref payment_hash, ref payment_preimage, ref payment_secret, ref amt, ref user_payment_id, } => {
+                       Event::PaymentReceived {ref payment_hash, ref amt, ref purpose, } => {
                                let mut payment_hash_nonref = (*payment_hash).clone();
-                               let mut payment_preimage_nonref = (*payment_preimage).clone();
-                               let mut local_payment_preimage_nonref = if payment_preimage_nonref.data == [0; 32] { None } else { Some( { ::lightning::ln::PaymentPreimage(payment_preimage_nonref.data) }) };
-                               let mut payment_secret_nonref = (*payment_secret).clone();
                                let mut amt_nonref = (*amt).clone();
-                               let mut user_payment_id_nonref = (*user_payment_id).clone();
+                               let mut purpose_nonref = (*purpose).clone();
                                nativeEvent::PaymentReceived {
                                        payment_hash: ::lightning::ln::PaymentHash(payment_hash_nonref.data),
-                                       payment_preimage: local_payment_preimage_nonref,
-                                       payment_secret: ::lightning::ln::PaymentSecret(payment_secret_nonref.data),
                                        amt: amt_nonref,
-                                       user_payment_id: user_payment_id_nonref,
+                                       purpose: purpose_nonref.into_native(),
                                }
                        },
                        Event::PaymentSent {ref payment_preimage, } => {
@@ -184,6 +323,15 @@ impl Event {
                                        outputs: local_outputs_nonref,
                                }
                        },
+                       Event::PaymentForwarded {ref fee_earned_msat, ref claim_from_onchain_tx, } => {
+                               let mut fee_earned_msat_nonref = (*fee_earned_msat).clone();
+                               let mut local_fee_earned_msat_nonref = if fee_earned_msat_nonref.is_some() { Some( { fee_earned_msat_nonref.take() }) } else { None };
+                               let mut claim_from_onchain_tx_nonref = (*claim_from_onchain_tx).clone();
+                               nativeEvent::PaymentForwarded {
+                                       fee_earned_msat: local_fee_earned_msat_nonref,
+                                       claim_from_onchain_tx: claim_from_onchain_tx_nonref,
+                               }
+                       },
                }
        }
        #[allow(unused)]
@@ -197,14 +345,11 @@ impl Event {
                                        user_channel_id: user_channel_id,
                                }
                        },
-                       Event::PaymentReceived {mut payment_hash, mut payment_preimage, mut payment_secret, mut amt, mut user_payment_id, } => {
-                               let mut local_payment_preimage = if payment_preimage.data == [0; 32] { None } else { Some( { ::lightning::ln::PaymentPreimage(payment_preimage.data) }) };
+                       Event::PaymentReceived {mut payment_hash, mut amt, mut purpose, } => {
                                nativeEvent::PaymentReceived {
                                        payment_hash: ::lightning::ln::PaymentHash(payment_hash.data),
-                                       payment_preimage: local_payment_preimage,
-                                       payment_secret: ::lightning::ln::PaymentSecret(payment_secret.data),
                                        amt: amt,
-                                       user_payment_id: user_payment_id,
+                                       purpose: purpose.into_native(),
                                }
                        },
                        Event::PaymentSent {mut payment_preimage, } => {
@@ -229,6 +374,13 @@ impl Event {
                                        outputs: local_outputs,
                                }
                        },
+                       Event::PaymentForwarded {mut fee_earned_msat, mut claim_from_onchain_tx, } => {
+                               let mut local_fee_earned_msat = if fee_earned_msat.is_some() { Some( { fee_earned_msat.take() }) } else { None };
+                               nativeEvent::PaymentForwarded {
+                                       fee_earned_msat: local_fee_earned_msat,
+                                       claim_from_onchain_tx: claim_from_onchain_tx,
+                               }
+                       },
                }
        }
        #[allow(unused)]
@@ -246,19 +398,14 @@ impl Event {
                                        user_channel_id: user_channel_id_nonref,
                                }
                        },
-                       nativeEvent::PaymentReceived {ref payment_hash, ref payment_preimage, ref payment_secret, ref amt, ref user_payment_id, } => {
+                       nativeEvent::PaymentReceived {ref payment_hash, ref amt, ref purpose, } => {
                                let mut payment_hash_nonref = (*payment_hash).clone();
-                               let mut payment_preimage_nonref = (*payment_preimage).clone();
-                               let mut local_payment_preimage_nonref = if payment_preimage_nonref.is_none() { crate::c_types::ThirtyTwoBytes::null() } else {  { crate::c_types::ThirtyTwoBytes { data: (payment_preimage_nonref.unwrap()).0 } } };
-                               let mut payment_secret_nonref = (*payment_secret).clone();
                                let mut amt_nonref = (*amt).clone();
-                               let mut user_payment_id_nonref = (*user_payment_id).clone();
+                               let mut purpose_nonref = (*purpose).clone();
                                Event::PaymentReceived {
                                        payment_hash: crate::c_types::ThirtyTwoBytes { data: payment_hash_nonref.0 },
-                                       payment_preimage: local_payment_preimage_nonref,
-                                       payment_secret: crate::c_types::ThirtyTwoBytes { data: payment_secret_nonref.0 },
                                        amt: amt_nonref,
-                                       user_payment_id: user_payment_id_nonref,
+                                       purpose: crate::lightning::util::events::PaymentPurpose::native_into(purpose_nonref),
                                }
                        },
                        nativeEvent::PaymentSent {ref payment_preimage, } => {
@@ -288,6 +435,15 @@ impl Event {
                                        outputs: local_outputs_nonref.into(),
                                }
                        },
+                       nativeEvent::PaymentForwarded {ref fee_earned_msat, ref claim_from_onchain_tx, } => {
+                               let mut fee_earned_msat_nonref = (*fee_earned_msat).clone();
+                               let mut local_fee_earned_msat_nonref = if fee_earned_msat_nonref.is_none() { crate::c_types::derived::COption_u64Z::None } else {  { crate::c_types::derived::COption_u64Z::Some(fee_earned_msat_nonref.unwrap()) } };
+                               let mut claim_from_onchain_tx_nonref = (*claim_from_onchain_tx).clone();
+                               Event::PaymentForwarded {
+                                       fee_earned_msat: local_fee_earned_msat_nonref,
+                                       claim_from_onchain_tx: claim_from_onchain_tx_nonref,
+                               }
+                       },
                }
        }
        #[allow(unused)]
@@ -301,14 +457,11 @@ impl Event {
                                        user_channel_id: user_channel_id,
                                }
                        },
-                       nativeEvent::PaymentReceived {mut payment_hash, mut payment_preimage, mut payment_secret, mut amt, mut user_payment_id, } => {
-                               let mut local_payment_preimage = if payment_preimage.is_none() { crate::c_types::ThirtyTwoBytes::null() } else {  { crate::c_types::ThirtyTwoBytes { data: (payment_preimage.unwrap()).0 } } };
+                       nativeEvent::PaymentReceived {mut payment_hash, mut amt, mut purpose, } => {
                                Event::PaymentReceived {
                                        payment_hash: crate::c_types::ThirtyTwoBytes { data: payment_hash.0 },
-                                       payment_preimage: local_payment_preimage,
-                                       payment_secret: crate::c_types::ThirtyTwoBytes { data: payment_secret.0 },
                                        amt: amt,
-                                       user_payment_id: user_payment_id,
+                                       purpose: crate::lightning::util::events::PaymentPurpose::native_into(purpose),
                                }
                        },
                        nativeEvent::PaymentSent {mut payment_preimage, } => {
@@ -333,6 +486,13 @@ impl Event {
                                        outputs: local_outputs.into(),
                                }
                        },
+                       nativeEvent::PaymentForwarded {mut fee_earned_msat, mut claim_from_onchain_tx, } => {
+                               let mut local_fee_earned_msat = if fee_earned_msat.is_none() { crate::c_types::derived::COption_u64Z::None } else {  { crate::c_types::derived::COption_u64Z::Some(fee_earned_msat.unwrap()) } };
+                               Event::PaymentForwarded {
+                                       fee_earned_msat: local_fee_earned_msat,
+                                       claim_from_onchain_tx: claim_from_onchain_tx,
+                               }
+                       },
                }
        }
 }
@@ -345,6 +505,62 @@ pub extern "C" fn Event_clone(orig: &Event) -> Event {
        orig.clone()
 }
 #[no_mangle]
+/// Utility method to constructs a new FundingGenerationReady-variant Event
+pub extern "C" fn Event_funding_generation_ready(temporary_channel_id: crate::c_types::ThirtyTwoBytes, channel_value_satoshis: u64, output_script: crate::c_types::derived::CVec_u8Z, user_channel_id: u64) -> Event {
+       Event::FundingGenerationReady {
+               temporary_channel_id,
+               channel_value_satoshis,
+               output_script,
+               user_channel_id,
+       }
+}
+#[no_mangle]
+/// Utility method to constructs a new PaymentReceived-variant Event
+pub extern "C" fn Event_payment_received(payment_hash: crate::c_types::ThirtyTwoBytes, amt: u64, purpose: crate::lightning::util::events::PaymentPurpose) -> Event {
+       Event::PaymentReceived {
+               payment_hash,
+               amt,
+               purpose,
+       }
+}
+#[no_mangle]
+/// Utility method to constructs a new PaymentSent-variant Event
+pub extern "C" fn Event_payment_sent(payment_preimage: crate::c_types::ThirtyTwoBytes) -> Event {
+       Event::PaymentSent {
+               payment_preimage,
+       }
+}
+#[no_mangle]
+/// Utility method to constructs a new PaymentFailed-variant Event
+pub extern "C" fn Event_payment_failed(payment_hash: crate::c_types::ThirtyTwoBytes, rejected_by_dest: bool) -> Event {
+       Event::PaymentFailed {
+               payment_hash,
+               rejected_by_dest,
+       }
+}
+#[no_mangle]
+/// Utility method to constructs a new PendingHTLCsForwardable-variant Event
+pub extern "C" fn Event_pending_htlcs_forwardable(time_forwardable: u64) -> Event {
+       Event::PendingHTLCsForwardable {
+               time_forwardable,
+       }
+}
+#[no_mangle]
+/// Utility method to constructs a new SpendableOutputs-variant Event
+pub extern "C" fn Event_spendable_outputs(outputs: crate::c_types::derived::CVec_SpendableOutputDescriptorZ) -> Event {
+       Event::SpendableOutputs {
+               outputs,
+       }
+}
+#[no_mangle]
+/// Utility method to constructs a new PaymentForwarded-variant Event
+pub extern "C" fn Event_payment_forwarded(fee_earned_msat: crate::c_types::derived::COption_u64Z, claim_from_onchain_tx: bool) -> Event {
+       Event::PaymentForwarded {
+               fee_earned_msat,
+               claim_from_onchain_tx,
+       }
+}
+#[no_mangle]
 /// Serialize the Event object into a byte array which can be read by Event_read
 pub extern "C" fn Event_write(obj: &Event) -> crate::c_types::derived::CVec_u8Z {
        crate::c_types::serialize_obj(&unsafe { &*obj }.to_native())
@@ -1079,6 +1295,163 @@ pub extern "C" fn MessageSendEvent_free(this_ptr: MessageSendEvent) { }
 pub extern "C" fn MessageSendEvent_clone(orig: &MessageSendEvent) -> MessageSendEvent {
        orig.clone()
 }
+#[no_mangle]
+/// Utility method to constructs a new SendAcceptChannel-variant MessageSendEvent
+pub extern "C" fn MessageSendEvent_send_accept_channel(node_id: crate::c_types::PublicKey, msg: crate::lightning::ln::msgs::AcceptChannel) -> MessageSendEvent {
+       MessageSendEvent::SendAcceptChannel {
+               node_id,
+               msg,
+       }
+}
+#[no_mangle]
+/// Utility method to constructs a new SendOpenChannel-variant MessageSendEvent
+pub extern "C" fn MessageSendEvent_send_open_channel(node_id: crate::c_types::PublicKey, msg: crate::lightning::ln::msgs::OpenChannel) -> MessageSendEvent {
+       MessageSendEvent::SendOpenChannel {
+               node_id,
+               msg,
+       }
+}
+#[no_mangle]
+/// Utility method to constructs a new SendFundingCreated-variant MessageSendEvent
+pub extern "C" fn MessageSendEvent_send_funding_created(node_id: crate::c_types::PublicKey, msg: crate::lightning::ln::msgs::FundingCreated) -> MessageSendEvent {
+       MessageSendEvent::SendFundingCreated {
+               node_id,
+               msg,
+       }
+}
+#[no_mangle]
+/// Utility method to constructs a new SendFundingSigned-variant MessageSendEvent
+pub extern "C" fn MessageSendEvent_send_funding_signed(node_id: crate::c_types::PublicKey, msg: crate::lightning::ln::msgs::FundingSigned) -> MessageSendEvent {
+       MessageSendEvent::SendFundingSigned {
+               node_id,
+               msg,
+       }
+}
+#[no_mangle]
+/// Utility method to constructs a new SendFundingLocked-variant MessageSendEvent
+pub extern "C" fn MessageSendEvent_send_funding_locked(node_id: crate::c_types::PublicKey, msg: crate::lightning::ln::msgs::FundingLocked) -> MessageSendEvent {
+       MessageSendEvent::SendFundingLocked {
+               node_id,
+               msg,
+       }
+}
+#[no_mangle]
+/// Utility method to constructs a new SendAnnouncementSignatures-variant MessageSendEvent
+pub extern "C" fn MessageSendEvent_send_announcement_signatures(node_id: crate::c_types::PublicKey, msg: crate::lightning::ln::msgs::AnnouncementSignatures) -> MessageSendEvent {
+       MessageSendEvent::SendAnnouncementSignatures {
+               node_id,
+               msg,
+       }
+}
+#[no_mangle]
+/// Utility method to constructs a new UpdateHTLCs-variant MessageSendEvent
+pub extern "C" fn MessageSendEvent_update_htlcs(node_id: crate::c_types::PublicKey, updates: crate::lightning::ln::msgs::CommitmentUpdate) -> MessageSendEvent {
+       MessageSendEvent::UpdateHTLCs {
+               node_id,
+               updates,
+       }
+}
+#[no_mangle]
+/// Utility method to constructs a new SendRevokeAndACK-variant MessageSendEvent
+pub extern "C" fn MessageSendEvent_send_revoke_and_ack(node_id: crate::c_types::PublicKey, msg: crate::lightning::ln::msgs::RevokeAndACK) -> MessageSendEvent {
+       MessageSendEvent::SendRevokeAndACK {
+               node_id,
+               msg,
+       }
+}
+#[no_mangle]
+/// Utility method to constructs a new SendClosingSigned-variant MessageSendEvent
+pub extern "C" fn MessageSendEvent_send_closing_signed(node_id: crate::c_types::PublicKey, msg: crate::lightning::ln::msgs::ClosingSigned) -> MessageSendEvent {
+       MessageSendEvent::SendClosingSigned {
+               node_id,
+               msg,
+       }
+}
+#[no_mangle]
+/// Utility method to constructs a new SendShutdown-variant MessageSendEvent
+pub extern "C" fn MessageSendEvent_send_shutdown(node_id: crate::c_types::PublicKey, msg: crate::lightning::ln::msgs::Shutdown) -> MessageSendEvent {
+       MessageSendEvent::SendShutdown {
+               node_id,
+               msg,
+       }
+}
+#[no_mangle]
+/// Utility method to constructs a new SendChannelReestablish-variant MessageSendEvent
+pub extern "C" fn MessageSendEvent_send_channel_reestablish(node_id: crate::c_types::PublicKey, msg: crate::lightning::ln::msgs::ChannelReestablish) -> MessageSendEvent {
+       MessageSendEvent::SendChannelReestablish {
+               node_id,
+               msg,
+       }
+}
+#[no_mangle]
+/// Utility method to constructs a new BroadcastChannelAnnouncement-variant MessageSendEvent
+pub extern "C" fn MessageSendEvent_broadcast_channel_announcement(msg: crate::lightning::ln::msgs::ChannelAnnouncement, update_msg: crate::lightning::ln::msgs::ChannelUpdate) -> MessageSendEvent {
+       MessageSendEvent::BroadcastChannelAnnouncement {
+               msg,
+               update_msg,
+       }
+}
+#[no_mangle]
+/// Utility method to constructs a new BroadcastNodeAnnouncement-variant MessageSendEvent
+pub extern "C" fn MessageSendEvent_broadcast_node_announcement(msg: crate::lightning::ln::msgs::NodeAnnouncement) -> MessageSendEvent {
+       MessageSendEvent::BroadcastNodeAnnouncement {
+               msg,
+       }
+}
+#[no_mangle]
+/// Utility method to constructs a new BroadcastChannelUpdate-variant MessageSendEvent
+pub extern "C" fn MessageSendEvent_broadcast_channel_update(msg: crate::lightning::ln::msgs::ChannelUpdate) -> MessageSendEvent {
+       MessageSendEvent::BroadcastChannelUpdate {
+               msg,
+       }
+}
+#[no_mangle]
+/// Utility method to constructs a new SendChannelUpdate-variant MessageSendEvent
+pub extern "C" fn MessageSendEvent_send_channel_update(node_id: crate::c_types::PublicKey, msg: crate::lightning::ln::msgs::ChannelUpdate) -> MessageSendEvent {
+       MessageSendEvent::SendChannelUpdate {
+               node_id,
+               msg,
+       }
+}
+#[no_mangle]
+/// Utility method to constructs a new HandleError-variant MessageSendEvent
+pub extern "C" fn MessageSendEvent_handle_error(node_id: crate::c_types::PublicKey, action: crate::lightning::ln::msgs::ErrorAction) -> MessageSendEvent {
+       MessageSendEvent::HandleError {
+               node_id,
+               action,
+       }
+}
+#[no_mangle]
+/// Utility method to constructs a new PaymentFailureNetworkUpdate-variant MessageSendEvent
+pub extern "C" fn MessageSendEvent_payment_failure_network_update(update: crate::lightning::ln::msgs::HTLCFailChannelUpdate) -> MessageSendEvent {
+       MessageSendEvent::PaymentFailureNetworkUpdate {
+               update,
+       }
+}
+#[no_mangle]
+/// Utility method to constructs a new SendChannelRangeQuery-variant MessageSendEvent
+pub extern "C" fn MessageSendEvent_send_channel_range_query(node_id: crate::c_types::PublicKey, msg: crate::lightning::ln::msgs::QueryChannelRange) -> MessageSendEvent {
+       MessageSendEvent::SendChannelRangeQuery {
+               node_id,
+               msg,
+       }
+}
+#[no_mangle]
+/// Utility method to constructs a new SendShortIdsQuery-variant MessageSendEvent
+pub extern "C" fn MessageSendEvent_send_short_ids_query(node_id: crate::c_types::PublicKey, msg: crate::lightning::ln::msgs::QueryShortChannelIds) -> MessageSendEvent {
+       MessageSendEvent::SendShortIdsQuery {
+               node_id,
+               msg,
+       }
+}
+#[no_mangle]
+/// Utility method to constructs a new SendReplyChannelRange-variant MessageSendEvent
+pub extern "C" fn MessageSendEvent_send_reply_channel_range(node_id: crate::c_types::PublicKey, msg: crate::lightning::ln::msgs::ReplyChannelRange) -> MessageSendEvent {
+       MessageSendEvent::SendReplyChannelRange {
+               node_id,
+               msg,
+       }
+}
 /// A trait indicating an object may generate message send events
 #[repr(C)]
 pub struct MessageSendEventsProvider {
@@ -1095,6 +1468,14 @@ pub struct MessageSendEventsProvider {
 }
 unsafe impl Send for MessageSendEventsProvider {}
 unsafe impl Sync for MessageSendEventsProvider {}
+#[no_mangle]
+pub(crate) extern "C" fn MessageSendEventsProvider_clone_fields(orig: &MessageSendEventsProvider) -> MessageSendEventsProvider {
+       MessageSendEventsProvider {
+               this_arg: orig.this_arg,
+               get_and_clear_pending_msg_events: Clone::clone(&orig.get_and_clear_pending_msg_events),
+               free: Clone::clone(&orig.free),
+       }
+}
 
 use lightning::util::events::MessageSendEventsProvider as rustMessageSendEventsProvider;
 impl rustMessageSendEventsProvider for MessageSendEventsProvider {
@@ -1164,6 +1545,14 @@ pub struct EventsProvider {
 }
 unsafe impl Send for EventsProvider {}
 unsafe impl Sync for EventsProvider {}
+#[no_mangle]
+pub(crate) extern "C" fn EventsProvider_clone_fields(orig: &EventsProvider) -> EventsProvider {
+       EventsProvider {
+               this_arg: orig.this_arg,
+               process_pending_events: Clone::clone(&orig.process_pending_events),
+               free: Clone::clone(&orig.free),
+       }
+}
 
 use lightning::util::events::EventsProvider as rustEventsProvider;
 /// Calls the free function if one is set
@@ -1192,6 +1581,14 @@ pub struct EventHandler {
 }
 unsafe impl Send for EventHandler {}
 unsafe impl Sync for EventHandler {}
+#[no_mangle]
+pub(crate) extern "C" fn EventHandler_clone_fields(orig: &EventHandler) -> EventHandler {
+       EventHandler {
+               this_arg: orig.this_arg,
+               handle_event: Clone::clone(&orig.handle_event),
+               free: Clone::clone(&orig.free),
+       }
+}
 
 use lightning::util::events::EventHandler as rustEventHandler;
 impl rustEventHandler for EventHandler {
index dc67386841c02ff3ba070e18694ed92dddadb497..cec6bb5c2035480a69f7994dd2bbab496e1e5e86 100644 (file)
@@ -82,6 +82,26 @@ impl Level {
 pub extern "C" fn Level_clone(orig: &Level) -> Level {
        orig.clone()
 }
+#[no_mangle]
+/// Utility method to constructs a new Trace-variant Level
+pub extern "C" fn Level_trace() -> Level {
+       Level::Trace}
+#[no_mangle]
+/// Utility method to constructs a new Debug-variant Level
+pub extern "C" fn Level_debug() -> Level {
+       Level::Debug}
+#[no_mangle]
+/// Utility method to constructs a new Info-variant Level
+pub extern "C" fn Level_info() -> Level {
+       Level::Info}
+#[no_mangle]
+/// Utility method to constructs a new Warn-variant Level
+pub extern "C" fn Level_warn() -> Level {
+       Level::Warn}
+#[no_mangle]
+/// Utility method to constructs a new Error-variant Level
+pub extern "C" fn Level_error() -> Level {
+       Level::Error}
 /// Checks if two Levels contain equal inner contents.
 /// This ignores pointers and is_owned flags and looks at the values in fields.
 #[no_mangle]
@@ -119,6 +139,14 @@ pub struct Logger {
 }
 unsafe impl Send for Logger {}
 unsafe impl Sync for Logger {}
+#[no_mangle]
+pub(crate) extern "C" fn Logger_clone_fields(orig: &Logger) -> Logger {
+       Logger {
+               this_arg: orig.this_arg,
+               log: Clone::clone(&orig.log),
+               free: Clone::clone(&orig.free),
+       }
+}
 
 use lightning::util::logger::Logger as rustLogger;
 impl rustLogger for Logger {
index 3900224e65c9989c775b902c8a7dc2712c6ce08f..fc44da94f86dc0bba314555130bed269ed72c3ca 100644 (file)
@@ -33,6 +33,7 @@ type nativeBackgroundProcessor = nativeBackgroundProcessorImport;
 /// then there is a risk of channels force-closing on startup when the manager realizes it's
 /// outdated. However, as long as `ChannelMonitor` backups are sound, no funds besides those used
 /// for unilateral chain closure fees are at risk.
+///BackgroundProcessor will immediately stop on drop. It should be stored until shutdown.
 #[must_use]
 #[repr(C)]
 pub struct BackgroundProcessor {
@@ -93,6 +94,14 @@ pub struct ChannelManagerPersister {
 }
 unsafe impl Send for ChannelManagerPersister {}
 unsafe impl Sync for ChannelManagerPersister {}
+#[no_mangle]
+pub(crate) extern "C" fn ChannelManagerPersister_clone_fields(orig: &ChannelManagerPersister) -> ChannelManagerPersister {
+       ChannelManagerPersister {
+               this_arg: orig.this_arg,
+               persist_manager: Clone::clone(&orig.persist_manager),
+               free: Clone::clone(&orig.free),
+       }
+}
 
 use lightning_background_processor::ChannelManagerPersister as rustChannelManagerPersister;
 impl rustChannelManagerPersister<crate::lightning::chain::keysinterface::Sign, crate::lightning::chain::Watch, crate::lightning::chain::chaininterface::BroadcasterInterface, crate::lightning::chain::keysinterface::KeysInterface, crate::lightning::chain::chaininterface::FeeEstimator, crate::lightning::util::logger::Logger> for ChannelManagerPersister {
@@ -121,21 +130,25 @@ impl Drop for ChannelManagerPersister {
                }
        }
 }
-/// Start a background thread that takes care of responsibilities enumerated in the top-level
-/// documentation.
+/// Start a background thread that takes care of responsibilities enumerated in the [top-level
+/// documentation].
 ///
-/// If `persist_manager` returns an error, then this thread will return said error (and
-/// `start()` will need to be called again to restart the `BackgroundProcessor`). Users should
-/// wait on [`thread_handle`]'s `join()` method to be able to tell if and when an error is
-/// returned, or implement `persist_manager` such that an error is never returned to the
-/// `BackgroundProcessor`
+/// The thread runs indefinitely unless the object is dropped, [`stop`] is called, or
+/// `persist_manager` returns an error. In case of an error, the error is retrieved by calling
+/// either [`join`] or [`stop`].
+///
+/// Typically, users should either implement [`ChannelManagerPersister`] to never return an
+/// error or call [`join`] and handle any error that may arise. For the latter case, the
+/// `BackgroundProcessor` must be restarted by calling `start` again after handling the error.
 ///
 /// `persist_manager` is responsible for writing out the [`ChannelManager`] to disk, and/or
 /// uploading to one or more backup services. See [`ChannelManager::write`] for writing out a
 /// [`ChannelManager`]. See [`FilesystemPersister::persist_manager`] for Rust-Lightning's
 /// provided implementation.
 ///
-/// [`thread_handle`]: BackgroundProcessor::thread_handle
+/// [top-level documentation]: Self
+/// [`join`]: Self::join
+/// [`stop`]: Self::stop
 /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
 /// [`ChannelManager::write`]: lightning::ln::channelmanager::ChannelManager#impl-Writeable
 /// [`FilesystemPersister::persist_manager`]: lightning_persister::FilesystemPersister::persist_manager
@@ -146,7 +159,32 @@ pub extern "C" fn BackgroundProcessor_start(mut persister: crate::lightning_back
        BackgroundProcessor { inner: Box::into_raw(Box::new(ret)), is_owned: true }
 }
 
-/// Stop `BackgroundProcessor`'s thread.
+/// Join `BackgroundProcessor`'s thread, returning any error that occurred while persisting
+/// [`ChannelManager`].
+///
+/// # Panics
+///
+/// This function panics if the background thread has panicked such as while persisting or
+/// handling events.
+///
+/// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
+#[must_use]
+#[no_mangle]
+pub extern "C" fn BackgroundProcessor_join(mut this_arg: BackgroundProcessor) -> crate::c_types::derived::CResult_NoneErrorZ {
+       let mut ret = (*unsafe { Box::from_raw(this_arg.take_inner()) }).join();
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::IOError::from_rust(e) }).into() };
+       local_ret
+}
+
+/// Stop `BackgroundProcessor`'s thread, returning any error that occurred while persisting
+/// [`ChannelManager`].
+///
+/// # Panics
+///
+/// This function panics if the background thread has panicked such as while persisting or
+/// handling events.
+///
+/// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
 #[must_use]
 #[no_mangle]
 pub extern "C" fn BackgroundProcessor_stop(mut this_arg: BackgroundProcessor) -> crate::c_types::derived::CResult_NoneErrorZ {
index 0891447b5f733a274ab3387e7657ae7c8ba4e0ec..7ab1c2ede2be551286d1eb80e2afce77fbf6dde1 100644 (file)
@@ -607,6 +607,22 @@ impl SiPrefix {
 pub extern "C" fn SiPrefix_clone(orig: &SiPrefix) -> SiPrefix {
        orig.clone()
 }
+#[no_mangle]
+/// Utility method to constructs a new Milli-variant SiPrefix
+pub extern "C" fn SiPrefix_milli() -> SiPrefix {
+       SiPrefix::Milli}
+#[no_mangle]
+/// Utility method to constructs a new Micro-variant SiPrefix
+pub extern "C" fn SiPrefix_micro() -> SiPrefix {
+       SiPrefix::Micro}
+#[no_mangle]
+/// Utility method to constructs a new Nano-variant SiPrefix
+pub extern "C" fn SiPrefix_nano() -> SiPrefix {
+       SiPrefix::Nano}
+#[no_mangle]
+/// Utility method to constructs a new Pico-variant SiPrefix
+pub extern "C" fn SiPrefix_pico() -> SiPrefix {
+       SiPrefix::Pico}
 /// Checks if two SiPrefixs contain equal inner contents.
 /// This ignores pointers and is_owned flags and looks at the values in fields.
 #[no_mangle]
@@ -686,6 +702,26 @@ impl Currency {
 pub extern "C" fn Currency_clone(orig: &Currency) -> Currency {
        orig.clone()
 }
+#[no_mangle]
+/// Utility method to constructs a new Bitcoin-variant Currency
+pub extern "C" fn Currency_bitcoin() -> Currency {
+       Currency::Bitcoin}
+#[no_mangle]
+/// Utility method to constructs a new BitcoinTestnet-variant Currency
+pub extern "C" fn Currency_bitcoin_testnet() -> Currency {
+       Currency::BitcoinTestnet}
+#[no_mangle]
+/// Utility method to constructs a new Regtest-variant Currency
+pub extern "C" fn Currency_regtest() -> Currency {
+       Currency::Regtest}
+#[no_mangle]
+/// Utility method to constructs a new Simnet-variant Currency
+pub extern "C" fn Currency_simnet() -> Currency {
+       Currency::Simnet}
+#[no_mangle]
+/// Utility method to constructs a new Signet-variant Currency
+pub extern "C" fn Currency_signet() -> Currency {
+       Currency::Signet}
 /// Checks if two Currencys contain equal inner contents.
 /// This ignores pointers and is_owned flags and looks at the values in fields.
 #[no_mangle]
@@ -1185,6 +1221,24 @@ pub extern "C" fn Fallback_free(this_ptr: Fallback) { }
 pub extern "C" fn Fallback_clone(orig: &Fallback) -> Fallback {
        orig.clone()
 }
+#[no_mangle]
+/// Utility method to constructs a new SegWitProgram-variant Fallback
+pub extern "C" fn Fallback_seg_wit_program(version: crate::c_types::u5, program: crate::c_types::derived::CVec_u8Z) -> Fallback {
+       Fallback::SegWitProgram {
+               version,
+               program,
+       }
+}
+#[no_mangle]
+/// Utility method to constructs a new PubKeyHash-variant Fallback
+pub extern "C" fn Fallback_pub_key_hash(a: crate::c_types::TwentyBytes) -> Fallback {
+       Fallback::PubKeyHash(a, )
+}
+#[no_mangle]
+/// Utility method to constructs a new ScriptHash-variant Fallback
+pub extern "C" fn Fallback_script_hash(a: crate::c_types::TwentyBytes) -> Fallback {
+       Fallback::ScriptHash(a, )
+}
 /// Checks if two Fallbacks contain equal inner contents.
 /// This ignores pointers and is_owned flags and looks at the values in fields.
 #[no_mangle]
@@ -1403,6 +1457,8 @@ pub extern "C" fn RawInvoice_hash(this_arg: &RawInvoice) -> crate::c_types::Thir
        crate::c_types::ThirtyTwoBytes { data: ret }
 }
 
+///
+/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[must_use]
 #[no_mangle]
 pub extern "C" fn RawInvoice_payment_hash(this_arg: &RawInvoice) -> crate::lightning_invoice::Sha256 {
@@ -1411,6 +1467,8 @@ pub extern "C" fn RawInvoice_payment_hash(this_arg: &RawInvoice) -> crate::light
        local_ret
 }
 
+///
+/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[must_use]
 #[no_mangle]
 pub extern "C" fn RawInvoice_description(this_arg: &RawInvoice) -> crate::lightning_invoice::Description {
@@ -1419,6 +1477,8 @@ pub extern "C" fn RawInvoice_description(this_arg: &RawInvoice) -> crate::lightn
        local_ret
 }
 
+///
+/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[must_use]
 #[no_mangle]
 pub extern "C" fn RawInvoice_payee_pub_key(this_arg: &RawInvoice) -> crate::lightning_invoice::PayeePubKey {
@@ -1427,6 +1487,8 @@ pub extern "C" fn RawInvoice_payee_pub_key(this_arg: &RawInvoice) -> crate::ligh
        local_ret
 }
 
+///
+/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[must_use]
 #[no_mangle]
 pub extern "C" fn RawInvoice_description_hash(this_arg: &RawInvoice) -> crate::lightning_invoice::Sha256 {
@@ -1435,6 +1497,8 @@ pub extern "C" fn RawInvoice_description_hash(this_arg: &RawInvoice) -> crate::l
        local_ret
 }
 
+///
+/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[must_use]
 #[no_mangle]
 pub extern "C" fn RawInvoice_expiry_time(this_arg: &RawInvoice) -> crate::lightning_invoice::ExpiryTime {
@@ -1443,6 +1507,8 @@ pub extern "C" fn RawInvoice_expiry_time(this_arg: &RawInvoice) -> crate::lightn
        local_ret
 }
 
+///
+/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[must_use]
 #[no_mangle]
 pub extern "C" fn RawInvoice_min_final_cltv_expiry(this_arg: &RawInvoice) -> crate::lightning_invoice::MinFinalCltvExpiry {
@@ -1451,6 +1517,8 @@ pub extern "C" fn RawInvoice_min_final_cltv_expiry(this_arg: &RawInvoice) -> cra
        local_ret
 }
 
+///
+/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[must_use]
 #[no_mangle]
 pub extern "C" fn RawInvoice_payment_secret(this_arg: &RawInvoice) -> crate::c_types::ThirtyTwoBytes {
@@ -1459,6 +1527,8 @@ pub extern "C" fn RawInvoice_payment_secret(this_arg: &RawInvoice) -> crate::c_t
        local_ret
 }
 
+///
+/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[must_use]
 #[no_mangle]
 pub extern "C" fn RawInvoice_features(this_arg: &RawInvoice) -> crate::lightning::ln::features::InvoiceFeatures {
@@ -1583,6 +1653,8 @@ pub extern "C" fn Invoice_payment_hash(this_arg: &Invoice) -> *const [u8; 32] {
 }
 
 /// Get the payee's public key if one was included in the invoice
+///
+/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[must_use]
 #[no_mangle]
 pub extern "C" fn Invoice_payee_pub_key(this_arg: &Invoice) -> crate::c_types::PublicKey {
@@ -1592,6 +1664,8 @@ pub extern "C" fn Invoice_payee_pub_key(this_arg: &Invoice) -> crate::c_types::P
 }
 
 /// Get the payment secret if one was included in the invoice
+///
+/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[must_use]
 #[no_mangle]
 pub extern "C" fn Invoice_payment_secret(this_arg: &Invoice) -> crate::c_types::ThirtyTwoBytes {
@@ -1601,6 +1675,8 @@ pub extern "C" fn Invoice_payment_secret(this_arg: &Invoice) -> crate::c_types::
 }
 
 /// Get the invoice features if they were included in the invoice
+///
+/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[must_use]
 #[no_mangle]
 pub extern "C" fn Invoice_features(this_arg: &Invoice) -> crate::lightning::ln::features::InvoiceFeatures {
@@ -1802,6 +1878,22 @@ impl CreationError {
 pub extern "C" fn CreationError_clone(orig: &CreationError) -> CreationError {
        orig.clone()
 }
+#[no_mangle]
+/// Utility method to constructs a new DescriptionTooLong-variant CreationError
+pub extern "C" fn CreationError_description_too_long() -> CreationError {
+       CreationError::DescriptionTooLong}
+#[no_mangle]
+/// Utility method to constructs a new RouteTooLong-variant CreationError
+pub extern "C" fn CreationError_route_too_long() -> CreationError {
+       CreationError::RouteTooLong}
+#[no_mangle]
+/// Utility method to constructs a new TimestampOutOfBounds-variant CreationError
+pub extern "C" fn CreationError_timestamp_out_of_bounds() -> CreationError {
+       CreationError::TimestampOutOfBounds}
+#[no_mangle]
+/// Utility method to constructs a new ExpiryTimeOutOfBounds-variant CreationError
+pub extern "C" fn CreationError_expiry_time_out_of_bounds() -> CreationError {
+       CreationError::ExpiryTimeOutOfBounds}
 /// Checks if two CreationErrors contain equal inner contents.
 /// This ignores pointers and is_owned flags and looks at the values in fields.
 #[no_mangle]
@@ -1896,6 +1988,38 @@ impl SemanticError {
 pub extern "C" fn SemanticError_clone(orig: &SemanticError) -> SemanticError {
        orig.clone()
 }
+#[no_mangle]
+/// Utility method to constructs a new NoPaymentHash-variant SemanticError
+pub extern "C" fn SemanticError_no_payment_hash() -> SemanticError {
+       SemanticError::NoPaymentHash}
+#[no_mangle]
+/// Utility method to constructs a new MultiplePaymentHashes-variant SemanticError
+pub extern "C" fn SemanticError_multiple_payment_hashes() -> SemanticError {
+       SemanticError::MultiplePaymentHashes}
+#[no_mangle]
+/// Utility method to constructs a new NoDescription-variant SemanticError
+pub extern "C" fn SemanticError_no_description() -> SemanticError {
+       SemanticError::NoDescription}
+#[no_mangle]
+/// Utility method to constructs a new MultipleDescriptions-variant SemanticError
+pub extern "C" fn SemanticError_multiple_descriptions() -> SemanticError {
+       SemanticError::MultipleDescriptions}
+#[no_mangle]
+/// Utility method to constructs a new MultiplePaymentSecrets-variant SemanticError
+pub extern "C" fn SemanticError_multiple_payment_secrets() -> SemanticError {
+       SemanticError::MultiplePaymentSecrets}
+#[no_mangle]
+/// Utility method to constructs a new InvalidFeatures-variant SemanticError
+pub extern "C" fn SemanticError_invalid_features() -> SemanticError {
+       SemanticError::InvalidFeatures}
+#[no_mangle]
+/// Utility method to constructs a new InvalidRecoveryId-variant SemanticError
+pub extern "C" fn SemanticError_invalid_recovery_id() -> SemanticError {
+       SemanticError::InvalidRecoveryId}
+#[no_mangle]
+/// Utility method to constructs a new InvalidSignature-variant SemanticError
+pub extern "C" fn SemanticError_invalid_signature() -> SemanticError {
+       SemanticError::InvalidSignature}
 /// Checks if two SemanticErrors contain equal inner contents.
 /// This ignores pointers and is_owned flags and looks at the values in fields.
 #[no_mangle]
@@ -1985,6 +2109,16 @@ pub extern "C" fn SignOrCreationError_free(this_ptr: SignOrCreationError) { }
 pub extern "C" fn SignOrCreationError_clone(orig: &SignOrCreationError) -> SignOrCreationError {
        orig.clone()
 }
+#[no_mangle]
+/// Utility method to constructs a new SignError-variant SignOrCreationError
+pub extern "C" fn SignOrCreationError_sign_error() -> SignOrCreationError {
+       SignOrCreationError::SignError
+}
+#[no_mangle]
+/// Utility method to constructs a new CreationError-variant SignOrCreationError
+pub extern "C" fn SignOrCreationError_creation_error(a: crate::lightning_invoice::CreationError) -> SignOrCreationError {
+       SignOrCreationError::CreationError(a, )
+}
 /// Checks if two SignOrCreationErrors contain equal inner contents.
 /// This ignores pointers and is_owned flags and looks at the values in fields.
 #[no_mangle]