├── c-bindings-gen ├── .gitignore ├── Cargo.toml └── README.md ├── deterministic-build-wrappers ├── compiler-builtins-dummy │ ├── src │ │ └── lib.rs │ └── Cargo.toml ├── clang-x86_64-windows ├── clang-lto-link-osx └── rustc ├── lightning-c-bindings ├── src │ ├── bitcoin │ │ ├── mod.rs │ │ └── network.rs │ ├── lightning │ │ ├── io.rs │ │ ├── util │ │ │ ├── indexed_map.rs │ │ │ ├── string.rs │ │ │ ├── ser_macros.rs │ │ │ ├── hash_tables.rs │ │ │ ├── message_signing.rs │ │ │ ├── mod.rs │ │ │ ├── scid_utils.rs │ │ │ ├── wakers.rs │ │ │ └── errors.rs │ │ ├── routing │ │ │ └── mod.rs │ │ ├── onion_message │ │ │ └── mod.rs │ │ ├── offers │ │ │ ├── mod.rs │ │ │ ├── nonce.rs │ │ │ └── merkle.rs │ │ ├── ln │ │ │ ├── bolt11_payment.rs │ │ │ ├── onion_payment.rs │ │ │ ├── inbound_payment.rs │ │ │ ├── wire.rs │ │ │ ├── types.rs │ │ │ └── mod.rs │ │ ├── mod.rs │ │ └── chain │ │ │ └── transaction.rs │ ├── lightning_types │ │ ├── payment.rs │ │ ├── mod.rs │ │ └── string.rs │ ├── lightning_persister │ │ ├── mod.rs │ │ └── fs_store.rs │ ├── lib.rs │ ├── lightning_invoice │ │ └── constants.rs │ └── lightning_background_processor.rs ├── .gitignore ├── valgrind-suppressions.txt ├── cbindgen.toml ├── Cargo.toml ├── demo.c └── README.md ├── LICENSE.md ├── LICENSE-MIT ├── ldk-net └── ldk_net.h ├── .github └── workflows │ └── build.yml └── LICENSE-APACHE /c-bindings-gen/.gitignore: -------------------------------------------------------------------------------- 1 | Cargo.lock 2 | target 3 | -------------------------------------------------------------------------------- /deterministic-build-wrappers/compiler-builtins-dummy/src/lib.rs: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /lightning-c-bindings/src/bitcoin/mod.rs: -------------------------------------------------------------------------------- 1 | //! C-mapped versions of items from rust-bitcoin 2 | 3 | pub mod network; 4 | -------------------------------------------------------------------------------- /lightning-c-bindings/.gitignore: -------------------------------------------------------------------------------- 1 | Cargo.lock 2 | a.out 3 | a.out.* 4 | include/ldk_ver.h 5 | ldk_net.o 6 | src/version.rs 7 | target 8 | -------------------------------------------------------------------------------- /deterministic-build-wrappers/clang-x86_64-windows: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | clang -fembed-bitcode -fuse-ld=lld -target x86_64-pc-windows-gnu "$@" 3 | -------------------------------------------------------------------------------- /deterministic-build-wrappers/compiler-builtins-dummy/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "compiler-builtins-dummy" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | compiler_builtins = "=0.1.109" 8 | -------------------------------------------------------------------------------- /lightning-c-bindings/valgrind-suppressions.txt: -------------------------------------------------------------------------------- 1 | { 2 | Apparently rust stdlib accesses uninitialized values while debug'ing a duration 3 | Memcheck:Cond 4 | ... 5 | fun:_ZN57_$LT$core..time..Duration$u20$as$u20$core..fmt..Debug$* 6 | } 7 | -------------------------------------------------------------------------------- /c-bindings-gen/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "c-bindings-gen" 3 | version = "0.0.1" 4 | authors = ["Matt Corallo"] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | syn = { version = "1", features = ["full", "extra-traits"] } 9 | proc-macro2 = "1" 10 | quote = "1" 11 | 12 | [profile.release] 13 | incremental = true 14 | codegen-units = 256 15 | opt-level = 2 16 | lto = false 17 | debug = true 18 | 19 | # We're not in the workspace as we're just a binary code generator: 20 | [workspace] 21 | -------------------------------------------------------------------------------- /deterministic-build-wrappers/clang-lto-link-osx: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # We want to use rustc's -C linker-plugin-lto, but it passes several arguments 3 | # that are not understood by OSX clang/ld64.lld. Specifically, it passes 4 | # -plugin-opt* arguments to set optimization levels, which are not supported. 5 | # Thus, we intercept the call here, strip the unsupported arguments, and pass 6 | # -flto and -O3. 7 | args=("$@") 8 | for ((i=0; i<"${#args[@]}"; ++i)); do 9 | case ${args[i]} in 10 | -Wl,-plugin-opt*) 11 | args[i]="" 12 | ;; 13 | esac 14 | done 15 | $LDK_CLANG_PATH -flto -O3 -Wl,-O3 "${args[@]}" 16 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | This software is licensed under [Apache 2.0](LICENSE-APACHE) or 2 | [MIT](LICENSE-MIT), at your option. 3 | 4 | Some files retain their own copyright notice. However, for full authorship 5 | information, see version control history. 6 | 7 | Except as otherwise noted in individual files, all files in this repository are 8 | licensed under the Apache License, Version 2.0 or the MIT 9 | license , at your option. 10 | 11 | You may not use, copy, modify, merge, publish, distribute, sublicense, and/or 12 | sell copies of this software or any files in this repository except in 13 | accordance with one or both of these licenses. 14 | -------------------------------------------------------------------------------- /lightning-c-bindings/src/lightning/io.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history and in the source files from which this was generated. 3 | // 4 | // This file is licensed under the license available in the LICENSE or LICENSE.md 5 | // file in the root of this repository or, if no such file exists, the same 6 | // license as that which applies to the original source files from which this 7 | // source was automatically generated. 8 | 9 | /// Extension of the bitcoin::io module 10 | 11 | use alloc::str::FromStr; 12 | use alloc::string::String; 13 | use core::ffi::c_void; 14 | use core::convert::Infallible; 15 | use bitcoin::hashes::Hash; 16 | use crate::c_types::*; 17 | #[cfg(feature="no-std")] 18 | use alloc::{vec::Vec, boxed::Box}; 19 | 20 | -------------------------------------------------------------------------------- /lightning-c-bindings/src/lightning_types/payment.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history and in the source files from which this was generated. 3 | // 4 | // This file is licensed under the license available in the LICENSE or LICENSE.md 5 | // file in the root of this repository or, if no such file exists, the same 6 | // license as that which applies to the original source files from which this 7 | // source was automatically generated. 8 | 9 | //! Types which describe payments in lightning. 10 | 11 | use alloc::str::FromStr; 12 | use alloc::string::String; 13 | use core::ffi::c_void; 14 | use core::convert::Infallible; 15 | use bitcoin::hashes::Hash; 16 | use crate::c_types::*; 17 | #[cfg(feature="no-std")] 18 | use alloc::{vec::Vec, boxed::Box}; 19 | 20 | -------------------------------------------------------------------------------- /lightning-c-bindings/src/lightning/util/indexed_map.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history and in the source files from which this was generated. 3 | // 4 | // This file is licensed under the license available in the LICENSE or LICENSE.md 5 | // file in the root of this repository or, if no such file exists, the same 6 | // license as that which applies to the original source files from which this 7 | // source was automatically generated. 8 | 9 | //! This module has a map which can be iterated in a deterministic order. See the [`IndexedMap`]. 10 | 11 | use alloc::str::FromStr; 12 | use alloc::string::String; 13 | use core::ffi::c_void; 14 | use core::convert::Infallible; 15 | use bitcoin::hashes::Hash; 16 | use crate::c_types::*; 17 | #[cfg(feature="no-std")] 18 | use alloc::{vec::Vec, boxed::Box}; 19 | 20 | -------------------------------------------------------------------------------- /lightning-c-bindings/cbindgen.toml: -------------------------------------------------------------------------------- 1 | language = "C" 2 | include_guard = "LDK_C_BINDINGS_H" 3 | autogen_warning = "/* Warning, this file is autogenerated by cbindgen. Don't modify this manually. */" 4 | trailer = "#include \"ldk_ver.h\"" 5 | include_version = true 6 | namespace = "LDK" 7 | 8 | line_length = 80 9 | tab_width = 3 10 | 11 | [export] 12 | prefix = "LDK" 13 | 14 | [fn] 15 | args = "horizontal" 16 | must_use = "MUST_USE_RES" 17 | 18 | [struct] 19 | must_use = "MUST_USE_STRUCT" 20 | 21 | [enum] 22 | # We use the sentinel as a flag to indicate memory freeing is not necessary. 23 | add_sentinel = true 24 | 25 | # Whether enum variant names should be prefixed with the name of the enum. 26 | # default: false 27 | prefix_with_name = true 28 | must_use = "MUST_USE_ENUM" 29 | 30 | [ptr] 31 | non_null_attribute = "NONNULL_PTR" 32 | 33 | [defines] 34 | "test_mod_pointers" = "LDK_DEBUG_BUILD" 35 | -------------------------------------------------------------------------------- /lightning-c-bindings/src/lightning/util/string.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history and in the source files from which this was generated. 3 | // 4 | // This file is licensed under the license available in the LICENSE or LICENSE.md 5 | // file in the root of this repository or, if no such file exists, the same 6 | // license as that which applies to the original source files from which this 7 | // source was automatically generated. 8 | 9 | //! Utilities to wrap untrusted strings and handle them (more) safely 10 | //! 11 | //! These re-exports are deprecated in favor of [`lightning::types::string`]. 12 | //! 13 | //! [`lightning::types::string`]: crate::types::string 14 | 15 | use alloc::str::FromStr; 16 | use alloc::string::String; 17 | use core::ffi::c_void; 18 | use core::convert::Infallible; 19 | use bitcoin::hashes::Hash; 20 | use crate::c_types::*; 21 | #[cfg(feature="no-std")] 22 | use alloc::{vec::Vec, boxed::Box}; 23 | 24 | -------------------------------------------------------------------------------- /lightning-c-bindings/src/lightning_types/mod.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history and in the source files from which this was generated. 3 | // 4 | // This file is licensed under the license available in the LICENSE or LICENSE.md 5 | // file in the root of this repository or, if no such file exists, the same 6 | // license as that which applies to the original source files from which this 7 | // source was automatically generated. 8 | 9 | //!lightning_types 10 | //! Various types which are used in the lightning network. 11 | //! 12 | //! See the `lightning` crate for usage of these. 13 | 14 | use alloc::str::FromStr; 15 | use alloc::string::String; 16 | use core::ffi::c_void; 17 | use core::convert::Infallible; 18 | use bitcoin::hashes::Hash; 19 | use crate::c_types::*; 20 | #[cfg(feature="no-std")] 21 | use alloc::{vec::Vec, boxed::Box}; 22 | 23 | pub mod features; 24 | pub mod payment; 25 | pub mod routing; 26 | pub mod string; 27 | -------------------------------------------------------------------------------- /c-bindings-gen/README.md: -------------------------------------------------------------------------------- 1 | LDK C Bindings Generator 2 | ======================== 3 | 4 | This program parses a Rust crate's AST from a single lib.rs passed in on stdin and generates a 5 | second crate which is C-callable (and carries appropriate annotations for cbindgen). It is usually 6 | invoked via the `genbindings.sh` script in the top-level directory, which converts the lightning 7 | crate into a single file with a call to 8 | `RUSTC_BOOTSTRAP=1 cargo rustc --profile=check -- -Zunstable-options --pretty=expanded`. 9 | 10 | `genbindings.sh` requires that you have a rustc installed with the `wasm32-wasi` target available 11 | (eg via the `libstd-rust-dev-wasm32` package on Debian or `rustup target add wasm32-wasi` for those 12 | using rustup), cbindgen installed via `cargo install cbindgen` and in your `PATH`, and `clang`, 13 | `clang++`, `gcc`, and `g++` available in your `PATH`. It uses `valgrind` if it is available to test 14 | the generated bindings thoroughly for memory management issues. 15 | -------------------------------------------------------------------------------- /lightning-c-bindings/src/lightning/util/ser_macros.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history and in the source files from which this was generated. 3 | // 4 | // This file is licensed under the license available in the LICENSE or LICENSE.md 5 | // file in the root of this repository or, if no such file exists, the same 6 | // license as that which applies to the original source files from which this 7 | // source was automatically generated. 8 | 9 | //! Some macros that implement [`Readable`]/[`Writeable`] traits for lightning messages. 10 | //! They also handle serialization and deserialization of TLVs. 11 | //! 12 | //! [`Readable`]: crate::util::ser::Readable 13 | //! [`Writeable`]: crate::util::ser::Writeable 14 | 15 | use alloc::str::FromStr; 16 | use alloc::string::String; 17 | use core::ffi::c_void; 18 | use core::convert::Infallible; 19 | use bitcoin::hashes::Hash; 20 | use crate::c_types::*; 21 | #[cfg(feature="no-std")] 22 | use alloc::{vec::Vec, boxed::Box}; 23 | 24 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any person obtaining a copy of 2 | this software and associated documentation files (the "Software"), to deal in 3 | the Software without restriction, including without limitation the rights to 4 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 5 | the Software, and to permit persons to whom the Software is furnished to do so, 6 | subject to the following conditions: 7 | 8 | The above copyright notice and this permission notice shall be included in all 9 | copies or substantial portions of the Software. 10 | 11 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 12 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 13 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 14 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 15 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 16 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 17 | -------------------------------------------------------------------------------- /lightning-c-bindings/src/lightning_persister/mod.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history and in the source files from which this was generated. 3 | // 4 | // This file is licensed under the license available in the LICENSE or LICENSE.md 5 | // file in the root of this repository or, if no such file exists, the same 6 | // license as that which applies to the original source files from which this 7 | // source was automatically generated. 8 | 9 | //! Provides utilities for LDK data persistence and retrieval. 10 | 11 | use alloc::str::FromStr; 12 | use alloc::string::String; 13 | use core::ffi::c_void; 14 | use core::convert::Infallible; 15 | use bitcoin::hashes::Hash; 16 | use crate::c_types::*; 17 | #[cfg(feature="no-std")] 18 | use alloc::{vec::Vec, boxed::Box}; 19 | 20 | pub mod fs_store; 21 | mod utils { 22 | 23 | use alloc::str::FromStr; 24 | use alloc::string::String; 25 | use core::ffi::c_void; 26 | use core::convert::Infallible; 27 | use bitcoin::hashes::Hash; 28 | use crate::c_types::*; 29 | #[cfg(feature="no-std")] 30 | use alloc::{vec::Vec, boxed::Box}; 31 | 32 | } 33 | -------------------------------------------------------------------------------- /ldk-net/ldk_net.h: -------------------------------------------------------------------------------- 1 | #include "lightning.h" 2 | #include 3 | /** 4 | * Initializes socket handling and spawns a background thread to handle socket 5 | * events and pass them to the given LDKPeerManager. 6 | * 7 | * Returns NULL on error, otherwise an opaque pointer which should be passed as 8 | * `handler` in the remaining functions. 9 | */ 10 | void* init_socket_handling(const struct LDKPeerManager *NONNULL_PTR ldk_peer_manger); 11 | /** 12 | * Stop the socket handling thread and free socket handling resources for the 13 | * given handler, as returned by init_socket_handling. 14 | */ 15 | void interrupt_socket_handling(void* handler); 16 | /** 17 | * Bind the given address to accept incoming connections on the given handler's 18 | * background thread. 19 | * Returns 0 on success. 20 | */ 21 | int socket_bind(void* handler, struct sockaddr *addr, socklen_t addrlen); 22 | /** 23 | * Connect to the given address and handle socket events on the given handler's 24 | * background thread. 25 | * Returns 0 on success. 26 | */ 27 | int socket_connect(void* handler, LDKPublicKey counterparty_pubkey, struct sockaddr *addr, size_t addrlen); 28 | -------------------------------------------------------------------------------- /lightning-c-bindings/src/bitcoin/network.rs: -------------------------------------------------------------------------------- 1 | //! A C-mapped version fo bitcoin::network::constants::Network 2 | 3 | use bitcoin::Network as BitcoinNetwork; 4 | 5 | #[repr(C)] 6 | /// An enum representing the possible Bitcoin or test networks which we can run on 7 | pub enum Network { 8 | /// The main Bitcoin blockchain. 9 | Bitcoin, 10 | /// The testnet3 blockchain. 11 | Testnet, 12 | /// A local test blockchain. 13 | Regtest, 14 | /// A blockchain on which blocks are signed instead of mined. 15 | Signet, 16 | } 17 | 18 | impl Network { 19 | pub(crate) fn into_bitcoin(&self) -> BitcoinNetwork { 20 | match self { 21 | Network::Bitcoin => BitcoinNetwork::Bitcoin, 22 | Network::Testnet => BitcoinNetwork::Testnet, 23 | Network::Regtest => BitcoinNetwork::Regtest, 24 | Network::Signet => BitcoinNetwork::Signet, 25 | } 26 | } 27 | pub(crate) fn from_bitcoin(net: &BitcoinNetwork) -> Self { 28 | match net { 29 | BitcoinNetwork::Bitcoin => Network::Bitcoin, 30 | BitcoinNetwork::Testnet => Network::Testnet, 31 | BitcoinNetwork::Regtest => Network::Regtest, 32 | BitcoinNetwork::Signet => Network::Signet, 33 | _ => unreachable!(), 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /lightning-c-bindings/src/lightning/routing/mod.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history and in the source files from which this was generated. 3 | // 4 | // This file is licensed under the license available in the LICENSE or LICENSE.md 5 | // file in the root of this repository or, if no such file exists, the same 6 | // license as that which applies to the original source files from which this 7 | // source was automatically generated. 8 | 9 | //! Structs and impls for receiving messages about the network and storing the topology live here. 10 | 11 | use alloc::str::FromStr; 12 | use alloc::string::String; 13 | use core::ffi::c_void; 14 | use core::convert::Infallible; 15 | use bitcoin::hashes::Hash; 16 | use crate::c_types::*; 17 | #[cfg(feature="no-std")] 18 | use alloc::{vec::Vec, boxed::Box}; 19 | 20 | pub mod utxo; 21 | pub mod gossip; 22 | pub mod router; 23 | pub mod scoring; 24 | mod log_approx { 25 | 26 | use alloc::str::FromStr; 27 | use alloc::string::String; 28 | use core::ffi::c_void; 29 | use core::convert::Infallible; 30 | use bitcoin::hashes::Hash; 31 | use crate::c_types::*; 32 | #[cfg(feature="no-std")] 33 | use alloc::{vec::Vec, boxed::Box}; 34 | 35 | } 36 | -------------------------------------------------------------------------------- /lightning-c-bindings/src/lib.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history and in the source files from which this was generated. 3 | // 4 | // This file is licensed under the license available in the LICENSE or LICENSE.md 5 | // file in the root of this repository or, if no such file exists, the same 6 | // license as that which applies to the original source files from which this 7 | // source was automatically generated. 8 | 9 | //! C Bindings 10 | #![allow(unknown_lints)] 11 | #![allow(non_camel_case_types)] 12 | #![allow(non_snake_case)] 13 | #![allow(unused_imports)] 14 | #![allow(unused_variables)] 15 | #![allow(unused_mut)] 16 | #![allow(unused_parens)] 17 | #![allow(unused_unsafe)] 18 | #![allow(unused_braces)] 19 | #![cfg_attr(not(feature = "std"), no_std)] 20 | #[cfg(not(any(feature = "std", feature = "no-std")))] 21 | compile_error!("at least one of the `std` or `no-std` features must be enabled"); 22 | extern crate alloc; 23 | pub mod version; 24 | pub mod c_types; 25 | pub mod bitcoin; 26 | pub mod lightning; 27 | pub mod lightning_types; 28 | pub mod lightning_persister; 29 | pub mod lightning_background_processor; 30 | pub mod lightning_invoice; 31 | pub mod lightning_rapid_gossip_sync; 32 | -------------------------------------------------------------------------------- /deterministic-build-wrappers/rustc: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # rustc calculates a unique metadata tag to mangle symbols which includes the 3 | # actual path to the crate. This breaks our deterministic builds as we depend 4 | # on a copy of rust-lightning via a path. We insert this shim between cargo and 5 | # rustc and edit the metadata tag for rust-lightning. 6 | # While we could just set RUSTFLAGS="-C metadata=42", this would break if we 7 | # ever (indirectly) depend on multiple versions of the same crate. 8 | args=("$@") 9 | IS_LIGHTNING=false 10 | for ((i=0; i<"${#args[@]}"; ++i)); do 11 | case ${args[i]} in 12 | --crate-name) 13 | if [ "${args[i+1]}" = "lightning" -o "${args[i+1]}" = "lightning_types" -o "${args[i+1]}" = "lightning_background_processor" -o "${args[i+1]}" = "lightning_invoice" -o "${args[i+1]}" = "lightning_persister" -o "${args[i+1]}" = "lightning_rapid_gossip_sync" -o "${args[i+1]}" = "ldk" ]; then 14 | IS_LIGHTNING=true 15 | fi 16 | ;; 17 | esac 18 | done 19 | for ((i=0; i<"${#args[@]}"; ++i)); do 20 | case ${args[i]} in 21 | metadata*) 22 | if [ "$IS_LIGHTNING" = "true" ]; then 23 | # Pick any random value for metadata, it doesn't matter 24 | args[i]="metadata=42" 25 | fi 26 | ;; 27 | esac 28 | done 29 | 30 | $LDK_RUSTC_PATH "${args[@]}" 31 | -------------------------------------------------------------------------------- /lightning-c-bindings/src/lightning/util/hash_tables.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history and in the source files from which this was generated. 3 | // 4 | // This file is licensed under the license available in the LICENSE or LICENSE.md 5 | // file in the root of this repository or, if no such file exists, the same 6 | // license as that which applies to the original source files from which this 7 | // source was automatically generated. 8 | 9 | //! Generally LDK uses `hashbrown`'s `HashMap`s with the `std` `SipHasher` and uses `getrandom` to 10 | //! opportunistically randomize it, if randomization is available. 11 | //! 12 | //! This module simply re-exports the `HashMap` used in LDK for public consumption. 13 | 14 | use alloc::str::FromStr; 15 | use alloc::string::String; 16 | use core::ffi::c_void; 17 | use core::convert::Infallible; 18 | use bitcoin::hashes::Hash; 19 | use crate::c_types::*; 20 | #[cfg(feature="no-std")] 21 | use alloc::{vec::Vec, boxed::Box}; 22 | 23 | mod hashbrown_tables { 24 | 25 | use alloc::str::FromStr; 26 | use alloc::string::String; 27 | use core::ffi::c_void; 28 | use core::convert::Infallible; 29 | use bitcoin::hashes::Hash; 30 | use crate::c_types::*; 31 | #[cfg(feature="no-std")] 32 | use alloc::{vec::Vec, boxed::Box}; 33 | 34 | mod hasher { 35 | 36 | use alloc::str::FromStr; 37 | use alloc::string::String; 38 | use core::ffi::c_void; 39 | use core::convert::Infallible; 40 | use bitcoin::hashes::Hash; 41 | use crate::c_types::*; 42 | #[cfg(feature="no-std")] 43 | use alloc::{vec::Vec, boxed::Box}; 44 | 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /lightning-c-bindings/src/lightning/onion_message/mod.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history and in the source files from which this was generated. 3 | // 4 | // This file is licensed under the license available in the LICENSE or LICENSE.md 5 | // file in the root of this repository or, if no such file exists, the same 6 | // license as that which applies to the original source files from which this 7 | // source was automatically generated. 8 | 9 | //! Onion Messages: sending, receiving, forwarding, and ancillary utilities live here 10 | //! 11 | //! Onion messages are multi-purpose messages sent between peers over the lightning network. In the 12 | //! near future, they will be used to communicate invoices for [offers], unlocking use cases such as 13 | //! static invoices, refunds and proof of payer. Further, you will be able to accept payments 14 | //! without revealing your node id through the use of [blinded paths]. 15 | //! 16 | //! LDK sends and receives onion messages via the [`OnionMessenger`]. See its documentation for more 17 | //! information on its usage. 18 | //! 19 | //! [offers]: 20 | //! [blinded paths]: crate::blinded_path::message::BlindedMessagePath 21 | //! [`OnionMessenger`]: self::messenger::OnionMessenger 22 | 23 | use alloc::str::FromStr; 24 | use alloc::string::String; 25 | use core::ffi::c_void; 26 | use core::convert::Infallible; 27 | use bitcoin::hashes::Hash; 28 | use crate::c_types::*; 29 | #[cfg(feature="no-std")] 30 | use alloc::{vec::Vec, boxed::Box}; 31 | 32 | pub mod async_payments; 33 | pub mod dns_resolution; 34 | pub mod messenger; 35 | pub mod offers; 36 | pub mod packet; 37 | -------------------------------------------------------------------------------- /lightning-c-bindings/src/lightning/offers/mod.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history and in the source files from which this was generated. 3 | // 4 | // This file is licensed under the license available in the LICENSE or LICENSE.md 5 | // file in the root of this repository or, if no such file exists, the same 6 | // license as that which applies to the original source files from which this 7 | // source was automatically generated. 8 | 9 | //! Implementation of Lightning Offers 10 | //! ([BOLT 12](https://github.com/lightning/bolts/blob/master/12-offer-encoding.md)). 11 | //! 12 | //! Offers are a flexible protocol for Lightning payments. 13 | 14 | use alloc::str::FromStr; 15 | use alloc::string::String; 16 | use core::ffi::c_void; 17 | use core::convert::Infallible; 18 | use bitcoin::hashes::Hash; 19 | use crate::c_types::*; 20 | #[cfg(feature="no-std")] 21 | use alloc::{vec::Vec, boxed::Box}; 22 | 23 | pub mod offer; 24 | pub mod invoice; 25 | pub mod invoice_error; 26 | pub mod invoice_request; 27 | pub mod merkle; 28 | pub mod nonce; 29 | pub mod parse; 30 | pub mod refund; 31 | mod invoice_macros { 32 | 33 | use alloc::str::FromStr; 34 | use alloc::string::String; 35 | use core::ffi::c_void; 36 | use core::convert::Infallible; 37 | use bitcoin::hashes::Hash; 38 | use crate::c_types::*; 39 | #[cfg(feature="no-std")] 40 | use alloc::{vec::Vec, boxed::Box}; 41 | 42 | } 43 | mod payer { 44 | 45 | use alloc::str::FromStr; 46 | use alloc::string::String; 47 | use core::ffi::c_void; 48 | use core::convert::Infallible; 49 | use bitcoin::hashes::Hash; 50 | use crate::c_types::*; 51 | #[cfg(feature="no-std")] 52 | use alloc::{vec::Vec, boxed::Box}; 53 | 54 | } 55 | mod signer { 56 | 57 | use alloc::str::FromStr; 58 | use alloc::string::String; 59 | use core::ffi::c_void; 60 | use core::convert::Infallible; 61 | use bitcoin::hashes::Hash; 62 | use crate::c_types::*; 63 | #[cfg(feature="no-std")] 64 | use alloc::{vec::Vec, boxed::Box}; 65 | 66 | } 67 | -------------------------------------------------------------------------------- /lightning-c-bindings/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "lightning-c-bindings" 3 | version = "0.0.1" 4 | authors = ["Matt Corallo"] 5 | license = "Apache-2.0" 6 | edition = "2018" 7 | description = """ 8 | Utilities to fetch the chain from Bitcoin Core REST/RPC Interfaces and feed them into Rust Lightning. 9 | """ 10 | 11 | [lib] 12 | name = "ldk" 13 | crate-type = ["staticlib" 14 | # Note that the following line is matched exactly by genbindings to turn off dylib creation 15 | ,"cdylib"] 16 | 17 | [features] 18 | no-std = ["lightning/dnssec"] 19 | std = ["bitcoin/std", "lightning/std", "lightning/dnssec", "lightning-invoice/std", "lightning-background-processor/std", "lightning-rapid-gossip-sync/std"] 20 | 21 | [dependencies] 22 | bitcoin = { version = "0.32", default-features = false } 23 | bech32 = { version = "0.9", default-features = false } 24 | secp256k1 = { version = "0.29", features = ["global-context", "recovery"] } 25 | # Note that the following line is matched by genbindings to update the path 26 | lightning = { git = "https://github.com/lightningdevkit/rust-lightning", branch = "0.1-bindings", default-features = false } 27 | lightning-types = { git = "https://github.com/lightningdevkit/rust-lightning", branch = "0.1-bindings", default-features = false } 28 | lightning-persister = { git = "https://github.com/lightningdevkit/rust-lightning", branch = "0.1-bindings", default-features = false } 29 | lightning-invoice = { git = "https://github.com/lightningdevkit/rust-lightning", branch = "0.1-bindings", default-features = false } 30 | lightning-background-processor = { git = "https://github.com/lightningdevkit/rust-lightning", branch = "0.1-bindings", default-features = false } 31 | lightning-rapid-gossip-sync = { git = "https://github.com/lightningdevkit/rust-lightning", branch = "0.1-bindings", default-features = false } 32 | 33 | # Always force panic=abort, further options are set in the genbindings.sh build script 34 | [profile.dev] 35 | panic = "abort" 36 | 37 | [profile.release] 38 | panic = "abort" 39 | -------------------------------------------------------------------------------- /lightning-c-bindings/src/lightning_invoice/constants.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history and in the source files from which this was generated. 3 | // 4 | // This file is licensed under the license available in the LICENSE or LICENSE.md 5 | // file in the root of this repository or, if no such file exists, the same 6 | // license as that which applies to the original source files from which this 7 | // source was automatically generated. 8 | 9 | /// Tag constants as specified in BOLT11 10 | 11 | use alloc::str::FromStr; 12 | use alloc::string::String; 13 | use core::ffi::c_void; 14 | use core::convert::Infallible; 15 | use bitcoin::hashes::Hash; 16 | use crate::c_types::*; 17 | #[cfg(feature="no-std")] 18 | use alloc::{vec::Vec, boxed::Box}; 19 | 20 | 21 | #[no_mangle] 22 | pub static TAG_PAYMENT_HASH: u8 = lightning_invoice::constants::TAG_PAYMENT_HASH; 23 | 24 | #[no_mangle] 25 | pub static TAG_DESCRIPTION: u8 = lightning_invoice::constants::TAG_DESCRIPTION; 26 | 27 | #[no_mangle] 28 | pub static TAG_PAYEE_PUB_KEY: u8 = lightning_invoice::constants::TAG_PAYEE_PUB_KEY; 29 | 30 | #[no_mangle] 31 | pub static TAG_DESCRIPTION_HASH: u8 = lightning_invoice::constants::TAG_DESCRIPTION_HASH; 32 | 33 | #[no_mangle] 34 | pub static TAG_EXPIRY_TIME: u8 = lightning_invoice::constants::TAG_EXPIRY_TIME; 35 | 36 | #[no_mangle] 37 | pub static TAG_MIN_FINAL_CLTV_EXPIRY_DELTA: u8 = lightning_invoice::constants::TAG_MIN_FINAL_CLTV_EXPIRY_DELTA; 38 | 39 | #[no_mangle] 40 | pub static TAG_FALLBACK: u8 = lightning_invoice::constants::TAG_FALLBACK; 41 | 42 | #[no_mangle] 43 | pub static TAG_PRIVATE_ROUTE: u8 = lightning_invoice::constants::TAG_PRIVATE_ROUTE; 44 | 45 | #[no_mangle] 46 | pub static TAG_PAYMENT_SECRET: u8 = lightning_invoice::constants::TAG_PAYMENT_SECRET; 47 | 48 | #[no_mangle] 49 | pub static TAG_PAYMENT_METADATA: u8 = lightning_invoice::constants::TAG_PAYMENT_METADATA; 50 | 51 | #[no_mangle] 52 | pub static TAG_FEATURES: u8 = lightning_invoice::constants::TAG_FEATURES; 53 | -------------------------------------------------------------------------------- /lightning-c-bindings/src/lightning/util/message_signing.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history and in the source files from which this was generated. 3 | // 4 | // This file is licensed under the license available in the LICENSE or LICENSE.md 5 | // file in the root of this repository or, if no such file exists, the same 6 | // license as that which applies to the original source files from which this 7 | // source was automatically generated. 8 | 9 | //! Lightning message signing and verification lives here. These tools can be used to sign messages using the node's 10 | //! secret so receivers are sure that they come from you. You can also use this to verify that a given message comes 11 | //! from a specific node. 12 | //! Furthermore, these tools can be used to sign / verify messages using ephemeral keys not tied to node's identities. 13 | //! 14 | //! Note this is not part of the specs, but follows lnd's signing and verifying protocol, which can is defined as follows: 15 | //! 16 | //! signature = zbase32(SigRec(sha256d((\"Lightning Signed Message:\" + msg))) 17 | //! zbase32 from 18 | //! SigRec has first byte 31 + recovery id, followed by 64 byte sig. 19 | //! 20 | //! This implementation is compatible with both lnd's and c-lightning's 21 | //! 22 | //! 23 | //! 24 | 25 | use alloc::str::FromStr; 26 | use alloc::string::String; 27 | use core::ffi::c_void; 28 | use core::convert::Infallible; 29 | use bitcoin::hashes::Hash; 30 | use crate::c_types::*; 31 | #[cfg(feature="no-std")] 32 | use alloc::{vec::Vec, boxed::Box}; 33 | 34 | /// Creates a digital signature of a message given a SecretKey, like the node's secret. 35 | /// A receiver knowing the PublicKey (e.g. the node's id) and the message can be sure that the signature was generated by the caller. 36 | /// Signatures are EC recoverable, meaning that given the message and the signature the PublicKey of the signer can be extracted. 37 | #[no_mangle] 38 | pub extern "C" fn sign(mut msg: crate::c_types::u8slice, sk: *const [u8; 32]) -> crate::c_types::Str { 39 | let mut ret = lightning::util::message_signing::sign(msg.to_slice(), &::bitcoin::secp256k1::SecretKey::from_slice(&unsafe { *sk}[..]).unwrap()); 40 | ret.into() 41 | } 42 | 43 | /// Recovers the PublicKey of the signer of the message given the message and the signature. 44 | #[no_mangle] 45 | pub extern "C" fn recover_pk(mut msg: crate::c_types::u8slice, mut sig: crate::c_types::Str) -> crate::c_types::derived::CResult_PublicKeySecp256k1ErrorZ { 46 | let mut ret = lightning::util::message_signing::recover_pk(msg.to_slice(), sig.into_str()); 47 | 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() }; 48 | local_ret 49 | } 50 | 51 | /// Verifies a message was signed by a PrivateKey that derives to a given PublicKey, given a message, a signature, 52 | /// and the PublicKey. 53 | #[no_mangle] 54 | pub extern "C" fn verify(mut msg: crate::c_types::u8slice, mut sig: crate::c_types::Str, mut pk: crate::c_types::PublicKey) -> bool { 55 | let mut ret = lightning::util::message_signing::verify(msg.to_slice(), sig.into_str(), &pk.into_rust()); 56 | ret 57 | } 58 | 59 | -------------------------------------------------------------------------------- /lightning-c-bindings/src/lightning/util/mod.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history and in the source files from which this was generated. 3 | // 4 | // This file is licensed under the license available in the LICENSE or LICENSE.md 5 | // file in the root of this repository or, if no such file exists, the same 6 | // license as that which applies to the original source files from which this 7 | // source was automatically generated. 8 | 9 | //! Some utility modules live here. See individual sub-modules for more info. 10 | 11 | use alloc::str::FromStr; 12 | use alloc::string::String; 13 | use core::ffi::c_void; 14 | use core::convert::Infallible; 15 | use bitcoin::hashes::Hash; 16 | use crate::c_types::*; 17 | #[cfg(feature="no-std")] 18 | use alloc::{vec::Vec, boxed::Box}; 19 | 20 | pub mod ser_macros; 21 | pub mod errors; 22 | pub mod ser; 23 | pub mod message_signing; 24 | pub mod persist; 25 | pub mod scid_utils; 26 | pub mod sweep; 27 | pub mod wakers; 28 | pub mod hash_tables; 29 | pub mod indexed_map; 30 | pub mod logger; 31 | pub mod config; 32 | pub mod string; 33 | mod fuzz_wrappers { 34 | 35 | use alloc::str::FromStr; 36 | use alloc::string::String; 37 | use core::ffi::c_void; 38 | use core::convert::Infallible; 39 | use bitcoin::hashes::Hash; 40 | use crate::c_types::*; 41 | #[cfg(feature="no-std")] 42 | use alloc::{vec::Vec, boxed::Box}; 43 | 44 | } 45 | mod base32 { 46 | 47 | use alloc::str::FromStr; 48 | use alloc::string::String; 49 | use core::ffi::c_void; 50 | use core::convert::Infallible; 51 | use bitcoin::hashes::Hash; 52 | use crate::c_types::*; 53 | #[cfg(feature="no-std")] 54 | use alloc::{vec::Vec, boxed::Box}; 55 | 56 | } 57 | mod atomic_counter { 58 | 59 | use alloc::str::FromStr; 60 | use alloc::string::String; 61 | use core::ffi::c_void; 62 | use core::convert::Infallible; 63 | use bitcoin::hashes::Hash; 64 | use crate::c_types::*; 65 | #[cfg(feature="no-std")] 66 | use alloc::{vec::Vec, boxed::Box}; 67 | 68 | } 69 | mod async_poll { 70 | 71 | use alloc::str::FromStr; 72 | use alloc::string::String; 73 | use core::ffi::c_void; 74 | use core::convert::Infallible; 75 | use bitcoin::hashes::Hash; 76 | use crate::c_types::*; 77 | #[cfg(feature="no-std")] 78 | use alloc::{vec::Vec, boxed::Box}; 79 | 80 | } 81 | mod byte_utils { 82 | 83 | use alloc::str::FromStr; 84 | use alloc::string::String; 85 | use core::ffi::c_void; 86 | use core::convert::Infallible; 87 | use bitcoin::hashes::Hash; 88 | use crate::c_types::*; 89 | #[cfg(feature="no-std")] 90 | use alloc::{vec::Vec, boxed::Box}; 91 | 92 | } 93 | mod transaction_utils { 94 | 95 | use alloc::str::FromStr; 96 | use alloc::string::String; 97 | use core::ffi::c_void; 98 | use core::convert::Infallible; 99 | use bitcoin::hashes::Hash; 100 | use crate::c_types::*; 101 | #[cfg(feature="no-std")] 102 | use alloc::{vec::Vec, boxed::Box}; 103 | 104 | } 105 | mod time { 106 | 107 | use alloc::str::FromStr; 108 | use alloc::string::String; 109 | use core::ffi::c_void; 110 | use core::convert::Infallible; 111 | use bitcoin::hashes::Hash; 112 | use crate::c_types::*; 113 | #[cfg(feature="no-std")] 114 | use alloc::{vec::Vec, boxed::Box}; 115 | 116 | } 117 | mod macro_logger { 118 | 119 | use alloc::str::FromStr; 120 | use alloc::string::String; 121 | use core::ffi::c_void; 122 | use core::convert::Infallible; 123 | use bitcoin::hashes::Hash; 124 | use crate::c_types::*; 125 | #[cfg(feature="no-std")] 126 | use alloc::{vec::Vec, boxed::Box}; 127 | 128 | } 129 | -------------------------------------------------------------------------------- /lightning-c-bindings/src/lightning/ln/bolt11_payment.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history and in the source files from which this was generated. 3 | // 4 | // This file is licensed under the license available in the LICENSE or LICENSE.md 5 | // file in the root of this repository or, if no such file exists, the same 6 | // license as that which applies to the original source files from which this 7 | // source was automatically generated. 8 | 9 | //! Convenient utilities for paying Lightning invoices. 10 | 11 | use alloc::str::FromStr; 12 | use alloc::string::String; 13 | use core::ffi::c_void; 14 | use core::convert::Infallible; 15 | use bitcoin::hashes::Hash; 16 | use crate::c_types::*; 17 | #[cfg(feature="no-std")] 18 | use alloc::{vec::Vec, boxed::Box}; 19 | 20 | /// Builds the necessary parameters to pay or pre-flight probe the given variable-amount 21 | /// (also known as 'zero-amount') [`Bolt11Invoice`] using 22 | /// [`ChannelManager::send_payment`] or [`ChannelManager::send_preflight_probes`]. 23 | /// 24 | /// Prior to paying, you must ensure that the [`Bolt11Invoice::payment_hash`] is unique and the 25 | /// same [`PaymentHash`] has never been paid before. 26 | /// 27 | /// Will always succeed unless the invoice has an amount specified, in which case 28 | /// [`payment_parameters_from_invoice`] should be used. 29 | /// 30 | /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment 31 | /// [`ChannelManager::send_preflight_probes`]: crate::ln::channelmanager::ChannelManager::send_preflight_probes 32 | #[no_mangle] 33 | pub extern "C" fn payment_parameters_from_variable_amount_invoice(invoice: &crate::lightning_invoice::Bolt11Invoice, mut amount_msat: u64) -> crate::c_types::derived::CResult_C3Tuple_ThirtyTwoBytesRecipientOnionFieldsRouteParametersZNoneZ { 34 | let mut ret = lightning::ln::bolt11_payment::payment_parameters_from_variable_amount_invoice(invoice.get_native_ref(), amount_msat); 35 | 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, mut orig_ret_0_2) = o; let mut local_ret_0 = (crate::c_types::ThirtyTwoBytes { data: orig_ret_0_0.0 }, crate::lightning::ln::outbound_payment::RecipientOnionFields { inner: ObjOps::heap_alloc(orig_ret_0_1), is_owned: true }, crate::lightning::routing::router::RouteParameters { inner: ObjOps::heap_alloc(orig_ret_0_2), is_owned: true }).into(); local_ret_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; 36 | local_ret 37 | } 38 | 39 | /// Builds the necessary parameters to pay or pre-flight probe the given [`Bolt11Invoice`] using 40 | /// [`ChannelManager::send_payment`] or [`ChannelManager::send_preflight_probes`]. 41 | /// 42 | /// Prior to paying, you must ensure that the [`Bolt11Invoice::payment_hash`] is unique and the 43 | /// same [`PaymentHash`] has never been paid before. 44 | /// 45 | /// Will always succeed unless the invoice has no amount specified, in which case 46 | /// [`payment_parameters_from_variable_amount_invoice`] should be used. 47 | /// 48 | /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment 49 | /// [`ChannelManager::send_preflight_probes`]: crate::ln::channelmanager::ChannelManager::send_preflight_probes 50 | #[no_mangle] 51 | pub extern "C" fn payment_parameters_from_invoice(invoice: &crate::lightning_invoice::Bolt11Invoice) -> crate::c_types::derived::CResult_C3Tuple_ThirtyTwoBytesRecipientOnionFieldsRouteParametersZNoneZ { 52 | let mut ret = lightning::ln::bolt11_payment::payment_parameters_from_invoice(invoice.get_native_ref()); 53 | 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, mut orig_ret_0_2) = o; let mut local_ret_0 = (crate::c_types::ThirtyTwoBytes { data: orig_ret_0_0.0 }, crate::lightning::ln::outbound_payment::RecipientOnionFields { inner: ObjOps::heap_alloc(orig_ret_0_1), is_owned: true }, crate::lightning::routing::router::RouteParameters { inner: ObjOps::heap_alloc(orig_ret_0_2), is_owned: true }).into(); local_ret_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; 54 | local_ret 55 | } 56 | 57 | -------------------------------------------------------------------------------- /lightning-c-bindings/demo.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | void print_log(const void *this_arg, const LDKRecord record) { 8 | LDKStr mod = Record_get_module_path(&record); 9 | LDKStr str = Record_get_args(&record); 10 | printf("%.*s:%d - %.*s\n", (int)mod.len, mod.chars, Record_get_line(&record), (int)str.len, str.chars); 11 | Str_free(str); 12 | Str_free(mod); 13 | Record_free(record); 14 | } 15 | 16 | uint32_t get_fee(const void *this_arg, LDKConfirmationTarget target) { 17 | if (target == LDKConfirmationTarget_AnchorChannelFee || target == LDKConfirmationTarget_MinAllowedAnchorChannelRemoteFee) { 18 | return 253; 19 | } else { 20 | return 507; 21 | } 22 | } 23 | 24 | void broadcast_txn(const void *this_arg, LDKCVec_TransactionZ txn) { 25 | //TODO 26 | CVec_TransactionZ_free(txn); 27 | } 28 | 29 | LDKCResult_ChannelMonitorUpdateStatusNoneZ add_channel_monitor(const void *this_arg, LDKOutPoint funding_txo, LDKChannelMonitor monitor) { 30 | return CResult_ChannelMonitorUpdateStatusNoneZ_ok(ChannelMonitorUpdateStatus_completed()); 31 | } 32 | LDKChannelMonitorUpdateStatus update_channel_monitor(const void *this_arg, LDKOutPoint funding_txo, const LDKChannelMonitorUpdate *monitor) { 33 | return ChannelMonitorUpdateStatus_completed(); 34 | } 35 | LDKCVec_C4Tuple_OutPointChannelIdCVec_MonitorEventZPublicKeyZZ monitors_pending_monitor_events(const void *this_arg) { 36 | LDKCVec_C4Tuple_OutPointChannelIdCVec_MonitorEventZPublicKeyZZ empty_htlc_vec = { 37 | .data = NULL, 38 | .datalen = 0, 39 | }; 40 | return empty_htlc_vec; 41 | } 42 | 43 | LDKCResult_NoneReplayEventZ never_handle_event(const void *this_arg, const struct LDKEvent event) { 44 | // Note that we never actually generate any events to handle in the code below. 45 | assert(false); 46 | return CResult_NoneReplayEventZ_ok(); 47 | } 48 | 49 | LDKCResult_RouteLightningErrorZ do_find_route(const void *this_arg, LDKPublicKey payer, const LDKRouteParameters *route_params, LDKCVec_ChannelDetailsZ *first_hops, const LDKInFlightHtlcs inflight_htlcs) { 50 | LDKStr reason = { .chars = (const unsigned char*)"", .len = 0, .chars_is_owned = false }; 51 | return CResult_RouteLightningErrorZ_err(LightningError_new(reason, ErrorAction_ignore_error())); 52 | } 53 | 54 | LDKCResult_RouteLightningErrorZ do_find_route_with_id(const void *this_arg, LDKPublicKey payer, const LDKRouteParameters *route_params, LDKCVec_ChannelDetailsZ *first_hops, const LDKInFlightHtlcs inflight_htlcs, struct LDKThirtyTwoBytes payment_hash, struct LDKThirtyTwoBytes payment_id) { 55 | LDKStr reason = { .chars = (const unsigned char*)"", .len = 0, .chars_is_owned = false }; 56 | return CResult_RouteLightningErrorZ_err(LightningError_new(reason, ErrorAction_ignore_error())); 57 | } 58 | 59 | int main() { 60 | uint8_t node_seed[32]; 61 | memset(node_seed, 0, 32); 62 | 63 | LDKNetwork net = LDKNetwork_Bitcoin; 64 | 65 | LDKLogger logger = { 66 | .this_arg = NULL, 67 | .log = print_log, 68 | .free = NULL, 69 | }; 70 | 71 | LDKFeeEstimator fee_est = { 72 | .this_arg = NULL, 73 | .get_est_sat_per_1000_weight = get_fee, 74 | .free = NULL 75 | }; 76 | 77 | LDKWatch mon = { 78 | .this_arg = NULL, 79 | .watch_channel = add_channel_monitor, 80 | .update_channel = update_channel_monitor, 81 | .release_pending_monitor_events = monitors_pending_monitor_events, 82 | .free = NULL, 83 | }; 84 | 85 | LDKBroadcasterInterface broadcast = { 86 | .this_arg = NULL, 87 | .broadcast_transactions = broadcast_txn, 88 | .free = NULL, 89 | }; 90 | 91 | LDKRouter router = { 92 | .this_arg = NULL, 93 | .find_route = do_find_route, 94 | .find_route_with_id = do_find_route_with_id, 95 | .free = NULL, 96 | }; 97 | 98 | LDKMessageRouter msg_router = { 99 | .this_arg = NULL, 100 | .find_path = NULL, 101 | .create_blinded_paths = NULL, 102 | .create_compact_blinded_paths = NULL, 103 | .free = NULL, 104 | }; 105 | 106 | LDKKeysManager keys = KeysManager_new(&node_seed, 0, 0); 107 | LDKEntropySource entropy_source = KeysManager_as_EntropySource(&keys); 108 | LDKNodeSigner node_signer = KeysManager_as_NodeSigner(&keys); 109 | LDKSignerProvider signer_provider = KeysManager_as_SignerProvider(&keys); 110 | 111 | LDKUserConfig config = UserConfig_default(); 112 | LDKThirtyTwoBytes chain_tip; 113 | memset(&chain_tip, 0, 32); 114 | LDKChainParameters chain = ChainParameters_new(net, BestBlock_new(chain_tip, 0)); 115 | LDKChannelManager cm = ChannelManager_new(fee_est, mon, broadcast, router, msg_router, logger, entropy_source, node_signer, signer_provider, config, chain, 42); 116 | 117 | LDKCVec_ChannelDetailsZ channels = ChannelManager_list_channels(&cm); 118 | assert((unsigned long)channels.data < 4096); // There's an offset, but it should still be an offset against null in the 0 page 119 | assert(channels.datalen == 0); 120 | CVec_ChannelDetailsZ_free(channels); 121 | 122 | LDKEventsProvider prov = ChannelManager_as_EventsProvider(&cm); 123 | // Check that no events were generated by asserting if any events are passed to never_handle_event. 124 | LDKEventHandler handler = { .handle_event = never_handle_event, .free = NULL }; 125 | (prov.process_pending_events)(prov.this_arg, handler); 126 | 127 | ChannelManager_free(cm); 128 | KeysManager_free(keys); 129 | 130 | // Check that passing empty vecs to rust doesn't blow it up: 131 | LDKCVec_MonitorEventZ empty_htlc_vec = { 132 | .data = NULL, 133 | .datalen = 0, 134 | }; 135 | CVec_MonitorEventZ_free(empty_htlc_vec); 136 | } 137 | -------------------------------------------------------------------------------- /lightning-c-bindings/src/lightning/mod.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history and in the source files from which this was generated. 3 | // 4 | // This file is licensed under the license available in the LICENSE or LICENSE.md 5 | // file in the root of this repository or, if no such file exists, the same 6 | // license as that which applies to the original source files from which this 7 | // source was automatically generated. 8 | 9 | //!lightning 10 | //! Rust-Lightning, not Rusty's Lightning! 11 | //! 12 | //! A full-featured but also flexible lightning implementation, in library form. This allows the 13 | //! user (you) to decide how they wish to use it instead of being a fully self-contained daemon. 14 | //! This means there is no built-in threading/execution environment and it's up to the user to 15 | //! figure out how best to make networking happen/timers fire/things get written to disk/keys get 16 | //! generated/etc. This makes it a good candidate for tight integration into an existing wallet 17 | //! instead of having a rather-separate lightning appendage to a wallet. 18 | //! 19 | //! `default` features are: 20 | //! 21 | //! * `std` - enables functionalities which require `std`, including `std::io` trait implementations and things which utilize time 22 | //! * `grind_signatures` - enables generation of [low-r bitcoin signatures](https://bitcoin.stackexchange.com/questions/111660/what-is-signature-grinding), 23 | //! which saves 1 byte per signature in 50% of the cases (see [bitcoin PR #13666](https://github.com/bitcoin/bitcoin/pull/13666)) 24 | //! 25 | //! Available features are: 26 | //! 27 | //! * `std` 28 | //! * `grind_signatures` 29 | 30 | use alloc::str::FromStr; 31 | use alloc::string::String; 32 | use core::ffi::c_void; 33 | use core::convert::Infallible; 34 | use bitcoin::hashes::Hash; 35 | use crate::c_types::*; 36 | #[cfg(feature="no-std")] 37 | use alloc::{vec::Vec, boxed::Box}; 38 | 39 | pub mod util; 40 | pub mod chain; 41 | pub mod ln; 42 | pub mod offers; 43 | pub mod routing; 44 | pub mod sign; 45 | pub mod onion_message; 46 | pub mod blinded_path; 47 | pub mod events; 48 | pub mod io; 49 | mod crypto { 50 | 51 | use alloc::str::FromStr; 52 | use alloc::string::String; 53 | use core::ffi::c_void; 54 | use core::convert::Infallible; 55 | use bitcoin::hashes::Hash; 56 | use crate::c_types::*; 57 | #[cfg(feature="no-std")] 58 | use alloc::{vec::Vec, boxed::Box}; 59 | 60 | mod chacha20 { 61 | 62 | use alloc::str::FromStr; 63 | use alloc::string::String; 64 | use core::ffi::c_void; 65 | use core::convert::Infallible; 66 | use bitcoin::hashes::Hash; 67 | use crate::c_types::*; 68 | #[cfg(feature="no-std")] 69 | use alloc::{vec::Vec, boxed::Box}; 70 | 71 | mod real_chacha { 72 | 73 | use alloc::str::FromStr; 74 | use alloc::string::String; 75 | use core::ffi::c_void; 76 | use core::convert::Infallible; 77 | use bitcoin::hashes::Hash; 78 | use crate::c_types::*; 79 | #[cfg(feature="no-std")] 80 | use alloc::{vec::Vec, boxed::Box}; 81 | 82 | } 83 | } 84 | mod chacha20poly1305rfc { 85 | 86 | use alloc::str::FromStr; 87 | use alloc::string::String; 88 | use core::ffi::c_void; 89 | use core::convert::Infallible; 90 | use bitcoin::hashes::Hash; 91 | use crate::c_types::*; 92 | #[cfg(feature="no-std")] 93 | use alloc::{vec::Vec, boxed::Box}; 94 | 95 | mod real_chachapoly { 96 | 97 | use alloc::str::FromStr; 98 | use alloc::string::String; 99 | use core::ffi::c_void; 100 | use core::convert::Infallible; 101 | use bitcoin::hashes::Hash; 102 | use crate::c_types::*; 103 | #[cfg(feature="no-std")] 104 | use alloc::{vec::Vec, boxed::Box}; 105 | 106 | } 107 | } 108 | mod poly1305 { 109 | 110 | use alloc::str::FromStr; 111 | use alloc::string::String; 112 | use core::ffi::c_void; 113 | use core::convert::Infallible; 114 | use bitcoin::hashes::Hash; 115 | use crate::c_types::*; 116 | #[cfg(feature="no-std")] 117 | use alloc::{vec::Vec, boxed::Box}; 118 | 119 | } 120 | mod streams { 121 | 122 | use alloc::str::FromStr; 123 | use alloc::string::String; 124 | use core::ffi::c_void; 125 | use core::convert::Infallible; 126 | use bitcoin::hashes::Hash; 127 | use crate::c_types::*; 128 | #[cfg(feature="no-std")] 129 | use alloc::{vec::Vec, boxed::Box}; 130 | 131 | } 132 | mod utils { 133 | 134 | use alloc::str::FromStr; 135 | use alloc::string::String; 136 | use core::ffi::c_void; 137 | use core::convert::Infallible; 138 | use bitcoin::hashes::Hash; 139 | use crate::c_types::*; 140 | #[cfg(feature="no-std")] 141 | use alloc::{vec::Vec, boxed::Box}; 142 | 143 | } 144 | } 145 | mod prelude { 146 | 147 | use alloc::str::FromStr; 148 | use alloc::string::String; 149 | use core::ffi::c_void; 150 | use core::convert::Infallible; 151 | use bitcoin::hashes::Hash; 152 | use crate::c_types::*; 153 | #[cfg(feature="no-std")] 154 | use alloc::{vec::Vec, boxed::Box}; 155 | 156 | } 157 | mod sync { 158 | 159 | use alloc::str::FromStr; 160 | use alloc::string::String; 161 | use core::ffi::c_void; 162 | use core::convert::Infallible; 163 | use bitcoin::hashes::Hash; 164 | use crate::c_types::*; 165 | #[cfg(feature="no-std")] 166 | use alloc::{vec::Vec, boxed::Box}; 167 | 168 | mod fairrwlock { 169 | 170 | use alloc::str::FromStr; 171 | use alloc::string::String; 172 | use core::ffi::c_void; 173 | use core::convert::Infallible; 174 | use bitcoin::hashes::Hash; 175 | use crate::c_types::*; 176 | #[cfg(feature="no-std")] 177 | use alloc::{vec::Vec, boxed::Box}; 178 | 179 | } 180 | mod ext_impl { 181 | 182 | use alloc::str::FromStr; 183 | use alloc::string::String; 184 | use core::ffi::c_void; 185 | use core::convert::Infallible; 186 | use bitcoin::hashes::Hash; 187 | use crate::c_types::*; 188 | #[cfg(feature="no-std")] 189 | use alloc::{vec::Vec, boxed::Box}; 190 | 191 | } 192 | } 193 | -------------------------------------------------------------------------------- /lightning-c-bindings/src/lightning/offers/nonce.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history and in the source files from which this was generated. 3 | // 4 | // This file is licensed under the license available in the LICENSE or LICENSE.md 5 | // file in the root of this repository or, if no such file exists, the same 6 | // license as that which applies to the original source files from which this 7 | // source was automatically generated. 8 | 9 | //! A number used only once. 10 | 11 | use alloc::str::FromStr; 12 | use alloc::string::String; 13 | use core::ffi::c_void; 14 | use core::convert::Infallible; 15 | use bitcoin::hashes::Hash; 16 | use crate::c_types::*; 17 | #[cfg(feature="no-std")] 18 | use alloc::{vec::Vec, boxed::Box}; 19 | 20 | 21 | use lightning::offers::nonce::Nonce as nativeNonceImport; 22 | pub(crate) type nativeNonce = nativeNonceImport; 23 | 24 | /// A 128-bit number used only once. 25 | /// 26 | /// Needed when constructing [`Offer::metadata`] and deriving [`Offer::issuer_signing_pubkey`] from 27 | /// [`ExpandedKey`]. Must not be reused for any other derivation without first hashing. 28 | /// 29 | /// [`Offer::metadata`]: crate::offers::offer::Offer::metadata 30 | /// [`Offer::issuer_signing_pubkey`]: crate::offers::offer::Offer::issuer_signing_pubkey 31 | /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey 32 | #[must_use] 33 | #[repr(C)] 34 | pub struct Nonce { 35 | /// A pointer to the opaque Rust object. 36 | 37 | /// Nearly everywhere, inner must be non-null, however in places where 38 | /// the Rust equivalent takes an Option, it may be set to null to indicate None. 39 | pub inner: *mut nativeNonce, 40 | /// Indicates that this is the only struct which contains the same pointer. 41 | 42 | /// Rust functions which take ownership of an object provided via an argument require 43 | /// this to be true and invalidate the object pointed to by inner. 44 | pub is_owned: bool, 45 | } 46 | 47 | impl core::ops::Deref for Nonce { 48 | type Target = nativeNonce; 49 | fn deref(&self) -> &Self::Target { unsafe { &*ObjOps::untweak_ptr(self.inner) } } 50 | } 51 | unsafe impl core::marker::Send for Nonce { } 52 | unsafe impl core::marker::Sync for Nonce { } 53 | impl Drop for Nonce { 54 | fn drop(&mut self) { 55 | if self.is_owned && !<*mut nativeNonce>::is_null(self.inner) { 56 | let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; 57 | } 58 | } 59 | } 60 | /// Frees any resources used by the Nonce, if is_owned is set and inner is non-NULL. 61 | #[no_mangle] 62 | pub extern "C" fn Nonce_free(this_obj: Nonce) { } 63 | #[allow(unused)] 64 | /// Used only if an object of this type is returned as a trait impl by a method 65 | pub(crate) extern "C" fn Nonce_free_void(this_ptr: *mut c_void) { 66 | let _ = unsafe { Box::from_raw(this_ptr as *mut nativeNonce) }; 67 | } 68 | #[allow(unused)] 69 | impl Nonce { 70 | pub(crate) fn get_native_ref(&self) -> &'static nativeNonce { 71 | unsafe { &*ObjOps::untweak_ptr(self.inner) } 72 | } 73 | pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeNonce { 74 | unsafe { &mut *ObjOps::untweak_ptr(self.inner) } 75 | } 76 | /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy 77 | pub(crate) fn take_inner(mut self) -> *mut nativeNonce { 78 | assert!(self.is_owned); 79 | let ret = ObjOps::untweak_ptr(self.inner); 80 | self.inner = core::ptr::null_mut(); 81 | ret 82 | } 83 | pub(crate) fn as_ref_to(&self) -> Self { 84 | Self { inner: self.inner, is_owned: false } 85 | } 86 | } 87 | impl Clone for Nonce { 88 | fn clone(&self) -> Self { 89 | Self { 90 | inner: if <*mut nativeNonce>::is_null(self.inner) { core::ptr::null_mut() } else { 91 | ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, 92 | is_owned: true, 93 | } 94 | } 95 | } 96 | #[allow(unused)] 97 | /// Used only if an object of this type is returned as a trait impl by a method 98 | pub(crate) extern "C" fn Nonce_clone_void(this_ptr: *const c_void) -> *mut c_void { 99 | Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativeNonce)).clone() })) as *mut c_void 100 | } 101 | #[no_mangle] 102 | /// Creates a copy of the Nonce 103 | pub extern "C" fn Nonce_clone(orig: &Nonce) -> Nonce { 104 | orig.clone() 105 | } 106 | /// Get a string which allows debug introspection of a Nonce object 107 | pub extern "C" fn Nonce_debug_str_void(o: *const c_void) -> Str { 108 | alloc::format!("{:?}", unsafe { o as *const crate::lightning::offers::nonce::Nonce }).into()} 109 | /// Checks if two Nonces contain equal inner contents. 110 | /// This ignores pointers and is_owned flags and looks at the values in fields. 111 | /// Two objects with NULL inner values will be considered "equal" here. 112 | #[no_mangle] 113 | pub extern "C" fn Nonce_eq(a: &Nonce, b: &Nonce) -> bool { 114 | if a.inner == b.inner { return true; } 115 | if a.inner.is_null() || b.inner.is_null() { return false; } 116 | if a.get_native_ref() == b.get_native_ref() { true } else { false } 117 | } 118 | /// Creates a `Nonce` from the given [`EntropySource`]. 119 | #[must_use] 120 | #[no_mangle] 121 | pub extern "C" fn Nonce_from_entropy_source(mut entropy_source: crate::lightning::sign::EntropySource) -> crate::lightning::offers::nonce::Nonce { 122 | let mut ret = lightning::offers::nonce::Nonce::from_entropy_source(entropy_source); 123 | crate::lightning::offers::nonce::Nonce { inner: ObjOps::heap_alloc(ret), is_owned: true } 124 | } 125 | 126 | /// Returns a slice of the underlying bytes of size [`Nonce::LENGTH`]. 127 | #[must_use] 128 | #[no_mangle] 129 | pub extern "C" fn Nonce_as_slice(this_arg: &crate::lightning::offers::nonce::Nonce) -> crate::c_types::u8slice { 130 | let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.as_slice(); 131 | let mut local_ret = crate::c_types::u8slice::from_slice(ret); 132 | local_ret 133 | } 134 | 135 | #[no_mangle] 136 | /// Serialize the Nonce object into a byte array which can be read by Nonce_read 137 | pub extern "C" fn Nonce_write(obj: &crate::lightning::offers::nonce::Nonce) -> crate::c_types::derived::CVec_u8Z { 138 | crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) 139 | } 140 | #[allow(unused)] 141 | pub(crate) extern "C" fn Nonce_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { 142 | crate::c_types::serialize_obj(unsafe { &*(obj as *const crate::lightning::offers::nonce::nativeNonce) }) 143 | } 144 | #[no_mangle] 145 | /// Read a Nonce from a byte array, created by Nonce_write 146 | pub extern "C" fn Nonce_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_NonceDecodeErrorZ { 147 | let res: Result = crate::c_types::deserialize_obj(ser); 148 | let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::offers::nonce::Nonce { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() }; 149 | local_res 150 | } 151 | -------------------------------------------------------------------------------- /lightning-c-bindings/src/lightning/util/scid_utils.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history and in the source files from which this was generated. 3 | // 4 | // This file is licensed under the license available in the LICENSE or LICENSE.md 5 | // file in the root of this repository or, if no such file exists, the same 6 | // license as that which applies to the original source files from which this 7 | // source was automatically generated. 8 | 9 | //! Utilities for creating and parsing short channel ids. 10 | 11 | use alloc::str::FromStr; 12 | use alloc::string::String; 13 | use core::ffi::c_void; 14 | use core::convert::Infallible; 15 | use bitcoin::hashes::Hash; 16 | use crate::c_types::*; 17 | #[cfg(feature="no-std")] 18 | use alloc::{vec::Vec, boxed::Box}; 19 | 20 | /// Maximum block height that can be used in a `short_channel_id`. This 21 | /// value is based on the 3-bytes available for block height. 22 | 23 | #[no_mangle] 24 | pub static MAX_SCID_BLOCK: u64 = lightning::util::scid_utils::MAX_SCID_BLOCK; 25 | /// Maximum transaction index that can be used in a `short_channel_id`. 26 | /// This value is based on the 3-bytes available for tx index. 27 | 28 | #[no_mangle] 29 | pub static MAX_SCID_TX_INDEX: u64 = lightning::util::scid_utils::MAX_SCID_TX_INDEX; 30 | /// Maximum vout index that can be used in a `short_channel_id`. This 31 | /// value is based on the 2-bytes available for the vout index. 32 | 33 | #[no_mangle] 34 | pub static MAX_SCID_VOUT_INDEX: u64 = lightning::util::scid_utils::MAX_SCID_VOUT_INDEX; 35 | /// A `short_channel_id` construction error 36 | #[derive(Clone)] 37 | #[must_use] 38 | #[repr(C)] 39 | pub enum ShortChannelIdError { 40 | /// Block height too high 41 | BlockOverflow, 42 | /// Tx index too high 43 | TxIndexOverflow, 44 | /// Vout index too high 45 | VoutIndexOverflow, 46 | } 47 | use lightning::util::scid_utils::ShortChannelIdError as ShortChannelIdErrorImport; 48 | pub(crate) type nativeShortChannelIdError = ShortChannelIdErrorImport; 49 | 50 | impl ShortChannelIdError { 51 | #[allow(unused)] 52 | pub(crate) fn to_native(&self) -> nativeShortChannelIdError { 53 | match self { 54 | ShortChannelIdError::BlockOverflow => nativeShortChannelIdError::BlockOverflow, 55 | ShortChannelIdError::TxIndexOverflow => nativeShortChannelIdError::TxIndexOverflow, 56 | ShortChannelIdError::VoutIndexOverflow => nativeShortChannelIdError::VoutIndexOverflow, 57 | } 58 | } 59 | #[allow(unused)] 60 | pub(crate) fn into_native(self) -> nativeShortChannelIdError { 61 | match self { 62 | ShortChannelIdError::BlockOverflow => nativeShortChannelIdError::BlockOverflow, 63 | ShortChannelIdError::TxIndexOverflow => nativeShortChannelIdError::TxIndexOverflow, 64 | ShortChannelIdError::VoutIndexOverflow => nativeShortChannelIdError::VoutIndexOverflow, 65 | } 66 | } 67 | #[allow(unused)] 68 | pub(crate) fn from_native(native: &ShortChannelIdErrorImport) -> Self { 69 | let native = unsafe { &*(native as *const _ as *const c_void as *const nativeShortChannelIdError) }; 70 | match native { 71 | nativeShortChannelIdError::BlockOverflow => ShortChannelIdError::BlockOverflow, 72 | nativeShortChannelIdError::TxIndexOverflow => ShortChannelIdError::TxIndexOverflow, 73 | nativeShortChannelIdError::VoutIndexOverflow => ShortChannelIdError::VoutIndexOverflow, 74 | } 75 | } 76 | #[allow(unused)] 77 | pub(crate) fn native_into(native: nativeShortChannelIdError) -> Self { 78 | match native { 79 | nativeShortChannelIdError::BlockOverflow => ShortChannelIdError::BlockOverflow, 80 | nativeShortChannelIdError::TxIndexOverflow => ShortChannelIdError::TxIndexOverflow, 81 | nativeShortChannelIdError::VoutIndexOverflow => ShortChannelIdError::VoutIndexOverflow, 82 | } 83 | } 84 | } 85 | /// Creates a copy of the ShortChannelIdError 86 | #[no_mangle] 87 | pub extern "C" fn ShortChannelIdError_clone(orig: &ShortChannelIdError) -> ShortChannelIdError { 88 | orig.clone() 89 | } 90 | #[allow(unused)] 91 | /// Used only if an object of this type is returned as a trait impl by a method 92 | pub(crate) extern "C" fn ShortChannelIdError_clone_void(this_ptr: *const c_void) -> *mut c_void { 93 | Box::into_raw(Box::new(unsafe { (*(this_ptr as *const ShortChannelIdError)).clone() })) as *mut c_void 94 | } 95 | #[allow(unused)] 96 | /// Used only if an object of this type is returned as a trait impl by a method 97 | pub(crate) extern "C" fn ShortChannelIdError_free_void(this_ptr: *mut c_void) { 98 | let _ = unsafe { Box::from_raw(this_ptr as *mut ShortChannelIdError) }; 99 | } 100 | #[no_mangle] 101 | /// Utility method to constructs a new BlockOverflow-variant ShortChannelIdError 102 | pub extern "C" fn ShortChannelIdError_block_overflow() -> ShortChannelIdError { 103 | ShortChannelIdError::BlockOverflow} 104 | #[no_mangle] 105 | /// Utility method to constructs a new TxIndexOverflow-variant ShortChannelIdError 106 | pub extern "C" fn ShortChannelIdError_tx_index_overflow() -> ShortChannelIdError { 107 | ShortChannelIdError::TxIndexOverflow} 108 | #[no_mangle] 109 | /// Utility method to constructs a new VoutIndexOverflow-variant ShortChannelIdError 110 | pub extern "C" fn ShortChannelIdError_vout_index_overflow() -> ShortChannelIdError { 111 | ShortChannelIdError::VoutIndexOverflow} 112 | /// Get a string which allows debug introspection of a ShortChannelIdError object 113 | pub extern "C" fn ShortChannelIdError_debug_str_void(o: *const c_void) -> Str { 114 | alloc::format!("{:?}", unsafe { o as *const crate::lightning::util::scid_utils::ShortChannelIdError }).into()} 115 | /// Checks if two ShortChannelIdErrors contain equal inner contents. 116 | /// This ignores pointers and is_owned flags and looks at the values in fields. 117 | #[no_mangle] 118 | pub extern "C" fn ShortChannelIdError_eq(a: &ShortChannelIdError, b: &ShortChannelIdError) -> bool { 119 | if &a.to_native() == &b.to_native() { true } else { false } 120 | } 121 | /// Extracts the block height (most significant 3-bytes) from the `short_channel_id` 122 | #[no_mangle] 123 | pub extern "C" fn block_from_scid(mut short_channel_id: u64) -> u32 { 124 | let mut ret = lightning::util::scid_utils::block_from_scid(short_channel_id); 125 | ret 126 | } 127 | 128 | /// Extracts the tx index (bytes [2..4]) from the `short_channel_id` 129 | #[no_mangle] 130 | pub extern "C" fn tx_index_from_scid(mut short_channel_id: u64) -> u32 { 131 | let mut ret = lightning::util::scid_utils::tx_index_from_scid(short_channel_id); 132 | ret 133 | } 134 | 135 | /// Extracts the vout (bytes [0..2]) from the `short_channel_id` 136 | #[no_mangle] 137 | pub extern "C" fn vout_from_scid(mut short_channel_id: u64) -> u16 { 138 | let mut ret = lightning::util::scid_utils::vout_from_scid(short_channel_id); 139 | ret 140 | } 141 | 142 | /// Constructs a `short_channel_id` using the components pieces. Results in an error 143 | /// if the block height, tx index, or vout index overflow the maximum sizes. 144 | #[no_mangle] 145 | pub extern "C" fn scid_from_parts(mut block: u64, mut tx_index: u64, mut vout_index: u64) -> crate::c_types::derived::CResult_u64ShortChannelIdErrorZ { 146 | let mut ret = lightning::util::scid_utils::scid_from_parts(block, tx_index, vout_index); 147 | 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::scid_utils::ShortChannelIdError::native_into(e) }).into() }; 148 | local_ret 149 | } 150 | 151 | mod fake_scid { 152 | 153 | use alloc::str::FromStr; 154 | use alloc::string::String; 155 | use core::ffi::c_void; 156 | use core::convert::Infallible; 157 | use bitcoin::hashes::Hash; 158 | use crate::c_types::*; 159 | #[cfg(feature="no-std")] 160 | use alloc::{vec::Vec, boxed::Box}; 161 | 162 | } 163 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Continuous Integration Checks 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | check_bindings: 7 | strategy: 8 | fail-fast: false 9 | matrix: 10 | # Ubuntu's version of rustc uses its own LLVM instead of being a real native package. 11 | # This leaves us with an incompatible LLVM version when linking. Instead, use a real OS. 12 | distro: [ "debian:bookworm", "fedora:41" ] 13 | runs-on: ubuntu-latest 14 | container: ${{ matrix.distro }} 15 | env: 16 | TOOLCHAIN: stable 17 | steps: 18 | - name: Install native Rust toolchain, Valgrind, and build utilitis 19 | if: "matrix.distro == 'debian:bookworm'" 20 | run: | 21 | apt-get update 22 | apt-get -y dist-upgrade 23 | apt-get -y install cargo libstd-rust-dev-wasm32 wasi-libc valgrind lld git g++ clang wget 24 | - name: Install native Rust toolchain, Valgrind, and build utilitis 25 | if: "matrix.distro == 'fedora:41'" 26 | run: | 27 | dnf -y install cargo rust-std-static-wasm32-wasi valgrind lld git g++ clang wget which diffutils 28 | - name: Checkout source code 29 | uses: actions/checkout@v2 30 | with: 31 | fetch-depth: 0 32 | - name: Sanity test bindings against Cargo.toml RL 33 | working-directory: lightning-c-bindings 34 | run: | 35 | # Note that the version tags aren't checked into git 36 | touch src/version.rs 37 | RUSTFLAGS="--cfg=c_bindings" cargo check --features std 38 | - name: Install cbindgen 39 | run: | 40 | git clone https://github.com/eqrion/cbindgen 41 | cd cbindgen/ 42 | git checkout v0.20.0 43 | cargo update -p indexmap --precise "1.6.2" --verbose 44 | cargo install --locked --path . 45 | - name: Checkout Rust-Lightning git 46 | run: | 47 | git clone https://github.com/rust-bitcoin/rust-lightning 48 | cd rust-lightning 49 | git checkout 0.1-bindings 50 | - name: Fix Github Actions to not be broken 51 | run: git config --global --add safe.directory /__w/ldk-c-bindings/ldk-c-bindings 52 | - name: Pin proc-macro and quote to meet MSRV 53 | run: | 54 | cd c-bindings-gen 55 | cargo update -p quote --precise "1.0.30" --verbose 56 | cargo update -p proc-macro2 --precise "1.0.65" --verbose 57 | - name: Rebuild bindings without std, and check the sample app builds + links 58 | run: ./genbindings.sh ./rust-lightning false 59 | - name: Rebuild bindings, and check the sample app builds + links 60 | run: ./genbindings.sh ./rust-lightning true 61 | - name: Check that the latest bindings are in git 62 | run: | 63 | git checkout lightning-c-bindings/Cargo.toml # genbindings edits this to update the path 64 | if [ "$(git diff)" != "" ]; then 65 | # cbindgen's bindings output order can be FS-dependant, so check that the lines are all the same: 66 | mv lightning-c-bindings/include/lightning.h lightning-c-bindings/include/lightning.h.new 67 | git checkout lightning-c-bindings/include/lightning.h 68 | cat lightning-c-bindings/include/lightning.h | grep -v "Generated with cbindgen:[0-9\.]*" | sort > lightning-c-bindings/include/lightning.h.sorted 69 | cat lightning-c-bindings/include/lightning.h.new | grep -v "Generated with cbindgen:[0-9\.]*" | sort > lightning-c-bindings/include/lightning.h.new.sorted 70 | diff lightning-c-bindings/include/lightning.h.sorted lightning-c-bindings/include/lightning.h.new.sorted 71 | [ "$(diff lightning-c-bindings/include/lightning.h.sorted lightning-c-bindings/include/lightning.h.new.sorted)" != "" ] && exit 2 72 | git diff --exit-code 73 | fi 74 | 75 | check_macos: 76 | runs-on: ubuntu-latest 77 | # Ubuntu's version of rustc uses its own LLVM instead of being a real native package. 78 | # This leaves us with an incompatible LLVM version when linking. Instead, use a real OS. 79 | container: debian:bookworm 80 | env: 81 | TOOLCHAIN: stable 82 | steps: 83 | - name: Install native Rust toolchain, Valgrind, and build utilitis 84 | run: | 85 | apt-get update 86 | apt-get -y dist-upgrade 87 | apt-get -y install cargo libstd-rust-dev-wasm32 valgrind lld git g++ clang wget rust-src 88 | - name: Checkout source code 89 | uses: actions/checkout@v2 90 | with: 91 | fetch-depth: 0 92 | - name: Sanity test bindings against Cargo.toml RL 93 | working-directory: lightning-c-bindings 94 | run: | 95 | # Note that the version tags aren't checked into git 96 | touch src/version.rs 97 | RUSTFLAGS="--cfg=c_bindings" cargo check --features std 98 | - name: Install cbindgen 99 | run: | 100 | git clone https://github.com/eqrion/cbindgen 101 | cd cbindgen/ 102 | git checkout v0.20.0 103 | cargo update -p indexmap --precise "1.6.2" --verbose 104 | cargo install --locked --path . 105 | - name: Checkout Rust-Lightning git 106 | run: | 107 | git clone https://github.com/rust-bitcoin/rust-lightning 108 | cd rust-lightning 109 | git checkout 0.1-bindings 110 | - name: Fix Github Actions to not be broken 111 | run: git config --global --add safe.directory /__w/ldk-c-bindings/ldk-c-bindings 112 | - name: Fetch MacOS SDK 113 | run: | 114 | wget https://bitcoincore.org/depends-sources/sdks/Xcode-12.2-12B45b-extracted-SDK-with-libcxx-headers.tar.gz 115 | tar xvvf Xcode-12.2-12B45b-extracted-SDK-with-libcxx-headers.tar.gz 116 | - name: Rebuild bindings, and check the sample app builds + links 117 | run: | 118 | # rust-src doesn't distribute the rustlib Cargo.lock, but an empty 119 | # file seems to suffice to make `-Zbuild-std` happy. 120 | touch /usr/lib/rustlib/src/rust/Cargo.lock 121 | MACOS_SDK="$PWD/Xcode-12.2-12B45b-extracted-SDK-with-libcxx-headers" ./genbindings.sh ./rust-lightning true 122 | 123 | osx: 124 | strategy: 125 | matrix: 126 | include: 127 | - platform: macos-13 128 | - platform: macos-latest 129 | runs-on: ${{ matrix.platform }} 130 | env: 131 | TOOLCHAIN: stable 132 | steps: 133 | - name: Install other Rust platforms 134 | run: rustup target install aarch64-apple-darwin 135 | - name: Fetch upstream LLVM/clang snapshot 136 | run: | 137 | wget -O clang+llvm-15.0.3-x86_64-apple-darwin.tar.xz https://github.com/llvm/llvm-project/releases/download/llvmorg-15.0.3/clang+llvm-15.0.3-x86_64-apple-darwin.tar.xz 138 | if [ "$(shasum -a 256 clang+llvm-15.0.3-x86_64-apple-darwin.tar.xz | awk '{ print $1 }')" != "ac668586b2b3d068f1e43520a3ef0b1592e5dc3eff1a4a4b772e29803b428a69" ]; then 139 | echo "Bad hash" 140 | exit 1 141 | fi 142 | - name: Unpack upstream LLVM+clang and use it by default 143 | run: | 144 | tar xvvf clang+llvm-15.0.3-x86_64-apple-darwin.tar.xz 145 | - name: Checkout source code 146 | uses: actions/checkout@v2 147 | with: 148 | fetch-depth: 0 149 | - name: Install cbindgen 150 | run: cargo install cbindgen 151 | - name: Checkout Rust-Lightning git 152 | run: | 153 | git clone https://github.com/rust-bitcoin/rust-lightning 154 | cd rust-lightning 155 | git checkout 0.1-bindings 156 | - name: Rebuild bindings using Apple clang, and check the sample app builds + links 157 | run: ./genbindings.sh ./rust-lightning true 158 | - name: Rebuild bindings using upstream clang, and check the sample app builds + links 159 | run: | 160 | export PATH=`pwd`/clang+llvm-15.0.3-x86_64-apple-darwin/bin:$PATH 161 | CC=clang ./genbindings.sh ./rust-lightning true 162 | -------------------------------------------------------------------------------- /lightning-c-bindings/src/lightning/chain/transaction.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history and in the source files from which this was generated. 3 | // 4 | // This file is licensed under the license available in the LICENSE or LICENSE.md 5 | // file in the root of this repository or, if no such file exists, the same 6 | // license as that which applies to the original source files from which this 7 | // source was automatically generated. 8 | 9 | //! Types describing on-chain transactions. 10 | 11 | use alloc::str::FromStr; 12 | use alloc::string::String; 13 | use core::ffi::c_void; 14 | use core::convert::Infallible; 15 | use bitcoin::hashes::Hash; 16 | use crate::c_types::*; 17 | #[cfg(feature="no-std")] 18 | use alloc::{vec::Vec, boxed::Box}; 19 | 20 | 21 | use lightning::chain::transaction::OutPoint as nativeOutPointImport; 22 | pub(crate) type nativeOutPoint = nativeOutPointImport; 23 | 24 | /// A reference to a transaction output. 25 | /// 26 | /// Differs from bitcoin::transaction::OutPoint as the index is a u16 instead of u32 27 | /// due to LN's restrictions on index values. Should reduce (possibly) unsafe conversions this way. 28 | #[must_use] 29 | #[repr(C)] 30 | pub struct OutPoint { 31 | /// A pointer to the opaque Rust object. 32 | 33 | /// Nearly everywhere, inner must be non-null, however in places where 34 | /// the Rust equivalent takes an Option, it may be set to null to indicate None. 35 | pub inner: *mut nativeOutPoint, 36 | /// Indicates that this is the only struct which contains the same pointer. 37 | 38 | /// Rust functions which take ownership of an object provided via an argument require 39 | /// this to be true and invalidate the object pointed to by inner. 40 | pub is_owned: bool, 41 | } 42 | 43 | impl core::ops::Deref for OutPoint { 44 | type Target = nativeOutPoint; 45 | fn deref(&self) -> &Self::Target { unsafe { &*ObjOps::untweak_ptr(self.inner) } } 46 | } 47 | unsafe impl core::marker::Send for OutPoint { } 48 | unsafe impl core::marker::Sync for OutPoint { } 49 | impl Drop for OutPoint { 50 | fn drop(&mut self) { 51 | if self.is_owned && !<*mut nativeOutPoint>::is_null(self.inner) { 52 | let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; 53 | } 54 | } 55 | } 56 | /// Frees any resources used by the OutPoint, if is_owned is set and inner is non-NULL. 57 | #[no_mangle] 58 | pub extern "C" fn OutPoint_free(this_obj: OutPoint) { } 59 | #[allow(unused)] 60 | /// Used only if an object of this type is returned as a trait impl by a method 61 | pub(crate) extern "C" fn OutPoint_free_void(this_ptr: *mut c_void) { 62 | let _ = unsafe { Box::from_raw(this_ptr as *mut nativeOutPoint) }; 63 | } 64 | #[allow(unused)] 65 | impl OutPoint { 66 | pub(crate) fn get_native_ref(&self) -> &'static nativeOutPoint { 67 | unsafe { &*ObjOps::untweak_ptr(self.inner) } 68 | } 69 | pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeOutPoint { 70 | unsafe { &mut *ObjOps::untweak_ptr(self.inner) } 71 | } 72 | /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy 73 | pub(crate) fn take_inner(mut self) -> *mut nativeOutPoint { 74 | assert!(self.is_owned); 75 | let ret = ObjOps::untweak_ptr(self.inner); 76 | self.inner = core::ptr::null_mut(); 77 | ret 78 | } 79 | pub(crate) fn as_ref_to(&self) -> Self { 80 | Self { inner: self.inner, is_owned: false } 81 | } 82 | } 83 | /// The referenced transaction's txid. 84 | #[no_mangle] 85 | pub extern "C" fn OutPoint_get_txid(this_ptr: &OutPoint) -> *const [u8; 32] { 86 | let mut inner_val = &mut this_ptr.get_native_mut_ref().txid; 87 | inner_val.as_ref() 88 | } 89 | /// The referenced transaction's txid. 90 | #[no_mangle] 91 | pub extern "C" fn OutPoint_set_txid(this_ptr: &mut OutPoint, mut val: crate::c_types::ThirtyTwoBytes) { 92 | unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.txid = ::bitcoin::hash_types::Txid::from_slice(&val.data[..]).unwrap(); 93 | } 94 | /// The index of the referenced output in its transaction's vout. 95 | #[no_mangle] 96 | pub extern "C" fn OutPoint_get_index(this_ptr: &OutPoint) -> u16 { 97 | let mut inner_val = &mut this_ptr.get_native_mut_ref().index; 98 | *inner_val 99 | } 100 | /// The index of the referenced output in its transaction's vout. 101 | #[no_mangle] 102 | pub extern "C" fn OutPoint_set_index(this_ptr: &mut OutPoint, mut val: u16) { 103 | unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.index = val; 104 | } 105 | /// Constructs a new OutPoint given each field 106 | #[must_use] 107 | #[no_mangle] 108 | pub extern "C" fn OutPoint_new(mut txid_arg: crate::c_types::ThirtyTwoBytes, mut index_arg: u16) -> OutPoint { 109 | OutPoint { inner: ObjOps::heap_alloc(nativeOutPoint { 110 | txid: ::bitcoin::hash_types::Txid::from_slice(&txid_arg.data[..]).unwrap(), 111 | index: index_arg, 112 | }), is_owned: true } 113 | } 114 | impl Clone for OutPoint { 115 | fn clone(&self) -> Self { 116 | Self { 117 | inner: if <*mut nativeOutPoint>::is_null(self.inner) { core::ptr::null_mut() } else { 118 | ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, 119 | is_owned: true, 120 | } 121 | } 122 | } 123 | #[allow(unused)] 124 | /// Used only if an object of this type is returned as a trait impl by a method 125 | pub(crate) extern "C" fn OutPoint_clone_void(this_ptr: *const c_void) -> *mut c_void { 126 | Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativeOutPoint)).clone() })) as *mut c_void 127 | } 128 | #[no_mangle] 129 | /// Creates a copy of the OutPoint 130 | pub extern "C" fn OutPoint_clone(orig: &OutPoint) -> OutPoint { 131 | orig.clone() 132 | } 133 | /// Checks if two OutPoints contain equal inner contents. 134 | /// This ignores pointers and is_owned flags and looks at the values in fields. 135 | /// Two objects with NULL inner values will be considered "equal" here. 136 | #[no_mangle] 137 | pub extern "C" fn OutPoint_eq(a: &OutPoint, b: &OutPoint) -> bool { 138 | if a.inner == b.inner { return true; } 139 | if a.inner.is_null() || b.inner.is_null() { return false; } 140 | if a.get_native_ref() == b.get_native_ref() { true } else { false } 141 | } 142 | /// Get a string which allows debug introspection of a OutPoint object 143 | pub extern "C" fn OutPoint_debug_str_void(o: *const c_void) -> Str { 144 | alloc::format!("{:?}", unsafe { o as *const crate::lightning::chain::transaction::OutPoint }).into()} 145 | /// Generates a non-cryptographic 64-bit hash of the OutPoint. 146 | #[no_mangle] 147 | pub extern "C" fn OutPoint_hash(o: &OutPoint) -> u64 { 148 | if o.inner.is_null() { return 0; } 149 | // Note that we'd love to use alloc::collections::hash_map::DefaultHasher but it's not in core 150 | #[allow(deprecated)] 151 | let mut hasher = core::hash::SipHasher::new(); 152 | core::hash::Hash::hash(o.get_native_ref(), &mut hasher); 153 | core::hash::Hasher::finish(&hasher) 154 | } 155 | #[no_mangle] 156 | /// Get the string representation of a OutPoint object 157 | pub extern "C" fn OutPoint_to_str(o: &crate::lightning::chain::transaction::OutPoint) -> Str { 158 | alloc::format!("{}", o.get_native_ref()).into() 159 | } 160 | #[no_mangle] 161 | /// Serialize the OutPoint object into a byte array which can be read by OutPoint_read 162 | pub extern "C" fn OutPoint_write(obj: &crate::lightning::chain::transaction::OutPoint) -> crate::c_types::derived::CVec_u8Z { 163 | crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) 164 | } 165 | #[allow(unused)] 166 | pub(crate) extern "C" fn OutPoint_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { 167 | crate::c_types::serialize_obj(unsafe { &*(obj as *const crate::lightning::chain::transaction::nativeOutPoint) }) 168 | } 169 | #[no_mangle] 170 | /// Read a OutPoint from a byte array, created by OutPoint_write 171 | pub extern "C" fn OutPoint_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_OutPointDecodeErrorZ { 172 | let res: Result = crate::c_types::deserialize_obj(ser); 173 | let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() }; 174 | local_res 175 | } 176 | -------------------------------------------------------------------------------- /lightning-c-bindings/src/lightning/offers/merkle.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history and in the source files from which this was generated. 3 | // 4 | // This file is licensed under the license available in the LICENSE or LICENSE.md 5 | // file in the root of this repository or, if no such file exists, the same 6 | // license as that which applies to the original source files from which this 7 | // source was automatically generated. 8 | 9 | //! Tagged hashes for use in signature calculation and verification. 10 | 11 | use alloc::str::FromStr; 12 | use alloc::string::String; 13 | use core::ffi::c_void; 14 | use core::convert::Infallible; 15 | use bitcoin::hashes::Hash; 16 | use crate::c_types::*; 17 | #[cfg(feature="no-std")] 18 | use alloc::{vec::Vec, boxed::Box}; 19 | 20 | 21 | use lightning::offers::merkle::TaggedHash as nativeTaggedHashImport; 22 | pub(crate) type nativeTaggedHash = nativeTaggedHashImport; 23 | 24 | /// A hash for use in a specific context by tweaking with a context-dependent tag as per [BIP 340] 25 | /// and computed over the merkle root of a TLV stream to sign as defined in [BOLT 12]. 26 | /// 27 | /// [BIP 340]: https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki 28 | /// [BOLT 12]: https://github.com/rustyrussell/lightning-rfc/blob/guilt/offers/12-offer-encoding.md#signature-calculation 29 | #[must_use] 30 | #[repr(C)] 31 | pub struct TaggedHash { 32 | /// A pointer to the opaque Rust object. 33 | 34 | /// Nearly everywhere, inner must be non-null, however in places where 35 | /// the Rust equivalent takes an Option, it may be set to null to indicate None. 36 | pub inner: *mut nativeTaggedHash, 37 | /// Indicates that this is the only struct which contains the same pointer. 38 | 39 | /// Rust functions which take ownership of an object provided via an argument require 40 | /// this to be true and invalidate the object pointed to by inner. 41 | pub is_owned: bool, 42 | } 43 | 44 | impl core::ops::Deref for TaggedHash { 45 | type Target = nativeTaggedHash; 46 | fn deref(&self) -> &Self::Target { unsafe { &*ObjOps::untweak_ptr(self.inner) } } 47 | } 48 | unsafe impl core::marker::Send for TaggedHash { } 49 | unsafe impl core::marker::Sync for TaggedHash { } 50 | impl Drop for TaggedHash { 51 | fn drop(&mut self) { 52 | if self.is_owned && !<*mut nativeTaggedHash>::is_null(self.inner) { 53 | let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; 54 | } 55 | } 56 | } 57 | /// Frees any resources used by the TaggedHash, if is_owned is set and inner is non-NULL. 58 | #[no_mangle] 59 | pub extern "C" fn TaggedHash_free(this_obj: TaggedHash) { } 60 | #[allow(unused)] 61 | /// Used only if an object of this type is returned as a trait impl by a method 62 | pub(crate) extern "C" fn TaggedHash_free_void(this_ptr: *mut c_void) { 63 | let _ = unsafe { Box::from_raw(this_ptr as *mut nativeTaggedHash) }; 64 | } 65 | #[allow(unused)] 66 | impl TaggedHash { 67 | pub(crate) fn get_native_ref(&self) -> &'static nativeTaggedHash { 68 | unsafe { &*ObjOps::untweak_ptr(self.inner) } 69 | } 70 | pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeTaggedHash { 71 | unsafe { &mut *ObjOps::untweak_ptr(self.inner) } 72 | } 73 | /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy 74 | pub(crate) fn take_inner(mut self) -> *mut nativeTaggedHash { 75 | assert!(self.is_owned); 76 | let ret = ObjOps::untweak_ptr(self.inner); 77 | self.inner = core::ptr::null_mut(); 78 | ret 79 | } 80 | pub(crate) fn as_ref_to(&self) -> Self { 81 | Self { inner: self.inner, is_owned: false } 82 | } 83 | } 84 | impl Clone for TaggedHash { 85 | fn clone(&self) -> Self { 86 | Self { 87 | inner: if <*mut nativeTaggedHash>::is_null(self.inner) { core::ptr::null_mut() } else { 88 | ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, 89 | is_owned: true, 90 | } 91 | } 92 | } 93 | #[allow(unused)] 94 | /// Used only if an object of this type is returned as a trait impl by a method 95 | pub(crate) extern "C" fn TaggedHash_clone_void(this_ptr: *const c_void) -> *mut c_void { 96 | Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativeTaggedHash)).clone() })) as *mut c_void 97 | } 98 | #[no_mangle] 99 | /// Creates a copy of the TaggedHash 100 | pub extern "C" fn TaggedHash_clone(orig: &TaggedHash) -> TaggedHash { 101 | orig.clone() 102 | } 103 | /// Get a string which allows debug introspection of a TaggedHash object 104 | pub extern "C" fn TaggedHash_debug_str_void(o: *const c_void) -> Str { 105 | alloc::format!("{:?}", unsafe { o as *const crate::lightning::offers::merkle::TaggedHash }).into()} 106 | /// Returns the digest to sign. 107 | #[must_use] 108 | #[no_mangle] 109 | pub extern "C" fn TaggedHash_as_digest(this_arg: &crate::lightning::offers::merkle::TaggedHash) -> *const [u8; 32] { 110 | let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.as_digest(); 111 | ret.as_ref() 112 | } 113 | 114 | /// Returns the tag used in the tagged hash. 115 | #[must_use] 116 | #[no_mangle] 117 | pub extern "C" fn TaggedHash_tag(this_arg: &crate::lightning::offers::merkle::TaggedHash) -> crate::c_types::Str { 118 | let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.tag(); 119 | ret.into() 120 | } 121 | 122 | /// Returns the merkle root used in the tagged hash. 123 | #[must_use] 124 | #[no_mangle] 125 | pub extern "C" fn TaggedHash_merkle_root(this_arg: &crate::lightning::offers::merkle::TaggedHash) -> crate::c_types::ThirtyTwoBytes { 126 | let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.merkle_root(); 127 | crate::c_types::ThirtyTwoBytes { data: *ret.as_ref() } 128 | } 129 | 130 | /// Error when signing messages. 131 | #[derive(Clone)] 132 | #[must_use] 133 | #[repr(C)] 134 | pub enum SignError { 135 | /// User-defined error when signing the message. 136 | Signing, 137 | /// Error when verifying the produced signature using the given pubkey. 138 | Verification( 139 | crate::c_types::Secp256k1Error), 140 | } 141 | use lightning::offers::merkle::SignError as SignErrorImport; 142 | pub(crate) type nativeSignError = SignErrorImport; 143 | 144 | impl SignError { 145 | #[allow(unused)] 146 | pub(crate) fn to_native(&self) -> nativeSignError { 147 | match self { 148 | SignError::Signing => nativeSignError::Signing, 149 | SignError::Verification (ref a, ) => { 150 | let mut a_nonref = Clone::clone(a); 151 | nativeSignError::Verification ( 152 | a_nonref.into_rust(), 153 | ) 154 | }, 155 | } 156 | } 157 | #[allow(unused)] 158 | pub(crate) fn into_native(self) -> nativeSignError { 159 | match self { 160 | SignError::Signing => nativeSignError::Signing, 161 | SignError::Verification (mut a, ) => { 162 | nativeSignError::Verification ( 163 | a.into_rust(), 164 | ) 165 | }, 166 | } 167 | } 168 | #[allow(unused)] 169 | pub(crate) fn from_native(native: &SignErrorImport) -> Self { 170 | let native = unsafe { &*(native as *const _ as *const c_void as *const nativeSignError) }; 171 | match native { 172 | nativeSignError::Signing => SignError::Signing, 173 | nativeSignError::Verification (ref a, ) => { 174 | let mut a_nonref = Clone::clone(a); 175 | SignError::Verification ( 176 | crate::c_types::Secp256k1Error::from_rust(a_nonref), 177 | ) 178 | }, 179 | } 180 | } 181 | #[allow(unused)] 182 | pub(crate) fn native_into(native: nativeSignError) -> Self { 183 | match native { 184 | nativeSignError::Signing => SignError::Signing, 185 | nativeSignError::Verification (mut a, ) => { 186 | SignError::Verification ( 187 | crate::c_types::Secp256k1Error::from_rust(a), 188 | ) 189 | }, 190 | } 191 | } 192 | } 193 | /// Frees any resources used by the SignError 194 | #[no_mangle] 195 | pub extern "C" fn SignError_free(this_ptr: SignError) { } 196 | /// Creates a copy of the SignError 197 | #[no_mangle] 198 | pub extern "C" fn SignError_clone(orig: &SignError) -> SignError { 199 | orig.clone() 200 | } 201 | #[allow(unused)] 202 | /// Used only if an object of this type is returned as a trait impl by a method 203 | pub(crate) extern "C" fn SignError_clone_void(this_ptr: *const c_void) -> *mut c_void { 204 | Box::into_raw(Box::new(unsafe { (*(this_ptr as *const SignError)).clone() })) as *mut c_void 205 | } 206 | #[allow(unused)] 207 | /// Used only if an object of this type is returned as a trait impl by a method 208 | pub(crate) extern "C" fn SignError_free_void(this_ptr: *mut c_void) { 209 | let _ = unsafe { Box::from_raw(this_ptr as *mut SignError) }; 210 | } 211 | #[no_mangle] 212 | /// Utility method to constructs a new Signing-variant SignError 213 | pub extern "C" fn SignError_signing() -> SignError { 214 | SignError::Signing} 215 | #[no_mangle] 216 | /// Utility method to constructs a new Verification-variant SignError 217 | pub extern "C" fn SignError_verification(a: crate::c_types::Secp256k1Error) -> SignError { 218 | SignError::Verification(a, ) 219 | } 220 | /// Get a string which allows debug introspection of a SignError object 221 | pub extern "C" fn SignError_debug_str_void(o: *const c_void) -> Str { 222 | alloc::format!("{:?}", unsafe { o as *const crate::lightning::offers::merkle::SignError }).into()} 223 | -------------------------------------------------------------------------------- /lightning-c-bindings/src/lightning/ln/onion_payment.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history and in the source files from which this was generated. 3 | // 4 | // This file is licensed under the license available in the LICENSE or LICENSE.md 5 | // file in the root of this repository or, if no such file exists, the same 6 | // license as that which applies to the original source files from which this 7 | // source was automatically generated. 8 | 9 | //! Utilities to decode payment onions and do contextless validation of incoming payments. 10 | //! 11 | //! Primarily features [`peel_payment_onion`], which allows the decoding of an onion statelessly 12 | //! and can be used to predict whether we'd accept a payment. 13 | 14 | use alloc::str::FromStr; 15 | use alloc::string::String; 16 | use core::ffi::c_void; 17 | use core::convert::Infallible; 18 | use bitcoin::hashes::Hash; 19 | use crate::c_types::*; 20 | #[cfg(feature="no-std")] 21 | use alloc::{vec::Vec, boxed::Box}; 22 | 23 | 24 | use lightning::ln::onion_payment::InboundHTLCErr as nativeInboundHTLCErrImport; 25 | pub(crate) type nativeInboundHTLCErr = nativeInboundHTLCErrImport; 26 | 27 | /// Invalid inbound onion payment. 28 | #[must_use] 29 | #[repr(C)] 30 | pub struct InboundHTLCErr { 31 | /// A pointer to the opaque Rust object. 32 | 33 | /// Nearly everywhere, inner must be non-null, however in places where 34 | /// the Rust equivalent takes an Option, it may be set to null to indicate None. 35 | pub inner: *mut nativeInboundHTLCErr, 36 | /// Indicates that this is the only struct which contains the same pointer. 37 | 38 | /// Rust functions which take ownership of an object provided via an argument require 39 | /// this to be true and invalidate the object pointed to by inner. 40 | pub is_owned: bool, 41 | } 42 | 43 | impl core::ops::Deref for InboundHTLCErr { 44 | type Target = nativeInboundHTLCErr; 45 | fn deref(&self) -> &Self::Target { unsafe { &*ObjOps::untweak_ptr(self.inner) } } 46 | } 47 | unsafe impl core::marker::Send for InboundHTLCErr { } 48 | unsafe impl core::marker::Sync for InboundHTLCErr { } 49 | impl Drop for InboundHTLCErr { 50 | fn drop(&mut self) { 51 | if self.is_owned && !<*mut nativeInboundHTLCErr>::is_null(self.inner) { 52 | let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; 53 | } 54 | } 55 | } 56 | /// Frees any resources used by the InboundHTLCErr, if is_owned is set and inner is non-NULL. 57 | #[no_mangle] 58 | pub extern "C" fn InboundHTLCErr_free(this_obj: InboundHTLCErr) { } 59 | #[allow(unused)] 60 | /// Used only if an object of this type is returned as a trait impl by a method 61 | pub(crate) extern "C" fn InboundHTLCErr_free_void(this_ptr: *mut c_void) { 62 | let _ = unsafe { Box::from_raw(this_ptr as *mut nativeInboundHTLCErr) }; 63 | } 64 | #[allow(unused)] 65 | impl InboundHTLCErr { 66 | pub(crate) fn get_native_ref(&self) -> &'static nativeInboundHTLCErr { 67 | unsafe { &*ObjOps::untweak_ptr(self.inner) } 68 | } 69 | pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeInboundHTLCErr { 70 | unsafe { &mut *ObjOps::untweak_ptr(self.inner) } 71 | } 72 | /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy 73 | pub(crate) fn take_inner(mut self) -> *mut nativeInboundHTLCErr { 74 | assert!(self.is_owned); 75 | let ret = ObjOps::untweak_ptr(self.inner); 76 | self.inner = core::ptr::null_mut(); 77 | ret 78 | } 79 | pub(crate) fn as_ref_to(&self) -> Self { 80 | Self { inner: self.inner, is_owned: false } 81 | } 82 | } 83 | /// BOLT 4 error code. 84 | #[no_mangle] 85 | pub extern "C" fn InboundHTLCErr_get_err_code(this_ptr: &InboundHTLCErr) -> u16 { 86 | let mut inner_val = &mut this_ptr.get_native_mut_ref().err_code; 87 | *inner_val 88 | } 89 | /// BOLT 4 error code. 90 | #[no_mangle] 91 | pub extern "C" fn InboundHTLCErr_set_err_code(this_ptr: &mut InboundHTLCErr, mut val: u16) { 92 | unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.err_code = val; 93 | } 94 | /// Data attached to this error. 95 | /// 96 | /// Returns a copy of the field. 97 | #[no_mangle] 98 | pub extern "C" fn InboundHTLCErr_get_err_data(this_ptr: &InboundHTLCErr) -> crate::c_types::derived::CVec_u8Z { 99 | let mut inner_val = this_ptr.get_native_mut_ref().err_data.clone(); 100 | let mut local_inner_val = Vec::new(); for mut item in inner_val.drain(..) { local_inner_val.push( { item }); }; 101 | local_inner_val.into() 102 | } 103 | /// Data attached to this error. 104 | #[no_mangle] 105 | pub extern "C" fn InboundHTLCErr_set_err_data(this_ptr: &mut InboundHTLCErr, mut val: crate::c_types::derived::CVec_u8Z) { 106 | let mut local_val = Vec::new(); for mut item in val.into_rust().drain(..) { local_val.push( { item }); }; 107 | unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.err_data = local_val; 108 | } 109 | /// Error message text. 110 | #[no_mangle] 111 | pub extern "C" fn InboundHTLCErr_get_msg(this_ptr: &InboundHTLCErr) -> crate::c_types::Str { 112 | let mut inner_val = &mut this_ptr.get_native_mut_ref().msg; 113 | inner_val.into() 114 | } 115 | /// Error message text. 116 | #[no_mangle] 117 | pub extern "C" fn InboundHTLCErr_set_msg(this_ptr: &mut InboundHTLCErr, mut val: crate::c_types::Str) { 118 | unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.msg = val.into_str(); 119 | } 120 | /// Constructs a new InboundHTLCErr given each field 121 | #[must_use] 122 | #[no_mangle] 123 | pub extern "C" fn InboundHTLCErr_new(mut err_code_arg: u16, mut err_data_arg: crate::c_types::derived::CVec_u8Z, mut msg_arg: crate::c_types::Str) -> InboundHTLCErr { 124 | let mut local_err_data_arg = Vec::new(); for mut item in err_data_arg.into_rust().drain(..) { local_err_data_arg.push( { item }); }; 125 | InboundHTLCErr { inner: ObjOps::heap_alloc(nativeInboundHTLCErr { 126 | err_code: err_code_arg, 127 | err_data: local_err_data_arg, 128 | msg: msg_arg.into_str(), 129 | }), is_owned: true } 130 | } 131 | impl Clone for InboundHTLCErr { 132 | fn clone(&self) -> Self { 133 | Self { 134 | inner: if <*mut nativeInboundHTLCErr>::is_null(self.inner) { core::ptr::null_mut() } else { 135 | ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, 136 | is_owned: true, 137 | } 138 | } 139 | } 140 | #[allow(unused)] 141 | /// Used only if an object of this type is returned as a trait impl by a method 142 | pub(crate) extern "C" fn InboundHTLCErr_clone_void(this_ptr: *const c_void) -> *mut c_void { 143 | Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativeInboundHTLCErr)).clone() })) as *mut c_void 144 | } 145 | #[no_mangle] 146 | /// Creates a copy of the InboundHTLCErr 147 | pub extern "C" fn InboundHTLCErr_clone(orig: &InboundHTLCErr) -> InboundHTLCErr { 148 | orig.clone() 149 | } 150 | /// Get a string which allows debug introspection of a InboundHTLCErr object 151 | pub extern "C" fn InboundHTLCErr_debug_str_void(o: *const c_void) -> Str { 152 | alloc::format!("{:?}", unsafe { o as *const crate::lightning::ln::onion_payment::InboundHTLCErr }).into()} 153 | /// Generates a non-cryptographic 64-bit hash of the InboundHTLCErr. 154 | #[no_mangle] 155 | pub extern "C" fn InboundHTLCErr_hash(o: &InboundHTLCErr) -> u64 { 156 | if o.inner.is_null() { return 0; } 157 | // Note that we'd love to use alloc::collections::hash_map::DefaultHasher but it's not in core 158 | #[allow(deprecated)] 159 | let mut hasher = core::hash::SipHasher::new(); 160 | core::hash::Hash::hash(o.get_native_ref(), &mut hasher); 161 | core::hash::Hasher::finish(&hasher) 162 | } 163 | /// Checks if two InboundHTLCErrs contain equal inner contents. 164 | /// This ignores pointers and is_owned flags and looks at the values in fields. 165 | /// Two objects with NULL inner values will be considered "equal" here. 166 | #[no_mangle] 167 | pub extern "C" fn InboundHTLCErr_eq(a: &InboundHTLCErr, b: &InboundHTLCErr) -> bool { 168 | if a.inner == b.inner { return true; } 169 | if a.inner.is_null() || b.inner.is_null() { return false; } 170 | if a.get_native_ref() == b.get_native_ref() { true } else { false } 171 | } 172 | /// Peel one layer off an incoming onion, returning a [`PendingHTLCInfo`] that contains information 173 | /// about the intended next-hop for the HTLC. 174 | /// 175 | /// This does all the relevant context-free checks that LDK requires for payment relay or 176 | /// acceptance. If the payment is to be received, and the amount matches the expected amount for 177 | /// a given invoice, this indicates the [`msgs::UpdateAddHTLC`], once fully committed in the 178 | /// channel, will generate an [`Event::PaymentClaimable`]. 179 | /// 180 | /// [`Event::PaymentClaimable`]: crate::events::Event::PaymentClaimable 181 | #[no_mangle] 182 | pub extern "C" fn peel_payment_onion(msg: &crate::lightning::ln::msgs::UpdateAddHTLC, mut node_signer: crate::lightning::sign::NodeSigner, mut logger: crate::lightning::util::logger::Logger, mut cur_height: u32, mut allow_skimmed_fees: bool) -> crate::c_types::derived::CResult_PendingHTLCInfoInboundHTLCErrZ { 183 | let mut ret = lightning::ln::onion_payment::peel_payment_onion(msg.get_native_ref(), node_signer, logger, secp256k1::global::SECP256K1, cur_height, allow_skimmed_fees); 184 | let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::channelmanager::PendingHTLCInfo { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::onion_payment::InboundHTLCErr { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; 185 | local_ret 186 | } 187 | 188 | -------------------------------------------------------------------------------- /lightning-c-bindings/src/lightning/ln/inbound_payment.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history and in the source files from which this was generated. 3 | // 4 | // This file is licensed under the license available in the LICENSE or LICENSE.md 5 | // file in the root of this repository or, if no such file exists, the same 6 | // license as that which applies to the original source files from which this 7 | // source was automatically generated. 8 | 9 | //! Utilities to generate inbound payment information in service of invoice creation. 10 | 11 | use alloc::str::FromStr; 12 | use alloc::string::String; 13 | use core::ffi::c_void; 14 | use core::convert::Infallible; 15 | use bitcoin::hashes::Hash; 16 | use crate::c_types::*; 17 | #[cfg(feature="no-std")] 18 | use alloc::{vec::Vec, boxed::Box}; 19 | 20 | 21 | use lightning::ln::inbound_payment::ExpandedKey as nativeExpandedKeyImport; 22 | pub(crate) type nativeExpandedKey = nativeExpandedKeyImport; 23 | 24 | /// A set of keys that were HKDF-expanded. Returned by [`NodeSigner::get_inbound_payment_key`]. 25 | /// 26 | /// [`NodeSigner::get_inbound_payment_key`]: crate::sign::NodeSigner::get_inbound_payment_key 27 | #[must_use] 28 | #[repr(C)] 29 | pub struct ExpandedKey { 30 | /// A pointer to the opaque Rust object. 31 | 32 | /// Nearly everywhere, inner must be non-null, however in places where 33 | /// the Rust equivalent takes an Option, it may be set to null to indicate None. 34 | pub inner: *mut nativeExpandedKey, 35 | /// Indicates that this is the only struct which contains the same pointer. 36 | 37 | /// Rust functions which take ownership of an object provided via an argument require 38 | /// this to be true and invalidate the object pointed to by inner. 39 | pub is_owned: bool, 40 | } 41 | 42 | impl core::ops::Deref for ExpandedKey { 43 | type Target = nativeExpandedKey; 44 | fn deref(&self) -> &Self::Target { unsafe { &*ObjOps::untweak_ptr(self.inner) } } 45 | } 46 | unsafe impl core::marker::Send for ExpandedKey { } 47 | unsafe impl core::marker::Sync for ExpandedKey { } 48 | impl Drop for ExpandedKey { 49 | fn drop(&mut self) { 50 | if self.is_owned && !<*mut nativeExpandedKey>::is_null(self.inner) { 51 | let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; 52 | } 53 | } 54 | } 55 | /// Frees any resources used by the ExpandedKey, if is_owned is set and inner is non-NULL. 56 | #[no_mangle] 57 | pub extern "C" fn ExpandedKey_free(this_obj: ExpandedKey) { } 58 | #[allow(unused)] 59 | /// Used only if an object of this type is returned as a trait impl by a method 60 | pub(crate) extern "C" fn ExpandedKey_free_void(this_ptr: *mut c_void) { 61 | let _ = unsafe { Box::from_raw(this_ptr as *mut nativeExpandedKey) }; 62 | } 63 | #[allow(unused)] 64 | impl ExpandedKey { 65 | pub(crate) fn get_native_ref(&self) -> &'static nativeExpandedKey { 66 | unsafe { &*ObjOps::untweak_ptr(self.inner) } 67 | } 68 | pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeExpandedKey { 69 | unsafe { &mut *ObjOps::untweak_ptr(self.inner) } 70 | } 71 | /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy 72 | pub(crate) fn take_inner(mut self) -> *mut nativeExpandedKey { 73 | assert!(self.is_owned); 74 | let ret = ObjOps::untweak_ptr(self.inner); 75 | self.inner = core::ptr::null_mut(); 76 | ret 77 | } 78 | pub(crate) fn as_ref_to(&self) -> Self { 79 | Self { inner: self.inner, is_owned: false } 80 | } 81 | } 82 | /// Generates a non-cryptographic 64-bit hash of the ExpandedKey. 83 | #[no_mangle] 84 | pub extern "C" fn ExpandedKey_hash(o: &ExpandedKey) -> u64 { 85 | if o.inner.is_null() { return 0; } 86 | // Note that we'd love to use alloc::collections::hash_map::DefaultHasher but it's not in core 87 | #[allow(deprecated)] 88 | let mut hasher = core::hash::SipHasher::new(); 89 | core::hash::Hash::hash(o.get_native_ref(), &mut hasher); 90 | core::hash::Hasher::finish(&hasher) 91 | } 92 | impl Clone for ExpandedKey { 93 | fn clone(&self) -> Self { 94 | Self { 95 | inner: if <*mut nativeExpandedKey>::is_null(self.inner) { core::ptr::null_mut() } else { 96 | ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, 97 | is_owned: true, 98 | } 99 | } 100 | } 101 | #[allow(unused)] 102 | /// Used only if an object of this type is returned as a trait impl by a method 103 | pub(crate) extern "C" fn ExpandedKey_clone_void(this_ptr: *const c_void) -> *mut c_void { 104 | Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativeExpandedKey)).clone() })) as *mut c_void 105 | } 106 | #[no_mangle] 107 | /// Creates a copy of the ExpandedKey 108 | pub extern "C" fn ExpandedKey_clone(orig: &ExpandedKey) -> ExpandedKey { 109 | orig.clone() 110 | } 111 | /// Checks if two ExpandedKeys contain equal inner contents. 112 | /// This ignores pointers and is_owned flags and looks at the values in fields. 113 | /// Two objects with NULL inner values will be considered "equal" here. 114 | #[no_mangle] 115 | pub extern "C" fn ExpandedKey_eq(a: &ExpandedKey, b: &ExpandedKey) -> bool { 116 | if a.inner == b.inner { return true; } 117 | if a.inner.is_null() || b.inner.is_null() { return false; } 118 | if a.get_native_ref() == b.get_native_ref() { true } else { false } 119 | } 120 | /// Get a string which allows debug introspection of a ExpandedKey object 121 | pub extern "C" fn ExpandedKey_debug_str_void(o: *const c_void) -> Str { 122 | alloc::format!("{:?}", unsafe { o as *const crate::lightning::ln::inbound_payment::ExpandedKey }).into()} 123 | /// Create a new [`ExpandedKey`] for generating an inbound payment hash and secret. 124 | /// 125 | /// It is recommended to cache this value and not regenerate it for each new inbound payment. 126 | #[must_use] 127 | #[no_mangle] 128 | pub extern "C" fn ExpandedKey_new(mut key_material: crate::c_types::ThirtyTwoBytes) -> crate::lightning::ln::inbound_payment::ExpandedKey { 129 | let mut ret = lightning::ln::inbound_payment::ExpandedKey::new(key_material.data); 130 | crate::lightning::ln::inbound_payment::ExpandedKey { inner: ObjOps::heap_alloc(ret), is_owned: true } 131 | } 132 | 133 | /// Equivalent to [`crate::ln::channelmanager::ChannelManager::create_inbound_payment`], but no 134 | /// `ChannelManager` is required. Useful for generating invoices for [phantom node payments] without 135 | /// a `ChannelManager`. 136 | /// 137 | /// `keys` is generated by calling [`NodeSigner::get_inbound_payment_key`]. It is recommended to 138 | /// cache this value and not regenerate it for each new inbound payment. 139 | /// 140 | /// `current_time` is a Unix timestamp representing the current time. 141 | /// 142 | /// Note that if `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable 143 | /// on versions of LDK prior to 0.0.114. 144 | /// 145 | /// [phantom node payments]: crate::sign::PhantomKeysManager 146 | /// [`NodeSigner::get_inbound_payment_key`]: crate::sign::NodeSigner::get_inbound_payment_key 147 | #[no_mangle] 148 | pub extern "C" fn create(keys: &crate::lightning::ln::inbound_payment::ExpandedKey, mut min_value_msat: crate::c_types::derived::COption_u64Z, mut invoice_expiry_delta_secs: u32, entropy_source: &crate::lightning::sign::EntropySource, mut current_time: u64, mut min_final_cltv_expiry_delta: crate::c_types::derived::COption_u16Z) -> crate::c_types::derived::CResult_C2Tuple_ThirtyTwoBytesThirtyTwoBytesZNoneZ { 149 | let mut local_min_value_msat = if min_value_msat.is_some() { Some( { min_value_msat.take() }) } else { None }; 150 | let mut local_min_final_cltv_expiry_delta = if min_final_cltv_expiry_delta.is_some() { Some( { min_final_cltv_expiry_delta.take() }) } else { None }; 151 | let mut ret = lightning::ln::inbound_payment::create::(keys.get_native_ref(), local_min_value_msat, invoice_expiry_delta_secs, entropy_source, current_time, local_min_final_cltv_expiry_delta); 152 | 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_ret_0 = (crate::c_types::ThirtyTwoBytes { data: orig_ret_0_0.0 }, crate::c_types::ThirtyTwoBytes { data: orig_ret_0_1.0 }).into(); local_ret_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; 153 | local_ret 154 | } 155 | 156 | /// Equivalent to [`crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash`], 157 | /// but no `ChannelManager` is required. Useful for generating invoices for [phantom node payments] 158 | /// without a `ChannelManager`. 159 | /// 160 | /// See [`create`] for information on the `keys` and `current_time` parameters. 161 | /// 162 | /// Note that if `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable 163 | /// on versions of LDK prior to 0.0.114. 164 | /// 165 | /// [phantom node payments]: crate::sign::PhantomKeysManager 166 | #[no_mangle] 167 | pub extern "C" fn create_from_hash(keys: &crate::lightning::ln::inbound_payment::ExpandedKey, mut min_value_msat: crate::c_types::derived::COption_u64Z, mut payment_hash: crate::c_types::ThirtyTwoBytes, mut invoice_expiry_delta_secs: u32, mut current_time: u64, mut min_final_cltv_expiry_delta: crate::c_types::derived::COption_u16Z) -> crate::c_types::derived::CResult_ThirtyTwoBytesNoneZ { 168 | let mut local_min_value_msat = if min_value_msat.is_some() { Some( { min_value_msat.take() }) } else { None }; 169 | let mut local_min_final_cltv_expiry_delta = if min_final_cltv_expiry_delta.is_some() { Some( { min_final_cltv_expiry_delta.take() }) } else { None }; 170 | let mut ret = lightning::ln::inbound_payment::create_from_hash(keys.get_native_ref(), local_min_value_msat, ::lightning::types::payment::PaymentHash(payment_hash.data), invoice_expiry_delta_secs, current_time, local_min_final_cltv_expiry_delta); 171 | 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( { () /*e*/ }).into() }; 172 | local_ret 173 | } 174 | 175 | -------------------------------------------------------------------------------- /lightning-c-bindings/src/lightning/ln/wire.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history and in the source files from which this was generated. 3 | // 4 | // This file is licensed under the license available in the LICENSE or LICENSE.md 5 | // file in the root of this repository or, if no such file exists, the same 6 | // license as that which applies to the original source files from which this 7 | // source was automatically generated. 8 | 9 | //! Wire encoding/decoding for Lightning messages according to [BOLT #1], and for 10 | //! custom message through the [`CustomMessageReader`] trait. 11 | //! 12 | //! [BOLT #1]: https://github.com/lightning/bolts/blob/master/01-messaging.md 13 | 14 | use alloc::str::FromStr; 15 | use alloc::string::String; 16 | use core::ffi::c_void; 17 | use core::convert::Infallible; 18 | use bitcoin::hashes::Hash; 19 | use crate::c_types::*; 20 | #[cfg(feature="no-std")] 21 | use alloc::{vec::Vec, boxed::Box}; 22 | 23 | /// Trait to be implemented by custom message (unrelated to the channel/gossip LN layers) 24 | /// decoders. 25 | #[repr(C)] 26 | pub struct CustomMessageReader { 27 | /// An opaque pointer which is passed to your function implementations as an argument. 28 | /// This has no meaning in the LDK, and can be NULL or any other value. 29 | pub this_arg: *mut c_void, 30 | /// Decodes a custom message to `CustomMessageType`. If the given message type is known to the 31 | /// implementation and the message could be decoded, must return `Ok(Some(message))`. If the 32 | /// message type is unknown to the implementation, must return `Ok(None)`. If a decoding error 33 | /// occur, must return `Err(DecodeError::X)` where `X` details the encountered error. 34 | pub read: extern "C" fn (this_arg: *const c_void, message_type: u16, buffer: crate::c_types::u8slice) -> crate::c_types::derived::CResult_COption_TypeZDecodeErrorZ, 35 | /// Frees any resources associated with this object given its this_arg pointer. 36 | /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed. 37 | pub free: Option, 38 | } 39 | unsafe impl Send for CustomMessageReader {} 40 | unsafe impl Sync for CustomMessageReader {} 41 | #[allow(unused)] 42 | pub(crate) fn CustomMessageReader_clone_fields(orig: &CustomMessageReader) -> CustomMessageReader { 43 | CustomMessageReader { 44 | this_arg: orig.this_arg, 45 | read: Clone::clone(&orig.read), 46 | free: Clone::clone(&orig.free), 47 | } 48 | } 49 | 50 | use lightning::ln::wire::CustomMessageReader as rustCustomMessageReader; 51 | impl rustCustomMessageReader for CustomMessageReader { 52 | type CustomMessage = crate::lightning::ln::wire::Type; 53 | fn read(&self, mut message_type: u16, mut buffer: &mut R) -> Result, lightning::ln::msgs::DecodeError> { 54 | let mut ret = (self.read)(self.this_arg, message_type, crate::c_types::u8slice::from_vec(&crate::c_types::reader_to_vec(buffer))); 55 | let mut local_ret = match ret.result_ok { true => Ok( { let mut local_ret_0 = { /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ let ret_0_opt = (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }); if ret_0_opt.is_none() { None } else { Some({ { { ret_0_opt.take() } }})} }; local_ret_0 }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).into_native() })}; 56 | local_ret 57 | } 58 | } 59 | 60 | pub struct CustomMessageReaderRef(CustomMessageReader); 61 | impl rustCustomMessageReader for CustomMessageReaderRef { 62 | type CustomMessage = crate::lightning::ln::wire::Type; 63 | fn read(&self, mut message_type: u16, mut buffer: &mut R) -> Result, lightning::ln::msgs::DecodeError> { 64 | let mut ret = (self.0.read)(self.0.this_arg, message_type, crate::c_types::u8slice::from_vec(&crate::c_types::reader_to_vec(buffer))); 65 | let mut local_ret = match ret.result_ok { true => Ok( { let mut local_ret_0 = { /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ let ret_0_opt = (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }); if ret_0_opt.is_none() { None } else { Some({ { { ret_0_opt.take() } }})} }; local_ret_0 }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).into_native() })}; 66 | local_ret 67 | } 68 | } 69 | 70 | // We're essentially a pointer already, or at least a set of pointers, so allow us to be used 71 | // directly as a Deref trait in higher-level structs: 72 | impl core::ops::Deref for CustomMessageReader { 73 | type Target = CustomMessageReaderRef; 74 | fn deref(&self) -> &Self::Target { 75 | unsafe { &*(self as *const _ as *const CustomMessageReaderRef) } 76 | } 77 | } 78 | impl core::ops::DerefMut for CustomMessageReader { 79 | fn deref_mut(&mut self) -> &mut CustomMessageReaderRef { 80 | unsafe { &mut *(self as *mut _ as *mut CustomMessageReaderRef) } 81 | } 82 | } 83 | /// Calls the free function if one is set 84 | #[no_mangle] 85 | pub extern "C" fn CustomMessageReader_free(this_ptr: CustomMessageReader) { } 86 | impl Drop for CustomMessageReader { 87 | fn drop(&mut self) { 88 | if let Some(f) = self.free { 89 | f(self.this_arg); 90 | } 91 | } 92 | } 93 | mod encode { 94 | 95 | use alloc::str::FromStr; 96 | use alloc::string::String; 97 | use core::ffi::c_void; 98 | use core::convert::Infallible; 99 | use bitcoin::hashes::Hash; 100 | use crate::c_types::*; 101 | #[cfg(feature="no-std")] 102 | use alloc::{vec::Vec, boxed::Box}; 103 | 104 | } 105 | /// Defines a type identifier for sending messages over the wire. 106 | /// 107 | /// Messages implementing this trait specify a type and must be [`Writeable`]. 108 | #[repr(C)] 109 | pub struct Type { 110 | /// An opaque pointer which is passed to your function implementations as an argument. 111 | /// This has no meaning in the LDK, and can be NULL or any other value. 112 | pub this_arg: *mut c_void, 113 | /// Returns the type identifying the message payload. 114 | pub type_id: extern "C" fn (this_arg: *const c_void) -> u16, 115 | /// Return a human-readable "debug" string describing this object 116 | pub debug_str: extern "C" fn (this_arg: *const c_void) -> crate::c_types::Str, 117 | /// Serialize the object into a byte array 118 | pub write: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_u8Z, 119 | /// Called, if set, after this Type has been cloned into a duplicate object. 120 | /// The new Type is provided, and should be mutated as needed to perform a 121 | /// deep copy of the object pointed to by this_arg or avoid any double-freeing. 122 | pub cloned: Option, 123 | /// Frees any resources associated with this object given its this_arg pointer. 124 | /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed. 125 | pub free: Option, 126 | } 127 | unsafe impl Send for Type {} 128 | unsafe impl Sync for Type {} 129 | #[allow(unused)] 130 | pub(crate) fn Type_clone_fields(orig: &Type) -> Type { 131 | Type { 132 | this_arg: orig.this_arg, 133 | type_id: Clone::clone(&orig.type_id), 134 | debug_str: Clone::clone(&orig.debug_str), 135 | write: Clone::clone(&orig.write), 136 | cloned: Clone::clone(&orig.cloned), 137 | free: Clone::clone(&orig.free), 138 | } 139 | } 140 | impl core::fmt::Debug for Type { 141 | fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> { 142 | f.write_str((self.debug_str)(self.this_arg).into_str()) 143 | } 144 | } 145 | impl core::fmt::Debug for TypeRef { 146 | fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> { 147 | f.write_str((self.0.debug_str)(self.0.this_arg).into_str()) 148 | } 149 | } 150 | impl lightning::util::ser::Writeable for Type { 151 | fn write(&self, w: &mut W) -> Result<(), crate::c_types::io::Error> { 152 | let vec = (self.write)(self.this_arg); 153 | w.write_all(vec.as_slice()) 154 | } 155 | } 156 | impl lightning::util::ser::Writeable for TypeRef { 157 | fn write(&self, w: &mut W) -> Result<(), crate::c_types::io::Error> { 158 | let vec = (self.0.write)(self.0.this_arg); 159 | w.write_all(vec.as_slice()) 160 | } 161 | } 162 | #[no_mangle] 163 | /// Creates a copy of a Type 164 | pub extern "C" fn Type_clone(orig: &Type) -> Type { 165 | let mut res = Type_clone_fields(orig); 166 | if let Some(f) = orig.cloned { (f)(&mut res) }; 167 | res 168 | } 169 | impl Clone for Type { 170 | fn clone(&self) -> Self { 171 | Type_clone(self) 172 | } 173 | } 174 | impl Clone for TypeRef { 175 | fn clone(&self) -> Self { 176 | Self(Type_clone(&self.0)) 177 | } 178 | } 179 | 180 | use lightning::ln::wire::Type as rustType; 181 | impl rustType for Type { 182 | fn type_id(&self) -> u16 { 183 | let mut ret = (self.type_id)(self.this_arg); 184 | ret 185 | } 186 | } 187 | 188 | pub struct TypeRef(Type); 189 | impl rustType for TypeRef { 190 | fn type_id(&self) -> u16 { 191 | let mut ret = (self.0.type_id)(self.0.this_arg); 192 | ret 193 | } 194 | } 195 | 196 | // We're essentially a pointer already, or at least a set of pointers, so allow us to be used 197 | // directly as a Deref trait in higher-level structs: 198 | impl core::ops::Deref for Type { 199 | type Target = TypeRef; 200 | fn deref(&self) -> &Self::Target { 201 | unsafe { &*(self as *const _ as *const TypeRef) } 202 | } 203 | } 204 | impl core::ops::DerefMut for Type { 205 | fn deref_mut(&mut self) -> &mut TypeRef { 206 | unsafe { &mut *(self as *mut _ as *mut TypeRef) } 207 | } 208 | } 209 | /// Calls the free function if one is set 210 | #[no_mangle] 211 | pub extern "C" fn Type_free(this_ptr: Type) { } 212 | impl Drop for Type { 213 | fn drop(&mut self) { 214 | if let Some(f) = self.free { 215 | f(self.this_arg); 216 | } 217 | } 218 | } 219 | -------------------------------------------------------------------------------- /lightning-c-bindings/src/lightning_types/string.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history and in the source files from which this was generated. 3 | // 4 | // This file is licensed under the license available in the LICENSE or LICENSE.md 5 | // file in the root of this repository or, if no such file exists, the same 6 | // license as that which applies to the original source files from which this 7 | // source was automatically generated. 8 | 9 | //! Utilities for strings. 10 | 11 | use alloc::str::FromStr; 12 | use alloc::string::String; 13 | use core::ffi::c_void; 14 | use core::convert::Infallible; 15 | use bitcoin::hashes::Hash; 16 | use crate::c_types::*; 17 | #[cfg(feature="no-std")] 18 | use alloc::{vec::Vec, boxed::Box}; 19 | 20 | 21 | use lightning_types::string::UntrustedString as nativeUntrustedStringImport; 22 | pub(crate) type nativeUntrustedString = nativeUntrustedStringImport; 23 | 24 | /// Struct to `Display` fields in a safe way using `PrintableString` 25 | #[must_use] 26 | #[repr(C)] 27 | pub struct UntrustedString { 28 | /// A pointer to the opaque Rust object. 29 | 30 | /// Nearly everywhere, inner must be non-null, however in places where 31 | /// the Rust equivalent takes an Option, it may be set to null to indicate None. 32 | pub inner: *mut nativeUntrustedString, 33 | /// Indicates that this is the only struct which contains the same pointer. 34 | 35 | /// Rust functions which take ownership of an object provided via an argument require 36 | /// this to be true and invalidate the object pointed to by inner. 37 | pub is_owned: bool, 38 | } 39 | 40 | impl core::ops::Deref for UntrustedString { 41 | type Target = nativeUntrustedString; 42 | fn deref(&self) -> &Self::Target { unsafe { &*ObjOps::untweak_ptr(self.inner) } } 43 | } 44 | unsafe impl core::marker::Send for UntrustedString { } 45 | unsafe impl core::marker::Sync for UntrustedString { } 46 | impl Drop for UntrustedString { 47 | fn drop(&mut self) { 48 | if self.is_owned && !<*mut nativeUntrustedString>::is_null(self.inner) { 49 | let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; 50 | } 51 | } 52 | } 53 | /// Frees any resources used by the UntrustedString, if is_owned is set and inner is non-NULL. 54 | #[no_mangle] 55 | pub extern "C" fn UntrustedString_free(this_obj: UntrustedString) { } 56 | #[allow(unused)] 57 | /// Used only if an object of this type is returned as a trait impl by a method 58 | pub(crate) extern "C" fn UntrustedString_free_void(this_ptr: *mut c_void) { 59 | let _ = unsafe { Box::from_raw(this_ptr as *mut nativeUntrustedString) }; 60 | } 61 | #[allow(unused)] 62 | impl UntrustedString { 63 | pub(crate) fn get_native_ref(&self) -> &'static nativeUntrustedString { 64 | unsafe { &*ObjOps::untweak_ptr(self.inner) } 65 | } 66 | pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeUntrustedString { 67 | unsafe { &mut *ObjOps::untweak_ptr(self.inner) } 68 | } 69 | /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy 70 | pub(crate) fn take_inner(mut self) -> *mut nativeUntrustedString { 71 | assert!(self.is_owned); 72 | let ret = ObjOps::untweak_ptr(self.inner); 73 | self.inner = core::ptr::null_mut(); 74 | ret 75 | } 76 | pub(crate) fn as_ref_to(&self) -> Self { 77 | Self { inner: self.inner, is_owned: false } 78 | } 79 | } 80 | #[no_mangle] 81 | pub extern "C" fn UntrustedString_get_a(this_ptr: &UntrustedString) -> crate::c_types::Str { 82 | let mut inner_val = &mut this_ptr.get_native_mut_ref().0; 83 | inner_val.as_str().into() 84 | } 85 | #[no_mangle] 86 | pub extern "C" fn UntrustedString_set_a(this_ptr: &mut UntrustedString, mut val: crate::c_types::Str) { 87 | unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.0 = val.into_string(); 88 | } 89 | /// Constructs a new UntrustedString given each field 90 | #[must_use] 91 | #[no_mangle] 92 | pub extern "C" fn UntrustedString_new(mut a_arg: crate::c_types::Str) -> UntrustedString { 93 | UntrustedString { inner: ObjOps::heap_alloc(lightning_types::string::UntrustedString ( 94 | a_arg.into_string(), 95 | )), is_owned: true } 96 | } 97 | impl Clone for UntrustedString { 98 | fn clone(&self) -> Self { 99 | Self { 100 | inner: if <*mut nativeUntrustedString>::is_null(self.inner) { core::ptr::null_mut() } else { 101 | ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, 102 | is_owned: true, 103 | } 104 | } 105 | } 106 | #[allow(unused)] 107 | /// Used only if an object of this type is returned as a trait impl by a method 108 | pub(crate) extern "C" fn UntrustedString_clone_void(this_ptr: *const c_void) -> *mut c_void { 109 | Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativeUntrustedString)).clone() })) as *mut c_void 110 | } 111 | #[no_mangle] 112 | /// Creates a copy of the UntrustedString 113 | pub extern "C" fn UntrustedString_clone(orig: &UntrustedString) -> UntrustedString { 114 | orig.clone() 115 | } 116 | /// Get a string which allows debug introspection of a UntrustedString object 117 | pub extern "C" fn UntrustedString_debug_str_void(o: *const c_void) -> Str { 118 | alloc::format!("{:?}", unsafe { o as *const crate::lightning_types::string::UntrustedString }).into()} 119 | /// Checks if two UntrustedStrings contain equal inner contents. 120 | /// This ignores pointers and is_owned flags and looks at the values in fields. 121 | /// Two objects with NULL inner values will be considered "equal" here. 122 | #[no_mangle] 123 | pub extern "C" fn UntrustedString_eq(a: &UntrustedString, b: &UntrustedString) -> bool { 124 | if a.inner == b.inner { return true; } 125 | if a.inner.is_null() || b.inner.is_null() { return false; } 126 | if a.get_native_ref() == b.get_native_ref() { true } else { false } 127 | } 128 | /// Generates a non-cryptographic 64-bit hash of the UntrustedString. 129 | #[no_mangle] 130 | pub extern "C" fn UntrustedString_hash(o: &UntrustedString) -> u64 { 131 | if o.inner.is_null() { return 0; } 132 | // Note that we'd love to use alloc::collections::hash_map::DefaultHasher but it's not in core 133 | #[allow(deprecated)] 134 | let mut hasher = core::hash::SipHasher::new(); 135 | core::hash::Hash::hash(o.get_native_ref(), &mut hasher); 136 | core::hash::Hasher::finish(&hasher) 137 | } 138 | #[no_mangle] 139 | /// Get the string representation of a UntrustedString object 140 | pub extern "C" fn UntrustedString_to_str(o: &crate::lightning_types::string::UntrustedString) -> Str { 141 | alloc::format!("{}", o.get_native_ref()).into() 142 | } 143 | 144 | use lightning_types::string::PrintableString as nativePrintableStringImport; 145 | pub(crate) type nativePrintableString = nativePrintableStringImport<'static, >; 146 | 147 | /// A string that displays only printable characters, replacing control characters with 148 | /// [`core::char::REPLACEMENT_CHARACTER`]. 149 | #[must_use] 150 | #[repr(C)] 151 | pub struct PrintableString { 152 | /// A pointer to the opaque Rust object. 153 | 154 | /// Nearly everywhere, inner must be non-null, however in places where 155 | /// the Rust equivalent takes an Option, it may be set to null to indicate None. 156 | pub inner: *mut nativePrintableString, 157 | /// Indicates that this is the only struct which contains the same pointer. 158 | 159 | /// Rust functions which take ownership of an object provided via an argument require 160 | /// this to be true and invalidate the object pointed to by inner. 161 | pub is_owned: bool, 162 | } 163 | 164 | impl core::ops::Deref for PrintableString { 165 | type Target = nativePrintableString; 166 | fn deref(&self) -> &Self::Target { unsafe { &*ObjOps::untweak_ptr(self.inner) } } 167 | } 168 | unsafe impl core::marker::Send for PrintableString { } 169 | unsafe impl core::marker::Sync for PrintableString { } 170 | impl Drop for PrintableString { 171 | fn drop(&mut self) { 172 | if self.is_owned && !<*mut nativePrintableString>::is_null(self.inner) { 173 | let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; 174 | } 175 | } 176 | } 177 | /// Frees any resources used by the PrintableString, if is_owned is set and inner is non-NULL. 178 | #[no_mangle] 179 | pub extern "C" fn PrintableString_free(this_obj: PrintableString) { } 180 | #[allow(unused)] 181 | /// Used only if an object of this type is returned as a trait impl by a method 182 | pub(crate) extern "C" fn PrintableString_free_void(this_ptr: *mut c_void) { 183 | let _ = unsafe { Box::from_raw(this_ptr as *mut nativePrintableString) }; 184 | } 185 | #[allow(unused)] 186 | impl PrintableString { 187 | pub(crate) fn get_native_ref(&self) -> &'static nativePrintableString { 188 | unsafe { &*ObjOps::untweak_ptr(self.inner) } 189 | } 190 | pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativePrintableString { 191 | unsafe { &mut *ObjOps::untweak_ptr(self.inner) } 192 | } 193 | /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy 194 | pub(crate) fn take_inner(mut self) -> *mut nativePrintableString { 195 | assert!(self.is_owned); 196 | let ret = ObjOps::untweak_ptr(self.inner); 197 | self.inner = core::ptr::null_mut(); 198 | ret 199 | } 200 | pub(crate) fn as_ref_to(&self) -> Self { 201 | Self { inner: self.inner, is_owned: false } 202 | } 203 | } 204 | #[no_mangle] 205 | pub extern "C" fn PrintableString_get_a(this_ptr: &PrintableString) -> crate::c_types::Str { 206 | let mut inner_val = &mut this_ptr.get_native_mut_ref().0; 207 | inner_val.into() 208 | } 209 | #[no_mangle] 210 | pub extern "C" fn PrintableString_set_a(this_ptr: &mut PrintableString, mut val: crate::c_types::Str) { 211 | unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.0 = val.into_str(); 212 | } 213 | /// Constructs a new PrintableString given each field 214 | #[must_use] 215 | #[no_mangle] 216 | pub extern "C" fn PrintableString_new(mut a_arg: crate::c_types::Str) -> PrintableString { 217 | PrintableString { inner: ObjOps::heap_alloc(lightning_types::string::PrintableString ( 218 | a_arg.into_str(), 219 | )), is_owned: true } 220 | } 221 | /// Get a string which allows debug introspection of a PrintableString object 222 | pub extern "C" fn PrintableString_debug_str_void(o: *const c_void) -> Str { 223 | alloc::format!("{:?}", unsafe { o as *const crate::lightning_types::string::PrintableString }).into()} 224 | #[no_mangle] 225 | /// Get the string representation of a PrintableString object 226 | pub extern "C" fn PrintableString_to_str(o: &crate::lightning_types::string::PrintableString) -> Str { 227 | alloc::format!("{}", o.get_native_ref()).into() 228 | } 229 | -------------------------------------------------------------------------------- /lightning-c-bindings/src/lightning_persister/fs_store.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history and in the source files from which this was generated. 3 | // 4 | // This file is licensed under the license available in the LICENSE or LICENSE.md 5 | // file in the root of this repository or, if no such file exists, the same 6 | // license as that which applies to the original source files from which this 7 | // source was automatically generated. 8 | 9 | //! Objects related to [`FilesystemStore`] live here. 10 | 11 | use alloc::str::FromStr; 12 | use alloc::string::String; 13 | use core::ffi::c_void; 14 | use core::convert::Infallible; 15 | use bitcoin::hashes::Hash; 16 | use crate::c_types::*; 17 | #[cfg(feature="no-std")] 18 | use alloc::{vec::Vec, boxed::Box}; 19 | 20 | 21 | use lightning_persister::fs_store::FilesystemStore as nativeFilesystemStoreImport; 22 | pub(crate) type nativeFilesystemStore = nativeFilesystemStoreImport; 23 | 24 | /// A [`KVStore`] implementation that writes to and reads from the file system. 25 | #[must_use] 26 | #[repr(C)] 27 | pub struct FilesystemStore { 28 | /// A pointer to the opaque Rust object. 29 | 30 | /// Nearly everywhere, inner must be non-null, however in places where 31 | /// the Rust equivalent takes an Option, it may be set to null to indicate None. 32 | pub inner: *mut nativeFilesystemStore, 33 | /// Indicates that this is the only struct which contains the same pointer. 34 | 35 | /// Rust functions which take ownership of an object provided via an argument require 36 | /// this to be true and invalidate the object pointed to by inner. 37 | pub is_owned: bool, 38 | } 39 | 40 | impl core::ops::Deref for FilesystemStore { 41 | type Target = nativeFilesystemStore; 42 | fn deref(&self) -> &Self::Target { unsafe { &*ObjOps::untweak_ptr(self.inner) } } 43 | } 44 | unsafe impl core::marker::Send for FilesystemStore { } 45 | unsafe impl core::marker::Sync for FilesystemStore { } 46 | impl Drop for FilesystemStore { 47 | fn drop(&mut self) { 48 | if self.is_owned && !<*mut nativeFilesystemStore>::is_null(self.inner) { 49 | let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; 50 | } 51 | } 52 | } 53 | /// Frees any resources used by the FilesystemStore, if is_owned is set and inner is non-NULL. 54 | #[no_mangle] 55 | pub extern "C" fn FilesystemStore_free(this_obj: FilesystemStore) { } 56 | #[allow(unused)] 57 | /// Used only if an object of this type is returned as a trait impl by a method 58 | pub(crate) extern "C" fn FilesystemStore_free_void(this_ptr: *mut c_void) { 59 | let _ = unsafe { Box::from_raw(this_ptr as *mut nativeFilesystemStore) }; 60 | } 61 | #[allow(unused)] 62 | impl FilesystemStore { 63 | pub(crate) fn get_native_ref(&self) -> &'static nativeFilesystemStore { 64 | unsafe { &*ObjOps::untweak_ptr(self.inner) } 65 | } 66 | pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeFilesystemStore { 67 | unsafe { &mut *ObjOps::untweak_ptr(self.inner) } 68 | } 69 | /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy 70 | pub(crate) fn take_inner(mut self) -> *mut nativeFilesystemStore { 71 | assert!(self.is_owned); 72 | let ret = ObjOps::untweak_ptr(self.inner); 73 | self.inner = core::ptr::null_mut(); 74 | ret 75 | } 76 | pub(crate) fn as_ref_to(&self) -> Self { 77 | Self { inner: self.inner, is_owned: false } 78 | } 79 | } 80 | /// Constructs a new [`FilesystemStore`]. 81 | #[must_use] 82 | #[no_mangle] 83 | pub extern "C" fn FilesystemStore_new(mut data_dir: crate::c_types::Str) -> crate::lightning_persister::fs_store::FilesystemStore { 84 | let mut ret = lightning_persister::fs_store::FilesystemStore::new(data_dir.into_pathbuf()); 85 | crate::lightning_persister::fs_store::FilesystemStore { inner: ObjOps::heap_alloc(ret), is_owned: true } 86 | } 87 | 88 | /// Returns the data directory. 89 | #[must_use] 90 | #[no_mangle] 91 | pub extern "C" fn FilesystemStore_get_data_dir(this_arg: &crate::lightning_persister::fs_store::FilesystemStore) -> crate::c_types::Str { 92 | let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_data_dir(); 93 | ret.into() 94 | } 95 | 96 | impl From for crate::lightning::util::persist::KVStore { 97 | fn from(obj: nativeFilesystemStore) -> Self { 98 | let rust_obj = crate::lightning_persister::fs_store::FilesystemStore { inner: ObjOps::heap_alloc(obj), is_owned: true }; 99 | let mut ret = FilesystemStore_as_KVStore(&rust_obj); 100 | // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn 101 | core::mem::forget(rust_obj); 102 | ret.free = Some(FilesystemStore_free_void); 103 | ret 104 | } 105 | } 106 | /// Constructs a new KVStore which calls the relevant methods on this_arg. 107 | /// This copies the `inner` pointer in this_arg and thus the returned KVStore must be freed before this_arg is 108 | #[no_mangle] 109 | pub extern "C" fn FilesystemStore_as_KVStore(this_arg: &FilesystemStore) -> crate::lightning::util::persist::KVStore { 110 | crate::lightning::util::persist::KVStore { 111 | this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void }, 112 | free: None, 113 | read: FilesystemStore_KVStore_read, 114 | write: FilesystemStore_KVStore_write, 115 | remove: FilesystemStore_KVStore_remove, 116 | list: FilesystemStore_KVStore_list, 117 | } 118 | } 119 | 120 | #[must_use] 121 | extern "C" fn FilesystemStore_KVStore_read(this_arg: *const c_void, mut primary_namespace: crate::c_types::Str, mut secondary_namespace: crate::c_types::Str, mut key: crate::c_types::Str) -> crate::c_types::derived::CResult_CVec_u8ZIOErrorZ { 122 | let mut ret = ::read(unsafe { &mut *(this_arg as *mut nativeFilesystemStore) }, primary_namespace.into_str(), secondary_namespace.into_str(), key.into_str()); 123 | 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( { item }); }; local_ret_0.into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::IOError::from_bitcoin(e) }).into() }; 124 | local_ret 125 | } 126 | #[must_use] 127 | extern "C" fn FilesystemStore_KVStore_write(this_arg: *const c_void, mut primary_namespace: crate::c_types::Str, mut secondary_namespace: crate::c_types::Str, mut key: crate::c_types::Str, mut buf: crate::c_types::u8slice) -> crate::c_types::derived::CResult_NoneIOErrorZ { 128 | let mut ret = ::write(unsafe { &mut *(this_arg as *mut nativeFilesystemStore) }, primary_namespace.into_str(), secondary_namespace.into_str(), key.into_str(), buf.to_slice()); 129 | 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_bitcoin(e) }).into() }; 130 | local_ret 131 | } 132 | #[must_use] 133 | extern "C" fn FilesystemStore_KVStore_remove(this_arg: *const c_void, mut primary_namespace: crate::c_types::Str, mut secondary_namespace: crate::c_types::Str, mut key: crate::c_types::Str, mut lazy: bool) -> crate::c_types::derived::CResult_NoneIOErrorZ { 134 | let mut ret = ::remove(unsafe { &mut *(this_arg as *mut nativeFilesystemStore) }, primary_namespace.into_str(), secondary_namespace.into_str(), key.into_str(), lazy); 135 | 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_bitcoin(e) }).into() }; 136 | local_ret 137 | } 138 | #[must_use] 139 | extern "C" fn FilesystemStore_KVStore_list(this_arg: *const c_void, mut primary_namespace: crate::c_types::Str, mut secondary_namespace: crate::c_types::Str) -> crate::c_types::derived::CResult_CVec_StrZIOErrorZ { 140 | let mut ret = ::list(unsafe { &mut *(this_arg as *mut nativeFilesystemStore) }, primary_namespace.into_str(), secondary_namespace.into_str()); 141 | 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( { item.into() }); }; local_ret_0.into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::IOError::from_bitcoin(e) }).into() }; 142 | local_ret 143 | } 144 | 145 | impl From for crate::lightning::util::persist::MigratableKVStore { 146 | fn from(obj: nativeFilesystemStore) -> Self { 147 | let rust_obj = crate::lightning_persister::fs_store::FilesystemStore { inner: ObjOps::heap_alloc(obj), is_owned: true }; 148 | let mut ret = FilesystemStore_as_MigratableKVStore(&rust_obj); 149 | // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn 150 | core::mem::forget(rust_obj); 151 | ret.free = Some(FilesystemStore_free_void); 152 | ret 153 | } 154 | } 155 | /// Constructs a new MigratableKVStore which calls the relevant methods on this_arg. 156 | /// This copies the `inner` pointer in this_arg and thus the returned MigratableKVStore must be freed before this_arg is 157 | #[no_mangle] 158 | pub extern "C" fn FilesystemStore_as_MigratableKVStore(this_arg: &FilesystemStore) -> crate::lightning::util::persist::MigratableKVStore { 159 | crate::lightning::util::persist::MigratableKVStore { 160 | this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void }, 161 | free: None, 162 | list_all_keys: FilesystemStore_MigratableKVStore_list_all_keys, 163 | KVStore: crate::lightning::util::persist::KVStore { 164 | this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void }, 165 | free: None, 166 | read: FilesystemStore_KVStore_read, 167 | write: FilesystemStore_KVStore_write, 168 | remove: FilesystemStore_KVStore_remove, 169 | list: FilesystemStore_KVStore_list, 170 | }, 171 | } 172 | } 173 | 174 | #[must_use] 175 | extern "C" fn FilesystemStore_MigratableKVStore_list_all_keys(this_arg: *const c_void) -> crate::c_types::derived::CResult_CVec_C3Tuple_StrStrStrZZIOErrorZ { 176 | let mut ret = ::list_all_keys(unsafe { &mut *(this_arg as *mut nativeFilesystemStore) }, ); 177 | 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 orig_ret_0_0_0, mut orig_ret_0_0_1, mut orig_ret_0_0_2) = item; let mut local_ret_0_0 = (orig_ret_0_0_0.into(), orig_ret_0_0_1.into(), orig_ret_0_0_2.into()).into(); local_ret_0_0 }); }; local_ret_0.into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::IOError::from_bitcoin(e) }).into() }; 178 | local_ret 179 | } 180 | 181 | -------------------------------------------------------------------------------- /lightning-c-bindings/src/lightning/ln/types.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history and in the source files from which this was generated. 3 | // 4 | // This file is licensed under the license available in the LICENSE or LICENSE.md 5 | // file in the root of this repository or, if no such file exists, the same 6 | // license as that which applies to the original source files from which this 7 | // source was automatically generated. 8 | 9 | //! Various wrapper types (most around 32-byte arrays) for use in lightning. 10 | 11 | use alloc::str::FromStr; 12 | use alloc::string::String; 13 | use core::ffi::c_void; 14 | use core::convert::Infallible; 15 | use bitcoin::hashes::Hash; 16 | use crate::c_types::*; 17 | #[cfg(feature="no-std")] 18 | use alloc::{vec::Vec, boxed::Box}; 19 | 20 | 21 | use lightning::ln::types::ChannelId as nativeChannelIdImport; 22 | pub(crate) type nativeChannelId = nativeChannelIdImport; 23 | 24 | /// A unique 32-byte identifier for a channel. 25 | /// Depending on how the ID is generated, several varieties are distinguished 26 | /// (but all are stored as 32 bytes): 27 | /// _v1_ and _temporary_. 28 | /// A _v1_ channel ID is generated based on funding tx outpoint (txid & index). 29 | /// A _temporary_ ID is generated randomly. 30 | /// (Later revocation-point-based _v2_ is a possibility.) 31 | /// The variety (context) is not stored, it is relevant only at creation. 32 | #[must_use] 33 | #[repr(C)] 34 | pub struct ChannelId { 35 | /// A pointer to the opaque Rust object. 36 | 37 | /// Nearly everywhere, inner must be non-null, however in places where 38 | /// the Rust equivalent takes an Option, it may be set to null to indicate None. 39 | pub inner: *mut nativeChannelId, 40 | /// Indicates that this is the only struct which contains the same pointer. 41 | 42 | /// Rust functions which take ownership of an object provided via an argument require 43 | /// this to be true and invalidate the object pointed to by inner. 44 | pub is_owned: bool, 45 | } 46 | 47 | impl core::ops::Deref for ChannelId { 48 | type Target = nativeChannelId; 49 | fn deref(&self) -> &Self::Target { unsafe { &*ObjOps::untweak_ptr(self.inner) } } 50 | } 51 | unsafe impl core::marker::Send for ChannelId { } 52 | unsafe impl core::marker::Sync for ChannelId { } 53 | impl Drop for ChannelId { 54 | fn drop(&mut self) { 55 | if self.is_owned && !<*mut nativeChannelId>::is_null(self.inner) { 56 | let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; 57 | } 58 | } 59 | } 60 | /// Frees any resources used by the ChannelId, if is_owned is set and inner is non-NULL. 61 | #[no_mangle] 62 | pub extern "C" fn ChannelId_free(this_obj: ChannelId) { } 63 | #[allow(unused)] 64 | /// Used only if an object of this type is returned as a trait impl by a method 65 | pub(crate) extern "C" fn ChannelId_free_void(this_ptr: *mut c_void) { 66 | let _ = unsafe { Box::from_raw(this_ptr as *mut nativeChannelId) }; 67 | } 68 | #[allow(unused)] 69 | impl ChannelId { 70 | pub(crate) fn get_native_ref(&self) -> &'static nativeChannelId { 71 | unsafe { &*ObjOps::untweak_ptr(self.inner) } 72 | } 73 | pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelId { 74 | unsafe { &mut *ObjOps::untweak_ptr(self.inner) } 75 | } 76 | /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy 77 | pub(crate) fn take_inner(mut self) -> *mut nativeChannelId { 78 | assert!(self.is_owned); 79 | let ret = ObjOps::untweak_ptr(self.inner); 80 | self.inner = core::ptr::null_mut(); 81 | ret 82 | } 83 | pub(crate) fn as_ref_to(&self) -> Self { 84 | Self { inner: self.inner, is_owned: false } 85 | } 86 | } 87 | #[no_mangle] 88 | pub extern "C" fn ChannelId_get_a(this_ptr: &ChannelId) -> *const [u8; 32] { 89 | let mut inner_val = &mut this_ptr.get_native_mut_ref().0; 90 | inner_val 91 | } 92 | #[no_mangle] 93 | pub extern "C" fn ChannelId_set_a(this_ptr: &mut ChannelId, mut val: crate::c_types::ThirtyTwoBytes) { 94 | unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.0 = val.data; 95 | } 96 | /// Constructs a new ChannelId given each field 97 | #[must_use] 98 | #[no_mangle] 99 | pub extern "C" fn ChannelId_new(mut a_arg: crate::c_types::ThirtyTwoBytes) -> ChannelId { 100 | ChannelId { inner: ObjOps::heap_alloc(lightning::ln::types::ChannelId ( 101 | a_arg.data, 102 | )), is_owned: true } 103 | } 104 | impl Clone for ChannelId { 105 | fn clone(&self) -> Self { 106 | Self { 107 | inner: if <*mut nativeChannelId>::is_null(self.inner) { core::ptr::null_mut() } else { 108 | ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, 109 | is_owned: true, 110 | } 111 | } 112 | } 113 | #[allow(unused)] 114 | /// Used only if an object of this type is returned as a trait impl by a method 115 | pub(crate) extern "C" fn ChannelId_clone_void(this_ptr: *const c_void) -> *mut c_void { 116 | Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativeChannelId)).clone() })) as *mut c_void 117 | } 118 | #[no_mangle] 119 | /// Creates a copy of the ChannelId 120 | pub extern "C" fn ChannelId_clone(orig: &ChannelId) -> ChannelId { 121 | orig.clone() 122 | } 123 | /// Checks if two ChannelIds contain equal inner contents. 124 | /// This ignores pointers and is_owned flags and looks at the values in fields. 125 | /// Two objects with NULL inner values will be considered "equal" here. 126 | #[no_mangle] 127 | pub extern "C" fn ChannelId_eq(a: &ChannelId, b: &ChannelId) -> bool { 128 | if a.inner == b.inner { return true; } 129 | if a.inner.is_null() || b.inner.is_null() { return false; } 130 | if a.get_native_ref() == b.get_native_ref() { true } else { false } 131 | } 132 | /// Generates a non-cryptographic 64-bit hash of the ChannelId. 133 | #[no_mangle] 134 | pub extern "C" fn ChannelId_hash(o: &ChannelId) -> u64 { 135 | if o.inner.is_null() { return 0; } 136 | // Note that we'd love to use alloc::collections::hash_map::DefaultHasher but it's not in core 137 | #[allow(deprecated)] 138 | let mut hasher = core::hash::SipHasher::new(); 139 | core::hash::Hash::hash(o.get_native_ref(), &mut hasher); 140 | core::hash::Hasher::finish(&hasher) 141 | } 142 | /// Create _v1_ channel ID based on a funding TX ID and output index 143 | #[must_use] 144 | #[no_mangle] 145 | pub extern "C" fn ChannelId_v1_from_funding_txid(txid: *const [u8; 32], mut output_index: u16) -> crate::lightning::ln::types::ChannelId { 146 | let mut ret = lightning::ln::types::ChannelId::v1_from_funding_txid(unsafe { &*txid}, output_index); 147 | crate::lightning::ln::types::ChannelId { inner: ObjOps::heap_alloc(ret), is_owned: true } 148 | } 149 | 150 | /// Create _v1_ channel ID from a funding tx outpoint 151 | #[must_use] 152 | #[no_mangle] 153 | pub extern "C" fn ChannelId_v1_from_funding_outpoint(mut outpoint: crate::lightning::chain::transaction::OutPoint) -> crate::lightning::ln::types::ChannelId { 154 | let mut ret = lightning::ln::types::ChannelId::v1_from_funding_outpoint(*unsafe { Box::from_raw(outpoint.take_inner()) }); 155 | crate::lightning::ln::types::ChannelId { inner: ObjOps::heap_alloc(ret), is_owned: true } 156 | } 157 | 158 | /// Create a _temporary_ channel ID randomly, based on an entropy source. 159 | #[must_use] 160 | #[no_mangle] 161 | pub extern "C" fn ChannelId_temporary_from_entropy_source(entropy_source: &crate::lightning::sign::EntropySource) -> crate::lightning::ln::types::ChannelId { 162 | let mut ret = lightning::ln::types::ChannelId::temporary_from_entropy_source(entropy_source); 163 | crate::lightning::ln::types::ChannelId { inner: ObjOps::heap_alloc(ret), is_owned: true } 164 | } 165 | 166 | /// Generic constructor; create a new channel ID from the provided data. 167 | /// Use a more specific `*_from_*` constructor when possible. 168 | #[must_use] 169 | #[no_mangle] 170 | pub extern "C" fn ChannelId_from_bytes(mut data: crate::c_types::ThirtyTwoBytes) -> crate::lightning::ln::types::ChannelId { 171 | let mut ret = lightning::ln::types::ChannelId::from_bytes(data.data); 172 | crate::lightning::ln::types::ChannelId { inner: ObjOps::heap_alloc(ret), is_owned: true } 173 | } 174 | 175 | /// Create a channel ID consisting of all-zeros data (e.g. when uninitialized or a placeholder). 176 | #[must_use] 177 | #[no_mangle] 178 | pub extern "C" fn ChannelId_new_zero() -> crate::lightning::ln::types::ChannelId { 179 | let mut ret = lightning::ln::types::ChannelId::new_zero(); 180 | crate::lightning::ln::types::ChannelId { inner: ObjOps::heap_alloc(ret), is_owned: true } 181 | } 182 | 183 | /// Check whether ID is consisting of all zeros (uninitialized) 184 | #[must_use] 185 | #[no_mangle] 186 | pub extern "C" fn ChannelId_is_zero(this_arg: &crate::lightning::ln::types::ChannelId) -> bool { 187 | let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.is_zero(); 188 | ret 189 | } 190 | 191 | /// Create _v2_ channel ID by concatenating the holder revocation basepoint with the counterparty 192 | /// revocation basepoint and hashing the result. The basepoints will be concatenated in increasing 193 | /// sorted order. 194 | #[must_use] 195 | #[no_mangle] 196 | pub extern "C" fn ChannelId_v2_from_revocation_basepoints(ours: &crate::lightning::ln::channel_keys::RevocationBasepoint, theirs: &crate::lightning::ln::channel_keys::RevocationBasepoint) -> crate::lightning::ln::types::ChannelId { 197 | let mut ret = lightning::ln::types::ChannelId::v2_from_revocation_basepoints(ours.get_native_ref(), theirs.get_native_ref()); 198 | crate::lightning::ln::types::ChannelId { inner: ObjOps::heap_alloc(ret), is_owned: true } 199 | } 200 | 201 | /// Create temporary _v2_ channel ID by concatenating a zeroed out basepoint with the holder 202 | /// revocation basepoint and hashing the result. 203 | #[must_use] 204 | #[no_mangle] 205 | pub extern "C" fn ChannelId_temporary_v2_from_revocation_basepoint(our_revocation_basepoint: &crate::lightning::ln::channel_keys::RevocationBasepoint) -> crate::lightning::ln::types::ChannelId { 206 | let mut ret = lightning::ln::types::ChannelId::temporary_v2_from_revocation_basepoint(our_revocation_basepoint.get_native_ref()); 207 | crate::lightning::ln::types::ChannelId { inner: ObjOps::heap_alloc(ret), is_owned: true } 208 | } 209 | 210 | #[no_mangle] 211 | /// Serialize the ChannelId object into a byte array which can be read by ChannelId_read 212 | pub extern "C" fn ChannelId_write(obj: &crate::lightning::ln::types::ChannelId) -> crate::c_types::derived::CVec_u8Z { 213 | crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) 214 | } 215 | #[allow(unused)] 216 | pub(crate) extern "C" fn ChannelId_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { 217 | crate::c_types::serialize_obj(unsafe { &*(obj as *const crate::lightning::ln::types::nativeChannelId) }) 218 | } 219 | #[no_mangle] 220 | /// Read a ChannelId from a byte array, created by ChannelId_write 221 | pub extern "C" fn ChannelId_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelIdDecodeErrorZ { 222 | let res: Result = crate::c_types::deserialize_obj(ser); 223 | let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::types::ChannelId { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() }; 224 | local_res 225 | } 226 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /lightning-c-bindings/src/lightning/ln/mod.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history and in the source files from which this was generated. 3 | // 4 | // This file is licensed under the license available in the LICENSE or LICENSE.md 5 | // file in the root of this repository or, if no such file exists, the same 6 | // license as that which applies to the original source files from which this 7 | // source was automatically generated. 8 | 9 | //! Implementations of various parts of the Lightning protocol are in this module. 10 | 11 | use alloc::str::FromStr; 12 | use alloc::string::String; 13 | use core::ffi::c_void; 14 | use core::convert::Infallible; 15 | use bitcoin::hashes::Hash; 16 | use crate::c_types::*; 17 | #[cfg(feature="no-std")] 18 | use alloc::{vec::Vec, boxed::Box}; 19 | 20 | pub mod onion_payment; 21 | pub mod channelmanager; 22 | pub mod channel_keys; 23 | pub mod channel_state; 24 | pub mod inbound_payment; 25 | pub mod msgs; 26 | pub mod peer_handler; 27 | pub mod chan_utils; 28 | pub mod script; 29 | pub mod types; 30 | pub mod invoice_utils; 31 | pub mod bolt11_payment; 32 | pub mod outbound_payment; 33 | pub mod wire; 34 | mod features { 35 | 36 | use alloc::str::FromStr; 37 | use alloc::string::String; 38 | use core::ffi::c_void; 39 | use core::convert::Infallible; 40 | use bitcoin::hashes::Hash; 41 | use crate::c_types::*; 42 | #[cfg(feature="no-std")] 43 | use alloc::{vec::Vec, boxed::Box}; 44 | 45 | #[no_mangle] 46 | /// Serialize the InitFeatures object into a byte array which can be read by InitFeatures_read 47 | pub extern "C" fn InitFeatures_write(obj: &crate::lightning_types::features::InitFeatures) -> crate::c_types::derived::CVec_u8Z { 48 | crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) 49 | } 50 | #[allow(unused)] 51 | pub(crate) extern "C" fn InitFeatures_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { 52 | crate::c_types::serialize_obj(unsafe { &*(obj as *const crate::lightning_types::features::nativeInitFeatures) }) 53 | } 54 | #[no_mangle] 55 | /// Read a InitFeatures from a byte array, created by InitFeatures_write 56 | pub extern "C" fn InitFeatures_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_InitFeaturesDecodeErrorZ { 57 | let res: Result = crate::c_types::deserialize_obj(ser); 58 | let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_types::features::InitFeatures { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() }; 59 | local_res 60 | } 61 | #[no_mangle] 62 | /// Serialize the ChannelFeatures object into a byte array which can be read by ChannelFeatures_read 63 | pub extern "C" fn ChannelFeatures_write(obj: &crate::lightning_types::features::ChannelFeatures) -> crate::c_types::derived::CVec_u8Z { 64 | crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) 65 | } 66 | #[allow(unused)] 67 | pub(crate) extern "C" fn ChannelFeatures_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { 68 | crate::c_types::serialize_obj(unsafe { &*(obj as *const crate::lightning_types::features::nativeChannelFeatures) }) 69 | } 70 | #[no_mangle] 71 | /// Read a ChannelFeatures from a byte array, created by ChannelFeatures_write 72 | pub extern "C" fn ChannelFeatures_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelFeaturesDecodeErrorZ { 73 | let res: Result = crate::c_types::deserialize_obj(ser); 74 | let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_types::features::ChannelFeatures { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() }; 75 | local_res 76 | } 77 | #[no_mangle] 78 | /// Serialize the NodeFeatures object into a byte array which can be read by NodeFeatures_read 79 | pub extern "C" fn NodeFeatures_write(obj: &crate::lightning_types::features::NodeFeatures) -> crate::c_types::derived::CVec_u8Z { 80 | crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) 81 | } 82 | #[allow(unused)] 83 | pub(crate) extern "C" fn NodeFeatures_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { 84 | crate::c_types::serialize_obj(unsafe { &*(obj as *const crate::lightning_types::features::nativeNodeFeatures) }) 85 | } 86 | #[no_mangle] 87 | /// Read a NodeFeatures from a byte array, created by NodeFeatures_write 88 | pub extern "C" fn NodeFeatures_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_NodeFeaturesDecodeErrorZ { 89 | let res: Result = crate::c_types::deserialize_obj(ser); 90 | let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_types::features::NodeFeatures { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() }; 91 | local_res 92 | } 93 | #[no_mangle] 94 | /// Serialize the Bolt11InvoiceFeatures object into a byte array which can be read by Bolt11InvoiceFeatures_read 95 | pub extern "C" fn Bolt11InvoiceFeatures_write(obj: &crate::lightning_types::features::Bolt11InvoiceFeatures) -> crate::c_types::derived::CVec_u8Z { 96 | crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) 97 | } 98 | #[allow(unused)] 99 | pub(crate) extern "C" fn Bolt11InvoiceFeatures_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { 100 | crate::c_types::serialize_obj(unsafe { &*(obj as *const crate::lightning_types::features::nativeBolt11InvoiceFeatures) }) 101 | } 102 | #[no_mangle] 103 | /// Read a Bolt11InvoiceFeatures from a byte array, created by Bolt11InvoiceFeatures_write 104 | pub extern "C" fn Bolt11InvoiceFeatures_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_Bolt11InvoiceFeaturesDecodeErrorZ { 105 | let res: Result = crate::c_types::deserialize_obj(ser); 106 | let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_types::features::Bolt11InvoiceFeatures { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() }; 107 | local_res 108 | } 109 | #[no_mangle] 110 | /// Serialize the Bolt12InvoiceFeatures object into a byte array which can be read by Bolt12InvoiceFeatures_read 111 | pub extern "C" fn Bolt12InvoiceFeatures_write(obj: &crate::lightning_types::features::Bolt12InvoiceFeatures) -> crate::c_types::derived::CVec_u8Z { 112 | crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) 113 | } 114 | #[allow(unused)] 115 | pub(crate) extern "C" fn Bolt12InvoiceFeatures_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { 116 | crate::c_types::serialize_obj(unsafe { &*(obj as *const crate::lightning_types::features::nativeBolt12InvoiceFeatures) }) 117 | } 118 | #[no_mangle] 119 | /// Read a Bolt12InvoiceFeatures from a byte array, created by Bolt12InvoiceFeatures_write 120 | pub extern "C" fn Bolt12InvoiceFeatures_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_Bolt12InvoiceFeaturesDecodeErrorZ { 121 | let res: Result = crate::c_types::deserialize_obj(ser); 122 | let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_types::features::Bolt12InvoiceFeatures { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() }; 123 | local_res 124 | } 125 | #[no_mangle] 126 | /// Serialize the BlindedHopFeatures object into a byte array which can be read by BlindedHopFeatures_read 127 | pub extern "C" fn BlindedHopFeatures_write(obj: &crate::lightning_types::features::BlindedHopFeatures) -> crate::c_types::derived::CVec_u8Z { 128 | crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) 129 | } 130 | #[allow(unused)] 131 | pub(crate) extern "C" fn BlindedHopFeatures_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { 132 | crate::c_types::serialize_obj(unsafe { &*(obj as *const crate::lightning_types::features::nativeBlindedHopFeatures) }) 133 | } 134 | #[no_mangle] 135 | /// Read a BlindedHopFeatures from a byte array, created by BlindedHopFeatures_write 136 | pub extern "C" fn BlindedHopFeatures_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_BlindedHopFeaturesDecodeErrorZ { 137 | let res: Result = crate::c_types::deserialize_obj(ser); 138 | let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_types::features::BlindedHopFeatures { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() }; 139 | local_res 140 | } 141 | #[no_mangle] 142 | /// Serialize the ChannelTypeFeatures object into a byte array which can be read by ChannelTypeFeatures_read 143 | pub extern "C" fn ChannelTypeFeatures_write(obj: &crate::lightning_types::features::ChannelTypeFeatures) -> crate::c_types::derived::CVec_u8Z { 144 | crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) 145 | } 146 | #[allow(unused)] 147 | pub(crate) extern "C" fn ChannelTypeFeatures_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { 148 | crate::c_types::serialize_obj(unsafe { &*(obj as *const crate::lightning_types::features::nativeChannelTypeFeatures) }) 149 | } 150 | #[no_mangle] 151 | /// Read a ChannelTypeFeatures from a byte array, created by ChannelTypeFeatures_write 152 | pub extern "C" fn ChannelTypeFeatures_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelTypeFeaturesDecodeErrorZ { 153 | let res: Result = crate::c_types::deserialize_obj(ser); 154 | let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_types::features::ChannelTypeFeatures { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() }; 155 | local_res 156 | } 157 | } 158 | mod peer_channel_encryptor { 159 | 160 | use alloc::str::FromStr; 161 | use alloc::string::String; 162 | use core::ffi::c_void; 163 | use core::convert::Infallible; 164 | use bitcoin::hashes::Hash; 165 | use crate::c_types::*; 166 | #[cfg(feature="no-std")] 167 | use alloc::{vec::Vec, boxed::Box}; 168 | 169 | } 170 | mod channel { 171 | 172 | use alloc::str::FromStr; 173 | use alloc::string::String; 174 | use core::ffi::c_void; 175 | use core::convert::Infallible; 176 | use bitcoin::hashes::Hash; 177 | use crate::c_types::*; 178 | #[cfg(feature="no-std")] 179 | use alloc::{vec::Vec, boxed::Box}; 180 | 181 | mod state_flags { 182 | 183 | use alloc::str::FromStr; 184 | use alloc::string::String; 185 | use core::ffi::c_void; 186 | use core::convert::Infallible; 187 | use bitcoin::hashes::Hash; 188 | use crate::c_types::*; 189 | #[cfg(feature="no-std")] 190 | use alloc::{vec::Vec, boxed::Box}; 191 | 192 | } 193 | } 194 | mod onion_utils { 195 | 196 | use alloc::str::FromStr; 197 | use alloc::string::String; 198 | use core::ffi::c_void; 199 | use core::convert::Infallible; 200 | use bitcoin::hashes::Hash; 201 | use crate::c_types::*; 202 | #[cfg(feature="no-std")] 203 | use alloc::{vec::Vec, boxed::Box}; 204 | 205 | } 206 | mod interactivetxs { 207 | 208 | use alloc::str::FromStr; 209 | use alloc::string::String; 210 | use core::ffi::c_void; 211 | use core::convert::Infallible; 212 | use bitcoin::hashes::Hash; 213 | use crate::c_types::*; 214 | #[cfg(feature="no-std")] 215 | use alloc::{vec::Vec, boxed::Box}; 216 | 217 | } 218 | -------------------------------------------------------------------------------- /lightning-c-bindings/src/lightning/util/wakers.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history and in the source files from which this was generated. 3 | // 4 | // This file is licensed under the license available in the LICENSE or LICENSE.md 5 | // file in the root of this repository or, if no such file exists, the same 6 | // license as that which applies to the original source files from which this 7 | // source was automatically generated. 8 | 9 | //! Utilities which allow users to block on some future notification from LDK. These are 10 | //! specifically used by [`ChannelManager`] to allow waiting until the [`ChannelManager`] needs to 11 | //! be re-persisted. 12 | //! 13 | //! [`ChannelManager`]: crate::ln::channelmanager::ChannelManager 14 | 15 | use alloc::str::FromStr; 16 | use alloc::string::String; 17 | use core::ffi::c_void; 18 | use core::convert::Infallible; 19 | use bitcoin::hashes::Hash; 20 | use crate::c_types::*; 21 | #[cfg(feature="no-std")] 22 | use alloc::{vec::Vec, boxed::Box}; 23 | 24 | /// A callback which is called when a [`Future`] completes. 25 | /// 26 | /// Note that this MUST NOT call back into LDK directly, it must instead schedule actions to be 27 | /// taken later. 28 | ///Rust users should use the [`std::future::Future`] implementation for [`Future`] instead. 29 | /// 30 | ///Note that the [`std::future::Future`] implementation may only work for runtimes which schedule futures when they receive a wake, rather than immediately executing them. 31 | #[repr(C)] 32 | pub struct FutureCallback { 33 | /// An opaque pointer which is passed to your function implementations as an argument. 34 | /// This has no meaning in the LDK, and can be NULL or any other value. 35 | pub this_arg: *mut c_void, 36 | /// The method which is called. 37 | pub call: extern "C" fn (this_arg: *const c_void), 38 | /// Frees any resources associated with this object given its this_arg pointer. 39 | /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed. 40 | pub free: Option, 41 | } 42 | unsafe impl Send for FutureCallback {} 43 | unsafe impl Sync for FutureCallback {} 44 | #[allow(unused)] 45 | pub(crate) fn FutureCallback_clone_fields(orig: &FutureCallback) -> FutureCallback { 46 | FutureCallback { 47 | this_arg: orig.this_arg, 48 | call: Clone::clone(&orig.call), 49 | free: Clone::clone(&orig.free), 50 | } 51 | } 52 | 53 | use lightning::util::wakers::FutureCallback as rustFutureCallback; 54 | impl rustFutureCallback for FutureCallback { 55 | fn call(&self) { 56 | (self.call)(self.this_arg) 57 | } 58 | } 59 | 60 | pub struct FutureCallbackRef(FutureCallback); 61 | impl rustFutureCallback for FutureCallbackRef { 62 | fn call(&self) { 63 | (self.0.call)(self.0.this_arg) 64 | } 65 | } 66 | 67 | // We're essentially a pointer already, or at least a set of pointers, so allow us to be used 68 | // directly as a Deref trait in higher-level structs: 69 | impl core::ops::Deref for FutureCallback { 70 | type Target = FutureCallbackRef; 71 | fn deref(&self) -> &Self::Target { 72 | unsafe { &*(self as *const _ as *const FutureCallbackRef) } 73 | } 74 | } 75 | impl core::ops::DerefMut for FutureCallback { 76 | fn deref_mut(&mut self) -> &mut FutureCallbackRef { 77 | unsafe { &mut *(self as *mut _ as *mut FutureCallbackRef) } 78 | } 79 | } 80 | /// Calls the free function if one is set 81 | #[no_mangle] 82 | pub extern "C" fn FutureCallback_free(this_ptr: FutureCallback) { } 83 | impl Drop for FutureCallback { 84 | fn drop(&mut self) { 85 | if let Some(f) = self.free { 86 | f(self.this_arg); 87 | } 88 | } 89 | } 90 | 91 | use lightning::util::wakers::Future as nativeFutureImport; 92 | pub(crate) type nativeFuture = nativeFutureImport; 93 | 94 | /// A simple future which can complete once, and calls some callback(s) when it does so. 95 | #[must_use] 96 | #[repr(C)] 97 | pub struct Future { 98 | /// A pointer to the opaque Rust object. 99 | 100 | /// Nearly everywhere, inner must be non-null, however in places where 101 | /// the Rust equivalent takes an Option, it may be set to null to indicate None. 102 | pub inner: *mut nativeFuture, 103 | /// Indicates that this is the only struct which contains the same pointer. 104 | 105 | /// Rust functions which take ownership of an object provided via an argument require 106 | /// this to be true and invalidate the object pointed to by inner. 107 | pub is_owned: bool, 108 | } 109 | 110 | impl core::ops::Deref for Future { 111 | type Target = nativeFuture; 112 | fn deref(&self) -> &Self::Target { unsafe { &*ObjOps::untweak_ptr(self.inner) } } 113 | } 114 | unsafe impl core::marker::Send for Future { } 115 | unsafe impl core::marker::Sync for Future { } 116 | impl Drop for Future { 117 | fn drop(&mut self) { 118 | if self.is_owned && !<*mut nativeFuture>::is_null(self.inner) { 119 | let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; 120 | } 121 | } 122 | } 123 | /// Frees any resources used by the Future, if is_owned is set and inner is non-NULL. 124 | #[no_mangle] 125 | pub extern "C" fn Future_free(this_obj: Future) { } 126 | #[allow(unused)] 127 | /// Used only if an object of this type is returned as a trait impl by a method 128 | pub(crate) extern "C" fn Future_free_void(this_ptr: *mut c_void) { 129 | let _ = unsafe { Box::from_raw(this_ptr as *mut nativeFuture) }; 130 | } 131 | #[allow(unused)] 132 | impl Future { 133 | pub(crate) fn get_native_ref(&self) -> &'static nativeFuture { 134 | unsafe { &*ObjOps::untweak_ptr(self.inner) } 135 | } 136 | pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeFuture { 137 | unsafe { &mut *ObjOps::untweak_ptr(self.inner) } 138 | } 139 | /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy 140 | pub(crate) fn take_inner(mut self) -> *mut nativeFuture { 141 | assert!(self.is_owned); 142 | let ret = ObjOps::untweak_ptr(self.inner); 143 | self.inner = core::ptr::null_mut(); 144 | ret 145 | } 146 | pub(crate) fn as_ref_to(&self) -> Self { 147 | Self { inner: self.inner, is_owned: false } 148 | } 149 | } 150 | /// Registers a callback to be called upon completion of this future. If the future has already 151 | /// completed, the callback will be called immediately. 152 | #[no_mangle] 153 | pub extern "C" fn Future_register_callback_fn(this_arg: &crate::lightning::util::wakers::Future, mut callback: crate::lightning::util::wakers::FutureCallback) { 154 | unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.register_callback_fn(callback) 155 | } 156 | 157 | /// Waits until this [`Future`] completes. 158 | #[no_mangle] 159 | pub extern "C" fn Future_wait(this_arg: &crate::lightning::util::wakers::Future) { 160 | unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.wait() 161 | } 162 | 163 | /// Waits until this [`Future`] completes or the given amount of time has elapsed. 164 | /// 165 | /// Returns true if the [`Future`] completed, false if the time elapsed. 166 | #[must_use] 167 | #[no_mangle] 168 | pub extern "C" fn Future_wait_timeout(this_arg: &crate::lightning::util::wakers::Future, mut max_wait: u64) -> bool { 169 | let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.wait_timeout(core::time::Duration::from_secs(max_wait)); 170 | ret 171 | } 172 | 173 | 174 | use lightning::util::wakers::Sleeper as nativeSleeperImport; 175 | pub(crate) type nativeSleeper = nativeSleeperImport; 176 | 177 | /// A struct which can be used to select across many [`Future`]s at once without relying on a full 178 | /// async context. 179 | #[must_use] 180 | #[repr(C)] 181 | pub struct Sleeper { 182 | /// A pointer to the opaque Rust object. 183 | 184 | /// Nearly everywhere, inner must be non-null, however in places where 185 | /// the Rust equivalent takes an Option, it may be set to null to indicate None. 186 | pub inner: *mut nativeSleeper, 187 | /// Indicates that this is the only struct which contains the same pointer. 188 | 189 | /// Rust functions which take ownership of an object provided via an argument require 190 | /// this to be true and invalidate the object pointed to by inner. 191 | pub is_owned: bool, 192 | } 193 | 194 | impl core::ops::Deref for Sleeper { 195 | type Target = nativeSleeper; 196 | fn deref(&self) -> &Self::Target { unsafe { &*ObjOps::untweak_ptr(self.inner) } } 197 | } 198 | unsafe impl core::marker::Send for Sleeper { } 199 | unsafe impl core::marker::Sync for Sleeper { } 200 | impl Drop for Sleeper { 201 | fn drop(&mut self) { 202 | if self.is_owned && !<*mut nativeSleeper>::is_null(self.inner) { 203 | let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; 204 | } 205 | } 206 | } 207 | /// Frees any resources used by the Sleeper, if is_owned is set and inner is non-NULL. 208 | #[no_mangle] 209 | pub extern "C" fn Sleeper_free(this_obj: Sleeper) { } 210 | #[allow(unused)] 211 | /// Used only if an object of this type is returned as a trait impl by a method 212 | pub(crate) extern "C" fn Sleeper_free_void(this_ptr: *mut c_void) { 213 | let _ = unsafe { Box::from_raw(this_ptr as *mut nativeSleeper) }; 214 | } 215 | #[allow(unused)] 216 | impl Sleeper { 217 | pub(crate) fn get_native_ref(&self) -> &'static nativeSleeper { 218 | unsafe { &*ObjOps::untweak_ptr(self.inner) } 219 | } 220 | pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeSleeper { 221 | unsafe { &mut *ObjOps::untweak_ptr(self.inner) } 222 | } 223 | /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy 224 | pub(crate) fn take_inner(mut self) -> *mut nativeSleeper { 225 | assert!(self.is_owned); 226 | let ret = ObjOps::untweak_ptr(self.inner); 227 | self.inner = core::ptr::null_mut(); 228 | ret 229 | } 230 | pub(crate) fn as_ref_to(&self) -> Self { 231 | Self { inner: self.inner, is_owned: false } 232 | } 233 | } 234 | /// Constructs a new sleeper from one future, allowing blocking on it. 235 | #[must_use] 236 | #[no_mangle] 237 | pub extern "C" fn Sleeper_from_single_future(future: &crate::lightning::util::wakers::Future) -> crate::lightning::util::wakers::Sleeper { 238 | let mut ret = lightning::util::wakers::Sleeper::from_single_future(future.get_native_ref()); 239 | crate::lightning::util::wakers::Sleeper { inner: ObjOps::heap_alloc(ret), is_owned: true } 240 | } 241 | 242 | /// Constructs a new sleeper from two futures, allowing blocking on both at once. 243 | #[must_use] 244 | #[no_mangle] 245 | pub extern "C" fn Sleeper_from_two_futures(fut_a: &crate::lightning::util::wakers::Future, fut_b: &crate::lightning::util::wakers::Future) -> crate::lightning::util::wakers::Sleeper { 246 | let mut ret = lightning::util::wakers::Sleeper::from_two_futures(fut_a.get_native_ref(), fut_b.get_native_ref()); 247 | crate::lightning::util::wakers::Sleeper { inner: ObjOps::heap_alloc(ret), is_owned: true } 248 | } 249 | 250 | /// Constructs a new sleeper from three futures, allowing blocking on all three at once. 251 | /// 252 | #[must_use] 253 | #[no_mangle] 254 | pub extern "C" fn Sleeper_from_three_futures(fut_a: &crate::lightning::util::wakers::Future, fut_b: &crate::lightning::util::wakers::Future, fut_c: &crate::lightning::util::wakers::Future) -> crate::lightning::util::wakers::Sleeper { 255 | let mut ret = lightning::util::wakers::Sleeper::from_three_futures(fut_a.get_native_ref(), fut_b.get_native_ref(), fut_c.get_native_ref()); 256 | crate::lightning::util::wakers::Sleeper { inner: ObjOps::heap_alloc(ret), is_owned: true } 257 | } 258 | 259 | /// Constructs a new sleeper on many futures, allowing blocking on all at once. 260 | #[must_use] 261 | #[no_mangle] 262 | pub extern "C" fn Sleeper_new(mut futures: crate::c_types::derived::CVec_FutureZ) -> crate::lightning::util::wakers::Sleeper { 263 | let mut local_futures = Vec::new(); for mut item in futures.into_rust().drain(..) { local_futures.push( { *unsafe { Box::from_raw(item.take_inner()) } }); }; 264 | let mut ret = lightning::util::wakers::Sleeper::new(local_futures); 265 | crate::lightning::util::wakers::Sleeper { inner: ObjOps::heap_alloc(ret), is_owned: true } 266 | } 267 | 268 | /// Wait until one of the [`Future`]s registered with this [`Sleeper`] has completed. 269 | #[no_mangle] 270 | pub extern "C" fn Sleeper_wait(this_arg: &crate::lightning::util::wakers::Sleeper) { 271 | unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.wait() 272 | } 273 | 274 | /// Wait until one of the [`Future`]s registered with this [`Sleeper`] has completed or the 275 | /// given amount of time has elapsed. Returns true if a [`Future`] completed, false if the time 276 | /// elapsed. 277 | #[must_use] 278 | #[no_mangle] 279 | pub extern "C" fn Sleeper_wait_timeout(this_arg: &crate::lightning::util::wakers::Sleeper, mut max_wait: u64) -> bool { 280 | let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.wait_timeout(core::time::Duration::from_secs(max_wait)); 281 | ret 282 | } 283 | 284 | -------------------------------------------------------------------------------- /lightning-c-bindings/src/lightning/util/errors.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history and in the source files from which this was generated. 3 | // 4 | // This file is licensed under the license available in the LICENSE or LICENSE.md 5 | // file in the root of this repository or, if no such file exists, the same 6 | // license as that which applies to the original source files from which this 7 | // source was automatically generated. 8 | 9 | //! Error types live here. 10 | 11 | use alloc::str::FromStr; 12 | use alloc::string::String; 13 | use core::ffi::c_void; 14 | use core::convert::Infallible; 15 | use bitcoin::hashes::Hash; 16 | use crate::c_types::*; 17 | #[cfg(feature="no-std")] 18 | use alloc::{vec::Vec, boxed::Box}; 19 | 20 | /// Indicates an error on the client's part (usually some variant of attempting to use too-low or 21 | /// too-high values) 22 | #[derive(Clone)] 23 | #[must_use] 24 | #[repr(C)] 25 | pub enum APIError { 26 | /// Indicates the API was wholly misused (see err for more). Cases where these can be returned 27 | /// are documented, but generally indicates some precondition of a function was violated. 28 | APIMisuseError { 29 | /// A human-readable error message 30 | err: crate::c_types::Str, 31 | }, 32 | /// Due to a high feerate, we were unable to complete the request. 33 | /// For example, this may be returned if the feerate implies we cannot open a channel at the 34 | /// requested value, but opening a larger channel would succeed. 35 | FeeRateTooHigh { 36 | /// A human-readable error message 37 | err: crate::c_types::Str, 38 | /// The feerate which was too high. 39 | feerate: u32, 40 | }, 41 | /// A malformed Route was provided (eg overflowed value, node id mismatch, overly-looped route, 42 | /// too-many-hops, etc). 43 | InvalidRoute { 44 | /// A human-readable error message 45 | err: crate::c_types::Str, 46 | }, 47 | /// We were unable to complete the request as the Channel required to do so is unable to 48 | /// complete the request (or was not found). This can take many forms, including disconnected 49 | /// peer, channel at capacity, channel shutting down, etc. 50 | ChannelUnavailable { 51 | /// A human-readable error message 52 | err: crate::c_types::Str, 53 | }, 54 | /// An attempt to call [`chain::Watch::watch_channel`]/[`chain::Watch::update_channel`] 55 | /// returned a [`ChannelMonitorUpdateStatus::InProgress`] indicating the persistence of a 56 | /// monitor update is awaiting async resolution. Once it resolves the attempted action should 57 | /// complete automatically. 58 | /// 59 | /// [`chain::Watch::watch_channel`]: crate::chain::Watch::watch_channel 60 | /// [`chain::Watch::update_channel`]: crate::chain::Watch::update_channel 61 | /// [`ChannelMonitorUpdateStatus::InProgress`]: crate::chain::ChannelMonitorUpdateStatus::InProgress 62 | MonitorUpdateInProgress, 63 | /// [`SignerProvider::get_shutdown_scriptpubkey`] returned a shutdown scriptpubkey incompatible 64 | /// with the channel counterparty as negotiated in [`InitFeatures`]. 65 | /// 66 | /// Using a SegWit v0 script should resolve this issue. If you cannot, you won't be able to open 67 | /// a channel or cooperatively close one with this peer (and will have to force-close instead). 68 | /// 69 | /// [`SignerProvider::get_shutdown_scriptpubkey`]: crate::sign::SignerProvider::get_shutdown_scriptpubkey 70 | /// [`InitFeatures`]: crate::types::features::InitFeatures 71 | IncompatibleShutdownScript { 72 | /// The incompatible shutdown script. 73 | script: crate::lightning::ln::script::ShutdownScript, 74 | }, 75 | } 76 | use lightning::util::errors::APIError as APIErrorImport; 77 | pub(crate) type nativeAPIError = APIErrorImport; 78 | 79 | impl APIError { 80 | #[allow(unused)] 81 | pub(crate) fn to_native(&self) -> nativeAPIError { 82 | match self { 83 | APIError::APIMisuseError {ref err, } => { 84 | let mut err_nonref = Clone::clone(err); 85 | nativeAPIError::APIMisuseError { 86 | err: err_nonref.into_string(), 87 | } 88 | }, 89 | APIError::FeeRateTooHigh {ref err, ref feerate, } => { 90 | let mut err_nonref = Clone::clone(err); 91 | let mut feerate_nonref = Clone::clone(feerate); 92 | nativeAPIError::FeeRateTooHigh { 93 | err: err_nonref.into_string(), 94 | feerate: feerate_nonref, 95 | } 96 | }, 97 | APIError::InvalidRoute {ref err, } => { 98 | let mut err_nonref = Clone::clone(err); 99 | nativeAPIError::InvalidRoute { 100 | err: err_nonref.into_string(), 101 | } 102 | }, 103 | APIError::ChannelUnavailable {ref err, } => { 104 | let mut err_nonref = Clone::clone(err); 105 | nativeAPIError::ChannelUnavailable { 106 | err: err_nonref.into_string(), 107 | } 108 | }, 109 | APIError::MonitorUpdateInProgress => nativeAPIError::MonitorUpdateInProgress, 110 | APIError::IncompatibleShutdownScript {ref script, } => { 111 | let mut script_nonref = Clone::clone(script); 112 | nativeAPIError::IncompatibleShutdownScript { 113 | script: *unsafe { Box::from_raw(script_nonref.take_inner()) }, 114 | } 115 | }, 116 | } 117 | } 118 | #[allow(unused)] 119 | pub(crate) fn into_native(self) -> nativeAPIError { 120 | match self { 121 | APIError::APIMisuseError {mut err, } => { 122 | nativeAPIError::APIMisuseError { 123 | err: err.into_string(), 124 | } 125 | }, 126 | APIError::FeeRateTooHigh {mut err, mut feerate, } => { 127 | nativeAPIError::FeeRateTooHigh { 128 | err: err.into_string(), 129 | feerate: feerate, 130 | } 131 | }, 132 | APIError::InvalidRoute {mut err, } => { 133 | nativeAPIError::InvalidRoute { 134 | err: err.into_string(), 135 | } 136 | }, 137 | APIError::ChannelUnavailable {mut err, } => { 138 | nativeAPIError::ChannelUnavailable { 139 | err: err.into_string(), 140 | } 141 | }, 142 | APIError::MonitorUpdateInProgress => nativeAPIError::MonitorUpdateInProgress, 143 | APIError::IncompatibleShutdownScript {mut script, } => { 144 | nativeAPIError::IncompatibleShutdownScript { 145 | script: *unsafe { Box::from_raw(script.take_inner()) }, 146 | } 147 | }, 148 | } 149 | } 150 | #[allow(unused)] 151 | pub(crate) fn from_native(native: &APIErrorImport) -> Self { 152 | let native = unsafe { &*(native as *const _ as *const c_void as *const nativeAPIError) }; 153 | match native { 154 | nativeAPIError::APIMisuseError {ref err, } => { 155 | let mut err_nonref = Clone::clone(err); 156 | APIError::APIMisuseError { 157 | err: err_nonref.into(), 158 | } 159 | }, 160 | nativeAPIError::FeeRateTooHigh {ref err, ref feerate, } => { 161 | let mut err_nonref = Clone::clone(err); 162 | let mut feerate_nonref = Clone::clone(feerate); 163 | APIError::FeeRateTooHigh { 164 | err: err_nonref.into(), 165 | feerate: feerate_nonref, 166 | } 167 | }, 168 | nativeAPIError::InvalidRoute {ref err, } => { 169 | let mut err_nonref = Clone::clone(err); 170 | APIError::InvalidRoute { 171 | err: err_nonref.into(), 172 | } 173 | }, 174 | nativeAPIError::ChannelUnavailable {ref err, } => { 175 | let mut err_nonref = Clone::clone(err); 176 | APIError::ChannelUnavailable { 177 | err: err_nonref.into(), 178 | } 179 | }, 180 | nativeAPIError::MonitorUpdateInProgress => APIError::MonitorUpdateInProgress, 181 | nativeAPIError::IncompatibleShutdownScript {ref script, } => { 182 | let mut script_nonref = Clone::clone(script); 183 | APIError::IncompatibleShutdownScript { 184 | script: crate::lightning::ln::script::ShutdownScript { inner: ObjOps::heap_alloc(script_nonref), is_owned: true }, 185 | } 186 | }, 187 | } 188 | } 189 | #[allow(unused)] 190 | pub(crate) fn native_into(native: nativeAPIError) -> Self { 191 | match native { 192 | nativeAPIError::APIMisuseError {mut err, } => { 193 | APIError::APIMisuseError { 194 | err: err.into(), 195 | } 196 | }, 197 | nativeAPIError::FeeRateTooHigh {mut err, mut feerate, } => { 198 | APIError::FeeRateTooHigh { 199 | err: err.into(), 200 | feerate: feerate, 201 | } 202 | }, 203 | nativeAPIError::InvalidRoute {mut err, } => { 204 | APIError::InvalidRoute { 205 | err: err.into(), 206 | } 207 | }, 208 | nativeAPIError::ChannelUnavailable {mut err, } => { 209 | APIError::ChannelUnavailable { 210 | err: err.into(), 211 | } 212 | }, 213 | nativeAPIError::MonitorUpdateInProgress => APIError::MonitorUpdateInProgress, 214 | nativeAPIError::IncompatibleShutdownScript {mut script, } => { 215 | APIError::IncompatibleShutdownScript { 216 | script: crate::lightning::ln::script::ShutdownScript { inner: ObjOps::heap_alloc(script), is_owned: true }, 217 | } 218 | }, 219 | } 220 | } 221 | } 222 | /// Frees any resources used by the APIError 223 | #[no_mangle] 224 | pub extern "C" fn APIError_free(this_ptr: APIError) { } 225 | /// Creates a copy of the APIError 226 | #[no_mangle] 227 | pub extern "C" fn APIError_clone(orig: &APIError) -> APIError { 228 | orig.clone() 229 | } 230 | #[allow(unused)] 231 | /// Used only if an object of this type is returned as a trait impl by a method 232 | pub(crate) extern "C" fn APIError_clone_void(this_ptr: *const c_void) -> *mut c_void { 233 | Box::into_raw(Box::new(unsafe { (*(this_ptr as *const APIError)).clone() })) as *mut c_void 234 | } 235 | #[allow(unused)] 236 | /// Used only if an object of this type is returned as a trait impl by a method 237 | pub(crate) extern "C" fn APIError_free_void(this_ptr: *mut c_void) { 238 | let _ = unsafe { Box::from_raw(this_ptr as *mut APIError) }; 239 | } 240 | #[no_mangle] 241 | /// Utility method to constructs a new APIMisuseError-variant APIError 242 | pub extern "C" fn APIError_apimisuse_error(err: crate::c_types::Str) -> APIError { 243 | APIError::APIMisuseError { 244 | err, 245 | } 246 | } 247 | #[no_mangle] 248 | /// Utility method to constructs a new FeeRateTooHigh-variant APIError 249 | pub extern "C" fn APIError_fee_rate_too_high(err: crate::c_types::Str, feerate: u32) -> APIError { 250 | APIError::FeeRateTooHigh { 251 | err, 252 | feerate, 253 | } 254 | } 255 | #[no_mangle] 256 | /// Utility method to constructs a new InvalidRoute-variant APIError 257 | pub extern "C" fn APIError_invalid_route(err: crate::c_types::Str) -> APIError { 258 | APIError::InvalidRoute { 259 | err, 260 | } 261 | } 262 | #[no_mangle] 263 | /// Utility method to constructs a new ChannelUnavailable-variant APIError 264 | pub extern "C" fn APIError_channel_unavailable(err: crate::c_types::Str) -> APIError { 265 | APIError::ChannelUnavailable { 266 | err, 267 | } 268 | } 269 | #[no_mangle] 270 | /// Utility method to constructs a new MonitorUpdateInProgress-variant APIError 271 | pub extern "C" fn APIError_monitor_update_in_progress() -> APIError { 272 | APIError::MonitorUpdateInProgress} 273 | #[no_mangle] 274 | /// Utility method to constructs a new IncompatibleShutdownScript-variant APIError 275 | pub extern "C" fn APIError_incompatible_shutdown_script(script: crate::lightning::ln::script::ShutdownScript) -> APIError { 276 | APIError::IncompatibleShutdownScript { 277 | script, 278 | } 279 | } 280 | /// Checks if two APIErrors contain equal inner contents. 281 | /// This ignores pointers and is_owned flags and looks at the values in fields. 282 | #[no_mangle] 283 | pub extern "C" fn APIError_eq(a: &APIError, b: &APIError) -> bool { 284 | if &a.to_native() == &b.to_native() { true } else { false } 285 | } 286 | /// Get a string which allows debug introspection of a APIError object 287 | pub extern "C" fn APIError_debug_str_void(o: *const c_void) -> Str { 288 | alloc::format!("{:?}", unsafe { o as *const crate::lightning::util::errors::APIError }).into()} 289 | #[no_mangle] 290 | /// Serialize the APIError object into a byte array which can be read by APIError_read 291 | pub extern "C" fn APIError_write(obj: &crate::lightning::util::errors::APIError) -> crate::c_types::derived::CVec_u8Z { 292 | crate::c_types::serialize_obj(&unsafe { &*obj }.to_native()) 293 | } 294 | #[allow(unused)] 295 | pub(crate) extern "C" fn APIError_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { 296 | APIError_write(unsafe { &*(obj as *const APIError) }) 297 | } 298 | #[no_mangle] 299 | /// Read a APIError from a byte array, created by APIError_write 300 | pub extern "C" fn APIError_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_COption_APIErrorZDecodeErrorZ { 301 | let res: Result, lightning::ln::msgs::DecodeError> = crate::c_types::maybe_deserialize_obj(ser); 302 | let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { let mut local_res_0 = if o.is_none() { crate::c_types::derived::COption_APIErrorZ::None } else { crate::c_types::derived::COption_APIErrorZ::Some( { crate::lightning::util::errors::APIError::native_into(o.unwrap()) }) }; local_res_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() }; 303 | local_res 304 | } 305 | -------------------------------------------------------------------------------- /lightning-c-bindings/README.md: -------------------------------------------------------------------------------- 1 | The wrapper crate and C/C++ Headers in this folder are auto-generated from the Rust-Lightning 2 | source by the c-bindings-gen crate contained in the source tree and 3 | [cbindgen](https://github.com/eqrion/cbindgen). They are intended to be used as a base for building 4 | language-specific bindings, and are thus incredibly low-level and may be difficult to work with 5 | directly. 6 | 7 | In other words, if you're reading this, you're either writing bindings for a new language, or 8 | you're in the wrong place - individual language bindings should come with their own documentation. 9 | 10 | LDK C Bindings 11 | ============== 12 | 13 | The C bindings available at include/lightning.h require inclusion of include/rust_types.h first. 14 | 15 | All of the Rust-Lightning types are mapped into C equivalents which take a few forms, with the C 16 | type getting an `LDK` prefix to their native Rust type names. 17 | 18 | #### Structs 19 | Structs are mapped into a simple wrapper containing a pointer to the native Rust-Lightning object 20 | and a flag to indicate whether the object is owned or only a reference. Such mappings usually 21 | generate a `X_free` function which must be called to release the allocated resources. Note that 22 | calling `X_free` will do nothing if the underlying pointer is NULL or if the `is_owned` flag is not 23 | set. 24 | 25 | You MUST NOT create such wrapper structs manually, relying instead on constructors which have been 26 | mapped from equivalent Rust constructors. 27 | 28 | Note that, thanks to the is-owned flag and the pointer being NULLable, such structs effectively 29 | represent `RustType`, `&RustType`, and `Option`. Check the corresponding Rust 30 | documentation for the function or struct you are using to ensure you use the correct call semantics. 31 | The passed struct must match the call semantics or an assertion failure or NULL pointer dereference 32 | may occur. 33 | 34 | For example, this is the mapping of ChannelManager. 35 | ```c 36 | typedef struct MUST_USE_STRUCT LDKChannelManager { 37 | /** ... */ 38 | LDKnativeChannelManager *inner; 39 | bool is_owned; 40 | } LDKChannelManager; 41 | ``` 42 | 43 | #### Traits 44 | Traits are mapped into a concrete struct containing a void pointer (named `this_arg` and a jump 45 | table listing the functions which the trait must implement. The void pointer may be set to any value 46 | and is never interpreted (or dereferenced) by the bindings logic in any way. It is passed as the 47 | first argument to all function calls in the trait. You may wish to use it as a pointer to your own 48 | internal data structure, though it may also occasionally make sense to e.g. cast a file descriptor 49 | into a void pointer and use it to track a socket. 50 | 51 | This should remind you of a C++ vtable, only written out by hand and with the class only containing 52 | a pointer, instead of the regular class data. 53 | 54 | Each trait additionally contains `free` and `clone` function pointers, which may be NULL. The `free` 55 | function is passed the void pointer when the object is `Drop`ed in Rust. The `clone` function is 56 | passed the void pointer when the object is `Clone`ed in Rust, returning a new void pointer for the 57 | new object. If the `free` pointer is NULL, you will not receive any notification when the trait 58 | object is no longer needed. If the `clone` pointer is NULL, we assume that the trait object may be 59 | `memcpy()`'d to create copies. Note that if you release resources with `free` without implementing 60 | `clone`, you will likely end up with use-after-free bugs (as copies of the original this_arg value 61 | may still exist, unbeknownst to you). 62 | 63 | For example, `LDKSocketDescriptor` is mapped as follows: 64 | ```c 65 | typedef struct LDKSocketDescriptor { 66 | void *this_arg; 67 | /** ... */ 68 | uintptr_t (*send_data)(void *this_arg, LDKu8slice data, bool resume_read); 69 | /** ... */ 70 | void (*disconnect_socket)(void *this_arg); 71 | bool (*eq)(const void *this_arg, const void *other_arg); 72 | uint64_t (*hash)(const void *this_arg); 73 | void *(*clone)(const void *this_arg); 74 | void (*free)(void *this_arg); 75 | } LDKSocketDescriptor; 76 | ``` 77 | 78 | ##### Rust Trait Implementations 79 | Rust structs that implement a trait result in the generation of an `X_as_Y` function, which takes a 80 | C struct wrapping the Rust native object and returns a generated trait object. Such generated 81 | objects are only valid as long as the original Rust native object has not been `free`'d or moved as 82 | a part of a Rust function call (ie continues to be owned by the C struct). For example, to use an 83 | `LDKInMemoryChannelKeys` as a `ChannelKeys`, `InMemoryChannelKeys_as_ChannelKeys` is exposed: 84 | 85 | ```c 86 | LDKChannelKeys InMemoryChannelKeys_as_ChannelKeys(const LDKInMemoryChannelKeys *this_arg); 87 | ``` 88 | 89 | #### Enums 90 | Rust "unitary" enums are mapped simply as an equivalent C enum; however, some Rust enums have 91 | variants which contain payloads. Such enums are mapped automatically by cbindgen as a tag which 92 | indicates the type and a union which holds the relevant fields for a given tag. An `X_free` function 93 | is provided for the enum as a whole which automatically frees the correct fields for a give tag, and 94 | a `Sentinel` tag is provided which causes the free function to do nothing (but which must never 95 | appear in an enum when accessed by Rust code). The `Sentinel` tag is used by the C++ wrapper classes 96 | to allow moving the ownership of an enum while invalidating the old copy. 97 | 98 | For example, the unitary enum `LDKChannelMonitorUpdateErr` is mapped as follows: 99 | ```c 100 | typedef enum LDKChannelMonitorUpdateErr { 101 | /** .. */ 102 | LDKChannelMonitorUpdateErr_TemporaryFailure, 103 | /** .. */ 104 | LDKChannelMonitorUpdateErr_PermanentFailure, 105 | /** .. */ 106 | LDKChannelMonitorUpdateErr_Sentinel, 107 | } LDKChannelMonitorUpdateErr; 108 | ``` 109 | 110 | and the non-unitary enum LDKErrorAction is mapped as follows: 111 | ```c 112 | typedef enum LDKErrorAction_Tag { 113 | /** .. */ 114 | LDKErrorAction_DisconnectPeer, 115 | /** .. */ 116 | LDKErrorAction_IgnoreError, 117 | /** .. */ 118 | LDKErrorAction_SendErrorMessage, 119 | /** .. */ 120 | LDKErrorAction_Sentinel, 121 | } LDKErrorAction_Tag; 122 | 123 | typedef struct LDKErrorAction_LDKDisconnectPeer_Body { 124 | LDKErrorMessage msg; 125 | } LDKErrorAction_LDKDisconnectPeer_Body; 126 | 127 | typedef struct LDKErrorAction_LDKSendErrorMessage_Body { 128 | LDKErrorMessage msg; 129 | } LDKErrorAction_LDKSendErrorMessage_Body; 130 | 131 | typedef struct LDKErrorAction { 132 | LDKErrorAction_Tag tag; 133 | union { 134 | LDKErrorAction_LDKDisconnectPeer_Body disconnect_peer; 135 | LDKErrorAction_LDKSendErrorMessage_Body send_error_message; 136 | }; 137 | } LDKErrorAction; 138 | ``` 139 | 140 | #### Functions 141 | Struct member functions are mapped as `Struct_function_name` and take a pointer to the mapped struct 142 | as their first argument. Free-standing functions are mapped simply as `function_name` and take the 143 | relevant mapped type arguments. 144 | 145 | Functions which return `&OpaqueRustType` and which return `OpaqueRustType` are both mapped to a 146 | function returning an owned wrapper struct. The `is_owned` flag (see above) will be set to indicate 147 | that the pointed-to Rust object is owned or only a reference. Thus, when implementing a function 148 | which Rust will call or calling a Rust function, you should check the Rust documentation for the 149 | function to determine whether an owned or referenced object is expected or returned. 150 | 151 | Similarly, when a function takes an `Option` as a parameter or a return value, the C type 152 | is the same as if it took only `RustType`, with the `inner` field set to NULL to indicate None. For 153 | example, `ChannelManager_create_channel` takes an `Option` not an `LDKUserConfig`, 154 | but its definition is: 155 | ```c 156 | MUST_USE_RES ... ChannelManager_create_channel(const LDKChannelManager *this_arg, ..., LDKUserConfig override_config); 157 | ``` 158 | 159 | #### Containers 160 | Various containers (Tuples, Vecs, Results, etc) are mapped into C structs of the form 161 | `LDKCContainerType_ContainerElementsZ`. Inner fields are often pointers, and in the case of 162 | primitive types, these may be allocated in C using the system allocator. See [the Rust docs on your 163 | platform's default System allocator](https://doc.rust-lang.org/std/alloc/struct.System.html) for 164 | which allocator you must use. Recursive containers are possible, and simply replace the 165 | `ContainerElements` part with `InnerContainerType_InnerContainerElementsZ`, eg 166 | `LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ` represents a 167 | `Result<(Signature, Vec), ()>`. 168 | 169 | #### Notes 170 | As the bindings are auto-generated, the best resource for documentation on them is the native Rust 171 | docs available via `cargo doc` or [docs.rs/lightning](https://docs.rs/lightning). 172 | 173 | The memory model is largely the Rust memory model and not a native C-like memory model. Thus, 174 | function parameters are largely only ever passed by reference or by move, with pass-by-copy 175 | semantics only applying to primitive types. However, because the underlying types are largely 176 | pointers, the same function signature may imply two different memory ownership semantics. Thus, you 177 | MUST read the Rust documentation while using the C bindings. For functions which take arguments 178 | where ownership is moved to the function scope, the corresponding `X_free` function MUST NOT be 179 | called on the object, whereas for all other objects, `X_free` MUST be used to free resources. 180 | 181 | LDK C++ Bindings 182 | ================ 183 | 184 | The C++ bindings available at include/lightningpp.hpp require extern "C" inclusion of lightning.h 185 | and rust_types.h first. They represent thin wrappers around the C types which provide a few 186 | C++-isms to make memory model correctness easier to achieve. They provide: 187 | * automated destructors which call the relevant `X_free` C functions, 188 | * move constructors both from C++ classes and the original C struct, with the original object 189 | cleared to ensure destruction/`X_free` calls do not cause a double-free. 190 | * Move semantics via the () operator, returning the original C struct and clearing the C++ object. 191 | This allows calls such as `C_function(cpp_object)` which work as expected with move semantics. 192 | 193 | In general, you should prefer to use the C++ bindings if possible, as they make memory leaks and 194 | other violations somewhat easier to avoid. Note that, because the C functions are not redefined in 195 | C++, all functions return the C type. Thus, you must bind returned values to the equivalent C++ type 196 | (replacing `LDKX` with `LDK::X`) to ensure the destructor is properly run. A demonstration of such 197 | usage is available at [demo.cpp](demo.cpp). 198 | 199 | Gotchas 200 | ======= 201 | 202 | There are a few gotchas around future changes to Rust-Lightning which the bindings may not support. 203 | These include: 204 | * Any trait method which returns a reference to a struct or inner variable cannot be called in 205 | parallel. This is because such functions always return a local variable stored inside the trait, 206 | with a call through a function pointer to get the local variable set correctly. Automatically 207 | generated setter functions have comments describing the potential race conditions in their 208 | definition. 209 | 210 | For example, the `ChannelKeys::pubkeys() -> &ChannelPublicKeys` function is mapped as this: 211 | 212 | ```c 213 | typedef struct LDKChannelKeys { 214 | ... 215 | LDKChannelPublicKeys pubkeys; 216 | /** ... */ 217 | void (*set_pubkeys)(const LDKChannelKeys*); 218 | ... 219 | } LDKChannelKeys; 220 | ``` 221 | * Private and public keys are asserted valid at the FFI boundary. Thus, before passing any 222 | (untrusted) private or public key material across the boundary, ensure that they represent valid 223 | (ie in-range) keys. 224 | 225 | **It is highly recommended that you test any code which relies on the C (or C++) bindings in 226 | valgrind, AddressSanitizer, MemorySanitizer, or other similar tools to ensure correctness.** 227 | 228 | Process 229 | ======= 230 | 231 | `genbindings.sh` is currently a catch-all script for bindings - it generates the latest Rust/C/C++ 232 | code for bindings from the rust-lightning source code, builds it, and then runs various test apps. 233 | 234 | Note that after running `genbindings.sh`, if possible, the static lib in target/debug (eg 235 | target/debug/liblightning.a) will be linked with address sanitizer. In order to build against it, 236 | you will need to link with `clang` with `-fsanitize=address` with the same version of LLVM as 237 | `rustc`'s LLVM. If `genbindings.sh` failed to find a matching `clang` or you are building on an 238 | unsupported platform, a warning noting that address sanitizer is not available will be printed. 239 | -------------------------------------------------------------------------------- /lightning-c-bindings/src/lightning_background_processor.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history and in the source files from which this was generated. 3 | // 4 | // This file is licensed under the license available in the LICENSE or LICENSE.md 5 | // file in the root of this repository or, if no such file exists, the same 6 | // license as that which applies to the original source files from which this 7 | // source was automatically generated. 8 | 9 | //! Utilities that take care of tasks that (1) need to happen periodically to keep Rust-Lightning 10 | //! running properly, and (2) either can or should be run in the background. 11 | //!See docs for [`BackgroundProcessor`] for more details. 12 | 13 | use alloc::str::FromStr; 14 | use alloc::string::String; 15 | use core::ffi::c_void; 16 | use core::convert::Infallible; 17 | use bitcoin::hashes::Hash; 18 | use crate::c_types::*; 19 | #[cfg(feature="no-std")] 20 | use alloc::{vec::Vec, boxed::Box}; 21 | 22 | 23 | use lightning_background_processor::BackgroundProcessor as nativeBackgroundProcessorImport; 24 | pub(crate) type nativeBackgroundProcessor = nativeBackgroundProcessorImport; 25 | 26 | /// `BackgroundProcessor` takes care of tasks that (1) need to happen periodically to keep 27 | /// Rust-Lightning running properly, and (2) either can or should be run in the background. Its 28 | /// responsibilities are: 29 | /// * Processing [`Event`]s with a user-provided [`EventHandler`]. 30 | /// * Monitoring whether the [`ChannelManager`] needs to be re-persisted to disk, and if so, 31 | /// writing it to disk/backups by invoking the callback given to it at startup. 32 | /// [`ChannelManager`] persistence should be done in the background. 33 | /// * Calling [`ChannelManager::timer_tick_occurred`], [`ChainMonitor::rebroadcast_pending_claims`] 34 | /// and [`PeerManager::timer_tick_occurred`] at the appropriate intervals. 35 | /// * Calling [`NetworkGraph::remove_stale_channels_and_tracking`] (if a [`GossipSync`] with a 36 | /// [`NetworkGraph`] is provided to [`BackgroundProcessor::start`]). 37 | /// 38 | /// It will also call [`PeerManager::process_events`] periodically though this shouldn't be relied 39 | /// upon as doing so may result in high latency. 40 | /// 41 | /// # Note 42 | /// 43 | /// If [`ChannelManager`] persistence fails and the persisted manager becomes out-of-date, then 44 | /// there is a risk of channels force-closing on startup when the manager realizes it's outdated. 45 | /// However, as long as [`ChannelMonitor`] backups are sound, no funds besides those used for 46 | /// unilateral chain closure fees are at risk. 47 | /// 48 | /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager 49 | /// [`ChannelManager::timer_tick_occurred`]: lightning::ln::channelmanager::ChannelManager::timer_tick_occurred 50 | /// [`ChannelMonitor`]: lightning::chain::channelmonitor::ChannelMonitor 51 | /// [`Event`]: lightning::events::Event 52 | /// [`PeerManager::timer_tick_occurred`]: lightning::ln::peer_handler::PeerManager::timer_tick_occurred 53 | /// [`PeerManager::process_events`]: lightning::ln::peer_handler::PeerManager::process_events 54 | ///BackgroundProcessor will immediately stop on drop. It should be stored until shutdown. 55 | #[must_use] 56 | #[repr(C)] 57 | pub struct BackgroundProcessor { 58 | /// A pointer to the opaque Rust object. 59 | 60 | /// Nearly everywhere, inner must be non-null, however in places where 61 | /// the Rust equivalent takes an Option, it may be set to null to indicate None. 62 | pub inner: *mut nativeBackgroundProcessor, 63 | /// Indicates that this is the only struct which contains the same pointer. 64 | 65 | /// Rust functions which take ownership of an object provided via an argument require 66 | /// this to be true and invalidate the object pointed to by inner. 67 | pub is_owned: bool, 68 | } 69 | 70 | impl core::ops::Deref for BackgroundProcessor { 71 | type Target = nativeBackgroundProcessor; 72 | fn deref(&self) -> &Self::Target { unsafe { &*ObjOps::untweak_ptr(self.inner) } } 73 | } 74 | unsafe impl core::marker::Send for BackgroundProcessor { } 75 | unsafe impl core::marker::Sync for BackgroundProcessor { } 76 | impl Drop for BackgroundProcessor { 77 | fn drop(&mut self) { 78 | if self.is_owned && !<*mut nativeBackgroundProcessor>::is_null(self.inner) { 79 | let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; 80 | } 81 | } 82 | } 83 | /// Frees any resources used by the BackgroundProcessor, if is_owned is set and inner is non-NULL. 84 | #[no_mangle] 85 | pub extern "C" fn BackgroundProcessor_free(this_obj: BackgroundProcessor) { } 86 | #[allow(unused)] 87 | /// Used only if an object of this type is returned as a trait impl by a method 88 | pub(crate) extern "C" fn BackgroundProcessor_free_void(this_ptr: *mut c_void) { 89 | let _ = unsafe { Box::from_raw(this_ptr as *mut nativeBackgroundProcessor) }; 90 | } 91 | #[allow(unused)] 92 | impl BackgroundProcessor { 93 | pub(crate) fn get_native_ref(&self) -> &'static nativeBackgroundProcessor { 94 | unsafe { &*ObjOps::untweak_ptr(self.inner) } 95 | } 96 | pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeBackgroundProcessor { 97 | unsafe { &mut *ObjOps::untweak_ptr(self.inner) } 98 | } 99 | /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy 100 | pub(crate) fn take_inner(mut self) -> *mut nativeBackgroundProcessor { 101 | assert!(self.is_owned); 102 | let ret = ObjOps::untweak_ptr(self.inner); 103 | self.inner = core::ptr::null_mut(); 104 | ret 105 | } 106 | pub(crate) fn as_ref_to(&self) -> Self { 107 | Self { inner: self.inner, is_owned: false } 108 | } 109 | } 110 | /// Either [`P2PGossipSync`] or [`RapidGossipSync`]. 111 | #[must_use] 112 | #[repr(C)] 113 | pub enum GossipSync { 114 | /// Gossip sync via the lightning peer-to-peer network as defined by BOLT 7. 115 | P2P( 116 | /// Note that this field is expected to be a reference. 117 | crate::lightning::routing::gossip::P2PGossipSync), 118 | /// Rapid gossip sync from a trusted server. 119 | Rapid( 120 | /// Note that this field is expected to be a reference. 121 | crate::lightning_rapid_gossip_sync::RapidGossipSync), 122 | /// No gossip sync. 123 | None, 124 | } 125 | use lightning_background_processor::GossipSync as GossipSyncImport; 126 | pub(crate) type nativeGossipSync = GossipSyncImport<&'static lightning::routing::gossip::P2PGossipSync<&'static lightning::routing::gossip::NetworkGraph, crate::lightning::routing::utxo::UtxoLookup, crate::lightning::util::logger::Logger>, &'static lightning_rapid_gossip_sync::RapidGossipSync<&'static lightning::routing::gossip::NetworkGraph, crate::lightning::util::logger::Logger>, &'static lightning::routing::gossip::NetworkGraph, crate::lightning::routing::utxo::UtxoLookup, crate::lightning::util::logger::Logger, >; 127 | 128 | impl GossipSync { 129 | #[allow(unused)] 130 | pub(crate) fn into_native(self) -> nativeGossipSync { 131 | match self { 132 | GossipSync::P2P (mut a, ) => { 133 | nativeGossipSync::P2P ( 134 | a.get_native_ref(), 135 | ) 136 | }, 137 | GossipSync::Rapid (mut a, ) => { 138 | nativeGossipSync::Rapid ( 139 | a.get_native_ref(), 140 | ) 141 | }, 142 | GossipSync::None => nativeGossipSync::None, 143 | } 144 | } 145 | #[allow(unused)] 146 | pub(crate) fn native_into(native: nativeGossipSync) -> Self { 147 | match native { 148 | nativeGossipSync::P2P (mut a, ) => { 149 | GossipSync::P2P ( 150 | crate::lightning::routing::gossip::P2PGossipSync { inner: unsafe { ObjOps::nonnull_ptr_to_inner((a as *const lightning::routing::gossip::P2PGossipSync<_, _, _, >) as *mut _) }, is_owned: false }, 151 | ) 152 | }, 153 | nativeGossipSync::Rapid (mut a, ) => { 154 | GossipSync::Rapid ( 155 | crate::lightning_rapid_gossip_sync::RapidGossipSync { inner: unsafe { ObjOps::nonnull_ptr_to_inner((a as *const lightning_rapid_gossip_sync::RapidGossipSync<_, _, >) as *mut _) }, is_owned: false }, 156 | ) 157 | }, 158 | nativeGossipSync::None => GossipSync::None, 159 | } 160 | } 161 | } 162 | /// Frees any resources used by the GossipSync 163 | #[no_mangle] 164 | pub extern "C" fn GossipSync_free(this_ptr: GossipSync) { } 165 | #[allow(unused)] 166 | /// Used only if an object of this type is returned as a trait impl by a method 167 | pub(crate) extern "C" fn GossipSync_free_void(this_ptr: *mut c_void) { 168 | let _ = unsafe { Box::from_raw(this_ptr as *mut GossipSync) }; 169 | } 170 | #[no_mangle] 171 | /// Utility method to constructs a new P2P-variant GossipSync 172 | pub extern "C" fn GossipSync_p2_p(a: &crate::lightning::routing::gossip::P2PGossipSync) -> GossipSync { 173 | GossipSync::P2P(crate::lightning::routing::gossip::P2PGossipSync { inner: a.inner, is_owned: false }, ) 174 | } 175 | #[no_mangle] 176 | /// Utility method to constructs a new Rapid-variant GossipSync 177 | pub extern "C" fn GossipSync_rapid(a: &crate::lightning_rapid_gossip_sync::RapidGossipSync) -> GossipSync { 178 | GossipSync::Rapid(crate::lightning_rapid_gossip_sync::RapidGossipSync { inner: a.inner, is_owned: false }, ) 179 | } 180 | #[no_mangle] 181 | /// Utility method to constructs a new None-variant GossipSync 182 | pub extern "C" fn GossipSync_none() -> GossipSync { 183 | GossipSync::None} 184 | /// Start a background thread that takes care of responsibilities enumerated in the [top-level 185 | /// documentation]. 186 | /// 187 | /// The thread runs indefinitely unless the object is dropped, [`stop`] is called, or 188 | /// [`Persister::persist_manager`] returns an error. In case of an error, the error is retrieved by calling 189 | /// either [`join`] or [`stop`]. 190 | /// 191 | /// # Data Persistence 192 | /// 193 | /// [`Persister::persist_manager`] is responsible for writing out the [`ChannelManager`] to disk, and/or 194 | /// uploading to one or more backup services. See [`ChannelManager::write`] for writing out a 195 | /// [`ChannelManager`]. See the `lightning-persister` crate for LDK's 196 | /// provided implementation. 197 | /// 198 | /// [`Persister::persist_graph`] is responsible for writing out the [`NetworkGraph`] to disk, if 199 | /// [`GossipSync`] is supplied. See [`NetworkGraph::write`] for writing out a [`NetworkGraph`]. 200 | /// See the `lightning-persister` crate for LDK's provided implementation. 201 | /// 202 | /// Typically, users should either implement [`Persister::persist_manager`] to never return an 203 | /// error or call [`join`] and handle any error that may arise. For the latter case, 204 | /// `BackgroundProcessor` must be restarted by calling `start` again after handling the error. 205 | /// 206 | /// # Event Handling 207 | /// 208 | /// `event_handler` is responsible for handling events that users should be notified of (e.g., 209 | /// payment failed). [`BackgroundProcessor`] may decorate the given [`EventHandler`] with common 210 | /// functionality implemented by other handlers. 211 | /// * [`P2PGossipSync`] if given will update the [`NetworkGraph`] based on payment failures. 212 | /// 213 | /// # Rapid Gossip Sync 214 | /// 215 | /// If rapid gossip sync is meant to run at startup, pass [`RapidGossipSync`] via `gossip_sync` 216 | /// to indicate that the [`BackgroundProcessor`] should not prune the [`NetworkGraph`] instance 217 | /// until the [`RapidGossipSync`] instance completes its first sync. 218 | /// 219 | /// [top-level documentation]: BackgroundProcessor 220 | /// [`join`]: Self::join 221 | /// [`stop`]: Self::stop 222 | /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager 223 | /// [`ChannelManager::write`]: lightning::ln::channelmanager::ChannelManager#impl-Writeable 224 | /// [`Persister::persist_manager`]: lightning::util::persist::Persister::persist_manager 225 | /// [`Persister::persist_graph`]: lightning::util::persist::Persister::persist_graph 226 | /// [`NetworkGraph`]: lightning::routing::gossip::NetworkGraph 227 | /// [`NetworkGraph::write`]: lightning::routing::gossip::NetworkGraph#impl-Writeable 228 | #[must_use] 229 | #[no_mangle] 230 | pub extern "C" fn BackgroundProcessor_start(mut persister: crate::lightning::util::persist::Persister, mut event_handler: crate::lightning::events::EventHandler, chain_monitor: &crate::lightning::chain::chainmonitor::ChainMonitor, channel_manager: &crate::lightning::ln::channelmanager::ChannelManager, onion_messenger: &crate::lightning::onion_message::messenger::OnionMessenger, mut gossip_sync: crate::lightning_background_processor::GossipSync, peer_manager: &crate::lightning::ln::peer_handler::PeerManager, mut logger: crate::lightning::util::logger::Logger, mut scorer: crate::c_types::derived::COption_WriteableScoreZ) -> crate::lightning_background_processor::BackgroundProcessor { 231 | let mut local_scorer = { /*scorer*/ let scorer_opt = scorer; if scorer_opt.is_none() { None } else { Some({ { { scorer_opt.take() } }})} }; 232 | let mut ret = lightning_background_processor::BackgroundProcessor::start(persister, event_handler, chain_monitor.get_native_ref(), channel_manager.as_ref_to(), onion_messenger.as_ref_to(), gossip_sync.into_native(), peer_manager.as_ref_to(), logger, local_scorer); 233 | crate::lightning_background_processor::BackgroundProcessor { inner: ObjOps::heap_alloc(ret), is_owned: true } 234 | } 235 | 236 | /// Join `BackgroundProcessor`'s thread, returning any error that occurred while persisting 237 | /// [`ChannelManager`]. 238 | /// 239 | /// # Panics 240 | /// 241 | /// This function panics if the background thread has panicked such as while persisting or 242 | /// handling events. 243 | /// 244 | /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager 245 | #[must_use] 246 | #[no_mangle] 247 | pub extern "C" fn BackgroundProcessor_join(mut this_arg: crate::lightning_background_processor::BackgroundProcessor) -> crate::c_types::derived::CResult_NoneIOErrorZ { 248 | let mut ret = (*unsafe { Box::from_raw(this_arg.take_inner()) }).join(); 249 | 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() }; 250 | local_ret 251 | } 252 | 253 | /// Stop `BackgroundProcessor`'s thread, returning any error that occurred while persisting 254 | /// [`ChannelManager`]. 255 | /// 256 | /// # Panics 257 | /// 258 | /// This function panics if the background thread has panicked such as while persisting or 259 | /// handling events. 260 | /// 261 | /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager 262 | #[must_use] 263 | #[no_mangle] 264 | pub extern "C" fn BackgroundProcessor_stop(mut this_arg: crate::lightning_background_processor::BackgroundProcessor) -> crate::c_types::derived::CResult_NoneIOErrorZ { 265 | let mut ret = (*unsafe { Box::from_raw(this_arg.take_inner()) }).stop(); 266 | 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() }; 267 | local_ret 268 | } 269 | 270 | --------------------------------------------------------------------------------