From: Matt Corallo <649246+TheBlueMatt@users.noreply.github.com> Date: Sat, 1 May 2021 02:02:41 +0000 (+0000) Subject: Merge pull request #19 from TheBlueMatt/2021-04-invoice-incl X-Git-Tag: v0.0.98~9 X-Git-Url: http://git.bitcoin.ninja/index.cgi?p=ldk-c-bindings;a=commitdiff_plain;h=1926a7a71ae0f37ebd6562996769334e0af0cf1b;hp=5eebd45b471833805e81ad4c23ec93d7711e0a23 Merge pull request #19 from TheBlueMatt/2021-04-invoice-incl --- diff --git a/c-bindings-gen/src/blocks.rs b/c-bindings-gen/src/blocks.rs index 8817272..82b10ad 100644 --- a/c-bindings-gen/src/blocks.rs +++ b/c-bindings-gen/src/blocks.rs @@ -137,12 +137,8 @@ pub fn write_result_block(w: &mut W, mangled_container: &str, writeln!(w, "\t}}").unwrap(); writeln!(w, "}}").unwrap(); - // TODO: Templates should use () now that they can, too - let templ_ok_type = if ok_type != "()" { ok_type } else { "u8" }; - let templ_err_type = if err_type != "()" { err_type } else { "u8" }; - - writeln!(w, "impl From> for {} {{", templ_ok_type, templ_err_type, mangled_container).unwrap(); - writeln!(w, "\tfn from(mut o: crate::c_types::CResultTempl<{}, {}>) -> Self {{", templ_ok_type, templ_err_type).unwrap(); + writeln!(w, "impl From> for {} {{", ok_type, err_type, mangled_container).unwrap(); + writeln!(w, "\tfn from(mut o: crate::c_types::CResultTempl<{}, {}>) -> Self {{", ok_type, err_type).unwrap(); writeln!(w, "\t\tlet contents = if o.result_ok {{").unwrap(); if ok_type != "()" { writeln!(w, "\t\t\tlet result = unsafe {{ o.contents.result }};").unwrap(); diff --git a/c-bindings-gen/src/main.rs b/c-bindings-gen/src/main.rs index 24bcf82..c2ef30f 100644 --- a/c-bindings-gen/src/main.rs +++ b/c-bindings-gen/src/main.rs @@ -388,7 +388,7 @@ fn writeln_trait<'a, 'b, W: std::io::Write>(w: &mut W, t: &'a syn::ItemTrait, ty ident.mutability.is_some() || ident.subpat.is_some() { unimplemented!(); } - write!(w, ", {}{}: ", if $type_resolver.skip_arg(&*arg.ty, Some(&meth_gen_types)) { "_" } else { "" }, ident.ident).unwrap(); + write!(w, ", mut {}{}: ", if $type_resolver.skip_arg(&*arg.ty, Some(&meth_gen_types)) { "_" } else { "" }, ident.ident).unwrap(); } _ => unimplemented!(), } @@ -966,22 +966,31 @@ fn writeln_impl(w: &mut W, i: &syn::ItemImpl, types: &mut Typ writeln!(w, "#[no_mangle]").unwrap(); writeln!(w, "/// Read a {} object from a string", ident).unwrap(); writeln!(w, "pub extern \"C\" fn {}_from_str(s: crate::c_types::Str) -> {} {{", ident, container).unwrap(); - writeln!(w, "\tmatch {}::from_str(s.into()) {{", resolved_path).unwrap(); + writeln!(w, "\tmatch {}::from_str(s.into_str()) {{", resolved_path).unwrap(); writeln!(w, "\t\tOk(r) => {{").unwrap(); - let new_var = types.write_to_c_conversion_new_var(w, &syn::Ident::new("r", Span::call_site()), &*i.self_ty, Some(&gen_types), false); + let new_var = types.write_to_c_conversion_new_var(w, &format_ident!("r"), &*i.self_ty, Some(&gen_types), false); write!(w, "\t\t\tcrate::c_types::CResultTempl::ok(\n\t\t\t\t").unwrap(); types.write_to_c_conversion_inline_prefix(w, &*i.self_ty, Some(&gen_types), false); write!(w, "{}r", if new_var { "local_" } else { "" }).unwrap(); types.write_to_c_conversion_inline_suffix(w, &*i.self_ty, Some(&gen_types), false); writeln!(w, "\n\t\t\t)\n\t\t}},").unwrap(); - writeln!(w, "\t\tErr(e) => crate::c_types::CResultTempl::err(0u8),").unwrap(); + writeln!(w, "\t\tErr(e) => crate::c_types::CResultTempl::err(()),").unwrap(); writeln!(w, "\t}}.into()\n}}").unwrap(); } } else if path_matches_nongeneric(&trait_path.1, &["Display"]) { writeln!(w, "#[no_mangle]").unwrap(); writeln!(w, "/// Get the string representation of a {} object", ident).unwrap(); - writeln!(w, "pub extern \"C\" fn {}_to_str(o: &{}) -> Str {{", ident, resolved_path).unwrap(); - writeln!(w, "\tformat!(\"{{}}\", o).into()").unwrap(); + writeln!(w, "pub extern \"C\" fn {}_to_str(o: &crate::{}) -> Str {{", ident, resolved_path).unwrap(); + + let self_ty = &i.self_ty; + let ref_type: syn::Type = syn::parse_quote!(&#self_ty); + let new_var = types.write_from_c_conversion_new_var(w, &format_ident!("o"), &ref_type, Some(&gen_types)); + write!(w, "\tformat!(\"{{}}\", ").unwrap(); + types.write_from_c_conversion_prefix(w, &ref_type, Some(&gen_types)); + write!(w, "{}o", if new_var { "local_" } else { "" }).unwrap(); + types.write_from_c_conversion_suffix(w, &ref_type, Some(&gen_types)); + writeln!(w, ").into()").unwrap(); + writeln!(w, "}}").unwrap(); } else { //XXX: implement for other things like ToString @@ -1128,9 +1137,8 @@ fn writeln_enum<'a, 'b, W: std::io::Write>(w: &mut W, e: &'a syn::ItemEnum, type } writeln_docs(w, &e.attrs, ""); - if e.generics.lt_token.is_some() { - unimplemented!(); - } + let mut gen_types = GenericTypes::new(None); + assert!(gen_types.learn_generics(&e.generics, types)); let mut needs_free = false; @@ -1146,21 +1154,31 @@ fn writeln_enum<'a, 'b, W: std::io::Write>(w: &mut W, e: &'a syn::ItemEnum, type if export_status(&field.attrs) == ExportStatus::TestOnly { continue; } writeln_docs(w, &field.attrs, "\t\t"); write!(w, "\t\t{}: ", field.ident.as_ref().unwrap()).unwrap(); - types.write_c_type(w, &field.ty, None, false); + types.write_c_type(w, &field.ty, Some(&gen_types), false); writeln!(w, ",").unwrap(); } write!(w, "\t}}").unwrap(); } else if let syn::Fields::Unnamed(fields) = &var.fields { - needs_free = true; - write!(w, "(").unwrap(); - for (idx, field) in fields.unnamed.iter().enumerate() { - if export_status(&field.attrs) == ExportStatus::TestOnly { continue; } - types.write_c_type(w, &field.ty, None, false); - if idx != fields.unnamed.len() - 1 { - write!(w, ",").unwrap(); + 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); + if empty_check.is_empty() { + empty_tuple_variant = true; + } + } + if !empty_tuple_variant { + needs_free = true; + write!(w, "(").unwrap(); + for (idx, field) in fields.unnamed.iter().enumerate() { + if export_status(&field.attrs) == ExportStatus::TestOnly { continue; } + types.write_c_type(w, &field.ty, Some(&gen_types), false); + if idx != fields.unnamed.len() - 1 { + write!(w, ",").unwrap(); + } } + write!(w, ")").unwrap(); } - write!(w, ")").unwrap(); } if var.discriminant.is_some() { unimplemented!(); } writeln!(w, ",").unwrap(); @@ -1172,6 +1190,7 @@ fn writeln_enum<'a, 'b, W: std::io::Write>(w: &mut W, e: &'a syn::ItemEnum, type writeln!(w, "\t#[allow(unused)]\n\tpub(crate) fn {} {{\n\t\tmatch {} {{", $fn_sig, if $to_c { "native" } else { "self" }).unwrap(); for var in e.variants.iter() { write!(w, "\t\t\t{}{}::{} ", if $to_c { "native" } else { "" }, e.ident, var.ident).unwrap(); + let mut empty_tuple_variant = false; if let syn::Fields::Named(fields) = &var.fields { write!(w, "{{").unwrap(); for field in fields.named.iter() { @@ -1180,12 +1199,21 @@ fn writeln_enum<'a, 'b, W: std::io::Write>(w: &mut W, e: &'a syn::ItemEnum, type } write!(w, "}} ").unwrap(); } else if let syn::Fields::Unnamed(fields) = &var.fields { - write!(w, "(").unwrap(); - for (idx, field) in fields.unnamed.iter().enumerate() { - if export_status(&field.attrs) == ExportStatus::TestOnly { continue; } - write!(w, "{}{}, ", if $ref { "ref " } else { "mut " }, ('a' as u8 + idx as u8) as char).unwrap(); + 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); + if empty_check.is_empty() { + empty_tuple_variant = true; + } + } + if !empty_tuple_variant || $to_c { + write!(w, "(").unwrap(); + for (idx, field) in fields.unnamed.iter().enumerate() { + if export_status(&field.attrs) == ExportStatus::TestOnly { continue; } + write!(w, "{}{}, ", if $ref { "ref " } else { "mut " }, ('a' as u8 + idx as u8) as char).unwrap(); + } + write!(w, ") ").unwrap(); } - write!(w, ") ").unwrap(); } write!(w, "=>").unwrap(); @@ -1195,9 +1223,9 @@ fn writeln_enum<'a, 'b, W: std::io::Write>(w: &mut W, e: &'a syn::ItemEnum, type let mut sink = ::std::io::sink(); let mut out: &mut dyn std::io::Write = if $ref { &mut sink } else { w }; let new_var = if $to_c { - types.write_to_c_conversion_new_var(&mut out, $field_ident, &$field.ty, None, false) + types.write_to_c_conversion_new_var(&mut out, $field_ident, &$field.ty, Some(&gen_types), false) } else { - types.write_from_c_conversion_new_var(&mut out, $field_ident, &$field.ty, None) + types.write_from_c_conversion_new_var(&mut out, $field_ident, &$field.ty, Some(&gen_types)) }; if $ref || new_var { if $ref { @@ -1205,9 +1233,9 @@ fn writeln_enum<'a, 'b, W: std::io::Write>(w: &mut W, e: &'a syn::ItemEnum, type if new_var { let nonref_ident = format_ident!("{}_nonref", $field_ident); if $to_c { - types.write_to_c_conversion_new_var(w, &nonref_ident, &$field.ty, None, false); + types.write_to_c_conversion_new_var(w, &nonref_ident, &$field.ty, Some(&gen_types), false); } else { - types.write_from_c_conversion_new_var(w, &nonref_ident, &$field.ty, None); + types.write_from_c_conversion_new_var(w, &nonref_ident, &$field.ty, Some(&gen_types)); } write!(w, "\n\t\t\t\t").unwrap(); } @@ -1225,7 +1253,9 @@ fn writeln_enum<'a, 'b, W: std::io::Write>(w: &mut W, e: &'a syn::ItemEnum, type } else if let syn::Fields::Unnamed(fields) = &var.fields { write!(w, " {{\n\t\t\t\t").unwrap(); for (idx, field) in fields.unnamed.iter().enumerate() { - handle_field_a!(field, &format_ident!("{}", ('a' as u8 + idx as u8) as char)); + if !empty_tuple_variant { + handle_field_a!(field, &format_ident!("{}", ('a' as u8 + idx as u8) as char)); + } } } else { write!(w, " ").unwrap(); } @@ -1235,16 +1265,16 @@ fn writeln_enum<'a, 'b, W: std::io::Write>(w: &mut W, e: &'a syn::ItemEnum, type ($field: expr, $field_ident: expr) => { { if export_status(&$field.attrs) == ExportStatus::TestOnly { continue; } if $to_c { - types.write_to_c_conversion_inline_prefix(w, &$field.ty, None, false); + types.write_to_c_conversion_inline_prefix(w, &$field.ty, Some(&gen_types), false); } else { - types.write_from_c_conversion_prefix(w, &$field.ty, None); + types.write_from_c_conversion_prefix(w, &$field.ty, Some(&gen_types)); } write!(w, "{}{}", $field_ident, if $ref { "_nonref" } else { "" }).unwrap(); if $to_c { - types.write_to_c_conversion_inline_suffix(w, &$field.ty, None, false); + types.write_to_c_conversion_inline_suffix(w, &$field.ty, Some(&gen_types), false); } else { - types.write_from_c_conversion_suffix(w, &$field.ty, None); + types.write_from_c_conversion_suffix(w, &$field.ty, Some(&gen_types)); } write!(w, ",").unwrap(); } } @@ -1260,12 +1290,14 @@ fn writeln_enum<'a, 'b, W: std::io::Write>(w: &mut W, e: &'a syn::ItemEnum, type writeln!(w, "\n\t\t\t\t}}").unwrap(); write!(w, "\t\t\t}}").unwrap(); } else if let syn::Fields::Unnamed(fields) = &var.fields { - write!(w, " (").unwrap(); - for (idx, field) in fields.unnamed.iter().enumerate() { - write!(w, "\n\t\t\t\t\t").unwrap(); - handle_field_b!(field, &format_ident!("{}", ('a' as u8 + idx as u8) as char)); + if !empty_tuple_variant || !$to_c { + write!(w, " (").unwrap(); + for (idx, field) in fields.unnamed.iter().enumerate() { + write!(w, "\n\t\t\t\t\t").unwrap(); + handle_field_b!(field, &format_ident!("{}", ('a' as u8 + idx as u8) as char)); + } + writeln!(w, "\n\t\t\t\t)").unwrap(); } - writeln!(w, "\n\t\t\t\t)").unwrap(); write!(w, "\t\t\t}}").unwrap(); } writeln!(w, ",").unwrap(); diff --git a/c-bindings-gen/src/types.rs b/c-bindings-gen/src/types.rs index a45cf2b..d945431 100644 --- a/c-bindings-gen/src/types.rs +++ b/c-bindings-gen/src/types.rs @@ -167,17 +167,18 @@ pub struct GenericTypes<'a, 'b> { self_ty: Option<(String, &'a syn::Path)>, parent: Option<&'b GenericTypes<'b, 'b>>, typed_generics: HashMap<&'a syn::Ident, (String, Option<&'a syn::Path>)>, + default_generics: HashMap<&'a syn::Ident, (&'a syn::Type, syn::Type)>, } impl<'a, 'p: 'a> GenericTypes<'a, 'p> { pub fn new(self_ty: Option<(String, &'a syn::Path)>) -> Self { - Self { self_ty, parent: None, typed_generics: HashMap::new(), } + Self { self_ty, parent: None, typed_generics: HashMap::new(), default_generics: HashMap::new(), } } /// push a new context onto the stack, allowing for a new set of generics to be learned which /// will override any lower contexts, but which will still fall back to resoltion via lower /// contexts. pub fn push_ctx<'c>(&'c self) -> GenericTypes<'a, 'c> { - GenericTypes { self_ty: None, parent: Some(self), typed_generics: HashMap::new(), } + GenericTypes { self_ty: None, parent: Some(self), typed_generics: HashMap::new(), default_generics: HashMap::new(), } } /// Learn the generics in generics in the current context, given a TypeResolver. @@ -208,6 +209,10 @@ impl<'a, 'p: 'a> GenericTypes<'a, 'p> { } else { return false; } } } + if let Some(default) = type_param.default.as_ref() { + assert!(type_param.bounds.is_empty()); + self.default_generics.insert(&type_param.ident, (default, parse_quote!(&#default))); + } }, _ => {}, } @@ -296,6 +301,7 @@ impl<'a, 'p: 'a> GenericTypes<'a, 'p> { None } } + /// Attempt to resolve a Path as a generic parameter and return the full path. as both a string /// and syn::Path. pub fn maybe_resolve_path<'b>(&'b self, path: &syn::Path) -> Option<(&'b String, &'a syn::Path)> { @@ -327,6 +333,34 @@ impl<'a, 'p: 'a> GenericTypes<'a, 'p> { } } +trait ResolveType<'a> { fn resolve_type(&'a self, ty: &'a syn::Type) -> &'a syn::Type; } +impl<'a, 'b, 'c: 'a + 'b> ResolveType<'c> for Option<&GenericTypes<'a, 'b>> { + fn resolve_type(&'c self, ty: &'c syn::Type) -> &'c syn::Type { + if let Some(us) = self { + match ty { + syn::Type::Path(p) => { + if let Some(ident) = p.path.get_ident() { + if let Some((ty, _)) = us.default_generics.get(ident) { + return ty; + } + } + }, + syn::Type::Reference(syn::TypeReference { elem, .. }) => { + if let syn::Type::Path(p) = &**elem { + if let Some(ident) = p.path.get_ident() { + if let Some((_, refty)) = us.default_generics.get(ident) { + return refty; + } + } + } + } + _ => {}, + } + } + ty + } +} + #[derive(Clone, PartialEq)] // The type of declaration and the object itself pub enum DeclType<'a> { @@ -558,7 +592,6 @@ impl<'mod_lifetime, 'crate_lft: 'mod_lifetime> ImportResolver<'mod_lifetime, 'cr pub fn resolve_imported_refs(&self, mut ty: syn::Type) -> syn::Type { match &mut ty { syn::Type::Path(p) => { -eprintln!("rir {:?}", p); if p.path.segments.len() != 1 { unimplemented!(); } let mut args = p.path.segments[0].arguments.clone(); if let syn::PathArguments::AngleBracketed(ref mut generics) = &mut args { @@ -782,6 +815,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> { match ty { "()" => true, "crate::c_types::Signature" => true, + "crate::c_types::RecoverableSignature" => true, "crate::c_types::TxOut" => true, _ => false, } @@ -808,8 +842,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> { "[u8; 3]" if !is_ref => Some("crate::c_types::ThreeBytes"), // Used for RGB values "str" if is_ref => Some("crate::c_types::Str"), - "String" if !is_ref => Some("crate::c_types::derived::CVec_u8Z"), - "String" if is_ref => Some("crate::c_types::Str"), + "String" => Some("crate::c_types::Str"), "std::time::Duration" => Some("u64"), "std::time::SystemTime" => Some("u64"), @@ -820,6 +853,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> { "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey" => Some("crate::c_types::PublicKey"), "bitcoin::secp256k1::Signature" => Some("crate::c_types::Signature"), + "bitcoin::secp256k1::recovery::RecoverableSignature" => Some("crate::c_types::RecoverableSignature"), "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey" if is_ref => Some("*const [u8; 32]"), "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey" @@ -841,12 +875,12 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> { "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"), "bitcoin::secp256k1::Message" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"), - "lightning::ln::channelmanager::PaymentHash" if is_ref => Some("*const [u8; 32]"), - "lightning::ln::channelmanager::PaymentHash" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"), - "lightning::ln::channelmanager::PaymentPreimage" if is_ref => Some("*const [u8; 32]"), - "lightning::ln::channelmanager::PaymentPreimage" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"), - "lightning::ln::channelmanager::PaymentSecret" if is_ref => Some("crate::c_types::ThirtyTwoBytes"), - "lightning::ln::channelmanager::PaymentSecret" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"), + "lightning::ln::PaymentHash" if is_ref => Some("*const [u8; 32]"), + "lightning::ln::PaymentHash" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"), + "lightning::ln::PaymentPreimage" if is_ref => Some("*const [u8; 32]"), + "lightning::ln::PaymentPreimage" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"), + "lightning::ln::PaymentSecret" if is_ref => Some("crate::c_types::ThirtyTwoBytes"), + "lightning::ln::PaymentSecret" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"), // Override the default since Records contain an fmt with a lifetime: "lightning::util::logger::Record" => Some("*const std::os::raw::c_char"), @@ -880,7 +914,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> { "[usize]" if is_ref => Some(""), "str" if is_ref => Some(""), - "String" if !is_ref => Some("String::from_utf8("), + "String" => Some(""), // Note that we'll panic for String if is_ref, as we only have non-owned memory, we // cannot create a &String. @@ -895,6 +929,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> { => Some(""), "bitcoin::secp256k1::Signature" if is_ref => Some("&"), "bitcoin::secp256k1::Signature" => Some(""), + "bitcoin::secp256k1::recovery::RecoverableSignature" => Some(""), "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey" if is_ref => Some("&::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *"), "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey" @@ -912,11 +947,11 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> { "bitcoin::hash_types::Txid" if is_ref => Some("&::bitcoin::hash_types::Txid::from_slice(&unsafe { &*"), "bitcoin::hash_types::Txid" if !is_ref => Some("::bitcoin::hash_types::Txid::from_slice(&"), "bitcoin::hash_types::BlockHash" => Some("::bitcoin::hash_types::BlockHash::from_slice(&"), - "lightning::ln::channelmanager::PaymentHash" if !is_ref => Some("::lightning::ln::channelmanager::PaymentHash("), - "lightning::ln::channelmanager::PaymentHash" if is_ref => Some("&::lightning::ln::channelmanager::PaymentHash(unsafe { *"), - "lightning::ln::channelmanager::PaymentPreimage" if !is_ref => Some("::lightning::ln::channelmanager::PaymentPreimage("), - "lightning::ln::channelmanager::PaymentPreimage" if is_ref => Some("&::lightning::ln::channelmanager::PaymentPreimage(unsafe { *"), - "lightning::ln::channelmanager::PaymentSecret" => Some("::lightning::ln::channelmanager::PaymentSecret("), + "lightning::ln::PaymentHash" if !is_ref => Some("::lightning::ln::PaymentHash("), + "lightning::ln::PaymentHash" if is_ref => Some("&::lightning::ln::PaymentHash(unsafe { *"), + "lightning::ln::PaymentPreimage" if !is_ref => Some("::lightning::ln::PaymentPreimage("), + "lightning::ln::PaymentPreimage" if is_ref => Some("&::lightning::ln::PaymentPreimage(unsafe { *"), + "lightning::ln::PaymentSecret" => Some("::lightning::ln::PaymentSecret("), // List of traits we map (possibly during processing of other files): "crate::util::logger::Logger" => Some(""), @@ -944,8 +979,8 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> { "[u8]" if is_ref => Some(".to_slice()"), "[usize]" if is_ref => Some(".to_slice()"), - "str" if is_ref => Some(".into()"), - "String" if !is_ref => Some(".into_rust()).unwrap()"), + "str" if is_ref => Some(".into_str()"), + "String" => Some(".into_string()"), "std::time::Duration" => Some(")"), "std::time::SystemTime" => Some("))"), @@ -955,6 +990,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> { "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey" => Some(".into_rust()"), "bitcoin::secp256k1::Signature" => Some(".into_rust()"), + "bitcoin::secp256k1::recovery::RecoverableSignature" => Some(".into_rust()"), "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey" if !is_ref => Some(".into_rust()"), "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey" @@ -971,11 +1007,11 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> { "bitcoin::hash_types::Txid" if is_ref => Some(" }[..]).unwrap()"), "bitcoin::hash_types::Txid" => Some(".data[..]).unwrap()"), "bitcoin::hash_types::BlockHash" if !is_ref => Some(".data[..]).unwrap()"), - "lightning::ln::channelmanager::PaymentHash" if !is_ref => Some(".data)"), - "lightning::ln::channelmanager::PaymentHash" if is_ref => Some(" })"), - "lightning::ln::channelmanager::PaymentPreimage" if !is_ref => Some(".data)"), - "lightning::ln::channelmanager::PaymentPreimage" if is_ref => Some(" })"), - "lightning::ln::channelmanager::PaymentSecret" => Some(".data)"), + "lightning::ln::PaymentHash" if !is_ref => Some(".data)"), + "lightning::ln::PaymentHash" if is_ref => Some(" })"), + "lightning::ln::PaymentPreimage" if !is_ref => Some(".data)"), + "lightning::ln::PaymentPreimage" if is_ref => Some(" })"), + "lightning::ln::PaymentSecret" => Some(".data)"), // List of traits we map (possibly during processing of other files): "crate::util::logger::Logger" => Some(""), @@ -1034,6 +1070,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> { "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey" => Some("crate::c_types::PublicKey::from_rust(&"), "bitcoin::secp256k1::Signature" => Some("crate::c_types::Signature::from_rust(&"), + "bitcoin::secp256k1::recovery::RecoverableSignature" => Some("crate::c_types::RecoverableSignature::from_rust(&"), "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey" if is_ref => Some(""), "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey" @@ -1058,11 +1095,11 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> { "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "), "bitcoin::secp256k1::Message" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "), - "lightning::ln::channelmanager::PaymentHash" if is_ref => Some("&"), - "lightning::ln::channelmanager::PaymentHash" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "), - "lightning::ln::channelmanager::PaymentPreimage" if is_ref => Some("&"), - "lightning::ln::channelmanager::PaymentPreimage" => Some("crate::c_types::ThirtyTwoBytes { data: "), - "lightning::ln::channelmanager::PaymentSecret" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "), + "lightning::ln::PaymentHash" if is_ref => Some("&"), + "lightning::ln::PaymentHash" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "), + "lightning::ln::PaymentPreimage" if is_ref => Some("&"), + "lightning::ln::PaymentPreimage" => Some("crate::c_types::ThirtyTwoBytes { data: "), + "lightning::ln::PaymentSecret" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "), // Override the default since Records contain an fmt with a lifetime: "lightning::util::logger::Record" => Some("local_"), @@ -1091,8 +1128,8 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> { "[usize]" if is_ref => Some(""), "str" if is_ref => Some(".into()"), - "String" if !is_ref => Some(".into_bytes().into()"), "String" if is_ref => Some(".as_str().into()"), + "String" => Some(".into()"), "std::time::Duration" => Some(".as_secs()"), "std::time::SystemTime" => Some(".duration_since(::std::time::SystemTime::UNIX_EPOCH).expect(\"Times must be post-1970\").as_secs()"), @@ -1103,6 +1140,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> { "bitcoin::secp256k1::key::PublicKey"|"bitcoin::secp256k1::PublicKey"|"secp256k1::key::PublicKey" => Some(")"), "bitcoin::secp256k1::Signature" => Some(")"), + "bitcoin::secp256k1::recovery::RecoverableSignature" => Some(")"), "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey" if !is_ref => Some(")"), "bitcoin::secp256k1::key::SecretKey"|"bitcoin::secp256k1::SecretKey" @@ -1126,11 +1164,11 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> { "bitcoin::hash_types::Txid"|"bitcoin::hash_types::BlockHash"|"bitcoin_hashes::sha256::Hash" if !is_ref => Some(".into_inner() }"), "bitcoin::secp256k1::Message" if !is_ref => Some(".as_ref().clone() }"), - "lightning::ln::channelmanager::PaymentHash" if is_ref => Some(".0"), - "lightning::ln::channelmanager::PaymentHash" => Some(".0 }"), - "lightning::ln::channelmanager::PaymentPreimage" if is_ref => Some(".0"), - "lightning::ln::channelmanager::PaymentPreimage" => Some(".0 }"), - "lightning::ln::channelmanager::PaymentSecret" if !is_ref => Some(".0 }"), + "lightning::ln::PaymentHash" if is_ref => Some(".0"), + "lightning::ln::PaymentHash" => Some(".0 }"), + "lightning::ln::PaymentPreimage" if is_ref => Some(".0"), + "lightning::ln::PaymentPreimage" => Some(".0 }"), + "lightning::ln::PaymentSecret" if !is_ref => Some(".0 }"), // Override the default since Records contain an fmt with a lifetime: "lightning::util::logger::Record" => Some(".as_ptr()"), @@ -1141,7 +1179,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> { fn empty_val_check_suffix_from_path(&self, full_path: &str) -> Option<&str> { match full_path { - "lightning::ln::channelmanager::PaymentSecret" => Some(".data == [0; 32]"), + "lightning::ln::PaymentSecret" => Some(".data == [0; 32]"), "secp256k1::key::PublicKey"|"bitcoin::secp256k1::key::PublicKey" => Some(".is_null()"), "bitcoin::secp256k1::Signature" => Some(".is_null()"), _ => None @@ -1639,7 +1677,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> { LP: Fn(&str, bool, bool) -> Option, DL: Fn(&mut W, &DeclType, &str, bool, bool), SC: Fn(bool, Option<&str>) -> String> (&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, is_ref: bool, is_mut: bool, ptr_for_ref: bool, tupleconv: &str, prefix: bool, sliceconv: SC, path_lookup: LP, decl_lookup: DL) { - match t { + match generics.resolve_type(t) { syn::Type::Reference(r) => { self.write_conversion_inline_intern(w, &*r.elem, generics, true, r.mutability.is_some(), ptr_for_ref, tupleconv, prefix, sliceconv, path_lookup, decl_lookup); @@ -1737,7 +1775,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> { } fn write_to_c_conversion_inline_prefix_inner(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, is_ref: bool, ptr_for_ref: bool, from_ptr: bool) { - self.write_conversion_inline_intern(w, t, generics, is_ref, false, ptr_for_ref, "0u8 /*", true, |_, _| "local_".to_owned(), + self.write_conversion_inline_intern(w, t, generics, is_ref, false, ptr_for_ref, "() /*", true, |_, _| "local_".to_owned(), |a, b, c| self.to_c_conversion_inline_prefix_from_path(a, b, c), |w, decl_type, decl_path, is_ref, _is_mut| { match decl_type { @@ -1969,7 +2007,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> { } } } - match t { + match generics.resolve_type(t) { syn::Type::Reference(r) => { if let syn::Type::Slice(_) = &*r.elem { self.write_conversion_new_var_intern(w, ident, var, &*r.elem, generics, is_ref, ptr_for_ref, to_c, path_lookup, container_lookup, var_prefix, var_suffix) @@ -2413,7 +2451,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> { } } fn write_c_type_intern(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, is_ref: bool, is_mut: bool, ptr_for_ref: bool) -> bool { - match t { + match generics.resolve_type(t) { syn::Type::Path(p) => { if p.qself.is_some() { return false; diff --git a/lightning-c-bindings/Cargo.toml b/lightning-c-bindings/Cargo.toml index 169696a..badaf9f 100644 --- a/lightning-c-bindings/Cargo.toml +++ b/lightning-c-bindings/Cargo.toml @@ -18,9 +18,9 @@ crate-type = ["staticlib" bitcoin = "0.26" secp256k1 = { version = "0.20.1", features = ["global-context-less-secure"] } # Note that the following line is matched by genbindings to update the path -lightning = { git = "https://git.bitcoin.ninja/rust-lightning", rev = "cb0b4bfd76763c946b6479192d62d0cb0c67f6ed", features = ["allow_wallclock_use"] } -lightning-persister = { git = "https://git.bitcoin.ninja/rust-lightning", rev = "cb0b4bfd76763c946b6479192d62d0cb0c67f6ed" } -lightning-invoice = { git = "https://git.bitcoin.ninja/rust-lightning", rev = "cb0b4bfd76763c946b6479192d62d0cb0c67f6ed" } +lightning = { git = "https://git.bitcoin.ninja/rust-lightning", rev = "d4d322580994857b1222488f8467311d6db61482", features = ["allow_wallclock_use"] } +lightning-persister = { git = "https://git.bitcoin.ninja/rust-lightning", rev = "d4d322580994857b1222488f8467311d6db61482" } +lightning-invoice = { git = "https://git.bitcoin.ninja/rust-lightning", rev = "d4d322580994857b1222488f8467311d6db61482" } [patch.crates-io] # Rust-Secp256k1 PR 279. Should be dropped once merged. diff --git a/lightning-c-bindings/include/lightning.h b/lightning-c-bindings/include/lightning.h index fba5cc1..2527e65 100644 --- a/lightning-c-bindings/include/lightning.h +++ b/lightning-c-bindings/include/lightning.h @@ -1286,346 +1286,150 @@ typedef struct LDKCResult_CVec_SignatureZNoneZ { bool result_ok; } LDKCResult_CVec_SignatureZNoneZ; - - /** - * SHA-256 hash + * The contents of CResult_SiPrefixNoneZ */ -typedef struct MUST_USE_STRUCT LDKSha256 { - /** - * A pointer to the opaque Rust object. - * Nearly everywhere, inner must be non-null, however in places where - * the Rust equivalent takes an Option, it may be set to null to indicate None. - */ - LDKnativeSha256 *inner; - /** - * Indicates that this is the only struct which contains the same pointer. - * Rust functions which take ownership of an object provided via an argument require - * this to be true and invalidate the object pointed to by inner. - */ - bool is_owned; -} LDKSha256; - - - -/** - * Description string - * - * # Invariants - * The description can be at most 639 __bytes__ long - */ -typedef struct MUST_USE_STRUCT LDKDescription { +typedef union LDKCResult_SiPrefixNoneZPtr { /** - * A pointer to the opaque Rust object. - * Nearly everywhere, inner must be non-null, however in places where - * the Rust equivalent takes an Option, it may be set to null to indicate None. + * A pointer to the contents in the success state. + * Reading from this pointer when `result_ok` is not set is undefined. */ - LDKnativeDescription *inner; + enum LDKSiPrefix *result; /** - * Indicates that this is the only struct which contains the same pointer. - * Rust functions which take ownership of an object provided via an argument require - * this to be true and invalidate the object pointed to by inner. + * Note that this value is always NULL, as there are no contents in the Err variant */ - bool is_owned; -} LDKDescription; - - + void *err; +} LDKCResult_SiPrefixNoneZPtr; /** - * Payee public key + * A CResult_SiPrefixNoneZ represents the result of a fallible operation, + * containing a crate::lightning_invoice::SiPrefix on success and a () on failure. + * `result_ok` indicates the overall state, and the contents are provided via `contents`. */ -typedef struct MUST_USE_STRUCT LDKPayeePubKey { +typedef struct LDKCResult_SiPrefixNoneZ { /** - * A pointer to the opaque Rust object. - * Nearly everywhere, inner must be non-null, however in places where - * the Rust equivalent takes an Option, it may be set to null to indicate None. + * The contents of this CResult_SiPrefixNoneZ, accessible via either + * `err` or `result` depending on the state of `result_ok`. */ - LDKnativePayeePubKey *inner; + union LDKCResult_SiPrefixNoneZPtr contents; /** - * Indicates that this is the only struct which contains the same pointer. - * Rust functions which take ownership of an object provided via an argument require - * this to be true and invalidate the object pointed to by inner. + * Whether this CResult_SiPrefixNoneZ represents a success state. */ - bool is_owned; -} LDKPayeePubKey; + bool result_ok; +} LDKCResult_SiPrefixNoneZ; /** - * Positive duration that defines when (relatively to the timestamp) in the future the invoice - * expires + * Represents a syntactically and semantically correct lightning BOLT11 invoice. * - * # Invariants - * The number of seconds this expiry time represents has to be in the range - * `0...(SYSTEM_TIME_MAX_UNIX_TIMESTAMP - MAX_EXPIRY_TIME)` to avoid overflows when adding it to a - * timestamp + * There are three ways to construct an `Invoice`: + * 1. using `InvoiceBuilder` + * 2. using `Invoice::from_signed(SignedRawInvoice)` + * 3. using `str::parse::(&str)` */ -typedef struct MUST_USE_STRUCT LDKExpiryTime { +typedef struct MUST_USE_STRUCT LDKInvoice { /** * A pointer to the opaque Rust object. * Nearly everywhere, inner must be non-null, however in places where * the Rust equivalent takes an Option, it may be set to null to indicate None. */ - LDKnativeExpiryTime *inner; + LDKnativeInvoice *inner; /** * Indicates that this is the only struct which contains the same pointer. * Rust functions which take ownership of an object provided via an argument require * this to be true and invalidate the object pointed to by inner. */ bool is_owned; -} LDKExpiryTime; - - +} LDKInvoice; /** - * `min_final_cltv_expiry` to use for the last HTLC in the route + * The contents of CResult_InvoiceNoneZ */ -typedef struct MUST_USE_STRUCT LDKMinFinalCltvExpiry { +typedef union LDKCResult_InvoiceNoneZPtr { /** - * A pointer to the opaque Rust object. - * Nearly everywhere, inner must be non-null, however in places where - * the Rust equivalent takes an Option, it may be set to null to indicate None. + * A pointer to the contents in the success state. + * Reading from this pointer when `result_ok` is not set is undefined. */ - LDKnativeMinFinalCltvExpiry *inner; + struct LDKInvoice *result; /** - * Indicates that this is the only struct which contains the same pointer. - * Rust functions which take ownership of an object provided via an argument require - * this to be true and invalidate the object pointed to by inner. + * Note that this value is always NULL, as there are no contents in the Err variant */ - bool is_owned; -} LDKMinFinalCltvExpiry; - -/** - * Integer in the range `0..32` - */ -typedef struct LDKu5 { - uint8_t _0; -} LDKu5; + void *err; +} LDKCResult_InvoiceNoneZPtr; /** - * A 20-byte byte array. + * A CResult_InvoiceNoneZ represents the result of a fallible operation, + * containing a crate::lightning_invoice::Invoice on success and a () on failure. + * `result_ok` indicates the overall state, and the contents are provided via `contents`. */ -typedef struct LDKTwentyBytes { +typedef struct LDKCResult_InvoiceNoneZ { /** - * The twenty bytes + * The contents of this CResult_InvoiceNoneZ, accessible via either + * `err` or `result` depending on the state of `result_ok`. */ - uint8_t data[20]; -} LDKTwentyBytes; - -/** - * Fallback address in case no LN payment is possible - */ -typedef enum LDKFallback_Tag { - LDKFallback_SegWitProgram, - LDKFallback_PubKeyHash, - LDKFallback_ScriptHash, + union LDKCResult_InvoiceNoneZPtr contents; /** - * Must be last for serialization purposes + * Whether this CResult_InvoiceNoneZ represents a success state. */ - LDKFallback_Sentinel, -} LDKFallback_Tag; - -typedef struct LDKFallback_LDKSegWitProgram_Body { - struct LDKu5 version; - struct LDKCVec_u8Z program; -} LDKFallback_LDKSegWitProgram_Body; - -typedef struct MUST_USE_STRUCT LDKFallback { - LDKFallback_Tag tag; - union { - LDKFallback_LDKSegWitProgram_Body seg_wit_program; - struct { - struct LDKTwentyBytes pub_key_hash; - }; - struct { - struct LDKTwentyBytes script_hash; - }; - }; -} LDKFallback; + bool result_ok; +} LDKCResult_InvoiceNoneZ; /** - * Private routing information + * Represents a signed `RawInvoice` with cached hash. The signature is not checked and may be + * invalid. * * # Invariants - * The encoded route has to be <1024 5bit characters long (<=639 bytes or <=12 hops) - * - */ -typedef struct MUST_USE_STRUCT LDKRouteHint { - /** - * A pointer to the opaque Rust object. - * Nearly everywhere, inner must be non-null, however in places where - * the Rust equivalent takes an Option, it may be set to null to indicate None. - */ - LDKnativeRouteHint *inner; - /** - * Indicates that this is the only struct which contains the same pointer. - * Rust functions which take ownership of an object provided via an argument require - * this to be true and invalidate the object pointed to by inner. - */ - bool is_owned; -} LDKRouteHint; - - - -/** - * 256-bit payment secret - */ -typedef struct MUST_USE_STRUCT LDKPaymentSecret { - /** - * A pointer to the opaque Rust object. - * Nearly everywhere, inner must be non-null, however in places where - * the Rust equivalent takes an Option, it may be set to null to indicate None. - */ - LDKnativePaymentSecret *inner; - /** - * Indicates that this is the only struct which contains the same pointer. - * Rust functions which take ownership of an object provided via an argument require - * this to be true and invalidate the object pointed to by inner. - */ - bool is_owned; -} LDKPaymentSecret; - - - -/** - * Features used within an invoice. + * The hash has to be either from the deserialized invoice or from the serialized `raw_invoice`. */ -typedef struct MUST_USE_STRUCT LDKInvoiceFeatures { +typedef struct MUST_USE_STRUCT LDKSignedRawInvoice { /** * A pointer to the opaque Rust object. * Nearly everywhere, inner must be non-null, however in places where * the Rust equivalent takes an Option, it may be set to null to indicate None. */ - LDKnativeInvoiceFeatures *inner; + LDKnativeSignedRawInvoice *inner; /** * Indicates that this is the only struct which contains the same pointer. * Rust functions which take ownership of an object provided via an argument require * this to be true and invalidate the object pointed to by inner. */ bool is_owned; -} LDKInvoiceFeatures; - -/** - * Tagged field with known tag - * - * For descriptions of the enum values please refer to the enclosed type's docs. - */ -typedef enum LDKTaggedField_Tag { - LDKTaggedField_PaymentHash, - LDKTaggedField_Description, - LDKTaggedField_PayeePubKey, - LDKTaggedField_DescriptionHash, - LDKTaggedField_ExpiryTime, - LDKTaggedField_MinFinalCltvExpiry, - LDKTaggedField_Fallback, - LDKTaggedField_Route, - LDKTaggedField_PaymentSecret, - LDKTaggedField_Features, - /** - * Must be last for serialization purposes - */ - LDKTaggedField_Sentinel, -} LDKTaggedField_Tag; - -typedef struct MUST_USE_STRUCT LDKTaggedField { - LDKTaggedField_Tag tag; - union { - struct { - struct LDKSha256 payment_hash; - }; - struct { - struct LDKDescription description; - }; - struct { - struct LDKPayeePubKey payee_pub_key; - }; - struct { - struct LDKSha256 description_hash; - }; - struct { - struct LDKExpiryTime expiry_time; - }; - struct { - struct LDKMinFinalCltvExpiry min_final_cltv_expiry; - }; - struct { - struct LDKFallback fallback; - }; - struct { - struct LDKRouteHint route; - }; - struct { - struct LDKPaymentSecret payment_secret; - }; - struct { - struct LDKInvoiceFeatures features; - }; - }; -} LDKTaggedField; - -/** - * A dynamically-allocated array of crate::c_types::u5s of arbitrary size. - * This corresponds to std::vector in C++ - */ -typedef struct LDKCVec_u5Z { - /** - * The elements in the array. - * If datalen is non-0 this must be a valid, non-NULL pointer allocated by malloc(). - */ - struct LDKu5 *data; - /** - * The number of elements pointed to by `data`. - */ - uintptr_t datalen; -} LDKCVec_u5Z; +} LDKSignedRawInvoice; /** - * Tagged field which may have an unknown tag + * The contents of CResult_SignedRawInvoiceNoneZ */ -typedef enum LDKRawTaggedField_Tag { - /** - * Parsed tagged field with known tag - */ - LDKRawTaggedField_KnownSemantics, +typedef union LDKCResult_SignedRawInvoiceNoneZPtr { /** - * tagged field which was not parsed due to an unknown tag or undefined field semantics + * A pointer to the contents in the success state. + * Reading from this pointer when `result_ok` is not set is undefined. */ - LDKRawTaggedField_UnknownSemantics, + struct LDKSignedRawInvoice *result; /** - * Must be last for serialization purposes + * Note that this value is always NULL, as there are no contents in the Err variant */ - LDKRawTaggedField_Sentinel, -} LDKRawTaggedField_Tag; - -typedef struct MUST_USE_STRUCT LDKRawTaggedField { - LDKRawTaggedField_Tag tag; - union { - struct { - struct LDKTaggedField known_semantics; - }; - struct { - struct LDKCVec_u5Z unknown_semantics; - }; - }; -} LDKRawTaggedField; + void *err; +} LDKCResult_SignedRawInvoiceNoneZPtr; /** - * A dynamically-allocated array of crate::lightning_invoice::RawTaggedFields of arbitrary size. - * This corresponds to std::vector in C++ + * A CResult_SignedRawInvoiceNoneZ represents the result of a fallible operation, + * containing a crate::lightning_invoice::SignedRawInvoice on success and a () on failure. + * `result_ok` indicates the overall state, and the contents are provided via `contents`. */ -typedef struct LDKCVec_RawTaggedFieldZ { +typedef struct LDKCResult_SignedRawInvoiceNoneZ { /** - * The elements in the array. - * If datalen is non-0 this must be a valid, non-NULL pointer allocated by malloc(). + * The contents of this CResult_SignedRawInvoiceNoneZ, accessible via either + * `err` or `result` depending on the state of `result_ok`. */ - struct LDKRawTaggedField *data; + union LDKCResult_SignedRawInvoiceNoneZPtr contents; /** - * The number of elements pointed to by `data`. + * Whether this CResult_SignedRawInvoiceNoneZ represents a success state. */ - uintptr_t datalen; -} LDKCVec_RawTaggedFieldZ; + bool result_ok; +} LDKCResult_SignedRawInvoiceNoneZ; @@ -1700,6 +1504,26 @@ typedef struct LDKC3Tuple_RawInvoice_u832InvoiceSignatureZ { struct LDKInvoiceSignature c; } LDKC3Tuple_RawInvoice_u832InvoiceSignatureZ; + + +/** + * Payee public key + */ +typedef struct MUST_USE_STRUCT LDKPayeePubKey { + /** + * A pointer to the opaque Rust object. + * Nearly everywhere, inner must be non-null, however in places where + * the Rust equivalent takes an Option, it may be set to null to indicate None. + */ + LDKnativePayeePubKey *inner; + /** + * Indicates that this is the only struct which contains the same pointer. + * Rust functions which take ownership of an object provided via an argument require + * this to be true and invalidate the object pointed to by inner. + */ + bool is_owned; +} LDKPayeePubKey; + /** * The contents of CResult_PayeePubKeyErrorZ */ @@ -1733,6 +1557,30 @@ typedef struct LDKCResult_PayeePubKeyErrorZ { bool result_ok; } LDKCResult_PayeePubKeyErrorZ; + + +/** + * Private routing information + * + * # Invariants + * The encoded route has to be <1024 5bit characters long (<=639 bytes or <=12 hops) + * + */ +typedef struct MUST_USE_STRUCT LDKRouteHint { + /** + * A pointer to the opaque Rust object. + * Nearly everywhere, inner must be non-null, however in places where + * the Rust equivalent takes an Option, it may be set to null to indicate None. + */ + LDKnativeRouteHint *inner; + /** + * Indicates that this is the only struct which contains the same pointer. + * Rust functions which take ownership of an object provided via an argument require + * this to be true and invalidate the object pointed to by inner. + */ + bool is_owned; +} LDKRouteHint; + /** * A dynamically-allocated array of crate::lightning_invoice::RouteHints of arbitrary size. * This corresponds to std::vector in C++ @@ -1866,31 +1714,6 @@ typedef struct LDKCResult_NoneSemanticErrorZ { bool result_ok; } LDKCResult_NoneSemanticErrorZ; - - -/** - * Represents a syntactically and semantically correct lightning BOLT11 invoice. - * - * There are three ways to construct an `Invoice`: - * 1. using `InvoiceBuilder` - * 2. using `Invoice::from_signed(SignedRawInvoice)` - * 3. using `str::parse::(&str)` - */ -typedef struct MUST_USE_STRUCT LDKInvoice { - /** - * A pointer to the opaque Rust object. - * Nearly everywhere, inner must be non-null, however in places where - * the Rust equivalent takes an Option, it may be set to null to indicate None. - */ - LDKnativeInvoice *inner; - /** - * Indicates that this is the only struct which contains the same pointer. - * Rust functions which take ownership of an object provided via an argument require - * this to be true and invalidate the object pointed to by inner. - */ - bool is_owned; -} LDKInvoice; - /** * The contents of CResult_InvoiceSemanticErrorZ */ @@ -1924,6 +1747,29 @@ typedef struct LDKCResult_InvoiceSemanticErrorZ { bool result_ok; } LDKCResult_InvoiceSemanticErrorZ; + + +/** + * Description string + * + * # Invariants + * The description can be at most 639 __bytes__ long + */ +typedef struct MUST_USE_STRUCT LDKDescription { + /** + * A pointer to the opaque Rust object. + * Nearly everywhere, inner must be non-null, however in places where + * the Rust equivalent takes an Option, it may be set to null to indicate None. + */ + LDKnativeDescription *inner; + /** + * Indicates that this is the only struct which contains the same pointer. + * Rust functions which take ownership of an object provided via an argument require + * this to be true and invalidate the object pointed to by inner. + */ + bool is_owned; +} LDKDescription; + /** * The contents of CResult_DescriptionCreationErrorZ */ @@ -1957,6 +1803,32 @@ typedef struct LDKCResult_DescriptionCreationErrorZ { bool result_ok; } LDKCResult_DescriptionCreationErrorZ; + + +/** + * Positive duration that defines when (relatively to the timestamp) in the future the invoice + * expires + * + * # Invariants + * The number of seconds this expiry time represents has to be in the range + * `0...(SYSTEM_TIME_MAX_UNIX_TIMESTAMP - MAX_EXPIRY_TIME)` to avoid overflows when adding it to a + * timestamp + */ +typedef struct MUST_USE_STRUCT LDKExpiryTime { + /** + * A pointer to the opaque Rust object. + * Nearly everywhere, inner must be non-null, however in places where + * the Rust equivalent takes an Option, it may be set to null to indicate None. + */ + LDKnativeExpiryTime *inner; + /** + * Indicates that this is the only struct which contains the same pointer. + * Rust functions which take ownership of an object provided via an argument require + * this to be true and invalidate the object pointed to by inner. + */ + bool is_owned; +} LDKExpiryTime; + /** * The contents of CResult_ExpiryTimeCreationErrorZ */ @@ -2067,7 +1939,7 @@ typedef union LDKCResult_StringErrorZPtr { * A pointer to the contents in the success state. * Reading from this pointer when `result_ok` is not set is undefined. */ - struct LDKCVec_u8Z *result; + struct LDKStr *result; /** * A pointer to the contents in the error state. * Reading from this pointer when `result_ok` is set is undefined. @@ -2077,7 +1949,7 @@ typedef union LDKCResult_StringErrorZPtr { /** * A CResult_StringErrorZ represents the result of a fallible operation, - * containing a crate::c_types::derived::CVec_u8Z on success and a crate::c_types::Secp256k1Error on failure. + * containing a crate::c_types::Str on success and a crate::c_types::Secp256k1Error on failure. * `result_ok` indicates the overall state, and the contents are provided via `contents`. */ typedef struct LDKCResult_StringErrorZ { @@ -5206,6 +5078,26 @@ typedef struct LDKCResult_ChannelFeaturesDecodeErrorZ { bool result_ok; } LDKCResult_ChannelFeaturesDecodeErrorZ; + + +/** + * Features used within an invoice. + */ +typedef struct MUST_USE_STRUCT LDKInvoiceFeatures { + /** + * A pointer to the opaque Rust object. + * Nearly everywhere, inner must be non-null, however in places where + * the Rust equivalent takes an Option, it may be set to null to indicate None. + */ + LDKnativeInvoiceFeatures *inner; + /** + * Indicates that this is the only struct which contains the same pointer. + * Rust functions which take ownership of an object provided via an argument require + * this to be true and invalidate the object pointed to by inner. + */ + bool is_owned; +} LDKInvoiceFeatures; + /** * The contents of CResult_InvoiceFeaturesDecodeErrorZ */ @@ -6625,37 +6517,98 @@ typedef struct MUST_USE_STRUCT LDKGossipTimestampFilter { } LDKGossipTimestampFilter; /** - * The contents of CResult_GossipTimestampFilterDecodeErrorZ + * The contents of CResult_GossipTimestampFilterDecodeErrorZ + */ +typedef union LDKCResult_GossipTimestampFilterDecodeErrorZPtr { + /** + * A pointer to the contents in the success state. + * Reading from this pointer when `result_ok` is not set is undefined. + */ + struct LDKGossipTimestampFilter *result; + /** + * A pointer to the contents in the error state. + * Reading from this pointer when `result_ok` is set is undefined. + */ + struct LDKDecodeError *err; +} LDKCResult_GossipTimestampFilterDecodeErrorZPtr; + +/** + * A CResult_GossipTimestampFilterDecodeErrorZ represents the result of a fallible operation, + * containing a crate::lightning::ln::msgs::GossipTimestampFilter on success and a crate::lightning::ln::msgs::DecodeError on failure. + * `result_ok` indicates the overall state, and the contents are provided via `contents`. + */ +typedef struct LDKCResult_GossipTimestampFilterDecodeErrorZ { + /** + * The contents of this CResult_GossipTimestampFilterDecodeErrorZ, accessible via either + * `err` or `result` depending on the state of `result_ok`. + */ + union LDKCResult_GossipTimestampFilterDecodeErrorZPtr contents; + /** + * Whether this CResult_GossipTimestampFilterDecodeErrorZ represents a success state. + */ + bool result_ok; +} LDKCResult_GossipTimestampFilterDecodeErrorZ; + +/** + * When signing using a fallible method either an user-supplied `SignError` or a `CreationError` + * may occur. + */ +typedef enum LDKSignOrCreationError_Tag { + /** + * An error occurred during signing + */ + LDKSignOrCreationError_SignError, + /** + * An error occurred while building the transaction + */ + LDKSignOrCreationError_CreationError, + /** + * Must be last for serialization purposes + */ + LDKSignOrCreationError_Sentinel, +} LDKSignOrCreationError_Tag; + +typedef struct MUST_USE_STRUCT LDKSignOrCreationError { + LDKSignOrCreationError_Tag tag; + union { + struct { + enum LDKCreationError creation_error; + }; + }; +} LDKSignOrCreationError; + +/** + * The contents of CResult_InvoiceSignOrCreationErrorZ */ -typedef union LDKCResult_GossipTimestampFilterDecodeErrorZPtr { +typedef union LDKCResult_InvoiceSignOrCreationErrorZPtr { /** * A pointer to the contents in the success state. * Reading from this pointer when `result_ok` is not set is undefined. */ - struct LDKGossipTimestampFilter *result; + struct LDKInvoice *result; /** * A pointer to the contents in the error state. * Reading from this pointer when `result_ok` is set is undefined. */ - struct LDKDecodeError *err; -} LDKCResult_GossipTimestampFilterDecodeErrorZPtr; + struct LDKSignOrCreationError *err; +} LDKCResult_InvoiceSignOrCreationErrorZPtr; /** - * A CResult_GossipTimestampFilterDecodeErrorZ represents the result of a fallible operation, - * containing a crate::lightning::ln::msgs::GossipTimestampFilter on success and a crate::lightning::ln::msgs::DecodeError on failure. + * A CResult_InvoiceSignOrCreationErrorZ represents the result of a fallible operation, + * containing a crate::lightning_invoice::Invoice on success and a crate::lightning_invoice::SignOrCreationError on failure. * `result_ok` indicates the overall state, and the contents are provided via `contents`. */ -typedef struct LDKCResult_GossipTimestampFilterDecodeErrorZ { +typedef struct LDKCResult_InvoiceSignOrCreationErrorZ { /** - * The contents of this CResult_GossipTimestampFilterDecodeErrorZ, accessible via either + * The contents of this CResult_InvoiceSignOrCreationErrorZ, accessible via either * `err` or `result` depending on the state of `result_ok`. */ - union LDKCResult_GossipTimestampFilterDecodeErrorZPtr contents; + union LDKCResult_InvoiceSignOrCreationErrorZPtr contents; /** - * Whether this CResult_GossipTimestampFilterDecodeErrorZ represents a success state. + * Whether this CResult_InvoiceSignOrCreationErrorZ represents a success state. */ bool result_ok; -} LDKCResult_GossipTimestampFilterDecodeErrorZ; +} LDKCResult_InvoiceSignOrCreationErrorZ; /** * The contents of CResult_SpendableOutputDescriptorDecodeErrorZ @@ -6723,6 +6676,50 @@ typedef struct LDKCResult_SignDecodeErrorZ { bool result_ok; } LDKCResult_SignDecodeErrorZ; +/** + * Represents a secp256k1 signature serialized as two 32-byte numbers as well as a tag which + * allows recovering the exact public key which created the signature given the message. + */ +typedef struct LDKRecoverableSignature { + /** + * The bytes of the signature in "compact" form plus a "Recovery ID" which allows for + * recovery. + */ + uint8_t serialized_form[68]; +} LDKRecoverableSignature; + +/** + * The contents of CResult_RecoverableSignatureNoneZ + */ +typedef union LDKCResult_RecoverableSignatureNoneZPtr { + /** + * A pointer to the contents in the success state. + * Reading from this pointer when `result_ok` is not set is undefined. + */ + struct LDKRecoverableSignature *result; + /** + * Note that this value is always NULL, as there are no contents in the Err variant + */ + void *err; +} LDKCResult_RecoverableSignatureNoneZPtr; + +/** + * A CResult_RecoverableSignatureNoneZ represents the result of a fallible operation, + * containing a crate::c_types::RecoverableSignature on success and a () on failure. + * `result_ok` indicates the overall state, and the contents are provided via `contents`. + */ +typedef struct LDKCResult_RecoverableSignatureNoneZ { + /** + * The contents of this CResult_RecoverableSignatureNoneZ, accessible via either + * `err` or `result` depending on the state of `result_ok`. + */ + union LDKCResult_RecoverableSignatureNoneZPtr contents; + /** + * Whether this CResult_RecoverableSignatureNoneZ represents a success state. + */ + bool result_ok; +} LDKCResult_RecoverableSignatureNoneZ; + /** * A dynamically-allocated array of crate::c_types::derived::CVec_u8Zs of arbitrary size. * This corresponds to std::vector in C++ @@ -6998,14 +6995,14 @@ typedef struct LDKAPIError_LDKAPIMisuseError_Body { /** * A human-readable error message */ - struct LDKCVec_u8Z err; + struct LDKStr err; } LDKAPIError_LDKAPIMisuseError_Body; typedef struct LDKAPIError_LDKFeeRateTooHigh_Body { /** * A human-readable error message */ - struct LDKCVec_u8Z err; + struct LDKStr err; /** * The feerate which was too high. */ @@ -7023,7 +7020,7 @@ typedef struct LDKAPIError_LDKChannelUnavailable_Body { /** * A human-readable error message */ - struct LDKCVec_u8Z err; + struct LDKStr err; } LDKAPIError_LDKChannelUnavailable_Body; typedef struct MUST_USE_STRUCT LDKAPIError { @@ -7414,6 +7411,13 @@ typedef struct LDKKeysInterface { * you've read all of the provided bytes to ensure no corruption occurred. */ struct LDKCResult_SignDecodeErrorZ (*read_chan_signer)(const void *this_arg, 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. + */ + struct LDKCResult_RecoverableSignatureNoneZ (*sign_invoice)(const void *this_arg, struct LDKCVec_u8Z invoice_preimage); /** * 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. @@ -8614,46 +8618,110 @@ typedef struct MUST_USE_STRUCT LDKFilesystemPersister { /** - * Represents a signed `RawInvoice` with cached hash. The signature is not checked and may be - * invalid. - * - * # Invariants - * The hash has to be either from the deserialized invoice or from the serialized `raw_invoice`. + * Data of the `RawInvoice` that is encoded in the data part */ -typedef struct MUST_USE_STRUCT LDKSignedRawInvoice { +typedef struct MUST_USE_STRUCT LDKRawDataPart { /** * A pointer to the opaque Rust object. * Nearly everywhere, inner must be non-null, however in places where * the Rust equivalent takes an Option, it may be set to null to indicate None. */ - LDKnativeSignedRawInvoice *inner; + LDKnativeRawDataPart *inner; /** * Indicates that this is the only struct which contains the same pointer. * Rust functions which take ownership of an object provided via an argument require * this to be true and invalidate the object pointed to by inner. */ bool is_owned; -} LDKSignedRawInvoice; +} LDKRawDataPart; /** - * Data of the `RawInvoice` that is encoded in the data part + * SHA-256 hash */ -typedef struct MUST_USE_STRUCT LDKRawDataPart { +typedef struct MUST_USE_STRUCT LDKSha256 { /** * A pointer to the opaque Rust object. * Nearly everywhere, inner must be non-null, however in places where * the Rust equivalent takes an Option, it may be set to null to indicate None. */ - LDKnativeRawDataPart *inner; + LDKnativeSha256 *inner; /** * Indicates that this is the only struct which contains the same pointer. * Rust functions which take ownership of an object provided via an argument require * this to be true and invalidate the object pointed to by inner. */ bool is_owned; -} LDKRawDataPart; +} LDKSha256; + + + +/** + * `min_final_cltv_expiry` to use for the last HTLC in the route + */ +typedef struct MUST_USE_STRUCT LDKMinFinalCltvExpiry { + /** + * A pointer to the opaque Rust object. + * Nearly everywhere, inner must be non-null, however in places where + * the Rust equivalent takes an Option, it may be set to null to indicate None. + */ + LDKnativeMinFinalCltvExpiry *inner; + /** + * Indicates that this is the only struct which contains the same pointer. + * Rust functions which take ownership of an object provided via an argument require + * this to be true and invalidate the object pointed to by inner. + */ + bool is_owned; +} LDKMinFinalCltvExpiry; + +/** + * Integer in the range `0..32` + */ +typedef struct LDKu5 { + uint8_t _0; +} LDKu5; + +/** + * A 20-byte byte array. + */ +typedef struct LDKTwentyBytes { + /** + * The twenty bytes + */ + uint8_t data[20]; +} LDKTwentyBytes; + +/** + * Fallback address in case no LN payment is possible + */ +typedef enum LDKFallback_Tag { + LDKFallback_SegWitProgram, + LDKFallback_PubKeyHash, + LDKFallback_ScriptHash, + /** + * Must be last for serialization purposes + */ + LDKFallback_Sentinel, +} LDKFallback_Tag; + +typedef struct LDKFallback_LDKSegWitProgram_Body { + struct LDKu5 version; + struct LDKCVec_u8Z program; +} LDKFallback_LDKSegWitProgram_Body; + +typedef struct MUST_USE_STRUCT LDKFallback { + LDKFallback_Tag tag; + union { + LDKFallback_LDKSegWitProgram_Body seg_wit_program; + struct { + struct LDKTwentyBytes pub_key_hash; + }; + struct { + struct LDKTwentyBytes script_hash; + }; + }; +} LDKFallback; extern const uintptr_t MAX_BUF_SIZE; @@ -9027,14 +9095,67 @@ void CResult_CVec_SignatureZNoneZ_free(struct LDKCResult_CVec_SignatureZNoneZ _r struct LDKCResult_CVec_SignatureZNoneZ CResult_CVec_SignatureZNoneZ_clone(const struct LDKCResult_CVec_SignatureZNoneZ *NONNULL_PTR orig); /** - * Frees the buffer pointed to by `data` if `datalen` is non-0. + * Creates a new CResult_SiPrefixNoneZ in the success state. */ -void CVec_RawTaggedFieldZ_free(struct LDKCVec_RawTaggedFieldZ _res); +struct LDKCResult_SiPrefixNoneZ CResult_SiPrefixNoneZ_ok(enum LDKSiPrefix o); /** - * Frees the buffer pointed to by `data` if `datalen` is non-0. + * Creates a new CResult_SiPrefixNoneZ in the error state. + */ +struct LDKCResult_SiPrefixNoneZ CResult_SiPrefixNoneZ_err(void); + +/** + * Frees any resources used by the CResult_SiPrefixNoneZ. + */ +void CResult_SiPrefixNoneZ_free(struct LDKCResult_SiPrefixNoneZ _res); + +/** + * Creates a new CResult_SiPrefixNoneZ which has the same data as `orig` + * but with all dynamically-allocated buffers duplicated in new buffers. + */ +struct LDKCResult_SiPrefixNoneZ CResult_SiPrefixNoneZ_clone(const struct LDKCResult_SiPrefixNoneZ *NONNULL_PTR orig); + +/** + * Creates a new CResult_InvoiceNoneZ in the success state. + */ +struct LDKCResult_InvoiceNoneZ CResult_InvoiceNoneZ_ok(struct LDKInvoice o); + +/** + * Creates a new CResult_InvoiceNoneZ in the error state. + */ +struct LDKCResult_InvoiceNoneZ CResult_InvoiceNoneZ_err(void); + +/** + * Frees any resources used by the CResult_InvoiceNoneZ. + */ +void CResult_InvoiceNoneZ_free(struct LDKCResult_InvoiceNoneZ _res); + +/** + * Creates a new CResult_InvoiceNoneZ which has the same data as `orig` + * but with all dynamically-allocated buffers duplicated in new buffers. + */ +struct LDKCResult_InvoiceNoneZ CResult_InvoiceNoneZ_clone(const struct LDKCResult_InvoiceNoneZ *NONNULL_PTR orig); + +/** + * Creates a new CResult_SignedRawInvoiceNoneZ in the success state. + */ +struct LDKCResult_SignedRawInvoiceNoneZ CResult_SignedRawInvoiceNoneZ_ok(struct LDKSignedRawInvoice o); + +/** + * Creates a new CResult_SignedRawInvoiceNoneZ in the error state. + */ +struct LDKCResult_SignedRawInvoiceNoneZ CResult_SignedRawInvoiceNoneZ_err(void); + +/** + * Frees any resources used by the CResult_SignedRawInvoiceNoneZ. + */ +void CResult_SignedRawInvoiceNoneZ_free(struct LDKCResult_SignedRawInvoiceNoneZ _res); + +/** + * Creates a new CResult_SignedRawInvoiceNoneZ which has the same data as `orig` + * but with all dynamically-allocated buffers duplicated in new buffers. */ -void CVec_u5Z_free(struct LDKCVec_u5Z _res); +struct LDKCResult_SignedRawInvoiceNoneZ CResult_SignedRawInvoiceNoneZ_clone(const struct LDKCResult_SignedRawInvoiceNoneZ *NONNULL_PTR orig); /** * Frees the buffer pointed to by `data` if `datalen` is non-0. @@ -9226,7 +9347,7 @@ struct LDKCResult_RouteHintCreationErrorZ CResult_RouteHintCreationErrorZ_clone( /** * Creates a new CResult_StringErrorZ in the success state. */ -struct LDKCResult_StringErrorZ CResult_StringErrorZ_ok(struct LDKCVec_u8Z o); +struct LDKCResult_StringErrorZ CResult_StringErrorZ_ok(struct LDKStr o); /** * Creates a new CResult_StringErrorZ in the error state. @@ -10618,6 +10739,27 @@ void CResult_GossipTimestampFilterDecodeErrorZ_free(struct LDKCResult_GossipTime */ struct LDKCResult_GossipTimestampFilterDecodeErrorZ CResult_GossipTimestampFilterDecodeErrorZ_clone(const struct LDKCResult_GossipTimestampFilterDecodeErrorZ *NONNULL_PTR orig); +/** + * Creates a new CResult_InvoiceSignOrCreationErrorZ in the success state. + */ +struct LDKCResult_InvoiceSignOrCreationErrorZ CResult_InvoiceSignOrCreationErrorZ_ok(struct LDKInvoice o); + +/** + * Creates a new CResult_InvoiceSignOrCreationErrorZ in the error state. + */ +struct LDKCResult_InvoiceSignOrCreationErrorZ CResult_InvoiceSignOrCreationErrorZ_err(struct LDKSignOrCreationError e); + +/** + * Frees any resources used by the CResult_InvoiceSignOrCreationErrorZ. + */ +void CResult_InvoiceSignOrCreationErrorZ_free(struct LDKCResult_InvoiceSignOrCreationErrorZ _res); + +/** + * Creates a new CResult_InvoiceSignOrCreationErrorZ which has the same data as `orig` + * but with all dynamically-allocated buffers duplicated in new buffers. + */ +struct LDKCResult_InvoiceSignOrCreationErrorZ CResult_InvoiceSignOrCreationErrorZ_clone(const struct LDKCResult_InvoiceSignOrCreationErrorZ *NONNULL_PTR orig); + /** * Creates a new CResult_SpendableOutputDescriptorDecodeErrorZ in the success state. */ @@ -10718,6 +10860,27 @@ void CResult_SignDecodeErrorZ_free(struct LDKCResult_SignDecodeErrorZ _res); */ struct LDKCResult_SignDecodeErrorZ CResult_SignDecodeErrorZ_clone(const struct LDKCResult_SignDecodeErrorZ *NONNULL_PTR orig); +/** + * Creates a new CResult_RecoverableSignatureNoneZ in the success state. + */ +struct LDKCResult_RecoverableSignatureNoneZ CResult_RecoverableSignatureNoneZ_ok(struct LDKRecoverableSignature o); + +/** + * Creates a new CResult_RecoverableSignatureNoneZ in the error state. + */ +struct LDKCResult_RecoverableSignatureNoneZ CResult_RecoverableSignatureNoneZ_err(void); + +/** + * Frees any resources used by the CResult_RecoverableSignatureNoneZ. + */ +void CResult_RecoverableSignatureNoneZ_free(struct LDKCResult_RecoverableSignatureNoneZ _res); + +/** + * Creates a new CResult_RecoverableSignatureNoneZ which has the same data as `orig` + * but with all dynamically-allocated buffers duplicated in new buffers. + */ +struct LDKCResult_RecoverableSignatureNoneZ CResult_RecoverableSignatureNoneZ_clone(const struct LDKCResult_RecoverableSignatureNoneZ *NONNULL_PTR orig); + /** * Frees the buffer pointed to by `data` if `datalen` is non-0. */ @@ -12811,6 +12974,10 @@ MUST_USE_RES struct LDKC2Tuple_PaymentHashPaymentSecretZ ChannelManager_create_i * If you need exact expiry semantics, you should enforce them upon receipt of * [`PaymentReceived`]. * + * Pending inbound payments are stored in memory and in serialized versions of this + * [`ChannelManager`]. If potentially unbounded numbers of inbound payments may exist and + * space is limited, you may wish to rate-limit inbound payment creation. + * * May panic if `invoice_expiry_delta_secs` is greater than one year. * * Note that invoices generated for inbound payments should have their `min_final_cltv_expiry` @@ -13038,12 +13205,12 @@ struct LDKStr ErrorMessage_get_data(const struct LDKErrorMessage *NONNULL_PTR th * or printed to stdout). Otherwise, a well crafted error message may trigger a security * vulnerability in the terminal emulator or the logging subsystem. */ -void ErrorMessage_set_data(struct LDKErrorMessage *NONNULL_PTR this_ptr, struct LDKCVec_u8Z val); +void ErrorMessage_set_data(struct LDKErrorMessage *NONNULL_PTR this_ptr, struct LDKStr val); /** * Constructs a new ErrorMessage given each field */ -MUST_USE_RES struct LDKErrorMessage ErrorMessage_new(struct LDKThirtyTwoBytes channel_id_arg, struct LDKCVec_u8Z data_arg); +MUST_USE_RES struct LDKErrorMessage ErrorMessage_new(struct LDKThirtyTwoBytes channel_id_arg, struct LDKStr data_arg); /** * Creates a copy of the ErrorMessage @@ -14736,7 +14903,7 @@ struct LDKStr LightningError_get_err(const struct LDKLightningError *NONNULL_PTR /** * A human-readable message describing the error */ -void LightningError_set_err(struct LDKLightningError *NONNULL_PTR this_ptr, struct LDKCVec_u8Z val); +void LightningError_set_err(struct LDKLightningError *NONNULL_PTR this_ptr, struct LDKStr val); /** * The action which should be taken against the offending peer. @@ -14751,7 +14918,7 @@ void LightningError_set_action(struct LDKLightningError *NONNULL_PTR this_ptr, s /** * Constructs a new LightningError given each field */ -MUST_USE_RES struct LDKLightningError LightningError_new(struct LDKCVec_u8Z err_arg, struct LDKErrorAction action_arg); +MUST_USE_RES struct LDKLightningError LightningError_new(struct LDKStr err_arg, struct LDKErrorAction action_arg); /** * Creates a copy of the LightningError @@ -16995,18 +17162,18 @@ void FilesystemPersister_free(struct LDKFilesystemPersister this_obj); * Initialize a new FilesystemPersister and set the path to the individual channels' * files. */ -MUST_USE_RES struct LDKFilesystemPersister FilesystemPersister_new(struct LDKCVec_u8Z path_to_channel_data); +MUST_USE_RES struct LDKFilesystemPersister FilesystemPersister_new(struct LDKStr path_to_channel_data); /** * Get the directory which was provided when this persister was initialized. */ -MUST_USE_RES struct LDKCVec_u8Z FilesystemPersister_get_data_dir(const struct LDKFilesystemPersister *NONNULL_PTR this_arg); +MUST_USE_RES struct LDKStr FilesystemPersister_get_data_dir(const struct LDKFilesystemPersister *NONNULL_PTR this_arg); /** * Writes the provided `ChannelManager` to the path provided at `FilesystemPersister` * initialization, within a file called \"manager\". */ -MUST_USE_RES struct LDKCResult_NoneErrorZ FilesystemPersister_persist_manager(struct LDKCVec_u8Z data_dir, const struct LDKChannelManager *NONNULL_PTR manager); +MUST_USE_RES struct LDKCResult_NoneErrorZ FilesystemPersister_persist_manager(struct LDKStr data_dir, const struct LDKChannelManager *NONNULL_PTR manager); /** * Read `ChannelMonitor`s from disk. @@ -17091,16 +17258,6 @@ struct LDKPositiveTimestamp RawDataPart_get_timestamp(const struct LDKRawDataPar */ void RawDataPart_set_timestamp(struct LDKRawDataPart *NONNULL_PTR this_ptr, struct LDKPositiveTimestamp val); -/** - * tagged fields of the payment request - */ -void RawDataPart_set_tagged_fields(struct LDKRawDataPart *NONNULL_PTR this_ptr, struct LDKCVec_RawTaggedFieldZ val); - -/** - * Constructs a new RawDataPart given each field - */ -MUST_USE_RES struct LDKRawDataPart RawDataPart_new(struct LDKPositiveTimestamp timestamp_arg, struct LDKCVec_RawTaggedFieldZ tagged_fields_arg); - /** * Creates a copy of the RawDataPart */ @@ -17132,26 +17289,6 @@ MUST_USE_RES uint64_t SiPrefix_multiplier(const enum LDKSiPrefix *NONNULL_PTR th */ enum LDKCurrency Currency_clone(const enum LDKCurrency *NONNULL_PTR orig); -/** - * Frees any resources used by the RawTaggedField - */ -void RawTaggedField_free(struct LDKRawTaggedField this_ptr); - -/** - * Creates a copy of the RawTaggedField - */ -struct LDKRawTaggedField RawTaggedField_clone(const struct LDKRawTaggedField *NONNULL_PTR orig); - -/** - * Frees any resources used by the TaggedField - */ -void TaggedField_free(struct LDKTaggedField this_ptr); - -/** - * Creates a copy of the TaggedField - */ -struct LDKTaggedField TaggedField_clone(const struct LDKTaggedField *NONNULL_PTR orig); - /** * Frees any resources used by the Sha256, if is_owned is set and inner is non-NULL. */ @@ -17182,16 +17319,6 @@ void PayeePubKey_free(struct LDKPayeePubKey this_obj); */ struct LDKPayeePubKey PayeePubKey_clone(const struct LDKPayeePubKey *NONNULL_PTR orig); -/** - * Frees any resources used by the PaymentSecret, if is_owned is set and inner is non-NULL. - */ -void PaymentSecret_free(struct LDKPaymentSecret this_obj); - -/** - * Creates a copy of the PaymentSecret - */ -struct LDKPaymentSecret PaymentSecret_clone(const struct LDKPaymentSecret *NONNULL_PTR orig); - /** * Frees any resources used by the ExpiryTime, if is_owned is set and inner is non-NULL. */ @@ -17293,7 +17420,7 @@ MUST_USE_RES struct LDKExpiryTime RawInvoice_expiry_time(const struct LDKRawInvo MUST_USE_RES struct LDKMinFinalCltvExpiry RawInvoice_min_final_cltv_expiry(const struct LDKRawInvoice *NONNULL_PTR this_arg); -MUST_USE_RES struct LDKPaymentSecret RawInvoice_payment_secret(const struct LDKRawInvoice *NONNULL_PTR this_arg); +MUST_USE_RES struct LDKThirtyTwoBytes RawInvoice_payment_secret(const struct LDKRawInvoice *NONNULL_PTR this_arg); MUST_USE_RES struct LDKInvoiceFeatures RawInvoice_features(const struct LDKRawInvoice *NONNULL_PTR this_arg); @@ -17372,7 +17499,7 @@ MUST_USE_RES struct LDKPublicKey Invoice_payee_pub_key(const struct LDKInvoice * /** * Get the payment secret if one was included in the invoice */ -MUST_USE_RES struct LDKPaymentSecret Invoice_payment_secret(const struct LDKInvoice *NONNULL_PTR this_arg); +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 @@ -17385,14 +17512,15 @@ MUST_USE_RES struct LDKInvoiceFeatures Invoice_features(const struct LDKInvoice MUST_USE_RES struct LDKPublicKey Invoice_recover_payee_pub_key(const struct LDKInvoice *NONNULL_PTR this_arg); /** - * Returns the invoice's expiry time if present + * Returns the invoice's expiry time, if present, otherwise [`DEFAULT_EXPIRY_TIME`]. */ MUST_USE_RES uint64_t Invoice_expiry_time(const struct LDKInvoice *NONNULL_PTR this_arg); /** - * Returns the invoice's `min_cltv_expiry` time if present + * Returns the invoice's `min_final_cltv_expiry` time, if present, otherwise + * [`DEFAULT_MIN_FINAL_CLTV_EXPIRY`]. */ -MUST_USE_RES struct LDKCOption_u64Z Invoice_min_final_cltv_expiry(const struct LDKInvoice *NONNULL_PTR this_arg); +MUST_USE_RES uint64_t Invoice_min_final_cltv_expiry(const struct LDKInvoice *NONNULL_PTR this_arg); /** * Returns a list of all routes included in the invoice @@ -17409,23 +17537,18 @@ MUST_USE_RES enum LDKCurrency Invoice_currency(const struct LDKInvoice *NONNULL_ */ MUST_USE_RES struct LDKCOption_u64Z Invoice_amount_pico_btc(const struct LDKInvoice *NONNULL_PTR this_arg); -/** - * Numeric representation of the field's tag - */ -MUST_USE_RES struct LDKu5 TaggedField_tag(const struct LDKTaggedField *NONNULL_PTR this_arg); - /** * Creates a new `Description` if `description` is at most 1023 __bytes__ long, * returns `CreationError::DescriptionTooLong` otherwise * * Please note that single characters may use more than one byte due to UTF8 encoding. */ -MUST_USE_RES struct LDKCResult_DescriptionCreationErrorZ Description_new(struct LDKCVec_u8Z description); +MUST_USE_RES struct LDKCResult_DescriptionCreationErrorZ Description_new(struct LDKStr description); /** * Returns the underlying description `String` */ -MUST_USE_RES struct LDKCVec_u8Z Description_into_inner(struct LDKDescription this_arg); +MUST_USE_RES struct LDKStr Description_into_inner(struct LDKDescription this_arg); /** * Construct an `ExpiryTime` from seconds. If there exists a `PositiveTimestamp` which would @@ -17481,4 +17604,63 @@ enum LDKSemanticError SemanticError_clone(const enum LDKSemanticError *NONNULL_P */ struct LDKStr SemanticError_to_str(const enum LDKSemanticError *NONNULL_PTR o); +/** + * Frees any resources used by the SignOrCreationError + */ +void SignOrCreationError_free(struct LDKSignOrCreationError this_ptr); + +/** + * Creates a copy of the SignOrCreationError + */ +struct LDKSignOrCreationError SignOrCreationError_clone(const struct LDKSignOrCreationError *NONNULL_PTR orig); + +/** + * Get the string representation of a SignOrCreationError object + */ +struct LDKStr SignOrCreationError_to_str(const struct LDKSignOrCreationError *NONNULL_PTR o); + +/** + * Utility to construct an invoice. Generally, unless you want to do something like a custom + * cltv_expiry, this is what you should be using to create an invoice. The reason being, this + * method stores the invoice's payment secret and preimage in `ChannelManager`, so (a) the user + * doesn't have to store preimage/payment secret information and (b) `ChannelManager` can verify + * that the payment secret is valid when the invoice is paid. + */ +struct LDKCResult_InvoiceSignOrCreationErrorZ create_invoice_from_channelmanager(const struct LDKChannelManager *NONNULL_PTR channelmanager, struct LDKKeysInterface keys_manager, enum LDKCurrency network, struct LDKCOption_u64Z amt_msat, struct LDKStr description); + +/** + * Read a SiPrefix object from a string + */ +struct LDKCResult_SiPrefixNoneZ SiPrefix_from_str(struct LDKStr s); + +/** + * Read a Invoice object from a string + */ +struct LDKCResult_InvoiceNoneZ Invoice_from_str(struct LDKStr s); + +/** + * Read a SignedRawInvoice object from a string + */ +struct LDKCResult_SignedRawInvoiceNoneZ SignedRawInvoice_from_str(struct LDKStr s); + +/** + * Get the string representation of a Invoice object + */ +struct LDKStr Invoice_to_str(const struct LDKInvoice *NONNULL_PTR o); + +/** + * Get the string representation of a SignedRawInvoice object + */ +struct LDKStr SignedRawInvoice_to_str(const struct LDKSignedRawInvoice *NONNULL_PTR o); + +/** + * Get the string representation of a Currency object + */ +struct LDKStr Currency_to_str(const enum LDKCurrency *NONNULL_PTR o); + +/** + * Get the string representation of a SiPrefix object + */ +struct LDKStr SiPrefix_to_str(const enum LDKSiPrefix *NONNULL_PTR o); + #endif /* LDK_C_BINDINGS_H */ diff --git a/lightning-c-bindings/include/lightningpp.hpp b/lightning-c-bindings/include/lightningpp.hpp index 7c21ba9..d00d238 100644 --- a/lightning-c-bindings/include/lightningpp.hpp +++ b/lightning-c-bindings/include/lightningpp.hpp @@ -343,36 +343,6 @@ public: const LDKCurrency* operator &() const { return &self; } const LDKCurrency* operator ->() const { return &self; } }; -class RawTaggedField { -private: - LDKRawTaggedField self; -public: - RawTaggedField(const RawTaggedField&) = delete; - RawTaggedField(RawTaggedField&& o) : self(o.self) { memset(&o, 0, sizeof(RawTaggedField)); } - RawTaggedField(LDKRawTaggedField&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKRawTaggedField)); } - operator LDKRawTaggedField() && { LDKRawTaggedField res = self; memset(&self, 0, sizeof(LDKRawTaggedField)); return res; } - ~RawTaggedField() { RawTaggedField_free(self); } - RawTaggedField& operator=(RawTaggedField&& o) { RawTaggedField_free(self); self = o.self; memset(&o, 0, sizeof(RawTaggedField)); return *this; } - LDKRawTaggedField* operator &() { return &self; } - LDKRawTaggedField* operator ->() { return &self; } - const LDKRawTaggedField* operator &() const { return &self; } - const LDKRawTaggedField* operator ->() const { return &self; } -}; -class TaggedField { -private: - LDKTaggedField self; -public: - TaggedField(const TaggedField&) = delete; - TaggedField(TaggedField&& o) : self(o.self) { memset(&o, 0, sizeof(TaggedField)); } - TaggedField(LDKTaggedField&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKTaggedField)); } - operator LDKTaggedField() && { LDKTaggedField res = self; memset(&self, 0, sizeof(LDKTaggedField)); return res; } - ~TaggedField() { TaggedField_free(self); } - TaggedField& operator=(TaggedField&& o) { TaggedField_free(self); self = o.self; memset(&o, 0, sizeof(TaggedField)); return *this; } - LDKTaggedField* operator &() { return &self; } - LDKTaggedField* operator ->() { return &self; } - const LDKTaggedField* operator &() const { return &self; } - const LDKTaggedField* operator ->() const { return &self; } -}; class Sha256 { private: LDKSha256 self; @@ -418,21 +388,6 @@ public: const LDKPayeePubKey* operator &() const { return &self; } const LDKPayeePubKey* operator ->() const { return &self; } }; -class PaymentSecret { -private: - LDKPaymentSecret self; -public: - PaymentSecret(const PaymentSecret&) = delete; - PaymentSecret(PaymentSecret&& o) : self(o.self) { memset(&o, 0, sizeof(PaymentSecret)); } - PaymentSecret(LDKPaymentSecret&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKPaymentSecret)); } - operator LDKPaymentSecret() && { LDKPaymentSecret res = self; memset(&self, 0, sizeof(LDKPaymentSecret)); return res; } - ~PaymentSecret() { PaymentSecret_free(self); } - PaymentSecret& operator=(PaymentSecret&& o) { PaymentSecret_free(self); self = o.self; memset(&o, 0, sizeof(PaymentSecret)); return *this; } - LDKPaymentSecret* operator &() { return &self; } - LDKPaymentSecret* operator ->() { return &self; } - const LDKPaymentSecret* operator &() const { return &self; } - const LDKPaymentSecret* operator ->() const { return &self; } -}; class ExpiryTime { private: LDKExpiryTime self; @@ -536,6 +491,21 @@ public: const LDKSemanticError* operator &() const { return &self; } const LDKSemanticError* operator ->() const { return &self; } }; +class SignOrCreationError { +private: + LDKSignOrCreationError self; +public: + SignOrCreationError(const SignOrCreationError&) = delete; + SignOrCreationError(SignOrCreationError&& o) : self(o.self) { memset(&o, 0, sizeof(SignOrCreationError)); } + SignOrCreationError(LDKSignOrCreationError&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKSignOrCreationError)); } + operator LDKSignOrCreationError() && { LDKSignOrCreationError res = self; memset(&self, 0, sizeof(LDKSignOrCreationError)); return res; } + ~SignOrCreationError() { SignOrCreationError_free(self); } + SignOrCreationError& operator=(SignOrCreationError&& o) { SignOrCreationError_free(self); self = o.self; memset(&o, 0, sizeof(SignOrCreationError)); return *this; } + LDKSignOrCreationError* operator &() { return &self; } + LDKSignOrCreationError* operator ->() { return &self; } + const LDKSignOrCreationError* operator &() const { return &self; } + const LDKSignOrCreationError* operator ->() const { return &self; } +}; class ChannelMonitorUpdate { private: LDKChannelMonitorUpdate self; @@ -2317,6 +2287,21 @@ public: const LDKCResult_ChannelReestablishDecodeErrorZ* operator &() const { return &self; } const LDKCResult_ChannelReestablishDecodeErrorZ* operator ->() const { return &self; } }; +class CResult_InvoiceSignOrCreationErrorZ { +private: + LDKCResult_InvoiceSignOrCreationErrorZ self; +public: + CResult_InvoiceSignOrCreationErrorZ(const CResult_InvoiceSignOrCreationErrorZ&) = delete; + CResult_InvoiceSignOrCreationErrorZ(CResult_InvoiceSignOrCreationErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_InvoiceSignOrCreationErrorZ)); } + CResult_InvoiceSignOrCreationErrorZ(LDKCResult_InvoiceSignOrCreationErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_InvoiceSignOrCreationErrorZ)); } + operator LDKCResult_InvoiceSignOrCreationErrorZ() && { LDKCResult_InvoiceSignOrCreationErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_InvoiceSignOrCreationErrorZ)); return res; } + ~CResult_InvoiceSignOrCreationErrorZ() { CResult_InvoiceSignOrCreationErrorZ_free(self); } + CResult_InvoiceSignOrCreationErrorZ& operator=(CResult_InvoiceSignOrCreationErrorZ&& o) { CResult_InvoiceSignOrCreationErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_InvoiceSignOrCreationErrorZ)); return *this; } + LDKCResult_InvoiceSignOrCreationErrorZ* operator &() { return &self; } + LDKCResult_InvoiceSignOrCreationErrorZ* operator ->() { return &self; } + const LDKCResult_InvoiceSignOrCreationErrorZ* operator &() const { return &self; } + const LDKCResult_InvoiceSignOrCreationErrorZ* operator ->() const { return &self; } +}; class CResult_CommitmentSignedDecodeErrorZ { private: LDKCResult_CommitmentSignedDecodeErrorZ self; @@ -2407,6 +2392,21 @@ public: const LDKCResult_ExpiryTimeCreationErrorZ* operator &() const { return &self; } const LDKCResult_ExpiryTimeCreationErrorZ* operator ->() const { return &self; } }; +class CResult_SignedRawInvoiceNoneZ { +private: + LDKCResult_SignedRawInvoiceNoneZ self; +public: + CResult_SignedRawInvoiceNoneZ(const CResult_SignedRawInvoiceNoneZ&) = delete; + CResult_SignedRawInvoiceNoneZ(CResult_SignedRawInvoiceNoneZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_SignedRawInvoiceNoneZ)); } + CResult_SignedRawInvoiceNoneZ(LDKCResult_SignedRawInvoiceNoneZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_SignedRawInvoiceNoneZ)); } + operator LDKCResult_SignedRawInvoiceNoneZ() && { LDKCResult_SignedRawInvoiceNoneZ res = self; memset(&self, 0, sizeof(LDKCResult_SignedRawInvoiceNoneZ)); return res; } + ~CResult_SignedRawInvoiceNoneZ() { CResult_SignedRawInvoiceNoneZ_free(self); } + CResult_SignedRawInvoiceNoneZ& operator=(CResult_SignedRawInvoiceNoneZ&& o) { CResult_SignedRawInvoiceNoneZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_SignedRawInvoiceNoneZ)); return *this; } + LDKCResult_SignedRawInvoiceNoneZ* operator &() { return &self; } + LDKCResult_SignedRawInvoiceNoneZ* operator ->() { return &self; } + const LDKCResult_SignedRawInvoiceNoneZ* operator &() const { return &self; } + const LDKCResult_SignedRawInvoiceNoneZ* operator ->() const { return &self; } +}; class COption_C2Tuple_usizeTransactionZZ { private: LDKCOption_C2Tuple_usizeTransactionZZ self; @@ -2527,6 +2527,21 @@ public: const LDKCResult_SecretKeyErrorZ* operator &() const { return &self; } const LDKCResult_SecretKeyErrorZ* operator ->() const { return &self; } }; +class CResult_InvoiceNoneZ { +private: + LDKCResult_InvoiceNoneZ self; +public: + CResult_InvoiceNoneZ(const CResult_InvoiceNoneZ&) = delete; + CResult_InvoiceNoneZ(CResult_InvoiceNoneZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_InvoiceNoneZ)); } + CResult_InvoiceNoneZ(LDKCResult_InvoiceNoneZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_InvoiceNoneZ)); } + operator LDKCResult_InvoiceNoneZ() && { LDKCResult_InvoiceNoneZ res = self; memset(&self, 0, sizeof(LDKCResult_InvoiceNoneZ)); return res; } + ~CResult_InvoiceNoneZ() { CResult_InvoiceNoneZ_free(self); } + CResult_InvoiceNoneZ& operator=(CResult_InvoiceNoneZ&& o) { CResult_InvoiceNoneZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_InvoiceNoneZ)); return *this; } + LDKCResult_InvoiceNoneZ* operator &() { return &self; } + LDKCResult_InvoiceNoneZ* operator ->() { return &self; } + const LDKCResult_InvoiceNoneZ* operator &() const { return &self; } + const LDKCResult_InvoiceNoneZ* operator ->() const { return &self; } +}; class CResult_QueryChannelRangeDecodeErrorZ { private: LDKCResult_QueryChannelRangeDecodeErrorZ self; @@ -2737,6 +2752,21 @@ public: const LDKCResult_NodeAnnouncementInfoDecodeErrorZ* operator &() const { return &self; } const LDKCResult_NodeAnnouncementInfoDecodeErrorZ* operator ->() const { return &self; } }; +class CResult_RecoverableSignatureNoneZ { +private: + LDKCResult_RecoverableSignatureNoneZ self; +public: + CResult_RecoverableSignatureNoneZ(const CResult_RecoverableSignatureNoneZ&) = delete; + CResult_RecoverableSignatureNoneZ(CResult_RecoverableSignatureNoneZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_RecoverableSignatureNoneZ)); } + CResult_RecoverableSignatureNoneZ(LDKCResult_RecoverableSignatureNoneZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_RecoverableSignatureNoneZ)); } + operator LDKCResult_RecoverableSignatureNoneZ() && { LDKCResult_RecoverableSignatureNoneZ res = self; memset(&self, 0, sizeof(LDKCResult_RecoverableSignatureNoneZ)); return res; } + ~CResult_RecoverableSignatureNoneZ() { CResult_RecoverableSignatureNoneZ_free(self); } + CResult_RecoverableSignatureNoneZ& operator=(CResult_RecoverableSignatureNoneZ&& o) { CResult_RecoverableSignatureNoneZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_RecoverableSignatureNoneZ)); return *this; } + LDKCResult_RecoverableSignatureNoneZ* operator &() { return &self; } + LDKCResult_RecoverableSignatureNoneZ* operator ->() { return &self; } + const LDKCResult_RecoverableSignatureNoneZ* operator &() const { return &self; } + const LDKCResult_RecoverableSignatureNoneZ* operator ->() const { return &self; } +}; class CResult_NetAddressu8Z { private: LDKCResult_NetAddressu8Z self; @@ -3037,21 +3067,6 @@ public: const LDKCResult_OutPointDecodeErrorZ* operator &() const { return &self; } const LDKCResult_OutPointDecodeErrorZ* operator ->() const { return &self; } }; -class CVec_RawTaggedFieldZ { -private: - LDKCVec_RawTaggedFieldZ self; -public: - CVec_RawTaggedFieldZ(const CVec_RawTaggedFieldZ&) = delete; - CVec_RawTaggedFieldZ(CVec_RawTaggedFieldZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_RawTaggedFieldZ)); } - CVec_RawTaggedFieldZ(LDKCVec_RawTaggedFieldZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_RawTaggedFieldZ)); } - operator LDKCVec_RawTaggedFieldZ() && { LDKCVec_RawTaggedFieldZ res = self; memset(&self, 0, sizeof(LDKCVec_RawTaggedFieldZ)); return res; } - ~CVec_RawTaggedFieldZ() { CVec_RawTaggedFieldZ_free(self); } - CVec_RawTaggedFieldZ& operator=(CVec_RawTaggedFieldZ&& o) { CVec_RawTaggedFieldZ_free(self); self = o.self; memset(&o, 0, sizeof(CVec_RawTaggedFieldZ)); return *this; } - LDKCVec_RawTaggedFieldZ* operator &() { return &self; } - LDKCVec_RawTaggedFieldZ* operator ->() { return &self; } - const LDKCVec_RawTaggedFieldZ* operator &() const { return &self; } - const LDKCVec_RawTaggedFieldZ* operator ->() const { return &self; } -}; class CVec_ChannelDetailsZ { private: LDKCVec_ChannelDetailsZ self; @@ -3067,21 +3082,6 @@ public: const LDKCVec_ChannelDetailsZ* operator &() const { return &self; } const LDKCVec_ChannelDetailsZ* operator ->() const { return &self; } }; -class CVec_MessageSendEventZ { -private: - LDKCVec_MessageSendEventZ self; -public: - CVec_MessageSendEventZ(const CVec_MessageSendEventZ&) = delete; - CVec_MessageSendEventZ(CVec_MessageSendEventZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_MessageSendEventZ)); } - CVec_MessageSendEventZ(LDKCVec_MessageSendEventZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_MessageSendEventZ)); } - operator LDKCVec_MessageSendEventZ() && { LDKCVec_MessageSendEventZ res = self; memset(&self, 0, sizeof(LDKCVec_MessageSendEventZ)); return res; } - ~CVec_MessageSendEventZ() { CVec_MessageSendEventZ_free(self); } - CVec_MessageSendEventZ& operator=(CVec_MessageSendEventZ&& o) { CVec_MessageSendEventZ_free(self); self = o.self; memset(&o, 0, sizeof(CVec_MessageSendEventZ)); return *this; } - LDKCVec_MessageSendEventZ* operator &() { return &self; } - LDKCVec_MessageSendEventZ* operator ->() { return &self; } - const LDKCVec_MessageSendEventZ* operator &() const { return &self; } - const LDKCVec_MessageSendEventZ* operator ->() const { return &self; } -}; class CResult_SignDecodeErrorZ { private: LDKCResult_SignDecodeErrorZ self; @@ -3097,6 +3097,21 @@ public: const LDKCResult_SignDecodeErrorZ* operator &() const { return &self; } const LDKCResult_SignDecodeErrorZ* operator ->() const { return &self; } }; +class CVec_MessageSendEventZ { +private: + LDKCVec_MessageSendEventZ self; +public: + CVec_MessageSendEventZ(const CVec_MessageSendEventZ&) = delete; + CVec_MessageSendEventZ(CVec_MessageSendEventZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_MessageSendEventZ)); } + CVec_MessageSendEventZ(LDKCVec_MessageSendEventZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_MessageSendEventZ)); } + operator LDKCVec_MessageSendEventZ() && { LDKCVec_MessageSendEventZ res = self; memset(&self, 0, sizeof(LDKCVec_MessageSendEventZ)); return res; } + ~CVec_MessageSendEventZ() { CVec_MessageSendEventZ_free(self); } + CVec_MessageSendEventZ& operator=(CVec_MessageSendEventZ&& o) { CVec_MessageSendEventZ_free(self); self = o.self; memset(&o, 0, sizeof(CVec_MessageSendEventZ)); return *this; } + LDKCVec_MessageSendEventZ* operator &() { return &self; } + LDKCVec_MessageSendEventZ* operator ->() { return &self; } + const LDKCVec_MessageSendEventZ* operator &() const { return &self; } + const LDKCVec_MessageSendEventZ* operator ->() const { return &self; } +}; class C2Tuple_OutPointScriptZ { private: LDKC2Tuple_OutPointScriptZ self; @@ -3847,6 +3862,21 @@ public: const LDKCResult_NoneChannelMonitorUpdateErrZ* operator &() const { return &self; } const LDKCResult_NoneChannelMonitorUpdateErrZ* operator ->() const { return &self; } }; +class CResult_SiPrefixNoneZ { +private: + LDKCResult_SiPrefixNoneZ self; +public: + CResult_SiPrefixNoneZ(const CResult_SiPrefixNoneZ&) = delete; + CResult_SiPrefixNoneZ(CResult_SiPrefixNoneZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_SiPrefixNoneZ)); } + CResult_SiPrefixNoneZ(LDKCResult_SiPrefixNoneZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_SiPrefixNoneZ)); } + operator LDKCResult_SiPrefixNoneZ() && { LDKCResult_SiPrefixNoneZ res = self; memset(&self, 0, sizeof(LDKCResult_SiPrefixNoneZ)); return res; } + ~CResult_SiPrefixNoneZ() { CResult_SiPrefixNoneZ_free(self); } + CResult_SiPrefixNoneZ& operator=(CResult_SiPrefixNoneZ&& o) { CResult_SiPrefixNoneZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_SiPrefixNoneZ)); return *this; } + LDKCResult_SiPrefixNoneZ* operator &() { return &self; } + LDKCResult_SiPrefixNoneZ* operator ->() { return &self; } + const LDKCResult_SiPrefixNoneZ* operator &() const { return &self; } + const LDKCResult_SiPrefixNoneZ* operator ->() const { return &self; } +}; class CResult_PublicKeyErrorZ { private: LDKCResult_PublicKeyErrorZ self; @@ -3982,21 +4012,6 @@ public: const LDKCResult_NodeFeaturesDecodeErrorZ* operator &() const { return &self; } const LDKCResult_NodeFeaturesDecodeErrorZ* operator ->() const { return &self; } }; -class CVec_u5Z { -private: - LDKCVec_u5Z self; -public: - CVec_u5Z(const CVec_u5Z&) = delete; - CVec_u5Z(CVec_u5Z&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_u5Z)); } - CVec_u5Z(LDKCVec_u5Z&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_u5Z)); } - operator LDKCVec_u5Z() && { LDKCVec_u5Z res = self; memset(&self, 0, sizeof(LDKCVec_u5Z)); return res; } - ~CVec_u5Z() { CVec_u5Z_free(self); } - CVec_u5Z& operator=(CVec_u5Z&& o) { CVec_u5Z_free(self); self = o.self; memset(&o, 0, sizeof(CVec_u5Z)); return *this; } - LDKCVec_u5Z* operator &() { return &self; } - LDKCVec_u5Z* operator ->() { return &self; } - const LDKCVec_u5Z* operator &() const { return &self; } - const LDKCVec_u5Z* operator ->() const { return &self; } -}; class CResult_ReplyShortChannelIdsEndDecodeErrorZ { private: LDKCResult_ReplyShortChannelIdsEndDecodeErrorZ self; @@ -4012,6 +4027,21 @@ public: const LDKCResult_ReplyShortChannelIdsEndDecodeErrorZ* operator &() const { return &self; } const LDKCResult_ReplyShortChannelIdsEndDecodeErrorZ* operator ->() const { return &self; } }; +class CResult_InMemorySignerDecodeErrorZ { +private: + LDKCResult_InMemorySignerDecodeErrorZ self; +public: + CResult_InMemorySignerDecodeErrorZ(const CResult_InMemorySignerDecodeErrorZ&) = delete; + CResult_InMemorySignerDecodeErrorZ(CResult_InMemorySignerDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_InMemorySignerDecodeErrorZ)); } + CResult_InMemorySignerDecodeErrorZ(LDKCResult_InMemorySignerDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_InMemorySignerDecodeErrorZ)); } + operator LDKCResult_InMemorySignerDecodeErrorZ() && { LDKCResult_InMemorySignerDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_InMemorySignerDecodeErrorZ)); return res; } + ~CResult_InMemorySignerDecodeErrorZ() { CResult_InMemorySignerDecodeErrorZ_free(self); } + CResult_InMemorySignerDecodeErrorZ& operator=(CResult_InMemorySignerDecodeErrorZ&& o) { CResult_InMemorySignerDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_InMemorySignerDecodeErrorZ)); return *this; } + LDKCResult_InMemorySignerDecodeErrorZ* operator &() { return &self; } + LDKCResult_InMemorySignerDecodeErrorZ* operator ->() { return &self; } + const LDKCResult_InMemorySignerDecodeErrorZ* operator &() const { return &self; } + const LDKCResult_InMemorySignerDecodeErrorZ* operator ->() const { return &self; } +}; class C2Tuple_u32ScriptZ { private: LDKC2Tuple_u32ScriptZ self; @@ -4042,21 +4072,6 @@ public: const LDKCResult_CResult_NetAddressu8ZDecodeErrorZ* operator &() const { return &self; } const LDKCResult_CResult_NetAddressu8ZDecodeErrorZ* operator ->() const { return &self; } }; -class CResult_InMemorySignerDecodeErrorZ { -private: - LDKCResult_InMemorySignerDecodeErrorZ self; -public: - CResult_InMemorySignerDecodeErrorZ(const CResult_InMemorySignerDecodeErrorZ&) = delete; - CResult_InMemorySignerDecodeErrorZ(CResult_InMemorySignerDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_InMemorySignerDecodeErrorZ)); } - CResult_InMemorySignerDecodeErrorZ(LDKCResult_InMemorySignerDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_InMemorySignerDecodeErrorZ)); } - operator LDKCResult_InMemorySignerDecodeErrorZ() && { LDKCResult_InMemorySignerDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_InMemorySignerDecodeErrorZ)); return res; } - ~CResult_InMemorySignerDecodeErrorZ() { CResult_InMemorySignerDecodeErrorZ_free(self); } - CResult_InMemorySignerDecodeErrorZ& operator=(CResult_InMemorySignerDecodeErrorZ&& o) { CResult_InMemorySignerDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_InMemorySignerDecodeErrorZ)); return *this; } - LDKCResult_InMemorySignerDecodeErrorZ* operator &() { return &self; } - LDKCResult_InMemorySignerDecodeErrorZ* operator ->() { return &self; } - const LDKCResult_InMemorySignerDecodeErrorZ* operator &() const { return &self; } - const LDKCResult_InMemorySignerDecodeErrorZ* operator ->() const { return &self; } -}; class CResult_PaymentSecretAPIErrorZ { private: LDKCResult_PaymentSecretAPIErrorZ self; @@ -4072,20 +4087,20 @@ public: const LDKCResult_PaymentSecretAPIErrorZ* operator &() const { return &self; } const LDKCResult_PaymentSecretAPIErrorZ* operator ->() const { return &self; } }; -class CResult_RouteDecodeErrorZ { +class CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ { private: - LDKCResult_RouteDecodeErrorZ self; + LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ self; public: - CResult_RouteDecodeErrorZ(const CResult_RouteDecodeErrorZ&) = delete; - CResult_RouteDecodeErrorZ(CResult_RouteDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_RouteDecodeErrorZ)); } - CResult_RouteDecodeErrorZ(LDKCResult_RouteDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_RouteDecodeErrorZ)); } - operator LDKCResult_RouteDecodeErrorZ() && { LDKCResult_RouteDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_RouteDecodeErrorZ)); return res; } - ~CResult_RouteDecodeErrorZ() { CResult_RouteDecodeErrorZ_free(self); } - CResult_RouteDecodeErrorZ& operator=(CResult_RouteDecodeErrorZ&& o) { CResult_RouteDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_RouteDecodeErrorZ)); return *this; } - LDKCResult_RouteDecodeErrorZ* operator &() { return &self; } - LDKCResult_RouteDecodeErrorZ* operator ->() { return &self; } - const LDKCResult_RouteDecodeErrorZ* operator &() const { return &self; } - const LDKCResult_RouteDecodeErrorZ* operator ->() const { return &self; } + CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ(const CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ&) = delete; + CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ(CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ)); } + CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ(LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ)); } + operator LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ() && { LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ)); return res; } + ~CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ() { CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_free(self); } + CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ& operator=(CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ&& o) { CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ)); return *this; } + LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ* operator &() { return &self; } + LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ* operator ->() { return &self; } + const LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ* operator &() const { return &self; } + const LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ* operator ->() const { return &self; } }; class CResult_BuiltCommitmentTransactionDecodeErrorZ { private: @@ -4102,20 +4117,20 @@ public: const LDKCResult_BuiltCommitmentTransactionDecodeErrorZ* operator &() const { return &self; } const LDKCResult_BuiltCommitmentTransactionDecodeErrorZ* operator ->() const { return &self; } }; -class CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ { +class CResult_RouteDecodeErrorZ { private: - LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ self; + LDKCResult_RouteDecodeErrorZ self; public: - CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ(const CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ&) = delete; - CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ(CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ)); } - CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ(LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ)); } - operator LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ() && { LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ)); return res; } - ~CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ() { CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_free(self); } - CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ& operator=(CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ&& o) { CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ)); return *this; } - LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ* operator &() { return &self; } - LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ* operator ->() { return &self; } - const LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ* operator &() const { return &self; } - const LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ* operator ->() const { return &self; } + CResult_RouteDecodeErrorZ(const CResult_RouteDecodeErrorZ&) = delete; + CResult_RouteDecodeErrorZ(CResult_RouteDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_RouteDecodeErrorZ)); } + CResult_RouteDecodeErrorZ(LDKCResult_RouteDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_RouteDecodeErrorZ)); } + operator LDKCResult_RouteDecodeErrorZ() && { LDKCResult_RouteDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_RouteDecodeErrorZ)); return res; } + ~CResult_RouteDecodeErrorZ() { CResult_RouteDecodeErrorZ_free(self); } + CResult_RouteDecodeErrorZ& operator=(CResult_RouteDecodeErrorZ&& o) { CResult_RouteDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_RouteDecodeErrorZ)); return *this; } + LDKCResult_RouteDecodeErrorZ* operator &() { return &self; } + LDKCResult_RouteDecodeErrorZ* operator ->() { return &self; } + const LDKCResult_RouteDecodeErrorZ* operator &() const { return &self; } + const LDKCResult_RouteDecodeErrorZ* operator ->() const { return &self; } }; class CVec_UpdateFailHTLCZ { private: diff --git a/lightning-c-bindings/include/rust_types.h b/lightning-c-bindings/include/rust_types.h index 105348a..7dc569b 100644 --- a/lightning-c-bindings/include/rust_types.h +++ b/lightning-c-bindings/include/rust_types.h @@ -56,8 +56,6 @@ struct nativeDescriptionOpaque; typedef struct nativeDescriptionOpaque LDKnativeDescription; struct nativePayeePubKeyOpaque; typedef struct nativePayeePubKeyOpaque LDKnativePayeePubKey; -struct nativePaymentSecretOpaque; -typedef struct nativePaymentSecretOpaque LDKnativePaymentSecret; struct nativeExpiryTimeOpaque; typedef struct nativeExpiryTimeOpaque LDKnativeExpiryTime; struct nativeMinFinalCltvExpiryOpaque; diff --git a/lightning-c-bindings/src/c_types/derived.rs b/lightning-c-bindings/src/c_types/derived.rs index 37270e3..fc351bd 100644 --- a/lightning-c-bindings/src/c_types/derived.rs +++ b/lightning-c-bindings/src/c_types/derived.rs @@ -1263,8 +1263,8 @@ impl Drop for CResult_TrustedCommitmentTransactionNoneZ { } } } -impl From> for CResult_TrustedCommitmentTransactionNoneZ { - fn from(mut o: crate::c_types::CResultTempl) -> Self { +impl From> for CResult_TrustedCommitmentTransactionNoneZ { + fn from(mut o: crate::c_types::CResultTempl) -> Self { let contents = if o.result_ok { let result = unsafe { o.contents.result }; unsafe { o.contents.result = std::ptr::null_mut() }; @@ -1333,8 +1333,8 @@ impl Drop for CResult_CVec_SignatureZNoneZ { } } } -impl From> for CResult_CVec_SignatureZNoneZ { - fn from(mut o: crate::c_types::CResultTempl) -> Self { +impl From> for CResult_CVec_SignatureZNoneZ { + fn from(mut o: crate::c_types::CResultTempl) -> Self { let contents = if o.result_ok { let result = unsafe { o.contents.result }; unsafe { o.contents.result = std::ptr::null_mut() }; @@ -1368,97 +1368,266 @@ impl Clone for CResult_CVec_SignatureZNoneZ { /// but with all dynamically-allocated buffers duplicated in new buffers. pub extern "C" fn CResult_CVec_SignatureZNoneZ_clone(orig: &CResult_CVec_SignatureZNoneZ) -> CResult_CVec_SignatureZNoneZ { orig.clone() } #[repr(C)] -/// A dynamically-allocated array of crate::lightning_invoice::RawTaggedFields of arbitrary size. -/// This corresponds to std::vector in C++ -pub struct CVec_RawTaggedFieldZ { - /// The elements in the array. - /// If datalen is non-0 this must be a valid, non-NULL pointer allocated by malloc(). - pub data: *mut crate::lightning_invoice::RawTaggedField, - /// The number of elements pointed to by `data`. - pub datalen: usize +/// The contents of CResult_SiPrefixNoneZ +pub union CResult_SiPrefixNoneZPtr { + /// 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::lightning_invoice::SiPrefix, + /// Note that this value is always NULL, as there are no contents in the Err variant + pub err: *mut std::ffi::c_void, } -impl CVec_RawTaggedFieldZ { - #[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec { - if self.datalen == 0 { return Vec::new(); } - let ret = unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }.into(); - self.data = std::ptr::null_mut(); - self.datalen = 0; - ret - } - #[allow(unused)] pub(crate) fn as_slice(&self) -> &[crate::lightning_invoice::RawTaggedField] { - unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) } +#[repr(C)] +/// A CResult_SiPrefixNoneZ represents the result of a fallible operation, +/// containing a crate::lightning_invoice::SiPrefix on success and a () on failure. +/// `result_ok` indicates the overall state, and the contents are provided via `contents`. +pub struct CResult_SiPrefixNoneZ { + /// The contents of this CResult_SiPrefixNoneZ, accessible via either + /// `err` or `result` depending on the state of `result_ok`. + pub contents: CResult_SiPrefixNoneZPtr, + /// Whether this CResult_SiPrefixNoneZ represents a success state. + pub result_ok: bool, +} +#[no_mangle] +/// Creates a new CResult_SiPrefixNoneZ in the success state. +pub extern "C" fn CResult_SiPrefixNoneZ_ok(o: crate::lightning_invoice::SiPrefix) -> CResult_SiPrefixNoneZ { + CResult_SiPrefixNoneZ { + contents: CResult_SiPrefixNoneZPtr { + result: Box::into_raw(Box::new(o)), + }, + result_ok: true, } } -impl From> for CVec_RawTaggedFieldZ { - fn from(v: Vec) -> Self { - let datalen = v.len(); - let data = Box::into_raw(v.into_boxed_slice()); - Self { datalen, data: unsafe { (*data).as_mut_ptr() } } +#[no_mangle] +/// Creates a new CResult_SiPrefixNoneZ in the error state. +pub extern "C" fn CResult_SiPrefixNoneZ_err() -> CResult_SiPrefixNoneZ { + CResult_SiPrefixNoneZ { + contents: CResult_SiPrefixNoneZPtr { + err: std::ptr::null_mut(), + }, + result_ok: false, } } #[no_mangle] -/// Frees the buffer pointed to by `data` if `datalen` is non-0. -pub extern "C" fn CVec_RawTaggedFieldZ_free(_res: CVec_RawTaggedFieldZ) { } -impl Drop for CVec_RawTaggedFieldZ { +/// Frees any resources used by the CResult_SiPrefixNoneZ. +pub extern "C" fn CResult_SiPrefixNoneZ_free(_res: CResult_SiPrefixNoneZ) { } +impl Drop for CResult_SiPrefixNoneZ { fn drop(&mut self) { - if self.datalen == 0 { return; } - unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }; + if self.result_ok { + if unsafe { !(self.contents.result as *mut ()).is_null() } { + let _ = unsafe { Box::from_raw(self.contents.result) }; + } + } else { + } } } -impl Clone for CVec_RawTaggedFieldZ { +impl From> for CResult_SiPrefixNoneZ { + fn from(mut o: crate::c_types::CResultTempl) -> Self { + let contents = if o.result_ok { + let result = unsafe { o.contents.result }; + unsafe { o.contents.result = std::ptr::null_mut() }; + CResult_SiPrefixNoneZPtr { result } + } else { + let _ = unsafe { Box::from_raw(o.contents.err) }; + o.contents.err = std::ptr::null_mut(); + CResult_SiPrefixNoneZPtr { err: std::ptr::null_mut() } + }; + Self { + contents, + result_ok: o.result_ok, + } + } +} +impl Clone for CResult_SiPrefixNoneZ { fn clone(&self) -> Self { - let mut res = Vec::new(); - if self.datalen == 0 { return Self::from(res); } - res.extend_from_slice(unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) }); - Self::from(res) + if self.result_ok { + Self { result_ok: true, contents: CResult_SiPrefixNoneZPtr { + result: Box::into_raw(Box::new(::clone(unsafe { &*self.contents.result }))) + } } + } else { + Self { result_ok: false, contents: CResult_SiPrefixNoneZPtr { + err: std::ptr::null_mut() + } } + } } } +#[no_mangle] +/// Creates a new CResult_SiPrefixNoneZ which has the same data as `orig` +/// but with all dynamically-allocated buffers duplicated in new buffers. +pub extern "C" fn CResult_SiPrefixNoneZ_clone(orig: &CResult_SiPrefixNoneZ) -> CResult_SiPrefixNoneZ { orig.clone() } #[repr(C)] -/// A dynamically-allocated array of crate::c_types::u5s of arbitrary size. -/// This corresponds to std::vector in C++ -pub struct CVec_u5Z { - /// The elements in the array. - /// If datalen is non-0 this must be a valid, non-NULL pointer allocated by malloc(). - pub data: *mut crate::c_types::u5, - /// The number of elements pointed to by `data`. - pub datalen: usize +/// The contents of CResult_InvoiceNoneZ +pub union CResult_InvoiceNoneZPtr { + /// 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::lightning_invoice::Invoice, + /// Note that this value is always NULL, as there are no contents in the Err variant + pub err: *mut std::ffi::c_void, } -impl CVec_u5Z { - #[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec { - if self.datalen == 0 { return Vec::new(); } - let ret = unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }.into(); - self.data = std::ptr::null_mut(); - self.datalen = 0; - ret +#[repr(C)] +/// A CResult_InvoiceNoneZ represents the result of a fallible operation, +/// containing a crate::lightning_invoice::Invoice on success and a () on failure. +/// `result_ok` indicates the overall state, and the contents are provided via `contents`. +pub struct CResult_InvoiceNoneZ { + /// The contents of this CResult_InvoiceNoneZ, accessible via either + /// `err` or `result` depending on the state of `result_ok`. + pub contents: CResult_InvoiceNoneZPtr, + /// Whether this CResult_InvoiceNoneZ represents a success state. + pub result_ok: bool, +} +#[no_mangle] +/// Creates a new CResult_InvoiceNoneZ in the success state. +pub extern "C" fn CResult_InvoiceNoneZ_ok(o: crate::lightning_invoice::Invoice) -> CResult_InvoiceNoneZ { + CResult_InvoiceNoneZ { + contents: CResult_InvoiceNoneZPtr { + result: Box::into_raw(Box::new(o)), + }, + result_ok: true, } - #[allow(unused)] pub(crate) fn as_slice(&self) -> &[crate::c_types::u5] { - unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) } +} +#[no_mangle] +/// Creates a new CResult_InvoiceNoneZ in the error state. +pub extern "C" fn CResult_InvoiceNoneZ_err() -> CResult_InvoiceNoneZ { + CResult_InvoiceNoneZ { + contents: CResult_InvoiceNoneZPtr { + err: std::ptr::null_mut(), + }, + result_ok: false, } } -impl From> for CVec_u5Z { - fn from(v: Vec) -> Self { - let datalen = v.len(); - let data = Box::into_raw(v.into_boxed_slice()); - Self { datalen, data: unsafe { (*data).as_mut_ptr() } } +#[no_mangle] +/// Frees any resources used by the CResult_InvoiceNoneZ. +pub extern "C" fn CResult_InvoiceNoneZ_free(_res: CResult_InvoiceNoneZ) { } +impl Drop for CResult_InvoiceNoneZ { + 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 { + } + } +} +impl From> for CResult_InvoiceNoneZ { + fn from(mut o: crate::c_types::CResultTempl) -> Self { + let contents = if o.result_ok { + let result = unsafe { o.contents.result }; + unsafe { o.contents.result = std::ptr::null_mut() }; + CResult_InvoiceNoneZPtr { result } + } else { + let _ = unsafe { Box::from_raw(o.contents.err) }; + o.contents.err = std::ptr::null_mut(); + CResult_InvoiceNoneZPtr { err: std::ptr::null_mut() } + }; + Self { + contents, + result_ok: o.result_ok, + } + } +} +impl Clone for CResult_InvoiceNoneZ { + fn clone(&self) -> Self { + if self.result_ok { + Self { result_ok: true, contents: CResult_InvoiceNoneZPtr { + result: Box::into_raw(Box::new(::clone(unsafe { &*self.contents.result }))) + } } + } else { + Self { result_ok: false, contents: CResult_InvoiceNoneZPtr { + err: std::ptr::null_mut() + } } + } } } #[no_mangle] -/// Frees the buffer pointed to by `data` if `datalen` is non-0. -pub extern "C" fn CVec_u5Z_free(_res: CVec_u5Z) { } -impl Drop for CVec_u5Z { +/// Creates a new CResult_InvoiceNoneZ which has the same data as `orig` +/// but with all dynamically-allocated buffers duplicated in new buffers. +pub extern "C" fn CResult_InvoiceNoneZ_clone(orig: &CResult_InvoiceNoneZ) -> CResult_InvoiceNoneZ { orig.clone() } +#[repr(C)] +/// The contents of CResult_SignedRawInvoiceNoneZ +pub union CResult_SignedRawInvoiceNoneZPtr { + /// 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::lightning_invoice::SignedRawInvoice, + /// Note that this value is always NULL, as there are no contents in the Err variant + pub err: *mut std::ffi::c_void, +} +#[repr(C)] +/// A CResult_SignedRawInvoiceNoneZ represents the result of a fallible operation, +/// containing a crate::lightning_invoice::SignedRawInvoice on success and a () on failure. +/// `result_ok` indicates the overall state, and the contents are provided via `contents`. +pub struct CResult_SignedRawInvoiceNoneZ { + /// The contents of this CResult_SignedRawInvoiceNoneZ, accessible via either + /// `err` or `result` depending on the state of `result_ok`. + pub contents: CResult_SignedRawInvoiceNoneZPtr, + /// Whether this CResult_SignedRawInvoiceNoneZ represents a success state. + pub result_ok: bool, +} +#[no_mangle] +/// Creates a new CResult_SignedRawInvoiceNoneZ in the success state. +pub extern "C" fn CResult_SignedRawInvoiceNoneZ_ok(o: crate::lightning_invoice::SignedRawInvoice) -> CResult_SignedRawInvoiceNoneZ { + CResult_SignedRawInvoiceNoneZ { + contents: CResult_SignedRawInvoiceNoneZPtr { + result: Box::into_raw(Box::new(o)), + }, + result_ok: true, + } +} +#[no_mangle] +/// Creates a new CResult_SignedRawInvoiceNoneZ in the error state. +pub extern "C" fn CResult_SignedRawInvoiceNoneZ_err() -> CResult_SignedRawInvoiceNoneZ { + CResult_SignedRawInvoiceNoneZ { + contents: CResult_SignedRawInvoiceNoneZPtr { + err: std::ptr::null_mut(), + }, + result_ok: false, + } +} +#[no_mangle] +/// Frees any resources used by the CResult_SignedRawInvoiceNoneZ. +pub extern "C" fn CResult_SignedRawInvoiceNoneZ_free(_res: CResult_SignedRawInvoiceNoneZ) { } +impl Drop for CResult_SignedRawInvoiceNoneZ { fn drop(&mut self) { - if self.datalen == 0 { return; } - unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }; + if self.result_ok { + if unsafe { !(self.contents.result as *mut ()).is_null() } { + let _ = unsafe { Box::from_raw(self.contents.result) }; + } + } else { + } } } -impl Clone for CVec_u5Z { +impl From> for CResult_SignedRawInvoiceNoneZ { + fn from(mut o: crate::c_types::CResultTempl) -> Self { + let contents = if o.result_ok { + let result = unsafe { o.contents.result }; + unsafe { o.contents.result = std::ptr::null_mut() }; + CResult_SignedRawInvoiceNoneZPtr { result } + } else { + let _ = unsafe { Box::from_raw(o.contents.err) }; + o.contents.err = std::ptr::null_mut(); + CResult_SignedRawInvoiceNoneZPtr { err: std::ptr::null_mut() } + }; + Self { + contents, + result_ok: o.result_ok, + } + } +} +impl Clone for CResult_SignedRawInvoiceNoneZ { fn clone(&self) -> Self { - let mut res = Vec::new(); - if self.datalen == 0 { return Self::from(res); } - res.extend_from_slice(unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) }); - Self::from(res) + if self.result_ok { + Self { result_ok: true, contents: CResult_SignedRawInvoiceNoneZPtr { + result: Box::into_raw(Box::new(::clone(unsafe { &*self.contents.result }))) + } } + } else { + Self { result_ok: false, contents: CResult_SignedRawInvoiceNoneZPtr { + err: std::ptr::null_mut() + } } + } } } +#[no_mangle] +/// Creates a new CResult_SignedRawInvoiceNoneZ which has the same data as `orig` +/// but with all dynamically-allocated buffers duplicated in new buffers. +pub extern "C" fn CResult_SignedRawInvoiceNoneZ_clone(orig: &CResult_SignedRawInvoiceNoneZ) -> CResult_SignedRawInvoiceNoneZ { orig.clone() } #[repr(C)] /// A dynamically-allocated array of u8s of arbitrary size. /// This corresponds to std::vector in C++ @@ -1836,8 +2005,8 @@ impl Drop for CResult_NoneSemanticErrorZ { } } } -impl From> for CResult_NoneSemanticErrorZ { - fn from(mut o: crate::c_types::CResultTempl) -> Self { +impl From> for CResult_NoneSemanticErrorZ { + fn from(mut o: crate::c_types::CResultTempl<(), crate::lightning_invoice::SemanticError>) -> Self { let contents = if o.result_ok { let _ = unsafe { Box::from_raw(o.contents.result) }; o.contents.result = std::ptr::null_mut(); @@ -2285,14 +2454,14 @@ pub extern "C" fn CResult_RouteHintCreationErrorZ_clone(orig: &CResult_RouteHint pub union CResult_StringErrorZPtr { /// 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::derived::CVec_u8Z, + pub result: *mut crate::c_types::Str, /// A pointer to the contents in the error state. /// Reading from this pointer when `result_ok` is set is undefined. pub err: *mut crate::c_types::Secp256k1Error, } #[repr(C)] /// A CResult_StringErrorZ represents the result of a fallible operation, -/// containing a crate::c_types::derived::CVec_u8Z on success and a crate::c_types::Secp256k1Error on failure. +/// containing a crate::c_types::Str on success and a crate::c_types::Secp256k1Error on failure. /// `result_ok` indicates the overall state, and the contents are provided via `contents`. pub struct CResult_StringErrorZ { /// The contents of this CResult_StringErrorZ, accessible via either @@ -2303,7 +2472,7 @@ pub struct CResult_StringErrorZ { } #[no_mangle] /// Creates a new CResult_StringErrorZ in the success state. -pub extern "C" fn CResult_StringErrorZ_ok(o: crate::c_types::derived::CVec_u8Z) -> CResult_StringErrorZ { +pub extern "C" fn CResult_StringErrorZ_ok(o: crate::c_types::Str) -> CResult_StringErrorZ { CResult_StringErrorZ { contents: CResult_StringErrorZPtr { result: Box::into_raw(Box::new(o)), @@ -2337,8 +2506,8 @@ impl Drop for CResult_StringErrorZ { } } } -impl From> for CResult_StringErrorZ { - fn from(mut o: crate::c_types::CResultTempl) -> Self { +impl From> for CResult_StringErrorZ { + fn from(mut o: crate::c_types::CResultTempl) -> Self { let contents = if o.result_ok { let result = unsafe { o.contents.result }; unsafe { o.contents.result = std::ptr::null_mut() }; @@ -2589,8 +2758,8 @@ impl Drop for CResult_NoneMonitorUpdateErrorZ { } } } -impl From> for CResult_NoneMonitorUpdateErrorZ { - fn from(mut o: crate::c_types::CResultTempl) -> Self { +impl From> for CResult_NoneMonitorUpdateErrorZ { + fn from(mut o: crate::c_types::CResultTempl<(), crate::lightning::chain::channelmonitor::MonitorUpdateError>) -> Self { let contents = if o.result_ok { let _ = unsafe { Box::from_raw(o.contents.result) }; o.contents.result = std::ptr::null_mut(); @@ -3266,8 +3435,8 @@ impl Drop for CResult_NoneChannelMonitorUpdateErrZ { } } } -impl From> for CResult_NoneChannelMonitorUpdateErrZ { - fn from(mut o: crate::c_types::CResultTempl) -> Self { +impl From> for CResult_NoneChannelMonitorUpdateErrZ { + fn from(mut o: crate::c_types::CResultTempl<(), crate::lightning::chain::channelmonitor::ChannelMonitorUpdateErr>) -> Self { let contents = if o.result_ok { let _ = unsafe { Box::from_raw(o.contents.result) }; o.contents.result = std::ptr::null_mut(); @@ -4052,8 +4221,8 @@ impl Drop for CResult_NoneLightningErrorZ { } } } -impl From> for CResult_NoneLightningErrorZ { - fn from(mut o: crate::c_types::CResultTempl) -> Self { +impl From> for CResult_NoneLightningErrorZ { + fn from(mut o: crate::c_types::CResultTempl<(), crate::lightning::ln::msgs::LightningError>) -> Self { let contents = if o.result_ok { let _ = unsafe { Box::from_raw(o.contents.result) }; o.contents.result = std::ptr::null_mut(); @@ -4268,8 +4437,8 @@ impl Drop for CResult_NonePeerHandleErrorZ { } } } -impl From> for CResult_NonePeerHandleErrorZ { - fn from(mut o: crate::c_types::CResultTempl) -> Self { +impl From> for CResult_NonePeerHandleErrorZ { + fn from(mut o: crate::c_types::CResultTempl<(), crate::lightning::ln::peer_handler::PeerHandleError>) -> Self { let contents = if o.result_ok { let _ = unsafe { Box::from_raw(o.contents.result) }; o.contents.result = std::ptr::null_mut(); @@ -8681,6 +8850,97 @@ impl Clone for CResult_GossipTimestampFilterDecodeErrorZ { /// but with all dynamically-allocated buffers duplicated in new buffers. pub extern "C" fn CResult_GossipTimestampFilterDecodeErrorZ_clone(orig: &CResult_GossipTimestampFilterDecodeErrorZ) -> CResult_GossipTimestampFilterDecodeErrorZ { orig.clone() } #[repr(C)] +/// The contents of CResult_InvoiceSignOrCreationErrorZ +pub union CResult_InvoiceSignOrCreationErrorZPtr { + /// 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::lightning_invoice::Invoice, + /// 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_invoice::SignOrCreationError, +} +#[repr(C)] +/// A CResult_InvoiceSignOrCreationErrorZ represents the result of a fallible operation, +/// containing a crate::lightning_invoice::Invoice on success and a crate::lightning_invoice::SignOrCreationError on failure. +/// `result_ok` indicates the overall state, and the contents are provided via `contents`. +pub struct CResult_InvoiceSignOrCreationErrorZ { + /// The contents of this CResult_InvoiceSignOrCreationErrorZ, accessible via either + /// `err` or `result` depending on the state of `result_ok`. + pub contents: CResult_InvoiceSignOrCreationErrorZPtr, + /// Whether this CResult_InvoiceSignOrCreationErrorZ represents a success state. + pub result_ok: bool, +} +#[no_mangle] +/// Creates a new CResult_InvoiceSignOrCreationErrorZ in the success state. +pub extern "C" fn CResult_InvoiceSignOrCreationErrorZ_ok(o: crate::lightning_invoice::Invoice) -> CResult_InvoiceSignOrCreationErrorZ { + CResult_InvoiceSignOrCreationErrorZ { + contents: CResult_InvoiceSignOrCreationErrorZPtr { + result: Box::into_raw(Box::new(o)), + }, + result_ok: true, + } +} +#[no_mangle] +/// Creates a new CResult_InvoiceSignOrCreationErrorZ in the error state. +pub extern "C" fn CResult_InvoiceSignOrCreationErrorZ_err(e: crate::lightning_invoice::SignOrCreationError) -> CResult_InvoiceSignOrCreationErrorZ { + CResult_InvoiceSignOrCreationErrorZ { + contents: CResult_InvoiceSignOrCreationErrorZPtr { + err: Box::into_raw(Box::new(e)), + }, + result_ok: false, + } +} +#[no_mangle] +/// Frees any resources used by the CResult_InvoiceSignOrCreationErrorZ. +pub extern "C" fn CResult_InvoiceSignOrCreationErrorZ_free(_res: CResult_InvoiceSignOrCreationErrorZ) { } +impl Drop for CResult_InvoiceSignOrCreationErrorZ { + 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> for CResult_InvoiceSignOrCreationErrorZ { + fn from(mut o: crate::c_types::CResultTempl) -> Self { + let contents = if o.result_ok { + let result = unsafe { o.contents.result }; + unsafe { o.contents.result = std::ptr::null_mut() }; + CResult_InvoiceSignOrCreationErrorZPtr { result } + } else { + let err = unsafe { o.contents.err }; + unsafe { o.contents.err = std::ptr::null_mut(); } + CResult_InvoiceSignOrCreationErrorZPtr { err } + }; + Self { + contents, + result_ok: o.result_ok, + } + } +} +impl Clone for CResult_InvoiceSignOrCreationErrorZ { + fn clone(&self) -> Self { + if self.result_ok { + Self { result_ok: true, contents: CResult_InvoiceSignOrCreationErrorZPtr { + result: Box::into_raw(Box::new(::clone(unsafe { &*self.contents.result }))) + } } + } else { + Self { result_ok: false, contents: CResult_InvoiceSignOrCreationErrorZPtr { + err: Box::into_raw(Box::new(::clone(unsafe { &*self.contents.err }))) + } } + } + } +} +#[no_mangle] +/// Creates a new CResult_InvoiceSignOrCreationErrorZ which has the same data as `orig` +/// but with all dynamically-allocated buffers duplicated in new buffers. +pub extern "C" fn CResult_InvoiceSignOrCreationErrorZ_clone(orig: &CResult_InvoiceSignOrCreationErrorZ) -> CResult_InvoiceSignOrCreationErrorZ { orig.clone() } +#[repr(C)] /// The contents of CResult_SpendableOutputDescriptorDecodeErrorZ pub union CResult_SpendableOutputDescriptorDecodeErrorZPtr { /// A pointer to the contents in the success state. @@ -8866,8 +9126,8 @@ impl Drop for CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ { } } } -impl From> for CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ { - fn from(mut o: crate::c_types::CResultTempl) -> Self { +impl From> for CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ { + fn from(mut o: crate::c_types::CResultTempl) -> Self { let contents = if o.result_ok { let result = unsafe { o.contents.result }; unsafe { o.contents.result = std::ptr::null_mut() }; @@ -8953,8 +9213,8 @@ impl Drop for CResult_SignatureNoneZ { } } } -impl From> for CResult_SignatureNoneZ { - fn from(mut o: crate::c_types::CResultTempl) -> Self { +impl From> for CResult_SignatureNoneZ { + fn from(mut o: crate::c_types::CResultTempl) -> Self { let contents = if o.result_ok { let result = unsafe { o.contents.result }; unsafe { o.contents.result = std::ptr::null_mut() }; @@ -9079,6 +9339,93 @@ impl Clone for CResult_SignDecodeErrorZ { /// but with all dynamically-allocated buffers duplicated in new buffers. pub extern "C" fn CResult_SignDecodeErrorZ_clone(orig: &CResult_SignDecodeErrorZ) -> CResult_SignDecodeErrorZ { orig.clone() } #[repr(C)] +/// The contents of CResult_RecoverableSignatureNoneZ +pub union CResult_RecoverableSignatureNoneZPtr { + /// 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::RecoverableSignature, + /// Note that this value is always NULL, as there are no contents in the Err variant + pub err: *mut std::ffi::c_void, +} +#[repr(C)] +/// A CResult_RecoverableSignatureNoneZ represents the result of a fallible operation, +/// containing a crate::c_types::RecoverableSignature on success and a () on failure. +/// `result_ok` indicates the overall state, and the contents are provided via `contents`. +pub struct CResult_RecoverableSignatureNoneZ { + /// The contents of this CResult_RecoverableSignatureNoneZ, accessible via either + /// `err` or `result` depending on the state of `result_ok`. + pub contents: CResult_RecoverableSignatureNoneZPtr, + /// Whether this CResult_RecoverableSignatureNoneZ represents a success state. + pub result_ok: bool, +} +#[no_mangle] +/// Creates a new CResult_RecoverableSignatureNoneZ in the success state. +pub extern "C" fn CResult_RecoverableSignatureNoneZ_ok(o: crate::c_types::RecoverableSignature) -> CResult_RecoverableSignatureNoneZ { + CResult_RecoverableSignatureNoneZ { + contents: CResult_RecoverableSignatureNoneZPtr { + result: Box::into_raw(Box::new(o)), + }, + result_ok: true, + } +} +#[no_mangle] +/// Creates a new CResult_RecoverableSignatureNoneZ in the error state. +pub extern "C" fn CResult_RecoverableSignatureNoneZ_err() -> CResult_RecoverableSignatureNoneZ { + CResult_RecoverableSignatureNoneZ { + contents: CResult_RecoverableSignatureNoneZPtr { + err: std::ptr::null_mut(), + }, + result_ok: false, + } +} +#[no_mangle] +/// Frees any resources used by the CResult_RecoverableSignatureNoneZ. +pub extern "C" fn CResult_RecoverableSignatureNoneZ_free(_res: CResult_RecoverableSignatureNoneZ) { } +impl Drop for CResult_RecoverableSignatureNoneZ { + 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 { + } + } +} +impl From> for CResult_RecoverableSignatureNoneZ { + fn from(mut o: crate::c_types::CResultTempl) -> Self { + let contents = if o.result_ok { + let result = unsafe { o.contents.result }; + unsafe { o.contents.result = std::ptr::null_mut() }; + CResult_RecoverableSignatureNoneZPtr { result } + } else { + let _ = unsafe { Box::from_raw(o.contents.err) }; + o.contents.err = std::ptr::null_mut(); + CResult_RecoverableSignatureNoneZPtr { err: std::ptr::null_mut() } + }; + Self { + contents, + result_ok: o.result_ok, + } + } +} +impl Clone for CResult_RecoverableSignatureNoneZ { + fn clone(&self) -> Self { + if self.result_ok { + Self { result_ok: true, contents: CResult_RecoverableSignatureNoneZPtr { + result: Box::into_raw(Box::new(::clone(unsafe { &*self.contents.result }))) + } } + } else { + Self { result_ok: false, contents: CResult_RecoverableSignatureNoneZPtr { + err: std::ptr::null_mut() + } } + } + } +} +#[no_mangle] +/// Creates a new CResult_RecoverableSignatureNoneZ which has the same data as `orig` +/// but with all dynamically-allocated buffers duplicated in new buffers. +pub extern "C" fn CResult_RecoverableSignatureNoneZ_clone(orig: &CResult_RecoverableSignatureNoneZ) -> CResult_RecoverableSignatureNoneZ { orig.clone() } +#[repr(C)] /// A dynamically-allocated array of crate::c_types::derived::CVec_u8Zs of arbitrary size. /// This corresponds to std::vector in C++ pub struct CVec_CVec_u8ZZ { @@ -9177,8 +9524,8 @@ impl Drop for CResult_CVec_CVec_u8ZZNoneZ { } } } -impl From> for CResult_CVec_CVec_u8ZZNoneZ { - fn from(mut o: crate::c_types::CResultTempl) -> Self { +impl From> for CResult_CVec_CVec_u8ZZNoneZ { + fn from(mut o: crate::c_types::CResultTempl) -> Self { let contents = if o.result_ok { let result = unsafe { o.contents.result }; unsafe { o.contents.result = std::ptr::null_mut() }; @@ -9401,8 +9748,8 @@ impl Drop for CResult_TransactionNoneZ { } } } -impl From> for CResult_TransactionNoneZ { - fn from(mut o: crate::c_types::CResultTempl) -> Self { +impl From> for CResult_TransactionNoneZ { + fn from(mut o: crate::c_types::CResultTempl) -> Self { let contents = if o.result_ok { let result = unsafe { o.contents.result }; unsafe { o.contents.result = std::ptr::null_mut() }; @@ -9471,8 +9818,8 @@ impl Drop for CResult_NoneErrorZ { } } } -impl From> for CResult_NoneErrorZ { - fn from(mut o: crate::c_types::CResultTempl) -> Self { +impl From> for CResult_NoneErrorZ { + fn from(mut o: crate::c_types::CResultTempl<(), crate::c_types::IOError>) -> Self { let contents = if o.result_ok { let _ = unsafe { Box::from_raw(o.contents.result) }; o.contents.result = std::ptr::null_mut(); @@ -9653,8 +10000,8 @@ impl Drop for CResult_NoneAPIErrorZ { } } } -impl From> for CResult_NoneAPIErrorZ { - fn from(mut o: crate::c_types::CResultTempl) -> Self { +impl From> for CResult_NoneAPIErrorZ { + fn from(mut o: crate::c_types::CResultTempl<(), crate::lightning::util::errors::APIError>) -> Self { let contents = if o.result_ok { let _ = unsafe { Box::from_raw(o.contents.result) }; o.contents.result = std::ptr::null_mut(); @@ -9832,8 +10179,8 @@ impl Drop for CResult_NonePaymentSendFailureZ { } } } -impl From> for CResult_NonePaymentSendFailureZ { - fn from(mut o: crate::c_types::CResultTempl) -> Self { +impl From> for CResult_NonePaymentSendFailureZ { + fn from(mut o: crate::c_types::CResultTempl<(), crate::lightning::ln::channelmanager::PaymentSendFailure>) -> Self { let contents = if o.result_ok { let _ = unsafe { Box::from_raw(o.contents.result) }; o.contents.result = std::ptr::null_mut(); diff --git a/lightning-c-bindings/src/c_types/mod.rs b/lightning-c-bindings/src/c_types/mod.rs index cd96dff..3d45802 100644 --- a/lightning-c-bindings/src/c_types/mod.rs +++ b/lightning-c-bindings/src/c_types/mod.rs @@ -9,6 +9,8 @@ use bitcoin::secp256k1::key::PublicKey as SecpPublicKey; use bitcoin::secp256k1::key::SecretKey as SecpSecretKey; use bitcoin::secp256k1::Signature as SecpSignature; use bitcoin::secp256k1::Error as SecpError; +use bitcoin::secp256k1::recovery::RecoveryId; +use bitcoin::secp256k1::recovery::RecoverableSignature as SecpRecoverableSignature; use bitcoin::bech32; use std::convert::TryInto; // Bindings need at least rustc 1.34 @@ -85,6 +87,32 @@ impl Signature { #[allow(unused)] pub(crate) fn null() -> Self { Self { compact_form: [0; 64] } } } +#[repr(C)] +#[derive(Clone)] +/// Represents a secp256k1 signature serialized as two 32-byte numbers as well as a tag which +/// allows recovering the exact public key which created the signature given the message. +pub struct RecoverableSignature { + /// The bytes of the signature in "compact" form plus a "Recovery ID" which allows for + /// recovery. + pub serialized_form: [u8; 68], +} +impl RecoverableSignature { + pub(crate) fn from_rust(pk: &SecpRecoverableSignature) -> Self { + let (id, compact_form) = pk.serialize_compact(); + let mut serialized_form = [0; 68]; + serialized_form[0..64].copy_from_slice(&compact_form[..]); + serialized_form[64..].copy_from_slice(&id.to_i32().to_le_bytes()); + Self { serialized_form } + } + pub(crate) fn into_rust(&self) -> SecpRecoverableSignature { + let mut id = [0; 4]; + id.copy_from_slice(&self.serialized_form[64..]); + SecpRecoverableSignature::from_compact(&self.serialized_form[0..64], + RecoveryId::from_i32(i32::from_le_bytes(id)).expect("Invalid Recovery ID")) + .unwrap() + } +} + #[repr(C)] /// Represents an error returned from libsecp256k1 during validation of some secp256k1 data pub enum Secp256k1Error { @@ -354,11 +382,25 @@ impl Into for &'static str { Str { chars: self.as_ptr(), len: self.len(), chars_is_owned: false } } } -impl Into<&'static str> for Str { - fn into(self) -> &'static str { +impl Str { + pub(crate) fn into_str(&self) -> &'static str { if self.len == 0 { return ""; } std::str::from_utf8(unsafe { std::slice::from_raw_parts(self.chars, self.len) }).unwrap() } + pub(crate) fn into_string(self) -> String { + let bytes = if self.len == 0 { + Vec::new() + } else if self.chars_is_owned { + unsafe { + Box::from_raw(std::slice::from_raw_parts_mut(unsafe { self.chars as *mut u8 }, self.len)) + }.into() + } else { + let mut ret = Vec::with_capacity(self.len); + ret.extend_from_slice(unsafe { std::slice::from_raw_parts(self.chars, self.len) }); + ret + }; + String::from_utf8(bytes).unwrap() + } } impl Into for String { fn into(self) -> Str { diff --git a/lightning-c-bindings/src/lightning/chain/chaininterface.rs b/lightning-c-bindings/src/lightning/chain/chaininterface.rs index 99e3956..17cff8b 100644 --- a/lightning-c-bindings/src/lightning/chain/chaininterface.rs +++ b/lightning-c-bindings/src/lightning/chain/chaininterface.rs @@ -29,12 +29,10 @@ pub struct BroadcasterInterface { /// 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, } -unsafe impl Sync for BroadcasterInterface {} -unsafe impl Send for BroadcasterInterface {} use lightning::chain::chaininterface::BroadcasterInterface as rustBroadcasterInterface; impl rustBroadcasterInterface for BroadcasterInterface { - fn broadcast_transaction(&self, tx: &bitcoin::blockdata::transaction::Transaction) { + fn broadcast_transaction(&self, mut tx: &bitcoin::blockdata::transaction::Transaction) { (self.broadcast_transaction)(self.this_arg, crate::c_types::Transaction::from_bitcoin(tx)) } } @@ -134,12 +132,10 @@ pub struct FeeEstimator { /// 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, } -unsafe impl Sync for FeeEstimator {} -unsafe impl Send for FeeEstimator {} use lightning::chain::chaininterface::FeeEstimator as rustFeeEstimator; impl rustFeeEstimator for FeeEstimator { - fn get_est_sat_per_1000_weight(&self, confirmation_target: lightning::chain::chaininterface::ConfirmationTarget) -> u32 { + fn get_est_sat_per_1000_weight(&self, mut confirmation_target: lightning::chain::chaininterface::ConfirmationTarget) -> u32 { let mut ret = (self.get_est_sat_per_1000_weight)(self.this_arg, crate::lightning::chain::chaininterface::ConfirmationTarget::native_into(confirmation_target)); ret } diff --git a/lightning-c-bindings/src/lightning/chain/chainmonitor.rs b/lightning-c-bindings/src/lightning/chain/chainmonitor.rs index 9832df4..3005c4b 100644 --- a/lightning-c-bindings/src/lightning/chain/chainmonitor.rs +++ b/lightning-c-bindings/src/lightning/chain/chainmonitor.rs @@ -191,13 +191,13 @@ pub extern "C" fn ChainMonitor_as_Watch(this_arg: &ChainMonitor) -> crate::light #[must_use] extern "C" fn ChainMonitor_Watch_watch_channel(this_arg: *const c_void, mut funding_outpoint: crate::lightning::chain::transaction::OutPoint, mut monitor: crate::lightning::chain::channelmonitor::ChannelMonitor) -> crate::c_types::derived::CResult_NoneChannelMonitorUpdateErrZ { let mut ret = >::watch_channel(unsafe { &mut *(this_arg as *mut nativeChainMonitor) }, *unsafe { Box::from_raw(funding_outpoint.take_inner()) }, *unsafe { Box::from_raw(monitor.take_inner()) }); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::chain::channelmonitor::ChannelMonitorUpdateErr::native_into(e) }).into() }; + 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::lightning::chain::channelmonitor::ChannelMonitorUpdateErr::native_into(e) }).into() }; local_ret } #[must_use] extern "C" fn ChainMonitor_Watch_update_channel(this_arg: *const c_void, mut funding_txo: crate::lightning::chain::transaction::OutPoint, mut update: crate::lightning::chain::channelmonitor::ChannelMonitorUpdate) -> crate::c_types::derived::CResult_NoneChannelMonitorUpdateErrZ { let mut ret = >::update_channel(unsafe { &mut *(this_arg as *mut nativeChainMonitor) }, *unsafe { Box::from_raw(funding_txo.take_inner()) }, *unsafe { Box::from_raw(update.take_inner()) }); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::chain::channelmonitor::ChannelMonitorUpdateErr::native_into(e) }).into() }; + 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::lightning::chain::channelmonitor::ChannelMonitorUpdateErr::native_into(e) }).into() }; local_ret } #[must_use] diff --git a/lightning-c-bindings/src/lightning/chain/channelmonitor.rs b/lightning-c-bindings/src/lightning/chain/channelmonitor.rs index 2338270..6bfd3c3 100644 --- a/lightning-c-bindings/src/lightning/chain/channelmonitor.rs +++ b/lightning-c-bindings/src/lightning/chain/channelmonitor.rs @@ -556,7 +556,7 @@ pub(crate) extern "C" fn ChannelMonitor_write_void(obj: *const c_void) -> crate: #[no_mangle] pub extern "C" fn ChannelMonitor_update_monitor(this_arg: &ChannelMonitor, updates: &crate::lightning::chain::channelmonitor::ChannelMonitorUpdate, broadcaster: &crate::lightning::chain::chaininterface::BroadcasterInterface, fee_estimator: &crate::lightning::chain::chaininterface::FeeEstimator, logger: &crate::lightning::util::logger::Logger) -> crate::c_types::derived::CResult_NoneMonitorUpdateErrorZ { let mut ret = unsafe { &*this_arg.inner }.update_monitor(unsafe { &*updates.inner }, broadcaster, fee_estimator, logger); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::chain::channelmonitor::MonitorUpdateError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() }; + 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::lightning::chain::channelmonitor::MonitorUpdateError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() }; local_ret } @@ -769,17 +769,15 @@ pub struct Persist { /// 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, } -unsafe impl Send for Persist {} -unsafe impl Sync for Persist {} use lightning::chain::channelmonitor::Persist as rustPersist; impl rustPersist for Persist { - fn persist_new_channel(&self, id: lightning::chain::transaction::OutPoint, data: &lightning::chain::channelmonitor::ChannelMonitor) -> Result<(), lightning::chain::channelmonitor::ChannelMonitorUpdateErr> { + fn persist_new_channel(&self, mut id: lightning::chain::transaction::OutPoint, mut data: &lightning::chain::channelmonitor::ChannelMonitor) -> Result<(), lightning::chain::channelmonitor::ChannelMonitorUpdateErr> { let mut ret = (self.persist_new_channel)(self.this_arg, crate::lightning::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(id)), is_owned: true }, &crate::lightning::chain::channelmonitor::ChannelMonitor { inner: unsafe { (data 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)) })*/ }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).into_native() })}; local_ret } - fn update_persisted_channel(&self, id: lightning::chain::transaction::OutPoint, update: &lightning::chain::channelmonitor::ChannelMonitorUpdate, data: &lightning::chain::channelmonitor::ChannelMonitor) -> Result<(), lightning::chain::channelmonitor::ChannelMonitorUpdateErr> { + fn update_persisted_channel(&self, mut id: lightning::chain::transaction::OutPoint, mut update: &lightning::chain::channelmonitor::ChannelMonitorUpdate, mut data: &lightning::chain::channelmonitor::ChannelMonitor) -> Result<(), lightning::chain::channelmonitor::ChannelMonitorUpdateErr> { let mut ret = (self.update_persisted_channel)(self.this_arg, crate::lightning::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(id)), is_owned: true }, &crate::lightning::chain::channelmonitor::ChannelMonitorUpdate { inner: unsafe { (update as *const _) as *mut _ }, is_owned: false }, &crate::lightning::chain::channelmonitor::ChannelMonitor { inner: unsafe { (data 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)) })*/ }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).into_native() })}; local_ret diff --git a/lightning-c-bindings/src/lightning/chain/keysinterface.rs b/lightning-c-bindings/src/lightning/chain/keysinterface.rs index 140461f..c3292d3 100644 --- a/lightning-c-bindings/src/lightning/chain/keysinterface.rs +++ b/lightning-c-bindings/src/lightning/chain/keysinterface.rs @@ -598,15 +598,14 @@ pub struct BaseSign { /// 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, } -unsafe impl Send for BaseSign {} use lightning::chain::keysinterface::BaseSign as rustBaseSign; impl rustBaseSign for BaseSign { - fn get_per_commitment_point(&self, idx: u64, _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> bitcoin::secp256k1::key::PublicKey { + fn get_per_commitment_point(&self, mut idx: u64, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> bitcoin::secp256k1::key::PublicKey { let mut ret = (self.get_per_commitment_point)(self.this_arg, idx); ret.into_rust() } - fn release_commitment_secret(&self, idx: u64) -> [u8; 32] { + fn release_commitment_secret(&self, mut idx: u64) -> [u8; 32] { let mut ret = (self.release_commitment_secret)(self.this_arg, idx); ret.data } @@ -620,38 +619,38 @@ impl rustBaseSign for BaseSign { let mut ret = (self.channel_keys_id)(self.this_arg); ret.data } - fn sign_counterparty_commitment(&self, commitment_tx: &lightning::ln::chan_utils::CommitmentTransaction, _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result<(bitcoin::secp256k1::Signature, Vec), ()> { + fn sign_counterparty_commitment(&self, mut commitment_tx: &lightning::ln::chan_utils::CommitmentTransaction, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result<(bitcoin::secp256k1::Signature, Vec), ()> { let mut ret = (self.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 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, commitment_tx: &lightning::ln::chan_utils::HolderCommitmentTransaction, _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result<(bitcoin::secp256k1::Signature, Vec), ()> { + fn sign_holder_commitment_and_htlcs(&self, mut commitment_tx: &lightning::ln::chan_utils::HolderCommitmentTransaction, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result<(bitcoin::secp256k1::Signature, Vec), ()> { let mut ret = (self.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 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_transaction(&self, justice_tx: &bitcoin::blockdata::transaction::Transaction, input: usize, amount: u64, per_commitment_key: &bitcoin::secp256k1::key::SecretKey, htlc: &Option, _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result { + fn sign_justice_transaction(&self, mut justice_tx: &bitcoin::blockdata::transaction::Transaction, mut input: usize, mut amount: u64, mut per_commitment_key: &bitcoin::secp256k1::key::SecretKey, mut htlc: &Option, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result { let mut local_htlc = &crate::lightning::ln::chan_utils::HTLCOutputInCommitment { inner: unsafe { (if htlc.is_none() { std::ptr::null() } else { { (htlc.as_ref().unwrap()) } } as *const _) as *mut _ }, is_owned: false }; let mut ret = (self.sign_justice_transaction)(self.this_arg, crate::c_types::Transaction::from_bitcoin(justice_tx), input, amount, per_commitment_key.as_ref(), local_htlc); 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, htlc_tx: &bitcoin::blockdata::transaction::Transaction, input: usize, amount: u64, per_commitment_point: &bitcoin::secp256k1::key::PublicKey, htlc: &lightning::ln::chan_utils::HTLCOutputInCommitment, _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result { + 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) -> Result { let mut ret = (self.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 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, closing_tx: &bitcoin::blockdata::transaction::Transaction, _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result { + fn sign_closing_transaction(&self, mut closing_tx: &bitcoin::blockdata::transaction::Transaction, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result { let mut ret = (self.sign_closing_transaction)(self.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, msg: &lightning::ln::msgs::UnsignedChannelAnnouncement, _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result { + fn sign_channel_announcement(&self, mut msg: &lightning::ln::msgs::UnsignedChannelAnnouncement, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result { let mut ret = (self.sign_channel_announcement)(self.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, channel_parameters: &lightning::ln::chan_utils::ChannelTransactionParameters) { + fn ready_channel(&mut self, mut channel_parameters: &lightning::ln::chan_utils::ChannelTransactionParameters) { (self.ready_channel)(self.this_arg, &crate::lightning::ln::chan_utils::ChannelTransactionParameters { inner: unsafe { (channel_parameters as *const _) as *mut _ }, is_owned: false }) } } @@ -700,11 +699,11 @@ pub struct Sign { pub free: Option, } impl lightning::chain::keysinterface::BaseSign for Sign { - fn get_per_commitment_point(&self, idx: u64, _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> bitcoin::secp256k1::key::PublicKey { + fn get_per_commitment_point(&self, mut idx: u64, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> bitcoin::secp256k1::key::PublicKey { let mut ret = (self.BaseSign.get_per_commitment_point)(self.this_arg, idx); ret.into_rust() } - fn release_commitment_secret(&self, idx: u64) -> [u8; 32] { + fn release_commitment_secret(&self, mut idx: u64) -> [u8; 32] { let mut ret = (self.BaseSign.release_commitment_secret)(self.this_arg, idx); ret.data } @@ -718,42 +717,41 @@ impl lightning::chain::keysinterface::BaseSign for Sign { let mut ret = (self.BaseSign.channel_keys_id)(self.this_arg); ret.data } - fn sign_counterparty_commitment(&self, commitment_tx: &lightning::ln::chan_utils::CommitmentTransaction, _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result<(bitcoin::secp256k1::Signature, Vec), ()> { + fn sign_counterparty_commitment(&self, mut commitment_tx: &lightning::ln::chan_utils::CommitmentTransaction, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result<(bitcoin::secp256k1::Signature, Vec), ()> { 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 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, commitment_tx: &lightning::ln::chan_utils::HolderCommitmentTransaction, _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result<(bitcoin::secp256k1::Signature, Vec), ()> { + fn sign_holder_commitment_and_htlcs(&self, mut commitment_tx: &lightning::ln::chan_utils::HolderCommitmentTransaction, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result<(bitcoin::secp256k1::Signature, Vec), ()> { 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 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_transaction(&self, justice_tx: &bitcoin::blockdata::transaction::Transaction, input: usize, amount: u64, per_commitment_key: &bitcoin::secp256k1::key::SecretKey, htlc: &Option, _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result { + fn sign_justice_transaction(&self, mut justice_tx: &bitcoin::blockdata::transaction::Transaction, mut input: usize, mut amount: u64, mut per_commitment_key: &bitcoin::secp256k1::key::SecretKey, mut htlc: &Option, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result { let mut local_htlc = &crate::lightning::ln::chan_utils::HTLCOutputInCommitment { inner: unsafe { (if htlc.is_none() { std::ptr::null() } else { { (htlc.as_ref().unwrap()) } } as *const _) as *mut _ }, is_owned: false }; let mut ret = (self.BaseSign.sign_justice_transaction)(self.this_arg, crate::c_types::Transaction::from_bitcoin(justice_tx), input, amount, per_commitment_key.as_ref(), local_htlc); 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, htlc_tx: &bitcoin::blockdata::transaction::Transaction, input: usize, amount: u64, per_commitment_point: &bitcoin::secp256k1::key::PublicKey, htlc: &lightning::ln::chan_utils::HTLCOutputInCommitment, _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result { + 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) -> Result { 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 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, closing_tx: &bitcoin::blockdata::transaction::Transaction, _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result { + fn sign_closing_transaction(&self, mut closing_tx: &bitcoin::blockdata::transaction::Transaction, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result { let mut ret = (self.BaseSign.sign_closing_transaction)(self.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, msg: &lightning::ln::msgs::UnsignedChannelAnnouncement, _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result { + fn sign_channel_announcement(&self, mut msg: &lightning::ln::msgs::UnsignedChannelAnnouncement, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result { 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 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, channel_parameters: &lightning::ln::chan_utils::ChannelTransactionParameters) { + 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 }) } } -unsafe impl Send for Sign {} impl lightning::util::ser::Writeable for Sign { fn write(&self, w: &mut W) -> Result<(), ::std::io::Error> { let vec = (self.write)(self.this_arg); @@ -845,12 +843,16 @@ pub struct KeysInterface { /// you've read all of the provided bytes to ensure no corruption occurred. #[must_use] pub read_chan_signer: extern "C" fn (this_arg: *const c_void, reader: crate::c_types::u8slice) -> crate::c_types::derived::CResult_SignDecodeErrorZ, + /// 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. + #[must_use] + pub sign_invoice: extern "C" fn (this_arg: *const c_void, invoice_preimage: crate::c_types::derived::CVec_u8Z) -> crate::c_types::derived::CResult_RecoverableSignatureNoneZ, /// 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, } -unsafe impl Send for KeysInterface {} -unsafe impl Sync for KeysInterface {} use lightning::chain::keysinterface::KeysInterface as rustKeysInterface; impl rustKeysInterface for KeysInterface { @@ -867,7 +869,7 @@ impl rustKeysInterface for KeysInterface { let mut ret = (self.get_shutdown_pubkey)(self.this_arg); ret.into_rust() } - fn get_channel_signer(&self, inbound: bool, channel_value_satoshis: u64) -> crate::lightning::chain::keysinterface::Sign { + fn get_channel_signer(&self, mut inbound: bool, mut channel_value_satoshis: u64) -> crate::lightning::chain::keysinterface::Sign { let mut ret = (self.get_channel_signer)(self.this_arg, inbound, channel_value_satoshis); ret } @@ -875,12 +877,18 @@ impl rustKeysInterface for KeysInterface { let mut ret = (self.get_secure_random_bytes)(self.this_arg); ret.data } - fn read_chan_signer(&self, reader: &[u8]) -> Result { + fn read_chan_signer(&self, mut reader: &[u8]) -> Result { let mut local_reader = crate::c_types::u8slice::from_slice(reader); let mut ret = (self.read_chan_signer)(self.this_arg, local_reader); let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }) }), false => Err( { *unsafe { Box::from_raw((*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).take_inner()) } })}; local_ret } + fn sign_invoice(&self, mut invoice_preimage: Vec) -> Result { + let mut local_invoice_preimage = Vec::new(); for mut item in invoice_preimage.drain(..) { local_invoice_preimage.push( { item }); }; + let mut ret = (self.sign_invoice)(self.this_arg, local_invoice_preimage.into()); + 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 + } } // We're essentially a pointer already, or at least a set of pointers, so allow us to be used @@ -1111,7 +1119,7 @@ pub extern "C" fn InMemorySigner_get_channel_parameters(this_arg: &InMemorySigne #[no_mangle] pub extern "C" fn InMemorySigner_sign_counterparty_payment_input(this_arg: &InMemorySigner, mut spend_tx: crate::c_types::Transaction, mut input_idx: usize, descriptor: &crate::lightning::chain::keysinterface::StaticPaymentOutputDescriptor) -> crate::c_types::derived::CResult_CVec_CVec_u8ZZNoneZ { let mut ret = unsafe { &*this_arg.inner }.sign_counterparty_payment_input(&spend_tx.into_bitcoin(), input_idx, unsafe { &*descriptor.inner }, secp256k1::SECP256K1); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let mut local_ret_0 = Vec::new(); for mut item in o.drain(..) { local_ret_0.push( { let mut local_ret_0_0 = Vec::new(); for mut item in item.drain(..) { local_ret_0_0.push( { item }); }; local_ret_0_0.into() }); }; local_ret_0.into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }).into() }; + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let mut local_ret_0 = Vec::new(); for mut item in o.drain(..) { local_ret_0.push( { let mut local_ret_0_0 = Vec::new(); for mut item in item.drain(..) { local_ret_0_0.push( { item }); }; local_ret_0_0.into() }); }; local_ret_0.into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } @@ -1125,7 +1133,7 @@ pub extern "C" fn InMemorySigner_sign_counterparty_payment_input(this_arg: &InMe #[no_mangle] pub extern "C" fn InMemorySigner_sign_dynamic_p2wsh_input(this_arg: &InMemorySigner, mut spend_tx: crate::c_types::Transaction, mut input_idx: usize, descriptor: &crate::lightning::chain::keysinterface::DelayedPaymentOutputDescriptor) -> crate::c_types::derived::CResult_CVec_CVec_u8ZZNoneZ { let mut ret = unsafe { &*this_arg.inner }.sign_dynamic_p2wsh_input(&spend_tx.into_bitcoin(), input_idx, unsafe { &*descriptor.inner }, secp256k1::SECP256K1); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let mut local_ret_0 = Vec::new(); for mut item in o.drain(..) { local_ret_0.push( { let mut local_ret_0_0 = Vec::new(); for mut item in item.drain(..) { local_ret_0_0.push( { item }); }; local_ret_0_0.into() }); }; local_ret_0.into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }).into() }; + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let mut local_ret_0 = Vec::new(); for mut item in o.drain(..) { local_ret_0.push( { let mut local_ret_0_0 = Vec::new(); for mut item in item.drain(..) { local_ret_0_0.push( { item }); }; local_ret_0_0.into() }); }; local_ret_0.into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } @@ -1192,38 +1200,38 @@ extern "C" fn InMemorySigner_BaseSign_channel_keys_id(this_arg: *const c_void) - #[must_use] extern "C" fn InMemorySigner_BaseSign_sign_counterparty_commitment(this_arg: *const c_void, commitment_tx: &crate::lightning::ln::chan_utils::CommitmentTransaction) -> crate::c_types::derived::CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ { let mut ret = >::sign_counterparty_commitment(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, unsafe { &*commitment_tx.inner }, secp256k1::SECP256K1); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = o; let mut local_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.drain(..) { local_orig_ret_0_1.push( { crate::c_types::Signature::from_rust(&item) }); }; let mut local_ret_0 = (crate::c_types::Signature::from_rust(&orig_ret_0_0), local_orig_ret_0_1.into()).into(); local_ret_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }).into() }; + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = o; let mut local_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.drain(..) { local_orig_ret_0_1.push( { crate::c_types::Signature::from_rust(&item) }); }; let mut local_ret_0 = (crate::c_types::Signature::from_rust(&orig_ret_0_0), local_orig_ret_0_1.into()).into(); local_ret_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } #[must_use] extern "C" fn InMemorySigner_BaseSign_sign_holder_commitment_and_htlcs(this_arg: *const c_void, commitment_tx: &crate::lightning::ln::chan_utils::HolderCommitmentTransaction) -> crate::c_types::derived::CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ { let mut ret = >::sign_holder_commitment_and_htlcs(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, unsafe { &*commitment_tx.inner }, secp256k1::SECP256K1); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = o; let mut local_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.drain(..) { local_orig_ret_0_1.push( { crate::c_types::Signature::from_rust(&item) }); }; let mut local_ret_0 = (crate::c_types::Signature::from_rust(&orig_ret_0_0), local_orig_ret_0_1.into()).into(); local_ret_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }).into() }; + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = o; let mut local_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.drain(..) { local_orig_ret_0_1.push( { crate::c_types::Signature::from_rust(&item) }); }; let mut local_ret_0 = (crate::c_types::Signature::from_rust(&orig_ret_0_0), local_orig_ret_0_1.into()).into(); local_ret_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } #[must_use] extern "C" fn InMemorySigner_BaseSign_sign_justice_transaction(this_arg: *const c_void, mut justice_tx: crate::c_types::Transaction, mut input: usize, mut amount: u64, per_commitment_key: *const [u8; 32], htlc: &crate::lightning::ln::chan_utils::HTLCOutputInCommitment) -> crate::c_types::derived::CResult_SignatureNoneZ { let mut local_htlc = if htlc.inner.is_null() { None } else { Some((* { unsafe { &*htlc.inner } }).clone()) }; let mut ret = >::sign_justice_transaction(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, &justice_tx.into_bitcoin(), input, amount, &::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *per_commitment_key}[..]).unwrap(), &local_htlc, secp256k1::SECP256K1); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Signature::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }).into() }; + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Signature::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } #[must_use] extern "C" fn InMemorySigner_BaseSign_sign_counterparty_htlc_transaction(this_arg: *const c_void, mut htlc_tx: crate::c_types::Transaction, mut input: usize, mut amount: u64, mut per_commitment_point: crate::c_types::PublicKey, htlc: &crate::lightning::ln::chan_utils::HTLCOutputInCommitment) -> crate::c_types::derived::CResult_SignatureNoneZ { let mut ret = >::sign_counterparty_htlc_transaction(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, &htlc_tx.into_bitcoin(), input, amount, &per_commitment_point.into_rust(), unsafe { &*htlc.inner }, secp256k1::SECP256K1); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Signature::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }).into() }; + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Signature::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } #[must_use] extern "C" fn InMemorySigner_BaseSign_sign_closing_transaction(this_arg: *const c_void, mut closing_tx: crate::c_types::Transaction) -> crate::c_types::derived::CResult_SignatureNoneZ { let mut ret = >::sign_closing_transaction(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, &closing_tx.into_bitcoin(), secp256k1::SECP256K1); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Signature::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }).into() }; + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Signature::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } #[must_use] extern "C" fn InMemorySigner_BaseSign_sign_channel_announcement(this_arg: *const c_void, msg: &crate::lightning::ln::msgs::UnsignedChannelAnnouncement) -> crate::c_types::derived::CResult_SignatureNoneZ { let mut ret = >::sign_channel_announcement(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, unsafe { &*msg.inner }, secp256k1::SECP256K1); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Signature::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }).into() }; + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Signature::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } extern "C" fn InMemorySigner_BaseSign_ready_channel(this_arg: *mut c_void, channel_parameters: &crate::lightning::ln::chan_utils::ChannelTransactionParameters) { @@ -1412,7 +1420,7 @@ pub extern "C" fn KeysManager_spend_spendable_outputs(this_arg: &KeysManager, mu let mut local_descriptors = Vec::new(); for mut item in descriptors.into_rust().drain(..) { local_descriptors.push( { item.into_native() }); }; let mut local_outputs = Vec::new(); for mut item in outputs.into_rust().drain(..) { local_outputs.push( { item.into_rust() }); }; let mut ret = unsafe { &*this_arg.inner }.spend_spendable_outputs(&local_descriptors.iter().collect::>()[..], local_outputs, ::bitcoin::blockdata::script::Script::from(change_destination_script.into_rust()), feerate_sat_per_1000_weight, secp256k1::SECP256K1); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Transaction::from_bitcoin(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }).into() }; + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Transaction::from_bitcoin(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } @@ -1439,6 +1447,7 @@ pub extern "C" fn KeysManager_as_KeysInterface(this_arg: &KeysManager) -> crate: get_channel_signer: KeysManager_KeysInterface_get_channel_signer, get_secure_random_bytes: KeysManager_KeysInterface_get_secure_random_bytes, read_chan_signer: KeysManager_KeysInterface_read_chan_signer, + sign_invoice: KeysManager_KeysInterface_sign_invoice, } } @@ -1473,4 +1482,11 @@ extern "C" fn KeysManager_KeysInterface_read_chan_signer(this_arg: *const c_void let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { o.into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() }; local_ret } +#[must_use] +extern "C" fn KeysManager_KeysInterface_sign_invoice(this_arg: *const c_void, mut invoice_preimage: crate::c_types::derived::CVec_u8Z) -> crate::c_types::derived::CResult_RecoverableSignatureNoneZ { + let mut local_invoice_preimage = Vec::new(); for mut item in invoice_preimage.into_rust().drain(..) { local_invoice_preimage.push( { item }); }; + let mut ret = >::sign_invoice(unsafe { &mut *(this_arg as *mut nativeKeysManager) }, local_invoice_preimage); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::RecoverableSignature::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; + local_ret +} diff --git a/lightning-c-bindings/src/lightning/chain/mod.rs b/lightning-c-bindings/src/lightning/chain/mod.rs index 18b3fdb..2d43823 100644 --- a/lightning-c-bindings/src/lightning/chain/mod.rs +++ b/lightning-c-bindings/src/lightning/chain/mod.rs @@ -82,12 +82,10 @@ pub struct Access { /// 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, } -unsafe impl Send for Access {} -unsafe impl Sync for Access {} use lightning::chain::Access as rustAccess; impl rustAccess for Access { - fn get_utxo(&self, genesis_hash: &bitcoin::hash_types::BlockHash, short_channel_id: u64) -> Result { + fn get_utxo(&self, mut genesis_hash: &bitcoin::hash_types::BlockHash, mut short_channel_id: u64) -> Result { let mut ret = (self.get_utxo)(self.this_arg, genesis_hash.as_inner(), short_channel_id); 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)) }).into_native() })}; local_ret @@ -135,11 +133,11 @@ pub struct Listen { use lightning::chain::Listen as rustListen; impl rustListen for Listen { - fn block_connected(&self, block: &bitcoin::blockdata::block::Block, height: u32) { + fn block_connected(&self, mut block: &bitcoin::blockdata::block::Block, mut height: u32) { let mut local_block = ::bitcoin::consensus::encode::serialize(block); (self.block_connected)(self.this_arg, crate::c_types::u8slice::from_slice(&local_block), height) } - fn block_disconnected(&self, header: &bitcoin::blockdata::block::BlockHeader, height: u32) { + fn block_disconnected(&self, mut header: &bitcoin::blockdata::block::BlockHeader, mut height: u32) { let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s }; (self.block_disconnected)(self.this_arg, &local_header, height) } @@ -250,15 +248,15 @@ pub struct Confirm { use lightning::chain::Confirm as rustConfirm; impl rustConfirm for Confirm { - fn transactions_confirmed(&self, header: &bitcoin::blockdata::block::BlockHeader, txdata: &lightning::chain::transaction::TransactionData, height: u32) { + fn transactions_confirmed(&self, mut header: &bitcoin::blockdata::block::BlockHeader, mut txdata: &lightning::chain::transaction::TransactionData, mut height: u32) { let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s }; let mut local_txdata = Vec::new(); for item in txdata.iter() { local_txdata.push( { let (mut orig_txdata_0_0, mut orig_txdata_0_1) = *item; let mut local_txdata_0 = (orig_txdata_0_0, crate::c_types::Transaction::from_bitcoin(&orig_txdata_0_1)).into(); local_txdata_0 }); }; (self.transactions_confirmed)(self.this_arg, &local_header, local_txdata.into(), height) } - fn transaction_unconfirmed(&self, txid: &bitcoin::hash_types::Txid) { + fn transaction_unconfirmed(&self, mut txid: &bitcoin::hash_types::Txid) { (self.transaction_unconfirmed)(self.this_arg, txid.as_inner()) } - fn best_block_updated(&self, header: &bitcoin::blockdata::block::BlockHeader, height: u32) { + fn best_block_updated(&self, mut header: &bitcoin::blockdata::block::BlockHeader, mut height: u32) { let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s }; (self.best_block_updated)(self.this_arg, &local_header, height) } @@ -341,17 +339,15 @@ pub struct Watch { /// 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, } -unsafe impl Send for Watch {} -unsafe impl Sync for Watch {} use lightning::chain::Watch as rustWatch; impl rustWatch for Watch { - fn watch_channel(&self, funding_txo: lightning::chain::transaction::OutPoint, monitor: lightning::chain::channelmonitor::ChannelMonitor) -> Result<(), lightning::chain::channelmonitor::ChannelMonitorUpdateErr> { + fn watch_channel(&self, mut funding_txo: lightning::chain::transaction::OutPoint, mut monitor: lightning::chain::channelmonitor::ChannelMonitor) -> Result<(), lightning::chain::channelmonitor::ChannelMonitorUpdateErr> { let mut ret = (self.watch_channel)(self.this_arg, crate::lightning::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(funding_txo)), is_owned: true }, crate::lightning::chain::channelmonitor::ChannelMonitor { inner: Box::into_raw(Box::new(monitor)), is_owned: true }); let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).into_native() })}; local_ret } - fn update_channel(&self, funding_txo: lightning::chain::transaction::OutPoint, update: lightning::chain::channelmonitor::ChannelMonitorUpdate) -> Result<(), lightning::chain::channelmonitor::ChannelMonitorUpdateErr> { + fn update_channel(&self, mut funding_txo: lightning::chain::transaction::OutPoint, mut update: lightning::chain::channelmonitor::ChannelMonitorUpdate) -> Result<(), lightning::chain::channelmonitor::ChannelMonitorUpdateErr> { let mut ret = (self.update_channel)(self.this_arg, crate::lightning::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(funding_txo)), is_owned: true }, crate::lightning::chain::channelmonitor::ChannelMonitorUpdate { inner: Box::into_raw(Box::new(update)), is_owned: true }); let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).into_native() })}; local_ret @@ -424,15 +420,13 @@ pub struct Filter { /// 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, } -unsafe impl Send for Filter {} -unsafe impl Sync for Filter {} use lightning::chain::Filter as rustFilter; impl rustFilter for Filter { - fn register_tx(&self, txid: &bitcoin::hash_types::Txid, script_pubkey: &bitcoin::blockdata::script::Script) { + fn register_tx(&self, mut txid: &bitcoin::hash_types::Txid, mut script_pubkey: &bitcoin::blockdata::script::Script) { (self.register_tx)(self.this_arg, txid.as_inner(), crate::c_types::u8slice::from_slice(&script_pubkey[..])) } - fn register_output(&self, output: lightning::chain::WatchedOutput) -> Option<(usize, bitcoin::blockdata::transaction::Transaction)> { + fn register_output(&self, mut output: lightning::chain::WatchedOutput) -> Option<(usize, bitcoin::blockdata::transaction::Transaction)> { let mut ret = (self.register_output)(self.this_arg, crate::lightning::chain::WatchedOutput { inner: Box::into_raw(Box::new(output)), is_owned: true }); let mut local_ret = if ret.is_some() { Some( { let (mut orig_ret_0_0, mut orig_ret_0_1) = ret.take().to_rust(); let mut local_ret_0 = (orig_ret_0_0, orig_ret_0_1.into_bitcoin()); local_ret_0 }) } else { None }; local_ret diff --git a/lightning-c-bindings/src/lightning/ln/chan_utils.rs b/lightning-c-bindings/src/lightning/ln/chan_utils.rs index aadf315..529beac 100644 --- a/lightning-c-bindings/src/lightning/ln/chan_utils.rs +++ b/lightning-c-bindings/src/lightning/ln/chan_utils.rs @@ -534,7 +534,7 @@ pub extern "C" fn HTLCOutputInCommitment_get_payment_hash(this_ptr: &HTLCOutputI /// The hash of the preimage which unlocks this HTLC. #[no_mangle] pub extern "C" fn HTLCOutputInCommitment_set_payment_hash(this_ptr: &mut HTLCOutputInCommitment, mut val: crate::c_types::ThirtyTwoBytes) { - unsafe { &mut *this_ptr.inner }.payment_hash = ::lightning::ln::channelmanager::PaymentHash(val.data); + unsafe { &mut *this_ptr.inner }.payment_hash = ::lightning::ln::PaymentHash(val.data); } /// The position within the commitment transactions' outputs. This may be None if the value is /// below the dust limit (in which case no output appears in the commitment transaction and the @@ -562,7 +562,7 @@ pub extern "C" fn HTLCOutputInCommitment_new(mut offered_arg: bool, mut amount_m offered: offered_arg, amount_msat: amount_msat_arg, cltv_expiry: cltv_expiry_arg, - payment_hash: ::lightning::ln::channelmanager::PaymentHash(payment_hash_arg.data), + payment_hash: ::lightning::ln::PaymentHash(payment_hash_arg.data), transaction_output_index: local_transaction_output_index_arg, })), is_owned: true } } @@ -1404,7 +1404,7 @@ pub extern "C" fn CommitmentTransaction_trust(this_arg: &CommitmentTransaction) #[no_mangle] pub extern "C" fn CommitmentTransaction_verify(this_arg: &CommitmentTransaction, channel_parameters: &crate::lightning::ln::chan_utils::DirectedChannelTransactionParameters, broadcaster_keys: &crate::lightning::ln::chan_utils::ChannelPublicKeys, countersignatory_keys: &crate::lightning::ln::chan_utils::ChannelPublicKeys) -> crate::c_types::derived::CResult_TrustedCommitmentTransactionNoneZ { let mut ret = unsafe { &*this_arg.inner }.verify(unsafe { &*channel_parameters.inner }, unsafe { &*broadcaster_keys.inner }, unsafe { &*countersignatory_keys.inner }, secp256k1::SECP256K1); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::TrustedCommitmentTransaction { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }).into() }; + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::TrustedCommitmentTransaction { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } @@ -1490,7 +1490,7 @@ pub extern "C" fn TrustedCommitmentTransaction_keys(this_arg: &TrustedCommitment #[no_mangle] pub extern "C" fn TrustedCommitmentTransaction_get_htlc_sigs(this_arg: &TrustedCommitmentTransaction, htlc_base_key: *const [u8; 32], channel_parameters: &crate::lightning::ln::chan_utils::DirectedChannelTransactionParameters) -> crate::c_types::derived::CResult_CVec_SignatureZNoneZ { let mut ret = unsafe { &*this_arg.inner }.get_htlc_sigs(&::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *htlc_base_key}[..]).unwrap(), unsafe { &*channel_parameters.inner }, secp256k1::SECP256K1); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let mut local_ret_0 = Vec::new(); for mut item in o.drain(..) { local_ret_0.push( { crate::c_types::Signature::from_rust(&item) }); }; local_ret_0.into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }).into() }; + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let mut local_ret_0 = Vec::new(); for mut item in o.drain(..) { local_ret_0.push( { crate::c_types::Signature::from_rust(&item) }); }; local_ret_0.into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } diff --git a/lightning-c-bindings/src/lightning/ln/channelmanager.rs b/lightning-c-bindings/src/lightning/ln/channelmanager.rs index be2a55e..d404b81 100644 --- a/lightning-c-bindings/src/lightning/ln/channelmanager.rs +++ b/lightning-c-bindings/src/lightning/ln/channelmanager.rs @@ -609,7 +609,7 @@ impl PaymentSendFailure { }, nativePaymentSendFailure::PathParameterError (ref a, ) => { let mut a_nonref = (*a).clone(); - let mut local_a_nonref = Vec::new(); for mut item in a_nonref.drain(..) { local_a_nonref.push( { let mut local_a_nonref_0 = match item { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() }; local_a_nonref_0 }); }; + let mut local_a_nonref = Vec::new(); for mut item in a_nonref.drain(..) { local_a_nonref.push( { let mut local_a_nonref_0 = match item { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() }; local_a_nonref_0 }); }; PaymentSendFailure::PathParameterError ( local_a_nonref.into(), ) @@ -623,7 +623,7 @@ impl PaymentSendFailure { }, nativePaymentSendFailure::PartialFailure (ref a, ) => { let mut a_nonref = (*a).clone(); - let mut local_a_nonref = Vec::new(); for mut item in a_nonref.drain(..) { local_a_nonref.push( { let mut local_a_nonref_0 = match item { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() }; local_a_nonref_0 }); }; + let mut local_a_nonref = Vec::new(); for mut item in a_nonref.drain(..) { local_a_nonref.push( { let mut local_a_nonref_0 = match item { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() }; local_a_nonref_0 }); }; PaymentSendFailure::PartialFailure ( local_a_nonref.into(), ) @@ -639,7 +639,7 @@ impl PaymentSendFailure { ) }, nativePaymentSendFailure::PathParameterError (mut a, ) => { - let mut local_a = Vec::new(); for mut item in a.drain(..) { local_a.push( { let mut local_a_0 = match item { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() }; local_a_0 }); }; + let mut local_a = Vec::new(); for mut item in a.drain(..) { local_a.push( { let mut local_a_0 = match item { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() }; local_a_0 }); }; PaymentSendFailure::PathParameterError ( local_a.into(), ) @@ -651,7 +651,7 @@ impl PaymentSendFailure { ) }, nativePaymentSendFailure::PartialFailure (mut a, ) => { - let mut local_a = Vec::new(); for mut item in a.drain(..) { local_a.push( { let mut local_a_0 = match item { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() }; local_a_0 }); }; + let mut local_a = Vec::new(); for mut item in a.drain(..) { local_a.push( { let mut local_a_0 = match item { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() }; local_a_0 }); }; PaymentSendFailure::PartialFailure ( local_a.into(), ) @@ -712,7 +712,7 @@ pub extern "C" fn ChannelManager_get_current_default_configuration(this_arg: &Ch 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 { let mut local_override_config = if override_config.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(override_config.take_inner()) } }) }; let mut ret = unsafe { &*this_arg.inner }.create_channel(their_network_key.into_rust(), channel_value_satoshis, push_msat, user_id, local_override_config); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() }; + 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::lightning::util::errors::APIError::native_into(e) }).into() }; local_ret } @@ -748,7 +748,7 @@ pub extern "C" fn ChannelManager_list_usable_channels(this_arg: &ChannelManager) #[no_mangle] pub extern "C" fn ChannelManager_close_channel(this_arg: &ChannelManager, channel_id: *const [u8; 32]) -> crate::c_types::derived::CResult_NoneAPIErrorZ { let mut ret = unsafe { &*this_arg.inner }.close_channel(unsafe { &*channel_id}); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() }; + 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::lightning::util::errors::APIError::native_into(e) }).into() }; local_ret } @@ -758,7 +758,7 @@ pub extern "C" fn ChannelManager_close_channel(this_arg: &ChannelManager, channe #[no_mangle] pub extern "C" fn ChannelManager_force_close_channel(this_arg: &ChannelManager, channel_id: *const [u8; 32]) -> crate::c_types::derived::CResult_NoneAPIErrorZ { let mut ret = unsafe { &*this_arg.inner }.force_close_channel(unsafe { &*channel_id}); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() }; + 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::lightning::util::errors::APIError::native_into(e) }).into() }; local_ret } @@ -811,9 +811,9 @@ pub extern "C" fn ChannelManager_force_close_all_channels(this_arg: &ChannelMana #[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 { - let mut local_payment_secret = if payment_secret.data == [0; 32] { None } else { Some( { ::lightning::ln::channelmanager::PaymentSecret(payment_secret.data) }) }; - let mut ret = unsafe { &*this_arg.inner }.send_payment(unsafe { &*route.inner }, ::lightning::ln::channelmanager::PaymentHash(payment_hash.data), &local_payment_secret); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::channelmanager::PaymentSendFailure::native_into(e) }).into() }; + let mut local_payment_secret = if payment_secret.data == [0; 32] { None } else { Some( { ::lightning::ln::PaymentSecret(payment_secret.data) }) }; + let mut ret = unsafe { &*this_arg.inner }.send_payment(unsafe { &*route.inner }, ::lightning::ln::PaymentHash(payment_hash.data), &local_payment_secret); + 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::lightning::ln::channelmanager::PaymentSendFailure::native_into(e) }).into() }; local_ret } @@ -839,7 +839,7 @@ pub extern "C" fn ChannelManager_send_payment(this_arg: &ChannelManager, route: #[no_mangle] pub extern "C" fn ChannelManager_funding_transaction_generated(this_arg: &ChannelManager, temporary_channel_id: *const [u8; 32], mut funding_transaction: crate::c_types::Transaction) -> crate::c_types::derived::CResult_NoneAPIErrorZ { let mut ret = unsafe { &*this_arg.inner }.funding_transaction_generated(unsafe { &*temporary_channel_id}, funding_transaction.into_bitcoin()); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() }; + 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::lightning::util::errors::APIError::native_into(e) }).into() }; local_ret } @@ -891,7 +891,7 @@ pub extern "C" fn ChannelManager_timer_tick_occurred(this_arg: &ChannelManager) #[must_use] #[no_mangle] pub extern "C" fn ChannelManager_fail_htlc_backwards(this_arg: &ChannelManager, payment_hash: *const [u8; 32]) -> bool { - let mut ret = unsafe { &*this_arg.inner }.fail_htlc_backwards(&::lightning::ln::channelmanager::PaymentHash(unsafe { *payment_hash })); + let mut ret = unsafe { &*this_arg.inner }.fail_htlc_backwards(&::lightning::ln::PaymentHash(unsafe { *payment_hash })); ret } @@ -911,7 +911,7 @@ pub extern "C" fn ChannelManager_fail_htlc_backwards(this_arg: &ChannelManager, #[must_use] #[no_mangle] pub extern "C" fn ChannelManager_claim_funds(this_arg: &ChannelManager, mut payment_preimage: crate::c_types::ThirtyTwoBytes) -> bool { - let mut ret = unsafe { &*this_arg.inner }.claim_funds(::lightning::ln::channelmanager::PaymentPreimage(payment_preimage.data)); + let mut ret = unsafe { &*this_arg.inner }.claim_funds(::lightning::ln::PaymentPreimage(payment_preimage.data)); ret } @@ -1006,6 +1006,10 @@ pub extern "C" fn ChannelManager_create_inbound_payment(this_arg: &ChannelManage /// If you need exact expiry semantics, you should enforce them upon receipt of /// [`PaymentReceived`]. /// +/// Pending inbound payments are stored in memory and in serialized versions of this +/// [`ChannelManager`]. If potentially unbounded numbers of inbound payments may exist and +/// space is limited, you may wish to rate-limit inbound payment creation. +/// /// May panic if `invoice_expiry_delta_secs` is greater than one year. /// /// Note that invoices generated for inbound payments should have their `min_final_cltv_expiry` @@ -1018,7 +1022,7 @@ pub extern "C" fn ChannelManager_create_inbound_payment(this_arg: &ChannelManage #[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 { let mut local_min_value_msat = if min_value_msat.is_some() { Some( { min_value_msat.take() }) } else { None }; - let mut ret = unsafe { &*this_arg.inner }.create_inbound_payment_for_hash(::lightning::ln::channelmanager::PaymentHash(payment_hash.data), local_min_value_msat, invoice_expiry_delta_secs, user_payment_id); + let mut ret = unsafe { &*this_arg.inner }.create_inbound_payment_for_hash(::lightning::ln::PaymentHash(payment_hash.data), local_min_value_msat, invoice_expiry_delta_secs, user_payment_id); 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::util::errors::APIError::native_into(e) }).into() }; local_ret } diff --git a/lightning-c-bindings/src/lightning/ln/msgs.rs b/lightning-c-bindings/src/lightning/ln/msgs.rs index 9812571..d8906ea 100644 --- a/lightning-c-bindings/src/lightning/ln/msgs.rs +++ b/lightning-c-bindings/src/lightning/ln/msgs.rs @@ -245,16 +245,16 @@ pub extern "C" fn ErrorMessage_get_data(this_ptr: &ErrorMessage) -> crate::c_typ /// or printed to stdout). Otherwise, a well crafted error message may trigger a security /// vulnerability in the terminal emulator or the logging subsystem. #[no_mangle] -pub extern "C" fn ErrorMessage_set_data(this_ptr: &mut ErrorMessage, mut val: crate::c_types::derived::CVec_u8Z) { - unsafe { &mut *this_ptr.inner }.data = String::from_utf8(val.into_rust()).unwrap(); +pub extern "C" fn ErrorMessage_set_data(this_ptr: &mut ErrorMessage, mut val: crate::c_types::Str) { + unsafe { &mut *this_ptr.inner }.data = val.into_string(); } /// Constructs a new ErrorMessage given each field #[must_use] #[no_mangle] -pub extern "C" fn ErrorMessage_new(mut channel_id_arg: crate::c_types::ThirtyTwoBytes, mut data_arg: crate::c_types::derived::CVec_u8Z) -> ErrorMessage { +pub extern "C" fn ErrorMessage_new(mut channel_id_arg: crate::c_types::ThirtyTwoBytes, mut data_arg: crate::c_types::Str) -> ErrorMessage { ErrorMessage { inner: Box::into_raw(Box::new(nativeErrorMessage { channel_id: channel_id_arg.data, - data: String::from_utf8(data_arg.into_rust()).unwrap(), + data: data_arg.into_string(), })), is_owned: true } } impl Clone for ErrorMessage { @@ -1538,7 +1538,7 @@ pub extern "C" fn UpdateAddHTLC_get_payment_hash(this_ptr: &UpdateAddHTLC) -> *c /// The payment hash, the pre-image of which controls HTLC redemption #[no_mangle] pub extern "C" fn UpdateAddHTLC_set_payment_hash(this_ptr: &mut UpdateAddHTLC, mut val: crate::c_types::ThirtyTwoBytes) { - unsafe { &mut *this_ptr.inner }.payment_hash = ::lightning::ln::channelmanager::PaymentHash(val.data); + unsafe { &mut *this_ptr.inner }.payment_hash = ::lightning::ln::PaymentHash(val.data); } /// The expiry height of the HTLC #[no_mangle] @@ -1646,7 +1646,7 @@ pub extern "C" fn UpdateFulfillHTLC_get_payment_preimage(this_ptr: &UpdateFulfil /// The pre-image of the payment hash, allowing HTLC redemption #[no_mangle] pub extern "C" fn UpdateFulfillHTLC_set_payment_preimage(this_ptr: &mut UpdateFulfillHTLC, mut val: crate::c_types::ThirtyTwoBytes) { - unsafe { &mut *this_ptr.inner }.payment_preimage = ::lightning::ln::channelmanager::PaymentPreimage(val.data); + unsafe { &mut *this_ptr.inner }.payment_preimage = ::lightning::ln::PaymentPreimage(val.data); } /// Constructs a new UpdateFulfillHTLC given each field #[must_use] @@ -1655,7 +1655,7 @@ pub extern "C" fn UpdateFulfillHTLC_new(mut channel_id_arg: crate::c_types::Thir UpdateFulfillHTLC { inner: Box::into_raw(Box::new(nativeUpdateFulfillHTLC { channel_id: channel_id_arg.data, htlc_id: htlc_id_arg, - payment_preimage: ::lightning::ln::channelmanager::PaymentPreimage(payment_preimage_arg.data), + payment_preimage: ::lightning::ln::PaymentPreimage(payment_preimage_arg.data), })), is_owned: true } } impl Clone for UpdateFulfillHTLC { @@ -4149,8 +4149,8 @@ pub extern "C" fn LightningError_get_err(this_ptr: &LightningError) -> crate::c_ } /// A human-readable message describing the error #[no_mangle] -pub extern "C" fn LightningError_set_err(this_ptr: &mut LightningError, mut val: crate::c_types::derived::CVec_u8Z) { - unsafe { &mut *this_ptr.inner }.err = String::from_utf8(val.into_rust()).unwrap(); +pub extern "C" fn LightningError_set_err(this_ptr: &mut LightningError, mut val: crate::c_types::Str) { + unsafe { &mut *this_ptr.inner }.err = val.into_string(); } /// The action which should be taken against the offending peer. #[no_mangle] @@ -4166,9 +4166,9 @@ pub extern "C" fn LightningError_set_action(this_ptr: &mut LightningError, mut v /// Constructs a new LightningError given each field #[must_use] #[no_mangle] -pub extern "C" fn LightningError_new(mut err_arg: crate::c_types::derived::CVec_u8Z, mut action_arg: crate::lightning::ln::msgs::ErrorAction) -> LightningError { +pub extern "C" fn LightningError_new(mut err_arg: crate::c_types::Str, mut action_arg: crate::lightning::ln::msgs::ErrorAction) -> LightningError { LightningError { inner: Box::into_raw(Box::new(nativeLightningError { - err: String::from_utf8(err_arg.into_rust()).unwrap(), + err: err_arg.into_string(), action: action_arg.into_native(), })), is_owned: true } } @@ -4526,69 +4526,67 @@ impl lightning::util::events::MessageSendEventsProvider for ChannelMessageHandle local_ret } } -unsafe impl Send for ChannelMessageHandler {} -unsafe impl Sync for ChannelMessageHandler {} use lightning::ln::msgs::ChannelMessageHandler as rustChannelMessageHandler; impl rustChannelMessageHandler for ChannelMessageHandler { - fn handle_open_channel(&self, their_node_id: &bitcoin::secp256k1::key::PublicKey, their_features: lightning::ln::features::InitFeatures, msg: &lightning::ln::msgs::OpenChannel) { + fn handle_open_channel(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut their_features: lightning::ln::features::InitFeatures, mut msg: &lightning::ln::msgs::OpenChannel) { (self.handle_open_channel)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), crate::lightning::ln::features::InitFeatures { inner: Box::into_raw(Box::new(their_features)), is_owned: true }, &crate::lightning::ln::msgs::OpenChannel { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }) } - fn handle_accept_channel(&self, their_node_id: &bitcoin::secp256k1::key::PublicKey, their_features: lightning::ln::features::InitFeatures, msg: &lightning::ln::msgs::AcceptChannel) { + fn handle_accept_channel(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut their_features: lightning::ln::features::InitFeatures, mut msg: &lightning::ln::msgs::AcceptChannel) { (self.handle_accept_channel)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), crate::lightning::ln::features::InitFeatures { inner: Box::into_raw(Box::new(their_features)), is_owned: true }, &crate::lightning::ln::msgs::AcceptChannel { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }) } - fn handle_funding_created(&self, their_node_id: &bitcoin::secp256k1::key::PublicKey, msg: &lightning::ln::msgs::FundingCreated) { + fn handle_funding_created(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: &lightning::ln::msgs::FundingCreated) { (self.handle_funding_created)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::FundingCreated { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }) } - fn handle_funding_signed(&self, their_node_id: &bitcoin::secp256k1::key::PublicKey, msg: &lightning::ln::msgs::FundingSigned) { + fn handle_funding_signed(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: &lightning::ln::msgs::FundingSigned) { (self.handle_funding_signed)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::FundingSigned { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }) } - fn handle_funding_locked(&self, their_node_id: &bitcoin::secp256k1::key::PublicKey, msg: &lightning::ln::msgs::FundingLocked) { + fn handle_funding_locked(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: &lightning::ln::msgs::FundingLocked) { (self.handle_funding_locked)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::FundingLocked { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }) } - fn handle_shutdown(&self, their_node_id: &bitcoin::secp256k1::key::PublicKey, their_features: &lightning::ln::features::InitFeatures, msg: &lightning::ln::msgs::Shutdown) { + fn handle_shutdown(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut their_features: &lightning::ln::features::InitFeatures, mut msg: &lightning::ln::msgs::Shutdown) { (self.handle_shutdown)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::features::InitFeatures { inner: unsafe { (their_features as *const _) as *mut _ }, is_owned: false }, &crate::lightning::ln::msgs::Shutdown { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }) } - fn handle_closing_signed(&self, their_node_id: &bitcoin::secp256k1::key::PublicKey, msg: &lightning::ln::msgs::ClosingSigned) { + fn handle_closing_signed(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: &lightning::ln::msgs::ClosingSigned) { (self.handle_closing_signed)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::ClosingSigned { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }) } - fn handle_update_add_htlc(&self, their_node_id: &bitcoin::secp256k1::key::PublicKey, msg: &lightning::ln::msgs::UpdateAddHTLC) { + fn handle_update_add_htlc(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: &lightning::ln::msgs::UpdateAddHTLC) { (self.handle_update_add_htlc)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::UpdateAddHTLC { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }) } - fn handle_update_fulfill_htlc(&self, their_node_id: &bitcoin::secp256k1::key::PublicKey, msg: &lightning::ln::msgs::UpdateFulfillHTLC) { + fn handle_update_fulfill_htlc(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: &lightning::ln::msgs::UpdateFulfillHTLC) { (self.handle_update_fulfill_htlc)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::UpdateFulfillHTLC { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }) } - fn handle_update_fail_htlc(&self, their_node_id: &bitcoin::secp256k1::key::PublicKey, msg: &lightning::ln::msgs::UpdateFailHTLC) { + fn handle_update_fail_htlc(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: &lightning::ln::msgs::UpdateFailHTLC) { (self.handle_update_fail_htlc)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::UpdateFailHTLC { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }) } - fn handle_update_fail_malformed_htlc(&self, their_node_id: &bitcoin::secp256k1::key::PublicKey, msg: &lightning::ln::msgs::UpdateFailMalformedHTLC) { + fn handle_update_fail_malformed_htlc(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: &lightning::ln::msgs::UpdateFailMalformedHTLC) { (self.handle_update_fail_malformed_htlc)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::UpdateFailMalformedHTLC { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }) } - fn handle_commitment_signed(&self, their_node_id: &bitcoin::secp256k1::key::PublicKey, msg: &lightning::ln::msgs::CommitmentSigned) { + fn handle_commitment_signed(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: &lightning::ln::msgs::CommitmentSigned) { (self.handle_commitment_signed)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::CommitmentSigned { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }) } - fn handle_revoke_and_ack(&self, their_node_id: &bitcoin::secp256k1::key::PublicKey, msg: &lightning::ln::msgs::RevokeAndACK) { + fn handle_revoke_and_ack(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: &lightning::ln::msgs::RevokeAndACK) { (self.handle_revoke_and_ack)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::RevokeAndACK { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }) } - fn handle_update_fee(&self, their_node_id: &bitcoin::secp256k1::key::PublicKey, msg: &lightning::ln::msgs::UpdateFee) { + fn handle_update_fee(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: &lightning::ln::msgs::UpdateFee) { (self.handle_update_fee)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::UpdateFee { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }) } - fn handle_announcement_signatures(&self, their_node_id: &bitcoin::secp256k1::key::PublicKey, msg: &lightning::ln::msgs::AnnouncementSignatures) { + fn handle_announcement_signatures(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: &lightning::ln::msgs::AnnouncementSignatures) { (self.handle_announcement_signatures)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::AnnouncementSignatures { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }) } - fn peer_disconnected(&self, their_node_id: &bitcoin::secp256k1::key::PublicKey, no_connection_possible: bool) { + fn peer_disconnected(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut no_connection_possible: bool) { (self.peer_disconnected)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), no_connection_possible) } - fn peer_connected(&self, their_node_id: &bitcoin::secp256k1::key::PublicKey, msg: &lightning::ln::msgs::Init) { + fn peer_connected(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: &lightning::ln::msgs::Init) { (self.peer_connected)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::Init { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }) } - fn handle_channel_reestablish(&self, their_node_id: &bitcoin::secp256k1::key::PublicKey, msg: &lightning::ln::msgs::ChannelReestablish) { + fn handle_channel_reestablish(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: &lightning::ln::msgs::ChannelReestablish) { (self.handle_channel_reestablish)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::ChannelReestablish { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }) } - fn handle_channel_update(&self, their_node_id: &bitcoin::secp256k1::key::PublicKey, msg: &lightning::ln::msgs::ChannelUpdate) { + fn handle_channel_update(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: &lightning::ln::msgs::ChannelUpdate) { (self.handle_channel_update)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::ChannelUpdate { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }) } - fn handle_error(&self, their_node_id: &bitcoin::secp256k1::key::PublicKey, msg: &lightning::ln::msgs::ErrorMessage) { + fn handle_error(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: &lightning::ln::msgs::ErrorMessage) { (self.handle_error)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::ErrorMessage { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }) } } @@ -4677,8 +4675,6 @@ pub struct RoutingMessageHandler { /// 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, } -unsafe impl Send for RoutingMessageHandler {} -unsafe impl Sync for RoutingMessageHandler {} impl lightning::util::events::MessageSendEventsProvider for RoutingMessageHandler { fn get_and_clear_pending_msg_events(&self) -> Vec { let mut ret = (self.MessageSendEventsProvider.get_and_clear_pending_msg_events)(self.this_arg); @@ -4689,54 +4685,54 @@ impl lightning::util::events::MessageSendEventsProvider for RoutingMessageHandle use lightning::ln::msgs::RoutingMessageHandler as rustRoutingMessageHandler; impl rustRoutingMessageHandler for RoutingMessageHandler { - fn handle_node_announcement(&self, msg: &lightning::ln::msgs::NodeAnnouncement) -> Result { + fn handle_node_announcement(&self, mut msg: &lightning::ln::msgs::NodeAnnouncement) -> Result { let mut ret = (self.handle_node_announcement)(self.this_arg, &crate::lightning::ln::msgs::NodeAnnouncement { 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)) }) }), false => Err( { *unsafe { Box::from_raw((*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).take_inner()) } })}; local_ret } - fn handle_channel_announcement(&self, msg: &lightning::ln::msgs::ChannelAnnouncement) -> Result { + fn handle_channel_announcement(&self, mut msg: &lightning::ln::msgs::ChannelAnnouncement) -> Result { let mut ret = (self.handle_channel_announcement)(self.this_arg, &crate::lightning::ln::msgs::ChannelAnnouncement { 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)) }) }), false => Err( { *unsafe { Box::from_raw((*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).take_inner()) } })}; local_ret } - fn handle_channel_update(&self, msg: &lightning::ln::msgs::ChannelUpdate) -> Result { + fn handle_channel_update(&self, mut msg: &lightning::ln::msgs::ChannelUpdate) -> Result { let mut ret = (self.handle_channel_update)(self.this_arg, &crate::lightning::ln::msgs::ChannelUpdate { 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)) }) }), false => Err( { *unsafe { Box::from_raw((*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).take_inner()) } })}; local_ret } - fn handle_htlc_fail_channel_update(&self, update: &lightning::ln::msgs::HTLCFailChannelUpdate) { + fn handle_htlc_fail_channel_update(&self, mut update: &lightning::ln::msgs::HTLCFailChannelUpdate) { (self.handle_htlc_fail_channel_update)(self.this_arg, &crate::lightning::ln::msgs::HTLCFailChannelUpdate::from_native(update)) } - fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(lightning::ln::msgs::ChannelAnnouncement, Option, Option)> { + fn get_next_channel_announcements(&self, mut starting_point: u64, mut batch_amount: u8) -> Vec<(lightning::ln::msgs::ChannelAnnouncement, Option, Option)> { let mut ret = (self.get_next_channel_announcements)(self.this_arg, starting_point, batch_amount); let mut local_ret = Vec::new(); for mut item in ret.into_rust().drain(..) { local_ret.push( { let (mut orig_ret_0_0, mut orig_ret_0_1, mut orig_ret_0_2) = item.to_rust(); let mut local_orig_ret_0_1 = if orig_ret_0_1.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(orig_ret_0_1.take_inner()) } }) }; let mut local_orig_ret_0_2 = if orig_ret_0_2.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(orig_ret_0_2.take_inner()) } }) }; let mut local_ret_0 = (*unsafe { Box::from_raw(orig_ret_0_0.take_inner()) }, local_orig_ret_0_1, local_orig_ret_0_2); local_ret_0 }); }; local_ret } - fn get_next_node_announcements(&self, starting_point: Option<&bitcoin::secp256k1::key::PublicKey>, batch_amount: u8) -> Vec { + fn get_next_node_announcements(&self, mut starting_point: Option<&bitcoin::secp256k1::key::PublicKey>, mut batch_amount: u8) -> Vec { let mut local_starting_point = if starting_point.is_none() { crate::c_types::PublicKey::null() } else { { crate::c_types::PublicKey::from_rust(&(starting_point.unwrap())) } }; let mut ret = (self.get_next_node_announcements)(self.this_arg, local_starting_point, batch_amount); let mut local_ret = Vec::new(); for mut item in ret.into_rust().drain(..) { local_ret.push( { *unsafe { Box::from_raw(item.take_inner()) } }); }; local_ret } - fn sync_routing_table(&self, their_node_id: &bitcoin::secp256k1::key::PublicKey, init: &lightning::ln::msgs::Init) { + fn sync_routing_table(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut init: &lightning::ln::msgs::Init) { (self.sync_routing_table)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::Init { inner: unsafe { (init as *const _) as *mut _ }, is_owned: false }) } - fn handle_reply_channel_range(&self, their_node_id: &bitcoin::secp256k1::key::PublicKey, msg: lightning::ln::msgs::ReplyChannelRange) -> Result<(), lightning::ln::msgs::LightningError> { + fn handle_reply_channel_range(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: lightning::ln::msgs::ReplyChannelRange) -> Result<(), lightning::ln::msgs::LightningError> { let mut ret = (self.handle_reply_channel_range)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), crate::lightning::ln::msgs::ReplyChannelRange { inner: Box::into_raw(Box::new(msg)), is_owned: true }); let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { *unsafe { Box::from_raw((*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).take_inner()) } })}; local_ret } - fn handle_reply_short_channel_ids_end(&self, their_node_id: &bitcoin::secp256k1::key::PublicKey, msg: lightning::ln::msgs::ReplyShortChannelIdsEnd) -> Result<(), lightning::ln::msgs::LightningError> { + fn handle_reply_short_channel_ids_end(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: lightning::ln::msgs::ReplyShortChannelIdsEnd) -> Result<(), lightning::ln::msgs::LightningError> { let mut ret = (self.handle_reply_short_channel_ids_end)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), crate::lightning::ln::msgs::ReplyShortChannelIdsEnd { inner: Box::into_raw(Box::new(msg)), is_owned: true }); let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { *unsafe { Box::from_raw((*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).take_inner()) } })}; local_ret } - fn handle_query_channel_range(&self, their_node_id: &bitcoin::secp256k1::key::PublicKey, msg: lightning::ln::msgs::QueryChannelRange) -> Result<(), lightning::ln::msgs::LightningError> { + fn handle_query_channel_range(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: lightning::ln::msgs::QueryChannelRange) -> Result<(), lightning::ln::msgs::LightningError> { let mut ret = (self.handle_query_channel_range)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), crate::lightning::ln::msgs::QueryChannelRange { inner: Box::into_raw(Box::new(msg)), is_owned: true }); let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { *unsafe { Box::from_raw((*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).take_inner()) } })}; local_ret } - fn handle_query_short_channel_ids(&self, their_node_id: &bitcoin::secp256k1::key::PublicKey, msg: lightning::ln::msgs::QueryShortChannelIds) -> Result<(), lightning::ln::msgs::LightningError> { + fn handle_query_short_channel_ids(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: lightning::ln::msgs::QueryShortChannelIds) -> Result<(), lightning::ln::msgs::LightningError> { let mut ret = (self.handle_query_short_channel_ids)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), crate::lightning::ln::msgs::QueryShortChannelIds { inner: Box::into_raw(Box::new(msg)), is_owned: true }); let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { *unsafe { Box::from_raw((*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).take_inner()) } })}; local_ret diff --git a/lightning-c-bindings/src/lightning/ln/peer_handler.rs b/lightning-c-bindings/src/lightning/ln/peer_handler.rs index 42be858..b832b1f 100644 --- a/lightning-c-bindings/src/lightning/ln/peer_handler.rs +++ b/lightning-c-bindings/src/lightning/ln/peer_handler.rs @@ -176,25 +176,25 @@ extern "C" fn IgnoringMessageHandler_RoutingMessageHandler_sync_routing_table(th #[must_use] extern "C" fn IgnoringMessageHandler_RoutingMessageHandler_handle_reply_channel_range(this_arg: *const c_void, mut _their_node_id: crate::c_types::PublicKey, mut _msg: crate::lightning::ln::msgs::ReplyChannelRange) -> crate::c_types::derived::CResult_NoneLightningErrorZ { let mut ret = >::handle_reply_channel_range(unsafe { &mut *(this_arg as *mut nativeIgnoringMessageHandler) }, &_their_node_id.into_rust(), *unsafe { Box::from_raw(_msg.take_inner()) }); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).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() }; + 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::lightning::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() }; local_ret } #[must_use] extern "C" fn IgnoringMessageHandler_RoutingMessageHandler_handle_reply_short_channel_ids_end(this_arg: *const c_void, mut _their_node_id: crate::c_types::PublicKey, mut _msg: crate::lightning::ln::msgs::ReplyShortChannelIdsEnd) -> crate::c_types::derived::CResult_NoneLightningErrorZ { let mut ret = >::handle_reply_short_channel_ids_end(unsafe { &mut *(this_arg as *mut nativeIgnoringMessageHandler) }, &_their_node_id.into_rust(), *unsafe { Box::from_raw(_msg.take_inner()) }); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).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() }; + 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::lightning::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() }; local_ret } #[must_use] extern "C" fn IgnoringMessageHandler_RoutingMessageHandler_handle_query_channel_range(this_arg: *const c_void, mut _their_node_id: crate::c_types::PublicKey, mut _msg: crate::lightning::ln::msgs::QueryChannelRange) -> crate::c_types::derived::CResult_NoneLightningErrorZ { let mut ret = >::handle_query_channel_range(unsafe { &mut *(this_arg as *mut nativeIgnoringMessageHandler) }, &_their_node_id.into_rust(), *unsafe { Box::from_raw(_msg.take_inner()) }); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).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() }; + 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::lightning::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() }; local_ret } #[must_use] extern "C" fn IgnoringMessageHandler_RoutingMessageHandler_handle_query_short_channel_ids(this_arg: *const c_void, mut _their_node_id: crate::c_types::PublicKey, mut _msg: crate::lightning::ln::msgs::QueryShortChannelIds) -> crate::c_types::derived::CResult_NoneLightningErrorZ { let mut ret = >::handle_query_short_channel_ids(unsafe { &mut *(this_arg as *mut nativeIgnoringMessageHandler) }, &_their_node_id.into_rust(), *unsafe { Box::from_raw(_msg.take_inner()) }); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).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() }; + 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::lightning::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() }; local_ret } @@ -545,7 +545,7 @@ impl Clone for SocketDescriptor { use lightning::ln::peer_handler::SocketDescriptor as rustSocketDescriptor; impl rustSocketDescriptor for SocketDescriptor { - fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize { + fn send_data(&mut self, mut data: &[u8], mut resume_read: bool) -> usize { let mut local_data = crate::c_types::u8slice::from_slice(data); let mut ret = (self.send_data)(self.this_arg, local_data, resume_read); ret @@ -764,7 +764,7 @@ pub extern "C" fn PeerManager_new_outbound_connection(this_arg: &PeerManager, mu #[no_mangle] pub extern "C" fn PeerManager_new_inbound_connection(this_arg: &PeerManager, mut descriptor: crate::lightning::ln::peer_handler::SocketDescriptor) -> crate::c_types::derived::CResult_NonePeerHandleErrorZ { let mut ret = unsafe { &*this_arg.inner }.new_inbound_connection(descriptor); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::peer_handler::PeerHandleError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() }; + 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::lightning::ln::peer_handler::PeerHandleError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() }; local_ret } @@ -782,7 +782,7 @@ pub extern "C" fn PeerManager_new_inbound_connection(this_arg: &PeerManager, mut #[no_mangle] pub extern "C" fn PeerManager_write_buffer_space_avail(this_arg: &PeerManager, descriptor: &mut crate::lightning::ln::peer_handler::SocketDescriptor) -> crate::c_types::derived::CResult_NonePeerHandleErrorZ { let mut ret = unsafe { &*this_arg.inner }.write_buffer_space_avail(descriptor); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::peer_handler::PeerHandleError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() }; + 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::lightning::ln::peer_handler::PeerHandleError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() }; local_ret } diff --git a/lightning-c-bindings/src/lightning/routing/network_graph.rs b/lightning-c-bindings/src/lightning/routing/network_graph.rs index 9f35e43..0d50980 100644 --- a/lightning-c-bindings/src/lightning/routing/network_graph.rs +++ b/lightning-c-bindings/src/lightning/routing/network_graph.rs @@ -300,25 +300,25 @@ extern "C" fn NetGraphMsgHandler_RoutingMessageHandler_sync_routing_table(this_a #[must_use] extern "C" fn NetGraphMsgHandler_RoutingMessageHandler_handle_reply_channel_range(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, mut msg: crate::lightning::ln::msgs::ReplyChannelRange) -> crate::c_types::derived::CResult_NoneLightningErrorZ { let mut ret = >::handle_reply_channel_range(unsafe { &mut *(this_arg as *mut nativeNetGraphMsgHandler) }, &their_node_id.into_rust(), *unsafe { Box::from_raw(msg.take_inner()) }); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).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() }; + 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::lightning::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() }; local_ret } #[must_use] extern "C" fn NetGraphMsgHandler_RoutingMessageHandler_handle_reply_short_channel_ids_end(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, mut msg: crate::lightning::ln::msgs::ReplyShortChannelIdsEnd) -> crate::c_types::derived::CResult_NoneLightningErrorZ { let mut ret = >::handle_reply_short_channel_ids_end(unsafe { &mut *(this_arg as *mut nativeNetGraphMsgHandler) }, &their_node_id.into_rust(), *unsafe { Box::from_raw(msg.take_inner()) }); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).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() }; + 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::lightning::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() }; local_ret } #[must_use] extern "C" fn NetGraphMsgHandler_RoutingMessageHandler_handle_query_channel_range(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, mut msg: crate::lightning::ln::msgs::QueryChannelRange) -> crate::c_types::derived::CResult_NoneLightningErrorZ { let mut ret = >::handle_query_channel_range(unsafe { &mut *(this_arg as *mut nativeNetGraphMsgHandler) }, &their_node_id.into_rust(), *unsafe { Box::from_raw(msg.take_inner()) }); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).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() }; + 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::lightning::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() }; local_ret } #[must_use] extern "C" fn NetGraphMsgHandler_RoutingMessageHandler_handle_query_short_channel_ids(this_arg: *const c_void, mut _their_node_id: crate::c_types::PublicKey, mut _msg: crate::lightning::ln::msgs::QueryShortChannelIds) -> crate::c_types::derived::CResult_NoneLightningErrorZ { let mut ret = >::handle_query_short_channel_ids(unsafe { &mut *(this_arg as *mut nativeNetGraphMsgHandler) }, &_their_node_id.into_rust(), *unsafe { Box::from_raw(_msg.take_inner()) }); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).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() }; + 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::lightning::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() }; local_ret } @@ -1176,7 +1176,7 @@ pub extern "C" fn NetworkGraph_new(mut genesis_hash: crate::c_types::ThirtyTwoBy #[no_mangle] pub extern "C" fn NetworkGraph_update_node_from_announcement(this_arg: &mut NetworkGraph, msg: &crate::lightning::ln::msgs::NodeAnnouncement) -> crate::c_types::derived::CResult_NoneLightningErrorZ { let mut ret = unsafe { &mut (*(this_arg.inner as *mut nativeNetworkGraph)) }.update_node_from_announcement(unsafe { &*msg.inner }, secp256k1::SECP256K1); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).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() }; + 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::lightning::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() }; local_ret } @@ -1188,7 +1188,7 @@ pub extern "C" fn NetworkGraph_update_node_from_announcement(this_arg: &mut Netw #[no_mangle] pub extern "C" fn NetworkGraph_update_node_from_unsigned_announcement(this_arg: &mut NetworkGraph, msg: &crate::lightning::ln::msgs::UnsignedNodeAnnouncement) -> crate::c_types::derived::CResult_NoneLightningErrorZ { let mut ret = unsafe { &mut (*(this_arg.inner as *mut nativeNetworkGraph)) }.update_node_from_unsigned_announcement(unsafe { &*msg.inner }); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).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() }; + 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::lightning::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() }; local_ret } @@ -1205,7 +1205,7 @@ pub extern "C" fn NetworkGraph_update_node_from_unsigned_announcement(this_arg: 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 { let mut local_chain_access = if chain_access == std::ptr::null_mut() { None } else { Some( { unsafe { *Box::from_raw(chain_access) } }) }; let mut ret = unsafe { &mut (*(this_arg.inner as *mut nativeNetworkGraph)) }.update_channel_from_announcement(unsafe { &*msg.inner }, &local_chain_access, secp256k1::SECP256K1); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).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() }; + 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::lightning::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() }; local_ret } @@ -1220,7 +1220,7 @@ pub extern "C" fn NetworkGraph_update_channel_from_announcement(this_arg: &mut N 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 { let mut local_chain_access = if chain_access == std::ptr::null_mut() { None } else { Some( { unsafe { *Box::from_raw(chain_access) } }) }; let mut ret = unsafe { &mut (*(this_arg.inner as *mut nativeNetworkGraph)) }.update_channel_from_unsigned_announcement(unsafe { &*msg.inner }, &local_chain_access); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).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() }; + 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::lightning::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() }; local_ret } @@ -1243,7 +1243,7 @@ pub extern "C" fn NetworkGraph_close_channel_from_update(this_arg: &mut NetworkG #[no_mangle] pub extern "C" fn NetworkGraph_update_channel(this_arg: &mut NetworkGraph, msg: &crate::lightning::ln::msgs::ChannelUpdate) -> crate::c_types::derived::CResult_NoneLightningErrorZ { let mut ret = unsafe { &mut (*(this_arg.inner as *mut nativeNetworkGraph)) }.update_channel(unsafe { &*msg.inner }, secp256k1::SECP256K1); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).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() }; + 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::lightning::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() }; local_ret } @@ -1254,7 +1254,7 @@ pub extern "C" fn NetworkGraph_update_channel(this_arg: &mut NetworkGraph, msg: #[no_mangle] pub extern "C" fn NetworkGraph_update_channel_unsigned(this_arg: &mut NetworkGraph, msg: &crate::lightning::ln::msgs::UnsignedChannelUpdate) -> crate::c_types::derived::CResult_NoneLightningErrorZ { let mut ret = unsafe { &mut (*(this_arg.inner as *mut nativeNetworkGraph)) }.update_channel_unsigned(unsafe { &*msg.inner }); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).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() }; + 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::lightning::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() }; local_ret } diff --git a/lightning-c-bindings/src/lightning/util/errors.rs b/lightning-c-bindings/src/lightning/util/errors.rs index ce9fc14..81faa98 100644 --- a/lightning-c-bindings/src/lightning/util/errors.rs +++ b/lightning-c-bindings/src/lightning/util/errors.rs @@ -23,14 +23,14 @@ pub enum APIError { /// are documented, but generally indicates some precondition of a function was violated. APIMisuseError { /// A human-readable error message - err: crate::c_types::derived::CVec_u8Z, + err: crate::c_types::Str, }, /// Due to a high feerate, we were unable to complete the request. /// For example, this may be returned if the feerate implies we cannot open a channel at the /// requested value, but opening a larger channel would succeed. FeeRateTooHigh { /// A human-readable error message - err: crate::c_types::derived::CVec_u8Z, + err: crate::c_types::Str, /// The feerate which was too high. feerate: u32, }, @@ -45,7 +45,7 @@ pub enum APIError { /// peer, channel at capacity, channel shutting down, etc. ChannelUnavailable { /// A human-readable error message - err: crate::c_types::derived::CVec_u8Z, + err: crate::c_types::Str, }, /// An attempt to call watch/update_channel returned an Err (ie you did this!), causing the /// attempted action to fail. @@ -59,27 +59,27 @@ impl APIError { APIError::APIMisuseError {ref err, } => { let mut err_nonref = (*err).clone(); nativeAPIError::APIMisuseError { - err: String::from_utf8(err_nonref.into_rust()).unwrap(), + err: err_nonref.into_string(), } }, APIError::FeeRateTooHigh {ref err, ref feerate, } => { let mut err_nonref = (*err).clone(); let mut feerate_nonref = (*feerate).clone(); nativeAPIError::FeeRateTooHigh { - err: String::from_utf8(err_nonref.into_rust()).unwrap(), + err: err_nonref.into_string(), feerate: feerate_nonref, } }, APIError::RouteError {ref err, } => { let mut err_nonref = (*err).clone(); nativeAPIError::RouteError { - err: err_nonref.into(), + err: err_nonref.into_str(), } }, APIError::ChannelUnavailable {ref err, } => { let mut err_nonref = (*err).clone(); nativeAPIError::ChannelUnavailable { - err: String::from_utf8(err_nonref.into_rust()).unwrap(), + err: err_nonref.into_string(), } }, APIError::MonitorUpdateFailed => nativeAPIError::MonitorUpdateFailed, @@ -90,23 +90,23 @@ impl APIError { match self { APIError::APIMisuseError {mut err, } => { nativeAPIError::APIMisuseError { - err: String::from_utf8(err.into_rust()).unwrap(), + err: err.into_string(), } }, APIError::FeeRateTooHigh {mut err, mut feerate, } => { nativeAPIError::FeeRateTooHigh { - err: String::from_utf8(err.into_rust()).unwrap(), + err: err.into_string(), feerate: feerate, } }, APIError::RouteError {mut err, } => { nativeAPIError::RouteError { - err: err.into(), + err: err.into_str(), } }, APIError::ChannelUnavailable {mut err, } => { nativeAPIError::ChannelUnavailable { - err: String::from_utf8(err.into_rust()).unwrap(), + err: err.into_string(), } }, APIError::MonitorUpdateFailed => nativeAPIError::MonitorUpdateFailed, @@ -118,14 +118,14 @@ impl APIError { nativeAPIError::APIMisuseError {ref err, } => { let mut err_nonref = (*err).clone(); APIError::APIMisuseError { - err: err_nonref.into_bytes().into(), + err: err_nonref.into(), } }, nativeAPIError::FeeRateTooHigh {ref err, ref feerate, } => { let mut err_nonref = (*err).clone(); let mut feerate_nonref = (*feerate).clone(); APIError::FeeRateTooHigh { - err: err_nonref.into_bytes().into(), + err: err_nonref.into(), feerate: feerate_nonref, } }, @@ -138,7 +138,7 @@ impl APIError { nativeAPIError::ChannelUnavailable {ref err, } => { let mut err_nonref = (*err).clone(); APIError::ChannelUnavailable { - err: err_nonref.into_bytes().into(), + err: err_nonref.into(), } }, nativeAPIError::MonitorUpdateFailed => APIError::MonitorUpdateFailed, @@ -149,12 +149,12 @@ impl APIError { match native { nativeAPIError::APIMisuseError {mut err, } => { APIError::APIMisuseError { - err: err.into_bytes().into(), + err: err.into(), } }, nativeAPIError::FeeRateTooHigh {mut err, mut feerate, } => { APIError::FeeRateTooHigh { - err: err.into_bytes().into(), + err: err.into(), feerate: feerate, } }, @@ -165,7 +165,7 @@ impl APIError { }, nativeAPIError::ChannelUnavailable {mut err, } => { APIError::ChannelUnavailable { - err: err.into_bytes().into(), + err: err.into(), } }, nativeAPIError::MonitorUpdateFailed => APIError::MonitorUpdateFailed, diff --git a/lightning-c-bindings/src/lightning/util/events.rs b/lightning-c-bindings/src/lightning/util/events.rs index 4dcbd81..43c4db3 100644 --- a/lightning-c-bindings/src/lightning/util/events.rs +++ b/lightning-c-bindings/src/lightning/util/events.rs @@ -148,14 +148,14 @@ impl Event { Event::PaymentReceived {ref payment_hash, ref payment_preimage, ref payment_secret, ref amt, ref user_payment_id, } => { 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::channelmanager::PaymentPreimage(payment_preimage_nonref.data) }) }; + 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(); nativeEvent::PaymentReceived { - payment_hash: ::lightning::ln::channelmanager::PaymentHash(payment_hash_nonref.data), + payment_hash: ::lightning::ln::PaymentHash(payment_hash_nonref.data), payment_preimage: local_payment_preimage_nonref, - payment_secret: ::lightning::ln::channelmanager::PaymentSecret(payment_secret_nonref.data), + payment_secret: ::lightning::ln::PaymentSecret(payment_secret_nonref.data), amt: amt_nonref, user_payment_id: user_payment_id_nonref, } @@ -163,14 +163,14 @@ impl Event { Event::PaymentSent {ref payment_preimage, } => { let mut payment_preimage_nonref = (*payment_preimage).clone(); nativeEvent::PaymentSent { - payment_preimage: ::lightning::ln::channelmanager::PaymentPreimage(payment_preimage_nonref.data), + payment_preimage: ::lightning::ln::PaymentPreimage(payment_preimage_nonref.data), } }, Event::PaymentFailed {ref payment_hash, ref rejected_by_dest, } => { let mut payment_hash_nonref = (*payment_hash).clone(); let mut rejected_by_dest_nonref = (*rejected_by_dest).clone(); nativeEvent::PaymentFailed { - payment_hash: ::lightning::ln::channelmanager::PaymentHash(payment_hash_nonref.data), + payment_hash: ::lightning::ln::PaymentHash(payment_hash_nonref.data), rejected_by_dest: rejected_by_dest_nonref, } }, @@ -201,23 +201,23 @@ impl Event { } }, 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::channelmanager::PaymentPreimage(payment_preimage.data) }) }; + let mut local_payment_preimage = if payment_preimage.data == [0; 32] { None } else { Some( { ::lightning::ln::PaymentPreimage(payment_preimage.data) }) }; nativeEvent::PaymentReceived { - payment_hash: ::lightning::ln::channelmanager::PaymentHash(payment_hash.data), + payment_hash: ::lightning::ln::PaymentHash(payment_hash.data), payment_preimage: local_payment_preimage, - payment_secret: ::lightning::ln::channelmanager::PaymentSecret(payment_secret.data), + payment_secret: ::lightning::ln::PaymentSecret(payment_secret.data), amt: amt, user_payment_id: user_payment_id, } }, Event::PaymentSent {mut payment_preimage, } => { nativeEvent::PaymentSent { - payment_preimage: ::lightning::ln::channelmanager::PaymentPreimage(payment_preimage.data), + payment_preimage: ::lightning::ln::PaymentPreimage(payment_preimage.data), } }, Event::PaymentFailed {mut payment_hash, mut rejected_by_dest, } => { nativeEvent::PaymentFailed { - payment_hash: ::lightning::ln::channelmanager::PaymentHash(payment_hash.data), + payment_hash: ::lightning::ln::PaymentHash(payment_hash.data), rejected_by_dest: rejected_by_dest, } }, diff --git a/lightning-c-bindings/src/lightning/util/logger.rs b/lightning-c-bindings/src/lightning/util/logger.rs index b38fac0..0373245 100644 --- a/lightning-c-bindings/src/lightning/util/logger.rs +++ b/lightning-c-bindings/src/lightning/util/logger.rs @@ -108,12 +108,10 @@ pub struct Logger { /// 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, } -unsafe impl Sync for Logger {} -unsafe impl Send for Logger {} use lightning::util::logger::Logger as rustLogger; impl rustLogger for Logger { - fn log(&self, record: &lightning::util::logger::Record) { + fn log(&self, mut record: &lightning::util::logger::Record) { let mut local_record = std::ffi::CString::new(format!("{}", record.args)).unwrap(); (self.log)(self.this_arg, local_record.as_ptr()) } diff --git a/lightning-c-bindings/src/lightning/util/message_signing.rs b/lightning-c-bindings/src/lightning/util/message_signing.rs index 1c48e36..6aa95f5 100644 --- a/lightning-c-bindings/src/lightning/util/message_signing.rs +++ b/lightning-c-bindings/src/lightning/util/message_signing.rs @@ -33,14 +33,14 @@ use crate::c_types::*; #[no_mangle] pub extern "C" fn sign(mut msg: crate::c_types::u8slice, mut sk: crate::c_types::SecretKey) -> crate::c_types::derived::CResult_StringErrorZ { let mut ret = lightning::util::message_signing::sign(msg.to_slice(), sk.into_rust()); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { o.into_bytes().into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::Secp256k1Error::from_rust(e) }).into() }; + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { o.into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::Secp256k1Error::from_rust(e) }).into() }; local_ret } /// Recovers the PublicKey of the signer of the message given the message and the signature. #[no_mangle] pub extern "C" fn recover_pk(mut msg: crate::c_types::u8slice, mut sig: crate::c_types::Str) -> crate::c_types::derived::CResult_PublicKeyErrorZ { - let mut ret = lightning::util::message_signing::recover_pk(msg.to_slice(), sig.into()); + let mut ret = lightning::util::message_signing::recover_pk(msg.to_slice(), sig.into_str()); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::PublicKey::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::Secp256k1Error::from_rust(e) }).into() }; local_ret } @@ -49,7 +49,7 @@ pub extern "C" fn recover_pk(mut msg: crate::c_types::u8slice, mut sig: crate::c /// and the PublicKey. #[no_mangle] pub extern "C" fn verify(mut msg: crate::c_types::u8slice, mut sig: crate::c_types::Str, mut pk: crate::c_types::PublicKey) -> bool { - let mut ret = lightning::util::message_signing::verify(msg.to_slice(), sig.into(), pk.into_rust()); + let mut ret = lightning::util::message_signing::verify(msg.to_slice(), sig.into_str(), pk.into_rust()); ret } diff --git a/lightning-c-bindings/src/lightning_invoice/mod.rs b/lightning-c-bindings/src/lightning_invoice/mod.rs index a12e906..51f058b 100644 --- a/lightning-c-bindings/src/lightning_invoice/mod.rs +++ b/lightning-c-bindings/src/lightning_invoice/mod.rs @@ -20,6 +20,7 @@ use std::ffi::c_void; use bitcoin::hashes::Hash; use crate::c_types::*; +pub mod utils; pub mod constants; mod de { @@ -35,6 +36,42 @@ use std::ffi::c_void; use bitcoin::hashes::Hash; use crate::c_types::*; +} +#[no_mangle] +/// Read a SiPrefix object from a string +pub extern "C" fn SiPrefix_from_str(s: crate::c_types::Str) -> crate::c_types::derived::CResult_SiPrefixNoneZ { + match lightning_invoice::SiPrefix::from_str(s.into_str()) { + Ok(r) => { + crate::c_types::CResultTempl::ok( + crate::lightning_invoice::SiPrefix::native_into(r) + ) + }, + Err(e) => crate::c_types::CResultTempl::err(()), + }.into() +} +#[no_mangle] +/// Read a Invoice object from a string +pub extern "C" fn Invoice_from_str(s: crate::c_types::Str) -> crate::c_types::derived::CResult_InvoiceNoneZ { + match lightning_invoice::Invoice::from_str(s.into_str()) { + Ok(r) => { + crate::c_types::CResultTempl::ok( + crate::lightning_invoice::Invoice { inner: Box::into_raw(Box::new(r)), is_owned: true } + ) + }, + Err(e) => crate::c_types::CResultTempl::err(()), + }.into() +} +#[no_mangle] +/// Read a SignedRawInvoice object from a string +pub extern "C" fn SignedRawInvoice_from_str(s: crate::c_types::Str) -> crate::c_types::derived::CResult_SignedRawInvoiceNoneZ { + match lightning_invoice::SignedRawInvoice::from_str(s.into_str()) { + Ok(r) => { + crate::c_types::CResultTempl::ok( + crate::lightning_invoice::SignedRawInvoice { inner: Box::into_raw(Box::new(r)), is_owned: true } + ) + }, + Err(e) => crate::c_types::CResultTempl::err(()), + }.into() } } mod ser { @@ -44,6 +81,26 @@ use std::ffi::c_void; use bitcoin::hashes::Hash; use crate::c_types::*; +#[no_mangle] +/// Get the string representation of a Invoice object +pub extern "C" fn Invoice_to_str(o: &crate::lightning_invoice::Invoice) -> Str { + format!("{}", unsafe { &*o.inner }).into() +} +#[no_mangle] +/// Get the string representation of a SignedRawInvoice object +pub extern "C" fn SignedRawInvoice_to_str(o: &crate::lightning_invoice::SignedRawInvoice) -> Str { + format!("{}", unsafe { &*o.inner }).into() +} +#[no_mangle] +/// Get the string representation of a Currency object +pub extern "C" fn Currency_to_str(o: &crate::lightning_invoice::Currency) -> Str { + format!("{}", &o.to_native()).into() +} +#[no_mangle] +/// Get the string representation of a SiPrefix object +pub extern "C" fn SiPrefix_to_str(o: &crate::lightning_invoice::SiPrefix) -> Str { + format!("{}", &o.to_native()).into() +} } mod tb { @@ -343,22 +400,6 @@ pub extern "C" fn RawDataPart_get_timestamp(this_ptr: &RawDataPart) -> crate::li pub extern "C" fn RawDataPart_set_timestamp(this_ptr: &mut RawDataPart, mut val: crate::lightning_invoice::PositiveTimestamp) { unsafe { &mut *this_ptr.inner }.timestamp = *unsafe { Box::from_raw(val.take_inner()) }; } -/// tagged fields of the payment request -#[no_mangle] -pub extern "C" fn RawDataPart_set_tagged_fields(this_ptr: &mut RawDataPart, mut val: crate::c_types::derived::CVec_RawTaggedFieldZ) { - let mut local_val = Vec::new(); for mut item in val.into_rust().drain(..) { local_val.push( { item.into_native() }); }; - unsafe { &mut *this_ptr.inner }.tagged_fields = local_val; -} -/// Constructs a new RawDataPart given each field -#[must_use] -#[no_mangle] -pub extern "C" fn RawDataPart_new(mut timestamp_arg: crate::lightning_invoice::PositiveTimestamp, mut tagged_fields_arg: crate::c_types::derived::CVec_RawTaggedFieldZ) -> RawDataPart { - let mut local_tagged_fields_arg = Vec::new(); for mut item in tagged_fields_arg.into_rust().drain(..) { local_tagged_fields_arg.push( { item.into_native() }); }; - RawDataPart { inner: Box::into_raw(Box::new(nativeRawDataPart { - timestamp: *unsafe { Box::from_raw(timestamp_arg.take_inner()) }, - tagged_fields: local_tagged_fields_arg, - })), is_owned: true } -} impl Clone for RawDataPart { fn clone(&self) -> Self { Self { @@ -572,364 +613,6 @@ impl Currency { pub extern "C" fn Currency_clone(orig: &Currency) -> Currency { orig.clone() } -/// Tagged field which may have an unknown tag -#[must_use] -#[derive(Clone)] -#[repr(C)] -pub enum RawTaggedField { - /// Parsed tagged field with known tag - KnownSemantics(crate::lightning_invoice::TaggedField), - /// tagged field which was not parsed due to an unknown tag or undefined field semantics - UnknownSemantics(crate::c_types::derived::CVec_u5Z), -} -use lightning_invoice::RawTaggedField as nativeRawTaggedField; -impl RawTaggedField { - #[allow(unused)] - pub(crate) fn to_native(&self) -> nativeRawTaggedField { - match self { - RawTaggedField::KnownSemantics (ref a, ) => { - let mut a_nonref = (*a).clone(); - nativeRawTaggedField::KnownSemantics ( - a_nonref.into_native(), - ) - }, - RawTaggedField::UnknownSemantics (ref a, ) => { - let mut a_nonref = (*a).clone(); - let mut local_a_nonref = Vec::new(); for mut item in a_nonref.into_rust().drain(..) { local_a_nonref.push( { item.into() }); }; - nativeRawTaggedField::UnknownSemantics ( - local_a_nonref, - ) - }, - } - } - #[allow(unused)] - pub(crate) fn into_native(self) -> nativeRawTaggedField { - match self { - RawTaggedField::KnownSemantics (mut a, ) => { - nativeRawTaggedField::KnownSemantics ( - a.into_native(), - ) - }, - RawTaggedField::UnknownSemantics (mut a, ) => { - let mut local_a = Vec::new(); for mut item in a.into_rust().drain(..) { local_a.push( { item.into() }); }; - nativeRawTaggedField::UnknownSemantics ( - local_a, - ) - }, - } - } - #[allow(unused)] - pub(crate) fn from_native(native: &nativeRawTaggedField) -> Self { - match native { - nativeRawTaggedField::KnownSemantics (ref a, ) => { - let mut a_nonref = (*a).clone(); - RawTaggedField::KnownSemantics ( - crate::lightning_invoice::TaggedField::native_into(a_nonref), - ) - }, - nativeRawTaggedField::UnknownSemantics (ref a, ) => { - let mut a_nonref = (*a).clone(); - let mut local_a_nonref = Vec::new(); for mut item in a_nonref.drain(..) { local_a_nonref.push( { item.into() }); }; - RawTaggedField::UnknownSemantics ( - local_a_nonref.into(), - ) - }, - } - } - #[allow(unused)] - pub(crate) fn native_into(native: nativeRawTaggedField) -> Self { - match native { - nativeRawTaggedField::KnownSemantics (mut a, ) => { - RawTaggedField::KnownSemantics ( - crate::lightning_invoice::TaggedField::native_into(a), - ) - }, - nativeRawTaggedField::UnknownSemantics (mut a, ) => { - let mut local_a = Vec::new(); for mut item in a.drain(..) { local_a.push( { item.into() }); }; - RawTaggedField::UnknownSemantics ( - local_a.into(), - ) - }, - } - } -} -/// Frees any resources used by the RawTaggedField -#[no_mangle] -pub extern "C" fn RawTaggedField_free(this_ptr: RawTaggedField) { } -/// Creates a copy of the RawTaggedField -#[no_mangle] -pub extern "C" fn RawTaggedField_clone(orig: &RawTaggedField) -> RawTaggedField { - orig.clone() -} -/// Tagged field with known tag -/// -/// For descriptions of the enum values please refer to the enclosed type's docs. -#[must_use] -#[derive(Clone)] -#[repr(C)] -pub enum TaggedField { - PaymentHash(crate::lightning_invoice::Sha256), - Description(crate::lightning_invoice::Description), - PayeePubKey(crate::lightning_invoice::PayeePubKey), - DescriptionHash(crate::lightning_invoice::Sha256), - ExpiryTime(crate::lightning_invoice::ExpiryTime), - MinFinalCltvExpiry(crate::lightning_invoice::MinFinalCltvExpiry), - Fallback(crate::lightning_invoice::Fallback), - Route(crate::lightning_invoice::RouteHint), - PaymentSecret(crate::lightning_invoice::PaymentSecret), - Features(crate::lightning::ln::features::InvoiceFeatures), -} -use lightning_invoice::TaggedField as nativeTaggedField; -impl TaggedField { - #[allow(unused)] - pub(crate) fn to_native(&self) -> nativeTaggedField { - match self { - TaggedField::PaymentHash (ref a, ) => { - let mut a_nonref = (*a).clone(); - nativeTaggedField::PaymentHash ( - *unsafe { Box::from_raw(a_nonref.take_inner()) }, - ) - }, - TaggedField::Description (ref a, ) => { - let mut a_nonref = (*a).clone(); - nativeTaggedField::Description ( - *unsafe { Box::from_raw(a_nonref.take_inner()) }, - ) - }, - TaggedField::PayeePubKey (ref a, ) => { - let mut a_nonref = (*a).clone(); - nativeTaggedField::PayeePubKey ( - *unsafe { Box::from_raw(a_nonref.take_inner()) }, - ) - }, - TaggedField::DescriptionHash (ref a, ) => { - let mut a_nonref = (*a).clone(); - nativeTaggedField::DescriptionHash ( - *unsafe { Box::from_raw(a_nonref.take_inner()) }, - ) - }, - TaggedField::ExpiryTime (ref a, ) => { - let mut a_nonref = (*a).clone(); - nativeTaggedField::ExpiryTime ( - *unsafe { Box::from_raw(a_nonref.take_inner()) }, - ) - }, - TaggedField::MinFinalCltvExpiry (ref a, ) => { - let mut a_nonref = (*a).clone(); - nativeTaggedField::MinFinalCltvExpiry ( - *unsafe { Box::from_raw(a_nonref.take_inner()) }, - ) - }, - TaggedField::Fallback (ref a, ) => { - let mut a_nonref = (*a).clone(); - nativeTaggedField::Fallback ( - a_nonref.into_native(), - ) - }, - TaggedField::Route (ref a, ) => { - let mut a_nonref = (*a).clone(); - nativeTaggedField::Route ( - *unsafe { Box::from_raw(a_nonref.take_inner()) }, - ) - }, - TaggedField::PaymentSecret (ref a, ) => { - let mut a_nonref = (*a).clone(); - nativeTaggedField::PaymentSecret ( - *unsafe { Box::from_raw(a_nonref.take_inner()) }, - ) - }, - TaggedField::Features (ref a, ) => { - let mut a_nonref = (*a).clone(); - nativeTaggedField::Features ( - *unsafe { Box::from_raw(a_nonref.take_inner()) }, - ) - }, - } - } - #[allow(unused)] - pub(crate) fn into_native(self) -> nativeTaggedField { - match self { - TaggedField::PaymentHash (mut a, ) => { - nativeTaggedField::PaymentHash ( - *unsafe { Box::from_raw(a.take_inner()) }, - ) - }, - TaggedField::Description (mut a, ) => { - nativeTaggedField::Description ( - *unsafe { Box::from_raw(a.take_inner()) }, - ) - }, - TaggedField::PayeePubKey (mut a, ) => { - nativeTaggedField::PayeePubKey ( - *unsafe { Box::from_raw(a.take_inner()) }, - ) - }, - TaggedField::DescriptionHash (mut a, ) => { - nativeTaggedField::DescriptionHash ( - *unsafe { Box::from_raw(a.take_inner()) }, - ) - }, - TaggedField::ExpiryTime (mut a, ) => { - nativeTaggedField::ExpiryTime ( - *unsafe { Box::from_raw(a.take_inner()) }, - ) - }, - TaggedField::MinFinalCltvExpiry (mut a, ) => { - nativeTaggedField::MinFinalCltvExpiry ( - *unsafe { Box::from_raw(a.take_inner()) }, - ) - }, - TaggedField::Fallback (mut a, ) => { - nativeTaggedField::Fallback ( - a.into_native(), - ) - }, - TaggedField::Route (mut a, ) => { - nativeTaggedField::Route ( - *unsafe { Box::from_raw(a.take_inner()) }, - ) - }, - TaggedField::PaymentSecret (mut a, ) => { - nativeTaggedField::PaymentSecret ( - *unsafe { Box::from_raw(a.take_inner()) }, - ) - }, - TaggedField::Features (mut a, ) => { - nativeTaggedField::Features ( - *unsafe { Box::from_raw(a.take_inner()) }, - ) - }, - } - } - #[allow(unused)] - pub(crate) fn from_native(native: &nativeTaggedField) -> Self { - match native { - nativeTaggedField::PaymentHash (ref a, ) => { - let mut a_nonref = (*a).clone(); - TaggedField::PaymentHash ( - crate::lightning_invoice::Sha256 { inner: Box::into_raw(Box::new(a_nonref)), is_owned: true }, - ) - }, - nativeTaggedField::Description (ref a, ) => { - let mut a_nonref = (*a).clone(); - TaggedField::Description ( - crate::lightning_invoice::Description { inner: Box::into_raw(Box::new(a_nonref)), is_owned: true }, - ) - }, - nativeTaggedField::PayeePubKey (ref a, ) => { - let mut a_nonref = (*a).clone(); - TaggedField::PayeePubKey ( - crate::lightning_invoice::PayeePubKey { inner: Box::into_raw(Box::new(a_nonref)), is_owned: true }, - ) - }, - nativeTaggedField::DescriptionHash (ref a, ) => { - let mut a_nonref = (*a).clone(); - TaggedField::DescriptionHash ( - crate::lightning_invoice::Sha256 { inner: Box::into_raw(Box::new(a_nonref)), is_owned: true }, - ) - }, - nativeTaggedField::ExpiryTime (ref a, ) => { - let mut a_nonref = (*a).clone(); - TaggedField::ExpiryTime ( - crate::lightning_invoice::ExpiryTime { inner: Box::into_raw(Box::new(a_nonref)), is_owned: true }, - ) - }, - nativeTaggedField::MinFinalCltvExpiry (ref a, ) => { - let mut a_nonref = (*a).clone(); - TaggedField::MinFinalCltvExpiry ( - crate::lightning_invoice::MinFinalCltvExpiry { inner: Box::into_raw(Box::new(a_nonref)), is_owned: true }, - ) - }, - nativeTaggedField::Fallback (ref a, ) => { - let mut a_nonref = (*a).clone(); - TaggedField::Fallback ( - crate::lightning_invoice::Fallback::native_into(a_nonref), - ) - }, - nativeTaggedField::Route (ref a, ) => { - let mut a_nonref = (*a).clone(); - TaggedField::Route ( - crate::lightning_invoice::RouteHint { inner: Box::into_raw(Box::new(a_nonref)), is_owned: true }, - ) - }, - nativeTaggedField::PaymentSecret (ref a, ) => { - let mut a_nonref = (*a).clone(); - TaggedField::PaymentSecret ( - crate::lightning_invoice::PaymentSecret { inner: Box::into_raw(Box::new(a_nonref)), is_owned: true }, - ) - }, - nativeTaggedField::Features (ref a, ) => { - let mut a_nonref = (*a).clone(); - TaggedField::Features ( - crate::lightning::ln::features::InvoiceFeatures { inner: Box::into_raw(Box::new(a_nonref)), is_owned: true }, - ) - }, - } - } - #[allow(unused)] - pub(crate) fn native_into(native: nativeTaggedField) -> Self { - match native { - nativeTaggedField::PaymentHash (mut a, ) => { - TaggedField::PaymentHash ( - crate::lightning_invoice::Sha256 { inner: Box::into_raw(Box::new(a)), is_owned: true }, - ) - }, - nativeTaggedField::Description (mut a, ) => { - TaggedField::Description ( - crate::lightning_invoice::Description { inner: Box::into_raw(Box::new(a)), is_owned: true }, - ) - }, - nativeTaggedField::PayeePubKey (mut a, ) => { - TaggedField::PayeePubKey ( - crate::lightning_invoice::PayeePubKey { inner: Box::into_raw(Box::new(a)), is_owned: true }, - ) - }, - nativeTaggedField::DescriptionHash (mut a, ) => { - TaggedField::DescriptionHash ( - crate::lightning_invoice::Sha256 { inner: Box::into_raw(Box::new(a)), is_owned: true }, - ) - }, - nativeTaggedField::ExpiryTime (mut a, ) => { - TaggedField::ExpiryTime ( - crate::lightning_invoice::ExpiryTime { inner: Box::into_raw(Box::new(a)), is_owned: true }, - ) - }, - nativeTaggedField::MinFinalCltvExpiry (mut a, ) => { - TaggedField::MinFinalCltvExpiry ( - crate::lightning_invoice::MinFinalCltvExpiry { inner: Box::into_raw(Box::new(a)), is_owned: true }, - ) - }, - nativeTaggedField::Fallback (mut a, ) => { - TaggedField::Fallback ( - crate::lightning_invoice::Fallback::native_into(a), - ) - }, - nativeTaggedField::Route (mut a, ) => { - TaggedField::Route ( - crate::lightning_invoice::RouteHint { inner: Box::into_raw(Box::new(a)), is_owned: true }, - ) - }, - nativeTaggedField::PaymentSecret (mut a, ) => { - TaggedField::PaymentSecret ( - crate::lightning_invoice::PaymentSecret { inner: Box::into_raw(Box::new(a)), is_owned: true }, - ) - }, - nativeTaggedField::Features (mut a, ) => { - TaggedField::Features ( - crate::lightning::ln::features::InvoiceFeatures { inner: Box::into_raw(Box::new(a)), is_owned: true }, - ) - }, - } - } -} -/// Frees any resources used by the TaggedField -#[no_mangle] -pub extern "C" fn TaggedField_free(this_ptr: TaggedField) { } -/// Creates a copy of the TaggedField -#[no_mangle] -pub extern "C" fn TaggedField_clone(orig: &TaggedField) -> TaggedField { - orig.clone() -} use lightning_invoice::Sha256 as nativeSha256Import; type nativeSha256 = nativeSha256Import; @@ -1126,70 +809,6 @@ pub extern "C" fn PayeePubKey_clone(orig: &PayeePubKey) -> PayeePubKey { orig.clone() } -use lightning_invoice::PaymentSecret as nativePaymentSecretImport; -type nativePaymentSecret = nativePaymentSecretImport; - -/// 256-bit payment secret -#[must_use] -#[repr(C)] -pub struct PaymentSecret { - /// A pointer to the opaque Rust object. - - /// Nearly everywhere, inner must be non-null, however in places where - /// the Rust equivalent takes an Option, it may be set to null to indicate None. - pub inner: *mut nativePaymentSecret, - /// Indicates that this is the only struct which contains the same pointer. - - /// Rust functions which take ownership of an object provided via an argument require - /// this to be true and invalidate the object pointed to by inner. - pub is_owned: bool, -} - -impl Drop for PaymentSecret { - fn drop(&mut self) { - if self.is_owned && !<*mut nativePaymentSecret>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; - } - } -} -/// Frees any resources used by the PaymentSecret, if is_owned is set and inner is non-NULL. -#[no_mangle] -pub extern "C" fn PaymentSecret_free(this_obj: PaymentSecret) { } -#[allow(unused)] -/// Used only if an object of this type is returned as a trait impl by a method -extern "C" fn PaymentSecret_free_void(this_ptr: *mut c_void) { - unsafe { let _ = Box::from_raw(this_ptr as *mut nativePaymentSecret); } -} -#[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy -impl PaymentSecret { - pub(crate) fn take_inner(mut self) -> *mut nativePaymentSecret { - assert!(self.is_owned); - let ret = self.inner; - self.inner = std::ptr::null_mut(); - ret - } -} -impl Clone for PaymentSecret { - fn clone(&self) -> Self { - Self { - inner: if <*mut nativePaymentSecret>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, - is_owned: true, - } - } -} -#[allow(unused)] -/// Used only if an object of this type is returned as a trait impl by a method -pub(crate) extern "C" fn PaymentSecret_clone_void(this_ptr: *const c_void) -> *mut c_void { - Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativePaymentSecret)).clone() })) as *mut c_void -} -#[no_mangle] -/// Creates a copy of the PaymentSecret -pub extern "C" fn PaymentSecret_clone(orig: &PaymentSecret) -> PaymentSecret { - orig.clone() -} - use lightning_invoice::ExpiryTime as nativeExpiryTimeImport; type nativeExpiryTime = nativeExpiryTimeImport; @@ -1686,9 +1305,9 @@ pub extern "C" fn RawInvoice_min_final_cltv_expiry(this_arg: &RawInvoice) -> cra #[must_use] #[no_mangle] -pub extern "C" fn RawInvoice_payment_secret(this_arg: &RawInvoice) -> crate::lightning_invoice::PaymentSecret { +pub extern "C" fn RawInvoice_payment_secret(this_arg: &RawInvoice) -> crate::c_types::ThirtyTwoBytes { let mut ret = unsafe { &*this_arg.inner }.payment_secret(); - let mut local_ret = crate::lightning_invoice::PaymentSecret { inner: unsafe { (if ret.is_none() { std::ptr::null() } else { { (ret.as_ref().unwrap()) } } as *const _) as *mut _ }, is_owned: false }; + let mut local_ret = if ret.is_none() { crate::c_types::ThirtyTwoBytes::null() } else { { crate::c_types::ThirtyTwoBytes { data: (ret.unwrap()).0 } } }; local_ret } @@ -1774,7 +1393,7 @@ pub extern "C" fn Invoice_into_signed_raw(mut this_arg: Invoice) -> crate::light #[no_mangle] pub extern "C" fn Invoice_check_signature(this_arg: &Invoice) -> crate::c_types::derived::CResult_NoneSemanticErrorZ { let mut ret = unsafe { &*this_arg.inner }.check_signature(); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::SemanticError::native_into(e) }).into() }; + 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::lightning_invoice::SemanticError::native_into(e) }).into() }; local_ret } @@ -1827,9 +1446,9 @@ 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 #[must_use] #[no_mangle] -pub extern "C" fn Invoice_payment_secret(this_arg: &Invoice) -> crate::lightning_invoice::PaymentSecret { +pub extern "C" fn Invoice_payment_secret(this_arg: &Invoice) -> crate::c_types::ThirtyTwoBytes { let mut ret = unsafe { &*this_arg.inner }.payment_secret(); - let mut local_ret = crate::lightning_invoice::PaymentSecret { inner: unsafe { (if ret.is_none() { std::ptr::null() } else { { (ret.as_ref().unwrap()) } } as *const _) as *mut _ }, is_owned: false }; + let mut local_ret = if ret.is_none() { crate::c_types::ThirtyTwoBytes::null() } else { { crate::c_types::ThirtyTwoBytes { data: (ret.unwrap()).0 } } }; local_ret } @@ -1850,7 +1469,7 @@ pub extern "C" fn Invoice_recover_payee_pub_key(this_arg: &Invoice) -> crate::c_ crate::c_types::PublicKey::from_rust(&ret) } -/// Returns the invoice's expiry time if present +/// Returns the invoice's expiry time, if present, otherwise [`DEFAULT_EXPIRY_TIME`]. #[must_use] #[no_mangle] pub extern "C" fn Invoice_expiry_time(this_arg: &Invoice) -> u64 { @@ -1858,13 +1477,13 @@ pub extern "C" fn Invoice_expiry_time(this_arg: &Invoice) -> u64 { ret.as_secs() } -/// Returns the invoice's `min_cltv_expiry` time if present +/// Returns the invoice's `min_final_cltv_expiry` time, if present, otherwise +/// [`DEFAULT_MIN_FINAL_CLTV_EXPIRY`]. #[must_use] #[no_mangle] -pub extern "C" fn Invoice_min_final_cltv_expiry(this_arg: &Invoice) -> crate::c_types::derived::COption_u64Z { +pub extern "C" fn Invoice_min_final_cltv_expiry(this_arg: &Invoice) -> u64 { let mut ret = unsafe { &*this_arg.inner }.min_final_cltv_expiry(); - let mut local_ret = if ret.is_none() { crate::c_types::derived::COption_u64Z::None } else { { crate::c_types::derived::COption_u64Z::Some(ret.unwrap()) } }; - local_ret + ret } /// Returns a list of all routes included in the invoice @@ -1893,22 +1512,14 @@ pub extern "C" fn Invoice_amount_pico_btc(this_arg: &Invoice) -> crate::c_types: local_ret } -/// Numeric representation of the field's tag -#[must_use] -#[no_mangle] -pub extern "C" fn TaggedField_tag(this_arg: &TaggedField) -> crate::c_types::u5 { - let mut ret = this_arg.to_native().tag(); - ret.into() -} - /// Creates a new `Description` if `description` is at most 1023 __bytes__ long, /// returns `CreationError::DescriptionTooLong` otherwise /// /// Please note that single characters may use more than one byte due to UTF8 encoding. #[must_use] #[no_mangle] -pub extern "C" fn Description_new(mut description: crate::c_types::derived::CVec_u8Z) -> crate::c_types::derived::CResult_DescriptionCreationErrorZ { - let mut ret = lightning_invoice::Description::new(String::from_utf8(description.into_rust()).unwrap()); +pub extern "C" fn Description_new(mut description: crate::c_types::Str) -> crate::c_types::derived::CResult_DescriptionCreationErrorZ { + let mut ret = lightning_invoice::Description::new(description.into_string()); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::Description { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::CreationError::native_into(e) }).into() }; local_ret } @@ -1916,9 +1527,9 @@ pub extern "C" fn Description_new(mut description: crate::c_types::derived::CVec /// Returns the underlying description `String` #[must_use] #[no_mangle] -pub extern "C" fn Description_into_inner(mut this_arg: Description) -> crate::c_types::derived::CVec_u8Z { +pub extern "C" fn Description_into_inner(mut this_arg: Description) -> crate::c_types::Str { let mut ret = (*unsafe { Box::from_raw(this_arg.take_inner()) }).into_inner(); - ret.into_bytes().into() + ret.into() } /// Construct an `ExpiryTime` from seconds. If there exists a `PositiveTimestamp` which would @@ -2038,8 +1649,8 @@ pub extern "C" fn CreationError_clone(orig: &CreationError) -> CreationError { } #[no_mangle] /// Get the string representation of a CreationError object -pub extern "C" fn CreationError_to_str(o: &lightning_invoice::CreationError) -> Str { - format!("{}", o).into() +pub extern "C" fn CreationError_to_str(o: &crate::lightning_invoice::CreationError) -> Str { + format!("{}", &o.to_native()).into() } /// Errors that may occur when converting a `RawInvoice` to an `Invoice`. They relate to the /// requirements sections in BOLT #11 @@ -2114,6 +1725,89 @@ pub extern "C" fn SemanticError_clone(orig: &SemanticError) -> SemanticError { } #[no_mangle] /// Get the string representation of a SemanticError object -pub extern "C" fn SemanticError_to_str(o: &lightning_invoice::SemanticError) -> Str { - format!("{}", o).into() +pub extern "C" fn SemanticError_to_str(o: &crate::lightning_invoice::SemanticError) -> Str { + format!("{}", &o.to_native()).into() +} +/// When signing using a fallible method either an user-supplied `SignError` or a `CreationError` +/// may occur. +#[must_use] +#[derive(Clone)] +#[repr(C)] +pub enum SignOrCreationError { + /// An error occurred during signing + SignError, + /// An error occurred while building the transaction + CreationError(crate::lightning_invoice::CreationError), +} +use lightning_invoice::SignOrCreationError as nativeSignOrCreationError; +impl SignOrCreationError { + #[allow(unused)] + pub(crate) fn to_native(&self) -> nativeSignOrCreationError { + match self { + SignOrCreationError::SignError => { + nativeSignOrCreationError::SignError ( + () /*a_nonref*/, + ) + }, + SignOrCreationError::CreationError (ref a, ) => { + let mut a_nonref = (*a).clone(); + nativeSignOrCreationError::CreationError ( + a_nonref.into_native(), + ) + }, + } + } + #[allow(unused)] + pub(crate) fn into_native(self) -> nativeSignOrCreationError { + match self { + SignOrCreationError::SignError => { + nativeSignOrCreationError::SignError ( + () /*a*/, + ) + }, + SignOrCreationError::CreationError (mut a, ) => { + nativeSignOrCreationError::CreationError ( + a.into_native(), + ) + }, + } + } + #[allow(unused)] + pub(crate) fn from_native(native: &nativeSignOrCreationError) -> Self { + match native { + nativeSignOrCreationError::SignError (ref a, ) => { + SignOrCreationError::SignError }, + nativeSignOrCreationError::CreationError (ref a, ) => { + let mut a_nonref = (*a).clone(); + SignOrCreationError::CreationError ( + crate::lightning_invoice::CreationError::native_into(a_nonref), + ) + }, + } + } + #[allow(unused)] + pub(crate) fn native_into(native: nativeSignOrCreationError) -> Self { + match native { + nativeSignOrCreationError::SignError (mut a, ) => { + SignOrCreationError::SignError }, + nativeSignOrCreationError::CreationError (mut a, ) => { + SignOrCreationError::CreationError ( + crate::lightning_invoice::CreationError::native_into(a), + ) + }, + } + } +} +/// Frees any resources used by the SignOrCreationError +#[no_mangle] +pub extern "C" fn SignOrCreationError_free(this_ptr: SignOrCreationError) { } +/// Creates a copy of the SignOrCreationError +#[no_mangle] +pub extern "C" fn SignOrCreationError_clone(orig: &SignOrCreationError) -> SignOrCreationError { + orig.clone() +} +#[no_mangle] +/// Get the string representation of a SignOrCreationError object +pub extern "C" fn SignOrCreationError_to_str(o: &crate::lightning_invoice::SignOrCreationError) -> Str { + format!("{}", &o.to_native()).into() } diff --git a/lightning-c-bindings/src/lightning_invoice/utils.rs b/lightning-c-bindings/src/lightning_invoice/utils.rs new file mode 100644 index 0000000..6a1fa6c --- /dev/null +++ b/lightning-c-bindings/src/lightning_invoice/utils.rs @@ -0,0 +1,28 @@ +// This file is Copyright its original authors, visible in version control +// history and in the source files from which this was generated. +// +// This file is licensed under the license available in the LICENSE or LICENSE.md +// file in the root of this repository or, if no such file exists, the same +// license as that which applies to the original source files from which this +// source was automatically generated. + +//! Convenient utilities to create an invoice. + +use std::str::FromStr; +use std::ffi::c_void; +use bitcoin::hashes::Hash; +use crate::c_types::*; + +/// Utility to construct an invoice. Generally, unless you want to do something like a custom +/// cltv_expiry, this is what you should be using to create an invoice. The reason being, this +/// method stores the invoice's payment secret and preimage in `ChannelManager`, so (a) the user +/// doesn't have to store preimage/payment secret information and (b) `ChannelManager` can verify +/// that the payment secret is valid when the invoice is paid. +#[no_mangle] +pub extern "C" fn create_invoice_from_channelmanager(channelmanager: &crate::lightning::ln::channelmanager::ChannelManager, mut keys_manager: crate::lightning::chain::keysinterface::KeysInterface, mut network: crate::lightning_invoice::Currency, mut amt_msat: crate::c_types::derived::COption_u64Z, mut description: crate::c_types::Str) -> crate::c_types::derived::CResult_InvoiceSignOrCreationErrorZ { + let mut local_amt_msat = if amt_msat.is_some() { Some( { amt_msat.take() }) } else { None }; + let mut ret = lightning_invoice::utils::create_invoice_from_channelmanager(unsafe { &*channelmanager.inner }, keys_manager, network.into_native(), local_amt_msat, description.into_string()); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::Invoice { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::SignOrCreationError::native_into(e) }).into() }; + local_ret +} + diff --git a/lightning-c-bindings/src/lightning_persister.rs b/lightning-c-bindings/src/lightning_persister.rs index 1976839..8c4c3fa 100644 --- a/lightning-c-bindings/src/lightning_persister.rs +++ b/lightning-c-bindings/src/lightning_persister.rs @@ -81,26 +81,26 @@ impl FilesystemPersister { /// files. #[must_use] #[no_mangle] -pub extern "C" fn FilesystemPersister_new(mut path_to_channel_data: crate::c_types::derived::CVec_u8Z) -> FilesystemPersister { - let mut ret = lightning_persister::FilesystemPersister::new(String::from_utf8(path_to_channel_data.into_rust()).unwrap()); +pub extern "C" fn FilesystemPersister_new(mut path_to_channel_data: crate::c_types::Str) -> FilesystemPersister { + let mut ret = lightning_persister::FilesystemPersister::new(path_to_channel_data.into_string()); FilesystemPersister { inner: Box::into_raw(Box::new(ret)), is_owned: true } } /// Get the directory which was provided when this persister was initialized. #[must_use] #[no_mangle] -pub extern "C" fn FilesystemPersister_get_data_dir(this_arg: &FilesystemPersister) -> crate::c_types::derived::CVec_u8Z { +pub extern "C" fn FilesystemPersister_get_data_dir(this_arg: &FilesystemPersister) -> crate::c_types::Str { let mut ret = unsafe { &*this_arg.inner }.get_data_dir(); - ret.into_bytes().into() + ret.into() } /// Writes the provided `ChannelManager` to the path provided at `FilesystemPersister` /// initialization, within a file called \"manager\". #[must_use] #[no_mangle] -pub extern "C" fn FilesystemPersister_persist_manager(mut data_dir: crate::c_types::derived::CVec_u8Z, manager: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::c_types::derived::CResult_NoneErrorZ { - let mut ret = lightning_persister::FilesystemPersister::persist_manager(String::from_utf8(data_dir.into_rust()).unwrap(), unsafe { &*manager.inner }); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::IOError::from_rust(e) }).into() }; +pub extern "C" fn FilesystemPersister_persist_manager(mut data_dir: crate::c_types::Str, manager: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::c_types::derived::CResult_NoneErrorZ { + let mut ret = lightning_persister::FilesystemPersister::persist_manager(data_dir.into_string(), unsafe { &*manager.inner }); + 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 } @@ -138,13 +138,13 @@ pub extern "C" fn FilesystemPersister_as_Persist(this_arg: &FilesystemPersister) #[must_use] extern "C" fn FilesystemPersister_Persist_persist_new_channel(this_arg: *const c_void, mut funding_txo: crate::lightning::chain::transaction::OutPoint, monitor: &crate::lightning::chain::channelmonitor::ChannelMonitor) -> crate::c_types::derived::CResult_NoneChannelMonitorUpdateErrZ { let mut ret = >::persist_new_channel(unsafe { &mut *(this_arg as *mut nativeFilesystemPersister) }, *unsafe { Box::from_raw(funding_txo.take_inner()) }, unsafe { &*monitor.inner }); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::chain::channelmonitor::ChannelMonitorUpdateErr::native_into(e) }).into() }; + 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::lightning::chain::channelmonitor::ChannelMonitorUpdateErr::native_into(e) }).into() }; local_ret } #[must_use] extern "C" fn FilesystemPersister_Persist_update_persisted_channel(this_arg: *const c_void, mut funding_txo: crate::lightning::chain::transaction::OutPoint, _update: &crate::lightning::chain::channelmonitor::ChannelMonitorUpdate, monitor: &crate::lightning::chain::channelmonitor::ChannelMonitor) -> crate::c_types::derived::CResult_NoneChannelMonitorUpdateErrZ { let mut ret = >::update_persisted_channel(unsafe { &mut *(this_arg as *mut nativeFilesystemPersister) }, *unsafe { Box::from_raw(funding_txo.take_inner()) }, unsafe { &*_update.inner }, unsafe { &*monitor.inner }); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::chain::channelmonitor::ChannelMonitorUpdateErr::native_into(e) }).into() }; + 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::lightning::chain::channelmonitor::ChannelMonitorUpdateErr::native_into(e) }).into() }; local_ret }