Merge pull request #646 from naumenkogs/2020-06-router-mpp
authorMatt Corallo <649246+TheBlueMatt@users.noreply.github.com>
Wed, 3 Mar 2021 01:32:45 +0000 (20:32 -0500)
committerMatt Corallo <git@bluematt.me>
Wed, 3 Mar 2021 01:33:08 +0000 (20:33 -0500)
MPP on the router side

88 files changed:
.github/workflows/build.yml
CONTRIBUTING.md
Cargo.toml
GLOSSARY.md [new file with mode: 0644]
README.md
background-processor/Cargo.toml [new file with mode: 0644]
background-processor/src/lib.rs [new file with mode: 0644]
c-bindings-gen/Cargo.toml
c-bindings-gen/README.md [new file with mode: 0644]
c-bindings-gen/src/blocks.rs
c-bindings-gen/src/main.rs
c-bindings-gen/src/types.rs
fuzz/Cargo.toml
fuzz/src/chanmon_consistency.rs
fuzz/src/chanmon_deser.rs
fuzz/src/full_stack.rs
fuzz/src/router.rs
fuzz/src/utils/test_persister.rs
genbindings.sh
lightning-block-sync/Cargo.toml [new file with mode: 0644]
lightning-block-sync/src/convert.rs [new file with mode: 0644]
lightning-block-sync/src/http.rs [new file with mode: 0644]
lightning-block-sync/src/init.rs [new file with mode: 0644]
lightning-block-sync/src/lib.rs [new file with mode: 0644]
lightning-block-sync/src/poll.rs [new file with mode: 0644]
lightning-block-sync/src/rest.rs [new file with mode: 0644]
lightning-block-sync/src/rpc.rs [new file with mode: 0644]
lightning-block-sync/src/test_utils.rs [new file with mode: 0644]
lightning-block-sync/src/utils.rs [new file with mode: 0644]
lightning-c-bindings/Cargo.toml
lightning-c-bindings/cbindgen.toml
lightning-c-bindings/demo.c
lightning-c-bindings/demo.cpp
lightning-c-bindings/include/lightning.h
lightning-c-bindings/include/lightningpp.hpp
lightning-c-bindings/include/rust_types.h
lightning-c-bindings/src/c_types/derived.rs
lightning-c-bindings/src/c_types/mod.rs
lightning-c-bindings/src/chain/chainmonitor.rs
lightning-c-bindings/src/chain/channelmonitor.rs
lightning-c-bindings/src/chain/keysinterface.rs
lightning-c-bindings/src/chain/mod.rs
lightning-c-bindings/src/chain/transaction.rs
lightning-c-bindings/src/ln/chan_utils.rs
lightning-c-bindings/src/ln/channelmanager.rs
lightning-c-bindings/src/ln/features.rs
lightning-c-bindings/src/ln/msgs.rs
lightning-c-bindings/src/ln/peer_handler.rs
lightning-c-bindings/src/routing/network_graph.rs
lightning-c-bindings/src/routing/router.rs
lightning-c-bindings/src/util/config.rs
lightning-c-bindings/src/util/events.rs
lightning-c-bindings/src/util/macro_logger.rs [new file with mode: 0644]
lightning-c-bindings/src/util/mod.rs
lightning-c-bindings/src/util/ser.rs
lightning-net-tokio/Cargo.toml
lightning-net-tokio/src/lib.rs
lightning-persister/Cargo.toml
lightning-persister/src/lib.rs
lightning-persister/src/util.rs [new file with mode: 0644]
lightning/Cargo.toml
lightning/src/chain/chainmonitor.rs
lightning/src/chain/channelmonitor.rs
lightning/src/chain/keysinterface.rs
lightning/src/chain/mod.rs
lightning/src/lib.rs
lightning/src/ln/chan_utils.rs
lightning/src/ln/chanmon_update_fail_tests.rs
lightning/src/ln/channel.rs
lightning/src/ln/channelmanager.rs
lightning/src/ln/features.rs
lightning/src/ln/functional_test_utils.rs
lightning/src/ln/functional_tests.rs
lightning/src/ln/msgs.rs
lightning/src/ln/onchaintx.rs
lightning/src/ln/onion_route_tests.rs
lightning/src/ln/peer_handler.rs
lightning/src/routing/network_graph.rs
lightning/src/routing/router.rs
lightning/src/util/chacha20.rs
lightning/src/util/config.rs
lightning/src/util/enforcing_trait_impls.rs
lightning/src/util/errors.rs
lightning/src/util/macro_logger.rs
lightning/src/util/mod.rs
lightning/src/util/ser.rs
lightning/src/util/test_utils.rs
lightning/src/util/transaction_utils.rs

index bafdd29fffd975a7ae5ab1585e224de279ea2729..628d620a5dc67cf048bd4e641ecb6c8e1dc16986 100644 (file)
@@ -13,8 +13,8 @@ jobs:
                      1.30.0,
                      # 1.34.2 is Debian stable
                      1.34.2,
-                     # 1.39.0 is MSRV for lightning-net-tokio and generates coverage
-                     1.39.0]
+                     # 1.45.2 is MSRV for lightning-net-tokio, lightning-block-sync, and coverage generation
+                     1.45.2]
         include:
           - toolchain: stable
             build-net-tokio: true
@@ -26,7 +26,7 @@ jobs:
             build-net-tokio: true
           - toolchain: beta
             build-net-tokio: true
-          - toolchain: 1.39.0
+          - toolchain: 1.45.2
             build-net-tokio: true
             coverage: true
     runs-on: ${{ matrix.platform }}
@@ -48,6 +48,24 @@ jobs:
       - name: Build on Rust ${{ matrix.toolchain }}
         if: "! matrix.build-net-tokio"
         run: cargo build --verbose  --color always -p lightning
+      - name: Build Block Sync Clients on Rust ${{ matrix.toolchain }} with features
+        if: "matrix.build-net-tokio && !matrix.coverage"
+        run: |
+          cd lightning-block-sync
+          cargo build --verbose --color always --features rest-client
+          cargo build --verbose --color always --features rpc-client
+          cargo build --verbose --color always --features rpc-client,rest-client
+          cargo build --verbose --color always --features rpc-client,rest-client,tokio
+          cd ..
+      - name: Build Block Sync Clients on Rust ${{ matrix.toolchain }} with features and full code-linking for coverage generation
+        if: matrix.coverage
+        run: |
+          cd lightning-block-sync
+          RUSTFLAGS="-C link-dead-code" cargo build --verbose --color always --features rest-client
+          RUSTFLAGS="-C link-dead-code" cargo build --verbose --color always --features rpc-client
+          RUSTFLAGS="-C link-dead-code" cargo build --verbose --color always --features rpc-client,rest-client
+          RUSTFLAGS="-C link-dead-code" cargo build --verbose --color always --features rpc-client,rest-client,tokio
+          cd ..
       - name: Test on Rust ${{ matrix.toolchain }} with net-tokio
         if: "matrix.build-net-tokio && !matrix.coverage"
         run: cargo test --verbose --color always
@@ -57,6 +75,24 @@ jobs:
       - name: Test on Rust ${{ matrix.toolchain }}
         if: "! matrix.build-net-tokio"
         run: cargo test --verbose --color always  -p lightning
+      - name: Test Block Sync Clients on Rust ${{ matrix.toolchain }} with features
+        if: "matrix.build-net-tokio && !matrix.coverage"
+        run: |
+          cd lightning-block-sync
+          cargo test --verbose --color always --features rest-client
+          cargo test --verbose --color always --features rpc-client
+          cargo test --verbose --color always --features rpc-client,rest-client
+          cargo test --verbose --color always --features rpc-client,rest-client,tokio
+          cd ..
+      - name: Test Block Sync Clients on Rust ${{ matrix.toolchain }} with features and full code-linking for coverage generation
+        if: matrix.coverage
+        run: |
+          cd lightning-block-sync
+          RUSTFLAGS="-C link-dead-code" cargo test --verbose --color always --features rest-client
+          RUSTFLAGS="-C link-dead-code" cargo test --verbose --color always --features rpc-client
+          RUSTFLAGS="-C link-dead-code" cargo test --verbose --color always --features rpc-client,rest-client
+          RUSTFLAGS="-C link-dead-code" cargo test --verbose --color always --features rpc-client,rest-client,tokio
+          cd ..
       - name: Install deps for kcov
         if: matrix.coverage
         run: |
@@ -75,7 +111,7 @@ jobs:
       - name: Generate coverage report
         if: matrix.coverage
         run: |
-          for file in target/debug/lightning-*; do
+          for file in target/debug/deps/lightning*; do
             [ -x "${file}" ] || continue;
             mkdir -p "target/cov/$(basename $file)";
             ./kcov-build/usr/local/bin/kcov --exclude-pattern=/.cargo,/usr/lib --verify "target/cov/$(basename $file)" "$file";
@@ -90,6 +126,39 @@ jobs:
           token: f421b687-4dc2-4387-ac3d-dc3b2528af57
           fail_ci_if_error: true
 
+  benchmark:
+    runs-on: ubuntu-latest
+    env:
+      TOOLCHAIN: nightly
+    steps:
+      - name: Checkout source code
+        uses: actions/checkout@v2
+      - name: Install Rust ${{ env.TOOLCHAIN }} toolchain
+        uses: actions-rs/toolchain@v1
+        with:
+          toolchain: ${{ env.TOOLCHAIN }}
+          override: true
+          profile: minimal
+      - name: Cache routing graph snapshot
+        id: cache-graph
+        uses: actions/cache@v2
+        with:
+          path: lightning/net_graph-2021-02-12.bin
+          key: net_graph-2021-02-12
+      - name: Fetch routing graph snapshot
+        if: steps.cache-graph.outputs.cache-hit != 'true'
+        run: |
+          wget -O lightning/net_graph-2021-02-12.bin https://bitcoin.ninja/ldk-net_graph-879e309c128-2020-02-12.bin
+          if [ "$(sha256sum lightning/net_graph-2021-02-12.bin | awk '{ print $1 }')" != "890a1f80dfb6ef674a1e4ff0f23cd73d740731c395f99d85abbede0cfbb701ab" ]; then
+            echo "Bad hash"
+            exit 1
+          fi
+      - name: Run benchmarks on Rust ${{ matrix.toolchain }}
+        run: |
+          cd lightning
+          cargo bench --features unstable
+          cd ..
+
   check_commits:
     runs-on: ubuntu-latest
     env:
@@ -133,7 +202,7 @@ jobs:
           sudo apt-get update
           sudo apt-get -y install build-essential binutils-dev libunwind-dev
       - name: Sanity check fuzz targets on Rust ${{ env.TOOLCHAIN }}
-        run: cd fuzz && cargo test --verbose --color always
+        run: cd fuzz && RUSTFLAGS="--cfg=fuzzing" cargo test --verbose --color always
       - name: Run fuzzers
         run: cd fuzz && ./ci-fuzz.sh
 
@@ -180,7 +249,7 @@ jobs:
   linting:
     runs-on: ubuntu-latest
     env:
-      TOOLCHAIN: 1.39.0
+      TOOLCHAIN: 1.45.2
     steps:
       - name: Checkout source code
         uses: actions/checkout@v2
index e8a57d85f7f7e8a9cebe857f6011e7c84dee6b6d..186ae274fdacfcb165e7c0a9227f2837e12778c8 100644 (file)
@@ -30,9 +30,13 @@ Getting Started
 First and foremost, start small.
 
 This doesn't mean don't be ambitious with the breadth and depth of your contributions but rather
-understand the project context and culture before investing an asymmetric number of hours on
+understand the project culture before investing an asymmetric number of hours on
 development compared to your merged work.
 
+Browsing through the [meeting minutes](https://github.com/rust-bitcoin/rust-lightning/wiki/Meetings)
+is a good first step. You will learn who is working on what, how releases are drafted, what are the
+pending tasks to deliver, where you can contribute review bandwidth, etc.
+
 Even if you have an extensive open source background or sound software engineering skills, consider
 that the reviewers' comprehension of the code is as much important as technical correctness.
 
@@ -43,6 +47,8 @@ a "soft" commitment.
 If you're eager to increase the velocity of the dev process, reviewing other contributors work is
 the best you can do while waiting review on yours.
 
+Also, getting familiar with the [glossary](GLOSSARY.md) will streamline discussions with regular contributors.
+
 Contribution Workflow
 ---------------------
 
index c43e7927581432e9834aed21a16329aba92f80b3..1ffd75a8710494bd0694decc9bcb5e5ae03f6bfa 100644 (file)
@@ -2,8 +2,10 @@
 
 members = [
     "lightning",
+    "lightning-block-sync",
     "lightning-net-tokio",
     "lightning-persister",
+    "background-processor",
 ]
 
 # Our tests do actual crypo and lots of work, the tradeoff for -O1 is well worth it.
diff --git a/GLOSSARY.md b/GLOSSARY.md
new file mode 100644 (file)
index 0000000..506c126
--- /dev/null
@@ -0,0 +1,31 @@
+# Glossary
+
+This document gathers the canonical Lightning nomenclature used by LDK contributors. Note, they may diverge from the BOLT specs or the ones used by the wider Lightning community; the test of time has revealed that it can be hard to agree on terminology. The following terms are employed with a best effort across the codebase aiming to reduce confusion.
+
+### Channel Initiator
+
+The channel initiator is the entity who is taking the decision to open a channel. Finalization relies upon the counterparty's channel acceptance policy. Within current protocol version, the initiator has the burden of paying channel onchain fees.
+
+### Holder/Counterparty
+
+Inspired by financial cryptography, a holder is an owner of a given digital value. In Lightning, the holder is the entity operating the current node, of which the interests are served by the implementation during channel operations. The counterparty is the entity participating in the channel operation as a peer, but of whom the interests are not of concern by the implementation.
+
+Used across the `Channel` data structure, part of the channel-management subsystem.
+
+### Broadcaster/Countersignatory
+
+In Lightning, states are symmetric but punishment is asymmetric, which forces channel parties to hold different commitment transactions. At transaction construction, the broadcaster designates the entity that has the unilateral capability to broadcast the transaction. The countersignatory is the entity providing signatures for the broadcastable transaction and thus verifying it encodes the off-chain states. At any point in time, there should be two "latest" commitment transactions that have been processed by each party's implementation, one where the holder is the broadcaster and the counterparty is countersignatory, and one where the holder is the countersignatory and the counterparty is the broadcaster.
+
+Used across the channel-utils library (`chan_utils.rs`).
+
+### Watchtower
+
+A watchtower is an external untrusted service that can only publish justice transactions. The security property of watchtowers is that if you subscribe to *N* of them, you will be safe if at least 1 does the right thing.
+
+A (future) deployment configuration of the monitoring (`ChainMonitor`) subsystem.
+
+### Monitor Replicas
+
+An instance of a highly available distributed channel-monitor. It must have a correctly working HSM, because they have sensitive keys that can cause loss of all funds in the channel.
+
+A deployment configuration of the monitoring (`ChainMonitor`) subsystem.
index d157b7368f91d1fdd8aa8d2a1ac9a72bdd13d8a6..d73e71da8aaf3a10fa076ca6fc953f6949094c78 100644 (file)
--- a/README.md
+++ b/README.md
@@ -8,47 +8,108 @@ Rust-Lightning
 Rust-Lightning is a Bitcoin Lightning library written in Rust. The main crate,
 `lightning`, does not handle networking, persistence, or any other I/O. Thus,
 it is runtime-agnostic, but users must implement basic networking logic, chain
-interactions, and disk storage.
+interactions, and disk storage. More information is available in the `About`
+section.
 
 The `lightning-net-tokio` crate implements Lightning networking using the
 [Tokio](https://github.com/tokio-rs/tokio) async runtime.
 
+The `lightning-persister` crate implements persistence for channel data that
+is crucial to avoiding loss of channel funds. Sample modules for persistence of
+other Rust-Lightning data is coming soon.
+
 Status
 ------
 
-The project implements all of the BOLT specifications in the 1.0 spec except
-for [channel queries](https://github.com/lightningnetwork/lightning-rfc/blob/master/07-routing-gossip.md#query-messages). The
+The project implements all of the BOLT specifications in the 1.0 spec. The
 implementation has pretty good test coverage that is expected to continue to
-improve. There are a number of internal refactorings being done now that will
-make the code base more welcoming to new contributors. It is also anticipated
-that as developers begin using the API, the lessons from that will result in
-changes to the API, so any developer using this API at this stage should be prepared
-to embrace that. The current state is sufficient for a developer or project to
-experiment with it. Recent increased contribution rate to the project is expected
-to lead to a high quality, stable, production-worthy implementation in 2020.
+improve. It is also anticipated that as developers begin using the API, the
+lessons from that will result in changes to the API, so any developer using this
+API at this stage should be prepared to embrace that. The current state is
+sufficient for a developer or project to experiment with it. Recent increased
+contribution rate to the project is expected to lead to a high quality, stable,
+production-worthy implementation in 2021.
 
 Communications for Rust-Lightning and Lightning Development Kit happens through
 [LDK slack](http://lightningdevkit.org/).
 
+About
+-----------
+LDK/Rust-Lightning is a generic library which allows you to build a lightning
+node without needing to worry about getting all of the lightning state machine,
+routing, and on-chain punishment code (and other chain interactions) exactly
+correct. Note that Rust-Lightning isn't, in itself, a node. There are various
+working/in progress demos which could be used as a node today, but if you "just"
+want a generic lightning node, you're almost certainly better off with
+`c-lightning`/`lnd` - if, on the other hand, you want to integrate lightning
+with custom features such as your own chain sync, your own key management, your
+own data storage/backup logic, etc., LDK is likely your only option. Some
+Rust-Lightning utilities such as those in `chan_utils` are also suitable for use
+in non-LN Bitcoin applications such as DLCs and bulletin boards.
+
+We are currently working on a demo node which fetches blockchain data and
+on-chain funds via Bitcoin Core RPC/REST. The individual pieces of that demo
+are/will be composable, so you can pick the off-the-shelf parts you want and
+replace the rest.
+
+In general, Rust-Lightning does not provide (but LDK has implementations of):
+* on-disk storage - you can store the channel state any way you want - whether
+  Google Drive/iCloud, a local disk, any key-value store/database/a remote
+  server, or any combination of them - we provide a clean API that provides
+  objects which can be serialized into simple binary blobs, and stored in any
+  way you wish.
+* blockchain data - we provide a simple `block_connected`/`block_disconnected`
+  API which you provide block headers and transaction information to. We also
+  provide an API for getting information about transactions we wish to be
+  informed of, which is compatible with Electrum server requests/neutrino
+  filtering/etc.
+* UTXO management - RL/LDK owns on-chain funds as long as they are claimable as
+  a part of a lightning output which can be contested - once a channel is closed
+  and all on-chain outputs are spendable only by the user, we provide users
+  notifications that a UTXO is "theirs" again and it is up to them to spend it
+  as they wish. Additionally, channel funding is accomplished with a generic API
+  which notifies users of the output which needs to appear on-chain, which they
+  can then create a transaction for. Once a transaction is created, we handle
+  the rest. This is a large part of our API's goals - making it easier to
+  integrate lightning into existing on-chain wallets which have their own
+  on-chain logic - without needing to move funds in and out of a separate
+  lightning wallet with on-chain transactions and a separate private key system.
+* networking - to enable a user to run a full lightning node on an embedded
+  machine, we don't specify exactly how to connect to another node at all! We
+  provide a default implementation which uses TCP sockets, but, e.g., if you
+  wanted to run your full lightning node on a hardware wallet, you could, by
+  piping the lightning network messages over USB/serial and then sending them in
+  a TCP socket from another machine.
+* private keys - again we have "default implementations", but users can chose to
+  provide private keys to RL/LDK in any way they wish following a simple API. We
+  even support a generic API for signing transactions, allowing users to run
+  RL/LDK without any private keys in memory/putting private keys only on
+  hardware wallets.
+
+LDK's customizability was presented about at Advancing Bitcoin in February 2020:
+https://vimeo.com/showcase/7131712/video/418412286
+
 Design Goal
 -----------
 
 The goal is to provide a full-featured but also incredibly flexible lightning
 implementation, allowing the user to decide how they wish to use it. With that
-in mind, everything should be exposed via simple, composable APIs. The user
-should be able to decide whether they wish to use their own threading/execution
-models, allowing usage inside of existing library architectures, or allow us to
-handle that for them. Same goes with network connections - if the user wishes
-to use their own networking stack, they should be able to do so! This all means
-that we should provide simple external interfaces which allow the user to drive
-all execution, while implementing sample execution drivers that create a
-full-featured lightning daemon by default.
+in mind, everything should be exposed via simple, composable APIs. More
+information about Rust-Lightning's flexibility is provided in the `About`
+section above.
 
 For security reasons, do not add new dependencies. Really do not add new
 non-optional/non-test/non-library dependencies. Really really do not add
 dependencies with dependencies. Do convince Andrew to cut down dependency usage
 in rust-bitcoin.
 
+Rust-Lightning vs. LDK (Lightning Development Kit)
+-------------
+Rust-Lightning refers to the core `lightning` crate within this repo, whereas
+LDK encompasses Rust-Lightning and all of its sample modules and crates (e.g.
+the `lightning-persister` crate), language bindings, sample node
+implementation(s), and other tools built around using Rust-Lightning for
+lightning integration or building a lightning node.
 
 Tagline
 -------
diff --git a/background-processor/Cargo.toml b/background-processor/Cargo.toml
new file mode 100644 (file)
index 0000000..1a4dc48
--- /dev/null
@@ -0,0 +1,15 @@
+[package]
+name = "background-processor"
+version = "0.1.0"
+authors = ["Valentine Wallace <vwallace@protonmail.com>"]
+edition = "2018"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
+bitcoin = "0.26"
+lightning = { version = "0.0.12", path = "../lightning", features = ["allow_wallclock_use"] }
+lightning-persister = { version = "0.0.1", path = "../lightning-persister" }
+
+[dev-dependencies]
+lightning = { version = "0.0.12", path = "../lightning", features = ["_test_utils"] }
diff --git a/background-processor/src/lib.rs b/background-processor/src/lib.rs
new file mode 100644 (file)
index 0000000..0c7191f
--- /dev/null
@@ -0,0 +1,293 @@
+#[macro_use] extern crate lightning;
+
+use lightning::chain;
+use lightning::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
+use lightning::chain::keysinterface::{Sign, KeysInterface};
+use lightning::ln::channelmanager::ChannelManager;
+use lightning::util::logger::Logger;
+use std::sync::Arc;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::thread;
+use std::thread::JoinHandle;
+use std::time::{Duration, Instant};
+
+/// BackgroundProcessor takes care of tasks that (1) need to happen periodically to keep
+/// Rust-Lightning running properly, and (2) either can or should be run in the background. Its
+/// responsibilities are:
+/// * Monitoring whether the ChannelManager needs to be re-persisted to disk, and if so,
+///   writing it to disk/backups by invoking the callback given to it at startup.
+///   ChannelManager persistence should be done in the background.
+/// * Calling `ChannelManager::timer_chan_freshness_every_min()` every minute (can be done in the
+///   background).
+///
+/// Note that if ChannelManager persistence fails and the persisted manager becomes out-of-date,
+/// then there is a risk of channels force-closing on startup when the manager realizes it's
+/// outdated. However, as long as `ChannelMonitor` backups are sound, no funds besides those used
+/// for unilateral chain closure fees are at risk.
+pub struct BackgroundProcessor {
+       stop_thread: Arc<AtomicBool>,
+       /// May be used to retrieve and handle the error if `BackgroundProcessor`'s thread
+       /// exits due to an error while persisting.
+       pub thread_handle: JoinHandle<Result<(), std::io::Error>>,
+}
+
+#[cfg(not(test))]
+const CHAN_FRESHNESS_TIMER: u64 = 60;
+#[cfg(test)]
+const CHAN_FRESHNESS_TIMER: u64 = 1;
+
+impl BackgroundProcessor {
+       /// Start a background thread that takes care of responsibilities enumerated in the top-level
+       /// documentation.
+       ///
+       /// If `persist_manager` returns an error, then this thread will return said error (and `start()`
+       /// will need to be called again to restart the `BackgroundProcessor`). Users should wait on
+       /// [`thread_handle`]'s `join()` method to be able to tell if and when an error is returned, or
+       /// implement `persist_manager` such that an error is never returned to the `BackgroundProcessor`
+       ///
+       /// `persist_manager` is responsible for writing out the `ChannelManager` to disk, and/or uploading
+       /// to one or more backup services. See [`ChannelManager::write`] for writing out a `ChannelManager`.
+       /// See [`FilesystemPersister::persist_manager`] for Rust-Lightning's provided implementation.
+       ///
+       /// [`thread_handle`]: struct.BackgroundProcessor.html#structfield.thread_handle
+       /// [`ChannelManager::write`]: ../lightning/ln/channelmanager/struct.ChannelManager.html#method.write
+       /// [`FilesystemPersister::persist_manager`]: ../lightning_persister/struct.FilesystemPersister.html#impl
+       pub fn start<PM, Signer, M, T, K, F, L>(persist_manager: PM, manager: Arc<ChannelManager<Signer, Arc<M>, Arc<T>, Arc<K>, Arc<F>, Arc<L>>>, logger: Arc<L>) -> Self
+       where Signer: 'static + Sign,
+             M: 'static + chain::Watch<Signer>,
+             T: 'static + BroadcasterInterface,
+             K: 'static + KeysInterface<Signer=Signer>,
+             F: 'static + FeeEstimator,
+             L: 'static + Logger,
+             PM: 'static + Send + Fn(&ChannelManager<Signer, Arc<M>, Arc<T>, Arc<K>, Arc<F>, Arc<L>>) -> Result<(), std::io::Error>,
+       {
+               let stop_thread = Arc::new(AtomicBool::new(false));
+               let stop_thread_clone = stop_thread.clone();
+               let handle = thread::spawn(move || -> Result<(), std::io::Error> {
+                       let mut current_time = Instant::now();
+                       loop {
+                               let updates_available = manager.wait_timeout(Duration::from_millis(100));
+                               if updates_available {
+                                       persist_manager(&*manager)?;
+                               }
+                               // Exit the loop if the background processor was requested to stop.
+                               if stop_thread.load(Ordering::Acquire) == true {
+                                       log_trace!(logger, "Terminating background processor.");
+                                       return Ok(())
+                               }
+                               if current_time.elapsed().as_secs() > CHAN_FRESHNESS_TIMER {
+                                       log_trace!(logger, "Calling manager's timer_chan_freshness_every_min");
+                                       manager.timer_chan_freshness_every_min();
+                                       current_time = Instant::now();
+                               }
+                       }
+               });
+               Self {
+                       stop_thread: stop_thread_clone,
+                       thread_handle: handle,
+               }
+       }
+
+       /// Stop `BackgroundProcessor`'s thread.
+       pub fn stop(self) -> Result<(), std::io::Error> {
+               self.stop_thread.store(true, Ordering::Release);
+               self.thread_handle.join().unwrap()
+       }
+}
+
+#[cfg(test)]
+mod tests {
+       use bitcoin::blockdata::constants::genesis_block;
+       use bitcoin::blockdata::transaction::{Transaction, TxOut};
+       use bitcoin::network::constants::Network;
+       use lightning::chain;
+       use lightning::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
+       use lightning::chain::chainmonitor;
+       use lightning::chain::keysinterface::{Sign, InMemorySigner, KeysInterface, KeysManager};
+       use lightning::chain::transaction::OutPoint;
+       use lightning::get_event_msg;
+       use lightning::ln::channelmanager::{ChannelManager, SimpleArcChannelManager};
+       use lightning::ln::features::InitFeatures;
+       use lightning::ln::msgs::ChannelMessageHandler;
+       use lightning::util::config::UserConfig;
+       use lightning::util::events::{Event, EventsProvider, MessageSendEventsProvider, MessageSendEvent};
+       use lightning::util::logger::Logger;
+       use lightning::util::ser::Writeable;
+       use lightning::util::test_utils;
+       use lightning_persister::FilesystemPersister;
+       use std::fs;
+       use std::path::PathBuf;
+       use std::sync::{Arc, Mutex};
+       use std::time::Duration;
+       use super::BackgroundProcessor;
+
+       type ChainMonitor = chainmonitor::ChainMonitor<InMemorySigner, Arc<test_utils::TestChainSource>, Arc<test_utils::TestBroadcaster>, Arc<test_utils::TestFeeEstimator>, Arc<test_utils::TestLogger>, Arc<FilesystemPersister>>;
+
+       struct Node {
+               node: Arc<SimpleArcChannelManager<ChainMonitor, test_utils::TestBroadcaster, test_utils::TestFeeEstimator, test_utils::TestLogger>>,
+               persister: Arc<FilesystemPersister>,
+               logger: Arc<test_utils::TestLogger>,
+       }
+
+       impl Drop for Node {
+               fn drop(&mut self) {
+                       let data_dir = self.persister.get_data_dir();
+                       match fs::remove_dir_all(data_dir.clone()) {
+                               Err(e) => println!("Failed to remove test persister directory {}: {}", data_dir, e),
+                               _ => {}
+                       }
+               }
+       }
+
+       fn get_full_filepath(filepath: String, filename: String) -> String {
+               let mut path = PathBuf::from(filepath);
+               path.push(filename);
+               path.to_str().unwrap().to_string()
+       }
+
+       fn create_nodes(num_nodes: usize, persist_dir: String) -> Vec<Node> {
+               let mut nodes = Vec::new();
+               for i in 0..num_nodes {
+                       let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
+                       let fee_estimator = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
+                       let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
+                       let logger = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
+                       let persister = Arc::new(FilesystemPersister::new(format!("{}_persister_{}", persist_dir, i)));
+                       let seed = [i as u8; 32];
+                       let network = Network::Testnet;
+                       let now = Duration::from_secs(genesis_block(network).header.time as u64);
+                       let keys_manager = Arc::new(KeysManager::new(&seed, now.as_secs(), now.subsec_nanos()));
+                       let chain_monitor = Arc::new(chainmonitor::ChainMonitor::new(Some(chain_source.clone()), tx_broadcaster.clone(), logger.clone(), fee_estimator.clone(), persister.clone()));
+                       let manager = Arc::new(ChannelManager::new(Network::Testnet, fee_estimator.clone(), chain_monitor.clone(), tx_broadcaster, logger.clone(), keys_manager.clone(), UserConfig::default(), i));
+                       let node = Node { node: manager, persister, logger };
+                       nodes.push(node);
+               }
+               nodes
+       }
+
+       macro_rules! open_channel {
+               ($node_a: expr, $node_b: expr, $channel_value: expr) => {{
+                       $node_a.node.create_channel($node_b.node.get_our_node_id(), $channel_value, 100, 42, None).unwrap();
+                       $node_b.node.handle_open_channel(&$node_a.node.get_our_node_id(), InitFeatures::known(), &get_event_msg!($node_a, MessageSendEvent::SendOpenChannel, $node_b.node.get_our_node_id()));
+                       $node_a.node.handle_accept_channel(&$node_b.node.get_our_node_id(), InitFeatures::known(), &get_event_msg!($node_b, MessageSendEvent::SendAcceptChannel, $node_a.node.get_our_node_id()));
+                       let events = $node_a.node.get_and_clear_pending_events();
+                       assert_eq!(events.len(), 1);
+                       let (temporary_channel_id, tx, funding_output) = match events[0] {
+                               Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
+                                       assert_eq!(*channel_value_satoshis, $channel_value);
+                                       assert_eq!(user_channel_id, 42);
+
+                                       let tx = Transaction { version: 1 as i32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
+                                               value: *channel_value_satoshis, script_pubkey: output_script.clone(),
+                                       }]};
+                                       let funding_outpoint = OutPoint { txid: tx.txid(), index: 0 };
+                                       (*temporary_channel_id, tx, funding_outpoint)
+                               },
+                               _ => panic!("Unexpected event"),
+                       };
+
+                       $node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
+                       $node_b.node.handle_funding_created(&$node_a.node.get_our_node_id(), &get_event_msg!($node_a, MessageSendEvent::SendFundingCreated, $node_b.node.get_our_node_id()));
+                       $node_a.node.handle_funding_signed(&$node_b.node.get_our_node_id(), &get_event_msg!($node_b, MessageSendEvent::SendFundingSigned, $node_a.node.get_our_node_id()));
+                       tx
+               }}
+       }
+
+       #[test]
+       fn test_background_processor() {
+               // Test that when a new channel is created, the ChannelManager needs to be re-persisted with
+               // updates. Also test that when new updates are available, the manager signals that it needs
+               // re-persistence and is successfully re-persisted.
+               let nodes = create_nodes(2, "test_background_processor".to_string());
+
+               // Initiate the background processors to watch each node.
+               let data_dir = nodes[0].persister.get_data_dir();
+               let callback = move |node: &ChannelManager<InMemorySigner, Arc<ChainMonitor>, Arc<test_utils::TestBroadcaster>, Arc<KeysManager>, Arc<test_utils::TestFeeEstimator>, Arc<test_utils::TestLogger>>| FilesystemPersister::persist_manager(data_dir.clone(), node);
+               let bg_processor = BackgroundProcessor::start(callback, nodes[0].node.clone(), nodes[0].logger.clone());
+
+               // Go through the channel creation process until each node should have something persisted.
+               let tx = open_channel!(nodes[0], nodes[1], 100000);
+
+               macro_rules! check_persisted_data {
+                       ($node: expr, $filepath: expr, $expected_bytes: expr) => {
+                               match $node.write(&mut $expected_bytes) {
+                                       Ok(()) => {
+                                               loop {
+                                                       match std::fs::read($filepath) {
+                                                               Ok(bytes) => {
+                                                                       if bytes == $expected_bytes {
+                                                                               break
+                                                                       } else {
+                                                                               continue
+                                                                       }
+                                                               },
+                                                               Err(_) => continue
+                                                       }
+                                               }
+                                       },
+                                       Err(e) => panic!("Unexpected error: {}", e)
+                               }
+                       }
+               }
+
+               // Check that the initial channel manager data is persisted as expected.
+               let filepath = get_full_filepath("test_background_processor_persister_0".to_string(), "manager".to_string());
+               let mut expected_bytes = Vec::new();
+               check_persisted_data!(nodes[0].node, filepath.clone(), expected_bytes);
+               loop {
+                       if !nodes[0].node.get_persistence_condvar_value() { break }
+               }
+
+               // Force-close the channel.
+               nodes[0].node.force_close_channel(&OutPoint { txid: tx.txid(), index: 0 }.to_channel_id()).unwrap();
+
+               // Check that the force-close updates are persisted.
+               let mut expected_bytes = Vec::new();
+               check_persisted_data!(nodes[0].node, filepath.clone(), expected_bytes);
+               loop {
+                       if !nodes[0].node.get_persistence_condvar_value() { break }
+               }
+
+               assert!(bg_processor.stop().is_ok());
+       }
+
+       #[test]
+       fn test_chan_freshness_called() {
+               // Test that ChannelManager's `timer_chan_freshness_every_min` is called every
+               // `CHAN_FRESHNESS_TIMER`.
+               let nodes = create_nodes(1, "test_chan_freshness_called".to_string());
+               let data_dir = nodes[0].persister.get_data_dir();
+               let callback = move |node: &ChannelManager<InMemorySigner, Arc<ChainMonitor>, Arc<test_utils::TestBroadcaster>, Arc<KeysManager>, Arc<test_utils::TestFeeEstimator>, Arc<test_utils::TestLogger>>| FilesystemPersister::persist_manager(data_dir.clone(), node);
+               let bg_processor = BackgroundProcessor::start(callback, nodes[0].node.clone(), nodes[0].logger.clone());
+               loop {
+                       let log_entries = nodes[0].logger.lines.lock().unwrap();
+                       let desired_log = "Calling manager's timer_chan_freshness_every_min".to_string();
+                       if log_entries.get(&("background_processor".to_string(), desired_log)).is_some() {
+                               break
+                       }
+               }
+
+               assert!(bg_processor.stop().is_ok());
+       }
+
+       #[test]
+       fn test_persist_error() {
+               // Test that if we encounter an error during manager persistence, the thread panics.
+               fn persist_manager<Signer, M, T, K, F, L>(_data: &ChannelManager<Signer, Arc<M>, Arc<T>, Arc<K>, Arc<F>, Arc<L>>) -> Result<(), std::io::Error>
+               where Signer: 'static + Sign,
+                     M: 'static + chain::Watch<Signer>,
+                     T: 'static + BroadcasterInterface,
+                     K: 'static + KeysInterface<Signer=Signer>,
+                     F: 'static + FeeEstimator,
+                     L: 'static + Logger,
+               {
+                       Err(std::io::Error::new(std::io::ErrorKind::Other, "test"))
+               }
+
+               let nodes = create_nodes(2, "test_persist_error".to_string());
+               let bg_processor = BackgroundProcessor::start(persist_manager, nodes[0].node.clone(), nodes[0].logger.clone());
+               open_channel!(nodes[0], nodes[1], 100000);
+
+               let _ = bg_processor.thread_handle.join().unwrap().expect_err("Errored persisting manager: test");
+       }
+}
index 6f4716e82a3f5e94630a8b3b2aeed36bd50aa255..dedeade8f8e28e3746f5754ba8d25cb9608a40f4 100644 (file)
@@ -8,5 +8,8 @@ edition = "2018"
 syn = { version = "1", features = ["full", "extra-traits"] }
 proc-macro2 = "1"
 
+[profile.release]
+debug = true
+
 # We're not in the workspace as we're just a binary code generator:
 [workspace]
diff --git a/c-bindings-gen/README.md b/c-bindings-gen/README.md
new file mode 100644 (file)
index 0000000..8377adc
--- /dev/null
@@ -0,0 +1,14 @@
+LDK C Bindings Generator
+========================
+
+This program parses a Rust crate's AST from a single lib.rs passed in on stdin and generates a
+second crate which is C-callable (and carries appropriate annotations for cbindgen). It is usually
+invoked via the `genbindings.sh` script in the top-level directory, which converts the lightning
+crate into a single file with a call to
+`RUSTC_BOOTSTRAP=1 cargo rustc --profile=check -- -Zunstable-options --pretty=expanded`.
+
+`genbindings.sh` requires that you have a rustc installed with the `wasm32-wasi` target available
+(eg via the `libstd-rust-dev-wasm32` package on Debian or `rustup target add wasm32-wasi` for those
+using rustup), cbindgen installed via `cargo install cbindgen` and in your `PATH`, and `clang`,
+`clang++`, `gcc`, and `g++` available in your `PATH`. It uses `valgrind` if it is available to test
+the generated bindings thoroughly for memory management issues.
index 076f9373116985d638bcae7411b637b99be11f1c..dd57a82b5f2d557a188c8a15068d112a5f809afa 100644 (file)
@@ -1,7 +1,6 @@
 //! Printing logic for basic blocks of Rust-mapped code - parts of functions and declarations but
 //! not the full mapping logic.
 
-use std::collections::HashMap;
 use std::fs::File;
 use std::io::Write;
 use proc_macro2::{TokenTree, Span};
@@ -17,12 +16,15 @@ pub fn write_cpp_wrapper(cpp_header_file: &mut File, ty: &str, has_destructor: b
        writeln!(cpp_header_file, "\tLDK{} self;", ty).unwrap();
        writeln!(cpp_header_file, "public:").unwrap();
        writeln!(cpp_header_file, "\t{}(const {}&) = delete;", ty, ty).unwrap();
+       writeln!(cpp_header_file, "\t{}({}&& o) : self(o.self) {{ memset(&o, 0, sizeof({})); }}", ty, ty, ty).unwrap();
+       writeln!(cpp_header_file, "\t{}(LDK{}&& m_self) : self(m_self) {{ memset(&m_self, 0, sizeof(LDK{})); }}", ty, ty, ty).unwrap();
+       writeln!(cpp_header_file, "\toperator LDK{}() && {{ LDK{} res = self; memset(&self, 0, sizeof(LDK{})); return res; }}", ty, ty, ty).unwrap();
        if has_destructor {
                writeln!(cpp_header_file, "\t~{}() {{ {}_free(self); }}", ty, ty).unwrap();
+               writeln!(cpp_header_file, "\t{}& operator=({}&& o) {{ {}_free(self); self = o.self; memset(&o, 0, sizeof({})); return *this; }}", ty, ty, ty, ty).unwrap();
+       } else {
+               writeln!(cpp_header_file, "\t{}& operator=({}&& o) {{ self = o.self; memset(&o, 0, sizeof({})); return *this; }}", ty, ty, ty).unwrap();
        }
-       writeln!(cpp_header_file, "\t{}({}&& o) : self(o.self) {{ memset(&o, 0, sizeof({})); }}", ty, ty, ty).unwrap();
-       writeln!(cpp_header_file, "\t{}(LDK{}&& m_self) : self(m_self) {{ memset(&m_self, 0, sizeof(LDK{})); }}", ty, ty, ty).unwrap();
-       writeln!(cpp_header_file, "\toperator LDK{}() {{ LDK{} res = self; memset(&self, 0, sizeof(LDK{})); return res; }}", ty, ty, ty).unwrap();
        writeln!(cpp_header_file, "\tLDK{}* operator &() {{ return &self; }}", ty).unwrap();
        writeln!(cpp_header_file, "\tLDK{}* operator ->() {{ return &self; }}", ty).unwrap();
        writeln!(cpp_header_file, "\tconst LDK{}* operator &() const {{ return &self; }}", ty).unwrap();
@@ -30,6 +32,261 @@ pub fn write_cpp_wrapper(cpp_header_file: &mut File, ty: &str, has_destructor: b
        writeln!(cpp_header_file, "}};").unwrap();
 }
 
+/// Writes out a C-callable concrete Result<A, B> struct and utility methods
+pub fn write_result_block<W: std::io::Write>(w: &mut W, mangled_container: &str, ok_type: &str, err_type: &str, clonable: bool) {
+       writeln!(w, "#[repr(C)]").unwrap();
+       writeln!(w, "pub union {}Ptr {{", mangled_container).unwrap();
+       if ok_type != "()" {
+               writeln!(w, "\tpub result: *mut {},", ok_type).unwrap();
+       } else {
+               writeln!(w, "\t/// Note that this value is always NULL, as there are no contents in the OK variant").unwrap();
+               writeln!(w, "\tpub result: *mut std::ffi::c_void,").unwrap();
+       }
+       if err_type != "()" {
+               writeln!(w, "\tpub err: *mut {},", err_type).unwrap();
+       } else {
+               writeln!(w, "\t/// Note that this value is always NULL, as there are no contents in the Err variant").unwrap();
+               writeln!(w, "\tpub err: *mut std::ffi::c_void,").unwrap();
+       }
+       writeln!(w, "}}").unwrap();
+       writeln!(w, "#[repr(C)]").unwrap();
+       writeln!(w, "pub struct {} {{", mangled_container).unwrap();
+       writeln!(w, "\tpub contents: {}Ptr,", mangled_container).unwrap();
+       writeln!(w, "\tpub result_ok: bool,").unwrap();
+       writeln!(w, "}}").unwrap();
+
+       writeln!(w, "#[no_mangle]").unwrap();
+       if ok_type != "()" {
+               writeln!(w, "pub extern \"C\" fn {}_ok(o: {}) -> {} {{", mangled_container, ok_type, mangled_container).unwrap();
+       } else {
+               writeln!(w, "pub extern \"C\" fn {}_ok() -> {} {{", mangled_container, mangled_container).unwrap();
+       }
+       writeln!(w, "\t{} {{", mangled_container).unwrap();
+       writeln!(w, "\t\tcontents: {}Ptr {{", mangled_container).unwrap();
+       if ok_type != "()" {
+               writeln!(w, "\t\t\tresult: Box::into_raw(Box::new(o)),").unwrap();
+       } else {
+               writeln!(w, "\t\t\tresult: std::ptr::null_mut(),").unwrap();
+       }
+       writeln!(w, "\t\t}},").unwrap();
+       writeln!(w, "\t\tresult_ok: true,").unwrap();
+       writeln!(w, "\t}}").unwrap();
+       writeln!(w, "}}").unwrap();
+
+       writeln!(w, "#[no_mangle]").unwrap();
+       if err_type != "()" {
+               writeln!(w, "pub extern \"C\" fn {}_err(e: {}) -> {} {{", mangled_container, err_type, mangled_container).unwrap();
+       } else {
+               writeln!(w, "pub extern \"C\" fn {}_err() -> {} {{", mangled_container, mangled_container).unwrap();
+       }
+       writeln!(w, "\t{} {{", mangled_container).unwrap();
+       writeln!(w, "\t\tcontents: {}Ptr {{", mangled_container).unwrap();
+       if err_type != "()" {
+               writeln!(w, "\t\t\terr: Box::into_raw(Box::new(e)),").unwrap();
+       } else {
+               writeln!(w, "\t\t\terr: std::ptr::null_mut(),").unwrap();
+       }
+       writeln!(w, "\t\t}},").unwrap();
+       writeln!(w, "\t\tresult_ok: false,").unwrap();
+       writeln!(w, "\t}}").unwrap();
+       writeln!(w, "}}").unwrap();
+
+       writeln!(w, "#[no_mangle]").unwrap();
+       writeln!(w, "pub extern \"C\" fn {}_free(_res: {}) {{ }}", mangled_container, mangled_container).unwrap();
+       writeln!(w, "impl Drop for {} {{", mangled_container).unwrap();
+       writeln!(w, "\tfn drop(&mut self) {{").unwrap();
+       writeln!(w, "\t\tif self.result_ok {{").unwrap();
+       if ok_type != "()" {
+               writeln!(w, "\t\t\tif unsafe {{ !(self.contents.result as *mut ()).is_null() }} {{").unwrap();
+               writeln!(w, "\t\t\t\tlet _ = unsafe {{ Box::from_raw(self.contents.result) }};").unwrap();
+               writeln!(w, "\t\t\t}}").unwrap();
+       }
+       writeln!(w, "\t\t}} else {{").unwrap();
+       if err_type != "()" {
+               writeln!(w, "\t\t\tif unsafe {{ !(self.contents.err as *mut ()).is_null() }} {{").unwrap();
+               writeln!(w, "\t\t\t\tlet _ = unsafe {{ Box::from_raw(self.contents.err) }};").unwrap();
+               writeln!(w, "\t\t\t}}").unwrap();
+       }
+       writeln!(w, "\t\t}}").unwrap();
+       writeln!(w, "\t}}").unwrap();
+       writeln!(w, "}}").unwrap();
+
+       // TODO: Templates should use () now that they can, too
+       let templ_ok_type = if ok_type != "()" { ok_type } else { "u8" };
+       let templ_err_type = if err_type != "()" { err_type } else { "u8" };
+
+       writeln!(w, "impl From<crate::c_types::CResultTempl<{}, {}>> for {} {{", templ_ok_type, templ_err_type, mangled_container).unwrap();
+       writeln!(w, "\tfn from(mut o: crate::c_types::CResultTempl<{}, {}>) -> Self {{", templ_ok_type, templ_err_type).unwrap();
+       writeln!(w, "\t\tlet contents = if o.result_ok {{").unwrap();
+       if ok_type != "()" {
+               writeln!(w, "\t\t\tlet result = unsafe {{ o.contents.result }};").unwrap();
+               writeln!(w, "\t\t\tunsafe {{ o.contents.result = std::ptr::null_mut() }};").unwrap();
+               writeln!(w, "\t\t\t{}Ptr {{ result }}", mangled_container).unwrap();
+       } else {
+               writeln!(w, "\t\t\tlet _ = unsafe {{ Box::from_raw(o.contents.result) }};").unwrap();
+               writeln!(w, "\t\t\to.contents.result = std::ptr::null_mut();").unwrap();
+               writeln!(w, "\t\t\t{}Ptr {{ result: std::ptr::null_mut() }}", mangled_container).unwrap();
+       }
+       writeln!(w, "\t\t}} else {{").unwrap();
+       if err_type != "()" {
+               writeln!(w, "\t\t\tlet err = unsafe {{ o.contents.err }};").unwrap();
+               writeln!(w, "\t\t\tunsafe {{ o.contents.err = std::ptr::null_mut(); }}").unwrap();
+               writeln!(w, "\t\t\t{}Ptr {{ err }}", mangled_container).unwrap();
+       } else {
+               writeln!(w, "\t\t\tlet _ = unsafe {{ Box::from_raw(o.contents.err) }};").unwrap();
+               writeln!(w, "\t\t\to.contents.err = std::ptr::null_mut();").unwrap();
+               writeln!(w, "\t\t\t{}Ptr {{ err: std::ptr::null_mut() }}", mangled_container).unwrap();
+       }
+       writeln!(w, "\t\t}};").unwrap();
+       writeln!(w, "\t\tSelf {{").unwrap();
+       writeln!(w, "\t\t\tcontents,").unwrap();
+       writeln!(w, "\t\t\tresult_ok: o.result_ok,").unwrap();
+       writeln!(w, "\t\t}}").unwrap();
+       writeln!(w, "\t}}").unwrap();
+       writeln!(w, "}}").unwrap();
+
+       if clonable {
+               writeln!(w, "impl Clone for {} {{", mangled_container).unwrap();
+               writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
+               writeln!(w, "\t\tif self.result_ok {{").unwrap();
+               writeln!(w, "\t\t\tSelf {{ result_ok: true, contents: {}Ptr {{", mangled_container).unwrap();
+               if ok_type != "()" {
+                       writeln!(w, "\t\t\t\tresult: Box::into_raw(Box::new(<{}>::clone(unsafe {{ &*self.contents.result }})))", ok_type).unwrap();
+               } else {
+                       writeln!(w, "\t\t\t\tresult: std::ptr::null_mut()").unwrap();
+               }
+               writeln!(w, "\t\t\t}} }}").unwrap();
+               writeln!(w, "\t\t}} else {{").unwrap();
+               writeln!(w, "\t\t\tSelf {{ result_ok: false, contents: {}Ptr {{", mangled_container).unwrap();
+               if err_type != "()" {
+                       writeln!(w, "\t\t\t\terr: Box::into_raw(Box::new(<{}>::clone(unsafe {{ &*self.contents.err }})))", err_type).unwrap();
+               } else {
+                       writeln!(w, "\t\t\t\terr: std::ptr::null_mut()").unwrap();
+               }
+               writeln!(w, "\t\t\t}} }}").unwrap();
+               writeln!(w, "\t\t}}").unwrap();
+               writeln!(w, "\t}}").unwrap();
+               writeln!(w, "}}").unwrap();
+               writeln!(w, "#[no_mangle]").unwrap();
+               writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{ orig.clone() }}", mangled_container, mangled_container, mangled_container).unwrap();
+       }
+}
+
+/// Writes out a C-callable concrete Vec<A> struct and utility methods
+pub fn write_vec_block<W: std::io::Write>(w: &mut W, mangled_container: &str, inner_type: &str, clonable: bool) {
+       writeln!(w, "#[repr(C)]").unwrap();
+       writeln!(w, "pub struct {} {{", mangled_container).unwrap();
+       writeln!(w, "\tpub data: *mut {},", inner_type).unwrap();
+       writeln!(w, "\tpub datalen: usize").unwrap();
+       writeln!(w, "}}").unwrap();
+
+       writeln!(w, "impl {} {{", mangled_container).unwrap();
+       writeln!(w, "\t#[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec<{}> {{", inner_type).unwrap();
+       writeln!(w, "\t\tif self.datalen == 0 {{ return Vec::new(); }}").unwrap();
+       writeln!(w, "\t\tlet ret = unsafe {{ Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }}.into();").unwrap();
+       writeln!(w, "\t\tself.data = std::ptr::null_mut();").unwrap();
+       writeln!(w, "\t\tself.datalen = 0;").unwrap();
+       writeln!(w, "\t\tret").unwrap();
+       writeln!(w, "\t}}").unwrap();
+       writeln!(w, "\t#[allow(unused)] pub(crate) fn as_slice(&self) -> &[{}] {{", inner_type).unwrap();
+       writeln!(w, "\t\tunsafe {{ std::slice::from_raw_parts_mut(self.data, self.datalen) }}").unwrap();
+       writeln!(w, "\t}}").unwrap();
+       writeln!(w, "}}").unwrap();
+
+       writeln!(w, "impl From<Vec<{}>> for {} {{", inner_type, mangled_container).unwrap();
+       writeln!(w, "\tfn from(v: Vec<{}>) -> Self {{", inner_type).unwrap();
+       writeln!(w, "\t\tlet datalen = v.len();").unwrap();
+       writeln!(w, "\t\tlet data = Box::into_raw(v.into_boxed_slice());").unwrap();
+       writeln!(w, "\t\tSelf {{ datalen, data: unsafe {{ (*data).as_mut_ptr() }} }}").unwrap();
+       writeln!(w, "\t}}").unwrap();
+       writeln!(w, "}}").unwrap();
+
+       writeln!(w, "#[no_mangle]").unwrap();
+       writeln!(w, "pub extern \"C\" fn {}_free(_res: {}) {{ }}", mangled_container, mangled_container).unwrap();
+       writeln!(w, "impl Drop for {} {{", mangled_container).unwrap();
+       writeln!(w, "\tfn drop(&mut self) {{").unwrap();
+       writeln!(w, "\t\tif self.datalen == 0 {{ return; }}").unwrap();
+       writeln!(w, "\t\tunsafe {{ Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }};").unwrap();
+       writeln!(w, "\t}}").unwrap();
+       writeln!(w, "}}").unwrap();
+       if clonable {
+               writeln!(w, "impl Clone for {} {{", mangled_container).unwrap();
+               writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
+               writeln!(w, "\t\tlet mut res = Vec::new();").unwrap();
+               writeln!(w, "\t\tif self.datalen == 0 {{ return Self::from(res); }}").unwrap();
+               writeln!(w, "\t\tres.extend_from_slice(unsafe {{ std::slice::from_raw_parts_mut(self.data, self.datalen) }});").unwrap();
+               writeln!(w, "\t\tSelf::from(res)").unwrap();
+               writeln!(w, "\t}}").unwrap();
+               writeln!(w, "}}").unwrap();
+       }
+}
+
+/// Writes out a C-callable concrete (A, B, ...) struct and utility methods
+pub fn write_tuple_block<W: std::io::Write>(w: &mut W, mangled_container: &str, types: &[String], clonable: bool) {
+       writeln!(w, "#[repr(C)]").unwrap();
+       writeln!(w, "pub struct {} {{", mangled_container).unwrap();
+       for (idx, ty) in types.iter().enumerate() {
+               writeln!(w, "\tpub {}: {},", ('a' as u8 + idx as u8) as char, ty).unwrap();
+       }
+       writeln!(w, "}}").unwrap();
+
+       let mut tuple_str = "(".to_owned();
+       for (idx, ty) in types.iter().enumerate() {
+               if idx != 0 { tuple_str += ", "; }
+               tuple_str += ty;
+       }
+       tuple_str += ")";
+
+       writeln!(w, "impl From<{}> for {} {{", tuple_str, mangled_container).unwrap();
+       writeln!(w, "\tfn from (tup: {}) -> Self {{", tuple_str).unwrap();
+       writeln!(w, "\t\tSelf {{").unwrap();
+       for idx in 0..types.len() {
+               writeln!(w, "\t\t\t{}: tup.{},", ('a' as u8 + idx as u8) as char, idx).unwrap();
+       }
+       writeln!(w, "\t\t}}").unwrap();
+       writeln!(w, "\t}}").unwrap();
+       writeln!(w, "}}").unwrap();
+       writeln!(w, "impl {} {{", mangled_container).unwrap();
+       writeln!(w, "\t#[allow(unused)] pub(crate) fn to_rust(mut self) -> {} {{", tuple_str).unwrap();
+       write!(w, "\t\t(").unwrap();
+       for idx in 0..types.len() {
+               write!(w, "{}self.{}", if idx != 0 {", "} else {""}, ('a' as u8 + idx as u8) as char).unwrap();
+       }
+       writeln!(w, ")").unwrap();
+       writeln!(w, "\t}}").unwrap();
+       writeln!(w, "}}").unwrap();
+
+       if clonable {
+               writeln!(w, "impl Clone for {} {{", mangled_container).unwrap();
+               writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
+               writeln!(w, "\t\tSelf {{").unwrap();
+               for idx in 0..types.len() {
+                       writeln!(w, "\t\t\t{}: self.{}.clone(),", ('a' as u8 + idx as u8) as char, ('a' as u8 + idx as u8) as char).unwrap();
+               }
+               writeln!(w, "\t\t}}").unwrap();
+               writeln!(w, "\t}}").unwrap();
+               writeln!(w, "}}").unwrap();
+               writeln!(w, "#[no_mangle]").unwrap();
+               writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{ orig.clone() }}", mangled_container, mangled_container, mangled_container).unwrap();
+       }
+
+       write!(w, "#[no_mangle]\npub extern \"C\" fn {}_new(", mangled_container).unwrap();
+       for (idx, gen) in types.iter().enumerate() {
+               write!(w, "{}{}: ", if idx != 0 { ", " } else { "" }, ('a' as u8 + idx as u8) as char).unwrap();
+               //if !self.write_c_type_intern(&mut created_container, gen, generics, false, false, false) { return false; }
+               write!(w, "{}", gen).unwrap();
+       }
+       writeln!(w, ") -> {} {{", mangled_container).unwrap();
+       write!(w, "\t{} {{ ", mangled_container).unwrap();
+       for idx in 0..types.len() {
+               write!(w, "{}, ", ('a' as u8 + idx as u8) as char).unwrap();
+       }
+       writeln!(w, "}}\n}}\n").unwrap();
+
+       writeln!(w, "#[no_mangle]").unwrap();
+       writeln!(w, "pub extern \"C\" fn {}_free(_res: {}) {{ }}", mangled_container, mangled_container).unwrap();
+}
+
 /// Prints the docs from a given attribute list unless its tagged no export
 pub fn writeln_docs<W: std::io::Write>(w: &mut W, attrs: &[syn::Attribute], prefix: &str) {
        for attr in attrs.iter() {
@@ -77,7 +334,7 @@ pub fn writeln_docs<W: std::io::Write>(w: &mut W, attrs: &[syn::Attribute], pref
 ///
 /// this_param is used when returning Self or accepting a self parameter, and should be the
 /// concrete, mapped type.
-pub fn write_method_params<W: std::io::Write>(w: &mut W, sig: &syn::Signature, associated_types: &HashMap<&syn::Ident, &syn::Ident>, this_param: &str, types: &mut TypeResolver, generics: Option<&GenericTypes>, self_ptr: bool, fn_decl: bool) {
+pub fn write_method_params<W: std::io::Write>(w: &mut W, sig: &syn::Signature, this_param: &str, types: &mut TypeResolver, generics: Option<&GenericTypes>, self_ptr: bool, fn_decl: bool) {
        if sig.constness.is_some() || sig.asyncness.is_some() || sig.unsafety.is_some() ||
                        sig.abi.is_some() || sig.variadic.is_some() {
                unimplemented!();
@@ -140,26 +397,16 @@ pub fn write_method_params<W: std::io::Write>(w: &mut W, sig: &syn::Signature, a
                syn::ReturnType::Type(_, rtype) => {
                        write!(w, " -> ").unwrap();
                        if let Some(mut remaining_path) = first_seg_self(&*rtype) {
-                               if let Some(associated_seg) = get_single_remaining_path_seg(&mut remaining_path) {
-                                       // We're returning an associated type in a trait impl. Its probably a safe bet
-                                       // that its also a trait, so just return the trait type.
-                                       let real_type = associated_types.get(associated_seg).unwrap();
-                                       types.write_c_type(w, &syn::Type::Path(syn::TypePath { qself: None,
-                                               path: syn::PathSegment {
-                                                       ident: (*real_type).clone(),
-                                                       arguments: syn::PathArguments::None
-                                               }.into()
-                                       }), generics, true);
-                               } else {
+                               if remaining_path.next().is_none() {
                                        write!(w, "{}", this_param).unwrap();
+                                       return;
                                }
+                       }
+                       if let syn::Type::Reference(r) = &**rtype {
+                               // We can't return a reference, cause we allocate things on the stack.
+                               types.write_c_type(w, &*r.elem, generics, true);
                        } else {
-                               if let syn::Type::Reference(r) = &**rtype {
-                                       // We can't return a reference, cause we allocate things on the stack.
-                                       types.write_c_type(w, &*r.elem, generics, true);
-                               } else {
-                                       types.write_c_type(w, &*rtype, generics, true);
-                               }
+                               types.write_c_type(w, &*rtype, generics, true);
                        }
                },
                _ => {},
@@ -222,7 +469,7 @@ pub fn write_method_var_decl_body<W: std::io::Write>(w: &mut W, sig: &syn::Signa
 ///
 /// The return value is expected to be bound to a variable named `ret` which is available after a
 /// method-call-ending semicolon.
-pub fn write_method_call_params<W: std::io::Write>(w: &mut W, sig: &syn::Signature, associated_types: &HashMap<&syn::Ident, &syn::Ident>, extra_indent: &str, types: &TypeResolver, generics: Option<&GenericTypes>, this_type: &str, to_c: bool) {
+pub fn write_method_call_params<W: std::io::Write>(w: &mut W, sig: &syn::Signature, extra_indent: &str, types: &TypeResolver, generics: Option<&GenericTypes>, this_type: &str, to_c: bool) {
        let mut first_arg = true;
        let mut num_unused = 0;
        for inp in sig.inputs.iter() {
@@ -285,26 +532,12 @@ pub fn write_method_call_params<W: std::io::Write>(w: &mut W, sig: &syn::Signatu
                syn::ReturnType::Type(_, rtype) => {
                        write!(w, ";\n\t{}", extra_indent).unwrap();
 
+                       let self_segs_iter = first_seg_self(&*rtype);
                        if to_c && first_seg_self(&*rtype).is_some() {
                                // Assume rather blindly that we're returning an associated trait from a C fn call to a Rust trait object.
                                write!(w, "ret").unwrap();
-                       } else if !to_c && first_seg_self(&*rtype).is_some() {
-                               if let Some(mut remaining_path) = first_seg_self(&*rtype) {
-                                       if let Some(associated_seg) = get_single_remaining_path_seg(&mut remaining_path) {
-                                               let real_type = associated_types.get(associated_seg).unwrap();
-                                               if let Some(t) = types.crate_types.traits.get(&types.maybe_resolve_ident(&real_type).unwrap()) {
-                                                       // We're returning an associated trait from a Rust fn call to a C trait
-                                                       // object.
-                                                       writeln!(w, "let mut rust_obj = {} {{ inner: Box::into_raw(Box::new(ret)), is_owned: true }};", this_type).unwrap();
-                                                       writeln!(w, "\t{}let mut ret = {}_as_{}(&rust_obj);", extra_indent, this_type, t.ident).unwrap();
-                                                       writeln!(w, "\t{}// We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn", extra_indent).unwrap();
-                                                       writeln!(w, "\t{}rust_obj.inner = std::ptr::null_mut();", extra_indent).unwrap();
-                                                       writeln!(w, "\t{}ret.free = Some({}_free_void);", extra_indent, this_type).unwrap();
-                                                       writeln!(w, "\t{}ret", extra_indent).unwrap();
-                                                       return;
-                                               }
-                                       }
-                               }
+                       } else if !to_c && self_segs_iter.is_some() && self_segs_iter.unwrap().next().is_none() {
+                               // If we're returning "Self" (and not "Self::X"), just do it manually
                                write!(w, "{} {{ inner: Box::into_raw(Box::new(ret)), is_owned: true }}", this_type).unwrap();
                        } else if to_c {
                                let new_var = types.write_from_c_conversion_new_var(w, &syn::Ident::new("ret", Span::call_site()), rtype, generics);
index 4193f6d36206c14bc47c3aa733b23b355f5e529e..5b99cd681819df8ad6643272224cc97d57e8bc17 100644 (file)
 //! It also generates relevant memory-management functions and free-standing functions with
 //! parameters mapped.
 
-use std::collections::HashMap;
+use std::collections::{HashMap, hash_map, HashSet};
 use std::env;
 use std::fs::File;
 use std::io::{Read, Write};
-use std::path::Path;
 use std::process;
 
 use proc_macro2::{TokenTree, TokenStream, Span};
@@ -38,10 +37,14 @@ fn convert_macro<W: std::io::Write>(w: &mut W, macro_path: &syn::Path, stream: &
                        if let Some(s) = types.maybe_resolve_ident(&struct_for) {
                                if !types.crate_types.opaques.get(&s).is_some() { return; }
                                writeln!(w, "#[no_mangle]").unwrap();
-                               writeln!(w, "pub extern \"C\" fn {}_write(obj: *const {}) -> crate::c_types::derived::CVec_u8Z {{", struct_for, struct_for).unwrap();
+                               writeln!(w, "pub extern \"C\" fn {}_write(obj: &{}) -> crate::c_types::derived::CVec_u8Z {{", struct_for, struct_for).unwrap();
                                writeln!(w, "\tcrate::c_types::serialize_obj(unsafe {{ &(*(*obj).inner) }})").unwrap();
                                writeln!(w, "}}").unwrap();
                                writeln!(w, "#[no_mangle]").unwrap();
+                               writeln!(w, "pub(crate) extern \"C\" fn {}_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {{", struct_for).unwrap();
+                               writeln!(w, "\tcrate::c_types::serialize_obj(unsafe {{ &*(obj as *const native{}) }})", struct_for).unwrap();
+                               writeln!(w, "}}").unwrap();
+                               writeln!(w, "#[no_mangle]").unwrap();
                                writeln!(w, "pub extern \"C\" fn {}_read(ser: crate::c_types::u8slice) -> {} {{", struct_for, struct_for).unwrap();
                                writeln!(w, "\tif let Ok(res) = crate::c_types::deserialize_obj(ser) {{").unwrap();
                                writeln!(w, "\t\t{} {{ inner: Box::into_raw(Box::new(res)), is_owned: true }}", struct_for).unwrap();
@@ -54,32 +57,167 @@ fn convert_macro<W: std::io::Write>(w: &mut W, macro_path: &syn::Path, stream: &
        }
 }
 
-/// Convert "impl trait_path for for_obj { .. }" for manually-mapped types (ie (de)serialization)
-fn maybe_convert_trait_impl<W: std::io::Write>(w: &mut W, trait_path: &syn::Path, for_obj: &syn::Ident, types: &TypeResolver) {
-       if let Some(t) = types.maybe_resolve_path(&trait_path, None) {
-               let s = types.maybe_resolve_ident(for_obj).unwrap();
-               if !types.crate_types.opaques.get(&s).is_some() { return; }
+/// Convert "impl trait_path for for_ty { .. }" for manually-mapped types (ie (de)serialization)
+fn maybe_convert_trait_impl<W: std::io::Write>(w: &mut W, trait_path: &syn::Path, for_ty: &syn::Type, types: &mut TypeResolver, generics: &GenericTypes) {
+       if let Some(t) = types.maybe_resolve_path(&trait_path, Some(generics)) {
+               let for_obj;
+               let full_obj_path;
+               let mut has_inner = false;
+               if let syn::Type::Path(ref p) = for_ty {
+                       if let Some(ident) = single_ident_generic_path_to_ident(&p.path) {
+                               for_obj = format!("{}", ident);
+                               full_obj_path = for_obj.clone();
+                               has_inner = types.c_type_has_inner_from_path(&types.resolve_path(&p.path, Some(generics)));
+                       } else { return; }
+               } else {
+                       // We assume that anything that isn't a Path is somehow a generic that ends up in our
+                       // derived-types module.
+                       let mut for_obj_vec = Vec::new();
+                       types.write_c_type(&mut for_obj_vec, for_ty, Some(generics), false);
+                       full_obj_path = String::from_utf8(for_obj_vec).unwrap();
+                       assert!(full_obj_path.starts_with(TypeResolver::generated_container_path()));
+                       for_obj = full_obj_path[TypeResolver::generated_container_path().len() + 2..].into();
+               }
+
                match &t as &str {
                        "util::ser::Writeable" => {
                                writeln!(w, "#[no_mangle]").unwrap();
-                               writeln!(w, "pub extern \"C\" fn {}_write(obj: *const {}) -> crate::c_types::derived::CVec_u8Z {{", for_obj, for_obj).unwrap();
-                               writeln!(w, "\tcrate::c_types::serialize_obj(unsafe {{ &(*(*obj).inner) }})").unwrap();
+                               writeln!(w, "pub extern \"C\" fn {}_write(obj: &{}) -> crate::c_types::derived::CVec_u8Z {{", for_obj, full_obj_path).unwrap();
+
+                               let ref_type = syn::Type::Reference(syn::TypeReference {
+                                       and_token: syn::Token!(&)(Span::call_site()), lifetime: None, mutability: None,
+                                       elem: Box::new(for_ty.clone()) });
+                               assert!(!types.write_from_c_conversion_new_var(w, &syn::Ident::new("obj", Span::call_site()), &ref_type, Some(generics)));
+
+                               write!(w, "\tcrate::c_types::serialize_obj(").unwrap();
+                               types.write_from_c_conversion_prefix(w, &ref_type, Some(generics));
+                               write!(w, "unsafe {{ &*obj }}").unwrap();
+                               types.write_from_c_conversion_suffix(w, &ref_type, Some(generics));
+                               writeln!(w, ")").unwrap();
+
                                writeln!(w, "}}").unwrap();
+                               if has_inner {
+                                       writeln!(w, "#[no_mangle]").unwrap();
+                                       writeln!(w, "pub(crate) extern \"C\" fn {}_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {{", for_obj).unwrap();
+                                       writeln!(w, "\tcrate::c_types::serialize_obj(unsafe {{ &*(obj as *const native{}) }})", for_obj).unwrap();
+                                       writeln!(w, "}}").unwrap();
+                               }
                        },
-                       "util::ser::Readable" => {
+                       "util::ser::Readable"|"util::ser::ReadableArgs" => {
+                               // Create the Result<Object, DecodeError> syn::Type
+                               let mut err_segs = syn::punctuated::Punctuated::new();
+                               err_segs.push(syn::PathSegment { ident: syn::Ident::new("ln", Span::call_site()), arguments: syn::PathArguments::None });
+                               err_segs.push(syn::PathSegment { ident: syn::Ident::new("msgs", Span::call_site()), arguments: syn::PathArguments::None });
+                               err_segs.push(syn::PathSegment { ident: syn::Ident::new("DecodeError", Span::call_site()), arguments: syn::PathArguments::None });
+                               let mut args = syn::punctuated::Punctuated::new();
+                               args.push(syn::GenericArgument::Type(for_ty.clone()));
+                               args.push(syn::GenericArgument::Type(syn::Type::Path(syn::TypePath {
+                                       qself: None, path: syn::Path {
+                                               leading_colon: Some(syn::Token![::](Span::call_site())), segments: err_segs,
+                                       }
+                               })));
+                               let mut res_segs = syn::punctuated::Punctuated::new();
+                               res_segs.push(syn::PathSegment {
+                                       ident: syn::Ident::new("Result", Span::call_site()),
+                                       arguments: syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments {
+                                               colon2_token: None, lt_token: syn::Token![<](Span::call_site()), args, gt_token: syn::Token![>](Span::call_site()),
+                                       })
+                               });
+                               let res_ty = syn::Type::Path(syn::TypePath { qself: None, path: syn::Path {
+                                       leading_colon: None, segments: res_segs } });
+
                                writeln!(w, "#[no_mangle]").unwrap();
-                               writeln!(w, "pub extern \"C\" fn {}_read(ser: crate::c_types::u8slice) -> {} {{", for_obj, for_obj).unwrap();
-                               writeln!(w, "\tif let Ok(res) = crate::c_types::deserialize_obj(ser) {{").unwrap();
-                               writeln!(w, "\t\t{} {{ inner: Box::into_raw(Box::new(res)), is_owned: true }}", for_obj).unwrap();
-                               writeln!(w, "\t}} else {{").unwrap();
-                               writeln!(w, "\t\t{} {{ inner: std::ptr::null_mut(), is_owned: true }}", for_obj).unwrap();
-                               writeln!(w, "\t}}\n}}").unwrap();
+                               write!(w, "pub extern \"C\" fn {}_read(ser: crate::c_types::u8slice", for_obj).unwrap();
+
+                               let mut arg_conv = Vec::new();
+                               if t == "util::ser::ReadableArgs" {
+                                       write!(w, ", arg: ").unwrap();
+                                       assert!(trait_path.leading_colon.is_none());
+                                       let args_seg = trait_path.segments.iter().last().unwrap();
+                                       assert_eq!(format!("{}", args_seg.ident), "ReadableArgs");
+                                       if let syn::PathArguments::AngleBracketed(args) = &args_seg.arguments {
+                                               assert_eq!(args.args.len(), 1);
+                                               if let syn::GenericArgument::Type(args_ty) = args.args.iter().next().unwrap() {
+                                                       types.write_c_type(w, args_ty, Some(generics), false);
+
+                                                       assert!(!types.write_from_c_conversion_new_var(&mut arg_conv, &syn::Ident::new("arg", Span::call_site()), &args_ty, Some(generics)));
+
+                                                       write!(&mut arg_conv, "\tlet arg_conv = ").unwrap();
+                                                       types.write_from_c_conversion_prefix(&mut arg_conv, &args_ty, Some(generics));
+                                                       write!(&mut arg_conv, "arg").unwrap();
+                                                       types.write_from_c_conversion_suffix(&mut arg_conv, &args_ty, Some(generics));
+                                               } else { unreachable!(); }
+                                       } else { unreachable!(); }
+                               }
+                               write!(w, ") -> ").unwrap();
+                               types.write_c_type(w, &res_ty, Some(generics), false);
+                               writeln!(w, " {{").unwrap();
+
+                               if t == "util::ser::ReadableArgs" {
+                                       w.write(&arg_conv).unwrap();
+                                       write!(w, ";\n\tlet res: ").unwrap();
+                                       // At least in one case we need type annotations here, so provide them.
+                                       types.write_rust_type(w, Some(generics), &res_ty);
+                                       writeln!(w, " = crate::c_types::deserialize_obj_arg(ser, arg_conv);").unwrap();
+                               } else {
+                                       writeln!(w, "\tlet res = crate::c_types::deserialize_obj(ser);").unwrap();
+                               }
+                               write!(w, "\t").unwrap();
+                               if types.write_to_c_conversion_new_var(w, &syn::Ident::new("res", Span::call_site()), &res_ty, Some(generics), false) {
+                                       write!(w, "\n\t").unwrap();
+                               }
+                               types.write_to_c_conversion_inline_prefix(w, &res_ty, Some(generics), false);
+                               write!(w, "res").unwrap();
+                               types.write_to_c_conversion_inline_suffix(w, &res_ty, Some(generics), false);
+                               writeln!(w, "\n}}").unwrap();
                        },
                        _ => {},
                }
        }
 }
 
+/// Convert "TraitA : TraitB" to a single function name and return type.
+///
+/// This is (obviously) somewhat over-specialized and only useful for TraitB's that only require a
+/// single function (eg for serialization).
+fn convert_trait_impl_field(trait_path: &str) -> (String, &'static str) {
+       match trait_path {
+               "util::ser::Writeable" => ("write".to_owned(), "crate::c_types::derived::CVec_u8Z"),
+               _ => unimplemented!(),
+       }
+}
+
+/// Companion to convert_trait_impl_field, write an assignment for the function defined by it for
+/// `for_obj` which implements the the trait at `trait_path`.
+fn write_trait_impl_field_assign<W: std::io::Write>(w: &mut W, trait_path: &str, for_obj: &syn::Ident) {
+       match trait_path {
+               "util::ser::Writeable" => {
+                       writeln!(w, "\t\twrite: {}_write_void,", for_obj).unwrap();
+               },
+               _ => unimplemented!(),
+       }
+}
+
+/// Write out the impl block for a defined trait struct which has a supertrait
+fn do_write_impl_trait<W: std::io::Write>(w: &mut W, trait_path: &str, trait_name: &syn::Ident, for_obj: &str) {
+       match trait_path {
+               "util::events::MessageSendEventsProvider" => {
+                       writeln!(w, "impl lightning::{} for {} {{", trait_path, for_obj).unwrap();
+                       writeln!(w, "\tfn get_and_clear_pending_msg_events(&self) -> Vec<lightning::util::events::MessageSendEvent> {{").unwrap();
+                       writeln!(w, "\t\t<crate::{} as lightning::{}>::get_and_clear_pending_msg_events(&self.{})", trait_path, trait_path, trait_name).unwrap();
+                       writeln!(w, "\t}}\n}}").unwrap();
+               },
+               "util::ser::Writeable" => {
+                       writeln!(w, "impl lightning::{} for {} {{", trait_path, for_obj).unwrap();
+                       writeln!(w, "\tfn write<W: lightning::util::ser::Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {{").unwrap();
+                       writeln!(w, "\t\tlet vec = (self.write)(self.this_arg);").unwrap();
+                       writeln!(w, "\t\tw.write_all(vec.as_slice())").unwrap();
+                       writeln!(w, "\t}}\n}}").unwrap();
+               },
+               _ => panic!(),
+       }
+}
+
 // *******************************
 // *** Per-Type Printing Logic ***
 // *******************************
@@ -92,15 +230,23 @@ macro_rules! walk_supertraits { ($t: expr, $types: expr, ($( $pat: pat => $e: ex
                                        if supertrait.paren_token.is_some() || supertrait.lifetimes.is_some() {
                                                unimplemented!();
                                        }
+                                       // First try to resolve path to find in-crate traits, but if that doesn't work
+                                       // assume its a prelude trait (eg Clone, etc) and just use the single ident.
+                                       let types_opt: Option<&TypeResolver> = $types;
+                                       if let Some(types) = types_opt {
+                                               if let Some(path) = types.maybe_resolve_path(&supertrait.path, None) {
+                                                       match (&path as &str, &supertrait.path.segments.iter().last().unwrap().ident) {
+                                                               $( $pat => $e, )*
+                                                       }
+                                                       continue;
+                                               }
+                                       }
                                        if let Some(ident) = supertrait.path.get_ident() {
                                                match (&format!("{}", ident) as &str, &ident) {
                                                        $( $pat => $e, )*
                                                }
-                                       } else {
-                                               let path = $types.resolve_path(&supertrait.path, None);
-                                               match (&path as &str, &supertrait.path.segments.iter().last().unwrap().ident) {
-                                                       $( $pat => $e, )*
-                                               }
+                                       } else if types_opt.is_some() {
+                                               panic!("Supertrait unresolvable and not single-ident");
                                        }
                                },
                                syn::TypeParamBound::Lifetime(_) => unimplemented!(),
@@ -109,31 +255,6 @@ macro_rules! walk_supertraits { ($t: expr, $types: expr, ($( $pat: pat => $e: ex
        }
 } } }
 
-/// Gets a HashMap from name idents to the bounding trait for associated types.
-/// eg if a native trait has a "type T = TraitA", this will return a HashMap containing a mapping
-/// from "T" to "TraitA".
-fn learn_associated_types<'a>(t: &'a syn::ItemTrait) -> HashMap<&'a syn::Ident, &'a syn::Ident> {
-       let mut associated_types = HashMap::new();
-       for item in t.items.iter() {
-               match item {
-                       &syn::TraitItem::Type(ref t) => {
-                               if t.default.is_some() || t.generics.lt_token.is_some() { unimplemented!(); }
-                               let mut bounds_iter = t.bounds.iter();
-                               match bounds_iter.next().unwrap() {
-                                       syn::TypeParamBound::Trait(tr) => {
-                                               assert_simple_bound(&tr);
-                                               associated_types.insert(&t.ident, assert_single_path_seg(&tr.path));
-                                       },
-                                       _ => unimplemented!(),
-                               }
-                               if bounds_iter.next().is_some() { unimplemented!(); }
-                       },
-                       _ => {},
-               }
-       }
-       associated_types
-}
-
 /// Prints a C-mapped trait object containing a void pointer and a jump table for each function in
 /// the original trait.
 /// Implements the native Rust trait and relevant parent traits for the new C-mapped trait.
@@ -150,10 +271,10 @@ fn writeln_trait<'a, 'b, W: std::io::Write>(w: &mut W, t: &'a syn::ItemTrait, ty
 
        let mut gen_types = GenericTypes::new();
        assert!(gen_types.learn_generics(&t.generics, types));
+       gen_types.learn_associated_types(&t, types);
 
        writeln!(w, "#[repr(C)]\npub struct {} {{", trait_name).unwrap();
        writeln!(w, "\tpub this_arg: *mut c_void,").unwrap();
-       let associated_types = learn_associated_types(t);
        let mut generated_fields = Vec::new(); // Every field's name except this_arg, used in Clone generation
        for item in t.items.iter() {
                match item {
@@ -210,7 +331,7 @@ fn writeln_trait<'a, 'b, W: std::io::Write>(w: &mut W, t: &'a syn::ItemTrait, ty
 
                                write!(w, "\tpub {}: extern \"C\" fn (", m.sig.ident).unwrap();
                                generated_fields.push(format!("{}", m.sig.ident));
-                               write_method_params(w, &m.sig, &associated_types, "c_void", types, Some(&gen_types), true, false);
+                               write_method_params(w, &m.sig, "c_void", types, Some(&gen_types), true, false);
                                writeln!(w, ",").unwrap();
 
                                gen_types.pop_ctx();
@@ -220,7 +341,7 @@ fn writeln_trait<'a, 'b, W: std::io::Write>(w: &mut W, t: &'a syn::ItemTrait, ty
                }
        }
        // Add functions which may be required for supertrait implementations.
-       walk_supertraits!(t, types, (
+       walk_supertraits!(t, Some(&types), (
                ("Clone", _) => {
                        writeln!(w, "\tpub clone: Option<extern \"C\" fn (this_arg: *const c_void) -> *mut c_void>,").unwrap();
                        generated_fields.push("clone".to_owned());
@@ -236,17 +357,22 @@ fn writeln_trait<'a, 'b, W: std::io::Write>(w: &mut W, t: &'a syn::ItemTrait, ty
                },
                ("Send", _) => {}, ("Sync", _) => {},
                (s, i) => {
-                       // For in-crate supertraits, just store a C-mapped copy of the supertrait as a member.
-                       if types.crate_types.traits.get(s).is_none() { unimplemented!(); }
-                       writeln!(w, "\tpub {}: crate::{},", i, s).unwrap();
-                       generated_fields.push(format!("{}", i));
+                       generated_fields.push(if types.crate_types.traits.get(s).is_none() {
+                               let (name, ret) = convert_trait_impl_field(s);
+                               writeln!(w, "\tpub {}: extern \"C\" fn (this_arg: *const c_void) -> {},", name, ret).unwrap();
+                               name
+                       } else {
+                               // For in-crate supertraits, just store a C-mapped copy of the supertrait as a member.
+                               writeln!(w, "\tpub {}: crate::{},", i, s).unwrap();
+                               format!("{}", i)
+                       });
                }
        ) );
        writeln!(w, "\tpub free: Option<extern \"C\" fn(this_arg: *mut c_void)>,").unwrap();
        generated_fields.push("free".to_owned());
        writeln!(w, "}}").unwrap();
        // Implement supertraits for the C-mapped struct.
-       walk_supertraits!(t, types, (
+       walk_supertraits!(t, Some(&types), (
                ("Send", _) => writeln!(w, "unsafe impl Send for {} {{}}", trait_name).unwrap(),
                ("Sync", _) => writeln!(w, "unsafe impl Sync for {} {{}}", trait_name).unwrap(),
                ("std::cmp::Eq", _) => {
@@ -273,13 +399,7 @@ fn writeln_trait<'a, 'b, W: std::io::Write>(w: &mut W, t: &'a syn::ItemTrait, ty
                        writeln!(w, "\t}}\n}}").unwrap();
                },
                (s, i) => {
-                       if s != "util::events::MessageSendEventsProvider" { unimplemented!(); }
-                       // XXX: We straight-up cheat here - instead of bothering to get the trait object we
-                       // just print what we need since this is only used in one place.
-                       writeln!(w, "impl lightning::{} for {} {{", s, trait_name).unwrap();
-                       writeln!(w, "\tfn get_and_clear_pending_msg_events(&self) -> Vec<lightning::util::events::MessageSendEvent> {{").unwrap();
-                       writeln!(w, "\t\t<crate::{} as lightning::{}>::get_and_clear_pending_msg_events(&self.{})", s, s, i).unwrap();
-                       writeln!(w, "\t}}\n}}").unwrap();
+                       do_write_impl_trait(w, s, i, &trait_name);
                }
        ) );
 
@@ -363,7 +483,7 @@ fn writeln_trait<'a, 'b, W: std::io::Write>(w: &mut W, t: &'a syn::ItemTrait, ty
                                }
                                write_method_var_decl_body(w, &m.sig, "\t", types, Some(&gen_types), true);
                                write!(w, "(self.{})(", m.sig.ident).unwrap();
-                               write_method_call_params(w, &m.sig, &associated_types, "\t", types, Some(&gen_types), "", true);
+                               write_method_call_params(w, &m.sig, "\t", types, Some(&gen_types), "", true);
 
                                writeln!(w, "\n\t}}").unwrap();
                                gen_types.pop_ctx();
@@ -397,7 +517,6 @@ fn writeln_trait<'a, 'b, W: std::io::Write>(w: &mut W, t: &'a syn::ItemTrait, ty
        writeln!(w, "\t\t}}\n\t}}\n}}").unwrap();
 
        write_cpp_wrapper(cpp_headers, &trait_name, true);
-       types.trait_declared(&t.ident, t);
 }
 
 /// Write out a simple "opaque" type (eg structs) which contain a pointer to the native Rust type
@@ -427,49 +546,13 @@ fn writeln_opaque<W: std::io::Write>(w: &mut W, ident: &syn::Ident, struct_name:
        writeln!(w, "#[allow(unused)]").unwrap();
        writeln!(w, "/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy").unwrap();
        writeln!(w, "impl {} {{", struct_name).unwrap();
-       writeln!(w, "\tpub(crate) fn take_ptr(mut self) -> *mut native{} {{", struct_name).unwrap();
+       writeln!(w, "\tpub(crate) fn take_inner(mut self) -> *mut native{} {{", struct_name).unwrap();
        writeln!(w, "\t\tassert!(self.is_owned);").unwrap();
        writeln!(w, "\t\tlet ret = self.inner;").unwrap();
        writeln!(w, "\t\tself.inner = std::ptr::null_mut();").unwrap();
        writeln!(w, "\t\tret").unwrap();
        writeln!(w, "\t}}\n}}").unwrap();
 
-       'attr_loop: for attr in attrs.iter() {
-               let tokens_clone = attr.tokens.clone();
-               let mut token_iter = tokens_clone.into_iter();
-               if let Some(token) = token_iter.next() {
-                       match token {
-                               TokenTree::Group(g) => {
-                                       if format!("{}", single_ident_generic_path_to_ident(&attr.path).unwrap()) == "derive" {
-                                               for id in g.stream().into_iter() {
-                                                       if let TokenTree::Ident(i) = id {
-                                                               if i == "Clone" {
-                                                                       writeln!(w, "impl Clone for {} {{", struct_name).unwrap();
-                                                                       writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
-                                                                       writeln!(w, "\t\tSelf {{").unwrap();
-                                                                       writeln!(w, "\t\t\tinner: Box::into_raw(Box::new(unsafe {{ &*self.inner }}.clone())),").unwrap();
-                                                                       writeln!(w, "\t\t\tis_owned: true,").unwrap();
-                                                                       writeln!(w, "\t\t}}\n\t}}\n}}").unwrap();
-                                                                       writeln!(w, "#[allow(unused)]").unwrap();
-                                                                       writeln!(w, "/// Used only if an object of this type is returned as a trait impl by a method").unwrap();
-                                                                       writeln!(w, "pub(crate) extern \"C\" fn {}_clone_void(this_ptr: *const c_void) -> *mut c_void {{", struct_name).unwrap();
-                                                                       writeln!(w, "\tBox::into_raw(Box::new(unsafe {{ (*(this_ptr as *mut native{})).clone() }})) as *mut c_void", struct_name).unwrap();
-                                                                       writeln!(w, "}}").unwrap();
-                                                                       writeln!(w, "#[no_mangle]").unwrap();
-                                                                       writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", struct_name, struct_name, struct_name).unwrap();
-                                                                       writeln!(w, "\t{} {{ inner: Box::into_raw(Box::new(unsafe {{ &*orig.inner }}.clone())), is_owned: true }}", struct_name).unwrap();
-                                                                       writeln!(w, "}}").unwrap();
-                                                                       break 'attr_loop;
-                                                               }
-                                                       }
-                                               }
-                                       }
-                               },
-                               _ => {},
-                       }
-               }
-       }
-
        write_cpp_wrapper(cpp_headers, &format!("{}", ident), true);
 }
 
@@ -477,20 +560,11 @@ fn writeln_opaque<W: std::io::Write>(w: &mut W, ident: &syn::Ident, struct_name:
 /// the struct itself, and then writing getters and setters for public, understood-type fields and
 /// a constructor if every field is public.
 fn writeln_struct<'a, 'b, W: std::io::Write>(w: &mut W, s: &'a syn::ItemStruct, types: &mut TypeResolver<'b, 'a>, extra_headers: &mut File, cpp_headers: &mut File) {
-       let struct_name = &format!("{}", s.ident);
-       let export = export_status(&s.attrs);
-       match export {
-               ExportStatus::Export => {},
-               ExportStatus::TestOnly => return,
-               ExportStatus::NoExport => {
-                       types.struct_ignored(&s.ident);
-                       return;
-               }
-       }
+       if export_status(&s.attrs) != ExportStatus::Export { return; }
 
+       let struct_name = &format!("{}", s.ident);
        writeln_opaque(w, &s.ident, struct_name, &s.generics, &s.attrs, types, extra_headers, cpp_headers);
 
-       eprintln!("exporting fields for {}", struct_name);
        if let syn::Fields::Named(fields) = &s.fields {
                let mut gen_types = GenericTypes::new();
                assert!(gen_types.learn_generics(&s.generics, types));
@@ -571,8 +645,6 @@ fn writeln_struct<'a, 'b, W: std::io::Write>(w: &mut W, s: &'a syn::ItemStruct,
                        writeln!(w, "\t}})), is_owned: true }}\n}}").unwrap();
                }
        }
-
-       types.struct_imported(&s.ident, struct_name.clone());
 }
 
 /// Prints a relevant conversion for impl *
@@ -585,6 +657,36 @@ fn writeln_struct<'a, 'b, W: std::io::Write>(w: &mut W, s: &'a syn::ItemStruct,
 ///
 /// A few non-crate Traits are hard-coded including Default.
 fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut TypeResolver) {
+       match export_status(&i.attrs) {
+               ExportStatus::Export => {},
+               ExportStatus::NoExport|ExportStatus::TestOnly => return,
+       }
+
+       if let syn::Type::Tuple(_) = &*i.self_ty {
+               if types.understood_c_type(&*i.self_ty, None) {
+                       let mut gen_types = GenericTypes::new();
+                       if !gen_types.learn_generics(&i.generics, types) {
+                               eprintln!("Not implementing anything for `impl (..)` due to not understood generics");
+                               return;
+                       }
+
+                       if i.defaultness.is_some() || i.unsafety.is_some() { unimplemented!(); }
+                       if let Some(trait_path) = i.trait_.as_ref() {
+                               if trait_path.0.is_some() { unimplemented!(); }
+                               if types.understood_c_path(&trait_path.1) {
+                                       eprintln!("Not implementing anything for `impl Trait for (..)` - we only support manual defines");
+                                       return;
+                               } else {
+                                       // Just do a manual implementation:
+                                       maybe_convert_trait_impl(w, &trait_path.1, &*i.self_ty, types, &gen_types);
+                               }
+                       } else {
+                               eprintln!("Not implementing anything for plain `impl (..)` block - we only support `impl Trait for (..)` blocks");
+                               return;
+                       }
+               }
+               return;
+       }
        if let &syn::Type::Path(ref p) = &*i.self_ty {
                if p.qself.is_some() { unimplemented!(); }
                if let Some(ident) = single_ident_generic_path_to_ident(&p.path) {
@@ -605,7 +707,7 @@ fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut Typ
                                                // That's great, except that they are unresolved idents, so if we learn
                                                // mappings from a trai defined in a different file, we may mis-resolve or
                                                // fail to resolve the mapped types.
-                                               let trait_associated_types = learn_associated_types(trait_obj);
+                                               gen_types.learn_associated_types(trait_obj, types);
                                                let mut impl_associated_types = HashMap::new();
                                                for item in i.items.iter() {
                                                        match item {
@@ -625,7 +727,22 @@ fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut Typ
                                                        ExportStatus::Export => {},
                                                        ExportStatus::NoExport|ExportStatus::TestOnly => return,
                                                }
-                                               write!(w, "#[no_mangle]\npub extern \"C\" fn {}_as_{}(this_arg: *const {}) -> crate::{} {{\n", ident, trait_obj.ident, ident, full_trait_path).unwrap();
+
+                                               // For cases where we have a concrete native object which implements a
+                                               // trait and need to return the C-mapped version of the trait, provide a
+                                               // From<> implementation which does all the work to ensure free is handled
+                                               // properly. This way we can call this method from deep in the
+                                               // type-conversion logic without actually knowing the concrete native type.
+                                               writeln!(w, "impl From<native{}> for crate::{} {{", ident, full_trait_path).unwrap();
+                                               writeln!(w, "\tfn from(obj: native{}) -> Self {{", ident).unwrap();
+                                               writeln!(w, "\t\tlet mut rust_obj = {} {{ inner: Box::into_raw(Box::new(obj)), is_owned: true }};", ident).unwrap();
+                                               writeln!(w, "\t\tlet mut ret = {}_as_{}(&rust_obj);", ident, trait_obj.ident).unwrap();
+                                               writeln!(w, "\t\t// We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn").unwrap();
+                                               writeln!(w, "\t\trust_obj.inner = std::ptr::null_mut();").unwrap();
+                                               writeln!(w, "\t\tret.free = Some({}_free_void);", ident).unwrap();
+                                               writeln!(w, "\t\tret\n\t}}\n}}").unwrap();
+
+                                               write!(w, "#[no_mangle]\npub extern \"C\" fn {}_as_{}(this_arg: &{}) -> crate::{} {{\n", ident, trait_obj.ident, ident, full_trait_path).unwrap();
                                                writeln!(w, "\tcrate::{} {{", full_trait_path).unwrap();
                                                writeln!(w, "\t\tthis_arg: unsafe {{ (*this_arg).inner as *mut c_void }},").unwrap();
                                                writeln!(w, "\t\tfree: None,").unwrap();
@@ -666,13 +783,14 @@ fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut Typ
                                                                _ => {},
                                                        }
                                                }
-                                               walk_supertraits!(trait_obj, types, (
+                                               walk_supertraits!(trait_obj, Some(&types), (
                                                        ("Clone", _) => {
                                                                writeln!(w, "\t\tclone: Some({}_clone_void),", ident).unwrap();
                                                        },
+                                                       ("Sync", _) => {}, ("Send", _) => {},
+                                                       ("std::marker::Sync", _) => {}, ("std::marker::Send", _) => {},
                                                        (s, t) => {
-                                                               if s.starts_with("util::") {
-                                                                       let supertrait_obj = types.crate_types.traits.get(s).unwrap();
+                                                               if let Some(supertrait_obj) = types.crate_types.traits.get(s) {
                                                                        writeln!(w, "\t\t{}: crate::{} {{", t, s).unwrap();
                                                                        writeln!(w, "\t\t\tthis_arg: unsafe {{ (*this_arg).inner as *mut c_void }},").unwrap();
                                                                        writeln!(w, "\t\t\tfree: None,").unwrap();
@@ -685,6 +803,8 @@ fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut Typ
                                                                                }
                                                                        }
                                                                        write!(w, "\t\t}},\n").unwrap();
+                                                               } else {
+                                                                       write_trait_impl_field_assign(w, s, ident);
                                                                }
                                                        }
                                                ) );
@@ -706,7 +826,7 @@ fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut Typ
                                                                write!(w, "extern \"C\" fn {}_{}_{}(", ident, trait_obj.ident, $m.sig.ident).unwrap();
                                                                gen_types.push_ctx();
                                                                assert!(gen_types.learn_generics(&$m.sig.generics, types));
-                                                               write_method_params(w, &$m.sig, &trait_associated_types, "c_void", types, Some(&gen_types), true, true);
+                                                               write_method_params(w, &$m.sig, "c_void", types, Some(&gen_types), true, true);
                                                                write!(w, " {{\n\t").unwrap();
                                                                write_method_var_decl_body(w, &$m.sig, "", types, Some(&gen_types), false);
                                                                let mut takes_self = false;
@@ -715,10 +835,16 @@ fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut Typ
                                                                                takes_self = true;
                                                                        }
                                                                }
+
+                                                               let mut t_gen_args = String::new();
+                                                               for (idx, _) in $trait.generics.params.iter().enumerate() {
+                                                                       if idx != 0 { t_gen_args += ", " };
+                                                                       t_gen_args += "_"
+                                                               }
                                                                if takes_self {
-                                                                       write!(w, "unsafe {{ &mut *(this_arg as *mut native{}) }}.{}(", ident, $m.sig.ident).unwrap();
+                                                                       write!(w, "<native{} as {}TraitImport<{}>>::{}(unsafe {{ &mut *(this_arg as *mut native{}) }}, ", ident, $trait.ident, t_gen_args, $m.sig.ident, ident).unwrap();
                                                                } else {
-                                                                       write!(w, "{}::{}::{}(", types.orig_crate, resolved_path, $m.sig.ident).unwrap();
+                                                                       write!(w, "<native{} as {}TraitImport<{}>>::{}(", ident, $trait.ident, t_gen_args, $m.sig.ident).unwrap();
                                                                }
 
                                                                let mut real_type = "".to_string();
@@ -732,7 +858,7 @@ fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut Typ
                                                                        },
                                                                        _ => {},
                                                                }
-                                                               write_method_call_params(w, &$m.sig, &trait_associated_types, "", types, Some(&gen_types), &real_type, false);
+                                                               write_method_call_params(w, &$m.sig, "", types, Some(&gen_types), &real_type, false);
                                                                gen_types.pop_ctx();
                                                                write!(w, "\n}}\n").unwrap();
                                                                if let syn::ReturnType::Type(_, rtype) = &$m.sig.output {
@@ -761,11 +887,10 @@ fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut Typ
                                                                _ => unimplemented!(),
                                                        }
                                                }
-                                               walk_supertraits!(trait_obj, types, (
+                                               walk_supertraits!(trait_obj, Some(&types), (
                                                        (s, t) => {
-                                                               if s.starts_with("util::") {
+                                                               if let Some(supertrait_obj) = types.crate_types.traits.get(s).cloned() {
                                                                        writeln!(w, "use {}::{} as native{}Trait;", types.orig_crate, s, t).unwrap();
-                                                                       let supertrait_obj = *types.crate_types.traits.get(s).unwrap();
                                                                        for item in supertrait_obj.items.iter() {
                                                                                match item {
                                                                                        syn::TraitItem::Method(m) => {
@@ -778,23 +903,34 @@ fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut Typ
                                                        }
                                                ) );
                                                write!(w, "\n").unwrap();
-                                       } else if let Some(trait_ident) = trait_path.1.get_ident() {
+                                       } else if path_matches_nongeneric(&trait_path.1, &["From"]) {
+                                       } else if path_matches_nongeneric(&trait_path.1, &["Default"]) {
+                                               write!(w, "#[must_use]\n#[no_mangle]\npub extern \"C\" fn {}_default() -> {} {{\n", ident, ident).unwrap();
+                                               write!(w, "\t{} {{ inner: Box::into_raw(Box::new(Default::default())), is_owned: true }}\n", ident).unwrap();
+                                               write!(w, "}}\n").unwrap();
+                                       } else if path_matches_nongeneric(&trait_path.1, &["core", "cmp", "PartialEq"]) {
+                                       } else if (path_matches_nongeneric(&trait_path.1, &["core", "clone", "Clone"]) || path_matches_nongeneric(&trait_path.1, &["Clone"])) &&
+                                                       types.c_type_has_inner_from_path(&resolved_path) {
+                                               writeln!(w, "impl Clone for {} {{", ident).unwrap();
+                                               writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
+                                               writeln!(w, "\t\tSelf {{").unwrap();
+                                               writeln!(w, "\t\t\tinner: if self.inner.is_null() {{ std::ptr::null_mut() }} else {{").unwrap();
+                                               writeln!(w, "\t\t\t\tBox::into_raw(Box::new(unsafe {{ &*self.inner }}.clone())) }},").unwrap();
+                                               writeln!(w, "\t\t\tis_owned: true,").unwrap();
+                                               writeln!(w, "\t\t}}\n\t}}\n}}").unwrap();
+                                               writeln!(w, "#[allow(unused)]").unwrap();
+                                               writeln!(w, "/// Used only if an object of this type is returned as a trait impl by a method").unwrap();
+                                               writeln!(w, "pub(crate) extern \"C\" fn {}_clone_void(this_ptr: *const c_void) -> *mut c_void {{", ident).unwrap();
+                                               writeln!(w, "\tBox::into_raw(Box::new(unsafe {{ (*(this_ptr as *mut native{})).clone() }})) as *mut c_void", ident).unwrap();
+                                               writeln!(w, "}}").unwrap();
+                                               writeln!(w, "#[no_mangle]").unwrap();
+                                               writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", ident, ident, ident).unwrap();
+                                               writeln!(w, "\torig.clone()").unwrap();
+                                               writeln!(w, "}}").unwrap();
+                                       } else {
                                                //XXX: implement for other things like ToString
-                                               match &format!("{}", trait_ident) as &str {
-                                                       "From" => {},
-                                                       "Default" => {
-                                                               write!(w, "#[must_use]\n#[no_mangle]\npub extern \"C\" fn {}_default() -> {} {{\n", ident, ident).unwrap();
-                                                               write!(w, "\t{} {{ inner: Box::into_raw(Box::new(Default::default())), is_owned: true }}\n", ident).unwrap();
-                                                               write!(w, "}}\n").unwrap();
-                                                       },
-                                                       "PartialEq" => {},
-                                                       // If we have no generics, try a manual implementation:
-                                                       _ if p.path.get_ident().is_some() => maybe_convert_trait_impl(w, &trait_path.1, &ident, types),
-                                                       _ => {},
-                                               }
-                                       } else if p.path.get_ident().is_some() {
                                                // If we have no generics, try a manual implementation:
-                                               maybe_convert_trait_impl(w, &trait_path.1, &ident, types);
+                                               maybe_convert_trait_impl(w, &trait_path.1, &*i.self_ty, types, &gen_types);
                                        }
                                } else {
                                        let declared_type = (*types.get_declared_type(&ident).unwrap()).clone();
@@ -819,7 +955,7 @@ fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut Typ
                                                                        };
                                                                        gen_types.push_ctx();
                                                                        assert!(gen_types.learn_generics(&m.sig.generics, types));
-                                                                       write_method_params(w, &m.sig, &HashMap::new(), &ret_type, types, Some(&gen_types), false, true);
+                                                                       write_method_params(w, &m.sig, &ret_type, types, Some(&gen_types), false, true);
                                                                        write!(w, " {{\n\t").unwrap();
                                                                        write_method_var_decl_body(w, &m.sig, "", types, Some(&gen_types), false);
                                                                        let mut takes_self = false;
@@ -837,7 +973,7 @@ fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut Typ
                                                                        } else {
                                                                                write!(w, "{}::{}::{}(", types.orig_crate, resolved_path, m.sig.ident).unwrap();
                                                                        }
-                                                                       write_method_call_params(w, &m.sig, &HashMap::new(), "", types, Some(&gen_types), &ret_type, false);
+                                                                       write_method_call_params(w, &m.sig, "", types, Some(&gen_types), &ret_type, false);
                                                                        gen_types.pop_ctx();
                                                                        writeln!(w, "\n}}\n").unwrap();
                                                                }
@@ -846,31 +982,67 @@ fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut Typ
                                                }
                                        }
                                }
+                       } else if let Some(resolved_path) = types.maybe_resolve_ident(&ident) {
+                               if let Some(aliases) = types.crate_types.reverse_alias_map.get(&resolved_path).cloned() {
+                                       'alias_impls: for (alias, arguments) in aliases {
+                                               let alias_resolved = types.resolve_path(&alias, None);
+                                               for (idx, gen) in i.generics.params.iter().enumerate() {
+                                                       match gen {
+                                                               syn::GenericParam::Type(type_param) => {
+                                                                       'bounds_check: for bound in type_param.bounds.iter() {
+                                                                               if let syn::TypeParamBound::Trait(trait_bound) = bound {
+                                                                                       if let syn::PathArguments::AngleBracketed(ref t) = &arguments {
+                                                                                               assert!(idx < t.args.len());
+                                                                                               if let syn::GenericArgument::Type(syn::Type::Path(p)) = &t.args[idx] {
+                                                                                                       let generic_arg = types.resolve_path(&p.path, None);
+                                                                                                       let generic_bound = types.resolve_path(&trait_bound.path, None);
+                                                                                                       if let Some(traits_impld) = types.crate_types.trait_impls.get(&generic_arg) {
+                                                                                                               for trait_impld in traits_impld {
+                                                                                                                       if *trait_impld == generic_bound { continue 'bounds_check; }
+                                                                                                               }
+                                                                                                               eprintln!("struct {}'s generic arg {} didn't match bound {}", alias_resolved, generic_arg, generic_bound);
+                                                                                                               continue 'alias_impls;
+                                                                                                       } else {
+                                                                                                               eprintln!("struct {}'s generic arg {} didn't match bound {}", alias_resolved, generic_arg, generic_bound);
+                                                                                                               continue 'alias_impls;
+                                                                                                       }
+                                                                                               } else { unimplemented!(); }
+                                                                                       } else { unimplemented!(); }
+                                                                               } else { unimplemented!(); }
+                                                                       }
+                                                               },
+                                                               syn::GenericParam::Lifetime(_) => {},
+                                                               syn::GenericParam::Const(_) => unimplemented!(),
+                                                       }
+                                               }
+                                               let aliased_impl = syn::ItemImpl {
+                                                       attrs: i.attrs.clone(),
+                                                       brace_token: syn::token::Brace(Span::call_site()),
+                                                       defaultness: None,
+                                                       generics: syn::Generics {
+                                                               lt_token: None,
+                                                               params: syn::punctuated::Punctuated::new(),
+                                                               gt_token: None,
+                                                               where_clause: None,
+                                                       },
+                                                       impl_token: syn::Token![impl](Span::call_site()),
+                                                       items: i.items.clone(),
+                                                       self_ty: Box::new(syn::Type::Path(syn::TypePath { qself: None, path: alias.clone() })),
+                                                       trait_: i.trait_.clone(),
+                                                       unsafety: None,
+                                               };
+                                               writeln_impl(w, &aliased_impl, types);
+                                       }
+                               } else {
+                                       eprintln!("Not implementing anything for {} due to it being marked not exported", ident);
+                               }
                        } else {
-                               eprintln!("Not implementing anything for {} due to no-resolve (probably the type isn't pub or its marked not exported)", ident);
+                               eprintln!("Not implementing anything for {} due to no-resolve (probably the type isn't pub)", ident);
                        }
                }
        }
 }
 
-/// Returns true if the enum will be mapped as an opaue (ie struct with a pointer to the underlying
-/// type), otherwise it is mapped into a transparent, C-compatible version of itself.
-fn is_enum_opaque(e: &syn::ItemEnum) -> bool {
-       for var in e.variants.iter() {
-               if let syn::Fields::Unit = var.fields {
-               } else if let syn::Fields::Named(fields) = &var.fields {
-                       for field in fields.named.iter() {
-                               match export_status(&field.attrs) {
-                                       ExportStatus::Export|ExportStatus::TestOnly => {},
-                                       ExportStatus::NoExport => return true,
-                               }
-                       }
-               } else {
-                       return true;
-               }
-       }
-       false
-}
 
 /// Print a mapping of an enum. If all of the enum's fields are C-mapped in some form (or the enum
 /// is unitary), we generate an equivalent enum with all types replaced with their C mapped
@@ -885,7 +1057,6 @@ fn writeln_enum<'a, 'b, W: std::io::Write>(w: &mut W, e: &'a syn::ItemEnum, type
        if is_enum_opaque(e) {
                eprintln!("Skipping enum {} as it contains non-unit fields", e.ident);
                writeln_opaque(w, &e.ident, &format!("{}", e.ident), &e.generics, &e.attrs, types, extra_headers, cpp_headers);
-               types.enum_ignored(&e.ident);
                return;
        }
        writeln_docs(w, &e.attrs, "");
@@ -893,7 +1064,6 @@ fn writeln_enum<'a, 'b, W: std::io::Write>(w: &mut W, e: &'a syn::ItemEnum, type
        if e.generics.lt_token.is_some() {
                unimplemented!();
        }
-       types.mirrored_enum_declared(&e.ident);
 
        let mut needs_free = false;
 
@@ -912,6 +1082,17 @@ fn writeln_enum<'a, 'b, W: std::io::Write>(w: &mut W, e: &'a syn::ItemEnum, type
                                writeln!(w, ",").unwrap();
                        }
                        write!(w, "\t}}").unwrap();
+               } else if let syn::Fields::Unnamed(fields) = &var.fields {
+                       needs_free = true;
+                       write!(w, "(").unwrap();
+                       for (idx, field) in fields.unnamed.iter().enumerate() {
+                               if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
+                               types.write_c_type(w, &field.ty, None, false);
+                               if idx != fields.unnamed.len() - 1 {
+                                       write!(w, ",").unwrap();
+                               }
+                       }
+                       write!(w, ")").unwrap();
                }
                if var.discriminant.is_some() { unimplemented!(); }
                writeln!(w, ",").unwrap();
@@ -930,28 +1111,35 @@ fn writeln_enum<'a, 'b, W: std::io::Write>(w: &mut W, e: &'a syn::ItemEnum, type
                                                write!(w, "{}{}, ", if $ref { "ref " } else { "mut " }, field.ident.as_ref().unwrap()).unwrap();
                                        }
                                        write!(w, "}} ").unwrap();
+                               } else if let syn::Fields::Unnamed(fields) = &var.fields {
+                                       write!(w, "(").unwrap();
+                                       for (idx, field) in fields.unnamed.iter().enumerate() {
+                                               if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
+                                               write!(w, "{}{}, ", if $ref { "ref " } else { "mut " }, ('a' as u8 + idx as u8) as char).unwrap();
+                                       }
+                                       write!(w, ") ").unwrap();
                                }
                                write!(w, "=>").unwrap();
-                               if let syn::Fields::Named(fields) = &var.fields {
-                                       write!(w, " {{\n\t\t\t\t").unwrap();
-                                       for field in fields.named.iter() {
-                                               if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
+
+                               macro_rules! handle_field_a {
+                                       ($field: expr, $field_ident: expr) => { {
+                                               if export_status(&$field.attrs) == ExportStatus::TestOnly { continue; }
                                                let mut sink = ::std::io::sink();
                                                let mut out: &mut dyn std::io::Write = if $ref { &mut sink } else { w };
                                                let new_var = if $to_c {
-                                                       types.write_to_c_conversion_new_var(&mut out, field.ident.as_ref().unwrap(), &field.ty, None, false)
+                                                       types.write_to_c_conversion_new_var(&mut out, $field_ident, &$field.ty, None, false)
                                                } else {
-                                                       types.write_from_c_conversion_new_var(&mut out, field.ident.as_ref().unwrap(), &field.ty, None)
+                                                       types.write_from_c_conversion_new_var(&mut out, $field_ident, &$field.ty, None)
                                                };
                                                if $ref || new_var {
                                                        if $ref {
-                                                               write!(w, "let mut {}_nonref = (*{}).clone();\n\t\t\t\t", field.ident.as_ref().unwrap(), field.ident.as_ref().unwrap()).unwrap();
+                                                               write!(w, "let mut {}_nonref = (*{}).clone();\n\t\t\t\t", $field_ident, $field_ident).unwrap();
                                                                if new_var {
-                                                                       let nonref_ident = syn::Ident::new(&format!("{}_nonref", field.ident.as_ref().unwrap()), Span::call_site());
+                                                                       let nonref_ident = syn::Ident::new(&format!("{}_nonref", $field_ident), Span::call_site());
                                                                        if $to_c {
-                                                                               types.write_to_c_conversion_new_var(w, &nonref_ident, &field.ty, None, false);
+                                                                               types.write_to_c_conversion_new_var(w, &nonref_ident, &$field.ty, None, false);
                                                                        } else {
-                                                                               types.write_from_c_conversion_new_var(w, &nonref_ident, &field.ty, None);
+                                                                               types.write_from_c_conversion_new_var(w, &nonref_ident, &$field.ty, None);
                                                                        }
                                                                        write!(w, "\n\t\t\t\t").unwrap();
                                                                }
@@ -959,31 +1147,58 @@ fn writeln_enum<'a, 'b, W: std::io::Write>(w: &mut W, e: &'a syn::ItemEnum, type
                                                                write!(w, "\n\t\t\t\t").unwrap();
                                                        }
                                                }
+                                       } }
+                               }
+                               if let syn::Fields::Named(fields) = &var.fields {
+                                       write!(w, " {{\n\t\t\t\t").unwrap();
+                                       for field in fields.named.iter() {
+                                               handle_field_a!(field, field.ident.as_ref().unwrap());
+                                       }
+                               } else if let syn::Fields::Unnamed(fields) = &var.fields {
+                                       write!(w, " {{\n\t\t\t\t").unwrap();
+                                       for (idx, field) in fields.unnamed.iter().enumerate() {
+                                               handle_field_a!(field, &syn::Ident::new(&(('a' as u8 + idx as u8) as char).to_string(), Span::call_site()));
                                        }
                                } else { write!(w, " ").unwrap(); }
+
                                write!(w, "{}{}::{}", if $to_c { "" } else { "native" }, e.ident, var.ident).unwrap();
-                               if let syn::Fields::Named(fields) = &var.fields {
-                                       write!(w, " {{").unwrap();
-                                       for field in fields.named.iter() {
-                                               if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
-                                               write!(w, "\n\t\t\t\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
+
+                               macro_rules! handle_field_b {
+                                       ($field: expr, $field_ident: expr) => { {
+                                               if export_status(&$field.attrs) == ExportStatus::TestOnly { continue; }
                                                if $to_c {
-                                                       types.write_to_c_conversion_inline_prefix(w, &field.ty, None, false);
+                                                       types.write_to_c_conversion_inline_prefix(w, &$field.ty, None, false);
                                                } else {
-                                                       types.write_from_c_conversion_prefix(w, &field.ty, None);
+                                                       types.write_from_c_conversion_prefix(w, &$field.ty, None);
                                                }
-                                               write!(w, "{}{}",
-                                                       field.ident.as_ref().unwrap(),
+                                               write!(w, "{}{}", $field_ident,
                                                        if $ref { "_nonref" } else { "" }).unwrap();
                                                if $to_c {
-                                                       types.write_to_c_conversion_inline_suffix(w, &field.ty, None, false);
+                                                       types.write_to_c_conversion_inline_suffix(w, &$field.ty, None, false);
                                                } else {
-                                                       types.write_from_c_conversion_suffix(w, &field.ty, None);
+                                                       types.write_from_c_conversion_suffix(w, &$field.ty, None);
                                                }
                                                write!(w, ",").unwrap();
+                                       } }
+                               }
+
+                               if let syn::Fields::Named(fields) = &var.fields {
+                                       write!(w, " {{").unwrap();
+                                       for field in fields.named.iter() {
+                                               if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
+                                               write!(w, "\n\t\t\t\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
+                                               handle_field_b!(field, field.ident.as_ref().unwrap());
                                        }
                                        writeln!(w, "\n\t\t\t\t}}").unwrap();
                                        write!(w, "\t\t\t}}").unwrap();
+                               } else if let syn::Fields::Unnamed(fields) = &var.fields {
+                                       write!(w, " (").unwrap();
+                                       for (idx, field) in fields.unnamed.iter().enumerate() {
+                                               write!(w, "\n\t\t\t\t\t").unwrap();
+                                               handle_field_b!(field, &syn::Ident::new(&(('a' as u8 + idx as u8) as char).to_string(), Span::call_site()));
+                                       }
+                                       writeln!(w, "\n\t\t\t\t)").unwrap();
+                                       write!(w, "\t\t\t}}").unwrap();
                                }
                                writeln!(w, ",").unwrap();
                        }
@@ -1018,367 +1233,375 @@ fn writeln_fn<'a, 'b, W: std::io::Write>(w: &mut W, f: &'a syn::ItemFn, types: &
        if !gen_types.learn_generics(&f.sig.generics, types) { return; }
 
        write!(w, "#[no_mangle]\npub extern \"C\" fn {}(", f.sig.ident).unwrap();
-       write_method_params(w, &f.sig, &HashMap::new(), "", types, Some(&gen_types), false, true);
+       write_method_params(w, &f.sig, "", types, Some(&gen_types), false, true);
        write!(w, " {{\n\t").unwrap();
        write_method_var_decl_body(w, &f.sig, "", types, Some(&gen_types), false);
        write!(w, "{}::{}::{}(", types.orig_crate, types.module_path, f.sig.ident).unwrap();
-       write_method_call_params(w, &f.sig, &HashMap::new(), "", types, Some(&gen_types), "", false);
+       write_method_call_params(w, &f.sig, "", types, Some(&gen_types), "", false);
        writeln!(w, "\n}}\n").unwrap();
 }
 
 // ********************************
 // *** File/Crate Walking Logic ***
 // ********************************
-
-/// Simple utility to walk the modules in a crate - iterating over the modules (with file paths) in
-/// a single File.
-struct FileIter<'a, I: Iterator<Item = &'a syn::Item>> {
-       in_dir: &'a str,
-       path: &'a str,
-       module: &'a str,
-       item_iter: I,
+/// A public module
+struct ASTModule {
+       pub attrs: Vec<syn::Attribute>,
+       pub items: Vec<syn::Item>,
+       pub submods: Vec<String>,
 }
-impl<'a, I: Iterator<Item = &'a syn::Item>> Iterator for FileIter<'a, I> {
-       type Item = (String, String, &'a syn::ItemMod);
-       fn next(&mut self) -> std::option::Option<<Self as std::iter::Iterator>::Item> {
-               loop {
-                       match self.item_iter.next() {
-                               Some(syn::Item::Mod(m)) => {
-                                       if let syn::Visibility::Public(_) = m.vis {
-                                               match export_status(&m.attrs) {
-                                                       ExportStatus::Export => {},
-                                                       ExportStatus::NoExport|ExportStatus::TestOnly => continue,
-                                               }
-
-                                               let f_path = format!("{}/{}.rs", (self.path.as_ref() as &Path).parent().unwrap().display(), m.ident);
-                                               let new_mod = if self.module.is_empty() { format!("{}", m.ident) } else { format!("{}::{}", self.module, m.ident) };
-                                               if let Ok(_) = File::open(&format!("{}/{}", self.in_dir, f_path)) {
-                                                       return Some((f_path, new_mod, m));
+/// A struct containing the syn::File AST for each file in the crate.
+struct FullLibraryAST {
+       modules: HashMap<String, ASTModule, NonRandomHash>,
+}
+impl FullLibraryAST {
+       fn load_module(&mut self, module: String, attrs: Vec<syn::Attribute>, mut items: Vec<syn::Item>) {
+               let mut non_mod_items = Vec::with_capacity(items.len());
+               let mut submods = Vec::with_capacity(items.len());
+               for item in items.drain(..) {
+                       match item {
+                               syn::Item::Mod(m) if m.content.is_some() => {
+                                       if export_status(&m.attrs) == ExportStatus::Export {
+                                               if let syn::Visibility::Public(_) = m.vis {
+                                                       let modident = format!("{}", m.ident);
+                                                       let modname = if module != "" {
+                                                               module.clone() + "::" + &modident
+                                                       } else {
+                                                               modident.clone()
+                                                       };
+                                                       self.load_module(modname, m.attrs, m.content.unwrap().1);
+                                                       submods.push(modident);
                                                } else {
-                                                       return Some((
-                                                               format!("{}/{}/mod.rs", (self.path.as_ref() as &Path).parent().unwrap().display(), m.ident),
-                                                               new_mod, m));
+                                                       non_mod_items.push(syn::Item::Mod(m));
                                                }
                                        }
                                },
-                               Some(_) => {},
-                               None => return None,
+                               syn::Item::Mod(_) => panic!("--pretty=expanded output should never have non-body modules"),
+                               _ => { non_mod_items.push(item); }
                        }
                }
+               self.modules.insert(module, ASTModule { attrs, items: non_mod_items, submods });
        }
-}
-fn file_iter<'a>(file: &'a syn::File, in_dir: &'a str, path: &'a str, module: &'a str) ->
-               impl Iterator<Item = (String, String, &'a syn::ItemMod)> + 'a {
-       FileIter { in_dir, path, module, item_iter: file.items.iter() }
-}
 
-/// A struct containing the syn::File AST for each file in the crate.
-struct FullLibraryAST {
-       files: HashMap<String, syn::File>,
+       pub fn load_lib(lib: syn::File) -> Self {
+               assert_eq!(export_status(&lib.attrs), ExportStatus::Export);
+               let mut res = Self { modules: HashMap::default() };
+               res.load_module("".to_owned(), lib.attrs, lib.items);
+               res
+       }
 }
 
 /// Do the Real Work of mapping an original file to C-callable wrappers. Creates a new file at
 /// `out_path` and fills it with wrapper structs/functions to allow calling the things in the AST
 /// at `module` from C.
-fn convert_file<'a, 'b>(libast: &'a FullLibraryAST, crate_types: &mut CrateTypes<'a>, in_dir: &str, out_dir: &str, path: &str, orig_crate: &str, module: &str, header_file: &mut File, cpp_header_file: &mut File) {
-       let syntax = if let Some(ast) = libast.files.get(module) { ast } else { return };
-
-       assert!(syntax.shebang.is_none()); // Not sure what this is, hope we dont have one
-
-       let new_file_path = format!("{}/{}", out_dir, path);
-       let _ = std::fs::create_dir((&new_file_path.as_ref() as &std::path::Path).parent().unwrap());
-       let mut out = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
-               .open(new_file_path).expect("Unable to open new src file");
-
-       assert_eq!(export_status(&syntax.attrs), ExportStatus::Export);
-       writeln_docs(&mut out, &syntax.attrs, "");
-
-       if path.ends_with("/lib.rs") {
-               // Special-case the top-level lib.rs with various lint allows and a pointer to the c_types
-               // and bitcoin hand-written modules.
-               writeln!(out, "#![allow(unknown_lints)]").unwrap();
-               writeln!(out, "#![allow(non_camel_case_types)]").unwrap();
-               writeln!(out, "#![allow(non_snake_case)]").unwrap();
-               writeln!(out, "#![allow(unused_imports)]").unwrap();
-               writeln!(out, "#![allow(unused_variables)]").unwrap();
-               writeln!(out, "#![allow(unused_mut)]").unwrap();
-               writeln!(out, "#![allow(unused_parens)]").unwrap();
-               writeln!(out, "#![allow(unused_unsafe)]").unwrap();
-               writeln!(out, "#![allow(unused_braces)]").unwrap();
-               writeln!(out, "mod c_types;").unwrap();
-               writeln!(out, "mod bitcoin;").unwrap();
-       } else {
-               writeln!(out, "\nuse std::ffi::c_void;\nuse bitcoin::hashes::Hash;\nuse crate::c_types::*;\n").unwrap();
-       }
+fn convert_file<'a, 'b>(libast: &'a FullLibraryAST, crate_types: &mut CrateTypes<'a>, out_dir: &str, orig_crate: &str, header_file: &mut File, cpp_header_file: &mut File) {
+       for (module, astmod) in libast.modules.iter() {
+               let ASTModule { ref attrs, ref items, ref submods } = astmod;
+               assert_eq!(export_status(&attrs), ExportStatus::Export);
+
+               let new_file_path = if submods.is_empty() {
+                       format!("{}/{}.rs", out_dir, module.replace("::", "/"))
+               } else if module != "" {
+                       format!("{}/{}/mod.rs", out_dir, module.replace("::", "/"))
+               } else {
+                       format!("{}/lib.rs", out_dir)
+               };
+               let _ = std::fs::create_dir((&new_file_path.as_ref() as &std::path::Path).parent().unwrap());
+               let mut out = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
+                       .open(new_file_path).expect("Unable to open new src file");
+
+               writeln_docs(&mut out, &attrs, "");
+
+               if module == "" {
+                       // Special-case the top-level lib.rs with various lint allows and a pointer to the c_types
+                       // and bitcoin hand-written modules.
+                       writeln!(out, "#![allow(unknown_lints)]").unwrap();
+                       writeln!(out, "#![allow(non_camel_case_types)]").unwrap();
+                       writeln!(out, "#![allow(non_snake_case)]").unwrap();
+                       writeln!(out, "#![allow(unused_imports)]").unwrap();
+                       writeln!(out, "#![allow(unused_variables)]").unwrap();
+                       writeln!(out, "#![allow(unused_mut)]").unwrap();
+                       writeln!(out, "#![allow(unused_parens)]").unwrap();
+                       writeln!(out, "#![allow(unused_unsafe)]").unwrap();
+                       writeln!(out, "#![allow(unused_braces)]").unwrap();
+                       writeln!(out, "mod c_types;").unwrap();
+                       writeln!(out, "mod bitcoin;").unwrap();
+               } else {
+                       writeln!(out, "\nuse std::ffi::c_void;\nuse bitcoin::hashes::Hash;\nuse crate::c_types::*;\n").unwrap();
+               }
 
-       for (path, new_mod, m) in file_iter(&syntax, in_dir, path, &module) {
-               writeln_docs(&mut out, &m.attrs, "");
-               writeln!(out, "pub mod {};", m.ident).unwrap();
-               convert_file(libast, crate_types, in_dir, out_dir, &path,
-                       orig_crate, &new_mod, header_file, cpp_header_file);
-       }
+               for m in submods {
+                       writeln!(out, "pub mod {};", m).unwrap();
+               }
 
-       eprintln!("Converting {} entries...", path);
+               eprintln!("Converting {} entries...", module);
 
-       let mut type_resolver = TypeResolver::new(orig_crate, module, crate_types);
+               let import_resolver = ImportResolver::new(module, items);
+               let mut type_resolver = TypeResolver::new(orig_crate, module, import_resolver, crate_types);
 
-       for item in syntax.items.iter() {
-               match item {
-                       syn::Item::Use(u) => type_resolver.process_use(&mut out, &u),
-                       syn::Item::Static(_) => {},
-                       syn::Item::Enum(e) => {
-                               if let syn::Visibility::Public(_) = e.vis {
-                                       writeln_enum(&mut out, &e, &mut type_resolver, header_file, cpp_header_file);
-                               }
-                       },
-                       syn::Item::Impl(i) => {
-                               writeln_impl(&mut out, &i, &mut type_resolver);
-                       },
-                       syn::Item::Struct(s) => {
-                               if let syn::Visibility::Public(_) = s.vis {
-                                       writeln_struct(&mut out, &s, &mut type_resolver, header_file, cpp_header_file);
-                               }
-                       },
-                       syn::Item::Trait(t) => {
-                               if let syn::Visibility::Public(_) = t.vis {
-                                       writeln_trait(&mut out, &t, &mut type_resolver, header_file, cpp_header_file);
-                               }
-                       },
-                       syn::Item::Mod(_) => {}, // We don't have to do anything - the top loop handles these.
-                       syn::Item::Const(c) => {
-                               // Re-export any primitive-type constants.
-                               if let syn::Visibility::Public(_) = c.vis {
-                                       if let syn::Type::Path(p) = &*c.ty {
-                                               let resolved_path = type_resolver.resolve_path(&p.path, None);
-                                               if type_resolver.is_primitive(&resolved_path) {
-                                                       writeln!(out, "\n#[no_mangle]").unwrap();
-                                                       writeln!(out, "pub static {}: {} = {}::{}::{};", c.ident, resolved_path, orig_crate, module, c.ident).unwrap();
-                                               }
+               for item in items.iter() {
+                       match item {
+                               syn::Item::Use(_) => {}, // Handled above
+                               syn::Item::Static(_) => {},
+                               syn::Item::Enum(e) => {
+                                       if let syn::Visibility::Public(_) = e.vis {
+                                               writeln_enum(&mut out, &e, &mut type_resolver, header_file, cpp_header_file);
                                        }
-                               }
-                       },
-                       syn::Item::Type(t) => {
-                               if let syn::Visibility::Public(_) = t.vis {
-                                       match export_status(&t.attrs) {
-                                               ExportStatus::Export => {},
-                                               ExportStatus::NoExport|ExportStatus::TestOnly => continue,
+                               },
+                               syn::Item::Impl(i) => {
+                                       writeln_impl(&mut out, &i, &mut type_resolver);
+                               },
+                               syn::Item::Struct(s) => {
+                                       if let syn::Visibility::Public(_) = s.vis {
+                                               writeln_struct(&mut out, &s, &mut type_resolver, header_file, cpp_header_file);
                                        }
-
-                                       let mut process_alias = true;
-                                       for tok in t.generics.params.iter() {
-                                               if let syn::GenericParam::Lifetime(_) = tok {}
-                                               else { process_alias = false; }
+                               },
+                               syn::Item::Trait(t) => {
+                                       if let syn::Visibility::Public(_) = t.vis {
+                                               writeln_trait(&mut out, &t, &mut type_resolver, header_file, cpp_header_file);
                                        }
-                                       if process_alias {
-                                               match &*t.ty {
-                                                       syn::Type::Path(_) =>
-                                                               writeln_opaque(&mut out, &t.ident, &format!("{}", t.ident), &t.generics, &t.attrs, &type_resolver, header_file, cpp_header_file),
-                                                       _ => {}
+                               },
+                               syn::Item::Mod(_) => {}, // We don't have to do anything - the top loop handles these.
+                               syn::Item::Const(c) => {
+                                       // Re-export any primitive-type constants.
+                                       if let syn::Visibility::Public(_) = c.vis {
+                                               if let syn::Type::Path(p) = &*c.ty {
+                                                       let resolved_path = type_resolver.resolve_path(&p.path, None);
+                                                       if type_resolver.is_primitive(&resolved_path) {
+                                                               writeln!(out, "\n#[no_mangle]").unwrap();
+                                                               writeln!(out, "pub static {}: {} = {}::{}::{};", c.ident, resolved_path, orig_crate, module, c.ident).unwrap();
+                                                       }
                                                }
                                        }
-                               }
-                       },
-                       syn::Item::Fn(f) => {
-                               if let syn::Visibility::Public(_) = f.vis {
-                                       writeln_fn(&mut out, &f, &mut type_resolver);
-                               }
-                       },
-                       syn::Item::Macro(m) => {
-                               if m.ident.is_none() { // If its not a macro definition
-                                       convert_macro(&mut out, &m.mac.path, &m.mac.tokens, &type_resolver);
-                               }
-                       },
-                       syn::Item::Verbatim(_) => {},
-                       syn::Item::ExternCrate(_) => {},
-                       _ => unimplemented!(),
-               }
-       }
-
-       out.flush().unwrap();
-}
-
-/// Load the AST for each file in the crate, filling the FullLibraryAST object
-fn load_ast(in_dir: &str, path: &str, module: String, ast_storage: &mut FullLibraryAST) {
-       eprintln!("Loading {}{}...", in_dir, path);
-
-       let mut file = File::open(format!("{}/{}", in_dir, path)).expect("Unable to open file");
-       let mut src = String::new();
-       file.read_to_string(&mut src).expect("Unable to read file");
-       let syntax = syn::parse_file(&src).expect("Unable to parse file");
-
-       assert_eq!(export_status(&syntax.attrs), ExportStatus::Export);
-
-       for (path, new_mod, _) in file_iter(&syntax, in_dir, path, &module) {
-               load_ast(in_dir, &path, new_mod, ast_storage);
-       }
-       ast_storage.files.insert(module, syntax);
-}
+                               },
+                               syn::Item::Type(t) => {
+                                       if let syn::Visibility::Public(_) = t.vis {
+                                               match export_status(&t.attrs) {
+                                                       ExportStatus::Export => {},
+                                                       ExportStatus::NoExport|ExportStatus::TestOnly => continue,
+                                               }
 
-/// Insert ident -> absolute Path resolutions into imports from the given UseTree and path-prefix.
-fn process_use_intern<'a>(u: &'a syn::UseTree, mut path: syn::punctuated::Punctuated<syn::PathSegment, syn::token::Colon2>, imports: &mut HashMap<&'a syn::Ident, syn::Path>) {
-       match u {
-               syn::UseTree::Path(p) => {
-                       path.push(syn::PathSegment { ident: p.ident.clone(), arguments: syn::PathArguments::None });
-                       process_use_intern(&p.tree, path, imports);
-               },
-               syn::UseTree::Name(n) => {
-                       path.push(syn::PathSegment { ident: n.ident.clone(), arguments: syn::PathArguments::None });
-                       imports.insert(&n.ident, syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path });
-               },
-               syn::UseTree::Group(g) => {
-                       for i in g.items.iter() {
-                               process_use_intern(i, path.clone(), imports);
+                                               let mut process_alias = true;
+                                               for tok in t.generics.params.iter() {
+                                                       if let syn::GenericParam::Lifetime(_) = tok {}
+                                                       else { process_alias = false; }
+                                               }
+                                               if process_alias {
+                                                       match &*t.ty {
+                                                               syn::Type::Path(_) =>
+                                                                       writeln_opaque(&mut out, &t.ident, &format!("{}", t.ident), &t.generics, &t.attrs, &type_resolver, header_file, cpp_header_file),
+                                                               _ => {}
+                                                       }
+                                               }
+                                       }
+                               },
+                               syn::Item::Fn(f) => {
+                                       if let syn::Visibility::Public(_) = f.vis {
+                                               writeln_fn(&mut out, &f, &mut type_resolver);
+                                       }
+                               },
+                               syn::Item::Macro(m) => {
+                                       if m.ident.is_none() { // If its not a macro definition
+                                               convert_macro(&mut out, &m.mac.path, &m.mac.tokens, &type_resolver);
+                                       }
+                               },
+                               syn::Item::Verbatim(_) => {},
+                               syn::Item::ExternCrate(_) => {},
+                               _ => unimplemented!(),
                        }
-               },
-               _ => {}
-       }
-}
+               }
 
-/// Map all the Paths in a Type into absolute paths given a set of imports (generated via process_use_intern)
-fn resolve_imported_refs(imports: &HashMap<&syn::Ident, syn::Path>, mut ty: syn::Type) -> syn::Type {
-       match &mut ty {
-               syn::Type::Path(p) => {
-                       if let Some(ident) = p.path.get_ident() {
-                               if let Some(newpath) = imports.get(ident) {
-                                       p.path = newpath.clone();
-                               }
-                       } else { unimplemented!(); }
-               },
-               syn::Type::Reference(r) => {
-                       r.elem = Box::new(resolve_imported_refs(imports, (*r.elem).clone()));
-               },
-               syn::Type::Slice(s) => {
-                       s.elem = Box::new(resolve_imported_refs(imports, (*s.elem).clone()));
-               },
-               syn::Type::Tuple(t) => {
-                       for e in t.elems.iter_mut() {
-                               *e = resolve_imported_refs(imports, e.clone());
-                       }
-               },
-               _ => unimplemented!(),
+               out.flush().unwrap();
        }
-       ty
 }
 
-/// Walk the FullLibraryAST, deciding how things will be mapped and adding tracking to CrateTypes.
-fn walk_ast<'a>(in_dir: &str, path: &str, module: String, ast_storage: &'a FullLibraryAST, crate_types: &mut CrateTypes<'a>) {
-       let syntax = if let Some(ast) = ast_storage.files.get(&module) { ast } else { return };
-       assert_eq!(export_status(&syntax.attrs), ExportStatus::Export);
-
-       for (path, new_mod, _) in file_iter(&syntax, in_dir, path, &module) {
-               walk_ast(in_dir, &path, new_mod, ast_storage, crate_types);
-       }
-
-       let mut import_maps = HashMap::new();
-
-       for item in syntax.items.iter() {
+fn walk_private_mod<'a>(module: String, items: &'a syn::ItemMod, crate_types: &mut CrateTypes<'a>) {
+       let import_resolver = ImportResolver::new(&module, &items.content.as_ref().unwrap().1);
+       for item in items.content.as_ref().unwrap().1.iter() {
                match item {
-                       syn::Item::Use(u) => {
-                               process_use_intern(&u.tree, syn::punctuated::Punctuated::new(), &mut import_maps);
-                       },
-                       syn::Item::Struct(s) => {
-                               if let syn::Visibility::Public(_) = s.vis {
-                                       match export_status(&s.attrs) {
-                                               ExportStatus::Export => {},
-                                               ExportStatus::NoExport|ExportStatus::TestOnly => continue,
-                                       }
-                                       let struct_path = format!("{}::{}", module, s.ident);
-                                       crate_types.opaques.insert(struct_path, &s.ident);
-                               }
-                       },
-                       syn::Item::Trait(t) => {
-                               if let syn::Visibility::Public(_) = t.vis {
-                                       match export_status(&t.attrs) {
-                                               ExportStatus::Export => {},
-                                               ExportStatus::NoExport|ExportStatus::TestOnly => continue,
+                       syn::Item::Mod(m) => walk_private_mod(format!("{}::{}", module, m.ident), m, crate_types),
+                       syn::Item::Impl(i) => {
+                               if let &syn::Type::Path(ref p) = &*i.self_ty {
+                                       if let Some(trait_path) = i.trait_.as_ref() {
+                                               if let Some(tp) = import_resolver.maybe_resolve_path(&trait_path.1, None) {
+                                                       if let Some(sp) = import_resolver.maybe_resolve_path(&p.path, None) {
+                                                               match crate_types.trait_impls.entry(sp) {
+                                                                       hash_map::Entry::Occupied(mut e) => { e.get_mut().push(tp); },
+                                                                       hash_map::Entry::Vacant(e) => { e.insert(vec![tp]); },
+                                                               }
+                                                       }
+                                               }
                                        }
-                                       let trait_path = format!("{}::{}", module, t.ident);
-                                       crate_types.traits.insert(trait_path, &t);
                                }
                        },
-                       syn::Item::Type(t) => {
-                               if let syn::Visibility::Public(_) = t.vis {
-                                       match export_status(&t.attrs) {
-                                               ExportStatus::Export => {},
-                                               ExportStatus::NoExport|ExportStatus::TestOnly => continue,
-                                       }
-                                       let type_path = format!("{}::{}", module, t.ident);
-                                       let mut process_alias = true;
-                                       for tok in t.generics.params.iter() {
-                                               if let syn::GenericParam::Lifetime(_) = tok {}
-                                               else { process_alias = false; }
+                       _ => {},
+               }
+       }
+}
+
+/// Walk the FullLibraryAST, deciding how things will be mapped and adding tracking to CrateTypes.
+fn walk_ast<'a>(ast_storage: &'a FullLibraryAST, crate_types: &mut CrateTypes<'a>) {
+       for (module, astmod) in ast_storage.modules.iter() {
+               let ASTModule { ref attrs, ref items, submods: _ } = astmod;
+               assert_eq!(export_status(&attrs), ExportStatus::Export);
+               let import_resolver = ImportResolver::new(module, items);
+
+               for item in items.iter() {
+                       match item {
+                               syn::Item::Struct(s) => {
+                                       if let syn::Visibility::Public(_) = s.vis {
+                                               match export_status(&s.attrs) {
+                                                       ExportStatus::Export => {},
+                                                       ExportStatus::NoExport|ExportStatus::TestOnly => continue,
+                                               }
+                                               let struct_path = format!("{}::{}", module, s.ident);
+                                               crate_types.opaques.insert(struct_path, &s.ident);
                                        }
-                                       if process_alias {
-                                               match &*t.ty {
-                                                       syn::Type::Path(_) => {
-                                                               // If its a path with no generics, assume we don't map the aliased type and map it opaque
-                                                               crate_types.opaques.insert(type_path, &t.ident);
+                               },
+                               syn::Item::Trait(t) => {
+                                       if let syn::Visibility::Public(_) = t.vis {
+                                               match export_status(&t.attrs) {
+                                                       ExportStatus::Export => {},
+                                                       ExportStatus::NoExport|ExportStatus::TestOnly => continue,
+                                               }
+                                               let trait_path = format!("{}::{}", module, t.ident);
+                                               walk_supertraits!(t, None, (
+                                                       ("Clone", _) => {
+                                                               crate_types.clonable_types.insert("crate::".to_owned() + &trait_path);
                                                        },
-                                                       _ => {
-                                                               crate_types.type_aliases.insert(type_path, resolve_imported_refs(&import_maps, (*t.ty).clone()));
+                                                       (_, _) => {}
+                                               ) );
+                                               crate_types.traits.insert(trait_path, &t);
+                                       }
+                               },
+                               syn::Item::Type(t) => {
+                                       if let syn::Visibility::Public(_) = t.vis {
+                                               match export_status(&t.attrs) {
+                                                       ExportStatus::Export => {},
+                                                       ExportStatus::NoExport|ExportStatus::TestOnly => continue,
+                                               }
+                                               let type_path = format!("{}::{}", module, t.ident);
+                                               let mut process_alias = true;
+                                               for tok in t.generics.params.iter() {
+                                                       if let syn::GenericParam::Lifetime(_) = tok {}
+                                                       else { process_alias = false; }
+                                               }
+                                               if process_alias {
+                                                       match &*t.ty {
+                                                               syn::Type::Path(p) => {
+                                                                       // If its a path with no generics, assume we don't map the aliased type and map it opaque
+                                                                       let mut segments = syn::punctuated::Punctuated::new();
+                                                                       segments.push(syn::PathSegment {
+                                                                               ident: t.ident.clone(),
+                                                                               arguments: syn::PathArguments::None,
+                                                                       });
+                                                                       let path_obj = syn::Path { leading_colon: None, segments };
+                                                                       let args_obj = p.path.segments.last().unwrap().arguments.clone();
+                                                                       match crate_types.reverse_alias_map.entry(import_resolver.maybe_resolve_path(&p.path, None).unwrap()) {
+                                                                               hash_map::Entry::Occupied(mut e) => { e.get_mut().push((path_obj, args_obj)); },
+                                                                               hash_map::Entry::Vacant(e) => { e.insert(vec![(path_obj, args_obj)]); },
+                                                                       }
+
+                                                                       crate_types.opaques.insert(type_path.clone(), &t.ident);
+                                                               },
+                                                               _ => {
+                                                                       crate_types.type_aliases.insert(type_path, import_resolver.resolve_imported_refs((*t.ty).clone()));
+                                                               }
                                                        }
                                                }
                                        }
-                               }
-                       },
-                       syn::Item::Enum(e) if is_enum_opaque(e) => {
-                               if let syn::Visibility::Public(_) = e.vis {
-                                       match export_status(&e.attrs) {
-                                               ExportStatus::Export => {},
-                                               ExportStatus::NoExport|ExportStatus::TestOnly => continue,
+                               },
+                               syn::Item::Enum(e) if is_enum_opaque(e) => {
+                                       if let syn::Visibility::Public(_) = e.vis {
+                                               match export_status(&e.attrs) {
+                                                       ExportStatus::Export => {},
+                                                       ExportStatus::NoExport|ExportStatus::TestOnly => continue,
+                                               }
+                                               let enum_path = format!("{}::{}", module, e.ident);
+                                               crate_types.opaques.insert(enum_path, &e.ident);
                                        }
-                                       let enum_path = format!("{}::{}", module, e.ident);
-                                       crate_types.opaques.insert(enum_path, &e.ident);
-                               }
-                       },
-                       syn::Item::Enum(e) => {
-                               if let syn::Visibility::Public(_) = e.vis {
-                                       match export_status(&e.attrs) {
-                                               ExportStatus::Export => {},
-                                               ExportStatus::NoExport|ExportStatus::TestOnly => continue,
+                               },
+                               syn::Item::Enum(e) => {
+                                       if let syn::Visibility::Public(_) = e.vis {
+                                               match export_status(&e.attrs) {
+                                                       ExportStatus::Export => {},
+                                                       ExportStatus::NoExport|ExportStatus::TestOnly => continue,
+                                               }
+                                               let enum_path = format!("{}::{}", module, e.ident);
+                                               crate_types.mirrored_enums.insert(enum_path, &e);
                                        }
-                                       let enum_path = format!("{}::{}", module, e.ident);
-                                       crate_types.mirrored_enums.insert(enum_path, &e);
-                               }
-                       },
-                       _ => {},
+                               },
+                               syn::Item::Impl(i) => {
+                                       if let &syn::Type::Path(ref p) = &*i.self_ty {
+                                               if let Some(trait_path) = i.trait_.as_ref() {
+                                                       if path_matches_nongeneric(&trait_path.1, &["core", "clone", "Clone"]) {
+                                                               if let Some(full_path) = import_resolver.maybe_resolve_path(&p.path, None) {
+                                                                       crate_types.clonable_types.insert("crate::".to_owned() + &full_path);
+                                                               }
+                                                       }
+                                                       if let Some(tp) = import_resolver.maybe_resolve_path(&trait_path.1, None) {
+                                                               if let Some(sp) = import_resolver.maybe_resolve_path(&p.path, None) {
+                                                                       match crate_types.trait_impls.entry(sp) {
+                                                                               hash_map::Entry::Occupied(mut e) => { e.get_mut().push(tp); },
+                                                                               hash_map::Entry::Vacant(e) => { e.insert(vec![tp]); },
+                                                                       }
+                                                               }
+                                                       }
+                                               }
+                                       }
+                               },
+                               syn::Item::Mod(m) => walk_private_mod(format!("{}::{}", module, m.ident), m, crate_types),
+                               _ => {},
+                       }
                }
        }
 }
 
 fn main() {
        let args: Vec<String> = env::args().collect();
-       if args.len() != 7 {
-               eprintln!("Usage: source/dir target/dir source_crate_name derived_templates.rs extra/includes.h extra/cpp/includes.hpp");
+       if args.len() != 6 {
+               eprintln!("Usage: target/dir source_crate_name derived_templates.rs extra/includes.h extra/cpp/includes.hpp");
                process::exit(1);
        }
 
        let mut derived_templates = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
-               .open(&args[4]).expect("Unable to open new header file");
+               .open(&args[3]).expect("Unable to open new header file");
        let mut header_file = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
-               .open(&args[5]).expect("Unable to open new header file");
+               .open(&args[4]).expect("Unable to open new header file");
        let mut cpp_header_file = std::fs::OpenOptions::new().write(true).create(true).truncate(true)
-               .open(&args[6]).expect("Unable to open new header file");
+               .open(&args[5]).expect("Unable to open new header file");
 
-       writeln!(header_file, "#if defined(__GNUC__)\n#define MUST_USE_STRUCT __attribute__((warn_unused))").unwrap();
-       writeln!(header_file, "#else\n#define MUST_USE_STRUCT\n#endif").unwrap();
-       writeln!(header_file, "#if defined(__GNUC__)\n#define MUST_USE_RES __attribute__((warn_unused_result))").unwrap();
-       writeln!(header_file, "#else\n#define MUST_USE_RES\n#endif").unwrap();
+       writeln!(header_file, "#if defined(__GNUC__)").unwrap();
+       writeln!(header_file, "#define MUST_USE_STRUCT __attribute__((warn_unused))").unwrap();
+       writeln!(header_file, "#define MUST_USE_RES __attribute__((warn_unused_result))").unwrap();
+       writeln!(header_file, "#else").unwrap();
+       writeln!(header_file, "#define MUST_USE_STRUCT").unwrap();
+       writeln!(header_file, "#define MUST_USE_RES").unwrap();
+       writeln!(header_file, "#endif").unwrap();
+       writeln!(header_file, "#if defined(__clang__)").unwrap();
+       writeln!(header_file, "#define NONNULL_PTR _Nonnull").unwrap();
+       writeln!(header_file, "#else").unwrap();
+       writeln!(header_file, "#define NONNULL_PTR").unwrap();
+       writeln!(header_file, "#endif").unwrap();
        writeln!(cpp_header_file, "#include <string.h>\nnamespace LDK {{").unwrap();
 
        // First parse the full crate's ASTs, caching them so that we can hold references to the AST
        // objects in other datastructures:
-       let mut libast = FullLibraryAST { files: HashMap::new() };
-       load_ast(&args[1], "/lib.rs", "".to_string(), &mut libast);
+       let mut lib_src = String::new();
+       std::io::stdin().lock().read_to_string(&mut lib_src).unwrap();
+       let lib_syntax = syn::parse_file(&lib_src).expect("Unable to parse file");
+       let libast = FullLibraryAST::load_lib(lib_syntax);
 
        // ...then walk the ASTs tracking what types we will map, and how, so that we can resolve them
        // when parsing other file ASTs...
        let mut libtypes = CrateTypes { traits: HashMap::new(), opaques: HashMap::new(), mirrored_enums: HashMap::new(),
-               type_aliases: HashMap::new(), templates_defined: HashMap::default(), template_file: &mut derived_templates };
-       walk_ast(&args[1], "/lib.rs", "".to_string(), &libast, &mut libtypes);
+               type_aliases: HashMap::new(), reverse_alias_map: HashMap::new(), templates_defined: HashMap::default(),
+               template_file: &mut derived_templates,
+               clonable_types: HashSet::new(), trait_impls: HashMap::new() };
+       walk_ast(&libast, &mut libtypes);
 
        // ... finally, do the actual file conversion/mapping, writing out types as we go.
-       convert_file(&libast, &mut libtypes, &args[1], &args[2], "/lib.rs", &args[3], "", &mut header_file, &mut cpp_header_file);
+       convert_file(&libast, &mut libtypes, &args[1], &args[2], &mut header_file, &mut cpp_header_file);
 
        // For container templates which we created while walking the crate, make sure we add C++
        // mapped types so that C++ users can utilize the auto-destructors available.
index 483c1d9b9d12821b427cf8e0e143a56abb9a2400..7fc7e4cd905cff8d1cc66cd39aba44988b38c535 100644 (file)
@@ -1,8 +1,10 @@
-use std::collections::HashMap;
+use std::collections::{HashMap, HashSet};
 use std::fs::File;
 use std::io::Write;
 use std::hash;
 
+use crate::blocks::*;
+
 use proc_macro2::{TokenTree, Span};
 
 // The following utils are used purely to build our known types maps - they break down all the
@@ -33,17 +35,21 @@ pub fn get_single_remaining_path_seg<'a, I: Iterator<Item=&'a syn::PathSegment>>
        } else { None }
 }
 
-pub fn assert_single_path_seg<'a>(p: &'a syn::Path) -> &'a syn::Ident {
-       if p.leading_colon.is_some() { unimplemented!(); }
-       get_single_remaining_path_seg(&mut p.segments.iter()).unwrap()
-}
-
 pub fn single_ident_generic_path_to_ident(p: &syn::Path) -> Option<&syn::Ident> {
        if p.segments.len() == 1 {
                Some(&p.segments.iter().next().unwrap().ident)
        } else { None }
 }
 
+pub fn path_matches_nongeneric(p: &syn::Path, exp: &[&str]) -> bool {
+       if p.segments.len() != exp.len() { return false; }
+       for (seg, e) in p.segments.iter().zip(exp.iter()) {
+               if seg.arguments != syn::PathArguments::None { return false; }
+               if &format!("{}", seg.ident) != *e { return false; }
+       }
+       true
+}
+
 #[derive(Debug, PartialEq)]
 pub enum ExportStatus {
        Export,
@@ -104,6 +110,29 @@ pub fn assert_simple_bound(bound: &syn::TraitBound) {
        if let syn::TraitBoundModifier::Maybe(_) = bound.modifier { unimplemented!(); }
 }
 
+/// Returns true if the enum will be mapped as an opaue (ie struct with a pointer to the underlying
+/// type), otherwise it is mapped into a transparent, C-compatible version of itself.
+pub fn is_enum_opaque(e: &syn::ItemEnum) -> bool {
+       for var in e.variants.iter() {
+               if let syn::Fields::Named(fields) = &var.fields {
+                       for field in fields.named.iter() {
+                               match export_status(&field.attrs) {
+                                       ExportStatus::Export|ExportStatus::TestOnly => {},
+                                       ExportStatus::NoExport => return true,
+                               }
+                       }
+               } else if let syn::Fields::Unnamed(fields) = &var.fields {
+                       for field in fields.unnamed.iter() {
+                               match export_status(&field.attrs) {
+                                       ExportStatus::Export|ExportStatus::TestOnly => {},
+                                       ExportStatus::NoExport => return true,
+                               }
+                       }
+               }
+       }
+       false
+}
+
 /// A stack of sets of generic resolutions.
 ///
 /// This tracks the template parameters for a function, struct, or trait, allowing resolution into
@@ -134,6 +163,7 @@ impl<'a> GenericTypes<'a> {
 
        /// Learn the generics in generics in the current context, given a TypeResolver.
        pub fn learn_generics<'b, 'c>(&mut self, generics: &'a syn::Generics, types: &'b TypeResolver<'a, 'c>) -> bool {
+               // First learn simple generics...
                for generic in generics.params.iter() {
                        match generic {
                                syn::GenericParam::Type(type_param) => {
@@ -143,6 +173,7 @@ impl<'a> GenericTypes<'a> {
                                                        if let Some(ident) = single_ident_generic_path_to_ident(&trait_bound.path) {
                                                                match &format!("{}", ident) as &str { "Send" => continue, "Sync" => continue, _ => {} }
                                                        }
+                                                       if path_matches_nongeneric(&trait_bound.path, &["core", "clone", "Clone"]) { continue; }
 
                                                        assert_simple_bound(&trait_bound);
                                                        if let Some(mut path) = types.maybe_resolve_path(&trait_bound.path, None) {
@@ -161,6 +192,7 @@ impl<'a> GenericTypes<'a> {
                                _ => {},
                        }
                }
+               // Then find generics where we are required to pass a Deref<Target=X> and pretend its just X.
                if let Some(wh) = &generics.where_clause {
                        for pred in wh.predicates.iter() {
                                if let syn::WherePredicate::Type(t) = pred {
@@ -193,6 +225,38 @@ impl<'a> GenericTypes<'a> {
                true
        }
 
+       /// Learn the associated types from the trait in the current context.
+       pub fn learn_associated_types<'b, 'c>(&mut self, t: &'a syn::ItemTrait, types: &'b TypeResolver<'a, 'c>) {
+               for item in t.items.iter() {
+                       match item {
+                               &syn::TraitItem::Type(ref t) => {
+                                       if t.default.is_some() || t.generics.lt_token.is_some() { unimplemented!(); }
+                                       let mut bounds_iter = t.bounds.iter();
+                                       match bounds_iter.next().unwrap() {
+                                               syn::TypeParamBound::Trait(tr) => {
+                                                       assert_simple_bound(&tr);
+                                                       if let Some(mut path) = types.maybe_resolve_path(&tr.path, None) {
+                                                               if types.skip_path(&path) { continue; }
+                                                               // In general we handle Deref<Target=X> as if it were just X (and
+                                                               // implement Deref<Target=Self> for relevant types). We don't
+                                                               // bother to implement it for associated types, however, so we just
+                                                               // ignore such bounds.
+                                                               let new_ident = if path != "std::ops::Deref" {
+                                                                       path = "crate::".to_string() + &path;
+                                                                       Some(&tr.path)
+                                                               } else { None };
+                                                               self.typed_generics.last_mut().unwrap().insert(&t.ident, (path, new_ident));
+                                                       } else { unimplemented!(); }
+                                               },
+                                               _ => unimplemented!(),
+                                       }
+                                       if bounds_iter.next().is_some() { unimplemented!(); }
+                               },
+                               _ => {},
+                       }
+               }
+       }
+
        /// Attempt to resolve an Ident as a generic parameter and return the full path.
        pub fn maybe_resolve_ident<'b>(&'b self, ident: &syn::Ident) -> Option<&'b String> {
                for gen in self.typed_generics.iter().rev() {
@@ -211,6 +275,18 @@ impl<'a> GenericTypes<'a> {
                                        return Some(res);
                                }
                        }
+               } else {
+                       // Associated types are usually specified as "Self::Generic", so we check for that
+                       // explicitly here.
+                       let mut it = path.segments.iter();
+                       if path.segments.len() == 2 && format!("{}", it.next().unwrap().ident) == "Self" {
+                               let ident = &it.next().unwrap().ident;
+                               for gen in self.typed_generics.iter().rev() {
+                                       if let Some(res) = gen.get(ident).map(|(a, b)| (a, b.unwrap())) {
+                                               return Some(res);
+                                       }
+                               }
+                       }
                }
                None
        }
@@ -226,12 +302,225 @@ pub enum DeclType<'a> {
        EnumIgnored,
 }
 
+pub struct ImportResolver<'mod_lifetime, 'crate_lft: 'mod_lifetime> {
+       module_path: &'mod_lifetime str,
+       imports: HashMap<syn::Ident, (String, syn::Path)>,
+       declared: HashMap<syn::Ident, DeclType<'crate_lft>>,
+       priv_modules: HashSet<syn::Ident>,
+}
+impl<'mod_lifetime, 'crate_lft: 'mod_lifetime> ImportResolver<'mod_lifetime, 'crate_lft> {
+       fn process_use_intern(imports: &mut HashMap<syn::Ident, (String, syn::Path)>, u: &syn::UseTree, partial_path: &str, mut path: syn::punctuated::Punctuated<syn::PathSegment, syn::token::Colon2>) {
+               match u {
+                       syn::UseTree::Path(p) => {
+                               let new_path = format!("{}{}::", partial_path, p.ident);
+                               path.push(syn::PathSegment { ident: p.ident.clone(), arguments: syn::PathArguments::None });
+                               Self::process_use_intern(imports, &p.tree, &new_path, path);
+                       },
+                       syn::UseTree::Name(n) => {
+                               let full_path = format!("{}{}", partial_path, n.ident);
+                               path.push(syn::PathSegment { ident: n.ident.clone(), arguments: syn::PathArguments::None });
+                               imports.insert(n.ident.clone(), (full_path, syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path }));
+                       },
+                       syn::UseTree::Group(g) => {
+                               for i in g.items.iter() {
+                                       Self::process_use_intern(imports, i, partial_path, path.clone());
+                               }
+                       },
+                       syn::UseTree::Rename(r) => {
+                               let full_path = format!("{}{}", partial_path, r.ident);
+                               path.push(syn::PathSegment { ident: r.ident.clone(), arguments: syn::PathArguments::None });
+                               imports.insert(r.rename.clone(), (full_path, syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path }));
+                       },
+                       syn::UseTree::Glob(_) => {
+                               eprintln!("Ignoring * use for {} - this may result in resolution failures", partial_path);
+                       },
+               }
+       }
+
+       fn process_use(imports: &mut HashMap<syn::Ident, (String, syn::Path)>, u: &syn::ItemUse) {
+               if let syn::Visibility::Public(_) = u.vis {
+                       // We actually only use these for #[cfg(fuzztarget)]
+                       eprintln!("Ignoring pub(use) tree!");
+                       return;
+               }
+               if u.leading_colon.is_some() { eprintln!("Ignoring leading-colon use!"); return; }
+               Self::process_use_intern(imports, &u.tree, "", syn::punctuated::Punctuated::new());
+       }
+
+       fn insert_primitive(imports: &mut HashMap<syn::Ident, (String, syn::Path)>, id: &str) {
+               let ident = syn::Ident::new(id, Span::call_site());
+               let mut path = syn::punctuated::Punctuated::new();
+               path.push(syn::PathSegment { ident: ident.clone(), arguments: syn::PathArguments::None });
+               imports.insert(ident, (id.to_owned(), syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path }));
+       }
+
+       pub fn new(module_path: &'mod_lifetime str, contents: &'crate_lft [syn::Item]) -> Self {
+               let mut imports = HashMap::new();
+               // Add primitives to the "imports" list:
+               Self::insert_primitive(&mut imports, "bool");
+               Self::insert_primitive(&mut imports, "u64");
+               Self::insert_primitive(&mut imports, "u32");
+               Self::insert_primitive(&mut imports, "u16");
+               Self::insert_primitive(&mut imports, "u8");
+               Self::insert_primitive(&mut imports, "usize");
+               Self::insert_primitive(&mut imports, "str");
+               Self::insert_primitive(&mut imports, "String");
+
+               // These are here to allow us to print native Rust types in trait fn impls even if we don't
+               // have C mappings:
+               Self::insert_primitive(&mut imports, "Result");
+               Self::insert_primitive(&mut imports, "Vec");
+               Self::insert_primitive(&mut imports, "Option");
+
+               let mut declared = HashMap::new();
+               let mut priv_modules = HashSet::new();
+
+               for item in contents.iter() {
+                       match item {
+                               syn::Item::Use(u) => Self::process_use(&mut imports, &u),
+                               syn::Item::Struct(s) => {
+                                       if let syn::Visibility::Public(_) = s.vis {
+                                               match export_status(&s.attrs) {
+                                                       ExportStatus::Export => { declared.insert(s.ident.clone(), DeclType::StructImported); },
+                                                       ExportStatus::NoExport => { declared.insert(s.ident.clone(), DeclType::StructIgnored); },
+                                                       ExportStatus::TestOnly => continue,
+                                               }
+                                       }
+                               },
+                               syn::Item::Type(t) if export_status(&t.attrs) == ExportStatus::Export => {
+                                       if let syn::Visibility::Public(_) = t.vis {
+                                               let mut process_alias = true;
+                                               for tok in t.generics.params.iter() {
+                                                       if let syn::GenericParam::Lifetime(_) = tok {}
+                                                       else { process_alias = false; }
+                                               }
+                                               if process_alias {
+                                                       match &*t.ty {
+                                                               syn::Type::Path(_) => { declared.insert(t.ident.clone(), DeclType::StructImported); },
+                                                               _ => {},
+                                                       }
+                                               }
+                                       }
+                               },
+                               syn::Item::Enum(e) => {
+                                       if let syn::Visibility::Public(_) = e.vis {
+                                               match export_status(&e.attrs) {
+                                                       ExportStatus::Export if is_enum_opaque(e) => { declared.insert(e.ident.clone(), DeclType::EnumIgnored); },
+                                                       ExportStatus::Export => { declared.insert(e.ident.clone(), DeclType::MirroredEnum); },
+                                                       _ => continue,
+                                               }
+                                       }
+                               },
+                               syn::Item::Trait(t) if export_status(&t.attrs) == ExportStatus::Export => {
+                                       if let syn::Visibility::Public(_) = t.vis {
+                                               declared.insert(t.ident.clone(), DeclType::Trait(t));
+                                       }
+                               },
+                               syn::Item::Mod(m) => {
+                                       priv_modules.insert(m.ident.clone());
+                               },
+                               _ => {},
+                       }
+               }
+
+               Self { module_path, imports, declared, priv_modules }
+       }
+
+       pub fn get_declared_type(&self, ident: &syn::Ident) -> Option<&DeclType<'crate_lft>> {
+               self.declared.get(ident)
+       }
+
+       pub fn maybe_resolve_declared(&self, id: &syn::Ident) -> Option<&DeclType<'crate_lft>> {
+               self.declared.get(id)
+       }
+
+       pub fn maybe_resolve_ident(&self, id: &syn::Ident) -> Option<String> {
+               if let Some((imp, _)) = self.imports.get(id) {
+                       Some(imp.clone())
+               } else if self.declared.get(id).is_some() {
+                       Some(self.module_path.to_string() + "::" + &format!("{}", id))
+               } else { None }
+       }
+
+       pub fn maybe_resolve_non_ignored_ident(&self, id: &syn::Ident) -> Option<String> {
+               if let Some((imp, _)) = self.imports.get(id) {
+                       Some(imp.clone())
+               } else if let Some(decl_type) = self.declared.get(id) {
+                       match decl_type {
+                               DeclType::StructIgnored => None,
+                               _ => Some(self.module_path.to_string() + "::" + &format!("{}", id)),
+                       }
+               } else { None }
+       }
+
+       pub fn maybe_resolve_path(&self, p_arg: &syn::Path, generics: Option<&GenericTypes>) -> Option<String> {
+               let p = if let Some(gen_types) = generics {
+                       if let Some((_, synpath)) = gen_types.maybe_resolve_path(p_arg) {
+                               synpath
+                       } else { p_arg }
+               } else { p_arg };
+
+               if p.leading_colon.is_some() {
+                       Some(p.segments.iter().enumerate().map(|(idx, seg)| {
+                               format!("{}{}", if idx == 0 { "" } else { "::" }, seg.ident)
+                       }).collect())
+               } else if let Some(id) = p.get_ident() {
+                       self.maybe_resolve_ident(id)
+               } else {
+                       if p.segments.len() == 1 {
+                               let seg = p.segments.iter().next().unwrap();
+                               return self.maybe_resolve_ident(&seg.ident);
+                       }
+                       let mut seg_iter = p.segments.iter();
+                       let first_seg = seg_iter.next().unwrap();
+                       let remaining: String = seg_iter.map(|seg| {
+                               format!("::{}", seg.ident)
+                       }).collect();
+                       if let Some((imp, _)) = self.imports.get(&first_seg.ident) {
+                               if remaining != "" {
+                                       Some(imp.clone() + &remaining)
+                               } else {
+                                       Some(imp.clone())
+                               }
+                       } else if let Some(_) = self.priv_modules.get(&first_seg.ident) {
+                               Some(format!("{}::{}{}", self.module_path, first_seg.ident, remaining))
+                       } else { None }
+               }
+       }
+
+       /// Map all the Paths in a Type into absolute paths given a set of imports (generated via process_use_intern)
+       pub fn resolve_imported_refs(&self, mut ty: syn::Type) -> syn::Type {
+               match &mut ty {
+                       syn::Type::Path(p) => {
+                               if let Some(ident) = p.path.get_ident() {
+                                       if let Some((_, newpath)) = self.imports.get(ident) {
+                                               p.path = newpath.clone();
+                                       }
+                               } else { unimplemented!(); }
+                       },
+                       syn::Type::Reference(r) => {
+                               r.elem = Box::new(self.resolve_imported_refs((*r.elem).clone()));
+                       },
+                       syn::Type::Slice(s) => {
+                               s.elem = Box::new(self.resolve_imported_refs((*s.elem).clone()));
+                       },
+                       syn::Type::Tuple(t) => {
+                               for e in t.elems.iter_mut() {
+                                       *e = self.resolve_imported_refs(e.clone());
+                               }
+                       },
+                       _ => unimplemented!(),
+               }
+               ty
+       }
+}
+
 // templates_defined is walked to write the C++ header, so if we use the default hashing it get
 // reordered on each genbindings run. Instead, we use SipHasher (which defaults to 0-keys) so that
 // the sorting is stable across runs. It is deprecated, but the "replacement" doesn't actually
 // accomplish the same goals, so we just ignore it.
 #[allow(deprecated)]
-type NonRandomHash = hash::BuildHasherDefault<hash::SipHasher>;
+pub type NonRandomHash = hash::BuildHasherDefault<hash::SipHasher>;
 
 /// Top-level struct tracking everything which has been defined while walking the crate.
 pub struct CrateTypes<'a> {
@@ -244,6 +533,8 @@ pub struct CrateTypes<'a> {
        pub traits: HashMap<String, &'a syn::ItemTrait>,
        /// Aliases from paths to some other Type
        pub type_aliases: HashMap<String, syn::Type>,
+       /// Value is an alias to Key (maybe with some generics)
+       pub reverse_alias_map: HashMap<String, Vec<(syn::Path, syn::PathArguments)>>,
        /// Template continer types defined, map from mangled type name -> whether a destructor fn
        /// exists.
        ///
@@ -252,6 +543,10 @@ pub struct CrateTypes<'a> {
        /// The output file for any created template container types, written to as we find new
        /// template containers which need to be defined.
        pub template_file: &'a mut File,
+       /// Set of containers which are clonable
+       pub clonable_types: HashSet<String>,
+       /// Key impls Value
+       pub trait_impls: HashMap<String, Vec<String>>,
 }
 
 /// A struct which tracks resolving rust types into C-mapped equivalents, exists for one specific
@@ -259,10 +554,8 @@ pub struct CrateTypes<'a> {
 pub struct TypeResolver<'mod_lifetime, 'crate_lft: 'mod_lifetime> {
        pub orig_crate: &'mod_lifetime str,
        pub module_path: &'mod_lifetime str,
-       imports: HashMap<syn::Ident, String>,
-       // ident -> is-mirrored-enum
-       declared: HashMap<syn::Ident, DeclType<'crate_lft>>,
        pub crate_types: &'mod_lifetime mut CrateTypes<'crate_lft>,
+       types: ImportResolver<'mod_lifetime, 'crate_lft>,
 }
 
 /// Returned by write_empty_rust_val_check_suffix to indicate what type of dereferencing needs to
@@ -277,24 +570,8 @@ enum EmptyValExpectedTy {
 }
 
 impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
-       pub fn new(orig_crate: &'a str, module_path: &'a str, crate_types: &'a mut CrateTypes<'c>) -> Self {
-               let mut imports = HashMap::new();
-               // Add primitives to the "imports" list:
-               imports.insert(syn::Ident::new("bool", Span::call_site()), "bool".to_string());
-               imports.insert(syn::Ident::new("u64", Span::call_site()), "u64".to_string());
-               imports.insert(syn::Ident::new("u32", Span::call_site()), "u32".to_string());
-               imports.insert(syn::Ident::new("u16", Span::call_site()), "u16".to_string());
-               imports.insert(syn::Ident::new("u8", Span::call_site()), "u8".to_string());
-               imports.insert(syn::Ident::new("usize", Span::call_site()), "usize".to_string());
-               imports.insert(syn::Ident::new("str", Span::call_site()), "str".to_string());
-               imports.insert(syn::Ident::new("String", Span::call_site()), "String".to_string());
-
-               // These are here to allow us to print native Rust types in trait fn impls even if we don't
-               // have C mappings:
-               imports.insert(syn::Ident::new("Result", Span::call_site()), "Result".to_string());
-               imports.insert(syn::Ident::new("Vec", Span::call_site()), "Vec".to_string());
-               imports.insert(syn::Ident::new("Option", Span::call_site()), "Option".to_string());
-               Self { orig_crate, module_path, imports, declared: HashMap::new(), crate_types }
+       pub fn new(orig_crate: &'a str, module_path: &'a str, types: ImportResolver<'a, 'c>, crate_types: &'a mut CrateTypes<'c>) -> Self {
+               Self { orig_crate, module_path, types, crate_types }
        }
 
        // *************************************************
@@ -310,7 +587,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
        /// Returns true we if can just skip passing this to C entirely
        fn no_arg_path_to_rust(&self, full_path: &str) -> &str {
                if full_path == "bitcoin::secp256k1::Secp256k1" {
-                       "&bitcoin::secp256k1::Secp256k1::new()"
+                       "secp256k1::SECP256K1"
                } else { unimplemented!(); }
        }
 
@@ -327,9 +604,19 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                        _ => false,
                }
        }
+       pub fn is_clonable(&self, ty: &str) -> bool {
+               if self.crate_types.clonable_types.contains(ty) { return true; }
+               if self.is_primitive(ty) { return true; }
+               match ty {
+                       "()" => true,
+                       "crate::c_types::Signature" => true,
+                       "crate::c_types::TxOut" => true,
+                       _ => false,
+               }
+       }
        /// Gets the C-mapped type for types which are outside of the crate, or which are manually
        /// ignored by for some reason need mapping anyway.
-       fn c_type_from_path<'b>(&self, full_path: &'b str, is_ref: bool, ptr_for_ref: bool) -> Option<&'b str> {
+       fn c_type_from_path<'b>(&self, full_path: &'b str, is_ref: bool, _ptr_for_ref: bool) -> Option<&'b str> {
                if self.is_primitive(full_path) {
                        return Some(full_path);
                }
@@ -360,10 +647,9 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                        "bitcoin::secp256k1::Error" if !is_ref => Some("crate::c_types::Secp256k1Error"),
                        "bitcoin::blockdata::script::Script" if is_ref => Some("crate::c_types::u8slice"),
                        "bitcoin::blockdata::script::Script" if !is_ref => Some("crate::c_types::derived::CVec_u8Z"),
-                       "bitcoin::blockdata::transaction::OutPoint" if is_ref => Some("crate::chain::transaction::OutPoint"),
+                       "bitcoin::blockdata::transaction::OutPoint" => Some("crate::chain::transaction::OutPoint"),
                        "bitcoin::blockdata::transaction::Transaction" => Some("crate::c_types::Transaction"),
                        "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some("crate::c_types::TxOut"),
-                       "bitcoin::OutPoint" => Some("crate::chain::transaction::OutPoint"),
                        "bitcoin::network::constants::Network" => Some("crate::bitcoin::network::Network"),
                        "bitcoin::blockdata::block::BlockHeader" if is_ref  => Some("*const [u8; 80]"),
                        "bitcoin::blockdata::block::Block" if is_ref  => Some("crate::c_types::u8slice"),
@@ -373,6 +659,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                        "bitcoin::hash_types::Txid" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
                        "bitcoin::hash_types::BlockHash" if is_ref  => Some("*const [u8; 32]"),
                        "bitcoin::hash_types::BlockHash" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
+                       "bitcoin::secp256k1::Message" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
                        "ln::channelmanager::PaymentHash" if is_ref => Some("*const [u8; 32]"),
                        "ln::channelmanager::PaymentHash" if !is_ref => Some("crate::c_types::ThirtyTwoBytes"),
                        "ln::channelmanager::PaymentPreimage" if is_ref => Some("*const [u8; 32]"),
@@ -383,14 +670,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                        // Override the default since Records contain an fmt with a lifetime:
                        "util::logger::Record" => Some("*const std::os::raw::c_char"),
 
-                       // List of structs we map that aren't detected:
-                       "ln::features::InitFeatures" if is_ref && ptr_for_ref => Some("crate::ln::features::InitFeatures"),
-                       "ln::features::InitFeatures" if is_ref => Some("*const crate::ln::features::InitFeatures"),
-                       "ln::features::InitFeatures" => Some("crate::ln::features::InitFeatures"),
-                       _ => {
-                               eprintln!("    Type {} (ref: {}) unresolvable in C", full_path, is_ref);
-                               None
-                       },
+                       _ => None,
                }
        }
 
@@ -449,16 +729,10 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                        "ln::channelmanager::PaymentPreimage" if is_ref => Some("&::lightning::ln::channelmanager::PaymentPreimage(unsafe { *"),
                        "ln::channelmanager::PaymentSecret" => Some("::lightning::ln::channelmanager::PaymentSecret("),
 
-                       // List of structs we map (possibly during processing of other files):
-                       "ln::features::InitFeatures" if !is_ref => Some("*unsafe { Box::from_raw("),
-
                        // List of traits we map (possibly during processing of other files):
                        "crate::util::logger::Logger" => Some(""),
 
-                       _ => {
-                               eprintln!("    Type {} unconvertable from C", full_path);
-                               None
-                       },
+                       _ => None,
                }.map(|s| s.to_owned())
        }
        fn from_c_conversion_suffix_from_path<'b>(&self, full_path: &str, is_ref: bool) -> Option<String> {
@@ -507,17 +781,10 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                        "ln::channelmanager::PaymentPreimage" if is_ref => Some(" })"),
                        "ln::channelmanager::PaymentSecret" => Some(".data)"),
 
-                       // List of structs we map (possibly during processing of other files):
-                       "ln::features::InitFeatures" if is_ref => Some(".inner) }"),
-                       "ln::features::InitFeatures" if !is_ref => Some(".take_ptr()) }"),
-
                        // List of traits we map (possibly during processing of other files):
                        "crate::util::logger::Logger" => Some(""),
 
-                       _ => {
-                               eprintln!("    Type {} unconvertable from C", full_path);
-                               None
-                       },
+                       _ => None,
                }.map(|s| s.to_owned())
        }
 
@@ -541,7 +808,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                        _ => None,
                }.map(|s| s.to_owned())
        }
-       fn to_c_conversion_inline_prefix_from_path(&self, full_path: &str, is_ref: bool, ptr_for_ref: bool) -> Option<String> {
+       fn to_c_conversion_inline_prefix_from_path(&self, full_path: &str, is_ref: bool, _ptr_for_ref: bool) -> Option<String> {
                if self.is_primitive(full_path) {
                        return Some("".to_owned());
                }
@@ -573,6 +840,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                        "bitcoin::blockdata::script::Script" if is_ref => Some("crate::c_types::u8slice::from_slice(&"),
                        "bitcoin::blockdata::script::Script" if !is_ref => Some(""),
                        "bitcoin::blockdata::transaction::Transaction" => Some("crate::c_types::Transaction::from_vec(local_"),
+                       "bitcoin::blockdata::transaction::OutPoint" => Some("crate::c_types::bitcoin_to_C_outpoint("),
                        "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some("crate::c_types::TxOut::from_rust("),
                        "bitcoin::blockdata::block::BlockHeader" if is_ref => Some("&local_"),
                        "bitcoin::blockdata::block::Block" if is_ref => Some("crate::c_types::u8slice::from_slice(&local_"),
@@ -583,6 +851,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                        "bitcoin::hash_types::Txid" if is_ref => Some(""),
                        "bitcoin::hash_types::BlockHash" if is_ref => Some(""),
                        "bitcoin::hash_types::BlockHash" => Some("crate::c_types::ThirtyTwoBytes { data: "),
+                       "bitcoin::secp256k1::Message" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
                        "ln::channelmanager::PaymentHash" if is_ref => Some("&"),
                        "ln::channelmanager::PaymentHash" if !is_ref => Some("crate::c_types::ThirtyTwoBytes { data: "),
                        "ln::channelmanager::PaymentPreimage" if is_ref => Some("&"),
@@ -592,18 +861,10 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                        // Override the default since Records contain an fmt with a lifetime:
                        "util::logger::Record" => Some("local_"),
 
-                       // List of structs we map (possibly during processing of other files):
-                       "ln::features::InitFeatures" if is_ref && ptr_for_ref => Some("crate::ln::features::InitFeatures { inner: &mut "),
-                       "ln::features::InitFeatures" if is_ref => Some("Box::into_raw(Box::new(crate::ln::features::InitFeatures { inner: &mut "),
-                       "ln::features::InitFeatures" if !is_ref => Some("crate::ln::features::InitFeatures { inner: Box::into_raw(Box::new("),
-
-                       _ => {
-                               eprintln!("    Type {} (is_ref: {}) unconvertable to C", full_path, is_ref);
-                               None
-                       },
+                       _ => None,
                }.map(|s| s.to_owned())
        }
-       fn to_c_conversion_inline_suffix_from_path(&self, full_path: &str, is_ref: bool, ptr_for_ref: bool) -> Option<String> {
+       fn to_c_conversion_inline_suffix_from_path(&self, full_path: &str, is_ref: bool, _ptr_for_ref: bool) -> Option<String> {
                if self.is_primitive(full_path) {
                        return Some("".to_owned());
                }
@@ -636,6 +897,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                        "bitcoin::blockdata::script::Script" if is_ref => Some("[..])"),
                        "bitcoin::blockdata::script::Script" if !is_ref => Some(".into_bytes().into()"),
                        "bitcoin::blockdata::transaction::Transaction" => Some(")"),
+                       "bitcoin::blockdata::transaction::OutPoint" => Some(")"),
                        "bitcoin::blockdata::transaction::TxOut" if !is_ref => Some(")"),
                        "bitcoin::blockdata::block::BlockHeader" if is_ref => Some(""),
                        "bitcoin::blockdata::block::Block" if is_ref => Some(")"),
@@ -646,6 +908,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                        "bitcoin::hash_types::Txid" if is_ref => Some(".as_inner()"),
                        "bitcoin::hash_types::BlockHash" if is_ref => Some(".as_inner()"),
                        "bitcoin::hash_types::BlockHash" => Some(".into_inner() }"),
+                       "bitcoin::secp256k1::Message" if !is_ref => Some(".as_ref().clone() }"),
                        "ln::channelmanager::PaymentHash" if is_ref => Some(".0"),
                        "ln::channelmanager::PaymentHash" => Some(".0 }"),
                        "ln::channelmanager::PaymentPreimage" if is_ref => Some(".0"),
@@ -655,15 +918,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                        // Override the default since Records contain an fmt with a lifetime:
                        "util::logger::Record" => Some(".as_ptr()"),
 
-                       // List of structs we map (possibly during processing of other files):
-                       "ln::features::InitFeatures" if is_ref && ptr_for_ref => Some(", is_owned: false }"),
-                       "ln::features::InitFeatures" if is_ref => Some(", is_owned: false }))"),
-                       "ln::features::InitFeatures" => Some(")), is_owned: true }"),
-
-                       _ => {
-                               eprintln!("    Type {} unconvertable to C", full_path);
-                               None
-                       },
+                       _ => None,
                }.map(|s| s.to_owned())
        }
 
@@ -682,7 +937,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
 
        /// Returns the module path in the generated mapping crate to the containers which we generate
        /// when writing to CrateTypes::template_file.
-       fn generated_container_path() -> &'static str {
+       pub fn generated_container_path() -> &'static str {
                "crate::c_types::derived"
        }
        /// Returns the module path in the generated mapping crate to the container templates, which
@@ -708,11 +963,11 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                        "Result" if !is_ref => {
                                Some(("match ",
                                                vec![(" { Ok(mut o) => crate::c_types::CResultTempl::ok(".to_string(), "o".to_string()),
-                                                       ("), Err(mut e) => crate::c_types::CResultTempl::err(".to_string(), "e".to_string())],
-                                               ") }"))
+                                                       (").into(), Err(mut e) => crate::c_types::CResultTempl::err(".to_string(), "e".to_string())],
+                                               ").into() }"))
                        },
                        "Vec" if !is_ref => {
-                               Some(("Vec::new(); for item in ", vec![(format!(".drain(..) {{ local_{}.push(", var_name), "item".to_string())], "); }"))
+                               Some(("Vec::new(); for mut item in ", vec![(format!(".drain(..) {{ local_{}.push(", var_name), "item".to_string())], "); }"))
                        },
                        "Slice" => {
                                Some(("Vec::new(); for item in ", vec![(format!(".iter() {{ local_{}.push(", var_name), "**item".to_string())], "); }"))
@@ -753,8 +1008,8 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                match full_path {
                        "Result" if !is_ref => {
                                Some(("match ",
-                                               vec![(".result_ok { true => Ok(".to_string(), format!("(*unsafe {{ Box::from_raw({}.contents.result.take_ptr()) }})", var_name)),
-                                                    ("), false => Err(".to_string(), format!("(*unsafe {{ Box::from_raw({}.contents.err.take_ptr()) }})", var_name))],
+                                               vec![(".result_ok { true => Ok(".to_string(), format!("(*unsafe {{ Box::from_raw(<*mut _>::take_ptr(&mut {}.contents.result)) }})", var_access)),
+                                                    ("), false => Err(".to_string(), format!("(*unsafe {{ Box::from_raw(<*mut _>::take_ptr(&mut {}.contents.err)) }})", var_access))],
                                                ")}"))
                        },
                        "Vec"|"Slice" if !is_ref => {
@@ -767,9 +1022,9 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                                if let Some(syn::Type::Path(p)) = single_contained {
                                        if self.c_type_has_inner_from_path(&self.resolve_path(&p.path, generics)) {
                                                if is_ref {
-                                                       return Some(("if ", vec![(".inner.is_null() { None } else { Some((*".to_string(), format!("{}", var_name))], ").clone()) }"))
+                                                       return Some(("if ", vec![(".inner.is_null() { None } else { Some((*".to_string(), format!("{}", var_access))], ").clone()) }"))
                                                } else {
-                                                       return Some(("if ", vec![(".inner.is_null() { None } else { Some(".to_string(), format!("{}", var_name))], ") }"));
+                                                       return Some(("if ", vec![(".inner.is_null() { None } else { Some(".to_string(), format!("{}", var_access))], ") }"));
                                                }
                                        }
                                }
@@ -802,127 +1057,24 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
        // *** Type definition during main.rs processing ***
        // *************************************************
 
-       fn process_use_intern<W: std::io::Write>(&mut self, w: &mut W, u: &syn::UseTree, partial_path: &str) {
-               match u {
-                       syn::UseTree::Path(p) => {
-                               let new_path = format!("{}::{}", partial_path, p.ident);
-                               self.process_use_intern(w, &p.tree, &new_path);
-                       },
-                       syn::UseTree::Name(n) => {
-                               let full_path = format!("{}::{}", partial_path, n.ident);
-                               self.imports.insert(n.ident.clone(), full_path);
-                       },
-                       syn::UseTree::Group(g) => {
-                               for i in g.items.iter() {
-                                       self.process_use_intern(w, i, partial_path);
-                               }
-                       },
-                       syn::UseTree::Rename(r) => {
-                               let full_path = format!("{}::{}", partial_path, r.ident);
-                               self.imports.insert(r.rename.clone(), full_path);
-                       },
-                       syn::UseTree::Glob(_) => {
-                               eprintln!("Ignoring * use for {} - this may result in resolution failures", partial_path);
-                       },
-               }
-       }
-       pub fn process_use<W: std::io::Write>(&mut self, w: &mut W, u: &syn::ItemUse) {
-               if let syn::Visibility::Public(_) = u.vis {
-                       // We actually only use these for #[cfg(fuzztarget)]
-                       eprintln!("Ignoring pub(use) tree!");
-                       return;
-               }
-               match &u.tree {
-                       syn::UseTree::Path(p) => {
-                               let new_path = format!("{}", p.ident);
-                               self.process_use_intern(w, &p.tree, &new_path);
-                       },
-                       syn::UseTree::Name(n) => {
-                               let full_path = format!("{}", n.ident);
-                               self.imports.insert(n.ident.clone(), full_path);
-                       },
-                       _ => unimplemented!(),
-               }
-               if u.leading_colon.is_some() { unimplemented!() }
-       }
-
-       pub fn mirrored_enum_declared(&mut self, ident: &syn::Ident) {
-               eprintln!("{} mirrored", ident);
-               self.declared.insert(ident.clone(), DeclType::MirroredEnum);
-       }
-       pub fn enum_ignored(&mut self, ident: &'c syn::Ident) {
-               self.declared.insert(ident.clone(), DeclType::EnumIgnored);
-       }
-       pub fn struct_imported(&mut self, ident: &'c syn::Ident, named: String) {
-               eprintln!("Imported {} as {}", ident, named);
-               self.declared.insert(ident.clone(), DeclType::StructImported);
-       }
-       pub fn struct_ignored(&mut self, ident: &syn::Ident) {
-               eprintln!("Not importing {}", ident);
-               self.declared.insert(ident.clone(), DeclType::StructIgnored);
-       }
-       pub fn trait_declared(&mut self, ident: &syn::Ident, t: &'c syn::ItemTrait) {
-               eprintln!("Trait {} created", ident);
-               self.declared.insert(ident.clone(), DeclType::Trait(t));
-       }
        pub fn get_declared_type(&'a self, ident: &syn::Ident) -> Option<&'a DeclType<'c>> {
-               self.declared.get(ident)
+               self.types.get_declared_type(ident)
        }
        /// Returns true if the object at the given path is mapped as X { inner: *mut origX, .. }.
-       fn c_type_has_inner_from_path(&self, full_path: &str) -> bool{
+       pub fn c_type_has_inner_from_path(&self, full_path: &str) -> bool{
                self.crate_types.opaques.get(full_path).is_some()
        }
 
        pub fn maybe_resolve_ident(&self, id: &syn::Ident) -> Option<String> {
-               if let Some(imp) = self.imports.get(id) {
-                       Some(imp.clone())
-               } else if self.declared.get(id).is_some() {
-                       Some(self.module_path.to_string() + "::" + &format!("{}", id))
-               } else { None }
+               self.types.maybe_resolve_ident(id)
        }
 
        pub fn maybe_resolve_non_ignored_ident(&self, id: &syn::Ident) -> Option<String> {
-               if let Some(imp) = self.imports.get(id) {
-                       Some(imp.clone())
-               } else if let Some(decl_type) = self.declared.get(id) {
-                       match decl_type {
-                               DeclType::StructIgnored => None,
-                               _ => Some(self.module_path.to_string() + "::" + &format!("{}", id)),
-                       }
-               } else { None }
+               self.types.maybe_resolve_non_ignored_ident(id)
        }
 
        pub fn maybe_resolve_path(&self, p_arg: &syn::Path, generics: Option<&GenericTypes>) -> Option<String> {
-               let p = if let Some(gen_types) = generics {
-                       if let Some((_, synpath)) = gen_types.maybe_resolve_path(p_arg) {
-                               synpath
-                       } else { p_arg }
-               } else { p_arg };
-
-               if p.leading_colon.is_some() {
-                       Some(p.segments.iter().enumerate().map(|(idx, seg)| {
-                               format!("{}{}", if idx == 0 { "" } else { "::" }, seg.ident)
-                       }).collect())
-               } else if let Some(id) = p.get_ident() {
-                       self.maybe_resolve_ident(id)
-               } else {
-                       if p.segments.len() == 1 {
-                               let seg = p.segments.iter().next().unwrap();
-                               return self.maybe_resolve_ident(&seg.ident);
-                       }
-                       let mut seg_iter = p.segments.iter();
-                       let first_seg = seg_iter.next().unwrap();
-                       let remaining: String = seg_iter.map(|seg| {
-                               format!("::{}", seg.ident)
-                       }).collect();
-                       if let Some(imp) = self.imports.get(&first_seg.ident) {
-                               if remaining != "" {
-                                       Some(imp.clone() + &remaining)
-                               } else {
-                                       Some(imp.clone())
-                               }
-                       } else { None }
-               }
+               self.types.maybe_resolve_path(p_arg, generics)
        }
        pub fn resolve_path(&self, p: &syn::Path, generics: Option<&GenericTypes>) -> String {
                self.maybe_resolve_path(p, generics).unwrap()
@@ -1016,7 +1168,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
        pub fn write_rust_type<W: std::io::Write>(&self, w: &mut W, generics: Option<&GenericTypes>, t: &syn::Type) {
                match t {
                        syn::Type::Path(p) => {
-                               if p.qself.is_some() || p.path.leading_colon.is_some() {
+                               if p.qself.is_some() {
                                        unimplemented!();
                                }
                                self.write_rust_path(w, generics, &p.path);
@@ -1209,17 +1361,13 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                                        decl_lookup(w, &DeclType::StructImported, &resolved_path, is_ref, is_mut);
                                } else if self.crate_types.mirrored_enums.get(&resolved_path).is_some() {
                                        decl_lookup(w, &DeclType::MirroredEnum, &resolved_path, is_ref, is_mut);
+                               } else if let Some(t) = self.crate_types.traits.get(&resolved_path) {
+                                       decl_lookup(w, &DeclType::Trait(t), &resolved_path, is_ref, is_mut);
                                } else if let Some(ident) = single_ident_generic_path_to_ident(&p.path) {
-                                       if let Some(t) = self.crate_types.traits.get(&resolved_path) {
-                                               decl_lookup(w, &DeclType::Trait(t), &resolved_path, is_ref, is_mut);
-                                               return;
-                                       } else if let Some(_) = self.imports.get(ident) {
-                                               // crate_types lookup has to have succeeded:
-                                               panic!("Failed to print inline conversion for {}", ident);
-                                       } else if let Some(decl_type) = self.declared.get(ident) {
+                                       if let Some(decl_type) = self.types.maybe_resolve_declared(ident) {
                                                decl_lookup(w, decl_type, &self.maybe_resolve_ident(ident).unwrap(), is_ref, is_mut);
                                        } else { unimplemented!(); }
-                               }
+                               } else { unimplemented!(); }
                        },
                        syn::Type::Array(a) => {
                                // We assume all arrays contain only [int_literal; X]s.
@@ -1302,6 +1450,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                                                DeclType::EnumIgnored|DeclType::StructImported if !is_ref =>
                                                        write!(w, "crate::{} {{ inner: Box::into_raw(Box::new(", decl_path).unwrap(),
                                                DeclType::Trait(_) if is_ref => write!(w, "&").unwrap(),
+                                               DeclType::Trait(_) if !is_ref => {},
                                                _ => panic!("{:?}", decl_path),
                                        }
                                });
@@ -1324,6 +1473,13 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                                                write!(w, ", is_owned: true }}").unwrap(),
                                        DeclType::EnumIgnored|DeclType::StructImported if !is_ref => write!(w, ")), is_owned: true }}").unwrap(),
                                        DeclType::Trait(_) if is_ref => {},
+                                       DeclType::Trait(_) => {
+                                               // This is used when we're converting a concrete Rust type into a C trait
+                                               // for use when a Rust trait method returns an associated type.
+                                               // Because all of our C traits implement From<RustTypesImplementingTraits>
+                                               // we can just call .into() here and be done.
+                                               write!(w, ".into()").unwrap()
+                                       },
                                        _ => unimplemented!(),
                                });
        }
@@ -1358,7 +1514,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                                |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
                                        DeclType::StructImported if is_ref && ptr_for_ref => write!(w, ").inner }}").unwrap(),
                                        DeclType::StructImported if is_ref => write!(w, ".inner }}").unwrap(),
-                                       DeclType::StructImported if !is_ref => write!(w, ".take_ptr()) }}").unwrap(),
+                                       DeclType::StructImported if !is_ref => write!(w, ".take_inner()) }}").unwrap(),
                                        DeclType::MirroredEnum if is_ref => write!(w, ".to_native()").unwrap(),
                                        DeclType::MirroredEnum => write!(w, ".into_native()").unwrap(),
                                        DeclType::Trait(_) => {},
@@ -1533,7 +1689,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                                        if let Some((prefix, suffix)) = path_lookup(&resolved_path, is_ref) {
                                                write!(w, "let mut local_{} = {}{}{};", ident, prefix, var, suffix).unwrap();
                                                true
-                                       } else if self.declared.get(ty_ident).is_some() {
+                                       } else if self.types.maybe_resolve_declared(ty_ident).is_some() {
                                                false
                                        } else { false }
                                } else { false }
@@ -1668,155 +1824,96 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
        // *** C Container Type Equivalent and alias Printing ***
        // ******************************************************
 
-       fn write_template_constructor<W: std::io::Write>(&mut self, w: &mut W, container_type: &str, mangled_container: &str, args: &Vec<&syn::Type>, generics: Option<&GenericTypes>, is_ref: bool) {
-               if container_type == "Result" {
-                       assert_eq!(args.len(), 2);
-                       macro_rules! write_fn {
-                               ($call: expr) => { {
-                                       writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_{}() -> {} {{", mangled_container, $call, mangled_container).unwrap();
-                                       writeln!(w, "\t{}::CResultTempl::{}(0)\n}}\n", Self::container_templ_path(), $call).unwrap();
-                               } }
-                       }
-                       macro_rules! write_alias {
-                               ($call: expr, $item: expr) => { {
-                                       write!(w, "#[no_mangle]\npub static {}_{}: extern \"C\" fn (", mangled_container, $call).unwrap();
-                                       if let syn::Type::Path(syn::TypePath { path, .. }) = $item {
-                                               let resolved = self.resolve_path(path, generics);
-                                               if self.is_known_container(&resolved, is_ref) || self.is_transparent_container(&resolved, is_ref) {
-                                                       self.write_c_mangled_container_path_intern(w, Self::path_to_generic_args(path), generics,
-                                                               &format!("{}", single_ident_generic_path_to_ident(path).unwrap()), is_ref, false, false, false);
-                                               } else {
-                                                       self.write_template_generics(w, &mut [$item].iter().map(|t| *t), is_ref, true);
-                                               }
-                                       } else if let syn::Type::Tuple(syn::TypeTuple { elems, .. }) = $item {
-                                               self.write_c_mangled_container_path_intern(w, elems.iter().collect(), generics,
-                                                       &format!("{}Tuple", elems.len()), is_ref, false, false, false);
-                                       } else { unimplemented!(); }
-                                       write!(w, ") -> {} =\n\t{}::CResultTempl::<", mangled_container, Self::container_templ_path()).unwrap();
-                                       self.write_template_generics(w, &mut args.iter().map(|t| *t), is_ref, true);
-                                       writeln!(w, ">::{};\n", $call).unwrap();
-                               } }
-                       }
-                       match args[0] {
-                               syn::Type::Tuple(t) if t.elems.is_empty() => write_fn!("ok"),
-                               _ => write_alias!("ok", args[0]),
-                       }
-                       match args[1] {
-                               syn::Type::Tuple(t) if t.elems.is_empty() => write_fn!("err"),
-                               _ => write_alias!("err", args[1]),
-                       }
-               } else if container_type.ends_with("Tuple") {
-                       write!(w, "#[no_mangle]\npub extern \"C\" fn {}_new(", mangled_container).unwrap();
-                       for (idx, gen) in args.iter().enumerate() {
-                               write!(w, "{}{}: ", if idx != 0 { ", " } else { "" }, ('a' as u8 + idx as u8) as char).unwrap();
-                               assert!(self.write_c_type_intern(w, gen, None, false, false, false));
+       fn write_template_generics<'b, W: std::io::Write>(&mut self, w: &mut W, args: &mut dyn Iterator<Item=&'b syn::Type>, generics: Option<&GenericTypes>, is_ref: bool) -> bool {
+               assert!(!is_ref); // We don't currently support outer reference types
+               for (idx, t) in args.enumerate() {
+                       if idx != 0 {
+                               write!(w, ", ").unwrap();
                        }
-                       writeln!(w, ") -> {} {{", mangled_container).unwrap();
-                       write!(w, "\t{} {{ ", mangled_container).unwrap();
-                       for idx in 0..args.len() {
-                               write!(w, "{}, ", ('a' as u8 + idx as u8) as char).unwrap();
+                       if let syn::Type::Reference(r_arg) = t {
+                               if !self.write_c_type_intern(w, &*r_arg.elem, generics, false, false, false) { return false; }
+
+                               // While write_c_type_intern, above is correct, we don't want to blindly convert a
+                               // reference to something stupid, so check that the container is either opaque or a
+                               // predefined type (currently only Transaction).
+                               if let syn::Type::Path(p_arg) = &*r_arg.elem {
+                                       let resolved = self.resolve_path(&p_arg.path, generics);
+                                       assert!(self.crate_types.opaques.get(&resolved).is_some() ||
+                                                       self.c_type_from_path(&resolved, true, true).is_some(), "Template generics should be opaque or have a predefined mapping");
+                               } else { unimplemented!(); }
+                       } else {
+                               if !self.write_c_type_intern(w, t, generics, false, false, false) { return false; }
                        }
-                       writeln!(w, "}}\n}}\n").unwrap();
-               } else {
-                       writeln!(w, "").unwrap();
                }
+               true
        }
+       fn check_create_container(&mut self, mangled_container: String, container_type: &str, args: Vec<&syn::Type>, generics: Option<&GenericTypes>, is_ref: bool) -> bool {
+               if !self.crate_types.templates_defined.get(&mangled_container).is_some() {
+                       let mut created_container: Vec<u8> = Vec::new();
 
-       fn write_template_generics<'b, W: std::io::Write>(&self, w: &mut W, args: &mut dyn Iterator<Item=&'b syn::Type>, is_ref: bool, in_crate: bool) {
-               for (idx, t) in args.enumerate() {
-                       if idx != 0 {
-                               write!(w, ", ").unwrap();
-                       }
-                       if let syn::Type::Tuple(tup) = t {
-                               if tup.elems.is_empty() {
-                                       write!(w, "u8").unwrap();
-                               } else {
-                                       write!(w, "{}::C{}TupleTempl<", Self::container_templ_path(), tup.elems.len()).unwrap();
-                                       self.write_template_generics(w, &mut tup.elems.iter(), is_ref, in_crate);
-                                       write!(w, ">").unwrap();
-                               }
-                       } else if let syn::Type::Path(p_arg) = t {
-                               let resolved_generic = self.resolve_path(&p_arg.path, None);
-                               if self.is_primitive(&resolved_generic) {
-                                       write!(w, "{}", resolved_generic).unwrap();
-                               } else if let Some(c_type) = self.c_type_from_path(&resolved_generic, is_ref, false) {
-                                       if self.is_known_container(&resolved_generic, is_ref) {
-                                                       write!(w, "{}::C{}Templ<", Self::container_templ_path(), single_ident_generic_path_to_ident(&p_arg.path).unwrap()).unwrap();
-                                               assert_eq!(p_arg.path.segments.len(), 1);
-                                               if let syn::PathArguments::AngleBracketed(args) = &p_arg.path.segments.iter().next().unwrap().arguments {
-                                                       self.write_template_generics(w, &mut args.args.iter().map(|gen|
-                                                               if let syn::GenericArgument::Type(t) = gen { t } else { unimplemented!() }),
-                                                               is_ref, in_crate);
-                                               } else { unimplemented!(); }
-                                               write!(w, ">").unwrap();
-                                       } else if resolved_generic == "Option" {
-                                               if let syn::PathArguments::AngleBracketed(args) = &p_arg.path.segments.iter().next().unwrap().arguments {
-                                                       self.write_template_generics(w, &mut args.args.iter().map(|gen|
-                                                               if let syn::GenericArgument::Type(t) = gen { t } else { unimplemented!() }),
-                                                               is_ref, in_crate);
-                                               } else { unimplemented!(); }
-                                       } else if in_crate {
-                                               write!(w, "{}", c_type).unwrap();
+                       if container_type == "Result" {
+                               let mut a_ty: Vec<u8> = Vec::new();
+                               if let syn::Type::Tuple(tup) = args.iter().next().unwrap() {
+                                       if tup.elems.is_empty() {
+                                               write!(&mut a_ty, "()").unwrap();
                                        } else {
-                                               self.write_rust_type(w, None, &t);
+                                               if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t).take(1), generics, is_ref) { return false; }
                                        }
                                } else {
-                                       // If we just write out resolved_generic, it may mostly work, however for
-                                       // original types which are generic, we need the template args. We could
-                                       // figure them out and write them out, too, but its much easier to just
-                                       // reference the native{} type alias which exists at least for opaque types.
-                                       if in_crate {
-                                               write!(w, "crate::{}", resolved_generic).unwrap();
-                                       } else {
-                                               let path_name: Vec<&str> = resolved_generic.rsplitn(2, "::").collect();
-                                               if path_name.len() > 1 {
-                                                       write!(w, "crate::{}::native{}", path_name[1], path_name[0]).unwrap();
-                                               } else {
-                                                       write!(w, "crate::native{}", path_name[0]).unwrap();
-                                               }
-                                       }
+                                       if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t).take(1), generics, is_ref) { return false; }
                                }
-                       } else if let syn::Type::Reference(r_arg) = t {
-                               if let syn::Type::Path(p_arg) = &*r_arg.elem {
-                                       let resolved = self.resolve_path(&p_arg.path, None);
-                                       if self.crate_types.opaques.get(&resolved).is_some() {
-                                               write!(w, "crate::{}", resolved).unwrap();
+
+                               let mut b_ty: Vec<u8> = Vec::new();
+                               if let syn::Type::Tuple(tup) = args.iter().skip(1).next().unwrap() {
+                                       if tup.elems.is_empty() {
+                                               write!(&mut b_ty, "()").unwrap();
                                        } else {
-                                               let cty = self.c_type_from_path(&resolved, true, true).expect("Template generics should be opaque or have a predefined mapping");
-                                               w.write(cty.as_bytes()).unwrap();
+                                               if !self.write_template_generics(&mut b_ty, &mut args.iter().map(|t| *t).skip(1), generics, is_ref) { return false; }
                                        }
-                               } else { unimplemented!(); }
-                       } else if let syn::Type::Array(a_arg) = t {
-                               if let syn::Type::Path(p_arg) = &*a_arg.elem {
-                                       let resolved = self.resolve_path(&p_arg.path, None);
-                                       assert!(self.is_primitive(&resolved));
-                                       if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Int(len), .. }) = &a_arg.len {
-                                               write!(w, "{}",
-                                                       self.c_type_from_path(&format!("[{}; {}]", resolved, len.base10_digits()), is_ref, false).unwrap()).unwrap();
+                               } else {
+                                       if !self.write_template_generics(&mut b_ty, &mut args.iter().map(|t| *t).skip(1), generics, is_ref) { return false; }
+                               }
+
+                               let ok_str = String::from_utf8(a_ty).unwrap();
+                               let err_str = String::from_utf8(b_ty).unwrap();
+                               let is_clonable = self.is_clonable(&ok_str) && self.is_clonable(&err_str);
+                               write_result_block(&mut created_container, &mangled_container, &ok_str, &err_str, is_clonable);
+                               if is_clonable {
+                                       self.crate_types.clonable_types.insert(Self::generated_container_path().to_owned() + "::" + &mangled_container);
+                               }
+                       } else if container_type == "Vec" {
+                               let mut a_ty: Vec<u8> = Vec::new();
+                               if !self.write_template_generics(&mut a_ty, &mut args.iter().map(|t| *t), generics, is_ref) { return false; }
+                               let ty = String::from_utf8(a_ty).unwrap();
+                               let is_clonable = self.is_clonable(&ty);
+                               write_vec_block(&mut created_container, &mangled_container, &ty, is_clonable);
+                               if is_clonable {
+                                       self.crate_types.clonable_types.insert(Self::generated_container_path().to_owned() + "::" + &mangled_container);
+                               }
+                       } else if container_type.ends_with("Tuple") {
+                               let mut tuple_args = Vec::new();
+                               let mut is_clonable = true;
+                               for arg in args.iter() {
+                                       let mut ty: Vec<u8> = Vec::new();
+                                       if !self.write_template_generics(&mut ty, &mut [arg].iter().map(|t| **t), generics, is_ref) { return false; }
+                                       let ty_str = String::from_utf8(ty).unwrap();
+                                       if !self.is_clonable(&ty_str) {
+                                               is_clonable = false;
                                        }
+                                       tuple_args.push(ty_str);
                                }
+                               write_tuple_block(&mut created_container, &mangled_container, &tuple_args, is_clonable);
+                               if is_clonable {
+                                       self.crate_types.clonable_types.insert(Self::generated_container_path().to_owned() + "::" + &mangled_container);
+                               }
+                       } else {
+                               unreachable!();
                        }
-               }
-       }
-       fn check_create_container(&mut self, mangled_container: String, container_type: &str, args: Vec<&syn::Type>, generics: Option<&GenericTypes>, is_ref: bool) {
-               if !self.crate_types.templates_defined.get(&mangled_container).is_some() {
                        self.crate_types.templates_defined.insert(mangled_container.clone(), true);
-                       let mut created_container: Vec<u8> = Vec::new();
-
-                       write!(&mut created_container, "#[no_mangle]\npub type {} = ", mangled_container).unwrap();
-                       write!(&mut created_container, "{}::C{}Templ<", Self::container_templ_path(), container_type).unwrap();
-                       self.write_template_generics(&mut created_container, &mut args.iter().map(|t| *t), is_ref, true);
-                       writeln!(&mut created_container, ">;").unwrap();
-
-                       write!(&mut created_container, "#[no_mangle]\npub static {}_free: extern \"C\" fn({}) = ", mangled_container, mangled_container).unwrap();
-                       write!(&mut created_container, "{}::C{}Templ_free::<", Self::container_templ_path(), container_type).unwrap();
-                       self.write_template_generics(&mut created_container, &mut args.iter().map(|t| *t), is_ref, true);
-                       writeln!(&mut created_container, ">;").unwrap();
-
-                       self.write_template_constructor(&mut created_container, container_type, &mangled_container, &args, generics, is_ref);
 
                        self.crate_types.template_file.write(&created_container).unwrap();
                }
+               true
        }
        fn path_to_generic_args(path: &syn::Path) -> Vec<&syn::Type> {
                if let syn::PathArguments::AngleBracketed(args) = &path.segments.iter().next().unwrap().arguments {
@@ -1833,45 +1930,46 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                for arg in args.iter() {
                        macro_rules! write_path {
                                ($p_arg: expr, $extra_write: expr) => {
-                                       let subtype = self.resolve_path(&$p_arg.path, generics);
-                                       if self.is_transparent_container(ident, is_ref) {
-                                               // We dont (yet) support primitives or containers inside transparent
-                                               // containers, so check for that first:
-                                               if self.is_primitive(&subtype) { return false; }
-                                               if self.is_known_container(&subtype, is_ref) { return false; }
-                                               if !in_type {
-                                                       if self.c_type_has_inner_from_path(&subtype) {
-                                                               if !self.write_c_path_intern(w, &$p_arg.path, generics, is_ref, is_mut, ptr_for_ref) { return false; }
+                                       if let Some(subtype) = self.maybe_resolve_path(&$p_arg.path, generics) {
+                                               if self.is_transparent_container(ident, is_ref) {
+                                                       // We dont (yet) support primitives or containers inside transparent
+                                                       // containers, so check for that first:
+                                                       if self.is_primitive(&subtype) { return false; }
+                                                       if self.is_known_container(&subtype, is_ref) { return false; }
+                                                       if !in_type {
+                                                               if self.c_type_has_inner_from_path(&subtype) {
+                                                                       if !self.write_c_path_intern(w, &$p_arg.path, generics, is_ref, is_mut, ptr_for_ref) { return false; }
+                                                               } else {
+                                                                       // Option<T> needs to be converted to a *mut T, ie mut ptr-for-ref
+                                                                       if !self.write_c_path_intern(w, &$p_arg.path, generics, true, true, true) { return false; }
+                                                               }
                                                        } else {
-                                                               // Option<T> needs to be converted to a *mut T, ie mut ptr-for-ref
-                                                               if !self.write_c_path_intern(w, &$p_arg.path, generics, true, true, true) { return false; }
+                                                               if $p_arg.path.segments.len() == 1 {
+                                                                       write!(w, "{}", $p_arg.path.segments.iter().next().unwrap().ident).unwrap();
+                                                               } else {
+                                                                       return false;
+                                                               }
                                                        }
-                                               } else {
-                                                       if $p_arg.path.segments.len() == 1 {
-                                                               write!(w, "{}", $p_arg.path.segments.iter().next().unwrap().ident).unwrap();
-                                                       } else {
+                                               } else if self.is_known_container(&subtype, is_ref) || self.is_transparent_container(&subtype, is_ref) {
+                                                       if !self.write_c_mangled_container_path_intern(w, Self::path_to_generic_args(&$p_arg.path), generics,
+                                                                       &subtype, is_ref, is_mut, ptr_for_ref, true) {
                                                                return false;
                                                        }
-                                               }
-                                       } else if self.is_known_container(&subtype, is_ref) || self.is_transparent_container(&subtype, is_ref) {
-                                               if !self.write_c_mangled_container_path_intern(w, Self::path_to_generic_args(&$p_arg.path), generics,
-                                                               &subtype, is_ref, is_mut, ptr_for_ref, true) {
-                                                       return false;
-                                               }
-                                               self.write_c_mangled_container_path_intern(&mut mangled_type, Self::path_to_generic_args(&$p_arg.path),
-                                                       generics, &subtype, is_ref, is_mut, ptr_for_ref, true);
-                                               if let Some(w2) = $extra_write as Option<&mut Vec<u8>> {
-                                                       self.write_c_mangled_container_path_intern(w2, Self::path_to_generic_args(&$p_arg.path),
+                                                       self.write_c_mangled_container_path_intern(&mut mangled_type, Self::path_to_generic_args(&$p_arg.path),
                                                                generics, &subtype, is_ref, is_mut, ptr_for_ref, true);
+                                                       if let Some(w2) = $extra_write as Option<&mut Vec<u8>> {
+                                                               self.write_c_mangled_container_path_intern(w2, Self::path_to_generic_args(&$p_arg.path),
+                                                                       generics, &subtype, is_ref, is_mut, ptr_for_ref, true);
+                                                       }
+                                               } else {
+                                                       let id = subtype.rsplitn(2, ':').next().unwrap(); // Get the "Base" name of the resolved type
+                                                       write!(w, "{}", id).unwrap();
+                                                       write!(mangled_type, "{}", id).unwrap();
+                                                       if let Some(w2) = $extra_write as Option<&mut Vec<u8>> {
+                                                               write!(w2, "{}", id).unwrap();
+                                                       }
                                                }
-                                       } else {
-                                               let id = &&$p_arg.path.segments.iter().rev().next().unwrap().ident;
-                                               write!(w, "{}", id).unwrap();
-                                               write!(mangled_type, "{}", id).unwrap();
-                                               if let Some(w2) = $extra_write as Option<&mut Vec<u8>> {
-                                                       write!(w2, "{}", id).unwrap();
-                                               }
-                                       }
+                                       } else { return false; }
                                }
                        }
                        if let syn::Type::Tuple(tuple) = arg {
@@ -1900,13 +1998,14 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                                        write!(w, "Z").unwrap();
                                        write!(mangled_type, "Z").unwrap();
                                        write!(mangled_tuple_type, "Z").unwrap();
-                                       self.check_create_container(String::from_utf8(mangled_tuple_type).unwrap(),
-                                               &format!("{}Tuple", tuple.elems.len()), tuple.elems.iter().collect(), generics, is_ref);
+                                       if !self.check_create_container(String::from_utf8(mangled_tuple_type).unwrap(),
+                                                       &format!("{}Tuple", tuple.elems.len()), tuple.elems.iter().collect(), generics, is_ref) {
+                                               return false;
+                                       }
                                }
                        } else if let syn::Type::Path(p_arg) = arg {
                                write_path!(p_arg, None);
                        } else if let syn::Type::Reference(refty) = arg {
-                               if args.len() != 1 { return false; }
                                if let syn::Type::Path(p_arg) = &*refty.elem {
                                        write_path!(p_arg, None);
                                } else if let syn::Type::Slice(_) = &*refty.elem {
@@ -1914,6 +2013,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                                        // make it a pointer so that its an option. Note that we cannot always convert
                                        // the Vec-as-slice (ie non-ref types) containers, so sometimes need to be able
                                        // to edit it, hence we use *mut here instead of *const.
+                                       if args.len() != 1 { return false; }
                                        write!(w, "*mut ").unwrap();
                                        self.write_c_type(w, arg, None, true);
                                } else { return false; }
@@ -1935,8 +2035,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                write!(mangled_type, "Z").unwrap();
 
                // Make sure the type is actually defined:
-               self.check_create_container(String::from_utf8(mangled_type).unwrap(), ident, args, generics, is_ref);
-               true
+               self.check_create_container(String::from_utf8(mangled_type).unwrap(), ident, args, generics, is_ref)
        }
        fn write_c_mangled_container_path<W: std::io::Write>(&mut self, w: &mut W, args: Vec<&syn::Type>, generics: Option<&GenericTypes>, ident: &str, is_ref: bool, is_mut: bool, ptr_for_ref: bool) -> bool {
                if !self.is_transparent_container(ident, is_ref) {
@@ -2046,8 +2145,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                                                        format!("CVec_{}Z", id)
                                                } else { return false; };
                                                write!(w, "{}::{}", Self::generated_container_path(), mangled_container).unwrap();
-                                               self.check_create_container(mangled_container, "Vec", vec![&*r.elem], generics, false);
-                                               true
+                                               self.check_create_container(mangled_container, "Vec", vec![&*r.elem], generics, false)
                                        } else { false }
                                } else if let syn::Type::Tuple(_) = &*s.elem {
                                        let mut args = syn::punctuated::Punctuated::new();
index cb5d40eaa5837500fccd0e3201ed2feb1b31fb41..fc8e6d5965fb7e543fd23995552db5de0164086b 100644 (file)
@@ -19,11 +19,17 @@ stdin_fuzz = []
 [dependencies]
 afl = { version = "0.4", optional = true }
 lightning = { path = "../lightning", features = ["fuzztarget"] }
-bitcoin = { version = "0.24", features = ["fuzztarget"] }
+bitcoin = { version = "0.26", features = ["fuzztarget", "secp-lowmemory"] }
 hex = "0.3"
 honggfuzz = { version = "0.5", optional = true }
 libfuzzer-sys = { git = "https://github.com/rust-fuzz/libfuzzer-sys.git", optional = true }
 
+[patch.crates-io]
+# Rust-Secp256k1 PR 282. This patch should be dropped once that is merged.
+secp256k1 = { git = 'https://github.com/TheBlueMatt/rust-secp256k1', rev = '32767e0e21e8861701ff7d5957613169d67ff1f8' }
+# bitcoin_hashes PR 111 (without the top commit). This patch should be dropped once that is merged.
+bitcoin_hashes = { git = 'https://github.com/TheBlueMatt/bitcoin_hashes', rev = 'c90d26339a3e34fd2f942aa80298f410cc41b743' }
+
 [build-dependencies]
 cc = "1.0"
 
index 377ac8d7b5702c439e84dcc7b1db898645483428..dcf8c31ffb771a83a3db6d59ec3871d86a93ebc2 100644 (file)
@@ -34,17 +34,18 @@ use lightning::chain::channelmonitor;
 use lightning::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, MonitorEvent};
 use lightning::chain::transaction::OutPoint;
 use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator};
-use lightning::chain::keysinterface::{KeysInterface, InMemoryChannelKeys};
+use lightning::chain::keysinterface::{KeysInterface, InMemorySigner};
 use lightning::ln::channelmanager::{ChannelManager, PaymentHash, PaymentPreimage, PaymentSecret, PaymentSendFailure, ChannelManagerReadArgs};
 use lightning::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
-use lightning::ln::msgs::{CommitmentUpdate, ChannelMessageHandler, ErrorAction, UpdateAddHTLC, Init};
-use lightning::util::enforcing_trait_impls::EnforcingChannelKeys;
+use lightning::ln::msgs::{CommitmentUpdate, ChannelMessageHandler, DecodeError, ErrorAction, UpdateAddHTLC, Init};
+use lightning::util::enforcing_trait_impls::{EnforcingSigner, INITIAL_REVOKED_COMMITMENT_NUMBER};
 use lightning::util::errors::APIError;
 use lightning::util::events;
 use lightning::util::logger::Logger;
 use lightning::util::config::UserConfig;
 use lightning::util::events::{EventsProvider, MessageSendEventsProvider};
 use lightning::util::ser::{Readable, ReadableArgs, Writeable, Writer};
+use lightning::util::test_utils::OnlyReadsKeysInterface;
 use lightning::routing::router::{Route, RouteHop};
 
 
@@ -86,7 +87,7 @@ impl Writer for VecWriter {
 
 struct TestChainMonitor {
        pub logger: Arc<dyn Logger>,
-       pub chain_monitor: Arc<chainmonitor::ChainMonitor<EnforcingChannelKeys, Arc<dyn chain::Filter>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>, Arc<TestPersister>>>,
+       pub chain_monitor: Arc<chainmonitor::ChainMonitor<EnforcingSigner, Arc<dyn chain::Filter>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>, Arc<TestPersister>>>,
        pub update_ret: Mutex<Result<(), channelmonitor::ChannelMonitorUpdateErr>>,
        // If we reload a node with an old copy of ChannelMonitors, the ChannelManager deserialization
        // logic will automatically force-close our channels for us (as we don't have an up-to-date
@@ -107,12 +108,10 @@ impl TestChainMonitor {
                }
        }
 }
-impl chain::Watch for TestChainMonitor {
-       type Keys = EnforcingChannelKeys;
-
-       fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<EnforcingChannelKeys>) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
+impl chain::Watch<EnforcingSigner> for TestChainMonitor {
+       fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<EnforcingSigner>) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
                let mut ser = VecWriter(Vec::new());
-               monitor.serialize_for_disk(&mut ser).unwrap();
+               monitor.write(&mut ser).unwrap();
                if let Some(_) = self.latest_monitors.lock().unwrap().insert(funding_txo, (monitor.get_latest_update_id(), ser.0)) {
                        panic!("Already had monitor pre-watch_channel");
                }
@@ -127,11 +126,11 @@ impl chain::Watch for TestChainMonitor {
                        hash_map::Entry::Occupied(entry) => entry,
                        hash_map::Entry::Vacant(_) => panic!("Didn't have monitor on update call"),
                };
-               let mut deserialized_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::
-                       read(&mut Cursor::new(&map_entry.get().1)).unwrap().1;
+               let deserialized_monitor = <(Option<BlockHash>, channelmonitor::ChannelMonitor<EnforcingSigner>)>::
+                       read(&mut Cursor::new(&map_entry.get().1), &OnlyReadsKeysInterface {}).unwrap().1;
                deserialized_monitor.update_monitor(&update, &&TestBroadcaster{}, &&FuzzEstimator{}, &self.logger).unwrap();
                let mut ser = VecWriter(Vec::new());
-               deserialized_monitor.serialize_for_disk(&mut ser).unwrap();
+               deserialized_monitor.write(&mut ser).unwrap();
                map_entry.insert((update.update_id, ser.0));
                self.should_update_manager.store(true, atomic::Ordering::Relaxed);
                self.update_ret.lock().unwrap().clone()
@@ -145,9 +144,10 @@ impl chain::Watch for TestChainMonitor {
 struct KeyProvider {
        node_id: u8,
        rand_bytes_id: atomic::AtomicU8,
+       revoked_commitments: Mutex<HashMap<[u8;32], Arc<Mutex<u64>>>>,
 }
 impl KeysInterface for KeyProvider {
-       type ChanKeySigner = EnforcingChannelKeys;
+       type Signer = EnforcingSigner;
 
        fn get_node_secret(&self) -> SecretKey {
                SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, self.node_id]).unwrap()
@@ -165,25 +165,55 @@ impl KeysInterface for KeyProvider {
                PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, self.node_id]).unwrap())
        }
 
-       fn get_channel_keys(&self, _inbound: bool, channel_value_satoshis: u64) -> EnforcingChannelKeys {
+       fn get_channel_signer(&self, _inbound: bool, channel_value_satoshis: u64) -> EnforcingSigner {
                let secp_ctx = Secp256k1::signing_only();
-               EnforcingChannelKeys::new(InMemoryChannelKeys::new(
+               let id = self.rand_bytes_id.fetch_add(1, atomic::Ordering::Relaxed);
+               let keys = InMemorySigner::new(
                        &secp_ctx,
                        SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, self.node_id]).unwrap(),
                        SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, self.node_id]).unwrap(),
                        SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, self.node_id]).unwrap(),
                        SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, self.node_id]).unwrap(),
                        SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, self.node_id]).unwrap(),
-                       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, self.node_id],
+                       [id, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, self.node_id],
                        channel_value_satoshis,
-                       (0, 0),
-               ))
+                       [0; 32],
+               );
+               let revoked_commitment = self.make_revoked_commitment_cell(keys.commitment_seed);
+               EnforcingSigner::new_with_revoked(keys, revoked_commitment, false)
        }
 
        fn get_secure_random_bytes(&self) -> [u8; 32] {
                let id = self.rand_bytes_id.fetch_add(1, atomic::Ordering::Relaxed);
                [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, id, 11, self.node_id]
        }
+
+       fn read_chan_signer(&self, buffer: &[u8]) -> Result<Self::Signer, DecodeError> {
+               let mut reader = std::io::Cursor::new(buffer);
+
+               let inner: InMemorySigner = Readable::read(&mut reader)?;
+               let revoked_commitment = self.make_revoked_commitment_cell(inner.commitment_seed);
+
+               let last_commitment_number = Readable::read(&mut reader)?;
+
+               Ok(EnforcingSigner {
+                       inner,
+                       last_commitment_number: Arc::new(Mutex::new(last_commitment_number)),
+                       revoked_commitment,
+                       disable_revocation_policy_check: false,
+               })
+       }
+}
+
+impl KeyProvider {
+       fn make_revoked_commitment_cell(&self, commitment_seed: [u8; 32]) -> Arc<Mutex<u64>> {
+               let mut revoked_commitments = self.revoked_commitments.lock().unwrap();
+               if !revoked_commitments.contains_key(&commitment_seed) {
+                       revoked_commitments.insert(commitment_seed, Arc::new(Mutex::new(INITIAL_REVOKED_COMMITMENT_NUMBER)));
+               }
+               let cell = revoked_commitments.get(&commitment_seed).unwrap();
+               Arc::clone(cell)
+       }
 }
 
 #[inline]
@@ -227,7 +257,7 @@ fn check_payment_err(send_err: PaymentSendFailure) {
        }
 }
 
-type ChanMan = ChannelManager<EnforcingChannelKeys, Arc<TestChainMonitor>, Arc<TestBroadcaster>, Arc<KeyProvider>, Arc<FuzzEstimator>, Arc<dyn Logger>>;
+type ChanMan = ChannelManager<EnforcingSigner, Arc<TestChainMonitor>, Arc<TestBroadcaster>, Arc<KeyProvider>, Arc<FuzzEstimator>, Arc<dyn Logger>>;
 
 #[inline]
 fn send_payment(source: &ChanMan, dest: &ChanMan, dest_chan_id: u64, amt: u64, payment_id: &mut u8) -> bool {
@@ -283,22 +313,22 @@ pub fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
                        let logger: Arc<dyn Logger> = Arc::new(test_logger::TestLogger::new($node_id.to_string(), out.clone()));
                        let monitor = Arc::new(TestChainMonitor::new(broadcast.clone(), logger.clone(), fee_est.clone(), Arc::new(TestPersister{})));
 
-                       let keys_manager = Arc::new(KeyProvider { node_id: $node_id, rand_bytes_id: atomic::AtomicU8::new(0) });
+                       let keys_manager = Arc::new(KeyProvider { node_id: $node_id, rand_bytes_id: atomic::AtomicU8::new(0), revoked_commitments: Mutex::new(HashMap::new()) });
                        let mut config = UserConfig::default();
                        config.channel_options.fee_proportional_millionths = 0;
                        config.channel_options.announced_channel = true;
                        config.peer_channel_config_limits.min_dust_limit_satoshis = 0;
                        (ChannelManager::new(Network::Bitcoin, fee_est.clone(), monitor.clone(), broadcast.clone(), Arc::clone(&logger), keys_manager.clone(), config, 0),
-                       monitor)
+                       monitor, keys_manager)
                } }
        }
 
        macro_rules! reload_node {
-               ($ser: expr, $node_id: expr, $old_monitors: expr) => { {
+               ($ser: expr, $node_id: expr, $old_monitors: expr, $keys_manager: expr) => { {
+                   let keys_manager = Arc::clone(& $keys_manager);
                        let logger: Arc<dyn Logger> = Arc::new(test_logger::TestLogger::new($node_id.to_string(), out.clone()));
                        let chain_monitor = Arc::new(TestChainMonitor::new(broadcast.clone(), logger.clone(), fee_est.clone(), Arc::new(TestPersister{})));
 
-                       let keys_manager = Arc::new(KeyProvider { node_id: $node_id, rand_bytes_id: atomic::AtomicU8::new(0) });
                        let mut config = UserConfig::default();
                        config.channel_options.fee_proportional_millionths = 0;
                        config.channel_options.announced_channel = true;
@@ -307,7 +337,7 @@ pub fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
                        let mut monitors = HashMap::new();
                        let mut old_monitors = $old_monitors.latest_monitors.lock().unwrap();
                        for (outpoint, (update_id, monitor_ser)) in old_monitors.drain() {
-                               monitors.insert(outpoint, <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut Cursor::new(&monitor_ser)).expect("Failed to read monitor").1);
+                               monitors.insert(outpoint, <(Option<BlockHash>, ChannelMonitor<EnforcingSigner>)>::read(&mut Cursor::new(&monitor_ser), &OnlyReadsKeysInterface {}).expect("Failed to read monitor").1);
                                chain_monitor.latest_monitors.lock().unwrap().insert(outpoint, (update_id, monitor_ser));
                        }
                        let mut monitor_refs = HashMap::new();
@@ -325,7 +355,7 @@ pub fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
                                channel_monitors: monitor_refs,
                        };
 
-                       (<(BlockHash, ChanMan)>::read(&mut Cursor::new(&$ser.0), read_args).expect("Failed to read manager").1, chain_monitor)
+                       (<(Option<BlockHash>, ChanMan)>::read(&mut Cursor::new(&$ser.0), read_args).expect("Failed to read manager").1, chain_monitor)
                } }
        }
 
@@ -435,9 +465,9 @@ pub fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
 
        // 3 nodes is enough to hit all the possible cases, notably unknown-source-unknown-dest
        // forwarding.
-       let (node_a, mut monitor_a) = make_node!(0);
-       let (node_b, mut monitor_b) = make_node!(1);
-       let (node_c, mut monitor_c) = make_node!(2);
+       let (node_a, mut monitor_a, keys_manager_a) = make_node!(0);
+       let (node_b, mut monitor_b, keys_manager_b) = make_node!(1);
+       let (node_c, mut monitor_c, keys_manager_c) = make_node!(2);
 
        let mut nodes = [node_a, node_b, node_c];
 
@@ -788,7 +818,7 @@ pub fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
                                        chan_a_disconnected = true;
                                        drain_msg_events_on_disconnect!(0);
                                }
-                               let (new_node_a, new_monitor_a) = reload_node!(node_a_ser, 0, monitor_a);
+                               let (new_node_a, new_monitor_a) = reload_node!(node_a_ser, 0, monitor_a, keys_manager_a);
                                nodes[0] = new_node_a;
                                monitor_a = new_monitor_a;
                        },
@@ -805,7 +835,7 @@ pub fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
                                        nodes[2].get_and_clear_pending_msg_events();
                                        bc_events.clear();
                                }
-                               let (new_node_b, new_monitor_b) = reload_node!(node_b_ser, 1, monitor_b);
+                               let (new_node_b, new_monitor_b) = reload_node!(node_b_ser, 1, monitor_b, keys_manager_b);
                                nodes[1] = new_node_b;
                                monitor_b = new_monitor_b;
                        },
@@ -815,7 +845,7 @@ pub fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
                                        chan_b_disconnected = true;
                                        drain_msg_events_on_disconnect!(2);
                                }
-                               let (new_node_c, new_monitor_c) = reload_node!(node_c_ser, 2, monitor_c);
+                               let (new_node_c, new_monitor_c) = reload_node!(node_c_ser, 2, monitor_c, keys_manager_c);
                                nodes[2] = new_node_c;
                                monitor_c = new_monitor_c;
                        },
index fd326cc2ec85bdc72670da4cae4f7388366c05af..e7dbf3ed8d6a588aef5e7529d7295999018d01ca 100644 (file)
@@ -4,8 +4,9 @@
 use bitcoin::hash_types::BlockHash;
 
 use lightning::chain::channelmonitor;
-use lightning::util::enforcing_trait_impls::EnforcingChannelKeys;
-use lightning::util::ser::{Readable, Writer};
+use lightning::util::enforcing_trait_impls::EnforcingSigner;
+use lightning::util::ser::{ReadableArgs, Writer, Writeable};
+use lightning::util::test_utils::OnlyReadsKeysInterface;
 
 use utils::test_logger;
 
@@ -24,11 +25,13 @@ impl Writer for VecWriter {
 
 #[inline]
 pub fn do_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
-       if let Ok((latest_block_hash, monitor)) = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(&mut Cursor::new(data)) {
+       if let Ok((Some(latest_block_hash), monitor)) = <(Option<BlockHash>, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(&mut Cursor::new(data), &OnlyReadsKeysInterface {}) {
                let mut w = VecWriter(Vec::new());
-               monitor.serialize_for_disk(&mut w).unwrap();
-               let deserialized_copy = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(&mut Cursor::new(&w.0)).unwrap();
-               assert!(latest_block_hash == deserialized_copy.0);
+               monitor.write(&mut w).unwrap();
+               let deserialized_copy = <(Option<BlockHash>, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(&mut Cursor::new(&w.0), &OnlyReadsKeysInterface {}).unwrap();
+               if let Some(deserialized) = deserialized_copy.0 {
+                       assert!(latest_block_hash == deserialized);
+               }
                assert!(monitor == deserialized_copy.1);
        }
 }
index 6375d0765d76a3d4a7940d4781ef2b574b90b564..3774d0dce839848cb7034fbf041da52c78e60142 100644 (file)
@@ -30,15 +30,17 @@ use lightning::chain;
 use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator};
 use lightning::chain::chainmonitor;
 use lightning::chain::transaction::OutPoint;
-use lightning::chain::keysinterface::{InMemoryChannelKeys, KeysInterface};
+use lightning::chain::keysinterface::{InMemorySigner, KeysInterface};
 use lightning::ln::channelmanager::{ChannelManager, PaymentHash, PaymentPreimage, PaymentSecret};
 use lightning::ln::peer_handler::{MessageHandler,PeerManager,SocketDescriptor};
+use lightning::ln::msgs::DecodeError;
 use lightning::routing::router::get_route;
 use lightning::routing::network_graph::NetGraphMsgHandler;
+use lightning::util::config::UserConfig;
 use lightning::util::events::{EventsProvider,Event};
-use lightning::util::enforcing_trait_impls::EnforcingChannelKeys;
+use lightning::util::enforcing_trait_impls::EnforcingSigner;
 use lightning::util::logger::Logger;
-use lightning::util::config::UserConfig;
+use lightning::util::ser::Readable;
 
 use utils::test_logger;
 use utils::test_persister::TestPersister;
@@ -146,14 +148,14 @@ impl<'a> std::hash::Hash for Peer<'a> {
 }
 
 type ChannelMan = ChannelManager<
-       EnforcingChannelKeys,
-       Arc<chainmonitor::ChainMonitor<EnforcingChannelKeys, Arc<dyn chain::Filter>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>, Arc<TestPersister>>>,
+       EnforcingSigner,
+       Arc<chainmonitor::ChainMonitor<EnforcingSigner, Arc<dyn chain::Filter>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>, Arc<TestPersister>>>,
        Arc<TestBroadcaster>, Arc<KeyProvider>, Arc<FuzzEstimator>, Arc<dyn Logger>>;
 type PeerMan<'a> = PeerManager<Peer<'a>, Arc<ChannelMan>, Arc<NetGraphMsgHandler<Arc<dyn chain::Access>, Arc<dyn Logger>>>, Arc<dyn Logger>>;
 
 struct MoneyLossDetector<'a> {
        manager: Arc<ChannelMan>,
-       monitor: Arc<chainmonitor::ChainMonitor<EnforcingChannelKeys, Arc<dyn chain::Filter>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>, Arc<TestPersister>>>,
+       monitor: Arc<chainmonitor::ChainMonitor<EnforcingSigner, Arc<dyn chain::Filter>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>, Arc<TestPersister>>>,
        handler: PeerMan<'a>,
 
        peers: &'a RefCell<[bool; 256]>,
@@ -167,7 +169,7 @@ struct MoneyLossDetector<'a> {
 impl<'a> MoneyLossDetector<'a> {
        pub fn new(peers: &'a RefCell<[bool; 256]>,
                   manager: Arc<ChannelMan>,
-                  monitor: Arc<chainmonitor::ChainMonitor<EnforcingChannelKeys, Arc<dyn chain::Filter>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>, Arc<TestPersister>>>,
+                  monitor: Arc<chainmonitor::ChainMonitor<EnforcingSigner, Arc<dyn chain::Filter>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>, Arc<TestPersister>>>,
                   handler: PeerMan<'a>) -> Self {
                MoneyLossDetector {
                        manager,
@@ -246,7 +248,7 @@ struct KeyProvider {
        counter: AtomicU64,
 }
 impl KeysInterface for KeyProvider {
-       type ChanKeySigner = EnforcingChannelKeys;
+       type Signer = EnforcingSigner;
 
        fn get_node_secret(&self) -> SecretKey {
                self.node_secret.clone()
@@ -261,14 +263,14 @@ impl KeysInterface for KeyProvider {
 
        fn get_shutdown_pubkey(&self) -> PublicKey {
                let secp_ctx = Secp256k1::signing_only();
-               PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap())
+               PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]).unwrap())
        }
 
-       fn get_channel_keys(&self, inbound: bool, channel_value_satoshis: u64) -> EnforcingChannelKeys {
+       fn get_channel_signer(&self, inbound: bool, channel_value_satoshis: u64) -> EnforcingSigner {
                let ctr = self.counter.fetch_add(1, Ordering::Relaxed) as u8;
                let secp_ctx = Secp256k1::signing_only();
-               EnforcingChannelKeys::new(if inbound {
-                       InMemoryChannelKeys::new(
+               EnforcingSigner::new(if inbound {
+                       InMemorySigner::new(
                                &secp_ctx,
                                SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, ctr]).unwrap(),
                                SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, ctr]).unwrap(),
@@ -277,10 +279,10 @@ impl KeysInterface for KeyProvider {
                                SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, ctr]).unwrap(),
                                [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, ctr],
                                channel_value_satoshis,
-                               (0, 0),
+                               [0; 32]
                        )
                } else {
-                       InMemoryChannelKeys::new(
+                       InMemorySigner::new(
                                &secp_ctx,
                                SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, ctr]).unwrap(),
                                SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, ctr]).unwrap(),
@@ -289,7 +291,7 @@ impl KeysInterface for KeyProvider {
                                SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, ctr]).unwrap(),
                                [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, ctr],
                                channel_value_satoshis,
-                               (0, 0),
+                               [0; 32]
                        )
                })
        }
@@ -299,6 +301,10 @@ impl KeysInterface for KeyProvider {
                [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                (ctr >> 8*7) as u8, (ctr >> 8*6) as u8, (ctr >> 8*5) as u8, (ctr >> 8*4) as u8, (ctr >> 8*3) as u8, (ctr >> 8*2) as u8, (ctr >> 8*1) as u8, 14, (ctr >> 8*0) as u8]
        }
+
+       fn read_chan_signer(&self, data: &[u8]) -> Result<EnforcingSigner, DecodeError> {
+               EnforcingSigner::read(&mut std::io::Cursor::new(data))
+       }
 }
 
 #[inline]
@@ -542,7 +548,7 @@ pub fn do_test(data: &[u8], logger: &Arc<dyn Logger>) {
                                let channel_id = get_slice!(1)[0] as usize;
                                if channel_id >= channels.len() { return; }
                                channels.sort_by(|a, b| { a.channel_id.cmp(&b.channel_id) });
-                               channelmanager.force_close_channel(&channels[channel_id].channel_id);
+                               channelmanager.force_close_channel(&channels[channel_id].channel_id).unwrap();
                        },
                        // 15 is above
                        _ => return,
@@ -618,14 +624,14 @@ mod tests {
 
                // Writing new code generating transactions and see a new failure ? Don't forget to add input for the FuzzEstimator !
 
-               // 0000000000000000000000000000000000000000000000000000000000000000 - our network key
+               // 0100000000000000000000000000000000000000000000000000000000000000 - our network key
                // 00000000 - fee_proportional_millionths
                // 01 - announce_channels_publicly
                //
                // 00 - new outbound connection with id 0
-               // 030000000000000000000000000000000000000000000000000000000000000000 - peer's pubkey
+               // 030000000000000000000000000000000000000000000000000000000000000002 - peer's pubkey
                // 030032 - inbound read from peer id 0 of len 50
-               // 00 030000000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000 - noise act two (0||pubkey||mac)
+               // 00 030000000000000000000000000000000000000000000000000000000000000002 03000000000000000000000000000000 - noise act two (0||pubkey||mac)
                //
                // 030012 - inbound read from peer id 0 of len 18
                // 000a 03000000000000000000000000000000 - message header indicating message length 10
@@ -637,7 +643,7 @@ mod tests {
                // 0300fe - inbound read from peer id 0 of len 254
                // 0020 7500000000000000000000000000000000000000000000000000000000000000 ff4f00f805273c1b203bb5ebf8436bfde57b3be8c2f5e95d9491dbb181909679 000000000000c350 0000000000000000 0000000000000222 ffffffffffffffff 0000000000000222 0000000000000000 000000fd 0006 01e3 030000000000000000000000000000000000000000000000000000000000000001 030000000000000000000000000000000000000000000000000000000000000002 030000000000000000000000000000000000000000000000000000000000000003 030000000000000000000000000000000000000000000000000000000000000004 - beginning of open_channel message
                // 030053 - inbound read from peer id 0 of len 83
-               // 030000000000000000000000000000000000000000000000000000000000000005 030000000000000000000000000000000000000000000000000000000000000000 01 03000000000000000000000000000000 - rest of open_channel and mac
+               // 030000000000000000000000000000000000000000000000000000000000000005 020900000000000000000000000000000000000000000000000000000000000000 01 03000000000000000000000000000000 - rest of open_channel and mac
                //
                // 00fd00fd00fd - Three feerate requests (all returning min feerate, which our open_channel also uses) (gonna be ingested by FuzzEstimator)
                // - client should now respond with accept_channel (CHECK 1: type 33 to peer 03000000)
@@ -645,7 +651,7 @@ mod tests {
                // 030012 - inbound read from peer id 0 of len 18
                // 0084 03000000000000000000000000000000 - message header indicating message length 132
                // 030094 - inbound read from peer id 0 of len 148
-               // 0022 ff4f00f805273c1b203bb5ebf8436bfde57b3be8c2f5e95d9491dbb181909679 3d00000000000000000000000000000000000000000000000000000000000000 0000 20000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001 03000000000000000000000000000000 - funding_created and mac
+               // 0022 ff4f00f805273c1b203bb5ebf8436bfde57b3be8c2f5e95d9491dbb181909679 3d00000000000000000000000000000000000000000000000000000000000000 0000 00000000000000000000000000000000000000000000000000000000000000210100000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000 - funding_created and mac
                // - client should now respond with funding_signed (CHECK 2: type 35 to peer 03000000)
                //
                // 0c005e - connect a block with one transaction of len 94
@@ -667,11 +673,11 @@ mod tests {
                // 030012 - inbound read from peer id 0 of len 18
                // 0043 03000000000000000000000000000000 - message header indicating message length 67
                // 030053 - inbound read from peer id 0 of len 83
-               // 0024 3d00000000000000000000000000000000000000000000000000000000000000 030100000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000 - funding_locked and mac
+               // 0024 3d00000000000000000000000000000000000000000000000000000000000000 020800000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000 - funding_locked and mac
                //
                // 01 - new inbound connection with id 1
                // 030132 - inbound read from peer id 1 of len 50
-               // 0003000000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000 - inbound noise act 1
+               // 0003000000000000000000000000000000000000000000000000000000000000000703000000000000000000000000000000 - inbound noise act 1
                // 030142 - inbound read from peer id 1 of len 66
                // 000302000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000003000000000000000000000000000000 - inbound noise act 3
                //
@@ -686,7 +692,7 @@ mod tests {
                // 030112 - inbound read from peer id 1 of len 18
                // 0110 01000000000000000000000000000000 - message header indicating message length 272
                // 0301ff - inbound read from peer id 1 of len 255
-               // 0021 0000000000000000000000000000000000000000000000000000000000000e02 000000000000001a 00000000004c4b40 00000000000003e8 00000000000003e8 00000002 03f0 0005 030000000000000000000000000000000000000000000000000000000000000100 030000000000000000000000000000000000000000000000000000000000000200 030000000000000000000000000000000000000000000000000000000000000300 030000000000000000000000000000000000000000000000000000000000000400 030000000000000000000000000000000000000000000000000000000000000500 03000000000000000000000000000000 - beginning of accept_channel
+               // 0021 0000000000000000000000000000000000000000000000000000000000000e05 000000000000001a 00000000004c4b40 00000000000003e8 00000000000003e8 00000002 03f0 0005 030000000000000000000000000000000000000000000000000000000000000100 030000000000000000000000000000000000000000000000000000000000000200 030000000000000000000000000000000000000000000000000000000000000300 030000000000000000000000000000000000000000000000000000000000000400 030000000000000000000000000000000000000000000000000000000000000500 02660000000000000000000000000000 - beginning of accept_channel
                // 030121 - inbound read from peer id 1 of len 33
                // 0000000000000000000000000000000000 01000000000000000000000000000000 - rest of accept_channel and mac
                //
@@ -695,7 +701,7 @@ mod tests {
                // 030112 - inbound read from peer id 1 of len 18
                // 0062 01000000000000000000000000000000 - message header indicating message length 98
                // 030172 - inbound read from peer id 1 of len 114
-               // 0023 3900000000000000000000000000000000000000000000000000000000000000 f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100 01000000000000000000000000000000 - funding_signed message and mac
+               // 0023 3a00000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000007c0001000000000000000000000000000000000000000000000000000000000000 01000000000000000000000000000000 - funding_signed message and mac
                //
                // 0b - broadcast funding transaction
                // - by now client should have sent a funding_locked (CHECK 4: SendFundingLocked to 03020000 for chan 3f000000)
@@ -703,7 +709,7 @@ mod tests {
                // 030112 - inbound read from peer id 1 of len 18
                // 0043 01000000000000000000000000000000 - message header indicating message length 67
                // 030153 - inbound read from peer id 1 of len 83
-               // 0024 3900000000000000000000000000000000000000000000000000000000000000 030100000000000000000000000000000000000000000000000000000000000000 01000000000000000000000000000000 - funding_locked and mac
+               // 0024 3a00000000000000000000000000000000000000000000000000000000000000 026700000000000000000000000000000000000000000000000000000000000000 01000000000000000000000000000000 - funding_locked and mac
                //
                // 030012 - inbound read from peer id 0 of len 18
                // 05ac 03000000000000000000000000000000 - message header indicating message length 1452
@@ -725,13 +731,13 @@ mod tests {
                // 030012 - inbound read from peer id 0 of len 18
                // 0064 03000000000000000000000000000000 - message header indicating message length 100
                // 030074 - inbound read from peer id 0 of len 116
-               // 0084 3d00000000000000000000000000000000000000000000000000000000000000 31000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001 0000 03000000000000000000000000000000 - commitment_signed and mac
+               // 0084 3d00000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000300100000000000000000000000000000000000000000000000000000000000000 0000 03000000000000000000000000000000 - commitment_signed and mac
                // - client should now respond with revoke_and_ack and commitment_signed (CHECK 5/6: types 133 and 132 to peer 03000000)
                //
                // 030012 - inbound read from peer id 0 of len 18
                // 0063 03000000000000000000000000000000 - message header indicating message length 99
                // 030073 - inbound read from peer id 0 of len 115
-               // 0085 3d00000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 030200000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000 - revoke_and_ack and mac
+               // 0085 3d00000000000000000000000000000000000000000000000000000000000000 0900000000000000000000000000000000000000000000000000000000000000 020b00000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000 - revoke_and_ack and mac
                //
                // 07 - process the now-pending HTLC forward
                // - client now sends id 1 update_add_htlc and commitment_signed (CHECK 7: SendHTLCs event for node 03020000 with 1 HTLCs for channel 3f000000)
@@ -740,28 +746,28 @@ mod tests {
                // 030112 - inbound read from peer id 1 of len 18
                // 0064 01000000000000000000000000000000 - message header indicating message length 100
                // 030174 - inbound read from peer id 1 of len 116
-               // 0084 3900000000000000000000000000000000000000000000000000000000000000 f1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100 0000 01000000000000000000000000000000 - commitment_signed and mac
+               // 0084 3a00000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000006a0001000000000000000000000000000000000000000000000000000000000000 0000 01000000000000000000000000000000 - commitment_signed and mac
                //
                // 030112 - inbound read from peer id 1 of len 18
                // 0063 01000000000000000000000000000000 - message header indicating message length 99
                // 030173 - inbound read from peer id 1 of len 115
-               // 0085 3900000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 030200000000000000000000000000000000000000000000000000000000000000 01000000000000000000000000000000 - revoke_and_ack and mac
+               // 0085 3a00000000000000000000000000000000000000000000000000000000000000 6600000000000000000000000000000000000000000000000000000000000000 026400000000000000000000000000000000000000000000000000000000000000 01000000000000000000000000000000 - revoke_and_ack and mac
                //
                // 030112 - inbound read from peer id 1 of len 18
                // 004a 01000000000000000000000000000000 - message header indicating message length 74
                // 03015a - inbound read from peer id 1 of len 90
-               // 0082 3900000000000000000000000000000000000000000000000000000000000000 0000000000000000 ff00888888888888888888888888888888888888888888888888888888888888 01000000000000000000000000000000 - update_fulfill_htlc and mac
+               // 0082 3a00000000000000000000000000000000000000000000000000000000000000 0000000000000000 ff00888888888888888888888888888888888888888888888888888888888888 01000000000000000000000000000000 - update_fulfill_htlc and mac
                // - client should immediately claim the pending HTLC from peer 0 (CHECK 8: SendFulfillHTLCs for node 03000000 with preimage ff00888888 for channel 3d000000)
                //
                // 030112 - inbound read from peer id 1 of len 18
                // 0064 01000000000000000000000000000000 - message header indicating message length 100
                // 030174 - inbound read from peer id 1 of len 116
-               // 0084 3900000000000000000000000000000000000000000000000000000000000000 fd000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100 0000 01000000000000000000000000000000 - commitment_signed and mac
+               // 0084 3a00000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000100001000000000000000000000000000000000000000000000000000000000000 0000 01000000000000000000000000000000 - commitment_signed and mac
                //
                // 030112 - inbound read from peer id 1 of len 18
                // 0063 01000000000000000000000000000000 - message header indicating message length 99
                // 030173 - inbound read from peer id 1 of len 115
-               // 0085 3900000000000000000000000000000000000000000000000000000000000000 0100000000000000000000000000000000000000000000000000000000000000 030300000000000000000000000000000000000000000000000000000000000000 01000000000000000000000000000000 - revoke_and_ack and mac
+               // 0085 3a00000000000000000000000000000000000000000000000000000000000000 6700000000000000000000000000000000000000000000000000000000000000 026500000000000000000000000000000000000000000000000000000000000000 01000000000000000000000000000000 - revoke_and_ack and mac
                //
                // - before responding to the commitment_signed generated above, send a new HTLC
                // 030012 - inbound read from peer id 0 of len 18
@@ -785,18 +791,18 @@ mod tests {
                // 030012 - inbound read from peer id 0 of len 18
                // 0063 03000000000000000000000000000000 - message header indicating message length 99
                // 030073 - inbound read from peer id 0 of len 115
-               // 0085 3d00000000000000000000000000000000000000000000000000000000000000 0100000000000000000000000000000000000000000000000000000000000000 030300000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000 - revoke_and_ack and mac
+               // 0085 3d00000000000000000000000000000000000000000000000000000000000000 0800000000000000000000000000000000000000000000000000000000000000 020a00000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000 - revoke_and_ack and mac
                // - client should now respond with revoke_and_ack and commitment_signed (CHECK 5/6 duplicates)
                //
                // 030012 - inbound read from peer id 0 of len 18
                // 0064 03000000000000000000000000000000 - message header indicating message length 100
                // 030074 - inbound read from peer id 0 of len 116
-               // 0084 3d00000000000000000000000000000000000000000000000000000000000000 c2000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001 0000 03000000000000000000000000000000 - commitment_signed and mac
+               // 0084 3d00000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000c30100000000000000000000000000000000000000000000000000000000000000 0000 03000000000000000000000000000000 - commitment_signed and mac
                //
                // 030012 - inbound read from peer id 0 of len 18
                // 0063 03000000000000000000000000000000 - message header indicating message length 99
                // 030073 - inbound read from peer id 0 of len 115
-               // 0085 3d00000000000000000000000000000000000000000000000000000000000000 0200000000000000000000000000000000000000000000000000000000000000 030400000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000 - revoke_and_ack and mac
+               // 0085 3d00000000000000000000000000000000000000000000000000000000000000 0b00000000000000000000000000000000000000000000000000000000000000 020d00000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000 - revoke_and_ack and mac
                //
                // 07 - process the now-pending HTLC forward
                // - client now sends id 1 update_add_htlc and commitment_signed (CHECK 7 duplicate)
@@ -805,27 +811,27 @@ mod tests {
                // 030112 - inbound read from peer id 1 of len 18
                // 0064 01000000000000000000000000000000 - message header indicating message length 100
                // 030174 - inbound read from peer id 1 of len 116
-               // 0084 3900000000000000000000000000000000000000000000000000000000000000 fc000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100 0000 01000000000000000000000000000000 - commitment_signed and mac
+               // 0084 3a00000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000390001000000000000000000000000000000000000000000000000000000000000 0000 01000000000000000000000000000000 - commitment_signed and mac
                //
                // 030112 - inbound read from peer id 1 of len 18
                // 0063 01000000000000000000000000000000 - message header indicating message length 99
                // 030173 - inbound read from peer id 1 of len 115
-               // 0085 3900000000000000000000000000000000000000000000000000000000000000 0200000000000000000000000000000000000000000000000000000000000000 030400000000000000000000000000000000000000000000000000000000000000 01000000000000000000000000000000 - revoke_and_ack and mac
+               // 0085 3a00000000000000000000000000000000000000000000000000000000000000 6400000000000000000000000000000000000000000000000000000000000000 027000000000000000000000000000000000000000000000000000000000000000 01000000000000000000000000000000 - revoke_and_ack and mac
                //
                // 030112 - inbound read from peer id 1 of len 18
                // 002c 01000000000000000000000000000000 - message header indicating message length 44
                // 03013c - inbound read from peer id 1 of len 60
-               // 0083 3900000000000000000000000000000000000000000000000000000000000000 0000000000000001 0000 01000000000000000000000000000000 - update_fail_htlc and mac
+               // 0083 3a00000000000000000000000000000000000000000000000000000000000000 0000000000000001 0000 01000000000000000000000000000000 - update_fail_htlc and mac
                //
                // 030112 - inbound read from peer id 1 of len 18
                // 0064 01000000000000000000000000000000 - message header indicating message length 100
                // 030174 - inbound read from peer id 1 of len 116
-               // 0084 3900000000000000000000000000000000000000000000000000000000000000 fb000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100 0000 01000000000000000000000000000000 - commitment_signed and mac
+               // 0084 3a00000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000390001000000000000000000000000000000000000000000000000000000000000 0000 01000000000000000000000000000000 - commitment_signed and mac
                //
                // 030112 - inbound read from peer id 1 of len 18
                // 0063 01000000000000000000000000000000 - message header indicating message length 99
                // 030173 - inbound read from peer id 1 of len 115
-               // 0085 3900000000000000000000000000000000000000000000000000000000000000 0300000000000000000000000000000000000000000000000000000000000000 030500000000000000000000000000000000000000000000000000000000000000 01000000000000000000000000000000 - revoke_and_ack and mac
+               // 0085 3a00000000000000000000000000000000000000000000000000000000000000 6500000000000000000000000000000000000000000000000000000000000000 027100000000000000000000000000000000000000000000000000000000000000 01000000000000000000000000000000 - revoke_and_ack and mac
                //
                // 07 - process the now-pending HTLC forward
                // - client now sends id 0 update_fail_htlc and commitment_signed (CHECK 9)
@@ -834,12 +840,12 @@ mod tests {
                // 030012 - inbound read from peer id 0 of len 18
                // 0063 03000000000000000000000000000000 - message header indicating message length 99
                // 030073 - inbound read from peer id 0 of len 115
-               // 0085 3d00000000000000000000000000000000000000000000000000000000000000 0300000000000000000000000000000000000000000000000000000000000000 030500000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000 - revoke_and_ack and mac
+               // 0085 3d00000000000000000000000000000000000000000000000000000000000000 0a00000000000000000000000000000000000000000000000000000000000000 020c00000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000 - revoke_and_ack and mac
                //
                // 030012 - inbound read from peer id 0 of len 18
                // 0064 03000000000000000000000000000000 - message header indicating message length 100
                // 030074 - inbound read from peer id 0 of len 116
-               // 0084 3d00000000000000000000000000000000000000000000000000000000000000 33000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001 0000 03000000000000000000000000000000 - commitment_signed and mac
+               // 0084 3d00000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000320100000000000000000000000000000000000000000000000000000000000000 0000 03000000000000000000000000000000 - commitment_signed and mac
                // - client should now respond with revoke_and_ack (CHECK 5 duplicate)
                //
                // 030012 - inbound read from peer id 0 of len 18
@@ -862,23 +868,23 @@ mod tests {
                // 030012 - inbound read from peer id 0 of len 18
                // 00a4 03000000000000000000000000000000 - message header indicating message length 164
                // 0300b4 - inbound read from peer id 0 of len 180
-               // 0084 3d00000000000000000000000000000000000000000000000000000000000000 7b000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001 0001 c8000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007f00000000000000 03000000000000000000000000000000 - commitment_signed and mac
+               // 0084 3d00000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000a60100000000000000000000000000000000000000000000000000000000000000 0001 00000000000000000000000000000000000000000000000000000000000000b40500000000000000000000000000000000000000000000000000000000000006 03000000000000000000000000000000 - commitment_signed and mac
                // - client should now respond with revoke_and_ack and commitment_signed (CHECK 5/6 duplicates)
                //
                // 030012 - inbound read from peer id 0 of len 18
                // 0063 03000000000000000000000000000000 - message header indicating message length 99
                // 030073 - inbound read from peer id 0 of len 115
-               // 0085 3d00000000000000000000000000000000000000000000000000000000000000 0400000000000000000000000000000000000000000000000000000000000000 030600000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000 - revoke_and_ack and mac
+               // 0085 3d00000000000000000000000000000000000000000000000000000000000000 0d00000000000000000000000000000000000000000000000000000000000000 020f00000000000000000000000000000000000000000000000000000000000000 03000000000000000000000000000000 - revoke_and_ack and mac
                //
                // 07 - process the now-pending HTLC forward
                // - client now sends id 1 update_add_htlc and commitment_signed (CHECK 7 duplicate)
                //
                // 0c007d - connect a block with one transaction of len 125
-               // 02000000013900000000000000000000000000000000000000000000000000000000000000000000000000000080020001000000000000220020bb000000000000000000000000000000000000000000000000000000000000006cc10000000000001600142b0000000000000000000000000000000000000005000020 - the commitment transaction for channel 3f00000000000000000000000000000000000000000000000000000000000000
+               // 02000000013a0000000000000000000000000000000000000000000000000000000000000000000000000000008002000100000000000022002093000000000000000000000000000000000000000000000000000000000000006cc1000000000000160014280000000000000000000000000000000000000005000020 - the commitment transaction for channel 3f00000000000000000000000000000000000000000000000000000000000000
                // 00fd - A feerate request (returning min feerate, which our open_channel also uses) (gonna be ingested by FuzzEstimator)
                // 00fd - A feerate request (returning min feerate, which our open_channel also uses) (gonna be ingested by FuzzEstimator)
                // 0c005e - connect a block with one transaction of len 94
-               // 0200000001a100000000000000000000000000000000000000000000000000000000000000000000000000000000014f00000000000000220020f60000000000000000000000000000000000000000000000000000000000000000000000 - the HTLC timeout transaction
+               // 02000000018900000000000000000000000000000000000000000000000000000000000000000000000000000000014f00000000000000220020b20000000000000000000000000000000000000000000000000000000000000000000000 - the HTLC timeout transaction
                // 0c0000 - connect a block with no transactions
                // 0c0000 - connect a block with no transactions
                // 00fd - A feerate request (returning min feerate, which our open_channel also uses) (gonna be ingested by FuzzEstimator)
@@ -890,18 +896,18 @@ mod tests {
                // - client now fails the HTLC backwards as it was unable to extract the payment preimage (CHECK 9 duplicate and CHECK 10)
 
                let logger = Arc::new(TrackingLogger { lines: Mutex::new(HashMap::new()) });
-               super::do_test(&::hex::decode("00000000000000000000000000000000000000000000000000000000000000000000000001000300000000000000000000000000000000000000000000000000000000000000000300320003000000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000030012000a0300000000000000000000000000000003001a00100002200000022000030000000000000000000000000000000300120141030000000000000000000000000000000300fe00207500000000000000000000000000000000000000000000000000000000000000ff4f00f805273c1b203bb5ebf8436bfde57b3be8c2f5e95d9491dbb181909679000000000000c35000000000000000000000000000000222ffffffffffffffff00000000000002220000000000000000000000fd000601e3030000000000000000000000000000000000000000000000000000000000000001030000000000000000000000000000000000000000000000000000000000000002030000000000000000000000000000000000000000000000000000000000000003030000000000000000000000000000000000000000000000000000000000000004030053030000000000000000000000000000000000000000000000000000000000000005030000000000000000000000000000000000000000000000000000000000000000010300000000000000000000000000000000fd00fd00fd0300120084030000000000000000000000000000000300940022ff4f00f805273c1b203bb5ebf8436bfde57b3be8c2f5e95d9491dbb1819096793d00000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001030000000000000000000000000000000c005e020000000100000000000000000000000000000000000000000000000000000000000000000000000000ffffffff0150c3000000000000220020ae00000000000000000000000000000000000000000000000000000000000000000000000c00000c00000c00000c00000c00000c00000c00000c00000c00000c00000c00000c000003001200430300000000000000000000000000000003005300243d0000000000000000000000000000000000000000000000000000000000000003010000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000010301320003000000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000030142000302000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000003000000000000000000000000000000030112000a0100000000000000000000000000000003011a0010000220000002200001000000000000000000000000000000050103020000000000000000000000000000000000000000000000000000000000000000c3500003e800fd00fd0301120110010000000000000000000000000000000301ff00210000000000000000000000000000000000000000000000000000000000000e02000000000000001a00000000004c4b4000000000000003e800000000000003e80000000203f00005030000000000000000000000000000000000000000000000000000000000000100030000000000000000000000000000000000000000000000000000000000000200030000000000000000000000000000000000000000000000000000000000000300030000000000000000000000000000000000000000000000000000000000000400030000000000000000000000000000000000000000000000000000000000000500030000000000000000000000000000000301210000000000000000000000000000000000010000000000000000000000000000000a03011200620100000000000000000000000000000003017200233900000000000000000000000000000000000000000000000000000000000000f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100010000000000000000000000000000000b030112004301000000000000000000000000000000030153002439000000000000000000000000000000000000000000000000000000000000000301000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000003001205ac030000000000000000000000000000000300ff00803d0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003e80ff0000000000000000000000000000000000000000000000000000000000000000000121000300000000000000000000000000000000000000000000000000000000000005550000000e000001000000000000000003e80000007b0000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300c1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff95000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000000fd03001200640300000000000000000000000000000003007400843d000000000000000000000000000000000000000000000000000000000000003100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000300000000000000000000000000000003001200630300000000000000000000000000000003007300853d000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000030200000000000000000000000000000000000000000000000000000000000000030000000000000000000000000000000703011200640100000000000000000000000000000003017400843900000000000000000000000000000000000000000000000000000000000000f100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000100000000000000000000000000000003011200630100000000000000000000000000000003017300853900000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003020000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000030112004a0100000000000000000000000000000003015a008239000000000000000000000000000000000000000000000000000000000000000000000000000000ff008888888888888888888888888888888888888888888888888888888888880100000000000000000000000000000003011200640100000000000000000000000000000003017400843900000000000000000000000000000000000000000000000000000000000000fd0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000010000000000000000000000000000000301120063010000000000000000000000000000000301730085390000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000303000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000003001205ac030000000000000000000000000000000300ff00803d0000000000000000000000000000000000000000000000000000000000000000000000000000010000000000003e80ff0000000000000000000000000000000000000000000000000000000000000000000121000300000000000000000000000000000000000000000000000000000000000005550000000e000001000000000000000003e80000007b0000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300c1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff95000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000000fd03001200630300000000000000000000000000000003007300853d0000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000303000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000003001200640300000000000000000000000000000003007400843d00000000000000000000000000000000000000000000000000000000000000c200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000300000000000000000000000000000003001200630300000000000000000000000000000003007300853d000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000030400000000000000000000000000000000000000000000000000000000000000030000000000000000000000000000000703011200640100000000000000000000000000000003017400843900000000000000000000000000000000000000000000000000000000000000fc00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000100000000000000000000000000000003011200630100000000000000000000000000000003017300853900000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000003040000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000030112002c0100000000000000000000000000000003013c00833900000000000000000000000000000000000000000000000000000000000000000000000000000100000100000000000000000000000000000003011200640100000000000000000000000000000003017400843900000000000000000000000000000000000000000000000000000000000000fb000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000001000000000000000000000000000000030112006301000000000000000000000000000000030173008539000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000000000000000000000000000000000000030500000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000703001200630300000000000000000000000000000003007300853d0000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000000305000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000003001200640300000000000000000000000000000003007400843d000000000000000000000000000000000000000000000000000000000000003300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000300000000000000000000000000000003001205ac030000000000000000000000000000000300ff00803d00000000000000000000000000000000000000000000000000000000000000000000000000000200000000000b0838ff0000000000000000000000000000000000000000000000000000000000000000000121000300000000000000000000000000000000000000000000000000000000000005550000000e0000010000000000000003e8000000007b0000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300c1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff95000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000000fd03001200a4030000000000000000000000000000000300b400843d000000000000000000000000000000000000000000000000000000000000007b0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010001c8000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007f000000000000000300000000000000000000000000000003001200630300000000000000000000000000000003007300853d00000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000003060000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000070c007d02000000013900000000000000000000000000000000000000000000000000000000000000000000000000000080020001000000000000220020bb000000000000000000000000000000000000000000000000000000000000006cc10000000000001600142b000000000000000000000000000000000000000500002000fd00fd0c005e0200000001a100000000000000000000000000000000000000000000000000000000000000000000000000000000014f00000000000000220020f600000000000000000000000000000000000000000000000000000000000000000000000c00000c000000fd0c00000c00000c000007").unwrap(), &(Arc::clone(&logger) as Arc<dyn Logger>));
+               super::do_test(&::hex::decode("01000000000000000000000000000000000000000000000000000000000000000000000001000300000000000000000000000000000000000000000000000000000000000000020300320003000000000000000000000000000000000000000000000000000000000000000203000000000000000000000000000000030012000a0300000000000000000000000000000003001a00100002200000022000030000000000000000000000000000000300120141030000000000000000000000000000000300fe00207500000000000000000000000000000000000000000000000000000000000000ff4f00f805273c1b203bb5ebf8436bfde57b3be8c2f5e95d9491dbb181909679000000000000c35000000000000000000000000000000222ffffffffffffffff00000000000002220000000000000000000000fd000601e3030000000000000000000000000000000000000000000000000000000000000001030000000000000000000000000000000000000000000000000000000000000002030000000000000000000000000000000000000000000000000000000000000003030000000000000000000000000000000000000000000000000000000000000004030053030000000000000000000000000000000000000000000000000000000000000005020900000000000000000000000000000000000000000000000000000000000000010300000000000000000000000000000000fd00fd00fd0300120084030000000000000000000000000000000300940022ff4f00f805273c1b203bb5ebf8436bfde57b3be8c2f5e95d9491dbb1819096793d00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000210100000000000000000000000000000000000000000000000000000000000000030000000000000000000000000000000c005e020000000100000000000000000000000000000000000000000000000000000000000000000000000000ffffffff0150c3000000000000220020ae00000000000000000000000000000000000000000000000000000000000000000000000c00000c00000c00000c00000c00000c00000c00000c00000c00000c00000c00000c000003001200430300000000000000000000000000000003005300243d0000000000000000000000000000000000000000000000000000000000000002080000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000010301320003000000000000000000000000000000000000000000000000000000000000000703000000000000000000000000000000030142000302000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000003000000000000000000000000000000030112000a0100000000000000000000000000000003011a0010000220000002200001000000000000000000000000000000050103020000000000000000000000000000000000000000000000000000000000000000c3500003e800fd00fd0301120110010000000000000000000000000000000301ff00210000000000000000000000000000000000000000000000000000000000000e05000000000000001a00000000004c4b4000000000000003e800000000000003e80000000203f00005030000000000000000000000000000000000000000000000000000000000000100030000000000000000000000000000000000000000000000000000000000000200030000000000000000000000000000000000000000000000000000000000000300030000000000000000000000000000000000000000000000000000000000000400030000000000000000000000000000000000000000000000000000000000000500026600000000000000000000000000000301210000000000000000000000000000000000010000000000000000000000000000000a03011200620100000000000000000000000000000003017200233a00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007c0001000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000b03011200430100000000000000000000000000000003015300243a000000000000000000000000000000000000000000000000000000000000000267000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000003001205ac030000000000000000000000000000000300ff00803d0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003e80ff0000000000000000000000000000000000000000000000000000000000000000000121000300000000000000000000000000000000000000000000000000000000000005550000000e000001000000000000000003e80000007b0000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300c1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff95000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000000fd03001200640300000000000000000000000000000003007400843d000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000030010000000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000003001200630300000000000000000000000000000003007300853d000000000000000000000000000000000000000000000000000000000000000900000000000000000000000000000000000000000000000000000000000000020b00000000000000000000000000000000000000000000000000000000000000030000000000000000000000000000000703011200640100000000000000000000000000000003017400843a00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006a000100000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000003011200630100000000000000000000000000000003017300853a00000000000000000000000000000000000000000000000000000000000000660000000000000000000000000000000000000000000000000000000000000002640000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000030112004a0100000000000000000000000000000003015a00823a000000000000000000000000000000000000000000000000000000000000000000000000000000ff008888888888888888888888888888888888888888888888888888888888880100000000000000000000000000000003011200640100000000000000000000000000000003017400843a000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000100000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000003011200630100000000000000000000000000000003017300853a0000000000000000000000000000000000000000000000000000000000000067000000000000000000000000000000000000000000000000000000000000000265000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000003001205ac030000000000000000000000000000000300ff00803d0000000000000000000000000000000000000000000000000000000000000000000000000000010000000000003e80ff0000000000000000000000000000000000000000000000000000000000000000000121000300000000000000000000000000000000000000000000000000000000000005550000000e000001000000000000000003e80000007b0000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300c1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff95000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000000fd03001200630300000000000000000000000000000003007300853d000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000020a000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000003001200640300000000000000000000000000000003007400843d0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c3010000000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000003001200630300000000000000000000000000000003007300853d000000000000000000000000000000000000000000000000000000000000000b00000000000000000000000000000000000000000000000000000000000000020d00000000000000000000000000000000000000000000000000000000000000030000000000000000000000000000000703011200640100000000000000000000000000000003017400843a000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000039000100000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000003011200630100000000000000000000000000000003017300853a00000000000000000000000000000000000000000000000000000000000000640000000000000000000000000000000000000000000000000000000000000002700000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000030112002c0100000000000000000000000000000003013c00833a00000000000000000000000000000000000000000000000000000000000000000000000000000100000100000000000000000000000000000003011200640100000000000000000000000000000003017400843a000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000039000100000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000003011200630100000000000000000000000000000003017300853a000000000000000000000000000000000000000000000000000000000000006500000000000000000000000000000000000000000000000000000000000000027100000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000703001200630300000000000000000000000000000003007300853d000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000020c000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000003001200640300000000000000000000000000000003007400843d000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000032010000000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000003001205ac030000000000000000000000000000000300ff00803d00000000000000000000000000000000000000000000000000000000000000000000000000000200000000000b0838ff0000000000000000000000000000000000000000000000000000000000000000000121000300000000000000000000000000000000000000000000000000000000000005550000000e0000010000000000000003e8000000007b0000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0300c1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff95000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000000fd03001200a4030000000000000000000000000000000300b400843d0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000a60100000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000b405000000000000000000000000000000000000000000000000000000000000060300000000000000000000000000000003001200630300000000000000000000000000000003007300853d000000000000000000000000000000000000000000000000000000000000000d00000000000000000000000000000000000000000000000000000000000000020f0000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000070c007d02000000013a0000000000000000000000000000000000000000000000000000000000000000000000000000008002000100000000000022002093000000000000000000000000000000000000000000000000000000000000006cc100000000000016001428000000000000000000000000000000000000000500002000fd00fd0c005e02000000018900000000000000000000000000000000000000000000000000000000000000000000000000000000014f00000000000000220020b200000000000000000000000000000000000000000000000000000000000000000000000c00000c000000fd0c00000c00000c000007").unwrap(), &(Arc::clone(&logger) as Arc<dyn Logger>));
 
                let log_entries = logger.lines.lock().unwrap();
-               assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling SendAcceptChannel event in peer_handler for node 030000000000000000000000000000000000000000000000000000000000000000 for channel ff4f00f805273c1b203bb5ebf8436bfde57b3be8c2f5e95d9491dbb181909679".to_string())), Some(&1)); // 1
-               assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling SendFundingSigned event in peer_handler for node 030000000000000000000000000000000000000000000000000000000000000000 for channel 3d00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&1)); // 2
-               assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling SendFundingLocked event in peer_handler for node 030000000000000000000000000000000000000000000000000000000000000000 for channel 3d00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&1)); // 3
-               assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling SendFundingLocked event in peer_handler for node 030200000000000000000000000000000000000000000000000000000000000000 for channel 3900000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&1)); // 4
-               assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling SendRevokeAndACK event in peer_handler for node 030000000000000000000000000000000000000000000000000000000000000000 for channel 3d00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&4)); // 5
-               assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling UpdateHTLCs event in peer_handler for node 030000000000000000000000000000000000000000000000000000000000000000 with 0 adds, 0 fulfills, 0 fails for channel 3d00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&3)); // 6
-               assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling UpdateHTLCs event in peer_handler for node 030200000000000000000000000000000000000000000000000000000000000000 with 1 adds, 0 fulfills, 0 fails for channel 3900000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&3)); // 7
-               assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling UpdateHTLCs event in peer_handler for node 030000000000000000000000000000000000000000000000000000000000000000 with 0 adds, 1 fulfills, 0 fails for channel 3d00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&1)); // 8
-               assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling UpdateHTLCs event in peer_handler for node 030000000000000000000000000000000000000000000000000000000000000000 with 0 adds, 0 fulfills, 1 fails for channel 3d00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&2)); // 9
-               assert_eq!(log_entries.get(&("lightning::chain::channelmonitor".to_string(), "Input spending counterparty commitment tx (00000000000000000000000000000000000000000000000000000000000000a1:0) in 0000000000000000000000000000000000000000000000000000000000000018 resolves outbound HTLC with payment hash ff00000000000000000000000000000000000000000000000000000000000000 with timeout".to_string())), Some(&1)); // 10
+               assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling SendAcceptChannel event in peer_handler for node 030000000000000000000000000000000000000000000000000000000000000002 for channel ff4f00f805273c1b203bb5ebf8436bfde57b3be8c2f5e95d9491dbb181909679".to_string())), Some(&1)); // 1
+               assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling SendFundingSigned event in peer_handler for node 030000000000000000000000000000000000000000000000000000000000000002 for channel 3d00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&1)); // 2
+               assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling SendFundingLocked event in peer_handler for node 030000000000000000000000000000000000000000000000000000000000000002 for channel 3d00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&1)); // 3
+               assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling SendFundingLocked event in peer_handler for node 030200000000000000000000000000000000000000000000000000000000000000 for channel 3a00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&1)); // 4
+               assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling SendRevokeAndACK event in peer_handler for node 030000000000000000000000000000000000000000000000000000000000000002 for channel 3d00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&4)); // 5
+               assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling UpdateHTLCs event in peer_handler for node 030000000000000000000000000000000000000000000000000000000000000002 with 0 adds, 0 fulfills, 0 fails for channel 3d00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&3)); // 6
+               assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling UpdateHTLCs event in peer_handler for node 030200000000000000000000000000000000000000000000000000000000000000 with 1 adds, 0 fulfills, 0 fails for channel 3a00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&3)); // 7
+               assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling UpdateHTLCs event in peer_handler for node 030000000000000000000000000000000000000000000000000000000000000002 with 0 adds, 1 fulfills, 0 fails for channel 3d00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&1)); // 8
+               assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling UpdateHTLCs event in peer_handler for node 030000000000000000000000000000000000000000000000000000000000000002 with 0 adds, 0 fulfills, 1 fails for channel 3d00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&2)); // 9
+               assert_eq!(log_entries.get(&("lightning::chain::channelmonitor".to_string(), "Input spending counterparty commitment tx (0000000000000000000000000000000000000000000000000000000000000089:0) in 0000000000000000000000000000000000000000000000000000000000000074 resolves outbound HTLC with payment hash ff00000000000000000000000000000000000000000000000000000000000000 with timeout".to_string())), Some(&1)); // 10
        }
 }
index 51602d5b5e8845c87560cd0ab0beb04bdb9270a6..fa1cceb8a16487c45dcd468d4e47b7a13eda047a 100644 (file)
@@ -130,7 +130,7 @@ pub fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
                                        msgs::DecodeError::InvalidValue => return,
                                        msgs::DecodeError::BadLengthDescriptor => return,
                                        msgs::DecodeError::ShortRead => panic!("We picked the length..."),
-                                       msgs::DecodeError::Io(e) => panic!(format!("{}", e)),
+                                       msgs::DecodeError::Io(e) => panic!(format!("{:?}", e)),
                                }
                        }
                }}
index 0bd60911efe84afc4ca05f028d7a936106934494..9cb5b60b6a851f2546513fe4697336c690ab7229 100644 (file)
@@ -1,14 +1,14 @@
 use lightning::chain::channelmonitor;
 use lightning::chain::transaction::OutPoint;
-use lightning::util::enforcing_trait_impls::EnforcingChannelKeys;
+use lightning::util::enforcing_trait_impls::EnforcingSigner;
 
 pub struct TestPersister {}
-impl channelmonitor::Persist<EnforcingChannelKeys> for TestPersister {
-       fn persist_new_channel(&self, _funding_txo: OutPoint, _data: &channelmonitor::ChannelMonitor<EnforcingChannelKeys>) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
+impl channelmonitor::Persist<EnforcingSigner> for TestPersister {
+       fn persist_new_channel(&self, _funding_txo: OutPoint, _data: &channelmonitor::ChannelMonitor<EnforcingSigner>) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
                Ok(())
        }
 
-       fn update_persisted_channel(&self, _funding_txo: OutPoint, _update: &channelmonitor::ChannelMonitorUpdate, _data: &channelmonitor::ChannelMonitor<EnforcingChannelKeys>) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
+       fn update_persisted_channel(&self, _funding_txo: OutPoint, _update: &channelmonitor::ChannelMonitorUpdate, _data: &channelmonitor::ChannelMonitor<EnforcingSigner>) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
                Ok(())
        }
 }
index ae2a23578f05dd7fa5ec7d02de2452a0b97c92e4..bfeda6bcdaebac000f32e4d1968355395c314821 100755 (executable)
@@ -6,7 +6,7 @@ set -x
 # Generate (and reasonably test) C bindings
 
 # First build the latest c-bindings-gen binary
-cd c-bindings-gen && cargo build && cd ..
+cd c-bindings-gen && cargo build --release && cd ..
 
 # Then wipe all the existing C bindings (because we're being run in the right directory)
 # note that we keep the few manually-generated files first:
@@ -20,12 +20,15 @@ mv ./mod.rs lightning-c-bindings/src/c_types/
 mv ./bitcoin lightning-c-bindings/src/
 
 # Finally, run the c-bindings-gen binary, building fresh bindings.
-SRC="$(pwd)/lightning/src"
 OUT="$(pwd)/lightning-c-bindings/src"
 OUT_TEMPL="$(pwd)/lightning-c-bindings/src/c_types/derived.rs"
 OUT_F="$(pwd)/lightning-c-bindings/include/rust_types.h"
 OUT_CPP="$(pwd)/lightning-c-bindings/include/lightningpp.hpp"
-RUST_BACKTRACE=1 ./c-bindings-gen/target/debug/c-bindings-gen $SRC/ $OUT/ lightning $OUT_TEMPL $OUT_F $OUT_CPP
+
+cd lightning
+RUSTC_BOOTSTRAP=1 cargo rustc --profile=check -- -Zunstable-options --pretty=expanded |
+       RUST_BACKTRACE=1 ../c-bindings-gen/target/release/c-bindings-gen $OUT/ lightning $OUT_TEMPL $OUT_F $OUT_CPP
+cd ..
 
 # Now cd to lightning-c-bindings, build the generated bindings, and call cbindgen to build a C header file
 PATH="$PATH:~/.cargo/bin"
@@ -41,18 +44,28 @@ HOST_PLATFORM="$(rustc --version --verbose | grep "host:")"
 if [ "$HOST_PLATFORM" = "host: x86_64-apple-darwin" ]; then
        # OSX sed is for some reason not compatible with GNU sed
        sed -i '' 's/typedef LDKnative.*Import.*LDKnative.*;//g' include/lightning.h
+
+       # stdlib.h doesn't exist in clang's wasm sysroot, and cbindgen
+       # doesn't actually use it anyway, so drop the import.
+       sed -i '' 's/#include <stdlib.h>//g' include/lightning.h
 else
        sed -i 's/typedef LDKnative.*Import.*LDKnative.*;//g' include/lightning.h
+
+       # stdlib.h doesn't exist in clang's wasm sysroot, and cbindgen
+       # doesn't actually use it anyway, so drop the import.
+       sed -i 's/#include <stdlib.h>//g' include/lightning.h
 fi
 
 # Finally, sanity-check the generated C and C++ bindings with demo apps:
 
+CFLAGS="-Wall -Wno-nullability-completeness -pthread"
+
 # Naively run the C demo app:
-gcc -Wall -g -pthread demo.c target/debug/libldk.a -ldl
+gcc $CFLAGS -Wall -g -pthread demo.c target/debug/libldk.a -ldl
 ./a.out
 
 # And run the C++ demo app in valgrind to test memory model correctness and lack of leaks.
-g++ -std=c++11 -Wall -g -pthread demo.cpp -Ltarget/debug/ -lldk -ldl
+g++ $CFLAGS -std=c++11 -Wall -g -pthread demo.cpp -Ltarget/debug/ -lldk -ldl
 if [ -x "`which valgrind`" ]; then
        LD_LIBRARY_PATH=target/debug/ valgrind --error-exitcode=4 --memcheck:leak-check=full --show-leak-kinds=all ./a.out
        echo
@@ -62,8 +75,8 @@ fi
 
 # Test a statically-linked C++ version, tracking the resulting binary size and runtime
 # across debug, LTO, and cross-language LTO builds (using the same compiler each time).
-clang++ -std=c++11 -Wall -pthread demo.cpp target/debug/libldk.a -ldl
-./a.out >/dev/null
+clang++ $CFLAGS -std=c++11 demo.cpp target/debug/libldk.a -ldl
+strip ./a.out
 echo " C++ Bin size and runtime w/o optimization:"
 ls -lha a.out
 time ./a.out > /dev/null
@@ -83,11 +96,11 @@ if [ "$HOST_PLATFORM" = "host: x86_64-unknown-linux-gnu" ]; then
                        set +e
 
                        # First the C demo app...
-                       clang-$LLVM_V -std=c++11 -fsanitize=memory -fsanitize-memory-track-origins -Wall -g -pthread demo.c target/debug/libldk.a -ldl
+                       clang-$LLVM_V $CFLAGS -fsanitize=memory -fsanitize-memory-track-origins -g demo.c target/debug/libldk.a -ldl
                        ./a.out
 
                        # ...then the C++ demo app
-                       clang++-$LLVM_V -std=c++11 -fsanitize=memory -fsanitize-memory-track-origins -Wall -g -pthread demo.cpp target/debug/libldk.a -ldl
+                       clang++-$LLVM_V $CFLAGS -std=c++11 -fsanitize=memory -fsanitize-memory-track-origins -g demo.cpp target/debug/libldk.a -ldl
                        ./a.out >/dev/null
 
                        # restore exit-on-failure
@@ -153,11 +166,11 @@ if [ "$HOST_PLATFORM" = "host: x86_64-unknown-linux-gnu" -o "$HOST_PLATFORM" = "
                mv Cargo.toml.bk Cargo.toml
 
                # First the C demo app...
-               $CLANG -fsanitize=address -Wall -g -pthread demo.c target/debug/libldk.a -ldl
+               $CLANG $CFLAGS -fsanitize=address -g demo.c target/debug/libldk.a -ldl
                ASAN_OPTIONS='detect_leaks=1 detect_invalid_pointer_pairs=1 detect_stack_use_after_return=1' ./a.out
 
                # ...then the C++ demo app
-               $CLANGPP -std=c++11 -fsanitize=address -Wall -g -pthread demo.cpp target/debug/libldk.a -ldl
+               $CLANGPP $CFLAGS -std=c++11 -fsanitize=address -g demo.cpp target/debug/libldk.a -ldl
                ASAN_OPTIONS='detect_leaks=1 detect_invalid_pointer_pairs=1 detect_stack_use_after_return=1' ./a.out >/dev/null
        else
                echo "WARNING: Please install clang-$RUSTC_LLVM_V and clang++-$RUSTC_LLVM_V to build with address sanitizer"
@@ -166,9 +179,13 @@ else
        echo "WARNING: Can't use address sanitizer on non-Linux, non-OSX non-x86 platforms"
 fi
 
+cargo rustc -v --target=wasm32-wasi -- -C embed-bitcode=yes || echo "WARNING: Failed to generate WASM LLVM-bitcode-embedded library"
+CARGO_PROFILE_RELEASE_LTO=true cargo rustc -v --release --target=wasm32-wasi -- -C opt-level=s -C linker-plugin-lto -C lto || echo "WARNING: Failed to generate WASM LLVM-bitcode-embedded optimized library"
+
 # Now build with LTO on on both C++ and rust, but without cross-language LTO:
 CARGO_PROFILE_RELEASE_LTO=true cargo rustc -v --release -- -C lto
-clang++ -std=c++11 -Wall -flto -O2 -pthread demo.cpp target/release/libldk.a -ldl
+clang++ $CFLAGS -std=c++11 -flto -O2 demo.cpp target/release/libldk.a -ldl
+strip ./a.out
 echo "C++ Bin size and runtime with only RL (LTO) optimized:"
 ls -lha a.out
 time ./a.out > /dev/null
@@ -180,7 +197,8 @@ if [ "$HOST_PLATFORM" != "host: x86_64-apple-darwin" -a "$CLANGPP" != "" ]; then
        # packaging than simply shipping the rustup binaries (eg Debian should Just Work
        # here).
        CARGO_PROFILE_RELEASE_LTO=true cargo rustc -v --release -- -C linker-plugin-lto -C lto -C link-arg=-fuse-ld=lld
-       $CLANGPP -Wall -std=c++11 -flto -fuse-ld=lld -O2 -pthread demo.cpp target/release/libldk.a -ldl
+       $CLANGPP $CFLAGS -flto -fuse-ld=lld -O2 demo.cpp target/release/libldk.a -ldl
+       strip ./a.out
        echo "C++ Bin size and runtime with cross-language LTO:"
        ls -lha a.out
        time ./a.out > /dev/null
diff --git a/lightning-block-sync/Cargo.toml b/lightning-block-sync/Cargo.toml
new file mode 100644 (file)
index 0000000..c454de3
--- /dev/null
@@ -0,0 +1,25 @@
+[package]
+name = "lightning-block-sync"
+version = "0.0.1"
+authors = ["Jeffrey Czyz", "Matt Corallo"]
+license = "Apache-2.0"
+edition = "2018"
+description = """
+Utilities to fetch the chain data from a block source and feed them into Rust Lightning.
+"""
+
+[features]
+rest-client = [ "serde", "serde_json", "chunked_transfer" ]
+rpc-client = [ "serde", "serde_json", "chunked_transfer" ]
+
+[dependencies]
+bitcoin = "0.26"
+lightning = { version = "0.0.12", path = "../lightning" }
+tokio = { version = "1.0", features = [ "io-util", "net" ], optional = true }
+serde = { version = "1.0", features = ["derive"], optional = true }
+serde_json = { version = "1.0", optional = true }
+chunked_transfer = { version = "1.4", optional = true }
+futures = { version = "0.3" }
+
+[dev-dependencies]
+tokio = { version = "1.0", features = [ "macros", "rt" ] }
diff --git a/lightning-block-sync/src/convert.rs b/lightning-block-sync/src/convert.rs
new file mode 100644 (file)
index 0000000..37b2c43
--- /dev/null
@@ -0,0 +1,472 @@
+use crate::{BlockHeaderData, BlockSourceError};
+use crate::http::{BinaryResponse, JsonResponse};
+use crate::utils::hex_to_uint256;
+
+use bitcoin::blockdata::block::{Block, BlockHeader};
+use bitcoin::consensus::encode;
+use bitcoin::hash_types::{BlockHash, TxMerkleNode};
+use bitcoin::hashes::hex::{ToHex, FromHex};
+
+use serde::Deserialize;
+
+use serde_json;
+
+use std::convert::From;
+use std::convert::TryFrom;
+use std::convert::TryInto;
+
+/// Conversion from `std::io::Error` into `BlockSourceError`.
+impl From<std::io::Error> for BlockSourceError {
+       fn from(e: std::io::Error) -> BlockSourceError {
+               match e.kind() {
+                       std::io::ErrorKind::InvalidData => BlockSourceError::persistent(e),
+                       std::io::ErrorKind::InvalidInput => BlockSourceError::persistent(e),
+                       _ => BlockSourceError::transient(e),
+               }
+       }
+}
+
+/// Parses binary data as a block.
+impl TryInto<Block> for BinaryResponse {
+       type Error = std::io::Error;
+
+       fn try_into(self) -> std::io::Result<Block> {
+               match encode::deserialize(&self.0) {
+                       Err(_) => return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid block data")),
+                       Ok(block) => Ok(block),
+               }
+       }
+}
+
+/// Converts a JSON value into block header data. The JSON value may be an object representing a
+/// block header or an array of such objects. In the latter case, the first object is converted.
+impl TryInto<BlockHeaderData> for JsonResponse {
+       type Error = std::io::Error;
+
+       fn try_into(self) -> std::io::Result<BlockHeaderData> {
+               let mut header = match self.0 {
+                       serde_json::Value::Array(mut array) if !array.is_empty() => array.drain(..).next().unwrap(),
+                       serde_json::Value::Object(_) => self.0,
+                       _ => return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "unexpected JSON type")),
+               };
+
+               if !header.is_object() {
+                       return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "expected JSON object"));
+               }
+
+               // Add an empty previousblockhash for the genesis block.
+               if let None = header.get("previousblockhash") {
+                       let hash: BlockHash = Default::default();
+                       header.as_object_mut().unwrap().insert("previousblockhash".to_string(), serde_json::json!(hash.to_hex()));
+               }
+
+               match serde_json::from_value::<GetHeaderResponse>(header) {
+                       Err(_) => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid header response")),
+                       Ok(response) => match response.try_into() {
+                               Err(_) => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid header data")),
+                               Ok(header) => Ok(header),
+                       },
+               }
+       }
+}
+
+/// Response data from `getblockheader` RPC and `headers` REST requests.
+#[derive(Deserialize)]
+struct GetHeaderResponse {
+       pub version: i32,
+       pub merkleroot: String,
+       pub time: u32,
+       pub nonce: u32,
+       pub bits: String,
+       pub previousblockhash: String,
+
+       pub chainwork: String,
+       pub height: u32,
+}
+
+/// Converts from `GetHeaderResponse` to `BlockHeaderData`.
+impl TryFrom<GetHeaderResponse> for BlockHeaderData {
+       type Error = bitcoin::hashes::hex::Error;
+
+       fn try_from(response: GetHeaderResponse) -> Result<Self, bitcoin::hashes::hex::Error> {
+               Ok(BlockHeaderData {
+                       header: BlockHeader {
+                               version: response.version,
+                               prev_blockhash: BlockHash::from_hex(&response.previousblockhash)?,
+                               merkle_root: TxMerkleNode::from_hex(&response.merkleroot)?,
+                               time: response.time,
+                               bits: u32::from_be_bytes(<[u8; 4]>::from_hex(&response.bits)?),
+                               nonce: response.nonce,
+                       },
+                       chainwork: hex_to_uint256(&response.chainwork)?,
+                       height: response.height,
+               })
+       }
+}
+
+
+/// Converts a JSON value into a block. Assumes the block is hex-encoded in a JSON string.
+impl TryInto<Block> for JsonResponse {
+       type Error = std::io::Error;
+
+       fn try_into(self) -> std::io::Result<Block> {
+               match self.0.as_str() {
+                       None => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "expected JSON string")),
+                       Some(hex_data) => match Vec::<u8>::from_hex(hex_data) {
+                               Err(_) => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid hex data")),
+                               Ok(block_data) => match encode::deserialize(&block_data) {
+                                       Err(_) => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid block data")),
+                                       Ok(block) => Ok(block),
+                               },
+                       },
+               }
+       }
+}
+
+/// Converts a JSON value into the best block hash and optional height.
+impl TryInto<(BlockHash, Option<u32>)> for JsonResponse {
+       type Error = std::io::Error;
+
+       fn try_into(self) -> std::io::Result<(BlockHash, Option<u32>)> {
+               if !self.0.is_object() {
+                       return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "expected JSON object"));
+               }
+
+               let hash = match &self.0["bestblockhash"] {
+                       serde_json::Value::String(hex_data) => match BlockHash::from_hex(&hex_data) {
+                               Err(_) => return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid hex data")),
+                               Ok(block_hash) => block_hash,
+                       },
+                       _ => return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "expected JSON string")),
+               };
+
+               let height = match &self.0["blocks"] {
+                       serde_json::Value::Null => None,
+                       serde_json::Value::Number(height) => match height.as_u64() {
+                               None => return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid height")),
+                               Some(height) => match height.try_into() {
+                                       Err(_) => return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid height")),
+                                       Ok(height) => Some(height),
+                               }
+                       },
+                       _ => return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "expected JSON number")),
+               };
+
+               Ok((hash, height))
+       }
+}
+
+#[cfg(test)]
+pub(crate) mod tests {
+       use super::*;
+       use bitcoin::blockdata::constants::genesis_block;
+       use bitcoin::consensus::encode;
+       use bitcoin::network::constants::Network;
+
+       /// Converts from `BlockHeaderData` into a `GetHeaderResponse` JSON value.
+       impl From<BlockHeaderData> for serde_json::Value {
+               fn from(data: BlockHeaderData) -> Self {
+                       let BlockHeaderData { chainwork, height, header } = data;
+                       serde_json::json!({
+                               "chainwork": chainwork.to_string()["0x".len()..],
+                               "height": height,
+                               "version": header.version,
+                               "merkleroot": header.merkle_root.to_hex(),
+                               "time": header.time,
+                               "nonce": header.nonce,
+                               "bits": header.bits.to_hex(),
+                               "previousblockhash": header.prev_blockhash.to_hex(),
+                       })
+               }
+       }
+
+       #[test]
+       fn into_block_header_from_json_response_with_unexpected_type() {
+               let response = JsonResponse(serde_json::json!(42));
+               match TryInto::<BlockHeaderData>::try_into(response) {
+                       Err(e) => {
+                               assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
+                               assert_eq!(e.get_ref().unwrap().to_string(), "unexpected JSON type");
+                       },
+                       Ok(_) => panic!("Expected error"),
+               }
+       }
+
+       #[test]
+       fn into_block_header_from_json_response_with_unexpected_header_type() {
+               let response = JsonResponse(serde_json::json!([42]));
+               match TryInto::<BlockHeaderData>::try_into(response) {
+                       Err(e) => {
+                               assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
+                               assert_eq!(e.get_ref().unwrap().to_string(), "expected JSON object");
+                       },
+                       Ok(_) => panic!("Expected error"),
+               }
+       }
+
+       #[test]
+       fn into_block_header_from_json_response_with_invalid_header_response() {
+               let block = genesis_block(Network::Bitcoin);
+               let mut response = JsonResponse(BlockHeaderData {
+                       chainwork: block.header.work(),
+                       height: 0,
+                       header: block.header
+               }.into());
+               response.0["chainwork"].take();
+
+               match TryInto::<BlockHeaderData>::try_into(response) {
+                       Err(e) => {
+                               assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
+                               assert_eq!(e.get_ref().unwrap().to_string(), "invalid header response");
+                       },
+                       Ok(_) => panic!("Expected error"),
+               }
+       }
+
+       #[test]
+       fn into_block_header_from_json_response_with_invalid_header_data() {
+               let block = genesis_block(Network::Bitcoin);
+               let mut response = JsonResponse(BlockHeaderData {
+                       chainwork: block.header.work(),
+                       height: 0,
+                       header: block.header
+               }.into());
+               response.0["chainwork"] = serde_json::json!("foobar");
+
+               match TryInto::<BlockHeaderData>::try_into(response) {
+                       Err(e) => {
+                               assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
+                               assert_eq!(e.get_ref().unwrap().to_string(), "invalid header data");
+                       },
+                       Ok(_) => panic!("Expected error"),
+               }
+       }
+
+       #[test]
+       fn into_block_header_from_json_response_with_valid_header() {
+               let block = genesis_block(Network::Bitcoin);
+               let response = JsonResponse(BlockHeaderData {
+                       chainwork: block.header.work(),
+                       height: 0,
+                       header: block.header
+               }.into());
+
+               match TryInto::<BlockHeaderData>::try_into(response) {
+                       Err(e) => panic!("Unexpected error: {:?}", e),
+                       Ok(data) => {
+                               assert_eq!(data.chainwork, block.header.work());
+                               assert_eq!(data.height, 0);
+                               assert_eq!(data.header, block.header);
+                       },
+               }
+       }
+
+       #[test]
+       fn into_block_header_from_json_response_with_valid_header_array() {
+               let genesis_block = genesis_block(Network::Bitcoin);
+               let best_block_header = BlockHeader {
+                       prev_blockhash: genesis_block.block_hash(),
+                       ..genesis_block.header
+               };
+               let chainwork = genesis_block.header.work() + best_block_header.work();
+               let response = JsonResponse(serde_json::json!([
+                               serde_json::Value::from(BlockHeaderData {
+                                       chainwork, height: 1, header: best_block_header,
+                               }),
+                               serde_json::Value::from(BlockHeaderData {
+                                       chainwork: genesis_block.header.work(), height: 0, header: genesis_block.header,
+                               }),
+               ]));
+
+               match TryInto::<BlockHeaderData>::try_into(response) {
+                       Err(e) => panic!("Unexpected error: {:?}", e),
+                       Ok(data) => {
+                               assert_eq!(data.chainwork, chainwork);
+                               assert_eq!(data.height, 1);
+                               assert_eq!(data.header, best_block_header);
+                       },
+               }
+       }
+
+       #[test]
+       fn into_block_header_from_json_response_without_previous_block_hash() {
+               let block = genesis_block(Network::Bitcoin);
+               let mut response = JsonResponse(BlockHeaderData {
+                       chainwork: block.header.work(),
+                       height: 0,
+                       header: block.header
+               }.into());
+               response.0.as_object_mut().unwrap().remove("previousblockhash");
+
+               match TryInto::<BlockHeaderData>::try_into(response) {
+                       Err(e) => panic!("Unexpected error: {:?}", e),
+                       Ok(BlockHeaderData { chainwork: _, height: _, header }) => {
+                               assert_eq!(header, block.header);
+                       },
+               }
+       }
+
+       #[test]
+       fn into_block_from_invalid_binary_response() {
+               let response = BinaryResponse(b"foo".to_vec());
+               match TryInto::<Block>::try_into(response) {
+                       Err(_) => {},
+                       Ok(_) => panic!("Expected error"),
+               }
+       }
+
+       #[test]
+       fn into_block_from_valid_binary_response() {
+               let genesis_block = genesis_block(Network::Bitcoin);
+               let response = BinaryResponse(encode::serialize(&genesis_block));
+               match TryInto::<Block>::try_into(response) {
+                       Err(e) => panic!("Unexpected error: {:?}", e),
+                       Ok(block) => assert_eq!(block, genesis_block),
+               }
+       }
+
+       #[test]
+       fn into_block_from_json_response_with_unexpected_type() {
+               let response = JsonResponse(serde_json::json!({ "result": "foo" }));
+               match TryInto::<Block>::try_into(response) {
+                       Err(e) => {
+                               assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
+                               assert_eq!(e.get_ref().unwrap().to_string(), "expected JSON string");
+                       },
+                       Ok(_) => panic!("Expected error"),
+               }
+       }
+
+       #[test]
+       fn into_block_from_json_response_with_invalid_hex_data() {
+               let response = JsonResponse(serde_json::json!("foobar"));
+               match TryInto::<Block>::try_into(response) {
+                       Err(e) => {
+                               assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
+                               assert_eq!(e.get_ref().unwrap().to_string(), "invalid hex data");
+                       },
+                       Ok(_) => panic!("Expected error"),
+               }
+       }
+
+       #[test]
+       fn into_block_from_json_response_with_invalid_block_data() {
+               let response = JsonResponse(serde_json::json!("abcd"));
+               match TryInto::<Block>::try_into(response) {
+                       Err(e) => {
+                               assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
+                               assert_eq!(e.get_ref().unwrap().to_string(), "invalid block data");
+                       },
+                       Ok(_) => panic!("Expected error"),
+               }
+       }
+
+       #[test]
+       fn into_block_from_json_response_with_valid_block_data() {
+               let genesis_block = genesis_block(Network::Bitcoin);
+               let response = JsonResponse(serde_json::json!(encode::serialize_hex(&genesis_block)));
+               match TryInto::<Block>::try_into(response) {
+                       Err(e) => panic!("Unexpected error: {:?}", e),
+                       Ok(block) => assert_eq!(block, genesis_block),
+               }
+       }
+
+       #[test]
+       fn into_block_hash_from_json_response_with_unexpected_type() {
+               let response = JsonResponse(serde_json::json!("foo"));
+               match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
+                       Err(e) => {
+                               assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
+                               assert_eq!(e.get_ref().unwrap().to_string(), "expected JSON object");
+                       },
+                       Ok(_) => panic!("Expected error"),
+               }
+       }
+
+       #[test]
+       fn into_block_hash_from_json_response_with_unexpected_bestblockhash_type() {
+               let response = JsonResponse(serde_json::json!({ "bestblockhash": 42 }));
+               match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
+                       Err(e) => {
+                               assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
+                               assert_eq!(e.get_ref().unwrap().to_string(), "expected JSON string");
+                       },
+                       Ok(_) => panic!("Expected error"),
+               }
+       }
+
+       #[test]
+       fn into_block_hash_from_json_response_with_invalid_hex_data() {
+               let response = JsonResponse(serde_json::json!({ "bestblockhash": "foobar"} ));
+               match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
+                       Err(e) => {
+                               assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
+                               assert_eq!(e.get_ref().unwrap().to_string(), "invalid hex data");
+                       },
+                       Ok(_) => panic!("Expected error"),
+               }
+       }
+
+       #[test]
+       fn into_block_hash_from_json_response_without_height() {
+               let block = genesis_block(Network::Bitcoin);
+               let response = JsonResponse(serde_json::json!({
+                       "bestblockhash": block.block_hash().to_hex(),
+               }));
+               match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
+                       Err(e) => panic!("Unexpected error: {:?}", e),
+                       Ok((hash, height)) => {
+                               assert_eq!(hash, block.block_hash());
+                               assert!(height.is_none());
+                       },
+               }
+       }
+
+       #[test]
+       fn into_block_hash_from_json_response_with_unexpected_blocks_type() {
+               let block = genesis_block(Network::Bitcoin);
+               let response = JsonResponse(serde_json::json!({
+                       "bestblockhash": block.block_hash().to_hex(),
+                       "blocks": "foo",
+               }));
+               match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
+                       Err(e) => {
+                               assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
+                               assert_eq!(e.get_ref().unwrap().to_string(), "expected JSON number");
+                       },
+                       Ok(_) => panic!("Expected error"),
+               }
+       }
+
+       #[test]
+       fn into_block_hash_from_json_response_with_invalid_height() {
+               let block = genesis_block(Network::Bitcoin);
+               let response = JsonResponse(serde_json::json!({
+                       "bestblockhash": block.block_hash().to_hex(),
+                       "blocks": std::u64::MAX,
+               }));
+               match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
+                       Err(e) => {
+                               assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
+                               assert_eq!(e.get_ref().unwrap().to_string(), "invalid height");
+                       },
+                       Ok(_) => panic!("Expected error"),
+               }
+       }
+
+       #[test]
+       fn into_block_hash_from_json_response_with_height() {
+               let block = genesis_block(Network::Bitcoin);
+               let response = JsonResponse(serde_json::json!({
+                       "bestblockhash": block.block_hash().to_hex(),
+                       "blocks": 1,
+               }));
+               match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
+                       Err(e) => panic!("Unexpected error: {:?}", e),
+                       Ok((hash, height)) => {
+                               assert_eq!(hash, block.block_hash());
+                               assert_eq!(height.unwrap(), 1);
+                       },
+               }
+       }
+}
diff --git a/lightning-block-sync/src/http.rs b/lightning-block-sync/src/http.rs
new file mode 100644 (file)
index 0000000..0788bc9
--- /dev/null
@@ -0,0 +1,767 @@
+use chunked_transfer;
+use serde_json;
+
+use std::convert::TryFrom;
+#[cfg(not(feature = "tokio"))]
+use std::io::Write;
+use std::net::ToSocketAddrs;
+use std::time::Duration;
+
+#[cfg(feature = "tokio")]
+use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt};
+#[cfg(feature = "tokio")]
+use tokio::net::TcpStream;
+
+#[cfg(not(feature = "tokio"))]
+use std::io::BufRead;
+use std::io::Read;
+#[cfg(not(feature = "tokio"))]
+use std::net::TcpStream;
+
+/// Timeout for operations on TCP streams.
+const TCP_STREAM_TIMEOUT: Duration = Duration::from_secs(5);
+
+/// Maximum HTTP message header size in bytes.
+const MAX_HTTP_MESSAGE_HEADER_SIZE: usize = 8192;
+
+/// Maximum HTTP message body size in bytes. Enough for a hex-encoded block in JSON format and any
+/// overhead for HTTP chunked transfer encoding.
+const MAX_HTTP_MESSAGE_BODY_SIZE: usize = 2 * 4_000_000 + 32_000;
+
+/// Endpoint for interacting with an HTTP-based API.
+#[derive(Debug)]
+pub struct HttpEndpoint {
+       host: String,
+       port: Option<u16>,
+       path: String,
+}
+
+impl HttpEndpoint {
+       /// Creates an endpoint for the given host and default HTTP port.
+       pub fn for_host(host: String) -> Self {
+               Self {
+                       host,
+                       port: None,
+                       path: String::from("/"),
+               }
+       }
+
+       /// Specifies a port to use with the endpoint.
+       pub fn with_port(mut self, port: u16) -> Self {
+               self.port = Some(port);
+               self
+       }
+
+       /// Specifies a path to use with the endpoint.
+       pub fn with_path(mut self, path: String) -> Self {
+               self.path = path;
+               self
+       }
+
+       /// Returns the endpoint host.
+       pub fn host(&self) -> &str {
+               &self.host
+       }
+
+       /// Returns the endpoint port.
+       pub fn port(&self) -> u16 {
+               match self.port {
+                       None => 80,
+                       Some(port) => port,
+               }
+       }
+
+       /// Returns the endpoint path.
+       pub fn path(&self) -> &str {
+               &self.path
+       }
+}
+
+impl<'a> std::net::ToSocketAddrs for &'a HttpEndpoint {
+       type Iter = <(&'a str, u16) as std::net::ToSocketAddrs>::Iter;
+
+       fn to_socket_addrs(&self) -> std::io::Result<Self::Iter> {
+               (self.host(), self.port()).to_socket_addrs()
+       }
+}
+
+/// Client for making HTTP requests.
+pub(crate) struct HttpClient {
+       stream: TcpStream,
+}
+
+impl HttpClient {
+       /// Opens a connection to an HTTP endpoint.
+       pub fn connect<E: ToSocketAddrs>(endpoint: E) -> std::io::Result<Self> {
+               let address = match endpoint.to_socket_addrs()?.next() {
+                       None => {
+                               return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "could not resolve to any addresses"));
+                       },
+                       Some(address) => address,
+               };
+               let stream = std::net::TcpStream::connect_timeout(&address, TCP_STREAM_TIMEOUT)?;
+               stream.set_read_timeout(Some(TCP_STREAM_TIMEOUT))?;
+               stream.set_write_timeout(Some(TCP_STREAM_TIMEOUT))?;
+
+               #[cfg(feature = "tokio")]
+               let stream = {
+                       stream.set_nonblocking(true)?;
+                       TcpStream::from_std(stream)?
+               };
+
+               Ok(Self { stream })
+       }
+
+       /// Sends a `GET` request for a resource identified by `uri` at the `host`.
+       ///
+       /// Returns the response body in `F` format.
+       #[allow(dead_code)]
+       pub async fn get<F>(&mut self, uri: &str, host: &str) -> std::io::Result<F>
+       where F: TryFrom<Vec<u8>, Error = std::io::Error> {
+               let request = format!(
+                       "GET {} HTTP/1.1\r\n\
+                        Host: {}\r\n\
+                        Connection: keep-alive\r\n\
+                        \r\n", uri, host);
+               let response_body = self.send_request_with_retry(&request).await?;
+               F::try_from(response_body)
+       }
+
+       /// Sends a `POST` request for a resource identified by `uri` at the `host` using the given HTTP
+       /// authentication credentials.
+       ///
+       /// The request body consists of the provided JSON `content`. Returns the response body in `F`
+       /// format.
+       #[allow(dead_code)]
+       pub async fn post<F>(&mut self, uri: &str, host: &str, auth: &str, content: serde_json::Value) -> std::io::Result<F>
+       where F: TryFrom<Vec<u8>, Error = std::io::Error> {
+               let content = content.to_string();
+               let request = format!(
+                       "POST {} HTTP/1.1\r\n\
+                        Host: {}\r\n\
+                        Authorization: {}\r\n\
+                        Connection: keep-alive\r\n\
+                        Content-Type: application/json\r\n\
+                        Content-Length: {}\r\n\
+                        \r\n\
+                        {}", uri, host, auth, content.len(), content);
+               let response_body = self.send_request_with_retry(&request).await?;
+               F::try_from(response_body)
+       }
+
+       /// Sends an HTTP request message and reads the response, returning its body. Attempts to
+       /// reconnect and retry if the connection has been closed.
+       async fn send_request_with_retry(&mut self, request: &str) -> std::io::Result<Vec<u8>> {
+               let endpoint = self.stream.peer_addr().unwrap();
+               match self.send_request(request).await {
+                       Ok(bytes) => Ok(bytes),
+                       Err(e) => match e.kind() {
+                               std::io::ErrorKind::ConnectionReset |
+                               std::io::ErrorKind::ConnectionAborted |
+                               std::io::ErrorKind::UnexpectedEof => {
+                                       // Reconnect if the connection was closed. This may happen if the server's
+                                       // keep-alive limits are reached.
+                                       *self = Self::connect(endpoint)?;
+                                       self.send_request(request).await
+                               },
+                               _ => Err(e),
+                       },
+               }
+       }
+
+       /// Sends an HTTP request message and reads the response, returning its body.
+       async fn send_request(&mut self, request: &str) -> std::io::Result<Vec<u8>> {
+               self.write_request(request).await?;
+               self.read_response().await
+       }
+
+       /// Writes an HTTP request message.
+       async fn write_request(&mut self, request: &str) -> std::io::Result<()> {
+               #[cfg(feature = "tokio")]
+               {
+                       self.stream.write_all(request.as_bytes()).await?;
+                       self.stream.flush().await
+               }
+               #[cfg(not(feature = "tokio"))]
+               {
+                       self.stream.write_all(request.as_bytes())?;
+                       self.stream.flush()
+               }
+       }
+
+       /// Reads an HTTP response message.
+       async fn read_response(&mut self) -> std::io::Result<Vec<u8>> {
+               #[cfg(feature = "tokio")]
+               let stream = self.stream.split().0;
+               #[cfg(not(feature = "tokio"))]
+               let stream = std::io::Read::by_ref(&mut self.stream);
+
+               let limited_stream = stream.take(MAX_HTTP_MESSAGE_HEADER_SIZE as u64);
+
+               #[cfg(feature = "tokio")]
+               let mut reader = tokio::io::BufReader::new(limited_stream);
+               #[cfg(not(feature = "tokio"))]
+               let mut reader = std::io::BufReader::new(limited_stream);
+
+               macro_rules! read_line { () => { {
+                       let mut line = String::new();
+                       #[cfg(feature = "tokio")]
+                       let bytes_read = reader.read_line(&mut line).await?;
+                       #[cfg(not(feature = "tokio"))]
+                       let bytes_read = reader.read_line(&mut line)?;
+
+                       match bytes_read {
+                               0 => None,
+                               _ => {
+                                       // Remove trailing CRLF
+                                       if line.ends_with('\n') { line.pop(); if line.ends_with('\r') { line.pop(); } }
+                                       Some(line)
+                               },
+                       }
+               } } }
+
+               // Read and parse status line
+               let status_line = read_line!()
+                       .ok_or(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "no status line"))?;
+               let status = HttpStatus::parse(&status_line)?;
+
+               // Read and parse relevant headers
+               let mut message_length = HttpMessageLength::Empty;
+               loop {
+                       let line = read_line!()
+                               .ok_or(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "no headers"))?;
+                       if line.is_empty() { break; }
+
+                       let header = HttpHeader::parse(&line)?;
+                       if header.has_name("Content-Length") {
+                               let length = header.value.parse()
+                                       .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
+                               if let HttpMessageLength::Empty = message_length {
+                                       message_length = HttpMessageLength::ContentLength(length);
+                               }
+                               continue;
+                       }
+
+                       if header.has_name("Transfer-Encoding") {
+                               message_length = HttpMessageLength::TransferEncoding(header.value.into());
+                               continue;
+                       }
+               }
+
+               if !status.is_ok() {
+                       // TODO: Handle 3xx redirection responses.
+                       return Err(std::io::Error::new(std::io::ErrorKind::NotFound, "not found"));
+               }
+
+               // Read message body
+               let read_limit = MAX_HTTP_MESSAGE_BODY_SIZE - reader.buffer().len();
+               reader.get_mut().set_limit(read_limit as u64);
+               match message_length {
+                       HttpMessageLength::Empty => { Ok(Vec::new()) },
+                       HttpMessageLength::ContentLength(length) => {
+                               if length == 0 || length > MAX_HTTP_MESSAGE_BODY_SIZE {
+                                       Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "out of range"))
+                               } else {
+                                       let mut content = vec![0; length];
+                                       #[cfg(feature = "tokio")]
+                                       reader.read_exact(&mut content[..]).await?;
+                                       #[cfg(not(feature = "tokio"))]
+                                       reader.read_exact(&mut content[..])?;
+                                       Ok(content)
+                               }
+                       },
+                       HttpMessageLength::TransferEncoding(coding) => {
+                               if !coding.eq_ignore_ascii_case("chunked") {
+                                       Err(std::io::Error::new(
+                                                       std::io::ErrorKind::InvalidInput, "unsupported transfer coding"))
+                               } else {
+                                       let mut content = Vec::new();
+                                       #[cfg(feature = "tokio")]
+                                       {
+                                               // Since chunked_transfer doesn't have an async interface, only use it to
+                                               // determine the size of each chunk to read.
+                                               //
+                                               // TODO: Replace with an async interface when available.
+                                               // https://github.com/frewsxcv/rust-chunked-transfer/issues/7
+                                               loop {
+                                                       // Read the chunk header which contains the chunk size.
+                                                       let mut chunk_header = String::new();
+                                                       reader.read_line(&mut chunk_header).await?;
+                                                       if chunk_header == "0\r\n" {
+                                                               // Read the terminator chunk since the decoder consumes the CRLF
+                                                               // immediately when this chunk is encountered.
+                                                               reader.read_line(&mut chunk_header).await?;
+                                                       }
+
+                                                       // Decode the chunk header to obtain the chunk size.
+                                                       let mut buffer = Vec::new();
+                                                       let mut decoder = chunked_transfer::Decoder::new(chunk_header.as_bytes());
+                                                       decoder.read_to_end(&mut buffer)?;
+
+                                                       // Read the chunk body.
+                                                       let chunk_size = match decoder.remaining_chunks_size() {
+                                                               None => break,
+                                                               Some(chunk_size) => chunk_size,
+                                                       };
+                                                       let chunk_offset = content.len();
+                                                       content.resize(chunk_offset + chunk_size + "\r\n".len(), 0);
+                                                       reader.read_exact(&mut content[chunk_offset..]).await?;
+                                                       content.resize(chunk_offset + chunk_size, 0);
+                                               }
+                                               Ok(content)
+                                       }
+                                       #[cfg(not(feature = "tokio"))]
+                                       {
+                                               let mut decoder = chunked_transfer::Decoder::new(reader);
+                                               decoder.read_to_end(&mut content)?;
+                                               Ok(content)
+                                       }
+                               }
+                       },
+               }
+       }
+}
+
+/// HTTP response status code as defined by [RFC 7231].
+///
+/// [RFC 7231]: https://tools.ietf.org/html/rfc7231#section-6
+struct HttpStatus<'a> {
+       code: &'a str,
+}
+
+impl<'a> HttpStatus<'a> {
+       /// Parses an HTTP status line as defined by [RFC 7230].
+       ///
+       /// [RFC 7230]: https://tools.ietf.org/html/rfc7230#section-3.1.2
+       fn parse(line: &'a String) -> std::io::Result<HttpStatus<'a>> {
+               let mut tokens = line.splitn(3, ' ');
+
+               let http_version = tokens.next()
+                       .ok_or(std::io::Error::new(std::io::ErrorKind::InvalidData, "no HTTP-Version"))?;
+               if !http_version.eq_ignore_ascii_case("HTTP/1.1") &&
+                       !http_version.eq_ignore_ascii_case("HTTP/1.0") {
+                       return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid HTTP-Version"));
+               }
+
+               let code = tokens.next()
+                       .ok_or(std::io::Error::new(std::io::ErrorKind::InvalidData, "no Status-Code"))?;
+               if code.len() != 3 || !code.chars().all(|c| c.is_ascii_digit()) {
+                       return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid Status-Code"));
+               }
+
+               let _reason = tokens.next()
+                       .ok_or(std::io::Error::new(std::io::ErrorKind::InvalidData, "no Reason-Phrase"))?;
+
+               Ok(Self { code })
+       }
+
+       /// Returns whether the status is successful (i.e., 2xx status class).
+       fn is_ok(&self) -> bool {
+               self.code.starts_with('2')
+       }
+}
+
+/// HTTP response header as defined by [RFC 7231].
+///
+/// [RFC 7231]: https://tools.ietf.org/html/rfc7231#section-7
+struct HttpHeader<'a> {
+       name: &'a str,
+       value: &'a str,
+}
+
+impl<'a> HttpHeader<'a> {
+       /// Parses an HTTP header field as defined by [RFC 7230].
+       ///
+       /// [RFC 7230]: https://tools.ietf.org/html/rfc7230#section-3.2
+       fn parse(line: &'a String) -> std::io::Result<HttpHeader<'a>> {
+               let mut tokens = line.splitn(2, ':');
+               let name = tokens.next()
+                       .ok_or(std::io::Error::new(std::io::ErrorKind::InvalidData, "no header name"))?;
+               let value = tokens.next()
+                       .ok_or(std::io::Error::new(std::io::ErrorKind::InvalidData, "no header value"))?
+                       .trim_start();
+               Ok(Self { name, value })
+       }
+
+       /// Returns whether the header field has the given name.
+       fn has_name(&self, name: &str) -> bool {
+               self.name.eq_ignore_ascii_case(name)
+       }
+}
+
+/// HTTP message body length as defined by [RFC 7230].
+///
+/// [RFC 7230]: https://tools.ietf.org/html/rfc7230#section-3.3.3
+enum HttpMessageLength {
+       Empty,
+       ContentLength(usize),
+       TransferEncoding(String),
+}
+
+/// An HTTP response body in binary format.
+pub(crate) struct BinaryResponse(pub(crate) Vec<u8>);
+
+/// An HTTP response body in JSON format.
+pub(crate) struct JsonResponse(pub(crate) serde_json::Value);
+
+/// Interprets bytes from an HTTP response body as binary data.
+impl TryFrom<Vec<u8>> for BinaryResponse {
+       type Error = std::io::Error;
+
+       fn try_from(bytes: Vec<u8>) -> std::io::Result<Self> {
+               Ok(BinaryResponse(bytes))
+       }
+}
+
+/// Interprets bytes from an HTTP response body as a JSON value.
+impl TryFrom<Vec<u8>> for JsonResponse {
+       type Error = std::io::Error;
+
+       fn try_from(bytes: Vec<u8>) -> std::io::Result<Self> {
+               Ok(JsonResponse(serde_json::from_slice(&bytes)?))
+       }
+}
+
+#[cfg(test)]
+mod endpoint_tests {
+       use super::HttpEndpoint;
+
+       #[test]
+       fn with_default_port() {
+               let endpoint = HttpEndpoint::for_host("foo.com".into());
+               assert_eq!(endpoint.host(), "foo.com");
+               assert_eq!(endpoint.port(), 80);
+       }
+
+       #[test]
+       fn with_custom_port() {
+               let endpoint = HttpEndpoint::for_host("foo.com".into()).with_port(8080);
+               assert_eq!(endpoint.host(), "foo.com");
+               assert_eq!(endpoint.port(), 8080);
+       }
+
+       #[test]
+       fn with_uri_path() {
+               let endpoint = HttpEndpoint::for_host("foo.com".into()).with_path("/path".into());
+               assert_eq!(endpoint.host(), "foo.com");
+               assert_eq!(endpoint.path(), "/path");
+       }
+
+       #[test]
+       fn without_uri_path() {
+               let endpoint = HttpEndpoint::for_host("foo.com".into());
+               assert_eq!(endpoint.host(), "foo.com");
+               assert_eq!(endpoint.path(), "/");
+       }
+
+       #[test]
+       fn convert_to_socket_addrs() {
+               let endpoint = HttpEndpoint::for_host("foo.com".into());
+               let host = endpoint.host();
+               let port = endpoint.port();
+
+               use std::net::ToSocketAddrs;
+               match (&endpoint).to_socket_addrs() {
+                       Err(e) => panic!("Unexpected error: {:?}", e),
+                       Ok(mut socket_addrs) => {
+                               match socket_addrs.next() {
+                                       None => panic!("Expected socket address"),
+                                       Some(addr) => {
+                                               assert_eq!(addr, (host, port).to_socket_addrs().unwrap().next().unwrap());
+                                               assert!(socket_addrs.next().is_none());
+                                       }
+                               }
+                       }
+               }
+       }
+}
+
+#[cfg(test)]
+pub(crate) mod client_tests {
+       use super::*;
+       use std::io::BufRead;
+       use std::io::Write;
+
+       /// Server for handling HTTP client requests with a stock response.
+       pub struct HttpServer {
+               address: std::net::SocketAddr,
+               handler: std::thread::JoinHandle<()>,
+               shutdown: std::sync::Arc<std::sync::atomic::AtomicBool>,
+       }
+
+       /// Body of HTTP response messages.
+       pub enum MessageBody<T: ToString> {
+               Empty,
+               Content(T),
+               ChunkedContent(T),
+       }
+
+       impl HttpServer {
+               pub fn responding_with_ok<T: ToString>(body: MessageBody<T>) -> Self {
+                       let response = match body {
+                               MessageBody::Empty => "HTTP/1.1 200 OK\r\n\r\n".to_string(),
+                               MessageBody::Content(body) => {
+                                       let body = body.to_string();
+                                       format!(
+                                               "HTTP/1.1 200 OK\r\n\
+                                                Content-Length: {}\r\n\
+                                                \r\n\
+                                                {}", body.len(), body)
+                               },
+                               MessageBody::ChunkedContent(body) => {
+                                       let mut chuncked_body = Vec::new();
+                                       {
+                                               use chunked_transfer::Encoder;
+                                               let mut encoder = Encoder::with_chunks_size(&mut chuncked_body, 8);
+                                               encoder.write_all(body.to_string().as_bytes()).unwrap();
+                                       }
+                                       format!(
+                                               "HTTP/1.1 200 OK\r\n\
+                                                Transfer-Encoding: chunked\r\n\
+                                                \r\n\
+                                                {}", String::from_utf8(chuncked_body).unwrap())
+                               },
+                       };
+                       HttpServer::responding_with(response)
+               }
+
+               pub fn responding_with_not_found() -> Self {
+                       let response = "HTTP/1.1 404 Not Found\r\n\r\n".to_string();
+                       HttpServer::responding_with(response)
+               }
+
+               fn responding_with(response: String) -> Self {
+                       let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+                       let address = listener.local_addr().unwrap();
+
+                       let shutdown = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
+                       let shutdown_signaled = std::sync::Arc::clone(&shutdown);
+                       let handler = std::thread::spawn(move || {
+                               for stream in listener.incoming() {
+                                       let mut stream = stream.unwrap();
+                                       stream.set_write_timeout(Some(TCP_STREAM_TIMEOUT)).unwrap();
+
+                                       let lines_read = std::io::BufReader::new(&stream)
+                                               .lines()
+                                               .take_while(|line| !line.as_ref().unwrap().is_empty())
+                                               .count();
+                                       if lines_read == 0 { continue; }
+
+                                       for chunk in response.as_bytes().chunks(16) {
+                                               if shutdown_signaled.load(std::sync::atomic::Ordering::SeqCst) {
+                                                       return;
+                                               } else {
+                                                       if let Err(_) = stream.write(chunk) { break; }
+                                                       if let Err(_) = stream.flush() { break; }
+                                               }
+                                       }
+                               }
+                       });
+
+                       Self { address, handler, shutdown }
+               }
+
+               fn shutdown(self) {
+                       self.shutdown.store(true, std::sync::atomic::Ordering::SeqCst);
+                       self.handler.join().unwrap();
+               }
+
+               pub fn endpoint(&self) -> HttpEndpoint {
+                       HttpEndpoint::for_host(self.address.ip().to_string()).with_port(self.address.port())
+               }
+       }
+
+       #[test]
+       fn connect_to_unresolvable_host() {
+               match HttpClient::connect(("example.invalid", 80)) {
+                       Err(e) => assert_eq!(e.kind(), std::io::ErrorKind::Other),
+                       Ok(_) => panic!("Expected error"),
+               }
+       }
+
+       #[test]
+       fn connect_with_no_socket_address() {
+               match HttpClient::connect(&vec![][..]) {
+                       Err(e) => assert_eq!(e.kind(), std::io::ErrorKind::InvalidInput),
+                       Ok(_) => panic!("Expected error"),
+               }
+       }
+
+       #[test]
+       fn connect_with_unknown_server() {
+               match HttpClient::connect(("::", 80)) {
+                       #[cfg(target_os = "windows")]
+                       Err(e) => assert_eq!(e.kind(), std::io::ErrorKind::AddrNotAvailable),
+                       #[cfg(not(target_os = "windows"))]
+                       Err(e) => assert_eq!(e.kind(), std::io::ErrorKind::ConnectionRefused),
+                       Ok(_) => panic!("Expected error"),
+               }
+       }
+
+       #[tokio::test]
+       async fn connect_with_valid_endpoint() {
+               let server = HttpServer::responding_with_ok::<String>(MessageBody::Empty);
+
+               match HttpClient::connect(&server.endpoint()) {
+                       Err(e) => panic!("Unexpected error: {:?}", e),
+                       Ok(_) => {},
+               }
+       }
+
+       #[tokio::test]
+       async fn read_empty_message() {
+               let server = HttpServer::responding_with("".to_string());
+
+               let mut client = HttpClient::connect(&server.endpoint()).unwrap();
+               match client.get::<BinaryResponse>("/foo", "foo.com").await {
+                       Err(e) => {
+                               assert_eq!(e.kind(), std::io::ErrorKind::UnexpectedEof);
+                               assert_eq!(e.get_ref().unwrap().to_string(), "no status line");
+                       },
+                       Ok(_) => panic!("Expected error"),
+               }
+       }
+
+       #[tokio::test]
+       async fn read_incomplete_message() {
+               let server = HttpServer::responding_with("HTTP/1.1 200 OK".to_string());
+
+               let mut client = HttpClient::connect(&server.endpoint()).unwrap();
+               match client.get::<BinaryResponse>("/foo", "foo.com").await {
+                       Err(e) => {
+                               assert_eq!(e.kind(), std::io::ErrorKind::UnexpectedEof);
+                               assert_eq!(e.get_ref().unwrap().to_string(), "no headers");
+                       },
+                       Ok(_) => panic!("Expected error"),
+               }
+       }
+
+       #[tokio::test]
+       async fn read_too_large_message_headers() {
+               let response = format!(
+                       "HTTP/1.1 302 Found\r\n\
+                        Location: {}\r\n\
+                        \r\n", "Z".repeat(MAX_HTTP_MESSAGE_HEADER_SIZE));
+               let server = HttpServer::responding_with(response);
+
+               let mut client = HttpClient::connect(&server.endpoint()).unwrap();
+               match client.get::<BinaryResponse>("/foo", "foo.com").await {
+                       Err(e) => {
+                               assert_eq!(e.kind(), std::io::ErrorKind::UnexpectedEof);
+                               assert_eq!(e.get_ref().unwrap().to_string(), "no headers");
+                       },
+                       Ok(_) => panic!("Expected error"),
+               }
+       }
+
+       #[tokio::test]
+       async fn read_too_large_message_body() {
+               let body = "Z".repeat(MAX_HTTP_MESSAGE_BODY_SIZE + 1);
+               let server = HttpServer::responding_with_ok::<String>(MessageBody::Content(body));
+
+               let mut client = HttpClient::connect(&server.endpoint()).unwrap();
+               match client.get::<BinaryResponse>("/foo", "foo.com").await {
+                       Err(e) => {
+                               assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
+                               assert_eq!(e.get_ref().unwrap().to_string(), "out of range");
+                       },
+                       Ok(_) => panic!("Expected error"),
+               }
+               server.shutdown();
+       }
+
+       #[tokio::test]
+       async fn read_message_with_unsupported_transfer_coding() {
+               let response = String::from(
+                       "HTTP/1.1 200 OK\r\n\
+                        Transfer-Encoding: gzip\r\n\
+                        \r\n\
+                        foobar");
+               let server = HttpServer::responding_with(response);
+
+               let mut client = HttpClient::connect(&server.endpoint()).unwrap();
+               match client.get::<BinaryResponse>("/foo", "foo.com").await {
+                       Err(e) => {
+                               assert_eq!(e.kind(), std::io::ErrorKind::InvalidInput);
+                               assert_eq!(e.get_ref().unwrap().to_string(), "unsupported transfer coding");
+                       },
+                       Ok(_) => panic!("Expected error"),
+               }
+       }
+
+       #[tokio::test]
+       async fn read_empty_message_body() {
+               let server = HttpServer::responding_with_ok::<String>(MessageBody::Empty);
+
+               let mut client = HttpClient::connect(&server.endpoint()).unwrap();
+               match client.get::<BinaryResponse>("/foo", "foo.com").await {
+                       Err(e) => panic!("Unexpected error: {:?}", e),
+                       Ok(bytes) => assert_eq!(bytes.0, Vec::<u8>::new()),
+               }
+       }
+
+       #[tokio::test]
+       async fn read_message_body_with_length() {
+               let body = "foo bar baz qux".repeat(32);
+               let content = MessageBody::Content(body.clone());
+               let server = HttpServer::responding_with_ok::<String>(content);
+
+               let mut client = HttpClient::connect(&server.endpoint()).unwrap();
+               match client.get::<BinaryResponse>("/foo", "foo.com").await {
+                       Err(e) => panic!("Unexpected error: {:?}", e),
+                       Ok(bytes) => assert_eq!(bytes.0, body.as_bytes()),
+               }
+       }
+
+       #[tokio::test]
+       async fn read_chunked_message_body() {
+               let body = "foo bar baz qux".repeat(32);
+               let chunked_content = MessageBody::ChunkedContent(body.clone());
+               let server = HttpServer::responding_with_ok::<String>(chunked_content);
+
+               let mut client = HttpClient::connect(&server.endpoint()).unwrap();
+               match client.get::<BinaryResponse>("/foo", "foo.com").await {
+                       Err(e) => panic!("Unexpected error: {:?}", e),
+                       Ok(bytes) => assert_eq!(bytes.0, body.as_bytes()),
+               }
+       }
+
+       #[tokio::test]
+       async fn reconnect_closed_connection() {
+               let server = HttpServer::responding_with_ok::<String>(MessageBody::Empty);
+
+               let mut client = HttpClient::connect(&server.endpoint()).unwrap();
+               assert!(client.get::<BinaryResponse>("/foo", "foo.com").await.is_ok());
+               match client.get::<BinaryResponse>("/foo", "foo.com").await {
+                       Err(e) => panic!("Unexpected error: {:?}", e),
+                       Ok(bytes) => assert_eq!(bytes.0, Vec::<u8>::new()),
+               }
+       }
+
+       #[test]
+       fn from_bytes_into_binary_response() {
+               let bytes = b"foo";
+               match BinaryResponse::try_from(bytes.to_vec()) {
+                       Err(e) => panic!("Unexpected error: {:?}", e),
+                       Ok(response) => assert_eq!(&response.0, bytes),
+               }
+       }
+
+       #[test]
+       fn from_invalid_bytes_into_json_response() {
+               let json = serde_json::json!({ "result": 42 });
+               match JsonResponse::try_from(json.to_string().as_bytes()[..5].to_vec()) {
+                       Err(_) => {},
+                       Ok(_) => panic!("Expected error"),
+               }
+       }
+
+       #[test]
+       fn from_valid_bytes_into_json_response() {
+               let json = serde_json::json!({ "result": 42 });
+               match JsonResponse::try_from(json.to_string().as_bytes().to_vec()) {
+                       Err(e) => panic!("Unexpected error: {:?}", e),
+                       Ok(response) => assert_eq!(response.0, json),
+               }
+       }
+}
diff --git a/lightning-block-sync/src/init.rs b/lightning-block-sync/src/init.rs
new file mode 100644 (file)
index 0000000..59c0571
--- /dev/null
@@ -0,0 +1,362 @@
+use crate::{BlockSource, BlockSourceResult, Cache, ChainNotifier};
+use crate::poll::{ChainPoller, Validate, ValidatedBlockHeader};
+
+use bitcoin::blockdata::block::{Block, BlockHeader};
+use bitcoin::hash_types::BlockHash;
+use bitcoin::network::constants::Network;
+
+use lightning::chain;
+
+/// Returns a validated block header of the source's best chain tip.
+///
+/// Upon success, the returned header can be used to initialize [`SpvClient`]. Useful during a fresh
+/// start when there are no chain listeners to sync yet.
+pub async fn validate_best_block_header<B: BlockSource>(block_source: &mut B) ->
+BlockSourceResult<ValidatedBlockHeader> {
+       let (best_block_hash, best_block_height) = block_source.get_best_block().await?;
+       block_source
+               .get_header(&best_block_hash, best_block_height).await?
+               .validate(best_block_hash)
+}
+
+/// Performs a one-time sync of chain listeners using a single *trusted* block source, bringing each
+/// listener's view of the chain from its paired block hash to `block_source`'s best chain tip.
+///
+/// Upon success, the returned header can be used to initialize [`SpvClient`]. In the case of
+/// failure, each listener may be left at a different block hash than the one it was originally
+/// paired with.
+///
+/// Useful during startup to bring the [`ChannelManager`] and each [`ChannelMonitor`] in sync before
+/// switching to [`SpvClient`]. For example:
+///
+/// ```
+/// use bitcoin::hash_types::BlockHash;
+/// use bitcoin::network::constants::Network;
+///
+/// use lightning::chain;
+/// use lightning::chain::Watch;
+/// use lightning::chain::chainmonitor::ChainMonitor;
+/// use lightning::chain::channelmonitor;
+/// use lightning::chain::channelmonitor::ChannelMonitor;
+/// use lightning::chain::chaininterface::BroadcasterInterface;
+/// use lightning::chain::chaininterface::FeeEstimator;
+/// use lightning::chain::keysinterface;
+/// use lightning::chain::keysinterface::KeysInterface;
+/// use lightning::ln::channelmanager::ChannelManager;
+/// use lightning::ln::channelmanager::ChannelManagerReadArgs;
+/// use lightning::util::config::UserConfig;
+/// use lightning::util::logger::Logger;
+/// use lightning::util::ser::ReadableArgs;
+///
+/// use lightning_block_sync::*;
+///
+/// use std::io::Cursor;
+///
+/// async fn init_sync<
+///    B: BlockSource,
+///    K: KeysInterface<Signer = S>,
+///    S: keysinterface::Sign,
+///    T: BroadcasterInterface,
+///    F: FeeEstimator,
+///    L: Logger,
+///    C: chain::Filter,
+///    P: channelmonitor::Persist<S>,
+/// >(
+///    block_source: &mut B,
+///    chain_monitor: &ChainMonitor<S, &C, &T, &F, &L, &P>,
+///    config: UserConfig,
+///    keys_manager: &K,
+///    tx_broadcaster: &T,
+///    fee_estimator: &F,
+///    logger: &L,
+///    persister: &P,
+/// ) {
+///    // Read a serialized channel monitor paired with the block hash when it was persisted.
+///    let serialized_monitor = "...";
+///    let (monitor_block_hash_option, mut monitor) = <(Option<BlockHash>, ChannelMonitor<S>)>::read(
+///            &mut Cursor::new(&serialized_monitor), keys_manager).unwrap();
+///
+///    // Read the channel manager paired with the block hash when it was persisted.
+///    let serialized_manager = "...";
+///    let (manager_block_hash_option, mut manager) = {
+///            let read_args = ChannelManagerReadArgs::new(
+///                    keys_manager,
+///                    fee_estimator,
+///                    chain_monitor,
+///                    tx_broadcaster,
+///                    logger,
+///                    config,
+///                    vec![&mut monitor],
+///            );
+///            <(Option<BlockHash>, ChannelManager<S, &ChainMonitor<S, &C, &T, &F, &L, &P>, &T, &K, &F, &L>)>::read(
+///                    &mut Cursor::new(&serialized_manager), read_args).unwrap()
+///    };
+///
+///    // Synchronize any channel monitors and the channel manager to be on the best block.
+///    let mut cache = UnboundedCache::new();
+///    let mut monitor_listener = (monitor, &*tx_broadcaster, &*fee_estimator, &*logger);
+///    let mut listeners = vec![];
+///    if let Some(monitor_block_hash) = monitor_block_hash_option {
+///            listeners.push((monitor_block_hash, &mut monitor_listener as &mut dyn chain::Listen))
+///    }
+///    if let Some(manager_block_hash) = manager_block_hash_option {
+///            listeners.push((manager_block_hash, &mut manager as &mut dyn chain::Listen))
+///    }
+///    let chain_tip = init::synchronize_listeners(
+///            block_source, Network::Bitcoin, &mut cache, listeners).await.unwrap();
+///
+///    // Allow the chain monitor to watch any channels.
+///    let monitor = monitor_listener.0;
+///    chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor);
+///
+///    // Create an SPV client to notify the chain monitor and channel manager of block events.
+///    let chain_poller = poll::ChainPoller::new(block_source, Network::Bitcoin);
+///    let mut chain_listener = (chain_monitor, &manager);
+///    let spv_client = SpvClient::new(chain_tip, chain_poller, &mut cache, &chain_listener);
+/// }
+/// ```
+///
+/// [`SpvClient`]: ../struct.SpvClient.html
+/// [`ChannelManager`]: ../../lightning/ln/channelmanager/struct.ChannelManager.html
+/// [`ChannelMonitor`]: ../../lightning/chain/channelmonitor/struct.ChannelMonitor.html
+pub async fn synchronize_listeners<B: BlockSource, C: Cache>(
+       block_source: &mut B,
+       network: Network,
+       header_cache: &mut C,
+       mut chain_listeners: Vec<(BlockHash, &mut dyn chain::Listen)>,
+) -> BlockSourceResult<ValidatedBlockHeader> {
+       let best_header = validate_best_block_header(block_source).await?;
+
+       // Fetch the header for the block hash paired with each listener.
+       let mut chain_listeners_with_old_headers = Vec::new();
+       for (old_block_hash, chain_listener) in chain_listeners.drain(..) {
+               let old_header = match header_cache.look_up(&old_block_hash) {
+                       Some(header) => *header,
+                       None => block_source
+                               .get_header(&old_block_hash, None).await?
+                               .validate(old_block_hash)?
+               };
+               chain_listeners_with_old_headers.push((old_header, chain_listener))
+       }
+
+       // Find differences and disconnect blocks for each listener individually.
+       let mut chain_poller = ChainPoller::new(block_source, network);
+       let mut chain_listeners_at_height = Vec::new();
+       let mut most_common_ancestor = None;
+       let mut most_connected_blocks = Vec::new();
+       for (old_header, chain_listener) in chain_listeners_with_old_headers.drain(..) {
+               // Disconnect any stale blocks, but keep them in the cache for the next iteration.
+               let header_cache = &mut ReadOnlyCache(header_cache);
+               let (common_ancestor, connected_blocks) = {
+                       let chain_listener = &DynamicChainListener(chain_listener);
+                       let mut chain_notifier = ChainNotifier { header_cache, chain_listener };
+                       let difference =
+                               chain_notifier.find_difference(best_header, &old_header, &mut chain_poller).await?;
+                       chain_notifier.disconnect_blocks(difference.disconnected_blocks);
+                       (difference.common_ancestor, difference.connected_blocks)
+               };
+
+               // Keep track of the most common ancestor and all blocks connected across all listeners.
+               chain_listeners_at_height.push((common_ancestor.height, chain_listener));
+               if connected_blocks.len() > most_connected_blocks.len() {
+                       most_common_ancestor = Some(common_ancestor);
+                       most_connected_blocks = connected_blocks;
+               }
+       }
+
+       // Connect new blocks for all listeners at once to avoid re-fetching blocks.
+       if let Some(common_ancestor) = most_common_ancestor {
+               let chain_listener = &ChainListenerSet(chain_listeners_at_height);
+               let mut chain_notifier = ChainNotifier { header_cache, chain_listener };
+               chain_notifier.connect_blocks(common_ancestor, most_connected_blocks, &mut chain_poller)
+                       .await.or_else(|(e, _)| Err(e))?;
+       }
+
+       Ok(best_header)
+}
+
+/// A wrapper to make a cache read-only.
+///
+/// Used to prevent losing headers that may be needed to disconnect blocks common to more than one
+/// listener.
+struct ReadOnlyCache<'a, C: Cache>(&'a mut C);
+
+impl<'a, C: Cache> Cache for ReadOnlyCache<'a, C> {
+       fn look_up(&self, block_hash: &BlockHash) -> Option<&ValidatedBlockHeader> {
+               self.0.look_up(block_hash)
+       }
+
+       fn block_connected(&mut self, _block_hash: BlockHash, _block_header: ValidatedBlockHeader) {
+               unreachable!()
+       }
+
+       fn block_disconnected(&mut self, _block_hash: &BlockHash) -> Option<ValidatedBlockHeader> {
+               None
+       }
+}
+
+/// Wrapper for supporting dynamically sized chain listeners.
+struct DynamicChainListener<'a>(&'a mut dyn chain::Listen);
+
+impl<'a> chain::Listen for DynamicChainListener<'a> {
+       fn block_connected(&self, _block: &Block, _height: u32) {
+               unreachable!()
+       }
+
+       fn block_disconnected(&self, header: &BlockHeader, height: u32) {
+               self.0.block_disconnected(header, height)
+       }
+}
+
+/// A set of dynamically sized chain listeners, each paired with a starting block height.
+struct ChainListenerSet<'a>(Vec<(u32, &'a mut dyn chain::Listen)>);
+
+impl<'a> chain::Listen for ChainListenerSet<'a> {
+       fn block_connected(&self, block: &Block, height: u32) {
+               for (starting_height, chain_listener) in self.0.iter() {
+                       if height > *starting_height {
+                               chain_listener.block_connected(block, height);
+                       }
+               }
+       }
+
+       fn block_disconnected(&self, _header: &BlockHeader, _height: u32) {
+               unreachable!()
+       }
+}
+
+#[cfg(test)]
+mod tests {
+       use crate::test_utils::{Blockchain, MockChainListener};
+       use super::*;
+
+       use bitcoin::network::constants::Network;
+
+       #[tokio::test]
+       async fn sync_from_same_chain() {
+               let mut chain = Blockchain::default().with_height(4);
+
+               let mut listener_1 = MockChainListener::new()
+                       .expect_block_connected(*chain.at_height(2))
+                       .expect_block_connected(*chain.at_height(3))
+                       .expect_block_connected(*chain.at_height(4));
+               let mut listener_2 = MockChainListener::new()
+                       .expect_block_connected(*chain.at_height(3))
+                       .expect_block_connected(*chain.at_height(4));
+               let mut listener_3 = MockChainListener::new()
+                       .expect_block_connected(*chain.at_height(4));
+
+               let listeners = vec![
+                       (chain.at_height(1).block_hash, &mut listener_1 as &mut dyn chain::Listen),
+                       (chain.at_height(2).block_hash, &mut listener_2 as &mut dyn chain::Listen),
+                       (chain.at_height(3).block_hash, &mut listener_3 as &mut dyn chain::Listen),
+               ];
+               let mut cache = chain.header_cache(0..=4);
+               match synchronize_listeners(&mut chain, Network::Bitcoin, &mut cache, listeners).await {
+                       Ok(header) => assert_eq!(header, chain.tip()),
+                       Err(e) => panic!("Unexpected error: {:?}", e),
+               }
+       }
+
+       #[tokio::test]
+       async fn sync_from_different_chains() {
+               let mut main_chain = Blockchain::default().with_height(4);
+               let fork_chain_1 = main_chain.fork_at_height(1);
+               let fork_chain_2 = main_chain.fork_at_height(2);
+               let fork_chain_3 = main_chain.fork_at_height(3);
+
+               let mut listener_1 = MockChainListener::new()
+                       .expect_block_disconnected(*fork_chain_1.at_height(4))
+                       .expect_block_disconnected(*fork_chain_1.at_height(3))
+                       .expect_block_disconnected(*fork_chain_1.at_height(2))
+                       .expect_block_connected(*main_chain.at_height(2))
+                       .expect_block_connected(*main_chain.at_height(3))
+                       .expect_block_connected(*main_chain.at_height(4));
+               let mut listener_2 = MockChainListener::new()
+                       .expect_block_disconnected(*fork_chain_2.at_height(4))
+                       .expect_block_disconnected(*fork_chain_2.at_height(3))
+                       .expect_block_connected(*main_chain.at_height(3))
+                       .expect_block_connected(*main_chain.at_height(4));
+               let mut listener_3 = MockChainListener::new()
+                       .expect_block_disconnected(*fork_chain_3.at_height(4))
+                       .expect_block_connected(*main_chain.at_height(4));
+
+               let listeners = vec![
+                       (fork_chain_1.tip().block_hash, &mut listener_1 as &mut dyn chain::Listen),
+                       (fork_chain_2.tip().block_hash, &mut listener_2 as &mut dyn chain::Listen),
+                       (fork_chain_3.tip().block_hash, &mut listener_3 as &mut dyn chain::Listen),
+               ];
+               let mut cache = fork_chain_1.header_cache(2..=4);
+               cache.extend(fork_chain_2.header_cache(3..=4));
+               cache.extend(fork_chain_3.header_cache(4..=4));
+               match synchronize_listeners(&mut main_chain, Network::Bitcoin, &mut cache, listeners).await {
+                       Ok(header) => assert_eq!(header, main_chain.tip()),
+                       Err(e) => panic!("Unexpected error: {:?}", e),
+               }
+       }
+
+       #[tokio::test]
+       async fn sync_from_overlapping_chains() {
+               let mut main_chain = Blockchain::default().with_height(4);
+               let fork_chain_1 = main_chain.fork_at_height(1);
+               let fork_chain_2 = fork_chain_1.fork_at_height(2);
+               let fork_chain_3 = fork_chain_2.fork_at_height(3);
+
+               let mut listener_1 = MockChainListener::new()
+                       .expect_block_disconnected(*fork_chain_1.at_height(4))
+                       .expect_block_disconnected(*fork_chain_1.at_height(3))
+                       .expect_block_disconnected(*fork_chain_1.at_height(2))
+                       .expect_block_connected(*main_chain.at_height(2))
+                       .expect_block_connected(*main_chain.at_height(3))
+                       .expect_block_connected(*main_chain.at_height(4));
+               let mut listener_2 = MockChainListener::new()
+                       .expect_block_disconnected(*fork_chain_2.at_height(4))
+                       .expect_block_disconnected(*fork_chain_2.at_height(3))
+                       .expect_block_disconnected(*fork_chain_2.at_height(2))
+                       .expect_block_connected(*main_chain.at_height(2))
+                       .expect_block_connected(*main_chain.at_height(3))
+                       .expect_block_connected(*main_chain.at_height(4));
+               let mut listener_3 = MockChainListener::new()
+                       .expect_block_disconnected(*fork_chain_3.at_height(4))
+                       .expect_block_disconnected(*fork_chain_3.at_height(3))
+                       .expect_block_disconnected(*fork_chain_3.at_height(2))
+                       .expect_block_connected(*main_chain.at_height(2))
+                       .expect_block_connected(*main_chain.at_height(3))
+                       .expect_block_connected(*main_chain.at_height(4));
+
+               let listeners = vec![
+                       (fork_chain_1.tip().block_hash, &mut listener_1 as &mut dyn chain::Listen),
+                       (fork_chain_2.tip().block_hash, &mut listener_2 as &mut dyn chain::Listen),
+                       (fork_chain_3.tip().block_hash, &mut listener_3 as &mut dyn chain::Listen),
+               ];
+               let mut cache = fork_chain_1.header_cache(2..=4);
+               cache.extend(fork_chain_2.header_cache(3..=4));
+               cache.extend(fork_chain_3.header_cache(4..=4));
+               match synchronize_listeners(&mut main_chain, Network::Bitcoin, &mut cache, listeners).await {
+                       Ok(header) => assert_eq!(header, main_chain.tip()),
+                       Err(e) => panic!("Unexpected error: {:?}", e),
+               }
+       }
+
+       #[tokio::test]
+       async fn cache_connected_and_keep_disconnected_blocks() {
+               let mut main_chain = Blockchain::default().with_height(2);
+               let fork_chain = main_chain.fork_at_height(1);
+               let new_tip = main_chain.tip();
+               let old_tip = fork_chain.tip();
+
+               let mut listener = MockChainListener::new()
+                       .expect_block_disconnected(*old_tip)
+                       .expect_block_connected(*new_tip);
+
+               let listeners = vec![(old_tip.block_hash, &mut listener as &mut dyn chain::Listen)];
+               let mut cache = fork_chain.header_cache(2..=2);
+               match synchronize_listeners(&mut main_chain, Network::Bitcoin, &mut cache, listeners).await {
+                       Ok(_) => {
+                               assert!(cache.contains_key(&new_tip.block_hash));
+                               assert!(cache.contains_key(&old_tip.block_hash));
+                       },
+                       Err(e) => panic!("Unexpected error: {:?}", e),
+               }
+       }
+}
diff --git a/lightning-block-sync/src/lib.rs b/lightning-block-sync/src/lib.rs
new file mode 100644 (file)
index 0000000..db536fe
--- /dev/null
@@ -0,0 +1,707 @@
+//! A lightweight client for keeping in sync with chain activity.
+//!
+//! Defines an [`SpvClient`] utility for polling one or more block sources for the best chain tip.
+//! It is used to notify listeners of blocks connected or disconnected since the last poll. Useful
+//! for keeping a Lightning node in sync with the chain.
+//!
+//! Defines a [`BlockSource`] trait, which is an asynchronous interface for retrieving block headers
+//! and data.
+//!
+//! Enabling feature `rest-client` or `rpc-client` allows configuring the client to fetch blocks
+//! using Bitcoin Core's REST or RPC interface, respectively.
+//!
+//! Both features support either blocking I/O using `std::net::TcpStream` or, with feature `tokio`,
+//! non-blocking I/O using `tokio::net::TcpStream` from inside a Tokio runtime.
+//!
+//! [`SpvClient`]: struct.SpvClient.html
+//! [`BlockSource`]: trait.BlockSource.html
+
+#[cfg(any(feature = "rest-client", feature = "rpc-client"))]
+pub mod http;
+
+pub mod init;
+pub mod poll;
+
+#[cfg(feature = "rest-client")]
+pub mod rest;
+
+#[cfg(feature = "rpc-client")]
+pub mod rpc;
+
+#[cfg(any(feature = "rest-client", feature = "rpc-client"))]
+mod convert;
+
+#[cfg(test)]
+mod test_utils;
+
+#[cfg(any(feature = "rest-client", feature = "rpc-client"))]
+mod utils;
+
+use crate::poll::{ChainTip, Poll, ValidatedBlockHeader};
+
+use bitcoin::blockdata::block::{Block, BlockHeader};
+use bitcoin::hash_types::BlockHash;
+use bitcoin::util::uint::Uint256;
+
+use lightning::chain;
+use lightning::chain::Listen;
+
+use std::future::Future;
+use std::ops::Deref;
+use std::pin::Pin;
+
+/// Abstract type for retrieving block headers and data.
+pub trait BlockSource : Sync + Send {
+       /// Returns the header for a given hash. A height hint may be provided in case a block source
+       /// cannot easily find headers based on a hash. This is merely a hint and thus the returned
+       /// header must have the same hash as was requested. Otherwise, an error must be returned.
+       ///
+       /// Implementations that cannot find headers based on the hash should return a `Transient` error
+       /// when `height_hint` is `None`.
+       fn get_header<'a>(&'a mut self, header_hash: &'a BlockHash, height_hint: Option<u32>) -> AsyncBlockSourceResult<'a, BlockHeaderData>;
+
+       /// Returns the block for a given hash. A headers-only block source should return a `Transient`
+       /// error.
+       fn get_block<'a>(&'a mut self, header_hash: &'a BlockHash) -> AsyncBlockSourceResult<'a, Block>;
+
+       /// Returns the hash of the best block and, optionally, its height.
+       ///
+       /// When polling a block source, [`Poll`] implementations may pass the height to [`get_header`]
+       /// to allow for a more efficient lookup.
+       ///
+       /// [`Poll`]: poll/trait.Poll.html
+       /// [`get_header`]: #tymethod.get_header
+       fn get_best_block<'a>(&'a mut self) -> AsyncBlockSourceResult<(BlockHash, Option<u32>)>;
+}
+
+/// Result type for `BlockSource` requests.
+type BlockSourceResult<T> = Result<T, BlockSourceError>;
+
+// TODO: Replace with BlockSourceResult once `async` trait functions are supported. For details,
+// see: https://areweasyncyet.rs.
+/// Result type for asynchronous `BlockSource` requests.
+type AsyncBlockSourceResult<'a, T> = Pin<Box<dyn Future<Output = BlockSourceResult<T>> + 'a + Send>>;
+
+/// Error type for `BlockSource` requests.
+///
+/// Transient errors may be resolved when re-polling, but no attempt will be made to re-poll on
+/// persistent errors.
+#[derive(Debug)]
+pub struct BlockSourceError {
+       kind: BlockSourceErrorKind,
+       error: Box<dyn std::error::Error + Send + Sync>,
+}
+
+/// The kind of `BlockSourceError`, either persistent or transient.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum BlockSourceErrorKind {
+       /// Indicates an error that won't resolve when retrying a request (e.g., invalid data).
+       Persistent,
+
+       /// Indicates an error that may resolve when retrying a request (e.g., unresponsive).
+       Transient,
+}
+
+impl BlockSourceError {
+       /// Creates a new persistent error originated from the given error.
+       pub fn persistent<E>(error: E) -> Self
+       where E: Into<Box<dyn std::error::Error + Send + Sync>> {
+               Self {
+                       kind: BlockSourceErrorKind::Persistent,
+                       error: error.into(),
+               }
+       }
+
+       /// Creates a new transient error originated from the given error.
+       pub fn transient<E>(error: E) -> Self
+       where E: Into<Box<dyn std::error::Error + Send + Sync>> {
+               Self {
+                       kind: BlockSourceErrorKind::Transient,
+                       error: error.into(),
+               }
+       }
+
+       /// Returns the kind of error.
+       pub fn kind(&self) -> BlockSourceErrorKind {
+               self.kind
+       }
+
+       /// Converts the error into the underlying error.
+       pub fn into_inner(self) -> Box<dyn std::error::Error + Send + Sync> {
+               self.error
+       }
+}
+
+/// A block header and some associated data. This information should be available from most block
+/// sources (and, notably, is available in Bitcoin Core's RPC and REST interfaces).
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct BlockHeaderData {
+       /// The block header itself.
+       pub header: BlockHeader,
+
+       /// The block height where the genesis block has height 0.
+       pub height: u32,
+
+       /// The total chain work in expected number of double-SHA256 hashes required to build a chain
+       /// of equivalent weight.
+       pub chainwork: Uint256,
+}
+
+/// A lightweight client for keeping a listener in sync with the chain, allowing for Simplified
+/// Payment Verification (SPV).
+///
+/// The client is parameterized by a chain poller which is responsible for polling one or more block
+/// sources for the best chain tip. During this process it detects any chain forks, determines which
+/// constitutes the best chain, and updates the listener accordingly with any blocks that were
+/// connected or disconnected since the last poll.
+///
+/// Block headers for the best chain are maintained in the parameterized cache, allowing for a
+/// custom cache eviction policy. This offers flexibility to those sensitive to resource usage.
+/// Hence, there is a trade-off between a lower memory footprint and potentially increased network
+/// I/O as headers are re-fetched during fork detection.
+pub struct SpvClient<'a, P: Poll, C: Cache, L: Deref>
+where L::Target: chain::Listen {
+       chain_tip: ValidatedBlockHeader,
+       chain_poller: P,
+       chain_notifier: ChainNotifier<'a, C, L>,
+}
+
+/// The `Cache` trait defines behavior for managing a block header cache, where block headers are
+/// keyed by block hash.
+///
+/// Used by [`ChainNotifier`] to store headers along the best chain, which is important for ensuring
+/// that blocks can be disconnected if they are no longer accessible from a block source (e.g., if
+/// the block source does not store stale forks indefinitely).
+///
+/// Implementations may define how long to retain headers such that it's unlikely they will ever be
+/// needed to disconnect a block.  In cases where block sources provide access to headers on stale
+/// forks reliably, caches may be entirely unnecessary.
+///
+/// [`ChainNotifier`]: struct.ChainNotifier.html
+pub trait Cache {
+       /// Retrieves the block header keyed by the given block hash.
+       fn look_up(&self, block_hash: &BlockHash) -> Option<&ValidatedBlockHeader>;
+
+       /// Called when a block has been connected to the best chain to ensure it is available to be
+       /// disconnected later if needed.
+       fn block_connected(&mut self, block_hash: BlockHash, block_header: ValidatedBlockHeader);
+
+       /// Called when a block has been disconnected from the best chain. Once disconnected, a block's
+       /// header is no longer needed and thus can be removed.
+       fn block_disconnected(&mut self, block_hash: &BlockHash) -> Option<ValidatedBlockHeader>;
+}
+
+/// Unbounded cache of block headers keyed by block hash.
+pub type UnboundedCache = std::collections::HashMap<BlockHash, ValidatedBlockHeader>;
+
+impl Cache for UnboundedCache {
+       fn look_up(&self, block_hash: &BlockHash) -> Option<&ValidatedBlockHeader> {
+               self.get(block_hash)
+       }
+
+       fn block_connected(&mut self, block_hash: BlockHash, block_header: ValidatedBlockHeader) {
+               self.insert(block_hash, block_header);
+       }
+
+       fn block_disconnected(&mut self, block_hash: &BlockHash) -> Option<ValidatedBlockHeader> {
+               self.remove(block_hash)
+       }
+}
+
+impl<'a, P: Poll, C: Cache, L: Deref> SpvClient<'a, P, C, L> where L::Target: chain::Listen {
+       /// Creates a new SPV client using `chain_tip` as the best known chain tip.
+       ///
+       /// Subsequent calls to [`poll_best_tip`] will poll for the best chain tip using the given chain
+       /// poller, which may be configured with one or more block sources to query. At least one block
+       /// source must provide headers back from the best chain tip to its common ancestor with
+       /// `chain_tip`.
+       /// * `header_cache` is used to look up and store headers on the best chain
+       /// * `chain_listener` is notified of any blocks connected or disconnected
+       ///
+       /// [`poll_best_tip`]: struct.SpvClient.html#method.poll_best_tip
+       pub fn new(
+               chain_tip: ValidatedBlockHeader,
+               chain_poller: P,
+               header_cache: &'a mut C,
+               chain_listener: L,
+       ) -> Self {
+               let chain_notifier = ChainNotifier { header_cache, chain_listener };
+               Self { chain_tip, chain_poller, chain_notifier }
+       }
+
+       /// Polls for the best tip and updates the chain listener with any connected or disconnected
+       /// blocks accordingly.
+       ///
+       /// Returns the best polled chain tip relative to the previous best known tip and whether any
+       /// blocks were indeed connected or disconnected.
+       pub async fn poll_best_tip(&mut self) -> BlockSourceResult<(ChainTip, bool)> {
+               let chain_tip = self.chain_poller.poll_chain_tip(self.chain_tip).await?;
+               let blocks_connected = match chain_tip {
+                       ChainTip::Common => false,
+                       ChainTip::Better(chain_tip) => {
+                               debug_assert_ne!(chain_tip.block_hash, self.chain_tip.block_hash);
+                               debug_assert!(chain_tip.chainwork > self.chain_tip.chainwork);
+                               self.update_chain_tip(chain_tip).await
+                       },
+                       ChainTip::Worse(chain_tip) => {
+                               debug_assert_ne!(chain_tip.block_hash, self.chain_tip.block_hash);
+                               debug_assert!(chain_tip.chainwork <= self.chain_tip.chainwork);
+                               false
+                       },
+               };
+               Ok((chain_tip, blocks_connected))
+       }
+
+       /// Updates the chain tip, syncing the chain listener with any connected or disconnected
+       /// blocks. Returns whether there were any such blocks.
+       async fn update_chain_tip(&mut self, best_chain_tip: ValidatedBlockHeader) -> bool {
+               match self.chain_notifier.synchronize_listener(
+                       best_chain_tip, &self.chain_tip, &mut self.chain_poller).await
+               {
+                       Ok(_) => {
+                               self.chain_tip = best_chain_tip;
+                               true
+                       },
+                       Err((_, Some(chain_tip))) if chain_tip.block_hash != self.chain_tip.block_hash => {
+                               self.chain_tip = chain_tip;
+                               true
+                       },
+                       Err(_) => false,
+               }
+       }
+}
+
+/// Notifies [listeners] of blocks that have been connected or disconnected from the chain.
+///
+/// [listeners]: ../../lightning/chain/trait.Listen.html
+pub struct ChainNotifier<'a, C: Cache, L: Deref> where L::Target: chain::Listen {
+       /// Cache for looking up headers before fetching from a block source.
+       header_cache: &'a mut C,
+
+       /// Listener that will be notified of connected or disconnected blocks.
+       chain_listener: L,
+}
+
+/// Changes made to the chain between subsequent polls that transformed it from having one chain tip
+/// to another.
+///
+/// Blocks are given in height-descending order. Therefore, blocks are first disconnected in order
+/// before new blocks are connected in reverse order.
+struct ChainDifference {
+       /// The most recent ancestor common between the chain tips.
+       ///
+       /// If there are any disconnected blocks, this is where the chain forked.
+       common_ancestor: ValidatedBlockHeader,
+
+       /// Blocks that were disconnected from the chain since the last poll.
+       disconnected_blocks: Vec<ValidatedBlockHeader>,
+
+       /// Blocks that were connected to the chain since the last poll.
+       connected_blocks: Vec<ValidatedBlockHeader>,
+}
+
+impl<'a, C: Cache, L: Deref> ChainNotifier<'a, C, L> where L::Target: chain::Listen {
+       /// Finds the first common ancestor between `new_header` and `old_header`, disconnecting blocks
+       /// from `old_header` to get to that point and then connecting blocks until `new_header`.
+       ///
+       /// Validates headers along the transition path, but doesn't fetch blocks until the chain is
+       /// disconnected to the fork point. Thus, this may return an `Err` that includes where the tip
+       /// ended up which may not be `new_header`. Note that the returned `Err` contains `Some` header
+       /// if and only if the transition from `old_header` to `new_header` is valid.
+       async fn synchronize_listener<P: Poll>(
+               &mut self,
+               new_header: ValidatedBlockHeader,
+               old_header: &ValidatedBlockHeader,
+               chain_poller: &mut P,
+       ) -> Result<(), (BlockSourceError, Option<ValidatedBlockHeader>)> {
+               let difference = self.find_difference(new_header, old_header, chain_poller).await
+                       .map_err(|e| (e, None))?;
+               self.disconnect_blocks(difference.disconnected_blocks);
+               self.connect_blocks(
+                       difference.common_ancestor,
+                       difference.connected_blocks,
+                       chain_poller,
+               ).await
+       }
+
+       /// Returns the changes needed to produce the chain with `current_header` as its tip from the
+       /// chain with `prev_header` as its tip.
+       ///
+       /// Walks backwards from `current_header` and `prev_header`, finding the common ancestor.
+       async fn find_difference<P: Poll>(
+               &self,
+               current_header: ValidatedBlockHeader,
+               prev_header: &ValidatedBlockHeader,
+               chain_poller: &mut P,
+       ) -> BlockSourceResult<ChainDifference> {
+               let mut disconnected_blocks = Vec::new();
+               let mut connected_blocks = Vec::new();
+               let mut current = current_header;
+               let mut previous = *prev_header;
+               loop {
+                       // Found the common ancestor.
+                       if current.block_hash == previous.block_hash {
+                               break;
+                       }
+
+                       // Walk back the chain, finding blocks needed to connect and disconnect. Only walk back
+                       // the header with the greater height, or both if equal heights.
+                       let current_height = current.height;
+                       let previous_height = previous.height;
+                       if current_height <= previous_height {
+                               disconnected_blocks.push(previous);
+                               previous = self.look_up_previous_header(chain_poller, &previous).await?;
+                       }
+                       if current_height >= previous_height {
+                               connected_blocks.push(current);
+                               current = self.look_up_previous_header(chain_poller, &current).await?;
+                       }
+               }
+
+               let common_ancestor = current;
+               Ok(ChainDifference { common_ancestor, disconnected_blocks, connected_blocks })
+       }
+
+       /// Returns the previous header for the given header, either by looking it up in the cache or
+       /// fetching it if not found.
+       async fn look_up_previous_header<P: Poll>(
+               &self,
+               chain_poller: &mut P,
+               header: &ValidatedBlockHeader,
+       ) -> BlockSourceResult<ValidatedBlockHeader> {
+               match self.header_cache.look_up(&header.header.prev_blockhash) {
+                       Some(prev_header) => Ok(*prev_header),
+                       None => chain_poller.look_up_previous_header(header).await,
+               }
+       }
+
+       /// Notifies the chain listeners of disconnected blocks.
+       fn disconnect_blocks(&mut self, mut disconnected_blocks: Vec<ValidatedBlockHeader>) {
+               for header in disconnected_blocks.drain(..) {
+                       if let Some(cached_header) = self.header_cache.block_disconnected(&header.block_hash) {
+                               assert_eq!(cached_header, header);
+                       }
+                       self.chain_listener.block_disconnected(&header.header, header.height);
+               }
+       }
+
+       /// Notifies the chain listeners of connected blocks.
+       async fn connect_blocks<P: Poll>(
+               &mut self,
+               mut new_tip: ValidatedBlockHeader,
+               mut connected_blocks: Vec<ValidatedBlockHeader>,
+               chain_poller: &mut P,
+       ) -> Result<(), (BlockSourceError, Option<ValidatedBlockHeader>)> {
+               for header in connected_blocks.drain(..).rev() {
+                       let block = chain_poller
+                               .fetch_block(&header).await
+                               .or_else(|e| Err((e, Some(new_tip))))?;
+                       debug_assert_eq!(block.block_hash, header.block_hash);
+
+                       self.header_cache.block_connected(header.block_hash, header);
+                       self.chain_listener.block_connected(&block, header.height);
+                       new_tip = header;
+               }
+
+               Ok(())
+       }
+}
+
+#[cfg(test)]
+mod spv_client_tests {
+       use crate::test_utils::{Blockchain, NullChainListener};
+       use super::*;
+
+       use bitcoin::network::constants::Network;
+
+       #[tokio::test]
+       async fn poll_from_chain_without_headers() {
+               let mut chain = Blockchain::default().with_height(3).without_headers();
+               let best_tip = chain.at_height(1);
+
+               let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
+               let mut cache = UnboundedCache::new();
+               let mut listener = NullChainListener {};
+               let mut client = SpvClient::new(best_tip, poller, &mut cache, &mut listener);
+               match client.poll_best_tip().await {
+                       Err(e) => {
+                               assert_eq!(e.kind(), BlockSourceErrorKind::Persistent);
+                               assert_eq!(e.into_inner().as_ref().to_string(), "header not found");
+                       },
+                       Ok(_) => panic!("Expected error"),
+               }
+               assert_eq!(client.chain_tip, best_tip);
+       }
+
+       #[tokio::test]
+       async fn poll_from_chain_with_common_tip() {
+               let mut chain = Blockchain::default().with_height(3);
+               let common_tip = chain.tip();
+
+               let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
+               let mut cache = UnboundedCache::new();
+               let mut listener = NullChainListener {};
+               let mut client = SpvClient::new(common_tip, poller, &mut cache, &mut listener);
+               match client.poll_best_tip().await {
+                       Err(e) => panic!("Unexpected error: {:?}", e),
+                       Ok((chain_tip, blocks_connected)) => {
+                               assert_eq!(chain_tip, ChainTip::Common);
+                               assert!(!blocks_connected);
+                       },
+               }
+               assert_eq!(client.chain_tip, common_tip);
+       }
+
+       #[tokio::test]
+       async fn poll_from_chain_with_better_tip() {
+               let mut chain = Blockchain::default().with_height(3);
+               let new_tip = chain.tip();
+               let old_tip = chain.at_height(1);
+
+               let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
+               let mut cache = UnboundedCache::new();
+               let mut listener = NullChainListener {};
+               let mut client = SpvClient::new(old_tip, poller, &mut cache, &mut listener);
+               match client.poll_best_tip().await {
+                       Err(e) => panic!("Unexpected error: {:?}", e),
+                       Ok((chain_tip, blocks_connected)) => {
+                               assert_eq!(chain_tip, ChainTip::Better(new_tip));
+                               assert!(blocks_connected);
+                       },
+               }
+               assert_eq!(client.chain_tip, new_tip);
+       }
+
+       #[tokio::test]
+       async fn poll_from_chain_with_better_tip_and_without_any_new_blocks() {
+               let mut chain = Blockchain::default().with_height(3).without_blocks(2..);
+               let new_tip = chain.tip();
+               let old_tip = chain.at_height(1);
+
+               let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
+               let mut cache = UnboundedCache::new();
+               let mut listener = NullChainListener {};
+               let mut client = SpvClient::new(old_tip, poller, &mut cache, &mut listener);
+               match client.poll_best_tip().await {
+                       Err(e) => panic!("Unexpected error: {:?}", e),
+                       Ok((chain_tip, blocks_connected)) => {
+                               assert_eq!(chain_tip, ChainTip::Better(new_tip));
+                               assert!(!blocks_connected);
+                       },
+               }
+               assert_eq!(client.chain_tip, old_tip);
+       }
+
+       #[tokio::test]
+       async fn poll_from_chain_with_better_tip_and_without_some_new_blocks() {
+               let mut chain = Blockchain::default().with_height(3).without_blocks(3..);
+               let new_tip = chain.tip();
+               let old_tip = chain.at_height(1);
+
+               let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
+               let mut cache = UnboundedCache::new();
+               let mut listener = NullChainListener {};
+               let mut client = SpvClient::new(old_tip, poller, &mut cache, &mut listener);
+               match client.poll_best_tip().await {
+                       Err(e) => panic!("Unexpected error: {:?}", e),
+                       Ok((chain_tip, blocks_connected)) => {
+                               assert_eq!(chain_tip, ChainTip::Better(new_tip));
+                               assert!(blocks_connected);
+                       },
+               }
+               assert_eq!(client.chain_tip, chain.at_height(2));
+       }
+
+       #[tokio::test]
+       async fn poll_from_chain_with_worse_tip() {
+               let mut chain = Blockchain::default().with_height(3);
+               let best_tip = chain.tip();
+               chain.disconnect_tip();
+               let worse_tip = chain.tip();
+
+               let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
+               let mut cache = UnboundedCache::new();
+               let mut listener = NullChainListener {};
+               let mut client = SpvClient::new(best_tip, poller, &mut cache, &mut listener);
+               match client.poll_best_tip().await {
+                       Err(e) => panic!("Unexpected error: {:?}", e),
+                       Ok((chain_tip, blocks_connected)) => {
+                               assert_eq!(chain_tip, ChainTip::Worse(worse_tip));
+                               assert!(!blocks_connected);
+                       },
+               }
+               assert_eq!(client.chain_tip, best_tip);
+       }
+}
+
+#[cfg(test)]
+mod chain_notifier_tests {
+       use crate::test_utils::{Blockchain, MockChainListener};
+       use super::*;
+
+       use bitcoin::network::constants::Network;
+
+       #[tokio::test]
+       async fn sync_from_same_chain() {
+               let mut chain = Blockchain::default().with_height(3);
+
+               let new_tip = chain.tip();
+               let old_tip = chain.at_height(1);
+               let chain_listener = &MockChainListener::new()
+                       .expect_block_connected(*chain.at_height(2))
+                       .expect_block_connected(*new_tip);
+               let mut notifier = ChainNotifier {
+                       header_cache: &mut chain.header_cache(0..=1),
+                       chain_listener,
+               };
+               let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
+               match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
+                       Err((e, _)) => panic!("Unexpected error: {:?}", e),
+                       Ok(_) => {},
+               }
+       }
+
+       #[tokio::test]
+       async fn sync_from_different_chains() {
+               let mut test_chain = Blockchain::with_network(Network::Testnet).with_height(1);
+               let main_chain = Blockchain::with_network(Network::Bitcoin).with_height(1);
+
+               let new_tip = test_chain.tip();
+               let old_tip = main_chain.tip();
+               let chain_listener = &MockChainListener::new();
+               let mut notifier = ChainNotifier {
+                       header_cache: &mut main_chain.header_cache(0..=1),
+                       chain_listener,
+               };
+               let mut poller = poll::ChainPoller::new(&mut test_chain, Network::Testnet);
+               match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
+                       Err((e, _)) => {
+                               assert_eq!(e.kind(), BlockSourceErrorKind::Persistent);
+                               assert_eq!(e.into_inner().as_ref().to_string(), "genesis block reached");
+                       },
+                       Ok(_) => panic!("Expected error"),
+               }
+       }
+
+       #[tokio::test]
+       async fn sync_from_equal_length_fork() {
+               let main_chain = Blockchain::default().with_height(2);
+               let mut fork_chain = main_chain.fork_at_height(1);
+
+               let new_tip = fork_chain.tip();
+               let old_tip = main_chain.tip();
+               let chain_listener = &MockChainListener::new()
+                       .expect_block_disconnected(*old_tip)
+                       .expect_block_connected(*new_tip);
+               let mut notifier = ChainNotifier {
+                       header_cache: &mut main_chain.header_cache(0..=2),
+                       chain_listener,
+               };
+               let mut poller = poll::ChainPoller::new(&mut fork_chain, Network::Testnet);
+               match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
+                       Err((e, _)) => panic!("Unexpected error: {:?}", e),
+                       Ok(_) => {},
+               }
+       }
+
+       #[tokio::test]
+       async fn sync_from_shorter_fork() {
+               let main_chain = Blockchain::default().with_height(3);
+               let mut fork_chain = main_chain.fork_at_height(1);
+               fork_chain.disconnect_tip();
+
+               let new_tip = fork_chain.tip();
+               let old_tip = main_chain.tip();
+               let chain_listener = &MockChainListener::new()
+                       .expect_block_disconnected(*old_tip)
+                       .expect_block_disconnected(*main_chain.at_height(2))
+                       .expect_block_connected(*new_tip);
+               let mut notifier = ChainNotifier {
+                       header_cache: &mut main_chain.header_cache(0..=3),
+                       chain_listener,
+               };
+               let mut poller = poll::ChainPoller::new(&mut fork_chain, Network::Testnet);
+               match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
+                       Err((e, _)) => panic!("Unexpected error: {:?}", e),
+                       Ok(_) => {},
+               }
+       }
+
+       #[tokio::test]
+       async fn sync_from_longer_fork() {
+               let mut main_chain = Blockchain::default().with_height(3);
+               let mut fork_chain = main_chain.fork_at_height(1);
+               main_chain.disconnect_tip();
+
+               let new_tip = fork_chain.tip();
+               let old_tip = main_chain.tip();
+               let chain_listener = &MockChainListener::new()
+                       .expect_block_disconnected(*old_tip)
+                       .expect_block_connected(*fork_chain.at_height(2))
+                       .expect_block_connected(*new_tip);
+               let mut notifier = ChainNotifier {
+                       header_cache: &mut main_chain.header_cache(0..=2),
+                       chain_listener,
+               };
+               let mut poller = poll::ChainPoller::new(&mut fork_chain, Network::Testnet);
+               match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
+                       Err((e, _)) => panic!("Unexpected error: {:?}", e),
+                       Ok(_) => {},
+               }
+       }
+
+       #[tokio::test]
+       async fn sync_from_chain_without_headers() {
+               let mut chain = Blockchain::default().with_height(3).without_headers();
+
+               let new_tip = chain.tip();
+               let old_tip = chain.at_height(1);
+               let chain_listener = &MockChainListener::new();
+               let mut notifier = ChainNotifier {
+                       header_cache: &mut chain.header_cache(0..=1),
+                       chain_listener,
+               };
+               let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
+               match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
+                       Err((_, tip)) => assert_eq!(tip, None),
+                       Ok(_) => panic!("Expected error"),
+               }
+       }
+
+       #[tokio::test]
+       async fn sync_from_chain_without_any_new_blocks() {
+               let mut chain = Blockchain::default().with_height(3).without_blocks(2..);
+
+               let new_tip = chain.tip();
+               let old_tip = chain.at_height(1);
+               let chain_listener = &MockChainListener::new();
+               let mut notifier = ChainNotifier {
+                       header_cache: &mut chain.header_cache(0..=3),
+                       chain_listener,
+               };
+               let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
+               match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
+                       Err((_, tip)) => assert_eq!(tip, Some(old_tip)),
+                       Ok(_) => panic!("Expected error"),
+               }
+       }
+
+       #[tokio::test]
+       async fn sync_from_chain_without_some_new_blocks() {
+               let mut chain = Blockchain::default().with_height(3).without_blocks(3..);
+
+               let new_tip = chain.tip();
+               let old_tip = chain.at_height(1);
+               let chain_listener = &MockChainListener::new()
+                       .expect_block_connected(*chain.at_height(2));
+               let mut notifier = ChainNotifier {
+                       header_cache: &mut chain.header_cache(0..=3),
+                       chain_listener,
+               };
+               let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
+               match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
+                       Err((_, tip)) => assert_eq!(tip, Some(chain.at_height(2))),
+                       Ok(_) => panic!("Expected error"),
+               }
+       }
+}
diff --git a/lightning-block-sync/src/poll.rs b/lightning-block-sync/src/poll.rs
new file mode 100644 (file)
index 0000000..34be243
--- /dev/null
@@ -0,0 +1,356 @@
+use crate::{AsyncBlockSourceResult, BlockHeaderData, BlockSource, BlockSourceError, BlockSourceResult};
+
+use bitcoin::blockdata::block::Block;
+use bitcoin::hash_types::BlockHash;
+use bitcoin::network::constants::Network;
+
+use std::ops::DerefMut;
+
+/// The `Poll` trait defines behavior for polling block sources for a chain tip and retrieving
+/// related chain data. It serves as an adapter for `BlockSource`.
+///
+/// [`ChainPoller`] adapts a single `BlockSource`, while any other implementations of `Poll` are
+/// required to be built in terms of it to ensure chain data validity.
+///
+/// [`ChainPoller`]: ../struct.ChainPoller.html
+pub trait Poll {
+       /// Returns a chain tip in terms of its relationship to the provided chain tip.
+       fn poll_chain_tip<'a>(&'a mut self, best_known_chain_tip: ValidatedBlockHeader) ->
+               AsyncBlockSourceResult<'a, ChainTip>;
+
+       /// Returns the header that preceded the given header in the chain.
+       fn look_up_previous_header<'a>(&'a mut self, header: &'a ValidatedBlockHeader) ->
+               AsyncBlockSourceResult<'a, ValidatedBlockHeader>;
+
+       /// Returns the block associated with the given header.
+       fn fetch_block<'a>(&'a mut self, header: &'a ValidatedBlockHeader) ->
+               AsyncBlockSourceResult<'a, ValidatedBlock>;
+}
+
+/// A chain tip relative to another chain tip in terms of block hash and chainwork.
+#[derive(Clone, Debug, PartialEq)]
+pub enum ChainTip {
+       /// A chain tip with the same hash as another chain's tip.
+       Common,
+
+       /// A chain tip with more chainwork than another chain's tip.
+       Better(ValidatedBlockHeader),
+
+       /// A chain tip with less or equal chainwork than another chain's tip. In either case, the
+       /// hashes of each tip will be different.
+       Worse(ValidatedBlockHeader),
+}
+
+/// The `Validate` trait defines behavior for validating chain data.
+pub(crate) trait Validate {
+       /// The validated data wrapper which can be dereferenced to obtain the validated data.
+       type T: std::ops::Deref<Target = Self>;
+
+       /// Validates the chain data against the given block hash and any criteria needed to ensure that
+       /// it is internally consistent.
+       fn validate(self, block_hash: BlockHash) -> BlockSourceResult<Self::T>;
+}
+
+impl Validate for BlockHeaderData {
+       type T = ValidatedBlockHeader;
+
+       fn validate(self, block_hash: BlockHash) -> BlockSourceResult<Self::T> {
+               self.header
+                       .validate_pow(&self.header.target())
+                       .or_else(|e| Err(BlockSourceError::persistent(e)))?;
+
+               // TODO: Use the result of validate_pow instead of recomputing the block hash once upstream.
+               if self.header.block_hash() != block_hash {
+                       return Err(BlockSourceError::persistent("invalid block hash"));
+               }
+
+               Ok(ValidatedBlockHeader { block_hash, inner: self })
+       }
+}
+
+impl Validate for Block {
+       type T = ValidatedBlock;
+
+       fn validate(self, block_hash: BlockHash) -> BlockSourceResult<Self::T> {
+               self.header
+                       .validate_pow(&self.header.target())
+                       .or_else(|e| Err(BlockSourceError::persistent(e)))?;
+
+               // TODO: Use the result of validate_pow instead of recomputing the block hash once upstream.
+               if self.block_hash() != block_hash {
+                       return Err(BlockSourceError::persistent("invalid block hash"));
+               }
+
+               if !self.check_merkle_root() {
+                       return Err(BlockSourceError::persistent("invalid merkle root"));
+               }
+
+               if !self.check_witness_commitment() {
+                       return Err(BlockSourceError::persistent("invalid witness commitment"));
+               }
+
+               Ok(ValidatedBlock { block_hash, inner: self })
+       }
+}
+
+/// A block header with validated proof of work and corresponding block hash.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct ValidatedBlockHeader {
+       pub(crate) block_hash: BlockHash,
+       inner: BlockHeaderData,
+}
+
+impl std::ops::Deref for ValidatedBlockHeader {
+       type Target = BlockHeaderData;
+
+       fn deref(&self) -> &Self::Target {
+               &self.inner
+       }
+}
+
+impl ValidatedBlockHeader {
+       /// Checks that the header correctly builds on previous_header: the claimed work differential
+       /// matches the actual PoW and the difficulty transition is possible, i.e., within 4x.
+       fn check_builds_on(&self, previous_header: &ValidatedBlockHeader, network: Network) -> BlockSourceResult<()> {
+               if self.header.prev_blockhash != previous_header.block_hash {
+                       return Err(BlockSourceError::persistent("invalid previous block hash"));
+               }
+
+               if self.height != previous_header.height + 1 {
+                       return Err(BlockSourceError::persistent("invalid block height"));
+               }
+
+               let work = self.header.work();
+               if self.chainwork != previous_header.chainwork + work {
+                       return Err(BlockSourceError::persistent("invalid chainwork"));
+               }
+
+               if let Network::Bitcoin = network {
+                       if self.height % 2016 == 0 {
+                               let previous_work = previous_header.header.work();
+                               if work > (previous_work << 2) || work < (previous_work >> 2) {
+                                       return Err(BlockSourceError::persistent("invalid difficulty transition"))
+                               }
+                       } else if self.header.bits != previous_header.header.bits {
+                               return Err(BlockSourceError::persistent("invalid difficulty"))
+                       }
+               }
+
+               Ok(())
+       }
+}
+
+/// A block with validated data against its transaction list and corresponding block hash.
+pub struct ValidatedBlock {
+       pub(crate) block_hash: BlockHash,
+       inner: Block,
+}
+
+impl std::ops::Deref for ValidatedBlock {
+       type Target = Block;
+
+       fn deref(&self) -> &Self::Target {
+               &self.inner
+       }
+}
+
+/// The canonical `Poll` implementation used for a single `BlockSource`.
+///
+/// Other `Poll` implementations must be built using `ChainPoller` as it provides the only means of
+/// validating chain data.
+pub struct ChainPoller<B: DerefMut<Target=T> + Sized + Sync + Send, T: BlockSource> {
+       block_source: B,
+       network: Network,
+}
+
+impl<B: DerefMut<Target=T> + Sized + Sync + Send, T: BlockSource> ChainPoller<B, T> {
+       /// Creates a new poller for the given block source.
+       ///
+       /// If the `network` parameter is mainnet, then the difficulty between blocks is checked for
+       /// validity.
+       pub fn new(block_source: B, network: Network) -> Self {
+               Self { block_source, network }
+       }
+}
+
+impl<B: DerefMut<Target=T> + Sized + Sync + Send, T: BlockSource> Poll for ChainPoller<B, T> {
+       fn poll_chain_tip<'a>(&'a mut self, best_known_chain_tip: ValidatedBlockHeader) ->
+               AsyncBlockSourceResult<'a, ChainTip>
+       {
+               Box::pin(async move {
+                       let (block_hash, height) = self.block_source.get_best_block().await?;
+                       if block_hash == best_known_chain_tip.header.block_hash() {
+                               return Ok(ChainTip::Common);
+                       }
+
+                       let chain_tip = self.block_source
+                               .get_header(&block_hash, height).await?
+                               .validate(block_hash)?;
+                       if chain_tip.chainwork > best_known_chain_tip.chainwork {
+                               Ok(ChainTip::Better(chain_tip))
+                       } else {
+                               Ok(ChainTip::Worse(chain_tip))
+                       }
+               })
+       }
+
+       fn look_up_previous_header<'a>(&'a mut self, header: &'a ValidatedBlockHeader) ->
+               AsyncBlockSourceResult<'a, ValidatedBlockHeader>
+       {
+               Box::pin(async move {
+                       if header.height == 0 {
+                               return Err(BlockSourceError::persistent("genesis block reached"));
+                       }
+
+                       let previous_hash = &header.header.prev_blockhash;
+                       let height = header.height - 1;
+                       let previous_header = self.block_source
+                               .get_header(previous_hash, Some(height)).await?
+                               .validate(*previous_hash)?;
+                       header.check_builds_on(&previous_header, self.network)?;
+
+                       Ok(previous_header)
+               })
+       }
+
+       fn fetch_block<'a>(&'a mut self, header: &'a ValidatedBlockHeader) ->
+               AsyncBlockSourceResult<'a, ValidatedBlock>
+       {
+               Box::pin(async move {
+                       self.block_source
+                               .get_block(&header.block_hash).await?
+                               .validate(header.block_hash)
+               })
+       }
+}
+
+#[cfg(test)]
+mod tests {
+       use crate::*;
+       use crate::test_utils::Blockchain;
+       use super::*;
+       use bitcoin::util::uint::Uint256;
+
+       #[tokio::test]
+       async fn poll_empty_chain() {
+               let mut chain = Blockchain::default().with_height(0);
+               let best_known_chain_tip = chain.tip();
+               chain.disconnect_tip();
+
+               let mut poller = ChainPoller::new(&mut chain, Network::Bitcoin);
+               match poller.poll_chain_tip(best_known_chain_tip).await {
+                       Err(e) => {
+                               assert_eq!(e.kind(), BlockSourceErrorKind::Transient);
+                               assert_eq!(e.into_inner().as_ref().to_string(), "empty chain");
+                       },
+                       Ok(_) => panic!("Expected error"),
+               }
+       }
+
+       #[tokio::test]
+       async fn poll_chain_without_headers() {
+               let mut chain = Blockchain::default().with_height(1).without_headers();
+               let best_known_chain_tip = chain.at_height(0);
+
+               let mut poller = ChainPoller::new(&mut chain, Network::Bitcoin);
+               match poller.poll_chain_tip(best_known_chain_tip).await {
+                       Err(e) => {
+                               assert_eq!(e.kind(), BlockSourceErrorKind::Persistent);
+                               assert_eq!(e.into_inner().as_ref().to_string(), "header not found");
+                       },
+                       Ok(_) => panic!("Expected error"),
+               }
+       }
+
+       #[tokio::test]
+       async fn poll_chain_with_invalid_pow() {
+               let mut chain = Blockchain::default().with_height(1);
+               let best_known_chain_tip = chain.at_height(0);
+
+               // Invalidate the tip by changing its target.
+               chain.blocks.last_mut().unwrap().header.bits =
+                       BlockHeader::compact_target_from_u256(&Uint256::from_be_bytes([0; 32]));
+
+               let mut poller = ChainPoller::new(&mut chain, Network::Bitcoin);
+               match poller.poll_chain_tip(best_known_chain_tip).await {
+                       Err(e) => {
+                               assert_eq!(e.kind(), BlockSourceErrorKind::Persistent);
+                               assert_eq!(e.into_inner().as_ref().to_string(), "block target correct but not attained");
+                       },
+                       Ok(_) => panic!("Expected error"),
+               }
+       }
+
+       #[tokio::test]
+       async fn poll_chain_with_malformed_headers() {
+               let mut chain = Blockchain::default().with_height(1).malformed_headers();
+               let best_known_chain_tip = chain.at_height(0);
+
+               let mut poller = ChainPoller::new(&mut chain, Network::Bitcoin);
+               match poller.poll_chain_tip(best_known_chain_tip).await {
+                       Err(e) => {
+                               assert_eq!(e.kind(), BlockSourceErrorKind::Persistent);
+                               assert_eq!(e.into_inner().as_ref().to_string(), "invalid block hash");
+                       },
+                       Ok(_) => panic!("Expected error"),
+               }
+       }
+
+       #[tokio::test]
+       async fn poll_chain_with_common_tip() {
+               let mut chain = Blockchain::default().with_height(0);
+               let best_known_chain_tip = chain.tip();
+
+               let mut poller = ChainPoller::new(&mut chain, Network::Bitcoin);
+               match poller.poll_chain_tip(best_known_chain_tip).await {
+                       Err(e) => panic!("Unexpected error: {:?}", e),
+                       Ok(tip) => assert_eq!(tip, ChainTip::Common),
+               }
+       }
+
+       #[tokio::test]
+       async fn poll_chain_with_uncommon_tip_but_equal_chainwork() {
+               let mut chain = Blockchain::default().with_height(1);
+               let best_known_chain_tip = chain.tip();
+
+               // Change the nonce to get a different block hash with the same chainwork.
+               chain.blocks.last_mut().unwrap().header.nonce += 1;
+               let worse_chain_tip = chain.tip();
+               assert_eq!(best_known_chain_tip.chainwork, worse_chain_tip.chainwork);
+
+               let mut poller = ChainPoller::new(&mut chain, Network::Bitcoin);
+               match poller.poll_chain_tip(best_known_chain_tip).await {
+                       Err(e) => panic!("Unexpected error: {:?}", e),
+                       Ok(tip) => assert_eq!(tip, ChainTip::Worse(worse_chain_tip)),
+               }
+       }
+
+       #[tokio::test]
+       async fn poll_chain_with_worse_tip() {
+               let mut chain = Blockchain::default().with_height(1);
+               let best_known_chain_tip = chain.tip();
+
+               chain.disconnect_tip();
+               let worse_chain_tip = chain.tip();
+
+               let mut poller = ChainPoller::new(&mut chain, Network::Bitcoin);
+               match poller.poll_chain_tip(best_known_chain_tip).await {
+                       Err(e) => panic!("Unexpected error: {:?}", e),
+                       Ok(tip) => assert_eq!(tip, ChainTip::Worse(worse_chain_tip)),
+               }
+       }
+
+       #[tokio::test]
+       async fn poll_chain_with_better_tip() {
+               let mut chain = Blockchain::default().with_height(1);
+               let best_known_chain_tip = chain.at_height(0);
+
+               let better_chain_tip = chain.tip();
+
+               let mut poller = ChainPoller::new(&mut chain, Network::Bitcoin);
+               match poller.poll_chain_tip(best_known_chain_tip).await {
+                       Err(e) => panic!("Unexpected error: {:?}", e),
+                       Ok(tip) => assert_eq!(tip, ChainTip::Better(better_chain_tip)),
+               }
+       }
+}
diff --git a/lightning-block-sync/src/rest.rs b/lightning-block-sync/src/rest.rs
new file mode 100644 (file)
index 0000000..3c2e76e
--- /dev/null
@@ -0,0 +1,110 @@
+use crate::{BlockHeaderData, BlockSource, AsyncBlockSourceResult};
+use crate::http::{BinaryResponse, HttpEndpoint, HttpClient, JsonResponse};
+
+use bitcoin::blockdata::block::Block;
+use bitcoin::hash_types::BlockHash;
+use bitcoin::hashes::hex::ToHex;
+
+use std::convert::TryFrom;
+use std::convert::TryInto;
+
+/// A simple REST client for requesting resources using HTTP `GET`.
+pub struct RestClient {
+       endpoint: HttpEndpoint,
+       client: HttpClient,
+}
+
+impl RestClient {
+       /// Creates a new REST client connected to the given endpoint.
+       ///
+       /// The endpoint should contain the REST path component (e.g., http://127.0.0.1:8332/rest).
+       pub fn new(endpoint: HttpEndpoint) -> std::io::Result<Self> {
+               let client = HttpClient::connect(&endpoint)?;
+               Ok(Self { endpoint, client })
+       }
+
+       /// Requests a resource encoded in `F` format and interpreted as type `T`.
+       async fn request_resource<F, T>(&mut self, resource_path: &str) -> std::io::Result<T>
+       where F: TryFrom<Vec<u8>, Error = std::io::Error> + TryInto<T, Error = std::io::Error> {
+               let host = format!("{}:{}", self.endpoint.host(), self.endpoint.port());
+               let uri = format!("{}/{}", self.endpoint.path().trim_end_matches("/"), resource_path);
+               self.client.get::<F>(&uri, &host).await?.try_into()
+       }
+}
+
+impl BlockSource for RestClient {
+       fn get_header<'a>(&'a mut self, header_hash: &'a BlockHash, _height: Option<u32>) -> AsyncBlockSourceResult<'a, BlockHeaderData> {
+               Box::pin(async move {
+                       let resource_path = format!("headers/1/{}.json", header_hash.to_hex());
+                       Ok(self.request_resource::<JsonResponse, _>(&resource_path).await?)
+               })
+       }
+
+       fn get_block<'a>(&'a mut self, header_hash: &'a BlockHash) -> AsyncBlockSourceResult<'a, Block> {
+               Box::pin(async move {
+                       let resource_path = format!("block/{}.bin", header_hash.to_hex());
+                       Ok(self.request_resource::<BinaryResponse, _>(&resource_path).await?)
+               })
+       }
+
+       fn get_best_block<'a>(&'a mut self) -> AsyncBlockSourceResult<'a, (BlockHash, Option<u32>)> {
+               Box::pin(async move {
+                       Ok(self.request_resource::<JsonResponse, _>("chaininfo.json").await?)
+               })
+       }
+}
+
+#[cfg(test)]
+mod tests {
+       use super::*;
+       use crate::http::BinaryResponse;
+       use crate::http::client_tests::{HttpServer, MessageBody};
+
+       /// Parses binary data as a string-encoded `u32`.
+       impl TryInto<u32> for BinaryResponse {
+               type Error = std::io::Error;
+
+               fn try_into(self) -> std::io::Result<u32> {
+                       match std::str::from_utf8(&self.0) {
+                               Err(e) => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, e)),
+                               Ok(s) => match u32::from_str_radix(s, 10) {
+                                       Err(e) => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, e)),
+                                       Ok(n) => Ok(n),
+                               }
+                       }
+               }
+       }
+
+       #[tokio::test]
+       async fn request_unknown_resource() {
+               let server = HttpServer::responding_with_not_found();
+               let mut client = RestClient::new(server.endpoint()).unwrap();
+
+               match client.request_resource::<BinaryResponse, u32>("/").await {
+                       Err(e) => assert_eq!(e.kind(), std::io::ErrorKind::NotFound),
+                       Ok(_) => panic!("Expected error"),
+               }
+       }
+
+       #[tokio::test]
+       async fn request_malformed_resource() {
+               let server = HttpServer::responding_with_ok(MessageBody::Content("foo"));
+               let mut client = RestClient::new(server.endpoint()).unwrap();
+
+               match client.request_resource::<BinaryResponse, u32>("/").await {
+                       Err(e) => assert_eq!(e.kind(), std::io::ErrorKind::InvalidData),
+                       Ok(_) => panic!("Expected error"),
+               }
+       }
+
+       #[tokio::test]
+       async fn request_valid_resource() {
+               let server = HttpServer::responding_with_ok(MessageBody::Content(42));
+               let mut client = RestClient::new(server.endpoint()).unwrap();
+
+               match client.request_resource::<BinaryResponse, u32>("/").await {
+                       Err(e) => panic!("Unexpected error: {:?}", e),
+                       Ok(n) => assert_eq!(n, 42),
+               }
+       }
+}
diff --git a/lightning-block-sync/src/rpc.rs b/lightning-block-sync/src/rpc.rs
new file mode 100644 (file)
index 0000000..34cbd2e
--- /dev/null
@@ -0,0 +1,197 @@
+use crate::{BlockHeaderData, BlockSource, AsyncBlockSourceResult};
+use crate::http::{HttpClient, HttpEndpoint, JsonResponse};
+
+use bitcoin::blockdata::block::Block;
+use bitcoin::hash_types::BlockHash;
+use bitcoin::hashes::hex::ToHex;
+
+use serde_json;
+
+use std::convert::TryFrom;
+use std::convert::TryInto;
+use std::sync::atomic::{AtomicUsize, Ordering};
+
+/// A simple RPC client for calling methods using HTTP `POST`.
+pub struct RpcClient {
+       basic_auth: String,
+       endpoint: HttpEndpoint,
+       client: HttpClient,
+       id: AtomicUsize,
+}
+
+impl RpcClient {
+       /// Creates a new RPC client connected to the given endpoint with the provided credentials. The
+       /// credentials should be a base64 encoding of a user name and password joined by a colon, as is
+       /// required for HTTP basic access authentication.
+       pub fn new(credentials: &str, endpoint: HttpEndpoint) -> std::io::Result<Self> {
+               let client = HttpClient::connect(&endpoint)?;
+               Ok(Self {
+                       basic_auth: "Basic ".to_string() + credentials,
+                       endpoint,
+                       client,
+                       id: AtomicUsize::new(0),
+               })
+       }
+
+       /// Calls a method with the response encoded in JSON format and interpreted as type `T`.
+       async fn call_method<T>(&mut self, method: &str, params: &[serde_json::Value]) -> std::io::Result<T>
+       where JsonResponse: TryFrom<Vec<u8>, Error = std::io::Error> + TryInto<T, Error = std::io::Error> {
+               let host = format!("{}:{}", self.endpoint.host(), self.endpoint.port());
+               let uri = self.endpoint.path();
+               let content = serde_json::json!({
+                       "method": method,
+                       "params": params,
+                       "id": &self.id.fetch_add(1, Ordering::AcqRel).to_string()
+               });
+
+               let mut response = self.client.post::<JsonResponse>(&uri, &host, &self.basic_auth, content)
+                       .await?.0;
+               if !response.is_object() {
+                       return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "expected JSON object"));
+               }
+
+               let error = &response["error"];
+               if !error.is_null() {
+                       // TODO: Examine error code for a more precise std::io::ErrorKind.
+                       let message = error["message"].as_str().unwrap_or("unknown error");
+                       return Err(std::io::Error::new(std::io::ErrorKind::Other, message));
+               }
+
+               let result = &mut response["result"];
+               if result.is_null() {
+                       return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "expected JSON result"));
+               }
+
+               JsonResponse(result.take()).try_into()
+       }
+}
+
+impl BlockSource for RpcClient {
+       fn get_header<'a>(&'a mut self, header_hash: &'a BlockHash, _height: Option<u32>) -> AsyncBlockSourceResult<'a, BlockHeaderData> {
+               Box::pin(async move {
+                       let header_hash = serde_json::json!(header_hash.to_hex());
+                       Ok(self.call_method("getblockheader", &[header_hash]).await?)
+               })
+       }
+
+       fn get_block<'a>(&'a mut self, header_hash: &'a BlockHash) -> AsyncBlockSourceResult<'a, Block> {
+               Box::pin(async move {
+                       let header_hash = serde_json::json!(header_hash.to_hex());
+                       let verbosity = serde_json::json!(0);
+                       Ok(self.call_method("getblock", &[header_hash, verbosity]).await?)
+               })
+       }
+
+       fn get_best_block<'a>(&'a mut self) -> AsyncBlockSourceResult<'a, (BlockHash, Option<u32>)> {
+               Box::pin(async move {
+                       Ok(self.call_method("getblockchaininfo", &[]).await?)
+               })
+       }
+}
+
+#[cfg(test)]
+mod tests {
+       use super::*;
+       use crate::http::client_tests::{HttpServer, MessageBody};
+
+       /// Credentials encoded in base64.
+       const CREDENTIALS: &'static str = "dXNlcjpwYXNzd29yZA==";
+
+       /// Converts a JSON value into `u64`.
+       impl TryInto<u64> for JsonResponse {
+               type Error = std::io::Error;
+
+               fn try_into(self) -> std::io::Result<u64> {
+                       match self.0.as_u64() {
+                               None => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "not a number")),
+                               Some(n) => Ok(n),
+                       }
+               }
+       }
+
+       #[tokio::test]
+       async fn call_method_returning_unknown_response() {
+               let server = HttpServer::responding_with_not_found();
+               let mut client = RpcClient::new(CREDENTIALS, server.endpoint()).unwrap();
+
+               match client.call_method::<u64>("getblockcount", &[]).await {
+                       Err(e) => assert_eq!(e.kind(), std::io::ErrorKind::NotFound),
+                       Ok(_) => panic!("Expected error"),
+               }
+       }
+
+       #[tokio::test]
+       async fn call_method_returning_malfomred_response() {
+               let response = serde_json::json!("foo");
+               let server = HttpServer::responding_with_ok(MessageBody::Content(response));
+               let mut client = RpcClient::new(CREDENTIALS, server.endpoint()).unwrap();
+
+               match client.call_method::<u64>("getblockcount", &[]).await {
+                       Err(e) => {
+                               assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
+                               assert_eq!(e.get_ref().unwrap().to_string(), "expected JSON object");
+                       },
+                       Ok(_) => panic!("Expected error"),
+               }
+       }
+
+       #[tokio::test]
+       async fn call_method_returning_error() {
+               let response = serde_json::json!({
+                       "error": { "code": -8, "message": "invalid parameter" },
+               });
+               let server = HttpServer::responding_with_ok(MessageBody::Content(response));
+               let mut client = RpcClient::new(CREDENTIALS, server.endpoint()).unwrap();
+
+               let invalid_block_hash = serde_json::json!("foo");
+               match client.call_method::<u64>("getblock", &[invalid_block_hash]).await {
+                       Err(e) => {
+                               assert_eq!(e.kind(), std::io::ErrorKind::Other);
+                               assert_eq!(e.get_ref().unwrap().to_string(), "invalid parameter");
+                       },
+                       Ok(_) => panic!("Expected error"),
+               }
+       }
+
+       #[tokio::test]
+       async fn call_method_returning_missing_result() {
+               let response = serde_json::json!({ "result": null });
+               let server = HttpServer::responding_with_ok(MessageBody::Content(response));
+               let mut client = RpcClient::new(CREDENTIALS, server.endpoint()).unwrap();
+
+               match client.call_method::<u64>("getblockcount", &[]).await {
+                       Err(e) => {
+                               assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
+                               assert_eq!(e.get_ref().unwrap().to_string(), "expected JSON result");
+                       },
+                       Ok(_) => panic!("Expected error"),
+               }
+       }
+
+       #[tokio::test]
+       async fn call_method_returning_malformed_result() {
+               let response = serde_json::json!({ "result": "foo" });
+               let server = HttpServer::responding_with_ok(MessageBody::Content(response));
+               let mut client = RpcClient::new(CREDENTIALS, server.endpoint()).unwrap();
+
+               match client.call_method::<u64>("getblockcount", &[]).await {
+                       Err(e) => {
+                               assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
+                               assert_eq!(e.get_ref().unwrap().to_string(), "not a number");
+                       },
+                       Ok(_) => panic!("Expected error"),
+               }
+       }
+
+       #[tokio::test]
+       async fn call_method_returning_valid_result() {
+               let response = serde_json::json!({ "result": 654470 });
+               let server = HttpServer::responding_with_ok(MessageBody::Content(response));
+               let mut client = RpcClient::new(CREDENTIALS, server.endpoint()).unwrap();
+
+               match client.call_method::<u64>("getblockcount", &[]).await {
+                       Err(e) => panic!("Unexpected error: {:?}", e),
+                       Ok(count) => assert_eq!(count, 654470),
+               }
+       }
+}
diff --git a/lightning-block-sync/src/test_utils.rs b/lightning-block-sync/src/test_utils.rs
new file mode 100644 (file)
index 0000000..8c37c94
--- /dev/null
@@ -0,0 +1,239 @@
+use crate::{AsyncBlockSourceResult, BlockHeaderData, BlockSource, BlockSourceError, UnboundedCache};
+use crate::poll::{Validate, ValidatedBlockHeader};
+
+use bitcoin::blockdata::block::{Block, BlockHeader};
+use bitcoin::blockdata::constants::genesis_block;
+use bitcoin::hash_types::BlockHash;
+use bitcoin::network::constants::Network;
+use bitcoin::util::uint::Uint256;
+
+use lightning::chain;
+
+use std::cell::RefCell;
+use std::collections::VecDeque;
+
+#[derive(Default)]
+pub struct Blockchain {
+       pub blocks: Vec<Block>,
+       without_blocks: Option<std::ops::RangeFrom<usize>>,
+       without_headers: bool,
+       malformed_headers: bool,
+}
+
+impl Blockchain {
+       pub fn default() -> Self {
+               Blockchain::with_network(Network::Bitcoin)
+       }
+
+       pub fn with_network(network: Network) -> Self {
+               let blocks = vec![genesis_block(network)];
+               Self { blocks, ..Default::default() }
+       }
+
+       pub fn with_height(mut self, height: usize) -> Self {
+               self.blocks.reserve_exact(height);
+               let bits = BlockHeader::compact_target_from_u256(&Uint256::from_be_bytes([0xff; 32]));
+               for i in 1..=height {
+                       let prev_block = &self.blocks[i - 1];
+                       let prev_blockhash = prev_block.block_hash();
+                       let time = prev_block.header.time + height as u32;
+                       self.blocks.push(Block {
+                               header: BlockHeader {
+                                       version: 0,
+                                       prev_blockhash,
+                                       merkle_root: Default::default(),
+                                       time,
+                                       bits,
+                                       nonce: 0,
+                               },
+                               txdata: vec![],
+                       });
+               }
+               self
+       }
+
+       pub fn without_blocks(self, range: std::ops::RangeFrom<usize>) -> Self {
+               Self { without_blocks: Some(range), ..self }
+       }
+
+       pub fn without_headers(self) -> Self {
+               Self { without_headers: true, ..self }
+       }
+
+       pub fn malformed_headers(self) -> Self {
+               Self { malformed_headers: true, ..self }
+       }
+
+       pub fn fork_at_height(&self, height: usize) -> Self {
+               assert!(height + 1 < self.blocks.len());
+               let mut blocks = self.blocks.clone();
+               let mut prev_blockhash = blocks[height].block_hash();
+               for block in blocks.iter_mut().skip(height + 1) {
+                       block.header.prev_blockhash = prev_blockhash;
+                       block.header.nonce += 1;
+                       prev_blockhash = block.block_hash();
+               }
+               Self { blocks, without_blocks: None, ..*self }
+       }
+
+       pub fn at_height(&self, height: usize) -> ValidatedBlockHeader {
+               let block_header = self.at_height_unvalidated(height);
+               let block_hash = self.blocks[height].block_hash();
+               block_header.validate(block_hash).unwrap()
+       }
+
+       fn at_height_unvalidated(&self, height: usize) -> BlockHeaderData {
+               assert!(!self.blocks.is_empty());
+               assert!(height < self.blocks.len());
+               BlockHeaderData {
+                       chainwork: self.blocks[0].header.work() + Uint256::from_u64(height as u64).unwrap(),
+                       height: height as u32,
+                       header: self.blocks[height].header.clone(),
+               }
+       }
+
+       pub fn tip(&self) -> ValidatedBlockHeader {
+               assert!(!self.blocks.is_empty());
+               self.at_height(self.blocks.len() - 1)
+       }
+
+       pub fn disconnect_tip(&mut self) -> Option<Block> {
+               self.blocks.pop()
+       }
+
+       pub fn header_cache(&self, heights: std::ops::RangeInclusive<usize>) -> UnboundedCache {
+               let mut cache = UnboundedCache::new();
+               for i in heights {
+                       let value = self.at_height(i);
+                       let key = value.header.block_hash();
+                       assert!(cache.insert(key, value).is_none());
+               }
+               cache
+       }
+}
+
+impl BlockSource for Blockchain {
+       fn get_header<'a>(&'a mut self, header_hash: &'a BlockHash, _height_hint: Option<u32>) -> AsyncBlockSourceResult<'a, BlockHeaderData> {
+               Box::pin(async move {
+                       if self.without_headers {
+                               return Err(BlockSourceError::persistent("header not found"));
+                       }
+
+                       for (height, block) in self.blocks.iter().enumerate() {
+                               if block.header.block_hash() == *header_hash {
+                                       let mut header_data = self.at_height_unvalidated(height);
+                                       if self.malformed_headers {
+                                               header_data.header.time += 1;
+                                       }
+
+                                       return Ok(header_data);
+                               }
+                       }
+                       Err(BlockSourceError::transient("header not found"))
+               })
+       }
+
+       fn get_block<'a>(&'a mut self, header_hash: &'a BlockHash) -> AsyncBlockSourceResult<'a, Block> {
+               Box::pin(async move {
+                       for (height, block) in self.blocks.iter().enumerate() {
+                               if block.header.block_hash() == *header_hash {
+                                       if let Some(without_blocks) = &self.without_blocks {
+                                               if without_blocks.contains(&height) {
+                                                       return Err(BlockSourceError::persistent("block not found"));
+                                               }
+                                       }
+
+                                       return Ok(block.clone());
+                               }
+                       }
+                       Err(BlockSourceError::transient("block not found"))
+               })
+       }
+
+       fn get_best_block<'a>(&'a mut self) -> AsyncBlockSourceResult<'a, (BlockHash, Option<u32>)> {
+               Box::pin(async move {
+                       match self.blocks.last() {
+                               None => Err(BlockSourceError::transient("empty chain")),
+                               Some(block) => {
+                                       let height = (self.blocks.len() - 1) as u32;
+                                       Ok((block.block_hash(), Some(height)))
+                               },
+                       }
+               })
+       }
+}
+
+pub struct NullChainListener;
+
+impl chain::Listen for NullChainListener {
+       fn block_connected(&self, _block: &Block, _height: u32) {}
+       fn block_disconnected(&self, _header: &BlockHeader, _height: u32) {}
+}
+
+pub struct MockChainListener {
+       expected_blocks_connected: RefCell<VecDeque<BlockHeaderData>>,
+       expected_blocks_disconnected: RefCell<VecDeque<BlockHeaderData>>,
+}
+
+impl MockChainListener {
+       pub fn new() -> Self {
+               Self {
+                       expected_blocks_connected: RefCell::new(VecDeque::new()),
+                       expected_blocks_disconnected: RefCell::new(VecDeque::new()),
+               }
+       }
+
+       pub fn expect_block_connected(self, block: BlockHeaderData) -> Self {
+               self.expected_blocks_connected.borrow_mut().push_back(block);
+               self
+       }
+
+       pub fn expect_block_disconnected(self, block: BlockHeaderData) -> Self {
+               self.expected_blocks_disconnected.borrow_mut().push_back(block);
+               self
+       }
+}
+
+impl chain::Listen for MockChainListener {
+       fn block_connected(&self, block: &Block, height: u32) {
+               match self.expected_blocks_connected.borrow_mut().pop_front() {
+                       None => {
+                               panic!("Unexpected block connected: {:?}", block.block_hash());
+                       },
+                       Some(expected_block) => {
+                               assert_eq!(block.block_hash(), expected_block.header.block_hash());
+                               assert_eq!(height, expected_block.height);
+                       },
+               }
+       }
+
+       fn block_disconnected(&self, header: &BlockHeader, height: u32) {
+               match self.expected_blocks_disconnected.borrow_mut().pop_front() {
+                       None => {
+                               panic!("Unexpected block disconnected: {:?}", header.block_hash());
+                       },
+                       Some(expected_block) => {
+                               assert_eq!(header.block_hash(), expected_block.header.block_hash());
+                               assert_eq!(height, expected_block.height);
+                       },
+               }
+       }
+}
+
+impl Drop for MockChainListener {
+       fn drop(&mut self) {
+               if std::thread::panicking() {
+                       return;
+               }
+
+               let expected_blocks_connected = self.expected_blocks_connected.borrow();
+               if !expected_blocks_connected.is_empty() {
+                       panic!("Expected blocks connected: {:?}", expected_blocks_connected);
+               }
+
+               let expected_blocks_disconnected = self.expected_blocks_disconnected.borrow();
+               if !expected_blocks_disconnected.is_empty() {
+                       panic!("Expected blocks disconnected: {:?}", expected_blocks_disconnected);
+               }
+       }
+}
diff --git a/lightning-block-sync/src/utils.rs b/lightning-block-sync/src/utils.rs
new file mode 100644 (file)
index 0000000..96a2e57
--- /dev/null
@@ -0,0 +1,54 @@
+use bitcoin::hashes::hex::FromHex;
+use bitcoin::util::uint::Uint256;
+
+pub fn hex_to_uint256(hex: &str) -> Result<Uint256, bitcoin::hashes::hex::Error> {
+       let bytes = <[u8; 32]>::from_hex(hex)?;
+       Ok(Uint256::from_be_bytes(bytes))
+}
+
+#[cfg(test)]
+mod tests {
+       use super::*;
+       use bitcoin::util::uint::Uint256;
+
+       #[test]
+       fn hex_to_uint256_empty_str() {
+               assert!(hex_to_uint256("").is_err());
+       }
+
+       #[test]
+       fn hex_to_uint256_too_short_str() {
+               let hex = String::from_utf8(vec![b'0'; 32]).unwrap();
+               assert_eq!(hex_to_uint256(&hex), Err(bitcoin::hashes::hex::Error::InvalidLength(64, 32)));
+       }
+
+       #[test]
+       fn hex_to_uint256_too_long_str() {
+               let hex = String::from_utf8(vec![b'0'; 128]).unwrap();
+               assert_eq!(hex_to_uint256(&hex), Err(bitcoin::hashes::hex::Error::InvalidLength(64, 128)));
+       }
+
+       #[test]
+       fn hex_to_uint256_odd_length_str() {
+               let hex = String::from_utf8(vec![b'0'; 65]).unwrap();
+               assert_eq!(hex_to_uint256(&hex), Err(bitcoin::hashes::hex::Error::OddLengthString(65)));
+       }
+
+       #[test]
+       fn hex_to_uint256_invalid_char() {
+               let hex = String::from_utf8(vec![b'G'; 64]).unwrap();
+               assert_eq!(hex_to_uint256(&hex), Err(bitcoin::hashes::hex::Error::InvalidChar(b'G')));
+       }
+
+       #[test]
+       fn hex_to_uint256_lowercase_str() {
+               let hex: String = std::iter::repeat("0123456789abcdef").take(4).collect();
+               assert_eq!(hex_to_uint256(&hex).unwrap(), Uint256([0x0123456789abcdefu64; 4]));
+       }
+
+       #[test]
+       fn hex_to_uint256_uppercase_str() {
+               let hex: String = std::iter::repeat("0123456789ABCDEF").take(4).collect();
+               assert_eq!(hex_to_uint256(&hex).unwrap(), Uint256([0x0123456789abcdefu64; 4]));
+       }
+}
index 6bde30475f93382ffe58d0f0df3eaf63a580d57f..76047314ea148ad27d667ec63155a2f91a43bde8 100644 (file)
@@ -15,9 +15,21 @@ crate-type = ["staticlib"
 ,"cdylib"]
 
 [dependencies]
-bitcoin = "0.24"
+bitcoin = "0.26"
+secp256k1 = { version = "0.20.1", features = ["global-context-less-secure"] }
 lightning = { version = "0.0.12", path = "../lightning" }
 
+[patch.crates-io]
+# Rust-Secp256k1 PR 279. Should be dropped once merged.
+secp256k1 = { git = 'https://github.com/TheBlueMatt/rust-secp256k1', rev = '15a0d4195a20355f6b1e8f54c84eba56abc15cbd' }
+
+# Always force panic=abort, further options are set in the genbindings.sh build script
+[profile.dev]
+panic = "abort"
+
+[profile.release]
+panic = "abort"
+
 # We eventually want to join the root workspace, but for now, the bindings generation is
 # a bit brittle and we don't want to hold up other developers from making changes just
 # because they break the bindings
index 48267780f3190b9eeee6d1e49a3c686e8d288c20..9480b8688c71f6b6fba21c3cfbbeec6cef3df39e 100644 (file)
@@ -550,3 +550,6 @@ default_features = true
 #
 # default: []
 features = ["cbindgen"]
+
+[ptr]
+non_null_attribute = "NONNULL_PTR"
index 0f8bd102a48189be60b5156a686297a54fd2ac60..3f7c4be9d2fe2b9307d51173f15702c995a5949e 100644 (file)
@@ -68,7 +68,7 @@ int main() {
                .free = NULL,
        };
 
-       LDKKeysManager keys = KeysManager_new(&node_seed, net, 0, 0);
+       LDKKeysManager keys = KeysManager_new(&node_seed, 0, 0);
        LDKKeysInterface keys_source = KeysManager_as_KeysInterface(&keys);
 
        LDKUserConfig config = UserConfig_default();
index 531d7e679e522c38b59cb3285742765b40432bbb..84f27448a33f76259f064105e627d8ec2c7e558a 100644 (file)
@@ -9,6 +9,7 @@ extern "C" {
 #include <sys/socket.h>
 #include <unistd.h>
 
+#include <atomic>
 #include <chrono>
 #include <functional>
 #include <thread>
@@ -60,16 +61,16 @@ const uint8_t channel_open_tx[] = {
        0x02, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-       0x01, 0x40, 0x9c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x22, 0x00, 0x20, 0x20, 0x12, 0x70, 0x44,
-       0x41, 0x40, 0xaf, 0xc5, 0x72, 0x97, 0xc8, 0x69, 0xba, 0x04, 0xdb, 0x28, 0x7b, 0xd7, 0x32, 0x07,
-       0x33, 0x3a, 0x4a, 0xc2, 0xc5, 0x56, 0x06, 0x05, 0x65, 0xd7, 0xa8, 0xcf, 0x01, 0x00, 0x00, 0x00,
+       0x01, 0x40, 0x9c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x22, 0x00, 0x20, 0xd1, 0xd9, 0x13, 0xa9,
+       0x76, 0x09, 0x05, 0xa3, 0x4d, 0x13, 0x5b, 0x69, 0xaa, 0xe7, 0x79, 0x71, 0xb9, 0x75, 0xa1, 0xd0,
+       0x77, 0xcb, 0xa2, 0xf6, 0x6a, 0x25, 0x37, 0x3a, 0xaf, 0xdc, 0x11, 0x09, 0x01, 0x00, 0x00, 0x00,
        0x00, 0x00
 };
 
 // The first transaction in the block is header (80 bytes) + transaction count (1 byte) into the block data.
 const uint8_t channel_open_txid[] = {
-       0x5f, 0xa9, 0x4c, 0xee, 0x7d, 0x4f, 0x4c, 0x75, 0xbb, 0xb8, 0x98, 0xcf, 0xce, 0x5a, 0x84, 0x63,
-       0xde, 0x96, 0xa9, 0xbb, 0x34, 0x9a, 0x7a, 0xf9, 0x3f, 0x6a, 0xe0, 0xd4, 0xf8, 0xd2, 0x47, 0xa2
+       0x02, 0xe0, 0x50, 0x05, 0x33, 0xd3, 0x29, 0x66, 0x0c, 0xb2, 0xcb, 0x1e, 0x7a, 0x4a, 0xc7, 0xc7,
+       0x8b, 0x02, 0x46, 0x7e, 0x30, 0x2c, 0xe6, 0x19, 0xce, 0x43, 0x3e, 0xdf, 0x43, 0x65, 0xae, 0xf9,
 };
 
 // Two blocks built on top of channel_open_block:
@@ -98,6 +99,10 @@ const LDKThirtyTwoBytes payment_hash_1 = {
        }
 };
 
+const LDKThirtyTwoBytes genesis_hash = { // We don't care particularly if this is "right"
+       .data = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1 }
+};
+
 void print_log(const void *this_arg, const char *record) {
        printf("%p - %s\n", this_arg, record);
 }
@@ -117,7 +122,7 @@ const LDKFeeEstimator fee_est {
        .free = NULL,
 };
 
-static int num_txs_broadcasted = 0; // Technically a race, but ints are atomic on x86
+static std::atomic_int num_txs_broadcasted(0);
 void broadcast_tx(const void *this_arg, LDKTransaction tx) {
        num_txs_broadcasted += 1;
        //TODO
@@ -148,7 +153,7 @@ LDKCResult_NoneChannelMonitorUpdateErrZ add_channel_monitor(const void *this_arg
        arg->mons.push_back(std::make_pair(std::move(funding_txo), std::move(mon)));
        return CResult_NoneChannelMonitorUpdateErrZ_ok();
 }
-static int mons_updated = 0; // Technically a race, but ints are atomic on x86.
+static std::atomic_int mons_updated(0);
 LDKCResult_NoneChannelMonitorUpdateErrZ update_channel_monitor(const void *this_arg, LDKOutPoint funding_txo_arg, LDKChannelMonitorUpdate monitor_arg) {
        // First bind the args to C++ objects so they auto-free
        LDK::ChannelMonitorUpdate update(std::move(monitor_arg));
@@ -220,13 +225,74 @@ void sock_read_data_thread(int rdfd, LDKSocketDescriptor *peer_descriptor, LDKPe
        PeerManager_socket_disconnected(&*pm, peer_descriptor);
 }
 
-int main() {
-       uint8_t node_seed[32];
-       memset(&node_seed, 0, 32);
+class PeersConnection {
+       int pipefds_1_to_2[2];
+       int pipefds_2_to_1[2];
+       std::thread t1, t2;
+       LDKSocketDescriptor sock1, sock2;
+
+public:
+       PeersConnection(LDK::ChannelManager& cm1, LDK::ChannelManager& cm2, LDK::PeerManager& net1, LDK::PeerManager& net2) {
+               assert(!pipe(pipefds_1_to_2));
+               assert(!pipe(pipefds_2_to_1));
+
+               sock1 = LDKSocketDescriptor {
+                       .this_arg = (void*)(long)pipefds_1_to_2[1],
+                       .send_data = sock_send_data,
+                       .disconnect_socket = sock_disconnect_socket,
+                       .eq = sock_eq,
+                       .hash = sock_hash,
+                       .clone = NULL,
+                       .free = NULL,
+               };
+
+               sock2 = LDKSocketDescriptor {
+                       .this_arg = (void*)(long)pipefds_2_to_1[1],
+                       .send_data = sock_send_data,
+                       .disconnect_socket = sock_disconnect_socket,
+                       .eq = sock_eq,
+                       .hash = sock_hash,
+                       .clone = NULL,
+                       .free = NULL,
+               };
+
+               t1 = std::thread(&sock_read_data_thread, pipefds_2_to_1[0], &sock1, &net1);
+               t2 = std::thread(&sock_read_data_thread, pipefds_1_to_2[0], &sock2, &net2);
+
+               // Note that we have to bind the result to a C++ class to make sure it gets free'd
+               LDK::CResult_CVec_u8ZPeerHandleErrorZ con_res = PeerManager_new_outbound_connection(&net1, ChannelManager_get_our_node_id(&cm2), sock1);
+               assert(con_res->result_ok);
+               LDK::CResult_NonePeerHandleErrorZ con_res2 = PeerManager_new_inbound_connection(&net2, sock2);
+               assert(con_res2->result_ok);
+
+               auto writelen = write(pipefds_1_to_2[1], con_res->contents.result->data, con_res->contents.result->datalen);
+               assert(writelen > 0 && uint64_t(writelen) == con_res->contents.result->datalen);
 
+               while (true) {
+                       // Wait for the initial handshakes to complete...
+                       LDK::CVec_PublicKeyZ peers_1 = PeerManager_get_peer_node_ids(&net1);
+                       LDK::CVec_PublicKeyZ peers_2 = PeerManager_get_peer_node_ids(&net2);
+                       if (peers_1->datalen == 1 && peers_2->datalen ==1) { break; }
+                       std::this_thread::yield();
+               }
+       }
+
+       void stop() {
+               close(pipefds_1_to_2[0]);
+               close(pipefds_2_to_1[0]);
+               close(pipefds_1_to_2[1]);
+               close(pipefds_2_to_1[1]);
+               t1.join();
+               t2.join();
+       }
+};
+
+int main() {
        LDKPublicKey null_pk;
        memset(&null_pk, 0, sizeof(null_pk));
 
+       LDKThirtyTwoBytes random_bytes;
+
        LDKNetwork network = LDKNetwork_Testnet;
 
        // Trait implementations:
@@ -236,8 +302,7 @@ int main() {
                .free = NULL,
        };
 
-       // Instantiate classes for node 1:
-
+       // Instantiate classes for the nodes that don't get reloaded on a ser-des reload
        LDKLogger logger1 {
                .this_arg = (void*)1,
                .log = print_log,
@@ -254,30 +319,8 @@ int main() {
                .free = NULL,
        };
 
-       LDK::KeysManager keys1 = KeysManager_new(&node_seed, network, 0, 0);
-       LDK::KeysInterface keys_source1 = KeysManager_as_KeysInterface(&keys1);
-       LDKSecretKey node_secret1 = keys_source1->get_node_secret(keys_source1->this_arg);
-
-       LDK::UserConfig config1 = UserConfig_default();
-       LDK::ChannelManager cm1 = ChannelManager_new(network, fee_est, mon1, broadcast, logger1, KeysManager_as_KeysInterface(&keys1), config1, 0);
-
-       LDK::CVec_ChannelDetailsZ channels = ChannelManager_list_channels(&cm1);
-       assert(channels->datalen == 0);
-
-       LDK::NetGraphMsgHandler net_graph1 = NetGraphMsgHandler_new(NULL, logger1);
-
-       LDK::MessageHandler msg_handler1 = MessageHandler_new(ChannelManager_as_ChannelMessageHandler(&cm1), NetGraphMsgHandler_as_RoutingMessageHandler(&net_graph1));
-
-       LDKThirtyTwoBytes random_bytes = keys_source1->get_secure_random_bytes(keys_source1->this_arg);
-       LDK::PeerManager net1 = PeerManager_new(msg_handler1, node_secret1, &random_bytes.data, logger1);
-
-       // Demo getting a channel key and check that its returning real pubkeys:
-       LDK::ChannelKeys chan_keys1 = keys_source1->get_channel_keys(keys_source1->this_arg, false, 42);
-       chan_keys1->set_pubkeys(&chan_keys1); // Make sure pubkeys is defined
-       LDKPublicKey payment_point = ChannelPublicKeys_get_payment_point(&chan_keys1->pubkeys);
-       assert(memcmp(&payment_point, &null_pk, sizeof(null_pk)));
-
-       // Instantiate classes for node 2:
+       LDK::NetGraphMsgHandler net_graph1 = NetGraphMsgHandler_new(genesis_hash, NULL, logger1);
+       LDKSecretKey node_secret1;
 
        LDKLogger logger2 {
                .this_arg = (void*)2,
@@ -295,239 +338,284 @@ int main() {
                .free = NULL,
        };
 
-       memset(&node_seed, 1, 32);
-       LDK::KeysManager keys2 = KeysManager_new(&node_seed, network, 0, 0);
-       LDK::KeysInterface keys_source2 = KeysManager_as_KeysInterface(&keys2);
-       LDKSecretKey node_secret2 = keys_source2->get_node_secret(keys_source2->this_arg);
-
-       LDK::ChannelHandshakeConfig handshake_config2 = ChannelHandshakeConfig_default();
-       ChannelHandshakeConfig_set_minimum_depth(&handshake_config2, 2);
-       LDK::UserConfig config2 = UserConfig_default();
-       UserConfig_set_own_channel_config(&config2, handshake_config2);
-
-       LDK::ChannelManager cm2 = ChannelManager_new(network, fee_est, mon2, broadcast, logger2, KeysManager_as_KeysInterface(&keys2), config2, 0);
-
-       LDK::CVec_ChannelDetailsZ channels2 = ChannelManager_list_channels(&cm2);
-       assert(channels2->datalen == 0);
-
-       LDK::NetGraphMsgHandler net_graph2 = NetGraphMsgHandler_new(NULL, logger2);
-       LDK::RoutingMessageHandler net_msgs2 = NetGraphMsgHandler_as_RoutingMessageHandler(&net_graph2);
-       LDK::ChannelAnnouncement chan_ann = ChannelAnnouncement_read(LDKu8slice { .data = valid_node_announcement, .datalen = sizeof(valid_node_announcement) });
-       LDK::CResult_boolLightningErrorZ ann_res = net_msgs2->handle_channel_announcement(net_msgs2->this_arg, &chan_ann);
-       assert(ann_res->result_ok);
-
-       LDK::MessageHandler msg_handler2 = MessageHandler_new(ChannelManager_as_ChannelMessageHandler(&cm2), net_msgs2);
-
-       LDKThirtyTwoBytes random_bytes2 = keys_source2->get_secure_random_bytes(keys_source2->this_arg);
-       LDK::PeerManager net2 = PeerManager_new(msg_handler2, node_secret2, &random_bytes2.data, logger2);
-
-       // Open a connection!
-       int pipefds_1_to_2[2];
-       int pipefds_2_to_1[2];
-       assert(!pipe(pipefds_1_to_2));
-       assert(!pipe(pipefds_2_to_1));
-
-       LDKSocketDescriptor sock1 {
-               .this_arg = (void*)(long)pipefds_1_to_2[1],
-               .send_data = sock_send_data,
-               .disconnect_socket = sock_disconnect_socket,
-               .eq = sock_eq,
-               .hash = sock_hash,
-               .clone = NULL,
-               .free = NULL,
-       };
-
-       LDKSocketDescriptor sock2 {
-               .this_arg = (void*)(long)pipefds_2_to_1[1],
-               .send_data = sock_send_data,
-               .disconnect_socket = sock_disconnect_socket,
-               .eq = sock_eq,
-               .hash = sock_hash,
-               .clone = NULL,
-               .free = NULL,
-       };
-
-       std::thread t1(&sock_read_data_thread, pipefds_2_to_1[0], &sock1, &net1);
-       std::thread t2(&sock_read_data_thread, pipefds_1_to_2[0], &sock2, &net2);
-
-       // Note that we have to bind the result to a C++ class to make sure it gets free'd
-       LDK::CResult_CVec_u8ZPeerHandleErrorZ con_res = PeerManager_new_outbound_connection(&net1, ChannelManager_get_our_node_id(&cm2), sock1);
-       assert(con_res->result_ok);
-       LDK::CResult_NonePeerHandleErrorZ con_res2 = PeerManager_new_inbound_connection(&net2, sock2);
-       assert(con_res2->result_ok);
-
-       auto writelen = write(pipefds_1_to_2[1], con_res->contents.result->data, con_res->contents.result->datalen);
-       assert(writelen > 0 && uint64_t(writelen) == con_res->contents.result->datalen);
+       LDK::NetGraphMsgHandler net_graph2 = NetGraphMsgHandler_new(genesis_hash, NULL, logger2);
+       LDKSecretKey node_secret2;
+
+       LDK::CVec_u8Z cm1_ser = LDKCVec_u8Z {}; // ChannelManager 1 serialization at the end of the ser-des scope
+       LDK::CVec_u8Z cm2_ser = LDKCVec_u8Z {}; // ChannelManager 2 serialization at the end of the ser-des scope
+
+       { // Scope for the ser-des reload
+               // Instantiate classes for node 1:
+               uint8_t node_seed[32];
+               memset(&node_seed, 0, 32);
+               LDK::KeysManager keys1 = KeysManager_new(&node_seed, 0, 0);
+               LDK::KeysInterface keys_source1 = KeysManager_as_KeysInterface(&keys1);
+               node_secret1 = keys_source1->get_node_secret(keys_source1->this_arg);
+
+               LDK::ChannelManager cm1 = ChannelManager_new(network, fee_est, mon1, broadcast, logger1, KeysManager_as_KeysInterface(&keys1), UserConfig_default(), 0);
+
+               LDK::CVec_ChannelDetailsZ channels = ChannelManager_list_channels(&cm1);
+               assert(channels->datalen == 0);
+
+               LDK::MessageHandler msg_handler1 = MessageHandler_new(ChannelManager_as_ChannelMessageHandler(&cm1), NetGraphMsgHandler_as_RoutingMessageHandler(&net_graph1));
+
+               random_bytes = keys_source1->get_secure_random_bytes(keys_source1->this_arg);
+               LDK::PeerManager net1 = PeerManager_new(std::move(msg_handler1), node_secret1, &random_bytes.data, logger1);
+
+               // Demo getting a channel key and check that its returning real pubkeys:
+               LDK::Sign chan_signer1 = keys_source1->get_channel_signer(keys_source1->this_arg, false, 42);
+               chan_signer1->set_pubkeys(&chan_signer1); // Make sure pubkeys is defined
+               LDKPublicKey payment_point = ChannelPublicKeys_get_payment_point(&chan_signer1->pubkeys);
+               assert(memcmp(&payment_point, &null_pk, sizeof(null_pk)));
+
+               // Instantiate classes for node 2:
+               memset(&node_seed, 1, 32);
+               LDK::KeysManager keys2 = KeysManager_new(&node_seed, 0, 0);
+               LDK::KeysInterface keys_source2 = KeysManager_as_KeysInterface(&keys2);
+               node_secret2 = keys_source2->get_node_secret(keys_source2->this_arg);
+
+               LDK::ChannelHandshakeConfig handshake_config2 = ChannelHandshakeConfig_default();
+               ChannelHandshakeConfig_set_minimum_depth(&handshake_config2, 2);
+               LDK::UserConfig config2 = UserConfig_default();
+               UserConfig_set_own_channel_config(&config2, std::move(handshake_config2));
+
+               LDK::ChannelManager cm2 = ChannelManager_new(network, fee_est, mon2, broadcast, logger2, KeysManager_as_KeysInterface(&keys2), std::move(config2), 0);
+
+               LDK::CVec_ChannelDetailsZ channels2 = ChannelManager_list_channels(&cm2);
+               assert(channels2->datalen == 0);
+
+               LDK::RoutingMessageHandler net_msgs2 = NetGraphMsgHandler_as_RoutingMessageHandler(&net_graph2);
+               LDK::CResult_ChannelAnnouncementDecodeErrorZ chan_ann = ChannelAnnouncement_read(LDKu8slice { .data = valid_node_announcement, .datalen = sizeof(valid_node_announcement) });
+               assert(chan_ann->result_ok);
+               LDK::CResult_boolLightningErrorZ ann_res = net_msgs2->handle_channel_announcement(net_msgs2->this_arg, chan_ann->contents.result);
+               assert(ann_res->result_ok);
+
+               LDK::MessageHandler msg_handler2 = MessageHandler_new(ChannelManager_as_ChannelMessageHandler(&cm2), std::move(net_msgs2));
+
+               random_bytes = keys_source2->get_secure_random_bytes(keys_source2->this_arg);
+               LDK::PeerManager net2 = PeerManager_new(std::move(msg_handler2), node_secret2, &random_bytes.data, logger2);
+
+               // Open a connection!
+               PeersConnection conn(cm1, cm2, net1, net2);
+
+               // Note that we have to bind the result to a C++ class to make sure it gets free'd
+               LDK::CResult_NoneAPIErrorZ res = ChannelManager_create_channel(&cm1, ChannelManager_get_our_node_id(&cm2), 40000, 1000, 42, UserConfig_default());
+               assert(res->result_ok);
+               PeerManager_process_events(&net1);
+
+               LDK::CVec_ChannelDetailsZ new_channels = ChannelManager_list_channels(&cm1);
+               assert(new_channels->datalen == 1);
+               LDKPublicKey chan_open_pk = ChannelDetails_get_remote_network_id(&new_channels->data[0]);
+               assert(!memcmp(chan_open_pk.compressed_form, ChannelManager_get_our_node_id(&cm2).compressed_form, 33));
+
+               while (true) {
+                       LDK::CVec_ChannelDetailsZ new_channels_2 = ChannelManager_list_channels(&cm2);
+                       if (new_channels_2->datalen == 1) {
+                               // Sample getting our counterparty's init features (which used to be hard to do without a memory leak):
+                               const LDK::InitFeatures init_feats = ChannelDetails_get_counterparty_features(&new_channels_2->data[0]);
+                               assert(init_feats->inner != NULL);
+                               break;
+                       }
+                       std::this_thread::yield();
+               }
 
-       while (true) {
-               // Wait for the initial handshakes to complete...
-               LDK::CVec_PublicKeyZ peers_1 = PeerManager_get_peer_node_ids(&net1);
-               LDK::CVec_PublicKeyZ peers_2 = PeerManager_get_peer_node_ids(&net2);
-               if (peers_1->datalen == 1 && peers_2->datalen ==1) { break; }
-               std::this_thread::yield();
-       }
+               LDKEventsProvider ev1 = ChannelManager_as_EventsProvider(&cm1);
+               while (true) {
+                       LDK::CVec_EventZ events = ev1.get_and_clear_pending_events(ev1.this_arg);
+                       if (events->datalen == 1) {
+                               assert(events->data[0].tag == LDKEvent_FundingGenerationReady);
+                               assert(events->data[0].funding_generation_ready.user_channel_id == 42);
+                               assert(events->data[0].funding_generation_ready.channel_value_satoshis == 40000);
+                               assert(events->data[0].funding_generation_ready.output_script.datalen == 34);
+                               assert(!memcmp(events->data[0].funding_generation_ready.output_script.data, channel_open_tx + 58, 34));
+                               LDKThirtyTwoBytes txid;
+                               for (int i = 0; i < 32; i++) { txid.data[i] = channel_open_txid[31-i]; }
+                               LDK::OutPoint outp = OutPoint_new(txid, 0);
+                               ChannelManager_funding_transaction_generated(&cm1, &events->data[0].funding_generation_ready.temporary_channel_id.data, std::move(outp));
+                               break;
+                       }
+                       std::this_thread::yield();
+               }
 
-       // Note that we have to bind the result to a C++ class to make sure it gets free'd
-       LDK::CResult_NoneAPIErrorZ res = ChannelManager_create_channel(&cm1, ChannelManager_get_our_node_id(&cm2), 40000, 1000, 42, config1);
-       assert(res->result_ok);
-       PeerManager_process_events(&net1);
+               // We observe when the funding signed messages have been exchanged by
+               // waiting for two monitors to be registered.
+               PeerManager_process_events(&net1);
+               while (true) {
+                       LDK::CVec_EventZ events = ev1.get_and_clear_pending_events(ev1.this_arg);
+                       if (events->datalen == 1) {
+                               assert(events->data[0].tag == LDKEvent_FundingBroadcastSafe);
+                               assert(events->data[0].funding_broadcast_safe.user_channel_id == 42);
+                               break;
+                       }
+                       std::this_thread::yield();
+               }
 
-       LDK::CVec_ChannelDetailsZ new_channels = ChannelManager_list_channels(&cm1);
-       assert(new_channels->datalen == 1);
-       LDKPublicKey chan_open_pk = ChannelDetails_get_remote_network_id(&new_channels->data[0]);
-       assert(!memcmp(chan_open_pk.compressed_form, ChannelManager_get_our_node_id(&cm2).compressed_form, 33));
+               LDKCVec_C2Tuple_usizeTransactionZZ txdata { .data = (LDKC2Tuple_usizeTransactionZ*)malloc(sizeof(LDKC2Tuple_usizeTransactionZ)), .datalen = 1 };
+               *txdata.data = C2Tuple_usizeTransactionZ_new(0, LDKTransaction { .data = (uint8_t*)channel_open_tx, .datalen = sizeof(channel_open_tx), .data_is_owned = false });
+               ChannelManager_block_connected(&cm1, &channel_open_header, txdata, 1);
+
+               txdata = LDKCVec_C2Tuple_usizeTransactionZZ { .data = (LDKC2Tuple_usizeTransactionZ*)malloc(sizeof(LDKC2Tuple_usizeTransactionZ)), .datalen = 1 };
+               *txdata.data = C2Tuple_usizeTransactionZ_new(0, LDKTransaction { .data = (uint8_t*)channel_open_tx, .datalen = sizeof(channel_open_tx), .data_is_owned = false });
+               ChannelManager_block_connected(&cm2, &channel_open_header, txdata, 1);
+
+               txdata = LDKCVec_C2Tuple_usizeTransactionZZ { .data = (LDKC2Tuple_usizeTransactionZ*)malloc(sizeof(LDKC2Tuple_usizeTransactionZ)), .datalen = 1 };
+               *txdata.data = C2Tuple_usizeTransactionZ_new(0, LDKTransaction { .data = (uint8_t*)channel_open_tx, .datalen = sizeof(channel_open_tx), .data_is_owned = false });
+               mons1.ConnectBlock(&channel_open_header, 1, txdata, broadcast, fee_est);
+
+               txdata = LDKCVec_C2Tuple_usizeTransactionZZ { .data = (LDKC2Tuple_usizeTransactionZ*)malloc(sizeof(LDKC2Tuple_usizeTransactionZ)), .datalen = 1 };
+               *txdata.data = C2Tuple_usizeTransactionZ_new(0, LDKTransaction { .data = (uint8_t*)channel_open_tx, .datalen = sizeof(channel_open_tx), .data_is_owned = false });
+               mons2.ConnectBlock(&channel_open_header, 1, txdata, broadcast, fee_est);
+
+               ChannelManager_block_connected(&cm1, &header_1, LDKCVec_C2Tuple_usizeTransactionZZ { .data = NULL, .datalen = 0 }, 2);
+               ChannelManager_block_connected(&cm2, &header_1, LDKCVec_C2Tuple_usizeTransactionZZ { .data = NULL, .datalen = 0 }, 2);
+               mons1.ConnectBlock(&header_1, 2, LDKCVec_C2Tuple_usizeTransactionZZ { .data = NULL, .datalen = 0 }, broadcast, fee_est);
+               mons2.ConnectBlock(&header_1, 2, LDKCVec_C2Tuple_usizeTransactionZZ { .data = NULL, .datalen = 0 }, broadcast, fee_est);
+
+               ChannelManager_block_connected(&cm1, &header_2, LDKCVec_C2Tuple_usizeTransactionZZ { .data = NULL, .datalen = 0 }, 3);
+               ChannelManager_block_connected(&cm2, &header_2, LDKCVec_C2Tuple_usizeTransactionZZ { .data = NULL, .datalen = 0 }, 3);
+               mons1.ConnectBlock(&header_2, 3, LDKCVec_C2Tuple_usizeTransactionZZ { .data = NULL, .datalen = 0 }, broadcast, fee_est);
+               mons2.ConnectBlock(&header_2, 3, LDKCVec_C2Tuple_usizeTransactionZZ { .data = NULL, .datalen = 0 }, broadcast, fee_est);
+
+               PeerManager_process_events(&net1);
+               PeerManager_process_events(&net2);
+
+               // Now send funds from 1 to 2!
+               while (true) {
+                       LDK::CVec_ChannelDetailsZ outbound_channels = ChannelManager_list_usable_channels(&cm1);
+                       if (outbound_channels->datalen == 1) {
+                               const LDKChannelDetails *channel = &outbound_channels->data[0];
+                               // Note that the channel ID is the same as the channel txid reversed as the output index is 0
+                               uint8_t expected_chan_id[32];
+                               for (int i = 0; i < 32; i++) { expected_chan_id[i] = channel_open_txid[31-i]; }
+                               assert(!memcmp(ChannelDetails_get_channel_id(channel), expected_chan_id, 32));
+                               assert(!memcmp(ChannelDetails_get_remote_network_id(channel).compressed_form,
+                                               ChannelManager_get_our_node_id(&cm2).compressed_form, 33));
+                               assert(ChannelDetails_get_channel_value_satoshis(channel) == 40000);
+                               // We opened the channel with 1000 push_msat:
+                               assert(ChannelDetails_get_outbound_capacity_msat(channel) == 40000*1000 - 1000);
+                               assert(ChannelDetails_get_inbound_capacity_msat(channel) == 1000);
+                               assert(ChannelDetails_get_is_live(channel));
+                               break;
+                       }
+                       std::this_thread::yield();
+               }
 
-       while (true) {
-               LDK::CVec_ChannelDetailsZ new_channels_2 = ChannelManager_list_channels(&cm2);
-               if (new_channels_2->datalen == 1) {
-                       // Sample getting our counterparty's init features (which used to be hard to do without a memory leak):
-                       const LDK::InitFeatures init_feats = ChannelDetails_get_counterparty_features(&new_channels_2->data[0]);
-                       assert(init_feats->inner != NULL);
-                       break;
+               LDK::CVec_ChannelDetailsZ outbound_channels = ChannelManager_list_usable_channels(&cm1);
+               LDKThirtyTwoBytes payment_secret;
+               memset(payment_secret.data, 0x42, 32);
+               {
+                       LDK::LockedNetworkGraph graph_2_locked = NetGraphMsgHandler_read_locked_graph(&net_graph2);
+                       LDK::NetworkGraph graph_2_ref = LockedNetworkGraph_graph(&graph_2_locked);
+                       LDK::CResult_RouteLightningErrorZ route = get_route(ChannelManager_get_our_node_id(&cm1), &graph_2_ref, ChannelManager_get_our_node_id(&cm2), &outbound_channels, LDKCVec_RouteHintZ {
+                                       .data = NULL, .datalen = 0
+                               }, 5000, 10, logger1);
+                       assert(route->result_ok);
+                       LDK::CResult_NonePaymentSendFailureZ send_res = ChannelManager_send_payment(&cm1, route->contents.result, payment_hash_1, payment_secret);
+                       assert(send_res->result_ok);
                }
-               std::this_thread::yield();
-       }
 
-       LDKEventsProvider ev1 = ChannelManager_as_EventsProvider(&cm1);
-       while (true) {
-               LDK::CVec_EventZ events = ev1.get_and_clear_pending_events(ev1.this_arg);
-               if (events->datalen == 1) {
-                       assert(events->data[0].tag == LDKEvent_FundingGenerationReady);
-                       assert(events->data[0].funding_generation_ready.user_channel_id == 42);
-                       assert(events->data[0].funding_generation_ready.channel_value_satoshis == 40000);
-                       assert(events->data[0].funding_generation_ready.output_script.datalen == 34);
-                       assert(!memcmp(events->data[0].funding_generation_ready.output_script.data, channel_open_tx + 58, 34));
-                       LDKThirtyTwoBytes txid;
-                       for (int i = 0; i < 32; i++) { txid.data[i] = channel_open_txid[31-i]; }
-                       LDK::OutPoint outp = OutPoint_new(txid, 0);
-                       ChannelManager_funding_transaction_generated(&cm1, &events->data[0].funding_generation_ready.temporary_channel_id.data, outp);
-                       break;
+               mons_updated = 0;
+               PeerManager_process_events(&net1);
+               while (mons_updated != 4) {
+                       std::this_thread::yield();
                }
-               std::this_thread::yield();
-       }
 
-       // We observe when the funding signed messages have been exchanged by
-       // waiting for two monitors to be registered.
-       PeerManager_process_events(&net1);
-       while (true) {
-               LDK::CVec_EventZ events = ev1.get_and_clear_pending_events(ev1.this_arg);
-               if (events->datalen == 1) {
-                       assert(events->data[0].tag == LDKEvent_FundingBroadcastSafe);
-                       assert(events->data[0].funding_broadcast_safe.user_channel_id == 42);
-                       break;
+               // Check that we received the payment!
+               LDKEventsProvider ev2 = ChannelManager_as_EventsProvider(&cm2);
+               while (true) {
+                       LDK::CVec_EventZ events = ev2.get_and_clear_pending_events(ev2.this_arg);
+                       if (events->datalen == 1) {
+                               assert(events->data[0].tag == LDKEvent_PendingHTLCsForwardable);
+                               break;
+                       }
+                       std::this_thread::yield();
+               }
+               ChannelManager_process_pending_htlc_forwards(&cm2);
+               PeerManager_process_events(&net2);
+
+               mons_updated = 0;
+               {
+                       LDK::CVec_EventZ events = ev2.get_and_clear_pending_events(ev2.this_arg);
+                       assert(events->datalen == 1);
+                       assert(events->data[0].tag == LDKEvent_PaymentReceived);
+                       assert(!memcmp(events->data[0].payment_received.payment_hash.data, payment_hash_1.data, 32));
+                       assert(!memcmp(events->data[0].payment_received.payment_secret.data, payment_secret.data, 32));
+                       assert(events->data[0].payment_received.amt == 5000);
+                       assert(ChannelManager_claim_funds(&cm2, payment_preimage_1, payment_secret, 5000));
+               }
+               PeerManager_process_events(&net2);
+               // Wait until we've passed through a full set of monitor updates (ie new preimage + CS/RAA messages)
+               while (mons_updated != 5) {
+                       std::this_thread::yield();
+               }
+               {
+                       LDK::CVec_EventZ events = ev1.get_and_clear_pending_events(ev1.this_arg);
+                       assert(events->datalen == 1);
+                       assert(events->data[0].tag == LDKEvent_PaymentSent);
+                       assert(!memcmp(events->data[0].payment_sent.payment_preimage.data, payment_preimage_1.data, 32));
                }
-               std::this_thread::yield();
-       }
 
-       LDKCVec_C2Tuple_usizeTransactionZZ txdata { .data = (LDKC2TupleTempl_usize__Transaction*)malloc(sizeof(LDKC2Tuple_usizeTransactionZ)), .datalen = 1 };
-       *txdata.data = C2Tuple_usizeTransactionZ_new(0, LDKTransaction { .data = (uint8_t*)channel_open_tx, .datalen = sizeof(channel_open_tx), .data_is_owned = false });
-       ChannelManager_block_connected(&cm1, &channel_open_header, txdata, 1);
+               conn.stop();
 
-       txdata = LDKCVec_C2Tuple_usizeTransactionZZ { .data = (LDKC2TupleTempl_usize__Transaction*)malloc(sizeof(LDKC2Tuple_usizeTransactionZ)), .datalen = 1 };
-       *txdata.data = C2Tuple_usizeTransactionZ_new(0, LDKTransaction { .data = (uint8_t*)channel_open_tx, .datalen = sizeof(channel_open_tx), .data_is_owned = false });
-       ChannelManager_block_connected(&cm2, &channel_open_header, txdata, 1);
+               cm1_ser = ChannelManager_write(&cm1);
+               cm2_ser = ChannelManager_write(&cm2);
+       }
 
-       txdata = LDKCVec_C2Tuple_usizeTransactionZZ { .data = (LDKC2TupleTempl_usize__Transaction*)malloc(sizeof(LDKC2Tuple_usizeTransactionZ)), .datalen = 1 };
-       *txdata.data = C2Tuple_usizeTransactionZ_new(0, LDKTransaction { .data = (uint8_t*)channel_open_tx, .datalen = sizeof(channel_open_tx), .data_is_owned = false });
-       mons1.ConnectBlock(&channel_open_header, 1, txdata, broadcast, fee_est);
+       LDK::CVec_ChannelMonitorZ mons_list1 = LDKCVec_ChannelMonitorZ { .data = (LDKChannelMonitor*)malloc(sizeof(LDKChannelMonitor)), .datalen = 1 };
+       assert(mons1.mons.size() == 1);
+       mons_list1->data[0] = *& std::get<1>(mons1.mons[0]); // Note that we need a reference, thus need a raw clone here, which *& does.
+       mons_list1->data[0].is_owned = false; // XXX: God this sucks
+       uint8_t node_seed[32];
+       memset(&node_seed, 0, 32);
+       LDK::KeysManager keys1 = KeysManager_new(&node_seed, 1, 0);
+       LDK::KeysInterface keys_source1 = KeysManager_as_KeysInterface(&keys1);
 
-       txdata = LDKCVec_C2Tuple_usizeTransactionZZ { .data = (LDKC2TupleTempl_usize__Transaction*)malloc(sizeof(LDKC2Tuple_usizeTransactionZ)), .datalen = 1 };
-       *txdata.data = C2Tuple_usizeTransactionZ_new(0, LDKTransaction { .data = (uint8_t*)channel_open_tx, .datalen = sizeof(channel_open_tx), .data_is_owned = false });
-       mons2.ConnectBlock(&channel_open_header, 1, txdata, broadcast, fee_est);
+       LDK::ChannelManagerReadArgs cm1_args = ChannelManagerReadArgs_new(KeysManager_as_KeysInterface(&keys1), fee_est, mon1, broadcast, logger1, UserConfig_default(), std::move(mons_list1));
+       LDK::CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ cm1_read =
+               C2Tuple_BlockHashChannelManagerZ_read(LDKu8slice { .data = cm1_ser->data, .datalen = cm1_ser -> datalen}, std::move(cm1_args));
+       assert(cm1_read->result_ok);
+       LDK::ChannelManager cm1(std::move(cm1_read->contents.result->b));
 
-       ChannelManager_block_connected(&cm1, &header_1, LDKCVec_C2Tuple_usizeTransactionZZ { .data = NULL, .datalen = 0 }, 2);
-       ChannelManager_block_connected(&cm2, &header_1, LDKCVec_C2Tuple_usizeTransactionZZ { .data = NULL, .datalen = 0 }, 2);
-       mons1.ConnectBlock(&header_1, 2, LDKCVec_C2Tuple_usizeTransactionZZ { .data = NULL, .datalen = 0 }, broadcast, fee_est);
-       mons2.ConnectBlock(&header_1, 2, LDKCVec_C2Tuple_usizeTransactionZZ { .data = NULL, .datalen = 0 }, broadcast, fee_est);
+       LDK::CVec_ChannelMonitorZ mons_list2 = LDKCVec_ChannelMonitorZ { .data = (LDKChannelMonitor*)malloc(sizeof(LDKChannelMonitor)), .datalen = 1 };
+       assert(mons2.mons.size() == 1);
+       mons_list2->data[0] = *& std::get<1>(mons2.mons[0]); // Note that we need a reference, thus need a raw clone here, which *& does.
+       mons_list2->data[0].is_owned = false; // XXX: God this sucks
+       memset(&node_seed, 1, 32);
+       LDK::KeysManager keys2 = KeysManager_new(&node_seed, 1, 0);
 
-       ChannelManager_block_connected(&cm1, &header_2, LDKCVec_C2Tuple_usizeTransactionZZ { .data = NULL, .datalen = 0 }, 3);
-       ChannelManager_block_connected(&cm2, &header_2, LDKCVec_C2Tuple_usizeTransactionZZ { .data = NULL, .datalen = 0 }, 3);
-       mons1.ConnectBlock(&header_2, 3, LDKCVec_C2Tuple_usizeTransactionZZ { .data = NULL, .datalen = 0 }, broadcast, fee_est);
-       mons2.ConnectBlock(&header_2, 3, LDKCVec_C2Tuple_usizeTransactionZZ { .data = NULL, .datalen = 0 }, broadcast, fee_est);
+       LDK::ChannelManagerReadArgs cm2_args = ChannelManagerReadArgs_new(KeysManager_as_KeysInterface(&keys2), fee_est, mon2, broadcast, logger2, UserConfig_default(), std::move(mons_list2));
+       LDK::CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ cm2_read =
+               C2Tuple_BlockHashChannelManagerZ_read(LDKu8slice { .data = cm2_ser->data, .datalen = cm2_ser -> datalen}, std::move(cm2_args));
+       assert(cm2_read->result_ok);
+       LDK::ChannelManager cm2(std::move(cm2_read->contents.result->b));
 
-       PeerManager_process_events(&net1);
-       PeerManager_process_events(&net2);
+       // Attempt to close the channel...
+       uint8_t chan_id[32];
+       for (int i = 0; i < 32; i++) { chan_id[i] = channel_open_txid[31-i]; }
+       LDK::CResult_NoneAPIErrorZ close_res = ChannelManager_close_channel(&cm1, &chan_id);
+       assert(!close_res->result_ok); // Note that we can't close while disconnected!
 
-       // Now send funds from 1 to 2!
-       while (true) {
-               LDK::CVec_ChannelDetailsZ outbound_channels = ChannelManager_list_usable_channels(&cm1);
-               if (outbound_channels->datalen == 1) {
-                       const LDKChannelDetails *channel = &outbound_channels->data[0];
-                       // Note that the channel ID is the same as the channel txid reversed as the output index is 0
-                       uint8_t expected_chan_id[32];
-                       for (int i = 0; i < 32; i++) { expected_chan_id[i] = channel_open_txid[31-i]; }
-                       assert(!memcmp(ChannelDetails_get_channel_id(channel), expected_chan_id, 32));
-                       assert(!memcmp(ChannelDetails_get_remote_network_id(channel).compressed_form,
-                                       ChannelManager_get_our_node_id(&cm2).compressed_form, 33));
-                       assert(ChannelDetails_get_channel_value_satoshis(channel) == 40000);
-                       // We opened the channel with 1000 push_msat:
-                       assert(ChannelDetails_get_outbound_capacity_msat(channel) == 40000*1000 - 1000);
-                       assert(ChannelDetails_get_inbound_capacity_msat(channel) == 1000);
-                       assert(ChannelDetails_get_is_live(channel));
-                       break;
-               }
-               std::this_thread::yield();
-       }
+       // Open a connection!
+       LDK::MessageHandler msg_handler1 = MessageHandler_new(ChannelManager_as_ChannelMessageHandler(&cm1), NetGraphMsgHandler_as_RoutingMessageHandler(&net_graph1));
+       random_bytes = keys_source1->get_secure_random_bytes(keys_source1->this_arg);
+       LDK::PeerManager net1 = PeerManager_new(std::move(msg_handler1), node_secret1, &random_bytes.data, logger1);
 
-       LDK::CVec_ChannelDetailsZ outbound_channels = ChannelManager_list_usable_channels(&cm1);
-       LDKThirtyTwoBytes payment_secret;
-       memset(payment_secret.data, 0x42, 32);
-       {
-               LDK::LockedNetworkGraph graph_2_locked = NetGraphMsgHandler_read_locked_graph(&net_graph2);
-               LDK::NetworkGraph graph_2_ref = LockedNetworkGraph_graph(&graph_2_locked);
-               LDK::CResult_RouteLightningErrorZ route = get_route(ChannelManager_get_our_node_id(&cm1), &graph_2_ref, ChannelManager_get_our_node_id(&cm2), &outbound_channels, LDKCVec_RouteHintZ {
-                               .data = NULL, .datalen = 0
-                       }, 5000, 10, logger1);
-               assert(route->result_ok);
-               LDK::CResult_NonePaymentSendFailureZ send_res = ChannelManager_send_payment(&cm1, route->contents.result, payment_hash_1, payment_secret);
-               assert(send_res->result_ok);
-       }
+       LDK::MessageHandler msg_handler2 = MessageHandler_new(ChannelManager_as_ChannelMessageHandler(&cm2), NetGraphMsgHandler_as_RoutingMessageHandler(&net_graph2));
+       random_bytes = keys_source1->get_secure_random_bytes(keys_source1->this_arg);
+       LDK::PeerManager net2 = PeerManager_new(std::move(msg_handler2), node_secret2, &random_bytes.data, logger2);
 
-       mons_updated = 0;
-       PeerManager_process_events(&net1);
-       while (mons_updated != 4) {
-               std::this_thread::yield();
-       }
+       PeersConnection conn(cm1, cm2, net1, net2);
 
-       // Check that we received the payment!
-       LDKEventsProvider ev2 = ChannelManager_as_EventsProvider(&cm2);
        while (true) {
-               LDK::CVec_EventZ events = ev2.get_and_clear_pending_events(ev2.this_arg);
-               if (events->datalen == 1) {
-                       assert(events->data[0].tag == LDKEvent_PendingHTLCsForwardable);
+               // Wait for the channels to be considered up once the reestablish messages are processed
+               LDK::CVec_ChannelDetailsZ outbound_channels = ChannelManager_list_usable_channels(&cm1);
+               if (outbound_channels->datalen == 1) {
                        break;
                }
-               std::this_thread::yield();
-       }
-       ChannelManager_process_pending_htlc_forwards(&cm2);
-       PeerManager_process_events(&net2);
-
-       mons_updated = 0;
-       {
-               LDK::CVec_EventZ events = ev2.get_and_clear_pending_events(ev2.this_arg);
-               assert(events->datalen == 1);
-               assert(events->data[0].tag == LDKEvent_PaymentReceived);
-               assert(!memcmp(events->data[0].payment_received.payment_hash.data, payment_hash_1.data, 32));
-               assert(!memcmp(events->data[0].payment_received.payment_secret.data, payment_secret.data, 32));
-               assert(events->data[0].payment_received.amt == 5000);
-               assert(ChannelManager_claim_funds(&cm2, payment_preimage_1, payment_secret, 5000));
-       }
-       PeerManager_process_events(&net2);
-       // Wait until we've passed through a full set of monitor updates (ie new preimage + CS/RAA messages)
-       while (mons_updated != 5) {
-               std::this_thread::yield();
-       }
-       {
-               LDK::CVec_EventZ events = ev1.get_and_clear_pending_events(ev1.this_arg);
-               assert(events->datalen == 1);
-               assert(events->data[0].tag == LDKEvent_PaymentSent);
-               assert(!memcmp(events->data[0].payment_sent.payment_preimage.data, payment_preimage_1.data, 32));
        }
 
-       // Close the channel.
-       uint8_t chan_id[32];
-       for (int i = 0; i < 32; i++) { chan_id[i] = channel_open_txid[31-i]; }
-       LDK::CResult_NoneAPIErrorZ close_res = ChannelManager_close_channel(&cm1, &chan_id);
+       // Actually close the channel
+       close_res = ChannelManager_close_channel(&cm1, &chan_id);
        assert(close_res->result_ok);
        PeerManager_process_events(&net1);
        num_txs_broadcasted = 0;
@@ -539,18 +627,12 @@ int main() {
        LDK::CVec_ChannelDetailsZ chans_after_close2 = ChannelManager_list_channels(&cm2);
        assert(chans_after_close2->datalen == 0);
 
-       close(pipefds_1_to_2[0]);
-       close(pipefds_2_to_1[0]);
-       close(pipefds_1_to_2[1]);
-       close(pipefds_2_to_1[1]);
-       t1.join();
-       t2.join();
+       conn.stop();
 
        // Few extra random tests:
        LDKSecretKey sk;
        memset(&sk, 42, 32);
-       LDKC2Tuple_u64u64Z kdiv_params;
-       kdiv_params.a = 42;
-       kdiv_params.b = 42;
-       LDK::InMemoryChannelKeys keys = InMemoryChannelKeys_new(sk, sk, sk, sk, sk, random_bytes, 42, kdiv_params);
+       LDKThirtyTwoBytes kdiv_params;
+       memset(&kdiv_params, 43, 32);
+       LDK::InMemorySigner signer = InMemorySigner_new(sk, sk, sk, sk, sk, random_bytes, 42, kdiv_params);
 }
index 6154802268679a02df0a1e93031d226e91d4125b..8076e251b85ed9039859d20a1df09320007a610e 100644 (file)
@@ -1,13 +1,13 @@
 /* Text to put at the beginning of the generated file. Probably a license. */
 
-/* Generated with cbindgen:0.14.4 */
+/* Generated with cbindgen:0.16.0 */
 
 /* Warning, this file is autogenerated by cbindgen. Don't modify this manually. */
 
 #include <stdarg.h>
 #include <stdbool.h>
 #include <stdint.h>
-#include <stdlib.h>
+
 
 /**
  * An error when accessing the chain via [`Access`].
@@ -174,8 +174,8 @@ typedef enum LDKSecp256k1Error {
    LDKSecp256k1Error_InvalidSecretKey,
    LDKSecp256k1Error_InvalidRecoveryId,
    LDKSecp256k1Error_InvalidTweak,
+   LDKSecp256k1Error_TweakCheckFailed,
    LDKSecp256k1Error_NotEnoughMemory,
-   LDKSecp256k1Error_CallbackPanicked,
    /**
     * Must be last for serialization purposes
     */
@@ -206,343 +206,350 @@ typedef struct LDKTransaction {
    bool data_is_owned;
 } LDKTransaction;
 
-typedef struct LDKCVecTempl_u8 {
+typedef struct LDKCVec_u8Z {
    uint8_t *data;
    uintptr_t datalen;
-} LDKCVecTempl_u8;
-
-typedef LDKCVecTempl_u8 LDKCVec_u8Z;
+} LDKCVec_u8Z;
 
 /**
  * A transaction output including a scriptPubKey and value.
  * This type *does* own its own memory, so must be free'd appropriately.
  */
 typedef struct LDKTxOut {
-   LDKCVec_u8Z script_pubkey;
+   struct LDKCVec_u8Z script_pubkey;
    uint64_t value;
 } LDKTxOut;
 
-typedef struct LDKC2TupleTempl_usize__Transaction {
-   uintptr_t a;
-   LDKTransaction b;
-} LDKC2TupleTempl_usize__Transaction;
-
-typedef LDKC2TupleTempl_usize__Transaction LDKC2Tuple_usizeTransactionZ;
+typedef struct LDKSecretKey {
+   uint8_t bytes[32];
+} LDKSecretKey;
 
-typedef union LDKCResultPtr_u8__ChannelMonitorUpdateErr {
-   uint8_t *result;
-   LDKChannelMonitorUpdateErr *err;
-} LDKCResultPtr_u8__ChannelMonitorUpdateErr;
+typedef union LDKCResult_SecretKeyErrorZPtr {
+   struct LDKSecretKey *result;
+   enum LDKSecp256k1Error *err;
+} LDKCResult_SecretKeyErrorZPtr;
 
-typedef struct LDKCResultTempl_u8__ChannelMonitorUpdateErr {
-   LDKCResultPtr_u8__ChannelMonitorUpdateErr contents;
+typedef struct LDKCResult_SecretKeyErrorZ {
+   union LDKCResult_SecretKeyErrorZPtr contents;
    bool result_ok;
-} LDKCResultTempl_u8__ChannelMonitorUpdateErr;
+} LDKCResult_SecretKeyErrorZ;
+
+typedef struct LDKPublicKey {
+   uint8_t compressed_form[33];
+} LDKPublicKey;
+
+typedef union LDKCResult_PublicKeyErrorZPtr {
+   struct LDKPublicKey *result;
+   enum LDKSecp256k1Error *err;
+} LDKCResult_PublicKeyErrorZPtr;
 
-typedef LDKCResultTempl_u8__ChannelMonitorUpdateErr LDKCResult_NoneChannelMonitorUpdateErrZ;
+typedef struct LDKCResult_PublicKeyErrorZ {
+   union LDKCResult_PublicKeyErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_PublicKeyErrorZ;
 
 
 
 /**
- * General Err type for ChannelMonitor actions. Generally, this implies that the data provided is
- * inconsistent with the ChannelMonitor being called. eg for ChannelMonitor::update_monitor this
- * means you tried to update a monitor for a different channel or the ChannelMonitorUpdate was
- * corrupted.
- * Contains a developer-readable error message.
+ * The set of public keys which are used in the creation of one commitment transaction.
+ * These are derived from the channel base keys and per-commitment data.
+ *
+ * A broadcaster key is provided from potential broadcaster of the computed transaction.
+ * A countersignatory key is coming from a protocol participant unable to broadcast the
+ * transaction.
+ *
+ * These keys are assumed to be good, either because the code derived them from
+ * channel basepoints via the new function, or they were obtained via
+ * CommitmentTransaction.trust().keys() because we trusted the source of the
+ * pre-calculated keys.
  */
-typedef struct MUST_USE_STRUCT LDKMonitorUpdateError {
+typedef struct MUST_USE_STRUCT LDKTxCreationKeys {
    /**
     * Nearly everywhere, inner must be non-null, however in places where
     * the Rust equivalent takes an Option, it may be set to null to indicate None.
     */
-   LDKnativeMonitorUpdateError *inner;
+   LDKnativeTxCreationKeys *inner;
    bool is_owned;
-} LDKMonitorUpdateError;
-
-typedef union LDKCResultPtr_u8__MonitorUpdateError {
-   uint8_t *result;
-   LDKMonitorUpdateError *err;
-} LDKCResultPtr_u8__MonitorUpdateError;
-
-typedef struct LDKCResultTempl_u8__MonitorUpdateError {
-   LDKCResultPtr_u8__MonitorUpdateError contents;
-   bool result_ok;
-} LDKCResultTempl_u8__MonitorUpdateError;
-
-typedef LDKCResultTempl_u8__MonitorUpdateError LDKCResult_NoneMonitorUpdateErrorZ;
+} LDKTxCreationKeys;
 
 
 
 /**
- * A reference to a transaction output.
- *
- * Differs from bitcoin::blockdata::transaction::OutPoint as the index is a u16 instead of u32
- * due to LN's restrictions on index values. Should reduce (possibly) unsafe conversions this way.
+ * An error in decoding a message or struct.
  */
-typedef struct MUST_USE_STRUCT LDKOutPoint {
+typedef struct MUST_USE_STRUCT LDKDecodeError {
    /**
     * Nearly everywhere, inner must be non-null, however in places where
     * the Rust equivalent takes an Option, it may be set to null to indicate None.
     */
-   LDKnativeOutPoint *inner;
+   LDKnativeDecodeError *inner;
    bool is_owned;
-} LDKOutPoint;
+} LDKDecodeError;
 
-typedef struct LDKC2TupleTempl_OutPoint__CVec_u8Z {
-   LDKOutPoint a;
-   LDKCVec_u8Z b;
-} LDKC2TupleTempl_OutPoint__CVec_u8Z;
+typedef union LDKCResult_TxCreationKeysDecodeErrorZPtr {
+   struct LDKTxCreationKeys *result;
+   struct LDKDecodeError *err;
+} LDKCResult_TxCreationKeysDecodeErrorZPtr;
 
-typedef LDKC2TupleTempl_OutPoint__CVec_u8Z LDKC2Tuple_OutPointScriptZ;
+typedef struct LDKCResult_TxCreationKeysDecodeErrorZ {
+   union LDKCResult_TxCreationKeysDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_TxCreationKeysDecodeErrorZ;
 
-typedef struct LDKC2TupleTempl_u32__TxOut {
-   uint32_t a;
-   LDKTxOut b;
-} LDKC2TupleTempl_u32__TxOut;
 
-typedef LDKC2TupleTempl_u32__TxOut LDKC2Tuple_u32TxOutZ;
 
 /**
- * Arbitrary 32 bytes, which could represent one of a few different things. You probably want to
- * look up the corresponding function in rust-lightning's docs.
+ * One counterparty's public keys which do not change over the life of a channel.
  */
-typedef struct LDKThirtyTwoBytes {
-   uint8_t data[32];
-} LDKThirtyTwoBytes;
-
-typedef struct LDKCVecTempl_C2TupleTempl_u32__TxOut {
-   LDKC2TupleTempl_u32__TxOut *data;
-   uintptr_t datalen;
-} LDKCVecTempl_C2TupleTempl_u32__TxOut;
-
-typedef struct LDKC2TupleTempl_ThirtyTwoBytes__CVecTempl_C2TupleTempl_u32__TxOut {
-   LDKThirtyTwoBytes a;
-   LDKCVecTempl_C2TupleTempl_u32__TxOut b;
-} LDKC2TupleTempl_ThirtyTwoBytes__CVecTempl_C2TupleTempl_u32__TxOut;
-
-typedef LDKC2TupleTempl_ThirtyTwoBytes__CVecTempl_C2TupleTempl_u32__TxOut LDKC2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ;
-
-typedef LDKCVecTempl_C2TupleTempl_u32__TxOut LDKCVec_C2Tuple_u32TxOutZZ;
+typedef struct MUST_USE_STRUCT LDKChannelPublicKeys {
+   /**
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
+    */
+   LDKnativeChannelPublicKeys *inner;
+   bool is_owned;
+} LDKChannelPublicKeys;
 
-typedef struct LDKC2TupleTempl_u64__u64 {
-   uint64_t a;
-   uint64_t b;
-} LDKC2TupleTempl_u64__u64;
+typedef union LDKCResult_ChannelPublicKeysDecodeErrorZPtr {
+   struct LDKChannelPublicKeys *result;
+   struct LDKDecodeError *err;
+} LDKCResult_ChannelPublicKeysDecodeErrorZPtr;
 
-typedef LDKC2TupleTempl_u64__u64 LDKC2Tuple_u64u64Z;
+typedef struct LDKCResult_ChannelPublicKeysDecodeErrorZ {
+   union LDKCResult_ChannelPublicKeysDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_ChannelPublicKeysDecodeErrorZ;
 
-typedef struct LDKSignature {
-   uint8_t compact_form[64];
-} LDKSignature;
+typedef union LDKCResult_TxCreationKeysErrorZPtr {
+   struct LDKTxCreationKeys *result;
+   enum LDKSecp256k1Error *err;
+} LDKCResult_TxCreationKeysErrorZPtr;
 
-typedef struct LDKCVecTempl_Signature {
-   LDKSignature *data;
-   uintptr_t datalen;
-} LDKCVecTempl_Signature;
+typedef struct LDKCResult_TxCreationKeysErrorZ {
+   union LDKCResult_TxCreationKeysErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_TxCreationKeysErrorZ;
 
-typedef struct LDKC2TupleTempl_Signature__CVecTempl_Signature {
-   LDKSignature a;
-   LDKCVecTempl_Signature b;
-} LDKC2TupleTempl_Signature__CVecTempl_Signature;
 
-typedef LDKC2TupleTempl_Signature__CVecTempl_Signature LDKC2Tuple_SignatureCVec_SignatureZZ;
 
-typedef LDKCVecTempl_Signature LDKCVec_SignatureZ;
+/**
+ * Information about an HTLC as it appears in a commitment transaction
+ */
+typedef struct MUST_USE_STRUCT LDKHTLCOutputInCommitment {
+   /**
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
+    */
+   LDKnativeHTLCOutputInCommitment *inner;
+   bool is_owned;
+} LDKHTLCOutputInCommitment;
 
-typedef union LDKCResultPtr_C2TupleTempl_Signature__CVecTempl_Signature________u8 {
-   LDKC2TupleTempl_Signature__CVecTempl_Signature *result;
-   uint8_t *err;
-} LDKCResultPtr_C2TupleTempl_Signature__CVecTempl_Signature________u8;
+typedef union LDKCResult_HTLCOutputInCommitmentDecodeErrorZPtr {
+   struct LDKHTLCOutputInCommitment *result;
+   struct LDKDecodeError *err;
+} LDKCResult_HTLCOutputInCommitmentDecodeErrorZPtr;
 
-typedef struct LDKCResultTempl_C2TupleTempl_Signature__CVecTempl_Signature________u8 {
-   LDKCResultPtr_C2TupleTempl_Signature__CVecTempl_Signature________u8 contents;
+typedef struct LDKCResult_HTLCOutputInCommitmentDecodeErrorZ {
+   union LDKCResult_HTLCOutputInCommitmentDecodeErrorZPtr contents;
    bool result_ok;
-} LDKCResultTempl_C2TupleTempl_Signature__CVecTempl_Signature________u8;
+} LDKCResult_HTLCOutputInCommitmentDecodeErrorZ;
 
-typedef LDKCResultTempl_C2TupleTempl_Signature__CVecTempl_Signature________u8 LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ;
 
-typedef union LDKCResultPtr_Signature__u8 {
-   LDKSignature *result;
-   uint8_t *err;
-} LDKCResultPtr_Signature__u8;
-
-typedef struct LDKCResultTempl_Signature__u8 {
-   LDKCResultPtr_Signature__u8 contents;
-   bool result_ok;
-} LDKCResultTempl_Signature__u8;
 
-typedef LDKCResultTempl_Signature__u8 LDKCResult_SignatureNoneZ;
+/**
+ * Late-bound per-channel counterparty data used to build transactions.
+ */
+typedef struct MUST_USE_STRUCT LDKCounterpartyChannelTransactionParameters {
+   /**
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
+    */
+   LDKnativeCounterpartyChannelTransactionParameters *inner;
+   bool is_owned;
+} LDKCounterpartyChannelTransactionParameters;
 
-typedef union LDKCResultPtr_CVecTempl_Signature_____u8 {
-   LDKCVecTempl_Signature *result;
-   uint8_t *err;
-} LDKCResultPtr_CVecTempl_Signature_____u8;
+typedef union LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZPtr {
+   struct LDKCounterpartyChannelTransactionParameters *result;
+   struct LDKDecodeError *err;
+} LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZPtr;
 
-typedef struct LDKCResultTempl_CVecTempl_Signature_____u8 {
-   LDKCResultPtr_CVecTempl_Signature_____u8 contents;
+typedef struct LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZ {
+   union LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZPtr contents;
    bool result_ok;
-} LDKCResultTempl_CVecTempl_Signature_____u8;
+} LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZ;
 
-typedef LDKCResultTempl_CVecTempl_Signature_____u8 LDKCResult_CVec_SignatureZNoneZ;
 
-/**
- * A Rust str object, ie a reference to a UTF8-valid string.
- * This is *not* null-terminated so cannot be used directly as a C string!
- */
-typedef struct LDKStr {
-   const uint8_t *chars;
-   uintptr_t len;
-} LDKStr;
 
 /**
- * Indicates an error on the client's part (usually some variant of attempting to use too-low or
- * too-high values)
+ * Per-channel data used to build transactions in conjunction with the per-commitment data (CommitmentTransaction).
+ * The fields are organized by holder/counterparty.
+ *
+ * Normally, this is converted to the broadcaster/countersignatory-organized DirectedChannelTransactionParameters
+ * before use, via the as_holder_broadcastable and as_counterparty_broadcastable functions.
  */
-typedef enum LDKAPIError_Tag {
-   /**
-    * Indicates the API was wholly misused (see err for more). Cases where these can be returned
-    * are documented, but generally indicates some precondition of a function was violated.
-    */
-   LDKAPIError_APIMisuseError,
-   /**
-    * Due to a high feerate, we were unable to complete the request.
-    * For example, this may be returned if the feerate implies we cannot open a channel at the
-    * requested value, but opening a larger channel would succeed.
-    */
-   LDKAPIError_FeeRateTooHigh,
-   /**
-    * A malformed Route was provided (eg overflowed value, node id mismatch, overly-looped route,
-    * too-many-hops, etc).
-    */
-   LDKAPIError_RouteError,
-   /**
-    * We were unable to complete the request as the Channel required to do so is unable to
-    * complete the request (or was not found). This can take many forms, including disconnected
-    * peer, channel at capacity, channel shutting down, etc.
-    */
-   LDKAPIError_ChannelUnavailable,
-   /**
-    * An attempt to call watch/update_channel returned an Err (ie you did this!), causing the
-    * attempted action to fail.
-    */
-   LDKAPIError_MonitorUpdateFailed,
+typedef struct MUST_USE_STRUCT LDKChannelTransactionParameters {
    /**
-    * Must be last for serialization purposes
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
     */
-   LDKAPIError_Sentinel,
-} LDKAPIError_Tag;
+   LDKnativeChannelTransactionParameters *inner;
+   bool is_owned;
+} LDKChannelTransactionParameters;
 
-typedef struct LDKAPIError_LDKAPIMisuseError_Body {
-   LDKCVec_u8Z err;
-} LDKAPIError_LDKAPIMisuseError_Body;
+typedef union LDKCResult_ChannelTransactionParametersDecodeErrorZPtr {
+   struct LDKChannelTransactionParameters *result;
+   struct LDKDecodeError *err;
+} LDKCResult_ChannelTransactionParametersDecodeErrorZPtr;
 
-typedef struct LDKAPIError_LDKFeeRateTooHigh_Body {
-   LDKCVec_u8Z err;
-   uint32_t feerate;
-} LDKAPIError_LDKFeeRateTooHigh_Body;
+typedef struct LDKCResult_ChannelTransactionParametersDecodeErrorZ {
+   union LDKCResult_ChannelTransactionParametersDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_ChannelTransactionParametersDecodeErrorZ;
 
-typedef struct LDKAPIError_LDKRouteError_Body {
-   LDKStr err;
-} LDKAPIError_LDKRouteError_Body;
+typedef struct LDKSignature {
+   uint8_t compact_form[64];
+} LDKSignature;
 
-typedef struct LDKAPIError_LDKChannelUnavailable_Body {
-   LDKCVec_u8Z err;
-} LDKAPIError_LDKChannelUnavailable_Body;
+typedef struct LDKCVec_SignatureZ {
+   struct LDKSignature *data;
+   uintptr_t datalen;
+} LDKCVec_SignatureZ;
 
-typedef struct LDKAPIError {
-   LDKAPIError_Tag tag;
-   union {
-      LDKAPIError_LDKAPIMisuseError_Body api_misuse_error;
-      LDKAPIError_LDKFeeRateTooHigh_Body fee_rate_too_high;
-      LDKAPIError_LDKRouteError_Body route_error;
-      LDKAPIError_LDKChannelUnavailable_Body channel_unavailable;
-   };
-} LDKAPIError;
 
-typedef union LDKCResultPtr_u8__APIError {
-   uint8_t *result;
-   LDKAPIError *err;
-} LDKCResultPtr_u8__APIError;
 
-typedef struct LDKCResultTempl_u8__APIError {
-   LDKCResultPtr_u8__APIError contents;
-   bool result_ok;
-} LDKCResultTempl_u8__APIError;
+/**
+ * Information needed to build and sign a holder's commitment transaction.
+ *
+ * The transaction is only signed once we are ready to broadcast.
+ */
+typedef struct MUST_USE_STRUCT LDKHolderCommitmentTransaction {
+   /**
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
+    */
+   LDKnativeHolderCommitmentTransaction *inner;
+   bool is_owned;
+} LDKHolderCommitmentTransaction;
 
-typedef LDKCResultTempl_u8__APIError LDKCResult_NoneAPIErrorZ;
+typedef union LDKCResult_HolderCommitmentTransactionDecodeErrorZPtr {
+   struct LDKHolderCommitmentTransaction *result;
+   struct LDKDecodeError *err;
+} LDKCResult_HolderCommitmentTransactionDecodeErrorZPtr;
+
+typedef struct LDKCResult_HolderCommitmentTransactionDecodeErrorZ {
+   union LDKCResult_HolderCommitmentTransactionDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_HolderCommitmentTransactionDecodeErrorZ;
 
 
 
 /**
- * If a payment fails to send, it can be in one of several states. This enum is returned as the
- * Err() type describing which state the payment is in, see the description of individual enum
- * states for more.
+ * A pre-built Bitcoin commitment transaction and its txid.
  */
-typedef struct MUST_USE_STRUCT LDKPaymentSendFailure {
+typedef struct MUST_USE_STRUCT LDKBuiltCommitmentTransaction {
    /**
     * Nearly everywhere, inner must be non-null, however in places where
     * the Rust equivalent takes an Option, it may be set to null to indicate None.
     */
-   LDKnativePaymentSendFailure *inner;
+   LDKnativeBuiltCommitmentTransaction *inner;
    bool is_owned;
-} LDKPaymentSendFailure;
+} LDKBuiltCommitmentTransaction;
 
-typedef union LDKCResultPtr_u8__PaymentSendFailure {
-   uint8_t *result;
-   LDKPaymentSendFailure *err;
-} LDKCResultPtr_u8__PaymentSendFailure;
+typedef union LDKCResult_BuiltCommitmentTransactionDecodeErrorZPtr {
+   struct LDKBuiltCommitmentTransaction *result;
+   struct LDKDecodeError *err;
+} LDKCResult_BuiltCommitmentTransactionDecodeErrorZPtr;
 
-typedef struct LDKCResultTempl_u8__PaymentSendFailure {
-   LDKCResultPtr_u8__PaymentSendFailure contents;
+typedef struct LDKCResult_BuiltCommitmentTransactionDecodeErrorZ {
+   union LDKCResult_BuiltCommitmentTransactionDecodeErrorZPtr contents;
    bool result_ok;
-} LDKCResultTempl_u8__PaymentSendFailure;
-
-typedef LDKCResultTempl_u8__PaymentSendFailure LDKCResult_NonePaymentSendFailureZ;
+} LDKCResult_BuiltCommitmentTransactionDecodeErrorZ;
 
 
 
 /**
- * A channel_announcement message to be sent or received from a peer
+ * This class tracks the per-transaction information needed to build a commitment transaction and to
+ * actually build it and sign.  It is used for holder transactions that we sign only when needed
+ * and for transactions we sign for the counterparty.
+ *
+ * This class can be used inside a signer implementation to generate a signature given the relevant
+ * secret key.
  */
-typedef struct MUST_USE_STRUCT LDKChannelAnnouncement {
+typedef struct MUST_USE_STRUCT LDKCommitmentTransaction {
    /**
     * Nearly everywhere, inner must be non-null, however in places where
     * the Rust equivalent takes an Option, it may be set to null to indicate None.
     */
-   LDKnativeChannelAnnouncement *inner;
+   LDKnativeCommitmentTransaction *inner;
    bool is_owned;
-} LDKChannelAnnouncement;
+} LDKCommitmentTransaction;
+
+typedef union LDKCResult_CommitmentTransactionDecodeErrorZPtr {
+   struct LDKCommitmentTransaction *result;
+   struct LDKDecodeError *err;
+} LDKCResult_CommitmentTransactionDecodeErrorZPtr;
+
+typedef struct LDKCResult_CommitmentTransactionDecodeErrorZ {
+   union LDKCResult_CommitmentTransactionDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_CommitmentTransactionDecodeErrorZ;
 
 
 
 /**
- * A channel_update message to be sent or received from a peer
+ * A wrapper on CommitmentTransaction indicating that the derived fields (the built bitcoin
+ * transaction and the transaction creation keys) are trusted.
+ *
+ * See trust() and verify() functions on CommitmentTransaction.
+ *
+ * This structure implements Deref.
  */
-typedef struct MUST_USE_STRUCT LDKChannelUpdate {
+typedef struct MUST_USE_STRUCT LDKTrustedCommitmentTransaction {
    /**
     * Nearly everywhere, inner must be non-null, however in places where
     * the Rust equivalent takes an Option, it may be set to null to indicate None.
     */
-   LDKnativeChannelUpdate *inner;
+   LDKnativeTrustedCommitmentTransaction *inner;
    bool is_owned;
-} LDKChannelUpdate;
+} LDKTrustedCommitmentTransaction;
+
+typedef union LDKCResult_TrustedCommitmentTransactionNoneZPtr {
+   struct LDKTrustedCommitmentTransaction *result;
+   /**
+    * Note that this value is always NULL, as there are no contents in the Err variant
+    */
+   void *err;
+} LDKCResult_TrustedCommitmentTransactionNoneZPtr;
+
+typedef struct LDKCResult_TrustedCommitmentTransactionNoneZ {
+   union LDKCResult_TrustedCommitmentTransactionNoneZPtr contents;
+   bool result_ok;
+} LDKCResult_TrustedCommitmentTransactionNoneZ;
+
+typedef union LDKCResult_CVec_SignatureZNoneZPtr {
+   struct LDKCVec_SignatureZ *result;
+   /**
+    * Note that this value is always NULL, as there are no contents in the Err variant
+    */
+   void *err;
+} LDKCResult_CVec_SignatureZNoneZPtr;
 
-typedef struct LDKC3TupleTempl_ChannelAnnouncement__ChannelUpdate__ChannelUpdate {
-   LDKChannelAnnouncement a;
-   LDKChannelUpdate b;
-   LDKChannelUpdate c;
-} LDKC3TupleTempl_ChannelAnnouncement__ChannelUpdate__ChannelUpdate;
+typedef struct LDKCResult_CVec_SignatureZNoneZ {
+   union LDKCResult_CVec_SignatureZNoneZPtr contents;
+   bool result_ok;
+} LDKCResult_CVec_SignatureZNoneZ;
 
-typedef LDKC3TupleTempl_ChannelAnnouncement__ChannelUpdate__ChannelUpdate LDKC3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ;
+typedef struct LDKCVec_PublicKeyZ {
+   struct LDKPublicKey *data;
+   uintptr_t datalen;
+} LDKCVec_PublicKeyZ;
 
 
 
 /**
  * Error for PeerManager errors. If you get one of these, you must disconnect the socket and
- * generate no further read_event/write_buffer_space_avail calls for the descriptor, only
- * triggering a single socket_disconnected call (unless it was provided in response to a
- * new_*_connection event, in which case no such socket_disconnected() must be called and the
- * socket silently disconencted).
+ * generate no further read_event/write_buffer_space_avail/socket_disconnected calls for the
+ * descriptor.
  */
 typedef struct MUST_USE_STRUCT LDKPeerHandleError {
    /**
@@ -553,282 +560,230 @@ typedef struct MUST_USE_STRUCT LDKPeerHandleError {
    bool is_owned;
 } LDKPeerHandleError;
 
-typedef union LDKCResultPtr_u8__PeerHandleError {
-   uint8_t *result;
-   LDKPeerHandleError *err;
-} LDKCResultPtr_u8__PeerHandleError;
+typedef union LDKCResult_CVec_u8ZPeerHandleErrorZPtr {
+   struct LDKCVec_u8Z *result;
+   struct LDKPeerHandleError *err;
+} LDKCResult_CVec_u8ZPeerHandleErrorZPtr;
+
+typedef struct LDKCResult_CVec_u8ZPeerHandleErrorZ {
+   union LDKCResult_CVec_u8ZPeerHandleErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_CVec_u8ZPeerHandleErrorZ;
+
+typedef union LDKCResult_NonePeerHandleErrorZPtr {
+   /**
+    * Note that this value is always NULL, as there are no contents in the OK variant
+    */
+   void *result;
+   struct LDKPeerHandleError *err;
+} LDKCResult_NonePeerHandleErrorZPtr;
 
-typedef struct LDKCResultTempl_u8__PeerHandleError {
-   LDKCResultPtr_u8__PeerHandleError contents;
+typedef struct LDKCResult_NonePeerHandleErrorZ {
+   union LDKCResult_NonePeerHandleErrorZPtr contents;
    bool result_ok;
-} LDKCResultTempl_u8__PeerHandleError;
+} LDKCResult_NonePeerHandleErrorZ;
+
+typedef union LDKCResult_boolPeerHandleErrorZPtr {
+   bool *result;
+   struct LDKPeerHandleError *err;
+} LDKCResult_boolPeerHandleErrorZPtr;
 
-typedef LDKCResultTempl_u8__PeerHandleError LDKCResult_NonePeerHandleErrorZ;
+typedef struct LDKCResult_boolPeerHandleErrorZ {
+   union LDKCResult_boolPeerHandleErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_boolPeerHandleErrorZ;
 
 
 
 /**
- * Information about an HTLC as it appears in a commitment transaction
+ * Features used within an `init` message.
  */
-typedef struct MUST_USE_STRUCT LDKHTLCOutputInCommitment {
+typedef struct MUST_USE_STRUCT LDKInitFeatures {
    /**
     * Nearly everywhere, inner must be non-null, however in places where
     * the Rust equivalent takes an Option, it may be set to null to indicate None.
     */
-   LDKnativeHTLCOutputInCommitment *inner;
+   LDKnativeInitFeatures *inner;
    bool is_owned;
-} LDKHTLCOutputInCommitment;
+} LDKInitFeatures;
 
-typedef struct LDKC2TupleTempl_HTLCOutputInCommitment__Signature {
-   LDKHTLCOutputInCommitment a;
-   LDKSignature b;
-} LDKC2TupleTempl_HTLCOutputInCommitment__Signature;
+typedef union LDKCResult_InitFeaturesDecodeErrorZPtr {
+   struct LDKInitFeatures *result;
+   struct LDKDecodeError *err;
+} LDKCResult_InitFeaturesDecodeErrorZPtr;
 
-typedef LDKC2TupleTempl_HTLCOutputInCommitment__Signature LDKC2Tuple_HTLCOutputInCommitmentSignatureZ;
+typedef struct LDKCResult_InitFeaturesDecodeErrorZ {
+   union LDKCResult_InitFeaturesDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_InitFeaturesDecodeErrorZ;
 
 
 
 /**
- * An Err type for failure to process messages.
+ * Features used within a `node_announcement` message.
  */
-typedef struct MUST_USE_STRUCT LDKLightningError {
+typedef struct MUST_USE_STRUCT LDKNodeFeatures {
    /**
     * Nearly everywhere, inner must be non-null, however in places where
     * the Rust equivalent takes an Option, it may be set to null to indicate None.
     */
-   LDKnativeLightningError *inner;
+   LDKnativeNodeFeatures *inner;
    bool is_owned;
-} LDKLightningError;
+} LDKNodeFeatures;
 
-typedef union LDKCResultPtr_u8__LightningError {
-   uint8_t *result;
-   LDKLightningError *err;
-} LDKCResultPtr_u8__LightningError;
+typedef union LDKCResult_NodeFeaturesDecodeErrorZPtr {
+   struct LDKNodeFeatures *result;
+   struct LDKDecodeError *err;
+} LDKCResult_NodeFeaturesDecodeErrorZPtr;
 
-typedef struct LDKCResultTempl_u8__LightningError {
-   LDKCResultPtr_u8__LightningError contents;
+typedef struct LDKCResult_NodeFeaturesDecodeErrorZ {
+   union LDKCResult_NodeFeaturesDecodeErrorZPtr contents;
    bool result_ok;
-} LDKCResultTempl_u8__LightningError;
+} LDKCResult_NodeFeaturesDecodeErrorZ;
 
-typedef LDKCResultTempl_u8__LightningError LDKCResult_NoneLightningErrorZ;
 
-typedef struct LDKPublicKey {
-   uint8_t compressed_form[33];
-} LDKPublicKey;
 
 /**
- * When on-chain outputs are created by rust-lightning (which our counterparty is not able to
- * claim at any point in the future) an event is generated which you must track and be able to
- * spend on-chain. The information needed to do this is provided in this enum, including the
- * outpoint describing which txid and output index is available, the full output which exists at
- * that txid/index, and any keys or other information required to sign.
+ * Features used within a `channel_announcement` message.
  */
-typedef enum LDKSpendableOutputDescriptor_Tag {
+typedef struct MUST_USE_STRUCT LDKChannelFeatures {
    /**
-    * An output to a script which was provided via KeysInterface, thus you should already know
-    * how to spend it. No keys are provided as rust-lightning was never given any keys - only the
-    * script_pubkey as it appears in the output.
-    * These may include outputs from a transaction punishing our counterparty or claiming an HTLC
-    * on-chain using the payment preimage or after it has timed out.
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
     */
-   LDKSpendableOutputDescriptor_StaticOutput,
-   /**
-    * An output to a P2WSH script which can be spent with a single signature after a CSV delay.
-    *
-    * The witness in the spending input should be:
-    * <BIP 143 signature> <empty vector> (MINIMALIF standard rule) <provided witnessScript>
-    *
-    * Note that the nSequence field in the spending input must be set to to_self_delay
-    * (which means the transaction is not broadcastable until at least to_self_delay
-    * blocks after the outpoint confirms).
-    *
-    * These are generally the result of a \"revocable\" output to us, spendable only by us unless
-    * it is an output from an old state which we broadcast (which should never happen).
-    *
-    * To derive the delayed_payment key which is used to sign for this input, you must pass the
-    * holder delayed_payment_base_key (ie the private key which corresponds to the pubkey in
-    * ChannelKeys::pubkeys().delayed_payment_basepoint) and the provided per_commitment_point to
-    * chan_utils::derive_private_key. The public key can be generated without the secret key
-    * using chan_utils::derive_public_key and only the delayed_payment_basepoint which appears in
-    * ChannelKeys::pubkeys().
-    *
-    * To derive the revocation_pubkey provided here (which is used in the witness
-    * script generation), you must pass the counterparty revocation_basepoint (which appears in the
-    * call to ChannelKeys::on_accept) and the provided per_commitment point
-    * to chan_utils::derive_public_revocation_key.
-    *
-    * The witness script which is hashed and included in the output script_pubkey may be
-    * regenerated by passing the revocation_pubkey (derived as above), our delayed_payment pubkey
-    * (derived as above), and the to_self_delay contained here to
-    * chan_utils::get_revokeable_redeemscript.
-    */
-   LDKSpendableOutputDescriptor_DynamicOutputP2WSH,
-   /**
-    * An output to a P2WPKH, spendable exclusively by our payment key (ie the private key which
-    * corresponds to the public key in ChannelKeys::pubkeys().payment_point).
-    * The witness in the spending input, is, thus, simply:
-    * <BIP 143 signature> <payment key>
-    *
-    * These are generally the result of our counterparty having broadcast the current state,
-    * allowing us to claim the non-HTLC-encumbered outputs immediately.
-    */
-   LDKSpendableOutputDescriptor_StaticOutputCounterpartyPayment,
-   /**
-    * Must be last for serialization purposes
-    */
-   LDKSpendableOutputDescriptor_Sentinel,
-} LDKSpendableOutputDescriptor_Tag;
+   LDKnativeChannelFeatures *inner;
+   bool is_owned;
+} LDKChannelFeatures;
 
-typedef struct LDKSpendableOutputDescriptor_LDKStaticOutput_Body {
-   LDKOutPoint outpoint;
-   LDKTxOut output;
-} LDKSpendableOutputDescriptor_LDKStaticOutput_Body;
+typedef union LDKCResult_ChannelFeaturesDecodeErrorZPtr {
+   struct LDKChannelFeatures *result;
+   struct LDKDecodeError *err;
+} LDKCResult_ChannelFeaturesDecodeErrorZPtr;
 
-typedef struct LDKSpendableOutputDescriptor_LDKDynamicOutputP2WSH_Body {
-   LDKOutPoint outpoint;
-   LDKPublicKey per_commitment_point;
-   uint16_t to_self_delay;
-   LDKTxOut output;
-   LDKC2Tuple_u64u64Z key_derivation_params;
-   LDKPublicKey revocation_pubkey;
-} LDKSpendableOutputDescriptor_LDKDynamicOutputP2WSH_Body;
-
-typedef struct LDKSpendableOutputDescriptor_LDKStaticOutputCounterpartyPayment_Body {
-   LDKOutPoint outpoint;
-   LDKTxOut output;
-   LDKC2Tuple_u64u64Z key_derivation_params;
-} LDKSpendableOutputDescriptor_LDKStaticOutputCounterpartyPayment_Body;
-
-typedef struct LDKSpendableOutputDescriptor {
-   LDKSpendableOutputDescriptor_Tag tag;
-   union {
-      LDKSpendableOutputDescriptor_LDKStaticOutput_Body static_output;
-      LDKSpendableOutputDescriptor_LDKDynamicOutputP2WSH_Body dynamic_output_p2wsh;
-      LDKSpendableOutputDescriptor_LDKStaticOutputCounterpartyPayment_Body static_output_counterparty_payment;
-   };
-} LDKSpendableOutputDescriptor;
+typedef struct LDKCResult_ChannelFeaturesDecodeErrorZ {
+   union LDKCResult_ChannelFeaturesDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_ChannelFeaturesDecodeErrorZ;
 
-typedef struct LDKCVecTempl_SpendableOutputDescriptor {
-   LDKSpendableOutputDescriptor *data;
-   uintptr_t datalen;
-} LDKCVecTempl_SpendableOutputDescriptor;
 
-typedef LDKCVecTempl_SpendableOutputDescriptor LDKCVec_SpendableOutputDescriptorZ;
 
 /**
- * An Event which you should probably take some action in response to.
- *
- * Note that while Writeable and Readable are implemented for Event, you probably shouldn't use
- * them directly as they don't round-trip exactly (for example FundingGenerationReady is never
- * written as it makes no sense to respond to it after reconnecting to peers).
+ * Options which apply on a per-channel basis and may change at runtime or based on negotiation
+ * with our counterparty.
  */
-typedef enum LDKEvent_Tag {
-   /**
-    * Used to indicate that the client should generate a funding transaction with the given
-    * parameters and then call ChannelManager::funding_transaction_generated.
-    * Generated in ChannelManager message handling.
-    * Note that *all inputs* in the funding transaction must spend SegWit outputs or your
-    * counterparty can steal your funds!
-    */
-   LDKEvent_FundingGenerationReady,
-   /**
-    * Used to indicate that the client may now broadcast the funding transaction it created for a
-    * channel. Broadcasting such a transaction prior to this event may lead to our counterparty
-    * trivially stealing all funds in the funding transaction!
-    */
-   LDKEvent_FundingBroadcastSafe,
-   /**
-    * Indicates we've received money! Just gotta dig out that payment preimage and feed it to
-    * ChannelManager::claim_funds to get it....
-    * Note that if the preimage is not known or the amount paid is incorrect, you should call
-    * ChannelManager::fail_htlc_backwards to free up resources for this HTLC and avoid
-    * network congestion.
-    * The amount paid should be considered 'incorrect' when it is less than or more than twice
-    * the amount expected.
-    * If you fail to call either ChannelManager::claim_funds or
-    * ChannelManager::fail_htlc_backwards within the HTLC's timeout, the HTLC will be
-    * automatically failed.
-    */
-   LDKEvent_PaymentReceived,
-   /**
-    * Indicates an outbound payment we made succeeded (ie it made it all the way to its target
-    * and we got back the payment preimage for it).
-    * Note that duplicative PaymentSent Events may be generated - it is your responsibility to
-    * deduplicate them by payment_preimage (which MUST be unique)!
-    */
-   LDKEvent_PaymentSent,
+typedef struct MUST_USE_STRUCT LDKChannelConfig {
    /**
-    * Indicates an outbound payment we made failed. Probably some intermediary node dropped
-    * something. You may wish to retry with a different route.
-    * Note that duplicative PaymentFailed Events may be generated - it is your responsibility to
-    * deduplicate them by payment_hash (which MUST be unique)!
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
     */
-   LDKEvent_PaymentFailed,
+   LDKnativeChannelConfig *inner;
+   bool is_owned;
+} LDKChannelConfig;
+
+typedef union LDKCResult_ChannelConfigDecodeErrorZPtr {
+   struct LDKChannelConfig *result;
+   struct LDKDecodeError *err;
+} LDKCResult_ChannelConfigDecodeErrorZPtr;
+
+typedef struct LDKCResult_ChannelConfigDecodeErrorZ {
+   union LDKCResult_ChannelConfigDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_ChannelConfigDecodeErrorZ;
+
+
+
+/**
+ * An Err type for failure to process messages.
+ */
+typedef struct MUST_USE_STRUCT LDKLightningError {
    /**
-    * Used to indicate that ChannelManager::process_pending_htlc_forwards should be called at a
-    * time in the future.
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
     */
-   LDKEvent_PendingHTLCsForwardable,
+   LDKnativeLightningError *inner;
+   bool is_owned;
+} LDKLightningError;
+
+typedef union LDKCResult_boolLightningErrorZPtr {
+   bool *result;
+   struct LDKLightningError *err;
+} LDKCResult_boolLightningErrorZPtr;
+
+typedef struct LDKCResult_boolLightningErrorZ {
+   union LDKCResult_boolLightningErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_boolLightningErrorZ;
+
+
+
+/**
+ * A channel_announcement message to be sent or received from a peer
+ */
+typedef struct MUST_USE_STRUCT LDKChannelAnnouncement {
    /**
-    * Used to indicate that an output was generated on-chain which you should know how to spend.
-    * Such an output will *not* ever be spent by rust-lightning, and are not at risk of your
-    * counterparty spending them due to some kind of timeout. Thus, you need to store them
-    * somewhere and spend them when you create on-chain transactions.
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
     */
-   LDKEvent_SpendableOutputs,
+   LDKnativeChannelAnnouncement *inner;
+   bool is_owned;
+} LDKChannelAnnouncement;
+
+
+
+/**
+ * A channel_update message to be sent or received from a peer
+ */
+typedef struct MUST_USE_STRUCT LDKChannelUpdate {
    /**
-    * Must be last for serialization purposes
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
     */
-   LDKEvent_Sentinel,
-} LDKEvent_Tag;
+   LDKnativeChannelUpdate *inner;
+   bool is_owned;
+} LDKChannelUpdate;
 
-typedef struct LDKEvent_LDKFundingGenerationReady_Body {
-   LDKThirtyTwoBytes temporary_channel_id;
-   uint64_t channel_value_satoshis;
-   LDKCVec_u8Z output_script;
-   uint64_t user_channel_id;
-} LDKEvent_LDKFundingGenerationReady_Body;
+typedef struct LDKC3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ {
+   struct LDKChannelAnnouncement a;
+   struct LDKChannelUpdate b;
+   struct LDKChannelUpdate c;
+} LDKC3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ;
 
-typedef struct LDKEvent_LDKFundingBroadcastSafe_Body {
-   LDKOutPoint funding_txo;
-   uint64_t user_channel_id;
-} LDKEvent_LDKFundingBroadcastSafe_Body;
+typedef struct LDKCVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ {
+   struct LDKC3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ *data;
+   uintptr_t datalen;
+} LDKCVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ;
 
-typedef struct LDKEvent_LDKPaymentReceived_Body {
-   LDKThirtyTwoBytes payment_hash;
-   LDKThirtyTwoBytes payment_secret;
-   uint64_t amt;
-} LDKEvent_LDKPaymentReceived_Body;
 
-typedef struct LDKEvent_LDKPaymentSent_Body {
-   LDKThirtyTwoBytes payment_preimage;
-} LDKEvent_LDKPaymentSent_Body;
 
-typedef struct LDKEvent_LDKPaymentFailed_Body {
-   LDKThirtyTwoBytes payment_hash;
-   bool rejected_by_dest;
-} LDKEvent_LDKPaymentFailed_Body;
+/**
+ * A node_announcement message to be sent or received from a peer
+ */
+typedef struct MUST_USE_STRUCT LDKNodeAnnouncement {
+   /**
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
+    */
+   LDKnativeNodeAnnouncement *inner;
+   bool is_owned;
+} LDKNodeAnnouncement;
 
-typedef struct LDKEvent_LDKPendingHTLCsForwardable_Body {
-   uint64_t time_forwardable;
-} LDKEvent_LDKPendingHTLCsForwardable_Body;
+typedef struct LDKCVec_NodeAnnouncementZ {
+   struct LDKNodeAnnouncement *data;
+   uintptr_t datalen;
+} LDKCVec_NodeAnnouncementZ;
 
-typedef struct LDKEvent_LDKSpendableOutputs_Body {
-   LDKCVec_SpendableOutputDescriptorZ outputs;
-} LDKEvent_LDKSpendableOutputs_Body;
+typedef union LDKCResult_NoneLightningErrorZPtr {
+   /**
+    * Note that this value is always NULL, as there are no contents in the OK variant
+    */
+   void *result;
+   struct LDKLightningError *err;
+} LDKCResult_NoneLightningErrorZPtr;
 
-typedef struct LDKEvent {
-   LDKEvent_Tag tag;
-   union {
-      LDKEvent_LDKFundingGenerationReady_Body funding_generation_ready;
-      LDKEvent_LDKFundingBroadcastSafe_Body funding_broadcast_safe;
-      LDKEvent_LDKPaymentReceived_Body payment_received;
-      LDKEvent_LDKPaymentSent_Body payment_sent;
-      LDKEvent_LDKPaymentFailed_Body payment_failed;
-      LDKEvent_LDKPendingHTLCsForwardable_Body pending_htl_cs_forwardable;
-      LDKEvent_LDKSpendableOutputs_Body spendable_outputs;
-   };
-} LDKEvent;
+typedef struct LDKCResult_NoneLightningErrorZ {
+   union LDKCResult_NoneLightningErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_NoneLightningErrorZ;
 
 
 
@@ -987,20 +942,6 @@ typedef struct MUST_USE_STRUCT LDKChannelReestablish {
 
 
 
-/**
- * A node_announcement message to be sent or received from a peer
- */
-typedef struct MUST_USE_STRUCT LDKNodeAnnouncement {
-   /**
-    * Nearly everywhere, inner must be non-null, however in places where
-    * the Rust equivalent takes an Option, it may be set to null to indicate None.
-    */
-   LDKnativeNodeAnnouncement *inner;
-   bool is_owned;
-} LDKNodeAnnouncement;
-
-
-
 /**
  * An error message to be sent or received from a peer
  */
@@ -1036,14 +977,14 @@ typedef enum LDKErrorAction_Tag {
 } LDKErrorAction_Tag;
 
 typedef struct LDKErrorAction_LDKDisconnectPeer_Body {
-   LDKErrorMessage msg;
+   struct LDKErrorMessage msg;
 } LDKErrorAction_LDKDisconnectPeer_Body;
 
 typedef struct LDKErrorAction_LDKSendErrorMessage_Body {
-   LDKErrorMessage msg;
+   struct LDKErrorMessage msg;
 } LDKErrorAction_LDKSendErrorMessage_Body;
 
-typedef struct LDKErrorAction {
+typedef struct MUST_USE_STRUCT LDKErrorAction {
    LDKErrorAction_Tag tag;
    union {
       LDKErrorAction_LDKDisconnectPeer_Body disconnect_peer;
@@ -1076,7 +1017,7 @@ typedef enum LDKHTLCFailChannelUpdate_Tag {
 } LDKHTLCFailChannelUpdate_Tag;
 
 typedef struct LDKHTLCFailChannelUpdate_LDKChannelUpdateMessage_Body {
-   LDKChannelUpdate msg;
+   struct LDKChannelUpdate msg;
 } LDKHTLCFailChannelUpdate_LDKChannelUpdateMessage_Body;
 
 typedef struct LDKHTLCFailChannelUpdate_LDKChannelClosed_Body {
@@ -1085,11 +1026,11 @@ typedef struct LDKHTLCFailChannelUpdate_LDKChannelClosed_Body {
 } LDKHTLCFailChannelUpdate_LDKChannelClosed_Body;
 
 typedef struct LDKHTLCFailChannelUpdate_LDKNodeFailure_Body {
-   LDKPublicKey node_id;
+   struct LDKPublicKey node_id;
    bool is_permanent;
 } LDKHTLCFailChannelUpdate_LDKNodeFailure_Body;
 
-typedef struct LDKHTLCFailChannelUpdate {
+typedef struct MUST_USE_STRUCT LDKHTLCFailChannelUpdate {
    LDKHTLCFailChannelUpdate_Tag tag;
    union {
       LDKHTLCFailChannelUpdate_LDKChannelUpdateMessage_Body channel_update_message;
@@ -1098,6 +1039,44 @@ typedef struct LDKHTLCFailChannelUpdate {
    };
 } LDKHTLCFailChannelUpdate;
 
+
+
+/**
+ * A query_channel_range message is used to query a peer for channel
+ * UTXOs in a range of blocks. The recipient of a query makes a best
+ * effort to reply to the query using one or more reply_channel_range
+ * messages.
+ */
+typedef struct MUST_USE_STRUCT LDKQueryChannelRange {
+   /**
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
+    */
+   LDKnativeQueryChannelRange *inner;
+   bool is_owned;
+} LDKQueryChannelRange;
+
+
+
+/**
+ * A query_short_channel_ids message is used to query a peer for
+ * routing gossip messages related to one or more short_channel_ids.
+ * The query recipient will reply with the latest, if available,
+ * channel_announcement, channel_update and node_announcement messages
+ * it maintains for the requested short_channel_ids followed by a
+ * reply_short_channel_ids_end message. The short_channel_ids sent in
+ * this query are encoded. We only support encoding_type=0 uncompressed
+ * serialization and do not support encoding_type=1 zlib serialization.
+ */
+typedef struct MUST_USE_STRUCT LDKQueryShortChannelIds {
+   /**
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
+    */
+   LDKnativeQueryShortChannelIds *inner;
+   bool is_owned;
+} LDKQueryShortChannelIds;
+
 /**
  * An event generated by ChannelManager which indicates a message should be sent to a peer (or
  * broadcast to most peers).
@@ -1180,89 +1159,108 @@ typedef enum LDKMessageSendEvent_Tag {
     */
    LDKMessageSendEvent_PaymentFailureNetworkUpdate,
    /**
-    * Must be last for serialization purposes
+    * Query a peer for channels with funding transaction UTXOs in a block range.
     */
-   LDKMessageSendEvent_Sentinel,
-} LDKMessageSendEvent_Tag;
+   LDKMessageSendEvent_SendChannelRangeQuery,
+   /**
+    * Request routing gossip messages from a peer for a list of channels identified by
+    * their short_channel_ids.
+    */
+   LDKMessageSendEvent_SendShortIdsQuery,
+   /**
+    * Must be last for serialization purposes
+    */
+   LDKMessageSendEvent_Sentinel,
+} LDKMessageSendEvent_Tag;
 
 typedef struct LDKMessageSendEvent_LDKSendAcceptChannel_Body {
-   LDKPublicKey node_id;
-   LDKAcceptChannel msg;
+   struct LDKPublicKey node_id;
+   struct LDKAcceptChannel msg;
 } LDKMessageSendEvent_LDKSendAcceptChannel_Body;
 
 typedef struct LDKMessageSendEvent_LDKSendOpenChannel_Body {
-   LDKPublicKey node_id;
-   LDKOpenChannel msg;
+   struct LDKPublicKey node_id;
+   struct LDKOpenChannel msg;
 } LDKMessageSendEvent_LDKSendOpenChannel_Body;
 
 typedef struct LDKMessageSendEvent_LDKSendFundingCreated_Body {
-   LDKPublicKey node_id;
-   LDKFundingCreated msg;
+   struct LDKPublicKey node_id;
+   struct LDKFundingCreated msg;
 } LDKMessageSendEvent_LDKSendFundingCreated_Body;
 
 typedef struct LDKMessageSendEvent_LDKSendFundingSigned_Body {
-   LDKPublicKey node_id;
-   LDKFundingSigned msg;
+   struct LDKPublicKey node_id;
+   struct LDKFundingSigned msg;
 } LDKMessageSendEvent_LDKSendFundingSigned_Body;
 
 typedef struct LDKMessageSendEvent_LDKSendFundingLocked_Body {
-   LDKPublicKey node_id;
-   LDKFundingLocked msg;
+   struct LDKPublicKey node_id;
+   struct LDKFundingLocked msg;
 } LDKMessageSendEvent_LDKSendFundingLocked_Body;
 
 typedef struct LDKMessageSendEvent_LDKSendAnnouncementSignatures_Body {
-   LDKPublicKey node_id;
-   LDKAnnouncementSignatures msg;
+   struct LDKPublicKey node_id;
+   struct LDKAnnouncementSignatures msg;
 } LDKMessageSendEvent_LDKSendAnnouncementSignatures_Body;
 
 typedef struct LDKMessageSendEvent_LDKUpdateHTLCs_Body {
-   LDKPublicKey node_id;
-   LDKCommitmentUpdate updates;
+   struct LDKPublicKey node_id;
+   struct LDKCommitmentUpdate updates;
 } LDKMessageSendEvent_LDKUpdateHTLCs_Body;
 
 typedef struct LDKMessageSendEvent_LDKSendRevokeAndACK_Body {
-   LDKPublicKey node_id;
-   LDKRevokeAndACK msg;
+   struct LDKPublicKey node_id;
+   struct LDKRevokeAndACK msg;
 } LDKMessageSendEvent_LDKSendRevokeAndACK_Body;
 
 typedef struct LDKMessageSendEvent_LDKSendClosingSigned_Body {
-   LDKPublicKey node_id;
-   LDKClosingSigned msg;
+   struct LDKPublicKey node_id;
+   struct LDKClosingSigned msg;
 } LDKMessageSendEvent_LDKSendClosingSigned_Body;
 
 typedef struct LDKMessageSendEvent_LDKSendShutdown_Body {
-   LDKPublicKey node_id;
-   LDKShutdown msg;
+   struct LDKPublicKey node_id;
+   struct LDKShutdown msg;
 } LDKMessageSendEvent_LDKSendShutdown_Body;
 
 typedef struct LDKMessageSendEvent_LDKSendChannelReestablish_Body {
-   LDKPublicKey node_id;
-   LDKChannelReestablish msg;
+   struct LDKPublicKey node_id;
+   struct LDKChannelReestablish msg;
 } LDKMessageSendEvent_LDKSendChannelReestablish_Body;
 
 typedef struct LDKMessageSendEvent_LDKBroadcastChannelAnnouncement_Body {
-   LDKChannelAnnouncement msg;
-   LDKChannelUpdate update_msg;
+   struct LDKChannelAnnouncement msg;
+   struct LDKChannelUpdate update_msg;
 } LDKMessageSendEvent_LDKBroadcastChannelAnnouncement_Body;
 
 typedef struct LDKMessageSendEvent_LDKBroadcastNodeAnnouncement_Body {
-   LDKNodeAnnouncement msg;
+   struct LDKNodeAnnouncement msg;
 } LDKMessageSendEvent_LDKBroadcastNodeAnnouncement_Body;
 
 typedef struct LDKMessageSendEvent_LDKBroadcastChannelUpdate_Body {
-   LDKChannelUpdate msg;
+   struct LDKChannelUpdate msg;
 } LDKMessageSendEvent_LDKBroadcastChannelUpdate_Body;
 
 typedef struct LDKMessageSendEvent_LDKHandleError_Body {
-   LDKPublicKey node_id;
-   LDKErrorAction action;
+   struct LDKPublicKey node_id;
+   struct LDKErrorAction action;
 } LDKMessageSendEvent_LDKHandleError_Body;
 
 typedef struct LDKMessageSendEvent_LDKPaymentFailureNetworkUpdate_Body {
-   LDKHTLCFailChannelUpdate update;
+   struct LDKHTLCFailChannelUpdate update;
 } LDKMessageSendEvent_LDKPaymentFailureNetworkUpdate_Body;
 
-typedef struct LDKMessageSendEvent {
+typedef struct LDKMessageSendEvent_LDKSendChannelRangeQuery_Body {
+   struct LDKPublicKey node_id;
+   struct LDKQueryChannelRange msg;
+} LDKMessageSendEvent_LDKSendChannelRangeQuery_Body;
+
+typedef struct LDKMessageSendEvent_LDKSendShortIdsQuery_Body {
+   struct LDKPublicKey node_id;
+   struct LDKQueryShortChannelIds msg;
+} LDKMessageSendEvent_LDKSendShortIdsQuery_Body;
+
+typedef struct MUST_USE_STRUCT LDKMessageSendEvent {
    LDKMessageSendEvent_Tag tag;
    union {
       LDKMessageSendEvent_LDKSendAcceptChannel_Body send_accept_channel;
@@ -1281,416 +1279,590 @@ typedef struct LDKMessageSendEvent {
       LDKMessageSendEvent_LDKBroadcastChannelUpdate_Body broadcast_channel_update;
       LDKMessageSendEvent_LDKHandleError_Body handle_error;
       LDKMessageSendEvent_LDKPaymentFailureNetworkUpdate_Body payment_failure_network_update;
+      LDKMessageSendEvent_LDKSendChannelRangeQuery_Body send_channel_range_query;
+      LDKMessageSendEvent_LDKSendShortIdsQuery_Body send_short_ids_query;
    };
 } LDKMessageSendEvent;
 
-typedef struct LDKCVecTempl_MessageSendEvent {
-   LDKMessageSendEvent *data;
+typedef struct LDKCVec_MessageSendEventZ {
+   struct LDKMessageSendEvent *data;
    uintptr_t datalen;
-} LDKCVecTempl_MessageSendEvent;
+} LDKCVec_MessageSendEventZ;
+
 
-typedef LDKCVecTempl_MessageSendEvent LDKCVec_MessageSendEventZ;
 
 /**
- * A trait indicating an object may generate message send events
+ * Details about one direction of a channel. Received
+ * within a channel update.
  */
-typedef struct LDKMessageSendEventsProvider {
-   void *this_arg;
+typedef struct MUST_USE_STRUCT LDKDirectionalChannelInfo {
    /**
-    * Gets the list of pending events which were generated by previous actions, clearing the list
-    * in the process.
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
     */
-   LDKCVec_MessageSendEventZ (*get_and_clear_pending_msg_events)(const void *this_arg);
-   void (*free)(void *this_arg);
-} LDKMessageSendEventsProvider;
+   LDKnativeDirectionalChannelInfo *inner;
+   bool is_owned;
+} LDKDirectionalChannelInfo;
+
+typedef union LDKCResult_DirectionalChannelInfoDecodeErrorZPtr {
+   struct LDKDirectionalChannelInfo *result;
+   struct LDKDecodeError *err;
+} LDKCResult_DirectionalChannelInfoDecodeErrorZPtr;
+
+typedef struct LDKCResult_DirectionalChannelInfoDecodeErrorZ {
+   union LDKCResult_DirectionalChannelInfoDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_DirectionalChannelInfoDecodeErrorZ;
 
-typedef struct LDKCVecTempl_Event {
-   LDKEvent *data;
-   uintptr_t datalen;
-} LDKCVecTempl_Event;
 
-typedef LDKCVecTempl_Event LDKCVec_EventZ;
 
 /**
- * A trait indicating an object may generate events
+ * Details about a channel (both directions).
+ * Received within a channel announcement.
  */
-typedef struct LDKEventsProvider {
-   void *this_arg;
+typedef struct MUST_USE_STRUCT LDKChannelInfo {
    /**
-    * Gets the list of pending events which were generated by previous actions, clearing the list
-    * in the process.
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
     */
-   LDKCVec_EventZ (*get_and_clear_pending_events)(const void *this_arg);
-   void (*free)(void *this_arg);
-} LDKEventsProvider;
+   LDKnativeChannelInfo *inner;
+   bool is_owned;
+} LDKChannelInfo;
+
+typedef union LDKCResult_ChannelInfoDecodeErrorZPtr {
+   struct LDKChannelInfo *result;
+   struct LDKDecodeError *err;
+} LDKCResult_ChannelInfoDecodeErrorZPtr;
+
+typedef struct LDKCResult_ChannelInfoDecodeErrorZ {
+   union LDKCResult_ChannelInfoDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_ChannelInfoDecodeErrorZ;
+
+
 
 /**
- * A trait encapsulating the operations required of a logger
+ * Fees for routing via a given channel or a node
  */
-typedef struct LDKLogger {
-   void *this_arg;
+typedef struct MUST_USE_STRUCT LDKRoutingFees {
    /**
-    * Logs the `Record`
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
     */
-   void (*log)(const void *this_arg, const char *record);
-   void (*free)(void *this_arg);
-} LDKLogger;
+   LDKnativeRoutingFees *inner;
+   bool is_owned;
+} LDKRoutingFees;
+
+typedef union LDKCResult_RoutingFeesDecodeErrorZPtr {
+   struct LDKRoutingFees *result;
+   struct LDKDecodeError *err;
+} LDKCResult_RoutingFeesDecodeErrorZPtr;
 
+typedef struct LDKCResult_RoutingFeesDecodeErrorZ {
+   union LDKCResult_RoutingFeesDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_RoutingFeesDecodeErrorZ;
+
+typedef struct LDKFourBytes {
+   uint8_t data[4];
+} LDKFourBytes;
+
+typedef struct LDKSixteenBytes {
+   uint8_t data[16];
+} LDKSixteenBytes;
 
+typedef struct LDKTenBytes {
+   uint8_t data[10];
+} LDKTenBytes;
 
 /**
- * Configuration we set when applicable.
- *
- * Default::default() provides sane defaults.
+ * Arbitrary 32 bytes, which could represent one of a few different things. You probably want to
+ * look up the corresponding function in rust-lightning's docs.
  */
-typedef struct MUST_USE_STRUCT LDKChannelHandshakeConfig {
+typedef struct LDKThirtyTwoBytes {
+   uint8_t data[32];
+} LDKThirtyTwoBytes;
+
+/**
+ * An address which can be used to connect to a remote peer
+ */
+typedef enum LDKNetAddress_Tag {
    /**
-    * Nearly everywhere, inner must be non-null, however in places where
-    * the Rust equivalent takes an Option, it may be set to null to indicate None.
+    * An IPv4 address/port on which the peer is listening.
     */
-   LDKnativeChannelHandshakeConfig *inner;
-   bool is_owned;
-} LDKChannelHandshakeConfig;
+   LDKNetAddress_IPv4,
+   /**
+    * An IPv6 address/port on which the peer is listening.
+    */
+   LDKNetAddress_IPv6,
+   /**
+    * An old-style Tor onion address/port on which the peer is listening.
+    */
+   LDKNetAddress_OnionV2,
+   /**
+    * A new-style Tor onion address/port on which the peer is listening.
+    * To create the human-readable \"hostname\", concatenate ed25519_pubkey, checksum, and version,
+    * wrap as base32 and append \".onion\".
+    */
+   LDKNetAddress_OnionV3,
+   /**
+    * Must be last for serialization purposes
+    */
+   LDKNetAddress_Sentinel,
+} LDKNetAddress_Tag;
+
+typedef struct LDKNetAddress_LDKIPv4_Body {
+   struct LDKFourBytes addr;
+   uint16_t port;
+} LDKNetAddress_LDKIPv4_Body;
+
+typedef struct LDKNetAddress_LDKIPv6_Body {
+   struct LDKSixteenBytes addr;
+   uint16_t port;
+} LDKNetAddress_LDKIPv6_Body;
+
+typedef struct LDKNetAddress_LDKOnionV2_Body {
+   struct LDKTenBytes addr;
+   uint16_t port;
+} LDKNetAddress_LDKOnionV2_Body;
+
+typedef struct LDKNetAddress_LDKOnionV3_Body {
+   struct LDKThirtyTwoBytes ed25519_pubkey;
+   uint16_t checksum;
+   uint8_t version;
+   uint16_t port;
+} LDKNetAddress_LDKOnionV3_Body;
+
+typedef struct MUST_USE_STRUCT LDKNetAddress {
+   LDKNetAddress_Tag tag;
+   union {
+      LDKNetAddress_LDKIPv4_Body i_pv4;
+      LDKNetAddress_LDKIPv6_Body i_pv6;
+      LDKNetAddress_LDKOnionV2_Body onion_v2;
+      LDKNetAddress_LDKOnionV3_Body onion_v3;
+   };
+} LDKNetAddress;
+
+typedef struct LDKCVec_NetAddressZ {
+   struct LDKNetAddress *data;
+   uintptr_t datalen;
+} LDKCVec_NetAddressZ;
 
 
 
 /**
- * Optional channel limits which are applied during channel creation.
- *
- * These limits are only applied to our counterparty's limits, not our own.
- *
- * Use 0/<type>::max_value() as appropriate to skip checking.
- *
- * Provides sane defaults for most configurations.
- *
- * Most additional limits are disabled except those with which specify a default in individual
- * field documentation. Note that this may result in barely-usable channels, but since they
- * are applied mostly only to incoming channels that's not much of a problem.
+ * Information received in the latest node_announcement from this node.
  */
-typedef struct MUST_USE_STRUCT LDKChannelHandshakeLimits {
+typedef struct MUST_USE_STRUCT LDKNodeAnnouncementInfo {
    /**
     * Nearly everywhere, inner must be non-null, however in places where
     * the Rust equivalent takes an Option, it may be set to null to indicate None.
     */
-   LDKnativeChannelHandshakeLimits *inner;
+   LDKnativeNodeAnnouncementInfo *inner;
    bool is_owned;
-} LDKChannelHandshakeLimits;
+} LDKNodeAnnouncementInfo;
+
+typedef union LDKCResult_NodeAnnouncementInfoDecodeErrorZPtr {
+   struct LDKNodeAnnouncementInfo *result;
+   struct LDKDecodeError *err;
+} LDKCResult_NodeAnnouncementInfoDecodeErrorZPtr;
+
+typedef struct LDKCResult_NodeAnnouncementInfoDecodeErrorZ {
+   union LDKCResult_NodeAnnouncementInfoDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_NodeAnnouncementInfoDecodeErrorZ;
+
+typedef struct LDKCVec_u64Z {
+   uint64_t *data;
+   uintptr_t datalen;
+} LDKCVec_u64Z;
 
 
 
 /**
- * Options which apply on a per-channel basis and may change at runtime or based on negotiation
- * with our counterparty.
+ * Details about a node in the network, known from the network announcement.
  */
-typedef struct MUST_USE_STRUCT LDKChannelConfig {
+typedef struct MUST_USE_STRUCT LDKNodeInfo {
    /**
     * Nearly everywhere, inner must be non-null, however in places where
     * the Rust equivalent takes an Option, it may be set to null to indicate None.
     */
-   LDKnativeChannelConfig *inner;
+   LDKnativeNodeInfo *inner;
    bool is_owned;
-} LDKChannelConfig;
+} LDKNodeInfo;
 
-typedef struct LDKu8slice {
-   const uint8_t *data;
-   uintptr_t datalen;
-} LDKu8slice;
+typedef union LDKCResult_NodeInfoDecodeErrorZPtr {
+   struct LDKNodeInfo *result;
+   struct LDKDecodeError *err;
+} LDKCResult_NodeInfoDecodeErrorZPtr;
+
+typedef struct LDKCResult_NodeInfoDecodeErrorZ {
+   union LDKCResult_NodeInfoDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_NodeInfoDecodeErrorZ;
 
 
 
 /**
- * Top-level config which holds ChannelHandshakeLimits and ChannelConfig.
- *
- * Default::default() provides sane defaults for most configurations
- * (but currently with 0 relay fees!)
+ * Represents the network as nodes and channels between them
  */
-typedef struct MUST_USE_STRUCT LDKUserConfig {
+typedef struct MUST_USE_STRUCT LDKNetworkGraph {
    /**
     * Nearly everywhere, inner must be non-null, however in places where
     * the Rust equivalent takes an Option, it may be set to null to indicate None.
     */
-   LDKnativeUserConfig *inner;
+   LDKnativeNetworkGraph *inner;
    bool is_owned;
-} LDKUserConfig;
+} LDKNetworkGraph;
 
-typedef union LDKCResultPtr_TxOut__AccessError {
-   LDKTxOut *result;
-   LDKAccessError *err;
-} LDKCResultPtr_TxOut__AccessError;
+typedef union LDKCResult_NetworkGraphDecodeErrorZPtr {
+   struct LDKNetworkGraph *result;
+   struct LDKDecodeError *err;
+} LDKCResult_NetworkGraphDecodeErrorZPtr;
 
-typedef struct LDKCResultTempl_TxOut__AccessError {
-   LDKCResultPtr_TxOut__AccessError contents;
+typedef struct LDKCResult_NetworkGraphDecodeErrorZ {
+   union LDKCResult_NetworkGraphDecodeErrorZPtr contents;
    bool result_ok;
-} LDKCResultTempl_TxOut__AccessError;
+} LDKCResult_NetworkGraphDecodeErrorZ;
 
-typedef LDKCResultTempl_TxOut__AccessError LDKCResult_TxOutAccessErrorZ;
+typedef struct LDKC2Tuple_usizeTransactionZ {
+   uintptr_t a;
+   struct LDKTransaction b;
+} LDKC2Tuple_usizeTransactionZ;
 
-/**
- * The `Access` trait defines behavior for accessing chain data and state, such as blocks and
- * UTXOs.
- */
-typedef struct LDKAccess {
-   void *this_arg;
+typedef struct LDKCVec_C2Tuple_usizeTransactionZZ {
+   struct LDKC2Tuple_usizeTransactionZ *data;
+   uintptr_t datalen;
+} LDKCVec_C2Tuple_usizeTransactionZZ;
+
+typedef union LDKCResult_NoneChannelMonitorUpdateErrZPtr {
    /**
-    * Returns the transaction output of a funding transaction encoded by [`short_channel_id`].
-    * Returns an error if `genesis_hash` is for a different chain or if such a transaction output
-    * is unknown.
-    *
-    * [`short_channel_id`]: https://github.com/lightningnetwork/lightning-rfc/blob/master/07-routing-gossip.md#definition-of-short_channel_id
+    * Note that this value is always NULL, as there are no contents in the OK variant
     */
-   LDKCResult_TxOutAccessErrorZ (*get_utxo)(const void *this_arg, const uint8_t (*genesis_hash)[32], uint64_t short_channel_id);
-   void (*free)(void *this_arg);
-} LDKAccess;
+   void *result;
+   enum LDKChannelMonitorUpdateErr *err;
+} LDKCResult_NoneChannelMonitorUpdateErrZPtr;
+
+typedef struct LDKCResult_NoneChannelMonitorUpdateErrZ {
+   union LDKCResult_NoneChannelMonitorUpdateErrZPtr contents;
+   bool result_ok;
+} LDKCResult_NoneChannelMonitorUpdateErrZ;
 
 
 
 /**
- * One counterparty's public keys which do not change over the life of a channel.
+ * Simple structure sent back by `chain::Watch` when an HTLC from a forward channel is detected on
+ * chain. Used to update the corresponding HTLC in the backward channel. Failing to pass the
+ * preimage claim backward will lead to loss of funds.
+ *
+ * [`chain::Watch`]: ../trait.Watch.html
  */
-typedef struct MUST_USE_STRUCT LDKChannelPublicKeys {
+typedef struct MUST_USE_STRUCT LDKHTLCUpdate {
    /**
     * Nearly everywhere, inner must be non-null, however in places where
     * the Rust equivalent takes an Option, it may be set to null to indicate None.
     */
-   LDKnativeChannelPublicKeys *inner;
+   LDKnativeHTLCUpdate *inner;
    bool is_owned;
-} LDKChannelPublicKeys;
+} LDKHTLCUpdate;
 
 
 
 /**
- * The per-commitment point and a set of pre-calculated public keys used for transaction creation
- * in the signer.
- * The pre-calculated keys are an optimization, because ChannelKeys has enough
- * information to re-derive them.
+ * A reference to a transaction output.
+ *
+ * Differs from bitcoin::blockdata::transaction::OutPoint as the index is a u16 instead of u32
+ * due to LN's restrictions on index values. Should reduce (possibly) unsafe conversions this way.
  */
-typedef struct MUST_USE_STRUCT LDKPreCalculatedTxCreationKeys {
+typedef struct MUST_USE_STRUCT LDKOutPoint {
    /**
     * Nearly everywhere, inner must be non-null, however in places where
     * the Rust equivalent takes an Option, it may be set to null to indicate None.
     */
-   LDKnativePreCalculatedTxCreationKeys *inner;
+   LDKnativeOutPoint *inner;
    bool is_owned;
-} LDKPreCalculatedTxCreationKeys;
+} LDKOutPoint;
 
-typedef struct LDKCVecTempl_HTLCOutputInCommitment {
-   LDKHTLCOutputInCommitment *data;
-   uintptr_t datalen;
-} LDKCVecTempl_HTLCOutputInCommitment;
+/**
+ * An event to be processed by the ChannelManager.
+ */
+typedef enum LDKMonitorEvent_Tag {
+   /**
+    * A monitor event containing an HTLCUpdate.
+    */
+   LDKMonitorEvent_HTLCEvent,
+   /**
+    * A monitor event that the Channel's commitment transaction was broadcasted.
+    */
+   LDKMonitorEvent_CommitmentTxBroadcasted,
+   /**
+    * Must be last for serialization purposes
+    */
+   LDKMonitorEvent_Sentinel,
+} LDKMonitorEvent_Tag;
+
+typedef struct MUST_USE_STRUCT LDKMonitorEvent {
+   LDKMonitorEvent_Tag tag;
+   union {
+      struct {
+         struct LDKHTLCUpdate htlc_event;
+      };
+      struct {
+         struct LDKOutPoint commitment_tx_broadcasted;
+      };
+   };
+} LDKMonitorEvent;
 
-typedef LDKCVecTempl_HTLCOutputInCommitment LDKCVec_HTLCOutputInCommitmentZ;
+typedef struct LDKCVec_MonitorEventZ {
+   struct LDKMonitorEvent *data;
+   uintptr_t datalen;
+} LDKCVec_MonitorEventZ;
 
 
 
 /**
- * We use this to track holder commitment transactions and put off signing them until we are ready
- * to broadcast. This class can be used inside a signer implementation to generate a signature
- * given the relevant secret key.
+ * Information about a spendable output to a P2WSH script. See
+ * SpendableOutputDescriptor::DelayedPaymentOutput for more details on how to spend this.
  */
-typedef struct MUST_USE_STRUCT LDKHolderCommitmentTransaction {
+typedef struct MUST_USE_STRUCT LDKDelayedPaymentOutputDescriptor {
    /**
     * Nearly everywhere, inner must be non-null, however in places where
     * the Rust equivalent takes an Option, it may be set to null to indicate None.
     */
-   LDKnativeHolderCommitmentTransaction *inner;
+   LDKnativeDelayedPaymentOutputDescriptor *inner;
    bool is_owned;
-} LDKHolderCommitmentTransaction;
+} LDKDelayedPaymentOutputDescriptor;
 
 
 
 /**
- * The unsigned part of a channel_announcement
+ * Information about a spendable output to our \"payment key\". See
+ * SpendableOutputDescriptor::StaticPaymentOutput for more details on how to spend this.
  */
-typedef struct MUST_USE_STRUCT LDKUnsignedChannelAnnouncement {
+typedef struct MUST_USE_STRUCT LDKStaticPaymentOutputDescriptor {
    /**
     * Nearly everywhere, inner must be non-null, however in places where
     * the Rust equivalent takes an Option, it may be set to null to indicate None.
     */
-   LDKnativeUnsignedChannelAnnouncement *inner;
+   LDKnativeStaticPaymentOutputDescriptor *inner;
    bool is_owned;
-} LDKUnsignedChannelAnnouncement;
+} LDKStaticPaymentOutputDescriptor;
 
 /**
- * Set of lightning keys needed to operate a channel as described in BOLT 3.
- *
- * Signing services could be implemented on a hardware wallet. In this case,
- * the current ChannelKeys would be a front-end on top of a communication
- * channel connected to your secure device and lightning key material wouldn't
- * reside on a hot server. Nevertheless, a this deployment would still need
- * to trust the ChannelManager to avoid loss of funds as this latest component
- * could ask to sign commitment transaction with HTLCs paying to attacker pubkeys.
- *
- * A more secure iteration would be to use hashlock (or payment points) to pair
- * invoice/incoming HTLCs with outgoing HTLCs to implement a no-trust-ChannelManager
- * at the price of more state and computation on the hardware wallet side. In the future,
- * we are looking forward to design such interface.
- *
- * In any case, ChannelMonitor or fallback watchtowers are always going to be trusted
- * to act, as liveness and breach reply correctness are always going to be hard requirements
- * of LN security model, orthogonal of key management issues.
- *
- * If you're implementing a custom signer, you almost certainly want to implement
- * Readable/Writable to serialize out a unique reference to this set of keys so
- * that you can serialize the full ChannelManager object.
- *
+ * When on-chain outputs are created by rust-lightning (which our counterparty is not able to
+ * claim at any point in the future) an event is generated which you must track and be able to
+ * spend on-chain. The information needed to do this is provided in this enum, including the
+ * outpoint describing which txid and output index is available, the full output which exists at
+ * that txid/index, and any keys or other information required to sign.
  */
-typedef struct LDKChannelKeys {
-   void *this_arg;
+typedef enum LDKSpendableOutputDescriptor_Tag {
    /**
-    * Gets the per-commitment point for a specific commitment number
-    *
-    * Note that the commitment number starts at (1 << 48) - 1 and counts backwards.
+    * An output to a script which was provided via KeysInterface directly, either from
+    * `get_destination_script()` or `get_shutdown_pubkey()`, thus you should already know how to
+    * spend it. No secret keys are provided as rust-lightning was never given any key.
+    * These may include outputs from a transaction punishing our counterparty or claiming an HTLC
+    * on-chain using the payment preimage or after it has timed out.
     */
-   LDKPublicKey (*get_per_commitment_point)(const void *this_arg, uint64_t idx);
+   LDKSpendableOutputDescriptor_StaticOutput,
    /**
-    * Gets the commitment secret for a specific commitment number as part of the revocation process
+    * An output to a P2WSH script which can be spent with a single signature after a CSV delay.
     *
-    * An external signer implementation should error here if the commitment was already signed
-    * and should refuse to sign it in the future.
+    * The witness in the spending input should be:
+    * <BIP 143 signature> <empty vector> (MINIMALIF standard rule) <provided witnessScript>
     *
-    * May be called more than once for the same index.
+    * Note that the nSequence field in the spending input must be set to to_self_delay
+    * (which means the transaction is not broadcastable until at least to_self_delay
+    * blocks after the outpoint confirms).
     *
-    * Note that the commitment number starts at (1 << 48) - 1 and counts backwards.
-    * TODO: return a Result so we can signal a validation error
-    */
-   LDKThirtyTwoBytes (*release_commitment_secret)(const void *this_arg, uint64_t idx);
-   /**
-    * Gets the holder's channel public keys and basepoints
+    * These are generally the result of a \"revocable\" output to us, spendable only by us unless
+    * it is an output from an old state which we broadcast (which should never happen).
+    *
+    * To derive the delayed_payment key which is used to sign for this input, you must pass the
+    * holder delayed_payment_base_key (ie the private key which corresponds to the pubkey in
+    * Sign::pubkeys().delayed_payment_basepoint) and the provided per_commitment_point to
+    * chan_utils::derive_private_key. The public key can be generated without the secret key
+    * using chan_utils::derive_public_key and only the delayed_payment_basepoint which appears in
+    * Sign::pubkeys().
+    *
+    * To derive the revocation_pubkey provided here (which is used in the witness
+    * script generation), you must pass the counterparty revocation_basepoint (which appears in the
+    * call to Sign::ready_channel) and the provided per_commitment point
+    * to chan_utils::derive_public_revocation_key.
+    *
+    * The witness script which is hashed and included in the output script_pubkey may be
+    * regenerated by passing the revocation_pubkey (derived as above), our delayed_payment pubkey
+    * (derived as above), and the to_self_delay contained here to
+    * chan_utils::get_revokeable_redeemscript.
     */
-   LDKChannelPublicKeys pubkeys;
+   LDKSpendableOutputDescriptor_DelayedPaymentOutput,
    /**
-    * Fill in the pubkeys field as a reference to it will be given to Rust after this returns
-    * Note that this takes a pointer to this object, not the this_ptr like other methods do
-    * This function pointer may be NULL if pubkeys is filled in when this object is created and never needs updating.
+    * An output to a P2WPKH, spendable exclusively by our payment key (ie the private key which
+    * corresponds to the public key in Sign::pubkeys().payment_point).
+    * The witness in the spending input, is, thus, simply:
+    * <BIP 143 signature> <payment key>
+    *
+    * These are generally the result of our counterparty having broadcast the current state,
+    * allowing us to claim the non-HTLC-encumbered outputs immediately.
     */
-   void (*set_pubkeys)(const LDKChannelKeys*);
+   LDKSpendableOutputDescriptor_StaticPaymentOutput,
    /**
-    * Gets arbitrary identifiers describing the set of keys which are provided back to you in
-    * some SpendableOutputDescriptor types. These should be sufficient to identify this
-    * ChannelKeys object uniquely and lookup or re-derive its keys.
+    * Must be last for serialization purposes
     */
-   LDKC2Tuple_u64u64Z (*key_derivation_params)(const void *this_arg);
+   LDKSpendableOutputDescriptor_Sentinel,
+} LDKSpendableOutputDescriptor_Tag;
+
+typedef struct LDKSpendableOutputDescriptor_LDKStaticOutput_Body {
+   struct LDKOutPoint outpoint;
+   struct LDKTxOut output;
+} LDKSpendableOutputDescriptor_LDKStaticOutput_Body;
+
+typedef struct MUST_USE_STRUCT LDKSpendableOutputDescriptor {
+   LDKSpendableOutputDescriptor_Tag tag;
+   union {
+      LDKSpendableOutputDescriptor_LDKStaticOutput_Body static_output;
+      struct {
+         struct LDKDelayedPaymentOutputDescriptor delayed_payment_output;
+      };
+      struct {
+         struct LDKStaticPaymentOutputDescriptor static_payment_output;
+      };
+   };
+} LDKSpendableOutputDescriptor;
+
+typedef struct LDKCVec_SpendableOutputDescriptorZ {
+   struct LDKSpendableOutputDescriptor *data;
+   uintptr_t datalen;
+} LDKCVec_SpendableOutputDescriptorZ;
+
+/**
+ * An Event which you should probably take some action in response to.
+ *
+ * Note that while Writeable and Readable are implemented for Event, you probably shouldn't use
+ * them directly as they don't round-trip exactly (for example FundingGenerationReady is never
+ * written as it makes no sense to respond to it after reconnecting to peers).
+ */
+typedef enum LDKEvent_Tag {
    /**
-    * Create a signature for a counterparty's commitment transaction and associated HTLC transactions.
-    *
-    * Note that if signing fails or is rejected, the channel will be force-closed.
+    * Used to indicate that the client should generate a funding transaction with the given
+    * parameters and then call ChannelManager::funding_transaction_generated.
+    * Generated in ChannelManager message handling.
+    * Note that *all inputs* in the funding transaction must spend SegWit outputs or your
+    * counterparty can steal your funds!
     */
-   LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ (*sign_counterparty_commitment)(const void *this_arg, uint32_t feerate_per_kw, LDKTransaction commitment_tx, const LDKPreCalculatedTxCreationKeys *keys, LDKCVec_HTLCOutputInCommitmentZ htlcs);
+   LDKEvent_FundingGenerationReady,
    /**
-    * Create a signature for a holder's commitment transaction. This will only ever be called with
-    * the same holder_commitment_tx (or a copy thereof), though there are currently no guarantees
-    * that it will not be called multiple times.
-    * An external signer implementation should check that the commitment has not been revoked.
+    * Used to indicate that the client may now broadcast the funding transaction it created for a
+    * channel. Broadcasting such a transaction prior to this event may lead to our counterparty
+    * trivially stealing all funds in the funding transaction!
     */
-   LDKCResult_SignatureNoneZ (*sign_holder_commitment)(const void *this_arg, const LDKHolderCommitmentTransaction *holder_commitment_tx);
+   LDKEvent_FundingBroadcastSafe,
    /**
-    * Create a signature for each HTLC transaction spending a holder's commitment transaction.
-    *
-    * Unlike sign_holder_commitment, this may be called multiple times with *different*
-    * holder_commitment_tx values. While this will never be called with a revoked
-    * holder_commitment_tx, it is possible that it is called with the second-latest
-    * holder_commitment_tx (only if we haven't yet revoked it) if some watchtower/secondary
-    * ChannelMonitor decided to broadcast before it had been updated to the latest.
-    *
-    * Either an Err should be returned, or a Vec with one entry for each HTLC which exists in
-    * holder_commitment_tx. For those HTLCs which have transaction_output_index set to None
-    * (implying they were considered dust at the time the commitment transaction was negotiated),
-    * a corresponding None should be included in the return value. All other positions in the
-    * return value must contain a signature.
+    * Indicates we've received money! Just gotta dig out that payment preimage and feed it to
+    * ChannelManager::claim_funds to get it....
+    * Note that if the preimage is not known or the amount paid is incorrect, you should call
+    * ChannelManager::fail_htlc_backwards to free up resources for this HTLC and avoid
+    * network congestion.
+    * The amount paid should be considered 'incorrect' when it is less than or more than twice
+    * the amount expected.
+    * If you fail to call either ChannelManager::claim_funds or
+    * ChannelManager::fail_htlc_backwards within the HTLC's timeout, the HTLC will be
+    * automatically failed.
     */
-   LDKCResult_CVec_SignatureZNoneZ (*sign_holder_commitment_htlc_transactions)(const void *this_arg, const LDKHolderCommitmentTransaction *holder_commitment_tx);
+   LDKEvent_PaymentReceived,
    /**
-    * Create a signature for the given input in a transaction spending an HTLC or commitment
-    * transaction output when our counterparty broadcasts an old state.
-    *
-    * A justice transaction may claim multiples outputs at the same time if timelocks are
-    * similar, but only a signature for the input at index `input` should be signed for here.
-    * It may be called multiples time for same output(s) if a fee-bump is needed with regards
-    * to an upcoming timelock expiration.
-    *
-    * Amount is value of the output spent by this input, committed to in the BIP 143 signature.
-    *
-    * per_commitment_key is revocation secret which was provided by our counterparty when they
-    * revoked the state which they eventually broadcast. It's not a _holder_ secret key and does
-    * not allow the spending of any funds by itself (you need our holder revocation_secret to do
-    * so).
-    *
-    * htlc holds HTLC elements (hash, timelock) if the output being spent is a HTLC output, thus
-    * changing the format of the witness script (which is committed to in the BIP 143
-    * signatures).
+    * Indicates an outbound payment we made succeeded (ie it made it all the way to its target
+    * and we got back the payment preimage for it).
+    * Note that duplicative PaymentSent Events may be generated - it is your responsibility to
+    * deduplicate them by payment_preimage (which MUST be unique)!
     */
-   LDKCResult_SignatureNoneZ (*sign_justice_transaction)(const void *this_arg, LDKTransaction justice_tx, uintptr_t input, uint64_t amount, const uint8_t (*per_commitment_key)[32], const LDKHTLCOutputInCommitment *htlc);
+   LDKEvent_PaymentSent,
    /**
-    * Create a signature for a claiming transaction for a HTLC output on a counterparty's commitment
-    * transaction, either offered or received.
-    *
-    * Such a transaction may claim multiples offered outputs at same time if we know the
-    * preimage for each when we create it, but only the input at index `input` should be
-    * signed for here. It may be called multiple times for same output(s) if a fee-bump is
-    * needed with regards to an upcoming timelock expiration.
-    *
-    * Witness_script is either a offered or received script as defined in BOLT3 for HTLC
-    * outputs.
-    *
-    * Amount is value of the output spent by this input, committed to in the BIP 143 signature.
-    *
-    * Per_commitment_point is the dynamic point corresponding to the channel state
-    * detected onchain. It has been generated by our counterparty and is used to derive
-    * channel state keys, which are then included in the witness script and committed to in the
-    * BIP 143 signature.
+    * Indicates an outbound payment we made failed. Probably some intermediary node dropped
+    * something. You may wish to retry with a different route.
+    * Note that duplicative PaymentFailed Events may be generated - it is your responsibility to
+    * deduplicate them by payment_hash (which MUST be unique)!
     */
-   LDKCResult_SignatureNoneZ (*sign_counterparty_htlc_transaction)(const void *this_arg, LDKTransaction htlc_tx, uintptr_t input, uint64_t amount, LDKPublicKey per_commitment_point, const LDKHTLCOutputInCommitment *htlc);
+   LDKEvent_PaymentFailed,
    /**
-    * Create a signature for a (proposed) closing transaction.
-    *
-    * Note that, due to rounding, there may be one \"missing\" satoshi, and either party may have
-    * chosen to forgo their output as dust.
+    * Used to indicate that ChannelManager::process_pending_htlc_forwards should be called at a
+    * time in the future.
     */
-   LDKCResult_SignatureNoneZ (*sign_closing_transaction)(const void *this_arg, LDKTransaction closing_tx);
+   LDKEvent_PendingHTLCsForwardable,
    /**
-    * Signs a channel announcement message with our funding key, proving it comes from one
-    * of the channel participants.
-    *
-    * Note that if this fails or is rejected, the channel will not be publicly announced and
-    * our counterparty may (though likely will not) close the channel on us for violating the
-    * protocol.
+    * Used to indicate that an output was generated on-chain which you should know how to spend.
+    * Such an output will *not* ever be spent by rust-lightning, and are not at risk of your
+    * counterparty spending them due to some kind of timeout. Thus, you need to store them
+    * somewhere and spend them when you create on-chain transactions.
     */
-   LDKCResult_SignatureNoneZ (*sign_channel_announcement)(const void *this_arg, const LDKUnsignedChannelAnnouncement *msg);
+   LDKEvent_SpendableOutputs,
    /**
-    * Set the counterparty channel basepoints and counterparty_selected/holder_selected_contest_delay.
-    * This is done immediately on incoming channels and as soon as the channel is accepted on outgoing channels.
-    *
-    * We bind holder_selected_contest_delay late here for API convenience.
-    *
-    * Will be called before any signatures are applied.
+    * Must be last for serialization purposes
     */
-   void (*on_accept)(void *this_arg, const LDKChannelPublicKeys *channel_points, uint16_t counterparty_selected_contest_delay, uint16_t holder_selected_contest_delay);
-   void *(*clone)(const void *this_arg);
-   void (*free)(void *this_arg);
-} LDKChannelKeys;
+   LDKEvent_Sentinel,
+} LDKEvent_Tag;
+
+typedef struct LDKEvent_LDKFundingGenerationReady_Body {
+   struct LDKThirtyTwoBytes temporary_channel_id;
+   uint64_t channel_value_satoshis;
+   struct LDKCVec_u8Z output_script;
+   uint64_t user_channel_id;
+} LDKEvent_LDKFundingGenerationReady_Body;
 
+typedef struct LDKEvent_LDKFundingBroadcastSafe_Body {
+   struct LDKOutPoint funding_txo;
+   uint64_t user_channel_id;
+} LDKEvent_LDKFundingBroadcastSafe_Body;
 
+typedef struct LDKEvent_LDKPaymentReceived_Body {
+   struct LDKThirtyTwoBytes payment_hash;
+   struct LDKThirtyTwoBytes payment_secret;
+   uint64_t amt;
+} LDKEvent_LDKPaymentReceived_Body;
 
-/**
- * A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
- * on-chain transactions to ensure no loss of funds occurs.
- *
- * You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
- * information and are actively monitoring the chain.
- *
- * Pending Events or updated HTLCs which have not yet been read out by
- * get_and_clear_pending_monitor_events or get_and_clear_pending_events are serialized to disk and
- * reloaded at deserialize-time. Thus, you must ensure that, when handling events, all events
- * gotten are fully handled before re-serializing the new state.
- */
-typedef struct MUST_USE_STRUCT LDKChannelMonitor {
-   /**
-    * Nearly everywhere, inner must be non-null, however in places where
-    * the Rust equivalent takes an Option, it may be set to null to indicate None.
-    */
-   LDKnativeChannelMonitor *inner;
-   bool is_owned;
-} LDKChannelMonitor;
+typedef struct LDKEvent_LDKPaymentSent_Body {
+   struct LDKThirtyTwoBytes payment_preimage;
+} LDKEvent_LDKPaymentSent_Body;
+
+typedef struct LDKEvent_LDKPaymentFailed_Body {
+   struct LDKThirtyTwoBytes payment_hash;
+   bool rejected_by_dest;
+} LDKEvent_LDKPaymentFailed_Body;
+
+typedef struct LDKEvent_LDKPendingHTLCsForwardable_Body {
+   uint64_t time_forwardable;
+} LDKEvent_LDKPendingHTLCsForwardable_Body;
+
+typedef struct LDKEvent_LDKSpendableOutputs_Body {
+   struct LDKCVec_SpendableOutputDescriptorZ outputs;
+} LDKEvent_LDKSpendableOutputs_Body;
+
+typedef struct MUST_USE_STRUCT LDKEvent {
+   LDKEvent_Tag tag;
+   union {
+      LDKEvent_LDKFundingGenerationReady_Body funding_generation_ready;
+      LDKEvent_LDKFundingBroadcastSafe_Body funding_broadcast_safe;
+      LDKEvent_LDKPaymentReceived_Body payment_received;
+      LDKEvent_LDKPaymentSent_Body payment_sent;
+      LDKEvent_LDKPaymentFailed_Body payment_failed;
+      LDKEvent_LDKPendingHTLCsForwardable_Body pending_htl_cs_forwardable;
+      LDKEvent_LDKSpendableOutputs_Body spendable_outputs;
+   };
+} LDKEvent;
+
+typedef struct LDKCVec_EventZ {
+   struct LDKEvent *data;
+   uintptr_t datalen;
+} LDKCVec_EventZ;
+
+typedef union LDKCResult_OutPointDecodeErrorZPtr {
+   struct LDKOutPoint *result;
+   struct LDKDecodeError *err;
+} LDKCResult_OutPointDecodeErrorZPtr;
+
+typedef struct LDKCResult_OutPointDecodeErrorZ {
+   union LDKCResult_OutPointDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_OutPointDecodeErrorZ;
 
 
 
@@ -1707,396 +1879,431 @@ typedef struct MUST_USE_STRUCT LDKChannelMonitorUpdate {
    bool is_owned;
 } LDKChannelMonitorUpdate;
 
+typedef union LDKCResult_ChannelMonitorUpdateDecodeErrorZPtr {
+   struct LDKChannelMonitorUpdate *result;
+   struct LDKDecodeError *err;
+} LDKCResult_ChannelMonitorUpdateDecodeErrorZPtr;
 
+typedef struct LDKCResult_ChannelMonitorUpdateDecodeErrorZ {
+   union LDKCResult_ChannelMonitorUpdateDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_ChannelMonitorUpdateDecodeErrorZ;
 
-/**
- * An event to be processed by the ChannelManager.
- */
-typedef struct MUST_USE_STRUCT LDKMonitorEvent {
+typedef union LDKCResult_HTLCUpdateDecodeErrorZPtr {
+   struct LDKHTLCUpdate *result;
+   struct LDKDecodeError *err;
+} LDKCResult_HTLCUpdateDecodeErrorZPtr;
+
+typedef struct LDKCResult_HTLCUpdateDecodeErrorZ {
+   union LDKCResult_HTLCUpdateDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_HTLCUpdateDecodeErrorZ;
+
+
+
+/**
+ * General Err type for ChannelMonitor actions. Generally, this implies that the data provided is
+ * inconsistent with the ChannelMonitor being called. eg for ChannelMonitor::update_monitor this
+ * means you tried to update a monitor for a different channel or the ChannelMonitorUpdate was
+ * corrupted.
+ * Contains a developer-readable error message.
+ */
+typedef struct MUST_USE_STRUCT LDKMonitorUpdateError {
    /**
     * Nearly everywhere, inner must be non-null, however in places where
     * the Rust equivalent takes an Option, it may be set to null to indicate None.
     */
-   LDKnativeMonitorEvent *inner;
+   LDKnativeMonitorUpdateError *inner;
    bool is_owned;
-} LDKMonitorEvent;
+} LDKMonitorUpdateError;
+
+typedef union LDKCResult_NoneMonitorUpdateErrorZPtr {
+   /**
+    * Note that this value is always NULL, as there are no contents in the OK variant
+    */
+   void *result;
+   struct LDKMonitorUpdateError *err;
+} LDKCResult_NoneMonitorUpdateErrorZPtr;
+
+typedef struct LDKCResult_NoneMonitorUpdateErrorZ {
+   union LDKCResult_NoneMonitorUpdateErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_NoneMonitorUpdateErrorZ;
+
+typedef struct LDKC2Tuple_OutPointScriptZ {
+   struct LDKOutPoint a;
+   struct LDKCVec_u8Z b;
+} LDKC2Tuple_OutPointScriptZ;
+
+typedef struct LDKCVec_TransactionZ {
+   struct LDKTransaction *data;
+   uintptr_t datalen;
+} LDKCVec_TransactionZ;
+
+typedef struct LDKC2Tuple_u32TxOutZ {
+   uint32_t a;
+   struct LDKTxOut b;
+} LDKC2Tuple_u32TxOutZ;
+
+typedef struct LDKCVec_C2Tuple_u32TxOutZZ {
+   struct LDKC2Tuple_u32TxOutZ *data;
+   uintptr_t datalen;
+} LDKCVec_C2Tuple_u32TxOutZZ;
+
+typedef struct LDKC2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ {
+   struct LDKThirtyTwoBytes a;
+   struct LDKCVec_C2Tuple_u32TxOutZZ b;
+} LDKC2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ;
 
-typedef struct LDKCVecTempl_MonitorEvent {
-   LDKMonitorEvent *data;
+typedef struct LDKCVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ {
+   struct LDKC2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ *data;
    uintptr_t datalen;
-} LDKCVecTempl_MonitorEvent;
+} LDKCVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ;
+
+typedef struct LDKC2Tuple_SignatureCVec_SignatureZZ {
+   struct LDKSignature a;
+   struct LDKCVec_SignatureZ b;
+} LDKC2Tuple_SignatureCVec_SignatureZZ;
+
+typedef union LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZPtr {
+   struct LDKC2Tuple_SignatureCVec_SignatureZZ *result;
+   /**
+    * Note that this value is always NULL, as there are no contents in the Err variant
+    */
+   void *err;
+} LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZPtr;
+
+typedef struct LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ {
+   union LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZPtr contents;
+   bool result_ok;
+} LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ;
+
+typedef union LDKCResult_SignatureNoneZPtr {
+   struct LDKSignature *result;
+   /**
+    * Note that this value is always NULL, as there are no contents in the Err variant
+    */
+   void *err;
+} LDKCResult_SignatureNoneZPtr;
+
+typedef struct LDKCResult_SignatureNoneZ {
+   union LDKCResult_SignatureNoneZPtr contents;
+   bool result_ok;
+} LDKCResult_SignatureNoneZ;
+
 
-typedef LDKCVecTempl_MonitorEvent LDKCVec_MonitorEventZ;
 
 /**
- * The `Watch` trait defines behavior for watching on-chain activity pertaining to channels as
- * blocks are connected and disconnected.
- *
- * Each channel is associated with a [`ChannelMonitor`]. Implementations of this trait are
- * responsible for maintaining a set of monitors such that they can be updated accordingly as
- * channel state changes and HTLCs are resolved. See method documentation for specific
- * requirements.
+ * The unsigned part of a channel_announcement
+ */
+typedef struct MUST_USE_STRUCT LDKUnsignedChannelAnnouncement {
+   /**
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
+    */
+   LDKnativeUnsignedChannelAnnouncement *inner;
+   bool is_owned;
+} LDKUnsignedChannelAnnouncement;
+
+/**
+ * A trait to sign lightning channel transactions as described in BOLT 3.
  *
- * Implementations **must** ensure that updates are successfully applied and persisted upon method
- * completion. If an update fails with a [`PermanentFailure`], then it must immediately shut down
- * without taking any further action such as persisting the current state.
+ * Signing services could be implemented on a hardware wallet. In this case,
+ * the current Sign would be a front-end on top of a communication
+ * channel connected to your secure device and lightning key material wouldn't
+ * reside on a hot server. Nevertheless, a this deployment would still need
+ * to trust the ChannelManager to avoid loss of funds as this latest component
+ * could ask to sign commitment transaction with HTLCs paying to attacker pubkeys.
  *
- * If an implementation maintains multiple instances of a channel's monitor (e.g., by storing
- * backup copies), then it must ensure that updates are applied across all instances. Otherwise, it
- * could result in a revoked transaction being broadcast, allowing the counterparty to claim all
- * funds in the channel. See [`ChannelMonitorUpdateErr`] for more details about how to handle
- * multiple instances.
+ * A more secure iteration would be to use hashlock (or payment points) to pair
+ * invoice/incoming HTLCs with outgoing HTLCs to implement a no-trust-ChannelManager
+ * at the price of more state and computation on the hardware wallet side. In the future,
+ * we are looking forward to design such interface.
  *
- * [`ChannelMonitor`]: channelmonitor/struct.ChannelMonitor.html
- * [`ChannelMonitorUpdateErr`]: channelmonitor/enum.ChannelMonitorUpdateErr.html
- * [`PermanentFailure`]: channelmonitor/enum.ChannelMonitorUpdateErr.html#variant.PermanentFailure
+ * In any case, ChannelMonitor or fallback watchtowers are always going to be trusted
+ * to act, as liveness and breach reply correctness are always going to be hard requirements
+ * of LN security model, orthogonal of key management issues.
  */
-typedef struct LDKWatch {
+typedef struct LDKSign {
    void *this_arg;
    /**
-    * Watches a channel identified by `funding_txo` using `monitor`.
-    *
-    * Implementations are responsible for watching the chain for the funding transaction along
-    * with any spends of outputs returned by [`get_outputs_to_watch`]. In practice, this means
-    * calling [`block_connected`] and [`block_disconnected`] on the monitor.
+    * Gets the per-commitment point for a specific commitment number
     *
-    * [`get_outputs_to_watch`]: channelmonitor/struct.ChannelMonitor.html#method.get_outputs_to_watch
-    * [`block_connected`]: channelmonitor/struct.ChannelMonitor.html#method.block_connected
-    * [`block_disconnected`]: channelmonitor/struct.ChannelMonitor.html#method.block_disconnected
+    * Note that the commitment number starts at (1 << 48) - 1 and counts backwards.
     */
-   LDKCResult_NoneChannelMonitorUpdateErrZ (*watch_channel)(const void *this_arg, LDKOutPoint funding_txo, LDKChannelMonitor monitor);
+   struct LDKPublicKey (*get_per_commitment_point)(const void *this_arg, uint64_t idx);
    /**
-    * Updates a channel identified by `funding_txo` by applying `update` to its monitor.
+    * Gets the commitment secret for a specific commitment number as part of the revocation process
     *
-    * Implementations must call [`update_monitor`] with the given update. See
-    * [`ChannelMonitorUpdateErr`] for invariants around returning an error.
+    * An external signer implementation should error here if the commitment was already signed
+    * and should refuse to sign it in the future.
     *
-    * [`update_monitor`]: channelmonitor/struct.ChannelMonitor.html#method.update_monitor
-    * [`ChannelMonitorUpdateErr`]: channelmonitor/enum.ChannelMonitorUpdateErr.html
+    * May be called more than once for the same index.
+    *
+    * Note that the commitment number starts at (1 << 48) - 1 and counts backwards.
     */
-   LDKCResult_NoneChannelMonitorUpdateErrZ (*update_channel)(const void *this_arg, LDKOutPoint funding_txo, LDKChannelMonitorUpdate update);
+   struct LDKThirtyTwoBytes (*release_commitment_secret)(const void *this_arg, uint64_t idx);
    /**
-    * Returns any monitor events since the last call. Subsequent calls must only return new
-    * events.
+    * Gets the holder's channel public keys and basepoints
     */
-   LDKCVec_MonitorEventZ (*release_pending_monitor_events)(const void *this_arg);
-   void (*free)(void *this_arg);
-} LDKWatch;
-
-/**
- * The `Filter` trait defines behavior for indicating chain activity of interest pertaining to
- * channels.
- *
- * This is useful in order to have a [`Watch`] implementation convey to a chain source which
- * transactions to be notified of. Notification may take the form of pre-filtering blocks or, in
- * the case of [BIP 157]/[BIP 158], only fetching a block if the compact filter matches. If
- * receiving full blocks from a chain source, any further filtering is unnecessary.
- *
- * After an output has been registered, subsequent block retrievals from the chain source must not
- * exclude any transactions matching the new criteria nor any in-block descendants of such
- * transactions.
- *
- * Note that use as part of a [`Watch`] implementation involves reentrancy. Therefore, the `Filter`
- * should not block on I/O. Implementations should instead queue the newly monitored data to be
- * processed later. Then, in order to block until the data has been processed, any `Watch`
- * invocation that has called the `Filter` must return [`TemporaryFailure`].
- *
- * [`Watch`]: trait.Watch.html
- * [`TemporaryFailure`]: channelmonitor/enum.ChannelMonitorUpdateErr.html#variant.TemporaryFailure
- * [BIP 157]: https://github.com/bitcoin/bips/blob/master/bip-0157.mediawiki
- * [BIP 158]: https://github.com/bitcoin/bips/blob/master/bip-0158.mediawiki
- */
-typedef struct LDKFilter {
-   void *this_arg;
+   struct LDKChannelPublicKeys pubkeys;
    /**
-    * Registers interest in a transaction with `txid` and having an output with `script_pubkey` as
-    * a spending condition.
+    * Fill in the pubkeys field as a reference to it will be given to Rust after this returns
+    * Note that this takes a pointer to this object, not the this_ptr like other methods do
+    * This function pointer may be NULL if pubkeys is filled in when this object is created and never needs updating.
     */
-   void (*register_tx)(const void *this_arg, const uint8_t (*txid)[32], LDKu8slice script_pubkey);
+   void (*set_pubkeys)(const struct LDKSign*NONNULL_PTR );
    /**
-    * Registers interest in spends of a transaction output identified by `outpoint` having
-    * `script_pubkey` as the spending condition.
+    * Gets an arbitrary identifier describing the set of keys which are provided back to you in
+    * some SpendableOutputDescriptor types. This should be sufficient to identify this
+    * Sign object uniquely and lookup or re-derive its keys.
     */
-   void (*register_output)(const void *this_arg, const LDKOutPoint *outpoint, LDKu8slice script_pubkey);
-   void (*free)(void *this_arg);
-} LDKFilter;
-
-/**
- * An interface to send a transaction to the Bitcoin network.
- */
-typedef struct LDKBroadcasterInterface {
-   void *this_arg;
+   struct LDKThirtyTwoBytes (*channel_keys_id)(const void *this_arg);
    /**
-    * Sends a transaction out to (hopefully) be mined.
+    * Create a signature for a counterparty's commitment transaction and associated HTLC transactions.
+    *
+    * Note that if signing fails or is rejected, the channel will be force-closed.
     */
-   void (*broadcast_transaction)(const void *this_arg, LDKTransaction tx);
-   void (*free)(void *this_arg);
-} LDKBroadcasterInterface;
-
-/**
- * A trait which should be implemented to provide feerate information on a number of time
- * horizons.
- *
- * Note that all of the functions implemented here *must* be reentrant-safe (obviously - they're
- * called from inside the library in response to chain events, P2P events, or timer events).
- */
-typedef struct LDKFeeEstimator {
-   void *this_arg;
+   struct LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ (*sign_counterparty_commitment)(const void *this_arg, const struct LDKCommitmentTransaction *NONNULL_PTR commitment_tx);
    /**
-    * Gets estimated satoshis of fee required per 1000 Weight-Units.
+    * Create a signatures for a holder's commitment transaction and its claiming HTLC transactions.
+    * This will only ever be called with a non-revoked commitment_tx.  This will be called with the
+    * latest commitment_tx when we initiate a force-close.
+    * This will be called with the previous latest, just to get claiming HTLC signatures, if we are
+    * reacting to a ChannelMonitor replica that decided to broadcast before it had been updated to
+    * the latest.
+    * This may be called multiple times for the same transaction.
     *
-    * Must be no smaller than 253 (ie 1 satoshi-per-byte rounded up to ensure later round-downs
-    * don't put us below 1 satoshi-per-byte).
+    * An external signer implementation should check that the commitment has not been revoked.
     *
-    * This translates to:
-    *  * satoshis-per-byte * 250
-    *  * ceil(satoshis-per-kbyte / 4)
+    * May return Err if key derivation fails.  Callers, such as ChannelMonitor, will panic in such a case.
     */
-   uint32_t (*get_est_sat_per_1000_weight)(const void *this_arg, LDKConfirmationTarget confirmation_target);
-   void (*free)(void *this_arg);
-} LDKFeeEstimator;
-
-/**
- * `Persist` defines behavior for persisting channel monitors: this could mean
- * writing once to disk, and/or uploading to one or more backup services.
- *
- * Note that for every new monitor, you **must** persist the new `ChannelMonitor`
- * to disk/backups. And, on every update, you **must** persist either the
- * `ChannelMonitorUpdate` or the updated monitor itself. Otherwise, there is risk
- * of situations such as revoking a transaction, then crashing before this
- * revocation can be persisted, then unintentionally broadcasting a revoked
- * transaction and losing money. This is a risk because previous channel states
- * are toxic, so it's important that whatever channel state is persisted is
- * kept up-to-date.
- */
-typedef struct LDKPersist {
-   void *this_arg;
+   struct LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ (*sign_holder_commitment_and_htlcs)(const void *this_arg, const struct LDKHolderCommitmentTransaction *NONNULL_PTR commitment_tx);
    /**
-    * Persist a new channel's data. The data can be stored any way you want, but
-    * the identifier provided by Rust-Lightning is the channel's outpoint (and
-    * it is up to you to maintain a correct mapping between the outpoint and the
-    * stored channel data). Note that you **must** persist every new monitor to
-    * disk. See the `Persist` trait documentation for more details.
+    * Create a signature for the given input in a transaction spending an HTLC or commitment
+    * transaction output when our counterparty broadcasts an old state.
     *
-    * See [`ChannelMonitor::serialize_for_disk`] for writing out a `ChannelMonitor`,
-    * and [`ChannelMonitorUpdateErr`] for requirements when returning errors.
+    * A justice transaction may claim multiples outputs at the same time if timelocks are
+    * similar, but only a signature for the input at index `input` should be signed for here.
+    * It may be called multiples time for same output(s) if a fee-bump is needed with regards
+    * to an upcoming timelock expiration.
     *
-    * [`ChannelMonitor::serialize_for_disk`]: struct.ChannelMonitor.html#method.serialize_for_disk
-    * [`ChannelMonitorUpdateErr`]: enum.ChannelMonitorUpdateErr.html
+    * Amount is value of the output spent by this input, committed to in the BIP 143 signature.
+    *
+    * per_commitment_key is revocation secret which was provided by our counterparty when they
+    * revoked the state which they eventually broadcast. It's not a _holder_ secret key and does
+    * not allow the spending of any funds by itself (you need our holder revocation_secret to do
+    * so).
+    *
+    * htlc holds HTLC elements (hash, timelock) if the output being spent is a HTLC output, thus
+    * changing the format of the witness script (which is committed to in the BIP 143
+    * signatures).
     */
-   LDKCResult_NoneChannelMonitorUpdateErrZ (*persist_new_channel)(const void *this_arg, LDKOutPoint id, const LDKChannelMonitor *data);
+   struct LDKCResult_SignatureNoneZ (*sign_justice_transaction)(const void *this_arg, struct LDKTransaction justice_tx, uintptr_t input, uint64_t amount, const uint8_t (*per_commitment_key)[32], const struct LDKHTLCOutputInCommitment *NONNULL_PTR htlc);
    /**
-    * Update one channel's data. The provided `ChannelMonitor` has already
-    * applied the given update.
-    *
-    * Note that on every update, you **must** persist either the
-    * `ChannelMonitorUpdate` or the updated monitor itself to disk/backups. See
-    * the `Persist` trait documentation for more details.
+    * Create a signature for a claiming transaction for a HTLC output on a counterparty's commitment
+    * transaction, either offered or received.
     *
-    * If an implementer chooses to persist the updates only, they need to make
-    * sure that all the updates are applied to the `ChannelMonitors` *before*
-    * the set of channel monitors is given to the `ChannelManager`
-    * deserialization routine. See [`ChannelMonitor::update_monitor`] for
-    * applying a monitor update to a monitor. If full `ChannelMonitors` are
-    * persisted, then there is no need to persist individual updates.
+    * Such a transaction may claim multiples offered outputs at same time if we know the
+    * preimage for each when we create it, but only the input at index `input` should be
+    * signed for here. It may be called multiple times for same output(s) if a fee-bump is
+    * needed with regards to an upcoming timelock expiration.
     *
-    * Note that there could be a performance tradeoff between persisting complete
-    * channel monitors on every update vs. persisting only updates and applying
-    * them in batches. The size of each monitor grows `O(number of state updates)`
-    * whereas updates are small and `O(1)`.
+    * Witness_script is either a offered or received script as defined in BOLT3 for HTLC
+    * outputs.
     *
-    * See [`ChannelMonitor::serialize_for_disk`] for writing out a `ChannelMonitor`,
-    * [`ChannelMonitorUpdate::write`] for writing out an update, and
-    * [`ChannelMonitorUpdateErr`] for requirements when returning errors.
+    * Amount is value of the output spent by this input, committed to in the BIP 143 signature.
     *
-    * [`ChannelMonitor::update_monitor`]: struct.ChannelMonitor.html#impl-1
-    * [`ChannelMonitor::serialize_for_disk`]: struct.ChannelMonitor.html#method.serialize_for_disk
-    * [`ChannelMonitorUpdate::write`]: struct.ChannelMonitorUpdate.html#method.write
-    * [`ChannelMonitorUpdateErr`]: enum.ChannelMonitorUpdateErr.html
+    * Per_commitment_point is the dynamic point corresponding to the channel state
+    * detected onchain. It has been generated by our counterparty and is used to derive
+    * channel state keys, which are then included in the witness script and committed to in the
+    * BIP 143 signature.
     */
-   LDKCResult_NoneChannelMonitorUpdateErrZ (*update_persisted_channel)(const void *this_arg, LDKOutPoint id, const LDKChannelMonitorUpdate *update, const LDKChannelMonitor *data);
-   void (*free)(void *this_arg);
-} LDKPersist;
+   struct LDKCResult_SignatureNoneZ (*sign_counterparty_htlc_transaction)(const void *this_arg, struct LDKTransaction htlc_tx, uintptr_t input, uint64_t amount, struct LDKPublicKey per_commitment_point, const struct LDKHTLCOutputInCommitment *NONNULL_PTR htlc);
+   /**
+    * Create a signature for a (proposed) closing transaction.
+    *
+    * Note that, due to rounding, there may be one \"missing\" satoshi, and either party may have
+    * chosen to forgo their output as dust.
+    */
+   struct LDKCResult_SignatureNoneZ (*sign_closing_transaction)(const void *this_arg, struct LDKTransaction closing_tx);
+   /**
+    * Signs a channel announcement message with our funding key, proving it comes from one
+    * of the channel participants.
+    *
+    * Note that if this fails or is rejected, the channel will not be publicly announced and
+    * our counterparty may (though likely will not) close the channel on us for violating the
+    * protocol.
+    */
+   struct LDKCResult_SignatureNoneZ (*sign_channel_announcement)(const void *this_arg, const struct LDKUnsignedChannelAnnouncement *NONNULL_PTR msg);
+   /**
+    * Set the counterparty static channel data, including basepoints,
+    * counterparty_selected/holder_selected_contest_delay and funding outpoint.
+    * This is done as soon as the funding outpoint is known.  Since these are static channel data,
+    * they MUST NOT be allowed to change to different values once set.
+    *
+    * channel_parameters.is_populated() MUST be true.
+    *
+    * We bind holder_selected_contest_delay late here for API convenience.
+    *
+    * Will be called before any signatures are applied.
+    */
+   void (*ready_channel)(void *this_arg, const struct LDKChannelTransactionParameters *NONNULL_PTR channel_parameters);
+   void *(*clone)(const void *this_arg);
+   struct LDKCVec_u8Z (*write)(const void *this_arg);
+   void (*free)(void *this_arg);
+} LDKSign;
 
 
 
 /**
- * An implementation of [`chain::Watch`] for monitoring channels.
+ * A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
+ * on-chain transactions to ensure no loss of funds occurs.
  *
- * Connected and disconnected blocks must be provided to `ChainMonitor` as documented by
- * [`chain::Watch`]. May be used in conjunction with [`ChannelManager`] to monitor channels locally
- * or used independently to monitor channels remotely. See the [module-level documentation] for
- * details.
+ * You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
+ * information and are actively monitoring the chain.
  *
- * [`chain::Watch`]: ../trait.Watch.html
- * [`ChannelManager`]: ../../ln/channelmanager/struct.ChannelManager.html
- * [module-level documentation]: index.html
+ * Pending Events or updated HTLCs which have not yet been read out by
+ * get_and_clear_pending_monitor_events or get_and_clear_pending_events are serialized to disk and
+ * reloaded at deserialize-time. Thus, you must ensure that, when handling events, all events
+ * gotten are fully handled before re-serializing the new state.
+ *
+ * Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
+ * tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
+ * the \"reorg path\" (ie disconnecting blocks until you find a common ancestor from both the
+ * returned block hash and the the current chain and then reconnecting blocks to get to the
+ * best chain) upon deserializing the object!
  */
-typedef struct MUST_USE_STRUCT LDKChainMonitor {
+typedef struct MUST_USE_STRUCT LDKChannelMonitor {
    /**
     * Nearly everywhere, inner must be non-null, however in places where
     * the Rust equivalent takes an Option, it may be set to null to indicate None.
     */
-   LDKnativeChainMonitor *inner;
+   LDKnativeChannelMonitor *inner;
    bool is_owned;
-} LDKChainMonitor;
+} LDKChannelMonitor;
 
-typedef struct LDKCVecTempl_C2TupleTempl_usize__Transaction {
-   LDKC2TupleTempl_usize__Transaction *data;
-   uintptr_t datalen;
-} LDKCVecTempl_C2TupleTempl_usize__Transaction;
+typedef struct LDKC2Tuple_BlockHashChannelMonitorZ {
+   struct LDKThirtyTwoBytes a;
+   struct LDKChannelMonitor b;
+} LDKC2Tuple_BlockHashChannelMonitorZ;
 
-typedef LDKCVecTempl_C2TupleTempl_usize__Transaction LDKCVec_C2Tuple_usizeTransactionZZ;
+typedef union LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZPtr {
+   struct LDKC2Tuple_BlockHashChannelMonitorZ *result;
+   struct LDKDecodeError *err;
+} LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZPtr;
 
+typedef struct LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ {
+   union LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ;
+
+typedef union LDKCResult_TxOutAccessErrorZPtr {
+   struct LDKTxOut *result;
+   enum LDKAccessError *err;
+} LDKCResult_TxOutAccessErrorZPtr;
 
+typedef struct LDKCResult_TxOutAccessErrorZ {
+   union LDKCResult_TxOutAccessErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_TxOutAccessErrorZ;
 
 /**
- * Simple structure sent back by `chain::Watch` when an HTLC from a forward channel is detected on
- * chain. Used to update the corresponding HTLC in the backward channel. Failing to pass the
- * preimage claim backward will lead to loss of funds.
- *
- * [`chain::Watch`]: ../trait.Watch.html
+ * A Rust str object, ie a reference to a UTF8-valid string.
+ * This is *not* null-terminated so cannot be used directly as a C string!
  */
-typedef struct MUST_USE_STRUCT LDKHTLCUpdate {
-   /**
-    * Nearly everywhere, inner must be non-null, however in places where
-    * the Rust equivalent takes an Option, it may be set to null to indicate None.
-    */
-   LDKnativeHTLCUpdate *inner;
-   bool is_owned;
-} LDKHTLCUpdate;
-
-typedef struct LDKCVecTempl_Transaction {
-   LDKTransaction *data;
-   uintptr_t datalen;
-} LDKCVecTempl_Transaction;
-
-typedef LDKCVecTempl_Transaction LDKCVec_TransactionZ;
-
-typedef struct LDKCVecTempl_C2TupleTempl_ThirtyTwoBytes__CVecTempl_C2TupleTempl_u32__TxOut {
-   LDKC2TupleTempl_ThirtyTwoBytes__CVecTempl_C2TupleTempl_u32__TxOut *data;
-   uintptr_t datalen;
-} LDKCVecTempl_C2TupleTempl_ThirtyTwoBytes__CVecTempl_C2TupleTempl_u32__TxOut;
-
-typedef LDKCVecTempl_C2TupleTempl_ThirtyTwoBytes__CVecTempl_C2TupleTempl_u32__TxOut LDKCVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ;
-
-typedef struct LDKSecretKey {
-   uint8_t bytes[32];
-} LDKSecretKey;
+typedef struct LDKStr {
+   const uint8_t *chars;
+   uintptr_t len;
+} LDKStr;
 
 /**
- * A trait to describe an object which can get user secrets and key material.
+ * Indicates an error on the client's part (usually some variant of attempting to use too-low or
+ * too-high values)
  */
-typedef struct LDKKeysInterface {
-   void *this_arg;
+typedef enum LDKAPIError_Tag {
+   /**
+    * Indicates the API was wholly misused (see err for more). Cases where these can be returned
+    * are documented, but generally indicates some precondition of a function was violated.
+    */
+   LDKAPIError_APIMisuseError,
    /**
-    * Get node secret key (aka node_id or network_key)
+    * Due to a high feerate, we were unable to complete the request.
+    * For example, this may be returned if the feerate implies we cannot open a channel at the
+    * requested value, but opening a larger channel would succeed.
     */
-   LDKSecretKey (*get_node_secret)(const void *this_arg);
+   LDKAPIError_FeeRateTooHigh,
    /**
-    * Get destination redeemScript to encumber static protocol exit points.
+    * A malformed Route was provided (eg overflowed value, node id mismatch, overly-looped route,
+    * too-many-hops, etc).
     */
-   LDKCVec_u8Z (*get_destination_script)(const void *this_arg);
+   LDKAPIError_RouteError,
    /**
-    * Get shutdown_pubkey to use as PublicKey at channel closure
+    * We were unable to complete the request as the Channel required to do so is unable to
+    * complete the request (or was not found). This can take many forms, including disconnected
+    * peer, channel at capacity, channel shutting down, etc.
     */
-   LDKPublicKey (*get_shutdown_pubkey)(const void *this_arg);
+   LDKAPIError_ChannelUnavailable,
    /**
-    * Get a new set of ChannelKeys for per-channel secrets. These MUST be unique even if you
-    * restarted with some stale data!
+    * An attempt to call watch/update_channel returned an Err (ie you did this!), causing the
+    * attempted action to fail.
     */
-   LDKChannelKeys (*get_channel_keys)(const void *this_arg, bool inbound, uint64_t channel_value_satoshis);
+   LDKAPIError_MonitorUpdateFailed,
    /**
-    * Gets a unique, cryptographically-secure, random 32 byte value. This is used for encrypting
-    * onion packets and for temporary channel IDs. There is no requirement that these be
-    * persisted anywhere, though they must be unique across restarts.
+    * Must be last for serialization purposes
     */
-   LDKThirtyTwoBytes (*get_secure_random_bytes)(const void *this_arg);
-   void (*free)(void *this_arg);
-} LDKKeysInterface;
+   LDKAPIError_Sentinel,
+} LDKAPIError_Tag;
 
+typedef struct LDKAPIError_LDKAPIMisuseError_Body {
+   struct LDKCVec_u8Z err;
+} LDKAPIError_LDKAPIMisuseError_Body;
 
+typedef struct LDKAPIError_LDKFeeRateTooHigh_Body {
+   struct LDKCVec_u8Z err;
+   uint32_t feerate;
+} LDKAPIError_LDKFeeRateTooHigh_Body;
 
-/**
- * A simple implementation of ChannelKeys that just keeps the private keys in memory.
- */
-typedef struct MUST_USE_STRUCT LDKInMemoryChannelKeys {
-   /**
-    * Nearly everywhere, inner must be non-null, however in places where
-    * the Rust equivalent takes an Option, it may be set to null to indicate None.
-    */
-   LDKnativeInMemoryChannelKeys *inner;
-   bool is_owned;
-} LDKInMemoryChannelKeys;
+typedef struct LDKAPIError_LDKRouteError_Body {
+   struct LDKStr err;
+} LDKAPIError_LDKRouteError_Body;
 
+typedef struct LDKAPIError_LDKChannelUnavailable_Body {
+   struct LDKCVec_u8Z err;
+} LDKAPIError_LDKChannelUnavailable_Body;
 
+typedef struct MUST_USE_STRUCT LDKAPIError {
+   LDKAPIError_Tag tag;
+   union {
+      LDKAPIError_LDKAPIMisuseError_Body api_misuse_error;
+      LDKAPIError_LDKFeeRateTooHigh_Body fee_rate_too_high;
+      LDKAPIError_LDKRouteError_Body route_error;
+      LDKAPIError_LDKChannelUnavailable_Body channel_unavailable;
+   };
+} LDKAPIError;
 
-/**
- * Simple KeysInterface implementor that takes a 32-byte seed for use as a BIP 32 extended key
- * and derives keys from that.
- *
- * Your node_id is seed/0'
- * ChannelMonitor closes may use seed/1'
- * Cooperative closes may use seed/2'
- * The two close keys may be needed to claim on-chain funds!
- */
-typedef struct MUST_USE_STRUCT LDKKeysManager {
+typedef union LDKCResult_NoneAPIErrorZPtr {
    /**
-    * Nearly everywhere, inner must be non-null, however in places where
-    * the Rust equivalent takes an Option, it may be set to null to indicate None.
+    * Note that this value is always NULL, as there are no contents in the OK variant
     */
-   LDKnativeKeysManager *inner;
-   bool is_owned;
-} LDKKeysManager;
+   void *result;
+   struct LDKAPIError *err;
+} LDKCResult_NoneAPIErrorZPtr;
 
+typedef struct LDKCResult_NoneAPIErrorZ {
+   union LDKCResult_NoneAPIErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_NoneAPIErrorZ;
 
+typedef struct LDKCVec_CResult_NoneAPIErrorZZ {
+   struct LDKCResult_NoneAPIErrorZ *data;
+   uintptr_t datalen;
+} LDKCVec_CResult_NoneAPIErrorZZ;
 
-/**
- * Manager which keeps track of a number of channels and sends messages to the appropriate
- * channel, also tracking HTLC preimages and forwarding onion packets appropriately.
- *
- * Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
- * to individual Channels.
- *
- * Implements Writeable to write out all channel state to disk. Implies peer_disconnected() for
- * all peers during write/read (though does not modify this instance, only the instance being
- * serialized). This will result in any channels which have not yet exchanged funding_created (ie
- * called funding_transaction_generated for outbound channels).
- *
- * Note that you can be a bit lazier about writing out ChannelManager than you can be with
- * ChannelMonitors. With ChannelMonitors you MUST write each monitor update out to disk before
- * returning from chain::Watch::watch_/update_channel, with ChannelManagers, writing updates
- * happens out-of-band (and will prevent any other ChannelManager operations from occurring during
- * the serialization process). If the deserialized version is out-of-date compared to the
- * ChannelMonitors passed by reference to read(), those channels will be force-closed based on the
- * ChannelMonitor state and no funds will be lost (mod on-chain transaction fees).
- *
- * Note that the deserializer is only implemented for (Sha256dHash, ChannelManager), which
- * tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
- * the \"reorg path\" (ie call block_disconnected() until you get to a common block and then call
- * block_connected() to step towards your best block) upon deserialization before using the
- * object!
- *
- * Note that ChannelManager is responsible for tracking liveness of its channels and generating
- * ChannelUpdate messages informing peers that the channel is temporarily disabled. To avoid
- * spam due to quick disconnection/reconnection, updates are not sent until the channel has been
- * offline for a full minute. In order to track this, you must call
- * timer_chan_freshness_every_min roughly once per minute, though it doesn't have to be perfect.
- *
- * Rather than using a plain ChannelManager, it is preferable to use either a SimpleArcChannelManager
- * a SimpleRefChannelManager, for conciseness. See their documentation for more details, but
- * essentially you should default to using a SimpleRefChannelManager, and use a
- * SimpleArcChannelManager when you require a ChannelManager with a static lifetime, such as when
- * you're using lightning-net-tokio.
- */
-typedef struct MUST_USE_STRUCT LDKChannelManager {
-   /**
-    * Nearly everywhere, inner must be non-null, however in places where
-    * the Rust equivalent takes an Option, it may be set to null to indicate None.
-    */
-   LDKnativeChannelManager *inner;
-   bool is_owned;
-} LDKChannelManager;
+typedef struct LDKCVec_APIErrorZ {
+   struct LDKAPIError *data;
+   uintptr_t datalen;
+} LDKCVec_APIErrorZ;
 
 
 
@@ -2112,1250 +2319,2415 @@ typedef struct MUST_USE_STRUCT LDKChannelDetails {
    bool is_owned;
 } LDKChannelDetails;
 
-
+typedef struct LDKCVec_ChannelDetailsZ {
+   struct LDKChannelDetails *data;
+   uintptr_t datalen;
+} LDKCVec_ChannelDetailsZ;
 
 /**
- * Features used within an `init` message.
+ * If a payment fails to send, it can be in one of several states. This enum is returned as the
+ * Err() type describing which state the payment is in, see the description of individual enum
+ * states for more.
  */
-typedef struct MUST_USE_STRUCT LDKInitFeatures {
+typedef enum LDKPaymentSendFailure_Tag {
    /**
-    * Nearly everywhere, inner must be non-null, however in places where
-    * the Rust equivalent takes an Option, it may be set to null to indicate None.
+    * A parameter which was passed to send_payment was invalid, preventing us from attempting to
+    * send the payment at all. No channel state has been changed or messages sent to peers, and
+    * once you've changed the parameter at error, you can freely retry the payment in full.
     */
-   LDKnativeInitFeatures *inner;
-   bool is_owned;
-} LDKInitFeatures;
-
-typedef struct LDKCVecTempl_ChannelDetails {
-   LDKChannelDetails *data;
-   uintptr_t datalen;
-} LDKCVecTempl_ChannelDetails;
-
-typedef LDKCVecTempl_ChannelDetails LDKCVec_ChannelDetailsZ;
-
+   LDKPaymentSendFailure_ParameterError,
+   /**
+    * A parameter in a single path which was passed to send_payment was invalid, preventing us
+    * from attempting to send the payment at all. No channel state has been changed or messages
+    * sent to peers, and once you've changed the parameter at error, you can freely retry the
+    * payment in full.
+    *
+    * The results here are ordered the same as the paths in the route object which was passed to
+    * send_payment.
+    */
+   LDKPaymentSendFailure_PathParameterError,
+   /**
+    * All paths which were attempted failed to send, with no channel state change taking place.
+    * You can freely retry the payment in full (though you probably want to do so over different
+    * paths than the ones selected).
+    */
+   LDKPaymentSendFailure_AllFailedRetrySafe,
+   /**
+    * Some paths which were attempted failed to send, though possibly not all. At least some
+    * paths have irrevocably committed to the HTLC and retrying the payment in full would result
+    * in over-/re-payment.
+    *
+    * The results here are ordered the same as the paths in the route object which was passed to
+    * send_payment, and any Errs which are not APIError::MonitorUpdateFailed can be safely
+    * retried (though there is currently no API with which to do so).
+    *
+    * Any entries which contain Err(APIError::MonitorUpdateFailed) or Ok(()) MUST NOT be retried
+    * as they will result in over-/re-payment. These HTLCs all either successfully sent (in the
+    * case of Ok(())) or will send once channel_monitor_updated is called on the next-hop channel
+    * with the latest update_id.
+    */
+   LDKPaymentSendFailure_PartialFailure,
+   /**
+    * Must be last for serialization purposes
+    */
+   LDKPaymentSendFailure_Sentinel,
+} LDKPaymentSendFailure_Tag;
 
+typedef struct MUST_USE_STRUCT LDKPaymentSendFailure {
+   LDKPaymentSendFailure_Tag tag;
+   union {
+      struct {
+         struct LDKAPIError parameter_error;
+      };
+      struct {
+         struct LDKCVec_CResult_NoneAPIErrorZZ path_parameter_error;
+      };
+      struct {
+         struct LDKCVec_APIErrorZ all_failed_retry_safe;
+      };
+      struct {
+         struct LDKCVec_CResult_NoneAPIErrorZZ partial_failure;
+      };
+   };
+} LDKPaymentSendFailure;
 
-/**
- * A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
- * it can take multiple paths. Each path is composed of one or more hops through the network.
- */
-typedef struct MUST_USE_STRUCT LDKRoute {
+typedef union LDKCResult_NonePaymentSendFailureZPtr {
    /**
-    * Nearly everywhere, inner must be non-null, however in places where
-    * the Rust equivalent takes an Option, it may be set to null to indicate None.
+    * Note that this value is always NULL, as there are no contents in the OK variant
     */
-   LDKnativeRoute *inner;
-   bool is_owned;
-} LDKRoute;
-
-typedef struct LDKThreeBytes {
-   uint8_t data[3];
-} LDKThreeBytes;
+   void *result;
+   struct LDKPaymentSendFailure *err;
+} LDKCResult_NonePaymentSendFailureZPtr;
 
-typedef struct LDKFourBytes {
-   uint8_t data[4];
-} LDKFourBytes;
+typedef struct LDKCResult_NonePaymentSendFailureZ {
+   union LDKCResult_NonePaymentSendFailureZPtr contents;
+   bool result_ok;
+} LDKCResult_NonePaymentSendFailureZ;
 
-typedef struct LDKSixteenBytes {
-   uint8_t data[16];
-} LDKSixteenBytes;
-
-typedef struct LDKTenBytes {
-   uint8_t data[10];
-} LDKTenBytes;
+typedef struct LDKCVec_ChannelMonitorZ {
+   struct LDKChannelMonitor *data;
+   uintptr_t datalen;
+} LDKCVec_ChannelMonitorZ;
 
 /**
- * An address which can be used to connect to a remote peer
+ * The `Watch` trait defines behavior for watching on-chain activity pertaining to channels as
+ * blocks are connected and disconnected.
+ *
+ * Each channel is associated with a [`ChannelMonitor`]. Implementations of this trait are
+ * responsible for maintaining a set of monitors such that they can be updated accordingly as
+ * channel state changes and HTLCs are resolved. See method documentation for specific
+ * requirements.
+ *
+ * Implementations **must** ensure that updates are successfully applied and persisted upon method
+ * completion. If an update fails with a [`PermanentFailure`], then it must immediately shut down
+ * without taking any further action such as persisting the current state.
+ *
+ * If an implementation maintains multiple instances of a channel's monitor (e.g., by storing
+ * backup copies), then it must ensure that updates are applied across all instances. Otherwise, it
+ * could result in a revoked transaction being broadcast, allowing the counterparty to claim all
+ * funds in the channel. See [`ChannelMonitorUpdateErr`] for more details about how to handle
+ * multiple instances.
+ *
+ * [`ChannelMonitor`]: channelmonitor/struct.ChannelMonitor.html
+ * [`ChannelMonitorUpdateErr`]: channelmonitor/enum.ChannelMonitorUpdateErr.html
+ * [`PermanentFailure`]: channelmonitor/enum.ChannelMonitorUpdateErr.html#variant.PermanentFailure
  */
-typedef enum LDKNetAddress_Tag {
-   /**
-    * An IPv4 address/port on which the peer is listening.
-    */
-   LDKNetAddress_IPv4,
+typedef struct LDKWatch {
+   void *this_arg;
    /**
-    * An IPv6 address/port on which the peer is listening.
+    * Watches a channel identified by `funding_txo` using `monitor`.
+    *
+    * Implementations are responsible for watching the chain for the funding transaction along
+    * with any spends of outputs returned by [`get_outputs_to_watch`]. In practice, this means
+    * calling [`block_connected`] and [`block_disconnected`] on the monitor.
+    *
+    * [`get_outputs_to_watch`]: channelmonitor/struct.ChannelMonitor.html#method.get_outputs_to_watch
+    * [`block_connected`]: channelmonitor/struct.ChannelMonitor.html#method.block_connected
+    * [`block_disconnected`]: channelmonitor/struct.ChannelMonitor.html#method.block_disconnected
     */
-   LDKNetAddress_IPv6,
+   struct LDKCResult_NoneChannelMonitorUpdateErrZ (*watch_channel)(const void *this_arg, struct LDKOutPoint funding_txo, struct LDKChannelMonitor monitor);
    /**
-    * An old-style Tor onion address/port on which the peer is listening.
+    * Updates a channel identified by `funding_txo` by applying `update` to its monitor.
+    *
+    * Implementations must call [`update_monitor`] with the given update. See
+    * [`ChannelMonitorUpdateErr`] for invariants around returning an error.
+    *
+    * [`update_monitor`]: channelmonitor/struct.ChannelMonitor.html#method.update_monitor
+    * [`ChannelMonitorUpdateErr`]: channelmonitor/enum.ChannelMonitorUpdateErr.html
     */
-   LDKNetAddress_OnionV2,
+   struct LDKCResult_NoneChannelMonitorUpdateErrZ (*update_channel)(const void *this_arg, struct LDKOutPoint funding_txo, struct LDKChannelMonitorUpdate update);
    /**
-    * A new-style Tor onion address/port on which the peer is listening.
-    * To create the human-readable \"hostname\", concatenate ed25519_pubkey, checksum, and version,
-    * wrap as base32 and append \".onion\".
+    * Returns any monitor events since the last call. Subsequent calls must only return new
+    * events.
     */
-   LDKNetAddress_OnionV3,
+   struct LDKCVec_MonitorEventZ (*release_pending_monitor_events)(const void *this_arg);
+   void (*free)(void *this_arg);
+} LDKWatch;
+
+/**
+ * An interface to send a transaction to the Bitcoin network.
+ */
+typedef struct LDKBroadcasterInterface {
+   void *this_arg;
    /**
-    * Must be last for serialization purposes
+    * Sends a transaction out to (hopefully) be mined.
     */
-   LDKNetAddress_Sentinel,
-} LDKNetAddress_Tag;
-
-typedef struct LDKNetAddress_LDKIPv4_Body {
-   LDKFourBytes addr;
-   uint16_t port;
-} LDKNetAddress_LDKIPv4_Body;
-
-typedef struct LDKNetAddress_LDKIPv6_Body {
-   LDKSixteenBytes addr;
-   uint16_t port;
-} LDKNetAddress_LDKIPv6_Body;
-
-typedef struct LDKNetAddress_LDKOnionV2_Body {
-   LDKTenBytes addr;
-   uint16_t port;
-} LDKNetAddress_LDKOnionV2_Body;
+   void (*broadcast_transaction)(const void *this_arg, struct LDKTransaction tx);
+   void (*free)(void *this_arg);
+} LDKBroadcasterInterface;
 
-typedef struct LDKNetAddress_LDKOnionV3_Body {
-   LDKThirtyTwoBytes ed25519_pubkey;
-   uint16_t checksum;
-   uint8_t version;
-   uint16_t port;
-} LDKNetAddress_LDKOnionV3_Body;
+typedef union LDKCResult_SignDecodeErrorZPtr {
+   struct LDKSign *result;
+   struct LDKDecodeError *err;
+} LDKCResult_SignDecodeErrorZPtr;
 
-typedef struct LDKNetAddress {
-   LDKNetAddress_Tag tag;
-   union {
-      LDKNetAddress_LDKIPv4_Body i_pv4;
-      LDKNetAddress_LDKIPv6_Body i_pv6;
-      LDKNetAddress_LDKOnionV2_Body onion_v2;
-      LDKNetAddress_LDKOnionV3_Body onion_v3;
-   };
-} LDKNetAddress;
+typedef struct LDKCResult_SignDecodeErrorZ {
+   union LDKCResult_SignDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_SignDecodeErrorZ;
 
-typedef struct LDKCVecTempl_NetAddress {
-   LDKNetAddress *data;
+typedef struct LDKu8slice {
+   const uint8_t *data;
    uintptr_t datalen;
-} LDKCVecTempl_NetAddress;
-
-typedef LDKCVecTempl_NetAddress LDKCVec_NetAddressZ;
-
-
+} LDKu8slice;
 
 /**
- * An update_add_htlc message to be sent or received from a peer
+ * A trait to describe an object which can get user secrets and key material.
  */
-typedef struct MUST_USE_STRUCT LDKUpdateAddHTLC {
+typedef struct LDKKeysInterface {
+   void *this_arg;
    /**
-    * Nearly everywhere, inner must be non-null, however in places where
-    * the Rust equivalent takes an Option, it may be set to null to indicate None.
+    * Get node secret key (aka node_id or network_key).
+    *
+    * This method must return the same value each time it is called.
     */
-   LDKnativeUpdateAddHTLC *inner;
-   bool is_owned;
-} LDKUpdateAddHTLC;
-
+   struct LDKSecretKey (*get_node_secret)(const void *this_arg);
+   /**
+    * Get a script pubkey which we send funds to when claiming on-chain contestable outputs.
+    *
+    * This method should return a different value each time it is called, to avoid linking
+    * on-chain funds across channels as controlled to the same user.
+    */
+   struct LDKCVec_u8Z (*get_destination_script)(const void *this_arg);
+   /**
+    * Get a public key which we will send funds to (in the form of a P2WPKH output) when closing
+    * a channel.
+    *
+    * This method should return a different value each time it is called, to avoid linking
+    * on-chain funds across channels as controlled to the same user.
+    */
+   struct LDKPublicKey (*get_shutdown_pubkey)(const void *this_arg);
+   /**
+    * Get a new set of Sign for per-channel secrets. These MUST be unique even if you
+    * restarted with some stale data!
+    *
+    * This method must return a different value each time it is called.
+    */
+   struct LDKSign (*get_channel_signer)(const void *this_arg, bool inbound, uint64_t channel_value_satoshis);
+   /**
+    * Gets a unique, cryptographically-secure, random 32 byte value. This is used for encrypting
+    * onion packets and for temporary channel IDs. There is no requirement that these be
+    * persisted anywhere, though they must be unique across restarts.
+    *
+    * This method must return a different value each time it is called.
+    */
+   struct LDKThirtyTwoBytes (*get_secure_random_bytes)(const void *this_arg);
+   /**
+    * Reads a `Signer` for this `KeysInterface` from the given input stream.
+    * This is only called during deserialization of other objects which contain
+    * `Sign`-implementing objects (ie `ChannelMonitor`s and `ChannelManager`s).
+    * The bytes are exactly those which `<Self::Signer as Writeable>::write()` writes, and
+    * contain no versioning scheme. You may wish to include your own version prefix and ensure
+    * you've read all of the provided bytes to ensure no corruption occurred.
+    */
+   struct LDKCResult_SignDecodeErrorZ (*read_chan_signer)(const void *this_arg, struct LDKu8slice reader);
+   void (*free)(void *this_arg);
+} LDKKeysInterface;
 
+/**
+ * A trait which should be implemented to provide feerate information on a number of time
+ * horizons.
+ *
+ * Note that all of the functions implemented here *must* be reentrant-safe (obviously - they're
+ * called from inside the library in response to chain events, P2P events, or timer events).
+ */
+typedef struct LDKFeeEstimator {
+   void *this_arg;
+   /**
+    * Gets estimated satoshis of fee required per 1000 Weight-Units.
+    *
+    * Must be no smaller than 253 (ie 1 satoshi-per-byte rounded up to ensure later round-downs
+    * don't put us below 1 satoshi-per-byte).
+    *
+    * This translates to:
+    *  * satoshis-per-byte * 250
+    *  * ceil(satoshis-per-kbyte / 4)
+    */
+   uint32_t (*get_est_sat_per_1000_weight)(const void *this_arg, enum LDKConfirmationTarget confirmation_target);
+   void (*free)(void *this_arg);
+} LDKFeeEstimator;
 
 /**
- * An update_fulfill_htlc message to be sent or received from a peer
+ * A trait encapsulating the operations required of a logger
  */
-typedef struct MUST_USE_STRUCT LDKUpdateFulfillHTLC {
+typedef struct LDKLogger {
+   void *this_arg;
    /**
-    * Nearly everywhere, inner must be non-null, however in places where
-    * the Rust equivalent takes an Option, it may be set to null to indicate None.
+    * Logs the `Record`
     */
-   LDKnativeUpdateFulfillHTLC *inner;
-   bool is_owned;
-} LDKUpdateFulfillHTLC;
+   void (*log)(const void *this_arg, const char *record);
+   void (*free)(void *this_arg);
+} LDKLogger;
 
 
 
 /**
- * An update_fail_htlc message to be sent or received from a peer
+ * Manager which keeps track of a number of channels and sends messages to the appropriate
+ * channel, also tracking HTLC preimages and forwarding onion packets appropriately.
+ *
+ * Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
+ * to individual Channels.
+ *
+ * Implements Writeable to write out all channel state to disk. Implies peer_disconnected() for
+ * all peers during write/read (though does not modify this instance, only the instance being
+ * serialized). This will result in any channels which have not yet exchanged funding_created (ie
+ * called funding_transaction_generated for outbound channels).
+ *
+ * Note that you can be a bit lazier about writing out ChannelManager than you can be with
+ * ChannelMonitors. With ChannelMonitors you MUST write each monitor update out to disk before
+ * returning from chain::Watch::watch_/update_channel, with ChannelManagers, writing updates
+ * happens out-of-band (and will prevent any other ChannelManager operations from occurring during
+ * the serialization process). If the deserialized version is out-of-date compared to the
+ * ChannelMonitors passed by reference to read(), those channels will be force-closed based on the
+ * ChannelMonitor state and no funds will be lost (mod on-chain transaction fees).
+ *
+ * Note that the deserializer is only implemented for (Sha256dHash, ChannelManager), which
+ * tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
+ * the \"reorg path\" (ie call block_disconnected() until you get to a common block and then call
+ * block_connected() to step towards your best block) upon deserialization before using the
+ * object!
+ *
+ * Note that ChannelManager is responsible for tracking liveness of its channels and generating
+ * ChannelUpdate messages informing peers that the channel is temporarily disabled. To avoid
+ * spam due to quick disconnection/reconnection, updates are not sent until the channel has been
+ * offline for a full minute. In order to track this, you must call
+ * timer_chan_freshness_every_min roughly once per minute, though it doesn't have to be perfect.
+ *
+ * Rather than using a plain ChannelManager, it is preferable to use either a SimpleArcChannelManager
+ * a SimpleRefChannelManager, for conciseness. See their documentation for more details, but
+ * essentially you should default to using a SimpleRefChannelManager, and use a
+ * SimpleArcChannelManager when you require a ChannelManager with a static lifetime, such as when
+ * you're using lightning-net-tokio.
  */
-typedef struct MUST_USE_STRUCT LDKUpdateFailHTLC {
+typedef struct MUST_USE_STRUCT LDKChannelManager {
    /**
     * Nearly everywhere, inner must be non-null, however in places where
     * the Rust equivalent takes an Option, it may be set to null to indicate None.
     */
-   LDKnativeUpdateFailHTLC *inner;
+   LDKnativeChannelManager *inner;
    bool is_owned;
-} LDKUpdateFailHTLC;
+} LDKChannelManager;
 
+typedef struct LDKC2Tuple_BlockHashChannelManagerZ {
+   struct LDKThirtyTwoBytes a;
+   struct LDKChannelManager b;
+} LDKC2Tuple_BlockHashChannelManagerZ;
 
+typedef union LDKCResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZPtr {
+   struct LDKC2Tuple_BlockHashChannelManagerZ *result;
+   struct LDKDecodeError *err;
+} LDKCResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZPtr;
 
-/**
- * An update_fail_malformed_htlc message to be sent or received from a peer
- */
-typedef struct MUST_USE_STRUCT LDKUpdateFailMalformedHTLC {
+typedef struct LDKCResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ {
+   union LDKCResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ;
+
+typedef union LDKCResult_SpendableOutputDescriptorDecodeErrorZPtr {
+   struct LDKSpendableOutputDescriptor *result;
+   struct LDKDecodeError *err;
+} LDKCResult_SpendableOutputDescriptorDecodeErrorZPtr;
+
+typedef struct LDKCResult_SpendableOutputDescriptorDecodeErrorZ {
+   union LDKCResult_SpendableOutputDescriptorDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_SpendableOutputDescriptorDecodeErrorZ;
+
+typedef struct LDKCVec_CVec_u8ZZ {
+   struct LDKCVec_u8Z *data;
+   uintptr_t datalen;
+} LDKCVec_CVec_u8ZZ;
+
+typedef union LDKCResult_CVec_CVec_u8ZZNoneZPtr {
+   struct LDKCVec_CVec_u8ZZ *result;
    /**
-    * Nearly everywhere, inner must be non-null, however in places where
-    * the Rust equivalent takes an Option, it may be set to null to indicate None.
+    * Note that this value is always NULL, as there are no contents in the Err variant
     */
-   LDKnativeUpdateFailMalformedHTLC *inner;
-   bool is_owned;
-} LDKUpdateFailMalformedHTLC;
+   void *err;
+} LDKCResult_CVec_CVec_u8ZZNoneZPtr;
+
+typedef struct LDKCResult_CVec_CVec_u8ZZNoneZ {
+   union LDKCResult_CVec_CVec_u8ZZNoneZPtr contents;
+   bool result_ok;
+} LDKCResult_CVec_CVec_u8ZZNoneZ;
 
 
 
 /**
- * A commitment_signed message to be sent or received from a peer
+ * A simple implementation of Sign that just keeps the private keys in memory.
+ *
+ * This implementation performs no policy checks and is insufficient by itself as
+ * a secure external signer.
  */
-typedef struct MUST_USE_STRUCT LDKCommitmentSigned {
+typedef struct MUST_USE_STRUCT LDKInMemorySigner {
    /**
     * Nearly everywhere, inner must be non-null, however in places where
     * the Rust equivalent takes an Option, it may be set to null to indicate None.
     */
-   LDKnativeCommitmentSigned *inner;
+   LDKnativeInMemorySigner *inner;
    bool is_owned;
-} LDKCommitmentSigned;
+} LDKInMemorySigner;
 
+typedef union LDKCResult_InMemorySignerDecodeErrorZPtr {
+   struct LDKInMemorySigner *result;
+   struct LDKDecodeError *err;
+} LDKCResult_InMemorySignerDecodeErrorZPtr;
 
+typedef struct LDKCResult_InMemorySignerDecodeErrorZ {
+   union LDKCResult_InMemorySignerDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_InMemorySignerDecodeErrorZ;
 
-/**
- * An update_fee message to be sent or received from a peer
- */
-typedef struct MUST_USE_STRUCT LDKUpdateFee {
+typedef struct LDKCVec_TxOutZ {
+   struct LDKTxOut *data;
+   uintptr_t datalen;
+} LDKCVec_TxOutZ;
+
+typedef union LDKCResult_TransactionNoneZPtr {
+   struct LDKTransaction *result;
    /**
-    * Nearly everywhere, inner must be non-null, however in places where
-    * the Rust equivalent takes an Option, it may be set to null to indicate None.
+    * Note that this value is always NULL, as there are no contents in the Err variant
     */
-   LDKnativeUpdateFee *inner;
-   bool is_owned;
-} LDKUpdateFee;
+   void *err;
+} LDKCResult_TransactionNoneZPtr;
+
+typedef struct LDKCResult_TransactionNoneZ {
+   union LDKCResult_TransactionNoneZPtr contents;
+   bool result_ok;
+} LDKCResult_TransactionNoneZ;
 
 
 
 /**
- * An init message to be sent or received from a peer
+ * A hop in a route
  */
-typedef struct MUST_USE_STRUCT LDKInit {
+typedef struct MUST_USE_STRUCT LDKRouteHop {
    /**
     * Nearly everywhere, inner must be non-null, however in places where
     * the Rust equivalent takes an Option, it may be set to null to indicate None.
     */
-   LDKnativeInit *inner;
+   LDKnativeRouteHop *inner;
    bool is_owned;
-} LDKInit;
+} LDKRouteHop;
+
+typedef struct LDKCVec_RouteHopZ {
+   struct LDKRouteHop *data;
+   uintptr_t datalen;
+} LDKCVec_RouteHopZ;
+
+typedef struct LDKCVec_CVec_RouteHopZZ {
+   struct LDKCVec_RouteHopZ *data;
+   uintptr_t datalen;
+} LDKCVec_CVec_RouteHopZZ;
+
+
 
 /**
- * A trait to describe an object which can receive channel messages.
- *
- * Messages MAY be called in parallel when they originate from different their_node_ids, however
- * they MUST NOT be called in parallel when the two calls have the same their_node_id.
+ * A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
+ * it can take multiple paths. Each path is composed of one or more hops through the network.
  */
-typedef struct LDKChannelMessageHandler {
-   void *this_arg;
-   /**
-    * Handle an incoming open_channel message from the given peer.
-    */
-   void (*handle_open_channel)(const void *this_arg, LDKPublicKey their_node_id, LDKInitFeatures their_features, const LDKOpenChannel *msg);
-   /**
-    * Handle an incoming accept_channel message from the given peer.
-    */
-   void (*handle_accept_channel)(const void *this_arg, LDKPublicKey their_node_id, LDKInitFeatures their_features, const LDKAcceptChannel *msg);
-   /**
-    * Handle an incoming funding_created message from the given peer.
-    */
-   void (*handle_funding_created)(const void *this_arg, LDKPublicKey their_node_id, const LDKFundingCreated *msg);
-   /**
-    * Handle an incoming funding_signed message from the given peer.
-    */
-   void (*handle_funding_signed)(const void *this_arg, LDKPublicKey their_node_id, const LDKFundingSigned *msg);
-   /**
-    * Handle an incoming funding_locked message from the given peer.
-    */
-   void (*handle_funding_locked)(const void *this_arg, LDKPublicKey their_node_id, const LDKFundingLocked *msg);
-   /**
-    * Handle an incoming shutdown message from the given peer.
-    */
-   void (*handle_shutdown)(const void *this_arg, LDKPublicKey their_node_id, const LDKShutdown *msg);
-   /**
-    * Handle an incoming closing_signed message from the given peer.
-    */
-   void (*handle_closing_signed)(const void *this_arg, LDKPublicKey their_node_id, const LDKClosingSigned *msg);
-   /**
-    * Handle an incoming update_add_htlc message from the given peer.
-    */
-   void (*handle_update_add_htlc)(const void *this_arg, LDKPublicKey their_node_id, const LDKUpdateAddHTLC *msg);
-   /**
-    * Handle an incoming update_fulfill_htlc message from the given peer.
-    */
-   void (*handle_update_fulfill_htlc)(const void *this_arg, LDKPublicKey their_node_id, const LDKUpdateFulfillHTLC *msg);
-   /**
-    * Handle an incoming update_fail_htlc message from the given peer.
-    */
-   void (*handle_update_fail_htlc)(const void *this_arg, LDKPublicKey their_node_id, const LDKUpdateFailHTLC *msg);
-   /**
-    * Handle an incoming update_fail_malformed_htlc message from the given peer.
-    */
-   void (*handle_update_fail_malformed_htlc)(const void *this_arg, LDKPublicKey their_node_id, const LDKUpdateFailMalformedHTLC *msg);
+typedef struct MUST_USE_STRUCT LDKRoute {
    /**
-    * Handle an incoming commitment_signed message from the given peer.
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
     */
-   void (*handle_commitment_signed)(const void *this_arg, LDKPublicKey their_node_id, const LDKCommitmentSigned *msg);
+   LDKnativeRoute *inner;
+   bool is_owned;
+} LDKRoute;
+
+typedef union LDKCResult_RouteDecodeErrorZPtr {
+   struct LDKRoute *result;
+   struct LDKDecodeError *err;
+} LDKCResult_RouteDecodeErrorZPtr;
+
+typedef struct LDKCResult_RouteDecodeErrorZ {
+   union LDKCResult_RouteDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_RouteDecodeErrorZ;
+
+
+
+/**
+ * A channel descriptor which provides a last-hop route to get_route
+ */
+typedef struct MUST_USE_STRUCT LDKRouteHint {
    /**
-    * Handle an incoming revoke_and_ack message from the given peer.
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
     */
-   void (*handle_revoke_and_ack)(const void *this_arg, LDKPublicKey their_node_id, const LDKRevokeAndACK *msg);
+   LDKnativeRouteHint *inner;
+   bool is_owned;
+} LDKRouteHint;
+
+typedef struct LDKCVec_RouteHintZ {
+   struct LDKRouteHint *data;
+   uintptr_t datalen;
+} LDKCVec_RouteHintZ;
+
+typedef union LDKCResult_RouteLightningErrorZPtr {
+   struct LDKRoute *result;
+   struct LDKLightningError *err;
+} LDKCResult_RouteLightningErrorZPtr;
+
+typedef struct LDKCResult_RouteLightningErrorZ {
+   union LDKCResult_RouteLightningErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_RouteLightningErrorZ;
+
+typedef union LDKCResult_NetAddressu8ZPtr {
+   struct LDKNetAddress *result;
+   uint8_t *err;
+} LDKCResult_NetAddressu8ZPtr;
+
+typedef struct LDKCResult_NetAddressu8Z {
+   union LDKCResult_NetAddressu8ZPtr contents;
+   bool result_ok;
+} LDKCResult_NetAddressu8Z;
+
+typedef union LDKCResult_CResult_NetAddressu8ZDecodeErrorZPtr {
+   struct LDKCResult_NetAddressu8Z *result;
+   struct LDKDecodeError *err;
+} LDKCResult_CResult_NetAddressu8ZDecodeErrorZPtr;
+
+typedef struct LDKCResult_CResult_NetAddressu8ZDecodeErrorZ {
+   union LDKCResult_CResult_NetAddressu8ZDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_CResult_NetAddressu8ZDecodeErrorZ;
+
+
+
+/**
+ * An update_add_htlc message to be sent or received from a peer
+ */
+typedef struct MUST_USE_STRUCT LDKUpdateAddHTLC {
    /**
-    * Handle an incoming update_fee message from the given peer.
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
     */
-   void (*handle_update_fee)(const void *this_arg, LDKPublicKey their_node_id, const LDKUpdateFee *msg);
+   LDKnativeUpdateAddHTLC *inner;
+   bool is_owned;
+} LDKUpdateAddHTLC;
+
+typedef struct LDKCVec_UpdateAddHTLCZ {
+   struct LDKUpdateAddHTLC *data;
+   uintptr_t datalen;
+} LDKCVec_UpdateAddHTLCZ;
+
+
+
+/**
+ * An update_fulfill_htlc message to be sent or received from a peer
+ */
+typedef struct MUST_USE_STRUCT LDKUpdateFulfillHTLC {
    /**
-    * Handle an incoming announcement_signatures message from the given peer.
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
     */
-   void (*handle_announcement_signatures)(const void *this_arg, LDKPublicKey their_node_id, const LDKAnnouncementSignatures *msg);
+   LDKnativeUpdateFulfillHTLC *inner;
+   bool is_owned;
+} LDKUpdateFulfillHTLC;
+
+typedef struct LDKCVec_UpdateFulfillHTLCZ {
+   struct LDKUpdateFulfillHTLC *data;
+   uintptr_t datalen;
+} LDKCVec_UpdateFulfillHTLCZ;
+
+
+
+/**
+ * An update_fail_htlc message to be sent or received from a peer
+ */
+typedef struct MUST_USE_STRUCT LDKUpdateFailHTLC {
    /**
-    * Indicates a connection to the peer failed/an existing connection was lost. If no connection
-    * is believed to be possible in the future (eg they're sending us messages we don't
-    * understand or indicate they require unknown feature bits), no_connection_possible is set
-    * and any outstanding channels should be failed.
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
     */
-   void (*peer_disconnected)(const void *this_arg, LDKPublicKey their_node_id, bool no_connection_possible);
+   LDKnativeUpdateFailHTLC *inner;
+   bool is_owned;
+} LDKUpdateFailHTLC;
+
+typedef struct LDKCVec_UpdateFailHTLCZ {
+   struct LDKUpdateFailHTLC *data;
+   uintptr_t datalen;
+} LDKCVec_UpdateFailHTLCZ;
+
+
+
+/**
+ * An update_fail_malformed_htlc message to be sent or received from a peer
+ */
+typedef struct MUST_USE_STRUCT LDKUpdateFailMalformedHTLC {
    /**
-    * Handle a peer reconnecting, possibly generating channel_reestablish message(s).
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
     */
-   void (*peer_connected)(const void *this_arg, LDKPublicKey their_node_id, const LDKInit *msg);
+   LDKnativeUpdateFailMalformedHTLC *inner;
+   bool is_owned;
+} LDKUpdateFailMalformedHTLC;
+
+typedef struct LDKCVec_UpdateFailMalformedHTLCZ {
+   struct LDKUpdateFailMalformedHTLC *data;
+   uintptr_t datalen;
+} LDKCVec_UpdateFailMalformedHTLCZ;
+
+typedef union LDKCResult_AcceptChannelDecodeErrorZPtr {
+   struct LDKAcceptChannel *result;
+   struct LDKDecodeError *err;
+} LDKCResult_AcceptChannelDecodeErrorZPtr;
+
+typedef struct LDKCResult_AcceptChannelDecodeErrorZ {
+   union LDKCResult_AcceptChannelDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_AcceptChannelDecodeErrorZ;
+
+typedef union LDKCResult_AnnouncementSignaturesDecodeErrorZPtr {
+   struct LDKAnnouncementSignatures *result;
+   struct LDKDecodeError *err;
+} LDKCResult_AnnouncementSignaturesDecodeErrorZPtr;
+
+typedef struct LDKCResult_AnnouncementSignaturesDecodeErrorZ {
+   union LDKCResult_AnnouncementSignaturesDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_AnnouncementSignaturesDecodeErrorZ;
+
+typedef union LDKCResult_ChannelReestablishDecodeErrorZPtr {
+   struct LDKChannelReestablish *result;
+   struct LDKDecodeError *err;
+} LDKCResult_ChannelReestablishDecodeErrorZPtr;
+
+typedef struct LDKCResult_ChannelReestablishDecodeErrorZ {
+   union LDKCResult_ChannelReestablishDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_ChannelReestablishDecodeErrorZ;
+
+typedef union LDKCResult_ClosingSignedDecodeErrorZPtr {
+   struct LDKClosingSigned *result;
+   struct LDKDecodeError *err;
+} LDKCResult_ClosingSignedDecodeErrorZPtr;
+
+typedef struct LDKCResult_ClosingSignedDecodeErrorZ {
+   union LDKCResult_ClosingSignedDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_ClosingSignedDecodeErrorZ;
+
+
+
+/**
+ * A commitment_signed message to be sent or received from a peer
+ */
+typedef struct MUST_USE_STRUCT LDKCommitmentSigned {
    /**
-    * Handle an incoming channel_reestablish message from the given peer.
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
     */
-   void (*handle_channel_reestablish)(const void *this_arg, LDKPublicKey their_node_id, const LDKChannelReestablish *msg);
+   LDKnativeCommitmentSigned *inner;
+   bool is_owned;
+} LDKCommitmentSigned;
+
+typedef union LDKCResult_CommitmentSignedDecodeErrorZPtr {
+   struct LDKCommitmentSigned *result;
+   struct LDKDecodeError *err;
+} LDKCResult_CommitmentSignedDecodeErrorZPtr;
+
+typedef struct LDKCResult_CommitmentSignedDecodeErrorZ {
+   union LDKCResult_CommitmentSignedDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_CommitmentSignedDecodeErrorZ;
+
+typedef union LDKCResult_FundingCreatedDecodeErrorZPtr {
+   struct LDKFundingCreated *result;
+   struct LDKDecodeError *err;
+} LDKCResult_FundingCreatedDecodeErrorZPtr;
+
+typedef struct LDKCResult_FundingCreatedDecodeErrorZ {
+   union LDKCResult_FundingCreatedDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_FundingCreatedDecodeErrorZ;
+
+typedef union LDKCResult_FundingSignedDecodeErrorZPtr {
+   struct LDKFundingSigned *result;
+   struct LDKDecodeError *err;
+} LDKCResult_FundingSignedDecodeErrorZPtr;
+
+typedef struct LDKCResult_FundingSignedDecodeErrorZ {
+   union LDKCResult_FundingSignedDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_FundingSignedDecodeErrorZ;
+
+typedef union LDKCResult_FundingLockedDecodeErrorZPtr {
+   struct LDKFundingLocked *result;
+   struct LDKDecodeError *err;
+} LDKCResult_FundingLockedDecodeErrorZPtr;
+
+typedef struct LDKCResult_FundingLockedDecodeErrorZ {
+   union LDKCResult_FundingLockedDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_FundingLockedDecodeErrorZ;
+
+
+
+/**
+ * An init message to be sent or received from a peer
+ */
+typedef struct MUST_USE_STRUCT LDKInit {
    /**
-    * Handle an incoming error message from the given peer.
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
     */
-   void (*handle_error)(const void *this_arg, LDKPublicKey their_node_id, const LDKErrorMessage *msg);
-   LDKMessageSendEventsProvider MessageSendEventsProvider;
-   void (*free)(void *this_arg);
-} LDKChannelMessageHandler;
+   LDKnativeInit *inner;
+   bool is_owned;
+} LDKInit;
+
+typedef union LDKCResult_InitDecodeErrorZPtr {
+   struct LDKInit *result;
+   struct LDKDecodeError *err;
+} LDKCResult_InitDecodeErrorZPtr;
+
+typedef struct LDKCResult_InitDecodeErrorZ {
+   union LDKCResult_InitDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_InitDecodeErrorZ;
+
+typedef union LDKCResult_OpenChannelDecodeErrorZPtr {
+   struct LDKOpenChannel *result;
+   struct LDKDecodeError *err;
+} LDKCResult_OpenChannelDecodeErrorZPtr;
+
+typedef struct LDKCResult_OpenChannelDecodeErrorZ {
+   union LDKCResult_OpenChannelDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_OpenChannelDecodeErrorZ;
+
+typedef union LDKCResult_RevokeAndACKDecodeErrorZPtr {
+   struct LDKRevokeAndACK *result;
+   struct LDKDecodeError *err;
+} LDKCResult_RevokeAndACKDecodeErrorZPtr;
+
+typedef struct LDKCResult_RevokeAndACKDecodeErrorZ {
+   union LDKCResult_RevokeAndACKDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_RevokeAndACKDecodeErrorZ;
+
+typedef union LDKCResult_ShutdownDecodeErrorZPtr {
+   struct LDKShutdown *result;
+   struct LDKDecodeError *err;
+} LDKCResult_ShutdownDecodeErrorZPtr;
+
+typedef struct LDKCResult_ShutdownDecodeErrorZ {
+   union LDKCResult_ShutdownDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_ShutdownDecodeErrorZ;
+
+typedef union LDKCResult_UpdateFailHTLCDecodeErrorZPtr {
+   struct LDKUpdateFailHTLC *result;
+   struct LDKDecodeError *err;
+} LDKCResult_UpdateFailHTLCDecodeErrorZPtr;
+
+typedef struct LDKCResult_UpdateFailHTLCDecodeErrorZ {
+   union LDKCResult_UpdateFailHTLCDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_UpdateFailHTLCDecodeErrorZ;
+
+typedef union LDKCResult_UpdateFailMalformedHTLCDecodeErrorZPtr {
+   struct LDKUpdateFailMalformedHTLC *result;
+   struct LDKDecodeError *err;
+} LDKCResult_UpdateFailMalformedHTLCDecodeErrorZPtr;
+
+typedef struct LDKCResult_UpdateFailMalformedHTLCDecodeErrorZ {
+   union LDKCResult_UpdateFailMalformedHTLCDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_UpdateFailMalformedHTLCDecodeErrorZ;
 
 
 
 /**
- * Arguments for the creation of a ChannelManager that are not deserialized.
- *
- * At a high-level, the process for deserializing a ChannelManager and resuming normal operation
- * is:
- * 1) Deserialize all stored ChannelMonitors.
- * 2) Deserialize the ChannelManager by filling in this struct and calling <(Sha256dHash,
- *    ChannelManager)>::read(reader, args).
- *    This may result in closing some Channels if the ChannelMonitor is newer than the stored
- *    ChannelManager state to ensure no loss of funds. Thus, transactions may be broadcasted.
- * 3) Register all relevant ChannelMonitor outpoints with your chain watch mechanism using
- *    ChannelMonitor::get_outputs_to_watch() and ChannelMonitor::get_funding_txo().
- * 4) Reconnect blocks on your ChannelMonitors.
- * 5) Move the ChannelMonitors into your local chain::Watch.
- * 6) Disconnect/connect blocks on the ChannelManager.
+ * An update_fee message to be sent or received from a peer
  */
-typedef struct MUST_USE_STRUCT LDKChannelManagerReadArgs {
+typedef struct MUST_USE_STRUCT LDKUpdateFee {
    /**
     * Nearly everywhere, inner must be non-null, however in places where
     * the Rust equivalent takes an Option, it may be set to null to indicate None.
     */
-   LDKnativeChannelManagerReadArgs *inner;
+   LDKnativeUpdateFee *inner;
    bool is_owned;
-} LDKChannelManagerReadArgs;
+} LDKUpdateFee;
 
-typedef struct LDKCVecTempl_ChannelMonitor {
-   LDKChannelMonitor *data;
-   uintptr_t datalen;
-} LDKCVecTempl_ChannelMonitor;
+typedef union LDKCResult_UpdateFeeDecodeErrorZPtr {
+   struct LDKUpdateFee *result;
+   struct LDKDecodeError *err;
+} LDKCResult_UpdateFeeDecodeErrorZPtr;
+
+typedef struct LDKCResult_UpdateFeeDecodeErrorZ {
+   union LDKCResult_UpdateFeeDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_UpdateFeeDecodeErrorZ;
+
+typedef union LDKCResult_UpdateFulfillHTLCDecodeErrorZPtr {
+   struct LDKUpdateFulfillHTLC *result;
+   struct LDKDecodeError *err;
+} LDKCResult_UpdateFulfillHTLCDecodeErrorZPtr;
 
-typedef LDKCVecTempl_ChannelMonitor LDKCVec_ChannelMonitorZ;
+typedef struct LDKCResult_UpdateFulfillHTLCDecodeErrorZ {
+   union LDKCResult_UpdateFulfillHTLCDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_UpdateFulfillHTLCDecodeErrorZ;
+
+typedef union LDKCResult_UpdateAddHTLCDecodeErrorZPtr {
+   struct LDKUpdateAddHTLC *result;
+   struct LDKDecodeError *err;
+} LDKCResult_UpdateAddHTLCDecodeErrorZPtr;
+
+typedef struct LDKCResult_UpdateAddHTLCDecodeErrorZ {
+   union LDKCResult_UpdateAddHTLCDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_UpdateAddHTLCDecodeErrorZ;
 
 
 
 /**
- * An error in decoding a message or struct.
+ * A ping message to be sent or received from a peer
  */
-typedef struct MUST_USE_STRUCT LDKDecodeError {
+typedef struct MUST_USE_STRUCT LDKPing {
    /**
     * Nearly everywhere, inner must be non-null, however in places where
     * the Rust equivalent takes an Option, it may be set to null to indicate None.
     */
-   LDKnativeDecodeError *inner;
+   LDKnativePing *inner;
    bool is_owned;
-} LDKDecodeError;
+} LDKPing;
+
+typedef union LDKCResult_PingDecodeErrorZPtr {
+   struct LDKPing *result;
+   struct LDKDecodeError *err;
+} LDKCResult_PingDecodeErrorZPtr;
+
+typedef struct LDKCResult_PingDecodeErrorZ {
+   union LDKCResult_PingDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_PingDecodeErrorZ;
+
+
+
+/**
+ * A pong message to be sent or received from a peer
+ */
+typedef struct MUST_USE_STRUCT LDKPong {
+   /**
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
+    */
+   LDKnativePong *inner;
+   bool is_owned;
+} LDKPong;
+
+typedef union LDKCResult_PongDecodeErrorZPtr {
+   struct LDKPong *result;
+   struct LDKDecodeError *err;
+} LDKCResult_PongDecodeErrorZPtr;
+
+typedef struct LDKCResult_PongDecodeErrorZ {
+   union LDKCResult_PongDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_PongDecodeErrorZ;
+
+typedef union LDKCResult_UnsignedChannelAnnouncementDecodeErrorZPtr {
+   struct LDKUnsignedChannelAnnouncement *result;
+   struct LDKDecodeError *err;
+} LDKCResult_UnsignedChannelAnnouncementDecodeErrorZPtr;
+
+typedef struct LDKCResult_UnsignedChannelAnnouncementDecodeErrorZ {
+   union LDKCResult_UnsignedChannelAnnouncementDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_UnsignedChannelAnnouncementDecodeErrorZ;
+
+typedef union LDKCResult_ChannelAnnouncementDecodeErrorZPtr {
+   struct LDKChannelAnnouncement *result;
+   struct LDKDecodeError *err;
+} LDKCResult_ChannelAnnouncementDecodeErrorZPtr;
+
+typedef struct LDKCResult_ChannelAnnouncementDecodeErrorZ {
+   union LDKCResult_ChannelAnnouncementDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_ChannelAnnouncementDecodeErrorZ;
+
+
+
+/**
+ * The unsigned part of a channel_update
+ */
+typedef struct MUST_USE_STRUCT LDKUnsignedChannelUpdate {
+   /**
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
+    */
+   LDKnativeUnsignedChannelUpdate *inner;
+   bool is_owned;
+} LDKUnsignedChannelUpdate;
+
+typedef union LDKCResult_UnsignedChannelUpdateDecodeErrorZPtr {
+   struct LDKUnsignedChannelUpdate *result;
+   struct LDKDecodeError *err;
+} LDKCResult_UnsignedChannelUpdateDecodeErrorZPtr;
+
+typedef struct LDKCResult_UnsignedChannelUpdateDecodeErrorZ {
+   union LDKCResult_UnsignedChannelUpdateDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_UnsignedChannelUpdateDecodeErrorZ;
+
+typedef union LDKCResult_ChannelUpdateDecodeErrorZPtr {
+   struct LDKChannelUpdate *result;
+   struct LDKDecodeError *err;
+} LDKCResult_ChannelUpdateDecodeErrorZPtr;
+
+typedef struct LDKCResult_ChannelUpdateDecodeErrorZ {
+   union LDKCResult_ChannelUpdateDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_ChannelUpdateDecodeErrorZ;
+
+typedef union LDKCResult_ErrorMessageDecodeErrorZPtr {
+   struct LDKErrorMessage *result;
+   struct LDKDecodeError *err;
+} LDKCResult_ErrorMessageDecodeErrorZPtr;
+
+typedef struct LDKCResult_ErrorMessageDecodeErrorZ {
+   union LDKCResult_ErrorMessageDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_ErrorMessageDecodeErrorZ;
+
+
+
+/**
+ * The unsigned part of a node_announcement
+ */
+typedef struct MUST_USE_STRUCT LDKUnsignedNodeAnnouncement {
+   /**
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
+    */
+   LDKnativeUnsignedNodeAnnouncement *inner;
+   bool is_owned;
+} LDKUnsignedNodeAnnouncement;
+
+typedef union LDKCResult_UnsignedNodeAnnouncementDecodeErrorZPtr {
+   struct LDKUnsignedNodeAnnouncement *result;
+   struct LDKDecodeError *err;
+} LDKCResult_UnsignedNodeAnnouncementDecodeErrorZPtr;
+
+typedef struct LDKCResult_UnsignedNodeAnnouncementDecodeErrorZ {
+   union LDKCResult_UnsignedNodeAnnouncementDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_UnsignedNodeAnnouncementDecodeErrorZ;
+
+typedef union LDKCResult_NodeAnnouncementDecodeErrorZPtr {
+   struct LDKNodeAnnouncement *result;
+   struct LDKDecodeError *err;
+} LDKCResult_NodeAnnouncementDecodeErrorZPtr;
+
+typedef struct LDKCResult_NodeAnnouncementDecodeErrorZ {
+   union LDKCResult_NodeAnnouncementDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_NodeAnnouncementDecodeErrorZ;
+
+typedef union LDKCResult_QueryShortChannelIdsDecodeErrorZPtr {
+   struct LDKQueryShortChannelIds *result;
+   struct LDKDecodeError *err;
+} LDKCResult_QueryShortChannelIdsDecodeErrorZPtr;
+
+typedef struct LDKCResult_QueryShortChannelIdsDecodeErrorZ {
+   union LDKCResult_QueryShortChannelIdsDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_QueryShortChannelIdsDecodeErrorZ;
+
+
+
+/**
+ * A reply_short_channel_ids_end message is sent as a reply to a
+ * query_short_channel_ids message. The query recipient makes a best
+ * effort to respond based on their local network view which may not be
+ * a perfect view of the network.
+ */
+typedef struct MUST_USE_STRUCT LDKReplyShortChannelIdsEnd {
+   /**
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
+    */
+   LDKnativeReplyShortChannelIdsEnd *inner;
+   bool is_owned;
+} LDKReplyShortChannelIdsEnd;
+
+typedef union LDKCResult_ReplyShortChannelIdsEndDecodeErrorZPtr {
+   struct LDKReplyShortChannelIdsEnd *result;
+   struct LDKDecodeError *err;
+} LDKCResult_ReplyShortChannelIdsEndDecodeErrorZPtr;
+
+typedef struct LDKCResult_ReplyShortChannelIdsEndDecodeErrorZ {
+   union LDKCResult_ReplyShortChannelIdsEndDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_ReplyShortChannelIdsEndDecodeErrorZ;
+
+typedef union LDKCResult_QueryChannelRangeDecodeErrorZPtr {
+   struct LDKQueryChannelRange *result;
+   struct LDKDecodeError *err;
+} LDKCResult_QueryChannelRangeDecodeErrorZPtr;
+
+typedef struct LDKCResult_QueryChannelRangeDecodeErrorZ {
+   union LDKCResult_QueryChannelRangeDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_QueryChannelRangeDecodeErrorZ;
+
+
+
+/**
+ * A reply_channel_range message is a reply to a query_channel_range
+ * message. Multiple reply_channel_range messages can be sent in reply
+ * to a single query_channel_range message. The query recipient makes a
+ * best effort to respond based on their local network view which may
+ * not be a perfect view of the network. The short_channel_ids in the
+ * reply are encoded. We only support encoding_type=0 uncompressed
+ * serialization and do not support encoding_type=1 zlib serialization.
+ */
+typedef struct MUST_USE_STRUCT LDKReplyChannelRange {
+   /**
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
+    */
+   LDKnativeReplyChannelRange *inner;
+   bool is_owned;
+} LDKReplyChannelRange;
+
+typedef union LDKCResult_ReplyChannelRangeDecodeErrorZPtr {
+   struct LDKReplyChannelRange *result;
+   struct LDKDecodeError *err;
+} LDKCResult_ReplyChannelRangeDecodeErrorZPtr;
+
+typedef struct LDKCResult_ReplyChannelRangeDecodeErrorZ {
+   union LDKCResult_ReplyChannelRangeDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_ReplyChannelRangeDecodeErrorZ;
+
+
+
+/**
+ * A gossip_timestamp_filter message is used by a node to request
+ * gossip relay for messages in the requested time range when the
+ * gossip_queries feature has been negotiated.
+ */
+typedef struct MUST_USE_STRUCT LDKGossipTimestampFilter {
+   /**
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
+    */
+   LDKnativeGossipTimestampFilter *inner;
+   bool is_owned;
+} LDKGossipTimestampFilter;
+
+typedef union LDKCResult_GossipTimestampFilterDecodeErrorZPtr {
+   struct LDKGossipTimestampFilter *result;
+   struct LDKDecodeError *err;
+} LDKCResult_GossipTimestampFilterDecodeErrorZPtr;
+
+typedef struct LDKCResult_GossipTimestampFilterDecodeErrorZ {
+   union LDKCResult_GossipTimestampFilterDecodeErrorZPtr contents;
+   bool result_ok;
+} LDKCResult_GossipTimestampFilterDecodeErrorZ;
+
+/**
+ * A trait indicating an object may generate message send events
+ */
+typedef struct LDKMessageSendEventsProvider {
+   void *this_arg;
+   /**
+    * Gets the list of pending events which were generated by previous actions, clearing the list
+    * in the process.
+    */
+   struct LDKCVec_MessageSendEventZ (*get_and_clear_pending_msg_events)(const void *this_arg);
+   void (*free)(void *this_arg);
+} LDKMessageSendEventsProvider;
+
+/**
+ * A trait indicating an object may generate events
+ */
+typedef struct LDKEventsProvider {
+   void *this_arg;
+   /**
+    * Gets the list of pending events which were generated by previous actions, clearing the list
+    * in the process.
+    */
+   struct LDKCVec_EventZ (*get_and_clear_pending_events)(const void *this_arg);
+   void (*free)(void *this_arg);
+} LDKEventsProvider;
+
+
+
+/**
+ * Configuration we set when applicable.
+ *
+ * Default::default() provides sane defaults.
+ */
+typedef struct MUST_USE_STRUCT LDKChannelHandshakeConfig {
+   /**
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
+    */
+   LDKnativeChannelHandshakeConfig *inner;
+   bool is_owned;
+} LDKChannelHandshakeConfig;
+
+
+
+/**
+ * Optional channel limits which are applied during channel creation.
+ *
+ * These limits are only applied to our counterparty's limits, not our own.
+ *
+ * Use 0/<type>::max_value() as appropriate to skip checking.
+ *
+ * Provides sane defaults for most configurations.
+ *
+ * Most additional limits are disabled except those with which specify a default in individual
+ * field documentation. Note that this may result in barely-usable channels, but since they
+ * are applied mostly only to incoming channels that's not much of a problem.
+ */
+typedef struct MUST_USE_STRUCT LDKChannelHandshakeLimits {
+   /**
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
+    */
+   LDKnativeChannelHandshakeLimits *inner;
+   bool is_owned;
+} LDKChannelHandshakeLimits;
+
+
+
+/**
+ * Top-level config which holds ChannelHandshakeLimits and ChannelConfig.
+ *
+ * Default::default() provides sane defaults for most configurations
+ * (but currently with 0 relay fees!)
+ */
+typedef struct MUST_USE_STRUCT LDKUserConfig {
+   /**
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
+    */
+   LDKnativeUserConfig *inner;
+   bool is_owned;
+} LDKUserConfig;
+
+/**
+ * The `Access` trait defines behavior for accessing chain data and state, such as blocks and
+ * UTXOs.
+ */
+typedef struct LDKAccess {
+   void *this_arg;
+   /**
+    * Returns the transaction output of a funding transaction encoded by [`short_channel_id`].
+    * Returns an error if `genesis_hash` is for a different chain or if such a transaction output
+    * is unknown.
+    *
+    * [`short_channel_id`]: https://github.com/lightningnetwork/lightning-rfc/blob/master/07-routing-gossip.md#definition-of-short_channel_id
+    */
+   struct LDKCResult_TxOutAccessErrorZ (*get_utxo)(const void *this_arg, const uint8_t (*genesis_hash)[32], uint64_t short_channel_id);
+   void (*free)(void *this_arg);
+} LDKAccess;
+
+/**
+ * The `Listen` trait is used to be notified of when blocks have been connected or disconnected
+ * from the chain.
+ *
+ * Useful when needing to replay chain data upon startup or as new chain events occur.
+ */
+typedef struct LDKListen {
+   void *this_arg;
+   /**
+    * Notifies the listener that a block was added at the given height.
+    */
+   void (*block_connected)(const void *this_arg, struct LDKu8slice block, uint32_t height);
+   /**
+    * Notifies the listener that a block was removed at the given height.
+    */
+   void (*block_disconnected)(const void *this_arg, const uint8_t (*header)[80], uint32_t height);
+   void (*free)(void *this_arg);
+} LDKListen;
+
+/**
+ * The `Filter` trait defines behavior for indicating chain activity of interest pertaining to
+ * channels.
+ *
+ * This is useful in order to have a [`Watch`] implementation convey to a chain source which
+ * transactions to be notified of. Notification may take the form of pre-filtering blocks or, in
+ * the case of [BIP 157]/[BIP 158], only fetching a block if the compact filter matches. If
+ * receiving full blocks from a chain source, any further filtering is unnecessary.
+ *
+ * After an output has been registered, subsequent block retrievals from the chain source must not
+ * exclude any transactions matching the new criteria nor any in-block descendants of such
+ * transactions.
+ *
+ * Note that use as part of a [`Watch`] implementation involves reentrancy. Therefore, the `Filter`
+ * should not block on I/O. Implementations should instead queue the newly monitored data to be
+ * processed later. Then, in order to block until the data has been processed, any `Watch`
+ * invocation that has called the `Filter` must return [`TemporaryFailure`].
+ *
+ * [`Watch`]: trait.Watch.html
+ * [`TemporaryFailure`]: channelmonitor/enum.ChannelMonitorUpdateErr.html#variant.TemporaryFailure
+ * [BIP 157]: https://github.com/bitcoin/bips/blob/master/bip-0157.mediawiki
+ * [BIP 158]: https://github.com/bitcoin/bips/blob/master/bip-0158.mediawiki
+ */
+typedef struct LDKFilter {
+   void *this_arg;
+   /**
+    * Registers interest in a transaction with `txid` and having an output with `script_pubkey` as
+    * a spending condition.
+    */
+   void (*register_tx)(const void *this_arg, const uint8_t (*txid)[32], struct LDKu8slice script_pubkey);
+   /**
+    * Registers interest in spends of a transaction output identified by `outpoint` having
+    * `script_pubkey` as the spending condition.
+    */
+   void (*register_output)(const void *this_arg, const struct LDKOutPoint *NONNULL_PTR outpoint, struct LDKu8slice script_pubkey);
+   void (*free)(void *this_arg);
+} LDKFilter;
+
+/**
+ * `Persist` defines behavior for persisting channel monitors: this could mean
+ * writing once to disk, and/or uploading to one or more backup services.
+ *
+ * Note that for every new monitor, you **must** persist the new `ChannelMonitor`
+ * to disk/backups. And, on every update, you **must** persist either the
+ * `ChannelMonitorUpdate` or the updated monitor itself. Otherwise, there is risk
+ * of situations such as revoking a transaction, then crashing before this
+ * revocation can be persisted, then unintentionally broadcasting a revoked
+ * transaction and losing money. This is a risk because previous channel states
+ * are toxic, so it's important that whatever channel state is persisted is
+ * kept up-to-date.
+ */
+typedef struct LDKPersist {
+   void *this_arg;
+   /**
+    * Persist a new channel's data. The data can be stored any way you want, but
+    * the identifier provided by Rust-Lightning is the channel's outpoint (and
+    * it is up to you to maintain a correct mapping between the outpoint and the
+    * stored channel data). Note that you **must** persist every new monitor to
+    * disk. See the `Persist` trait documentation for more details.
+    *
+    * See [`ChannelMonitor::serialize_for_disk`] for writing out a `ChannelMonitor`,
+    * and [`ChannelMonitorUpdateErr`] for requirements when returning errors.
+    *
+    * [`ChannelMonitor::serialize_for_disk`]: struct.ChannelMonitor.html#method.serialize_for_disk
+    * [`ChannelMonitorUpdateErr`]: enum.ChannelMonitorUpdateErr.html
+    */
+   struct LDKCResult_NoneChannelMonitorUpdateErrZ (*persist_new_channel)(const void *this_arg, struct LDKOutPoint id, const struct LDKChannelMonitor *NONNULL_PTR data);
+   /**
+    * Update one channel's data. The provided `ChannelMonitor` has already
+    * applied the given update.
+    *
+    * Note that on every update, you **must** persist either the
+    * `ChannelMonitorUpdate` or the updated monitor itself to disk/backups. See
+    * the `Persist` trait documentation for more details.
+    *
+    * If an implementer chooses to persist the updates only, they need to make
+    * sure that all the updates are applied to the `ChannelMonitors` *before*
+    * the set of channel monitors is given to the `ChannelManager`
+    * deserialization routine. See [`ChannelMonitor::update_monitor`] for
+    * applying a monitor update to a monitor. If full `ChannelMonitors` are
+    * persisted, then there is no need to persist individual updates.
+    *
+    * Note that there could be a performance tradeoff between persisting complete
+    * channel monitors on every update vs. persisting only updates and applying
+    * them in batches. The size of each monitor grows `O(number of state updates)`
+    * whereas updates are small and `O(1)`.
+    *
+    * See [`ChannelMonitor::serialize_for_disk`] for writing out a `ChannelMonitor`,
+    * [`ChannelMonitorUpdate::write`] for writing out an update, and
+    * [`ChannelMonitorUpdateErr`] for requirements when returning errors.
+    *
+    * [`ChannelMonitor::update_monitor`]: struct.ChannelMonitor.html#impl-1
+    * [`ChannelMonitor::serialize_for_disk`]: struct.ChannelMonitor.html#method.serialize_for_disk
+    * [`ChannelMonitorUpdate::write`]: struct.ChannelMonitorUpdate.html#method.write
+    * [`ChannelMonitorUpdateErr`]: enum.ChannelMonitorUpdateErr.html
+    */
+   struct LDKCResult_NoneChannelMonitorUpdateErrZ (*update_persisted_channel)(const void *this_arg, struct LDKOutPoint id, const struct LDKChannelMonitorUpdate *NONNULL_PTR update, const struct LDKChannelMonitor *NONNULL_PTR data);
+   void (*free)(void *this_arg);
+} LDKPersist;
+
+
+
+/**
+ * An implementation of [`chain::Watch`] for monitoring channels.
+ *
+ * Connected and disconnected blocks must be provided to `ChainMonitor` as documented by
+ * [`chain::Watch`]. May be used in conjunction with [`ChannelManager`] to monitor channels locally
+ * or used independently to monitor channels remotely. See the [module-level documentation] for
+ * details.
+ *
+ * [`chain::Watch`]: ../trait.Watch.html
+ * [`ChannelManager`]: ../../ln/channelmanager/struct.ChannelManager.html
+ * [module-level documentation]: index.html
+ */
+typedef struct MUST_USE_STRUCT LDKChainMonitor {
+   /**
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
+    */
+   LDKnativeChainMonitor *inner;
+   bool is_owned;
+} LDKChainMonitor;
+
+
+
+/**
+ * Simple KeysInterface implementor that takes a 32-byte seed for use as a BIP 32 extended key
+ * and derives keys from that.
+ *
+ * Your node_id is seed/0'
+ * ChannelMonitor closes may use seed/1'
+ * Cooperative closes may use seed/2'
+ * The two close keys may be needed to claim on-chain funds!
+ */
+typedef struct MUST_USE_STRUCT LDKKeysManager {
+   /**
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
+    */
+   LDKnativeKeysManager *inner;
+   bool is_owned;
+} LDKKeysManager;
+
+typedef struct LDKThreeBytes {
+   uint8_t data[3];
+} LDKThreeBytes;
+
+/**
+ * A trait to describe an object which can receive channel messages.
+ *
+ * Messages MAY be called in parallel when they originate from different their_node_ids, however
+ * they MUST NOT be called in parallel when the two calls have the same their_node_id.
+ */
+typedef struct LDKChannelMessageHandler {
+   void *this_arg;
+   /**
+    * Handle an incoming open_channel message from the given peer.
+    */
+   void (*handle_open_channel)(const void *this_arg, struct LDKPublicKey their_node_id, struct LDKInitFeatures their_features, const struct LDKOpenChannel *NONNULL_PTR msg);
+   /**
+    * Handle an incoming accept_channel message from the given peer.
+    */
+   void (*handle_accept_channel)(const void *this_arg, struct LDKPublicKey their_node_id, struct LDKInitFeatures their_features, const struct LDKAcceptChannel *NONNULL_PTR msg);
+   /**
+    * Handle an incoming funding_created message from the given peer.
+    */
+   void (*handle_funding_created)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKFundingCreated *NONNULL_PTR msg);
+   /**
+    * Handle an incoming funding_signed message from the given peer.
+    */
+   void (*handle_funding_signed)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKFundingSigned *NONNULL_PTR msg);
+   /**
+    * Handle an incoming funding_locked message from the given peer.
+    */
+   void (*handle_funding_locked)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKFundingLocked *NONNULL_PTR msg);
+   /**
+    * Handle an incoming shutdown message from the given peer.
+    */
+   void (*handle_shutdown)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKInitFeatures *NONNULL_PTR their_features, const struct LDKShutdown *NONNULL_PTR msg);
+   /**
+    * Handle an incoming closing_signed message from the given peer.
+    */
+   void (*handle_closing_signed)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKClosingSigned *NONNULL_PTR msg);
+   /**
+    * Handle an incoming update_add_htlc message from the given peer.
+    */
+   void (*handle_update_add_htlc)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKUpdateAddHTLC *NONNULL_PTR msg);
+   /**
+    * Handle an incoming update_fulfill_htlc message from the given peer.
+    */
+   void (*handle_update_fulfill_htlc)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKUpdateFulfillHTLC *NONNULL_PTR msg);
+   /**
+    * Handle an incoming update_fail_htlc message from the given peer.
+    */
+   void (*handle_update_fail_htlc)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKUpdateFailHTLC *NONNULL_PTR msg);
+   /**
+    * Handle an incoming update_fail_malformed_htlc message from the given peer.
+    */
+   void (*handle_update_fail_malformed_htlc)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKUpdateFailMalformedHTLC *NONNULL_PTR msg);
+   /**
+    * Handle an incoming commitment_signed message from the given peer.
+    */
+   void (*handle_commitment_signed)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKCommitmentSigned *NONNULL_PTR msg);
+   /**
+    * Handle an incoming revoke_and_ack message from the given peer.
+    */
+   void (*handle_revoke_and_ack)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKRevokeAndACK *NONNULL_PTR msg);
+   /**
+    * Handle an incoming update_fee message from the given peer.
+    */
+   void (*handle_update_fee)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKUpdateFee *NONNULL_PTR msg);
+   /**
+    * Handle an incoming announcement_signatures message from the given peer.
+    */
+   void (*handle_announcement_signatures)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKAnnouncementSignatures *NONNULL_PTR msg);
+   /**
+    * Indicates a connection to the peer failed/an existing connection was lost. If no connection
+    * is believed to be possible in the future (eg they're sending us messages we don't
+    * understand or indicate they require unknown feature bits), no_connection_possible is set
+    * and any outstanding channels should be failed.
+    */
+   void (*peer_disconnected)(const void *this_arg, struct LDKPublicKey their_node_id, bool no_connection_possible);
+   /**
+    * Handle a peer reconnecting, possibly generating channel_reestablish message(s).
+    */
+   void (*peer_connected)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKInit *NONNULL_PTR msg);
+   /**
+    * Handle an incoming channel_reestablish message from the given peer.
+    */
+   void (*handle_channel_reestablish)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKChannelReestablish *NONNULL_PTR msg);
+   /**
+    * Handle an incoming error message from the given peer.
+    */
+   void (*handle_error)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKErrorMessage *NONNULL_PTR msg);
+   struct LDKMessageSendEventsProvider MessageSendEventsProvider;
+   void (*free)(void *this_arg);
+} LDKChannelMessageHandler;
+
+
+
+/**
+ * Arguments for the creation of a ChannelManager that are not deserialized.
+ *
+ * At a high-level, the process for deserializing a ChannelManager and resuming normal operation
+ * is:
+ * 1) Deserialize all stored ChannelMonitors.
+ * 2) Deserialize the ChannelManager by filling in this struct and calling <(Sha256dHash,
+ *    ChannelManager)>::read(reader, args).
+ *    This may result in closing some Channels if the ChannelMonitor is newer than the stored
+ *    ChannelManager state to ensure no loss of funds. Thus, transactions may be broadcasted.
+ * 3) Register all relevant ChannelMonitor outpoints with your chain watch mechanism using
+ *    ChannelMonitor::get_outputs_to_watch() and ChannelMonitor::get_funding_txo().
+ * 4) Reconnect blocks on your ChannelMonitors.
+ * 5) Move the ChannelMonitors into your local chain::Watch.
+ * 6) Disconnect/connect blocks on the ChannelManager.
+ */
+typedef struct MUST_USE_STRUCT LDKChannelManagerReadArgs {
+   /**
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
+    */
+   LDKnativeChannelManagerReadArgs *inner;
+   bool is_owned;
+} LDKChannelManagerReadArgs;
+
+
+
+/**
+ * Proof that the sender knows the per-commitment secret of the previous commitment transaction.
+ * This is used to convince the recipient that the channel is at a certain commitment
+ * number even if they lost that data due to a local failure.  Of course, the peer may lie
+ * and even later commitments may have been revoked.
+ */
+typedef struct MUST_USE_STRUCT LDKDataLossProtect {
+   /**
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
+    */
+   LDKnativeDataLossProtect *inner;
+   bool is_owned;
+} LDKDataLossProtect;
+
+/**
+ * A trait to describe an object which can receive routing messages.
+ *
+ * # Implementor DoS Warnings
+ *
+ * For `gossip_queries` messages there are potential DoS vectors when handling
+ * inbound queries. Implementors using an on-disk network graph should be aware of
+ * repeated disk I/O for queries accessing different parts of the network graph.
+ */
+typedef struct LDKRoutingMessageHandler {
+   void *this_arg;
+   /**
+    * Handle an incoming node_announcement message, returning true if it should be forwarded on,
+    * false or returning an Err otherwise.
+    */
+   struct LDKCResult_boolLightningErrorZ (*handle_node_announcement)(const void *this_arg, const struct LDKNodeAnnouncement *NONNULL_PTR msg);
+   /**
+    * Handle a channel_announcement message, returning true if it should be forwarded on, false
+    * or returning an Err otherwise.
+    */
+   struct LDKCResult_boolLightningErrorZ (*handle_channel_announcement)(const void *this_arg, const struct LDKChannelAnnouncement *NONNULL_PTR msg);
+   /**
+    * Handle an incoming channel_update message, returning true if it should be forwarded on,
+    * false or returning an Err otherwise.
+    */
+   struct LDKCResult_boolLightningErrorZ (*handle_channel_update)(const void *this_arg, const struct LDKChannelUpdate *NONNULL_PTR msg);
+   /**
+    * Handle some updates to the route graph that we learned due to an outbound failed payment.
+    */
+   void (*handle_htlc_fail_channel_update)(const void *this_arg, const struct LDKHTLCFailChannelUpdate *NONNULL_PTR update);
+   /**
+    * Gets a subset of the channel announcements and updates required to dump our routing table
+    * to a remote node, starting at the short_channel_id indicated by starting_point and
+    * including the batch_amount entries immediately higher in numerical value than starting_point.
+    */
+   struct LDKCVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ (*get_next_channel_announcements)(const void *this_arg, uint64_t starting_point, uint8_t batch_amount);
+   /**
+    * Gets a subset of the node announcements required to dump our routing table to a remote node,
+    * starting at the node *after* the provided publickey and including batch_amount entries
+    * immediately higher (as defined by <PublicKey as Ord>::cmp) than starting_point.
+    * If None is provided for starting_point, we start at the first node.
+    */
+   struct LDKCVec_NodeAnnouncementZ (*get_next_node_announcements)(const void *this_arg, struct LDKPublicKey starting_point, uint8_t batch_amount);
+   /**
+    * Called when a connection is established with a peer. This can be used to
+    * perform routing table synchronization using a strategy defined by the
+    * implementor.
+    */
+   void (*sync_routing_table)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKInit *NONNULL_PTR init);
+   /**
+    * Handles the reply of a query we initiated to learn about channels
+    * for a given range of blocks. We can expect to receive one or more
+    * replies to a single query.
+    */
+   struct LDKCResult_NoneLightningErrorZ (*handle_reply_channel_range)(const void *this_arg, struct LDKPublicKey their_node_id, struct LDKReplyChannelRange msg);
+   /**
+    * Handles the reply of a query we initiated asking for routing gossip
+    * messages for a list of channels. We should receive this message when
+    * a node has completed its best effort to send us the pertaining routing
+    * gossip messages.
+    */
+   struct LDKCResult_NoneLightningErrorZ (*handle_reply_short_channel_ids_end)(const void *this_arg, struct LDKPublicKey their_node_id, struct LDKReplyShortChannelIdsEnd msg);
+   /**
+    * Handles when a peer asks us to send a list of short_channel_ids
+    * for the requested range of blocks.
+    */
+   struct LDKCResult_NoneLightningErrorZ (*handle_query_channel_range)(const void *this_arg, struct LDKPublicKey their_node_id, struct LDKQueryChannelRange msg);
+   /**
+    * Handles when a peer asks us to send routing gossip messages for a
+    * list of short_channel_ids.
+    */
+   struct LDKCResult_NoneLightningErrorZ (*handle_query_short_channel_ids)(const void *this_arg, struct LDKPublicKey their_node_id, struct LDKQueryShortChannelIds msg);
+   struct LDKMessageSendEventsProvider MessageSendEventsProvider;
+   void (*free)(void *this_arg);
+} LDKRoutingMessageHandler;
+
+
+
+/**
+ * Provides references to trait impls which handle different types of messages.
+ */
+typedef struct MUST_USE_STRUCT LDKMessageHandler {
+   /**
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
+    */
+   LDKnativeMessageHandler *inner;
+   bool is_owned;
+} LDKMessageHandler;
+
+/**
+ * Provides an object which can be used to send data to and which uniquely identifies a connection
+ * to a remote host. You will need to be able to generate multiple of these which meet Eq and
+ * implement Hash to meet the PeerManager API.
+ *
+ * For efficiency, Clone should be relatively cheap for this type.
+ *
+ * You probably want to just extend an int and put a file descriptor in a struct and implement
+ * send_data. Note that if you are using a higher-level net library that may call close() itself,
+ * be careful to ensure you don't have races whereby you might register a new connection with an
+ * fd which is the same as a previous one which has yet to be removed via
+ * PeerManager::socket_disconnected().
+ */
+typedef struct LDKSocketDescriptor {
+   void *this_arg;
+   /**
+    * Attempts to send some data from the given slice to the peer.
+    *
+    * Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
+    * Note that in the disconnected case, socket_disconnected must still fire and further write
+    * attempts may occur until that time.
+    *
+    * If the returned size is smaller than data.len(), a write_available event must
+    * trigger the next time more data can be written. Additionally, until the a send_data event
+    * completes fully, no further read_events should trigger on the same peer!
+    *
+    * If a read_event on this descriptor had previously returned true (indicating that read
+    * events should be paused to prevent DoS in the send buffer), resume_read may be set
+    * indicating that read events on this descriptor should resume. A resume_read of false does
+    * *not* imply that further read events should be paused.
+    */
+   uintptr_t (*send_data)(void *this_arg, struct LDKu8slice data, bool resume_read);
+   /**
+    * Disconnect the socket pointed to by this SocketDescriptor. Once this function returns, no
+    * more calls to write_buffer_space_avail, read_event or socket_disconnected may be made with
+    * this descriptor. No socket_disconnected call should be generated as a result of this call,
+    * though races may occur whereby disconnect_socket is called after a call to
+    * socket_disconnected but prior to socket_disconnected returning.
+    */
+   void (*disconnect_socket)(void *this_arg);
+   bool (*eq)(const void *this_arg, const struct LDKSocketDescriptor *NONNULL_PTR other_arg);
+   uint64_t (*hash)(const void *this_arg);
+   void *(*clone)(const void *this_arg);
+   void (*free)(void *this_arg);
+} LDKSocketDescriptor;
+
+
+
+/**
+ * A PeerManager manages a set of peers, described by their SocketDescriptor and marshalls socket
+ * events into messages which it passes on to its MessageHandlers.
+ *
+ * Rather than using a plain PeerManager, it is preferable to use either a SimpleArcPeerManager
+ * a SimpleRefPeerManager, for conciseness. See their documentation for more details, but
+ * essentially you should default to using a SimpleRefPeerManager, and use a
+ * SimpleArcPeerManager when you require a PeerManager with a static lifetime, such as when
+ * you're using lightning-net-tokio.
+ */
+typedef struct MUST_USE_STRUCT LDKPeerManager {
+   /**
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
+    */
+   LDKnativePeerManager *inner;
+   bool is_owned;
+} LDKPeerManager;
+
+
+
+/**
+ * Static channel fields used to build transactions given per-commitment fields, organized by
+ * broadcaster/countersignatory.
+ *
+ * This is derived from the holder/counterparty-organized ChannelTransactionParameters via the
+ * as_holder_broadcastable and as_counterparty_broadcastable functions.
+ */
+typedef struct MUST_USE_STRUCT LDKDirectedChannelTransactionParameters {
+   /**
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
+    */
+   LDKnativeDirectedChannelTransactionParameters *inner;
+   bool is_owned;
+} LDKDirectedChannelTransactionParameters;
+
+
+
+/**
+ * A simple newtype for RwLockReadGuard<'a, NetworkGraph>.
+ * This exists only to make accessing a RwLock<NetworkGraph> possible from
+ * the C bindings, as it can be done directly in Rust code.
+ */
+typedef struct MUST_USE_STRUCT LDKLockedNetworkGraph {
+   /**
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
+    */
+   LDKnativeLockedNetworkGraph *inner;
+   bool is_owned;
+} LDKLockedNetworkGraph;
+
+
+
+/**
+ * Receives and validates network updates from peers,
+ * stores authentic and relevant data as a network graph.
+ * This network graph is then used for routing payments.
+ * Provides interface to help with initial routing sync by
+ * serving historical announcements.
+ */
+typedef struct MUST_USE_STRUCT LDKNetGraphMsgHandler {
+   /**
+    * Nearly everywhere, inner must be non-null, however in places where
+    * the Rust equivalent takes an Option, it may be set to null to indicate None.
+    */
+   LDKnativeNetGraphMsgHandler *inner;
+   bool is_owned;
+} LDKNetGraphMsgHandler;
+
+extern const uintptr_t MAX_BUF_SIZE;
+
+extern const uint64_t MIN_RELAY_FEE_SAT_PER_1000_WEIGHT;
+
+extern const uint64_t CLOSED_CHANNEL_UPDATE_ID;
+
+extern const uintptr_t REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH;
+
+void Transaction_free(struct LDKTransaction _res);
+
+void TxOut_free(struct LDKTxOut _res);
+
+struct LDKTxOut TxOut_clone(const struct LDKTxOut *NONNULL_PTR orig);
+
+struct LDKCResult_SecretKeyErrorZ CResult_SecretKeyErrorZ_ok(struct LDKSecretKey o);
+
+struct LDKCResult_SecretKeyErrorZ CResult_SecretKeyErrorZ_err(enum LDKSecp256k1Error e);
+
+void CResult_SecretKeyErrorZ_free(struct LDKCResult_SecretKeyErrorZ _res);
+
+struct LDKCResult_PublicKeyErrorZ CResult_PublicKeyErrorZ_ok(struct LDKPublicKey o);
+
+struct LDKCResult_PublicKeyErrorZ CResult_PublicKeyErrorZ_err(enum LDKSecp256k1Error e);
+
+void CResult_PublicKeyErrorZ_free(struct LDKCResult_PublicKeyErrorZ _res);
+
+struct LDKCResult_TxCreationKeysDecodeErrorZ CResult_TxCreationKeysDecodeErrorZ_ok(struct LDKTxCreationKeys o);
+
+struct LDKCResult_TxCreationKeysDecodeErrorZ CResult_TxCreationKeysDecodeErrorZ_err(struct LDKDecodeError e);
+
+void CResult_TxCreationKeysDecodeErrorZ_free(struct LDKCResult_TxCreationKeysDecodeErrorZ _res);
+
+struct LDKCResult_TxCreationKeysDecodeErrorZ CResult_TxCreationKeysDecodeErrorZ_clone(const struct LDKCResult_TxCreationKeysDecodeErrorZ *NONNULL_PTR orig);
+
+struct LDKCResult_ChannelPublicKeysDecodeErrorZ CResult_ChannelPublicKeysDecodeErrorZ_ok(struct LDKChannelPublicKeys o);
+
+struct LDKCResult_ChannelPublicKeysDecodeErrorZ CResult_ChannelPublicKeysDecodeErrorZ_err(struct LDKDecodeError e);
+
+void CResult_ChannelPublicKeysDecodeErrorZ_free(struct LDKCResult_ChannelPublicKeysDecodeErrorZ _res);
+
+struct LDKCResult_ChannelPublicKeysDecodeErrorZ CResult_ChannelPublicKeysDecodeErrorZ_clone(const struct LDKCResult_ChannelPublicKeysDecodeErrorZ *NONNULL_PTR orig);
+
+struct LDKCResult_TxCreationKeysErrorZ CResult_TxCreationKeysErrorZ_ok(struct LDKTxCreationKeys o);
+
+struct LDKCResult_TxCreationKeysErrorZ CResult_TxCreationKeysErrorZ_err(enum LDKSecp256k1Error e);
+
+void CResult_TxCreationKeysErrorZ_free(struct LDKCResult_TxCreationKeysErrorZ _res);
+
+struct LDKCResult_HTLCOutputInCommitmentDecodeErrorZ CResult_HTLCOutputInCommitmentDecodeErrorZ_ok(struct LDKHTLCOutputInCommitment o);
+
+struct LDKCResult_HTLCOutputInCommitmentDecodeErrorZ CResult_HTLCOutputInCommitmentDecodeErrorZ_err(struct LDKDecodeError e);
+
+void CResult_HTLCOutputInCommitmentDecodeErrorZ_free(struct LDKCResult_HTLCOutputInCommitmentDecodeErrorZ _res);
+
+struct LDKCResult_HTLCOutputInCommitmentDecodeErrorZ CResult_HTLCOutputInCommitmentDecodeErrorZ_clone(const struct LDKCResult_HTLCOutputInCommitmentDecodeErrorZ *NONNULL_PTR orig);
+
+struct LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZ CResult_CounterpartyChannelTransactionParametersDecodeErrorZ_ok(struct LDKCounterpartyChannelTransactionParameters o);
+
+struct LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZ CResult_CounterpartyChannelTransactionParametersDecodeErrorZ_err(struct LDKDecodeError e);
+
+void CResult_CounterpartyChannelTransactionParametersDecodeErrorZ_free(struct LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZ _res);
+
+struct LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZ CResult_CounterpartyChannelTransactionParametersDecodeErrorZ_clone(const struct LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZ *NONNULL_PTR orig);
+
+struct LDKCResult_ChannelTransactionParametersDecodeErrorZ CResult_ChannelTransactionParametersDecodeErrorZ_ok(struct LDKChannelTransactionParameters o);
+
+struct LDKCResult_ChannelTransactionParametersDecodeErrorZ CResult_ChannelTransactionParametersDecodeErrorZ_err(struct LDKDecodeError e);
+
+void CResult_ChannelTransactionParametersDecodeErrorZ_free(struct LDKCResult_ChannelTransactionParametersDecodeErrorZ _res);
+
+struct LDKCResult_ChannelTransactionParametersDecodeErrorZ CResult_ChannelTransactionParametersDecodeErrorZ_clone(const struct LDKCResult_ChannelTransactionParametersDecodeErrorZ *NONNULL_PTR orig);
+
+void CVec_SignatureZ_free(struct LDKCVec_SignatureZ _res);
+
+struct LDKCResult_HolderCommitmentTransactionDecodeErrorZ CResult_HolderCommitmentTransactionDecodeErrorZ_ok(struct LDKHolderCommitmentTransaction o);
+
+struct LDKCResult_HolderCommitmentTransactionDecodeErrorZ CResult_HolderCommitmentTransactionDecodeErrorZ_err(struct LDKDecodeError e);
+
+void CResult_HolderCommitmentTransactionDecodeErrorZ_free(struct LDKCResult_HolderCommitmentTransactionDecodeErrorZ _res);
+
+struct LDKCResult_HolderCommitmentTransactionDecodeErrorZ CResult_HolderCommitmentTransactionDecodeErrorZ_clone(const struct LDKCResult_HolderCommitmentTransactionDecodeErrorZ *NONNULL_PTR orig);
+
+struct LDKCResult_BuiltCommitmentTransactionDecodeErrorZ CResult_BuiltCommitmentTransactionDecodeErrorZ_ok(struct LDKBuiltCommitmentTransaction o);
+
+struct LDKCResult_BuiltCommitmentTransactionDecodeErrorZ CResult_BuiltCommitmentTransactionDecodeErrorZ_err(struct LDKDecodeError e);
+
+void CResult_BuiltCommitmentTransactionDecodeErrorZ_free(struct LDKCResult_BuiltCommitmentTransactionDecodeErrorZ _res);
+
+struct LDKCResult_BuiltCommitmentTransactionDecodeErrorZ CResult_BuiltCommitmentTransactionDecodeErrorZ_clone(const struct LDKCResult_BuiltCommitmentTransactionDecodeErrorZ *NONNULL_PTR orig);
+
+struct LDKCResult_CommitmentTransactionDecodeErrorZ CResult_CommitmentTransactionDecodeErrorZ_ok(struct LDKCommitmentTransaction o);
+
+struct LDKCResult_CommitmentTransactionDecodeErrorZ CResult_CommitmentTransactionDecodeErrorZ_err(struct LDKDecodeError e);
+
+void CResult_CommitmentTransactionDecodeErrorZ_free(struct LDKCResult_CommitmentTransactionDecodeErrorZ _res);
+
+struct LDKCResult_CommitmentTransactionDecodeErrorZ CResult_CommitmentTransactionDecodeErrorZ_clone(const struct LDKCResult_CommitmentTransactionDecodeErrorZ *NONNULL_PTR orig);
+
+struct LDKCResult_TrustedCommitmentTransactionNoneZ CResult_TrustedCommitmentTransactionNoneZ_ok(struct LDKTrustedCommitmentTransaction o);
+
+struct LDKCResult_TrustedCommitmentTransactionNoneZ CResult_TrustedCommitmentTransactionNoneZ_err(void);
+
+void CResult_TrustedCommitmentTransactionNoneZ_free(struct LDKCResult_TrustedCommitmentTransactionNoneZ _res);
+
+struct LDKCResult_CVec_SignatureZNoneZ CResult_CVec_SignatureZNoneZ_ok(struct LDKCVec_SignatureZ o);
+
+struct LDKCResult_CVec_SignatureZNoneZ CResult_CVec_SignatureZNoneZ_err(void);
+
+void CResult_CVec_SignatureZNoneZ_free(struct LDKCResult_CVec_SignatureZNoneZ _res);
+
+struct LDKCResult_CVec_SignatureZNoneZ CResult_CVec_SignatureZNoneZ_clone(const struct LDKCResult_CVec_SignatureZNoneZ *NONNULL_PTR orig);
+
+void CVec_PublicKeyZ_free(struct LDKCVec_PublicKeyZ _res);
+
+void CVec_u8Z_free(struct LDKCVec_u8Z _res);
+
+struct LDKCResult_CVec_u8ZPeerHandleErrorZ CResult_CVec_u8ZPeerHandleErrorZ_ok(struct LDKCVec_u8Z o);
+
+struct LDKCResult_CVec_u8ZPeerHandleErrorZ CResult_CVec_u8ZPeerHandleErrorZ_err(struct LDKPeerHandleError e);
+
+void CResult_CVec_u8ZPeerHandleErrorZ_free(struct LDKCResult_CVec_u8ZPeerHandleErrorZ _res);
+
+struct LDKCResult_CVec_u8ZPeerHandleErrorZ CResult_CVec_u8ZPeerHandleErrorZ_clone(const struct LDKCResult_CVec_u8ZPeerHandleErrorZ *NONNULL_PTR orig);
+
+struct LDKCResult_NonePeerHandleErrorZ CResult_NonePeerHandleErrorZ_ok(void);
+
+struct LDKCResult_NonePeerHandleErrorZ CResult_NonePeerHandleErrorZ_err(struct LDKPeerHandleError e);
+
+void CResult_NonePeerHandleErrorZ_free(struct LDKCResult_NonePeerHandleErrorZ _res);
+
+struct LDKCResult_NonePeerHandleErrorZ CResult_NonePeerHandleErrorZ_clone(const struct LDKCResult_NonePeerHandleErrorZ *NONNULL_PTR orig);
+
+struct LDKCResult_boolPeerHandleErrorZ CResult_boolPeerHandleErrorZ_ok(bool o);
+
+struct LDKCResult_boolPeerHandleErrorZ CResult_boolPeerHandleErrorZ_err(struct LDKPeerHandleError e);
+
+void CResult_boolPeerHandleErrorZ_free(struct LDKCResult_boolPeerHandleErrorZ _res);
+
+struct LDKCResult_boolPeerHandleErrorZ CResult_boolPeerHandleErrorZ_clone(const struct LDKCResult_boolPeerHandleErrorZ *NONNULL_PTR orig);
+
+struct LDKCResult_InitFeaturesDecodeErrorZ CResult_InitFeaturesDecodeErrorZ_ok(struct LDKInitFeatures o);
+
+struct LDKCResult_InitFeaturesDecodeErrorZ CResult_InitFeaturesDecodeErrorZ_err(struct LDKDecodeError e);
+
+void CResult_InitFeaturesDecodeErrorZ_free(struct LDKCResult_InitFeaturesDecodeErrorZ _res);
+
+struct LDKCResult_NodeFeaturesDecodeErrorZ CResult_NodeFeaturesDecodeErrorZ_ok(struct LDKNodeFeatures o);
+
+struct LDKCResult_NodeFeaturesDecodeErrorZ CResult_NodeFeaturesDecodeErrorZ_err(struct LDKDecodeError e);
+
+void CResult_NodeFeaturesDecodeErrorZ_free(struct LDKCResult_NodeFeaturesDecodeErrorZ _res);
+
+struct LDKCResult_ChannelFeaturesDecodeErrorZ CResult_ChannelFeaturesDecodeErrorZ_ok(struct LDKChannelFeatures o);
+
+struct LDKCResult_ChannelFeaturesDecodeErrorZ CResult_ChannelFeaturesDecodeErrorZ_err(struct LDKDecodeError e);
+
+void CResult_ChannelFeaturesDecodeErrorZ_free(struct LDKCResult_ChannelFeaturesDecodeErrorZ _res);
+
+struct LDKCResult_ChannelConfigDecodeErrorZ CResult_ChannelConfigDecodeErrorZ_ok(struct LDKChannelConfig o);
+
+struct LDKCResult_ChannelConfigDecodeErrorZ CResult_ChannelConfigDecodeErrorZ_err(struct LDKDecodeError e);
+
+void CResult_ChannelConfigDecodeErrorZ_free(struct LDKCResult_ChannelConfigDecodeErrorZ _res);
+
+struct LDKCResult_ChannelConfigDecodeErrorZ CResult_ChannelConfigDecodeErrorZ_clone(const struct LDKCResult_ChannelConfigDecodeErrorZ *NONNULL_PTR orig);
+
+struct LDKCResult_boolLightningErrorZ CResult_boolLightningErrorZ_ok(bool o);
+
+struct LDKCResult_boolLightningErrorZ CResult_boolLightningErrorZ_err(struct LDKLightningError e);
+
+void CResult_boolLightningErrorZ_free(struct LDKCResult_boolLightningErrorZ _res);
+
+struct LDKCResult_boolLightningErrorZ CResult_boolLightningErrorZ_clone(const struct LDKCResult_boolLightningErrorZ *NONNULL_PTR orig);
+
+struct LDKC3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ_clone(const struct LDKC3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ *NONNULL_PTR orig);
+
+struct LDKC3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ_new(struct LDKChannelAnnouncement a, struct LDKChannelUpdate b, struct LDKChannelUpdate c);
+
+void C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ_free(struct LDKC3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ _res);
+
+void CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ_free(struct LDKCVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ _res);
+
+void CVec_NodeAnnouncementZ_free(struct LDKCVec_NodeAnnouncementZ _res);
+
+struct LDKCResult_NoneLightningErrorZ CResult_NoneLightningErrorZ_ok(void);
+
+struct LDKCResult_NoneLightningErrorZ CResult_NoneLightningErrorZ_err(struct LDKLightningError e);
+
+void CResult_NoneLightningErrorZ_free(struct LDKCResult_NoneLightningErrorZ _res);
+
+struct LDKCResult_NoneLightningErrorZ CResult_NoneLightningErrorZ_clone(const struct LDKCResult_NoneLightningErrorZ *NONNULL_PTR orig);
+
+void CVec_MessageSendEventZ_free(struct LDKCVec_MessageSendEventZ _res);
+
+struct LDKCResult_DirectionalChannelInfoDecodeErrorZ CResult_DirectionalChannelInfoDecodeErrorZ_ok(struct LDKDirectionalChannelInfo o);
+
+struct LDKCResult_DirectionalChannelInfoDecodeErrorZ CResult_DirectionalChannelInfoDecodeErrorZ_err(struct LDKDecodeError e);
+
+void CResult_DirectionalChannelInfoDecodeErrorZ_free(struct LDKCResult_DirectionalChannelInfoDecodeErrorZ _res);
+
+struct LDKCResult_DirectionalChannelInfoDecodeErrorZ CResult_DirectionalChannelInfoDecodeErrorZ_clone(const struct LDKCResult_DirectionalChannelInfoDecodeErrorZ *NONNULL_PTR orig);
+
+struct LDKCResult_ChannelInfoDecodeErrorZ CResult_ChannelInfoDecodeErrorZ_ok(struct LDKChannelInfo o);
+
+struct LDKCResult_ChannelInfoDecodeErrorZ CResult_ChannelInfoDecodeErrorZ_err(struct LDKDecodeError e);
+
+void CResult_ChannelInfoDecodeErrorZ_free(struct LDKCResult_ChannelInfoDecodeErrorZ _res);
+
+struct LDKCResult_ChannelInfoDecodeErrorZ CResult_ChannelInfoDecodeErrorZ_clone(const struct LDKCResult_ChannelInfoDecodeErrorZ *NONNULL_PTR orig);
+
+struct LDKCResult_RoutingFeesDecodeErrorZ CResult_RoutingFeesDecodeErrorZ_ok(struct LDKRoutingFees o);
+
+struct LDKCResult_RoutingFeesDecodeErrorZ CResult_RoutingFeesDecodeErrorZ_err(struct LDKDecodeError e);
+
+void CResult_RoutingFeesDecodeErrorZ_free(struct LDKCResult_RoutingFeesDecodeErrorZ _res);
+
+struct LDKCResult_RoutingFeesDecodeErrorZ CResult_RoutingFeesDecodeErrorZ_clone(const struct LDKCResult_RoutingFeesDecodeErrorZ *NONNULL_PTR orig);
+
+void CVec_NetAddressZ_free(struct LDKCVec_NetAddressZ _res);
+
+struct LDKCResult_NodeAnnouncementInfoDecodeErrorZ CResult_NodeAnnouncementInfoDecodeErrorZ_ok(struct LDKNodeAnnouncementInfo o);
+
+struct LDKCResult_NodeAnnouncementInfoDecodeErrorZ CResult_NodeAnnouncementInfoDecodeErrorZ_err(struct LDKDecodeError e);
+
+void CResult_NodeAnnouncementInfoDecodeErrorZ_free(struct LDKCResult_NodeAnnouncementInfoDecodeErrorZ _res);
+
+struct LDKCResult_NodeAnnouncementInfoDecodeErrorZ CResult_NodeAnnouncementInfoDecodeErrorZ_clone(const struct LDKCResult_NodeAnnouncementInfoDecodeErrorZ *NONNULL_PTR orig);
+
+void CVec_u64Z_free(struct LDKCVec_u64Z _res);
+
+struct LDKCResult_NodeInfoDecodeErrorZ CResult_NodeInfoDecodeErrorZ_ok(struct LDKNodeInfo o);
+
+struct LDKCResult_NodeInfoDecodeErrorZ CResult_NodeInfoDecodeErrorZ_err(struct LDKDecodeError e);
+
+void CResult_NodeInfoDecodeErrorZ_free(struct LDKCResult_NodeInfoDecodeErrorZ _res);
+
+struct LDKCResult_NodeInfoDecodeErrorZ CResult_NodeInfoDecodeErrorZ_clone(const struct LDKCResult_NodeInfoDecodeErrorZ *NONNULL_PTR orig);
+
+struct LDKCResult_NetworkGraphDecodeErrorZ CResult_NetworkGraphDecodeErrorZ_ok(struct LDKNetworkGraph o);
+
+struct LDKCResult_NetworkGraphDecodeErrorZ CResult_NetworkGraphDecodeErrorZ_err(struct LDKDecodeError e);
+
+void CResult_NetworkGraphDecodeErrorZ_free(struct LDKCResult_NetworkGraphDecodeErrorZ _res);
+
+struct LDKCResult_NetworkGraphDecodeErrorZ CResult_NetworkGraphDecodeErrorZ_clone(const struct LDKCResult_NetworkGraphDecodeErrorZ *NONNULL_PTR orig);
+
+struct LDKC2Tuple_usizeTransactionZ C2Tuple_usizeTransactionZ_new(uintptr_t a, struct LDKTransaction b);
+
+void C2Tuple_usizeTransactionZ_free(struct LDKC2Tuple_usizeTransactionZ _res);
+
+void CVec_C2Tuple_usizeTransactionZZ_free(struct LDKCVec_C2Tuple_usizeTransactionZZ _res);
+
+struct LDKCResult_NoneChannelMonitorUpdateErrZ CResult_NoneChannelMonitorUpdateErrZ_ok(void);
+
+struct LDKCResult_NoneChannelMonitorUpdateErrZ CResult_NoneChannelMonitorUpdateErrZ_err(enum LDKChannelMonitorUpdateErr e);
+
+void CResult_NoneChannelMonitorUpdateErrZ_free(struct LDKCResult_NoneChannelMonitorUpdateErrZ _res);
+
+struct LDKCResult_NoneChannelMonitorUpdateErrZ CResult_NoneChannelMonitorUpdateErrZ_clone(const struct LDKCResult_NoneChannelMonitorUpdateErrZ *NONNULL_PTR orig);
+
+void CVec_MonitorEventZ_free(struct LDKCVec_MonitorEventZ _res);
+
+void CVec_EventZ_free(struct LDKCVec_EventZ _res);
+
+struct LDKCResult_OutPointDecodeErrorZ CResult_OutPointDecodeErrorZ_ok(struct LDKOutPoint o);
+
+struct LDKCResult_OutPointDecodeErrorZ CResult_OutPointDecodeErrorZ_err(struct LDKDecodeError e);
+
+void CResult_OutPointDecodeErrorZ_free(struct LDKCResult_OutPointDecodeErrorZ _res);
+
+struct LDKCResult_OutPointDecodeErrorZ CResult_OutPointDecodeErrorZ_clone(const struct LDKCResult_OutPointDecodeErrorZ *NONNULL_PTR orig);
+
+struct LDKCResult_ChannelMonitorUpdateDecodeErrorZ CResult_ChannelMonitorUpdateDecodeErrorZ_ok(struct LDKChannelMonitorUpdate o);
+
+struct LDKCResult_ChannelMonitorUpdateDecodeErrorZ CResult_ChannelMonitorUpdateDecodeErrorZ_err(struct LDKDecodeError e);
+
+void CResult_ChannelMonitorUpdateDecodeErrorZ_free(struct LDKCResult_ChannelMonitorUpdateDecodeErrorZ _res);
 
+struct LDKCResult_ChannelMonitorUpdateDecodeErrorZ CResult_ChannelMonitorUpdateDecodeErrorZ_clone(const struct LDKCResult_ChannelMonitorUpdateDecodeErrorZ *NONNULL_PTR orig);
 
+struct LDKCResult_HTLCUpdateDecodeErrorZ CResult_HTLCUpdateDecodeErrorZ_ok(struct LDKHTLCUpdate o);
 
-/**
- * A ping message to be sent or received from a peer
- */
-typedef struct MUST_USE_STRUCT LDKPing {
-   /**
-    * Nearly everywhere, inner must be non-null, however in places where
-    * the Rust equivalent takes an Option, it may be set to null to indicate None.
-    */
-   LDKnativePing *inner;
-   bool is_owned;
-} LDKPing;
+struct LDKCResult_HTLCUpdateDecodeErrorZ CResult_HTLCUpdateDecodeErrorZ_err(struct LDKDecodeError e);
 
+void CResult_HTLCUpdateDecodeErrorZ_free(struct LDKCResult_HTLCUpdateDecodeErrorZ _res);
 
+struct LDKCResult_HTLCUpdateDecodeErrorZ CResult_HTLCUpdateDecodeErrorZ_clone(const struct LDKCResult_HTLCUpdateDecodeErrorZ *NONNULL_PTR orig);
 
-/**
- * A pong message to be sent or received from a peer
- */
-typedef struct MUST_USE_STRUCT LDKPong {
-   /**
-    * Nearly everywhere, inner must be non-null, however in places where
-    * the Rust equivalent takes an Option, it may be set to null to indicate None.
-    */
-   LDKnativePong *inner;
-   bool is_owned;
-} LDKPong;
+struct LDKCResult_NoneMonitorUpdateErrorZ CResult_NoneMonitorUpdateErrorZ_ok(void);
 
+struct LDKCResult_NoneMonitorUpdateErrorZ CResult_NoneMonitorUpdateErrorZ_err(struct LDKMonitorUpdateError e);
 
+void CResult_NoneMonitorUpdateErrorZ_free(struct LDKCResult_NoneMonitorUpdateErrorZ _res);
 
-/**
- * Proof that the sender knows the per-commitment secret of the previous commitment transaction.
- * This is used to convince the recipient that the channel is at a certain commitment
- * number even if they lost that data due to a local failure.  Of course, the peer may lie
- * and even later commitments may have been revoked.
- */
-typedef struct MUST_USE_STRUCT LDKDataLossProtect {
-   /**
-    * Nearly everywhere, inner must be non-null, however in places where
-    * the Rust equivalent takes an Option, it may be set to null to indicate None.
-    */
-   LDKnativeDataLossProtect *inner;
-   bool is_owned;
-} LDKDataLossProtect;
+struct LDKCResult_NoneMonitorUpdateErrorZ CResult_NoneMonitorUpdateErrorZ_clone(const struct LDKCResult_NoneMonitorUpdateErrorZ *NONNULL_PTR orig);
 
+struct LDKC2Tuple_OutPointScriptZ C2Tuple_OutPointScriptZ_clone(const struct LDKC2Tuple_OutPointScriptZ *NONNULL_PTR orig);
 
+struct LDKC2Tuple_OutPointScriptZ C2Tuple_OutPointScriptZ_new(struct LDKOutPoint a, struct LDKCVec_u8Z b);
 
-/**
- * The unsigned part of a node_announcement
- */
-typedef struct MUST_USE_STRUCT LDKUnsignedNodeAnnouncement {
-   /**
-    * Nearly everywhere, inner must be non-null, however in places where
-    * the Rust equivalent takes an Option, it may be set to null to indicate None.
-    */
-   LDKnativeUnsignedNodeAnnouncement *inner;
-   bool is_owned;
-} LDKUnsignedNodeAnnouncement;
+void C2Tuple_OutPointScriptZ_free(struct LDKC2Tuple_OutPointScriptZ _res);
 
+void CVec_TransactionZ_free(struct LDKCVec_TransactionZ _res);
 
+struct LDKC2Tuple_u32TxOutZ C2Tuple_u32TxOutZ_clone(const struct LDKC2Tuple_u32TxOutZ *NONNULL_PTR orig);
 
-/**
- * Features used within a `node_announcement` message.
- */
-typedef struct MUST_USE_STRUCT LDKNodeFeatures {
-   /**
-    * Nearly everywhere, inner must be non-null, however in places where
-    * the Rust equivalent takes an Option, it may be set to null to indicate None.
-    */
-   LDKnativeNodeFeatures *inner;
-   bool is_owned;
-} LDKNodeFeatures;
+struct LDKC2Tuple_u32TxOutZ C2Tuple_u32TxOutZ_new(uint32_t a, struct LDKTxOut b);
 
+void C2Tuple_u32TxOutZ_free(struct LDKC2Tuple_u32TxOutZ _res);
 
+void CVec_C2Tuple_u32TxOutZZ_free(struct LDKCVec_C2Tuple_u32TxOutZZ _res);
 
-/**
- * Features used within a `channel_announcement` message.
- */
-typedef struct MUST_USE_STRUCT LDKChannelFeatures {
-   /**
-    * Nearly everywhere, inner must be non-null, however in places where
-    * the Rust equivalent takes an Option, it may be set to null to indicate None.
-    */
-   LDKnativeChannelFeatures *inner;
-   bool is_owned;
-} LDKChannelFeatures;
+struct LDKC2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ_new(struct LDKThirtyTwoBytes a, struct LDKCVec_C2Tuple_u32TxOutZZ b);
 
+void C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ_free(struct LDKC2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ _res);
 
+void CVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ_free(struct LDKCVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ _res);
 
-/**
- * The unsigned part of a channel_update
- */
-typedef struct MUST_USE_STRUCT LDKUnsignedChannelUpdate {
-   /**
-    * Nearly everywhere, inner must be non-null, however in places where
-    * the Rust equivalent takes an Option, it may be set to null to indicate None.
-    */
-   LDKnativeUnsignedChannelUpdate *inner;
-   bool is_owned;
-} LDKUnsignedChannelUpdate;
+struct LDKC2Tuple_BlockHashChannelMonitorZ C2Tuple_BlockHashChannelMonitorZ_new(struct LDKThirtyTwoBytes a, struct LDKChannelMonitor b);
 
+void C2Tuple_BlockHashChannelMonitorZ_free(struct LDKC2Tuple_BlockHashChannelMonitorZ _res);
 
+struct LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_ok(struct LDKC2Tuple_BlockHashChannelMonitorZ o);
 
-/**
- * A query_channel_range message is used to query a peer for channel
- * UTXOs in a range of blocks. The recipient of a query makes a best
- * effort to reply to the query using one or more reply_channel_range
- * messages.
- */
-typedef struct MUST_USE_STRUCT LDKQueryChannelRange {
-   /**
-    * Nearly everywhere, inner must be non-null, however in places where
-    * the Rust equivalent takes an Option, it may be set to null to indicate None.
-    */
-   LDKnativeQueryChannelRange *inner;
-   bool is_owned;
-} LDKQueryChannelRange;
+struct LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_err(struct LDKDecodeError e);
 
+void CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_free(struct LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ _res);
 
+void CVec_SpendableOutputDescriptorZ_free(struct LDKCVec_SpendableOutputDescriptorZ _res);
 
-/**
- * A reply_channel_range message is a reply to a query_channel_range
- * message. Multiple reply_channel_range messages can be sent in reply
- * to a single query_channel_range message. The query recipient makes a
- * best effort to respond based on their local network view which may
- * not be a perfect view of the network. The short_channel_ids in the
- * reply are encoded. We only support encoding_type=0 uncompressed
- * serialization and do not support encoding_type=1 zlib serialization.
- */
-typedef struct MUST_USE_STRUCT LDKReplyChannelRange {
-   /**
-    * Nearly everywhere, inner must be non-null, however in places where
-    * the Rust equivalent takes an Option, it may be set to null to indicate None.
-    */
-   LDKnativeReplyChannelRange *inner;
-   bool is_owned;
-} LDKReplyChannelRange;
+struct LDKCResult_TxOutAccessErrorZ CResult_TxOutAccessErrorZ_ok(struct LDKTxOut o);
 
-typedef struct LDKCVecTempl_u64 {
-   uint64_t *data;
-   uintptr_t datalen;
-} LDKCVecTempl_u64;
+struct LDKCResult_TxOutAccessErrorZ CResult_TxOutAccessErrorZ_err(enum LDKAccessError e);
 
-typedef LDKCVecTempl_u64 LDKCVec_u64Z;
+void CResult_TxOutAccessErrorZ_free(struct LDKCResult_TxOutAccessErrorZ _res);
 
+struct LDKCResult_TxOutAccessErrorZ CResult_TxOutAccessErrorZ_clone(const struct LDKCResult_TxOutAccessErrorZ *NONNULL_PTR orig);
 
+struct LDKCResult_NoneAPIErrorZ CResult_NoneAPIErrorZ_ok(void);
 
-/**
- * A query_short_channel_ids message is used to query a peer for
- * routing gossip messages related to one or more short_channel_ids.
- * The query recipient will reply with the latest, if available,
- * channel_announcement, channel_update and node_announcement messages
- * it maintains for the requested short_channel_ids followed by a
- * reply_short_channel_ids_end message. The short_channel_ids sent in
- * this query are encoded. We only support encoding_type=0 uncompressed
- * serialization and do not support encoding_type=1 zlib serialization.
- */
-typedef struct MUST_USE_STRUCT LDKQueryShortChannelIds {
-   /**
-    * Nearly everywhere, inner must be non-null, however in places where
-    * the Rust equivalent takes an Option, it may be set to null to indicate None.
-    */
-   LDKnativeQueryShortChannelIds *inner;
-   bool is_owned;
-} LDKQueryShortChannelIds;
+struct LDKCResult_NoneAPIErrorZ CResult_NoneAPIErrorZ_err(struct LDKAPIError e);
 
+void CResult_NoneAPIErrorZ_free(struct LDKCResult_NoneAPIErrorZ _res);
 
+struct LDKCResult_NoneAPIErrorZ CResult_NoneAPIErrorZ_clone(const struct LDKCResult_NoneAPIErrorZ *NONNULL_PTR orig);
 
-/**
- * A reply_short_channel_ids_end message is sent as a reply to a
- * query_short_channel_ids message. The query recipient makes a best
- * effort to respond based on their local network view which may not be
- * a perfect view of the network.
- */
-typedef struct MUST_USE_STRUCT LDKReplyShortChannelIdsEnd {
-   /**
-    * Nearly everywhere, inner must be non-null, however in places where
-    * the Rust equivalent takes an Option, it may be set to null to indicate None.
-    */
-   LDKnativeReplyShortChannelIdsEnd *inner;
-   bool is_owned;
-} LDKReplyShortChannelIdsEnd;
+void CVec_CResult_NoneAPIErrorZZ_free(struct LDKCVec_CResult_NoneAPIErrorZZ _res);
 
+void CVec_APIErrorZ_free(struct LDKCVec_APIErrorZ _res);
 
+void CVec_ChannelDetailsZ_free(struct LDKCVec_ChannelDetailsZ _res);
 
-/**
- * A gossip_timestamp_filter message is used by a node to request
- * gossip relay for messages in the requested time range when the
- * gossip_queries feature has been negotiated.
- */
-typedef struct MUST_USE_STRUCT LDKGossipTimestampFilter {
-   /**
-    * Nearly everywhere, inner must be non-null, however in places where
-    * the Rust equivalent takes an Option, it may be set to null to indicate None.
-    */
-   LDKnativeGossipTimestampFilter *inner;
-   bool is_owned;
-} LDKGossipTimestampFilter;
+struct LDKCResult_NonePaymentSendFailureZ CResult_NonePaymentSendFailureZ_ok(void);
 
-typedef struct LDKCVecTempl_UpdateAddHTLC {
-   LDKUpdateAddHTLC *data;
-   uintptr_t datalen;
-} LDKCVecTempl_UpdateAddHTLC;
+struct LDKCResult_NonePaymentSendFailureZ CResult_NonePaymentSendFailureZ_err(struct LDKPaymentSendFailure e);
 
-typedef LDKCVecTempl_UpdateAddHTLC LDKCVec_UpdateAddHTLCZ;
+void CResult_NonePaymentSendFailureZ_free(struct LDKCResult_NonePaymentSendFailureZ _res);
 
-typedef struct LDKCVecTempl_UpdateFulfillHTLC {
-   LDKUpdateFulfillHTLC *data;
-   uintptr_t datalen;
-} LDKCVecTempl_UpdateFulfillHTLC;
+struct LDKCResult_NonePaymentSendFailureZ CResult_NonePaymentSendFailureZ_clone(const struct LDKCResult_NonePaymentSendFailureZ *NONNULL_PTR orig);
 
-typedef LDKCVecTempl_UpdateFulfillHTLC LDKCVec_UpdateFulfillHTLCZ;
+void CVec_ChannelMonitorZ_free(struct LDKCVec_ChannelMonitorZ _res);
 
-typedef struct LDKCVecTempl_UpdateFailHTLC {
-   LDKUpdateFailHTLC *data;
-   uintptr_t datalen;
-} LDKCVecTempl_UpdateFailHTLC;
+struct LDKC2Tuple_BlockHashChannelManagerZ C2Tuple_BlockHashChannelManagerZ_new(struct LDKThirtyTwoBytes a, struct LDKChannelManager b);
 
-typedef LDKCVecTempl_UpdateFailHTLC LDKCVec_UpdateFailHTLCZ;
+void C2Tuple_BlockHashChannelManagerZ_free(struct LDKC2Tuple_BlockHashChannelManagerZ _res);
 
-typedef struct LDKCVecTempl_UpdateFailMalformedHTLC {
-   LDKUpdateFailMalformedHTLC *data;
-   uintptr_t datalen;
-} LDKCVecTempl_UpdateFailMalformedHTLC;
+struct LDKCResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_ok(struct LDKC2Tuple_BlockHashChannelManagerZ o);
 
-typedef LDKCVecTempl_UpdateFailMalformedHTLC LDKCVec_UpdateFailMalformedHTLCZ;
+struct LDKCResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_err(struct LDKDecodeError e);
 
-typedef union LDKCResultPtr_bool__LightningError {
-   bool *result;
-   LDKLightningError *err;
-} LDKCResultPtr_bool__LightningError;
+void CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_free(struct LDKCResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ _res);
 
-typedef struct LDKCResultTempl_bool__LightningError {
-   LDKCResultPtr_bool__LightningError contents;
-   bool result_ok;
-} LDKCResultTempl_bool__LightningError;
+struct LDKCResult_SpendableOutputDescriptorDecodeErrorZ CResult_SpendableOutputDescriptorDecodeErrorZ_ok(struct LDKSpendableOutputDescriptor o);
 
-typedef LDKCResultTempl_bool__LightningError LDKCResult_boolLightningErrorZ;
+struct LDKCResult_SpendableOutputDescriptorDecodeErrorZ CResult_SpendableOutputDescriptorDecodeErrorZ_err(struct LDKDecodeError e);
 
-typedef struct LDKCVecTempl_C3TupleTempl_ChannelAnnouncement__ChannelUpdate__ChannelUpdate {
-   LDKC3TupleTempl_ChannelAnnouncement__ChannelUpdate__ChannelUpdate *data;
-   uintptr_t datalen;
-} LDKCVecTempl_C3TupleTempl_ChannelAnnouncement__ChannelUpdate__ChannelUpdate;
+void CResult_SpendableOutputDescriptorDecodeErrorZ_free(struct LDKCResult_SpendableOutputDescriptorDecodeErrorZ _res);
 
-typedef LDKCVecTempl_C3TupleTempl_ChannelAnnouncement__ChannelUpdate__ChannelUpdate LDKCVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ;
+struct LDKCResult_SpendableOutputDescriptorDecodeErrorZ CResult_SpendableOutputDescriptorDecodeErrorZ_clone(const struct LDKCResult_SpendableOutputDescriptorDecodeErrorZ *NONNULL_PTR orig);
 
-typedef struct LDKCVecTempl_NodeAnnouncement {
-   LDKNodeAnnouncement *data;
-   uintptr_t datalen;
-} LDKCVecTempl_NodeAnnouncement;
+struct LDKC2Tuple_SignatureCVec_SignatureZZ C2Tuple_SignatureCVec_SignatureZZ_clone(const struct LDKC2Tuple_SignatureCVec_SignatureZZ *NONNULL_PTR orig);
 
-typedef LDKCVecTempl_NodeAnnouncement LDKCVec_NodeAnnouncementZ;
+struct LDKC2Tuple_SignatureCVec_SignatureZZ C2Tuple_SignatureCVec_SignatureZZ_new(struct LDKSignature a, struct LDKCVec_SignatureZ b);
 
-/**
- * A trait to describe an object which can receive routing messages.
- */
-typedef struct LDKRoutingMessageHandler {
-   void *this_arg;
-   /**
-    * Handle an incoming node_announcement message, returning true if it should be forwarded on,
-    * false or returning an Err otherwise.
-    */
-   LDKCResult_boolLightningErrorZ (*handle_node_announcement)(const void *this_arg, const LDKNodeAnnouncement *msg);
-   /**
-    * Handle a channel_announcement message, returning true if it should be forwarded on, false
-    * or returning an Err otherwise.
-    */
-   LDKCResult_boolLightningErrorZ (*handle_channel_announcement)(const void *this_arg, const LDKChannelAnnouncement *msg);
-   /**
-    * Handle an incoming channel_update message, returning true if it should be forwarded on,
-    * false or returning an Err otherwise.
-    */
-   LDKCResult_boolLightningErrorZ (*handle_channel_update)(const void *this_arg, const LDKChannelUpdate *msg);
-   /**
-    * Handle some updates to the route graph that we learned due to an outbound failed payment.
-    */
-   void (*handle_htlc_fail_channel_update)(const void *this_arg, const LDKHTLCFailChannelUpdate *update);
-   /**
-    * Gets a subset of the channel announcements and updates required to dump our routing table
-    * to a remote node, starting at the short_channel_id indicated by starting_point and
-    * including the batch_amount entries immediately higher in numerical value than starting_point.
-    */
-   LDKCVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ (*get_next_channel_announcements)(const void *this_arg, uint64_t starting_point, uint8_t batch_amount);
-   /**
-    * Gets a subset of the node announcements required to dump our routing table to a remote node,
-    * starting at the node *after* the provided publickey and including batch_amount entries
-    * immediately higher (as defined by <PublicKey as Ord>::cmp) than starting_point.
-    * If None is provided for starting_point, we start at the first node.
-    */
-   LDKCVec_NodeAnnouncementZ (*get_next_node_announcements)(const void *this_arg, LDKPublicKey starting_point, uint8_t batch_amount);
-   /**
-    * Returns whether a full sync should be requested from a peer.
-    */
-   bool (*should_request_full_sync)(const void *this_arg, LDKPublicKey node_id);
-   void (*free)(void *this_arg);
-} LDKRoutingMessageHandler;
+void C2Tuple_SignatureCVec_SignatureZZ_free(struct LDKC2Tuple_SignatureCVec_SignatureZZ _res);
 
+struct LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ_ok(struct LDKC2Tuple_SignatureCVec_SignatureZZ o);
 
+struct LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ_err(void);
 
-/**
- * Provides references to trait impls which handle different types of messages.
- */
-typedef struct MUST_USE_STRUCT LDKMessageHandler {
-   /**
-    * Nearly everywhere, inner must be non-null, however in places where
-    * the Rust equivalent takes an Option, it may be set to null to indicate None.
-    */
-   LDKnativeMessageHandler *inner;
-   bool is_owned;
-} LDKMessageHandler;
+void CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ_free(struct LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ _res);
 
-/**
- * Provides an object which can be used to send data to and which uniquely identifies a connection
- * to a remote host. You will need to be able to generate multiple of these which meet Eq and
- * implement Hash to meet the PeerManager API.
- *
- * For efficiency, Clone should be relatively cheap for this type.
- *
- * You probably want to just extend an int and put a file descriptor in a struct and implement
- * send_data. Note that if you are using a higher-level net library that may call close() itself,
- * be careful to ensure you don't have races whereby you might register a new connection with an
- * fd which is the same as a previous one which has yet to be removed via
- * PeerManager::socket_disconnected().
- */
-typedef struct LDKSocketDescriptor {
-   void *this_arg;
-   /**
-    * Attempts to send some data from the given slice to the peer.
-    *
-    * Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
-    * Note that in the disconnected case, socket_disconnected must still fire and further write
-    * attempts may occur until that time.
-    *
-    * If the returned size is smaller than data.len(), a write_available event must
-    * trigger the next time more data can be written. Additionally, until the a send_data event
-    * completes fully, no further read_events should trigger on the same peer!
-    *
-    * If a read_event on this descriptor had previously returned true (indicating that read
-    * events should be paused to prevent DoS in the send buffer), resume_read may be set
-    * indicating that read events on this descriptor should resume. A resume_read of false does
-    * *not* imply that further read events should be paused.
-    */
-   uintptr_t (*send_data)(void *this_arg, LDKu8slice data, bool resume_read);
-   /**
-    * Disconnect the socket pointed to by this SocketDescriptor. Once this function returns, no
-    * more calls to write_buffer_space_avail, read_event or socket_disconnected may be made with
-    * this descriptor. No socket_disconnected call should be generated as a result of this call,
-    * though races may occur whereby disconnect_socket is called after a call to
-    * socket_disconnected but prior to socket_disconnected returning.
-    */
-   void (*disconnect_socket)(void *this_arg);
-   bool (*eq)(const void *this_arg, const LDKSocketDescriptor *other_arg);
-   uint64_t (*hash)(const void *this_arg);
-   void *(*clone)(const void *this_arg);
-   void (*free)(void *this_arg);
-} LDKSocketDescriptor;
+struct LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ_clone(const struct LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ *NONNULL_PTR orig);
+
+struct LDKCResult_SignatureNoneZ CResult_SignatureNoneZ_ok(struct LDKSignature o);
 
+struct LDKCResult_SignatureNoneZ CResult_SignatureNoneZ_err(void);
 
+void CResult_SignatureNoneZ_free(struct LDKCResult_SignatureNoneZ _res);
 
-/**
- * A PeerManager manages a set of peers, described by their SocketDescriptor and marshalls socket
- * events into messages which it passes on to its MessageHandlers.
- *
- * Rather than using a plain PeerManager, it is preferable to use either a SimpleArcPeerManager
- * a SimpleRefPeerManager, for conciseness. See their documentation for more details, but
- * essentially you should default to using a SimpleRefPeerManager, and use a
- * SimpleArcPeerManager when you require a PeerManager with a static lifetime, such as when
- * you're using lightning-net-tokio.
- */
-typedef struct MUST_USE_STRUCT LDKPeerManager {
-   /**
-    * Nearly everywhere, inner must be non-null, however in places where
-    * the Rust equivalent takes an Option, it may be set to null to indicate None.
-    */
-   LDKnativePeerManager *inner;
-   bool is_owned;
-} LDKPeerManager;
+struct LDKCResult_SignatureNoneZ CResult_SignatureNoneZ_clone(const struct LDKCResult_SignatureNoneZ *NONNULL_PTR orig);
 
-typedef struct LDKCVecTempl_PublicKey {
-   LDKPublicKey *data;
-   uintptr_t datalen;
-} LDKCVecTempl_PublicKey;
+struct LDKCResult_SignDecodeErrorZ CResult_SignDecodeErrorZ_ok(struct LDKSign o);
 
-typedef LDKCVecTempl_PublicKey LDKCVec_PublicKeyZ;
+struct LDKCResult_SignDecodeErrorZ CResult_SignDecodeErrorZ_err(struct LDKDecodeError e);
 
-typedef union LDKCResultPtr_CVecTempl_u8_____PeerHandleError {
-   LDKCVecTempl_u8 *result;
-   LDKPeerHandleError *err;
-} LDKCResultPtr_CVecTempl_u8_____PeerHandleError;
+void CResult_SignDecodeErrorZ_free(struct LDKCResult_SignDecodeErrorZ _res);
 
-typedef struct LDKCResultTempl_CVecTempl_u8_____PeerHandleError {
-   LDKCResultPtr_CVecTempl_u8_____PeerHandleError contents;
-   bool result_ok;
-} LDKCResultTempl_CVecTempl_u8_____PeerHandleError;
+struct LDKCResult_SignDecodeErrorZ CResult_SignDecodeErrorZ_clone(const struct LDKCResult_SignDecodeErrorZ *NONNULL_PTR orig);
 
-typedef LDKCResultTempl_CVecTempl_u8_____PeerHandleError LDKCResult_CVec_u8ZPeerHandleErrorZ;
+void CVec_CVec_u8ZZ_free(struct LDKCVec_CVec_u8ZZ _res);
 
-typedef union LDKCResultPtr_bool__PeerHandleError {
-   bool *result;
-   LDKPeerHandleError *err;
-} LDKCResultPtr_bool__PeerHandleError;
+struct LDKCResult_CVec_CVec_u8ZZNoneZ CResult_CVec_CVec_u8ZZNoneZ_ok(struct LDKCVec_CVec_u8ZZ o);
 
-typedef struct LDKCResultTempl_bool__PeerHandleError {
-   LDKCResultPtr_bool__PeerHandleError contents;
-   bool result_ok;
-} LDKCResultTempl_bool__PeerHandleError;
+struct LDKCResult_CVec_CVec_u8ZZNoneZ CResult_CVec_CVec_u8ZZNoneZ_err(void);
 
-typedef LDKCResultTempl_bool__PeerHandleError LDKCResult_boolPeerHandleErrorZ;
+void CResult_CVec_CVec_u8ZZNoneZ_free(struct LDKCResult_CVec_CVec_u8ZZNoneZ _res);
 
-typedef union LDKCResultPtr_SecretKey__Secp256k1Error {
-   LDKSecretKey *result;
-   LDKSecp256k1Error *err;
-} LDKCResultPtr_SecretKey__Secp256k1Error;
+struct LDKCResult_CVec_CVec_u8ZZNoneZ CResult_CVec_CVec_u8ZZNoneZ_clone(const struct LDKCResult_CVec_CVec_u8ZZNoneZ *NONNULL_PTR orig);
 
-typedef struct LDKCResultTempl_SecretKey__Secp256k1Error {
-   LDKCResultPtr_SecretKey__Secp256k1Error contents;
-   bool result_ok;
-} LDKCResultTempl_SecretKey__Secp256k1Error;
+struct LDKCResult_InMemorySignerDecodeErrorZ CResult_InMemorySignerDecodeErrorZ_ok(struct LDKInMemorySigner o);
 
-typedef LDKCResultTempl_SecretKey__Secp256k1Error LDKCResult_SecretKeySecpErrorZ;
+struct LDKCResult_InMemorySignerDecodeErrorZ CResult_InMemorySignerDecodeErrorZ_err(struct LDKDecodeError e);
 
-typedef union LDKCResultPtr_PublicKey__Secp256k1Error {
-   LDKPublicKey *result;
-   LDKSecp256k1Error *err;
-} LDKCResultPtr_PublicKey__Secp256k1Error;
+void CResult_InMemorySignerDecodeErrorZ_free(struct LDKCResult_InMemorySignerDecodeErrorZ _res);
 
-typedef struct LDKCResultTempl_PublicKey__Secp256k1Error {
-   LDKCResultPtr_PublicKey__Secp256k1Error contents;
-   bool result_ok;
-} LDKCResultTempl_PublicKey__Secp256k1Error;
+struct LDKCResult_InMemorySignerDecodeErrorZ CResult_InMemorySignerDecodeErrorZ_clone(const struct LDKCResult_InMemorySignerDecodeErrorZ *NONNULL_PTR orig);
 
-typedef LDKCResultTempl_PublicKey__Secp256k1Error LDKCResult_PublicKeySecpErrorZ;
+void CVec_TxOutZ_free(struct LDKCVec_TxOutZ _res);
 
+struct LDKCResult_TransactionNoneZ CResult_TransactionNoneZ_ok(struct LDKTransaction o);
 
+struct LDKCResult_TransactionNoneZ CResult_TransactionNoneZ_err(void);
 
-/**
- * The set of public keys which are used in the creation of one commitment transaction.
- * These are derived from the channel base keys and per-commitment data.
- *
- * A broadcaster key is provided from potential broadcaster of the computed transaction.
- * A countersignatory key is coming from a protocol participant unable to broadcast the
- * transaction.
- *
- * These keys are assumed to be good, either because the code derived them from
- * channel basepoints via the new function, or they were obtained via
- * PreCalculatedTxCreationKeys.trust_key_derivation because we trusted the source of the
- * pre-calculated keys.
- */
-typedef struct MUST_USE_STRUCT LDKTxCreationKeys {
-   /**
-    * Nearly everywhere, inner must be non-null, however in places where
-    * the Rust equivalent takes an Option, it may be set to null to indicate None.
-    */
-   LDKnativeTxCreationKeys *inner;
-   bool is_owned;
-} LDKTxCreationKeys;
+void CResult_TransactionNoneZ_free(struct LDKCResult_TransactionNoneZ _res);
 
-typedef union LDKCResultPtr_TxCreationKeys__Secp256k1Error {
-   LDKTxCreationKeys *result;
-   LDKSecp256k1Error *err;
-} LDKCResultPtr_TxCreationKeys__Secp256k1Error;
+void CVec_RouteHopZ_free(struct LDKCVec_RouteHopZ _res);
 
-typedef struct LDKCResultTempl_TxCreationKeys__Secp256k1Error {
-   LDKCResultPtr_TxCreationKeys__Secp256k1Error contents;
-   bool result_ok;
-} LDKCResultTempl_TxCreationKeys__Secp256k1Error;
+void CVec_CVec_RouteHopZZ_free(struct LDKCVec_CVec_RouteHopZZ _res);
 
-typedef LDKCResultTempl_TxCreationKeys__Secp256k1Error LDKCResult_TxCreationKeysSecpErrorZ;
+struct LDKCResult_RouteDecodeErrorZ CResult_RouteDecodeErrorZ_ok(struct LDKRoute o);
 
-typedef struct LDKCVecTempl_C2TupleTempl_HTLCOutputInCommitment__Signature {
-   LDKC2TupleTempl_HTLCOutputInCommitment__Signature *data;
-   uintptr_t datalen;
-} LDKCVecTempl_C2TupleTempl_HTLCOutputInCommitment__Signature;
+struct LDKCResult_RouteDecodeErrorZ CResult_RouteDecodeErrorZ_err(struct LDKDecodeError e);
 
-typedef LDKCVecTempl_C2TupleTempl_HTLCOutputInCommitment__Signature LDKCVec_C2Tuple_HTLCOutputInCommitmentSignatureZZ;
+void CResult_RouteDecodeErrorZ_free(struct LDKCResult_RouteDecodeErrorZ _res);
 
+struct LDKCResult_RouteDecodeErrorZ CResult_RouteDecodeErrorZ_clone(const struct LDKCResult_RouteDecodeErrorZ *NONNULL_PTR orig);
 
+void CVec_RouteHintZ_free(struct LDKCVec_RouteHintZ _res);
 
-/**
- * A hop in a route
- */
-typedef struct MUST_USE_STRUCT LDKRouteHop {
-   /**
-    * Nearly everywhere, inner must be non-null, however in places where
-    * the Rust equivalent takes an Option, it may be set to null to indicate None.
-    */
-   LDKnativeRouteHop *inner;
-   bool is_owned;
-} LDKRouteHop;
+struct LDKCResult_RouteLightningErrorZ CResult_RouteLightningErrorZ_ok(struct LDKRoute o);
 
-typedef struct LDKCVecTempl_RouteHop {
-   LDKRouteHop *data;
-   uintptr_t datalen;
-} LDKCVecTempl_RouteHop;
+struct LDKCResult_RouteLightningErrorZ CResult_RouteLightningErrorZ_err(struct LDKLightningError e);
 
-typedef struct LDKCVecTempl_CVecTempl_RouteHop {
-   LDKCVecTempl_RouteHop *data;
-   uintptr_t datalen;
-} LDKCVecTempl_CVecTempl_RouteHop;
+void CResult_RouteLightningErrorZ_free(struct LDKCResult_RouteLightningErrorZ _res);
 
-typedef LDKCVecTempl_CVecTempl_RouteHop LDKCVec_CVec_RouteHopZZ;
+struct LDKCResult_RouteLightningErrorZ CResult_RouteLightningErrorZ_clone(const struct LDKCResult_RouteLightningErrorZ *NONNULL_PTR orig);
 
+struct LDKCResult_NetAddressu8Z CResult_NetAddressu8Z_ok(struct LDKNetAddress o);
 
+struct LDKCResult_NetAddressu8Z CResult_NetAddressu8Z_err(uint8_t e);
 
-/**
- * A channel descriptor which provides a last-hop route to get_route
- */
-typedef struct MUST_USE_STRUCT LDKRouteHint {
-   /**
-    * Nearly everywhere, inner must be non-null, however in places where
-    * the Rust equivalent takes an Option, it may be set to null to indicate None.
-    */
-   LDKnativeRouteHint *inner;
-   bool is_owned;
-} LDKRouteHint;
+void CResult_NetAddressu8Z_free(struct LDKCResult_NetAddressu8Z _res);
 
+struct LDKCResult_NetAddressu8Z CResult_NetAddressu8Z_clone(const struct LDKCResult_NetAddressu8Z *NONNULL_PTR orig);
 
+struct LDKCResult_CResult_NetAddressu8ZDecodeErrorZ CResult_CResult_NetAddressu8ZDecodeErrorZ_ok(struct LDKCResult_NetAddressu8Z o);
 
-/**
- * Fees for routing via a given channel or a node
- */
-typedef struct MUST_USE_STRUCT LDKRoutingFees {
-   /**
-    * Nearly everywhere, inner must be non-null, however in places where
-    * the Rust equivalent takes an Option, it may be set to null to indicate None.
-    */
-   LDKnativeRoutingFees *inner;
-   bool is_owned;
-} LDKRoutingFees;
+struct LDKCResult_CResult_NetAddressu8ZDecodeErrorZ CResult_CResult_NetAddressu8ZDecodeErrorZ_err(struct LDKDecodeError e);
 
-typedef union LDKCResultPtr_Route__LightningError {
-   LDKRoute *result;
-   LDKLightningError *err;
-} LDKCResultPtr_Route__LightningError;
+void CResult_CResult_NetAddressu8ZDecodeErrorZ_free(struct LDKCResult_CResult_NetAddressu8ZDecodeErrorZ _res);
 
-typedef struct LDKCResultTempl_Route__LightningError {
-   LDKCResultPtr_Route__LightningError contents;
-   bool result_ok;
-} LDKCResultTempl_Route__LightningError;
+struct LDKCResult_CResult_NetAddressu8ZDecodeErrorZ CResult_CResult_NetAddressu8ZDecodeErrorZ_clone(const struct LDKCResult_CResult_NetAddressu8ZDecodeErrorZ *NONNULL_PTR orig);
 
-typedef LDKCResultTempl_Route__LightningError LDKCResult_RouteLightningErrorZ;
+void CVec_UpdateAddHTLCZ_free(struct LDKCVec_UpdateAddHTLCZ _res);
 
+void CVec_UpdateFulfillHTLCZ_free(struct LDKCVec_UpdateFulfillHTLCZ _res);
 
+void CVec_UpdateFailHTLCZ_free(struct LDKCVec_UpdateFailHTLCZ _res);
 
-/**
- * Represents the network as nodes and channels between them
- */
-typedef struct MUST_USE_STRUCT LDKNetworkGraph {
-   /**
-    * Nearly everywhere, inner must be non-null, however in places where
-    * the Rust equivalent takes an Option, it may be set to null to indicate None.
-    */
-   LDKnativeNetworkGraph *inner;
-   bool is_owned;
-} LDKNetworkGraph;
+void CVec_UpdateFailMalformedHTLCZ_free(struct LDKCVec_UpdateFailMalformedHTLCZ _res);
 
-typedef struct LDKCVecTempl_RouteHint {
-   LDKRouteHint *data;
-   uintptr_t datalen;
-} LDKCVecTempl_RouteHint;
+struct LDKCResult_AcceptChannelDecodeErrorZ CResult_AcceptChannelDecodeErrorZ_ok(struct LDKAcceptChannel o);
 
-typedef LDKCVecTempl_RouteHint LDKCVec_RouteHintZ;
+struct LDKCResult_AcceptChannelDecodeErrorZ CResult_AcceptChannelDecodeErrorZ_err(struct LDKDecodeError e);
 
+void CResult_AcceptChannelDecodeErrorZ_free(struct LDKCResult_AcceptChannelDecodeErrorZ _res);
 
+struct LDKCResult_AcceptChannelDecodeErrorZ CResult_AcceptChannelDecodeErrorZ_clone(const struct LDKCResult_AcceptChannelDecodeErrorZ *NONNULL_PTR orig);
 
-/**
- * A simple newtype for RwLockReadGuard<'a, NetworkGraph>.
- * This exists only to make accessing a RwLock<NetworkGraph> possible from
- * the C bindings, as it can be done directly in Rust code.
- */
-typedef struct MUST_USE_STRUCT LDKLockedNetworkGraph {
-   /**
-    * Nearly everywhere, inner must be non-null, however in places where
-    * the Rust equivalent takes an Option, it may be set to null to indicate None.
-    */
-   LDKnativeLockedNetworkGraph *inner;
-   bool is_owned;
-} LDKLockedNetworkGraph;
+struct LDKCResult_AnnouncementSignaturesDecodeErrorZ CResult_AnnouncementSignaturesDecodeErrorZ_ok(struct LDKAnnouncementSignatures o);
 
+struct LDKCResult_AnnouncementSignaturesDecodeErrorZ CResult_AnnouncementSignaturesDecodeErrorZ_err(struct LDKDecodeError e);
 
+void CResult_AnnouncementSignaturesDecodeErrorZ_free(struct LDKCResult_AnnouncementSignaturesDecodeErrorZ _res);
 
-/**
- * Receives and validates network updates from peers,
- * stores authentic and relevant data as a network graph.
- * This network graph is then used for routing payments.
- * Provides interface to help with initial routing sync by
- * serving historical announcements.
- */
-typedef struct MUST_USE_STRUCT LDKNetGraphMsgHandler {
-   /**
-    * Nearly everywhere, inner must be non-null, however in places where
-    * the Rust equivalent takes an Option, it may be set to null to indicate None.
-    */
-   LDKnativeNetGraphMsgHandler *inner;
-   bool is_owned;
-} LDKNetGraphMsgHandler;
+struct LDKCResult_AnnouncementSignaturesDecodeErrorZ CResult_AnnouncementSignaturesDecodeErrorZ_clone(const struct LDKCResult_AnnouncementSignaturesDecodeErrorZ *NONNULL_PTR orig);
 
+struct LDKCResult_ChannelReestablishDecodeErrorZ CResult_ChannelReestablishDecodeErrorZ_ok(struct LDKChannelReestablish o);
 
+struct LDKCResult_ChannelReestablishDecodeErrorZ CResult_ChannelReestablishDecodeErrorZ_err(struct LDKDecodeError e);
 
-/**
- * Details about one direction of a channel. Received
- * within a channel update.
- */
-typedef struct MUST_USE_STRUCT LDKDirectionalChannelInfo {
-   /**
-    * Nearly everywhere, inner must be non-null, however in places where
-    * the Rust equivalent takes an Option, it may be set to null to indicate None.
-    */
-   LDKnativeDirectionalChannelInfo *inner;
-   bool is_owned;
-} LDKDirectionalChannelInfo;
+void CResult_ChannelReestablishDecodeErrorZ_free(struct LDKCResult_ChannelReestablishDecodeErrorZ _res);
 
+struct LDKCResult_ChannelReestablishDecodeErrorZ CResult_ChannelReestablishDecodeErrorZ_clone(const struct LDKCResult_ChannelReestablishDecodeErrorZ *NONNULL_PTR orig);
 
+struct LDKCResult_ClosingSignedDecodeErrorZ CResult_ClosingSignedDecodeErrorZ_ok(struct LDKClosingSigned o);
 
-/**
- * Details about a channel (both directions).
- * Received within a channel announcement.
- */
-typedef struct MUST_USE_STRUCT LDKChannelInfo {
-   /**
-    * Nearly everywhere, inner must be non-null, however in places where
-    * the Rust equivalent takes an Option, it may be set to null to indicate None.
-    */
-   LDKnativeChannelInfo *inner;
-   bool is_owned;
-} LDKChannelInfo;
+struct LDKCResult_ClosingSignedDecodeErrorZ CResult_ClosingSignedDecodeErrorZ_err(struct LDKDecodeError e);
 
+void CResult_ClosingSignedDecodeErrorZ_free(struct LDKCResult_ClosingSignedDecodeErrorZ _res);
 
+struct LDKCResult_ClosingSignedDecodeErrorZ CResult_ClosingSignedDecodeErrorZ_clone(const struct LDKCResult_ClosingSignedDecodeErrorZ *NONNULL_PTR orig);
 
-/**
- * Information received in the latest node_announcement from this node.
- */
-typedef struct MUST_USE_STRUCT LDKNodeAnnouncementInfo {
-   /**
-    * Nearly everywhere, inner must be non-null, however in places where
-    * the Rust equivalent takes an Option, it may be set to null to indicate None.
-    */
-   LDKnativeNodeAnnouncementInfo *inner;
-   bool is_owned;
-} LDKNodeAnnouncementInfo;
+struct LDKCResult_CommitmentSignedDecodeErrorZ CResult_CommitmentSignedDecodeErrorZ_ok(struct LDKCommitmentSigned o);
 
+struct LDKCResult_CommitmentSignedDecodeErrorZ CResult_CommitmentSignedDecodeErrorZ_err(struct LDKDecodeError e);
 
+void CResult_CommitmentSignedDecodeErrorZ_free(struct LDKCResult_CommitmentSignedDecodeErrorZ _res);
 
-/**
- * Details about a node in the network, known from the network announcement.
- */
-typedef struct MUST_USE_STRUCT LDKNodeInfo {
-   /**
-    * Nearly everywhere, inner must be non-null, however in places where
-    * the Rust equivalent takes an Option, it may be set to null to indicate None.
-    */
-   LDKnativeNodeInfo *inner;
-   bool is_owned;
-} LDKNodeInfo;
+struct LDKCResult_CommitmentSignedDecodeErrorZ CResult_CommitmentSignedDecodeErrorZ_clone(const struct LDKCResult_CommitmentSignedDecodeErrorZ *NONNULL_PTR orig);
 
-typedef LDKCVecTempl_RouteHop LDKCVec_RouteHopZ;
+struct LDKCResult_FundingCreatedDecodeErrorZ CResult_FundingCreatedDecodeErrorZ_ok(struct LDKFundingCreated o);
 
-extern const void (*C2Tuple_HTLCOutputInCommitmentSignatureZ_free)(LDKC2Tuple_HTLCOutputInCommitmentSignatureZ);
+struct LDKCResult_FundingCreatedDecodeErrorZ CResult_FundingCreatedDecodeErrorZ_err(struct LDKDecodeError e);
 
-extern const void (*C2Tuple_OutPointScriptZ_free)(LDKC2Tuple_OutPointScriptZ);
+void CResult_FundingCreatedDecodeErrorZ_free(struct LDKCResult_FundingCreatedDecodeErrorZ _res);
 
-extern const void (*C2Tuple_SignatureCVec_SignatureZZ_free)(LDKC2Tuple_SignatureCVec_SignatureZZ);
+struct LDKCResult_FundingCreatedDecodeErrorZ CResult_FundingCreatedDecodeErrorZ_clone(const struct LDKCResult_FundingCreatedDecodeErrorZ *NONNULL_PTR orig);
 
-extern const void (*C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ_free)(LDKC2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ);
+struct LDKCResult_FundingSignedDecodeErrorZ CResult_FundingSignedDecodeErrorZ_ok(struct LDKFundingSigned o);
 
-extern const void (*C2Tuple_u32TxOutZ_free)(LDKC2Tuple_u32TxOutZ);
+struct LDKCResult_FundingSignedDecodeErrorZ CResult_FundingSignedDecodeErrorZ_err(struct LDKDecodeError e);
 
-extern const void (*C2Tuple_u64u64Z_free)(LDKC2Tuple_u64u64Z);
+void CResult_FundingSignedDecodeErrorZ_free(struct LDKCResult_FundingSignedDecodeErrorZ _res);
 
-extern const void (*C2Tuple_usizeTransactionZ_free)(LDKC2Tuple_usizeTransactionZ);
+struct LDKCResult_FundingSignedDecodeErrorZ CResult_FundingSignedDecodeErrorZ_clone(const struct LDKCResult_FundingSignedDecodeErrorZ *NONNULL_PTR orig);
 
-extern const void (*C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ_free)(LDKC3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ);
+struct LDKCResult_FundingLockedDecodeErrorZ CResult_FundingLockedDecodeErrorZ_ok(struct LDKFundingLocked o);
 
-extern const uint64_t CLOSED_CHANNEL_UPDATE_ID;
+struct LDKCResult_FundingLockedDecodeErrorZ CResult_FundingLockedDecodeErrorZ_err(struct LDKDecodeError e);
 
-extern const void (*CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ_free)(LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ);
+void CResult_FundingLockedDecodeErrorZ_free(struct LDKCResult_FundingLockedDecodeErrorZ _res);
 
-extern const LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ (*CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ_ok)(LDKC2Tuple_SignatureCVec_SignatureZZ);
+struct LDKCResult_FundingLockedDecodeErrorZ CResult_FundingLockedDecodeErrorZ_clone(const struct LDKCResult_FundingLockedDecodeErrorZ *NONNULL_PTR orig);
 
-extern const void (*CResult_CVec_SignatureZNoneZ_free)(LDKCResult_CVec_SignatureZNoneZ);
+struct LDKCResult_InitDecodeErrorZ CResult_InitDecodeErrorZ_ok(struct LDKInit o);
 
-extern const LDKCResult_CVec_SignatureZNoneZ (*CResult_CVec_SignatureZNoneZ_ok)(LDKCVec_SignatureZ);
+struct LDKCResult_InitDecodeErrorZ CResult_InitDecodeErrorZ_err(struct LDKDecodeError e);
 
-extern const LDKCResult_CVec_u8ZPeerHandleErrorZ (*CResult_CVec_u8ZPeerHandleErrorZ_err)(LDKPeerHandleError);
+void CResult_InitDecodeErrorZ_free(struct LDKCResult_InitDecodeErrorZ _res);
 
-extern const void (*CResult_CVec_u8ZPeerHandleErrorZ_free)(LDKCResult_CVec_u8ZPeerHandleErrorZ);
+struct LDKCResult_InitDecodeErrorZ CResult_InitDecodeErrorZ_clone(const struct LDKCResult_InitDecodeErrorZ *NONNULL_PTR orig);
 
-extern const LDKCResult_CVec_u8ZPeerHandleErrorZ (*CResult_CVec_u8ZPeerHandleErrorZ_ok)(LDKCVec_u8Z);
+struct LDKCResult_OpenChannelDecodeErrorZ CResult_OpenChannelDecodeErrorZ_ok(struct LDKOpenChannel o);
 
-extern const LDKCResult_NoneAPIErrorZ (*CResult_NoneAPIErrorZ_err)(LDKAPIError);
+struct LDKCResult_OpenChannelDecodeErrorZ CResult_OpenChannelDecodeErrorZ_err(struct LDKDecodeError e);
 
-extern const void (*CResult_NoneAPIErrorZ_free)(LDKCResult_NoneAPIErrorZ);
+void CResult_OpenChannelDecodeErrorZ_free(struct LDKCResult_OpenChannelDecodeErrorZ _res);
 
-extern const LDKCResult_NoneChannelMonitorUpdateErrZ (*CResult_NoneChannelMonitorUpdateErrZ_err)(LDKChannelMonitorUpdateErr);
+struct LDKCResult_OpenChannelDecodeErrorZ CResult_OpenChannelDecodeErrorZ_clone(const struct LDKCResult_OpenChannelDecodeErrorZ *NONNULL_PTR orig);
 
-extern const void (*CResult_NoneChannelMonitorUpdateErrZ_free)(LDKCResult_NoneChannelMonitorUpdateErrZ);
+struct LDKCResult_RevokeAndACKDecodeErrorZ CResult_RevokeAndACKDecodeErrorZ_ok(struct LDKRevokeAndACK o);
 
-extern const LDKCResult_NoneLightningErrorZ (*CResult_NoneLightningErrorZ_err)(LDKLightningError);
+struct LDKCResult_RevokeAndACKDecodeErrorZ CResult_RevokeAndACKDecodeErrorZ_err(struct LDKDecodeError e);
 
-extern const void (*CResult_NoneLightningErrorZ_free)(LDKCResult_NoneLightningErrorZ);
+void CResult_RevokeAndACKDecodeErrorZ_free(struct LDKCResult_RevokeAndACKDecodeErrorZ _res);
 
-extern const LDKCResult_NoneMonitorUpdateErrorZ (*CResult_NoneMonitorUpdateErrorZ_err)(LDKMonitorUpdateError);
+struct LDKCResult_RevokeAndACKDecodeErrorZ CResult_RevokeAndACKDecodeErrorZ_clone(const struct LDKCResult_RevokeAndACKDecodeErrorZ *NONNULL_PTR orig);
 
-extern const void (*CResult_NoneMonitorUpdateErrorZ_free)(LDKCResult_NoneMonitorUpdateErrorZ);
+struct LDKCResult_ShutdownDecodeErrorZ CResult_ShutdownDecodeErrorZ_ok(struct LDKShutdown o);
 
-extern const LDKCResult_NonePaymentSendFailureZ (*CResult_NonePaymentSendFailureZ_err)(LDKPaymentSendFailure);
+struct LDKCResult_ShutdownDecodeErrorZ CResult_ShutdownDecodeErrorZ_err(struct LDKDecodeError e);
 
-extern const void (*CResult_NonePaymentSendFailureZ_free)(LDKCResult_NonePaymentSendFailureZ);
+void CResult_ShutdownDecodeErrorZ_free(struct LDKCResult_ShutdownDecodeErrorZ _res);
 
-extern const LDKCResult_NonePeerHandleErrorZ (*CResult_NonePeerHandleErrorZ_err)(LDKPeerHandleError);
+struct LDKCResult_ShutdownDecodeErrorZ CResult_ShutdownDecodeErrorZ_clone(const struct LDKCResult_ShutdownDecodeErrorZ *NONNULL_PTR orig);
 
-extern const void (*CResult_NonePeerHandleErrorZ_free)(LDKCResult_NonePeerHandleErrorZ);
+struct LDKCResult_UpdateFailHTLCDecodeErrorZ CResult_UpdateFailHTLCDecodeErrorZ_ok(struct LDKUpdateFailHTLC o);
 
-extern const LDKCResult_PublicKeySecpErrorZ (*CResult_PublicKeySecpErrorZ_err)(LDKSecp256k1Error);
+struct LDKCResult_UpdateFailHTLCDecodeErrorZ CResult_UpdateFailHTLCDecodeErrorZ_err(struct LDKDecodeError e);
 
-extern const void (*CResult_PublicKeySecpErrorZ_free)(LDKCResult_PublicKeySecpErrorZ);
+void CResult_UpdateFailHTLCDecodeErrorZ_free(struct LDKCResult_UpdateFailHTLCDecodeErrorZ _res);
 
-extern const LDKCResult_PublicKeySecpErrorZ (*CResult_PublicKeySecpErrorZ_ok)(LDKPublicKey);
+struct LDKCResult_UpdateFailHTLCDecodeErrorZ CResult_UpdateFailHTLCDecodeErrorZ_clone(const struct LDKCResult_UpdateFailHTLCDecodeErrorZ *NONNULL_PTR orig);
 
-extern const LDKCResult_RouteLightningErrorZ (*CResult_RouteLightningErrorZ_err)(LDKLightningError);
+struct LDKCResult_UpdateFailMalformedHTLCDecodeErrorZ CResult_UpdateFailMalformedHTLCDecodeErrorZ_ok(struct LDKUpdateFailMalformedHTLC o);
 
-extern const void (*CResult_RouteLightningErrorZ_free)(LDKCResult_RouteLightningErrorZ);
+struct LDKCResult_UpdateFailMalformedHTLCDecodeErrorZ CResult_UpdateFailMalformedHTLCDecodeErrorZ_err(struct LDKDecodeError e);
 
-extern const LDKCResult_RouteLightningErrorZ (*CResult_RouteLightningErrorZ_ok)(LDKRoute);
+void CResult_UpdateFailMalformedHTLCDecodeErrorZ_free(struct LDKCResult_UpdateFailMalformedHTLCDecodeErrorZ _res);
 
-extern const LDKCResult_SecretKeySecpErrorZ (*CResult_SecretKeySecpErrorZ_err)(LDKSecp256k1Error);
+struct LDKCResult_UpdateFailMalformedHTLCDecodeErrorZ CResult_UpdateFailMalformedHTLCDecodeErrorZ_clone(const struct LDKCResult_UpdateFailMalformedHTLCDecodeErrorZ *NONNULL_PTR orig);
 
-extern const void (*CResult_SecretKeySecpErrorZ_free)(LDKCResult_SecretKeySecpErrorZ);
+struct LDKCResult_UpdateFeeDecodeErrorZ CResult_UpdateFeeDecodeErrorZ_ok(struct LDKUpdateFee o);
 
-extern const LDKCResult_SecretKeySecpErrorZ (*CResult_SecretKeySecpErrorZ_ok)(LDKSecretKey);
+struct LDKCResult_UpdateFeeDecodeErrorZ CResult_UpdateFeeDecodeErrorZ_err(struct LDKDecodeError e);
 
-extern const void (*CResult_SignatureNoneZ_free)(LDKCResult_SignatureNoneZ);
+void CResult_UpdateFeeDecodeErrorZ_free(struct LDKCResult_UpdateFeeDecodeErrorZ _res);
 
-extern const LDKCResult_SignatureNoneZ (*CResult_SignatureNoneZ_ok)(LDKSignature);
+struct LDKCResult_UpdateFeeDecodeErrorZ CResult_UpdateFeeDecodeErrorZ_clone(const struct LDKCResult_UpdateFeeDecodeErrorZ *NONNULL_PTR orig);
 
-extern const LDKCResult_TxCreationKeysSecpErrorZ (*CResult_TxCreationKeysSecpErrorZ_err)(LDKSecp256k1Error);
+struct LDKCResult_UpdateFulfillHTLCDecodeErrorZ CResult_UpdateFulfillHTLCDecodeErrorZ_ok(struct LDKUpdateFulfillHTLC o);
 
-extern const void (*CResult_TxCreationKeysSecpErrorZ_free)(LDKCResult_TxCreationKeysSecpErrorZ);
+struct LDKCResult_UpdateFulfillHTLCDecodeErrorZ CResult_UpdateFulfillHTLCDecodeErrorZ_err(struct LDKDecodeError e);
 
-extern const LDKCResult_TxCreationKeysSecpErrorZ (*CResult_TxCreationKeysSecpErrorZ_ok)(LDKTxCreationKeys);
+void CResult_UpdateFulfillHTLCDecodeErrorZ_free(struct LDKCResult_UpdateFulfillHTLCDecodeErrorZ _res);
 
-extern const LDKCResult_TxOutAccessErrorZ (*CResult_TxOutAccessErrorZ_err)(LDKAccessError);
+struct LDKCResult_UpdateFulfillHTLCDecodeErrorZ CResult_UpdateFulfillHTLCDecodeErrorZ_clone(const struct LDKCResult_UpdateFulfillHTLCDecodeErrorZ *NONNULL_PTR orig);
 
-extern const void (*CResult_TxOutAccessErrorZ_free)(LDKCResult_TxOutAccessErrorZ);
+struct LDKCResult_UpdateAddHTLCDecodeErrorZ CResult_UpdateAddHTLCDecodeErrorZ_ok(struct LDKUpdateAddHTLC o);
 
-extern const LDKCResult_TxOutAccessErrorZ (*CResult_TxOutAccessErrorZ_ok)(LDKTxOut);
+struct LDKCResult_UpdateAddHTLCDecodeErrorZ CResult_UpdateAddHTLCDecodeErrorZ_err(struct LDKDecodeError e);
 
-extern const LDKCResult_boolLightningErrorZ (*CResult_boolLightningErrorZ_err)(LDKLightningError);
+void CResult_UpdateAddHTLCDecodeErrorZ_free(struct LDKCResult_UpdateAddHTLCDecodeErrorZ _res);
 
-extern const void (*CResult_boolLightningErrorZ_free)(LDKCResult_boolLightningErrorZ);
+struct LDKCResult_UpdateAddHTLCDecodeErrorZ CResult_UpdateAddHTLCDecodeErrorZ_clone(const struct LDKCResult_UpdateAddHTLCDecodeErrorZ *NONNULL_PTR orig);
 
-extern const LDKCResult_boolLightningErrorZ (*CResult_boolLightningErrorZ_ok)(bool);
+struct LDKCResult_PingDecodeErrorZ CResult_PingDecodeErrorZ_ok(struct LDKPing o);
 
-extern const LDKCResult_boolPeerHandleErrorZ (*CResult_boolPeerHandleErrorZ_err)(LDKPeerHandleError);
+struct LDKCResult_PingDecodeErrorZ CResult_PingDecodeErrorZ_err(struct LDKDecodeError e);
 
-extern const void (*CResult_boolPeerHandleErrorZ_free)(LDKCResult_boolPeerHandleErrorZ);
+void CResult_PingDecodeErrorZ_free(struct LDKCResult_PingDecodeErrorZ _res);
 
-extern const LDKCResult_boolPeerHandleErrorZ (*CResult_boolPeerHandleErrorZ_ok)(bool);
+struct LDKCResult_PingDecodeErrorZ CResult_PingDecodeErrorZ_clone(const struct LDKCResult_PingDecodeErrorZ *NONNULL_PTR orig);
 
-extern const void (*CVec_C2Tuple_HTLCOutputInCommitmentSignatureZZ_free)(LDKCVec_C2Tuple_HTLCOutputInCommitmentSignatureZZ);
+struct LDKCResult_PongDecodeErrorZ CResult_PongDecodeErrorZ_ok(struct LDKPong o);
 
-extern const void (*CVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ_free)(LDKCVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ);
+struct LDKCResult_PongDecodeErrorZ CResult_PongDecodeErrorZ_err(struct LDKDecodeError e);
 
-extern const void (*CVec_C2Tuple_u32TxOutZZ_free)(LDKCVec_C2Tuple_u32TxOutZZ);
+void CResult_PongDecodeErrorZ_free(struct LDKCResult_PongDecodeErrorZ _res);
 
-extern const void (*CVec_C2Tuple_usizeTransactionZZ_free)(LDKCVec_C2Tuple_usizeTransactionZZ);
+struct LDKCResult_PongDecodeErrorZ CResult_PongDecodeErrorZ_clone(const struct LDKCResult_PongDecodeErrorZ *NONNULL_PTR orig);
 
-extern const void (*CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ_free)(LDKCVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ);
+struct LDKCResult_UnsignedChannelAnnouncementDecodeErrorZ CResult_UnsignedChannelAnnouncementDecodeErrorZ_ok(struct LDKUnsignedChannelAnnouncement o);
 
-extern const void (*CVec_CVec_RouteHopZZ_free)(LDKCVec_CVec_RouteHopZZ);
+struct LDKCResult_UnsignedChannelAnnouncementDecodeErrorZ CResult_UnsignedChannelAnnouncementDecodeErrorZ_err(struct LDKDecodeError e);
 
-extern const void (*CVec_ChannelDetailsZ_free)(LDKCVec_ChannelDetailsZ);
+void CResult_UnsignedChannelAnnouncementDecodeErrorZ_free(struct LDKCResult_UnsignedChannelAnnouncementDecodeErrorZ _res);
 
-extern const void (*CVec_ChannelMonitorZ_free)(LDKCVec_ChannelMonitorZ);
+struct LDKCResult_UnsignedChannelAnnouncementDecodeErrorZ CResult_UnsignedChannelAnnouncementDecodeErrorZ_clone(const struct LDKCResult_UnsignedChannelAnnouncementDecodeErrorZ *NONNULL_PTR orig);
 
-extern const void (*CVec_EventZ_free)(LDKCVec_EventZ);
+struct LDKCResult_ChannelAnnouncementDecodeErrorZ CResult_ChannelAnnouncementDecodeErrorZ_ok(struct LDKChannelAnnouncement o);
 
-extern const void (*CVec_HTLCOutputInCommitmentZ_free)(LDKCVec_HTLCOutputInCommitmentZ);
+struct LDKCResult_ChannelAnnouncementDecodeErrorZ CResult_ChannelAnnouncementDecodeErrorZ_err(struct LDKDecodeError e);
 
-extern const void (*CVec_MessageSendEventZ_free)(LDKCVec_MessageSendEventZ);
+void CResult_ChannelAnnouncementDecodeErrorZ_free(struct LDKCResult_ChannelAnnouncementDecodeErrorZ _res);
 
-extern const void (*CVec_MonitorEventZ_free)(LDKCVec_MonitorEventZ);
+struct LDKCResult_ChannelAnnouncementDecodeErrorZ CResult_ChannelAnnouncementDecodeErrorZ_clone(const struct LDKCResult_ChannelAnnouncementDecodeErrorZ *NONNULL_PTR orig);
 
-extern const void (*CVec_NetAddressZ_free)(LDKCVec_NetAddressZ);
+struct LDKCResult_UnsignedChannelUpdateDecodeErrorZ CResult_UnsignedChannelUpdateDecodeErrorZ_ok(struct LDKUnsignedChannelUpdate o);
 
-extern const void (*CVec_NodeAnnouncementZ_free)(LDKCVec_NodeAnnouncementZ);
+struct LDKCResult_UnsignedChannelUpdateDecodeErrorZ CResult_UnsignedChannelUpdateDecodeErrorZ_err(struct LDKDecodeError e);
 
-extern const void (*CVec_PublicKeyZ_free)(LDKCVec_PublicKeyZ);
+void CResult_UnsignedChannelUpdateDecodeErrorZ_free(struct LDKCResult_UnsignedChannelUpdateDecodeErrorZ _res);
 
-extern const void (*CVec_RouteHintZ_free)(LDKCVec_RouteHintZ);
+struct LDKCResult_UnsignedChannelUpdateDecodeErrorZ CResult_UnsignedChannelUpdateDecodeErrorZ_clone(const struct LDKCResult_UnsignedChannelUpdateDecodeErrorZ *NONNULL_PTR orig);
 
-extern const void (*CVec_RouteHopZ_free)(LDKCVec_RouteHopZ);
+struct LDKCResult_ChannelUpdateDecodeErrorZ CResult_ChannelUpdateDecodeErrorZ_ok(struct LDKChannelUpdate o);
 
-extern const void (*CVec_SignatureZ_free)(LDKCVec_SignatureZ);
+struct LDKCResult_ChannelUpdateDecodeErrorZ CResult_ChannelUpdateDecodeErrorZ_err(struct LDKDecodeError e);
 
-extern const void (*CVec_SpendableOutputDescriptorZ_free)(LDKCVec_SpendableOutputDescriptorZ);
+void CResult_ChannelUpdateDecodeErrorZ_free(struct LDKCResult_ChannelUpdateDecodeErrorZ _res);
 
-extern const void (*CVec_TransactionZ_free)(LDKCVec_TransactionZ);
+struct LDKCResult_ChannelUpdateDecodeErrorZ CResult_ChannelUpdateDecodeErrorZ_clone(const struct LDKCResult_ChannelUpdateDecodeErrorZ *NONNULL_PTR orig);
 
-extern const void (*CVec_UpdateAddHTLCZ_free)(LDKCVec_UpdateAddHTLCZ);
+struct LDKCResult_ErrorMessageDecodeErrorZ CResult_ErrorMessageDecodeErrorZ_ok(struct LDKErrorMessage o);
 
-extern const void (*CVec_UpdateFailHTLCZ_free)(LDKCVec_UpdateFailHTLCZ);
+struct LDKCResult_ErrorMessageDecodeErrorZ CResult_ErrorMessageDecodeErrorZ_err(struct LDKDecodeError e);
 
-extern const void (*CVec_UpdateFailMalformedHTLCZ_free)(LDKCVec_UpdateFailMalformedHTLCZ);
+void CResult_ErrorMessageDecodeErrorZ_free(struct LDKCResult_ErrorMessageDecodeErrorZ _res);
 
-extern const void (*CVec_UpdateFulfillHTLCZ_free)(LDKCVec_UpdateFulfillHTLCZ);
+struct LDKCResult_ErrorMessageDecodeErrorZ CResult_ErrorMessageDecodeErrorZ_clone(const struct LDKCResult_ErrorMessageDecodeErrorZ *NONNULL_PTR orig);
 
-extern const void (*CVec_u64Z_free)(LDKCVec_u64Z);
+struct LDKCResult_UnsignedNodeAnnouncementDecodeErrorZ CResult_UnsignedNodeAnnouncementDecodeErrorZ_ok(struct LDKUnsignedNodeAnnouncement o);
 
-extern const void (*CVec_u8Z_free)(LDKCVec_u8Z);
+struct LDKCResult_UnsignedNodeAnnouncementDecodeErrorZ CResult_UnsignedNodeAnnouncementDecodeErrorZ_err(struct LDKDecodeError e);
 
-extern const uint64_t MIN_RELAY_FEE_SAT_PER_1000_WEIGHT;
+void CResult_UnsignedNodeAnnouncementDecodeErrorZ_free(struct LDKCResult_UnsignedNodeAnnouncementDecodeErrorZ _res);
+
+struct LDKCResult_UnsignedNodeAnnouncementDecodeErrorZ CResult_UnsignedNodeAnnouncementDecodeErrorZ_clone(const struct LDKCResult_UnsignedNodeAnnouncementDecodeErrorZ *NONNULL_PTR orig);
+
+struct LDKCResult_NodeAnnouncementDecodeErrorZ CResult_NodeAnnouncementDecodeErrorZ_ok(struct LDKNodeAnnouncement o);
+
+struct LDKCResult_NodeAnnouncementDecodeErrorZ CResult_NodeAnnouncementDecodeErrorZ_err(struct LDKDecodeError e);
+
+void CResult_NodeAnnouncementDecodeErrorZ_free(struct LDKCResult_NodeAnnouncementDecodeErrorZ _res);
+
+struct LDKCResult_NodeAnnouncementDecodeErrorZ CResult_NodeAnnouncementDecodeErrorZ_clone(const struct LDKCResult_NodeAnnouncementDecodeErrorZ *NONNULL_PTR orig);
+
+struct LDKCResult_QueryShortChannelIdsDecodeErrorZ CResult_QueryShortChannelIdsDecodeErrorZ_ok(struct LDKQueryShortChannelIds o);
 
-void Transaction_free(LDKTransaction _res);
+struct LDKCResult_QueryShortChannelIdsDecodeErrorZ CResult_QueryShortChannelIdsDecodeErrorZ_err(struct LDKDecodeError e);
 
-void TxOut_free(LDKTxOut _res);
+void CResult_QueryShortChannelIdsDecodeErrorZ_free(struct LDKCResult_QueryShortChannelIdsDecodeErrorZ _res);
 
-LDKC2Tuple_usizeTransactionZ C2Tuple_usizeTransactionZ_new(uintptr_t a, LDKTransaction b);
+struct LDKCResult_QueryShortChannelIdsDecodeErrorZ CResult_QueryShortChannelIdsDecodeErrorZ_clone(const struct LDKCResult_QueryShortChannelIdsDecodeErrorZ *NONNULL_PTR orig);
 
-LDKCResult_NoneChannelMonitorUpdateErrZ CResult_NoneChannelMonitorUpdateErrZ_ok(void);
+struct LDKCResult_ReplyShortChannelIdsEndDecodeErrorZ CResult_ReplyShortChannelIdsEndDecodeErrorZ_ok(struct LDKReplyShortChannelIdsEnd o);
 
-LDKCResult_NoneMonitorUpdateErrorZ CResult_NoneMonitorUpdateErrorZ_ok(void);
+struct LDKCResult_ReplyShortChannelIdsEndDecodeErrorZ CResult_ReplyShortChannelIdsEndDecodeErrorZ_err(struct LDKDecodeError e);
 
-LDKC2Tuple_OutPointScriptZ C2Tuple_OutPointScriptZ_new(LDKOutPoint a, LDKCVec_u8Z b);
+void CResult_ReplyShortChannelIdsEndDecodeErrorZ_free(struct LDKCResult_ReplyShortChannelIdsEndDecodeErrorZ _res);
 
-LDKC2Tuple_u32TxOutZ C2Tuple_u32TxOutZ_new(uint32_t a, LDKTxOut b);
+struct LDKCResult_ReplyShortChannelIdsEndDecodeErrorZ CResult_ReplyShortChannelIdsEndDecodeErrorZ_clone(const struct LDKCResult_ReplyShortChannelIdsEndDecodeErrorZ *NONNULL_PTR orig);
 
-LDKC2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ_new(LDKThirtyTwoBytes a, LDKCVec_C2Tuple_u32TxOutZZ b);
+struct LDKCResult_QueryChannelRangeDecodeErrorZ CResult_QueryChannelRangeDecodeErrorZ_ok(struct LDKQueryChannelRange o);
 
-LDKC2Tuple_u64u64Z C2Tuple_u64u64Z_new(uint64_t a, uint64_t b);
+struct LDKCResult_QueryChannelRangeDecodeErrorZ CResult_QueryChannelRangeDecodeErrorZ_err(struct LDKDecodeError e);
 
-LDKC2Tuple_SignatureCVec_SignatureZZ C2Tuple_SignatureCVec_SignatureZZ_new(LDKSignature a, LDKCVec_SignatureZ b);
+void CResult_QueryChannelRangeDecodeErrorZ_free(struct LDKCResult_QueryChannelRangeDecodeErrorZ _res);
 
-LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ_err(void);
+struct LDKCResult_QueryChannelRangeDecodeErrorZ CResult_QueryChannelRangeDecodeErrorZ_clone(const struct LDKCResult_QueryChannelRangeDecodeErrorZ *NONNULL_PTR orig);
 
-LDKCResult_SignatureNoneZ CResult_SignatureNoneZ_err(void);
+struct LDKCResult_ReplyChannelRangeDecodeErrorZ CResult_ReplyChannelRangeDecodeErrorZ_ok(struct LDKReplyChannelRange o);
 
-LDKCResult_CVec_SignatureZNoneZ CResult_CVec_SignatureZNoneZ_err(void);
+struct LDKCResult_ReplyChannelRangeDecodeErrorZ CResult_ReplyChannelRangeDecodeErrorZ_err(struct LDKDecodeError e);
 
-LDKCResult_NoneAPIErrorZ CResult_NoneAPIErrorZ_ok(void);
+void CResult_ReplyChannelRangeDecodeErrorZ_free(struct LDKCResult_ReplyChannelRangeDecodeErrorZ _res);
 
-LDKCResult_NonePaymentSendFailureZ CResult_NonePaymentSendFailureZ_ok(void);
+struct LDKCResult_ReplyChannelRangeDecodeErrorZ CResult_ReplyChannelRangeDecodeErrorZ_clone(const struct LDKCResult_ReplyChannelRangeDecodeErrorZ *NONNULL_PTR orig);
 
-LDKC3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ_new(LDKChannelAnnouncement a, LDKChannelUpdate b, LDKChannelUpdate c);
+struct LDKCResult_GossipTimestampFilterDecodeErrorZ CResult_GossipTimestampFilterDecodeErrorZ_ok(struct LDKGossipTimestampFilter o);
 
-LDKCResult_NonePeerHandleErrorZ CResult_NonePeerHandleErrorZ_ok(void);
+struct LDKCResult_GossipTimestampFilterDecodeErrorZ CResult_GossipTimestampFilterDecodeErrorZ_err(struct LDKDecodeError e);
 
-LDKC2Tuple_HTLCOutputInCommitmentSignatureZ C2Tuple_HTLCOutputInCommitmentSignatureZ_new(LDKHTLCOutputInCommitment a, LDKSignature b);
+void CResult_GossipTimestampFilterDecodeErrorZ_free(struct LDKCResult_GossipTimestampFilterDecodeErrorZ _res);
 
-LDKCResult_NoneLightningErrorZ CResult_NoneLightningErrorZ_ok(void);
+struct LDKCResult_GossipTimestampFilterDecodeErrorZ CResult_GossipTimestampFilterDecodeErrorZ_clone(const struct LDKCResult_GossipTimestampFilterDecodeErrorZ *NONNULL_PTR orig);
 
-void Event_free(LDKEvent this_ptr);
+void Event_free(struct LDKEvent this_ptr);
 
-LDKEvent Event_clone(const LDKEvent *orig);
+struct LDKEvent Event_clone(const struct LDKEvent *NONNULL_PTR orig);
 
-void MessageSendEvent_free(LDKMessageSendEvent this_ptr);
+struct LDKCVec_u8Z Event_write(const struct LDKEvent *NONNULL_PTR obj);
 
-LDKMessageSendEvent MessageSendEvent_clone(const LDKMessageSendEvent *orig);
+void MessageSendEvent_free(struct LDKMessageSendEvent this_ptr);
+
+struct LDKMessageSendEvent MessageSendEvent_clone(const struct LDKMessageSendEvent *NONNULL_PTR orig);
 
 /**
  * Calls the free function if one is set
  */
-void MessageSendEventsProvider_free(LDKMessageSendEventsProvider this_ptr);
+void MessageSendEventsProvider_free(struct LDKMessageSendEventsProvider this_ptr);
 
 /**
  * Calls the free function if one is set
  */
-void EventsProvider_free(LDKEventsProvider this_ptr);
+void EventsProvider_free(struct LDKEventsProvider this_ptr);
 
-void APIError_free(LDKAPIError this_ptr);
+void APIError_free(struct LDKAPIError this_ptr);
 
-LDKAPIError APIError_clone(const LDKAPIError *orig);
+struct LDKAPIError APIError_clone(const struct LDKAPIError *NONNULL_PTR orig);
 
-LDKLevel Level_clone(const LDKLevel *orig);
+enum LDKLevel Level_clone(const enum LDKLevel *NONNULL_PTR orig);
 
 /**
  * Returns the most verbose logging level.
  */
-MUST_USE_RES LDKLevel Level_max(void);
+MUST_USE_RES enum LDKLevel Level_max(void);
 
 /**
  * Calls the free function if one is set
  */
-void Logger_free(LDKLogger this_ptr);
-
-void ChannelHandshakeConfig_free(LDKChannelHandshakeConfig this_ptr);
+void Logger_free(struct LDKLogger this_ptr);
 
-LDKChannelHandshakeConfig ChannelHandshakeConfig_clone(const LDKChannelHandshakeConfig *orig);
+void ChannelHandshakeConfig_free(struct LDKChannelHandshakeConfig this_ptr);
 
 /**
  * Confirmations we will wait for before considering the channel locked in.
@@ -3364,7 +4736,7 @@ LDKChannelHandshakeConfig ChannelHandshakeConfig_clone(const LDKChannelHandshake
  *
  * Default value: 6.
  */
-uint32_t ChannelHandshakeConfig_get_minimum_depth(const LDKChannelHandshakeConfig *this_ptr);
+uint32_t ChannelHandshakeConfig_get_minimum_depth(const struct LDKChannelHandshakeConfig *NONNULL_PTR this_ptr);
 
 /**
  * Confirmations we will wait for before considering the channel locked in.
@@ -3373,7 +4745,7 @@ uint32_t ChannelHandshakeConfig_get_minimum_depth(const LDKChannelHandshakeConfi
  *
  * Default value: 6.
  */
-void ChannelHandshakeConfig_set_minimum_depth(LDKChannelHandshakeConfig *this_ptr, uint32_t val);
+void ChannelHandshakeConfig_set_minimum_depth(struct LDKChannelHandshakeConfig *NONNULL_PTR this_ptr, uint32_t val);
 
 /**
  * Set to the amount of time we require our counterparty to wait to claim their money.
@@ -3389,7 +4761,7 @@ void ChannelHandshakeConfig_set_minimum_depth(LDKChannelHandshakeConfig *this_pt
  * Default value: BREAKDOWN_TIMEOUT (currently 144), we enforce it as a minimum at channel
  * opening so you can tweak config to ask for more security, not less.
  */
-uint16_t ChannelHandshakeConfig_get_our_to_self_delay(const LDKChannelHandshakeConfig *this_ptr);
+uint16_t ChannelHandshakeConfig_get_our_to_self_delay(const struct LDKChannelHandshakeConfig *NONNULL_PTR this_ptr);
 
 /**
  * Set to the amount of time we require our counterparty to wait to claim their money.
@@ -3405,7 +4777,7 @@ uint16_t ChannelHandshakeConfig_get_our_to_self_delay(const LDKChannelHandshakeC
  * Default value: BREAKDOWN_TIMEOUT (currently 144), we enforce it as a minimum at channel
  * opening so you can tweak config to ask for more security, not less.
  */
-void ChannelHandshakeConfig_set_our_to_self_delay(LDKChannelHandshakeConfig *this_ptr, uint16_t val);
+void ChannelHandshakeConfig_set_our_to_self_delay(struct LDKChannelHandshakeConfig *NONNULL_PTR this_ptr, uint16_t val);
 
 /**
  * Set to the smallest value HTLC we will accept to process.
@@ -3416,7 +4788,7 @@ void ChannelHandshakeConfig_set_our_to_self_delay(LDKChannelHandshakeConfig *thi
  * Default value: 1. If the value is less than 1, it is ignored and set to 1, as is required
  * by the protocol.
  */
-uint64_t ChannelHandshakeConfig_get_our_htlc_minimum_msat(const LDKChannelHandshakeConfig *this_ptr);
+uint64_t ChannelHandshakeConfig_get_our_htlc_minimum_msat(const struct LDKChannelHandshakeConfig *NONNULL_PTR this_ptr);
 
 /**
  * Set to the smallest value HTLC we will accept to process.
@@ -3427,15 +4799,15 @@ uint64_t ChannelHandshakeConfig_get_our_htlc_minimum_msat(const LDKChannelHandsh
  * Default value: 1. If the value is less than 1, it is ignored and set to 1, as is required
  * by the protocol.
  */
-void ChannelHandshakeConfig_set_our_htlc_minimum_msat(LDKChannelHandshakeConfig *this_ptr, uint64_t val);
+void ChannelHandshakeConfig_set_our_htlc_minimum_msat(struct LDKChannelHandshakeConfig *NONNULL_PTR this_ptr, uint64_t val);
 
-MUST_USE_RES LDKChannelHandshakeConfig ChannelHandshakeConfig_new(uint32_t minimum_depth_arg, uint16_t our_to_self_delay_arg, uint64_t our_htlc_minimum_msat_arg);
+MUST_USE_RES struct LDKChannelHandshakeConfig ChannelHandshakeConfig_new(uint32_t minimum_depth_arg, uint16_t our_to_self_delay_arg, uint64_t our_htlc_minimum_msat_arg);
 
-MUST_USE_RES LDKChannelHandshakeConfig ChannelHandshakeConfig_default(void);
+struct LDKChannelHandshakeConfig ChannelHandshakeConfig_clone(const struct LDKChannelHandshakeConfig *NONNULL_PTR orig);
 
-void ChannelHandshakeLimits_free(LDKChannelHandshakeLimits this_ptr);
+MUST_USE_RES struct LDKChannelHandshakeConfig ChannelHandshakeConfig_default(void);
 
-LDKChannelHandshakeLimits ChannelHandshakeLimits_clone(const LDKChannelHandshakeLimits *orig);
+void ChannelHandshakeLimits_free(struct LDKChannelHandshakeLimits this_ptr);
 
 /**
  * Minimum allowed satoshis when a channel is funded, this is supplied by the sender and so
@@ -3443,7 +4815,7 @@ LDKChannelHandshakeLimits ChannelHandshakeLimits_clone(const LDKChannelHandshake
  *
  * Default value: 0.
  */
-uint64_t ChannelHandshakeLimits_get_min_funding_satoshis(const LDKChannelHandshakeLimits *this_ptr);
+uint64_t ChannelHandshakeLimits_get_min_funding_satoshis(const struct LDKChannelHandshakeLimits *NONNULL_PTR this_ptr);
 
 /**
  * Minimum allowed satoshis when a channel is funded, this is supplied by the sender and so
@@ -3451,7 +4823,7 @@ uint64_t ChannelHandshakeLimits_get_min_funding_satoshis(const LDKChannelHandsha
  *
  * Default value: 0.
  */
-void ChannelHandshakeLimits_set_min_funding_satoshis(LDKChannelHandshakeLimits *this_ptr, uint64_t val);
+void ChannelHandshakeLimits_set_min_funding_satoshis(struct LDKChannelHandshakeLimits *NONNULL_PTR this_ptr, uint64_t val);
 
 /**
  * The remote node sets a limit on the minimum size of HTLCs we can send to them. This allows
@@ -3459,7 +4831,7 @@ void ChannelHandshakeLimits_set_min_funding_satoshis(LDKChannelHandshakeLimits *
  *
  * Default value: u64::max_value.
  */
-uint64_t ChannelHandshakeLimits_get_max_htlc_minimum_msat(const LDKChannelHandshakeLimits *this_ptr);
+uint64_t ChannelHandshakeLimits_get_max_htlc_minimum_msat(const struct LDKChannelHandshakeLimits *NONNULL_PTR this_ptr);
 
 /**
  * The remote node sets a limit on the minimum size of HTLCs we can send to them. This allows
@@ -3467,7 +4839,7 @@ uint64_t ChannelHandshakeLimits_get_max_htlc_minimum_msat(const LDKChannelHandsh
  *
  * Default value: u64::max_value.
  */
-void ChannelHandshakeLimits_set_max_htlc_minimum_msat(LDKChannelHandshakeLimits *this_ptr, uint64_t val);
+void ChannelHandshakeLimits_set_max_htlc_minimum_msat(struct LDKChannelHandshakeLimits *NONNULL_PTR this_ptr, uint64_t val);
 
 /**
  * The remote node sets a limit on the maximum value of pending HTLCs to them at any given
@@ -3475,7 +4847,7 @@ void ChannelHandshakeLimits_set_max_htlc_minimum_msat(LDKChannelHandshakeLimits
  *
  * Default value: 0.
  */
-uint64_t ChannelHandshakeLimits_get_min_max_htlc_value_in_flight_msat(const LDKChannelHandshakeLimits *this_ptr);
+uint64_t ChannelHandshakeLimits_get_min_max_htlc_value_in_flight_msat(const struct LDKChannelHandshakeLimits *NONNULL_PTR this_ptr);
 
 /**
  * The remote node sets a limit on the maximum value of pending HTLCs to them at any given
@@ -3483,7 +4855,7 @@ uint64_t ChannelHandshakeLimits_get_min_max_htlc_value_in_flight_msat(const LDKC
  *
  * Default value: 0.
  */
-void ChannelHandshakeLimits_set_min_max_htlc_value_in_flight_msat(LDKChannelHandshakeLimits *this_ptr, uint64_t val);
+void ChannelHandshakeLimits_set_min_max_htlc_value_in_flight_msat(struct LDKChannelHandshakeLimits *NONNULL_PTR this_ptr, uint64_t val);
 
 /**
  * The remote node will require we keep a certain amount in direct payment to ourselves at all
@@ -3492,7 +4864,7 @@ void ChannelHandshakeLimits_set_min_max_htlc_value_in_flight_msat(LDKChannelHand
  *
  * Default value: u64::max_value.
  */
-uint64_t ChannelHandshakeLimits_get_max_channel_reserve_satoshis(const LDKChannelHandshakeLimits *this_ptr);
+uint64_t ChannelHandshakeLimits_get_max_channel_reserve_satoshis(const struct LDKChannelHandshakeLimits *NONNULL_PTR this_ptr);
 
 /**
  * The remote node will require we keep a certain amount in direct payment to ourselves at all
@@ -3501,7 +4873,7 @@ uint64_t ChannelHandshakeLimits_get_max_channel_reserve_satoshis(const LDKChanne
  *
  * Default value: u64::max_value.
  */
-void ChannelHandshakeLimits_set_max_channel_reserve_satoshis(LDKChannelHandshakeLimits *this_ptr, uint64_t val);
+void ChannelHandshakeLimits_set_max_channel_reserve_satoshis(struct LDKChannelHandshakeLimits *NONNULL_PTR this_ptr, uint64_t val);
 
 /**
  * The remote node sets a limit on the maximum number of pending HTLCs to them at any given
@@ -3509,7 +4881,7 @@ void ChannelHandshakeLimits_set_max_channel_reserve_satoshis(LDKChannelHandshake
  *
  * Default value: 0.
  */
-uint16_t ChannelHandshakeLimits_get_min_max_accepted_htlcs(const LDKChannelHandshakeLimits *this_ptr);
+uint16_t ChannelHandshakeLimits_get_min_max_accepted_htlcs(const struct LDKChannelHandshakeLimits *NONNULL_PTR this_ptr);
 
 /**
  * The remote node sets a limit on the maximum number of pending HTLCs to them at any given
@@ -3517,7 +4889,7 @@ uint16_t ChannelHandshakeLimits_get_min_max_accepted_htlcs(const LDKChannelHands
  *
  * Default value: 0.
  */
-void ChannelHandshakeLimits_set_min_max_accepted_htlcs(LDKChannelHandshakeLimits *this_ptr, uint16_t val);
+void ChannelHandshakeLimits_set_min_max_accepted_htlcs(struct LDKChannelHandshakeLimits *NONNULL_PTR this_ptr, uint16_t val);
 
 /**
  * Outputs below a certain value will not be added to on-chain transactions. The dust value is
@@ -3530,7 +4902,7 @@ void ChannelHandshakeLimits_set_min_max_accepted_htlcs(LDKChannelHandshakeLimits
  *
  * Default value: 546, the current dust limit on the Bitcoin network.
  */
-uint64_t ChannelHandshakeLimits_get_min_dust_limit_satoshis(const LDKChannelHandshakeLimits *this_ptr);
+uint64_t ChannelHandshakeLimits_get_min_dust_limit_satoshis(const struct LDKChannelHandshakeLimits *NONNULL_PTR this_ptr);
 
 /**
  * Outputs below a certain value will not be added to on-chain transactions. The dust value is
@@ -3543,7 +4915,7 @@ uint64_t ChannelHandshakeLimits_get_min_dust_limit_satoshis(const LDKChannelHand
  *
  * Default value: 546, the current dust limit on the Bitcoin network.
  */
-void ChannelHandshakeLimits_set_min_dust_limit_satoshis(LDKChannelHandshakeLimits *this_ptr, uint64_t val);
+void ChannelHandshakeLimits_set_min_dust_limit_satoshis(struct LDKChannelHandshakeLimits *NONNULL_PTR this_ptr, uint64_t val);
 
 /**
  * Maximum allowed threshold above which outputs will not be generated in their commitment
@@ -3552,7 +4924,7 @@ void ChannelHandshakeLimits_set_min_dust_limit_satoshis(LDKChannelHandshakeLimit
  *
  * Default value: u64::max_value.
  */
-uint64_t ChannelHandshakeLimits_get_max_dust_limit_satoshis(const LDKChannelHandshakeLimits *this_ptr);
+uint64_t ChannelHandshakeLimits_get_max_dust_limit_satoshis(const struct LDKChannelHandshakeLimits *NONNULL_PTR this_ptr);
 
 /**
  * Maximum allowed threshold above which outputs will not be generated in their commitment
@@ -3561,7 +4933,7 @@ uint64_t ChannelHandshakeLimits_get_max_dust_limit_satoshis(const LDKChannelHand
  *
  * Default value: u64::max_value.
  */
-void ChannelHandshakeLimits_set_max_dust_limit_satoshis(LDKChannelHandshakeLimits *this_ptr, uint64_t val);
+void ChannelHandshakeLimits_set_max_dust_limit_satoshis(struct LDKChannelHandshakeLimits *NONNULL_PTR this_ptr, uint64_t val);
 
 /**
  * Before a channel is usable the funding transaction will need to be confirmed by at least a
@@ -3571,7 +4943,7 @@ void ChannelHandshakeLimits_set_max_dust_limit_satoshis(LDKChannelHandshakeLimit
  *
  * Default value: 144, or roughly one day and only applies to outbound channels.
  */
-uint32_t ChannelHandshakeLimits_get_max_minimum_depth(const LDKChannelHandshakeLimits *this_ptr);
+uint32_t ChannelHandshakeLimits_get_max_minimum_depth(const struct LDKChannelHandshakeLimits *NONNULL_PTR this_ptr);
 
 /**
  * Before a channel is usable the funding transaction will need to be confirmed by at least a
@@ -3581,7 +4953,7 @@ uint32_t ChannelHandshakeLimits_get_max_minimum_depth(const LDKChannelHandshakeL
  *
  * Default value: 144, or roughly one day and only applies to outbound channels.
  */
-void ChannelHandshakeLimits_set_max_minimum_depth(LDKChannelHandshakeLimits *this_ptr, uint32_t val);
+void ChannelHandshakeLimits_set_max_minimum_depth(struct LDKChannelHandshakeLimits *NONNULL_PTR this_ptr, uint32_t val);
 
 /**
  * Set to force the incoming channel to match our announced channel preference in
@@ -3590,7 +4962,7 @@ void ChannelHandshakeLimits_set_max_minimum_depth(LDKChannelHandshakeLimits *thi
  * Default value: true, to make the default that no announced channels are possible (which is
  * appropriate for any nodes which are not online very reliably).
  */
-bool ChannelHandshakeLimits_get_force_announced_channel_preference(const LDKChannelHandshakeLimits *this_ptr);
+bool ChannelHandshakeLimits_get_force_announced_channel_preference(const struct LDKChannelHandshakeLimits *NONNULL_PTR this_ptr);
 
 /**
  * Set to force the incoming channel to match our announced channel preference in
@@ -3599,7 +4971,7 @@ bool ChannelHandshakeLimits_get_force_announced_channel_preference(const LDKChan
  * Default value: true, to make the default that no announced channels are possible (which is
  * appropriate for any nodes which are not online very reliably).
  */
-void ChannelHandshakeLimits_set_force_announced_channel_preference(LDKChannelHandshakeLimits *this_ptr, bool val);
+void ChannelHandshakeLimits_set_force_announced_channel_preference(struct LDKChannelHandshakeLimits *NONNULL_PTR this_ptr, bool val);
 
 /**
  * Set to the amount of time we're willing to wait to claim money back to us.
@@ -3610,7 +4982,7 @@ void ChannelHandshakeLimits_set_force_announced_channel_preference(LDKChannelHan
  * Default value: MAX_LOCAL_BREAKDOWN_TIMEOUT (1008), which we also enforce as a maximum value
  * so you can tweak config to reduce the loss of having useless locked funds (if your peer accepts)
  */
-uint16_t ChannelHandshakeLimits_get_their_to_self_delay(const LDKChannelHandshakeLimits *this_ptr);
+uint16_t ChannelHandshakeLimits_get_their_to_self_delay(const struct LDKChannelHandshakeLimits *NONNULL_PTR this_ptr);
 
 /**
  * Set to the amount of time we're willing to wait to claim money back to us.
@@ -3621,15 +4993,15 @@ uint16_t ChannelHandshakeLimits_get_their_to_self_delay(const LDKChannelHandshak
  * Default value: MAX_LOCAL_BREAKDOWN_TIMEOUT (1008), which we also enforce as a maximum value
  * so you can tweak config to reduce the loss of having useless locked funds (if your peer accepts)
  */
-void ChannelHandshakeLimits_set_their_to_self_delay(LDKChannelHandshakeLimits *this_ptr, uint16_t val);
+void ChannelHandshakeLimits_set_their_to_self_delay(struct LDKChannelHandshakeLimits *NONNULL_PTR this_ptr, uint16_t val);
 
-MUST_USE_RES LDKChannelHandshakeLimits ChannelHandshakeLimits_new(uint64_t min_funding_satoshis_arg, uint64_t max_htlc_minimum_msat_arg, uint64_t min_max_htlc_value_in_flight_msat_arg, uint64_t max_channel_reserve_satoshis_arg, uint16_t min_max_accepted_htlcs_arg, uint64_t min_dust_limit_satoshis_arg, uint64_t max_dust_limit_satoshis_arg, uint32_t max_minimum_depth_arg, bool force_announced_channel_preference_arg, uint16_t their_to_self_delay_arg);
+MUST_USE_RES struct LDKChannelHandshakeLimits ChannelHandshakeLimits_new(uint64_t min_funding_satoshis_arg, uint64_t max_htlc_minimum_msat_arg, uint64_t min_max_htlc_value_in_flight_msat_arg, uint64_t max_channel_reserve_satoshis_arg, uint16_t min_max_accepted_htlcs_arg, uint64_t min_dust_limit_satoshis_arg, uint64_t max_dust_limit_satoshis_arg, uint32_t max_minimum_depth_arg, bool force_announced_channel_preference_arg, uint16_t their_to_self_delay_arg);
 
-MUST_USE_RES LDKChannelHandshakeLimits ChannelHandshakeLimits_default(void);
+struct LDKChannelHandshakeLimits ChannelHandshakeLimits_clone(const struct LDKChannelHandshakeLimits *NONNULL_PTR orig);
 
-void ChannelConfig_free(LDKChannelConfig this_ptr);
+MUST_USE_RES struct LDKChannelHandshakeLimits ChannelHandshakeLimits_default(void);
 
-LDKChannelConfig ChannelConfig_clone(const LDKChannelConfig *orig);
+void ChannelConfig_free(struct LDKChannelConfig this_ptr);
 
 /**
  * Amount (in millionths of a satoshi) the channel will charge per transferred satoshi.
@@ -3638,7 +5010,7 @@ LDKChannelConfig ChannelConfig_clone(const LDKChannelConfig *orig);
  *
  * Default value: 0.
  */
-uint32_t ChannelConfig_get_fee_proportional_millionths(const LDKChannelConfig *this_ptr);
+uint32_t ChannelConfig_get_fee_proportional_millionths(const struct LDKChannelConfig *NONNULL_PTR this_ptr);
 
 /**
  * Amount (in millionths of a satoshi) the channel will charge per transferred satoshi.
@@ -3647,7 +5019,7 @@ uint32_t ChannelConfig_get_fee_proportional_millionths(const LDKChannelConfig *t
  *
  * Default value: 0.
  */
-void ChannelConfig_set_fee_proportional_millionths(LDKChannelConfig *this_ptr, uint32_t val);
+void ChannelConfig_set_fee_proportional_millionths(struct LDKChannelConfig *NONNULL_PTR this_ptr, uint32_t val);
 
 /**
  * Set to announce the channel publicly and notify all nodes that they can route via this
@@ -3662,7 +5034,7 @@ void ChannelConfig_set_fee_proportional_millionths(LDKChannelConfig *this_ptr, u
  *
  * Default value: false.
  */
-bool ChannelConfig_get_announced_channel(const LDKChannelConfig *this_ptr);
+bool ChannelConfig_get_announced_channel(const struct LDKChannelConfig *NONNULL_PTR this_ptr);
 
 /**
  * Set to announce the channel publicly and notify all nodes that they can route via this
@@ -3677,7 +5049,7 @@ bool ChannelConfig_get_announced_channel(const LDKChannelConfig *this_ptr);
  *
  * Default value: false.
  */
-void ChannelConfig_set_announced_channel(LDKChannelConfig *this_ptr, bool val);
+void ChannelConfig_set_announced_channel(struct LDKChannelConfig *NONNULL_PTR this_ptr, bool val);
 
 /**
  * When set, we commit to an upfront shutdown_pubkey at channel open. If our counterparty
@@ -3692,7 +5064,7 @@ void ChannelConfig_set_announced_channel(LDKChannelConfig *this_ptr, bool val);
  *
  * Default value: true.
  */
-bool ChannelConfig_get_commit_upfront_shutdown_pubkey(const LDKChannelConfig *this_ptr);
+bool ChannelConfig_get_commit_upfront_shutdown_pubkey(const struct LDKChannelConfig *NONNULL_PTR this_ptr);
 
 /**
  * When set, we commit to an upfront shutdown_pubkey at channel open. If our counterparty
@@ -3707,84 +5079,91 @@ bool ChannelConfig_get_commit_upfront_shutdown_pubkey(const LDKChannelConfig *th
  *
  * Default value: true.
  */
-void ChannelConfig_set_commit_upfront_shutdown_pubkey(LDKChannelConfig *this_ptr, bool val);
+void ChannelConfig_set_commit_upfront_shutdown_pubkey(struct LDKChannelConfig *NONNULL_PTR this_ptr, bool val);
 
-MUST_USE_RES LDKChannelConfig ChannelConfig_new(uint32_t fee_proportional_millionths_arg, bool announced_channel_arg, bool commit_upfront_shutdown_pubkey_arg);
+MUST_USE_RES struct LDKChannelConfig ChannelConfig_new(uint32_t fee_proportional_millionths_arg, bool announced_channel_arg, bool commit_upfront_shutdown_pubkey_arg);
 
-MUST_USE_RES LDKChannelConfig ChannelConfig_default(void);
+struct LDKChannelConfig ChannelConfig_clone(const struct LDKChannelConfig *NONNULL_PTR orig);
 
-LDKCVec_u8Z ChannelConfig_write(const LDKChannelConfig *obj);
+MUST_USE_RES struct LDKChannelConfig ChannelConfig_default(void);
 
-LDKChannelConfig ChannelConfig_read(LDKu8slice ser);
+struct LDKCVec_u8Z ChannelConfig_write(const struct LDKChannelConfig *NONNULL_PTR obj);
 
-void UserConfig_free(LDKUserConfig this_ptr);
+struct LDKCResult_ChannelConfigDecodeErrorZ ChannelConfig_read(struct LDKu8slice ser);
 
-LDKUserConfig UserConfig_clone(const LDKUserConfig *orig);
+void UserConfig_free(struct LDKUserConfig this_ptr);
 
 /**
  * Channel config that we propose to our counterparty.
  */
-LDKChannelHandshakeConfig UserConfig_get_own_channel_config(const LDKUserConfig *this_ptr);
+struct LDKChannelHandshakeConfig UserConfig_get_own_channel_config(const struct LDKUserConfig *NONNULL_PTR this_ptr);
 
 /**
  * Channel config that we propose to our counterparty.
  */
-void UserConfig_set_own_channel_config(LDKUserConfig *this_ptr, LDKChannelHandshakeConfig val);
+void UserConfig_set_own_channel_config(struct LDKUserConfig *NONNULL_PTR this_ptr, struct LDKChannelHandshakeConfig val);
 
 /**
  * Limits applied to our counterparty's proposed channel config settings.
  */
-LDKChannelHandshakeLimits UserConfig_get_peer_channel_config_limits(const LDKUserConfig *this_ptr);
+struct LDKChannelHandshakeLimits UserConfig_get_peer_channel_config_limits(const struct LDKUserConfig *NONNULL_PTR this_ptr);
 
 /**
  * Limits applied to our counterparty's proposed channel config settings.
  */
-void UserConfig_set_peer_channel_config_limits(LDKUserConfig *this_ptr, LDKChannelHandshakeLimits val);
+void UserConfig_set_peer_channel_config_limits(struct LDKUserConfig *NONNULL_PTR this_ptr, struct LDKChannelHandshakeLimits val);
 
 /**
  * Channel config which affects behavior during channel lifetime.
  */
-LDKChannelConfig UserConfig_get_channel_options(const LDKUserConfig *this_ptr);
+struct LDKChannelConfig UserConfig_get_channel_options(const struct LDKUserConfig *NONNULL_PTR this_ptr);
 
 /**
  * Channel config which affects behavior during channel lifetime.
  */
-void UserConfig_set_channel_options(LDKUserConfig *this_ptr, LDKChannelConfig val);
+void UserConfig_set_channel_options(struct LDKUserConfig *NONNULL_PTR this_ptr, struct LDKChannelConfig val);
+
+MUST_USE_RES struct LDKUserConfig UserConfig_new(struct LDKChannelHandshakeConfig own_channel_config_arg, struct LDKChannelHandshakeLimits peer_channel_config_limits_arg, struct LDKChannelConfig channel_options_arg);
+
+struct LDKUserConfig UserConfig_clone(const struct LDKUserConfig *NONNULL_PTR orig);
 
-MUST_USE_RES LDKUserConfig UserConfig_new(LDKChannelHandshakeConfig own_channel_config_arg, LDKChannelHandshakeLimits peer_channel_config_limits_arg, LDKChannelConfig channel_options_arg);
+MUST_USE_RES struct LDKUserConfig UserConfig_default(void);
 
-MUST_USE_RES LDKUserConfig UserConfig_default(void);
+enum LDKAccessError AccessError_clone(const enum LDKAccessError *NONNULL_PTR orig);
 
-LDKAccessError AccessError_clone(const LDKAccessError *orig);
+/**
+ * Calls the free function if one is set
+ */
+void Access_free(struct LDKAccess this_ptr);
 
 /**
  * Calls the free function if one is set
  */
-void Access_free(LDKAccess this_ptr);
+void Listen_free(struct LDKListen this_ptr);
 
 /**
  * Calls the free function if one is set
  */
-void Watch_free(LDKWatch this_ptr);
+void Watch_free(struct LDKWatch this_ptr);
 
 /**
  * Calls the free function if one is set
  */
-void Filter_free(LDKFilter this_ptr);
+void Filter_free(struct LDKFilter this_ptr);
 
 /**
  * Calls the free function if one is set
  */
-void BroadcasterInterface_free(LDKBroadcasterInterface this_ptr);
+void BroadcasterInterface_free(struct LDKBroadcasterInterface this_ptr);
 
-LDKConfirmationTarget ConfirmationTarget_clone(const LDKConfirmationTarget *orig);
+enum LDKConfirmationTarget ConfirmationTarget_clone(const enum LDKConfirmationTarget *NONNULL_PTR orig);
 
 /**
  * Calls the free function if one is set
  */
-void FeeEstimator_free(LDKFeeEstimator this_ptr);
+void FeeEstimator_free(struct LDKFeeEstimator this_ptr);
 
-void ChainMonitor_free(LDKChainMonitor this_ptr);
+void ChainMonitor_free(struct LDKChainMonitor this_ptr);
 
 /**
  * Dispatches to per-channel monitors, which are responsible for updating their on-chain view
@@ -3801,7 +5180,7 @@ void ChainMonitor_free(LDKChainMonitor this_ptr);
  * [`chain::Watch::release_pending_monitor_events`]: ../trait.Watch.html#tymethod.release_pending_monitor_events
  * [`chain::Filter`]: ../trait.Filter.html
  */
-void ChainMonitor_block_connected(const LDKChainMonitor *this_arg, const uint8_t (*header)[80], LDKCVec_C2Tuple_usizeTransactionZZ txdata, uint32_t height);
+void ChainMonitor_block_connected(const struct LDKChainMonitor *NONNULL_PTR this_arg, const uint8_t (*header)[80], struct LDKCVec_C2Tuple_usizeTransactionZZ txdata, uint32_t height);
 
 /**
  * Dispatches to per-channel monitors, which are responsible for updating their on-chain view
@@ -3810,7 +5189,7 @@ void ChainMonitor_block_connected(const LDKChainMonitor *this_arg, const uint8_t
  *
  * [`ChannelMonitor::block_disconnected`]: ../channelmonitor/struct.ChannelMonitor.html#method.block_disconnected
  */
-void ChainMonitor_block_disconnected(const LDKChainMonitor *this_arg, const uint8_t (*header)[80], uint32_t disconnected_height);
+void ChainMonitor_block_disconnected(const struct LDKChainMonitor *NONNULL_PTR this_arg, const uint8_t (*header)[80], uint32_t disconnected_height);
 
 /**
  * Creates a new `ChainMonitor` used to watch on-chain activity pertaining to channels.
@@ -3823,15 +5202,13 @@ void ChainMonitor_block_disconnected(const LDKChainMonitor *this_arg, const uint
  *
  * [`chain::Filter`]: ../trait.Filter.html
  */
-MUST_USE_RES LDKChainMonitor ChainMonitor_new(LDKFilter *chain_source, LDKBroadcasterInterface broadcaster, LDKLogger logger, LDKFeeEstimator feeest, LDKPersist persister);
-
-LDKWatch ChainMonitor_as_Watch(const LDKChainMonitor *this_arg);
+MUST_USE_RES struct LDKChainMonitor ChainMonitor_new(struct LDKFilter *chain_source, struct LDKBroadcasterInterface broadcaster, struct LDKLogger logger, struct LDKFeeEstimator feeest, struct LDKPersist persister);
 
-LDKEventsProvider ChainMonitor_as_EventsProvider(const LDKChainMonitor *this_arg);
+struct LDKWatch ChainMonitor_as_Watch(const struct LDKChainMonitor *NONNULL_PTR this_arg);
 
-void ChannelMonitorUpdate_free(LDKChannelMonitorUpdate this_ptr);
+struct LDKEventsProvider ChainMonitor_as_EventsProvider(const struct LDKChainMonitor *NONNULL_PTR this_arg);
 
-LDKChannelMonitorUpdate ChannelMonitorUpdate_clone(const LDKChannelMonitorUpdate *orig);
+void ChannelMonitorUpdate_free(struct LDKChannelMonitorUpdate this_ptr);
 
 /**
  * The sequence number of this update. Updates *must* be replayed in-order according to this
@@ -3848,7 +5225,7 @@ LDKChannelMonitorUpdate ChannelMonitorUpdate_clone(const LDKChannelMonitorUpdate
  *
  * [`CLOSED_CHANNEL_UPDATE_ID`]: constant.CLOSED_CHANNEL_UPDATE_ID.html
  */
-uint64_t ChannelMonitorUpdate_get_update_id(const LDKChannelMonitorUpdate *this_ptr);
+uint64_t ChannelMonitorUpdate_get_update_id(const struct LDKChannelMonitorUpdate *NONNULL_PTR this_ptr);
 
 /**
  * The sequence number of this update. Updates *must* be replayed in-order according to this
@@ -3865,29 +5242,35 @@ uint64_t ChannelMonitorUpdate_get_update_id(const LDKChannelMonitorUpdate *this_
  *
  * [`CLOSED_CHANNEL_UPDATE_ID`]: constant.CLOSED_CHANNEL_UPDATE_ID.html
  */
-void ChannelMonitorUpdate_set_update_id(LDKChannelMonitorUpdate *this_ptr, uint64_t val);
+void ChannelMonitorUpdate_set_update_id(struct LDKChannelMonitorUpdate *NONNULL_PTR this_ptr, uint64_t val);
 
-LDKCVec_u8Z ChannelMonitorUpdate_write(const LDKChannelMonitorUpdate *obj);
+struct LDKChannelMonitorUpdate ChannelMonitorUpdate_clone(const struct LDKChannelMonitorUpdate *NONNULL_PTR orig);
 
-LDKChannelMonitorUpdate ChannelMonitorUpdate_read(LDKu8slice ser);
+struct LDKCVec_u8Z ChannelMonitorUpdate_write(const struct LDKChannelMonitorUpdate *NONNULL_PTR obj);
 
-LDKChannelMonitorUpdateErr ChannelMonitorUpdateErr_clone(const LDKChannelMonitorUpdateErr *orig);
+struct LDKCResult_ChannelMonitorUpdateDecodeErrorZ ChannelMonitorUpdate_read(struct LDKu8slice ser);
 
-void MonitorUpdateError_free(LDKMonitorUpdateError this_ptr);
+enum LDKChannelMonitorUpdateErr ChannelMonitorUpdateErr_clone(const enum LDKChannelMonitorUpdateErr *NONNULL_PTR orig);
 
-void MonitorEvent_free(LDKMonitorEvent this_ptr);
+void MonitorUpdateError_free(struct LDKMonitorUpdateError this_ptr);
 
-LDKMonitorEvent MonitorEvent_clone(const LDKMonitorEvent *orig);
+struct LDKMonitorUpdateError MonitorUpdateError_clone(const struct LDKMonitorUpdateError *NONNULL_PTR orig);
 
-void HTLCUpdate_free(LDKHTLCUpdate this_ptr);
+void MonitorEvent_free(struct LDKMonitorEvent this_ptr);
 
-LDKHTLCUpdate HTLCUpdate_clone(const LDKHTLCUpdate *orig);
+struct LDKMonitorEvent MonitorEvent_clone(const struct LDKMonitorEvent *NONNULL_PTR orig);
 
-LDKCVec_u8Z HTLCUpdate_write(const LDKHTLCUpdate *obj);
+void HTLCUpdate_free(struct LDKHTLCUpdate this_ptr);
 
-LDKHTLCUpdate HTLCUpdate_read(LDKu8slice ser);
+struct LDKHTLCUpdate HTLCUpdate_clone(const struct LDKHTLCUpdate *NONNULL_PTR orig);
 
-void ChannelMonitor_free(LDKChannelMonitor this_ptr);
+struct LDKCVec_u8Z HTLCUpdate_write(const struct LDKHTLCUpdate *NONNULL_PTR obj);
+
+struct LDKCResult_HTLCUpdateDecodeErrorZ HTLCUpdate_read(struct LDKu8slice ser);
+
+void ChannelMonitor_free(struct LDKChannelMonitor this_ptr);
+
+struct LDKCVec_u8Z ChannelMonitor_write(const struct LDKChannelMonitor *NONNULL_PTR obj);
 
 /**
  * Updates a ChannelMonitor on the basis of some new information provided by the Channel
@@ -3895,18 +5278,18 @@ void ChannelMonitor_free(LDKChannelMonitor this_ptr);
  *
  * panics if the given update is not the next update by update_id.
  */
-MUST_USE_RES LDKCResult_NoneMonitorUpdateErrorZ ChannelMonitor_update_monitor(LDKChannelMonitor *this_arg, const LDKChannelMonitorUpdate *updates, const LDKBroadcasterInterface *broadcaster, const LDKFeeEstimator *fee_estimator, const LDKLogger *logger);
+MUST_USE_RES struct LDKCResult_NoneMonitorUpdateErrorZ ChannelMonitor_update_monitor(struct LDKChannelMonitor *NONNULL_PTR this_arg, const struct LDKChannelMonitorUpdate *NONNULL_PTR updates, const struct LDKBroadcasterInterface *NONNULL_PTR broadcaster, const struct LDKFeeEstimator *NONNULL_PTR fee_estimator, const struct LDKLogger *NONNULL_PTR logger);
 
 /**
  * Gets the update_id from the latest ChannelMonitorUpdate which was applied to this
  * ChannelMonitor.
  */
-MUST_USE_RES uint64_t ChannelMonitor_get_latest_update_id(const LDKChannelMonitor *this_arg);
+MUST_USE_RES uint64_t ChannelMonitor_get_latest_update_id(const struct LDKChannelMonitor *NONNULL_PTR this_arg);
 
 /**
  * Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
  */
-MUST_USE_RES LDKC2Tuple_OutPointScriptZ ChannelMonitor_get_funding_txo(const LDKChannelMonitor *this_arg);
+MUST_USE_RES struct LDKC2Tuple_OutPointScriptZ ChannelMonitor_get_funding_txo(const struct LDKChannelMonitor *NONNULL_PTR this_arg);
 
 /**
  * Get the list of HTLCs who's status has been updated on chain. This should be called by
@@ -3914,7 +5297,7 @@ MUST_USE_RES LDKC2Tuple_OutPointScriptZ ChannelMonitor_get_funding_txo(const LDK
  *
  * [`chain::Watch::release_pending_monitor_events`]: ../trait.Watch.html#tymethod.release_pending_monitor_events
  */
-MUST_USE_RES LDKCVec_MonitorEventZ ChannelMonitor_get_and_clear_pending_monitor_events(LDKChannelMonitor *this_arg);
+MUST_USE_RES struct LDKCVec_MonitorEventZ ChannelMonitor_get_and_clear_pending_monitor_events(struct LDKChannelMonitor *NONNULL_PTR this_arg);
 
 /**
  * Gets the list of pending events which were generated by previous actions, clearing the list
@@ -3924,7 +5307,7 @@ MUST_USE_RES LDKCVec_MonitorEventZ ChannelMonitor_get_and_clear_pending_monitor_
  * EventsProvider::get_and_clear_pending_events() except that it requires &mut self as we do
  * no internal locking in ChannelMonitors.
  */
-MUST_USE_RES LDKCVec_EventZ ChannelMonitor_get_and_clear_pending_events(LDKChannelMonitor *this_arg);
+MUST_USE_RES struct LDKCVec_EventZ ChannelMonitor_get_and_clear_pending_events(struct LDKChannelMonitor *NONNULL_PTR this_arg);
 
 /**
  * Used by ChannelManager deserialization to broadcast the latest holder state if its copy of
@@ -3937,7 +5320,7 @@ MUST_USE_RES LDKCVec_EventZ ChannelMonitor_get_and_clear_pending_events(LDKChann
  * out-of-band the other node operator to coordinate with him if option is available to you.
  * In any-case, choice is up to the user.
  */
-MUST_USE_RES LDKCVec_TransactionZ ChannelMonitor_get_latest_holder_commitment_txn(LDKChannelMonitor *this_arg, const LDKLogger *logger);
+MUST_USE_RES struct LDKCVec_TransactionZ ChannelMonitor_get_latest_holder_commitment_txn(struct LDKChannelMonitor *NONNULL_PTR this_arg, const struct LDKLogger *NONNULL_PTR logger);
 
 /**
  * Processes transactions in a newly connected block, which may result in any of the following:
@@ -3952,169 +5335,337 @@ MUST_USE_RES LDKCVec_TransactionZ ChannelMonitor_get_latest_holder_commitment_tx
  *
  * [`get_outputs_to_watch`]: #method.get_outputs_to_watch
  */
-MUST_USE_RES LDKCVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ ChannelMonitor_block_connected(LDKChannelMonitor *this_arg, const uint8_t (*header)[80], LDKCVec_C2Tuple_usizeTransactionZZ txdata, uint32_t height, LDKBroadcasterInterface broadcaster, LDKFeeEstimator fee_estimator, LDKLogger logger);
+MUST_USE_RES struct LDKCVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ ChannelMonitor_block_connected(struct LDKChannelMonitor *NONNULL_PTR this_arg, const uint8_t (*header)[80], struct LDKCVec_C2Tuple_usizeTransactionZZ txdata, uint32_t height, struct LDKBroadcasterInterface broadcaster, struct LDKFeeEstimator fee_estimator, struct LDKLogger logger);
+
+/**
+ * Determines if the disconnected block contained any transactions of interest and updates
+ * appropriately.
+ */
+void ChannelMonitor_block_disconnected(struct LDKChannelMonitor *NONNULL_PTR this_arg, const uint8_t (*header)[80], uint32_t height, struct LDKBroadcasterInterface broadcaster, struct LDKFeeEstimator fee_estimator, struct LDKLogger logger);
+
+/**
+ * Calls the free function if one is set
+ */
+void Persist_free(struct LDKPersist this_ptr);
+
+struct LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ C2Tuple_BlockHashChannelMonitorZ_read(struct LDKu8slice ser, const struct LDKKeysInterface *NONNULL_PTR arg);
+
+void OutPoint_free(struct LDKOutPoint this_ptr);
+
+/**
+ * The referenced transaction's txid.
+ */
+const uint8_t (*OutPoint_get_txid(const struct LDKOutPoint *NONNULL_PTR this_ptr))[32];
+
+/**
+ * The referenced transaction's txid.
+ */
+void OutPoint_set_txid(struct LDKOutPoint *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
+
+/**
+ * The index of the referenced output in its transaction's vout.
+ */
+uint16_t OutPoint_get_index(const struct LDKOutPoint *NONNULL_PTR this_ptr);
+
+/**
+ * The index of the referenced output in its transaction's vout.
+ */
+void OutPoint_set_index(struct LDKOutPoint *NONNULL_PTR this_ptr, uint16_t val);
+
+MUST_USE_RES struct LDKOutPoint OutPoint_new(struct LDKThirtyTwoBytes txid_arg, uint16_t index_arg);
+
+struct LDKOutPoint OutPoint_clone(const struct LDKOutPoint *NONNULL_PTR orig);
+
+/**
+ * Convert an `OutPoint` to a lightning channel id.
+ */
+MUST_USE_RES struct LDKThirtyTwoBytes OutPoint_to_channel_id(const struct LDKOutPoint *NONNULL_PTR this_arg);
+
+struct LDKCVec_u8Z OutPoint_write(const struct LDKOutPoint *NONNULL_PTR obj);
+
+struct LDKCResult_OutPointDecodeErrorZ OutPoint_read(struct LDKu8slice ser);
+
+void DelayedPaymentOutputDescriptor_free(struct LDKDelayedPaymentOutputDescriptor this_ptr);
+
+/**
+ * The outpoint which is spendable
+ */
+struct LDKOutPoint DelayedPaymentOutputDescriptor_get_outpoint(const struct LDKDelayedPaymentOutputDescriptor *NONNULL_PTR this_ptr);
+
+/**
+ * The outpoint which is spendable
+ */
+void DelayedPaymentOutputDescriptor_set_outpoint(struct LDKDelayedPaymentOutputDescriptor *NONNULL_PTR this_ptr, struct LDKOutPoint val);
+
+/**
+ * Per commitment point to derive delayed_payment_key by key holder
+ */
+struct LDKPublicKey DelayedPaymentOutputDescriptor_get_per_commitment_point(const struct LDKDelayedPaymentOutputDescriptor *NONNULL_PTR this_ptr);
+
+/**
+ * Per commitment point to derive delayed_payment_key by key holder
+ */
+void DelayedPaymentOutputDescriptor_set_per_commitment_point(struct LDKDelayedPaymentOutputDescriptor *NONNULL_PTR this_ptr, struct LDKPublicKey val);
+
+/**
+ * The nSequence value which must be set in the spending input to satisfy the OP_CSV in
+ * the witness_script.
+ */
+uint16_t DelayedPaymentOutputDescriptor_get_to_self_delay(const struct LDKDelayedPaymentOutputDescriptor *NONNULL_PTR this_ptr);
+
+/**
+ * The nSequence value which must be set in the spending input to satisfy the OP_CSV in
+ * the witness_script.
+ */
+void DelayedPaymentOutputDescriptor_set_to_self_delay(struct LDKDelayedPaymentOutputDescriptor *NONNULL_PTR this_ptr, uint16_t val);
+
+/**
+ * The output which is referenced by the given outpoint
+ */
+void DelayedPaymentOutputDescriptor_set_output(struct LDKDelayedPaymentOutputDescriptor *NONNULL_PTR this_ptr, struct LDKTxOut val);
+
+/**
+ * The revocation point specific to the commitment transaction which was broadcast. Used to
+ * derive the witnessScript for this output.
+ */
+struct LDKPublicKey DelayedPaymentOutputDescriptor_get_revocation_pubkey(const struct LDKDelayedPaymentOutputDescriptor *NONNULL_PTR this_ptr);
+
+/**
+ * The revocation point specific to the commitment transaction which was broadcast. Used to
+ * derive the witnessScript for this output.
+ */
+void DelayedPaymentOutputDescriptor_set_revocation_pubkey(struct LDKDelayedPaymentOutputDescriptor *NONNULL_PTR this_ptr, struct LDKPublicKey val);
+
+/**
+ * Arbitrary identification information returned by a call to
+ * `Sign::channel_keys_id()`. This may be useful in re-deriving keys used in
+ * the channel to spend the output.
+ */
+const uint8_t (*DelayedPaymentOutputDescriptor_get_channel_keys_id(const struct LDKDelayedPaymentOutputDescriptor *NONNULL_PTR this_ptr))[32];
+
+/**
+ * Arbitrary identification information returned by a call to
+ * `Sign::channel_keys_id()`. This may be useful in re-deriving keys used in
+ * the channel to spend the output.
+ */
+void DelayedPaymentOutputDescriptor_set_channel_keys_id(struct LDKDelayedPaymentOutputDescriptor *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
 
 /**
- * Determines if the disconnected block contained any transactions of interest and updates
- * appropriately.
+ * The value of the channel which this output originated from, possibly indirectly.
  */
-void ChannelMonitor_block_disconnected(LDKChannelMonitor *this_arg, const uint8_t (*header)[80], uint32_t height, LDKBroadcasterInterface broadcaster, LDKFeeEstimator fee_estimator, LDKLogger logger);
+uint64_t DelayedPaymentOutputDescriptor_get_channel_value_satoshis(const struct LDKDelayedPaymentOutputDescriptor *NONNULL_PTR this_ptr);
 
 /**
- * Calls the free function if one is set
+ * The value of the channel which this output originated from, possibly indirectly.
  */
-void Persist_free(LDKPersist this_ptr);
+void DelayedPaymentOutputDescriptor_set_channel_value_satoshis(struct LDKDelayedPaymentOutputDescriptor *NONNULL_PTR this_ptr, uint64_t val);
+
+MUST_USE_RES struct LDKDelayedPaymentOutputDescriptor DelayedPaymentOutputDescriptor_new(struct LDKOutPoint outpoint_arg, struct LDKPublicKey per_commitment_point_arg, uint16_t to_self_delay_arg, struct LDKTxOut output_arg, struct LDKPublicKey revocation_pubkey_arg, struct LDKThirtyTwoBytes channel_keys_id_arg, uint64_t channel_value_satoshis_arg);
 
-void OutPoint_free(LDKOutPoint this_ptr);
+struct LDKDelayedPaymentOutputDescriptor DelayedPaymentOutputDescriptor_clone(const struct LDKDelayedPaymentOutputDescriptor *NONNULL_PTR orig);
 
-LDKOutPoint OutPoint_clone(const LDKOutPoint *orig);
+void StaticPaymentOutputDescriptor_free(struct LDKStaticPaymentOutputDescriptor this_ptr);
 
 /**
- * The referenced transaction's txid.
+ * The outpoint which is spendable
  */
-const uint8_t (*OutPoint_get_txid(const LDKOutPoint *this_ptr))[32];
+struct LDKOutPoint StaticPaymentOutputDescriptor_get_outpoint(const struct LDKStaticPaymentOutputDescriptor *NONNULL_PTR this_ptr);
 
 /**
- * The referenced transaction's txid.
+ * The outpoint which is spendable
  */
-void OutPoint_set_txid(LDKOutPoint *this_ptr, LDKThirtyTwoBytes val);
+void StaticPaymentOutputDescriptor_set_outpoint(struct LDKStaticPaymentOutputDescriptor *NONNULL_PTR this_ptr, struct LDKOutPoint val);
 
 /**
- * The index of the referenced output in its transaction's vout.
+ * The output which is referenced by the given outpoint
  */
-uint16_t OutPoint_get_index(const LDKOutPoint *this_ptr);
+void StaticPaymentOutputDescriptor_set_output(struct LDKStaticPaymentOutputDescriptor *NONNULL_PTR this_ptr, struct LDKTxOut val);
 
 /**
- * The index of the referenced output in its transaction's vout.
+ * Arbitrary identification information returned by a call to
+ * `Sign::channel_keys_id()`. This may be useful in re-deriving keys used in
+ * the channel to spend the output.
  */
-void OutPoint_set_index(LDKOutPoint *this_ptr, uint16_t val);
+const uint8_t (*StaticPaymentOutputDescriptor_get_channel_keys_id(const struct LDKStaticPaymentOutputDescriptor *NONNULL_PTR this_ptr))[32];
 
-MUST_USE_RES LDKOutPoint OutPoint_new(LDKThirtyTwoBytes txid_arg, uint16_t index_arg);
+/**
+ * Arbitrary identification information returned by a call to
+ * `Sign::channel_keys_id()`. This may be useful in re-deriving keys used in
+ * the channel to spend the output.
+ */
+void StaticPaymentOutputDescriptor_set_channel_keys_id(struct LDKStaticPaymentOutputDescriptor *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
 
 /**
- * Convert an `OutPoint` to a lightning channel id.
+ * The value of the channel which this transactions spends.
+ */
+uint64_t StaticPaymentOutputDescriptor_get_channel_value_satoshis(const struct LDKStaticPaymentOutputDescriptor *NONNULL_PTR this_ptr);
+
+/**
+ * The value of the channel which this transactions spends.
  */
-MUST_USE_RES LDKThirtyTwoBytes OutPoint_to_channel_id(const LDKOutPoint *this_arg);
+void StaticPaymentOutputDescriptor_set_channel_value_satoshis(struct LDKStaticPaymentOutputDescriptor *NONNULL_PTR this_ptr, uint64_t val);
+
+MUST_USE_RES struct LDKStaticPaymentOutputDescriptor StaticPaymentOutputDescriptor_new(struct LDKOutPoint outpoint_arg, struct LDKTxOut output_arg, struct LDKThirtyTwoBytes channel_keys_id_arg, uint64_t channel_value_satoshis_arg);
+
+struct LDKStaticPaymentOutputDescriptor StaticPaymentOutputDescriptor_clone(const struct LDKStaticPaymentOutputDescriptor *NONNULL_PTR orig);
 
-LDKCVec_u8Z OutPoint_write(const LDKOutPoint *obj);
+void SpendableOutputDescriptor_free(struct LDKSpendableOutputDescriptor this_ptr);
 
-LDKOutPoint OutPoint_read(LDKu8slice ser);
+struct LDKSpendableOutputDescriptor SpendableOutputDescriptor_clone(const struct LDKSpendableOutputDescriptor *NONNULL_PTR orig);
 
-void SpendableOutputDescriptor_free(LDKSpendableOutputDescriptor this_ptr);
+struct LDKCVec_u8Z SpendableOutputDescriptor_write(const struct LDKSpendableOutputDescriptor *NONNULL_PTR obj);
 
-LDKSpendableOutputDescriptor SpendableOutputDescriptor_clone(const LDKSpendableOutputDescriptor *orig);
+struct LDKCResult_SpendableOutputDescriptorDecodeErrorZ SpendableOutputDescriptor_read(struct LDKu8slice ser);
 
-LDKChannelKeys ChannelKeys_clone(const LDKChannelKeys *orig);
+struct LDKSign Sign_clone(const struct LDKSign *NONNULL_PTR orig);
 
 /**
  * Calls the free function if one is set
  */
-void ChannelKeys_free(LDKChannelKeys this_ptr);
+void Sign_free(struct LDKSign this_ptr);
 
 /**
  * Calls the free function if one is set
  */
-void KeysInterface_free(LDKKeysInterface this_ptr);
+void KeysInterface_free(struct LDKKeysInterface this_ptr);
 
-void InMemoryChannelKeys_free(LDKInMemoryChannelKeys this_ptr);
-
-LDKInMemoryChannelKeys InMemoryChannelKeys_clone(const LDKInMemoryChannelKeys *orig);
+void InMemorySigner_free(struct LDKInMemorySigner this_ptr);
 
 /**
  * Private key of anchor tx
  */
-const uint8_t (*InMemoryChannelKeys_get_funding_key(const LDKInMemoryChannelKeys *this_ptr))[32];
+const uint8_t (*InMemorySigner_get_funding_key(const struct LDKInMemorySigner *NONNULL_PTR this_ptr))[32];
 
 /**
  * Private key of anchor tx
  */
-void InMemoryChannelKeys_set_funding_key(LDKInMemoryChannelKeys *this_ptr, LDKSecretKey val);
+void InMemorySigner_set_funding_key(struct LDKInMemorySigner *NONNULL_PTR this_ptr, struct LDKSecretKey val);
 
 /**
  * Holder secret key for blinded revocation pubkey
  */
-const uint8_t (*InMemoryChannelKeys_get_revocation_base_key(const LDKInMemoryChannelKeys *this_ptr))[32];
+const uint8_t (*InMemorySigner_get_revocation_base_key(const struct LDKInMemorySigner *NONNULL_PTR this_ptr))[32];
 
 /**
  * Holder secret key for blinded revocation pubkey
  */
-void InMemoryChannelKeys_set_revocation_base_key(LDKInMemoryChannelKeys *this_ptr, LDKSecretKey val);
+void InMemorySigner_set_revocation_base_key(struct LDKInMemorySigner *NONNULL_PTR this_ptr, struct LDKSecretKey val);
 
 /**
  * Holder secret key used for our balance in counterparty-broadcasted commitment transactions
  */
-const uint8_t (*InMemoryChannelKeys_get_payment_key(const LDKInMemoryChannelKeys *this_ptr))[32];
+const uint8_t (*InMemorySigner_get_payment_key(const struct LDKInMemorySigner *NONNULL_PTR this_ptr))[32];
 
 /**
  * Holder secret key used for our balance in counterparty-broadcasted commitment transactions
  */
-void InMemoryChannelKeys_set_payment_key(LDKInMemoryChannelKeys *this_ptr, LDKSecretKey val);
+void InMemorySigner_set_payment_key(struct LDKInMemorySigner *NONNULL_PTR this_ptr, struct LDKSecretKey val);
 
 /**
  * Holder secret key used in HTLC tx
  */
-const uint8_t (*InMemoryChannelKeys_get_delayed_payment_base_key(const LDKInMemoryChannelKeys *this_ptr))[32];
+const uint8_t (*InMemorySigner_get_delayed_payment_base_key(const struct LDKInMemorySigner *NONNULL_PTR this_ptr))[32];
 
 /**
  * Holder secret key used in HTLC tx
  */
-void InMemoryChannelKeys_set_delayed_payment_base_key(LDKInMemoryChannelKeys *this_ptr, LDKSecretKey val);
+void InMemorySigner_set_delayed_payment_base_key(struct LDKInMemorySigner *NONNULL_PTR this_ptr, struct LDKSecretKey val);
 
 /**
  * Holder htlc secret key used in commitment tx htlc outputs
  */
-const uint8_t (*InMemoryChannelKeys_get_htlc_base_key(const LDKInMemoryChannelKeys *this_ptr))[32];
+const uint8_t (*InMemorySigner_get_htlc_base_key(const struct LDKInMemorySigner *NONNULL_PTR this_ptr))[32];
 
 /**
  * Holder htlc secret key used in commitment tx htlc outputs
  */
-void InMemoryChannelKeys_set_htlc_base_key(LDKInMemoryChannelKeys *this_ptr, LDKSecretKey val);
+void InMemorySigner_set_htlc_base_key(struct LDKInMemorySigner *NONNULL_PTR this_ptr, struct LDKSecretKey val);
 
 /**
  * Commitment seed
  */
-const uint8_t (*InMemoryChannelKeys_get_commitment_seed(const LDKInMemoryChannelKeys *this_ptr))[32];
+const uint8_t (*InMemorySigner_get_commitment_seed(const struct LDKInMemorySigner *NONNULL_PTR this_ptr))[32];
 
 /**
  * Commitment seed
  */
-void InMemoryChannelKeys_set_commitment_seed(LDKInMemoryChannelKeys *this_ptr, LDKThirtyTwoBytes val);
+void InMemorySigner_set_commitment_seed(struct LDKInMemorySigner *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
+
+struct LDKInMemorySigner InMemorySigner_clone(const struct LDKInMemorySigner *NONNULL_PTR orig);
 
 /**
- * Create a new InMemoryChannelKeys
+ * Create a new InMemorySigner
  */
-MUST_USE_RES LDKInMemoryChannelKeys InMemoryChannelKeys_new(LDKSecretKey funding_key, LDKSecretKey revocation_base_key, LDKSecretKey payment_key, LDKSecretKey delayed_payment_base_key, LDKSecretKey htlc_base_key, LDKThirtyTwoBytes commitment_seed, uint64_t channel_value_satoshis, LDKC2Tuple_u64u64Z key_derivation_params);
+MUST_USE_RES struct LDKInMemorySigner InMemorySigner_new(struct LDKSecretKey funding_key, struct LDKSecretKey revocation_base_key, struct LDKSecretKey payment_key, struct LDKSecretKey delayed_payment_base_key, struct LDKSecretKey htlc_base_key, struct LDKThirtyTwoBytes commitment_seed, uint64_t channel_value_satoshis, struct LDKThirtyTwoBytes channel_keys_id);
 
 /**
  * Counterparty pubkeys.
- * Will panic if on_accept wasn't called.
+ * Will panic if ready_channel wasn't called.
  */
-MUST_USE_RES LDKChannelPublicKeys InMemoryChannelKeys_counterparty_pubkeys(const LDKInMemoryChannelKeys *this_arg);
+MUST_USE_RES struct LDKChannelPublicKeys InMemorySigner_counterparty_pubkeys(const struct LDKInMemorySigner *NONNULL_PTR this_arg);
 
 /**
  * The contest_delay value specified by our counterparty and applied on holder-broadcastable
  * transactions, ie the amount of time that we have to wait to recover our funds if we
- * broadcast a transaction. You'll likely want to pass this to the
- * ln::chan_utils::build*_transaction functions when signing holder's transactions.
- * Will panic if on_accept wasn't called.
+ * broadcast a transaction.
+ * Will panic if ready_channel wasn't called.
  */
-MUST_USE_RES uint16_t InMemoryChannelKeys_counterparty_selected_contest_delay(const LDKInMemoryChannelKeys *this_arg);
+MUST_USE_RES uint16_t InMemorySigner_counterparty_selected_contest_delay(const struct LDKInMemorySigner *NONNULL_PTR this_arg);
 
 /**
  * The contest_delay value specified by us and applied on transactions broadcastable
  * by our counterparty, ie the amount of time that they have to wait to recover their funds
  * if they broadcast a transaction.
- * Will panic if on_accept wasn't called.
+ * Will panic if ready_channel wasn't called.
+ */
+MUST_USE_RES uint16_t InMemorySigner_holder_selected_contest_delay(const struct LDKInMemorySigner *NONNULL_PTR this_arg);
+
+/**
+ * Whether the holder is the initiator
+ * Will panic if ready_channel wasn't called.
+ */
+MUST_USE_RES bool InMemorySigner_is_outbound(const struct LDKInMemorySigner *NONNULL_PTR this_arg);
+
+/**
+ * Funding outpoint
+ * Will panic if ready_channel wasn't called.
+ */
+MUST_USE_RES struct LDKOutPoint InMemorySigner_funding_outpoint(const struct LDKInMemorySigner *NONNULL_PTR this_arg);
+
+/**
+ * Obtain a ChannelTransactionParameters for this channel, to be used when verifying or
+ * building transactions.
+ *
+ * Will panic if ready_channel wasn't called.
+ */
+MUST_USE_RES struct LDKChannelTransactionParameters InMemorySigner_get_channel_parameters(const struct LDKInMemorySigner *NONNULL_PTR this_arg);
+
+/**
+ * Sign the single input of spend_tx at index `input_idx` which spends the output
+ * described by descriptor, returning the witness stack for the input.
+ *
+ * Returns an Err if the input at input_idx does not exist, has a non-empty script_sig,
+ * or is not spending the outpoint described by `descriptor.outpoint`.
  */
-MUST_USE_RES uint16_t InMemoryChannelKeys_holder_selected_contest_delay(const LDKInMemoryChannelKeys *this_arg);
+MUST_USE_RES struct LDKCResult_CVec_CVec_u8ZZNoneZ InMemorySigner_sign_counterparty_payment_input(const struct LDKInMemorySigner *NONNULL_PTR this_arg, struct LDKTransaction spend_tx, uintptr_t input_idx, const struct LDKStaticPaymentOutputDescriptor *NONNULL_PTR descriptor);
 
-LDKChannelKeys InMemoryChannelKeys_as_ChannelKeys(const LDKInMemoryChannelKeys *this_arg);
+/**
+ * Sign the single input of spend_tx at index `input_idx` which spends the output
+ * described by descriptor, returning the witness stack for the input.
+ *
+ * Returns an Err if the input at input_idx does not exist, has a non-empty script_sig,
+ * is not spending the outpoint described by `descriptor.outpoint`, or does not have a
+ * sequence set to `descriptor.to_self_delay`.
+ */
+MUST_USE_RES struct LDKCResult_CVec_CVec_u8ZZNoneZ InMemorySigner_sign_dynamic_p2wsh_input(const struct LDKInMemorySigner *NONNULL_PTR this_arg, struct LDKTransaction spend_tx, uintptr_t input_idx, const struct LDKDelayedPaymentOutputDescriptor *NONNULL_PTR descriptor);
+
+struct LDKSign InMemorySigner_as_Sign(const struct LDKInMemorySigner *NONNULL_PTR this_arg);
 
-LDKCVec_u8Z InMemoryChannelKeys_write(const LDKInMemoryChannelKeys *obj);
+struct LDKCVec_u8Z InMemorySigner_write(const struct LDKInMemorySigner *NONNULL_PTR obj);
 
-LDKInMemoryChannelKeys InMemoryChannelKeys_read(LDKu8slice ser);
+struct LDKCResult_InMemorySignerDecodeErrorZ InMemorySigner_read(struct LDKu8slice ser);
 
-void KeysManager_free(LDKKeysManager this_ptr);
+void KeysManager_free(struct LDKKeysManager this_ptr);
 
 /**
  * Constructs a KeysManager from a 32-byte seed. If the seed is in some way biased (eg your
@@ -4137,24 +5688,37 @@ void KeysManager_free(LDKKeysManager this_ptr);
  * versions. Once the library is more fully supported, the docs will be updated to include a
  * detailed description of the guarantee.
  */
-MUST_USE_RES LDKKeysManager KeysManager_new(const uint8_t (*seed)[32], LDKNetwork network, uint64_t starting_time_secs, uint32_t starting_time_nanos);
+MUST_USE_RES struct LDKKeysManager KeysManager_new(const uint8_t (*seed)[32], uint64_t starting_time_secs, uint32_t starting_time_nanos);
 
 /**
- * Derive an old set of ChannelKeys for per-channel secrets based on a key derivation
- * parameters.
+ * Derive an old Sign containing per-channel secrets based on a key derivation parameters.
+ *
  * Key derivation parameters are accessible through a per-channel secrets
- * ChannelKeys::key_derivation_params and is provided inside DynamicOuputP2WSH in case of
+ * Sign::channel_keys_id and is provided inside DynamicOuputP2WSH in case of
  * onchain output detection for which a corresponding delayed_payment_key must be derived.
  */
-MUST_USE_RES LDKInMemoryChannelKeys KeysManager_derive_channel_keys(const LDKKeysManager *this_arg, uint64_t channel_value_satoshis, uint64_t params_1, uint64_t params_2);
+MUST_USE_RES struct LDKInMemorySigner KeysManager_derive_channel_keys(const struct LDKKeysManager *NONNULL_PTR this_arg, uint64_t channel_value_satoshis, const uint8_t (*params)[32]);
 
-LDKKeysInterface KeysManager_as_KeysInterface(const LDKKeysManager *this_arg);
+/**
+ * Creates a Transaction which spends the given descriptors to the given outputs, plus an
+ * output to the given change destination (if sufficient change value remains). The
+ * transaction will have a feerate, at least, of the given value.
+ *
+ * Returns `Err(())` if the output value is greater than the input value minus required fee or
+ * if a descriptor was duplicated.
+ *
+ * We do not enforce that outputs meet the dust limit or that any output scripts are standard.
+ *
+ * May panic if the `SpendableOutputDescriptor`s were not generated by Channels which used
+ * this KeysManager or one of the `InMemorySigner` created by this KeysManager.
+ */
+MUST_USE_RES struct LDKCResult_TransactionNoneZ KeysManager_spend_spendable_outputs(const struct LDKKeysManager *NONNULL_PTR this_arg, struct LDKCVec_SpendableOutputDescriptorZ descriptors, struct LDKCVec_TxOutZ outputs, struct LDKCVec_u8Z change_destination_script, uint32_t feerate_sat_per_1000_weight);
 
-void ChannelManager_free(LDKChannelManager this_ptr);
+struct LDKKeysInterface KeysManager_as_KeysInterface(const struct LDKKeysManager *NONNULL_PTR this_arg);
 
-void ChannelDetails_free(LDKChannelDetails this_ptr);
+void ChannelManager_free(struct LDKChannelManager this_ptr);
 
-LDKChannelDetails ChannelDetails_clone(const LDKChannelDetails *orig);
+void ChannelDetails_free(struct LDKChannelDetails this_ptr);
 
 /**
  * The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
@@ -4162,7 +5726,7 @@ LDKChannelDetails ChannelDetails_clone(const LDKChannelDetails *orig);
  * Note that this means this value is *not* persistent - it can change once during the
  * lifetime of the channel.
  */
-const uint8_t (*ChannelDetails_get_channel_id(const LDKChannelDetails *this_ptr))[32];
+const uint8_t (*ChannelDetails_get_channel_id(const struct LDKChannelDetails *NONNULL_PTR this_ptr))[32];
 
 /**
  * The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
@@ -4170,51 +5734,51 @@ const uint8_t (*ChannelDetails_get_channel_id(const LDKChannelDetails *this_ptr)
  * Note that this means this value is *not* persistent - it can change once during the
  * lifetime of the channel.
  */
-void ChannelDetails_set_channel_id(LDKChannelDetails *this_ptr, LDKThirtyTwoBytes val);
+void ChannelDetails_set_channel_id(struct LDKChannelDetails *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
 
 /**
  * The node_id of our counterparty
  */
-LDKPublicKey ChannelDetails_get_remote_network_id(const LDKChannelDetails *this_ptr);
+struct LDKPublicKey ChannelDetails_get_remote_network_id(const struct LDKChannelDetails *NONNULL_PTR this_ptr);
 
 /**
  * The node_id of our counterparty
  */
-void ChannelDetails_set_remote_network_id(LDKChannelDetails *this_ptr, LDKPublicKey val);
+void ChannelDetails_set_remote_network_id(struct LDKChannelDetails *NONNULL_PTR this_ptr, struct LDKPublicKey val);
 
 /**
  * The Features the channel counterparty provided upon last connection.
  * Useful for routing as it is the most up-to-date copy of the counterparty's features and
  * many routing-relevant features are present in the init context.
  */
-LDKInitFeatures ChannelDetails_get_counterparty_features(const LDKChannelDetails *this_ptr);
+struct LDKInitFeatures ChannelDetails_get_counterparty_features(const struct LDKChannelDetails *NONNULL_PTR this_ptr);
 
 /**
  * The Features the channel counterparty provided upon last connection.
  * Useful for routing as it is the most up-to-date copy of the counterparty's features and
  * many routing-relevant features are present in the init context.
  */
-void ChannelDetails_set_counterparty_features(LDKChannelDetails *this_ptr, LDKInitFeatures val);
+void ChannelDetails_set_counterparty_features(struct LDKChannelDetails *NONNULL_PTR this_ptr, struct LDKInitFeatures val);
 
 /**
  * The value, in satoshis, of this channel as appears in the funding output
  */
-uint64_t ChannelDetails_get_channel_value_satoshis(const LDKChannelDetails *this_ptr);
+uint64_t ChannelDetails_get_channel_value_satoshis(const struct LDKChannelDetails *NONNULL_PTR this_ptr);
 
 /**
  * The value, in satoshis, of this channel as appears in the funding output
  */
-void ChannelDetails_set_channel_value_satoshis(LDKChannelDetails *this_ptr, uint64_t val);
+void ChannelDetails_set_channel_value_satoshis(struct LDKChannelDetails *NONNULL_PTR this_ptr, uint64_t val);
 
 /**
  * The user_id passed in to create_channel, or 0 if the channel was inbound.
  */
-uint64_t ChannelDetails_get_user_id(const LDKChannelDetails *this_ptr);
+uint64_t ChannelDetails_get_user_id(const struct LDKChannelDetails *NONNULL_PTR this_ptr);
 
 /**
  * The user_id passed in to create_channel, or 0 if the channel was inbound.
  */
-void ChannelDetails_set_user_id(LDKChannelDetails *this_ptr, uint64_t val);
+void ChannelDetails_set_user_id(struct LDKChannelDetails *NONNULL_PTR this_ptr, uint64_t val);
 
 /**
  * The available outbound capacity for sending HTLCs to the remote peer. This does not include
@@ -4222,7 +5786,7 @@ void ChannelDetails_set_user_id(LDKChannelDetails *this_ptr, uint64_t val);
  * available for inclusion in new outbound HTLCs). This further does not include any pending
  * outgoing HTLCs which are awaiting some other resolution to be sent.
  */
-uint64_t ChannelDetails_get_outbound_capacity_msat(const LDKChannelDetails *this_ptr);
+uint64_t ChannelDetails_get_outbound_capacity_msat(const struct LDKChannelDetails *NONNULL_PTR this_ptr);
 
 /**
  * The available outbound capacity for sending HTLCs to the remote peer. This does not include
@@ -4230,7 +5794,7 @@ uint64_t ChannelDetails_get_outbound_capacity_msat(const LDKChannelDetails *this
  * available for inclusion in new outbound HTLCs). This further does not include any pending
  * outgoing HTLCs which are awaiting some other resolution to be sent.
  */
-void ChannelDetails_set_outbound_capacity_msat(LDKChannelDetails *this_ptr, uint64_t val);
+void ChannelDetails_set_outbound_capacity_msat(struct LDKChannelDetails *NONNULL_PTR this_ptr, uint64_t val);
 
 /**
  * The available inbound capacity for the remote peer to send HTLCs to us. This does not
@@ -4239,7 +5803,7 @@ void ChannelDetails_set_outbound_capacity_msat(LDKChannelDetails *this_ptr, uint
  * Note that there are some corner cases not fully handled here, so the actual available
  * inbound capacity may be slightly higher than this.
  */
-uint64_t ChannelDetails_get_inbound_capacity_msat(const LDKChannelDetails *this_ptr);
+uint64_t ChannelDetails_get_inbound_capacity_msat(const struct LDKChannelDetails *NONNULL_PTR this_ptr);
 
 /**
  * The available inbound capacity for the remote peer to send HTLCs to us. This does not
@@ -4248,21 +5812,25 @@ uint64_t ChannelDetails_get_inbound_capacity_msat(const LDKChannelDetails *this_
  * Note that there are some corner cases not fully handled here, so the actual available
  * inbound capacity may be slightly higher than this.
  */
-void ChannelDetails_set_inbound_capacity_msat(LDKChannelDetails *this_ptr, uint64_t val);
+void ChannelDetails_set_inbound_capacity_msat(struct LDKChannelDetails *NONNULL_PTR this_ptr, uint64_t val);
 
 /**
  * True if the channel is (a) confirmed and funding_locked messages have been exchanged, (b)
  * the peer is connected, and (c) no monitor update failure is pending resolution.
  */
-bool ChannelDetails_get_is_live(const LDKChannelDetails *this_ptr);
+bool ChannelDetails_get_is_live(const struct LDKChannelDetails *NONNULL_PTR this_ptr);
 
 /**
  * True if the channel is (a) confirmed and funding_locked messages have been exchanged, (b)
  * the peer is connected, and (c) no monitor update failure is pending resolution.
  */
-void ChannelDetails_set_is_live(LDKChannelDetails *this_ptr, bool val);
+void ChannelDetails_set_is_live(struct LDKChannelDetails *NONNULL_PTR this_ptr, bool val);
+
+struct LDKChannelDetails ChannelDetails_clone(const struct LDKChannelDetails *NONNULL_PTR orig);
+
+void PaymentSendFailure_free(struct LDKPaymentSendFailure this_ptr);
 
-void PaymentSendFailure_free(LDKPaymentSendFailure this_ptr);
+struct LDKPaymentSendFailure PaymentSendFailure_clone(const struct LDKPaymentSendFailure *NONNULL_PTR orig);
 
 /**
  * Constructs a new ChannelManager to hold several channels and route between them.
@@ -4280,7 +5848,7 @@ void PaymentSendFailure_free(LDKPaymentSendFailure this_ptr);
  * Users need to notify the new ChannelManager when a new block is connected or
  * disconnected using its `block_connected` and `block_disconnected` methods.
  */
-MUST_USE_RES LDKChannelManager ChannelManager_new(LDKNetwork network, LDKFeeEstimator fee_est, LDKWatch chain_monitor, LDKBroadcasterInterface tx_broadcaster, LDKLogger logger, LDKKeysInterface keys_manager, LDKUserConfig config, uintptr_t current_blockchain_height);
+MUST_USE_RES struct LDKChannelManager ChannelManager_new(enum LDKNetwork network, struct LDKFeeEstimator fee_est, struct LDKWatch chain_monitor, struct LDKBroadcasterInterface tx_broadcaster, struct LDKLogger logger, struct LDKKeysInterface keys_manager, struct LDKUserConfig config, uintptr_t current_blockchain_height);
 
 /**
  * Creates a new outbound channel to the given remote node and with the given value.
@@ -4296,13 +5864,13 @@ MUST_USE_RES LDKChannelManager ChannelManager_new(LDKNetwork network, LDKFeeEsti
  * Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat is
  * greater than channel_value_satoshis * 1k or channel_value_satoshis is < 1000.
  */
-MUST_USE_RES LDKCResult_NoneAPIErrorZ ChannelManager_create_channel(const LDKChannelManager *this_arg, LDKPublicKey their_network_key, uint64_t channel_value_satoshis, uint64_t push_msat, uint64_t user_id, LDKUserConfig override_config);
+MUST_USE_RES struct LDKCResult_NoneAPIErrorZ ChannelManager_create_channel(const struct LDKChannelManager *NONNULL_PTR this_arg, struct LDKPublicKey their_network_key, uint64_t channel_value_satoshis, uint64_t push_msat, uint64_t user_id, struct LDKUserConfig override_config);
 
 /**
  * Gets the list of open channels, in random order. See ChannelDetail field documentation for
  * more information.
  */
-MUST_USE_RES LDKCVec_ChannelDetailsZ ChannelManager_list_channels(const LDKChannelManager *this_arg);
+MUST_USE_RES struct LDKCVec_ChannelDetailsZ ChannelManager_list_channels(const struct LDKChannelManager *NONNULL_PTR this_arg);
 
 /**
  * Gets the list of usable channels, in random order. Useful as an argument to
@@ -4311,7 +5879,7 @@ MUST_USE_RES LDKCVec_ChannelDetailsZ ChannelManager_list_channels(const LDKChann
  * These are guaranteed to have their is_live value set to true, see the documentation for
  * ChannelDetails::is_live for more info on exactly what the criteria are.
  */
-MUST_USE_RES LDKCVec_ChannelDetailsZ ChannelManager_list_usable_channels(const LDKChannelManager *this_arg);
+MUST_USE_RES struct LDKCVec_ChannelDetailsZ ChannelManager_list_usable_channels(const struct LDKChannelManager *NONNULL_PTR this_arg);
 
 /**
  * Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
@@ -4320,19 +5888,19 @@ MUST_USE_RES LDKCVec_ChannelDetailsZ ChannelManager_list_usable_channels(const L
  *
  * May generate a SendShutdown message event on success, which should be relayed.
  */
-MUST_USE_RES LDKCResult_NoneAPIErrorZ ChannelManager_close_channel(const LDKChannelManager *this_arg, const uint8_t (*channel_id)[32]);
+MUST_USE_RES struct LDKCResult_NoneAPIErrorZ ChannelManager_close_channel(const struct LDKChannelManager *NONNULL_PTR this_arg, const uint8_t (*channel_id)[32]);
 
 /**
  * Force closes a channel, immediately broadcasting the latest local commitment transaction to
- * the chain and rejecting new HTLCs on the given channel.
+ * the chain and rejecting new HTLCs on the given channel. Fails if channel_id is unknown to the manager.
  */
-void ChannelManager_force_close_channel(const LDKChannelManager *this_arg, const uint8_t (*channel_id)[32]);
+MUST_USE_RES struct LDKCResult_NoneAPIErrorZ ChannelManager_force_close_channel(const struct LDKChannelManager *NONNULL_PTR this_arg, const uint8_t (*channel_id)[32]);
 
 /**
  * Force close all channels, immediately broadcasting the latest local commitment transaction
  * for each to the chain and rejecting new HTLCs on each.
  */
-void ChannelManager_force_close_all_channels(const LDKChannelManager *this_arg);
+void ChannelManager_force_close_all_channels(const struct LDKChannelManager *NONNULL_PTR this_arg);
 
 /**
  * Sends a payment along a given route.
@@ -4375,7 +5943,7 @@ void ChannelManager_force_close_all_channels(const LDKChannelManager *this_arg);
  * bit set (either as required or as available). If multiple paths are present in the Route,
  * we assume the invoice had the basic_mpp feature set.
  */
-MUST_USE_RES LDKCResult_NonePaymentSendFailureZ ChannelManager_send_payment(const LDKChannelManager *this_arg, const LDKRoute *route, LDKThirtyTwoBytes payment_hash, LDKThirtyTwoBytes payment_secret);
+MUST_USE_RES struct LDKCResult_NonePaymentSendFailureZ ChannelManager_send_payment(const struct LDKChannelManager *NONNULL_PTR this_arg, const struct LDKRoute *NONNULL_PTR route, struct LDKThirtyTwoBytes payment_hash, struct LDKThirtyTwoBytes payment_secret);
 
 /**
  * Call this upon creation of a funding transaction for the given channel.
@@ -4388,7 +5956,7 @@ MUST_USE_RES LDKCResult_NonePaymentSendFailureZ ChannelManager_send_payment(cons
  * May panic if the funding_txo is duplicative with some other channel (note that this should
  * be trivially prevented by using unique funding transaction keys per-channel).
  */
-void ChannelManager_funding_transaction_generated(const LDKChannelManager *this_arg, const uint8_t (*temporary_channel_id)[32], LDKOutPoint funding_txo);
+void ChannelManager_funding_transaction_generated(const struct LDKChannelManager *NONNULL_PTR this_arg, const uint8_t (*temporary_channel_id)[32], struct LDKOutPoint funding_txo);
 
 /**
  * Generates a signed node_announcement from the given arguments and creates a
@@ -4405,7 +5973,7 @@ void ChannelManager_funding_transaction_generated(const LDKChannelManager *this_
  *
  * Panics if addresses is absurdly large (more than 500).
  */
-void ChannelManager_broadcast_node_announcement(const LDKChannelManager *this_arg, LDKThreeBytes rgb, LDKThirtyTwoBytes alias, LDKCVec_NetAddressZ addresses);
+void ChannelManager_broadcast_node_announcement(const struct LDKChannelManager *NONNULL_PTR this_arg, struct LDKThreeBytes rgb, struct LDKThirtyTwoBytes alias, struct LDKCVec_NetAddressZ addresses);
 
 /**
  * Processes HTLCs which are pending waiting on random forward delay.
@@ -4413,7 +5981,7 @@ void ChannelManager_broadcast_node_announcement(const LDKChannelManager *this_ar
  * Should only really ever be called in response to a PendingHTLCsForwardable event.
  * Will likely generate further events.
  */
-void ChannelManager_process_pending_htlc_forwards(const LDKChannelManager *this_arg);
+void ChannelManager_process_pending_htlc_forwards(const struct LDKChannelManager *NONNULL_PTR this_arg);
 
 /**
  * If a peer is disconnected we mark any channels with that peer as 'disabled'.
@@ -4422,7 +5990,7 @@ void ChannelManager_process_pending_htlc_forwards(const LDKChannelManager *this_
  *
  * This method handles all the details, and must be called roughly once per minute.
  */
-void ChannelManager_timer_chan_freshness_every_min(const LDKChannelManager *this_arg);
+void ChannelManager_timer_chan_freshness_every_min(const struct LDKChannelManager *NONNULL_PTR this_arg);
 
 /**
  * Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
@@ -4431,7 +5999,7 @@ void ChannelManager_timer_chan_freshness_every_min(const LDKChannelManager *this
  * Returns false if no payment was found to fail backwards, true if the process of failing the
  * HTLC backwards has been started.
  */
-MUST_USE_RES bool ChannelManager_fail_htlc_backwards(const LDKChannelManager *this_arg, const uint8_t (*payment_hash)[32], LDKThirtyTwoBytes payment_secret);
+MUST_USE_RES bool ChannelManager_fail_htlc_backwards(const struct LDKChannelManager *NONNULL_PTR this_arg, const uint8_t (*payment_hash)[32], struct LDKThirtyTwoBytes payment_secret);
 
 /**
  * Provides a payment preimage in response to a PaymentReceived event, returning true and
@@ -4450,12 +6018,12 @@ MUST_USE_RES bool ChannelManager_fail_htlc_backwards(const LDKChannelManager *th
  *
  * May panic if called except in response to a PaymentReceived event.
  */
-MUST_USE_RES bool ChannelManager_claim_funds(const LDKChannelManager *this_arg, LDKThirtyTwoBytes payment_preimage, LDKThirtyTwoBytes payment_secret, uint64_t expected_amount);
+MUST_USE_RES bool ChannelManager_claim_funds(const struct LDKChannelManager *NONNULL_PTR this_arg, struct LDKThirtyTwoBytes payment_preimage, struct LDKThirtyTwoBytes payment_secret, uint64_t expected_amount);
 
 /**
  * Gets the node_id held by this ChannelManager
  */
-MUST_USE_RES LDKPublicKey ChannelManager_get_our_node_id(const LDKChannelManager *this_arg);
+MUST_USE_RES struct LDKPublicKey ChannelManager_get_our_node_id(const struct LDKChannelManager *NONNULL_PTR this_arg);
 
 /**
  * Restores a single, given channel to normal operation after a
@@ -4479,16 +6047,18 @@ MUST_USE_RES LDKPublicKey ChannelManager_get_our_node_id(const LDKChannelManager
  *  4) once all remote copies are updated, you call this function with the update_id that
  *     completed, and once it is the latest the Channel will be re-enabled.
  */
-void ChannelManager_channel_monitor_updated(const LDKChannelManager *this_arg, const LDKOutPoint *funding_txo, uint64_t highest_applied_update_id);
+void ChannelManager_channel_monitor_updated(const struct LDKChannelManager *NONNULL_PTR this_arg, const struct LDKOutPoint *NONNULL_PTR funding_txo, uint64_t highest_applied_update_id);
 
-LDKMessageSendEventsProvider ChannelManager_as_MessageSendEventsProvider(const LDKChannelManager *this_arg);
+struct LDKMessageSendEventsProvider ChannelManager_as_MessageSendEventsProvider(const struct LDKChannelManager *NONNULL_PTR this_arg);
 
-LDKEventsProvider ChannelManager_as_EventsProvider(const LDKChannelManager *this_arg);
+struct LDKEventsProvider ChannelManager_as_EventsProvider(const struct LDKChannelManager *NONNULL_PTR this_arg);
+
+struct LDKListen ChannelManager_as_Listen(const struct LDKChannelManager *NONNULL_PTR this_arg);
 
 /**
  * Updates channel state based on transactions seen in a connected block.
  */
-void ChannelManager_block_connected(const LDKChannelManager *this_arg, const uint8_t (*header)[80], LDKCVec_C2Tuple_usizeTransactionZZ txdata, uint32_t height);
+void ChannelManager_block_connected(const struct LDKChannelManager *NONNULL_PTR this_arg, const uint8_t (*header)[80], struct LDKCVec_C2Tuple_usizeTransactionZZ txdata, uint32_t height);
 
 /**
  * Updates channel state based on a disconnected block.
@@ -4496,37 +6066,47 @@ void ChannelManager_block_connected(const LDKChannelManager *this_arg, const uin
  * If necessary, the channel may be force-closed without letting the counterparty participate
  * in the shutdown.
  */
-void ChannelManager_block_disconnected(const LDKChannelManager *this_arg, const uint8_t (*header)[80]);
+void ChannelManager_block_disconnected(const struct LDKChannelManager *NONNULL_PTR this_arg, const uint8_t (*header)[80]);
+
+/**
+ * Blocks until ChannelManager needs to be persisted. Only one listener on `wait` is
+ * guaranteed to be woken up.
+ */
+void ChannelManager_wait(const struct LDKChannelManager *NONNULL_PTR this_arg);
 
-LDKChannelMessageHandler ChannelManager_as_ChannelMessageHandler(const LDKChannelManager *this_arg);
+struct LDKChannelMessageHandler ChannelManager_as_ChannelMessageHandler(const struct LDKChannelManager *NONNULL_PTR this_arg);
 
-void ChannelManagerReadArgs_free(LDKChannelManagerReadArgs this_ptr);
+struct LDKCVec_u8Z ChannelManager_write(const struct LDKChannelManager *NONNULL_PTR obj);
+
+void ChannelManagerReadArgs_free(struct LDKChannelManagerReadArgs this_ptr);
 
 /**
  * The keys provider which will give us relevant keys. Some keys will be loaded during
- * deserialization.
+ * deserialization and KeysInterface::read_chan_signer will be used to read per-Channel
+ * signing data.
  */
-const LDKKeysInterface *ChannelManagerReadArgs_get_keys_manager(const LDKChannelManagerReadArgs *this_ptr);
+const struct LDKKeysInterface *ChannelManagerReadArgs_get_keys_manager(const struct LDKChannelManagerReadArgs *NONNULL_PTR this_ptr);
 
 /**
  * The keys provider which will give us relevant keys. Some keys will be loaded during
- * deserialization.
+ * deserialization and KeysInterface::read_chan_signer will be used to read per-Channel
+ * signing data.
  */
-void ChannelManagerReadArgs_set_keys_manager(LDKChannelManagerReadArgs *this_ptr, LDKKeysInterface val);
+void ChannelManagerReadArgs_set_keys_manager(struct LDKChannelManagerReadArgs *NONNULL_PTR this_ptr, struct LDKKeysInterface val);
 
 /**
  * The fee_estimator for use in the ChannelManager in the future.
  *
  * No calls to the FeeEstimator will be made during deserialization.
  */
-const LDKFeeEstimator *ChannelManagerReadArgs_get_fee_estimator(const LDKChannelManagerReadArgs *this_ptr);
+const struct LDKFeeEstimator *ChannelManagerReadArgs_get_fee_estimator(const struct LDKChannelManagerReadArgs *NONNULL_PTR this_ptr);
 
 /**
  * The fee_estimator for use in the ChannelManager in the future.
  *
  * No calls to the FeeEstimator will be made during deserialization.
  */
-void ChannelManagerReadArgs_set_fee_estimator(LDKChannelManagerReadArgs *this_ptr, LDKFeeEstimator val);
+void ChannelManagerReadArgs_set_fee_estimator(struct LDKChannelManagerReadArgs *NONNULL_PTR this_ptr, struct LDKFeeEstimator val);
 
 /**
  * The chain::Watch for use in the ChannelManager in the future.
@@ -4535,7 +6115,7 @@ void ChannelManagerReadArgs_set_fee_estimator(LDKChannelManagerReadArgs *this_pt
  * you have deserialized ChannelMonitors separately and will add them to your
  * chain::Watch after deserializing this ChannelManager.
  */
-const LDKWatch *ChannelManagerReadArgs_get_chain_monitor(const LDKChannelManagerReadArgs *this_ptr);
+const struct LDKWatch *ChannelManagerReadArgs_get_chain_monitor(const struct LDKChannelManagerReadArgs *NONNULL_PTR this_ptr);
 
 /**
  * The chain::Watch for use in the ChannelManager in the future.
@@ -4544,72 +6124,86 @@ const LDKWatch *ChannelManagerReadArgs_get_chain_monitor(const LDKChannelManager
  * you have deserialized ChannelMonitors separately and will add them to your
  * chain::Watch after deserializing this ChannelManager.
  */
-void ChannelManagerReadArgs_set_chain_monitor(LDKChannelManagerReadArgs *this_ptr, LDKWatch val);
+void ChannelManagerReadArgs_set_chain_monitor(struct LDKChannelManagerReadArgs *NONNULL_PTR this_ptr, struct LDKWatch val);
 
 /**
  * The BroadcasterInterface which will be used in the ChannelManager in the future and may be
  * used to broadcast the latest local commitment transactions of channels which must be
  * force-closed during deserialization.
  */
-const LDKBroadcasterInterface *ChannelManagerReadArgs_get_tx_broadcaster(const LDKChannelManagerReadArgs *this_ptr);
+const struct LDKBroadcasterInterface *ChannelManagerReadArgs_get_tx_broadcaster(const struct LDKChannelManagerReadArgs *NONNULL_PTR this_ptr);
 
 /**
  * The BroadcasterInterface which will be used in the ChannelManager in the future and may be
  * used to broadcast the latest local commitment transactions of channels which must be
  * force-closed during deserialization.
  */
-void ChannelManagerReadArgs_set_tx_broadcaster(LDKChannelManagerReadArgs *this_ptr, LDKBroadcasterInterface val);
+void ChannelManagerReadArgs_set_tx_broadcaster(struct LDKChannelManagerReadArgs *NONNULL_PTR this_ptr, struct LDKBroadcasterInterface val);
 
 /**
  * The Logger for use in the ChannelManager and which may be used to log information during
  * deserialization.
  */
-const LDKLogger *ChannelManagerReadArgs_get_logger(const LDKChannelManagerReadArgs *this_ptr);
+const struct LDKLogger *ChannelManagerReadArgs_get_logger(const struct LDKChannelManagerReadArgs *NONNULL_PTR this_ptr);
 
 /**
  * The Logger for use in the ChannelManager and which may be used to log information during
  * deserialization.
  */
-void ChannelManagerReadArgs_set_logger(LDKChannelManagerReadArgs *this_ptr, LDKLogger val);
+void ChannelManagerReadArgs_set_logger(struct LDKChannelManagerReadArgs *NONNULL_PTR this_ptr, struct LDKLogger val);
 
 /**
  * Default settings used for new channels. Any existing channels will continue to use the
  * runtime settings which were stored when the ChannelManager was serialized.
  */
-LDKUserConfig ChannelManagerReadArgs_get_default_config(const LDKChannelManagerReadArgs *this_ptr);
+struct LDKUserConfig ChannelManagerReadArgs_get_default_config(const struct LDKChannelManagerReadArgs *NONNULL_PTR this_ptr);
 
 /**
  * Default settings used for new channels. Any existing channels will continue to use the
  * runtime settings which were stored when the ChannelManager was serialized.
  */
-void ChannelManagerReadArgs_set_default_config(LDKChannelManagerReadArgs *this_ptr, LDKUserConfig val);
+void ChannelManagerReadArgs_set_default_config(struct LDKChannelManagerReadArgs *NONNULL_PTR this_ptr, struct LDKUserConfig val);
 
 /**
  * Simple utility function to create a ChannelManagerReadArgs which creates the monitor
  * HashMap for you. This is primarily useful for C bindings where it is not practical to
  * populate a HashMap directly from C.
  */
-MUST_USE_RES LDKChannelManagerReadArgs ChannelManagerReadArgs_new(LDKKeysInterface keys_manager, LDKFeeEstimator fee_estimator, LDKWatch chain_monitor, LDKBroadcasterInterface tx_broadcaster, LDKLogger logger, LDKUserConfig default_config, LDKCVec_ChannelMonitorZ channel_monitors);
+MUST_USE_RES struct LDKChannelManagerReadArgs ChannelManagerReadArgs_new(struct LDKKeysInterface keys_manager, struct LDKFeeEstimator fee_estimator, struct LDKWatch chain_monitor, struct LDKBroadcasterInterface tx_broadcaster, struct LDKLogger logger, struct LDKUserConfig default_config, struct LDKCVec_ChannelMonitorZ channel_monitors);
+
+struct LDKCResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ C2Tuple_BlockHashChannelManagerZ_read(struct LDKu8slice ser, struct LDKChannelManagerReadArgs arg);
 
-void DecodeError_free(LDKDecodeError this_ptr);
+void DecodeError_free(struct LDKDecodeError this_ptr);
+
+struct LDKDecodeError DecodeError_clone(const struct LDKDecodeError *NONNULL_PTR orig);
+
+void Init_free(struct LDKInit this_ptr);
+
+/**
+ * The relevant features which the sender supports
+ */
+struct LDKInitFeatures Init_get_features(const struct LDKInit *NONNULL_PTR this_ptr);
 
-void Init_free(LDKInit this_ptr);
+/**
+ * The relevant features which the sender supports
+ */
+void Init_set_features(struct LDKInit *NONNULL_PTR this_ptr, struct LDKInitFeatures val);
 
-LDKInit Init_clone(const LDKInit *orig);
+MUST_USE_RES struct LDKInit Init_new(struct LDKInitFeatures features_arg);
 
-void ErrorMessage_free(LDKErrorMessage this_ptr);
+struct LDKInit Init_clone(const struct LDKInit *NONNULL_PTR orig);
 
-LDKErrorMessage ErrorMessage_clone(const LDKErrorMessage *orig);
+void ErrorMessage_free(struct LDKErrorMessage this_ptr);
 
 /**
  * The channel ID involved in the error
  */
-const uint8_t (*ErrorMessage_get_channel_id(const LDKErrorMessage *this_ptr))[32];
+const uint8_t (*ErrorMessage_get_channel_id(const struct LDKErrorMessage *NONNULL_PTR this_ptr))[32];
 
 /**
  * The channel ID involved in the error
  */
-void ErrorMessage_set_channel_id(LDKErrorMessage *this_ptr, LDKThirtyTwoBytes val);
+void ErrorMessage_set_channel_id(struct LDKErrorMessage *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
 
 /**
  * A possibly human-readable error description.
@@ -4617,7 +6211,7 @@ void ErrorMessage_set_channel_id(LDKErrorMessage *this_ptr, LDKThirtyTwoBytes va
  * or printed to stdout).  Otherwise, a well crafted error message may trigger a security
  * vulnerability in the terminal emulator or the logging subsystem.
  */
-LDKStr ErrorMessage_get_data(const LDKErrorMessage *this_ptr);
+struct LDKStr ErrorMessage_get_data(const struct LDKErrorMessage *NONNULL_PTR this_ptr);
 
 /**
  * A possibly human-readable error description.
@@ -4625,1673 +6219,1681 @@ LDKStr ErrorMessage_get_data(const LDKErrorMessage *this_ptr);
  * or printed to stdout).  Otherwise, a well crafted error message may trigger a security
  * vulnerability in the terminal emulator or the logging subsystem.
  */
-void ErrorMessage_set_data(LDKErrorMessage *this_ptr, LDKCVec_u8Z val);
+void ErrorMessage_set_data(struct LDKErrorMessage *NONNULL_PTR this_ptr, struct LDKCVec_u8Z val);
 
-MUST_USE_RES LDKErrorMessage ErrorMessage_new(LDKThirtyTwoBytes channel_id_arg, LDKCVec_u8Z data_arg);
+MUST_USE_RES struct LDKErrorMessage ErrorMessage_new(struct LDKThirtyTwoBytes channel_id_arg, struct LDKCVec_u8Z data_arg);
 
-void Ping_free(LDKPing this_ptr);
+struct LDKErrorMessage ErrorMessage_clone(const struct LDKErrorMessage *NONNULL_PTR orig);
 
-LDKPing Ping_clone(const LDKPing *orig);
+void Ping_free(struct LDKPing this_ptr);
 
 /**
  * The desired response length
  */
-uint16_t Ping_get_ponglen(const LDKPing *this_ptr);
+uint16_t Ping_get_ponglen(const struct LDKPing *NONNULL_PTR this_ptr);
 
 /**
  * The desired response length
  */
-void Ping_set_ponglen(LDKPing *this_ptr, uint16_t val);
+void Ping_set_ponglen(struct LDKPing *NONNULL_PTR this_ptr, uint16_t val);
 
 /**
  * The ping packet size.
  * This field is not sent on the wire. byteslen zeros are sent.
  */
-uint16_t Ping_get_byteslen(const LDKPing *this_ptr);
+uint16_t Ping_get_byteslen(const struct LDKPing *NONNULL_PTR this_ptr);
 
 /**
  * The ping packet size.
  * This field is not sent on the wire. byteslen zeros are sent.
  */
-void Ping_set_byteslen(LDKPing *this_ptr, uint16_t val);
+void Ping_set_byteslen(struct LDKPing *NONNULL_PTR this_ptr, uint16_t val);
 
-MUST_USE_RES LDKPing Ping_new(uint16_t ponglen_arg, uint16_t byteslen_arg);
+MUST_USE_RES struct LDKPing Ping_new(uint16_t ponglen_arg, uint16_t byteslen_arg);
 
-void Pong_free(LDKPong this_ptr);
+struct LDKPing Ping_clone(const struct LDKPing *NONNULL_PTR orig);
 
-LDKPong Pong_clone(const LDKPong *orig);
+void Pong_free(struct LDKPong this_ptr);
 
 /**
  * The pong packet size.
  * This field is not sent on the wire. byteslen zeros are sent.
  */
-uint16_t Pong_get_byteslen(const LDKPong *this_ptr);
+uint16_t Pong_get_byteslen(const struct LDKPong *NONNULL_PTR this_ptr);
 
 /**
  * The pong packet size.
  * This field is not sent on the wire. byteslen zeros are sent.
  */
-void Pong_set_byteslen(LDKPong *this_ptr, uint16_t val);
+void Pong_set_byteslen(struct LDKPong *NONNULL_PTR this_ptr, uint16_t val);
 
-MUST_USE_RES LDKPong Pong_new(uint16_t byteslen_arg);
+MUST_USE_RES struct LDKPong Pong_new(uint16_t byteslen_arg);
 
-void OpenChannel_free(LDKOpenChannel this_ptr);
+struct LDKPong Pong_clone(const struct LDKPong *NONNULL_PTR orig);
 
-LDKOpenChannel OpenChannel_clone(const LDKOpenChannel *orig);
+void OpenChannel_free(struct LDKOpenChannel this_ptr);
 
 /**
  * The genesis hash of the blockchain where the channel is to be opened
  */
-const uint8_t (*OpenChannel_get_chain_hash(const LDKOpenChannel *this_ptr))[32];
+const uint8_t (*OpenChannel_get_chain_hash(const struct LDKOpenChannel *NONNULL_PTR this_ptr))[32];
 
 /**
  * The genesis hash of the blockchain where the channel is to be opened
  */
-void OpenChannel_set_chain_hash(LDKOpenChannel *this_ptr, LDKThirtyTwoBytes val);
+void OpenChannel_set_chain_hash(struct LDKOpenChannel *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
 
 /**
  * A temporary channel ID, until the funding outpoint is announced
  */
-const uint8_t (*OpenChannel_get_temporary_channel_id(const LDKOpenChannel *this_ptr))[32];
+const uint8_t (*OpenChannel_get_temporary_channel_id(const struct LDKOpenChannel *NONNULL_PTR this_ptr))[32];
 
 /**
  * A temporary channel ID, until the funding outpoint is announced
  */
-void OpenChannel_set_temporary_channel_id(LDKOpenChannel *this_ptr, LDKThirtyTwoBytes val);
+void OpenChannel_set_temporary_channel_id(struct LDKOpenChannel *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
 
 /**
  * The channel value
  */
-uint64_t OpenChannel_get_funding_satoshis(const LDKOpenChannel *this_ptr);
+uint64_t OpenChannel_get_funding_satoshis(const struct LDKOpenChannel *NONNULL_PTR this_ptr);
 
 /**
  * The channel value
  */
-void OpenChannel_set_funding_satoshis(LDKOpenChannel *this_ptr, uint64_t val);
+void OpenChannel_set_funding_satoshis(struct LDKOpenChannel *NONNULL_PTR this_ptr, uint64_t val);
 
 /**
  * The amount to push to the counterparty as part of the open, in milli-satoshi
  */
-uint64_t OpenChannel_get_push_msat(const LDKOpenChannel *this_ptr);
+uint64_t OpenChannel_get_push_msat(const struct LDKOpenChannel *NONNULL_PTR this_ptr);
 
 /**
  * The amount to push to the counterparty as part of the open, in milli-satoshi
  */
-void OpenChannel_set_push_msat(LDKOpenChannel *this_ptr, uint64_t val);
+void OpenChannel_set_push_msat(struct LDKOpenChannel *NONNULL_PTR this_ptr, uint64_t val);
 
 /**
  * The threshold below which outputs on transactions broadcast by sender will be omitted
  */
-uint64_t OpenChannel_get_dust_limit_satoshis(const LDKOpenChannel *this_ptr);
+uint64_t OpenChannel_get_dust_limit_satoshis(const struct LDKOpenChannel *NONNULL_PTR this_ptr);
 
 /**
  * The threshold below which outputs on transactions broadcast by sender will be omitted
  */
-void OpenChannel_set_dust_limit_satoshis(LDKOpenChannel *this_ptr, uint64_t val);
+void OpenChannel_set_dust_limit_satoshis(struct LDKOpenChannel *NONNULL_PTR this_ptr, uint64_t val);
 
 /**
  * The maximum inbound HTLC value in flight towards sender, in milli-satoshi
  */
-uint64_t OpenChannel_get_max_htlc_value_in_flight_msat(const LDKOpenChannel *this_ptr);
+uint64_t OpenChannel_get_max_htlc_value_in_flight_msat(const struct LDKOpenChannel *NONNULL_PTR this_ptr);
 
 /**
  * The maximum inbound HTLC value in flight towards sender, in milli-satoshi
  */
-void OpenChannel_set_max_htlc_value_in_flight_msat(LDKOpenChannel *this_ptr, uint64_t val);
+void OpenChannel_set_max_htlc_value_in_flight_msat(struct LDKOpenChannel *NONNULL_PTR this_ptr, uint64_t val);
 
 /**
  * The minimum value unencumbered by HTLCs for the counterparty to keep in the channel
  */
-uint64_t OpenChannel_get_channel_reserve_satoshis(const LDKOpenChannel *this_ptr);
+uint64_t OpenChannel_get_channel_reserve_satoshis(const struct LDKOpenChannel *NONNULL_PTR this_ptr);
 
 /**
  * The minimum value unencumbered by HTLCs for the counterparty to keep in the channel
  */
-void OpenChannel_set_channel_reserve_satoshis(LDKOpenChannel *this_ptr, uint64_t val);
+void OpenChannel_set_channel_reserve_satoshis(struct LDKOpenChannel *NONNULL_PTR this_ptr, uint64_t val);
 
 /**
  * The minimum HTLC size incoming to sender, in milli-satoshi
  */
-uint64_t OpenChannel_get_htlc_minimum_msat(const LDKOpenChannel *this_ptr);
+uint64_t OpenChannel_get_htlc_minimum_msat(const struct LDKOpenChannel *NONNULL_PTR this_ptr);
 
 /**
  * The minimum HTLC size incoming to sender, in milli-satoshi
  */
-void OpenChannel_set_htlc_minimum_msat(LDKOpenChannel *this_ptr, uint64_t val);
+void OpenChannel_set_htlc_minimum_msat(struct LDKOpenChannel *NONNULL_PTR this_ptr, uint64_t val);
 
 /**
  * The feerate per 1000-weight of sender generated transactions, until updated by update_fee
  */
-uint32_t OpenChannel_get_feerate_per_kw(const LDKOpenChannel *this_ptr);
+uint32_t OpenChannel_get_feerate_per_kw(const struct LDKOpenChannel *NONNULL_PTR this_ptr);
 
 /**
  * The feerate per 1000-weight of sender generated transactions, until updated by update_fee
  */
-void OpenChannel_set_feerate_per_kw(LDKOpenChannel *this_ptr, uint32_t val);
+void OpenChannel_set_feerate_per_kw(struct LDKOpenChannel *NONNULL_PTR this_ptr, uint32_t val);
 
 /**
  * The number of blocks which the counterparty will have to wait to claim on-chain funds if they broadcast a commitment transaction
  */
-uint16_t OpenChannel_get_to_self_delay(const LDKOpenChannel *this_ptr);
+uint16_t OpenChannel_get_to_self_delay(const struct LDKOpenChannel *NONNULL_PTR this_ptr);
 
 /**
  * The number of blocks which the counterparty will have to wait to claim on-chain funds if they broadcast a commitment transaction
  */
-void OpenChannel_set_to_self_delay(LDKOpenChannel *this_ptr, uint16_t val);
+void OpenChannel_set_to_self_delay(struct LDKOpenChannel *NONNULL_PTR this_ptr, uint16_t val);
 
 /**
  * The maximum number of inbound HTLCs towards sender
  */
-uint16_t OpenChannel_get_max_accepted_htlcs(const LDKOpenChannel *this_ptr);
+uint16_t OpenChannel_get_max_accepted_htlcs(const struct LDKOpenChannel *NONNULL_PTR this_ptr);
 
 /**
  * The maximum number of inbound HTLCs towards sender
  */
-void OpenChannel_set_max_accepted_htlcs(LDKOpenChannel *this_ptr, uint16_t val);
+void OpenChannel_set_max_accepted_htlcs(struct LDKOpenChannel *NONNULL_PTR this_ptr, uint16_t val);
 
 /**
  * The sender's key controlling the funding transaction
  */
-LDKPublicKey OpenChannel_get_funding_pubkey(const LDKOpenChannel *this_ptr);
+struct LDKPublicKey OpenChannel_get_funding_pubkey(const struct LDKOpenChannel *NONNULL_PTR this_ptr);
 
 /**
  * The sender's key controlling the funding transaction
  */
-void OpenChannel_set_funding_pubkey(LDKOpenChannel *this_ptr, LDKPublicKey val);
+void OpenChannel_set_funding_pubkey(struct LDKOpenChannel *NONNULL_PTR this_ptr, struct LDKPublicKey val);
 
 /**
  * Used to derive a revocation key for transactions broadcast by counterparty
  */
-LDKPublicKey OpenChannel_get_revocation_basepoint(const LDKOpenChannel *this_ptr);
+struct LDKPublicKey OpenChannel_get_revocation_basepoint(const struct LDKOpenChannel *NONNULL_PTR this_ptr);
 
 /**
  * Used to derive a revocation key for transactions broadcast by counterparty
  */
-void OpenChannel_set_revocation_basepoint(LDKOpenChannel *this_ptr, LDKPublicKey val);
+void OpenChannel_set_revocation_basepoint(struct LDKOpenChannel *NONNULL_PTR this_ptr, struct LDKPublicKey val);
 
 /**
  * A payment key to sender for transactions broadcast by counterparty
  */
-LDKPublicKey OpenChannel_get_payment_point(const LDKOpenChannel *this_ptr);
+struct LDKPublicKey OpenChannel_get_payment_point(const struct LDKOpenChannel *NONNULL_PTR this_ptr);
 
 /**
  * A payment key to sender for transactions broadcast by counterparty
  */
-void OpenChannel_set_payment_point(LDKOpenChannel *this_ptr, LDKPublicKey val);
+void OpenChannel_set_payment_point(struct LDKOpenChannel *NONNULL_PTR this_ptr, struct LDKPublicKey val);
 
 /**
  * Used to derive a payment key to sender for transactions broadcast by sender
  */
-LDKPublicKey OpenChannel_get_delayed_payment_basepoint(const LDKOpenChannel *this_ptr);
+struct LDKPublicKey OpenChannel_get_delayed_payment_basepoint(const struct LDKOpenChannel *NONNULL_PTR this_ptr);
 
 /**
  * Used to derive a payment key to sender for transactions broadcast by sender
  */
-void OpenChannel_set_delayed_payment_basepoint(LDKOpenChannel *this_ptr, LDKPublicKey val);
+void OpenChannel_set_delayed_payment_basepoint(struct LDKOpenChannel *NONNULL_PTR this_ptr, struct LDKPublicKey val);
 
 /**
  * Used to derive an HTLC payment key to sender
  */
-LDKPublicKey OpenChannel_get_htlc_basepoint(const LDKOpenChannel *this_ptr);
+struct LDKPublicKey OpenChannel_get_htlc_basepoint(const struct LDKOpenChannel *NONNULL_PTR this_ptr);
 
 /**
  * Used to derive an HTLC payment key to sender
  */
-void OpenChannel_set_htlc_basepoint(LDKOpenChannel *this_ptr, LDKPublicKey val);
+void OpenChannel_set_htlc_basepoint(struct LDKOpenChannel *NONNULL_PTR this_ptr, struct LDKPublicKey val);
 
 /**
  * The first to-be-broadcast-by-sender transaction's per commitment point
  */
-LDKPublicKey OpenChannel_get_first_per_commitment_point(const LDKOpenChannel *this_ptr);
+struct LDKPublicKey OpenChannel_get_first_per_commitment_point(const struct LDKOpenChannel *NONNULL_PTR this_ptr);
 
 /**
  * The first to-be-broadcast-by-sender transaction's per commitment point
  */
-void OpenChannel_set_first_per_commitment_point(LDKOpenChannel *this_ptr, LDKPublicKey val);
+void OpenChannel_set_first_per_commitment_point(struct LDKOpenChannel *NONNULL_PTR this_ptr, struct LDKPublicKey val);
 
 /**
  * Channel flags
  */
-uint8_t OpenChannel_get_channel_flags(const LDKOpenChannel *this_ptr);
+uint8_t OpenChannel_get_channel_flags(const struct LDKOpenChannel *NONNULL_PTR this_ptr);
 
 /**
  * Channel flags
  */
-void OpenChannel_set_channel_flags(LDKOpenChannel *this_ptr, uint8_t val);
+void OpenChannel_set_channel_flags(struct LDKOpenChannel *NONNULL_PTR this_ptr, uint8_t val);
 
-void AcceptChannel_free(LDKAcceptChannel this_ptr);
+struct LDKOpenChannel OpenChannel_clone(const struct LDKOpenChannel *NONNULL_PTR orig);
 
-LDKAcceptChannel AcceptChannel_clone(const LDKAcceptChannel *orig);
+void AcceptChannel_free(struct LDKAcceptChannel this_ptr);
 
 /**
  * A temporary channel ID, until the funding outpoint is announced
  */
-const uint8_t (*AcceptChannel_get_temporary_channel_id(const LDKAcceptChannel *this_ptr))[32];
+const uint8_t (*AcceptChannel_get_temporary_channel_id(const struct LDKAcceptChannel *NONNULL_PTR this_ptr))[32];
 
 /**
  * A temporary channel ID, until the funding outpoint is announced
  */
-void AcceptChannel_set_temporary_channel_id(LDKAcceptChannel *this_ptr, LDKThirtyTwoBytes val);
+void AcceptChannel_set_temporary_channel_id(struct LDKAcceptChannel *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
 
 /**
  * The threshold below which outputs on transactions broadcast by sender will be omitted
  */
-uint64_t AcceptChannel_get_dust_limit_satoshis(const LDKAcceptChannel *this_ptr);
+uint64_t AcceptChannel_get_dust_limit_satoshis(const struct LDKAcceptChannel *NONNULL_PTR this_ptr);
 
 /**
  * The threshold below which outputs on transactions broadcast by sender will be omitted
  */
-void AcceptChannel_set_dust_limit_satoshis(LDKAcceptChannel *this_ptr, uint64_t val);
+void AcceptChannel_set_dust_limit_satoshis(struct LDKAcceptChannel *NONNULL_PTR this_ptr, uint64_t val);
 
 /**
  * The maximum inbound HTLC value in flight towards sender, in milli-satoshi
  */
-uint64_t AcceptChannel_get_max_htlc_value_in_flight_msat(const LDKAcceptChannel *this_ptr);
+uint64_t AcceptChannel_get_max_htlc_value_in_flight_msat(const struct LDKAcceptChannel *NONNULL_PTR this_ptr);
 
 /**
  * The maximum inbound HTLC value in flight towards sender, in milli-satoshi
  */
-void AcceptChannel_set_max_htlc_value_in_flight_msat(LDKAcceptChannel *this_ptr, uint64_t val);
+void AcceptChannel_set_max_htlc_value_in_flight_msat(struct LDKAcceptChannel *NONNULL_PTR this_ptr, uint64_t val);
 
 /**
  * The minimum value unencumbered by HTLCs for the counterparty to keep in the channel
  */
-uint64_t AcceptChannel_get_channel_reserve_satoshis(const LDKAcceptChannel *this_ptr);
+uint64_t AcceptChannel_get_channel_reserve_satoshis(const struct LDKAcceptChannel *NONNULL_PTR this_ptr);
 
 /**
  * The minimum value unencumbered by HTLCs for the counterparty to keep in the channel
  */
-void AcceptChannel_set_channel_reserve_satoshis(LDKAcceptChannel *this_ptr, uint64_t val);
+void AcceptChannel_set_channel_reserve_satoshis(struct LDKAcceptChannel *NONNULL_PTR this_ptr, uint64_t val);
 
 /**
  * The minimum HTLC size incoming to sender, in milli-satoshi
  */
-uint64_t AcceptChannel_get_htlc_minimum_msat(const LDKAcceptChannel *this_ptr);
+uint64_t AcceptChannel_get_htlc_minimum_msat(const struct LDKAcceptChannel *NONNULL_PTR this_ptr);
 
 /**
  * The minimum HTLC size incoming to sender, in milli-satoshi
  */
-void AcceptChannel_set_htlc_minimum_msat(LDKAcceptChannel *this_ptr, uint64_t val);
+void AcceptChannel_set_htlc_minimum_msat(struct LDKAcceptChannel *NONNULL_PTR this_ptr, uint64_t val);
 
 /**
  * Minimum depth of the funding transaction before the channel is considered open
  */
-uint32_t AcceptChannel_get_minimum_depth(const LDKAcceptChannel *this_ptr);
+uint32_t AcceptChannel_get_minimum_depth(const struct LDKAcceptChannel *NONNULL_PTR this_ptr);
 
 /**
  * Minimum depth of the funding transaction before the channel is considered open
  */
-void AcceptChannel_set_minimum_depth(LDKAcceptChannel *this_ptr, uint32_t val);
+void AcceptChannel_set_minimum_depth(struct LDKAcceptChannel *NONNULL_PTR this_ptr, uint32_t val);
 
 /**
  * The number of blocks which the counterparty will have to wait to claim on-chain funds if they broadcast a commitment transaction
  */
-uint16_t AcceptChannel_get_to_self_delay(const LDKAcceptChannel *this_ptr);
+uint16_t AcceptChannel_get_to_self_delay(const struct LDKAcceptChannel *NONNULL_PTR this_ptr);
 
 /**
  * The number of blocks which the counterparty will have to wait to claim on-chain funds if they broadcast a commitment transaction
  */
-void AcceptChannel_set_to_self_delay(LDKAcceptChannel *this_ptr, uint16_t val);
+void AcceptChannel_set_to_self_delay(struct LDKAcceptChannel *NONNULL_PTR this_ptr, uint16_t val);
 
 /**
  * The maximum number of inbound HTLCs towards sender
  */
-uint16_t AcceptChannel_get_max_accepted_htlcs(const LDKAcceptChannel *this_ptr);
+uint16_t AcceptChannel_get_max_accepted_htlcs(const struct LDKAcceptChannel *NONNULL_PTR this_ptr);
 
 /**
  * The maximum number of inbound HTLCs towards sender
  */
-void AcceptChannel_set_max_accepted_htlcs(LDKAcceptChannel *this_ptr, uint16_t val);
+void AcceptChannel_set_max_accepted_htlcs(struct LDKAcceptChannel *NONNULL_PTR this_ptr, uint16_t val);
 
 /**
  * The sender's key controlling the funding transaction
  */
-LDKPublicKey AcceptChannel_get_funding_pubkey(const LDKAcceptChannel *this_ptr);
+struct LDKPublicKey AcceptChannel_get_funding_pubkey(const struct LDKAcceptChannel *NONNULL_PTR this_ptr);
 
 /**
  * The sender's key controlling the funding transaction
  */
-void AcceptChannel_set_funding_pubkey(LDKAcceptChannel *this_ptr, LDKPublicKey val);
+void AcceptChannel_set_funding_pubkey(struct LDKAcceptChannel *NONNULL_PTR this_ptr, struct LDKPublicKey val);
 
 /**
  * Used to derive a revocation key for transactions broadcast by counterparty
  */
-LDKPublicKey AcceptChannel_get_revocation_basepoint(const LDKAcceptChannel *this_ptr);
+struct LDKPublicKey AcceptChannel_get_revocation_basepoint(const struct LDKAcceptChannel *NONNULL_PTR this_ptr);
 
 /**
  * Used to derive a revocation key for transactions broadcast by counterparty
  */
-void AcceptChannel_set_revocation_basepoint(LDKAcceptChannel *this_ptr, LDKPublicKey val);
+void AcceptChannel_set_revocation_basepoint(struct LDKAcceptChannel *NONNULL_PTR this_ptr, struct LDKPublicKey val);
 
 /**
  * A payment key to sender for transactions broadcast by counterparty
  */
-LDKPublicKey AcceptChannel_get_payment_point(const LDKAcceptChannel *this_ptr);
+struct LDKPublicKey AcceptChannel_get_payment_point(const struct LDKAcceptChannel *NONNULL_PTR this_ptr);
 
 /**
  * A payment key to sender for transactions broadcast by counterparty
  */
-void AcceptChannel_set_payment_point(LDKAcceptChannel *this_ptr, LDKPublicKey val);
+void AcceptChannel_set_payment_point(struct LDKAcceptChannel *NONNULL_PTR this_ptr, struct LDKPublicKey val);
 
 /**
  * Used to derive a payment key to sender for transactions broadcast by sender
  */
-LDKPublicKey AcceptChannel_get_delayed_payment_basepoint(const LDKAcceptChannel *this_ptr);
+struct LDKPublicKey AcceptChannel_get_delayed_payment_basepoint(const struct LDKAcceptChannel *NONNULL_PTR this_ptr);
 
 /**
  * Used to derive a payment key to sender for transactions broadcast by sender
  */
-void AcceptChannel_set_delayed_payment_basepoint(LDKAcceptChannel *this_ptr, LDKPublicKey val);
+void AcceptChannel_set_delayed_payment_basepoint(struct LDKAcceptChannel *NONNULL_PTR this_ptr, struct LDKPublicKey val);
 
 /**
  * Used to derive an HTLC payment key to sender for transactions broadcast by counterparty
  */
-LDKPublicKey AcceptChannel_get_htlc_basepoint(const LDKAcceptChannel *this_ptr);
+struct LDKPublicKey AcceptChannel_get_htlc_basepoint(const struct LDKAcceptChannel *NONNULL_PTR this_ptr);
 
 /**
  * Used to derive an HTLC payment key to sender for transactions broadcast by counterparty
  */
-void AcceptChannel_set_htlc_basepoint(LDKAcceptChannel *this_ptr, LDKPublicKey val);
+void AcceptChannel_set_htlc_basepoint(struct LDKAcceptChannel *NONNULL_PTR this_ptr, struct LDKPublicKey val);
 
 /**
  * The first to-be-broadcast-by-sender transaction's per commitment point
  */
-LDKPublicKey AcceptChannel_get_first_per_commitment_point(const LDKAcceptChannel *this_ptr);
+struct LDKPublicKey AcceptChannel_get_first_per_commitment_point(const struct LDKAcceptChannel *NONNULL_PTR this_ptr);
 
 /**
  * The first to-be-broadcast-by-sender transaction's per commitment point
  */
-void AcceptChannel_set_first_per_commitment_point(LDKAcceptChannel *this_ptr, LDKPublicKey val);
+void AcceptChannel_set_first_per_commitment_point(struct LDKAcceptChannel *NONNULL_PTR this_ptr, struct LDKPublicKey val);
 
-void FundingCreated_free(LDKFundingCreated this_ptr);
+struct LDKAcceptChannel AcceptChannel_clone(const struct LDKAcceptChannel *NONNULL_PTR orig);
 
-LDKFundingCreated FundingCreated_clone(const LDKFundingCreated *orig);
+void FundingCreated_free(struct LDKFundingCreated this_ptr);
 
 /**
  * A temporary channel ID, until the funding is established
  */
-const uint8_t (*FundingCreated_get_temporary_channel_id(const LDKFundingCreated *this_ptr))[32];
+const uint8_t (*FundingCreated_get_temporary_channel_id(const struct LDKFundingCreated *NONNULL_PTR this_ptr))[32];
 
 /**
  * A temporary channel ID, until the funding is established
  */
-void FundingCreated_set_temporary_channel_id(LDKFundingCreated *this_ptr, LDKThirtyTwoBytes val);
+void FundingCreated_set_temporary_channel_id(struct LDKFundingCreated *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
 
 /**
  * The funding transaction ID
  */
-const uint8_t (*FundingCreated_get_funding_txid(const LDKFundingCreated *this_ptr))[32];
+const uint8_t (*FundingCreated_get_funding_txid(const struct LDKFundingCreated *NONNULL_PTR this_ptr))[32];
 
 /**
  * The funding transaction ID
  */
-void FundingCreated_set_funding_txid(LDKFundingCreated *this_ptr, LDKThirtyTwoBytes val);
+void FundingCreated_set_funding_txid(struct LDKFundingCreated *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
 
 /**
  * The specific output index funding this channel
  */
-uint16_t FundingCreated_get_funding_output_index(const LDKFundingCreated *this_ptr);
+uint16_t FundingCreated_get_funding_output_index(const struct LDKFundingCreated *NONNULL_PTR this_ptr);
 
 /**
  * The specific output index funding this channel
  */
-void FundingCreated_set_funding_output_index(LDKFundingCreated *this_ptr, uint16_t val);
+void FundingCreated_set_funding_output_index(struct LDKFundingCreated *NONNULL_PTR this_ptr, uint16_t val);
 
 /**
  * The signature of the channel initiator (funder) on the funding transaction
  */
-LDKSignature FundingCreated_get_signature(const LDKFundingCreated *this_ptr);
+struct LDKSignature FundingCreated_get_signature(const struct LDKFundingCreated *NONNULL_PTR this_ptr);
 
 /**
  * The signature of the channel initiator (funder) on the funding transaction
  */
-void FundingCreated_set_signature(LDKFundingCreated *this_ptr, LDKSignature val);
+void FundingCreated_set_signature(struct LDKFundingCreated *NONNULL_PTR this_ptr, struct LDKSignature val);
 
-MUST_USE_RES LDKFundingCreated FundingCreated_new(LDKThirtyTwoBytes temporary_channel_id_arg, LDKThirtyTwoBytes funding_txid_arg, uint16_t funding_output_index_arg, LDKSignature signature_arg);
+MUST_USE_RES struct LDKFundingCreated FundingCreated_new(struct LDKThirtyTwoBytes temporary_channel_id_arg, struct LDKThirtyTwoBytes funding_txid_arg, uint16_t funding_output_index_arg, struct LDKSignature signature_arg);
 
-void FundingSigned_free(LDKFundingSigned this_ptr);
+struct LDKFundingCreated FundingCreated_clone(const struct LDKFundingCreated *NONNULL_PTR orig);
 
-LDKFundingSigned FundingSigned_clone(const LDKFundingSigned *orig);
+void FundingSigned_free(struct LDKFundingSigned this_ptr);
 
 /**
  * The channel ID
  */
-const uint8_t (*FundingSigned_get_channel_id(const LDKFundingSigned *this_ptr))[32];
+const uint8_t (*FundingSigned_get_channel_id(const struct LDKFundingSigned *NONNULL_PTR this_ptr))[32];
 
 /**
  * The channel ID
  */
-void FundingSigned_set_channel_id(LDKFundingSigned *this_ptr, LDKThirtyTwoBytes val);
+void FundingSigned_set_channel_id(struct LDKFundingSigned *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
 
 /**
  * The signature of the channel acceptor (fundee) on the funding transaction
  */
-LDKSignature FundingSigned_get_signature(const LDKFundingSigned *this_ptr);
+struct LDKSignature FundingSigned_get_signature(const struct LDKFundingSigned *NONNULL_PTR this_ptr);
 
 /**
  * The signature of the channel acceptor (fundee) on the funding transaction
  */
-void FundingSigned_set_signature(LDKFundingSigned *this_ptr, LDKSignature val);
+void FundingSigned_set_signature(struct LDKFundingSigned *NONNULL_PTR this_ptr, struct LDKSignature val);
 
-MUST_USE_RES LDKFundingSigned FundingSigned_new(LDKThirtyTwoBytes channel_id_arg, LDKSignature signature_arg);
+MUST_USE_RES struct LDKFundingSigned FundingSigned_new(struct LDKThirtyTwoBytes channel_id_arg, struct LDKSignature signature_arg);
 
-void FundingLocked_free(LDKFundingLocked this_ptr);
+struct LDKFundingSigned FundingSigned_clone(const struct LDKFundingSigned *NONNULL_PTR orig);
 
-LDKFundingLocked FundingLocked_clone(const LDKFundingLocked *orig);
+void FundingLocked_free(struct LDKFundingLocked this_ptr);
 
 /**
  * The channel ID
  */
-const uint8_t (*FundingLocked_get_channel_id(const LDKFundingLocked *this_ptr))[32];
+const uint8_t (*FundingLocked_get_channel_id(const struct LDKFundingLocked *NONNULL_PTR this_ptr))[32];
 
 /**
  * The channel ID
  */
-void FundingLocked_set_channel_id(LDKFundingLocked *this_ptr, LDKThirtyTwoBytes val);
+void FundingLocked_set_channel_id(struct LDKFundingLocked *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
 
 /**
  * The per-commitment point of the second commitment transaction
  */
-LDKPublicKey FundingLocked_get_next_per_commitment_point(const LDKFundingLocked *this_ptr);
+struct LDKPublicKey FundingLocked_get_next_per_commitment_point(const struct LDKFundingLocked *NONNULL_PTR this_ptr);
 
 /**
  * The per-commitment point of the second commitment transaction
  */
-void FundingLocked_set_next_per_commitment_point(LDKFundingLocked *this_ptr, LDKPublicKey val);
+void FundingLocked_set_next_per_commitment_point(struct LDKFundingLocked *NONNULL_PTR this_ptr, struct LDKPublicKey val);
 
-MUST_USE_RES LDKFundingLocked FundingLocked_new(LDKThirtyTwoBytes channel_id_arg, LDKPublicKey next_per_commitment_point_arg);
+MUST_USE_RES struct LDKFundingLocked FundingLocked_new(struct LDKThirtyTwoBytes channel_id_arg, struct LDKPublicKey next_per_commitment_point_arg);
 
-void Shutdown_free(LDKShutdown this_ptr);
+struct LDKFundingLocked FundingLocked_clone(const struct LDKFundingLocked *NONNULL_PTR orig);
 
-LDKShutdown Shutdown_clone(const LDKShutdown *orig);
+void Shutdown_free(struct LDKShutdown this_ptr);
 
 /**
  * The channel ID
  */
-const uint8_t (*Shutdown_get_channel_id(const LDKShutdown *this_ptr))[32];
+const uint8_t (*Shutdown_get_channel_id(const struct LDKShutdown *NONNULL_PTR this_ptr))[32];
 
 /**
  * The channel ID
  */
-void Shutdown_set_channel_id(LDKShutdown *this_ptr, LDKThirtyTwoBytes val);
+void Shutdown_set_channel_id(struct LDKShutdown *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
 
 /**
  * The destination of this peer's funds on closing.
  * Must be in one of these forms: p2pkh, p2sh, p2wpkh, p2wsh.
  */
-LDKu8slice Shutdown_get_scriptpubkey(const LDKShutdown *this_ptr);
+struct LDKu8slice Shutdown_get_scriptpubkey(const struct LDKShutdown *NONNULL_PTR this_ptr);
 
 /**
  * The destination of this peer's funds on closing.
  * Must be in one of these forms: p2pkh, p2sh, p2wpkh, p2wsh.
  */
-void Shutdown_set_scriptpubkey(LDKShutdown *this_ptr, LDKCVec_u8Z val);
+void Shutdown_set_scriptpubkey(struct LDKShutdown *NONNULL_PTR this_ptr, struct LDKCVec_u8Z val);
 
-MUST_USE_RES LDKShutdown Shutdown_new(LDKThirtyTwoBytes channel_id_arg, LDKCVec_u8Z scriptpubkey_arg);
+MUST_USE_RES struct LDKShutdown Shutdown_new(struct LDKThirtyTwoBytes channel_id_arg, struct LDKCVec_u8Z scriptpubkey_arg);
 
-void ClosingSigned_free(LDKClosingSigned this_ptr);
+struct LDKShutdown Shutdown_clone(const struct LDKShutdown *NONNULL_PTR orig);
 
-LDKClosingSigned ClosingSigned_clone(const LDKClosingSigned *orig);
+void ClosingSigned_free(struct LDKClosingSigned this_ptr);
 
 /**
  * The channel ID
  */
-const uint8_t (*ClosingSigned_get_channel_id(const LDKClosingSigned *this_ptr))[32];
+const uint8_t (*ClosingSigned_get_channel_id(const struct LDKClosingSigned *NONNULL_PTR this_ptr))[32];
 
 /**
  * The channel ID
  */
-void ClosingSigned_set_channel_id(LDKClosingSigned *this_ptr, LDKThirtyTwoBytes val);
+void ClosingSigned_set_channel_id(struct LDKClosingSigned *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
 
 /**
  * The proposed total fee for the closing transaction
  */
-uint64_t ClosingSigned_get_fee_satoshis(const LDKClosingSigned *this_ptr);
+uint64_t ClosingSigned_get_fee_satoshis(const struct LDKClosingSigned *NONNULL_PTR this_ptr);
 
 /**
  * The proposed total fee for the closing transaction
  */
-void ClosingSigned_set_fee_satoshis(LDKClosingSigned *this_ptr, uint64_t val);
+void ClosingSigned_set_fee_satoshis(struct LDKClosingSigned *NONNULL_PTR this_ptr, uint64_t val);
 
 /**
  * A signature on the closing transaction
  */
-LDKSignature ClosingSigned_get_signature(const LDKClosingSigned *this_ptr);
+struct LDKSignature ClosingSigned_get_signature(const struct LDKClosingSigned *NONNULL_PTR this_ptr);
 
 /**
  * A signature on the closing transaction
  */
-void ClosingSigned_set_signature(LDKClosingSigned *this_ptr, LDKSignature val);
+void ClosingSigned_set_signature(struct LDKClosingSigned *NONNULL_PTR this_ptr, struct LDKSignature val);
 
-MUST_USE_RES LDKClosingSigned ClosingSigned_new(LDKThirtyTwoBytes channel_id_arg, uint64_t fee_satoshis_arg, LDKSignature signature_arg);
+MUST_USE_RES struct LDKClosingSigned ClosingSigned_new(struct LDKThirtyTwoBytes channel_id_arg, uint64_t fee_satoshis_arg, struct LDKSignature signature_arg);
 
-void UpdateAddHTLC_free(LDKUpdateAddHTLC this_ptr);
+struct LDKClosingSigned ClosingSigned_clone(const struct LDKClosingSigned *NONNULL_PTR orig);
 
-LDKUpdateAddHTLC UpdateAddHTLC_clone(const LDKUpdateAddHTLC *orig);
+void UpdateAddHTLC_free(struct LDKUpdateAddHTLC this_ptr);
 
 /**
  * The channel ID
  */
-const uint8_t (*UpdateAddHTLC_get_channel_id(const LDKUpdateAddHTLC *this_ptr))[32];
+const uint8_t (*UpdateAddHTLC_get_channel_id(const struct LDKUpdateAddHTLC *NONNULL_PTR this_ptr))[32];
 
 /**
  * The channel ID
  */
-void UpdateAddHTLC_set_channel_id(LDKUpdateAddHTLC *this_ptr, LDKThirtyTwoBytes val);
+void UpdateAddHTLC_set_channel_id(struct LDKUpdateAddHTLC *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
 
 /**
  * The HTLC ID
  */
-uint64_t UpdateAddHTLC_get_htlc_id(const LDKUpdateAddHTLC *this_ptr);
+uint64_t UpdateAddHTLC_get_htlc_id(const struct LDKUpdateAddHTLC *NONNULL_PTR this_ptr);
 
 /**
  * The HTLC ID
  */
-void UpdateAddHTLC_set_htlc_id(LDKUpdateAddHTLC *this_ptr, uint64_t val);
+void UpdateAddHTLC_set_htlc_id(struct LDKUpdateAddHTLC *NONNULL_PTR this_ptr, uint64_t val);
 
 /**
  * The HTLC value in milli-satoshi
  */
-uint64_t UpdateAddHTLC_get_amount_msat(const LDKUpdateAddHTLC *this_ptr);
+uint64_t UpdateAddHTLC_get_amount_msat(const struct LDKUpdateAddHTLC *NONNULL_PTR this_ptr);
 
 /**
  * The HTLC value in milli-satoshi
  */
-void UpdateAddHTLC_set_amount_msat(LDKUpdateAddHTLC *this_ptr, uint64_t val);
+void UpdateAddHTLC_set_amount_msat(struct LDKUpdateAddHTLC *NONNULL_PTR this_ptr, uint64_t val);
 
 /**
  * The payment hash, the pre-image of which controls HTLC redemption
  */
-const uint8_t (*UpdateAddHTLC_get_payment_hash(const LDKUpdateAddHTLC *this_ptr))[32];
+const uint8_t (*UpdateAddHTLC_get_payment_hash(const struct LDKUpdateAddHTLC *NONNULL_PTR this_ptr))[32];
 
 /**
  * The payment hash, the pre-image of which controls HTLC redemption
  */
-void UpdateAddHTLC_set_payment_hash(LDKUpdateAddHTLC *this_ptr, LDKThirtyTwoBytes val);
+void UpdateAddHTLC_set_payment_hash(struct LDKUpdateAddHTLC *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
 
 /**
  * The expiry height of the HTLC
  */
-uint32_t UpdateAddHTLC_get_cltv_expiry(const LDKUpdateAddHTLC *this_ptr);
+uint32_t UpdateAddHTLC_get_cltv_expiry(const struct LDKUpdateAddHTLC *NONNULL_PTR this_ptr);
 
 /**
  * The expiry height of the HTLC
  */
-void UpdateAddHTLC_set_cltv_expiry(LDKUpdateAddHTLC *this_ptr, uint32_t val);
+void UpdateAddHTLC_set_cltv_expiry(struct LDKUpdateAddHTLC *NONNULL_PTR this_ptr, uint32_t val);
 
-void UpdateFulfillHTLC_free(LDKUpdateFulfillHTLC this_ptr);
+struct LDKUpdateAddHTLC UpdateAddHTLC_clone(const struct LDKUpdateAddHTLC *NONNULL_PTR orig);
 
-LDKUpdateFulfillHTLC UpdateFulfillHTLC_clone(const LDKUpdateFulfillHTLC *orig);
+void UpdateFulfillHTLC_free(struct LDKUpdateFulfillHTLC this_ptr);
 
 /**
  * The channel ID
  */
-const uint8_t (*UpdateFulfillHTLC_get_channel_id(const LDKUpdateFulfillHTLC *this_ptr))[32];
+const uint8_t (*UpdateFulfillHTLC_get_channel_id(const struct LDKUpdateFulfillHTLC *NONNULL_PTR this_ptr))[32];
 
 /**
  * The channel ID
  */
-void UpdateFulfillHTLC_set_channel_id(LDKUpdateFulfillHTLC *this_ptr, LDKThirtyTwoBytes val);
+void UpdateFulfillHTLC_set_channel_id(struct LDKUpdateFulfillHTLC *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
 
 /**
  * The HTLC ID
  */
-uint64_t UpdateFulfillHTLC_get_htlc_id(const LDKUpdateFulfillHTLC *this_ptr);
+uint64_t UpdateFulfillHTLC_get_htlc_id(const struct LDKUpdateFulfillHTLC *NONNULL_PTR this_ptr);
 
 /**
  * The HTLC ID
  */
-void UpdateFulfillHTLC_set_htlc_id(LDKUpdateFulfillHTLC *this_ptr, uint64_t val);
+void UpdateFulfillHTLC_set_htlc_id(struct LDKUpdateFulfillHTLC *NONNULL_PTR this_ptr, uint64_t val);
 
 /**
  * The pre-image of the payment hash, allowing HTLC redemption
  */
-const uint8_t (*UpdateFulfillHTLC_get_payment_preimage(const LDKUpdateFulfillHTLC *this_ptr))[32];
+const uint8_t (*UpdateFulfillHTLC_get_payment_preimage(const struct LDKUpdateFulfillHTLC *NONNULL_PTR this_ptr))[32];
 
 /**
  * The pre-image of the payment hash, allowing HTLC redemption
  */
-void UpdateFulfillHTLC_set_payment_preimage(LDKUpdateFulfillHTLC *this_ptr, LDKThirtyTwoBytes val);
+void UpdateFulfillHTLC_set_payment_preimage(struct LDKUpdateFulfillHTLC *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
 
-MUST_USE_RES LDKUpdateFulfillHTLC UpdateFulfillHTLC_new(LDKThirtyTwoBytes channel_id_arg, uint64_t htlc_id_arg, LDKThirtyTwoBytes payment_preimage_arg);
+MUST_USE_RES struct LDKUpdateFulfillHTLC UpdateFulfillHTLC_new(struct LDKThirtyTwoBytes channel_id_arg, uint64_t htlc_id_arg, struct LDKThirtyTwoBytes payment_preimage_arg);
 
-void UpdateFailHTLC_free(LDKUpdateFailHTLC this_ptr);
+struct LDKUpdateFulfillHTLC UpdateFulfillHTLC_clone(const struct LDKUpdateFulfillHTLC *NONNULL_PTR orig);
 
-LDKUpdateFailHTLC UpdateFailHTLC_clone(const LDKUpdateFailHTLC *orig);
+void UpdateFailHTLC_free(struct LDKUpdateFailHTLC this_ptr);
 
 /**
  * The channel ID
  */
-const uint8_t (*UpdateFailHTLC_get_channel_id(const LDKUpdateFailHTLC *this_ptr))[32];
+const uint8_t (*UpdateFailHTLC_get_channel_id(const struct LDKUpdateFailHTLC *NONNULL_PTR this_ptr))[32];
 
 /**
  * The channel ID
  */
-void UpdateFailHTLC_set_channel_id(LDKUpdateFailHTLC *this_ptr, LDKThirtyTwoBytes val);
+void UpdateFailHTLC_set_channel_id(struct LDKUpdateFailHTLC *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
 
 /**
  * The HTLC ID
  */
-uint64_t UpdateFailHTLC_get_htlc_id(const LDKUpdateFailHTLC *this_ptr);
+uint64_t UpdateFailHTLC_get_htlc_id(const struct LDKUpdateFailHTLC *NONNULL_PTR this_ptr);
 
 /**
  * The HTLC ID
  */
-void UpdateFailHTLC_set_htlc_id(LDKUpdateFailHTLC *this_ptr, uint64_t val);
+void UpdateFailHTLC_set_htlc_id(struct LDKUpdateFailHTLC *NONNULL_PTR this_ptr, uint64_t val);
 
-void UpdateFailMalformedHTLC_free(LDKUpdateFailMalformedHTLC this_ptr);
+struct LDKUpdateFailHTLC UpdateFailHTLC_clone(const struct LDKUpdateFailHTLC *NONNULL_PTR orig);
 
-LDKUpdateFailMalformedHTLC UpdateFailMalformedHTLC_clone(const LDKUpdateFailMalformedHTLC *orig);
+void UpdateFailMalformedHTLC_free(struct LDKUpdateFailMalformedHTLC this_ptr);
 
 /**
  * The channel ID
  */
-const uint8_t (*UpdateFailMalformedHTLC_get_channel_id(const LDKUpdateFailMalformedHTLC *this_ptr))[32];
+const uint8_t (*UpdateFailMalformedHTLC_get_channel_id(const struct LDKUpdateFailMalformedHTLC *NONNULL_PTR this_ptr))[32];
 
 /**
  * The channel ID
  */
-void UpdateFailMalformedHTLC_set_channel_id(LDKUpdateFailMalformedHTLC *this_ptr, LDKThirtyTwoBytes val);
+void UpdateFailMalformedHTLC_set_channel_id(struct LDKUpdateFailMalformedHTLC *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
 
 /**
  * The HTLC ID
  */
-uint64_t UpdateFailMalformedHTLC_get_htlc_id(const LDKUpdateFailMalformedHTLC *this_ptr);
+uint64_t UpdateFailMalformedHTLC_get_htlc_id(const struct LDKUpdateFailMalformedHTLC *NONNULL_PTR this_ptr);
 
 /**
  * The HTLC ID
  */
-void UpdateFailMalformedHTLC_set_htlc_id(LDKUpdateFailMalformedHTLC *this_ptr, uint64_t val);
+void UpdateFailMalformedHTLC_set_htlc_id(struct LDKUpdateFailMalformedHTLC *NONNULL_PTR this_ptr, uint64_t val);
 
 /**
  * The failure code
  */
-uint16_t UpdateFailMalformedHTLC_get_failure_code(const LDKUpdateFailMalformedHTLC *this_ptr);
+uint16_t UpdateFailMalformedHTLC_get_failure_code(const struct LDKUpdateFailMalformedHTLC *NONNULL_PTR this_ptr);
 
 /**
  * The failure code
  */
-void UpdateFailMalformedHTLC_set_failure_code(LDKUpdateFailMalformedHTLC *this_ptr, uint16_t val);
+void UpdateFailMalformedHTLC_set_failure_code(struct LDKUpdateFailMalformedHTLC *NONNULL_PTR this_ptr, uint16_t val);
 
-void CommitmentSigned_free(LDKCommitmentSigned this_ptr);
+struct LDKUpdateFailMalformedHTLC UpdateFailMalformedHTLC_clone(const struct LDKUpdateFailMalformedHTLC *NONNULL_PTR orig);
 
-LDKCommitmentSigned CommitmentSigned_clone(const LDKCommitmentSigned *orig);
+void CommitmentSigned_free(struct LDKCommitmentSigned this_ptr);
 
 /**
  * The channel ID
  */
-const uint8_t (*CommitmentSigned_get_channel_id(const LDKCommitmentSigned *this_ptr))[32];
+const uint8_t (*CommitmentSigned_get_channel_id(const struct LDKCommitmentSigned *NONNULL_PTR this_ptr))[32];
 
 /**
  * The channel ID
  */
-void CommitmentSigned_set_channel_id(LDKCommitmentSigned *this_ptr, LDKThirtyTwoBytes val);
+void CommitmentSigned_set_channel_id(struct LDKCommitmentSigned *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
 
 /**
  * A signature on the commitment transaction
  */
-LDKSignature CommitmentSigned_get_signature(const LDKCommitmentSigned *this_ptr);
+struct LDKSignature CommitmentSigned_get_signature(const struct LDKCommitmentSigned *NONNULL_PTR this_ptr);
 
 /**
  * A signature on the commitment transaction
  */
-void CommitmentSigned_set_signature(LDKCommitmentSigned *this_ptr, LDKSignature val);
+void CommitmentSigned_set_signature(struct LDKCommitmentSigned *NONNULL_PTR this_ptr, struct LDKSignature val);
 
 /**
  * Signatures on the HTLC transactions
  */
-void CommitmentSigned_set_htlc_signatures(LDKCommitmentSigned *this_ptr, LDKCVec_SignatureZ val);
+void CommitmentSigned_set_htlc_signatures(struct LDKCommitmentSigned *NONNULL_PTR this_ptr, struct LDKCVec_SignatureZ val);
 
-MUST_USE_RES LDKCommitmentSigned CommitmentSigned_new(LDKThirtyTwoBytes channel_id_arg, LDKSignature signature_arg, LDKCVec_SignatureZ htlc_signatures_arg);
+MUST_USE_RES struct LDKCommitmentSigned CommitmentSigned_new(struct LDKThirtyTwoBytes channel_id_arg, struct LDKSignature signature_arg, struct LDKCVec_SignatureZ htlc_signatures_arg);
 
-void RevokeAndACK_free(LDKRevokeAndACK this_ptr);
+struct LDKCommitmentSigned CommitmentSigned_clone(const struct LDKCommitmentSigned *NONNULL_PTR orig);
 
-LDKRevokeAndACK RevokeAndACK_clone(const LDKRevokeAndACK *orig);
+void RevokeAndACK_free(struct LDKRevokeAndACK this_ptr);
 
 /**
  * The channel ID
  */
-const uint8_t (*RevokeAndACK_get_channel_id(const LDKRevokeAndACK *this_ptr))[32];
+const uint8_t (*RevokeAndACK_get_channel_id(const struct LDKRevokeAndACK *NONNULL_PTR this_ptr))[32];
 
 /**
  * The channel ID
  */
-void RevokeAndACK_set_channel_id(LDKRevokeAndACK *this_ptr, LDKThirtyTwoBytes val);
+void RevokeAndACK_set_channel_id(struct LDKRevokeAndACK *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
 
 /**
  * The secret corresponding to the per-commitment point
  */
-const uint8_t (*RevokeAndACK_get_per_commitment_secret(const LDKRevokeAndACK *this_ptr))[32];
+const uint8_t (*RevokeAndACK_get_per_commitment_secret(const struct LDKRevokeAndACK *NONNULL_PTR this_ptr))[32];
 
 /**
  * The secret corresponding to the per-commitment point
  */
-void RevokeAndACK_set_per_commitment_secret(LDKRevokeAndACK *this_ptr, LDKThirtyTwoBytes val);
+void RevokeAndACK_set_per_commitment_secret(struct LDKRevokeAndACK *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
 
 /**
  * The next sender-broadcast commitment transaction's per-commitment point
  */
-LDKPublicKey RevokeAndACK_get_next_per_commitment_point(const LDKRevokeAndACK *this_ptr);
+struct LDKPublicKey RevokeAndACK_get_next_per_commitment_point(const struct LDKRevokeAndACK *NONNULL_PTR this_ptr);
 
 /**
  * The next sender-broadcast commitment transaction's per-commitment point
  */
-void RevokeAndACK_set_next_per_commitment_point(LDKRevokeAndACK *this_ptr, LDKPublicKey val);
+void RevokeAndACK_set_next_per_commitment_point(struct LDKRevokeAndACK *NONNULL_PTR this_ptr, struct LDKPublicKey val);
 
-MUST_USE_RES LDKRevokeAndACK RevokeAndACK_new(LDKThirtyTwoBytes channel_id_arg, LDKThirtyTwoBytes per_commitment_secret_arg, LDKPublicKey next_per_commitment_point_arg);
+MUST_USE_RES struct LDKRevokeAndACK RevokeAndACK_new(struct LDKThirtyTwoBytes channel_id_arg, struct LDKThirtyTwoBytes per_commitment_secret_arg, struct LDKPublicKey next_per_commitment_point_arg);
 
-void UpdateFee_free(LDKUpdateFee this_ptr);
+struct LDKRevokeAndACK RevokeAndACK_clone(const struct LDKRevokeAndACK *NONNULL_PTR orig);
 
-LDKUpdateFee UpdateFee_clone(const LDKUpdateFee *orig);
+void UpdateFee_free(struct LDKUpdateFee this_ptr);
 
 /**
  * The channel ID
  */
-const uint8_t (*UpdateFee_get_channel_id(const LDKUpdateFee *this_ptr))[32];
+const uint8_t (*UpdateFee_get_channel_id(const struct LDKUpdateFee *NONNULL_PTR this_ptr))[32];
 
 /**
  * The channel ID
  */
-void UpdateFee_set_channel_id(LDKUpdateFee *this_ptr, LDKThirtyTwoBytes val);
+void UpdateFee_set_channel_id(struct LDKUpdateFee *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
 
 /**
  * Fee rate per 1000-weight of the transaction
  */
-uint32_t UpdateFee_get_feerate_per_kw(const LDKUpdateFee *this_ptr);
+uint32_t UpdateFee_get_feerate_per_kw(const struct LDKUpdateFee *NONNULL_PTR this_ptr);
 
 /**
  * Fee rate per 1000-weight of the transaction
  */
-void UpdateFee_set_feerate_per_kw(LDKUpdateFee *this_ptr, uint32_t val);
+void UpdateFee_set_feerate_per_kw(struct LDKUpdateFee *NONNULL_PTR this_ptr, uint32_t val);
 
-MUST_USE_RES LDKUpdateFee UpdateFee_new(LDKThirtyTwoBytes channel_id_arg, uint32_t feerate_per_kw_arg);
+MUST_USE_RES struct LDKUpdateFee UpdateFee_new(struct LDKThirtyTwoBytes channel_id_arg, uint32_t feerate_per_kw_arg);
 
-void DataLossProtect_free(LDKDataLossProtect this_ptr);
+struct LDKUpdateFee UpdateFee_clone(const struct LDKUpdateFee *NONNULL_PTR orig);
 
-LDKDataLossProtect DataLossProtect_clone(const LDKDataLossProtect *orig);
+void DataLossProtect_free(struct LDKDataLossProtect this_ptr);
 
 /**
  * Proof that the sender knows the per-commitment secret of a specific commitment transaction
  * belonging to the recipient
  */
-const uint8_t (*DataLossProtect_get_your_last_per_commitment_secret(const LDKDataLossProtect *this_ptr))[32];
+const uint8_t (*DataLossProtect_get_your_last_per_commitment_secret(const struct LDKDataLossProtect *NONNULL_PTR this_ptr))[32];
 
 /**
  * Proof that the sender knows the per-commitment secret of a specific commitment transaction
  * belonging to the recipient
  */
-void DataLossProtect_set_your_last_per_commitment_secret(LDKDataLossProtect *this_ptr, LDKThirtyTwoBytes val);
+void DataLossProtect_set_your_last_per_commitment_secret(struct LDKDataLossProtect *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
 
 /**
  * The sender's per-commitment point for their current commitment transaction
  */
-LDKPublicKey DataLossProtect_get_my_current_per_commitment_point(const LDKDataLossProtect *this_ptr);
+struct LDKPublicKey DataLossProtect_get_my_current_per_commitment_point(const struct LDKDataLossProtect *NONNULL_PTR this_ptr);
 
 /**
  * The sender's per-commitment point for their current commitment transaction
  */
-void DataLossProtect_set_my_current_per_commitment_point(LDKDataLossProtect *this_ptr, LDKPublicKey val);
+void DataLossProtect_set_my_current_per_commitment_point(struct LDKDataLossProtect *NONNULL_PTR this_ptr, struct LDKPublicKey val);
 
-MUST_USE_RES LDKDataLossProtect DataLossProtect_new(LDKThirtyTwoBytes your_last_per_commitment_secret_arg, LDKPublicKey my_current_per_commitment_point_arg);
+MUST_USE_RES struct LDKDataLossProtect DataLossProtect_new(struct LDKThirtyTwoBytes your_last_per_commitment_secret_arg, struct LDKPublicKey my_current_per_commitment_point_arg);
 
-void ChannelReestablish_free(LDKChannelReestablish this_ptr);
+struct LDKDataLossProtect DataLossProtect_clone(const struct LDKDataLossProtect *NONNULL_PTR orig);
 
-LDKChannelReestablish ChannelReestablish_clone(const LDKChannelReestablish *orig);
+void ChannelReestablish_free(struct LDKChannelReestablish this_ptr);
 
 /**
  * The channel ID
  */
-const uint8_t (*ChannelReestablish_get_channel_id(const LDKChannelReestablish *this_ptr))[32];
+const uint8_t (*ChannelReestablish_get_channel_id(const struct LDKChannelReestablish *NONNULL_PTR this_ptr))[32];
 
 /**
  * The channel ID
  */
-void ChannelReestablish_set_channel_id(LDKChannelReestablish *this_ptr, LDKThirtyTwoBytes val);
+void ChannelReestablish_set_channel_id(struct LDKChannelReestablish *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
 
 /**
  * The next commitment number for the sender
  */
-uint64_t ChannelReestablish_get_next_local_commitment_number(const LDKChannelReestablish *this_ptr);
+uint64_t ChannelReestablish_get_next_local_commitment_number(const struct LDKChannelReestablish *NONNULL_PTR this_ptr);
 
 /**
  * The next commitment number for the sender
  */
-void ChannelReestablish_set_next_local_commitment_number(LDKChannelReestablish *this_ptr, uint64_t val);
+void ChannelReestablish_set_next_local_commitment_number(struct LDKChannelReestablish *NONNULL_PTR this_ptr, uint64_t val);
 
 /**
  * The next commitment number for the recipient
  */
-uint64_t ChannelReestablish_get_next_remote_commitment_number(const LDKChannelReestablish *this_ptr);
+uint64_t ChannelReestablish_get_next_remote_commitment_number(const struct LDKChannelReestablish *NONNULL_PTR this_ptr);
 
 /**
  * The next commitment number for the recipient
  */
-void ChannelReestablish_set_next_remote_commitment_number(LDKChannelReestablish *this_ptr, uint64_t val);
+void ChannelReestablish_set_next_remote_commitment_number(struct LDKChannelReestablish *NONNULL_PTR this_ptr, uint64_t val);
 
-void AnnouncementSignatures_free(LDKAnnouncementSignatures this_ptr);
+struct LDKChannelReestablish ChannelReestablish_clone(const struct LDKChannelReestablish *NONNULL_PTR orig);
 
-LDKAnnouncementSignatures AnnouncementSignatures_clone(const LDKAnnouncementSignatures *orig);
+void AnnouncementSignatures_free(struct LDKAnnouncementSignatures this_ptr);
 
 /**
  * The channel ID
  */
-const uint8_t (*AnnouncementSignatures_get_channel_id(const LDKAnnouncementSignatures *this_ptr))[32];
+const uint8_t (*AnnouncementSignatures_get_channel_id(const struct LDKAnnouncementSignatures *NONNULL_PTR this_ptr))[32];
 
 /**
  * The channel ID
  */
-void AnnouncementSignatures_set_channel_id(LDKAnnouncementSignatures *this_ptr, LDKThirtyTwoBytes val);
+void AnnouncementSignatures_set_channel_id(struct LDKAnnouncementSignatures *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
 
 /**
  * The short channel ID
  */
-uint64_t AnnouncementSignatures_get_short_channel_id(const LDKAnnouncementSignatures *this_ptr);
+uint64_t AnnouncementSignatures_get_short_channel_id(const struct LDKAnnouncementSignatures *NONNULL_PTR this_ptr);
 
 /**
  * The short channel ID
  */
-void AnnouncementSignatures_set_short_channel_id(LDKAnnouncementSignatures *this_ptr, uint64_t val);
+void AnnouncementSignatures_set_short_channel_id(struct LDKAnnouncementSignatures *NONNULL_PTR this_ptr, uint64_t val);
 
 /**
  * A signature by the node key
  */
-LDKSignature AnnouncementSignatures_get_node_signature(const LDKAnnouncementSignatures *this_ptr);
+struct LDKSignature AnnouncementSignatures_get_node_signature(const struct LDKAnnouncementSignatures *NONNULL_PTR this_ptr);
 
 /**
  * A signature by the node key
  */
-void AnnouncementSignatures_set_node_signature(LDKAnnouncementSignatures *this_ptr, LDKSignature val);
+void AnnouncementSignatures_set_node_signature(struct LDKAnnouncementSignatures *NONNULL_PTR this_ptr, struct LDKSignature val);
 
 /**
  * A signature by the funding key
  */
-LDKSignature AnnouncementSignatures_get_bitcoin_signature(const LDKAnnouncementSignatures *this_ptr);
+struct LDKSignature AnnouncementSignatures_get_bitcoin_signature(const struct LDKAnnouncementSignatures *NONNULL_PTR this_ptr);
 
 /**
  * A signature by the funding key
  */
-void AnnouncementSignatures_set_bitcoin_signature(LDKAnnouncementSignatures *this_ptr, LDKSignature val);
+void AnnouncementSignatures_set_bitcoin_signature(struct LDKAnnouncementSignatures *NONNULL_PTR this_ptr, struct LDKSignature val);
+
+MUST_USE_RES struct LDKAnnouncementSignatures AnnouncementSignatures_new(struct LDKThirtyTwoBytes channel_id_arg, uint64_t short_channel_id_arg, struct LDKSignature node_signature_arg, struct LDKSignature bitcoin_signature_arg);
 
-MUST_USE_RES LDKAnnouncementSignatures AnnouncementSignatures_new(LDKThirtyTwoBytes channel_id_arg, uint64_t short_channel_id_arg, LDKSignature node_signature_arg, LDKSignature bitcoin_signature_arg);
+struct LDKAnnouncementSignatures AnnouncementSignatures_clone(const struct LDKAnnouncementSignatures *NONNULL_PTR orig);
 
-void NetAddress_free(LDKNetAddress this_ptr);
+void NetAddress_free(struct LDKNetAddress this_ptr);
 
-LDKNetAddress NetAddress_clone(const LDKNetAddress *orig);
+struct LDKNetAddress NetAddress_clone(const struct LDKNetAddress *NONNULL_PTR orig);
 
-void UnsignedNodeAnnouncement_free(LDKUnsignedNodeAnnouncement this_ptr);
+struct LDKCVec_u8Z NetAddress_write(const struct LDKNetAddress *NONNULL_PTR obj);
 
-LDKUnsignedNodeAnnouncement UnsignedNodeAnnouncement_clone(const LDKUnsignedNodeAnnouncement *orig);
+struct LDKCResult_CResult_NetAddressu8ZDecodeErrorZ Result_read(struct LDKu8slice ser);
+
+void UnsignedNodeAnnouncement_free(struct LDKUnsignedNodeAnnouncement this_ptr);
 
 /**
  * The advertised features
  */
-LDKNodeFeatures UnsignedNodeAnnouncement_get_features(const LDKUnsignedNodeAnnouncement *this_ptr);
+struct LDKNodeFeatures UnsignedNodeAnnouncement_get_features(const struct LDKUnsignedNodeAnnouncement *NONNULL_PTR this_ptr);
 
 /**
  * The advertised features
  */
-void UnsignedNodeAnnouncement_set_features(LDKUnsignedNodeAnnouncement *this_ptr, LDKNodeFeatures val);
+void UnsignedNodeAnnouncement_set_features(struct LDKUnsignedNodeAnnouncement *NONNULL_PTR this_ptr, struct LDKNodeFeatures val);
 
 /**
  * A strictly monotonic announcement counter, with gaps allowed
  */
-uint32_t UnsignedNodeAnnouncement_get_timestamp(const LDKUnsignedNodeAnnouncement *this_ptr);
+uint32_t UnsignedNodeAnnouncement_get_timestamp(const struct LDKUnsignedNodeAnnouncement *NONNULL_PTR this_ptr);
 
 /**
  * A strictly monotonic announcement counter, with gaps allowed
  */
-void UnsignedNodeAnnouncement_set_timestamp(LDKUnsignedNodeAnnouncement *this_ptr, uint32_t val);
+void UnsignedNodeAnnouncement_set_timestamp(struct LDKUnsignedNodeAnnouncement *NONNULL_PTR this_ptr, uint32_t val);
 
 /**
  * The node_id this announcement originated from (don't rebroadcast the node_announcement back
  * to this node).
  */
-LDKPublicKey UnsignedNodeAnnouncement_get_node_id(const LDKUnsignedNodeAnnouncement *this_ptr);
+struct LDKPublicKey UnsignedNodeAnnouncement_get_node_id(const struct LDKUnsignedNodeAnnouncement *NONNULL_PTR this_ptr);
 
 /**
  * The node_id this announcement originated from (don't rebroadcast the node_announcement back
  * to this node).
  */
-void UnsignedNodeAnnouncement_set_node_id(LDKUnsignedNodeAnnouncement *this_ptr, LDKPublicKey val);
+void UnsignedNodeAnnouncement_set_node_id(struct LDKUnsignedNodeAnnouncement *NONNULL_PTR this_ptr, struct LDKPublicKey val);
 
 /**
  * An RGB color for UI purposes
  */
-const uint8_t (*UnsignedNodeAnnouncement_get_rgb(const LDKUnsignedNodeAnnouncement *this_ptr))[3];
+const uint8_t (*UnsignedNodeAnnouncement_get_rgb(const struct LDKUnsignedNodeAnnouncement *NONNULL_PTR this_ptr))[3];
 
 /**
  * An RGB color for UI purposes
  */
-void UnsignedNodeAnnouncement_set_rgb(LDKUnsignedNodeAnnouncement *this_ptr, LDKThreeBytes val);
+void UnsignedNodeAnnouncement_set_rgb(struct LDKUnsignedNodeAnnouncement *NONNULL_PTR this_ptr, struct LDKThreeBytes val);
 
 /**
  * An alias, for UI purposes.  This should be sanitized before use.  There is no guarantee
  * of uniqueness.
  */
-const uint8_t (*UnsignedNodeAnnouncement_get_alias(const LDKUnsignedNodeAnnouncement *this_ptr))[32];
+const uint8_t (*UnsignedNodeAnnouncement_get_alias(const struct LDKUnsignedNodeAnnouncement *NONNULL_PTR this_ptr))[32];
 
 /**
  * An alias, for UI purposes.  This should be sanitized before use.  There is no guarantee
  * of uniqueness.
  */
-void UnsignedNodeAnnouncement_set_alias(LDKUnsignedNodeAnnouncement *this_ptr, LDKThirtyTwoBytes val);
+void UnsignedNodeAnnouncement_set_alias(struct LDKUnsignedNodeAnnouncement *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
 
 /**
  * List of addresses on which this node is reachable
  */
-void UnsignedNodeAnnouncement_set_addresses(LDKUnsignedNodeAnnouncement *this_ptr, LDKCVec_NetAddressZ val);
+void UnsignedNodeAnnouncement_set_addresses(struct LDKUnsignedNodeAnnouncement *NONNULL_PTR this_ptr, struct LDKCVec_NetAddressZ val);
 
-void NodeAnnouncement_free(LDKNodeAnnouncement this_ptr);
+struct LDKUnsignedNodeAnnouncement UnsignedNodeAnnouncement_clone(const struct LDKUnsignedNodeAnnouncement *NONNULL_PTR orig);
 
-LDKNodeAnnouncement NodeAnnouncement_clone(const LDKNodeAnnouncement *orig);
+void NodeAnnouncement_free(struct LDKNodeAnnouncement this_ptr);
 
 /**
  * The signature by the node key
  */
-LDKSignature NodeAnnouncement_get_signature(const LDKNodeAnnouncement *this_ptr);
+struct LDKSignature NodeAnnouncement_get_signature(const struct LDKNodeAnnouncement *NONNULL_PTR this_ptr);
 
 /**
  * The signature by the node key
  */
-void NodeAnnouncement_set_signature(LDKNodeAnnouncement *this_ptr, LDKSignature val);
+void NodeAnnouncement_set_signature(struct LDKNodeAnnouncement *NONNULL_PTR this_ptr, struct LDKSignature val);
 
 /**
  * The actual content of the announcement
  */
-LDKUnsignedNodeAnnouncement NodeAnnouncement_get_contents(const LDKNodeAnnouncement *this_ptr);
+struct LDKUnsignedNodeAnnouncement NodeAnnouncement_get_contents(const struct LDKNodeAnnouncement *NONNULL_PTR this_ptr);
 
 /**
  * The actual content of the announcement
  */
-void NodeAnnouncement_set_contents(LDKNodeAnnouncement *this_ptr, LDKUnsignedNodeAnnouncement val);
+void NodeAnnouncement_set_contents(struct LDKNodeAnnouncement *NONNULL_PTR this_ptr, struct LDKUnsignedNodeAnnouncement val);
 
-MUST_USE_RES LDKNodeAnnouncement NodeAnnouncement_new(LDKSignature signature_arg, LDKUnsignedNodeAnnouncement contents_arg);
+MUST_USE_RES struct LDKNodeAnnouncement NodeAnnouncement_new(struct LDKSignature signature_arg, struct LDKUnsignedNodeAnnouncement contents_arg);
 
-void UnsignedChannelAnnouncement_free(LDKUnsignedChannelAnnouncement this_ptr);
+struct LDKNodeAnnouncement NodeAnnouncement_clone(const struct LDKNodeAnnouncement *NONNULL_PTR orig);
 
-LDKUnsignedChannelAnnouncement UnsignedChannelAnnouncement_clone(const LDKUnsignedChannelAnnouncement *orig);
+void UnsignedChannelAnnouncement_free(struct LDKUnsignedChannelAnnouncement this_ptr);
 
 /**
  * The advertised channel features
  */
-LDKChannelFeatures UnsignedChannelAnnouncement_get_features(const LDKUnsignedChannelAnnouncement *this_ptr);
+struct LDKChannelFeatures UnsignedChannelAnnouncement_get_features(const struct LDKUnsignedChannelAnnouncement *NONNULL_PTR this_ptr);
 
 /**
  * The advertised channel features
  */
-void UnsignedChannelAnnouncement_set_features(LDKUnsignedChannelAnnouncement *this_ptr, LDKChannelFeatures val);
+void UnsignedChannelAnnouncement_set_features(struct LDKUnsignedChannelAnnouncement *NONNULL_PTR this_ptr, struct LDKChannelFeatures val);
 
 /**
  * The genesis hash of the blockchain where the channel is to be opened
  */
-const uint8_t (*UnsignedChannelAnnouncement_get_chain_hash(const LDKUnsignedChannelAnnouncement *this_ptr))[32];
+const uint8_t (*UnsignedChannelAnnouncement_get_chain_hash(const struct LDKUnsignedChannelAnnouncement *NONNULL_PTR this_ptr))[32];
 
 /**
  * The genesis hash of the blockchain where the channel is to be opened
  */
-void UnsignedChannelAnnouncement_set_chain_hash(LDKUnsignedChannelAnnouncement *this_ptr, LDKThirtyTwoBytes val);
+void UnsignedChannelAnnouncement_set_chain_hash(struct LDKUnsignedChannelAnnouncement *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
 
 /**
  * The short channel ID
  */
-uint64_t UnsignedChannelAnnouncement_get_short_channel_id(const LDKUnsignedChannelAnnouncement *this_ptr);
+uint64_t UnsignedChannelAnnouncement_get_short_channel_id(const struct LDKUnsignedChannelAnnouncement *NONNULL_PTR this_ptr);
 
 /**
  * The short channel ID
  */
-void UnsignedChannelAnnouncement_set_short_channel_id(LDKUnsignedChannelAnnouncement *this_ptr, uint64_t val);
+void UnsignedChannelAnnouncement_set_short_channel_id(struct LDKUnsignedChannelAnnouncement *NONNULL_PTR this_ptr, uint64_t val);
 
 /**
  * One of the two node_ids which are endpoints of this channel
  */
-LDKPublicKey UnsignedChannelAnnouncement_get_node_id_1(const LDKUnsignedChannelAnnouncement *this_ptr);
+struct LDKPublicKey UnsignedChannelAnnouncement_get_node_id_1(const struct LDKUnsignedChannelAnnouncement *NONNULL_PTR this_ptr);
 
 /**
  * One of the two node_ids which are endpoints of this channel
  */
-void UnsignedChannelAnnouncement_set_node_id_1(LDKUnsignedChannelAnnouncement *this_ptr, LDKPublicKey val);
+void UnsignedChannelAnnouncement_set_node_id_1(struct LDKUnsignedChannelAnnouncement *NONNULL_PTR this_ptr, struct LDKPublicKey val);
 
 /**
  * The other of the two node_ids which are endpoints of this channel
  */
-LDKPublicKey UnsignedChannelAnnouncement_get_node_id_2(const LDKUnsignedChannelAnnouncement *this_ptr);
+struct LDKPublicKey UnsignedChannelAnnouncement_get_node_id_2(const struct LDKUnsignedChannelAnnouncement *NONNULL_PTR this_ptr);
 
 /**
  * The other of the two node_ids which are endpoints of this channel
  */
-void UnsignedChannelAnnouncement_set_node_id_2(LDKUnsignedChannelAnnouncement *this_ptr, LDKPublicKey val);
+void UnsignedChannelAnnouncement_set_node_id_2(struct LDKUnsignedChannelAnnouncement *NONNULL_PTR this_ptr, struct LDKPublicKey val);
 
 /**
  * The funding key for the first node
  */
-LDKPublicKey UnsignedChannelAnnouncement_get_bitcoin_key_1(const LDKUnsignedChannelAnnouncement *this_ptr);
+struct LDKPublicKey UnsignedChannelAnnouncement_get_bitcoin_key_1(const struct LDKUnsignedChannelAnnouncement *NONNULL_PTR this_ptr);
 
 /**
  * The funding key for the first node
  */
-void UnsignedChannelAnnouncement_set_bitcoin_key_1(LDKUnsignedChannelAnnouncement *this_ptr, LDKPublicKey val);
+void UnsignedChannelAnnouncement_set_bitcoin_key_1(struct LDKUnsignedChannelAnnouncement *NONNULL_PTR this_ptr, struct LDKPublicKey val);
 
 /**
  * The funding key for the second node
  */
-LDKPublicKey UnsignedChannelAnnouncement_get_bitcoin_key_2(const LDKUnsignedChannelAnnouncement *this_ptr);
+struct LDKPublicKey UnsignedChannelAnnouncement_get_bitcoin_key_2(const struct LDKUnsignedChannelAnnouncement *NONNULL_PTR this_ptr);
 
 /**
  * The funding key for the second node
  */
-void UnsignedChannelAnnouncement_set_bitcoin_key_2(LDKUnsignedChannelAnnouncement *this_ptr, LDKPublicKey val);
+void UnsignedChannelAnnouncement_set_bitcoin_key_2(struct LDKUnsignedChannelAnnouncement *NONNULL_PTR this_ptr, struct LDKPublicKey val);
 
-void ChannelAnnouncement_free(LDKChannelAnnouncement this_ptr);
+struct LDKUnsignedChannelAnnouncement UnsignedChannelAnnouncement_clone(const struct LDKUnsignedChannelAnnouncement *NONNULL_PTR orig);
 
-LDKChannelAnnouncement ChannelAnnouncement_clone(const LDKChannelAnnouncement *orig);
+void ChannelAnnouncement_free(struct LDKChannelAnnouncement this_ptr);
 
 /**
  * Authentication of the announcement by the first public node
  */
-LDKSignature ChannelAnnouncement_get_node_signature_1(const LDKChannelAnnouncement *this_ptr);
+struct LDKSignature ChannelAnnouncement_get_node_signature_1(const struct LDKChannelAnnouncement *NONNULL_PTR this_ptr);
 
 /**
  * Authentication of the announcement by the first public node
  */
-void ChannelAnnouncement_set_node_signature_1(LDKChannelAnnouncement *this_ptr, LDKSignature val);
+void ChannelAnnouncement_set_node_signature_1(struct LDKChannelAnnouncement *NONNULL_PTR this_ptr, struct LDKSignature val);
 
 /**
  * Authentication of the announcement by the second public node
  */
-LDKSignature ChannelAnnouncement_get_node_signature_2(const LDKChannelAnnouncement *this_ptr);
+struct LDKSignature ChannelAnnouncement_get_node_signature_2(const struct LDKChannelAnnouncement *NONNULL_PTR this_ptr);
 
 /**
  * Authentication of the announcement by the second public node
  */
-void ChannelAnnouncement_set_node_signature_2(LDKChannelAnnouncement *this_ptr, LDKSignature val);
+void ChannelAnnouncement_set_node_signature_2(struct LDKChannelAnnouncement *NONNULL_PTR this_ptr, struct LDKSignature val);
 
 /**
  * Proof of funding UTXO ownership by the first public node
  */
-LDKSignature ChannelAnnouncement_get_bitcoin_signature_1(const LDKChannelAnnouncement *this_ptr);
+struct LDKSignature ChannelAnnouncement_get_bitcoin_signature_1(const struct LDKChannelAnnouncement *NONNULL_PTR this_ptr);
 
 /**
  * Proof of funding UTXO ownership by the first public node
  */
-void ChannelAnnouncement_set_bitcoin_signature_1(LDKChannelAnnouncement *this_ptr, LDKSignature val);
+void ChannelAnnouncement_set_bitcoin_signature_1(struct LDKChannelAnnouncement *NONNULL_PTR this_ptr, struct LDKSignature val);
 
 /**
  * Proof of funding UTXO ownership by the second public node
  */
-LDKSignature ChannelAnnouncement_get_bitcoin_signature_2(const LDKChannelAnnouncement *this_ptr);
+struct LDKSignature ChannelAnnouncement_get_bitcoin_signature_2(const struct LDKChannelAnnouncement *NONNULL_PTR this_ptr);
 
 /**
  * Proof of funding UTXO ownership by the second public node
  */
-void ChannelAnnouncement_set_bitcoin_signature_2(LDKChannelAnnouncement *this_ptr, LDKSignature val);
+void ChannelAnnouncement_set_bitcoin_signature_2(struct LDKChannelAnnouncement *NONNULL_PTR this_ptr, struct LDKSignature val);
 
 /**
  * The actual announcement
  */
-LDKUnsignedChannelAnnouncement ChannelAnnouncement_get_contents(const LDKChannelAnnouncement *this_ptr);
+struct LDKUnsignedChannelAnnouncement ChannelAnnouncement_get_contents(const struct LDKChannelAnnouncement *NONNULL_PTR this_ptr);
 
 /**
  * The actual announcement
  */
-void ChannelAnnouncement_set_contents(LDKChannelAnnouncement *this_ptr, LDKUnsignedChannelAnnouncement val);
+void ChannelAnnouncement_set_contents(struct LDKChannelAnnouncement *NONNULL_PTR this_ptr, struct LDKUnsignedChannelAnnouncement val);
 
-MUST_USE_RES LDKChannelAnnouncement ChannelAnnouncement_new(LDKSignature node_signature_1_arg, LDKSignature node_signature_2_arg, LDKSignature bitcoin_signature_1_arg, LDKSignature bitcoin_signature_2_arg, LDKUnsignedChannelAnnouncement contents_arg);
+MUST_USE_RES struct LDKChannelAnnouncement ChannelAnnouncement_new(struct LDKSignature node_signature_1_arg, struct LDKSignature node_signature_2_arg, struct LDKSignature bitcoin_signature_1_arg, struct LDKSignature bitcoin_signature_2_arg, struct LDKUnsignedChannelAnnouncement contents_arg);
 
-void UnsignedChannelUpdate_free(LDKUnsignedChannelUpdate this_ptr);
+struct LDKChannelAnnouncement ChannelAnnouncement_clone(const struct LDKChannelAnnouncement *NONNULL_PTR orig);
 
-LDKUnsignedChannelUpdate UnsignedChannelUpdate_clone(const LDKUnsignedChannelUpdate *orig);
+void UnsignedChannelUpdate_free(struct LDKUnsignedChannelUpdate this_ptr);
 
 /**
  * The genesis hash of the blockchain where the channel is to be opened
  */
-const uint8_t (*UnsignedChannelUpdate_get_chain_hash(const LDKUnsignedChannelUpdate *this_ptr))[32];
+const uint8_t (*UnsignedChannelUpdate_get_chain_hash(const struct LDKUnsignedChannelUpdate *NONNULL_PTR this_ptr))[32];
 
 /**
  * The genesis hash of the blockchain where the channel is to be opened
  */
-void UnsignedChannelUpdate_set_chain_hash(LDKUnsignedChannelUpdate *this_ptr, LDKThirtyTwoBytes val);
+void UnsignedChannelUpdate_set_chain_hash(struct LDKUnsignedChannelUpdate *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
 
 /**
  * The short channel ID
  */
-uint64_t UnsignedChannelUpdate_get_short_channel_id(const LDKUnsignedChannelUpdate *this_ptr);
+uint64_t UnsignedChannelUpdate_get_short_channel_id(const struct LDKUnsignedChannelUpdate *NONNULL_PTR this_ptr);
 
 /**
  * The short channel ID
  */
-void UnsignedChannelUpdate_set_short_channel_id(LDKUnsignedChannelUpdate *this_ptr, uint64_t val);
+void UnsignedChannelUpdate_set_short_channel_id(struct LDKUnsignedChannelUpdate *NONNULL_PTR this_ptr, uint64_t val);
 
 /**
  * A strictly monotonic announcement counter, with gaps allowed, specific to this channel
  */
-uint32_t UnsignedChannelUpdate_get_timestamp(const LDKUnsignedChannelUpdate *this_ptr);
+uint32_t UnsignedChannelUpdate_get_timestamp(const struct LDKUnsignedChannelUpdate *NONNULL_PTR this_ptr);
 
 /**
  * A strictly monotonic announcement counter, with gaps allowed, specific to this channel
  */
-void UnsignedChannelUpdate_set_timestamp(LDKUnsignedChannelUpdate *this_ptr, uint32_t val);
+void UnsignedChannelUpdate_set_timestamp(struct LDKUnsignedChannelUpdate *NONNULL_PTR this_ptr, uint32_t val);
 
 /**
  * Channel flags
  */
-uint8_t UnsignedChannelUpdate_get_flags(const LDKUnsignedChannelUpdate *this_ptr);
+uint8_t UnsignedChannelUpdate_get_flags(const struct LDKUnsignedChannelUpdate *NONNULL_PTR this_ptr);
 
 /**
  * Channel flags
  */
-void UnsignedChannelUpdate_set_flags(LDKUnsignedChannelUpdate *this_ptr, uint8_t val);
+void UnsignedChannelUpdate_set_flags(struct LDKUnsignedChannelUpdate *NONNULL_PTR this_ptr, uint8_t val);
 
 /**
  * The number of blocks to subtract from incoming HTLC cltv_expiry values
  */
-uint16_t UnsignedChannelUpdate_get_cltv_expiry_delta(const LDKUnsignedChannelUpdate *this_ptr);
+uint16_t UnsignedChannelUpdate_get_cltv_expiry_delta(const struct LDKUnsignedChannelUpdate *NONNULL_PTR this_ptr);
 
 /**
  * The number of blocks to subtract from incoming HTLC cltv_expiry values
  */
-void UnsignedChannelUpdate_set_cltv_expiry_delta(LDKUnsignedChannelUpdate *this_ptr, uint16_t val);
+void UnsignedChannelUpdate_set_cltv_expiry_delta(struct LDKUnsignedChannelUpdate *NONNULL_PTR this_ptr, uint16_t val);
 
 /**
  * The minimum HTLC size incoming to sender, in milli-satoshi
  */
-uint64_t UnsignedChannelUpdate_get_htlc_minimum_msat(const LDKUnsignedChannelUpdate *this_ptr);
+uint64_t UnsignedChannelUpdate_get_htlc_minimum_msat(const struct LDKUnsignedChannelUpdate *NONNULL_PTR this_ptr);
 
 /**
  * The minimum HTLC size incoming to sender, in milli-satoshi
  */
-void UnsignedChannelUpdate_set_htlc_minimum_msat(LDKUnsignedChannelUpdate *this_ptr, uint64_t val);
+void UnsignedChannelUpdate_set_htlc_minimum_msat(struct LDKUnsignedChannelUpdate *NONNULL_PTR this_ptr, uint64_t val);
 
 /**
  * The base HTLC fee charged by sender, in milli-satoshi
  */
-uint32_t UnsignedChannelUpdate_get_fee_base_msat(const LDKUnsignedChannelUpdate *this_ptr);
+uint32_t UnsignedChannelUpdate_get_fee_base_msat(const struct LDKUnsignedChannelUpdate *NONNULL_PTR this_ptr);
 
 /**
  * The base HTLC fee charged by sender, in milli-satoshi
  */
-void UnsignedChannelUpdate_set_fee_base_msat(LDKUnsignedChannelUpdate *this_ptr, uint32_t val);
+void UnsignedChannelUpdate_set_fee_base_msat(struct LDKUnsignedChannelUpdate *NONNULL_PTR this_ptr, uint32_t val);
 
 /**
  * The amount to fee multiplier, in micro-satoshi
  */
-uint32_t UnsignedChannelUpdate_get_fee_proportional_millionths(const LDKUnsignedChannelUpdate *this_ptr);
+uint32_t UnsignedChannelUpdate_get_fee_proportional_millionths(const struct LDKUnsignedChannelUpdate *NONNULL_PTR this_ptr);
 
 /**
  * The amount to fee multiplier, in micro-satoshi
  */
-void UnsignedChannelUpdate_set_fee_proportional_millionths(LDKUnsignedChannelUpdate *this_ptr, uint32_t val);
+void UnsignedChannelUpdate_set_fee_proportional_millionths(struct LDKUnsignedChannelUpdate *NONNULL_PTR this_ptr, uint32_t val);
 
-void ChannelUpdate_free(LDKChannelUpdate this_ptr);
+struct LDKUnsignedChannelUpdate UnsignedChannelUpdate_clone(const struct LDKUnsignedChannelUpdate *NONNULL_PTR orig);
 
-LDKChannelUpdate ChannelUpdate_clone(const LDKChannelUpdate *orig);
+void ChannelUpdate_free(struct LDKChannelUpdate this_ptr);
 
 /**
  * A signature of the channel update
  */
-LDKSignature ChannelUpdate_get_signature(const LDKChannelUpdate *this_ptr);
+struct LDKSignature ChannelUpdate_get_signature(const struct LDKChannelUpdate *NONNULL_PTR this_ptr);
 
 /**
  * A signature of the channel update
  */
-void ChannelUpdate_set_signature(LDKChannelUpdate *this_ptr, LDKSignature val);
+void ChannelUpdate_set_signature(struct LDKChannelUpdate *NONNULL_PTR this_ptr, struct LDKSignature val);
 
 /**
  * The actual channel update
  */
-LDKUnsignedChannelUpdate ChannelUpdate_get_contents(const LDKChannelUpdate *this_ptr);
+struct LDKUnsignedChannelUpdate ChannelUpdate_get_contents(const struct LDKChannelUpdate *NONNULL_PTR this_ptr);
 
 /**
  * The actual channel update
  */
-void ChannelUpdate_set_contents(LDKChannelUpdate *this_ptr, LDKUnsignedChannelUpdate val);
+void ChannelUpdate_set_contents(struct LDKChannelUpdate *NONNULL_PTR this_ptr, struct LDKUnsignedChannelUpdate val);
 
-MUST_USE_RES LDKChannelUpdate ChannelUpdate_new(LDKSignature signature_arg, LDKUnsignedChannelUpdate contents_arg);
+MUST_USE_RES struct LDKChannelUpdate ChannelUpdate_new(struct LDKSignature signature_arg, struct LDKUnsignedChannelUpdate contents_arg);
 
-void QueryChannelRange_free(LDKQueryChannelRange this_ptr);
+struct LDKChannelUpdate ChannelUpdate_clone(const struct LDKChannelUpdate *NONNULL_PTR orig);
 
-LDKQueryChannelRange QueryChannelRange_clone(const LDKQueryChannelRange *orig);
+void QueryChannelRange_free(struct LDKQueryChannelRange this_ptr);
 
 /**
  * The genesis hash of the blockchain being queried
  */
-const uint8_t (*QueryChannelRange_get_chain_hash(const LDKQueryChannelRange *this_ptr))[32];
+const uint8_t (*QueryChannelRange_get_chain_hash(const struct LDKQueryChannelRange *NONNULL_PTR this_ptr))[32];
 
 /**
  * The genesis hash of the blockchain being queried
  */
-void QueryChannelRange_set_chain_hash(LDKQueryChannelRange *this_ptr, LDKThirtyTwoBytes val);
+void QueryChannelRange_set_chain_hash(struct LDKQueryChannelRange *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
 
 /**
  * The height of the first block for the channel UTXOs being queried
  */
-uint32_t QueryChannelRange_get_first_blocknum(const LDKQueryChannelRange *this_ptr);
+uint32_t QueryChannelRange_get_first_blocknum(const struct LDKQueryChannelRange *NONNULL_PTR this_ptr);
 
 /**
  * The height of the first block for the channel UTXOs being queried
  */
-void QueryChannelRange_set_first_blocknum(LDKQueryChannelRange *this_ptr, uint32_t val);
+void QueryChannelRange_set_first_blocknum(struct LDKQueryChannelRange *NONNULL_PTR this_ptr, uint32_t val);
 
 /**
  * The number of blocks to include in the query results
  */
-uint32_t QueryChannelRange_get_number_of_blocks(const LDKQueryChannelRange *this_ptr);
+uint32_t QueryChannelRange_get_number_of_blocks(const struct LDKQueryChannelRange *NONNULL_PTR this_ptr);
 
 /**
  * The number of blocks to include in the query results
  */
-void QueryChannelRange_set_number_of_blocks(LDKQueryChannelRange *this_ptr, uint32_t val);
+void QueryChannelRange_set_number_of_blocks(struct LDKQueryChannelRange *NONNULL_PTR this_ptr, uint32_t val);
 
-MUST_USE_RES LDKQueryChannelRange QueryChannelRange_new(LDKThirtyTwoBytes chain_hash_arg, uint32_t first_blocknum_arg, uint32_t number_of_blocks_arg);
+MUST_USE_RES struct LDKQueryChannelRange QueryChannelRange_new(struct LDKThirtyTwoBytes chain_hash_arg, uint32_t first_blocknum_arg, uint32_t number_of_blocks_arg);
 
-void ReplyChannelRange_free(LDKReplyChannelRange this_ptr);
+struct LDKQueryChannelRange QueryChannelRange_clone(const struct LDKQueryChannelRange *NONNULL_PTR orig);
 
-LDKReplyChannelRange ReplyChannelRange_clone(const LDKReplyChannelRange *orig);
+void ReplyChannelRange_free(struct LDKReplyChannelRange this_ptr);
 
 /**
  * The genesis hash of the blockchain being queried
  */
-const uint8_t (*ReplyChannelRange_get_chain_hash(const LDKReplyChannelRange *this_ptr))[32];
+const uint8_t (*ReplyChannelRange_get_chain_hash(const struct LDKReplyChannelRange *NONNULL_PTR this_ptr))[32];
 
 /**
  * The genesis hash of the blockchain being queried
  */
-void ReplyChannelRange_set_chain_hash(LDKReplyChannelRange *this_ptr, LDKThirtyTwoBytes val);
+void ReplyChannelRange_set_chain_hash(struct LDKReplyChannelRange *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
 
 /**
  * The height of the first block in the range of the reply
  */
-uint32_t ReplyChannelRange_get_first_blocknum(const LDKReplyChannelRange *this_ptr);
+uint32_t ReplyChannelRange_get_first_blocknum(const struct LDKReplyChannelRange *NONNULL_PTR this_ptr);
 
 /**
  * The height of the first block in the range of the reply
  */
-void ReplyChannelRange_set_first_blocknum(LDKReplyChannelRange *this_ptr, uint32_t val);
+void ReplyChannelRange_set_first_blocknum(struct LDKReplyChannelRange *NONNULL_PTR this_ptr, uint32_t val);
 
 /**
  * The number of blocks included in the range of the reply
  */
-uint32_t ReplyChannelRange_get_number_of_blocks(const LDKReplyChannelRange *this_ptr);
+uint32_t ReplyChannelRange_get_number_of_blocks(const struct LDKReplyChannelRange *NONNULL_PTR this_ptr);
 
 /**
  * The number of blocks included in the range of the reply
  */
-void ReplyChannelRange_set_number_of_blocks(LDKReplyChannelRange *this_ptr, uint32_t val);
+void ReplyChannelRange_set_number_of_blocks(struct LDKReplyChannelRange *NONNULL_PTR this_ptr, uint32_t val);
 
 /**
- * Indicates if the query recipient maintains up-to-date channel
- * information for the chain_hash
+ * True when this is the final reply for a query
  */
-bool ReplyChannelRange_get_full_information(const LDKReplyChannelRange *this_ptr);
+bool ReplyChannelRange_get_sync_complete(const struct LDKReplyChannelRange *NONNULL_PTR this_ptr);
 
 /**
- * Indicates if the query recipient maintains up-to-date channel
- * information for the chain_hash
+ * True when this is the final reply for a query
  */
-void ReplyChannelRange_set_full_information(LDKReplyChannelRange *this_ptr, bool val);
+void ReplyChannelRange_set_sync_complete(struct LDKReplyChannelRange *NONNULL_PTR this_ptr, bool val);
 
 /**
  * The short_channel_ids in the channel range
  */
-void ReplyChannelRange_set_short_channel_ids(LDKReplyChannelRange *this_ptr, LDKCVec_u64Z val);
+void ReplyChannelRange_set_short_channel_ids(struct LDKReplyChannelRange *NONNULL_PTR this_ptr, struct LDKCVec_u64Z val);
 
-MUST_USE_RES LDKReplyChannelRange ReplyChannelRange_new(LDKThirtyTwoBytes chain_hash_arg, uint32_t first_blocknum_arg, uint32_t number_of_blocks_arg, bool full_information_arg, LDKCVec_u64Z short_channel_ids_arg);
+MUST_USE_RES struct LDKReplyChannelRange ReplyChannelRange_new(struct LDKThirtyTwoBytes chain_hash_arg, uint32_t first_blocknum_arg, uint32_t number_of_blocks_arg, bool sync_complete_arg, struct LDKCVec_u64Z short_channel_ids_arg);
 
-void QueryShortChannelIds_free(LDKQueryShortChannelIds this_ptr);
+struct LDKReplyChannelRange ReplyChannelRange_clone(const struct LDKReplyChannelRange *NONNULL_PTR orig);
 
-LDKQueryShortChannelIds QueryShortChannelIds_clone(const LDKQueryShortChannelIds *orig);
+void QueryShortChannelIds_free(struct LDKQueryShortChannelIds this_ptr);
 
 /**
  * The genesis hash of the blockchain being queried
  */
-const uint8_t (*QueryShortChannelIds_get_chain_hash(const LDKQueryShortChannelIds *this_ptr))[32];
+const uint8_t (*QueryShortChannelIds_get_chain_hash(const struct LDKQueryShortChannelIds *NONNULL_PTR this_ptr))[32];
 
 /**
  * The genesis hash of the blockchain being queried
  */
-void QueryShortChannelIds_set_chain_hash(LDKQueryShortChannelIds *this_ptr, LDKThirtyTwoBytes val);
+void QueryShortChannelIds_set_chain_hash(struct LDKQueryShortChannelIds *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
 
 /**
  * The short_channel_ids that are being queried
  */
-void QueryShortChannelIds_set_short_channel_ids(LDKQueryShortChannelIds *this_ptr, LDKCVec_u64Z val);
+void QueryShortChannelIds_set_short_channel_ids(struct LDKQueryShortChannelIds *NONNULL_PTR this_ptr, struct LDKCVec_u64Z val);
 
-MUST_USE_RES LDKQueryShortChannelIds QueryShortChannelIds_new(LDKThirtyTwoBytes chain_hash_arg, LDKCVec_u64Z short_channel_ids_arg);
+MUST_USE_RES struct LDKQueryShortChannelIds QueryShortChannelIds_new(struct LDKThirtyTwoBytes chain_hash_arg, struct LDKCVec_u64Z short_channel_ids_arg);
 
-void ReplyShortChannelIdsEnd_free(LDKReplyShortChannelIdsEnd this_ptr);
+struct LDKQueryShortChannelIds QueryShortChannelIds_clone(const struct LDKQueryShortChannelIds *NONNULL_PTR orig);
 
-LDKReplyShortChannelIdsEnd ReplyShortChannelIdsEnd_clone(const LDKReplyShortChannelIdsEnd *orig);
+void ReplyShortChannelIdsEnd_free(struct LDKReplyShortChannelIdsEnd this_ptr);
 
 /**
  * The genesis hash of the blockchain that was queried
  */
-const uint8_t (*ReplyShortChannelIdsEnd_get_chain_hash(const LDKReplyShortChannelIdsEnd *this_ptr))[32];
+const uint8_t (*ReplyShortChannelIdsEnd_get_chain_hash(const struct LDKReplyShortChannelIdsEnd *NONNULL_PTR this_ptr))[32];
 
 /**
  * The genesis hash of the blockchain that was queried
  */
-void ReplyShortChannelIdsEnd_set_chain_hash(LDKReplyShortChannelIdsEnd *this_ptr, LDKThirtyTwoBytes val);
+void ReplyShortChannelIdsEnd_set_chain_hash(struct LDKReplyShortChannelIdsEnd *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
 
 /**
  * Indicates if the query recipient maintains up-to-date channel
  * information for the chain_hash
  */
-bool ReplyShortChannelIdsEnd_get_full_information(const LDKReplyShortChannelIdsEnd *this_ptr);
+bool ReplyShortChannelIdsEnd_get_full_information(const struct LDKReplyShortChannelIdsEnd *NONNULL_PTR this_ptr);
 
 /**
  * Indicates if the query recipient maintains up-to-date channel
  * information for the chain_hash
  */
-void ReplyShortChannelIdsEnd_set_full_information(LDKReplyShortChannelIdsEnd *this_ptr, bool val);
+void ReplyShortChannelIdsEnd_set_full_information(struct LDKReplyShortChannelIdsEnd *NONNULL_PTR this_ptr, bool val);
 
-MUST_USE_RES LDKReplyShortChannelIdsEnd ReplyShortChannelIdsEnd_new(LDKThirtyTwoBytes chain_hash_arg, bool full_information_arg);
+MUST_USE_RES struct LDKReplyShortChannelIdsEnd ReplyShortChannelIdsEnd_new(struct LDKThirtyTwoBytes chain_hash_arg, bool full_information_arg);
 
-void GossipTimestampFilter_free(LDKGossipTimestampFilter this_ptr);
+struct LDKReplyShortChannelIdsEnd ReplyShortChannelIdsEnd_clone(const struct LDKReplyShortChannelIdsEnd *NONNULL_PTR orig);
 
-LDKGossipTimestampFilter GossipTimestampFilter_clone(const LDKGossipTimestampFilter *orig);
+void GossipTimestampFilter_free(struct LDKGossipTimestampFilter this_ptr);
 
 /**
  * The genesis hash of the blockchain for channel and node information
  */
-const uint8_t (*GossipTimestampFilter_get_chain_hash(const LDKGossipTimestampFilter *this_ptr))[32];
+const uint8_t (*GossipTimestampFilter_get_chain_hash(const struct LDKGossipTimestampFilter *NONNULL_PTR this_ptr))[32];
 
 /**
  * The genesis hash of the blockchain for channel and node information
  */
-void GossipTimestampFilter_set_chain_hash(LDKGossipTimestampFilter *this_ptr, LDKThirtyTwoBytes val);
+void GossipTimestampFilter_set_chain_hash(struct LDKGossipTimestampFilter *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
 
 /**
  * The starting unix timestamp
  */
-uint32_t GossipTimestampFilter_get_first_timestamp(const LDKGossipTimestampFilter *this_ptr);
+uint32_t GossipTimestampFilter_get_first_timestamp(const struct LDKGossipTimestampFilter *NONNULL_PTR this_ptr);
 
 /**
  * The starting unix timestamp
  */
-void GossipTimestampFilter_set_first_timestamp(LDKGossipTimestampFilter *this_ptr, uint32_t val);
+void GossipTimestampFilter_set_first_timestamp(struct LDKGossipTimestampFilter *NONNULL_PTR this_ptr, uint32_t val);
 
 /**
  * The range of information in seconds
  */
-uint32_t GossipTimestampFilter_get_timestamp_range(const LDKGossipTimestampFilter *this_ptr);
+uint32_t GossipTimestampFilter_get_timestamp_range(const struct LDKGossipTimestampFilter *NONNULL_PTR this_ptr);
 
 /**
  * The range of information in seconds
  */
-void GossipTimestampFilter_set_timestamp_range(LDKGossipTimestampFilter *this_ptr, uint32_t val);
+void GossipTimestampFilter_set_timestamp_range(struct LDKGossipTimestampFilter *NONNULL_PTR this_ptr, uint32_t val);
+
+MUST_USE_RES struct LDKGossipTimestampFilter GossipTimestampFilter_new(struct LDKThirtyTwoBytes chain_hash_arg, uint32_t first_timestamp_arg, uint32_t timestamp_range_arg);
 
-MUST_USE_RES LDKGossipTimestampFilter GossipTimestampFilter_new(LDKThirtyTwoBytes chain_hash_arg, uint32_t first_timestamp_arg, uint32_t timestamp_range_arg);
+struct LDKGossipTimestampFilter GossipTimestampFilter_clone(const struct LDKGossipTimestampFilter *NONNULL_PTR orig);
 
-void ErrorAction_free(LDKErrorAction this_ptr);
+void ErrorAction_free(struct LDKErrorAction this_ptr);
 
-LDKErrorAction ErrorAction_clone(const LDKErrorAction *orig);
+struct LDKErrorAction ErrorAction_clone(const struct LDKErrorAction *NONNULL_PTR orig);
 
-void LightningError_free(LDKLightningError this_ptr);
+void LightningError_free(struct LDKLightningError this_ptr);
 
 /**
  * A human-readable message describing the error
  */
-LDKStr LightningError_get_err(const LDKLightningError *this_ptr);
+struct LDKStr LightningError_get_err(const struct LDKLightningError *NONNULL_PTR this_ptr);
 
 /**
  * A human-readable message describing the error
  */
-void LightningError_set_err(LDKLightningError *this_ptr, LDKCVec_u8Z val);
+void LightningError_set_err(struct LDKLightningError *NONNULL_PTR this_ptr, struct LDKCVec_u8Z val);
 
 /**
  * The action which should be taken against the offending peer.
  */
-LDKErrorAction LightningError_get_action(const LDKLightningError *this_ptr);
+struct LDKErrorAction LightningError_get_action(const struct LDKLightningError *NONNULL_PTR this_ptr);
 
 /**
  * The action which should be taken against the offending peer.
  */
-void LightningError_set_action(LDKLightningError *this_ptr, LDKErrorAction val);
+void LightningError_set_action(struct LDKLightningError *NONNULL_PTR this_ptr, struct LDKErrorAction val);
 
-MUST_USE_RES LDKLightningError LightningError_new(LDKCVec_u8Z err_arg, LDKErrorAction action_arg);
+MUST_USE_RES struct LDKLightningError LightningError_new(struct LDKCVec_u8Z err_arg, struct LDKErrorAction action_arg);
 
-void CommitmentUpdate_free(LDKCommitmentUpdate this_ptr);
+struct LDKLightningError LightningError_clone(const struct LDKLightningError *NONNULL_PTR orig);
 
-LDKCommitmentUpdate CommitmentUpdate_clone(const LDKCommitmentUpdate *orig);
+void CommitmentUpdate_free(struct LDKCommitmentUpdate this_ptr);
 
 /**
  * update_add_htlc messages which should be sent
  */
-void CommitmentUpdate_set_update_add_htlcs(LDKCommitmentUpdate *this_ptr, LDKCVec_UpdateAddHTLCZ val);
+void CommitmentUpdate_set_update_add_htlcs(struct LDKCommitmentUpdate *NONNULL_PTR this_ptr, struct LDKCVec_UpdateAddHTLCZ val);
 
 /**
  * update_fulfill_htlc messages which should be sent
  */
-void CommitmentUpdate_set_update_fulfill_htlcs(LDKCommitmentUpdate *this_ptr, LDKCVec_UpdateFulfillHTLCZ val);
+void CommitmentUpdate_set_update_fulfill_htlcs(struct LDKCommitmentUpdate *NONNULL_PTR this_ptr, struct LDKCVec_UpdateFulfillHTLCZ val);
 
 /**
  * update_fail_htlc messages which should be sent
  */
-void CommitmentUpdate_set_update_fail_htlcs(LDKCommitmentUpdate *this_ptr, LDKCVec_UpdateFailHTLCZ val);
+void CommitmentUpdate_set_update_fail_htlcs(struct LDKCommitmentUpdate *NONNULL_PTR this_ptr, struct LDKCVec_UpdateFailHTLCZ val);
 
 /**
  * update_fail_malformed_htlc messages which should be sent
  */
-void CommitmentUpdate_set_update_fail_malformed_htlcs(LDKCommitmentUpdate *this_ptr, LDKCVec_UpdateFailMalformedHTLCZ val);
+void CommitmentUpdate_set_update_fail_malformed_htlcs(struct LDKCommitmentUpdate *NONNULL_PTR this_ptr, struct LDKCVec_UpdateFailMalformedHTLCZ val);
 
 /**
  * An update_fee message which should be sent
  */
-LDKUpdateFee CommitmentUpdate_get_update_fee(const LDKCommitmentUpdate *this_ptr);
+struct LDKUpdateFee CommitmentUpdate_get_update_fee(const struct LDKCommitmentUpdate *NONNULL_PTR this_ptr);
 
 /**
  * An update_fee message which should be sent
  */
-void CommitmentUpdate_set_update_fee(LDKCommitmentUpdate *this_ptr, LDKUpdateFee val);
+void CommitmentUpdate_set_update_fee(struct LDKCommitmentUpdate *NONNULL_PTR this_ptr, struct LDKUpdateFee val);
 
 /**
  * Finally, the commitment_signed message which should be sent
  */
-LDKCommitmentSigned CommitmentUpdate_get_commitment_signed(const LDKCommitmentUpdate *this_ptr);
+struct LDKCommitmentSigned CommitmentUpdate_get_commitment_signed(const struct LDKCommitmentUpdate *NONNULL_PTR this_ptr);
 
 /**
  * Finally, the commitment_signed message which should be sent
  */
-void CommitmentUpdate_set_commitment_signed(LDKCommitmentUpdate *this_ptr, LDKCommitmentSigned val);
+void CommitmentUpdate_set_commitment_signed(struct LDKCommitmentUpdate *NONNULL_PTR this_ptr, struct LDKCommitmentSigned val);
 
-MUST_USE_RES LDKCommitmentUpdate CommitmentUpdate_new(LDKCVec_UpdateAddHTLCZ update_add_htlcs_arg, LDKCVec_UpdateFulfillHTLCZ update_fulfill_htlcs_arg, LDKCVec_UpdateFailHTLCZ update_fail_htlcs_arg, LDKCVec_UpdateFailMalformedHTLCZ update_fail_malformed_htlcs_arg, LDKUpdateFee update_fee_arg, LDKCommitmentSigned commitment_signed_arg);
+MUST_USE_RES struct LDKCommitmentUpdate CommitmentUpdate_new(struct LDKCVec_UpdateAddHTLCZ update_add_htlcs_arg, struct LDKCVec_UpdateFulfillHTLCZ update_fulfill_htlcs_arg, struct LDKCVec_UpdateFailHTLCZ update_fail_htlcs_arg, struct LDKCVec_UpdateFailMalformedHTLCZ update_fail_malformed_htlcs_arg, struct LDKUpdateFee update_fee_arg, struct LDKCommitmentSigned commitment_signed_arg);
 
-void HTLCFailChannelUpdate_free(LDKHTLCFailChannelUpdate this_ptr);
+struct LDKCommitmentUpdate CommitmentUpdate_clone(const struct LDKCommitmentUpdate *NONNULL_PTR orig);
 
-LDKHTLCFailChannelUpdate HTLCFailChannelUpdate_clone(const LDKHTLCFailChannelUpdate *orig);
+void HTLCFailChannelUpdate_free(struct LDKHTLCFailChannelUpdate this_ptr);
+
+struct LDKHTLCFailChannelUpdate HTLCFailChannelUpdate_clone(const struct LDKHTLCFailChannelUpdate *NONNULL_PTR orig);
 
 /**
  * Calls the free function if one is set
  */
-void ChannelMessageHandler_free(LDKChannelMessageHandler this_ptr);
+void ChannelMessageHandler_free(struct LDKChannelMessageHandler this_ptr);
 
 /**
  * Calls the free function if one is set
  */
-void RoutingMessageHandler_free(LDKRoutingMessageHandler this_ptr);
+void RoutingMessageHandler_free(struct LDKRoutingMessageHandler this_ptr);
 
-LDKCVec_u8Z AcceptChannel_write(const LDKAcceptChannel *obj);
+struct LDKCVec_u8Z AcceptChannel_write(const struct LDKAcceptChannel *NONNULL_PTR obj);
 
-LDKAcceptChannel AcceptChannel_read(LDKu8slice ser);
+struct LDKCResult_AcceptChannelDecodeErrorZ AcceptChannel_read(struct LDKu8slice ser);
 
-LDKCVec_u8Z AnnouncementSignatures_write(const LDKAnnouncementSignatures *obj);
+struct LDKCVec_u8Z AnnouncementSignatures_write(const struct LDKAnnouncementSignatures *NONNULL_PTR obj);
 
-LDKAnnouncementSignatures AnnouncementSignatures_read(LDKu8slice ser);
+struct LDKCResult_AnnouncementSignaturesDecodeErrorZ AnnouncementSignatures_read(struct LDKu8slice ser);
 
-LDKCVec_u8Z ChannelReestablish_write(const LDKChannelReestablish *obj);
+struct LDKCVec_u8Z ChannelReestablish_write(const struct LDKChannelReestablish *NONNULL_PTR obj);
 
-LDKChannelReestablish ChannelReestablish_read(LDKu8slice ser);
+struct LDKCResult_ChannelReestablishDecodeErrorZ ChannelReestablish_read(struct LDKu8slice ser);
 
-LDKCVec_u8Z ClosingSigned_write(const LDKClosingSigned *obj);
+struct LDKCVec_u8Z ClosingSigned_write(const struct LDKClosingSigned *NONNULL_PTR obj);
 
-LDKClosingSigned ClosingSigned_read(LDKu8slice ser);
+struct LDKCResult_ClosingSignedDecodeErrorZ ClosingSigned_read(struct LDKu8slice ser);
 
-LDKCVec_u8Z CommitmentSigned_write(const LDKCommitmentSigned *obj);
+struct LDKCVec_u8Z CommitmentSigned_write(const struct LDKCommitmentSigned *NONNULL_PTR obj);
 
-LDKCommitmentSigned CommitmentSigned_read(LDKu8slice ser);
+struct LDKCResult_CommitmentSignedDecodeErrorZ CommitmentSigned_read(struct LDKu8slice ser);
 
-LDKCVec_u8Z FundingCreated_write(const LDKFundingCreated *obj);
+struct LDKCVec_u8Z FundingCreated_write(const struct LDKFundingCreated *NONNULL_PTR obj);
 
-LDKFundingCreated FundingCreated_read(LDKu8slice ser);
+struct LDKCResult_FundingCreatedDecodeErrorZ FundingCreated_read(struct LDKu8slice ser);
 
-LDKCVec_u8Z FundingSigned_write(const LDKFundingSigned *obj);
+struct LDKCVec_u8Z FundingSigned_write(const struct LDKFundingSigned *NONNULL_PTR obj);
 
-LDKFundingSigned FundingSigned_read(LDKu8slice ser);
+struct LDKCResult_FundingSignedDecodeErrorZ FundingSigned_read(struct LDKu8slice ser);
 
-LDKCVec_u8Z FundingLocked_write(const LDKFundingLocked *obj);
+struct LDKCVec_u8Z FundingLocked_write(const struct LDKFundingLocked *NONNULL_PTR obj);
 
-LDKFundingLocked FundingLocked_read(LDKu8slice ser);
+struct LDKCResult_FundingLockedDecodeErrorZ FundingLocked_read(struct LDKu8slice ser);
 
-LDKCVec_u8Z Init_write(const LDKInit *obj);
+struct LDKCVec_u8Z Init_write(const struct LDKInit *NONNULL_PTR obj);
 
-LDKInit Init_read(LDKu8slice ser);
+struct LDKCResult_InitDecodeErrorZ Init_read(struct LDKu8slice ser);
 
-LDKCVec_u8Z OpenChannel_write(const LDKOpenChannel *obj);
+struct LDKCVec_u8Z OpenChannel_write(const struct LDKOpenChannel *NONNULL_PTR obj);
 
-LDKOpenChannel OpenChannel_read(LDKu8slice ser);
+struct LDKCResult_OpenChannelDecodeErrorZ OpenChannel_read(struct LDKu8slice ser);
 
-LDKCVec_u8Z RevokeAndACK_write(const LDKRevokeAndACK *obj);
+struct LDKCVec_u8Z RevokeAndACK_write(const struct LDKRevokeAndACK *NONNULL_PTR obj);
 
-LDKRevokeAndACK RevokeAndACK_read(LDKu8slice ser);
+struct LDKCResult_RevokeAndACKDecodeErrorZ RevokeAndACK_read(struct LDKu8slice ser);
 
-LDKCVec_u8Z Shutdown_write(const LDKShutdown *obj);
+struct LDKCVec_u8Z Shutdown_write(const struct LDKShutdown *NONNULL_PTR obj);
 
-LDKShutdown Shutdown_read(LDKu8slice ser);
+struct LDKCResult_ShutdownDecodeErrorZ Shutdown_read(struct LDKu8slice ser);
 
-LDKCVec_u8Z UpdateFailHTLC_write(const LDKUpdateFailHTLC *obj);
+struct LDKCVec_u8Z UpdateFailHTLC_write(const struct LDKUpdateFailHTLC *NONNULL_PTR obj);
 
-LDKUpdateFailHTLC UpdateFailHTLC_read(LDKu8slice ser);
+struct LDKCResult_UpdateFailHTLCDecodeErrorZ UpdateFailHTLC_read(struct LDKu8slice ser);
 
-LDKCVec_u8Z UpdateFailMalformedHTLC_write(const LDKUpdateFailMalformedHTLC *obj);
+struct LDKCVec_u8Z UpdateFailMalformedHTLC_write(const struct LDKUpdateFailMalformedHTLC *NONNULL_PTR obj);
 
-LDKUpdateFailMalformedHTLC UpdateFailMalformedHTLC_read(LDKu8slice ser);
+struct LDKCResult_UpdateFailMalformedHTLCDecodeErrorZ UpdateFailMalformedHTLC_read(struct LDKu8slice ser);
 
-LDKCVec_u8Z UpdateFee_write(const LDKUpdateFee *obj);
+struct LDKCVec_u8Z UpdateFee_write(const struct LDKUpdateFee *NONNULL_PTR obj);
 
-LDKUpdateFee UpdateFee_read(LDKu8slice ser);
+struct LDKCResult_UpdateFeeDecodeErrorZ UpdateFee_read(struct LDKu8slice ser);
 
-LDKCVec_u8Z UpdateFulfillHTLC_write(const LDKUpdateFulfillHTLC *obj);
+struct LDKCVec_u8Z UpdateFulfillHTLC_write(const struct LDKUpdateFulfillHTLC *NONNULL_PTR obj);
 
-LDKUpdateFulfillHTLC UpdateFulfillHTLC_read(LDKu8slice ser);
+struct LDKCResult_UpdateFulfillHTLCDecodeErrorZ UpdateFulfillHTLC_read(struct LDKu8slice ser);
 
-LDKCVec_u8Z UpdateAddHTLC_write(const LDKUpdateAddHTLC *obj);
+struct LDKCVec_u8Z UpdateAddHTLC_write(const struct LDKUpdateAddHTLC *NONNULL_PTR obj);
 
-LDKUpdateAddHTLC UpdateAddHTLC_read(LDKu8slice ser);
+struct LDKCResult_UpdateAddHTLCDecodeErrorZ UpdateAddHTLC_read(struct LDKu8slice ser);
 
-LDKCVec_u8Z Ping_write(const LDKPing *obj);
+struct LDKCVec_u8Z Ping_write(const struct LDKPing *NONNULL_PTR obj);
 
-LDKPing Ping_read(LDKu8slice ser);
+struct LDKCResult_PingDecodeErrorZ Ping_read(struct LDKu8slice ser);
 
-LDKCVec_u8Z Pong_write(const LDKPong *obj);
+struct LDKCVec_u8Z Pong_write(const struct LDKPong *NONNULL_PTR obj);
 
-LDKPong Pong_read(LDKu8slice ser);
+struct LDKCResult_PongDecodeErrorZ Pong_read(struct LDKu8slice ser);
 
-LDKCVec_u8Z UnsignedChannelAnnouncement_write(const LDKUnsignedChannelAnnouncement *obj);
+struct LDKCVec_u8Z UnsignedChannelAnnouncement_write(const struct LDKUnsignedChannelAnnouncement *NONNULL_PTR obj);
 
-LDKUnsignedChannelAnnouncement UnsignedChannelAnnouncement_read(LDKu8slice ser);
+struct LDKCResult_UnsignedChannelAnnouncementDecodeErrorZ UnsignedChannelAnnouncement_read(struct LDKu8slice ser);
 
-LDKCVec_u8Z ChannelAnnouncement_write(const LDKChannelAnnouncement *obj);
+struct LDKCVec_u8Z ChannelAnnouncement_write(const struct LDKChannelAnnouncement *NONNULL_PTR obj);
 
-LDKChannelAnnouncement ChannelAnnouncement_read(LDKu8slice ser);
+struct LDKCResult_ChannelAnnouncementDecodeErrorZ ChannelAnnouncement_read(struct LDKu8slice ser);
 
-LDKCVec_u8Z UnsignedChannelUpdate_write(const LDKUnsignedChannelUpdate *obj);
+struct LDKCVec_u8Z UnsignedChannelUpdate_write(const struct LDKUnsignedChannelUpdate *NONNULL_PTR obj);
 
-LDKUnsignedChannelUpdate UnsignedChannelUpdate_read(LDKu8slice ser);
+struct LDKCResult_UnsignedChannelUpdateDecodeErrorZ UnsignedChannelUpdate_read(struct LDKu8slice ser);
 
-LDKCVec_u8Z ChannelUpdate_write(const LDKChannelUpdate *obj);
+struct LDKCVec_u8Z ChannelUpdate_write(const struct LDKChannelUpdate *NONNULL_PTR obj);
 
-LDKChannelUpdate ChannelUpdate_read(LDKu8slice ser);
+struct LDKCResult_ChannelUpdateDecodeErrorZ ChannelUpdate_read(struct LDKu8slice ser);
 
-LDKCVec_u8Z ErrorMessage_write(const LDKErrorMessage *obj);
+struct LDKCVec_u8Z ErrorMessage_write(const struct LDKErrorMessage *NONNULL_PTR obj);
 
-LDKErrorMessage ErrorMessage_read(LDKu8slice ser);
+struct LDKCResult_ErrorMessageDecodeErrorZ ErrorMessage_read(struct LDKu8slice ser);
 
-LDKCVec_u8Z UnsignedNodeAnnouncement_write(const LDKUnsignedNodeAnnouncement *obj);
+struct LDKCVec_u8Z UnsignedNodeAnnouncement_write(const struct LDKUnsignedNodeAnnouncement *NONNULL_PTR obj);
 
-LDKUnsignedNodeAnnouncement UnsignedNodeAnnouncement_read(LDKu8slice ser);
+struct LDKCResult_UnsignedNodeAnnouncementDecodeErrorZ UnsignedNodeAnnouncement_read(struct LDKu8slice ser);
 
-LDKCVec_u8Z NodeAnnouncement_write(const LDKNodeAnnouncement *obj);
+struct LDKCVec_u8Z NodeAnnouncement_write(const struct LDKNodeAnnouncement *NONNULL_PTR obj);
 
-LDKNodeAnnouncement NodeAnnouncement_read(LDKu8slice ser);
+struct LDKCResult_NodeAnnouncementDecodeErrorZ NodeAnnouncement_read(struct LDKu8slice ser);
 
-LDKQueryShortChannelIds QueryShortChannelIds_read(LDKu8slice ser);
+struct LDKCResult_QueryShortChannelIdsDecodeErrorZ QueryShortChannelIds_read(struct LDKu8slice ser);
 
-LDKCVec_u8Z QueryShortChannelIds_write(const LDKQueryShortChannelIds *obj);
+struct LDKCVec_u8Z QueryShortChannelIds_write(const struct LDKQueryShortChannelIds *NONNULL_PTR obj);
 
-LDKReplyShortChannelIdsEnd ReplyShortChannelIdsEnd_read(LDKu8slice ser);
+struct LDKCResult_ReplyShortChannelIdsEndDecodeErrorZ ReplyShortChannelIdsEnd_read(struct LDKu8slice ser);
 
-LDKCVec_u8Z ReplyShortChannelIdsEnd_write(const LDKReplyShortChannelIdsEnd *obj);
+struct LDKCVec_u8Z ReplyShortChannelIdsEnd_write(const struct LDKReplyShortChannelIdsEnd *NONNULL_PTR obj);
 
-LDKQueryChannelRange QueryChannelRange_read(LDKu8slice ser);
+struct LDKCResult_QueryChannelRangeDecodeErrorZ QueryChannelRange_read(struct LDKu8slice ser);
 
-LDKCVec_u8Z QueryChannelRange_write(const LDKQueryChannelRange *obj);
+struct LDKCVec_u8Z QueryChannelRange_write(const struct LDKQueryChannelRange *NONNULL_PTR obj);
 
-LDKReplyChannelRange ReplyChannelRange_read(LDKu8slice ser);
+struct LDKCResult_ReplyChannelRangeDecodeErrorZ ReplyChannelRange_read(struct LDKu8slice ser);
 
-LDKCVec_u8Z ReplyChannelRange_write(const LDKReplyChannelRange *obj);
+struct LDKCVec_u8Z ReplyChannelRange_write(const struct LDKReplyChannelRange *NONNULL_PTR obj);
 
-LDKGossipTimestampFilter GossipTimestampFilter_read(LDKu8slice ser);
+struct LDKCResult_GossipTimestampFilterDecodeErrorZ GossipTimestampFilter_read(struct LDKu8slice ser);
 
-LDKCVec_u8Z GossipTimestampFilter_write(const LDKGossipTimestampFilter *obj);
+struct LDKCVec_u8Z GossipTimestampFilter_write(const struct LDKGossipTimestampFilter *NONNULL_PTR obj);
 
-void MessageHandler_free(LDKMessageHandler this_ptr);
+void MessageHandler_free(struct LDKMessageHandler this_ptr);
 
 /**
  * A message handler which handles messages specific to channels. Usually this is just a
  * ChannelManager object.
  */
-const LDKChannelMessageHandler *MessageHandler_get_chan_handler(const LDKMessageHandler *this_ptr);
+const struct LDKChannelMessageHandler *MessageHandler_get_chan_handler(const struct LDKMessageHandler *NONNULL_PTR this_ptr);
 
 /**
  * A message handler which handles messages specific to channels. Usually this is just a
  * ChannelManager object.
  */
-void MessageHandler_set_chan_handler(LDKMessageHandler *this_ptr, LDKChannelMessageHandler val);
+void MessageHandler_set_chan_handler(struct LDKMessageHandler *NONNULL_PTR this_ptr, struct LDKChannelMessageHandler val);
 
 /**
  * A message handler which handles messages updating our knowledge of the network channel
  * graph. Usually this is just a NetGraphMsgHandlerMonitor object.
  */
-const LDKRoutingMessageHandler *MessageHandler_get_route_handler(const LDKMessageHandler *this_ptr);
+const struct LDKRoutingMessageHandler *MessageHandler_get_route_handler(const struct LDKMessageHandler *NONNULL_PTR this_ptr);
 
 /**
  * A message handler which handles messages updating our knowledge of the network channel
  * graph. Usually this is just a NetGraphMsgHandlerMonitor object.
  */
-void MessageHandler_set_route_handler(LDKMessageHandler *this_ptr, LDKRoutingMessageHandler val);
+void MessageHandler_set_route_handler(struct LDKMessageHandler *NONNULL_PTR this_ptr, struct LDKRoutingMessageHandler val);
 
-MUST_USE_RES LDKMessageHandler MessageHandler_new(LDKChannelMessageHandler chan_handler_arg, LDKRoutingMessageHandler route_handler_arg);
+MUST_USE_RES struct LDKMessageHandler MessageHandler_new(struct LDKChannelMessageHandler chan_handler_arg, struct LDKRoutingMessageHandler route_handler_arg);
 
-LDKSocketDescriptor SocketDescriptor_clone(const LDKSocketDescriptor *orig);
+struct LDKSocketDescriptor SocketDescriptor_clone(const struct LDKSocketDescriptor *NONNULL_PTR orig);
 
 /**
  * Calls the free function if one is set
  */
-void SocketDescriptor_free(LDKSocketDescriptor this_ptr);
+void SocketDescriptor_free(struct LDKSocketDescriptor this_ptr);
 
-void PeerHandleError_free(LDKPeerHandleError this_ptr);
+void PeerHandleError_free(struct LDKPeerHandleError this_ptr);
 
 /**
  * Used to indicate that we probably can't make any future connections to this peer, implying
  * we should go ahead and force-close any channels we have with it.
  */
-bool PeerHandleError_get_no_connection_possible(const LDKPeerHandleError *this_ptr);
+bool PeerHandleError_get_no_connection_possible(const struct LDKPeerHandleError *NONNULL_PTR this_ptr);
 
 /**
  * Used to indicate that we probably can't make any future connections to this peer, implying
  * we should go ahead and force-close any channels we have with it.
  */
-void PeerHandleError_set_no_connection_possible(LDKPeerHandleError *this_ptr, bool val);
+void PeerHandleError_set_no_connection_possible(struct LDKPeerHandleError *NONNULL_PTR this_ptr, bool val);
+
+MUST_USE_RES struct LDKPeerHandleError PeerHandleError_new(bool no_connection_possible_arg);
 
-MUST_USE_RES LDKPeerHandleError PeerHandleError_new(bool no_connection_possible_arg);
+struct LDKPeerHandleError PeerHandleError_clone(const struct LDKPeerHandleError *NONNULL_PTR orig);
 
-void PeerManager_free(LDKPeerManager this_ptr);
+void PeerManager_free(struct LDKPeerManager this_ptr);
 
 /**
  * Constructs a new PeerManager with the given message handlers and node_id secret key
  * ephemeral_random_data is used to derive per-connection ephemeral keys and must be
  * cryptographically secure random bytes.
  */
-MUST_USE_RES LDKPeerManager PeerManager_new(LDKMessageHandler message_handler, LDKSecretKey our_node_secret, const uint8_t (*ephemeral_random_data)[32], LDKLogger logger);
+MUST_USE_RES struct LDKPeerManager PeerManager_new(struct LDKMessageHandler message_handler, struct LDKSecretKey our_node_secret, const uint8_t (*ephemeral_random_data)[32], struct LDKLogger logger);
 
 /**
  * Get the list of node ids for peers which have completed the initial handshake.
@@ -6300,7 +7902,7 @@ MUST_USE_RES LDKPeerManager PeerManager_new(LDKMessageHandler message_handler, L
  * new_outbound_connection, however entries will only appear once the initial handshake has
  * completed and we are sure the remote peer has the private key for the given node_id.
  */
-MUST_USE_RES LDKCVec_PublicKeyZ PeerManager_get_peer_node_ids(const LDKPeerManager *this_arg);
+MUST_USE_RES struct LDKCVec_PublicKeyZ PeerManager_get_peer_node_ids(const struct LDKPeerManager *NONNULL_PTR this_arg);
 
 /**
  * Indicates a new outbound connection has been established to a node with the given node_id.
@@ -6312,7 +7914,7 @@ MUST_USE_RES LDKCVec_PublicKeyZ PeerManager_get_peer_node_ids(const LDKPeerManag
  * Panics if descriptor is duplicative with some other descriptor which has not yet had a
  * socket_disconnected().
  */
-MUST_USE_RES LDKCResult_CVec_u8ZPeerHandleErrorZ PeerManager_new_outbound_connection(const LDKPeerManager *this_arg, LDKPublicKey their_node_id, LDKSocketDescriptor descriptor);
+MUST_USE_RES struct LDKCResult_CVec_u8ZPeerHandleErrorZ PeerManager_new_outbound_connection(const struct LDKPeerManager *NONNULL_PTR this_arg, struct LDKPublicKey their_node_id, struct LDKSocketDescriptor descriptor);
 
 /**
  * Indicates a new inbound connection has been established.
@@ -6325,7 +7927,7 @@ MUST_USE_RES LDKCResult_CVec_u8ZPeerHandleErrorZ PeerManager_new_outbound_connec
  * Panics if descriptor is duplicative with some other descriptor which has not yet had
  * socket_disconnected called.
  */
-MUST_USE_RES LDKCResult_NonePeerHandleErrorZ PeerManager_new_inbound_connection(const LDKPeerManager *this_arg, LDKSocketDescriptor descriptor);
+MUST_USE_RES struct LDKCResult_NonePeerHandleErrorZ PeerManager_new_inbound_connection(const struct LDKPeerManager *NONNULL_PTR this_arg, struct LDKSocketDescriptor descriptor);
 
 /**
  * Indicates that there is room to write data to the given socket descriptor.
@@ -6339,7 +7941,7 @@ MUST_USE_RES LDKCResult_NonePeerHandleErrorZ PeerManager_new_inbound_connection(
  * here isn't sufficient! Panics if the descriptor was not previously registered in a
  * new_\\*_connection event.
  */
-MUST_USE_RES LDKCResult_NonePeerHandleErrorZ PeerManager_write_buffer_space_avail(const LDKPeerManager *this_arg, LDKSocketDescriptor *descriptor);
+MUST_USE_RES struct LDKCResult_NonePeerHandleErrorZ PeerManager_write_buffer_space_avail(const struct LDKPeerManager *NONNULL_PTR this_arg, struct LDKSocketDescriptor *NONNULL_PTR descriptor);
 
 /**
  * Indicates that data was read from the given socket descriptor.
@@ -6355,14 +7957,14 @@ MUST_USE_RES LDKCResult_NonePeerHandleErrorZ PeerManager_write_buffer_space_avai
  *
  * Panics if the descriptor was not previously registered in a new_*_connection event.
  */
-MUST_USE_RES LDKCResult_boolPeerHandleErrorZ PeerManager_read_event(const LDKPeerManager *this_arg, LDKSocketDescriptor *peer_descriptor, LDKu8slice data);
+MUST_USE_RES struct LDKCResult_boolPeerHandleErrorZ PeerManager_read_event(const struct LDKPeerManager *NONNULL_PTR this_arg, struct LDKSocketDescriptor *NONNULL_PTR peer_descriptor, struct LDKu8slice data);
 
 /**
  * Checks for any events generated by our handlers and processes them. Includes sending most
  * response messages as well as messages generated by calls to handler functions directly (eg
  * functions like ChannelManager::process_pending_htlc_forward or send_payment).
  */
-void PeerManager_process_events(const LDKPeerManager *this_arg);
+void PeerManager_process_events(const struct LDKPeerManager *NONNULL_PTR this_arg);
 
 /**
  * Indicates that the given socket descriptor's connection is now closed.
@@ -6374,19 +7976,30 @@ void PeerManager_process_events(const LDKPeerManager *this_arg);
  *
  * Panics if the descriptor was not previously registered in a successful new_*_connection event.
  */
-void PeerManager_socket_disconnected(const LDKPeerManager *this_arg, const LDKSocketDescriptor *descriptor);
+void PeerManager_socket_disconnected(const struct LDKPeerManager *NONNULL_PTR this_arg, const struct LDKSocketDescriptor *NONNULL_PTR descriptor);
+
+/**
+ * Disconnect a peer given its node id.
+ *
+ * Set no_connection_possible to true to prevent any further connection with this peer,
+ * force-closing any channels we have with it.
+ *
+ * If a peer is connected, this will call `disconnect_socket` on the descriptor for the peer,
+ * so be careful about reentrancy issues.
+ */
+void PeerManager_disconnect_by_node_id(const struct LDKPeerManager *NONNULL_PTR this_arg, struct LDKPublicKey node_id, bool no_connection_possible);
 
 /**
  * This function should be called roughly once every 30 seconds.
  * It will send pings to each peer and disconnect those which did not respond to the last round of pings.
  * Will most likely call send_data on all of the registered descriptors, thus, be very careful with reentrancy issues!
  */
-void PeerManager_timer_tick_occured(const LDKPeerManager *this_arg);
+void PeerManager_timer_tick_occured(const struct LDKPeerManager *NONNULL_PTR this_arg);
 
 /**
  * Build the commitment secret from the seed and the commitment number
  */
-LDKThirtyTwoBytes build_commitment_secret(const uint8_t (*commitment_seed)[32], uint64_t idx);
+struct LDKThirtyTwoBytes build_commitment_secret(const uint8_t (*commitment_seed)[32], uint64_t idx);
 
 /**
  * Derives a per-commitment-transaction private key (eg an htlc key or delayed_payment key)
@@ -6395,7 +8008,7 @@ LDKThirtyTwoBytes build_commitment_secret(const uint8_t (*commitment_seed)[32],
  * Note that this is infallible iff we trust that at least one of the two input keys are randomly
  * generated (ie our own).
  */
-LDKCResult_SecretKeySecpErrorZ derive_private_key(LDKPublicKey per_commitment_point, const uint8_t (*base_secret)[32]);
+struct LDKCResult_SecretKeyErrorZ derive_private_key(struct LDKPublicKey per_commitment_point, const uint8_t (*base_secret)[32]);
 
 /**
  * Derives a per-commitment-transaction public key (eg an htlc key or a delayed_payment key)
@@ -6405,7 +8018,7 @@ LDKCResult_SecretKeySecpErrorZ derive_private_key(LDKPublicKey per_commitment_po
  * Note that this is infallible iff we trust that at least one of the two input keys are randomly
  * generated (ie our own).
  */
-LDKCResult_PublicKeySecpErrorZ derive_public_key(LDKPublicKey per_commitment_point, LDKPublicKey base_point);
+struct LDKCResult_PublicKeyErrorZ derive_public_key(struct LDKPublicKey per_commitment_point, struct LDKPublicKey base_point);
 
 /**
  * Derives a per-commitment-transaction revocation key from its constituent parts.
@@ -6418,7 +8031,7 @@ LDKCResult_PublicKeySecpErrorZ derive_public_key(LDKPublicKey per_commitment_poi
  * Note that this is infallible iff we trust that at least one of the two input keys are randomly
  * generated (ie our own).
  */
-LDKCResult_SecretKeySecpErrorZ derive_private_revocation_key(const uint8_t (*per_commitment_secret)[32], const uint8_t (*countersignatory_revocation_base_secret)[32]);
+struct LDKCResult_SecretKeyErrorZ derive_private_revocation_key(const uint8_t (*per_commitment_secret)[32], const uint8_t (*countersignatory_revocation_base_secret)[32]);
 
 /**
  * Derives a per-commitment-transaction revocation public key from its constituent parts. This is
@@ -6433,107 +8046,85 @@ LDKCResult_SecretKeySecpErrorZ derive_private_revocation_key(const uint8_t (*per
  * Note that this is infallible iff we trust that at least one of the two input keys are randomly
  * generated (ie our own).
  */
-LDKCResult_PublicKeySecpErrorZ derive_public_revocation_key(LDKPublicKey per_commitment_point, LDKPublicKey countersignatory_revocation_base_point);
-
-void TxCreationKeys_free(LDKTxCreationKeys this_ptr);
+struct LDKCResult_PublicKeyErrorZ derive_public_revocation_key(struct LDKPublicKey per_commitment_point, struct LDKPublicKey countersignatory_revocation_base_point);
 
-LDKTxCreationKeys TxCreationKeys_clone(const LDKTxCreationKeys *orig);
+void TxCreationKeys_free(struct LDKTxCreationKeys this_ptr);
 
 /**
  * The broadcaster's per-commitment public key which was used to derive the other keys.
  */
-LDKPublicKey TxCreationKeys_get_per_commitment_point(const LDKTxCreationKeys *this_ptr);
+struct LDKPublicKey TxCreationKeys_get_per_commitment_point(const struct LDKTxCreationKeys *NONNULL_PTR this_ptr);
 
 /**
  * The broadcaster's per-commitment public key which was used to derive the other keys.
  */
-void TxCreationKeys_set_per_commitment_point(LDKTxCreationKeys *this_ptr, LDKPublicKey val);
+void TxCreationKeys_set_per_commitment_point(struct LDKTxCreationKeys *NONNULL_PTR this_ptr, struct LDKPublicKey val);
 
 /**
  * The revocation key which is used to allow the broadcaster of the commitment
  * transaction to provide their counterparty the ability to punish them if they broadcast
  * an old state.
  */
-LDKPublicKey TxCreationKeys_get_revocation_key(const LDKTxCreationKeys *this_ptr);
+struct LDKPublicKey TxCreationKeys_get_revocation_key(const struct LDKTxCreationKeys *NONNULL_PTR this_ptr);
 
 /**
  * The revocation key which is used to allow the broadcaster of the commitment
  * transaction to provide their counterparty the ability to punish them if they broadcast
  * an old state.
  */
-void TxCreationKeys_set_revocation_key(LDKTxCreationKeys *this_ptr, LDKPublicKey val);
+void TxCreationKeys_set_revocation_key(struct LDKTxCreationKeys *NONNULL_PTR this_ptr, struct LDKPublicKey val);
 
 /**
  * Broadcaster's HTLC Key
  */
-LDKPublicKey TxCreationKeys_get_broadcaster_htlc_key(const LDKTxCreationKeys *this_ptr);
+struct LDKPublicKey TxCreationKeys_get_broadcaster_htlc_key(const struct LDKTxCreationKeys *NONNULL_PTR this_ptr);
 
 /**
  * Broadcaster's HTLC Key
  */
-void TxCreationKeys_set_broadcaster_htlc_key(LDKTxCreationKeys *this_ptr, LDKPublicKey val);
+void TxCreationKeys_set_broadcaster_htlc_key(struct LDKTxCreationKeys *NONNULL_PTR this_ptr, struct LDKPublicKey val);
 
 /**
  * Countersignatory's HTLC Key
  */
-LDKPublicKey TxCreationKeys_get_countersignatory_htlc_key(const LDKTxCreationKeys *this_ptr);
+struct LDKPublicKey TxCreationKeys_get_countersignatory_htlc_key(const struct LDKTxCreationKeys *NONNULL_PTR this_ptr);
 
 /**
  * Countersignatory's HTLC Key
  */
-void TxCreationKeys_set_countersignatory_htlc_key(LDKTxCreationKeys *this_ptr, LDKPublicKey val);
+void TxCreationKeys_set_countersignatory_htlc_key(struct LDKTxCreationKeys *NONNULL_PTR this_ptr, struct LDKPublicKey val);
 
 /**
  * Broadcaster's Payment Key (which isn't allowed to be spent from for some delay)
  */
-LDKPublicKey TxCreationKeys_get_broadcaster_delayed_payment_key(const LDKTxCreationKeys *this_ptr);
+struct LDKPublicKey TxCreationKeys_get_broadcaster_delayed_payment_key(const struct LDKTxCreationKeys *NONNULL_PTR this_ptr);
 
 /**
  * Broadcaster's Payment Key (which isn't allowed to be spent from for some delay)
  */
-void TxCreationKeys_set_broadcaster_delayed_payment_key(LDKTxCreationKeys *this_ptr, LDKPublicKey val);
-
-MUST_USE_RES LDKTxCreationKeys TxCreationKeys_new(LDKPublicKey per_commitment_point_arg, LDKPublicKey revocation_key_arg, LDKPublicKey broadcaster_htlc_key_arg, LDKPublicKey countersignatory_htlc_key_arg, LDKPublicKey broadcaster_delayed_payment_key_arg);
-
-LDKCVec_u8Z TxCreationKeys_write(const LDKTxCreationKeys *obj);
+void TxCreationKeys_set_broadcaster_delayed_payment_key(struct LDKTxCreationKeys *NONNULL_PTR this_ptr, struct LDKPublicKey val);
 
-LDKTxCreationKeys TxCreationKeys_read(LDKu8slice ser);
-
-void PreCalculatedTxCreationKeys_free(LDKPreCalculatedTxCreationKeys this_ptr);
-
-LDKPreCalculatedTxCreationKeys PreCalculatedTxCreationKeys_clone(const LDKPreCalculatedTxCreationKeys *orig);
-
-/**
- * Create a new PreCalculatedTxCreationKeys from TxCreationKeys
- */
-MUST_USE_RES LDKPreCalculatedTxCreationKeys PreCalculatedTxCreationKeys_new(LDKTxCreationKeys keys);
+MUST_USE_RES struct LDKTxCreationKeys TxCreationKeys_new(struct LDKPublicKey per_commitment_point_arg, struct LDKPublicKey revocation_key_arg, struct LDKPublicKey broadcaster_htlc_key_arg, struct LDKPublicKey countersignatory_htlc_key_arg, struct LDKPublicKey broadcaster_delayed_payment_key_arg);
 
-/**
- * The pre-calculated transaction creation public keys.
- * An external validating signer should not trust these keys.
- */
-MUST_USE_RES LDKTxCreationKeys PreCalculatedTxCreationKeys_trust_key_derivation(const LDKPreCalculatedTxCreationKeys *this_arg);
+struct LDKTxCreationKeys TxCreationKeys_clone(const struct LDKTxCreationKeys *NONNULL_PTR orig);
 
-/**
- * The transaction per-commitment point
- */
-MUST_USE_RES LDKPublicKey PreCalculatedTxCreationKeys_per_commitment_point(const LDKPreCalculatedTxCreationKeys *this_arg);
+struct LDKCVec_u8Z TxCreationKeys_write(const struct LDKTxCreationKeys *NONNULL_PTR obj);
 
-void ChannelPublicKeys_free(LDKChannelPublicKeys this_ptr);
+struct LDKCResult_TxCreationKeysDecodeErrorZ TxCreationKeys_read(struct LDKu8slice ser);
 
-LDKChannelPublicKeys ChannelPublicKeys_clone(const LDKChannelPublicKeys *orig);
+void ChannelPublicKeys_free(struct LDKChannelPublicKeys this_ptr);
 
 /**
  * The public key which is used to sign all commitment transactions, as it appears in the
  * on-chain channel lock-in 2-of-2 multisig output.
  */
-LDKPublicKey ChannelPublicKeys_get_funding_pubkey(const LDKChannelPublicKeys *this_ptr);
+struct LDKPublicKey ChannelPublicKeys_get_funding_pubkey(const struct LDKChannelPublicKeys *NONNULL_PTR this_ptr);
 
 /**
  * The public key which is used to sign all commitment transactions, as it appears in the
  * on-chain channel lock-in 2-of-2 multisig output.
  */
-void ChannelPublicKeys_set_funding_pubkey(LDKChannelPublicKeys *this_ptr, LDKPublicKey val);
+void ChannelPublicKeys_set_funding_pubkey(struct LDKChannelPublicKeys *NONNULL_PTR this_ptr, struct LDKPublicKey val);
 
 /**
  * The base point which is used (with derive_public_revocation_key) to derive per-commitment
@@ -6541,7 +8132,7 @@ void ChannelPublicKeys_set_funding_pubkey(LDKChannelPublicKeys *this_ptr, LDKPub
  * counterparty to create a secret which the counterparty can reveal to revoke previous
  * states.
  */
-LDKPublicKey ChannelPublicKeys_get_revocation_basepoint(const LDKChannelPublicKeys *this_ptr);
+struct LDKPublicKey ChannelPublicKeys_get_revocation_basepoint(const struct LDKChannelPublicKeys *NONNULL_PTR this_ptr);
 
 /**
  * The base point which is used (with derive_public_revocation_key) to derive per-commitment
@@ -6549,69 +8140,76 @@ LDKPublicKey ChannelPublicKeys_get_revocation_basepoint(const LDKChannelPublicKe
  * counterparty to create a secret which the counterparty can reveal to revoke previous
  * states.
  */
-void ChannelPublicKeys_set_revocation_basepoint(LDKChannelPublicKeys *this_ptr, LDKPublicKey val);
+void ChannelPublicKeys_set_revocation_basepoint(struct LDKChannelPublicKeys *NONNULL_PTR this_ptr, struct LDKPublicKey val);
 
 /**
  * The public key on which the non-broadcaster (ie the countersignatory) receives an immediately
  * spendable primary channel balance on the broadcaster's commitment transaction. This key is
  * static across every commitment transaction.
  */
-LDKPublicKey ChannelPublicKeys_get_payment_point(const LDKChannelPublicKeys *this_ptr);
+struct LDKPublicKey ChannelPublicKeys_get_payment_point(const struct LDKChannelPublicKeys *NONNULL_PTR this_ptr);
 
 /**
  * The public key on which the non-broadcaster (ie the countersignatory) receives an immediately
  * spendable primary channel balance on the broadcaster's commitment transaction. This key is
  * static across every commitment transaction.
  */
-void ChannelPublicKeys_set_payment_point(LDKChannelPublicKeys *this_ptr, LDKPublicKey val);
+void ChannelPublicKeys_set_payment_point(struct LDKChannelPublicKeys *NONNULL_PTR this_ptr, struct LDKPublicKey val);
 
 /**
  * The base point which is used (with derive_public_key) to derive a per-commitment payment
  * public key which receives non-HTLC-encumbered funds which are only available for spending
  * after some delay (or can be claimed via the revocation path).
  */
-LDKPublicKey ChannelPublicKeys_get_delayed_payment_basepoint(const LDKChannelPublicKeys *this_ptr);
+struct LDKPublicKey ChannelPublicKeys_get_delayed_payment_basepoint(const struct LDKChannelPublicKeys *NONNULL_PTR this_ptr);
 
 /**
  * The base point which is used (with derive_public_key) to derive a per-commitment payment
  * public key which receives non-HTLC-encumbered funds which are only available for spending
  * after some delay (or can be claimed via the revocation path).
  */
-void ChannelPublicKeys_set_delayed_payment_basepoint(LDKChannelPublicKeys *this_ptr, LDKPublicKey val);
+void ChannelPublicKeys_set_delayed_payment_basepoint(struct LDKChannelPublicKeys *NONNULL_PTR this_ptr, struct LDKPublicKey val);
 
 /**
  * The base point which is used (with derive_public_key) to derive a per-commitment public key
  * which is used to encumber HTLC-in-flight outputs.
  */
-LDKPublicKey ChannelPublicKeys_get_htlc_basepoint(const LDKChannelPublicKeys *this_ptr);
+struct LDKPublicKey ChannelPublicKeys_get_htlc_basepoint(const struct LDKChannelPublicKeys *NONNULL_PTR this_ptr);
 
 /**
  * The base point which is used (with derive_public_key) to derive a per-commitment public key
  * which is used to encumber HTLC-in-flight outputs.
  */
-void ChannelPublicKeys_set_htlc_basepoint(LDKChannelPublicKeys *this_ptr, LDKPublicKey val);
+void ChannelPublicKeys_set_htlc_basepoint(struct LDKChannelPublicKeys *NONNULL_PTR this_ptr, struct LDKPublicKey val);
+
+MUST_USE_RES struct LDKChannelPublicKeys ChannelPublicKeys_new(struct LDKPublicKey funding_pubkey_arg, struct LDKPublicKey revocation_basepoint_arg, struct LDKPublicKey payment_point_arg, struct LDKPublicKey delayed_payment_basepoint_arg, struct LDKPublicKey htlc_basepoint_arg);
+
+struct LDKChannelPublicKeys ChannelPublicKeys_clone(const struct LDKChannelPublicKeys *NONNULL_PTR orig);
 
-MUST_USE_RES LDKChannelPublicKeys ChannelPublicKeys_new(LDKPublicKey funding_pubkey_arg, LDKPublicKey revocation_basepoint_arg, LDKPublicKey payment_point_arg, LDKPublicKey delayed_payment_basepoint_arg, LDKPublicKey htlc_basepoint_arg);
+struct LDKCVec_u8Z ChannelPublicKeys_write(const struct LDKChannelPublicKeys *NONNULL_PTR obj);
 
-LDKCVec_u8Z ChannelPublicKeys_write(const LDKChannelPublicKeys *obj);
+struct LDKCResult_ChannelPublicKeysDecodeErrorZ ChannelPublicKeys_read(struct LDKu8slice ser);
 
-LDKChannelPublicKeys ChannelPublicKeys_read(LDKu8slice ser);
+/**
+ * Create per-state keys from channel base points and the per-commitment point.
+ * Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
+ */
+MUST_USE_RES struct LDKCResult_TxCreationKeysErrorZ TxCreationKeys_derive_new(struct LDKPublicKey per_commitment_point, struct LDKPublicKey broadcaster_delayed_payment_base, struct LDKPublicKey broadcaster_htlc_base, struct LDKPublicKey countersignatory_revocation_base, struct LDKPublicKey countersignatory_htlc_base);
 
 /**
- * Create a new TxCreationKeys from channel base points and the per-commitment point
+ * Generate per-state keys from channel static keys.
+ * Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
  */
-MUST_USE_RES LDKCResult_TxCreationKeysSecpErrorZ TxCreationKeys_derive_new(LDKPublicKey per_commitment_point, LDKPublicKey broadcaster_delayed_payment_base, LDKPublicKey broadcaster_htlc_base, LDKPublicKey countersignatory_revocation_base, LDKPublicKey countersignatory_htlc_base);
+MUST_USE_RES struct LDKCResult_TxCreationKeysErrorZ TxCreationKeys_from_channel_static_keys(struct LDKPublicKey per_commitment_point, const struct LDKChannelPublicKeys *NONNULL_PTR broadcaster_keys, const struct LDKChannelPublicKeys *NONNULL_PTR countersignatory_keys);
 
 /**
  * A script either spendable by the revocation
  * key or the broadcaster_delayed_payment_key and satisfying the relative-locktime OP_CSV constrain.
  * Encumbering a `to_holder` output on a commitment transaction or 2nd-stage HTLC transactions.
  */
-LDKCVec_u8Z get_revokeable_redeemscript(LDKPublicKey revocation_key, uint16_t contest_delay, LDKPublicKey broadcaster_delayed_payment_key);
+struct LDKCVec_u8Z get_revokeable_redeemscript(struct LDKPublicKey revocation_key, uint16_t contest_delay, struct LDKPublicKey broadcaster_delayed_payment_key);
 
-void HTLCOutputInCommitment_free(LDKHTLCOutputInCommitment this_ptr);
-
-LDKHTLCOutputInCommitment HTLCOutputInCommitment_clone(const LDKHTLCOutputInCommitment *orig);
+void HTLCOutputInCommitment_free(struct LDKHTLCOutputInCommitment this_ptr);
 
 /**
  * Whether the HTLC was \"offered\" (ie outbound in relation to this commitment transaction).
@@ -6619,7 +8217,7 @@ LDKHTLCOutputInCommitment HTLCOutputInCommitment_clone(const LDKHTLCOutputInComm
  * need to compare this value to whether the commitment transaction in question is that of
  * the counterparty or our own.
  */
-bool HTLCOutputInCommitment_get_offered(const LDKHTLCOutputInCommitment *this_ptr);
+bool HTLCOutputInCommitment_get_offered(const struct LDKHTLCOutputInCommitment *NONNULL_PTR this_ptr);
 
 /**
  * Whether the HTLC was \"offered\" (ie outbound in relation to this commitment transaction).
@@ -6627,237 +8225,498 @@ bool HTLCOutputInCommitment_get_offered(const LDKHTLCOutputInCommitment *this_pt
  * need to compare this value to whether the commitment transaction in question is that of
  * the counterparty or our own.
  */
-void HTLCOutputInCommitment_set_offered(LDKHTLCOutputInCommitment *this_ptr, bool val);
+void HTLCOutputInCommitment_set_offered(struct LDKHTLCOutputInCommitment *NONNULL_PTR this_ptr, bool val);
 
 /**
  * The value, in msat, of the HTLC. The value as it appears in the commitment transaction is
  * this divided by 1000.
  */
-uint64_t HTLCOutputInCommitment_get_amount_msat(const LDKHTLCOutputInCommitment *this_ptr);
+uint64_t HTLCOutputInCommitment_get_amount_msat(const struct LDKHTLCOutputInCommitment *NONNULL_PTR this_ptr);
 
 /**
  * The value, in msat, of the HTLC. The value as it appears in the commitment transaction is
  * this divided by 1000.
  */
-void HTLCOutputInCommitment_set_amount_msat(LDKHTLCOutputInCommitment *this_ptr, uint64_t val);
+void HTLCOutputInCommitment_set_amount_msat(struct LDKHTLCOutputInCommitment *NONNULL_PTR this_ptr, uint64_t val);
 
 /**
  * The CLTV lock-time at which this HTLC expires.
  */
-uint32_t HTLCOutputInCommitment_get_cltv_expiry(const LDKHTLCOutputInCommitment *this_ptr);
+uint32_t HTLCOutputInCommitment_get_cltv_expiry(const struct LDKHTLCOutputInCommitment *NONNULL_PTR this_ptr);
 
 /**
  * The CLTV lock-time at which this HTLC expires.
  */
-void HTLCOutputInCommitment_set_cltv_expiry(LDKHTLCOutputInCommitment *this_ptr, uint32_t val);
+void HTLCOutputInCommitment_set_cltv_expiry(struct LDKHTLCOutputInCommitment *NONNULL_PTR this_ptr, uint32_t val);
 
 /**
  * The hash of the preimage which unlocks this HTLC.
  */
-const uint8_t (*HTLCOutputInCommitment_get_payment_hash(const LDKHTLCOutputInCommitment *this_ptr))[32];
+const uint8_t (*HTLCOutputInCommitment_get_payment_hash(const struct LDKHTLCOutputInCommitment *NONNULL_PTR this_ptr))[32];
 
 /**
  * The hash of the preimage which unlocks this HTLC.
  */
-void HTLCOutputInCommitment_set_payment_hash(LDKHTLCOutputInCommitment *this_ptr, LDKThirtyTwoBytes val);
+void HTLCOutputInCommitment_set_payment_hash(struct LDKHTLCOutputInCommitment *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
+
+struct LDKHTLCOutputInCommitment HTLCOutputInCommitment_clone(const struct LDKHTLCOutputInCommitment *NONNULL_PTR orig);
 
-LDKCVec_u8Z HTLCOutputInCommitment_write(const LDKHTLCOutputInCommitment *obj);
+struct LDKCVec_u8Z HTLCOutputInCommitment_write(const struct LDKHTLCOutputInCommitment *NONNULL_PTR obj);
 
-LDKHTLCOutputInCommitment HTLCOutputInCommitment_read(LDKu8slice ser);
+struct LDKCResult_HTLCOutputInCommitmentDecodeErrorZ HTLCOutputInCommitment_read(struct LDKu8slice ser);
 
 /**
  * Gets the witness redeemscript for an HTLC output in a commitment transaction. Note that htlc
  * does not need to have its previous_output_index filled.
  */
-LDKCVec_u8Z get_htlc_redeemscript(const LDKHTLCOutputInCommitment *htlc, const LDKTxCreationKeys *keys);
+struct LDKCVec_u8Z get_htlc_redeemscript(const struct LDKHTLCOutputInCommitment *NONNULL_PTR htlc, const struct LDKTxCreationKeys *NONNULL_PTR keys);
 
 /**
  * Gets the redeemscript for a funding output from the two funding public keys.
  * Note that the order of funding public keys does not matter.
  */
-LDKCVec_u8Z make_funding_redeemscript(LDKPublicKey broadcaster, LDKPublicKey countersignatory);
+struct LDKCVec_u8Z make_funding_redeemscript(struct LDKPublicKey broadcaster, struct LDKPublicKey countersignatory);
 
 /**
  * panics if htlc.transaction_output_index.is_none()!
  */
-LDKTransaction build_htlc_transaction(const uint8_t (*prev_hash)[32], uint32_t feerate_per_kw, uint16_t contest_delay, const LDKHTLCOutputInCommitment *htlc, LDKPublicKey broadcaster_delayed_payment_key, LDKPublicKey revocation_key);
+struct LDKTransaction build_htlc_transaction(const uint8_t (*prev_hash)[32], uint32_t feerate_per_kw, uint16_t contest_delay, const struct LDKHTLCOutputInCommitment *NONNULL_PTR htlc, struct LDKPublicKey broadcaster_delayed_payment_key, struct LDKPublicKey revocation_key);
+
+void ChannelTransactionParameters_free(struct LDKChannelTransactionParameters this_ptr);
+
+/**
+ * Holder public keys
+ */
+struct LDKChannelPublicKeys ChannelTransactionParameters_get_holder_pubkeys(const struct LDKChannelTransactionParameters *NONNULL_PTR this_ptr);
+
+/**
+ * Holder public keys
+ */
+void ChannelTransactionParameters_set_holder_pubkeys(struct LDKChannelTransactionParameters *NONNULL_PTR this_ptr, struct LDKChannelPublicKeys val);
+
+/**
+ * The contest delay selected by the holder, which applies to counterparty-broadcast transactions
+ */
+uint16_t ChannelTransactionParameters_get_holder_selected_contest_delay(const struct LDKChannelTransactionParameters *NONNULL_PTR this_ptr);
+
+/**
+ * The contest delay selected by the holder, which applies to counterparty-broadcast transactions
+ */
+void ChannelTransactionParameters_set_holder_selected_contest_delay(struct LDKChannelTransactionParameters *NONNULL_PTR this_ptr, uint16_t val);
+
+/**
+ * Whether the holder is the initiator of this channel.
+ * This is an input to the commitment number obscure factor computation.
+ */
+bool ChannelTransactionParameters_get_is_outbound_from_holder(const struct LDKChannelTransactionParameters *NONNULL_PTR this_ptr);
+
+/**
+ * Whether the holder is the initiator of this channel.
+ * This is an input to the commitment number obscure factor computation.
+ */
+void ChannelTransactionParameters_set_is_outbound_from_holder(struct LDKChannelTransactionParameters *NONNULL_PTR this_ptr, bool val);
+
+/**
+ * The late-bound counterparty channel transaction parameters.
+ * These parameters are populated at the point in the protocol where the counterparty provides them.
+ */
+struct LDKCounterpartyChannelTransactionParameters ChannelTransactionParameters_get_counterparty_parameters(const struct LDKChannelTransactionParameters *NONNULL_PTR this_ptr);
+
+/**
+ * The late-bound counterparty channel transaction parameters.
+ * These parameters are populated at the point in the protocol where the counterparty provides them.
+ */
+void ChannelTransactionParameters_set_counterparty_parameters(struct LDKChannelTransactionParameters *NONNULL_PTR this_ptr, struct LDKCounterpartyChannelTransactionParameters val);
+
+/**
+ * The late-bound funding outpoint
+ */
+struct LDKOutPoint ChannelTransactionParameters_get_funding_outpoint(const struct LDKChannelTransactionParameters *NONNULL_PTR this_ptr);
+
+/**
+ * The late-bound funding outpoint
+ */
+void ChannelTransactionParameters_set_funding_outpoint(struct LDKChannelTransactionParameters *NONNULL_PTR this_ptr, struct LDKOutPoint val);
+
+MUST_USE_RES struct LDKChannelTransactionParameters ChannelTransactionParameters_new(struct LDKChannelPublicKeys holder_pubkeys_arg, uint16_t holder_selected_contest_delay_arg, bool is_outbound_from_holder_arg, struct LDKCounterpartyChannelTransactionParameters counterparty_parameters_arg, struct LDKOutPoint funding_outpoint_arg);
+
+struct LDKChannelTransactionParameters ChannelTransactionParameters_clone(const struct LDKChannelTransactionParameters *NONNULL_PTR orig);
+
+void CounterpartyChannelTransactionParameters_free(struct LDKCounterpartyChannelTransactionParameters this_ptr);
+
+/**
+ * Counter-party public keys
+ */
+struct LDKChannelPublicKeys CounterpartyChannelTransactionParameters_get_pubkeys(const struct LDKCounterpartyChannelTransactionParameters *NONNULL_PTR this_ptr);
+
+/**
+ * Counter-party public keys
+ */
+void CounterpartyChannelTransactionParameters_set_pubkeys(struct LDKCounterpartyChannelTransactionParameters *NONNULL_PTR this_ptr, struct LDKChannelPublicKeys val);
+
+/**
+ * The contest delay selected by the counterparty, which applies to holder-broadcast transactions
+ */
+uint16_t CounterpartyChannelTransactionParameters_get_selected_contest_delay(const struct LDKCounterpartyChannelTransactionParameters *NONNULL_PTR this_ptr);
+
+/**
+ * The contest delay selected by the counterparty, which applies to holder-broadcast transactions
+ */
+void CounterpartyChannelTransactionParameters_set_selected_contest_delay(struct LDKCounterpartyChannelTransactionParameters *NONNULL_PTR this_ptr, uint16_t val);
+
+MUST_USE_RES struct LDKCounterpartyChannelTransactionParameters CounterpartyChannelTransactionParameters_new(struct LDKChannelPublicKeys pubkeys_arg, uint16_t selected_contest_delay_arg);
+
+struct LDKCounterpartyChannelTransactionParameters CounterpartyChannelTransactionParameters_clone(const struct LDKCounterpartyChannelTransactionParameters *NONNULL_PTR orig);
+
+/**
+ * Whether the late bound parameters are populated.
+ */
+MUST_USE_RES bool ChannelTransactionParameters_is_populated(const struct LDKChannelTransactionParameters *NONNULL_PTR this_arg);
+
+/**
+ * Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
+ * given that the holder is the broadcaster.
+ *
+ * self.is_populated() must be true before calling this function.
+ */
+MUST_USE_RES struct LDKDirectedChannelTransactionParameters ChannelTransactionParameters_as_holder_broadcastable(const struct LDKChannelTransactionParameters *NONNULL_PTR this_arg);
+
+/**
+ * Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
+ * given that the counterparty is the broadcaster.
+ *
+ * self.is_populated() must be true before calling this function.
+ */
+MUST_USE_RES struct LDKDirectedChannelTransactionParameters ChannelTransactionParameters_as_counterparty_broadcastable(const struct LDKChannelTransactionParameters *NONNULL_PTR this_arg);
+
+struct LDKCVec_u8Z CounterpartyChannelTransactionParameters_write(const struct LDKCounterpartyChannelTransactionParameters *NONNULL_PTR obj);
+
+struct LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZ CounterpartyChannelTransactionParameters_read(struct LDKu8slice ser);
+
+struct LDKCVec_u8Z ChannelTransactionParameters_write(const struct LDKChannelTransactionParameters *NONNULL_PTR obj);
+
+struct LDKCResult_ChannelTransactionParametersDecodeErrorZ ChannelTransactionParameters_read(struct LDKu8slice ser);
+
+void DirectedChannelTransactionParameters_free(struct LDKDirectedChannelTransactionParameters this_ptr);
+
+/**
+ * Get the channel pubkeys for the broadcaster
+ */
+MUST_USE_RES struct LDKChannelPublicKeys DirectedChannelTransactionParameters_broadcaster_pubkeys(const struct LDKDirectedChannelTransactionParameters *NONNULL_PTR this_arg);
+
+/**
+ * Get the channel pubkeys for the countersignatory
+ */
+MUST_USE_RES struct LDKChannelPublicKeys DirectedChannelTransactionParameters_countersignatory_pubkeys(const struct LDKDirectedChannelTransactionParameters *NONNULL_PTR this_arg);
+
+/**
+ * Get the contest delay applicable to the transactions.
+ * Note that the contest delay was selected by the countersignatory.
+ */
+MUST_USE_RES uint16_t DirectedChannelTransactionParameters_contest_delay(const struct LDKDirectedChannelTransactionParameters *NONNULL_PTR this_arg);
+
+/**
+ * Whether the channel is outbound from the broadcaster.
+ *
+ * The boolean representing the side that initiated the channel is
+ * an input to the commitment number obscure factor computation.
+ */
+MUST_USE_RES bool DirectedChannelTransactionParameters_is_outbound(const struct LDKDirectedChannelTransactionParameters *NONNULL_PTR this_arg);
 
-void HolderCommitmentTransaction_free(LDKHolderCommitmentTransaction this_ptr);
+/**
+ * The funding outpoint
+ */
+MUST_USE_RES struct LDKOutPoint DirectedChannelTransactionParameters_funding_outpoint(const struct LDKDirectedChannelTransactionParameters *NONNULL_PTR this_arg);
 
-LDKHolderCommitmentTransaction HolderCommitmentTransaction_clone(const LDKHolderCommitmentTransaction *orig);
+void HolderCommitmentTransaction_free(struct LDKHolderCommitmentTransaction this_ptr);
 
 /**
- * The commitment transaction itself, in unsigned form.
+ * Our counterparty's signature for the transaction
  */
-LDKTransaction HolderCommitmentTransaction_get_unsigned_tx(const LDKHolderCommitmentTransaction *this_ptr);
+struct LDKSignature HolderCommitmentTransaction_get_counterparty_sig(const struct LDKHolderCommitmentTransaction *NONNULL_PTR this_ptr);
 
 /**
- * The commitment transaction itself, in unsigned form.
+ * Our counterparty's signature for the transaction
  */
-void HolderCommitmentTransaction_set_unsigned_tx(LDKHolderCommitmentTransaction *this_ptr, LDKTransaction val);
+void HolderCommitmentTransaction_set_counterparty_sig(struct LDKHolderCommitmentTransaction *NONNULL_PTR this_ptr, struct LDKSignature val);
 
 /**
- * Our counterparty's signature for the transaction, above.
+ * All non-dust counterparty HTLC signatures, in the order they appear in the transaction
  */
-LDKSignature HolderCommitmentTransaction_get_counterparty_sig(const LDKHolderCommitmentTransaction *this_ptr);
+void HolderCommitmentTransaction_set_counterparty_htlc_sigs(struct LDKHolderCommitmentTransaction *NONNULL_PTR this_ptr, struct LDKCVec_SignatureZ val);
+
+struct LDKHolderCommitmentTransaction HolderCommitmentTransaction_clone(const struct LDKHolderCommitmentTransaction *NONNULL_PTR orig);
+
+struct LDKCVec_u8Z HolderCommitmentTransaction_write(const struct LDKHolderCommitmentTransaction *NONNULL_PTR obj);
+
+struct LDKCResult_HolderCommitmentTransactionDecodeErrorZ HolderCommitmentTransaction_read(struct LDKu8slice ser);
 
 /**
- * Our counterparty's signature for the transaction, above.
+ * Create a new holder transaction with the given counterparty signatures.
+ * The funding keys are used to figure out which signature should go first when building the transaction for broadcast.
  */
-void HolderCommitmentTransaction_set_counterparty_sig(LDKHolderCommitmentTransaction *this_ptr, LDKSignature val);
+MUST_USE_RES struct LDKHolderCommitmentTransaction HolderCommitmentTransaction_new(struct LDKCommitmentTransaction commitment_tx, struct LDKSignature counterparty_sig, struct LDKCVec_SignatureZ counterparty_htlc_sigs, struct LDKPublicKey holder_funding_key, struct LDKPublicKey counterparty_funding_key);
+
+void BuiltCommitmentTransaction_free(struct LDKBuiltCommitmentTransaction this_ptr);
 
 /**
- * The feerate paid per 1000-weight-unit in this commitment transaction. This value is
- * controlled by the channel initiator.
+ * The commitment transaction
  */
-uint32_t HolderCommitmentTransaction_get_feerate_per_kw(const LDKHolderCommitmentTransaction *this_ptr);
+struct LDKTransaction BuiltCommitmentTransaction_get_transaction(const struct LDKBuiltCommitmentTransaction *NONNULL_PTR this_ptr);
 
 /**
- * The feerate paid per 1000-weight-unit in this commitment transaction. This value is
- * controlled by the channel initiator.
+ * The commitment transaction
  */
-void HolderCommitmentTransaction_set_feerate_per_kw(LDKHolderCommitmentTransaction *this_ptr, uint32_t val);
+void BuiltCommitmentTransaction_set_transaction(struct LDKBuiltCommitmentTransaction *NONNULL_PTR this_ptr, struct LDKTransaction val);
 
 /**
- * The HTLCs and counterparty htlc signatures which were included in this commitment transaction.
+ * The txid for the commitment transaction.
  *
- * Note that this includes all HTLCs, including ones which were considered dust and not
- * actually included in the transaction as it appears on-chain, but who's value is burned as
- * fees and not included in the to_holder or to_counterparty outputs.
+ * This is provided as a performance optimization, instead of calling transaction.txid()
+ * multiple times.
+ */
+const uint8_t (*BuiltCommitmentTransaction_get_txid(const struct LDKBuiltCommitmentTransaction *NONNULL_PTR this_ptr))[32];
+
+/**
+ * The txid for the commitment transaction.
  *
- * The counterparty HTLC signatures in the second element will always be set for non-dust HTLCs, ie
- * those for which transaction_output_index.is_some().
+ * This is provided as a performance optimization, instead of calling transaction.txid()
+ * multiple times.
  */
-void HolderCommitmentTransaction_set_per_htlc(LDKHolderCommitmentTransaction *this_ptr, LDKCVec_C2Tuple_HTLCOutputInCommitmentSignatureZZ val);
+void BuiltCommitmentTransaction_set_txid(struct LDKBuiltCommitmentTransaction *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
+
+MUST_USE_RES struct LDKBuiltCommitmentTransaction BuiltCommitmentTransaction_new(struct LDKTransaction transaction_arg, struct LDKThirtyTwoBytes txid_arg);
+
+struct LDKBuiltCommitmentTransaction BuiltCommitmentTransaction_clone(const struct LDKBuiltCommitmentTransaction *NONNULL_PTR orig);
+
+struct LDKCVec_u8Z BuiltCommitmentTransaction_write(const struct LDKBuiltCommitmentTransaction *NONNULL_PTR obj);
+
+struct LDKCResult_BuiltCommitmentTransactionDecodeErrorZ BuiltCommitmentTransaction_read(struct LDKu8slice ser);
 
 /**
- * Generate a new HolderCommitmentTransaction based on a raw commitment transaction,
- * counterparty signature and both parties keys.
+ * Get the SIGHASH_ALL sighash value of the transaction.
  *
- * The unsigned transaction outputs must be consistent with htlc_data.  This function
- * only checks that the shape and amounts are consistent, but does not check the scriptPubkey.
+ * This can be used to verify a signature.
  */
-MUST_USE_RES LDKHolderCommitmentTransaction HolderCommitmentTransaction_new_missing_holder_sig(LDKTransaction unsigned_tx, LDKSignature counterparty_sig, LDKPublicKey holder_funding_key, LDKPublicKey counterparty_funding_key, LDKTxCreationKeys keys, uint32_t feerate_per_kw, LDKCVec_C2Tuple_HTLCOutputInCommitmentSignatureZZ htlc_data);
+MUST_USE_RES struct LDKThirtyTwoBytes BuiltCommitmentTransaction_get_sighash_all(const struct LDKBuiltCommitmentTransaction *NONNULL_PTR this_arg, struct LDKu8slice funding_redeemscript, uint64_t channel_value_satoshis);
 
 /**
- * The pre-calculated transaction creation public keys.
- * An external validating signer should not trust these keys.
+ * Sign a transaction, either because we are counter-signing the counterparty's transaction or
+ * because we are about to broadcast a holder transaction.
+ */
+MUST_USE_RES struct LDKSignature BuiltCommitmentTransaction_sign(const struct LDKBuiltCommitmentTransaction *NONNULL_PTR this_arg, const uint8_t (*funding_key)[32], struct LDKu8slice funding_redeemscript, uint64_t channel_value_satoshis);
+
+void CommitmentTransaction_free(struct LDKCommitmentTransaction this_ptr);
+
+struct LDKCommitmentTransaction CommitmentTransaction_clone(const struct LDKCommitmentTransaction *NONNULL_PTR orig);
+
+struct LDKCVec_u8Z CommitmentTransaction_write(const struct LDKCommitmentTransaction *NONNULL_PTR obj);
+
+struct LDKCResult_CommitmentTransactionDecodeErrorZ CommitmentTransaction_read(struct LDKu8slice ser);
+
+/**
+ * The backwards-counting commitment number
+ */
+MUST_USE_RES uint64_t CommitmentTransaction_commitment_number(const struct LDKCommitmentTransaction *NONNULL_PTR this_arg);
+
+/**
+ * The value to be sent to the broadcaster
+ */
+MUST_USE_RES uint64_t CommitmentTransaction_to_broadcaster_value_sat(const struct LDKCommitmentTransaction *NONNULL_PTR this_arg);
+
+/**
+ * The value to be sent to the counterparty
  */
-MUST_USE_RES LDKTxCreationKeys HolderCommitmentTransaction_trust_key_derivation(const LDKHolderCommitmentTransaction *this_arg);
+MUST_USE_RES uint64_t CommitmentTransaction_to_countersignatory_value_sat(const struct LDKCommitmentTransaction *NONNULL_PTR this_arg);
 
 /**
- * Get the txid of the holder commitment transaction contained in this
- * HolderCommitmentTransaction
+ * The feerate paid per 1000-weight-unit in this commitment transaction.
+ */
+MUST_USE_RES uint32_t CommitmentTransaction_feerate_per_kw(const struct LDKCommitmentTransaction *NONNULL_PTR this_arg);
+
+/**
+ * Trust our pre-built transaction and derived transaction creation public keys.
+ *
+ * Applies a wrapper which allows access to these fields.
+ *
+ * This should only be used if you fully trust the builder of this object.  It should not
+ *\tbe used by an external signer - instead use the verify function.
  */
-MUST_USE_RES LDKThirtyTwoBytes HolderCommitmentTransaction_txid(const LDKHolderCommitmentTransaction *this_arg);
+MUST_USE_RES struct LDKTrustedCommitmentTransaction CommitmentTransaction_trust(const struct LDKCommitmentTransaction *NONNULL_PTR this_arg);
 
 /**
- * Gets holder signature for the contained commitment transaction given holder funding private key.
+ * Verify our pre-built transaction and derived transaction creation public keys.
+ *
+ * Applies a wrapper which allows access to these fields.
  *
- * Funding key is your key included in the 2-2 funding_outpoint lock. Should be provided
- * by your ChannelKeys.
- * Funding redeemscript is script locking funding_outpoint. This is the mutlsig script
- * between your own funding key and your counterparty's. Currently, this is provided in
- * ChannelKeys::sign_holder_commitment() calls directly.
- * Channel value is amount locked in funding_outpoint.
+ * An external validating signer must call this method before signing
+ * or using the built transaction.
+ */
+MUST_USE_RES struct LDKCResult_TrustedCommitmentTransactionNoneZ CommitmentTransaction_verify(const struct LDKCommitmentTransaction *NONNULL_PTR this_arg, const struct LDKDirectedChannelTransactionParameters *NONNULL_PTR channel_parameters, const struct LDKChannelPublicKeys *NONNULL_PTR broadcaster_keys, const struct LDKChannelPublicKeys *NONNULL_PTR countersignatory_keys);
+
+void TrustedCommitmentTransaction_free(struct LDKTrustedCommitmentTransaction this_ptr);
+
+/**
+ * The transaction ID of the built Bitcoin transaction
+ */
+MUST_USE_RES struct LDKThirtyTwoBytes TrustedCommitmentTransaction_txid(const struct LDKTrustedCommitmentTransaction *NONNULL_PTR this_arg);
+
+/**
+ * The pre-built Bitcoin commitment transaction
+ */
+MUST_USE_RES struct LDKBuiltCommitmentTransaction TrustedCommitmentTransaction_built_transaction(const struct LDKTrustedCommitmentTransaction *NONNULL_PTR this_arg);
+
+/**
+ * The pre-calculated transaction creation public keys.
  */
-MUST_USE_RES LDKSignature HolderCommitmentTransaction_get_holder_sig(const LDKHolderCommitmentTransaction *this_arg, const uint8_t (*funding_key)[32], LDKu8slice funding_redeemscript, uint64_t channel_value_satoshis);
+MUST_USE_RES struct LDKTxCreationKeys TrustedCommitmentTransaction_keys(const struct LDKTrustedCommitmentTransaction *NONNULL_PTR this_arg);
 
 /**
  * Get a signature for each HTLC which was included in the commitment transaction (ie for
  * which HTLCOutputInCommitment::transaction_output_index.is_some()).
  *
- * The returned Vec has one entry for each HTLC, and in the same order. For HTLCs which were
- * considered dust and not included, a None entry exists, for all others a signature is
- * included.
+ * The returned Vec has one entry for each HTLC, and in the same order.
+ */
+MUST_USE_RES struct LDKCResult_CVec_SignatureZNoneZ TrustedCommitmentTransaction_get_htlc_sigs(const struct LDKTrustedCommitmentTransaction *NONNULL_PTR this_arg, const uint8_t (*htlc_base_key)[32], const struct LDKDirectedChannelTransactionParameters *NONNULL_PTR channel_parameters);
+
+/**
+ * Get the transaction number obscure factor
+ */
+uint64_t get_commitment_transaction_number_obscure_factor(struct LDKPublicKey broadcaster_payment_basepoint, struct LDKPublicKey countersignatory_payment_basepoint, bool outbound_from_broadcaster);
+
+struct LDKInitFeatures InitFeatures_clone(const struct LDKInitFeatures *NONNULL_PTR orig);
+
+struct LDKNodeFeatures NodeFeatures_clone(const struct LDKNodeFeatures *NONNULL_PTR orig);
+
+struct LDKChannelFeatures ChannelFeatures_clone(const struct LDKChannelFeatures *NONNULL_PTR orig);
+
+void InitFeatures_free(struct LDKInitFeatures this_ptr);
+
+void NodeFeatures_free(struct LDKNodeFeatures this_ptr);
+
+void ChannelFeatures_free(struct LDKChannelFeatures this_ptr);
+
+/**
+ * Create a blank Features with no features set
+ */
+MUST_USE_RES struct LDKInitFeatures InitFeatures_empty(void);
+
+/**
+ * Creates features known by the implementation as defined by [`T::KNOWN_FEATURE_FLAGS`].
+ *
+ * [`T::KNOWN_FEATURE_FLAGS`]: sealed/trait.Context.html#associatedconstant.KNOWN_FEATURE_FLAGS
+ */
+MUST_USE_RES struct LDKInitFeatures InitFeatures_known(void);
+
+/**
+ * Create a blank Features with no features set
+ */
+MUST_USE_RES struct LDKNodeFeatures NodeFeatures_empty(void);
+
+/**
+ * Creates features known by the implementation as defined by [`T::KNOWN_FEATURE_FLAGS`].
+ *
+ * [`T::KNOWN_FEATURE_FLAGS`]: sealed/trait.Context.html#associatedconstant.KNOWN_FEATURE_FLAGS
+ */
+MUST_USE_RES struct LDKNodeFeatures NodeFeatures_known(void);
+
+/**
+ * Create a blank Features with no features set
+ */
+MUST_USE_RES struct LDKChannelFeatures ChannelFeatures_empty(void);
+
+/**
+ * Creates features known by the implementation as defined by [`T::KNOWN_FEATURE_FLAGS`].
+ *
+ * [`T::KNOWN_FEATURE_FLAGS`]: sealed/trait.Context.html#associatedconstant.KNOWN_FEATURE_FLAGS
  */
-MUST_USE_RES LDKCResult_CVec_SignatureZNoneZ HolderCommitmentTransaction_get_htlc_sigs(const LDKHolderCommitmentTransaction *this_arg, const uint8_t (*htlc_base_key)[32], uint16_t counterparty_selected_contest_delay);
+MUST_USE_RES struct LDKChannelFeatures ChannelFeatures_known(void);
 
-LDKCVec_u8Z HolderCommitmentTransaction_write(const LDKHolderCommitmentTransaction *obj);
+struct LDKCVec_u8Z InitFeatures_write(const struct LDKInitFeatures *NONNULL_PTR obj);
 
-LDKHolderCommitmentTransaction HolderCommitmentTransaction_read(LDKu8slice ser);
+struct LDKCVec_u8Z NodeFeatures_write(const struct LDKNodeFeatures *NONNULL_PTR obj);
 
-void InitFeatures_free(LDKInitFeatures this_ptr);
+struct LDKCVec_u8Z ChannelFeatures_write(const struct LDKChannelFeatures *NONNULL_PTR obj);
 
-void NodeFeatures_free(LDKNodeFeatures this_ptr);
+struct LDKCResult_InitFeaturesDecodeErrorZ InitFeatures_read(struct LDKu8slice ser);
 
-void ChannelFeatures_free(LDKChannelFeatures this_ptr);
+struct LDKCResult_NodeFeaturesDecodeErrorZ NodeFeatures_read(struct LDKu8slice ser);
 
-void RouteHop_free(LDKRouteHop this_ptr);
+struct LDKCResult_ChannelFeaturesDecodeErrorZ ChannelFeatures_read(struct LDKu8slice ser);
 
-LDKRouteHop RouteHop_clone(const LDKRouteHop *orig);
+void RouteHop_free(struct LDKRouteHop this_ptr);
 
 /**
  * The node_id of the node at this hop.
  */
-LDKPublicKey RouteHop_get_pubkey(const LDKRouteHop *this_ptr);
+struct LDKPublicKey RouteHop_get_pubkey(const struct LDKRouteHop *NONNULL_PTR this_ptr);
 
 /**
  * The node_id of the node at this hop.
  */
-void RouteHop_set_pubkey(LDKRouteHop *this_ptr, LDKPublicKey val);
+void RouteHop_set_pubkey(struct LDKRouteHop *NONNULL_PTR this_ptr, struct LDKPublicKey val);
 
 /**
  * The node_announcement features of the node at this hop. For the last hop, these may be
  * amended to match the features present in the invoice this node generated.
  */
-LDKNodeFeatures RouteHop_get_node_features(const LDKRouteHop *this_ptr);
+struct LDKNodeFeatures RouteHop_get_node_features(const struct LDKRouteHop *NONNULL_PTR this_ptr);
 
 /**
  * The node_announcement features of the node at this hop. For the last hop, these may be
  * amended to match the features present in the invoice this node generated.
  */
-void RouteHop_set_node_features(LDKRouteHop *this_ptr, LDKNodeFeatures val);
+void RouteHop_set_node_features(struct LDKRouteHop *NONNULL_PTR this_ptr, struct LDKNodeFeatures val);
 
 /**
  * The channel that should be used from the previous hop to reach this node.
  */
-uint64_t RouteHop_get_short_channel_id(const LDKRouteHop *this_ptr);
+uint64_t RouteHop_get_short_channel_id(const struct LDKRouteHop *NONNULL_PTR this_ptr);
 
 /**
  * The channel that should be used from the previous hop to reach this node.
  */
-void RouteHop_set_short_channel_id(LDKRouteHop *this_ptr, uint64_t val);
+void RouteHop_set_short_channel_id(struct LDKRouteHop *NONNULL_PTR this_ptr, uint64_t val);
 
 /**
  * The channel_announcement features of the channel that should be used from the previous hop
  * to reach this node.
  */
-LDKChannelFeatures RouteHop_get_channel_features(const LDKRouteHop *this_ptr);
+struct LDKChannelFeatures RouteHop_get_channel_features(const struct LDKRouteHop *NONNULL_PTR this_ptr);
 
 /**
  * The channel_announcement features of the channel that should be used from the previous hop
  * to reach this node.
  */
-void RouteHop_set_channel_features(LDKRouteHop *this_ptr, LDKChannelFeatures val);
+void RouteHop_set_channel_features(struct LDKRouteHop *NONNULL_PTR this_ptr, struct LDKChannelFeatures val);
 
 /**
  * The fee taken on this hop. For the last hop, this should be the full value of the payment.
  */
-uint64_t RouteHop_get_fee_msat(const LDKRouteHop *this_ptr);
+uint64_t RouteHop_get_fee_msat(const struct LDKRouteHop *NONNULL_PTR this_ptr);
 
 /**
  * The fee taken on this hop. For the last hop, this should be the full value of the payment.
  */
-void RouteHop_set_fee_msat(LDKRouteHop *this_ptr, uint64_t val);
+void RouteHop_set_fee_msat(struct LDKRouteHop *NONNULL_PTR this_ptr, uint64_t val);
 
 /**
  * The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
  * expected at the destination, in excess of the current block height.
  */
-uint32_t RouteHop_get_cltv_expiry_delta(const LDKRouteHop *this_ptr);
+uint32_t RouteHop_get_cltv_expiry_delta(const struct LDKRouteHop *NONNULL_PTR this_ptr);
 
 /**
  * The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
  * expected at the destination, in excess of the current block height.
  */
-void RouteHop_set_cltv_expiry_delta(LDKRouteHop *this_ptr, uint32_t val);
+void RouteHop_set_cltv_expiry_delta(struct LDKRouteHop *NONNULL_PTR this_ptr, uint32_t val);
 
-MUST_USE_RES LDKRouteHop RouteHop_new(LDKPublicKey pubkey_arg, LDKNodeFeatures node_features_arg, uint64_t short_channel_id_arg, LDKChannelFeatures channel_features_arg, uint64_t fee_msat_arg, uint32_t cltv_expiry_delta_arg);
+MUST_USE_RES struct LDKRouteHop RouteHop_new(struct LDKPublicKey pubkey_arg, struct LDKNodeFeatures node_features_arg, uint64_t short_channel_id_arg, struct LDKChannelFeatures channel_features_arg, uint64_t fee_msat_arg, uint32_t cltv_expiry_delta_arg);
 
-void Route_free(LDKRoute this_ptr);
+struct LDKRouteHop RouteHop_clone(const struct LDKRouteHop *NONNULL_PTR orig);
 
-LDKRoute Route_clone(const LDKRoute *orig);
+void Route_free(struct LDKRoute this_ptr);
 
 /**
  * The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
@@ -6867,69 +8726,71 @@ LDKRoute Route_clone(const LDKRoute *orig);
  * given path is variable, keeping the length of any path to less than 20 should currently
  * ensure it is viable.
  */
-void Route_set_paths(LDKRoute *this_ptr, LDKCVec_CVec_RouteHopZZ val);
+void Route_set_paths(struct LDKRoute *NONNULL_PTR this_ptr, struct LDKCVec_CVec_RouteHopZZ val);
 
-MUST_USE_RES LDKRoute Route_new(LDKCVec_CVec_RouteHopZZ paths_arg);
+MUST_USE_RES struct LDKRoute Route_new(struct LDKCVec_CVec_RouteHopZZ paths_arg);
 
-LDKCVec_u8Z Route_write(const LDKRoute *obj);
+struct LDKRoute Route_clone(const struct LDKRoute *NONNULL_PTR orig);
 
-LDKRoute Route_read(LDKu8slice ser);
+struct LDKCVec_u8Z Route_write(const struct LDKRoute *NONNULL_PTR obj);
 
-void RouteHint_free(LDKRouteHint this_ptr);
+struct LDKCResult_RouteDecodeErrorZ Route_read(struct LDKu8slice ser);
 
-LDKRouteHint RouteHint_clone(const LDKRouteHint *orig);
+void RouteHint_free(struct LDKRouteHint this_ptr);
 
 /**
  * The node_id of the non-target end of the route
  */
-LDKPublicKey RouteHint_get_src_node_id(const LDKRouteHint *this_ptr);
+struct LDKPublicKey RouteHint_get_src_node_id(const struct LDKRouteHint *NONNULL_PTR this_ptr);
 
 /**
  * The node_id of the non-target end of the route
  */
-void RouteHint_set_src_node_id(LDKRouteHint *this_ptr, LDKPublicKey val);
+void RouteHint_set_src_node_id(struct LDKRouteHint *NONNULL_PTR this_ptr, struct LDKPublicKey val);
 
 /**
  * The short_channel_id of this channel
  */
-uint64_t RouteHint_get_short_channel_id(const LDKRouteHint *this_ptr);
+uint64_t RouteHint_get_short_channel_id(const struct LDKRouteHint *NONNULL_PTR this_ptr);
 
 /**
  * The short_channel_id of this channel
  */
-void RouteHint_set_short_channel_id(LDKRouteHint *this_ptr, uint64_t val);
+void RouteHint_set_short_channel_id(struct LDKRouteHint *NONNULL_PTR this_ptr, uint64_t val);
 
 /**
  * The fees which must be paid to use this channel
  */
-LDKRoutingFees RouteHint_get_fees(const LDKRouteHint *this_ptr);
+struct LDKRoutingFees RouteHint_get_fees(const struct LDKRouteHint *NONNULL_PTR this_ptr);
 
 /**
  * The fees which must be paid to use this channel
  */
-void RouteHint_set_fees(LDKRouteHint *this_ptr, LDKRoutingFees val);
+void RouteHint_set_fees(struct LDKRouteHint *NONNULL_PTR this_ptr, struct LDKRoutingFees val);
 
 /**
  * The difference in CLTV values between this node and the next node.
  */
-uint16_t RouteHint_get_cltv_expiry_delta(const LDKRouteHint *this_ptr);
+uint16_t RouteHint_get_cltv_expiry_delta(const struct LDKRouteHint *NONNULL_PTR this_ptr);
 
 /**
  * The difference in CLTV values between this node and the next node.
  */
-void RouteHint_set_cltv_expiry_delta(LDKRouteHint *this_ptr, uint16_t val);
+void RouteHint_set_cltv_expiry_delta(struct LDKRouteHint *NONNULL_PTR this_ptr, uint16_t val);
 
 /**
  * The minimum value, in msat, which must be relayed to the next hop.
  */
-uint64_t RouteHint_get_htlc_minimum_msat(const LDKRouteHint *this_ptr);
+uint64_t RouteHint_get_htlc_minimum_msat(const struct LDKRouteHint *NONNULL_PTR this_ptr);
 
 /**
  * The minimum value, in msat, which must be relayed to the next hop.
  */
-void RouteHint_set_htlc_minimum_msat(LDKRouteHint *this_ptr, uint64_t val);
+void RouteHint_set_htlc_minimum_msat(struct LDKRouteHint *NONNULL_PTR this_ptr, uint64_t val);
+
+MUST_USE_RES struct LDKRouteHint RouteHint_new(struct LDKPublicKey src_node_id_arg, uint64_t short_channel_id_arg, struct LDKRoutingFees fees_arg, uint16_t cltv_expiry_delta_arg, uint64_t htlc_minimum_msat_arg);
 
-MUST_USE_RES LDKRouteHint RouteHint_new(LDKPublicKey src_node_id_arg, uint64_t short_channel_id_arg, LDKRoutingFees fees_arg, uint16_t cltv_expiry_delta_arg, uint64_t htlc_minimum_msat_arg);
+struct LDKRouteHint RouteHint_clone(const struct LDKRouteHint *NONNULL_PTR orig);
 
 /**
  * Gets a route from us to the given target node.
@@ -6949,13 +8810,15 @@ MUST_USE_RES LDKRouteHint RouteHint_new(LDKPublicKey src_node_id_arg, uint64_t s
  * equal), however the enabled/disabled bit on such channels as well as the htlc_minimum_msat
  * *is* checked as they may change based on the receiving node.
  */
-LDKCResult_RouteLightningErrorZ get_route(LDKPublicKey our_node_id, const LDKNetworkGraph *network, LDKPublicKey target, LDKCVec_ChannelDetailsZ *first_hops, LDKCVec_RouteHintZ last_hops, uint64_t final_value_msat, uint32_t final_cltv, LDKLogger logger);
+struct LDKCResult_RouteLightningErrorZ get_route(struct LDKPublicKey our_node_id, const struct LDKNetworkGraph *NONNULL_PTR network, struct LDKPublicKey target, struct LDKCVec_ChannelDetailsZ *first_hops, struct LDKCVec_RouteHintZ last_hops, uint64_t final_value_msat, uint32_t final_cltv, struct LDKLogger logger);
 
-void NetworkGraph_free(LDKNetworkGraph this_ptr);
+void NetworkGraph_free(struct LDKNetworkGraph this_ptr);
 
-void LockedNetworkGraph_free(LDKLockedNetworkGraph this_ptr);
+struct LDKNetworkGraph NetworkGraph_clone(const struct LDKNetworkGraph *NONNULL_PTR orig);
 
-void NetGraphMsgHandler_free(LDKNetGraphMsgHandler this_ptr);
+void LockedNetworkGraph_free(struct LDKLockedNetworkGraph this_ptr);
+
+void NetGraphMsgHandler_free(struct LDKNetGraphMsgHandler this_ptr);
 
 /**
  * Creates a new tracker of the actual state of the network of channels and nodes,
@@ -6964,13 +8827,13 @@ void NetGraphMsgHandler_free(LDKNetGraphMsgHandler this_ptr);
  * channel data is correct, and that the announcement is signed with
  * channel owners' keys.
  */
-MUST_USE_RES LDKNetGraphMsgHandler NetGraphMsgHandler_new(LDKAccess *chain_access, LDKLogger logger);
+MUST_USE_RES struct LDKNetGraphMsgHandler NetGraphMsgHandler_new(struct LDKThirtyTwoBytes genesis_hash, struct LDKAccess *chain_access, struct LDKLogger logger);
 
 /**
  * Creates a new tracker of the actual state of the network of channels and nodes,
  * assuming an existing Network Graph.
  */
-MUST_USE_RES LDKNetGraphMsgHandler NetGraphMsgHandler_from_net_graph(LDKAccess *chain_access, LDKLogger logger, LDKNetworkGraph network_graph);
+MUST_USE_RES struct LDKNetGraphMsgHandler NetGraphMsgHandler_from_net_graph(struct LDKAccess *chain_access, struct LDKLogger logger, struct LDKNetworkGraph network_graph);
 
 /**
  * Take a read lock on the network_graph and return it in the C-bindings
@@ -6978,58 +8841,70 @@ MUST_USE_RES LDKNetGraphMsgHandler NetGraphMsgHandler_from_net_graph(LDKAccess *
  * bindings as you can call `self.network_graph.read().unwrap()` in Rust
  * yourself.
  */
-MUST_USE_RES LDKLockedNetworkGraph NetGraphMsgHandler_read_locked_graph(const LDKNetGraphMsgHandler *this_arg);
+MUST_USE_RES struct LDKLockedNetworkGraph NetGraphMsgHandler_read_locked_graph(const struct LDKNetGraphMsgHandler *NONNULL_PTR this_arg);
 
 /**
  * Get a reference to the NetworkGraph which this read-lock contains.
  */
-MUST_USE_RES LDKNetworkGraph LockedNetworkGraph_graph(const LDKLockedNetworkGraph *this_arg);
+MUST_USE_RES struct LDKNetworkGraph LockedNetworkGraph_graph(const struct LDKLockedNetworkGraph *NONNULL_PTR this_arg);
+
+struct LDKRoutingMessageHandler NetGraphMsgHandler_as_RoutingMessageHandler(const struct LDKNetGraphMsgHandler *NONNULL_PTR this_arg);
 
-LDKRoutingMessageHandler NetGraphMsgHandler_as_RoutingMessageHandler(const LDKNetGraphMsgHandler *this_arg);
+struct LDKMessageSendEventsProvider NetGraphMsgHandler_as_MessageSendEventsProvider(const struct LDKNetGraphMsgHandler *NONNULL_PTR this_arg);
 
-void DirectionalChannelInfo_free(LDKDirectionalChannelInfo this_ptr);
+void DirectionalChannelInfo_free(struct LDKDirectionalChannelInfo this_ptr);
 
 /**
  * When the last update to the channel direction was issued.
  * Value is opaque, as set in the announcement.
  */
-uint32_t DirectionalChannelInfo_get_last_update(const LDKDirectionalChannelInfo *this_ptr);
+uint32_t DirectionalChannelInfo_get_last_update(const struct LDKDirectionalChannelInfo *NONNULL_PTR this_ptr);
 
 /**
  * When the last update to the channel direction was issued.
  * Value is opaque, as set in the announcement.
  */
-void DirectionalChannelInfo_set_last_update(LDKDirectionalChannelInfo *this_ptr, uint32_t val);
+void DirectionalChannelInfo_set_last_update(struct LDKDirectionalChannelInfo *NONNULL_PTR this_ptr, uint32_t val);
 
 /**
  * Whether the channel can be currently used for payments (in this one direction).
  */
-bool DirectionalChannelInfo_get_enabled(const LDKDirectionalChannelInfo *this_ptr);
+bool DirectionalChannelInfo_get_enabled(const struct LDKDirectionalChannelInfo *NONNULL_PTR this_ptr);
 
 /**
  * Whether the channel can be currently used for payments (in this one direction).
  */
-void DirectionalChannelInfo_set_enabled(LDKDirectionalChannelInfo *this_ptr, bool val);
+void DirectionalChannelInfo_set_enabled(struct LDKDirectionalChannelInfo *NONNULL_PTR this_ptr, bool val);
 
 /**
  * The difference in CLTV values that you must have when routing through this channel.
  */
-uint16_t DirectionalChannelInfo_get_cltv_expiry_delta(const LDKDirectionalChannelInfo *this_ptr);
+uint16_t DirectionalChannelInfo_get_cltv_expiry_delta(const struct LDKDirectionalChannelInfo *NONNULL_PTR this_ptr);
 
 /**
  * The difference in CLTV values that you must have when routing through this channel.
  */
-void DirectionalChannelInfo_set_cltv_expiry_delta(LDKDirectionalChannelInfo *this_ptr, uint16_t val);
+void DirectionalChannelInfo_set_cltv_expiry_delta(struct LDKDirectionalChannelInfo *NONNULL_PTR this_ptr, uint16_t val);
 
 /**
  * The minimum value, which must be relayed to the next hop via the channel
  */
-uint64_t DirectionalChannelInfo_get_htlc_minimum_msat(const LDKDirectionalChannelInfo *this_ptr);
+uint64_t DirectionalChannelInfo_get_htlc_minimum_msat(const struct LDKDirectionalChannelInfo *NONNULL_PTR this_ptr);
 
 /**
  * The minimum value, which must be relayed to the next hop via the channel
  */
-void DirectionalChannelInfo_set_htlc_minimum_msat(LDKDirectionalChannelInfo *this_ptr, uint64_t val);
+void DirectionalChannelInfo_set_htlc_minimum_msat(struct LDKDirectionalChannelInfo *NONNULL_PTR this_ptr, uint64_t val);
+
+/**
+ * Fees charged when the channel is used for routing
+ */
+struct LDKRoutingFees DirectionalChannelInfo_get_fees(const struct LDKDirectionalChannelInfo *NONNULL_PTR this_ptr);
+
+/**
+ * Fees charged when the channel is used for routing
+ */
+void DirectionalChannelInfo_set_fees(struct LDKDirectionalChannelInfo *NONNULL_PTR this_ptr, struct LDKRoutingFees val);
 
 /**
  * Most recent update for the channel received from the network
@@ -7037,7 +8912,7 @@ void DirectionalChannelInfo_set_htlc_minimum_msat(LDKDirectionalChannelInfo *thi
  * Everything else is useful only for sending out for initial routing sync.
  * Not stored if contains excess data to prevent DoS.
  */
-LDKChannelUpdate DirectionalChannelInfo_get_last_update_message(const LDKDirectionalChannelInfo *this_ptr);
+struct LDKChannelUpdate DirectionalChannelInfo_get_last_update_message(const struct LDKDirectionalChannelInfo *NONNULL_PTR this_ptr);
 
 /**
  * Most recent update for the channel received from the network
@@ -7045,63 +8920,65 @@ LDKChannelUpdate DirectionalChannelInfo_get_last_update_message(const LDKDirecti
  * Everything else is useful only for sending out for initial routing sync.
  * Not stored if contains excess data to prevent DoS.
  */
-void DirectionalChannelInfo_set_last_update_message(LDKDirectionalChannelInfo *this_ptr, LDKChannelUpdate val);
+void DirectionalChannelInfo_set_last_update_message(struct LDKDirectionalChannelInfo *NONNULL_PTR this_ptr, struct LDKChannelUpdate val);
 
-LDKCVec_u8Z DirectionalChannelInfo_write(const LDKDirectionalChannelInfo *obj);
+struct LDKDirectionalChannelInfo DirectionalChannelInfo_clone(const struct LDKDirectionalChannelInfo *NONNULL_PTR orig);
 
-LDKDirectionalChannelInfo DirectionalChannelInfo_read(LDKu8slice ser);
+struct LDKCVec_u8Z DirectionalChannelInfo_write(const struct LDKDirectionalChannelInfo *NONNULL_PTR obj);
 
-void ChannelInfo_free(LDKChannelInfo this_ptr);
+struct LDKCResult_DirectionalChannelInfoDecodeErrorZ DirectionalChannelInfo_read(struct LDKu8slice ser);
+
+void ChannelInfo_free(struct LDKChannelInfo this_ptr);
 
 /**
  * Protocol features of a channel communicated during its announcement
  */
-LDKChannelFeatures ChannelInfo_get_features(const LDKChannelInfo *this_ptr);
+struct LDKChannelFeatures ChannelInfo_get_features(const struct LDKChannelInfo *NONNULL_PTR this_ptr);
 
 /**
  * Protocol features of a channel communicated during its announcement
  */
-void ChannelInfo_set_features(LDKChannelInfo *this_ptr, LDKChannelFeatures val);
+void ChannelInfo_set_features(struct LDKChannelInfo *NONNULL_PTR this_ptr, struct LDKChannelFeatures val);
 
 /**
  * Source node of the first direction of a channel
  */
-LDKPublicKey ChannelInfo_get_node_one(const LDKChannelInfo *this_ptr);
+struct LDKPublicKey ChannelInfo_get_node_one(const struct LDKChannelInfo *NONNULL_PTR this_ptr);
 
 /**
  * Source node of the first direction of a channel
  */
-void ChannelInfo_set_node_one(LDKChannelInfo *this_ptr, LDKPublicKey val);
+void ChannelInfo_set_node_one(struct LDKChannelInfo *NONNULL_PTR this_ptr, struct LDKPublicKey val);
 
 /**
  * Details about the first direction of a channel
  */
-LDKDirectionalChannelInfo ChannelInfo_get_one_to_two(const LDKChannelInfo *this_ptr);
+struct LDKDirectionalChannelInfo ChannelInfo_get_one_to_two(const struct LDKChannelInfo *NONNULL_PTR this_ptr);
 
 /**
  * Details about the first direction of a channel
  */
-void ChannelInfo_set_one_to_two(LDKChannelInfo *this_ptr, LDKDirectionalChannelInfo val);
+void ChannelInfo_set_one_to_two(struct LDKChannelInfo *NONNULL_PTR this_ptr, struct LDKDirectionalChannelInfo val);
 
 /**
  * Source node of the second direction of a channel
  */
-LDKPublicKey ChannelInfo_get_node_two(const LDKChannelInfo *this_ptr);
+struct LDKPublicKey ChannelInfo_get_node_two(const struct LDKChannelInfo *NONNULL_PTR this_ptr);
 
 /**
  * Source node of the second direction of a channel
  */
-void ChannelInfo_set_node_two(LDKChannelInfo *this_ptr, LDKPublicKey val);
+void ChannelInfo_set_node_two(struct LDKChannelInfo *NONNULL_PTR this_ptr, struct LDKPublicKey val);
 
 /**
  * Details about the second direction of a channel
  */
-LDKDirectionalChannelInfo ChannelInfo_get_two_to_one(const LDKChannelInfo *this_ptr);
+struct LDKDirectionalChannelInfo ChannelInfo_get_two_to_one(const struct LDKChannelInfo *NONNULL_PTR this_ptr);
 
 /**
  * Details about the second direction of a channel
  */
-void ChannelInfo_set_two_to_one(LDKChannelInfo *this_ptr, LDKDirectionalChannelInfo val);
+void ChannelInfo_set_two_to_one(struct LDKChannelInfo *NONNULL_PTR this_ptr, struct LDKDirectionalChannelInfo val);
 
 /**
  * An initial announcement of the channel
@@ -7109,7 +8986,7 @@ void ChannelInfo_set_two_to_one(LDKChannelInfo *this_ptr, LDKDirectionalChannelI
  * Everything else is useful only for sending out for initial routing sync.
  * Not stored if contains excess data to prevent DoS.
  */
-LDKChannelAnnouncement ChannelInfo_get_announcement_message(const LDKChannelInfo *this_ptr);
+struct LDKChannelAnnouncement ChannelInfo_get_announcement_message(const struct LDKChannelInfo *NONNULL_PTR this_ptr);
 
 /**
  * An initial announcement of the channel
@@ -7117,96 +8994,98 @@ LDKChannelAnnouncement ChannelInfo_get_announcement_message(const LDKChannelInfo
  * Everything else is useful only for sending out for initial routing sync.
  * Not stored if contains excess data to prevent DoS.
  */
-void ChannelInfo_set_announcement_message(LDKChannelInfo *this_ptr, LDKChannelAnnouncement val);
+void ChannelInfo_set_announcement_message(struct LDKChannelInfo *NONNULL_PTR this_ptr, struct LDKChannelAnnouncement val);
 
-LDKCVec_u8Z ChannelInfo_write(const LDKChannelInfo *obj);
+struct LDKChannelInfo ChannelInfo_clone(const struct LDKChannelInfo *NONNULL_PTR orig);
 
-LDKChannelInfo ChannelInfo_read(LDKu8slice ser);
+struct LDKCVec_u8Z ChannelInfo_write(const struct LDKChannelInfo *NONNULL_PTR obj);
 
-void RoutingFees_free(LDKRoutingFees this_ptr);
+struct LDKCResult_ChannelInfoDecodeErrorZ ChannelInfo_read(struct LDKu8slice ser);
 
-LDKRoutingFees RoutingFees_clone(const LDKRoutingFees *orig);
+void RoutingFees_free(struct LDKRoutingFees this_ptr);
 
 /**
  * Flat routing fee in satoshis
  */
-uint32_t RoutingFees_get_base_msat(const LDKRoutingFees *this_ptr);
+uint32_t RoutingFees_get_base_msat(const struct LDKRoutingFees *NONNULL_PTR this_ptr);
 
 /**
  * Flat routing fee in satoshis
  */
-void RoutingFees_set_base_msat(LDKRoutingFees *this_ptr, uint32_t val);
+void RoutingFees_set_base_msat(struct LDKRoutingFees *NONNULL_PTR this_ptr, uint32_t val);
 
 /**
  * Liquidity-based routing fee in millionths of a routed amount.
  * In other words, 10000 is 1%.
  */
-uint32_t RoutingFees_get_proportional_millionths(const LDKRoutingFees *this_ptr);
+uint32_t RoutingFees_get_proportional_millionths(const struct LDKRoutingFees *NONNULL_PTR this_ptr);
 
 /**
  * Liquidity-based routing fee in millionths of a routed amount.
  * In other words, 10000 is 1%.
  */
-void RoutingFees_set_proportional_millionths(LDKRoutingFees *this_ptr, uint32_t val);
+void RoutingFees_set_proportional_millionths(struct LDKRoutingFees *NONNULL_PTR this_ptr, uint32_t val);
+
+MUST_USE_RES struct LDKRoutingFees RoutingFees_new(uint32_t base_msat_arg, uint32_t proportional_millionths_arg);
 
-MUST_USE_RES LDKRoutingFees RoutingFees_new(uint32_t base_msat_arg, uint32_t proportional_millionths_arg);
+struct LDKRoutingFees RoutingFees_clone(const struct LDKRoutingFees *NONNULL_PTR orig);
 
-LDKRoutingFees RoutingFees_read(LDKu8slice ser);
+struct LDKCResult_RoutingFeesDecodeErrorZ RoutingFees_read(struct LDKu8slice ser);
 
-LDKCVec_u8Z RoutingFees_write(const LDKRoutingFees *obj);
+struct LDKCVec_u8Z RoutingFees_write(const struct LDKRoutingFees *NONNULL_PTR obj);
 
-void NodeAnnouncementInfo_free(LDKNodeAnnouncementInfo this_ptr);
+void NodeAnnouncementInfo_free(struct LDKNodeAnnouncementInfo this_ptr);
 
 /**
  * Protocol features the node announced support for
  */
-LDKNodeFeatures NodeAnnouncementInfo_get_features(const LDKNodeAnnouncementInfo *this_ptr);
+struct LDKNodeFeatures NodeAnnouncementInfo_get_features(const struct LDKNodeAnnouncementInfo *NONNULL_PTR this_ptr);
 
 /**
  * Protocol features the node announced support for
  */
-void NodeAnnouncementInfo_set_features(LDKNodeAnnouncementInfo *this_ptr, LDKNodeFeatures val);
+void NodeAnnouncementInfo_set_features(struct LDKNodeAnnouncementInfo *NONNULL_PTR this_ptr, struct LDKNodeFeatures val);
 
 /**
  * When the last known update to the node state was issued.
  * Value is opaque, as set in the announcement.
  */
-uint32_t NodeAnnouncementInfo_get_last_update(const LDKNodeAnnouncementInfo *this_ptr);
+uint32_t NodeAnnouncementInfo_get_last_update(const struct LDKNodeAnnouncementInfo *NONNULL_PTR this_ptr);
 
 /**
  * When the last known update to the node state was issued.
  * Value is opaque, as set in the announcement.
  */
-void NodeAnnouncementInfo_set_last_update(LDKNodeAnnouncementInfo *this_ptr, uint32_t val);
+void NodeAnnouncementInfo_set_last_update(struct LDKNodeAnnouncementInfo *NONNULL_PTR this_ptr, uint32_t val);
 
 /**
  * Color assigned to the node
  */
-const uint8_t (*NodeAnnouncementInfo_get_rgb(const LDKNodeAnnouncementInfo *this_ptr))[3];
+const uint8_t (*NodeAnnouncementInfo_get_rgb(const struct LDKNodeAnnouncementInfo *NONNULL_PTR this_ptr))[3];
 
 /**
  * Color assigned to the node
  */
-void NodeAnnouncementInfo_set_rgb(LDKNodeAnnouncementInfo *this_ptr, LDKThreeBytes val);
+void NodeAnnouncementInfo_set_rgb(struct LDKNodeAnnouncementInfo *NONNULL_PTR this_ptr, struct LDKThreeBytes val);
 
 /**
  * Moniker assigned to the node.
  * May be invalid or malicious (eg control chars),
  * should not be exposed to the user.
  */
-const uint8_t (*NodeAnnouncementInfo_get_alias(const LDKNodeAnnouncementInfo *this_ptr))[32];
+const uint8_t (*NodeAnnouncementInfo_get_alias(const struct LDKNodeAnnouncementInfo *NONNULL_PTR this_ptr))[32];
 
 /**
  * Moniker assigned to the node.
  * May be invalid or malicious (eg control chars),
  * should not be exposed to the user.
  */
-void NodeAnnouncementInfo_set_alias(LDKNodeAnnouncementInfo *this_ptr, LDKThirtyTwoBytes val);
+void NodeAnnouncementInfo_set_alias(struct LDKNodeAnnouncementInfo *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
 
 /**
  * Internet-level addresses via which one can connect to the node
  */
-void NodeAnnouncementInfo_set_addresses(LDKNodeAnnouncementInfo *this_ptr, LDKCVec_NetAddressZ val);
+void NodeAnnouncementInfo_set_addresses(struct LDKNodeAnnouncementInfo *NONNULL_PTR this_ptr, struct LDKCVec_NetAddressZ val);
 
 /**
  * An initial announcement of the node
@@ -7214,7 +9093,7 @@ void NodeAnnouncementInfo_set_addresses(LDKNodeAnnouncementInfo *this_ptr, LDKCV
  * Everything else is useful only for sending out for initial routing sync.
  * Not stored if contains excess data to prevent DoS.
  */
-LDKNodeAnnouncement NodeAnnouncementInfo_get_announcement_message(const LDKNodeAnnouncementInfo *this_ptr);
+struct LDKNodeAnnouncement NodeAnnouncementInfo_get_announcement_message(const struct LDKNodeAnnouncementInfo *NONNULL_PTR this_ptr);
 
 /**
  * An initial announcement of the node
@@ -7222,63 +9101,67 @@ LDKNodeAnnouncement NodeAnnouncementInfo_get_announcement_message(const LDKNodeA
  * Everything else is useful only for sending out for initial routing sync.
  * Not stored if contains excess data to prevent DoS.
  */
-void NodeAnnouncementInfo_set_announcement_message(LDKNodeAnnouncementInfo *this_ptr, LDKNodeAnnouncement val);
+void NodeAnnouncementInfo_set_announcement_message(struct LDKNodeAnnouncementInfo *NONNULL_PTR this_ptr, struct LDKNodeAnnouncement val);
 
-MUST_USE_RES LDKNodeAnnouncementInfo NodeAnnouncementInfo_new(LDKNodeFeatures features_arg, uint32_t last_update_arg, LDKThreeBytes rgb_arg, LDKThirtyTwoBytes alias_arg, LDKCVec_NetAddressZ addresses_arg, LDKNodeAnnouncement announcement_message_arg);
+MUST_USE_RES struct LDKNodeAnnouncementInfo NodeAnnouncementInfo_new(struct LDKNodeFeatures features_arg, uint32_t last_update_arg, struct LDKThreeBytes rgb_arg, struct LDKThirtyTwoBytes alias_arg, struct LDKCVec_NetAddressZ addresses_arg, struct LDKNodeAnnouncement announcement_message_arg);
 
-LDKCVec_u8Z NodeAnnouncementInfo_write(const LDKNodeAnnouncementInfo *obj);
+struct LDKNodeAnnouncementInfo NodeAnnouncementInfo_clone(const struct LDKNodeAnnouncementInfo *NONNULL_PTR orig);
 
-LDKNodeAnnouncementInfo NodeAnnouncementInfo_read(LDKu8slice ser);
+struct LDKCVec_u8Z NodeAnnouncementInfo_write(const struct LDKNodeAnnouncementInfo *NONNULL_PTR obj);
 
-void NodeInfo_free(LDKNodeInfo this_ptr);
+struct LDKCResult_NodeAnnouncementInfoDecodeErrorZ NodeAnnouncementInfo_read(struct LDKu8slice ser);
+
+void NodeInfo_free(struct LDKNodeInfo this_ptr);
 
 /**
  * All valid channels a node has announced
  */
-void NodeInfo_set_channels(LDKNodeInfo *this_ptr, LDKCVec_u64Z val);
+void NodeInfo_set_channels(struct LDKNodeInfo *NONNULL_PTR this_ptr, struct LDKCVec_u64Z val);
 
 /**
  * Lowest fees enabling routing via any of the enabled, known channels to a node.
  * The two fields (flat and proportional fee) are independent,
  * meaning they don't have to refer to the same channel.
  */
-LDKRoutingFees NodeInfo_get_lowest_inbound_channel_fees(const LDKNodeInfo *this_ptr);
+struct LDKRoutingFees NodeInfo_get_lowest_inbound_channel_fees(const struct LDKNodeInfo *NONNULL_PTR this_ptr);
 
 /**
  * Lowest fees enabling routing via any of the enabled, known channels to a node.
  * The two fields (flat and proportional fee) are independent,
  * meaning they don't have to refer to the same channel.
  */
-void NodeInfo_set_lowest_inbound_channel_fees(LDKNodeInfo *this_ptr, LDKRoutingFees val);
+void NodeInfo_set_lowest_inbound_channel_fees(struct LDKNodeInfo *NONNULL_PTR this_ptr, struct LDKRoutingFees val);
 
 /**
  * More information about a node from node_announcement.
  * Optional because we store a Node entry after learning about it from
  * a channel announcement, but before receiving a node announcement.
  */
-LDKNodeAnnouncementInfo NodeInfo_get_announcement_info(const LDKNodeInfo *this_ptr);
+struct LDKNodeAnnouncementInfo NodeInfo_get_announcement_info(const struct LDKNodeInfo *NONNULL_PTR this_ptr);
 
 /**
  * More information about a node from node_announcement.
  * Optional because we store a Node entry after learning about it from
  * a channel announcement, but before receiving a node announcement.
  */
-void NodeInfo_set_announcement_info(LDKNodeInfo *this_ptr, LDKNodeAnnouncementInfo val);
+void NodeInfo_set_announcement_info(struct LDKNodeInfo *NONNULL_PTR this_ptr, struct LDKNodeAnnouncementInfo val);
+
+MUST_USE_RES struct LDKNodeInfo NodeInfo_new(struct LDKCVec_u64Z channels_arg, struct LDKRoutingFees lowest_inbound_channel_fees_arg, struct LDKNodeAnnouncementInfo announcement_info_arg);
 
-MUST_USE_RES LDKNodeInfo NodeInfo_new(LDKCVec_u64Z channels_arg, LDKRoutingFees lowest_inbound_channel_fees_arg, LDKNodeAnnouncementInfo announcement_info_arg);
+struct LDKNodeInfo NodeInfo_clone(const struct LDKNodeInfo *NONNULL_PTR orig);
 
-LDKCVec_u8Z NodeInfo_write(const LDKNodeInfo *obj);
+struct LDKCVec_u8Z NodeInfo_write(const struct LDKNodeInfo *NONNULL_PTR obj);
 
-LDKNodeInfo NodeInfo_read(LDKu8slice ser);
+struct LDKCResult_NodeInfoDecodeErrorZ NodeInfo_read(struct LDKu8slice ser);
 
-LDKCVec_u8Z NetworkGraph_write(const LDKNetworkGraph *obj);
+struct LDKCVec_u8Z NetworkGraph_write(const struct LDKNetworkGraph *NONNULL_PTR obj);
 
-LDKNetworkGraph NetworkGraph_read(LDKu8slice ser);
+struct LDKCResult_NetworkGraphDecodeErrorZ NetworkGraph_read(struct LDKu8slice ser);
 
 /**
  * Creates a new, empty, network graph.
  */
-MUST_USE_RES LDKNetworkGraph NetworkGraph_new(void);
+MUST_USE_RES struct LDKNetworkGraph NetworkGraph_new(struct LDKThirtyTwoBytes genesis_hash);
 
 /**
  * For an already known node (from channel announcements), update its stored properties from a
@@ -7288,7 +9171,7 @@ MUST_USE_RES LDKNetworkGraph NetworkGraph_new(void);
  * RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
  * routing messages from a source using a protocol other than the lightning P2P protocol.
  */
-MUST_USE_RES LDKCResult_NoneLightningErrorZ NetworkGraph_update_node_from_announcement(LDKNetworkGraph *this_arg, const LDKNodeAnnouncement *msg);
+MUST_USE_RES struct LDKCResult_NoneLightningErrorZ NetworkGraph_update_node_from_announcement(struct LDKNetworkGraph *NONNULL_PTR this_arg, const struct LDKNodeAnnouncement *NONNULL_PTR msg);
 
 /**
  * For an already known node (from channel announcements), update its stored properties from a
@@ -7296,7 +9179,7 @@ MUST_USE_RES LDKCResult_NoneLightningErrorZ NetworkGraph_update_node_from_announ
  * given the associated signatures here we cannot relay the node announcement to any of our
  * peers.
  */
-MUST_USE_RES LDKCResult_NoneLightningErrorZ NetworkGraph_update_node_from_unsigned_announcement(LDKNetworkGraph *this_arg, const LDKUnsignedNodeAnnouncement *msg);
+MUST_USE_RES struct LDKCResult_NoneLightningErrorZ NetworkGraph_update_node_from_unsigned_announcement(struct LDKNetworkGraph *NONNULL_PTR this_arg, const struct LDKUnsignedNodeAnnouncement *NONNULL_PTR msg);
 
 /**
  * Store or update channel info from a channel announcement.
@@ -7308,7 +9191,7 @@ MUST_USE_RES LDKCResult_NoneLightningErrorZ NetworkGraph_update_node_from_unsign
  * If a `chain::Access` object is provided via `chain_access`, it will be called to verify
  * the corresponding UTXO exists on chain and is correctly-formatted.
  */
-MUST_USE_RES LDKCResult_NoneLightningErrorZ NetworkGraph_update_channel_from_announcement(LDKNetworkGraph *this_arg, const LDKChannelAnnouncement *msg, LDKAccess *chain_access);
+MUST_USE_RES struct LDKCResult_NoneLightningErrorZ NetworkGraph_update_channel_from_announcement(struct LDKNetworkGraph *NONNULL_PTR this_arg, const struct LDKChannelAnnouncement *NONNULL_PTR msg, struct LDKAccess *chain_access);
 
 /**
  * Store or update channel info from a channel announcement without verifying the associated
@@ -7318,7 +9201,7 @@ MUST_USE_RES LDKCResult_NoneLightningErrorZ NetworkGraph_update_channel_from_ann
  * If a `chain::Access` object is provided via `chain_access`, it will be called to verify
  * the corresponding UTXO exists on chain and is correctly-formatted.
  */
-MUST_USE_RES LDKCResult_NoneLightningErrorZ NetworkGraph_update_channel_from_unsigned_announcement(LDKNetworkGraph *this_arg, const LDKUnsignedChannelAnnouncement *msg, LDKAccess *chain_access);
+MUST_USE_RES struct LDKCResult_NoneLightningErrorZ NetworkGraph_update_channel_from_unsigned_announcement(struct LDKNetworkGraph *NONNULL_PTR this_arg, const struct LDKUnsignedChannelAnnouncement *NONNULL_PTR msg, struct LDKAccess *chain_access);
 
 /**
  * Close a channel if a corresponding HTLC fail was sent.
@@ -7326,7 +9209,7 @@ MUST_USE_RES LDKCResult_NoneLightningErrorZ NetworkGraph_update_channel_from_uns
  * May cause the removal of nodes too, if this was their last channel.
  * If not permanent, makes channels unavailable for routing.
  */
-void NetworkGraph_close_channel_from_update(LDKNetworkGraph *this_arg, uint64_t short_channel_id, bool is_permanent);
+void NetworkGraph_close_channel_from_update(struct LDKNetworkGraph *NONNULL_PTR this_arg, uint64_t short_channel_id, bool is_permanent);
 
 /**
  * For an already known (from announcement) channel, update info about one of the directions
@@ -7336,13 +9219,13 @@ void NetworkGraph_close_channel_from_update(LDKNetworkGraph *this_arg, uint64_t
  * RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
  * routing messages from a source using a protocol other than the lightning P2P protocol.
  */
-MUST_USE_RES LDKCResult_NoneLightningErrorZ NetworkGraph_update_channel(LDKNetworkGraph *this_arg, const LDKChannelUpdate *msg);
+MUST_USE_RES struct LDKCResult_NoneLightningErrorZ NetworkGraph_update_channel(struct LDKNetworkGraph *NONNULL_PTR this_arg, const struct LDKChannelUpdate *NONNULL_PTR msg);
 
 /**
  * For an already known (from announcement) channel, update info about one of the directions
  * of the channel without verifying the associated signatures. Because we aren't given the
  * associated signatures here we cannot relay the channel update to any of our peers.
  */
-MUST_USE_RES LDKCResult_NoneLightningErrorZ NetworkGraph_update_channel_unsigned(LDKNetworkGraph *this_arg, const LDKUnsignedChannelUpdate *msg);
+MUST_USE_RES struct LDKCResult_NoneLightningErrorZ NetworkGraph_update_channel_unsigned(struct LDKNetworkGraph *NONNULL_PTR this_arg, const struct LDKUnsignedChannelUpdate *NONNULL_PTR msg);
 
 /* Text to put at the end of the generated file */
index 5f8b77f3f6e6dded34a149a189c37d179ca2a4cb..78193157c19c652b4fbf36fdacb9fa79509091f0 100644 (file)
 #include <string.h>
 namespace LDK {
-class Event {
+class APIError {
 private:
-       LDKEvent self;
+       LDKAPIError self;
 public:
-       Event(const Event&) = delete;
-       ~Event() { Event_free(self); }
-       Event(Event&& o) : self(o.self) { memset(&o, 0, sizeof(Event)); }
-       Event(LDKEvent&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKEvent)); }
-       operator LDKEvent() { LDKEvent res = self; memset(&self, 0, sizeof(LDKEvent)); return res; }
-       LDKEvent* operator &() { return &self; }
-       LDKEvent* operator ->() { return &self; }
-       const LDKEvent* operator &() const { return &self; }
-       const LDKEvent* operator ->() const { return &self; }
+       APIError(const APIError&) = delete;
+       APIError(APIError&& o) : self(o.self) { memset(&o, 0, sizeof(APIError)); }
+       APIError(LDKAPIError&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKAPIError)); }
+       operator LDKAPIError() && { LDKAPIError res = self; memset(&self, 0, sizeof(LDKAPIError)); return res; }
+       ~APIError() { APIError_free(self); }
+       APIError& operator=(APIError&& o) { APIError_free(self); self = o.self; memset(&o, 0, sizeof(APIError)); return *this; }
+       LDKAPIError* operator &() { return &self; }
+       LDKAPIError* operator ->() { return &self; }
+       const LDKAPIError* operator &() const { return &self; }
+       const LDKAPIError* operator ->() const { return &self; }
 };
-class MessageSendEvent {
+class TxCreationKeys {
 private:
-       LDKMessageSendEvent self;
+       LDKTxCreationKeys self;
 public:
-       MessageSendEvent(const MessageSendEvent&) = delete;
-       ~MessageSendEvent() { MessageSendEvent_free(self); }
-       MessageSendEvent(MessageSendEvent&& o) : self(o.self) { memset(&o, 0, sizeof(MessageSendEvent)); }
-       MessageSendEvent(LDKMessageSendEvent&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKMessageSendEvent)); }
-       operator LDKMessageSendEvent() { LDKMessageSendEvent res = self; memset(&self, 0, sizeof(LDKMessageSendEvent)); return res; }
-       LDKMessageSendEvent* operator &() { return &self; }
-       LDKMessageSendEvent* operator ->() { return &self; }
-       const LDKMessageSendEvent* operator &() const { return &self; }
-       const LDKMessageSendEvent* operator ->() const { return &self; }
+       TxCreationKeys(const TxCreationKeys&) = delete;
+       TxCreationKeys(TxCreationKeys&& o) : self(o.self) { memset(&o, 0, sizeof(TxCreationKeys)); }
+       TxCreationKeys(LDKTxCreationKeys&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKTxCreationKeys)); }
+       operator LDKTxCreationKeys() && { LDKTxCreationKeys res = self; memset(&self, 0, sizeof(LDKTxCreationKeys)); return res; }
+       ~TxCreationKeys() { TxCreationKeys_free(self); }
+       TxCreationKeys& operator=(TxCreationKeys&& o) { TxCreationKeys_free(self); self = o.self; memset(&o, 0, sizeof(TxCreationKeys)); return *this; }
+       LDKTxCreationKeys* operator &() { return &self; }
+       LDKTxCreationKeys* operator ->() { return &self; }
+       const LDKTxCreationKeys* operator &() const { return &self; }
+       const LDKTxCreationKeys* operator ->() const { return &self; }
 };
-class MessageSendEventsProvider {
+class ChannelPublicKeys {
 private:
-       LDKMessageSendEventsProvider self;
+       LDKChannelPublicKeys self;
 public:
-       MessageSendEventsProvider(const MessageSendEventsProvider&) = delete;
-       ~MessageSendEventsProvider() { MessageSendEventsProvider_free(self); }
-       MessageSendEventsProvider(MessageSendEventsProvider&& o) : self(o.self) { memset(&o, 0, sizeof(MessageSendEventsProvider)); }
-       MessageSendEventsProvider(LDKMessageSendEventsProvider&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKMessageSendEventsProvider)); }
-       operator LDKMessageSendEventsProvider() { LDKMessageSendEventsProvider res = self; memset(&self, 0, sizeof(LDKMessageSendEventsProvider)); return res; }
-       LDKMessageSendEventsProvider* operator &() { return &self; }
-       LDKMessageSendEventsProvider* operator ->() { return &self; }
-       const LDKMessageSendEventsProvider* operator &() const { return &self; }
-       const LDKMessageSendEventsProvider* operator ->() const { return &self; }
+       ChannelPublicKeys(const ChannelPublicKeys&) = delete;
+       ChannelPublicKeys(ChannelPublicKeys&& o) : self(o.self) { memset(&o, 0, sizeof(ChannelPublicKeys)); }
+       ChannelPublicKeys(LDKChannelPublicKeys&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKChannelPublicKeys)); }
+       operator LDKChannelPublicKeys() && { LDKChannelPublicKeys res = self; memset(&self, 0, sizeof(LDKChannelPublicKeys)); return res; }
+       ~ChannelPublicKeys() { ChannelPublicKeys_free(self); }
+       ChannelPublicKeys& operator=(ChannelPublicKeys&& o) { ChannelPublicKeys_free(self); self = o.self; memset(&o, 0, sizeof(ChannelPublicKeys)); return *this; }
+       LDKChannelPublicKeys* operator &() { return &self; }
+       LDKChannelPublicKeys* operator ->() { return &self; }
+       const LDKChannelPublicKeys* operator &() const { return &self; }
+       const LDKChannelPublicKeys* operator ->() const { return &self; }
 };
-class EventsProvider {
+class HTLCOutputInCommitment {
 private:
-       LDKEventsProvider self;
+       LDKHTLCOutputInCommitment self;
 public:
-       EventsProvider(const EventsProvider&) = delete;
-       ~EventsProvider() { EventsProvider_free(self); }
-       EventsProvider(EventsProvider&& o) : self(o.self) { memset(&o, 0, sizeof(EventsProvider)); }
-       EventsProvider(LDKEventsProvider&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKEventsProvider)); }
-       operator LDKEventsProvider() { LDKEventsProvider res = self; memset(&self, 0, sizeof(LDKEventsProvider)); return res; }
-       LDKEventsProvider* operator &() { return &self; }
-       LDKEventsProvider* operator ->() { return &self; }
-       const LDKEventsProvider* operator &() const { return &self; }
-       const LDKEventsProvider* operator ->() const { return &self; }
+       HTLCOutputInCommitment(const HTLCOutputInCommitment&) = delete;
+       HTLCOutputInCommitment(HTLCOutputInCommitment&& o) : self(o.self) { memset(&o, 0, sizeof(HTLCOutputInCommitment)); }
+       HTLCOutputInCommitment(LDKHTLCOutputInCommitment&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKHTLCOutputInCommitment)); }
+       operator LDKHTLCOutputInCommitment() && { LDKHTLCOutputInCommitment res = self; memset(&self, 0, sizeof(LDKHTLCOutputInCommitment)); return res; }
+       ~HTLCOutputInCommitment() { HTLCOutputInCommitment_free(self); }
+       HTLCOutputInCommitment& operator=(HTLCOutputInCommitment&& o) { HTLCOutputInCommitment_free(self); self = o.self; memset(&o, 0, sizeof(HTLCOutputInCommitment)); return *this; }
+       LDKHTLCOutputInCommitment* operator &() { return &self; }
+       LDKHTLCOutputInCommitment* operator ->() { return &self; }
+       const LDKHTLCOutputInCommitment* operator &() const { return &self; }
+       const LDKHTLCOutputInCommitment* operator ->() const { return &self; }
 };
-class APIError {
+class ChannelTransactionParameters {
+private:
+       LDKChannelTransactionParameters self;
+public:
+       ChannelTransactionParameters(const ChannelTransactionParameters&) = delete;
+       ChannelTransactionParameters(ChannelTransactionParameters&& o) : self(o.self) { memset(&o, 0, sizeof(ChannelTransactionParameters)); }
+       ChannelTransactionParameters(LDKChannelTransactionParameters&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKChannelTransactionParameters)); }
+       operator LDKChannelTransactionParameters() && { LDKChannelTransactionParameters res = self; memset(&self, 0, sizeof(LDKChannelTransactionParameters)); return res; }
+       ~ChannelTransactionParameters() { ChannelTransactionParameters_free(self); }
+       ChannelTransactionParameters& operator=(ChannelTransactionParameters&& o) { ChannelTransactionParameters_free(self); self = o.self; memset(&o, 0, sizeof(ChannelTransactionParameters)); return *this; }
+       LDKChannelTransactionParameters* operator &() { return &self; }
+       LDKChannelTransactionParameters* operator ->() { return &self; }
+       const LDKChannelTransactionParameters* operator &() const { return &self; }
+       const LDKChannelTransactionParameters* operator ->() const { return &self; }
+};
+class CounterpartyChannelTransactionParameters {
+private:
+       LDKCounterpartyChannelTransactionParameters self;
+public:
+       CounterpartyChannelTransactionParameters(const CounterpartyChannelTransactionParameters&) = delete;
+       CounterpartyChannelTransactionParameters(CounterpartyChannelTransactionParameters&& o) : self(o.self) { memset(&o, 0, sizeof(CounterpartyChannelTransactionParameters)); }
+       CounterpartyChannelTransactionParameters(LDKCounterpartyChannelTransactionParameters&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCounterpartyChannelTransactionParameters)); }
+       operator LDKCounterpartyChannelTransactionParameters() && { LDKCounterpartyChannelTransactionParameters res = self; memset(&self, 0, sizeof(LDKCounterpartyChannelTransactionParameters)); return res; }
+       ~CounterpartyChannelTransactionParameters() { CounterpartyChannelTransactionParameters_free(self); }
+       CounterpartyChannelTransactionParameters& operator=(CounterpartyChannelTransactionParameters&& o) { CounterpartyChannelTransactionParameters_free(self); self = o.self; memset(&o, 0, sizeof(CounterpartyChannelTransactionParameters)); return *this; }
+       LDKCounterpartyChannelTransactionParameters* operator &() { return &self; }
+       LDKCounterpartyChannelTransactionParameters* operator ->() { return &self; }
+       const LDKCounterpartyChannelTransactionParameters* operator &() const { return &self; }
+       const LDKCounterpartyChannelTransactionParameters* operator ->() const { return &self; }
+};
+class DirectedChannelTransactionParameters {
+private:
+       LDKDirectedChannelTransactionParameters self;
+public:
+       DirectedChannelTransactionParameters(const DirectedChannelTransactionParameters&) = delete;
+       DirectedChannelTransactionParameters(DirectedChannelTransactionParameters&& o) : self(o.self) { memset(&o, 0, sizeof(DirectedChannelTransactionParameters)); }
+       DirectedChannelTransactionParameters(LDKDirectedChannelTransactionParameters&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKDirectedChannelTransactionParameters)); }
+       operator LDKDirectedChannelTransactionParameters() && { LDKDirectedChannelTransactionParameters res = self; memset(&self, 0, sizeof(LDKDirectedChannelTransactionParameters)); return res; }
+       ~DirectedChannelTransactionParameters() { DirectedChannelTransactionParameters_free(self); }
+       DirectedChannelTransactionParameters& operator=(DirectedChannelTransactionParameters&& o) { DirectedChannelTransactionParameters_free(self); self = o.self; memset(&o, 0, sizeof(DirectedChannelTransactionParameters)); return *this; }
+       LDKDirectedChannelTransactionParameters* operator &() { return &self; }
+       LDKDirectedChannelTransactionParameters* operator ->() { return &self; }
+       const LDKDirectedChannelTransactionParameters* operator &() const { return &self; }
+       const LDKDirectedChannelTransactionParameters* operator ->() const { return &self; }
+};
+class HolderCommitmentTransaction {
 private:
-       LDKAPIError self;
+       LDKHolderCommitmentTransaction self;
 public:
-       APIError(const APIError&) = delete;
-       ~APIError() { APIError_free(self); }
-       APIError(APIError&& o) : self(o.self) { memset(&o, 0, sizeof(APIError)); }
-       APIError(LDKAPIError&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKAPIError)); }
-       operator LDKAPIError() { LDKAPIError res = self; memset(&self, 0, sizeof(LDKAPIError)); return res; }
-       LDKAPIError* operator &() { return &self; }
-       LDKAPIError* operator ->() { return &self; }
-       const LDKAPIError* operator &() const { return &self; }
-       const LDKAPIError* operator ->() const { return &self; }
+       HolderCommitmentTransaction(const HolderCommitmentTransaction&) = delete;
+       HolderCommitmentTransaction(HolderCommitmentTransaction&& o) : self(o.self) { memset(&o, 0, sizeof(HolderCommitmentTransaction)); }
+       HolderCommitmentTransaction(LDKHolderCommitmentTransaction&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKHolderCommitmentTransaction)); }
+       operator LDKHolderCommitmentTransaction() && { LDKHolderCommitmentTransaction res = self; memset(&self, 0, sizeof(LDKHolderCommitmentTransaction)); return res; }
+       ~HolderCommitmentTransaction() { HolderCommitmentTransaction_free(self); }
+       HolderCommitmentTransaction& operator=(HolderCommitmentTransaction&& o) { HolderCommitmentTransaction_free(self); self = o.self; memset(&o, 0, sizeof(HolderCommitmentTransaction)); return *this; }
+       LDKHolderCommitmentTransaction* operator &() { return &self; }
+       LDKHolderCommitmentTransaction* operator ->() { return &self; }
+       const LDKHolderCommitmentTransaction* operator &() const { return &self; }
+       const LDKHolderCommitmentTransaction* operator ->() const { return &self; }
 };
-class Level {
+class BuiltCommitmentTransaction {
+private:
+       LDKBuiltCommitmentTransaction self;
+public:
+       BuiltCommitmentTransaction(const BuiltCommitmentTransaction&) = delete;
+       BuiltCommitmentTransaction(BuiltCommitmentTransaction&& o) : self(o.self) { memset(&o, 0, sizeof(BuiltCommitmentTransaction)); }
+       BuiltCommitmentTransaction(LDKBuiltCommitmentTransaction&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKBuiltCommitmentTransaction)); }
+       operator LDKBuiltCommitmentTransaction() && { LDKBuiltCommitmentTransaction res = self; memset(&self, 0, sizeof(LDKBuiltCommitmentTransaction)); return res; }
+       ~BuiltCommitmentTransaction() { BuiltCommitmentTransaction_free(self); }
+       BuiltCommitmentTransaction& operator=(BuiltCommitmentTransaction&& o) { BuiltCommitmentTransaction_free(self); self = o.self; memset(&o, 0, sizeof(BuiltCommitmentTransaction)); return *this; }
+       LDKBuiltCommitmentTransaction* operator &() { return &self; }
+       LDKBuiltCommitmentTransaction* operator ->() { return &self; }
+       const LDKBuiltCommitmentTransaction* operator &() const { return &self; }
+       const LDKBuiltCommitmentTransaction* operator ->() const { return &self; }
+};
+class CommitmentTransaction {
+private:
+       LDKCommitmentTransaction self;
+public:
+       CommitmentTransaction(const CommitmentTransaction&) = delete;
+       CommitmentTransaction(CommitmentTransaction&& o) : self(o.self) { memset(&o, 0, sizeof(CommitmentTransaction)); }
+       CommitmentTransaction(LDKCommitmentTransaction&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCommitmentTransaction)); }
+       operator LDKCommitmentTransaction() && { LDKCommitmentTransaction res = self; memset(&self, 0, sizeof(LDKCommitmentTransaction)); return res; }
+       ~CommitmentTransaction() { CommitmentTransaction_free(self); }
+       CommitmentTransaction& operator=(CommitmentTransaction&& o) { CommitmentTransaction_free(self); self = o.self; memset(&o, 0, sizeof(CommitmentTransaction)); return *this; }
+       LDKCommitmentTransaction* operator &() { return &self; }
+       LDKCommitmentTransaction* operator ->() { return &self; }
+       const LDKCommitmentTransaction* operator &() const { return &self; }
+       const LDKCommitmentTransaction* operator ->() const { return &self; }
+};
+class TrustedCommitmentTransaction {
+private:
+       LDKTrustedCommitmentTransaction self;
+public:
+       TrustedCommitmentTransaction(const TrustedCommitmentTransaction&) = delete;
+       TrustedCommitmentTransaction(TrustedCommitmentTransaction&& o) : self(o.self) { memset(&o, 0, sizeof(TrustedCommitmentTransaction)); }
+       TrustedCommitmentTransaction(LDKTrustedCommitmentTransaction&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKTrustedCommitmentTransaction)); }
+       operator LDKTrustedCommitmentTransaction() && { LDKTrustedCommitmentTransaction res = self; memset(&self, 0, sizeof(LDKTrustedCommitmentTransaction)); return res; }
+       ~TrustedCommitmentTransaction() { TrustedCommitmentTransaction_free(self); }
+       TrustedCommitmentTransaction& operator=(TrustedCommitmentTransaction&& o) { TrustedCommitmentTransaction_free(self); self = o.self; memset(&o, 0, sizeof(TrustedCommitmentTransaction)); return *this; }
+       LDKTrustedCommitmentTransaction* operator &() { return &self; }
+       LDKTrustedCommitmentTransaction* operator ->() { return &self; }
+       const LDKTrustedCommitmentTransaction* operator &() const { return &self; }
+       const LDKTrustedCommitmentTransaction* operator ->() const { return &self; }
+};
+class MessageHandler {
 private:
-       LDKLevel self;
+       LDKMessageHandler self;
 public:
-       Level(const Level&) = delete;
-       Level(Level&& o) : self(o.self) { memset(&o, 0, sizeof(Level)); }
-       Level(LDKLevel&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKLevel)); }
-       operator LDKLevel() { LDKLevel res = self; memset(&self, 0, sizeof(LDKLevel)); return res; }
-       LDKLevel* operator &() { return &self; }
-       LDKLevel* operator ->() { return &self; }
-       const LDKLevel* operator &() const { return &self; }
-       const LDKLevel* operator ->() const { return &self; }
+       MessageHandler(const MessageHandler&) = delete;
+       MessageHandler(MessageHandler&& o) : self(o.self) { memset(&o, 0, sizeof(MessageHandler)); }
+       MessageHandler(LDKMessageHandler&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKMessageHandler)); }
+       operator LDKMessageHandler() && { LDKMessageHandler res = self; memset(&self, 0, sizeof(LDKMessageHandler)); return res; }
+       ~MessageHandler() { MessageHandler_free(self); }
+       MessageHandler& operator=(MessageHandler&& o) { MessageHandler_free(self); self = o.self; memset(&o, 0, sizeof(MessageHandler)); return *this; }
+       LDKMessageHandler* operator &() { return &self; }
+       LDKMessageHandler* operator ->() { return &self; }
+       const LDKMessageHandler* operator &() const { return &self; }
+       const LDKMessageHandler* operator ->() const { return &self; }
 };
-class Logger {
+class SocketDescriptor {
 private:
-       LDKLogger self;
+       LDKSocketDescriptor self;
 public:
-       Logger(const Logger&) = delete;
-       ~Logger() { Logger_free(self); }
-       Logger(Logger&& o) : self(o.self) { memset(&o, 0, sizeof(Logger)); }
-       Logger(LDKLogger&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKLogger)); }
-       operator LDKLogger() { LDKLogger res = self; memset(&self, 0, sizeof(LDKLogger)); return res; }
-       LDKLogger* operator &() { return &self; }
-       LDKLogger* operator ->() { return &self; }
-       const LDKLogger* operator &() const { return &self; }
-       const LDKLogger* operator ->() const { return &self; }
+       SocketDescriptor(const SocketDescriptor&) = delete;
+       SocketDescriptor(SocketDescriptor&& o) : self(o.self) { memset(&o, 0, sizeof(SocketDescriptor)); }
+       SocketDescriptor(LDKSocketDescriptor&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKSocketDescriptor)); }
+       operator LDKSocketDescriptor() && { LDKSocketDescriptor res = self; memset(&self, 0, sizeof(LDKSocketDescriptor)); return res; }
+       ~SocketDescriptor() { SocketDescriptor_free(self); }
+       SocketDescriptor& operator=(SocketDescriptor&& o) { SocketDescriptor_free(self); self = o.self; memset(&o, 0, sizeof(SocketDescriptor)); return *this; }
+       LDKSocketDescriptor* operator &() { return &self; }
+       LDKSocketDescriptor* operator ->() { return &self; }
+       const LDKSocketDescriptor* operator &() const { return &self; }
+       const LDKSocketDescriptor* operator ->() const { return &self; }
+};
+class PeerHandleError {
+private:
+       LDKPeerHandleError self;
+public:
+       PeerHandleError(const PeerHandleError&) = delete;
+       PeerHandleError(PeerHandleError&& o) : self(o.self) { memset(&o, 0, sizeof(PeerHandleError)); }
+       PeerHandleError(LDKPeerHandleError&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKPeerHandleError)); }
+       operator LDKPeerHandleError() && { LDKPeerHandleError res = self; memset(&self, 0, sizeof(LDKPeerHandleError)); return res; }
+       ~PeerHandleError() { PeerHandleError_free(self); }
+       PeerHandleError& operator=(PeerHandleError&& o) { PeerHandleError_free(self); self = o.self; memset(&o, 0, sizeof(PeerHandleError)); return *this; }
+       LDKPeerHandleError* operator &() { return &self; }
+       LDKPeerHandleError* operator ->() { return &self; }
+       const LDKPeerHandleError* operator &() const { return &self; }
+       const LDKPeerHandleError* operator ->() const { return &self; }
+};
+class PeerManager {
+private:
+       LDKPeerManager self;
+public:
+       PeerManager(const PeerManager&) = delete;
+       PeerManager(PeerManager&& o) : self(o.self) { memset(&o, 0, sizeof(PeerManager)); }
+       PeerManager(LDKPeerManager&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKPeerManager)); }
+       operator LDKPeerManager() && { LDKPeerManager res = self; memset(&self, 0, sizeof(LDKPeerManager)); return res; }
+       ~PeerManager() { PeerManager_free(self); }
+       PeerManager& operator=(PeerManager&& o) { PeerManager_free(self); self = o.self; memset(&o, 0, sizeof(PeerManager)); return *this; }
+       LDKPeerManager* operator &() { return &self; }
+       LDKPeerManager* operator ->() { return &self; }
+       const LDKPeerManager* operator &() const { return &self; }
+       const LDKPeerManager* operator ->() const { return &self; }
+};
+class InitFeatures {
+private:
+       LDKInitFeatures self;
+public:
+       InitFeatures(const InitFeatures&) = delete;
+       InitFeatures(InitFeatures&& o) : self(o.self) { memset(&o, 0, sizeof(InitFeatures)); }
+       InitFeatures(LDKInitFeatures&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKInitFeatures)); }
+       operator LDKInitFeatures() && { LDKInitFeatures res = self; memset(&self, 0, sizeof(LDKInitFeatures)); return res; }
+       ~InitFeatures() { InitFeatures_free(self); }
+       InitFeatures& operator=(InitFeatures&& o) { InitFeatures_free(self); self = o.self; memset(&o, 0, sizeof(InitFeatures)); return *this; }
+       LDKInitFeatures* operator &() { return &self; }
+       LDKInitFeatures* operator ->() { return &self; }
+       const LDKInitFeatures* operator &() const { return &self; }
+       const LDKInitFeatures* operator ->() const { return &self; }
+};
+class NodeFeatures {
+private:
+       LDKNodeFeatures self;
+public:
+       NodeFeatures(const NodeFeatures&) = delete;
+       NodeFeatures(NodeFeatures&& o) : self(o.self) { memset(&o, 0, sizeof(NodeFeatures)); }
+       NodeFeatures(LDKNodeFeatures&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKNodeFeatures)); }
+       operator LDKNodeFeatures() && { LDKNodeFeatures res = self; memset(&self, 0, sizeof(LDKNodeFeatures)); return res; }
+       ~NodeFeatures() { NodeFeatures_free(self); }
+       NodeFeatures& operator=(NodeFeatures&& o) { NodeFeatures_free(self); self = o.self; memset(&o, 0, sizeof(NodeFeatures)); return *this; }
+       LDKNodeFeatures* operator &() { return &self; }
+       LDKNodeFeatures* operator ->() { return &self; }
+       const LDKNodeFeatures* operator &() const { return &self; }
+       const LDKNodeFeatures* operator ->() const { return &self; }
+};
+class ChannelFeatures {
+private:
+       LDKChannelFeatures self;
+public:
+       ChannelFeatures(const ChannelFeatures&) = delete;
+       ChannelFeatures(ChannelFeatures&& o) : self(o.self) { memset(&o, 0, sizeof(ChannelFeatures)); }
+       ChannelFeatures(LDKChannelFeatures&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKChannelFeatures)); }
+       operator LDKChannelFeatures() && { LDKChannelFeatures res = self; memset(&self, 0, sizeof(LDKChannelFeatures)); return res; }
+       ~ChannelFeatures() { ChannelFeatures_free(self); }
+       ChannelFeatures& operator=(ChannelFeatures&& o) { ChannelFeatures_free(self); self = o.self; memset(&o, 0, sizeof(ChannelFeatures)); return *this; }
+       LDKChannelFeatures* operator &() { return &self; }
+       LDKChannelFeatures* operator ->() { return &self; }
+       const LDKChannelFeatures* operator &() const { return &self; }
+       const LDKChannelFeatures* operator ->() const { return &self; }
 };
 class ChannelHandshakeConfig {
 private:
        LDKChannelHandshakeConfig self;
 public:
        ChannelHandshakeConfig(const ChannelHandshakeConfig&) = delete;
-       ~ChannelHandshakeConfig() { ChannelHandshakeConfig_free(self); }
        ChannelHandshakeConfig(ChannelHandshakeConfig&& o) : self(o.self) { memset(&o, 0, sizeof(ChannelHandshakeConfig)); }
        ChannelHandshakeConfig(LDKChannelHandshakeConfig&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKChannelHandshakeConfig)); }
-       operator LDKChannelHandshakeConfig() { LDKChannelHandshakeConfig res = self; memset(&self, 0, sizeof(LDKChannelHandshakeConfig)); return res; }
+       operator LDKChannelHandshakeConfig() && { LDKChannelHandshakeConfig res = self; memset(&self, 0, sizeof(LDKChannelHandshakeConfig)); return res; }
+       ~ChannelHandshakeConfig() { ChannelHandshakeConfig_free(self); }
+       ChannelHandshakeConfig& operator=(ChannelHandshakeConfig&& o) { ChannelHandshakeConfig_free(self); self = o.self; memset(&o, 0, sizeof(ChannelHandshakeConfig)); return *this; }
        LDKChannelHandshakeConfig* operator &() { return &self; }
        LDKChannelHandshakeConfig* operator ->() { return &self; }
        const LDKChannelHandshakeConfig* operator &() const { return &self; }
@@ -116,10 +290,11 @@ private:
        LDKChannelHandshakeLimits self;
 public:
        ChannelHandshakeLimits(const ChannelHandshakeLimits&) = delete;
-       ~ChannelHandshakeLimits() { ChannelHandshakeLimits_free(self); }
        ChannelHandshakeLimits(ChannelHandshakeLimits&& o) : self(o.self) { memset(&o, 0, sizeof(ChannelHandshakeLimits)); }
        ChannelHandshakeLimits(LDKChannelHandshakeLimits&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKChannelHandshakeLimits)); }
-       operator LDKChannelHandshakeLimits() { LDKChannelHandshakeLimits res = self; memset(&self, 0, sizeof(LDKChannelHandshakeLimits)); return res; }
+       operator LDKChannelHandshakeLimits() && { LDKChannelHandshakeLimits res = self; memset(&self, 0, sizeof(LDKChannelHandshakeLimits)); return res; }
+       ~ChannelHandshakeLimits() { ChannelHandshakeLimits_free(self); }
+       ChannelHandshakeLimits& operator=(ChannelHandshakeLimits&& o) { ChannelHandshakeLimits_free(self); self = o.self; memset(&o, 0, sizeof(ChannelHandshakeLimits)); return *this; }
        LDKChannelHandshakeLimits* operator &() { return &self; }
        LDKChannelHandshakeLimits* operator ->() { return &self; }
        const LDKChannelHandshakeLimits* operator &() const { return &self; }
@@ -130,10 +305,11 @@ private:
        LDKChannelConfig self;
 public:
        ChannelConfig(const ChannelConfig&) = delete;
-       ~ChannelConfig() { ChannelConfig_free(self); }
        ChannelConfig(ChannelConfig&& o) : self(o.self) { memset(&o, 0, sizeof(ChannelConfig)); }
        ChannelConfig(LDKChannelConfig&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKChannelConfig)); }
-       operator LDKChannelConfig() { LDKChannelConfig res = self; memset(&self, 0, sizeof(LDKChannelConfig)); return res; }
+       operator LDKChannelConfig() && { LDKChannelConfig res = self; memset(&self, 0, sizeof(LDKChannelConfig)); return res; }
+       ~ChannelConfig() { ChannelConfig_free(self); }
+       ChannelConfig& operator=(ChannelConfig&& o) { ChannelConfig_free(self); self = o.self; memset(&o, 0, sizeof(ChannelConfig)); return *this; }
        LDKChannelConfig* operator &() { return &self; }
        LDKChannelConfig* operator ->() { return &self; }
        const LDKChannelConfig* operator &() const { return &self; }
@@ -144,79 +320,205 @@ private:
        LDKUserConfig self;
 public:
        UserConfig(const UserConfig&) = delete;
-       ~UserConfig() { UserConfig_free(self); }
        UserConfig(UserConfig&& o) : self(o.self) { memset(&o, 0, sizeof(UserConfig)); }
        UserConfig(LDKUserConfig&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKUserConfig)); }
-       operator LDKUserConfig() { LDKUserConfig res = self; memset(&self, 0, sizeof(LDKUserConfig)); return res; }
+       operator LDKUserConfig() && { LDKUserConfig res = self; memset(&self, 0, sizeof(LDKUserConfig)); return res; }
+       ~UserConfig() { UserConfig_free(self); }
+       UserConfig& operator=(UserConfig&& o) { UserConfig_free(self); self = o.self; memset(&o, 0, sizeof(UserConfig)); return *this; }
        LDKUserConfig* operator &() { return &self; }
        LDKUserConfig* operator ->() { return &self; }
        const LDKUserConfig* operator &() const { return &self; }
        const LDKUserConfig* operator ->() const { return &self; }
 };
-class BroadcasterInterface {
+class NetworkGraph {
 private:
-       LDKBroadcasterInterface self;
+       LDKNetworkGraph self;
 public:
-       BroadcasterInterface(const BroadcasterInterface&) = delete;
-       ~BroadcasterInterface() { BroadcasterInterface_free(self); }
-       BroadcasterInterface(BroadcasterInterface&& o) : self(o.self) { memset(&o, 0, sizeof(BroadcasterInterface)); }
-       BroadcasterInterface(LDKBroadcasterInterface&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKBroadcasterInterface)); }
-       operator LDKBroadcasterInterface() { LDKBroadcasterInterface res = self; memset(&self, 0, sizeof(LDKBroadcasterInterface)); return res; }
-       LDKBroadcasterInterface* operator &() { return &self; }
-       LDKBroadcasterInterface* operator ->() { return &self; }
-       const LDKBroadcasterInterface* operator &() const { return &self; }
-       const LDKBroadcasterInterface* operator ->() const { return &self; }
+       NetworkGraph(const NetworkGraph&) = delete;
+       NetworkGraph(NetworkGraph&& o) : self(o.self) { memset(&o, 0, sizeof(NetworkGraph)); }
+       NetworkGraph(LDKNetworkGraph&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKNetworkGraph)); }
+       operator LDKNetworkGraph() && { LDKNetworkGraph res = self; memset(&self, 0, sizeof(LDKNetworkGraph)); return res; }
+       ~NetworkGraph() { NetworkGraph_free(self); }
+       NetworkGraph& operator=(NetworkGraph&& o) { NetworkGraph_free(self); self = o.self; memset(&o, 0, sizeof(NetworkGraph)); return *this; }
+       LDKNetworkGraph* operator &() { return &self; }
+       LDKNetworkGraph* operator ->() { return &self; }
+       const LDKNetworkGraph* operator &() const { return &self; }
+       const LDKNetworkGraph* operator ->() const { return &self; }
 };
-class ConfirmationTarget {
+class LockedNetworkGraph {
 private:
-       LDKConfirmationTarget self;
+       LDKLockedNetworkGraph self;
 public:
-       ConfirmationTarget(const ConfirmationTarget&) = delete;
-       ConfirmationTarget(ConfirmationTarget&& o) : self(o.self) { memset(&o, 0, sizeof(ConfirmationTarget)); }
-       ConfirmationTarget(LDKConfirmationTarget&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKConfirmationTarget)); }
-       operator LDKConfirmationTarget() { LDKConfirmationTarget res = self; memset(&self, 0, sizeof(LDKConfirmationTarget)); return res; }
-       LDKConfirmationTarget* operator &() { return &self; }
-       LDKConfirmationTarget* operator ->() { return &self; }
-       const LDKConfirmationTarget* operator &() const { return &self; }
-       const LDKConfirmationTarget* operator ->() const { return &self; }
+       LockedNetworkGraph(const LockedNetworkGraph&) = delete;
+       LockedNetworkGraph(LockedNetworkGraph&& o) : self(o.self) { memset(&o, 0, sizeof(LockedNetworkGraph)); }
+       LockedNetworkGraph(LDKLockedNetworkGraph&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKLockedNetworkGraph)); }
+       operator LDKLockedNetworkGraph() && { LDKLockedNetworkGraph res = self; memset(&self, 0, sizeof(LDKLockedNetworkGraph)); return res; }
+       ~LockedNetworkGraph() { LockedNetworkGraph_free(self); }
+       LockedNetworkGraph& operator=(LockedNetworkGraph&& o) { LockedNetworkGraph_free(self); self = o.self; memset(&o, 0, sizeof(LockedNetworkGraph)); return *this; }
+       LDKLockedNetworkGraph* operator &() { return &self; }
+       LDKLockedNetworkGraph* operator ->() { return &self; }
+       const LDKLockedNetworkGraph* operator &() const { return &self; }
+       const LDKLockedNetworkGraph* operator ->() const { return &self; }
 };
-class FeeEstimator {
+class NetGraphMsgHandler {
 private:
-       LDKFeeEstimator self;
+       LDKNetGraphMsgHandler self;
 public:
-       FeeEstimator(const FeeEstimator&) = delete;
-       ~FeeEstimator() { FeeEstimator_free(self); }
-       FeeEstimator(FeeEstimator&& o) : self(o.self) { memset(&o, 0, sizeof(FeeEstimator)); }
-       FeeEstimator(LDKFeeEstimator&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKFeeEstimator)); }
-       operator LDKFeeEstimator() { LDKFeeEstimator res = self; memset(&self, 0, sizeof(LDKFeeEstimator)); return res; }
-       LDKFeeEstimator* operator &() { return &self; }
-       LDKFeeEstimator* operator ->() { return &self; }
-       const LDKFeeEstimator* operator &() const { return &self; }
-       const LDKFeeEstimator* operator ->() const { return &self; }
+       NetGraphMsgHandler(const NetGraphMsgHandler&) = delete;
+       NetGraphMsgHandler(NetGraphMsgHandler&& o) : self(o.self) { memset(&o, 0, sizeof(NetGraphMsgHandler)); }
+       NetGraphMsgHandler(LDKNetGraphMsgHandler&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKNetGraphMsgHandler)); }
+       operator LDKNetGraphMsgHandler() && { LDKNetGraphMsgHandler res = self; memset(&self, 0, sizeof(LDKNetGraphMsgHandler)); return res; }
+       ~NetGraphMsgHandler() { NetGraphMsgHandler_free(self); }
+       NetGraphMsgHandler& operator=(NetGraphMsgHandler&& o) { NetGraphMsgHandler_free(self); self = o.self; memset(&o, 0, sizeof(NetGraphMsgHandler)); return *this; }
+       LDKNetGraphMsgHandler* operator &() { return &self; }
+       LDKNetGraphMsgHandler* operator ->() { return &self; }
+       const LDKNetGraphMsgHandler* operator &() const { return &self; }
+       const LDKNetGraphMsgHandler* operator ->() const { return &self; }
+};
+class DirectionalChannelInfo {
+private:
+       LDKDirectionalChannelInfo self;
+public:
+       DirectionalChannelInfo(const DirectionalChannelInfo&) = delete;
+       DirectionalChannelInfo(DirectionalChannelInfo&& o) : self(o.self) { memset(&o, 0, sizeof(DirectionalChannelInfo)); }
+       DirectionalChannelInfo(LDKDirectionalChannelInfo&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKDirectionalChannelInfo)); }
+       operator LDKDirectionalChannelInfo() && { LDKDirectionalChannelInfo res = self; memset(&self, 0, sizeof(LDKDirectionalChannelInfo)); return res; }
+       ~DirectionalChannelInfo() { DirectionalChannelInfo_free(self); }
+       DirectionalChannelInfo& operator=(DirectionalChannelInfo&& o) { DirectionalChannelInfo_free(self); self = o.self; memset(&o, 0, sizeof(DirectionalChannelInfo)); return *this; }
+       LDKDirectionalChannelInfo* operator &() { return &self; }
+       LDKDirectionalChannelInfo* operator ->() { return &self; }
+       const LDKDirectionalChannelInfo* operator &() const { return &self; }
+       const LDKDirectionalChannelInfo* operator ->() const { return &self; }
+};
+class ChannelInfo {
+private:
+       LDKChannelInfo self;
+public:
+       ChannelInfo(const ChannelInfo&) = delete;
+       ChannelInfo(ChannelInfo&& o) : self(o.self) { memset(&o, 0, sizeof(ChannelInfo)); }
+       ChannelInfo(LDKChannelInfo&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKChannelInfo)); }
+       operator LDKChannelInfo() && { LDKChannelInfo res = self; memset(&self, 0, sizeof(LDKChannelInfo)); return res; }
+       ~ChannelInfo() { ChannelInfo_free(self); }
+       ChannelInfo& operator=(ChannelInfo&& o) { ChannelInfo_free(self); self = o.self; memset(&o, 0, sizeof(ChannelInfo)); return *this; }
+       LDKChannelInfo* operator &() { return &self; }
+       LDKChannelInfo* operator ->() { return &self; }
+       const LDKChannelInfo* operator &() const { return &self; }
+       const LDKChannelInfo* operator ->() const { return &self; }
+};
+class RoutingFees {
+private:
+       LDKRoutingFees self;
+public:
+       RoutingFees(const RoutingFees&) = delete;
+       RoutingFees(RoutingFees&& o) : self(o.self) { memset(&o, 0, sizeof(RoutingFees)); }
+       RoutingFees(LDKRoutingFees&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKRoutingFees)); }
+       operator LDKRoutingFees() && { LDKRoutingFees res = self; memset(&self, 0, sizeof(LDKRoutingFees)); return res; }
+       ~RoutingFees() { RoutingFees_free(self); }
+       RoutingFees& operator=(RoutingFees&& o) { RoutingFees_free(self); self = o.self; memset(&o, 0, sizeof(RoutingFees)); return *this; }
+       LDKRoutingFees* operator &() { return &self; }
+       LDKRoutingFees* operator ->() { return &self; }
+       const LDKRoutingFees* operator &() const { return &self; }
+       const LDKRoutingFees* operator ->() const { return &self; }
+};
+class NodeAnnouncementInfo {
+private:
+       LDKNodeAnnouncementInfo self;
+public:
+       NodeAnnouncementInfo(const NodeAnnouncementInfo&) = delete;
+       NodeAnnouncementInfo(NodeAnnouncementInfo&& o) : self(o.self) { memset(&o, 0, sizeof(NodeAnnouncementInfo)); }
+       NodeAnnouncementInfo(LDKNodeAnnouncementInfo&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKNodeAnnouncementInfo)); }
+       operator LDKNodeAnnouncementInfo() && { LDKNodeAnnouncementInfo res = self; memset(&self, 0, sizeof(LDKNodeAnnouncementInfo)); return res; }
+       ~NodeAnnouncementInfo() { NodeAnnouncementInfo_free(self); }
+       NodeAnnouncementInfo& operator=(NodeAnnouncementInfo&& o) { NodeAnnouncementInfo_free(self); self = o.self; memset(&o, 0, sizeof(NodeAnnouncementInfo)); return *this; }
+       LDKNodeAnnouncementInfo* operator &() { return &self; }
+       LDKNodeAnnouncementInfo* operator ->() { return &self; }
+       const LDKNodeAnnouncementInfo* operator &() const { return &self; }
+       const LDKNodeAnnouncementInfo* operator ->() const { return &self; }
+};
+class NodeInfo {
+private:
+       LDKNodeInfo self;
+public:
+       NodeInfo(const NodeInfo&) = delete;
+       NodeInfo(NodeInfo&& o) : self(o.self) { memset(&o, 0, sizeof(NodeInfo)); }
+       NodeInfo(LDKNodeInfo&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKNodeInfo)); }
+       operator LDKNodeInfo() && { LDKNodeInfo res = self; memset(&self, 0, sizeof(LDKNodeInfo)); return res; }
+       ~NodeInfo() { NodeInfo_free(self); }
+       NodeInfo& operator=(NodeInfo&& o) { NodeInfo_free(self); self = o.self; memset(&o, 0, sizeof(NodeInfo)); return *this; }
+       LDKNodeInfo* operator &() { return &self; }
+       LDKNodeInfo* operator ->() { return &self; }
+       const LDKNodeInfo* operator &() const { return &self; }
+       const LDKNodeInfo* operator ->() const { return &self; }
+};
+class Level {
+private:
+       LDKLevel self;
+public:
+       Level(const Level&) = delete;
+       Level(Level&& o) : self(o.self) { memset(&o, 0, sizeof(Level)); }
+       Level(LDKLevel&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKLevel)); }
+       operator LDKLevel() && { LDKLevel res = self; memset(&self, 0, sizeof(LDKLevel)); return res; }
+       Level& operator=(Level&& o) { self = o.self; memset(&o, 0, sizeof(Level)); return *this; }
+       LDKLevel* operator &() { return &self; }
+       LDKLevel* operator ->() { return &self; }
+       const LDKLevel* operator &() const { return &self; }
+       const LDKLevel* operator ->() const { return &self; }
+};
+class Logger {
+private:
+       LDKLogger self;
+public:
+       Logger(const Logger&) = delete;
+       Logger(Logger&& o) : self(o.self) { memset(&o, 0, sizeof(Logger)); }
+       Logger(LDKLogger&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKLogger)); }
+       operator LDKLogger() && { LDKLogger res = self; memset(&self, 0, sizeof(LDKLogger)); return res; }
+       ~Logger() { Logger_free(self); }
+       Logger& operator=(Logger&& o) { Logger_free(self); self = o.self; memset(&o, 0, sizeof(Logger)); return *this; }
+       LDKLogger* operator &() { return &self; }
+       LDKLogger* operator ->() { return &self; }
+       const LDKLogger* operator &() const { return &self; }
+       const LDKLogger* operator ->() const { return &self; }
 };
 class ChainMonitor {
 private:
        LDKChainMonitor self;
 public:
        ChainMonitor(const ChainMonitor&) = delete;
-       ~ChainMonitor() { ChainMonitor_free(self); }
        ChainMonitor(ChainMonitor&& o) : self(o.self) { memset(&o, 0, sizeof(ChainMonitor)); }
        ChainMonitor(LDKChainMonitor&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKChainMonitor)); }
-       operator LDKChainMonitor() { LDKChainMonitor res = self; memset(&self, 0, sizeof(LDKChainMonitor)); return res; }
+       operator LDKChainMonitor() && { LDKChainMonitor res = self; memset(&self, 0, sizeof(LDKChainMonitor)); return res; }
+       ~ChainMonitor() { ChainMonitor_free(self); }
+       ChainMonitor& operator=(ChainMonitor&& o) { ChainMonitor_free(self); self = o.self; memset(&o, 0, sizeof(ChainMonitor)); return *this; }
        LDKChainMonitor* operator &() { return &self; }
        LDKChainMonitor* operator ->() { return &self; }
        const LDKChainMonitor* operator &() const { return &self; }
        const LDKChainMonitor* operator ->() const { return &self; }
 };
+class OutPoint {
+private:
+       LDKOutPoint self;
+public:
+       OutPoint(const OutPoint&) = delete;
+       OutPoint(OutPoint&& o) : self(o.self) { memset(&o, 0, sizeof(OutPoint)); }
+       OutPoint(LDKOutPoint&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKOutPoint)); }
+       operator LDKOutPoint() && { LDKOutPoint res = self; memset(&self, 0, sizeof(LDKOutPoint)); return res; }
+       ~OutPoint() { OutPoint_free(self); }
+       OutPoint& operator=(OutPoint&& o) { OutPoint_free(self); self = o.self; memset(&o, 0, sizeof(OutPoint)); return *this; }
+       LDKOutPoint* operator &() { return &self; }
+       LDKOutPoint* operator ->() { return &self; }
+       const LDKOutPoint* operator &() const { return &self; }
+       const LDKOutPoint* operator ->() const { return &self; }
+};
 class ChannelMonitorUpdate {
 private:
        LDKChannelMonitorUpdate self;
 public:
        ChannelMonitorUpdate(const ChannelMonitorUpdate&) = delete;
-       ~ChannelMonitorUpdate() { ChannelMonitorUpdate_free(self); }
        ChannelMonitorUpdate(ChannelMonitorUpdate&& o) : self(o.self) { memset(&o, 0, sizeof(ChannelMonitorUpdate)); }
        ChannelMonitorUpdate(LDKChannelMonitorUpdate&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKChannelMonitorUpdate)); }
-       operator LDKChannelMonitorUpdate() { LDKChannelMonitorUpdate res = self; memset(&self, 0, sizeof(LDKChannelMonitorUpdate)); return res; }
+       operator LDKChannelMonitorUpdate() && { LDKChannelMonitorUpdate res = self; memset(&self, 0, sizeof(LDKChannelMonitorUpdate)); return res; }
+       ~ChannelMonitorUpdate() { ChannelMonitorUpdate_free(self); }
+       ChannelMonitorUpdate& operator=(ChannelMonitorUpdate&& o) { ChannelMonitorUpdate_free(self); self = o.self; memset(&o, 0, sizeof(ChannelMonitorUpdate)); return *this; }
        LDKChannelMonitorUpdate* operator &() { return &self; }
        LDKChannelMonitorUpdate* operator ->() { return &self; }
        const LDKChannelMonitorUpdate* operator &() const { return &self; }
@@ -229,7 +531,8 @@ public:
        ChannelMonitorUpdateErr(const ChannelMonitorUpdateErr&) = delete;
        ChannelMonitorUpdateErr(ChannelMonitorUpdateErr&& o) : self(o.self) { memset(&o, 0, sizeof(ChannelMonitorUpdateErr)); }
        ChannelMonitorUpdateErr(LDKChannelMonitorUpdateErr&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKChannelMonitorUpdateErr)); }
-       operator LDKChannelMonitorUpdateErr() { LDKChannelMonitorUpdateErr res = self; memset(&self, 0, sizeof(LDKChannelMonitorUpdateErr)); return res; }
+       operator LDKChannelMonitorUpdateErr() && { LDKChannelMonitorUpdateErr res = self; memset(&self, 0, sizeof(LDKChannelMonitorUpdateErr)); return res; }
+       ChannelMonitorUpdateErr& operator=(ChannelMonitorUpdateErr&& o) { self = o.self; memset(&o, 0, sizeof(ChannelMonitorUpdateErr)); return *this; }
        LDKChannelMonitorUpdateErr* operator &() { return &self; }
        LDKChannelMonitorUpdateErr* operator ->() { return &self; }
        const LDKChannelMonitorUpdateErr* operator &() const { return &self; }
@@ -240,10 +543,11 @@ private:
        LDKMonitorUpdateError self;
 public:
        MonitorUpdateError(const MonitorUpdateError&) = delete;
-       ~MonitorUpdateError() { MonitorUpdateError_free(self); }
        MonitorUpdateError(MonitorUpdateError&& o) : self(o.self) { memset(&o, 0, sizeof(MonitorUpdateError)); }
        MonitorUpdateError(LDKMonitorUpdateError&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKMonitorUpdateError)); }
-       operator LDKMonitorUpdateError() { LDKMonitorUpdateError res = self; memset(&self, 0, sizeof(LDKMonitorUpdateError)); return res; }
+       operator LDKMonitorUpdateError() && { LDKMonitorUpdateError res = self; memset(&self, 0, sizeof(LDKMonitorUpdateError)); return res; }
+       ~MonitorUpdateError() { MonitorUpdateError_free(self); }
+       MonitorUpdateError& operator=(MonitorUpdateError&& o) { MonitorUpdateError_free(self); self = o.self; memset(&o, 0, sizeof(MonitorUpdateError)); return *this; }
        LDKMonitorUpdateError* operator &() { return &self; }
        LDKMonitorUpdateError* operator ->() { return &self; }
        const LDKMonitorUpdateError* operator &() const { return &self; }
@@ -254,10 +558,11 @@ private:
        LDKMonitorEvent self;
 public:
        MonitorEvent(const MonitorEvent&) = delete;
-       ~MonitorEvent() { MonitorEvent_free(self); }
        MonitorEvent(MonitorEvent&& o) : self(o.self) { memset(&o, 0, sizeof(MonitorEvent)); }
        MonitorEvent(LDKMonitorEvent&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKMonitorEvent)); }
-       operator LDKMonitorEvent() { LDKMonitorEvent res = self; memset(&self, 0, sizeof(LDKMonitorEvent)); return res; }
+       operator LDKMonitorEvent() && { LDKMonitorEvent res = self; memset(&self, 0, sizeof(LDKMonitorEvent)); return res; }
+       ~MonitorEvent() { MonitorEvent_free(self); }
+       MonitorEvent& operator=(MonitorEvent&& o) { MonitorEvent_free(self); self = o.self; memset(&o, 0, sizeof(MonitorEvent)); return *this; }
        LDKMonitorEvent* operator &() { return &self; }
        LDKMonitorEvent* operator ->() { return &self; }
        const LDKMonitorEvent* operator &() const { return &self; }
@@ -268,10 +573,11 @@ private:
        LDKHTLCUpdate self;
 public:
        HTLCUpdate(const HTLCUpdate&) = delete;
-       ~HTLCUpdate() { HTLCUpdate_free(self); }
        HTLCUpdate(HTLCUpdate&& o) : self(o.self) { memset(&o, 0, sizeof(HTLCUpdate)); }
        HTLCUpdate(LDKHTLCUpdate&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKHTLCUpdate)); }
-       operator LDKHTLCUpdate() { LDKHTLCUpdate res = self; memset(&self, 0, sizeof(LDKHTLCUpdate)); return res; }
+       operator LDKHTLCUpdate() && { LDKHTLCUpdate res = self; memset(&self, 0, sizeof(LDKHTLCUpdate)); return res; }
+       ~HTLCUpdate() { HTLCUpdate_free(self); }
+       HTLCUpdate& operator=(HTLCUpdate&& o) { HTLCUpdate_free(self); self = o.self; memset(&o, 0, sizeof(HTLCUpdate)); return *this; }
        LDKHTLCUpdate* operator &() { return &self; }
        LDKHTLCUpdate* operator ->() { return &self; }
        const LDKHTLCUpdate* operator &() const { return &self; }
@@ -282,10 +588,11 @@ private:
        LDKChannelMonitor self;
 public:
        ChannelMonitor(const ChannelMonitor&) = delete;
-       ~ChannelMonitor() { ChannelMonitor_free(self); }
        ChannelMonitor(ChannelMonitor&& o) : self(o.self) { memset(&o, 0, sizeof(ChannelMonitor)); }
        ChannelMonitor(LDKChannelMonitor&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKChannelMonitor)); }
-       operator LDKChannelMonitor() { LDKChannelMonitor res = self; memset(&self, 0, sizeof(LDKChannelMonitor)); return res; }
+       operator LDKChannelMonitor() && { LDKChannelMonitor res = self; memset(&self, 0, sizeof(LDKChannelMonitor)); return res; }
+       ~ChannelMonitor() { ChannelMonitor_free(self); }
+       ChannelMonitor& operator=(ChannelMonitor&& o) { ChannelMonitor_free(self); self = o.self; memset(&o, 0, sizeof(ChannelMonitor)); return *this; }
        LDKChannelMonitor* operator &() { return &self; }
        LDKChannelMonitor* operator ->() { return &self; }
        const LDKChannelMonitor* operator &() const { return &self; }
@@ -296,98 +603,75 @@ private:
        LDKPersist self;
 public:
        Persist(const Persist&) = delete;
-       ~Persist() { Persist_free(self); }
        Persist(Persist&& o) : self(o.self) { memset(&o, 0, sizeof(Persist)); }
        Persist(LDKPersist&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKPersist)); }
-       operator LDKPersist() { LDKPersist res = self; memset(&self, 0, sizeof(LDKPersist)); return res; }
+       operator LDKPersist() && { LDKPersist res = self; memset(&self, 0, sizeof(LDKPersist)); return res; }
+       ~Persist() { Persist_free(self); }
+       Persist& operator=(Persist&& o) { Persist_free(self); self = o.self; memset(&o, 0, sizeof(Persist)); return *this; }
        LDKPersist* operator &() { return &self; }
        LDKPersist* operator ->() { return &self; }
        const LDKPersist* operator &() const { return &self; }
        const LDKPersist* operator ->() const { return &self; }
 };
-class OutPoint {
-private:
-       LDKOutPoint self;
-public:
-       OutPoint(const OutPoint&) = delete;
-       ~OutPoint() { OutPoint_free(self); }
-       OutPoint(OutPoint&& o) : self(o.self) { memset(&o, 0, sizeof(OutPoint)); }
-       OutPoint(LDKOutPoint&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKOutPoint)); }
-       operator LDKOutPoint() { LDKOutPoint res = self; memset(&self, 0, sizeof(LDKOutPoint)); return res; }
-       LDKOutPoint* operator &() { return &self; }
-       LDKOutPoint* operator ->() { return &self; }
-       const LDKOutPoint* operator &() const { return &self; }
-       const LDKOutPoint* operator ->() const { return &self; }
-};
-class SpendableOutputDescriptor {
-private:
-       LDKSpendableOutputDescriptor self;
-public:
-       SpendableOutputDescriptor(const SpendableOutputDescriptor&) = delete;
-       ~SpendableOutputDescriptor() { SpendableOutputDescriptor_free(self); }
-       SpendableOutputDescriptor(SpendableOutputDescriptor&& o) : self(o.self) { memset(&o, 0, sizeof(SpendableOutputDescriptor)); }
-       SpendableOutputDescriptor(LDKSpendableOutputDescriptor&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKSpendableOutputDescriptor)); }
-       operator LDKSpendableOutputDescriptor() { LDKSpendableOutputDescriptor res = self; memset(&self, 0, sizeof(LDKSpendableOutputDescriptor)); return res; }
-       LDKSpendableOutputDescriptor* operator &() { return &self; }
-       LDKSpendableOutputDescriptor* operator ->() { return &self; }
-       const LDKSpendableOutputDescriptor* operator &() const { return &self; }
-       const LDKSpendableOutputDescriptor* operator ->() const { return &self; }
-};
-class ChannelKeys {
+class Event {
 private:
-       LDKChannelKeys self;
+       LDKEvent self;
 public:
-       ChannelKeys(const ChannelKeys&) = delete;
-       ~ChannelKeys() { ChannelKeys_free(self); }
-       ChannelKeys(ChannelKeys&& o) : self(o.self) { memset(&o, 0, sizeof(ChannelKeys)); }
-       ChannelKeys(LDKChannelKeys&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKChannelKeys)); }
-       operator LDKChannelKeys() { LDKChannelKeys res = self; memset(&self, 0, sizeof(LDKChannelKeys)); return res; }
-       LDKChannelKeys* operator &() { return &self; }
-       LDKChannelKeys* operator ->() { return &self; }
-       const LDKChannelKeys* operator &() const { return &self; }
-       const LDKChannelKeys* operator ->() const { return &self; }
+       Event(const Event&) = delete;
+       Event(Event&& o) : self(o.self) { memset(&o, 0, sizeof(Event)); }
+       Event(LDKEvent&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKEvent)); }
+       operator LDKEvent() && { LDKEvent res = self; memset(&self, 0, sizeof(LDKEvent)); return res; }
+       ~Event() { Event_free(self); }
+       Event& operator=(Event&& o) { Event_free(self); self = o.self; memset(&o, 0, sizeof(Event)); return *this; }
+       LDKEvent* operator &() { return &self; }
+       LDKEvent* operator ->() { return &self; }
+       const LDKEvent* operator &() const { return &self; }
+       const LDKEvent* operator ->() const { return &self; }
 };
-class KeysInterface {
+class MessageSendEvent {
 private:
-       LDKKeysInterface self;
+       LDKMessageSendEvent self;
 public:
-       KeysInterface(const KeysInterface&) = delete;
-       ~KeysInterface() { KeysInterface_free(self); }
-       KeysInterface(KeysInterface&& o) : self(o.self) { memset(&o, 0, sizeof(KeysInterface)); }
-       KeysInterface(LDKKeysInterface&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKKeysInterface)); }
-       operator LDKKeysInterface() { LDKKeysInterface res = self; memset(&self, 0, sizeof(LDKKeysInterface)); return res; }
-       LDKKeysInterface* operator &() { return &self; }
-       LDKKeysInterface* operator ->() { return &self; }
-       const LDKKeysInterface* operator &() const { return &self; }
-       const LDKKeysInterface* operator ->() const { return &self; }
+       MessageSendEvent(const MessageSendEvent&) = delete;
+       MessageSendEvent(MessageSendEvent&& o) : self(o.self) { memset(&o, 0, sizeof(MessageSendEvent)); }
+       MessageSendEvent(LDKMessageSendEvent&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKMessageSendEvent)); }
+       operator LDKMessageSendEvent() && { LDKMessageSendEvent res = self; memset(&self, 0, sizeof(LDKMessageSendEvent)); return res; }
+       ~MessageSendEvent() { MessageSendEvent_free(self); }
+       MessageSendEvent& operator=(MessageSendEvent&& o) { MessageSendEvent_free(self); self = o.self; memset(&o, 0, sizeof(MessageSendEvent)); return *this; }
+       LDKMessageSendEvent* operator &() { return &self; }
+       LDKMessageSendEvent* operator ->() { return &self; }
+       const LDKMessageSendEvent* operator &() const { return &self; }
+       const LDKMessageSendEvent* operator ->() const { return &self; }
 };
-class InMemoryChannelKeys {
+class MessageSendEventsProvider {
 private:
-       LDKInMemoryChannelKeys self;
+       LDKMessageSendEventsProvider self;
 public:
-       InMemoryChannelKeys(const InMemoryChannelKeys&) = delete;
-       ~InMemoryChannelKeys() { InMemoryChannelKeys_free(self); }
-       InMemoryChannelKeys(InMemoryChannelKeys&& o) : self(o.self) { memset(&o, 0, sizeof(InMemoryChannelKeys)); }
-       InMemoryChannelKeys(LDKInMemoryChannelKeys&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKInMemoryChannelKeys)); }
-       operator LDKInMemoryChannelKeys() { LDKInMemoryChannelKeys res = self; memset(&self, 0, sizeof(LDKInMemoryChannelKeys)); return res; }
-       LDKInMemoryChannelKeys* operator &() { return &self; }
-       LDKInMemoryChannelKeys* operator ->() { return &self; }
-       const LDKInMemoryChannelKeys* operator &() const { return &self; }
-       const LDKInMemoryChannelKeys* operator ->() const { return &self; }
+       MessageSendEventsProvider(const MessageSendEventsProvider&) = delete;
+       MessageSendEventsProvider(MessageSendEventsProvider&& o) : self(o.self) { memset(&o, 0, sizeof(MessageSendEventsProvider)); }
+       MessageSendEventsProvider(LDKMessageSendEventsProvider&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKMessageSendEventsProvider)); }
+       operator LDKMessageSendEventsProvider() && { LDKMessageSendEventsProvider res = self; memset(&self, 0, sizeof(LDKMessageSendEventsProvider)); return res; }
+       ~MessageSendEventsProvider() { MessageSendEventsProvider_free(self); }
+       MessageSendEventsProvider& operator=(MessageSendEventsProvider&& o) { MessageSendEventsProvider_free(self); self = o.self; memset(&o, 0, sizeof(MessageSendEventsProvider)); return *this; }
+       LDKMessageSendEventsProvider* operator &() { return &self; }
+       LDKMessageSendEventsProvider* operator ->() { return &self; }
+       const LDKMessageSendEventsProvider* operator &() const { return &self; }
+       const LDKMessageSendEventsProvider* operator ->() const { return &self; }
 };
-class KeysManager {
+class EventsProvider {
 private:
-       LDKKeysManager self;
+       LDKEventsProvider self;
 public:
-       KeysManager(const KeysManager&) = delete;
-       ~KeysManager() { KeysManager_free(self); }
-       KeysManager(KeysManager&& o) : self(o.self) { memset(&o, 0, sizeof(KeysManager)); }
-       KeysManager(LDKKeysManager&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKKeysManager)); }
-       operator LDKKeysManager() { LDKKeysManager res = self; memset(&self, 0, sizeof(LDKKeysManager)); return res; }
-       LDKKeysManager* operator &() { return &self; }
-       LDKKeysManager* operator ->() { return &self; }
-       const LDKKeysManager* operator &() const { return &self; }
-       const LDKKeysManager* operator ->() const { return &self; }
+       EventsProvider(const EventsProvider&) = delete;
+       EventsProvider(EventsProvider&& o) : self(o.self) { memset(&o, 0, sizeof(EventsProvider)); }
+       EventsProvider(LDKEventsProvider&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKEventsProvider)); }
+       operator LDKEventsProvider() && { LDKEventsProvider res = self; memset(&self, 0, sizeof(LDKEventsProvider)); return res; }
+       ~EventsProvider() { EventsProvider_free(self); }
+       EventsProvider& operator=(EventsProvider&& o) { EventsProvider_free(self); self = o.self; memset(&o, 0, sizeof(EventsProvider)); return *this; }
+       LDKEventsProvider* operator &() { return &self; }
+       LDKEventsProvider* operator ->() { return &self; }
+       const LDKEventsProvider* operator &() const { return &self; }
+       const LDKEventsProvider* operator ->() const { return &self; }
 };
 class AccessError {
 private:
@@ -396,7 +680,8 @@ public:
        AccessError(const AccessError&) = delete;
        AccessError(AccessError&& o) : self(o.self) { memset(&o, 0, sizeof(AccessError)); }
        AccessError(LDKAccessError&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKAccessError)); }
-       operator LDKAccessError() { LDKAccessError res = self; memset(&self, 0, sizeof(LDKAccessError)); return res; }
+       operator LDKAccessError() && { LDKAccessError res = self; memset(&self, 0, sizeof(LDKAccessError)); return res; }
+       AccessError& operator=(AccessError&& o) { self = o.self; memset(&o, 0, sizeof(AccessError)); return *this; }
        LDKAccessError* operator &() { return &self; }
        LDKAccessError* operator ->() { return &self; }
        const LDKAccessError* operator &() const { return &self; }
@@ -407,24 +692,41 @@ private:
        LDKAccess self;
 public:
        Access(const Access&) = delete;
-       ~Access() { Access_free(self); }
        Access(Access&& o) : self(o.self) { memset(&o, 0, sizeof(Access)); }
        Access(LDKAccess&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKAccess)); }
-       operator LDKAccess() { LDKAccess res = self; memset(&self, 0, sizeof(LDKAccess)); return res; }
+       operator LDKAccess() && { LDKAccess res = self; memset(&self, 0, sizeof(LDKAccess)); return res; }
+       ~Access() { Access_free(self); }
+       Access& operator=(Access&& o) { Access_free(self); self = o.self; memset(&o, 0, sizeof(Access)); return *this; }
        LDKAccess* operator &() { return &self; }
        LDKAccess* operator ->() { return &self; }
        const LDKAccess* operator &() const { return &self; }
        const LDKAccess* operator ->() const { return &self; }
 };
+class Listen {
+private:
+       LDKListen self;
+public:
+       Listen(const Listen&) = delete;
+       Listen(Listen&& o) : self(o.self) { memset(&o, 0, sizeof(Listen)); }
+       Listen(LDKListen&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKListen)); }
+       operator LDKListen() && { LDKListen res = self; memset(&self, 0, sizeof(LDKListen)); return res; }
+       ~Listen() { Listen_free(self); }
+       Listen& operator=(Listen&& o) { Listen_free(self); self = o.self; memset(&o, 0, sizeof(Listen)); return *this; }
+       LDKListen* operator &() { return &self; }
+       LDKListen* operator ->() { return &self; }
+       const LDKListen* operator &() const { return &self; }
+       const LDKListen* operator ->() const { return &self; }
+};
 class Watch {
 private:
        LDKWatch self;
 public:
        Watch(const Watch&) = delete;
-       ~Watch() { Watch_free(self); }
        Watch(Watch&& o) : self(o.self) { memset(&o, 0, sizeof(Watch)); }
        Watch(LDKWatch&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKWatch)); }
-       operator LDKWatch() { LDKWatch res = self; memset(&self, 0, sizeof(LDKWatch)); return res; }
+       operator LDKWatch() && { LDKWatch res = self; memset(&self, 0, sizeof(LDKWatch)); return res; }
+       ~Watch() { Watch_free(self); }
+       Watch& operator=(Watch&& o) { Watch_free(self); self = o.self; memset(&o, 0, sizeof(Watch)); return *this; }
        LDKWatch* operator &() { return &self; }
        LDKWatch* operator ->() { return &self; }
        const LDKWatch* operator &() const { return &self; }
@@ -435,38 +737,85 @@ private:
        LDKFilter self;
 public:
        Filter(const Filter&) = delete;
-       ~Filter() { Filter_free(self); }
        Filter(Filter&& o) : self(o.self) { memset(&o, 0, sizeof(Filter)); }
        Filter(LDKFilter&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKFilter)); }
-       operator LDKFilter() { LDKFilter res = self; memset(&self, 0, sizeof(LDKFilter)); return res; }
+       operator LDKFilter() && { LDKFilter res = self; memset(&self, 0, sizeof(LDKFilter)); return res; }
+       ~Filter() { Filter_free(self); }
+       Filter& operator=(Filter&& o) { Filter_free(self); self = o.self; memset(&o, 0, sizeof(Filter)); return *this; }
        LDKFilter* operator &() { return &self; }
        LDKFilter* operator ->() { return &self; }
        const LDKFilter* operator &() const { return &self; }
        const LDKFilter* operator ->() const { return &self; }
 };
-class ChannelManager {
+class BroadcasterInterface {
 private:
-       LDKChannelManager self;
+       LDKBroadcasterInterface self;
 public:
-       ChannelManager(const ChannelManager&) = delete;
-       ~ChannelManager() { ChannelManager_free(self); }
-       ChannelManager(ChannelManager&& o) : self(o.self) { memset(&o, 0, sizeof(ChannelManager)); }
-       ChannelManager(LDKChannelManager&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKChannelManager)); }
-       operator LDKChannelManager() { LDKChannelManager res = self; memset(&self, 0, sizeof(LDKChannelManager)); return res; }
-       LDKChannelManager* operator &() { return &self; }
-       LDKChannelManager* operator ->() { return &self; }
-       const LDKChannelManager* operator &() const { return &self; }
-       const LDKChannelManager* operator ->() const { return &self; }
+       BroadcasterInterface(const BroadcasterInterface&) = delete;
+       BroadcasterInterface(BroadcasterInterface&& o) : self(o.self) { memset(&o, 0, sizeof(BroadcasterInterface)); }
+       BroadcasterInterface(LDKBroadcasterInterface&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKBroadcasterInterface)); }
+       operator LDKBroadcasterInterface() && { LDKBroadcasterInterface res = self; memset(&self, 0, sizeof(LDKBroadcasterInterface)); return res; }
+       ~BroadcasterInterface() { BroadcasterInterface_free(self); }
+       BroadcasterInterface& operator=(BroadcasterInterface&& o) { BroadcasterInterface_free(self); self = o.self; memset(&o, 0, sizeof(BroadcasterInterface)); return *this; }
+       LDKBroadcasterInterface* operator &() { return &self; }
+       LDKBroadcasterInterface* operator ->() { return &self; }
+       const LDKBroadcasterInterface* operator &() const { return &self; }
+       const LDKBroadcasterInterface* operator ->() const { return &self; }
 };
-class ChannelDetails {
+class ConfirmationTarget {
 private:
-       LDKChannelDetails self;
+       LDKConfirmationTarget self;
 public:
-       ChannelDetails(const ChannelDetails&) = delete;
-       ~ChannelDetails() { ChannelDetails_free(self); }
-       ChannelDetails(ChannelDetails&& o) : self(o.self) { memset(&o, 0, sizeof(ChannelDetails)); }
+       ConfirmationTarget(const ConfirmationTarget&) = delete;
+       ConfirmationTarget(ConfirmationTarget&& o) : self(o.self) { memset(&o, 0, sizeof(ConfirmationTarget)); }
+       ConfirmationTarget(LDKConfirmationTarget&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKConfirmationTarget)); }
+       operator LDKConfirmationTarget() && { LDKConfirmationTarget res = self; memset(&self, 0, sizeof(LDKConfirmationTarget)); return res; }
+       ConfirmationTarget& operator=(ConfirmationTarget&& o) { self = o.self; memset(&o, 0, sizeof(ConfirmationTarget)); return *this; }
+       LDKConfirmationTarget* operator &() { return &self; }
+       LDKConfirmationTarget* operator ->() { return &self; }
+       const LDKConfirmationTarget* operator &() const { return &self; }
+       const LDKConfirmationTarget* operator ->() const { return &self; }
+};
+class FeeEstimator {
+private:
+       LDKFeeEstimator self;
+public:
+       FeeEstimator(const FeeEstimator&) = delete;
+       FeeEstimator(FeeEstimator&& o) : self(o.self) { memset(&o, 0, sizeof(FeeEstimator)); }
+       FeeEstimator(LDKFeeEstimator&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKFeeEstimator)); }
+       operator LDKFeeEstimator() && { LDKFeeEstimator res = self; memset(&self, 0, sizeof(LDKFeeEstimator)); return res; }
+       ~FeeEstimator() { FeeEstimator_free(self); }
+       FeeEstimator& operator=(FeeEstimator&& o) { FeeEstimator_free(self); self = o.self; memset(&o, 0, sizeof(FeeEstimator)); return *this; }
+       LDKFeeEstimator* operator &() { return &self; }
+       LDKFeeEstimator* operator ->() { return &self; }
+       const LDKFeeEstimator* operator &() const { return &self; }
+       const LDKFeeEstimator* operator ->() const { return &self; }
+};
+class ChannelManager {
+private:
+       LDKChannelManager self;
+public:
+       ChannelManager(const ChannelManager&) = delete;
+       ChannelManager(ChannelManager&& o) : self(o.self) { memset(&o, 0, sizeof(ChannelManager)); }
+       ChannelManager(LDKChannelManager&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKChannelManager)); }
+       operator LDKChannelManager() && { LDKChannelManager res = self; memset(&self, 0, sizeof(LDKChannelManager)); return res; }
+       ~ChannelManager() { ChannelManager_free(self); }
+       ChannelManager& operator=(ChannelManager&& o) { ChannelManager_free(self); self = o.self; memset(&o, 0, sizeof(ChannelManager)); return *this; }
+       LDKChannelManager* operator &() { return &self; }
+       LDKChannelManager* operator ->() { return &self; }
+       const LDKChannelManager* operator &() const { return &self; }
+       const LDKChannelManager* operator ->() const { return &self; }
+};
+class ChannelDetails {
+private:
+       LDKChannelDetails self;
+public:
+       ChannelDetails(const ChannelDetails&) = delete;
+       ChannelDetails(ChannelDetails&& o) : self(o.self) { memset(&o, 0, sizeof(ChannelDetails)); }
        ChannelDetails(LDKChannelDetails&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKChannelDetails)); }
-       operator LDKChannelDetails() { LDKChannelDetails res = self; memset(&self, 0, sizeof(LDKChannelDetails)); return res; }
+       operator LDKChannelDetails() && { LDKChannelDetails res = self; memset(&self, 0, sizeof(LDKChannelDetails)); return res; }
+       ~ChannelDetails() { ChannelDetails_free(self); }
+       ChannelDetails& operator=(ChannelDetails&& o) { ChannelDetails_free(self); self = o.self; memset(&o, 0, sizeof(ChannelDetails)); return *this; }
        LDKChannelDetails* operator &() { return &self; }
        LDKChannelDetails* operator ->() { return &self; }
        const LDKChannelDetails* operator &() const { return &self; }
@@ -477,10 +826,11 @@ private:
        LDKPaymentSendFailure self;
 public:
        PaymentSendFailure(const PaymentSendFailure&) = delete;
-       ~PaymentSendFailure() { PaymentSendFailure_free(self); }
        PaymentSendFailure(PaymentSendFailure&& o) : self(o.self) { memset(&o, 0, sizeof(PaymentSendFailure)); }
        PaymentSendFailure(LDKPaymentSendFailure&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKPaymentSendFailure)); }
-       operator LDKPaymentSendFailure() { LDKPaymentSendFailure res = self; memset(&self, 0, sizeof(LDKPaymentSendFailure)); return res; }
+       operator LDKPaymentSendFailure() && { LDKPaymentSendFailure res = self; memset(&self, 0, sizeof(LDKPaymentSendFailure)); return res; }
+       ~PaymentSendFailure() { PaymentSendFailure_free(self); }
+       PaymentSendFailure& operator=(PaymentSendFailure&& o) { PaymentSendFailure_free(self); self = o.self; memset(&o, 0, sizeof(PaymentSendFailure)); return *this; }
        LDKPaymentSendFailure* operator &() { return &self; }
        LDKPaymentSendFailure* operator ->() { return &self; }
        const LDKPaymentSendFailure* operator &() const { return &self; }
@@ -491,24 +841,176 @@ private:
        LDKChannelManagerReadArgs self;
 public:
        ChannelManagerReadArgs(const ChannelManagerReadArgs&) = delete;
-       ~ChannelManagerReadArgs() { ChannelManagerReadArgs_free(self); }
        ChannelManagerReadArgs(ChannelManagerReadArgs&& o) : self(o.self) { memset(&o, 0, sizeof(ChannelManagerReadArgs)); }
        ChannelManagerReadArgs(LDKChannelManagerReadArgs&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKChannelManagerReadArgs)); }
-       operator LDKChannelManagerReadArgs() { LDKChannelManagerReadArgs res = self; memset(&self, 0, sizeof(LDKChannelManagerReadArgs)); return res; }
+       operator LDKChannelManagerReadArgs() && { LDKChannelManagerReadArgs res = self; memset(&self, 0, sizeof(LDKChannelManagerReadArgs)); return res; }
+       ~ChannelManagerReadArgs() { ChannelManagerReadArgs_free(self); }
+       ChannelManagerReadArgs& operator=(ChannelManagerReadArgs&& o) { ChannelManagerReadArgs_free(self); self = o.self; memset(&o, 0, sizeof(ChannelManagerReadArgs)); return *this; }
        LDKChannelManagerReadArgs* operator &() { return &self; }
        LDKChannelManagerReadArgs* operator ->() { return &self; }
        const LDKChannelManagerReadArgs* operator &() const { return &self; }
        const LDKChannelManagerReadArgs* operator ->() const { return &self; }
 };
+class DelayedPaymentOutputDescriptor {
+private:
+       LDKDelayedPaymentOutputDescriptor self;
+public:
+       DelayedPaymentOutputDescriptor(const DelayedPaymentOutputDescriptor&) = delete;
+       DelayedPaymentOutputDescriptor(DelayedPaymentOutputDescriptor&& o) : self(o.self) { memset(&o, 0, sizeof(DelayedPaymentOutputDescriptor)); }
+       DelayedPaymentOutputDescriptor(LDKDelayedPaymentOutputDescriptor&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKDelayedPaymentOutputDescriptor)); }
+       operator LDKDelayedPaymentOutputDescriptor() && { LDKDelayedPaymentOutputDescriptor res = self; memset(&self, 0, sizeof(LDKDelayedPaymentOutputDescriptor)); return res; }
+       ~DelayedPaymentOutputDescriptor() { DelayedPaymentOutputDescriptor_free(self); }
+       DelayedPaymentOutputDescriptor& operator=(DelayedPaymentOutputDescriptor&& o) { DelayedPaymentOutputDescriptor_free(self); self = o.self; memset(&o, 0, sizeof(DelayedPaymentOutputDescriptor)); return *this; }
+       LDKDelayedPaymentOutputDescriptor* operator &() { return &self; }
+       LDKDelayedPaymentOutputDescriptor* operator ->() { return &self; }
+       const LDKDelayedPaymentOutputDescriptor* operator &() const { return &self; }
+       const LDKDelayedPaymentOutputDescriptor* operator ->() const { return &self; }
+};
+class StaticPaymentOutputDescriptor {
+private:
+       LDKStaticPaymentOutputDescriptor self;
+public:
+       StaticPaymentOutputDescriptor(const StaticPaymentOutputDescriptor&) = delete;
+       StaticPaymentOutputDescriptor(StaticPaymentOutputDescriptor&& o) : self(o.self) { memset(&o, 0, sizeof(StaticPaymentOutputDescriptor)); }
+       StaticPaymentOutputDescriptor(LDKStaticPaymentOutputDescriptor&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKStaticPaymentOutputDescriptor)); }
+       operator LDKStaticPaymentOutputDescriptor() && { LDKStaticPaymentOutputDescriptor res = self; memset(&self, 0, sizeof(LDKStaticPaymentOutputDescriptor)); return res; }
+       ~StaticPaymentOutputDescriptor() { StaticPaymentOutputDescriptor_free(self); }
+       StaticPaymentOutputDescriptor& operator=(StaticPaymentOutputDescriptor&& o) { StaticPaymentOutputDescriptor_free(self); self = o.self; memset(&o, 0, sizeof(StaticPaymentOutputDescriptor)); return *this; }
+       LDKStaticPaymentOutputDescriptor* operator &() { return &self; }
+       LDKStaticPaymentOutputDescriptor* operator ->() { return &self; }
+       const LDKStaticPaymentOutputDescriptor* operator &() const { return &self; }
+       const LDKStaticPaymentOutputDescriptor* operator ->() const { return &self; }
+};
+class SpendableOutputDescriptor {
+private:
+       LDKSpendableOutputDescriptor self;
+public:
+       SpendableOutputDescriptor(const SpendableOutputDescriptor&) = delete;
+       SpendableOutputDescriptor(SpendableOutputDescriptor&& o) : self(o.self) { memset(&o, 0, sizeof(SpendableOutputDescriptor)); }
+       SpendableOutputDescriptor(LDKSpendableOutputDescriptor&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKSpendableOutputDescriptor)); }
+       operator LDKSpendableOutputDescriptor() && { LDKSpendableOutputDescriptor res = self; memset(&self, 0, sizeof(LDKSpendableOutputDescriptor)); return res; }
+       ~SpendableOutputDescriptor() { SpendableOutputDescriptor_free(self); }
+       SpendableOutputDescriptor& operator=(SpendableOutputDescriptor&& o) { SpendableOutputDescriptor_free(self); self = o.self; memset(&o, 0, sizeof(SpendableOutputDescriptor)); return *this; }
+       LDKSpendableOutputDescriptor* operator &() { return &self; }
+       LDKSpendableOutputDescriptor* operator ->() { return &self; }
+       const LDKSpendableOutputDescriptor* operator &() const { return &self; }
+       const LDKSpendableOutputDescriptor* operator ->() const { return &self; }
+};
+class Sign {
+private:
+       LDKSign self;
+public:
+       Sign(const Sign&) = delete;
+       Sign(Sign&& o) : self(o.self) { memset(&o, 0, sizeof(Sign)); }
+       Sign(LDKSign&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKSign)); }
+       operator LDKSign() && { LDKSign res = self; memset(&self, 0, sizeof(LDKSign)); return res; }
+       ~Sign() { Sign_free(self); }
+       Sign& operator=(Sign&& o) { Sign_free(self); self = o.self; memset(&o, 0, sizeof(Sign)); return *this; }
+       LDKSign* operator &() { return &self; }
+       LDKSign* operator ->() { return &self; }
+       const LDKSign* operator &() const { return &self; }
+       const LDKSign* operator ->() const { return &self; }
+};
+class KeysInterface {
+private:
+       LDKKeysInterface self;
+public:
+       KeysInterface(const KeysInterface&) = delete;
+       KeysInterface(KeysInterface&& o) : self(o.self) { memset(&o, 0, sizeof(KeysInterface)); }
+       KeysInterface(LDKKeysInterface&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKKeysInterface)); }
+       operator LDKKeysInterface() && { LDKKeysInterface res = self; memset(&self, 0, sizeof(LDKKeysInterface)); return res; }
+       ~KeysInterface() { KeysInterface_free(self); }
+       KeysInterface& operator=(KeysInterface&& o) { KeysInterface_free(self); self = o.self; memset(&o, 0, sizeof(KeysInterface)); return *this; }
+       LDKKeysInterface* operator &() { return &self; }
+       LDKKeysInterface* operator ->() { return &self; }
+       const LDKKeysInterface* operator &() const { return &self; }
+       const LDKKeysInterface* operator ->() const { return &self; }
+};
+class InMemorySigner {
+private:
+       LDKInMemorySigner self;
+public:
+       InMemorySigner(const InMemorySigner&) = delete;
+       InMemorySigner(InMemorySigner&& o) : self(o.self) { memset(&o, 0, sizeof(InMemorySigner)); }
+       InMemorySigner(LDKInMemorySigner&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKInMemorySigner)); }
+       operator LDKInMemorySigner() && { LDKInMemorySigner res = self; memset(&self, 0, sizeof(LDKInMemorySigner)); return res; }
+       ~InMemorySigner() { InMemorySigner_free(self); }
+       InMemorySigner& operator=(InMemorySigner&& o) { InMemorySigner_free(self); self = o.self; memset(&o, 0, sizeof(InMemorySigner)); return *this; }
+       LDKInMemorySigner* operator &() { return &self; }
+       LDKInMemorySigner* operator ->() { return &self; }
+       const LDKInMemorySigner* operator &() const { return &self; }
+       const LDKInMemorySigner* operator ->() const { return &self; }
+};
+class KeysManager {
+private:
+       LDKKeysManager self;
+public:
+       KeysManager(const KeysManager&) = delete;
+       KeysManager(KeysManager&& o) : self(o.self) { memset(&o, 0, sizeof(KeysManager)); }
+       KeysManager(LDKKeysManager&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKKeysManager)); }
+       operator LDKKeysManager() && { LDKKeysManager res = self; memset(&self, 0, sizeof(LDKKeysManager)); return res; }
+       ~KeysManager() { KeysManager_free(self); }
+       KeysManager& operator=(KeysManager&& o) { KeysManager_free(self); self = o.self; memset(&o, 0, sizeof(KeysManager)); return *this; }
+       LDKKeysManager* operator &() { return &self; }
+       LDKKeysManager* operator ->() { return &self; }
+       const LDKKeysManager* operator &() const { return &self; }
+       const LDKKeysManager* operator ->() const { return &self; }
+};
+class RouteHop {
+private:
+       LDKRouteHop self;
+public:
+       RouteHop(const RouteHop&) = delete;
+       RouteHop(RouteHop&& o) : self(o.self) { memset(&o, 0, sizeof(RouteHop)); }
+       RouteHop(LDKRouteHop&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKRouteHop)); }
+       operator LDKRouteHop() && { LDKRouteHop res = self; memset(&self, 0, sizeof(LDKRouteHop)); return res; }
+       ~RouteHop() { RouteHop_free(self); }
+       RouteHop& operator=(RouteHop&& o) { RouteHop_free(self); self = o.self; memset(&o, 0, sizeof(RouteHop)); return *this; }
+       LDKRouteHop* operator &() { return &self; }
+       LDKRouteHop* operator ->() { return &self; }
+       const LDKRouteHop* operator &() const { return &self; }
+       const LDKRouteHop* operator ->() const { return &self; }
+};
+class Route {
+private:
+       LDKRoute self;
+public:
+       Route(const Route&) = delete;
+       Route(Route&& o) : self(o.self) { memset(&o, 0, sizeof(Route)); }
+       Route(LDKRoute&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKRoute)); }
+       operator LDKRoute() && { LDKRoute res = self; memset(&self, 0, sizeof(LDKRoute)); return res; }
+       ~Route() { Route_free(self); }
+       Route& operator=(Route&& o) { Route_free(self); self = o.self; memset(&o, 0, sizeof(Route)); return *this; }
+       LDKRoute* operator &() { return &self; }
+       LDKRoute* operator ->() { return &self; }
+       const LDKRoute* operator &() const { return &self; }
+       const LDKRoute* operator ->() const { return &self; }
+};
+class RouteHint {
+private:
+       LDKRouteHint self;
+public:
+       RouteHint(const RouteHint&) = delete;
+       RouteHint(RouteHint&& o) : self(o.self) { memset(&o, 0, sizeof(RouteHint)); }
+       RouteHint(LDKRouteHint&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKRouteHint)); }
+       operator LDKRouteHint() && { LDKRouteHint res = self; memset(&self, 0, sizeof(LDKRouteHint)); return res; }
+       ~RouteHint() { RouteHint_free(self); }
+       RouteHint& operator=(RouteHint&& o) { RouteHint_free(self); self = o.self; memset(&o, 0, sizeof(RouteHint)); return *this; }
+       LDKRouteHint* operator &() { return &self; }
+       LDKRouteHint* operator ->() { return &self; }
+       const LDKRouteHint* operator &() const { return &self; }
+       const LDKRouteHint* operator ->() const { return &self; }
+};
 class DecodeError {
 private:
        LDKDecodeError self;
 public:
        DecodeError(const DecodeError&) = delete;
-       ~DecodeError() { DecodeError_free(self); }
        DecodeError(DecodeError&& o) : self(o.self) { memset(&o, 0, sizeof(DecodeError)); }
        DecodeError(LDKDecodeError&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKDecodeError)); }
-       operator LDKDecodeError() { LDKDecodeError res = self; memset(&self, 0, sizeof(LDKDecodeError)); return res; }
+       operator LDKDecodeError() && { LDKDecodeError res = self; memset(&self, 0, sizeof(LDKDecodeError)); return res; }
+       ~DecodeError() { DecodeError_free(self); }
+       DecodeError& operator=(DecodeError&& o) { DecodeError_free(self); self = o.self; memset(&o, 0, sizeof(DecodeError)); return *this; }
        LDKDecodeError* operator &() { return &self; }
        LDKDecodeError* operator ->() { return &self; }
        const LDKDecodeError* operator &() const { return &self; }
@@ -519,10 +1021,11 @@ private:
        LDKInit self;
 public:
        Init(const Init&) = delete;
-       ~Init() { Init_free(self); }
        Init(Init&& o) : self(o.self) { memset(&o, 0, sizeof(Init)); }
        Init(LDKInit&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKInit)); }
-       operator LDKInit() { LDKInit res = self; memset(&self, 0, sizeof(LDKInit)); return res; }
+       operator LDKInit() && { LDKInit res = self; memset(&self, 0, sizeof(LDKInit)); return res; }
+       ~Init() { Init_free(self); }
+       Init& operator=(Init&& o) { Init_free(self); self = o.self; memset(&o, 0, sizeof(Init)); return *this; }
        LDKInit* operator &() { return &self; }
        LDKInit* operator ->() { return &self; }
        const LDKInit* operator &() const { return &self; }
@@ -533,10 +1036,11 @@ private:
        LDKErrorMessage self;
 public:
        ErrorMessage(const ErrorMessage&) = delete;
-       ~ErrorMessage() { ErrorMessage_free(self); }
        ErrorMessage(ErrorMessage&& o) : self(o.self) { memset(&o, 0, sizeof(ErrorMessage)); }
        ErrorMessage(LDKErrorMessage&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKErrorMessage)); }
-       operator LDKErrorMessage() { LDKErrorMessage res = self; memset(&self, 0, sizeof(LDKErrorMessage)); return res; }
+       operator LDKErrorMessage() && { LDKErrorMessage res = self; memset(&self, 0, sizeof(LDKErrorMessage)); return res; }
+       ~ErrorMessage() { ErrorMessage_free(self); }
+       ErrorMessage& operator=(ErrorMessage&& o) { ErrorMessage_free(self); self = o.self; memset(&o, 0, sizeof(ErrorMessage)); return *this; }
        LDKErrorMessage* operator &() { return &self; }
        LDKErrorMessage* operator ->() { return &self; }
        const LDKErrorMessage* operator &() const { return &self; }
@@ -547,10 +1051,11 @@ private:
        LDKPing self;
 public:
        Ping(const Ping&) = delete;
-       ~Ping() { Ping_free(self); }
        Ping(Ping&& o) : self(o.self) { memset(&o, 0, sizeof(Ping)); }
        Ping(LDKPing&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKPing)); }
-       operator LDKPing() { LDKPing res = self; memset(&self, 0, sizeof(LDKPing)); return res; }
+       operator LDKPing() && { LDKPing res = self; memset(&self, 0, sizeof(LDKPing)); return res; }
+       ~Ping() { Ping_free(self); }
+       Ping& operator=(Ping&& o) { Ping_free(self); self = o.self; memset(&o, 0, sizeof(Ping)); return *this; }
        LDKPing* operator &() { return &self; }
        LDKPing* operator ->() { return &self; }
        const LDKPing* operator &() const { return &self; }
@@ -561,10 +1066,11 @@ private:
        LDKPong self;
 public:
        Pong(const Pong&) = delete;
-       ~Pong() { Pong_free(self); }
        Pong(Pong&& o) : self(o.self) { memset(&o, 0, sizeof(Pong)); }
        Pong(LDKPong&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKPong)); }
-       operator LDKPong() { LDKPong res = self; memset(&self, 0, sizeof(LDKPong)); return res; }
+       operator LDKPong() && { LDKPong res = self; memset(&self, 0, sizeof(LDKPong)); return res; }
+       ~Pong() { Pong_free(self); }
+       Pong& operator=(Pong&& o) { Pong_free(self); self = o.self; memset(&o, 0, sizeof(Pong)); return *this; }
        LDKPong* operator &() { return &self; }
        LDKPong* operator ->() { return &self; }
        const LDKPong* operator &() const { return &self; }
@@ -575,10 +1081,11 @@ private:
        LDKOpenChannel self;
 public:
        OpenChannel(const OpenChannel&) = delete;
-       ~OpenChannel() { OpenChannel_free(self); }
        OpenChannel(OpenChannel&& o) : self(o.self) { memset(&o, 0, sizeof(OpenChannel)); }
        OpenChannel(LDKOpenChannel&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKOpenChannel)); }
-       operator LDKOpenChannel() { LDKOpenChannel res = self; memset(&self, 0, sizeof(LDKOpenChannel)); return res; }
+       operator LDKOpenChannel() && { LDKOpenChannel res = self; memset(&self, 0, sizeof(LDKOpenChannel)); return res; }
+       ~OpenChannel() { OpenChannel_free(self); }
+       OpenChannel& operator=(OpenChannel&& o) { OpenChannel_free(self); self = o.self; memset(&o, 0, sizeof(OpenChannel)); return *this; }
        LDKOpenChannel* operator &() { return &self; }
        LDKOpenChannel* operator ->() { return &self; }
        const LDKOpenChannel* operator &() const { return &self; }
@@ -589,10 +1096,11 @@ private:
        LDKAcceptChannel self;
 public:
        AcceptChannel(const AcceptChannel&) = delete;
-       ~AcceptChannel() { AcceptChannel_free(self); }
        AcceptChannel(AcceptChannel&& o) : self(o.self) { memset(&o, 0, sizeof(AcceptChannel)); }
        AcceptChannel(LDKAcceptChannel&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKAcceptChannel)); }
-       operator LDKAcceptChannel() { LDKAcceptChannel res = self; memset(&self, 0, sizeof(LDKAcceptChannel)); return res; }
+       operator LDKAcceptChannel() && { LDKAcceptChannel res = self; memset(&self, 0, sizeof(LDKAcceptChannel)); return res; }
+       ~AcceptChannel() { AcceptChannel_free(self); }
+       AcceptChannel& operator=(AcceptChannel&& o) { AcceptChannel_free(self); self = o.self; memset(&o, 0, sizeof(AcceptChannel)); return *this; }
        LDKAcceptChannel* operator &() { return &self; }
        LDKAcceptChannel* operator ->() { return &self; }
        const LDKAcceptChannel* operator &() const { return &self; }
@@ -603,10 +1111,11 @@ private:
        LDKFundingCreated self;
 public:
        FundingCreated(const FundingCreated&) = delete;
-       ~FundingCreated() { FundingCreated_free(self); }
        FundingCreated(FundingCreated&& o) : self(o.self) { memset(&o, 0, sizeof(FundingCreated)); }
        FundingCreated(LDKFundingCreated&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKFundingCreated)); }
-       operator LDKFundingCreated() { LDKFundingCreated res = self; memset(&self, 0, sizeof(LDKFundingCreated)); return res; }
+       operator LDKFundingCreated() && { LDKFundingCreated res = self; memset(&self, 0, sizeof(LDKFundingCreated)); return res; }
+       ~FundingCreated() { FundingCreated_free(self); }
+       FundingCreated& operator=(FundingCreated&& o) { FundingCreated_free(self); self = o.self; memset(&o, 0, sizeof(FundingCreated)); return *this; }
        LDKFundingCreated* operator &() { return &self; }
        LDKFundingCreated* operator ->() { return &self; }
        const LDKFundingCreated* operator &() const { return &self; }
@@ -617,10 +1126,11 @@ private:
        LDKFundingSigned self;
 public:
        FundingSigned(const FundingSigned&) = delete;
-       ~FundingSigned() { FundingSigned_free(self); }
        FundingSigned(FundingSigned&& o) : self(o.self) { memset(&o, 0, sizeof(FundingSigned)); }
        FundingSigned(LDKFundingSigned&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKFundingSigned)); }
-       operator LDKFundingSigned() { LDKFundingSigned res = self; memset(&self, 0, sizeof(LDKFundingSigned)); return res; }
+       operator LDKFundingSigned() && { LDKFundingSigned res = self; memset(&self, 0, sizeof(LDKFundingSigned)); return res; }
+       ~FundingSigned() { FundingSigned_free(self); }
+       FundingSigned& operator=(FundingSigned&& o) { FundingSigned_free(self); self = o.self; memset(&o, 0, sizeof(FundingSigned)); return *this; }
        LDKFundingSigned* operator &() { return &self; }
        LDKFundingSigned* operator ->() { return &self; }
        const LDKFundingSigned* operator &() const { return &self; }
@@ -631,10 +1141,11 @@ private:
        LDKFundingLocked self;
 public:
        FundingLocked(const FundingLocked&) = delete;
-       ~FundingLocked() { FundingLocked_free(self); }
        FundingLocked(FundingLocked&& o) : self(o.self) { memset(&o, 0, sizeof(FundingLocked)); }
        FundingLocked(LDKFundingLocked&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKFundingLocked)); }
-       operator LDKFundingLocked() { LDKFundingLocked res = self; memset(&self, 0, sizeof(LDKFundingLocked)); return res; }
+       operator LDKFundingLocked() && { LDKFundingLocked res = self; memset(&self, 0, sizeof(LDKFundingLocked)); return res; }
+       ~FundingLocked() { FundingLocked_free(self); }
+       FundingLocked& operator=(FundingLocked&& o) { FundingLocked_free(self); self = o.self; memset(&o, 0, sizeof(FundingLocked)); return *this; }
        LDKFundingLocked* operator &() { return &self; }
        LDKFundingLocked* operator ->() { return &self; }
        const LDKFundingLocked* operator &() const { return &self; }
@@ -645,10 +1156,11 @@ private:
        LDKShutdown self;
 public:
        Shutdown(const Shutdown&) = delete;
-       ~Shutdown() { Shutdown_free(self); }
        Shutdown(Shutdown&& o) : self(o.self) { memset(&o, 0, sizeof(Shutdown)); }
        Shutdown(LDKShutdown&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKShutdown)); }
-       operator LDKShutdown() { LDKShutdown res = self; memset(&self, 0, sizeof(LDKShutdown)); return res; }
+       operator LDKShutdown() && { LDKShutdown res = self; memset(&self, 0, sizeof(LDKShutdown)); return res; }
+       ~Shutdown() { Shutdown_free(self); }
+       Shutdown& operator=(Shutdown&& o) { Shutdown_free(self); self = o.self; memset(&o, 0, sizeof(Shutdown)); return *this; }
        LDKShutdown* operator &() { return &self; }
        LDKShutdown* operator ->() { return &self; }
        const LDKShutdown* operator &() const { return &self; }
@@ -659,10 +1171,11 @@ private:
        LDKClosingSigned self;
 public:
        ClosingSigned(const ClosingSigned&) = delete;
-       ~ClosingSigned() { ClosingSigned_free(self); }
        ClosingSigned(ClosingSigned&& o) : self(o.self) { memset(&o, 0, sizeof(ClosingSigned)); }
        ClosingSigned(LDKClosingSigned&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKClosingSigned)); }
-       operator LDKClosingSigned() { LDKClosingSigned res = self; memset(&self, 0, sizeof(LDKClosingSigned)); return res; }
+       operator LDKClosingSigned() && { LDKClosingSigned res = self; memset(&self, 0, sizeof(LDKClosingSigned)); return res; }
+       ~ClosingSigned() { ClosingSigned_free(self); }
+       ClosingSigned& operator=(ClosingSigned&& o) { ClosingSigned_free(self); self = o.self; memset(&o, 0, sizeof(ClosingSigned)); return *this; }
        LDKClosingSigned* operator &() { return &self; }
        LDKClosingSigned* operator ->() { return &self; }
        const LDKClosingSigned* operator &() const { return &self; }
@@ -673,10 +1186,11 @@ private:
        LDKUpdateAddHTLC self;
 public:
        UpdateAddHTLC(const UpdateAddHTLC&) = delete;
-       ~UpdateAddHTLC() { UpdateAddHTLC_free(self); }
        UpdateAddHTLC(UpdateAddHTLC&& o) : self(o.self) { memset(&o, 0, sizeof(UpdateAddHTLC)); }
        UpdateAddHTLC(LDKUpdateAddHTLC&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKUpdateAddHTLC)); }
-       operator LDKUpdateAddHTLC() { LDKUpdateAddHTLC res = self; memset(&self, 0, sizeof(LDKUpdateAddHTLC)); return res; }
+       operator LDKUpdateAddHTLC() && { LDKUpdateAddHTLC res = self; memset(&self, 0, sizeof(LDKUpdateAddHTLC)); return res; }
+       ~UpdateAddHTLC() { UpdateAddHTLC_free(self); }
+       UpdateAddHTLC& operator=(UpdateAddHTLC&& o) { UpdateAddHTLC_free(self); self = o.self; memset(&o, 0, sizeof(UpdateAddHTLC)); return *this; }
        LDKUpdateAddHTLC* operator &() { return &self; }
        LDKUpdateAddHTLC* operator ->() { return &self; }
        const LDKUpdateAddHTLC* operator &() const { return &self; }
@@ -687,10 +1201,11 @@ private:
        LDKUpdateFulfillHTLC self;
 public:
        UpdateFulfillHTLC(const UpdateFulfillHTLC&) = delete;
-       ~UpdateFulfillHTLC() { UpdateFulfillHTLC_free(self); }
        UpdateFulfillHTLC(UpdateFulfillHTLC&& o) : self(o.self) { memset(&o, 0, sizeof(UpdateFulfillHTLC)); }
        UpdateFulfillHTLC(LDKUpdateFulfillHTLC&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKUpdateFulfillHTLC)); }
-       operator LDKUpdateFulfillHTLC() { LDKUpdateFulfillHTLC res = self; memset(&self, 0, sizeof(LDKUpdateFulfillHTLC)); return res; }
+       operator LDKUpdateFulfillHTLC() && { LDKUpdateFulfillHTLC res = self; memset(&self, 0, sizeof(LDKUpdateFulfillHTLC)); return res; }
+       ~UpdateFulfillHTLC() { UpdateFulfillHTLC_free(self); }
+       UpdateFulfillHTLC& operator=(UpdateFulfillHTLC&& o) { UpdateFulfillHTLC_free(self); self = o.self; memset(&o, 0, sizeof(UpdateFulfillHTLC)); return *this; }
        LDKUpdateFulfillHTLC* operator &() { return &self; }
        LDKUpdateFulfillHTLC* operator ->() { return &self; }
        const LDKUpdateFulfillHTLC* operator &() const { return &self; }
@@ -701,10 +1216,11 @@ private:
        LDKUpdateFailHTLC self;
 public:
        UpdateFailHTLC(const UpdateFailHTLC&) = delete;
-       ~UpdateFailHTLC() { UpdateFailHTLC_free(self); }
        UpdateFailHTLC(UpdateFailHTLC&& o) : self(o.self) { memset(&o, 0, sizeof(UpdateFailHTLC)); }
        UpdateFailHTLC(LDKUpdateFailHTLC&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKUpdateFailHTLC)); }
-       operator LDKUpdateFailHTLC() { LDKUpdateFailHTLC res = self; memset(&self, 0, sizeof(LDKUpdateFailHTLC)); return res; }
+       operator LDKUpdateFailHTLC() && { LDKUpdateFailHTLC res = self; memset(&self, 0, sizeof(LDKUpdateFailHTLC)); return res; }
+       ~UpdateFailHTLC() { UpdateFailHTLC_free(self); }
+       UpdateFailHTLC& operator=(UpdateFailHTLC&& o) { UpdateFailHTLC_free(self); self = o.self; memset(&o, 0, sizeof(UpdateFailHTLC)); return *this; }
        LDKUpdateFailHTLC* operator &() { return &self; }
        LDKUpdateFailHTLC* operator ->() { return &self; }
        const LDKUpdateFailHTLC* operator &() const { return &self; }
@@ -715,10 +1231,11 @@ private:
        LDKUpdateFailMalformedHTLC self;
 public:
        UpdateFailMalformedHTLC(const UpdateFailMalformedHTLC&) = delete;
-       ~UpdateFailMalformedHTLC() { UpdateFailMalformedHTLC_free(self); }
        UpdateFailMalformedHTLC(UpdateFailMalformedHTLC&& o) : self(o.self) { memset(&o, 0, sizeof(UpdateFailMalformedHTLC)); }
        UpdateFailMalformedHTLC(LDKUpdateFailMalformedHTLC&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKUpdateFailMalformedHTLC)); }
-       operator LDKUpdateFailMalformedHTLC() { LDKUpdateFailMalformedHTLC res = self; memset(&self, 0, sizeof(LDKUpdateFailMalformedHTLC)); return res; }
+       operator LDKUpdateFailMalformedHTLC() && { LDKUpdateFailMalformedHTLC res = self; memset(&self, 0, sizeof(LDKUpdateFailMalformedHTLC)); return res; }
+       ~UpdateFailMalformedHTLC() { UpdateFailMalformedHTLC_free(self); }
+       UpdateFailMalformedHTLC& operator=(UpdateFailMalformedHTLC&& o) { UpdateFailMalformedHTLC_free(self); self = o.self; memset(&o, 0, sizeof(UpdateFailMalformedHTLC)); return *this; }
        LDKUpdateFailMalformedHTLC* operator &() { return &self; }
        LDKUpdateFailMalformedHTLC* operator ->() { return &self; }
        const LDKUpdateFailMalformedHTLC* operator &() const { return &self; }
@@ -729,10 +1246,11 @@ private:
        LDKCommitmentSigned self;
 public:
        CommitmentSigned(const CommitmentSigned&) = delete;
-       ~CommitmentSigned() { CommitmentSigned_free(self); }
        CommitmentSigned(CommitmentSigned&& o) : self(o.self) { memset(&o, 0, sizeof(CommitmentSigned)); }
        CommitmentSigned(LDKCommitmentSigned&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCommitmentSigned)); }
-       operator LDKCommitmentSigned() { LDKCommitmentSigned res = self; memset(&self, 0, sizeof(LDKCommitmentSigned)); return res; }
+       operator LDKCommitmentSigned() && { LDKCommitmentSigned res = self; memset(&self, 0, sizeof(LDKCommitmentSigned)); return res; }
+       ~CommitmentSigned() { CommitmentSigned_free(self); }
+       CommitmentSigned& operator=(CommitmentSigned&& o) { CommitmentSigned_free(self); self = o.self; memset(&o, 0, sizeof(CommitmentSigned)); return *this; }
        LDKCommitmentSigned* operator &() { return &self; }
        LDKCommitmentSigned* operator ->() { return &self; }
        const LDKCommitmentSigned* operator &() const { return &self; }
@@ -743,10 +1261,11 @@ private:
        LDKRevokeAndACK self;
 public:
        RevokeAndACK(const RevokeAndACK&) = delete;
-       ~RevokeAndACK() { RevokeAndACK_free(self); }
        RevokeAndACK(RevokeAndACK&& o) : self(o.self) { memset(&o, 0, sizeof(RevokeAndACK)); }
        RevokeAndACK(LDKRevokeAndACK&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKRevokeAndACK)); }
-       operator LDKRevokeAndACK() { LDKRevokeAndACK res = self; memset(&self, 0, sizeof(LDKRevokeAndACK)); return res; }
+       operator LDKRevokeAndACK() && { LDKRevokeAndACK res = self; memset(&self, 0, sizeof(LDKRevokeAndACK)); return res; }
+       ~RevokeAndACK() { RevokeAndACK_free(self); }
+       RevokeAndACK& operator=(RevokeAndACK&& o) { RevokeAndACK_free(self); self = o.self; memset(&o, 0, sizeof(RevokeAndACK)); return *this; }
        LDKRevokeAndACK* operator &() { return &self; }
        LDKRevokeAndACK* operator ->() { return &self; }
        const LDKRevokeAndACK* operator &() const { return &self; }
@@ -757,10 +1276,11 @@ private:
        LDKUpdateFee self;
 public:
        UpdateFee(const UpdateFee&) = delete;
-       ~UpdateFee() { UpdateFee_free(self); }
        UpdateFee(UpdateFee&& o) : self(o.self) { memset(&o, 0, sizeof(UpdateFee)); }
        UpdateFee(LDKUpdateFee&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKUpdateFee)); }
-       operator LDKUpdateFee() { LDKUpdateFee res = self; memset(&self, 0, sizeof(LDKUpdateFee)); return res; }
+       operator LDKUpdateFee() && { LDKUpdateFee res = self; memset(&self, 0, sizeof(LDKUpdateFee)); return res; }
+       ~UpdateFee() { UpdateFee_free(self); }
+       UpdateFee& operator=(UpdateFee&& o) { UpdateFee_free(self); self = o.self; memset(&o, 0, sizeof(UpdateFee)); return *this; }
        LDKUpdateFee* operator &() { return &self; }
        LDKUpdateFee* operator ->() { return &self; }
        const LDKUpdateFee* operator &() const { return &self; }
@@ -771,10 +1291,11 @@ private:
        LDKDataLossProtect self;
 public:
        DataLossProtect(const DataLossProtect&) = delete;
-       ~DataLossProtect() { DataLossProtect_free(self); }
        DataLossProtect(DataLossProtect&& o) : self(o.self) { memset(&o, 0, sizeof(DataLossProtect)); }
        DataLossProtect(LDKDataLossProtect&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKDataLossProtect)); }
-       operator LDKDataLossProtect() { LDKDataLossProtect res = self; memset(&self, 0, sizeof(LDKDataLossProtect)); return res; }
+       operator LDKDataLossProtect() && { LDKDataLossProtect res = self; memset(&self, 0, sizeof(LDKDataLossProtect)); return res; }
+       ~DataLossProtect() { DataLossProtect_free(self); }
+       DataLossProtect& operator=(DataLossProtect&& o) { DataLossProtect_free(self); self = o.self; memset(&o, 0, sizeof(DataLossProtect)); return *this; }
        LDKDataLossProtect* operator &() { return &self; }
        LDKDataLossProtect* operator ->() { return &self; }
        const LDKDataLossProtect* operator &() const { return &self; }
@@ -785,10 +1306,11 @@ private:
        LDKChannelReestablish self;
 public:
        ChannelReestablish(const ChannelReestablish&) = delete;
-       ~ChannelReestablish() { ChannelReestablish_free(self); }
        ChannelReestablish(ChannelReestablish&& o) : self(o.self) { memset(&o, 0, sizeof(ChannelReestablish)); }
        ChannelReestablish(LDKChannelReestablish&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKChannelReestablish)); }
-       operator LDKChannelReestablish() { LDKChannelReestablish res = self; memset(&self, 0, sizeof(LDKChannelReestablish)); return res; }
+       operator LDKChannelReestablish() && { LDKChannelReestablish res = self; memset(&self, 0, sizeof(LDKChannelReestablish)); return res; }
+       ~ChannelReestablish() { ChannelReestablish_free(self); }
+       ChannelReestablish& operator=(ChannelReestablish&& o) { ChannelReestablish_free(self); self = o.self; memset(&o, 0, sizeof(ChannelReestablish)); return *this; }
        LDKChannelReestablish* operator &() { return &self; }
        LDKChannelReestablish* operator ->() { return &self; }
        const LDKChannelReestablish* operator &() const { return &self; }
@@ -799,10 +1321,11 @@ private:
        LDKAnnouncementSignatures self;
 public:
        AnnouncementSignatures(const AnnouncementSignatures&) = delete;
-       ~AnnouncementSignatures() { AnnouncementSignatures_free(self); }
        AnnouncementSignatures(AnnouncementSignatures&& o) : self(o.self) { memset(&o, 0, sizeof(AnnouncementSignatures)); }
        AnnouncementSignatures(LDKAnnouncementSignatures&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKAnnouncementSignatures)); }
-       operator LDKAnnouncementSignatures() { LDKAnnouncementSignatures res = self; memset(&self, 0, sizeof(LDKAnnouncementSignatures)); return res; }
+       operator LDKAnnouncementSignatures() && { LDKAnnouncementSignatures res = self; memset(&self, 0, sizeof(LDKAnnouncementSignatures)); return res; }
+       ~AnnouncementSignatures() { AnnouncementSignatures_free(self); }
+       AnnouncementSignatures& operator=(AnnouncementSignatures&& o) { AnnouncementSignatures_free(self); self = o.self; memset(&o, 0, sizeof(AnnouncementSignatures)); return *this; }
        LDKAnnouncementSignatures* operator &() { return &self; }
        LDKAnnouncementSignatures* operator ->() { return &self; }
        const LDKAnnouncementSignatures* operator &() const { return &self; }
@@ -813,10 +1336,11 @@ private:
        LDKNetAddress self;
 public:
        NetAddress(const NetAddress&) = delete;
-       ~NetAddress() { NetAddress_free(self); }
        NetAddress(NetAddress&& o) : self(o.self) { memset(&o, 0, sizeof(NetAddress)); }
        NetAddress(LDKNetAddress&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKNetAddress)); }
-       operator LDKNetAddress() { LDKNetAddress res = self; memset(&self, 0, sizeof(LDKNetAddress)); return res; }
+       operator LDKNetAddress() && { LDKNetAddress res = self; memset(&self, 0, sizeof(LDKNetAddress)); return res; }
+       ~NetAddress() { NetAddress_free(self); }
+       NetAddress& operator=(NetAddress&& o) { NetAddress_free(self); self = o.self; memset(&o, 0, sizeof(NetAddress)); return *this; }
        LDKNetAddress* operator &() { return &self; }
        LDKNetAddress* operator ->() { return &self; }
        const LDKNetAddress* operator &() const { return &self; }
@@ -827,10 +1351,11 @@ private:
        LDKUnsignedNodeAnnouncement self;
 public:
        UnsignedNodeAnnouncement(const UnsignedNodeAnnouncement&) = delete;
-       ~UnsignedNodeAnnouncement() { UnsignedNodeAnnouncement_free(self); }
        UnsignedNodeAnnouncement(UnsignedNodeAnnouncement&& o) : self(o.self) { memset(&o, 0, sizeof(UnsignedNodeAnnouncement)); }
        UnsignedNodeAnnouncement(LDKUnsignedNodeAnnouncement&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKUnsignedNodeAnnouncement)); }
-       operator LDKUnsignedNodeAnnouncement() { LDKUnsignedNodeAnnouncement res = self; memset(&self, 0, sizeof(LDKUnsignedNodeAnnouncement)); return res; }
+       operator LDKUnsignedNodeAnnouncement() && { LDKUnsignedNodeAnnouncement res = self; memset(&self, 0, sizeof(LDKUnsignedNodeAnnouncement)); return res; }
+       ~UnsignedNodeAnnouncement() { UnsignedNodeAnnouncement_free(self); }
+       UnsignedNodeAnnouncement& operator=(UnsignedNodeAnnouncement&& o) { UnsignedNodeAnnouncement_free(self); self = o.self; memset(&o, 0, sizeof(UnsignedNodeAnnouncement)); return *this; }
        LDKUnsignedNodeAnnouncement* operator &() { return &self; }
        LDKUnsignedNodeAnnouncement* operator ->() { return &self; }
        const LDKUnsignedNodeAnnouncement* operator &() const { return &self; }
@@ -841,10 +1366,11 @@ private:
        LDKNodeAnnouncement self;
 public:
        NodeAnnouncement(const NodeAnnouncement&) = delete;
-       ~NodeAnnouncement() { NodeAnnouncement_free(self); }
        NodeAnnouncement(NodeAnnouncement&& o) : self(o.self) { memset(&o, 0, sizeof(NodeAnnouncement)); }
        NodeAnnouncement(LDKNodeAnnouncement&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKNodeAnnouncement)); }
-       operator LDKNodeAnnouncement() { LDKNodeAnnouncement res = self; memset(&self, 0, sizeof(LDKNodeAnnouncement)); return res; }
+       operator LDKNodeAnnouncement() && { LDKNodeAnnouncement res = self; memset(&self, 0, sizeof(LDKNodeAnnouncement)); return res; }
+       ~NodeAnnouncement() { NodeAnnouncement_free(self); }
+       NodeAnnouncement& operator=(NodeAnnouncement&& o) { NodeAnnouncement_free(self); self = o.self; memset(&o, 0, sizeof(NodeAnnouncement)); return *this; }
        LDKNodeAnnouncement* operator &() { return &self; }
        LDKNodeAnnouncement* operator ->() { return &self; }
        const LDKNodeAnnouncement* operator &() const { return &self; }
@@ -855,10 +1381,11 @@ private:
        LDKUnsignedChannelAnnouncement self;
 public:
        UnsignedChannelAnnouncement(const UnsignedChannelAnnouncement&) = delete;
-       ~UnsignedChannelAnnouncement() { UnsignedChannelAnnouncement_free(self); }
        UnsignedChannelAnnouncement(UnsignedChannelAnnouncement&& o) : self(o.self) { memset(&o, 0, sizeof(UnsignedChannelAnnouncement)); }
        UnsignedChannelAnnouncement(LDKUnsignedChannelAnnouncement&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKUnsignedChannelAnnouncement)); }
-       operator LDKUnsignedChannelAnnouncement() { LDKUnsignedChannelAnnouncement res = self; memset(&self, 0, sizeof(LDKUnsignedChannelAnnouncement)); return res; }
+       operator LDKUnsignedChannelAnnouncement() && { LDKUnsignedChannelAnnouncement res = self; memset(&self, 0, sizeof(LDKUnsignedChannelAnnouncement)); return res; }
+       ~UnsignedChannelAnnouncement() { UnsignedChannelAnnouncement_free(self); }
+       UnsignedChannelAnnouncement& operator=(UnsignedChannelAnnouncement&& o) { UnsignedChannelAnnouncement_free(self); self = o.self; memset(&o, 0, sizeof(UnsignedChannelAnnouncement)); return *this; }
        LDKUnsignedChannelAnnouncement* operator &() { return &self; }
        LDKUnsignedChannelAnnouncement* operator ->() { return &self; }
        const LDKUnsignedChannelAnnouncement* operator &() const { return &self; }
@@ -869,10 +1396,11 @@ private:
        LDKChannelAnnouncement self;
 public:
        ChannelAnnouncement(const ChannelAnnouncement&) = delete;
-       ~ChannelAnnouncement() { ChannelAnnouncement_free(self); }
        ChannelAnnouncement(ChannelAnnouncement&& o) : self(o.self) { memset(&o, 0, sizeof(ChannelAnnouncement)); }
        ChannelAnnouncement(LDKChannelAnnouncement&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKChannelAnnouncement)); }
-       operator LDKChannelAnnouncement() { LDKChannelAnnouncement res = self; memset(&self, 0, sizeof(LDKChannelAnnouncement)); return res; }
+       operator LDKChannelAnnouncement() && { LDKChannelAnnouncement res = self; memset(&self, 0, sizeof(LDKChannelAnnouncement)); return res; }
+       ~ChannelAnnouncement() { ChannelAnnouncement_free(self); }
+       ChannelAnnouncement& operator=(ChannelAnnouncement&& o) { ChannelAnnouncement_free(self); self = o.self; memset(&o, 0, sizeof(ChannelAnnouncement)); return *this; }
        LDKChannelAnnouncement* operator &() { return &self; }
        LDKChannelAnnouncement* operator ->() { return &self; }
        const LDKChannelAnnouncement* operator &() const { return &self; }
@@ -883,10 +1411,11 @@ private:
        LDKUnsignedChannelUpdate self;
 public:
        UnsignedChannelUpdate(const UnsignedChannelUpdate&) = delete;
-       ~UnsignedChannelUpdate() { UnsignedChannelUpdate_free(self); }
        UnsignedChannelUpdate(UnsignedChannelUpdate&& o) : self(o.self) { memset(&o, 0, sizeof(UnsignedChannelUpdate)); }
        UnsignedChannelUpdate(LDKUnsignedChannelUpdate&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKUnsignedChannelUpdate)); }
-       operator LDKUnsignedChannelUpdate() { LDKUnsignedChannelUpdate res = self; memset(&self, 0, sizeof(LDKUnsignedChannelUpdate)); return res; }
+       operator LDKUnsignedChannelUpdate() && { LDKUnsignedChannelUpdate res = self; memset(&self, 0, sizeof(LDKUnsignedChannelUpdate)); return res; }
+       ~UnsignedChannelUpdate() { UnsignedChannelUpdate_free(self); }
+       UnsignedChannelUpdate& operator=(UnsignedChannelUpdate&& o) { UnsignedChannelUpdate_free(self); self = o.self; memset(&o, 0, sizeof(UnsignedChannelUpdate)); return *this; }
        LDKUnsignedChannelUpdate* operator &() { return &self; }
        LDKUnsignedChannelUpdate* operator ->() { return &self; }
        const LDKUnsignedChannelUpdate* operator &() const { return &self; }
@@ -897,10 +1426,11 @@ private:
        LDKChannelUpdate self;
 public:
        ChannelUpdate(const ChannelUpdate&) = delete;
-       ~ChannelUpdate() { ChannelUpdate_free(self); }
        ChannelUpdate(ChannelUpdate&& o) : self(o.self) { memset(&o, 0, sizeof(ChannelUpdate)); }
        ChannelUpdate(LDKChannelUpdate&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKChannelUpdate)); }
-       operator LDKChannelUpdate() { LDKChannelUpdate res = self; memset(&self, 0, sizeof(LDKChannelUpdate)); return res; }
+       operator LDKChannelUpdate() && { LDKChannelUpdate res = self; memset(&self, 0, sizeof(LDKChannelUpdate)); return res; }
+       ~ChannelUpdate() { ChannelUpdate_free(self); }
+       ChannelUpdate& operator=(ChannelUpdate&& o) { ChannelUpdate_free(self); self = o.self; memset(&o, 0, sizeof(ChannelUpdate)); return *this; }
        LDKChannelUpdate* operator &() { return &self; }
        LDKChannelUpdate* operator ->() { return &self; }
        const LDKChannelUpdate* operator &() const { return &self; }
@@ -911,10 +1441,11 @@ private:
        LDKQueryChannelRange self;
 public:
        QueryChannelRange(const QueryChannelRange&) = delete;
-       ~QueryChannelRange() { QueryChannelRange_free(self); }
        QueryChannelRange(QueryChannelRange&& o) : self(o.self) { memset(&o, 0, sizeof(QueryChannelRange)); }
        QueryChannelRange(LDKQueryChannelRange&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKQueryChannelRange)); }
-       operator LDKQueryChannelRange() { LDKQueryChannelRange res = self; memset(&self, 0, sizeof(LDKQueryChannelRange)); return res; }
+       operator LDKQueryChannelRange() && { LDKQueryChannelRange res = self; memset(&self, 0, sizeof(LDKQueryChannelRange)); return res; }
+       ~QueryChannelRange() { QueryChannelRange_free(self); }
+       QueryChannelRange& operator=(QueryChannelRange&& o) { QueryChannelRange_free(self); self = o.self; memset(&o, 0, sizeof(QueryChannelRange)); return *this; }
        LDKQueryChannelRange* operator &() { return &self; }
        LDKQueryChannelRange* operator ->() { return &self; }
        const LDKQueryChannelRange* operator &() const { return &self; }
@@ -925,10 +1456,11 @@ private:
        LDKReplyChannelRange self;
 public:
        ReplyChannelRange(const ReplyChannelRange&) = delete;
-       ~ReplyChannelRange() { ReplyChannelRange_free(self); }
        ReplyChannelRange(ReplyChannelRange&& o) : self(o.self) { memset(&o, 0, sizeof(ReplyChannelRange)); }
        ReplyChannelRange(LDKReplyChannelRange&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKReplyChannelRange)); }
-       operator LDKReplyChannelRange() { LDKReplyChannelRange res = self; memset(&self, 0, sizeof(LDKReplyChannelRange)); return res; }
+       operator LDKReplyChannelRange() && { LDKReplyChannelRange res = self; memset(&self, 0, sizeof(LDKReplyChannelRange)); return res; }
+       ~ReplyChannelRange() { ReplyChannelRange_free(self); }
+       ReplyChannelRange& operator=(ReplyChannelRange&& o) { ReplyChannelRange_free(self); self = o.self; memset(&o, 0, sizeof(ReplyChannelRange)); return *this; }
        LDKReplyChannelRange* operator &() { return &self; }
        LDKReplyChannelRange* operator ->() { return &self; }
        const LDKReplyChannelRange* operator &() const { return &self; }
@@ -939,10 +1471,11 @@ private:
        LDKQueryShortChannelIds self;
 public:
        QueryShortChannelIds(const QueryShortChannelIds&) = delete;
-       ~QueryShortChannelIds() { QueryShortChannelIds_free(self); }
        QueryShortChannelIds(QueryShortChannelIds&& o) : self(o.self) { memset(&o, 0, sizeof(QueryShortChannelIds)); }
        QueryShortChannelIds(LDKQueryShortChannelIds&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKQueryShortChannelIds)); }
-       operator LDKQueryShortChannelIds() { LDKQueryShortChannelIds res = self; memset(&self, 0, sizeof(LDKQueryShortChannelIds)); return res; }
+       operator LDKQueryShortChannelIds() && { LDKQueryShortChannelIds res = self; memset(&self, 0, sizeof(LDKQueryShortChannelIds)); return res; }
+       ~QueryShortChannelIds() { QueryShortChannelIds_free(self); }
+       QueryShortChannelIds& operator=(QueryShortChannelIds&& o) { QueryShortChannelIds_free(self); self = o.self; memset(&o, 0, sizeof(QueryShortChannelIds)); return *this; }
        LDKQueryShortChannelIds* operator &() { return &self; }
        LDKQueryShortChannelIds* operator ->() { return &self; }
        const LDKQueryShortChannelIds* operator &() const { return &self; }
@@ -953,10 +1486,11 @@ private:
        LDKReplyShortChannelIdsEnd self;
 public:
        ReplyShortChannelIdsEnd(const ReplyShortChannelIdsEnd&) = delete;
-       ~ReplyShortChannelIdsEnd() { ReplyShortChannelIdsEnd_free(self); }
        ReplyShortChannelIdsEnd(ReplyShortChannelIdsEnd&& o) : self(o.self) { memset(&o, 0, sizeof(ReplyShortChannelIdsEnd)); }
        ReplyShortChannelIdsEnd(LDKReplyShortChannelIdsEnd&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKReplyShortChannelIdsEnd)); }
-       operator LDKReplyShortChannelIdsEnd() { LDKReplyShortChannelIdsEnd res = self; memset(&self, 0, sizeof(LDKReplyShortChannelIdsEnd)); return res; }
+       operator LDKReplyShortChannelIdsEnd() && { LDKReplyShortChannelIdsEnd res = self; memset(&self, 0, sizeof(LDKReplyShortChannelIdsEnd)); return res; }
+       ~ReplyShortChannelIdsEnd() { ReplyShortChannelIdsEnd_free(self); }
+       ReplyShortChannelIdsEnd& operator=(ReplyShortChannelIdsEnd&& o) { ReplyShortChannelIdsEnd_free(self); self = o.self; memset(&o, 0, sizeof(ReplyShortChannelIdsEnd)); return *this; }
        LDKReplyShortChannelIdsEnd* operator &() { return &self; }
        LDKReplyShortChannelIdsEnd* operator ->() { return &self; }
        const LDKReplyShortChannelIdsEnd* operator &() const { return &self; }
@@ -967,10 +1501,11 @@ private:
        LDKGossipTimestampFilter self;
 public:
        GossipTimestampFilter(const GossipTimestampFilter&) = delete;
-       ~GossipTimestampFilter() { GossipTimestampFilter_free(self); }
        GossipTimestampFilter(GossipTimestampFilter&& o) : self(o.self) { memset(&o, 0, sizeof(GossipTimestampFilter)); }
        GossipTimestampFilter(LDKGossipTimestampFilter&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKGossipTimestampFilter)); }
-       operator LDKGossipTimestampFilter() { LDKGossipTimestampFilter res = self; memset(&self, 0, sizeof(LDKGossipTimestampFilter)); return res; }
+       operator LDKGossipTimestampFilter() && { LDKGossipTimestampFilter res = self; memset(&self, 0, sizeof(LDKGossipTimestampFilter)); return res; }
+       ~GossipTimestampFilter() { GossipTimestampFilter_free(self); }
+       GossipTimestampFilter& operator=(GossipTimestampFilter&& o) { GossipTimestampFilter_free(self); self = o.self; memset(&o, 0, sizeof(GossipTimestampFilter)); return *this; }
        LDKGossipTimestampFilter* operator &() { return &self; }
        LDKGossipTimestampFilter* operator ->() { return &self; }
        const LDKGossipTimestampFilter* operator &() const { return &self; }
@@ -981,10 +1516,11 @@ private:
        LDKErrorAction self;
 public:
        ErrorAction(const ErrorAction&) = delete;
-       ~ErrorAction() { ErrorAction_free(self); }
        ErrorAction(ErrorAction&& o) : self(o.self) { memset(&o, 0, sizeof(ErrorAction)); }
        ErrorAction(LDKErrorAction&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKErrorAction)); }
-       operator LDKErrorAction() { LDKErrorAction res = self; memset(&self, 0, sizeof(LDKErrorAction)); return res; }
+       operator LDKErrorAction() && { LDKErrorAction res = self; memset(&self, 0, sizeof(LDKErrorAction)); return res; }
+       ~ErrorAction() { ErrorAction_free(self); }
+       ErrorAction& operator=(ErrorAction&& o) { ErrorAction_free(self); self = o.self; memset(&o, 0, sizeof(ErrorAction)); return *this; }
        LDKErrorAction* operator &() { return &self; }
        LDKErrorAction* operator ->() { return &self; }
        const LDKErrorAction* operator &() const { return &self; }
@@ -995,10 +1531,11 @@ private:
        LDKLightningError self;
 public:
        LightningError(const LightningError&) = delete;
-       ~LightningError() { LightningError_free(self); }
        LightningError(LightningError&& o) : self(o.self) { memset(&o, 0, sizeof(LightningError)); }
        LightningError(LDKLightningError&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKLightningError)); }
-       operator LDKLightningError() { LDKLightningError res = self; memset(&self, 0, sizeof(LDKLightningError)); return res; }
+       operator LDKLightningError() && { LDKLightningError res = self; memset(&self, 0, sizeof(LDKLightningError)); return res; }
+       ~LightningError() { LightningError_free(self); }
+       LightningError& operator=(LightningError&& o) { LightningError_free(self); self = o.self; memset(&o, 0, sizeof(LightningError)); return *this; }
        LDKLightningError* operator &() { return &self; }
        LDKLightningError* operator ->() { return &self; }
        const LDKLightningError* operator &() const { return &self; }
@@ -1009,10 +1546,11 @@ private:
        LDKCommitmentUpdate self;
 public:
        CommitmentUpdate(const CommitmentUpdate&) = delete;
-       ~CommitmentUpdate() { CommitmentUpdate_free(self); }
        CommitmentUpdate(CommitmentUpdate&& o) : self(o.self) { memset(&o, 0, sizeof(CommitmentUpdate)); }
        CommitmentUpdate(LDKCommitmentUpdate&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCommitmentUpdate)); }
-       operator LDKCommitmentUpdate() { LDKCommitmentUpdate res = self; memset(&self, 0, sizeof(LDKCommitmentUpdate)); return res; }
+       operator LDKCommitmentUpdate() && { LDKCommitmentUpdate res = self; memset(&self, 0, sizeof(LDKCommitmentUpdate)); return res; }
+       ~CommitmentUpdate() { CommitmentUpdate_free(self); }
+       CommitmentUpdate& operator=(CommitmentUpdate&& o) { CommitmentUpdate_free(self); self = o.self; memset(&o, 0, sizeof(CommitmentUpdate)); return *this; }
        LDKCommitmentUpdate* operator &() { return &self; }
        LDKCommitmentUpdate* operator ->() { return &self; }
        const LDKCommitmentUpdate* operator &() const { return &self; }
@@ -1023,10 +1561,11 @@ private:
        LDKHTLCFailChannelUpdate self;
 public:
        HTLCFailChannelUpdate(const HTLCFailChannelUpdate&) = delete;
-       ~HTLCFailChannelUpdate() { HTLCFailChannelUpdate_free(self); }
        HTLCFailChannelUpdate(HTLCFailChannelUpdate&& o) : self(o.self) { memset(&o, 0, sizeof(HTLCFailChannelUpdate)); }
        HTLCFailChannelUpdate(LDKHTLCFailChannelUpdate&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKHTLCFailChannelUpdate)); }
-       operator LDKHTLCFailChannelUpdate() { LDKHTLCFailChannelUpdate res = self; memset(&self, 0, sizeof(LDKHTLCFailChannelUpdate)); return res; }
+       operator LDKHTLCFailChannelUpdate() && { LDKHTLCFailChannelUpdate res = self; memset(&self, 0, sizeof(LDKHTLCFailChannelUpdate)); return res; }
+       ~HTLCFailChannelUpdate() { HTLCFailChannelUpdate_free(self); }
+       HTLCFailChannelUpdate& operator=(HTLCFailChannelUpdate&& o) { HTLCFailChannelUpdate_free(self); self = o.self; memset(&o, 0, sizeof(HTLCFailChannelUpdate)); return *this; }
        LDKHTLCFailChannelUpdate* operator &() { return &self; }
        LDKHTLCFailChannelUpdate* operator ->() { return &self; }
        const LDKHTLCFailChannelUpdate* operator &() const { return &self; }
@@ -1037,10 +1576,11 @@ private:
        LDKChannelMessageHandler self;
 public:
        ChannelMessageHandler(const ChannelMessageHandler&) = delete;
-       ~ChannelMessageHandler() { ChannelMessageHandler_free(self); }
        ChannelMessageHandler(ChannelMessageHandler&& o) : self(o.self) { memset(&o, 0, sizeof(ChannelMessageHandler)); }
        ChannelMessageHandler(LDKChannelMessageHandler&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKChannelMessageHandler)); }
-       operator LDKChannelMessageHandler() { LDKChannelMessageHandler res = self; memset(&self, 0, sizeof(LDKChannelMessageHandler)); return res; }
+       operator LDKChannelMessageHandler() && { LDKChannelMessageHandler res = self; memset(&self, 0, sizeof(LDKChannelMessageHandler)); return res; }
+       ~ChannelMessageHandler() { ChannelMessageHandler_free(self); }
+       ChannelMessageHandler& operator=(ChannelMessageHandler&& o) { ChannelMessageHandler_free(self); self = o.self; memset(&o, 0, sizeof(ChannelMessageHandler)); return *this; }
        LDKChannelMessageHandler* operator &() { return &self; }
        LDKChannelMessageHandler* operator ->() { return &self; }
        const LDKChannelMessageHandler* operator &() const { return &self; }
@@ -1051,794 +1591,1181 @@ private:
        LDKRoutingMessageHandler self;
 public:
        RoutingMessageHandler(const RoutingMessageHandler&) = delete;
-       ~RoutingMessageHandler() { RoutingMessageHandler_free(self); }
        RoutingMessageHandler(RoutingMessageHandler&& o) : self(o.self) { memset(&o, 0, sizeof(RoutingMessageHandler)); }
        RoutingMessageHandler(LDKRoutingMessageHandler&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKRoutingMessageHandler)); }
-       operator LDKRoutingMessageHandler() { LDKRoutingMessageHandler res = self; memset(&self, 0, sizeof(LDKRoutingMessageHandler)); return res; }
+       operator LDKRoutingMessageHandler() && { LDKRoutingMessageHandler res = self; memset(&self, 0, sizeof(LDKRoutingMessageHandler)); return res; }
+       ~RoutingMessageHandler() { RoutingMessageHandler_free(self); }
+       RoutingMessageHandler& operator=(RoutingMessageHandler&& o) { RoutingMessageHandler_free(self); self = o.self; memset(&o, 0, sizeof(RoutingMessageHandler)); return *this; }
        LDKRoutingMessageHandler* operator &() { return &self; }
        LDKRoutingMessageHandler* operator ->() { return &self; }
        const LDKRoutingMessageHandler* operator &() const { return &self; }
        const LDKRoutingMessageHandler* operator ->() const { return &self; }
 };
-class MessageHandler {
+class CVec_SpendableOutputDescriptorZ {
 private:
-       LDKMessageHandler self;
+       LDKCVec_SpendableOutputDescriptorZ self;
 public:
-       MessageHandler(const MessageHandler&) = delete;
-       ~MessageHandler() { MessageHandler_free(self); }
-       MessageHandler(MessageHandler&& o) : self(o.self) { memset(&o, 0, sizeof(MessageHandler)); }
-       MessageHandler(LDKMessageHandler&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKMessageHandler)); }
-       operator LDKMessageHandler() { LDKMessageHandler res = self; memset(&self, 0, sizeof(LDKMessageHandler)); return res; }
-       LDKMessageHandler* operator &() { return &self; }
-       LDKMessageHandler* operator ->() { return &self; }
-       const LDKMessageHandler* operator &() const { return &self; }
-       const LDKMessageHandler* operator ->() const { return &self; }
+       CVec_SpendableOutputDescriptorZ(const CVec_SpendableOutputDescriptorZ&) = delete;
+       CVec_SpendableOutputDescriptorZ(CVec_SpendableOutputDescriptorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_SpendableOutputDescriptorZ)); }
+       CVec_SpendableOutputDescriptorZ(LDKCVec_SpendableOutputDescriptorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_SpendableOutputDescriptorZ)); }
+       operator LDKCVec_SpendableOutputDescriptorZ() && { LDKCVec_SpendableOutputDescriptorZ res = self; memset(&self, 0, sizeof(LDKCVec_SpendableOutputDescriptorZ)); return res; }
+       ~CVec_SpendableOutputDescriptorZ() { CVec_SpendableOutputDescriptorZ_free(self); }
+       CVec_SpendableOutputDescriptorZ& operator=(CVec_SpendableOutputDescriptorZ&& o) { CVec_SpendableOutputDescriptorZ_free(self); self = o.self; memset(&o, 0, sizeof(CVec_SpendableOutputDescriptorZ)); return *this; }
+       LDKCVec_SpendableOutputDescriptorZ* operator &() { return &self; }
+       LDKCVec_SpendableOutputDescriptorZ* operator ->() { return &self; }
+       const LDKCVec_SpendableOutputDescriptorZ* operator &() const { return &self; }
+       const LDKCVec_SpendableOutputDescriptorZ* operator ->() const { return &self; }
 };
-class SocketDescriptor {
-private:
-       LDKSocketDescriptor self;
-public:
-       SocketDescriptor(const SocketDescriptor&) = delete;
-       ~SocketDescriptor() { SocketDescriptor_free(self); }
-       SocketDescriptor(SocketDescriptor&& o) : self(o.self) { memset(&o, 0, sizeof(SocketDescriptor)); }
-       SocketDescriptor(LDKSocketDescriptor&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKSocketDescriptor)); }
-       operator LDKSocketDescriptor() { LDKSocketDescriptor res = self; memset(&self, 0, sizeof(LDKSocketDescriptor)); return res; }
-       LDKSocketDescriptor* operator &() { return &self; }
-       LDKSocketDescriptor* operator ->() { return &self; }
-       const LDKSocketDescriptor* operator &() const { return &self; }
-       const LDKSocketDescriptor* operator ->() const { return &self; }
+class CResult_FundingCreatedDecodeErrorZ {
+private:
+       LDKCResult_FundingCreatedDecodeErrorZ self;
+public:
+       CResult_FundingCreatedDecodeErrorZ(const CResult_FundingCreatedDecodeErrorZ&) = delete;
+       CResult_FundingCreatedDecodeErrorZ(CResult_FundingCreatedDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_FundingCreatedDecodeErrorZ)); }
+       CResult_FundingCreatedDecodeErrorZ(LDKCResult_FundingCreatedDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_FundingCreatedDecodeErrorZ)); }
+       operator LDKCResult_FundingCreatedDecodeErrorZ() && { LDKCResult_FundingCreatedDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_FundingCreatedDecodeErrorZ)); return res; }
+       ~CResult_FundingCreatedDecodeErrorZ() { CResult_FundingCreatedDecodeErrorZ_free(self); }
+       CResult_FundingCreatedDecodeErrorZ& operator=(CResult_FundingCreatedDecodeErrorZ&& o) { CResult_FundingCreatedDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_FundingCreatedDecodeErrorZ)); return *this; }
+       LDKCResult_FundingCreatedDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_FundingCreatedDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_FundingCreatedDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_FundingCreatedDecodeErrorZ* operator ->() const { return &self; }
+};
+class CResult_ChannelAnnouncementDecodeErrorZ {
+private:
+       LDKCResult_ChannelAnnouncementDecodeErrorZ self;
+public:
+       CResult_ChannelAnnouncementDecodeErrorZ(const CResult_ChannelAnnouncementDecodeErrorZ&) = delete;
+       CResult_ChannelAnnouncementDecodeErrorZ(CResult_ChannelAnnouncementDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_ChannelAnnouncementDecodeErrorZ)); }
+       CResult_ChannelAnnouncementDecodeErrorZ(LDKCResult_ChannelAnnouncementDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_ChannelAnnouncementDecodeErrorZ)); }
+       operator LDKCResult_ChannelAnnouncementDecodeErrorZ() && { LDKCResult_ChannelAnnouncementDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_ChannelAnnouncementDecodeErrorZ)); return res; }
+       ~CResult_ChannelAnnouncementDecodeErrorZ() { CResult_ChannelAnnouncementDecodeErrorZ_free(self); }
+       CResult_ChannelAnnouncementDecodeErrorZ& operator=(CResult_ChannelAnnouncementDecodeErrorZ&& o) { CResult_ChannelAnnouncementDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_ChannelAnnouncementDecodeErrorZ)); return *this; }
+       LDKCResult_ChannelAnnouncementDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_ChannelAnnouncementDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_ChannelAnnouncementDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_ChannelAnnouncementDecodeErrorZ* operator ->() const { return &self; }
+};
+class CResult_HTLCUpdateDecodeErrorZ {
+private:
+       LDKCResult_HTLCUpdateDecodeErrorZ self;
+public:
+       CResult_HTLCUpdateDecodeErrorZ(const CResult_HTLCUpdateDecodeErrorZ&) = delete;
+       CResult_HTLCUpdateDecodeErrorZ(CResult_HTLCUpdateDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_HTLCUpdateDecodeErrorZ)); }
+       CResult_HTLCUpdateDecodeErrorZ(LDKCResult_HTLCUpdateDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_HTLCUpdateDecodeErrorZ)); }
+       operator LDKCResult_HTLCUpdateDecodeErrorZ() && { LDKCResult_HTLCUpdateDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_HTLCUpdateDecodeErrorZ)); return res; }
+       ~CResult_HTLCUpdateDecodeErrorZ() { CResult_HTLCUpdateDecodeErrorZ_free(self); }
+       CResult_HTLCUpdateDecodeErrorZ& operator=(CResult_HTLCUpdateDecodeErrorZ&& o) { CResult_HTLCUpdateDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_HTLCUpdateDecodeErrorZ)); return *this; }
+       LDKCResult_HTLCUpdateDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_HTLCUpdateDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_HTLCUpdateDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_HTLCUpdateDecodeErrorZ* operator ->() const { return &self; }
 };
-class PeerHandleError {
+class CVec_C2Tuple_u32TxOutZZ {
 private:
-       LDKPeerHandleError self;
+       LDKCVec_C2Tuple_u32TxOutZZ self;
 public:
-       PeerHandleError(const PeerHandleError&) = delete;
-       ~PeerHandleError() { PeerHandleError_free(self); }
-       PeerHandleError(PeerHandleError&& o) : self(o.self) { memset(&o, 0, sizeof(PeerHandleError)); }
-       PeerHandleError(LDKPeerHandleError&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKPeerHandleError)); }
-       operator LDKPeerHandleError() { LDKPeerHandleError res = self; memset(&self, 0, sizeof(LDKPeerHandleError)); return res; }
-       LDKPeerHandleError* operator &() { return &self; }
-       LDKPeerHandleError* operator ->() { return &self; }
-       const LDKPeerHandleError* operator &() const { return &self; }
-       const LDKPeerHandleError* operator ->() const { return &self; }
-};
-class PeerManager {
-private:
-       LDKPeerManager self;
-public:
-       PeerManager(const PeerManager&) = delete;
-       ~PeerManager() { PeerManager_free(self); }
-       PeerManager(PeerManager&& o) : self(o.self) { memset(&o, 0, sizeof(PeerManager)); }
-       PeerManager(LDKPeerManager&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKPeerManager)); }
-       operator LDKPeerManager() { LDKPeerManager res = self; memset(&self, 0, sizeof(LDKPeerManager)); return res; }
-       LDKPeerManager* operator &() { return &self; }
-       LDKPeerManager* operator ->() { return &self; }
-       const LDKPeerManager* operator &() const { return &self; }
-       const LDKPeerManager* operator ->() const { return &self; }
-};
-class TxCreationKeys {
-private:
-       LDKTxCreationKeys self;
-public:
-       TxCreationKeys(const TxCreationKeys&) = delete;
-       ~TxCreationKeys() { TxCreationKeys_free(self); }
-       TxCreationKeys(TxCreationKeys&& o) : self(o.self) { memset(&o, 0, sizeof(TxCreationKeys)); }
-       TxCreationKeys(LDKTxCreationKeys&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKTxCreationKeys)); }
-       operator LDKTxCreationKeys() { LDKTxCreationKeys res = self; memset(&self, 0, sizeof(LDKTxCreationKeys)); return res; }
-       LDKTxCreationKeys* operator &() { return &self; }
-       LDKTxCreationKeys* operator ->() { return &self; }
-       const LDKTxCreationKeys* operator &() const { return &self; }
-       const LDKTxCreationKeys* operator ->() const { return &self; }
+       CVec_C2Tuple_u32TxOutZZ(const CVec_C2Tuple_u32TxOutZZ&) = delete;
+       CVec_C2Tuple_u32TxOutZZ(CVec_C2Tuple_u32TxOutZZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_C2Tuple_u32TxOutZZ)); }
+       CVec_C2Tuple_u32TxOutZZ(LDKCVec_C2Tuple_u32TxOutZZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_C2Tuple_u32TxOutZZ)); }
+       operator LDKCVec_C2Tuple_u32TxOutZZ() && { LDKCVec_C2Tuple_u32TxOutZZ res = self; memset(&self, 0, sizeof(LDKCVec_C2Tuple_u32TxOutZZ)); return res; }
+       ~CVec_C2Tuple_u32TxOutZZ() { CVec_C2Tuple_u32TxOutZZ_free(self); }
+       CVec_C2Tuple_u32TxOutZZ& operator=(CVec_C2Tuple_u32TxOutZZ&& o) { CVec_C2Tuple_u32TxOutZZ_free(self); self = o.self; memset(&o, 0, sizeof(CVec_C2Tuple_u32TxOutZZ)); return *this; }
+       LDKCVec_C2Tuple_u32TxOutZZ* operator &() { return &self; }
+       LDKCVec_C2Tuple_u32TxOutZZ* operator ->() { return &self; }
+       const LDKCVec_C2Tuple_u32TxOutZZ* operator &() const { return &self; }
+       const LDKCVec_C2Tuple_u32TxOutZZ* operator ->() const { return &self; }
 };
-class PreCalculatedTxCreationKeys {
+class C2Tuple_SignatureCVec_SignatureZZ {
 private:
-       LDKPreCalculatedTxCreationKeys self;
+       LDKC2Tuple_SignatureCVec_SignatureZZ self;
 public:
-       PreCalculatedTxCreationKeys(const PreCalculatedTxCreationKeys&) = delete;
-       ~PreCalculatedTxCreationKeys() { PreCalculatedTxCreationKeys_free(self); }
-       PreCalculatedTxCreationKeys(PreCalculatedTxCreationKeys&& o) : self(o.self) { memset(&o, 0, sizeof(PreCalculatedTxCreationKeys)); }
-       PreCalculatedTxCreationKeys(LDKPreCalculatedTxCreationKeys&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKPreCalculatedTxCreationKeys)); }
-       operator LDKPreCalculatedTxCreationKeys() { LDKPreCalculatedTxCreationKeys res = self; memset(&self, 0, sizeof(LDKPreCalculatedTxCreationKeys)); return res; }
-       LDKPreCalculatedTxCreationKeys* operator &() { return &self; }
-       LDKPreCalculatedTxCreationKeys* operator ->() { return &self; }
-       const LDKPreCalculatedTxCreationKeys* operator &() const { return &self; }
-       const LDKPreCalculatedTxCreationKeys* operator ->() const { return &self; }
+       C2Tuple_SignatureCVec_SignatureZZ(const C2Tuple_SignatureCVec_SignatureZZ&) = delete;
+       C2Tuple_SignatureCVec_SignatureZZ(C2Tuple_SignatureCVec_SignatureZZ&& o) : self(o.self) { memset(&o, 0, sizeof(C2Tuple_SignatureCVec_SignatureZZ)); }
+       C2Tuple_SignatureCVec_SignatureZZ(LDKC2Tuple_SignatureCVec_SignatureZZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKC2Tuple_SignatureCVec_SignatureZZ)); }
+       operator LDKC2Tuple_SignatureCVec_SignatureZZ() && { LDKC2Tuple_SignatureCVec_SignatureZZ res = self; memset(&self, 0, sizeof(LDKC2Tuple_SignatureCVec_SignatureZZ)); return res; }
+       ~C2Tuple_SignatureCVec_SignatureZZ() { C2Tuple_SignatureCVec_SignatureZZ_free(self); }
+       C2Tuple_SignatureCVec_SignatureZZ& operator=(C2Tuple_SignatureCVec_SignatureZZ&& o) { C2Tuple_SignatureCVec_SignatureZZ_free(self); self = o.self; memset(&o, 0, sizeof(C2Tuple_SignatureCVec_SignatureZZ)); return *this; }
+       LDKC2Tuple_SignatureCVec_SignatureZZ* operator &() { return &self; }
+       LDKC2Tuple_SignatureCVec_SignatureZZ* operator ->() { return &self; }
+       const LDKC2Tuple_SignatureCVec_SignatureZZ* operator &() const { return &self; }
+       const LDKC2Tuple_SignatureCVec_SignatureZZ* operator ->() const { return &self; }
 };
-class ChannelPublicKeys {
+class CResult_ChannelInfoDecodeErrorZ {
 private:
-       LDKChannelPublicKeys self;
+       LDKCResult_ChannelInfoDecodeErrorZ self;
 public:
-       ChannelPublicKeys(const ChannelPublicKeys&) = delete;
-       ~ChannelPublicKeys() { ChannelPublicKeys_free(self); }
-       ChannelPublicKeys(ChannelPublicKeys&& o) : self(o.self) { memset(&o, 0, sizeof(ChannelPublicKeys)); }
-       ChannelPublicKeys(LDKChannelPublicKeys&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKChannelPublicKeys)); }
-       operator LDKChannelPublicKeys() { LDKChannelPublicKeys res = self; memset(&self, 0, sizeof(LDKChannelPublicKeys)); return res; }
-       LDKChannelPublicKeys* operator &() { return &self; }
-       LDKChannelPublicKeys* operator ->() { return &self; }
-       const LDKChannelPublicKeys* operator &() const { return &self; }
-       const LDKChannelPublicKeys* operator ->() const { return &self; }
+       CResult_ChannelInfoDecodeErrorZ(const CResult_ChannelInfoDecodeErrorZ&) = delete;
+       CResult_ChannelInfoDecodeErrorZ(CResult_ChannelInfoDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_ChannelInfoDecodeErrorZ)); }
+       CResult_ChannelInfoDecodeErrorZ(LDKCResult_ChannelInfoDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_ChannelInfoDecodeErrorZ)); }
+       operator LDKCResult_ChannelInfoDecodeErrorZ() && { LDKCResult_ChannelInfoDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_ChannelInfoDecodeErrorZ)); return res; }
+       ~CResult_ChannelInfoDecodeErrorZ() { CResult_ChannelInfoDecodeErrorZ_free(self); }
+       CResult_ChannelInfoDecodeErrorZ& operator=(CResult_ChannelInfoDecodeErrorZ&& o) { CResult_ChannelInfoDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_ChannelInfoDecodeErrorZ)); return *this; }
+       LDKCResult_ChannelInfoDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_ChannelInfoDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_ChannelInfoDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_ChannelInfoDecodeErrorZ* operator ->() const { return &self; }
 };
-class HTLCOutputInCommitment {
+class CResult_CVec_u8ZPeerHandleErrorZ {
 private:
-       LDKHTLCOutputInCommitment self;
+       LDKCResult_CVec_u8ZPeerHandleErrorZ self;
 public:
-       HTLCOutputInCommitment(const HTLCOutputInCommitment&) = delete;
-       ~HTLCOutputInCommitment() { HTLCOutputInCommitment_free(self); }
-       HTLCOutputInCommitment(HTLCOutputInCommitment&& o) : self(o.self) { memset(&o, 0, sizeof(HTLCOutputInCommitment)); }
-       HTLCOutputInCommitment(LDKHTLCOutputInCommitment&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKHTLCOutputInCommitment)); }
-       operator LDKHTLCOutputInCommitment() { LDKHTLCOutputInCommitment res = self; memset(&self, 0, sizeof(LDKHTLCOutputInCommitment)); return res; }
-       LDKHTLCOutputInCommitment* operator &() { return &self; }
-       LDKHTLCOutputInCommitment* operator ->() { return &self; }
-       const LDKHTLCOutputInCommitment* operator &() const { return &self; }
-       const LDKHTLCOutputInCommitment* operator ->() const { return &self; }
+       CResult_CVec_u8ZPeerHandleErrorZ(const CResult_CVec_u8ZPeerHandleErrorZ&) = delete;
+       CResult_CVec_u8ZPeerHandleErrorZ(CResult_CVec_u8ZPeerHandleErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_CVec_u8ZPeerHandleErrorZ)); }
+       CResult_CVec_u8ZPeerHandleErrorZ(LDKCResult_CVec_u8ZPeerHandleErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_CVec_u8ZPeerHandleErrorZ)); }
+       operator LDKCResult_CVec_u8ZPeerHandleErrorZ() && { LDKCResult_CVec_u8ZPeerHandleErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_CVec_u8ZPeerHandleErrorZ)); return res; }
+       ~CResult_CVec_u8ZPeerHandleErrorZ() { CResult_CVec_u8ZPeerHandleErrorZ_free(self); }
+       CResult_CVec_u8ZPeerHandleErrorZ& operator=(CResult_CVec_u8ZPeerHandleErrorZ&& o) { CResult_CVec_u8ZPeerHandleErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_CVec_u8ZPeerHandleErrorZ)); return *this; }
+       LDKCResult_CVec_u8ZPeerHandleErrorZ* operator &() { return &self; }
+       LDKCResult_CVec_u8ZPeerHandleErrorZ* operator ->() { return &self; }
+       const LDKCResult_CVec_u8ZPeerHandleErrorZ* operator &() const { return &self; }
+       const LDKCResult_CVec_u8ZPeerHandleErrorZ* operator ->() const { return &self; }
 };
-class HolderCommitmentTransaction {
-private:
-       LDKHolderCommitmentTransaction self;
-public:
-       HolderCommitmentTransaction(const HolderCommitmentTransaction&) = delete;
-       ~HolderCommitmentTransaction() { HolderCommitmentTransaction_free(self); }
-       HolderCommitmentTransaction(HolderCommitmentTransaction&& o) : self(o.self) { memset(&o, 0, sizeof(HolderCommitmentTransaction)); }
-       HolderCommitmentTransaction(LDKHolderCommitmentTransaction&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKHolderCommitmentTransaction)); }
-       operator LDKHolderCommitmentTransaction() { LDKHolderCommitmentTransaction res = self; memset(&self, 0, sizeof(LDKHolderCommitmentTransaction)); return res; }
-       LDKHolderCommitmentTransaction* operator &() { return &self; }
-       LDKHolderCommitmentTransaction* operator ->() { return &self; }
-       const LDKHolderCommitmentTransaction* operator &() const { return &self; }
-       const LDKHolderCommitmentTransaction* operator ->() const { return &self; }
+class CResult_ChannelMonitorUpdateDecodeErrorZ {
+private:
+       LDKCResult_ChannelMonitorUpdateDecodeErrorZ self;
+public:
+       CResult_ChannelMonitorUpdateDecodeErrorZ(const CResult_ChannelMonitorUpdateDecodeErrorZ&) = delete;
+       CResult_ChannelMonitorUpdateDecodeErrorZ(CResult_ChannelMonitorUpdateDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_ChannelMonitorUpdateDecodeErrorZ)); }
+       CResult_ChannelMonitorUpdateDecodeErrorZ(LDKCResult_ChannelMonitorUpdateDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_ChannelMonitorUpdateDecodeErrorZ)); }
+       operator LDKCResult_ChannelMonitorUpdateDecodeErrorZ() && { LDKCResult_ChannelMonitorUpdateDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_ChannelMonitorUpdateDecodeErrorZ)); return res; }
+       ~CResult_ChannelMonitorUpdateDecodeErrorZ() { CResult_ChannelMonitorUpdateDecodeErrorZ_free(self); }
+       CResult_ChannelMonitorUpdateDecodeErrorZ& operator=(CResult_ChannelMonitorUpdateDecodeErrorZ&& o) { CResult_ChannelMonitorUpdateDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_ChannelMonitorUpdateDecodeErrorZ)); return *this; }
+       LDKCResult_ChannelMonitorUpdateDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_ChannelMonitorUpdateDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_ChannelMonitorUpdateDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_ChannelMonitorUpdateDecodeErrorZ* operator ->() const { return &self; }
+};
+class CResult_ReplyChannelRangeDecodeErrorZ {
+private:
+       LDKCResult_ReplyChannelRangeDecodeErrorZ self;
+public:
+       CResult_ReplyChannelRangeDecodeErrorZ(const CResult_ReplyChannelRangeDecodeErrorZ&) = delete;
+       CResult_ReplyChannelRangeDecodeErrorZ(CResult_ReplyChannelRangeDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_ReplyChannelRangeDecodeErrorZ)); }
+       CResult_ReplyChannelRangeDecodeErrorZ(LDKCResult_ReplyChannelRangeDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_ReplyChannelRangeDecodeErrorZ)); }
+       operator LDKCResult_ReplyChannelRangeDecodeErrorZ() && { LDKCResult_ReplyChannelRangeDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_ReplyChannelRangeDecodeErrorZ)); return res; }
+       ~CResult_ReplyChannelRangeDecodeErrorZ() { CResult_ReplyChannelRangeDecodeErrorZ_free(self); }
+       CResult_ReplyChannelRangeDecodeErrorZ& operator=(CResult_ReplyChannelRangeDecodeErrorZ&& o) { CResult_ReplyChannelRangeDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_ReplyChannelRangeDecodeErrorZ)); return *this; }
+       LDKCResult_ReplyChannelRangeDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_ReplyChannelRangeDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_ReplyChannelRangeDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_ReplyChannelRangeDecodeErrorZ* operator ->() const { return &self; }
+};
+class CResult_GossipTimestampFilterDecodeErrorZ {
+private:
+       LDKCResult_GossipTimestampFilterDecodeErrorZ self;
+public:
+       CResult_GossipTimestampFilterDecodeErrorZ(const CResult_GossipTimestampFilterDecodeErrorZ&) = delete;
+       CResult_GossipTimestampFilterDecodeErrorZ(CResult_GossipTimestampFilterDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_GossipTimestampFilterDecodeErrorZ)); }
+       CResult_GossipTimestampFilterDecodeErrorZ(LDKCResult_GossipTimestampFilterDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_GossipTimestampFilterDecodeErrorZ)); }
+       operator LDKCResult_GossipTimestampFilterDecodeErrorZ() && { LDKCResult_GossipTimestampFilterDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_GossipTimestampFilterDecodeErrorZ)); return res; }
+       ~CResult_GossipTimestampFilterDecodeErrorZ() { CResult_GossipTimestampFilterDecodeErrorZ_free(self); }
+       CResult_GossipTimestampFilterDecodeErrorZ& operator=(CResult_GossipTimestampFilterDecodeErrorZ&& o) { CResult_GossipTimestampFilterDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_GossipTimestampFilterDecodeErrorZ)); return *this; }
+       LDKCResult_GossipTimestampFilterDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_GossipTimestampFilterDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_GossipTimestampFilterDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_GossipTimestampFilterDecodeErrorZ* operator ->() const { return &self; }
 };
-class InitFeatures {
+class CResult_TxOutAccessErrorZ {
 private:
-       LDKInitFeatures self;
+       LDKCResult_TxOutAccessErrorZ self;
 public:
-       InitFeatures(const InitFeatures&) = delete;
-       ~InitFeatures() { InitFeatures_free(self); }
-       InitFeatures(InitFeatures&& o) : self(o.self) { memset(&o, 0, sizeof(InitFeatures)); }
-       InitFeatures(LDKInitFeatures&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKInitFeatures)); }
-       operator LDKInitFeatures() { LDKInitFeatures res = self; memset(&self, 0, sizeof(LDKInitFeatures)); return res; }
-       LDKInitFeatures* operator &() { return &self; }
-       LDKInitFeatures* operator ->() { return &self; }
-       const LDKInitFeatures* operator &() const { return &self; }
-       const LDKInitFeatures* operator ->() const { return &self; }
+       CResult_TxOutAccessErrorZ(const CResult_TxOutAccessErrorZ&) = delete;
+       CResult_TxOutAccessErrorZ(CResult_TxOutAccessErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_TxOutAccessErrorZ)); }
+       CResult_TxOutAccessErrorZ(LDKCResult_TxOutAccessErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_TxOutAccessErrorZ)); }
+       operator LDKCResult_TxOutAccessErrorZ() && { LDKCResult_TxOutAccessErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_TxOutAccessErrorZ)); return res; }
+       ~CResult_TxOutAccessErrorZ() { CResult_TxOutAccessErrorZ_free(self); }
+       CResult_TxOutAccessErrorZ& operator=(CResult_TxOutAccessErrorZ&& o) { CResult_TxOutAccessErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_TxOutAccessErrorZ)); return *this; }
+       LDKCResult_TxOutAccessErrorZ* operator &() { return &self; }
+       LDKCResult_TxOutAccessErrorZ* operator ->() { return &self; }
+       const LDKCResult_TxOutAccessErrorZ* operator &() const { return &self; }
+       const LDKCResult_TxOutAccessErrorZ* operator ->() const { return &self; }
 };
-class NodeFeatures {
-private:
-       LDKNodeFeatures self;
-public:
-       NodeFeatures(const NodeFeatures&) = delete;
-       ~NodeFeatures() { NodeFeatures_free(self); }
-       NodeFeatures(NodeFeatures&& o) : self(o.self) { memset(&o, 0, sizeof(NodeFeatures)); }
-       NodeFeatures(LDKNodeFeatures&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKNodeFeatures)); }
-       operator LDKNodeFeatures() { LDKNodeFeatures res = self; memset(&self, 0, sizeof(LDKNodeFeatures)); return res; }
-       LDKNodeFeatures* operator &() { return &self; }
-       LDKNodeFeatures* operator ->() { return &self; }
-       const LDKNodeFeatures* operator &() const { return &self; }
-       const LDKNodeFeatures* operator ->() const { return &self; }
+class CResult_UnsignedNodeAnnouncementDecodeErrorZ {
+private:
+       LDKCResult_UnsignedNodeAnnouncementDecodeErrorZ self;
+public:
+       CResult_UnsignedNodeAnnouncementDecodeErrorZ(const CResult_UnsignedNodeAnnouncementDecodeErrorZ&) = delete;
+       CResult_UnsignedNodeAnnouncementDecodeErrorZ(CResult_UnsignedNodeAnnouncementDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_UnsignedNodeAnnouncementDecodeErrorZ)); }
+       CResult_UnsignedNodeAnnouncementDecodeErrorZ(LDKCResult_UnsignedNodeAnnouncementDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_UnsignedNodeAnnouncementDecodeErrorZ)); }
+       operator LDKCResult_UnsignedNodeAnnouncementDecodeErrorZ() && { LDKCResult_UnsignedNodeAnnouncementDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_UnsignedNodeAnnouncementDecodeErrorZ)); return res; }
+       ~CResult_UnsignedNodeAnnouncementDecodeErrorZ() { CResult_UnsignedNodeAnnouncementDecodeErrorZ_free(self); }
+       CResult_UnsignedNodeAnnouncementDecodeErrorZ& operator=(CResult_UnsignedNodeAnnouncementDecodeErrorZ&& o) { CResult_UnsignedNodeAnnouncementDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_UnsignedNodeAnnouncementDecodeErrorZ)); return *this; }
+       LDKCResult_UnsignedNodeAnnouncementDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_UnsignedNodeAnnouncementDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_UnsignedNodeAnnouncementDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_UnsignedNodeAnnouncementDecodeErrorZ* operator ->() const { return &self; }
+};
+class CResult_ChannelReestablishDecodeErrorZ {
+private:
+       LDKCResult_ChannelReestablishDecodeErrorZ self;
+public:
+       CResult_ChannelReestablishDecodeErrorZ(const CResult_ChannelReestablishDecodeErrorZ&) = delete;
+       CResult_ChannelReestablishDecodeErrorZ(CResult_ChannelReestablishDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_ChannelReestablishDecodeErrorZ)); }
+       CResult_ChannelReestablishDecodeErrorZ(LDKCResult_ChannelReestablishDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_ChannelReestablishDecodeErrorZ)); }
+       operator LDKCResult_ChannelReestablishDecodeErrorZ() && { LDKCResult_ChannelReestablishDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_ChannelReestablishDecodeErrorZ)); return res; }
+       ~CResult_ChannelReestablishDecodeErrorZ() { CResult_ChannelReestablishDecodeErrorZ_free(self); }
+       CResult_ChannelReestablishDecodeErrorZ& operator=(CResult_ChannelReestablishDecodeErrorZ&& o) { CResult_ChannelReestablishDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_ChannelReestablishDecodeErrorZ)); return *this; }
+       LDKCResult_ChannelReestablishDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_ChannelReestablishDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_ChannelReestablishDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_ChannelReestablishDecodeErrorZ* operator ->() const { return &self; }
+};
+class CResult_CommitmentSignedDecodeErrorZ {
+private:
+       LDKCResult_CommitmentSignedDecodeErrorZ self;
+public:
+       CResult_CommitmentSignedDecodeErrorZ(const CResult_CommitmentSignedDecodeErrorZ&) = delete;
+       CResult_CommitmentSignedDecodeErrorZ(CResult_CommitmentSignedDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_CommitmentSignedDecodeErrorZ)); }
+       CResult_CommitmentSignedDecodeErrorZ(LDKCResult_CommitmentSignedDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_CommitmentSignedDecodeErrorZ)); }
+       operator LDKCResult_CommitmentSignedDecodeErrorZ() && { LDKCResult_CommitmentSignedDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_CommitmentSignedDecodeErrorZ)); return res; }
+       ~CResult_CommitmentSignedDecodeErrorZ() { CResult_CommitmentSignedDecodeErrorZ_free(self); }
+       CResult_CommitmentSignedDecodeErrorZ& operator=(CResult_CommitmentSignedDecodeErrorZ&& o) { CResult_CommitmentSignedDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_CommitmentSignedDecodeErrorZ)); return *this; }
+       LDKCResult_CommitmentSignedDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_CommitmentSignedDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_CommitmentSignedDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_CommitmentSignedDecodeErrorZ* operator ->() const { return &self; }
 };
-class ChannelFeatures {
+class CVec_UpdateAddHTLCZ {
 private:
-       LDKChannelFeatures self;
+       LDKCVec_UpdateAddHTLCZ self;
 public:
-       ChannelFeatures(const ChannelFeatures&) = delete;
-       ~ChannelFeatures() { ChannelFeatures_free(self); }
-       ChannelFeatures(ChannelFeatures&& o) : self(o.self) { memset(&o, 0, sizeof(ChannelFeatures)); }
-       ChannelFeatures(LDKChannelFeatures&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKChannelFeatures)); }
-       operator LDKChannelFeatures() { LDKChannelFeatures res = self; memset(&self, 0, sizeof(LDKChannelFeatures)); return res; }
-       LDKChannelFeatures* operator &() { return &self; }
-       LDKChannelFeatures* operator ->() { return &self; }
-       const LDKChannelFeatures* operator &() const { return &self; }
-       const LDKChannelFeatures* operator ->() const { return &self; }
+       CVec_UpdateAddHTLCZ(const CVec_UpdateAddHTLCZ&) = delete;
+       CVec_UpdateAddHTLCZ(CVec_UpdateAddHTLCZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_UpdateAddHTLCZ)); }
+       CVec_UpdateAddHTLCZ(LDKCVec_UpdateAddHTLCZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_UpdateAddHTLCZ)); }
+       operator LDKCVec_UpdateAddHTLCZ() && { LDKCVec_UpdateAddHTLCZ res = self; memset(&self, 0, sizeof(LDKCVec_UpdateAddHTLCZ)); return res; }
+       ~CVec_UpdateAddHTLCZ() { CVec_UpdateAddHTLCZ_free(self); }
+       CVec_UpdateAddHTLCZ& operator=(CVec_UpdateAddHTLCZ&& o) { CVec_UpdateAddHTLCZ_free(self); self = o.self; memset(&o, 0, sizeof(CVec_UpdateAddHTLCZ)); return *this; }
+       LDKCVec_UpdateAddHTLCZ* operator &() { return &self; }
+       LDKCVec_UpdateAddHTLCZ* operator ->() { return &self; }
+       const LDKCVec_UpdateAddHTLCZ* operator &() const { return &self; }
+       const LDKCVec_UpdateAddHTLCZ* operator ->() const { return &self; }
 };
-class RouteHop {
-private:
-       LDKRouteHop self;
-public:
-       RouteHop(const RouteHop&) = delete;
-       ~RouteHop() { RouteHop_free(self); }
-       RouteHop(RouteHop&& o) : self(o.self) { memset(&o, 0, sizeof(RouteHop)); }
-       RouteHop(LDKRouteHop&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKRouteHop)); }
-       operator LDKRouteHop() { LDKRouteHop res = self; memset(&self, 0, sizeof(LDKRouteHop)); return res; }
-       LDKRouteHop* operator &() { return &self; }
-       LDKRouteHop* operator ->() { return &self; }
-       const LDKRouteHop* operator &() const { return &self; }
-       const LDKRouteHop* operator ->() const { return &self; }
+class CResult_InitFeaturesDecodeErrorZ {
+private:
+       LDKCResult_InitFeaturesDecodeErrorZ self;
+public:
+       CResult_InitFeaturesDecodeErrorZ(const CResult_InitFeaturesDecodeErrorZ&) = delete;
+       CResult_InitFeaturesDecodeErrorZ(CResult_InitFeaturesDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_InitFeaturesDecodeErrorZ)); }
+       CResult_InitFeaturesDecodeErrorZ(LDKCResult_InitFeaturesDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_InitFeaturesDecodeErrorZ)); }
+       operator LDKCResult_InitFeaturesDecodeErrorZ() && { LDKCResult_InitFeaturesDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_InitFeaturesDecodeErrorZ)); return res; }
+       ~CResult_InitFeaturesDecodeErrorZ() { CResult_InitFeaturesDecodeErrorZ_free(self); }
+       CResult_InitFeaturesDecodeErrorZ& operator=(CResult_InitFeaturesDecodeErrorZ&& o) { CResult_InitFeaturesDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_InitFeaturesDecodeErrorZ)); return *this; }
+       LDKCResult_InitFeaturesDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_InitFeaturesDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_InitFeaturesDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_InitFeaturesDecodeErrorZ* operator ->() const { return &self; }
+};
+class CResult_CommitmentTransactionDecodeErrorZ {
+private:
+       LDKCResult_CommitmentTransactionDecodeErrorZ self;
+public:
+       CResult_CommitmentTransactionDecodeErrorZ(const CResult_CommitmentTransactionDecodeErrorZ&) = delete;
+       CResult_CommitmentTransactionDecodeErrorZ(CResult_CommitmentTransactionDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_CommitmentTransactionDecodeErrorZ)); }
+       CResult_CommitmentTransactionDecodeErrorZ(LDKCResult_CommitmentTransactionDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_CommitmentTransactionDecodeErrorZ)); }
+       operator LDKCResult_CommitmentTransactionDecodeErrorZ() && { LDKCResult_CommitmentTransactionDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_CommitmentTransactionDecodeErrorZ)); return res; }
+       ~CResult_CommitmentTransactionDecodeErrorZ() { CResult_CommitmentTransactionDecodeErrorZ_free(self); }
+       CResult_CommitmentTransactionDecodeErrorZ& operator=(CResult_CommitmentTransactionDecodeErrorZ&& o) { CResult_CommitmentTransactionDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_CommitmentTransactionDecodeErrorZ)); return *this; }
+       LDKCResult_CommitmentTransactionDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_CommitmentTransactionDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_CommitmentTransactionDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_CommitmentTransactionDecodeErrorZ* operator ->() const { return &self; }
+};
+class CResult_TransactionNoneZ {
+private:
+       LDKCResult_TransactionNoneZ self;
+public:
+       CResult_TransactionNoneZ(const CResult_TransactionNoneZ&) = delete;
+       CResult_TransactionNoneZ(CResult_TransactionNoneZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_TransactionNoneZ)); }
+       CResult_TransactionNoneZ(LDKCResult_TransactionNoneZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_TransactionNoneZ)); }
+       operator LDKCResult_TransactionNoneZ() && { LDKCResult_TransactionNoneZ res = self; memset(&self, 0, sizeof(LDKCResult_TransactionNoneZ)); return res; }
+       ~CResult_TransactionNoneZ() { CResult_TransactionNoneZ_free(self); }
+       CResult_TransactionNoneZ& operator=(CResult_TransactionNoneZ&& o) { CResult_TransactionNoneZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_TransactionNoneZ)); return *this; }
+       LDKCResult_TransactionNoneZ* operator &() { return &self; }
+       LDKCResult_TransactionNoneZ* operator ->() { return &self; }
+       const LDKCResult_TransactionNoneZ* operator &() const { return &self; }
+       const LDKCResult_TransactionNoneZ* operator ->() const { return &self; }
+};
+class CResult_PingDecodeErrorZ {
+private:
+       LDKCResult_PingDecodeErrorZ self;
+public:
+       CResult_PingDecodeErrorZ(const CResult_PingDecodeErrorZ&) = delete;
+       CResult_PingDecodeErrorZ(CResult_PingDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_PingDecodeErrorZ)); }
+       CResult_PingDecodeErrorZ(LDKCResult_PingDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_PingDecodeErrorZ)); }
+       operator LDKCResult_PingDecodeErrorZ() && { LDKCResult_PingDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_PingDecodeErrorZ)); return res; }
+       ~CResult_PingDecodeErrorZ() { CResult_PingDecodeErrorZ_free(self); }
+       CResult_PingDecodeErrorZ& operator=(CResult_PingDecodeErrorZ&& o) { CResult_PingDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_PingDecodeErrorZ)); return *this; }
+       LDKCResult_PingDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_PingDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_PingDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_PingDecodeErrorZ* operator ->() const { return &self; }
+};
+class CResult_ErrorMessageDecodeErrorZ {
+private:
+       LDKCResult_ErrorMessageDecodeErrorZ self;
+public:
+       CResult_ErrorMessageDecodeErrorZ(const CResult_ErrorMessageDecodeErrorZ&) = delete;
+       CResult_ErrorMessageDecodeErrorZ(CResult_ErrorMessageDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_ErrorMessageDecodeErrorZ)); }
+       CResult_ErrorMessageDecodeErrorZ(LDKCResult_ErrorMessageDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_ErrorMessageDecodeErrorZ)); }
+       operator LDKCResult_ErrorMessageDecodeErrorZ() && { LDKCResult_ErrorMessageDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_ErrorMessageDecodeErrorZ)); return res; }
+       ~CResult_ErrorMessageDecodeErrorZ() { CResult_ErrorMessageDecodeErrorZ_free(self); }
+       CResult_ErrorMessageDecodeErrorZ& operator=(CResult_ErrorMessageDecodeErrorZ&& o) { CResult_ErrorMessageDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_ErrorMessageDecodeErrorZ)); return *this; }
+       LDKCResult_ErrorMessageDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_ErrorMessageDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_ErrorMessageDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_ErrorMessageDecodeErrorZ* operator ->() const { return &self; }
+};
+class CResult_OpenChannelDecodeErrorZ {
+private:
+       LDKCResult_OpenChannelDecodeErrorZ self;
+public:
+       CResult_OpenChannelDecodeErrorZ(const CResult_OpenChannelDecodeErrorZ&) = delete;
+       CResult_OpenChannelDecodeErrorZ(CResult_OpenChannelDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_OpenChannelDecodeErrorZ)); }
+       CResult_OpenChannelDecodeErrorZ(LDKCResult_OpenChannelDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_OpenChannelDecodeErrorZ)); }
+       operator LDKCResult_OpenChannelDecodeErrorZ() && { LDKCResult_OpenChannelDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_OpenChannelDecodeErrorZ)); return res; }
+       ~CResult_OpenChannelDecodeErrorZ() { CResult_OpenChannelDecodeErrorZ_free(self); }
+       CResult_OpenChannelDecodeErrorZ& operator=(CResult_OpenChannelDecodeErrorZ&& o) { CResult_OpenChannelDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_OpenChannelDecodeErrorZ)); return *this; }
+       LDKCResult_OpenChannelDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_OpenChannelDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_OpenChannelDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_OpenChannelDecodeErrorZ* operator ->() const { return &self; }
+};
+class CVec_CVec_u8ZZ {
+private:
+       LDKCVec_CVec_u8ZZ self;
+public:
+       CVec_CVec_u8ZZ(const CVec_CVec_u8ZZ&) = delete;
+       CVec_CVec_u8ZZ(CVec_CVec_u8ZZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_CVec_u8ZZ)); }
+       CVec_CVec_u8ZZ(LDKCVec_CVec_u8ZZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_CVec_u8ZZ)); }
+       operator LDKCVec_CVec_u8ZZ() && { LDKCVec_CVec_u8ZZ res = self; memset(&self, 0, sizeof(LDKCVec_CVec_u8ZZ)); return res; }
+       ~CVec_CVec_u8ZZ() { CVec_CVec_u8ZZ_free(self); }
+       CVec_CVec_u8ZZ& operator=(CVec_CVec_u8ZZ&& o) { CVec_CVec_u8ZZ_free(self); self = o.self; memset(&o, 0, sizeof(CVec_CVec_u8ZZ)); return *this; }
+       LDKCVec_CVec_u8ZZ* operator &() { return &self; }
+       LDKCVec_CVec_u8ZZ* operator ->() { return &self; }
+       const LDKCVec_CVec_u8ZZ* operator &() const { return &self; }
+       const LDKCVec_CVec_u8ZZ* operator ->() const { return &self; }
+};
+class CResult_SecretKeyErrorZ {
+private:
+       LDKCResult_SecretKeyErrorZ self;
+public:
+       CResult_SecretKeyErrorZ(const CResult_SecretKeyErrorZ&) = delete;
+       CResult_SecretKeyErrorZ(CResult_SecretKeyErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_SecretKeyErrorZ)); }
+       CResult_SecretKeyErrorZ(LDKCResult_SecretKeyErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_SecretKeyErrorZ)); }
+       operator LDKCResult_SecretKeyErrorZ() && { LDKCResult_SecretKeyErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_SecretKeyErrorZ)); return res; }
+       ~CResult_SecretKeyErrorZ() { CResult_SecretKeyErrorZ_free(self); }
+       CResult_SecretKeyErrorZ& operator=(CResult_SecretKeyErrorZ&& o) { CResult_SecretKeyErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_SecretKeyErrorZ)); return *this; }
+       LDKCResult_SecretKeyErrorZ* operator &() { return &self; }
+       LDKCResult_SecretKeyErrorZ* operator ->() { return &self; }
+       const LDKCResult_SecretKeyErrorZ* operator &() const { return &self; }
+       const LDKCResult_SecretKeyErrorZ* operator ->() const { return &self; }
+};
+class CResult_QueryChannelRangeDecodeErrorZ {
+private:
+       LDKCResult_QueryChannelRangeDecodeErrorZ self;
+public:
+       CResult_QueryChannelRangeDecodeErrorZ(const CResult_QueryChannelRangeDecodeErrorZ&) = delete;
+       CResult_QueryChannelRangeDecodeErrorZ(CResult_QueryChannelRangeDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_QueryChannelRangeDecodeErrorZ)); }
+       CResult_QueryChannelRangeDecodeErrorZ(LDKCResult_QueryChannelRangeDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_QueryChannelRangeDecodeErrorZ)); }
+       operator LDKCResult_QueryChannelRangeDecodeErrorZ() && { LDKCResult_QueryChannelRangeDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_QueryChannelRangeDecodeErrorZ)); return res; }
+       ~CResult_QueryChannelRangeDecodeErrorZ() { CResult_QueryChannelRangeDecodeErrorZ_free(self); }
+       CResult_QueryChannelRangeDecodeErrorZ& operator=(CResult_QueryChannelRangeDecodeErrorZ&& o) { CResult_QueryChannelRangeDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_QueryChannelRangeDecodeErrorZ)); return *this; }
+       LDKCResult_QueryChannelRangeDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_QueryChannelRangeDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_QueryChannelRangeDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_QueryChannelRangeDecodeErrorZ* operator ->() const { return &self; }
 };
-class Route {
+class CVec_TransactionZ {
 private:
-       LDKRoute self;
+       LDKCVec_TransactionZ self;
 public:
-       Route(const Route&) = delete;
-       ~Route() { Route_free(self); }
-       Route(Route&& o) : self(o.self) { memset(&o, 0, sizeof(Route)); }
-       Route(LDKRoute&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKRoute)); }
-       operator LDKRoute() { LDKRoute res = self; memset(&self, 0, sizeof(LDKRoute)); return res; }
-       LDKRoute* operator &() { return &self; }
-       LDKRoute* operator ->() { return &self; }
-       const LDKRoute* operator &() const { return &self; }
-       const LDKRoute* operator ->() const { return &self; }
+       CVec_TransactionZ(const CVec_TransactionZ&) = delete;
+       CVec_TransactionZ(CVec_TransactionZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_TransactionZ)); }
+       CVec_TransactionZ(LDKCVec_TransactionZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_TransactionZ)); }
+       operator LDKCVec_TransactionZ() && { LDKCVec_TransactionZ res = self; memset(&self, 0, sizeof(LDKCVec_TransactionZ)); return res; }
+       ~CVec_TransactionZ() { CVec_TransactionZ_free(self); }
+       CVec_TransactionZ& operator=(CVec_TransactionZ&& o) { CVec_TransactionZ_free(self); self = o.self; memset(&o, 0, sizeof(CVec_TransactionZ)); return *this; }
+       LDKCVec_TransactionZ* operator &() { return &self; }
+       LDKCVec_TransactionZ* operator ->() { return &self; }
+       const LDKCVec_TransactionZ* operator &() const { return &self; }
+       const LDKCVec_TransactionZ* operator ->() const { return &self; }
 };
-class RouteHint {
+class CResult_TxCreationKeysDecodeErrorZ {
 private:
-       LDKRouteHint self;
+       LDKCResult_TxCreationKeysDecodeErrorZ self;
 public:
-       RouteHint(const RouteHint&) = delete;
-       ~RouteHint() { RouteHint_free(self); }
-       RouteHint(RouteHint&& o) : self(o.self) { memset(&o, 0, sizeof(RouteHint)); }
-       RouteHint(LDKRouteHint&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKRouteHint)); }
-       operator LDKRouteHint() { LDKRouteHint res = self; memset(&self, 0, sizeof(LDKRouteHint)); return res; }
-       LDKRouteHint* operator &() { return &self; }
-       LDKRouteHint* operator ->() { return &self; }
-       const LDKRouteHint* operator &() const { return &self; }
-       const LDKRouteHint* operator ->() const { return &self; }
+       CResult_TxCreationKeysDecodeErrorZ(const CResult_TxCreationKeysDecodeErrorZ&) = delete;
+       CResult_TxCreationKeysDecodeErrorZ(CResult_TxCreationKeysDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_TxCreationKeysDecodeErrorZ)); }
+       CResult_TxCreationKeysDecodeErrorZ(LDKCResult_TxCreationKeysDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_TxCreationKeysDecodeErrorZ)); }
+       operator LDKCResult_TxCreationKeysDecodeErrorZ() && { LDKCResult_TxCreationKeysDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_TxCreationKeysDecodeErrorZ)); return res; }
+       ~CResult_TxCreationKeysDecodeErrorZ() { CResult_TxCreationKeysDecodeErrorZ_free(self); }
+       CResult_TxCreationKeysDecodeErrorZ& operator=(CResult_TxCreationKeysDecodeErrorZ&& o) { CResult_TxCreationKeysDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_TxCreationKeysDecodeErrorZ)); return *this; }
+       LDKCResult_TxCreationKeysDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_TxCreationKeysDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_TxCreationKeysDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_TxCreationKeysDecodeErrorZ* operator ->() const { return &self; }
 };
-class NetworkGraph {
+class CResult_ChannelFeaturesDecodeErrorZ {
 private:
-       LDKNetworkGraph self;
+       LDKCResult_ChannelFeaturesDecodeErrorZ self;
 public:
-       NetworkGraph(const NetworkGraph&) = delete;
-       ~NetworkGraph() { NetworkGraph_free(self); }
-       NetworkGraph(NetworkGraph&& o) : self(o.self) { memset(&o, 0, sizeof(NetworkGraph)); }
-       NetworkGraph(LDKNetworkGraph&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKNetworkGraph)); }
-       operator LDKNetworkGraph() { LDKNetworkGraph res = self; memset(&self, 0, sizeof(LDKNetworkGraph)); return res; }
-       LDKNetworkGraph* operator &() { return &self; }
-       LDKNetworkGraph* operator ->() { return &self; }
-       const LDKNetworkGraph* operator &() const { return &self; }
-       const LDKNetworkGraph* operator ->() const { return &self; }
+       CResult_ChannelFeaturesDecodeErrorZ(const CResult_ChannelFeaturesDecodeErrorZ&) = delete;
+       CResult_ChannelFeaturesDecodeErrorZ(CResult_ChannelFeaturesDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_ChannelFeaturesDecodeErrorZ)); }
+       CResult_ChannelFeaturesDecodeErrorZ(LDKCResult_ChannelFeaturesDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_ChannelFeaturesDecodeErrorZ)); }
+       operator LDKCResult_ChannelFeaturesDecodeErrorZ() && { LDKCResult_ChannelFeaturesDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_ChannelFeaturesDecodeErrorZ)); return res; }
+       ~CResult_ChannelFeaturesDecodeErrorZ() { CResult_ChannelFeaturesDecodeErrorZ_free(self); }
+       CResult_ChannelFeaturesDecodeErrorZ& operator=(CResult_ChannelFeaturesDecodeErrorZ&& o) { CResult_ChannelFeaturesDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_ChannelFeaturesDecodeErrorZ)); return *this; }
+       LDKCResult_ChannelFeaturesDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_ChannelFeaturesDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_ChannelFeaturesDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_ChannelFeaturesDecodeErrorZ* operator ->() const { return &self; }
 };
-class LockedNetworkGraph {
+class C2Tuple_usizeTransactionZ {
 private:
-       LDKLockedNetworkGraph self;
+       LDKC2Tuple_usizeTransactionZ self;
 public:
-       LockedNetworkGraph(const LockedNetworkGraph&) = delete;
-       ~LockedNetworkGraph() { LockedNetworkGraph_free(self); }
-       LockedNetworkGraph(LockedNetworkGraph&& o) : self(o.self) { memset(&o, 0, sizeof(LockedNetworkGraph)); }
-       LockedNetworkGraph(LDKLockedNetworkGraph&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKLockedNetworkGraph)); }
-       operator LDKLockedNetworkGraph() { LDKLockedNetworkGraph res = self; memset(&self, 0, sizeof(LDKLockedNetworkGraph)); return res; }
-       LDKLockedNetworkGraph* operator &() { return &self; }
-       LDKLockedNetworkGraph* operator ->() { return &self; }
-       const LDKLockedNetworkGraph* operator &() const { return &self; }
-       const LDKLockedNetworkGraph* operator ->() const { return &self; }
+       C2Tuple_usizeTransactionZ(const C2Tuple_usizeTransactionZ&) = delete;
+       C2Tuple_usizeTransactionZ(C2Tuple_usizeTransactionZ&& o) : self(o.self) { memset(&o, 0, sizeof(C2Tuple_usizeTransactionZ)); }
+       C2Tuple_usizeTransactionZ(LDKC2Tuple_usizeTransactionZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKC2Tuple_usizeTransactionZ)); }
+       operator LDKC2Tuple_usizeTransactionZ() && { LDKC2Tuple_usizeTransactionZ res = self; memset(&self, 0, sizeof(LDKC2Tuple_usizeTransactionZ)); return res; }
+       ~C2Tuple_usizeTransactionZ() { C2Tuple_usizeTransactionZ_free(self); }
+       C2Tuple_usizeTransactionZ& operator=(C2Tuple_usizeTransactionZ&& o) { C2Tuple_usizeTransactionZ_free(self); self = o.self; memset(&o, 0, sizeof(C2Tuple_usizeTransactionZ)); return *this; }
+       LDKC2Tuple_usizeTransactionZ* operator &() { return &self; }
+       LDKC2Tuple_usizeTransactionZ* operator ->() { return &self; }
+       const LDKC2Tuple_usizeTransactionZ* operator &() const { return &self; }
+       const LDKC2Tuple_usizeTransactionZ* operator ->() const { return &self; }
 };
-class NetGraphMsgHandler {
+class CVec_ChannelMonitorZ {
 private:
-       LDKNetGraphMsgHandler self;
+       LDKCVec_ChannelMonitorZ self;
 public:
-       NetGraphMsgHandler(const NetGraphMsgHandler&) = delete;
-       ~NetGraphMsgHandler() { NetGraphMsgHandler_free(self); }
-       NetGraphMsgHandler(NetGraphMsgHandler&& o) : self(o.self) { memset(&o, 0, sizeof(NetGraphMsgHandler)); }
-       NetGraphMsgHandler(LDKNetGraphMsgHandler&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKNetGraphMsgHandler)); }
-       operator LDKNetGraphMsgHandler() { LDKNetGraphMsgHandler res = self; memset(&self, 0, sizeof(LDKNetGraphMsgHandler)); return res; }
-       LDKNetGraphMsgHandler* operator &() { return &self; }
-       LDKNetGraphMsgHandler* operator ->() { return &self; }
-       const LDKNetGraphMsgHandler* operator &() const { return &self; }
-       const LDKNetGraphMsgHandler* operator ->() const { return &self; }
+       CVec_ChannelMonitorZ(const CVec_ChannelMonitorZ&) = delete;
+       CVec_ChannelMonitorZ(CVec_ChannelMonitorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_ChannelMonitorZ)); }
+       CVec_ChannelMonitorZ(LDKCVec_ChannelMonitorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_ChannelMonitorZ)); }
+       operator LDKCVec_ChannelMonitorZ() && { LDKCVec_ChannelMonitorZ res = self; memset(&self, 0, sizeof(LDKCVec_ChannelMonitorZ)); return res; }
+       ~CVec_ChannelMonitorZ() { CVec_ChannelMonitorZ_free(self); }
+       CVec_ChannelMonitorZ& operator=(CVec_ChannelMonitorZ&& o) { CVec_ChannelMonitorZ_free(self); self = o.self; memset(&o, 0, sizeof(CVec_ChannelMonitorZ)); return *this; }
+       LDKCVec_ChannelMonitorZ* operator &() { return &self; }
+       LDKCVec_ChannelMonitorZ* operator ->() { return &self; }
+       const LDKCVec_ChannelMonitorZ* operator &() const { return &self; }
+       const LDKCVec_ChannelMonitorZ* operator ->() const { return &self; }
 };
-class DirectionalChannelInfo {
-private:
-       LDKDirectionalChannelInfo self;
-public:
-       DirectionalChannelInfo(const DirectionalChannelInfo&) = delete;
-       ~DirectionalChannelInfo() { DirectionalChannelInfo_free(self); }
-       DirectionalChannelInfo(DirectionalChannelInfo&& o) : self(o.self) { memset(&o, 0, sizeof(DirectionalChannelInfo)); }
-       DirectionalChannelInfo(LDKDirectionalChannelInfo&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKDirectionalChannelInfo)); }
-       operator LDKDirectionalChannelInfo() { LDKDirectionalChannelInfo res = self; memset(&self, 0, sizeof(LDKDirectionalChannelInfo)); return res; }
-       LDKDirectionalChannelInfo* operator &() { return &self; }
-       LDKDirectionalChannelInfo* operator ->() { return &self; }
-       const LDKDirectionalChannelInfo* operator &() const { return &self; }
-       const LDKDirectionalChannelInfo* operator ->() const { return &self; }
+class CResult_UpdateFeeDecodeErrorZ {
+private:
+       LDKCResult_UpdateFeeDecodeErrorZ self;
+public:
+       CResult_UpdateFeeDecodeErrorZ(const CResult_UpdateFeeDecodeErrorZ&) = delete;
+       CResult_UpdateFeeDecodeErrorZ(CResult_UpdateFeeDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_UpdateFeeDecodeErrorZ)); }
+       CResult_UpdateFeeDecodeErrorZ(LDKCResult_UpdateFeeDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_UpdateFeeDecodeErrorZ)); }
+       operator LDKCResult_UpdateFeeDecodeErrorZ() && { LDKCResult_UpdateFeeDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_UpdateFeeDecodeErrorZ)); return res; }
+       ~CResult_UpdateFeeDecodeErrorZ() { CResult_UpdateFeeDecodeErrorZ_free(self); }
+       CResult_UpdateFeeDecodeErrorZ& operator=(CResult_UpdateFeeDecodeErrorZ&& o) { CResult_UpdateFeeDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_UpdateFeeDecodeErrorZ)); return *this; }
+       LDKCResult_UpdateFeeDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_UpdateFeeDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_UpdateFeeDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_UpdateFeeDecodeErrorZ* operator ->() const { return &self; }
+};
+class CResult_NodeAnnouncementDecodeErrorZ {
+private:
+       LDKCResult_NodeAnnouncementDecodeErrorZ self;
+public:
+       CResult_NodeAnnouncementDecodeErrorZ(const CResult_NodeAnnouncementDecodeErrorZ&) = delete;
+       CResult_NodeAnnouncementDecodeErrorZ(CResult_NodeAnnouncementDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_NodeAnnouncementDecodeErrorZ)); }
+       CResult_NodeAnnouncementDecodeErrorZ(LDKCResult_NodeAnnouncementDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_NodeAnnouncementDecodeErrorZ)); }
+       operator LDKCResult_NodeAnnouncementDecodeErrorZ() && { LDKCResult_NodeAnnouncementDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_NodeAnnouncementDecodeErrorZ)); return res; }
+       ~CResult_NodeAnnouncementDecodeErrorZ() { CResult_NodeAnnouncementDecodeErrorZ_free(self); }
+       CResult_NodeAnnouncementDecodeErrorZ& operator=(CResult_NodeAnnouncementDecodeErrorZ&& o) { CResult_NodeAnnouncementDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_NodeAnnouncementDecodeErrorZ)); return *this; }
+       LDKCResult_NodeAnnouncementDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_NodeAnnouncementDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_NodeAnnouncementDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_NodeAnnouncementDecodeErrorZ* operator ->() const { return &self; }
+};
+class CResult_HTLCOutputInCommitmentDecodeErrorZ {
+private:
+       LDKCResult_HTLCOutputInCommitmentDecodeErrorZ self;
+public:
+       CResult_HTLCOutputInCommitmentDecodeErrorZ(const CResult_HTLCOutputInCommitmentDecodeErrorZ&) = delete;
+       CResult_HTLCOutputInCommitmentDecodeErrorZ(CResult_HTLCOutputInCommitmentDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_HTLCOutputInCommitmentDecodeErrorZ)); }
+       CResult_HTLCOutputInCommitmentDecodeErrorZ(LDKCResult_HTLCOutputInCommitmentDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_HTLCOutputInCommitmentDecodeErrorZ)); }
+       operator LDKCResult_HTLCOutputInCommitmentDecodeErrorZ() && { LDKCResult_HTLCOutputInCommitmentDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_HTLCOutputInCommitmentDecodeErrorZ)); return res; }
+       ~CResult_HTLCOutputInCommitmentDecodeErrorZ() { CResult_HTLCOutputInCommitmentDecodeErrorZ_free(self); }
+       CResult_HTLCOutputInCommitmentDecodeErrorZ& operator=(CResult_HTLCOutputInCommitmentDecodeErrorZ&& o) { CResult_HTLCOutputInCommitmentDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_HTLCOutputInCommitmentDecodeErrorZ)); return *this; }
+       LDKCResult_HTLCOutputInCommitmentDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_HTLCOutputInCommitmentDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_HTLCOutputInCommitmentDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_HTLCOutputInCommitmentDecodeErrorZ* operator ->() const { return &self; }
 };
-class ChannelInfo {
+class CResult_boolLightningErrorZ {
 private:
-       LDKChannelInfo self;
+       LDKCResult_boolLightningErrorZ self;
 public:
-       ChannelInfo(const ChannelInfo&) = delete;
-       ~ChannelInfo() { ChannelInfo_free(self); }
-       ChannelInfo(ChannelInfo&& o) : self(o.self) { memset(&o, 0, sizeof(ChannelInfo)); }
-       ChannelInfo(LDKChannelInfo&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKChannelInfo)); }
-       operator LDKChannelInfo() { LDKChannelInfo res = self; memset(&self, 0, sizeof(LDKChannelInfo)); return res; }
-       LDKChannelInfo* operator &() { return &self; }
-       LDKChannelInfo* operator ->() { return &self; }
-       const LDKChannelInfo* operator &() const { return &self; }
-       const LDKChannelInfo* operator ->() const { return &self; }
+       CResult_boolLightningErrorZ(const CResult_boolLightningErrorZ&) = delete;
+       CResult_boolLightningErrorZ(CResult_boolLightningErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_boolLightningErrorZ)); }
+       CResult_boolLightningErrorZ(LDKCResult_boolLightningErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_boolLightningErrorZ)); }
+       operator LDKCResult_boolLightningErrorZ() && { LDKCResult_boolLightningErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_boolLightningErrorZ)); return res; }
+       ~CResult_boolLightningErrorZ() { CResult_boolLightningErrorZ_free(self); }
+       CResult_boolLightningErrorZ& operator=(CResult_boolLightningErrorZ&& o) { CResult_boolLightningErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_boolLightningErrorZ)); return *this; }
+       LDKCResult_boolLightningErrorZ* operator &() { return &self; }
+       LDKCResult_boolLightningErrorZ* operator ->() { return &self; }
+       const LDKCResult_boolLightningErrorZ* operator &() const { return &self; }
+       const LDKCResult_boolLightningErrorZ* operator ->() const { return &self; }
 };
-class RoutingFees {
-private:
-       LDKRoutingFees self;
-public:
-       RoutingFees(const RoutingFees&) = delete;
-       ~RoutingFees() { RoutingFees_free(self); }
-       RoutingFees(RoutingFees&& o) : self(o.self) { memset(&o, 0, sizeof(RoutingFees)); }
-       RoutingFees(LDKRoutingFees&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKRoutingFees)); }
-       operator LDKRoutingFees() { LDKRoutingFees res = self; memset(&self, 0, sizeof(LDKRoutingFees)); return res; }
-       LDKRoutingFees* operator &() { return &self; }
-       LDKRoutingFees* operator ->() { return &self; }
-       const LDKRoutingFees* operator &() const { return &self; }
-       const LDKRoutingFees* operator ->() const { return &self; }
+class CResult_TxCreationKeysErrorZ {
+private:
+       LDKCResult_TxCreationKeysErrorZ self;
+public:
+       CResult_TxCreationKeysErrorZ(const CResult_TxCreationKeysErrorZ&) = delete;
+       CResult_TxCreationKeysErrorZ(CResult_TxCreationKeysErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_TxCreationKeysErrorZ)); }
+       CResult_TxCreationKeysErrorZ(LDKCResult_TxCreationKeysErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_TxCreationKeysErrorZ)); }
+       operator LDKCResult_TxCreationKeysErrorZ() && { LDKCResult_TxCreationKeysErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_TxCreationKeysErrorZ)); return res; }
+       ~CResult_TxCreationKeysErrorZ() { CResult_TxCreationKeysErrorZ_free(self); }
+       CResult_TxCreationKeysErrorZ& operator=(CResult_TxCreationKeysErrorZ&& o) { CResult_TxCreationKeysErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_TxCreationKeysErrorZ)); return *this; }
+       LDKCResult_TxCreationKeysErrorZ* operator &() { return &self; }
+       LDKCResult_TxCreationKeysErrorZ* operator ->() { return &self; }
+       const LDKCResult_TxCreationKeysErrorZ* operator &() const { return &self; }
+       const LDKCResult_TxCreationKeysErrorZ* operator ->() const { return &self; }
+};
+class C2Tuple_BlockHashChannelMonitorZ {
+private:
+       LDKC2Tuple_BlockHashChannelMonitorZ self;
+public:
+       C2Tuple_BlockHashChannelMonitorZ(const C2Tuple_BlockHashChannelMonitorZ&) = delete;
+       C2Tuple_BlockHashChannelMonitorZ(C2Tuple_BlockHashChannelMonitorZ&& o) : self(o.self) { memset(&o, 0, sizeof(C2Tuple_BlockHashChannelMonitorZ)); }
+       C2Tuple_BlockHashChannelMonitorZ(LDKC2Tuple_BlockHashChannelMonitorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKC2Tuple_BlockHashChannelMonitorZ)); }
+       operator LDKC2Tuple_BlockHashChannelMonitorZ() && { LDKC2Tuple_BlockHashChannelMonitorZ res = self; memset(&self, 0, sizeof(LDKC2Tuple_BlockHashChannelMonitorZ)); return res; }
+       ~C2Tuple_BlockHashChannelMonitorZ() { C2Tuple_BlockHashChannelMonitorZ_free(self); }
+       C2Tuple_BlockHashChannelMonitorZ& operator=(C2Tuple_BlockHashChannelMonitorZ&& o) { C2Tuple_BlockHashChannelMonitorZ_free(self); self = o.self; memset(&o, 0, sizeof(C2Tuple_BlockHashChannelMonitorZ)); return *this; }
+       LDKC2Tuple_BlockHashChannelMonitorZ* operator &() { return &self; }
+       LDKC2Tuple_BlockHashChannelMonitorZ* operator ->() { return &self; }
+       const LDKC2Tuple_BlockHashChannelMonitorZ* operator &() const { return &self; }
+       const LDKC2Tuple_BlockHashChannelMonitorZ* operator ->() const { return &self; }
+};
+class CResult_FundingSignedDecodeErrorZ {
+private:
+       LDKCResult_FundingSignedDecodeErrorZ self;
+public:
+       CResult_FundingSignedDecodeErrorZ(const CResult_FundingSignedDecodeErrorZ&) = delete;
+       CResult_FundingSignedDecodeErrorZ(CResult_FundingSignedDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_FundingSignedDecodeErrorZ)); }
+       CResult_FundingSignedDecodeErrorZ(LDKCResult_FundingSignedDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_FundingSignedDecodeErrorZ)); }
+       operator LDKCResult_FundingSignedDecodeErrorZ() && { LDKCResult_FundingSignedDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_FundingSignedDecodeErrorZ)); return res; }
+       ~CResult_FundingSignedDecodeErrorZ() { CResult_FundingSignedDecodeErrorZ_free(self); }
+       CResult_FundingSignedDecodeErrorZ& operator=(CResult_FundingSignedDecodeErrorZ&& o) { CResult_FundingSignedDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_FundingSignedDecodeErrorZ)); return *this; }
+       LDKCResult_FundingSignedDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_FundingSignedDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_FundingSignedDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_FundingSignedDecodeErrorZ* operator ->() const { return &self; }
+};
+class CResult_NodeAnnouncementInfoDecodeErrorZ {
+private:
+       LDKCResult_NodeAnnouncementInfoDecodeErrorZ self;
+public:
+       CResult_NodeAnnouncementInfoDecodeErrorZ(const CResult_NodeAnnouncementInfoDecodeErrorZ&) = delete;
+       CResult_NodeAnnouncementInfoDecodeErrorZ(CResult_NodeAnnouncementInfoDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_NodeAnnouncementInfoDecodeErrorZ)); }
+       CResult_NodeAnnouncementInfoDecodeErrorZ(LDKCResult_NodeAnnouncementInfoDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_NodeAnnouncementInfoDecodeErrorZ)); }
+       operator LDKCResult_NodeAnnouncementInfoDecodeErrorZ() && { LDKCResult_NodeAnnouncementInfoDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_NodeAnnouncementInfoDecodeErrorZ)); return res; }
+       ~CResult_NodeAnnouncementInfoDecodeErrorZ() { CResult_NodeAnnouncementInfoDecodeErrorZ_free(self); }
+       CResult_NodeAnnouncementInfoDecodeErrorZ& operator=(CResult_NodeAnnouncementInfoDecodeErrorZ&& o) { CResult_NodeAnnouncementInfoDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_NodeAnnouncementInfoDecodeErrorZ)); return *this; }
+       LDKCResult_NodeAnnouncementInfoDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_NodeAnnouncementInfoDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_NodeAnnouncementInfoDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_NodeAnnouncementInfoDecodeErrorZ* operator ->() const { return &self; }
+};
+class CResult_NetAddressu8Z {
+private:
+       LDKCResult_NetAddressu8Z self;
+public:
+       CResult_NetAddressu8Z(const CResult_NetAddressu8Z&) = delete;
+       CResult_NetAddressu8Z(CResult_NetAddressu8Z&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_NetAddressu8Z)); }
+       CResult_NetAddressu8Z(LDKCResult_NetAddressu8Z&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_NetAddressu8Z)); }
+       operator LDKCResult_NetAddressu8Z() && { LDKCResult_NetAddressu8Z res = self; memset(&self, 0, sizeof(LDKCResult_NetAddressu8Z)); return res; }
+       ~CResult_NetAddressu8Z() { CResult_NetAddressu8Z_free(self); }
+       CResult_NetAddressu8Z& operator=(CResult_NetAddressu8Z&& o) { CResult_NetAddressu8Z_free(self); self = o.self; memset(&o, 0, sizeof(CResult_NetAddressu8Z)); return *this; }
+       LDKCResult_NetAddressu8Z* operator &() { return &self; }
+       LDKCResult_NetAddressu8Z* operator ->() { return &self; }
+       const LDKCResult_NetAddressu8Z* operator &() const { return &self; }
+       const LDKCResult_NetAddressu8Z* operator ->() const { return &self; }
 };
-class NodeAnnouncementInfo {
+class CVec_UpdateFailMalformedHTLCZ {
 private:
-       LDKNodeAnnouncementInfo self;
+       LDKCVec_UpdateFailMalformedHTLCZ self;
 public:
-       NodeAnnouncementInfo(const NodeAnnouncementInfo&) = delete;
-       ~NodeAnnouncementInfo() { NodeAnnouncementInfo_free(self); }
-       NodeAnnouncementInfo(NodeAnnouncementInfo&& o) : self(o.self) { memset(&o, 0, sizeof(NodeAnnouncementInfo)); }
-       NodeAnnouncementInfo(LDKNodeAnnouncementInfo&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKNodeAnnouncementInfo)); }
-       operator LDKNodeAnnouncementInfo() { LDKNodeAnnouncementInfo res = self; memset(&self, 0, sizeof(LDKNodeAnnouncementInfo)); return res; }
-       LDKNodeAnnouncementInfo* operator &() { return &self; }
-       LDKNodeAnnouncementInfo* operator ->() { return &self; }
-       const LDKNodeAnnouncementInfo* operator &() const { return &self; }
-       const LDKNodeAnnouncementInfo* operator ->() const { return &self; }
+       CVec_UpdateFailMalformedHTLCZ(const CVec_UpdateFailMalformedHTLCZ&) = delete;
+       CVec_UpdateFailMalformedHTLCZ(CVec_UpdateFailMalformedHTLCZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_UpdateFailMalformedHTLCZ)); }
+       CVec_UpdateFailMalformedHTLCZ(LDKCVec_UpdateFailMalformedHTLCZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_UpdateFailMalformedHTLCZ)); }
+       operator LDKCVec_UpdateFailMalformedHTLCZ() && { LDKCVec_UpdateFailMalformedHTLCZ res = self; memset(&self, 0, sizeof(LDKCVec_UpdateFailMalformedHTLCZ)); return res; }
+       ~CVec_UpdateFailMalformedHTLCZ() { CVec_UpdateFailMalformedHTLCZ_free(self); }
+       CVec_UpdateFailMalformedHTLCZ& operator=(CVec_UpdateFailMalformedHTLCZ&& o) { CVec_UpdateFailMalformedHTLCZ_free(self); self = o.self; memset(&o, 0, sizeof(CVec_UpdateFailMalformedHTLCZ)); return *this; }
+       LDKCVec_UpdateFailMalformedHTLCZ* operator &() { return &self; }
+       LDKCVec_UpdateFailMalformedHTLCZ* operator ->() { return &self; }
+       const LDKCVec_UpdateFailMalformedHTLCZ* operator &() const { return &self; }
+       const LDKCVec_UpdateFailMalformedHTLCZ* operator ->() const { return &self; }
 };
-class NodeInfo {
+class CResult_NetworkGraphDecodeErrorZ {
 private:
-       LDKNodeInfo self;
+       LDKCResult_NetworkGraphDecodeErrorZ self;
 public:
-       NodeInfo(const NodeInfo&) = delete;
-       ~NodeInfo() { NodeInfo_free(self); }
-       NodeInfo(NodeInfo&& o) : self(o.self) { memset(&o, 0, sizeof(NodeInfo)); }
-       NodeInfo(LDKNodeInfo&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKNodeInfo)); }
-       operator LDKNodeInfo() { LDKNodeInfo res = self; memset(&self, 0, sizeof(LDKNodeInfo)); return res; }
-       LDKNodeInfo* operator &() { return &self; }
-       LDKNodeInfo* operator ->() { return &self; }
-       const LDKNodeInfo* operator &() const { return &self; }
-       const LDKNodeInfo* operator ->() const { return &self; }
+       CResult_NetworkGraphDecodeErrorZ(const CResult_NetworkGraphDecodeErrorZ&) = delete;
+       CResult_NetworkGraphDecodeErrorZ(CResult_NetworkGraphDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_NetworkGraphDecodeErrorZ)); }
+       CResult_NetworkGraphDecodeErrorZ(LDKCResult_NetworkGraphDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_NetworkGraphDecodeErrorZ)); }
+       operator LDKCResult_NetworkGraphDecodeErrorZ() && { LDKCResult_NetworkGraphDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_NetworkGraphDecodeErrorZ)); return res; }
+       ~CResult_NetworkGraphDecodeErrorZ() { CResult_NetworkGraphDecodeErrorZ_free(self); }
+       CResult_NetworkGraphDecodeErrorZ& operator=(CResult_NetworkGraphDecodeErrorZ&& o) { CResult_NetworkGraphDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_NetworkGraphDecodeErrorZ)); return *this; }
+       LDKCResult_NetworkGraphDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_NetworkGraphDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_NetworkGraphDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_NetworkGraphDecodeErrorZ* operator ->() const { return &self; }
 };
-class CVec_SpendableOutputDescriptorZ {
+class CVec_RouteHopZ {
 private:
-       LDKCVec_SpendableOutputDescriptorZ self;
+       LDKCVec_RouteHopZ self;
 public:
-       CVec_SpendableOutputDescriptorZ(const CVec_SpendableOutputDescriptorZ&) = delete;
-       ~CVec_SpendableOutputDescriptorZ() { CVec_SpendableOutputDescriptorZ_free(self); }
-       CVec_SpendableOutputDescriptorZ(CVec_SpendableOutputDescriptorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_SpendableOutputDescriptorZ)); }
-       CVec_SpendableOutputDescriptorZ(LDKCVec_SpendableOutputDescriptorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_SpendableOutputDescriptorZ)); }
-       operator LDKCVec_SpendableOutputDescriptorZ() { LDKCVec_SpendableOutputDescriptorZ res = self; memset(&self, 0, sizeof(LDKCVec_SpendableOutputDescriptorZ)); return res; }
-       LDKCVec_SpendableOutputDescriptorZ* operator &() { return &self; }
-       LDKCVec_SpendableOutputDescriptorZ* operator ->() { return &self; }
-       const LDKCVec_SpendableOutputDescriptorZ* operator &() const { return &self; }
-       const LDKCVec_SpendableOutputDescriptorZ* operator ->() const { return &self; }
+       CVec_RouteHopZ(const CVec_RouteHopZ&) = delete;
+       CVec_RouteHopZ(CVec_RouteHopZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_RouteHopZ)); }
+       CVec_RouteHopZ(LDKCVec_RouteHopZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_RouteHopZ)); }
+       operator LDKCVec_RouteHopZ() && { LDKCVec_RouteHopZ res = self; memset(&self, 0, sizeof(LDKCVec_RouteHopZ)); return res; }
+       ~CVec_RouteHopZ() { CVec_RouteHopZ_free(self); }
+       CVec_RouteHopZ& operator=(CVec_RouteHopZ&& o) { CVec_RouteHopZ_free(self); self = o.self; memset(&o, 0, sizeof(CVec_RouteHopZ)); return *this; }
+       LDKCVec_RouteHopZ* operator &() { return &self; }
+       LDKCVec_RouteHopZ* operator ->() { return &self; }
+       const LDKCVec_RouteHopZ* operator &() const { return &self; }
+       const LDKCVec_RouteHopZ* operator ->() const { return &self; }
 };
-class CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ {
+class CResult_NodeInfoDecodeErrorZ {
 private:
-       LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ self;
+       LDKCResult_NodeInfoDecodeErrorZ self;
 public:
-       CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ(const CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ&) = delete;
-       ~CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ() { CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ_free(self); }
-       CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ(CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ)); }
-       CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ(LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ)); }
-       operator LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ() { LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ res = self; memset(&self, 0, sizeof(LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ)); return res; }
-       LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ* operator &() { return &self; }
-       LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ* operator ->() { return &self; }
-       const LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ* operator &() const { return &self; }
-       const LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ* operator ->() const { return &self; }
+       CResult_NodeInfoDecodeErrorZ(const CResult_NodeInfoDecodeErrorZ&) = delete;
+       CResult_NodeInfoDecodeErrorZ(CResult_NodeInfoDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_NodeInfoDecodeErrorZ)); }
+       CResult_NodeInfoDecodeErrorZ(LDKCResult_NodeInfoDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_NodeInfoDecodeErrorZ)); }
+       operator LDKCResult_NodeInfoDecodeErrorZ() && { LDKCResult_NodeInfoDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_NodeInfoDecodeErrorZ)); return res; }
+       ~CResult_NodeInfoDecodeErrorZ() { CResult_NodeInfoDecodeErrorZ_free(self); }
+       CResult_NodeInfoDecodeErrorZ& operator=(CResult_NodeInfoDecodeErrorZ&& o) { CResult_NodeInfoDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_NodeInfoDecodeErrorZ)); return *this; }
+       LDKCResult_NodeInfoDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_NodeInfoDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_NodeInfoDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_NodeInfoDecodeErrorZ* operator ->() const { return &self; }
 };
-class C2Tuple_u32TxOutZ {
+class CResult_NonePaymentSendFailureZ {
 private:
-       LDKC2Tuple_u32TxOutZ self;
+       LDKCResult_NonePaymentSendFailureZ self;
 public:
-       C2Tuple_u32TxOutZ(const C2Tuple_u32TxOutZ&) = delete;
-       ~C2Tuple_u32TxOutZ() { C2Tuple_u32TxOutZ_free(self); }
-       C2Tuple_u32TxOutZ(C2Tuple_u32TxOutZ&& o) : self(o.self) { memset(&o, 0, sizeof(C2Tuple_u32TxOutZ)); }
-       C2Tuple_u32TxOutZ(LDKC2Tuple_u32TxOutZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKC2Tuple_u32TxOutZ)); }
-       operator LDKC2Tuple_u32TxOutZ() { LDKC2Tuple_u32TxOutZ res = self; memset(&self, 0, sizeof(LDKC2Tuple_u32TxOutZ)); return res; }
-       LDKC2Tuple_u32TxOutZ* operator &() { return &self; }
-       LDKC2Tuple_u32TxOutZ* operator ->() { return &self; }
-       const LDKC2Tuple_u32TxOutZ* operator &() const { return &self; }
-       const LDKC2Tuple_u32TxOutZ* operator ->() const { return &self; }
+       CResult_NonePaymentSendFailureZ(const CResult_NonePaymentSendFailureZ&) = delete;
+       CResult_NonePaymentSendFailureZ(CResult_NonePaymentSendFailureZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_NonePaymentSendFailureZ)); }
+       CResult_NonePaymentSendFailureZ(LDKCResult_NonePaymentSendFailureZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_NonePaymentSendFailureZ)); }
+       operator LDKCResult_NonePaymentSendFailureZ() && { LDKCResult_NonePaymentSendFailureZ res = self; memset(&self, 0, sizeof(LDKCResult_NonePaymentSendFailureZ)); return res; }
+       ~CResult_NonePaymentSendFailureZ() { CResult_NonePaymentSendFailureZ_free(self); }
+       CResult_NonePaymentSendFailureZ& operator=(CResult_NonePaymentSendFailureZ&& o) { CResult_NonePaymentSendFailureZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_NonePaymentSendFailureZ)); return *this; }
+       LDKCResult_NonePaymentSendFailureZ* operator &() { return &self; }
+       LDKCResult_NonePaymentSendFailureZ* operator ->() { return &self; }
+       const LDKCResult_NonePaymentSendFailureZ* operator &() const { return &self; }
+       const LDKCResult_NonePaymentSendFailureZ* operator ->() const { return &self; }
 };
-class CResult_NoneMonitorUpdateErrorZ {
+class CVec_u8Z {
 private:
-       LDKCResult_NoneMonitorUpdateErrorZ self;
+       LDKCVec_u8Z self;
 public:
-       CResult_NoneMonitorUpdateErrorZ(const CResult_NoneMonitorUpdateErrorZ&) = delete;
-       ~CResult_NoneMonitorUpdateErrorZ() { CResult_NoneMonitorUpdateErrorZ_free(self); }
-       CResult_NoneMonitorUpdateErrorZ(CResult_NoneMonitorUpdateErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_NoneMonitorUpdateErrorZ)); }
-       CResult_NoneMonitorUpdateErrorZ(LDKCResult_NoneMonitorUpdateErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_NoneMonitorUpdateErrorZ)); }
-       operator LDKCResult_NoneMonitorUpdateErrorZ() { LDKCResult_NoneMonitorUpdateErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_NoneMonitorUpdateErrorZ)); return res; }
-       LDKCResult_NoneMonitorUpdateErrorZ* operator &() { return &self; }
-       LDKCResult_NoneMonitorUpdateErrorZ* operator ->() { return &self; }
-       const LDKCResult_NoneMonitorUpdateErrorZ* operator &() const { return &self; }
-       const LDKCResult_NoneMonitorUpdateErrorZ* operator ->() const { return &self; }
+       CVec_u8Z(const CVec_u8Z&) = delete;
+       CVec_u8Z(CVec_u8Z&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_u8Z)); }
+       CVec_u8Z(LDKCVec_u8Z&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_u8Z)); }
+       operator LDKCVec_u8Z() && { LDKCVec_u8Z res = self; memset(&self, 0, sizeof(LDKCVec_u8Z)); return res; }
+       ~CVec_u8Z() { CVec_u8Z_free(self); }
+       CVec_u8Z& operator=(CVec_u8Z&& o) { CVec_u8Z_free(self); self = o.self; memset(&o, 0, sizeof(CVec_u8Z)); return *this; }
+       LDKCVec_u8Z* operator &() { return &self; }
+       LDKCVec_u8Z* operator ->() { return &self; }
+       const LDKCVec_u8Z* operator &() const { return &self; }
+       const LDKCVec_u8Z* operator ->() const { return &self; }
 };
-class CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ {
+class CResult_ChannelPublicKeysDecodeErrorZ {
 private:
-       LDKCVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ self;
+       LDKCResult_ChannelPublicKeysDecodeErrorZ self;
 public:
-       CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ(const CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ&) = delete;
-       ~CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ() { CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ_free(self); }
-       CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ(CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ)); }
-       CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ(LDKCVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ)); }
-       operator LDKCVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ() { LDKCVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ res = self; memset(&self, 0, sizeof(LDKCVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ)); return res; }
-       LDKCVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ* operator &() { return &self; }
-       LDKCVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ* operator ->() { return &self; }
-       const LDKCVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ* operator &() const { return &self; }
-       const LDKCVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ* operator ->() const { return &self; }
+       CResult_ChannelPublicKeysDecodeErrorZ(const CResult_ChannelPublicKeysDecodeErrorZ&) = delete;
+       CResult_ChannelPublicKeysDecodeErrorZ(CResult_ChannelPublicKeysDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_ChannelPublicKeysDecodeErrorZ)); }
+       CResult_ChannelPublicKeysDecodeErrorZ(LDKCResult_ChannelPublicKeysDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_ChannelPublicKeysDecodeErrorZ)); }
+       operator LDKCResult_ChannelPublicKeysDecodeErrorZ() && { LDKCResult_ChannelPublicKeysDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_ChannelPublicKeysDecodeErrorZ)); return res; }
+       ~CResult_ChannelPublicKeysDecodeErrorZ() { CResult_ChannelPublicKeysDecodeErrorZ_free(self); }
+       CResult_ChannelPublicKeysDecodeErrorZ& operator=(CResult_ChannelPublicKeysDecodeErrorZ&& o) { CResult_ChannelPublicKeysDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_ChannelPublicKeysDecodeErrorZ)); return *this; }
+       LDKCResult_ChannelPublicKeysDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_ChannelPublicKeysDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_ChannelPublicKeysDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_ChannelPublicKeysDecodeErrorZ* operator ->() const { return &self; }
 };
-class CVec_PublicKeyZ {
+class CResult_RouteLightningErrorZ {
 private:
-       LDKCVec_PublicKeyZ self;
+       LDKCResult_RouteLightningErrorZ self;
 public:
-       CVec_PublicKeyZ(const CVec_PublicKeyZ&) = delete;
-       ~CVec_PublicKeyZ() { CVec_PublicKeyZ_free(self); }
-       CVec_PublicKeyZ(CVec_PublicKeyZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_PublicKeyZ)); }
-       CVec_PublicKeyZ(LDKCVec_PublicKeyZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_PublicKeyZ)); }
-       operator LDKCVec_PublicKeyZ() { LDKCVec_PublicKeyZ res = self; memset(&self, 0, sizeof(LDKCVec_PublicKeyZ)); return res; }
-       LDKCVec_PublicKeyZ* operator &() { return &self; }
-       LDKCVec_PublicKeyZ* operator ->() { return &self; }
-       const LDKCVec_PublicKeyZ* operator &() const { return &self; }
-       const LDKCVec_PublicKeyZ* operator ->() const { return &self; }
+       CResult_RouteLightningErrorZ(const CResult_RouteLightningErrorZ&) = delete;
+       CResult_RouteLightningErrorZ(CResult_RouteLightningErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_RouteLightningErrorZ)); }
+       CResult_RouteLightningErrorZ(LDKCResult_RouteLightningErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_RouteLightningErrorZ)); }
+       operator LDKCResult_RouteLightningErrorZ() && { LDKCResult_RouteLightningErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_RouteLightningErrorZ)); return res; }
+       ~CResult_RouteLightningErrorZ() { CResult_RouteLightningErrorZ_free(self); }
+       CResult_RouteLightningErrorZ& operator=(CResult_RouteLightningErrorZ&& o) { CResult_RouteLightningErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_RouteLightningErrorZ)); return *this; }
+       LDKCResult_RouteLightningErrorZ* operator &() { return &self; }
+       LDKCResult_RouteLightningErrorZ* operator ->() { return &self; }
+       const LDKCResult_RouteLightningErrorZ* operator &() const { return &self; }
+       const LDKCResult_RouteLightningErrorZ* operator ->() const { return &self; }
 };
-class CResult_boolLightningErrorZ {
-private:
-       LDKCResult_boolLightningErrorZ self;
-public:
-       CResult_boolLightningErrorZ(const CResult_boolLightningErrorZ&) = delete;
-       ~CResult_boolLightningErrorZ() { CResult_boolLightningErrorZ_free(self); }
-       CResult_boolLightningErrorZ(CResult_boolLightningErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_boolLightningErrorZ)); }
-       CResult_boolLightningErrorZ(LDKCResult_boolLightningErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_boolLightningErrorZ)); }
-       operator LDKCResult_boolLightningErrorZ() { LDKCResult_boolLightningErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_boolLightningErrorZ)); return res; }
-       LDKCResult_boolLightningErrorZ* operator &() { return &self; }
-       LDKCResult_boolLightningErrorZ* operator ->() { return &self; }
-       const LDKCResult_boolLightningErrorZ* operator &() const { return &self; }
-       const LDKCResult_boolLightningErrorZ* operator ->() const { return &self; }
+class CResult_ClosingSignedDecodeErrorZ {
+private:
+       LDKCResult_ClosingSignedDecodeErrorZ self;
+public:
+       CResult_ClosingSignedDecodeErrorZ(const CResult_ClosingSignedDecodeErrorZ&) = delete;
+       CResult_ClosingSignedDecodeErrorZ(CResult_ClosingSignedDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_ClosingSignedDecodeErrorZ)); }
+       CResult_ClosingSignedDecodeErrorZ(LDKCResult_ClosingSignedDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_ClosingSignedDecodeErrorZ)); }
+       operator LDKCResult_ClosingSignedDecodeErrorZ() && { LDKCResult_ClosingSignedDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_ClosingSignedDecodeErrorZ)); return res; }
+       ~CResult_ClosingSignedDecodeErrorZ() { CResult_ClosingSignedDecodeErrorZ_free(self); }
+       CResult_ClosingSignedDecodeErrorZ& operator=(CResult_ClosingSignedDecodeErrorZ&& o) { CResult_ClosingSignedDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_ClosingSignedDecodeErrorZ)); return *this; }
+       LDKCResult_ClosingSignedDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_ClosingSignedDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_ClosingSignedDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_ClosingSignedDecodeErrorZ* operator ->() const { return &self; }
+};
+class CResult_HolderCommitmentTransactionDecodeErrorZ {
+private:
+       LDKCResult_HolderCommitmentTransactionDecodeErrorZ self;
+public:
+       CResult_HolderCommitmentTransactionDecodeErrorZ(const CResult_HolderCommitmentTransactionDecodeErrorZ&) = delete;
+       CResult_HolderCommitmentTransactionDecodeErrorZ(CResult_HolderCommitmentTransactionDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_HolderCommitmentTransactionDecodeErrorZ)); }
+       CResult_HolderCommitmentTransactionDecodeErrorZ(LDKCResult_HolderCommitmentTransactionDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_HolderCommitmentTransactionDecodeErrorZ)); }
+       operator LDKCResult_HolderCommitmentTransactionDecodeErrorZ() && { LDKCResult_HolderCommitmentTransactionDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_HolderCommitmentTransactionDecodeErrorZ)); return res; }
+       ~CResult_HolderCommitmentTransactionDecodeErrorZ() { CResult_HolderCommitmentTransactionDecodeErrorZ_free(self); }
+       CResult_HolderCommitmentTransactionDecodeErrorZ& operator=(CResult_HolderCommitmentTransactionDecodeErrorZ&& o) { CResult_HolderCommitmentTransactionDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_HolderCommitmentTransactionDecodeErrorZ)); return *this; }
+       LDKCResult_HolderCommitmentTransactionDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_HolderCommitmentTransactionDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_HolderCommitmentTransactionDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_HolderCommitmentTransactionDecodeErrorZ* operator ->() const { return &self; }
+};
+class CVec_CResult_NoneAPIErrorZZ {
+private:
+       LDKCVec_CResult_NoneAPIErrorZZ self;
+public:
+       CVec_CResult_NoneAPIErrorZZ(const CVec_CResult_NoneAPIErrorZZ&) = delete;
+       CVec_CResult_NoneAPIErrorZZ(CVec_CResult_NoneAPIErrorZZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_CResult_NoneAPIErrorZZ)); }
+       CVec_CResult_NoneAPIErrorZZ(LDKCVec_CResult_NoneAPIErrorZZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_CResult_NoneAPIErrorZZ)); }
+       operator LDKCVec_CResult_NoneAPIErrorZZ() && { LDKCVec_CResult_NoneAPIErrorZZ res = self; memset(&self, 0, sizeof(LDKCVec_CResult_NoneAPIErrorZZ)); return res; }
+       ~CVec_CResult_NoneAPIErrorZZ() { CVec_CResult_NoneAPIErrorZZ_free(self); }
+       CVec_CResult_NoneAPIErrorZZ& operator=(CVec_CResult_NoneAPIErrorZZ&& o) { CVec_CResult_NoneAPIErrorZZ_free(self); self = o.self; memset(&o, 0, sizeof(CVec_CResult_NoneAPIErrorZZ)); return *this; }
+       LDKCVec_CResult_NoneAPIErrorZZ* operator &() { return &self; }
+       LDKCVec_CResult_NoneAPIErrorZZ* operator ->() { return &self; }
+       const LDKCVec_CResult_NoneAPIErrorZZ* operator &() const { return &self; }
+       const LDKCVec_CResult_NoneAPIErrorZZ* operator ->() const { return &self; }
 };
-class CVec_C2Tuple_u32TxOutZZ {
+class CResult_SignatureNoneZ {
 private:
-       LDKCVec_C2Tuple_u32TxOutZZ self;
+       LDKCResult_SignatureNoneZ self;
 public:
-       CVec_C2Tuple_u32TxOutZZ(const CVec_C2Tuple_u32TxOutZZ&) = delete;
-       ~CVec_C2Tuple_u32TxOutZZ() { CVec_C2Tuple_u32TxOutZZ_free(self); }
-       CVec_C2Tuple_u32TxOutZZ(CVec_C2Tuple_u32TxOutZZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_C2Tuple_u32TxOutZZ)); }
-       CVec_C2Tuple_u32TxOutZZ(LDKCVec_C2Tuple_u32TxOutZZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_C2Tuple_u32TxOutZZ)); }
-       operator LDKCVec_C2Tuple_u32TxOutZZ() { LDKCVec_C2Tuple_u32TxOutZZ res = self; memset(&self, 0, sizeof(LDKCVec_C2Tuple_u32TxOutZZ)); return res; }
-       LDKCVec_C2Tuple_u32TxOutZZ* operator &() { return &self; }
-       LDKCVec_C2Tuple_u32TxOutZZ* operator ->() { return &self; }
-       const LDKCVec_C2Tuple_u32TxOutZZ* operator &() const { return &self; }
-       const LDKCVec_C2Tuple_u32TxOutZZ* operator ->() const { return &self; }
+       CResult_SignatureNoneZ(const CResult_SignatureNoneZ&) = delete;
+       CResult_SignatureNoneZ(CResult_SignatureNoneZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_SignatureNoneZ)); }
+       CResult_SignatureNoneZ(LDKCResult_SignatureNoneZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_SignatureNoneZ)); }
+       operator LDKCResult_SignatureNoneZ() && { LDKCResult_SignatureNoneZ res = self; memset(&self, 0, sizeof(LDKCResult_SignatureNoneZ)); return res; }
+       ~CResult_SignatureNoneZ() { CResult_SignatureNoneZ_free(self); }
+       CResult_SignatureNoneZ& operator=(CResult_SignatureNoneZ&& o) { CResult_SignatureNoneZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_SignatureNoneZ)); return *this; }
+       LDKCResult_SignatureNoneZ* operator &() { return &self; }
+       LDKCResult_SignatureNoneZ* operator ->() { return &self; }
+       const LDKCResult_SignatureNoneZ* operator &() const { return &self; }
+       const LDKCResult_SignatureNoneZ* operator ->() const { return &self; }
 };
-class CVec_SignatureZ {
+class C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ {
 private:
-       LDKCVec_SignatureZ self;
+       LDKC2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ self;
 public:
-       CVec_SignatureZ(const CVec_SignatureZ&) = delete;
-       ~CVec_SignatureZ() { CVec_SignatureZ_free(self); }
-       CVec_SignatureZ(CVec_SignatureZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_SignatureZ)); }
-       CVec_SignatureZ(LDKCVec_SignatureZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_SignatureZ)); }
-       operator LDKCVec_SignatureZ() { LDKCVec_SignatureZ res = self; memset(&self, 0, sizeof(LDKCVec_SignatureZ)); return res; }
-       LDKCVec_SignatureZ* operator &() { return &self; }
-       LDKCVec_SignatureZ* operator ->() { return &self; }
-       const LDKCVec_SignatureZ* operator &() const { return &self; }
-       const LDKCVec_SignatureZ* operator ->() const { return &self; }
+       C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ(const C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ&) = delete;
+       C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ(C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ&& o) : self(o.self) { memset(&o, 0, sizeof(C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ)); }
+       C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ(LDKC2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKC2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ)); }
+       operator LDKC2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ() && { LDKC2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ res = self; memset(&self, 0, sizeof(LDKC2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ)); return res; }
+       ~C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ() { C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ_free(self); }
+       C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ& operator=(C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ&& o) { C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ_free(self); self = o.self; memset(&o, 0, sizeof(C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ)); return *this; }
+       LDKC2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ* operator &() { return &self; }
+       LDKC2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ* operator ->() { return &self; }
+       const LDKC2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ* operator &() const { return &self; }
+       const LDKC2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ* operator ->() const { return &self; }
 };
-class C2Tuple_SignatureCVec_SignatureZZ {
+class CResult_InitDecodeErrorZ {
 private:
-       LDKC2Tuple_SignatureCVec_SignatureZZ self;
+       LDKCResult_InitDecodeErrorZ self;
 public:
-       C2Tuple_SignatureCVec_SignatureZZ(const C2Tuple_SignatureCVec_SignatureZZ&) = delete;
-       ~C2Tuple_SignatureCVec_SignatureZZ() { C2Tuple_SignatureCVec_SignatureZZ_free(self); }
-       C2Tuple_SignatureCVec_SignatureZZ(C2Tuple_SignatureCVec_SignatureZZ&& o) : self(o.self) { memset(&o, 0, sizeof(C2Tuple_SignatureCVec_SignatureZZ)); }
-       C2Tuple_SignatureCVec_SignatureZZ(LDKC2Tuple_SignatureCVec_SignatureZZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKC2Tuple_SignatureCVec_SignatureZZ)); }
-       operator LDKC2Tuple_SignatureCVec_SignatureZZ() { LDKC2Tuple_SignatureCVec_SignatureZZ res = self; memset(&self, 0, sizeof(LDKC2Tuple_SignatureCVec_SignatureZZ)); return res; }
-       LDKC2Tuple_SignatureCVec_SignatureZZ* operator &() { return &self; }
-       LDKC2Tuple_SignatureCVec_SignatureZZ* operator ->() { return &self; }
-       const LDKC2Tuple_SignatureCVec_SignatureZZ* operator &() const { return &self; }
-       const LDKC2Tuple_SignatureCVec_SignatureZZ* operator ->() const { return &self; }
+       CResult_InitDecodeErrorZ(const CResult_InitDecodeErrorZ&) = delete;
+       CResult_InitDecodeErrorZ(CResult_InitDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_InitDecodeErrorZ)); }
+       CResult_InitDecodeErrorZ(LDKCResult_InitDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_InitDecodeErrorZ)); }
+       operator LDKCResult_InitDecodeErrorZ() && { LDKCResult_InitDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_InitDecodeErrorZ)); return res; }
+       ~CResult_InitDecodeErrorZ() { CResult_InitDecodeErrorZ_free(self); }
+       CResult_InitDecodeErrorZ& operator=(CResult_InitDecodeErrorZ&& o) { CResult_InitDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_InitDecodeErrorZ)); return *this; }
+       LDKCResult_InitDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_InitDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_InitDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_InitDecodeErrorZ* operator ->() const { return &self; }
 };
-class CVec_u64Z {
+class CResult_OutPointDecodeErrorZ {
 private:
-       LDKCVec_u64Z self;
+       LDKCResult_OutPointDecodeErrorZ self;
 public:
-       CVec_u64Z(const CVec_u64Z&) = delete;
-       ~CVec_u64Z() { CVec_u64Z_free(self); }
-       CVec_u64Z(CVec_u64Z&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_u64Z)); }
-       CVec_u64Z(LDKCVec_u64Z&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_u64Z)); }
-       operator LDKCVec_u64Z() { LDKCVec_u64Z res = self; memset(&self, 0, sizeof(LDKCVec_u64Z)); return res; }
-       LDKCVec_u64Z* operator &() { return &self; }
-       LDKCVec_u64Z* operator ->() { return &self; }
-       const LDKCVec_u64Z* operator &() const { return &self; }
-       const LDKCVec_u64Z* operator ->() const { return &self; }
+       CResult_OutPointDecodeErrorZ(const CResult_OutPointDecodeErrorZ&) = delete;
+       CResult_OutPointDecodeErrorZ(CResult_OutPointDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_OutPointDecodeErrorZ)); }
+       CResult_OutPointDecodeErrorZ(LDKCResult_OutPointDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_OutPointDecodeErrorZ)); }
+       operator LDKCResult_OutPointDecodeErrorZ() && { LDKCResult_OutPointDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_OutPointDecodeErrorZ)); return res; }
+       ~CResult_OutPointDecodeErrorZ() { CResult_OutPointDecodeErrorZ_free(self); }
+       CResult_OutPointDecodeErrorZ& operator=(CResult_OutPointDecodeErrorZ&& o) { CResult_OutPointDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_OutPointDecodeErrorZ)); return *this; }
+       LDKCResult_OutPointDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_OutPointDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_OutPointDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_OutPointDecodeErrorZ* operator ->() const { return &self; }
 };
-class CVec_UpdateFailMalformedHTLCZ {
+class CVec_ChannelDetailsZ {
 private:
-       LDKCVec_UpdateFailMalformedHTLCZ self;
+       LDKCVec_ChannelDetailsZ self;
 public:
-       CVec_UpdateFailMalformedHTLCZ(const CVec_UpdateFailMalformedHTLCZ&) = delete;
-       ~CVec_UpdateFailMalformedHTLCZ() { CVec_UpdateFailMalformedHTLCZ_free(self); }
-       CVec_UpdateFailMalformedHTLCZ(CVec_UpdateFailMalformedHTLCZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_UpdateFailMalformedHTLCZ)); }
-       CVec_UpdateFailMalformedHTLCZ(LDKCVec_UpdateFailMalformedHTLCZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_UpdateFailMalformedHTLCZ)); }
-       operator LDKCVec_UpdateFailMalformedHTLCZ() { LDKCVec_UpdateFailMalformedHTLCZ res = self; memset(&self, 0, sizeof(LDKCVec_UpdateFailMalformedHTLCZ)); return res; }
-       LDKCVec_UpdateFailMalformedHTLCZ* operator &() { return &self; }
-       LDKCVec_UpdateFailMalformedHTLCZ* operator ->() { return &self; }
-       const LDKCVec_UpdateFailMalformedHTLCZ* operator &() const { return &self; }
-       const LDKCVec_UpdateFailMalformedHTLCZ* operator ->() const { return &self; }
+       CVec_ChannelDetailsZ(const CVec_ChannelDetailsZ&) = delete;
+       CVec_ChannelDetailsZ(CVec_ChannelDetailsZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_ChannelDetailsZ)); }
+       CVec_ChannelDetailsZ(LDKCVec_ChannelDetailsZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_ChannelDetailsZ)); }
+       operator LDKCVec_ChannelDetailsZ() && { LDKCVec_ChannelDetailsZ res = self; memset(&self, 0, sizeof(LDKCVec_ChannelDetailsZ)); return res; }
+       ~CVec_ChannelDetailsZ() { CVec_ChannelDetailsZ_free(self); }
+       CVec_ChannelDetailsZ& operator=(CVec_ChannelDetailsZ&& o) { CVec_ChannelDetailsZ_free(self); self = o.self; memset(&o, 0, sizeof(CVec_ChannelDetailsZ)); return *this; }
+       LDKCVec_ChannelDetailsZ* operator &() { return &self; }
+       LDKCVec_ChannelDetailsZ* operator ->() { return &self; }
+       const LDKCVec_ChannelDetailsZ* operator &() const { return &self; }
+       const LDKCVec_ChannelDetailsZ* operator ->() const { return &self; }
 };
-class CResult_SecretKeySecpErrorZ {
+class CResult_SignDecodeErrorZ {
 private:
-       LDKCResult_SecretKeySecpErrorZ self;
+       LDKCResult_SignDecodeErrorZ self;
 public:
-       CResult_SecretKeySecpErrorZ(const CResult_SecretKeySecpErrorZ&) = delete;
-       ~CResult_SecretKeySecpErrorZ() { CResult_SecretKeySecpErrorZ_free(self); }
-       CResult_SecretKeySecpErrorZ(CResult_SecretKeySecpErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_SecretKeySecpErrorZ)); }
-       CResult_SecretKeySecpErrorZ(LDKCResult_SecretKeySecpErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_SecretKeySecpErrorZ)); }
-       operator LDKCResult_SecretKeySecpErrorZ() { LDKCResult_SecretKeySecpErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_SecretKeySecpErrorZ)); return res; }
-       LDKCResult_SecretKeySecpErrorZ* operator &() { return &self; }
-       LDKCResult_SecretKeySecpErrorZ* operator ->() { return &self; }
-       const LDKCResult_SecretKeySecpErrorZ* operator &() const { return &self; }
-       const LDKCResult_SecretKeySecpErrorZ* operator ->() const { return &self; }
+       CResult_SignDecodeErrorZ(const CResult_SignDecodeErrorZ&) = delete;
+       CResult_SignDecodeErrorZ(CResult_SignDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_SignDecodeErrorZ)); }
+       CResult_SignDecodeErrorZ(LDKCResult_SignDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_SignDecodeErrorZ)); }
+       operator LDKCResult_SignDecodeErrorZ() && { LDKCResult_SignDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_SignDecodeErrorZ)); return res; }
+       ~CResult_SignDecodeErrorZ() { CResult_SignDecodeErrorZ_free(self); }
+       CResult_SignDecodeErrorZ& operator=(CResult_SignDecodeErrorZ&& o) { CResult_SignDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_SignDecodeErrorZ)); return *this; }
+       LDKCResult_SignDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_SignDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_SignDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_SignDecodeErrorZ* operator ->() const { return &self; }
 };
-class C2Tuple_HTLCOutputInCommitmentSignatureZ {
+class CVec_MessageSendEventZ {
 private:
-       LDKC2Tuple_HTLCOutputInCommitmentSignatureZ self;
+       LDKCVec_MessageSendEventZ self;
 public:
-       C2Tuple_HTLCOutputInCommitmentSignatureZ(const C2Tuple_HTLCOutputInCommitmentSignatureZ&) = delete;
-       ~C2Tuple_HTLCOutputInCommitmentSignatureZ() { C2Tuple_HTLCOutputInCommitmentSignatureZ_free(self); }
-       C2Tuple_HTLCOutputInCommitmentSignatureZ(C2Tuple_HTLCOutputInCommitmentSignatureZ&& o) : self(o.self) { memset(&o, 0, sizeof(C2Tuple_HTLCOutputInCommitmentSignatureZ)); }
-       C2Tuple_HTLCOutputInCommitmentSignatureZ(LDKC2Tuple_HTLCOutputInCommitmentSignatureZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKC2Tuple_HTLCOutputInCommitmentSignatureZ)); }
-       operator LDKC2Tuple_HTLCOutputInCommitmentSignatureZ() { LDKC2Tuple_HTLCOutputInCommitmentSignatureZ res = self; memset(&self, 0, sizeof(LDKC2Tuple_HTLCOutputInCommitmentSignatureZ)); return res; }
-       LDKC2Tuple_HTLCOutputInCommitmentSignatureZ* operator &() { return &self; }
-       LDKC2Tuple_HTLCOutputInCommitmentSignatureZ* operator ->() { return &self; }
-       const LDKC2Tuple_HTLCOutputInCommitmentSignatureZ* operator &() const { return &self; }
-       const LDKC2Tuple_HTLCOutputInCommitmentSignatureZ* operator ->() const { return &self; }
+       CVec_MessageSendEventZ(const CVec_MessageSendEventZ&) = delete;
+       CVec_MessageSendEventZ(CVec_MessageSendEventZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_MessageSendEventZ)); }
+       CVec_MessageSendEventZ(LDKCVec_MessageSendEventZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_MessageSendEventZ)); }
+       operator LDKCVec_MessageSendEventZ() && { LDKCVec_MessageSendEventZ res = self; memset(&self, 0, sizeof(LDKCVec_MessageSendEventZ)); return res; }
+       ~CVec_MessageSendEventZ() { CVec_MessageSendEventZ_free(self); }
+       CVec_MessageSendEventZ& operator=(CVec_MessageSendEventZ&& o) { CVec_MessageSendEventZ_free(self); self = o.self; memset(&o, 0, sizeof(CVec_MessageSendEventZ)); return *this; }
+       LDKCVec_MessageSendEventZ* operator &() { return &self; }
+       LDKCVec_MessageSendEventZ* operator ->() { return &self; }
+       const LDKCVec_MessageSendEventZ* operator &() const { return &self; }
+       const LDKCVec_MessageSendEventZ* operator ->() const { return &self; }
 };
-class CVec_EventZ {
+class CVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ {
 private:
-       LDKCVec_EventZ self;
+       LDKCVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ self;
 public:
-       CVec_EventZ(const CVec_EventZ&) = delete;
-       ~CVec_EventZ() { CVec_EventZ_free(self); }
-       CVec_EventZ(CVec_EventZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_EventZ)); }
-       CVec_EventZ(LDKCVec_EventZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_EventZ)); }
-       operator LDKCVec_EventZ() { LDKCVec_EventZ res = self; memset(&self, 0, sizeof(LDKCVec_EventZ)); return res; }
-       LDKCVec_EventZ* operator &() { return &self; }
-       LDKCVec_EventZ* operator ->() { return &self; }
-       const LDKCVec_EventZ* operator &() const { return &self; }
-       const LDKCVec_EventZ* operator ->() const { return &self; }
+       CVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ(const CVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ&) = delete;
+       CVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ(CVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ)); }
+       CVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ(LDKCVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ)); }
+       operator LDKCVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ() && { LDKCVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ res = self; memset(&self, 0, sizeof(LDKCVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ)); return res; }
+       ~CVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ() { CVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ_free(self); }
+       CVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ& operator=(CVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ&& o) { CVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ_free(self); self = o.self; memset(&o, 0, sizeof(CVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ)); return *this; }
+       LDKCVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ* operator &() { return &self; }
+       LDKCVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ* operator ->() { return &self; }
+       const LDKCVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ* operator &() const { return &self; }
+       const LDKCVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ* operator ->() const { return &self; }
 };
-class CResult_CVec_u8ZPeerHandleErrorZ {
+class C2Tuple_OutPointScriptZ {
 private:
-       LDKCResult_CVec_u8ZPeerHandleErrorZ self;
+       LDKC2Tuple_OutPointScriptZ self;
 public:
-       CResult_CVec_u8ZPeerHandleErrorZ(const CResult_CVec_u8ZPeerHandleErrorZ&) = delete;
-       ~CResult_CVec_u8ZPeerHandleErrorZ() { CResult_CVec_u8ZPeerHandleErrorZ_free(self); }
-       CResult_CVec_u8ZPeerHandleErrorZ(CResult_CVec_u8ZPeerHandleErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_CVec_u8ZPeerHandleErrorZ)); }
-       CResult_CVec_u8ZPeerHandleErrorZ(LDKCResult_CVec_u8ZPeerHandleErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_CVec_u8ZPeerHandleErrorZ)); }
-       operator LDKCResult_CVec_u8ZPeerHandleErrorZ() { LDKCResult_CVec_u8ZPeerHandleErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_CVec_u8ZPeerHandleErrorZ)); return res; }
-       LDKCResult_CVec_u8ZPeerHandleErrorZ* operator &() { return &self; }
-       LDKCResult_CVec_u8ZPeerHandleErrorZ* operator ->() { return &self; }
-       const LDKCResult_CVec_u8ZPeerHandleErrorZ* operator &() const { return &self; }
-       const LDKCResult_CVec_u8ZPeerHandleErrorZ* operator ->() const { return &self; }
+       C2Tuple_OutPointScriptZ(const C2Tuple_OutPointScriptZ&) = delete;
+       C2Tuple_OutPointScriptZ(C2Tuple_OutPointScriptZ&& o) : self(o.self) { memset(&o, 0, sizeof(C2Tuple_OutPointScriptZ)); }
+       C2Tuple_OutPointScriptZ(LDKC2Tuple_OutPointScriptZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKC2Tuple_OutPointScriptZ)); }
+       operator LDKC2Tuple_OutPointScriptZ() && { LDKC2Tuple_OutPointScriptZ res = self; memset(&self, 0, sizeof(LDKC2Tuple_OutPointScriptZ)); return res; }
+       ~C2Tuple_OutPointScriptZ() { C2Tuple_OutPointScriptZ_free(self); }
+       C2Tuple_OutPointScriptZ& operator=(C2Tuple_OutPointScriptZ&& o) { C2Tuple_OutPointScriptZ_free(self); self = o.self; memset(&o, 0, sizeof(C2Tuple_OutPointScriptZ)); return *this; }
+       LDKC2Tuple_OutPointScriptZ* operator &() { return &self; }
+       LDKC2Tuple_OutPointScriptZ* operator ->() { return &self; }
+       const LDKC2Tuple_OutPointScriptZ* operator &() const { return &self; }
+       const LDKC2Tuple_OutPointScriptZ* operator ->() const { return &self; }
 };
-class CVec_MonitorEventZ {
+class CResult_UpdateFailMalformedHTLCDecodeErrorZ {
 private:
-       LDKCVec_MonitorEventZ self;
+       LDKCResult_UpdateFailMalformedHTLCDecodeErrorZ self;
 public:
-       CVec_MonitorEventZ(const CVec_MonitorEventZ&) = delete;
-       ~CVec_MonitorEventZ() { CVec_MonitorEventZ_free(self); }
-       CVec_MonitorEventZ(CVec_MonitorEventZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_MonitorEventZ)); }
-       CVec_MonitorEventZ(LDKCVec_MonitorEventZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_MonitorEventZ)); }
-       operator LDKCVec_MonitorEventZ() { LDKCVec_MonitorEventZ res = self; memset(&self, 0, sizeof(LDKCVec_MonitorEventZ)); return res; }
-       LDKCVec_MonitorEventZ* operator &() { return &self; }
-       LDKCVec_MonitorEventZ* operator ->() { return &self; }
-       const LDKCVec_MonitorEventZ* operator &() const { return &self; }
-       const LDKCVec_MonitorEventZ* operator ->() const { return &self; }
+       CResult_UpdateFailMalformedHTLCDecodeErrorZ(const CResult_UpdateFailMalformedHTLCDecodeErrorZ&) = delete;
+       CResult_UpdateFailMalformedHTLCDecodeErrorZ(CResult_UpdateFailMalformedHTLCDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_UpdateFailMalformedHTLCDecodeErrorZ)); }
+       CResult_UpdateFailMalformedHTLCDecodeErrorZ(LDKCResult_UpdateFailMalformedHTLCDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_UpdateFailMalformedHTLCDecodeErrorZ)); }
+       operator LDKCResult_UpdateFailMalformedHTLCDecodeErrorZ() && { LDKCResult_UpdateFailMalformedHTLCDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_UpdateFailMalformedHTLCDecodeErrorZ)); return res; }
+       ~CResult_UpdateFailMalformedHTLCDecodeErrorZ() { CResult_UpdateFailMalformedHTLCDecodeErrorZ_free(self); }
+       CResult_UpdateFailMalformedHTLCDecodeErrorZ& operator=(CResult_UpdateFailMalformedHTLCDecodeErrorZ&& o) { CResult_UpdateFailMalformedHTLCDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_UpdateFailMalformedHTLCDecodeErrorZ)); return *this; }
+       LDKCResult_UpdateFailMalformedHTLCDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_UpdateFailMalformedHTLCDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_UpdateFailMalformedHTLCDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_UpdateFailMalformedHTLCDecodeErrorZ* operator ->() const { return &self; }
 };
-class CVec_RouteHopZ {
+class CVec_NodeAnnouncementZ {
 private:
-       LDKCVec_RouteHopZ self;
+       LDKCVec_NodeAnnouncementZ self;
 public:
-       CVec_RouteHopZ(const CVec_RouteHopZ&) = delete;
-       ~CVec_RouteHopZ() { CVec_RouteHopZ_free(self); }
-       CVec_RouteHopZ(CVec_RouteHopZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_RouteHopZ)); }
-       CVec_RouteHopZ(LDKCVec_RouteHopZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_RouteHopZ)); }
-       operator LDKCVec_RouteHopZ() { LDKCVec_RouteHopZ res = self; memset(&self, 0, sizeof(LDKCVec_RouteHopZ)); return res; }
-       LDKCVec_RouteHopZ* operator &() { return &self; }
-       LDKCVec_RouteHopZ* operator ->() { return &self; }
-       const LDKCVec_RouteHopZ* operator &() const { return &self; }
-       const LDKCVec_RouteHopZ* operator ->() const { return &self; }
+       CVec_NodeAnnouncementZ(const CVec_NodeAnnouncementZ&) = delete;
+       CVec_NodeAnnouncementZ(CVec_NodeAnnouncementZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_NodeAnnouncementZ)); }
+       CVec_NodeAnnouncementZ(LDKCVec_NodeAnnouncementZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_NodeAnnouncementZ)); }
+       operator LDKCVec_NodeAnnouncementZ() && { LDKCVec_NodeAnnouncementZ res = self; memset(&self, 0, sizeof(LDKCVec_NodeAnnouncementZ)); return res; }
+       ~CVec_NodeAnnouncementZ() { CVec_NodeAnnouncementZ_free(self); }
+       CVec_NodeAnnouncementZ& operator=(CVec_NodeAnnouncementZ&& o) { CVec_NodeAnnouncementZ_free(self); self = o.self; memset(&o, 0, sizeof(CVec_NodeAnnouncementZ)); return *this; }
+       LDKCVec_NodeAnnouncementZ* operator &() { return &self; }
+       LDKCVec_NodeAnnouncementZ* operator ->() { return &self; }
+       const LDKCVec_NodeAnnouncementZ* operator &() const { return &self; }
+       const LDKCVec_NodeAnnouncementZ* operator ->() const { return &self; }
 };
-class CResult_TxOutAccessErrorZ {
+class CResult_UnsignedChannelAnnouncementDecodeErrorZ {
 private:
-       LDKCResult_TxOutAccessErrorZ self;
+       LDKCResult_UnsignedChannelAnnouncementDecodeErrorZ self;
 public:
-       CResult_TxOutAccessErrorZ(const CResult_TxOutAccessErrorZ&) = delete;
-       ~CResult_TxOutAccessErrorZ() { CResult_TxOutAccessErrorZ_free(self); }
-       CResult_TxOutAccessErrorZ(CResult_TxOutAccessErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_TxOutAccessErrorZ)); }
-       CResult_TxOutAccessErrorZ(LDKCResult_TxOutAccessErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_TxOutAccessErrorZ)); }
-       operator LDKCResult_TxOutAccessErrorZ() { LDKCResult_TxOutAccessErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_TxOutAccessErrorZ)); return res; }
-       LDKCResult_TxOutAccessErrorZ* operator &() { return &self; }
-       LDKCResult_TxOutAccessErrorZ* operator ->() { return &self; }
-       const LDKCResult_TxOutAccessErrorZ* operator &() const { return &self; }
-       const LDKCResult_TxOutAccessErrorZ* operator ->() const { return &self; }
+       CResult_UnsignedChannelAnnouncementDecodeErrorZ(const CResult_UnsignedChannelAnnouncementDecodeErrorZ&) = delete;
+       CResult_UnsignedChannelAnnouncementDecodeErrorZ(CResult_UnsignedChannelAnnouncementDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_UnsignedChannelAnnouncementDecodeErrorZ)); }
+       CResult_UnsignedChannelAnnouncementDecodeErrorZ(LDKCResult_UnsignedChannelAnnouncementDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_UnsignedChannelAnnouncementDecodeErrorZ)); }
+       operator LDKCResult_UnsignedChannelAnnouncementDecodeErrorZ() && { LDKCResult_UnsignedChannelAnnouncementDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_UnsignedChannelAnnouncementDecodeErrorZ)); return res; }
+       ~CResult_UnsignedChannelAnnouncementDecodeErrorZ() { CResult_UnsignedChannelAnnouncementDecodeErrorZ_free(self); }
+       CResult_UnsignedChannelAnnouncementDecodeErrorZ& operator=(CResult_UnsignedChannelAnnouncementDecodeErrorZ&& o) { CResult_UnsignedChannelAnnouncementDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_UnsignedChannelAnnouncementDecodeErrorZ)); return *this; }
+       LDKCResult_UnsignedChannelAnnouncementDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_UnsignedChannelAnnouncementDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_UnsignedChannelAnnouncementDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_UnsignedChannelAnnouncementDecodeErrorZ* operator ->() const { return &self; }
 };
-class CResult_NoneChannelMonitorUpdateErrZ {
+class CResult_PongDecodeErrorZ {
 private:
-       LDKCResult_NoneChannelMonitorUpdateErrZ self;
+       LDKCResult_PongDecodeErrorZ self;
 public:
-       CResult_NoneChannelMonitorUpdateErrZ(const CResult_NoneChannelMonitorUpdateErrZ&) = delete;
-       ~CResult_NoneChannelMonitorUpdateErrZ() { CResult_NoneChannelMonitorUpdateErrZ_free(self); }
-       CResult_NoneChannelMonitorUpdateErrZ(CResult_NoneChannelMonitorUpdateErrZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_NoneChannelMonitorUpdateErrZ)); }
-       CResult_NoneChannelMonitorUpdateErrZ(LDKCResult_NoneChannelMonitorUpdateErrZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_NoneChannelMonitorUpdateErrZ)); }
-       operator LDKCResult_NoneChannelMonitorUpdateErrZ() { LDKCResult_NoneChannelMonitorUpdateErrZ res = self; memset(&self, 0, sizeof(LDKCResult_NoneChannelMonitorUpdateErrZ)); return res; }
-       LDKCResult_NoneChannelMonitorUpdateErrZ* operator &() { return &self; }
-       LDKCResult_NoneChannelMonitorUpdateErrZ* operator ->() { return &self; }
-       const LDKCResult_NoneChannelMonitorUpdateErrZ* operator &() const { return &self; }
-       const LDKCResult_NoneChannelMonitorUpdateErrZ* operator ->() const { return &self; }
+       CResult_PongDecodeErrorZ(const CResult_PongDecodeErrorZ&) = delete;
+       CResult_PongDecodeErrorZ(CResult_PongDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_PongDecodeErrorZ)); }
+       CResult_PongDecodeErrorZ(LDKCResult_PongDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_PongDecodeErrorZ)); }
+       operator LDKCResult_PongDecodeErrorZ() && { LDKCResult_PongDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_PongDecodeErrorZ)); return res; }
+       ~CResult_PongDecodeErrorZ() { CResult_PongDecodeErrorZ_free(self); }
+       CResult_PongDecodeErrorZ& operator=(CResult_PongDecodeErrorZ&& o) { CResult_PongDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_PongDecodeErrorZ)); return *this; }
+       LDKCResult_PongDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_PongDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_PongDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_PongDecodeErrorZ* operator ->() const { return &self; }
 };
-class CResult_NonePaymentSendFailureZ {
+class CResult_NoneMonitorUpdateErrorZ {
 private:
-       LDKCResult_NonePaymentSendFailureZ self;
+       LDKCResult_NoneMonitorUpdateErrorZ self;
 public:
-       CResult_NonePaymentSendFailureZ(const CResult_NonePaymentSendFailureZ&) = delete;
-       ~CResult_NonePaymentSendFailureZ() { CResult_NonePaymentSendFailureZ_free(self); }
-       CResult_NonePaymentSendFailureZ(CResult_NonePaymentSendFailureZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_NonePaymentSendFailureZ)); }
-       CResult_NonePaymentSendFailureZ(LDKCResult_NonePaymentSendFailureZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_NonePaymentSendFailureZ)); }
-       operator LDKCResult_NonePaymentSendFailureZ() { LDKCResult_NonePaymentSendFailureZ res = self; memset(&self, 0, sizeof(LDKCResult_NonePaymentSendFailureZ)); return res; }
-       LDKCResult_NonePaymentSendFailureZ* operator &() { return &self; }
-       LDKCResult_NonePaymentSendFailureZ* operator ->() { return &self; }
-       const LDKCResult_NonePaymentSendFailureZ* operator &() const { return &self; }
-       const LDKCResult_NonePaymentSendFailureZ* operator ->() const { return &self; }
+       CResult_NoneMonitorUpdateErrorZ(const CResult_NoneMonitorUpdateErrorZ&) = delete;
+       CResult_NoneMonitorUpdateErrorZ(CResult_NoneMonitorUpdateErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_NoneMonitorUpdateErrorZ)); }
+       CResult_NoneMonitorUpdateErrorZ(LDKCResult_NoneMonitorUpdateErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_NoneMonitorUpdateErrorZ)); }
+       operator LDKCResult_NoneMonitorUpdateErrorZ() && { LDKCResult_NoneMonitorUpdateErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_NoneMonitorUpdateErrorZ)); return res; }
+       ~CResult_NoneMonitorUpdateErrorZ() { CResult_NoneMonitorUpdateErrorZ_free(self); }
+       CResult_NoneMonitorUpdateErrorZ& operator=(CResult_NoneMonitorUpdateErrorZ&& o) { CResult_NoneMonitorUpdateErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_NoneMonitorUpdateErrorZ)); return *this; }
+       LDKCResult_NoneMonitorUpdateErrorZ* operator &() { return &self; }
+       LDKCResult_NoneMonitorUpdateErrorZ* operator ->() { return &self; }
+       const LDKCResult_NoneMonitorUpdateErrorZ* operator &() const { return &self; }
+       const LDKCResult_NoneMonitorUpdateErrorZ* operator ->() const { return &self; }
 };
-class CResult_TxCreationKeysSecpErrorZ {
+class CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ {
 private:
-       LDKCResult_TxCreationKeysSecpErrorZ self;
+       LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ self;
 public:
-       CResult_TxCreationKeysSecpErrorZ(const CResult_TxCreationKeysSecpErrorZ&) = delete;
-       ~CResult_TxCreationKeysSecpErrorZ() { CResult_TxCreationKeysSecpErrorZ_free(self); }
-       CResult_TxCreationKeysSecpErrorZ(CResult_TxCreationKeysSecpErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_TxCreationKeysSecpErrorZ)); }
-       CResult_TxCreationKeysSecpErrorZ(LDKCResult_TxCreationKeysSecpErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_TxCreationKeysSecpErrorZ)); }
-       operator LDKCResult_TxCreationKeysSecpErrorZ() { LDKCResult_TxCreationKeysSecpErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_TxCreationKeysSecpErrorZ)); return res; }
-       LDKCResult_TxCreationKeysSecpErrorZ* operator &() { return &self; }
-       LDKCResult_TxCreationKeysSecpErrorZ* operator ->() { return &self; }
-       const LDKCResult_TxCreationKeysSecpErrorZ* operator &() const { return &self; }
-       const LDKCResult_TxCreationKeysSecpErrorZ* operator ->() const { return &self; }
+       CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ(const CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ&) = delete;
+       CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ(CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ)); }
+       CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ(LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ)); }
+       operator LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ() && { LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ res = self; memset(&self, 0, sizeof(LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ)); return res; }
+       ~CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ() { CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ_free(self); }
+       CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ& operator=(CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ&& o) { CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ)); return *this; }
+       LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ* operator &() { return &self; }
+       LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ* operator ->() { return &self; }
+       const LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ* operator &() const { return &self; }
+       const LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ* operator ->() const { return &self; }
 };
-class CVec_u8Z {
+class CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ {
 private:
-       LDKCVec_u8Z self;
+       LDKCVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ self;
 public:
-       CVec_u8Z(const CVec_u8Z&) = delete;
-       ~CVec_u8Z() { CVec_u8Z_free(self); }
-       CVec_u8Z(CVec_u8Z&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_u8Z)); }
-       CVec_u8Z(LDKCVec_u8Z&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_u8Z)); }
-       operator LDKCVec_u8Z() { LDKCVec_u8Z res = self; memset(&self, 0, sizeof(LDKCVec_u8Z)); return res; }
-       LDKCVec_u8Z* operator &() { return &self; }
-       LDKCVec_u8Z* operator ->() { return &self; }
-       const LDKCVec_u8Z* operator &() const { return &self; }
-       const LDKCVec_u8Z* operator ->() const { return &self; }
+       CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ(const CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ&) = delete;
+       CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ(CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ)); }
+       CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ(LDKCVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ)); }
+       operator LDKCVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ() && { LDKCVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ res = self; memset(&self, 0, sizeof(LDKCVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ)); return res; }
+       ~CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ() { CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ_free(self); }
+       CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ& operator=(CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ&& o) { CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ_free(self); self = o.self; memset(&o, 0, sizeof(CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ)); return *this; }
+       LDKCVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ* operator &() { return &self; }
+       LDKCVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ* operator ->() { return &self; }
+       const LDKCVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ* operator &() const { return &self; }
+       const LDKCVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ* operator ->() const { return &self; }
 };
-class CResult_PublicKeySecpErrorZ {
+class CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ {
+private:
+       LDKCResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ self;
+public:
+       CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ(const CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ&) = delete;
+       CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ(CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ)); }
+       CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ(LDKCResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ)); }
+       operator LDKCResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ() && { LDKCResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ)); return res; }
+       ~CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ() { CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_free(self); }
+       CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ& operator=(CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ&& o) { CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ)); return *this; }
+       LDKCResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ* operator ->() const { return &self; }
+};
+class CResult_CVec_CVec_u8ZZNoneZ {
+private:
+       LDKCResult_CVec_CVec_u8ZZNoneZ self;
+public:
+       CResult_CVec_CVec_u8ZZNoneZ(const CResult_CVec_CVec_u8ZZNoneZ&) = delete;
+       CResult_CVec_CVec_u8ZZNoneZ(CResult_CVec_CVec_u8ZZNoneZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_CVec_CVec_u8ZZNoneZ)); }
+       CResult_CVec_CVec_u8ZZNoneZ(LDKCResult_CVec_CVec_u8ZZNoneZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_CVec_CVec_u8ZZNoneZ)); }
+       operator LDKCResult_CVec_CVec_u8ZZNoneZ() && { LDKCResult_CVec_CVec_u8ZZNoneZ res = self; memset(&self, 0, sizeof(LDKCResult_CVec_CVec_u8ZZNoneZ)); return res; }
+       ~CResult_CVec_CVec_u8ZZNoneZ() { CResult_CVec_CVec_u8ZZNoneZ_free(self); }
+       CResult_CVec_CVec_u8ZZNoneZ& operator=(CResult_CVec_CVec_u8ZZNoneZ&& o) { CResult_CVec_CVec_u8ZZNoneZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_CVec_CVec_u8ZZNoneZ)); return *this; }
+       LDKCResult_CVec_CVec_u8ZZNoneZ* operator &() { return &self; }
+       LDKCResult_CVec_CVec_u8ZZNoneZ* operator ->() { return &self; }
+       const LDKCResult_CVec_CVec_u8ZZNoneZ* operator &() const { return &self; }
+       const LDKCResult_CVec_CVec_u8ZZNoneZ* operator ->() const { return &self; }
+};
+class CResult_AcceptChannelDecodeErrorZ {
+private:
+       LDKCResult_AcceptChannelDecodeErrorZ self;
+public:
+       CResult_AcceptChannelDecodeErrorZ(const CResult_AcceptChannelDecodeErrorZ&) = delete;
+       CResult_AcceptChannelDecodeErrorZ(CResult_AcceptChannelDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_AcceptChannelDecodeErrorZ)); }
+       CResult_AcceptChannelDecodeErrorZ(LDKCResult_AcceptChannelDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_AcceptChannelDecodeErrorZ)); }
+       operator LDKCResult_AcceptChannelDecodeErrorZ() && { LDKCResult_AcceptChannelDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_AcceptChannelDecodeErrorZ)); return res; }
+       ~CResult_AcceptChannelDecodeErrorZ() { CResult_AcceptChannelDecodeErrorZ_free(self); }
+       CResult_AcceptChannelDecodeErrorZ& operator=(CResult_AcceptChannelDecodeErrorZ&& o) { CResult_AcceptChannelDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_AcceptChannelDecodeErrorZ)); return *this; }
+       LDKCResult_AcceptChannelDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_AcceptChannelDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_AcceptChannelDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_AcceptChannelDecodeErrorZ* operator ->() const { return &self; }
+};
+class C2Tuple_BlockHashChannelManagerZ {
+private:
+       LDKC2Tuple_BlockHashChannelManagerZ self;
+public:
+       C2Tuple_BlockHashChannelManagerZ(const C2Tuple_BlockHashChannelManagerZ&) = delete;
+       C2Tuple_BlockHashChannelManagerZ(C2Tuple_BlockHashChannelManagerZ&& o) : self(o.self) { memset(&o, 0, sizeof(C2Tuple_BlockHashChannelManagerZ)); }
+       C2Tuple_BlockHashChannelManagerZ(LDKC2Tuple_BlockHashChannelManagerZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKC2Tuple_BlockHashChannelManagerZ)); }
+       operator LDKC2Tuple_BlockHashChannelManagerZ() && { LDKC2Tuple_BlockHashChannelManagerZ res = self; memset(&self, 0, sizeof(LDKC2Tuple_BlockHashChannelManagerZ)); return res; }
+       ~C2Tuple_BlockHashChannelManagerZ() { C2Tuple_BlockHashChannelManagerZ_free(self); }
+       C2Tuple_BlockHashChannelManagerZ& operator=(C2Tuple_BlockHashChannelManagerZ&& o) { C2Tuple_BlockHashChannelManagerZ_free(self); self = o.self; memset(&o, 0, sizeof(C2Tuple_BlockHashChannelManagerZ)); return *this; }
+       LDKC2Tuple_BlockHashChannelManagerZ* operator &() { return &self; }
+       LDKC2Tuple_BlockHashChannelManagerZ* operator ->() { return &self; }
+       const LDKC2Tuple_BlockHashChannelManagerZ* operator &() const { return &self; }
+       const LDKC2Tuple_BlockHashChannelManagerZ* operator ->() const { return &self; }
+};
+class CResult_ChannelTransactionParametersDecodeErrorZ {
+private:
+       LDKCResult_ChannelTransactionParametersDecodeErrorZ self;
+public:
+       CResult_ChannelTransactionParametersDecodeErrorZ(const CResult_ChannelTransactionParametersDecodeErrorZ&) = delete;
+       CResult_ChannelTransactionParametersDecodeErrorZ(CResult_ChannelTransactionParametersDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_ChannelTransactionParametersDecodeErrorZ)); }
+       CResult_ChannelTransactionParametersDecodeErrorZ(LDKCResult_ChannelTransactionParametersDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_ChannelTransactionParametersDecodeErrorZ)); }
+       operator LDKCResult_ChannelTransactionParametersDecodeErrorZ() && { LDKCResult_ChannelTransactionParametersDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_ChannelTransactionParametersDecodeErrorZ)); return res; }
+       ~CResult_ChannelTransactionParametersDecodeErrorZ() { CResult_ChannelTransactionParametersDecodeErrorZ_free(self); }
+       CResult_ChannelTransactionParametersDecodeErrorZ& operator=(CResult_ChannelTransactionParametersDecodeErrorZ&& o) { CResult_ChannelTransactionParametersDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_ChannelTransactionParametersDecodeErrorZ)); return *this; }
+       LDKCResult_ChannelTransactionParametersDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_ChannelTransactionParametersDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_ChannelTransactionParametersDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_ChannelTransactionParametersDecodeErrorZ* operator ->() const { return &self; }
+};
+class CVec_SignatureZ {
 private:
-       LDKCResult_PublicKeySecpErrorZ self;
+       LDKCVec_SignatureZ self;
 public:
-       CResult_PublicKeySecpErrorZ(const CResult_PublicKeySecpErrorZ&) = delete;
-       ~CResult_PublicKeySecpErrorZ() { CResult_PublicKeySecpErrorZ_free(self); }
-       CResult_PublicKeySecpErrorZ(CResult_PublicKeySecpErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_PublicKeySecpErrorZ)); }
-       CResult_PublicKeySecpErrorZ(LDKCResult_PublicKeySecpErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_PublicKeySecpErrorZ)); }
-       operator LDKCResult_PublicKeySecpErrorZ() { LDKCResult_PublicKeySecpErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_PublicKeySecpErrorZ)); return res; }
-       LDKCResult_PublicKeySecpErrorZ* operator &() { return &self; }
-       LDKCResult_PublicKeySecpErrorZ* operator ->() { return &self; }
-       const LDKCResult_PublicKeySecpErrorZ* operator &() const { return &self; }
-       const LDKCResult_PublicKeySecpErrorZ* operator ->() const { return &self; }
+       CVec_SignatureZ(const CVec_SignatureZ&) = delete;
+       CVec_SignatureZ(CVec_SignatureZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_SignatureZ)); }
+       CVec_SignatureZ(LDKCVec_SignatureZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_SignatureZ)); }
+       operator LDKCVec_SignatureZ() && { LDKCVec_SignatureZ res = self; memset(&self, 0, sizeof(LDKCVec_SignatureZ)); return res; }
+       ~CVec_SignatureZ() { CVec_SignatureZ_free(self); }
+       CVec_SignatureZ& operator=(CVec_SignatureZ&& o) { CVec_SignatureZ_free(self); self = o.self; memset(&o, 0, sizeof(CVec_SignatureZ)); return *this; }
+       LDKCVec_SignatureZ* operator &() { return &self; }
+       LDKCVec_SignatureZ* operator ->() { return &self; }
+       const LDKCVec_SignatureZ* operator &() const { return &self; }
+       const LDKCVec_SignatureZ* operator ->() const { return &self; }
 };
-class CVec_C2Tuple_HTLCOutputInCommitmentSignatureZZ {
+class CVec_u64Z {
 private:
-       LDKCVec_C2Tuple_HTLCOutputInCommitmentSignatureZZ self;
+       LDKCVec_u64Z self;
 public:
-       CVec_C2Tuple_HTLCOutputInCommitmentSignatureZZ(const CVec_C2Tuple_HTLCOutputInCommitmentSignatureZZ&) = delete;
-       ~CVec_C2Tuple_HTLCOutputInCommitmentSignatureZZ() { CVec_C2Tuple_HTLCOutputInCommitmentSignatureZZ_free(self); }
-       CVec_C2Tuple_HTLCOutputInCommitmentSignatureZZ(CVec_C2Tuple_HTLCOutputInCommitmentSignatureZZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_C2Tuple_HTLCOutputInCommitmentSignatureZZ)); }
-       CVec_C2Tuple_HTLCOutputInCommitmentSignatureZZ(LDKCVec_C2Tuple_HTLCOutputInCommitmentSignatureZZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_C2Tuple_HTLCOutputInCommitmentSignatureZZ)); }
-       operator LDKCVec_C2Tuple_HTLCOutputInCommitmentSignatureZZ() { LDKCVec_C2Tuple_HTLCOutputInCommitmentSignatureZZ res = self; memset(&self, 0, sizeof(LDKCVec_C2Tuple_HTLCOutputInCommitmentSignatureZZ)); return res; }
-       LDKCVec_C2Tuple_HTLCOutputInCommitmentSignatureZZ* operator &() { return &self; }
-       LDKCVec_C2Tuple_HTLCOutputInCommitmentSignatureZZ* operator ->() { return &self; }
-       const LDKCVec_C2Tuple_HTLCOutputInCommitmentSignatureZZ* operator &() const { return &self; }
-       const LDKCVec_C2Tuple_HTLCOutputInCommitmentSignatureZZ* operator ->() const { return &self; }
+       CVec_u64Z(const CVec_u64Z&) = delete;
+       CVec_u64Z(CVec_u64Z&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_u64Z)); }
+       CVec_u64Z(LDKCVec_u64Z&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_u64Z)); }
+       operator LDKCVec_u64Z() && { LDKCVec_u64Z res = self; memset(&self, 0, sizeof(LDKCVec_u64Z)); return res; }
+       ~CVec_u64Z() { CVec_u64Z_free(self); }
+       CVec_u64Z& operator=(CVec_u64Z&& o) { CVec_u64Z_free(self); self = o.self; memset(&o, 0, sizeof(CVec_u64Z)); return *this; }
+       LDKCVec_u64Z* operator &() { return &self; }
+       LDKCVec_u64Z* operator ->() { return &self; }
+       const LDKCVec_u64Z* operator &() const { return &self; }
+       const LDKCVec_u64Z* operator ->() const { return &self; }
 };
-class C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ {
+class CVec_RouteHintZ {
 private:
-       LDKC3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ self;
+       LDKCVec_RouteHintZ self;
 public:
-       C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ(const C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ&) = delete;
-       ~C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ() { C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ_free(self); }
-       C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ(C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ&& o) : self(o.self) { memset(&o, 0, sizeof(C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ)); }
-       C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ(LDKC3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKC3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ)); }
-       operator LDKC3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ() { LDKC3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ res = self; memset(&self, 0, sizeof(LDKC3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ)); return res; }
-       LDKC3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ* operator &() { return &self; }
-       LDKC3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ* operator ->() { return &self; }
-       const LDKC3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ* operator &() const { return &self; }
-       const LDKC3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ* operator ->() const { return &self; }
+       CVec_RouteHintZ(const CVec_RouteHintZ&) = delete;
+       CVec_RouteHintZ(CVec_RouteHintZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_RouteHintZ)); }
+       CVec_RouteHintZ(LDKCVec_RouteHintZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_RouteHintZ)); }
+       operator LDKCVec_RouteHintZ() && { LDKCVec_RouteHintZ res = self; memset(&self, 0, sizeof(LDKCVec_RouteHintZ)); return res; }
+       ~CVec_RouteHintZ() { CVec_RouteHintZ_free(self); }
+       CVec_RouteHintZ& operator=(CVec_RouteHintZ&& o) { CVec_RouteHintZ_free(self); self = o.self; memset(&o, 0, sizeof(CVec_RouteHintZ)); return *this; }
+       LDKCVec_RouteHintZ* operator &() { return &self; }
+       LDKCVec_RouteHintZ* operator ->() { return &self; }
+       const LDKCVec_RouteHintZ* operator &() const { return &self; }
+       const LDKCVec_RouteHintZ* operator ->() const { return &self; }
 };
 class CVec_CVec_RouteHopZZ {
 private:
        LDKCVec_CVec_RouteHopZZ self;
 public:
        CVec_CVec_RouteHopZZ(const CVec_CVec_RouteHopZZ&) = delete;
-       ~CVec_CVec_RouteHopZZ() { CVec_CVec_RouteHopZZ_free(self); }
        CVec_CVec_RouteHopZZ(CVec_CVec_RouteHopZZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_CVec_RouteHopZZ)); }
        CVec_CVec_RouteHopZZ(LDKCVec_CVec_RouteHopZZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_CVec_RouteHopZZ)); }
-       operator LDKCVec_CVec_RouteHopZZ() { LDKCVec_CVec_RouteHopZZ res = self; memset(&self, 0, sizeof(LDKCVec_CVec_RouteHopZZ)); return res; }
+       operator LDKCVec_CVec_RouteHopZZ() && { LDKCVec_CVec_RouteHopZZ res = self; memset(&self, 0, sizeof(LDKCVec_CVec_RouteHopZZ)); return res; }
+       ~CVec_CVec_RouteHopZZ() { CVec_CVec_RouteHopZZ_free(self); }
+       CVec_CVec_RouteHopZZ& operator=(CVec_CVec_RouteHopZZ&& o) { CVec_CVec_RouteHopZZ_free(self); self = o.self; memset(&o, 0, sizeof(CVec_CVec_RouteHopZZ)); return *this; }
        LDKCVec_CVec_RouteHopZZ* operator &() { return &self; }
        LDKCVec_CVec_RouteHopZZ* operator ->() { return &self; }
        const LDKCVec_CVec_RouteHopZZ* operator &() const { return &self; }
        const LDKCVec_CVec_RouteHopZZ* operator ->() const { return &self; }
 };
-class CVec_UpdateAddHTLCZ {
+class CResult_TrustedCommitmentTransactionNoneZ {
 private:
-       LDKCVec_UpdateAddHTLCZ self;
+       LDKCResult_TrustedCommitmentTransactionNoneZ self;
 public:
-       CVec_UpdateAddHTLCZ(const CVec_UpdateAddHTLCZ&) = delete;
-       ~CVec_UpdateAddHTLCZ() { CVec_UpdateAddHTLCZ_free(self); }
-       CVec_UpdateAddHTLCZ(CVec_UpdateAddHTLCZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_UpdateAddHTLCZ)); }
-       CVec_UpdateAddHTLCZ(LDKCVec_UpdateAddHTLCZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_UpdateAddHTLCZ)); }
-       operator LDKCVec_UpdateAddHTLCZ() { LDKCVec_UpdateAddHTLCZ res = self; memset(&self, 0, sizeof(LDKCVec_UpdateAddHTLCZ)); return res; }
-       LDKCVec_UpdateAddHTLCZ* operator &() { return &self; }
-       LDKCVec_UpdateAddHTLCZ* operator ->() { return &self; }
-       const LDKCVec_UpdateAddHTLCZ* operator &() const { return &self; }
-       const LDKCVec_UpdateAddHTLCZ* operator ->() const { return &self; }
+       CResult_TrustedCommitmentTransactionNoneZ(const CResult_TrustedCommitmentTransactionNoneZ&) = delete;
+       CResult_TrustedCommitmentTransactionNoneZ(CResult_TrustedCommitmentTransactionNoneZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_TrustedCommitmentTransactionNoneZ)); }
+       CResult_TrustedCommitmentTransactionNoneZ(LDKCResult_TrustedCommitmentTransactionNoneZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_TrustedCommitmentTransactionNoneZ)); }
+       operator LDKCResult_TrustedCommitmentTransactionNoneZ() && { LDKCResult_TrustedCommitmentTransactionNoneZ res = self; memset(&self, 0, sizeof(LDKCResult_TrustedCommitmentTransactionNoneZ)); return res; }
+       ~CResult_TrustedCommitmentTransactionNoneZ() { CResult_TrustedCommitmentTransactionNoneZ_free(self); }
+       CResult_TrustedCommitmentTransactionNoneZ& operator=(CResult_TrustedCommitmentTransactionNoneZ&& o) { CResult_TrustedCommitmentTransactionNoneZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_TrustedCommitmentTransactionNoneZ)); return *this; }
+       LDKCResult_TrustedCommitmentTransactionNoneZ* operator &() { return &self; }
+       LDKCResult_TrustedCommitmentTransactionNoneZ* operator ->() { return &self; }
+       const LDKCResult_TrustedCommitmentTransactionNoneZ* operator &() const { return &self; }
+       const LDKCResult_TrustedCommitmentTransactionNoneZ* operator ->() const { return &self; }
 };
 class CResult_NonePeerHandleErrorZ {
 private:
        LDKCResult_NonePeerHandleErrorZ self;
 public:
        CResult_NonePeerHandleErrorZ(const CResult_NonePeerHandleErrorZ&) = delete;
-       ~CResult_NonePeerHandleErrorZ() { CResult_NonePeerHandleErrorZ_free(self); }
        CResult_NonePeerHandleErrorZ(CResult_NonePeerHandleErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_NonePeerHandleErrorZ)); }
        CResult_NonePeerHandleErrorZ(LDKCResult_NonePeerHandleErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_NonePeerHandleErrorZ)); }
-       operator LDKCResult_NonePeerHandleErrorZ() { LDKCResult_NonePeerHandleErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_NonePeerHandleErrorZ)); return res; }
-       LDKCResult_NonePeerHandleErrorZ* operator &() { return &self; }
-       LDKCResult_NonePeerHandleErrorZ* operator ->() { return &self; }
-       const LDKCResult_NonePeerHandleErrorZ* operator &() const { return &self; }
-       const LDKCResult_NonePeerHandleErrorZ* operator ->() const { return &self; }
-};
-class CResult_boolPeerHandleErrorZ {
-private:
-       LDKCResult_boolPeerHandleErrorZ self;
-public:
-       CResult_boolPeerHandleErrorZ(const CResult_boolPeerHandleErrorZ&) = delete;
-       ~CResult_boolPeerHandleErrorZ() { CResult_boolPeerHandleErrorZ_free(self); }
-       CResult_boolPeerHandleErrorZ(CResult_boolPeerHandleErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_boolPeerHandleErrorZ)); }
-       CResult_boolPeerHandleErrorZ(LDKCResult_boolPeerHandleErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_boolPeerHandleErrorZ)); }
-       operator LDKCResult_boolPeerHandleErrorZ() { LDKCResult_boolPeerHandleErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_boolPeerHandleErrorZ)); return res; }
-       LDKCResult_boolPeerHandleErrorZ* operator &() { return &self; }
-       LDKCResult_boolPeerHandleErrorZ* operator ->() { return &self; }
-       const LDKCResult_boolPeerHandleErrorZ* operator &() const { return &self; }
-       const LDKCResult_boolPeerHandleErrorZ* operator ->() const { return &self; }
-};
-class CVec_RouteHintZ {
-private:
-       LDKCVec_RouteHintZ self;
-public:
-       CVec_RouteHintZ(const CVec_RouteHintZ&) = delete;
-       ~CVec_RouteHintZ() { CVec_RouteHintZ_free(self); }
-       CVec_RouteHintZ(CVec_RouteHintZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_RouteHintZ)); }
-       CVec_RouteHintZ(LDKCVec_RouteHintZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_RouteHintZ)); }
-       operator LDKCVec_RouteHintZ() { LDKCVec_RouteHintZ res = self; memset(&self, 0, sizeof(LDKCVec_RouteHintZ)); return res; }
-       LDKCVec_RouteHintZ* operator &() { return &self; }
-       LDKCVec_RouteHintZ* operator ->() { return &self; }
-       const LDKCVec_RouteHintZ* operator &() const { return &self; }
-       const LDKCVec_RouteHintZ* operator ->() const { return &self; }
-};
-class CResult_RouteLightningErrorZ {
-private:
-       LDKCResult_RouteLightningErrorZ self;
-public:
-       CResult_RouteLightningErrorZ(const CResult_RouteLightningErrorZ&) = delete;
-       ~CResult_RouteLightningErrorZ() { CResult_RouteLightningErrorZ_free(self); }
-       CResult_RouteLightningErrorZ(CResult_RouteLightningErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_RouteLightningErrorZ)); }
-       CResult_RouteLightningErrorZ(LDKCResult_RouteLightningErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_RouteLightningErrorZ)); }
-       operator LDKCResult_RouteLightningErrorZ() { LDKCResult_RouteLightningErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_RouteLightningErrorZ)); return res; }
-       LDKCResult_RouteLightningErrorZ* operator &() { return &self; }
-       LDKCResult_RouteLightningErrorZ* operator ->() { return &self; }
-       const LDKCResult_RouteLightningErrorZ* operator &() const { return &self; }
-       const LDKCResult_RouteLightningErrorZ* operator ->() const { return &self; }
+       operator LDKCResult_NonePeerHandleErrorZ() && { LDKCResult_NonePeerHandleErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_NonePeerHandleErrorZ)); return res; }
+       ~CResult_NonePeerHandleErrorZ() { CResult_NonePeerHandleErrorZ_free(self); }
+       CResult_NonePeerHandleErrorZ& operator=(CResult_NonePeerHandleErrorZ&& o) { CResult_NonePeerHandleErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_NonePeerHandleErrorZ)); return *this; }
+       LDKCResult_NonePeerHandleErrorZ* operator &() { return &self; }
+       LDKCResult_NonePeerHandleErrorZ* operator ->() { return &self; }
+       const LDKCResult_NonePeerHandleErrorZ* operator &() const { return &self; }
+       const LDKCResult_NonePeerHandleErrorZ* operator ->() const { return &self; }
 };
 class CResult_NoneLightningErrorZ {
 private:
        LDKCResult_NoneLightningErrorZ self;
 public:
        CResult_NoneLightningErrorZ(const CResult_NoneLightningErrorZ&) = delete;
-       ~CResult_NoneLightningErrorZ() { CResult_NoneLightningErrorZ_free(self); }
        CResult_NoneLightningErrorZ(CResult_NoneLightningErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_NoneLightningErrorZ)); }
        CResult_NoneLightningErrorZ(LDKCResult_NoneLightningErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_NoneLightningErrorZ)); }
-       operator LDKCResult_NoneLightningErrorZ() { LDKCResult_NoneLightningErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_NoneLightningErrorZ)); return res; }
+       operator LDKCResult_NoneLightningErrorZ() && { LDKCResult_NoneLightningErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_NoneLightningErrorZ)); return res; }
+       ~CResult_NoneLightningErrorZ() { CResult_NoneLightningErrorZ_free(self); }
+       CResult_NoneLightningErrorZ& operator=(CResult_NoneLightningErrorZ&& o) { CResult_NoneLightningErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_NoneLightningErrorZ)); return *this; }
        LDKCResult_NoneLightningErrorZ* operator &() { return &self; }
        LDKCResult_NoneLightningErrorZ* operator ->() { return &self; }
        const LDKCResult_NoneLightningErrorZ* operator &() const { return &self; }
@@ -1849,251 +2776,569 @@ private:
        LDKCResult_CVec_SignatureZNoneZ self;
 public:
        CResult_CVec_SignatureZNoneZ(const CResult_CVec_SignatureZNoneZ&) = delete;
-       ~CResult_CVec_SignatureZNoneZ() { CResult_CVec_SignatureZNoneZ_free(self); }
        CResult_CVec_SignatureZNoneZ(CResult_CVec_SignatureZNoneZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_CVec_SignatureZNoneZ)); }
        CResult_CVec_SignatureZNoneZ(LDKCResult_CVec_SignatureZNoneZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_CVec_SignatureZNoneZ)); }
-       operator LDKCResult_CVec_SignatureZNoneZ() { LDKCResult_CVec_SignatureZNoneZ res = self; memset(&self, 0, sizeof(LDKCResult_CVec_SignatureZNoneZ)); return res; }
+       operator LDKCResult_CVec_SignatureZNoneZ() && { LDKCResult_CVec_SignatureZNoneZ res = self; memset(&self, 0, sizeof(LDKCResult_CVec_SignatureZNoneZ)); return res; }
+       ~CResult_CVec_SignatureZNoneZ() { CResult_CVec_SignatureZNoneZ_free(self); }
+       CResult_CVec_SignatureZNoneZ& operator=(CResult_CVec_SignatureZNoneZ&& o) { CResult_CVec_SignatureZNoneZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_CVec_SignatureZNoneZ)); return *this; }
        LDKCResult_CVec_SignatureZNoneZ* operator &() { return &self; }
        LDKCResult_CVec_SignatureZNoneZ* operator ->() { return &self; }
        const LDKCResult_CVec_SignatureZNoneZ* operator &() const { return &self; }
        const LDKCResult_CVec_SignatureZNoneZ* operator ->() const { return &self; }
 };
-class CVec_UpdateFulfillHTLCZ {
-private:
-       LDKCVec_UpdateFulfillHTLCZ self;
-public:
-       CVec_UpdateFulfillHTLCZ(const CVec_UpdateFulfillHTLCZ&) = delete;
-       ~CVec_UpdateFulfillHTLCZ() { CVec_UpdateFulfillHTLCZ_free(self); }
-       CVec_UpdateFulfillHTLCZ(CVec_UpdateFulfillHTLCZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_UpdateFulfillHTLCZ)); }
-       CVec_UpdateFulfillHTLCZ(LDKCVec_UpdateFulfillHTLCZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_UpdateFulfillHTLCZ)); }
-       operator LDKCVec_UpdateFulfillHTLCZ() { LDKCVec_UpdateFulfillHTLCZ res = self; memset(&self, 0, sizeof(LDKCVec_UpdateFulfillHTLCZ)); return res; }
-       LDKCVec_UpdateFulfillHTLCZ* operator &() { return &self; }
-       LDKCVec_UpdateFulfillHTLCZ* operator ->() { return &self; }
-       const LDKCVec_UpdateFulfillHTLCZ* operator &() const { return &self; }
-       const LDKCVec_UpdateFulfillHTLCZ* operator ->() const { return &self; }
-};
-class CResult_SignatureNoneZ {
-private:
-       LDKCResult_SignatureNoneZ self;
-public:
-       CResult_SignatureNoneZ(const CResult_SignatureNoneZ&) = delete;
-       ~CResult_SignatureNoneZ() { CResult_SignatureNoneZ_free(self); }
-       CResult_SignatureNoneZ(CResult_SignatureNoneZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_SignatureNoneZ)); }
-       CResult_SignatureNoneZ(LDKCResult_SignatureNoneZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_SignatureNoneZ)); }
-       operator LDKCResult_SignatureNoneZ() { LDKCResult_SignatureNoneZ res = self; memset(&self, 0, sizeof(LDKCResult_SignatureNoneZ)); return res; }
-       LDKCResult_SignatureNoneZ* operator &() { return &self; }
-       LDKCResult_SignatureNoneZ* operator ->() { return &self; }
-       const LDKCResult_SignatureNoneZ* operator &() const { return &self; }
-       const LDKCResult_SignatureNoneZ* operator ->() const { return &self; }
-};
-class C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ {
-private:
-       LDKC2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ self;
-public:
-       C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ(const C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ&) = delete;
-       ~C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ() { C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ_free(self); }
-       C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ(C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ&& o) : self(o.self) { memset(&o, 0, sizeof(C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ)); }
-       C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ(LDKC2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKC2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ)); }
-       operator LDKC2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ() { LDKC2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ res = self; memset(&self, 0, sizeof(LDKC2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ)); return res; }
-       LDKC2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ* operator &() { return &self; }
-       LDKC2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ* operator ->() { return &self; }
-       const LDKC2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ* operator &() const { return &self; }
-       const LDKC2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ* operator ->() const { return &self; }
-};
-class CVec_ChannelDetailsZ {
-private:
-       LDKCVec_ChannelDetailsZ self;
-public:
-       CVec_ChannelDetailsZ(const CVec_ChannelDetailsZ&) = delete;
-       ~CVec_ChannelDetailsZ() { CVec_ChannelDetailsZ_free(self); }
-       CVec_ChannelDetailsZ(CVec_ChannelDetailsZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_ChannelDetailsZ)); }
-       CVec_ChannelDetailsZ(LDKCVec_ChannelDetailsZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_ChannelDetailsZ)); }
-       operator LDKCVec_ChannelDetailsZ() { LDKCVec_ChannelDetailsZ res = self; memset(&self, 0, sizeof(LDKCVec_ChannelDetailsZ)); return res; }
-       LDKCVec_ChannelDetailsZ* operator &() { return &self; }
-       LDKCVec_ChannelDetailsZ* operator ->() { return &self; }
-       const LDKCVec_ChannelDetailsZ* operator &() const { return &self; }
-       const LDKCVec_ChannelDetailsZ* operator ->() const { return &self; }
-};
-class CVec_MessageSendEventZ {
-private:
-       LDKCVec_MessageSendEventZ self;
-public:
-       CVec_MessageSendEventZ(const CVec_MessageSendEventZ&) = delete;
-       ~CVec_MessageSendEventZ() { CVec_MessageSendEventZ_free(self); }
-       CVec_MessageSendEventZ(CVec_MessageSendEventZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_MessageSendEventZ)); }
-       CVec_MessageSendEventZ(LDKCVec_MessageSendEventZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_MessageSendEventZ)); }
-       operator LDKCVec_MessageSendEventZ() { LDKCVec_MessageSendEventZ res = self; memset(&self, 0, sizeof(LDKCVec_MessageSendEventZ)); return res; }
-       LDKCVec_MessageSendEventZ* operator &() { return &self; }
-       LDKCVec_MessageSendEventZ* operator ->() { return &self; }
-       const LDKCVec_MessageSendEventZ* operator &() const { return &self; }
-       const LDKCVec_MessageSendEventZ* operator ->() const { return &self; }
-};
-class CVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ {
-private:
-       LDKCVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ self;
-public:
-       CVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ(const CVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ&) = delete;
-       ~CVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ() { CVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ_free(self); }
-       CVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ(CVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ)); }
-       CVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ(LDKCVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ)); }
-       operator LDKCVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ() { LDKCVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ res = self; memset(&self, 0, sizeof(LDKCVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ)); return res; }
-       LDKCVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ* operator &() { return &self; }
-       LDKCVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ* operator ->() { return &self; }
-       const LDKCVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ* operator &() const { return &self; }
-       const LDKCVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ* operator ->() const { return &self; }
+class CResult_RoutingFeesDecodeErrorZ {
+private:
+       LDKCResult_RoutingFeesDecodeErrorZ self;
+public:
+       CResult_RoutingFeesDecodeErrorZ(const CResult_RoutingFeesDecodeErrorZ&) = delete;
+       CResult_RoutingFeesDecodeErrorZ(CResult_RoutingFeesDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_RoutingFeesDecodeErrorZ)); }
+       CResult_RoutingFeesDecodeErrorZ(LDKCResult_RoutingFeesDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_RoutingFeesDecodeErrorZ)); }
+       operator LDKCResult_RoutingFeesDecodeErrorZ() && { LDKCResult_RoutingFeesDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_RoutingFeesDecodeErrorZ)); return res; }
+       ~CResult_RoutingFeesDecodeErrorZ() { CResult_RoutingFeesDecodeErrorZ_free(self); }
+       CResult_RoutingFeesDecodeErrorZ& operator=(CResult_RoutingFeesDecodeErrorZ&& o) { CResult_RoutingFeesDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_RoutingFeesDecodeErrorZ)); return *this; }
+       LDKCResult_RoutingFeesDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_RoutingFeesDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_RoutingFeesDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_RoutingFeesDecodeErrorZ* operator ->() const { return &self; }
+};
+class CResult_QueryShortChannelIdsDecodeErrorZ {
+private:
+       LDKCResult_QueryShortChannelIdsDecodeErrorZ self;
+public:
+       CResult_QueryShortChannelIdsDecodeErrorZ(const CResult_QueryShortChannelIdsDecodeErrorZ&) = delete;
+       CResult_QueryShortChannelIdsDecodeErrorZ(CResult_QueryShortChannelIdsDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_QueryShortChannelIdsDecodeErrorZ)); }
+       CResult_QueryShortChannelIdsDecodeErrorZ(LDKCResult_QueryShortChannelIdsDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_QueryShortChannelIdsDecodeErrorZ)); }
+       operator LDKCResult_QueryShortChannelIdsDecodeErrorZ() && { LDKCResult_QueryShortChannelIdsDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_QueryShortChannelIdsDecodeErrorZ)); return res; }
+       ~CResult_QueryShortChannelIdsDecodeErrorZ() { CResult_QueryShortChannelIdsDecodeErrorZ_free(self); }
+       CResult_QueryShortChannelIdsDecodeErrorZ& operator=(CResult_QueryShortChannelIdsDecodeErrorZ&& o) { CResult_QueryShortChannelIdsDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_QueryShortChannelIdsDecodeErrorZ)); return *this; }
+       LDKCResult_QueryShortChannelIdsDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_QueryShortChannelIdsDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_QueryShortChannelIdsDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_QueryShortChannelIdsDecodeErrorZ* operator ->() const { return &self; }
+};
+class CResult_UpdateAddHTLCDecodeErrorZ {
+private:
+       LDKCResult_UpdateAddHTLCDecodeErrorZ self;
+public:
+       CResult_UpdateAddHTLCDecodeErrorZ(const CResult_UpdateAddHTLCDecodeErrorZ&) = delete;
+       CResult_UpdateAddHTLCDecodeErrorZ(CResult_UpdateAddHTLCDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_UpdateAddHTLCDecodeErrorZ)); }
+       CResult_UpdateAddHTLCDecodeErrorZ(LDKCResult_UpdateAddHTLCDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_UpdateAddHTLCDecodeErrorZ)); }
+       operator LDKCResult_UpdateAddHTLCDecodeErrorZ() && { LDKCResult_UpdateAddHTLCDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_UpdateAddHTLCDecodeErrorZ)); return res; }
+       ~CResult_UpdateAddHTLCDecodeErrorZ() { CResult_UpdateAddHTLCDecodeErrorZ_free(self); }
+       CResult_UpdateAddHTLCDecodeErrorZ& operator=(CResult_UpdateAddHTLCDecodeErrorZ&& o) { CResult_UpdateAddHTLCDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_UpdateAddHTLCDecodeErrorZ)); return *this; }
+       LDKCResult_UpdateAddHTLCDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_UpdateAddHTLCDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_UpdateAddHTLCDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_UpdateAddHTLCDecodeErrorZ* operator ->() const { return &self; }
+};
+class CResult_CounterpartyChannelTransactionParametersDecodeErrorZ {
+private:
+       LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZ self;
+public:
+       CResult_CounterpartyChannelTransactionParametersDecodeErrorZ(const CResult_CounterpartyChannelTransactionParametersDecodeErrorZ&) = delete;
+       CResult_CounterpartyChannelTransactionParametersDecodeErrorZ(CResult_CounterpartyChannelTransactionParametersDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_CounterpartyChannelTransactionParametersDecodeErrorZ)); }
+       CResult_CounterpartyChannelTransactionParametersDecodeErrorZ(LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZ)); }
+       operator LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZ() && { LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZ)); return res; }
+       ~CResult_CounterpartyChannelTransactionParametersDecodeErrorZ() { CResult_CounterpartyChannelTransactionParametersDecodeErrorZ_free(self); }
+       CResult_CounterpartyChannelTransactionParametersDecodeErrorZ& operator=(CResult_CounterpartyChannelTransactionParametersDecodeErrorZ&& o) { CResult_CounterpartyChannelTransactionParametersDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_CounterpartyChannelTransactionParametersDecodeErrorZ)); return *this; }
+       LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZ* operator ->() const { return &self; }
 };
 class CResult_NoneAPIErrorZ {
 private:
        LDKCResult_NoneAPIErrorZ self;
 public:
        CResult_NoneAPIErrorZ(const CResult_NoneAPIErrorZ&) = delete;
-       ~CResult_NoneAPIErrorZ() { CResult_NoneAPIErrorZ_free(self); }
        CResult_NoneAPIErrorZ(CResult_NoneAPIErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_NoneAPIErrorZ)); }
        CResult_NoneAPIErrorZ(LDKCResult_NoneAPIErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_NoneAPIErrorZ)); }
-       operator LDKCResult_NoneAPIErrorZ() { LDKCResult_NoneAPIErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_NoneAPIErrorZ)); return res; }
+       operator LDKCResult_NoneAPIErrorZ() && { LDKCResult_NoneAPIErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_NoneAPIErrorZ)); return res; }
+       ~CResult_NoneAPIErrorZ() { CResult_NoneAPIErrorZ_free(self); }
+       CResult_NoneAPIErrorZ& operator=(CResult_NoneAPIErrorZ&& o) { CResult_NoneAPIErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_NoneAPIErrorZ)); return *this; }
        LDKCResult_NoneAPIErrorZ* operator &() { return &self; }
        LDKCResult_NoneAPIErrorZ* operator ->() { return &self; }
        const LDKCResult_NoneAPIErrorZ* operator &() const { return &self; }
        const LDKCResult_NoneAPIErrorZ* operator ->() const { return &self; }
 };
-class C2Tuple_OutPointScriptZ {
-private:
-       LDKC2Tuple_OutPointScriptZ self;
-public:
-       C2Tuple_OutPointScriptZ(const C2Tuple_OutPointScriptZ&) = delete;
-       ~C2Tuple_OutPointScriptZ() { C2Tuple_OutPointScriptZ_free(self); }
-       C2Tuple_OutPointScriptZ(C2Tuple_OutPointScriptZ&& o) : self(o.self) { memset(&o, 0, sizeof(C2Tuple_OutPointScriptZ)); }
-       C2Tuple_OutPointScriptZ(LDKC2Tuple_OutPointScriptZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKC2Tuple_OutPointScriptZ)); }
-       operator LDKC2Tuple_OutPointScriptZ() { LDKC2Tuple_OutPointScriptZ res = self; memset(&self, 0, sizeof(LDKC2Tuple_OutPointScriptZ)); return res; }
-       LDKC2Tuple_OutPointScriptZ* operator &() { return &self; }
-       LDKC2Tuple_OutPointScriptZ* operator ->() { return &self; }
-       const LDKC2Tuple_OutPointScriptZ* operator &() const { return &self; }
-       const LDKC2Tuple_OutPointScriptZ* operator ->() const { return &self; }
-};
 class CVec_NetAddressZ {
 private:
        LDKCVec_NetAddressZ self;
 public:
        CVec_NetAddressZ(const CVec_NetAddressZ&) = delete;
-       ~CVec_NetAddressZ() { CVec_NetAddressZ_free(self); }
        CVec_NetAddressZ(CVec_NetAddressZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_NetAddressZ)); }
        CVec_NetAddressZ(LDKCVec_NetAddressZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_NetAddressZ)); }
-       operator LDKCVec_NetAddressZ() { LDKCVec_NetAddressZ res = self; memset(&self, 0, sizeof(LDKCVec_NetAddressZ)); return res; }
+       operator LDKCVec_NetAddressZ() && { LDKCVec_NetAddressZ res = self; memset(&self, 0, sizeof(LDKCVec_NetAddressZ)); return res; }
+       ~CVec_NetAddressZ() { CVec_NetAddressZ_free(self); }
+       CVec_NetAddressZ& operator=(CVec_NetAddressZ&& o) { CVec_NetAddressZ_free(self); self = o.self; memset(&o, 0, sizeof(CVec_NetAddressZ)); return *this; }
        LDKCVec_NetAddressZ* operator &() { return &self; }
        LDKCVec_NetAddressZ* operator ->() { return &self; }
        const LDKCVec_NetAddressZ* operator &() const { return &self; }
        const LDKCVec_NetAddressZ* operator ->() const { return &self; }
 };
-class C2Tuple_usizeTransactionZ {
+class CVec_PublicKeyZ {
 private:
-       LDKC2Tuple_usizeTransactionZ self;
+       LDKCVec_PublicKeyZ self;
 public:
-       C2Tuple_usizeTransactionZ(const C2Tuple_usizeTransactionZ&) = delete;
-       ~C2Tuple_usizeTransactionZ() { C2Tuple_usizeTransactionZ_free(self); }
-       C2Tuple_usizeTransactionZ(C2Tuple_usizeTransactionZ&& o) : self(o.self) { memset(&o, 0, sizeof(C2Tuple_usizeTransactionZ)); }
-       C2Tuple_usizeTransactionZ(LDKC2Tuple_usizeTransactionZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKC2Tuple_usizeTransactionZ)); }
-       operator LDKC2Tuple_usizeTransactionZ() { LDKC2Tuple_usizeTransactionZ res = self; memset(&self, 0, sizeof(LDKC2Tuple_usizeTransactionZ)); return res; }
-       LDKC2Tuple_usizeTransactionZ* operator &() { return &self; }
-       LDKC2Tuple_usizeTransactionZ* operator ->() { return &self; }
-       const LDKC2Tuple_usizeTransactionZ* operator &() const { return &self; }
-       const LDKC2Tuple_usizeTransactionZ* operator ->() const { return &self; }
+       CVec_PublicKeyZ(const CVec_PublicKeyZ&) = delete;
+       CVec_PublicKeyZ(CVec_PublicKeyZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_PublicKeyZ)); }
+       CVec_PublicKeyZ(LDKCVec_PublicKeyZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_PublicKeyZ)); }
+       operator LDKCVec_PublicKeyZ() && { LDKCVec_PublicKeyZ res = self; memset(&self, 0, sizeof(LDKCVec_PublicKeyZ)); return res; }
+       ~CVec_PublicKeyZ() { CVec_PublicKeyZ_free(self); }
+       CVec_PublicKeyZ& operator=(CVec_PublicKeyZ&& o) { CVec_PublicKeyZ_free(self); self = o.self; memset(&o, 0, sizeof(CVec_PublicKeyZ)); return *this; }
+       LDKCVec_PublicKeyZ* operator &() { return &self; }
+       LDKCVec_PublicKeyZ* operator ->() { return &self; }
+       const LDKCVec_PublicKeyZ* operator &() const { return &self; }
+       const LDKCVec_PublicKeyZ* operator ->() const { return &self; }
 };
 class CVec_C2Tuple_usizeTransactionZZ {
 private:
        LDKCVec_C2Tuple_usizeTransactionZZ self;
 public:
        CVec_C2Tuple_usizeTransactionZZ(const CVec_C2Tuple_usizeTransactionZZ&) = delete;
-       ~CVec_C2Tuple_usizeTransactionZZ() { CVec_C2Tuple_usizeTransactionZZ_free(self); }
        CVec_C2Tuple_usizeTransactionZZ(CVec_C2Tuple_usizeTransactionZZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_C2Tuple_usizeTransactionZZ)); }
        CVec_C2Tuple_usizeTransactionZZ(LDKCVec_C2Tuple_usizeTransactionZZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_C2Tuple_usizeTransactionZZ)); }
-       operator LDKCVec_C2Tuple_usizeTransactionZZ() { LDKCVec_C2Tuple_usizeTransactionZZ res = self; memset(&self, 0, sizeof(LDKCVec_C2Tuple_usizeTransactionZZ)); return res; }
+       operator LDKCVec_C2Tuple_usizeTransactionZZ() && { LDKCVec_C2Tuple_usizeTransactionZZ res = self; memset(&self, 0, sizeof(LDKCVec_C2Tuple_usizeTransactionZZ)); return res; }
+       ~CVec_C2Tuple_usizeTransactionZZ() { CVec_C2Tuple_usizeTransactionZZ_free(self); }
+       CVec_C2Tuple_usizeTransactionZZ& operator=(CVec_C2Tuple_usizeTransactionZZ&& o) { CVec_C2Tuple_usizeTransactionZZ_free(self); self = o.self; memset(&o, 0, sizeof(CVec_C2Tuple_usizeTransactionZZ)); return *this; }
        LDKCVec_C2Tuple_usizeTransactionZZ* operator &() { return &self; }
        LDKCVec_C2Tuple_usizeTransactionZZ* operator ->() { return &self; }
        const LDKCVec_C2Tuple_usizeTransactionZZ* operator &() const { return &self; }
        const LDKCVec_C2Tuple_usizeTransactionZZ* operator ->() const { return &self; }
 };
-class CVec_TransactionZ {
+class CResult_DirectionalChannelInfoDecodeErrorZ {
 private:
-       LDKCVec_TransactionZ self;
+       LDKCResult_DirectionalChannelInfoDecodeErrorZ self;
 public:
-       CVec_TransactionZ(const CVec_TransactionZ&) = delete;
-       ~CVec_TransactionZ() { CVec_TransactionZ_free(self); }
-       CVec_TransactionZ(CVec_TransactionZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_TransactionZ)); }
-       CVec_TransactionZ(LDKCVec_TransactionZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_TransactionZ)); }
-       operator LDKCVec_TransactionZ() { LDKCVec_TransactionZ res = self; memset(&self, 0, sizeof(LDKCVec_TransactionZ)); return res; }
-       LDKCVec_TransactionZ* operator &() { return &self; }
-       LDKCVec_TransactionZ* operator ->() { return &self; }
-       const LDKCVec_TransactionZ* operator &() const { return &self; }
-       const LDKCVec_TransactionZ* operator ->() const { return &self; }
+       CResult_DirectionalChannelInfoDecodeErrorZ(const CResult_DirectionalChannelInfoDecodeErrorZ&) = delete;
+       CResult_DirectionalChannelInfoDecodeErrorZ(CResult_DirectionalChannelInfoDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_DirectionalChannelInfoDecodeErrorZ)); }
+       CResult_DirectionalChannelInfoDecodeErrorZ(LDKCResult_DirectionalChannelInfoDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_DirectionalChannelInfoDecodeErrorZ)); }
+       operator LDKCResult_DirectionalChannelInfoDecodeErrorZ() && { LDKCResult_DirectionalChannelInfoDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_DirectionalChannelInfoDecodeErrorZ)); return res; }
+       ~CResult_DirectionalChannelInfoDecodeErrorZ() { CResult_DirectionalChannelInfoDecodeErrorZ_free(self); }
+       CResult_DirectionalChannelInfoDecodeErrorZ& operator=(CResult_DirectionalChannelInfoDecodeErrorZ&& o) { CResult_DirectionalChannelInfoDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_DirectionalChannelInfoDecodeErrorZ)); return *this; }
+       LDKCResult_DirectionalChannelInfoDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_DirectionalChannelInfoDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_DirectionalChannelInfoDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_DirectionalChannelInfoDecodeErrorZ* operator ->() const { return &self; }
 };
-class CVec_ChannelMonitorZ {
+class C2Tuple_u32TxOutZ {
 private:
-       LDKCVec_ChannelMonitorZ self;
+       LDKC2Tuple_u32TxOutZ self;
 public:
-       CVec_ChannelMonitorZ(const CVec_ChannelMonitorZ&) = delete;
-       ~CVec_ChannelMonitorZ() { CVec_ChannelMonitorZ_free(self); }
-       CVec_ChannelMonitorZ(CVec_ChannelMonitorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_ChannelMonitorZ)); }
-       CVec_ChannelMonitorZ(LDKCVec_ChannelMonitorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_ChannelMonitorZ)); }
-       operator LDKCVec_ChannelMonitorZ() { LDKCVec_ChannelMonitorZ res = self; memset(&self, 0, sizeof(LDKCVec_ChannelMonitorZ)); return res; }
-       LDKCVec_ChannelMonitorZ* operator &() { return &self; }
-       LDKCVec_ChannelMonitorZ* operator ->() { return &self; }
-       const LDKCVec_ChannelMonitorZ* operator &() const { return &self; }
-       const LDKCVec_ChannelMonitorZ* operator ->() const { return &self; }
+       C2Tuple_u32TxOutZ(const C2Tuple_u32TxOutZ&) = delete;
+       C2Tuple_u32TxOutZ(C2Tuple_u32TxOutZ&& o) : self(o.self) { memset(&o, 0, sizeof(C2Tuple_u32TxOutZ)); }
+       C2Tuple_u32TxOutZ(LDKC2Tuple_u32TxOutZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKC2Tuple_u32TxOutZ)); }
+       operator LDKC2Tuple_u32TxOutZ() && { LDKC2Tuple_u32TxOutZ res = self; memset(&self, 0, sizeof(LDKC2Tuple_u32TxOutZ)); return res; }
+       ~C2Tuple_u32TxOutZ() { C2Tuple_u32TxOutZ_free(self); }
+       C2Tuple_u32TxOutZ& operator=(C2Tuple_u32TxOutZ&& o) { C2Tuple_u32TxOutZ_free(self); self = o.self; memset(&o, 0, sizeof(C2Tuple_u32TxOutZ)); return *this; }
+       LDKC2Tuple_u32TxOutZ* operator &() { return &self; }
+       LDKC2Tuple_u32TxOutZ* operator ->() { return &self; }
+       const LDKC2Tuple_u32TxOutZ* operator &() const { return &self; }
+       const LDKC2Tuple_u32TxOutZ* operator ->() const { return &self; }
+};
+class CResult_UpdateFailHTLCDecodeErrorZ {
+private:
+       LDKCResult_UpdateFailHTLCDecodeErrorZ self;
+public:
+       CResult_UpdateFailHTLCDecodeErrorZ(const CResult_UpdateFailHTLCDecodeErrorZ&) = delete;
+       CResult_UpdateFailHTLCDecodeErrorZ(CResult_UpdateFailHTLCDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_UpdateFailHTLCDecodeErrorZ)); }
+       CResult_UpdateFailHTLCDecodeErrorZ(LDKCResult_UpdateFailHTLCDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_UpdateFailHTLCDecodeErrorZ)); }
+       operator LDKCResult_UpdateFailHTLCDecodeErrorZ() && { LDKCResult_UpdateFailHTLCDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_UpdateFailHTLCDecodeErrorZ)); return res; }
+       ~CResult_UpdateFailHTLCDecodeErrorZ() { CResult_UpdateFailHTLCDecodeErrorZ_free(self); }
+       CResult_UpdateFailHTLCDecodeErrorZ& operator=(CResult_UpdateFailHTLCDecodeErrorZ&& o) { CResult_UpdateFailHTLCDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_UpdateFailHTLCDecodeErrorZ)); return *this; }
+       LDKCResult_UpdateFailHTLCDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_UpdateFailHTLCDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_UpdateFailHTLCDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_UpdateFailHTLCDecodeErrorZ* operator ->() const { return &self; }
+};
+class CResult_ChannelConfigDecodeErrorZ {
+private:
+       LDKCResult_ChannelConfigDecodeErrorZ self;
+public:
+       CResult_ChannelConfigDecodeErrorZ(const CResult_ChannelConfigDecodeErrorZ&) = delete;
+       CResult_ChannelConfigDecodeErrorZ(CResult_ChannelConfigDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_ChannelConfigDecodeErrorZ)); }
+       CResult_ChannelConfigDecodeErrorZ(LDKCResult_ChannelConfigDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_ChannelConfigDecodeErrorZ)); }
+       operator LDKCResult_ChannelConfigDecodeErrorZ() && { LDKCResult_ChannelConfigDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_ChannelConfigDecodeErrorZ)); return res; }
+       ~CResult_ChannelConfigDecodeErrorZ() { CResult_ChannelConfigDecodeErrorZ_free(self); }
+       CResult_ChannelConfigDecodeErrorZ& operator=(CResult_ChannelConfigDecodeErrorZ&& o) { CResult_ChannelConfigDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_ChannelConfigDecodeErrorZ)); return *this; }
+       LDKCResult_ChannelConfigDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_ChannelConfigDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_ChannelConfigDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_ChannelConfigDecodeErrorZ* operator ->() const { return &self; }
+};
+class CResult_RevokeAndACKDecodeErrorZ {
+private:
+       LDKCResult_RevokeAndACKDecodeErrorZ self;
+public:
+       CResult_RevokeAndACKDecodeErrorZ(const CResult_RevokeAndACKDecodeErrorZ&) = delete;
+       CResult_RevokeAndACKDecodeErrorZ(CResult_RevokeAndACKDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_RevokeAndACKDecodeErrorZ)); }
+       CResult_RevokeAndACKDecodeErrorZ(LDKCResult_RevokeAndACKDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_RevokeAndACKDecodeErrorZ)); }
+       operator LDKCResult_RevokeAndACKDecodeErrorZ() && { LDKCResult_RevokeAndACKDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_RevokeAndACKDecodeErrorZ)); return res; }
+       ~CResult_RevokeAndACKDecodeErrorZ() { CResult_RevokeAndACKDecodeErrorZ_free(self); }
+       CResult_RevokeAndACKDecodeErrorZ& operator=(CResult_RevokeAndACKDecodeErrorZ&& o) { CResult_RevokeAndACKDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_RevokeAndACKDecodeErrorZ)); return *this; }
+       LDKCResult_RevokeAndACKDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_RevokeAndACKDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_RevokeAndACKDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_RevokeAndACKDecodeErrorZ* operator ->() const { return &self; }
+};
+class CResult_SpendableOutputDescriptorDecodeErrorZ {
+private:
+       LDKCResult_SpendableOutputDescriptorDecodeErrorZ self;
+public:
+       CResult_SpendableOutputDescriptorDecodeErrorZ(const CResult_SpendableOutputDescriptorDecodeErrorZ&) = delete;
+       CResult_SpendableOutputDescriptorDecodeErrorZ(CResult_SpendableOutputDescriptorDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_SpendableOutputDescriptorDecodeErrorZ)); }
+       CResult_SpendableOutputDescriptorDecodeErrorZ(LDKCResult_SpendableOutputDescriptorDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_SpendableOutputDescriptorDecodeErrorZ)); }
+       operator LDKCResult_SpendableOutputDescriptorDecodeErrorZ() && { LDKCResult_SpendableOutputDescriptorDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_SpendableOutputDescriptorDecodeErrorZ)); return res; }
+       ~CResult_SpendableOutputDescriptorDecodeErrorZ() { CResult_SpendableOutputDescriptorDecodeErrorZ_free(self); }
+       CResult_SpendableOutputDescriptorDecodeErrorZ& operator=(CResult_SpendableOutputDescriptorDecodeErrorZ&& o) { CResult_SpendableOutputDescriptorDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_SpendableOutputDescriptorDecodeErrorZ)); return *this; }
+       LDKCResult_SpendableOutputDescriptorDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_SpendableOutputDescriptorDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_SpendableOutputDescriptorDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_SpendableOutputDescriptorDecodeErrorZ* operator ->() const { return &self; }
+};
+class CResult_UnsignedChannelUpdateDecodeErrorZ {
+private:
+       LDKCResult_UnsignedChannelUpdateDecodeErrorZ self;
+public:
+       CResult_UnsignedChannelUpdateDecodeErrorZ(const CResult_UnsignedChannelUpdateDecodeErrorZ&) = delete;
+       CResult_UnsignedChannelUpdateDecodeErrorZ(CResult_UnsignedChannelUpdateDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_UnsignedChannelUpdateDecodeErrorZ)); }
+       CResult_UnsignedChannelUpdateDecodeErrorZ(LDKCResult_UnsignedChannelUpdateDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_UnsignedChannelUpdateDecodeErrorZ)); }
+       operator LDKCResult_UnsignedChannelUpdateDecodeErrorZ() && { LDKCResult_UnsignedChannelUpdateDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_UnsignedChannelUpdateDecodeErrorZ)); return res; }
+       ~CResult_UnsignedChannelUpdateDecodeErrorZ() { CResult_UnsignedChannelUpdateDecodeErrorZ_free(self); }
+       CResult_UnsignedChannelUpdateDecodeErrorZ& operator=(CResult_UnsignedChannelUpdateDecodeErrorZ&& o) { CResult_UnsignedChannelUpdateDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_UnsignedChannelUpdateDecodeErrorZ)); return *this; }
+       LDKCResult_UnsignedChannelUpdateDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_UnsignedChannelUpdateDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_UnsignedChannelUpdateDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_UnsignedChannelUpdateDecodeErrorZ* operator ->() const { return &self; }
+};
+class CResult_ShutdownDecodeErrorZ {
+private:
+       LDKCResult_ShutdownDecodeErrorZ self;
+public:
+       CResult_ShutdownDecodeErrorZ(const CResult_ShutdownDecodeErrorZ&) = delete;
+       CResult_ShutdownDecodeErrorZ(CResult_ShutdownDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_ShutdownDecodeErrorZ)); }
+       CResult_ShutdownDecodeErrorZ(LDKCResult_ShutdownDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_ShutdownDecodeErrorZ)); }
+       operator LDKCResult_ShutdownDecodeErrorZ() && { LDKCResult_ShutdownDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_ShutdownDecodeErrorZ)); return res; }
+       ~CResult_ShutdownDecodeErrorZ() { CResult_ShutdownDecodeErrorZ_free(self); }
+       CResult_ShutdownDecodeErrorZ& operator=(CResult_ShutdownDecodeErrorZ&& o) { CResult_ShutdownDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_ShutdownDecodeErrorZ)); return *this; }
+       LDKCResult_ShutdownDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_ShutdownDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_ShutdownDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_ShutdownDecodeErrorZ* operator ->() const { return &self; }
+};
+class CVec_EventZ {
+private:
+       LDKCVec_EventZ self;
+public:
+       CVec_EventZ(const CVec_EventZ&) = delete;
+       CVec_EventZ(CVec_EventZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_EventZ)); }
+       CVec_EventZ(LDKCVec_EventZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_EventZ)); }
+       operator LDKCVec_EventZ() && { LDKCVec_EventZ res = self; memset(&self, 0, sizeof(LDKCVec_EventZ)); return res; }
+       ~CVec_EventZ() { CVec_EventZ_free(self); }
+       CVec_EventZ& operator=(CVec_EventZ&& o) { CVec_EventZ_free(self); self = o.self; memset(&o, 0, sizeof(CVec_EventZ)); return *this; }
+       LDKCVec_EventZ* operator &() { return &self; }
+       LDKCVec_EventZ* operator ->() { return &self; }
+       const LDKCVec_EventZ* operator &() const { return &self; }
+       const LDKCVec_EventZ* operator ->() const { return &self; }
+};
+class CVec_MonitorEventZ {
+private:
+       LDKCVec_MonitorEventZ self;
+public:
+       CVec_MonitorEventZ(const CVec_MonitorEventZ&) = delete;
+       CVec_MonitorEventZ(CVec_MonitorEventZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_MonitorEventZ)); }
+       CVec_MonitorEventZ(LDKCVec_MonitorEventZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_MonitorEventZ)); }
+       operator LDKCVec_MonitorEventZ() && { LDKCVec_MonitorEventZ res = self; memset(&self, 0, sizeof(LDKCVec_MonitorEventZ)); return res; }
+       ~CVec_MonitorEventZ() { CVec_MonitorEventZ_free(self); }
+       CVec_MonitorEventZ& operator=(CVec_MonitorEventZ&& o) { CVec_MonitorEventZ_free(self); self = o.self; memset(&o, 0, sizeof(CVec_MonitorEventZ)); return *this; }
+       LDKCVec_MonitorEventZ* operator &() { return &self; }
+       LDKCVec_MonitorEventZ* operator ->() { return &self; }
+       const LDKCVec_MonitorEventZ* operator &() const { return &self; }
+       const LDKCVec_MonitorEventZ* operator ->() const { return &self; }
+};
+class CResult_NoneChannelMonitorUpdateErrZ {
+private:
+       LDKCResult_NoneChannelMonitorUpdateErrZ self;
+public:
+       CResult_NoneChannelMonitorUpdateErrZ(const CResult_NoneChannelMonitorUpdateErrZ&) = delete;
+       CResult_NoneChannelMonitorUpdateErrZ(CResult_NoneChannelMonitorUpdateErrZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_NoneChannelMonitorUpdateErrZ)); }
+       CResult_NoneChannelMonitorUpdateErrZ(LDKCResult_NoneChannelMonitorUpdateErrZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_NoneChannelMonitorUpdateErrZ)); }
+       operator LDKCResult_NoneChannelMonitorUpdateErrZ() && { LDKCResult_NoneChannelMonitorUpdateErrZ res = self; memset(&self, 0, sizeof(LDKCResult_NoneChannelMonitorUpdateErrZ)); return res; }
+       ~CResult_NoneChannelMonitorUpdateErrZ() { CResult_NoneChannelMonitorUpdateErrZ_free(self); }
+       CResult_NoneChannelMonitorUpdateErrZ& operator=(CResult_NoneChannelMonitorUpdateErrZ&& o) { CResult_NoneChannelMonitorUpdateErrZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_NoneChannelMonitorUpdateErrZ)); return *this; }
+       LDKCResult_NoneChannelMonitorUpdateErrZ* operator &() { return &self; }
+       LDKCResult_NoneChannelMonitorUpdateErrZ* operator ->() { return &self; }
+       const LDKCResult_NoneChannelMonitorUpdateErrZ* operator &() const { return &self; }
+       const LDKCResult_NoneChannelMonitorUpdateErrZ* operator ->() const { return &self; }
+};
+class CResult_PublicKeyErrorZ {
+private:
+       LDKCResult_PublicKeyErrorZ self;
+public:
+       CResult_PublicKeyErrorZ(const CResult_PublicKeyErrorZ&) = delete;
+       CResult_PublicKeyErrorZ(CResult_PublicKeyErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_PublicKeyErrorZ)); }
+       CResult_PublicKeyErrorZ(LDKCResult_PublicKeyErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_PublicKeyErrorZ)); }
+       operator LDKCResult_PublicKeyErrorZ() && { LDKCResult_PublicKeyErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_PublicKeyErrorZ)); return res; }
+       ~CResult_PublicKeyErrorZ() { CResult_PublicKeyErrorZ_free(self); }
+       CResult_PublicKeyErrorZ& operator=(CResult_PublicKeyErrorZ&& o) { CResult_PublicKeyErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_PublicKeyErrorZ)); return *this; }
+       LDKCResult_PublicKeyErrorZ* operator &() { return &self; }
+       LDKCResult_PublicKeyErrorZ* operator ->() { return &self; }
+       const LDKCResult_PublicKeyErrorZ* operator &() const { return &self; }
+       const LDKCResult_PublicKeyErrorZ* operator ->() const { return &self; }
+};
+class C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ {
+private:
+       LDKC3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ self;
+public:
+       C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ(const C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ&) = delete;
+       C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ(C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ&& o) : self(o.self) { memset(&o, 0, sizeof(C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ)); }
+       C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ(LDKC3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKC3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ)); }
+       operator LDKC3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ() && { LDKC3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ res = self; memset(&self, 0, sizeof(LDKC3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ)); return res; }
+       ~C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ() { C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ_free(self); }
+       C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ& operator=(C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ&& o) { C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ_free(self); self = o.self; memset(&o, 0, sizeof(C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ)); return *this; }
+       LDKC3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ* operator &() { return &self; }
+       LDKC3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ* operator ->() { return &self; }
+       const LDKC3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ* operator &() const { return &self; }
+       const LDKC3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ* operator ->() const { return &self; }
+};
+class CResult_boolPeerHandleErrorZ {
+private:
+       LDKCResult_boolPeerHandleErrorZ self;
+public:
+       CResult_boolPeerHandleErrorZ(const CResult_boolPeerHandleErrorZ&) = delete;
+       CResult_boolPeerHandleErrorZ(CResult_boolPeerHandleErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_boolPeerHandleErrorZ)); }
+       CResult_boolPeerHandleErrorZ(LDKCResult_boolPeerHandleErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_boolPeerHandleErrorZ)); }
+       operator LDKCResult_boolPeerHandleErrorZ() && { LDKCResult_boolPeerHandleErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_boolPeerHandleErrorZ)); return res; }
+       ~CResult_boolPeerHandleErrorZ() { CResult_boolPeerHandleErrorZ_free(self); }
+       CResult_boolPeerHandleErrorZ& operator=(CResult_boolPeerHandleErrorZ&& o) { CResult_boolPeerHandleErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_boolPeerHandleErrorZ)); return *this; }
+       LDKCResult_boolPeerHandleErrorZ* operator &() { return &self; }
+       LDKCResult_boolPeerHandleErrorZ* operator ->() { return &self; }
+       const LDKCResult_boolPeerHandleErrorZ* operator &() const { return &self; }
+       const LDKCResult_boolPeerHandleErrorZ* operator ->() const { return &self; }
+};
+class CResult_ChannelUpdateDecodeErrorZ {
+private:
+       LDKCResult_ChannelUpdateDecodeErrorZ self;
+public:
+       CResult_ChannelUpdateDecodeErrorZ(const CResult_ChannelUpdateDecodeErrorZ&) = delete;
+       CResult_ChannelUpdateDecodeErrorZ(CResult_ChannelUpdateDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_ChannelUpdateDecodeErrorZ)); }
+       CResult_ChannelUpdateDecodeErrorZ(LDKCResult_ChannelUpdateDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_ChannelUpdateDecodeErrorZ)); }
+       operator LDKCResult_ChannelUpdateDecodeErrorZ() && { LDKCResult_ChannelUpdateDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_ChannelUpdateDecodeErrorZ)); return res; }
+       ~CResult_ChannelUpdateDecodeErrorZ() { CResult_ChannelUpdateDecodeErrorZ_free(self); }
+       CResult_ChannelUpdateDecodeErrorZ& operator=(CResult_ChannelUpdateDecodeErrorZ&& o) { CResult_ChannelUpdateDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_ChannelUpdateDecodeErrorZ)); return *this; }
+       LDKCResult_ChannelUpdateDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_ChannelUpdateDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_ChannelUpdateDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_ChannelUpdateDecodeErrorZ* operator ->() const { return &self; }
+};
+class CVec_APIErrorZ {
+private:
+       LDKCVec_APIErrorZ self;
+public:
+       CVec_APIErrorZ(const CVec_APIErrorZ&) = delete;
+       CVec_APIErrorZ(CVec_APIErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_APIErrorZ)); }
+       CVec_APIErrorZ(LDKCVec_APIErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_APIErrorZ)); }
+       operator LDKCVec_APIErrorZ() && { LDKCVec_APIErrorZ res = self; memset(&self, 0, sizeof(LDKCVec_APIErrorZ)); return res; }
+       ~CVec_APIErrorZ() { CVec_APIErrorZ_free(self); }
+       CVec_APIErrorZ& operator=(CVec_APIErrorZ&& o) { CVec_APIErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CVec_APIErrorZ)); return *this; }
+       LDKCVec_APIErrorZ* operator &() { return &self; }
+       LDKCVec_APIErrorZ* operator ->() { return &self; }
+       const LDKCVec_APIErrorZ* operator &() const { return &self; }
+       const LDKCVec_APIErrorZ* operator ->() const { return &self; }
+};
+class CVec_UpdateFulfillHTLCZ {
+private:
+       LDKCVec_UpdateFulfillHTLCZ self;
+public:
+       CVec_UpdateFulfillHTLCZ(const CVec_UpdateFulfillHTLCZ&) = delete;
+       CVec_UpdateFulfillHTLCZ(CVec_UpdateFulfillHTLCZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_UpdateFulfillHTLCZ)); }
+       CVec_UpdateFulfillHTLCZ(LDKCVec_UpdateFulfillHTLCZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_UpdateFulfillHTLCZ)); }
+       operator LDKCVec_UpdateFulfillHTLCZ() && { LDKCVec_UpdateFulfillHTLCZ res = self; memset(&self, 0, sizeof(LDKCVec_UpdateFulfillHTLCZ)); return res; }
+       ~CVec_UpdateFulfillHTLCZ() { CVec_UpdateFulfillHTLCZ_free(self); }
+       CVec_UpdateFulfillHTLCZ& operator=(CVec_UpdateFulfillHTLCZ&& o) { CVec_UpdateFulfillHTLCZ_free(self); self = o.self; memset(&o, 0, sizeof(CVec_UpdateFulfillHTLCZ)); return *this; }
+       LDKCVec_UpdateFulfillHTLCZ* operator &() { return &self; }
+       LDKCVec_UpdateFulfillHTLCZ* operator ->() { return &self; }
+       const LDKCVec_UpdateFulfillHTLCZ* operator &() const { return &self; }
+       const LDKCVec_UpdateFulfillHTLCZ* operator ->() const { return &self; }
+};
+class CResult_AnnouncementSignaturesDecodeErrorZ {
+private:
+       LDKCResult_AnnouncementSignaturesDecodeErrorZ self;
+public:
+       CResult_AnnouncementSignaturesDecodeErrorZ(const CResult_AnnouncementSignaturesDecodeErrorZ&) = delete;
+       CResult_AnnouncementSignaturesDecodeErrorZ(CResult_AnnouncementSignaturesDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_AnnouncementSignaturesDecodeErrorZ)); }
+       CResult_AnnouncementSignaturesDecodeErrorZ(LDKCResult_AnnouncementSignaturesDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_AnnouncementSignaturesDecodeErrorZ)); }
+       operator LDKCResult_AnnouncementSignaturesDecodeErrorZ() && { LDKCResult_AnnouncementSignaturesDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_AnnouncementSignaturesDecodeErrorZ)); return res; }
+       ~CResult_AnnouncementSignaturesDecodeErrorZ() { CResult_AnnouncementSignaturesDecodeErrorZ_free(self); }
+       CResult_AnnouncementSignaturesDecodeErrorZ& operator=(CResult_AnnouncementSignaturesDecodeErrorZ&& o) { CResult_AnnouncementSignaturesDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_AnnouncementSignaturesDecodeErrorZ)); return *this; }
+       LDKCResult_AnnouncementSignaturesDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_AnnouncementSignaturesDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_AnnouncementSignaturesDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_AnnouncementSignaturesDecodeErrorZ* operator ->() const { return &self; }
+};
+class CResult_UpdateFulfillHTLCDecodeErrorZ {
+private:
+       LDKCResult_UpdateFulfillHTLCDecodeErrorZ self;
+public:
+       CResult_UpdateFulfillHTLCDecodeErrorZ(const CResult_UpdateFulfillHTLCDecodeErrorZ&) = delete;
+       CResult_UpdateFulfillHTLCDecodeErrorZ(CResult_UpdateFulfillHTLCDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_UpdateFulfillHTLCDecodeErrorZ)); }
+       CResult_UpdateFulfillHTLCDecodeErrorZ(LDKCResult_UpdateFulfillHTLCDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_UpdateFulfillHTLCDecodeErrorZ)); }
+       operator LDKCResult_UpdateFulfillHTLCDecodeErrorZ() && { LDKCResult_UpdateFulfillHTLCDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_UpdateFulfillHTLCDecodeErrorZ)); return res; }
+       ~CResult_UpdateFulfillHTLCDecodeErrorZ() { CResult_UpdateFulfillHTLCDecodeErrorZ_free(self); }
+       CResult_UpdateFulfillHTLCDecodeErrorZ& operator=(CResult_UpdateFulfillHTLCDecodeErrorZ&& o) { CResult_UpdateFulfillHTLCDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_UpdateFulfillHTLCDecodeErrorZ)); return *this; }
+       LDKCResult_UpdateFulfillHTLCDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_UpdateFulfillHTLCDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_UpdateFulfillHTLCDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_UpdateFulfillHTLCDecodeErrorZ* operator ->() const { return &self; }
+};
+class CResult_NodeFeaturesDecodeErrorZ {
+private:
+       LDKCResult_NodeFeaturesDecodeErrorZ self;
+public:
+       CResult_NodeFeaturesDecodeErrorZ(const CResult_NodeFeaturesDecodeErrorZ&) = delete;
+       CResult_NodeFeaturesDecodeErrorZ(CResult_NodeFeaturesDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_NodeFeaturesDecodeErrorZ)); }
+       CResult_NodeFeaturesDecodeErrorZ(LDKCResult_NodeFeaturesDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_NodeFeaturesDecodeErrorZ)); }
+       operator LDKCResult_NodeFeaturesDecodeErrorZ() && { LDKCResult_NodeFeaturesDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_NodeFeaturesDecodeErrorZ)); return res; }
+       ~CResult_NodeFeaturesDecodeErrorZ() { CResult_NodeFeaturesDecodeErrorZ_free(self); }
+       CResult_NodeFeaturesDecodeErrorZ& operator=(CResult_NodeFeaturesDecodeErrorZ&& o) { CResult_NodeFeaturesDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_NodeFeaturesDecodeErrorZ)); return *this; }
+       LDKCResult_NodeFeaturesDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_NodeFeaturesDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_NodeFeaturesDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_NodeFeaturesDecodeErrorZ* operator ->() const { return &self; }
+};
+class CResult_InMemorySignerDecodeErrorZ {
+private:
+       LDKCResult_InMemorySignerDecodeErrorZ self;
+public:
+       CResult_InMemorySignerDecodeErrorZ(const CResult_InMemorySignerDecodeErrorZ&) = delete;
+       CResult_InMemorySignerDecodeErrorZ(CResult_InMemorySignerDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_InMemorySignerDecodeErrorZ)); }
+       CResult_InMemorySignerDecodeErrorZ(LDKCResult_InMemorySignerDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_InMemorySignerDecodeErrorZ)); }
+       operator LDKCResult_InMemorySignerDecodeErrorZ() && { LDKCResult_InMemorySignerDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_InMemorySignerDecodeErrorZ)); return res; }
+       ~CResult_InMemorySignerDecodeErrorZ() { CResult_InMemorySignerDecodeErrorZ_free(self); }
+       CResult_InMemorySignerDecodeErrorZ& operator=(CResult_InMemorySignerDecodeErrorZ&& o) { CResult_InMemorySignerDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_InMemorySignerDecodeErrorZ)); return *this; }
+       LDKCResult_InMemorySignerDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_InMemorySignerDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_InMemorySignerDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_InMemorySignerDecodeErrorZ* operator ->() const { return &self; }
+};
+class CResult_ReplyShortChannelIdsEndDecodeErrorZ {
+private:
+       LDKCResult_ReplyShortChannelIdsEndDecodeErrorZ self;
+public:
+       CResult_ReplyShortChannelIdsEndDecodeErrorZ(const CResult_ReplyShortChannelIdsEndDecodeErrorZ&) = delete;
+       CResult_ReplyShortChannelIdsEndDecodeErrorZ(CResult_ReplyShortChannelIdsEndDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_ReplyShortChannelIdsEndDecodeErrorZ)); }
+       CResult_ReplyShortChannelIdsEndDecodeErrorZ(LDKCResult_ReplyShortChannelIdsEndDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_ReplyShortChannelIdsEndDecodeErrorZ)); }
+       operator LDKCResult_ReplyShortChannelIdsEndDecodeErrorZ() && { LDKCResult_ReplyShortChannelIdsEndDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_ReplyShortChannelIdsEndDecodeErrorZ)); return res; }
+       ~CResult_ReplyShortChannelIdsEndDecodeErrorZ() { CResult_ReplyShortChannelIdsEndDecodeErrorZ_free(self); }
+       CResult_ReplyShortChannelIdsEndDecodeErrorZ& operator=(CResult_ReplyShortChannelIdsEndDecodeErrorZ&& o) { CResult_ReplyShortChannelIdsEndDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_ReplyShortChannelIdsEndDecodeErrorZ)); return *this; }
+       LDKCResult_ReplyShortChannelIdsEndDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_ReplyShortChannelIdsEndDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_ReplyShortChannelIdsEndDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_ReplyShortChannelIdsEndDecodeErrorZ* operator ->() const { return &self; }
+};
+class CResult_CResult_NetAddressu8ZDecodeErrorZ {
+private:
+       LDKCResult_CResult_NetAddressu8ZDecodeErrorZ self;
+public:
+       CResult_CResult_NetAddressu8ZDecodeErrorZ(const CResult_CResult_NetAddressu8ZDecodeErrorZ&) = delete;
+       CResult_CResult_NetAddressu8ZDecodeErrorZ(CResult_CResult_NetAddressu8ZDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_CResult_NetAddressu8ZDecodeErrorZ)); }
+       CResult_CResult_NetAddressu8ZDecodeErrorZ(LDKCResult_CResult_NetAddressu8ZDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_CResult_NetAddressu8ZDecodeErrorZ)); }
+       operator LDKCResult_CResult_NetAddressu8ZDecodeErrorZ() && { LDKCResult_CResult_NetAddressu8ZDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_CResult_NetAddressu8ZDecodeErrorZ)); return res; }
+       ~CResult_CResult_NetAddressu8ZDecodeErrorZ() { CResult_CResult_NetAddressu8ZDecodeErrorZ_free(self); }
+       CResult_CResult_NetAddressu8ZDecodeErrorZ& operator=(CResult_CResult_NetAddressu8ZDecodeErrorZ&& o) { CResult_CResult_NetAddressu8ZDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_CResult_NetAddressu8ZDecodeErrorZ)); return *this; }
+       LDKCResult_CResult_NetAddressu8ZDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_CResult_NetAddressu8ZDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_CResult_NetAddressu8ZDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_CResult_NetAddressu8ZDecodeErrorZ* operator ->() const { return &self; }
+};
+class CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ {
+private:
+       LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ self;
+public:
+       CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ(const CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ&) = delete;
+       CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ(CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ)); }
+       CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ(LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ)); }
+       operator LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ() && { LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ)); return res; }
+       ~CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ() { CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_free(self); }
+       CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ& operator=(CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ&& o) { CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ)); return *this; }
+       LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ* operator ->() const { return &self; }
+};
+class CResult_BuiltCommitmentTransactionDecodeErrorZ {
+private:
+       LDKCResult_BuiltCommitmentTransactionDecodeErrorZ self;
+public:
+       CResult_BuiltCommitmentTransactionDecodeErrorZ(const CResult_BuiltCommitmentTransactionDecodeErrorZ&) = delete;
+       CResult_BuiltCommitmentTransactionDecodeErrorZ(CResult_BuiltCommitmentTransactionDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_BuiltCommitmentTransactionDecodeErrorZ)); }
+       CResult_BuiltCommitmentTransactionDecodeErrorZ(LDKCResult_BuiltCommitmentTransactionDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_BuiltCommitmentTransactionDecodeErrorZ)); }
+       operator LDKCResult_BuiltCommitmentTransactionDecodeErrorZ() && { LDKCResult_BuiltCommitmentTransactionDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_BuiltCommitmentTransactionDecodeErrorZ)); return res; }
+       ~CResult_BuiltCommitmentTransactionDecodeErrorZ() { CResult_BuiltCommitmentTransactionDecodeErrorZ_free(self); }
+       CResult_BuiltCommitmentTransactionDecodeErrorZ& operator=(CResult_BuiltCommitmentTransactionDecodeErrorZ&& o) { CResult_BuiltCommitmentTransactionDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_BuiltCommitmentTransactionDecodeErrorZ)); return *this; }
+       LDKCResult_BuiltCommitmentTransactionDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_BuiltCommitmentTransactionDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_BuiltCommitmentTransactionDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_BuiltCommitmentTransactionDecodeErrorZ* operator ->() const { return &self; }
+};
+class CResult_RouteDecodeErrorZ {
+private:
+       LDKCResult_RouteDecodeErrorZ self;
+public:
+       CResult_RouteDecodeErrorZ(const CResult_RouteDecodeErrorZ&) = delete;
+       CResult_RouteDecodeErrorZ(CResult_RouteDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_RouteDecodeErrorZ)); }
+       CResult_RouteDecodeErrorZ(LDKCResult_RouteDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_RouteDecodeErrorZ)); }
+       operator LDKCResult_RouteDecodeErrorZ() && { LDKCResult_RouteDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_RouteDecodeErrorZ)); return res; }
+       ~CResult_RouteDecodeErrorZ() { CResult_RouteDecodeErrorZ_free(self); }
+       CResult_RouteDecodeErrorZ& operator=(CResult_RouteDecodeErrorZ&& o) { CResult_RouteDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_RouteDecodeErrorZ)); return *this; }
+       LDKCResult_RouteDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_RouteDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_RouteDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_RouteDecodeErrorZ* operator ->() const { return &self; }
+};
+class CVec_TxOutZ {
+private:
+       LDKCVec_TxOutZ self;
+public:
+       CVec_TxOutZ(const CVec_TxOutZ&) = delete;
+       CVec_TxOutZ(CVec_TxOutZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_TxOutZ)); }
+       CVec_TxOutZ(LDKCVec_TxOutZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_TxOutZ)); }
+       operator LDKCVec_TxOutZ() && { LDKCVec_TxOutZ res = self; memset(&self, 0, sizeof(LDKCVec_TxOutZ)); return res; }
+       ~CVec_TxOutZ() { CVec_TxOutZ_free(self); }
+       CVec_TxOutZ& operator=(CVec_TxOutZ&& o) { CVec_TxOutZ_free(self); self = o.self; memset(&o, 0, sizeof(CVec_TxOutZ)); return *this; }
+       LDKCVec_TxOutZ* operator &() { return &self; }
+       LDKCVec_TxOutZ* operator ->() { return &self; }
+       const LDKCVec_TxOutZ* operator &() const { return &self; }
+       const LDKCVec_TxOutZ* operator ->() const { return &self; }
 };
 class CVec_UpdateFailHTLCZ {
 private:
        LDKCVec_UpdateFailHTLCZ self;
 public:
        CVec_UpdateFailHTLCZ(const CVec_UpdateFailHTLCZ&) = delete;
-       ~CVec_UpdateFailHTLCZ() { CVec_UpdateFailHTLCZ_free(self); }
        CVec_UpdateFailHTLCZ(CVec_UpdateFailHTLCZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_UpdateFailHTLCZ)); }
        CVec_UpdateFailHTLCZ(LDKCVec_UpdateFailHTLCZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_UpdateFailHTLCZ)); }
-       operator LDKCVec_UpdateFailHTLCZ() { LDKCVec_UpdateFailHTLCZ res = self; memset(&self, 0, sizeof(LDKCVec_UpdateFailHTLCZ)); return res; }
+       operator LDKCVec_UpdateFailHTLCZ() && { LDKCVec_UpdateFailHTLCZ res = self; memset(&self, 0, sizeof(LDKCVec_UpdateFailHTLCZ)); return res; }
+       ~CVec_UpdateFailHTLCZ() { CVec_UpdateFailHTLCZ_free(self); }
+       CVec_UpdateFailHTLCZ& operator=(CVec_UpdateFailHTLCZ&& o) { CVec_UpdateFailHTLCZ_free(self); self = o.self; memset(&o, 0, sizeof(CVec_UpdateFailHTLCZ)); return *this; }
        LDKCVec_UpdateFailHTLCZ* operator &() { return &self; }
        LDKCVec_UpdateFailHTLCZ* operator ->() { return &self; }
        const LDKCVec_UpdateFailHTLCZ* operator &() const { return &self; }
        const LDKCVec_UpdateFailHTLCZ* operator ->() const { return &self; }
 };
-class CVec_NodeAnnouncementZ {
+class CResult_FundingLockedDecodeErrorZ {
 private:
-       LDKCVec_NodeAnnouncementZ self;
+       LDKCResult_FundingLockedDecodeErrorZ self;
 public:
-       CVec_NodeAnnouncementZ(const CVec_NodeAnnouncementZ&) = delete;
-       ~CVec_NodeAnnouncementZ() { CVec_NodeAnnouncementZ_free(self); }
-       CVec_NodeAnnouncementZ(CVec_NodeAnnouncementZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_NodeAnnouncementZ)); }
-       CVec_NodeAnnouncementZ(LDKCVec_NodeAnnouncementZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_NodeAnnouncementZ)); }
-       operator LDKCVec_NodeAnnouncementZ() { LDKCVec_NodeAnnouncementZ res = self; memset(&self, 0, sizeof(LDKCVec_NodeAnnouncementZ)); return res; }
-       LDKCVec_NodeAnnouncementZ* operator &() { return &self; }
-       LDKCVec_NodeAnnouncementZ* operator ->() { return &self; }
-       const LDKCVec_NodeAnnouncementZ* operator &() const { return &self; }
-       const LDKCVec_NodeAnnouncementZ* operator ->() const { return &self; }
-};
-class C2Tuple_u64u64Z {
-private:
-       LDKC2Tuple_u64u64Z self;
-public:
-       C2Tuple_u64u64Z(const C2Tuple_u64u64Z&) = delete;
-       ~C2Tuple_u64u64Z() { C2Tuple_u64u64Z_free(self); }
-       C2Tuple_u64u64Z(C2Tuple_u64u64Z&& o) : self(o.self) { memset(&o, 0, sizeof(C2Tuple_u64u64Z)); }
-       C2Tuple_u64u64Z(LDKC2Tuple_u64u64Z&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKC2Tuple_u64u64Z)); }
-       operator LDKC2Tuple_u64u64Z() { LDKC2Tuple_u64u64Z res = self; memset(&self, 0, sizeof(LDKC2Tuple_u64u64Z)); return res; }
-       LDKC2Tuple_u64u64Z* operator &() { return &self; }
-       LDKC2Tuple_u64u64Z* operator ->() { return &self; }
-       const LDKC2Tuple_u64u64Z* operator &() const { return &self; }
-       const LDKC2Tuple_u64u64Z* operator ->() const { return &self; }
-};
-class CVec_HTLCOutputInCommitmentZ {
-private:
-       LDKCVec_HTLCOutputInCommitmentZ self;
-public:
-       CVec_HTLCOutputInCommitmentZ(const CVec_HTLCOutputInCommitmentZ&) = delete;
-       ~CVec_HTLCOutputInCommitmentZ() { CVec_HTLCOutputInCommitmentZ_free(self); }
-       CVec_HTLCOutputInCommitmentZ(CVec_HTLCOutputInCommitmentZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_HTLCOutputInCommitmentZ)); }
-       CVec_HTLCOutputInCommitmentZ(LDKCVec_HTLCOutputInCommitmentZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_HTLCOutputInCommitmentZ)); }
-       operator LDKCVec_HTLCOutputInCommitmentZ() { LDKCVec_HTLCOutputInCommitmentZ res = self; memset(&self, 0, sizeof(LDKCVec_HTLCOutputInCommitmentZ)); return res; }
-       LDKCVec_HTLCOutputInCommitmentZ* operator &() { return &self; }
-       LDKCVec_HTLCOutputInCommitmentZ* operator ->() { return &self; }
-       const LDKCVec_HTLCOutputInCommitmentZ* operator &() const { return &self; }
-       const LDKCVec_HTLCOutputInCommitmentZ* operator ->() const { return &self; }
+       CResult_FundingLockedDecodeErrorZ(const CResult_FundingLockedDecodeErrorZ&) = delete;
+       CResult_FundingLockedDecodeErrorZ(CResult_FundingLockedDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_FundingLockedDecodeErrorZ)); }
+       CResult_FundingLockedDecodeErrorZ(LDKCResult_FundingLockedDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_FundingLockedDecodeErrorZ)); }
+       operator LDKCResult_FundingLockedDecodeErrorZ() && { LDKCResult_FundingLockedDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_FundingLockedDecodeErrorZ)); return res; }
+       ~CResult_FundingLockedDecodeErrorZ() { CResult_FundingLockedDecodeErrorZ_free(self); }
+       CResult_FundingLockedDecodeErrorZ& operator=(CResult_FundingLockedDecodeErrorZ&& o) { CResult_FundingLockedDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_FundingLockedDecodeErrorZ)); return *this; }
+       LDKCResult_FundingLockedDecodeErrorZ* operator &() { return &self; }
+       LDKCResult_FundingLockedDecodeErrorZ* operator ->() { return &self; }
+       const LDKCResult_FundingLockedDecodeErrorZ* operator &() const { return &self; }
+       const LDKCResult_FundingLockedDecodeErrorZ* operator ->() const { return &self; }
 };
 }
index 2e15b2a2b2adf1d99d15b7091a40d878f68e8ed1..d998eb04cfbff82363b4eae47c74df234061de45 100644 (file)
@@ -1,13 +1,48 @@
 #if defined(__GNUC__)
 #define MUST_USE_STRUCT __attribute__((warn_unused))
+#define MUST_USE_RES __attribute__((warn_unused_result))
 #else
 #define MUST_USE_STRUCT
+#define MUST_USE_RES
 #endif
-#if defined(__GNUC__)
-#define MUST_USE_RES __attribute__((warn_unused_result))
+#if defined(__clang__)
+#define NONNULL_PTR _Nonnull
 #else
-#define MUST_USE_RES
+#define NONNULL_PTR
 #endif
+struct nativeTxCreationKeysOpaque;
+typedef struct nativeTxCreationKeysOpaque LDKnativeTxCreationKeys;
+struct nativeChannelPublicKeysOpaque;
+typedef struct nativeChannelPublicKeysOpaque LDKnativeChannelPublicKeys;
+struct nativeHTLCOutputInCommitmentOpaque;
+typedef struct nativeHTLCOutputInCommitmentOpaque LDKnativeHTLCOutputInCommitment;
+struct nativeChannelTransactionParametersOpaque;
+typedef struct nativeChannelTransactionParametersOpaque LDKnativeChannelTransactionParameters;
+struct nativeCounterpartyChannelTransactionParametersOpaque;
+typedef struct nativeCounterpartyChannelTransactionParametersOpaque LDKnativeCounterpartyChannelTransactionParameters;
+struct nativeDirectedChannelTransactionParametersOpaque;
+typedef struct nativeDirectedChannelTransactionParametersOpaque LDKnativeDirectedChannelTransactionParameters;
+struct nativeHolderCommitmentTransactionOpaque;
+typedef struct nativeHolderCommitmentTransactionOpaque LDKnativeHolderCommitmentTransaction;
+struct nativeBuiltCommitmentTransactionOpaque;
+typedef struct nativeBuiltCommitmentTransactionOpaque LDKnativeBuiltCommitmentTransaction;
+struct nativeCommitmentTransactionOpaque;
+typedef struct nativeCommitmentTransactionOpaque LDKnativeCommitmentTransaction;
+struct nativeTrustedCommitmentTransactionOpaque;
+typedef struct nativeTrustedCommitmentTransactionOpaque LDKnativeTrustedCommitmentTransaction;
+struct nativeMessageHandlerOpaque;
+typedef struct nativeMessageHandlerOpaque LDKnativeMessageHandler;
+typedef struct LDKSocketDescriptor LDKSocketDescriptor;
+struct nativePeerHandleErrorOpaque;
+typedef struct nativePeerHandleErrorOpaque LDKnativePeerHandleError;
+struct nativePeerManagerOpaque;
+typedef struct nativePeerManagerOpaque LDKnativePeerManager;
+struct nativeInitFeaturesOpaque;
+typedef struct nativeInitFeaturesOpaque LDKnativeInitFeatures;
+struct nativeNodeFeaturesOpaque;
+typedef struct nativeNodeFeaturesOpaque LDKnativeNodeFeatures;
+struct nativeChannelFeaturesOpaque;
+typedef struct nativeChannelFeaturesOpaque LDKnativeChannelFeatures;
 struct nativeChannelHandshakeConfigOpaque;
 typedef struct nativeChannelHandshakeConfigOpaque LDKnativeChannelHandshakeConfig;
 struct nativeChannelHandshakeLimitsOpaque;
@@ -16,34 +51,56 @@ struct nativeChannelConfigOpaque;
 typedef struct nativeChannelConfigOpaque LDKnativeChannelConfig;
 struct nativeUserConfigOpaque;
 typedef struct nativeUserConfigOpaque LDKnativeUserConfig;
+struct nativeNetworkGraphOpaque;
+typedef struct nativeNetworkGraphOpaque LDKnativeNetworkGraph;
+struct nativeLockedNetworkGraphOpaque;
+typedef struct nativeLockedNetworkGraphOpaque LDKnativeLockedNetworkGraph;
+struct nativeNetGraphMsgHandlerOpaque;
+typedef struct nativeNetGraphMsgHandlerOpaque LDKnativeNetGraphMsgHandler;
+struct nativeDirectionalChannelInfoOpaque;
+typedef struct nativeDirectionalChannelInfoOpaque LDKnativeDirectionalChannelInfo;
+struct nativeChannelInfoOpaque;
+typedef struct nativeChannelInfoOpaque LDKnativeChannelInfo;
+struct nativeRoutingFeesOpaque;
+typedef struct nativeRoutingFeesOpaque LDKnativeRoutingFees;
+struct nativeNodeAnnouncementInfoOpaque;
+typedef struct nativeNodeAnnouncementInfoOpaque LDKnativeNodeAnnouncementInfo;
+struct nativeNodeInfoOpaque;
+typedef struct nativeNodeInfoOpaque LDKnativeNodeInfo;
 struct nativeChainMonitorOpaque;
 typedef struct nativeChainMonitorOpaque LDKnativeChainMonitor;
+struct nativeOutPointOpaque;
+typedef struct nativeOutPointOpaque LDKnativeOutPoint;
 struct nativeChannelMonitorUpdateOpaque;
 typedef struct nativeChannelMonitorUpdateOpaque LDKnativeChannelMonitorUpdate;
 struct nativeMonitorUpdateErrorOpaque;
 typedef struct nativeMonitorUpdateErrorOpaque LDKnativeMonitorUpdateError;
-struct nativeMonitorEventOpaque;
-typedef struct nativeMonitorEventOpaque LDKnativeMonitorEvent;
 struct nativeHTLCUpdateOpaque;
 typedef struct nativeHTLCUpdateOpaque LDKnativeHTLCUpdate;
 struct nativeChannelMonitorOpaque;
 typedef struct nativeChannelMonitorOpaque LDKnativeChannelMonitor;
-struct nativeOutPointOpaque;
-typedef struct nativeOutPointOpaque LDKnativeOutPoint;
-struct LDKChannelKeys;
-typedef struct LDKChannelKeys LDKChannelKeys;
-struct nativeInMemoryChannelKeysOpaque;
-typedef struct nativeInMemoryChannelKeysOpaque LDKnativeInMemoryChannelKeys;
-struct nativeKeysManagerOpaque;
-typedef struct nativeKeysManagerOpaque LDKnativeKeysManager;
 struct nativeChannelManagerOpaque;
 typedef struct nativeChannelManagerOpaque LDKnativeChannelManager;
 struct nativeChannelDetailsOpaque;
 typedef struct nativeChannelDetailsOpaque LDKnativeChannelDetails;
-struct nativePaymentSendFailureOpaque;
-typedef struct nativePaymentSendFailureOpaque LDKnativePaymentSendFailure;
 struct nativeChannelManagerReadArgsOpaque;
 typedef struct nativeChannelManagerReadArgsOpaque LDKnativeChannelManagerReadArgs;
+struct nativeDelayedPaymentOutputDescriptorOpaque;
+typedef struct nativeDelayedPaymentOutputDescriptorOpaque LDKnativeDelayedPaymentOutputDescriptor;
+struct nativeStaticPaymentOutputDescriptorOpaque;
+typedef struct nativeStaticPaymentOutputDescriptorOpaque LDKnativeStaticPaymentOutputDescriptor;
+struct LDKSign;
+typedef struct LDKSign LDKSign;
+struct nativeInMemorySignerOpaque;
+typedef struct nativeInMemorySignerOpaque LDKnativeInMemorySigner;
+struct nativeKeysManagerOpaque;
+typedef struct nativeKeysManagerOpaque LDKnativeKeysManager;
+struct nativeRouteHopOpaque;
+typedef struct nativeRouteHopOpaque LDKnativeRouteHop;
+struct nativeRouteOpaque;
+typedef struct nativeRouteOpaque LDKnativeRoute;
+struct nativeRouteHintOpaque;
+typedef struct nativeRouteHintOpaque LDKnativeRouteHint;
 struct nativeDecodeErrorOpaque;
 typedef struct nativeDecodeErrorOpaque LDKnativeDecodeError;
 struct nativeInitOpaque;
@@ -114,48 +171,3 @@ struct nativeLightningErrorOpaque;
 typedef struct nativeLightningErrorOpaque LDKnativeLightningError;
 struct nativeCommitmentUpdateOpaque;
 typedef struct nativeCommitmentUpdateOpaque LDKnativeCommitmentUpdate;
-struct nativeMessageHandlerOpaque;
-typedef struct nativeMessageHandlerOpaque LDKnativeMessageHandler;
-typedef struct LDKSocketDescriptor LDKSocketDescriptor;
-struct nativePeerHandleErrorOpaque;
-typedef struct nativePeerHandleErrorOpaque LDKnativePeerHandleError;
-struct nativePeerManagerOpaque;
-typedef struct nativePeerManagerOpaque LDKnativePeerManager;
-struct nativeTxCreationKeysOpaque;
-typedef struct nativeTxCreationKeysOpaque LDKnativeTxCreationKeys;
-struct nativePreCalculatedTxCreationKeysOpaque;
-typedef struct nativePreCalculatedTxCreationKeysOpaque LDKnativePreCalculatedTxCreationKeys;
-struct nativeChannelPublicKeysOpaque;
-typedef struct nativeChannelPublicKeysOpaque LDKnativeChannelPublicKeys;
-struct nativeHTLCOutputInCommitmentOpaque;
-typedef struct nativeHTLCOutputInCommitmentOpaque LDKnativeHTLCOutputInCommitment;
-struct nativeHolderCommitmentTransactionOpaque;
-typedef struct nativeHolderCommitmentTransactionOpaque LDKnativeHolderCommitmentTransaction;
-struct nativeInitFeaturesOpaque;
-typedef struct nativeInitFeaturesOpaque LDKnativeInitFeatures;
-struct nativeNodeFeaturesOpaque;
-typedef struct nativeNodeFeaturesOpaque LDKnativeNodeFeatures;
-struct nativeChannelFeaturesOpaque;
-typedef struct nativeChannelFeaturesOpaque LDKnativeChannelFeatures;
-struct nativeRouteHopOpaque;
-typedef struct nativeRouteHopOpaque LDKnativeRouteHop;
-struct nativeRouteOpaque;
-typedef struct nativeRouteOpaque LDKnativeRoute;
-struct nativeRouteHintOpaque;
-typedef struct nativeRouteHintOpaque LDKnativeRouteHint;
-struct nativeNetworkGraphOpaque;
-typedef struct nativeNetworkGraphOpaque LDKnativeNetworkGraph;
-struct nativeLockedNetworkGraphOpaque;
-typedef struct nativeLockedNetworkGraphOpaque LDKnativeLockedNetworkGraph;
-struct nativeNetGraphMsgHandlerOpaque;
-typedef struct nativeNetGraphMsgHandlerOpaque LDKnativeNetGraphMsgHandler;
-struct nativeDirectionalChannelInfoOpaque;
-typedef struct nativeDirectionalChannelInfoOpaque LDKnativeDirectionalChannelInfo;
-struct nativeChannelInfoOpaque;
-typedef struct nativeChannelInfoOpaque LDKnativeChannelInfo;
-struct nativeRoutingFeesOpaque;
-typedef struct nativeRoutingFeesOpaque LDKnativeRoutingFees;
-struct nativeNodeAnnouncementInfoOpaque;
-typedef struct nativeNodeAnnouncementInfoOpaque LDKnativeNodeAnnouncementInfo;
-struct nativeNodeInfoOpaque;
-typedef struct nativeNodeInfoOpaque LDKnativeNodeInfo;
index 38139e0e0b9a64c9c95a3c23031f77fbe0e73875..f2211f191ee94f8fbe97e5494bac4626bb5c6cdd 100644 (file)
+#[repr(C)]
+pub union CResult_SecretKeyErrorZPtr {
+       pub result: *mut crate::c_types::SecretKey,
+       pub err: *mut crate::c_types::Secp256k1Error,
+}
+#[repr(C)]
+pub struct CResult_SecretKeyErrorZ {
+       pub contents: CResult_SecretKeyErrorZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_SecretKeyErrorZ_ok(o: crate::c_types::SecretKey) -> CResult_SecretKeyErrorZ {
+       CResult_SecretKeyErrorZ {
+               contents: CResult_SecretKeyErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_SecretKeyErrorZ_err(e: crate::c_types::Secp256k1Error) -> CResult_SecretKeyErrorZ {
+       CResult_SecretKeyErrorZ {
+               contents: CResult_SecretKeyErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_SecretKeyErrorZ_free(_res: CResult_SecretKeyErrorZ) { }
+impl Drop for CResult_SecretKeyErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::c_types::SecretKey, crate::c_types::Secp256k1Error>> for CResult_SecretKeyErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::c_types::SecretKey, crate::c_types::Secp256k1Error>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_SecretKeyErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_SecretKeyErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+#[repr(C)]
+pub union CResult_PublicKeyErrorZPtr {
+       pub result: *mut crate::c_types::PublicKey,
+       pub err: *mut crate::c_types::Secp256k1Error,
+}
+#[repr(C)]
+pub struct CResult_PublicKeyErrorZ {
+       pub contents: CResult_PublicKeyErrorZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_PublicKeyErrorZ_ok(o: crate::c_types::PublicKey) -> CResult_PublicKeyErrorZ {
+       CResult_PublicKeyErrorZ {
+               contents: CResult_PublicKeyErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_PublicKeyErrorZ_err(e: crate::c_types::Secp256k1Error) -> CResult_PublicKeyErrorZ {
+       CResult_PublicKeyErrorZ {
+               contents: CResult_PublicKeyErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_PublicKeyErrorZ_free(_res: CResult_PublicKeyErrorZ) { }
+impl Drop for CResult_PublicKeyErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::c_types::PublicKey, crate::c_types::Secp256k1Error>> for CResult_PublicKeyErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::c_types::PublicKey, crate::c_types::Secp256k1Error>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_PublicKeyErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_PublicKeyErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+#[repr(C)]
+pub union CResult_TxCreationKeysDecodeErrorZPtr {
+       pub result: *mut crate::ln::chan_utils::TxCreationKeys,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_TxCreationKeysDecodeErrorZ {
+       pub contents: CResult_TxCreationKeysDecodeErrorZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_TxCreationKeysDecodeErrorZ_ok(o: crate::ln::chan_utils::TxCreationKeys) -> CResult_TxCreationKeysDecodeErrorZ {
+       CResult_TxCreationKeysDecodeErrorZ {
+               contents: CResult_TxCreationKeysDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_TxCreationKeysDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_TxCreationKeysDecodeErrorZ {
+       CResult_TxCreationKeysDecodeErrorZ {
+               contents: CResult_TxCreationKeysDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_TxCreationKeysDecodeErrorZ_free(_res: CResult_TxCreationKeysDecodeErrorZ) { }
+impl Drop for CResult_TxCreationKeysDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::chan_utils::TxCreationKeys, crate::ln::msgs::DecodeError>> for CResult_TxCreationKeysDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::chan_utils::TxCreationKeys, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_TxCreationKeysDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_TxCreationKeysDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_TxCreationKeysDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_TxCreationKeysDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::chan_utils::TxCreationKeys>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_TxCreationKeysDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_TxCreationKeysDecodeErrorZ_clone(orig: &CResult_TxCreationKeysDecodeErrorZ) -> CResult_TxCreationKeysDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_ChannelPublicKeysDecodeErrorZPtr {
+       pub result: *mut crate::ln::chan_utils::ChannelPublicKeys,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_ChannelPublicKeysDecodeErrorZ {
+       pub contents: CResult_ChannelPublicKeysDecodeErrorZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_ChannelPublicKeysDecodeErrorZ_ok(o: crate::ln::chan_utils::ChannelPublicKeys) -> CResult_ChannelPublicKeysDecodeErrorZ {
+       CResult_ChannelPublicKeysDecodeErrorZ {
+               contents: CResult_ChannelPublicKeysDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_ChannelPublicKeysDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_ChannelPublicKeysDecodeErrorZ {
+       CResult_ChannelPublicKeysDecodeErrorZ {
+               contents: CResult_ChannelPublicKeysDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_ChannelPublicKeysDecodeErrorZ_free(_res: CResult_ChannelPublicKeysDecodeErrorZ) { }
+impl Drop for CResult_ChannelPublicKeysDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::chan_utils::ChannelPublicKeys, crate::ln::msgs::DecodeError>> for CResult_ChannelPublicKeysDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::chan_utils::ChannelPublicKeys, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_ChannelPublicKeysDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_ChannelPublicKeysDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_ChannelPublicKeysDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_ChannelPublicKeysDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::chan_utils::ChannelPublicKeys>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_ChannelPublicKeysDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_ChannelPublicKeysDecodeErrorZ_clone(orig: &CResult_ChannelPublicKeysDecodeErrorZ) -> CResult_ChannelPublicKeysDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_TxCreationKeysErrorZPtr {
+       pub result: *mut crate::ln::chan_utils::TxCreationKeys,
+       pub err: *mut crate::c_types::Secp256k1Error,
+}
+#[repr(C)]
+pub struct CResult_TxCreationKeysErrorZ {
+       pub contents: CResult_TxCreationKeysErrorZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_TxCreationKeysErrorZ_ok(o: crate::ln::chan_utils::TxCreationKeys) -> CResult_TxCreationKeysErrorZ {
+       CResult_TxCreationKeysErrorZ {
+               contents: CResult_TxCreationKeysErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_TxCreationKeysErrorZ_err(e: crate::c_types::Secp256k1Error) -> CResult_TxCreationKeysErrorZ {
+       CResult_TxCreationKeysErrorZ {
+               contents: CResult_TxCreationKeysErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_TxCreationKeysErrorZ_free(_res: CResult_TxCreationKeysErrorZ) { }
+impl Drop for CResult_TxCreationKeysErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::chan_utils::TxCreationKeys, crate::c_types::Secp256k1Error>> for CResult_TxCreationKeysErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::chan_utils::TxCreationKeys, crate::c_types::Secp256k1Error>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_TxCreationKeysErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_TxCreationKeysErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+#[repr(C)]
+pub union CResult_HTLCOutputInCommitmentDecodeErrorZPtr {
+       pub result: *mut crate::ln::chan_utils::HTLCOutputInCommitment,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_HTLCOutputInCommitmentDecodeErrorZ {
+       pub contents: CResult_HTLCOutputInCommitmentDecodeErrorZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_HTLCOutputInCommitmentDecodeErrorZ_ok(o: crate::ln::chan_utils::HTLCOutputInCommitment) -> CResult_HTLCOutputInCommitmentDecodeErrorZ {
+       CResult_HTLCOutputInCommitmentDecodeErrorZ {
+               contents: CResult_HTLCOutputInCommitmentDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_HTLCOutputInCommitmentDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_HTLCOutputInCommitmentDecodeErrorZ {
+       CResult_HTLCOutputInCommitmentDecodeErrorZ {
+               contents: CResult_HTLCOutputInCommitmentDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_HTLCOutputInCommitmentDecodeErrorZ_free(_res: CResult_HTLCOutputInCommitmentDecodeErrorZ) { }
+impl Drop for CResult_HTLCOutputInCommitmentDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::chan_utils::HTLCOutputInCommitment, crate::ln::msgs::DecodeError>> for CResult_HTLCOutputInCommitmentDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::chan_utils::HTLCOutputInCommitment, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_HTLCOutputInCommitmentDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_HTLCOutputInCommitmentDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_HTLCOutputInCommitmentDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_HTLCOutputInCommitmentDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::chan_utils::HTLCOutputInCommitment>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_HTLCOutputInCommitmentDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_HTLCOutputInCommitmentDecodeErrorZ_clone(orig: &CResult_HTLCOutputInCommitmentDecodeErrorZ) -> CResult_HTLCOutputInCommitmentDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_CounterpartyChannelTransactionParametersDecodeErrorZPtr {
+       pub result: *mut crate::ln::chan_utils::CounterpartyChannelTransactionParameters,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_CounterpartyChannelTransactionParametersDecodeErrorZ {
+       pub contents: CResult_CounterpartyChannelTransactionParametersDecodeErrorZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_CounterpartyChannelTransactionParametersDecodeErrorZ_ok(o: crate::ln::chan_utils::CounterpartyChannelTransactionParameters) -> CResult_CounterpartyChannelTransactionParametersDecodeErrorZ {
+       CResult_CounterpartyChannelTransactionParametersDecodeErrorZ {
+               contents: CResult_CounterpartyChannelTransactionParametersDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_CounterpartyChannelTransactionParametersDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_CounterpartyChannelTransactionParametersDecodeErrorZ {
+       CResult_CounterpartyChannelTransactionParametersDecodeErrorZ {
+               contents: CResult_CounterpartyChannelTransactionParametersDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_CounterpartyChannelTransactionParametersDecodeErrorZ_free(_res: CResult_CounterpartyChannelTransactionParametersDecodeErrorZ) { }
+impl Drop for CResult_CounterpartyChannelTransactionParametersDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::chan_utils::CounterpartyChannelTransactionParameters, crate::ln::msgs::DecodeError>> for CResult_CounterpartyChannelTransactionParametersDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::chan_utils::CounterpartyChannelTransactionParameters, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_CounterpartyChannelTransactionParametersDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_CounterpartyChannelTransactionParametersDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_CounterpartyChannelTransactionParametersDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_CounterpartyChannelTransactionParametersDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::chan_utils::CounterpartyChannelTransactionParameters>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_CounterpartyChannelTransactionParametersDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_CounterpartyChannelTransactionParametersDecodeErrorZ_clone(orig: &CResult_CounterpartyChannelTransactionParametersDecodeErrorZ) -> CResult_CounterpartyChannelTransactionParametersDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_ChannelTransactionParametersDecodeErrorZPtr {
+       pub result: *mut crate::ln::chan_utils::ChannelTransactionParameters,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_ChannelTransactionParametersDecodeErrorZ {
+       pub contents: CResult_ChannelTransactionParametersDecodeErrorZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_ChannelTransactionParametersDecodeErrorZ_ok(o: crate::ln::chan_utils::ChannelTransactionParameters) -> CResult_ChannelTransactionParametersDecodeErrorZ {
+       CResult_ChannelTransactionParametersDecodeErrorZ {
+               contents: CResult_ChannelTransactionParametersDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_ChannelTransactionParametersDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_ChannelTransactionParametersDecodeErrorZ {
+       CResult_ChannelTransactionParametersDecodeErrorZ {
+               contents: CResult_ChannelTransactionParametersDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_ChannelTransactionParametersDecodeErrorZ_free(_res: CResult_ChannelTransactionParametersDecodeErrorZ) { }
+impl Drop for CResult_ChannelTransactionParametersDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::chan_utils::ChannelTransactionParameters, crate::ln::msgs::DecodeError>> for CResult_ChannelTransactionParametersDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::chan_utils::ChannelTransactionParameters, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_ChannelTransactionParametersDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_ChannelTransactionParametersDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_ChannelTransactionParametersDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_ChannelTransactionParametersDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::chan_utils::ChannelTransactionParameters>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_ChannelTransactionParametersDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_ChannelTransactionParametersDecodeErrorZ_clone(orig: &CResult_ChannelTransactionParametersDecodeErrorZ) -> CResult_ChannelTransactionParametersDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub struct CVec_SignatureZ {
+       pub data: *mut crate::c_types::Signature,
+       pub datalen: usize
+}
+impl CVec_SignatureZ {
+       #[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec<crate::c_types::Signature> {
+               if self.datalen == 0 { return Vec::new(); }
+               let ret = unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }.into();
+               self.data = std::ptr::null_mut();
+               self.datalen = 0;
+               ret
+       }
+       #[allow(unused)] pub(crate) fn as_slice(&self) -> &[crate::c_types::Signature] {
+               unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) }
+       }
+}
+impl From<Vec<crate::c_types::Signature>> for CVec_SignatureZ {
+       fn from(v: Vec<crate::c_types::Signature>) -> Self {
+               let datalen = v.len();
+               let data = Box::into_raw(v.into_boxed_slice());
+               Self { datalen, data: unsafe { (*data).as_mut_ptr() } }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CVec_SignatureZ_free(_res: CVec_SignatureZ) { }
+impl Drop for CVec_SignatureZ {
+       fn drop(&mut self) {
+               if self.datalen == 0 { return; }
+               unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) };
+       }
+}
+impl Clone for CVec_SignatureZ {
+       fn clone(&self) -> Self {
+               let mut res = Vec::new();
+               if self.datalen == 0 { return Self::from(res); }
+               res.extend_from_slice(unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) });
+               Self::from(res)
+       }
+}
+#[repr(C)]
+pub union CResult_HolderCommitmentTransactionDecodeErrorZPtr {
+       pub result: *mut crate::ln::chan_utils::HolderCommitmentTransaction,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_HolderCommitmentTransactionDecodeErrorZ {
+       pub contents: CResult_HolderCommitmentTransactionDecodeErrorZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_HolderCommitmentTransactionDecodeErrorZ_ok(o: crate::ln::chan_utils::HolderCommitmentTransaction) -> CResult_HolderCommitmentTransactionDecodeErrorZ {
+       CResult_HolderCommitmentTransactionDecodeErrorZ {
+               contents: CResult_HolderCommitmentTransactionDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_HolderCommitmentTransactionDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_HolderCommitmentTransactionDecodeErrorZ {
+       CResult_HolderCommitmentTransactionDecodeErrorZ {
+               contents: CResult_HolderCommitmentTransactionDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_HolderCommitmentTransactionDecodeErrorZ_free(_res: CResult_HolderCommitmentTransactionDecodeErrorZ) { }
+impl Drop for CResult_HolderCommitmentTransactionDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::chan_utils::HolderCommitmentTransaction, crate::ln::msgs::DecodeError>> for CResult_HolderCommitmentTransactionDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::chan_utils::HolderCommitmentTransaction, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_HolderCommitmentTransactionDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_HolderCommitmentTransactionDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_HolderCommitmentTransactionDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_HolderCommitmentTransactionDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::chan_utils::HolderCommitmentTransaction>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_HolderCommitmentTransactionDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_HolderCommitmentTransactionDecodeErrorZ_clone(orig: &CResult_HolderCommitmentTransactionDecodeErrorZ) -> CResult_HolderCommitmentTransactionDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_BuiltCommitmentTransactionDecodeErrorZPtr {
+       pub result: *mut crate::ln::chan_utils::BuiltCommitmentTransaction,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_BuiltCommitmentTransactionDecodeErrorZ {
+       pub contents: CResult_BuiltCommitmentTransactionDecodeErrorZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_BuiltCommitmentTransactionDecodeErrorZ_ok(o: crate::ln::chan_utils::BuiltCommitmentTransaction) -> CResult_BuiltCommitmentTransactionDecodeErrorZ {
+       CResult_BuiltCommitmentTransactionDecodeErrorZ {
+               contents: CResult_BuiltCommitmentTransactionDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_BuiltCommitmentTransactionDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_BuiltCommitmentTransactionDecodeErrorZ {
+       CResult_BuiltCommitmentTransactionDecodeErrorZ {
+               contents: CResult_BuiltCommitmentTransactionDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_BuiltCommitmentTransactionDecodeErrorZ_free(_res: CResult_BuiltCommitmentTransactionDecodeErrorZ) { }
+impl Drop for CResult_BuiltCommitmentTransactionDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::chan_utils::BuiltCommitmentTransaction, crate::ln::msgs::DecodeError>> for CResult_BuiltCommitmentTransactionDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::chan_utils::BuiltCommitmentTransaction, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_BuiltCommitmentTransactionDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_BuiltCommitmentTransactionDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_BuiltCommitmentTransactionDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_BuiltCommitmentTransactionDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::chan_utils::BuiltCommitmentTransaction>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_BuiltCommitmentTransactionDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_BuiltCommitmentTransactionDecodeErrorZ_clone(orig: &CResult_BuiltCommitmentTransactionDecodeErrorZ) -> CResult_BuiltCommitmentTransactionDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_CommitmentTransactionDecodeErrorZPtr {
+       pub result: *mut crate::ln::chan_utils::CommitmentTransaction,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_CommitmentTransactionDecodeErrorZ {
+       pub contents: CResult_CommitmentTransactionDecodeErrorZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_CommitmentTransactionDecodeErrorZ_ok(o: crate::ln::chan_utils::CommitmentTransaction) -> CResult_CommitmentTransactionDecodeErrorZ {
+       CResult_CommitmentTransactionDecodeErrorZ {
+               contents: CResult_CommitmentTransactionDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_CommitmentTransactionDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_CommitmentTransactionDecodeErrorZ {
+       CResult_CommitmentTransactionDecodeErrorZ {
+               contents: CResult_CommitmentTransactionDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_CommitmentTransactionDecodeErrorZ_free(_res: CResult_CommitmentTransactionDecodeErrorZ) { }
+impl Drop for CResult_CommitmentTransactionDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::chan_utils::CommitmentTransaction, crate::ln::msgs::DecodeError>> for CResult_CommitmentTransactionDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::chan_utils::CommitmentTransaction, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_CommitmentTransactionDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_CommitmentTransactionDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_CommitmentTransactionDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_CommitmentTransactionDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::chan_utils::CommitmentTransaction>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_CommitmentTransactionDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_CommitmentTransactionDecodeErrorZ_clone(orig: &CResult_CommitmentTransactionDecodeErrorZ) -> CResult_CommitmentTransactionDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_TrustedCommitmentTransactionNoneZPtr {
+       pub result: *mut crate::ln::chan_utils::TrustedCommitmentTransaction,
+       /// Note that this value is always NULL, as there are no contents in the Err variant
+       pub err: *mut std::ffi::c_void,
+}
+#[repr(C)]
+pub struct CResult_TrustedCommitmentTransactionNoneZ {
+       pub contents: CResult_TrustedCommitmentTransactionNoneZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_TrustedCommitmentTransactionNoneZ_ok(o: crate::ln::chan_utils::TrustedCommitmentTransaction) -> CResult_TrustedCommitmentTransactionNoneZ {
+       CResult_TrustedCommitmentTransactionNoneZ {
+               contents: CResult_TrustedCommitmentTransactionNoneZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_TrustedCommitmentTransactionNoneZ_err() -> CResult_TrustedCommitmentTransactionNoneZ {
+       CResult_TrustedCommitmentTransactionNoneZ {
+               contents: CResult_TrustedCommitmentTransactionNoneZPtr {
+                       err: std::ptr::null_mut(),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_TrustedCommitmentTransactionNoneZ_free(_res: CResult_TrustedCommitmentTransactionNoneZ) { }
+impl Drop for CResult_TrustedCommitmentTransactionNoneZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::chan_utils::TrustedCommitmentTransaction, u8>> for CResult_TrustedCommitmentTransactionNoneZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::chan_utils::TrustedCommitmentTransaction, u8>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_TrustedCommitmentTransactionNoneZPtr { result }
+               } else {
+                       let _ = unsafe { Box::from_raw(o.contents.err) };
+                       o.contents.err = std::ptr::null_mut();
+                       CResult_TrustedCommitmentTransactionNoneZPtr { err: std::ptr::null_mut() }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+#[repr(C)]
+pub union CResult_CVec_SignatureZNoneZPtr {
+       pub result: *mut crate::c_types::derived::CVec_SignatureZ,
+       /// Note that this value is always NULL, as there are no contents in the Err variant
+       pub err: *mut std::ffi::c_void,
+}
+#[repr(C)]
+pub struct CResult_CVec_SignatureZNoneZ {
+       pub contents: CResult_CVec_SignatureZNoneZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_CVec_SignatureZNoneZ_ok(o: crate::c_types::derived::CVec_SignatureZ) -> CResult_CVec_SignatureZNoneZ {
+       CResult_CVec_SignatureZNoneZ {
+               contents: CResult_CVec_SignatureZNoneZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_CVec_SignatureZNoneZ_err() -> CResult_CVec_SignatureZNoneZ {
+       CResult_CVec_SignatureZNoneZ {
+               contents: CResult_CVec_SignatureZNoneZPtr {
+                       err: std::ptr::null_mut(),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_CVec_SignatureZNoneZ_free(_res: CResult_CVec_SignatureZNoneZ) { }
+impl Drop for CResult_CVec_SignatureZNoneZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::c_types::derived::CVec_SignatureZ, u8>> for CResult_CVec_SignatureZNoneZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::c_types::derived::CVec_SignatureZ, u8>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_CVec_SignatureZNoneZPtr { result }
+               } else {
+                       let _ = unsafe { Box::from_raw(o.contents.err) };
+                       o.contents.err = std::ptr::null_mut();
+                       CResult_CVec_SignatureZNoneZPtr { err: std::ptr::null_mut() }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_CVec_SignatureZNoneZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_CVec_SignatureZNoneZPtr {
+                               result: Box::into_raw(Box::new(<crate::c_types::derived::CVec_SignatureZ>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_CVec_SignatureZNoneZPtr {
+                               err: std::ptr::null_mut()
+                       } }
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_CVec_SignatureZNoneZ_clone(orig: &CResult_CVec_SignatureZNoneZ) -> CResult_CVec_SignatureZNoneZ { orig.clone() }
+#[repr(C)]
+pub struct CVec_PublicKeyZ {
+       pub data: *mut crate::c_types::PublicKey,
+       pub datalen: usize
+}
+impl CVec_PublicKeyZ {
+       #[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec<crate::c_types::PublicKey> {
+               if self.datalen == 0 { return Vec::new(); }
+               let ret = unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }.into();
+               self.data = std::ptr::null_mut();
+               self.datalen = 0;
+               ret
+       }
+       #[allow(unused)] pub(crate) fn as_slice(&self) -> &[crate::c_types::PublicKey] {
+               unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) }
+       }
+}
+impl From<Vec<crate::c_types::PublicKey>> for CVec_PublicKeyZ {
+       fn from(v: Vec<crate::c_types::PublicKey>) -> Self {
+               let datalen = v.len();
+               let data = Box::into_raw(v.into_boxed_slice());
+               Self { datalen, data: unsafe { (*data).as_mut_ptr() } }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CVec_PublicKeyZ_free(_res: CVec_PublicKeyZ) { }
+impl Drop for CVec_PublicKeyZ {
+       fn drop(&mut self) {
+               if self.datalen == 0 { return; }
+               unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) };
+       }
+}
+#[repr(C)]
+pub struct CVec_u8Z {
+       pub data: *mut u8,
+       pub datalen: usize
+}
+impl CVec_u8Z {
+       #[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec<u8> {
+               if self.datalen == 0 { return Vec::new(); }
+               let ret = unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }.into();
+               self.data = std::ptr::null_mut();
+               self.datalen = 0;
+               ret
+       }
+       #[allow(unused)] pub(crate) fn as_slice(&self) -> &[u8] {
+               unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) }
+       }
+}
+impl From<Vec<u8>> for CVec_u8Z {
+       fn from(v: Vec<u8>) -> Self {
+               let datalen = v.len();
+               let data = Box::into_raw(v.into_boxed_slice());
+               Self { datalen, data: unsafe { (*data).as_mut_ptr() } }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CVec_u8Z_free(_res: CVec_u8Z) { }
+impl Drop for CVec_u8Z {
+       fn drop(&mut self) {
+               if self.datalen == 0 { return; }
+               unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) };
+       }
+}
+impl Clone for CVec_u8Z {
+       fn clone(&self) -> Self {
+               let mut res = Vec::new();
+               if self.datalen == 0 { return Self::from(res); }
+               res.extend_from_slice(unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) });
+               Self::from(res)
+       }
+}
+#[repr(C)]
+pub union CResult_CVec_u8ZPeerHandleErrorZPtr {
+       pub result: *mut crate::c_types::derived::CVec_u8Z,
+       pub err: *mut crate::ln::peer_handler::PeerHandleError,
+}
+#[repr(C)]
+pub struct CResult_CVec_u8ZPeerHandleErrorZ {
+       pub contents: CResult_CVec_u8ZPeerHandleErrorZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_CVec_u8ZPeerHandleErrorZ_ok(o: crate::c_types::derived::CVec_u8Z) -> CResult_CVec_u8ZPeerHandleErrorZ {
+       CResult_CVec_u8ZPeerHandleErrorZ {
+               contents: CResult_CVec_u8ZPeerHandleErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_CVec_u8ZPeerHandleErrorZ_err(e: crate::ln::peer_handler::PeerHandleError) -> CResult_CVec_u8ZPeerHandleErrorZ {
+       CResult_CVec_u8ZPeerHandleErrorZ {
+               contents: CResult_CVec_u8ZPeerHandleErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_CVec_u8ZPeerHandleErrorZ_free(_res: CResult_CVec_u8ZPeerHandleErrorZ) { }
+impl Drop for CResult_CVec_u8ZPeerHandleErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::c_types::derived::CVec_u8Z, crate::ln::peer_handler::PeerHandleError>> for CResult_CVec_u8ZPeerHandleErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::c_types::derived::CVec_u8Z, crate::ln::peer_handler::PeerHandleError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_CVec_u8ZPeerHandleErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_CVec_u8ZPeerHandleErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_CVec_u8ZPeerHandleErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_CVec_u8ZPeerHandleErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::c_types::derived::CVec_u8Z>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_CVec_u8ZPeerHandleErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::peer_handler::PeerHandleError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_CVec_u8ZPeerHandleErrorZ_clone(orig: &CResult_CVec_u8ZPeerHandleErrorZ) -> CResult_CVec_u8ZPeerHandleErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_NonePeerHandleErrorZPtr {
+       /// Note that this value is always NULL, as there are no contents in the OK variant
+       pub result: *mut std::ffi::c_void,
+       pub err: *mut crate::ln::peer_handler::PeerHandleError,
+}
+#[repr(C)]
+pub struct CResult_NonePeerHandleErrorZ {
+       pub contents: CResult_NonePeerHandleErrorZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_NonePeerHandleErrorZ_ok() -> CResult_NonePeerHandleErrorZ {
+       CResult_NonePeerHandleErrorZ {
+               contents: CResult_NonePeerHandleErrorZPtr {
+                       result: std::ptr::null_mut(),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_NonePeerHandleErrorZ_err(e: crate::ln::peer_handler::PeerHandleError) -> CResult_NonePeerHandleErrorZ {
+       CResult_NonePeerHandleErrorZ {
+               contents: CResult_NonePeerHandleErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_NonePeerHandleErrorZ_free(_res: CResult_NonePeerHandleErrorZ) { }
+impl Drop for CResult_NonePeerHandleErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<u8, crate::ln::peer_handler::PeerHandleError>> for CResult_NonePeerHandleErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<u8, crate::ln::peer_handler::PeerHandleError>) -> Self {
+               let contents = if o.result_ok {
+                       let _ = unsafe { Box::from_raw(o.contents.result) };
+                       o.contents.result = std::ptr::null_mut();
+                       CResult_NonePeerHandleErrorZPtr { result: std::ptr::null_mut() }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_NonePeerHandleErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_NonePeerHandleErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_NonePeerHandleErrorZPtr {
+                               result: std::ptr::null_mut()
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_NonePeerHandleErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::peer_handler::PeerHandleError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_NonePeerHandleErrorZ_clone(orig: &CResult_NonePeerHandleErrorZ) -> CResult_NonePeerHandleErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_boolPeerHandleErrorZPtr {
+       pub result: *mut bool,
+       pub err: *mut crate::ln::peer_handler::PeerHandleError,
+}
+#[repr(C)]
+pub struct CResult_boolPeerHandleErrorZ {
+       pub contents: CResult_boolPeerHandleErrorZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_boolPeerHandleErrorZ_ok(o: bool) -> CResult_boolPeerHandleErrorZ {
+       CResult_boolPeerHandleErrorZ {
+               contents: CResult_boolPeerHandleErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_boolPeerHandleErrorZ_err(e: crate::ln::peer_handler::PeerHandleError) -> CResult_boolPeerHandleErrorZ {
+       CResult_boolPeerHandleErrorZ {
+               contents: CResult_boolPeerHandleErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_boolPeerHandleErrorZ_free(_res: CResult_boolPeerHandleErrorZ) { }
+impl Drop for CResult_boolPeerHandleErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<bool, crate::ln::peer_handler::PeerHandleError>> for CResult_boolPeerHandleErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<bool, crate::ln::peer_handler::PeerHandleError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_boolPeerHandleErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_boolPeerHandleErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_boolPeerHandleErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_boolPeerHandleErrorZPtr {
+                               result: Box::into_raw(Box::new(<bool>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_boolPeerHandleErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::peer_handler::PeerHandleError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_boolPeerHandleErrorZ_clone(orig: &CResult_boolPeerHandleErrorZ) -> CResult_boolPeerHandleErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_InitFeaturesDecodeErrorZPtr {
+       pub result: *mut crate::ln::features::InitFeatures,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_InitFeaturesDecodeErrorZ {
+       pub contents: CResult_InitFeaturesDecodeErrorZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_InitFeaturesDecodeErrorZ_ok(o: crate::ln::features::InitFeatures) -> CResult_InitFeaturesDecodeErrorZ {
+       CResult_InitFeaturesDecodeErrorZ {
+               contents: CResult_InitFeaturesDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_InitFeaturesDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_InitFeaturesDecodeErrorZ {
+       CResult_InitFeaturesDecodeErrorZ {
+               contents: CResult_InitFeaturesDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_InitFeaturesDecodeErrorZ_free(_res: CResult_InitFeaturesDecodeErrorZ) { }
+impl Drop for CResult_InitFeaturesDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::features::InitFeatures, crate::ln::msgs::DecodeError>> for CResult_InitFeaturesDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::features::InitFeatures, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_InitFeaturesDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_InitFeaturesDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+#[repr(C)]
+pub union CResult_NodeFeaturesDecodeErrorZPtr {
+       pub result: *mut crate::ln::features::NodeFeatures,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_NodeFeaturesDecodeErrorZ {
+       pub contents: CResult_NodeFeaturesDecodeErrorZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_NodeFeaturesDecodeErrorZ_ok(o: crate::ln::features::NodeFeatures) -> CResult_NodeFeaturesDecodeErrorZ {
+       CResult_NodeFeaturesDecodeErrorZ {
+               contents: CResult_NodeFeaturesDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_NodeFeaturesDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_NodeFeaturesDecodeErrorZ {
+       CResult_NodeFeaturesDecodeErrorZ {
+               contents: CResult_NodeFeaturesDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_NodeFeaturesDecodeErrorZ_free(_res: CResult_NodeFeaturesDecodeErrorZ) { }
+impl Drop for CResult_NodeFeaturesDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::features::NodeFeatures, crate::ln::msgs::DecodeError>> for CResult_NodeFeaturesDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::features::NodeFeatures, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_NodeFeaturesDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_NodeFeaturesDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+#[repr(C)]
+pub union CResult_ChannelFeaturesDecodeErrorZPtr {
+       pub result: *mut crate::ln::features::ChannelFeatures,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_ChannelFeaturesDecodeErrorZ {
+       pub contents: CResult_ChannelFeaturesDecodeErrorZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_ChannelFeaturesDecodeErrorZ_ok(o: crate::ln::features::ChannelFeatures) -> CResult_ChannelFeaturesDecodeErrorZ {
+       CResult_ChannelFeaturesDecodeErrorZ {
+               contents: CResult_ChannelFeaturesDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_ChannelFeaturesDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_ChannelFeaturesDecodeErrorZ {
+       CResult_ChannelFeaturesDecodeErrorZ {
+               contents: CResult_ChannelFeaturesDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_ChannelFeaturesDecodeErrorZ_free(_res: CResult_ChannelFeaturesDecodeErrorZ) { }
+impl Drop for CResult_ChannelFeaturesDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::features::ChannelFeatures, crate::ln::msgs::DecodeError>> for CResult_ChannelFeaturesDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::features::ChannelFeatures, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_ChannelFeaturesDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_ChannelFeaturesDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+#[repr(C)]
+pub union CResult_ChannelConfigDecodeErrorZPtr {
+       pub result: *mut crate::util::config::ChannelConfig,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_ChannelConfigDecodeErrorZ {
+       pub contents: CResult_ChannelConfigDecodeErrorZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_ChannelConfigDecodeErrorZ_ok(o: crate::util::config::ChannelConfig) -> CResult_ChannelConfigDecodeErrorZ {
+       CResult_ChannelConfigDecodeErrorZ {
+               contents: CResult_ChannelConfigDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_ChannelConfigDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_ChannelConfigDecodeErrorZ {
+       CResult_ChannelConfigDecodeErrorZ {
+               contents: CResult_ChannelConfigDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_ChannelConfigDecodeErrorZ_free(_res: CResult_ChannelConfigDecodeErrorZ) { }
+impl Drop for CResult_ChannelConfigDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::util::config::ChannelConfig, crate::ln::msgs::DecodeError>> for CResult_ChannelConfigDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::util::config::ChannelConfig, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_ChannelConfigDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_ChannelConfigDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_ChannelConfigDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_ChannelConfigDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::util::config::ChannelConfig>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_ChannelConfigDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_ChannelConfigDecodeErrorZ_clone(orig: &CResult_ChannelConfigDecodeErrorZ) -> CResult_ChannelConfigDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_boolLightningErrorZPtr {
+       pub result: *mut bool,
+       pub err: *mut crate::ln::msgs::LightningError,
+}
+#[repr(C)]
+pub struct CResult_boolLightningErrorZ {
+       pub contents: CResult_boolLightningErrorZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_boolLightningErrorZ_ok(o: bool) -> CResult_boolLightningErrorZ {
+       CResult_boolLightningErrorZ {
+               contents: CResult_boolLightningErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_boolLightningErrorZ_err(e: crate::ln::msgs::LightningError) -> CResult_boolLightningErrorZ {
+       CResult_boolLightningErrorZ {
+               contents: CResult_boolLightningErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_boolLightningErrorZ_free(_res: CResult_boolLightningErrorZ) { }
+impl Drop for CResult_boolLightningErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<bool, crate::ln::msgs::LightningError>> for CResult_boolLightningErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<bool, crate::ln::msgs::LightningError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_boolLightningErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_boolLightningErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_boolLightningErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_boolLightningErrorZPtr {
+                               result: Box::into_raw(Box::new(<bool>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_boolLightningErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::LightningError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_boolLightningErrorZ_clone(orig: &CResult_boolLightningErrorZ) -> CResult_boolLightningErrorZ { orig.clone() }
+#[repr(C)]
+pub struct C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ {
+       pub a: crate::ln::msgs::ChannelAnnouncement,
+       pub b: crate::ln::msgs::ChannelUpdate,
+       pub c: crate::ln::msgs::ChannelUpdate,
+}
+impl From<(crate::ln::msgs::ChannelAnnouncement, crate::ln::msgs::ChannelUpdate, crate::ln::msgs::ChannelUpdate)> for C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ {
+       fn from (tup: (crate::ln::msgs::ChannelAnnouncement, crate::ln::msgs::ChannelUpdate, crate::ln::msgs::ChannelUpdate)) -> Self {
+               Self {
+                       a: tup.0,
+                       b: tup.1,
+                       c: tup.2,
+               }
+       }
+}
+impl C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ {
+       #[allow(unused)] pub(crate) fn to_rust(mut self) -> (crate::ln::msgs::ChannelAnnouncement, crate::ln::msgs::ChannelUpdate, crate::ln::msgs::ChannelUpdate) {
+               (self.a, self.b, self.c)
+       }
+}
+impl Clone for C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ {
+       fn clone(&self) -> Self {
+               Self {
+                       a: self.a.clone(),
+                       b: self.b.clone(),
+                       c: self.c.clone(),
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ_clone(orig: &C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ) -> C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ { orig.clone() }
+#[no_mangle]
+pub extern "C" fn C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ_new(a: crate::ln::msgs::ChannelAnnouncement, b: crate::ln::msgs::ChannelUpdate, c: crate::ln::msgs::ChannelUpdate) -> C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ {
+       C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ { a, b, c, }
+}
+
+#[no_mangle]
+pub extern "C" fn C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ_free(_res: C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ) { }
+#[repr(C)]
+pub struct CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ {
+       pub data: *mut crate::c_types::derived::C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ,
+       pub datalen: usize
+}
+impl CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ {
+       #[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec<crate::c_types::derived::C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ> {
+               if self.datalen == 0 { return Vec::new(); }
+               let ret = unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }.into();
+               self.data = std::ptr::null_mut();
+               self.datalen = 0;
+               ret
+       }
+       #[allow(unused)] pub(crate) fn as_slice(&self) -> &[crate::c_types::derived::C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ] {
+               unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) }
+       }
+}
+impl From<Vec<crate::c_types::derived::C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ>> for CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ {
+       fn from(v: Vec<crate::c_types::derived::C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ>) -> Self {
+               let datalen = v.len();
+               let data = Box::into_raw(v.into_boxed_slice());
+               Self { datalen, data: unsafe { (*data).as_mut_ptr() } }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ_free(_res: CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ) { }
+impl Drop for CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ {
+       fn drop(&mut self) {
+               if self.datalen == 0 { return; }
+               unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) };
+       }
+}
+impl Clone for CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ {
+       fn clone(&self) -> Self {
+               let mut res = Vec::new();
+               if self.datalen == 0 { return Self::from(res); }
+               res.extend_from_slice(unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) });
+               Self::from(res)
+       }
+}
+#[repr(C)]
+pub struct CVec_NodeAnnouncementZ {
+       pub data: *mut crate::ln::msgs::NodeAnnouncement,
+       pub datalen: usize
+}
+impl CVec_NodeAnnouncementZ {
+       #[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec<crate::ln::msgs::NodeAnnouncement> {
+               if self.datalen == 0 { return Vec::new(); }
+               let ret = unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }.into();
+               self.data = std::ptr::null_mut();
+               self.datalen = 0;
+               ret
+       }
+       #[allow(unused)] pub(crate) fn as_slice(&self) -> &[crate::ln::msgs::NodeAnnouncement] {
+               unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) }
+       }
+}
+impl From<Vec<crate::ln::msgs::NodeAnnouncement>> for CVec_NodeAnnouncementZ {
+       fn from(v: Vec<crate::ln::msgs::NodeAnnouncement>) -> Self {
+               let datalen = v.len();
+               let data = Box::into_raw(v.into_boxed_slice());
+               Self { datalen, data: unsafe { (*data).as_mut_ptr() } }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CVec_NodeAnnouncementZ_free(_res: CVec_NodeAnnouncementZ) { }
+impl Drop for CVec_NodeAnnouncementZ {
+       fn drop(&mut self) {
+               if self.datalen == 0 { return; }
+               unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) };
+       }
+}
+impl Clone for CVec_NodeAnnouncementZ {
+       fn clone(&self) -> Self {
+               let mut res = Vec::new();
+               if self.datalen == 0 { return Self::from(res); }
+               res.extend_from_slice(unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) });
+               Self::from(res)
+       }
+}
+#[repr(C)]
+pub union CResult_NoneLightningErrorZPtr {
+       /// Note that this value is always NULL, as there are no contents in the OK variant
+       pub result: *mut std::ffi::c_void,
+       pub err: *mut crate::ln::msgs::LightningError,
+}
+#[repr(C)]
+pub struct CResult_NoneLightningErrorZ {
+       pub contents: CResult_NoneLightningErrorZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_NoneLightningErrorZ_ok() -> CResult_NoneLightningErrorZ {
+       CResult_NoneLightningErrorZ {
+               contents: CResult_NoneLightningErrorZPtr {
+                       result: std::ptr::null_mut(),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_NoneLightningErrorZ_err(e: crate::ln::msgs::LightningError) -> CResult_NoneLightningErrorZ {
+       CResult_NoneLightningErrorZ {
+               contents: CResult_NoneLightningErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_NoneLightningErrorZ_free(_res: CResult_NoneLightningErrorZ) { }
+impl Drop for CResult_NoneLightningErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<u8, crate::ln::msgs::LightningError>> for CResult_NoneLightningErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<u8, crate::ln::msgs::LightningError>) -> Self {
+               let contents = if o.result_ok {
+                       let _ = unsafe { Box::from_raw(o.contents.result) };
+                       o.contents.result = std::ptr::null_mut();
+                       CResult_NoneLightningErrorZPtr { result: std::ptr::null_mut() }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_NoneLightningErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_NoneLightningErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_NoneLightningErrorZPtr {
+                               result: std::ptr::null_mut()
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_NoneLightningErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::LightningError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_NoneLightningErrorZ_clone(orig: &CResult_NoneLightningErrorZ) -> CResult_NoneLightningErrorZ { orig.clone() }
+#[repr(C)]
+pub struct CVec_MessageSendEventZ {
+       pub data: *mut crate::util::events::MessageSendEvent,
+       pub datalen: usize
+}
+impl CVec_MessageSendEventZ {
+       #[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec<crate::util::events::MessageSendEvent> {
+               if self.datalen == 0 { return Vec::new(); }
+               let ret = unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }.into();
+               self.data = std::ptr::null_mut();
+               self.datalen = 0;
+               ret
+       }
+       #[allow(unused)] pub(crate) fn as_slice(&self) -> &[crate::util::events::MessageSendEvent] {
+               unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) }
+       }
+}
+impl From<Vec<crate::util::events::MessageSendEvent>> for CVec_MessageSendEventZ {
+       fn from(v: Vec<crate::util::events::MessageSendEvent>) -> Self {
+               let datalen = v.len();
+               let data = Box::into_raw(v.into_boxed_slice());
+               Self { datalen, data: unsafe { (*data).as_mut_ptr() } }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CVec_MessageSendEventZ_free(_res: CVec_MessageSendEventZ) { }
+impl Drop for CVec_MessageSendEventZ {
+       fn drop(&mut self) {
+               if self.datalen == 0 { return; }
+               unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) };
+       }
+}
+impl Clone for CVec_MessageSendEventZ {
+       fn clone(&self) -> Self {
+               let mut res = Vec::new();
+               if self.datalen == 0 { return Self::from(res); }
+               res.extend_from_slice(unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) });
+               Self::from(res)
+       }
+}
+#[repr(C)]
+pub union CResult_DirectionalChannelInfoDecodeErrorZPtr {
+       pub result: *mut crate::routing::network_graph::DirectionalChannelInfo,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_DirectionalChannelInfoDecodeErrorZ {
+       pub contents: CResult_DirectionalChannelInfoDecodeErrorZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_DirectionalChannelInfoDecodeErrorZ_ok(o: crate::routing::network_graph::DirectionalChannelInfo) -> CResult_DirectionalChannelInfoDecodeErrorZ {
+       CResult_DirectionalChannelInfoDecodeErrorZ {
+               contents: CResult_DirectionalChannelInfoDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_DirectionalChannelInfoDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_DirectionalChannelInfoDecodeErrorZ {
+       CResult_DirectionalChannelInfoDecodeErrorZ {
+               contents: CResult_DirectionalChannelInfoDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_DirectionalChannelInfoDecodeErrorZ_free(_res: CResult_DirectionalChannelInfoDecodeErrorZ) { }
+impl Drop for CResult_DirectionalChannelInfoDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::routing::network_graph::DirectionalChannelInfo, crate::ln::msgs::DecodeError>> for CResult_DirectionalChannelInfoDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::routing::network_graph::DirectionalChannelInfo, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_DirectionalChannelInfoDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_DirectionalChannelInfoDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_DirectionalChannelInfoDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_DirectionalChannelInfoDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::routing::network_graph::DirectionalChannelInfo>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_DirectionalChannelInfoDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_DirectionalChannelInfoDecodeErrorZ_clone(orig: &CResult_DirectionalChannelInfoDecodeErrorZ) -> CResult_DirectionalChannelInfoDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_ChannelInfoDecodeErrorZPtr {
+       pub result: *mut crate::routing::network_graph::ChannelInfo,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_ChannelInfoDecodeErrorZ {
+       pub contents: CResult_ChannelInfoDecodeErrorZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_ChannelInfoDecodeErrorZ_ok(o: crate::routing::network_graph::ChannelInfo) -> CResult_ChannelInfoDecodeErrorZ {
+       CResult_ChannelInfoDecodeErrorZ {
+               contents: CResult_ChannelInfoDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_ChannelInfoDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_ChannelInfoDecodeErrorZ {
+       CResult_ChannelInfoDecodeErrorZ {
+               contents: CResult_ChannelInfoDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_ChannelInfoDecodeErrorZ_free(_res: CResult_ChannelInfoDecodeErrorZ) { }
+impl Drop for CResult_ChannelInfoDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::routing::network_graph::ChannelInfo, crate::ln::msgs::DecodeError>> for CResult_ChannelInfoDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::routing::network_graph::ChannelInfo, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_ChannelInfoDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_ChannelInfoDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_ChannelInfoDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_ChannelInfoDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::routing::network_graph::ChannelInfo>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_ChannelInfoDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_ChannelInfoDecodeErrorZ_clone(orig: &CResult_ChannelInfoDecodeErrorZ) -> CResult_ChannelInfoDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_RoutingFeesDecodeErrorZPtr {
+       pub result: *mut crate::routing::network_graph::RoutingFees,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_RoutingFeesDecodeErrorZ {
+       pub contents: CResult_RoutingFeesDecodeErrorZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_RoutingFeesDecodeErrorZ_ok(o: crate::routing::network_graph::RoutingFees) -> CResult_RoutingFeesDecodeErrorZ {
+       CResult_RoutingFeesDecodeErrorZ {
+               contents: CResult_RoutingFeesDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_RoutingFeesDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_RoutingFeesDecodeErrorZ {
+       CResult_RoutingFeesDecodeErrorZ {
+               contents: CResult_RoutingFeesDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_RoutingFeesDecodeErrorZ_free(_res: CResult_RoutingFeesDecodeErrorZ) { }
+impl Drop for CResult_RoutingFeesDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::routing::network_graph::RoutingFees, crate::ln::msgs::DecodeError>> for CResult_RoutingFeesDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::routing::network_graph::RoutingFees, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_RoutingFeesDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_RoutingFeesDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_RoutingFeesDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_RoutingFeesDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::routing::network_graph::RoutingFees>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_RoutingFeesDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_RoutingFeesDecodeErrorZ_clone(orig: &CResult_RoutingFeesDecodeErrorZ) -> CResult_RoutingFeesDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub struct CVec_NetAddressZ {
+       pub data: *mut crate::ln::msgs::NetAddress,
+       pub datalen: usize
+}
+impl CVec_NetAddressZ {
+       #[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec<crate::ln::msgs::NetAddress> {
+               if self.datalen == 0 { return Vec::new(); }
+               let ret = unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }.into();
+               self.data = std::ptr::null_mut();
+               self.datalen = 0;
+               ret
+       }
+       #[allow(unused)] pub(crate) fn as_slice(&self) -> &[crate::ln::msgs::NetAddress] {
+               unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) }
+       }
+}
+impl From<Vec<crate::ln::msgs::NetAddress>> for CVec_NetAddressZ {
+       fn from(v: Vec<crate::ln::msgs::NetAddress>) -> Self {
+               let datalen = v.len();
+               let data = Box::into_raw(v.into_boxed_slice());
+               Self { datalen, data: unsafe { (*data).as_mut_ptr() } }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CVec_NetAddressZ_free(_res: CVec_NetAddressZ) { }
+impl Drop for CVec_NetAddressZ {
+       fn drop(&mut self) {
+               if self.datalen == 0 { return; }
+               unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) };
+       }
+}
+impl Clone for CVec_NetAddressZ {
+       fn clone(&self) -> Self {
+               let mut res = Vec::new();
+               if self.datalen == 0 { return Self::from(res); }
+               res.extend_from_slice(unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) });
+               Self::from(res)
+       }
+}
+#[repr(C)]
+pub union CResult_NodeAnnouncementInfoDecodeErrorZPtr {
+       pub result: *mut crate::routing::network_graph::NodeAnnouncementInfo,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_NodeAnnouncementInfoDecodeErrorZ {
+       pub contents: CResult_NodeAnnouncementInfoDecodeErrorZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_NodeAnnouncementInfoDecodeErrorZ_ok(o: crate::routing::network_graph::NodeAnnouncementInfo) -> CResult_NodeAnnouncementInfoDecodeErrorZ {
+       CResult_NodeAnnouncementInfoDecodeErrorZ {
+               contents: CResult_NodeAnnouncementInfoDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_NodeAnnouncementInfoDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_NodeAnnouncementInfoDecodeErrorZ {
+       CResult_NodeAnnouncementInfoDecodeErrorZ {
+               contents: CResult_NodeAnnouncementInfoDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_NodeAnnouncementInfoDecodeErrorZ_free(_res: CResult_NodeAnnouncementInfoDecodeErrorZ) { }
+impl Drop for CResult_NodeAnnouncementInfoDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::routing::network_graph::NodeAnnouncementInfo, crate::ln::msgs::DecodeError>> for CResult_NodeAnnouncementInfoDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::routing::network_graph::NodeAnnouncementInfo, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_NodeAnnouncementInfoDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_NodeAnnouncementInfoDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_NodeAnnouncementInfoDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_NodeAnnouncementInfoDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::routing::network_graph::NodeAnnouncementInfo>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_NodeAnnouncementInfoDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_NodeAnnouncementInfoDecodeErrorZ_clone(orig: &CResult_NodeAnnouncementInfoDecodeErrorZ) -> CResult_NodeAnnouncementInfoDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub struct CVec_u64Z {
+       pub data: *mut u64,
+       pub datalen: usize
+}
+impl CVec_u64Z {
+       #[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec<u64> {
+               if self.datalen == 0 { return Vec::new(); }
+               let ret = unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }.into();
+               self.data = std::ptr::null_mut();
+               self.datalen = 0;
+               ret
+       }
+       #[allow(unused)] pub(crate) fn as_slice(&self) -> &[u64] {
+               unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) }
+       }
+}
+impl From<Vec<u64>> for CVec_u64Z {
+       fn from(v: Vec<u64>) -> Self {
+               let datalen = v.len();
+               let data = Box::into_raw(v.into_boxed_slice());
+               Self { datalen, data: unsafe { (*data).as_mut_ptr() } }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CVec_u64Z_free(_res: CVec_u64Z) { }
+impl Drop for CVec_u64Z {
+       fn drop(&mut self) {
+               if self.datalen == 0 { return; }
+               unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) };
+       }
+}
+impl Clone for CVec_u64Z {
+       fn clone(&self) -> Self {
+               let mut res = Vec::new();
+               if self.datalen == 0 { return Self::from(res); }
+               res.extend_from_slice(unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) });
+               Self::from(res)
+       }
+}
+#[repr(C)]
+pub union CResult_NodeInfoDecodeErrorZPtr {
+       pub result: *mut crate::routing::network_graph::NodeInfo,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_NodeInfoDecodeErrorZ {
+       pub contents: CResult_NodeInfoDecodeErrorZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_NodeInfoDecodeErrorZ_ok(o: crate::routing::network_graph::NodeInfo) -> CResult_NodeInfoDecodeErrorZ {
+       CResult_NodeInfoDecodeErrorZ {
+               contents: CResult_NodeInfoDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_NodeInfoDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_NodeInfoDecodeErrorZ {
+       CResult_NodeInfoDecodeErrorZ {
+               contents: CResult_NodeInfoDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_NodeInfoDecodeErrorZ_free(_res: CResult_NodeInfoDecodeErrorZ) { }
+impl Drop for CResult_NodeInfoDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::routing::network_graph::NodeInfo, crate::ln::msgs::DecodeError>> for CResult_NodeInfoDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::routing::network_graph::NodeInfo, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_NodeInfoDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_NodeInfoDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_NodeInfoDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_NodeInfoDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::routing::network_graph::NodeInfo>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_NodeInfoDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_NodeInfoDecodeErrorZ_clone(orig: &CResult_NodeInfoDecodeErrorZ) -> CResult_NodeInfoDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_NetworkGraphDecodeErrorZPtr {
+       pub result: *mut crate::routing::network_graph::NetworkGraph,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_NetworkGraphDecodeErrorZ {
+       pub contents: CResult_NetworkGraphDecodeErrorZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_NetworkGraphDecodeErrorZ_ok(o: crate::routing::network_graph::NetworkGraph) -> CResult_NetworkGraphDecodeErrorZ {
+       CResult_NetworkGraphDecodeErrorZ {
+               contents: CResult_NetworkGraphDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_NetworkGraphDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_NetworkGraphDecodeErrorZ {
+       CResult_NetworkGraphDecodeErrorZ {
+               contents: CResult_NetworkGraphDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_NetworkGraphDecodeErrorZ_free(_res: CResult_NetworkGraphDecodeErrorZ) { }
+impl Drop for CResult_NetworkGraphDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::routing::network_graph::NetworkGraph, crate::ln::msgs::DecodeError>> for CResult_NetworkGraphDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::routing::network_graph::NetworkGraph, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_NetworkGraphDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_NetworkGraphDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_NetworkGraphDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_NetworkGraphDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::routing::network_graph::NetworkGraph>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_NetworkGraphDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_NetworkGraphDecodeErrorZ_clone(orig: &CResult_NetworkGraphDecodeErrorZ) -> CResult_NetworkGraphDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub struct C2Tuple_usizeTransactionZ {
+       pub a: usize,
+       pub b: crate::c_types::Transaction,
+}
+impl From<(usize, crate::c_types::Transaction)> for C2Tuple_usizeTransactionZ {
+       fn from (tup: (usize, crate::c_types::Transaction)) -> Self {
+               Self {
+                       a: tup.0,
+                       b: tup.1,
+               }
+       }
+}
+impl C2Tuple_usizeTransactionZ {
+       #[allow(unused)] pub(crate) fn to_rust(mut self) -> (usize, crate::c_types::Transaction) {
+               (self.a, self.b)
+       }
+}
+#[no_mangle]
+pub extern "C" fn C2Tuple_usizeTransactionZ_new(a: usize, b: crate::c_types::Transaction) -> C2Tuple_usizeTransactionZ {
+       C2Tuple_usizeTransactionZ { a, b, }
+}
+
+#[no_mangle]
+pub extern "C" fn C2Tuple_usizeTransactionZ_free(_res: C2Tuple_usizeTransactionZ) { }
+#[repr(C)]
+pub struct CVec_C2Tuple_usizeTransactionZZ {
+       pub data: *mut crate::c_types::derived::C2Tuple_usizeTransactionZ,
+       pub datalen: usize
+}
+impl CVec_C2Tuple_usizeTransactionZZ {
+       #[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec<crate::c_types::derived::C2Tuple_usizeTransactionZ> {
+               if self.datalen == 0 { return Vec::new(); }
+               let ret = unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }.into();
+               self.data = std::ptr::null_mut();
+               self.datalen = 0;
+               ret
+       }
+       #[allow(unused)] pub(crate) fn as_slice(&self) -> &[crate::c_types::derived::C2Tuple_usizeTransactionZ] {
+               unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) }
+       }
+}
+impl From<Vec<crate::c_types::derived::C2Tuple_usizeTransactionZ>> for CVec_C2Tuple_usizeTransactionZZ {
+       fn from(v: Vec<crate::c_types::derived::C2Tuple_usizeTransactionZ>) -> Self {
+               let datalen = v.len();
+               let data = Box::into_raw(v.into_boxed_slice());
+               Self { datalen, data: unsafe { (*data).as_mut_ptr() } }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CVec_C2Tuple_usizeTransactionZZ_free(_res: CVec_C2Tuple_usizeTransactionZZ) { }
+impl Drop for CVec_C2Tuple_usizeTransactionZZ {
+       fn drop(&mut self) {
+               if self.datalen == 0 { return; }
+               unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) };
+       }
+}
+#[repr(C)]
+pub union CResult_NoneChannelMonitorUpdateErrZPtr {
+       /// Note that this value is always NULL, as there are no contents in the OK variant
+       pub result: *mut std::ffi::c_void,
+       pub err: *mut crate::chain::channelmonitor::ChannelMonitorUpdateErr,
+}
+#[repr(C)]
+pub struct CResult_NoneChannelMonitorUpdateErrZ {
+       pub contents: CResult_NoneChannelMonitorUpdateErrZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_NoneChannelMonitorUpdateErrZ_ok() -> CResult_NoneChannelMonitorUpdateErrZ {
+       CResult_NoneChannelMonitorUpdateErrZ {
+               contents: CResult_NoneChannelMonitorUpdateErrZPtr {
+                       result: std::ptr::null_mut(),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_NoneChannelMonitorUpdateErrZ_err(e: crate::chain::channelmonitor::ChannelMonitorUpdateErr) -> CResult_NoneChannelMonitorUpdateErrZ {
+       CResult_NoneChannelMonitorUpdateErrZ {
+               contents: CResult_NoneChannelMonitorUpdateErrZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_NoneChannelMonitorUpdateErrZ_free(_res: CResult_NoneChannelMonitorUpdateErrZ) { }
+impl Drop for CResult_NoneChannelMonitorUpdateErrZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<u8, crate::chain::channelmonitor::ChannelMonitorUpdateErr>> for CResult_NoneChannelMonitorUpdateErrZ {
+       fn from(mut o: crate::c_types::CResultTempl<u8, crate::chain::channelmonitor::ChannelMonitorUpdateErr>) -> Self {
+               let contents = if o.result_ok {
+                       let _ = unsafe { Box::from_raw(o.contents.result) };
+                       o.contents.result = std::ptr::null_mut();
+                       CResult_NoneChannelMonitorUpdateErrZPtr { result: std::ptr::null_mut() }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_NoneChannelMonitorUpdateErrZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_NoneChannelMonitorUpdateErrZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_NoneChannelMonitorUpdateErrZPtr {
+                               result: std::ptr::null_mut()
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_NoneChannelMonitorUpdateErrZPtr {
+                               err: Box::into_raw(Box::new(<crate::chain::channelmonitor::ChannelMonitorUpdateErr>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_NoneChannelMonitorUpdateErrZ_clone(orig: &CResult_NoneChannelMonitorUpdateErrZ) -> CResult_NoneChannelMonitorUpdateErrZ { orig.clone() }
+#[repr(C)]
+pub struct CVec_MonitorEventZ {
+       pub data: *mut crate::chain::channelmonitor::MonitorEvent,
+       pub datalen: usize
+}
+impl CVec_MonitorEventZ {
+       #[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec<crate::chain::channelmonitor::MonitorEvent> {
+               if self.datalen == 0 { return Vec::new(); }
+               let ret = unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }.into();
+               self.data = std::ptr::null_mut();
+               self.datalen = 0;
+               ret
+       }
+       #[allow(unused)] pub(crate) fn as_slice(&self) -> &[crate::chain::channelmonitor::MonitorEvent] {
+               unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) }
+       }
+}
+impl From<Vec<crate::chain::channelmonitor::MonitorEvent>> for CVec_MonitorEventZ {
+       fn from(v: Vec<crate::chain::channelmonitor::MonitorEvent>) -> Self {
+               let datalen = v.len();
+               let data = Box::into_raw(v.into_boxed_slice());
+               Self { datalen, data: unsafe { (*data).as_mut_ptr() } }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CVec_MonitorEventZ_free(_res: CVec_MonitorEventZ) { }
+impl Drop for CVec_MonitorEventZ {
+       fn drop(&mut self) {
+               if self.datalen == 0 { return; }
+               unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) };
+       }
+}
+impl Clone for CVec_MonitorEventZ {
+       fn clone(&self) -> Self {
+               let mut res = Vec::new();
+               if self.datalen == 0 { return Self::from(res); }
+               res.extend_from_slice(unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) });
+               Self::from(res)
+       }
+}
+#[repr(C)]
+pub struct CVec_EventZ {
+       pub data: *mut crate::util::events::Event,
+       pub datalen: usize
+}
+impl CVec_EventZ {
+       #[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec<crate::util::events::Event> {
+               if self.datalen == 0 { return Vec::new(); }
+               let ret = unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }.into();
+               self.data = std::ptr::null_mut();
+               self.datalen = 0;
+               ret
+       }
+       #[allow(unused)] pub(crate) fn as_slice(&self) -> &[crate::util::events::Event] {
+               unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) }
+       }
+}
+impl From<Vec<crate::util::events::Event>> for CVec_EventZ {
+       fn from(v: Vec<crate::util::events::Event>) -> Self {
+               let datalen = v.len();
+               let data = Box::into_raw(v.into_boxed_slice());
+               Self { datalen, data: unsafe { (*data).as_mut_ptr() } }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CVec_EventZ_free(_res: CVec_EventZ) { }
+impl Drop for CVec_EventZ {
+       fn drop(&mut self) {
+               if self.datalen == 0 { return; }
+               unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) };
+       }
+}
+impl Clone for CVec_EventZ {
+       fn clone(&self) -> Self {
+               let mut res = Vec::new();
+               if self.datalen == 0 { return Self::from(res); }
+               res.extend_from_slice(unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) });
+               Self::from(res)
+       }
+}
+#[repr(C)]
+pub union CResult_OutPointDecodeErrorZPtr {
+       pub result: *mut crate::chain::transaction::OutPoint,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_OutPointDecodeErrorZ {
+       pub contents: CResult_OutPointDecodeErrorZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_OutPointDecodeErrorZ_ok(o: crate::chain::transaction::OutPoint) -> CResult_OutPointDecodeErrorZ {
+       CResult_OutPointDecodeErrorZ {
+               contents: CResult_OutPointDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_OutPointDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_OutPointDecodeErrorZ {
+       CResult_OutPointDecodeErrorZ {
+               contents: CResult_OutPointDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_OutPointDecodeErrorZ_free(_res: CResult_OutPointDecodeErrorZ) { }
+impl Drop for CResult_OutPointDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::chain::transaction::OutPoint, crate::ln::msgs::DecodeError>> for CResult_OutPointDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::chain::transaction::OutPoint, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_OutPointDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_OutPointDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_OutPointDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_OutPointDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::chain::transaction::OutPoint>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_OutPointDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_OutPointDecodeErrorZ_clone(orig: &CResult_OutPointDecodeErrorZ) -> CResult_OutPointDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_ChannelMonitorUpdateDecodeErrorZPtr {
+       pub result: *mut crate::chain::channelmonitor::ChannelMonitorUpdate,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_ChannelMonitorUpdateDecodeErrorZ {
+       pub contents: CResult_ChannelMonitorUpdateDecodeErrorZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_ChannelMonitorUpdateDecodeErrorZ_ok(o: crate::chain::channelmonitor::ChannelMonitorUpdate) -> CResult_ChannelMonitorUpdateDecodeErrorZ {
+       CResult_ChannelMonitorUpdateDecodeErrorZ {
+               contents: CResult_ChannelMonitorUpdateDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_ChannelMonitorUpdateDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_ChannelMonitorUpdateDecodeErrorZ {
+       CResult_ChannelMonitorUpdateDecodeErrorZ {
+               contents: CResult_ChannelMonitorUpdateDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_ChannelMonitorUpdateDecodeErrorZ_free(_res: CResult_ChannelMonitorUpdateDecodeErrorZ) { }
+impl Drop for CResult_ChannelMonitorUpdateDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::chain::channelmonitor::ChannelMonitorUpdate, crate::ln::msgs::DecodeError>> for CResult_ChannelMonitorUpdateDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::chain::channelmonitor::ChannelMonitorUpdate, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_ChannelMonitorUpdateDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_ChannelMonitorUpdateDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_ChannelMonitorUpdateDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_ChannelMonitorUpdateDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::chain::channelmonitor::ChannelMonitorUpdate>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_ChannelMonitorUpdateDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_ChannelMonitorUpdateDecodeErrorZ_clone(orig: &CResult_ChannelMonitorUpdateDecodeErrorZ) -> CResult_ChannelMonitorUpdateDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_HTLCUpdateDecodeErrorZPtr {
+       pub result: *mut crate::chain::channelmonitor::HTLCUpdate,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_HTLCUpdateDecodeErrorZ {
+       pub contents: CResult_HTLCUpdateDecodeErrorZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_HTLCUpdateDecodeErrorZ_ok(o: crate::chain::channelmonitor::HTLCUpdate) -> CResult_HTLCUpdateDecodeErrorZ {
+       CResult_HTLCUpdateDecodeErrorZ {
+               contents: CResult_HTLCUpdateDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_HTLCUpdateDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_HTLCUpdateDecodeErrorZ {
+       CResult_HTLCUpdateDecodeErrorZ {
+               contents: CResult_HTLCUpdateDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_HTLCUpdateDecodeErrorZ_free(_res: CResult_HTLCUpdateDecodeErrorZ) { }
+impl Drop for CResult_HTLCUpdateDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::chain::channelmonitor::HTLCUpdate, crate::ln::msgs::DecodeError>> for CResult_HTLCUpdateDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::chain::channelmonitor::HTLCUpdate, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_HTLCUpdateDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_HTLCUpdateDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_HTLCUpdateDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_HTLCUpdateDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::chain::channelmonitor::HTLCUpdate>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_HTLCUpdateDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_HTLCUpdateDecodeErrorZ_clone(orig: &CResult_HTLCUpdateDecodeErrorZ) -> CResult_HTLCUpdateDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_NoneMonitorUpdateErrorZPtr {
+       /// Note that this value is always NULL, as there are no contents in the OK variant
+       pub result: *mut std::ffi::c_void,
+       pub err: *mut crate::chain::channelmonitor::MonitorUpdateError,
+}
+#[repr(C)]
+pub struct CResult_NoneMonitorUpdateErrorZ {
+       pub contents: CResult_NoneMonitorUpdateErrorZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_NoneMonitorUpdateErrorZ_ok() -> CResult_NoneMonitorUpdateErrorZ {
+       CResult_NoneMonitorUpdateErrorZ {
+               contents: CResult_NoneMonitorUpdateErrorZPtr {
+                       result: std::ptr::null_mut(),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_NoneMonitorUpdateErrorZ_err(e: crate::chain::channelmonitor::MonitorUpdateError) -> CResult_NoneMonitorUpdateErrorZ {
+       CResult_NoneMonitorUpdateErrorZ {
+               contents: CResult_NoneMonitorUpdateErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_NoneMonitorUpdateErrorZ_free(_res: CResult_NoneMonitorUpdateErrorZ) { }
+impl Drop for CResult_NoneMonitorUpdateErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<u8, crate::chain::channelmonitor::MonitorUpdateError>> for CResult_NoneMonitorUpdateErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<u8, crate::chain::channelmonitor::MonitorUpdateError>) -> Self {
+               let contents = if o.result_ok {
+                       let _ = unsafe { Box::from_raw(o.contents.result) };
+                       o.contents.result = std::ptr::null_mut();
+                       CResult_NoneMonitorUpdateErrorZPtr { result: std::ptr::null_mut() }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_NoneMonitorUpdateErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_NoneMonitorUpdateErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_NoneMonitorUpdateErrorZPtr {
+                               result: std::ptr::null_mut()
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_NoneMonitorUpdateErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::chain::channelmonitor::MonitorUpdateError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_NoneMonitorUpdateErrorZ_clone(orig: &CResult_NoneMonitorUpdateErrorZ) -> CResult_NoneMonitorUpdateErrorZ { orig.clone() }
+#[repr(C)]
+pub struct C2Tuple_OutPointScriptZ {
+       pub a: crate::chain::transaction::OutPoint,
+       pub b: crate::c_types::derived::CVec_u8Z,
+}
+impl From<(crate::chain::transaction::OutPoint, crate::c_types::derived::CVec_u8Z)> for C2Tuple_OutPointScriptZ {
+       fn from (tup: (crate::chain::transaction::OutPoint, crate::c_types::derived::CVec_u8Z)) -> Self {
+               Self {
+                       a: tup.0,
+                       b: tup.1,
+               }
+       }
+}
+impl C2Tuple_OutPointScriptZ {
+       #[allow(unused)] pub(crate) fn to_rust(mut self) -> (crate::chain::transaction::OutPoint, crate::c_types::derived::CVec_u8Z) {
+               (self.a, self.b)
+       }
+}
+impl Clone for C2Tuple_OutPointScriptZ {
+       fn clone(&self) -> Self {
+               Self {
+                       a: self.a.clone(),
+                       b: self.b.clone(),
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn C2Tuple_OutPointScriptZ_clone(orig: &C2Tuple_OutPointScriptZ) -> C2Tuple_OutPointScriptZ { orig.clone() }
+#[no_mangle]
+pub extern "C" fn C2Tuple_OutPointScriptZ_new(a: crate::chain::transaction::OutPoint, b: crate::c_types::derived::CVec_u8Z) -> C2Tuple_OutPointScriptZ {
+       C2Tuple_OutPointScriptZ { a, b, }
+}
+
+#[no_mangle]
+pub extern "C" fn C2Tuple_OutPointScriptZ_free(_res: C2Tuple_OutPointScriptZ) { }
+#[repr(C)]
+pub struct CVec_TransactionZ {
+       pub data: *mut crate::c_types::Transaction,
+       pub datalen: usize
+}
+impl CVec_TransactionZ {
+       #[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec<crate::c_types::Transaction> {
+               if self.datalen == 0 { return Vec::new(); }
+               let ret = unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }.into();
+               self.data = std::ptr::null_mut();
+               self.datalen = 0;
+               ret
+       }
+       #[allow(unused)] pub(crate) fn as_slice(&self) -> &[crate::c_types::Transaction] {
+               unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) }
+       }
+}
+impl From<Vec<crate::c_types::Transaction>> for CVec_TransactionZ {
+       fn from(v: Vec<crate::c_types::Transaction>) -> Self {
+               let datalen = v.len();
+               let data = Box::into_raw(v.into_boxed_slice());
+               Self { datalen, data: unsafe { (*data).as_mut_ptr() } }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CVec_TransactionZ_free(_res: CVec_TransactionZ) { }
+impl Drop for CVec_TransactionZ {
+       fn drop(&mut self) {
+               if self.datalen == 0 { return; }
+               unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) };
+       }
+}
+#[repr(C)]
+pub struct C2Tuple_u32TxOutZ {
+       pub a: u32,
+       pub b: crate::c_types::TxOut,
+}
+impl From<(u32, crate::c_types::TxOut)> for C2Tuple_u32TxOutZ {
+       fn from (tup: (u32, crate::c_types::TxOut)) -> Self {
+               Self {
+                       a: tup.0,
+                       b: tup.1,
+               }
+       }
+}
+impl C2Tuple_u32TxOutZ {
+       #[allow(unused)] pub(crate) fn to_rust(mut self) -> (u32, crate::c_types::TxOut) {
+               (self.a, self.b)
+       }
+}
+impl Clone for C2Tuple_u32TxOutZ {
+       fn clone(&self) -> Self {
+               Self {
+                       a: self.a.clone(),
+                       b: self.b.clone(),
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn C2Tuple_u32TxOutZ_clone(orig: &C2Tuple_u32TxOutZ) -> C2Tuple_u32TxOutZ { orig.clone() }
+#[no_mangle]
+pub extern "C" fn C2Tuple_u32TxOutZ_new(a: u32, b: crate::c_types::TxOut) -> C2Tuple_u32TxOutZ {
+       C2Tuple_u32TxOutZ { a, b, }
+}
+
+#[no_mangle]
+pub extern "C" fn C2Tuple_u32TxOutZ_free(_res: C2Tuple_u32TxOutZ) { }
+#[repr(C)]
+pub struct CVec_C2Tuple_u32TxOutZZ {
+       pub data: *mut crate::c_types::derived::C2Tuple_u32TxOutZ,
+       pub datalen: usize
+}
+impl CVec_C2Tuple_u32TxOutZZ {
+       #[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec<crate::c_types::derived::C2Tuple_u32TxOutZ> {
+               if self.datalen == 0 { return Vec::new(); }
+               let ret = unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }.into();
+               self.data = std::ptr::null_mut();
+               self.datalen = 0;
+               ret
+       }
+       #[allow(unused)] pub(crate) fn as_slice(&self) -> &[crate::c_types::derived::C2Tuple_u32TxOutZ] {
+               unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) }
+       }
+}
+impl From<Vec<crate::c_types::derived::C2Tuple_u32TxOutZ>> for CVec_C2Tuple_u32TxOutZZ {
+       fn from(v: Vec<crate::c_types::derived::C2Tuple_u32TxOutZ>) -> Self {
+               let datalen = v.len();
+               let data = Box::into_raw(v.into_boxed_slice());
+               Self { datalen, data: unsafe { (*data).as_mut_ptr() } }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CVec_C2Tuple_u32TxOutZZ_free(_res: CVec_C2Tuple_u32TxOutZZ) { }
+impl Drop for CVec_C2Tuple_u32TxOutZZ {
+       fn drop(&mut self) {
+               if self.datalen == 0 { return; }
+               unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) };
+       }
+}
+impl Clone for CVec_C2Tuple_u32TxOutZZ {
+       fn clone(&self) -> Self {
+               let mut res = Vec::new();
+               if self.datalen == 0 { return Self::from(res); }
+               res.extend_from_slice(unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) });
+               Self::from(res)
+       }
+}
+#[repr(C)]
+pub struct C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ {
+       pub a: crate::c_types::ThirtyTwoBytes,
+       pub b: crate::c_types::derived::CVec_C2Tuple_u32TxOutZZ,
+}
+impl From<(crate::c_types::ThirtyTwoBytes, crate::c_types::derived::CVec_C2Tuple_u32TxOutZZ)> for C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ {
+       fn from (tup: (crate::c_types::ThirtyTwoBytes, crate::c_types::derived::CVec_C2Tuple_u32TxOutZZ)) -> Self {
+               Self {
+                       a: tup.0,
+                       b: tup.1,
+               }
+       }
+}
+impl C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ {
+       #[allow(unused)] pub(crate) fn to_rust(mut self) -> (crate::c_types::ThirtyTwoBytes, crate::c_types::derived::CVec_C2Tuple_u32TxOutZZ) {
+               (self.a, self.b)
+       }
+}
+#[no_mangle]
+pub extern "C" fn C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ_new(a: crate::c_types::ThirtyTwoBytes, b: crate::c_types::derived::CVec_C2Tuple_u32TxOutZZ) -> C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ {
+       C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ { a, b, }
+}
+
+#[no_mangle]
+pub extern "C" fn C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ_free(_res: C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ) { }
+#[repr(C)]
+pub struct CVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ {
+       pub data: *mut crate::c_types::derived::C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ,
+       pub datalen: usize
+}
+impl CVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ {
+       #[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec<crate::c_types::derived::C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ> {
+               if self.datalen == 0 { return Vec::new(); }
+               let ret = unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }.into();
+               self.data = std::ptr::null_mut();
+               self.datalen = 0;
+               ret
+       }
+       #[allow(unused)] pub(crate) fn as_slice(&self) -> &[crate::c_types::derived::C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ] {
+               unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) }
+       }
+}
+impl From<Vec<crate::c_types::derived::C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ>> for CVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ {
+       fn from(v: Vec<crate::c_types::derived::C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ>) -> Self {
+               let datalen = v.len();
+               let data = Box::into_raw(v.into_boxed_slice());
+               Self { datalen, data: unsafe { (*data).as_mut_ptr() } }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ_free(_res: CVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ) { }
+impl Drop for CVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ {
+       fn drop(&mut self) {
+               if self.datalen == 0 { return; }
+               unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) };
+       }
+}
+#[repr(C)]
+pub struct C2Tuple_BlockHashChannelMonitorZ {
+       pub a: crate::c_types::ThirtyTwoBytes,
+       pub b: crate::chain::channelmonitor::ChannelMonitor,
+}
+impl From<(crate::c_types::ThirtyTwoBytes, crate::chain::channelmonitor::ChannelMonitor)> for C2Tuple_BlockHashChannelMonitorZ {
+       fn from (tup: (crate::c_types::ThirtyTwoBytes, crate::chain::channelmonitor::ChannelMonitor)) -> Self {
+               Self {
+                       a: tup.0,
+                       b: tup.1,
+               }
+       }
+}
+impl C2Tuple_BlockHashChannelMonitorZ {
+       #[allow(unused)] pub(crate) fn to_rust(mut self) -> (crate::c_types::ThirtyTwoBytes, crate::chain::channelmonitor::ChannelMonitor) {
+               (self.a, self.b)
+       }
+}
+#[no_mangle]
+pub extern "C" fn C2Tuple_BlockHashChannelMonitorZ_new(a: crate::c_types::ThirtyTwoBytes, b: crate::chain::channelmonitor::ChannelMonitor) -> C2Tuple_BlockHashChannelMonitorZ {
+       C2Tuple_BlockHashChannelMonitorZ { a, b, }
+}
+
+#[no_mangle]
+pub extern "C" fn C2Tuple_BlockHashChannelMonitorZ_free(_res: C2Tuple_BlockHashChannelMonitorZ) { }
+#[repr(C)]
+pub union CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZPtr {
+       pub result: *mut crate::c_types::derived::C2Tuple_BlockHashChannelMonitorZ,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ {
+       pub contents: CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_ok(o: crate::c_types::derived::C2Tuple_BlockHashChannelMonitorZ) -> CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ {
+       CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ {
+               contents: CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ {
+       CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ {
+               contents: CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_free(_res: CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ) { }
+impl Drop for CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::c_types::derived::C2Tuple_BlockHashChannelMonitorZ, crate::ln::msgs::DecodeError>> for CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::c_types::derived::C2Tuple_BlockHashChannelMonitorZ, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+#[repr(C)]
+pub struct CVec_SpendableOutputDescriptorZ {
+       pub data: *mut crate::chain::keysinterface::SpendableOutputDescriptor,
+       pub datalen: usize
+}
+impl CVec_SpendableOutputDescriptorZ {
+       #[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec<crate::chain::keysinterface::SpendableOutputDescriptor> {
+               if self.datalen == 0 { return Vec::new(); }
+               let ret = unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }.into();
+               self.data = std::ptr::null_mut();
+               self.datalen = 0;
+               ret
+       }
+       #[allow(unused)] pub(crate) fn as_slice(&self) -> &[crate::chain::keysinterface::SpendableOutputDescriptor] {
+               unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) }
+       }
+}
+impl From<Vec<crate::chain::keysinterface::SpendableOutputDescriptor>> for CVec_SpendableOutputDescriptorZ {
+       fn from(v: Vec<crate::chain::keysinterface::SpendableOutputDescriptor>) -> Self {
+               let datalen = v.len();
+               let data = Box::into_raw(v.into_boxed_slice());
+               Self { datalen, data: unsafe { (*data).as_mut_ptr() } }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CVec_SpendableOutputDescriptorZ_free(_res: CVec_SpendableOutputDescriptorZ) { }
+impl Drop for CVec_SpendableOutputDescriptorZ {
+       fn drop(&mut self) {
+               if self.datalen == 0 { return; }
+               unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) };
+       }
+}
+impl Clone for CVec_SpendableOutputDescriptorZ {
+       fn clone(&self) -> Self {
+               let mut res = Vec::new();
+               if self.datalen == 0 { return Self::from(res); }
+               res.extend_from_slice(unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) });
+               Self::from(res)
+       }
+}
+#[repr(C)]
+pub union CResult_TxOutAccessErrorZPtr {
+       pub result: *mut crate::c_types::TxOut,
+       pub err: *mut crate::chain::AccessError,
+}
+#[repr(C)]
+pub struct CResult_TxOutAccessErrorZ {
+       pub contents: CResult_TxOutAccessErrorZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_TxOutAccessErrorZ_ok(o: crate::c_types::TxOut) -> CResult_TxOutAccessErrorZ {
+       CResult_TxOutAccessErrorZ {
+               contents: CResult_TxOutAccessErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_TxOutAccessErrorZ_err(e: crate::chain::AccessError) -> CResult_TxOutAccessErrorZ {
+       CResult_TxOutAccessErrorZ {
+               contents: CResult_TxOutAccessErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_TxOutAccessErrorZ_free(_res: CResult_TxOutAccessErrorZ) { }
+impl Drop for CResult_TxOutAccessErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::c_types::TxOut, crate::chain::AccessError>> for CResult_TxOutAccessErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::c_types::TxOut, crate::chain::AccessError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_TxOutAccessErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_TxOutAccessErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_TxOutAccessErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_TxOutAccessErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::c_types::TxOut>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_TxOutAccessErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::chain::AccessError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_TxOutAccessErrorZ_clone(orig: &CResult_TxOutAccessErrorZ) -> CResult_TxOutAccessErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_NoneAPIErrorZPtr {
+       /// Note that this value is always NULL, as there are no contents in the OK variant
+       pub result: *mut std::ffi::c_void,
+       pub err: *mut crate::util::errors::APIError,
+}
+#[repr(C)]
+pub struct CResult_NoneAPIErrorZ {
+       pub contents: CResult_NoneAPIErrorZPtr,
+       pub result_ok: bool,
+}
 #[no_mangle]
-pub type CVec_SpendableOutputDescriptorZ = crate::c_types::CVecTempl<crate::chain::keysinterface::SpendableOutputDescriptor>;
+pub extern "C" fn CResult_NoneAPIErrorZ_ok() -> CResult_NoneAPIErrorZ {
+       CResult_NoneAPIErrorZ {
+               contents: CResult_NoneAPIErrorZPtr {
+                       result: std::ptr::null_mut(),
+               },
+               result_ok: true,
+       }
+}
 #[no_mangle]
-pub static CVec_SpendableOutputDescriptorZ_free: extern "C" fn(CVec_SpendableOutputDescriptorZ) = crate::c_types::CVecTempl_free::<crate::chain::keysinterface::SpendableOutputDescriptor>;
-
+pub extern "C" fn CResult_NoneAPIErrorZ_err(e: crate::util::errors::APIError) -> CResult_NoneAPIErrorZ {
+       CResult_NoneAPIErrorZ {
+               contents: CResult_NoneAPIErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
 #[no_mangle]
-pub type CVec_MessageSendEventZ = crate::c_types::CVecTempl<crate::util::events::MessageSendEvent>;
+pub extern "C" fn CResult_NoneAPIErrorZ_free(_res: CResult_NoneAPIErrorZ) { }
+impl Drop for CResult_NoneAPIErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<u8, crate::util::errors::APIError>> for CResult_NoneAPIErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<u8, crate::util::errors::APIError>) -> Self {
+               let contents = if o.result_ok {
+                       let _ = unsafe { Box::from_raw(o.contents.result) };
+                       o.contents.result = std::ptr::null_mut();
+                       CResult_NoneAPIErrorZPtr { result: std::ptr::null_mut() }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_NoneAPIErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_NoneAPIErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_NoneAPIErrorZPtr {
+                               result: std::ptr::null_mut()
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_NoneAPIErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::util::errors::APIError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
 #[no_mangle]
-pub static CVec_MessageSendEventZ_free: extern "C" fn(CVec_MessageSendEventZ) = crate::c_types::CVecTempl_free::<crate::util::events::MessageSendEvent>;
-
+pub extern "C" fn CResult_NoneAPIErrorZ_clone(orig: &CResult_NoneAPIErrorZ) -> CResult_NoneAPIErrorZ { orig.clone() }
+#[repr(C)]
+pub struct CVec_CResult_NoneAPIErrorZZ {
+       pub data: *mut crate::c_types::derived::CResult_NoneAPIErrorZ,
+       pub datalen: usize
+}
+impl CVec_CResult_NoneAPIErrorZZ {
+       #[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec<crate::c_types::derived::CResult_NoneAPIErrorZ> {
+               if self.datalen == 0 { return Vec::new(); }
+               let ret = unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }.into();
+               self.data = std::ptr::null_mut();
+               self.datalen = 0;
+               ret
+       }
+       #[allow(unused)] pub(crate) fn as_slice(&self) -> &[crate::c_types::derived::CResult_NoneAPIErrorZ] {
+               unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) }
+       }
+}
+impl From<Vec<crate::c_types::derived::CResult_NoneAPIErrorZ>> for CVec_CResult_NoneAPIErrorZZ {
+       fn from(v: Vec<crate::c_types::derived::CResult_NoneAPIErrorZ>) -> Self {
+               let datalen = v.len();
+               let data = Box::into_raw(v.into_boxed_slice());
+               Self { datalen, data: unsafe { (*data).as_mut_ptr() } }
+       }
+}
 #[no_mangle]
-pub type CVec_EventZ = crate::c_types::CVecTempl<crate::util::events::Event>;
+pub extern "C" fn CVec_CResult_NoneAPIErrorZZ_free(_res: CVec_CResult_NoneAPIErrorZZ) { }
+impl Drop for CVec_CResult_NoneAPIErrorZZ {
+       fn drop(&mut self) {
+               if self.datalen == 0 { return; }
+               unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) };
+       }
+}
+impl Clone for CVec_CResult_NoneAPIErrorZZ {
+       fn clone(&self) -> Self {
+               let mut res = Vec::new();
+               if self.datalen == 0 { return Self::from(res); }
+               res.extend_from_slice(unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) });
+               Self::from(res)
+       }
+}
+#[repr(C)]
+pub struct CVec_APIErrorZ {
+       pub data: *mut crate::util::errors::APIError,
+       pub datalen: usize
+}
+impl CVec_APIErrorZ {
+       #[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec<crate::util::errors::APIError> {
+               if self.datalen == 0 { return Vec::new(); }
+               let ret = unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }.into();
+               self.data = std::ptr::null_mut();
+               self.datalen = 0;
+               ret
+       }
+       #[allow(unused)] pub(crate) fn as_slice(&self) -> &[crate::util::errors::APIError] {
+               unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) }
+       }
+}
+impl From<Vec<crate::util::errors::APIError>> for CVec_APIErrorZ {
+       fn from(v: Vec<crate::util::errors::APIError>) -> Self {
+               let datalen = v.len();
+               let data = Box::into_raw(v.into_boxed_slice());
+               Self { datalen, data: unsafe { (*data).as_mut_ptr() } }
+       }
+}
 #[no_mangle]
-pub static CVec_EventZ_free: extern "C" fn(CVec_EventZ) = crate::c_types::CVecTempl_free::<crate::util::events::Event>;
-
+pub extern "C" fn CVec_APIErrorZ_free(_res: CVec_APIErrorZ) { }
+impl Drop for CVec_APIErrorZ {
+       fn drop(&mut self) {
+               if self.datalen == 0 { return; }
+               unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) };
+       }
+}
+impl Clone for CVec_APIErrorZ {
+       fn clone(&self) -> Self {
+               let mut res = Vec::new();
+               if self.datalen == 0 { return Self::from(res); }
+               res.extend_from_slice(unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) });
+               Self::from(res)
+       }
+}
+#[repr(C)]
+pub struct CVec_ChannelDetailsZ {
+       pub data: *mut crate::ln::channelmanager::ChannelDetails,
+       pub datalen: usize
+}
+impl CVec_ChannelDetailsZ {
+       #[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec<crate::ln::channelmanager::ChannelDetails> {
+               if self.datalen == 0 { return Vec::new(); }
+               let ret = unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }.into();
+               self.data = std::ptr::null_mut();
+               self.datalen = 0;
+               ret
+       }
+       #[allow(unused)] pub(crate) fn as_slice(&self) -> &[crate::ln::channelmanager::ChannelDetails] {
+               unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) }
+       }
+}
+impl From<Vec<crate::ln::channelmanager::ChannelDetails>> for CVec_ChannelDetailsZ {
+       fn from(v: Vec<crate::ln::channelmanager::ChannelDetails>) -> Self {
+               let datalen = v.len();
+               let data = Box::into_raw(v.into_boxed_slice());
+               Self { datalen, data: unsafe { (*data).as_mut_ptr() } }
+       }
+}
 #[no_mangle]
-pub type C2Tuple_usizeTransactionZ = crate::c_types::C2TupleTempl<usize, crate::c_types::Transaction>;
+pub extern "C" fn CVec_ChannelDetailsZ_free(_res: CVec_ChannelDetailsZ) { }
+impl Drop for CVec_ChannelDetailsZ {
+       fn drop(&mut self) {
+               if self.datalen == 0 { return; }
+               unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) };
+       }
+}
+impl Clone for CVec_ChannelDetailsZ {
+       fn clone(&self) -> Self {
+               let mut res = Vec::new();
+               if self.datalen == 0 { return Self::from(res); }
+               res.extend_from_slice(unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) });
+               Self::from(res)
+       }
+}
+#[repr(C)]
+pub union CResult_NonePaymentSendFailureZPtr {
+       /// Note that this value is always NULL, as there are no contents in the OK variant
+       pub result: *mut std::ffi::c_void,
+       pub err: *mut crate::ln::channelmanager::PaymentSendFailure,
+}
+#[repr(C)]
+pub struct CResult_NonePaymentSendFailureZ {
+       pub contents: CResult_NonePaymentSendFailureZPtr,
+       pub result_ok: bool,
+}
 #[no_mangle]
-pub static C2Tuple_usizeTransactionZ_free: extern "C" fn(C2Tuple_usizeTransactionZ) = crate::c_types::C2TupleTempl_free::<usize, crate::c_types::Transaction>;
+pub extern "C" fn CResult_NonePaymentSendFailureZ_ok() -> CResult_NonePaymentSendFailureZ {
+       CResult_NonePaymentSendFailureZ {
+               contents: CResult_NonePaymentSendFailureZPtr {
+                       result: std::ptr::null_mut(),
+               },
+               result_ok: true,
+       }
+}
 #[no_mangle]
-pub extern "C" fn C2Tuple_usizeTransactionZ_new(a: usize, b: crate::c_types::Transaction) -> C2Tuple_usizeTransactionZ {
-       C2Tuple_usizeTransactionZ { a, b, }
+pub extern "C" fn CResult_NonePaymentSendFailureZ_err(e: crate::ln::channelmanager::PaymentSendFailure) -> CResult_NonePaymentSendFailureZ {
+       CResult_NonePaymentSendFailureZ {
+               contents: CResult_NonePaymentSendFailureZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_NonePaymentSendFailureZ_free(_res: CResult_NonePaymentSendFailureZ) { }
+impl Drop for CResult_NonePaymentSendFailureZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<u8, crate::ln::channelmanager::PaymentSendFailure>> for CResult_NonePaymentSendFailureZ {
+       fn from(mut o: crate::c_types::CResultTempl<u8, crate::ln::channelmanager::PaymentSendFailure>) -> Self {
+               let contents = if o.result_ok {
+                       let _ = unsafe { Box::from_raw(o.contents.result) };
+                       o.contents.result = std::ptr::null_mut();
+                       CResult_NonePaymentSendFailureZPtr { result: std::ptr::null_mut() }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_NonePaymentSendFailureZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_NonePaymentSendFailureZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_NonePaymentSendFailureZPtr {
+                               result: std::ptr::null_mut()
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_NonePaymentSendFailureZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::channelmanager::PaymentSendFailure>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_NonePaymentSendFailureZ_clone(orig: &CResult_NonePaymentSendFailureZ) -> CResult_NonePaymentSendFailureZ { orig.clone() }
+#[repr(C)]
+pub struct CVec_ChannelMonitorZ {
+       pub data: *mut crate::chain::channelmonitor::ChannelMonitor,
+       pub datalen: usize
+}
+impl CVec_ChannelMonitorZ {
+       #[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec<crate::chain::channelmonitor::ChannelMonitor> {
+               if self.datalen == 0 { return Vec::new(); }
+               let ret = unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }.into();
+               self.data = std::ptr::null_mut();
+               self.datalen = 0;
+               ret
+       }
+       #[allow(unused)] pub(crate) fn as_slice(&self) -> &[crate::chain::channelmonitor::ChannelMonitor] {
+               unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) }
+       }
+}
+impl From<Vec<crate::chain::channelmonitor::ChannelMonitor>> for CVec_ChannelMonitorZ {
+       fn from(v: Vec<crate::chain::channelmonitor::ChannelMonitor>) -> Self {
+               let datalen = v.len();
+               let data = Box::into_raw(v.into_boxed_slice());
+               Self { datalen, data: unsafe { (*data).as_mut_ptr() } }
+       }
 }
-
 #[no_mangle]
-pub type CVec_C2Tuple_usizeTransactionZZ = crate::c_types::CVecTempl<crate::c_types::C2TupleTempl<usize, crate::c_types::Transaction>>;
+pub extern "C" fn CVec_ChannelMonitorZ_free(_res: CVec_ChannelMonitorZ) { }
+impl Drop for CVec_ChannelMonitorZ {
+       fn drop(&mut self) {
+               if self.datalen == 0 { return; }
+               unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) };
+       }
+}
+#[repr(C)]
+pub struct C2Tuple_BlockHashChannelManagerZ {
+       pub a: crate::c_types::ThirtyTwoBytes,
+       pub b: crate::ln::channelmanager::ChannelManager,
+}
+impl From<(crate::c_types::ThirtyTwoBytes, crate::ln::channelmanager::ChannelManager)> for C2Tuple_BlockHashChannelManagerZ {
+       fn from (tup: (crate::c_types::ThirtyTwoBytes, crate::ln::channelmanager::ChannelManager)) -> Self {
+               Self {
+                       a: tup.0,
+                       b: tup.1,
+               }
+       }
+}
+impl C2Tuple_BlockHashChannelManagerZ {
+       #[allow(unused)] pub(crate) fn to_rust(mut self) -> (crate::c_types::ThirtyTwoBytes, crate::ln::channelmanager::ChannelManager) {
+               (self.a, self.b)
+       }
+}
 #[no_mangle]
-pub static CVec_C2Tuple_usizeTransactionZZ_free: extern "C" fn(CVec_C2Tuple_usizeTransactionZZ) = crate::c_types::CVecTempl_free::<crate::c_types::C2TupleTempl<usize, crate::c_types::Transaction>>;
+pub extern "C" fn C2Tuple_BlockHashChannelManagerZ_new(a: crate::c_types::ThirtyTwoBytes, b: crate::ln::channelmanager::ChannelManager) -> C2Tuple_BlockHashChannelManagerZ {
+       C2Tuple_BlockHashChannelManagerZ { a, b, }
+}
 
 #[no_mangle]
-pub type CResult_NoneChannelMonitorUpdateErrZ = crate::c_types::CResultTempl<u8, crate::chain::channelmonitor::ChannelMonitorUpdateErr>;
+pub extern "C" fn C2Tuple_BlockHashChannelManagerZ_free(_res: C2Tuple_BlockHashChannelManagerZ) { }
+#[repr(C)]
+pub union CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZPtr {
+       pub result: *mut crate::c_types::derived::C2Tuple_BlockHashChannelManagerZ,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ {
+       pub contents: CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZPtr,
+       pub result_ok: bool,
+}
 #[no_mangle]
-pub static CResult_NoneChannelMonitorUpdateErrZ_free: extern "C" fn(CResult_NoneChannelMonitorUpdateErrZ) = crate::c_types::CResultTempl_free::<u8, crate::chain::channelmonitor::ChannelMonitorUpdateErr>;
+pub extern "C" fn CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_ok(o: crate::c_types::derived::C2Tuple_BlockHashChannelManagerZ) -> CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ {
+       CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ {
+               contents: CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
 #[no_mangle]
-pub extern "C" fn CResult_NoneChannelMonitorUpdateErrZ_ok() -> CResult_NoneChannelMonitorUpdateErrZ {
-       crate::c_types::CResultTempl::ok(0)
+pub extern "C" fn CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ {
+       CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ {
+               contents: CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
 }
-
 #[no_mangle]
-pub static CResult_NoneChannelMonitorUpdateErrZ_err: extern "C" fn (crate::chain::channelmonitor::ChannelMonitorUpdateErr) -> CResult_NoneChannelMonitorUpdateErrZ =
-       crate::c_types::CResultTempl::<u8, crate::chain::channelmonitor::ChannelMonitorUpdateErr>::err;
-
+pub extern "C" fn CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_free(_res: CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ) { }
+impl Drop for CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::c_types::derived::C2Tuple_BlockHashChannelManagerZ, crate::ln::msgs::DecodeError>> for CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::c_types::derived::C2Tuple_BlockHashChannelManagerZ, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+#[repr(C)]
+pub union CResult_SpendableOutputDescriptorDecodeErrorZPtr {
+       pub result: *mut crate::chain::keysinterface::SpendableOutputDescriptor,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_SpendableOutputDescriptorDecodeErrorZ {
+       pub contents: CResult_SpendableOutputDescriptorDecodeErrorZPtr,
+       pub result_ok: bool,
+}
 #[no_mangle]
-pub type CVec_MonitorEventZ = crate::c_types::CVecTempl<crate::chain::channelmonitor::MonitorEvent>;
+pub extern "C" fn CResult_SpendableOutputDescriptorDecodeErrorZ_ok(o: crate::chain::keysinterface::SpendableOutputDescriptor) -> CResult_SpendableOutputDescriptorDecodeErrorZ {
+       CResult_SpendableOutputDescriptorDecodeErrorZ {
+               contents: CResult_SpendableOutputDescriptorDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
 #[no_mangle]
-pub static CVec_MonitorEventZ_free: extern "C" fn(CVec_MonitorEventZ) = crate::c_types::CVecTempl_free::<crate::chain::channelmonitor::MonitorEvent>;
-
+pub extern "C" fn CResult_SpendableOutputDescriptorDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_SpendableOutputDescriptorDecodeErrorZ {
+       CResult_SpendableOutputDescriptorDecodeErrorZ {
+               contents: CResult_SpendableOutputDescriptorDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_SpendableOutputDescriptorDecodeErrorZ_free(_res: CResult_SpendableOutputDescriptorDecodeErrorZ) { }
+impl Drop for CResult_SpendableOutputDescriptorDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::chain::keysinterface::SpendableOutputDescriptor, crate::ln::msgs::DecodeError>> for CResult_SpendableOutputDescriptorDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::chain::keysinterface::SpendableOutputDescriptor, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_SpendableOutputDescriptorDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_SpendableOutputDescriptorDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_SpendableOutputDescriptorDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_SpendableOutputDescriptorDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::chain::keysinterface::SpendableOutputDescriptor>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_SpendableOutputDescriptorDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
 #[no_mangle]
-pub type CResult_NoneMonitorUpdateErrorZ = crate::c_types::CResultTempl<u8, crate::chain::channelmonitor::MonitorUpdateError>;
+pub extern "C" fn CResult_SpendableOutputDescriptorDecodeErrorZ_clone(orig: &CResult_SpendableOutputDescriptorDecodeErrorZ) -> CResult_SpendableOutputDescriptorDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub struct C2Tuple_SignatureCVec_SignatureZZ {
+       pub a: crate::c_types::Signature,
+       pub b: crate::c_types::derived::CVec_SignatureZ,
+}
+impl From<(crate::c_types::Signature, crate::c_types::derived::CVec_SignatureZ)> for C2Tuple_SignatureCVec_SignatureZZ {
+       fn from (tup: (crate::c_types::Signature, crate::c_types::derived::CVec_SignatureZ)) -> Self {
+               Self {
+                       a: tup.0,
+                       b: tup.1,
+               }
+       }
+}
+impl C2Tuple_SignatureCVec_SignatureZZ {
+       #[allow(unused)] pub(crate) fn to_rust(mut self) -> (crate::c_types::Signature, crate::c_types::derived::CVec_SignatureZ) {
+               (self.a, self.b)
+       }
+}
+impl Clone for C2Tuple_SignatureCVec_SignatureZZ {
+       fn clone(&self) -> Self {
+               Self {
+                       a: self.a.clone(),
+                       b: self.b.clone(),
+               }
+       }
+}
 #[no_mangle]
-pub static CResult_NoneMonitorUpdateErrorZ_free: extern "C" fn(CResult_NoneMonitorUpdateErrorZ) = crate::c_types::CResultTempl_free::<u8, crate::chain::channelmonitor::MonitorUpdateError>;
+pub extern "C" fn C2Tuple_SignatureCVec_SignatureZZ_clone(orig: &C2Tuple_SignatureCVec_SignatureZZ) -> C2Tuple_SignatureCVec_SignatureZZ { orig.clone() }
 #[no_mangle]
-pub extern "C" fn CResult_NoneMonitorUpdateErrorZ_ok() -> CResult_NoneMonitorUpdateErrorZ {
-       crate::c_types::CResultTempl::ok(0)
+pub extern "C" fn C2Tuple_SignatureCVec_SignatureZZ_new(a: crate::c_types::Signature, b: crate::c_types::derived::CVec_SignatureZ) -> C2Tuple_SignatureCVec_SignatureZZ {
+       C2Tuple_SignatureCVec_SignatureZZ { a, b, }
 }
 
 #[no_mangle]
-pub static CResult_NoneMonitorUpdateErrorZ_err: extern "C" fn (crate::chain::channelmonitor::MonitorUpdateError) -> CResult_NoneMonitorUpdateErrorZ =
-       crate::c_types::CResultTempl::<u8, crate::chain::channelmonitor::MonitorUpdateError>::err;
-
+pub extern "C" fn C2Tuple_SignatureCVec_SignatureZZ_free(_res: C2Tuple_SignatureCVec_SignatureZZ) { }
+#[repr(C)]
+pub union CResult_C2Tuple_SignatureCVec_SignatureZZNoneZPtr {
+       pub result: *mut crate::c_types::derived::C2Tuple_SignatureCVec_SignatureZZ,
+       /// Note that this value is always NULL, as there are no contents in the Err variant
+       pub err: *mut std::ffi::c_void,
+}
+#[repr(C)]
+pub struct CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ {
+       pub contents: CResult_C2Tuple_SignatureCVec_SignatureZZNoneZPtr,
+       pub result_ok: bool,
+}
 #[no_mangle]
-pub type C2Tuple_OutPointScriptZ = crate::c_types::C2TupleTempl<crate::chain::transaction::OutPoint, crate::c_types::derived::CVec_u8Z>;
+pub extern "C" fn CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ_ok(o: crate::c_types::derived::C2Tuple_SignatureCVec_SignatureZZ) -> CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ {
+       CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ {
+               contents: CResult_C2Tuple_SignatureCVec_SignatureZZNoneZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
 #[no_mangle]
-pub static C2Tuple_OutPointScriptZ_free: extern "C" fn(C2Tuple_OutPointScriptZ) = crate::c_types::C2TupleTempl_free::<crate::chain::transaction::OutPoint, crate::c_types::derived::CVec_u8Z>;
+pub extern "C" fn CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ_err() -> CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ {
+       CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ {
+               contents: CResult_C2Tuple_SignatureCVec_SignatureZZNoneZPtr {
+                       err: std::ptr::null_mut(),
+               },
+               result_ok: false,
+       }
+}
 #[no_mangle]
-pub extern "C" fn C2Tuple_OutPointScriptZ_new(a: crate::chain::transaction::OutPoint, b: crate::c_types::derived::CVec_u8Z) -> C2Tuple_OutPointScriptZ {
-       C2Tuple_OutPointScriptZ { a, b, }
+pub extern "C" fn CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ_free(_res: CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ) { }
+impl Drop for CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::c_types::derived::C2Tuple_SignatureCVec_SignatureZZ, u8>> for CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::c_types::derived::C2Tuple_SignatureCVec_SignatureZZ, u8>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_C2Tuple_SignatureCVec_SignatureZZNoneZPtr { result }
+               } else {
+                       let _ = unsafe { Box::from_raw(o.contents.err) };
+                       o.contents.err = std::ptr::null_mut();
+                       CResult_C2Tuple_SignatureCVec_SignatureZZNoneZPtr { err: std::ptr::null_mut() }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_C2Tuple_SignatureCVec_SignatureZZNoneZPtr {
+                               result: Box::into_raw(Box::new(<crate::c_types::derived::C2Tuple_SignatureCVec_SignatureZZ>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_C2Tuple_SignatureCVec_SignatureZZNoneZPtr {
+                               err: std::ptr::null_mut()
+                       } }
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ_clone(orig: &CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ) -> CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ { orig.clone() }
+#[repr(C)]
+pub union CResult_SignatureNoneZPtr {
+       pub result: *mut crate::c_types::Signature,
+       /// Note that this value is always NULL, as there are no contents in the Err variant
+       pub err: *mut std::ffi::c_void,
+}
+#[repr(C)]
+pub struct CResult_SignatureNoneZ {
+       pub contents: CResult_SignatureNoneZPtr,
+       pub result_ok: bool,
 }
-
 #[no_mangle]
-pub type CVec_TransactionZ = crate::c_types::CVecTempl<crate::c_types::Transaction>;
+pub extern "C" fn CResult_SignatureNoneZ_ok(o: crate::c_types::Signature) -> CResult_SignatureNoneZ {
+       CResult_SignatureNoneZ {
+               contents: CResult_SignatureNoneZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
 #[no_mangle]
-pub static CVec_TransactionZ_free: extern "C" fn(CVec_TransactionZ) = crate::c_types::CVecTempl_free::<crate::c_types::Transaction>;
-
+pub extern "C" fn CResult_SignatureNoneZ_err() -> CResult_SignatureNoneZ {
+       CResult_SignatureNoneZ {
+               contents: CResult_SignatureNoneZPtr {
+                       err: std::ptr::null_mut(),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_SignatureNoneZ_free(_res: CResult_SignatureNoneZ) { }
+impl Drop for CResult_SignatureNoneZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::c_types::Signature, u8>> for CResult_SignatureNoneZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::c_types::Signature, u8>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_SignatureNoneZPtr { result }
+               } else {
+                       let _ = unsafe { Box::from_raw(o.contents.err) };
+                       o.contents.err = std::ptr::null_mut();
+                       CResult_SignatureNoneZPtr { err: std::ptr::null_mut() }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_SignatureNoneZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_SignatureNoneZPtr {
+                               result: Box::into_raw(Box::new(<crate::c_types::Signature>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_SignatureNoneZPtr {
+                               err: std::ptr::null_mut()
+                       } }
+               }
+       }
+}
 #[no_mangle]
-pub type C2Tuple_u32TxOutZ = crate::c_types::C2TupleTempl<u32, crate::c_types::TxOut>;
+pub extern "C" fn CResult_SignatureNoneZ_clone(orig: &CResult_SignatureNoneZ) -> CResult_SignatureNoneZ { orig.clone() }
+#[repr(C)]
+pub union CResult_SignDecodeErrorZPtr {
+       pub result: *mut crate::chain::keysinterface::Sign,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_SignDecodeErrorZ {
+       pub contents: CResult_SignDecodeErrorZPtr,
+       pub result_ok: bool,
+}
 #[no_mangle]
-pub static C2Tuple_u32TxOutZ_free: extern "C" fn(C2Tuple_u32TxOutZ) = crate::c_types::C2TupleTempl_free::<u32, crate::c_types::TxOut>;
+pub extern "C" fn CResult_SignDecodeErrorZ_ok(o: crate::chain::keysinterface::Sign) -> CResult_SignDecodeErrorZ {
+       CResult_SignDecodeErrorZ {
+               contents: CResult_SignDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
 #[no_mangle]
-pub extern "C" fn C2Tuple_u32TxOutZ_new(a: u32, b: crate::c_types::TxOut) -> C2Tuple_u32TxOutZ {
-       C2Tuple_u32TxOutZ { a, b, }
+pub extern "C" fn CResult_SignDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_SignDecodeErrorZ {
+       CResult_SignDecodeErrorZ {
+               contents: CResult_SignDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_SignDecodeErrorZ_free(_res: CResult_SignDecodeErrorZ) { }
+impl Drop for CResult_SignDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::chain::keysinterface::Sign, crate::ln::msgs::DecodeError>> for CResult_SignDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::chain::keysinterface::Sign, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_SignDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_SignDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_SignDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_SignDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::chain::keysinterface::Sign>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_SignDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_SignDecodeErrorZ_clone(orig: &CResult_SignDecodeErrorZ) -> CResult_SignDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub struct CVec_CVec_u8ZZ {
+       pub data: *mut crate::c_types::derived::CVec_u8Z,
+       pub datalen: usize
+}
+impl CVec_CVec_u8ZZ {
+       #[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec<crate::c_types::derived::CVec_u8Z> {
+               if self.datalen == 0 { return Vec::new(); }
+               let ret = unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }.into();
+               self.data = std::ptr::null_mut();
+               self.datalen = 0;
+               ret
+       }
+       #[allow(unused)] pub(crate) fn as_slice(&self) -> &[crate::c_types::derived::CVec_u8Z] {
+               unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) }
+       }
+}
+impl From<Vec<crate::c_types::derived::CVec_u8Z>> for CVec_CVec_u8ZZ {
+       fn from(v: Vec<crate::c_types::derived::CVec_u8Z>) -> Self {
+               let datalen = v.len();
+               let data = Box::into_raw(v.into_boxed_slice());
+               Self { datalen, data: unsafe { (*data).as_mut_ptr() } }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CVec_CVec_u8ZZ_free(_res: CVec_CVec_u8ZZ) { }
+impl Drop for CVec_CVec_u8ZZ {
+       fn drop(&mut self) {
+               if self.datalen == 0 { return; }
+               unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) };
+       }
+}
+impl Clone for CVec_CVec_u8ZZ {
+       fn clone(&self) -> Self {
+               let mut res = Vec::new();
+               if self.datalen == 0 { return Self::from(res); }
+               res.extend_from_slice(unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) });
+               Self::from(res)
+       }
+}
+#[repr(C)]
+pub union CResult_CVec_CVec_u8ZZNoneZPtr {
+       pub result: *mut crate::c_types::derived::CVec_CVec_u8ZZ,
+       /// Note that this value is always NULL, as there are no contents in the Err variant
+       pub err: *mut std::ffi::c_void,
+}
+#[repr(C)]
+pub struct CResult_CVec_CVec_u8ZZNoneZ {
+       pub contents: CResult_CVec_CVec_u8ZZNoneZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_CVec_CVec_u8ZZNoneZ_ok(o: crate::c_types::derived::CVec_CVec_u8ZZ) -> CResult_CVec_CVec_u8ZZNoneZ {
+       CResult_CVec_CVec_u8ZZNoneZ {
+               contents: CResult_CVec_CVec_u8ZZNoneZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_CVec_CVec_u8ZZNoneZ_err() -> CResult_CVec_CVec_u8ZZNoneZ {
+       CResult_CVec_CVec_u8ZZNoneZ {
+               contents: CResult_CVec_CVec_u8ZZNoneZPtr {
+                       err: std::ptr::null_mut(),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_CVec_CVec_u8ZZNoneZ_free(_res: CResult_CVec_CVec_u8ZZNoneZ) { }
+impl Drop for CResult_CVec_CVec_u8ZZNoneZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::c_types::derived::CVec_CVec_u8ZZ, u8>> for CResult_CVec_CVec_u8ZZNoneZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::c_types::derived::CVec_CVec_u8ZZ, u8>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_CVec_CVec_u8ZZNoneZPtr { result }
+               } else {
+                       let _ = unsafe { Box::from_raw(o.contents.err) };
+                       o.contents.err = std::ptr::null_mut();
+                       CResult_CVec_CVec_u8ZZNoneZPtr { err: std::ptr::null_mut() }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_CVec_CVec_u8ZZNoneZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_CVec_CVec_u8ZZNoneZPtr {
+                               result: Box::into_raw(Box::new(<crate::c_types::derived::CVec_CVec_u8ZZ>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_CVec_CVec_u8ZZNoneZPtr {
+                               err: std::ptr::null_mut()
+                       } }
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_CVec_CVec_u8ZZNoneZ_clone(orig: &CResult_CVec_CVec_u8ZZNoneZ) -> CResult_CVec_CVec_u8ZZNoneZ { orig.clone() }
+#[repr(C)]
+pub union CResult_InMemorySignerDecodeErrorZPtr {
+       pub result: *mut crate::chain::keysinterface::InMemorySigner,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_InMemorySignerDecodeErrorZ {
+       pub contents: CResult_InMemorySignerDecodeErrorZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_InMemorySignerDecodeErrorZ_ok(o: crate::chain::keysinterface::InMemorySigner) -> CResult_InMemorySignerDecodeErrorZ {
+       CResult_InMemorySignerDecodeErrorZ {
+               contents: CResult_InMemorySignerDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_InMemorySignerDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_InMemorySignerDecodeErrorZ {
+       CResult_InMemorySignerDecodeErrorZ {
+               contents: CResult_InMemorySignerDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_InMemorySignerDecodeErrorZ_free(_res: CResult_InMemorySignerDecodeErrorZ) { }
+impl Drop for CResult_InMemorySignerDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::chain::keysinterface::InMemorySigner, crate::ln::msgs::DecodeError>> for CResult_InMemorySignerDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::chain::keysinterface::InMemorySigner, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_InMemorySignerDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_InMemorySignerDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_InMemorySignerDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_InMemorySignerDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::chain::keysinterface::InMemorySigner>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_InMemorySignerDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_InMemorySignerDecodeErrorZ_clone(orig: &CResult_InMemorySignerDecodeErrorZ) -> CResult_InMemorySignerDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub struct CVec_TxOutZ {
+       pub data: *mut crate::c_types::TxOut,
+       pub datalen: usize
+}
+impl CVec_TxOutZ {
+       #[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec<crate::c_types::TxOut> {
+               if self.datalen == 0 { return Vec::new(); }
+               let ret = unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }.into();
+               self.data = std::ptr::null_mut();
+               self.datalen = 0;
+               ret
+       }
+       #[allow(unused)] pub(crate) fn as_slice(&self) -> &[crate::c_types::TxOut] {
+               unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) }
+       }
+}
+impl From<Vec<crate::c_types::TxOut>> for CVec_TxOutZ {
+       fn from(v: Vec<crate::c_types::TxOut>) -> Self {
+               let datalen = v.len();
+               let data = Box::into_raw(v.into_boxed_slice());
+               Self { datalen, data: unsafe { (*data).as_mut_ptr() } }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CVec_TxOutZ_free(_res: CVec_TxOutZ) { }
+impl Drop for CVec_TxOutZ {
+       fn drop(&mut self) {
+               if self.datalen == 0 { return; }
+               unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) };
+       }
+}
+impl Clone for CVec_TxOutZ {
+       fn clone(&self) -> Self {
+               let mut res = Vec::new();
+               if self.datalen == 0 { return Self::from(res); }
+               res.extend_from_slice(unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) });
+               Self::from(res)
+       }
+}
+#[repr(C)]
+pub union CResult_TransactionNoneZPtr {
+       pub result: *mut crate::c_types::Transaction,
+       /// Note that this value is always NULL, as there are no contents in the Err variant
+       pub err: *mut std::ffi::c_void,
+}
+#[repr(C)]
+pub struct CResult_TransactionNoneZ {
+       pub contents: CResult_TransactionNoneZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_TransactionNoneZ_ok(o: crate::c_types::Transaction) -> CResult_TransactionNoneZ {
+       CResult_TransactionNoneZ {
+               contents: CResult_TransactionNoneZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_TransactionNoneZ_err() -> CResult_TransactionNoneZ {
+       CResult_TransactionNoneZ {
+               contents: CResult_TransactionNoneZPtr {
+                       err: std::ptr::null_mut(),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_TransactionNoneZ_free(_res: CResult_TransactionNoneZ) { }
+impl Drop for CResult_TransactionNoneZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::c_types::Transaction, u8>> for CResult_TransactionNoneZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::c_types::Transaction, u8>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_TransactionNoneZPtr { result }
+               } else {
+                       let _ = unsafe { Box::from_raw(o.contents.err) };
+                       o.contents.err = std::ptr::null_mut();
+                       CResult_TransactionNoneZPtr { err: std::ptr::null_mut() }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+#[repr(C)]
+pub struct CVec_RouteHopZ {
+       pub data: *mut crate::routing::router::RouteHop,
+       pub datalen: usize
+}
+impl CVec_RouteHopZ {
+       #[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec<crate::routing::router::RouteHop> {
+               if self.datalen == 0 { return Vec::new(); }
+               let ret = unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }.into();
+               self.data = std::ptr::null_mut();
+               self.datalen = 0;
+               ret
+       }
+       #[allow(unused)] pub(crate) fn as_slice(&self) -> &[crate::routing::router::RouteHop] {
+               unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) }
+       }
+}
+impl From<Vec<crate::routing::router::RouteHop>> for CVec_RouteHopZ {
+       fn from(v: Vec<crate::routing::router::RouteHop>) -> Self {
+               let datalen = v.len();
+               let data = Box::into_raw(v.into_boxed_slice());
+               Self { datalen, data: unsafe { (*data).as_mut_ptr() } }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CVec_RouteHopZ_free(_res: CVec_RouteHopZ) { }
+impl Drop for CVec_RouteHopZ {
+       fn drop(&mut self) {
+               if self.datalen == 0 { return; }
+               unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) };
+       }
+}
+impl Clone for CVec_RouteHopZ {
+       fn clone(&self) -> Self {
+               let mut res = Vec::new();
+               if self.datalen == 0 { return Self::from(res); }
+               res.extend_from_slice(unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) });
+               Self::from(res)
+       }
+}
+#[repr(C)]
+pub struct CVec_CVec_RouteHopZZ {
+       pub data: *mut crate::c_types::derived::CVec_RouteHopZ,
+       pub datalen: usize
+}
+impl CVec_CVec_RouteHopZZ {
+       #[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec<crate::c_types::derived::CVec_RouteHopZ> {
+               if self.datalen == 0 { return Vec::new(); }
+               let ret = unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }.into();
+               self.data = std::ptr::null_mut();
+               self.datalen = 0;
+               ret
+       }
+       #[allow(unused)] pub(crate) fn as_slice(&self) -> &[crate::c_types::derived::CVec_RouteHopZ] {
+               unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) }
+       }
+}
+impl From<Vec<crate::c_types::derived::CVec_RouteHopZ>> for CVec_CVec_RouteHopZZ {
+       fn from(v: Vec<crate::c_types::derived::CVec_RouteHopZ>) -> Self {
+               let datalen = v.len();
+               let data = Box::into_raw(v.into_boxed_slice());
+               Self { datalen, data: unsafe { (*data).as_mut_ptr() } }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CVec_CVec_RouteHopZZ_free(_res: CVec_CVec_RouteHopZZ) { }
+impl Drop for CVec_CVec_RouteHopZZ {
+       fn drop(&mut self) {
+               if self.datalen == 0 { return; }
+               unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) };
+       }
+}
+impl Clone for CVec_CVec_RouteHopZZ {
+       fn clone(&self) -> Self {
+               let mut res = Vec::new();
+               if self.datalen == 0 { return Self::from(res); }
+               res.extend_from_slice(unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) });
+               Self::from(res)
+       }
+}
+#[repr(C)]
+pub union CResult_RouteDecodeErrorZPtr {
+       pub result: *mut crate::routing::router::Route,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_RouteDecodeErrorZ {
+       pub contents: CResult_RouteDecodeErrorZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_RouteDecodeErrorZ_ok(o: crate::routing::router::Route) -> CResult_RouteDecodeErrorZ {
+       CResult_RouteDecodeErrorZ {
+               contents: CResult_RouteDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_RouteDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_RouteDecodeErrorZ {
+       CResult_RouteDecodeErrorZ {
+               contents: CResult_RouteDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_RouteDecodeErrorZ_free(_res: CResult_RouteDecodeErrorZ) { }
+impl Drop for CResult_RouteDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::routing::router::Route, crate::ln::msgs::DecodeError>> for CResult_RouteDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::routing::router::Route, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_RouteDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_RouteDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_RouteDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_RouteDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::routing::router::Route>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_RouteDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_RouteDecodeErrorZ_clone(orig: &CResult_RouteDecodeErrorZ) -> CResult_RouteDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub struct CVec_RouteHintZ {
+       pub data: *mut crate::routing::router::RouteHint,
+       pub datalen: usize
+}
+impl CVec_RouteHintZ {
+       #[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec<crate::routing::router::RouteHint> {
+               if self.datalen == 0 { return Vec::new(); }
+               let ret = unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }.into();
+               self.data = std::ptr::null_mut();
+               self.datalen = 0;
+               ret
+       }
+       #[allow(unused)] pub(crate) fn as_slice(&self) -> &[crate::routing::router::RouteHint] {
+               unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) }
+       }
+}
+impl From<Vec<crate::routing::router::RouteHint>> for CVec_RouteHintZ {
+       fn from(v: Vec<crate::routing::router::RouteHint>) -> Self {
+               let datalen = v.len();
+               let data = Box::into_raw(v.into_boxed_slice());
+               Self { datalen, data: unsafe { (*data).as_mut_ptr() } }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CVec_RouteHintZ_free(_res: CVec_RouteHintZ) { }
+impl Drop for CVec_RouteHintZ {
+       fn drop(&mut self) {
+               if self.datalen == 0 { return; }
+               unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) };
+       }
+}
+impl Clone for CVec_RouteHintZ {
+       fn clone(&self) -> Self {
+               let mut res = Vec::new();
+               if self.datalen == 0 { return Self::from(res); }
+               res.extend_from_slice(unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) });
+               Self::from(res)
+       }
+}
+#[repr(C)]
+pub union CResult_RouteLightningErrorZPtr {
+       pub result: *mut crate::routing::router::Route,
+       pub err: *mut crate::ln::msgs::LightningError,
+}
+#[repr(C)]
+pub struct CResult_RouteLightningErrorZ {
+       pub contents: CResult_RouteLightningErrorZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_RouteLightningErrorZ_ok(o: crate::routing::router::Route) -> CResult_RouteLightningErrorZ {
+       CResult_RouteLightningErrorZ {
+               contents: CResult_RouteLightningErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_RouteLightningErrorZ_err(e: crate::ln::msgs::LightningError) -> CResult_RouteLightningErrorZ {
+       CResult_RouteLightningErrorZ {
+               contents: CResult_RouteLightningErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_RouteLightningErrorZ_free(_res: CResult_RouteLightningErrorZ) { }
+impl Drop for CResult_RouteLightningErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::routing::router::Route, crate::ln::msgs::LightningError>> for CResult_RouteLightningErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::routing::router::Route, crate::ln::msgs::LightningError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_RouteLightningErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_RouteLightningErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_RouteLightningErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_RouteLightningErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::routing::router::Route>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_RouteLightningErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::LightningError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_RouteLightningErrorZ_clone(orig: &CResult_RouteLightningErrorZ) -> CResult_RouteLightningErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_NetAddressu8ZPtr {
+       pub result: *mut crate::ln::msgs::NetAddress,
+       pub err: *mut u8,
+}
+#[repr(C)]
+pub struct CResult_NetAddressu8Z {
+       pub contents: CResult_NetAddressu8ZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_NetAddressu8Z_ok(o: crate::ln::msgs::NetAddress) -> CResult_NetAddressu8Z {
+       CResult_NetAddressu8Z {
+               contents: CResult_NetAddressu8ZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_NetAddressu8Z_err(e: u8) -> CResult_NetAddressu8Z {
+       CResult_NetAddressu8Z {
+               contents: CResult_NetAddressu8ZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_NetAddressu8Z_free(_res: CResult_NetAddressu8Z) { }
+impl Drop for CResult_NetAddressu8Z {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::msgs::NetAddress, u8>> for CResult_NetAddressu8Z {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::msgs::NetAddress, u8>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_NetAddressu8ZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_NetAddressu8ZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_NetAddressu8Z {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_NetAddressu8ZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::msgs::NetAddress>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_NetAddressu8ZPtr {
+                               err: Box::into_raw(Box::new(<u8>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_NetAddressu8Z_clone(orig: &CResult_NetAddressu8Z) -> CResult_NetAddressu8Z { orig.clone() }
+#[repr(C)]
+pub union CResult_CResult_NetAddressu8ZDecodeErrorZPtr {
+       pub result: *mut crate::c_types::derived::CResult_NetAddressu8Z,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_CResult_NetAddressu8ZDecodeErrorZ {
+       pub contents: CResult_CResult_NetAddressu8ZDecodeErrorZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_CResult_NetAddressu8ZDecodeErrorZ_ok(o: crate::c_types::derived::CResult_NetAddressu8Z) -> CResult_CResult_NetAddressu8ZDecodeErrorZ {
+       CResult_CResult_NetAddressu8ZDecodeErrorZ {
+               contents: CResult_CResult_NetAddressu8ZDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_CResult_NetAddressu8ZDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_CResult_NetAddressu8ZDecodeErrorZ {
+       CResult_CResult_NetAddressu8ZDecodeErrorZ {
+               contents: CResult_CResult_NetAddressu8ZDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_CResult_NetAddressu8ZDecodeErrorZ_free(_res: CResult_CResult_NetAddressu8ZDecodeErrorZ) { }
+impl Drop for CResult_CResult_NetAddressu8ZDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::c_types::derived::CResult_NetAddressu8Z, crate::ln::msgs::DecodeError>> for CResult_CResult_NetAddressu8ZDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::c_types::derived::CResult_NetAddressu8Z, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_CResult_NetAddressu8ZDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_CResult_NetAddressu8ZDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_CResult_NetAddressu8ZDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_CResult_NetAddressu8ZDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::c_types::derived::CResult_NetAddressu8Z>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_CResult_NetAddressu8ZDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_CResult_NetAddressu8ZDecodeErrorZ_clone(orig: &CResult_CResult_NetAddressu8ZDecodeErrorZ) -> CResult_CResult_NetAddressu8ZDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub struct CVec_UpdateAddHTLCZ {
+       pub data: *mut crate::ln::msgs::UpdateAddHTLC,
+       pub datalen: usize
+}
+impl CVec_UpdateAddHTLCZ {
+       #[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec<crate::ln::msgs::UpdateAddHTLC> {
+               if self.datalen == 0 { return Vec::new(); }
+               let ret = unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }.into();
+               self.data = std::ptr::null_mut();
+               self.datalen = 0;
+               ret
+       }
+       #[allow(unused)] pub(crate) fn as_slice(&self) -> &[crate::ln::msgs::UpdateAddHTLC] {
+               unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) }
+       }
+}
+impl From<Vec<crate::ln::msgs::UpdateAddHTLC>> for CVec_UpdateAddHTLCZ {
+       fn from(v: Vec<crate::ln::msgs::UpdateAddHTLC>) -> Self {
+               let datalen = v.len();
+               let data = Box::into_raw(v.into_boxed_slice());
+               Self { datalen, data: unsafe { (*data).as_mut_ptr() } }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CVec_UpdateAddHTLCZ_free(_res: CVec_UpdateAddHTLCZ) { }
+impl Drop for CVec_UpdateAddHTLCZ {
+       fn drop(&mut self) {
+               if self.datalen == 0 { return; }
+               unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) };
+       }
+}
+impl Clone for CVec_UpdateAddHTLCZ {
+       fn clone(&self) -> Self {
+               let mut res = Vec::new();
+               if self.datalen == 0 { return Self::from(res); }
+               res.extend_from_slice(unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) });
+               Self::from(res)
+       }
+}
+#[repr(C)]
+pub struct CVec_UpdateFulfillHTLCZ {
+       pub data: *mut crate::ln::msgs::UpdateFulfillHTLC,
+       pub datalen: usize
+}
+impl CVec_UpdateFulfillHTLCZ {
+       #[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec<crate::ln::msgs::UpdateFulfillHTLC> {
+               if self.datalen == 0 { return Vec::new(); }
+               let ret = unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }.into();
+               self.data = std::ptr::null_mut();
+               self.datalen = 0;
+               ret
+       }
+       #[allow(unused)] pub(crate) fn as_slice(&self) -> &[crate::ln::msgs::UpdateFulfillHTLC] {
+               unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) }
+       }
+}
+impl From<Vec<crate::ln::msgs::UpdateFulfillHTLC>> for CVec_UpdateFulfillHTLCZ {
+       fn from(v: Vec<crate::ln::msgs::UpdateFulfillHTLC>) -> Self {
+               let datalen = v.len();
+               let data = Box::into_raw(v.into_boxed_slice());
+               Self { datalen, data: unsafe { (*data).as_mut_ptr() } }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CVec_UpdateFulfillHTLCZ_free(_res: CVec_UpdateFulfillHTLCZ) { }
+impl Drop for CVec_UpdateFulfillHTLCZ {
+       fn drop(&mut self) {
+               if self.datalen == 0 { return; }
+               unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) };
+       }
+}
+impl Clone for CVec_UpdateFulfillHTLCZ {
+       fn clone(&self) -> Self {
+               let mut res = Vec::new();
+               if self.datalen == 0 { return Self::from(res); }
+               res.extend_from_slice(unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) });
+               Self::from(res)
+       }
+}
+#[repr(C)]
+pub struct CVec_UpdateFailHTLCZ {
+       pub data: *mut crate::ln::msgs::UpdateFailHTLC,
+       pub datalen: usize
+}
+impl CVec_UpdateFailHTLCZ {
+       #[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec<crate::ln::msgs::UpdateFailHTLC> {
+               if self.datalen == 0 { return Vec::new(); }
+               let ret = unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }.into();
+               self.data = std::ptr::null_mut();
+               self.datalen = 0;
+               ret
+       }
+       #[allow(unused)] pub(crate) fn as_slice(&self) -> &[crate::ln::msgs::UpdateFailHTLC] {
+               unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) }
+       }
+}
+impl From<Vec<crate::ln::msgs::UpdateFailHTLC>> for CVec_UpdateFailHTLCZ {
+       fn from(v: Vec<crate::ln::msgs::UpdateFailHTLC>) -> Self {
+               let datalen = v.len();
+               let data = Box::into_raw(v.into_boxed_slice());
+               Self { datalen, data: unsafe { (*data).as_mut_ptr() } }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CVec_UpdateFailHTLCZ_free(_res: CVec_UpdateFailHTLCZ) { }
+impl Drop for CVec_UpdateFailHTLCZ {
+       fn drop(&mut self) {
+               if self.datalen == 0 { return; }
+               unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) };
+       }
+}
+impl Clone for CVec_UpdateFailHTLCZ {
+       fn clone(&self) -> Self {
+               let mut res = Vec::new();
+               if self.datalen == 0 { return Self::from(res); }
+               res.extend_from_slice(unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) });
+               Self::from(res)
+       }
+}
+#[repr(C)]
+pub struct CVec_UpdateFailMalformedHTLCZ {
+       pub data: *mut crate::ln::msgs::UpdateFailMalformedHTLC,
+       pub datalen: usize
+}
+impl CVec_UpdateFailMalformedHTLCZ {
+       #[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec<crate::ln::msgs::UpdateFailMalformedHTLC> {
+               if self.datalen == 0 { return Vec::new(); }
+               let ret = unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }.into();
+               self.data = std::ptr::null_mut();
+               self.datalen = 0;
+               ret
+       }
+       #[allow(unused)] pub(crate) fn as_slice(&self) -> &[crate::ln::msgs::UpdateFailMalformedHTLC] {
+               unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) }
+       }
+}
+impl From<Vec<crate::ln::msgs::UpdateFailMalformedHTLC>> for CVec_UpdateFailMalformedHTLCZ {
+       fn from(v: Vec<crate::ln::msgs::UpdateFailMalformedHTLC>) -> Self {
+               let datalen = v.len();
+               let data = Box::into_raw(v.into_boxed_slice());
+               Self { datalen, data: unsafe { (*data).as_mut_ptr() } }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CVec_UpdateFailMalformedHTLCZ_free(_res: CVec_UpdateFailMalformedHTLCZ) { }
+impl Drop for CVec_UpdateFailMalformedHTLCZ {
+       fn drop(&mut self) {
+               if self.datalen == 0 { return; }
+               unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) };
+       }
+}
+impl Clone for CVec_UpdateFailMalformedHTLCZ {
+       fn clone(&self) -> Self {
+               let mut res = Vec::new();
+               if self.datalen == 0 { return Self::from(res); }
+               res.extend_from_slice(unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) });
+               Self::from(res)
+       }
+}
+#[repr(C)]
+pub union CResult_AcceptChannelDecodeErrorZPtr {
+       pub result: *mut crate::ln::msgs::AcceptChannel,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_AcceptChannelDecodeErrorZ {
+       pub contents: CResult_AcceptChannelDecodeErrorZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_AcceptChannelDecodeErrorZ_ok(o: crate::ln::msgs::AcceptChannel) -> CResult_AcceptChannelDecodeErrorZ {
+       CResult_AcceptChannelDecodeErrorZ {
+               contents: CResult_AcceptChannelDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_AcceptChannelDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_AcceptChannelDecodeErrorZ {
+       CResult_AcceptChannelDecodeErrorZ {
+               contents: CResult_AcceptChannelDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_AcceptChannelDecodeErrorZ_free(_res: CResult_AcceptChannelDecodeErrorZ) { }
+impl Drop for CResult_AcceptChannelDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::msgs::AcceptChannel, crate::ln::msgs::DecodeError>> for CResult_AcceptChannelDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::msgs::AcceptChannel, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_AcceptChannelDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_AcceptChannelDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_AcceptChannelDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_AcceptChannelDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::msgs::AcceptChannel>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_AcceptChannelDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_AcceptChannelDecodeErrorZ_clone(orig: &CResult_AcceptChannelDecodeErrorZ) -> CResult_AcceptChannelDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_AnnouncementSignaturesDecodeErrorZPtr {
+       pub result: *mut crate::ln::msgs::AnnouncementSignatures,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_AnnouncementSignaturesDecodeErrorZ {
+       pub contents: CResult_AnnouncementSignaturesDecodeErrorZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_AnnouncementSignaturesDecodeErrorZ_ok(o: crate::ln::msgs::AnnouncementSignatures) -> CResult_AnnouncementSignaturesDecodeErrorZ {
+       CResult_AnnouncementSignaturesDecodeErrorZ {
+               contents: CResult_AnnouncementSignaturesDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_AnnouncementSignaturesDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_AnnouncementSignaturesDecodeErrorZ {
+       CResult_AnnouncementSignaturesDecodeErrorZ {
+               contents: CResult_AnnouncementSignaturesDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_AnnouncementSignaturesDecodeErrorZ_free(_res: CResult_AnnouncementSignaturesDecodeErrorZ) { }
+impl Drop for CResult_AnnouncementSignaturesDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::msgs::AnnouncementSignatures, crate::ln::msgs::DecodeError>> for CResult_AnnouncementSignaturesDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::msgs::AnnouncementSignatures, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_AnnouncementSignaturesDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_AnnouncementSignaturesDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_AnnouncementSignaturesDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_AnnouncementSignaturesDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::msgs::AnnouncementSignatures>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_AnnouncementSignaturesDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CResult_AnnouncementSignaturesDecodeErrorZ_clone(orig: &CResult_AnnouncementSignaturesDecodeErrorZ) -> CResult_AnnouncementSignaturesDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_ChannelReestablishDecodeErrorZPtr {
+       pub result: *mut crate::ln::msgs::ChannelReestablish,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_ChannelReestablishDecodeErrorZ {
+       pub contents: CResult_ChannelReestablishDecodeErrorZPtr,
+       pub result_ok: bool,
+}
+#[no_mangle]
+pub extern "C" fn CResult_ChannelReestablishDecodeErrorZ_ok(o: crate::ln::msgs::ChannelReestablish) -> CResult_ChannelReestablishDecodeErrorZ {
+       CResult_ChannelReestablishDecodeErrorZ {
+               contents: CResult_ChannelReestablishDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
 }
-
 #[no_mangle]
-pub type CVec_C2Tuple_u32TxOutZZ = crate::c_types::CVecTempl<crate::c_types::C2TupleTempl<u32, crate::c_types::TxOut>>;
+pub extern "C" fn CResult_ChannelReestablishDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_ChannelReestablishDecodeErrorZ {
+       CResult_ChannelReestablishDecodeErrorZ {
+               contents: CResult_ChannelReestablishDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
 #[no_mangle]
-pub static CVec_C2Tuple_u32TxOutZZ_free: extern "C" fn(CVec_C2Tuple_u32TxOutZZ) = crate::c_types::CVecTempl_free::<crate::c_types::C2TupleTempl<u32, crate::c_types::TxOut>>;
-
+pub extern "C" fn CResult_ChannelReestablishDecodeErrorZ_free(_res: CResult_ChannelReestablishDecodeErrorZ) { }
+impl Drop for CResult_ChannelReestablishDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::msgs::ChannelReestablish, crate::ln::msgs::DecodeError>> for CResult_ChannelReestablishDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::msgs::ChannelReestablish, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_ChannelReestablishDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_ChannelReestablishDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_ChannelReestablishDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_ChannelReestablishDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::msgs::ChannelReestablish>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_ChannelReestablishDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
 #[no_mangle]
-pub type C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ = crate::c_types::C2TupleTempl<crate::c_types::ThirtyTwoBytes, crate::c_types::CVecTempl<crate::c_types::C2TupleTempl<u32, crate::c_types::TxOut>>>;
+pub extern "C" fn CResult_ChannelReestablishDecodeErrorZ_clone(orig: &CResult_ChannelReestablishDecodeErrorZ) -> CResult_ChannelReestablishDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_ClosingSignedDecodeErrorZPtr {
+       pub result: *mut crate::ln::msgs::ClosingSigned,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_ClosingSignedDecodeErrorZ {
+       pub contents: CResult_ClosingSignedDecodeErrorZPtr,
+       pub result_ok: bool,
+}
 #[no_mangle]
-pub static C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ_free: extern "C" fn(C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ) = crate::c_types::C2TupleTempl_free::<crate::c_types::ThirtyTwoBytes, crate::c_types::CVecTempl<crate::c_types::C2TupleTempl<u32, crate::c_types::TxOut>>>;
+pub extern "C" fn CResult_ClosingSignedDecodeErrorZ_ok(o: crate::ln::msgs::ClosingSigned) -> CResult_ClosingSignedDecodeErrorZ {
+       CResult_ClosingSignedDecodeErrorZ {
+               contents: CResult_ClosingSignedDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
 #[no_mangle]
-pub extern "C" fn C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ_new(a: crate::c_types::ThirtyTwoBytes, b: crate::c_types::derived::CVec_C2Tuple_u32TxOutZZ) -> C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ {
-       C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ { a, b, }
+pub extern "C" fn CResult_ClosingSignedDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_ClosingSignedDecodeErrorZ {
+       CResult_ClosingSignedDecodeErrorZ {
+               contents: CResult_ClosingSignedDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
 }
-
 #[no_mangle]
-pub type CVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ = crate::c_types::CVecTempl<crate::c_types::C2TupleTempl<crate::c_types::ThirtyTwoBytes, crate::c_types::CVecTempl<crate::c_types::C2TupleTempl<u32, crate::c_types::TxOut>>>>;
+pub extern "C" fn CResult_ClosingSignedDecodeErrorZ_free(_res: CResult_ClosingSignedDecodeErrorZ) { }
+impl Drop for CResult_ClosingSignedDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::msgs::ClosingSigned, crate::ln::msgs::DecodeError>> for CResult_ClosingSignedDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::msgs::ClosingSigned, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_ClosingSignedDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_ClosingSignedDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_ClosingSignedDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_ClosingSignedDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::msgs::ClosingSigned>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_ClosingSignedDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
 #[no_mangle]
-pub static CVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ_free: extern "C" fn(CVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ) = crate::c_types::CVecTempl_free::<crate::c_types::C2TupleTempl<crate::c_types::ThirtyTwoBytes, crate::c_types::CVecTempl<crate::c_types::C2TupleTempl<u32, crate::c_types::TxOut>>>>;
-
+pub extern "C" fn CResult_ClosingSignedDecodeErrorZ_clone(orig: &CResult_ClosingSignedDecodeErrorZ) -> CResult_ClosingSignedDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_CommitmentSignedDecodeErrorZPtr {
+       pub result: *mut crate::ln::msgs::CommitmentSigned,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_CommitmentSignedDecodeErrorZ {
+       pub contents: CResult_CommitmentSignedDecodeErrorZPtr,
+       pub result_ok: bool,
+}
 #[no_mangle]
-pub type C2Tuple_u64u64Z = crate::c_types::C2TupleTempl<u64, u64>;
+pub extern "C" fn CResult_CommitmentSignedDecodeErrorZ_ok(o: crate::ln::msgs::CommitmentSigned) -> CResult_CommitmentSignedDecodeErrorZ {
+       CResult_CommitmentSignedDecodeErrorZ {
+               contents: CResult_CommitmentSignedDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
 #[no_mangle]
-pub static C2Tuple_u64u64Z_free: extern "C" fn(C2Tuple_u64u64Z) = crate::c_types::C2TupleTempl_free::<u64, u64>;
+pub extern "C" fn CResult_CommitmentSignedDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_CommitmentSignedDecodeErrorZ {
+       CResult_CommitmentSignedDecodeErrorZ {
+               contents: CResult_CommitmentSignedDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
 #[no_mangle]
-pub extern "C" fn C2Tuple_u64u64Z_new(a: u64, b: u64) -> C2Tuple_u64u64Z {
-       C2Tuple_u64u64Z { a, b, }
+pub extern "C" fn CResult_CommitmentSignedDecodeErrorZ_free(_res: CResult_CommitmentSignedDecodeErrorZ) { }
+impl Drop for CResult_CommitmentSignedDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::msgs::CommitmentSigned, crate::ln::msgs::DecodeError>> for CResult_CommitmentSignedDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::msgs::CommitmentSigned, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_CommitmentSignedDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_CommitmentSignedDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_CommitmentSignedDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_CommitmentSignedDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::msgs::CommitmentSigned>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_CommitmentSignedDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
 }
-
 #[no_mangle]
-pub type CVec_HTLCOutputInCommitmentZ = crate::c_types::CVecTempl<crate::ln::chan_utils::HTLCOutputInCommitment>;
+pub extern "C" fn CResult_CommitmentSignedDecodeErrorZ_clone(orig: &CResult_CommitmentSignedDecodeErrorZ) -> CResult_CommitmentSignedDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_FundingCreatedDecodeErrorZPtr {
+       pub result: *mut crate::ln::msgs::FundingCreated,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_FundingCreatedDecodeErrorZ {
+       pub contents: CResult_FundingCreatedDecodeErrorZPtr,
+       pub result_ok: bool,
+}
 #[no_mangle]
-pub static CVec_HTLCOutputInCommitmentZ_free: extern "C" fn(CVec_HTLCOutputInCommitmentZ) = crate::c_types::CVecTempl_free::<crate::ln::chan_utils::HTLCOutputInCommitment>;
-
+pub extern "C" fn CResult_FundingCreatedDecodeErrorZ_ok(o: crate::ln::msgs::FundingCreated) -> CResult_FundingCreatedDecodeErrorZ {
+       CResult_FundingCreatedDecodeErrorZ {
+               contents: CResult_FundingCreatedDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
 #[no_mangle]
-pub type CVec_SignatureZ = crate::c_types::CVecTempl<crate::c_types::Signature>;
+pub extern "C" fn CResult_FundingCreatedDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_FundingCreatedDecodeErrorZ {
+       CResult_FundingCreatedDecodeErrorZ {
+               contents: CResult_FundingCreatedDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
 #[no_mangle]
-pub static CVec_SignatureZ_free: extern "C" fn(CVec_SignatureZ) = crate::c_types::CVecTempl_free::<crate::c_types::Signature>;
-
+pub extern "C" fn CResult_FundingCreatedDecodeErrorZ_free(_res: CResult_FundingCreatedDecodeErrorZ) { }
+impl Drop for CResult_FundingCreatedDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::msgs::FundingCreated, crate::ln::msgs::DecodeError>> for CResult_FundingCreatedDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::msgs::FundingCreated, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_FundingCreatedDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_FundingCreatedDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_FundingCreatedDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_FundingCreatedDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::msgs::FundingCreated>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_FundingCreatedDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
 #[no_mangle]
-pub type C2Tuple_SignatureCVec_SignatureZZ = crate::c_types::C2TupleTempl<crate::c_types::Signature, crate::c_types::CVecTempl<crate::c_types::Signature>>;
+pub extern "C" fn CResult_FundingCreatedDecodeErrorZ_clone(orig: &CResult_FundingCreatedDecodeErrorZ) -> CResult_FundingCreatedDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_FundingSignedDecodeErrorZPtr {
+       pub result: *mut crate::ln::msgs::FundingSigned,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_FundingSignedDecodeErrorZ {
+       pub contents: CResult_FundingSignedDecodeErrorZPtr,
+       pub result_ok: bool,
+}
 #[no_mangle]
-pub static C2Tuple_SignatureCVec_SignatureZZ_free: extern "C" fn(C2Tuple_SignatureCVec_SignatureZZ) = crate::c_types::C2TupleTempl_free::<crate::c_types::Signature, crate::c_types::CVecTempl<crate::c_types::Signature>>;
+pub extern "C" fn CResult_FundingSignedDecodeErrorZ_ok(o: crate::ln::msgs::FundingSigned) -> CResult_FundingSignedDecodeErrorZ {
+       CResult_FundingSignedDecodeErrorZ {
+               contents: CResult_FundingSignedDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
 #[no_mangle]
-pub extern "C" fn C2Tuple_SignatureCVec_SignatureZZ_new(a: crate::c_types::Signature, b: crate::c_types::derived::CVec_SignatureZ) -> C2Tuple_SignatureCVec_SignatureZZ {
-       C2Tuple_SignatureCVec_SignatureZZ { a, b, }
+pub extern "C" fn CResult_FundingSignedDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_FundingSignedDecodeErrorZ {
+       CResult_FundingSignedDecodeErrorZ {
+               contents: CResult_FundingSignedDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
 }
-
 #[no_mangle]
-pub type CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ = crate::c_types::CResultTempl<crate::c_types::C2TupleTempl<crate::c_types::Signature, crate::c_types::CVecTempl<crate::c_types::Signature>>, u8>;
+pub extern "C" fn CResult_FundingSignedDecodeErrorZ_free(_res: CResult_FundingSignedDecodeErrorZ) { }
+impl Drop for CResult_FundingSignedDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::msgs::FundingSigned, crate::ln::msgs::DecodeError>> for CResult_FundingSignedDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::msgs::FundingSigned, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_FundingSignedDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_FundingSignedDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_FundingSignedDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_FundingSignedDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::msgs::FundingSigned>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_FundingSignedDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
 #[no_mangle]
-pub static CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ_free: extern "C" fn(CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ) = crate::c_types::CResultTempl_free::<crate::c_types::C2TupleTempl<crate::c_types::Signature, crate::c_types::CVecTempl<crate::c_types::Signature>>, u8>;
+pub extern "C" fn CResult_FundingSignedDecodeErrorZ_clone(orig: &CResult_FundingSignedDecodeErrorZ) -> CResult_FundingSignedDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_FundingLockedDecodeErrorZPtr {
+       pub result: *mut crate::ln::msgs::FundingLocked,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_FundingLockedDecodeErrorZ {
+       pub contents: CResult_FundingLockedDecodeErrorZPtr,
+       pub result_ok: bool,
+}
 #[no_mangle]
-pub static CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ_ok: extern "C" fn (C2Tuple_SignatureCVec_SignatureZZ) -> CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ =
-       crate::c_types::CResultTempl::<crate::c_types::C2TupleTempl<crate::c_types::Signature, crate::c_types::CVecTempl<crate::c_types::Signature>>, u8>::ok;
-
+pub extern "C" fn CResult_FundingLockedDecodeErrorZ_ok(o: crate::ln::msgs::FundingLocked) -> CResult_FundingLockedDecodeErrorZ {
+       CResult_FundingLockedDecodeErrorZ {
+               contents: CResult_FundingLockedDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
 #[no_mangle]
-pub extern "C" fn CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ_err() -> CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ {
-       crate::c_types::CResultTempl::err(0)
+pub extern "C" fn CResult_FundingLockedDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_FundingLockedDecodeErrorZ {
+       CResult_FundingLockedDecodeErrorZ {
+               contents: CResult_FundingLockedDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
 }
-
 #[no_mangle]
-pub type CResult_SignatureNoneZ = crate::c_types::CResultTempl<crate::c_types::Signature, u8>;
+pub extern "C" fn CResult_FundingLockedDecodeErrorZ_free(_res: CResult_FundingLockedDecodeErrorZ) { }
+impl Drop for CResult_FundingLockedDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::msgs::FundingLocked, crate::ln::msgs::DecodeError>> for CResult_FundingLockedDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::msgs::FundingLocked, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_FundingLockedDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_FundingLockedDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_FundingLockedDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_FundingLockedDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::msgs::FundingLocked>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_FundingLockedDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
 #[no_mangle]
-pub static CResult_SignatureNoneZ_free: extern "C" fn(CResult_SignatureNoneZ) = crate::c_types::CResultTempl_free::<crate::c_types::Signature, u8>;
+pub extern "C" fn CResult_FundingLockedDecodeErrorZ_clone(orig: &CResult_FundingLockedDecodeErrorZ) -> CResult_FundingLockedDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_InitDecodeErrorZPtr {
+       pub result: *mut crate::ln::msgs::Init,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_InitDecodeErrorZ {
+       pub contents: CResult_InitDecodeErrorZPtr,
+       pub result_ok: bool,
+}
 #[no_mangle]
-pub static CResult_SignatureNoneZ_ok: extern "C" fn (crate::c_types::Signature) -> CResult_SignatureNoneZ =
-       crate::c_types::CResultTempl::<crate::c_types::Signature, u8>::ok;
-
+pub extern "C" fn CResult_InitDecodeErrorZ_ok(o: crate::ln::msgs::Init) -> CResult_InitDecodeErrorZ {
+       CResult_InitDecodeErrorZ {
+               contents: CResult_InitDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
 #[no_mangle]
-pub extern "C" fn CResult_SignatureNoneZ_err() -> CResult_SignatureNoneZ {
-       crate::c_types::CResultTempl::err(0)
+pub extern "C" fn CResult_InitDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_InitDecodeErrorZ {
+       CResult_InitDecodeErrorZ {
+               contents: CResult_InitDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
 }
-
 #[no_mangle]
-pub type CResult_CVec_SignatureZNoneZ = crate::c_types::CResultTempl<crate::c_types::CVecTempl<crate::c_types::Signature>, u8>;
+pub extern "C" fn CResult_InitDecodeErrorZ_free(_res: CResult_InitDecodeErrorZ) { }
+impl Drop for CResult_InitDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::msgs::Init, crate::ln::msgs::DecodeError>> for CResult_InitDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::msgs::Init, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_InitDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_InitDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_InitDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_InitDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::msgs::Init>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_InitDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
 #[no_mangle]
-pub static CResult_CVec_SignatureZNoneZ_free: extern "C" fn(CResult_CVec_SignatureZNoneZ) = crate::c_types::CResultTempl_free::<crate::c_types::CVecTempl<crate::c_types::Signature>, u8>;
+pub extern "C" fn CResult_InitDecodeErrorZ_clone(orig: &CResult_InitDecodeErrorZ) -> CResult_InitDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_OpenChannelDecodeErrorZPtr {
+       pub result: *mut crate::ln::msgs::OpenChannel,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_OpenChannelDecodeErrorZ {
+       pub contents: CResult_OpenChannelDecodeErrorZPtr,
+       pub result_ok: bool,
+}
 #[no_mangle]
-pub static CResult_CVec_SignatureZNoneZ_ok: extern "C" fn (CVec_SignatureZ) -> CResult_CVec_SignatureZNoneZ =
-       crate::c_types::CResultTempl::<crate::c_types::CVecTempl<crate::c_types::Signature>, u8>::ok;
-
+pub extern "C" fn CResult_OpenChannelDecodeErrorZ_ok(o: crate::ln::msgs::OpenChannel) -> CResult_OpenChannelDecodeErrorZ {
+       CResult_OpenChannelDecodeErrorZ {
+               contents: CResult_OpenChannelDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
 #[no_mangle]
-pub extern "C" fn CResult_CVec_SignatureZNoneZ_err() -> CResult_CVec_SignatureZNoneZ {
-       crate::c_types::CResultTempl::err(0)
+pub extern "C" fn CResult_OpenChannelDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_OpenChannelDecodeErrorZ {
+       CResult_OpenChannelDecodeErrorZ {
+               contents: CResult_OpenChannelDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
 }
-
 #[no_mangle]
-pub type CResult_TxOutAccessErrorZ = crate::c_types::CResultTempl<crate::c_types::TxOut, crate::chain::AccessError>;
+pub extern "C" fn CResult_OpenChannelDecodeErrorZ_free(_res: CResult_OpenChannelDecodeErrorZ) { }
+impl Drop for CResult_OpenChannelDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::msgs::OpenChannel, crate::ln::msgs::DecodeError>> for CResult_OpenChannelDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::msgs::OpenChannel, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_OpenChannelDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_OpenChannelDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_OpenChannelDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_OpenChannelDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::msgs::OpenChannel>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_OpenChannelDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
 #[no_mangle]
-pub static CResult_TxOutAccessErrorZ_free: extern "C" fn(CResult_TxOutAccessErrorZ) = crate::c_types::CResultTempl_free::<crate::c_types::TxOut, crate::chain::AccessError>;
+pub extern "C" fn CResult_OpenChannelDecodeErrorZ_clone(orig: &CResult_OpenChannelDecodeErrorZ) -> CResult_OpenChannelDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_RevokeAndACKDecodeErrorZPtr {
+       pub result: *mut crate::ln::msgs::RevokeAndACK,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_RevokeAndACKDecodeErrorZ {
+       pub contents: CResult_RevokeAndACKDecodeErrorZPtr,
+       pub result_ok: bool,
+}
 #[no_mangle]
-pub static CResult_TxOutAccessErrorZ_ok: extern "C" fn (crate::c_types::TxOut) -> CResult_TxOutAccessErrorZ =
-       crate::c_types::CResultTempl::<crate::c_types::TxOut, crate::chain::AccessError>::ok;
-
+pub extern "C" fn CResult_RevokeAndACKDecodeErrorZ_ok(o: crate::ln::msgs::RevokeAndACK) -> CResult_RevokeAndACKDecodeErrorZ {
+       CResult_RevokeAndACKDecodeErrorZ {
+               contents: CResult_RevokeAndACKDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
 #[no_mangle]
-pub static CResult_TxOutAccessErrorZ_err: extern "C" fn (crate::chain::AccessError) -> CResult_TxOutAccessErrorZ =
-       crate::c_types::CResultTempl::<crate::c_types::TxOut, crate::chain::AccessError>::err;
-
+pub extern "C" fn CResult_RevokeAndACKDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_RevokeAndACKDecodeErrorZ {
+       CResult_RevokeAndACKDecodeErrorZ {
+               contents: CResult_RevokeAndACKDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
 #[no_mangle]
-pub type CResult_NoneAPIErrorZ = crate::c_types::CResultTempl<u8, crate::util::errors::APIError>;
+pub extern "C" fn CResult_RevokeAndACKDecodeErrorZ_free(_res: CResult_RevokeAndACKDecodeErrorZ) { }
+impl Drop for CResult_RevokeAndACKDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::msgs::RevokeAndACK, crate::ln::msgs::DecodeError>> for CResult_RevokeAndACKDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::msgs::RevokeAndACK, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_RevokeAndACKDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_RevokeAndACKDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_RevokeAndACKDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_RevokeAndACKDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::msgs::RevokeAndACK>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_RevokeAndACKDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
 #[no_mangle]
-pub static CResult_NoneAPIErrorZ_free: extern "C" fn(CResult_NoneAPIErrorZ) = crate::c_types::CResultTempl_free::<u8, crate::util::errors::APIError>;
+pub extern "C" fn CResult_RevokeAndACKDecodeErrorZ_clone(orig: &CResult_RevokeAndACKDecodeErrorZ) -> CResult_RevokeAndACKDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_ShutdownDecodeErrorZPtr {
+       pub result: *mut crate::ln::msgs::Shutdown,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_ShutdownDecodeErrorZ {
+       pub contents: CResult_ShutdownDecodeErrorZPtr,
+       pub result_ok: bool,
+}
 #[no_mangle]
-pub extern "C" fn CResult_NoneAPIErrorZ_ok() -> CResult_NoneAPIErrorZ {
-       crate::c_types::CResultTempl::ok(0)
+pub extern "C" fn CResult_ShutdownDecodeErrorZ_ok(o: crate::ln::msgs::Shutdown) -> CResult_ShutdownDecodeErrorZ {
+       CResult_ShutdownDecodeErrorZ {
+               contents: CResult_ShutdownDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
 }
-
 #[no_mangle]
-pub static CResult_NoneAPIErrorZ_err: extern "C" fn (crate::util::errors::APIError) -> CResult_NoneAPIErrorZ =
-       crate::c_types::CResultTempl::<u8, crate::util::errors::APIError>::err;
-
+pub extern "C" fn CResult_ShutdownDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_ShutdownDecodeErrorZ {
+       CResult_ShutdownDecodeErrorZ {
+               contents: CResult_ShutdownDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
 #[no_mangle]
-pub type CVec_ChannelDetailsZ = crate::c_types::CVecTempl<crate::ln::channelmanager::ChannelDetails>;
+pub extern "C" fn CResult_ShutdownDecodeErrorZ_free(_res: CResult_ShutdownDecodeErrorZ) { }
+impl Drop for CResult_ShutdownDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::msgs::Shutdown, crate::ln::msgs::DecodeError>> for CResult_ShutdownDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::msgs::Shutdown, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_ShutdownDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_ShutdownDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_ShutdownDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_ShutdownDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::msgs::Shutdown>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_ShutdownDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
 #[no_mangle]
-pub static CVec_ChannelDetailsZ_free: extern "C" fn(CVec_ChannelDetailsZ) = crate::c_types::CVecTempl_free::<crate::ln::channelmanager::ChannelDetails>;
-
+pub extern "C" fn CResult_ShutdownDecodeErrorZ_clone(orig: &CResult_ShutdownDecodeErrorZ) -> CResult_ShutdownDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_UpdateFailHTLCDecodeErrorZPtr {
+       pub result: *mut crate::ln::msgs::UpdateFailHTLC,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_UpdateFailHTLCDecodeErrorZ {
+       pub contents: CResult_UpdateFailHTLCDecodeErrorZPtr,
+       pub result_ok: bool,
+}
 #[no_mangle]
-pub type CResult_NonePaymentSendFailureZ = crate::c_types::CResultTempl<u8, crate::ln::channelmanager::PaymentSendFailure>;
+pub extern "C" fn CResult_UpdateFailHTLCDecodeErrorZ_ok(o: crate::ln::msgs::UpdateFailHTLC) -> CResult_UpdateFailHTLCDecodeErrorZ {
+       CResult_UpdateFailHTLCDecodeErrorZ {
+               contents: CResult_UpdateFailHTLCDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
 #[no_mangle]
-pub static CResult_NonePaymentSendFailureZ_free: extern "C" fn(CResult_NonePaymentSendFailureZ) = crate::c_types::CResultTempl_free::<u8, crate::ln::channelmanager::PaymentSendFailure>;
+pub extern "C" fn CResult_UpdateFailHTLCDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_UpdateFailHTLCDecodeErrorZ {
+       CResult_UpdateFailHTLCDecodeErrorZ {
+               contents: CResult_UpdateFailHTLCDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
 #[no_mangle]
-pub extern "C" fn CResult_NonePaymentSendFailureZ_ok() -> CResult_NonePaymentSendFailureZ {
-       crate::c_types::CResultTempl::ok(0)
+pub extern "C" fn CResult_UpdateFailHTLCDecodeErrorZ_free(_res: CResult_UpdateFailHTLCDecodeErrorZ) { }
+impl Drop for CResult_UpdateFailHTLCDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::msgs::UpdateFailHTLC, crate::ln::msgs::DecodeError>> for CResult_UpdateFailHTLCDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::msgs::UpdateFailHTLC, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_UpdateFailHTLCDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_UpdateFailHTLCDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_UpdateFailHTLCDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_UpdateFailHTLCDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::msgs::UpdateFailHTLC>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_UpdateFailHTLCDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
 }
-
 #[no_mangle]
-pub static CResult_NonePaymentSendFailureZ_err: extern "C" fn (crate::ln::channelmanager::PaymentSendFailure) -> CResult_NonePaymentSendFailureZ =
-       crate::c_types::CResultTempl::<u8, crate::ln::channelmanager::PaymentSendFailure>::err;
-
+pub extern "C" fn CResult_UpdateFailHTLCDecodeErrorZ_clone(orig: &CResult_UpdateFailHTLCDecodeErrorZ) -> CResult_UpdateFailHTLCDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_UpdateFailMalformedHTLCDecodeErrorZPtr {
+       pub result: *mut crate::ln::msgs::UpdateFailMalformedHTLC,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_UpdateFailMalformedHTLCDecodeErrorZ {
+       pub contents: CResult_UpdateFailMalformedHTLCDecodeErrorZPtr,
+       pub result_ok: bool,
+}
 #[no_mangle]
-pub type CVec_NetAddressZ = crate::c_types::CVecTempl<crate::ln::msgs::NetAddress>;
+pub extern "C" fn CResult_UpdateFailMalformedHTLCDecodeErrorZ_ok(o: crate::ln::msgs::UpdateFailMalformedHTLC) -> CResult_UpdateFailMalformedHTLCDecodeErrorZ {
+       CResult_UpdateFailMalformedHTLCDecodeErrorZ {
+               contents: CResult_UpdateFailMalformedHTLCDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
 #[no_mangle]
-pub static CVec_NetAddressZ_free: extern "C" fn(CVec_NetAddressZ) = crate::c_types::CVecTempl_free::<crate::ln::msgs::NetAddress>;
-
+pub extern "C" fn CResult_UpdateFailMalformedHTLCDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_UpdateFailMalformedHTLCDecodeErrorZ {
+       CResult_UpdateFailMalformedHTLCDecodeErrorZ {
+               contents: CResult_UpdateFailMalformedHTLCDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
 #[no_mangle]
-pub type CVec_ChannelMonitorZ = crate::c_types::CVecTempl<crate::chain::channelmonitor::ChannelMonitor>;
+pub extern "C" fn CResult_UpdateFailMalformedHTLCDecodeErrorZ_free(_res: CResult_UpdateFailMalformedHTLCDecodeErrorZ) { }
+impl Drop for CResult_UpdateFailMalformedHTLCDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::msgs::UpdateFailMalformedHTLC, crate::ln::msgs::DecodeError>> for CResult_UpdateFailMalformedHTLCDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::msgs::UpdateFailMalformedHTLC, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_UpdateFailMalformedHTLCDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_UpdateFailMalformedHTLCDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_UpdateFailMalformedHTLCDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_UpdateFailMalformedHTLCDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::msgs::UpdateFailMalformedHTLC>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_UpdateFailMalformedHTLCDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
 #[no_mangle]
-pub static CVec_ChannelMonitorZ_free: extern "C" fn(CVec_ChannelMonitorZ) = crate::c_types::CVecTempl_free::<crate::chain::channelmonitor::ChannelMonitor>;
-
+pub extern "C" fn CResult_UpdateFailMalformedHTLCDecodeErrorZ_clone(orig: &CResult_UpdateFailMalformedHTLCDecodeErrorZ) -> CResult_UpdateFailMalformedHTLCDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_UpdateFeeDecodeErrorZPtr {
+       pub result: *mut crate::ln::msgs::UpdateFee,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_UpdateFeeDecodeErrorZ {
+       pub contents: CResult_UpdateFeeDecodeErrorZPtr,
+       pub result_ok: bool,
+}
 #[no_mangle]
-pub type CVec_u64Z = crate::c_types::CVecTempl<u64>;
+pub extern "C" fn CResult_UpdateFeeDecodeErrorZ_ok(o: crate::ln::msgs::UpdateFee) -> CResult_UpdateFeeDecodeErrorZ {
+       CResult_UpdateFeeDecodeErrorZ {
+               contents: CResult_UpdateFeeDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
 #[no_mangle]
-pub static CVec_u64Z_free: extern "C" fn(CVec_u64Z) = crate::c_types::CVecTempl_free::<u64>;
-
+pub extern "C" fn CResult_UpdateFeeDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_UpdateFeeDecodeErrorZ {
+       CResult_UpdateFeeDecodeErrorZ {
+               contents: CResult_UpdateFeeDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
 #[no_mangle]
-pub type CVec_UpdateAddHTLCZ = crate::c_types::CVecTempl<crate::ln::msgs::UpdateAddHTLC>;
+pub extern "C" fn CResult_UpdateFeeDecodeErrorZ_free(_res: CResult_UpdateFeeDecodeErrorZ) { }
+impl Drop for CResult_UpdateFeeDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::msgs::UpdateFee, crate::ln::msgs::DecodeError>> for CResult_UpdateFeeDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::msgs::UpdateFee, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_UpdateFeeDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_UpdateFeeDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_UpdateFeeDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_UpdateFeeDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::msgs::UpdateFee>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_UpdateFeeDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
 #[no_mangle]
-pub static CVec_UpdateAddHTLCZ_free: extern "C" fn(CVec_UpdateAddHTLCZ) = crate::c_types::CVecTempl_free::<crate::ln::msgs::UpdateAddHTLC>;
-
+pub extern "C" fn CResult_UpdateFeeDecodeErrorZ_clone(orig: &CResult_UpdateFeeDecodeErrorZ) -> CResult_UpdateFeeDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_UpdateFulfillHTLCDecodeErrorZPtr {
+       pub result: *mut crate::ln::msgs::UpdateFulfillHTLC,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_UpdateFulfillHTLCDecodeErrorZ {
+       pub contents: CResult_UpdateFulfillHTLCDecodeErrorZPtr,
+       pub result_ok: bool,
+}
 #[no_mangle]
-pub type CVec_UpdateFulfillHTLCZ = crate::c_types::CVecTempl<crate::ln::msgs::UpdateFulfillHTLC>;
+pub extern "C" fn CResult_UpdateFulfillHTLCDecodeErrorZ_ok(o: crate::ln::msgs::UpdateFulfillHTLC) -> CResult_UpdateFulfillHTLCDecodeErrorZ {
+       CResult_UpdateFulfillHTLCDecodeErrorZ {
+               contents: CResult_UpdateFulfillHTLCDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
 #[no_mangle]
-pub static CVec_UpdateFulfillHTLCZ_free: extern "C" fn(CVec_UpdateFulfillHTLCZ) = crate::c_types::CVecTempl_free::<crate::ln::msgs::UpdateFulfillHTLC>;
-
+pub extern "C" fn CResult_UpdateFulfillHTLCDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_UpdateFulfillHTLCDecodeErrorZ {
+       CResult_UpdateFulfillHTLCDecodeErrorZ {
+               contents: CResult_UpdateFulfillHTLCDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
 #[no_mangle]
-pub type CVec_UpdateFailHTLCZ = crate::c_types::CVecTempl<crate::ln::msgs::UpdateFailHTLC>;
+pub extern "C" fn CResult_UpdateFulfillHTLCDecodeErrorZ_free(_res: CResult_UpdateFulfillHTLCDecodeErrorZ) { }
+impl Drop for CResult_UpdateFulfillHTLCDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::msgs::UpdateFulfillHTLC, crate::ln::msgs::DecodeError>> for CResult_UpdateFulfillHTLCDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::msgs::UpdateFulfillHTLC, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_UpdateFulfillHTLCDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_UpdateFulfillHTLCDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_UpdateFulfillHTLCDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_UpdateFulfillHTLCDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::msgs::UpdateFulfillHTLC>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_UpdateFulfillHTLCDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
 #[no_mangle]
-pub static CVec_UpdateFailHTLCZ_free: extern "C" fn(CVec_UpdateFailHTLCZ) = crate::c_types::CVecTempl_free::<crate::ln::msgs::UpdateFailHTLC>;
-
+pub extern "C" fn CResult_UpdateFulfillHTLCDecodeErrorZ_clone(orig: &CResult_UpdateFulfillHTLCDecodeErrorZ) -> CResult_UpdateFulfillHTLCDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_UpdateAddHTLCDecodeErrorZPtr {
+       pub result: *mut crate::ln::msgs::UpdateAddHTLC,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_UpdateAddHTLCDecodeErrorZ {
+       pub contents: CResult_UpdateAddHTLCDecodeErrorZPtr,
+       pub result_ok: bool,
+}
 #[no_mangle]
-pub type CVec_UpdateFailMalformedHTLCZ = crate::c_types::CVecTempl<crate::ln::msgs::UpdateFailMalformedHTLC>;
+pub extern "C" fn CResult_UpdateAddHTLCDecodeErrorZ_ok(o: crate::ln::msgs::UpdateAddHTLC) -> CResult_UpdateAddHTLCDecodeErrorZ {
+       CResult_UpdateAddHTLCDecodeErrorZ {
+               contents: CResult_UpdateAddHTLCDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
 #[no_mangle]
-pub static CVec_UpdateFailMalformedHTLCZ_free: extern "C" fn(CVec_UpdateFailMalformedHTLCZ) = crate::c_types::CVecTempl_free::<crate::ln::msgs::UpdateFailMalformedHTLC>;
-
+pub extern "C" fn CResult_UpdateAddHTLCDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_UpdateAddHTLCDecodeErrorZ {
+       CResult_UpdateAddHTLCDecodeErrorZ {
+               contents: CResult_UpdateAddHTLCDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
 #[no_mangle]
-pub type CResult_boolLightningErrorZ = crate::c_types::CResultTempl<bool, crate::ln::msgs::LightningError>;
+pub extern "C" fn CResult_UpdateAddHTLCDecodeErrorZ_free(_res: CResult_UpdateAddHTLCDecodeErrorZ) { }
+impl Drop for CResult_UpdateAddHTLCDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::msgs::UpdateAddHTLC, crate::ln::msgs::DecodeError>> for CResult_UpdateAddHTLCDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::msgs::UpdateAddHTLC, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_UpdateAddHTLCDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_UpdateAddHTLCDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_UpdateAddHTLCDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_UpdateAddHTLCDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::msgs::UpdateAddHTLC>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_UpdateAddHTLCDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
 #[no_mangle]
-pub static CResult_boolLightningErrorZ_free: extern "C" fn(CResult_boolLightningErrorZ) = crate::c_types::CResultTempl_free::<bool, crate::ln::msgs::LightningError>;
+pub extern "C" fn CResult_UpdateAddHTLCDecodeErrorZ_clone(orig: &CResult_UpdateAddHTLCDecodeErrorZ) -> CResult_UpdateAddHTLCDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_PingDecodeErrorZPtr {
+       pub result: *mut crate::ln::msgs::Ping,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_PingDecodeErrorZ {
+       pub contents: CResult_PingDecodeErrorZPtr,
+       pub result_ok: bool,
+}
 #[no_mangle]
-pub static CResult_boolLightningErrorZ_ok: extern "C" fn (bool) -> CResult_boolLightningErrorZ =
-       crate::c_types::CResultTempl::<bool, crate::ln::msgs::LightningError>::ok;
-
+pub extern "C" fn CResult_PingDecodeErrorZ_ok(o: crate::ln::msgs::Ping) -> CResult_PingDecodeErrorZ {
+       CResult_PingDecodeErrorZ {
+               contents: CResult_PingDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
 #[no_mangle]
-pub static CResult_boolLightningErrorZ_err: extern "C" fn (crate::ln::msgs::LightningError) -> CResult_boolLightningErrorZ =
-       crate::c_types::CResultTempl::<bool, crate::ln::msgs::LightningError>::err;
-
+pub extern "C" fn CResult_PingDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_PingDecodeErrorZ {
+       CResult_PingDecodeErrorZ {
+               contents: CResult_PingDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
 #[no_mangle]
-pub type C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ = crate::c_types::C3TupleTempl<crate::ln::msgs::ChannelAnnouncement, crate::ln::msgs::ChannelUpdate, crate::ln::msgs::ChannelUpdate>;
+pub extern "C" fn CResult_PingDecodeErrorZ_free(_res: CResult_PingDecodeErrorZ) { }
+impl Drop for CResult_PingDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::msgs::Ping, crate::ln::msgs::DecodeError>> for CResult_PingDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::msgs::Ping, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_PingDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_PingDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_PingDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_PingDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::msgs::Ping>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_PingDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
 #[no_mangle]
-pub static C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ_free: extern "C" fn(C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ) = crate::c_types::C3TupleTempl_free::<crate::ln::msgs::ChannelAnnouncement, crate::ln::msgs::ChannelUpdate, crate::ln::msgs::ChannelUpdate>;
+pub extern "C" fn CResult_PingDecodeErrorZ_clone(orig: &CResult_PingDecodeErrorZ) -> CResult_PingDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_PongDecodeErrorZPtr {
+       pub result: *mut crate::ln::msgs::Pong,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_PongDecodeErrorZ {
+       pub contents: CResult_PongDecodeErrorZPtr,
+       pub result_ok: bool,
+}
 #[no_mangle]
-pub extern "C" fn C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ_new(a: crate::ln::msgs::ChannelAnnouncement, b: crate::ln::msgs::ChannelUpdate, c: crate::ln::msgs::ChannelUpdate) -> C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ {
-       C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZ { a, b, c, }
+pub extern "C" fn CResult_PongDecodeErrorZ_ok(o: crate::ln::msgs::Pong) -> CResult_PongDecodeErrorZ {
+       CResult_PongDecodeErrorZ {
+               contents: CResult_PongDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
 }
-
 #[no_mangle]
-pub type CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ = crate::c_types::CVecTempl<crate::c_types::C3TupleTempl<crate::ln::msgs::ChannelAnnouncement, crate::ln::msgs::ChannelUpdate, crate::ln::msgs::ChannelUpdate>>;
+pub extern "C" fn CResult_PongDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_PongDecodeErrorZ {
+       CResult_PongDecodeErrorZ {
+               contents: CResult_PongDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
 #[no_mangle]
-pub static CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ_free: extern "C" fn(CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ) = crate::c_types::CVecTempl_free::<crate::c_types::C3TupleTempl<crate::ln::msgs::ChannelAnnouncement, crate::ln::msgs::ChannelUpdate, crate::ln::msgs::ChannelUpdate>>;
-
+pub extern "C" fn CResult_PongDecodeErrorZ_free(_res: CResult_PongDecodeErrorZ) { }
+impl Drop for CResult_PongDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::msgs::Pong, crate::ln::msgs::DecodeError>> for CResult_PongDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::msgs::Pong, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_PongDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_PongDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_PongDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_PongDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::msgs::Pong>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_PongDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
 #[no_mangle]
-pub type CVec_NodeAnnouncementZ = crate::c_types::CVecTempl<crate::ln::msgs::NodeAnnouncement>;
+pub extern "C" fn CResult_PongDecodeErrorZ_clone(orig: &CResult_PongDecodeErrorZ) -> CResult_PongDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_UnsignedChannelAnnouncementDecodeErrorZPtr {
+       pub result: *mut crate::ln::msgs::UnsignedChannelAnnouncement,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_UnsignedChannelAnnouncementDecodeErrorZ {
+       pub contents: CResult_UnsignedChannelAnnouncementDecodeErrorZPtr,
+       pub result_ok: bool,
+}
 #[no_mangle]
-pub static CVec_NodeAnnouncementZ_free: extern "C" fn(CVec_NodeAnnouncementZ) = crate::c_types::CVecTempl_free::<crate::ln::msgs::NodeAnnouncement>;
-
+pub extern "C" fn CResult_UnsignedChannelAnnouncementDecodeErrorZ_ok(o: crate::ln::msgs::UnsignedChannelAnnouncement) -> CResult_UnsignedChannelAnnouncementDecodeErrorZ {
+       CResult_UnsignedChannelAnnouncementDecodeErrorZ {
+               contents: CResult_UnsignedChannelAnnouncementDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
 #[no_mangle]
-pub type CVec_PublicKeyZ = crate::c_types::CVecTempl<crate::c_types::PublicKey>;
+pub extern "C" fn CResult_UnsignedChannelAnnouncementDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_UnsignedChannelAnnouncementDecodeErrorZ {
+       CResult_UnsignedChannelAnnouncementDecodeErrorZ {
+               contents: CResult_UnsignedChannelAnnouncementDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
 #[no_mangle]
-pub static CVec_PublicKeyZ_free: extern "C" fn(CVec_PublicKeyZ) = crate::c_types::CVecTempl_free::<crate::c_types::PublicKey>;
-
+pub extern "C" fn CResult_UnsignedChannelAnnouncementDecodeErrorZ_free(_res: CResult_UnsignedChannelAnnouncementDecodeErrorZ) { }
+impl Drop for CResult_UnsignedChannelAnnouncementDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::msgs::UnsignedChannelAnnouncement, crate::ln::msgs::DecodeError>> for CResult_UnsignedChannelAnnouncementDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::msgs::UnsignedChannelAnnouncement, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_UnsignedChannelAnnouncementDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_UnsignedChannelAnnouncementDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_UnsignedChannelAnnouncementDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_UnsignedChannelAnnouncementDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::msgs::UnsignedChannelAnnouncement>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_UnsignedChannelAnnouncementDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
 #[no_mangle]
-pub type CVec_u8Z = crate::c_types::CVecTempl<u8>;
+pub extern "C" fn CResult_UnsignedChannelAnnouncementDecodeErrorZ_clone(orig: &CResult_UnsignedChannelAnnouncementDecodeErrorZ) -> CResult_UnsignedChannelAnnouncementDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_ChannelAnnouncementDecodeErrorZPtr {
+       pub result: *mut crate::ln::msgs::ChannelAnnouncement,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_ChannelAnnouncementDecodeErrorZ {
+       pub contents: CResult_ChannelAnnouncementDecodeErrorZPtr,
+       pub result_ok: bool,
+}
 #[no_mangle]
-pub static CVec_u8Z_free: extern "C" fn(CVec_u8Z) = crate::c_types::CVecTempl_free::<u8>;
-
+pub extern "C" fn CResult_ChannelAnnouncementDecodeErrorZ_ok(o: crate::ln::msgs::ChannelAnnouncement) -> CResult_ChannelAnnouncementDecodeErrorZ {
+       CResult_ChannelAnnouncementDecodeErrorZ {
+               contents: CResult_ChannelAnnouncementDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
 #[no_mangle]
-pub type CResult_CVec_u8ZPeerHandleErrorZ = crate::c_types::CResultTempl<crate::c_types::CVecTempl<u8>, crate::ln::peer_handler::PeerHandleError>;
+pub extern "C" fn CResult_ChannelAnnouncementDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_ChannelAnnouncementDecodeErrorZ {
+       CResult_ChannelAnnouncementDecodeErrorZ {
+               contents: CResult_ChannelAnnouncementDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
 #[no_mangle]
-pub static CResult_CVec_u8ZPeerHandleErrorZ_free: extern "C" fn(CResult_CVec_u8ZPeerHandleErrorZ) = crate::c_types::CResultTempl_free::<crate::c_types::CVecTempl<u8>, crate::ln::peer_handler::PeerHandleError>;
+pub extern "C" fn CResult_ChannelAnnouncementDecodeErrorZ_free(_res: CResult_ChannelAnnouncementDecodeErrorZ) { }
+impl Drop for CResult_ChannelAnnouncementDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::msgs::ChannelAnnouncement, crate::ln::msgs::DecodeError>> for CResult_ChannelAnnouncementDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::msgs::ChannelAnnouncement, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_ChannelAnnouncementDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_ChannelAnnouncementDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_ChannelAnnouncementDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_ChannelAnnouncementDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::msgs::ChannelAnnouncement>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_ChannelAnnouncementDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
 #[no_mangle]
-pub static CResult_CVec_u8ZPeerHandleErrorZ_ok: extern "C" fn (CVec_u8Z) -> CResult_CVec_u8ZPeerHandleErrorZ =
-       crate::c_types::CResultTempl::<crate::c_types::CVecTempl<u8>, crate::ln::peer_handler::PeerHandleError>::ok;
-
+pub extern "C" fn CResult_ChannelAnnouncementDecodeErrorZ_clone(orig: &CResult_ChannelAnnouncementDecodeErrorZ) -> CResult_ChannelAnnouncementDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_UnsignedChannelUpdateDecodeErrorZPtr {
+       pub result: *mut crate::ln::msgs::UnsignedChannelUpdate,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_UnsignedChannelUpdateDecodeErrorZ {
+       pub contents: CResult_UnsignedChannelUpdateDecodeErrorZPtr,
+       pub result_ok: bool,
+}
 #[no_mangle]
-pub static CResult_CVec_u8ZPeerHandleErrorZ_err: extern "C" fn (crate::ln::peer_handler::PeerHandleError) -> CResult_CVec_u8ZPeerHandleErrorZ =
-       crate::c_types::CResultTempl::<crate::c_types::CVecTempl<u8>, crate::ln::peer_handler::PeerHandleError>::err;
-
+pub extern "C" fn CResult_UnsignedChannelUpdateDecodeErrorZ_ok(o: crate::ln::msgs::UnsignedChannelUpdate) -> CResult_UnsignedChannelUpdateDecodeErrorZ {
+       CResult_UnsignedChannelUpdateDecodeErrorZ {
+               contents: CResult_UnsignedChannelUpdateDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
 #[no_mangle]
-pub type CResult_NonePeerHandleErrorZ = crate::c_types::CResultTempl<u8, crate::ln::peer_handler::PeerHandleError>;
+pub extern "C" fn CResult_UnsignedChannelUpdateDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_UnsignedChannelUpdateDecodeErrorZ {
+       CResult_UnsignedChannelUpdateDecodeErrorZ {
+               contents: CResult_UnsignedChannelUpdateDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
 #[no_mangle]
-pub static CResult_NonePeerHandleErrorZ_free: extern "C" fn(CResult_NonePeerHandleErrorZ) = crate::c_types::CResultTempl_free::<u8, crate::ln::peer_handler::PeerHandleError>;
+pub extern "C" fn CResult_UnsignedChannelUpdateDecodeErrorZ_free(_res: CResult_UnsignedChannelUpdateDecodeErrorZ) { }
+impl Drop for CResult_UnsignedChannelUpdateDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::msgs::UnsignedChannelUpdate, crate::ln::msgs::DecodeError>> for CResult_UnsignedChannelUpdateDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::msgs::UnsignedChannelUpdate, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_UnsignedChannelUpdateDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_UnsignedChannelUpdateDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_UnsignedChannelUpdateDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_UnsignedChannelUpdateDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::msgs::UnsignedChannelUpdate>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_UnsignedChannelUpdateDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
 #[no_mangle]
-pub extern "C" fn CResult_NonePeerHandleErrorZ_ok() -> CResult_NonePeerHandleErrorZ {
-       crate::c_types::CResultTempl::ok(0)
+pub extern "C" fn CResult_UnsignedChannelUpdateDecodeErrorZ_clone(orig: &CResult_UnsignedChannelUpdateDecodeErrorZ) -> CResult_UnsignedChannelUpdateDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_ChannelUpdateDecodeErrorZPtr {
+       pub result: *mut crate::ln::msgs::ChannelUpdate,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_ChannelUpdateDecodeErrorZ {
+       pub contents: CResult_ChannelUpdateDecodeErrorZPtr,
+       pub result_ok: bool,
 }
-
 #[no_mangle]
-pub static CResult_NonePeerHandleErrorZ_err: extern "C" fn (crate::ln::peer_handler::PeerHandleError) -> CResult_NonePeerHandleErrorZ =
-       crate::c_types::CResultTempl::<u8, crate::ln::peer_handler::PeerHandleError>::err;
-
+pub extern "C" fn CResult_ChannelUpdateDecodeErrorZ_ok(o: crate::ln::msgs::ChannelUpdate) -> CResult_ChannelUpdateDecodeErrorZ {
+       CResult_ChannelUpdateDecodeErrorZ {
+               contents: CResult_ChannelUpdateDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
 #[no_mangle]
-pub type CResult_boolPeerHandleErrorZ = crate::c_types::CResultTempl<bool, crate::ln::peer_handler::PeerHandleError>;
+pub extern "C" fn CResult_ChannelUpdateDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_ChannelUpdateDecodeErrorZ {
+       CResult_ChannelUpdateDecodeErrorZ {
+               contents: CResult_ChannelUpdateDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
 #[no_mangle]
-pub static CResult_boolPeerHandleErrorZ_free: extern "C" fn(CResult_boolPeerHandleErrorZ) = crate::c_types::CResultTempl_free::<bool, crate::ln::peer_handler::PeerHandleError>;
+pub extern "C" fn CResult_ChannelUpdateDecodeErrorZ_free(_res: CResult_ChannelUpdateDecodeErrorZ) { }
+impl Drop for CResult_ChannelUpdateDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::msgs::ChannelUpdate, crate::ln::msgs::DecodeError>> for CResult_ChannelUpdateDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::msgs::ChannelUpdate, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_ChannelUpdateDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_ChannelUpdateDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_ChannelUpdateDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_ChannelUpdateDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::msgs::ChannelUpdate>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_ChannelUpdateDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
 #[no_mangle]
-pub static CResult_boolPeerHandleErrorZ_ok: extern "C" fn (bool) -> CResult_boolPeerHandleErrorZ =
-       crate::c_types::CResultTempl::<bool, crate::ln::peer_handler::PeerHandleError>::ok;
-
+pub extern "C" fn CResult_ChannelUpdateDecodeErrorZ_clone(orig: &CResult_ChannelUpdateDecodeErrorZ) -> CResult_ChannelUpdateDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_ErrorMessageDecodeErrorZPtr {
+       pub result: *mut crate::ln::msgs::ErrorMessage,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_ErrorMessageDecodeErrorZ {
+       pub contents: CResult_ErrorMessageDecodeErrorZPtr,
+       pub result_ok: bool,
+}
 #[no_mangle]
-pub static CResult_boolPeerHandleErrorZ_err: extern "C" fn (crate::ln::peer_handler::PeerHandleError) -> CResult_boolPeerHandleErrorZ =
-       crate::c_types::CResultTempl::<bool, crate::ln::peer_handler::PeerHandleError>::err;
-
+pub extern "C" fn CResult_ErrorMessageDecodeErrorZ_ok(o: crate::ln::msgs::ErrorMessage) -> CResult_ErrorMessageDecodeErrorZ {
+       CResult_ErrorMessageDecodeErrorZ {
+               contents: CResult_ErrorMessageDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
 #[no_mangle]
-pub type CResult_SecretKeySecpErrorZ = crate::c_types::CResultTempl<crate::c_types::SecretKey, crate::c_types::Secp256k1Error>;
+pub extern "C" fn CResult_ErrorMessageDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_ErrorMessageDecodeErrorZ {
+       CResult_ErrorMessageDecodeErrorZ {
+               contents: CResult_ErrorMessageDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
 #[no_mangle]
-pub static CResult_SecretKeySecpErrorZ_free: extern "C" fn(CResult_SecretKeySecpErrorZ) = crate::c_types::CResultTempl_free::<crate::c_types::SecretKey, crate::c_types::Secp256k1Error>;
+pub extern "C" fn CResult_ErrorMessageDecodeErrorZ_free(_res: CResult_ErrorMessageDecodeErrorZ) { }
+impl Drop for CResult_ErrorMessageDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::msgs::ErrorMessage, crate::ln::msgs::DecodeError>> for CResult_ErrorMessageDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::msgs::ErrorMessage, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_ErrorMessageDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_ErrorMessageDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_ErrorMessageDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_ErrorMessageDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::msgs::ErrorMessage>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_ErrorMessageDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
 #[no_mangle]
-pub static CResult_SecretKeySecpErrorZ_ok: extern "C" fn (crate::c_types::SecretKey) -> CResult_SecretKeySecpErrorZ =
-       crate::c_types::CResultTempl::<crate::c_types::SecretKey, crate::c_types::Secp256k1Error>::ok;
-
+pub extern "C" fn CResult_ErrorMessageDecodeErrorZ_clone(orig: &CResult_ErrorMessageDecodeErrorZ) -> CResult_ErrorMessageDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_UnsignedNodeAnnouncementDecodeErrorZPtr {
+       pub result: *mut crate::ln::msgs::UnsignedNodeAnnouncement,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_UnsignedNodeAnnouncementDecodeErrorZ {
+       pub contents: CResult_UnsignedNodeAnnouncementDecodeErrorZPtr,
+       pub result_ok: bool,
+}
 #[no_mangle]
-pub static CResult_SecretKeySecpErrorZ_err: extern "C" fn (crate::c_types::Secp256k1Error) -> CResult_SecretKeySecpErrorZ =
-       crate::c_types::CResultTempl::<crate::c_types::SecretKey, crate::c_types::Secp256k1Error>::err;
-
+pub extern "C" fn CResult_UnsignedNodeAnnouncementDecodeErrorZ_ok(o: crate::ln::msgs::UnsignedNodeAnnouncement) -> CResult_UnsignedNodeAnnouncementDecodeErrorZ {
+       CResult_UnsignedNodeAnnouncementDecodeErrorZ {
+               contents: CResult_UnsignedNodeAnnouncementDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
 #[no_mangle]
-pub type CResult_PublicKeySecpErrorZ = crate::c_types::CResultTempl<crate::c_types::PublicKey, crate::c_types::Secp256k1Error>;
+pub extern "C" fn CResult_UnsignedNodeAnnouncementDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_UnsignedNodeAnnouncementDecodeErrorZ {
+       CResult_UnsignedNodeAnnouncementDecodeErrorZ {
+               contents: CResult_UnsignedNodeAnnouncementDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
 #[no_mangle]
-pub static CResult_PublicKeySecpErrorZ_free: extern "C" fn(CResult_PublicKeySecpErrorZ) = crate::c_types::CResultTempl_free::<crate::c_types::PublicKey, crate::c_types::Secp256k1Error>;
+pub extern "C" fn CResult_UnsignedNodeAnnouncementDecodeErrorZ_free(_res: CResult_UnsignedNodeAnnouncementDecodeErrorZ) { }
+impl Drop for CResult_UnsignedNodeAnnouncementDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::msgs::UnsignedNodeAnnouncement, crate::ln::msgs::DecodeError>> for CResult_UnsignedNodeAnnouncementDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::msgs::UnsignedNodeAnnouncement, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_UnsignedNodeAnnouncementDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_UnsignedNodeAnnouncementDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_UnsignedNodeAnnouncementDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_UnsignedNodeAnnouncementDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::msgs::UnsignedNodeAnnouncement>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_UnsignedNodeAnnouncementDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
 #[no_mangle]
-pub static CResult_PublicKeySecpErrorZ_ok: extern "C" fn (crate::c_types::PublicKey) -> CResult_PublicKeySecpErrorZ =
-       crate::c_types::CResultTempl::<crate::c_types::PublicKey, crate::c_types::Secp256k1Error>::ok;
-
+pub extern "C" fn CResult_UnsignedNodeAnnouncementDecodeErrorZ_clone(orig: &CResult_UnsignedNodeAnnouncementDecodeErrorZ) -> CResult_UnsignedNodeAnnouncementDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_NodeAnnouncementDecodeErrorZPtr {
+       pub result: *mut crate::ln::msgs::NodeAnnouncement,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_NodeAnnouncementDecodeErrorZ {
+       pub contents: CResult_NodeAnnouncementDecodeErrorZPtr,
+       pub result_ok: bool,
+}
 #[no_mangle]
-pub static CResult_PublicKeySecpErrorZ_err: extern "C" fn (crate::c_types::Secp256k1Error) -> CResult_PublicKeySecpErrorZ =
-       crate::c_types::CResultTempl::<crate::c_types::PublicKey, crate::c_types::Secp256k1Error>::err;
-
+pub extern "C" fn CResult_NodeAnnouncementDecodeErrorZ_ok(o: crate::ln::msgs::NodeAnnouncement) -> CResult_NodeAnnouncementDecodeErrorZ {
+       CResult_NodeAnnouncementDecodeErrorZ {
+               contents: CResult_NodeAnnouncementDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
 #[no_mangle]
-pub type CResult_TxCreationKeysSecpErrorZ = crate::c_types::CResultTempl<crate::ln::chan_utils::TxCreationKeys, crate::c_types::Secp256k1Error>;
+pub extern "C" fn CResult_NodeAnnouncementDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_NodeAnnouncementDecodeErrorZ {
+       CResult_NodeAnnouncementDecodeErrorZ {
+               contents: CResult_NodeAnnouncementDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
 #[no_mangle]
-pub static CResult_TxCreationKeysSecpErrorZ_free: extern "C" fn(CResult_TxCreationKeysSecpErrorZ) = crate::c_types::CResultTempl_free::<crate::ln::chan_utils::TxCreationKeys, crate::c_types::Secp256k1Error>;
+pub extern "C" fn CResult_NodeAnnouncementDecodeErrorZ_free(_res: CResult_NodeAnnouncementDecodeErrorZ) { }
+impl Drop for CResult_NodeAnnouncementDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::msgs::NodeAnnouncement, crate::ln::msgs::DecodeError>> for CResult_NodeAnnouncementDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::msgs::NodeAnnouncement, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_NodeAnnouncementDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_NodeAnnouncementDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_NodeAnnouncementDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_NodeAnnouncementDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::msgs::NodeAnnouncement>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_NodeAnnouncementDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
 #[no_mangle]
-pub static CResult_TxCreationKeysSecpErrorZ_ok: extern "C" fn (crate::ln::chan_utils::TxCreationKeys) -> CResult_TxCreationKeysSecpErrorZ =
-       crate::c_types::CResultTempl::<crate::ln::chan_utils::TxCreationKeys, crate::c_types::Secp256k1Error>::ok;
-
+pub extern "C" fn CResult_NodeAnnouncementDecodeErrorZ_clone(orig: &CResult_NodeAnnouncementDecodeErrorZ) -> CResult_NodeAnnouncementDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_QueryShortChannelIdsDecodeErrorZPtr {
+       pub result: *mut crate::ln::msgs::QueryShortChannelIds,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_QueryShortChannelIdsDecodeErrorZ {
+       pub contents: CResult_QueryShortChannelIdsDecodeErrorZPtr,
+       pub result_ok: bool,
+}
 #[no_mangle]
-pub static CResult_TxCreationKeysSecpErrorZ_err: extern "C" fn (crate::c_types::Secp256k1Error) -> CResult_TxCreationKeysSecpErrorZ =
-       crate::c_types::CResultTempl::<crate::ln::chan_utils::TxCreationKeys, crate::c_types::Secp256k1Error>::err;
-
+pub extern "C" fn CResult_QueryShortChannelIdsDecodeErrorZ_ok(o: crate::ln::msgs::QueryShortChannelIds) -> CResult_QueryShortChannelIdsDecodeErrorZ {
+       CResult_QueryShortChannelIdsDecodeErrorZ {
+               contents: CResult_QueryShortChannelIdsDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
 #[no_mangle]
-pub type C2Tuple_HTLCOutputInCommitmentSignatureZ = crate::c_types::C2TupleTempl<crate::ln::chan_utils::HTLCOutputInCommitment, crate::c_types::Signature>;
+pub extern "C" fn CResult_QueryShortChannelIdsDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_QueryShortChannelIdsDecodeErrorZ {
+       CResult_QueryShortChannelIdsDecodeErrorZ {
+               contents: CResult_QueryShortChannelIdsDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
 #[no_mangle]
-pub static C2Tuple_HTLCOutputInCommitmentSignatureZ_free: extern "C" fn(C2Tuple_HTLCOutputInCommitmentSignatureZ) = crate::c_types::C2TupleTempl_free::<crate::ln::chan_utils::HTLCOutputInCommitment, crate::c_types::Signature>;
+pub extern "C" fn CResult_QueryShortChannelIdsDecodeErrorZ_free(_res: CResult_QueryShortChannelIdsDecodeErrorZ) { }
+impl Drop for CResult_QueryShortChannelIdsDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::msgs::QueryShortChannelIds, crate::ln::msgs::DecodeError>> for CResult_QueryShortChannelIdsDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::msgs::QueryShortChannelIds, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_QueryShortChannelIdsDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_QueryShortChannelIdsDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_QueryShortChannelIdsDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_QueryShortChannelIdsDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::msgs::QueryShortChannelIds>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_QueryShortChannelIdsDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
 #[no_mangle]
-pub extern "C" fn C2Tuple_HTLCOutputInCommitmentSignatureZ_new(a: crate::ln::chan_utils::HTLCOutputInCommitment, b: crate::c_types::Signature) -> C2Tuple_HTLCOutputInCommitmentSignatureZ {
-       C2Tuple_HTLCOutputInCommitmentSignatureZ { a, b, }
+pub extern "C" fn CResult_QueryShortChannelIdsDecodeErrorZ_clone(orig: &CResult_QueryShortChannelIdsDecodeErrorZ) -> CResult_QueryShortChannelIdsDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_ReplyShortChannelIdsEndDecodeErrorZPtr {
+       pub result: *mut crate::ln::msgs::ReplyShortChannelIdsEnd,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_ReplyShortChannelIdsEndDecodeErrorZ {
+       pub contents: CResult_ReplyShortChannelIdsEndDecodeErrorZPtr,
+       pub result_ok: bool,
 }
-
 #[no_mangle]
-pub type CVec_C2Tuple_HTLCOutputInCommitmentSignatureZZ = crate::c_types::CVecTempl<crate::c_types::C2TupleTempl<crate::ln::chan_utils::HTLCOutputInCommitment, crate::c_types::Signature>>;
+pub extern "C" fn CResult_ReplyShortChannelIdsEndDecodeErrorZ_ok(o: crate::ln::msgs::ReplyShortChannelIdsEnd) -> CResult_ReplyShortChannelIdsEndDecodeErrorZ {
+       CResult_ReplyShortChannelIdsEndDecodeErrorZ {
+               contents: CResult_ReplyShortChannelIdsEndDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
 #[no_mangle]
-pub static CVec_C2Tuple_HTLCOutputInCommitmentSignatureZZ_free: extern "C" fn(CVec_C2Tuple_HTLCOutputInCommitmentSignatureZZ) = crate::c_types::CVecTempl_free::<crate::c_types::C2TupleTempl<crate::ln::chan_utils::HTLCOutputInCommitment, crate::c_types::Signature>>;
-
+pub extern "C" fn CResult_ReplyShortChannelIdsEndDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_ReplyShortChannelIdsEndDecodeErrorZ {
+       CResult_ReplyShortChannelIdsEndDecodeErrorZ {
+               contents: CResult_ReplyShortChannelIdsEndDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
 #[no_mangle]
-pub type CVec_RouteHopZ = crate::c_types::CVecTempl<crate::routing::router::RouteHop>;
+pub extern "C" fn CResult_ReplyShortChannelIdsEndDecodeErrorZ_free(_res: CResult_ReplyShortChannelIdsEndDecodeErrorZ) { }
+impl Drop for CResult_ReplyShortChannelIdsEndDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::msgs::ReplyShortChannelIdsEnd, crate::ln::msgs::DecodeError>> for CResult_ReplyShortChannelIdsEndDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::msgs::ReplyShortChannelIdsEnd, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_ReplyShortChannelIdsEndDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_ReplyShortChannelIdsEndDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_ReplyShortChannelIdsEndDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_ReplyShortChannelIdsEndDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::msgs::ReplyShortChannelIdsEnd>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_ReplyShortChannelIdsEndDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
 #[no_mangle]
-pub static CVec_RouteHopZ_free: extern "C" fn(CVec_RouteHopZ) = crate::c_types::CVecTempl_free::<crate::routing::router::RouteHop>;
-
+pub extern "C" fn CResult_ReplyShortChannelIdsEndDecodeErrorZ_clone(orig: &CResult_ReplyShortChannelIdsEndDecodeErrorZ) -> CResult_ReplyShortChannelIdsEndDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_QueryChannelRangeDecodeErrorZPtr {
+       pub result: *mut crate::ln::msgs::QueryChannelRange,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_QueryChannelRangeDecodeErrorZ {
+       pub contents: CResult_QueryChannelRangeDecodeErrorZPtr,
+       pub result_ok: bool,
+}
 #[no_mangle]
-pub type CVec_CVec_RouteHopZZ = crate::c_types::CVecTempl<crate::c_types::CVecTempl<crate::routing::router::RouteHop>>;
+pub extern "C" fn CResult_QueryChannelRangeDecodeErrorZ_ok(o: crate::ln::msgs::QueryChannelRange) -> CResult_QueryChannelRangeDecodeErrorZ {
+       CResult_QueryChannelRangeDecodeErrorZ {
+               contents: CResult_QueryChannelRangeDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
 #[no_mangle]
-pub static CVec_CVec_RouteHopZZ_free: extern "C" fn(CVec_CVec_RouteHopZZ) = crate::c_types::CVecTempl_free::<crate::c_types::CVecTempl<crate::routing::router::RouteHop>>;
-
+pub extern "C" fn CResult_QueryChannelRangeDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_QueryChannelRangeDecodeErrorZ {
+       CResult_QueryChannelRangeDecodeErrorZ {
+               contents: CResult_QueryChannelRangeDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
 #[no_mangle]
-pub type CVec_RouteHintZ = crate::c_types::CVecTempl<crate::routing::router::RouteHint>;
+pub extern "C" fn CResult_QueryChannelRangeDecodeErrorZ_free(_res: CResult_QueryChannelRangeDecodeErrorZ) { }
+impl Drop for CResult_QueryChannelRangeDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::msgs::QueryChannelRange, crate::ln::msgs::DecodeError>> for CResult_QueryChannelRangeDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::msgs::QueryChannelRange, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_QueryChannelRangeDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_QueryChannelRangeDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_QueryChannelRangeDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_QueryChannelRangeDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::msgs::QueryChannelRange>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_QueryChannelRangeDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
 #[no_mangle]
-pub static CVec_RouteHintZ_free: extern "C" fn(CVec_RouteHintZ) = crate::c_types::CVecTempl_free::<crate::routing::router::RouteHint>;
-
+pub extern "C" fn CResult_QueryChannelRangeDecodeErrorZ_clone(orig: &CResult_QueryChannelRangeDecodeErrorZ) -> CResult_QueryChannelRangeDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_ReplyChannelRangeDecodeErrorZPtr {
+       pub result: *mut crate::ln::msgs::ReplyChannelRange,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_ReplyChannelRangeDecodeErrorZ {
+       pub contents: CResult_ReplyChannelRangeDecodeErrorZPtr,
+       pub result_ok: bool,
+}
 #[no_mangle]
-pub type CResult_RouteLightningErrorZ = crate::c_types::CResultTempl<crate::routing::router::Route, crate::ln::msgs::LightningError>;
+pub extern "C" fn CResult_ReplyChannelRangeDecodeErrorZ_ok(o: crate::ln::msgs::ReplyChannelRange) -> CResult_ReplyChannelRangeDecodeErrorZ {
+       CResult_ReplyChannelRangeDecodeErrorZ {
+               contents: CResult_ReplyChannelRangeDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
 #[no_mangle]
-pub static CResult_RouteLightningErrorZ_free: extern "C" fn(CResult_RouteLightningErrorZ) = crate::c_types::CResultTempl_free::<crate::routing::router::Route, crate::ln::msgs::LightningError>;
+pub extern "C" fn CResult_ReplyChannelRangeDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_ReplyChannelRangeDecodeErrorZ {
+       CResult_ReplyChannelRangeDecodeErrorZ {
+               contents: CResult_ReplyChannelRangeDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
 #[no_mangle]
-pub static CResult_RouteLightningErrorZ_ok: extern "C" fn (crate::routing::router::Route) -> CResult_RouteLightningErrorZ =
-       crate::c_types::CResultTempl::<crate::routing::router::Route, crate::ln::msgs::LightningError>::ok;
-
+pub extern "C" fn CResult_ReplyChannelRangeDecodeErrorZ_free(_res: CResult_ReplyChannelRangeDecodeErrorZ) { }
+impl Drop for CResult_ReplyChannelRangeDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::msgs::ReplyChannelRange, crate::ln::msgs::DecodeError>> for CResult_ReplyChannelRangeDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::msgs::ReplyChannelRange, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_ReplyChannelRangeDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_ReplyChannelRangeDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_ReplyChannelRangeDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_ReplyChannelRangeDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::msgs::ReplyChannelRange>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_ReplyChannelRangeDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
+}
 #[no_mangle]
-pub static CResult_RouteLightningErrorZ_err: extern "C" fn (crate::ln::msgs::LightningError) -> CResult_RouteLightningErrorZ =
-       crate::c_types::CResultTempl::<crate::routing::router::Route, crate::ln::msgs::LightningError>::err;
-
+pub extern "C" fn CResult_ReplyChannelRangeDecodeErrorZ_clone(orig: &CResult_ReplyChannelRangeDecodeErrorZ) -> CResult_ReplyChannelRangeDecodeErrorZ { orig.clone() }
+#[repr(C)]
+pub union CResult_GossipTimestampFilterDecodeErrorZPtr {
+       pub result: *mut crate::ln::msgs::GossipTimestampFilter,
+       pub err: *mut crate::ln::msgs::DecodeError,
+}
+#[repr(C)]
+pub struct CResult_GossipTimestampFilterDecodeErrorZ {
+       pub contents: CResult_GossipTimestampFilterDecodeErrorZPtr,
+       pub result_ok: bool,
+}
 #[no_mangle]
-pub type CResult_NoneLightningErrorZ = crate::c_types::CResultTempl<u8, crate::ln::msgs::LightningError>;
+pub extern "C" fn CResult_GossipTimestampFilterDecodeErrorZ_ok(o: crate::ln::msgs::GossipTimestampFilter) -> CResult_GossipTimestampFilterDecodeErrorZ {
+       CResult_GossipTimestampFilterDecodeErrorZ {
+               contents: CResult_GossipTimestampFilterDecodeErrorZPtr {
+                       result: Box::into_raw(Box::new(o)),
+               },
+               result_ok: true,
+       }
+}
 #[no_mangle]
-pub static CResult_NoneLightningErrorZ_free: extern "C" fn(CResult_NoneLightningErrorZ) = crate::c_types::CResultTempl_free::<u8, crate::ln::msgs::LightningError>;
+pub extern "C" fn CResult_GossipTimestampFilterDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_GossipTimestampFilterDecodeErrorZ {
+       CResult_GossipTimestampFilterDecodeErrorZ {
+               contents: CResult_GossipTimestampFilterDecodeErrorZPtr {
+                       err: Box::into_raw(Box::new(e)),
+               },
+               result_ok: false,
+       }
+}
 #[no_mangle]
-pub extern "C" fn CResult_NoneLightningErrorZ_ok() -> CResult_NoneLightningErrorZ {
-       crate::c_types::CResultTempl::ok(0)
+pub extern "C" fn CResult_GossipTimestampFilterDecodeErrorZ_free(_res: CResult_GossipTimestampFilterDecodeErrorZ) { }
+impl Drop for CResult_GossipTimestampFilterDecodeErrorZ {
+       fn drop(&mut self) {
+               if self.result_ok {
+                       if unsafe { !(self.contents.result as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.result) };
+                       }
+               } else {
+                       if unsafe { !(self.contents.err as *mut ()).is_null() } {
+                               let _ = unsafe { Box::from_raw(self.contents.err) };
+                       }
+               }
+       }
+}
+impl From<crate::c_types::CResultTempl<crate::ln::msgs::GossipTimestampFilter, crate::ln::msgs::DecodeError>> for CResult_GossipTimestampFilterDecodeErrorZ {
+       fn from(mut o: crate::c_types::CResultTempl<crate::ln::msgs::GossipTimestampFilter, crate::ln::msgs::DecodeError>) -> Self {
+               let contents = if o.result_ok {
+                       let result = unsafe { o.contents.result };
+                       unsafe { o.contents.result = std::ptr::null_mut() };
+                       CResult_GossipTimestampFilterDecodeErrorZPtr { result }
+               } else {
+                       let err = unsafe { o.contents.err };
+                       unsafe { o.contents.err = std::ptr::null_mut(); }
+                       CResult_GossipTimestampFilterDecodeErrorZPtr { err }
+               };
+               Self {
+                       contents,
+                       result_ok: o.result_ok,
+               }
+       }
+}
+impl Clone for CResult_GossipTimestampFilterDecodeErrorZ {
+       fn clone(&self) -> Self {
+               if self.result_ok {
+                       Self { result_ok: true, contents: CResult_GossipTimestampFilterDecodeErrorZPtr {
+                               result: Box::into_raw(Box::new(<crate::ln::msgs::GossipTimestampFilter>::clone(unsafe { &*self.contents.result })))
+                       } }
+               } else {
+                       Self { result_ok: false, contents: CResult_GossipTimestampFilterDecodeErrorZPtr {
+                               err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
+                       } }
+               }
+       }
 }
-
 #[no_mangle]
-pub static CResult_NoneLightningErrorZ_err: extern "C" fn (crate::ln::msgs::LightningError) -> CResult_NoneLightningErrorZ =
-       crate::c_types::CResultTempl::<u8, crate::ln::msgs::LightningError>::err;
-
+pub extern "C" fn CResult_GossipTimestampFilterDecodeErrorZ_clone(orig: &CResult_GossipTimestampFilterDecodeErrorZ) -> CResult_GossipTimestampFilterDecodeErrorZ { orig.clone() }
index 1919277902306bfcf98b36b0661189b0538ec921..0a96f3e7d6789d0ad0be381022db26bb78b727ed 100644 (file)
@@ -2,11 +2,14 @@ pub mod derived;
 
 use bitcoin::Script as BitcoinScript;
 use bitcoin::Transaction as BitcoinTransaction;
+use bitcoin::hashes::Hash;
 use bitcoin::secp256k1::key::PublicKey as SecpPublicKey;
 use bitcoin::secp256k1::key::SecretKey as SecpSecretKey;
 use bitcoin::secp256k1::Signature as SecpSignature;
 use bitcoin::secp256k1::Error as SecpError;
 
+use std::convert::TryInto; // Bindings need at least rustc 1.34
+
 #[derive(Clone)]
 #[repr(C)]
 pub struct PublicKey {
@@ -42,6 +45,7 @@ impl SecretKey {
 }
 
 #[repr(C)]
+#[derive(Clone)]
 pub struct Signature {
        pub compact_form: [u8; 64],
 }
@@ -54,8 +58,9 @@ impl Signature {
        pub(crate) fn into_rust(&self) -> SecpSignature {
                SecpSignature::from_compact(&self.compact_form).unwrap()
        }
-       pub(crate) fn is_null(&self) -> bool { self.compact_form[..] == [0; 64][..] }
-       pub(crate) fn null() -> Self { Self { compact_form: [0; 64] } }
+       // The following are used for Option<Signature> which we support, but don't use anymore
+       #[allow(unused)] pub(crate) fn is_null(&self) -> bool { self.compact_form[..] == [0; 64][..] }
+       #[allow(unused)] pub(crate) fn null() -> Self { Self { compact_form: [0; 64] } }
 }
 
 #[repr(C)]
@@ -67,8 +72,8 @@ pub enum Secp256k1Error {
        InvalidSecretKey,
        InvalidRecoveryId,
        InvalidTweak,
+       TweakCheckFailed,
        NotEnoughMemory,
-       CallbackPanicked,
 }
 impl Secp256k1Error {
        pub(crate) fn from_rust(err: SecpError) -> Self {
@@ -80,6 +85,7 @@ impl Secp256k1Error {
                        SecpError::InvalidSecretKey => Secp256k1Error::InvalidSecretKey,
                        SecpError::InvalidRecoveryId => Secp256k1Error::InvalidRecoveryId,
                        SecpError::InvalidTweak => Secp256k1Error::InvalidTweak,
+                       SecpError::TweakCheckFailed => Secp256k1Error::TweakCheckFailed,
                        SecpError::NotEnoughMemory => Secp256k1Error::NotEnoughMemory,
                }
        }
@@ -123,13 +129,17 @@ impl Transaction {
 impl Drop for Transaction {
        fn drop(&mut self) {
                if self.data_is_owned && self.datalen != 0 {
-                       let _ = CVecTempl { data: self.data as *mut u8, datalen: self.datalen };
+                       let _ = derived::CVec_u8Z { data: self.data as *mut u8, datalen: self.datalen };
                }
        }
 }
 #[no_mangle]
 pub extern "C" fn Transaction_free(_res: Transaction) { }
 
+pub(crate) fn bitcoin_to_C_outpoint(outpoint: ::bitcoin::blockdata::transaction::OutPoint) -> crate::chain::transaction::OutPoint {
+       crate::chain::transaction::OutPoint_new(ThirtyTwoBytes { data: outpoint.txid.into_inner() }, outpoint.vout.try_into().unwrap())
+}
+
 #[repr(C)]
 #[derive(Clone)]
 /// A transaction output including a scriptPubKey and value.
@@ -148,13 +158,15 @@ impl TxOut {
        }
        pub(crate) fn from_rust(txout: ::bitcoin::blockdata::transaction::TxOut) -> Self {
                Self {
-                       script_pubkey: CVecTempl::from(txout.script_pubkey.into_bytes()),
+                       script_pubkey: derived::CVec_u8Z::from(txout.script_pubkey.into_bytes()),
                        value: txout.value
                }
        }
 }
 #[no_mangle]
 pub extern "C" fn TxOut_free(_res: TxOut) { }
+#[no_mangle]
+pub extern "C" fn TxOut_clone(orig: &TxOut) -> TxOut { orig.clone() }
 
 #[repr(C)]
 pub struct u8slice {
@@ -212,11 +224,14 @@ impl lightning::util::ser::Writer for VecWriter {
 pub(crate) fn serialize_obj<I: lightning::util::ser::Writeable>(i: &I) -> derived::CVec_u8Z {
        let mut out = VecWriter(Vec::new());
        i.write(&mut out).unwrap();
-       CVecTempl::from(out.0)
+       derived::CVec_u8Z::from(out.0)
 }
 pub(crate) fn deserialize_obj<I: lightning::util::ser::Readable>(s: u8slice) -> Result<I, lightning::ln::msgs::DecodeError> {
        I::read(&mut s.to_slice())
 }
+pub(crate) fn deserialize_obj_arg<A, I: lightning::util::ser::ReadableArgs<A>>(s: u8slice, args: A) -> Result<I, lightning::ln::msgs::DecodeError> {
+       I::read(&mut s.to_slice(), args)
+}
 
 #[repr(C)]
 #[derive(Copy, Clone)]
@@ -245,14 +260,14 @@ impl Into<&'static str> for Str {
 // everywhere in the containers.
 
 #[repr(C)]
-pub union CResultPtr<O, E> {
-       pub result: *mut O,
-       pub err: *mut E,
+pub(crate) union CResultPtr<O, E> {
+       pub(crate) result: *mut O,
+       pub(crate) err: *mut E,
 }
 #[repr(C)]
-pub struct CResultTempl<O, E> {
-       pub contents: CResultPtr<O, E>,
-       pub result_ok: bool,
+pub(crate) struct CResultTempl<O, E> {
+       pub(crate) contents: CResultPtr<O, E>,
+       pub(crate) result_ok: bool,
 }
 impl<O, E> CResultTempl<O, E> {
        pub(crate) extern "C" fn ok(o: O) -> Self {
@@ -272,7 +287,6 @@ impl<O, E> CResultTempl<O, E> {
                }
        }
 }
-pub extern "C" fn CResultTempl_free<O, E>(_res: CResultTempl<O, E>) { }
 impl<O, E> Drop for CResultTempl<O, E> {
        fn drop(&mut self) {
                if self.result_ok {
@@ -285,96 +299,6 @@ impl<O, E> Drop for CResultTempl<O, E> {
        }
 }
 
-#[repr(C)]
-pub struct CVecTempl<T> {
-       pub data: *mut T,
-       pub datalen: usize
-}
-impl<T> CVecTempl<T> {
-       pub(crate) fn into_rust(&mut self) -> Vec<T> {
-               if self.datalen == 0 { return Vec::new(); }
-               let ret = unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }.into();
-               self.data = std::ptr::null_mut();
-               self.datalen = 0;
-               ret
-       }
-       pub(crate) fn as_slice(&self) -> &[T] {
-               unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) }
-       }
-}
-impl<T> From<Vec<T>> for CVecTempl<T> {
-       fn from(v: Vec<T>) -> Self {
-               let datalen = v.len();
-               let data = Box::into_raw(v.into_boxed_slice());
-               CVecTempl { datalen, data: unsafe { (*data).as_mut_ptr() } }
-       }
-}
-pub extern "C" fn CVecTempl_free<T>(_res: CVecTempl<T>) { }
-impl<T> Drop for CVecTempl<T> {
-       fn drop(&mut self) {
-               if self.datalen == 0 { return; }
-               unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) };
-       }
-}
-impl<T: Clone> Clone for CVecTempl<T> {
-       fn clone(&self) -> Self {
-               let mut res = Vec::new();
-               if self.datalen == 0 { return Self::from(res); }
-               res.extend_from_slice(unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) });
-               Self::from(res)
-       }
-}
-
-#[repr(C)]
-pub struct C2TupleTempl<A, B> {
-       pub a: A,
-       pub b: B,
-}
-impl<A, B> From<(A, B)> for C2TupleTempl<A, B> {
-       fn from(tup: (A, B)) -> Self {
-               Self {
-                       a: tup.0,
-                       b: tup.1,
-               }
-       }
-}
-impl<A, B> C2TupleTempl<A, B> {
-       pub(crate) fn to_rust(mut self) -> (A, B) {
-               (self.a, self.b)
-       }
-}
-pub extern "C" fn C2TupleTempl_free<A, B>(_res: C2TupleTempl<A, B>) { }
-impl <A: Clone, B: Clone> Clone for C2TupleTempl<A, B> {
-       fn clone(&self) -> Self {
-               Self {
-                       a: self.a.clone(),
-                       b: self.b.clone()
-               }
-       }
-}
-
-#[repr(C)]
-pub struct C3TupleTempl<A, B, C> {
-       pub a: A,
-       pub b: B,
-       pub c: C,
-}
-impl<A, B, C> From<(A, B, C)> for C3TupleTempl<A, B, C> {
-       fn from(tup: (A, B, C)) -> Self {
-               Self {
-                       a: tup.0,
-                       b: tup.1,
-                       c: tup.2,
-               }
-       }
-}
-impl<A, B, C> C3TupleTempl<A, B, C> {
-       pub(crate) fn to_rust(mut self) -> (A, B, C) {
-               (self.a, self.b, self.c)
-       }
-}
-pub extern "C" fn C3TupleTempl_free<A, B, C>(_res: C3TupleTempl<A, B, C>) { }
-
 /// Utility to make it easy to set a pointer to null and get its original value in line.
 pub(crate) trait TakePointer<T> {
        fn take_ptr(&mut self) -> T;
index 35eb1bed22d1e442c7bfbbc9991156e0cd72cc84..de47fcb572f2ea177fe841abec29fd520fbf361c 100644 (file)
@@ -26,7 +26,7 @@ use crate::c_types::*;
 
 
 use lightning::chain::chainmonitor::ChainMonitor as nativeChainMonitorImport;
-type nativeChainMonitor = nativeChainMonitorImport<crate::chain::keysinterface::ChannelKeys, crate::chain::Filter, crate::chain::chaininterface::BroadcasterInterface, crate::chain::chaininterface::FeeEstimator, crate::util::logger::Logger, crate::chain::channelmonitor::Persist>;
+type nativeChainMonitor = nativeChainMonitorImport<crate::chain::keysinterface::Sign, crate::chain::Filter, crate::chain::chaininterface::BroadcasterInterface, crate::chain::chaininterface::FeeEstimator, crate::util::logger::Logger, crate::chain::channelmonitor::Persist>;
 
 /// An implementation of [`chain::Watch`] for monitoring channels.
 ///
@@ -64,7 +64,7 @@ extern "C" fn ChainMonitor_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl ChainMonitor {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeChainMonitor {
+       pub(crate) fn take_inner(mut self) -> *mut nativeChainMonitor {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
@@ -117,8 +117,18 @@ pub extern "C" fn ChainMonitor_new(chain_source: *mut crate::chain::Filter, mut
        ChainMonitor { inner: Box::into_raw(Box::new(ret)), is_owned: true }
 }
 
+impl From<nativeChainMonitor> for crate::chain::Watch {
+       fn from(obj: nativeChainMonitor) -> Self {
+               let mut rust_obj = ChainMonitor { inner: Box::into_raw(Box::new(obj)), is_owned: true };
+               let mut ret = ChainMonitor_as_Watch(&rust_obj);
+               // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
+               rust_obj.inner = std::ptr::null_mut();
+               ret.free = Some(ChainMonitor_free_void);
+               ret
+       }
+}
 #[no_mangle]
-pub extern "C" fn ChainMonitor_as_Watch(this_arg: *const ChainMonitor) -> crate::chain::Watch {
+pub extern "C" fn ChainMonitor_as_Watch(this_arg: &ChainMonitor) -> crate::chain::Watch {
        crate::chain::Watch {
                this_arg: unsafe { (*this_arg).inner as *mut c_void },
                free: None,
@@ -130,25 +140,35 @@ pub extern "C" fn ChainMonitor_as_Watch(this_arg: *const ChainMonitor) -> crate:
 use lightning::chain::Watch as WatchTraitImport;
 #[must_use]
 extern "C" fn ChainMonitor_Watch_watch_channel(this_arg: *const c_void, mut funding_outpoint: crate::chain::transaction::OutPoint, mut monitor: crate::chain::channelmonitor::ChannelMonitor) -> crate::c_types::derived::CResult_NoneChannelMonitorUpdateErrZ {
-       let mut ret = unsafe { &mut *(this_arg as *mut nativeChainMonitor) }.watch_channel(*unsafe { Box::from_raw(funding_outpoint.take_ptr()) }, *unsafe { Box::from_raw(monitor.take_ptr()) });
-       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }), Err(mut e) => crate::c_types::CResultTempl::err( { crate::chain::channelmonitor::ChannelMonitorUpdateErr::native_into(e) }) };
+       let mut ret = <nativeChainMonitor as WatchTraitImport<_>>::watch_channel(unsafe { &mut *(this_arg as *mut nativeChainMonitor) }, *unsafe { Box::from_raw(funding_outpoint.take_inner()) }, *unsafe { Box::from_raw(monitor.take_inner()) });
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::chain::channelmonitor::ChannelMonitorUpdateErr::native_into(e) }).into() };
        local_ret
 }
 #[must_use]
 extern "C" fn ChainMonitor_Watch_update_channel(this_arg: *const c_void, mut funding_txo: crate::chain::transaction::OutPoint, mut update: crate::chain::channelmonitor::ChannelMonitorUpdate) -> crate::c_types::derived::CResult_NoneChannelMonitorUpdateErrZ {
-       let mut ret = unsafe { &mut *(this_arg as *mut nativeChainMonitor) }.update_channel(*unsafe { Box::from_raw(funding_txo.take_ptr()) }, *unsafe { Box::from_raw(update.take_ptr()) });
-       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }), Err(mut e) => crate::c_types::CResultTempl::err( { crate::chain::channelmonitor::ChannelMonitorUpdateErr::native_into(e) }) };
+       let mut ret = <nativeChainMonitor as WatchTraitImport<_>>::update_channel(unsafe { &mut *(this_arg as *mut nativeChainMonitor) }, *unsafe { Box::from_raw(funding_txo.take_inner()) }, *unsafe { Box::from_raw(update.take_inner()) });
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::chain::channelmonitor::ChannelMonitorUpdateErr::native_into(e) }).into() };
        local_ret
 }
 #[must_use]
 extern "C" fn ChainMonitor_Watch_release_pending_monitor_events(this_arg: *const c_void) -> crate::c_types::derived::CVec_MonitorEventZ {
-       let mut ret = unsafe { &mut *(this_arg as *mut nativeChainMonitor) }.release_pending_monitor_events();
-       let mut local_ret = Vec::new(); for item in ret.drain(..) { local_ret.push( { crate::chain::channelmonitor::MonitorEvent { inner: Box::into_raw(Box::new(item)), is_owned: true } }); };
+       let mut ret = <nativeChainMonitor as WatchTraitImport<_>>::release_pending_monitor_events(unsafe { &mut *(this_arg as *mut nativeChainMonitor) }, );
+       let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::chain::channelmonitor::MonitorEvent::native_into(item) }); };
        local_ret.into()
 }
 
+impl From<nativeChainMonitor> for crate::util::events::EventsProvider {
+       fn from(obj: nativeChainMonitor) -> Self {
+               let mut rust_obj = ChainMonitor { inner: Box::into_raw(Box::new(obj)), is_owned: true };
+               let mut ret = ChainMonitor_as_EventsProvider(&rust_obj);
+               // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
+               rust_obj.inner = std::ptr::null_mut();
+               ret.free = Some(ChainMonitor_free_void);
+               ret
+       }
+}
 #[no_mangle]
-pub extern "C" fn ChainMonitor_as_EventsProvider(this_arg: *const ChainMonitor) -> crate::util::events::EventsProvider {
+pub extern "C" fn ChainMonitor_as_EventsProvider(this_arg: &ChainMonitor) -> crate::util::events::EventsProvider {
        crate::util::events::EventsProvider {
                this_arg: unsafe { (*this_arg).inner as *mut c_void },
                free: None,
@@ -158,8 +178,8 @@ pub extern "C" fn ChainMonitor_as_EventsProvider(this_arg: *const ChainMonitor)
 use lightning::util::events::EventsProvider as EventsProviderTraitImport;
 #[must_use]
 extern "C" fn ChainMonitor_EventsProvider_get_and_clear_pending_events(this_arg: *const c_void) -> crate::c_types::derived::CVec_EventZ {
-       let mut ret = unsafe { &mut *(this_arg as *mut nativeChainMonitor) }.get_and_clear_pending_events();
-       let mut local_ret = Vec::new(); for item in ret.drain(..) { local_ret.push( { crate::util::events::Event::native_into(item) }); };
+       let mut ret = <nativeChainMonitor as EventsProviderTraitImport<>>::get_and_clear_pending_events(unsafe { &mut *(this_arg as *mut nativeChainMonitor) }, );
+       let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::util::events::Event::native_into(item) }); };
        local_ret.into()
 }
 
index c644670257b2b34bcded75a22f1f3bdc02693ed8..efab4b165d5f46c7e5830d00487daa72c8b79760 100644 (file)
@@ -49,30 +49,13 @@ extern "C" fn ChannelMonitorUpdate_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl ChannelMonitorUpdate {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeChannelMonitorUpdate {
+       pub(crate) fn take_inner(mut self) -> *mut nativeChannelMonitorUpdate {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for ChannelMonitorUpdate {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn ChannelMonitorUpdate_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelMonitorUpdate)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn ChannelMonitorUpdate_clone(orig: &ChannelMonitorUpdate) -> ChannelMonitorUpdate {
-       ChannelMonitorUpdate { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// The sequence number of this update. Updates *must* be replayed in-order according to this
 /// sequence number (and updates may panic if they are not). The update_id values are strictly
 /// increasing and increase by one for each new update, with one exception specified below.
@@ -108,20 +91,40 @@ pub extern "C" fn ChannelMonitorUpdate_get_update_id(this_ptr: &ChannelMonitorUp
 pub extern "C" fn ChannelMonitorUpdate_set_update_id(this_ptr: &mut ChannelMonitorUpdate, mut val: u64) {
        unsafe { &mut *this_ptr.inner }.update_id = val;
 }
+impl Clone for ChannelMonitorUpdate {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn ChannelMonitorUpdate_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelMonitorUpdate)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn ChannelMonitorUpdate_clone(orig: &ChannelMonitorUpdate) -> ChannelMonitorUpdate {
+       orig.clone()
+}
 
 #[no_mangle]
 pub static CLOSED_CHANNEL_UPDATE_ID: u64 = lightning::chain::channelmonitor::CLOSED_CHANNEL_UPDATE_ID;
 #[no_mangle]
-pub extern "C" fn ChannelMonitorUpdate_write(obj: *const ChannelMonitorUpdate) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub extern "C" fn ChannelMonitorUpdate_write(obj: &ChannelMonitorUpdate) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
 }
 #[no_mangle]
-pub extern "C" fn ChannelMonitorUpdate_read(ser: crate::c_types::u8slice) -> ChannelMonitorUpdate {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               ChannelMonitorUpdate { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               ChannelMonitorUpdate { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub(crate) extern "C" fn ChannelMonitorUpdate_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeChannelMonitorUpdate) })
+}
+#[no_mangle]
+pub extern "C" fn ChannelMonitorUpdate_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelMonitorUpdateDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::chain::channelmonitor::ChannelMonitorUpdate { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
 }
 /// An error enum representing a failure to persist a channel monitor update.
 #[must_use]
@@ -255,67 +258,113 @@ extern "C" fn MonitorUpdateError_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl MonitorUpdateError {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeMonitorUpdateError {
+       pub(crate) fn take_inner(mut self) -> *mut nativeMonitorUpdateError {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-
-use lightning::chain::channelmonitor::MonitorEvent as nativeMonitorEventImport;
-type nativeMonitorEvent = nativeMonitorEventImport;
-
-/// An event to be processed by the ChannelManager.
-#[must_use]
-#[repr(C)]
-pub struct MonitorEvent {
-       /// Nearly everywhere, inner must be non-null, however in places where
-       /// the Rust equivalent takes an Option, it may be set to null to indicate None.
-       pub inner: *mut nativeMonitorEvent,
-       pub is_owned: bool,
-}
-
-impl Drop for MonitorEvent {
-       fn drop(&mut self) {
-               if self.is_owned && !self.inner.is_null() {
-                       let _ = unsafe { Box::from_raw(self.inner) };
+impl Clone for MonitorUpdateError {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
                }
        }
 }
-#[no_mangle]
-pub extern "C" fn MonitorEvent_free(this_ptr: MonitorEvent) { }
 #[allow(unused)]
 /// Used only if an object of this type is returned as a trait impl by a method
-extern "C" fn MonitorEvent_free_void(this_ptr: *mut c_void) {
-       unsafe { let _ = Box::from_raw(this_ptr as *mut nativeMonitorEvent); }
+pub(crate) extern "C" fn MonitorUpdateError_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeMonitorUpdateError)).clone() })) as *mut c_void
 }
-#[allow(unused)]
-/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
+#[no_mangle]
+pub extern "C" fn MonitorUpdateError_clone(orig: &MonitorUpdateError) -> MonitorUpdateError {
+       orig.clone()
+}
+/// An event to be processed by the ChannelManager.
+#[must_use]
+#[derive(Clone)]
+#[repr(C)]
+pub enum MonitorEvent {
+       /// A monitor event containing an HTLCUpdate.
+       HTLCEvent(crate::chain::channelmonitor::HTLCUpdate),
+       /// A monitor event that the Channel's commitment transaction was broadcasted.
+       CommitmentTxBroadcasted(crate::chain::transaction::OutPoint),
+}
+use lightning::chain::channelmonitor::MonitorEvent as nativeMonitorEvent;
 impl MonitorEvent {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeMonitorEvent {
-               assert!(self.is_owned);
-               let ret = self.inner;
-               self.inner = std::ptr::null_mut();
-               ret
+       #[allow(unused)]
+       pub(crate) fn to_native(&self) -> nativeMonitorEvent {
+               match self {
+                       MonitorEvent::HTLCEvent (ref a, ) => {
+                               let mut a_nonref = (*a).clone();
+                               nativeMonitorEvent::HTLCEvent (
+                                       *unsafe { Box::from_raw(a_nonref.take_inner()) },
+                               )
+                       },
+                       MonitorEvent::CommitmentTxBroadcasted (ref a, ) => {
+                               let mut a_nonref = (*a).clone();
+                               nativeMonitorEvent::CommitmentTxBroadcasted (
+                                       *unsafe { Box::from_raw(a_nonref.take_inner()) },
+                               )
+                       },
+               }
        }
-}
-impl Clone for MonitorEvent {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
+       #[allow(unused)]
+       pub(crate) fn into_native(self) -> nativeMonitorEvent {
+               match self {
+                       MonitorEvent::HTLCEvent (mut a, ) => {
+                               nativeMonitorEvent::HTLCEvent (
+                                       *unsafe { Box::from_raw(a.take_inner()) },
+                               )
+                       },
+                       MonitorEvent::CommitmentTxBroadcasted (mut a, ) => {
+                               nativeMonitorEvent::CommitmentTxBroadcasted (
+                                       *unsafe { Box::from_raw(a.take_inner()) },
+                               )
+                       },
+               }
+       }
+       #[allow(unused)]
+       pub(crate) fn from_native(native: &nativeMonitorEvent) -> Self {
+               match native {
+                       nativeMonitorEvent::HTLCEvent (ref a, ) => {
+                               let mut a_nonref = (*a).clone();
+                               MonitorEvent::HTLCEvent (
+                                       crate::chain::channelmonitor::HTLCUpdate { inner: Box::into_raw(Box::new(a_nonref)), is_owned: true },
+                               )
+                       },
+                       nativeMonitorEvent::CommitmentTxBroadcasted (ref a, ) => {
+                               let mut a_nonref = (*a).clone();
+                               MonitorEvent::CommitmentTxBroadcasted (
+                                       crate::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(a_nonref)), is_owned: true },
+                               )
+                       },
+               }
+       }
+       #[allow(unused)]
+       pub(crate) fn native_into(native: nativeMonitorEvent) -> Self {
+               match native {
+                       nativeMonitorEvent::HTLCEvent (mut a, ) => {
+                               MonitorEvent::HTLCEvent (
+                                       crate::chain::channelmonitor::HTLCUpdate { inner: Box::into_raw(Box::new(a)), is_owned: true },
+                               )
+                       },
+                       nativeMonitorEvent::CommitmentTxBroadcasted (mut a, ) => {
+                               MonitorEvent::CommitmentTxBroadcasted (
+                                       crate::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(a)), is_owned: true },
+                               )
+                       },
                }
        }
 }
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn MonitorEvent_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeMonitorEvent)).clone() })) as *mut c_void
-}
+#[no_mangle]
+pub extern "C" fn MonitorEvent_free(this_ptr: MonitorEvent) { }
 #[no_mangle]
 pub extern "C" fn MonitorEvent_clone(orig: &MonitorEvent) -> MonitorEvent {
-       MonitorEvent { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
+       orig.clone()
 }
 
 use lightning::chain::channelmonitor::HTLCUpdate as nativeHTLCUpdateImport;
@@ -352,7 +401,7 @@ extern "C" fn HTLCUpdate_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl HTLCUpdate {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeHTLCUpdate {
+       pub(crate) fn take_inner(mut self) -> *mut nativeHTLCUpdate {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
@@ -362,7 +411,8 @@ impl HTLCUpdate {
 impl Clone for HTLCUpdate {
        fn clone(&self) -> Self {
                Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
                        is_owned: true,
                }
        }
@@ -374,23 +424,25 @@ pub(crate) extern "C" fn HTLCUpdate_clone_void(this_ptr: *const c_void) -> *mut
 }
 #[no_mangle]
 pub extern "C" fn HTLCUpdate_clone(orig: &HTLCUpdate) -> HTLCUpdate {
-       HTLCUpdate { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
+       orig.clone()
 }
 #[no_mangle]
-pub extern "C" fn HTLCUpdate_write(obj: *const HTLCUpdate) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub extern "C" fn HTLCUpdate_write(obj: &HTLCUpdate) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
 }
 #[no_mangle]
-pub extern "C" fn HTLCUpdate_read(ser: crate::c_types::u8slice) -> HTLCUpdate {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               HTLCUpdate { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               HTLCUpdate { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub(crate) extern "C" fn HTLCUpdate_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeHTLCUpdate) })
+}
+#[no_mangle]
+pub extern "C" fn HTLCUpdate_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_HTLCUpdateDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::chain::channelmonitor::HTLCUpdate { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
 }
 
 use lightning::chain::channelmonitor::ChannelMonitor as nativeChannelMonitorImport;
-type nativeChannelMonitor = nativeChannelMonitorImport<crate::chain::keysinterface::ChannelKeys>;
+type nativeChannelMonitor = nativeChannelMonitorImport<crate::chain::keysinterface::Sign>;
 
 /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
 /// on-chain transactions to ensure no loss of funds occurs.
@@ -402,6 +454,12 @@ type nativeChannelMonitor = nativeChannelMonitorImport<crate::chain::keysinterfa
 /// get_and_clear_pending_monitor_events or get_and_clear_pending_events are serialized to disk and
 /// reloaded at deserialize-time. Thus, you must ensure that, when handling events, all events
 /// gotten are fully handled before re-serializing the new state.
+///
+/// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
+/// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
+/// the \"reorg path\" (ie disconnecting blocks until you find a common ancestor from both the
+/// returned block hash and the the current chain and then reconnecting blocks to get to the
+/// best chain) upon deserializing the object!
 #[must_use]
 #[repr(C)]
 pub struct ChannelMonitor {
@@ -428,13 +486,21 @@ extern "C" fn ChannelMonitor_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl ChannelMonitor {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeChannelMonitor {
+       pub(crate) fn take_inner(mut self) -> *mut nativeChannelMonitor {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
+#[no_mangle]
+pub extern "C" fn ChannelMonitor_write(obj: &ChannelMonitor) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+}
+#[no_mangle]
+pub(crate) extern "C" fn ChannelMonitor_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeChannelMonitor) })
+}
 /// Updates a ChannelMonitor on the basis of some new information provided by the Channel
 /// itself.
 ///
@@ -443,7 +509,7 @@ impl ChannelMonitor {
 #[no_mangle]
 pub extern "C" fn ChannelMonitor_update_monitor(this_arg: &mut ChannelMonitor, updates: &crate::chain::channelmonitor::ChannelMonitorUpdate, broadcaster: &crate::chain::chaininterface::BroadcasterInterface, fee_estimator: &crate::chain::chaininterface::FeeEstimator, logger: &crate::util::logger::Logger) -> crate::c_types::derived::CResult_NoneMonitorUpdateErrorZ {
        let mut ret = unsafe { &mut (*(this_arg.inner as *mut nativeChannelMonitor)) }.update_monitor(unsafe { &*updates.inner }, broadcaster, fee_estimator, logger);
-       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }), Err(mut e) => crate::c_types::CResultTempl::err( { crate::chain::channelmonitor::MonitorUpdateError { inner: Box::into_raw(Box::new(e)), is_owned: true } }) };
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::chain::channelmonitor::MonitorUpdateError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
        local_ret
 }
 
@@ -473,7 +539,7 @@ pub extern "C" fn ChannelMonitor_get_funding_txo(this_arg: &ChannelMonitor) -> c
 #[no_mangle]
 pub extern "C" fn ChannelMonitor_get_and_clear_pending_monitor_events(this_arg: &mut ChannelMonitor) -> crate::c_types::derived::CVec_MonitorEventZ {
        let mut ret = unsafe { &mut (*(this_arg.inner as *mut nativeChannelMonitor)) }.get_and_clear_pending_monitor_events();
-       let mut local_ret = Vec::new(); for item in ret.drain(..) { local_ret.push( { crate::chain::channelmonitor::MonitorEvent { inner: Box::into_raw(Box::new(item)), is_owned: true } }); };
+       let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::chain::channelmonitor::MonitorEvent::native_into(item) }); };
        local_ret.into()
 }
 
@@ -487,7 +553,7 @@ pub extern "C" fn ChannelMonitor_get_and_clear_pending_monitor_events(this_arg:
 #[no_mangle]
 pub extern "C" fn ChannelMonitor_get_and_clear_pending_events(this_arg: &mut ChannelMonitor) -> crate::c_types::derived::CVec_EventZ {
        let mut ret = unsafe { &mut (*(this_arg.inner as *mut nativeChannelMonitor)) }.get_and_clear_pending_events();
-       let mut local_ret = Vec::new(); for item in ret.drain(..) { local_ret.push( { crate::util::events::Event::native_into(item) }); };
+       let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::util::events::Event::native_into(item) }); };
        local_ret.into()
 }
 
@@ -504,7 +570,7 @@ pub extern "C" fn ChannelMonitor_get_and_clear_pending_events(this_arg: &mut Cha
 #[no_mangle]
 pub extern "C" fn ChannelMonitor_get_latest_holder_commitment_txn(this_arg: &mut ChannelMonitor, logger: &crate::util::logger::Logger) -> crate::c_types::derived::CVec_TransactionZ {
        let mut ret = unsafe { &mut (*(this_arg.inner as *mut nativeChannelMonitor)) }.get_latest_holder_commitment_txn(logger);
-       let mut local_ret = Vec::new(); for item in ret.drain(..) { local_ret.push( { let mut local_ret_0 = ::bitcoin::consensus::encode::serialize(&item); crate::c_types::Transaction::from_vec(local_ret_0) }); };
+       let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { let mut local_ret_0 = ::bitcoin::consensus::encode::serialize(&item); crate::c_types::Transaction::from_vec(local_ret_0) }); };
        local_ret.into()
 }
 
@@ -524,7 +590,7 @@ pub extern "C" fn ChannelMonitor_get_latest_holder_commitment_txn(this_arg: &mut
 pub extern "C" fn ChannelMonitor_block_connected(this_arg: &mut ChannelMonitor, header: *const [u8; 80], mut txdata: crate::c_types::derived::CVec_C2Tuple_usizeTransactionZZ, mut height: u32, mut broadcaster: crate::chain::chaininterface::BroadcasterInterface, mut fee_estimator: crate::chain::chaininterface::FeeEstimator, mut logger: crate::util::logger::Logger) -> crate::c_types::derived::CVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ {
        let mut local_txdata = Vec::new(); for mut item in txdata.into_rust().drain(..) { local_txdata.push( { let (mut orig_txdata_0_0, mut orig_txdata_0_1) = item.to_rust(); let mut local_txdata_0 = (orig_txdata_0_0, orig_txdata_0_1.into_bitcoin()); local_txdata_0 }); };
        let mut ret = unsafe { &mut (*(this_arg.inner as *mut nativeChannelMonitor)) }.block_connected(&::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), &local_txdata.iter().map(|(a, b)| (*a, b)).collect::<Vec<_>>()[..], height, broadcaster, fee_estimator, logger);
-       let mut local_ret = Vec::new(); for item in ret.drain(..) { local_ret.push( { let (mut orig_ret_0_0, mut orig_ret_0_1) = item; let mut local_orig_ret_0_1 = Vec::new(); for item in orig_ret_0_1.drain(..) { local_orig_ret_0_1.push( { let (mut orig_orig_ret_0_1_0_0, mut orig_orig_ret_0_1_0_1) = item; let mut local_orig_ret_0_1_0 = (orig_orig_ret_0_1_0_0, crate::c_types::TxOut::from_rust(orig_orig_ret_0_1_0_1)).into(); local_orig_ret_0_1_0 }); }; let mut local_ret_0 = (crate::c_types::ThirtyTwoBytes { data: orig_ret_0_0.into_inner() }, local_orig_ret_0_1.into()).into(); local_ret_0 }); };
+       let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { let (mut orig_ret_0_0, mut orig_ret_0_1) = item; let mut local_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.drain(..) { local_orig_ret_0_1.push( { let (mut orig_orig_ret_0_1_0_0, mut orig_orig_ret_0_1_0_1) = item; let mut local_orig_ret_0_1_0 = (orig_orig_ret_0_1_0_0, crate::c_types::TxOut::from_rust(orig_orig_ret_0_1_0_1)).into(); local_orig_ret_0_1_0 }); }; let mut local_ret_0 = (crate::c_types::ThirtyTwoBytes { data: orig_ret_0_0.into_inner() }, local_orig_ret_0_1.into()).into(); local_ret_0 }); };
        local_ret.into()
 }
 
@@ -597,15 +663,15 @@ unsafe impl Send for Persist {}
 unsafe impl Sync for Persist {}
 
 use lightning::chain::channelmonitor::Persist as rustPersist;
-impl rustPersist<crate::chain::keysinterface::ChannelKeys> for Persist {
-       fn persist_new_channel(&self, id: lightning::chain::transaction::OutPoint, data: &lightning::chain::channelmonitor::ChannelMonitor<crate::chain::keysinterface::ChannelKeys>) -> Result<(), lightning::chain::channelmonitor::ChannelMonitorUpdateErr> {
+impl rustPersist<crate::chain::keysinterface::Sign> for Persist {
+       fn persist_new_channel(&self, id: lightning::chain::transaction::OutPoint, data: &lightning::chain::channelmonitor::ChannelMonitor<crate::chain::keysinterface::Sign>) -> Result<(), lightning::chain::channelmonitor::ChannelMonitorUpdateErr> {
                let mut ret = (self.persist_new_channel)(self.this_arg, crate::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(id)), is_owned: true }, &crate::chain::channelmonitor::ChannelMonitor { inner: unsafe { (data as *const _) as *mut _ }, is_owned: false });
-               let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(ret.contents.result.take_ptr()) })*/ }), false => Err( { (*unsafe { Box::from_raw(ret.contents.err.take_ptr()) }).into_native() })};
+               let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).into_native() })};
                local_ret
        }
-       fn update_persisted_channel(&self, id: lightning::chain::transaction::OutPoint, update: &lightning::chain::channelmonitor::ChannelMonitorUpdate, data: &lightning::chain::channelmonitor::ChannelMonitor<crate::chain::keysinterface::ChannelKeys>) -> Result<(), lightning::chain::channelmonitor::ChannelMonitorUpdateErr> {
+       fn update_persisted_channel(&self, id: lightning::chain::transaction::OutPoint, update: &lightning::chain::channelmonitor::ChannelMonitorUpdate, data: &lightning::chain::channelmonitor::ChannelMonitor<crate::chain::keysinterface::Sign>) -> Result<(), lightning::chain::channelmonitor::ChannelMonitorUpdateErr> {
                let mut ret = (self.update_persisted_channel)(self.this_arg, crate::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(id)), is_owned: true }, &crate::chain::channelmonitor::ChannelMonitorUpdate { inner: unsafe { (update as *const _) as *mut _ }, is_owned: false }, &crate::chain::channelmonitor::ChannelMonitor { inner: unsafe { (data as *const _) as *mut _ }, is_owned: false });
-               let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(ret.contents.result.take_ptr()) })*/ }), false => Err( { (*unsafe { Box::from_raw(ret.contents.err.take_ptr()) }).into_native() })};
+               let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).into_native() })};
                local_ret
        }
 }
@@ -628,3 +694,10 @@ impl Drop for Persist {
                }
        }
 }
+#[no_mangle]
+pub extern "C" fn C2Tuple_BlockHashChannelMonitorZ_read(ser: crate::c_types::u8slice, arg: &crate::chain::keysinterface::KeysInterface) -> crate::c_types::derived::CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ {
+       let arg_conv = arg;
+       let res: Result<(bitcoin::hash_types::BlockHash, lightning::chain::channelmonitor::ChannelMonitor<crate::chain::keysinterface::Sign>), lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj_arg(ser, arg_conv);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_res_0_0, mut orig_res_0_1) = o; let mut local_res_0 = (crate::c_types::ThirtyTwoBytes { data: orig_res_0_0.into_inner() }, crate::chain::channelmonitor::ChannelMonitor { inner: Box::into_raw(Box::new(orig_res_0_1)), is_owned: true }).into(); local_res_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
+}
index afa982bc45cfdabe65855595a130ee57856e36a5..9235f8ec38a3924f183e1ffcb43cbb9f7648f7cf 100644 (file)
@@ -6,6 +6,264 @@ use std::ffi::c_void;
 use bitcoin::hashes::Hash;
 use crate::c_types::*;
 
+
+use lightning::chain::keysinterface::DelayedPaymentOutputDescriptor as nativeDelayedPaymentOutputDescriptorImport;
+type nativeDelayedPaymentOutputDescriptor = nativeDelayedPaymentOutputDescriptorImport;
+
+/// Information about a spendable output to a P2WSH script. See
+/// SpendableOutputDescriptor::DelayedPaymentOutput for more details on how to spend this.
+#[must_use]
+#[repr(C)]
+pub struct DelayedPaymentOutputDescriptor {
+       /// Nearly everywhere, inner must be non-null, however in places where
+       /// the Rust equivalent takes an Option, it may be set to null to indicate None.
+       pub inner: *mut nativeDelayedPaymentOutputDescriptor,
+       pub is_owned: bool,
+}
+
+impl Drop for DelayedPaymentOutputDescriptor {
+       fn drop(&mut self) {
+               if self.is_owned && !self.inner.is_null() {
+                       let _ = unsafe { Box::from_raw(self.inner) };
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn DelayedPaymentOutputDescriptor_free(this_ptr: DelayedPaymentOutputDescriptor) { }
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+extern "C" fn DelayedPaymentOutputDescriptor_free_void(this_ptr: *mut c_void) {
+       unsafe { let _ = Box::from_raw(this_ptr as *mut nativeDelayedPaymentOutputDescriptor); }
+}
+#[allow(unused)]
+/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
+impl DelayedPaymentOutputDescriptor {
+       pub(crate) fn take_inner(mut self) -> *mut nativeDelayedPaymentOutputDescriptor {
+               assert!(self.is_owned);
+               let ret = self.inner;
+               self.inner = std::ptr::null_mut();
+               ret
+       }
+}
+/// The outpoint which is spendable
+#[no_mangle]
+pub extern "C" fn DelayedPaymentOutputDescriptor_get_outpoint(this_ptr: &DelayedPaymentOutputDescriptor) -> crate::chain::transaction::OutPoint {
+       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.outpoint;
+       crate::chain::transaction::OutPoint { inner: unsafe { ( (&((*inner_val)) as *const _) as *mut _) }, is_owned: false }
+}
+/// The outpoint which is spendable
+#[no_mangle]
+pub extern "C" fn DelayedPaymentOutputDescriptor_set_outpoint(this_ptr: &mut DelayedPaymentOutputDescriptor, mut val: crate::chain::transaction::OutPoint) {
+       unsafe { &mut *this_ptr.inner }.outpoint = *unsafe { Box::from_raw(val.take_inner()) };
+}
+/// Per commitment point to derive delayed_payment_key by key holder
+#[no_mangle]
+pub extern "C" fn DelayedPaymentOutputDescriptor_get_per_commitment_point(this_ptr: &DelayedPaymentOutputDescriptor) -> crate::c_types::PublicKey {
+       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.per_commitment_point;
+       crate::c_types::PublicKey::from_rust(&(*inner_val))
+}
+/// Per commitment point to derive delayed_payment_key by key holder
+#[no_mangle]
+pub extern "C" fn DelayedPaymentOutputDescriptor_set_per_commitment_point(this_ptr: &mut DelayedPaymentOutputDescriptor, mut val: crate::c_types::PublicKey) {
+       unsafe { &mut *this_ptr.inner }.per_commitment_point = val.into_rust();
+}
+/// The nSequence value which must be set in the spending input to satisfy the OP_CSV in
+/// the witness_script.
+#[no_mangle]
+pub extern "C" fn DelayedPaymentOutputDescriptor_get_to_self_delay(this_ptr: &DelayedPaymentOutputDescriptor) -> u16 {
+       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.to_self_delay;
+       (*inner_val)
+}
+/// The nSequence value which must be set in the spending input to satisfy the OP_CSV in
+/// the witness_script.
+#[no_mangle]
+pub extern "C" fn DelayedPaymentOutputDescriptor_set_to_self_delay(this_ptr: &mut DelayedPaymentOutputDescriptor, mut val: u16) {
+       unsafe { &mut *this_ptr.inner }.to_self_delay = val;
+}
+/// The output which is referenced by the given outpoint
+#[no_mangle]
+pub extern "C" fn DelayedPaymentOutputDescriptor_set_output(this_ptr: &mut DelayedPaymentOutputDescriptor, mut val: crate::c_types::TxOut) {
+       unsafe { &mut *this_ptr.inner }.output = val.into_rust();
+}
+/// The revocation point specific to the commitment transaction which was broadcast. Used to
+/// derive the witnessScript for this output.
+#[no_mangle]
+pub extern "C" fn DelayedPaymentOutputDescriptor_get_revocation_pubkey(this_ptr: &DelayedPaymentOutputDescriptor) -> crate::c_types::PublicKey {
+       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.revocation_pubkey;
+       crate::c_types::PublicKey::from_rust(&(*inner_val))
+}
+/// The revocation point specific to the commitment transaction which was broadcast. Used to
+/// derive the witnessScript for this output.
+#[no_mangle]
+pub extern "C" fn DelayedPaymentOutputDescriptor_set_revocation_pubkey(this_ptr: &mut DelayedPaymentOutputDescriptor, mut val: crate::c_types::PublicKey) {
+       unsafe { &mut *this_ptr.inner }.revocation_pubkey = val.into_rust();
+}
+/// Arbitrary identification information returned by a call to
+/// `Sign::channel_keys_id()`. This may be useful in re-deriving keys used in
+/// the channel to spend the output.
+#[no_mangle]
+pub extern "C" fn DelayedPaymentOutputDescriptor_get_channel_keys_id(this_ptr: &DelayedPaymentOutputDescriptor) -> *const [u8; 32] {
+       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.channel_keys_id;
+       &(*inner_val)
+}
+/// Arbitrary identification information returned by a call to
+/// `Sign::channel_keys_id()`. This may be useful in re-deriving keys used in
+/// the channel to spend the output.
+#[no_mangle]
+pub extern "C" fn DelayedPaymentOutputDescriptor_set_channel_keys_id(this_ptr: &mut DelayedPaymentOutputDescriptor, mut val: crate::c_types::ThirtyTwoBytes) {
+       unsafe { &mut *this_ptr.inner }.channel_keys_id = val.data;
+}
+/// The value of the channel which this output originated from, possibly indirectly.
+#[no_mangle]
+pub extern "C" fn DelayedPaymentOutputDescriptor_get_channel_value_satoshis(this_ptr: &DelayedPaymentOutputDescriptor) -> u64 {
+       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.channel_value_satoshis;
+       (*inner_val)
+}
+/// The value of the channel which this output originated from, possibly indirectly.
+#[no_mangle]
+pub extern "C" fn DelayedPaymentOutputDescriptor_set_channel_value_satoshis(this_ptr: &mut DelayedPaymentOutputDescriptor, mut val: u64) {
+       unsafe { &mut *this_ptr.inner }.channel_value_satoshis = val;
+}
+#[must_use]
+#[no_mangle]
+pub extern "C" fn DelayedPaymentOutputDescriptor_new(mut outpoint_arg: crate::chain::transaction::OutPoint, mut per_commitment_point_arg: crate::c_types::PublicKey, mut to_self_delay_arg: u16, mut output_arg: crate::c_types::TxOut, mut revocation_pubkey_arg: crate::c_types::PublicKey, mut channel_keys_id_arg: crate::c_types::ThirtyTwoBytes, mut channel_value_satoshis_arg: u64) -> DelayedPaymentOutputDescriptor {
+       DelayedPaymentOutputDescriptor { inner: Box::into_raw(Box::new(nativeDelayedPaymentOutputDescriptor {
+               outpoint: *unsafe { Box::from_raw(outpoint_arg.take_inner()) },
+               per_commitment_point: per_commitment_point_arg.into_rust(),
+               to_self_delay: to_self_delay_arg,
+               output: output_arg.into_rust(),
+               revocation_pubkey: revocation_pubkey_arg.into_rust(),
+               channel_keys_id: channel_keys_id_arg.data,
+               channel_value_satoshis: channel_value_satoshis_arg,
+       })), is_owned: true }
+}
+impl Clone for DelayedPaymentOutputDescriptor {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn DelayedPaymentOutputDescriptor_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeDelayedPaymentOutputDescriptor)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn DelayedPaymentOutputDescriptor_clone(orig: &DelayedPaymentOutputDescriptor) -> DelayedPaymentOutputDescriptor {
+       orig.clone()
+}
+
+use lightning::chain::keysinterface::StaticPaymentOutputDescriptor as nativeStaticPaymentOutputDescriptorImport;
+type nativeStaticPaymentOutputDescriptor = nativeStaticPaymentOutputDescriptorImport;
+
+/// Information about a spendable output to our \"payment key\". See
+/// SpendableOutputDescriptor::StaticPaymentOutput for more details on how to spend this.
+#[must_use]
+#[repr(C)]
+pub struct StaticPaymentOutputDescriptor {
+       /// Nearly everywhere, inner must be non-null, however in places where
+       /// the Rust equivalent takes an Option, it may be set to null to indicate None.
+       pub inner: *mut nativeStaticPaymentOutputDescriptor,
+       pub is_owned: bool,
+}
+
+impl Drop for StaticPaymentOutputDescriptor {
+       fn drop(&mut self) {
+               if self.is_owned && !self.inner.is_null() {
+                       let _ = unsafe { Box::from_raw(self.inner) };
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn StaticPaymentOutputDescriptor_free(this_ptr: StaticPaymentOutputDescriptor) { }
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+extern "C" fn StaticPaymentOutputDescriptor_free_void(this_ptr: *mut c_void) {
+       unsafe { let _ = Box::from_raw(this_ptr as *mut nativeStaticPaymentOutputDescriptor); }
+}
+#[allow(unused)]
+/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
+impl StaticPaymentOutputDescriptor {
+       pub(crate) fn take_inner(mut self) -> *mut nativeStaticPaymentOutputDescriptor {
+               assert!(self.is_owned);
+               let ret = self.inner;
+               self.inner = std::ptr::null_mut();
+               ret
+       }
+}
+/// The outpoint which is spendable
+#[no_mangle]
+pub extern "C" fn StaticPaymentOutputDescriptor_get_outpoint(this_ptr: &StaticPaymentOutputDescriptor) -> crate::chain::transaction::OutPoint {
+       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.outpoint;
+       crate::chain::transaction::OutPoint { inner: unsafe { ( (&((*inner_val)) as *const _) as *mut _) }, is_owned: false }
+}
+/// The outpoint which is spendable
+#[no_mangle]
+pub extern "C" fn StaticPaymentOutputDescriptor_set_outpoint(this_ptr: &mut StaticPaymentOutputDescriptor, mut val: crate::chain::transaction::OutPoint) {
+       unsafe { &mut *this_ptr.inner }.outpoint = *unsafe { Box::from_raw(val.take_inner()) };
+}
+/// The output which is referenced by the given outpoint
+#[no_mangle]
+pub extern "C" fn StaticPaymentOutputDescriptor_set_output(this_ptr: &mut StaticPaymentOutputDescriptor, mut val: crate::c_types::TxOut) {
+       unsafe { &mut *this_ptr.inner }.output = val.into_rust();
+}
+/// Arbitrary identification information returned by a call to
+/// `Sign::channel_keys_id()`. This may be useful in re-deriving keys used in
+/// the channel to spend the output.
+#[no_mangle]
+pub extern "C" fn StaticPaymentOutputDescriptor_get_channel_keys_id(this_ptr: &StaticPaymentOutputDescriptor) -> *const [u8; 32] {
+       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.channel_keys_id;
+       &(*inner_val)
+}
+/// Arbitrary identification information returned by a call to
+/// `Sign::channel_keys_id()`. This may be useful in re-deriving keys used in
+/// the channel to spend the output.
+#[no_mangle]
+pub extern "C" fn StaticPaymentOutputDescriptor_set_channel_keys_id(this_ptr: &mut StaticPaymentOutputDescriptor, mut val: crate::c_types::ThirtyTwoBytes) {
+       unsafe { &mut *this_ptr.inner }.channel_keys_id = val.data;
+}
+/// The value of the channel which this transactions spends.
+#[no_mangle]
+pub extern "C" fn StaticPaymentOutputDescriptor_get_channel_value_satoshis(this_ptr: &StaticPaymentOutputDescriptor) -> u64 {
+       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.channel_value_satoshis;
+       (*inner_val)
+}
+/// The value of the channel which this transactions spends.
+#[no_mangle]
+pub extern "C" fn StaticPaymentOutputDescriptor_set_channel_value_satoshis(this_ptr: &mut StaticPaymentOutputDescriptor, mut val: u64) {
+       unsafe { &mut *this_ptr.inner }.channel_value_satoshis = val;
+}
+#[must_use]
+#[no_mangle]
+pub extern "C" fn StaticPaymentOutputDescriptor_new(mut outpoint_arg: crate::chain::transaction::OutPoint, mut output_arg: crate::c_types::TxOut, mut channel_keys_id_arg: crate::c_types::ThirtyTwoBytes, mut channel_value_satoshis_arg: u64) -> StaticPaymentOutputDescriptor {
+       StaticPaymentOutputDescriptor { inner: Box::into_raw(Box::new(nativeStaticPaymentOutputDescriptor {
+               outpoint: *unsafe { Box::from_raw(outpoint_arg.take_inner()) },
+               output: output_arg.into_rust(),
+               channel_keys_id: channel_keys_id_arg.data,
+               channel_value_satoshis: channel_value_satoshis_arg,
+       })), is_owned: true }
+}
+impl Clone for StaticPaymentOutputDescriptor {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn StaticPaymentOutputDescriptor_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeStaticPaymentOutputDescriptor)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn StaticPaymentOutputDescriptor_clone(orig: &StaticPaymentOutputDescriptor) -> StaticPaymentOutputDescriptor {
+       orig.clone()
+}
 /// When on-chain outputs are created by rust-lightning (which our counterparty is not able to
 /// claim at any point in the future) an event is generated which you must track and be able to
 /// spend on-chain. The information needed to do this is provided in this enum, including the
@@ -15,9 +273,9 @@ use crate::c_types::*;
 #[derive(Clone)]
 #[repr(C)]
 pub enum SpendableOutputDescriptor {
-       /// An output to a script which was provided via KeysInterface, thus you should already know
-       /// how to spend it. No keys are provided as rust-lightning was never given any keys - only the
-       /// script_pubkey as it appears in the output.
+       /// An output to a script which was provided via KeysInterface directly, either from
+       /// `get_destination_script()` or `get_shutdown_pubkey()`, thus you should already know how to
+       /// spend it. No secret keys are provided as rust-lightning was never given any key.
        /// These may include outputs from a transaction punishing our counterparty or claiming an HTLC
        /// on-chain using the payment preimage or after it has timed out.
        StaticOutput {
@@ -38,40 +296,29 @@ pub enum SpendableOutputDescriptor {
        ///
        /// To derive the delayed_payment key which is used to sign for this input, you must pass the
        /// holder delayed_payment_base_key (ie the private key which corresponds to the pubkey in
-       /// ChannelKeys::pubkeys().delayed_payment_basepoint) and the provided per_commitment_point to
+       /// Sign::pubkeys().delayed_payment_basepoint) and the provided per_commitment_point to
        /// chan_utils::derive_private_key. The public key can be generated without the secret key
        /// using chan_utils::derive_public_key and only the delayed_payment_basepoint which appears in
-       /// ChannelKeys::pubkeys().
+       /// Sign::pubkeys().
        ///
        /// To derive the revocation_pubkey provided here (which is used in the witness
        /// script generation), you must pass the counterparty revocation_basepoint (which appears in the
-       /// call to ChannelKeys::on_accept) and the provided per_commitment point
+       /// call to Sign::ready_channel) and the provided per_commitment point
        /// to chan_utils::derive_public_revocation_key.
        ///
        /// The witness script which is hashed and included in the output script_pubkey may be
        /// regenerated by passing the revocation_pubkey (derived as above), our delayed_payment pubkey
        /// (derived as above), and the to_self_delay contained here to
        /// chan_utils::get_revokeable_redeemscript.
-       DynamicOutputP2WSH {
-               outpoint: crate::chain::transaction::OutPoint,
-               per_commitment_point: crate::c_types::PublicKey,
-               to_self_delay: u16,
-               output: crate::c_types::TxOut,
-               key_derivation_params: crate::c_types::derived::C2Tuple_u64u64Z,
-               revocation_pubkey: crate::c_types::PublicKey,
-       },
+       DelayedPaymentOutput(crate::chain::keysinterface::DelayedPaymentOutputDescriptor),
        /// An output to a P2WPKH, spendable exclusively by our payment key (ie the private key which
-       /// corresponds to the public key in ChannelKeys::pubkeys().payment_point).
+       /// corresponds to the public key in Sign::pubkeys().payment_point).
        /// The witness in the spending input, is, thus, simply:
        /// <BIP 143 signature> <payment key>
        ///
        /// These are generally the result of our counterparty having broadcast the current state,
        /// allowing us to claim the non-HTLC-encumbered outputs immediately.
-       StaticOutputCounterpartyPayment {
-               outpoint: crate::chain::transaction::OutPoint,
-               output: crate::c_types::TxOut,
-               key_derivation_params: crate::c_types::derived::C2Tuple_u64u64Z,
-       },
+       StaticPaymentOutput(crate::chain::keysinterface::StaticPaymentOutputDescriptor),
 }
 use lightning::chain::keysinterface::SpendableOutputDescriptor as nativeSpendableOutputDescriptor;
 impl SpendableOutputDescriptor {
@@ -82,37 +329,21 @@ impl SpendableOutputDescriptor {
                                let mut outpoint_nonref = (*outpoint).clone();
                                let mut output_nonref = (*output).clone();
                                nativeSpendableOutputDescriptor::StaticOutput {
-                                       outpoint: *unsafe { Box::from_raw(outpoint_nonref.take_ptr()) },
+                                       outpoint: *unsafe { Box::from_raw(outpoint_nonref.take_inner()) },
                                        output: output_nonref.into_rust(),
                                }
                        },
-                       SpendableOutputDescriptor::DynamicOutputP2WSH {ref outpoint, ref per_commitment_point, ref to_self_delay, ref output, ref key_derivation_params, ref revocation_pubkey, } => {
-                               let mut outpoint_nonref = (*outpoint).clone();
-                               let mut per_commitment_point_nonref = (*per_commitment_point).clone();
-                               let mut to_self_delay_nonref = (*to_self_delay).clone();
-                               let mut output_nonref = (*output).clone();
-                               let mut key_derivation_params_nonref = (*key_derivation_params).clone();
-                               let (mut orig_key_derivation_params_nonref_0, mut orig_key_derivation_params_nonref_1) = key_derivation_params_nonref.to_rust(); let mut local_key_derivation_params_nonref = (orig_key_derivation_params_nonref_0, orig_key_derivation_params_nonref_1);
-                               let mut revocation_pubkey_nonref = (*revocation_pubkey).clone();
-                               nativeSpendableOutputDescriptor::DynamicOutputP2WSH {
-                                       outpoint: *unsafe { Box::from_raw(outpoint_nonref.take_ptr()) },
-                                       per_commitment_point: per_commitment_point_nonref.into_rust(),
-                                       to_self_delay: to_self_delay_nonref,
-                                       output: output_nonref.into_rust(),
-                                       key_derivation_params: local_key_derivation_params_nonref,
-                                       revocation_pubkey: revocation_pubkey_nonref.into_rust(),
-                               }
+                       SpendableOutputDescriptor::DelayedPaymentOutput (ref a, ) => {
+                               let mut a_nonref = (*a).clone();
+                               nativeSpendableOutputDescriptor::DelayedPaymentOutput (
+                                       *unsafe { Box::from_raw(a_nonref.take_inner()) },
+                               )
                        },
-                       SpendableOutputDescriptor::StaticOutputCounterpartyPayment {ref outpoint, ref output, ref key_derivation_params, } => {
-                               let mut outpoint_nonref = (*outpoint).clone();
-                               let mut output_nonref = (*output).clone();
-                               let mut key_derivation_params_nonref = (*key_derivation_params).clone();
-                               let (mut orig_key_derivation_params_nonref_0, mut orig_key_derivation_params_nonref_1) = key_derivation_params_nonref.to_rust(); let mut local_key_derivation_params_nonref = (orig_key_derivation_params_nonref_0, orig_key_derivation_params_nonref_1);
-                               nativeSpendableOutputDescriptor::StaticOutputCounterpartyPayment {
-                                       outpoint: *unsafe { Box::from_raw(outpoint_nonref.take_ptr()) },
-                                       output: output_nonref.into_rust(),
-                                       key_derivation_params: local_key_derivation_params_nonref,
-                               }
+                       SpendableOutputDescriptor::StaticPaymentOutput (ref a, ) => {
+                               let mut a_nonref = (*a).clone();
+                               nativeSpendableOutputDescriptor::StaticPaymentOutput (
+                                       *unsafe { Box::from_raw(a_nonref.take_inner()) },
+                               )
                        },
                }
        }
@@ -121,28 +352,19 @@ impl SpendableOutputDescriptor {
                match self {
                        SpendableOutputDescriptor::StaticOutput {mut outpoint, mut output, } => {
                                nativeSpendableOutputDescriptor::StaticOutput {
-                                       outpoint: *unsafe { Box::from_raw(outpoint.take_ptr()) },
+                                       outpoint: *unsafe { Box::from_raw(outpoint.take_inner()) },
                                        output: output.into_rust(),
                                }
                        },
-                       SpendableOutputDescriptor::DynamicOutputP2WSH {mut outpoint, mut per_commitment_point, mut to_self_delay, mut output, mut key_derivation_params, mut revocation_pubkey, } => {
-                               let (mut orig_key_derivation_params_0, mut orig_key_derivation_params_1) = key_derivation_params.to_rust(); let mut local_key_derivation_params = (orig_key_derivation_params_0, orig_key_derivation_params_1);
-                               nativeSpendableOutputDescriptor::DynamicOutputP2WSH {
-                                       outpoint: *unsafe { Box::from_raw(outpoint.take_ptr()) },
-                                       per_commitment_point: per_commitment_point.into_rust(),
-                                       to_self_delay: to_self_delay,
-                                       output: output.into_rust(),
-                                       key_derivation_params: local_key_derivation_params,
-                                       revocation_pubkey: revocation_pubkey.into_rust(),
-                               }
+                       SpendableOutputDescriptor::DelayedPaymentOutput (mut a, ) => {
+                               nativeSpendableOutputDescriptor::DelayedPaymentOutput (
+                                       *unsafe { Box::from_raw(a.take_inner()) },
+                               )
                        },
-                       SpendableOutputDescriptor::StaticOutputCounterpartyPayment {mut outpoint, mut output, mut key_derivation_params, } => {
-                               let (mut orig_key_derivation_params_0, mut orig_key_derivation_params_1) = key_derivation_params.to_rust(); let mut local_key_derivation_params = (orig_key_derivation_params_0, orig_key_derivation_params_1);
-                               nativeSpendableOutputDescriptor::StaticOutputCounterpartyPayment {
-                                       outpoint: *unsafe { Box::from_raw(outpoint.take_ptr()) },
-                                       output: output.into_rust(),
-                                       key_derivation_params: local_key_derivation_params,
-                               }
+                       SpendableOutputDescriptor::StaticPaymentOutput (mut a, ) => {
+                               nativeSpendableOutputDescriptor::StaticPaymentOutput (
+                                       *unsafe { Box::from_raw(a.take_inner()) },
+                               )
                        },
                }
        }
@@ -157,33 +379,17 @@ impl SpendableOutputDescriptor {
                                        output: crate::c_types::TxOut::from_rust(output_nonref),
                                }
                        },
-                       nativeSpendableOutputDescriptor::DynamicOutputP2WSH {ref outpoint, ref per_commitment_point, ref to_self_delay, ref output, ref key_derivation_params, ref revocation_pubkey, } => {
-                               let mut outpoint_nonref = (*outpoint).clone();
-                               let mut per_commitment_point_nonref = (*per_commitment_point).clone();
-                               let mut to_self_delay_nonref = (*to_self_delay).clone();
-                               let mut output_nonref = (*output).clone();
-                               let mut key_derivation_params_nonref = (*key_derivation_params).clone();
-                               let (mut orig_key_derivation_params_nonref_0, mut orig_key_derivation_params_nonref_1) = key_derivation_params_nonref; let mut local_key_derivation_params_nonref = (orig_key_derivation_params_nonref_0, orig_key_derivation_params_nonref_1).into();
-                               let mut revocation_pubkey_nonref = (*revocation_pubkey).clone();
-                               SpendableOutputDescriptor::DynamicOutputP2WSH {
-                                       outpoint: crate::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(outpoint_nonref)), is_owned: true },
-                                       per_commitment_point: crate::c_types::PublicKey::from_rust(&per_commitment_point_nonref),
-                                       to_self_delay: to_self_delay_nonref,
-                                       output: crate::c_types::TxOut::from_rust(output_nonref),
-                                       key_derivation_params: local_key_derivation_params_nonref,
-                                       revocation_pubkey: crate::c_types::PublicKey::from_rust(&revocation_pubkey_nonref),
-                               }
+                       nativeSpendableOutputDescriptor::DelayedPaymentOutput (ref a, ) => {
+                               let mut a_nonref = (*a).clone();
+                               SpendableOutputDescriptor::DelayedPaymentOutput (
+                                       crate::chain::keysinterface::DelayedPaymentOutputDescriptor { inner: Box::into_raw(Box::new(a_nonref)), is_owned: true },
+                               )
                        },
-                       nativeSpendableOutputDescriptor::StaticOutputCounterpartyPayment {ref outpoint, ref output, ref key_derivation_params, } => {
-                               let mut outpoint_nonref = (*outpoint).clone();
-                               let mut output_nonref = (*output).clone();
-                               let mut key_derivation_params_nonref = (*key_derivation_params).clone();
-                               let (mut orig_key_derivation_params_nonref_0, mut orig_key_derivation_params_nonref_1) = key_derivation_params_nonref; let mut local_key_derivation_params_nonref = (orig_key_derivation_params_nonref_0, orig_key_derivation_params_nonref_1).into();
-                               SpendableOutputDescriptor::StaticOutputCounterpartyPayment {
-                                       outpoint: crate::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(outpoint_nonref)), is_owned: true },
-                                       output: crate::c_types::TxOut::from_rust(output_nonref),
-                                       key_derivation_params: local_key_derivation_params_nonref,
-                               }
+                       nativeSpendableOutputDescriptor::StaticPaymentOutput (ref a, ) => {
+                               let mut a_nonref = (*a).clone();
+                               SpendableOutputDescriptor::StaticPaymentOutput (
+                                       crate::chain::keysinterface::StaticPaymentOutputDescriptor { inner: Box::into_raw(Box::new(a_nonref)), is_owned: true },
+                               )
                        },
                }
        }
@@ -196,24 +402,15 @@ impl SpendableOutputDescriptor {
                                        output: crate::c_types::TxOut::from_rust(output),
                                }
                        },
-                       nativeSpendableOutputDescriptor::DynamicOutputP2WSH {mut outpoint, mut per_commitment_point, mut to_self_delay, mut output, mut key_derivation_params, mut revocation_pubkey, } => {
-                               let (mut orig_key_derivation_params_0, mut orig_key_derivation_params_1) = key_derivation_params; let mut local_key_derivation_params = (orig_key_derivation_params_0, orig_key_derivation_params_1).into();
-                               SpendableOutputDescriptor::DynamicOutputP2WSH {
-                                       outpoint: crate::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(outpoint)), is_owned: true },
-                                       per_commitment_point: crate::c_types::PublicKey::from_rust(&per_commitment_point),
-                                       to_self_delay: to_self_delay,
-                                       output: crate::c_types::TxOut::from_rust(output),
-                                       key_derivation_params: local_key_derivation_params,
-                                       revocation_pubkey: crate::c_types::PublicKey::from_rust(&revocation_pubkey),
-                               }
+                       nativeSpendableOutputDescriptor::DelayedPaymentOutput (mut a, ) => {
+                               SpendableOutputDescriptor::DelayedPaymentOutput (
+                                       crate::chain::keysinterface::DelayedPaymentOutputDescriptor { inner: Box::into_raw(Box::new(a)), is_owned: true },
+                               )
                        },
-                       nativeSpendableOutputDescriptor::StaticOutputCounterpartyPayment {mut outpoint, mut output, mut key_derivation_params, } => {
-                               let (mut orig_key_derivation_params_0, mut orig_key_derivation_params_1) = key_derivation_params; let mut local_key_derivation_params = (orig_key_derivation_params_0, orig_key_derivation_params_1).into();
-                               SpendableOutputDescriptor::StaticOutputCounterpartyPayment {
-                                       outpoint: crate::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(outpoint)), is_owned: true },
-                                       output: crate::c_types::TxOut::from_rust(output),
-                                       key_derivation_params: local_key_derivation_params,
-                               }
+                       nativeSpendableOutputDescriptor::StaticPaymentOutput (mut a, ) => {
+                               SpendableOutputDescriptor::StaticPaymentOutput (
+                                       crate::chain::keysinterface::StaticPaymentOutputDescriptor { inner: Box::into_raw(Box::new(a)), is_owned: true },
+                               )
                        },
                }
        }
@@ -224,10 +421,20 @@ pub extern "C" fn SpendableOutputDescriptor_free(this_ptr: SpendableOutputDescri
 pub extern "C" fn SpendableOutputDescriptor_clone(orig: &SpendableOutputDescriptor) -> SpendableOutputDescriptor {
        orig.clone()
 }
-/// Set of lightning keys needed to operate a channel as described in BOLT 3.
+#[no_mangle]
+pub extern "C" fn SpendableOutputDescriptor_write(obj: &SpendableOutputDescriptor) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(&unsafe { &*obj }.to_native())
+}
+#[no_mangle]
+pub extern "C" fn SpendableOutputDescriptor_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_SpendableOutputDescriptorDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::chain::keysinterface::SpendableOutputDescriptor::native_into(o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
+}
+/// A trait to sign lightning channel transactions as described in BOLT 3.
 ///
 /// Signing services could be implemented on a hardware wallet. In this case,
-/// the current ChannelKeys would be a front-end on top of a communication
+/// the current Sign would be a front-end on top of a communication
 /// channel connected to your secure device and lightning key material wouldn't
 /// reside on a hot server. Nevertheless, a this deployment would still need
 /// to trust the ChannelManager to avoid loss of funds as this latest component
@@ -241,13 +448,8 @@ pub extern "C" fn SpendableOutputDescriptor_clone(orig: &SpendableOutputDescript
 /// In any case, ChannelMonitor or fallback watchtowers are always going to be trusted
 /// to act, as liveness and breach reply correctness are always going to be hard requirements
 /// of LN security model, orthogonal of key management issues.
-///
-/// If you're implementing a custom signer, you almost certainly want to implement
-/// Readable/Writable to serialize out a unique reference to this set of keys so
-/// that you can serialize the full ChannelManager object.
-///
 #[repr(C)]
-pub struct ChannelKeys {
+pub struct Sign {
        pub this_arg: *mut c_void,
        /// Gets the per-commitment point for a specific commitment number
        ///
@@ -262,7 +464,6 @@ pub struct ChannelKeys {
        /// May be called more than once for the same index.
        ///
        /// Note that the commitment number starts at (1 << 48) - 1 and counts backwards.
-       /// TODO: return a Result so we can signal a validation error
        #[must_use]
        pub release_commitment_secret: extern "C" fn (this_arg: *const c_void, idx: u64) -> crate::c_types::ThirtyTwoBytes,
        /// Gets the holder's channel public keys and basepoints
@@ -270,38 +471,30 @@ pub struct ChannelKeys {
        /// Fill in the pubkeys field as a reference to it will be given to Rust after this returns
        /// Note that this takes a pointer to this object, not the this_ptr like other methods do
        /// This function pointer may be NULL if pubkeys is filled in when this object is created and never needs updating.
-       pub set_pubkeys: Option<extern "C" fn(&ChannelKeys)>,
-       /// Gets arbitrary identifiers describing the set of keys which are provided back to you in
-       /// some SpendableOutputDescriptor types. These should be sufficient to identify this
-       /// ChannelKeys object uniquely and lookup or re-derive its keys.
+       pub set_pubkeys: Option<extern "C" fn(&Sign)>,
+       /// Gets an arbitrary identifier describing the set of keys which are provided back to you in
+       /// some SpendableOutputDescriptor types. This should be sufficient to identify this
+       /// Sign object uniquely and lookup or re-derive its keys.
        #[must_use]
-       pub key_derivation_params: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::C2Tuple_u64u64Z,
+       pub channel_keys_id: extern "C" fn (this_arg: *const c_void) -> crate::c_types::ThirtyTwoBytes,
        /// Create a signature for a counterparty's commitment transaction and associated HTLC transactions.
        ///
        /// Note that if signing fails or is rejected, the channel will be force-closed.
        #[must_use]
-       pub sign_counterparty_commitment: extern "C" fn (this_arg: *const c_void, feerate_per_kw: u32, commitment_tx: crate::c_types::Transaction, keys: &crate::ln::chan_utils::PreCalculatedTxCreationKeys, htlcs: crate::c_types::derived::CVec_HTLCOutputInCommitmentZ) -> crate::c_types::derived::CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ,
-       /// Create a signature for a holder's commitment transaction. This will only ever be called with
-       /// the same holder_commitment_tx (or a copy thereof), though there are currently no guarantees
-       /// that it will not be called multiple times.
+       pub sign_counterparty_commitment: extern "C" fn (this_arg: *const c_void, commitment_tx: &crate::ln::chan_utils::CommitmentTransaction) -> crate::c_types::derived::CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ,
+       /// Create a signatures for a holder's commitment transaction and its claiming HTLC transactions.
+       /// This will only ever be called with a non-revoked commitment_tx.  This will be called with the
+       /// latest commitment_tx when we initiate a force-close.
+       /// This will be called with the previous latest, just to get claiming HTLC signatures, if we are
+       /// reacting to a ChannelMonitor replica that decided to broadcast before it had been updated to
+       /// the latest.
+       /// This may be called multiple times for the same transaction.
+       ///
        /// An external signer implementation should check that the commitment has not been revoked.
+       ///
+       /// May return Err if key derivation fails.  Callers, such as ChannelMonitor, will panic in such a case.
        #[must_use]
-       pub sign_holder_commitment: extern "C" fn (this_arg: *const c_void, holder_commitment_tx: &crate::ln::chan_utils::HolderCommitmentTransaction) -> crate::c_types::derived::CResult_SignatureNoneZ,
-       /// Create a signature for each HTLC transaction spending a holder's commitment transaction.
-       ///
-       /// Unlike sign_holder_commitment, this may be called multiple times with *different*
-       /// holder_commitment_tx values. While this will never be called with a revoked
-       /// holder_commitment_tx, it is possible that it is called with the second-latest
-       /// holder_commitment_tx (only if we haven't yet revoked it) if some watchtower/secondary
-       /// ChannelMonitor decided to broadcast before it had been updated to the latest.
-       ///
-       /// Either an Err should be returned, or a Vec with one entry for each HTLC which exists in
-       /// holder_commitment_tx. For those HTLCs which have transaction_output_index set to None
-       /// (implying they were considered dust at the time the commitment transaction was negotiated),
-       /// a corresponding None should be included in the return value. All other positions in the
-       /// return value must contain a signature.
-       #[must_use]
-       pub sign_holder_commitment_htlc_transactions: extern "C" fn (this_arg: *const c_void, holder_commitment_tx: &crate::ln::chan_utils::HolderCommitmentTransaction) -> crate::c_types::derived::CResult_CVec_SignatureZNoneZ,
+       pub sign_holder_commitment_and_htlcs: extern "C" fn (this_arg: *const c_void, commitment_tx: &crate::ln::chan_utils::HolderCommitmentTransaction) -> crate::c_types::derived::CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ,
        /// Create a signature for the given input in a transaction spending an HTLC or commitment
        /// transaction output when our counterparty broadcasts an old state.
        ///
@@ -355,46 +548,57 @@ pub struct ChannelKeys {
        /// protocol.
        #[must_use]
        pub sign_channel_announcement: extern "C" fn (this_arg: *const c_void, msg: &crate::ln::msgs::UnsignedChannelAnnouncement) -> crate::c_types::derived::CResult_SignatureNoneZ,
-       /// Set the counterparty channel basepoints and counterparty_selected/holder_selected_contest_delay.
-       /// This is done immediately on incoming channels and as soon as the channel is accepted on outgoing channels.
+       /// Set the counterparty static channel data, including basepoints,
+       /// counterparty_selected/holder_selected_contest_delay and funding outpoint.
+       /// This is done as soon as the funding outpoint is known.  Since these are static channel data,
+       /// they MUST NOT be allowed to change to different values once set.
+       ///
+       /// channel_parameters.is_populated() MUST be true.
        ///
        /// We bind holder_selected_contest_delay late here for API convenience.
        ///
        /// Will be called before any signatures are applied.
-       pub on_accept: extern "C" fn (this_arg: *mut c_void, channel_points: &crate::ln::chan_utils::ChannelPublicKeys, counterparty_selected_contest_delay: u16, holder_selected_contest_delay: u16),
+       pub ready_channel: extern "C" fn (this_arg: *mut c_void, channel_parameters: &crate::ln::chan_utils::ChannelTransactionParameters),
        pub clone: Option<extern "C" fn (this_arg: *const c_void) -> *mut c_void>,
+       pub write: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_u8Z,
        pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
 }
-unsafe impl Send for ChannelKeys {}
+unsafe impl Send for Sign {}
 #[no_mangle]
-pub extern "C" fn ChannelKeys_clone(orig: &ChannelKeys) -> ChannelKeys {
-       ChannelKeys {
+pub extern "C" fn Sign_clone(orig: &Sign) -> Sign {
+       Sign {
                this_arg: if let Some(f) = orig.clone { (f)(orig.this_arg) } else { orig.this_arg },
                get_per_commitment_point: orig.get_per_commitment_point.clone(),
                release_commitment_secret: orig.release_commitment_secret.clone(),
                pubkeys: orig.pubkeys.clone(),
                set_pubkeys: orig.set_pubkeys.clone(),
-               key_derivation_params: orig.key_derivation_params.clone(),
+               channel_keys_id: orig.channel_keys_id.clone(),
                sign_counterparty_commitment: orig.sign_counterparty_commitment.clone(),
-               sign_holder_commitment: orig.sign_holder_commitment.clone(),
-               sign_holder_commitment_htlc_transactions: orig.sign_holder_commitment_htlc_transactions.clone(),
+               sign_holder_commitment_and_htlcs: orig.sign_holder_commitment_and_htlcs.clone(),
                sign_justice_transaction: orig.sign_justice_transaction.clone(),
                sign_counterparty_htlc_transaction: orig.sign_counterparty_htlc_transaction.clone(),
                sign_closing_transaction: orig.sign_closing_transaction.clone(),
                sign_channel_announcement: orig.sign_channel_announcement.clone(),
-               on_accept: orig.on_accept.clone(),
+               ready_channel: orig.ready_channel.clone(),
                clone: orig.clone.clone(),
+               write: orig.write.clone(),
                free: orig.free.clone(),
        }
 }
-impl Clone for ChannelKeys {
+impl Clone for Sign {
        fn clone(&self) -> Self {
-               ChannelKeys_clone(self)
+               Sign_clone(self)
+       }
+}
+impl lightning::util::ser::Writeable for Sign {
+       fn write<W: lightning::util::ser::Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
+               let vec = (self.write)(self.this_arg);
+               w.write_all(vec.as_slice())
        }
 }
 
-use lightning::chain::keysinterface::ChannelKeys as rustChannelKeys;
-impl rustChannelKeys for ChannelKeys {
+use lightning::chain::keysinterface::Sign as rustSign;
+impl rustSign for Sign {
        fn get_per_commitment_point<T:bitcoin::secp256k1::Signing + bitcoin::secp256k1::Verification>(&self, idx: u64, _secp_ctx: &bitcoin::secp256k1::Secp256k1<T>) -> bitcoin::secp256k1::key::PublicKey {
                let mut ret = (self.get_per_commitment_point)(self.this_arg, idx);
                ret.into_rust()
@@ -409,60 +613,52 @@ impl rustChannelKeys for ChannelKeys {
                }
                unsafe { &*self.pubkeys.inner }
        }
-       fn key_derivation_params(&self) -> (u64, u64) {
-               let mut ret = (self.key_derivation_params)(self.this_arg);
-               let (mut orig_ret_0, mut orig_ret_1) = ret.to_rust(); let mut local_ret = (orig_ret_0, orig_ret_1);
-               local_ret
-       }
-       fn sign_counterparty_commitment<T:bitcoin::secp256k1::Signing + bitcoin::secp256k1::Verification>(&self, feerate_per_kw: u32, commitment_tx: &bitcoin::blockdata::transaction::Transaction, keys: &lightning::ln::chan_utils::PreCalculatedTxCreationKeys, htlcs: &[&lightning::ln::chan_utils::HTLCOutputInCommitment], _secp_ctx: &bitcoin::secp256k1::Secp256k1<T>) -> Result<(bitcoin::secp256k1::Signature, Vec<bitcoin::secp256k1::Signature>), ()> {
-               let mut local_commitment_tx = ::bitcoin::consensus::encode::serialize(commitment_tx);
-               let mut local_htlcs = Vec::new(); for item in htlcs.iter() { local_htlcs.push( { crate::ln::chan_utils::HTLCOutputInCommitment { inner: unsafe { ( (&(**item) as *const _) as *mut _) }, is_owned: false } }); };
-               let mut ret = (self.sign_counterparty_commitment)(self.this_arg, feerate_per_kw, crate::c_types::Transaction::from_vec(local_commitment_tx), &crate::ln::chan_utils::PreCalculatedTxCreationKeys { inner: unsafe { (keys as *const _) as *mut _ }, is_owned: false }, local_htlcs.into());
-               let mut local_ret = match ret.result_ok { true => Ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = (*unsafe { Box::from_raw(ret.contents.result.take_ptr()) }).to_rust(); let mut local_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.into_rust().drain(..) { local_orig_ret_0_1.push( { item.into_rust() }); }; let mut local_ret_0 = (orig_ret_0_0.into_rust(), local_orig_ret_0_1); local_ret_0 }), false => Err( { () /*(*unsafe { Box::from_raw(ret.contents.err.take_ptr()) })*/ })};
-               local_ret
+       fn channel_keys_id(&self) -> [u8; 32] {
+               let mut ret = (self.channel_keys_id)(self.this_arg);
+               ret.data
        }
-       fn sign_holder_commitment<T:bitcoin::secp256k1::Signing + bitcoin::secp256k1::Verification>(&self, holder_commitment_tx: &lightning::ln::chan_utils::HolderCommitmentTransaction, _secp_ctx: &bitcoin::secp256k1::Secp256k1<T>) -> Result<bitcoin::secp256k1::Signature, ()> {
-               let mut ret = (self.sign_holder_commitment)(self.this_arg, &crate::ln::chan_utils::HolderCommitmentTransaction { inner: unsafe { (holder_commitment_tx as *const _) as *mut _ }, is_owned: false });
-               let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(ret.contents.result.take_ptr()) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(ret.contents.err.take_ptr()) })*/ })};
+       fn sign_counterparty_commitment<T:bitcoin::secp256k1::Signing + bitcoin::secp256k1::Verification>(&self, commitment_tx: &lightning::ln::chan_utils::CommitmentTransaction, _secp_ctx: &bitcoin::secp256k1::Secp256k1<T>) -> Result<(bitcoin::secp256k1::Signature, Vec<bitcoin::secp256k1::Signature>), ()> {
+               let mut ret = (self.sign_counterparty_commitment)(self.this_arg, &crate::ln::chan_utils::CommitmentTransaction { inner: unsafe { (commitment_tx as *const _) as *mut _ }, is_owned: false });
+               let mut local_ret = match ret.result_ok { true => Ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).to_rust(); let mut local_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.into_rust().drain(..) { local_orig_ret_0_1.push( { item.into_rust() }); }; let mut local_ret_0 = (orig_ret_0_0.into_rust(), local_orig_ret_0_1); local_ret_0 }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })};
                local_ret
        }
-       fn sign_holder_commitment_htlc_transactions<T:bitcoin::secp256k1::Signing + bitcoin::secp256k1::Verification>(&self, holder_commitment_tx: &lightning::ln::chan_utils::HolderCommitmentTransaction, _secp_ctx: &bitcoin::secp256k1::Secp256k1<T>) -> Result<Vec<Option<bitcoin::secp256k1::Signature>>, ()> {
-               let mut ret = (self.sign_holder_commitment_htlc_transactions)(self.this_arg, &crate::ln::chan_utils::HolderCommitmentTransaction { inner: unsafe { (holder_commitment_tx as *const _) as *mut _ }, is_owned: false });
-               let mut local_ret = match ret.result_ok { true => Ok( { let mut local_ret_0 = Vec::new(); for mut item in (*unsafe { Box::from_raw(ret.contents.result.take_ptr()) }).into_rust().drain(..) { local_ret_0.push( { let mut local_ret_0_0 = if item.is_null() { None } else { Some( { item.into_rust() }) }; local_ret_0_0 }); }; local_ret_0 }), false => Err( { () /*(*unsafe { Box::from_raw(ret.contents.err.take_ptr()) })*/ })};
+       fn sign_holder_commitment_and_htlcs<T:bitcoin::secp256k1::Signing + bitcoin::secp256k1::Verification>(&self, commitment_tx: &lightning::ln::chan_utils::HolderCommitmentTransaction, _secp_ctx: &bitcoin::secp256k1::Secp256k1<T>) -> Result<(bitcoin::secp256k1::Signature, Vec<bitcoin::secp256k1::Signature>), ()> {
+               let mut ret = (self.sign_holder_commitment_and_htlcs)(self.this_arg, &crate::ln::chan_utils::HolderCommitmentTransaction { inner: unsafe { (commitment_tx as *const _) as *mut _ }, is_owned: false });
+               let mut local_ret = match ret.result_ok { true => Ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).to_rust(); let mut local_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.into_rust().drain(..) { local_orig_ret_0_1.push( { item.into_rust() }); }; let mut local_ret_0 = (orig_ret_0_0.into_rust(), local_orig_ret_0_1); local_ret_0 }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })};
                local_ret
        }
        fn sign_justice_transaction<T:bitcoin::secp256k1::Signing + bitcoin::secp256k1::Verification>(&self, justice_tx: &bitcoin::blockdata::transaction::Transaction, input: usize, amount: u64, per_commitment_key: &bitcoin::secp256k1::key::SecretKey, htlc: &Option<lightning::ln::chan_utils::HTLCOutputInCommitment>, _secp_ctx: &bitcoin::secp256k1::Secp256k1<T>) -> Result<bitcoin::secp256k1::Signature, ()> {
                let mut local_justice_tx = ::bitcoin::consensus::encode::serialize(justice_tx);
                let mut local_htlc = &crate::ln::chan_utils::HTLCOutputInCommitment { inner: unsafe { (if htlc.is_none() { std::ptr::null() } else {  { (htlc.as_ref().unwrap()) } } as *const _) as *mut _ }, is_owned: false };
                let mut ret = (self.sign_justice_transaction)(self.this_arg, crate::c_types::Transaction::from_vec(local_justice_tx), input, amount, per_commitment_key.as_ref(), local_htlc);
-               let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(ret.contents.result.take_ptr()) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(ret.contents.err.take_ptr()) })*/ })};
+               let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })};
                local_ret
        }
        fn sign_counterparty_htlc_transaction<T:bitcoin::secp256k1::Signing + bitcoin::secp256k1::Verification>(&self, htlc_tx: &bitcoin::blockdata::transaction::Transaction, input: usize, amount: u64, per_commitment_point: &bitcoin::secp256k1::key::PublicKey, htlc: &lightning::ln::chan_utils::HTLCOutputInCommitment, _secp_ctx: &bitcoin::secp256k1::Secp256k1<T>) -> Result<bitcoin::secp256k1::Signature, ()> {
                let mut local_htlc_tx = ::bitcoin::consensus::encode::serialize(htlc_tx);
                let mut ret = (self.sign_counterparty_htlc_transaction)(self.this_arg, crate::c_types::Transaction::from_vec(local_htlc_tx), input, amount, crate::c_types::PublicKey::from_rust(&per_commitment_point), &crate::ln::chan_utils::HTLCOutputInCommitment { inner: unsafe { (htlc as *const _) as *mut _ }, is_owned: false });
-               let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(ret.contents.result.take_ptr()) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(ret.contents.err.take_ptr()) })*/ })};
+               let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })};
                local_ret
        }
        fn sign_closing_transaction<T:bitcoin::secp256k1::Signing>(&self, closing_tx: &bitcoin::blockdata::transaction::Transaction, _secp_ctx: &bitcoin::secp256k1::Secp256k1<T>) -> Result<bitcoin::secp256k1::Signature, ()> {
                let mut local_closing_tx = ::bitcoin::consensus::encode::serialize(closing_tx);
                let mut ret = (self.sign_closing_transaction)(self.this_arg, crate::c_types::Transaction::from_vec(local_closing_tx));
-               let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(ret.contents.result.take_ptr()) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(ret.contents.err.take_ptr()) })*/ })};
+               let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })};
                local_ret
        }
        fn sign_channel_announcement<T:bitcoin::secp256k1::Signing>(&self, msg: &lightning::ln::msgs::UnsignedChannelAnnouncement, _secp_ctx: &bitcoin::secp256k1::Secp256k1<T>) -> Result<bitcoin::secp256k1::Signature, ()> {
                let mut ret = (self.sign_channel_announcement)(self.this_arg, &crate::ln::msgs::UnsignedChannelAnnouncement { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false });
-               let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(ret.contents.result.take_ptr()) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(ret.contents.err.take_ptr()) })*/ })};
+               let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })};
                local_ret
        }
-       fn on_accept(&mut self, channel_points: &lightning::ln::chan_utils::ChannelPublicKeys, counterparty_selected_contest_delay: u16, holder_selected_contest_delay: u16) {
-               (self.on_accept)(self.this_arg, &crate::ln::chan_utils::ChannelPublicKeys { inner: unsafe { (channel_points as *const _) as *mut _ }, is_owned: false }, counterparty_selected_contest_delay, holder_selected_contest_delay)
+       fn ready_channel(&mut self, channel_parameters: &lightning::ln::chan_utils::ChannelTransactionParameters) {
+               (self.ready_channel)(self.this_arg, &crate::ln::chan_utils::ChannelTransactionParameters { inner: unsafe { (channel_parameters as *const _) as *mut _ }, is_owned: false })
        }
 }
 
 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
 // directly as a Deref trait in higher-level structs:
-impl std::ops::Deref for ChannelKeys {
+impl std::ops::Deref for Sign {
        type Target = Self;
        fn deref(&self) -> &Self {
                self
@@ -470,8 +666,8 @@ impl std::ops::Deref for ChannelKeys {
 }
 /// Calls the free function if one is set
 #[no_mangle]
-pub extern "C" fn ChannelKeys_free(this_ptr: ChannelKeys) { }
-impl Drop for ChannelKeys {
+pub extern "C" fn Sign_free(this_ptr: Sign) { }
+impl Drop for Sign {
        fn drop(&mut self) {
                if let Some(f) = self.free {
                        f(self.this_arg);
@@ -482,24 +678,45 @@ impl Drop for ChannelKeys {
 #[repr(C)]
 pub struct KeysInterface {
        pub this_arg: *mut c_void,
-       /// Get node secret key (aka node_id or network_key)
+       /// Get node secret key (aka node_id or network_key).
+       ///
+       /// This method must return the same value each time it is called.
        #[must_use]
        pub get_node_secret: extern "C" fn (this_arg: *const c_void) -> crate::c_types::SecretKey,
-       /// Get destination redeemScript to encumber static protocol exit points.
+       /// Get a script pubkey which we send funds to when claiming on-chain contestable outputs.
+       ///
+       /// This method should return a different value each time it is called, to avoid linking
+       /// on-chain funds across channels as controlled to the same user.
        #[must_use]
        pub get_destination_script: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_u8Z,
-       /// Get shutdown_pubkey to use as PublicKey at channel closure
+       /// Get a public key which we will send funds to (in the form of a P2WPKH output) when closing
+       /// a channel.
+       ///
+       /// This method should return a different value each time it is called, to avoid linking
+       /// on-chain funds across channels as controlled to the same user.
        #[must_use]
        pub get_shutdown_pubkey: extern "C" fn (this_arg: *const c_void) -> crate::c_types::PublicKey,
-       /// Get a new set of ChannelKeys for per-channel secrets. These MUST be unique even if you
+       /// Get a new set of Sign for per-channel secrets. These MUST be unique even if you
        /// restarted with some stale data!
+       ///
+       /// This method must return a different value each time it is called.
        #[must_use]
-       pub get_channel_keys: extern "C" fn (this_arg: *const c_void, inbound: bool, channel_value_satoshis: u64) -> crate::chain::keysinterface::ChannelKeys,
+       pub get_channel_signer: extern "C" fn (this_arg: *const c_void, inbound: bool, channel_value_satoshis: u64) -> crate::chain::keysinterface::Sign,
        /// Gets a unique, cryptographically-secure, random 32 byte value. This is used for encrypting
        /// onion packets and for temporary channel IDs. There is no requirement that these be
        /// persisted anywhere, though they must be unique across restarts.
+       ///
+       /// This method must return a different value each time it is called.
        #[must_use]
        pub get_secure_random_bytes: extern "C" fn (this_arg: *const c_void) -> crate::c_types::ThirtyTwoBytes,
+       /// Reads a `Signer` for this `KeysInterface` from the given input stream.
+       /// This is only called during deserialization of other objects which contain
+       /// `Sign`-implementing objects (ie `ChannelMonitor`s and `ChannelManager`s).
+       /// The bytes are exactly those which `<Self::Signer as Writeable>::write()` writes, and
+       /// contain no versioning scheme. You may wish to include your own version prefix and ensure
+       /// you've read all of the provided bytes to ensure no corruption occurred.
+       #[must_use]
+       pub read_chan_signer: extern "C" fn (this_arg: *const c_void, reader: crate::c_types::u8slice) -> crate::c_types::derived::CResult_SignDecodeErrorZ,
        pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
 }
 unsafe impl Send for KeysInterface {}
@@ -507,7 +724,7 @@ unsafe impl Sync for KeysInterface {}
 
 use lightning::chain::keysinterface::KeysInterface as rustKeysInterface;
 impl rustKeysInterface for KeysInterface {
-       type ChanKeySigner = crate::chain::keysinterface::ChannelKeys;
+       type Signer = crate::chain::keysinterface::Sign;
        fn get_node_secret(&self) -> bitcoin::secp256k1::key::SecretKey {
                let mut ret = (self.get_node_secret)(self.this_arg);
                ret.into_rust()
@@ -520,14 +737,20 @@ impl rustKeysInterface for KeysInterface {
                let mut ret = (self.get_shutdown_pubkey)(self.this_arg);
                ret.into_rust()
        }
-       fn get_channel_keys(&self, inbound: bool, channel_value_satoshis: u64) -> Self::ChanKeySigner {
-               let mut ret = (self.get_channel_keys)(self.this_arg, inbound, channel_value_satoshis);
+       fn get_channel_signer(&self, inbound: bool, channel_value_satoshis: u64) -> crate::chain::keysinterface::Sign {
+               let mut ret = (self.get_channel_signer)(self.this_arg, inbound, channel_value_satoshis);
                ret
        }
        fn get_secure_random_bytes(&self) -> [u8; 32] {
                let mut ret = (self.get_secure_random_bytes)(self.this_arg);
                ret.data
        }
+       fn read_chan_signer(&self, reader: &[u8]) -> Result<crate::chain::keysinterface::Sign, lightning::ln::msgs::DecodeError> {
+               let mut local_reader = crate::c_types::u8slice::from_slice(reader);
+               let mut ret = (self.read_chan_signer)(self.this_arg, local_reader);
+               let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }) }), false => Err( { *unsafe { Box::from_raw((*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).take_inner()) } })};
+               local_ret
+       }
 }
 
 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
@@ -549,20 +772,23 @@ impl Drop for KeysInterface {
        }
 }
 
-use lightning::chain::keysinterface::InMemoryChannelKeys as nativeInMemoryChannelKeysImport;
-type nativeInMemoryChannelKeys = nativeInMemoryChannelKeysImport;
+use lightning::chain::keysinterface::InMemorySigner as nativeInMemorySignerImport;
+type nativeInMemorySigner = nativeInMemorySignerImport;
 
-/// A simple implementation of ChannelKeys that just keeps the private keys in memory.
+/// A simple implementation of Sign that just keeps the private keys in memory.
+///
+/// This implementation performs no policy checks and is insufficient by itself as
+/// a secure external signer.
 #[must_use]
 #[repr(C)]
-pub struct InMemoryChannelKeys {
+pub struct InMemorySigner {
        /// Nearly everywhere, inner must be non-null, however in places where
        /// the Rust equivalent takes an Option, it may be set to null to indicate None.
-       pub inner: *mut nativeInMemoryChannelKeys,
+       pub inner: *mut nativeInMemorySigner,
        pub is_owned: bool,
 }
 
-impl Drop for InMemoryChannelKeys {
+impl Drop for InMemorySigner {
        fn drop(&mut self) {
                if self.is_owned && !self.inner.is_null() {
                        let _ = unsafe { Box::from_raw(self.inner) };
@@ -570,131 +796,130 @@ impl Drop for InMemoryChannelKeys {
        }
 }
 #[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_free(this_ptr: InMemoryChannelKeys) { }
+pub extern "C" fn InMemorySigner_free(this_ptr: InMemorySigner) { }
 #[allow(unused)]
 /// Used only if an object of this type is returned as a trait impl by a method
-extern "C" fn InMemoryChannelKeys_free_void(this_ptr: *mut c_void) {
-       unsafe { let _ = Box::from_raw(this_ptr as *mut nativeInMemoryChannelKeys); }
+extern "C" fn InMemorySigner_free_void(this_ptr: *mut c_void) {
+       unsafe { let _ = Box::from_raw(this_ptr as *mut nativeInMemorySigner); }
 }
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
-impl InMemoryChannelKeys {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeInMemoryChannelKeys {
+impl InMemorySigner {
+       pub(crate) fn take_inner(mut self) -> *mut nativeInMemorySigner {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for InMemoryChannelKeys {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn InMemoryChannelKeys_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeInMemoryChannelKeys)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_clone(orig: &InMemoryChannelKeys) -> InMemoryChannelKeys {
-       InMemoryChannelKeys { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// Private key of anchor tx
 #[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_get_funding_key(this_ptr: &InMemoryChannelKeys) -> *const [u8; 32] {
+pub extern "C" fn InMemorySigner_get_funding_key(this_ptr: &InMemorySigner) -> *const [u8; 32] {
        let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.funding_key;
        (*inner_val).as_ref()
 }
 /// Private key of anchor tx
 #[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_set_funding_key(this_ptr: &mut InMemoryChannelKeys, mut val: crate::c_types::SecretKey) {
+pub extern "C" fn InMemorySigner_set_funding_key(this_ptr: &mut InMemorySigner, mut val: crate::c_types::SecretKey) {
        unsafe { &mut *this_ptr.inner }.funding_key = val.into_rust();
 }
 /// Holder secret key for blinded revocation pubkey
 #[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_get_revocation_base_key(this_ptr: &InMemoryChannelKeys) -> *const [u8; 32] {
+pub extern "C" fn InMemorySigner_get_revocation_base_key(this_ptr: &InMemorySigner) -> *const [u8; 32] {
        let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.revocation_base_key;
        (*inner_val).as_ref()
 }
 /// Holder secret key for blinded revocation pubkey
 #[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_set_revocation_base_key(this_ptr: &mut InMemoryChannelKeys, mut val: crate::c_types::SecretKey) {
+pub extern "C" fn InMemorySigner_set_revocation_base_key(this_ptr: &mut InMemorySigner, mut val: crate::c_types::SecretKey) {
        unsafe { &mut *this_ptr.inner }.revocation_base_key = val.into_rust();
 }
 /// Holder secret key used for our balance in counterparty-broadcasted commitment transactions
 #[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_get_payment_key(this_ptr: &InMemoryChannelKeys) -> *const [u8; 32] {
+pub extern "C" fn InMemorySigner_get_payment_key(this_ptr: &InMemorySigner) -> *const [u8; 32] {
        let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.payment_key;
        (*inner_val).as_ref()
 }
 /// Holder secret key used for our balance in counterparty-broadcasted commitment transactions
 #[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_set_payment_key(this_ptr: &mut InMemoryChannelKeys, mut val: crate::c_types::SecretKey) {
+pub extern "C" fn InMemorySigner_set_payment_key(this_ptr: &mut InMemorySigner, mut val: crate::c_types::SecretKey) {
        unsafe { &mut *this_ptr.inner }.payment_key = val.into_rust();
 }
 /// Holder secret key used in HTLC tx
 #[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_get_delayed_payment_base_key(this_ptr: &InMemoryChannelKeys) -> *const [u8; 32] {
+pub extern "C" fn InMemorySigner_get_delayed_payment_base_key(this_ptr: &InMemorySigner) -> *const [u8; 32] {
        let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.delayed_payment_base_key;
        (*inner_val).as_ref()
 }
 /// Holder secret key used in HTLC tx
 #[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_set_delayed_payment_base_key(this_ptr: &mut InMemoryChannelKeys, mut val: crate::c_types::SecretKey) {
+pub extern "C" fn InMemorySigner_set_delayed_payment_base_key(this_ptr: &mut InMemorySigner, mut val: crate::c_types::SecretKey) {
        unsafe { &mut *this_ptr.inner }.delayed_payment_base_key = val.into_rust();
 }
 /// Holder htlc secret key used in commitment tx htlc outputs
 #[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_get_htlc_base_key(this_ptr: &InMemoryChannelKeys) -> *const [u8; 32] {
+pub extern "C" fn InMemorySigner_get_htlc_base_key(this_ptr: &InMemorySigner) -> *const [u8; 32] {
        let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.htlc_base_key;
        (*inner_val).as_ref()
 }
 /// Holder htlc secret key used in commitment tx htlc outputs
 #[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_set_htlc_base_key(this_ptr: &mut InMemoryChannelKeys, mut val: crate::c_types::SecretKey) {
+pub extern "C" fn InMemorySigner_set_htlc_base_key(this_ptr: &mut InMemorySigner, mut val: crate::c_types::SecretKey) {
        unsafe { &mut *this_ptr.inner }.htlc_base_key = val.into_rust();
 }
 /// Commitment seed
 #[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_get_commitment_seed(this_ptr: &InMemoryChannelKeys) -> *const [u8; 32] {
+pub extern "C" fn InMemorySigner_get_commitment_seed(this_ptr: &InMemorySigner) -> *const [u8; 32] {
        let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.commitment_seed;
        &(*inner_val)
 }
 /// Commitment seed
 #[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_set_commitment_seed(this_ptr: &mut InMemoryChannelKeys, mut val: crate::c_types::ThirtyTwoBytes) {
+pub extern "C" fn InMemorySigner_set_commitment_seed(this_ptr: &mut InMemorySigner, mut val: crate::c_types::ThirtyTwoBytes) {
        unsafe { &mut *this_ptr.inner }.commitment_seed = val.data;
 }
-/// Create a new InMemoryChannelKeys
+impl Clone for InMemorySigner {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn InMemorySigner_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeInMemorySigner)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn InMemorySigner_clone(orig: &InMemorySigner) -> InMemorySigner {
+       orig.clone()
+}
+/// Create a new InMemorySigner
 #[must_use]
 #[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_new(mut funding_key: crate::c_types::SecretKey, mut revocation_base_key: crate::c_types::SecretKey, mut payment_key: crate::c_types::SecretKey, mut delayed_payment_base_key: crate::c_types::SecretKey, mut htlc_base_key: crate::c_types::SecretKey, mut commitment_seed: crate::c_types::ThirtyTwoBytes, mut channel_value_satoshis: u64, mut key_derivation_params: crate::c_types::derived::C2Tuple_u64u64Z) -> crate::chain::keysinterface::InMemoryChannelKeys {
-       let (mut orig_key_derivation_params_0, mut orig_key_derivation_params_1) = key_derivation_params.to_rust(); let mut local_key_derivation_params = (orig_key_derivation_params_0, orig_key_derivation_params_1);
-       let mut ret = lightning::chain::keysinterface::InMemoryChannelKeys::new(&bitcoin::secp256k1::Secp256k1::new(), funding_key.into_rust(), revocation_base_key.into_rust(), payment_key.into_rust(), delayed_payment_base_key.into_rust(), htlc_base_key.into_rust(), commitment_seed.data, channel_value_satoshis, local_key_derivation_params);
-       crate::chain::keysinterface::InMemoryChannelKeys { inner: Box::into_raw(Box::new(ret)), is_owned: true }
+pub extern "C" fn InMemorySigner_new(mut funding_key: crate::c_types::SecretKey, mut revocation_base_key: crate::c_types::SecretKey, mut payment_key: crate::c_types::SecretKey, mut delayed_payment_base_key: crate::c_types::SecretKey, mut htlc_base_key: crate::c_types::SecretKey, mut commitment_seed: crate::c_types::ThirtyTwoBytes, mut channel_value_satoshis: u64, mut channel_keys_id: crate::c_types::ThirtyTwoBytes) -> crate::chain::keysinterface::InMemorySigner {
+       let mut ret = lightning::chain::keysinterface::InMemorySigner::new(secp256k1::SECP256K1, funding_key.into_rust(), revocation_base_key.into_rust(), payment_key.into_rust(), delayed_payment_base_key.into_rust(), htlc_base_key.into_rust(), commitment_seed.data, channel_value_satoshis, channel_keys_id.data);
+       crate::chain::keysinterface::InMemorySigner { inner: Box::into_raw(Box::new(ret)), is_owned: true }
 }
 
 /// Counterparty pubkeys.
-/// Will panic if on_accept wasn't called.
+/// Will panic if ready_channel wasn't called.
 #[must_use]
 #[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_counterparty_pubkeys(this_arg: &InMemoryChannelKeys) -> crate::ln::chan_utils::ChannelPublicKeys {
+pub extern "C" fn InMemorySigner_counterparty_pubkeys(this_arg: &InMemorySigner) -> crate::ln::chan_utils::ChannelPublicKeys {
        let mut ret = unsafe { &*this_arg.inner }.counterparty_pubkeys();
        crate::ln::chan_utils::ChannelPublicKeys { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false }
 }
 
 /// The contest_delay value specified by our counterparty and applied on holder-broadcastable
 /// transactions, ie the amount of time that we have to wait to recover our funds if we
-/// broadcast a transaction. You'll likely want to pass this to the
-/// ln::chan_utils::build*_transaction functions when signing holder's transactions.
-/// Will panic if on_accept wasn't called.
+/// broadcast a transaction.
+/// Will panic if ready_channel wasn't called.
 #[must_use]
 #[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_counterparty_selected_contest_delay(this_arg: &InMemoryChannelKeys) -> u16 {
+pub extern "C" fn InMemorySigner_counterparty_selected_contest_delay(this_arg: &InMemorySigner) -> u16 {
        let mut ret = unsafe { &*this_arg.inner }.counterparty_selected_contest_delay();
        ret
 }
@@ -702,124 +927,184 @@ pub extern "C" fn InMemoryChannelKeys_counterparty_selected_contest_delay(this_a
 /// The contest_delay value specified by us and applied on transactions broadcastable
 /// by our counterparty, ie the amount of time that they have to wait to recover their funds
 /// if they broadcast a transaction.
-/// Will panic if on_accept wasn't called.
+/// Will panic if ready_channel wasn't called.
 #[must_use]
 #[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_holder_selected_contest_delay(this_arg: &InMemoryChannelKeys) -> u16 {
+pub extern "C" fn InMemorySigner_holder_selected_contest_delay(this_arg: &InMemorySigner) -> u16 {
        let mut ret = unsafe { &*this_arg.inner }.holder_selected_contest_delay();
        ret
 }
 
+/// Whether the holder is the initiator
+/// Will panic if ready_channel wasn't called.
+#[must_use]
 #[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_as_ChannelKeys(this_arg: *const InMemoryChannelKeys) -> crate::chain::keysinterface::ChannelKeys {
-       crate::chain::keysinterface::ChannelKeys {
+pub extern "C" fn InMemorySigner_is_outbound(this_arg: &InMemorySigner) -> bool {
+       let mut ret = unsafe { &*this_arg.inner }.is_outbound();
+       ret
+}
+
+/// Funding outpoint
+/// Will panic if ready_channel wasn't called.
+#[must_use]
+#[no_mangle]
+pub extern "C" fn InMemorySigner_funding_outpoint(this_arg: &InMemorySigner) -> crate::chain::transaction::OutPoint {
+       let mut ret = unsafe { &*this_arg.inner }.funding_outpoint();
+       crate::chain::transaction::OutPoint { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false }
+}
+
+/// Obtain a ChannelTransactionParameters for this channel, to be used when verifying or
+/// building transactions.
+///
+/// Will panic if ready_channel wasn't called.
+#[must_use]
+#[no_mangle]
+pub extern "C" fn InMemorySigner_get_channel_parameters(this_arg: &InMemorySigner) -> crate::ln::chan_utils::ChannelTransactionParameters {
+       let mut ret = unsafe { &*this_arg.inner }.get_channel_parameters();
+       crate::ln::chan_utils::ChannelTransactionParameters { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false }
+}
+
+/// Sign the single input of spend_tx at index `input_idx` which spends the output
+/// described by descriptor, returning the witness stack for the input.
+///
+/// Returns an Err if the input at input_idx does not exist, has a non-empty script_sig,
+/// or is not spending the outpoint described by `descriptor.outpoint`.
+#[must_use]
+#[no_mangle]
+pub extern "C" fn InMemorySigner_sign_counterparty_payment_input(this_arg: &InMemorySigner, mut spend_tx: crate::c_types::Transaction, mut input_idx: usize, descriptor: &crate::chain::keysinterface::StaticPaymentOutputDescriptor) -> crate::c_types::derived::CResult_CVec_CVec_u8ZZNoneZ {
+       let mut ret = unsafe { &*this_arg.inner }.sign_counterparty_payment_input(&spend_tx.into_bitcoin(), input_idx, unsafe { &*descriptor.inner }, secp256k1::SECP256K1);
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let mut local_ret_0 = Vec::new(); for mut item in o.drain(..) { local_ret_0.push( { let mut local_ret_0_0 = Vec::new(); for mut item in item.drain(..) { local_ret_0_0.push( { item }); }; local_ret_0_0.into() }); }; local_ret_0.into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }).into() };
+       local_ret
+}
+
+/// Sign the single input of spend_tx at index `input_idx` which spends the output
+/// described by descriptor, returning the witness stack for the input.
+///
+/// Returns an Err if the input at input_idx does not exist, has a non-empty script_sig,
+/// is not spending the outpoint described by `descriptor.outpoint`, or does not have a
+/// sequence set to `descriptor.to_self_delay`.
+#[must_use]
+#[no_mangle]
+pub extern "C" fn InMemorySigner_sign_dynamic_p2wsh_input(this_arg: &InMemorySigner, mut spend_tx: crate::c_types::Transaction, mut input_idx: usize, descriptor: &crate::chain::keysinterface::DelayedPaymentOutputDescriptor) -> crate::c_types::derived::CResult_CVec_CVec_u8ZZNoneZ {
+       let mut ret = unsafe { &*this_arg.inner }.sign_dynamic_p2wsh_input(&spend_tx.into_bitcoin(), input_idx, unsafe { &*descriptor.inner }, secp256k1::SECP256K1);
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let mut local_ret_0 = Vec::new(); for mut item in o.drain(..) { local_ret_0.push( { let mut local_ret_0_0 = Vec::new(); for mut item in item.drain(..) { local_ret_0_0.push( { item }); }; local_ret_0_0.into() }); }; local_ret_0.into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }).into() };
+       local_ret
+}
+
+impl From<nativeInMemorySigner> for crate::chain::keysinterface::Sign {
+       fn from(obj: nativeInMemorySigner) -> Self {
+               let mut rust_obj = InMemorySigner { inner: Box::into_raw(Box::new(obj)), is_owned: true };
+               let mut ret = InMemorySigner_as_Sign(&rust_obj);
+               // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
+               rust_obj.inner = std::ptr::null_mut();
+               ret.free = Some(InMemorySigner_free_void);
+               ret
+       }
+}
+#[no_mangle]
+pub extern "C" fn InMemorySigner_as_Sign(this_arg: &InMemorySigner) -> crate::chain::keysinterface::Sign {
+       crate::chain::keysinterface::Sign {
                this_arg: unsafe { (*this_arg).inner as *mut c_void },
                free: None,
-               get_per_commitment_point: InMemoryChannelKeys_ChannelKeys_get_per_commitment_point,
-               release_commitment_secret: InMemoryChannelKeys_ChannelKeys_release_commitment_secret,
+               get_per_commitment_point: InMemorySigner_Sign_get_per_commitment_point,
+               release_commitment_secret: InMemorySigner_Sign_release_commitment_secret,
 
                pubkeys: crate::ln::chan_utils::ChannelPublicKeys { inner: std::ptr::null_mut(), is_owned: true },
-               set_pubkeys: Some(InMemoryChannelKeys_ChannelKeys_set_pubkeys),
-               key_derivation_params: InMemoryChannelKeys_ChannelKeys_key_derivation_params,
-               sign_counterparty_commitment: InMemoryChannelKeys_ChannelKeys_sign_counterparty_commitment,
-               sign_holder_commitment: InMemoryChannelKeys_ChannelKeys_sign_holder_commitment,
-               sign_holder_commitment_htlc_transactions: InMemoryChannelKeys_ChannelKeys_sign_holder_commitment_htlc_transactions,
-               sign_justice_transaction: InMemoryChannelKeys_ChannelKeys_sign_justice_transaction,
-               sign_counterparty_htlc_transaction: InMemoryChannelKeys_ChannelKeys_sign_counterparty_htlc_transaction,
-               sign_closing_transaction: InMemoryChannelKeys_ChannelKeys_sign_closing_transaction,
-               sign_channel_announcement: InMemoryChannelKeys_ChannelKeys_sign_channel_announcement,
-               on_accept: InMemoryChannelKeys_ChannelKeys_on_accept,
-               clone: Some(InMemoryChannelKeys_clone_void),
-       }
-}
-use lightning::chain::keysinterface::ChannelKeys as ChannelKeysTraitImport;
-#[must_use]
-extern "C" fn InMemoryChannelKeys_ChannelKeys_get_per_commitment_point(this_arg: *const c_void, mut idx: u64) -> crate::c_types::PublicKey {
-       let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemoryChannelKeys) }.get_per_commitment_point(idx, &bitcoin::secp256k1::Secp256k1::new());
+               set_pubkeys: Some(InMemorySigner_Sign_set_pubkeys),
+               channel_keys_id: InMemorySigner_Sign_channel_keys_id,
+               sign_counterparty_commitment: InMemorySigner_Sign_sign_counterparty_commitment,
+               sign_holder_commitment_and_htlcs: InMemorySigner_Sign_sign_holder_commitment_and_htlcs,
+               sign_justice_transaction: InMemorySigner_Sign_sign_justice_transaction,
+               sign_counterparty_htlc_transaction: InMemorySigner_Sign_sign_counterparty_htlc_transaction,
+               sign_closing_transaction: InMemorySigner_Sign_sign_closing_transaction,
+               sign_channel_announcement: InMemorySigner_Sign_sign_channel_announcement,
+               ready_channel: InMemorySigner_Sign_ready_channel,
+               clone: Some(InMemorySigner_clone_void),
+               write: InMemorySigner_write_void,
+       }
+}
+use lightning::chain::keysinterface::Sign as SignTraitImport;
+#[must_use]
+extern "C" fn InMemorySigner_Sign_get_per_commitment_point(this_arg: *const c_void, mut idx: u64) -> crate::c_types::PublicKey {
+       let mut ret = <nativeInMemorySigner as SignTraitImport<>>::get_per_commitment_point(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, idx, secp256k1::SECP256K1);
        crate::c_types::PublicKey::from_rust(&ret)
 }
 #[must_use]
-extern "C" fn InMemoryChannelKeys_ChannelKeys_release_commitment_secret(this_arg: *const c_void, mut idx: u64) -> crate::c_types::ThirtyTwoBytes {
-       let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemoryChannelKeys) }.release_commitment_secret(idx);
+extern "C" fn InMemorySigner_Sign_release_commitment_secret(this_arg: *const c_void, mut idx: u64) -> crate::c_types::ThirtyTwoBytes {
+       let mut ret = <nativeInMemorySigner as SignTraitImport<>>::release_commitment_secret(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, idx);
        crate::c_types::ThirtyTwoBytes { data: ret }
 }
 #[must_use]
-extern "C" fn InMemoryChannelKeys_ChannelKeys_pubkeys(this_arg: *const c_void) -> crate::ln::chan_utils::ChannelPublicKeys {
-       let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemoryChannelKeys) }.pubkeys();
+extern "C" fn InMemorySigner_Sign_pubkeys(this_arg: *const c_void) -> crate::ln::chan_utils::ChannelPublicKeys {
+       let mut ret = <nativeInMemorySigner as SignTraitImport<>>::pubkeys(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, );
        crate::ln::chan_utils::ChannelPublicKeys { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false }
 }
-extern "C" fn InMemoryChannelKeys_ChannelKeys_set_pubkeys(trait_self_arg: &ChannelKeys) {
+extern "C" fn InMemorySigner_Sign_set_pubkeys(trait_self_arg: &Sign) {
        // This is a bit race-y in the general case, but for our specific use-cases today, we're safe
        // Specifically, we must ensure that the first time we're called it can never be in parallel
        if trait_self_arg.pubkeys.inner.is_null() {
-               unsafe { &mut *(trait_self_arg as *const ChannelKeys  as *mut ChannelKeys) }.pubkeys = InMemoryChannelKeys_ChannelKeys_pubkeys(trait_self_arg.this_arg);
+               unsafe { &mut *(trait_self_arg as *const Sign  as *mut Sign) }.pubkeys = InMemorySigner_Sign_pubkeys(trait_self_arg.this_arg);
        }
 }
 #[must_use]
-extern "C" fn InMemoryChannelKeys_ChannelKeys_key_derivation_params(this_arg: *const c_void) -> crate::c_types::derived::C2Tuple_u64u64Z {
-       let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemoryChannelKeys) }.key_derivation_params();
-       let (mut orig_ret_0, mut orig_ret_1) = ret; let mut local_ret = (orig_ret_0, orig_ret_1).into();
-       local_ret
-}
-#[must_use]
-extern "C" fn InMemoryChannelKeys_ChannelKeys_sign_counterparty_commitment(this_arg: *const c_void, mut feerate_per_kw: u32, mut commitment_tx: crate::c_types::Transaction, pre_keys: &crate::ln::chan_utils::PreCalculatedTxCreationKeys, mut htlcs: crate::c_types::derived::CVec_HTLCOutputInCommitmentZ) -> crate::c_types::derived::CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ {
-       let mut local_htlcs = Vec::new(); for mut item in htlcs.as_slice().iter() { local_htlcs.push( { unsafe { &*item.inner } }); };
-       let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemoryChannelKeys) }.sign_counterparty_commitment(feerate_per_kw, &commitment_tx.into_bitcoin(), unsafe { &*pre_keys.inner }, &local_htlcs[..], &bitcoin::secp256k1::Secp256k1::new());
-       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = o; let mut local_orig_ret_0_1 = Vec::new(); for item in orig_ret_0_1.drain(..) { local_orig_ret_0_1.push( { crate::c_types::Signature::from_rust(&item) }); }; let mut local_ret_0 = (crate::c_types::Signature::from_rust(&orig_ret_0_0), local_orig_ret_0_1.into()).into(); local_ret_0 }), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }) };
-       local_ret
+extern "C" fn InMemorySigner_Sign_channel_keys_id(this_arg: *const c_void) -> crate::c_types::ThirtyTwoBytes {
+       let mut ret = <nativeInMemorySigner as SignTraitImport<>>::channel_keys_id(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, );
+       crate::c_types::ThirtyTwoBytes { data: ret }
 }
 #[must_use]
-extern "C" fn InMemoryChannelKeys_ChannelKeys_sign_holder_commitment(this_arg: *const c_void, holder_commitment_tx: &crate::ln::chan_utils::HolderCommitmentTransaction) -> crate::c_types::derived::CResult_SignatureNoneZ {
-       let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemoryChannelKeys) }.sign_holder_commitment(unsafe { &*holder_commitment_tx.inner }, &bitcoin::secp256k1::Secp256k1::new());
-       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Signature::from_rust(&o) }), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }) };
+extern "C" fn InMemorySigner_Sign_sign_counterparty_commitment(this_arg: *const c_void, commitment_tx: &crate::ln::chan_utils::CommitmentTransaction) -> crate::c_types::derived::CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ {
+       let mut ret = <nativeInMemorySigner as SignTraitImport<>>::sign_counterparty_commitment(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, unsafe { &*commitment_tx.inner }, secp256k1::SECP256K1);
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = o; let mut local_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.drain(..) { local_orig_ret_0_1.push( { crate::c_types::Signature::from_rust(&item) }); }; let mut local_ret_0 = (crate::c_types::Signature::from_rust(&orig_ret_0_0), local_orig_ret_0_1.into()).into(); local_ret_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }).into() };
        local_ret
 }
 #[must_use]
-extern "C" fn InMemoryChannelKeys_ChannelKeys_sign_holder_commitment_htlc_transactions(this_arg: *const c_void, holder_commitment_tx: &crate::ln::chan_utils::HolderCommitmentTransaction) -> crate::c_types::derived::CResult_CVec_SignatureZNoneZ {
-       let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemoryChannelKeys) }.sign_holder_commitment_htlc_transactions(unsafe { &*holder_commitment_tx.inner }, &bitcoin::secp256k1::Secp256k1::new());
-       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let mut local_ret_0 = Vec::new(); for item in o.drain(..) { local_ret_0.push( { let mut local_ret_0_0 = if item.is_none() { crate::c_types::Signature::null() } else {  { crate::c_types::Signature::from_rust(&(item.unwrap())) } }; local_ret_0_0 }); }; local_ret_0.into() }), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }) };
+extern "C" fn InMemorySigner_Sign_sign_holder_commitment_and_htlcs(this_arg: *const c_void, commitment_tx: &crate::ln::chan_utils::HolderCommitmentTransaction) -> crate::c_types::derived::CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ {
+       let mut ret = <nativeInMemorySigner as SignTraitImport<>>::sign_holder_commitment_and_htlcs(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, unsafe { &*commitment_tx.inner }, secp256k1::SECP256K1);
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = o; let mut local_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.drain(..) { local_orig_ret_0_1.push( { crate::c_types::Signature::from_rust(&item) }); }; let mut local_ret_0 = (crate::c_types::Signature::from_rust(&orig_ret_0_0), local_orig_ret_0_1.into()).into(); local_ret_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }).into() };
        local_ret
 }
 #[must_use]
-extern "C" fn InMemoryChannelKeys_ChannelKeys_sign_justice_transaction(this_arg: *const c_void, mut justice_tx: crate::c_types::Transaction, mut input: usize, mut amount: u64, per_commitment_key: *const [u8; 32], htlc: &crate::ln::chan_utils::HTLCOutputInCommitment) -> crate::c_types::derived::CResult_SignatureNoneZ {
+extern "C" fn InMemorySigner_Sign_sign_justice_transaction(this_arg: *const c_void, mut justice_tx: crate::c_types::Transaction, mut input: usize, mut amount: u64, per_commitment_key: *const [u8; 32], htlc: &crate::ln::chan_utils::HTLCOutputInCommitment) -> crate::c_types::derived::CResult_SignatureNoneZ {
        let mut local_htlc = if htlc.inner.is_null() { None } else { Some((* { unsafe { &*htlc.inner } }).clone()) };
-       let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemoryChannelKeys) }.sign_justice_transaction(&justice_tx.into_bitcoin(), input, amount, &::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *per_commitment_key}[..]).unwrap(), &local_htlc, &bitcoin::secp256k1::Secp256k1::new());
-       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Signature::from_rust(&o) }), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }) };
+       let mut ret = <nativeInMemorySigner as SignTraitImport<>>::sign_justice_transaction(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, &justice_tx.into_bitcoin(), input, amount, &::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *per_commitment_key}[..]).unwrap(), &local_htlc, secp256k1::SECP256K1);
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Signature::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }).into() };
        local_ret
 }
 #[must_use]
-extern "C" fn InMemoryChannelKeys_ChannelKeys_sign_counterparty_htlc_transaction(this_arg: *const c_void, mut htlc_tx: crate::c_types::Transaction, mut input: usize, mut amount: u64, mut per_commitment_point: crate::c_types::PublicKey, htlc: &crate::ln::chan_utils::HTLCOutputInCommitment) -> crate::c_types::derived::CResult_SignatureNoneZ {
-       let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemoryChannelKeys) }.sign_counterparty_htlc_transaction(&htlc_tx.into_bitcoin(), input, amount, &per_commitment_point.into_rust(), unsafe { &*htlc.inner }, &bitcoin::secp256k1::Secp256k1::new());
-       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Signature::from_rust(&o) }), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }) };
+extern "C" fn InMemorySigner_Sign_sign_counterparty_htlc_transaction(this_arg: *const c_void, mut htlc_tx: crate::c_types::Transaction, mut input: usize, mut amount: u64, mut per_commitment_point: crate::c_types::PublicKey, htlc: &crate::ln::chan_utils::HTLCOutputInCommitment) -> crate::c_types::derived::CResult_SignatureNoneZ {
+       let mut ret = <nativeInMemorySigner as SignTraitImport<>>::sign_counterparty_htlc_transaction(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, &htlc_tx.into_bitcoin(), input, amount, &per_commitment_point.into_rust(), unsafe { &*htlc.inner }, secp256k1::SECP256K1);
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Signature::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }).into() };
        local_ret
 }
 #[must_use]
-extern "C" fn InMemoryChannelKeys_ChannelKeys_sign_closing_transaction(this_arg: *const c_void, mut closing_tx: crate::c_types::Transaction) -> crate::c_types::derived::CResult_SignatureNoneZ {
-       let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemoryChannelKeys) }.sign_closing_transaction(&closing_tx.into_bitcoin(), &bitcoin::secp256k1::Secp256k1::new());
-       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Signature::from_rust(&o) }), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }) };
+extern "C" fn InMemorySigner_Sign_sign_closing_transaction(this_arg: *const c_void, mut closing_tx: crate::c_types::Transaction) -> crate::c_types::derived::CResult_SignatureNoneZ {
+       let mut ret = <nativeInMemorySigner as SignTraitImport<>>::sign_closing_transaction(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, &closing_tx.into_bitcoin(), secp256k1::SECP256K1);
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Signature::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }).into() };
        local_ret
 }
 #[must_use]
-extern "C" fn InMemoryChannelKeys_ChannelKeys_sign_channel_announcement(this_arg: *const c_void, msg: &crate::ln::msgs::UnsignedChannelAnnouncement) -> crate::c_types::derived::CResult_SignatureNoneZ {
-       let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemoryChannelKeys) }.sign_channel_announcement(unsafe { &*msg.inner }, &bitcoin::secp256k1::Secp256k1::new());
-       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Signature::from_rust(&o) }), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }) };
+extern "C" fn InMemorySigner_Sign_sign_channel_announcement(this_arg: *const c_void, msg: &crate::ln::msgs::UnsignedChannelAnnouncement) -> crate::c_types::derived::CResult_SignatureNoneZ {
+       let mut ret = <nativeInMemorySigner as SignTraitImport<>>::sign_channel_announcement(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, unsafe { &*msg.inner }, secp256k1::SECP256K1);
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Signature::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }).into() };
        local_ret
 }
-extern "C" fn InMemoryChannelKeys_ChannelKeys_on_accept(this_arg: *mut c_void, channel_pubkeys: &crate::ln::chan_utils::ChannelPublicKeys, mut counterparty_selected_contest_delay: u16, mut holder_selected_contest_delay: u16) {
-       unsafe { &mut *(this_arg as *mut nativeInMemoryChannelKeys) }.on_accept(unsafe { &*channel_pubkeys.inner }, counterparty_selected_contest_delay, holder_selected_contest_delay)
+extern "C" fn InMemorySigner_Sign_ready_channel(this_arg: *mut c_void, channel_parameters: &crate::ln::chan_utils::ChannelTransactionParameters) {
+       <nativeInMemorySigner as SignTraitImport<>>::ready_channel(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, unsafe { &*channel_parameters.inner })
 }
 
 #[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_write(obj: *const InMemoryChannelKeys) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub extern "C" fn InMemorySigner_write(obj: &InMemorySigner) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
 }
 #[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_read(ser: crate::c_types::u8slice) -> InMemoryChannelKeys {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               InMemoryChannelKeys { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               InMemoryChannelKeys { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub(crate) extern "C" fn InMemorySigner_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeInMemorySigner) })
+}
+#[no_mangle]
+pub extern "C" fn InMemorySigner_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_InMemorySignerDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::chain::keysinterface::InMemorySigner { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
 }
 
 use lightning::chain::keysinterface::KeysManager as nativeKeysManagerImport;
@@ -858,7 +1143,7 @@ extern "C" fn KeysManager_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl KeysManager {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeKeysManager {
+       pub(crate) fn take_inner(mut self) -> *mut nativeKeysManager {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
@@ -886,65 +1171,97 @@ impl KeysManager {
 /// detailed description of the guarantee.
 #[must_use]
 #[no_mangle]
-pub extern "C" fn KeysManager_new(seed: *const [u8; 32], mut network: crate::bitcoin::network::Network, mut starting_time_secs: u64, mut starting_time_nanos: u32) -> KeysManager {
-       let mut ret = lightning::chain::keysinterface::KeysManager::new(unsafe { &*seed}, network.into_bitcoin(), starting_time_secs, starting_time_nanos);
+pub extern "C" fn KeysManager_new(seed: *const [u8; 32], mut starting_time_secs: u64, mut starting_time_nanos: u32) -> KeysManager {
+       let mut ret = lightning::chain::keysinterface::KeysManager::new(unsafe { &*seed}, starting_time_secs, starting_time_nanos);
        KeysManager { inner: Box::into_raw(Box::new(ret)), is_owned: true }
 }
 
-/// Derive an old set of ChannelKeys for per-channel secrets based on a key derivation
-/// parameters.
+/// Derive an old Sign containing per-channel secrets based on a key derivation parameters.
+///
 /// Key derivation parameters are accessible through a per-channel secrets
-/// ChannelKeys::key_derivation_params and is provided inside DynamicOuputP2WSH in case of
+/// Sign::channel_keys_id and is provided inside DynamicOuputP2WSH in case of
 /// onchain output detection for which a corresponding delayed_payment_key must be derived.
 #[must_use]
 #[no_mangle]
-pub extern "C" fn KeysManager_derive_channel_keys(this_arg: &KeysManager, mut channel_value_satoshis: u64, mut params_1: u64, mut params_2: u64) -> crate::chain::keysinterface::InMemoryChannelKeys {
-       let mut ret = unsafe { &*this_arg.inner }.derive_channel_keys(channel_value_satoshis, params_1, params_2);
-       crate::chain::keysinterface::InMemoryChannelKeys { inner: Box::into_raw(Box::new(ret)), is_owned: true }
+pub extern "C" fn KeysManager_derive_channel_keys(this_arg: &KeysManager, mut channel_value_satoshis: u64, params: *const [u8; 32]) -> crate::chain::keysinterface::InMemorySigner {
+       let mut ret = unsafe { &*this_arg.inner }.derive_channel_keys(channel_value_satoshis, unsafe { &*params});
+       crate::chain::keysinterface::InMemorySigner { inner: Box::into_raw(Box::new(ret)), is_owned: true }
 }
 
+/// Creates a Transaction which spends the given descriptors to the given outputs, plus an
+/// output to the given change destination (if sufficient change value remains). The
+/// transaction will have a feerate, at least, of the given value.
+///
+/// Returns `Err(())` if the output value is greater than the input value minus required fee or
+/// if a descriptor was duplicated.
+///
+/// We do not enforce that outputs meet the dust limit or that any output scripts are standard.
+///
+/// May panic if the `SpendableOutputDescriptor`s were not generated by Channels which used
+/// this KeysManager or one of the `InMemorySigner` created by this KeysManager.
+#[must_use]
+#[no_mangle]
+pub extern "C" fn KeysManager_spend_spendable_outputs(this_arg: &KeysManager, mut descriptors: crate::c_types::derived::CVec_SpendableOutputDescriptorZ, mut outputs: crate::c_types::derived::CVec_TxOutZ, mut change_destination_script: crate::c_types::derived::CVec_u8Z, mut feerate_sat_per_1000_weight: u32) -> crate::c_types::derived::CResult_TransactionNoneZ {
+       let mut local_descriptors = Vec::new(); for mut item in descriptors.into_rust().drain(..) { local_descriptors.push( { item.into_native() }); };
+       let mut local_outputs = Vec::new(); for mut item in outputs.into_rust().drain(..) { local_outputs.push( { item.into_rust() }); };
+       let mut ret = unsafe { &*this_arg.inner }.spend_spendable_outputs(&local_descriptors.iter().collect::<Vec<_>>()[..], local_outputs, ::bitcoin::blockdata::script::Script::from(change_destination_script.into_rust()), feerate_sat_per_1000_weight, secp256k1::SECP256K1);
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let mut local_ret_0 = ::bitcoin::consensus::encode::serialize(&o); crate::c_types::Transaction::from_vec(local_ret_0) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }).into() };
+       local_ret
+}
+
+impl From<nativeKeysManager> for crate::chain::keysinterface::KeysInterface {
+       fn from(obj: nativeKeysManager) -> Self {
+               let mut rust_obj = KeysManager { inner: Box::into_raw(Box::new(obj)), is_owned: true };
+               let mut ret = KeysManager_as_KeysInterface(&rust_obj);
+               // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
+               rust_obj.inner = std::ptr::null_mut();
+               ret.free = Some(KeysManager_free_void);
+               ret
+       }
+}
 #[no_mangle]
-pub extern "C" fn KeysManager_as_KeysInterface(this_arg: *const KeysManager) -> crate::chain::keysinterface::KeysInterface {
+pub extern "C" fn KeysManager_as_KeysInterface(this_arg: &KeysManager) -> crate::chain::keysinterface::KeysInterface {
        crate::chain::keysinterface::KeysInterface {
                this_arg: unsafe { (*this_arg).inner as *mut c_void },
                free: None,
                get_node_secret: KeysManager_KeysInterface_get_node_secret,
                get_destination_script: KeysManager_KeysInterface_get_destination_script,
                get_shutdown_pubkey: KeysManager_KeysInterface_get_shutdown_pubkey,
-               get_channel_keys: KeysManager_KeysInterface_get_channel_keys,
+               get_channel_signer: KeysManager_KeysInterface_get_channel_signer,
                get_secure_random_bytes: KeysManager_KeysInterface_get_secure_random_bytes,
+               read_chan_signer: KeysManager_KeysInterface_read_chan_signer,
        }
 }
 use lightning::chain::keysinterface::KeysInterface as KeysInterfaceTraitImport;
 #[must_use]
 extern "C" fn KeysManager_KeysInterface_get_node_secret(this_arg: *const c_void) -> crate::c_types::SecretKey {
-       let mut ret = unsafe { &mut *(this_arg as *mut nativeKeysManager) }.get_node_secret();
+       let mut ret = <nativeKeysManager as KeysInterfaceTraitImport<>>::get_node_secret(unsafe { &mut *(this_arg as *mut nativeKeysManager) }, );
        crate::c_types::SecretKey::from_rust(ret)
 }
 #[must_use]
 extern "C" fn KeysManager_KeysInterface_get_destination_script(this_arg: *const c_void) -> crate::c_types::derived::CVec_u8Z {
-       let mut ret = unsafe { &mut *(this_arg as *mut nativeKeysManager) }.get_destination_script();
+       let mut ret = <nativeKeysManager as KeysInterfaceTraitImport<>>::get_destination_script(unsafe { &mut *(this_arg as *mut nativeKeysManager) }, );
        ret.into_bytes().into()
 }
 #[must_use]
 extern "C" fn KeysManager_KeysInterface_get_shutdown_pubkey(this_arg: *const c_void) -> crate::c_types::PublicKey {
-       let mut ret = unsafe { &mut *(this_arg as *mut nativeKeysManager) }.get_shutdown_pubkey();
+       let mut ret = <nativeKeysManager as KeysInterfaceTraitImport<>>::get_shutdown_pubkey(unsafe { &mut *(this_arg as *mut nativeKeysManager) }, );
        crate::c_types::PublicKey::from_rust(&ret)
 }
 #[must_use]
-extern "C" fn KeysManager_KeysInterface_get_channel_keys(this_arg: *const c_void, mut _inbound: bool, mut channel_value_satoshis: u64) -> crate::chain::keysinterface::ChannelKeys {
-       let mut ret = unsafe { &mut *(this_arg as *mut nativeKeysManager) }.get_channel_keys(_inbound, channel_value_satoshis);
-       let mut rust_obj = InMemoryChannelKeys { inner: Box::into_raw(Box::new(ret)), is_owned: true };
-       let mut ret = InMemoryChannelKeys_as_ChannelKeys(&rust_obj);
-       // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
-       rust_obj.inner = std::ptr::null_mut();
-       ret.free = Some(InMemoryChannelKeys_free_void);
-       ret
-
+extern "C" fn KeysManager_KeysInterface_get_channel_signer(this_arg: *const c_void, mut _inbound: bool, mut channel_value_satoshis: u64) -> crate::chain::keysinterface::Sign {
+       let mut ret = <nativeKeysManager as KeysInterfaceTraitImport<>>::get_channel_signer(unsafe { &mut *(this_arg as *mut nativeKeysManager) }, _inbound, channel_value_satoshis);
+       ret.into()
 }
 #[must_use]
 extern "C" fn KeysManager_KeysInterface_get_secure_random_bytes(this_arg: *const c_void) -> crate::c_types::ThirtyTwoBytes {
-       let mut ret = unsafe { &mut *(this_arg as *mut nativeKeysManager) }.get_secure_random_bytes();
+       let mut ret = <nativeKeysManager as KeysInterfaceTraitImport<>>::get_secure_random_bytes(unsafe { &mut *(this_arg as *mut nativeKeysManager) }, );
        crate::c_types::ThirtyTwoBytes { data: ret }
 }
+#[must_use]
+extern "C" fn KeysManager_KeysInterface_read_chan_signer(this_arg: *const c_void, mut reader: crate::c_types::u8slice) -> crate::c_types::derived::CResult_SignDecodeErrorZ {
+       let mut ret = <nativeKeysManager as KeysInterfaceTraitImport<>>::read_chan_signer(unsafe { &mut *(this_arg as *mut nativeKeysManager) }, reader.to_slice());
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { o.into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_ret
+}
 
index 6ea4d99db9df9e403b29f8aa8f4a52ede7df17d4..fb72263f39c45ee5dcc6110d4f50384d3bb75712 100644 (file)
@@ -77,7 +77,7 @@ use lightning::chain::Access as rustAccess;
 impl rustAccess for Access {
        fn get_utxo(&self, genesis_hash: &bitcoin::hash_types::BlockHash, short_channel_id: u64) -> Result<bitcoin::blockdata::transaction::TxOut, lightning::chain::AccessError> {
                let mut ret = (self.get_utxo)(self.this_arg, genesis_hash.as_inner(), short_channel_id);
-               let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(ret.contents.result.take_ptr()) }).into_rust() }), false => Err( { (*unsafe { Box::from_raw(ret.contents.err.take_ptr()) }).into_native() })};
+               let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).into_native() })};
                local_ret
        }
 }
@@ -100,6 +100,50 @@ impl Drop for Access {
                }
        }
 }
+/// The `Listen` trait is used to be notified of when blocks have been connected or disconnected
+/// from the chain.
+///
+/// Useful when needing to replay chain data upon startup or as new chain events occur.
+#[repr(C)]
+pub struct Listen {
+       pub this_arg: *mut c_void,
+       /// Notifies the listener that a block was added at the given height.
+       pub block_connected: extern "C" fn (this_arg: *const c_void, block: crate::c_types::u8slice, height: u32),
+       /// Notifies the listener that a block was removed at the given height.
+       pub block_disconnected: extern "C" fn (this_arg: *const c_void, header: *const [u8; 80], height: u32),
+       pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
+}
+
+use lightning::chain::Listen as rustListen;
+impl rustListen for Listen {
+       fn block_connected(&self, block: &bitcoin::blockdata::block::Block, height: u32) {
+               let mut local_block = ::bitcoin::consensus::encode::serialize(block);
+               (self.block_connected)(self.this_arg, crate::c_types::u8slice::from_slice(&local_block), height)
+       }
+       fn block_disconnected(&self, header: &bitcoin::blockdata::block::BlockHeader, height: u32) {
+               let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
+               (self.block_disconnected)(self.this_arg, &local_header, height)
+       }
+}
+
+// We're essentially a pointer already, or at least a set of pointers, so allow us to be used
+// directly as a Deref trait in higher-level structs:
+impl std::ops::Deref for Listen {
+       type Target = Self;
+       fn deref(&self) -> &Self {
+               self
+       }
+}
+/// Calls the free function if one is set
+#[no_mangle]
+pub extern "C" fn Listen_free(this_ptr: Listen) { }
+impl Drop for Listen {
+       fn drop(&mut self) {
+               if let Some(f) = self.free {
+                       f(self.this_arg);
+               }
+       }
+}
 /// The `Watch` trait defines behavior for watching on-chain activity pertaining to channels as
 /// blocks are connected and disconnected.
 ///
@@ -154,21 +198,20 @@ unsafe impl Send for Watch {}
 unsafe impl Sync for Watch {}
 
 use lightning::chain::Watch as rustWatch;
-impl rustWatch for Watch {
-       type Keys = crate::chain::keysinterface::ChannelKeys;
-       fn watch_channel(&self, funding_txo: lightning::chain::transaction::OutPoint, monitor: lightning::chain::channelmonitor::ChannelMonitor<Self::Keys>) -> Result<(), lightning::chain::channelmonitor::ChannelMonitorUpdateErr> {
+impl rustWatch<crate::chain::keysinterface::Sign> for Watch {
+       fn watch_channel(&self, funding_txo: lightning::chain::transaction::OutPoint, monitor: lightning::chain::channelmonitor::ChannelMonitor<crate::chain::keysinterface::Sign>) -> Result<(), lightning::chain::channelmonitor::ChannelMonitorUpdateErr> {
                let mut ret = (self.watch_channel)(self.this_arg, crate::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(funding_txo)), is_owned: true }, crate::chain::channelmonitor::ChannelMonitor { inner: Box::into_raw(Box::new(monitor)), is_owned: true });
-               let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(ret.contents.result.take_ptr()) })*/ }), false => Err( { (*unsafe { Box::from_raw(ret.contents.err.take_ptr()) }).into_native() })};
+               let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).into_native() })};
                local_ret
        }
        fn update_channel(&self, funding_txo: lightning::chain::transaction::OutPoint, update: lightning::chain::channelmonitor::ChannelMonitorUpdate) -> Result<(), lightning::chain::channelmonitor::ChannelMonitorUpdateErr> {
                let mut ret = (self.update_channel)(self.this_arg, crate::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(funding_txo)), is_owned: true }, crate::chain::channelmonitor::ChannelMonitorUpdate { inner: Box::into_raw(Box::new(update)), is_owned: true });
-               let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(ret.contents.result.take_ptr()) })*/ }), false => Err( { (*unsafe { Box::from_raw(ret.contents.err.take_ptr()) }).into_native() })};
+               let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).into_native() })};
                local_ret
        }
        fn release_pending_monitor_events(&self) -> Vec<lightning::chain::channelmonitor::MonitorEvent> {
                let mut ret = (self.release_pending_monitor_events)(self.this_arg);
-               let mut local_ret = Vec::new(); for mut item in ret.into_rust().drain(..) { local_ret.push( { *unsafe { Box::from_raw(item.take_ptr()) } }); };
+               let mut local_ret = Vec::new(); for mut item in ret.into_rust().drain(..) { local_ret.push( { item.into_native() }); };
                local_ret
        }
 }
index 3a35c4727f937183018e304786e6cf4029c2fda4..d0fd8c62112469ec8ede0856c6436a5d10c784e7 100644 (file)
@@ -38,30 +38,13 @@ extern "C" fn OutPoint_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl OutPoint {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeOutPoint {
+       pub(crate) fn take_inner(mut self) -> *mut nativeOutPoint {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for OutPoint {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn OutPoint_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeOutPoint)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn OutPoint_clone(orig: &OutPoint) -> OutPoint {
-       OutPoint { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// The referenced transaction's txid.
 #[no_mangle]
 pub extern "C" fn OutPoint_get_txid(this_ptr: &OutPoint) -> *const [u8; 32] {
@@ -92,6 +75,24 @@ pub extern "C" fn OutPoint_new(mut txid_arg: crate::c_types::ThirtyTwoBytes, mut
                index: index_arg,
        })), is_owned: true }
 }
+impl Clone for OutPoint {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn OutPoint_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeOutPoint)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn OutPoint_clone(orig: &OutPoint) -> OutPoint {
+       orig.clone()
+}
 /// Convert an `OutPoint` to a lightning channel id.
 #[must_use]
 #[no_mangle]
@@ -101,14 +102,16 @@ pub extern "C" fn OutPoint_to_channel_id(this_arg: &OutPoint) -> crate::c_types:
 }
 
 #[no_mangle]
-pub extern "C" fn OutPoint_write(obj: *const OutPoint) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub extern "C" fn OutPoint_write(obj: &OutPoint) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
 }
 #[no_mangle]
-pub extern "C" fn OutPoint_read(ser: crate::c_types::u8slice) -> OutPoint {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               OutPoint { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               OutPoint { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub(crate) extern "C" fn OutPoint_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeOutPoint) })
+}
+#[no_mangle]
+pub extern "C" fn OutPoint_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_OutPointDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
 }
index f9e6c407ef036df18c28e437c1d18ea2bec19543..a32feb6e21442f0acab40ca2034ec926b9115493 100644 (file)
@@ -1,6 +1,5 @@
 //! Various utilities for building scripts and deriving keys related to channels. These are
-//! largely of interest for those implementing chain::keysinterface::ChannelKeys message signing
-//! by hand.
+//! largely of interest for those implementing chain::keysinterface::Sign message signing by hand.
 
 use std::ffi::c_void;
 use bitcoin::hashes::Hash;
@@ -19,9 +18,9 @@ pub extern "C" fn build_commitment_secret(commitment_seed: *const [u8; 32], mut
 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
 /// generated (ie our own).
 #[no_mangle]
-pub extern "C" fn derive_private_key(mut per_commitment_point: crate::c_types::PublicKey, base_secret: *const [u8; 32]) -> crate::c_types::derived::CResult_SecretKeySecpErrorZ {
-       let mut ret = lightning::ln::chan_utils::derive_private_key(&bitcoin::secp256k1::Secp256k1::new(), &per_commitment_point.into_rust(), &::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *base_secret}[..]).unwrap());
-       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::SecretKey::from_rust(o) }), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::Secp256k1Error::from_rust(e) }) };
+pub extern "C" fn derive_private_key(mut per_commitment_point: crate::c_types::PublicKey, base_secret: *const [u8; 32]) -> crate::c_types::derived::CResult_SecretKeyErrorZ {
+       let mut ret = lightning::ln::chan_utils::derive_private_key(secp256k1::SECP256K1, &per_commitment_point.into_rust(), &::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *base_secret}[..]).unwrap());
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::SecretKey::from_rust(o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::Secp256k1Error::from_rust(e) }).into() };
        local_ret
 }
 
@@ -32,9 +31,9 @@ pub extern "C" fn derive_private_key(mut per_commitment_point: crate::c_types::P
 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
 /// generated (ie our own).
 #[no_mangle]
-pub extern "C" fn derive_public_key(mut per_commitment_point: crate::c_types::PublicKey, mut base_point: crate::c_types::PublicKey) -> crate::c_types::derived::CResult_PublicKeySecpErrorZ {
-       let mut ret = lightning::ln::chan_utils::derive_public_key(&bitcoin::secp256k1::Secp256k1::new(), &per_commitment_point.into_rust(), &base_point.into_rust());
-       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::PublicKey::from_rust(&o) }), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::Secp256k1Error::from_rust(e) }) };
+pub extern "C" fn derive_public_key(mut per_commitment_point: crate::c_types::PublicKey, mut base_point: crate::c_types::PublicKey) -> crate::c_types::derived::CResult_PublicKeyErrorZ {
+       let mut ret = lightning::ln::chan_utils::derive_public_key(secp256k1::SECP256K1, &per_commitment_point.into_rust(), &base_point.into_rust());
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::PublicKey::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::Secp256k1Error::from_rust(e) }).into() };
        local_ret
 }
 
@@ -48,9 +47,9 @@ pub extern "C" fn derive_public_key(mut per_commitment_point: crate::c_types::Pu
 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
 /// generated (ie our own).
 #[no_mangle]
-pub extern "C" fn derive_private_revocation_key(per_commitment_secret: *const [u8; 32], countersignatory_revocation_base_secret: *const [u8; 32]) -> crate::c_types::derived::CResult_SecretKeySecpErrorZ {
-       let mut ret = lightning::ln::chan_utils::derive_private_revocation_key(&bitcoin::secp256k1::Secp256k1::new(), &::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *per_commitment_secret}[..]).unwrap(), &::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *countersignatory_revocation_base_secret}[..]).unwrap());
-       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::SecretKey::from_rust(o) }), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::Secp256k1Error::from_rust(e) }) };
+pub extern "C" fn derive_private_revocation_key(per_commitment_secret: *const [u8; 32], countersignatory_revocation_base_secret: *const [u8; 32]) -> crate::c_types::derived::CResult_SecretKeyErrorZ {
+       let mut ret = lightning::ln::chan_utils::derive_private_revocation_key(secp256k1::SECP256K1, &::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *per_commitment_secret}[..]).unwrap(), &::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *countersignatory_revocation_base_secret}[..]).unwrap());
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::SecretKey::from_rust(o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::Secp256k1Error::from_rust(e) }).into() };
        local_ret
 }
 
@@ -66,9 +65,9 @@ pub extern "C" fn derive_private_revocation_key(per_commitment_secret: *const [u
 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
 /// generated (ie our own).
 #[no_mangle]
-pub extern "C" fn derive_public_revocation_key(mut per_commitment_point: crate::c_types::PublicKey, mut countersignatory_revocation_base_point: crate::c_types::PublicKey) -> crate::c_types::derived::CResult_PublicKeySecpErrorZ {
-       let mut ret = lightning::ln::chan_utils::derive_public_revocation_key(&bitcoin::secp256k1::Secp256k1::new(), &per_commitment_point.into_rust(), &countersignatory_revocation_base_point.into_rust());
-       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::PublicKey::from_rust(&o) }), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::Secp256k1Error::from_rust(e) }) };
+pub extern "C" fn derive_public_revocation_key(mut per_commitment_point: crate::c_types::PublicKey, mut countersignatory_revocation_base_point: crate::c_types::PublicKey) -> crate::c_types::derived::CResult_PublicKeyErrorZ {
+       let mut ret = lightning::ln::chan_utils::derive_public_revocation_key(secp256k1::SECP256K1, &per_commitment_point.into_rust(), &countersignatory_revocation_base_point.into_rust());
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::PublicKey::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::Secp256k1Error::from_rust(e) }).into() };
        local_ret
 }
 
@@ -85,7 +84,7 @@ type nativeTxCreationKeys = nativeTxCreationKeysImport;
 ///
 /// These keys are assumed to be good, either because the code derived them from
 /// channel basepoints via the new function, or they were obtained via
-/// PreCalculatedTxCreationKeys.trust_key_derivation because we trusted the source of the
+/// CommitmentTransaction.trust().keys() because we trusted the source of the
 /// pre-calculated keys.
 #[must_use]
 #[repr(C)]
@@ -113,30 +112,13 @@ extern "C" fn TxCreationKeys_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl TxCreationKeys {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeTxCreationKeys {
+       pub(crate) fn take_inner(mut self) -> *mut nativeTxCreationKeys {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for TxCreationKeys {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn TxCreationKeys_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeTxCreationKeys)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn TxCreationKeys_clone(orig: &TxCreationKeys) -> TxCreationKeys {
-       TxCreationKeys { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// The broadcaster's per-commitment public key which was used to derive the other keys.
 #[no_mangle]
 pub extern "C" fn TxCreationKeys_get_per_commitment_point(this_ptr: &TxCreationKeys) -> crate::c_types::PublicKey {
@@ -207,102 +189,39 @@ pub extern "C" fn TxCreationKeys_new(mut per_commitment_point_arg: crate::c_type
                broadcaster_delayed_payment_key: broadcaster_delayed_payment_key_arg.into_rust(),
        })), is_owned: true }
 }
-#[no_mangle]
-pub extern "C" fn TxCreationKeys_write(obj: *const TxCreationKeys) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
-}
-#[no_mangle]
-pub extern "C" fn TxCreationKeys_read(ser: crate::c_types::u8slice) -> TxCreationKeys {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               TxCreationKeys { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               TxCreationKeys { inner: std::ptr::null_mut(), is_owned: true }
-       }
-}
-
-use lightning::ln::chan_utils::PreCalculatedTxCreationKeys as nativePreCalculatedTxCreationKeysImport;
-type nativePreCalculatedTxCreationKeys = nativePreCalculatedTxCreationKeysImport;
-
-/// The per-commitment point and a set of pre-calculated public keys used for transaction creation
-/// in the signer.
-/// The pre-calculated keys are an optimization, because ChannelKeys has enough
-/// information to re-derive them.
-#[must_use]
-#[repr(C)]
-pub struct PreCalculatedTxCreationKeys {
-       /// Nearly everywhere, inner must be non-null, however in places where
-       /// the Rust equivalent takes an Option, it may be set to null to indicate None.
-       pub inner: *mut nativePreCalculatedTxCreationKeys,
-       pub is_owned: bool,
-}
-
-impl Drop for PreCalculatedTxCreationKeys {
-       fn drop(&mut self) {
-               if self.is_owned && !self.inner.is_null() {
-                       let _ = unsafe { Box::from_raw(self.inner) };
-               }
-       }
-}
-#[no_mangle]
-pub extern "C" fn PreCalculatedTxCreationKeys_free(this_ptr: PreCalculatedTxCreationKeys) { }
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-extern "C" fn PreCalculatedTxCreationKeys_free_void(this_ptr: *mut c_void) {
-       unsafe { let _ = Box::from_raw(this_ptr as *mut nativePreCalculatedTxCreationKeys); }
-}
-#[allow(unused)]
-/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
-impl PreCalculatedTxCreationKeys {
-       pub(crate) fn take_ptr(mut self) -> *mut nativePreCalculatedTxCreationKeys {
-               assert!(self.is_owned);
-               let ret = self.inner;
-               self.inner = std::ptr::null_mut();
-               ret
-       }
-}
-impl Clone for PreCalculatedTxCreationKeys {
+impl Clone for TxCreationKeys {
        fn clone(&self) -> Self {
                Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
                        is_owned: true,
                }
        }
 }
 #[allow(unused)]
 /// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn PreCalculatedTxCreationKeys_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativePreCalculatedTxCreationKeys)).clone() })) as *mut c_void
+pub(crate) extern "C" fn TxCreationKeys_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeTxCreationKeys)).clone() })) as *mut c_void
 }
 #[no_mangle]
-pub extern "C" fn PreCalculatedTxCreationKeys_clone(orig: &PreCalculatedTxCreationKeys) -> PreCalculatedTxCreationKeys {
-       PreCalculatedTxCreationKeys { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
+pub extern "C" fn TxCreationKeys_clone(orig: &TxCreationKeys) -> TxCreationKeys {
+       orig.clone()
 }
-/// Create a new PreCalculatedTxCreationKeys from TxCreationKeys
-#[must_use]
 #[no_mangle]
-pub extern "C" fn PreCalculatedTxCreationKeys_new(mut keys: crate::ln::chan_utils::TxCreationKeys) -> PreCalculatedTxCreationKeys {
-       let mut ret = lightning::ln::chan_utils::PreCalculatedTxCreationKeys::new(*unsafe { Box::from_raw(keys.take_ptr()) });
-       PreCalculatedTxCreationKeys { inner: Box::into_raw(Box::new(ret)), is_owned: true }
+pub extern "C" fn TxCreationKeys_write(obj: &TxCreationKeys) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
 }
-
-/// The pre-calculated transaction creation public keys.
-/// An external validating signer should not trust these keys.
-#[must_use]
 #[no_mangle]
-pub extern "C" fn PreCalculatedTxCreationKeys_trust_key_derivation(this_arg: &PreCalculatedTxCreationKeys) -> crate::ln::chan_utils::TxCreationKeys {
-       let mut ret = unsafe { &*this_arg.inner }.trust_key_derivation();
-       crate::ln::chan_utils::TxCreationKeys { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false }
+pub(crate) extern "C" fn TxCreationKeys_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeTxCreationKeys) })
 }
-
-/// The transaction per-commitment point
-#[must_use]
 #[no_mangle]
-pub extern "C" fn PreCalculatedTxCreationKeys_per_commitment_point(this_arg: &PreCalculatedTxCreationKeys) -> crate::c_types::PublicKey {
-       let mut ret = unsafe { &*this_arg.inner }.per_commitment_point();
-       crate::c_types::PublicKey::from_rust(&*ret)
+pub extern "C" fn TxCreationKeys_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_TxCreationKeysDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::chan_utils::TxCreationKeys { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
 }
 
-
 use lightning::ln::chan_utils::ChannelPublicKeys as nativeChannelPublicKeysImport;
 type nativeChannelPublicKeys = nativeChannelPublicKeysImport;
 
@@ -333,30 +252,13 @@ extern "C" fn ChannelPublicKeys_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl ChannelPublicKeys {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeChannelPublicKeys {
+       pub(crate) fn take_inner(mut self) -> *mut nativeChannelPublicKeys {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for ChannelPublicKeys {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn ChannelPublicKeys_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelPublicKeys)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn ChannelPublicKeys_clone(orig: &ChannelPublicKeys) -> ChannelPublicKeys {
-       ChannelPublicKeys { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// The public key which is used to sign all commitment transactions, as it appears in the
 /// on-chain channel lock-in 2-of-2 multisig output.
 #[no_mangle]
@@ -441,27 +343,61 @@ pub extern "C" fn ChannelPublicKeys_new(mut funding_pubkey_arg: crate::c_types::
                htlc_basepoint: htlc_basepoint_arg.into_rust(),
        })), is_owned: true }
 }
+impl Clone for ChannelPublicKeys {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn ChannelPublicKeys_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelPublicKeys)).clone() })) as *mut c_void
+}
 #[no_mangle]
-pub extern "C" fn ChannelPublicKeys_write(obj: *const ChannelPublicKeys) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub extern "C" fn ChannelPublicKeys_clone(orig: &ChannelPublicKeys) -> ChannelPublicKeys {
+       orig.clone()
 }
 #[no_mangle]
-pub extern "C" fn ChannelPublicKeys_read(ser: crate::c_types::u8slice) -> ChannelPublicKeys {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               ChannelPublicKeys { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               ChannelPublicKeys { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub extern "C" fn ChannelPublicKeys_write(obj: &ChannelPublicKeys) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+}
+#[no_mangle]
+pub(crate) extern "C" fn ChannelPublicKeys_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeChannelPublicKeys) })
+}
+#[no_mangle]
+pub extern "C" fn ChannelPublicKeys_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelPublicKeysDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::chan_utils::ChannelPublicKeys { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
+}
+/// Create per-state keys from channel base points and the per-commitment point.
+/// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
+#[must_use]
+#[no_mangle]
+pub extern "C" fn TxCreationKeys_derive_new(mut per_commitment_point: crate::c_types::PublicKey, mut broadcaster_delayed_payment_base: crate::c_types::PublicKey, mut broadcaster_htlc_base: crate::c_types::PublicKey, mut countersignatory_revocation_base: crate::c_types::PublicKey, mut countersignatory_htlc_base: crate::c_types::PublicKey) -> crate::c_types::derived::CResult_TxCreationKeysErrorZ {
+       let mut ret = lightning::ln::chan_utils::TxCreationKeys::derive_new(secp256k1::SECP256K1, &per_commitment_point.into_rust(), &broadcaster_delayed_payment_base.into_rust(), &broadcaster_htlc_base.into_rust(), &countersignatory_revocation_base.into_rust(), &countersignatory_htlc_base.into_rust());
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::chan_utils::TxCreationKeys { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::Secp256k1Error::from_rust(e) }).into() };
+       local_ret
 }
-/// Create a new TxCreationKeys from channel base points and the per-commitment point
+
+/// Generate per-state keys from channel static keys.
+/// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
 #[must_use]
 #[no_mangle]
-pub extern "C" fn TxCreationKeys_derive_new(mut per_commitment_point: crate::c_types::PublicKey, mut broadcaster_delayed_payment_base: crate::c_types::PublicKey, mut broadcaster_htlc_base: crate::c_types::PublicKey, mut countersignatory_revocation_base: crate::c_types::PublicKey, mut countersignatory_htlc_base: crate::c_types::PublicKey) -> crate::c_types::derived::CResult_TxCreationKeysSecpErrorZ {
-       let mut ret = lightning::ln::chan_utils::TxCreationKeys::derive_new(&bitcoin::secp256k1::Secp256k1::new(), &per_commitment_point.into_rust(), &broadcaster_delayed_payment_base.into_rust(), &broadcaster_htlc_base.into_rust(), &countersignatory_revocation_base.into_rust(), &countersignatory_htlc_base.into_rust());
-       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::chan_utils::TxCreationKeys { inner: Box::into_raw(Box::new(o)), is_owned: true } }), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::Secp256k1Error::from_rust(e) }) };
+pub extern "C" fn TxCreationKeys_from_channel_static_keys(mut per_commitment_point: crate::c_types::PublicKey, broadcaster_keys: &crate::ln::chan_utils::ChannelPublicKeys, countersignatory_keys: &crate::ln::chan_utils::ChannelPublicKeys) -> crate::c_types::derived::CResult_TxCreationKeysErrorZ {
+       let mut ret = lightning::ln::chan_utils::TxCreationKeys::from_channel_static_keys(&per_commitment_point.into_rust(), unsafe { &*broadcaster_keys.inner }, unsafe { &*countersignatory_keys.inner }, secp256k1::SECP256K1);
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::chan_utils::TxCreationKeys { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::Secp256k1Error::from_rust(e) }).into() };
        local_ret
 }
 
+
+#[no_mangle]
+pub static REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH: usize = lightning::ln::chan_utils::REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH;
 /// A script either spendable by the revocation
 /// key or the broadcaster_delayed_payment_key and satisfying the relative-locktime OP_CSV constrain.
 /// Encumbering a `to_holder` output on a commitment transaction or 2nd-stage HTLC transactions.
@@ -502,30 +438,13 @@ extern "C" fn HTLCOutputInCommitment_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl HTLCOutputInCommitment {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeHTLCOutputInCommitment {
+       pub(crate) fn take_inner(mut self) -> *mut nativeHTLCOutputInCommitment {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for HTLCOutputInCommitment {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn HTLCOutputInCommitment_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeHTLCOutputInCommitment)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn HTLCOutputInCommitment_clone(orig: &HTLCOutputInCommitment) -> HTLCOutputInCommitment {
-       HTLCOutputInCommitment { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// Whether the HTLC was \"offered\" (ie outbound in relation to this commitment transaction).
 /// Note that this is not the same as whether it is ountbound *from us*. To determine that you
 /// need to compare this value to whether the commitment transaction in question is that of
@@ -578,17 +497,37 @@ pub extern "C" fn HTLCOutputInCommitment_get_payment_hash(this_ptr: &HTLCOutputI
 pub extern "C" fn HTLCOutputInCommitment_set_payment_hash(this_ptr: &mut HTLCOutputInCommitment, mut val: crate::c_types::ThirtyTwoBytes) {
        unsafe { &mut *this_ptr.inner }.payment_hash = ::lightning::ln::channelmanager::PaymentHash(val.data);
 }
+impl Clone for HTLCOutputInCommitment {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn HTLCOutputInCommitment_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeHTLCOutputInCommitment)).clone() })) as *mut c_void
+}
 #[no_mangle]
-pub extern "C" fn HTLCOutputInCommitment_write(obj: *const HTLCOutputInCommitment) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub extern "C" fn HTLCOutputInCommitment_clone(orig: &HTLCOutputInCommitment) -> HTLCOutputInCommitment {
+       orig.clone()
 }
 #[no_mangle]
-pub extern "C" fn HTLCOutputInCommitment_read(ser: crate::c_types::u8slice) -> HTLCOutputInCommitment {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               HTLCOutputInCommitment { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               HTLCOutputInCommitment { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub extern "C" fn HTLCOutputInCommitment_write(obj: &HTLCOutputInCommitment) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+}
+#[no_mangle]
+pub(crate) extern "C" fn HTLCOutputInCommitment_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeHTLCOutputInCommitment) })
+}
+#[no_mangle]
+pub extern "C" fn HTLCOutputInCommitment_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_HTLCOutputInCommitmentDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::chan_utils::HTLCOutputInCommitment { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
 }
 /// Gets the witness redeemscript for an HTLC output in a commitment transaction. Note that htlc
 /// does not need to have its previous_output_index filled.
@@ -615,12 +554,378 @@ pub extern "C" fn build_htlc_transaction(prev_hash: *const [u8; 32], mut feerate
 }
 
 
+use lightning::ln::chan_utils::ChannelTransactionParameters as nativeChannelTransactionParametersImport;
+type nativeChannelTransactionParameters = nativeChannelTransactionParametersImport;
+
+/// Per-channel data used to build transactions in conjunction with the per-commitment data (CommitmentTransaction).
+/// The fields are organized by holder/counterparty.
+///
+/// Normally, this is converted to the broadcaster/countersignatory-organized DirectedChannelTransactionParameters
+/// before use, via the as_holder_broadcastable and as_counterparty_broadcastable functions.
+#[must_use]
+#[repr(C)]
+pub struct ChannelTransactionParameters {
+       /// Nearly everywhere, inner must be non-null, however in places where
+       /// the Rust equivalent takes an Option, it may be set to null to indicate None.
+       pub inner: *mut nativeChannelTransactionParameters,
+       pub is_owned: bool,
+}
+
+impl Drop for ChannelTransactionParameters {
+       fn drop(&mut self) {
+               if self.is_owned && !self.inner.is_null() {
+                       let _ = unsafe { Box::from_raw(self.inner) };
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn ChannelTransactionParameters_free(this_ptr: ChannelTransactionParameters) { }
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+extern "C" fn ChannelTransactionParameters_free_void(this_ptr: *mut c_void) {
+       unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelTransactionParameters); }
+}
+#[allow(unused)]
+/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
+impl ChannelTransactionParameters {
+       pub(crate) fn take_inner(mut self) -> *mut nativeChannelTransactionParameters {
+               assert!(self.is_owned);
+               let ret = self.inner;
+               self.inner = std::ptr::null_mut();
+               ret
+       }
+}
+/// Holder public keys
+#[no_mangle]
+pub extern "C" fn ChannelTransactionParameters_get_holder_pubkeys(this_ptr: &ChannelTransactionParameters) -> crate::ln::chan_utils::ChannelPublicKeys {
+       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.holder_pubkeys;
+       crate::ln::chan_utils::ChannelPublicKeys { inner: unsafe { ( (&((*inner_val)) as *const _) as *mut _) }, is_owned: false }
+}
+/// Holder public keys
+#[no_mangle]
+pub extern "C" fn ChannelTransactionParameters_set_holder_pubkeys(this_ptr: &mut ChannelTransactionParameters, mut val: crate::ln::chan_utils::ChannelPublicKeys) {
+       unsafe { &mut *this_ptr.inner }.holder_pubkeys = *unsafe { Box::from_raw(val.take_inner()) };
+}
+/// The contest delay selected by the holder, which applies to counterparty-broadcast transactions
+#[no_mangle]
+pub extern "C" fn ChannelTransactionParameters_get_holder_selected_contest_delay(this_ptr: &ChannelTransactionParameters) -> u16 {
+       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.holder_selected_contest_delay;
+       (*inner_val)
+}
+/// The contest delay selected by the holder, which applies to counterparty-broadcast transactions
+#[no_mangle]
+pub extern "C" fn ChannelTransactionParameters_set_holder_selected_contest_delay(this_ptr: &mut ChannelTransactionParameters, mut val: u16) {
+       unsafe { &mut *this_ptr.inner }.holder_selected_contest_delay = val;
+}
+/// Whether the holder is the initiator of this channel.
+/// This is an input to the commitment number obscure factor computation.
+#[no_mangle]
+pub extern "C" fn ChannelTransactionParameters_get_is_outbound_from_holder(this_ptr: &ChannelTransactionParameters) -> bool {
+       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.is_outbound_from_holder;
+       (*inner_val)
+}
+/// Whether the holder is the initiator of this channel.
+/// This is an input to the commitment number obscure factor computation.
+#[no_mangle]
+pub extern "C" fn ChannelTransactionParameters_set_is_outbound_from_holder(this_ptr: &mut ChannelTransactionParameters, mut val: bool) {
+       unsafe { &mut *this_ptr.inner }.is_outbound_from_holder = val;
+}
+/// The late-bound counterparty channel transaction parameters.
+/// These parameters are populated at the point in the protocol where the counterparty provides them.
+#[no_mangle]
+pub extern "C" fn ChannelTransactionParameters_get_counterparty_parameters(this_ptr: &ChannelTransactionParameters) -> crate::ln::chan_utils::CounterpartyChannelTransactionParameters {
+       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.counterparty_parameters;
+       let mut local_inner_val = crate::ln::chan_utils::CounterpartyChannelTransactionParameters { inner: unsafe { (if inner_val.is_none() { std::ptr::null() } else {  { (inner_val.as_ref().unwrap()) } } as *const _) as *mut _ }, is_owned: false };
+       local_inner_val
+}
+/// The late-bound counterparty channel transaction parameters.
+/// These parameters are populated at the point in the protocol where the counterparty provides them.
+#[no_mangle]
+pub extern "C" fn ChannelTransactionParameters_set_counterparty_parameters(this_ptr: &mut ChannelTransactionParameters, mut val: crate::ln::chan_utils::CounterpartyChannelTransactionParameters) {
+       let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) };
+       unsafe { &mut *this_ptr.inner }.counterparty_parameters = local_val;
+}
+/// The late-bound funding outpoint
+#[no_mangle]
+pub extern "C" fn ChannelTransactionParameters_get_funding_outpoint(this_ptr: &ChannelTransactionParameters) -> crate::chain::transaction::OutPoint {
+       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.funding_outpoint;
+       let mut local_inner_val = crate::chain::transaction::OutPoint { inner: unsafe { (if inner_val.is_none() { std::ptr::null() } else {  { (inner_val.as_ref().unwrap()) } } as *const _) as *mut _ }, is_owned: false };
+       local_inner_val
+}
+/// The late-bound funding outpoint
+#[no_mangle]
+pub extern "C" fn ChannelTransactionParameters_set_funding_outpoint(this_ptr: &mut ChannelTransactionParameters, mut val: crate::chain::transaction::OutPoint) {
+       let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) };
+       unsafe { &mut *this_ptr.inner }.funding_outpoint = local_val;
+}
+#[must_use]
+#[no_mangle]
+pub extern "C" fn ChannelTransactionParameters_new(mut holder_pubkeys_arg: crate::ln::chan_utils::ChannelPublicKeys, mut holder_selected_contest_delay_arg: u16, mut is_outbound_from_holder_arg: bool, mut counterparty_parameters_arg: crate::ln::chan_utils::CounterpartyChannelTransactionParameters, mut funding_outpoint_arg: crate::chain::transaction::OutPoint) -> ChannelTransactionParameters {
+       let mut local_counterparty_parameters_arg = if counterparty_parameters_arg.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(counterparty_parameters_arg.take_inner()) } }) };
+       let mut local_funding_outpoint_arg = if funding_outpoint_arg.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(funding_outpoint_arg.take_inner()) } }) };
+       ChannelTransactionParameters { inner: Box::into_raw(Box::new(nativeChannelTransactionParameters {
+               holder_pubkeys: *unsafe { Box::from_raw(holder_pubkeys_arg.take_inner()) },
+               holder_selected_contest_delay: holder_selected_contest_delay_arg,
+               is_outbound_from_holder: is_outbound_from_holder_arg,
+               counterparty_parameters: local_counterparty_parameters_arg,
+               funding_outpoint: local_funding_outpoint_arg,
+       })), is_owned: true }
+}
+impl Clone for ChannelTransactionParameters {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn ChannelTransactionParameters_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelTransactionParameters)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn ChannelTransactionParameters_clone(orig: &ChannelTransactionParameters) -> ChannelTransactionParameters {
+       orig.clone()
+}
+
+use lightning::ln::chan_utils::CounterpartyChannelTransactionParameters as nativeCounterpartyChannelTransactionParametersImport;
+type nativeCounterpartyChannelTransactionParameters = nativeCounterpartyChannelTransactionParametersImport;
+
+/// Late-bound per-channel counterparty data used to build transactions.
+#[must_use]
+#[repr(C)]
+pub struct CounterpartyChannelTransactionParameters {
+       /// Nearly everywhere, inner must be non-null, however in places where
+       /// the Rust equivalent takes an Option, it may be set to null to indicate None.
+       pub inner: *mut nativeCounterpartyChannelTransactionParameters,
+       pub is_owned: bool,
+}
+
+impl Drop for CounterpartyChannelTransactionParameters {
+       fn drop(&mut self) {
+               if self.is_owned && !self.inner.is_null() {
+                       let _ = unsafe { Box::from_raw(self.inner) };
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CounterpartyChannelTransactionParameters_free(this_ptr: CounterpartyChannelTransactionParameters) { }
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+extern "C" fn CounterpartyChannelTransactionParameters_free_void(this_ptr: *mut c_void) {
+       unsafe { let _ = Box::from_raw(this_ptr as *mut nativeCounterpartyChannelTransactionParameters); }
+}
+#[allow(unused)]
+/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
+impl CounterpartyChannelTransactionParameters {
+       pub(crate) fn take_inner(mut self) -> *mut nativeCounterpartyChannelTransactionParameters {
+               assert!(self.is_owned);
+               let ret = self.inner;
+               self.inner = std::ptr::null_mut();
+               ret
+       }
+}
+/// Counter-party public keys
+#[no_mangle]
+pub extern "C" fn CounterpartyChannelTransactionParameters_get_pubkeys(this_ptr: &CounterpartyChannelTransactionParameters) -> crate::ln::chan_utils::ChannelPublicKeys {
+       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.pubkeys;
+       crate::ln::chan_utils::ChannelPublicKeys { inner: unsafe { ( (&((*inner_val)) as *const _) as *mut _) }, is_owned: false }
+}
+/// Counter-party public keys
+#[no_mangle]
+pub extern "C" fn CounterpartyChannelTransactionParameters_set_pubkeys(this_ptr: &mut CounterpartyChannelTransactionParameters, mut val: crate::ln::chan_utils::ChannelPublicKeys) {
+       unsafe { &mut *this_ptr.inner }.pubkeys = *unsafe { Box::from_raw(val.take_inner()) };
+}
+/// The contest delay selected by the counterparty, which applies to holder-broadcast transactions
+#[no_mangle]
+pub extern "C" fn CounterpartyChannelTransactionParameters_get_selected_contest_delay(this_ptr: &CounterpartyChannelTransactionParameters) -> u16 {
+       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.selected_contest_delay;
+       (*inner_val)
+}
+/// The contest delay selected by the counterparty, which applies to holder-broadcast transactions
+#[no_mangle]
+pub extern "C" fn CounterpartyChannelTransactionParameters_set_selected_contest_delay(this_ptr: &mut CounterpartyChannelTransactionParameters, mut val: u16) {
+       unsafe { &mut *this_ptr.inner }.selected_contest_delay = val;
+}
+#[must_use]
+#[no_mangle]
+pub extern "C" fn CounterpartyChannelTransactionParameters_new(mut pubkeys_arg: crate::ln::chan_utils::ChannelPublicKeys, mut selected_contest_delay_arg: u16) -> CounterpartyChannelTransactionParameters {
+       CounterpartyChannelTransactionParameters { inner: Box::into_raw(Box::new(nativeCounterpartyChannelTransactionParameters {
+               pubkeys: *unsafe { Box::from_raw(pubkeys_arg.take_inner()) },
+               selected_contest_delay: selected_contest_delay_arg,
+       })), is_owned: true }
+}
+impl Clone for CounterpartyChannelTransactionParameters {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn CounterpartyChannelTransactionParameters_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeCounterpartyChannelTransactionParameters)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn CounterpartyChannelTransactionParameters_clone(orig: &CounterpartyChannelTransactionParameters) -> CounterpartyChannelTransactionParameters {
+       orig.clone()
+}
+/// Whether the late bound parameters are populated.
+#[must_use]
+#[no_mangle]
+pub extern "C" fn ChannelTransactionParameters_is_populated(this_arg: &ChannelTransactionParameters) -> bool {
+       let mut ret = unsafe { &*this_arg.inner }.is_populated();
+       ret
+}
+
+/// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
+/// given that the holder is the broadcaster.
+///
+/// self.is_populated() must be true before calling this function.
+#[must_use]
+#[no_mangle]
+pub extern "C" fn ChannelTransactionParameters_as_holder_broadcastable(this_arg: &ChannelTransactionParameters) -> crate::ln::chan_utils::DirectedChannelTransactionParameters {
+       let mut ret = unsafe { &*this_arg.inner }.as_holder_broadcastable();
+       crate::ln::chan_utils::DirectedChannelTransactionParameters { inner: Box::into_raw(Box::new(ret)), is_owned: true }
+}
+
+/// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
+/// given that the counterparty is the broadcaster.
+///
+/// self.is_populated() must be true before calling this function.
+#[must_use]
+#[no_mangle]
+pub extern "C" fn ChannelTransactionParameters_as_counterparty_broadcastable(this_arg: &ChannelTransactionParameters) -> crate::ln::chan_utils::DirectedChannelTransactionParameters {
+       let mut ret = unsafe { &*this_arg.inner }.as_counterparty_broadcastable();
+       crate::ln::chan_utils::DirectedChannelTransactionParameters { inner: Box::into_raw(Box::new(ret)), is_owned: true }
+}
+
+#[no_mangle]
+pub extern "C" fn CounterpartyChannelTransactionParameters_write(obj: &CounterpartyChannelTransactionParameters) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+}
+#[no_mangle]
+pub(crate) extern "C" fn CounterpartyChannelTransactionParameters_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeCounterpartyChannelTransactionParameters) })
+}
+#[no_mangle]
+pub extern "C" fn CounterpartyChannelTransactionParameters_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_CounterpartyChannelTransactionParametersDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::chan_utils::CounterpartyChannelTransactionParameters { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
+}
+#[no_mangle]
+pub extern "C" fn ChannelTransactionParameters_write(obj: &ChannelTransactionParameters) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+}
+#[no_mangle]
+pub(crate) extern "C" fn ChannelTransactionParameters_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeChannelTransactionParameters) })
+}
+#[no_mangle]
+pub extern "C" fn ChannelTransactionParameters_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelTransactionParametersDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::chan_utils::ChannelTransactionParameters { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
+}
+
+use lightning::ln::chan_utils::DirectedChannelTransactionParameters as nativeDirectedChannelTransactionParametersImport;
+type nativeDirectedChannelTransactionParameters = nativeDirectedChannelTransactionParametersImport<'static>;
+
+/// Static channel fields used to build transactions given per-commitment fields, organized by
+/// broadcaster/countersignatory.
+///
+/// This is derived from the holder/counterparty-organized ChannelTransactionParameters via the
+/// as_holder_broadcastable and as_counterparty_broadcastable functions.
+#[must_use]
+#[repr(C)]
+pub struct DirectedChannelTransactionParameters {
+       /// Nearly everywhere, inner must be non-null, however in places where
+       /// the Rust equivalent takes an Option, it may be set to null to indicate None.
+       pub inner: *mut nativeDirectedChannelTransactionParameters,
+       pub is_owned: bool,
+}
+
+impl Drop for DirectedChannelTransactionParameters {
+       fn drop(&mut self) {
+               if self.is_owned && !self.inner.is_null() {
+                       let _ = unsafe { Box::from_raw(self.inner) };
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn DirectedChannelTransactionParameters_free(this_ptr: DirectedChannelTransactionParameters) { }
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+extern "C" fn DirectedChannelTransactionParameters_free_void(this_ptr: *mut c_void) {
+       unsafe { let _ = Box::from_raw(this_ptr as *mut nativeDirectedChannelTransactionParameters); }
+}
+#[allow(unused)]
+/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
+impl DirectedChannelTransactionParameters {
+       pub(crate) fn take_inner(mut self) -> *mut nativeDirectedChannelTransactionParameters {
+               assert!(self.is_owned);
+               let ret = self.inner;
+               self.inner = std::ptr::null_mut();
+               ret
+       }
+}
+/// Get the channel pubkeys for the broadcaster
+#[must_use]
+#[no_mangle]
+pub extern "C" fn DirectedChannelTransactionParameters_broadcaster_pubkeys(this_arg: &DirectedChannelTransactionParameters) -> crate::ln::chan_utils::ChannelPublicKeys {
+       let mut ret = unsafe { &*this_arg.inner }.broadcaster_pubkeys();
+       crate::ln::chan_utils::ChannelPublicKeys { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false }
+}
+
+/// Get the channel pubkeys for the countersignatory
+#[must_use]
+#[no_mangle]
+pub extern "C" fn DirectedChannelTransactionParameters_countersignatory_pubkeys(this_arg: &DirectedChannelTransactionParameters) -> crate::ln::chan_utils::ChannelPublicKeys {
+       let mut ret = unsafe { &*this_arg.inner }.countersignatory_pubkeys();
+       crate::ln::chan_utils::ChannelPublicKeys { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false }
+}
+
+/// Get the contest delay applicable to the transactions.
+/// Note that the contest delay was selected by the countersignatory.
+#[must_use]
+#[no_mangle]
+pub extern "C" fn DirectedChannelTransactionParameters_contest_delay(this_arg: &DirectedChannelTransactionParameters) -> u16 {
+       let mut ret = unsafe { &*this_arg.inner }.contest_delay();
+       ret
+}
+
+/// Whether the channel is outbound from the broadcaster.
+///
+/// The boolean representing the side that initiated the channel is
+/// an input to the commitment number obscure factor computation.
+#[must_use]
+#[no_mangle]
+pub extern "C" fn DirectedChannelTransactionParameters_is_outbound(this_arg: &DirectedChannelTransactionParameters) -> bool {
+       let mut ret = unsafe { &*this_arg.inner }.is_outbound();
+       ret
+}
+
+/// The funding outpoint
+#[must_use]
+#[no_mangle]
+pub extern "C" fn DirectedChannelTransactionParameters_funding_outpoint(this_arg: &DirectedChannelTransactionParameters) -> crate::chain::transaction::OutPoint {
+       let mut ret = unsafe { &*this_arg.inner }.funding_outpoint();
+       crate::c_types::bitcoin_to_C_outpoint(ret)
+}
+
+
 use lightning::ln::chan_utils::HolderCommitmentTransaction as nativeHolderCommitmentTransactionImport;
 type nativeHolderCommitmentTransaction = nativeHolderCommitmentTransactionImport;
 
-/// We use this to track holder commitment transactions and put off signing them until we are ready
-/// to broadcast. This class can be used inside a signer implementation to generate a signature
-/// given the relevant secret key.
+/// Information needed to build and sign a holder's commitment transaction.
+///
+/// The transaction is only signed once we are ready to broadcast.
 #[must_use]
 #[repr(C)]
 pub struct HolderCommitmentTransaction {
@@ -647,17 +952,35 @@ extern "C" fn HolderCommitmentTransaction_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl HolderCommitmentTransaction {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeHolderCommitmentTransaction {
+       pub(crate) fn take_inner(mut self) -> *mut nativeHolderCommitmentTransaction {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
+/// Our counterparty's signature for the transaction
+#[no_mangle]
+pub extern "C" fn HolderCommitmentTransaction_get_counterparty_sig(this_ptr: &HolderCommitmentTransaction) -> crate::c_types::Signature {
+       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.counterparty_sig;
+       crate::c_types::Signature::from_rust(&(*inner_val))
+}
+/// Our counterparty's signature for the transaction
+#[no_mangle]
+pub extern "C" fn HolderCommitmentTransaction_set_counterparty_sig(this_ptr: &mut HolderCommitmentTransaction, mut val: crate::c_types::Signature) {
+       unsafe { &mut *this_ptr.inner }.counterparty_sig = val.into_rust();
+}
+/// All non-dust counterparty HTLC signatures, in the order they appear in the transaction
+#[no_mangle]
+pub extern "C" fn HolderCommitmentTransaction_set_counterparty_htlc_sigs(this_ptr: &mut HolderCommitmentTransaction, mut val: crate::c_types::derived::CVec_SignatureZ) {
+       let mut local_val = Vec::new(); for mut item in val.into_rust().drain(..) { local_val.push( { item.into_rust() }); };
+       unsafe { &mut *this_ptr.inner }.counterparty_htlc_sigs = local_val;
+}
 impl Clone for HolderCommitmentTransaction {
        fn clone(&self) -> Self {
                Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
                        is_owned: true,
                }
        }
@@ -669,126 +992,375 @@ pub(crate) extern "C" fn HolderCommitmentTransaction_clone_void(this_ptr: *const
 }
 #[no_mangle]
 pub extern "C" fn HolderCommitmentTransaction_clone(orig: &HolderCommitmentTransaction) -> HolderCommitmentTransaction {
-       HolderCommitmentTransaction { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
+       orig.clone()
+}
+#[no_mangle]
+pub extern "C" fn HolderCommitmentTransaction_write(obj: &HolderCommitmentTransaction) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+}
+#[no_mangle]
+pub(crate) extern "C" fn HolderCommitmentTransaction_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeHolderCommitmentTransaction) })
+}
+#[no_mangle]
+pub extern "C" fn HolderCommitmentTransaction_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_HolderCommitmentTransactionDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::chan_utils::HolderCommitmentTransaction { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
+}
+/// Create a new holder transaction with the given counterparty signatures.
+/// The funding keys are used to figure out which signature should go first when building the transaction for broadcast.
+#[must_use]
+#[no_mangle]
+pub extern "C" fn HolderCommitmentTransaction_new(mut commitment_tx: crate::ln::chan_utils::CommitmentTransaction, mut counterparty_sig: crate::c_types::Signature, mut counterparty_htlc_sigs: crate::c_types::derived::CVec_SignatureZ, mut holder_funding_key: crate::c_types::PublicKey, mut counterparty_funding_key: crate::c_types::PublicKey) -> HolderCommitmentTransaction {
+       let mut local_counterparty_htlc_sigs = Vec::new(); for mut item in counterparty_htlc_sigs.into_rust().drain(..) { local_counterparty_htlc_sigs.push( { item.into_rust() }); };
+       let mut ret = lightning::ln::chan_utils::HolderCommitmentTransaction::new(*unsafe { Box::from_raw(commitment_tx.take_inner()) }, counterparty_sig.into_rust(), local_counterparty_htlc_sigs, &holder_funding_key.into_rust(), &counterparty_funding_key.into_rust());
+       HolderCommitmentTransaction { inner: Box::into_raw(Box::new(ret)), is_owned: true }
+}
+
+
+use lightning::ln::chan_utils::BuiltCommitmentTransaction as nativeBuiltCommitmentTransactionImport;
+type nativeBuiltCommitmentTransaction = nativeBuiltCommitmentTransactionImport;
+
+/// A pre-built Bitcoin commitment transaction and its txid.
+#[must_use]
+#[repr(C)]
+pub struct BuiltCommitmentTransaction {
+       /// Nearly everywhere, inner must be non-null, however in places where
+       /// the Rust equivalent takes an Option, it may be set to null to indicate None.
+       pub inner: *mut nativeBuiltCommitmentTransaction,
+       pub is_owned: bool,
+}
+
+impl Drop for BuiltCommitmentTransaction {
+       fn drop(&mut self) {
+               if self.is_owned && !self.inner.is_null() {
+                       let _ = unsafe { Box::from_raw(self.inner) };
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn BuiltCommitmentTransaction_free(this_ptr: BuiltCommitmentTransaction) { }
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+extern "C" fn BuiltCommitmentTransaction_free_void(this_ptr: *mut c_void) {
+       unsafe { let _ = Box::from_raw(this_ptr as *mut nativeBuiltCommitmentTransaction); }
+}
+#[allow(unused)]
+/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
+impl BuiltCommitmentTransaction {
+       pub(crate) fn take_inner(mut self) -> *mut nativeBuiltCommitmentTransaction {
+               assert!(self.is_owned);
+               let ret = self.inner;
+               self.inner = std::ptr::null_mut();
+               ret
+       }
 }
-/// The commitment transaction itself, in unsigned form.
+/// The commitment transaction
 #[no_mangle]
-pub extern "C" fn HolderCommitmentTransaction_get_unsigned_tx(this_ptr: &HolderCommitmentTransaction) -> crate::c_types::Transaction {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.unsigned_tx;
+pub extern "C" fn BuiltCommitmentTransaction_get_transaction(this_ptr: &BuiltCommitmentTransaction) -> crate::c_types::Transaction {
+       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.transaction;
        let mut local_inner_val = ::bitcoin::consensus::encode::serialize(inner_val);
        crate::c_types::Transaction::from_vec(local_inner_val)
 }
-/// The commitment transaction itself, in unsigned form.
+/// The commitment transaction
 #[no_mangle]
-pub extern "C" fn HolderCommitmentTransaction_set_unsigned_tx(this_ptr: &mut HolderCommitmentTransaction, mut val: crate::c_types::Transaction) {
-       unsafe { &mut *this_ptr.inner }.unsigned_tx = val.into_bitcoin();
+pub extern "C" fn BuiltCommitmentTransaction_set_transaction(this_ptr: &mut BuiltCommitmentTransaction, mut val: crate::c_types::Transaction) {
+       unsafe { &mut *this_ptr.inner }.transaction = val.into_bitcoin();
 }
-/// Our counterparty's signature for the transaction, above.
+/// The txid for the commitment transaction.
+///
+/// This is provided as a performance optimization, instead of calling transaction.txid()
+/// multiple times.
 #[no_mangle]
-pub extern "C" fn HolderCommitmentTransaction_get_counterparty_sig(this_ptr: &HolderCommitmentTransaction) -> crate::c_types::Signature {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.counterparty_sig;
-       crate::c_types::Signature::from_rust(&(*inner_val))
+pub extern "C" fn BuiltCommitmentTransaction_get_txid(this_ptr: &BuiltCommitmentTransaction) -> *const [u8; 32] {
+       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.txid;
+       (*inner_val).as_inner()
 }
-/// Our counterparty's signature for the transaction, above.
+/// The txid for the commitment transaction.
+///
+/// This is provided as a performance optimization, instead of calling transaction.txid()
+/// multiple times.
 #[no_mangle]
-pub extern "C" fn HolderCommitmentTransaction_set_counterparty_sig(this_ptr: &mut HolderCommitmentTransaction, mut val: crate::c_types::Signature) {
-       unsafe { &mut *this_ptr.inner }.counterparty_sig = val.into_rust();
+pub extern "C" fn BuiltCommitmentTransaction_set_txid(this_ptr: &mut BuiltCommitmentTransaction, mut val: crate::c_types::ThirtyTwoBytes) {
+       unsafe { &mut *this_ptr.inner }.txid = ::bitcoin::hash_types::Txid::from_slice(&val.data[..]).unwrap();
 }
-/// The feerate paid per 1000-weight-unit in this commitment transaction. This value is
-/// controlled by the channel initiator.
+#[must_use]
 #[no_mangle]
-pub extern "C" fn HolderCommitmentTransaction_get_feerate_per_kw(this_ptr: &HolderCommitmentTransaction) -> u32 {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.feerate_per_kw;
-       (*inner_val)
+pub extern "C" fn BuiltCommitmentTransaction_new(mut transaction_arg: crate::c_types::Transaction, mut txid_arg: crate::c_types::ThirtyTwoBytes) -> BuiltCommitmentTransaction {
+       BuiltCommitmentTransaction { inner: Box::into_raw(Box::new(nativeBuiltCommitmentTransaction {
+               transaction: transaction_arg.into_bitcoin(),
+               txid: ::bitcoin::hash_types::Txid::from_slice(&txid_arg.data[..]).unwrap(),
+       })), is_owned: true }
+}
+impl Clone for BuiltCommitmentTransaction {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn BuiltCommitmentTransaction_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeBuiltCommitmentTransaction)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn BuiltCommitmentTransaction_clone(orig: &BuiltCommitmentTransaction) -> BuiltCommitmentTransaction {
+       orig.clone()
+}
+#[no_mangle]
+pub extern "C" fn BuiltCommitmentTransaction_write(obj: &BuiltCommitmentTransaction) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+}
+#[no_mangle]
+pub(crate) extern "C" fn BuiltCommitmentTransaction_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeBuiltCommitmentTransaction) })
 }
-/// The feerate paid per 1000-weight-unit in this commitment transaction. This value is
-/// controlled by the channel initiator.
 #[no_mangle]
-pub extern "C" fn HolderCommitmentTransaction_set_feerate_per_kw(this_ptr: &mut HolderCommitmentTransaction, mut val: u32) {
-       unsafe { &mut *this_ptr.inner }.feerate_per_kw = val;
+pub extern "C" fn BuiltCommitmentTransaction_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_BuiltCommitmentTransactionDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::chan_utils::BuiltCommitmentTransaction { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
 }
-/// The HTLCs and counterparty htlc signatures which were included in this commitment transaction.
+/// Get the SIGHASH_ALL sighash value of the transaction.
 ///
-/// Note that this includes all HTLCs, including ones which were considered dust and not
-/// actually included in the transaction as it appears on-chain, but who's value is burned as
-/// fees and not included in the to_holder or to_counterparty outputs.
+/// This can be used to verify a signature.
+#[must_use]
+#[no_mangle]
+pub extern "C" fn BuiltCommitmentTransaction_get_sighash_all(this_arg: &BuiltCommitmentTransaction, mut funding_redeemscript: crate::c_types::u8slice, mut channel_value_satoshis: u64) -> crate::c_types::ThirtyTwoBytes {
+       let mut ret = unsafe { &*this_arg.inner }.get_sighash_all(&::bitcoin::blockdata::script::Script::from(Vec::from(funding_redeemscript.to_slice())), channel_value_satoshis);
+       crate::c_types::ThirtyTwoBytes { data: ret.as_ref().clone() }
+}
+
+/// Sign a transaction, either because we are counter-signing the counterparty's transaction or
+/// because we are about to broadcast a holder transaction.
+#[must_use]
+#[no_mangle]
+pub extern "C" fn BuiltCommitmentTransaction_sign(this_arg: &BuiltCommitmentTransaction, funding_key: *const [u8; 32], mut funding_redeemscript: crate::c_types::u8slice, mut channel_value_satoshis: u64) -> crate::c_types::Signature {
+       let mut ret = unsafe { &*this_arg.inner }.sign(&::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *funding_key}[..]).unwrap(), &::bitcoin::blockdata::script::Script::from(Vec::from(funding_redeemscript.to_slice())), channel_value_satoshis, secp256k1::SECP256K1);
+       crate::c_types::Signature::from_rust(&ret)
+}
+
+
+use lightning::ln::chan_utils::CommitmentTransaction as nativeCommitmentTransactionImport;
+type nativeCommitmentTransaction = nativeCommitmentTransactionImport;
+
+/// This class tracks the per-transaction information needed to build a commitment transaction and to
+/// actually build it and sign.  It is used for holder transactions that we sign only when needed
+/// and for transactions we sign for the counterparty.
 ///
-/// The counterparty HTLC signatures in the second element will always be set for non-dust HTLCs, ie
-/// those for which transaction_output_index.is_some().
+/// This class can be used inside a signer implementation to generate a signature given the relevant
+/// secret key.
+#[must_use]
+#[repr(C)]
+pub struct CommitmentTransaction {
+       /// Nearly everywhere, inner must be non-null, however in places where
+       /// the Rust equivalent takes an Option, it may be set to null to indicate None.
+       pub inner: *mut nativeCommitmentTransaction,
+       pub is_owned: bool,
+}
+
+impl Drop for CommitmentTransaction {
+       fn drop(&mut self) {
+               if self.is_owned && !self.inner.is_null() {
+                       let _ = unsafe { Box::from_raw(self.inner) };
+               }
+       }
+}
+#[no_mangle]
+pub extern "C" fn CommitmentTransaction_free(this_ptr: CommitmentTransaction) { }
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+extern "C" fn CommitmentTransaction_free_void(this_ptr: *mut c_void) {
+       unsafe { let _ = Box::from_raw(this_ptr as *mut nativeCommitmentTransaction); }
+}
+#[allow(unused)]
+/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
+impl CommitmentTransaction {
+       pub(crate) fn take_inner(mut self) -> *mut nativeCommitmentTransaction {
+               assert!(self.is_owned);
+               let ret = self.inner;
+               self.inner = std::ptr::null_mut();
+               ret
+       }
+}
+impl Clone for CommitmentTransaction {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn CommitmentTransaction_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeCommitmentTransaction)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn CommitmentTransaction_clone(orig: &CommitmentTransaction) -> CommitmentTransaction {
+       orig.clone()
+}
+#[no_mangle]
+pub extern "C" fn CommitmentTransaction_write(obj: &CommitmentTransaction) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+}
+#[no_mangle]
+pub(crate) extern "C" fn CommitmentTransaction_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeCommitmentTransaction) })
+}
 #[no_mangle]
-pub extern "C" fn HolderCommitmentTransaction_set_per_htlc(this_ptr: &mut HolderCommitmentTransaction, mut val: crate::c_types::derived::CVec_C2Tuple_HTLCOutputInCommitmentSignatureZZ) {
-       let mut local_val = Vec::new(); for mut item in val.into_rust().drain(..) { local_val.push( { let (mut orig_val_0_0, mut orig_val_0_1) = item.to_rust(); let mut local_orig_val_0_1 = if orig_val_0_1.is_null() { None } else { Some( { orig_val_0_1.into_rust() }) }; let mut local_val_0 = (*unsafe { Box::from_raw(orig_val_0_0.take_ptr()) }, local_orig_val_0_1); local_val_0 }); };
-       unsafe { &mut *this_ptr.inner }.per_htlc = local_val;
+pub extern "C" fn CommitmentTransaction_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_CommitmentTransactionDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::chan_utils::CommitmentTransaction { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
 }
-/// Generate a new HolderCommitmentTransaction based on a raw commitment transaction,
-/// counterparty signature and both parties keys.
+/// The backwards-counting commitment number
+#[must_use]
+#[no_mangle]
+pub extern "C" fn CommitmentTransaction_commitment_number(this_arg: &CommitmentTransaction) -> u64 {
+       let mut ret = unsafe { &*this_arg.inner }.commitment_number();
+       ret
+}
+
+/// The value to be sent to the broadcaster
+#[must_use]
+#[no_mangle]
+pub extern "C" fn CommitmentTransaction_to_broadcaster_value_sat(this_arg: &CommitmentTransaction) -> u64 {
+       let mut ret = unsafe { &*this_arg.inner }.to_broadcaster_value_sat();
+       ret
+}
+
+/// The value to be sent to the counterparty
+#[must_use]
+#[no_mangle]
+pub extern "C" fn CommitmentTransaction_to_countersignatory_value_sat(this_arg: &CommitmentTransaction) -> u64 {
+       let mut ret = unsafe { &*this_arg.inner }.to_countersignatory_value_sat();
+       ret
+}
+
+/// The feerate paid per 1000-weight-unit in this commitment transaction.
+#[must_use]
+#[no_mangle]
+pub extern "C" fn CommitmentTransaction_feerate_per_kw(this_arg: &CommitmentTransaction) -> u32 {
+       let mut ret = unsafe { &*this_arg.inner }.feerate_per_kw();
+       ret
+}
+
+/// Trust our pre-built transaction and derived transaction creation public keys.
 ///
-/// The unsigned transaction outputs must be consistent with htlc_data.  This function
-/// only checks that the shape and amounts are consistent, but does not check the scriptPubkey.
+/// Applies a wrapper which allows access to these fields.
+///
+/// This should only be used if you fully trust the builder of this object.  It should not
+///\tbe used by an external signer - instead use the verify function.
 #[must_use]
 #[no_mangle]
-pub extern "C" fn HolderCommitmentTransaction_new_missing_holder_sig(mut unsigned_tx: crate::c_types::Transaction, mut counterparty_sig: crate::c_types::Signature, mut holder_funding_key: crate::c_types::PublicKey, mut counterparty_funding_key: crate::c_types::PublicKey, mut keys: crate::ln::chan_utils::TxCreationKeys, mut feerate_per_kw: u32, mut htlc_data: crate::c_types::derived::CVec_C2Tuple_HTLCOutputInCommitmentSignatureZZ) -> crate::ln::chan_utils::HolderCommitmentTransaction {
-       let mut local_htlc_data = Vec::new(); for mut item in htlc_data.into_rust().drain(..) { local_htlc_data.push( { let (mut orig_htlc_data_0_0, mut orig_htlc_data_0_1) = item.to_rust(); let mut local_orig_htlc_data_0_1 = if orig_htlc_data_0_1.is_null() { None } else { Some( { orig_htlc_data_0_1.into_rust() }) }; let mut local_htlc_data_0 = (*unsafe { Box::from_raw(orig_htlc_data_0_0.take_ptr()) }, local_orig_htlc_data_0_1); local_htlc_data_0 }); };
-       let mut ret = lightning::ln::chan_utils::HolderCommitmentTransaction::new_missing_holder_sig(unsigned_tx.into_bitcoin(), counterparty_sig.into_rust(), &holder_funding_key.into_rust(), &counterparty_funding_key.into_rust(), *unsafe { Box::from_raw(keys.take_ptr()) }, feerate_per_kw, local_htlc_data);
-       crate::ln::chan_utils::HolderCommitmentTransaction { inner: Box::into_raw(Box::new(ret)), is_owned: true }
+pub extern "C" fn CommitmentTransaction_trust(this_arg: &CommitmentTransaction) -> crate::ln::chan_utils::TrustedCommitmentTransaction {
+       let mut ret = unsafe { &*this_arg.inner }.trust();
+       crate::ln::chan_utils::TrustedCommitmentTransaction { inner: Box::into_raw(Box::new(ret)), is_owned: true }
 }
 
-/// The pre-calculated transaction creation public keys.
-/// An external validating signer should not trust these keys.
+/// Verify our pre-built transaction and derived transaction creation public keys.
+///
+/// Applies a wrapper which allows access to these fields.
+///
+/// An external validating signer must call this method before signing
+/// or using the built transaction.
 #[must_use]
 #[no_mangle]
-pub extern "C" fn HolderCommitmentTransaction_trust_key_derivation(this_arg: &HolderCommitmentTransaction) -> crate::ln::chan_utils::TxCreationKeys {
-       let mut ret = unsafe { &*this_arg.inner }.trust_key_derivation();
-       crate::ln::chan_utils::TxCreationKeys { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false }
+pub extern "C" fn CommitmentTransaction_verify(this_arg: &CommitmentTransaction, channel_parameters: &crate::ln::chan_utils::DirectedChannelTransactionParameters, broadcaster_keys: &crate::ln::chan_utils::ChannelPublicKeys, countersignatory_keys: &crate::ln::chan_utils::ChannelPublicKeys) -> crate::c_types::derived::CResult_TrustedCommitmentTransactionNoneZ {
+       let mut ret = unsafe { &*this_arg.inner }.verify(unsafe { &*channel_parameters.inner }, unsafe { &*broadcaster_keys.inner }, unsafe { &*countersignatory_keys.inner }, secp256k1::SECP256K1);
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::chan_utils::TrustedCommitmentTransaction { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }).into() };
+       local_ret
 }
 
-/// Get the txid of the holder commitment transaction contained in this
-/// HolderCommitmentTransaction
+
+use lightning::ln::chan_utils::TrustedCommitmentTransaction as nativeTrustedCommitmentTransactionImport;
+type nativeTrustedCommitmentTransaction = nativeTrustedCommitmentTransactionImport<'static>;
+
+/// A wrapper on CommitmentTransaction indicating that the derived fields (the built bitcoin
+/// transaction and the transaction creation keys) are trusted.
+///
+/// See trust() and verify() functions on CommitmentTransaction.
+///
+/// This structure implements Deref.
 #[must_use]
+#[repr(C)]
+pub struct TrustedCommitmentTransaction {
+       /// Nearly everywhere, inner must be non-null, however in places where
+       /// the Rust equivalent takes an Option, it may be set to null to indicate None.
+       pub inner: *mut nativeTrustedCommitmentTransaction,
+       pub is_owned: bool,
+}
+
+impl Drop for TrustedCommitmentTransaction {
+       fn drop(&mut self) {
+               if self.is_owned && !self.inner.is_null() {
+                       let _ = unsafe { Box::from_raw(self.inner) };
+               }
+       }
+}
 #[no_mangle]
-pub extern "C" fn HolderCommitmentTransaction_txid(this_arg: &HolderCommitmentTransaction) -> crate::c_types::ThirtyTwoBytes {
+pub extern "C" fn TrustedCommitmentTransaction_free(this_ptr: TrustedCommitmentTransaction) { }
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+extern "C" fn TrustedCommitmentTransaction_free_void(this_ptr: *mut c_void) {
+       unsafe { let _ = Box::from_raw(this_ptr as *mut nativeTrustedCommitmentTransaction); }
+}
+#[allow(unused)]
+/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
+impl TrustedCommitmentTransaction {
+       pub(crate) fn take_inner(mut self) -> *mut nativeTrustedCommitmentTransaction {
+               assert!(self.is_owned);
+               let ret = self.inner;
+               self.inner = std::ptr::null_mut();
+               ret
+       }
+}
+/// The transaction ID of the built Bitcoin transaction
+#[must_use]
+#[no_mangle]
+pub extern "C" fn TrustedCommitmentTransaction_txid(this_arg: &TrustedCommitmentTransaction) -> crate::c_types::ThirtyTwoBytes {
        let mut ret = unsafe { &*this_arg.inner }.txid();
        crate::c_types::ThirtyTwoBytes { data: ret.into_inner() }
 }
 
-/// Gets holder signature for the contained commitment transaction given holder funding private key.
-///
-/// Funding key is your key included in the 2-2 funding_outpoint lock. Should be provided
-/// by your ChannelKeys.
-/// Funding redeemscript is script locking funding_outpoint. This is the mutlsig script
-/// between your own funding key and your counterparty's. Currently, this is provided in
-/// ChannelKeys::sign_holder_commitment() calls directly.
-/// Channel value is amount locked in funding_outpoint.
+/// The pre-built Bitcoin commitment transaction
 #[must_use]
 #[no_mangle]
-pub extern "C" fn HolderCommitmentTransaction_get_holder_sig(this_arg: &HolderCommitmentTransaction, funding_key: *const [u8; 32], mut funding_redeemscript: crate::c_types::u8slice, mut channel_value_satoshis: u64) -> crate::c_types::Signature {
-       let mut ret = unsafe { &*this_arg.inner }.get_holder_sig(&::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *funding_key}[..]).unwrap(), &::bitcoin::blockdata::script::Script::from(Vec::from(funding_redeemscript.to_slice())), channel_value_satoshis, &bitcoin::secp256k1::Secp256k1::new());
-       crate::c_types::Signature::from_rust(&ret)
+pub extern "C" fn TrustedCommitmentTransaction_built_transaction(this_arg: &TrustedCommitmentTransaction) -> crate::ln::chan_utils::BuiltCommitmentTransaction {
+       let mut ret = unsafe { &*this_arg.inner }.built_transaction();
+       crate::ln::chan_utils::BuiltCommitmentTransaction { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false }
+}
+
+/// The pre-calculated transaction creation public keys.
+#[must_use]
+#[no_mangle]
+pub extern "C" fn TrustedCommitmentTransaction_keys(this_arg: &TrustedCommitmentTransaction) -> crate::ln::chan_utils::TxCreationKeys {
+       let mut ret = unsafe { &*this_arg.inner }.keys();
+       crate::ln::chan_utils::TxCreationKeys { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false }
 }
 
 /// Get a signature for each HTLC which was included in the commitment transaction (ie for
 /// which HTLCOutputInCommitment::transaction_output_index.is_some()).
 ///
-/// The returned Vec has one entry for each HTLC, and in the same order. For HTLCs which were
-/// considered dust and not included, a None entry exists, for all others a signature is
-/// included.
+/// The returned Vec has one entry for each HTLC, and in the same order.
 #[must_use]
 #[no_mangle]
-pub extern "C" fn HolderCommitmentTransaction_get_htlc_sigs(this_arg: &HolderCommitmentTransaction, htlc_base_key: *const [u8; 32], mut counterparty_selected_contest_delay: u16) -> crate::c_types::derived::CResult_CVec_SignatureZNoneZ {
-       let mut ret = unsafe { &*this_arg.inner }.get_htlc_sigs(&::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *htlc_base_key}[..]).unwrap(), counterparty_selected_contest_delay, &bitcoin::secp256k1::Secp256k1::new());
-       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let mut local_ret_0 = Vec::new(); for item in o.drain(..) { local_ret_0.push( { let mut local_ret_0_0 = if item.is_none() { crate::c_types::Signature::null() } else {  { crate::c_types::Signature::from_rust(&(item.unwrap())) } }; local_ret_0_0 }); }; local_ret_0.into() }), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }) };
+pub extern "C" fn TrustedCommitmentTransaction_get_htlc_sigs(this_arg: &TrustedCommitmentTransaction, htlc_base_key: *const [u8; 32], channel_parameters: &crate::ln::chan_utils::DirectedChannelTransactionParameters) -> crate::c_types::derived::CResult_CVec_SignatureZNoneZ {
+       let mut ret = unsafe { &*this_arg.inner }.get_htlc_sigs(&::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *htlc_base_key}[..]).unwrap(), unsafe { &*channel_parameters.inner }, secp256k1::SECP256K1);
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let mut local_ret_0 = Vec::new(); for mut item in o.drain(..) { local_ret_0.push( { crate::c_types::Signature::from_rust(&item) }); }; local_ret_0.into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }).into() };
        local_ret
 }
 
+/// Get the transaction number obscure factor
 #[no_mangle]
-pub extern "C" fn HolderCommitmentTransaction_write(obj: *const HolderCommitmentTransaction) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
-}
-#[no_mangle]
-pub extern "C" fn HolderCommitmentTransaction_read(ser: crate::c_types::u8slice) -> HolderCommitmentTransaction {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               HolderCommitmentTransaction { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               HolderCommitmentTransaction { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub extern "C" fn get_commitment_transaction_number_obscure_factor(mut broadcaster_payment_basepoint: crate::c_types::PublicKey, mut countersignatory_payment_basepoint: crate::c_types::PublicKey, mut outbound_from_broadcaster: bool) -> u64 {
+       let mut ret = lightning::ln::chan_utils::get_commitment_transaction_number_obscure_factor(&broadcaster_payment_basepoint.into_rust(), &countersignatory_payment_basepoint.into_rust(), outbound_from_broadcaster);
+       ret
 }
+
index c21f26e94e05bfc2c7c3bb4069f4135293e10f5f..a175a2ce917a8ceeca8bdb96efc88c73f0a145e9 100644 (file)
@@ -15,7 +15,7 @@ use crate::c_types::*;
 
 
 use lightning::ln::channelmanager::ChannelManager as nativeChannelManagerImport;
-type nativeChannelManager = nativeChannelManagerImport<crate::chain::keysinterface::ChannelKeys, crate::chain::Watch, crate::chain::chaininterface::BroadcasterInterface, crate::chain::keysinterface::KeysInterface, crate::chain::chaininterface::FeeEstimator, crate::util::logger::Logger>;
+type nativeChannelManager = nativeChannelManagerImport<crate::chain::keysinterface::Sign, crate::chain::Watch, crate::chain::chaininterface::BroadcasterInterface, crate::chain::keysinterface::KeysInterface, crate::chain::chaininterface::FeeEstimator, crate::util::logger::Logger>;
 
 /// Manager which keeps track of a number of channels and sends messages to the appropriate
 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
@@ -79,7 +79,7 @@ extern "C" fn ChannelManager_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl ChannelManager {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeChannelManager {
+       pub(crate) fn take_inner(mut self) -> *mut nativeChannelManager {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
@@ -117,30 +117,13 @@ extern "C" fn ChannelDetails_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl ChannelDetails {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeChannelDetails {
+       pub(crate) fn take_inner(mut self) -> *mut nativeChannelDetails {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for ChannelDetails {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn ChannelDetails_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelDetails)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn ChannelDetails_clone(orig: &ChannelDetails) -> ChannelDetails {
-       ChannelDetails { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
 /// thereafter this is the txid of the funding transaction xor the funding transaction output).
 /// Note that this means this value is *not* persistent - it can change once during the
@@ -175,14 +158,14 @@ pub extern "C" fn ChannelDetails_set_remote_network_id(this_ptr: &mut ChannelDet
 #[no_mangle]
 pub extern "C" fn ChannelDetails_get_counterparty_features(this_ptr: &ChannelDetails) -> crate::ln::features::InitFeatures {
        let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.counterparty_features;
-       crate::ln::features::InitFeatures { inner: &mut (*inner_val), is_owned: false }
+       crate::ln::features::InitFeatures { inner: unsafe { ( (&((*inner_val)) as *const _) as *mut _) }, is_owned: false }
 }
 /// The Features the channel counterparty provided upon last connection.
 /// Useful for routing as it is the most up-to-date copy of the counterparty's features and
 /// many routing-relevant features are present in the init context.
 #[no_mangle]
 pub extern "C" fn ChannelDetails_set_counterparty_features(this_ptr: &mut ChannelDetails, mut val: crate::ln::features::InitFeatures) {
-       unsafe { &mut *this_ptr.inner }.counterparty_features = *unsafe { Box::from_raw(val.take_ptr()) };
+       unsafe { &mut *this_ptr.inner }.counterparty_features = *unsafe { Box::from_raw(val.take_inner()) };
 }
 /// The value, in satoshis, of this channel as appears in the funding output
 #[no_mangle]
@@ -255,45 +238,189 @@ pub extern "C" fn ChannelDetails_get_is_live(this_ptr: &ChannelDetails) -> bool
 pub extern "C" fn ChannelDetails_set_is_live(this_ptr: &mut ChannelDetails, mut val: bool) {
        unsafe { &mut *this_ptr.inner }.is_live = val;
 }
-
-use lightning::ln::channelmanager::PaymentSendFailure as nativePaymentSendFailureImport;
-type nativePaymentSendFailure = nativePaymentSendFailureImport;
-
+impl Clone for ChannelDetails {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn ChannelDetails_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelDetails)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn ChannelDetails_clone(orig: &ChannelDetails) -> ChannelDetails {
+       orig.clone()
+}
 /// If a payment fails to send, it can be in one of several states. This enum is returned as the
 /// Err() type describing which state the payment is in, see the description of individual enum
 /// states for more.
 #[must_use]
+#[derive(Clone)]
 #[repr(C)]
-pub struct PaymentSendFailure {
-       /// Nearly everywhere, inner must be non-null, however in places where
-       /// the Rust equivalent takes an Option, it may be set to null to indicate None.
-       pub inner: *mut nativePaymentSendFailure,
-       pub is_owned: bool,
-}
-
-impl Drop for PaymentSendFailure {
-       fn drop(&mut self) {
-               if self.is_owned && !self.inner.is_null() {
-                       let _ = unsafe { Box::from_raw(self.inner) };
+pub enum PaymentSendFailure {
+       /// A parameter which was passed to send_payment was invalid, preventing us from attempting to
+       /// send the payment at all. No channel state has been changed or messages sent to peers, and
+       /// once you've changed the parameter at error, you can freely retry the payment in full.
+       ParameterError(crate::util::errors::APIError),
+       /// A parameter in a single path which was passed to send_payment was invalid, preventing us
+       /// from attempting to send the payment at all. No channel state has been changed or messages
+       /// sent to peers, and once you've changed the parameter at error, you can freely retry the
+       /// payment in full.
+       ///
+       /// The results here are ordered the same as the paths in the route object which was passed to
+       /// send_payment.
+       PathParameterError(crate::c_types::derived::CVec_CResult_NoneAPIErrorZZ),
+       /// All paths which were attempted failed to send, with no channel state change taking place.
+       /// You can freely retry the payment in full (though you probably want to do so over different
+       /// paths than the ones selected).
+       AllFailedRetrySafe(crate::c_types::derived::CVec_APIErrorZ),
+       /// Some paths which were attempted failed to send, though possibly not all. At least some
+       /// paths have irrevocably committed to the HTLC and retrying the payment in full would result
+       /// in over-/re-payment.
+       ///
+       /// The results here are ordered the same as the paths in the route object which was passed to
+       /// send_payment, and any Errs which are not APIError::MonitorUpdateFailed can be safely
+       /// retried (though there is currently no API with which to do so).
+       ///
+       /// Any entries which contain Err(APIError::MonitorUpdateFailed) or Ok(()) MUST NOT be retried
+       /// as they will result in over-/re-payment. These HTLCs all either successfully sent (in the
+       /// case of Ok(())) or will send once channel_monitor_updated is called on the next-hop channel
+       /// with the latest update_id.
+       PartialFailure(crate::c_types::derived::CVec_CResult_NoneAPIErrorZZ),
+}
+use lightning::ln::channelmanager::PaymentSendFailure as nativePaymentSendFailure;
+impl PaymentSendFailure {
+       #[allow(unused)]
+       pub(crate) fn to_native(&self) -> nativePaymentSendFailure {
+               match self {
+                       PaymentSendFailure::ParameterError (ref a, ) => {
+                               let mut a_nonref = (*a).clone();
+                               nativePaymentSendFailure::ParameterError (
+                                       a_nonref.into_native(),
+                               )
+                       },
+                       PaymentSendFailure::PathParameterError (ref a, ) => {
+                               let mut a_nonref = (*a).clone();
+                               let mut local_a_nonref = Vec::new(); for mut item in a_nonref.into_rust().drain(..) { local_a_nonref.push( { let mut local_a_nonref_0 = match item.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut item.contents.result)) })*/ }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut item.contents.err)) }).into_native() })}; local_a_nonref_0 }); };
+                               nativePaymentSendFailure::PathParameterError (
+                                       local_a_nonref,
+                               )
+                       },
+                       PaymentSendFailure::AllFailedRetrySafe (ref a, ) => {
+                               let mut a_nonref = (*a).clone();
+                               let mut local_a_nonref = Vec::new(); for mut item in a_nonref.into_rust().drain(..) { local_a_nonref.push( { item.into_native() }); };
+                               nativePaymentSendFailure::AllFailedRetrySafe (
+                                       local_a_nonref,
+                               )
+                       },
+                       PaymentSendFailure::PartialFailure (ref a, ) => {
+                               let mut a_nonref = (*a).clone();
+                               let mut local_a_nonref = Vec::new(); for mut item in a_nonref.into_rust().drain(..) { local_a_nonref.push( { let mut local_a_nonref_0 = match item.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut item.contents.result)) })*/ }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut item.contents.err)) }).into_native() })}; local_a_nonref_0 }); };
+                               nativePaymentSendFailure::PartialFailure (
+                                       local_a_nonref,
+                               )
+                       },
+               }
+       }
+       #[allow(unused)]
+       pub(crate) fn into_native(self) -> nativePaymentSendFailure {
+               match self {
+                       PaymentSendFailure::ParameterError (mut a, ) => {
+                               nativePaymentSendFailure::ParameterError (
+                                       a.into_native(),
+                               )
+                       },
+                       PaymentSendFailure::PathParameterError (mut a, ) => {
+                               let mut local_a = Vec::new(); for mut item in a.into_rust().drain(..) { local_a.push( { let mut local_a_0 = match item.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut item.contents.result)) })*/ }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut item.contents.err)) }).into_native() })}; local_a_0 }); };
+                               nativePaymentSendFailure::PathParameterError (
+                                       local_a,
+                               )
+                       },
+                       PaymentSendFailure::AllFailedRetrySafe (mut a, ) => {
+                               let mut local_a = Vec::new(); for mut item in a.into_rust().drain(..) { local_a.push( { item.into_native() }); };
+                               nativePaymentSendFailure::AllFailedRetrySafe (
+                                       local_a,
+                               )
+                       },
+                       PaymentSendFailure::PartialFailure (mut a, ) => {
+                               let mut local_a = Vec::new(); for mut item in a.into_rust().drain(..) { local_a.push( { let mut local_a_0 = match item.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut item.contents.result)) })*/ }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut item.contents.err)) }).into_native() })}; local_a_0 }); };
+                               nativePaymentSendFailure::PartialFailure (
+                                       local_a,
+                               )
+                       },
+               }
+       }
+       #[allow(unused)]
+       pub(crate) fn from_native(native: &nativePaymentSendFailure) -> Self {
+               match native {
+                       nativePaymentSendFailure::ParameterError (ref a, ) => {
+                               let mut a_nonref = (*a).clone();
+                               PaymentSendFailure::ParameterError (
+                                       crate::util::errors::APIError::native_into(a_nonref),
+                               )
+                       },
+                       nativePaymentSendFailure::PathParameterError (ref a, ) => {
+                               let mut a_nonref = (*a).clone();
+                               let mut local_a_nonref = Vec::new(); for mut item in a_nonref.drain(..) { local_a_nonref.push( { let mut local_a_nonref_0 = match item { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::util::errors::APIError::native_into(e) }).into() }; local_a_nonref_0 }); };
+                               PaymentSendFailure::PathParameterError (
+                                       local_a_nonref.into(),
+                               )
+                       },
+                       nativePaymentSendFailure::AllFailedRetrySafe (ref a, ) => {
+                               let mut a_nonref = (*a).clone();
+                               let mut local_a_nonref = Vec::new(); for mut item in a_nonref.drain(..) { local_a_nonref.push( { crate::util::errors::APIError::native_into(item) }); };
+                               PaymentSendFailure::AllFailedRetrySafe (
+                                       local_a_nonref.into(),
+                               )
+                       },
+                       nativePaymentSendFailure::PartialFailure (ref a, ) => {
+                               let mut a_nonref = (*a).clone();
+                               let mut local_a_nonref = Vec::new(); for mut item in a_nonref.drain(..) { local_a_nonref.push( { let mut local_a_nonref_0 = match item { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::util::errors::APIError::native_into(e) }).into() }; local_a_nonref_0 }); };
+                               PaymentSendFailure::PartialFailure (
+                                       local_a_nonref.into(),
+                               )
+                       },
+               }
+       }
+       #[allow(unused)]
+       pub(crate) fn native_into(native: nativePaymentSendFailure) -> Self {
+               match native {
+                       nativePaymentSendFailure::ParameterError (mut a, ) => {
+                               PaymentSendFailure::ParameterError (
+                                       crate::util::errors::APIError::native_into(a),
+                               )
+                       },
+                       nativePaymentSendFailure::PathParameterError (mut a, ) => {
+                               let mut local_a = Vec::new(); for mut item in a.drain(..) { local_a.push( { let mut local_a_0 = match item { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::util::errors::APIError::native_into(e) }).into() }; local_a_0 }); };
+                               PaymentSendFailure::PathParameterError (
+                                       local_a.into(),
+                               )
+                       },
+                       nativePaymentSendFailure::AllFailedRetrySafe (mut a, ) => {
+                               let mut local_a = Vec::new(); for mut item in a.drain(..) { local_a.push( { crate::util::errors::APIError::native_into(item) }); };
+                               PaymentSendFailure::AllFailedRetrySafe (
+                                       local_a.into(),
+                               )
+                       },
+                       nativePaymentSendFailure::PartialFailure (mut a, ) => {
+                               let mut local_a = Vec::new(); for mut item in a.drain(..) { local_a.push( { let mut local_a_0 = match item { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::util::errors::APIError::native_into(e) }).into() }; local_a_0 }); };
+                               PaymentSendFailure::PartialFailure (
+                                       local_a.into(),
+                               )
+                       },
                }
        }
 }
 #[no_mangle]
 pub extern "C" fn PaymentSendFailure_free(this_ptr: PaymentSendFailure) { }
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-extern "C" fn PaymentSendFailure_free_void(this_ptr: *mut c_void) {
-       unsafe { let _ = Box::from_raw(this_ptr as *mut nativePaymentSendFailure); }
-}
-#[allow(unused)]
-/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
-impl PaymentSendFailure {
-       pub(crate) fn take_ptr(mut self) -> *mut nativePaymentSendFailure {
-               assert!(self.is_owned);
-               let ret = self.inner;
-               self.inner = std::ptr::null_mut();
-               ret
-       }
+#[no_mangle]
+pub extern "C" fn PaymentSendFailure_clone(orig: &PaymentSendFailure) -> PaymentSendFailure {
+       orig.clone()
 }
 /// Constructs a new ChannelManager to hold several channels and route between them.
 ///
@@ -312,7 +439,7 @@ impl PaymentSendFailure {
 #[must_use]
 #[no_mangle]
 pub extern "C" fn ChannelManager_new(mut network: crate::bitcoin::network::Network, mut fee_est: crate::chain::chaininterface::FeeEstimator, mut chain_monitor: crate::chain::Watch, mut tx_broadcaster: crate::chain::chaininterface::BroadcasterInterface, mut logger: crate::util::logger::Logger, mut keys_manager: crate::chain::keysinterface::KeysInterface, mut config: crate::util::config::UserConfig, mut current_blockchain_height: usize) -> ChannelManager {
-       let mut ret = lightning::ln::channelmanager::ChannelManager::new(network.into_bitcoin(), fee_est, chain_monitor, tx_broadcaster, logger, keys_manager, *unsafe { Box::from_raw(config.take_ptr()) }, current_blockchain_height);
+       let mut ret = lightning::ln::channelmanager::ChannelManager::new(network.into_bitcoin(), fee_est, chain_monitor, tx_broadcaster, logger, keys_manager, *unsafe { Box::from_raw(config.take_inner()) }, current_blockchain_height);
        ChannelManager { inner: Box::into_raw(Box::new(ret)), is_owned: true }
 }
 
@@ -331,9 +458,9 @@ pub extern "C" fn ChannelManager_new(mut network: crate::bitcoin::network::Netwo
 #[must_use]
 #[no_mangle]
 pub extern "C" fn ChannelManager_create_channel(this_arg: &ChannelManager, mut their_network_key: crate::c_types::PublicKey, mut channel_value_satoshis: u64, mut push_msat: u64, mut user_id: u64, mut override_config: crate::util::config::UserConfig) -> crate::c_types::derived::CResult_NoneAPIErrorZ {
-       let mut local_override_config = if override_config.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(override_config.take_ptr()) } }) };
+       let mut local_override_config = if override_config.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(override_config.take_inner()) } }) };
        let mut ret = unsafe { &*this_arg.inner }.create_channel(their_network_key.into_rust(), channel_value_satoshis, push_msat, user_id, local_override_config);
-       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }), Err(mut e) => crate::c_types::CResultTempl::err( { crate::util::errors::APIError::native_into(e) }) };
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::util::errors::APIError::native_into(e) }).into() };
        local_ret
 }
 
@@ -343,7 +470,7 @@ pub extern "C" fn ChannelManager_create_channel(this_arg: &ChannelManager, mut t
 #[no_mangle]
 pub extern "C" fn ChannelManager_list_channels(this_arg: &ChannelManager) -> crate::c_types::derived::CVec_ChannelDetailsZ {
        let mut ret = unsafe { &*this_arg.inner }.list_channels();
-       let mut local_ret = Vec::new(); for item in ret.drain(..) { local_ret.push( { crate::ln::channelmanager::ChannelDetails { inner: Box::into_raw(Box::new(item)), is_owned: true } }); };
+       let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::ln::channelmanager::ChannelDetails { inner: Box::into_raw(Box::new(item)), is_owned: true } }); };
        local_ret.into()
 }
 
@@ -356,7 +483,7 @@ pub extern "C" fn ChannelManager_list_channels(this_arg: &ChannelManager) -> cra
 #[no_mangle]
 pub extern "C" fn ChannelManager_list_usable_channels(this_arg: &ChannelManager) -> crate::c_types::derived::CVec_ChannelDetailsZ {
        let mut ret = unsafe { &*this_arg.inner }.list_usable_channels();
-       let mut local_ret = Vec::new(); for item in ret.drain(..) { local_ret.push( { crate::ln::channelmanager::ChannelDetails { inner: Box::into_raw(Box::new(item)), is_owned: true } }); };
+       let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::ln::channelmanager::ChannelDetails { inner: Box::into_raw(Box::new(item)), is_owned: true } }); };
        local_ret.into()
 }
 
@@ -369,15 +496,18 @@ pub extern "C" fn ChannelManager_list_usable_channels(this_arg: &ChannelManager)
 #[no_mangle]
 pub extern "C" fn ChannelManager_close_channel(this_arg: &ChannelManager, channel_id: *const [u8; 32]) -> crate::c_types::derived::CResult_NoneAPIErrorZ {
        let mut ret = unsafe { &*this_arg.inner }.close_channel(unsafe { &*channel_id});
-       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }), Err(mut e) => crate::c_types::CResultTempl::err( { crate::util::errors::APIError::native_into(e) }) };
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::util::errors::APIError::native_into(e) }).into() };
        local_ret
 }
 
 /// Force closes a channel, immediately broadcasting the latest local commitment transaction to
-/// the chain and rejecting new HTLCs on the given channel.
+/// the chain and rejecting new HTLCs on the given channel. Fails if channel_id is unknown to the manager.
+#[must_use]
 #[no_mangle]
-pub extern "C" fn ChannelManager_force_close_channel(this_arg: &ChannelManager, channel_id: *const [u8; 32]) {
-       unsafe { &*this_arg.inner }.force_close_channel(unsafe { &*channel_id})
+pub extern "C" fn ChannelManager_force_close_channel(this_arg: &ChannelManager, channel_id: *const [u8; 32]) -> crate::c_types::derived::CResult_NoneAPIErrorZ {
+       let mut ret = unsafe { &*this_arg.inner }.force_close_channel(unsafe { &*channel_id});
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::util::errors::APIError::native_into(e) }).into() };
+       local_ret
 }
 
 /// Force close all channels, immediately broadcasting the latest local commitment transaction
@@ -431,7 +561,7 @@ pub extern "C" fn ChannelManager_force_close_all_channels(this_arg: &ChannelMana
 pub extern "C" fn ChannelManager_send_payment(this_arg: &ChannelManager, route: &crate::routing::router::Route, mut payment_hash: crate::c_types::ThirtyTwoBytes, mut payment_secret: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_NonePaymentSendFailureZ {
        let mut local_payment_secret = if payment_secret.data == [0; 32] { None } else { Some( { ::lightning::ln::channelmanager::PaymentSecret(payment_secret.data) }) };
        let mut ret = unsafe { &*this_arg.inner }.send_payment(unsafe { &*route.inner }, ::lightning::ln::channelmanager::PaymentHash(payment_hash.data), &local_payment_secret);
-       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::channelmanager::PaymentSendFailure { inner: Box::into_raw(Box::new(e)), is_owned: true } }) };
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::channelmanager::PaymentSendFailure::native_into(e) }).into() };
        local_ret
 }
 
@@ -446,7 +576,7 @@ pub extern "C" fn ChannelManager_send_payment(this_arg: &ChannelManager, route:
 /// be trivially prevented by using unique funding transaction keys per-channel).
 #[no_mangle]
 pub extern "C" fn ChannelManager_funding_transaction_generated(this_arg: &ChannelManager, temporary_channel_id: *const [u8; 32], mut funding_txo: crate::chain::transaction::OutPoint) {
-       unsafe { &*this_arg.inner }.funding_transaction_generated(unsafe { &*temporary_channel_id}, *unsafe { Box::from_raw(funding_txo.take_ptr()) })
+       unsafe { &*this_arg.inner }.funding_transaction_generated(unsafe { &*temporary_channel_id}, *unsafe { Box::from_raw(funding_txo.take_inner()) })
 }
 
 /// Generates a signed node_announcement from the given arguments and creates a
@@ -556,8 +686,18 @@ pub extern "C" fn ChannelManager_channel_monitor_updated(this_arg: &ChannelManag
        unsafe { &*this_arg.inner }.channel_monitor_updated(unsafe { &*funding_txo.inner }, highest_applied_update_id)
 }
 
+impl From<nativeChannelManager> for crate::util::events::MessageSendEventsProvider {
+       fn from(obj: nativeChannelManager) -> Self {
+               let mut rust_obj = ChannelManager { inner: Box::into_raw(Box::new(obj)), is_owned: true };
+               let mut ret = ChannelManager_as_MessageSendEventsProvider(&rust_obj);
+               // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
+               rust_obj.inner = std::ptr::null_mut();
+               ret.free = Some(ChannelManager_free_void);
+               ret
+       }
+}
 #[no_mangle]
-pub extern "C" fn ChannelManager_as_MessageSendEventsProvider(this_arg: *const ChannelManager) -> crate::util::events::MessageSendEventsProvider {
+pub extern "C" fn ChannelManager_as_MessageSendEventsProvider(this_arg: &ChannelManager) -> crate::util::events::MessageSendEventsProvider {
        crate::util::events::MessageSendEventsProvider {
                this_arg: unsafe { (*this_arg).inner as *mut c_void },
                free: None,
@@ -567,13 +707,23 @@ pub extern "C" fn ChannelManager_as_MessageSendEventsProvider(this_arg: *const C
 use lightning::util::events::MessageSendEventsProvider as MessageSendEventsProviderTraitImport;
 #[must_use]
 extern "C" fn ChannelManager_MessageSendEventsProvider_get_and_clear_pending_msg_events(this_arg: *const c_void) -> crate::c_types::derived::CVec_MessageSendEventZ {
-       let mut ret = unsafe { &mut *(this_arg as *mut nativeChannelManager) }.get_and_clear_pending_msg_events();
-       let mut local_ret = Vec::new(); for item in ret.drain(..) { local_ret.push( { crate::util::events::MessageSendEvent::native_into(item) }); };
+       let mut ret = <nativeChannelManager as MessageSendEventsProviderTraitImport<>>::get_and_clear_pending_msg_events(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, );
+       let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::util::events::MessageSendEvent::native_into(item) }); };
        local_ret.into()
 }
 
+impl From<nativeChannelManager> for crate::util::events::EventsProvider {
+       fn from(obj: nativeChannelManager) -> Self {
+               let mut rust_obj = ChannelManager { inner: Box::into_raw(Box::new(obj)), is_owned: true };
+               let mut ret = ChannelManager_as_EventsProvider(&rust_obj);
+               // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
+               rust_obj.inner = std::ptr::null_mut();
+               ret.free = Some(ChannelManager_free_void);
+               ret
+       }
+}
 #[no_mangle]
-pub extern "C" fn ChannelManager_as_EventsProvider(this_arg: *const ChannelManager) -> crate::util::events::EventsProvider {
+pub extern "C" fn ChannelManager_as_EventsProvider(this_arg: &ChannelManager) -> crate::util::events::EventsProvider {
        crate::util::events::EventsProvider {
                this_arg: unsafe { (*this_arg).inner as *mut c_void },
                free: None,
@@ -583,11 +733,38 @@ pub extern "C" fn ChannelManager_as_EventsProvider(this_arg: *const ChannelManag
 use lightning::util::events::EventsProvider as EventsProviderTraitImport;
 #[must_use]
 extern "C" fn ChannelManager_EventsProvider_get_and_clear_pending_events(this_arg: *const c_void) -> crate::c_types::derived::CVec_EventZ {
-       let mut ret = unsafe { &mut *(this_arg as *mut nativeChannelManager) }.get_and_clear_pending_events();
-       let mut local_ret = Vec::new(); for item in ret.drain(..) { local_ret.push( { crate::util::events::Event::native_into(item) }); };
+       let mut ret = <nativeChannelManager as EventsProviderTraitImport<>>::get_and_clear_pending_events(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, );
+       let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::util::events::Event::native_into(item) }); };
        local_ret.into()
 }
 
+impl From<nativeChannelManager> for crate::chain::Listen {
+       fn from(obj: nativeChannelManager) -> Self {
+               let mut rust_obj = ChannelManager { inner: Box::into_raw(Box::new(obj)), is_owned: true };
+               let mut ret = ChannelManager_as_Listen(&rust_obj);
+               // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
+               rust_obj.inner = std::ptr::null_mut();
+               ret.free = Some(ChannelManager_free_void);
+               ret
+       }
+}
+#[no_mangle]
+pub extern "C" fn ChannelManager_as_Listen(this_arg: &ChannelManager) -> crate::chain::Listen {
+       crate::chain::Listen {
+               this_arg: unsafe { (*this_arg).inner as *mut c_void },
+               free: None,
+               block_connected: ChannelManager_Listen_block_connected,
+               block_disconnected: ChannelManager_Listen_block_disconnected,
+       }
+}
+use lightning::chain::Listen as ListenTraitImport;
+extern "C" fn ChannelManager_Listen_block_connected(this_arg: *const c_void, mut block: crate::c_types::u8slice, mut height: u32) {
+       <nativeChannelManager as ListenTraitImport<>>::block_connected(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &::bitcoin::consensus::encode::deserialize(block.to_slice()).unwrap(), height)
+}
+extern "C" fn ChannelManager_Listen_block_disconnected(this_arg: *const c_void, header: *const [u8; 80], mut _height: u32) {
+       <nativeChannelManager as ListenTraitImport<>>::block_disconnected(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), _height)
+}
+
 /// Updates channel state based on transactions seen in a connected block.
 #[no_mangle]
 pub extern "C" fn ChannelManager_block_connected(this_arg: &ChannelManager, header: *const [u8; 80], mut txdata: crate::c_types::derived::CVec_C2Tuple_usizeTransactionZZ, mut height: u32) {
@@ -604,8 +781,25 @@ pub extern "C" fn ChannelManager_block_disconnected(this_arg: &ChannelManager, h
        unsafe { &*this_arg.inner }.block_disconnected(&::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap())
 }
 
+/// Blocks until ChannelManager needs to be persisted. Only one listener on `wait` is
+/// guaranteed to be woken up.
 #[no_mangle]
-pub extern "C" fn ChannelManager_as_ChannelMessageHandler(this_arg: *const ChannelManager) -> crate::ln::msgs::ChannelMessageHandler {
+pub extern "C" fn ChannelManager_wait(this_arg: &ChannelManager) {
+       unsafe { &*this_arg.inner }.wait()
+}
+
+impl From<nativeChannelManager> for crate::ln::msgs::ChannelMessageHandler {
+       fn from(obj: nativeChannelManager) -> Self {
+               let mut rust_obj = ChannelManager { inner: Box::into_raw(Box::new(obj)), is_owned: true };
+               let mut ret = ChannelManager_as_ChannelMessageHandler(&rust_obj);
+               // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
+               rust_obj.inner = std::ptr::null_mut();
+               ret.free = Some(ChannelManager_free_void);
+               ret
+       }
+}
+#[no_mangle]
+pub extern "C" fn ChannelManager_as_ChannelMessageHandler(this_arg: &ChannelManager) -> crate::ln::msgs::ChannelMessageHandler {
        crate::ln::msgs::ChannelMessageHandler {
                this_arg: unsafe { (*this_arg).inner as *mut c_void },
                free: None,
@@ -637,73 +831,81 @@ pub extern "C" fn ChannelManager_as_ChannelMessageHandler(this_arg: *const Chann
 }
 use lightning::ln::msgs::ChannelMessageHandler as ChannelMessageHandlerTraitImport;
 extern "C" fn ChannelManager_ChannelMessageHandler_handle_open_channel(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, mut their_features: crate::ln::features::InitFeatures, msg: &crate::ln::msgs::OpenChannel) {
-       unsafe { &mut *(this_arg as *mut nativeChannelManager) }.handle_open_channel(&counterparty_node_id.into_rust(), *unsafe { Box::from_raw(their_features.take_ptr()) }, unsafe { &*msg.inner })
+       <nativeChannelManager as ChannelMessageHandlerTraitImport<>>::handle_open_channel(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), *unsafe { Box::from_raw(their_features.take_inner()) }, unsafe { &*msg.inner })
 }
 extern "C" fn ChannelManager_ChannelMessageHandler_handle_accept_channel(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, mut their_features: crate::ln::features::InitFeatures, msg: &crate::ln::msgs::AcceptChannel) {
-       unsafe { &mut *(this_arg as *mut nativeChannelManager) }.handle_accept_channel(&counterparty_node_id.into_rust(), *unsafe { Box::from_raw(their_features.take_ptr()) }, unsafe { &*msg.inner })
+       <nativeChannelManager as ChannelMessageHandlerTraitImport<>>::handle_accept_channel(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), *unsafe { Box::from_raw(their_features.take_inner()) }, unsafe { &*msg.inner })
 }
 extern "C" fn ChannelManager_ChannelMessageHandler_handle_funding_created(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::ln::msgs::FundingCreated) {
-       unsafe { &mut *(this_arg as *mut nativeChannelManager) }.handle_funding_created(&counterparty_node_id.into_rust(), unsafe { &*msg.inner })
+       <nativeChannelManager as ChannelMessageHandlerTraitImport<>>::handle_funding_created(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
 }
 extern "C" fn ChannelManager_ChannelMessageHandler_handle_funding_signed(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::ln::msgs::FundingSigned) {
-       unsafe { &mut *(this_arg as *mut nativeChannelManager) }.handle_funding_signed(&counterparty_node_id.into_rust(), unsafe { &*msg.inner })
+       <nativeChannelManager as ChannelMessageHandlerTraitImport<>>::handle_funding_signed(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
 }
 extern "C" fn ChannelManager_ChannelMessageHandler_handle_funding_locked(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::ln::msgs::FundingLocked) {
-       unsafe { &mut *(this_arg as *mut nativeChannelManager) }.handle_funding_locked(&counterparty_node_id.into_rust(), unsafe { &*msg.inner })
+       <nativeChannelManager as ChannelMessageHandlerTraitImport<>>::handle_funding_locked(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
 }
-extern "C" fn ChannelManager_ChannelMessageHandler_handle_shutdown(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::ln::msgs::Shutdown) {
-       unsafe { &mut *(this_arg as *mut nativeChannelManager) }.handle_shutdown(&counterparty_node_id.into_rust(), unsafe { &*msg.inner })
+extern "C" fn ChannelManager_ChannelMessageHandler_handle_shutdown(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, their_features: &crate::ln::features::InitFeatures, msg: &crate::ln::msgs::Shutdown) {
+       <nativeChannelManager as ChannelMessageHandlerTraitImport<>>::handle_shutdown(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*their_features.inner }, unsafe { &*msg.inner })
 }
 extern "C" fn ChannelManager_ChannelMessageHandler_handle_closing_signed(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::ln::msgs::ClosingSigned) {
-       unsafe { &mut *(this_arg as *mut nativeChannelManager) }.handle_closing_signed(&counterparty_node_id.into_rust(), unsafe { &*msg.inner })
+       <nativeChannelManager as ChannelMessageHandlerTraitImport<>>::handle_closing_signed(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
 }
 extern "C" fn ChannelManager_ChannelMessageHandler_handle_update_add_htlc(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::ln::msgs::UpdateAddHTLC) {
-       unsafe { &mut *(this_arg as *mut nativeChannelManager) }.handle_update_add_htlc(&counterparty_node_id.into_rust(), unsafe { &*msg.inner })
+       <nativeChannelManager as ChannelMessageHandlerTraitImport<>>::handle_update_add_htlc(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
 }
 extern "C" fn ChannelManager_ChannelMessageHandler_handle_update_fulfill_htlc(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::ln::msgs::UpdateFulfillHTLC) {
-       unsafe { &mut *(this_arg as *mut nativeChannelManager) }.handle_update_fulfill_htlc(&counterparty_node_id.into_rust(), unsafe { &*msg.inner })
+       <nativeChannelManager as ChannelMessageHandlerTraitImport<>>::handle_update_fulfill_htlc(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
 }
 extern "C" fn ChannelManager_ChannelMessageHandler_handle_update_fail_htlc(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::ln::msgs::UpdateFailHTLC) {
-       unsafe { &mut *(this_arg as *mut nativeChannelManager) }.handle_update_fail_htlc(&counterparty_node_id.into_rust(), unsafe { &*msg.inner })
+       <nativeChannelManager as ChannelMessageHandlerTraitImport<>>::handle_update_fail_htlc(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
 }
 extern "C" fn ChannelManager_ChannelMessageHandler_handle_update_fail_malformed_htlc(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::ln::msgs::UpdateFailMalformedHTLC) {
-       unsafe { &mut *(this_arg as *mut nativeChannelManager) }.handle_update_fail_malformed_htlc(&counterparty_node_id.into_rust(), unsafe { &*msg.inner })
+       <nativeChannelManager as ChannelMessageHandlerTraitImport<>>::handle_update_fail_malformed_htlc(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
 }
 extern "C" fn ChannelManager_ChannelMessageHandler_handle_commitment_signed(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::ln::msgs::CommitmentSigned) {
-       unsafe { &mut *(this_arg as *mut nativeChannelManager) }.handle_commitment_signed(&counterparty_node_id.into_rust(), unsafe { &*msg.inner })
+       <nativeChannelManager as ChannelMessageHandlerTraitImport<>>::handle_commitment_signed(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
 }
 extern "C" fn ChannelManager_ChannelMessageHandler_handle_revoke_and_ack(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::ln::msgs::RevokeAndACK) {
-       unsafe { &mut *(this_arg as *mut nativeChannelManager) }.handle_revoke_and_ack(&counterparty_node_id.into_rust(), unsafe { &*msg.inner })
+       <nativeChannelManager as ChannelMessageHandlerTraitImport<>>::handle_revoke_and_ack(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
 }
 extern "C" fn ChannelManager_ChannelMessageHandler_handle_update_fee(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::ln::msgs::UpdateFee) {
-       unsafe { &mut *(this_arg as *mut nativeChannelManager) }.handle_update_fee(&counterparty_node_id.into_rust(), unsafe { &*msg.inner })
+       <nativeChannelManager as ChannelMessageHandlerTraitImport<>>::handle_update_fee(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
 }
 extern "C" fn ChannelManager_ChannelMessageHandler_handle_announcement_signatures(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::ln::msgs::AnnouncementSignatures) {
-       unsafe { &mut *(this_arg as *mut nativeChannelManager) }.handle_announcement_signatures(&counterparty_node_id.into_rust(), unsafe { &*msg.inner })
+       <nativeChannelManager as ChannelMessageHandlerTraitImport<>>::handle_announcement_signatures(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
 }
 extern "C" fn ChannelManager_ChannelMessageHandler_handle_channel_reestablish(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::ln::msgs::ChannelReestablish) {
-       unsafe { &mut *(this_arg as *mut nativeChannelManager) }.handle_channel_reestablish(&counterparty_node_id.into_rust(), unsafe { &*msg.inner })
+       <nativeChannelManager as ChannelMessageHandlerTraitImport<>>::handle_channel_reestablish(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
 }
 extern "C" fn ChannelManager_ChannelMessageHandler_peer_disconnected(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, mut no_connection_possible: bool) {
-       unsafe { &mut *(this_arg as *mut nativeChannelManager) }.peer_disconnected(&counterparty_node_id.into_rust(), no_connection_possible)
+       <nativeChannelManager as ChannelMessageHandlerTraitImport<>>::peer_disconnected(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), no_connection_possible)
 }
 extern "C" fn ChannelManager_ChannelMessageHandler_peer_connected(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, init_msg: &crate::ln::msgs::Init) {
-       unsafe { &mut *(this_arg as *mut nativeChannelManager) }.peer_connected(&counterparty_node_id.into_rust(), unsafe { &*init_msg.inner })
+       <nativeChannelManager as ChannelMessageHandlerTraitImport<>>::peer_connected(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*init_msg.inner })
 }
 extern "C" fn ChannelManager_ChannelMessageHandler_handle_error(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::ln::msgs::ErrorMessage) {
-       unsafe { &mut *(this_arg as *mut nativeChannelManager) }.handle_error(&counterparty_node_id.into_rust(), unsafe { &*msg.inner })
+       <nativeChannelManager as ChannelMessageHandlerTraitImport<>>::handle_error(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
 }
 use lightning::util::events::MessageSendEventsProvider as nativeMessageSendEventsProviderTrait;
 #[must_use]
 extern "C" fn ChannelManager_ChannelMessageHandler_get_and_clear_pending_msg_events(this_arg: *const c_void) -> crate::c_types::derived::CVec_MessageSendEventZ {
-       let mut ret = unsafe { &mut *(this_arg as *mut nativeChannelManager) }.get_and_clear_pending_msg_events();
-       let mut local_ret = Vec::new(); for item in ret.drain(..) { local_ret.push( { crate::util::events::MessageSendEvent::native_into(item) }); };
+       let mut ret = <nativeChannelManager as MessageSendEventsProviderTraitImport<>>::get_and_clear_pending_msg_events(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, );
+       let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::util::events::MessageSendEvent::native_into(item) }); };
        local_ret.into()
 }
 
+#[no_mangle]
+pub extern "C" fn ChannelManager_write(obj: &ChannelManager) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+}
+#[no_mangle]
+pub(crate) extern "C" fn ChannelManager_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeChannelManager) })
+}
 
 use lightning::ln::channelmanager::ChannelManagerReadArgs as nativeChannelManagerReadArgsImport;
-type nativeChannelManagerReadArgs = nativeChannelManagerReadArgsImport<'static, crate::chain::keysinterface::ChannelKeys, crate::chain::Watch, crate::chain::chaininterface::BroadcasterInterface, crate::chain::keysinterface::KeysInterface, crate::chain::chaininterface::FeeEstimator, crate::util::logger::Logger>;
+type nativeChannelManagerReadArgs = nativeChannelManagerReadArgsImport<'static, crate::chain::keysinterface::Sign, crate::chain::Watch, crate::chain::chaininterface::BroadcasterInterface, crate::chain::keysinterface::KeysInterface, crate::chain::chaininterface::FeeEstimator, crate::util::logger::Logger>;
 
 /// Arguments for the creation of a ChannelManager that are not deserialized.
 ///
@@ -745,7 +947,7 @@ extern "C" fn ChannelManagerReadArgs_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl ChannelManagerReadArgs {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeChannelManagerReadArgs {
+       pub(crate) fn take_inner(mut self) -> *mut nativeChannelManagerReadArgs {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
@@ -753,14 +955,16 @@ impl ChannelManagerReadArgs {
        }
 }
 /// The keys provider which will give us relevant keys. Some keys will be loaded during
-/// deserialization.
+/// deserialization and KeysInterface::read_chan_signer will be used to read per-Channel
+/// signing data.
 #[no_mangle]
 pub extern "C" fn ChannelManagerReadArgs_get_keys_manager(this_ptr: &ChannelManagerReadArgs) -> *const crate::chain::keysinterface::KeysInterface {
        let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.keys_manager;
        &(*inner_val)
 }
 /// The keys provider which will give us relevant keys. Some keys will be loaded during
-/// deserialization.
+/// deserialization and KeysInterface::read_chan_signer will be used to read per-Channel
+/// signing data.
 #[no_mangle]
 pub extern "C" fn ChannelManagerReadArgs_set_keys_manager(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::chain::keysinterface::KeysInterface) {
        unsafe { &mut *this_ptr.inner }.keys_manager = val;
@@ -838,7 +1042,7 @@ pub extern "C" fn ChannelManagerReadArgs_get_default_config(this_ptr: &ChannelMa
 /// runtime settings which were stored when the ChannelManager was serialized.
 #[no_mangle]
 pub extern "C" fn ChannelManagerReadArgs_set_default_config(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::util::config::UserConfig) {
-       unsafe { &mut *this_ptr.inner }.default_config = *unsafe { Box::from_raw(val.take_ptr()) };
+       unsafe { &mut *this_ptr.inner }.default_config = *unsafe { Box::from_raw(val.take_inner()) };
 }
 /// Simple utility function to create a ChannelManagerReadArgs which creates the monitor
 /// HashMap for you. This is primarily useful for C bindings where it is not practical to
@@ -847,7 +1051,14 @@ pub extern "C" fn ChannelManagerReadArgs_set_default_config(this_ptr: &mut Chann
 #[no_mangle]
 pub extern "C" fn ChannelManagerReadArgs_new(mut keys_manager: crate::chain::keysinterface::KeysInterface, mut fee_estimator: crate::chain::chaininterface::FeeEstimator, mut chain_monitor: crate::chain::Watch, mut tx_broadcaster: crate::chain::chaininterface::BroadcasterInterface, mut logger: crate::util::logger::Logger, mut default_config: crate::util::config::UserConfig, mut channel_monitors: crate::c_types::derived::CVec_ChannelMonitorZ) -> ChannelManagerReadArgs {
        let mut local_channel_monitors = Vec::new(); for mut item in channel_monitors.into_rust().drain(..) { local_channel_monitors.push( { unsafe { &mut *item.inner } }); };
-       let mut ret = lightning::ln::channelmanager::ChannelManagerReadArgs::new(keys_manager, fee_estimator, chain_monitor, tx_broadcaster, logger, *unsafe { Box::from_raw(default_config.take_ptr()) }, local_channel_monitors);
+       let mut ret = lightning::ln::channelmanager::ChannelManagerReadArgs::new(keys_manager, fee_estimator, chain_monitor, tx_broadcaster, logger, *unsafe { Box::from_raw(default_config.take_inner()) }, local_channel_monitors);
        ChannelManagerReadArgs { inner: Box::into_raw(Box::new(ret)), is_owned: true }
 }
 
+#[no_mangle]
+pub extern "C" fn C2Tuple_BlockHashChannelManagerZ_read(ser: crate::c_types::u8slice, arg: crate::ln::channelmanager::ChannelManagerReadArgs) -> crate::c_types::derived::CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ {
+       let arg_conv = *unsafe { Box::from_raw(arg.take_inner()) };
+       let res: Result<(bitcoin::hash_types::BlockHash, lightning::ln::channelmanager::ChannelManager<crate::chain::keysinterface::Sign, crate::chain::Watch, crate::chain::chaininterface::BroadcasterInterface, crate::chain::keysinterface::KeysInterface, crate::chain::chaininterface::FeeEstimator, crate::util::logger::Logger>), lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj_arg(ser, arg_conv);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_res_0_0, mut orig_res_0_1) = o; let mut local_res_0 = (crate::c_types::ThirtyTwoBytes { data: orig_res_0_0.into_inner() }, crate::ln::channelmanager::ChannelManager { inner: Box::into_raw(Box::new(orig_res_0_1)), is_owned: true }).into(); local_res_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
+}
index 6a6be28459a03a560c8efc311d0789bda9c9dd0a..71adebeb5725210808a956616cc8fa71e0641575 100644 (file)
@@ -20,6 +20,60 @@ use std::ffi::c_void;
 use bitcoin::hashes::Hash;
 use crate::c_types::*;
 
+impl Clone for InitFeatures {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn InitFeatures_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeInitFeatures)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn InitFeatures_clone(orig: &InitFeatures) -> InitFeatures {
+       orig.clone()
+}
+impl Clone for NodeFeatures {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn NodeFeatures_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeNodeFeatures)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn NodeFeatures_clone(orig: &NodeFeatures) -> NodeFeatures {
+       orig.clone()
+}
+impl Clone for ChannelFeatures {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn ChannelFeatures_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelFeatures)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn ChannelFeatures_clone(orig: &ChannelFeatures) -> ChannelFeatures {
+       orig.clone()
+}
 
 use lightning::ln::features::InitFeatures as nativeInitFeaturesImport;
 type nativeInitFeatures = nativeInitFeaturesImport;
@@ -51,7 +105,7 @@ extern "C" fn InitFeatures_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl InitFeatures {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeInitFeatures {
+       pub(crate) fn take_inner(mut self) -> *mut nativeInitFeatures {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
@@ -89,7 +143,7 @@ extern "C" fn NodeFeatures_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl NodeFeatures {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeNodeFeatures {
+       pub(crate) fn take_inner(mut self) -> *mut nativeNodeFeatures {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
@@ -127,10 +181,106 @@ extern "C" fn ChannelFeatures_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl ChannelFeatures {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeChannelFeatures {
+       pub(crate) fn take_inner(mut self) -> *mut nativeChannelFeatures {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
+/// Create a blank Features with no features set
+#[must_use]
+#[no_mangle]
+pub extern "C" fn InitFeatures_empty() -> InitFeatures {
+       let mut ret = lightning::ln::features::InitFeatures::empty();
+       InitFeatures { inner: Box::into_raw(Box::new(ret)), is_owned: true }
+}
+
+/// Creates features known by the implementation as defined by [`T::KNOWN_FEATURE_FLAGS`].
+///
+/// [`T::KNOWN_FEATURE_FLAGS`]: sealed/trait.Context.html#associatedconstant.KNOWN_FEATURE_FLAGS
+#[must_use]
+#[no_mangle]
+pub extern "C" fn InitFeatures_known() -> InitFeatures {
+       let mut ret = lightning::ln::features::InitFeatures::known();
+       InitFeatures { inner: Box::into_raw(Box::new(ret)), is_owned: true }
+}
+
+/// Create a blank Features with no features set
+#[must_use]
+#[no_mangle]
+pub extern "C" fn NodeFeatures_empty() -> NodeFeatures {
+       let mut ret = lightning::ln::features::NodeFeatures::empty();
+       NodeFeatures { inner: Box::into_raw(Box::new(ret)), is_owned: true }
+}
+
+/// Creates features known by the implementation as defined by [`T::KNOWN_FEATURE_FLAGS`].
+///
+/// [`T::KNOWN_FEATURE_FLAGS`]: sealed/trait.Context.html#associatedconstant.KNOWN_FEATURE_FLAGS
+#[must_use]
+#[no_mangle]
+pub extern "C" fn NodeFeatures_known() -> NodeFeatures {
+       let mut ret = lightning::ln::features::NodeFeatures::known();
+       NodeFeatures { inner: Box::into_raw(Box::new(ret)), is_owned: true }
+}
+
+/// Create a blank Features with no features set
+#[must_use]
+#[no_mangle]
+pub extern "C" fn ChannelFeatures_empty() -> ChannelFeatures {
+       let mut ret = lightning::ln::features::ChannelFeatures::empty();
+       ChannelFeatures { inner: Box::into_raw(Box::new(ret)), is_owned: true }
+}
+
+/// Creates features known by the implementation as defined by [`T::KNOWN_FEATURE_FLAGS`].
+///
+/// [`T::KNOWN_FEATURE_FLAGS`]: sealed/trait.Context.html#associatedconstant.KNOWN_FEATURE_FLAGS
+#[must_use]
+#[no_mangle]
+pub extern "C" fn ChannelFeatures_known() -> ChannelFeatures {
+       let mut ret = lightning::ln::features::ChannelFeatures::known();
+       ChannelFeatures { inner: Box::into_raw(Box::new(ret)), is_owned: true }
+}
+
+#[no_mangle]
+pub extern "C" fn InitFeatures_write(obj: &InitFeatures) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+}
+#[no_mangle]
+pub(crate) extern "C" fn InitFeatures_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeInitFeatures) })
+}
+#[no_mangle]
+pub extern "C" fn NodeFeatures_write(obj: &NodeFeatures) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+}
+#[no_mangle]
+pub(crate) extern "C" fn NodeFeatures_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeNodeFeatures) })
+}
+#[no_mangle]
+pub extern "C" fn ChannelFeatures_write(obj: &ChannelFeatures) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+}
+#[no_mangle]
+pub(crate) extern "C" fn ChannelFeatures_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeChannelFeatures) })
+}
+#[no_mangle]
+pub extern "C" fn InitFeatures_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_InitFeaturesDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::features::InitFeatures { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
+}
+#[no_mangle]
+pub extern "C" fn NodeFeatures_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_NodeFeaturesDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::features::NodeFeatures { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
+}
+#[no_mangle]
+pub extern "C" fn ChannelFeatures_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelFeaturesDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::features::ChannelFeatures { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
+}
index 401da37772c30c8afca85ccdf96b86ae0d19f8b0..4425e24cbb6deba2d6920b20c3328004b7d1a0e6 100644 (file)
@@ -50,13 +50,31 @@ extern "C" fn DecodeError_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl DecodeError {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeDecodeError {
+       pub(crate) fn take_inner(mut self) -> *mut nativeDecodeError {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
+impl Clone for DecodeError {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn DecodeError_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeDecodeError)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn DecodeError_clone(orig: &DecodeError) -> DecodeError {
+       orig.clone()
+}
 
 use lightning::ln::msgs::Init as nativeInitImport;
 type nativeInit = nativeInitImport;
@@ -88,17 +106,36 @@ extern "C" fn Init_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl Init {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeInit {
+       pub(crate) fn take_inner(mut self) -> *mut nativeInit {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
+/// The relevant features which the sender supports
+#[no_mangle]
+pub extern "C" fn Init_get_features(this_ptr: &Init) -> crate::ln::features::InitFeatures {
+       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.features;
+       crate::ln::features::InitFeatures { inner: unsafe { ( (&((*inner_val)) as *const _) as *mut _) }, is_owned: false }
+}
+/// The relevant features which the sender supports
+#[no_mangle]
+pub extern "C" fn Init_set_features(this_ptr: &mut Init, mut val: crate::ln::features::InitFeatures) {
+       unsafe { &mut *this_ptr.inner }.features = *unsafe { Box::from_raw(val.take_inner()) };
+}
+#[must_use]
+#[no_mangle]
+pub extern "C" fn Init_new(mut features_arg: crate::ln::features::InitFeatures) -> Init {
+       Init { inner: Box::into_raw(Box::new(nativeInit {
+               features: *unsafe { Box::from_raw(features_arg.take_inner()) },
+       })), is_owned: true }
+}
 impl Clone for Init {
        fn clone(&self) -> Self {
                Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
                        is_owned: true,
                }
        }
@@ -110,7 +147,7 @@ pub(crate) extern "C" fn Init_clone_void(this_ptr: *const c_void) -> *mut c_void
 }
 #[no_mangle]
 pub extern "C" fn Init_clone(orig: &Init) -> Init {
-       Init { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
+       orig.clone()
 }
 
 use lightning::ln::msgs::ErrorMessage as nativeErrorMessageImport;
@@ -143,30 +180,13 @@ extern "C" fn ErrorMessage_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl ErrorMessage {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeErrorMessage {
+       pub(crate) fn take_inner(mut self) -> *mut nativeErrorMessage {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for ErrorMessage {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn ErrorMessage_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeErrorMessage)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn ErrorMessage_clone(orig: &ErrorMessage) -> ErrorMessage {
-       ErrorMessage { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// The channel ID involved in the error
 #[no_mangle]
 pub extern "C" fn ErrorMessage_get_channel_id(this_ptr: &ErrorMessage) -> *const [u8; 32] {
@@ -203,6 +223,24 @@ pub extern "C" fn ErrorMessage_new(mut channel_id_arg: crate::c_types::ThirtyTwo
                data: String::from_utf8(data_arg.into_rust()).unwrap(),
        })), is_owned: true }
 }
+impl Clone for ErrorMessage {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn ErrorMessage_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeErrorMessage)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn ErrorMessage_clone(orig: &ErrorMessage) -> ErrorMessage {
+       orig.clone()
+}
 
 use lightning::ln::msgs::Ping as nativePingImport;
 type nativePing = nativePingImport;
@@ -234,30 +272,13 @@ extern "C" fn Ping_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl Ping {
-       pub(crate) fn take_ptr(mut self) -> *mut nativePing {
+       pub(crate) fn take_inner(mut self) -> *mut nativePing {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for Ping {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn Ping_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativePing)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn Ping_clone(orig: &Ping) -> Ping {
-       Ping { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// The desired response length
 #[no_mangle]
 pub extern "C" fn Ping_get_ponglen(this_ptr: &Ping) -> u16 {
@@ -290,6 +311,24 @@ pub extern "C" fn Ping_new(mut ponglen_arg: u16, mut byteslen_arg: u16) -> Ping
                byteslen: byteslen_arg,
        })), is_owned: true }
 }
+impl Clone for Ping {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn Ping_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativePing)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn Ping_clone(orig: &Ping) -> Ping {
+       orig.clone()
+}
 
 use lightning::ln::msgs::Pong as nativePongImport;
 type nativePong = nativePongImport;
@@ -321,30 +360,13 @@ extern "C" fn Pong_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl Pong {
-       pub(crate) fn take_ptr(mut self) -> *mut nativePong {
+       pub(crate) fn take_inner(mut self) -> *mut nativePong {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for Pong {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn Pong_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativePong)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn Pong_clone(orig: &Pong) -> Pong {
-       Pong { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// The pong packet size.
 /// This field is not sent on the wire. byteslen zeros are sent.
 #[no_mangle]
@@ -365,6 +387,24 @@ pub extern "C" fn Pong_new(mut byteslen_arg: u16) -> Pong {
                byteslen: byteslen_arg,
        })), is_owned: true }
 }
+impl Clone for Pong {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn Pong_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativePong)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn Pong_clone(orig: &Pong) -> Pong {
+       orig.clone()
+}
 
 use lightning::ln::msgs::OpenChannel as nativeOpenChannelImport;
 type nativeOpenChannel = nativeOpenChannelImport;
@@ -396,30 +436,13 @@ extern "C" fn OpenChannel_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl OpenChannel {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeOpenChannel {
+       pub(crate) fn take_inner(mut self) -> *mut nativeOpenChannel {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for OpenChannel {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn OpenChannel_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeOpenChannel)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn OpenChannel_clone(orig: &OpenChannel) -> OpenChannel {
-       OpenChannel { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// The genesis hash of the blockchain where the channel is to be opened
 #[no_mangle]
 pub extern "C" fn OpenChannel_get_chain_hash(this_ptr: &OpenChannel) -> *const [u8; 32] {
@@ -618,6 +641,24 @@ pub extern "C" fn OpenChannel_get_channel_flags(this_ptr: &OpenChannel) -> u8 {
 pub extern "C" fn OpenChannel_set_channel_flags(this_ptr: &mut OpenChannel, mut val: u8) {
        unsafe { &mut *this_ptr.inner }.channel_flags = val;
 }
+impl Clone for OpenChannel {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn OpenChannel_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeOpenChannel)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn OpenChannel_clone(orig: &OpenChannel) -> OpenChannel {
+       orig.clone()
+}
 
 use lightning::ln::msgs::AcceptChannel as nativeAcceptChannelImport;
 type nativeAcceptChannel = nativeAcceptChannelImport;
@@ -649,30 +690,13 @@ extern "C" fn AcceptChannel_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl AcceptChannel {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeAcceptChannel {
+       pub(crate) fn take_inner(mut self) -> *mut nativeAcceptChannel {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for AcceptChannel {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn AcceptChannel_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeAcceptChannel)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn AcceptChannel_clone(orig: &AcceptChannel) -> AcceptChannel {
-       AcceptChannel { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// A temporary channel ID, until the funding outpoint is announced
 #[no_mangle]
 pub extern "C" fn AcceptChannel_get_temporary_channel_id(this_ptr: &AcceptChannel) -> *const [u8; 32] {
@@ -827,6 +851,24 @@ pub extern "C" fn AcceptChannel_get_first_per_commitment_point(this_ptr: &Accept
 pub extern "C" fn AcceptChannel_set_first_per_commitment_point(this_ptr: &mut AcceptChannel, mut val: crate::c_types::PublicKey) {
        unsafe { &mut *this_ptr.inner }.first_per_commitment_point = val.into_rust();
 }
+impl Clone for AcceptChannel {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn AcceptChannel_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeAcceptChannel)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn AcceptChannel_clone(orig: &AcceptChannel) -> AcceptChannel {
+       orig.clone()
+}
 
 use lightning::ln::msgs::FundingCreated as nativeFundingCreatedImport;
 type nativeFundingCreated = nativeFundingCreatedImport;
@@ -858,30 +900,13 @@ extern "C" fn FundingCreated_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl FundingCreated {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeFundingCreated {
+       pub(crate) fn take_inner(mut self) -> *mut nativeFundingCreated {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for FundingCreated {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn FundingCreated_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeFundingCreated)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn FundingCreated_clone(orig: &FundingCreated) -> FundingCreated {
-       FundingCreated { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// A temporary channel ID, until the funding is established
 #[no_mangle]
 pub extern "C" fn FundingCreated_get_temporary_channel_id(this_ptr: &FundingCreated) -> *const [u8; 32] {
@@ -936,6 +961,24 @@ pub extern "C" fn FundingCreated_new(mut temporary_channel_id_arg: crate::c_type
                signature: signature_arg.into_rust(),
        })), is_owned: true }
 }
+impl Clone for FundingCreated {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn FundingCreated_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeFundingCreated)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn FundingCreated_clone(orig: &FundingCreated) -> FundingCreated {
+       orig.clone()
+}
 
 use lightning::ln::msgs::FundingSigned as nativeFundingSignedImport;
 type nativeFundingSigned = nativeFundingSignedImport;
@@ -967,30 +1010,13 @@ extern "C" fn FundingSigned_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl FundingSigned {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeFundingSigned {
+       pub(crate) fn take_inner(mut self) -> *mut nativeFundingSigned {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for FundingSigned {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn FundingSigned_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeFundingSigned)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn FundingSigned_clone(orig: &FundingSigned) -> FundingSigned {
-       FundingSigned { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// The channel ID
 #[no_mangle]
 pub extern "C" fn FundingSigned_get_channel_id(this_ptr: &FundingSigned) -> *const [u8; 32] {
@@ -1021,6 +1047,24 @@ pub extern "C" fn FundingSigned_new(mut channel_id_arg: crate::c_types::ThirtyTw
                signature: signature_arg.into_rust(),
        })), is_owned: true }
 }
+impl Clone for FundingSigned {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn FundingSigned_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeFundingSigned)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn FundingSigned_clone(orig: &FundingSigned) -> FundingSigned {
+       orig.clone()
+}
 
 use lightning::ln::msgs::FundingLocked as nativeFundingLockedImport;
 type nativeFundingLocked = nativeFundingLockedImport;
@@ -1052,30 +1096,13 @@ extern "C" fn FundingLocked_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl FundingLocked {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeFundingLocked {
+       pub(crate) fn take_inner(mut self) -> *mut nativeFundingLocked {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for FundingLocked {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn FundingLocked_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeFundingLocked)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn FundingLocked_clone(orig: &FundingLocked) -> FundingLocked {
-       FundingLocked { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// The channel ID
 #[no_mangle]
 pub extern "C" fn FundingLocked_get_channel_id(this_ptr: &FundingLocked) -> *const [u8; 32] {
@@ -1106,8 +1133,26 @@ pub extern "C" fn FundingLocked_new(mut channel_id_arg: crate::c_types::ThirtyTw
                next_per_commitment_point: next_per_commitment_point_arg.into_rust(),
        })), is_owned: true }
 }
-
-use lightning::ln::msgs::Shutdown as nativeShutdownImport;
+impl Clone for FundingLocked {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn FundingLocked_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeFundingLocked)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn FundingLocked_clone(orig: &FundingLocked) -> FundingLocked {
+       orig.clone()
+}
+
+use lightning::ln::msgs::Shutdown as nativeShutdownImport;
 type nativeShutdown = nativeShutdownImport;
 
 /// A shutdown message to be sent or received from a peer
@@ -1137,30 +1182,13 @@ extern "C" fn Shutdown_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl Shutdown {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeShutdown {
+       pub(crate) fn take_inner(mut self) -> *mut nativeShutdown {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for Shutdown {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn Shutdown_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeShutdown)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn Shutdown_clone(orig: &Shutdown) -> Shutdown {
-       Shutdown { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// The channel ID
 #[no_mangle]
 pub extern "C" fn Shutdown_get_channel_id(this_ptr: &Shutdown) -> *const [u8; 32] {
@@ -1193,6 +1221,24 @@ pub extern "C" fn Shutdown_new(mut channel_id_arg: crate::c_types::ThirtyTwoByte
                scriptpubkey: ::bitcoin::blockdata::script::Script::from(scriptpubkey_arg.into_rust()),
        })), is_owned: true }
 }
+impl Clone for Shutdown {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn Shutdown_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeShutdown)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn Shutdown_clone(orig: &Shutdown) -> Shutdown {
+       orig.clone()
+}
 
 use lightning::ln::msgs::ClosingSigned as nativeClosingSignedImport;
 type nativeClosingSigned = nativeClosingSignedImport;
@@ -1224,30 +1270,13 @@ extern "C" fn ClosingSigned_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl ClosingSigned {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeClosingSigned {
+       pub(crate) fn take_inner(mut self) -> *mut nativeClosingSigned {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for ClosingSigned {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn ClosingSigned_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeClosingSigned)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn ClosingSigned_clone(orig: &ClosingSigned) -> ClosingSigned {
-       ClosingSigned { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// The channel ID
 #[no_mangle]
 pub extern "C" fn ClosingSigned_get_channel_id(this_ptr: &ClosingSigned) -> *const [u8; 32] {
@@ -1290,6 +1319,24 @@ pub extern "C" fn ClosingSigned_new(mut channel_id_arg: crate::c_types::ThirtyTw
                signature: signature_arg.into_rust(),
        })), is_owned: true }
 }
+impl Clone for ClosingSigned {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn ClosingSigned_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeClosingSigned)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn ClosingSigned_clone(orig: &ClosingSigned) -> ClosingSigned {
+       orig.clone()
+}
 
 use lightning::ln::msgs::UpdateAddHTLC as nativeUpdateAddHTLCImport;
 type nativeUpdateAddHTLC = nativeUpdateAddHTLCImport;
@@ -1321,30 +1368,13 @@ extern "C" fn UpdateAddHTLC_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl UpdateAddHTLC {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeUpdateAddHTLC {
+       pub(crate) fn take_inner(mut self) -> *mut nativeUpdateAddHTLC {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for UpdateAddHTLC {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn UpdateAddHTLC_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeUpdateAddHTLC)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn UpdateAddHTLC_clone(orig: &UpdateAddHTLC) -> UpdateAddHTLC {
-       UpdateAddHTLC { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// The channel ID
 #[no_mangle]
 pub extern "C" fn UpdateAddHTLC_get_channel_id(this_ptr: &UpdateAddHTLC) -> *const [u8; 32] {
@@ -1400,6 +1430,24 @@ pub extern "C" fn UpdateAddHTLC_get_cltv_expiry(this_ptr: &UpdateAddHTLC) -> u32
 pub extern "C" fn UpdateAddHTLC_set_cltv_expiry(this_ptr: &mut UpdateAddHTLC, mut val: u32) {
        unsafe { &mut *this_ptr.inner }.cltv_expiry = val;
 }
+impl Clone for UpdateAddHTLC {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn UpdateAddHTLC_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeUpdateAddHTLC)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn UpdateAddHTLC_clone(orig: &UpdateAddHTLC) -> UpdateAddHTLC {
+       orig.clone()
+}
 
 use lightning::ln::msgs::UpdateFulfillHTLC as nativeUpdateFulfillHTLCImport;
 type nativeUpdateFulfillHTLC = nativeUpdateFulfillHTLCImport;
@@ -1431,30 +1479,13 @@ extern "C" fn UpdateFulfillHTLC_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl UpdateFulfillHTLC {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeUpdateFulfillHTLC {
+       pub(crate) fn take_inner(mut self) -> *mut nativeUpdateFulfillHTLC {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for UpdateFulfillHTLC {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn UpdateFulfillHTLC_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeUpdateFulfillHTLC)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn UpdateFulfillHTLC_clone(orig: &UpdateFulfillHTLC) -> UpdateFulfillHTLC {
-       UpdateFulfillHTLC { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// The channel ID
 #[no_mangle]
 pub extern "C" fn UpdateFulfillHTLC_get_channel_id(this_ptr: &UpdateFulfillHTLC) -> *const [u8; 32] {
@@ -1497,6 +1528,24 @@ pub extern "C" fn UpdateFulfillHTLC_new(mut channel_id_arg: crate::c_types::Thir
                payment_preimage: ::lightning::ln::channelmanager::PaymentPreimage(payment_preimage_arg.data),
        })), is_owned: true }
 }
+impl Clone for UpdateFulfillHTLC {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn UpdateFulfillHTLC_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeUpdateFulfillHTLC)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn UpdateFulfillHTLC_clone(orig: &UpdateFulfillHTLC) -> UpdateFulfillHTLC {
+       orig.clone()
+}
 
 use lightning::ln::msgs::UpdateFailHTLC as nativeUpdateFailHTLCImport;
 type nativeUpdateFailHTLC = nativeUpdateFailHTLCImport;
@@ -1528,30 +1577,13 @@ extern "C" fn UpdateFailHTLC_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl UpdateFailHTLC {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeUpdateFailHTLC {
+       pub(crate) fn take_inner(mut self) -> *mut nativeUpdateFailHTLC {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for UpdateFailHTLC {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn UpdateFailHTLC_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeUpdateFailHTLC)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn UpdateFailHTLC_clone(orig: &UpdateFailHTLC) -> UpdateFailHTLC {
-       UpdateFailHTLC { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// The channel ID
 #[no_mangle]
 pub extern "C" fn UpdateFailHTLC_get_channel_id(this_ptr: &UpdateFailHTLC) -> *const [u8; 32] {
@@ -1574,6 +1606,24 @@ pub extern "C" fn UpdateFailHTLC_get_htlc_id(this_ptr: &UpdateFailHTLC) -> u64 {
 pub extern "C" fn UpdateFailHTLC_set_htlc_id(this_ptr: &mut UpdateFailHTLC, mut val: u64) {
        unsafe { &mut *this_ptr.inner }.htlc_id = val;
 }
+impl Clone for UpdateFailHTLC {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn UpdateFailHTLC_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeUpdateFailHTLC)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn UpdateFailHTLC_clone(orig: &UpdateFailHTLC) -> UpdateFailHTLC {
+       orig.clone()
+}
 
 use lightning::ln::msgs::UpdateFailMalformedHTLC as nativeUpdateFailMalformedHTLCImport;
 type nativeUpdateFailMalformedHTLC = nativeUpdateFailMalformedHTLCImport;
@@ -1605,30 +1655,13 @@ extern "C" fn UpdateFailMalformedHTLC_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl UpdateFailMalformedHTLC {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeUpdateFailMalformedHTLC {
+       pub(crate) fn take_inner(mut self) -> *mut nativeUpdateFailMalformedHTLC {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for UpdateFailMalformedHTLC {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn UpdateFailMalformedHTLC_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeUpdateFailMalformedHTLC)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn UpdateFailMalformedHTLC_clone(orig: &UpdateFailMalformedHTLC) -> UpdateFailMalformedHTLC {
-       UpdateFailMalformedHTLC { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// The channel ID
 #[no_mangle]
 pub extern "C" fn UpdateFailMalformedHTLC_get_channel_id(this_ptr: &UpdateFailMalformedHTLC) -> *const [u8; 32] {
@@ -1662,6 +1695,24 @@ pub extern "C" fn UpdateFailMalformedHTLC_get_failure_code(this_ptr: &UpdateFail
 pub extern "C" fn UpdateFailMalformedHTLC_set_failure_code(this_ptr: &mut UpdateFailMalformedHTLC, mut val: u16) {
        unsafe { &mut *this_ptr.inner }.failure_code = val;
 }
+impl Clone for UpdateFailMalformedHTLC {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn UpdateFailMalformedHTLC_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeUpdateFailMalformedHTLC)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn UpdateFailMalformedHTLC_clone(orig: &UpdateFailMalformedHTLC) -> UpdateFailMalformedHTLC {
+       orig.clone()
+}
 
 use lightning::ln::msgs::CommitmentSigned as nativeCommitmentSignedImport;
 type nativeCommitmentSigned = nativeCommitmentSignedImport;
@@ -1693,30 +1744,13 @@ extern "C" fn CommitmentSigned_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl CommitmentSigned {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeCommitmentSigned {
+       pub(crate) fn take_inner(mut self) -> *mut nativeCommitmentSigned {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for CommitmentSigned {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn CommitmentSigned_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeCommitmentSigned)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn CommitmentSigned_clone(orig: &CommitmentSigned) -> CommitmentSigned {
-       CommitmentSigned { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// The channel ID
 #[no_mangle]
 pub extern "C" fn CommitmentSigned_get_channel_id(this_ptr: &CommitmentSigned) -> *const [u8; 32] {
@@ -1755,6 +1789,24 @@ pub extern "C" fn CommitmentSigned_new(mut channel_id_arg: crate::c_types::Thirt
                htlc_signatures: local_htlc_signatures_arg,
        })), is_owned: true }
 }
+impl Clone for CommitmentSigned {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn CommitmentSigned_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeCommitmentSigned)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn CommitmentSigned_clone(orig: &CommitmentSigned) -> CommitmentSigned {
+       orig.clone()
+}
 
 use lightning::ln::msgs::RevokeAndACK as nativeRevokeAndACKImport;
 type nativeRevokeAndACK = nativeRevokeAndACKImport;
@@ -1786,30 +1838,13 @@ extern "C" fn RevokeAndACK_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl RevokeAndACK {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeRevokeAndACK {
+       pub(crate) fn take_inner(mut self) -> *mut nativeRevokeAndACK {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for RevokeAndACK {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn RevokeAndACK_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeRevokeAndACK)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn RevokeAndACK_clone(orig: &RevokeAndACK) -> RevokeAndACK {
-       RevokeAndACK { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// The channel ID
 #[no_mangle]
 pub extern "C" fn RevokeAndACK_get_channel_id(this_ptr: &RevokeAndACK) -> *const [u8; 32] {
@@ -1852,6 +1887,24 @@ pub extern "C" fn RevokeAndACK_new(mut channel_id_arg: crate::c_types::ThirtyTwo
                next_per_commitment_point: next_per_commitment_point_arg.into_rust(),
        })), is_owned: true }
 }
+impl Clone for RevokeAndACK {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn RevokeAndACK_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeRevokeAndACK)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn RevokeAndACK_clone(orig: &RevokeAndACK) -> RevokeAndACK {
+       orig.clone()
+}
 
 use lightning::ln::msgs::UpdateFee as nativeUpdateFeeImport;
 type nativeUpdateFee = nativeUpdateFeeImport;
@@ -1883,30 +1936,13 @@ extern "C" fn UpdateFee_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl UpdateFee {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeUpdateFee {
+       pub(crate) fn take_inner(mut self) -> *mut nativeUpdateFee {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for UpdateFee {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn UpdateFee_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeUpdateFee)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn UpdateFee_clone(orig: &UpdateFee) -> UpdateFee {
-       UpdateFee { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// The channel ID
 #[no_mangle]
 pub extern "C" fn UpdateFee_get_channel_id(this_ptr: &UpdateFee) -> *const [u8; 32] {
@@ -1937,6 +1973,24 @@ pub extern "C" fn UpdateFee_new(mut channel_id_arg: crate::c_types::ThirtyTwoByt
                feerate_per_kw: feerate_per_kw_arg,
        })), is_owned: true }
 }
+impl Clone for UpdateFee {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn UpdateFee_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeUpdateFee)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn UpdateFee_clone(orig: &UpdateFee) -> UpdateFee {
+       orig.clone()
+}
 
 use lightning::ln::msgs::DataLossProtect as nativeDataLossProtectImport;
 type nativeDataLossProtect = nativeDataLossProtectImport;
@@ -1971,30 +2025,13 @@ extern "C" fn DataLossProtect_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl DataLossProtect {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeDataLossProtect {
+       pub(crate) fn take_inner(mut self) -> *mut nativeDataLossProtect {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for DataLossProtect {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn DataLossProtect_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeDataLossProtect)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn DataLossProtect_clone(orig: &DataLossProtect) -> DataLossProtect {
-       DataLossProtect { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// Proof that the sender knows the per-commitment secret of a specific commitment transaction
 /// belonging to the recipient
 #[no_mangle]
@@ -2027,6 +2064,24 @@ pub extern "C" fn DataLossProtect_new(mut your_last_per_commitment_secret_arg: c
                my_current_per_commitment_point: my_current_per_commitment_point_arg.into_rust(),
        })), is_owned: true }
 }
+impl Clone for DataLossProtect {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn DataLossProtect_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeDataLossProtect)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn DataLossProtect_clone(orig: &DataLossProtect) -> DataLossProtect {
+       orig.clone()
+}
 
 use lightning::ln::msgs::ChannelReestablish as nativeChannelReestablishImport;
 type nativeChannelReestablish = nativeChannelReestablishImport;
@@ -2058,30 +2113,13 @@ extern "C" fn ChannelReestablish_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl ChannelReestablish {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeChannelReestablish {
+       pub(crate) fn take_inner(mut self) -> *mut nativeChannelReestablish {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for ChannelReestablish {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn ChannelReestablish_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelReestablish)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn ChannelReestablish_clone(orig: &ChannelReestablish) -> ChannelReestablish {
-       ChannelReestablish { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// The channel ID
 #[no_mangle]
 pub extern "C" fn ChannelReestablish_get_channel_id(this_ptr: &ChannelReestablish) -> *const [u8; 32] {
@@ -2115,6 +2153,24 @@ pub extern "C" fn ChannelReestablish_get_next_remote_commitment_number(this_ptr:
 pub extern "C" fn ChannelReestablish_set_next_remote_commitment_number(this_ptr: &mut ChannelReestablish, mut val: u64) {
        unsafe { &mut *this_ptr.inner }.next_remote_commitment_number = val;
 }
+impl Clone for ChannelReestablish {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn ChannelReestablish_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelReestablish)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn ChannelReestablish_clone(orig: &ChannelReestablish) -> ChannelReestablish {
+       orig.clone()
+}
 
 use lightning::ln::msgs::AnnouncementSignatures as nativeAnnouncementSignaturesImport;
 type nativeAnnouncementSignatures = nativeAnnouncementSignaturesImport;
@@ -2146,30 +2202,13 @@ extern "C" fn AnnouncementSignatures_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl AnnouncementSignatures {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeAnnouncementSignatures {
+       pub(crate) fn take_inner(mut self) -> *mut nativeAnnouncementSignatures {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for AnnouncementSignatures {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn AnnouncementSignatures_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeAnnouncementSignatures)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn AnnouncementSignatures_clone(orig: &AnnouncementSignatures) -> AnnouncementSignatures {
-       AnnouncementSignatures { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// The channel ID
 #[no_mangle]
 pub extern "C" fn AnnouncementSignatures_get_channel_id(this_ptr: &AnnouncementSignatures) -> *const [u8; 32] {
@@ -2224,6 +2263,24 @@ pub extern "C" fn AnnouncementSignatures_new(mut channel_id_arg: crate::c_types:
                bitcoin_signature: bitcoin_signature_arg.into_rust(),
        })), is_owned: true }
 }
+impl Clone for AnnouncementSignatures {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn AnnouncementSignatures_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeAnnouncementSignatures)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn AnnouncementSignatures_clone(orig: &AnnouncementSignatures) -> AnnouncementSignatures {
+       orig.clone()
+}
 /// An address which can be used to connect to a remote peer
 #[must_use]
 #[derive(Clone)]
@@ -2407,6 +2464,16 @@ pub extern "C" fn NetAddress_free(this_ptr: NetAddress) { }
 pub extern "C" fn NetAddress_clone(orig: &NetAddress) -> NetAddress {
        orig.clone()
 }
+#[no_mangle]
+pub extern "C" fn NetAddress_write(obj: &NetAddress) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(&unsafe { &*obj }.to_native())
+}
+#[no_mangle]
+pub extern "C" fn Result_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_CResult_NetAddressu8ZDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { let mut local_res_0 = match o { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::msgs::NetAddress::native_into(o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { e }).into() }; local_res_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
+}
 
 use lightning::ln::msgs::UnsignedNodeAnnouncement as nativeUnsignedNodeAnnouncementImport;
 type nativeUnsignedNodeAnnouncement = nativeUnsignedNodeAnnouncementImport;
@@ -2438,30 +2505,13 @@ extern "C" fn UnsignedNodeAnnouncement_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl UnsignedNodeAnnouncement {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeUnsignedNodeAnnouncement {
+       pub(crate) fn take_inner(mut self) -> *mut nativeUnsignedNodeAnnouncement {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for UnsignedNodeAnnouncement {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn UnsignedNodeAnnouncement_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeUnsignedNodeAnnouncement)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn UnsignedNodeAnnouncement_clone(orig: &UnsignedNodeAnnouncement) -> UnsignedNodeAnnouncement {
-       UnsignedNodeAnnouncement { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// The advertised features
 #[no_mangle]
 pub extern "C" fn UnsignedNodeAnnouncement_get_features(this_ptr: &UnsignedNodeAnnouncement) -> crate::ln::features::NodeFeatures {
@@ -2471,7 +2521,7 @@ pub extern "C" fn UnsignedNodeAnnouncement_get_features(this_ptr: &UnsignedNodeA
 /// The advertised features
 #[no_mangle]
 pub extern "C" fn UnsignedNodeAnnouncement_set_features(this_ptr: &mut UnsignedNodeAnnouncement, mut val: crate::ln::features::NodeFeatures) {
-       unsafe { &mut *this_ptr.inner }.features = *unsafe { Box::from_raw(val.take_ptr()) };
+       unsafe { &mut *this_ptr.inner }.features = *unsafe { Box::from_raw(val.take_inner()) };
 }
 /// A strictly monotonic announcement counter, with gaps allowed
 #[no_mangle]
@@ -2527,6 +2577,24 @@ pub extern "C" fn UnsignedNodeAnnouncement_set_addresses(this_ptr: &mut Unsigned
        let mut local_val = Vec::new(); for mut item in val.into_rust().drain(..) { local_val.push( { item.into_native() }); };
        unsafe { &mut *this_ptr.inner }.addresses = local_val;
 }
+impl Clone for UnsignedNodeAnnouncement {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn UnsignedNodeAnnouncement_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeUnsignedNodeAnnouncement)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn UnsignedNodeAnnouncement_clone(orig: &UnsignedNodeAnnouncement) -> UnsignedNodeAnnouncement {
+       orig.clone()
+}
 
 use lightning::ln::msgs::NodeAnnouncement as nativeNodeAnnouncementImport;
 type nativeNodeAnnouncement = nativeNodeAnnouncementImport;
@@ -2558,30 +2626,13 @@ extern "C" fn NodeAnnouncement_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl NodeAnnouncement {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeNodeAnnouncement {
+       pub(crate) fn take_inner(mut self) -> *mut nativeNodeAnnouncement {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for NodeAnnouncement {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn NodeAnnouncement_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeNodeAnnouncement)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn NodeAnnouncement_clone(orig: &NodeAnnouncement) -> NodeAnnouncement {
-       NodeAnnouncement { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// The signature by the node key
 #[no_mangle]
 pub extern "C" fn NodeAnnouncement_get_signature(this_ptr: &NodeAnnouncement) -> crate::c_types::Signature {
@@ -2602,16 +2653,34 @@ pub extern "C" fn NodeAnnouncement_get_contents(this_ptr: &NodeAnnouncement) ->
 /// The actual content of the announcement
 #[no_mangle]
 pub extern "C" fn NodeAnnouncement_set_contents(this_ptr: &mut NodeAnnouncement, mut val: crate::ln::msgs::UnsignedNodeAnnouncement) {
-       unsafe { &mut *this_ptr.inner }.contents = *unsafe { Box::from_raw(val.take_ptr()) };
+       unsafe { &mut *this_ptr.inner }.contents = *unsafe { Box::from_raw(val.take_inner()) };
 }
 #[must_use]
 #[no_mangle]
 pub extern "C" fn NodeAnnouncement_new(mut signature_arg: crate::c_types::Signature, mut contents_arg: crate::ln::msgs::UnsignedNodeAnnouncement) -> NodeAnnouncement {
        NodeAnnouncement { inner: Box::into_raw(Box::new(nativeNodeAnnouncement {
                signature: signature_arg.into_rust(),
-               contents: *unsafe { Box::from_raw(contents_arg.take_ptr()) },
+               contents: *unsafe { Box::from_raw(contents_arg.take_inner()) },
        })), is_owned: true }
 }
+impl Clone for NodeAnnouncement {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn NodeAnnouncement_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeNodeAnnouncement)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn NodeAnnouncement_clone(orig: &NodeAnnouncement) -> NodeAnnouncement {
+       orig.clone()
+}
 
 use lightning::ln::msgs::UnsignedChannelAnnouncement as nativeUnsignedChannelAnnouncementImport;
 type nativeUnsignedChannelAnnouncement = nativeUnsignedChannelAnnouncementImport;
@@ -2643,30 +2712,13 @@ extern "C" fn UnsignedChannelAnnouncement_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl UnsignedChannelAnnouncement {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeUnsignedChannelAnnouncement {
+       pub(crate) fn take_inner(mut self) -> *mut nativeUnsignedChannelAnnouncement {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for UnsignedChannelAnnouncement {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn UnsignedChannelAnnouncement_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeUnsignedChannelAnnouncement)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn UnsignedChannelAnnouncement_clone(orig: &UnsignedChannelAnnouncement) -> UnsignedChannelAnnouncement {
-       UnsignedChannelAnnouncement { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// The advertised channel features
 #[no_mangle]
 pub extern "C" fn UnsignedChannelAnnouncement_get_features(this_ptr: &UnsignedChannelAnnouncement) -> crate::ln::features::ChannelFeatures {
@@ -2676,7 +2728,7 @@ pub extern "C" fn UnsignedChannelAnnouncement_get_features(this_ptr: &UnsignedCh
 /// The advertised channel features
 #[no_mangle]
 pub extern "C" fn UnsignedChannelAnnouncement_set_features(this_ptr: &mut UnsignedChannelAnnouncement, mut val: crate::ln::features::ChannelFeatures) {
-       unsafe { &mut *this_ptr.inner }.features = *unsafe { Box::from_raw(val.take_ptr()) };
+       unsafe { &mut *this_ptr.inner }.features = *unsafe { Box::from_raw(val.take_inner()) };
 }
 /// The genesis hash of the blockchain where the channel is to be opened
 #[no_mangle]
@@ -2744,6 +2796,24 @@ pub extern "C" fn UnsignedChannelAnnouncement_get_bitcoin_key_2(this_ptr: &Unsig
 pub extern "C" fn UnsignedChannelAnnouncement_set_bitcoin_key_2(this_ptr: &mut UnsignedChannelAnnouncement, mut val: crate::c_types::PublicKey) {
        unsafe { &mut *this_ptr.inner }.bitcoin_key_2 = val.into_rust();
 }
+impl Clone for UnsignedChannelAnnouncement {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn UnsignedChannelAnnouncement_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeUnsignedChannelAnnouncement)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn UnsignedChannelAnnouncement_clone(orig: &UnsignedChannelAnnouncement) -> UnsignedChannelAnnouncement {
+       orig.clone()
+}
 
 use lightning::ln::msgs::ChannelAnnouncement as nativeChannelAnnouncementImport;
 type nativeChannelAnnouncement = nativeChannelAnnouncementImport;
@@ -2775,30 +2845,13 @@ extern "C" fn ChannelAnnouncement_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl ChannelAnnouncement {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeChannelAnnouncement {
+       pub(crate) fn take_inner(mut self) -> *mut nativeChannelAnnouncement {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for ChannelAnnouncement {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn ChannelAnnouncement_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelAnnouncement)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn ChannelAnnouncement_clone(orig: &ChannelAnnouncement) -> ChannelAnnouncement {
-       ChannelAnnouncement { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// Authentication of the announcement by the first public node
 #[no_mangle]
 pub extern "C" fn ChannelAnnouncement_get_node_signature_1(this_ptr: &ChannelAnnouncement) -> crate::c_types::Signature {
@@ -2852,7 +2905,7 @@ pub extern "C" fn ChannelAnnouncement_get_contents(this_ptr: &ChannelAnnouncemen
 /// The actual announcement
 #[no_mangle]
 pub extern "C" fn ChannelAnnouncement_set_contents(this_ptr: &mut ChannelAnnouncement, mut val: crate::ln::msgs::UnsignedChannelAnnouncement) {
-       unsafe { &mut *this_ptr.inner }.contents = *unsafe { Box::from_raw(val.take_ptr()) };
+       unsafe { &mut *this_ptr.inner }.contents = *unsafe { Box::from_raw(val.take_inner()) };
 }
 #[must_use]
 #[no_mangle]
@@ -2862,9 +2915,27 @@ pub extern "C" fn ChannelAnnouncement_new(mut node_signature_1_arg: crate::c_typ
                node_signature_2: node_signature_2_arg.into_rust(),
                bitcoin_signature_1: bitcoin_signature_1_arg.into_rust(),
                bitcoin_signature_2: bitcoin_signature_2_arg.into_rust(),
-               contents: *unsafe { Box::from_raw(contents_arg.take_ptr()) },
+               contents: *unsafe { Box::from_raw(contents_arg.take_inner()) },
        })), is_owned: true }
 }
+impl Clone for ChannelAnnouncement {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn ChannelAnnouncement_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelAnnouncement)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn ChannelAnnouncement_clone(orig: &ChannelAnnouncement) -> ChannelAnnouncement {
+       orig.clone()
+}
 
 use lightning::ln::msgs::UnsignedChannelUpdate as nativeUnsignedChannelUpdateImport;
 type nativeUnsignedChannelUpdate = nativeUnsignedChannelUpdateImport;
@@ -2896,30 +2967,13 @@ extern "C" fn UnsignedChannelUpdate_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl UnsignedChannelUpdate {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeUnsignedChannelUpdate {
+       pub(crate) fn take_inner(mut self) -> *mut nativeUnsignedChannelUpdate {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for UnsignedChannelUpdate {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn UnsignedChannelUpdate_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeUnsignedChannelUpdate)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn UnsignedChannelUpdate_clone(orig: &UnsignedChannelUpdate) -> UnsignedChannelUpdate {
-       UnsignedChannelUpdate { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// The genesis hash of the blockchain where the channel is to be opened
 #[no_mangle]
 pub extern "C" fn UnsignedChannelUpdate_get_chain_hash(this_ptr: &UnsignedChannelUpdate) -> *const [u8; 32] {
@@ -3008,6 +3062,24 @@ pub extern "C" fn UnsignedChannelUpdate_get_fee_proportional_millionths(this_ptr
 pub extern "C" fn UnsignedChannelUpdate_set_fee_proportional_millionths(this_ptr: &mut UnsignedChannelUpdate, mut val: u32) {
        unsafe { &mut *this_ptr.inner }.fee_proportional_millionths = val;
 }
+impl Clone for UnsignedChannelUpdate {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn UnsignedChannelUpdate_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeUnsignedChannelUpdate)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn UnsignedChannelUpdate_clone(orig: &UnsignedChannelUpdate) -> UnsignedChannelUpdate {
+       orig.clone()
+}
 
 use lightning::ln::msgs::ChannelUpdate as nativeChannelUpdateImport;
 type nativeChannelUpdate = nativeChannelUpdateImport;
@@ -3039,30 +3111,13 @@ extern "C" fn ChannelUpdate_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl ChannelUpdate {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeChannelUpdate {
+       pub(crate) fn take_inner(mut self) -> *mut nativeChannelUpdate {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for ChannelUpdate {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn ChannelUpdate_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelUpdate)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn ChannelUpdate_clone(orig: &ChannelUpdate) -> ChannelUpdate {
-       ChannelUpdate { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// A signature of the channel update
 #[no_mangle]
 pub extern "C" fn ChannelUpdate_get_signature(this_ptr: &ChannelUpdate) -> crate::c_types::Signature {
@@ -3083,16 +3138,34 @@ pub extern "C" fn ChannelUpdate_get_contents(this_ptr: &ChannelUpdate) -> crate:
 /// The actual channel update
 #[no_mangle]
 pub extern "C" fn ChannelUpdate_set_contents(this_ptr: &mut ChannelUpdate, mut val: crate::ln::msgs::UnsignedChannelUpdate) {
-       unsafe { &mut *this_ptr.inner }.contents = *unsafe { Box::from_raw(val.take_ptr()) };
+       unsafe { &mut *this_ptr.inner }.contents = *unsafe { Box::from_raw(val.take_inner()) };
 }
 #[must_use]
 #[no_mangle]
 pub extern "C" fn ChannelUpdate_new(mut signature_arg: crate::c_types::Signature, mut contents_arg: crate::ln::msgs::UnsignedChannelUpdate) -> ChannelUpdate {
        ChannelUpdate { inner: Box::into_raw(Box::new(nativeChannelUpdate {
                signature: signature_arg.into_rust(),
-               contents: *unsafe { Box::from_raw(contents_arg.take_ptr()) },
+               contents: *unsafe { Box::from_raw(contents_arg.take_inner()) },
        })), is_owned: true }
 }
+impl Clone for ChannelUpdate {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn ChannelUpdate_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelUpdate)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn ChannelUpdate_clone(orig: &ChannelUpdate) -> ChannelUpdate {
+       orig.clone()
+}
 
 use lightning::ln::msgs::QueryChannelRange as nativeQueryChannelRangeImport;
 type nativeQueryChannelRange = nativeQueryChannelRangeImport;
@@ -3127,30 +3200,13 @@ extern "C" fn QueryChannelRange_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl QueryChannelRange {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeQueryChannelRange {
+       pub(crate) fn take_inner(mut self) -> *mut nativeQueryChannelRange {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for QueryChannelRange {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn QueryChannelRange_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeQueryChannelRange)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn QueryChannelRange_clone(orig: &QueryChannelRange) -> QueryChannelRange {
-       QueryChannelRange { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// The genesis hash of the blockchain being queried
 #[no_mangle]
 pub extern "C" fn QueryChannelRange_get_chain_hash(this_ptr: &QueryChannelRange) -> *const [u8; 32] {
@@ -3193,6 +3249,24 @@ pub extern "C" fn QueryChannelRange_new(mut chain_hash_arg: crate::c_types::Thir
                number_of_blocks: number_of_blocks_arg,
        })), is_owned: true }
 }
+impl Clone for QueryChannelRange {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn QueryChannelRange_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeQueryChannelRange)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn QueryChannelRange_clone(orig: &QueryChannelRange) -> QueryChannelRange {
+       orig.clone()
+}
 
 use lightning::ln::msgs::ReplyChannelRange as nativeReplyChannelRangeImport;
 type nativeReplyChannelRange = nativeReplyChannelRangeImport;
@@ -3230,30 +3304,13 @@ extern "C" fn ReplyChannelRange_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl ReplyChannelRange {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeReplyChannelRange {
+       pub(crate) fn take_inner(mut self) -> *mut nativeReplyChannelRange {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for ReplyChannelRange {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn ReplyChannelRange_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeReplyChannelRange)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn ReplyChannelRange_clone(orig: &ReplyChannelRange) -> ReplyChannelRange {
-       ReplyChannelRange { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// The genesis hash of the blockchain being queried
 #[no_mangle]
 pub extern "C" fn ReplyChannelRange_get_chain_hash(this_ptr: &ReplyChannelRange) -> *const [u8; 32] {
@@ -3287,18 +3344,16 @@ pub extern "C" fn ReplyChannelRange_get_number_of_blocks(this_ptr: &ReplyChannel
 pub extern "C" fn ReplyChannelRange_set_number_of_blocks(this_ptr: &mut ReplyChannelRange, mut val: u32) {
        unsafe { &mut *this_ptr.inner }.number_of_blocks = val;
 }
-/// Indicates if the query recipient maintains up-to-date channel
-/// information for the chain_hash
+/// True when this is the final reply for a query
 #[no_mangle]
-pub extern "C" fn ReplyChannelRange_get_full_information(this_ptr: &ReplyChannelRange) -> bool {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.full_information;
+pub extern "C" fn ReplyChannelRange_get_sync_complete(this_ptr: &ReplyChannelRange) -> bool {
+       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.sync_complete;
        (*inner_val)
 }
-/// Indicates if the query recipient maintains up-to-date channel
-/// information for the chain_hash
+/// True when this is the final reply for a query
 #[no_mangle]
-pub extern "C" fn ReplyChannelRange_set_full_information(this_ptr: &mut ReplyChannelRange, mut val: bool) {
-       unsafe { &mut *this_ptr.inner }.full_information = val;
+pub extern "C" fn ReplyChannelRange_set_sync_complete(this_ptr: &mut ReplyChannelRange, mut val: bool) {
+       unsafe { &mut *this_ptr.inner }.sync_complete = val;
 }
 /// The short_channel_ids in the channel range
 #[no_mangle]
@@ -3308,16 +3363,34 @@ pub extern "C" fn ReplyChannelRange_set_short_channel_ids(this_ptr: &mut ReplyCh
 }
 #[must_use]
 #[no_mangle]
-pub extern "C" fn ReplyChannelRange_new(mut chain_hash_arg: crate::c_types::ThirtyTwoBytes, mut first_blocknum_arg: u32, mut number_of_blocks_arg: u32, mut full_information_arg: bool, mut short_channel_ids_arg: crate::c_types::derived::CVec_u64Z) -> ReplyChannelRange {
+pub extern "C" fn ReplyChannelRange_new(mut chain_hash_arg: crate::c_types::ThirtyTwoBytes, mut first_blocknum_arg: u32, mut number_of_blocks_arg: u32, mut sync_complete_arg: bool, mut short_channel_ids_arg: crate::c_types::derived::CVec_u64Z) -> ReplyChannelRange {
        let mut local_short_channel_ids_arg = Vec::new(); for mut item in short_channel_ids_arg.into_rust().drain(..) { local_short_channel_ids_arg.push( { item }); };
        ReplyChannelRange { inner: Box::into_raw(Box::new(nativeReplyChannelRange {
                chain_hash: ::bitcoin::hash_types::BlockHash::from_slice(&chain_hash_arg.data[..]).unwrap(),
                first_blocknum: first_blocknum_arg,
                number_of_blocks: number_of_blocks_arg,
-               full_information: full_information_arg,
+               sync_complete: sync_complete_arg,
                short_channel_ids: local_short_channel_ids_arg,
        })), is_owned: true }
 }
+impl Clone for ReplyChannelRange {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn ReplyChannelRange_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeReplyChannelRange)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn ReplyChannelRange_clone(orig: &ReplyChannelRange) -> ReplyChannelRange {
+       orig.clone()
+}
 
 use lightning::ln::msgs::QueryShortChannelIds as nativeQueryShortChannelIdsImport;
 type nativeQueryShortChannelIds = nativeQueryShortChannelIdsImport;
@@ -3356,30 +3429,13 @@ extern "C" fn QueryShortChannelIds_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl QueryShortChannelIds {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeQueryShortChannelIds {
+       pub(crate) fn take_inner(mut self) -> *mut nativeQueryShortChannelIds {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for QueryShortChannelIds {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn QueryShortChannelIds_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeQueryShortChannelIds)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn QueryShortChannelIds_clone(orig: &QueryShortChannelIds) -> QueryShortChannelIds {
-       QueryShortChannelIds { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// The genesis hash of the blockchain being queried
 #[no_mangle]
 pub extern "C" fn QueryShortChannelIds_get_chain_hash(this_ptr: &QueryShortChannelIds) -> *const [u8; 32] {
@@ -3406,6 +3462,24 @@ pub extern "C" fn QueryShortChannelIds_new(mut chain_hash_arg: crate::c_types::T
                short_channel_ids: local_short_channel_ids_arg,
        })), is_owned: true }
 }
+impl Clone for QueryShortChannelIds {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn QueryShortChannelIds_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeQueryShortChannelIds)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn QueryShortChannelIds_clone(orig: &QueryShortChannelIds) -> QueryShortChannelIds {
+       orig.clone()
+}
 
 use lightning::ln::msgs::ReplyShortChannelIdsEnd as nativeReplyShortChannelIdsEndImport;
 type nativeReplyShortChannelIdsEnd = nativeReplyShortChannelIdsEndImport;
@@ -3440,30 +3514,13 @@ extern "C" fn ReplyShortChannelIdsEnd_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl ReplyShortChannelIdsEnd {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeReplyShortChannelIdsEnd {
+       pub(crate) fn take_inner(mut self) -> *mut nativeReplyShortChannelIdsEnd {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for ReplyShortChannelIdsEnd {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn ReplyShortChannelIdsEnd_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeReplyShortChannelIdsEnd)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn ReplyShortChannelIdsEnd_clone(orig: &ReplyShortChannelIdsEnd) -> ReplyShortChannelIdsEnd {
-       ReplyShortChannelIdsEnd { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// The genesis hash of the blockchain that was queried
 #[no_mangle]
 pub extern "C" fn ReplyShortChannelIdsEnd_get_chain_hash(this_ptr: &ReplyShortChannelIdsEnd) -> *const [u8; 32] {
@@ -3496,6 +3553,24 @@ pub extern "C" fn ReplyShortChannelIdsEnd_new(mut chain_hash_arg: crate::c_types
                full_information: full_information_arg,
        })), is_owned: true }
 }
+impl Clone for ReplyShortChannelIdsEnd {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn ReplyShortChannelIdsEnd_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeReplyShortChannelIdsEnd)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn ReplyShortChannelIdsEnd_clone(orig: &ReplyShortChannelIdsEnd) -> ReplyShortChannelIdsEnd {
+       orig.clone()
+}
 
 use lightning::ln::msgs::GossipTimestampFilter as nativeGossipTimestampFilterImport;
 type nativeGossipTimestampFilter = nativeGossipTimestampFilterImport;
@@ -3529,30 +3604,13 @@ extern "C" fn GossipTimestampFilter_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl GossipTimestampFilter {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeGossipTimestampFilter {
+       pub(crate) fn take_inner(mut self) -> *mut nativeGossipTimestampFilter {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for GossipTimestampFilter {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn GossipTimestampFilter_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeGossipTimestampFilter)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn GossipTimestampFilter_clone(orig: &GossipTimestampFilter) -> GossipTimestampFilter {
-       GossipTimestampFilter { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// The genesis hash of the blockchain for channel and node information
 #[no_mangle]
 pub extern "C" fn GossipTimestampFilter_get_chain_hash(this_ptr: &GossipTimestampFilter) -> *const [u8; 32] {
@@ -3595,6 +3653,24 @@ pub extern "C" fn GossipTimestampFilter_new(mut chain_hash_arg: crate::c_types::
                timestamp_range: timestamp_range_arg,
        })), is_owned: true }
 }
+impl Clone for GossipTimestampFilter {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn GossipTimestampFilter_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeGossipTimestampFilter)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn GossipTimestampFilter_clone(orig: &GossipTimestampFilter) -> GossipTimestampFilter {
+       orig.clone()
+}
 /// Used to put an error message in a LightningError
 #[must_use]
 #[derive(Clone)]
@@ -3618,7 +3694,7 @@ impl ErrorAction {
                match self {
                        ErrorAction::DisconnectPeer {ref msg, } => {
                                let mut msg_nonref = (*msg).clone();
-                               let mut local_msg_nonref = if msg_nonref.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(msg_nonref.take_ptr()) } }) };
+                               let mut local_msg_nonref = if msg_nonref.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(msg_nonref.take_inner()) } }) };
                                nativeErrorAction::DisconnectPeer {
                                        msg: local_msg_nonref,
                                }
@@ -3627,7 +3703,7 @@ impl ErrorAction {
                        ErrorAction::SendErrorMessage {ref msg, } => {
                                let mut msg_nonref = (*msg).clone();
                                nativeErrorAction::SendErrorMessage {
-                                       msg: *unsafe { Box::from_raw(msg_nonref.take_ptr()) },
+                                       msg: *unsafe { Box::from_raw(msg_nonref.take_inner()) },
                                }
                        },
                }
@@ -3636,7 +3712,7 @@ impl ErrorAction {
        pub(crate) fn into_native(self) -> nativeErrorAction {
                match self {
                        ErrorAction::DisconnectPeer {mut msg, } => {
-                               let mut local_msg = if msg.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(msg.take_ptr()) } }) };
+                               let mut local_msg = if msg.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(msg.take_inner()) } }) };
                                nativeErrorAction::DisconnectPeer {
                                        msg: local_msg,
                                }
@@ -3644,7 +3720,7 @@ impl ErrorAction {
                        ErrorAction::IgnoreError => nativeErrorAction::IgnoreError,
                        ErrorAction::SendErrorMessage {mut msg, } => {
                                nativeErrorAction::SendErrorMessage {
-                                       msg: *unsafe { Box::from_raw(msg.take_ptr()) },
+                                       msg: *unsafe { Box::from_raw(msg.take_inner()) },
                                }
                        },
                }
@@ -3723,7 +3799,7 @@ extern "C" fn LightningError_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl LightningError {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeLightningError {
+       pub(crate) fn take_inner(mut self) -> *mut nativeLightningError {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
@@ -3760,6 +3836,24 @@ pub extern "C" fn LightningError_new(mut err_arg: crate::c_types::derived::CVec_
                action: action_arg.into_native(),
        })), is_owned: true }
 }
+impl Clone for LightningError {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn LightningError_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeLightningError)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn LightningError_clone(orig: &LightningError) -> LightningError {
+       orig.clone()
+}
 
 use lightning::ln::msgs::CommitmentUpdate as nativeCommitmentUpdateImport;
 type nativeCommitmentUpdate = nativeCommitmentUpdateImport;
@@ -3792,52 +3886,35 @@ extern "C" fn CommitmentUpdate_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl CommitmentUpdate {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeCommitmentUpdate {
+       pub(crate) fn take_inner(mut self) -> *mut nativeCommitmentUpdate {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for CommitmentUpdate {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn CommitmentUpdate_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeCommitmentUpdate)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn CommitmentUpdate_clone(orig: &CommitmentUpdate) -> CommitmentUpdate {
-       CommitmentUpdate { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// update_add_htlc messages which should be sent
 #[no_mangle]
 pub extern "C" fn CommitmentUpdate_set_update_add_htlcs(this_ptr: &mut CommitmentUpdate, mut val: crate::c_types::derived::CVec_UpdateAddHTLCZ) {
-       let mut local_val = Vec::new(); for mut item in val.into_rust().drain(..) { local_val.push( { *unsafe { Box::from_raw(item.take_ptr()) } }); };
+       let mut local_val = Vec::new(); for mut item in val.into_rust().drain(..) { local_val.push( { *unsafe { Box::from_raw(item.take_inner()) } }); };
        unsafe { &mut *this_ptr.inner }.update_add_htlcs = local_val;
 }
 /// update_fulfill_htlc messages which should be sent
 #[no_mangle]
 pub extern "C" fn CommitmentUpdate_set_update_fulfill_htlcs(this_ptr: &mut CommitmentUpdate, mut val: crate::c_types::derived::CVec_UpdateFulfillHTLCZ) {
-       let mut local_val = Vec::new(); for mut item in val.into_rust().drain(..) { local_val.push( { *unsafe { Box::from_raw(item.take_ptr()) } }); };
+       let mut local_val = Vec::new(); for mut item in val.into_rust().drain(..) { local_val.push( { *unsafe { Box::from_raw(item.take_inner()) } }); };
        unsafe { &mut *this_ptr.inner }.update_fulfill_htlcs = local_val;
 }
 /// update_fail_htlc messages which should be sent
 #[no_mangle]
 pub extern "C" fn CommitmentUpdate_set_update_fail_htlcs(this_ptr: &mut CommitmentUpdate, mut val: crate::c_types::derived::CVec_UpdateFailHTLCZ) {
-       let mut local_val = Vec::new(); for mut item in val.into_rust().drain(..) { local_val.push( { *unsafe { Box::from_raw(item.take_ptr()) } }); };
+       let mut local_val = Vec::new(); for mut item in val.into_rust().drain(..) { local_val.push( { *unsafe { Box::from_raw(item.take_inner()) } }); };
        unsafe { &mut *this_ptr.inner }.update_fail_htlcs = local_val;
 }
 /// update_fail_malformed_htlc messages which should be sent
 #[no_mangle]
 pub extern "C" fn CommitmentUpdate_set_update_fail_malformed_htlcs(this_ptr: &mut CommitmentUpdate, mut val: crate::c_types::derived::CVec_UpdateFailMalformedHTLCZ) {
-       let mut local_val = Vec::new(); for mut item in val.into_rust().drain(..) { local_val.push( { *unsafe { Box::from_raw(item.take_ptr()) } }); };
+       let mut local_val = Vec::new(); for mut item in val.into_rust().drain(..) { local_val.push( { *unsafe { Box::from_raw(item.take_inner()) } }); };
        unsafe { &mut *this_ptr.inner }.update_fail_malformed_htlcs = local_val;
 }
 /// An update_fee message which should be sent
@@ -3850,7 +3927,7 @@ pub extern "C" fn CommitmentUpdate_get_update_fee(this_ptr: &CommitmentUpdate) -
 /// An update_fee message which should be sent
 #[no_mangle]
 pub extern "C" fn CommitmentUpdate_set_update_fee(this_ptr: &mut CommitmentUpdate, mut val: crate::ln::msgs::UpdateFee) {
-       let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_ptr()) } }) };
+       let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) };
        unsafe { &mut *this_ptr.inner }.update_fee = local_val;
 }
 /// Finally, the commitment_signed message which should be sent
@@ -3862,25 +3939,43 @@ pub extern "C" fn CommitmentUpdate_get_commitment_signed(this_ptr: &CommitmentUp
 /// Finally, the commitment_signed message which should be sent
 #[no_mangle]
 pub extern "C" fn CommitmentUpdate_set_commitment_signed(this_ptr: &mut CommitmentUpdate, mut val: crate::ln::msgs::CommitmentSigned) {
-       unsafe { &mut *this_ptr.inner }.commitment_signed = *unsafe { Box::from_raw(val.take_ptr()) };
+       unsafe { &mut *this_ptr.inner }.commitment_signed = *unsafe { Box::from_raw(val.take_inner()) };
 }
 #[must_use]
 #[no_mangle]
 pub extern "C" fn CommitmentUpdate_new(mut update_add_htlcs_arg: crate::c_types::derived::CVec_UpdateAddHTLCZ, mut update_fulfill_htlcs_arg: crate::c_types::derived::CVec_UpdateFulfillHTLCZ, mut update_fail_htlcs_arg: crate::c_types::derived::CVec_UpdateFailHTLCZ, mut update_fail_malformed_htlcs_arg: crate::c_types::derived::CVec_UpdateFailMalformedHTLCZ, mut update_fee_arg: crate::ln::msgs::UpdateFee, mut commitment_signed_arg: crate::ln::msgs::CommitmentSigned) -> CommitmentUpdate {
-       let mut local_update_add_htlcs_arg = Vec::new(); for mut item in update_add_htlcs_arg.into_rust().drain(..) { local_update_add_htlcs_arg.push( { *unsafe { Box::from_raw(item.take_ptr()) } }); };
-       let mut local_update_fulfill_htlcs_arg = Vec::new(); for mut item in update_fulfill_htlcs_arg.into_rust().drain(..) { local_update_fulfill_htlcs_arg.push( { *unsafe { Box::from_raw(item.take_ptr()) } }); };
-       let mut local_update_fail_htlcs_arg = Vec::new(); for mut item in update_fail_htlcs_arg.into_rust().drain(..) { local_update_fail_htlcs_arg.push( { *unsafe { Box::from_raw(item.take_ptr()) } }); };
-       let mut local_update_fail_malformed_htlcs_arg = Vec::new(); for mut item in update_fail_malformed_htlcs_arg.into_rust().drain(..) { local_update_fail_malformed_htlcs_arg.push( { *unsafe { Box::from_raw(item.take_ptr()) } }); };
-       let mut local_update_fee_arg = if update_fee_arg.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(update_fee_arg.take_ptr()) } }) };
+       let mut local_update_add_htlcs_arg = Vec::new(); for mut item in update_add_htlcs_arg.into_rust().drain(..) { local_update_add_htlcs_arg.push( { *unsafe { Box::from_raw(item.take_inner()) } }); };
+       let mut local_update_fulfill_htlcs_arg = Vec::new(); for mut item in update_fulfill_htlcs_arg.into_rust().drain(..) { local_update_fulfill_htlcs_arg.push( { *unsafe { Box::from_raw(item.take_inner()) } }); };
+       let mut local_update_fail_htlcs_arg = Vec::new(); for mut item in update_fail_htlcs_arg.into_rust().drain(..) { local_update_fail_htlcs_arg.push( { *unsafe { Box::from_raw(item.take_inner()) } }); };
+       let mut local_update_fail_malformed_htlcs_arg = Vec::new(); for mut item in update_fail_malformed_htlcs_arg.into_rust().drain(..) { local_update_fail_malformed_htlcs_arg.push( { *unsafe { Box::from_raw(item.take_inner()) } }); };
+       let mut local_update_fee_arg = if update_fee_arg.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(update_fee_arg.take_inner()) } }) };
        CommitmentUpdate { inner: Box::into_raw(Box::new(nativeCommitmentUpdate {
                update_add_htlcs: local_update_add_htlcs_arg,
                update_fulfill_htlcs: local_update_fulfill_htlcs_arg,
                update_fail_htlcs: local_update_fail_htlcs_arg,
                update_fail_malformed_htlcs: local_update_fail_malformed_htlcs_arg,
                update_fee: local_update_fee_arg,
-               commitment_signed: *unsafe { Box::from_raw(commitment_signed_arg.take_ptr()) },
+               commitment_signed: *unsafe { Box::from_raw(commitment_signed_arg.take_inner()) },
        })), is_owned: true }
 }
+impl Clone for CommitmentUpdate {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn CommitmentUpdate_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeCommitmentUpdate)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn CommitmentUpdate_clone(orig: &CommitmentUpdate) -> CommitmentUpdate {
+       orig.clone()
+}
 /// The information we received from a peer along the route of a payment we originated. This is
 /// returned by ChannelMessageHandler::handle_update_fail_htlc to be passed into
 /// RoutingMessageHandler::handle_htlc_fail_channel_update to update our network map.
@@ -3911,7 +4006,7 @@ impl HTLCFailChannelUpdate {
                        HTLCFailChannelUpdate::ChannelUpdateMessage {ref msg, } => {
                                let mut msg_nonref = (*msg).clone();
                                nativeHTLCFailChannelUpdate::ChannelUpdateMessage {
-                                       msg: *unsafe { Box::from_raw(msg_nonref.take_ptr()) },
+                                       msg: *unsafe { Box::from_raw(msg_nonref.take_inner()) },
                                }
                        },
                        HTLCFailChannelUpdate::ChannelClosed {ref short_channel_id, ref is_permanent, } => {
@@ -3937,7 +4032,7 @@ impl HTLCFailChannelUpdate {
                match self {
                        HTLCFailChannelUpdate::ChannelUpdateMessage {mut msg, } => {
                                nativeHTLCFailChannelUpdate::ChannelUpdateMessage {
-                                       msg: *unsafe { Box::from_raw(msg.take_ptr()) },
+                                       msg: *unsafe { Box::from_raw(msg.take_inner()) },
                                }
                        },
                        HTLCFailChannelUpdate::ChannelClosed {mut short_channel_id, mut is_permanent, } => {
@@ -4028,7 +4123,7 @@ pub struct ChannelMessageHandler {
        /// Handle an incoming funding_locked message from the given peer.
        pub handle_funding_locked: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, msg: &crate::ln::msgs::FundingLocked),
        /// Handle an incoming shutdown message from the given peer.
-       pub handle_shutdown: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, msg: &crate::ln::msgs::Shutdown),
+       pub handle_shutdown: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, their_features: &crate::ln::features::InitFeatures, msg: &crate::ln::msgs::Shutdown),
        /// Handle an incoming closing_signed message from the given peer.
        pub handle_closing_signed: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, msg: &crate::ln::msgs::ClosingSigned),
        /// Handle an incoming update_add_htlc message from the given peer.
@@ -4086,8 +4181,8 @@ impl rustChannelMessageHandler for ChannelMessageHandler {
        fn handle_funding_locked(&self, their_node_id: &bitcoin::secp256k1::key::PublicKey, msg: &lightning::ln::msgs::FundingLocked) {
                (self.handle_funding_locked)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::ln::msgs::FundingLocked { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false })
        }
-       fn handle_shutdown(&self, their_node_id: &bitcoin::secp256k1::key::PublicKey, msg: &lightning::ln::msgs::Shutdown) {
-               (self.handle_shutdown)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::ln::msgs::Shutdown { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false })
+       fn handle_shutdown(&self, their_node_id: &bitcoin::secp256k1::key::PublicKey, their_features: &lightning::ln::features::InitFeatures, msg: &lightning::ln::msgs::Shutdown) {
+               (self.handle_shutdown)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::ln::features::InitFeatures { inner: unsafe { (their_features as *const _) as *mut _ }, is_owned: false }, &crate::ln::msgs::Shutdown { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false })
        }
        fn handle_closing_signed(&self, their_node_id: &bitcoin::secp256k1::key::PublicKey, msg: &lightning::ln::msgs::ClosingSigned) {
                (self.handle_closing_signed)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::ln::msgs::ClosingSigned { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false })
@@ -4149,6 +4244,12 @@ impl Drop for ChannelMessageHandler {
        }
 }
 /// A trait to describe an object which can receive routing messages.
+///
+/// # Implementor DoS Warnings
+///
+/// For `gossip_queries` messages there are potential DoS vectors when handling
+/// inbound queries. Implementors using an on-disk network graph should be aware of
+/// repeated disk I/O for queries accessing different parts of the network graph.
 #[repr(C)]
 pub struct RoutingMessageHandler {
        pub this_arg: *mut c_void,
@@ -4177,29 +4278,55 @@ pub struct RoutingMessageHandler {
        /// If None is provided for starting_point, we start at the first node.
        #[must_use]
        pub get_next_node_announcements: extern "C" fn (this_arg: *const c_void, starting_point: crate::c_types::PublicKey, batch_amount: u8) -> crate::c_types::derived::CVec_NodeAnnouncementZ,
-       /// Returns whether a full sync should be requested from a peer.
+       /// Called when a connection is established with a peer. This can be used to
+       /// perform routing table synchronization using a strategy defined by the
+       /// implementor.
+       pub sync_routing_table: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, init: &crate::ln::msgs::Init),
+       /// Handles the reply of a query we initiated to learn about channels
+       /// for a given range of blocks. We can expect to receive one or more
+       /// replies to a single query.
+       #[must_use]
+       pub handle_reply_channel_range: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, msg: crate::ln::msgs::ReplyChannelRange) -> crate::c_types::derived::CResult_NoneLightningErrorZ,
+       /// Handles the reply of a query we initiated asking for routing gossip
+       /// messages for a list of channels. We should receive this message when
+       /// a node has completed its best effort to send us the pertaining routing
+       /// gossip messages.
+       #[must_use]
+       pub handle_reply_short_channel_ids_end: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, msg: crate::ln::msgs::ReplyShortChannelIdsEnd) -> crate::c_types::derived::CResult_NoneLightningErrorZ,
+       /// Handles when a peer asks us to send a list of short_channel_ids
+       /// for the requested range of blocks.
        #[must_use]
-       pub should_request_full_sync: extern "C" fn (this_arg: *const c_void, node_id: crate::c_types::PublicKey) -> bool,
+       pub handle_query_channel_range: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, msg: crate::ln::msgs::QueryChannelRange) -> crate::c_types::derived::CResult_NoneLightningErrorZ,
+       /// Handles when a peer asks us to send routing gossip messages for a
+       /// list of short_channel_ids.
+       #[must_use]
+       pub handle_query_short_channel_ids: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, msg: crate::ln::msgs::QueryShortChannelIds) -> crate::c_types::derived::CResult_NoneLightningErrorZ,
+       pub MessageSendEventsProvider: crate::util::events::MessageSendEventsProvider,
        pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
 }
 unsafe impl Send for RoutingMessageHandler {}
 unsafe impl Sync for RoutingMessageHandler {}
+impl lightning::util::events::MessageSendEventsProvider for RoutingMessageHandler {
+       fn get_and_clear_pending_msg_events(&self) -> Vec<lightning::util::events::MessageSendEvent> {
+               <crate::util::events::MessageSendEventsProvider as lightning::util::events::MessageSendEventsProvider>::get_and_clear_pending_msg_events(&self.MessageSendEventsProvider)
+       }
+}
 
 use lightning::ln::msgs::RoutingMessageHandler as rustRoutingMessageHandler;
 impl rustRoutingMessageHandler for RoutingMessageHandler {
        fn handle_node_announcement(&self, msg: &lightning::ln::msgs::NodeAnnouncement) -> Result<bool, lightning::ln::msgs::LightningError> {
                let mut ret = (self.handle_node_announcement)(self.this_arg, &crate::ln::msgs::NodeAnnouncement { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false });
-               let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(ret.contents.result.take_ptr()) }) }), false => Err( { *unsafe { Box::from_raw((*unsafe { Box::from_raw(ret.contents.err.take_ptr()) }).take_ptr()) } })};
+               let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }) }), false => Err( { *unsafe { Box::from_raw((*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).take_inner()) } })};
                local_ret
        }
        fn handle_channel_announcement(&self, msg: &lightning::ln::msgs::ChannelAnnouncement) -> Result<bool, lightning::ln::msgs::LightningError> {
                let mut ret = (self.handle_channel_announcement)(self.this_arg, &crate::ln::msgs::ChannelAnnouncement { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false });
-               let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(ret.contents.result.take_ptr()) }) }), false => Err( { *unsafe { Box::from_raw((*unsafe { Box::from_raw(ret.contents.err.take_ptr()) }).take_ptr()) } })};
+               let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }) }), false => Err( { *unsafe { Box::from_raw((*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).take_inner()) } })};
                local_ret
        }
        fn handle_channel_update(&self, msg: &lightning::ln::msgs::ChannelUpdate) -> Result<bool, lightning::ln::msgs::LightningError> {
                let mut ret = (self.handle_channel_update)(self.this_arg, &crate::ln::msgs::ChannelUpdate { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false });
-               let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(ret.contents.result.take_ptr()) }) }), false => Err( { *unsafe { Box::from_raw((*unsafe { Box::from_raw(ret.contents.err.take_ptr()) }).take_ptr()) } })};
+               let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }) }), false => Err( { *unsafe { Box::from_raw((*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).take_inner()) } })};
                local_ret
        }
        fn handle_htlc_fail_channel_update(&self, update: &lightning::ln::msgs::HTLCFailChannelUpdate) {
@@ -4207,18 +4334,37 @@ impl rustRoutingMessageHandler for RoutingMessageHandler {
        }
        fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(lightning::ln::msgs::ChannelAnnouncement, Option<lightning::ln::msgs::ChannelUpdate>, Option<lightning::ln::msgs::ChannelUpdate>)> {
                let mut ret = (self.get_next_channel_announcements)(self.this_arg, starting_point, batch_amount);
-               let mut local_ret = Vec::new(); for mut item in ret.into_rust().drain(..) { local_ret.push( { let (mut orig_ret_0_0, mut orig_ret_0_1, mut orig_ret_0_2) = item.to_rust(); let mut local_orig_ret_0_1 = if orig_ret_0_1.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(orig_ret_0_1.take_ptr()) } }) }; let mut local_orig_ret_0_2 = if orig_ret_0_2.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(orig_ret_0_2.take_ptr()) } }) }; let mut local_ret_0 = (*unsafe { Box::from_raw(orig_ret_0_0.take_ptr()) }, local_orig_ret_0_1, local_orig_ret_0_2); local_ret_0 }); };
+               let mut local_ret = Vec::new(); for mut item in ret.into_rust().drain(..) { local_ret.push( { let (mut orig_ret_0_0, mut orig_ret_0_1, mut orig_ret_0_2) = item.to_rust(); let mut local_orig_ret_0_1 = if orig_ret_0_1.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(orig_ret_0_1.take_inner()) } }) }; let mut local_orig_ret_0_2 = if orig_ret_0_2.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(orig_ret_0_2.take_inner()) } }) }; let mut local_ret_0 = (*unsafe { Box::from_raw(orig_ret_0_0.take_inner()) }, local_orig_ret_0_1, local_orig_ret_0_2); local_ret_0 }); };
                local_ret
        }
        fn get_next_node_announcements(&self, starting_point: Option<&bitcoin::secp256k1::key::PublicKey>, batch_amount: u8) -> Vec<lightning::ln::msgs::NodeAnnouncement> {
                let mut local_starting_point = if starting_point.is_none() { crate::c_types::PublicKey::null() } else {  { crate::c_types::PublicKey::from_rust(&(starting_point.unwrap())) } };
                let mut ret = (self.get_next_node_announcements)(self.this_arg, local_starting_point, batch_amount);
-               let mut local_ret = Vec::new(); for mut item in ret.into_rust().drain(..) { local_ret.push( { *unsafe { Box::from_raw(item.take_ptr()) } }); };
+               let mut local_ret = Vec::new(); for mut item in ret.into_rust().drain(..) { local_ret.push( { *unsafe { Box::from_raw(item.take_inner()) } }); };
                local_ret
        }
-       fn should_request_full_sync(&self, node_id: &bitcoin::secp256k1::key::PublicKey) -> bool {
-               let mut ret = (self.should_request_full_sync)(self.this_arg, crate::c_types::PublicKey::from_rust(&node_id));
-               ret
+       fn sync_routing_table(&self, their_node_id: &bitcoin::secp256k1::key::PublicKey, init: &lightning::ln::msgs::Init) {
+               (self.sync_routing_table)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::ln::msgs::Init { inner: unsafe { (init as *const _) as *mut _ }, is_owned: false })
+       }
+       fn handle_reply_channel_range(&self, their_node_id: &bitcoin::secp256k1::key::PublicKey, msg: lightning::ln::msgs::ReplyChannelRange) -> Result<(), lightning::ln::msgs::LightningError> {
+               let mut ret = (self.handle_reply_channel_range)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), crate::ln::msgs::ReplyChannelRange { inner: Box::into_raw(Box::new(msg)), is_owned: true });
+               let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { *unsafe { Box::from_raw((*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).take_inner()) } })};
+               local_ret
+       }
+       fn handle_reply_short_channel_ids_end(&self, their_node_id: &bitcoin::secp256k1::key::PublicKey, msg: lightning::ln::msgs::ReplyShortChannelIdsEnd) -> Result<(), lightning::ln::msgs::LightningError> {
+               let mut ret = (self.handle_reply_short_channel_ids_end)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), crate::ln::msgs::ReplyShortChannelIdsEnd { inner: Box::into_raw(Box::new(msg)), is_owned: true });
+               let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { *unsafe { Box::from_raw((*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).take_inner()) } })};
+               local_ret
+       }
+       fn handle_query_channel_range(&self, their_node_id: &bitcoin::secp256k1::key::PublicKey, msg: lightning::ln::msgs::QueryChannelRange) -> Result<(), lightning::ln::msgs::LightningError> {
+               let mut ret = (self.handle_query_channel_range)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), crate::ln::msgs::QueryChannelRange { inner: Box::into_raw(Box::new(msg)), is_owned: true });
+               let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { *unsafe { Box::from_raw((*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).take_inner()) } })};
+               local_ret
+       }
+       fn handle_query_short_channel_ids(&self, their_node_id: &bitcoin::secp256k1::key::PublicKey, msg: lightning::ln::msgs::QueryShortChannelIds) -> Result<(), lightning::ln::msgs::LightningError> {
+               let mut ret = (self.handle_query_short_channel_ids)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), crate::ln::msgs::QueryShortChannelIds { inner: Box::into_raw(Box::new(msg)), is_owned: true });
+               let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { *unsafe { Box::from_raw((*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).take_inner()) } })};
+               local_ret
        }
 }
 
@@ -4241,374 +4387,436 @@ impl Drop for RoutingMessageHandler {
        }
 }
 #[no_mangle]
-pub extern "C" fn AcceptChannel_write(obj: *const AcceptChannel) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub extern "C" fn AcceptChannel_write(obj: &AcceptChannel) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
 }
 #[no_mangle]
-pub extern "C" fn AcceptChannel_read(ser: crate::c_types::u8slice) -> AcceptChannel {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               AcceptChannel { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               AcceptChannel { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub(crate) extern "C" fn AcceptChannel_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeAcceptChannel) })
 }
 #[no_mangle]
-pub extern "C" fn AnnouncementSignatures_write(obj: *const AnnouncementSignatures) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub extern "C" fn AcceptChannel_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_AcceptChannelDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::msgs::AcceptChannel { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
 }
 #[no_mangle]
-pub extern "C" fn AnnouncementSignatures_read(ser: crate::c_types::u8slice) -> AnnouncementSignatures {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               AnnouncementSignatures { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               AnnouncementSignatures { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub extern "C" fn AnnouncementSignatures_write(obj: &AnnouncementSignatures) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
 }
 #[no_mangle]
-pub extern "C" fn ChannelReestablish_write(obj: *const ChannelReestablish) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub(crate) extern "C" fn AnnouncementSignatures_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeAnnouncementSignatures) })
 }
 #[no_mangle]
-pub extern "C" fn ChannelReestablish_read(ser: crate::c_types::u8slice) -> ChannelReestablish {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               ChannelReestablish { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               ChannelReestablish { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub extern "C" fn AnnouncementSignatures_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_AnnouncementSignaturesDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::msgs::AnnouncementSignatures { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
 }
 #[no_mangle]
-pub extern "C" fn ClosingSigned_write(obj: *const ClosingSigned) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub extern "C" fn ChannelReestablish_write(obj: &ChannelReestablish) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
 }
 #[no_mangle]
-pub extern "C" fn ClosingSigned_read(ser: crate::c_types::u8slice) -> ClosingSigned {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               ClosingSigned { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               ClosingSigned { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub(crate) extern "C" fn ChannelReestablish_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeChannelReestablish) })
 }
 #[no_mangle]
-pub extern "C" fn CommitmentSigned_write(obj: *const CommitmentSigned) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub extern "C" fn ChannelReestablish_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelReestablishDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::msgs::ChannelReestablish { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
 }
 #[no_mangle]
-pub extern "C" fn CommitmentSigned_read(ser: crate::c_types::u8slice) -> CommitmentSigned {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               CommitmentSigned { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               CommitmentSigned { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub extern "C" fn ClosingSigned_write(obj: &ClosingSigned) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
 }
 #[no_mangle]
-pub extern "C" fn FundingCreated_write(obj: *const FundingCreated) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub(crate) extern "C" fn ClosingSigned_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeClosingSigned) })
 }
 #[no_mangle]
-pub extern "C" fn FundingCreated_read(ser: crate::c_types::u8slice) -> FundingCreated {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               FundingCreated { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               FundingCreated { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub extern "C" fn ClosingSigned_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ClosingSignedDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::msgs::ClosingSigned { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
 }
 #[no_mangle]
-pub extern "C" fn FundingSigned_write(obj: *const FundingSigned) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub extern "C" fn CommitmentSigned_write(obj: &CommitmentSigned) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
 }
 #[no_mangle]
-pub extern "C" fn FundingSigned_read(ser: crate::c_types::u8slice) -> FundingSigned {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               FundingSigned { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               FundingSigned { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub(crate) extern "C" fn CommitmentSigned_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeCommitmentSigned) })
 }
 #[no_mangle]
-pub extern "C" fn FundingLocked_write(obj: *const FundingLocked) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub extern "C" fn CommitmentSigned_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_CommitmentSignedDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::msgs::CommitmentSigned { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
 }
 #[no_mangle]
-pub extern "C" fn FundingLocked_read(ser: crate::c_types::u8slice) -> FundingLocked {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               FundingLocked { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               FundingLocked { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub extern "C" fn FundingCreated_write(obj: &FundingCreated) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
 }
 #[no_mangle]
-pub extern "C" fn Init_write(obj: *const Init) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub(crate) extern "C" fn FundingCreated_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeFundingCreated) })
 }
 #[no_mangle]
-pub extern "C" fn Init_read(ser: crate::c_types::u8slice) -> Init {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               Init { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               Init { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub extern "C" fn FundingCreated_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_FundingCreatedDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::msgs::FundingCreated { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
 }
 #[no_mangle]
-pub extern "C" fn OpenChannel_write(obj: *const OpenChannel) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub extern "C" fn FundingSigned_write(obj: &FundingSigned) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
 }
 #[no_mangle]
-pub extern "C" fn OpenChannel_read(ser: crate::c_types::u8slice) -> OpenChannel {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               OpenChannel { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               OpenChannel { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub(crate) extern "C" fn FundingSigned_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeFundingSigned) })
 }
 #[no_mangle]
-pub extern "C" fn RevokeAndACK_write(obj: *const RevokeAndACK) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub extern "C" fn FundingSigned_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_FundingSignedDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::msgs::FundingSigned { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
 }
 #[no_mangle]
-pub extern "C" fn RevokeAndACK_read(ser: crate::c_types::u8slice) -> RevokeAndACK {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               RevokeAndACK { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               RevokeAndACK { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub extern "C" fn FundingLocked_write(obj: &FundingLocked) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
 }
 #[no_mangle]
-pub extern "C" fn Shutdown_write(obj: *const Shutdown) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub(crate) extern "C" fn FundingLocked_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeFundingLocked) })
 }
 #[no_mangle]
-pub extern "C" fn Shutdown_read(ser: crate::c_types::u8slice) -> Shutdown {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               Shutdown { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               Shutdown { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub extern "C" fn FundingLocked_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_FundingLockedDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::msgs::FundingLocked { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
 }
 #[no_mangle]
-pub extern "C" fn UpdateFailHTLC_write(obj: *const UpdateFailHTLC) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub extern "C" fn Init_write(obj: &Init) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
 }
 #[no_mangle]
-pub extern "C" fn UpdateFailHTLC_read(ser: crate::c_types::u8slice) -> UpdateFailHTLC {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               UpdateFailHTLC { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               UpdateFailHTLC { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub(crate) extern "C" fn Init_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeInit) })
 }
 #[no_mangle]
-pub extern "C" fn UpdateFailMalformedHTLC_write(obj: *const UpdateFailMalformedHTLC) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub extern "C" fn Init_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_InitDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::msgs::Init { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
 }
 #[no_mangle]
-pub extern "C" fn UpdateFailMalformedHTLC_read(ser: crate::c_types::u8slice) -> UpdateFailMalformedHTLC {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               UpdateFailMalformedHTLC { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               UpdateFailMalformedHTLC { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub extern "C" fn OpenChannel_write(obj: &OpenChannel) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
 }
 #[no_mangle]
-pub extern "C" fn UpdateFee_write(obj: *const UpdateFee) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub(crate) extern "C" fn OpenChannel_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeOpenChannel) })
 }
 #[no_mangle]
-pub extern "C" fn UpdateFee_read(ser: crate::c_types::u8slice) -> UpdateFee {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               UpdateFee { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               UpdateFee { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub extern "C" fn OpenChannel_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_OpenChannelDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::msgs::OpenChannel { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
 }
 #[no_mangle]
-pub extern "C" fn UpdateFulfillHTLC_write(obj: *const UpdateFulfillHTLC) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub extern "C" fn RevokeAndACK_write(obj: &RevokeAndACK) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
 }
 #[no_mangle]
-pub extern "C" fn UpdateFulfillHTLC_read(ser: crate::c_types::u8slice) -> UpdateFulfillHTLC {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               UpdateFulfillHTLC { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               UpdateFulfillHTLC { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub(crate) extern "C" fn RevokeAndACK_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeRevokeAndACK) })
 }
 #[no_mangle]
-pub extern "C" fn UpdateAddHTLC_write(obj: *const UpdateAddHTLC) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub extern "C" fn RevokeAndACK_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_RevokeAndACKDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::msgs::RevokeAndACK { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
 }
 #[no_mangle]
-pub extern "C" fn UpdateAddHTLC_read(ser: crate::c_types::u8slice) -> UpdateAddHTLC {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               UpdateAddHTLC { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               UpdateAddHTLC { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub extern "C" fn Shutdown_write(obj: &Shutdown) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
 }
 #[no_mangle]
-pub extern "C" fn Ping_write(obj: *const Ping) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub(crate) extern "C" fn Shutdown_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeShutdown) })
 }
 #[no_mangle]
-pub extern "C" fn Ping_read(ser: crate::c_types::u8slice) -> Ping {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               Ping { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               Ping { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub extern "C" fn Shutdown_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ShutdownDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::msgs::Shutdown { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
 }
 #[no_mangle]
-pub extern "C" fn Pong_write(obj: *const Pong) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub extern "C" fn UpdateFailHTLC_write(obj: &UpdateFailHTLC) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
 }
 #[no_mangle]
-pub extern "C" fn Pong_read(ser: crate::c_types::u8slice) -> Pong {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               Pong { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               Pong { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub(crate) extern "C" fn UpdateFailHTLC_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeUpdateFailHTLC) })
 }
 #[no_mangle]
-pub extern "C" fn UnsignedChannelAnnouncement_write(obj: *const UnsignedChannelAnnouncement) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub extern "C" fn UpdateFailHTLC_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_UpdateFailHTLCDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::msgs::UpdateFailHTLC { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
 }
 #[no_mangle]
-pub extern "C" fn UnsignedChannelAnnouncement_read(ser: crate::c_types::u8slice) -> UnsignedChannelAnnouncement {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               UnsignedChannelAnnouncement { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               UnsignedChannelAnnouncement { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub extern "C" fn UpdateFailMalformedHTLC_write(obj: &UpdateFailMalformedHTLC) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
 }
 #[no_mangle]
-pub extern "C" fn ChannelAnnouncement_write(obj: *const ChannelAnnouncement) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub(crate) extern "C" fn UpdateFailMalformedHTLC_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeUpdateFailMalformedHTLC) })
 }
 #[no_mangle]
-pub extern "C" fn ChannelAnnouncement_read(ser: crate::c_types::u8slice) -> ChannelAnnouncement {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               ChannelAnnouncement { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               ChannelAnnouncement { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub extern "C" fn UpdateFailMalformedHTLC_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_UpdateFailMalformedHTLCDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::msgs::UpdateFailMalformedHTLC { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
 }
 #[no_mangle]
-pub extern "C" fn UnsignedChannelUpdate_write(obj: *const UnsignedChannelUpdate) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub extern "C" fn UpdateFee_write(obj: &UpdateFee) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
 }
 #[no_mangle]
-pub extern "C" fn UnsignedChannelUpdate_read(ser: crate::c_types::u8slice) -> UnsignedChannelUpdate {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               UnsignedChannelUpdate { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               UnsignedChannelUpdate { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub(crate) extern "C" fn UpdateFee_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeUpdateFee) })
 }
 #[no_mangle]
-pub extern "C" fn ChannelUpdate_write(obj: *const ChannelUpdate) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub extern "C" fn UpdateFee_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_UpdateFeeDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::msgs::UpdateFee { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
 }
 #[no_mangle]
-pub extern "C" fn ChannelUpdate_read(ser: crate::c_types::u8slice) -> ChannelUpdate {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               ChannelUpdate { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               ChannelUpdate { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub extern "C" fn UpdateFulfillHTLC_write(obj: &UpdateFulfillHTLC) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
 }
 #[no_mangle]
-pub extern "C" fn ErrorMessage_write(obj: *const ErrorMessage) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub(crate) extern "C" fn UpdateFulfillHTLC_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeUpdateFulfillHTLC) })
 }
 #[no_mangle]
-pub extern "C" fn ErrorMessage_read(ser: crate::c_types::u8slice) -> ErrorMessage {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               ErrorMessage { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               ErrorMessage { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub extern "C" fn UpdateFulfillHTLC_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_UpdateFulfillHTLCDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::msgs::UpdateFulfillHTLC { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
 }
 #[no_mangle]
-pub extern "C" fn UnsignedNodeAnnouncement_write(obj: *const UnsignedNodeAnnouncement) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub extern "C" fn UpdateAddHTLC_write(obj: &UpdateAddHTLC) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
 }
 #[no_mangle]
-pub extern "C" fn UnsignedNodeAnnouncement_read(ser: crate::c_types::u8slice) -> UnsignedNodeAnnouncement {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               UnsignedNodeAnnouncement { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               UnsignedNodeAnnouncement { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub(crate) extern "C" fn UpdateAddHTLC_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeUpdateAddHTLC) })
 }
 #[no_mangle]
-pub extern "C" fn NodeAnnouncement_write(obj: *const NodeAnnouncement) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub extern "C" fn UpdateAddHTLC_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_UpdateAddHTLCDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::msgs::UpdateAddHTLC { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
 }
 #[no_mangle]
-pub extern "C" fn NodeAnnouncement_read(ser: crate::c_types::u8slice) -> NodeAnnouncement {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               NodeAnnouncement { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               NodeAnnouncement { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub extern "C" fn Ping_write(obj: &Ping) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
 }
 #[no_mangle]
-pub extern "C" fn QueryShortChannelIds_read(ser: crate::c_types::u8slice) -> QueryShortChannelIds {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               QueryShortChannelIds { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               QueryShortChannelIds { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub(crate) extern "C" fn Ping_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativePing) })
 }
 #[no_mangle]
-pub extern "C" fn QueryShortChannelIds_write(obj: *const QueryShortChannelIds) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub extern "C" fn Ping_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_PingDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::msgs::Ping { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
 }
 #[no_mangle]
-pub extern "C" fn ReplyShortChannelIdsEnd_read(ser: crate::c_types::u8slice) -> ReplyShortChannelIdsEnd {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               ReplyShortChannelIdsEnd { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               ReplyShortChannelIdsEnd { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub extern "C" fn Pong_write(obj: &Pong) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
 }
 #[no_mangle]
-pub extern "C" fn ReplyShortChannelIdsEnd_write(obj: *const ReplyShortChannelIdsEnd) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub(crate) extern "C" fn Pong_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativePong) })
 }
 #[no_mangle]
-pub extern "C" fn QueryChannelRange_read(ser: crate::c_types::u8slice) -> QueryChannelRange {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               QueryChannelRange { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               QueryChannelRange { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub extern "C" fn Pong_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_PongDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::msgs::Pong { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
 }
 #[no_mangle]
-pub extern "C" fn QueryChannelRange_write(obj: *const QueryChannelRange) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub extern "C" fn UnsignedChannelAnnouncement_write(obj: &UnsignedChannelAnnouncement) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
 }
 #[no_mangle]
-pub extern "C" fn ReplyChannelRange_read(ser: crate::c_types::u8slice) -> ReplyChannelRange {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               ReplyChannelRange { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               ReplyChannelRange { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub(crate) extern "C" fn UnsignedChannelAnnouncement_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeUnsignedChannelAnnouncement) })
 }
 #[no_mangle]
-pub extern "C" fn ReplyChannelRange_write(obj: *const ReplyChannelRange) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub extern "C" fn UnsignedChannelAnnouncement_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_UnsignedChannelAnnouncementDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::msgs::UnsignedChannelAnnouncement { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
 }
 #[no_mangle]
-pub extern "C" fn GossipTimestampFilter_read(ser: crate::c_types::u8slice) -> GossipTimestampFilter {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               GossipTimestampFilter { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               GossipTimestampFilter { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub extern "C" fn ChannelAnnouncement_write(obj: &ChannelAnnouncement) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+}
+#[no_mangle]
+pub(crate) extern "C" fn ChannelAnnouncement_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeChannelAnnouncement) })
+}
+#[no_mangle]
+pub extern "C" fn ChannelAnnouncement_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelAnnouncementDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::msgs::ChannelAnnouncement { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
+}
+#[no_mangle]
+pub extern "C" fn UnsignedChannelUpdate_write(obj: &UnsignedChannelUpdate) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+}
+#[no_mangle]
+pub(crate) extern "C" fn UnsignedChannelUpdate_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeUnsignedChannelUpdate) })
+}
+#[no_mangle]
+pub extern "C" fn UnsignedChannelUpdate_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_UnsignedChannelUpdateDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::msgs::UnsignedChannelUpdate { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
+}
+#[no_mangle]
+pub extern "C" fn ChannelUpdate_write(obj: &ChannelUpdate) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+}
+#[no_mangle]
+pub(crate) extern "C" fn ChannelUpdate_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeChannelUpdate) })
+}
+#[no_mangle]
+pub extern "C" fn ChannelUpdate_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelUpdateDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::msgs::ChannelUpdate { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
+}
+#[no_mangle]
+pub extern "C" fn ErrorMessage_write(obj: &ErrorMessage) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+}
+#[no_mangle]
+pub(crate) extern "C" fn ErrorMessage_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeErrorMessage) })
+}
+#[no_mangle]
+pub extern "C" fn ErrorMessage_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ErrorMessageDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::msgs::ErrorMessage { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
+}
+#[no_mangle]
+pub extern "C" fn UnsignedNodeAnnouncement_write(obj: &UnsignedNodeAnnouncement) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+}
+#[no_mangle]
+pub(crate) extern "C" fn UnsignedNodeAnnouncement_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeUnsignedNodeAnnouncement) })
+}
+#[no_mangle]
+pub extern "C" fn UnsignedNodeAnnouncement_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_UnsignedNodeAnnouncementDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::msgs::UnsignedNodeAnnouncement { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
+}
+#[no_mangle]
+pub extern "C" fn NodeAnnouncement_write(obj: &NodeAnnouncement) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+}
+#[no_mangle]
+pub(crate) extern "C" fn NodeAnnouncement_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeNodeAnnouncement) })
+}
+#[no_mangle]
+pub extern "C" fn NodeAnnouncement_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_NodeAnnouncementDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::msgs::NodeAnnouncement { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
+}
+#[no_mangle]
+pub extern "C" fn QueryShortChannelIds_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_QueryShortChannelIdsDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::msgs::QueryShortChannelIds { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
+}
+#[no_mangle]
+pub extern "C" fn QueryShortChannelIds_write(obj: &QueryShortChannelIds) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+}
+#[no_mangle]
+pub(crate) extern "C" fn QueryShortChannelIds_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeQueryShortChannelIds) })
+}
+#[no_mangle]
+pub extern "C" fn ReplyShortChannelIdsEnd_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ReplyShortChannelIdsEndDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::msgs::ReplyShortChannelIdsEnd { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
+}
+#[no_mangle]
+pub extern "C" fn ReplyShortChannelIdsEnd_write(obj: &ReplyShortChannelIdsEnd) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+}
+#[no_mangle]
+pub(crate) extern "C" fn ReplyShortChannelIdsEnd_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeReplyShortChannelIdsEnd) })
+}
+#[no_mangle]
+pub extern "C" fn QueryChannelRange_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_QueryChannelRangeDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::msgs::QueryChannelRange { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
+}
+#[no_mangle]
+pub extern "C" fn QueryChannelRange_write(obj: &QueryChannelRange) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+}
+#[no_mangle]
+pub(crate) extern "C" fn QueryChannelRange_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeQueryChannelRange) })
+}
+#[no_mangle]
+pub extern "C" fn ReplyChannelRange_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ReplyChannelRangeDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::msgs::ReplyChannelRange { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
+}
+#[no_mangle]
+pub extern "C" fn ReplyChannelRange_write(obj: &ReplyChannelRange) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+}
+#[no_mangle]
+pub(crate) extern "C" fn ReplyChannelRange_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeReplyChannelRange) })
+}
+#[no_mangle]
+pub extern "C" fn GossipTimestampFilter_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_GossipTimestampFilterDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::ln::msgs::GossipTimestampFilter { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
+}
+#[no_mangle]
+pub extern "C" fn GossipTimestampFilter_write(obj: &GossipTimestampFilter) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
 }
 #[no_mangle]
-pub extern "C" fn GossipTimestampFilter_write(obj: *const GossipTimestampFilter) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub(crate) extern "C" fn GossipTimestampFilter_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeGossipTimestampFilter) })
 }
index 50e1c3696a8d222e0017a2e6309e8fc2408c0f02..d1b1538f68593e5ae2fc6c7a14c1e54bf4e29092 100644 (file)
@@ -41,7 +41,7 @@ extern "C" fn MessageHandler_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl MessageHandler {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeMessageHandler {
+       pub(crate) fn take_inner(mut self) -> *mut nativeMessageHandler {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
@@ -183,10 +183,8 @@ use lightning::ln::peer_handler::PeerHandleError as nativePeerHandleErrorImport;
 type nativePeerHandleError = nativePeerHandleErrorImport;
 
 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
-/// generate no further read_event/write_buffer_space_avail calls for the descriptor, only
-/// triggering a single socket_disconnected call (unless it was provided in response to a
-/// new_*_connection event, in which case no such socket_disconnected() must be called and the
-/// socket silently disconencted).
+/// generate no further read_event/write_buffer_space_avail/socket_disconnected calls for the
+/// descriptor.
 #[must_use]
 #[repr(C)]
 pub struct PeerHandleError {
@@ -213,7 +211,7 @@ extern "C" fn PeerHandleError_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl PeerHandleError {
-       pub(crate) fn take_ptr(mut self) -> *mut nativePeerHandleError {
+       pub(crate) fn take_inner(mut self) -> *mut nativePeerHandleError {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
@@ -240,6 +238,24 @@ pub extern "C" fn PeerHandleError_new(mut no_connection_possible_arg: bool) -> P
                no_connection_possible: no_connection_possible_arg,
        })), is_owned: true }
 }
+impl Clone for PeerHandleError {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn PeerHandleError_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativePeerHandleError)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn PeerHandleError_clone(orig: &PeerHandleError) -> PeerHandleError {
+       orig.clone()
+}
 
 use lightning::ln::peer_handler::PeerManager as nativePeerManagerImport;
 type nativePeerManager = nativePeerManagerImport<crate::ln::peer_handler::SocketDescriptor, crate::ln::msgs::ChannelMessageHandler, crate::ln::msgs::RoutingMessageHandler, crate::util::logger::Logger>;
@@ -278,7 +294,7 @@ extern "C" fn PeerManager_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl PeerManager {
-       pub(crate) fn take_ptr(mut self) -> *mut nativePeerManager {
+       pub(crate) fn take_inner(mut self) -> *mut nativePeerManager {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
@@ -291,7 +307,7 @@ impl PeerManager {
 #[must_use]
 #[no_mangle]
 pub extern "C" fn PeerManager_new(mut message_handler: crate::ln::peer_handler::MessageHandler, mut our_node_secret: crate::c_types::SecretKey, ephemeral_random_data: *const [u8; 32], mut logger: crate::util::logger::Logger) -> PeerManager {
-       let mut ret = lightning::ln::peer_handler::PeerManager::new(*unsafe { Box::from_raw(message_handler.take_ptr()) }, our_node_secret.into_rust(), unsafe { &*ephemeral_random_data}, logger);
+       let mut ret = lightning::ln::peer_handler::PeerManager::new(*unsafe { Box::from_raw(message_handler.take_inner()) }, our_node_secret.into_rust(), unsafe { &*ephemeral_random_data}, logger);
        PeerManager { inner: Box::into_raw(Box::new(ret)), is_owned: true }
 }
 
@@ -304,7 +320,7 @@ pub extern "C" fn PeerManager_new(mut message_handler: crate::ln::peer_handler::
 #[no_mangle]
 pub extern "C" fn PeerManager_get_peer_node_ids(this_arg: &PeerManager) -> crate::c_types::derived::CVec_PublicKeyZ {
        let mut ret = unsafe { &*this_arg.inner }.get_peer_node_ids();
-       let mut local_ret = Vec::new(); for item in ret.drain(..) { local_ret.push( { crate::c_types::PublicKey::from_rust(&item) }); };
+       let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::c_types::PublicKey::from_rust(&item) }); };
        local_ret.into()
 }
 
@@ -320,7 +336,7 @@ pub extern "C" fn PeerManager_get_peer_node_ids(this_arg: &PeerManager) -> crate
 #[no_mangle]
 pub extern "C" fn PeerManager_new_outbound_connection(this_arg: &PeerManager, mut their_node_id: crate::c_types::PublicKey, mut descriptor: crate::ln::peer_handler::SocketDescriptor) -> crate::c_types::derived::CResult_CVec_u8ZPeerHandleErrorZ {
        let mut ret = unsafe { &*this_arg.inner }.new_outbound_connection(their_node_id.into_rust(), descriptor);
-       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let mut local_ret_0 = Vec::new(); for item in o.drain(..) { local_ret_0.push( { item }); }; local_ret_0.into() }), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::peer_handler::PeerHandleError { inner: Box::into_raw(Box::new(e)), is_owned: true } }) };
+       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::ln::peer_handler::PeerHandleError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
        local_ret
 }
 
@@ -337,7 +353,7 @@ pub extern "C" fn PeerManager_new_outbound_connection(this_arg: &PeerManager, mu
 #[no_mangle]
 pub extern "C" fn PeerManager_new_inbound_connection(this_arg: &PeerManager, mut descriptor: crate::ln::peer_handler::SocketDescriptor) -> crate::c_types::derived::CResult_NonePeerHandleErrorZ {
        let mut ret = unsafe { &*this_arg.inner }.new_inbound_connection(descriptor);
-       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::peer_handler::PeerHandleError { inner: Box::into_raw(Box::new(e)), is_owned: true } }) };
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::peer_handler::PeerHandleError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
        local_ret
 }
 
@@ -355,7 +371,7 @@ pub extern "C" fn PeerManager_new_inbound_connection(this_arg: &PeerManager, mut
 #[no_mangle]
 pub extern "C" fn PeerManager_write_buffer_space_avail(this_arg: &PeerManager, descriptor: &mut crate::ln::peer_handler::SocketDescriptor) -> crate::c_types::derived::CResult_NonePeerHandleErrorZ {
        let mut ret = unsafe { &*this_arg.inner }.write_buffer_space_avail(descriptor);
-       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::peer_handler::PeerHandleError { inner: Box::into_raw(Box::new(e)), is_owned: true } }) };
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::peer_handler::PeerHandleError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
        local_ret
 }
 
@@ -375,7 +391,7 @@ pub extern "C" fn PeerManager_write_buffer_space_avail(this_arg: &PeerManager, d
 #[no_mangle]
 pub extern "C" fn PeerManager_read_event(this_arg: &PeerManager, peer_descriptor: &mut crate::ln::peer_handler::SocketDescriptor, mut data: crate::c_types::u8slice) -> crate::c_types::derived::CResult_boolPeerHandleErrorZ {
        let mut ret = unsafe { &*this_arg.inner }.read_event(peer_descriptor, data.to_slice());
-       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { o }), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::peer_handler::PeerHandleError { inner: Box::into_raw(Box::new(e)), is_owned: true } }) };
+       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::ln::peer_handler::PeerHandleError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
        local_ret
 }
 
@@ -400,6 +416,18 @@ pub extern "C" fn PeerManager_socket_disconnected(this_arg: &PeerManager, descri
        unsafe { &*this_arg.inner }.socket_disconnected(descriptor)
 }
 
+/// Disconnect a peer given its node id.
+///
+/// Set no_connection_possible to true to prevent any further connection with this peer,
+/// force-closing any channels we have with it.
+///
+/// If a peer is connected, this will call `disconnect_socket` on the descriptor for the peer,
+/// so be careful about reentrancy issues.
+#[no_mangle]
+pub extern "C" fn PeerManager_disconnect_by_node_id(this_arg: &PeerManager, mut node_id: crate::c_types::PublicKey, mut no_connection_possible: bool) {
+       unsafe { &*this_arg.inner }.disconnect_by_node_id(node_id.into_rust(), no_connection_possible)
+}
+
 /// This function should be called roughly once every 30 seconds.
 /// It will send pings to each peer and disconnect those which did not respond to the last round of pings.
 /// Will most likely call send_data on all of the registered descriptors, thus, be very careful with reentrancy issues!
index b4c8de585c55dd57450f91c5d300a21de35aa0b8..51d92a18c80795ae3e78574eae2ce48fa1686ccd 100644 (file)
@@ -35,13 +35,31 @@ extern "C" fn NetworkGraph_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl NetworkGraph {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeNetworkGraph {
+       pub(crate) fn take_inner(mut self) -> *mut nativeNetworkGraph {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
+impl Clone for NetworkGraph {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn NetworkGraph_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeNetworkGraph)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn NetworkGraph_clone(orig: &NetworkGraph) -> NetworkGraph {
+       orig.clone()
+}
 
 use lightning::routing::network_graph::LockedNetworkGraph as nativeLockedNetworkGraphImport;
 type nativeLockedNetworkGraph = nativeLockedNetworkGraphImport<'static>;
@@ -75,7 +93,7 @@ extern "C" fn LockedNetworkGraph_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl LockedNetworkGraph {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeLockedNetworkGraph {
+       pub(crate) fn take_inner(mut self) -> *mut nativeLockedNetworkGraph {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
@@ -117,7 +135,7 @@ extern "C" fn NetGraphMsgHandler_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl NetGraphMsgHandler {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeNetGraphMsgHandler {
+       pub(crate) fn take_inner(mut self) -> *mut nativeNetGraphMsgHandler {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
@@ -131,9 +149,9 @@ impl NetGraphMsgHandler {
 /// channel owners' keys.
 #[must_use]
 #[no_mangle]
-pub extern "C" fn NetGraphMsgHandler_new(chain_access: *mut crate::chain::Access, mut logger: crate::util::logger::Logger) -> NetGraphMsgHandler {
+pub extern "C" fn NetGraphMsgHandler_new(mut genesis_hash: crate::c_types::ThirtyTwoBytes, chain_access: *mut crate::chain::Access, mut logger: crate::util::logger::Logger) -> NetGraphMsgHandler {
        let mut local_chain_access = if chain_access == std::ptr::null_mut() { None } else { Some( { unsafe { *Box::from_raw(chain_access) } }) };
-       let mut ret = lightning::routing::network_graph::NetGraphMsgHandler::new(local_chain_access, logger);
+       let mut ret = lightning::routing::network_graph::NetGraphMsgHandler::new(::bitcoin::hash_types::BlockHash::from_slice(&genesis_hash.data[..]).unwrap(), local_chain_access, logger);
        NetGraphMsgHandler { inner: Box::into_raw(Box::new(ret)), is_owned: true }
 }
 
@@ -143,7 +161,7 @@ pub extern "C" fn NetGraphMsgHandler_new(chain_access: *mut crate::chain::Access
 #[no_mangle]
 pub extern "C" fn NetGraphMsgHandler_from_net_graph(chain_access: *mut crate::chain::Access, mut logger: crate::util::logger::Logger, mut network_graph: crate::routing::network_graph::NetworkGraph) -> NetGraphMsgHandler {
        let mut local_chain_access = if chain_access == std::ptr::null_mut() { None } else { Some( { unsafe { *Box::from_raw(chain_access) } }) };
-       let mut ret = lightning::routing::network_graph::NetGraphMsgHandler::from_net_graph(local_chain_access, logger, *unsafe { Box::from_raw(network_graph.take_ptr()) });
+       let mut ret = lightning::routing::network_graph::NetGraphMsgHandler::from_net_graph(local_chain_access, logger, *unsafe { Box::from_raw(network_graph.take_inner()) });
        NetGraphMsgHandler { inner: Box::into_raw(Box::new(ret)), is_owned: true }
 }
 
@@ -166,8 +184,18 @@ pub extern "C" fn LockedNetworkGraph_graph(this_arg: &LockedNetworkGraph) -> cra
        crate::routing::network_graph::NetworkGraph { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false }
 }
 
+impl From<nativeNetGraphMsgHandler> for crate::ln::msgs::RoutingMessageHandler {
+       fn from(obj: nativeNetGraphMsgHandler) -> Self {
+               let mut rust_obj = NetGraphMsgHandler { inner: Box::into_raw(Box::new(obj)), is_owned: true };
+               let mut ret = NetGraphMsgHandler_as_RoutingMessageHandler(&rust_obj);
+               // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
+               rust_obj.inner = std::ptr::null_mut();
+               ret.free = Some(NetGraphMsgHandler_free_void);
+               ret
+       }
+}
 #[no_mangle]
-pub extern "C" fn NetGraphMsgHandler_as_RoutingMessageHandler(this_arg: *const NetGraphMsgHandler) -> crate::ln::msgs::RoutingMessageHandler {
+pub extern "C" fn NetGraphMsgHandler_as_RoutingMessageHandler(this_arg: &NetGraphMsgHandler) -> crate::ln::msgs::RoutingMessageHandler {
        crate::ln::msgs::RoutingMessageHandler {
                this_arg: unsafe { (*this_arg).inner as *mut c_void },
                free: None,
@@ -177,48 +205,112 @@ pub extern "C" fn NetGraphMsgHandler_as_RoutingMessageHandler(this_arg: *const N
                handle_htlc_fail_channel_update: NetGraphMsgHandler_RoutingMessageHandler_handle_htlc_fail_channel_update,
                get_next_channel_announcements: NetGraphMsgHandler_RoutingMessageHandler_get_next_channel_announcements,
                get_next_node_announcements: NetGraphMsgHandler_RoutingMessageHandler_get_next_node_announcements,
-               should_request_full_sync: NetGraphMsgHandler_RoutingMessageHandler_should_request_full_sync,
+               sync_routing_table: NetGraphMsgHandler_RoutingMessageHandler_sync_routing_table,
+               handle_reply_channel_range: NetGraphMsgHandler_RoutingMessageHandler_handle_reply_channel_range,
+               handle_reply_short_channel_ids_end: NetGraphMsgHandler_RoutingMessageHandler_handle_reply_short_channel_ids_end,
+               handle_query_channel_range: NetGraphMsgHandler_RoutingMessageHandler_handle_query_channel_range,
+               handle_query_short_channel_ids: NetGraphMsgHandler_RoutingMessageHandler_handle_query_short_channel_ids,
+               MessageSendEventsProvider: crate::util::events::MessageSendEventsProvider {
+                       this_arg: unsafe { (*this_arg).inner as *mut c_void },
+                       free: None,
+                       get_and_clear_pending_msg_events: NetGraphMsgHandler_RoutingMessageHandler_get_and_clear_pending_msg_events,
+               },
        }
 }
 use lightning::ln::msgs::RoutingMessageHandler as RoutingMessageHandlerTraitImport;
 #[must_use]
 extern "C" fn NetGraphMsgHandler_RoutingMessageHandler_handle_node_announcement(this_arg: *const c_void, msg: &crate::ln::msgs::NodeAnnouncement) -> crate::c_types::derived::CResult_boolLightningErrorZ {
-       let mut ret = unsafe { &mut *(this_arg as *mut nativeNetGraphMsgHandler) }.handle_node_announcement(unsafe { &*msg.inner });
-       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { o }), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }) };
+       let mut ret = <nativeNetGraphMsgHandler as RoutingMessageHandlerTraitImport<>>::handle_node_announcement(unsafe { &mut *(this_arg as *mut nativeNetGraphMsgHandler) }, unsafe { &*msg.inner });
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { o }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
        local_ret
 }
 #[must_use]
 extern "C" fn NetGraphMsgHandler_RoutingMessageHandler_handle_channel_announcement(this_arg: *const c_void, msg: &crate::ln::msgs::ChannelAnnouncement) -> crate::c_types::derived::CResult_boolLightningErrorZ {
-       let mut ret = unsafe { &mut *(this_arg as *mut nativeNetGraphMsgHandler) }.handle_channel_announcement(unsafe { &*msg.inner });
-       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { o }), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }) };
+       let mut ret = <nativeNetGraphMsgHandler as RoutingMessageHandlerTraitImport<>>::handle_channel_announcement(unsafe { &mut *(this_arg as *mut nativeNetGraphMsgHandler) }, unsafe { &*msg.inner });
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { o }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
        local_ret
 }
 extern "C" fn NetGraphMsgHandler_RoutingMessageHandler_handle_htlc_fail_channel_update(this_arg: *const c_void, update: &crate::ln::msgs::HTLCFailChannelUpdate) {
-       unsafe { &mut *(this_arg as *mut nativeNetGraphMsgHandler) }.handle_htlc_fail_channel_update(&update.to_native())
+       <nativeNetGraphMsgHandler as RoutingMessageHandlerTraitImport<>>::handle_htlc_fail_channel_update(unsafe { &mut *(this_arg as *mut nativeNetGraphMsgHandler) }, &update.to_native())
 }
 #[must_use]
 extern "C" fn NetGraphMsgHandler_RoutingMessageHandler_handle_channel_update(this_arg: *const c_void, msg: &crate::ln::msgs::ChannelUpdate) -> crate::c_types::derived::CResult_boolLightningErrorZ {
-       let mut ret = unsafe { &mut *(this_arg as *mut nativeNetGraphMsgHandler) }.handle_channel_update(unsafe { &*msg.inner });
-       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { o }), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }) };
+       let mut ret = <nativeNetGraphMsgHandler as RoutingMessageHandlerTraitImport<>>::handle_channel_update(unsafe { &mut *(this_arg as *mut nativeNetGraphMsgHandler) }, unsafe { &*msg.inner });
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { o }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
        local_ret
 }
 #[must_use]
 extern "C" fn NetGraphMsgHandler_RoutingMessageHandler_get_next_channel_announcements(this_arg: *const c_void, mut starting_point: u64, mut batch_amount: u8) -> crate::c_types::derived::CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ {
-       let mut ret = unsafe { &mut *(this_arg as *mut nativeNetGraphMsgHandler) }.get_next_channel_announcements(starting_point, batch_amount);
-       let mut local_ret = Vec::new(); for item in ret.drain(..) { local_ret.push( { let (mut orig_ret_0_0, mut orig_ret_0_1, mut orig_ret_0_2) = item; let mut local_orig_ret_0_1 = crate::ln::msgs::ChannelUpdate { inner: if orig_ret_0_1.is_none() { std::ptr::null_mut() } else {  { Box::into_raw(Box::new((orig_ret_0_1.unwrap()))) } }, is_owned: true }; let mut local_orig_ret_0_2 = crate::ln::msgs::ChannelUpdate { inner: if orig_ret_0_2.is_none() { std::ptr::null_mut() } else {  { Box::into_raw(Box::new((orig_ret_0_2.unwrap()))) } }, is_owned: true }; let mut local_ret_0 = (crate::ln::msgs::ChannelAnnouncement { inner: Box::into_raw(Box::new(orig_ret_0_0)), is_owned: true }, local_orig_ret_0_1, local_orig_ret_0_2).into(); local_ret_0 }); };
+       let mut ret = <nativeNetGraphMsgHandler as RoutingMessageHandlerTraitImport<>>::get_next_channel_announcements(unsafe { &mut *(this_arg as *mut nativeNetGraphMsgHandler) }, starting_point, batch_amount);
+       let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { let (mut orig_ret_0_0, mut orig_ret_0_1, mut orig_ret_0_2) = item; let mut local_orig_ret_0_1 = crate::ln::msgs::ChannelUpdate { inner: if orig_ret_0_1.is_none() { std::ptr::null_mut() } else {  { Box::into_raw(Box::new((orig_ret_0_1.unwrap()))) } }, is_owned: true }; let mut local_orig_ret_0_2 = crate::ln::msgs::ChannelUpdate { inner: if orig_ret_0_2.is_none() { std::ptr::null_mut() } else {  { Box::into_raw(Box::new((orig_ret_0_2.unwrap()))) } }, is_owned: true }; let mut local_ret_0 = (crate::ln::msgs::ChannelAnnouncement { inner: Box::into_raw(Box::new(orig_ret_0_0)), is_owned: true }, local_orig_ret_0_1, local_orig_ret_0_2).into(); local_ret_0 }); };
        local_ret.into()
 }
 #[must_use]
 extern "C" fn NetGraphMsgHandler_RoutingMessageHandler_get_next_node_announcements(this_arg: *const c_void, mut starting_point: crate::c_types::PublicKey, mut batch_amount: u8) -> crate::c_types::derived::CVec_NodeAnnouncementZ {
        let mut local_starting_point_base = if starting_point.is_null() { None } else { Some( { starting_point.into_rust() }) }; let mut local_starting_point = local_starting_point_base.as_ref();
-       let mut ret = unsafe { &mut *(this_arg as *mut nativeNetGraphMsgHandler) }.get_next_node_announcements(local_starting_point, batch_amount);
-       let mut local_ret = Vec::new(); for item in ret.drain(..) { local_ret.push( { crate::ln::msgs::NodeAnnouncement { inner: Box::into_raw(Box::new(item)), is_owned: true } }); };
+       let mut ret = <nativeNetGraphMsgHandler as RoutingMessageHandlerTraitImport<>>::get_next_node_announcements(unsafe { &mut *(this_arg as *mut nativeNetGraphMsgHandler) }, local_starting_point, batch_amount);
+       let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::ln::msgs::NodeAnnouncement { inner: Box::into_raw(Box::new(item)), is_owned: true } }); };
+       local_ret.into()
+}
+extern "C" fn NetGraphMsgHandler_RoutingMessageHandler_sync_routing_table(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, init_msg: &crate::ln::msgs::Init) {
+       <nativeNetGraphMsgHandler as RoutingMessageHandlerTraitImport<>>::sync_routing_table(unsafe { &mut *(this_arg as *mut nativeNetGraphMsgHandler) }, &their_node_id.into_rust(), unsafe { &*init_msg.inner })
+}
+#[must_use]
+extern "C" fn NetGraphMsgHandler_RoutingMessageHandler_handle_reply_channel_range(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, mut msg: crate::ln::msgs::ReplyChannelRange) -> crate::c_types::derived::CResult_NoneLightningErrorZ {
+       let mut ret = <nativeNetGraphMsgHandler as RoutingMessageHandlerTraitImport<>>::handle_reply_channel_range(unsafe { &mut *(this_arg as *mut nativeNetGraphMsgHandler) }, &their_node_id.into_rust(), *unsafe { Box::from_raw(msg.take_inner()) });
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_ret
+}
+#[must_use]
+extern "C" fn NetGraphMsgHandler_RoutingMessageHandler_handle_reply_short_channel_ids_end(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, mut msg: crate::ln::msgs::ReplyShortChannelIdsEnd) -> crate::c_types::derived::CResult_NoneLightningErrorZ {
+       let mut ret = <nativeNetGraphMsgHandler as RoutingMessageHandlerTraitImport<>>::handle_reply_short_channel_ids_end(unsafe { &mut *(this_arg as *mut nativeNetGraphMsgHandler) }, &their_node_id.into_rust(), *unsafe { Box::from_raw(msg.take_inner()) });
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_ret
+}
+#[must_use]
+extern "C" fn NetGraphMsgHandler_RoutingMessageHandler_handle_query_channel_range(this_arg: *const c_void, mut _their_node_id: crate::c_types::PublicKey, mut _msg: crate::ln::msgs::QueryChannelRange) -> crate::c_types::derived::CResult_NoneLightningErrorZ {
+       let mut ret = <nativeNetGraphMsgHandler as RoutingMessageHandlerTraitImport<>>::handle_query_channel_range(unsafe { &mut *(this_arg as *mut nativeNetGraphMsgHandler) }, &_their_node_id.into_rust(), *unsafe { Box::from_raw(_msg.take_inner()) });
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_ret
+}
+#[must_use]
+extern "C" fn NetGraphMsgHandler_RoutingMessageHandler_handle_query_short_channel_ids(this_arg: *const c_void, mut _their_node_id: crate::c_types::PublicKey, mut _msg: crate::ln::msgs::QueryShortChannelIds) -> crate::c_types::derived::CResult_NoneLightningErrorZ {
+       let mut ret = <nativeNetGraphMsgHandler as RoutingMessageHandlerTraitImport<>>::handle_query_short_channel_ids(unsafe { &mut *(this_arg as *mut nativeNetGraphMsgHandler) }, &_their_node_id.into_rust(), *unsafe { Box::from_raw(_msg.take_inner()) });
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_ret
+}
+use lightning::util::events::MessageSendEventsProvider as nativeMessageSendEventsProviderTrait;
+#[must_use]
+extern "C" fn NetGraphMsgHandler_RoutingMessageHandler_get_and_clear_pending_msg_events(this_arg: *const c_void) -> crate::c_types::derived::CVec_MessageSendEventZ {
+       let mut ret = <nativeNetGraphMsgHandler as MessageSendEventsProviderTraitImport<>>::get_and_clear_pending_msg_events(unsafe { &mut *(this_arg as *mut nativeNetGraphMsgHandler) }, );
+       let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::util::events::MessageSendEvent::native_into(item) }); };
        local_ret.into()
 }
+
+impl From<nativeNetGraphMsgHandler> for crate::util::events::MessageSendEventsProvider {
+       fn from(obj: nativeNetGraphMsgHandler) -> Self {
+               let mut rust_obj = NetGraphMsgHandler { inner: Box::into_raw(Box::new(obj)), is_owned: true };
+               let mut ret = NetGraphMsgHandler_as_MessageSendEventsProvider(&rust_obj);
+               // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
+               rust_obj.inner = std::ptr::null_mut();
+               ret.free = Some(NetGraphMsgHandler_free_void);
+               ret
+       }
+}
+#[no_mangle]
+pub extern "C" fn NetGraphMsgHandler_as_MessageSendEventsProvider(this_arg: &NetGraphMsgHandler) -> crate::util::events::MessageSendEventsProvider {
+       crate::util::events::MessageSendEventsProvider {
+               this_arg: unsafe { (*this_arg).inner as *mut c_void },
+               free: None,
+               get_and_clear_pending_msg_events: NetGraphMsgHandler_MessageSendEventsProvider_get_and_clear_pending_msg_events,
+       }
+}
+use lightning::util::events::MessageSendEventsProvider as MessageSendEventsProviderTraitImport;
 #[must_use]
-extern "C" fn NetGraphMsgHandler_RoutingMessageHandler_should_request_full_sync(this_arg: *const c_void, mut _node_id: crate::c_types::PublicKey) -> bool {
-       let mut ret = unsafe { &mut *(this_arg as *mut nativeNetGraphMsgHandler) }.should_request_full_sync(&_node_id.into_rust());
-       ret
+extern "C" fn NetGraphMsgHandler_MessageSendEventsProvider_get_and_clear_pending_msg_events(this_arg: *const c_void) -> crate::c_types::derived::CVec_MessageSendEventZ {
+       let mut ret = <nativeNetGraphMsgHandler as MessageSendEventsProviderTraitImport<>>::get_and_clear_pending_msg_events(unsafe { &mut *(this_arg as *mut nativeNetGraphMsgHandler) }, );
+       let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::util::events::MessageSendEvent::native_into(item) }); };
+       local_ret.into()
 }
 
 
@@ -253,7 +345,7 @@ extern "C" fn DirectionalChannelInfo_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl DirectionalChannelInfo {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeDirectionalChannelInfo {
+       pub(crate) fn take_inner(mut self) -> *mut nativeDirectionalChannelInfo {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
@@ -306,6 +398,17 @@ pub extern "C" fn DirectionalChannelInfo_get_htlc_minimum_msat(this_ptr: &Direct
 pub extern "C" fn DirectionalChannelInfo_set_htlc_minimum_msat(this_ptr: &mut DirectionalChannelInfo, mut val: u64) {
        unsafe { &mut *this_ptr.inner }.htlc_minimum_msat = val;
 }
+/// Fees charged when the channel is used for routing
+#[no_mangle]
+pub extern "C" fn DirectionalChannelInfo_get_fees(this_ptr: &DirectionalChannelInfo) -> crate::routing::network_graph::RoutingFees {
+       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.fees;
+       crate::routing::network_graph::RoutingFees { inner: unsafe { ( (&((*inner_val)) as *const _) as *mut _) }, is_owned: false }
+}
+/// Fees charged when the channel is used for routing
+#[no_mangle]
+pub extern "C" fn DirectionalChannelInfo_set_fees(this_ptr: &mut DirectionalChannelInfo, mut val: crate::routing::network_graph::RoutingFees) {
+       unsafe { &mut *this_ptr.inner }.fees = *unsafe { Box::from_raw(val.take_inner()) };
+}
 /// Most recent update for the channel received from the network
 /// Mostly redundant with the data we store in fields explicitly.
 /// Everything else is useful only for sending out for initial routing sync.
@@ -322,20 +425,40 @@ pub extern "C" fn DirectionalChannelInfo_get_last_update_message(this_ptr: &Dire
 /// Not stored if contains excess data to prevent DoS.
 #[no_mangle]
 pub extern "C" fn DirectionalChannelInfo_set_last_update_message(this_ptr: &mut DirectionalChannelInfo, mut val: crate::ln::msgs::ChannelUpdate) {
-       let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_ptr()) } }) };
+       let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) };
        unsafe { &mut *this_ptr.inner }.last_update_message = local_val;
 }
+impl Clone for DirectionalChannelInfo {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn DirectionalChannelInfo_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeDirectionalChannelInfo)).clone() })) as *mut c_void
+}
 #[no_mangle]
-pub extern "C" fn DirectionalChannelInfo_write(obj: *const DirectionalChannelInfo) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub extern "C" fn DirectionalChannelInfo_clone(orig: &DirectionalChannelInfo) -> DirectionalChannelInfo {
+       orig.clone()
 }
 #[no_mangle]
-pub extern "C" fn DirectionalChannelInfo_read(ser: crate::c_types::u8slice) -> DirectionalChannelInfo {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               DirectionalChannelInfo { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               DirectionalChannelInfo { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub extern "C" fn DirectionalChannelInfo_write(obj: &DirectionalChannelInfo) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+}
+#[no_mangle]
+pub(crate) extern "C" fn DirectionalChannelInfo_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeDirectionalChannelInfo) })
+}
+#[no_mangle]
+pub extern "C" fn DirectionalChannelInfo_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_DirectionalChannelInfoDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::routing::network_graph::DirectionalChannelInfo { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
 }
 
 use lightning::routing::network_graph::ChannelInfo as nativeChannelInfoImport;
@@ -369,7 +492,7 @@ extern "C" fn ChannelInfo_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl ChannelInfo {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeChannelInfo {
+       pub(crate) fn take_inner(mut self) -> *mut nativeChannelInfo {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
@@ -385,7 +508,7 @@ pub extern "C" fn ChannelInfo_get_features(this_ptr: &ChannelInfo) -> crate::ln:
 /// Protocol features of a channel communicated during its announcement
 #[no_mangle]
 pub extern "C" fn ChannelInfo_set_features(this_ptr: &mut ChannelInfo, mut val: crate::ln::features::ChannelFeatures) {
-       unsafe { &mut *this_ptr.inner }.features = *unsafe { Box::from_raw(val.take_ptr()) };
+       unsafe { &mut *this_ptr.inner }.features = *unsafe { Box::from_raw(val.take_inner()) };
 }
 /// Source node of the first direction of a channel
 #[no_mangle]
@@ -408,7 +531,7 @@ pub extern "C" fn ChannelInfo_get_one_to_two(this_ptr: &ChannelInfo) -> crate::r
 /// Details about the first direction of a channel
 #[no_mangle]
 pub extern "C" fn ChannelInfo_set_one_to_two(this_ptr: &mut ChannelInfo, mut val: crate::routing::network_graph::DirectionalChannelInfo) {
-       let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_ptr()) } }) };
+       let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) };
        unsafe { &mut *this_ptr.inner }.one_to_two = local_val;
 }
 /// Source node of the second direction of a channel
@@ -432,7 +555,7 @@ pub extern "C" fn ChannelInfo_get_two_to_one(this_ptr: &ChannelInfo) -> crate::r
 /// Details about the second direction of a channel
 #[no_mangle]
 pub extern "C" fn ChannelInfo_set_two_to_one(this_ptr: &mut ChannelInfo, mut val: crate::routing::network_graph::DirectionalChannelInfo) {
-       let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_ptr()) } }) };
+       let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) };
        unsafe { &mut *this_ptr.inner }.two_to_one = local_val;
 }
 /// An initial announcement of the channel
@@ -451,20 +574,40 @@ pub extern "C" fn ChannelInfo_get_announcement_message(this_ptr: &ChannelInfo) -
 /// Not stored if contains excess data to prevent DoS.
 #[no_mangle]
 pub extern "C" fn ChannelInfo_set_announcement_message(this_ptr: &mut ChannelInfo, mut val: crate::ln::msgs::ChannelAnnouncement) {
-       let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_ptr()) } }) };
+       let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) };
        unsafe { &mut *this_ptr.inner }.announcement_message = local_val;
 }
+impl Clone for ChannelInfo {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn ChannelInfo_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelInfo)).clone() })) as *mut c_void
+}
 #[no_mangle]
-pub extern "C" fn ChannelInfo_write(obj: *const ChannelInfo) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub extern "C" fn ChannelInfo_clone(orig: &ChannelInfo) -> ChannelInfo {
+       orig.clone()
 }
 #[no_mangle]
-pub extern "C" fn ChannelInfo_read(ser: crate::c_types::u8slice) -> ChannelInfo {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               ChannelInfo { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               ChannelInfo { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub extern "C" fn ChannelInfo_write(obj: &ChannelInfo) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+}
+#[no_mangle]
+pub(crate) extern "C" fn ChannelInfo_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeChannelInfo) })
+}
+#[no_mangle]
+pub extern "C" fn ChannelInfo_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelInfoDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::routing::network_graph::ChannelInfo { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
 }
 
 use lightning::routing::network_graph::RoutingFees as nativeRoutingFeesImport;
@@ -497,30 +640,13 @@ extern "C" fn RoutingFees_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl RoutingFees {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeRoutingFees {
+       pub(crate) fn take_inner(mut self) -> *mut nativeRoutingFees {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for RoutingFees {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn RoutingFees_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeRoutingFees)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn RoutingFees_clone(orig: &RoutingFees) -> RoutingFees {
-       RoutingFees { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// Flat routing fee in satoshis
 #[no_mangle]
 pub extern "C" fn RoutingFees_get_base_msat(this_ptr: &RoutingFees) -> u32 {
@@ -553,17 +679,37 @@ pub extern "C" fn RoutingFees_new(mut base_msat_arg: u32, mut proportional_milli
                proportional_millionths: proportional_millionths_arg,
        })), is_owned: true }
 }
-#[no_mangle]
-pub extern "C" fn RoutingFees_read(ser: crate::c_types::u8slice) -> RoutingFees {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               RoutingFees { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               RoutingFees { inner: std::ptr::null_mut(), is_owned: true }
+impl Clone for RoutingFees {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
        }
 }
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn RoutingFees_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeRoutingFees)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn RoutingFees_clone(orig: &RoutingFees) -> RoutingFees {
+       orig.clone()
+}
+#[no_mangle]
+pub extern "C" fn RoutingFees_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_RoutingFeesDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::routing::network_graph::RoutingFees { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
+}
+#[no_mangle]
+pub extern "C" fn RoutingFees_write(obj: &RoutingFees) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+}
 #[no_mangle]
-pub extern "C" fn RoutingFees_write(obj: *const RoutingFees) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub(crate) extern "C" fn RoutingFees_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeRoutingFees) })
 }
 
 use lightning::routing::network_graph::NodeAnnouncementInfo as nativeNodeAnnouncementInfoImport;
@@ -596,7 +742,7 @@ extern "C" fn NodeAnnouncementInfo_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl NodeAnnouncementInfo {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeNodeAnnouncementInfo {
+       pub(crate) fn take_inner(mut self) -> *mut nativeNodeAnnouncementInfo {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
@@ -612,7 +758,7 @@ pub extern "C" fn NodeAnnouncementInfo_get_features(this_ptr: &NodeAnnouncementI
 /// Protocol features the node announced support for
 #[no_mangle]
 pub extern "C" fn NodeAnnouncementInfo_set_features(this_ptr: &mut NodeAnnouncementInfo, mut val: crate::ln::features::NodeFeatures) {
-       unsafe { &mut *this_ptr.inner }.features = *unsafe { Box::from_raw(val.take_ptr()) };
+       unsafe { &mut *this_ptr.inner }.features = *unsafe { Box::from_raw(val.take_inner()) };
 }
 /// When the last known update to the node state was issued.
 /// Value is opaque, as set in the announcement.
@@ -675,16 +821,16 @@ pub extern "C" fn NodeAnnouncementInfo_get_announcement_message(this_ptr: &NodeA
 /// Not stored if contains excess data to prevent DoS.
 #[no_mangle]
 pub extern "C" fn NodeAnnouncementInfo_set_announcement_message(this_ptr: &mut NodeAnnouncementInfo, mut val: crate::ln::msgs::NodeAnnouncement) {
-       let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_ptr()) } }) };
+       let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) };
        unsafe { &mut *this_ptr.inner }.announcement_message = local_val;
 }
 #[must_use]
 #[no_mangle]
 pub extern "C" fn NodeAnnouncementInfo_new(mut features_arg: crate::ln::features::NodeFeatures, mut last_update_arg: u32, mut rgb_arg: crate::c_types::ThreeBytes, mut alias_arg: crate::c_types::ThirtyTwoBytes, mut addresses_arg: crate::c_types::derived::CVec_NetAddressZ, mut announcement_message_arg: crate::ln::msgs::NodeAnnouncement) -> NodeAnnouncementInfo {
        let mut local_addresses_arg = Vec::new(); for mut item in addresses_arg.into_rust().drain(..) { local_addresses_arg.push( { item.into_native() }); };
-       let mut local_announcement_message_arg = if announcement_message_arg.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(announcement_message_arg.take_ptr()) } }) };
+       let mut local_announcement_message_arg = if announcement_message_arg.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(announcement_message_arg.take_inner()) } }) };
        NodeAnnouncementInfo { inner: Box::into_raw(Box::new(nativeNodeAnnouncementInfo {
-               features: *unsafe { Box::from_raw(features_arg.take_ptr()) },
+               features: *unsafe { Box::from_raw(features_arg.take_inner()) },
                last_update: last_update_arg,
                rgb: rgb_arg.data,
                alias: alias_arg.data,
@@ -692,17 +838,37 @@ pub extern "C" fn NodeAnnouncementInfo_new(mut features_arg: crate::ln::features
                announcement_message: local_announcement_message_arg,
        })), is_owned: true }
 }
+impl Clone for NodeAnnouncementInfo {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn NodeAnnouncementInfo_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeNodeAnnouncementInfo)).clone() })) as *mut c_void
+}
 #[no_mangle]
-pub extern "C" fn NodeAnnouncementInfo_write(obj: *const NodeAnnouncementInfo) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub extern "C" fn NodeAnnouncementInfo_clone(orig: &NodeAnnouncementInfo) -> NodeAnnouncementInfo {
+       orig.clone()
 }
 #[no_mangle]
-pub extern "C" fn NodeAnnouncementInfo_read(ser: crate::c_types::u8slice) -> NodeAnnouncementInfo {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               NodeAnnouncementInfo { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               NodeAnnouncementInfo { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub extern "C" fn NodeAnnouncementInfo_write(obj: &NodeAnnouncementInfo) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+}
+#[no_mangle]
+pub(crate) extern "C" fn NodeAnnouncementInfo_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeNodeAnnouncementInfo) })
+}
+#[no_mangle]
+pub extern "C" fn NodeAnnouncementInfo_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_NodeAnnouncementInfoDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::routing::network_graph::NodeAnnouncementInfo { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
 }
 
 use lightning::routing::network_graph::NodeInfo as nativeNodeInfoImport;
@@ -735,7 +901,7 @@ extern "C" fn NodeInfo_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl NodeInfo {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeNodeInfo {
+       pub(crate) fn take_inner(mut self) -> *mut nativeNodeInfo {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
@@ -762,7 +928,7 @@ pub extern "C" fn NodeInfo_get_lowest_inbound_channel_fees(this_ptr: &NodeInfo)
 /// meaning they don't have to refer to the same channel.
 #[no_mangle]
 pub extern "C" fn NodeInfo_set_lowest_inbound_channel_fees(this_ptr: &mut NodeInfo, mut val: crate::routing::network_graph::RoutingFees) {
-       let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_ptr()) } }) };
+       let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) };
        unsafe { &mut *this_ptr.inner }.lowest_inbound_channel_fees = local_val;
 }
 /// More information about a node from node_announcement.
@@ -779,50 +945,72 @@ pub extern "C" fn NodeInfo_get_announcement_info(this_ptr: &NodeInfo) -> crate::
 /// a channel announcement, but before receiving a node announcement.
 #[no_mangle]
 pub extern "C" fn NodeInfo_set_announcement_info(this_ptr: &mut NodeInfo, mut val: crate::routing::network_graph::NodeAnnouncementInfo) {
-       let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_ptr()) } }) };
+       let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) };
        unsafe { &mut *this_ptr.inner }.announcement_info = local_val;
 }
 #[must_use]
 #[no_mangle]
 pub extern "C" fn NodeInfo_new(mut channels_arg: crate::c_types::derived::CVec_u64Z, mut lowest_inbound_channel_fees_arg: crate::routing::network_graph::RoutingFees, mut announcement_info_arg: crate::routing::network_graph::NodeAnnouncementInfo) -> NodeInfo {
        let mut local_channels_arg = Vec::new(); for mut item in channels_arg.into_rust().drain(..) { local_channels_arg.push( { item }); };
-       let mut local_lowest_inbound_channel_fees_arg = if lowest_inbound_channel_fees_arg.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(lowest_inbound_channel_fees_arg.take_ptr()) } }) };
-       let mut local_announcement_info_arg = if announcement_info_arg.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(announcement_info_arg.take_ptr()) } }) };
+       let mut local_lowest_inbound_channel_fees_arg = if lowest_inbound_channel_fees_arg.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(lowest_inbound_channel_fees_arg.take_inner()) } }) };
+       let mut local_announcement_info_arg = if announcement_info_arg.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(announcement_info_arg.take_inner()) } }) };
        NodeInfo { inner: Box::into_raw(Box::new(nativeNodeInfo {
                channels: local_channels_arg,
                lowest_inbound_channel_fees: local_lowest_inbound_channel_fees_arg,
                announcement_info: local_announcement_info_arg,
        })), is_owned: true }
 }
+impl Clone for NodeInfo {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn NodeInfo_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeNodeInfo)).clone() })) as *mut c_void
+}
 #[no_mangle]
-pub extern "C" fn NodeInfo_write(obj: *const NodeInfo) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub extern "C" fn NodeInfo_clone(orig: &NodeInfo) -> NodeInfo {
+       orig.clone()
 }
 #[no_mangle]
-pub extern "C" fn NodeInfo_read(ser: crate::c_types::u8slice) -> NodeInfo {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               NodeInfo { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               NodeInfo { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub extern "C" fn NodeInfo_write(obj: &NodeInfo) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
 }
 #[no_mangle]
-pub extern "C" fn NetworkGraph_write(obj: *const NetworkGraph) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub(crate) extern "C" fn NodeInfo_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeNodeInfo) })
 }
 #[no_mangle]
-pub extern "C" fn NetworkGraph_read(ser: crate::c_types::u8slice) -> NetworkGraph {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               NetworkGraph { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               NetworkGraph { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub extern "C" fn NodeInfo_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_NodeInfoDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::routing::network_graph::NodeInfo { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
+}
+#[no_mangle]
+pub extern "C" fn NetworkGraph_write(obj: &NetworkGraph) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+}
+#[no_mangle]
+pub(crate) extern "C" fn NetworkGraph_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeNetworkGraph) })
+}
+#[no_mangle]
+pub extern "C" fn NetworkGraph_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_NetworkGraphDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::routing::network_graph::NetworkGraph { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
 }
 /// Creates a new, empty, network graph.
 #[must_use]
 #[no_mangle]
-pub extern "C" fn NetworkGraph_new() -> crate::routing::network_graph::NetworkGraph {
-       let mut ret = lightning::routing::network_graph::NetworkGraph::new();
+pub extern "C" fn NetworkGraph_new(mut genesis_hash: crate::c_types::ThirtyTwoBytes) -> crate::routing::network_graph::NetworkGraph {
+       let mut ret = lightning::routing::network_graph::NetworkGraph::new(::bitcoin::hash_types::BlockHash::from_slice(&genesis_hash.data[..]).unwrap());
        crate::routing::network_graph::NetworkGraph { inner: Box::into_raw(Box::new(ret)), is_owned: true }
 }
 
@@ -835,8 +1023,8 @@ pub extern "C" fn NetworkGraph_new() -> crate::routing::network_graph::NetworkGr
 #[must_use]
 #[no_mangle]
 pub extern "C" fn NetworkGraph_update_node_from_announcement(this_arg: &mut NetworkGraph, msg: &crate::ln::msgs::NodeAnnouncement) -> crate::c_types::derived::CResult_NoneLightningErrorZ {
-       let mut ret = unsafe { &mut (*(this_arg.inner as *mut nativeNetworkGraph)) }.update_node_from_announcement(unsafe { &*msg.inner }, &bitcoin::secp256k1::Secp256k1::new());
-       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }) };
+       let mut ret = unsafe { &mut (*(this_arg.inner as *mut nativeNetworkGraph)) }.update_node_from_announcement(unsafe { &*msg.inner }, secp256k1::SECP256K1);
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
        local_ret
 }
 
@@ -848,7 +1036,7 @@ pub extern "C" fn NetworkGraph_update_node_from_announcement(this_arg: &mut Netw
 #[no_mangle]
 pub extern "C" fn NetworkGraph_update_node_from_unsigned_announcement(this_arg: &mut NetworkGraph, msg: &crate::ln::msgs::UnsignedNodeAnnouncement) -> crate::c_types::derived::CResult_NoneLightningErrorZ {
        let mut ret = unsafe { &mut (*(this_arg.inner as *mut nativeNetworkGraph)) }.update_node_from_unsigned_announcement(unsafe { &*msg.inner });
-       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }) };
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
        local_ret
 }
 
@@ -864,8 +1052,8 @@ pub extern "C" fn NetworkGraph_update_node_from_unsigned_announcement(this_arg:
 #[no_mangle]
 pub extern "C" fn NetworkGraph_update_channel_from_announcement(this_arg: &mut NetworkGraph, msg: &crate::ln::msgs::ChannelAnnouncement, chain_access: *mut crate::chain::Access) -> crate::c_types::derived::CResult_NoneLightningErrorZ {
        let mut local_chain_access = if chain_access == std::ptr::null_mut() { None } else { Some( { unsafe { *Box::from_raw(chain_access) } }) };
-       let mut ret = unsafe { &mut (*(this_arg.inner as *mut nativeNetworkGraph)) }.update_channel_from_announcement(unsafe { &*msg.inner }, &local_chain_access, &bitcoin::secp256k1::Secp256k1::new());
-       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }) };
+       let mut ret = unsafe { &mut (*(this_arg.inner as *mut nativeNetworkGraph)) }.update_channel_from_announcement(unsafe { &*msg.inner }, &local_chain_access, secp256k1::SECP256K1);
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
        local_ret
 }
 
@@ -880,7 +1068,7 @@ pub extern "C" fn NetworkGraph_update_channel_from_announcement(this_arg: &mut N
 pub extern "C" fn NetworkGraph_update_channel_from_unsigned_announcement(this_arg: &mut NetworkGraph, msg: &crate::ln::msgs::UnsignedChannelAnnouncement, chain_access: *mut crate::chain::Access) -> crate::c_types::derived::CResult_NoneLightningErrorZ {
        let mut local_chain_access = if chain_access == std::ptr::null_mut() { None } else { Some( { unsafe { *Box::from_raw(chain_access) } }) };
        let mut ret = unsafe { &mut (*(this_arg.inner as *mut nativeNetworkGraph)) }.update_channel_from_unsigned_announcement(unsafe { &*msg.inner }, &local_chain_access);
-       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }) };
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
        local_ret
 }
 
@@ -902,8 +1090,8 @@ pub extern "C" fn NetworkGraph_close_channel_from_update(this_arg: &mut NetworkG
 #[must_use]
 #[no_mangle]
 pub extern "C" fn NetworkGraph_update_channel(this_arg: &mut NetworkGraph, msg: &crate::ln::msgs::ChannelUpdate) -> crate::c_types::derived::CResult_NoneLightningErrorZ {
-       let mut ret = unsafe { &mut (*(this_arg.inner as *mut nativeNetworkGraph)) }.update_channel(unsafe { &*msg.inner }, &bitcoin::secp256k1::Secp256k1::new());
-       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }) };
+       let mut ret = unsafe { &mut (*(this_arg.inner as *mut nativeNetworkGraph)) }.update_channel(unsafe { &*msg.inner }, secp256k1::SECP256K1);
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
        local_ret
 }
 
@@ -914,7 +1102,7 @@ pub extern "C" fn NetworkGraph_update_channel(this_arg: &mut NetworkGraph, msg:
 #[no_mangle]
 pub extern "C" fn NetworkGraph_update_channel_unsigned(this_arg: &mut NetworkGraph, msg: &crate::ln::msgs::UnsignedChannelUpdate) -> crate::c_types::derived::CResult_NoneLightningErrorZ {
        let mut ret = unsafe { &mut (*(this_arg.inner as *mut nativeNetworkGraph)) }.update_channel_unsigned(unsafe { &*msg.inner });
-       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }) };
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
        local_ret
 }
 
index 8be9528330d2ae41b1b8ba87704690d150b5277a..ba1a18bb8a6c5b75a0d39ede14b5bd3194eefb64 100644 (file)
@@ -38,30 +38,13 @@ extern "C" fn RouteHop_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl RouteHop {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeRouteHop {
+       pub(crate) fn take_inner(mut self) -> *mut nativeRouteHop {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for RouteHop {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn RouteHop_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeRouteHop)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn RouteHop_clone(orig: &RouteHop) -> RouteHop {
-       RouteHop { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// The node_id of the node at this hop.
 #[no_mangle]
 pub extern "C" fn RouteHop_get_pubkey(this_ptr: &RouteHop) -> crate::c_types::PublicKey {
@@ -84,7 +67,7 @@ pub extern "C" fn RouteHop_get_node_features(this_ptr: &RouteHop) -> crate::ln::
 /// amended to match the features present in the invoice this node generated.
 #[no_mangle]
 pub extern "C" fn RouteHop_set_node_features(this_ptr: &mut RouteHop, mut val: crate::ln::features::NodeFeatures) {
-       unsafe { &mut *this_ptr.inner }.node_features = *unsafe { Box::from_raw(val.take_ptr()) };
+       unsafe { &mut *this_ptr.inner }.node_features = *unsafe { Box::from_raw(val.take_inner()) };
 }
 /// The channel that should be used from the previous hop to reach this node.
 #[no_mangle]
@@ -108,7 +91,7 @@ pub extern "C" fn RouteHop_get_channel_features(this_ptr: &RouteHop) -> crate::l
 /// to reach this node.
 #[no_mangle]
 pub extern "C" fn RouteHop_set_channel_features(this_ptr: &mut RouteHop, mut val: crate::ln::features::ChannelFeatures) {
-       unsafe { &mut *this_ptr.inner }.channel_features = *unsafe { Box::from_raw(val.take_ptr()) };
+       unsafe { &mut *this_ptr.inner }.channel_features = *unsafe { Box::from_raw(val.take_inner()) };
 }
 /// The fee taken on this hop. For the last hop, this should be the full value of the payment.
 #[no_mangle]
@@ -139,13 +122,31 @@ pub extern "C" fn RouteHop_set_cltv_expiry_delta(this_ptr: &mut RouteHop, mut va
 pub extern "C" fn RouteHop_new(mut pubkey_arg: crate::c_types::PublicKey, mut node_features_arg: crate::ln::features::NodeFeatures, mut short_channel_id_arg: u64, mut channel_features_arg: crate::ln::features::ChannelFeatures, mut fee_msat_arg: u64, mut cltv_expiry_delta_arg: u32) -> RouteHop {
        RouteHop { inner: Box::into_raw(Box::new(nativeRouteHop {
                pubkey: pubkey_arg.into_rust(),
-               node_features: *unsafe { Box::from_raw(node_features_arg.take_ptr()) },
+               node_features: *unsafe { Box::from_raw(node_features_arg.take_inner()) },
                short_channel_id: short_channel_id_arg,
-               channel_features: *unsafe { Box::from_raw(channel_features_arg.take_ptr()) },
+               channel_features: *unsafe { Box::from_raw(channel_features_arg.take_inner()) },
                fee_msat: fee_msat_arg,
                cltv_expiry_delta: cltv_expiry_delta_arg,
        })), is_owned: true }
 }
+impl Clone for RouteHop {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn RouteHop_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeRouteHop)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn RouteHop_clone(orig: &RouteHop) -> RouteHop {
+       orig.clone()
+}
 
 use lightning::routing::router::Route as nativeRouteImport;
 type nativeRoute = nativeRouteImport;
@@ -178,30 +179,13 @@ extern "C" fn Route_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl Route {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeRoute {
+       pub(crate) fn take_inner(mut self) -> *mut nativeRoute {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for Route {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn Route_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeRoute)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn Route_clone(orig: &Route) -> Route {
-       Route { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
 /// last RouteHop in each path must be the same.
 /// Each entry represents a list of hops, NOT INCLUDING our own, where the last hop is the
@@ -210,28 +194,48 @@ pub extern "C" fn Route_clone(orig: &Route) -> Route {
 /// ensure it is viable.
 #[no_mangle]
 pub extern "C" fn Route_set_paths(this_ptr: &mut Route, mut val: crate::c_types::derived::CVec_CVec_RouteHopZZ) {
-       let mut local_val = Vec::new(); for mut item in val.into_rust().drain(..) { local_val.push( { let mut local_val_0 = Vec::new(); for mut item in item.into_rust().drain(..) { local_val_0.push( { *unsafe { Box::from_raw(item.take_ptr()) } }); }; local_val_0 }); };
+       let mut local_val = Vec::new(); for mut item in val.into_rust().drain(..) { local_val.push( { let mut local_val_0 = Vec::new(); for mut item in item.into_rust().drain(..) { local_val_0.push( { *unsafe { Box::from_raw(item.take_inner()) } }); }; local_val_0 }); };
        unsafe { &mut *this_ptr.inner }.paths = local_val;
 }
 #[must_use]
 #[no_mangle]
 pub extern "C" fn Route_new(mut paths_arg: crate::c_types::derived::CVec_CVec_RouteHopZZ) -> Route {
-       let mut local_paths_arg = Vec::new(); for mut item in paths_arg.into_rust().drain(..) { local_paths_arg.push( { let mut local_paths_arg_0 = Vec::new(); for mut item in item.into_rust().drain(..) { local_paths_arg_0.push( { *unsafe { Box::from_raw(item.take_ptr()) } }); }; local_paths_arg_0 }); };
+       let mut local_paths_arg = Vec::new(); for mut item in paths_arg.into_rust().drain(..) { local_paths_arg.push( { let mut local_paths_arg_0 = Vec::new(); for mut item in item.into_rust().drain(..) { local_paths_arg_0.push( { *unsafe { Box::from_raw(item.take_inner()) } }); }; local_paths_arg_0 }); };
        Route { inner: Box::into_raw(Box::new(nativeRoute {
                paths: local_paths_arg,
        })), is_owned: true }
 }
+impl Clone for Route {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn Route_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeRoute)).clone() })) as *mut c_void
+}
 #[no_mangle]
-pub extern "C" fn Route_write(obj: *const Route) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub extern "C" fn Route_clone(orig: &Route) -> Route {
+       orig.clone()
 }
 #[no_mangle]
-pub extern "C" fn Route_read(ser: crate::c_types::u8slice) -> Route {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               Route { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               Route { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub extern "C" fn Route_write(obj: &Route) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+}
+#[no_mangle]
+pub(crate) extern "C" fn Route_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeRoute) })
+}
+#[no_mangle]
+pub extern "C" fn Route_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_RouteDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::routing::router::Route { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
 }
 
 use lightning::routing::router::RouteHint as nativeRouteHintImport;
@@ -264,30 +268,13 @@ extern "C" fn RouteHint_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl RouteHint {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeRouteHint {
+       pub(crate) fn take_inner(mut self) -> *mut nativeRouteHint {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for RouteHint {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn RouteHint_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeRouteHint)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn RouteHint_clone(orig: &RouteHint) -> RouteHint {
-       RouteHint { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// The node_id of the non-target end of the route
 #[no_mangle]
 pub extern "C" fn RouteHint_get_src_node_id(this_ptr: &RouteHint) -> crate::c_types::PublicKey {
@@ -319,7 +306,7 @@ pub extern "C" fn RouteHint_get_fees(this_ptr: &RouteHint) -> crate::routing::ne
 /// The fees which must be paid to use this channel
 #[no_mangle]
 pub extern "C" fn RouteHint_set_fees(this_ptr: &mut RouteHint, mut val: crate::routing::network_graph::RoutingFees) {
-       unsafe { &mut *this_ptr.inner }.fees = *unsafe { Box::from_raw(val.take_ptr()) };
+       unsafe { &mut *this_ptr.inner }.fees = *unsafe { Box::from_raw(val.take_inner()) };
 }
 /// The difference in CLTV values between this node and the next node.
 #[no_mangle]
@@ -349,11 +336,29 @@ pub extern "C" fn RouteHint_new(mut src_node_id_arg: crate::c_types::PublicKey,
        RouteHint { inner: Box::into_raw(Box::new(nativeRouteHint {
                src_node_id: src_node_id_arg.into_rust(),
                short_channel_id: short_channel_id_arg,
-               fees: *unsafe { Box::from_raw(fees_arg.take_ptr()) },
+               fees: *unsafe { Box::from_raw(fees_arg.take_inner()) },
                cltv_expiry_delta: cltv_expiry_delta_arg,
                htlc_minimum_msat: htlc_minimum_msat_arg,
        })), is_owned: true }
 }
+impl Clone for RouteHint {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn RouteHint_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeRouteHint)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn RouteHint_clone(orig: &RouteHint) -> RouteHint {
+       orig.clone()
+}
 /// Gets a route from us to the given target node.
 ///
 /// Extra routing hops between known nodes and the target will be used if they are included in
@@ -375,7 +380,7 @@ pub extern "C" fn get_route(mut our_node_id: crate::c_types::PublicKey, network:
        let mut local_first_hops_base = if first_hops == std::ptr::null_mut() { None } else { Some( { let mut local_first_hops_0 = Vec::new(); for mut item in unsafe { &mut *first_hops }.as_slice().iter() { local_first_hops_0.push( { unsafe { &*item.inner } }); }; local_first_hops_0 }) }; let mut local_first_hops = local_first_hops_base.as_ref().map(|a| &a[..]);
        let mut local_last_hops = Vec::new(); for mut item in last_hops.as_slice().iter() { local_last_hops.push( { unsafe { &*item.inner } }); };
        let mut ret = lightning::routing::router::get_route(&our_node_id.into_rust(), unsafe { &*network.inner }, &target.into_rust(), local_first_hops, &local_last_hops[..], final_value_msat, final_cltv, logger);
-       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::routing::router::Route { inner: Box::into_raw(Box::new(o)), is_owned: true } }), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }) };
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::routing::router::Route { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
        local_ret
 }
 
index 346ddc344a1a70f174cabc29c0e6b63767dc9f74..78e837485c6f0eef2c2f4eedf109bfca4ddf560f 100644 (file)
@@ -38,30 +38,13 @@ extern "C" fn ChannelHandshakeConfig_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl ChannelHandshakeConfig {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeChannelHandshakeConfig {
+       pub(crate) fn take_inner(mut self) -> *mut nativeChannelHandshakeConfig {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for ChannelHandshakeConfig {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn ChannelHandshakeConfig_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelHandshakeConfig)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn ChannelHandshakeConfig_clone(orig: &ChannelHandshakeConfig) -> ChannelHandshakeConfig {
-       ChannelHandshakeConfig { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// Confirmations we will wait for before considering the channel locked in.
 /// Applied only for inbound channels (see ChannelHandshakeLimits::max_minimum_depth for the
 /// equivalent limit applied to outbound channels).
@@ -146,6 +129,24 @@ pub extern "C" fn ChannelHandshakeConfig_new(mut minimum_depth_arg: u32, mut our
                our_htlc_minimum_msat: our_htlc_minimum_msat_arg,
        })), is_owned: true }
 }
+impl Clone for ChannelHandshakeConfig {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn ChannelHandshakeConfig_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelHandshakeConfig)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn ChannelHandshakeConfig_clone(orig: &ChannelHandshakeConfig) -> ChannelHandshakeConfig {
+       orig.clone()
+}
 #[must_use]
 #[no_mangle]
 pub extern "C" fn ChannelHandshakeConfig_default() -> ChannelHandshakeConfig {
@@ -192,30 +193,13 @@ extern "C" fn ChannelHandshakeLimits_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl ChannelHandshakeLimits {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeChannelHandshakeLimits {
+       pub(crate) fn take_inner(mut self) -> *mut nativeChannelHandshakeLimits {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for ChannelHandshakeLimits {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn ChannelHandshakeLimits_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelHandshakeLimits)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn ChannelHandshakeLimits_clone(orig: &ChannelHandshakeLimits) -> ChannelHandshakeLimits {
-       ChannelHandshakeLimits { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// Minimum allowed satoshis when a channel is funded, this is supplied by the sender and so
 /// only applies to inbound channels.
 ///
@@ -428,6 +412,24 @@ pub extern "C" fn ChannelHandshakeLimits_new(mut min_funding_satoshis_arg: u64,
                their_to_self_delay: their_to_self_delay_arg,
        })), is_owned: true }
 }
+impl Clone for ChannelHandshakeLimits {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn ChannelHandshakeLimits_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelHandshakeLimits)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn ChannelHandshakeLimits_clone(orig: &ChannelHandshakeLimits) -> ChannelHandshakeLimits {
+       orig.clone()
+}
 #[must_use]
 #[no_mangle]
 pub extern "C" fn ChannelHandshakeLimits_default() -> ChannelHandshakeLimits {
@@ -465,30 +467,13 @@ extern "C" fn ChannelConfig_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl ChannelConfig {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeChannelConfig {
+       pub(crate) fn take_inner(mut self) -> *mut nativeChannelConfig {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for ChannelConfig {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn ChannelConfig_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelConfig)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn ChannelConfig_clone(orig: &ChannelConfig) -> ChannelConfig {
-       ChannelConfig { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// Amount (in millionths of a satoshi) the channel will charge per transferred satoshi.
 /// This may be allowed to change at runtime in a later update, however doing so must result in
 /// update messages sent to notify all nodes of our updated relay fee.
@@ -579,22 +564,42 @@ pub extern "C" fn ChannelConfig_new(mut fee_proportional_millionths_arg: u32, mu
                commit_upfront_shutdown_pubkey: commit_upfront_shutdown_pubkey_arg,
        })), is_owned: true }
 }
+impl Clone for ChannelConfig {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn ChannelConfig_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelConfig)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn ChannelConfig_clone(orig: &ChannelConfig) -> ChannelConfig {
+       orig.clone()
+}
 #[must_use]
 #[no_mangle]
 pub extern "C" fn ChannelConfig_default() -> ChannelConfig {
        ChannelConfig { inner: Box::into_raw(Box::new(Default::default())), is_owned: true }
 }
 #[no_mangle]
-pub extern "C" fn ChannelConfig_write(obj: *const ChannelConfig) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
+pub extern "C" fn ChannelConfig_write(obj: &ChannelConfig) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
 }
 #[no_mangle]
-pub extern "C" fn ChannelConfig_read(ser: crate::c_types::u8slice) -> ChannelConfig {
-       if let Ok(res) = crate::c_types::deserialize_obj(ser) {
-               ChannelConfig { inner: Box::into_raw(Box::new(res)), is_owned: true }
-       } else {
-               ChannelConfig { inner: std::ptr::null_mut(), is_owned: true }
-       }
+pub(crate) extern "C" fn ChannelConfig_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeChannelConfig) })
+}
+#[no_mangle]
+pub extern "C" fn ChannelConfig_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelConfigDecodeErrorZ {
+       let res = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::util::config::ChannelConfig { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       local_res
 }
 
 use lightning::util::config::UserConfig as nativeUserConfigImport;
@@ -630,30 +635,13 @@ extern "C" fn UserConfig_free_void(this_ptr: *mut c_void) {
 #[allow(unused)]
 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl UserConfig {
-       pub(crate) fn take_ptr(mut self) -> *mut nativeUserConfig {
+       pub(crate) fn take_inner(mut self) -> *mut nativeUserConfig {
                assert!(self.is_owned);
                let ret = self.inner;
                self.inner = std::ptr::null_mut();
                ret
        }
 }
-impl Clone for UserConfig {
-       fn clone(&self) -> Self {
-               Self {
-                       inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
-                       is_owned: true,
-               }
-       }
-}
-#[allow(unused)]
-/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn UserConfig_clone_void(this_ptr: *const c_void) -> *mut c_void {
-       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeUserConfig)).clone() })) as *mut c_void
-}
-#[no_mangle]
-pub extern "C" fn UserConfig_clone(orig: &UserConfig) -> UserConfig {
-       UserConfig { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
-}
 /// Channel config that we propose to our counterparty.
 #[no_mangle]
 pub extern "C" fn UserConfig_get_own_channel_config(this_ptr: &UserConfig) -> crate::util::config::ChannelHandshakeConfig {
@@ -663,7 +651,7 @@ pub extern "C" fn UserConfig_get_own_channel_config(this_ptr: &UserConfig) -> cr
 /// Channel config that we propose to our counterparty.
 #[no_mangle]
 pub extern "C" fn UserConfig_set_own_channel_config(this_ptr: &mut UserConfig, mut val: crate::util::config::ChannelHandshakeConfig) {
-       unsafe { &mut *this_ptr.inner }.own_channel_config = *unsafe { Box::from_raw(val.take_ptr()) };
+       unsafe { &mut *this_ptr.inner }.own_channel_config = *unsafe { Box::from_raw(val.take_inner()) };
 }
 /// Limits applied to our counterparty's proposed channel config settings.
 #[no_mangle]
@@ -674,7 +662,7 @@ pub extern "C" fn UserConfig_get_peer_channel_config_limits(this_ptr: &UserConfi
 /// Limits applied to our counterparty's proposed channel config settings.
 #[no_mangle]
 pub extern "C" fn UserConfig_set_peer_channel_config_limits(this_ptr: &mut UserConfig, mut val: crate::util::config::ChannelHandshakeLimits) {
-       unsafe { &mut *this_ptr.inner }.peer_channel_config_limits = *unsafe { Box::from_raw(val.take_ptr()) };
+       unsafe { &mut *this_ptr.inner }.peer_channel_config_limits = *unsafe { Box::from_raw(val.take_inner()) };
 }
 /// Channel config which affects behavior during channel lifetime.
 #[no_mangle]
@@ -685,17 +673,35 @@ pub extern "C" fn UserConfig_get_channel_options(this_ptr: &UserConfig) -> crate
 /// Channel config which affects behavior during channel lifetime.
 #[no_mangle]
 pub extern "C" fn UserConfig_set_channel_options(this_ptr: &mut UserConfig, mut val: crate::util::config::ChannelConfig) {
-       unsafe { &mut *this_ptr.inner }.channel_options = *unsafe { Box::from_raw(val.take_ptr()) };
+       unsafe { &mut *this_ptr.inner }.channel_options = *unsafe { Box::from_raw(val.take_inner()) };
 }
 #[must_use]
 #[no_mangle]
 pub extern "C" fn UserConfig_new(mut own_channel_config_arg: crate::util::config::ChannelHandshakeConfig, mut peer_channel_config_limits_arg: crate::util::config::ChannelHandshakeLimits, mut channel_options_arg: crate::util::config::ChannelConfig) -> UserConfig {
        UserConfig { inner: Box::into_raw(Box::new(nativeUserConfig {
-               own_channel_config: *unsafe { Box::from_raw(own_channel_config_arg.take_ptr()) },
-               peer_channel_config_limits: *unsafe { Box::from_raw(peer_channel_config_limits_arg.take_ptr()) },
-               channel_options: *unsafe { Box::from_raw(channel_options_arg.take_ptr()) },
+               own_channel_config: *unsafe { Box::from_raw(own_channel_config_arg.take_inner()) },
+               peer_channel_config_limits: *unsafe { Box::from_raw(peer_channel_config_limits_arg.take_inner()) },
+               channel_options: *unsafe { Box::from_raw(channel_options_arg.take_inner()) },
        })), is_owned: true }
 }
+impl Clone for UserConfig {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if self.inner.is_null() { std::ptr::null_mut() } else {
+                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                       is_owned: true,
+               }
+       }
+}
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn UserConfig_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeUserConfig)).clone() })) as *mut c_void
+}
+#[no_mangle]
+pub extern "C" fn UserConfig_clone(orig: &UserConfig) -> UserConfig {
+       orig.clone()
+}
 #[must_use]
 #[no_mangle]
 pub extern "C" fn UserConfig_default() -> UserConfig {
index e596774b6c137253f0216c365299a32d58c1bef4..52893679e4d5d3a14d19f45751f9bf6ed5e5c41b 100644 (file)
@@ -100,7 +100,7 @@ impl Event {
                                let mut funding_txo_nonref = (*funding_txo).clone();
                                let mut user_channel_id_nonref = (*user_channel_id).clone();
                                nativeEvent::FundingBroadcastSafe {
-                                       funding_txo: *unsafe { Box::from_raw(funding_txo_nonref.take_ptr()) },
+                                       funding_txo: *unsafe { Box::from_raw(funding_txo_nonref.take_inner()) },
                                        user_channel_id: user_channel_id_nonref,
                                }
                        },
@@ -157,7 +157,7 @@ impl Event {
                        },
                        Event::FundingBroadcastSafe {mut funding_txo, mut user_channel_id, } => {
                                nativeEvent::FundingBroadcastSafe {
-                                       funding_txo: *unsafe { Box::from_raw(funding_txo.take_ptr()) },
+                                       funding_txo: *unsafe { Box::from_raw(funding_txo.take_inner()) },
                                        user_channel_id: user_channel_id,
                                }
                        },
@@ -249,7 +249,7 @@ impl Event {
                        },
                        nativeEvent::SpendableOutputs {ref outputs, } => {
                                let mut outputs_nonref = (*outputs).clone();
-                               let mut local_outputs_nonref = Vec::new(); for item in outputs_nonref.drain(..) { local_outputs_nonref.push( { crate::chain::keysinterface::SpendableOutputDescriptor::native_into(item) }); };
+                               let mut local_outputs_nonref = Vec::new(); for mut item in outputs_nonref.drain(..) { local_outputs_nonref.push( { crate::chain::keysinterface::SpendableOutputDescriptor::native_into(item) }); };
                                Event::SpendableOutputs {
                                        outputs: local_outputs_nonref.into(),
                                }
@@ -298,7 +298,7 @@ impl Event {
                                }
                        },
                        nativeEvent::SpendableOutputs {mut outputs, } => {
-                               let mut local_outputs = Vec::new(); for item in outputs.drain(..) { local_outputs.push( { crate::chain::keysinterface::SpendableOutputDescriptor::native_into(item) }); };
+                               let mut local_outputs = Vec::new(); for mut item in outputs.drain(..) { local_outputs.push( { crate::chain::keysinterface::SpendableOutputDescriptor::native_into(item) }); };
                                Event::SpendableOutputs {
                                        outputs: local_outputs.into(),
                                }
@@ -312,6 +312,10 @@ pub extern "C" fn Event_free(this_ptr: Event) { }
 pub extern "C" fn Event_clone(orig: &Event) -> Event {
        orig.clone()
 }
+#[no_mangle]
+pub extern "C" fn Event_write(obj: &Event) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(&unsafe { &*obj }.to_native())
+}
 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
 /// broadcast to most peers).
 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
@@ -407,6 +411,17 @@ pub enum MessageSendEvent {
        PaymentFailureNetworkUpdate {
                update: crate::ln::msgs::HTLCFailChannelUpdate,
        },
+       /// Query a peer for channels with funding transaction UTXOs in a block range.
+       SendChannelRangeQuery {
+               node_id: crate::c_types::PublicKey,
+               msg: crate::ln::msgs::QueryChannelRange,
+       },
+       /// Request routing gossip messages from a peer for a list of channels identified by
+       /// their short_channel_ids.
+       SendShortIdsQuery {
+               node_id: crate::c_types::PublicKey,
+               msg: crate::ln::msgs::QueryShortChannelIds,
+       },
 }
 use lightning::util::events::MessageSendEvent as nativeMessageSendEvent;
 impl MessageSendEvent {
@@ -418,7 +433,7 @@ impl MessageSendEvent {
                                let mut msg_nonref = (*msg).clone();
                                nativeMessageSendEvent::SendAcceptChannel {
                                        node_id: node_id_nonref.into_rust(),
-                                       msg: *unsafe { Box::from_raw(msg_nonref.take_ptr()) },
+                                       msg: *unsafe { Box::from_raw(msg_nonref.take_inner()) },
                                }
                        },
                        MessageSendEvent::SendOpenChannel {ref node_id, ref msg, } => {
@@ -426,7 +441,7 @@ impl MessageSendEvent {
                                let mut msg_nonref = (*msg).clone();
                                nativeMessageSendEvent::SendOpenChannel {
                                        node_id: node_id_nonref.into_rust(),
-                                       msg: *unsafe { Box::from_raw(msg_nonref.take_ptr()) },
+                                       msg: *unsafe { Box::from_raw(msg_nonref.take_inner()) },
                                }
                        },
                        MessageSendEvent::SendFundingCreated {ref node_id, ref msg, } => {
@@ -434,7 +449,7 @@ impl MessageSendEvent {
                                let mut msg_nonref = (*msg).clone();
                                nativeMessageSendEvent::SendFundingCreated {
                                        node_id: node_id_nonref.into_rust(),
-                                       msg: *unsafe { Box::from_raw(msg_nonref.take_ptr()) },
+                                       msg: *unsafe { Box::from_raw(msg_nonref.take_inner()) },
                                }
                        },
                        MessageSendEvent::SendFundingSigned {ref node_id, ref msg, } => {
@@ -442,7 +457,7 @@ impl MessageSendEvent {
                                let mut msg_nonref = (*msg).clone();
                                nativeMessageSendEvent::SendFundingSigned {
                                        node_id: node_id_nonref.into_rust(),
-                                       msg: *unsafe { Box::from_raw(msg_nonref.take_ptr()) },
+                                       msg: *unsafe { Box::from_raw(msg_nonref.take_inner()) },
                                }
                        },
                        MessageSendEvent::SendFundingLocked {ref node_id, ref msg, } => {
@@ -450,7 +465,7 @@ impl MessageSendEvent {
                                let mut msg_nonref = (*msg).clone();
                                nativeMessageSendEvent::SendFundingLocked {
                                        node_id: node_id_nonref.into_rust(),
-                                       msg: *unsafe { Box::from_raw(msg_nonref.take_ptr()) },
+                                       msg: *unsafe { Box::from_raw(msg_nonref.take_inner()) },
                                }
                        },
                        MessageSendEvent::SendAnnouncementSignatures {ref node_id, ref msg, } => {
@@ -458,7 +473,7 @@ impl MessageSendEvent {
                                let mut msg_nonref = (*msg).clone();
                                nativeMessageSendEvent::SendAnnouncementSignatures {
                                        node_id: node_id_nonref.into_rust(),
-                                       msg: *unsafe { Box::from_raw(msg_nonref.take_ptr()) },
+                                       msg: *unsafe { Box::from_raw(msg_nonref.take_inner()) },
                                }
                        },
                        MessageSendEvent::UpdateHTLCs {ref node_id, ref updates, } => {
@@ -466,7 +481,7 @@ impl MessageSendEvent {
                                let mut updates_nonref = (*updates).clone();
                                nativeMessageSendEvent::UpdateHTLCs {
                                        node_id: node_id_nonref.into_rust(),
-                                       updates: *unsafe { Box::from_raw(updates_nonref.take_ptr()) },
+                                       updates: *unsafe { Box::from_raw(updates_nonref.take_inner()) },
                                }
                        },
                        MessageSendEvent::SendRevokeAndACK {ref node_id, ref msg, } => {
@@ -474,7 +489,7 @@ impl MessageSendEvent {
                                let mut msg_nonref = (*msg).clone();
                                nativeMessageSendEvent::SendRevokeAndACK {
                                        node_id: node_id_nonref.into_rust(),
-                                       msg: *unsafe { Box::from_raw(msg_nonref.take_ptr()) },
+                                       msg: *unsafe { Box::from_raw(msg_nonref.take_inner()) },
                                }
                        },
                        MessageSendEvent::SendClosingSigned {ref node_id, ref msg, } => {
@@ -482,7 +497,7 @@ impl MessageSendEvent {
                                let mut msg_nonref = (*msg).clone();
                                nativeMessageSendEvent::SendClosingSigned {
                                        node_id: node_id_nonref.into_rust(),
-                                       msg: *unsafe { Box::from_raw(msg_nonref.take_ptr()) },
+                                       msg: *unsafe { Box::from_raw(msg_nonref.take_inner()) },
                                }
                        },
                        MessageSendEvent::SendShutdown {ref node_id, ref msg, } => {
@@ -490,7 +505,7 @@ impl MessageSendEvent {
                                let mut msg_nonref = (*msg).clone();
                                nativeMessageSendEvent::SendShutdown {
                                        node_id: node_id_nonref.into_rust(),
-                                       msg: *unsafe { Box::from_raw(msg_nonref.take_ptr()) },
+                                       msg: *unsafe { Box::from_raw(msg_nonref.take_inner()) },
                                }
                        },
                        MessageSendEvent::SendChannelReestablish {ref node_id, ref msg, } => {
@@ -498,27 +513,27 @@ impl MessageSendEvent {
                                let mut msg_nonref = (*msg).clone();
                                nativeMessageSendEvent::SendChannelReestablish {
                                        node_id: node_id_nonref.into_rust(),
-                                       msg: *unsafe { Box::from_raw(msg_nonref.take_ptr()) },
+                                       msg: *unsafe { Box::from_raw(msg_nonref.take_inner()) },
                                }
                        },
                        MessageSendEvent::BroadcastChannelAnnouncement {ref msg, ref update_msg, } => {
                                let mut msg_nonref = (*msg).clone();
                                let mut update_msg_nonref = (*update_msg).clone();
                                nativeMessageSendEvent::BroadcastChannelAnnouncement {
-                                       msg: *unsafe { Box::from_raw(msg_nonref.take_ptr()) },
-                                       update_msg: *unsafe { Box::from_raw(update_msg_nonref.take_ptr()) },
+                                       msg: *unsafe { Box::from_raw(msg_nonref.take_inner()) },
+                                       update_msg: *unsafe { Box::from_raw(update_msg_nonref.take_inner()) },
                                }
                        },
                        MessageSendEvent::BroadcastNodeAnnouncement {ref msg, } => {
                                let mut msg_nonref = (*msg).clone();
                                nativeMessageSendEvent::BroadcastNodeAnnouncement {
-                                       msg: *unsafe { Box::from_raw(msg_nonref.take_ptr()) },
+                                       msg: *unsafe { Box::from_raw(msg_nonref.take_inner()) },
                                }
                        },
                        MessageSendEvent::BroadcastChannelUpdate {ref msg, } => {
                                let mut msg_nonref = (*msg).clone();
                                nativeMessageSendEvent::BroadcastChannelUpdate {
-                                       msg: *unsafe { Box::from_raw(msg_nonref.take_ptr()) },
+                                       msg: *unsafe { Box::from_raw(msg_nonref.take_inner()) },
                                }
                        },
                        MessageSendEvent::HandleError {ref node_id, ref action, } => {
@@ -535,6 +550,22 @@ impl MessageSendEvent {
                                        update: update_nonref.into_native(),
                                }
                        },
+                       MessageSendEvent::SendChannelRangeQuery {ref node_id, ref msg, } => {
+                               let mut node_id_nonref = (*node_id).clone();
+                               let mut msg_nonref = (*msg).clone();
+                               nativeMessageSendEvent::SendChannelRangeQuery {
+                                       node_id: node_id_nonref.into_rust(),
+                                       msg: *unsafe { Box::from_raw(msg_nonref.take_inner()) },
+                               }
+                       },
+                       MessageSendEvent::SendShortIdsQuery {ref node_id, ref msg, } => {
+                               let mut node_id_nonref = (*node_id).clone();
+                               let mut msg_nonref = (*msg).clone();
+                               nativeMessageSendEvent::SendShortIdsQuery {
+                                       node_id: node_id_nonref.into_rust(),
+                                       msg: *unsafe { Box::from_raw(msg_nonref.take_inner()) },
+                               }
+                       },
                }
        }
        #[allow(unused)]
@@ -543,83 +574,83 @@ impl MessageSendEvent {
                        MessageSendEvent::SendAcceptChannel {mut node_id, mut msg, } => {
                                nativeMessageSendEvent::SendAcceptChannel {
                                        node_id: node_id.into_rust(),
-                                       msg: *unsafe { Box::from_raw(msg.take_ptr()) },
+                                       msg: *unsafe { Box::from_raw(msg.take_inner()) },
                                }
                        },
                        MessageSendEvent::SendOpenChannel {mut node_id, mut msg, } => {
                                nativeMessageSendEvent::SendOpenChannel {
                                        node_id: node_id.into_rust(),
-                                       msg: *unsafe { Box::from_raw(msg.take_ptr()) },
+                                       msg: *unsafe { Box::from_raw(msg.take_inner()) },
                                }
                        },
                        MessageSendEvent::SendFundingCreated {mut node_id, mut msg, } => {
                                nativeMessageSendEvent::SendFundingCreated {
                                        node_id: node_id.into_rust(),
-                                       msg: *unsafe { Box::from_raw(msg.take_ptr()) },
+                                       msg: *unsafe { Box::from_raw(msg.take_inner()) },
                                }
                        },
                        MessageSendEvent::SendFundingSigned {mut node_id, mut msg, } => {
                                nativeMessageSendEvent::SendFundingSigned {
                                        node_id: node_id.into_rust(),
-                                       msg: *unsafe { Box::from_raw(msg.take_ptr()) },
+                                       msg: *unsafe { Box::from_raw(msg.take_inner()) },
                                }
                        },
                        MessageSendEvent::SendFundingLocked {mut node_id, mut msg, } => {
                                nativeMessageSendEvent::SendFundingLocked {
                                        node_id: node_id.into_rust(),
-                                       msg: *unsafe { Box::from_raw(msg.take_ptr()) },
+                                       msg: *unsafe { Box::from_raw(msg.take_inner()) },
                                }
                        },
                        MessageSendEvent::SendAnnouncementSignatures {mut node_id, mut msg, } => {
                                nativeMessageSendEvent::SendAnnouncementSignatures {
                                        node_id: node_id.into_rust(),
-                                       msg: *unsafe { Box::from_raw(msg.take_ptr()) },
+                                       msg: *unsafe { Box::from_raw(msg.take_inner()) },
                                }
                        },
                        MessageSendEvent::UpdateHTLCs {mut node_id, mut updates, } => {
                                nativeMessageSendEvent::UpdateHTLCs {
                                        node_id: node_id.into_rust(),
-                                       updates: *unsafe { Box::from_raw(updates.take_ptr()) },
+                                       updates: *unsafe { Box::from_raw(updates.take_inner()) },
                                }
                        },
                        MessageSendEvent::SendRevokeAndACK {mut node_id, mut msg, } => {
                                nativeMessageSendEvent::SendRevokeAndACK {
                                        node_id: node_id.into_rust(),
-                                       msg: *unsafe { Box::from_raw(msg.take_ptr()) },
+                                       msg: *unsafe { Box::from_raw(msg.take_inner()) },
                                }
                        },
                        MessageSendEvent::SendClosingSigned {mut node_id, mut msg, } => {
                                nativeMessageSendEvent::SendClosingSigned {
                                        node_id: node_id.into_rust(),
-                                       msg: *unsafe { Box::from_raw(msg.take_ptr()) },
+                                       msg: *unsafe { Box::from_raw(msg.take_inner()) },
                                }
                        },
                        MessageSendEvent::SendShutdown {mut node_id, mut msg, } => {
                                nativeMessageSendEvent::SendShutdown {
                                        node_id: node_id.into_rust(),
-                                       msg: *unsafe { Box::from_raw(msg.take_ptr()) },
+                                       msg: *unsafe { Box::from_raw(msg.take_inner()) },
                                }
                        },
                        MessageSendEvent::SendChannelReestablish {mut node_id, mut msg, } => {
                                nativeMessageSendEvent::SendChannelReestablish {
                                        node_id: node_id.into_rust(),
-                                       msg: *unsafe { Box::from_raw(msg.take_ptr()) },
+                                       msg: *unsafe { Box::from_raw(msg.take_inner()) },
                                }
                        },
                        MessageSendEvent::BroadcastChannelAnnouncement {mut msg, mut update_msg, } => {
                                nativeMessageSendEvent::BroadcastChannelAnnouncement {
-                                       msg: *unsafe { Box::from_raw(msg.take_ptr()) },
-                                       update_msg: *unsafe { Box::from_raw(update_msg.take_ptr()) },
+                                       msg: *unsafe { Box::from_raw(msg.take_inner()) },
+                                       update_msg: *unsafe { Box::from_raw(update_msg.take_inner()) },
                                }
                        },
                        MessageSendEvent::BroadcastNodeAnnouncement {mut msg, } => {
                                nativeMessageSendEvent::BroadcastNodeAnnouncement {
-                                       msg: *unsafe { Box::from_raw(msg.take_ptr()) },
+                                       msg: *unsafe { Box::from_raw(msg.take_inner()) },
                                }
                        },
                        MessageSendEvent::BroadcastChannelUpdate {mut msg, } => {
                                nativeMessageSendEvent::BroadcastChannelUpdate {
-                                       msg: *unsafe { Box::from_raw(msg.take_ptr()) },
+                                       msg: *unsafe { Box::from_raw(msg.take_inner()) },
                                }
                        },
                        MessageSendEvent::HandleError {mut node_id, mut action, } => {
@@ -633,6 +664,18 @@ impl MessageSendEvent {
                                        update: update.into_native(),
                                }
                        },
+                       MessageSendEvent::SendChannelRangeQuery {mut node_id, mut msg, } => {
+                               nativeMessageSendEvent::SendChannelRangeQuery {
+                                       node_id: node_id.into_rust(),
+                                       msg: *unsafe { Box::from_raw(msg.take_inner()) },
+                               }
+                       },
+                       MessageSendEvent::SendShortIdsQuery {mut node_id, mut msg, } => {
+                               nativeMessageSendEvent::SendShortIdsQuery {
+                                       node_id: node_id.into_rust(),
+                                       msg: *unsafe { Box::from_raw(msg.take_inner()) },
+                               }
+                       },
                }
        }
        #[allow(unused)]
@@ -760,6 +803,22 @@ impl MessageSendEvent {
                                        update: crate::ln::msgs::HTLCFailChannelUpdate::native_into(update_nonref),
                                }
                        },
+                       nativeMessageSendEvent::SendChannelRangeQuery {ref node_id, ref msg, } => {
+                               let mut node_id_nonref = (*node_id).clone();
+                               let mut msg_nonref = (*msg).clone();
+                               MessageSendEvent::SendChannelRangeQuery {
+                                       node_id: crate::c_types::PublicKey::from_rust(&node_id_nonref),
+                                       msg: crate::ln::msgs::QueryChannelRange { inner: Box::into_raw(Box::new(msg_nonref)), is_owned: true },
+                               }
+                       },
+                       nativeMessageSendEvent::SendShortIdsQuery {ref node_id, ref msg, } => {
+                               let mut node_id_nonref = (*node_id).clone();
+                               let mut msg_nonref = (*msg).clone();
+                               MessageSendEvent::SendShortIdsQuery {
+                                       node_id: crate::c_types::PublicKey::from_rust(&node_id_nonref),
+                                       msg: crate::ln::msgs::QueryShortChannelIds { inner: Box::into_raw(Box::new(msg_nonref)), is_owned: true },
+                               }
+                       },
                }
        }
        #[allow(unused)]
@@ -858,6 +917,18 @@ impl MessageSendEvent {
                                        update: crate::ln::msgs::HTLCFailChannelUpdate::native_into(update),
                                }
                        },
+                       nativeMessageSendEvent::SendChannelRangeQuery {mut node_id, mut msg, } => {
+                               MessageSendEvent::SendChannelRangeQuery {
+                                       node_id: crate::c_types::PublicKey::from_rust(&node_id),
+                                       msg: crate::ln::msgs::QueryChannelRange { inner: Box::into_raw(Box::new(msg)), is_owned: true },
+                               }
+                       },
+                       nativeMessageSendEvent::SendShortIdsQuery {mut node_id, mut msg, } => {
+                               MessageSendEvent::SendShortIdsQuery {
+                                       node_id: crate::c_types::PublicKey::from_rust(&node_id),
+                                       msg: crate::ln::msgs::QueryShortChannelIds { inner: Box::into_raw(Box::new(msg)), is_owned: true },
+                               }
+                       },
                }
        }
 }
diff --git a/lightning-c-bindings/src/util/macro_logger.rs b/lightning-c-bindings/src/util/macro_logger.rs
new file mode 100644 (file)
index 0000000..79c1ea1
--- /dev/null
@@ -0,0 +1,6 @@
+/// Logging macro utilities.
+
+use std::ffi::c_void;
+use bitcoin::hashes::Hash;
+use crate::c_types::*;
+
index c35bf641a53dcd32c033d731c38920c07120f64e..8e5bf04b86e4ba7c9de80137394ebc72e87fdfc5 100644 (file)
@@ -7,5 +7,6 @@ use crate::c_types::*;
 pub mod events;
 pub mod errors;
 pub mod ser;
+pub mod macro_logger;
 pub mod logger;
 pub mod config;
index deb9383ae3ee720fea8f0a71de3321b1e96c30b5..db9549c658dd594fd8ed0d529282666632cc6b70 100644 (file)
@@ -5,3 +5,6 @@ use std::ffi::c_void;
 use bitcoin::hashes::Hash;
 use crate::c_types::*;
 
+
+#[no_mangle]
+pub static MAX_BUF_SIZE: usize = lightning::util::ser::MAX_BUF_SIZE;
index 50634bd32df2ce4be3263a232feea74cb7f1b36a..587fe1b12a913798c5cf6e2511a82f1f4f9336ef 100644 (file)
@@ -10,9 +10,9 @@ For Rust-Lightning clients which wish to make direct connections to Lightning P2
 """
 
 [dependencies]
-bitcoin = "0.24"
+bitcoin = "0.26"
 lightning = { version = "0.0.12", path = "../lightning" }
-tokio = { version = ">=0.2.12", features = [ "io-util", "macros", "rt-core", "sync", "tcp", "time" ] }
+tokio = { version = "1.0", features = [ "io-util", "macros", "rt", "sync", "net", "time" ] }
 
 [dev-dependencies]
-tokio = { version = ">=0.2.12", features = [ "io-util", "macros", "rt-core", "rt-threaded", "sync", "tcp", "time" ] }
+tokio = { version = "1.0", features = [ "io-util", "macros", "rt", "rt-multi-thread", "sync", "net", "time" ] }
index 8e5885ca9bf2d7b67b017d8575a4059e9ecc5ce2..8c98333080f941b5102bf415e9cb4e54a17a8a76 100644 (file)
@@ -24,7 +24,7 @@
 //! The call site should, thus, look something like this:
 //! ```
 //! use tokio::sync::mpsc;
-//! use tokio::net::TcpStream;
+//! use std::net::TcpStream;
 //! use bitcoin::secp256k1::key::PublicKey;
 //! use lightning::util::events::EventsProvider;
 //! use std::net::SocketAddr;
 //! type Logger = dyn lightning::util::logger::Logger;
 //! type ChainAccess = dyn lightning::chain::Access;
 //! type ChainFilter = dyn lightning::chain::Filter;
-//! type DataPersister = dyn lightning::chain::channelmonitor::Persist<lightning::chain::keysinterface::InMemoryChannelKeys>;
-//! type ChainMonitor = lightning::chain::chainmonitor::ChainMonitor<lightning::chain::keysinterface::InMemoryChannelKeys, Arc<ChainFilter>, Arc<TxBroadcaster>, Arc<FeeEstimator>, Arc<Logger>, Arc<DataPersister>>;
-//! type ChannelManager = lightning::ln::channelmanager::SimpleArcChannelManager<ChainMonitor, TxBroadcaster, FeeEstimator, Logger>;
-//! type PeerManager = lightning::ln::peer_handler::SimpleArcPeerManager<lightning_net_tokio::SocketDescriptor, ChainMonitor, TxBroadcaster, FeeEstimator, ChainAccess, Logger>;
+//! type DataPersister = dyn lightning::chain::channelmonitor::Persist<lightning::chain::keysinterface::InMemorySigner>;
+//! type ChainMonitor = lightning::chain::chainmonitor::ChainMonitor<lightning::chain::keysinterface::InMemorySigner, Arc<ChainFilter>, Arc<TxBroadcaster>, Arc<FeeEstimator>, Arc<Logger>, Arc<DataPersister>>;
+//! type ChannelManager = Arc<lightning::ln::channelmanager::SimpleArcChannelManager<ChainMonitor, TxBroadcaster, FeeEstimator, Logger>>;
+//! type PeerManager = Arc<lightning::ln::peer_handler::SimpleArcPeerManager<lightning_net_tokio::SocketDescriptor, ChainMonitor, TxBroadcaster, FeeEstimator, ChainAccess, Logger>>;
 //!
 //! // Connect to node with pubkey their_node_id at addr:
 //! async fn connect_to_node(peer_manager: PeerManager, chain_monitor: Arc<ChainMonitor>, channel_manager: ChannelManager, their_node_id: PublicKey, addr: SocketAddr) {
@@ -86,6 +86,7 @@ use lightning::util::logger::Logger;
 
 use std::{task, thread};
 use std::net::SocketAddr;
+use std::net::TcpStream as StdTcpStream;
 use std::sync::{Arc, Mutex, MutexGuard};
 use std::sync::atomic::{AtomicU64, Ordering};
 use std::time::Duration;
@@ -156,7 +157,7 @@ impl Connection {
                        // In this case, we do need to call peer_manager.socket_disconnected() to inform
                        // Rust-Lightning that the socket is gone.
                        PeerDisconnected
-               };
+               }
                let disconnect_type = loop {
                        macro_rules! shutdown_socket {
                                ($err: expr, $need_disconnect: expr) => { {
@@ -218,7 +219,7 @@ impl Connection {
                }
        }
 
-       fn new(event_notify: mpsc::Sender<()>, stream: TcpStream) -> (io::ReadHalf<TcpStream>, mpsc::Receiver<()>, mpsc::Receiver<()>, Arc<Mutex<Self>>) {
+       fn new(event_notify: mpsc::Sender<()>, stream: StdTcpStream) -> (io::ReadHalf<TcpStream>, mpsc::Receiver<()>, mpsc::Receiver<()>, Arc<Mutex<Self>>) {
                // We only ever need a channel of depth 1 here: if we returned a non-full write to the
                // PeerManager, we will eventually get notified that there is room in the socket to write
                // new bytes, which will generate an event. That event will be popped off the queue before
@@ -229,7 +230,8 @@ impl Connection {
                // we shove a value into the channel which comes after we've reset the read_paused bool to
                // false.
                let (read_waker, read_receiver) = mpsc::channel(1);
-               let (reader, writer) = io::split(stream);
+               stream.set_nonblocking(true).unwrap();
+               let (reader, writer) = io::split(TcpStream::from_std(stream).unwrap());
 
                (reader, write_receiver, read_receiver,
                Arc::new(Mutex::new(Self {
@@ -248,7 +250,7 @@ impl Connection {
 /// not need to poll the provided future in order to make progress.
 ///
 /// See the module-level documentation for how to handle the event_notify mpsc::Sender.
-pub fn setup_inbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, stream: TcpStream) -> impl std::future::Future<Output=()> where
+pub fn setup_inbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, stream: StdTcpStream) -> impl std::future::Future<Output=()> where
                CMH: ChannelMessageHandler + 'static,
                RMH: RoutingMessageHandler + 'static,
                L: Logger + 'static + ?Sized {
@@ -290,7 +292,7 @@ pub fn setup_inbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<So
 /// not need to poll the provided future in order to make progress.
 ///
 /// See the module-level documentation for how to handle the event_notify mpsc::Sender.
-pub fn setup_outbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, their_node_id: PublicKey, stream: TcpStream) -> impl std::future::Future<Output=()> where
+pub fn setup_outbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, their_node_id: PublicKey, stream: StdTcpStream) -> impl std::future::Future<Output=()> where
                CMH: ChannelMessageHandler + 'static,
                RMH: RoutingMessageHandler + 'static,
                L: Logger + 'static + ?Sized {
@@ -366,7 +368,7 @@ pub async fn connect_outbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerM
                CMH: ChannelMessageHandler + 'static,
                RMH: RoutingMessageHandler + 'static,
                L: Logger + 'static + ?Sized {
-       if let Ok(Ok(stream)) = time::timeout(Duration::from_secs(10), TcpStream::connect(&addr)).await {
+       if let Ok(Ok(stream)) = time::timeout(Duration::from_secs(10), async { TcpStream::connect(&addr).await.map(|s| s.into_std().unwrap()) }).await {
                Some(setup_outbound(peer_manager, event_notify, their_node_id, stream))
        } else { None }
 }
@@ -388,7 +390,7 @@ fn wake_socket_waker(orig_ptr: *const ()) {
 }
 fn wake_socket_waker_by_ref(orig_ptr: *const ()) {
        let sender_ptr = orig_ptr as *const mpsc::Sender<()>;
-       let mut sender = unsafe { (*sender_ptr).clone() };
+       let sender = unsafe { (*sender_ptr).clone() };
        let _ = sender.try_send(());
 }
 fn drop_socket_waker(orig_ptr: *const ()) {
@@ -512,6 +514,7 @@ mod tests {
        use tokio::sync::mpsc;
 
        use std::mem;
+       use std::sync::atomic::{AtomicBool, Ordering};
        use std::sync::{Arc, Mutex};
        use std::time::Duration;
 
@@ -526,6 +529,7 @@ mod tests {
                expected_pubkey: PublicKey,
                pubkey_connected: mpsc::Sender<()>,
                pubkey_disconnected: mpsc::Sender<()>,
+               disconnected_flag: AtomicBool,
                msg_events: Mutex<Vec<MessageSendEvent>>,
        }
        impl RoutingMessageHandler for MsgHandler {
@@ -547,7 +551,7 @@ mod tests {
                fn handle_funding_created(&self, _their_node_id: &PublicKey, _msg: &FundingCreated) {}
                fn handle_funding_signed(&self, _their_node_id: &PublicKey, _msg: &FundingSigned) {}
                fn handle_funding_locked(&self, _their_node_id: &PublicKey, _msg: &FundingLocked) {}
-               fn handle_shutdown(&self, _their_node_id: &PublicKey, _msg: &Shutdown) {}
+               fn handle_shutdown(&self, _their_node_id: &PublicKey, _their_features: &InitFeatures, _msg: &Shutdown) {}
                fn handle_closing_signed(&self, _their_node_id: &PublicKey, _msg: &ClosingSigned) {}
                fn handle_update_add_htlc(&self, _their_node_id: &PublicKey, _msg: &UpdateAddHTLC) {}
                fn handle_update_fulfill_htlc(&self, _their_node_id: &PublicKey, _msg: &UpdateFulfillHTLC) {}
@@ -559,6 +563,7 @@ mod tests {
                fn handle_announcement_signatures(&self, _their_node_id: &PublicKey, _msg: &AnnouncementSignatures) {}
                fn peer_disconnected(&self, their_node_id: &PublicKey, _no_connection_possible: bool) {
                        if *their_node_id == self.expected_pubkey {
+                               self.disconnected_flag.store(true, Ordering::SeqCst);
                                self.pubkey_disconnected.clone().try_send(()).unwrap();
                        }
                }
@@ -591,6 +596,7 @@ mod tests {
                        expected_pubkey: b_pub,
                        pubkey_connected: a_connected_sender,
                        pubkey_disconnected: a_disconnected_sender,
+                       disconnected_flag: AtomicBool::new(false),
                        msg_events: Mutex::new(Vec::new()),
                });
                let a_manager = Arc::new(PeerManager::new(MessageHandler {
@@ -604,6 +610,7 @@ mod tests {
                        expected_pubkey: a_pub,
                        pubkey_connected: b_connected_sender,
                        pubkey_disconnected: b_disconnected_sender,
+                       disconnected_flag: AtomicBool::new(false),
                        msg_events: Mutex::new(Vec::new()),
                });
                let b_manager = Arc::new(PeerManager::new(MessageHandler {
@@ -624,8 +631,8 @@ mod tests {
                } else { panic!("Failed to bind to v4 localhost on common ports"); };
 
                let (sender, _receiver) = mpsc::channel(2);
-               let fut_a = super::setup_outbound(Arc::clone(&a_manager), sender.clone(), b_pub, tokio::net::TcpStream::from_std(conn_a).unwrap());
-               let fut_b = super::setup_inbound(b_manager, sender, tokio::net::TcpStream::from_std(conn_b).unwrap());
+               let fut_a = super::setup_outbound(Arc::clone(&a_manager), sender.clone(), b_pub, conn_a);
+               let fut_b = super::setup_inbound(b_manager, sender, conn_b);
 
                tokio::time::timeout(Duration::from_secs(10), a_connected.recv()).await.unwrap();
                tokio::time::timeout(Duration::from_secs(1), b_connected.recv()).await.unwrap();
@@ -633,18 +640,20 @@ mod tests {
                a_handler.msg_events.lock().unwrap().push(MessageSendEvent::HandleError {
                        node_id: b_pub, action: ErrorAction::DisconnectPeer { msg: None }
                });
-               assert!(a_disconnected.try_recv().is_err());
-               assert!(b_disconnected.try_recv().is_err());
+               assert!(!a_handler.disconnected_flag.load(Ordering::SeqCst));
+               assert!(!b_handler.disconnected_flag.load(Ordering::SeqCst));
 
                a_manager.process_events();
                tokio::time::timeout(Duration::from_secs(10), a_disconnected.recv()).await.unwrap();
                tokio::time::timeout(Duration::from_secs(1), b_disconnected.recv()).await.unwrap();
+               assert!(a_handler.disconnected_flag.load(Ordering::SeqCst));
+               assert!(b_handler.disconnected_flag.load(Ordering::SeqCst));
 
                fut_a.await;
                fut_b.await;
        }
 
-       #[tokio::test(threaded_scheduler)]
+       #[tokio::test(flavor = "multi_thread")]
        async fn basic_threaded_connection_test() {
                do_basic_connection_test().await;
        }
index 63b69a1e166667118ffd2933797963232554e22b..fa71dc0d4dd9e9e0ac67e0acfd0014abd2aa8215 100644 (file)
@@ -8,12 +8,15 @@ Utilities to manage channel data persistence and retrieval.
 """
 
 [dependencies]
-bitcoin = "0.24"
+bitcoin = "0.26"
 lightning = { version = "0.0.12", path = "../lightning" }
 libc = "0.2"
 
+[target.'cfg(windows)'.dependencies]
+winapi = { version = "0.3", features = ["winbase"] }
+
 [dev-dependencies.bitcoin]
-version = "0.24"
+version = "0.26"
 features = ["bitcoinconsensus"]
 
 [dev-dependencies]
index 48d4d0aa810c3b4b0ca8645acd8485646a9722e7..0151b1e464ea6af8559e147ef19084331485f8f9 100644 (file)
@@ -1,28 +1,34 @@
+mod util;
+
 extern crate lightning;
 extern crate bitcoin;
 extern crate libc;
 
 use bitcoin::hashes::hex::ToHex;
+use crate::util::DiskWriteable;
+use lightning::chain;
+use lightning::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
 use lightning::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr};
 use lightning::chain::channelmonitor;
-use lightning::chain::keysinterface::ChannelKeys;
+use lightning::chain::keysinterface::{Sign, KeysInterface};
 use lightning::chain::transaction::OutPoint;
-use lightning::util::ser::{Writeable, Readable};
+use lightning::ln::channelmanager::ChannelManager;
+use lightning::util::logger::Logger;
+use lightning::util::ser::Writeable;
 use std::fs;
 use std::io::Error;
-use std::path::{Path, PathBuf};
+use std::path::PathBuf;
+use std::sync::Arc;
 
 #[cfg(test)]
 use {
+       lightning::util::ser::ReadableArgs,
        bitcoin::{BlockHash, Txid},
        bitcoin::hashes::hex::FromHex,
        std::collections::HashMap,
        std::io::Cursor
 };
 
-#[cfg(not(target_os = "windows"))]
-use std::os::unix::io::AsRawFd;
-
 /// FilesystemPersister persists channel data on disk, where each channel's
 /// data is stored in a file named after its funding outpoint.
 ///
@@ -39,13 +45,21 @@ pub struct FilesystemPersister {
        path_to_channel_data: String,
 }
 
-trait DiskWriteable {
-       fn write(&self, writer: &mut fs::File) -> Result<(), Error>;
+impl<Signer: Sign> DiskWriteable for ChannelMonitor<Signer> {
+       fn write_to_file(&self, writer: &mut fs::File) -> Result<(), Error> {
+               self.write(writer)
+       }
 }
 
-impl<ChanSigner: ChannelKeys + Writeable> DiskWriteable for ChannelMonitor<ChanSigner> {
-       fn write(&self, writer: &mut fs::File) -> Result<(), Error> {
-               self.serialize_for_disk(writer)
+impl<Signer: Sign, M, T, K, F, L> DiskWriteable for ChannelManager<Signer, Arc<M>, Arc<T>, Arc<K>, Arc<F>, Arc<L>>
+where M: chain::Watch<Signer>,
+      T: BroadcasterInterface,
+      K: KeysInterface<Signer=Signer>,
+      F: FeeEstimator,
+      L: Logger,
+{
+       fn write_to_file(&self, writer: &mut fs::File) -> Result<(), std::io::Error> {
+               self.write(writer)
        }
 }
 
@@ -58,100 +72,82 @@ impl FilesystemPersister {
                }
        }
 
-       fn get_full_filepath(&self, funding_txo: OutPoint) -> String {
-               let mut path = PathBuf::from(&self.path_to_channel_data);
-               path.push(format!("{}_{}", funding_txo.txid.to_hex(), funding_txo.index));
-               path.to_str().unwrap().to_string()
+       pub fn get_data_dir(&self) -> String {
+               self.path_to_channel_data.clone()
        }
 
-       // Utility to write a file to disk.
-       fn write_channel_data(&self, funding_txo: OutPoint, monitor: &dyn DiskWriteable) -> std::io::Result<()> {
-               fs::create_dir_all(&self.path_to_channel_data)?;
-               // Do a crazy dance with lots of fsync()s to be overly cautious here...
-               // We never want to end up in a state where we've lost the old data, or end up using the
-               // old data on power loss after we've returned.
-               // The way to atomically write a file on Unix platforms is:
-               // open(tmpname), write(tmpfile), fsync(tmpfile), close(tmpfile), rename(), fsync(dir)
-               let filename = self.get_full_filepath(funding_txo);
-               let tmp_filename = format!("{}.tmp", filename.clone());
-
-               {
-                       // Note that going by rust-lang/rust@d602a6b, on MacOS it is only safe to use
-                       // rust stdlib 1.36 or higher.
-                       let mut f = fs::File::create(&tmp_filename)?;
-                       monitor.write(&mut f)?;
-                       f.sync_all()?;
-               }
-               fs::rename(&tmp_filename, &filename)?;
-               // Fsync the parent directory on Unix.
-               #[cfg(not(target_os = "windows"))]
-               {
-                       let path = Path::new(&filename).parent().unwrap();
-                       let dir_file = fs::OpenOptions::new().read(true).open(path)?;
-                       unsafe { libc::fsync(dir_file.as_raw_fd()); }
-               }
-               Ok(())
+       pub(crate) fn path_to_monitor_data(&self) -> PathBuf {
+               let mut path = PathBuf::from(self.path_to_channel_data.clone());
+               path.push("monitors");
+               path
+       }
+
+       /// Writes the provided `ChannelManager` to the path provided at `FilesystemPersister`
+       /// initialization, within a file called "manager".
+       pub fn persist_manager<Signer, M, T, K, F, L>(
+               data_dir: String,
+               manager: &ChannelManager<Signer, Arc<M>, Arc<T>, Arc<K>, Arc<F>, Arc<L>>
+       ) -> Result<(), std::io::Error>
+       where Signer: Sign,
+             M: chain::Watch<Signer>,
+             T: BroadcasterInterface,
+             K: KeysInterface<Signer=Signer>,
+             F: FeeEstimator,
+             L: Logger
+       {
+               let path = PathBuf::from(data_dir);
+               util::write_to_file(path, "manager".to_string(), manager)
        }
 
        #[cfg(test)]
-       fn load_channel_data<ChanSigner: ChannelKeys + Readable + Writeable>(&self) ->
-               Result<HashMap<OutPoint, ChannelMonitor<ChanSigner>>, ChannelMonitorUpdateErr> {
-               if let Err(_) = fs::create_dir_all(&self.path_to_channel_data) {
-                       return Err(ChannelMonitorUpdateErr::PermanentFailure);
-               }
-               let mut res = HashMap::new();
-               for file_option in fs::read_dir(&self.path_to_channel_data).unwrap() {
-                       let file = file_option.unwrap();
-                       let owned_file_name = file.file_name();
-                       let filename = owned_file_name.to_str();
-                       if !filename.is_some() || !filename.unwrap().is_ascii() || filename.unwrap().len() < 65 {
+       fn load_channel_data<Keys: KeysInterface>(&self, keys: &Keys) ->
+               Result<HashMap<OutPoint, ChannelMonitor<Keys::Signer>>, ChannelMonitorUpdateErr> {
+                       if let Err(_) = fs::create_dir_all(self.path_to_monitor_data()) {
                                return Err(ChannelMonitorUpdateErr::PermanentFailure);
                        }
+                       let mut res = HashMap::new();
+                       for file_option in fs::read_dir(self.path_to_monitor_data()).unwrap() {
+                               let file = file_option.unwrap();
+                               let owned_file_name = file.file_name();
+                               let filename = owned_file_name.to_str();
+                               if !filename.is_some() || !filename.unwrap().is_ascii() || filename.unwrap().len() < 65 {
+                                       return Err(ChannelMonitorUpdateErr::PermanentFailure);
+                               }
 
-                       let txid = Txid::from_hex(filename.unwrap().split_at(64).0);
-                       if txid.is_err() { return Err(ChannelMonitorUpdateErr::PermanentFailure); }
+                               let txid = Txid::from_hex(filename.unwrap().split_at(64).0);
+                               if txid.is_err() { return Err(ChannelMonitorUpdateErr::PermanentFailure); }
 
-                       let index = filename.unwrap().split_at(65).1.split('.').next().unwrap().parse();
-                       if index.is_err() { return Err(ChannelMonitorUpdateErr::PermanentFailure); }
+                               let index = filename.unwrap().split_at(65).1.split('.').next().unwrap().parse();
+                               if index.is_err() { return Err(ChannelMonitorUpdateErr::PermanentFailure); }
 
-                       let contents = fs::read(&file.path());
-                       if contents.is_err() { return Err(ChannelMonitorUpdateErr::PermanentFailure); }
+                               let contents = fs::read(&file.path());
+                               if contents.is_err() { return Err(ChannelMonitorUpdateErr::PermanentFailure); }
 
-                       if let Ok((_, loaded_monitor)) =
-                               <(BlockHash, ChannelMonitor<ChanSigner>)>::read(&mut Cursor::new(&contents.unwrap())) {
-                               res.insert(OutPoint { txid: txid.unwrap(), index: index.unwrap() }, loaded_monitor);
-                       } else {
-                               return Err(ChannelMonitorUpdateErr::PermanentFailure);
+                               if let Ok((_, loaded_monitor)) =
+                                       <(Option<BlockHash>, ChannelMonitor<Keys::Signer>)>::read(&mut Cursor::new(&contents.unwrap()), keys) {
+                                               res.insert(OutPoint { txid: txid.unwrap(), index: index.unwrap() }, loaded_monitor);
+                                       } else {
+                                               return Err(ChannelMonitorUpdateErr::PermanentFailure);
+                                       }
                        }
+                       Ok(res)
                }
-               Ok(res)
-       }
 }
 
-impl<ChanSigner: ChannelKeys + Readable + Writeable + Send + Sync> channelmonitor::Persist<ChanSigner> for FilesystemPersister {
-       fn persist_new_channel(&self, funding_txo: OutPoint, monitor: &ChannelMonitor<ChanSigner>) -> Result<(), ChannelMonitorUpdateErr> {
-               self.write_channel_data(funding_txo, monitor)
+impl<ChannelSigner: Sign + Send + Sync> channelmonitor::Persist<ChannelSigner> for FilesystemPersister {
+       fn persist_new_channel(&self, funding_txo: OutPoint, monitor: &ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr> {
+               let filename = format!("{}_{}", funding_txo.txid.to_hex(), funding_txo.index);
+               util::write_to_file(self.path_to_monitor_data(), filename, monitor)
                  .map_err(|_| ChannelMonitorUpdateErr::PermanentFailure)
        }
 
-       fn update_persisted_channel(&self, funding_txo: OutPoint, _update: &ChannelMonitorUpdate, monitor: &ChannelMonitor<ChanSigner>) -> Result<(), ChannelMonitorUpdateErr> {
-               self.write_channel_data(funding_txo, monitor)
+       fn update_persisted_channel(&self, funding_txo: OutPoint, _update: &ChannelMonitorUpdate, monitor: &ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr> {
+               let filename = format!("{}_{}", funding_txo.txid.to_hex(), funding_txo.index);
+               util::write_to_file(self.path_to_monitor_data(), filename, monitor)
                  .map_err(|_| ChannelMonitorUpdateErr::PermanentFailure)
        }
 }
 
-#[cfg(test)]
-impl Drop for FilesystemPersister {
-       fn drop(&mut self) {
-               // We test for invalid directory names, so it's OK if directory removal
-               // fails.
-               match fs::remove_dir_all(&self.path_to_channel_data) {
-                       Err(e) => println!("Failed to remove test persister directory: {}", e),
-                       _ => {}
-               }
-       }
-}
-
 #[cfg(test)]
 mod tests {
        extern crate lightning;
@@ -160,30 +156,29 @@ mod tests {
        use bitcoin::blockdata::block::{Block, BlockHeader};
        use bitcoin::hashes::hex::FromHex;
        use bitcoin::Txid;
-       use DiskWriteable;
-       use Error;
        use lightning::chain::channelmonitor::{Persist, ChannelMonitorUpdateErr};
        use lightning::chain::transaction::OutPoint;
        use lightning::{check_closed_broadcast, check_added_monitors};
        use lightning::ln::features::InitFeatures;
        use lightning::ln::functional_test_utils::*;
        use lightning::ln::msgs::ErrorAction;
-       use lightning::util::enforcing_trait_impls::EnforcingChannelKeys;
        use lightning::util::events::{MessageSendEventsProvider, MessageSendEvent};
-       use lightning::util::ser::Writer;
        use lightning::util::test_utils;
        use std::fs;
-       use std::io;
        #[cfg(target_os = "windows")]
        use {
                lightning::get_event_msg,
                lightning::ln::msgs::ChannelMessageHandler,
        };
 
-       struct TestWriteable{}
-       impl DiskWriteable for TestWriteable {
-               fn write(&self, writer: &mut fs::File) -> Result<(), Error> {
-                       writer.write_all(&[42; 1])
+       impl Drop for FilesystemPersister {
+               fn drop(&mut self) {
+                       // We test for invalid directory names, so it's OK if directory removal
+                       // fails.
+                       match fs::remove_dir_all(&self.path_to_channel_data) {
+                               Err(e) => println!("Failed to remove test persister directory: {}", e),
+                               _ => {}
+                       }
                }
        }
 
@@ -197,8 +192,8 @@ mod tests {
                let persister_1 = FilesystemPersister::new("test_filesystem_persister_1".to_string());
                let chanmon_cfgs = create_chanmon_cfgs(2);
                let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
-               let chain_mon_0 = test_utils::TestChainMonitor::new(Some(&chanmon_cfgs[0].chain_source), &chanmon_cfgs[0].tx_broadcaster, &chanmon_cfgs[0].logger, &chanmon_cfgs[0].fee_estimator, &persister_0);
-               let chain_mon_1 = test_utils::TestChainMonitor::new(Some(&chanmon_cfgs[1].chain_source), &chanmon_cfgs[1].tx_broadcaster, &chanmon_cfgs[1].logger, &chanmon_cfgs[1].fee_estimator, &persister_1);
+               let chain_mon_0 = test_utils::TestChainMonitor::new(Some(&chanmon_cfgs[0].chain_source), &chanmon_cfgs[0].tx_broadcaster, &chanmon_cfgs[0].logger, &chanmon_cfgs[0].fee_estimator, &persister_0, &node_cfgs[0].keys_manager);
+               let chain_mon_1 = test_utils::TestChainMonitor::new(Some(&chanmon_cfgs[1].chain_source), &chanmon_cfgs[1].tx_broadcaster, &chanmon_cfgs[1].logger, &chanmon_cfgs[1].fee_estimator, &persister_1, &node_cfgs[1].keys_manager);
                node_cfgs[0].chain_monitor = chain_mon_0;
                node_cfgs[1].chain_monitor = chain_mon_1;
                let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
@@ -206,20 +201,20 @@ mod tests {
 
                // Check that the persisted channel data is empty before any channels are
                // open.
-               let mut persisted_chan_data_0 = persister_0.load_channel_data::<EnforcingChannelKeys>().unwrap();
+               let mut persisted_chan_data_0 = persister_0.load_channel_data(nodes[0].keys_manager).unwrap();
                assert_eq!(persisted_chan_data_0.keys().len(), 0);
-               let mut persisted_chan_data_1 = persister_1.load_channel_data::<EnforcingChannelKeys>().unwrap();
+               let mut persisted_chan_data_1 = persister_1.load_channel_data(nodes[1].keys_manager).unwrap();
                assert_eq!(persisted_chan_data_1.keys().len(), 0);
 
                // Helper to make sure the channel is on the expected update ID.
                macro_rules! check_persisted_data {
                        ($expected_update_id: expr) => {
-                               persisted_chan_data_0 = persister_0.load_channel_data::<EnforcingChannelKeys>().unwrap();
+                               persisted_chan_data_0 = persister_0.load_channel_data(nodes[0].keys_manager).unwrap();
                                assert_eq!(persisted_chan_data_0.keys().len(), 1);
                                for mon in persisted_chan_data_0.values() {
                                        assert_eq!(mon.get_latest_update_id(), $expected_update_id);
                                }
-                               persisted_chan_data_1 = persister_1.load_channel_data::<EnforcingChannelKeys>().unwrap();
+                               persisted_chan_data_1 = persister_1.load_channel_data(nodes[1].keys_manager).unwrap();
                                assert_eq!(persisted_chan_data_1.keys().len(), 1);
                                for mon in persisted_chan_data_1.values() {
                                        assert_eq!(mon.get_latest_update_id(), $expected_update_id);
@@ -239,7 +234,7 @@ mod tests {
 
                // Force close because cooperative close doesn't result in any persisted
                // updates.
-               nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
+               nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
                check_closed_broadcast!(nodes[0], false);
                check_added_monitors!(nodes[0], 1);
 
@@ -255,88 +250,6 @@ mod tests {
                check_persisted_data!(11);
        }
 
-       // Test that if the persister's path to channel data is read-only, writing
-       // data to it fails. Windows ignores the read-only flag for folders, so this
-       // test is Unix-only.
-       #[cfg(not(target_os = "windows"))]
-       #[test]
-       fn test_readonly_dir() {
-               let persister = FilesystemPersister::new("test_readonly_dir_persister".to_string());
-               let test_writeable = TestWriteable{};
-               let test_txo = OutPoint {
-                       txid: Txid::from_hex("8984484a580b825b9972d7adb15050b3ab624ccd731946b3eeddb92f4e7ef6be").unwrap(),
-                       index: 0
-               };
-               // Create the persister's directory and set it to read-only.
-               let path = &persister.path_to_channel_data;
-               fs::create_dir_all(path).unwrap();
-               let mut perms = fs::metadata(path).unwrap().permissions();
-               perms.set_readonly(true);
-               fs::set_permissions(path, perms).unwrap();
-               match persister.write_channel_data(test_txo, &test_writeable) {
-                       Err(e) => assert_eq!(e.kind(), io::ErrorKind::PermissionDenied),
-                       _ => panic!("Unexpected error message")
-               }
-       }
-
-       // Test failure to rename in the process of atomically creating a channel
-       // monitor's file. We induce this failure by making the `tmp` file a
-       // directory.
-       // Explanation: given "from" = the file being renamed, "to" = the
-       // renamee that already exists: Windows should fail because it'll fail
-       // whenever "to" is a directory, and Unix should fail because if "from" is a
-       // file, then "to" is also required to be a file.
-       #[test]
-       fn test_rename_failure() {
-               let persister = FilesystemPersister::new("test_rename_failure".to_string());
-               let test_writeable = TestWriteable{};
-               let txid_hex = "8984484a580b825b9972d7adb15050b3ab624ccd731946b3eeddb92f4e7ef6be";
-               let outp_idx = 0;
-               let test_txo = OutPoint {
-                       txid: Txid::from_hex(txid_hex).unwrap(),
-                       index: outp_idx,
-               };
-               // Create the channel data file and make it a directory.
-               let path = &persister.path_to_channel_data;
-               fs::create_dir_all(format!("{}/{}_{}", path, txid_hex, outp_idx)).unwrap();
-               match persister.write_channel_data(test_txo, &test_writeable) {
-                       Err(e) => {
-                               #[cfg(not(target_os = "windows"))]
-                               assert_eq!(e.kind(), io::ErrorKind::Other);
-                               #[cfg(target_os = "windows")]
-                               assert_eq!(e.kind(), io::ErrorKind::PermissionDenied);
-                       }
-                       _ => panic!("Unexpected error message")
-               }
-       }
-
-       // Test failure to create the temporary file in the persistence process.
-       // We induce this failure by having the temp file already exist and be a
-       // directory.
-       #[test]
-       fn test_tmp_file_creation_failure() {
-               let persister = FilesystemPersister::new("test_tmp_file_creation_failure".to_string());
-               let test_writeable = TestWriteable{};
-               let txid_hex = "8984484a580b825b9972d7adb15050b3ab624ccd731946b3eeddb92f4e7ef6be";
-               let outp_idx = 0;
-               let test_txo = OutPoint {
-                       txid: Txid::from_hex(txid_hex).unwrap(),
-                       index: outp_idx,
-               };
-               // Create the tmp file and make it a directory.
-               let path = &persister.path_to_channel_data;
-               fs::create_dir_all(format!("{}/{}_{}.tmp", path, txid_hex, outp_idx)).unwrap();
-               match persister.write_channel_data(test_txo, &test_writeable) {
-                       Err(e) => {
-                               #[cfg(not(target_os = "windows"))]
-                               assert_eq!(e.kind(), io::ErrorKind::Other);
-                               #[cfg(target_os = "windows")]
-                               assert_eq!(e.kind(), io::ErrorKind::PermissionDenied);
-                       }
-                       _ => panic!("Unexpected error message")
-               }
-       }
-
        // Test that if the persister's path to channel data is read-only, writing a
        // monitor to it results in the persister returning a PermanentFailure.
        // Windows ignores the read-only flag for folders, so this test is Unix-only.
@@ -353,7 +266,7 @@ mod tests {
                let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
                let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
                let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
-               nodes[1].node.force_close_channel(&chan.2);
+               nodes[1].node.force_close_channel(&chan.2).unwrap();
                let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
 
                // Set the persister's directory to read-only, which should result in
@@ -389,7 +302,7 @@ mod tests {
                let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
                let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
                let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
-               nodes[1].node.force_close_channel(&chan.2);
+               nodes[1].node.force_close_channel(&chan.2).unwrap();
                let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
 
                // Create the persister with an invalid directory name and test that the
diff --git a/lightning-persister/src/util.rs b/lightning-persister/src/util.rs
new file mode 100644 (file)
index 0000000..1825980
--- /dev/null
@@ -0,0 +1,188 @@
+#[cfg(target_os = "windows")]
+extern crate winapi;
+
+use std::fs;
+use std::path::{Path, PathBuf};
+
+#[cfg(not(target_os = "windows"))]
+use std::os::unix::io::AsRawFd;
+
+#[cfg(target_os = "windows")]
+use {
+       std::ffi::OsStr,
+       std::os::windows::ffi::OsStrExt
+};
+
+pub(crate) trait DiskWriteable {
+       fn write_to_file(&self, writer: &mut fs::File) -> Result<(), std::io::Error>;
+}
+
+pub(crate) fn get_full_filepath(mut filepath: PathBuf, filename: String) -> String {
+       filepath.push(filename);
+       filepath.to_str().unwrap().to_string()
+}
+
+#[cfg(target_os = "windows")]
+macro_rules! call {
+       ($e: expr) => (
+               if $e != 0 {
+                       return Ok(())
+               } else {
+                       return Err(std::io::Error::last_os_error())
+               }
+       )
+}
+
+#[cfg(target_os = "windows")]
+fn path_to_windows_str<T: AsRef<OsStr>>(path: T) -> Vec<winapi::shared::ntdef::WCHAR> {
+       path.as_ref().encode_wide().chain(Some(0)).collect()
+}
+
+#[allow(bare_trait_objects)]
+pub(crate) fn write_to_file<D: DiskWriteable>(path: PathBuf, filename: String, data: &D) -> std::io::Result<()> {
+       fs::create_dir_all(path.clone())?;
+       // Do a crazy dance with lots of fsync()s to be overly cautious here...
+       // We never want to end up in a state where we've lost the old data, or end up using the
+       // old data on power loss after we've returned.
+       // The way to atomically write a file on Unix platforms is:
+       // open(tmpname), write(tmpfile), fsync(tmpfile), close(tmpfile), rename(), fsync(dir)
+       let filename_with_path = get_full_filepath(path, filename);
+       let tmp_filename = format!("{}.tmp", filename_with_path.clone());
+
+       {
+               // Note that going by rust-lang/rust@d602a6b, on MacOS it is only safe to use
+               // rust stdlib 1.36 or higher.
+               let mut f = fs::File::create(&tmp_filename)?;
+               data.write_to_file(&mut f)?;
+               f.sync_all()?;
+       }
+       // Fsync the parent directory on Unix.
+       #[cfg(not(target_os = "windows"))]
+       {
+               fs::rename(&tmp_filename, &filename_with_path)?;
+               let path = Path::new(&filename_with_path).parent().unwrap();
+               let dir_file = fs::OpenOptions::new().read(true).open(path)?;
+               unsafe { libc::fsync(dir_file.as_raw_fd()); }
+       }
+       #[cfg(target_os = "windows")]
+       {
+               let src = PathBuf::from(tmp_filename.clone());
+               let dst = PathBuf::from(filename_with_path.clone());
+               if Path::new(&filename_with_path.clone()).exists() {
+                       unsafe {winapi::um::winbase::ReplaceFileW(
+                               path_to_windows_str(dst).as_ptr(), path_to_windows_str(src).as_ptr(), std::ptr::null(),
+                               winapi::um::winbase::REPLACEFILE_IGNORE_MERGE_ERRORS,
+                               std::ptr::null_mut() as *mut winapi::ctypes::c_void,
+                               std::ptr::null_mut() as *mut winapi::ctypes::c_void
+                       )};
+               } else {
+                       call!(unsafe {winapi::um::winbase::MoveFileExW(
+                               path_to_windows_str(src).as_ptr(), path_to_windows_str(dst).as_ptr(),
+                               winapi::um::winbase::MOVEFILE_WRITE_THROUGH | winapi::um::winbase::MOVEFILE_REPLACE_EXISTING
+                       )});
+               }
+       }
+       Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+       use super::{DiskWriteable, get_full_filepath, write_to_file};
+       use std::fs;
+       use std::io;
+       use std::io::Write;
+       use std::path::PathBuf;
+
+       struct TestWriteable{}
+       impl DiskWriteable for TestWriteable {
+               fn write_to_file(&self, writer: &mut fs::File) -> Result<(), io::Error> {
+                       writer.write_all(&[42; 1])
+               }
+       }
+
+       // Test that if the persister's path to channel data is read-only, writing
+       // data to it fails. Windows ignores the read-only flag for folders, so this
+       // test is Unix-only.
+       #[cfg(not(target_os = "windows"))]
+       #[test]
+       fn test_readonly_dir() {
+               let test_writeable = TestWriteable{};
+               let filename = "test_readonly_dir_persister_filename".to_string();
+               let path = "test_readonly_dir_persister_dir";
+               fs::create_dir_all(path.to_string()).unwrap();
+               let mut perms = fs::metadata(path.to_string()).unwrap().permissions();
+               perms.set_readonly(true);
+               fs::set_permissions(path.to_string(), perms).unwrap();
+               match write_to_file(PathBuf::from(path.to_string()), filename, &test_writeable) {
+                       Err(e) => assert_eq!(e.kind(), io::ErrorKind::PermissionDenied),
+                       _ => panic!("Unexpected error message")
+               }
+       }
+
+       // Test failure to rename in the process of atomically creating a channel
+       // monitor's file. We induce this failure by making the `tmp` file a
+       // directory.
+       // Explanation: given "from" = the file being renamed, "to" = the destination
+       // file that already exists: Unix should fail because if "from" is a file,
+       // then "to" is also required to be a file.
+       // TODO: ideally try to make this work on Windows again
+       #[cfg(not(target_os = "windows"))]
+       #[test]
+       fn test_rename_failure() {
+               let test_writeable = TestWriteable{};
+               let filename = "test_rename_failure_filename";
+               let path = PathBuf::from("test_rename_failure_dir");
+               // Create the channel data file and make it a directory.
+               fs::create_dir_all(get_full_filepath(path.clone(), filename.to_string())).unwrap();
+               match write_to_file(path.clone(), filename.to_string(), &test_writeable) {
+                       Err(e) => assert_eq!(e.kind(), io::ErrorKind::Other),
+                       _ => panic!("Unexpected Ok(())")
+               }
+               fs::remove_dir_all(path).unwrap();
+       }
+
+       #[test]
+       fn test_diskwriteable_failure() {
+               struct FailingWriteable {}
+               impl DiskWriteable for FailingWriteable {
+                       fn write_to_file(&self, _writer: &mut fs::File) -> Result<(), std::io::Error> {
+                               Err(std::io::Error::new(std::io::ErrorKind::Other, "expected failure"))
+                       }
+               }
+
+               let filename = "test_diskwriteable_failure";
+               let path = PathBuf::from("test_diskwriteable_failure_dir");
+               let test_writeable = FailingWriteable{};
+               match write_to_file(path.clone(), filename.to_string(), &test_writeable) {
+                       Err(e) => {
+                               assert_eq!(e.kind(), std::io::ErrorKind::Other);
+                               assert_eq!(e.get_ref().unwrap().to_string(), "expected failure");
+                       },
+                       _ => panic!("unexpected result")
+               }
+               fs::remove_dir_all(path).unwrap();
+       }
+
+       // Test failure to create the temporary file in the persistence process.
+       // We induce this failure by having the temp file already exist and be a
+       // directory.
+       #[test]
+       fn test_tmp_file_creation_failure() {
+               let test_writeable = TestWriteable{};
+               let filename = "test_tmp_file_creation_failure_filename".to_string();
+               let path = PathBuf::from("test_tmp_file_creation_failure_dir");
+
+               // Create the tmp file and make it a directory.
+               let tmp_path = get_full_filepath(path.clone(), format!("{}.tmp", filename.clone()));
+               fs::create_dir_all(tmp_path).unwrap();
+               match write_to_file(path, filename, &test_writeable) {
+                       Err(e) => {
+                               #[cfg(not(target_os = "windows"))]
+                               assert_eq!(e.kind(), io::ErrorKind::Other);
+                               #[cfg(target_os = "windows")]
+                               assert_eq!(e.kind(), io::ErrorKind::PermissionDenied);
+                       }
+                       _ => panic!("Unexpected error message")
+               }
+       }
+}
index c1f364394dd98a3bf194fec80fc29773e62d0ad1..f02813bfd3c2bbfa64365aef65f128cf77ec130c 100644 (file)
@@ -11,7 +11,9 @@ Still missing tons of error-handling. See GitHub issues for suggested projects i
 """
 
 [features]
-fuzztarget = ["bitcoin/fuzztarget"]
+allow_wallclock_use = []
+fuzztarget = ["bitcoin/fuzztarget", "regex"]
+# Internal test utilities exposed to other repo crates
 _test_utils = ["hex", "regex"]
 # Unlog messages superior at targeted level.
 max_level_off = []
@@ -22,17 +24,21 @@ max_level_debug = []
 # Allow signing of local transactions that may have been revoked or will be revoked, for functional testing (e.g. justice tx handling).
 # This is unsafe to use in production because it may result in the counterparty publishing taking our funds.
 unsafe_revoked_tx_signing = []
+unstable = []
 
 [dependencies]
-bitcoin = "0.24"
+bitcoin = "0.26"
 
 hex = { version = "0.3", optional = true }
 regex = { version = "0.1.80", optional = true }
 
 [dev-dependencies.bitcoin]
-version = "0.24"
+version = "0.26"
 features = ["bitcoinconsensus"]
 
 [dev-dependencies]
 hex = "0.3"
 regex = "0.1.80"
+
+[package.metadata.docs.rs]
+features = ["allow_wallclock_use"] # When https://github.com/rust-lang/rust/issues/43781 complies with our MSVR, we can add nice banners in the docs for the methods behind this feature-gate.
index 13a0a883140994de21444992134492acedf0377f..de826d054d3716bd41df35e03706ac3e900c1322 100644 (file)
@@ -29,7 +29,7 @@
 //! [`ChannelMonitor`]: ../channelmonitor/struct.ChannelMonitor.html
 //! [`MonitorEvent`]: ../channelmonitor/enum.MonitorEvent.html
 
-use bitcoin::blockdata::block::BlockHeader;
+use bitcoin::blockdata::block::{Block, BlockHeader};
 
 use chain;
 use chain::Filter;
@@ -37,13 +37,13 @@ use chain::chaininterface::{BroadcasterInterface, FeeEstimator};
 use chain::channelmonitor;
 use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr, MonitorEvent, Persist};
 use chain::transaction::{OutPoint, TransactionData};
-use chain::keysinterface::ChannelKeys;
+use chain::keysinterface::Sign;
 use util::logger::Logger;
 use util::events;
 use util::events::Event;
 
 use std::collections::{HashMap, hash_map};
-use std::sync::Mutex;
+use std::sync::RwLock;
 use std::ops::Deref;
 
 /// An implementation of [`chain::Watch`] for monitoring channels.
@@ -56,15 +56,15 @@ use std::ops::Deref;
 /// [`chain::Watch`]: ../trait.Watch.html
 /// [`ChannelManager`]: ../../ln/channelmanager/struct.ChannelManager.html
 /// [module-level documentation]: index.html
-pub struct ChainMonitor<ChanSigner: ChannelKeys, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref>
+pub struct ChainMonitor<ChannelSigner: Sign, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref>
        where C::Target: chain::Filter,
         T::Target: BroadcasterInterface,
         F::Target: FeeEstimator,
         L::Target: Logger,
-        P::Target: channelmonitor::Persist<ChanSigner>,
+        P::Target: channelmonitor::Persist<ChannelSigner>,
 {
        /// The monitors
-       pub monitors: Mutex<HashMap<OutPoint, ChannelMonitor<ChanSigner>>>,
+       pub monitors: RwLock<HashMap<OutPoint, ChannelMonitor<ChannelSigner>>>,
        chain_source: Option<C>,
        broadcaster: T,
        logger: L,
@@ -72,12 +72,12 @@ pub struct ChainMonitor<ChanSigner: ChannelKeys, C: Deref, T: Deref, F: Deref, L
        persister: P,
 }
 
-impl<ChanSigner: ChannelKeys, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref> ChainMonitor<ChanSigner, C, T, F, L, P>
+impl<ChannelSigner: Sign, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref> ChainMonitor<ChannelSigner, C, T, F, L, P>
 where C::Target: chain::Filter,
            T::Target: BroadcasterInterface,
            F::Target: FeeEstimator,
            L::Target: Logger,
-           P::Target: channelmonitor::Persist<ChanSigner>,
+           P::Target: channelmonitor::Persist<ChannelSigner>,
 {
        /// Dispatches to per-channel monitors, which are responsible for updating their on-chain view
        /// of a channel and reacting accordingly based on transactions in the connected block. See
@@ -93,8 +93,8 @@ where C::Target: chain::Filter,
        /// [`chain::Watch::release_pending_monitor_events`]: ../trait.Watch.html#tymethod.release_pending_monitor_events
        /// [`chain::Filter`]: ../trait.Filter.html
        pub fn block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
-               let mut monitors = self.monitors.lock().unwrap();
-               for monitor in monitors.values_mut() {
+               let monitors = self.monitors.read().unwrap();
+               for monitor in monitors.values() {
                        let mut txn_outputs = monitor.block_connected(header, txdata, height, &*self.broadcaster, &*self.fee_estimator, &*self.logger);
 
                        if let Some(ref chain_source) = self.chain_source {
@@ -113,8 +113,8 @@ where C::Target: chain::Filter,
        ///
        /// [`ChannelMonitor::block_disconnected`]: ../channelmonitor/struct.ChannelMonitor.html#method.block_disconnected
        pub fn block_disconnected(&self, header: &BlockHeader, disconnected_height: u32) {
-               let mut monitors = self.monitors.lock().unwrap();
-               for monitor in monitors.values_mut() {
+               let monitors = self.monitors.read().unwrap();
+               for monitor in monitors.values() {
                        monitor.block_disconnected(header, disconnected_height, &*self.broadcaster, &*self.fee_estimator, &*self.logger);
                }
        }
@@ -130,7 +130,7 @@ where C::Target: chain::Filter,
        /// [`chain::Filter`]: ../trait.Filter.html
        pub fn new(chain_source: Option<C>, broadcaster: T, logger: L, feeest: F, persister: P) -> Self {
                Self {
-                       monitors: Mutex::new(HashMap::new()),
+                       monitors: RwLock::new(HashMap::new()),
                        chain_source,
                        broadcaster,
                        logger,
@@ -140,15 +140,34 @@ where C::Target: chain::Filter,
        }
 }
 
-impl<ChanSigner: ChannelKeys, C: Deref + Sync + Send, T: Deref + Sync + Send, F: Deref + Sync + Send, L: Deref + Sync + Send, P: Deref + Sync + Send> chain::Watch for ChainMonitor<ChanSigner, C, T, F, L, P>
+impl<ChannelSigner: Sign, C: Deref + Send + Sync, T: Deref + Send + Sync, F: Deref + Send + Sync, L: Deref + Send + Sync, P: Deref + Send + Sync>
+chain::Listen for ChainMonitor<ChannelSigner, C, T, F, L, P>
+where
+       ChannelSigner: Sign,
+       C::Target: chain::Filter,
+       T::Target: BroadcasterInterface,
+       F::Target: FeeEstimator,
+       L::Target: Logger,
+       P::Target: channelmonitor::Persist<ChannelSigner>,
+{
+       fn block_connected(&self, block: &Block, height: u32) {
+               let txdata: Vec<_> = block.txdata.iter().enumerate().collect();
+               ChainMonitor::block_connected(self, &block.header, &txdata, height);
+       }
+
+       fn block_disconnected(&self, header: &BlockHeader, height: u32) {
+               ChainMonitor::block_disconnected(self, header, height);
+       }
+}
+
+impl<ChannelSigner: Sign, C: Deref + Sync + Send, T: Deref + Sync + Send, F: Deref + Sync + Send, L: Deref + Sync + Send, P: Deref + Sync + Send>
+chain::Watch<ChannelSigner> for ChainMonitor<ChannelSigner, C, T, F, L, P>
 where C::Target: chain::Filter,
            T::Target: BroadcasterInterface,
            F::Target: FeeEstimator,
            L::Target: Logger,
-           P::Target: channelmonitor::Persist<ChanSigner>,
+           P::Target: channelmonitor::Persist<ChannelSigner>,
 {
-       type Keys = ChanSigner;
-
        /// Adds the monitor that watches the channel referred to by the given outpoint.
        ///
        /// Calls back to [`chain::Filter`] with the funding transaction and outputs to watch.
@@ -157,8 +176,8 @@ where C::Target: chain::Filter,
        /// monitors lock.
        ///
        /// [`chain::Filter`]: ../trait.Filter.html
-       fn watch_channel(&self, funding_outpoint: OutPoint, monitor: ChannelMonitor<ChanSigner>) -> Result<(), ChannelMonitorUpdateErr> {
-               let mut monitors = self.monitors.lock().unwrap();
+       fn watch_channel(&self, funding_outpoint: OutPoint, monitor: ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr> {
+               let mut monitors = self.monitors.write().unwrap();
                let entry = match monitors.entry(funding_outpoint) {
                        hash_map::Entry::Occupied(_) => {
                                log_error!(self.logger, "Failed to add new channel data: channel monitor for given outpoint is already present");
@@ -190,8 +209,8 @@ where C::Target: chain::Filter,
        /// `ChainMonitor` monitors lock.
        fn update_channel(&self, funding_txo: OutPoint, update: ChannelMonitorUpdate) -> Result<(), ChannelMonitorUpdateErr> {
                // Update the monitor that watches the channel referred to by the given outpoint.
-               let mut monitors = self.monitors.lock().unwrap();
-               match monitors.get_mut(&funding_txo) {
+               let monitors = self.monitors.read().unwrap();
+               match monitors.get(&funding_txo) {
                        None => {
                                log_error!(self.logger, "Failed to update channel monitor: no such monitor registered");
 
@@ -203,15 +222,15 @@ where C::Target: chain::Filter,
                                #[cfg(not(any(test, feature = "fuzztarget")))]
                                Err(ChannelMonitorUpdateErr::PermanentFailure)
                        },
-                       Some(orig_monitor) => {
-                               log_trace!(self.logger, "Updating Channel Monitor for channel {}", log_funding_info!(orig_monitor));
-                               let update_res = orig_monitor.update_monitor(&update, &self.broadcaster, &self.fee_estimator, &self.logger);
+                       Some(monitor) => {
+                               log_trace!(self.logger, "Updating Channel Monitor for channel {}", log_funding_info!(monitor));
+                               let update_res = monitor.update_monitor(&update, &self.broadcaster, &self.fee_estimator, &self.logger);
                                if let Err(e) = &update_res {
                                        log_error!(self.logger, "Failed to update channel monitor: {:?}", e);
                                }
                                // Even if updating the monitor returns an error, the monitor's state will
                                // still be changed. So, persist the updated monitor despite the error.
-                               let persist_res = self.persister.update_persisted_channel(funding_txo, &update, orig_monitor);
+                               let persist_res = self.persister.update_persisted_channel(funding_txo, &update, monitor);
                                if let Err(ref e) = persist_res {
                                        log_error!(self.logger, "Failed to persist channel monitor update: {:?}", e);
                                }
@@ -226,24 +245,24 @@ where C::Target: chain::Filter,
 
        fn release_pending_monitor_events(&self) -> Vec<MonitorEvent> {
                let mut pending_monitor_events = Vec::new();
-               for chan in self.monitors.lock().unwrap().values_mut() {
-                       pending_monitor_events.append(&mut chan.get_and_clear_pending_monitor_events());
+               for monitor in self.monitors.read().unwrap().values() {
+                       pending_monitor_events.append(&mut monitor.get_and_clear_pending_monitor_events());
                }
                pending_monitor_events
        }
 }
 
-impl<ChanSigner: ChannelKeys, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref> events::EventsProvider for ChainMonitor<ChanSigner, C, T, F, L, P>
+impl<ChannelSigner: Sign, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref> events::EventsProvider for ChainMonitor<ChannelSigner, C, T, F, L, P>
        where C::Target: chain::Filter,
              T::Target: BroadcasterInterface,
              F::Target: FeeEstimator,
              L::Target: Logger,
-             P::Target: channelmonitor::Persist<ChanSigner>,
+             P::Target: channelmonitor::Persist<ChannelSigner>,
 {
        fn get_and_clear_pending_events(&self) -> Vec<Event> {
                let mut pending_events = Vec::new();
-               for chan in self.monitors.lock().unwrap().values_mut() {
-                       pending_events.append(&mut chan.get_and_clear_pending_events());
+               for monitor in self.monitors.read().unwrap().values() {
+                       pending_events.append(&mut monitor.get_and_clear_pending_events());
                }
                pending_events
        }
index c3382caaea4f8f199b4bf40843788db682c5e6bf..4d2d1b848aecb187471c203e1f962675a37fdbf8 100644 (file)
 //!
 //! [`chain::Watch`]: ../trait.Watch.html
 
-use bitcoin::blockdata::block::BlockHeader;
+use bitcoin::blockdata::block::{Block, BlockHeader};
 use bitcoin::blockdata::transaction::{TxOut,Transaction};
 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
 use bitcoin::blockdata::script::{Script, Builder};
 use bitcoin::blockdata::opcodes;
-use bitcoin::consensus::encode;
 
 use bitcoin::hashes::Hash;
 use bitcoin::hashes::sha256::Hash as Sha256;
@@ -39,25 +38,27 @@ use bitcoin::secp256k1;
 
 use ln::msgs::DecodeError;
 use ln::chan_utils;
-use ln::chan_utils::{CounterpartyCommitmentSecrets, HTLCOutputInCommitment, HolderCommitmentTransaction, HTLCType};
+use ln::chan_utils::{CounterpartyCommitmentSecrets, HTLCOutputInCommitment, HTLCType, ChannelTransactionParameters, HolderCommitmentTransaction};
 use ln::channelmanager::{HTLCSource, PaymentPreimage, PaymentHash};
 use ln::onchaintx::{OnchainTxHandler, InputDescriptors};
+use chain;
 use chain::chaininterface::{BroadcasterInterface, FeeEstimator};
 use chain::transaction::{OutPoint, TransactionData};
-use chain::keysinterface::{SpendableOutputDescriptor, ChannelKeys};
+use chain::keysinterface::{SpendableOutputDescriptor, StaticPaymentOutputDescriptor, DelayedPaymentOutputDescriptor, Sign, KeysInterface};
 use util::logger::Logger;
-use util::ser::{Readable, MaybeReadable, Writer, Writeable, U48};
+use util::ser::{Readable, ReadableArgs, MaybeReadable, Writer, Writeable, U48};
 use util::byte_utils;
 use util::events::Event;
 
 use std::collections::{HashMap, HashSet, hash_map};
 use std::{cmp, mem};
-use std::ops::Deref;
 use std::io::Error;
+use std::ops::Deref;
+use std::sync::Mutex;
 
 /// An update generated by the underlying Channel itself which contains some new information the
 /// ChannelMonitor should be made aware of.
-#[cfg_attr(any(test, feature = "_test_utils"), derive(PartialEq))]
+#[cfg_attr(any(test, feature = "fuzztarget", feature = "_test_utils"), derive(PartialEq))]
 #[derive(Clone)]
 #[must_use]
 pub struct ChannelMonitorUpdate {
@@ -175,7 +176,7 @@ pub enum ChannelMonitorUpdateErr {
 /// means you tried to update a monitor for a different channel or the ChannelMonitorUpdate was
 /// corrupted.
 /// Contains a developer-readable error message.
-#[derive(Debug)]
+#[derive(Clone, Debug)]
 pub struct MonitorUpdateError(pub &'static str);
 
 /// An event to be processed by the ChannelManager.
@@ -252,6 +253,7 @@ pub(crate) const ANTI_REORG_DELAY: u32 = 6;
 /// end up force-closing the channel on us to claim it.
 pub(crate) const HTLC_FAIL_BACK_BUFFER: u32 = CLTV_CLAIM_BUFFER + LATENCY_GRACE_PERIOD_BLOCKS;
 
+// TODO(devrandom) replace this with HolderCommitmentTransaction
 #[derive(Clone, PartialEq)]
 struct HolderSignedTx {
        /// txid of the transaction in tx, just used to make comparison faster
@@ -485,7 +487,7 @@ enum OnchainEvent {
 const SERIALIZATION_VERSION: u8 = 1;
 const MIN_SERIALIZATION_VERSION: u8 = 1;
 
-#[cfg_attr(any(test, feature = "_test_utils"), derive(PartialEq))]
+#[cfg_attr(any(test, feature = "fuzztarget", feature = "_test_utils"), derive(PartialEq))]
 #[derive(Clone)]
 pub(crate) enum ChannelMonitorUpdateStep {
        LatestHolderCommitmentTXInfo {
@@ -493,7 +495,7 @@ pub(crate) enum ChannelMonitorUpdateStep {
                htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
        },
        LatestCounterpartyCommitmentTXInfo {
-               unsigned_commitment_tx: Transaction, // TODO: We should actually only need the txid here
+               commitment_txid: Txid,
                htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
                commitment_number: u64,
                their_revocation_point: PublicKey,
@@ -527,9 +529,9 @@ impl Writeable for ChannelMonitorUpdateStep {
                                        source.write(w)?;
                                }
                        }
-                       &ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { ref unsigned_commitment_tx, ref htlc_outputs, ref commitment_number, ref their_revocation_point } => {
+                       &ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { commitment_txid, ref htlc_outputs, ref commitment_number, ref their_revocation_point } => {
                                1u8.write(w)?;
-                               unsigned_commitment_tx.write(w)?;
+                               commitment_txid.write(w)?;
                                commitment_number.write(w)?;
                                their_revocation_point.write(w)?;
                                (htlc_outputs.len() as u64).write(w)?;
@@ -573,7 +575,7 @@ impl Readable for ChannelMonitorUpdateStep {
                        },
                        1u8 => {
                                Ok(ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo {
-                                       unsigned_commitment_tx: Readable::read(r)?,
+                                       commitment_txid: Readable::read(r)?,
                                        commitment_number: Readable::read(r)?,
                                        their_revocation_point: Readable::read(r)?,
                                        htlc_outputs: {
@@ -617,7 +619,20 @@ impl Readable for ChannelMonitorUpdateStep {
 /// get_and_clear_pending_monitor_events or get_and_clear_pending_events are serialized to disk and
 /// reloaded at deserialize-time. Thus, you must ensure that, when handling events, all events
 /// gotten are fully handled before re-serializing the new state.
-pub struct ChannelMonitor<ChanSigner: ChannelKeys> {
+///
+/// Note that the deserializer is only implemented for (Option<BlockHash>, ChannelMonitor), which
+/// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
+/// the "reorg path" (ie disconnecting blocks until you find a common ancestor from both the
+/// returned block hash and the the current chain and then reconnecting blocks to get to the
+/// best chain) upon deserializing the object!
+pub struct ChannelMonitor<Signer: Sign> {
+       #[cfg(test)]
+       pub(crate) inner: Mutex<ChannelMonitorImpl<Signer>>,
+       #[cfg(not(test))]
+       inner: Mutex<ChannelMonitorImpl<Signer>>,
+}
+
+pub(crate) struct ChannelMonitorImpl<Signer: Sign> {
        latest_update_id: u64,
        commitment_transaction_number_obscure_factor: u64,
 
@@ -626,7 +641,8 @@ pub struct ChannelMonitor<ChanSigner: ChannelKeys> {
        counterparty_payment_script: Script,
        shutdown_script: Script,
 
-       keys: ChanSigner,
+       channel_keys_id: [u8; 32],
+       holder_revocation_basepoint: PublicKey,
        funding_info: (OutPoint, Script),
        current_counterparty_commitment_txid: Option<Txid>,
        prev_counterparty_commitment_txid: Option<Txid>,
@@ -684,9 +700,9 @@ pub struct ChannelMonitor<ChanSigner: ChannelKeys> {
        outputs_to_watch: HashMap<Txid, Vec<(u32, Script)>>,
 
        #[cfg(test)]
-       pub onchain_tx_handler: OnchainTxHandler<ChanSigner>,
+       pub onchain_tx_handler: OnchainTxHandler<Signer>,
        #[cfg(not(test))]
-       onchain_tx_handler: OnchainTxHandler<ChanSigner>,
+       onchain_tx_handler: OnchainTxHandler<Signer>,
 
        // This is set when the Channel[Manager] generated a ChannelMonitorUpdate which indicated the
        // channel has been force-closed. After this is set, no further holder commitment transaction
@@ -714,14 +730,26 @@ pub struct ChannelMonitor<ChanSigner: ChannelKeys> {
 #[cfg(any(test, feature = "fuzztarget", feature = "_test_utils"))]
 /// Used only in testing and fuzztarget to check serialization roundtrips don't change the
 /// underlying object
-impl<ChanSigner: ChannelKeys> PartialEq for ChannelMonitor<ChanSigner> {
+impl<Signer: Sign> PartialEq for ChannelMonitor<Signer> {
+       fn eq(&self, other: &Self) -> bool {
+               let inner = self.inner.lock().unwrap();
+               let other = other.inner.lock().unwrap();
+               inner.eq(&other)
+       }
+}
+
+#[cfg(any(test, feature = "fuzztarget", feature = "_test_utils"))]
+/// Used only in testing and fuzztarget to check serialization roundtrips don't change the
+/// underlying object
+impl<Signer: Sign> PartialEq for ChannelMonitorImpl<Signer> {
        fn eq(&self, other: &Self) -> bool {
                if self.latest_update_id != other.latest_update_id ||
                        self.commitment_transaction_number_obscure_factor != other.commitment_transaction_number_obscure_factor ||
                        self.destination_script != other.destination_script ||
                        self.broadcasted_holder_revokable_script != other.broadcasted_holder_revokable_script ||
                        self.counterparty_payment_script != other.counterparty_payment_script ||
-                       self.keys.pubkeys() != other.keys.pubkeys() ||
+                       self.channel_keys_id != other.channel_keys_id ||
+                       self.holder_revocation_basepoint != other.holder_revocation_basepoint ||
                        self.funding_info != other.funding_info ||
                        self.current_counterparty_commitment_txid != other.current_counterparty_commitment_txid ||
                        self.prev_counterparty_commitment_txid != other.prev_counterparty_commitment_txid ||
@@ -753,20 +781,19 @@ impl<ChanSigner: ChannelKeys> PartialEq for ChannelMonitor<ChanSigner> {
        }
 }
 
-impl<ChanSigner: ChannelKeys + Writeable> ChannelMonitor<ChanSigner> {
-       /// Writes this monitor into the given writer, suitable for writing to disk.
-       ///
-       /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
-       /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
-       /// the "reorg path" (ie disconnecting blocks until you find a common ancestor from both the
-       /// returned block hash and the the current chain and then reconnecting blocks to get to the
-       /// best chain) upon deserializing the object!
-       pub fn serialize_for_disk<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
+impl<Signer: Sign> Writeable for ChannelMonitor<Signer> {
+       fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
                //TODO: We still write out all the serialization here manually instead of using the fancy
                //serialization framework we have, we should migrate things over to it.
                writer.write_all(&[SERIALIZATION_VERSION; 1])?;
                writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
 
+               self.inner.lock().unwrap().write(writer)
+       }
+}
+
+impl<Signer: Sign> Writeable for ChannelMonitorImpl<Signer> {
+       fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
                self.latest_update_id.write(writer)?;
 
                // Set in initial Channel-object creation, so should always be set by now:
@@ -785,7 +812,8 @@ impl<ChanSigner: ChannelKeys + Writeable> ChannelMonitor<ChanSigner> {
                self.counterparty_payment_script.write(writer)?;
                self.shutdown_script.write(writer)?;
 
-               self.keys.write(writer)?;
+               self.channel_keys_id.write(writer)?;
+               self.holder_revocation_basepoint.write(writer)?;
                writer.write_all(&self.funding_info.0.txid[..])?;
                writer.write_all(&byte_utils::be16_to_array(self.funding_info.0.index))?;
                self.funding_info.1.write(writer)?;
@@ -946,13 +974,13 @@ impl<ChanSigner: ChannelKeys + Writeable> ChannelMonitor<ChanSigner> {
        }
 }
 
-impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
-       pub(crate) fn new(keys: ChanSigner, shutdown_pubkey: &PublicKey,
-                       on_counterparty_tx_csv: u16, destination_script: &Script, funding_info: (OutPoint, Script),
-                       counterparty_htlc_base_key: &PublicKey, counterparty_delayed_payment_base_key: &PublicKey,
-                       on_holder_tx_csv: u16, funding_redeemscript: Script, channel_value_satoshis: u64,
-                       commitment_transaction_number_obscure_factor: u64,
-                       initial_holder_commitment_tx: HolderCommitmentTransaction) -> ChannelMonitor<ChanSigner> {
+impl<Signer: Sign> ChannelMonitor<Signer> {
+       pub(crate) fn new(secp_ctx: Secp256k1<secp256k1::All>, keys: Signer, shutdown_pubkey: &PublicKey,
+                         on_counterparty_tx_csv: u16, destination_script: &Script, funding_info: (OutPoint, Script),
+                         channel_parameters: &ChannelTransactionParameters,
+                         funding_redeemscript: Script, channel_value_satoshis: u64,
+                         commitment_transaction_number_obscure_factor: u64,
+                         initial_holder_commitment_tx: HolderCommitmentTransaction) -> ChannelMonitor<Signer> {
 
                assert!(commitment_transaction_number_obscure_factor <= (1 << 48));
                let our_channel_close_key_hash = WPubkeyHash::hash(&shutdown_pubkey.serialize());
@@ -960,75 +988,290 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
                let payment_key_hash = WPubkeyHash::hash(&keys.pubkeys().payment_point.serialize());
                let counterparty_payment_script = Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&payment_key_hash[..]).into_script();
 
-               let counterparty_tx_cache = CounterpartyCommitmentTransaction { counterparty_delayed_payment_base_key: *counterparty_delayed_payment_base_key, counterparty_htlc_base_key: *counterparty_htlc_base_key, on_counterparty_tx_csv, per_htlc: HashMap::new() };
-
-               let mut onchain_tx_handler = OnchainTxHandler::new(destination_script.clone(), keys.clone(), on_holder_tx_csv);
-
-               let holder_tx_sequence = initial_holder_commitment_tx.unsigned_tx.input[0].sequence as u64;
-               let holder_tx_locktime = initial_holder_commitment_tx.unsigned_tx.lock_time as u64;
-               let holder_commitment_tx = HolderSignedTx {
-                       txid: initial_holder_commitment_tx.txid(),
-                       revocation_key: initial_holder_commitment_tx.keys.revocation_key,
-                       a_htlc_key: initial_holder_commitment_tx.keys.broadcaster_htlc_key,
-                       b_htlc_key: initial_holder_commitment_tx.keys.countersignatory_htlc_key,
-                       delayed_payment_key: initial_holder_commitment_tx.keys.broadcaster_delayed_payment_key,
-                       per_commitment_point: initial_holder_commitment_tx.keys.per_commitment_point,
-                       feerate_per_kw: initial_holder_commitment_tx.feerate_per_kw,
-                       htlc_outputs: Vec::new(), // There are never any HTLCs in the initial commitment transactions
+               let counterparty_channel_parameters = channel_parameters.counterparty_parameters.as_ref().unwrap();
+               let counterparty_delayed_payment_base_key = counterparty_channel_parameters.pubkeys.delayed_payment_basepoint;
+               let counterparty_htlc_base_key = counterparty_channel_parameters.pubkeys.htlc_basepoint;
+               let counterparty_tx_cache = CounterpartyCommitmentTransaction { counterparty_delayed_payment_base_key, counterparty_htlc_base_key, on_counterparty_tx_csv, per_htlc: HashMap::new() };
+
+               let channel_keys_id = keys.channel_keys_id();
+               let holder_revocation_basepoint = keys.pubkeys().revocation_basepoint;
+
+               // block for Rust 1.34 compat
+               let (holder_commitment_tx, current_holder_commitment_number) = {
+                       let trusted_tx = initial_holder_commitment_tx.trust();
+                       let txid = trusted_tx.txid();
+
+                       let tx_keys = trusted_tx.keys();
+                       let holder_commitment_tx = HolderSignedTx {
+                               txid,
+                               revocation_key: tx_keys.revocation_key,
+                               a_htlc_key: tx_keys.broadcaster_htlc_key,
+                               b_htlc_key: tx_keys.countersignatory_htlc_key,
+                               delayed_payment_key: tx_keys.broadcaster_delayed_payment_key,
+                               per_commitment_point: tx_keys.per_commitment_point,
+                               feerate_per_kw: trusted_tx.feerate_per_kw(),
+                               htlc_outputs: Vec::new(), // There are never any HTLCs in the initial commitment transactions
+                       };
+                       (holder_commitment_tx, trusted_tx.commitment_number())
                };
-               onchain_tx_handler.provide_latest_holder_tx(initial_holder_commitment_tx);
+
+               let onchain_tx_handler =
+                       OnchainTxHandler::new(destination_script.clone(), keys,
+                       channel_parameters.clone(), initial_holder_commitment_tx, secp_ctx.clone());
 
                let mut outputs_to_watch = HashMap::new();
                outputs_to_watch.insert(funding_info.0.txid, vec![(funding_info.0.index as u32, funding_info.1.clone())]);
 
                ChannelMonitor {
-                       latest_update_id: 0,
-                       commitment_transaction_number_obscure_factor,
+                       inner: Mutex::new(ChannelMonitorImpl {
+                               latest_update_id: 0,
+                               commitment_transaction_number_obscure_factor,
 
-                       destination_script: destination_script.clone(),
-                       broadcasted_holder_revokable_script: None,
-                       counterparty_payment_script,
-                       shutdown_script,
+                               destination_script: destination_script.clone(),
+                               broadcasted_holder_revokable_script: None,
+                               counterparty_payment_script,
+                               shutdown_script,
 
-                       keys,
-                       funding_info,
-                       current_counterparty_commitment_txid: None,
-                       prev_counterparty_commitment_txid: None,
+                               channel_keys_id,
+                               holder_revocation_basepoint,
+                               funding_info,
+                               current_counterparty_commitment_txid: None,
+                               prev_counterparty_commitment_txid: None,
 
-                       counterparty_tx_cache,
-                       funding_redeemscript,
-                       channel_value_satoshis,
-                       their_cur_revocation_points: None,
+                               counterparty_tx_cache,
+                               funding_redeemscript,
+                               channel_value_satoshis,
+                               their_cur_revocation_points: None,
 
-                       on_holder_tx_csv,
+                               on_holder_tx_csv: counterparty_channel_parameters.selected_contest_delay,
 
-                       commitment_secrets: CounterpartyCommitmentSecrets::new(),
-                       counterparty_claimable_outpoints: HashMap::new(),
-                       counterparty_commitment_txn_on_chain: HashMap::new(),
-                       counterparty_hash_commitment_number: HashMap::new(),
+                               commitment_secrets: CounterpartyCommitmentSecrets::new(),
+                               counterparty_claimable_outpoints: HashMap::new(),
+                               counterparty_commitment_txn_on_chain: HashMap::new(),
+                               counterparty_hash_commitment_number: HashMap::new(),
 
-                       prev_holder_signed_commitment_tx: None,
-                       current_holder_commitment_tx: holder_commitment_tx,
-                       current_counterparty_commitment_number: 1 << 48,
-                       current_holder_commitment_number: 0xffff_ffff_ffff - ((((holder_tx_sequence & 0xffffff) << 3*8) | (holder_tx_locktime as u64 & 0xffffff)) ^ commitment_transaction_number_obscure_factor),
+                               prev_holder_signed_commitment_tx: None,
+                               current_holder_commitment_tx: holder_commitment_tx,
+                               current_counterparty_commitment_number: 1 << 48,
+                               current_holder_commitment_number,
 
-                       payment_preimages: HashMap::new(),
-                       pending_monitor_events: Vec::new(),
-                       pending_events: Vec::new(),
+                               payment_preimages: HashMap::new(),
+                               pending_monitor_events: Vec::new(),
+                               pending_events: Vec::new(),
 
-                       onchain_events_waiting_threshold_conf: HashMap::new(),
-                       outputs_to_watch,
+                               onchain_events_waiting_threshold_conf: HashMap::new(),
+                               outputs_to_watch,
 
-                       onchain_tx_handler,
+                               onchain_tx_handler,
 
-                       lockdown_from_offchain: false,
-                       holder_tx_signed: false,
+                               lockdown_from_offchain: false,
+                               holder_tx_signed: false,
 
-                       last_block_hash: Default::default(),
-                       secp_ctx: Secp256k1::new(),
+                               last_block_hash: Default::default(),
+                               secp_ctx,
+                       }),
                }
        }
 
+       #[cfg(test)]
+       fn provide_secret(&self, idx: u64, secret: [u8; 32]) -> Result<(), MonitorUpdateError> {
+               self.inner.lock().unwrap().provide_secret(idx, secret)
+       }
+
+       /// Informs this monitor of the latest counterparty (ie non-broadcastable) commitment transaction.
+       /// The monitor watches for it to be broadcasted and then uses the HTLC information (and
+       /// possibly future revocation/preimage information) to claim outputs where possible.
+       /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers.
+       pub(crate) fn provide_latest_counterparty_commitment_tx<L: Deref>(
+               &self,
+               txid: Txid,
+               htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
+               commitment_number: u64,
+               their_revocation_point: PublicKey,
+               logger: &L,
+       ) where L::Target: Logger {
+               self.inner.lock().unwrap().provide_latest_counterparty_commitment_tx(
+                       txid, htlc_outputs, commitment_number, their_revocation_point, logger)
+       }
+
+       #[cfg(test)]
+       fn provide_latest_holder_commitment_tx(
+               &self,
+               holder_commitment_tx: HolderCommitmentTransaction,
+               htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
+       ) -> Result<(), MonitorUpdateError> {
+               self.inner.lock().unwrap().provide_latest_holder_commitment_tx(
+                       holder_commitment_tx, htlc_outputs)
+       }
+
+       #[cfg(test)]
+       pub(crate) fn provide_payment_preimage<B: Deref, F: Deref, L: Deref>(
+               &self,
+               payment_hash: &PaymentHash,
+               payment_preimage: &PaymentPreimage,
+               broadcaster: &B,
+               fee_estimator: &F,
+               logger: &L,
+       ) where
+               B::Target: BroadcasterInterface,
+               F::Target: FeeEstimator,
+               L::Target: Logger,
+       {
+               self.inner.lock().unwrap().provide_payment_preimage(
+                       payment_hash, payment_preimage, broadcaster, fee_estimator, logger)
+       }
+
+       pub(crate) fn broadcast_latest_holder_commitment_txn<B: Deref, L: Deref>(
+               &self,
+               broadcaster: &B,
+               logger: &L,
+       ) where
+               B::Target: BroadcasterInterface,
+               L::Target: Logger,
+       {
+               self.inner.lock().unwrap().broadcast_latest_holder_commitment_txn(broadcaster, logger)
+       }
+
+       /// Updates a ChannelMonitor on the basis of some new information provided by the Channel
+       /// itself.
+       ///
+       /// panics if the given update is not the next update by update_id.
+       pub fn update_monitor<B: Deref, F: Deref, L: Deref>(
+               &self,
+               updates: &ChannelMonitorUpdate,
+               broadcaster: &B,
+               fee_estimator: &F,
+               logger: &L,
+       ) -> Result<(), MonitorUpdateError>
+       where
+               B::Target: BroadcasterInterface,
+               F::Target: FeeEstimator,
+               L::Target: Logger,
+       {
+               self.inner.lock().unwrap().update_monitor(updates, broadcaster, fee_estimator, logger)
+       }
+
+       /// Gets the update_id from the latest ChannelMonitorUpdate which was applied to this
+       /// ChannelMonitor.
+       pub fn get_latest_update_id(&self) -> u64 {
+               self.inner.lock().unwrap().get_latest_update_id()
+       }
+
+       /// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
+       pub fn get_funding_txo(&self) -> (OutPoint, Script) {
+               self.inner.lock().unwrap().get_funding_txo().clone()
+       }
+
+       /// Gets a list of txids, with their output scripts (in the order they appear in the
+       /// transaction), which we must learn about spends of via block_connected().
+       ///
+       /// (C-not exported) because we have no HashMap bindings
+       pub fn get_outputs_to_watch(&self) -> HashMap<Txid, Vec<(u32, Script)>> {
+               self.inner.lock().unwrap().get_outputs_to_watch().clone()
+       }
+
+       /// Get the list of HTLCs who's status has been updated on chain. This should be called by
+       /// ChannelManager via [`chain::Watch::release_pending_monitor_events`].
+       ///
+       /// [`chain::Watch::release_pending_monitor_events`]: ../trait.Watch.html#tymethod.release_pending_monitor_events
+       pub fn get_and_clear_pending_monitor_events(&self) -> Vec<MonitorEvent> {
+               self.inner.lock().unwrap().get_and_clear_pending_monitor_events()
+       }
+
+       /// Gets the list of pending events which were generated by previous actions, clearing the list
+       /// in the process.
+       ///
+       /// This is called by ChainMonitor::get_and_clear_pending_events() and is equivalent to
+       /// EventsProvider::get_and_clear_pending_events() except that it requires &mut self as we do
+       /// no internal locking in ChannelMonitors.
+       pub fn get_and_clear_pending_events(&self) -> Vec<Event> {
+               self.inner.lock().unwrap().get_and_clear_pending_events()
+       }
+
+       pub(crate) fn get_min_seen_secret(&self) -> u64 {
+               self.inner.lock().unwrap().get_min_seen_secret()
+       }
+
+       pub(crate) fn get_cur_counterparty_commitment_number(&self) -> u64 {
+               self.inner.lock().unwrap().get_cur_counterparty_commitment_number()
+       }
+
+       pub(crate) fn get_cur_holder_commitment_number(&self) -> u64 {
+               self.inner.lock().unwrap().get_cur_holder_commitment_number()
+       }
+
+       /// Used by ChannelManager deserialization to broadcast the latest holder state if its copy of
+       /// the Channel was out-of-date. You may use it to get a broadcastable holder toxic tx in case of
+       /// fallen-behind, i.e when receiving a channel_reestablish with a proof that our counterparty side knows
+       /// a higher revocation secret than the holder commitment number we are aware of. Broadcasting these
+       /// transactions are UNSAFE, as they allow counterparty side to punish you. Nevertheless you may want to
+       /// broadcast them if counterparty don't close channel with his higher commitment transaction after a
+       /// substantial amount of time (a month or even a year) to get back funds. Best may be to contact
+       /// out-of-band the other node operator to coordinate with him if option is available to you.
+       /// In any-case, choice is up to the user.
+       pub fn get_latest_holder_commitment_txn<L: Deref>(&self, logger: &L) -> Vec<Transaction>
+       where L::Target: Logger {
+               self.inner.lock().unwrap().get_latest_holder_commitment_txn(logger)
+       }
+
+       /// Unsafe test-only version of get_latest_holder_commitment_txn used by our test framework
+       /// to bypass HolderCommitmentTransaction state update lockdown after signature and generate
+       /// revoked commitment transaction.
+       #[cfg(any(test, feature = "unsafe_revoked_tx_signing"))]
+       pub fn unsafe_get_latest_holder_commitment_txn<L: Deref>(&self, logger: &L) -> Vec<Transaction>
+       where L::Target: Logger {
+               self.inner.lock().unwrap().unsafe_get_latest_holder_commitment_txn(logger)
+       }
+
+       /// Processes transactions in a newly connected block, which may result in any of the following:
+       /// - update the monitor's state against resolved HTLCs
+       /// - punish the counterparty in the case of seeing a revoked commitment transaction
+       /// - force close the channel and claim/timeout incoming/outgoing HTLCs if near expiration
+       /// - detect settled outputs for later spending
+       /// - schedule and bump any in-flight claims
+       ///
+       /// Returns any new outputs to watch from `txdata`; after called, these are also included in
+       /// [`get_outputs_to_watch`].
+       ///
+       /// [`get_outputs_to_watch`]: #method.get_outputs_to_watch
+       pub fn block_connected<B: Deref, F: Deref, L: Deref>(
+               &self,
+               header: &BlockHeader,
+               txdata: &TransactionData,
+               height: u32,
+               broadcaster: B,
+               fee_estimator: F,
+               logger: L,
+       ) -> Vec<(Txid, Vec<(u32, TxOut)>)>
+       where
+               B::Target: BroadcasterInterface,
+               F::Target: FeeEstimator,
+               L::Target: Logger,
+       {
+               self.inner.lock().unwrap().block_connected(
+                       header, txdata, height, broadcaster, fee_estimator, logger)
+       }
+
+       /// Determines if the disconnected block contained any transactions of interest and updates
+       /// appropriately.
+       pub fn block_disconnected<B: Deref, F: Deref, L: Deref>(
+               &self,
+               header: &BlockHeader,
+               height: u32,
+               broadcaster: B,
+               fee_estimator: F,
+               logger: L,
+       ) where
+               B::Target: BroadcasterInterface,
+               F::Target: FeeEstimator,
+               L::Target: Logger,
+       {
+               self.inner.lock().unwrap().block_disconnected(
+                       header, height, broadcaster, fee_estimator, logger)
+       }
+}
+
+impl<Signer: Sign> ChannelMonitorImpl<Signer> {
        /// Inserts a revocation secret into this channel monitor. Prunes old preimages if neither
        /// needed by holder commitment transactions HTCLs nor by counterparty ones. Unless we haven't already seen
        /// counterparty commitment transaction's secret, they are de facto pruned (we can use revocation key).
@@ -1080,11 +1323,7 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
                Ok(())
        }
 
-       /// Informs this monitor of the latest counterparty (ie non-broadcastable) commitment transaction.
-       /// The monitor watches for it to be broadcasted and then uses the HTLC information (and
-       /// possibly future revocation/preimage information) to claim outputs where possible.
-       /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers.
-       pub(crate) fn provide_latest_counterparty_commitment_tx_info<L: Deref>(&mut self, unsigned_commitment_tx: &Transaction, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>, commitment_number: u64, their_revocation_point: PublicKey, logger: &L) where L::Target: Logger {
+       pub(crate) fn provide_latest_counterparty_commitment_tx<L: Deref>(&mut self, txid: Txid, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>, commitment_number: u64, their_revocation_point: PublicKey, logger: &L) where L::Target: Logger {
                // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
                // so that a remote monitor doesn't learn anything unless there is a malicious close.
                // (only maybe, sadly we cant do the same for local info, as we need to be aware of
@@ -1093,12 +1332,10 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
                        self.counterparty_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
                }
 
-               let new_txid = unsigned_commitment_tx.txid();
-               log_trace!(logger, "Tracking new counterparty commitment transaction with txid {} at commitment number {} with {} HTLC outputs", new_txid, commitment_number, htlc_outputs.len());
-               log_trace!(logger, "New potential counterparty commitment transaction: {}", encode::serialize_hex(unsigned_commitment_tx));
+               log_trace!(logger, "Tracking new counterparty commitment transaction with txid {} at commitment number {} with {} HTLC outputs", txid, commitment_number, htlc_outputs.len());
                self.prev_counterparty_commitment_txid = self.current_counterparty_commitment_txid.take();
-               self.current_counterparty_commitment_txid = Some(new_txid);
-               self.counterparty_claimable_outpoints.insert(new_txid, htlc_outputs.clone());
+               self.current_counterparty_commitment_txid = Some(txid);
+               self.counterparty_claimable_outpoints.insert(txid, htlc_outputs.clone());
                self.current_counterparty_commitment_number = commitment_number;
                //TODO: Merge this into the other per-counterparty-transaction output storage stuff
                match self.their_cur_revocation_points {
@@ -1125,7 +1362,7 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
                                htlcs.push(htlc.0);
                        }
                }
-               self.counterparty_tx_cache.per_htlc.insert(new_txid, htlcs);
+               self.counterparty_tx_cache.per_htlc.insert(txid, htlcs);
        }
 
        /// Informs this monitor of the latest holder (ie broadcastable) commitment transaction. The
@@ -1133,22 +1370,25 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
        /// is important that any clones of this channel monitor (including remote clones) by kept
        /// up-to-date as our holder commitment transaction is updated.
        /// Panics if set_on_holder_tx_csv has never been called.
-       fn provide_latest_holder_commitment_tx_info(&mut self, commitment_tx: HolderCommitmentTransaction, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>) -> Result<(), MonitorUpdateError> {
-               let txid = commitment_tx.txid();
-               let sequence = commitment_tx.unsigned_tx.input[0].sequence as u64;
-               let locktime = commitment_tx.unsigned_tx.lock_time as u64;
-               let mut new_holder_commitment_tx = HolderSignedTx {
-                       txid,
-                       revocation_key: commitment_tx.keys.revocation_key,
-                       a_htlc_key: commitment_tx.keys.broadcaster_htlc_key,
-                       b_htlc_key: commitment_tx.keys.countersignatory_htlc_key,
-                       delayed_payment_key: commitment_tx.keys.broadcaster_delayed_payment_key,
-                       per_commitment_point: commitment_tx.keys.per_commitment_point,
-                       feerate_per_kw: commitment_tx.feerate_per_kw,
-                       htlc_outputs,
+       fn provide_latest_holder_commitment_tx(&mut self, holder_commitment_tx: HolderCommitmentTransaction, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>) -> Result<(), MonitorUpdateError> {
+               // block for Rust 1.34 compat
+               let mut new_holder_commitment_tx = {
+                       let trusted_tx = holder_commitment_tx.trust();
+                       let txid = trusted_tx.txid();
+                       let tx_keys = trusted_tx.keys();
+                       self.current_holder_commitment_number = trusted_tx.commitment_number();
+                       HolderSignedTx {
+                               txid,
+                               revocation_key: tx_keys.revocation_key,
+                               a_htlc_key: tx_keys.broadcaster_htlc_key,
+                               b_htlc_key: tx_keys.countersignatory_htlc_key,
+                               delayed_payment_key: tx_keys.broadcaster_delayed_payment_key,
+                               per_commitment_point: tx_keys.per_commitment_point,
+                               feerate_per_kw: trusted_tx.feerate_per_kw(),
+                               htlc_outputs,
+                       }
                };
-               self.onchain_tx_handler.provide_latest_holder_tx(commitment_tx);
-               self.current_holder_commitment_number = 0xffff_ffff_ffff - ((((sequence & 0xffffff) << 3*8) | (locktime as u64 & 0xffffff)) ^ self.commitment_transaction_number_obscure_factor);
+               self.onchain_tx_handler.provide_latest_holder_tx(holder_commitment_tx);
                mem::swap(&mut new_holder_commitment_tx, &mut self.current_holder_commitment_tx);
                self.prev_holder_signed_commitment_tx = Some(new_holder_commitment_tx);
                if self.holder_tx_signed {
@@ -1159,7 +1399,7 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
 
        /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
        /// commitment_tx_infos which contain the payment hash have been revoked.
-       pub(crate) fn provide_payment_preimage<B: Deref, F: Deref, L: Deref>(&mut self, payment_hash: &PaymentHash, payment_preimage: &PaymentPreimage, broadcaster: &B, fee_estimator: &F, logger: &L)
+       fn provide_payment_preimage<B: Deref, F: Deref, L: Deref>(&mut self, payment_hash: &PaymentHash, payment_preimage: &PaymentPreimage, broadcaster: &B, fee_estimator: &F, logger: &L)
        where B::Target: BroadcasterInterface,
                    F::Target: FeeEstimator,
                    L::Target: Logger,
@@ -1212,10 +1452,6 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
                self.pending_monitor_events.push(MonitorEvent::CommitmentTxBroadcasted(self.funding_info.0));
        }
 
-       /// Updates a ChannelMonitor on the basis of some new information provided by the Channel
-       /// itself.
-       ///
-       /// panics if the given update is not the next update by update_id.
        pub fn update_monitor<B: Deref, F: Deref, L: Deref>(&mut self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: &F, logger: &L) -> Result<(), MonitorUpdateError>
        where B::Target: BroadcasterInterface,
                    F::Target: FeeEstimator,
@@ -1239,11 +1475,11 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
                                ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { commitment_tx, htlc_outputs } => {
                                        log_trace!(logger, "Updating ChannelMonitor with latest holder commitment transaction info");
                                        if self.lockdown_from_offchain { panic!(); }
-                                       self.provide_latest_holder_commitment_tx_info(commitment_tx.clone(), htlc_outputs.clone())?
-                               },
-                               ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { unsigned_commitment_tx, htlc_outputs, commitment_number, their_revocation_point } => {
+                                       self.provide_latest_holder_commitment_tx(commitment_tx.clone(), htlc_outputs.clone())?
+                               }
+                               ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { commitment_txid, htlc_outputs, commitment_number, their_revocation_point } => {
                                        log_trace!(logger, "Updating ChannelMonitor with latest counterparty commitment transaction info");
-                                       self.provide_latest_counterparty_commitment_tx_info(&unsigned_commitment_tx, htlc_outputs.clone(), *commitment_number, *their_revocation_point, logger)
+                                       self.provide_latest_counterparty_commitment_tx(*commitment_txid, htlc_outputs.clone(), *commitment_number, *their_revocation_point, logger)
                                },
                                ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage } => {
                                        log_trace!(logger, "Updating ChannelMonitor with payment preimage");
@@ -1268,21 +1504,14 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
                Ok(())
        }
 
-       /// Gets the update_id from the latest ChannelMonitorUpdate which was applied to this
-       /// ChannelMonitor.
        pub fn get_latest_update_id(&self) -> u64 {
                self.latest_update_id
        }
 
-       /// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
        pub fn get_funding_txo(&self) -> &(OutPoint, Script) {
                &self.funding_info
        }
 
-       /// Gets a list of txids, with their output scripts (in the order they appear in the
-       /// transaction), which we must learn about spends of via block_connected().
-       ///
-       /// (C-not exported) because we have no HashMap bindings
        pub fn get_outputs_to_watch(&self) -> &HashMap<Txid, Vec<(u32, Script)>> {
                // If we've detected a counterparty commitment tx on chain, we must include it in the set
                // of outputs to watch for spends of, otherwise we're likely to lose user funds. Because
@@ -1293,22 +1522,12 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
                &self.outputs_to_watch
        }
 
-       /// Get the list of HTLCs who's status has been updated on chain. This should be called by
-       /// ChannelManager via [`chain::Watch::release_pending_monitor_events`].
-       ///
-       /// [`chain::Watch::release_pending_monitor_events`]: ../trait.Watch.html#tymethod.release_pending_monitor_events
        pub fn get_and_clear_pending_monitor_events(&mut self) -> Vec<MonitorEvent> {
                let mut ret = Vec::new();
                mem::swap(&mut ret, &mut self.pending_monitor_events);
                ret
        }
 
-       /// Gets the list of pending events which were generated by previous actions, clearing the list
-       /// in the process.
-       ///
-       /// This is called by ChainMonitor::get_and_clear_pending_events() and is equivalent to
-       /// EventsProvider::get_and_clear_pending_events() except that it requires &mut self as we do
-       /// no internal locking in ChannelMonitors.
        pub fn get_and_clear_pending_events(&mut self) -> Vec<Event> {
                let mut ret = Vec::new();
                mem::swap(&mut ret, &mut self.pending_events);
@@ -1361,7 +1580,7 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
                        let secret = self.get_secret(commitment_number).unwrap();
                        let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
                        let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
-                       let revocation_pubkey = ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &self.keys.pubkeys().revocation_basepoint));
+                       let revocation_pubkey = ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &self.holder_revocation_basepoint));
                        let delayed_key = ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key), &self.counterparty_tx_cache.counterparty_delayed_payment_base_key));
 
                        let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.counterparty_tx_cache.on_counterparty_tx_csv, &delayed_key);
@@ -1696,81 +1915,54 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
                (claim_requests, (commitment_txid, watch_outputs))
        }
 
-       /// Used by ChannelManager deserialization to broadcast the latest holder state if its copy of
-       /// the Channel was out-of-date. You may use it to get a broadcastable holder toxic tx in case of
-       /// fallen-behind, i.e when receiving a channel_reestablish with a proof that our counterparty side knows
-       /// a higher revocation secret than the holder commitment number we are aware of. Broadcasting these
-       /// transactions are UNSAFE, as they allow counterparty side to punish you. Nevertheless you may want to
-       /// broadcast them if counterparty don't close channel with his higher commitment transaction after a
-       /// substantial amount of time (a month or even a year) to get back funds. Best may be to contact
-       /// out-of-band the other node operator to coordinate with him if option is available to you.
-       /// In any-case, choice is up to the user.
        pub fn get_latest_holder_commitment_txn<L: Deref>(&mut self, logger: &L) -> Vec<Transaction> where L::Target: Logger {
                log_trace!(logger, "Getting signed latest holder commitment transaction!");
                self.holder_tx_signed = true;
-               if let Some(commitment_tx) = self.onchain_tx_handler.get_fully_signed_holder_tx(&self.funding_redeemscript) {
-                       let txid = commitment_tx.txid();
-                       let mut res = vec![commitment_tx];
-                       for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
-                               if let Some(vout) = htlc.0.transaction_output_index {
-                                       let preimage = if !htlc.0.offered {
-                                                       if let Some(preimage) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
-                                                               // We can't build an HTLC-Success transaction without the preimage
-                                                               continue;
-                                                       }
-                                               } else { None };
-                                       if let Some(htlc_tx) = self.onchain_tx_handler.get_fully_signed_htlc_tx(
-                                                       &::bitcoin::OutPoint { txid, vout }, &preimage) {
-                                               res.push(htlc_tx);
+               let commitment_tx = self.onchain_tx_handler.get_fully_signed_holder_tx(&self.funding_redeemscript);
+               let txid = commitment_tx.txid();
+               let mut res = vec![commitment_tx];
+               for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
+                       if let Some(vout) = htlc.0.transaction_output_index {
+                               let preimage = if !htlc.0.offered {
+                                       if let Some(preimage) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
+                                               // We can't build an HTLC-Success transaction without the preimage
+                                               continue;
                                        }
+                               } else { None };
+                               if let Some(htlc_tx) = self.onchain_tx_handler.get_fully_signed_htlc_tx(
+                                       &::bitcoin::OutPoint { txid, vout }, &preimage) {
+                                       res.push(htlc_tx);
                                }
                        }
-                       // We throw away the generated waiting_first_conf data as we aren't (yet) confirmed and we don't actually know what the caller wants to do.
-                       // The data will be re-generated and tracked in check_spend_holder_transaction if we get a confirmation.
-                       return res
                }
-               Vec::new()
+               // We throw away the generated waiting_first_conf data as we aren't (yet) confirmed and we don't actually know what the caller wants to do.
+               // The data will be re-generated and tracked in check_spend_holder_transaction if we get a confirmation.
+               return res;
        }
 
-       /// Unsafe test-only version of get_latest_holder_commitment_txn used by our test framework
-       /// to bypass HolderCommitmentTransaction state update lockdown after signature and generate
-       /// revoked commitment transaction.
        #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
-       pub fn unsafe_get_latest_holder_commitment_txn<L: Deref>(&mut self, logger: &L) -> Vec<Transaction> where L::Target: Logger {
+       fn unsafe_get_latest_holder_commitment_txn<L: Deref>(&mut self, logger: &L) -> Vec<Transaction> where L::Target: Logger {
                log_trace!(logger, "Getting signed copy of latest holder commitment transaction!");
-               if let Some(commitment_tx) = self.onchain_tx_handler.get_fully_signed_copy_holder_tx(&self.funding_redeemscript) {
-                       let txid = commitment_tx.txid();
-                       let mut res = vec![commitment_tx];
-                       for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
-                               if let Some(vout) = htlc.0.transaction_output_index {
-                                       let preimage = if !htlc.0.offered {
-                                                       if let Some(preimage) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
-                                                               // We can't build an HTLC-Success transaction without the preimage
-                                                               continue;
-                                                       }
-                                               } else { None };
-                                       if let Some(htlc_tx) = self.onchain_tx_handler.unsafe_get_fully_signed_htlc_tx(
-                                                       &::bitcoin::OutPoint { txid, vout }, &preimage) {
-                                               res.push(htlc_tx);
+               let commitment_tx = self.onchain_tx_handler.get_fully_signed_copy_holder_tx(&self.funding_redeemscript);
+               let txid = commitment_tx.txid();
+               let mut res = vec![commitment_tx];
+               for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
+                       if let Some(vout) = htlc.0.transaction_output_index {
+                               let preimage = if !htlc.0.offered {
+                                       if let Some(preimage) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
+                                               // We can't build an HTLC-Success transaction without the preimage
+                                               continue;
                                        }
+                               } else { None };
+                               if let Some(htlc_tx) = self.onchain_tx_handler.unsafe_get_fully_signed_htlc_tx(
+                                       &::bitcoin::OutPoint { txid, vout }, &preimage) {
+                                       res.push(htlc_tx);
                                }
                        }
-                       return res
                }
-               Vec::new()
+               return res
        }
 
-       /// Processes transactions in a newly connected block, which may result in any of the following:
-       /// - update the monitor's state against resolved HTLCs
-       /// - punish the counterparty in the case of seeing a revoked commitment transaction
-       /// - force close the channel and claim/timeout incoming/outgoing HTLCs if near expiration
-       /// - detect settled outputs for later spending
-       /// - schedule and bump any in-flight claims
-       ///
-       /// Returns any new outputs to watch from `txdata`; after called, these are also included in
-       /// [`get_outputs_to_watch`].
-       ///
-       /// [`get_outputs_to_watch`]: #method.get_outputs_to_watch
        pub fn block_connected<B: Deref, F: Deref, L: Deref>(&mut self, header: &BlockHeader, txdata: &TransactionData, height: u32, broadcaster: B, fee_estimator: F, logger: L)-> Vec<(Txid, Vec<(u32, TxOut)>)>
                where B::Target: BroadcasterInterface,
                      F::Target: FeeEstimator,
@@ -1836,15 +2028,14 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
                }
                if should_broadcast {
                        self.pending_monitor_events.push(MonitorEvent::CommitmentTxBroadcasted(self.funding_info.0));
-                       if let Some(commitment_tx) = self.onchain_tx_handler.get_fully_signed_holder_tx(&self.funding_redeemscript) {
-                               self.holder_tx_signed = true;
-                               let (mut new_outpoints, _) = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx);
-                               let new_outputs = self.get_broadcasted_holder_watch_outputs(&self.current_holder_commitment_tx, &commitment_tx);
-                               if !new_outputs.is_empty() {
-                                       watch_outputs.push((self.current_holder_commitment_tx.txid.clone(), new_outputs));
-                               }
-                               claimable_outpoints.append(&mut new_outpoints);
+                       let commitment_tx = self.onchain_tx_handler.get_fully_signed_holder_tx(&self.funding_redeemscript);
+                       self.holder_tx_signed = true;
+                       let (mut new_outpoints, _) = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx);
+                       let new_outputs = self.get_broadcasted_holder_watch_outputs(&self.current_holder_commitment_tx, &commitment_tx);
+                       if !new_outputs.is_empty() {
+                               watch_outputs.push((self.current_holder_commitment_tx.txid.clone(), new_outputs));
                        }
+                       claimable_outpoints.append(&mut new_outpoints);
                }
                if let Some(events) = self.onchain_events_waiting_threshold_conf.remove(&height) {
                        for ev in events {
@@ -1893,8 +2084,6 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
                watch_outputs
        }
 
-       /// Determines if the disconnected block contained any transactions of interest and updates
-       /// appropriately.
        pub fn block_disconnected<B: Deref, F: Deref, L: Deref>(&mut self, header: &BlockHeader, height: u32, broadcaster: B, fee_estimator: F, logger: L)
                where B::Target: BroadcasterInterface,
                      F::Target: FeeEstimator,
@@ -2188,22 +2377,24 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
                                break;
                        } else if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
                                if broadcasted_holder_revokable_script.0 == outp.script_pubkey {
-                                       spendable_output =  Some(SpendableOutputDescriptor::DynamicOutputP2WSH {
+                                       spendable_output =  Some(SpendableOutputDescriptor::DelayedPaymentOutput(DelayedPaymentOutputDescriptor {
                                                outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
                                                per_commitment_point: broadcasted_holder_revokable_script.1,
                                                to_self_delay: self.on_holder_tx_csv,
                                                output: outp.clone(),
-                                               key_derivation_params: self.keys.key_derivation_params(),
                                                revocation_pubkey: broadcasted_holder_revokable_script.2.clone(),
-                                       });
+                                               channel_keys_id: self.channel_keys_id,
+                                               channel_value_satoshis: self.channel_value_satoshis,
+                                       }));
                                        break;
                                }
                        } else if self.counterparty_payment_script == outp.script_pubkey {
-                               spendable_output = Some(SpendableOutputDescriptor::StaticOutputCounterpartyPayment {
+                               spendable_output = Some(SpendableOutputDescriptor::StaticPaymentOutput(StaticPaymentOutputDescriptor {
                                        outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
                                        output: outp.clone(),
-                                       key_derivation_params: self.keys.key_derivation_params(),
-                               });
+                                       channel_keys_id: self.channel_keys_id,
+                                       channel_value_satoshis: self.channel_value_satoshis,
+                               }));
                                break;
                        } else if outp.script_pubkey == self.shutdown_script {
                                spendable_output = Some(SpendableOutputDescriptor::StaticOutput {
@@ -2238,7 +2429,7 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
 /// transaction and losing money. This is a risk because previous channel states
 /// are toxic, so it's important that whatever channel state is persisted is
 /// kept up-to-date.
-pub trait Persist<Keys: ChannelKeys>: Send + Sync {
+pub trait Persist<ChannelSigner: Sign>: Send + Sync {
        /// Persist a new channel's data. The data can be stored any way you want, but
        /// the identifier provided by Rust-Lightning is the channel's outpoint (and
        /// it is up to you to maintain a correct mapping between the outpoint and the
@@ -2250,7 +2441,7 @@ pub trait Persist<Keys: ChannelKeys>: Send + Sync {
        ///
        /// [`ChannelMonitor::serialize_for_disk`]: struct.ChannelMonitor.html#method.serialize_for_disk
        /// [`ChannelMonitorUpdateErr`]: enum.ChannelMonitorUpdateErr.html
-       fn persist_new_channel(&self, id: OutPoint, data: &ChannelMonitor<Keys>) -> Result<(), ChannelMonitorUpdateErr>;
+       fn persist_new_channel(&self, id: OutPoint, data: &ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr>;
 
        /// Update one channel's data. The provided `ChannelMonitor` has already
        /// applied the given update.
@@ -2279,13 +2470,30 @@ pub trait Persist<Keys: ChannelKeys>: Send + Sync {
        /// [`ChannelMonitor::serialize_for_disk`]: struct.ChannelMonitor.html#method.serialize_for_disk
        /// [`ChannelMonitorUpdate::write`]: struct.ChannelMonitorUpdate.html#method.write
        /// [`ChannelMonitorUpdateErr`]: enum.ChannelMonitorUpdateErr.html
-       fn update_persisted_channel(&self, id: OutPoint, update: &ChannelMonitorUpdate, data: &ChannelMonitor<Keys>) -> Result<(), ChannelMonitorUpdateErr>;
+       fn update_persisted_channel(&self, id: OutPoint, update: &ChannelMonitorUpdate, data: &ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr>;
+}
+
+impl<Signer: Sign, T: Deref, F: Deref, L: Deref> chain::Listen for (ChannelMonitor<Signer>, T, F, L)
+where
+       T::Target: BroadcasterInterface,
+       F::Target: FeeEstimator,
+       L::Target: Logger,
+{
+       fn block_connected(&self, block: &Block, height: u32) {
+               let txdata: Vec<_> = block.txdata.iter().enumerate().collect();
+               self.0.block_connected(&block.header, &txdata, height, &*self.1, &*self.2, &*self.3);
+       }
+
+       fn block_disconnected(&self, header: &BlockHeader, height: u32) {
+               self.0.block_disconnected(header, height, &*self.1, &*self.2, &*self.3);
+       }
 }
 
 const MAX_ALLOC_SIZE: usize = 64*1024;
 
-impl<ChanSigner: ChannelKeys + Readable> Readable for (BlockHash, ChannelMonitor<ChanSigner>) {
-       fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
+impl<'a, Signer: Sign, K: KeysInterface<Signer = Signer>> ReadableArgs<&'a K>
+               for (Option<BlockHash>, ChannelMonitor<Signer>) {
+       fn read<R: ::std::io::Read>(reader: &mut R, keys_manager: &'a K) -> Result<Self, DecodeError> {
                macro_rules! unwrap_obj {
                        ($key: expr) => {
                                match $key {
@@ -2318,7 +2526,8 @@ impl<ChanSigner: ChannelKeys + Readable> Readable for (BlockHash, ChannelMonitor
                let counterparty_payment_script = Readable::read(reader)?;
                let shutdown_script = Readable::read(reader)?;
 
-               let keys = Readable::read(reader)?;
+               let channel_keys_id = Readable::read(reader)?;
+               let holder_revocation_basepoint = Readable::read(reader)?;
                // Technically this can fail and serialize fail a round-trip, but only for serialization of
                // barely-init'd ChannelMonitors that we can't do anything with.
                let outpoint = OutPoint {
@@ -2518,56 +2727,68 @@ impl<ChanSigner: ChannelKeys + Readable> Readable for (BlockHash, ChannelMonitor
                                return Err(DecodeError::InvalidValue);
                        }
                }
-               let onchain_tx_handler = Readable::read(reader)?;
+               let onchain_tx_handler = ReadableArgs::read(reader, keys_manager)?;
 
                let lockdown_from_offchain = Readable::read(reader)?;
                let holder_tx_signed = Readable::read(reader)?;
 
-               Ok((last_block_hash.clone(), ChannelMonitor {
-                       latest_update_id,
-                       commitment_transaction_number_obscure_factor,
+               let mut secp_ctx = Secp256k1::new();
+               secp_ctx.seeded_randomize(&keys_manager.get_secure_random_bytes());
 
-                       destination_script,
-                       broadcasted_holder_revokable_script,
-                       counterparty_payment_script,
-                       shutdown_script,
+               let last_seen_block_hash = if last_block_hash == Default::default() {
+                       None
+               } else {
+                       Some(last_block_hash)
+               };
+
+               Ok((last_seen_block_hash, ChannelMonitor {
+                       inner: Mutex::new(ChannelMonitorImpl {
+                               latest_update_id,
+                               commitment_transaction_number_obscure_factor,
 
-                       keys,
-                       funding_info,
-                       current_counterparty_commitment_txid,
-                       prev_counterparty_commitment_txid,
+                               destination_script,
+                               broadcasted_holder_revokable_script,
+                               counterparty_payment_script,
+                               shutdown_script,
 
-                       counterparty_tx_cache,
-                       funding_redeemscript,
-                       channel_value_satoshis,
-                       their_cur_revocation_points,
+                               channel_keys_id,
+                               holder_revocation_basepoint,
+                               funding_info,
+                               current_counterparty_commitment_txid,
+                               prev_counterparty_commitment_txid,
 
-                       on_holder_tx_csv,
+                               counterparty_tx_cache,
+                               funding_redeemscript,
+                               channel_value_satoshis,
+                               their_cur_revocation_points,
 
-                       commitment_secrets,
-                       counterparty_claimable_outpoints,
-                       counterparty_commitment_txn_on_chain,
-                       counterparty_hash_commitment_number,
+                               on_holder_tx_csv,
 
-                       prev_holder_signed_commitment_tx,
-                       current_holder_commitment_tx,
-                       current_counterparty_commitment_number,
-                       current_holder_commitment_number,
+                               commitment_secrets,
+                               counterparty_claimable_outpoints,
+                               counterparty_commitment_txn_on_chain,
+                               counterparty_hash_commitment_number,
 
-                       payment_preimages,
-                       pending_monitor_events,
-                       pending_events,
+                               prev_holder_signed_commitment_tx,
+                               current_holder_commitment_tx,
+                               current_counterparty_commitment_number,
+                               current_holder_commitment_number,
 
-                       onchain_events_waiting_threshold_conf,
-                       outputs_to_watch,
+                               payment_preimages,
+                               pending_monitor_events,
+                               pending_events,
 
-                       onchain_tx_handler,
+                               onchain_events_waiting_threshold_conf,
+                               outputs_to_watch,
 
-                       lockdown_from_offchain,
-                       holder_tx_signed,
+                               onchain_tx_handler,
 
-                       last_block_hash,
-                       secp_ctx: Secp256k1::new(),
+                               lockdown_from_offchain,
+                               holder_tx_signed,
+
+                               last_block_hash,
+                               secp_ctx,
+                       }),
                }))
        }
 }
@@ -2589,12 +2810,12 @@ mod tests {
        use ln::channelmanager::{PaymentPreimage, PaymentHash};
        use ln::onchaintx::{OnchainTxHandler, InputDescriptors};
        use ln::chan_utils;
-       use ln::chan_utils::{HTLCOutputInCommitment, HolderCommitmentTransaction};
+       use ln::chan_utils::{HTLCOutputInCommitment, ChannelPublicKeys, ChannelTransactionParameters, HolderCommitmentTransaction, CounterpartyChannelTransactionParameters};
        use util::test_utils::{TestLogger, TestBroadcaster, TestFeeEstimator};
        use bitcoin::secp256k1::key::{SecretKey,PublicKey};
        use bitcoin::secp256k1::Secp256k1;
        use std::sync::{Arc, Mutex};
-       use chain::keysinterface::InMemoryChannelKeys;
+       use chain::keysinterface::InMemorySigner;
 
        #[test]
        fn test_prune_preimages() {
@@ -2645,12 +2866,12 @@ mod tests {
                macro_rules! test_preimages_exist {
                        ($preimages_slice: expr, $monitor: expr) => {
                                for preimage in $preimages_slice {
-                                       assert!($monitor.payment_preimages.contains_key(&preimage.1));
+                                       assert!($monitor.inner.lock().unwrap().payment_preimages.contains_key(&preimage.1));
                                }
                        }
                }
 
-               let keys = InMemoryChannelKeys::new(
+               let keys = InMemorySigner::new(
                        &secp_ctx,
                        SecretKey::from_slice(&[41; 32]).unwrap(),
                        SecretKey::from_slice(&[41; 32]).unwrap(),
@@ -2659,23 +2880,42 @@ mod tests {
                        SecretKey::from_slice(&[41; 32]).unwrap(),
                        [41; 32],
                        0,
-                       (0, 0)
+                       [0; 32]
                );
 
+               let counterparty_pubkeys = ChannelPublicKeys {
+                       funding_pubkey: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()),
+                       revocation_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()),
+                       payment_point: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[46; 32]).unwrap()),
+                       delayed_payment_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[47; 32]).unwrap()),
+                       htlc_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[48; 32]).unwrap())
+               };
+               let funding_outpoint = OutPoint { txid: Default::default(), index: u16::max_value() };
+               let channel_parameters = ChannelTransactionParameters {
+                       holder_pubkeys: keys.holder_channel_pubkeys.clone(),
+                       holder_selected_contest_delay: 66,
+                       is_outbound_from_holder: true,
+                       counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
+                               pubkeys: counterparty_pubkeys,
+                               selected_contest_delay: 67,
+                       }),
+                       funding_outpoint: Some(funding_outpoint),
+               };
                // Prune with one old state and a holder commitment tx holding a few overlaps with the
                // old state.
-               let mut monitor = ChannelMonitor::new(keys,
-                       &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0, &Script::new(),
-                       (OutPoint { txid: Txid::from_slice(&[43; 32]).unwrap(), index: 0 }, Script::new()),
-                       &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()),
-                       &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()),
-                       10, Script::new(), 46, 0, HolderCommitmentTransaction::dummy());
-
-               monitor.provide_latest_holder_commitment_tx_info(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..10])).unwrap();
-               monitor.provide_latest_counterparty_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key, &logger);
-               monitor.provide_latest_counterparty_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key, &logger);
-               monitor.provide_latest_counterparty_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key, &logger);
-               monitor.provide_latest_counterparty_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key, &logger);
+               let monitor = ChannelMonitor::new(Secp256k1::new(), keys,
+                                                 &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0, &Script::new(),
+                                                 (OutPoint { txid: Txid::from_slice(&[43; 32]).unwrap(), index: 0 }, Script::new()),
+                                                 &channel_parameters,
+                                                 Script::new(), 46, 0,
+                                                 HolderCommitmentTransaction::dummy());
+
+               monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..10])).unwrap();
+               let dummy_txid = dummy_tx.txid();
+               monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key, &logger);
+               monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key, &logger);
+               monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key, &logger);
+               monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key, &logger);
                for &(ref preimage, ref hash) in preimages.iter() {
                        monitor.provide_payment_preimage(hash, preimage, &broadcaster, &fee_estimator, &logger);
                }
@@ -2684,31 +2924,31 @@ mod tests {
                let mut secret = [0; 32];
                secret[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
                monitor.provide_secret(281474976710655, secret.clone()).unwrap();
-               assert_eq!(monitor.payment_preimages.len(), 15);
+               assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 15);
                test_preimages_exist!(&preimages[0..10], monitor);
                test_preimages_exist!(&preimages[15..20], monitor);
 
                // Now provide a further secret, pruning preimages 15-17
                secret[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
                monitor.provide_secret(281474976710654, secret.clone()).unwrap();
-               assert_eq!(monitor.payment_preimages.len(), 13);
+               assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 13);
                test_preimages_exist!(&preimages[0..10], monitor);
                test_preimages_exist!(&preimages[17..20], monitor);
 
                // Now update holder commitment tx info, pruning only element 18 as we still care about the
                // previous commitment tx's preimages too
-               monitor.provide_latest_holder_commitment_tx_info(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..5])).unwrap();
+               monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..5])).unwrap();
                secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
                monitor.provide_secret(281474976710653, secret.clone()).unwrap();
-               assert_eq!(monitor.payment_preimages.len(), 12);
+               assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 12);
                test_preimages_exist!(&preimages[0..10], monitor);
                test_preimages_exist!(&preimages[18..20], monitor);
 
                // But if we do it again, we'll prune 5-10
-               monitor.provide_latest_holder_commitment_tx_info(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..3])).unwrap();
+               monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..3])).unwrap();
                secret[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
                monitor.provide_secret(281474976710652, secret.clone()).unwrap();
-               assert_eq!(monitor.payment_preimages.len(), 5);
+               assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 5);
                test_preimages_exist!(&preimages[0..5], monitor);
        }
 
@@ -2781,7 +3021,7 @@ mod tests {
                                sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs);
                        }
                }
-               assert_eq!(base_weight + OnchainTxHandler::<InMemoryChannelKeys>::get_witnesses_weight(&inputs_des[..]),  claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_des.len() - sum_actual_sigs));
+               assert_eq!(base_weight + OnchainTxHandler::<InMemorySigner>::get_witnesses_weight(&inputs_des[..]),  claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_des.len() - sum_actual_sigs));
 
                // Claim tx with 1 offered HTLCs, 3 received HTLCs
                claim_tx.input.clear();
@@ -2805,7 +3045,7 @@ mod tests {
                                sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs);
                        }
                }
-               assert_eq!(base_weight + OnchainTxHandler::<InMemoryChannelKeys>::get_witnesses_weight(&inputs_des[..]),  claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_des.len() - sum_actual_sigs));
+               assert_eq!(base_weight + OnchainTxHandler::<InMemorySigner>::get_witnesses_weight(&inputs_des[..]),  claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_des.len() - sum_actual_sigs));
 
                // Justice tx with 1 revoked HTLC-Success tx output
                claim_tx.input.clear();
@@ -2827,7 +3067,7 @@ mod tests {
                                sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs);
                        }
                }
-               assert_eq!(base_weight + OnchainTxHandler::<InMemoryChannelKeys>::get_witnesses_weight(&inputs_des[..]), claim_tx.get_weight() + /* max_length_isg */ (73 * inputs_des.len() - sum_actual_sigs));
+               assert_eq!(base_weight + OnchainTxHandler::<InMemorySigner>::get_witnesses_weight(&inputs_des[..]), claim_tx.get_weight() + /* max_length_isg */ (73 * inputs_des.len() - sum_actual_sigs));
        }
 
        // Further testing is done in the ChannelManager integration tests.
index 5599bfbb9fd763e88c58dd475735ace5a86a0079..89557b43670202f700c38939c3ff5506bb44b63e 100644 (file)
@@ -11,7 +11,7 @@
 //! spendable on-chain outputs which the user owns and is responsible for using just as any other
 //! on-chain output which is theirs.
 
-use bitcoin::blockdata::transaction::{Transaction, TxOut, SigHashType};
+use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType};
 use bitcoin::blockdata::script::{Script, Builder};
 use bitcoin::blockdata::opcodes;
 use bitcoin::network::constants::Network;
@@ -28,17 +28,70 @@ use bitcoin::secp256k1::key::{SecretKey, PublicKey};
 use bitcoin::secp256k1::{Secp256k1, Signature, Signing};
 use bitcoin::secp256k1;
 
-use util::byte_utils;
+use util::{byte_utils, transaction_utils};
 use util::ser::{Writeable, Writer, Readable};
 
 use chain::transaction::OutPoint;
 use ln::chan_utils;
-use ln::chan_utils::{HTLCOutputInCommitment, make_funding_redeemscript, ChannelPublicKeys, HolderCommitmentTransaction, PreCalculatedTxCreationKeys};
+use ln::chan_utils::{HTLCOutputInCommitment, make_funding_redeemscript, ChannelPublicKeys, HolderCommitmentTransaction, ChannelTransactionParameters, CommitmentTransaction};
 use ln::msgs::UnsignedChannelAnnouncement;
 
+use std::collections::HashSet;
 use std::sync::atomic::{AtomicUsize, Ordering};
 use std::io::Error;
-use ln::msgs::DecodeError;
+use ln::msgs::{DecodeError, MAX_VALUE_MSAT};
+
+/// Information about a spendable output to a P2WSH script. See
+/// SpendableOutputDescriptor::DelayedPaymentOutput for more details on how to spend this.
+#[derive(Clone, Debug, PartialEq)]
+pub struct DelayedPaymentOutputDescriptor {
+       /// The outpoint which is spendable
+       pub outpoint: OutPoint,
+       /// Per commitment point to derive delayed_payment_key by key holder
+       pub per_commitment_point: PublicKey,
+       /// The nSequence value which must be set in the spending input to satisfy the OP_CSV in
+       /// the witness_script.
+       pub to_self_delay: u16,
+       /// The output which is referenced by the given outpoint
+       pub output: TxOut,
+       /// The revocation point specific to the commitment transaction which was broadcast. Used to
+       /// derive the witnessScript for this output.
+       pub revocation_pubkey: PublicKey,
+       /// Arbitrary identification information returned by a call to
+       /// `Sign::channel_keys_id()`. This may be useful in re-deriving keys used in
+       /// the channel to spend the output.
+       pub channel_keys_id: [u8; 32],
+       /// The value of the channel which this output originated from, possibly indirectly.
+       pub channel_value_satoshis: u64,
+}
+impl DelayedPaymentOutputDescriptor {
+       /// The maximum length a well-formed witness spending one of these should have.
+       // Calculated as 1 byte length + 73 byte signature, 1 byte empty vec push, 1 byte length plus
+       // redeemscript push length.
+       pub const MAX_WITNESS_LENGTH: usize = 1 + 73 + 1 + chan_utils::REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH + 1;
+}
+
+/// Information about a spendable output to our "payment key". See
+/// SpendableOutputDescriptor::StaticPaymentOutput for more details on how to spend this.
+#[derive(Clone, Debug, PartialEq)]
+pub struct StaticPaymentOutputDescriptor {
+       /// The outpoint which is spendable
+       pub outpoint: OutPoint,
+       /// The output which is referenced by the given outpoint
+       pub output: TxOut,
+       /// Arbitrary identification information returned by a call to
+       /// `Sign::channel_keys_id()`. This may be useful in re-deriving keys used in
+       /// the channel to spend the output.
+       pub channel_keys_id: [u8; 32],
+       /// The value of the channel which this transactions spends.
+       pub channel_value_satoshis: u64,
+}
+impl StaticPaymentOutputDescriptor {
+       /// The maximum length a well-formed witness spending one of these should have.
+       // Calculated as 1 byte legnth + 73 byte signature, 1 byte empty vec push, 1 byte length plus
+       // redeemscript push length.
+       pub const MAX_WITNESS_LENGTH: usize = 1 + 73 + 34;
+}
 
 /// When on-chain outputs are created by rust-lightning (which our counterparty is not able to
 /// claim at any point in the future) an event is generated which you must track and be able to
@@ -47,9 +100,9 @@ use ln::msgs::DecodeError;
 /// that txid/index, and any keys or other information required to sign.
 #[derive(Clone, Debug, PartialEq)]
 pub enum SpendableOutputDescriptor {
-       /// An output to a script which was provided via KeysInterface, thus you should already know
-       /// how to spend it. No keys are provided as rust-lightning was never given any keys - only the
-       /// script_pubkey as it appears in the output.
+       /// An output to a script which was provided via KeysInterface directly, either from
+       /// `get_destination_script()` or `get_shutdown_pubkey()`, thus you should already know how to
+       /// spend it. No secret keys are provided as rust-lightning was never given any key.
        /// These may include outputs from a transaction punishing our counterparty or claiming an HTLC
        /// on-chain using the payment preimage or after it has timed out.
        StaticOutput {
@@ -72,54 +125,29 @@ pub enum SpendableOutputDescriptor {
        ///
        /// To derive the delayed_payment key which is used to sign for this input, you must pass the
        /// holder delayed_payment_base_key (ie the private key which corresponds to the pubkey in
-       /// ChannelKeys::pubkeys().delayed_payment_basepoint) and the provided per_commitment_point to
+       /// Sign::pubkeys().delayed_payment_basepoint) and the provided per_commitment_point to
        /// chan_utils::derive_private_key. The public key can be generated without the secret key
        /// using chan_utils::derive_public_key and only the delayed_payment_basepoint which appears in
-       /// ChannelKeys::pubkeys().
+       /// Sign::pubkeys().
        ///
        /// To derive the revocation_pubkey provided here (which is used in the witness
        /// script generation), you must pass the counterparty revocation_basepoint (which appears in the
-       /// call to ChannelKeys::on_accept) and the provided per_commitment point
+       /// call to Sign::ready_channel) and the provided per_commitment point
        /// to chan_utils::derive_public_revocation_key.
        ///
        /// The witness script which is hashed and included in the output script_pubkey may be
        /// regenerated by passing the revocation_pubkey (derived as above), our delayed_payment pubkey
        /// (derived as above), and the to_self_delay contained here to
        /// chan_utils::get_revokeable_redeemscript.
-       //
-       // TODO: we need to expose utility methods in KeyManager to do all the relevant derivation.
-       DynamicOutputP2WSH {
-               /// The outpoint which is spendable
-               outpoint: OutPoint,
-               /// Per commitment point to derive delayed_payment_key by key holder
-               per_commitment_point: PublicKey,
-               /// The nSequence value which must be set in the spending input to satisfy the OP_CSV in
-               /// the witness_script.
-               to_self_delay: u16,
-               /// The output which is referenced by the given outpoint
-               output: TxOut,
-               /// The channel keys state used to proceed to derivation of signing key. Must
-               /// be pass to KeysInterface::derive_channel_keys.
-               key_derivation_params: (u64, u64),
-               /// The revocation_pubkey used to derive witnessScript
-               revocation_pubkey: PublicKey
-       },
+       DelayedPaymentOutput(DelayedPaymentOutputDescriptor),
        /// An output to a P2WPKH, spendable exclusively by our payment key (ie the private key which
-       /// corresponds to the public key in ChannelKeys::pubkeys().payment_point).
+       /// corresponds to the public key in Sign::pubkeys().payment_point).
        /// The witness in the spending input, is, thus, simply:
        /// <BIP 143 signature> <payment key>
        ///
        /// These are generally the result of our counterparty having broadcast the current state,
        /// allowing us to claim the non-HTLC-encumbered outputs immediately.
-       StaticOutputCounterpartyPayment {
-               /// The outpoint which is spendable
-               outpoint: OutPoint,
-               /// The output which is reference by the given outpoint
-               output: TxOut,
-               /// The channel keys state used to proceed to derivation of signing key. Must
-               /// be pass to KeysInterface::derive_channel_keys.
-               key_derivation_params: (u64, u64),
-       }
+       StaticPaymentOutput(StaticPaymentOutputDescriptor),
 }
 
 impl Writeable for SpendableOutputDescriptor {
@@ -130,22 +158,22 @@ impl Writeable for SpendableOutputDescriptor {
                                outpoint.write(writer)?;
                                output.write(writer)?;
                        },
-                       &SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref per_commitment_point, ref to_self_delay, ref output, ref key_derivation_params, ref revocation_pubkey } => {
+                       &SpendableOutputDescriptor::DelayedPaymentOutput(ref descriptor) => {
                                1u8.write(writer)?;
-                               outpoint.write(writer)?;
-                               per_commitment_point.write(writer)?;
-                               to_self_delay.write(writer)?;
-                               output.write(writer)?;
-                               key_derivation_params.0.write(writer)?;
-                               key_derivation_params.1.write(writer)?;
-                               revocation_pubkey.write(writer)?;
+                               descriptor.outpoint.write(writer)?;
+                               descriptor.per_commitment_point.write(writer)?;
+                               descriptor.to_self_delay.write(writer)?;
+                               descriptor.output.write(writer)?;
+                               descriptor.revocation_pubkey.write(writer)?;
+                               descriptor.channel_keys_id.write(writer)?;
+                               descriptor.channel_value_satoshis.write(writer)?;
                        },
-                       &SpendableOutputDescriptor::StaticOutputCounterpartyPayment { ref outpoint, ref output, ref key_derivation_params } => {
+                       &SpendableOutputDescriptor::StaticPaymentOutput(ref descriptor) => {
                                2u8.write(writer)?;
-                               outpoint.write(writer)?;
-                               output.write(writer)?;
-                               key_derivation_params.0.write(writer)?;
-                               key_derivation_params.1.write(writer)?;
+                               descriptor.outpoint.write(writer)?;
+                               descriptor.output.write(writer)?;
+                               descriptor.channel_keys_id.write(writer)?;
+                               descriptor.channel_value_satoshis.write(writer)?;
                        },
                }
                Ok(())
@@ -159,28 +187,30 @@ impl Readable for SpendableOutputDescriptor {
                                outpoint: Readable::read(reader)?,
                                output: Readable::read(reader)?,
                        }),
-                       1u8 => Ok(SpendableOutputDescriptor::DynamicOutputP2WSH {
+                       1u8 => Ok(SpendableOutputDescriptor::DelayedPaymentOutput(DelayedPaymentOutputDescriptor {
                                outpoint: Readable::read(reader)?,
                                per_commitment_point: Readable::read(reader)?,
                                to_self_delay: Readable::read(reader)?,
                                output: Readable::read(reader)?,
-                               key_derivation_params: (Readable::read(reader)?, Readable::read(reader)?),
                                revocation_pubkey: Readable::read(reader)?,
-                       }),
-                       2u8 => Ok(SpendableOutputDescriptor::StaticOutputCounterpartyPayment {
+                               channel_keys_id: Readable::read(reader)?,
+                               channel_value_satoshis: Readable::read(reader)?,
+                       })),
+                       2u8 => Ok(SpendableOutputDescriptor::StaticPaymentOutput(StaticPaymentOutputDescriptor {
                                outpoint: Readable::read(reader)?,
                                output: Readable::read(reader)?,
-                               key_derivation_params: (Readable::read(reader)?, Readable::read(reader)?),
-                       }),
+                               channel_keys_id: Readable::read(reader)?,
+                               channel_value_satoshis: Readable::read(reader)?,
+                       })),
                        _ => Err(DecodeError::InvalidValue),
                }
        }
 }
 
-/// Set of lightning keys needed to operate a channel as described in BOLT 3.
+/// A trait to sign lightning channel transactions as described in BOLT 3.
 ///
 /// Signing services could be implemented on a hardware wallet. In this case,
-/// the current ChannelKeys would be a front-end on top of a communication
+/// the current Sign would be a front-end on top of a communication
 /// channel connected to your secure device and lightning key material wouldn't
 /// reside on a hot server. Nevertheless, a this deployment would still need
 /// to trust the ChannelManager to avoid loss of funds as this latest component
@@ -194,17 +224,9 @@ impl Readable for SpendableOutputDescriptor {
 /// In any case, ChannelMonitor or fallback watchtowers are always going to be trusted
 /// to act, as liveness and breach reply correctness are always going to be hard requirements
 /// of LN security model, orthogonal of key management issues.
-///
-/// If you're implementing a custom signer, you almost certainly want to implement
-/// Readable/Writable to serialize out a unique reference to this set of keys so
-/// that you can serialize the full ChannelManager object.
-///
-// (TODO: We shouldn't require that, and should have an API to get them at deser time, due mostly
-// to the possibility of reentrancy issues by calling the user's code during our deserialization
-// routine).
-// TODO: We should remove Clone by instead requesting a new ChannelKeys copy when we create
+// TODO: We should remove Clone by instead requesting a new Sign copy when we create
 // ChannelMonitors instead of expecting to clone the one out of the Channel into the monitors.
-pub trait ChannelKeys : Send+Clone {
+pub trait Sign : Send+Clone + Writeable {
        /// Gets the per-commitment point for a specific commitment number
        ///
        /// Note that the commitment number starts at (1 << 48) - 1 and counts backwards.
@@ -217,54 +239,44 @@ pub trait ChannelKeys : Send+Clone {
        /// May be called more than once for the same index.
        ///
        /// Note that the commitment number starts at (1 << 48) - 1 and counts backwards.
-       /// TODO: return a Result so we can signal a validation error
+       // TODO: return a Result so we can signal a validation error
        fn release_commitment_secret(&self, idx: u64) -> [u8; 32];
        /// Gets the holder's channel public keys and basepoints
        fn pubkeys(&self) -> &ChannelPublicKeys;
-       /// Gets arbitrary identifiers describing the set of keys which are provided back to you in
-       /// some SpendableOutputDescriptor types. These should be sufficient to identify this
-       /// ChannelKeys object uniquely and lookup or re-derive its keys.
-       fn key_derivation_params(&self) -> (u64, u64);
+       /// Gets an arbitrary identifier describing the set of keys which are provided back to you in
+       /// some SpendableOutputDescriptor types. This should be sufficient to identify this
+       /// Sign object uniquely and lookup or re-derive its keys.
+       fn channel_keys_id(&self) -> [u8; 32];
 
        /// Create a signature for a counterparty's commitment transaction and associated HTLC transactions.
        ///
        /// Note that if signing fails or is rejected, the channel will be force-closed.
        //
        // TODO: Document the things someone using this interface should enforce before signing.
-       // TODO: Add more input vars to enable better checking (preferably removing commitment_tx and
-       // making the callee generate it via some util function we expose)!
-       fn sign_counterparty_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, feerate_per_kw: u32, commitment_tx: &Transaction, keys: &PreCalculatedTxCreationKeys, htlcs: &[&HTLCOutputInCommitment], secp_ctx: &Secp256k1<T>) -> Result<(Signature, Vec<Signature>), ()>;
-
-       /// Create a signature for a holder's commitment transaction. This will only ever be called with
-       /// the same holder_commitment_tx (or a copy thereof), though there are currently no guarantees
-       /// that it will not be called multiple times.
+       fn sign_counterparty_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, commitment_tx: &CommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<(Signature, Vec<Signature>), ()>;
+
+       /// Create a signatures for a holder's commitment transaction and its claiming HTLC transactions.
+       /// This will only ever be called with a non-revoked commitment_tx.  This will be called with the
+       /// latest commitment_tx when we initiate a force-close.
+       /// This will be called with the previous latest, just to get claiming HTLC signatures, if we are
+       /// reacting to a ChannelMonitor replica that decided to broadcast before it had been updated to
+       /// the latest.
+       /// This may be called multiple times for the same transaction.
+       ///
        /// An external signer implementation should check that the commitment has not been revoked.
+       ///
+       /// May return Err if key derivation fails.  Callers, such as ChannelMonitor, will panic in such a case.
        //
        // TODO: Document the things someone using this interface should enforce before signing.
-       // TODO: Add more input vars to enable better checking (preferably removing commitment_tx and
-       fn sign_holder_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, holder_commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
+       // TODO: Key derivation failure should panic rather than Err
+       fn sign_holder_commitment_and_htlcs<T: secp256k1::Signing + secp256k1::Verification>(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<(Signature, Vec<Signature>), ()>;
 
        /// Same as sign_holder_commitment, but exists only for tests to get access to holder commitment
        /// transactions which will be broadcasted later, after the channel has moved on to a newer
        /// state. Thus, needs its own method as sign_holder_commitment may enforce that we only ever
        /// get called once.
        #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
-       fn unsafe_sign_holder_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, holder_commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
-
-       /// Create a signature for each HTLC transaction spending a holder's commitment transaction.
-       ///
-       /// Unlike sign_holder_commitment, this may be called multiple times with *different*
-       /// holder_commitment_tx values. While this will never be called with a revoked
-       /// holder_commitment_tx, it is possible that it is called with the second-latest
-       /// holder_commitment_tx (only if we haven't yet revoked it) if some watchtower/secondary
-       /// ChannelMonitor decided to broadcast before it had been updated to the latest.
-       ///
-       /// Either an Err should be returned, or a Vec with one entry for each HTLC which exists in
-       /// holder_commitment_tx. For those HTLCs which have transaction_output_index set to None
-       /// (implying they were considered dust at the time the commitment transaction was negotiated),
-       /// a corresponding None should be included in the return value. All other positions in the
-       /// return value must contain a signature.
-       fn sign_holder_commitment_htlc_transactions<T: secp256k1::Signing + secp256k1::Verification>(&self, holder_commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<Vec<Option<Signature>>, ()>;
+       fn unsafe_sign_holder_commitment_and_htlcs<T: secp256k1::Signing + secp256k1::Verification>(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<(Signature, Vec<Signature>), ()>;
 
        /// Create a signature for the given input in a transaction spending an HTLC or commitment
        /// transaction output when our counterparty broadcasts an old state.
@@ -319,57 +331,66 @@ pub trait ChannelKeys : Send+Clone {
        /// protocol.
        fn sign_channel_announcement<T: secp256k1::Signing>(&self, msg: &UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
 
-       /// Set the counterparty channel basepoints and counterparty_selected/holder_selected_contest_delay.
-       /// This is done immediately on incoming channels and as soon as the channel is accepted on outgoing channels.
+       /// Set the counterparty static channel data, including basepoints,
+       /// counterparty_selected/holder_selected_contest_delay and funding outpoint.
+       /// This is done as soon as the funding outpoint is known.  Since these are static channel data,
+       /// they MUST NOT be allowed to change to different values once set.
+       ///
+       /// channel_parameters.is_populated() MUST be true.
        ///
        /// We bind holder_selected_contest_delay late here for API convenience.
        ///
        /// Will be called before any signatures are applied.
-       fn on_accept(&mut self, channel_points: &ChannelPublicKeys, counterparty_selected_contest_delay: u16, holder_selected_contest_delay: u16);
+       fn ready_channel(&mut self, channel_parameters: &ChannelTransactionParameters);
 }
 
 /// A trait to describe an object which can get user secrets and key material.
 pub trait KeysInterface: Send + Sync {
-       /// A type which implements ChannelKeys which will be returned by get_channel_keys.
-       type ChanKeySigner : ChannelKeys;
+       /// A type which implements Sign which will be returned by get_channel_signer.
+       type Signer : Sign;
 
-       /// Get node secret key (aka node_id or network_key)
+       /// Get node secret key (aka node_id or network_key).
+       ///
+       /// This method must return the same value each time it is called.
        fn get_node_secret(&self) -> SecretKey;
-       /// Get destination redeemScript to encumber static protocol exit points.
+       /// Get a script pubkey which we send funds to when claiming on-chain contestable outputs.
+       ///
+       /// This method should return a different value each time it is called, to avoid linking
+       /// on-chain funds across channels as controlled to the same user.
        fn get_destination_script(&self) -> Script;
-       /// Get shutdown_pubkey to use as PublicKey at channel closure
+       /// Get a public key which we will send funds to (in the form of a P2WPKH output) when closing
+       /// a channel.
+       ///
+       /// This method should return a different value each time it is called, to avoid linking
+       /// on-chain funds across channels as controlled to the same user.
        fn get_shutdown_pubkey(&self) -> PublicKey;
-       /// Get a new set of ChannelKeys for per-channel secrets. These MUST be unique even if you
+       /// Get a new set of Sign for per-channel secrets. These MUST be unique even if you
        /// restarted with some stale data!
-       fn get_channel_keys(&self, inbound: bool, channel_value_satoshis: u64) -> Self::ChanKeySigner;
+       ///
+       /// This method must return a different value each time it is called.
+       fn get_channel_signer(&self, inbound: bool, channel_value_satoshis: u64) -> Self::Signer;
        /// Gets a unique, cryptographically-secure, random 32 byte value. This is used for encrypting
        /// onion packets and for temporary channel IDs. There is no requirement that these be
        /// persisted anywhere, though they must be unique across restarts.
+       ///
+       /// This method must return a different value each time it is called.
        fn get_secure_random_bytes(&self) -> [u8; 32];
-}
 
-#[derive(Clone)]
-/// Holds late-bound channel data.
-/// This data is available after the channel is known to be accepted, either
-/// when receiving an open_channel for an inbound channel or when
-/// receiving accept_channel for an outbound channel.
-struct AcceptedChannelData {
-       /// Counterparty public keys and base points
-       counterparty_channel_pubkeys: ChannelPublicKeys,
-       /// The contest_delay value specified by our counterparty and applied on holder-broadcastable
-       /// transactions, ie the amount of time that we have to wait to recover our funds if we
-       /// broadcast a transaction. You'll likely want to pass this to the
-       /// ln::chan_utils::build*_transaction functions when signing holder's transactions.
-       counterparty_selected_contest_delay: u16,
-       /// The contest_delay value specified by us and applied on transactions broadcastable
-       /// by our counterparty, ie the amount of time that they have to wait to recover their funds
-       /// if they broadcast a transaction.
-       holder_selected_contest_delay: u16,
+       /// Reads a `Signer` for this `KeysInterface` from the given input stream.
+       /// This is only called during deserialization of other objects which contain
+       /// `Sign`-implementing objects (ie `ChannelMonitor`s and `ChannelManager`s).
+       /// The bytes are exactly those which `<Self::Signer as Writeable>::write()` writes, and
+       /// contain no versioning scheme. You may wish to include your own version prefix and ensure
+       /// you've read all of the provided bytes to ensure no corruption occurred.
+       fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::Signer, DecodeError>;
 }
 
 #[derive(Clone)]
-/// A simple implementation of ChannelKeys that just keeps the private keys in memory.
-pub struct InMemoryChannelKeys {
+/// A simple implementation of Sign that just keeps the private keys in memory.
+///
+/// This implementation performs no policy checks and is insufficient by itself as
+/// a secure external signer.
+pub struct InMemorySigner {
        /// Private key of anchor tx
        pub funding_key: SecretKey,
        /// Holder secret key for blinded revocation pubkey
@@ -385,15 +406,15 @@ pub struct InMemoryChannelKeys {
        /// Holder public keys and basepoints
        pub(crate) holder_channel_pubkeys: ChannelPublicKeys,
        /// Counterparty public keys and counterparty/holder selected_contest_delay, populated on channel acceptance
-       accepted_channel_data: Option<AcceptedChannelData>,
+       channel_parameters: Option<ChannelTransactionParameters>,
        /// The total value of this channel
        channel_value_satoshis: u64,
        /// Key derivation parameters
-       key_derivation_params: (u64, u64),
+       channel_keys_id: [u8; 32],
 }
 
-impl InMemoryChannelKeys {
-       /// Create a new InMemoryChannelKeys
+impl InMemorySigner {
+       /// Create a new InMemorySigner
        pub fn new<C: Signing>(
                secp_ctx: &Secp256k1<C>,
                funding_key: SecretKey,
@@ -403,12 +424,12 @@ impl InMemoryChannelKeys {
                htlc_base_key: SecretKey,
                commitment_seed: [u8; 32],
                channel_value_satoshis: u64,
-               key_derivation_params: (u64, u64)) -> InMemoryChannelKeys {
+               channel_keys_id: [u8; 32]) -> InMemorySigner {
                let holder_channel_pubkeys =
-                       InMemoryChannelKeys::make_holder_keys(secp_ctx, &funding_key, &revocation_base_key,
+                       InMemorySigner::make_holder_keys(secp_ctx, &funding_key, &revocation_base_key,
                                                             &payment_key, &delayed_payment_base_key,
                                                             &htlc_base_key);
-               InMemoryChannelKeys {
+               InMemorySigner {
                        funding_key,
                        revocation_base_key,
                        payment_key,
@@ -417,8 +438,8 @@ impl InMemoryChannelKeys {
                        commitment_seed,
                        channel_value_satoshis,
                        holder_channel_pubkeys,
-                       accepted_channel_data: None,
-                       key_derivation_params,
+                       channel_parameters: None,
+                       channel_keys_id,
                }
        }
 
@@ -439,24 +460,96 @@ impl InMemoryChannelKeys {
        }
 
        /// Counterparty pubkeys.
-       /// Will panic if on_accept wasn't called.
-       pub fn counterparty_pubkeys(&self) -> &ChannelPublicKeys { &self.accepted_channel_data.as_ref().unwrap().counterparty_channel_pubkeys }
+       /// Will panic if ready_channel wasn't called.
+       pub fn counterparty_pubkeys(&self) -> &ChannelPublicKeys { &self.get_channel_parameters().counterparty_parameters.as_ref().unwrap().pubkeys }
 
        /// The contest_delay value specified by our counterparty and applied on holder-broadcastable
        /// transactions, ie the amount of time that we have to wait to recover our funds if we
-       /// broadcast a transaction. You'll likely want to pass this to the
-       /// ln::chan_utils::build*_transaction functions when signing holder's transactions.
-       /// Will panic if on_accept wasn't called.
-       pub fn counterparty_selected_contest_delay(&self) -> u16 { self.accepted_channel_data.as_ref().unwrap().counterparty_selected_contest_delay }
+       /// broadcast a transaction.
+       /// Will panic if ready_channel wasn't called.
+       pub fn counterparty_selected_contest_delay(&self) -> u16 { self.get_channel_parameters().counterparty_parameters.as_ref().unwrap().selected_contest_delay }
 
        /// The contest_delay value specified by us and applied on transactions broadcastable
        /// by our counterparty, ie the amount of time that they have to wait to recover their funds
        /// if they broadcast a transaction.
-       /// Will panic if on_accept wasn't called.
-       pub fn holder_selected_contest_delay(&self) -> u16 { self.accepted_channel_data.as_ref().unwrap().holder_selected_contest_delay }
+       /// Will panic if ready_channel wasn't called.
+       pub fn holder_selected_contest_delay(&self) -> u16 { self.get_channel_parameters().holder_selected_contest_delay }
+
+       /// Whether the holder is the initiator
+       /// Will panic if ready_channel wasn't called.
+       pub fn is_outbound(&self) -> bool { self.get_channel_parameters().is_outbound_from_holder }
+
+       /// Funding outpoint
+       /// Will panic if ready_channel wasn't called.
+       pub fn funding_outpoint(&self) -> &OutPoint { self.get_channel_parameters().funding_outpoint.as_ref().unwrap() }
+
+       /// Obtain a ChannelTransactionParameters for this channel, to be used when verifying or
+       /// building transactions.
+       ///
+       /// Will panic if ready_channel wasn't called.
+       pub fn get_channel_parameters(&self) -> &ChannelTransactionParameters {
+               self.channel_parameters.as_ref().unwrap()
+       }
+
+       /// Sign the single input of spend_tx at index `input_idx` which spends the output
+       /// described by descriptor, returning the witness stack for the input.
+       ///
+       /// Returns an Err if the input at input_idx does not exist, has a non-empty script_sig,
+       /// or is not spending the outpoint described by `descriptor.outpoint`.
+       pub fn sign_counterparty_payment_input<C: Signing>(&self, spend_tx: &Transaction, input_idx: usize, descriptor: &StaticPaymentOutputDescriptor, secp_ctx: &Secp256k1<C>) -> Result<Vec<Vec<u8>>, ()> {
+               // TODO: We really should be taking the SigHashCache as a parameter here instead of
+               // spend_tx, but ideally the SigHashCache would expose the transaction's inputs read-only
+               // so that we can check them. This requires upstream rust-bitcoin changes (as well as
+               // bindings updates to support SigHashCache objects).
+               if spend_tx.input.len() <= input_idx { return Err(()); }
+               if !spend_tx.input[input_idx].script_sig.is_empty() { return Err(()); }
+               if spend_tx.input[input_idx].previous_output != descriptor.outpoint.into_bitcoin_outpoint() { return Err(()); }
+
+               let remotepubkey = self.pubkeys().payment_point;
+               let witness_script = bitcoin::Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: remotepubkey}, Network::Testnet).script_pubkey();
+               let sighash = hash_to_message!(&bip143::SigHashCache::new(spend_tx).signature_hash(input_idx, &witness_script, descriptor.output.value, SigHashType::All)[..]);
+               let remotesig = secp_ctx.sign(&sighash, &self.payment_key);
+
+               let mut witness = Vec::with_capacity(2);
+               witness.push(remotesig.serialize_der().to_vec());
+               witness[0].push(SigHashType::All as u8);
+               witness.push(remotepubkey.serialize().to_vec());
+               Ok(witness)
+       }
+
+       /// Sign the single input of spend_tx at index `input_idx` which spends the output
+       /// described by descriptor, returning the witness stack for the input.
+       ///
+       /// Returns an Err if the input at input_idx does not exist, has a non-empty script_sig,
+       /// is not spending the outpoint described by `descriptor.outpoint`, or does not have a
+       /// sequence set to `descriptor.to_self_delay`.
+       pub fn sign_dynamic_p2wsh_input<C: Signing>(&self, spend_tx: &Transaction, input_idx: usize, descriptor: &DelayedPaymentOutputDescriptor, secp_ctx: &Secp256k1<C>) -> Result<Vec<Vec<u8>>, ()> {
+               // TODO: We really should be taking the SigHashCache as a parameter here instead of
+               // spend_tx, but ideally the SigHashCache would expose the transaction's inputs read-only
+               // so that we can check them. This requires upstream rust-bitcoin changes (as well as
+               // bindings updates to support SigHashCache objects).
+               if spend_tx.input.len() <= input_idx { return Err(()); }
+               if !spend_tx.input[input_idx].script_sig.is_empty() { return Err(()); }
+               if spend_tx.input[input_idx].previous_output != descriptor.outpoint.into_bitcoin_outpoint() { return Err(()); }
+               if spend_tx.input[input_idx].sequence != descriptor.to_self_delay as u32 { return Err(()); }
+
+               let delayed_payment_key = chan_utils::derive_private_key(&secp_ctx, &descriptor.per_commitment_point, &self.delayed_payment_base_key)
+                       .expect("We constructed the payment_base_key, so we can only fail here if the RNG is busted.");
+               let delayed_payment_pubkey = PublicKey::from_secret_key(&secp_ctx, &delayed_payment_key);
+               let witness_script = chan_utils::get_revokeable_redeemscript(&descriptor.revocation_pubkey, descriptor.to_self_delay, &delayed_payment_pubkey);
+               let sighash = hash_to_message!(&bip143::SigHashCache::new(spend_tx).signature_hash(input_idx, &witness_script, descriptor.output.value, SigHashType::All)[..]);
+               let local_delayedsig = secp_ctx.sign(&sighash, &delayed_payment_key);
+
+               let mut witness = Vec::with_capacity(3);
+               witness.push(local_delayedsig.serialize_der().to_vec());
+               witness[0].push(SigHashType::All as u8);
+               witness.push(vec!()); //MINIMALIF
+               witness.push(witness_script.clone().into_bytes());
+               Ok(witness)
+       }
 }
 
-impl ChannelKeys for InMemoryChannelKeys {
+impl Sign for InMemorySigner {
        fn get_per_commitment_point<T: secp256k1::Signing + secp256k1::Verification>(&self, idx: u64, secp_ctx: &Secp256k1<T>) -> PublicKey {
                let commitment_secret = SecretKey::from_slice(&chan_utils::build_commitment_secret(&self.commitment_seed, idx)).unwrap();
                PublicKey::from_secret_key(secp_ctx, &commitment_secret)
@@ -467,58 +560,53 @@ impl ChannelKeys for InMemoryChannelKeys {
        }
 
        fn pubkeys(&self) -> &ChannelPublicKeys { &self.holder_channel_pubkeys }
-       fn key_derivation_params(&self) -> (u64, u64) { self.key_derivation_params }
+       fn channel_keys_id(&self) -> [u8; 32] { self.channel_keys_id }
 
-       fn sign_counterparty_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, feerate_per_kw: u32, commitment_tx: &Transaction, pre_keys: &PreCalculatedTxCreationKeys, htlcs: &[&HTLCOutputInCommitment], secp_ctx: &Secp256k1<T>) -> Result<(Signature, Vec<Signature>), ()> {
-               if commitment_tx.input.len() != 1 { return Err(()); }
-               let keys = pre_keys.trust_key_derivation();
+       fn sign_counterparty_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, commitment_tx: &CommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<(Signature, Vec<Signature>), ()> {
+               let trusted_tx = commitment_tx.trust();
+               let keys = trusted_tx.keys();
 
                let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
-               let accepted_data = self.accepted_channel_data.as_ref().expect("must accept before signing");
-               let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &accepted_data.counterparty_channel_pubkeys.funding_pubkey);
-
-               let commitment_sighash = hash_to_message!(&bip143::SigHashCache::new(commitment_tx).signature_hash(0, &channel_funding_redeemscript, self.channel_value_satoshis, SigHashType::All)[..]);
-               let commitment_sig = secp_ctx.sign(&commitment_sighash, &self.funding_key);
-
-               let commitment_txid = commitment_tx.txid();
-
-               let mut htlc_sigs = Vec::with_capacity(htlcs.len());
-               for ref htlc in htlcs {
-                       if let Some(_) = htlc.transaction_output_index {
-                               let htlc_tx = chan_utils::build_htlc_transaction(&commitment_txid, feerate_per_kw, accepted_data.holder_selected_contest_delay, htlc, &keys.broadcaster_delayed_payment_key, &keys.revocation_key);
-                               let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, &keys);
-                               let htlc_sighash = hash_to_message!(&bip143::SigHashCache::new(&htlc_tx).signature_hash(0, &htlc_redeemscript, htlc.amount_msat / 1000, SigHashType::All)[..]);
-                               let our_htlc_key = match chan_utils::derive_private_key(&secp_ctx, &keys.per_commitment_point, &self.htlc_base_key) {
-                                       Ok(s) => s,
-                                       Err(_) => return Err(()),
-                               };
-                               htlc_sigs.push(secp_ctx.sign(&htlc_sighash, &our_htlc_key));
-                       }
+               let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &self.counterparty_pubkeys().funding_pubkey);
+
+               let built_tx = trusted_tx.built_transaction();
+               let commitment_sig = built_tx.sign(&self.funding_key, &channel_funding_redeemscript, self.channel_value_satoshis, secp_ctx);
+               let commitment_txid = built_tx.txid;
+
+               let mut htlc_sigs = Vec::with_capacity(commitment_tx.htlcs().len());
+               for htlc in commitment_tx.htlcs() {
+                       let htlc_tx = chan_utils::build_htlc_transaction(&commitment_txid, commitment_tx.feerate_per_kw(), self.holder_selected_contest_delay(), htlc, &keys.broadcaster_delayed_payment_key, &keys.revocation_key);
+                       let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, &keys);
+                       let htlc_sighash = hash_to_message!(&bip143::SigHashCache::new(&htlc_tx).signature_hash(0, &htlc_redeemscript, htlc.amount_msat / 1000, SigHashType::All)[..]);
+                       let holder_htlc_key = match chan_utils::derive_private_key(&secp_ctx, &keys.per_commitment_point, &self.htlc_base_key) {
+                               Ok(s) => s,
+                               Err(_) => return Err(()),
+                       };
+                       htlc_sigs.push(secp_ctx.sign(&htlc_sighash, &holder_htlc_key));
                }
 
                Ok((commitment_sig, htlc_sigs))
        }
 
-       fn sign_holder_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, holder_commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
+       fn sign_holder_commitment_and_htlcs<T: secp256k1::Signing + secp256k1::Verification>(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<(Signature, Vec<Signature>), ()> {
                let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
-               let counterparty_channel_data = self.accepted_channel_data.as_ref().expect("must accept before signing");
-               let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &counterparty_channel_data.counterparty_channel_pubkeys.funding_pubkey);
-
-               Ok(holder_commitment_tx.get_holder_sig(&self.funding_key, &channel_funding_redeemscript, self.channel_value_satoshis, secp_ctx))
+               let funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &self.counterparty_pubkeys().funding_pubkey);
+               let trusted_tx = commitment_tx.trust();
+               let sig = trusted_tx.built_transaction().sign(&self.funding_key, &funding_redeemscript, self.channel_value_satoshis, secp_ctx);
+               let channel_parameters = self.get_channel_parameters();
+               let htlc_sigs = trusted_tx.get_htlc_sigs(&self.htlc_base_key, &channel_parameters.as_holder_broadcastable(), secp_ctx)?;
+               Ok((sig, htlc_sigs))
        }
 
        #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
-       fn unsafe_sign_holder_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, holder_commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
+       fn unsafe_sign_holder_commitment_and_htlcs<T: secp256k1::Signing + secp256k1::Verification>(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<(Signature, Vec<Signature>), ()> {
                let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
-               let counterparty_channel_pubkeys = &self.accepted_channel_data.as_ref().expect("must accept before signing").counterparty_channel_pubkeys;
-               let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &counterparty_channel_pubkeys.funding_pubkey);
-
-               Ok(holder_commitment_tx.get_holder_sig(&self.funding_key, &channel_funding_redeemscript, self.channel_value_satoshis, secp_ctx))
-       }
-
-       fn sign_holder_commitment_htlc_transactions<T: secp256k1::Signing + secp256k1::Verification>(&self, holder_commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<Vec<Option<Signature>>, ()> {
-               let counterparty_selected_contest_delay = self.accepted_channel_data.as_ref().unwrap().counterparty_selected_contest_delay;
-               holder_commitment_tx.get_htlc_sigs(&self.htlc_base_key, counterparty_selected_contest_delay, secp_ctx)
+               let funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &self.counterparty_pubkeys().funding_pubkey);
+               let trusted_tx = commitment_tx.trust();
+               let sig = trusted_tx.built_transaction().sign(&self.funding_key, &funding_redeemscript, self.channel_value_satoshis, secp_ctx);
+               let channel_parameters = self.get_channel_parameters();
+               let htlc_sigs = trusted_tx.get_htlc_sigs(&self.htlc_base_key, &channel_parameters.as_holder_broadcastable(), secp_ctx)?;
+               Ok((sig, htlc_sigs))
        }
 
        fn sign_justice_transaction<T: secp256k1::Signing + secp256k1::Verification>(&self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey, htlc: &Option<HTLCOutputInCommitment>, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
@@ -575,8 +663,7 @@ impl ChannelKeys for InMemoryChannelKeys {
                if closing_tx.output.len() > 2 { return Err(()); }
 
                let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
-               let counterparty_channel_data = self.accepted_channel_data.as_ref().expect("must accept before signing");
-               let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &counterparty_channel_data.counterparty_channel_pubkeys.funding_pubkey);
+               let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &self.counterparty_pubkeys().funding_pubkey);
 
                let sighash = hash_to_message!(&bip143::SigHashCache::new(closing_tx)
                        .signature_hash(0, &channel_funding_redeemscript, self.channel_value_satoshis, SigHashType::All)[..]);
@@ -588,20 +675,14 @@ impl ChannelKeys for InMemoryChannelKeys {
                Ok(secp_ctx.sign(&msghash, &self.funding_key))
        }
 
-       fn on_accept(&mut self, channel_pubkeys: &ChannelPublicKeys, counterparty_selected_contest_delay: u16, holder_selected_contest_delay: u16) {
-               assert!(self.accepted_channel_data.is_none(), "Already accepted");
-               self.accepted_channel_data = Some(AcceptedChannelData {
-                       counterparty_channel_pubkeys: channel_pubkeys.clone(),
-                       counterparty_selected_contest_delay,
-                       holder_selected_contest_delay,
-               });
+       fn ready_channel(&mut self, channel_parameters: &ChannelTransactionParameters) {
+               assert!(self.channel_parameters.is_none(), "Acceptance already noted");
+               assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
+               self.channel_parameters = Some(channel_parameters.clone());
        }
 }
 
-impl_writeable!(AcceptedChannelData, 0,
- { counterparty_channel_pubkeys, counterparty_selected_contest_delay, holder_selected_contest_delay });
-
-impl Writeable for InMemoryChannelKeys {
+impl Writeable for InMemorySigner {
        fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
                self.funding_key.write(writer)?;
                self.revocation_base_key.write(writer)?;
@@ -609,16 +690,15 @@ impl Writeable for InMemoryChannelKeys {
                self.delayed_payment_base_key.write(writer)?;
                self.htlc_base_key.write(writer)?;
                self.commitment_seed.write(writer)?;
-               self.accepted_channel_data.write(writer)?;
+               self.channel_parameters.write(writer)?;
                self.channel_value_satoshis.write(writer)?;
-               self.key_derivation_params.0.write(writer)?;
-               self.key_derivation_params.1.write(writer)?;
+               self.channel_keys_id.write(writer)?;
 
                Ok(())
        }
 }
 
-impl Readable for InMemoryChannelKeys {
+impl Readable for InMemorySigner {
        fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
                let funding_key = Readable::read(reader)?;
                let revocation_base_key = Readable::read(reader)?;
@@ -630,13 +710,12 @@ impl Readable for InMemoryChannelKeys {
                let channel_value_satoshis = Readable::read(reader)?;
                let secp_ctx = Secp256k1::signing_only();
                let holder_channel_pubkeys =
-                       InMemoryChannelKeys::make_holder_keys(&secp_ctx, &funding_key, &revocation_base_key,
+                       InMemorySigner::make_holder_keys(&secp_ctx, &funding_key, &revocation_base_key,
                                                             &payment_key, &delayed_payment_base_key,
                                                             &htlc_base_key);
-               let params_1 = Readable::read(reader)?;
-               let params_2 = Readable::read(reader)?;
+               let keys_id = Readable::read(reader)?;
 
-               Ok(InMemoryChannelKeys {
+               Ok(InMemorySigner {
                        funding_key,
                        revocation_base_key,
                        payment_key,
@@ -645,8 +724,8 @@ impl Readable for InMemoryChannelKeys {
                        commitment_seed,
                        channel_value_satoshis,
                        holder_channel_pubkeys,
-                       accepted_channel_data: counterparty_channel_data,
-                       key_derivation_params: (params_1, params_2),
+                       channel_parameters: counterparty_channel_data,
+                       channel_keys_id: keys_id,
                })
        }
 }
@@ -665,8 +744,10 @@ pub struct KeysManager {
        shutdown_pubkey: PublicKey,
        channel_master_key: ExtendedPrivKey,
        channel_child_index: AtomicUsize,
+
        rand_bytes_master_key: ExtendedPrivKey,
        rand_bytes_child_index: AtomicUsize,
+       rand_bytes_unique_start: Sha256State,
 
        seed: [u8; 32],
        starting_time_secs: u64,
@@ -693,9 +774,10 @@ impl KeysManager {
        /// Note that until the 0.1 release there is no guarantee of backward compatibility between
        /// versions. Once the library is more fully supported, the docs will be updated to include a
        /// detailed description of the guarantee.
-       pub fn new(seed: &[u8; 32], network: Network, starting_time_secs: u64, starting_time_nanos: u32) -> Self {
+       pub fn new(seed: &[u8; 32], starting_time_secs: u64, starting_time_nanos: u32) -> Self {
                let secp_ctx = Secp256k1::signing_only();
-               match ExtendedPrivKey::new_master(network.clone(), seed) {
+               // Note that when we aren't serializing the key, network doesn't matter
+               match ExtendedPrivKey::new_master(Network::Testnet, seed) {
                        Ok(master_key) => {
                                let node_secret = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(0).unwrap()).expect("Your RNG is busted").private_key.key;
                                let destination_script = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(1).unwrap()) {
@@ -714,47 +796,52 @@ impl KeysManager {
                                let channel_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(3).unwrap()).expect("Your RNG is busted");
                                let rand_bytes_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(4).unwrap()).expect("Your RNG is busted");
 
-                               KeysManager {
+                               let mut rand_bytes_unique_start = Sha256::engine();
+                               rand_bytes_unique_start.input(&byte_utils::be64_to_array(starting_time_secs));
+                               rand_bytes_unique_start.input(&byte_utils::be32_to_array(starting_time_nanos));
+                               rand_bytes_unique_start.input(seed);
+
+                               let mut res = KeysManager {
                                        secp_ctx,
                                        node_secret,
+
                                        destination_script,
                                        shutdown_pubkey,
+
                                        channel_master_key,
                                        channel_child_index: AtomicUsize::new(0),
+
                                        rand_bytes_master_key,
                                        rand_bytes_child_index: AtomicUsize::new(0),
+                                       rand_bytes_unique_start,
 
                                        seed: *seed,
                                        starting_time_secs,
                                        starting_time_nanos,
-                               }
+                               };
+                               let secp_seed = res.get_secure_random_bytes();
+                               res.secp_ctx.seeded_randomize(&secp_seed);
+                               res
                        },
                        Err(_) => panic!("Your rng is busted"),
                }
        }
-       fn derive_unique_start(&self) -> Sha256State {
-               let mut unique_start = Sha256::engine();
-               unique_start.input(&byte_utils::be64_to_array(self.starting_time_secs));
-               unique_start.input(&byte_utils::be32_to_array(self.starting_time_nanos));
-               unique_start.input(&self.seed);
-               unique_start
-       }
-       /// Derive an old set of ChannelKeys for per-channel secrets based on a key derivation
-       /// parameters.
+       /// Derive an old Sign containing per-channel secrets based on a key derivation parameters.
+       ///
        /// Key derivation parameters are accessible through a per-channel secrets
-       /// ChannelKeys::key_derivation_params and is provided inside DynamicOuputP2WSH in case of
+       /// Sign::channel_keys_id and is provided inside DynamicOuputP2WSH in case of
        /// onchain output detection for which a corresponding delayed_payment_key must be derived.
-       pub fn derive_channel_keys(&self, channel_value_satoshis: u64, params_1: u64, params_2: u64) -> InMemoryChannelKeys {
-               let chan_id = ((params_1 & 0xFFFF_FFFF_0000_0000) >> 32) as u32;
+       pub fn derive_channel_keys(&self, channel_value_satoshis: u64, params: &[u8; 32]) -> InMemorySigner {
+               let chan_id = byte_utils::slice_to_be64(&params[0..8]);
+               assert!(chan_id <= std::u32::MAX as u64); // Otherwise the params field wasn't created by us
                let mut unique_start = Sha256::engine();
-               unique_start.input(&byte_utils::be64_to_array(params_2));
-               unique_start.input(&byte_utils::be32_to_array(params_1 as u32));
+               unique_start.input(params);
                unique_start.input(&self.seed);
 
                // We only seriously intend to rely on the channel_master_key for true secure
                // entropy, everything else just ensures uniqueness. We rely on the unique_start (ie
                // starting_time provided in the constructor) to be unique.
-               let child_privkey = self.channel_master_key.ckd_priv(&self.secp_ctx, ChildNumber::from_hardened_idx(chan_id).expect("key space exhausted")).expect("Your RNG is busted");
+               let child_privkey = self.channel_master_key.ckd_priv(&self.secp_ctx, ChildNumber::from_hardened_idx(chan_id as u32).expect("key space exhausted")).expect("Your RNG is busted");
                unique_start.input(&child_privkey.private_key.key[..]);
 
                let seed = Sha256::from_engine(unique_start).into_inner();
@@ -780,7 +867,7 @@ impl KeysManager {
                let delayed_payment_base_key = key_step!(b"delayed payment base key", payment_key);
                let htlc_base_key = key_step!(b"HTLC base key", delayed_payment_base_key);
 
-               InMemoryChannelKeys::new(
+               InMemorySigner::new(
                        &self.secp_ctx,
                        funding_key,
                        revocation_base_key,
@@ -789,13 +876,130 @@ impl KeysManager {
                        htlc_base_key,
                        commitment_seed,
                        channel_value_satoshis,
-                       (params_1, params_2),
+                       params.clone()
                )
        }
+
+       /// Creates a Transaction which spends the given descriptors to the given outputs, plus an
+       /// output to the given change destination (if sufficient change value remains). The
+       /// transaction will have a feerate, at least, of the given value.
+       ///
+       /// Returns `Err(())` if the output value is greater than the input value minus required fee or
+       /// if a descriptor was duplicated.
+       ///
+       /// We do not enforce that outputs meet the dust limit or that any output scripts are standard.
+       ///
+       /// May panic if the `SpendableOutputDescriptor`s were not generated by Channels which used
+       /// this KeysManager or one of the `InMemorySigner` created by this KeysManager.
+       pub fn spend_spendable_outputs<C: Signing>(&self, descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>, change_destination_script: Script, feerate_sat_per_1000_weight: u32, secp_ctx: &Secp256k1<C>) -> Result<Transaction, ()> {
+               let mut input = Vec::new();
+               let mut input_value = 0;
+               let mut witness_weight = 0;
+               let mut output_set = HashSet::with_capacity(descriptors.len());
+               for outp in descriptors {
+                       match outp {
+                               SpendableOutputDescriptor::StaticPaymentOutput(descriptor) => {
+                                       input.push(TxIn {
+                                               previous_output: descriptor.outpoint.into_bitcoin_outpoint(),
+                                               script_sig: Script::new(),
+                                               sequence: 0,
+                                               witness: Vec::new(),
+                                       });
+                                       witness_weight += StaticPaymentOutputDescriptor::MAX_WITNESS_LENGTH;
+                                       input_value += descriptor.output.value;
+                                       if !output_set.insert(descriptor.outpoint) { return Err(()); }
+                               },
+                               SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) => {
+                                       input.push(TxIn {
+                                               previous_output: descriptor.outpoint.into_bitcoin_outpoint(),
+                                               script_sig: Script::new(),
+                                               sequence: descriptor.to_self_delay as u32,
+                                               witness: Vec::new(),
+                                       });
+                                       witness_weight += DelayedPaymentOutputDescriptor::MAX_WITNESS_LENGTH;
+                                       input_value += descriptor.output.value;
+                                       if !output_set.insert(descriptor.outpoint) { return Err(()); }
+                               },
+                               SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
+                                       input.push(TxIn {
+                                               previous_output: outpoint.into_bitcoin_outpoint(),
+                                               script_sig: Script::new(),
+                                               sequence: 0,
+                                               witness: Vec::new(),
+                                       });
+                                       witness_weight += 1 + 73 + 34;
+                                       input_value += output.value;
+                                       if !output_set.insert(*outpoint) { return Err(()); }
+                               }
+                       }
+                       if input_value > MAX_VALUE_MSAT / 1000 { return Err(()); }
+               }
+               let mut spend_tx = Transaction {
+                       version: 2,
+                       lock_time: 0,
+                       input,
+                       output: outputs,
+               };
+               transaction_utils::maybe_add_change_output(&mut spend_tx, input_value, witness_weight, feerate_sat_per_1000_weight, change_destination_script)?;
+
+               let mut keys_cache: Option<(InMemorySigner, [u8; 32])> = None;
+               let mut input_idx = 0;
+               for outp in descriptors {
+                       match outp {
+                               SpendableOutputDescriptor::StaticPaymentOutput(descriptor) => {
+                                       if keys_cache.is_none() || keys_cache.as_ref().unwrap().1 != descriptor.channel_keys_id {
+                                               keys_cache = Some((
+                                                       self.derive_channel_keys(descriptor.channel_value_satoshis, &descriptor.channel_keys_id),
+                                                       descriptor.channel_keys_id));
+                                       }
+                                       spend_tx.input[input_idx].witness = keys_cache.as_ref().unwrap().0.sign_counterparty_payment_input(&spend_tx, input_idx, &descriptor, &secp_ctx).unwrap();
+                               },
+                               SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) => {
+                                       if keys_cache.is_none() || keys_cache.as_ref().unwrap().1 != descriptor.channel_keys_id {
+                                               keys_cache = Some((
+                                                       self.derive_channel_keys(descriptor.channel_value_satoshis, &descriptor.channel_keys_id),
+                                                       descriptor.channel_keys_id));
+                                       }
+                                       spend_tx.input[input_idx].witness = keys_cache.as_ref().unwrap().0.sign_dynamic_p2wsh_input(&spend_tx, input_idx, &descriptor, &secp_ctx).unwrap();
+                               },
+                               SpendableOutputDescriptor::StaticOutput { ref output, .. } => {
+                                       let derivation_idx = if output.script_pubkey == self.destination_script {
+                                               1
+                                       } else {
+                                               2
+                                       };
+                                       let secret = {
+                                               // Note that when we aren't serializing the key, network doesn't matter
+                                               match ExtendedPrivKey::new_master(Network::Testnet, &self.seed) {
+                                                       Ok(master_key) => {
+                                                               match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(derivation_idx).expect("key space exhausted")) {
+                                                                       Ok(key) => key,
+                                                                       Err(_) => panic!("Your RNG is busted"),
+                                                               }
+                                                       }
+                                                       Err(_) => panic!("Your rng is busted"),
+                                               }
+                                       };
+                                       let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
+                                       if derivation_idx == 2 {
+                                               assert_eq!(pubkey.key, self.shutdown_pubkey);
+                                       }
+                                       let witness_script = bitcoin::Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
+                                       let sighash = hash_to_message!(&bip143::SigHashCache::new(&spend_tx).signature_hash(input_idx, &witness_script, output.value, SigHashType::All)[..]);
+                                       let sig = secp_ctx.sign(&sighash, &secret.private_key.key);
+                                       spend_tx.input[input_idx].witness.push(sig.serialize_der().to_vec());
+                                       spend_tx.input[input_idx].witness[0].push(SigHashType::All as u8);
+                                       spend_tx.input[input_idx].witness.push(pubkey.key.serialize().to_vec());
+                               },
+                       }
+                       input_idx += 1;
+               }
+               Ok(spend_tx)
+       }
 }
 
 impl KeysInterface for KeysManager {
-       type ChanKeySigner = InMemoryChannelKeys;
+       type Signer = InMemorySigner;
 
        fn get_node_secret(&self) -> SecretKey {
                self.node_secret.clone()
@@ -809,14 +1013,18 @@ impl KeysInterface for KeysManager {
                self.shutdown_pubkey.clone()
        }
 
-       fn get_channel_keys(&self, _inbound: bool, channel_value_satoshis: u64) -> Self::ChanKeySigner {
+       fn get_channel_signer(&self, _inbound: bool, channel_value_satoshis: u64) -> Self::Signer {
                let child_ix = self.channel_child_index.fetch_add(1, Ordering::AcqRel);
-               let ix_and_nanos: u64 = (child_ix as u64) << 32 | (self.starting_time_nanos as u64);
-               self.derive_channel_keys(channel_value_satoshis, ix_and_nanos, self.starting_time_secs)
+               assert!(child_ix <= std::u32::MAX as usize);
+               let mut id = [0; 32];
+               id[0..8].copy_from_slice(&byte_utils::be64_to_array(child_ix as u64));
+               id[8..16].copy_from_slice(&byte_utils::be64_to_array(self.starting_time_nanos as u64));
+               id[16..24].copy_from_slice(&byte_utils::be64_to_array(self.starting_time_secs));
+               self.derive_channel_keys(channel_value_satoshis, &id)
        }
 
        fn get_secure_random_bytes(&self) -> [u8; 32] {
-               let mut sha = self.derive_unique_start();
+               let mut sha = self.rand_bytes_unique_start.clone();
 
                let child_ix = self.rand_bytes_child_index.fetch_add(1, Ordering::AcqRel);
                let child_privkey = self.rand_bytes_master_key.ckd_priv(&self.secp_ctx, ChildNumber::from_hardened_idx(child_ix as u32).expect("key space exhausted")).expect("Your RNG is busted");
@@ -825,4 +1033,8 @@ impl KeysInterface for KeysManager {
                sha.input(b"Unique Secure Random Bytes Salt");
                Sha256::from_engine(sha).into_inner()
        }
+
+       fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::Signer, DecodeError> {
+               InMemorySigner::read(&mut std::io::Cursor::new(reader))
+       }
 }
index af3fbea44f84856d4d7b4aada676db3a52513f96..c1fceec8c47171969397558db0ce62d11faf93ed 100644 (file)
@@ -9,12 +9,13 @@
 
 //! Structs and traits which allow other parts of rust-lightning to interact with the blockchain.
 
+use bitcoin::blockdata::block::{Block, BlockHeader};
 use bitcoin::blockdata::script::Script;
 use bitcoin::blockdata::transaction::TxOut;
 use bitcoin::hash_types::{BlockHash, Txid};
 
 use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr, MonitorEvent};
-use chain::keysinterface::ChannelKeys;
+use chain::keysinterface::Sign;
 use chain::transaction::OutPoint;
 
 pub mod chaininterface;
@@ -46,6 +47,18 @@ pub trait Access: Send + Sync {
        fn get_utxo(&self, genesis_hash: &BlockHash, short_channel_id: u64) -> Result<TxOut, AccessError>;
 }
 
+/// The `Listen` trait is used to be notified of when blocks have been connected or disconnected
+/// from the chain.
+///
+/// Useful when needing to replay chain data upon startup or as new chain events occur.
+pub trait Listen {
+       /// Notifies the listener that a block was added at the given height.
+       fn block_connected(&self, block: &Block, height: u32);
+
+       /// Notifies the listener that a block was removed at the given height.
+       fn block_disconnected(&self, header: &BlockHeader, height: u32);
+}
+
 /// The `Watch` trait defines behavior for watching on-chain activity pertaining to channels as
 /// blocks are connected and disconnected.
 ///
@@ -67,10 +80,7 @@ pub trait Access: Send + Sync {
 /// [`ChannelMonitor`]: channelmonitor/struct.ChannelMonitor.html
 /// [`ChannelMonitorUpdateErr`]: channelmonitor/enum.ChannelMonitorUpdateErr.html
 /// [`PermanentFailure`]: channelmonitor/enum.ChannelMonitorUpdateErr.html#variant.PermanentFailure
-pub trait Watch: Send + Sync {
-       /// Keys needed by monitors for creating and signing transactions.
-       type Keys: ChannelKeys;
-
+pub trait Watch<ChannelSigner: Sign>: Send + Sync {
        /// Watches a channel identified by `funding_txo` using `monitor`.
        ///
        /// Implementations are responsible for watching the chain for the funding transaction along
@@ -80,7 +90,7 @@ pub trait Watch: Send + Sync {
        /// [`get_outputs_to_watch`]: channelmonitor/struct.ChannelMonitor.html#method.get_outputs_to_watch
        /// [`block_connected`]: channelmonitor/struct.ChannelMonitor.html#method.block_connected
        /// [`block_disconnected`]: channelmonitor/struct.ChannelMonitor.html#method.block_disconnected
-       fn watch_channel(&self, funding_txo: OutPoint, monitor: ChannelMonitor<Self::Keys>) -> Result<(), ChannelMonitorUpdateErr>;
+       fn watch_channel(&self, funding_txo: OutPoint, monitor: ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr>;
 
        /// Updates a channel identified by `funding_txo` by applying `update` to its monitor.
        ///
@@ -126,3 +136,29 @@ pub trait Filter: Send + Sync {
        /// `script_pubkey` as the spending condition.
        fn register_output(&self, outpoint: &OutPoint, script_pubkey: &Script);
 }
+
+impl<T: Listen> Listen for std::ops::Deref<Target = T> {
+       fn block_connected(&self, block: &Block, height: u32) {
+               (**self).block_connected(block, height);
+       }
+
+       fn block_disconnected(&self, header: &BlockHeader, height: u32) {
+               (**self).block_disconnected(header, height);
+       }
+}
+
+impl<T: std::ops::Deref, U: std::ops::Deref> Listen for (T, U)
+where
+       T::Target: Listen,
+       U::Target: Listen,
+{
+       fn block_connected(&self, block: &Block, height: u32) {
+               self.0.block_connected(block, height);
+               self.1.block_connected(block, height);
+       }
+
+       fn block_disconnected(&self, header: &BlockHeader, height: u32) {
+               self.0.block_disconnected(header, height);
+               self.1.block_disconnected(header, height);
+       }
+}
index c5d369268cc6836f462ddb69d4c1b58c2a2047c5..567a7e18687abef37c6c1939e892684304d40512 100644 (file)
@@ -19,7 +19,7 @@
 //! instead of having a rather-separate lightning appendage to a wallet.
 
 #![cfg_attr(not(any(feature = "fuzztarget", feature = "_test_utils")), deny(missing_docs))]
-#![forbid(unsafe_code)]
+#![cfg_attr(not(any(test, feature = "fuzztarget", feature = "_test_utils")), forbid(unsafe_code))]
 
 // In general, rust is absolutely horrid at supporting users doing things like,
 // for example, compiling Rust code for real environments. Disable useless lints
 #![allow(bare_trait_objects)]
 #![allow(ellipsis_inclusive_range_patterns)]
 
+#![cfg_attr(all(test, feature = "unstable"), feature(test))]
+#[cfg(all(test, feature = "unstable"))] extern crate test;
+
 extern crate bitcoin;
 #[cfg(any(test, feature = "_test_utils"))] extern crate hex;
-#[cfg(any(test, feature = "_test_utils"))] extern crate regex;
+#[cfg(any(test, feature = "fuzztarget", feature = "_test_utils"))] extern crate regex;
 
 #[macro_use]
 pub mod util;
index 7b7d511d653e0553e2fb41d44cd97c2a31adf445..647fc323880dc62fddde8a94730d549f0e6d9d97 100644 (file)
@@ -8,14 +8,11 @@
 // licenses.
 
 //! Various utilities for building scripts and deriving keys related to channels. These are
-//! largely of interest for those implementing chain::keysinterface::ChannelKeys message signing
-//! by hand.
+//! largely of interest for those implementing chain::keysinterface::Sign message signing by hand.
 
 use bitcoin::blockdata::script::{Script,Builder};
 use bitcoin::blockdata::opcodes;
 use bitcoin::blockdata::transaction::{TxIn,TxOut,OutPoint,Transaction, SigHashType};
-use bitcoin::consensus::encode::{Decodable, Encodable};
-use bitcoin::consensus::encode;
 use bitcoin::util::bip143;
 
 use bitcoin::hashes::{Hash, HashEngine};
@@ -25,17 +22,29 @@ use bitcoin::hash_types::{Txid, PubkeyHash};
 
 use ln::channelmanager::{PaymentHash, PaymentPreimage};
 use ln::msgs::DecodeError;
-use util::ser::{Readable, Writeable, Writer, WriterWriteAdaptor};
+use util::ser::{Readable, Writeable, Writer, MAX_BUF_SIZE};
 use util::byte_utils;
 
+use bitcoin::hash_types::WPubkeyHash;
 use bitcoin::secp256k1::key::{SecretKey, PublicKey};
-use bitcoin::secp256k1::{Secp256k1, Signature};
+use bitcoin::secp256k1::{Secp256k1, Signature, Message};
 use bitcoin::secp256k1::Error as SecpError;
 use bitcoin::secp256k1;
 
-use std::{cmp, mem};
+use std::cmp;
+use ln::chan_utils;
+use util::transaction_utils::sort_outputs;
+use ln::channel::INITIAL_COMMITMENT_NUMBER;
+use std::io::Read;
+use std::ops::Deref;
+use chain;
 
-const MAX_ALLOC_SIZE: usize = 64*1024;
+const HTLC_OUTPUT_IN_COMMITMENT_SIZE: usize = 1 + 8 + 4 + 32 + 5;
+
+pub(crate) const MAX_HTLCS: u16 = 483;
+
+// This checks that the buffer size is greater than the maximum possible size for serialized HTLCS
+const _EXCESS_BUFFER_SIZE: usize = MAX_BUF_SIZE - MAX_HTLCS as usize * HTLC_OUTPUT_IN_COMMITMENT_SIZE;
 
 pub(super) const HTLC_SUCCESS_TX_WEIGHT: u64 = 703;
 pub(super) const HTLC_TIMEOUT_TX_WEIGHT: u64 = 663;
@@ -294,7 +303,7 @@ pub fn derive_public_revocation_key<T: secp256k1::Verification>(secp_ctx: &Secp2
 ///
 /// These keys are assumed to be good, either because the code derived them from
 /// channel basepoints via the new function, or they were obtained via
-/// PreCalculatedTxCreationKeys.trust_key_derivation because we trusted the source of the
+/// CommitmentTransaction.trust().keys() because we trusted the source of the
 /// pre-calculated keys.
 #[derive(PartialEq, Clone)]
 pub struct TxCreationKeys {
@@ -314,31 +323,6 @@ pub struct TxCreationKeys {
 impl_writeable!(TxCreationKeys, 33*6,
        { per_commitment_point, revocation_key, broadcaster_htlc_key, countersignatory_htlc_key, broadcaster_delayed_payment_key });
 
-/// The per-commitment point and a set of pre-calculated public keys used for transaction creation
-/// in the signer.
-/// The pre-calculated keys are an optimization, because ChannelKeys has enough
-/// information to re-derive them.
-#[derive(PartialEq, Clone)]
-pub struct PreCalculatedTxCreationKeys(TxCreationKeys);
-
-impl PreCalculatedTxCreationKeys {
-       /// Create a new PreCalculatedTxCreationKeys from TxCreationKeys
-       pub fn new(keys: TxCreationKeys) -> Self {
-               PreCalculatedTxCreationKeys(keys)
-       }
-
-       /// The pre-calculated transaction creation public keys.
-       /// An external validating signer should not trust these keys.
-       pub fn trust_key_derivation(&self) -> &TxCreationKeys {
-               &self.0
-       }
-
-       /// The transaction per-commitment point
-       pub fn per_commitment_point(&self) -> &PublicKey {
-               &self.0.per_commitment_point
-       }
-}
-
 /// One counterparty's public keys which do not change over the life of a channel.
 #[derive(Clone, PartialEq)]
 pub struct ChannelPublicKeys {
@@ -373,7 +357,8 @@ impl_writeable!(ChannelPublicKeys, 33*5, {
 
 
 impl TxCreationKeys {
-       /// Create a new TxCreationKeys from channel base points and the per-commitment point
+       /// Create per-state keys from channel base points and the per-commitment point.
+       /// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
        pub fn derive_new<T: secp256k1::Signing + secp256k1::Verification>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, broadcaster_delayed_payment_base: &PublicKey, broadcaster_htlc_base: &PublicKey, countersignatory_revocation_base: &PublicKey, countersignatory_htlc_base: &PublicKey) -> Result<TxCreationKeys, SecpError> {
                Ok(TxCreationKeys {
                        per_commitment_point: per_commitment_point.clone(),
@@ -383,13 +368,31 @@ impl TxCreationKeys {
                        broadcaster_delayed_payment_key: derive_public_key(&secp_ctx, &per_commitment_point, &broadcaster_delayed_payment_base)?,
                })
        }
+
+       /// Generate per-state keys from channel static keys.
+       /// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
+       pub fn from_channel_static_keys<T: secp256k1::Signing + secp256k1::Verification>(per_commitment_point: &PublicKey, broadcaster_keys: &ChannelPublicKeys, countersignatory_keys: &ChannelPublicKeys, secp_ctx: &Secp256k1<T>) -> Result<TxCreationKeys, SecpError> {
+               TxCreationKeys::derive_new(
+                       &secp_ctx,
+                       &per_commitment_point,
+                       &broadcaster_keys.delayed_payment_basepoint,
+                       &broadcaster_keys.htlc_basepoint,
+                       &countersignatory_keys.revocation_basepoint,
+                       &countersignatory_keys.htlc_basepoint,
+               )
+       }
 }
 
+/// The maximum length of a script returned by get_revokeable_redeemscript.
+// Calculated as 6 bytes of opcodes, 1 byte push plus 2 bytes for contest_delay, and two public
+// keys of 33 bytes (+ 1 push).
+pub const REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH: usize = 6 + 3 + 34*2;
+
 /// A script either spendable by the revocation
 /// key or the broadcaster_delayed_payment_key and satisfying the relative-locktime OP_CSV constrain.
 /// Encumbering a `to_holder` output on a commitment transaction or 2nd-stage HTLC transactions.
 pub fn get_revokeable_redeemscript(revocation_key: &PublicKey, contest_delay: u16, broadcaster_delayed_payment_key: &PublicKey) -> Script {
-       Builder::new().push_opcode(opcodes::all::OP_IF)
+       let res = Builder::new().push_opcode(opcodes::all::OP_IF)
                      .push_slice(&revocation_key.serialize())
                      .push_opcode(opcodes::all::OP_ELSE)
                      .push_int(contest_delay as i64)
@@ -398,7 +401,9 @@ pub fn get_revokeable_redeemscript(revocation_key: &PublicKey, contest_delay: u1
                      .push_slice(&broadcaster_delayed_payment_key.serialize())
                      .push_opcode(opcodes::all::OP_ENDIF)
                      .push_opcode(opcodes::all::OP_CHECKSIG)
-                     .into_script()
+                     .into_script();
+       debug_assert!(res.len() <= REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH);
+       res
 }
 
 #[derive(Clone, PartialEq)]
@@ -422,7 +427,7 @@ pub struct HTLCOutputInCommitment {
        pub transaction_output_index: Option<u32>,
 }
 
-impl_writeable!(HTLCOutputInCommitment, 1 + 8 + 4 + 32 + 5, {
+impl_writeable!(HTLCOutputInCommitment, HTLC_OUTPUT_IN_COMMITMENT_SIZE, {
        offered,
        amount_msat,
        cltv_expiry,
@@ -551,130 +556,216 @@ pub fn build_htlc_transaction(prev_hash: &Txid, feerate_per_kw: u32, contest_del
        }
 }
 
+/// Per-channel data used to build transactions in conjunction with the per-commitment data (CommitmentTransaction).
+/// The fields are organized by holder/counterparty.
+///
+/// Normally, this is converted to the broadcaster/countersignatory-organized DirectedChannelTransactionParameters
+/// before use, via the as_holder_broadcastable and as_counterparty_broadcastable functions.
+#[derive(Clone)]
+pub struct ChannelTransactionParameters {
+       /// Holder public keys
+       pub holder_pubkeys: ChannelPublicKeys,
+       /// The contest delay selected by the holder, which applies to counterparty-broadcast transactions
+       pub holder_selected_contest_delay: u16,
+       /// Whether the holder is the initiator of this channel.
+       /// This is an input to the commitment number obscure factor computation.
+       pub is_outbound_from_holder: bool,
+       /// The late-bound counterparty channel transaction parameters.
+       /// These parameters are populated at the point in the protocol where the counterparty provides them.
+       pub counterparty_parameters: Option<CounterpartyChannelTransactionParameters>,
+       /// The late-bound funding outpoint
+       pub funding_outpoint: Option<chain::transaction::OutPoint>,
+}
+
+/// Late-bound per-channel counterparty data used to build transactions.
+#[derive(Clone)]
+pub struct CounterpartyChannelTransactionParameters {
+       /// Counter-party public keys
+       pub pubkeys: ChannelPublicKeys,
+       /// The contest delay selected by the counterparty, which applies to holder-broadcast transactions
+       pub selected_contest_delay: u16,
+}
+
+impl ChannelTransactionParameters {
+       /// Whether the late bound parameters are populated.
+       pub fn is_populated(&self) -> bool {
+               self.counterparty_parameters.is_some() && self.funding_outpoint.is_some()
+       }
+
+       /// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
+       /// given that the holder is the broadcaster.
+       ///
+       /// self.is_populated() must be true before calling this function.
+       pub fn as_holder_broadcastable(&self) -> DirectedChannelTransactionParameters {
+               assert!(self.is_populated(), "self.late_parameters must be set before using as_holder_broadcastable");
+               DirectedChannelTransactionParameters {
+                       inner: self,
+                       holder_is_broadcaster: true
+               }
+       }
+
+       /// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
+       /// given that the counterparty is the broadcaster.
+       ///
+       /// self.is_populated() must be true before calling this function.
+       pub fn as_counterparty_broadcastable(&self) -> DirectedChannelTransactionParameters {
+               assert!(self.is_populated(), "self.late_parameters must be set before using as_counterparty_broadcastable");
+               DirectedChannelTransactionParameters {
+                       inner: self,
+                       holder_is_broadcaster: false
+               }
+       }
+}
+
+impl_writeable!(CounterpartyChannelTransactionParameters, 0, {
+       pubkeys,
+       selected_contest_delay
+});
+
+impl_writeable!(ChannelTransactionParameters, 0, {
+       holder_pubkeys,
+       holder_selected_contest_delay,
+       is_outbound_from_holder,
+       counterparty_parameters,
+       funding_outpoint
+});
+
+/// Static channel fields used to build transactions given per-commitment fields, organized by
+/// broadcaster/countersignatory.
+///
+/// This is derived from the holder/counterparty-organized ChannelTransactionParameters via the
+/// as_holder_broadcastable and as_counterparty_broadcastable functions.
+pub struct DirectedChannelTransactionParameters<'a> {
+       /// The holder's channel static parameters
+       inner: &'a ChannelTransactionParameters,
+       /// Whether the holder is the broadcaster
+       holder_is_broadcaster: bool,
+}
+
+impl<'a> DirectedChannelTransactionParameters<'a> {
+       /// Get the channel pubkeys for the broadcaster
+       pub fn broadcaster_pubkeys(&self) -> &ChannelPublicKeys {
+               if self.holder_is_broadcaster {
+                       &self.inner.holder_pubkeys
+               } else {
+                       &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
+               }
+       }
+
+       /// Get the channel pubkeys for the countersignatory
+       pub fn countersignatory_pubkeys(&self) -> &ChannelPublicKeys {
+               if self.holder_is_broadcaster {
+                       &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
+               } else {
+                       &self.inner.holder_pubkeys
+               }
+       }
+
+       /// Get the contest delay applicable to the transactions.
+       /// Note that the contest delay was selected by the countersignatory.
+       pub fn contest_delay(&self) -> u16 {
+               let counterparty_parameters = self.inner.counterparty_parameters.as_ref().unwrap();
+               if self.holder_is_broadcaster { counterparty_parameters.selected_contest_delay } else { self.inner.holder_selected_contest_delay }
+       }
+
+       /// Whether the channel is outbound from the broadcaster.
+       ///
+       /// The boolean representing the side that initiated the channel is
+       /// an input to the commitment number obscure factor computation.
+       pub fn is_outbound(&self) -> bool {
+               if self.holder_is_broadcaster { self.inner.is_outbound_from_holder } else { !self.inner.is_outbound_from_holder }
+       }
+
+       /// The funding outpoint
+       pub fn funding_outpoint(&self) -> OutPoint {
+               self.inner.funding_outpoint.unwrap().into_bitcoin_outpoint()
+       }
+}
+
+/// Information needed to build and sign a holder's commitment transaction.
+///
+/// The transaction is only signed once we are ready to broadcast.
 #[derive(Clone)]
-/// We use this to track holder commitment transactions and put off signing them until we are ready
-/// to broadcast. This class can be used inside a signer implementation to generate a signature
-/// given the relevant secret key.
 pub struct HolderCommitmentTransaction {
-       // TODO: We should migrate away from providing the transaction, instead providing enough to
-       // allow the ChannelKeys to construct it from scratch. Luckily we already have HTLC data here,
-       // so we're probably most of the way there.
-       /// The commitment transaction itself, in unsigned form.
-       pub unsigned_tx: Transaction,
-       /// Our counterparty's signature for the transaction, above.
+       inner: CommitmentTransaction,
+       /// Our counterparty's signature for the transaction
        pub counterparty_sig: Signature,
+       /// All non-dust counterparty HTLC signatures, in the order they appear in the transaction
+       pub counterparty_htlc_sigs: Vec<Signature>,
        // Which order the signatures should go in when constructing the final commitment tx witness.
-       // The user should be able to reconstruc this themselves, so we don't bother to expose it.
+       // The user should be able to reconstruct this themselves, so we don't bother to expose it.
        holder_sig_first: bool,
-       pub(crate) keys: TxCreationKeys,
-       /// The feerate paid per 1000-weight-unit in this commitment transaction. This value is
-       /// controlled by the channel initiator.
-       pub feerate_per_kw: u32,
-       /// The HTLCs and counterparty htlc signatures which were included in this commitment transaction.
-       ///
-       /// Note that this includes all HTLCs, including ones which were considered dust and not
-       /// actually included in the transaction as it appears on-chain, but who's value is burned as
-       /// fees and not included in the to_holder or to_counterparty outputs.
-       ///
-       /// The counterparty HTLC signatures in the second element will always be set for non-dust HTLCs, ie
-       /// those for which transaction_output_index.is_some().
-       pub per_htlc: Vec<(HTLCOutputInCommitment, Option<Signature>)>,
 }
+
+impl Deref for HolderCommitmentTransaction {
+       type Target = CommitmentTransaction;
+
+       fn deref(&self) -> &Self::Target { &self.inner }
+}
+
+impl PartialEq for HolderCommitmentTransaction {
+       // We dont care whether we are signed in equality comparison
+       fn eq(&self, o: &Self) -> bool {
+               self.inner == o.inner
+       }
+}
+
+impl_writeable!(HolderCommitmentTransaction, 0, {
+       inner, counterparty_sig, counterparty_htlc_sigs, holder_sig_first
+});
+
 impl HolderCommitmentTransaction {
        #[cfg(test)]
        pub fn dummy() -> Self {
-               let dummy_input = TxIn {
-                       previous_output: OutPoint {
-                               txid: Default::default(),
-                               vout: 0,
-                       },
-                       script_sig: Default::default(),
-                       sequence: 0,
-                       witness: vec![]
+               let secp_ctx = Secp256k1::new();
+               let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
+               let dummy_sig = secp_ctx.sign(&secp256k1::Message::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap());
+
+               let keys = TxCreationKeys {
+                       per_commitment_point: dummy_key.clone(),
+                       revocation_key: dummy_key.clone(),
+                       broadcaster_htlc_key: dummy_key.clone(),
+                       countersignatory_htlc_key: dummy_key.clone(),
+                       broadcaster_delayed_payment_key: dummy_key.clone(),
                };
-               let dummy_key = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&[42; 32]).unwrap());
-               let dummy_sig = Secp256k1::new().sign(&secp256k1::Message::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap());
-               Self {
-                       unsigned_tx: Transaction {
-                               version: 2,
-                               input: vec![dummy_input],
-                               output: Vec::new(),
-                               lock_time: 0,
-                       },
+               let channel_pubkeys = ChannelPublicKeys {
+                       funding_pubkey: dummy_key.clone(),
+                       revocation_basepoint: dummy_key.clone(),
+                       payment_point: dummy_key.clone(),
+                       delayed_payment_basepoint: dummy_key.clone(),
+                       htlc_basepoint: dummy_key.clone()
+               };
+               let channel_parameters = ChannelTransactionParameters {
+                       holder_pubkeys: channel_pubkeys.clone(),
+                       holder_selected_contest_delay: 0,
+                       is_outbound_from_holder: false,
+                       counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: channel_pubkeys.clone(), selected_contest_delay: 0 }),
+                       funding_outpoint: Some(chain::transaction::OutPoint { txid: Default::default(), index: 0 })
+               };
+               let mut htlcs_with_aux: Vec<(_, ())> = Vec::new();
+               let inner = CommitmentTransaction::new_with_auxiliary_htlc_data(0, 0, 0, keys, 0, &mut htlcs_with_aux, &channel_parameters.as_counterparty_broadcastable());
+               HolderCommitmentTransaction {
+                       inner,
                        counterparty_sig: dummy_sig,
-                       holder_sig_first: false,
-                       keys: TxCreationKeys {
-                                       per_commitment_point: dummy_key.clone(),
-                                       revocation_key: dummy_key.clone(),
-                                       broadcaster_htlc_key: dummy_key.clone(),
-                                       countersignatory_htlc_key: dummy_key.clone(),
-                                       broadcaster_delayed_payment_key: dummy_key.clone(),
-                               },
-                       feerate_per_kw: 0,
-                       per_htlc: Vec::new()
+                       counterparty_htlc_sigs: Vec::new(),
+                       holder_sig_first: false
                }
        }
 
-       /// Generate a new HolderCommitmentTransaction based on a raw commitment transaction,
-       /// counterparty signature and both parties keys.
-       ///
-       /// The unsigned transaction outputs must be consistent with htlc_data.  This function
-       /// only checks that the shape and amounts are consistent, but does not check the scriptPubkey.
-       pub fn new_missing_holder_sig(unsigned_tx: Transaction, counterparty_sig: Signature, holder_funding_key: &PublicKey, counterparty_funding_key: &PublicKey, keys: TxCreationKeys, feerate_per_kw: u32, htlc_data: Vec<(HTLCOutputInCommitment, Option<Signature>)>) -> HolderCommitmentTransaction {
-               if unsigned_tx.input.len() != 1 { panic!("Tried to store a commitment transaction that had input count != 1!"); }
-               if unsigned_tx.input[0].witness.len() != 0 { panic!("Tried to store a signed commitment transaction?"); }
-
-               for htlc in &htlc_data {
-                       if let Some(index) = htlc.0.transaction_output_index {
-                               let out = &unsigned_tx.output[index as usize];
-                               if out.value != htlc.0.amount_msat / 1000 {
-                                       panic!("HTLC at index {} has incorrect amount", index);
-                               }
-                               if !out.script_pubkey.is_v0_p2wsh() {
-                                       panic!("HTLC at index {} doesn't have p2wsh scriptPubkey", index);
-                               }
-                       }
-               }
-
+       /// Create a new holder transaction with the given counterparty signatures.
+       /// The funding keys are used to figure out which signature should go first when building the transaction for broadcast.
+       pub fn new(commitment_tx: CommitmentTransaction, counterparty_sig: Signature, counterparty_htlc_sigs: Vec<Signature>, holder_funding_key: &PublicKey, counterparty_funding_key: &PublicKey) -> Self {
                Self {
-                       unsigned_tx,
+                       inner: commitment_tx,
                        counterparty_sig,
+                       counterparty_htlc_sigs,
                        holder_sig_first: holder_funding_key.serialize()[..] < counterparty_funding_key.serialize()[..],
-                       keys,
-                       feerate_per_kw,
-                       per_htlc: htlc_data,
                }
        }
 
-       /// The pre-calculated transaction creation public keys.
-       /// An external validating signer should not trust these keys.
-       pub fn trust_key_derivation(&self) -> &TxCreationKeys {
-               &self.keys
-       }
-
-       /// Get the txid of the holder commitment transaction contained in this
-       /// HolderCommitmentTransaction
-       pub fn txid(&self) -> Txid {
-               self.unsigned_tx.txid()
-       }
-
-       /// Gets holder signature for the contained commitment transaction given holder funding private key.
-       ///
-       /// Funding key is your key included in the 2-2 funding_outpoint lock. Should be provided
-       /// by your ChannelKeys.
-       /// Funding redeemscript is script locking funding_outpoint. This is the mutlsig script
-       /// between your own funding key and your counterparty's. Currently, this is provided in
-       /// ChannelKeys::sign_holder_commitment() calls directly.
-       /// Channel value is amount locked in funding_outpoint.
-       pub fn get_holder_sig<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
-               let sighash = hash_to_message!(&bip143::SigHashCache::new(&self.unsigned_tx)
-                       .signature_hash(0, funding_redeemscript, channel_value_satoshis, SigHashType::All)[..]);
-               secp_ctx.sign(&sighash, funding_key)
-       }
-
        pub(crate) fn add_holder_sig(&self, funding_redeemscript: &Script, holder_sig: Signature) -> Transaction {
-               let mut tx = self.unsigned_tx.clone();
                // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
+               let mut tx = self.inner.built.transaction.clone();
                tx.input[0].witness.push(Vec::new());
 
                if self.holder_sig_first {
@@ -690,59 +781,409 @@ impl HolderCommitmentTransaction {
                tx.input[0].witness.push(funding_redeemscript.as_bytes().to_vec());
                tx
        }
+}
+
+/// A pre-built Bitcoin commitment transaction and its txid.
+#[derive(Clone)]
+pub struct BuiltCommitmentTransaction {
+       /// The commitment transaction
+       pub transaction: Transaction,
+       /// The txid for the commitment transaction.
+       ///
+       /// This is provided as a performance optimization, instead of calling transaction.txid()
+       /// multiple times.
+       pub txid: Txid,
+}
+
+impl_writeable!(BuiltCommitmentTransaction, 0, { transaction, txid });
+
+impl BuiltCommitmentTransaction {
+       /// Get the SIGHASH_ALL sighash value of the transaction.
+       ///
+       /// This can be used to verify a signature.
+       pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message {
+               let sighash = &bip143::SigHashCache::new(&self.transaction).signature_hash(0, funding_redeemscript, channel_value_satoshis, SigHashType::All)[..];
+               hash_to_message!(sighash)
+       }
+
+       /// Sign a transaction, either because we are counter-signing the counterparty's transaction or
+       /// because we are about to broadcast a holder transaction.
+       pub fn sign<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
+               let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
+               secp_ctx.sign(&sighash, funding_key)
+       }
+}
+
+/// This class tracks the per-transaction information needed to build a commitment transaction and to
+/// actually build it and sign.  It is used for holder transactions that we sign only when needed
+/// and for transactions we sign for the counterparty.
+///
+/// This class can be used inside a signer implementation to generate a signature given the relevant
+/// secret key.
+#[derive(Clone)]
+pub struct CommitmentTransaction {
+       commitment_number: u64,
+       to_broadcaster_value_sat: u64,
+       to_countersignatory_value_sat: u64,
+       feerate_per_kw: u32,
+       htlcs: Vec<HTLCOutputInCommitment>,
+       // A cache of the parties' pubkeys required to construct the transaction, see doc for trust()
+       keys: TxCreationKeys,
+       // For access to the pre-built transaction, see doc for trust()
+       built: BuiltCommitmentTransaction,
+}
+
+impl PartialEq for CommitmentTransaction {
+       fn eq(&self, o: &Self) -> bool {
+               let eq = self.commitment_number == o.commitment_number &&
+                       self.to_broadcaster_value_sat == o.to_broadcaster_value_sat &&
+                       self.to_countersignatory_value_sat == o.to_countersignatory_value_sat &&
+                       self.feerate_per_kw == o.feerate_per_kw &&
+                       self.htlcs == o.htlcs &&
+                       self.keys == o.keys;
+               if eq {
+                       debug_assert_eq!(self.built.transaction, o.built.transaction);
+                       debug_assert_eq!(self.built.txid, o.built.txid);
+               }
+               eq
+       }
+}
+
+/// (C-not exported) as users never need to call this directly
+impl Writeable for Vec<HTLCOutputInCommitment> {
+       #[inline]
+       fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
+               (self.len() as u16).write(w)?;
+               for e in self.iter() {
+                       e.write(w)?;
+               }
+               Ok(())
+       }
+}
+
+/// (C-not exported) as users never need to call this directly
+impl Readable for Vec<HTLCOutputInCommitment> {
+       #[inline]
+       fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
+               let len: u16 = Readable::read(r)?;
+               let byte_size = (len as usize)
+                       .checked_mul(HTLC_OUTPUT_IN_COMMITMENT_SIZE)
+                       .ok_or(DecodeError::BadLengthDescriptor)?;
+               if byte_size > MAX_BUF_SIZE {
+                       return Err(DecodeError::BadLengthDescriptor);
+               }
+               let mut ret = Vec::with_capacity(len as usize);
+               for _ in 0..len { ret.push(HTLCOutputInCommitment::read(r)?); }
+               Ok(ret)
+       }
+}
+
+impl_writeable!(CommitmentTransaction, 0, {
+       commitment_number,
+       to_broadcaster_value_sat,
+       to_countersignatory_value_sat,
+       feerate_per_kw,
+       htlcs,
+       keys,
+       built
+});
+
+impl CommitmentTransaction {
+       /// Construct an object of the class while assigning transaction output indices to HTLCs.
+       ///
+       /// Populates HTLCOutputInCommitment.transaction_output_index in htlcs_with_aux.
+       ///
+       /// The generic T allows the caller to match the HTLC output index with auxiliary data.
+       /// This auxiliary data is not stored in this object.
+       ///
+       /// Only include HTLCs that are above the dust limit for the channel.
+       ///
+       /// (C-not exported) due to the generic though we likely should expose a version without
+       pub fn new_with_auxiliary_htlc_data<T>(commitment_number: u64, to_broadcaster_value_sat: u64, to_countersignatory_value_sat: u64, keys: TxCreationKeys, feerate_per_kw: u32, htlcs_with_aux: &mut Vec<(HTLCOutputInCommitment, T)>, channel_parameters: &DirectedChannelTransactionParameters) -> CommitmentTransaction {
+               // Sort outputs and populate output indices while keeping track of the auxiliary data
+               let (outputs, htlcs) = Self::internal_build_outputs(&keys, to_broadcaster_value_sat, to_countersignatory_value_sat, htlcs_with_aux, channel_parameters).unwrap();
+
+               let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(commitment_number, channel_parameters);
+               let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
+               let txid = transaction.txid();
+               CommitmentTransaction {
+                       commitment_number,
+                       to_broadcaster_value_sat,
+                       to_countersignatory_value_sat,
+                       feerate_per_kw,
+                       htlcs,
+                       keys,
+                       built: BuiltCommitmentTransaction {
+                               transaction,
+                               txid
+                       },
+               }
+       }
+
+       fn internal_rebuild_transaction(&self, keys: &TxCreationKeys, channel_parameters: &DirectedChannelTransactionParameters) -> Result<BuiltCommitmentTransaction, ()> {
+               let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(self.commitment_number, channel_parameters);
+
+               let mut htlcs_with_aux = self.htlcs.iter().map(|h| (h.clone(), ())).collect();
+               let (outputs, _) = Self::internal_build_outputs(keys, self.to_broadcaster_value_sat, self.to_countersignatory_value_sat, &mut htlcs_with_aux, channel_parameters)?;
+
+               let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
+               let txid = transaction.txid();
+               let built_transaction = BuiltCommitmentTransaction {
+                       transaction,
+                       txid
+               };
+               Ok(built_transaction)
+       }
+
+       fn make_transaction(obscured_commitment_transaction_number: u64, txins: Vec<TxIn>, outputs: Vec<TxOut>) -> Transaction {
+               Transaction {
+                       version: 2,
+                       lock_time: ((0x20 as u32) << 8 * 3) | ((obscured_commitment_transaction_number & 0xffffffu64) as u32),
+                       input: txins,
+                       output: outputs,
+               }
+       }
+
+       // This is used in two cases:
+       // - initial sorting of outputs / HTLCs in the constructor, in which case T is auxiliary data the
+       //   caller needs to have sorted together with the HTLCs so it can keep track of the output index
+       // - building of a bitcoin transaction during a verify() call, in which case T is just ()
+       fn internal_build_outputs<T>(keys: &TxCreationKeys, to_broadcaster_value_sat: u64, to_countersignatory_value_sat: u64, htlcs_with_aux: &mut Vec<(HTLCOutputInCommitment, T)>, channel_parameters: &DirectedChannelTransactionParameters) -> Result<(Vec<TxOut>, Vec<HTLCOutputInCommitment>), ()> {
+               let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
+               let contest_delay = channel_parameters.contest_delay();
+
+               let mut txouts: Vec<(TxOut, Option<&mut HTLCOutputInCommitment>)> = Vec::new();
+
+               if to_countersignatory_value_sat > 0 {
+                       let script = script_for_p2wpkh(&countersignatory_pubkeys.payment_point);
+                       txouts.push((
+                               TxOut {
+                                       script_pubkey: script.clone(),
+                                       value: to_countersignatory_value_sat,
+                               },
+                               None,
+                       ))
+               }
+
+               if to_broadcaster_value_sat > 0 {
+                       let redeem_script = get_revokeable_redeemscript(
+                               &keys.revocation_key,
+                               contest_delay,
+                               &keys.broadcaster_delayed_payment_key,
+                       );
+                       txouts.push((
+                               TxOut {
+                                       script_pubkey: redeem_script.to_v0_p2wsh(),
+                                       value: to_broadcaster_value_sat,
+                               },
+                               None,
+                       ));
+               }
+
+               let mut htlcs = Vec::with_capacity(htlcs_with_aux.len());
+               for (htlc, _) in htlcs_with_aux {
+                       let script = chan_utils::get_htlc_redeemscript(&htlc, &keys);
+                       let txout = TxOut {
+                               script_pubkey: script.to_v0_p2wsh(),
+                               value: htlc.amount_msat / 1000,
+                       };
+                       txouts.push((txout, Some(htlc)));
+               }
+
+               // Sort output in BIP-69 order (amount, scriptPubkey).  Tie-breaks based on HTLC
+               // CLTV expiration height.
+               sort_outputs(&mut txouts, |a, b| {
+                       if let &Some(ref a_htlcout) = a {
+                               if let &Some(ref b_htlcout) = b {
+                                       a_htlcout.cltv_expiry.cmp(&b_htlcout.cltv_expiry)
+                                               // Note that due to hash collisions, we have to have a fallback comparison
+                                               // here for fuzztarget mode (otherwise at least chanmon_fail_consistency
+                                               // may fail)!
+                                               .then(a_htlcout.payment_hash.0.cmp(&b_htlcout.payment_hash.0))
+                               // For non-HTLC outputs, if they're copying our SPK we don't really care if we
+                               // close the channel due to mismatches - they're doing something dumb:
+                               } else { cmp::Ordering::Equal }
+                       } else { cmp::Ordering::Equal }
+               });
+
+               let mut outputs = Vec::with_capacity(txouts.len());
+               for (idx, out) in txouts.drain(..).enumerate() {
+                       if let Some(htlc) = out.1 {
+                               htlc.transaction_output_index = Some(idx as u32);
+                               htlcs.push(htlc.clone());
+                       }
+                       outputs.push(out.0);
+               }
+               Ok((outputs, htlcs))
+       }
+
+       fn internal_build_inputs(commitment_number: u64, channel_parameters: &DirectedChannelTransactionParameters) -> (u64, Vec<TxIn>) {
+               let broadcaster_pubkeys = channel_parameters.broadcaster_pubkeys();
+               let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
+               let commitment_transaction_number_obscure_factor = get_commitment_transaction_number_obscure_factor(
+                       &broadcaster_pubkeys.payment_point,
+                       &countersignatory_pubkeys.payment_point,
+                       channel_parameters.is_outbound(),
+               );
+
+               let obscured_commitment_transaction_number =
+                       commitment_transaction_number_obscure_factor ^ (INITIAL_COMMITMENT_NUMBER - commitment_number);
+
+               let txins = {
+                       let mut ins: Vec<TxIn> = Vec::new();
+                       ins.push(TxIn {
+                               previous_output: channel_parameters.funding_outpoint(),
+                               script_sig: Script::new(),
+                               sequence: ((0x80 as u32) << 8 * 3)
+                                       | ((obscured_commitment_transaction_number >> 3 * 8) as u32),
+                               witness: Vec::new(),
+                       });
+                       ins
+               };
+               (obscured_commitment_transaction_number, txins)
+       }
+
+       /// The backwards-counting commitment number
+       pub fn commitment_number(&self) -> u64 {
+               self.commitment_number
+       }
+
+       /// The value to be sent to the broadcaster
+       pub fn to_broadcaster_value_sat(&self) -> u64 {
+               self.to_broadcaster_value_sat
+       }
+
+       /// The value to be sent to the counterparty
+       pub fn to_countersignatory_value_sat(&self) -> u64 {
+               self.to_countersignatory_value_sat
+       }
+
+       /// The feerate paid per 1000-weight-unit in this commitment transaction.
+       pub fn feerate_per_kw(&self) -> u32 {
+               self.feerate_per_kw
+       }
+
+       /// The non-dust HTLCs (direction, amt, height expiration, hash, transaction output index)
+       /// which were included in this commitment transaction in output order.
+       /// The transaction index is always populated.
+       ///
+       /// (C-not exported) as we cannot currently convert Vec references to/from C, though we should
+       /// expose a less effecient version which creates a Vec of references in the future.
+       pub fn htlcs(&self) -> &Vec<HTLCOutputInCommitment> {
+               &self.htlcs
+       }
+
+       /// Trust our pre-built transaction and derived transaction creation public keys.
+       ///
+       /// Applies a wrapper which allows access to these fields.
+       ///
+       /// This should only be used if you fully trust the builder of this object.  It should not
+       ///     be used by an external signer - instead use the verify function.
+       pub fn trust(&self) -> TrustedCommitmentTransaction {
+               TrustedCommitmentTransaction { inner: self }
+       }
+
+       /// Verify our pre-built transaction and derived transaction creation public keys.
+       ///
+       /// Applies a wrapper which allows access to these fields.
+       ///
+       /// An external validating signer must call this method before signing
+       /// or using the built transaction.
+       pub fn verify<T: secp256k1::Signing + secp256k1::Verification>(&self, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_keys: &ChannelPublicKeys, countersignatory_keys: &ChannelPublicKeys, secp_ctx: &Secp256k1<T>) -> Result<TrustedCommitmentTransaction, ()> {
+               // This is the only field of the key cache that we trust
+               let per_commitment_point = self.keys.per_commitment_point;
+               let keys = TxCreationKeys::from_channel_static_keys(&per_commitment_point, broadcaster_keys, countersignatory_keys, secp_ctx).unwrap();
+               if keys != self.keys {
+                       return Err(());
+               }
+               let tx = self.internal_rebuild_transaction(&keys, channel_parameters)?;
+               if self.built.transaction != tx.transaction || self.built.txid != tx.txid {
+                       return Err(());
+               }
+               Ok(TrustedCommitmentTransaction { inner: self })
+       }
+}
+
+/// A wrapper on CommitmentTransaction indicating that the derived fields (the built bitcoin
+/// transaction and the transaction creation keys) are trusted.
+///
+/// See trust() and verify() functions on CommitmentTransaction.
+///
+/// This structure implements Deref.
+pub struct TrustedCommitmentTransaction<'a> {
+       inner: &'a CommitmentTransaction,
+}
+
+impl<'a> Deref for TrustedCommitmentTransaction<'a> {
+       type Target = CommitmentTransaction;
+
+       fn deref(&self) -> &Self::Target { self.inner }
+}
+
+impl<'a> TrustedCommitmentTransaction<'a> {
+       /// The transaction ID of the built Bitcoin transaction
+       pub fn txid(&self) -> Txid {
+               self.inner.built.txid
+       }
+
+       /// The pre-built Bitcoin commitment transaction
+       pub fn built_transaction(&self) -> &BuiltCommitmentTransaction {
+               &self.inner.built
+       }
+
+       /// The pre-calculated transaction creation public keys.
+       pub fn keys(&self) -> &TxCreationKeys {
+               &self.inner.keys
+       }
 
        /// Get a signature for each HTLC which was included in the commitment transaction (ie for
        /// which HTLCOutputInCommitment::transaction_output_index.is_some()).
        ///
-       /// The returned Vec has one entry for each HTLC, and in the same order. For HTLCs which were
-       /// considered dust and not included, a None entry exists, for all others a signature is
-       /// included.
-       pub fn get_htlc_sigs<T: secp256k1::Signing + secp256k1::Verification>(&self, htlc_base_key: &SecretKey, counterparty_selected_contest_delay: u16, secp_ctx: &Secp256k1<T>) -> Result<Vec<Option<Signature>>, ()> {
-               let txid = self.txid();
-               let mut ret = Vec::with_capacity(self.per_htlc.len());
-               let holder_htlc_key = derive_private_key(secp_ctx, &self.keys.per_commitment_point, htlc_base_key).map_err(|_| ())?;
-
-               for this_htlc in self.per_htlc.iter() {
-                       if this_htlc.0.transaction_output_index.is_some() {
-                               let htlc_tx = build_htlc_transaction(&txid, self.feerate_per_kw, counterparty_selected_contest_delay, &this_htlc.0, &self.keys.broadcaster_delayed_payment_key, &self.keys.revocation_key);
-
-                               let htlc_redeemscript = get_htlc_redeemscript_with_explicit_keys(&this_htlc.0, &self.keys.broadcaster_htlc_key, &self.keys.countersignatory_htlc_key, &self.keys.revocation_key);
-
-                               let sighash = hash_to_message!(&bip143::SigHashCache::new(&htlc_tx).signature_hash(0, &htlc_redeemscript, this_htlc.0.amount_msat / 1000, SigHashType::All)[..]);
-                               ret.push(Some(secp_ctx.sign(&sighash, &holder_htlc_key)));
-                       } else {
-                               ret.push(None);
-                       }
+       /// The returned Vec has one entry for each HTLC, and in the same order.
+       pub fn get_htlc_sigs<T: secp256k1::Signing>(&self, htlc_base_key: &SecretKey, channel_parameters: &DirectedChannelTransactionParameters, secp_ctx: &Secp256k1<T>) -> Result<Vec<Signature>, ()> {
+               let inner = self.inner;
+               let keys = &inner.keys;
+               let txid = inner.built.txid;
+               let mut ret = Vec::with_capacity(inner.htlcs.len());
+               let holder_htlc_key = derive_private_key(secp_ctx, &inner.keys.per_commitment_point, htlc_base_key).map_err(|_| ())?;
+
+               for this_htlc in inner.htlcs.iter() {
+                       assert!(this_htlc.transaction_output_index.is_some());
+                       let htlc_tx = build_htlc_transaction(&txid, inner.feerate_per_kw, channel_parameters.contest_delay(), &this_htlc, &keys.broadcaster_delayed_payment_key, &keys.revocation_key);
+
+                       let htlc_redeemscript = get_htlc_redeemscript_with_explicit_keys(&this_htlc, &keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key);
+
+                       let sighash = hash_to_message!(&bip143::SigHashCache::new(&htlc_tx).signature_hash(0, &htlc_redeemscript, this_htlc.amount_msat / 1000, SigHashType::All)[..]);
+                       ret.push(secp_ctx.sign(&sighash, &holder_htlc_key));
                }
                Ok(ret)
        }
 
        /// Gets a signed HTLC transaction given a preimage (for !htlc.offered) and the holder HTLC transaction signature.
-       pub(crate) fn get_signed_htlc_tx(&self, htlc_index: usize, signature: &Signature, preimage: &Option<PaymentPreimage>, counterparty_selected_contest_delay: u16) -> Transaction {
-               let txid = self.txid();
-               let this_htlc = &self.per_htlc[htlc_index];
-               assert!(this_htlc.0.transaction_output_index.is_some());
+       pub(crate) fn get_signed_htlc_tx(&self, channel_parameters: &DirectedChannelTransactionParameters, htlc_index: usize, counterparty_signature: &Signature, signature: &Signature, preimage: &Option<PaymentPreimage>) -> Transaction {
+               let inner = self.inner;
+               let keys = &inner.keys;
+               let txid = inner.built.txid;
+               let this_htlc = &inner.htlcs[htlc_index];
+               assert!(this_htlc.transaction_output_index.is_some());
                // if we don't have preimage for an HTLC-Success, we can't generate an HTLC transaction.
-               if !this_htlc.0.offered && preimage.is_none() { unreachable!(); }
+               if !this_htlc.offered && preimage.is_none() { unreachable!(); }
                // Further, we should never be provided the preimage for an HTLC-Timeout transaction.
-               if  this_htlc.0.offered && preimage.is_some() { unreachable!(); }
+               if  this_htlc.offered && preimage.is_some() { unreachable!(); }
 
-               let mut htlc_tx = build_htlc_transaction(&txid, self.feerate_per_kw, counterparty_selected_contest_delay, &this_htlc.0, &self.keys.broadcaster_delayed_payment_key, &self.keys.revocation_key);
-               // Channel should have checked that we have a counterparty signature for this HTLC at
-               // creation, and we should have a sensible htlc transaction:
-               assert!(this_htlc.1.is_some());
+               let mut htlc_tx = build_htlc_transaction(&txid, inner.feerate_per_kw, channel_parameters.contest_delay(), &this_htlc, &keys.broadcaster_delayed_payment_key, &keys.revocation_key);
 
-               let htlc_redeemscript = get_htlc_redeemscript_with_explicit_keys(&this_htlc.0, &self.keys.broadcaster_htlc_key, &self.keys.countersignatory_htlc_key, &self.keys.revocation_key);
+               let htlc_redeemscript = get_htlc_redeemscript_with_explicit_keys(&this_htlc, &keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key);
 
                // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
                htlc_tx.input[0].witness.push(Vec::new());
 
-               htlc_tx.input[0].witness.push(this_htlc.1.unwrap().serialize_der().to_vec());
+               htlc_tx.input[0].witness.push(counterparty_signature.serialize_der().to_vec());
                htlc_tx.input[0].witness.push(signature.serialize_der().to_vec());
                htlc_tx.input[0].witness[1].push(SigHashType::All as u8);
                htlc_tx.input[0].witness[2].push(SigHashType::All as u8);
 
-               if this_htlc.0.offered {
+               if this_htlc.offered {
                        // Due to BIP146 (MINIMALIF) this must be a zero-length element to relay.
                        htlc_tx.input[0].witness.push(Vec::new());
                } else {
@@ -753,66 +1194,36 @@ impl HolderCommitmentTransaction {
                htlc_tx
        }
 }
-impl PartialEq for HolderCommitmentTransaction {
-       // We dont care whether we are signed in equality comparison
-       fn eq(&self, o: &Self) -> bool {
-               self.txid() == o.txid()
-       }
-}
-impl Writeable for HolderCommitmentTransaction {
-       fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
-               if let Err(e) = self.unsigned_tx.consensus_encode(&mut WriterWriteAdaptor(writer)) {
-                       match e {
-                               encode::Error::Io(e) => return Err(e),
-                               _ => panic!("holder tx must have been well-formed!"),
-                       }
-               }
-               self.counterparty_sig.write(writer)?;
-               self.holder_sig_first.write(writer)?;
-               self.keys.write(writer)?;
-               self.feerate_per_kw.write(writer)?;
-               writer.write_all(&byte_utils::be64_to_array(self.per_htlc.len() as u64))?;
-               for &(ref htlc, ref sig) in self.per_htlc.iter() {
-                       htlc.write(writer)?;
-                       sig.write(writer)?;
-               }
-               Ok(())
+
+/// Get the transaction number obscure factor
+pub fn get_commitment_transaction_number_obscure_factor(
+       broadcaster_payment_basepoint: &PublicKey,
+       countersignatory_payment_basepoint: &PublicKey,
+       outbound_from_broadcaster: bool,
+) -> u64 {
+       let mut sha = Sha256::engine();
+
+       if outbound_from_broadcaster {
+               sha.input(&broadcaster_payment_basepoint.serialize());
+               sha.input(&countersignatory_payment_basepoint.serialize());
+       } else {
+               sha.input(&countersignatory_payment_basepoint.serialize());
+               sha.input(&broadcaster_payment_basepoint.serialize());
        }
+       let res = Sha256::from_engine(sha).into_inner();
+
+       ((res[26] as u64) << 5 * 8)
+               | ((res[27] as u64) << 4 * 8)
+               | ((res[28] as u64) << 3 * 8)
+               | ((res[29] as u64) << 2 * 8)
+               | ((res[30] as u64) << 1 * 8)
+               | ((res[31] as u64) << 0 * 8)
 }
-impl Readable for HolderCommitmentTransaction {
-       fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
-               let unsigned_tx = match Transaction::consensus_decode(reader.by_ref()) {
-                       Ok(tx) => tx,
-                       Err(e) => match e {
-                               encode::Error::Io(ioe) => return Err(DecodeError::Io(ioe)),
-                               _ => return Err(DecodeError::InvalidValue),
-                       },
-               };
-               let counterparty_sig = Readable::read(reader)?;
-               let holder_sig_first = Readable::read(reader)?;
-               let keys = Readable::read(reader)?;
-               let feerate_per_kw = Readable::read(reader)?;
-               let htlcs_count: u64 = Readable::read(reader)?;
-               let mut per_htlc = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / mem::size_of::<(HTLCOutputInCommitment, Option<Signature>)>()));
-               for _ in 0..htlcs_count {
-                       let htlc: HTLCOutputInCommitment = Readable::read(reader)?;
-                       let sigs = Readable::read(reader)?;
-                       per_htlc.push((htlc, sigs));
-               }
 
-               if unsigned_tx.input.len() != 1 {
-                       // Ensure tx didn't hit the 0-input ambiguity case.
-                       return Err(DecodeError::InvalidValue);
-               }
-               Ok(Self {
-                       unsigned_tx,
-                       counterparty_sig,
-                       holder_sig_first,
-                       keys,
-                       feerate_per_kw,
-                       per_htlc,
-               })
-       }
+fn script_for_p2wpkh(key: &PublicKey) -> Script {
+       Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
+               .push_slice(&WPubkeyHash::hash(&key.serialize())[..])
+               .into_script()
 }
 
 #[cfg(test)]
index 689c3496de16ebfd83fdc782d7ddec931d36b0f9..3ed84de95ae493f355abab0fb57cd57b6b01cf8d 100644 (file)
@@ -23,10 +23,10 @@ use ln::features::InitFeatures;
 use ln::msgs;
 use ln::msgs::{ChannelMessageHandler, ErrorAction, RoutingMessageHandler};
 use routing::router::get_route;
-use util::enforcing_trait_impls::EnforcingChannelKeys;
+use util::enforcing_trait_impls::EnforcingSigner;
 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
 use util::errors::APIError;
-use util::ser::Readable;
+use util::ser::{ReadableArgs, Writeable};
 
 use bitcoin::hashes::sha256::Hash as Sha256;
 use bitcoin::hashes::Hash;
@@ -102,14 +102,14 @@ fn test_monitor_and_persister_update_fail() {
        let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
        let persister = test_utils::TestPersister::new();
        let chain_mon = {
-               let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
+               let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
                let monitor = monitors.get(&outpoint).unwrap();
                let mut w = test_utils::TestVecWriter(Vec::new());
-               monitor.serialize_for_disk(&mut w).unwrap();
-               let new_monitor = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(
-                       &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
+               monitor.write(&mut w).unwrap();
+               let new_monitor = <(Option<BlockHash>, ChannelMonitor<EnforcingSigner>)>::read(
+                       &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
                assert!(new_monitor == *monitor);
-               let chain_mon = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister);
+               let chain_mon = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
                assert!(chain_mon.watch_channel(outpoint, new_monitor).is_ok());
                chain_mon
        };
@@ -239,7 +239,7 @@ fn do_test_simple_monitor_temporary_update_fail(disconnect: bool, persister_fail
        }
 
        // ...and make sure we can force-close a frozen channel
-       nodes[0].node.force_close_channel(&channel_id);
+       nodes[0].node.force_close_channel(&channel_id).unwrap();
        check_added_monitors!(nodes[0], 1);
        check_closed_broadcast!(nodes[0], false);
 
index 3c8be717f3237edc56297d559c806bdb96d80780..633652222d11352f64be2f1f13a75d543e07eca4 100644 (file)
@@ -14,7 +14,7 @@ use bitcoin::blockdata::opcodes;
 use bitcoin::util::bip143;
 use bitcoin::consensus::encode;
 
-use bitcoin::hashes::{Hash, HashEngine};
+use bitcoin::hashes::Hash;
 use bitcoin::hashes::sha256::Hash as Sha256;
 use bitcoin::hash_types::{Txid, BlockHash, WPubkeyHash};
 
@@ -26,14 +26,14 @@ use ln::features::{ChannelFeatures, InitFeatures};
 use ln::msgs;
 use ln::msgs::{DecodeError, OptionalField, DataLossProtect};
 use ln::channelmanager::{PendingHTLCStatus, HTLCSource, HTLCFailReason, HTLCFailureMsg, PendingHTLCInfo, RAACommitmentOrder, PaymentPreimage, PaymentHash, BREAKDOWN_TIMEOUT, MAX_LOCAL_BREAKDOWN_TIMEOUT};
-use ln::chan_utils::{CounterpartyCommitmentSecrets, HolderCommitmentTransaction, TxCreationKeys, HTLCOutputInCommitment, HTLC_SUCCESS_TX_WEIGHT, HTLC_TIMEOUT_TX_WEIGHT, make_funding_redeemscript, ChannelPublicKeys, PreCalculatedTxCreationKeys};
+use ln::chan_utils::{CounterpartyCommitmentSecrets, TxCreationKeys, HTLCOutputInCommitment, HTLC_SUCCESS_TX_WEIGHT, HTLC_TIMEOUT_TX_WEIGHT, make_funding_redeemscript, ChannelPublicKeys, CommitmentTransaction, HolderCommitmentTransaction, ChannelTransactionParameters, CounterpartyChannelTransactionParameters, MAX_HTLCS, get_commitment_transaction_number_obscure_factor};
 use ln::chan_utils;
 use chain::chaininterface::{FeeEstimator,ConfirmationTarget};
 use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, HTLC_FAIL_BACK_BUFFER};
 use chain::transaction::{OutPoint, TransactionData};
-use chain::keysinterface::{ChannelKeys, KeysInterface};
+use chain::keysinterface::{Sign, KeysInterface};
 use util::transaction_utils;
-use util::ser::{Readable, Writeable, Writer};
+use util::ser::{Readable, ReadableArgs, Writeable, Writer, VecWriter};
 use util::logger::Logger;
 use util::errors::APIError;
 use util::config::{UserConfig,ChannelConfig};
@@ -42,7 +42,10 @@ use std;
 use std::default::Default;
 use std::{cmp,mem,fmt};
 use std::ops::Deref;
+#[cfg(any(test, feature = "fuzztarget"))]
+use std::sync::Mutex;
 use bitcoin::hashes::hex::ToHex;
+use bitcoin::blockdata::opcodes::all::OP_PUSHBYTES_0;
 
 #[cfg(test)]
 pub struct ChannelValueStat {
@@ -111,7 +114,7 @@ enum InboundHTLCState {
        /// anyway). That said, ChannelMonitor does this for us (see
        /// ChannelMonitor::would_broadcast_at_height) so we actually remove the HTLC from our own
        /// local state before then, once we're sure that the next commitment_signed and
-       /// ChannelMonitor::provide_latest_local_commitment_tx_info will not include this HTLC.
+       /// ChannelMonitor::provide_latest_local_commitment_tx will not include this HTLC.
        LocalRemoved(InboundHTLCRemovalReason),
 }
 
@@ -242,7 +245,7 @@ enum ChannelState {
 const BOTH_SIDES_SHUTDOWN_MASK: u32 = ChannelState::LocalShutdownSent as u32 | ChannelState::RemoteShutdownSent as u32;
 const MULTI_STATE_FLAGS: u32 = BOTH_SIDES_SHUTDOWN_MASK | ChannelState::PeerDisconnected as u32 | ChannelState::MonitorUpdateFailed as u32;
 
-const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
+pub const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
 
 /// Liveness is called to fluctuate given peer disconnecton/monitor failures/closing.
 /// If channel is public, network should have a liveness view announced by us on a
@@ -258,6 +261,27 @@ enum UpdateStatus {
        DisabledStaged,
 }
 
+/// An enum indicating whether the local or remote side offered a given HTLC.
+enum HTLCInitiator {
+       LocalOffered,
+       RemoteOffered,
+}
+
+/// Used when calculating whether we or the remote can afford an additional HTLC.
+struct HTLCCandidate {
+       amount_msat: u64,
+       origin: HTLCInitiator,
+}
+
+impl HTLCCandidate {
+       fn new(amount_msat: u64, origin: HTLCInitiator) -> Self {
+               Self {
+                       amount_msat,
+                       origin,
+               }
+       }
+}
+
 // TODO: We should refactor this to be an Inbound/OutboundChannel until initial setup handshaking
 // has been completed, and then turn into a Channel to get compiler-time enforcement of things like
 // calling channel_id() before we're set up or things like get_outbound_funding_signed on an
@@ -265,23 +289,19 @@ enum UpdateStatus {
 //
 // Holder designates channel data owned for the benefice of the user client.
 // Counterparty designates channel data owned by the another channel participant entity.
-pub(super) struct Channel<ChanSigner: ChannelKeys> {
+pub(super) struct Channel<Signer: Sign> {
        config: ChannelConfig,
 
        user_id: u64,
 
        channel_id: [u8; 32],
        channel_state: u32,
-       channel_outbound: bool,
        secp_ctx: Secp256k1<secp256k1::All>,
        channel_value_satoshis: u64,
 
        latest_monitor_update_id: u64,
 
-       #[cfg(not(test))]
-       holder_keys: ChanSigner,
-       #[cfg(test)]
-       pub(super) holder_keys: ChanSigner,
+       holder_signer: Signer,
        shutdown_pubkey: PublicKey,
        destination_script: Script,
 
@@ -342,8 +362,6 @@ pub(super) struct Channel<ChanSigner: ChannelKeys> {
 
        last_sent_closing_fee: Option<(u32, u64, Signature)>, // (feerate, fee, holder_sig)
 
-       funding_txo: Option<OutPoint>,
-
        /// The hash of the block in which the funding transaction reached our CONF_TARGET. We use this
        /// to detect unconfirmation after a serialize-unserialize roundtrip where we may not see a full
        /// series of block_connected/block_disconnected calls. Obviously this is not a guarantee as we
@@ -370,8 +388,6 @@ pub(super) struct Channel<ChanSigner: ChannelKeys> {
        // get_holder_selected_channel_reserve_satoshis(channel_value_sats: u64): u64
        counterparty_htlc_minimum_msat: u64,
        holder_htlc_minimum_msat: u64,
-       counterparty_selected_contest_delay: u16,
-       holder_selected_contest_delay: u16,
        #[cfg(test)]
        pub counterparty_max_accepted_htlcs: u16,
        #[cfg(not(test))]
@@ -379,7 +395,7 @@ pub(super) struct Channel<ChanSigner: ChannelKeys> {
        //implied by OUR_MAX_HTLCS: max_accepted_htlcs: u16,
        minimum_depth: u32,
 
-       counterparty_pubkeys: Option<ChannelPublicKeys>,
+       pub(crate) channel_transaction_parameters: ChannelTransactionParameters,
 
        counterparty_cur_commitment_point: Option<PublicKey>,
 
@@ -391,6 +407,24 @@ pub(super) struct Channel<ChanSigner: ChannelKeys> {
        commitment_secrets: CounterpartyCommitmentSecrets,
 
        network_sync: UpdateStatus,
+
+       // We save these values so we can make sure `next_local_commit_tx_fee_msat` and
+       // `next_remote_commit_tx_fee_msat` properly predict what the next commitment transaction fee will
+       // be, by comparing the cached values to the fee of the tranaction generated by
+       // `build_commitment_transaction`.
+       #[cfg(any(test, feature = "fuzztarget"))]
+       next_local_commitment_tx_fee_info_cached: Mutex<Option<CommitmentTxInfoCached>>,
+       #[cfg(any(test, feature = "fuzztarget"))]
+       next_remote_commitment_tx_fee_info_cached: Mutex<Option<CommitmentTxInfoCached>>,
+}
+
+#[cfg(any(test, feature = "fuzztarget"))]
+struct CommitmentTxInfoCached {
+       fee: u64,
+       total_pending_htlcs: usize,
+       next_holder_htlc_id: u64,
+       next_counterparty_htlc_id: u64,
+       feerate: u32,
 }
 
 pub const OUR_MAX_HTLCS: u16 = 50; //TODO
@@ -442,7 +476,7 @@ macro_rules! secp_check {
        };
 }
 
-impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
+impl<Signer: Sign> Channel<Signer> {
        // Convert constants + channel value to limits:
        fn get_holder_max_htlc_value_in_flight_msat(channel_value_satoshis: u64) -> u64 {
                channel_value_satoshis * 1000 / 10 //TODO
@@ -462,12 +496,13 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
        }
 
        // Constructors:
-       pub fn new_outbound<K: Deref, F: Deref>(fee_estimator: &F, keys_provider: &K, counterparty_node_id: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64, config: &UserConfig) -> Result<Channel<ChanSigner>, APIError>
-       where K::Target: KeysInterface<ChanKeySigner = ChanSigner>,
+       pub fn new_outbound<K: Deref, F: Deref>(fee_estimator: &F, keys_provider: &K, counterparty_node_id: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64, config: &UserConfig) -> Result<Channel<Signer>, APIError>
+       where K::Target: KeysInterface<Signer = Signer>,
              F::Target: FeeEstimator,
        {
                let holder_selected_contest_delay = config.own_channel_config.our_to_self_delay;
-               let chan_keys = keys_provider.get_channel_keys(false, channel_value_satoshis);
+               let holder_signer = keys_provider.get_channel_signer(false, channel_value_satoshis);
+               let pubkeys = holder_signer.pubkeys().clone();
 
                if channel_value_satoshis >= MAX_FUNDING_SATOSHIS {
                        return Err(APIError::APIMisuseError{err: format!("funding_value must be smaller than {}, it was {}", MAX_FUNDING_SATOSHIS, channel_value_satoshis)});
@@ -480,25 +515,27 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                        return Err(APIError::APIMisuseError {err: format!("Configured with an unreasonable our_to_self_delay ({}) putting user funds at risks", holder_selected_contest_delay)});
                }
                let background_feerate = fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Background);
-               if Channel::<ChanSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_satoshis) < Channel::<ChanSigner>::derive_holder_dust_limit_satoshis(background_feerate) {
+               if Channel::<Signer>::get_holder_selected_channel_reserve_satoshis(channel_value_satoshis) < Channel::<Signer>::derive_holder_dust_limit_satoshis(background_feerate) {
                        return Err(APIError::FeeRateTooHigh{err: format!("Not enough reserve above dust limit can be found at current fee rate({})", background_feerate), feerate: background_feerate});
                }
 
                let feerate = fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Normal);
 
+               let mut secp_ctx = Secp256k1::new();
+               secp_ctx.seeded_randomize(&keys_provider.get_secure_random_bytes());
+
                Ok(Channel {
                        user_id,
                        config: config.channel_options.clone(),
 
                        channel_id: keys_provider.get_secure_random_bytes(),
                        channel_state: ChannelState::OurInitSent as u32,
-                       channel_outbound: true,
-                       secp_ctx: Secp256k1::new(),
+                       secp_ctx,
                        channel_value_satoshis,
 
                        latest_monitor_update_id: 0,
 
-                       holder_keys: chan_keys,
+                       holder_signer,
                        shutdown_pubkey: keys_provider.get_shutdown_pubkey(),
                        destination_script: keys_provider.get_destination_script(),
 
@@ -530,7 +567,6 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
 
                        last_sent_closing_fee: None,
 
-                       funding_txo: None,
                        funding_tx_confirmed_in: None,
                        short_channel_id: None,
                        last_block_connected: Default::default(),
@@ -538,17 +574,21 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
 
                        feerate_per_kw: feerate,
                        counterparty_dust_limit_satoshis: 0,
-                       holder_dust_limit_satoshis: Channel::<ChanSigner>::derive_holder_dust_limit_satoshis(background_feerate),
+                       holder_dust_limit_satoshis: Channel::<Signer>::derive_holder_dust_limit_satoshis(background_feerate),
                        counterparty_max_htlc_value_in_flight_msat: 0,
                        counterparty_selected_channel_reserve_satoshis: 0,
                        counterparty_htlc_minimum_msat: 0,
                        holder_htlc_minimum_msat: if config.own_channel_config.our_htlc_minimum_msat == 0 { 1 } else { config.own_channel_config.our_htlc_minimum_msat },
-                       counterparty_selected_contest_delay: 0,
-                       holder_selected_contest_delay,
                        counterparty_max_accepted_htlcs: 0,
                        minimum_depth: 0, // Filled in in accept_channel
 
-                       counterparty_pubkeys: None,
+                       channel_transaction_parameters: ChannelTransactionParameters {
+                               holder_pubkeys: pubkeys,
+                               holder_selected_contest_delay: config.own_channel_config.our_to_self_delay,
+                               is_outbound_from_holder: true,
+                               counterparty_parameters: None,
+                               funding_outpoint: None
+                       },
                        counterparty_cur_commitment_point: None,
 
                        counterparty_prev_commitment_point: None,
@@ -559,6 +599,11 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                        commitment_secrets: CounterpartyCommitmentSecrets::new(),
 
                        network_sync: UpdateStatus::Fresh,
+
+                       #[cfg(any(test, feature = "fuzztarget"))]
+                       next_local_commitment_tx_fee_info_cached: Mutex::new(None),
+                       #[cfg(any(test, feature = "fuzztarget"))]
+                       next_remote_commitment_tx_fee_info_cached: Mutex::new(None),
                })
        }
 
@@ -578,11 +623,12 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
 
        /// Creates a new channel from a remote sides' request for one.
        /// Assumes chain_hash has already been checked and corresponds with what we expect!
-       pub fn new_from_req<K: Deref, F: Deref>(fee_estimator: &F, keys_provider: &K, counterparty_node_id: PublicKey, their_features: InitFeatures, msg: &msgs::OpenChannel, user_id: u64, config: &UserConfig) -> Result<Channel<ChanSigner>, ChannelError>
-               where K::Target: KeysInterface<ChanKeySigner = ChanSigner>,
+       pub fn new_from_req<K: Deref, F: Deref>(fee_estimator: &F, keys_provider: &K, counterparty_node_id: PublicKey, their_features: InitFeatures, msg: &msgs::OpenChannel, user_id: u64, config: &UserConfig) -> Result<Channel<Signer>, ChannelError>
+               where K::Target: KeysInterface<Signer = Signer>,
           F::Target: FeeEstimator
        {
-               let mut chan_keys = keys_provider.get_channel_keys(true, msg.funding_satoshis);
+               let holder_signer = keys_provider.get_channel_signer(true, msg.funding_satoshis);
+               let pubkeys = holder_signer.pubkeys().clone();
                let counterparty_pubkeys = ChannelPublicKeys {
                        funding_pubkey: msg.funding_pubkey,
                        revocation_basepoint: msg.revocation_basepoint,
@@ -590,7 +636,6 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                        delayed_payment_basepoint: msg.delayed_payment_basepoint,
                        htlc_basepoint: msg.htlc_basepoint
                };
-               chan_keys.on_accept(&counterparty_pubkeys, msg.to_self_delay, config.own_channel_config.our_to_self_delay);
                let mut local_config = (*config).channel_options.clone();
 
                if config.own_channel_config.our_to_self_delay < BREAKDOWN_TIMEOUT {
@@ -618,7 +663,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                if msg.htlc_minimum_msat >= full_channel_value_msat {
                        return Err(ChannelError::Close(format!("Minimum htlc value ({}) was larger than full channel value ({})", msg.htlc_minimum_msat, full_channel_value_msat)));
                }
-               Channel::<ChanSigner>::check_remote_fee(fee_estimator, msg.feerate_per_kw)?;
+               Channel::<Signer>::check_remote_fee(fee_estimator, msg.feerate_per_kw)?;
 
                let max_counterparty_selected_contest_delay = u16::min(config.peer_channel_config_limits.their_to_self_delay, MAX_LOCAL_BREAKDOWN_TIMEOUT);
                if msg.to_self_delay > max_counterparty_selected_contest_delay {
@@ -627,8 +672,8 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                if msg.max_accepted_htlcs < 1 {
                        return Err(ChannelError::Close("0 max_accepted_htlcs makes for a useless channel".to_owned()));
                }
-               if msg.max_accepted_htlcs > 483 {
-                       return Err(ChannelError::Close(format!("max_accepted_htlcs was {}. It must not be larger than 483", msg.max_accepted_htlcs)));
+               if msg.max_accepted_htlcs > MAX_HTLCS {
+                       return Err(ChannelError::Close(format!("max_accepted_htlcs was {}. It must not be larger than {}", msg.max_accepted_htlcs, MAX_HTLCS)));
                }
 
                // Now check against optional parameters as set by config...
@@ -667,8 +712,8 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
 
                let background_feerate = fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Background);
 
-               let holder_dust_limit_satoshis = Channel::<ChanSigner>::derive_holder_dust_limit_satoshis(background_feerate);
-               let holder_selected_channel_reserve_satoshis = Channel::<ChanSigner>::get_holder_selected_channel_reserve_satoshis(msg.funding_satoshis);
+               let holder_dust_limit_satoshis = Channel::<Signer>::derive_holder_dust_limit_satoshis(background_feerate);
+               let holder_selected_channel_reserve_satoshis = Channel::<Signer>::get_holder_selected_channel_reserve_satoshis(msg.funding_satoshis);
                if holder_selected_channel_reserve_satoshis < holder_dust_limit_satoshis {
                        return Err(ChannelError::Close(format!("Suitable channel reserve not found. remote_channel_reserve was ({}). dust_limit_satoshis is ({}).", holder_selected_channel_reserve_satoshis, holder_dust_limit_satoshis)));
                }
@@ -696,15 +741,14 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                let counterparty_shutdown_scriptpubkey = if their_features.supports_upfront_shutdown_script() {
                        match &msg.shutdown_scriptpubkey {
                                &OptionalField::Present(ref script) => {
-                                       // Peer is signaling upfront_shutdown and has provided a non-accepted scriptpubkey format. We enforce it while receiving shutdown msg
-                                       if script.is_p2pkh() || script.is_p2sh() || script.is_v0_p2wsh() || script.is_v0_p2wpkh() {
-                                               Some(script.clone())
                                        // Peer is signaling upfront_shutdown and has opt-out with a 0-length script. We don't enforce anything
-                                       } else if script.len() == 0 {
+                                       if script.len() == 0 {
                                                None
                                        // Peer is signaling upfront_shutdown and has provided a non-accepted scriptpubkey format. Fail the channel
-                                       } else {
+                                       } else if is_unsupported_shutdown_script(&their_features, script) {
                                                return Err(ChannelError::Close(format!("Peer is signaling upfront_shutdown but has provided a non-accepted scriptpubkey format. script: ({})", script.to_bytes().to_hex())));
+                                       } else {
+                                               Some(script.clone())
                                        }
                                },
                                // Peer is signaling upfront shutdown but don't opt-out with correct mechanism (a.k.a 0-length script). Peer looks buggy, we fail the channel
@@ -714,18 +758,20 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                        }
                } else { None };
 
+               let mut secp_ctx = Secp256k1::new();
+               secp_ctx.seeded_randomize(&keys_provider.get_secure_random_bytes());
+
                let chan = Channel {
                        user_id,
                        config: local_config,
 
                        channel_id: msg.temporary_channel_id,
                        channel_state: (ChannelState::OurInitSent as u32) | (ChannelState::TheirInitSent as u32),
-                       channel_outbound: false,
-                       secp_ctx: Secp256k1::new(),
+                       secp_ctx,
 
                        latest_monitor_update_id: 0,
 
-                       holder_keys: chan_keys,
+                       holder_signer,
                        shutdown_pubkey: keys_provider.get_shutdown_pubkey(),
                        destination_script: keys_provider.get_destination_script(),
 
@@ -757,7 +803,6 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
 
                        last_sent_closing_fee: None,
 
-                       funding_txo: None,
                        funding_tx_confirmed_in: None,
                        short_channel_id: None,
                        last_block_connected: Default::default(),
@@ -771,12 +816,19 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                        counterparty_selected_channel_reserve_satoshis: msg.channel_reserve_satoshis,
                        counterparty_htlc_minimum_msat: msg.htlc_minimum_msat,
                        holder_htlc_minimum_msat: if config.own_channel_config.our_htlc_minimum_msat == 0 { 1 } else { config.own_channel_config.our_htlc_minimum_msat },
-                       counterparty_selected_contest_delay: msg.to_self_delay,
-                       holder_selected_contest_delay: config.own_channel_config.our_to_self_delay,
                        counterparty_max_accepted_htlcs: msg.max_accepted_htlcs,
                        minimum_depth: config.own_channel_config.minimum_depth,
 
-                       counterparty_pubkeys: Some(counterparty_pubkeys),
+                       channel_transaction_parameters: ChannelTransactionParameters {
+                               holder_pubkeys: pubkeys,
+                               holder_selected_contest_delay: config.own_channel_config.our_to_self_delay,
+                               is_outbound_from_holder: false,
+                               counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
+                                       selected_contest_delay: msg.to_self_delay,
+                                       pubkeys: counterparty_pubkeys,
+                               }),
+                               funding_outpoint: None
+                       },
                        counterparty_cur_commitment_point: Some(msg.first_per_commitment_point),
 
                        counterparty_prev_commitment_point: None,
@@ -787,34 +839,16 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                        commitment_secrets: CounterpartyCommitmentSecrets::new(),
 
                        network_sync: UpdateStatus::Fresh,
+
+                       #[cfg(any(test, feature = "fuzztarget"))]
+                       next_local_commitment_tx_fee_info_cached: Mutex::new(None),
+                       #[cfg(any(test, feature = "fuzztarget"))]
+                       next_remote_commitment_tx_fee_info_cached: Mutex::new(None),
                };
 
                Ok(chan)
        }
 
-       // Utilities to build transactions:
-
-       fn get_commitment_transaction_number_obscure_factor(&self) -> u64 {
-               let mut sha = Sha256::engine();
-
-               let counterparty_payment_point = &self.counterparty_pubkeys.as_ref().unwrap().payment_point.serialize();
-               if self.channel_outbound {
-                       sha.input(&self.holder_keys.pubkeys().payment_point.serialize());
-                       sha.input(counterparty_payment_point);
-               } else {
-                       sha.input(counterparty_payment_point);
-                       sha.input(&self.holder_keys.pubkeys().payment_point.serialize());
-               }
-               let res = Sha256::from_engine(sha).into_inner();
-
-               ((res[26] as u64) << 5*8) |
-               ((res[27] as u64) << 4*8) |
-               ((res[28] as u64) << 3*8) |
-               ((res[29] as u64) << 2*8) |
-               ((res[30] as u64) << 1*8) |
-               ((res[31] as u64) << 0*8)
-       }
-
        /// Transaction nomenclature is somewhat confusing here as there are many different cases - a
        /// transaction is referred to as "a's transaction" implying that a will be able to broadcast
        /// the transaction. Thus, b will generally be sending a signature over such a transaction to
@@ -828,34 +862,22 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
        /// have not yet committed it. Such HTLCs will only be included in transactions which are being
        /// generated by the peer which proposed adding the HTLCs, and thus we need to understand both
        /// which peer generated this transaction and "to whom" this transaction flows.
-       /// Returns (the transaction built, the number of HTLC outputs which were present in the
+       /// Returns (the transaction info, the number of HTLC outputs which were present in the
        /// transaction, the list of HTLCs which were not ignored when building the transaction).
        /// Note that below-dust HTLCs are included in the third return value, but not the second, and
        /// sources are provided only for outbound HTLCs in the third return value.
        #[inline]
-       fn build_commitment_transaction<L: Deref>(&self, commitment_number: u64, keys: &TxCreationKeys, local: bool, generated_by_local: bool, feerate_per_kw: u32, logger: &L) -> (Transaction, usize, Vec<(HTLCOutputInCommitment, Option<&HTLCSource>)>) where L::Target: Logger {
-               let obscured_commitment_transaction_number = self.get_commitment_transaction_number_obscure_factor() ^ (INITIAL_COMMITMENT_NUMBER - commitment_number);
-
-               let txins = {
-                       let mut ins: Vec<TxIn> = Vec::new();
-                       ins.push(TxIn {
-                               previous_output: self.funding_txo.unwrap().into_bitcoin_outpoint(),
-                               script_sig: Script::new(),
-                               sequence: ((0x80 as u32) << 8*3) | ((obscured_commitment_transaction_number >> 3*8) as u32),
-                               witness: Vec::new(),
-                       });
-                       ins
-               };
-
-               let mut txouts: Vec<(TxOut, Option<(HTLCOutputInCommitment, Option<&HTLCSource>)>)> = Vec::with_capacity(self.pending_inbound_htlcs.len() + self.pending_outbound_htlcs.len() + 2);
+       fn build_commitment_transaction<L: Deref>(&self, commitment_number: u64, keys: &TxCreationKeys, local: bool, generated_by_local: bool, feerate_per_kw: u32, logger: &L) -> (CommitmentTransaction, usize, Vec<(HTLCOutputInCommitment, Option<&HTLCSource>)>) where L::Target: Logger {
                let mut included_dust_htlcs: Vec<(HTLCOutputInCommitment, Option<&HTLCSource>)> = Vec::new();
+               let num_htlcs = self.pending_inbound_htlcs.len() + self.pending_outbound_htlcs.len();
+               let mut included_non_dust_htlcs: Vec<(HTLCOutputInCommitment, Option<&HTLCSource>)> = Vec::with_capacity(num_htlcs);
 
                let broadcaster_dust_limit_satoshis = if local { self.holder_dust_limit_satoshis } else { self.counterparty_dust_limit_satoshis };
                let mut remote_htlc_total_msat = 0;
                let mut local_htlc_total_msat = 0;
                let mut value_to_self_msat_offset = 0;
 
-               log_trace!(logger, "Building commitment transaction number {} (really {} xor {}) for {}, generated by {} with fee {}...", commitment_number, (INITIAL_COMMITMENT_NUMBER - commitment_number), self.get_commitment_transaction_number_obscure_factor(), if local { "us" } else { "remote" }, if generated_by_local { "us" } else { "remote" }, feerate_per_kw);
+               log_trace!(logger, "Building commitment transaction number {} (really {} xor {}) for {}, generated by {} with fee {}...", commitment_number, (INITIAL_COMMITMENT_NUMBER - commitment_number), get_commitment_transaction_number_obscure_factor(&self.get_holder_pubkeys().payment_point, &self.get_counterparty_pubkeys().payment_point, self.is_outbound()), if local { "us" } else { "remote" }, if generated_by_local { "us" } else { "remote" }, feerate_per_kw);
 
                macro_rules! get_htlc_in_commitment {
                        ($htlc: expr, $offered: expr) => {
@@ -875,10 +897,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                                        let htlc_in_tx = get_htlc_in_commitment!($htlc, true);
                                        if $htlc.amount_msat / 1000 >= broadcaster_dust_limit_satoshis + (feerate_per_kw as u64 * HTLC_TIMEOUT_TX_WEIGHT / 1000) {
                                                log_trace!(logger, "   ...including {} {} HTLC {} (hash {}) with value {}", if $outbound { "outbound" } else { "inbound" }, $state_name, $htlc.htlc_id, log_bytes!($htlc.payment_hash.0), $htlc.amount_msat);
-                                               txouts.push((TxOut {
-                                                       script_pubkey: chan_utils::get_htlc_redeemscript(&htlc_in_tx, &keys).to_v0_p2wsh(),
-                                                       value: $htlc.amount_msat / 1000
-                                               }, Some((htlc_in_tx, $source))));
+                                               included_non_dust_htlcs.push((htlc_in_tx, $source));
                                        } else {
                                                log_trace!(logger, "   ...including {} {} dust HTLC {} (hash {}) with value {} due to dust limit", if $outbound { "outbound" } else { "inbound" }, $state_name, $htlc.htlc_id, log_bytes!($htlc.payment_hash.0), $htlc.amount_msat);
                                                included_dust_htlcs.push((htlc_in_tx, $source));
@@ -887,10 +906,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                                        let htlc_in_tx = get_htlc_in_commitment!($htlc, false);
                                        if $htlc.amount_msat / 1000 >= broadcaster_dust_limit_satoshis + (feerate_per_kw as u64 * HTLC_SUCCESS_TX_WEIGHT / 1000) {
                                                log_trace!(logger, "   ...including {} {} HTLC {} (hash {}) with value {}", if $outbound { "outbound" } else { "inbound" }, $state_name, $htlc.htlc_id, log_bytes!($htlc.payment_hash.0), $htlc.amount_msat);
-                                               txouts.push((TxOut { // "received HTLC output"
-                                                       script_pubkey: chan_utils::get_htlc_redeemscript(&htlc_in_tx, &keys).to_v0_p2wsh(),
-                                                       value: $htlc.amount_msat / 1000
-                                               }, Some((htlc_in_tx, $source))));
+                                               included_non_dust_htlcs.push((htlc_in_tx, $source));
                                        } else {
                                                log_trace!(logger, "   ...including {} {} dust HTLC {} (hash {}) with value {}", if $outbound { "outbound" } else { "inbound" }, $state_name, $htlc.htlc_id, log_bytes!($htlc.payment_hash.0), $htlc.amount_msat);
                                                included_dust_htlcs.push((htlc_in_tx, $source));
@@ -974,77 +990,51 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                        };
                        debug_assert!(broadcaster_max_commitment_tx_output.0 <= value_to_self_msat as u64 || value_to_self_msat / 1000 >= self.counterparty_selected_channel_reserve_satoshis as i64);
                        broadcaster_max_commitment_tx_output.0 = cmp::max(broadcaster_max_commitment_tx_output.0, value_to_self_msat as u64);
-                       debug_assert!(broadcaster_max_commitment_tx_output.1 <= value_to_remote_msat as u64 || value_to_remote_msat / 1000 >= Channel::<ChanSigner>::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis) as i64);
+                       debug_assert!(broadcaster_max_commitment_tx_output.1 <= value_to_remote_msat as u64 || value_to_remote_msat / 1000 >= Channel::<Signer>::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis) as i64);
                        broadcaster_max_commitment_tx_output.1 = cmp::max(broadcaster_max_commitment_tx_output.1, value_to_remote_msat as u64);
                }
 
-               let total_fee = feerate_per_kw as u64 * (COMMITMENT_TX_BASE_WEIGHT + (txouts.len() as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
-               let (value_to_self, value_to_remote) = if self.channel_outbound {
+               let total_fee = feerate_per_kw as u64 * (COMMITMENT_TX_BASE_WEIGHT + (included_non_dust_htlcs.len() as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
+               let (value_to_self, value_to_remote) = if self.is_outbound() {
                        (value_to_self_msat / 1000 - total_fee as i64, value_to_remote_msat / 1000)
                } else {
                        (value_to_self_msat / 1000, value_to_remote_msat / 1000 - total_fee as i64)
                };
 
-               let value_to_a = if local { value_to_self } else { value_to_remote };
-               let value_to_b = if local { value_to_remote } else { value_to_self };
+               let mut value_to_a = if local { value_to_self } else { value_to_remote };
+               let mut value_to_b = if local { value_to_remote } else { value_to_self };
 
                if value_to_a >= (broadcaster_dust_limit_satoshis as i64) {
                        log_trace!(logger, "   ...including {} output with value {}", if local { "to_local" } else { "to_remote" }, value_to_a);
-                       txouts.push((TxOut {
-                               script_pubkey: chan_utils::get_revokeable_redeemscript(&keys.revocation_key,
-                                                                                      if local { self.counterparty_selected_contest_delay } else { self.holder_selected_contest_delay },
-                                                                                      &keys.broadcaster_delayed_payment_key).to_v0_p2wsh(),
-                               value: value_to_a as u64
-                       }, None));
+               } else {
+                       value_to_a = 0;
                }
 
                if value_to_b >= (broadcaster_dust_limit_satoshis as i64) {
                        log_trace!(logger, "   ...including {} output with value {}", if local { "to_remote" } else { "to_local" }, value_to_b);
-                       let static_payment_pk = if local {
-                               self.counterparty_pubkeys.as_ref().unwrap().payment_point
-                       } else {
-                               self.holder_keys.pubkeys().payment_point
-                       }.serialize();
-                       txouts.push((TxOut {
-                               script_pubkey: Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
-                                                            .push_slice(&WPubkeyHash::hash(&static_payment_pk)[..])
-                                                            .into_script(),
-                               value: value_to_b as u64
-                       }, None));
-               }
-
-               transaction_utils::sort_outputs(&mut txouts, |a, b| {
-                       if let &Some(ref a_htlc) = a {
-                               if let &Some(ref b_htlc) = b {
-                                       a_htlc.0.cltv_expiry.cmp(&b_htlc.0.cltv_expiry)
-                                               // Note that due to hash collisions, we have to have a fallback comparison
-                                               // here for fuzztarget mode (otherwise at least chanmon_fail_consistency
-                                               // may fail)!
-                                               .then(a_htlc.0.payment_hash.0.cmp(&b_htlc.0.payment_hash.0))
-                               // For non-HTLC outputs, if they're copying our SPK we don't really care if we
-                               // close the channel due to mismatches - they're doing something dumb:
-                               } else { cmp::Ordering::Equal }
-                       } else { cmp::Ordering::Equal }
-               });
-
-               let mut outputs: Vec<TxOut> = Vec::with_capacity(txouts.len());
-               let mut htlcs_included: Vec<(HTLCOutputInCommitment, Option<&HTLCSource>)> = Vec::with_capacity(txouts.len() + included_dust_htlcs.len());
-               for (idx, mut out) in txouts.drain(..).enumerate() {
-                       outputs.push(out.0);
-                       if let Some((mut htlc, source_option)) = out.1.take() {
-                               htlc.transaction_output_index = Some(idx as u32);
-                               htlcs_included.push((htlc, source_option));
-                       }
+               } else {
+                       value_to_b = 0;
                }
-               let non_dust_htlc_count = htlcs_included.len();
+
+               let num_nondust_htlcs = included_non_dust_htlcs.len();
+
+               let channel_parameters =
+                       if local { self.channel_transaction_parameters.as_holder_broadcastable() }
+                       else { self.channel_transaction_parameters.as_counterparty_broadcastable() };
+               let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(commitment_number,
+                                                                            value_to_a as u64,
+                                                                            value_to_b as u64,
+                                                                            keys.clone(),
+                                                                            feerate_per_kw,
+                                                                            &mut included_non_dust_htlcs,
+                                                                            &channel_parameters
+               );
+               let mut htlcs_included = included_non_dust_htlcs;
+               // The unwrap is safe, because all non-dust HTLCs have been assigned an output index
+               htlcs_included.sort_unstable_by_key(|h| h.0.transaction_output_index.unwrap());
                htlcs_included.append(&mut included_dust_htlcs);
 
-               (Transaction {
-                       version: 2,
-                       lock_time: ((0x20 as u32) << 8*3) | ((obscured_commitment_transaction_number & 0xffffffu64) as u32),
-                       input: txins,
-                       output: outputs,
-               }, non_dust_htlc_count, htlcs_included)
+               (tx, num_nondust_htlcs, htlcs_included)
        }
 
        #[inline]
@@ -1085,7 +1075,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                let txins = {
                        let mut ins: Vec<TxIn> = Vec::new();
                        ins.push(TxIn {
-                               previous_output: self.funding_txo.unwrap().into_bitcoin_outpoint(),
+                               previous_output: self.funding_outpoint().into_bitcoin_outpoint(),
                                script_sig: Script::new(),
                                sequence: 0xffffffff,
                                witness: Vec::new(),
@@ -1098,14 +1088,14 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                let mut txouts: Vec<(TxOut, ())> = Vec::new();
 
                let mut total_fee_satoshis = proposed_total_fee_satoshis;
-               let value_to_self: i64 = (self.value_to_self_msat as i64) / 1000 - if self.channel_outbound { total_fee_satoshis as i64 } else { 0 };
-               let value_to_remote: i64 = ((self.channel_value_satoshis * 1000 - self.value_to_self_msat) as i64 / 1000) - if self.channel_outbound { 0 } else { total_fee_satoshis as i64 };
+               let value_to_self: i64 = (self.value_to_self_msat as i64) / 1000 - if self.is_outbound() { total_fee_satoshis as i64 } else { 0 };
+               let value_to_remote: i64 = ((self.channel_value_satoshis * 1000 - self.value_to_self_msat) as i64 / 1000) - if self.is_outbound() { 0 } else { total_fee_satoshis as i64 };
 
                if value_to_self < 0 {
-                       assert!(self.channel_outbound);
+                       assert!(self.is_outbound());
                        total_fee_satoshis += (-value_to_self) as u64;
                } else if value_to_remote < 0 {
-                       assert!(!self.channel_outbound);
+                       assert!(!self.is_outbound());
                        total_fee_satoshis += (-value_to_remote) as u64;
                }
 
@@ -1138,6 +1128,10 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                }, total_fee_satoshis)
        }
 
+       fn funding_outpoint(&self) -> OutPoint {
+               self.channel_transaction_parameters.funding_outpoint.unwrap()
+       }
+
        #[inline]
        /// Creates a set of keys for build_commitment_transaction to generate a transaction which our
        /// counterparty will sign (ie DO NOT send signatures over a transaction created by this to
@@ -1145,10 +1139,10 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
        /// The result is a transaction which we can revoke broadcastership of (ie a "local" transaction)
        /// TODO Some magic rust shit to compile-time check this?
        fn build_holder_transaction_keys(&self, commitment_number: u64) -> Result<TxCreationKeys, ChannelError> {
-               let per_commitment_point = self.holder_keys.get_per_commitment_point(commitment_number, &self.secp_ctx);
-               let delayed_payment_base = &self.holder_keys.pubkeys().delayed_payment_basepoint;
-               let htlc_basepoint = &self.holder_keys.pubkeys().htlc_basepoint;
-               let counterparty_pubkeys = self.counterparty_pubkeys.as_ref().unwrap();
+               let per_commitment_point = self.holder_signer.get_per_commitment_point(commitment_number, &self.secp_ctx);
+               let delayed_payment_base = &self.get_holder_pubkeys().delayed_payment_basepoint;
+               let htlc_basepoint = &self.get_holder_pubkeys().htlc_basepoint;
+               let counterparty_pubkeys = self.get_counterparty_pubkeys();
 
                Ok(secp_check!(TxCreationKeys::derive_new(&self.secp_ctx, &per_commitment_point, delayed_payment_base, htlc_basepoint, &counterparty_pubkeys.revocation_basepoint, &counterparty_pubkeys.htlc_basepoint), "Local tx keys generation got bogus keys".to_owned()))
        }
@@ -1160,9 +1154,9 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
        fn build_remote_transaction_keys(&self) -> Result<TxCreationKeys, ChannelError> {
                //TODO: Ensure that the payment_key derived here ends up in the library users' wallet as we
                //may see payments to it!
-               let revocation_basepoint = &self.holder_keys.pubkeys().revocation_basepoint;
-               let htlc_basepoint = &self.holder_keys.pubkeys().htlc_basepoint;
-               let counterparty_pubkeys = self.counterparty_pubkeys.as_ref().unwrap();
+               let revocation_basepoint = &self.get_holder_pubkeys().revocation_basepoint;
+               let htlc_basepoint = &self.get_holder_pubkeys().htlc_basepoint;
+               let counterparty_pubkeys = self.get_counterparty_pubkeys();
 
                Ok(secp_check!(TxCreationKeys::derive_new(&self.secp_ctx, &self.counterparty_cur_commitment_point.unwrap(), &counterparty_pubkeys.delayed_payment_basepoint, &counterparty_pubkeys.htlc_basepoint, revocation_basepoint, htlc_basepoint), "Remote tx keys generation got bogus keys".to_owned()))
        }
@@ -1171,14 +1165,14 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
        /// pays to get_funding_redeemscript().to_v0_p2wsh()).
        /// Panics if called before accept_channel/new_from_req
        pub fn get_funding_redeemscript(&self) -> Script {
-               make_funding_redeemscript(&self.holder_keys.pubkeys().funding_pubkey, self.counterparty_funding_pubkey())
+               make_funding_redeemscript(&self.get_holder_pubkeys().funding_pubkey, self.counterparty_funding_pubkey())
        }
 
        /// Builds the htlc-success or htlc-timeout transaction which spends a given HTLC output
        /// @local is used only to convert relevant internal structures which refer to remote vs local
        /// to decide value of outputs and direction of HTLCs.
        fn build_htlc_transaction(&self, prev_hash: &Txid, htlc: &HTLCOutputInCommitment, local: bool, keys: &TxCreationKeys, feerate_per_kw: u32) -> Transaction {
-               chan_utils::build_htlc_transaction(prev_hash, feerate_per_kw, if local { self.counterparty_selected_contest_delay } else { self.holder_selected_contest_delay }, htlc, &keys.broadcaster_delayed_payment_key, &keys.revocation_key)
+               chan_utils::build_htlc_transaction(prev_hash, feerate_per_kw, if local { self.get_counterparty_selected_contest_delay() } else { self.get_holder_selected_contest_delay() }, htlc, &keys.broadcaster_delayed_payment_key, &keys.revocation_key)
        }
 
        /// Per HTLC, only one get_update_fail_htlc or get_update_fulfill_htlc call may be made.
@@ -1388,7 +1382,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
 
        pub fn accept_channel(&mut self, msg: &msgs::AcceptChannel, config: &UserConfig, their_features: InitFeatures) -> Result<(), ChannelError> {
                // Check sanity of message fields:
-               if !self.channel_outbound {
+               if !self.is_outbound() {
                        return Err(ChannelError::Close("Got an accept_channel message from an inbound peer".to_owned()));
                }
                if self.channel_state != ChannelState::OurInitSent as u32 {
@@ -1406,7 +1400,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                if msg.channel_reserve_satoshis < self.holder_dust_limit_satoshis {
                        return Err(ChannelError::Close(format!("Peer never wants payout outputs? channel_reserve_satoshis was ({}). dust_limit is ({})", msg.channel_reserve_satoshis, self.holder_dust_limit_satoshis)));
                }
-               let remote_reserve = Channel::<ChanSigner>::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis);
+               let remote_reserve = Channel::<Signer>::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis);
                if msg.dust_limit_satoshis > remote_reserve {
                        return Err(ChannelError::Close(format!("Dust limit ({}) is bigger than our channel reserve ({})", msg.dust_limit_satoshis, remote_reserve)));
                }
@@ -1421,8 +1415,8 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                if msg.max_accepted_htlcs < 1 {
                        return Err(ChannelError::Close("0 max_accepted_htlcs makes for a useless channel".to_owned()));
                }
-               if msg.max_accepted_htlcs > 483 {
-                       return Err(ChannelError::Close(format!("max_accepted_htlcs was {}. It must not be larger than 483", msg.max_accepted_htlcs)));
+               if msg.max_accepted_htlcs > MAX_HTLCS {
+                       return Err(ChannelError::Close(format!("max_accepted_htlcs was {}. It must not be larger than {}", msg.max_accepted_htlcs, MAX_HTLCS)));
                }
 
                // Now check against optional parameters as set by config...
@@ -1451,15 +1445,14 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                let counterparty_shutdown_scriptpubkey = if their_features.supports_upfront_shutdown_script() {
                        match &msg.shutdown_scriptpubkey {
                                &OptionalField::Present(ref script) => {
-                                       // Peer is signaling upfront_shutdown and has provided a non-accepted scriptpubkey format. We enforce it while receiving shutdown msg
-                                       if script.is_p2pkh() || script.is_p2sh() || script.is_v0_p2wsh() || script.is_v0_p2wpkh() {
-                                               Some(script.clone())
                                        // Peer is signaling upfront_shutdown and has opt-out with a 0-length script. We don't enforce anything
-                                       } else if script.len() == 0 {
+                                       if script.len() == 0 {
                                                None
                                        // Peer is signaling upfront_shutdown and has provided a non-accepted scriptpubkey format. Fail the channel
+                                       } else if is_unsupported_shutdown_script(&their_features, script) {
+                                               return Err(ChannelError::Close(format!("Peer is signaling upfront_shutdown but has provided a non-accepted scriptpubkey format. script: ({})", script.to_bytes().to_hex())));
                                        } else {
-                                               return Err(ChannelError::Close(format!("Peer is signaling upfront_shutdown but has provided a non-accepted scriptpubkey format. scriptpubkey: ({})", script.to_bytes().to_hex())));
+                                               Some(script.clone())
                                        }
                                },
                                // Peer is signaling upfront shutdown but don't opt-out with correct mechanism (a.k.a 0-length script). Peer looks buggy, we fail the channel
@@ -1473,7 +1466,6 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                self.counterparty_max_htlc_value_in_flight_msat = cmp::min(msg.max_htlc_value_in_flight_msat, self.channel_value_satoshis * 1000);
                self.counterparty_selected_channel_reserve_satoshis = msg.channel_reserve_satoshis;
                self.counterparty_htlc_minimum_msat = msg.htlc_minimum_msat;
-               self.counterparty_selected_contest_delay = msg.to_self_delay;
                self.counterparty_max_accepted_htlcs = msg.max_accepted_htlcs;
                self.minimum_depth = msg.minimum_depth;
 
@@ -1485,8 +1477,10 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                        htlc_basepoint: msg.htlc_basepoint
                };
 
-               self.holder_keys.on_accept(&counterparty_pubkeys, msg.to_self_delay, self.holder_selected_contest_delay);
-               self.counterparty_pubkeys = Some(counterparty_pubkeys);
+               self.channel_transaction_parameters.counterparty_parameters = Some(CounterpartyChannelTransactionParameters {
+                       selected_contest_delay: msg.to_self_delay,
+                       pubkeys: counterparty_pubkeys,
+               });
 
                self.counterparty_cur_commitment_point = Some(msg.first_per_commitment_point);
                self.counterparty_shutdown_scriptpubkey = counterparty_shutdown_scriptpubkey;
@@ -1496,35 +1490,40 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                Ok(())
        }
 
-       fn funding_created_signature<L: Deref>(&mut self, sig: &Signature, logger: &L) -> Result<(Transaction, HolderCommitmentTransaction, Signature), ChannelError> where L::Target: Logger {
+       fn funding_created_signature<L: Deref>(&mut self, sig: &Signature, logger: &L) -> Result<(Txid, CommitmentTransaction, Signature), ChannelError> where L::Target: Logger {
                let funding_script = self.get_funding_redeemscript();
 
                let keys = self.build_holder_transaction_keys(self.cur_holder_commitment_transaction_number)?;
                let initial_commitment_tx = self.build_commitment_transaction(self.cur_holder_commitment_transaction_number, &keys, true, false, self.feerate_per_kw, logger).0;
-               let sighash = hash_to_message!(&bip143::SigHashCache::new(&initial_commitment_tx).signature_hash(0, &funding_script, self.channel_value_satoshis, SigHashType::All)[..]);
-
-               // They sign the "our" commitment transaction...
-               log_trace!(logger, "Checking funding_created tx signature {} by key {} against tx {} (sighash {}) with redeemscript {}", log_bytes!(sig.serialize_compact()[..]), log_bytes!(self.counterparty_funding_pubkey().serialize()), encode::serialize_hex(&initial_commitment_tx), log_bytes!(sighash[..]), encode::serialize_hex(&funding_script));
-               secp_check!(self.secp_ctx.verify(&sighash, &sig, self.counterparty_funding_pubkey()), "Invalid funding_created signature from peer".to_owned());
-
-               let tx = HolderCommitmentTransaction::new_missing_holder_sig(initial_commitment_tx, sig.clone(), &self.holder_keys.pubkeys().funding_pubkey, self.counterparty_funding_pubkey(), keys, self.feerate_per_kw, Vec::new());
+               {
+                       let trusted_tx = initial_commitment_tx.trust();
+                       let initial_commitment_bitcoin_tx = trusted_tx.built_transaction();
+                       let sighash = initial_commitment_bitcoin_tx.get_sighash_all(&funding_script, self.channel_value_satoshis);
+                       // They sign the holder commitment transaction...
+                       log_trace!(logger, "Checking funding_created tx signature {} by key {} against tx {} (sighash {}) with redeemscript {}", log_bytes!(sig.serialize_compact()[..]), log_bytes!(self.counterparty_funding_pubkey().serialize()), encode::serialize_hex(&initial_commitment_bitcoin_tx.transaction), log_bytes!(sighash[..]), encode::serialize_hex(&funding_script));
+                       secp_check!(self.secp_ctx.verify(&sighash, &sig, self.counterparty_funding_pubkey()), "Invalid funding_created signature from peer".to_owned());
+               }
 
                let counterparty_keys = self.build_remote_transaction_keys()?;
                let counterparty_initial_commitment_tx = self.build_commitment_transaction(self.cur_counterparty_commitment_transaction_number, &counterparty_keys, false, false, self.feerate_per_kw, logger).0;
-               let pre_remote_keys = PreCalculatedTxCreationKeys::new(counterparty_keys);
-               let counterparty_signature = self.holder_keys.sign_counterparty_commitment(self.feerate_per_kw, &counterparty_initial_commitment_tx, &pre_remote_keys, &Vec::new(), &self.secp_ctx)
+
+               let counterparty_trusted_tx = counterparty_initial_commitment_tx.trust();
+               let counterparty_initial_bitcoin_tx = counterparty_trusted_tx.built_transaction();
+               log_trace!(logger, "Initial counterparty ID {} tx {}", counterparty_initial_bitcoin_tx.txid, encode::serialize_hex(&counterparty_initial_bitcoin_tx.transaction));
+
+               let counterparty_signature = self.holder_signer.sign_counterparty_commitment(&counterparty_initial_commitment_tx, &self.secp_ctx)
                                .map_err(|_| ChannelError::Close("Failed to get signatures for new commitment_signed".to_owned()))?.0;
 
                // We sign "counterparty" commitment transaction, allowing them to broadcast the tx if they wish.
-               Ok((counterparty_initial_commitment_tx, tx, counterparty_signature))
+               Ok((counterparty_initial_bitcoin_tx.txid, initial_commitment_tx, counterparty_signature))
        }
 
        fn counterparty_funding_pubkey(&self) -> &PublicKey {
-               &self.counterparty_pubkeys.as_ref().expect("funding_pubkey() only allowed after accept_channel").funding_pubkey
+               &self.get_counterparty_pubkeys().funding_pubkey
        }
 
-       pub fn funding_created<L: Deref>(&mut self, msg: &msgs::FundingCreated, logger: &L) -> Result<(msgs::FundingSigned, ChannelMonitor<ChanSigner>), ChannelError> where L::Target: Logger {
-               if self.channel_outbound {
+       pub fn funding_created<L: Deref>(&mut self, msg: &msgs::FundingCreated, logger: &L) -> Result<(msgs::FundingSigned, ChannelMonitor<Signer>), ChannelError> where L::Target: Logger {
+               if self.is_outbound() {
                        return Err(ChannelError::Close("Received funding_created for an outbound channel?".to_owned()));
                }
                if self.channel_state != (ChannelState::OurInitSent as u32 | ChannelState::TheirInitSent as u32) {
@@ -1539,38 +1538,47 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                        panic!("Should not have advanced channel commitment tx numbers prior to funding_created");
                }
 
-               let funding_txo = OutPoint{ txid: msg.funding_txid, index: msg.funding_output_index };
-               self.funding_txo = Some(funding_txo.clone());
+               let funding_txo = OutPoint { txid: msg.funding_txid, index: msg.funding_output_index };
+               self.channel_transaction_parameters.funding_outpoint = Some(funding_txo);
+               // This is an externally observable change before we finish all our checks.  In particular
+               // funding_created_signature may fail.
+               self.holder_signer.ready_channel(&self.channel_transaction_parameters);
 
-               let (counterparty_initial_commitment_tx, initial_commitment_tx, signature) = match self.funding_created_signature(&msg.signature, logger) {
+               let (counterparty_initial_commitment_txid, initial_commitment_tx, signature) = match self.funding_created_signature(&msg.signature, logger) {
                        Ok(res) => res,
+                       Err(ChannelError::Close(e)) => {
+                               self.channel_transaction_parameters.funding_outpoint = None;
+                               return Err(ChannelError::Close(e));
+                       },
                        Err(e) => {
-                               self.funding_txo = None;
-                               return Err(e);
+                               // The only error we know how to handle is ChannelError::Close, so we fall over here
+                               // to make sure we don't continue with an inconsistent state.
+                               panic!("unexpected error type from funding_created_signature {:?}", e);
                        }
                };
 
+               let holder_commitment_tx = HolderCommitmentTransaction::new(
+                       initial_commitment_tx,
+                       msg.signature,
+                       Vec::new(),
+                       &self.get_holder_pubkeys().funding_pubkey,
+                       self.counterparty_funding_pubkey()
+               );
+
                // Now that we're past error-generating stuff, update our local state:
 
-               let counterparty_pubkeys = self.counterparty_pubkeys.as_ref().unwrap();
                let funding_redeemscript = self.get_funding_redeemscript();
                let funding_txo_script = funding_redeemscript.to_v0_p2wsh();
-               macro_rules! create_monitor {
-                       () => { {
-                               let mut channel_monitor = ChannelMonitor::new(self.holder_keys.clone(),
-                                                                             &self.shutdown_pubkey, self.holder_selected_contest_delay,
-                                                                             &self.destination_script, (funding_txo, funding_txo_script.clone()),
-                                                                             &counterparty_pubkeys.htlc_basepoint, &counterparty_pubkeys.delayed_payment_basepoint,
-                                                                             self.counterparty_selected_contest_delay, funding_redeemscript.clone(), self.channel_value_satoshis,
-                                                                             self.get_commitment_transaction_number_obscure_factor(),
-                                                                             initial_commitment_tx.clone());
-
-                               channel_monitor.provide_latest_counterparty_commitment_tx_info(&counterparty_initial_commitment_tx, Vec::new(), self.cur_counterparty_commitment_transaction_number, self.counterparty_cur_commitment_point.unwrap(), logger);
-                               channel_monitor
-                       } }
-               }
+               let obscure_factor = get_commitment_transaction_number_obscure_factor(&self.get_holder_pubkeys().payment_point, &self.get_counterparty_pubkeys().payment_point, self.is_outbound());
+               let channel_monitor = ChannelMonitor::new(self.secp_ctx.clone(), self.holder_signer.clone(),
+                                                         &self.shutdown_pubkey, self.get_holder_selected_contest_delay(),
+                                                         &self.destination_script, (funding_txo, funding_txo_script.clone()),
+                                                         &self.channel_transaction_parameters,
+                                                         funding_redeemscript.clone(), self.channel_value_satoshis,
+                                                         obscure_factor,
+                                                         holder_commitment_tx);
 
-               let channel_monitor = create_monitor!();
+               channel_monitor.provide_latest_counterparty_commitment_tx(counterparty_initial_commitment_txid, Vec::new(), self.cur_counterparty_commitment_transaction_number, self.counterparty_cur_commitment_point.unwrap(), logger);
 
                self.channel_state = ChannelState::FundingSent as u32;
                self.channel_id = funding_txo.to_channel_id();
@@ -1585,8 +1593,8 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
 
        /// Handles a funding_signed message from the remote end.
        /// If this call is successful, broadcast the funding transaction (and not before!)
-       pub fn funding_signed<L: Deref>(&mut self, msg: &msgs::FundingSigned, logger: &L) -> Result<ChannelMonitor<ChanSigner>, ChannelError> where L::Target: Logger {
-               if !self.channel_outbound {
+       pub fn funding_signed<L: Deref>(&mut self, msg: &msgs::FundingSigned, logger: &L) -> Result<ChannelMonitor<Signer>, ChannelError> where L::Target: Logger {
+               if !self.is_outbound() {
                        return Err(ChannelError::Close("Received funding_signed for an inbound channel?".to_owned()));
                }
                if self.channel_state & !(ChannelState::MonitorUpdateFailed as u32) != ChannelState::FundingCreated as u32 {
@@ -1602,40 +1610,45 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
 
                let counterparty_keys = self.build_remote_transaction_keys()?;
                let counterparty_initial_commitment_tx = self.build_commitment_transaction(self.cur_counterparty_commitment_transaction_number, &counterparty_keys, false, false, self.feerate_per_kw, logger).0;
+               let counterparty_trusted_tx = counterparty_initial_commitment_tx.trust();
+               let counterparty_initial_bitcoin_tx = counterparty_trusted_tx.built_transaction();
 
-               let holder_keys = self.build_holder_transaction_keys(self.cur_holder_commitment_transaction_number)?;
-               let initial_commitment_tx = self.build_commitment_transaction(self.cur_holder_commitment_transaction_number, &holder_keys, true, false, self.feerate_per_kw, logger).0;
-               let sighash = hash_to_message!(&bip143::SigHashCache::new(&initial_commitment_tx).signature_hash(0, &funding_script, self.channel_value_satoshis, SigHashType::All)[..]);
-
-               let counterparty_funding_pubkey = &self.counterparty_pubkeys.as_ref().unwrap().funding_pubkey;
+               log_trace!(logger, "Initial counterparty ID {} tx {}", counterparty_initial_bitcoin_tx.txid, encode::serialize_hex(&counterparty_initial_bitcoin_tx.transaction));
 
-               // They sign our commitment transaction, allowing us to broadcast the tx if we wish.
-               if let Err(_) = self.secp_ctx.verify(&sighash, &msg.signature, counterparty_funding_pubkey) {
-                       return Err(ChannelError::Close("Invalid funding_signed signature from peer".to_owned()));
+               let holder_signer = self.build_holder_transaction_keys(self.cur_holder_commitment_transaction_number)?;
+               let initial_commitment_tx = self.build_commitment_transaction(self.cur_holder_commitment_transaction_number, &holder_signer, true, false, self.feerate_per_kw, logger).0;
+               {
+                       let trusted_tx = initial_commitment_tx.trust();
+                       let initial_commitment_bitcoin_tx = trusted_tx.built_transaction();
+                       let sighash = initial_commitment_bitcoin_tx.get_sighash_all(&funding_script, self.channel_value_satoshis);
+                       // They sign our commitment transaction, allowing us to broadcast the tx if we wish.
+                       if let Err(_) = self.secp_ctx.verify(&sighash, &msg.signature, &self.get_counterparty_pubkeys().funding_pubkey) {
+                               return Err(ChannelError::Close("Invalid funding_signed signature from peer".to_owned()));
+                       }
                }
 
-               let counterparty_pubkeys = self.counterparty_pubkeys.as_ref().unwrap();
+               let holder_commitment_tx = HolderCommitmentTransaction::new(
+                       initial_commitment_tx,
+                       msg.signature,
+                       Vec::new(),
+                       &self.get_holder_pubkeys().funding_pubkey,
+                       self.counterparty_funding_pubkey()
+               );
+
+
                let funding_redeemscript = self.get_funding_redeemscript();
-               let funding_txo = self.funding_txo.as_ref().unwrap();
+               let funding_txo = self.get_funding_txo().unwrap();
                let funding_txo_script = funding_redeemscript.to_v0_p2wsh();
-               macro_rules! create_monitor {
-                       () => { {
-                               let commitment_tx = HolderCommitmentTransaction::new_missing_holder_sig(initial_commitment_tx.clone(), msg.signature.clone(), &self.holder_keys.pubkeys().funding_pubkey, counterparty_funding_pubkey, holder_keys.clone(), self.feerate_per_kw, Vec::new());
-                               let mut channel_monitor = ChannelMonitor::new(self.holder_keys.clone(),
-                                                                             &self.shutdown_pubkey, self.holder_selected_contest_delay,
-                                                                             &self.destination_script, (funding_txo.clone(), funding_txo_script.clone()),
-                                                                             &counterparty_pubkeys.htlc_basepoint, &counterparty_pubkeys.delayed_payment_basepoint,
-                                                                             self.counterparty_selected_contest_delay, funding_redeemscript.clone(), self.channel_value_satoshis,
-                                                                             self.get_commitment_transaction_number_obscure_factor(),
-                                                                             commitment_tx);
-
-                               channel_monitor.provide_latest_counterparty_commitment_tx_info(&counterparty_initial_commitment_tx, Vec::new(), self.cur_counterparty_commitment_transaction_number, self.counterparty_cur_commitment_point.unwrap(), logger);
-
-                               channel_monitor
-                       } }
-               }
+               let obscure_factor = get_commitment_transaction_number_obscure_factor(&self.get_holder_pubkeys().payment_point, &self.get_counterparty_pubkeys().payment_point, self.is_outbound());
+               let channel_monitor = ChannelMonitor::new(self.secp_ctx.clone(), self.holder_signer.clone(),
+                                                         &self.shutdown_pubkey, self.get_holder_selected_contest_delay(),
+                                                         &self.destination_script, (funding_txo, funding_txo_script),
+                                                         &self.channel_transaction_parameters,
+                                                         funding_redeemscript.clone(), self.channel_value_satoshis,
+                                                         obscure_factor,
+                                                         holder_commitment_tx);
 
-               let channel_monitor = create_monitor!();
+               channel_monitor.provide_latest_counterparty_commitment_tx(counterparty_initial_bitcoin_tx.txid, Vec::new(), self.cur_counterparty_commitment_transaction_number, self.counterparty_cur_commitment_point.unwrap(), logger);
 
                assert_eq!(self.channel_state & (ChannelState::MonitorUpdateFailed as u32), 0); // We have no had any monitor(s) yet to fail update!
                self.channel_state = ChannelState::FundingSent as u32;
@@ -1724,63 +1737,172 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                (COMMITMENT_TX_BASE_WEIGHT + num_htlcs as u64 * COMMITMENT_TX_WEIGHT_PER_HTLC) * self.feerate_per_kw as u64 / 1000 * 1000
        }
 
-       // Get the commitment tx fee for the local (i.e our) next commitment transaction
-       // based on the number of pending HTLCs that are on track to be in our next
-       // commitment tx. `addl_htcs` is an optional parameter allowing the caller
-       // to add a number of additional HTLCs to the calculation. Note that dust
-       // HTLCs are excluded.
-       fn next_local_commit_tx_fee_msat(&self, addl_htlcs: usize) -> u64 {
-               assert!(self.channel_outbound);
+       // Get the commitment tx fee for the local's (i.e. our) next commitment transaction based on the
+       // number of pending HTLCs that are on track to be in our next commitment tx, plus an additional
+       // HTLC if `fee_spike_buffer_htlc` is Some, plus a new HTLC given by `new_htlc_amount`. Dust HTLCs
+       // are excluded.
+       fn next_local_commit_tx_fee_msat(&self, htlc: HTLCCandidate, fee_spike_buffer_htlc: Option<()>) -> u64 {
+               assert!(self.is_outbound());
+
+               let real_dust_limit_success_sat = (self.feerate_per_kw as u64 * HTLC_SUCCESS_TX_WEIGHT / 1000) + self.holder_dust_limit_satoshis;
+               let real_dust_limit_timeout_sat = (self.feerate_per_kw as u64 * HTLC_TIMEOUT_TX_WEIGHT / 1000) + self.holder_dust_limit_satoshis;
+
+               let mut addl_htlcs = 0;
+               if fee_spike_buffer_htlc.is_some() { addl_htlcs += 1; }
+               match htlc.origin {
+                       HTLCInitiator::LocalOffered => {
+                               if htlc.amount_msat / 1000 >= real_dust_limit_timeout_sat {
+                                       addl_htlcs += 1;
+                               }
+                       },
+                       HTLCInitiator::RemoteOffered => {
+                               if htlc.amount_msat / 1000 >= real_dust_limit_success_sat {
+                                       addl_htlcs += 1;
+                               }
+                       }
+               }
+
+               let mut included_htlcs = 0;
+               for ref htlc in self.pending_inbound_htlcs.iter() {
+                       if htlc.amount_msat / 1000 < real_dust_limit_success_sat {
+                               continue
+                       }
+                       // We include LocalRemoved HTLCs here because we may still need to broadcast a commitment
+                       // transaction including this HTLC if it times out before they RAA.
+                       included_htlcs += 1;
+               }
 
-               let mut their_acked_htlcs = self.pending_inbound_htlcs.len();
                for ref htlc in self.pending_outbound_htlcs.iter() {
-                       if htlc.amount_msat / 1000 <= self.holder_dust_limit_satoshis {
+                       if htlc.amount_msat / 1000 < real_dust_limit_timeout_sat {
                                continue
                        }
                        match htlc.state {
-                               OutboundHTLCState::Committed => their_acked_htlcs += 1,
-                               OutboundHTLCState::RemoteRemoved {..} => their_acked_htlcs += 1,
-                               OutboundHTLCState::LocalAnnounced {..} => their_acked_htlcs += 1,
+                               OutboundHTLCState::LocalAnnounced {..} => included_htlcs += 1,
+                               OutboundHTLCState::Committed => included_htlcs += 1,
+                               OutboundHTLCState::RemoteRemoved {..} => included_htlcs += 1,
+                               // We don't include AwaitingRemoteRevokeToRemove HTLCs because our next commitment
+                               // transaction won't be generated until they send us their next RAA, which will mean
+                               // dropping any HTLCs in this state.
                                _ => {},
                        }
                }
 
                for htlc in self.holding_cell_htlc_updates.iter() {
                        match htlc {
-                               &HTLCUpdateAwaitingACK::AddHTLC { .. } => their_acked_htlcs += 1,
-                               _ => {},
+                               &HTLCUpdateAwaitingACK::AddHTLC { amount_msat, .. } => {
+                                       if amount_msat / 1000 < real_dust_limit_timeout_sat {
+                                               continue
+                                       }
+                                       included_htlcs += 1
+                               },
+                               _ => {}, // Don't include claims/fails that are awaiting ack, because once we get the
+                                        // ack we're guaranteed to never include them in commitment txs anymore.
                        }
                }
 
-               self.commit_tx_fee_msat(their_acked_htlcs + addl_htlcs)
+               let num_htlcs = included_htlcs + addl_htlcs;
+               let res = self.commit_tx_fee_msat(num_htlcs);
+               #[cfg(any(test, feature = "fuzztarget"))]
+               {
+                       let mut fee = res;
+                       if fee_spike_buffer_htlc.is_some() {
+                               fee = self.commit_tx_fee_msat(num_htlcs - 1);
+                       }
+                       let total_pending_htlcs = self.pending_inbound_htlcs.len() + self.pending_outbound_htlcs.len()
+                               + self.holding_cell_htlc_updates.len();
+                       let commitment_tx_info = CommitmentTxInfoCached {
+                               fee,
+                               total_pending_htlcs,
+                               next_holder_htlc_id: match htlc.origin {
+                                       HTLCInitiator::LocalOffered => self.next_holder_htlc_id + 1,
+                                       HTLCInitiator::RemoteOffered => self.next_holder_htlc_id,
+                               },
+                               next_counterparty_htlc_id: match htlc.origin {
+                                       HTLCInitiator::LocalOffered => self.next_counterparty_htlc_id,
+                                       HTLCInitiator::RemoteOffered => self.next_counterparty_htlc_id + 1,
+                               },
+                               feerate: self.feerate_per_kw,
+                       };
+                       *self.next_local_commitment_tx_fee_info_cached.lock().unwrap() = Some(commitment_tx_info);
+               }
+               res
        }
 
-       // Get the commitment tx fee for the remote's next commitment transaction
-       // based on the number of pending HTLCs that are on track to be in their
-       // next commitment tx. `addl_htcs` is an optional parameter allowing the caller
-       // to add a number of additional HTLCs to the calculation. Note that dust HTLCs
-       // are excluded.
-       fn next_remote_commit_tx_fee_msat(&self, addl_htlcs: usize) -> u64 {
-               assert!(!self.channel_outbound);
+       // Get the commitment tx fee for the remote's next commitment transaction based on the number of
+       // pending HTLCs that are on track to be in their next commitment tx, plus an additional HTLC if
+       // `fee_spike_buffer_htlc` is Some, plus a new HTLC given by `new_htlc_amount`. Dust HTLCs are
+       // excluded.
+       fn next_remote_commit_tx_fee_msat(&self, htlc: HTLCCandidate, fee_spike_buffer_htlc: Option<()>) -> u64 {
+               assert!(!self.is_outbound());
+
+               let real_dust_limit_success_sat = (self.feerate_per_kw as u64 * HTLC_SUCCESS_TX_WEIGHT / 1000) + self.counterparty_dust_limit_satoshis;
+               let real_dust_limit_timeout_sat = (self.feerate_per_kw as u64 * HTLC_TIMEOUT_TX_WEIGHT / 1000) + self.counterparty_dust_limit_satoshis;
+
+               let mut addl_htlcs = 0;
+               if fee_spike_buffer_htlc.is_some() { addl_htlcs += 1; }
+               match htlc.origin {
+                       HTLCInitiator::LocalOffered => {
+                               if htlc.amount_msat / 1000 >= real_dust_limit_success_sat {
+                                       addl_htlcs += 1;
+                               }
+                       },
+                       HTLCInitiator::RemoteOffered => {
+                               if htlc.amount_msat / 1000 >= real_dust_limit_timeout_sat {
+                                       addl_htlcs += 1;
+                               }
+                       }
+               }
+
+               // When calculating the set of HTLCs which will be included in their next commitment_signed, all
+               // non-dust inbound HTLCs are included (as all states imply it will be included) and only
+               // committed outbound HTLCs, see below.
+               let mut included_htlcs = 0;
+               for ref htlc in self.pending_inbound_htlcs.iter() {
+                       if htlc.amount_msat / 1000 <= real_dust_limit_timeout_sat {
+                               continue
+                       }
+                       included_htlcs += 1;
+               }
 
-               // When calculating the set of HTLCs which will be included in their next
-               // commitment_signed, all inbound HTLCs are included (as all states imply it will be
-               // included) and only committed outbound HTLCs, see below.
-               let mut their_acked_htlcs = self.pending_inbound_htlcs.len();
                for ref htlc in self.pending_outbound_htlcs.iter() {
-                       if htlc.amount_msat / 1000 <= self.counterparty_dust_limit_satoshis {
+                       if htlc.amount_msat / 1000 <= real_dust_limit_success_sat {
                                continue
                        }
-                       // We only include outbound HTLCs if it will not be included in their next
-                       // commitment_signed, i.e. if they've responded to us with an RAA after announcement.
+                       // We only include outbound HTLCs if it will not be included in their next commitment_signed,
+                       // i.e. if they've responded to us with an RAA after announcement.
                        match htlc.state {
-                               OutboundHTLCState::Committed => their_acked_htlcs += 1,
-                               OutboundHTLCState::RemoteRemoved {..} => their_acked_htlcs += 1,
+                               OutboundHTLCState::Committed => included_htlcs += 1,
+                               OutboundHTLCState::RemoteRemoved {..} => included_htlcs += 1,
+                               OutboundHTLCState::LocalAnnounced { .. } => included_htlcs += 1,
                                _ => {},
                        }
                }
 
-               self.commit_tx_fee_msat(their_acked_htlcs + addl_htlcs)
+               let num_htlcs = included_htlcs + addl_htlcs;
+               let res = self.commit_tx_fee_msat(num_htlcs);
+               #[cfg(any(test, feature = "fuzztarget"))]
+               {
+                       let mut fee = res;
+                       if fee_spike_buffer_htlc.is_some() {
+                               fee = self.commit_tx_fee_msat(num_htlcs - 1);
+                       }
+                       let total_pending_htlcs = self.pending_inbound_htlcs.len() + self.pending_outbound_htlcs.len();
+                       let commitment_tx_info = CommitmentTxInfoCached {
+                               fee,
+                               total_pending_htlcs,
+                               next_holder_htlc_id: match htlc.origin {
+                                       HTLCInitiator::LocalOffered => self.next_holder_htlc_id + 1,
+                                       HTLCInitiator::RemoteOffered => self.next_holder_htlc_id,
+                               },
+                               next_counterparty_htlc_id: match htlc.origin {
+                                       HTLCInitiator::LocalOffered => self.next_counterparty_htlc_id,
+                                       HTLCInitiator::RemoteOffered => self.next_counterparty_htlc_id + 1,
+                               },
+                               feerate: self.feerate_per_kw,
+                       };
+                       *self.next_remote_commitment_tx_fee_info_cached.lock().unwrap() = Some(commitment_tx_info);
+               }
+               res
        }
 
        pub fn update_add_htlc<F, L: Deref>(&mut self, msg: &msgs::UpdateAddHTLC, mut pending_forward_status: PendingHTLCStatus, create_pending_htlc_status: F, logger: &L) -> Result<(), ChannelError>
@@ -1812,7 +1934,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                if inbound_htlc_count + 1 > OUR_MAX_HTLCS as u32 {
                        return Err(ChannelError::Close(format!("Remote tried to push more than our max accepted HTLCs ({})", OUR_MAX_HTLCS)));
                }
-               let holder_max_htlc_value_in_flight_msat = Channel::<ChanSigner>::get_holder_max_htlc_value_in_flight_msat(self.channel_value_satoshis);
+               let holder_max_htlc_value_in_flight_msat = Channel::<Signer>::get_holder_max_htlc_value_in_flight_msat(self.channel_value_satoshis);
                if htlc_inbound_value_msat + msg.amount_msat > holder_max_htlc_value_in_flight_msat {
                        return Err(ChannelError::Close(format!("Remote HTLC add would put them over our max HTLC value ({})", holder_max_htlc_value_in_flight_msat)));
                }
@@ -1847,29 +1969,31 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
 
                // Check that the remote can afford to pay for this HTLC on-chain at the current
                // feerate_per_kw, while maintaining their channel reserve (as required by the spec).
-               let remote_commit_tx_fee_msat = if self.channel_outbound { 0 } else {
-                       // +1 for this HTLC.
-                       self.next_remote_commit_tx_fee_msat(1)
+               let remote_commit_tx_fee_msat = if self.is_outbound() { 0 } else {
+                       let htlc_candidate = HTLCCandidate::new(msg.amount_msat, HTLCInitiator::RemoteOffered);
+                       self.next_remote_commit_tx_fee_msat(htlc_candidate, None) // Don't include the extra fee spike buffer HTLC in calculations
                };
                if pending_remote_value_msat - msg.amount_msat < remote_commit_tx_fee_msat {
                        return Err(ChannelError::Close("Remote HTLC add would not leave enough to pay for fees".to_owned()));
                };
 
                let chan_reserve_msat =
-                       Channel::<ChanSigner>::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis) * 1000;
+                       Channel::<Signer>::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis) * 1000;
                if pending_remote_value_msat - msg.amount_msat - remote_commit_tx_fee_msat < chan_reserve_msat {
                        return Err(ChannelError::Close("Remote HTLC add would put them under remote reserve value".to_owned()));
                }
 
-               if !self.channel_outbound {
-                       // `+1` for this HTLC, `2 *` and `+1` fee spike buffer we keep for the remote. This deviates from the
-                       // spec because in the spec, the fee spike buffer requirement doesn't exist on the receiver's side,
-                       // only on the sender's.
-                       // Note that when we eventually remove support for fee updates and switch to anchor output fees,
-                       // we will drop the `2 *`, since we no longer be as sensitive to fee spikes. But, keep the extra +1
-                       // as we should still be able to afford adding this HTLC plus one more future HTLC, regardless of
-                       // being sensitive to fee spikes.
-                       let remote_fee_cost_incl_stuck_buffer_msat = 2 * self.next_remote_commit_tx_fee_msat(1 + 1);
+               if !self.is_outbound() {
+                       // `2 *` and `Some(())` is for the fee spike buffer we keep for the remote. This deviates from
+                       // the spec because in the spec, the fee spike buffer requirement doesn't exist on the
+                       // receiver's side, only on the sender's.
+                       // Note that when we eventually remove support for fee updates and switch to anchor output
+                       // fees, we will drop the `2 *`, since we no longer be as sensitive to fee spikes. But, keep
+                       // the extra htlc when calculating the next remote commitment transaction fee as we should
+                       // still be able to afford adding this HTLC plus one more future HTLC, regardless of being
+                       // sensitive to fee spikes.
+                       let htlc_candidate = HTLCCandidate::new(msg.amount_msat, HTLCInitiator::RemoteOffered);
+                       let remote_fee_cost_incl_stuck_buffer_msat = 2 * self.next_remote_commit_tx_fee_msat(htlc_candidate, Some(()));
                        if pending_remote_value_msat - msg.amount_msat - chan_reserve_msat < remote_fee_cost_incl_stuck_buffer_msat {
                                // Note that if the pending_forward_status is not updated here, then it's because we're already failing
                                // the HTLC, i.e. its status is already set to failing.
@@ -1878,9 +2002,8 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                        }
                } else {
                        // Check that they won't violate our local required channel reserve by adding this HTLC.
-
-                       // +1 for this HTLC.
-                       let local_commit_tx_fee_msat = self.next_local_commit_tx_fee_msat(1);
+                       let htlc_candidate = HTLCCandidate::new(msg.amount_msat, HTLCInitiator::RemoteOffered);
+                       let local_commit_tx_fee_msat = self.next_local_commit_tx_fee_msat(htlc_candidate, None);
                        if self.value_to_self_msat < self.counterparty_selected_channel_reserve_satoshis * 1000 + local_commit_tx_fee_msat {
                                return Err(ChannelError::Close("Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_owned()));
                        }
@@ -1992,45 +2115,63 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                let keys = self.build_holder_transaction_keys(self.cur_holder_commitment_transaction_number).map_err(|e| (None, e))?;
 
                let mut update_fee = false;
-               let feerate_per_kw = if !self.channel_outbound && self.pending_update_fee.is_some() {
+               let feerate_per_kw = if !self.is_outbound() && self.pending_update_fee.is_some() {
                        update_fee = true;
                        self.pending_update_fee.unwrap()
                } else {
                        self.feerate_per_kw
                };
 
-               let mut commitment_tx = {
-                       let mut commitment_tx = self.build_commitment_transaction(self.cur_holder_commitment_transaction_number, &keys, true, false, feerate_per_kw, logger);
-                       let htlcs_cloned: Vec<_> = commitment_tx.2.drain(..).map(|htlc| (htlc.0, htlc.1.map(|h| h.clone()))).collect();
-                       (commitment_tx.0, commitment_tx.1, htlcs_cloned)
+               let (num_htlcs, mut htlcs_cloned, commitment_tx, commitment_txid) = {
+                       let commitment_tx = self.build_commitment_transaction(self.cur_holder_commitment_transaction_number, &keys, true, false, feerate_per_kw, logger);
+                       let commitment_txid = {
+                               let trusted_tx = commitment_tx.0.trust();
+                               let bitcoin_tx = trusted_tx.built_transaction();
+                               let sighash = bitcoin_tx.get_sighash_all(&funding_script, self.channel_value_satoshis);
+
+                               log_trace!(logger, "Checking commitment tx signature {} by key {} against tx {} (sighash {}) with redeemscript {}", log_bytes!(msg.signature.serialize_compact()[..]), log_bytes!(self.counterparty_funding_pubkey().serialize()), encode::serialize_hex(&bitcoin_tx.transaction), log_bytes!(sighash[..]), encode::serialize_hex(&funding_script));
+                               if let Err(_) = self.secp_ctx.verify(&sighash, &msg.signature, &self.counterparty_funding_pubkey()) {
+                                       return Err((None, ChannelError::Close("Invalid commitment tx signature from peer".to_owned())));
+                               }
+                               bitcoin_tx.txid
+                       };
+                       let htlcs_cloned: Vec<_> = commitment_tx.2.iter().map(|htlc| (htlc.0.clone(), htlc.1.map(|h| h.clone()))).collect();
+                       (commitment_tx.1, htlcs_cloned, commitment_tx.0, commitment_txid)
                };
-               let commitment_txid = commitment_tx.0.txid();
-               let sighash = hash_to_message!(&bip143::SigHashCache::new(&commitment_tx.0).signature_hash(0, &funding_script, self.channel_value_satoshis, SigHashType::All)[..]);
-               log_trace!(logger, "Checking commitment tx signature {} by key {} against tx {} (sighash {}) with redeemscript {}", log_bytes!(msg.signature.serialize_compact()[..]), log_bytes!(self.counterparty_funding_pubkey().serialize()), encode::serialize_hex(&commitment_tx.0), log_bytes!(sighash[..]), encode::serialize_hex(&funding_script));
-               if let Err(_) = self.secp_ctx.verify(&sighash, &msg.signature, &self.counterparty_funding_pubkey()) {
-                       return Err((None, ChannelError::Close("Invalid commitment tx signature from peer".to_owned())));
-               }
 
+               let total_fee = feerate_per_kw as u64 * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
                //If channel fee was updated by funder confirm funder can afford the new fee rate when applied to the current local commitment transaction
                if update_fee {
-                       let num_htlcs = commitment_tx.1;
-                       let total_fee = feerate_per_kw as u64 * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
-
-                       let counterparty_reserve_we_require = Channel::<ChanSigner>::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis);
+                       let counterparty_reserve_we_require = Channel::<Signer>::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis);
                        if self.channel_value_satoshis - self.value_to_self_msat / 1000 < total_fee + counterparty_reserve_we_require {
                                return Err((None, ChannelError::Close("Funding remote cannot afford proposed new fee".to_owned())));
                        }
                }
+               #[cfg(any(test, feature = "fuzztarget"))]
+               {
+                       if self.is_outbound() {
+                               let projected_commit_tx_info = self.next_local_commitment_tx_fee_info_cached.lock().unwrap().take();
+                               *self.next_remote_commitment_tx_fee_info_cached.lock().unwrap() = None;
+                               if let Some(info) = projected_commit_tx_info {
+                                       let total_pending_htlcs = self.pending_inbound_htlcs.len() + self.pending_outbound_htlcs.len()
+                                               + self.holding_cell_htlc_updates.len();
+                                       if info.total_pending_htlcs == total_pending_htlcs
+                                               && info.next_holder_htlc_id == self.next_holder_htlc_id
+                                               && info.next_counterparty_htlc_id == self.next_counterparty_htlc_id
+                                               && info.feerate == self.feerate_per_kw {
+                                                       assert_eq!(total_fee, info.fee / 1000);
+                                               }
+                               }
+                       }
+               }
 
-               if msg.htlc_signatures.len() != commitment_tx.1 {
-                       return Err((None, ChannelError::Close(format!("Got wrong number of HTLC signatures ({}) from remote. It must be {}", msg.htlc_signatures.len(), commitment_tx.1))));
+               if msg.htlc_signatures.len() != num_htlcs {
+                       return Err((None, ChannelError::Close(format!("Got wrong number of HTLC signatures ({}) from remote. It must be {}", msg.htlc_signatures.len(), num_htlcs))));
                }
 
-               // TODO: Merge these two, sadly they are currently both required to be passed separately to
-               // ChannelMonitor:
-               let mut htlcs_without_source = Vec::with_capacity(commitment_tx.2.len());
-               let mut htlcs_and_sigs = Vec::with_capacity(commitment_tx.2.len());
-               for (idx, (htlc, source)) in commitment_tx.2.drain(..).enumerate() {
+               // TODO: Sadly, we pass HTLCs twice to ChannelMonitor: once via the HolderCommitmentTransaction and once via the update
+               let mut htlcs_and_sigs = Vec::with_capacity(htlcs_cloned.len());
+               for (idx, (htlc, source)) in htlcs_cloned.drain(..).enumerate() {
                        if let Some(_) = htlc.transaction_output_index {
                                let htlc_tx = self.build_htlc_transaction(&commitment_txid, &htlc, true, &keys, feerate_per_kw);
                                let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, &keys);
@@ -2039,20 +2180,26 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                                if let Err(_) = self.secp_ctx.verify(&htlc_sighash, &msg.htlc_signatures[idx], &keys.countersignatory_htlc_key) {
                                        return Err((None, ChannelError::Close("Invalid HTLC tx signature from peer".to_owned())));
                                }
-                               htlcs_without_source.push((htlc.clone(), Some(msg.htlc_signatures[idx])));
                                htlcs_and_sigs.push((htlc, Some(msg.htlc_signatures[idx]), source));
                        } else {
-                               htlcs_without_source.push((htlc.clone(), None));
                                htlcs_and_sigs.push((htlc, None, source));
                        }
                }
 
-               let next_per_commitment_point = self.holder_keys.get_per_commitment_point(self.cur_holder_commitment_transaction_number - 1, &self.secp_ctx);
-               let per_commitment_secret = self.holder_keys.release_commitment_secret(self.cur_holder_commitment_transaction_number + 1);
+               let holder_commitment_tx = HolderCommitmentTransaction::new(
+                       commitment_tx,
+                       msg.signature,
+                       msg.htlc_signatures.clone(),
+                       &self.get_holder_pubkeys().funding_pubkey,
+                       self.counterparty_funding_pubkey()
+               );
+
+               let next_per_commitment_point = self.holder_signer.get_per_commitment_point(self.cur_holder_commitment_transaction_number - 1, &self.secp_ctx);
+               let per_commitment_secret = self.holder_signer.release_commitment_secret(self.cur_holder_commitment_transaction_number + 1);
 
                // Update state now that we've passed all the can-fail calls...
                let mut need_commitment = false;
-               if !self.channel_outbound {
+               if !self.is_outbound() {
                        if let Some(fee_update) = self.pending_update_fee {
                                self.feerate_per_kw = fee_update;
                                // We later use the presence of pending_update_fee to indicate we should generate a
@@ -2065,13 +2212,11 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                        }
                }
 
-               let counterparty_funding_pubkey = self.counterparty_pubkeys.as_ref().unwrap().funding_pubkey;
-
                self.latest_monitor_update_id += 1;
                let mut monitor_update = ChannelMonitorUpdate {
                        update_id: self.latest_monitor_update_id,
                        updates: vec![ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo {
-                               commitment_tx: HolderCommitmentTransaction::new_missing_holder_sig(commitment_tx.0, msg.signature.clone(), &self.holder_keys.pubkeys().funding_pubkey, &counterparty_funding_pubkey, keys, self.feerate_per_kw, htlcs_without_source),
+                               commitment_tx: holder_commitment_tx,
                                htlc_outputs: htlcs_and_sigs
                        }]
                };
@@ -2284,6 +2429,12 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                        return Err(ChannelError::Close("Received an unexpected revoke_and_ack".to_owned()));
                }
 
+               #[cfg(any(test, feature = "fuzztarget"))]
+               {
+                       *self.next_local_commitment_tx_fee_info_cached.lock().unwrap() = None;
+                       *self.next_remote_commitment_tx_fee_info_cached.lock().unwrap() = None;
+               }
+
                self.commitment_secrets.provide_secret(self.cur_counterparty_commitment_transaction_number + 1, msg.per_commitment_secret)
                        .map_err(|_| ChannelError::Close("Previous secrets did not match new one".to_owned()))?;
                self.latest_monitor_update_id += 1;
@@ -2393,7 +2544,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                }
                self.value_to_self_msat = (self.value_to_self_msat as i64 + value_to_self_msat_diff) as u64;
 
-               if self.channel_outbound {
+               if self.is_outbound() {
                        if let Some(feerate) = self.pending_update_fee.take() {
                                self.feerate_per_kw = feerate;
                        }
@@ -2477,7 +2628,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
        /// further details on the optionness of the return value.
        /// You MUST call send_commitment prior to any other calls on this Channel
        fn send_update_fee(&mut self, feerate_per_kw: u32) -> Option<msgs::UpdateFee> {
-               if !self.channel_outbound {
+               if !self.is_outbound() {
                        panic!("Cannot send fee from inbound channel");
                }
                if !self.is_usable() {
@@ -2609,7 +2760,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                assert_eq!(self.channel_state & ChannelState::MonitorUpdateFailed as u32, ChannelState::MonitorUpdateFailed as u32);
                self.channel_state &= !(ChannelState::MonitorUpdateFailed as u32);
 
-               let needs_broadcast_safe = self.channel_state & (ChannelState::FundingSent as u32) != 0 && self.channel_outbound;
+               let needs_broadcast_safe = self.channel_state & (ChannelState::FundingSent as u32) != 0 && self.is_outbound();
 
                // Because we will never generate a FundingBroadcastSafe event when we're in
                // MonitorUpdateFailed, if we assume the user only broadcast the funding transaction when
@@ -2618,9 +2769,9 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                // monitor on funding_created, and we even got the funding transaction confirmed before the
                // monitor was persisted.
                let funding_locked = if self.monitor_pending_funding_locked {
-                       assert!(!self.channel_outbound, "Funding transaction broadcast without FundingBroadcastSafe!");
+                       assert!(!self.is_outbound(), "Funding transaction broadcast without FundingBroadcastSafe!");
                        self.monitor_pending_funding_locked = false;
-                       let next_per_commitment_point = self.holder_keys.get_per_commitment_point(self.cur_holder_commitment_transaction_number, &self.secp_ctx);
+                       let next_per_commitment_point = self.holder_signer.get_per_commitment_point(self.cur_holder_commitment_transaction_number, &self.secp_ctx);
                        Some(msgs::FundingLocked {
                                channel_id: self.channel_id(),
                                next_per_commitment_point,
@@ -2659,21 +2810,21 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
        pub fn update_fee<F: Deref>(&mut self, fee_estimator: &F, msg: &msgs::UpdateFee) -> Result<(), ChannelError>
                where F::Target: FeeEstimator
        {
-               if self.channel_outbound {
+               if self.is_outbound() {
                        return Err(ChannelError::Close("Non-funding remote tried to update channel fee".to_owned()));
                }
                if self.channel_state & (ChannelState::PeerDisconnected as u32) == ChannelState::PeerDisconnected as u32 {
                        return Err(ChannelError::Close("Peer sent update_fee when we needed a channel_reestablish".to_owned()));
                }
-               Channel::<ChanSigner>::check_remote_fee(fee_estimator, msg.feerate_per_kw)?;
+               Channel::<Signer>::check_remote_fee(fee_estimator, msg.feerate_per_kw)?;
                self.pending_update_fee = Some(msg.feerate_per_kw);
                self.update_time_counter += 1;
                Ok(())
        }
 
        fn get_last_revoke_and_ack(&self) -> msgs::RevokeAndACK {
-               let next_per_commitment_point = self.holder_keys.get_per_commitment_point(self.cur_holder_commitment_transaction_number, &self.secp_ctx);
-               let per_commitment_secret = self.holder_keys.release_commitment_secret(self.cur_holder_commitment_transaction_number + 2);
+               let next_per_commitment_point = self.holder_signer.get_per_commitment_point(self.cur_holder_commitment_transaction_number, &self.secp_ctx);
+               let per_commitment_secret = self.holder_signer.release_commitment_secret(self.cur_holder_commitment_transaction_number + 2);
                msgs::RevokeAndACK {
                        channel_id: self.channel_id,
                        per_commitment_secret,
@@ -2756,7 +2907,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                if msg.next_remote_commitment_number > 0 {
                        match msg.data_loss_protect {
                                OptionalField::Present(ref data_loss) => {
-                                       let expected_point = self.holder_keys.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - msg.next_remote_commitment_number + 1, &self.secp_ctx);
+                                       let expected_point = self.holder_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - msg.next_remote_commitment_number + 1, &self.secp_ctx);
                                        let given_secret = SecretKey::from_slice(&data_loss.your_last_per_commitment_secret)
                                                .map_err(|_| ChannelError::Close("Peer sent a garbage channel_reestablish with unparseable secret key".to_owned()))?;
                                        if expected_point != PublicKey::from_secret_key(&self.secp_ctx, &given_secret) {
@@ -2795,7 +2946,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                        }
 
                        // We have OurFundingLocked set!
-                       let next_per_commitment_point = self.holder_keys.get_per_commitment_point(self.cur_holder_commitment_transaction_number, &self.secp_ctx);
+                       let next_per_commitment_point = self.holder_signer.get_per_commitment_point(self.cur_holder_commitment_transaction_number, &self.secp_ctx);
                        return Ok((Some(msgs::FundingLocked {
                                channel_id: self.channel_id(),
                                next_per_commitment_point,
@@ -2825,7 +2976,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
 
                let resend_funding_locked = if msg.next_local_commitment_number == 1 && INITIAL_COMMITMENT_NUMBER - self.cur_holder_commitment_transaction_number == 1 {
                        // We should never have to worry about MonitorUpdateFailed resending FundingLocked
-                       let next_per_commitment_point = self.holder_keys.get_per_commitment_point(self.cur_holder_commitment_transaction_number, &self.secp_ctx);
+                       let next_per_commitment_point = self.holder_signer.get_per_commitment_point(self.cur_holder_commitment_transaction_number, &self.secp_ctx);
                        Some(msgs::FundingLocked {
                                channel_id: self.channel_id(),
                                next_per_commitment_point,
@@ -2892,7 +3043,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
        fn maybe_propose_first_closing_signed<F: Deref>(&mut self, fee_estimator: &F) -> Option<msgs::ClosingSigned>
                where F::Target: FeeEstimator
        {
-               if !self.channel_outbound || !self.pending_inbound_htlcs.is_empty() || !self.pending_outbound_htlcs.is_empty() ||
+               if !self.is_outbound() || !self.pending_inbound_htlcs.is_empty() || !self.pending_outbound_htlcs.is_empty() ||
                                self.channel_state & (BOTH_SIDES_SHUTDOWN_MASK | ChannelState::AwaitingRemoteRevoke as u32) != BOTH_SIDES_SHUTDOWN_MASK ||
                                self.last_sent_closing_fee.is_some() || self.pending_update_fee.is_some() {
                        return None;
@@ -2906,7 +3057,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                let proposed_total_fee_satoshis = proposed_feerate as u64 * tx_weight / 1000;
 
                let (closing_tx, total_fee_satoshis) = self.build_closing_transaction(proposed_total_fee_satoshis, false);
-               let sig = self.holder_keys
+               let sig = self.holder_signer
                        .sign_closing_transaction(&closing_tx, &self.secp_ctx)
                        .ok();
                assert!(closing_tx.get_weight() as u64 <= tx_weight);
@@ -2920,7 +3071,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                })
        }
 
-       pub fn shutdown<F: Deref>(&mut self, fee_estimator: &F, msg: &msgs::Shutdown) -> Result<(Option<msgs::Shutdown>, Option<msgs::ClosingSigned>, Vec<(HTLCSource, PaymentHash)>), ChannelError>
+       pub fn shutdown<F: Deref>(&mut self, fee_estimator: &F, their_features: &InitFeatures, msg: &msgs::Shutdown) -> Result<(Option<msgs::Shutdown>, Option<msgs::ClosingSigned>, Vec<(HTLCSource, PaymentHash)>), ChannelError>
                where F::Target: FeeEstimator
        {
                if self.channel_state & (ChannelState::PeerDisconnected as u32) == ChannelState::PeerDisconnected as u32 {
@@ -2939,14 +3090,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                }
                assert_eq!(self.channel_state & ChannelState::ShutdownComplete as u32, 0);
 
-               // BOLT 2 says we must only send a scriptpubkey of certain standard forms, which are up to
-               // 34 bytes in length, so don't let the remote peer feed us some super fee-heavy script.
-               if self.channel_outbound && msg.scriptpubkey.len() > 34 {
-                       return Err(ChannelError::Close(format!("Got counterparty shutdown_scriptpubkey ({}) of absurd length from remote peer", msg.scriptpubkey.to_bytes().to_hex())));
-               }
-
-               //Check counterparty_shutdown_scriptpubkey form as BOLT says we must
-               if !msg.scriptpubkey.is_p2pkh() && !msg.scriptpubkey.is_p2sh() && !msg.scriptpubkey.is_v0_p2wpkh() && !msg.scriptpubkey.is_v0_p2wsh() {
+               if is_unsupported_shutdown_script(&their_features, &msg.scriptpubkey) {
                        return Err(ChannelError::Close(format!("Got a nonstandard scriptpubkey ({}) from remote peer", msg.scriptpubkey.to_bytes().to_hex())));
                }
 
@@ -3003,7 +3147,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
 
                tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
 
-               let funding_key = self.holder_keys.pubkeys().funding_pubkey.serialize();
+               let funding_key = self.get_holder_pubkeys().funding_pubkey.serialize();
                let counterparty_funding_key = self.counterparty_funding_pubkey().serialize();
                if funding_key[..] < counterparty_funding_key[..] {
                        tx.input[0].witness.push(sig.serialize_der().to_vec());
@@ -3041,9 +3185,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                }
                let mut sighash = hash_to_message!(&bip143::SigHashCache::new(&closing_tx).signature_hash(0, &funding_redeemscript, self.channel_value_satoshis, SigHashType::All)[..]);
 
-               let counterparty_funding_pubkey = &self.counterparty_pubkeys.as_ref().unwrap().funding_pubkey;
-
-               match self.secp_ctx.verify(&sighash, &msg.signature, counterparty_funding_pubkey) {
+               match self.secp_ctx.verify(&sighash, &msg.signature, &self.get_counterparty_pubkeys().funding_pubkey) {
                        Ok(_) => {},
                        Err(_e) => {
                                // The remote end may have decided to revoke their output due to inconsistent dust
@@ -3072,7 +3214,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                        ($new_feerate: expr) => {
                                let tx_weight = self.get_closing_transaction_weight(Some(&self.get_closing_scriptpubkey()), Some(self.counterparty_shutdown_scriptpubkey.as_ref().unwrap()));
                                let (closing_tx, used_total_fee) = self.build_closing_transaction($new_feerate as u64 * tx_weight / 1000, false);
-                               let sig = self.holder_keys
+                               let sig = self.holder_signer
                                        .sign_closing_transaction(&closing_tx, &self.secp_ctx)
                                        .map_err(|_| ChannelError::Close("External signer refused to sign closing transaction".to_owned()))?;
                                assert!(closing_tx.get_weight() as u64 <= tx_weight);
@@ -3086,7 +3228,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                }
 
                let mut min_feerate = 253;
-               if self.channel_outbound {
+               if self.is_outbound() {
                        let max_feerate = fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Normal);
                        if (msg.fee_satoshis as u64) > max_feerate as u64 * closing_tx_max_weight / 1000 {
                                if let Some((last_feerate, _, _)) = self.last_sent_closing_fee {
@@ -3108,7 +3250,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                        propose_new_feerate!(min_feerate);
                }
 
-               let sig = self.holder_keys
+               let sig = self.holder_signer
                        .sign_closing_transaction(&closing_tx, &self.secp_ctx)
                        .map_err(|_| ChannelError::Close("External signer refused to sign closing transaction".to_owned()))?;
                self.build_signed_closing_transaction(&mut closing_tx, &msg.signature, &sig);
@@ -3147,7 +3289,23 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
        /// Returns the funding_txo we either got from our peer, or were given by
        /// get_outbound_funding_created.
        pub fn get_funding_txo(&self) -> Option<OutPoint> {
-               self.funding_txo
+               self.channel_transaction_parameters.funding_outpoint
+       }
+
+       fn get_holder_selected_contest_delay(&self) -> u16 {
+               self.channel_transaction_parameters.holder_selected_contest_delay
+       }
+
+       fn get_holder_pubkeys(&self) -> &ChannelPublicKeys {
+               &self.channel_transaction_parameters.holder_pubkeys
+       }
+
+       fn get_counterparty_selected_contest_delay(&self) -> u16 {
+               self.channel_transaction_parameters.counterparty_parameters.as_ref().unwrap().selected_contest_delay
+       }
+
+       fn get_counterparty_pubkeys(&self) -> &ChannelPublicKeys {
+               &self.channel_transaction_parameters.counterparty_parameters.as_ref().unwrap().pubkeys
        }
 
        /// Allowed in any state (including after shutdown)
@@ -3169,7 +3327,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                        // channel might have been used to route very small values (either by honest users or as DoS).
                        self.channel_value_satoshis * 1000 * 9 / 10,
 
-                       Channel::<ChanSigner>::get_holder_max_htlc_value_in_flight_msat(self.channel_value_satoshis)
+                       Channel::<Signer>::get_holder_max_htlc_value_in_flight_msat(self.channel_value_satoshis)
                );
        }
 
@@ -3204,8 +3362,8 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
        }
 
        #[cfg(test)]
-       pub fn get_keys(&self) -> &ChanSigner {
-               &self.holder_keys
+       pub fn get_signer(&self) -> &Signer {
+               &self.holder_signer
        }
 
        #[cfg(test)]
@@ -3247,7 +3405,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
        }
 
        pub fn is_outbound(&self) -> bool {
-               self.channel_outbound
+               self.channel_transaction_parameters.is_outbound_from_holder
        }
 
        /// Gets the fee we'd want to charge for adding an HTLC output to this Channel
@@ -3261,7 +3419,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                // the fee cost of the HTLC-Success/HTLC-Timeout transaction:
                let mut res = self.feerate_per_kw as u64 * cmp::max(HTLC_TIMEOUT_TX_WEIGHT, HTLC_SUCCESS_TX_WEIGHT) / 1000;
 
-               if self.channel_outbound {
+               if self.is_outbound() {
                        // + the marginal fee increase cost to us in the commitment transaction:
                        res += self.feerate_per_kw as u64 * COMMITMENT_TX_WEIGHT_PER_HTLC / 1000;
                }
@@ -3367,11 +3525,12 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                }
                if non_shutdown_state & !(ChannelState::TheirFundingLocked as u32) == ChannelState::FundingSent as u32 {
                        for &(index_in_block, tx) in txdata.iter() {
-                               if tx.txid() == self.funding_txo.unwrap().txid {
-                                       let txo_idx = self.funding_txo.unwrap().index as usize;
+                               let funding_txo = self.get_funding_txo().unwrap();
+                               if tx.txid() == funding_txo.txid {
+                                       let txo_idx = funding_txo.index as usize;
                                        if txo_idx >= tx.output.len() || tx.output[txo_idx].script_pubkey != self.get_funding_redeemscript().to_v0_p2wsh() ||
                                                        tx.output[txo_idx].value != self.channel_value_satoshis {
-                                               if self.channel_outbound {
+                                               if self.is_outbound() {
                                                        // If we generated the funding transaction and it doesn't match what it
                                                        // should, the client is really broken and we should just panic and
                                                        // tell them off. That said, because hash collisions happen with high
@@ -3387,7 +3546,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                                                        data: "funding tx had wrong script/value".to_owned()
                                                });
                                        } else {
-                                               if self.channel_outbound {
+                                               if self.is_outbound() {
                                                        for input in tx.input.iter() {
                                                                if input.witness.is_empty() {
                                                                        // We generated a malleable funding transaction, implying we've
@@ -3440,7 +3599,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                                        //a protocol oversight, but I assume I'm just missing something.
                                        if need_commitment_update {
                                                if self.channel_state & (ChannelState::MonitorUpdateFailed as u32) == 0 {
-                                                       let next_per_commitment_point = self.holder_keys.get_per_commitment_point(self.cur_holder_commitment_transaction_number, &self.secp_ctx);
+                                                       let next_per_commitment_point = self.holder_signer.get_per_commitment_point(self.cur_holder_commitment_transaction_number, &self.secp_ctx);
                                                        return Ok((Some(msgs::FundingLocked {
                                                                channel_id: self.channel_id,
                                                                next_per_commitment_point,
@@ -3477,7 +3636,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
        // something in the handler for the message that prompted this message):
 
        pub fn get_open_channel(&self, chain_hash: BlockHash) -> msgs::OpenChannel {
-               if !self.channel_outbound {
+               if !self.is_outbound() {
                        panic!("Tried to open a channel for an inbound channel?");
                }
                if self.channel_state != ChannelState::OurInitSent as u32 {
@@ -3488,8 +3647,8 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                        panic!("Tried to send an open_channel for a channel that has already advanced");
                }
 
-               let first_per_commitment_point = self.holder_keys.get_per_commitment_point(self.cur_holder_commitment_transaction_number, &self.secp_ctx);
-               let keys = self.holder_keys.pubkeys();
+               let first_per_commitment_point = self.holder_signer.get_per_commitment_point(self.cur_holder_commitment_transaction_number, &self.secp_ctx);
+               let keys = self.get_holder_pubkeys();
 
                msgs::OpenChannel {
                        chain_hash,
@@ -3497,11 +3656,11 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                        funding_satoshis: self.channel_value_satoshis,
                        push_msat: self.channel_value_satoshis * 1000 - self.value_to_self_msat,
                        dust_limit_satoshis: self.holder_dust_limit_satoshis,
-                       max_htlc_value_in_flight_msat: Channel::<ChanSigner>::get_holder_max_htlc_value_in_flight_msat(self.channel_value_satoshis),
-                       channel_reserve_satoshis: Channel::<ChanSigner>::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis),
+                       max_htlc_value_in_flight_msat: Channel::<Signer>::get_holder_max_htlc_value_in_flight_msat(self.channel_value_satoshis),
+                       channel_reserve_satoshis: Channel::<Signer>::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis),
                        htlc_minimum_msat: self.holder_htlc_minimum_msat,
                        feerate_per_kw: self.feerate_per_kw as u32,
-                       to_self_delay: self.holder_selected_contest_delay,
+                       to_self_delay: self.get_holder_selected_contest_delay(),
                        max_accepted_htlcs: OUR_MAX_HTLCS,
                        funding_pubkey: keys.funding_pubkey,
                        revocation_basepoint: keys.revocation_basepoint,
@@ -3515,7 +3674,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
        }
 
        pub fn get_accept_channel(&self) -> msgs::AcceptChannel {
-               if self.channel_outbound {
+               if self.is_outbound() {
                        panic!("Tried to send accept_channel for an outbound channel?");
                }
                if self.channel_state != (ChannelState::OurInitSent as u32) | (ChannelState::TheirInitSent as u32) {
@@ -3525,17 +3684,17 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                        panic!("Tried to send an accept_channel for a channel that has already advanced");
                }
 
-               let first_per_commitment_point = self.holder_keys.get_per_commitment_point(self.cur_holder_commitment_transaction_number, &self.secp_ctx);
-               let keys = self.holder_keys.pubkeys();
+               let first_per_commitment_point = self.holder_signer.get_per_commitment_point(self.cur_holder_commitment_transaction_number, &self.secp_ctx);
+               let keys = self.get_holder_pubkeys();
 
                msgs::AcceptChannel {
                        temporary_channel_id: self.channel_id,
                        dust_limit_satoshis: self.holder_dust_limit_satoshis,
-                       max_htlc_value_in_flight_msat: Channel::<ChanSigner>::get_holder_max_htlc_value_in_flight_msat(self.channel_value_satoshis),
-                       channel_reserve_satoshis: Channel::<ChanSigner>::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis),
+                       max_htlc_value_in_flight_msat: Channel::<Signer>::get_holder_max_htlc_value_in_flight_msat(self.channel_value_satoshis),
+                       channel_reserve_satoshis: Channel::<Signer>::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis),
                        htlc_minimum_msat: self.holder_htlc_minimum_msat,
                        minimum_depth: self.minimum_depth,
-                       to_self_delay: self.holder_selected_contest_delay,
+                       to_self_delay: self.get_holder_selected_contest_delay(),
                        max_accepted_htlcs: OUR_MAX_HTLCS,
                        funding_pubkey: keys.funding_pubkey,
                        revocation_basepoint: keys.revocation_basepoint,
@@ -3551,8 +3710,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
        fn get_outbound_funding_created_signature<L: Deref>(&mut self, logger: &L) -> Result<Signature, ChannelError> where L::Target: Logger {
                let counterparty_keys = self.build_remote_transaction_keys()?;
                let counterparty_initial_commitment_tx = self.build_commitment_transaction(self.cur_counterparty_commitment_transaction_number, &counterparty_keys, false, false, self.feerate_per_kw, logger).0;
-               let pre_remote_keys = PreCalculatedTxCreationKeys::new(counterparty_keys);
-               Ok(self.holder_keys.sign_counterparty_commitment(self.feerate_per_kw, &counterparty_initial_commitment_tx, &pre_remote_keys, &Vec::new(), &self.secp_ctx)
+               Ok(self.holder_signer.sign_counterparty_commitment(&counterparty_initial_commitment_tx, &self.secp_ctx)
                                .map_err(|_| ChannelError::Close("Failed to get signatures for new commitment_signed".to_owned()))?.0)
        }
 
@@ -3564,7 +3722,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
        /// Do NOT broadcast the funding transaction until after a successful funding_signed call!
        /// If an Err is returned, it is a ChannelError::Close.
        pub fn get_outbound_funding_created<L: Deref>(&mut self, funding_txo: OutPoint, logger: &L) -> Result<msgs::FundingCreated, ChannelError> where L::Target: Logger {
-               if !self.channel_outbound {
+               if !self.is_outbound() {
                        panic!("Tried to create outbound funding_created message on an inbound channel!");
                }
                if self.channel_state != (ChannelState::OurInitSent as u32 | ChannelState::TheirInitSent as u32) {
@@ -3576,12 +3734,14 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                        panic!("Should not have advanced channel commitment tx numbers prior to funding_created");
                }
 
-               self.funding_txo = Some(funding_txo.clone());
+               self.channel_transaction_parameters.funding_outpoint = Some(funding_txo);
+               self.holder_signer.ready_channel(&self.channel_transaction_parameters);
+
                let signature = match self.get_outbound_funding_created_signature(logger) {
                        Ok(res) => res,
                        Err(e) => {
                                log_error!(logger, "Got bad signatures: {:?}!", e);
-                               self.funding_txo = None;
+                               self.channel_transaction_parameters.funding_outpoint = None;
                                return Err(e);
                        }
                };
@@ -3628,12 +3788,12 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                        short_channel_id: self.get_short_channel_id().unwrap(),
                        node_id_1: if were_node_one { node_id } else { self.get_counterparty_node_id() },
                        node_id_2: if were_node_one { self.get_counterparty_node_id() } else { node_id },
-                       bitcoin_key_1: if were_node_one { self.holder_keys.pubkeys().funding_pubkey } else { self.counterparty_funding_pubkey().clone() },
-                       bitcoin_key_2: if were_node_one { self.counterparty_funding_pubkey().clone() } else { self.holder_keys.pubkeys().funding_pubkey },
+                       bitcoin_key_1: if were_node_one { self.get_holder_pubkeys().funding_pubkey } else { self.counterparty_funding_pubkey().clone() },
+                       bitcoin_key_2: if were_node_one { self.counterparty_funding_pubkey().clone() } else { self.get_holder_pubkeys().funding_pubkey },
                        excess_data: Vec::new(),
                };
 
-               let sig = self.holder_keys.sign_channel_announcement(&msg, &self.secp_ctx)
+               let sig = self.holder_signer.sign_channel_announcement(&msg, &self.secp_ctx)
                        .map_err(|_| ChannelError::Ignore("Signer rejected channel_announcement".to_owned()))?;
 
                Ok((msg, sig))
@@ -3736,13 +3896,12 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                        return Err(ChannelError::Ignore(format!("Cannot send value that would put us over the max HTLC value in flight our peer will accept ({})", self.counterparty_max_htlc_value_in_flight_msat)));
                }
 
-               if !self.channel_outbound {
+               if !self.is_outbound() {
                        // Check that we won't violate the remote channel reserve by adding this HTLC.
-
                        let counterparty_balance_msat = self.channel_value_satoshis * 1000 - self.value_to_self_msat;
-                       let holder_selected_chan_reserve_msat = Channel::<ChanSigner>::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis);
-                       // 1 additional HTLC corresponding to this HTLC.
-                       let counterparty_commit_tx_fee_msat = self.next_remote_commit_tx_fee_msat(1);
+                       let holder_selected_chan_reserve_msat = Channel::<Signer>::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis);
+                       let htlc_candidate = HTLCCandidate::new(amount_msat, HTLCInitiator::LocalOffered);
+                       let counterparty_commit_tx_fee_msat = self.next_remote_commit_tx_fee_msat(htlc_candidate, None);
                        if counterparty_balance_msat < holder_selected_chan_reserve_msat + counterparty_commit_tx_fee_msat {
                                return Err(ChannelError::Ignore("Cannot send value that would put counterparty balance under holder-announced channel reserve value".to_owned()));
                        }
@@ -3753,10 +3912,10 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                        return Err(ChannelError::Ignore(format!("Cannot send value that would overdraw remaining funds. Amount: {}, pending value to self {}", amount_msat, pending_value_to_self_msat)));
                }
 
-               // The `+1` is for the HTLC currently being added to the commitment tx and
-               // the `2 *` and `+1` are for the fee spike buffer.
-               let commit_tx_fee_msat = if self.channel_outbound {
-                       2 * self.next_local_commit_tx_fee_msat(1 + 1)
+               // `2 *` and extra HTLC are for the fee spike buffer.
+               let commit_tx_fee_msat = if self.is_outbound() {
+                       let htlc_candidate = HTLCCandidate::new(amount_msat, HTLCInitiator::LocalOffered);
+                       2 * self.next_local_commit_tx_fee_msat(htlc_candidate, Some(()))
                } else { 0 };
                if pending_value_to_self_msat - amount_msat < commit_tx_fee_msat {
                        return Err(ChannelError::Ignore(format!("Cannot send value that would not leave enough to pay for fees. Pending value to self: {}. local_commit_tx_fee {}", pending_value_to_self_msat, commit_tx_fee_msat)));
@@ -3860,7 +4019,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                }
                self.resend_order = RAACommitmentOrder::RevokeAndACKFirst;
 
-               let (res, counterparty_commitment_tx, htlcs) = match self.send_commitment_no_state_update(logger) {
+               let (res, counterparty_commitment_txid, htlcs) = match self.send_commitment_no_state_update(logger) {
                        Ok((res, (counterparty_commitment_tx, mut htlcs))) => {
                                // Update state now that we've passed all the can-fail calls...
                                let htlcs_no_ref: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)> =
@@ -3874,7 +4033,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                let monitor_update = ChannelMonitorUpdate {
                        update_id: self.latest_monitor_update_id,
                        updates: vec![ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo {
-                               unsigned_commitment_tx: counterparty_commitment_tx.clone(),
+                               commitment_txid: counterparty_commitment_txid,
                                htlc_outputs: htlcs.clone(),
                                commitment_number: self.cur_counterparty_commitment_transaction_number,
                                their_revocation_point: self.counterparty_cur_commitment_point.unwrap()
@@ -3886,40 +4045,58 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
 
        /// Only fails in case of bad keys. Used for channel_reestablish commitment_signed generation
        /// when we shouldn't change HTLC/channel state.
-       fn send_commitment_no_state_update<L: Deref>(&self, logger: &L) -> Result<(msgs::CommitmentSigned, (Transaction, Vec<(HTLCOutputInCommitment, Option<&HTLCSource>)>)), ChannelError> where L::Target: Logger {
+       fn send_commitment_no_state_update<L: Deref>(&self, logger: &L) -> Result<(msgs::CommitmentSigned, (Txid, Vec<(HTLCOutputInCommitment, Option<&HTLCSource>)>)), ChannelError> where L::Target: Logger {
                let mut feerate_per_kw = self.feerate_per_kw;
                if let Some(feerate) = self.pending_update_fee {
-                       if self.channel_outbound {
+                       if self.is_outbound() {
                                feerate_per_kw = feerate;
                        }
                }
 
                let counterparty_keys = self.build_remote_transaction_keys()?;
                let counterparty_commitment_tx = self.build_commitment_transaction(self.cur_counterparty_commitment_transaction_number, &counterparty_keys, false, true, feerate_per_kw, logger);
+               let counterparty_commitment_txid = counterparty_commitment_tx.0.trust().txid();
                let (signature, htlc_signatures);
 
+               #[cfg(any(test, feature = "fuzztarget"))]
+               {
+                       if !self.is_outbound() {
+                               let projected_commit_tx_info = self.next_remote_commitment_tx_fee_info_cached.lock().unwrap().take();
+                               *self.next_local_commitment_tx_fee_info_cached.lock().unwrap() = None;
+                               if let Some(info) = projected_commit_tx_info {
+                                       let total_pending_htlcs = self.pending_inbound_htlcs.len() + self.pending_outbound_htlcs.len();
+                                       if info.total_pending_htlcs == total_pending_htlcs
+                                               && info.next_holder_htlc_id == self.next_holder_htlc_id
+                                               && info.next_counterparty_htlc_id == self.next_counterparty_htlc_id
+                                               && info.feerate == self.feerate_per_kw {
+                                                       let actual_fee = self.commit_tx_fee_msat(counterparty_commitment_tx.1);
+                                                       assert_eq!(actual_fee, info.fee);
+                                               }
+                               }
+                       }
+               }
+
                {
                        let mut htlcs = Vec::with_capacity(counterparty_commitment_tx.2.len());
                        for &(ref htlc, _) in counterparty_commitment_tx.2.iter() {
                                htlcs.push(htlc);
                        }
 
-                       let pre_remote_keys = PreCalculatedTxCreationKeys::new(counterparty_keys);
-                       let res = self.holder_keys.sign_counterparty_commitment(feerate_per_kw, &counterparty_commitment_tx.0, &pre_remote_keys, &htlcs, &self.secp_ctx)
+                       let res = self.holder_signer.sign_counterparty_commitment(&counterparty_commitment_tx.0, &self.secp_ctx)
                                .map_err(|_| ChannelError::Close("Failed to get signatures for new commitment_signed".to_owned()))?;
                        signature = res.0;
                        htlc_signatures = res.1;
-                       let counterparty_keys = pre_remote_keys.trust_key_derivation();
 
-                       log_trace!(logger, "Signed remote commitment tx {} with redeemscript {} -> {}",
-                               encode::serialize_hex(&counterparty_commitment_tx.0),
+                       log_trace!(logger, "Signed remote commitment tx {} (txid {}) with redeemscript {} -> {}",
+                               encode::serialize_hex(&counterparty_commitment_tx.0.trust().built_transaction().transaction),
+                               &counterparty_commitment_txid,
                                encode::serialize_hex(&self.get_funding_redeemscript()),
                                log_bytes!(signature.serialize_compact()[..]));
 
                        for (ref htlc_sig, ref htlc) in htlc_signatures.iter().zip(htlcs) {
                                log_trace!(logger, "Signed remote HTLC tx {} with redeemscript {} with pubkey {} -> {}",
-                                       encode::serialize_hex(&chan_utils::build_htlc_transaction(&counterparty_commitment_tx.0.txid(), feerate_per_kw, self.holder_selected_contest_delay, htlc, &counterparty_keys.broadcaster_delayed_payment_key, &counterparty_keys.revocation_key)),
-                                       encode::serialize_hex(&chan_utils::get_htlc_redeemscript(&htlc, counterparty_keys)),
+                                       encode::serialize_hex(&chan_utils::build_htlc_transaction(&counterparty_commitment_txid, feerate_per_kw, self.get_holder_selected_contest_delay(), htlc, &counterparty_keys.broadcaster_delayed_payment_key, &counterparty_keys.revocation_key)),
+                                       encode::serialize_hex(&chan_utils::get_htlc_redeemscript(&htlc, &counterparty_keys)),
                                        log_bytes!(counterparty_keys.broadcaster_htlc_key.serialize()),
                                        log_bytes!(htlc_sig.serialize_compact()[..]));
                        }
@@ -3929,7 +4106,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                        channel_id: self.channel_id,
                        signature,
                        htlc_signatures,
-               }, (counterparty_commitment_tx.0, counterparty_commitment_tx.2)))
+               }, (counterparty_commitment_txid, counterparty_commitment_tx.2)))
        }
 
        /// Adds a pending outbound HTLC to this channel, and creates a signed commitment transaction
@@ -4016,7 +4193,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
                                _ => {}
                        }
                }
-               let funding_txo = if let Some(funding_txo) = self.funding_txo {
+               let funding_txo = if let Some(funding_txo) = self.get_funding_txo() {
                        // If we haven't yet exchanged funding signatures (ie channel_state < FundingSent),
                        // returning a channel monitor update here would imply a channel monitor update before
                        // we even registered the channel monitor to begin with, which is invalid.
@@ -4039,6 +4216,24 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
        }
 }
 
+fn is_unsupported_shutdown_script(their_features: &InitFeatures, script: &Script) -> bool {
+       // We restrain shutdown scripts to standards forms to avoid transactions not propagating on the p2p tx-relay network
+
+       // BOLT 2 says we must only send a scriptpubkey of certain standard forms,
+       // which for a a BIP-141-compliant witness program is at max 42 bytes in length.
+       // So don't let the remote peer feed us some super fee-heavy script.
+       let is_script_too_long = script.len() > 42;
+       if is_script_too_long {
+               return true;
+       }
+
+       if their_features.supports_shutdown_anysegwit() && script.is_witness_program() && script.as_bytes()[0] != OP_PUSHBYTES_0.into_u8() {
+               return false;
+       }
+
+       return !script.is_p2pkh() && !script.is_p2sh() && !script.is_v0_p2wpkh() && !script.is_v0_p2wsh()
+}
+
 const SERIALIZATION_VERSION: u8 = 1;
 const MIN_SERIALIZATION_VERSION: u8 = 1;
 
@@ -4074,7 +4269,7 @@ impl Readable for InboundHTLCRemovalReason {
        }
 }
 
-impl<ChanSigner: ChannelKeys + Writeable> Writeable for Channel<ChanSigner> {
+impl<Signer: Sign> Writeable for Channel<Signer> {
        fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
                // Note that we write out as if remove_uncommitted_htlcs_and_mark_paused had just been
                // called but include holding cell updates (and obviously we don't modify self).
@@ -4087,12 +4282,17 @@ impl<ChanSigner: ChannelKeys + Writeable> Writeable for Channel<ChanSigner> {
 
                self.channel_id.write(writer)?;
                (self.channel_state | ChannelState::PeerDisconnected as u32).write(writer)?;
-               self.channel_outbound.write(writer)?;
                self.channel_value_satoshis.write(writer)?;
 
                self.latest_monitor_update_id.write(writer)?;
 
-               self.holder_keys.write(writer)?;
+               let mut key_data = VecWriter(Vec::new());
+               self.holder_signer.write(&mut key_data)?;
+               assert!(key_data.0.len() < std::usize::MAX);
+               assert!(key_data.0.len() < std::u32::MAX as usize);
+               (key_data.0.len() as u32).write(writer)?;
+               writer.write_all(&key_data.0[..])?;
+
                self.shutdown_pubkey.write(writer)?;
                self.destination_script.write(writer)?;
 
@@ -4229,7 +4429,6 @@ impl<ChanSigner: ChannelKeys + Writeable> Writeable for Channel<ChanSigner> {
                        None => 0u8.write(writer)?,
                }
 
-               self.funding_txo.write(writer)?;
                self.funding_tx_confirmed_in.write(writer)?;
                self.short_channel_id.write(writer)?;
 
@@ -4242,12 +4441,10 @@ impl<ChanSigner: ChannelKeys + Writeable> Writeable for Channel<ChanSigner> {
                self.counterparty_selected_channel_reserve_satoshis.write(writer)?;
                self.counterparty_htlc_minimum_msat.write(writer)?;
                self.holder_htlc_minimum_msat.write(writer)?;
-               self.counterparty_selected_contest_delay.write(writer)?;
-               self.holder_selected_contest_delay.write(writer)?;
                self.counterparty_max_accepted_htlcs.write(writer)?;
                self.minimum_depth.write(writer)?;
 
-               self.counterparty_pubkeys.write(writer)?;
+               self.channel_transaction_parameters.write(writer)?;
                self.counterparty_cur_commitment_point.write(writer)?;
 
                self.counterparty_prev_commitment_point.write(writer)?;
@@ -4260,8 +4457,10 @@ impl<ChanSigner: ChannelKeys + Writeable> Writeable for Channel<ChanSigner> {
        }
 }
 
-impl<ChanSigner: ChannelKeys + Readable> Readable for Channel<ChanSigner> {
-       fn read<R : ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
+const MAX_ALLOC_SIZE: usize = 64*1024;
+impl<'a, Signer: Sign, K: Deref> ReadableArgs<&'a K> for Channel<Signer>
+               where K::Target: KeysInterface<Signer = Signer> {
+       fn read<R : ::std::io::Read>(reader: &mut R, keys_source: &'a K) -> Result<Self, DecodeError> {
                let _ver: u8 = Readable::read(reader)?;
                let min_ver: u8 = Readable::read(reader)?;
                if min_ver > SERIALIZATION_VERSION {
@@ -4273,12 +4472,21 @@ impl<ChanSigner: ChannelKeys + Readable> Readable for Channel<ChanSigner> {
 
                let channel_id = Readable::read(reader)?;
                let channel_state = Readable::read(reader)?;
-               let channel_outbound = Readable::read(reader)?;
                let channel_value_satoshis = Readable::read(reader)?;
 
                let latest_monitor_update_id = Readable::read(reader)?;
 
-               let holder_keys = Readable::read(reader)?;
+               let keys_len: u32 = Readable::read(reader)?;
+               let mut keys_data = Vec::with_capacity(cmp::min(keys_len as usize, MAX_ALLOC_SIZE));
+               while keys_data.len() != keys_len as usize {
+                       // Read 1KB at a time to avoid accidentally allocating 4GB on corrupted channel keys
+                       let mut data = [0; 1024];
+                       let read_slice = &mut data[0..cmp::min(1024, keys_len as usize - keys_data.len())];
+                       reader.read_exact(read_slice)?;
+                       keys_data.extend_from_slice(read_slice);
+               }
+               let holder_signer = keys_source.read_chan_signer(&keys_data)?;
+
                let shutdown_pubkey = Readable::read(reader)?;
                let destination_script = Readable::read(reader)?;
 
@@ -4383,7 +4591,6 @@ impl<ChanSigner: ChannelKeys + Readable> Readable for Channel<ChanSigner> {
                        _ => return Err(DecodeError::InvalidValue),
                };
 
-               let funding_txo = Readable::read(reader)?;
                let funding_tx_confirmed_in = Readable::read(reader)?;
                let short_channel_id = Readable::read(reader)?;
 
@@ -4396,12 +4603,10 @@ impl<ChanSigner: ChannelKeys + Readable> Readable for Channel<ChanSigner> {
                let counterparty_selected_channel_reserve_satoshis = Readable::read(reader)?;
                let counterparty_htlc_minimum_msat = Readable::read(reader)?;
                let holder_htlc_minimum_msat = Readable::read(reader)?;
-               let counterparty_selected_contest_delay = Readable::read(reader)?;
-               let holder_selected_contest_delay = Readable::read(reader)?;
                let counterparty_max_accepted_htlcs = Readable::read(reader)?;
                let minimum_depth = Readable::read(reader)?;
 
-               let counterparty_pubkeys = Readable::read(reader)?;
+               let channel_parameters = Readable::read(reader)?;
                let counterparty_cur_commitment_point = Readable::read(reader)?;
 
                let counterparty_prev_commitment_point = Readable::read(reader)?;
@@ -4410,19 +4615,21 @@ impl<ChanSigner: ChannelKeys + Readable> Readable for Channel<ChanSigner> {
                let counterparty_shutdown_scriptpubkey = Readable::read(reader)?;
                let commitment_secrets = Readable::read(reader)?;
 
+               let mut secp_ctx = Secp256k1::new();
+               secp_ctx.seeded_randomize(&keys_source.get_secure_random_bytes());
+
                Ok(Channel {
                        user_id,
 
                        config,
                        channel_id,
                        channel_state,
-                       channel_outbound,
-                       secp_ctx: Secp256k1::new(),
+                       secp_ctx,
                        channel_value_satoshis,
 
                        latest_monitor_update_id,
 
-                       holder_keys,
+                       holder_signer,
                        shutdown_pubkey,
                        destination_script,
 
@@ -4456,7 +4663,6 @@ impl<ChanSigner: ChannelKeys + Readable> Readable for Channel<ChanSigner> {
 
                        last_sent_closing_fee,
 
-                       funding_txo,
                        funding_tx_confirmed_in,
                        short_channel_id,
                        last_block_connected,
@@ -4468,12 +4674,10 @@ impl<ChanSigner: ChannelKeys + Readable> Readable for Channel<ChanSigner> {
                        counterparty_selected_channel_reserve_satoshis,
                        counterparty_htlc_minimum_msat,
                        holder_htlc_minimum_msat,
-                       counterparty_selected_contest_delay,
-                       holder_selected_contest_delay,
                        counterparty_max_accepted_htlcs,
                        minimum_depth,
 
-                       counterparty_pubkeys,
+                       channel_transaction_parameters: channel_parameters,
                        counterparty_cur_commitment_point,
 
                        counterparty_prev_commitment_point,
@@ -4484,6 +4688,11 @@ impl<ChanSigner: ChannelKeys + Readable> Readable for Channel<ChanSigner> {
                        commitment_secrets,
 
                        network_sync: UpdateStatus::Fresh,
+
+                       #[cfg(any(test, feature = "fuzztarget"))]
+                       next_local_commitment_tx_fee_info_cached: Mutex::new(None),
+                       #[cfg(any(test, feature = "fuzztarget"))]
+                       next_remote_commitment_tx_fee_info_cached: Mutex::new(None),
                })
        }
 }
@@ -4500,17 +4709,17 @@ mod tests {
        use bitcoin::hashes::hex::FromHex;
        use hex;
        use ln::channelmanager::{HTLCSource, PaymentPreimage, PaymentHash};
-       use ln::channel::{Channel,ChannelKeys,InboundHTLCOutput,OutboundHTLCOutput,InboundHTLCState,OutboundHTLCState,HTLCOutputInCommitment,TxCreationKeys};
+       use ln::channel::{Channel,Sign,InboundHTLCOutput,OutboundHTLCOutput,InboundHTLCState,OutboundHTLCState,HTLCOutputInCommitment,HTLCCandidate,HTLCInitiator,TxCreationKeys};
        use ln::channel::MAX_FUNDING_SATOSHIS;
        use ln::features::InitFeatures;
-       use ln::msgs::{OptionalField, DataLossProtect};
+       use ln::msgs::{OptionalField, DataLossProtect, DecodeError};
        use ln::chan_utils;
-       use ln::chan_utils::{HolderCommitmentTransaction, ChannelPublicKeys};
+       use ln::chan_utils::{ChannelPublicKeys, HolderCommitmentTransaction, CounterpartyChannelTransactionParameters, HTLC_SUCCESS_TX_WEIGHT, HTLC_TIMEOUT_TX_WEIGHT};
        use chain::chaininterface::{FeeEstimator,ConfirmationTarget};
-       use chain::keysinterface::{InMemoryChannelKeys, KeysInterface};
+       use chain::keysinterface::{InMemorySigner, KeysInterface};
        use chain::transaction::OutPoint;
        use util::config::UserConfig;
-       use util::enforcing_trait_impls::EnforcingChannelKeys;
+       use util::enforcing_trait_impls::EnforcingSigner;
        use util::test_utils;
        use util::logger::Logger;
        use bitcoin::secp256k1::{Secp256k1, Message, Signature, All};
@@ -4536,10 +4745,10 @@ mod tests {
        }
 
        struct Keys {
-               chan_keys: InMemoryChannelKeys,
+               signer: InMemorySigner,
        }
        impl KeysInterface for Keys {
-               type ChanKeySigner = InMemoryChannelKeys;
+               type Signer = InMemorySigner;
 
                fn get_node_secret(&self) -> SecretKey { panic!(); }
                fn get_destination_script(&self) -> Script {
@@ -4555,10 +4764,11 @@ mod tests {
                        PublicKey::from_secret_key(&secp_ctx, &channel_close_key)
                }
 
-               fn get_channel_keys(&self, _inbound: bool, _channel_value_satoshis: u64) -> InMemoryChannelKeys {
-                       self.chan_keys.clone()
+               fn get_channel_signer(&self, _inbound: bool, _channel_value_satoshis: u64) -> InMemorySigner {
+                       self.signer.clone()
                }
                fn get_secure_random_bytes(&self) -> [u8; 32] { [0; 32] }
+               fn read_chan_signer(&self, _data: &[u8]) -> Result<Self::Signer, DecodeError> { panic!(); }
        }
 
        fn public_from_secret_hex(secp_ctx: &Secp256k1<All>, hex: &str) -> PublicKey {
@@ -4578,7 +4788,7 @@ mod tests {
 
                let node_a_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
                let config = UserConfig::default();
-               let node_a_chan = Channel::<EnforcingChannelKeys>::new_outbound(&&fee_est, &&keys_provider, node_a_node_id, 10000000, 100000, 42, &config).unwrap();
+               let node_a_chan = Channel::<EnforcingSigner>::new_outbound(&&fee_est, &&keys_provider, node_a_node_id, 10000000, 100000, 42, &config).unwrap();
 
                // Now change the fee so we can check that the fee in the open_channel message is the
                // same as the old fee.
@@ -4587,6 +4797,122 @@ mod tests {
                assert_eq!(open_channel_msg.feerate_per_kw, original_fee);
        }
 
+       #[test]
+       fn test_holder_vs_counterparty_dust_limit() {
+               // Test that when calculating the local and remote commitment transaction fees, the correct
+               // dust limits are used.
+               let feeest = TestFeeEstimator{fee_est: 15000};
+               let secp_ctx = Secp256k1::new();
+               let seed = [42; 32];
+               let network = Network::Testnet;
+               let keys_provider = test_utils::TestKeysInterface::new(&seed, network);
+
+               // Go through the flow of opening a channel between two nodes, making sure
+               // they have different dust limits.
+
+               // Create Node A's channel pointing to Node B's pubkey
+               let node_b_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
+               let config = UserConfig::default();
+               let mut node_a_chan = Channel::<EnforcingSigner>::new_outbound(&&feeest, &&keys_provider, node_b_node_id, 10000000, 100000, 42, &config).unwrap();
+
+               // Create Node B's channel by receiving Node A's open_channel message
+               // Make sure A's dust limit is as we expect.
+               let open_channel_msg = node_a_chan.get_open_channel(genesis_block(network).header.block_hash());
+               assert_eq!(open_channel_msg.dust_limit_satoshis, 1560);
+               let node_b_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[7; 32]).unwrap());
+               let node_b_chan = Channel::<EnforcingSigner>::new_from_req(&&feeest, &&keys_provider, node_b_node_id, InitFeatures::known(), &open_channel_msg, 7, &config).unwrap();
+
+               // Node B --> Node A: accept channel, explicitly setting B's dust limit.
+               let mut accept_channel_msg = node_b_chan.get_accept_channel();
+               accept_channel_msg.dust_limit_satoshis = 546;
+               node_a_chan.accept_channel(&accept_channel_msg, &config, InitFeatures::known()).unwrap();
+
+               // Put some inbound and outbound HTLCs in A's channel.
+               let htlc_amount_msat = 11_092_000; // put an amount below A's effective dust limit but above B's.
+               node_a_chan.pending_inbound_htlcs.push(InboundHTLCOutput {
+                       htlc_id: 0,
+                       amount_msat: htlc_amount_msat,
+                       payment_hash: PaymentHash(Sha256::hash(&[42; 32]).into_inner()),
+                       cltv_expiry: 300000000,
+                       state: InboundHTLCState::Committed,
+               });
+
+               node_a_chan.pending_outbound_htlcs.push(OutboundHTLCOutput {
+                       htlc_id: 1,
+                       amount_msat: htlc_amount_msat, // put an amount below A's dust amount but above B's.
+                       payment_hash: PaymentHash(Sha256::hash(&[43; 32]).into_inner()),
+                       cltv_expiry: 200000000,
+                       state: OutboundHTLCState::Committed,
+                       source: HTLCSource::OutboundRoute {
+                               path: Vec::new(),
+                               session_priv: SecretKey::from_slice(&hex::decode("0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").unwrap()[..]).unwrap(),
+                               first_hop_htlc_msat: 548,
+                       }
+               });
+
+               // Make sure when Node A calculates their local commitment transaction, none of the HTLCs pass
+               // the dust limit check.
+               let htlc_candidate = HTLCCandidate::new(htlc_amount_msat, HTLCInitiator::LocalOffered);
+               let local_commit_tx_fee = node_a_chan.next_local_commit_tx_fee_msat(htlc_candidate, None);
+               let local_commit_fee_0_htlcs = node_a_chan.commit_tx_fee_msat(0);
+               assert_eq!(local_commit_tx_fee, local_commit_fee_0_htlcs);
+
+               // Finally, make sure that when Node A calculates the remote's commitment transaction fees, all
+               // of the HTLCs are seen to be above the dust limit.
+               node_a_chan.channel_transaction_parameters.is_outbound_from_holder = false;
+               let remote_commit_fee_3_htlcs = node_a_chan.commit_tx_fee_msat(3);
+               let htlc_candidate = HTLCCandidate::new(htlc_amount_msat, HTLCInitiator::LocalOffered);
+               let remote_commit_tx_fee = node_a_chan.next_remote_commit_tx_fee_msat(htlc_candidate, None);
+               assert_eq!(remote_commit_tx_fee, remote_commit_fee_3_htlcs);
+       }
+
+       #[test]
+       fn test_timeout_vs_success_htlc_dust_limit() {
+               // Make sure that when `next_remote_commit_tx_fee_msat` and `next_local_commit_tx_fee_msat`
+               // calculate the real dust limits for HTLCs (i.e. the dust limit given by the counterparty
+               // *plus* the fees paid for the HTLC) they don't swap `HTLC_SUCCESS_TX_WEIGHT` for
+               // `HTLC_TIMEOUT_TX_WEIGHT`, and vice versa.
+               let fee_est = TestFeeEstimator{fee_est: 253 };
+               let secp_ctx = Secp256k1::new();
+               let seed = [42; 32];
+               let network = Network::Testnet;
+               let keys_provider = test_utils::TestKeysInterface::new(&seed, network);
+
+               let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
+               let config = UserConfig::default();
+               let mut chan = Channel::<EnforcingSigner>::new_outbound(&&fee_est, &&keys_provider, node_id, 10000000, 100000, 42, &config).unwrap();
+
+               let commitment_tx_fee_0_htlcs = chan.commit_tx_fee_msat(0);
+               let commitment_tx_fee_1_htlc = chan.commit_tx_fee_msat(1);
+
+               // If HTLC_SUCCESS_TX_WEIGHT and HTLC_TIMEOUT_TX_WEIGHT were swapped: then this HTLC would be
+               // counted as dust when it shouldn't be.
+               let htlc_amt_above_timeout = ((253 * HTLC_TIMEOUT_TX_WEIGHT / 1000) + chan.holder_dust_limit_satoshis + 1) * 1000;
+               let htlc_candidate = HTLCCandidate::new(htlc_amt_above_timeout, HTLCInitiator::LocalOffered);
+               let commitment_tx_fee = chan.next_local_commit_tx_fee_msat(htlc_candidate, None);
+               assert_eq!(commitment_tx_fee, commitment_tx_fee_1_htlc);
+
+               // If swapped: this HTLC would be counted as non-dust when it shouldn't be.
+               let dust_htlc_amt_below_success = ((253 * HTLC_SUCCESS_TX_WEIGHT / 1000) + chan.holder_dust_limit_satoshis - 1) * 1000;
+               let htlc_candidate = HTLCCandidate::new(dust_htlc_amt_below_success, HTLCInitiator::RemoteOffered);
+               let commitment_tx_fee = chan.next_local_commit_tx_fee_msat(htlc_candidate, None);
+               assert_eq!(commitment_tx_fee, commitment_tx_fee_0_htlcs);
+
+               chan.channel_transaction_parameters.is_outbound_from_holder = false;
+
+               // If swapped: this HTLC would be counted as non-dust when it shouldn't be.
+               let dust_htlc_amt_above_timeout = ((253 * HTLC_TIMEOUT_TX_WEIGHT / 1000) + chan.counterparty_dust_limit_satoshis + 1) * 1000;
+               let htlc_candidate = HTLCCandidate::new(dust_htlc_amt_above_timeout, HTLCInitiator::LocalOffered);
+               let commitment_tx_fee = chan.next_remote_commit_tx_fee_msat(htlc_candidate, None);
+               assert_eq!(commitment_tx_fee, commitment_tx_fee_0_htlcs);
+
+               // If swapped: this HTLC would be counted as dust when it shouldn't be.
+               let htlc_amt_below_success = ((253 * HTLC_SUCCESS_TX_WEIGHT / 1000) + chan.counterparty_dust_limit_satoshis - 1) * 1000;
+               let htlc_candidate = HTLCCandidate::new(htlc_amt_below_success, HTLCInitiator::RemoteOffered);
+               let commitment_tx_fee = chan.next_remote_commit_tx_fee_msat(htlc_candidate, None);
+               assert_eq!(commitment_tx_fee, commitment_tx_fee_1_htlc);
+       }
+
        #[test]
        fn channel_reestablish_no_updates() {
                let feeest = TestFeeEstimator{fee_est: 15000};
@@ -4601,12 +4927,12 @@ mod tests {
                // Create Node A's channel pointing to Node B's pubkey
                let node_b_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
                let config = UserConfig::default();
-               let mut node_a_chan = Channel::<EnforcingChannelKeys>::new_outbound(&&feeest, &&keys_provider, node_b_node_id, 10000000, 100000, 42, &config).unwrap();
+               let mut node_a_chan = Channel::<EnforcingSigner>::new_outbound(&&feeest, &&keys_provider, node_b_node_id, 10000000, 100000, 42, &config).unwrap();
 
                // Create Node B's channel by receiving Node A's open_channel message
                let open_channel_msg = node_a_chan.get_open_channel(genesis_block(network).header.block_hash());
                let node_b_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[7; 32]).unwrap());
-               let mut node_b_chan = Channel::<EnforcingChannelKeys>::new_from_req(&&feeest, &&keys_provider, node_b_node_id, InitFeatures::known(), &open_channel_msg, 7, &config).unwrap();
+               let mut node_b_chan = Channel::<EnforcingSigner>::new_from_req(&&feeest, &&keys_provider, node_b_node_id, InitFeatures::known(), &open_channel_msg, 7, &config).unwrap();
 
                // Node B --> Node A: accept channel
                let accept_channel_msg = node_b_chan.get_accept_channel();
@@ -4658,7 +4984,7 @@ mod tests {
                let logger : Arc<Logger> = Arc::new(test_utils::TestLogger::new());
                let secp_ctx = Secp256k1::new();
 
-               let mut chan_keys = InMemoryChannelKeys::new(
+               let mut signer = InMemorySigner::new(
                        &secp_ctx,
                        SecretKey::from_slice(&hex::decode("30ff4956bbdd3222d44cc5e8a1261dab1e07957bdac5ae88fe3261ef321f3749").unwrap()[..]).unwrap(),
                        SecretKey::from_slice(&hex::decode("0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").unwrap()[..]).unwrap(),
@@ -4669,22 +4995,20 @@ mod tests {
                        // These aren't set in the test vectors:
                        [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff],
                        10_000_000,
-                       (0, 0)
+                       [0; 32]
                );
 
-               assert_eq!(chan_keys.pubkeys().funding_pubkey.serialize()[..],
+               assert_eq!(signer.pubkeys().funding_pubkey.serialize()[..],
                                hex::decode("023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb").unwrap()[..]);
-               let keys_provider = Keys { chan_keys: chan_keys.clone() };
+               let keys_provider = Keys { signer: signer.clone() };
 
                let counterparty_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
                let mut config = UserConfig::default();
                config.channel_options.announced_channel = false;
-               let mut chan = Channel::<InMemoryChannelKeys>::new_outbound(&&feeest, &&keys_provider, counterparty_node_id, 10_000_000, 100000, 42, &config).unwrap(); // Nothing uses their network key in this test
-               chan.counterparty_selected_contest_delay = 144;
+               let mut chan = Channel::<InMemorySigner>::new_outbound(&&feeest, &&keys_provider, counterparty_node_id, 10_000_000, 100000, 42, &config).unwrap(); // Nothing uses their network key in this test
                chan.holder_dust_limit_satoshis = 546;
 
                let funding_info = OutPoint{ txid: Txid::from_hex("8984484a580b825b9972d7adb15050b3ab624ccd731946b3eeddb92f4e7ef6be").unwrap(), index: 0 };
-               chan.funding_txo = Some(funding_info);
 
                let counterparty_pubkeys = ChannelPublicKeys {
                        funding_pubkey: public_from_secret_hex(&secp_ctx, "1552dfba4f6cf29a62a0af13c8d6981d36d0ef8d61ba10fb0fe90da7634d7e13"),
@@ -4693,7 +5017,13 @@ mod tests {
                        delayed_payment_basepoint: public_from_secret_hex(&secp_ctx, "1552dfba4f6cf29a62a0af13c8d6981d36d0ef8d61ba10fb0fe90da7634d7e13"),
                        htlc_basepoint: public_from_secret_hex(&secp_ctx, "4444444444444444444444444444444444444444444444444444444444444444")
                };
-               chan_keys.on_accept(&counterparty_pubkeys, chan.counterparty_selected_contest_delay, chan.holder_selected_contest_delay);
+               chan.channel_transaction_parameters.counterparty_parameters = Some(
+                       CounterpartyChannelTransactionParameters {
+                               pubkeys: counterparty_pubkeys.clone(),
+                               selected_contest_delay: 144
+                       });
+               chan.channel_transaction_parameters.funding_outpoint = Some(funding_info);
+               signer.ready_channel(&chan.channel_transaction_parameters);
 
                assert_eq!(counterparty_pubkeys.payment_point.serialize()[..],
                           hex::decode("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991").unwrap()[..]);
@@ -4707,56 +5037,64 @@ mod tests {
                // We can't just use build_holder_transaction_keys here as the per_commitment_secret is not
                // derived from a commitment_seed, so instead we copy it here and call
                // build_commitment_transaction.
-               let delayed_payment_base = &chan.holder_keys.pubkeys().delayed_payment_basepoint;
+               let delayed_payment_base = &chan.holder_signer.pubkeys().delayed_payment_basepoint;
                let per_commitment_secret = SecretKey::from_slice(&hex::decode("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100").unwrap()[..]).unwrap();
                let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
-               let htlc_basepoint = &chan.holder_keys.pubkeys().htlc_basepoint;
+               let htlc_basepoint = &chan.holder_signer.pubkeys().htlc_basepoint;
                let keys = TxCreationKeys::derive_new(&secp_ctx, &per_commitment_point, delayed_payment_base, htlc_basepoint, &counterparty_pubkeys.revocation_basepoint, &counterparty_pubkeys.htlc_basepoint).unwrap();
 
-               chan.counterparty_pubkeys = Some(counterparty_pubkeys);
-
-               let mut unsigned_tx: (Transaction, Vec<HTLCOutputInCommitment>);
-
-               let mut holdertx;
                macro_rules! test_commitment {
                        ( $counterparty_sig_hex: expr, $sig_hex: expr, $tx_hex: expr, {
                                $( { $htlc_idx: expr, $counterparty_htlc_sig_hex: expr, $htlc_sig_hex: expr, $htlc_tx_hex: expr } ), *
                        } ) => { {
-                               unsigned_tx = {
+                               let (commitment_tx, htlcs): (_, Vec<HTLCOutputInCommitment>) = {
                                        let mut res = chan.build_commitment_transaction(0xffffffffffff - 42, &keys, true, false, chan.feerate_per_kw, &logger);
+
                                        let htlcs = res.2.drain(..)
                                                .filter_map(|(htlc, _)| if htlc.transaction_output_index.is_some() { Some(htlc) } else { None })
                                                .collect();
                                        (res.0, htlcs)
                                };
+                               let trusted_tx = commitment_tx.trust();
+                               let unsigned_tx = trusted_tx.built_transaction();
                                let redeemscript = chan.get_funding_redeemscript();
                                let counterparty_signature = Signature::from_der(&hex::decode($counterparty_sig_hex).unwrap()[..]).unwrap();
-                               let sighash = Message::from_slice(&bip143::SigHashCache::new(&unsigned_tx.0).signature_hash(0, &redeemscript, chan.channel_value_satoshis, SigHashType::All)[..]).unwrap();
+                               let sighash = unsigned_tx.get_sighash_all(&redeemscript, chan.channel_value_satoshis);
                                secp_ctx.verify(&sighash, &counterparty_signature, chan.counterparty_funding_pubkey()).unwrap();
 
-                               let mut per_htlc = Vec::new();
+                               let mut per_htlc: Vec<(HTLCOutputInCommitment, Option<Signature>)> = Vec::new();
                                per_htlc.clear(); // Don't warn about excess mut for no-HTLC calls
+                               let mut counterparty_htlc_sigs = Vec::new();
+                               counterparty_htlc_sigs.clear(); // Don't warn about excess mut for no-HTLC calls
                                $({
                                        let remote_signature = Signature::from_der(&hex::decode($counterparty_htlc_sig_hex).unwrap()[..]).unwrap();
-                                       per_htlc.push((unsigned_tx.1[$htlc_idx].clone(), Some(remote_signature)));
+                                       per_htlc.push((htlcs[$htlc_idx].clone(), Some(remote_signature)));
+                                       counterparty_htlc_sigs.push(remote_signature);
                                })*
-                               assert_eq!(unsigned_tx.1.len(), per_htlc.len());
+                               assert_eq!(htlcs.len(), per_htlc.len());
 
-                               holdertx = HolderCommitmentTransaction::new_missing_holder_sig(unsigned_tx.0.clone(), counterparty_signature.clone(), &chan_keys.pubkeys().funding_pubkey, chan.counterparty_funding_pubkey(), keys.clone(), chan.feerate_per_kw, per_htlc);
-                               let holder_sig = chan_keys.sign_holder_commitment(&holdertx, &chan.secp_ctx).unwrap();
-                               assert_eq!(Signature::from_der(&hex::decode($sig_hex).unwrap()[..]).unwrap(), holder_sig);
+                               let holder_commitment_tx = HolderCommitmentTransaction::new(
+                                       commitment_tx.clone(),
+                                       counterparty_signature,
+                                       counterparty_htlc_sigs,
+                                       &chan.holder_signer.pubkeys().funding_pubkey,
+                                       chan.counterparty_funding_pubkey()
+                               );
+                               let (holder_sig, htlc_sigs) = signer.sign_holder_commitment_and_htlcs(&holder_commitment_tx, &secp_ctx).unwrap();
+                               assert_eq!(Signature::from_der(&hex::decode($sig_hex).unwrap()[..]).unwrap(), holder_sig, "holder_sig");
 
-                               assert_eq!(serialize(&holdertx.add_holder_sig(&redeemscript, holder_sig))[..],
-                                               hex::decode($tx_hex).unwrap()[..]);
+                               let funding_redeemscript = chan.get_funding_redeemscript();
+                               let tx = holder_commitment_tx.add_holder_sig(&funding_redeemscript, holder_sig);
+                               assert_eq!(serialize(&tx)[..], hex::decode($tx_hex).unwrap()[..], "tx");
 
-                               let htlc_sigs = chan_keys.sign_holder_commitment_htlc_transactions(&holdertx, &chan.secp_ctx).unwrap();
-                               let mut htlc_sig_iter = holdertx.per_htlc.iter().zip(htlc_sigs.iter().enumerate());
+                               // ((htlc, counterparty_sig), (index, holder_sig))
+                               let mut htlc_sig_iter = holder_commitment_tx.htlcs().iter().zip(&holder_commitment_tx.counterparty_htlc_sigs).zip(htlc_sigs.iter().enumerate());
 
                                $({
                                        let remote_signature = Signature::from_der(&hex::decode($counterparty_htlc_sig_hex).unwrap()[..]).unwrap();
 
-                                       let ref htlc = unsigned_tx.1[$htlc_idx];
-                                       let htlc_tx = chan.build_htlc_transaction(&unsigned_tx.0.txid(), &htlc, true, &keys, chan.feerate_per_kw);
+                                       let ref htlc = htlcs[$htlc_idx];
+                                       let htlc_tx = chan.build_htlc_transaction(&unsigned_tx.txid, &htlc, true, &keys, chan.feerate_per_kw);
                                        let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, &keys);
                                        let htlc_sighash = Message::from_slice(&bip143::SigHashCache::new(&htlc_tx).signature_hash(0, &htlc_redeemscript, htlc.amount_msat / 1000, SigHashType::All)[..]).unwrap();
                                        secp_ctx.verify(&htlc_sighash, &remote_signature, &keys.countersignatory_htlc_key).unwrap();
@@ -4773,20 +5111,18 @@ mod tests {
                                                assert!(preimage.is_some());
                                        }
 
-                                       let mut htlc_sig = htlc_sig_iter.next().unwrap();
-                                       while (htlc_sig.1).1.is_none() { htlc_sig = htlc_sig_iter.next().unwrap(); }
-                                       assert_eq!((htlc_sig.0).0.transaction_output_index, Some($htlc_idx));
+                                       let htlc_sig = htlc_sig_iter.next().unwrap();
+                                       assert_eq!((htlc_sig.0).0.transaction_output_index, Some($htlc_idx), "output index");
 
                                        let signature = Signature::from_der(&hex::decode($htlc_sig_hex).unwrap()[..]).unwrap();
-                                       assert_eq!(Some(signature), *(htlc_sig.1).1);
-                                       assert_eq!(serialize(&holdertx.get_signed_htlc_tx((htlc_sig.1).0, &(htlc_sig.1).1.unwrap(), &preimage, chan.counterparty_selected_contest_delay))[..],
-                                                       hex::decode($htlc_tx_hex).unwrap()[..]);
+                                       assert_eq!(signature, *(htlc_sig.1).1, "htlc sig");
+                                       let index = (htlc_sig.1).0;
+                                       let channel_parameters = chan.channel_transaction_parameters.as_holder_broadcastable();
+                                       let trusted_tx = holder_commitment_tx.trust();
+                                       assert_eq!(serialize(&trusted_tx.get_signed_htlc_tx(&channel_parameters, index, &(htlc_sig.0).1, (htlc_sig.1).1, &preimage))[..],
+                                                       hex::decode($htlc_tx_hex).unwrap()[..], "htlc tx");
                                })*
-                               loop {
-                                       let htlc_sig = htlc_sig_iter.next();
-                                       if htlc_sig.is_none() { break; }
-                                       assert!((htlc_sig.unwrap().1).1.is_none());
-                               }
+                               assert!(htlc_sig_iter.next().is_none());
                        } }
                }
 
@@ -5126,6 +5462,65 @@ mod tests {
                test_commitment!("304402202ade0142008309eb376736575ad58d03e5b115499709c6db0b46e36ff394b492022037b63d78d66404d6504d4c4ac13be346f3d1802928a6d3ad95a6a944227161a2",
                                 "304402207e8d51e0c570a5868a78414f4e0cbfaed1106b171b9581542c30718ee4eb95ba02203af84194c97adf98898c9afe2f2ed4a7f8dba05a2dfab28ac9d9c604aa49a379",
                                 "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b8001c0c62d0000000000160014cc1b07838e387deacd0e5232e1e8b49f4c29e484040047304402207e8d51e0c570a5868a78414f4e0cbfaed1106b171b9581542c30718ee4eb95ba02203af84194c97adf98898c9afe2f2ed4a7f8dba05a2dfab28ac9d9c604aa49a3790147304402202ade0142008309eb376736575ad58d03e5b115499709c6db0b46e36ff394b492022037b63d78d66404d6504d4c4ac13be346f3d1802928a6d3ad95a6a944227161a201475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", {});
+
+               // commitment tx with 3 htlc outputs, 2 offered having the same amount and preimage
+               chan.value_to_self_msat = 7_000_000_000 - 2_000_000;
+               chan.feerate_per_kw = 253;
+               chan.pending_inbound_htlcs.clear();
+               chan.pending_inbound_htlcs.push({
+                       let mut out = InboundHTLCOutput{
+                               htlc_id: 1,
+                               amount_msat: 2000000,
+                               cltv_expiry: 501,
+                               payment_hash: PaymentHash([0; 32]),
+                               state: InboundHTLCState::Committed,
+                       };
+                       out.payment_hash.0 = Sha256::hash(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()).into_inner();
+                       out
+               });
+               chan.pending_outbound_htlcs.clear();
+               chan.pending_outbound_htlcs.push({
+                       let mut out = OutboundHTLCOutput{
+                               htlc_id: 6,
+                               amount_msat: 5000000,
+                               cltv_expiry: 506,
+                               payment_hash: PaymentHash([0; 32]),
+                               state: OutboundHTLCState::Committed,
+                               source: HTLCSource::dummy(),
+                       };
+                       out.payment_hash.0 = Sha256::hash(&hex::decode("0505050505050505050505050505050505050505050505050505050505050505").unwrap()).into_inner();
+                       out
+               });
+               chan.pending_outbound_htlcs.push({
+                       let mut out = OutboundHTLCOutput{
+                               htlc_id: 5,
+                               amount_msat: 5000000,
+                               cltv_expiry: 505,
+                               payment_hash: PaymentHash([0; 32]),
+                               state: OutboundHTLCState::Committed,
+                               source: HTLCSource::dummy(),
+                       };
+                       out.payment_hash.0 = Sha256::hash(&hex::decode("0505050505050505050505050505050505050505050505050505050505050505").unwrap()).into_inner();
+                       out
+               });
+
+               test_commitment!("30440220048705bec5288d28b3f29344b8d124853b1af423a568664d2c6f02c8ea886525022060f998a461052a2476b912db426ea2a06700953a241135c7957f2e79bc222df9",
+                                "3045022100c4f1d60b6fca9febc8b39de1a31e84c5f7c4b41c97239ef05f4350aa484c6b5e02200c5134ac8b20eb7a29d0dd4a501f6aa8fefb8489171f4cb408bd2a32324ab03f",
+                                "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b8005d007000000000000220020748eba944fedc8827f6b06bc44678f93c0f9e6078b35c6331ed31e75f8ce0c2d8813000000000000220020305c12e1a0bc21e283c131cea1c66d68857d28b7b2fce0a6fbc40c164852121b8813000000000000220020305c12e1a0bc21e283c131cea1c66d68857d28b7b2fce0a6fbc40c164852121bc0c62d0000000000160014cc1b07838e387deacd0e5232e1e8b49f4c29e484a79f6a00000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0400483045022100c4f1d60b6fca9febc8b39de1a31e84c5f7c4b41c97239ef05f4350aa484c6b5e02200c5134ac8b20eb7a29d0dd4a501f6aa8fefb8489171f4cb408bd2a32324ab03f014730440220048705bec5288d28b3f29344b8d124853b1af423a568664d2c6f02c8ea886525022060f998a461052a2476b912db426ea2a06700953a241135c7957f2e79bc222df901475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", {
+
+                                 { 0,
+                                 "304502210081cbb94121761d34c189cd4e6a281feea6f585060ad0ba2632e8d6b3c6bb8a6c02201007981bbd16539d63df2805b5568f1f5688cd2a885d04706f50db9b77ba13c6",
+                                 "304502210090ed76aeb21b53236a598968abc66e2024691d07b62f53ddbeca8f93144af9c602205f873af5a0c10e62690e9aba09740550f194a9dc455ba4c1c23f6cde7704674c",
+                                 "0200000000010189a326e23addc28323dbadcb4e71c2c17088b6e8fa184103e552f44075dddc34000000000000000000011f070000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e050048304502210081cbb94121761d34c189cd4e6a281feea6f585060ad0ba2632e8d6b3c6bb8a6c02201007981bbd16539d63df2805b5568f1f5688cd2a885d04706f50db9b77ba13c60148304502210090ed76aeb21b53236a598968abc66e2024691d07b62f53ddbeca8f93144af9c602205f873af5a0c10e62690e9aba09740550f194a9dc455ba4c1c23f6cde7704674c012001010101010101010101010101010101010101010101010101010101010101018a76a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c8201208763a9144b6b2e5444c2639cc0fb7bcea5afba3f3cdce23988527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae677502f501b175ac686800000000" },
+                                 { 1,
+                                 "304402201d0f09d2bf7bc245a4f17980e1e9164290df16c70c6a2ff1592f5030d6108581022061e744a7dc151b36bf0aff7a4f1812ba90b8b03633bb979a270d19858fd960c5",
+                                 "30450221009aef000d2e843a4202c1b1a2bf554abc9a7902bf49b2cb0759bc507456b7ebad02204e7c3d193ede2fd2b4cd6b39f51a920e581e35575e357e44d7b699c40ce61d39",
+                                 "0200000000010189a326e23addc28323dbadcb4e71c2c17088b6e8fa184103e552f44075dddc3401000000000000000001e1120000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e050047304402201d0f09d2bf7bc245a4f17980e1e9164290df16c70c6a2ff1592f5030d6108581022061e744a7dc151b36bf0aff7a4f1812ba90b8b03633bb979a270d19858fd960c5014830450221009aef000d2e843a4202c1b1a2bf554abc9a7902bf49b2cb0759bc507456b7ebad02204e7c3d193ede2fd2b4cd6b39f51a920e581e35575e357e44d7b699c40ce61d3901008576a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c820120876475527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae67a9142002cc93ebefbb1b73f0af055dcc27a0b504ad7688ac6868f9010000" },
+                                 { 2,
+                                 "30440220010bf035d5823596e50dce2076a4d9f942d8d28031c9c428b901a02b6b8140de02203250e8e4a08bc5b4ecdca4d0eedf98223e02e3ac1c0206b3a7ffdb374aa21e5f",
+                                 "30440220073de0067b88e425b3018b30366bfeda0ccb703118ccd3d02ead08c0f53511d002203fac50ac0e4cf8a3af0b4b1b12e801650591f748f8ddf1e089c160f10b69e511",
+                                 "0200000000010189a326e23addc28323dbadcb4e71c2c17088b6e8fa184103e552f44075dddc3402000000000000000001e1120000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e05004730440220010bf035d5823596e50dce2076a4d9f942d8d28031c9c428b901a02b6b8140de02203250e8e4a08bc5b4ecdca4d0eedf98223e02e3ac1c0206b3a7ffdb374aa21e5f014730440220073de0067b88e425b3018b30366bfeda0ccb703118ccd3d02ead08c0f53511d002203fac50ac0e4cf8a3af0b4b1b12e801650591f748f8ddf1e089c160f10b69e51101008576a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c820120876475527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae67a9142002cc93ebefbb1b73f0af055dcc27a0b504ad7688ac6868fa010000" }
+               } );
        }
 
        #[test]
index c39eef3ea477a9d7558b69629601c4be14d6dbfc..b56ce5d9d052aa38c955d172e498d6cde4260713 100644 (file)
@@ -18,7 +18,7 @@
 //! imply it needs to fail HTLCs/payments/channels it manages).
 //!
 
-use bitcoin::blockdata::block::BlockHeader;
+use bitcoin::blockdata::block::{Block, BlockHeader};
 use bitcoin::blockdata::constants::genesis_block;
 use bitcoin::network::constants::Network;
 
@@ -46,7 +46,7 @@ use ln::msgs;
 use ln::msgs::NetAddress;
 use ln::onion_utils;
 use ln::msgs::{ChannelMessageHandler, DecodeError, LightningError, OptionalField};
-use chain::keysinterface::{ChannelKeys, KeysInterface, KeysManager, InMemoryChannelKeys};
+use chain::keysinterface::{Sign, KeysInterface, KeysManager, InMemorySigner};
 use util::config::UserConfig;
 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
 use util::{byte_utils, events};
@@ -58,9 +58,11 @@ use util::errors::APIError;
 use std::{cmp, mem};
 use std::collections::{HashMap, hash_map, HashSet};
 use std::io::{Cursor, Read};
-use std::sync::{Arc, Mutex, MutexGuard, RwLock};
+use std::sync::{Arc, Condvar, Mutex, MutexGuard, RwLock, RwLockReadGuard};
 use std::sync::atomic::{AtomicUsize, Ordering};
 use std::time::Duration;
+#[cfg(any(test, feature = "allow_wallclock_use"))]
+use std::time::Instant;
 use std::marker::{Sync, Send};
 use std::ops::Deref;
 use bitcoin::hashes::hex::ToHex;
@@ -312,8 +314,8 @@ pub(super) enum RAACommitmentOrder {
 }
 
 // Note this is only exposed in cfg(test):
-pub(super) struct ChannelHolder<ChanSigner: ChannelKeys> {
-       pub(super) by_id: HashMap<[u8; 32], Channel<ChanSigner>>,
+pub(super) struct ChannelHolder<Signer: Sign> {
+       pub(super) by_id: HashMap<[u8; 32], Channel<Signer>>,
        pub(super) short_to_id: HashMap<u64, [u8; 32]>,
        /// short channel id -> forward infos. Key of 0 means payments received
        /// Note that while this is held in the same mutex as the channels themselves, no consistency
@@ -347,7 +349,7 @@ const ERR: () = "You need at least 32 bit pointers (well, usize, but we'll assum
 /// issues such as overly long function definitions. Note that the ChannelManager can take any
 /// type that implements KeysInterface for its keys manager, but this type alias chooses the
 /// concrete type of the KeysManager.
-pub type SimpleArcChannelManager<M, T, F, L> = Arc<ChannelManager<InMemoryChannelKeys, Arc<M>, Arc<T>, Arc<KeysManager>, Arc<F>, Arc<L>>>;
+pub type SimpleArcChannelManager<M, T, F, L> = ChannelManager<InMemorySigner, Arc<M>, Arc<T>, Arc<KeysManager>, Arc<F>, Arc<L>>;
 
 /// SimpleRefChannelManager is a type alias for a ChannelManager reference, and is the reference
 /// counterpart to the SimpleArcChannelManager type alias. Use this type by default when you don't
@@ -357,7 +359,7 @@ pub type SimpleArcChannelManager<M, T, F, L> = Arc<ChannelManager<InMemoryChanne
 /// helps with issues such as long function definitions. Note that the ChannelManager can take any
 /// type that implements KeysInterface for its keys manager, but this type alias chooses the
 /// concrete type of the KeysManager.
-pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, M, T, F, L> = ChannelManager<InMemoryChannelKeys, &'a M, &'b T, &'c KeysManager, &'d F, &'e L>;
+pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, M, T, F, L> = ChannelManager<InMemorySigner, &'a M, &'b T, &'c KeysManager, &'d F, &'e L>;
 
 /// Manager which keeps track of a number of channels and sends messages to the appropriate
 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
@@ -378,7 +380,7 @@ pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, M, T, F, L> = ChannelManage
 /// ChannelMonitors passed by reference to read(), those channels will be force-closed based on the
 /// ChannelMonitor state and no funds will be lost (mod on-chain transaction fees).
 ///
-/// Note that the deserializer is only implemented for (Sha256dHash, ChannelManager), which
+/// Note that the deserializer is only implemented for (Option<BlockHash>, ChannelManager), which
 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
 /// the "reorg path" (ie call block_disconnected() until you get to a common block and then call
 /// block_connected() to step towards your best block) upon deserialization before using the
@@ -395,10 +397,10 @@ pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, M, T, F, L> = ChannelManage
 /// essentially you should default to using a SimpleRefChannelManager, and use a
 /// SimpleArcChannelManager when you require a ChannelManager with a static lifetime, such as when
 /// you're using lightning-net-tokio.
-pub struct ChannelManager<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
-       where M::Target: chain::Watch<Keys=ChanSigner>,
+pub struct ChannelManager<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
+       where M::Target: chain::Watch<Signer>,
         T::Target: BroadcasterInterface,
-        K::Target: KeysInterface<ChanKeySigner = ChanSigner>,
+        K::Target: KeysInterface<Signer = Signer>,
         F::Target: FeeEstimator,
                                L::Target: Logger,
 {
@@ -416,9 +418,9 @@ pub struct ChannelManager<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref,
        secp_ctx: Secp256k1<secp256k1::All>,
 
        #[cfg(any(test, feature = "_test_utils"))]
-       pub(super) channel_state: Mutex<ChannelHolder<ChanSigner>>,
+       pub(super) channel_state: Mutex<ChannelHolder<Signer>>,
        #[cfg(not(any(test, feature = "_test_utils")))]
-       channel_state: Mutex<ChannelHolder<ChanSigner>>,
+       channel_state: Mutex<ChannelHolder<Signer>>,
        our_network_key: SecretKey,
 
        /// Used to track the last value sent in a node_announcement "timestamp" field. We ensure this
@@ -437,13 +439,46 @@ pub struct ChannelManager<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref,
        /// Used when we have to take a BIG lock to make sure everything is self-consistent.
        /// Essentially just when we're serializing ourselves out.
        /// Taken first everywhere where we are making changes before any other locks.
+       /// When acquiring this lock in read mode, rather than acquiring it directly, call
+       /// `PersistenceNotifierGuard::new(..)` and pass the lock to it, to ensure the PersistenceNotifier
+       /// the lock contains sends out a notification when the lock is released.
        total_consistency_lock: RwLock<()>,
 
+       persistence_notifier: PersistenceNotifier,
+
        keys_manager: K,
 
        logger: L,
 }
 
+/// Whenever we release the `ChannelManager`'s `total_consistency_lock`, from read mode, it is
+/// desirable to notify any listeners on `wait_timeout`/`wait` that new updates are available for
+/// persistence. Therefore, this struct is responsible for locking the total consistency lock and,
+/// upon going out of scope, sending the aforementioned notification (since the lock being released
+/// indicates that the updates are ready for persistence).
+struct PersistenceNotifierGuard<'a> {
+       persistence_notifier: &'a PersistenceNotifier,
+       // We hold onto this result so the lock doesn't get released immediately.
+       _read_guard: RwLockReadGuard<'a, ()>,
+}
+
+impl<'a> PersistenceNotifierGuard<'a> {
+       fn new(lock: &'a RwLock<()>, notifier: &'a PersistenceNotifier) -> Self {
+               let read_guard = lock.read().unwrap();
+
+               Self {
+                       persistence_notifier: notifier,
+                       _read_guard: read_guard,
+               }
+       }
+}
+
+impl<'a> Drop for PersistenceNotifierGuard<'a> {
+       fn drop(&mut self) {
+               self.persistence_notifier.notify();
+       }
+}
+
 /// The amount of time we require our counterparty wait to claim their money (ie time between when
 /// we, or our watchtower, must check for them having broadcast a theft transaction).
 pub(crate) const BREAKDOWN_TIMEOUT: u16 = 6 * 24;
@@ -514,7 +549,7 @@ pub struct ChannelDetails {
 /// If a payment fails to send, it can be in one of several states. This enum is returned as the
 /// Err() type describing which state the payment is in, see the description of individual enum
 /// states for more.
-#[derive(Debug)]
+#[derive(Clone, Debug)]
 pub enum PaymentSendFailure {
        /// A parameter which was passed to send_payment was invalid, preventing us from attempting to
        /// send the payment at all. No channel state has been changed or messages sent to peers, and
@@ -709,10 +744,10 @@ macro_rules! maybe_break_monitor_err {
        }
 }
 
-impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<ChanSigner, M, T, K, F, L>
-       where M::Target: chain::Watch<Keys=ChanSigner>,
+impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<Signer, M, T, K, F, L>
+       where M::Target: chain::Watch<Signer>,
         T::Target: BroadcasterInterface,
-        K::Target: KeysInterface<ChanKeySigner = ChanSigner>,
+        K::Target: KeysInterface<Signer = Signer>,
         F::Target: FeeEstimator,
         L::Target: Logger,
 {
@@ -731,7 +766,8 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
        /// Users need to notify the new ChannelManager when a new block is connected or
        /// disconnected using its `block_connected` and `block_disconnected` methods.
        pub fn new(network: Network, fee_est: F, chain_monitor: M, tx_broadcaster: T, logger: L, keys_manager: K, config: UserConfig, current_blockchain_height: usize) -> Self {
-               let secp_ctx = Secp256k1::new();
+               let mut secp_ctx = Secp256k1::new();
+               secp_ctx.seeded_randomize(&keys_manager.get_secure_random_bytes());
 
                ChannelManager {
                        default_configuration: config.clone(),
@@ -759,6 +795,7 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
 
                        pending_events: Mutex::new(Vec::new()),
                        total_consistency_lock: RwLock::new(()),
+                       persistence_notifier: PersistenceNotifier::new(),
 
                        keys_manager,
 
@@ -787,7 +824,10 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
                let channel = Channel::new_outbound(&self.fee_estimator, &self.keys_manager, their_network_key, channel_value_satoshis, push_msat, user_id, config)?;
                let res = channel.get_open_channel(self.genesis_hash.clone());
 
-               let _consistency_lock = self.total_consistency_lock.read().unwrap();
+               let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
+               // We want to make sure the lock is actually acquired by PersistenceNotifierGuard.
+               debug_assert!(&self.total_consistency_lock.try_write().is_err());
+
                let mut channel_state = self.channel_state.lock().unwrap();
                match channel_state.by_id.entry(channel.channel_id()) {
                        hash_map::Entry::Occupied(_) => {
@@ -806,7 +846,7 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
                Ok(())
        }
 
-       fn list_channels_with_filter<Fn: FnMut(&(&[u8; 32], &Channel<ChanSigner>)) -> bool>(&self, f: Fn) -> Vec<ChannelDetails> {
+       fn list_channels_with_filter<Fn: FnMut(&(&[u8; 32], &Channel<Signer>)) -> bool>(&self, f: Fn) -> Vec<ChannelDetails> {
                let mut res = Vec::new();
                {
                        let channel_state = self.channel_state.lock().unwrap();
@@ -859,7 +899,7 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
        ///
        /// May generate a SendShutdown message event on success, which should be relayed.
        pub fn close_channel(&self, channel_id: &[u8; 32]) -> Result<(), APIError> {
-               let _consistency_lock = self.total_consistency_lock.read().unwrap();
+               let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
 
                let (mut failed_htlcs, chan_option) = {
                        let mut channel_state_lock = self.channel_state.lock().unwrap();
@@ -916,21 +956,24 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
                }
        }
 
-       /// Force closes a channel, immediately broadcasting the latest local commitment transaction to
-       /// the chain and rejecting new HTLCs on the given channel.
-       pub fn force_close_channel(&self, channel_id: &[u8; 32]) {
-               let _consistency_lock = self.total_consistency_lock.read().unwrap();
-
+       fn force_close_channel_with_peer(&self, channel_id: &[u8; 32], peer_node_id: Option<&PublicKey>) -> Result<(), APIError> {
                let mut chan = {
                        let mut channel_state_lock = self.channel_state.lock().unwrap();
                        let channel_state = &mut *channel_state_lock;
-                       if let Some(chan) = channel_state.by_id.remove(channel_id) {
-                               if let Some(short_id) = chan.get_short_channel_id() {
+                       if let hash_map::Entry::Occupied(chan) = channel_state.by_id.entry(channel_id.clone()) {
+                               if let Some(node_id) = peer_node_id {
+                                       if chan.get().get_counterparty_node_id() != *node_id {
+                                               // Error or Ok here doesn't matter - the result is only exposed publicly
+                                               // when peer_node_id is None anyway.
+                                               return Ok(());
+                                       }
+                               }
+                               if let Some(short_id) = chan.get().get_short_channel_id() {
                                        channel_state.short_to_id.remove(&short_id);
                                }
-                               chan
+                               chan.remove_entry().1
                        } else {
-                               return;
+                               return Err(APIError::ChannelUnavailable{err: "No such channel".to_owned()});
                        }
                };
                log_trace!(self.logger, "Force-closing channel {}", log_bytes!(channel_id[..]));
@@ -941,17 +984,26 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
                                msg: update
                        });
                }
+
+               Ok(())
+       }
+
+       /// Force closes a channel, immediately broadcasting the latest local commitment transaction to
+       /// the chain and rejecting new HTLCs on the given channel. Fails if channel_id is unknown to the manager.
+       pub fn force_close_channel(&self, channel_id: &[u8; 32]) -> Result<(), APIError> {
+               let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
+               self.force_close_channel_with_peer(channel_id, None)
        }
 
        /// Force close all channels, immediately broadcasting the latest local commitment transaction
        /// for each to the chain and rejecting new HTLCs on each.
        pub fn force_close_all_channels(&self) {
                for chan in self.list_channels() {
-                       self.force_close_channel(&chan.channel_id);
+                       let _ = self.force_close_channel(&chan.channel_id);
                }
        }
 
-       fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard<ChannelHolder<ChanSigner>>) {
+       fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard<ChannelHolder<Signer>>) {
                macro_rules! return_malformed_err {
                        ($msg: expr, $err_code: expr) => {
                                {
@@ -1223,7 +1275,7 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
 
        /// only fails if the channel does not yet have an assigned short_id
        /// May be called with channel_state already locked!
-       fn get_channel_update(&self, chan: &Channel<ChanSigner>) -> Result<msgs::ChannelUpdate, LightningError> {
+       fn get_channel_update(&self, chan: &Channel<Signer>) -> Result<msgs::ChannelUpdate, LightningError> {
                let short_channel_id = match chan.get_short_channel_id() {
                        None => return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError}),
                        Some(id) => id,
@@ -1267,7 +1319,7 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
                }
                let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, prng_seed, payment_hash);
 
-               let _consistency_lock = self.total_consistency_lock.read().unwrap();
+               let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
 
                let err: Result<(), _> = loop {
                        let mut channel_lock = self.channel_state.lock().unwrap();
@@ -1435,7 +1487,7 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
        /// May panic if the funding_txo is duplicative with some other channel (note that this should
        /// be trivially prevented by using unique funding transaction keys per-channel).
        pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], funding_txo: OutPoint) {
-               let _consistency_lock = self.total_consistency_lock.read().unwrap();
+               let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
 
                let (chan, msg) = {
                        let (res, chan) = match self.channel_state.lock().unwrap().by_id.remove(temporary_channel_id) {
@@ -1471,7 +1523,7 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
                }
        }
 
-       fn get_announcement_sigs(&self, chan: &Channel<ChanSigner>) -> Option<msgs::AnnouncementSignatures> {
+       fn get_announcement_sigs(&self, chan: &Channel<Signer>) -> Option<msgs::AnnouncementSignatures> {
                if !chan.should_announce() {
                        log_trace!(self.logger, "Can't send announcement_signatures for private channel {}", log_bytes!(chan.channel_id()));
                        return None
@@ -1518,7 +1570,7 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
        ///
        /// Panics if addresses is absurdly large (more than 500).
        pub fn broadcast_node_announcement(&self, rgb: [u8; 3], alias: [u8; 32], addresses: Vec<NetAddress>) {
-               let _consistency_lock = self.total_consistency_lock.read().unwrap();
+               let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
 
                if addresses.len() > 500 {
                        panic!("More than half the message size was taken up by public addresses!");
@@ -1548,7 +1600,7 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
        /// Should only really ever be called in response to a PendingHTLCsForwardable event.
        /// Will likely generate further events.
        pub fn process_pending_htlc_forwards(&self) {
-               let _consistency_lock = self.total_consistency_lock.read().unwrap();
+               let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
 
                let mut new_events = Vec::new();
                let mut failed_forwards = Vec::new();
@@ -1808,7 +1860,7 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
        ///
        /// This method handles all the details, and must be called roughly once per minute.
        pub fn timer_chan_freshness_every_min(&self) {
-               let _consistency_lock = self.total_consistency_lock.read().unwrap();
+               let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
                let mut channel_state_lock = self.channel_state.lock().unwrap();
                let channel_state = &mut *channel_state_lock;
                for (_, chan) in channel_state.by_id.iter_mut() {
@@ -1833,7 +1885,7 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
        /// Returns false if no payment was found to fail backwards, true if the process of failing the
        /// HTLC backwards has been started.
        pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash, payment_secret: &Option<PaymentSecret>) -> bool {
-               let _consistency_lock = self.total_consistency_lock.read().unwrap();
+               let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
 
                let mut channel_state = Some(self.channel_state.lock().unwrap());
                let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&(*payment_hash, *payment_secret));
@@ -1896,7 +1948,7 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
        /// to fail and take the channel_state lock for each iteration (as we take ownership and may
        /// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to
        /// still-available channels.
-       fn fail_htlc_backwards_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder<ChanSigner>>, source: HTLCSource, payment_hash: &PaymentHash, onion_error: HTLCFailReason) {
+       fn fail_htlc_backwards_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder<Signer>>, source: HTLCSource, payment_hash: &PaymentHash, onion_error: HTLCFailReason) {
                //TODO: There is a timing attack here where if a node fails an HTLC back to us they can
                //identify whether we sent it or not based on the (I presume) very different runtime
                //between the branches here. We should make this async and move it into the forward HTLCs
@@ -2012,7 +2064,7 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
        pub fn claim_funds(&self, payment_preimage: PaymentPreimage, payment_secret: &Option<PaymentSecret>, expected_amount: u64) -> bool {
                let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
 
-               let _consistency_lock = self.total_consistency_lock.read().unwrap();
+               let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
 
                let mut channel_state = Some(self.channel_state.lock().unwrap());
                let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&(payment_hash, *payment_secret));
@@ -2090,7 +2142,7 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
                } else { false }
        }
 
-       fn claim_funds_from_hop(&self, channel_state_lock: &mut MutexGuard<ChannelHolder<ChanSigner>>, prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage) -> Result<(), Option<(PublicKey, MsgHandleErrInternal)>> {
+       fn claim_funds_from_hop(&self, channel_state_lock: &mut MutexGuard<ChannelHolder<Signer>>, prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage) -> Result<(), Option<(PublicKey, MsgHandleErrInternal)>> {
                //TODO: Delay the claimed_funds relaying just like we do outbound relay!
                let channel_state = &mut **channel_state_lock;
                let chan_id = match channel_state.short_to_id.get(&prev_hop.short_channel_id) {
@@ -2143,7 +2195,7 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
                } else { unreachable!(); }
        }
 
-       fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder<ChanSigner>>, source: HTLCSource, payment_preimage: PaymentPreimage) {
+       fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder<Signer>>, source: HTLCSource, payment_preimage: PaymentPreimage) {
                match source {
                        HTLCSource::OutboundRoute { .. } => {
                                mem::drop(channel_state_lock);
@@ -2208,7 +2260,7 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
        ///  4) once all remote copies are updated, you call this function with the update_id that
        ///     completed, and once it is the latest the Channel will be re-enabled.
        pub fn channel_monitor_updated(&self, funding_txo: &OutPoint, highest_applied_update_id: u64) {
-               let _consistency_lock = self.total_consistency_lock.read().unwrap();
+               let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
 
                let mut close_results = Vec::new();
                let mut htlc_forwards = Vec::new();
@@ -2456,7 +2508,7 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
                }
        }
 
-       fn internal_shutdown(&self, counterparty_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
+       fn internal_shutdown(&self, counterparty_node_id: &PublicKey, their_features: &InitFeatures, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
                let (mut dropped_htlcs, chan_option) = {
                        let mut channel_state_lock = self.channel_state.lock().unwrap();
                        let channel_state = &mut *channel_state_lock;
@@ -2466,7 +2518,7 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
                                        if chan_entry.get().get_counterparty_node_id() != *counterparty_node_id {
                                                return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
                                        }
-                                       let (shutdown, closing_signed, dropped_htlcs) = try_chan_entry!(self, chan_entry.get_mut().shutdown(&self.fee_estimator, &msg), channel_state, chan_entry);
+                                       let (shutdown, closing_signed, dropped_htlcs) = try_chan_entry!(self, chan_entry.get_mut().shutdown(&self.fee_estimator, &their_features, &msg), channel_state, chan_entry);
                                        if let Some(msg) = shutdown {
                                                channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
                                                        node_id: counterparty_node_id.clone(),
@@ -2568,7 +2620,7 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
                                        return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
                                }
 
-                               let create_pending_htlc_status = |chan: &Channel<ChanSigner>, pending_forward_info: PendingHTLCStatus, error_code: u16| {
+                               let create_pending_htlc_status = |chan: &Channel<Signer>, pending_forward_info: PendingHTLCStatus, error_code: u16| {
                                        // Ensure error_code has the UPDATE flag set, since by default we send a
                                        // channel update along as part of failing the HTLC.
                                        assert!((error_code & 0x1000) != 0);
@@ -2959,7 +3011,7 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
        /// (C-not exported) Cause its doc(hidden) anyway
        #[doc(hidden)]
        pub fn update_fee(&self, channel_id: [u8;32], feerate_per_kw: u32) -> Result<(), APIError> {
-               let _consistency_lock = self.total_consistency_lock.read().unwrap();
+               let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
                let counterparty_node_id;
                let err: Result<(), _> = loop {
                        let mut channel_state_lock = self.channel_state.lock().unwrap();
@@ -3050,10 +3102,10 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
        }
 }
 
-impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> MessageSendEventsProvider for ChannelManager<ChanSigner, M, T, K, F, L>
-       where M::Target: chain::Watch<Keys=ChanSigner>,
+impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> MessageSendEventsProvider for ChannelManager<Signer, M, T, K, F, L>
+       where M::Target: chain::Watch<Signer>,
         T::Target: BroadcasterInterface,
-        K::Target: KeysInterface<ChanKeySigner = ChanSigner>,
+        K::Target: KeysInterface<Signer = Signer>,
         F::Target: FeeEstimator,
                                L::Target: Logger,
 {
@@ -3069,10 +3121,10 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
        }
 }
 
-impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> EventsProvider for ChannelManager<ChanSigner, M, T, K, F, L>
-       where M::Target: chain::Watch<Keys=ChanSigner>,
+impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> EventsProvider for ChannelManager<Signer, M, T, K, F, L>
+       where M::Target: chain::Watch<Signer>,
         T::Target: BroadcasterInterface,
-        K::Target: KeysInterface<ChanKeySigner = ChanSigner>,
+        K::Target: KeysInterface<Signer = Signer>,
         F::Target: FeeEstimator,
                                L::Target: Logger,
 {
@@ -3088,10 +3140,28 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
        }
 }
 
-impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<ChanSigner, M, T, K, F, L>
-       where M::Target: chain::Watch<Keys=ChanSigner>,
+impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> chain::Listen for ChannelManager<Signer, M, T, K, F, L>
+where
+       M::Target: chain::Watch<Signer>,
+       T::Target: BroadcasterInterface,
+       K::Target: KeysInterface<Signer = Signer>,
+       F::Target: FeeEstimator,
+       L::Target: Logger,
+{
+       fn block_connected(&self, block: &Block, height: u32) {
+               let txdata: Vec<_> = block.txdata.iter().enumerate().collect();
+               ChannelManager::block_connected(self, &block.header, &txdata, height);
+       }
+
+       fn block_disconnected(&self, header: &BlockHeader, _height: u32) {
+               ChannelManager::block_disconnected(self, header);
+       }
+}
+
+impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<Signer, M, T, K, F, L>
+       where M::Target: chain::Watch<Signer>,
         T::Target: BroadcasterInterface,
-        K::Target: KeysInterface<ChanKeySigner = ChanSigner>,
+        K::Target: KeysInterface<Signer = Signer>,
         F::Target: FeeEstimator,
         L::Target: Logger,
 {
@@ -3099,7 +3169,7 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
        pub fn block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
                let header_hash = header.block_hash();
                log_trace!(self.logger, "Block {} at height {} connected", header_hash, height);
-               let _consistency_lock = self.total_consistency_lock.read().unwrap();
+               let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
                let mut failed_channels = Vec::new();
                let mut timed_out_htlcs = Vec::new();
                {
@@ -3212,7 +3282,7 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
        /// If necessary, the channel may be force-closed without letting the counterparty participate
        /// in the shutdown.
        pub fn block_disconnected(&self, header: &BlockHeader) {
-               let _consistency_lock = self.total_consistency_lock.read().unwrap();
+               let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
                let mut failed_channels = Vec::new();
                {
                        let mut channel_lock = self.channel_state.lock().unwrap();
@@ -3242,98 +3312,121 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
                self.latest_block_height.fetch_sub(1, Ordering::AcqRel);
                *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.block_hash();
        }
+
+       /// Blocks until ChannelManager needs to be persisted or a timeout is reached. It returns a bool
+       /// indicating whether persistence is necessary. Only one listener on `wait_timeout` is
+       /// guaranteed to be woken up.
+       /// Note that the feature `allow_wallclock_use` must be enabled to use this function.
+       #[cfg(any(test, feature = "allow_wallclock_use"))]
+       pub fn wait_timeout(&self, max_wait: Duration) -> bool {
+               self.persistence_notifier.wait_timeout(max_wait)
+       }
+
+       /// Blocks until ChannelManager needs to be persisted. Only one listener on `wait` is
+       /// guaranteed to be woken up.
+       pub fn wait(&self) {
+               self.persistence_notifier.wait()
+       }
+
+       #[cfg(any(test, feature = "_test_utils"))]
+       pub fn get_persistence_condvar_value(&self) -> bool {
+               let mutcond = &self.persistence_notifier.persistence_lock;
+               let &(ref mtx, _) = mutcond;
+               let guard = mtx.lock().unwrap();
+               *guard
+       }
 }
 
-impl<ChanSigner: ChannelKeys, M: Deref + Sync + Send, T: Deref + Sync + Send, K: Deref + Sync + Send, F: Deref + Sync + Send, L: Deref + Sync + Send>
-       ChannelMessageHandler for ChannelManager<ChanSigner, M, T, K, F, L>
-       where M::Target: chain::Watch<Keys=ChanSigner>,
+impl<Signer: Sign, M: Deref + Sync + Send, T: Deref + Sync + Send, K: Deref + Sync + Send, F: Deref + Sync + Send, L: Deref + Sync + Send>
+       ChannelMessageHandler for ChannelManager<Signer, M, T, K, F, L>
+       where M::Target: chain::Watch<Signer>,
         T::Target: BroadcasterInterface,
-        K::Target: KeysInterface<ChanKeySigner = ChanSigner>,
+        K::Target: KeysInterface<Signer = Signer>,
         F::Target: FeeEstimator,
         L::Target: Logger,
 {
        fn handle_open_channel(&self, counterparty_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::OpenChannel) {
-               let _consistency_lock = self.total_consistency_lock.read().unwrap();
+               let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
                let _ = handle_error!(self, self.internal_open_channel(counterparty_node_id, their_features, msg), *counterparty_node_id);
        }
 
        fn handle_accept_channel(&self, counterparty_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::AcceptChannel) {
-               let _consistency_lock = self.total_consistency_lock.read().unwrap();
+               let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
                let _ = handle_error!(self, self.internal_accept_channel(counterparty_node_id, their_features, msg), *counterparty_node_id);
        }
 
        fn handle_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) {
-               let _consistency_lock = self.total_consistency_lock.read().unwrap();
+               let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
                let _ = handle_error!(self, self.internal_funding_created(counterparty_node_id, msg), *counterparty_node_id);
        }
 
        fn handle_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) {
-               let _consistency_lock = self.total_consistency_lock.read().unwrap();
+               let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
                let _ = handle_error!(self, self.internal_funding_signed(counterparty_node_id, msg), *counterparty_node_id);
        }
 
        fn handle_funding_locked(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingLocked) {
-               let _consistency_lock = self.total_consistency_lock.read().unwrap();
+               let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
                let _ = handle_error!(self, self.internal_funding_locked(counterparty_node_id, msg), *counterparty_node_id);
        }
 
-       fn handle_shutdown(&self, counterparty_node_id: &PublicKey, msg: &msgs::Shutdown) {
-               let _consistency_lock = self.total_consistency_lock.read().unwrap();
-               let _ = handle_error!(self, self.internal_shutdown(counterparty_node_id, msg), *counterparty_node_id);
+       fn handle_shutdown(&self, counterparty_node_id: &PublicKey, their_features: &InitFeatures, msg: &msgs::Shutdown) {
+               let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
+               let _ = handle_error!(self, self.internal_shutdown(counterparty_node_id, their_features, msg), *counterparty_node_id);
        }
 
        fn handle_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
-               let _consistency_lock = self.total_consistency_lock.read().unwrap();
+               let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
                let _ = handle_error!(self, self.internal_closing_signed(counterparty_node_id, msg), *counterparty_node_id);
        }
 
        fn handle_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
-               let _consistency_lock = self.total_consistency_lock.read().unwrap();
+               let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
                let _ = handle_error!(self, self.internal_update_add_htlc(counterparty_node_id, msg), *counterparty_node_id);
        }
 
        fn handle_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
-               let _consistency_lock = self.total_consistency_lock.read().unwrap();
+               let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
                let _ = handle_error!(self, self.internal_update_fulfill_htlc(counterparty_node_id, msg), *counterparty_node_id);
        }
 
        fn handle_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
-               let _consistency_lock = self.total_consistency_lock.read().unwrap();
+               let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
                let _ = handle_error!(self, self.internal_update_fail_htlc(counterparty_node_id, msg), *counterparty_node_id);
        }
 
        fn handle_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
-               let _consistency_lock = self.total_consistency_lock.read().unwrap();
+               let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
                let _ = handle_error!(self, self.internal_update_fail_malformed_htlc(counterparty_node_id, msg), *counterparty_node_id);
        }
 
        fn handle_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
-               let _consistency_lock = self.total_consistency_lock.read().unwrap();
+               let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
                let _ = handle_error!(self, self.internal_commitment_signed(counterparty_node_id, msg), *counterparty_node_id);
        }
 
        fn handle_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
-               let _consistency_lock = self.total_consistency_lock.read().unwrap();
+               let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
                let _ = handle_error!(self, self.internal_revoke_and_ack(counterparty_node_id, msg), *counterparty_node_id);
        }
 
        fn handle_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) {
-               let _consistency_lock = self.total_consistency_lock.read().unwrap();
+               let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
                let _ = handle_error!(self, self.internal_update_fee(counterparty_node_id, msg), *counterparty_node_id);
        }
 
        fn handle_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
-               let _consistency_lock = self.total_consistency_lock.read().unwrap();
+               let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
                let _ = handle_error!(self, self.internal_announcement_signatures(counterparty_node_id, msg), *counterparty_node_id);
        }
 
        fn handle_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
-               let _consistency_lock = self.total_consistency_lock.read().unwrap();
+               let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
                let _ = handle_error!(self, self.internal_channel_reestablish(counterparty_node_id, msg), *counterparty_node_id);
        }
 
        fn peer_disconnected(&self, counterparty_node_id: &PublicKey, no_connection_possible: bool) {
-               let _consistency_lock = self.total_consistency_lock.read().unwrap();
+               let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
                let mut failed_channels = Vec::new();
                let mut failed_payments = Vec::new();
                let mut no_channels_remain = true;
@@ -3426,7 +3519,7 @@ impl<ChanSigner: ChannelKeys, M: Deref + Sync + Send, T: Deref + Sync + Send, K:
        fn peer_connected(&self, counterparty_node_id: &PublicKey, init_msg: &msgs::Init) {
                log_debug!(self.logger, "Generating channel_reestablish events for {}", log_pubkey!(counterparty_node_id));
 
-               let _consistency_lock = self.total_consistency_lock.read().unwrap();
+               let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
 
                {
                        let mut peer_state_lock = self.per_peer_state.write().unwrap();
@@ -3466,18 +3559,83 @@ impl<ChanSigner: ChannelKeys, M: Deref + Sync + Send, T: Deref + Sync + Send, K:
        }
 
        fn handle_error(&self, counterparty_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
-               let _consistency_lock = self.total_consistency_lock.read().unwrap();
+               let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
 
                if msg.channel_id == [0; 32] {
                        for chan in self.list_channels() {
                                if chan.remote_network_id == *counterparty_node_id {
-                                       self.force_close_channel(&chan.channel_id);
+                                       // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
+                                       let _ = self.force_close_channel_with_peer(&chan.channel_id, Some(counterparty_node_id));
                                }
                        }
                } else {
-                       self.force_close_channel(&msg.channel_id);
+                       // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
+                       let _ = self.force_close_channel_with_peer(&msg.channel_id, Some(counterparty_node_id));
+               }
+       }
+}
+
+/// Used to signal to the ChannelManager persister that the manager needs to be re-persisted to
+/// disk/backups, through `wait_timeout` and `wait`.
+struct PersistenceNotifier {
+       /// Users won't access the persistence_lock directly, but rather wait on its bool using
+       /// `wait_timeout` and `wait`.
+       persistence_lock: (Mutex<bool>, Condvar),
+}
+
+impl PersistenceNotifier {
+       fn new() -> Self {
+               Self {
+                       persistence_lock: (Mutex::new(false), Condvar::new()),
+               }
+       }
+
+       fn wait(&self) {
+               loop {
+                       let &(ref mtx, ref cvar) = &self.persistence_lock;
+                       let mut guard = mtx.lock().unwrap();
+                       guard = cvar.wait(guard).unwrap();
+                       let result = *guard;
+                       if result {
+                               *guard = false;
+                               return
+                       }
+               }
+       }
+
+       #[cfg(any(test, feature = "allow_wallclock_use"))]
+       fn wait_timeout(&self, max_wait: Duration) -> bool {
+               let current_time = Instant::now();
+               loop {
+                       let &(ref mtx, ref cvar) = &self.persistence_lock;
+                       let mut guard = mtx.lock().unwrap();
+                       guard = cvar.wait_timeout(guard, max_wait).unwrap().0;
+                       // Due to spurious wakeups that can happen on `wait_timeout`, here we need to check if the
+                       // desired wait time has actually passed, and if not then restart the loop with a reduced wait
+                       // time. Note that this logic can be highly simplified through the use of
+                       // `Condvar::wait_while` and `Condvar::wait_timeout_while`, if and when our MSRV is raised to
+                       // 1.42.0.
+                       let elapsed = current_time.elapsed();
+                       let result = *guard;
+                       if result || elapsed >= max_wait {
+                               *guard = false;
+                               return result;
+                       }
+                       match max_wait.checked_sub(elapsed) {
+                               None => return result,
+                               Some(_) => continue
+                       }
                }
        }
+
+       // Signal to the ChannelManager persister that there are updates necessitating persisting to disk.
+       fn notify(&self) {
+               let &(ref persist_mtx, ref cnd) = &self.persistence_lock;
+               let mut persistence_lock = persist_mtx.lock().unwrap();
+               *persistence_lock = true;
+               mem::drop(persistence_lock);
+               cnd.notify_all();
+       }
 }
 
 const SERIALIZATION_VERSION: u8 = 1;
@@ -3693,10 +3851,10 @@ impl Readable for HTLCForwardInfo {
        }
 }
 
-impl<ChanSigner: ChannelKeys + Writeable, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> Writeable for ChannelManager<ChanSigner, M, T, K, F, L>
-       where M::Target: chain::Watch<Keys=ChanSigner>,
+impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> Writeable for ChannelManager<Signer, M, T, K, F, L>
+       where M::Target: chain::Watch<Signer>,
         T::Target: BroadcasterInterface,
-        K::Target: KeysInterface<ChanKeySigner = ChanSigner>,
+        K::Target: KeysInterface<Signer = Signer>,
         F::Target: FeeEstimator,
         L::Target: Logger,
 {
@@ -3767,7 +3925,7 @@ impl<ChanSigner: ChannelKeys + Writeable, M: Deref, T: Deref, K: Deref, F: Deref
 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
 /// is:
 /// 1) Deserialize all stored ChannelMonitors.
-/// 2) Deserialize the ChannelManager by filling in this struct and calling <(Sha256dHash,
+/// 2) Deserialize the ChannelManager by filling in this struct and calling <(Option<BlockHash>,
 ///    ChannelManager)>::read(reader, args).
 ///    This may result in closing some Channels if the ChannelMonitor is newer than the stored
 ///    ChannelManager state to ensure no loss of funds. Thus, transactions may be broadcasted.
@@ -3776,15 +3934,16 @@ impl<ChanSigner: ChannelKeys + Writeable, M: Deref, T: Deref, K: Deref, F: Deref
 /// 4) Reconnect blocks on your ChannelMonitors.
 /// 5) Move the ChannelMonitors into your local chain::Watch.
 /// 6) Disconnect/connect blocks on the ChannelManager.
-pub struct ChannelManagerReadArgs<'a, ChanSigner: 'a + ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
-       where M::Target: chain::Watch<Keys=ChanSigner>,
+pub struct ChannelManagerReadArgs<'a, Signer: 'a + Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
+       where M::Target: chain::Watch<Signer>,
         T::Target: BroadcasterInterface,
-        K::Target: KeysInterface<ChanKeySigner = ChanSigner>,
+        K::Target: KeysInterface<Signer = Signer>,
         F::Target: FeeEstimator,
         L::Target: Logger,
 {
        /// The keys provider which will give us relevant keys. Some keys will be loaded during
-       /// deserialization.
+       /// deserialization and KeysInterface::read_chan_signer will be used to read per-Channel
+       /// signing data.
        pub keys_manager: K,
 
        /// The fee_estimator for use in the ChannelManager in the future.
@@ -3821,14 +3980,14 @@ pub struct ChannelManagerReadArgs<'a, ChanSigner: 'a + ChannelKeys, M: Deref, T:
        /// this struct.
        ///
        /// (C-not exported) because we have no HashMap bindings
-       pub channel_monitors: HashMap<OutPoint, &'a mut ChannelMonitor<ChanSigner>>,
+       pub channel_monitors: HashMap<OutPoint, &'a mut ChannelMonitor<Signer>>,
 }
 
-impl<'a, ChanSigner: 'a + ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
-               ChannelManagerReadArgs<'a, ChanSigner, M, T, K, F, L>
-       where M::Target: chain::Watch<Keys=ChanSigner>,
+impl<'a, Signer: 'a + Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
+               ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>
+       where M::Target: chain::Watch<Signer>,
                T::Target: BroadcasterInterface,
-               K::Target: KeysInterface<ChanKeySigner = ChanSigner>,
+               K::Target: KeysInterface<Signer = Signer>,
                F::Target: FeeEstimator,
                L::Target: Logger,
        {
@@ -3836,7 +3995,7 @@ impl<'a, ChanSigner: 'a + ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L
        /// HashMap for you. This is primarily useful for C bindings where it is not practical to
        /// populate a HashMap directly from C.
        pub fn new(keys_manager: K, fee_estimator: F, chain_monitor: M, tx_broadcaster: T, logger: L, default_config: UserConfig,
-                       mut channel_monitors: Vec<&'a mut ChannelMonitor<ChanSigner>>) -> Self {
+                       mut channel_monitors: Vec<&'a mut ChannelMonitor<Signer>>) -> Self {
                Self {
                        keys_manager, fee_estimator, chain_monitor, tx_broadcaster, logger, default_config,
                        channel_monitors: channel_monitors.drain(..).map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect()
@@ -3846,29 +4005,29 @@ impl<'a, ChanSigner: 'a + ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L
 
 // Implement ReadableArgs for an Arc'd ChannelManager to make it a bit easier to work with the
 // SipmleArcChannelManager type:
-impl<'a, ChanSigner: ChannelKeys + Readable, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
-       ReadableArgs<ChannelManagerReadArgs<'a, ChanSigner, M, T, K, F, L>> for (BlockHash, Arc<ChannelManager<ChanSigner, M, T, K, F, L>>)
-       where M::Target: chain::Watch<Keys=ChanSigner>,
+impl<'a, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
+       ReadableArgs<ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>> for (Option<BlockHash>, Arc<ChannelManager<Signer, M, T, K, F, L>>)
+       where M::Target: chain::Watch<Signer>,
         T::Target: BroadcasterInterface,
-        K::Target: KeysInterface<ChanKeySigner = ChanSigner>,
+        K::Target: KeysInterface<Signer = Signer>,
         F::Target: FeeEstimator,
         L::Target: Logger,
 {
-       fn read<R: ::std::io::Read>(reader: &mut R, args: ChannelManagerReadArgs<'a, ChanSigner, M, T, K, F, L>) -> Result<Self, DecodeError> {
-               let (blockhash, chan_manager) = <(BlockHash, ChannelManager<ChanSigner, M, T, K, F, L>)>::read(reader, args)?;
+       fn read<R: ::std::io::Read>(reader: &mut R, args: ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>) -> Result<Self, DecodeError> {
+               let (blockhash, chan_manager) = <(Option<BlockHash>, ChannelManager<Signer, M, T, K, F, L>)>::read(reader, args)?;
                Ok((blockhash, Arc::new(chan_manager)))
        }
 }
 
-impl<'a, ChanSigner: ChannelKeys + Readable, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
-       ReadableArgs<ChannelManagerReadArgs<'a, ChanSigner, M, T, K, F, L>> for (BlockHash, ChannelManager<ChanSigner, M, T, K, F, L>)
-       where M::Target: chain::Watch<Keys=ChanSigner>,
+impl<'a, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
+       ReadableArgs<ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>> for (Option<BlockHash>, ChannelManager<Signer, M, T, K, F, L>)
+       where M::Target: chain::Watch<Signer>,
         T::Target: BroadcasterInterface,
-        K::Target: KeysInterface<ChanKeySigner = ChanSigner>,
+        K::Target: KeysInterface<Signer = Signer>,
         F::Target: FeeEstimator,
         L::Target: Logger,
 {
-       fn read<R: ::std::io::Read>(reader: &mut R, mut args: ChannelManagerReadArgs<'a, ChanSigner, M, T, K, F, L>) -> Result<Self, DecodeError> {
+       fn read<R: ::std::io::Read>(reader: &mut R, mut args: ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>) -> Result<Self, DecodeError> {
                let _ver: u8 = Readable::read(reader)?;
                let min_ver: u8 = Readable::read(reader)?;
                if min_ver > SERIALIZATION_VERSION {
@@ -3886,7 +4045,7 @@ impl<'a, ChanSigner: ChannelKeys + Readable, M: Deref, T: Deref, K: Deref, F: De
                let mut by_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
                let mut short_to_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
                for _ in 0..channel_count {
-                       let mut channel: Channel<ChanSigner> = Readable::read(reader)?;
+                       let mut channel: Channel<Signer> = Channel::read(reader, &args.keys_manager)?;
                        if channel.last_block_connected != Default::default() && channel.last_block_connected != last_block_hash {
                                return Err(DecodeError::InvalidValue);
                        }
@@ -3971,6 +4130,9 @@ impl<'a, ChanSigner: ChannelKeys + Readable, M: Deref, T: Deref, K: Deref, F: De
 
                let last_node_announcement_serial: u32 = Readable::read(reader)?;
 
+               let mut secp_ctx = Secp256k1::new();
+               secp_ctx.seeded_randomize(&args.keys_manager.get_secure_random_bytes());
+
                let channel_manager = ChannelManager {
                        genesis_hash,
                        fee_estimator: args.fee_estimator,
@@ -3979,7 +4141,7 @@ impl<'a, ChanSigner: ChannelKeys + Readable, M: Deref, T: Deref, K: Deref, F: De
 
                        latest_block_height: AtomicUsize::new(latest_block_height as usize),
                        last_block_hash: Mutex::new(last_block_hash),
-                       secp_ctx: Secp256k1::new(),
+                       secp_ctx,
 
                        channel_state: Mutex::new(ChannelHolder {
                                by_id,
@@ -3996,6 +4158,8 @@ impl<'a, ChanSigner: ChannelKeys + Readable, M: Deref, T: Deref, K: Deref, F: De
 
                        pending_events: Mutex::new(pending_events_read),
                        total_consistency_lock: RwLock::new(()),
+                       persistence_notifier: PersistenceNotifier::new(),
+
                        keys_manager: args.keys_manager,
                        logger: args.logger,
                        default_configuration: args.default_config,
@@ -4008,6 +4172,62 @@ impl<'a, ChanSigner: ChannelKeys + Readable, M: Deref, T: Deref, K: Deref, F: De
                //TODO: Broadcast channel update for closed channels, but only after we've made a
                //connection or two.
 
-               Ok((last_block_hash.clone(), channel_manager))
+               let last_seen_block_hash = if last_block_hash == Default::default() {
+                       None
+               } else {
+                       Some(last_block_hash)
+               };
+               Ok((last_seen_block_hash, channel_manager))
+       }
+}
+
+#[cfg(test)]
+mod tests {
+       use ln::channelmanager::PersistenceNotifier;
+       use std::sync::Arc;
+       use std::sync::atomic::{AtomicBool, Ordering};
+       use std::thread;
+       use std::time::Duration;
+
+       #[test]
+       fn test_wait_timeout() {
+               let persistence_notifier = Arc::new(PersistenceNotifier::new());
+               let thread_notifier = Arc::clone(&persistence_notifier);
+
+               let exit_thread = Arc::new(AtomicBool::new(false));
+               let exit_thread_clone = exit_thread.clone();
+               thread::spawn(move || {
+                       loop {
+                               let &(ref persist_mtx, ref cnd) = &thread_notifier.persistence_lock;
+                               let mut persistence_lock = persist_mtx.lock().unwrap();
+                               *persistence_lock = true;
+                               cnd.notify_all();
+
+                               if exit_thread_clone.load(Ordering::SeqCst) {
+                                       break
+                               }
+                       }
+               });
+
+               // Check that we can block indefinitely until updates are available.
+               let _ = persistence_notifier.wait();
+
+               // Check that the PersistenceNotifier will return after the given duration if updates are
+               // available.
+               loop {
+                       if persistence_notifier.wait_timeout(Duration::from_millis(100)) {
+                               break
+                       }
+               }
+
+               exit_thread.store(true, Ordering::SeqCst);
+
+               // Check that the PersistenceNotifier will return after the given duration even if no updates
+               // are available.
+               loop {
+                       if !persistence_notifier.wait_timeout(Duration::from_millis(100)) {
+                               break
+                       }
+               }
        }
 }
index 3ce3d4fa7e604b9e0fb979dd8f4da0911adbdda2..35c9410bc0b2b70ce4f7b5bd342b74134e950040 100644 (file)
@@ -26,7 +26,6 @@
 //! [`Context`]: sealed/trait.Context.html
 
 use std::{cmp, fmt};
-use std::result::Result;
 use std::marker::PhantomData;
 
 use ln::msgs::DecodeError;
@@ -101,6 +100,8 @@ mod sealed {
                        StaticRemoteKey,
                        // Byte 2
                        ,
+                       // Byte 3
+                       ,
                ],
                optional_features: [
                        // Byte 0
@@ -109,6 +110,8 @@ mod sealed {
                        VariableLengthOnion | PaymentSecret,
                        // Byte 2
                        BasicMPP,
+                       // Byte 3
+                       ShutdownAnySegwit,
                ],
        });
        define_context!(NodeContext {
@@ -119,6 +122,8 @@ mod sealed {
                        StaticRemoteKey,
                        // Byte 2
                        ,
+                       // Byte 3
+                       ,
                ],
                optional_features: [
                        // Byte 0
@@ -127,6 +132,8 @@ mod sealed {
                        VariableLengthOnion | PaymentSecret,
                        // Byte 2
                        BasicMPP,
+                       // Byte 3
+                       ShutdownAnySegwit,
                ],
        });
        define_context!(ChannelContext {
@@ -253,6 +260,8 @@ mod sealed {
                "Feature flags for `payment_secret`.");
        define_feature!(17, BasicMPP, [InitContext, NodeContext],
                "Feature flags for `basic_mpp`.");
+       define_feature!(27, ShutdownAnySegwit, [InitContext, NodeContext],
+               "Feature flags for `opt_shutdown_anysegwit`.");
 
        #[cfg(test)]
        define_context!(TestingContext {
@@ -352,7 +361,7 @@ impl InitFeatures {
 
 impl<T: sealed::Context> Features<T> {
        /// Create a blank Features with no features set
-       pub fn empty() -> Features<T> {
+       pub fn empty() -> Self {
                Features {
                        flags: Vec::new(),
                        mark: PhantomData,
@@ -362,7 +371,7 @@ impl<T: sealed::Context> Features<T> {
        /// Creates features known by the implementation as defined by [`T::KNOWN_FEATURE_FLAGS`].
        ///
        /// [`T::KNOWN_FEATURE_FLAGS`]: sealed/trait.Context.html#associatedconstant.KNOWN_FEATURE_FLAGS
-       pub fn known() -> Features<T> {
+       pub fn known() -> Self {
                Self {
                        flags: T::KNOWN_FEATURE_FLAGS.to_vec(),
                        mark: PhantomData,
@@ -550,6 +559,17 @@ impl<T: sealed::BasicMPP> Features<T> {
        }
 }
 
+impl<T: sealed::ShutdownAnySegwit> Features<T> {
+       pub(crate) fn supports_shutdown_anysegwit(&self) -> bool {
+               <T as sealed::ShutdownAnySegwit>::supports_feature(&self.flags)
+       }
+       #[cfg(test)]
+       pub(crate) fn clear_shutdown_anysegwit(mut self) -> Self {
+               <T as sealed::ShutdownAnySegwit>::clear_bits(&mut self.flags);
+               self
+       }
+}
+
 impl<T: sealed::Context> Writeable for Features<T> {
        fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
                w.size_hint(self.flags.len() + 2);
@@ -620,6 +640,9 @@ mod tests {
                assert!(!InitFeatures::known().requires_basic_mpp());
                assert!(!NodeFeatures::known().requires_basic_mpp());
 
+               assert!(InitFeatures::known().supports_shutdown_anysegwit());
+               assert!(NodeFeatures::known().supports_shutdown_anysegwit());
+
                let mut init_features = InitFeatures::known();
                assert!(init_features.initial_routing_sync());
                init_features.clear_initial_routing_sync();
@@ -658,10 +681,12 @@ mod tests {
                        // - option_data_loss_protect
                        // - var_onion_optin | static_remote_key (req) | payment_secret
                        // - basic_mpp
-                       assert_eq!(node_features.flags.len(), 3);
+                       // - opt_shutdown_anysegwit
+                       assert_eq!(node_features.flags.len(), 4);
                        assert_eq!(node_features.flags[0], 0b00000010);
                        assert_eq!(node_features.flags[1], 0b10010010);
                        assert_eq!(node_features.flags[2], 0b00000010);
+                       assert_eq!(node_features.flags[3], 0b00001000);
                }
 
                // Check that cleared flags are kept blank when converting back:
index d54045f8e619d7d3075482d7e893279ca04f7686..d5d8566696740df15542d82c9271c709e51fbd3e 100644 (file)
@@ -19,7 +19,7 @@ use routing::network_graph::{NetGraphMsgHandler, NetworkGraph};
 use ln::features::InitFeatures;
 use ln::msgs;
 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler};
-use util::enforcing_trait_impls::EnforcingChannelKeys;
+use util::enforcing_trait_impls::EnforcingSigner;
 use util::test_utils;
 use util::test_utils::TestChainMonitor;
 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
@@ -96,6 +96,7 @@ pub struct TestChanMonCfg {
        pub chain_source: test_utils::TestChainSource,
        pub persister: test_utils::TestPersister,
        pub logger: test_utils::TestLogger,
+       pub keys_manager: test_utils::TestKeysInterface,
 }
 
 pub struct NodeCfg<'a> {
@@ -103,7 +104,7 @@ pub struct NodeCfg<'a> {
        pub tx_broadcaster: &'a test_utils::TestBroadcaster,
        pub fee_estimator: &'a test_utils::TestFeeEstimator,
        pub chain_monitor: test_utils::TestChainMonitor<'a>,
-       pub keys_manager: test_utils::TestKeysInterface,
+       pub keys_manager: &'a test_utils::TestKeysInterface,
        pub logger: &'a test_utils::TestLogger,
        pub node_seed: [u8; 32],
 }
@@ -113,7 +114,7 @@ pub struct Node<'a, 'b: 'a, 'c: 'b> {
        pub tx_broadcaster: &'c test_utils::TestBroadcaster,
        pub chain_monitor: &'b test_utils::TestChainMonitor<'c>,
        pub keys_manager: &'b test_utils::TestKeysInterface,
-       pub node: &'a ChannelManager<EnforcingChannelKeys, &'b TestChainMonitor<'c>, &'c test_utils::TestBroadcaster, &'b test_utils::TestKeysInterface, &'c test_utils::TestFeeEstimator, &'c test_utils::TestLogger>,
+       pub node: &'a ChannelManager<EnforcingSigner, &'b TestChainMonitor<'c>, &'c test_utils::TestBroadcaster, &'b test_utils::TestKeysInterface, &'c test_utils::TestFeeEstimator, &'c test_utils::TestLogger>,
        pub net_graph_msg_handler: NetGraphMsgHandler<&'c test_utils::TestChainSource, &'c test_utils::TestLogger>,
        pub node_seed: [u8; 32],
        pub network_payment_count: Rc<RefCell<u8>>,
@@ -167,12 +168,12 @@ impl<'a, 'b, 'c> Drop for Node<'a, 'b, 'c> {
                        let feeest = test_utils::TestFeeEstimator { sat_per_kw: 253 };
                        let mut deserialized_monitors = Vec::new();
                        {
-                               let old_monitors = self.chain_monitor.chain_monitor.monitors.lock().unwrap();
+                               let old_monitors = self.chain_monitor.chain_monitor.monitors.read().unwrap();
                                for (_, old_monitor) in old_monitors.iter() {
                                        let mut w = test_utils::TestVecWriter(Vec::new());
-                                       old_monitor.serialize_for_disk(&mut w).unwrap();
-                                       let (_, deserialized_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(
-                                               &mut ::std::io::Cursor::new(&w.0)).unwrap();
+                                       old_monitor.write(&mut w).unwrap();
+                                       let (_, deserialized_monitor) = <(Option<BlockHash>, ChannelMonitor<EnforcingSigner>)>::read(
+                                               &mut ::std::io::Cursor::new(&w.0), self.keys_manager).unwrap();
                                        deserialized_monitors.push(deserialized_monitor);
                                }
                        }
@@ -187,7 +188,7 @@ impl<'a, 'b, 'c> Drop for Node<'a, 'b, 'c> {
 
                                let mut w = test_utils::TestVecWriter(Vec::new());
                                self.node.write(&mut w).unwrap();
-                               <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut ::std::io::Cursor::new(w.0), ChannelManagerReadArgs {
+                               <(Option<BlockHash>, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut ::std::io::Cursor::new(w.0), ChannelManagerReadArgs {
                                        default_config: UserConfig::default(),
                                        keys_manager: self.keys_manager,
                                        fee_estimator: &test_utils::TestFeeEstimator { sat_per_kw: 253 },
@@ -205,7 +206,7 @@ impl<'a, 'b, 'c> Drop for Node<'a, 'b, 'c> {
                                txn_broadcasted: Mutex::new(self.tx_broadcaster.txn_broadcasted.lock().unwrap().clone())
                        };
                        let chain_source = test_utils::TestChainSource::new(Network::Testnet);
-                       let chain_monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &broadcaster, &self.logger, &feeest, &persister);
+                       let chain_monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &broadcaster, &self.logger, &feeest, &persister, &self.keys_manager);
                        for deserialized_monitor in deserialized_monitors.drain(..) {
                                if let Err(_) = chain_monitor.watch_channel(deserialized_monitor.get_funding_txo().0, deserialized_monitor) {
                                        panic!();
@@ -304,9 +305,9 @@ macro_rules! get_feerate {
 macro_rules! get_local_commitment_txn {
        ($node: expr, $channel_id: expr) => {
                {
-                       let mut monitors = $node.chain_monitor.chain_monitor.monitors.lock().unwrap();
+                       let monitors = $node.chain_monitor.chain_monitor.monitors.read().unwrap();
                        let mut commitment_txn = None;
-                       for (funding_txo, monitor) in monitors.iter_mut() {
+                       for (funding_txo, monitor) in monitors.iter() {
                                if funding_txo.to_channel_id() == $channel_id {
                                        commitment_txn = Some(monitor.unsafe_get_latest_holder_commitment_txn(&$node.logger));
                                        break;
@@ -603,7 +604,7 @@ pub fn close_channel<'a, 'b, 'c>(outbound_node: &Node<'a, 'b, 'c>, inbound_node:
        let (tx_a, tx_b);
 
        node_a.close_channel(channel_id).unwrap();
-       node_b.handle_shutdown(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id()));
+       node_b.handle_shutdown(&node_a.get_our_node_id(), &InitFeatures::known(), &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id()));
 
        let events_1 = node_b.get_and_clear_pending_msg_events();
        assert!(events_1.len() >= 1);
@@ -628,7 +629,7 @@ pub fn close_channel<'a, 'b, 'c>(outbound_node: &Node<'a, 'b, 'c>, inbound_node:
                })
        };
 
-       node_a.handle_shutdown(&node_b.get_our_node_id(), &shutdown_b);
+       node_a.handle_shutdown(&node_b.get_our_node_id(), &InitFeatures::known(), &shutdown_b);
        let (as_update, bs_update) = if close_inbound_first {
                assert!(node_a.get_and_clear_pending_msg_events().is_empty());
                node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap());
@@ -1132,7 +1133,10 @@ pub fn create_chanmon_cfgs(node_count: usize) -> Vec<TestChanMonCfg> {
                let chain_source = test_utils::TestChainSource::new(Network::Testnet);
                let logger = test_utils::TestLogger::with_id(format!("node {}", i));
                let persister = test_utils::TestPersister::new();
-               chan_mon_cfgs.push(TestChanMonCfg{ tx_broadcaster, fee_estimator, chain_source, logger, persister });
+               let seed = [i as u8; 32];
+               let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
+
+               chan_mon_cfgs.push(TestChanMonCfg{ tx_broadcaster, fee_estimator, chain_source, logger, persister, keys_manager });
        }
 
        chan_mon_cfgs
@@ -1142,30 +1146,29 @@ pub fn create_node_cfgs<'a>(node_count: usize, chanmon_cfgs: &'a Vec<TestChanMon
        let mut nodes = Vec::new();
 
        for i in 0..node_count {
+               let chain_monitor = test_utils::TestChainMonitor::new(Some(&chanmon_cfgs[i].chain_source), &chanmon_cfgs[i].tx_broadcaster, &chanmon_cfgs[i].logger, &chanmon_cfgs[i].fee_estimator, &chanmon_cfgs[i].persister, &chanmon_cfgs[i].keys_manager);
                let seed = [i as u8; 32];
-               let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
-               let chain_monitor = test_utils::TestChainMonitor::new(Some(&chanmon_cfgs[i].chain_source), &chanmon_cfgs[i].tx_broadcaster, &chanmon_cfgs[i].logger, &chanmon_cfgs[i].fee_estimator, &chanmon_cfgs[i].persister);
-               nodes.push(NodeCfg { chain_source: &chanmon_cfgs[i].chain_source, logger: &chanmon_cfgs[i].logger, tx_broadcaster: &chanmon_cfgs[i].tx_broadcaster, fee_estimator: &chanmon_cfgs[i].fee_estimator, chain_monitor, keys_manager, node_seed: seed });
+               nodes.push(NodeCfg { chain_source: &chanmon_cfgs[i].chain_source, logger: &chanmon_cfgs[i].logger, tx_broadcaster: &chanmon_cfgs[i].tx_broadcaster, fee_estimator: &chanmon_cfgs[i].fee_estimator, chain_monitor, keys_manager: &chanmon_cfgs[i].keys_manager, node_seed: seed });
        }
 
        nodes
 }
 
-pub fn create_node_chanmgrs<'a, 'b>(node_count: usize, cfgs: &'a Vec<NodeCfg<'b>>, node_config: &[Option<UserConfig>]) -> Vec<ChannelManager<EnforcingChannelKeys, &'a TestChainMonitor<'b>, &'b test_utils::TestBroadcaster, &'a test_utils::TestKeysInterface, &'b test_utils::TestFeeEstimator, &'b test_utils::TestLogger>> {
+pub fn create_node_chanmgrs<'a, 'b>(node_count: usize, cfgs: &'a Vec<NodeCfg<'b>>, node_config: &[Option<UserConfig>]) -> Vec<ChannelManager<EnforcingSigner, &'a TestChainMonitor<'b>, &'b test_utils::TestBroadcaster, &'a test_utils::TestKeysInterface, &'b test_utils::TestFeeEstimator, &'b test_utils::TestLogger>> {
        let mut chanmgrs = Vec::new();
        for i in 0..node_count {
                let mut default_config = UserConfig::default();
                default_config.channel_options.announced_channel = true;
                default_config.peer_channel_config_limits.force_announced_channel_preference = false;
                default_config.own_channel_config.our_htlc_minimum_msat = 1000; // sanitization being done by the sender, to exerce receiver logic we need to lift of limit
-               let node = ChannelManager::new(Network::Testnet, cfgs[i].fee_estimator, &cfgs[i].chain_monitor, cfgs[i].tx_broadcaster, cfgs[i].logger, &cfgs[i].keys_manager, if node_config[i].is_some() { node_config[i].clone().unwrap() } else { default_config }, 0);
+               let node = ChannelManager::new(Network::Testnet, cfgs[i].fee_estimator, &cfgs[i].chain_monitor, cfgs[i].tx_broadcaster, cfgs[i].logger, cfgs[i].keys_manager, if node_config[i].is_some() { node_config[i].clone().unwrap() } else { default_config }, 0);
                chanmgrs.push(node);
        }
 
        chanmgrs
 }
 
-pub fn create_network<'a, 'b: 'a, 'c: 'b>(node_count: usize, cfgs: &'b Vec<NodeCfg<'c>>, chan_mgrs: &'a Vec<ChannelManager<EnforcingChannelKeys, &'b TestChainMonitor<'c>, &'c test_utils::TestBroadcaster, &'b test_utils::TestKeysInterface, &'c test_utils::TestFeeEstimator, &'c test_utils::TestLogger>>) -> Vec<Node<'a, 'b, 'c>> {
+pub fn create_network<'a, 'b: 'a, 'c: 'b>(node_count: usize, cfgs: &'b Vec<NodeCfg<'c>>, chan_mgrs: &'a Vec<ChannelManager<EnforcingSigner, &'b TestChainMonitor<'c>, &'c test_utils::TestBroadcaster, &'b test_utils::TestKeysInterface, &'c test_utils::TestFeeEstimator, &'c test_utils::TestLogger>>) -> Vec<Node<'a, 'b, 'c>> {
        let mut nodes = Vec::new();
        let chan_count = Rc::new(RefCell::new(0));
        let payment_count = Rc::new(RefCell::new(0));
index eef89d1b413cd36704d7ec6a6957f586c00e729e..4a2f5d3778ce339739df0a99aa1c4625fae5faae 100644 (file)
@@ -15,7 +15,7 @@ use chain::Watch;
 use chain::channelmonitor;
 use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
 use chain::transaction::OutPoint;
-use chain::keysinterface::{ChannelKeys, KeysInterface, SpendableOutputDescriptor};
+use chain::keysinterface::{Sign, KeysInterface};
 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentPreimage, PaymentHash, PaymentSecret, PaymentSendFailure, BREAKDOWN_TIMEOUT};
 use ln::channel::{Channel, ChannelError};
@@ -24,22 +24,17 @@ use routing::router::{Route, RouteHop, get_route};
 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
 use ln::msgs;
 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate, ErrorAction};
-use util::enforcing_trait_impls::EnforcingChannelKeys;
+use util::enforcing_trait_impls::EnforcingSigner;
 use util::{byte_utils, test_utils};
 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
 use util::errors::APIError;
-use util::ser::{Writeable, ReadableArgs, Readable};
+use util::ser::{Writeable, ReadableArgs};
 use util::config::UserConfig;
 
 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
-use bitcoin::hashes::HashEngine;
-use bitcoin::hash_types::{Txid, BlockHash, WPubkeyHash};
-use bitcoin::util::bip143;
-use bitcoin::util::address::Address;
-use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
+use bitcoin::hash_types::{Txid, BlockHash};
 use bitcoin::blockdata::block::{Block, BlockHeader};
-use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType, OutPoint as BitcoinOutPoint};
-use bitcoin::blockdata::script::{Builder, Script};
+use bitcoin::blockdata::script::Builder;
 use bitcoin::blockdata::opcodes;
 use bitcoin::blockdata::constants::genesis_block;
 use bitcoin::network::constants::Network;
@@ -54,12 +49,13 @@ use regex;
 
 use std::collections::{BTreeSet, HashMap, HashSet};
 use std::default::Default;
-use std::sync::{Arc, Mutex};
+use std::sync::Mutex;
 use std::sync::atomic::Ordering;
 use std::mem;
 
 use ln::functional_test_utils::*;
-use ln::chan_utils::PreCalculatedTxCreationKeys;
+use ln::chan_utils::CommitmentTransaction;
+use ln::msgs::OptionalField::Present;
 
 #[test]
 fn test_insane_channel_opens() {
@@ -72,7 +68,7 @@ fn test_insane_channel_opens() {
        // Instantiate channel parameters where we push the maximum msats given our
        // funding satoshis
        let channel_value_sat = 31337; // same as funding satoshis
-       let channel_reserve_satoshis = Channel::<EnforcingChannelKeys>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
+       let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
        let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
 
        // Have node0 initiate a channel to node1 with aforementioned parameters
@@ -837,9 +833,9 @@ fn pre_funding_lock_shutdown_test() {
 
        nodes[0].node.close_channel(&OutPoint { txid: tx.txid(), index: 0 }.to_channel_id()).unwrap();
        let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
-       nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
+       nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
        let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
-       nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
+       nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
 
        let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
        nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
@@ -867,9 +863,9 @@ fn updates_shutdown_wait() {
 
        nodes[0].node.close_channel(&chan_1.2).unwrap();
        let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
-       nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
+       nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
        let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
-       nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
+       nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
 
        assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
        assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
@@ -954,13 +950,13 @@ fn htlc_fail_async_shutdown() {
 
        nodes[1].node.close_channel(&chan_1.2).unwrap();
        let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
-       nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
+       nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
        let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
 
        nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
        nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
        check_added_monitors!(nodes[1], 1);
-       nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
+       nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
        commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
 
        let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
@@ -1022,10 +1018,10 @@ fn do_test_shutdown_rebroadcast(recv_count: u8) {
        nodes[1].node.close_channel(&chan_1.2).unwrap();
        let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
        if recv_count > 0 {
-               nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
+               nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
                let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
                if recv_count > 1 {
-                       nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
+                       nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
                }
        }
 
@@ -1044,14 +1040,14 @@ fn do_test_shutdown_rebroadcast(recv_count: u8) {
        nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish);
        let node_0_2nd_shutdown = if recv_count > 0 {
                let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
-               nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
+               nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_2nd_shutdown);
                node_0_2nd_shutdown
        } else {
                assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
-               nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
+               nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_2nd_shutdown);
                get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
        };
-       nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown);
+       nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_2nd_shutdown);
 
        assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
        assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
@@ -1111,10 +1107,10 @@ fn do_test_shutdown_rebroadcast(recv_count: u8) {
                let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
                assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
 
-               nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown);
+               nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_3rd_shutdown);
                assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
 
-               nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown);
+               nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_3rd_shutdown);
                let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
                assert!(node_0_closing_signed == node_0_2nd_closing_signed);
 
@@ -1584,7 +1580,7 @@ fn test_fee_spike_violation_fails_htlc() {
                        let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
                        (route, payment_hash, payment_preimage)
                }}
-       };
+       }
 
        let (route, payment_hash, _) = get_route_and_payment_hash!(3460001);
        // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
@@ -1615,98 +1611,58 @@ fn test_fee_spike_violation_fails_htlc() {
 
        const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
 
-       // Get the EnforcingChannelKeys for each channel, which will be used to (1) get the keys
+       // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
        // needed to sign the new commitment tx and (2) sign the new commitment tx.
-       let (local_revocation_basepoint, local_htlc_basepoint, local_payment_point, local_secret, local_secret2) = {
+       let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point) = {
                let chan_lock = nodes[0].node.channel_state.lock().unwrap();
                let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
-               let chan_keys = local_chan.get_keys();
-               let pubkeys = chan_keys.pubkeys();
-               (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint, pubkeys.payment_point,
-                chan_keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER), chan_keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2))
+               let chan_signer = local_chan.get_signer();
+               let pubkeys = chan_signer.pubkeys();
+               (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
+                chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
+                chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx))
        };
-       let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_payment_point, remote_secret1) = {
+       let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point) = {
                let chan_lock = nodes[1].node.channel_state.lock().unwrap();
                let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
-               let chan_keys = remote_chan.get_keys();
-               let pubkeys = chan_keys.pubkeys();
-               (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint, pubkeys.payment_point,
-                chan_keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1))
+               let chan_signer = remote_chan.get_signer();
+               let pubkeys = chan_signer.pubkeys();
+               (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
+                chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx))
        };
 
        // Assemble the set of keys we can use for signatures for our commitment_signed message.
-       let commitment_secret = SecretKey::from_slice(&remote_secret1).unwrap();
-       let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &commitment_secret);
-       let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &per_commitment_point, &remote_delayed_payment_basepoint,
+       let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
                &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
 
        // Build the remote commitment transaction so we can sign it, and then later use the
        // signature for the commitment_signed message.
        let local_chan_balance = 1313;
-       let static_payment_pk = local_payment_point.serialize();
-       let remote_commit_tx_output = TxOut {
-                               script_pubkey: Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
-                                                            .push_slice(&WPubkeyHash::hash(&static_payment_pk)[..])
-                                                            .into_script(),
-               value: local_chan_balance as u64
-       };
-
-       let local_commit_tx_output = TxOut {
-               script_pubkey: chan_utils::get_revokeable_redeemscript(&commit_tx_keys.revocation_key,
-                                                                              BREAKDOWN_TIMEOUT,
-                                                                              &commit_tx_keys.broadcaster_delayed_payment_key).to_v0_p2wsh(),
-                               value: 95000,
-       };
 
        let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
                offered: false,
                amount_msat: 3460001,
                cltv_expiry: htlc_cltv,
-               payment_hash: payment_hash,
+               payment_hash,
                transaction_output_index: Some(1),
        };
 
-       let htlc_output = TxOut {
-               script_pubkey: chan_utils::get_htlc_redeemscript(&accepted_htlc_info, &commit_tx_keys).to_v0_p2wsh(),
-               value: 3460001 / 1000
-       };
-
-       let commit_tx_obscure_factor = {
-               let mut sha = Sha256::engine();
-               let remote_payment_point = &remote_payment_point.serialize();
-               sha.input(&local_payment_point.serialize());
-               sha.input(remote_payment_point);
-               let res = Sha256::from_engine(sha).into_inner();
-
-               ((res[26] as u64) << 5*8) |
-               ((res[27] as u64) << 4*8) |
-               ((res[28] as u64) << 3*8) |
-               ((res[29] as u64) << 2*8) |
-               ((res[30] as u64) << 1*8) |
-               ((res[31] as u64) << 0*8)
-       };
-       let commitment_number = 1;
-       let obscured_commitment_transaction_number = commit_tx_obscure_factor ^ commitment_number;
-       let lock_time = ((0x20 as u32) << 8*3) | ((obscured_commitment_transaction_number & 0xffffffu64) as u32);
-       let input = TxIn {
-               previous_output: BitcoinOutPoint { txid: chan.3.txid(), vout: 0 },
-               script_sig: Script::new(),
-               sequence: ((0x80 as u32) << 8*3) | ((obscured_commitment_transaction_number >> 3*8) as u32),
-               witness: Vec::new(),
-       };
+       let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
 
-       let commit_tx = Transaction {
-               version: 2,
-               lock_time,
-               input: vec![input],
-               output: vec![remote_commit_tx_output, htlc_output, local_commit_tx_output],
-       };
        let res = {
                let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
                let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
-               let local_chan_keys = local_chan.get_keys();
-               let pre_commit_tx_keys = PreCalculatedTxCreationKeys::new(commit_tx_keys);
-               local_chan_keys.sign_counterparty_commitment(feerate_per_kw, &commit_tx, &pre_commit_tx_keys, &[&accepted_htlc_info], &secp_ctx).unwrap()
+               let local_chan_signer = local_chan.get_signer();
+               let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
+                       commitment_number,
+                       95000,
+                       local_chan_balance,
+                       commit_tx_keys.clone(),
+                       feerate_per_kw,
+                       &mut vec![(accepted_htlc_info, ())],
+                       &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
+               );
+               local_chan_signer.sign_counterparty_commitment(&commitment_tx, &secp_ctx).unwrap()
        };
 
        let commit_signed_msg = msgs::CommitmentSigned {
@@ -1720,10 +1676,11 @@ fn test_fee_spike_violation_fails_htlc() {
        let _ = nodes[1].node.get_and_clear_pending_msg_events();
 
        // Send the RAA to nodes[1].
-       let per_commitment_secret = local_secret;
-       let next_secret = SecretKey::from_slice(&local_secret2).unwrap();
-       let next_per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &next_secret);
-       let raa_msg = msgs::RevokeAndACK{ channel_id: chan.2, per_commitment_secret, next_per_commitment_point};
+       let raa_msg = msgs::RevokeAndACK {
+               channel_id: chan.2,
+               per_commitment_secret: local_secret,
+               next_per_commitment_point: next_local_point
+       };
        nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
 
        let events = nodes[1].node.get_and_clear_pending_msg_events();
@@ -1745,8 +1702,9 @@ fn test_fee_spike_violation_fails_htlc() {
 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
        let mut chanmon_cfgs = create_chanmon_cfgs(2);
        // Set the fee rate for the channel very high, to the point where the fundee
-       // sending any amount would result in a channel reserve violation. In this test
-       // we check that we would be prevented from sending an HTLC in this situation.
+       // sending any above-dust amount would result in a channel reserve violation.
+       // In this test we check that we would be prevented from sending an HTLC in
+       // this situation.
        chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
        chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
        let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
@@ -1762,9 +1720,9 @@ fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
                        let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.first().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
                        (route, payment_hash, payment_preimage)
                }}
-       };
+       }
 
-       let (route, our_payment_hash, _) = get_route_and_payment_hash!(1000);
+       let (route, our_payment_hash, _) = get_route_and_payment_hash!(4843000);
        unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
                assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
        assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
@@ -1794,7 +1752,7 @@ fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
                        let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.first().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
                        (route, payment_hash, payment_preimage)
                }}
-       };
+       }
 
        let (route, payment_hash, _) = get_route_and_payment_hash!(1000);
        // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
@@ -1822,6 +1780,57 @@ fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
        check_added_monitors!(nodes[0], 1);
 }
 
+#[test]
+fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
+       // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
+       // calculating our commitment transaction fee (this was previously broken).
+       let chanmon_cfgs = create_chanmon_cfgs(2);
+       let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
+       let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
+       let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
+
+       // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
+       // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
+       // transaction fee with 0 HTLCs (183 sats)).
+       create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98817000, InitFeatures::known(), InitFeatures::known());
+
+       let dust_amt = 546000; // Dust amount
+       // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
+       // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
+       // commitment transaction fee.
+       let (_, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
+}
+
+#[test]
+fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
+       // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
+       // calculating our counterparty's commitment transaction fee (this was previously broken).
+       let chanmon_cfgs = create_chanmon_cfgs(2);
+       let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
+       let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
+       let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
+       create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
+
+       let payment_amt = 46000; // Dust amount
+       // In the previous code, these first four payments would succeed.
+       let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
+       let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
+       let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
+       let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
+
+       // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
+       let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
+       let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
+       let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
+       let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
+       let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
+
+       // And this last payment previously resulted in nodes[1] closing on its inbound-channel
+       // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
+       // transaction fee and therefore perceived this next payment as a channel reserve violation.
+       let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
+}
+
 #[test]
 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
        let chanmon_cfgs = create_chanmon_cfgs(3);
@@ -1839,7 +1848,7 @@ fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
                        let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
                        (route, payment_hash, payment_preimage)
                }}
-       };
+       }
 
        let feemsat = 239;
        let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
@@ -1940,7 +1949,7 @@ fn test_channel_reserve_holding_cell_htlcs() {
                        let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
                        (route, payment_hash, payment_preimage)
                }}
-       };
+       }
 
        macro_rules! expect_forward {
                ($node: expr) => {{
@@ -2134,23 +2143,6 @@ fn test_channel_reserve_holding_cell_htlcs() {
 
        let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
        let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
-       {
-               let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_3 + 1);
-               let err = nodes[0].node.send_payment(&route, our_payment_hash, &None).err().unwrap();
-               match err {
-                       PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
-                               match &fails[0] {
-                                       &APIError::ChannelUnavailable{ref err} =>
-                                               assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
-                                       _ => panic!("Unexpected error variant"),
-                               }
-                       },
-                       _ => panic!("Unexpected error variant"),
-               }
-               assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
-               nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put our balance under counterparty-announced channel reserve value".to_string(), 3);
-       }
-
        send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3, recv_value_3);
 
        let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
@@ -2511,7 +2503,9 @@ fn test_justice_tx() {
        bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
        bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
        let user_cfgs = [Some(alice_config), Some(bob_config)];
-       let chanmon_cfgs = create_chanmon_cfgs(2);
+       let mut chanmon_cfgs = create_chanmon_cfgs(2);
+       chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
+       chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
        let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
        let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
        let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
@@ -2641,7 +2635,8 @@ fn revoked_output_claim() {
 #[test]
 fn claim_htlc_outputs_shared_tx() {
        // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
-       let chanmon_cfgs = create_chanmon_cfgs(2);
+       let mut chanmon_cfgs = create_chanmon_cfgs(2);
+       chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
        let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
        let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
        let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
@@ -2711,7 +2706,8 @@ fn claim_htlc_outputs_shared_tx() {
 #[test]
 fn claim_htlc_outputs_single_tx() {
        // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
-       let chanmon_cfgs = create_chanmon_cfgs(2);
+       let mut chanmon_cfgs = create_chanmon_cfgs(2);
+       chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
        let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
        let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
        let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
@@ -3437,7 +3433,7 @@ fn test_htlc_ignore_latest_remote_commitment() {
        create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
 
        route_payment(&nodes[0], &[&nodes[1]], 10000000);
-       nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
+       nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
        check_closed_broadcast!(nodes[0], false);
        check_added_monitors!(nodes[0], 1);
 
@@ -3498,7 +3494,7 @@ fn test_force_close_fail_back() {
        // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
        // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
 
-       nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
+       nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
        check_closed_broadcast!(nodes[2], false);
        check_added_monitors!(nodes[2], 1);
        let tx = {
@@ -3522,8 +3518,8 @@ fn test_force_close_fail_back() {
 
        // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
        {
-               let mut monitors = nodes[2].chain_monitor.chain_monitor.monitors.lock().unwrap();
-               monitors.get_mut(&OutPoint{ txid: Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), index: 0 }).unwrap()
+               let mut monitors = nodes[2].chain_monitor.chain_monitor.monitors.read().unwrap();
+               monitors.get(&OutPoint{ txid: Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), index: 0 }).unwrap()
                        .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &&logger);
        }
        connect_block(&nodes[2], &block, 1);
@@ -4242,8 +4238,8 @@ fn test_invalid_channel_announcement() {
 
        nodes[0].net_graph_msg_handler.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
 
-       let as_bitcoin_key = as_chan.get_keys().inner.holder_channel_pubkeys.funding_pubkey;
-       let bs_bitcoin_key = bs_chan.get_keys().inner.holder_channel_pubkeys.funding_pubkey;
+       let as_bitcoin_key = as_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
+       let bs_bitcoin_key = bs_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
 
        let as_network_key = nodes[0].node.get_our_node_id();
        let bs_network_key = nodes[1].node.get_our_node_id();
@@ -4270,8 +4266,8 @@ fn test_invalid_channel_announcement() {
        macro_rules! sign_msg {
                ($unsigned_msg: expr) => {
                        let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
-                       let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_keys().inner.funding_key);
-                       let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_keys().inner.funding_key);
+                       let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_signer().inner.funding_key);
+                       let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_signer().inner.funding_key);
                        let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
                        let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
                        chan_announcement = msgs::ChannelAnnouncement {
@@ -4310,8 +4306,7 @@ fn test_no_txn_manager_serialize_deserialize() {
        let fee_estimator: test_utils::TestFeeEstimator;
        let persister: test_utils::TestPersister;
        let new_chain_monitor: test_utils::TestChainMonitor;
-       let keys_manager: test_utils::TestKeysInterface;
-       let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
+       let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
        let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
 
        let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
@@ -4320,26 +4315,27 @@ fn test_no_txn_manager_serialize_deserialize() {
 
        let nodes_0_serialized = nodes[0].node.encode();
        let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
-       nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.serialize_for_disk(&mut chan_0_monitor_serialized).unwrap();
+       nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
 
        logger = test_utils::TestLogger::new();
        fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
        persister = test_utils::TestPersister::new();
-       new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister);
+       let keys_manager = &chanmon_cfgs[0].keys_manager;
+       new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
        nodes[0].chain_monitor = &new_chain_monitor;
        let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
-       let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
+       let (_, mut chan_0_monitor) = <(Option<BlockHash>, ChannelMonitor<EnforcingSigner>)>::read(
+               &mut chan_0_monitor_read, keys_manager).unwrap();
        assert!(chan_0_monitor_read.is_empty());
 
        let mut nodes_0_read = &nodes_0_serialized[..];
        let config = UserConfig::default();
-       keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
        let (_, nodes_0_deserialized_tmp) = {
                let mut channel_monitors = HashMap::new();
                channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
-               <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
+               <(Option<BlockHash>, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
                        default_config: config,
-                       keys_manager: &keys_manager,
+                       keys_manager,
                        fee_estimator: &fee_estimator,
                        chain_monitor: nodes[0].chain_monitor,
                        tx_broadcaster: nodes[0].tx_broadcaster.clone(),
@@ -4386,8 +4382,7 @@ fn test_manager_serialize_deserialize_events() {
        let persister: test_utils::TestPersister;
        let logger: test_utils::TestLogger;
        let new_chain_monitor: test_utils::TestChainMonitor;
-       let keys_manager: test_utils::TestKeysInterface;
-       let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
+       let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
        let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
 
        // Start creating a channel, but stop right before broadcasting the event message FundingBroadcastSafe
@@ -4395,8 +4390,8 @@ fn test_manager_serialize_deserialize_events() {
        let push_msat = 10001;
        let a_flags = InitFeatures::known();
        let b_flags = InitFeatures::known();
-       let node_a = nodes.pop().unwrap();
-       let node_b = nodes.pop().unwrap();
+       let node_a = nodes.remove(0);
+       let node_b = nodes.remove(0);
        node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
        node_b.node.handle_open_channel(&node_a.node.get_our_node_id(), a_flags, &get_event_msg!(node_a, MessageSendEvent::SendOpenChannel, node_b.node.get_our_node_id()));
        node_a.node.handle_accept_channel(&node_b.node.get_our_node_id(), b_flags, &get_event_msg!(node_b, MessageSendEvent::SendAcceptChannel, node_a.node.get_our_node_id()));
@@ -4429,26 +4424,27 @@ fn test_manager_serialize_deserialize_events() {
        // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
        let nodes_0_serialized = nodes[0].node.encode();
        let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
-       nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.serialize_for_disk(&mut chan_0_monitor_serialized).unwrap();
+       nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
 
        fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
        logger = test_utils::TestLogger::new();
        persister = test_utils::TestPersister::new();
-       new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister);
+       let keys_manager = &chanmon_cfgs[0].keys_manager;
+       new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
        nodes[0].chain_monitor = &new_chain_monitor;
        let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
-       let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
+       let (_, mut chan_0_monitor) = <(Option<BlockHash>, ChannelMonitor<EnforcingSigner>)>::read(
+               &mut chan_0_monitor_read, keys_manager).unwrap();
        assert!(chan_0_monitor_read.is_empty());
 
        let mut nodes_0_read = &nodes_0_serialized[..];
        let config = UserConfig::default();
-       keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
        let (_, nodes_0_deserialized_tmp) = {
                let mut channel_monitors = HashMap::new();
                channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
-               <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
+               <(Option<BlockHash>, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
                        default_config: config,
-                       keys_manager: &keys_manager,
+                       keys_manager,
                        fee_estimator: &fee_estimator,
                        chain_monitor: nodes[0].chain_monitor,
                        tx_broadcaster: nodes[0].tx_broadcaster.clone(),
@@ -4509,8 +4505,7 @@ fn test_simple_manager_serialize_deserialize() {
        let fee_estimator: test_utils::TestFeeEstimator;
        let persister: test_utils::TestPersister;
        let new_chain_monitor: test_utils::TestChainMonitor;
-       let keys_manager: test_utils::TestKeysInterface;
-       let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
+       let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
        let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
        create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
 
@@ -4521,25 +4516,26 @@ fn test_simple_manager_serialize_deserialize() {
 
        let nodes_0_serialized = nodes[0].node.encode();
        let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
-       nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.serialize_for_disk(&mut chan_0_monitor_serialized).unwrap();
+       nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
 
        logger = test_utils::TestLogger::new();
        fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
        persister = test_utils::TestPersister::new();
-       new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister);
+       let keys_manager = &chanmon_cfgs[0].keys_manager;
+       new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
        nodes[0].chain_monitor = &new_chain_monitor;
        let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
-       let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
+       let (_, mut chan_0_monitor) = <(Option<BlockHash>, ChannelMonitor<EnforcingSigner>)>::read(
+               &mut chan_0_monitor_read, keys_manager).unwrap();
        assert!(chan_0_monitor_read.is_empty());
 
        let mut nodes_0_read = &nodes_0_serialized[..];
-       keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
        let (_, nodes_0_deserialized_tmp) = {
                let mut channel_monitors = HashMap::new();
                channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
-               <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
+               <(Option<BlockHash>, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
                        default_config: UserConfig::default(),
-                       keys_manager: &keys_manager,
+                       keys_manager,
                        fee_estimator: &fee_estimator,
                        chain_monitor: nodes[0].chain_monitor,
                        tx_broadcaster: nodes[0].tx_broadcaster.clone(),
@@ -4570,17 +4566,16 @@ fn test_manager_serialize_deserialize_inconsistent_monitor() {
        let fee_estimator: test_utils::TestFeeEstimator;
        let persister: test_utils::TestPersister;
        let new_chain_monitor: test_utils::TestChainMonitor;
-       let keys_manager: test_utils::TestKeysInterface;
-       let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
+       let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
        let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
        create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
        create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
        let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
 
        let mut node_0_stale_monitors_serialized = Vec::new();
-       for monitor in nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter() {
+       for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
                let mut writer = test_utils::TestVecWriter(Vec::new());
-               monitor.1.serialize_for_disk(&mut writer).unwrap();
+               monitor.1.write(&mut writer).unwrap();
                node_0_stale_monitors_serialized.push(writer.0);
        }
 
@@ -4597,22 +4592,24 @@ fn test_manager_serialize_deserialize_inconsistent_monitor() {
        // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
        // nodes[3])
        let mut node_0_monitors_serialized = Vec::new();
-       for monitor in nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter() {
+       for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
                let mut writer = test_utils::TestVecWriter(Vec::new());
-               monitor.1.serialize_for_disk(&mut writer).unwrap();
+               monitor.1.write(&mut writer).unwrap();
                node_0_monitors_serialized.push(writer.0);
        }
 
        logger = test_utils::TestLogger::new();
        fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
        persister = test_utils::TestPersister::new();
-       new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister);
+       let keys_manager = &chanmon_cfgs[0].keys_manager;
+       new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
        nodes[0].chain_monitor = &new_chain_monitor;
 
+
        let mut node_0_stale_monitors = Vec::new();
        for serialized in node_0_stale_monitors_serialized.iter() {
                let mut read = &serialized[..];
-               let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read).unwrap();
+               let (_, monitor) = <(Option<BlockHash>, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
                assert!(read.is_empty());
                node_0_stale_monitors.push(monitor);
        }
@@ -4620,18 +4617,16 @@ fn test_manager_serialize_deserialize_inconsistent_monitor() {
        let mut node_0_monitors = Vec::new();
        for serialized in node_0_monitors_serialized.iter() {
                let mut read = &serialized[..];
-               let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read).unwrap();
+               let (_, monitor) = <(Option<BlockHash>, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
                assert!(read.is_empty());
                node_0_monitors.push(monitor);
        }
 
-       keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
-
        let mut nodes_0_read = &nodes_0_serialized[..];
        if let Err(msgs::DecodeError::InvalidValue) =
-               <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
+               <(Option<BlockHash>, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
                default_config: UserConfig::default(),
-               keys_manager: &keys_manager,
+               keys_manager,
                fee_estimator: &fee_estimator,
                chain_monitor: nodes[0].chain_monitor,
                tx_broadcaster: nodes[0].tx_broadcaster.clone(),
@@ -4643,9 +4638,9 @@ fn test_manager_serialize_deserialize_inconsistent_monitor() {
 
        let mut nodes_0_read = &nodes_0_serialized[..];
        let (_, nodes_0_deserialized_tmp) =
-               <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
+               <(Option<BlockHash>, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
                default_config: UserConfig::default(),
-               keys_manager: &keys_manager,
+               keys_manager,
                fee_estimator: &fee_estimator,
                chain_monitor: nodes[0].chain_monitor,
                tx_broadcaster: nodes[0].tx_broadcaster.clone(),
@@ -4693,120 +4688,26 @@ fn test_manager_serialize_deserialize_inconsistent_monitor() {
 macro_rules! check_spendable_outputs {
        ($node: expr, $der_idx: expr, $keysinterface: expr, $chan_value: expr) => {
                {
-                       let events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
+                       let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
                        let mut txn = Vec::new();
-                       for event in events {
+                       let mut all_outputs = Vec::new();
+                       let secp_ctx = Secp256k1::new();
+                       for event in events.drain(..) {
                                match event {
-                                       Event::SpendableOutputs { ref outputs } => {
-                                               for outp in outputs {
-                                                       match *outp {
-                                                               SpendableOutputDescriptor::StaticOutputCounterpartyPayment { ref outpoint, ref output, ref key_derivation_params } => {
-                                                                       let input = TxIn {
-                                                                               previous_output: outpoint.into_bitcoin_outpoint(),
-                                                                               script_sig: Script::new(),
-                                                                               sequence: 0,
-                                                                               witness: Vec::new(),
-                                                                       };
-                                                                       let outp = TxOut {
-                                                                               script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
-                                                                               value: output.value,
-                                                                       };
-                                                                       let mut spend_tx = Transaction {
-                                                                               version: 2,
-                                                                               lock_time: 0,
-                                                                               input: vec![input],
-                                                                               output: vec![outp],
-                                                                       };
-                                                                       spend_tx.output[0].value -= (spend_tx.get_weight() + 2 + 1 + 73 + 35 + 3) as u64 / 4; // (Max weight + 3 (to round up)) / 4
-                                                                       let secp_ctx = Secp256k1::new();
-                                                                       let keys = $keysinterface.derive_channel_keys($chan_value, key_derivation_params.0, key_derivation_params.1);
-                                                                       let remotepubkey = keys.pubkeys().payment_point;
-                                                                       let witness_script = Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: remotepubkey}, Network::Testnet).script_pubkey();
-                                                                       let sighash = Message::from_slice(&bip143::SigHashCache::new(&spend_tx).signature_hash(0, &witness_script, output.value, SigHashType::All)[..]).unwrap();
-                                                                       let remotesig = secp_ctx.sign(&sighash, &keys.inner.payment_key);
-                                                                       spend_tx.input[0].witness.push(remotesig.serialize_der().to_vec());
-                                                                       spend_tx.input[0].witness[0].push(SigHashType::All as u8);
-                                                                       spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
-                                                                       txn.push(spend_tx);
-                                                               },
-                                                               SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref per_commitment_point, ref to_self_delay, ref output, ref key_derivation_params, ref revocation_pubkey } => {
-                                                                       let input = TxIn {
-                                                                               previous_output: outpoint.into_bitcoin_outpoint(),
-                                                                               script_sig: Script::new(),
-                                                                               sequence: *to_self_delay as u32,
-                                                                               witness: Vec::new(),
-                                                                       };
-                                                                       let outp = TxOut {
-                                                                               script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
-                                                                               value: output.value,
-                                                                       };
-                                                                       let mut spend_tx = Transaction {
-                                                                               version: 2,
-                                                                               lock_time: 0,
-                                                                               input: vec![input],
-                                                                               output: vec![outp],
-                                                                       };
-                                                                       let secp_ctx = Secp256k1::new();
-                                                                       let keys = $keysinterface.derive_channel_keys($chan_value, key_derivation_params.0, key_derivation_params.1);
-                                                                       if let Ok(delayed_payment_key) = chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, &keys.inner.delayed_payment_base_key) {
-
-                                                                               let delayed_payment_pubkey = PublicKey::from_secret_key(&secp_ctx, &delayed_payment_key);
-                                                                               let witness_script = chan_utils::get_revokeable_redeemscript(revocation_pubkey, *to_self_delay, &delayed_payment_pubkey);
-                                                                               spend_tx.output[0].value -= (spend_tx.get_weight() + 2 + 1 + 73 + 1 + witness_script.len() + 1 + 3) as u64 / 4; // (Max weight + 3 (to round up)) / 4
-                                                                               let sighash = Message::from_slice(&bip143::SigHashCache::new(&spend_tx).signature_hash(0, &witness_script, output.value, SigHashType::All)[..]).unwrap();
-                                                                               let local_delayedsig = secp_ctx.sign(&sighash, &delayed_payment_key);
-                                                                               spend_tx.input[0].witness.push(local_delayedsig.serialize_der().to_vec());
-                                                                               spend_tx.input[0].witness[0].push(SigHashType::All as u8);
-                                                                               spend_tx.input[0].witness.push(vec!()); //MINIMALIF
-                                                                               spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
-                                                                       } else { panic!() }
-                                                                       txn.push(spend_tx);
-                                                               },
-                                                               SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
-                                                                       let secp_ctx = Secp256k1::new();
-                                                                       let input = TxIn {
-                                                                               previous_output: outpoint.into_bitcoin_outpoint(),
-                                                                               script_sig: Script::new(),
-                                                                               sequence: 0,
-                                                                               witness: Vec::new(),
-                                                                       };
-                                                                       let outp = TxOut {
-                                                                               script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
-                                                                               value: output.value,
-                                                                       };
-                                                                       let mut spend_tx = Transaction {
-                                                                               version: 2,
-                                                                               lock_time: 0,
-                                                                               input: vec![input],
-                                                                               output: vec![outp.clone()],
-                                                                       };
-                                                                       spend_tx.output[0].value -= (spend_tx.get_weight() + 2 + 1 + 73 + 35 + 3) as u64 / 4; // (Max weight + 3 (to round up)) / 4
-                                                                       let secret = {
-                                                                               match ExtendedPrivKey::new_master(Network::Testnet, &$node.node_seed) {
-                                                                                       Ok(master_key) => {
-                                                                                               match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx).expect("key space exhausted")) {
-                                                                                                       Ok(key) => key,
-                                                                                                       Err(_) => panic!("Your RNG is busted"),
-                                                                                               }
-                                                                                       }
-                                                                                       Err(_) => panic!("Your rng is busted"),
-                                                                               }
-                                                                       };
-                                                                       let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
-                                                                       let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
-                                                                       let sighash = Message::from_slice(&bip143::SigHashCache::new(&spend_tx).signature_hash(0, &witness_script, output.value, SigHashType::All)[..]).unwrap();
-                                                                       let sig = secp_ctx.sign(&sighash, &secret.private_key.key);
-                                                                       spend_tx.input[0].witness.push(sig.serialize_der().to_vec());
-                                                                       spend_tx.input[0].witness[0].push(SigHashType::All as u8);
-                                                                       spend_tx.input[0].witness.push(pubkey.key.serialize().to_vec());
-                                                                       txn.push(spend_tx);
-                                                               },
-                                                       }
+                                       Event::SpendableOutputs { mut outputs } => {
+                                               for outp in outputs.drain(..) {
+                                                       txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
+                                                       all_outputs.push(outp);
                                                }
                                        },
                                        _ => panic!("Unexpected event"),
                                };
                        }
+                       if all_outputs.len() > 1 {
+                               if let Ok(tx) = $keysinterface.backing.spend_spendable_outputs(&all_outputs.iter().map(|a| a).collect::<Vec<_>>(), Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx) {
+                                       txn.push(tx);
+                               }
+                       }
                        txn
                }
        }
@@ -4821,7 +4722,7 @@ fn test_claim_sizeable_push_msat() {
        let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
 
        let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
-       nodes[1].node.force_close_channel(&chan.2);
+       nodes[1].node.force_close_channel(&chan.2).unwrap();
        check_closed_broadcast!(nodes[1], false);
        check_added_monitors!(nodes[1], 1);
        let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
@@ -4848,7 +4749,7 @@ fn test_claim_on_remote_sizeable_push_msat() {
        let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
 
        let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
-       nodes[0].node.force_close_channel(&chan.2);
+       nodes[0].node.force_close_channel(&chan.2).unwrap();
        check_closed_broadcast!(nodes[0], false);
        check_added_monitors!(nodes[0], 1);
 
@@ -4896,9 +4797,10 @@ fn test_claim_on_remote_revoked_sizeable_push_msat() {
        connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
 
        let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
-       assert_eq!(spend_txn.len(), 2);
+       assert_eq!(spend_txn.len(), 3);
        check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
        check_spends!(spend_txn[1], node_txn[0]);
+       check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
 }
 
 #[test]
@@ -4993,8 +4895,10 @@ fn test_static_spendable_outputs_timeout_tx() {
        expect_payment_failed!(nodes[1], our_payment_hash, true);
 
        let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
-       assert_eq!(spend_txn.len(), 2); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
+       assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
+       check_spends!(spend_txn[0], commitment_tx[0]);
        check_spends!(spend_txn[1], node_txn[0]);
+       check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
 }
 
 #[test]
@@ -5035,7 +4939,8 @@ fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
 
 #[test]
 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
-       let chanmon_cfgs = create_chanmon_cfgs(2);
+       let mut chanmon_cfgs = create_chanmon_cfgs(2);
+       chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
        let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
        let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
        let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
@@ -5101,7 +5006,8 @@ fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
 
 #[test]
 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
-       let chanmon_cfgs = create_chanmon_cfgs(2);
+       let mut chanmon_cfgs = create_chanmon_cfgs(2);
+       chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
        let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
        let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
        let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
@@ -5169,11 +5075,12 @@ fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
 
        // Check A's ChannelMonitor was able to generate the right spendable output descriptor
        let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
-       assert_eq!(spend_txn.len(), 2);
+       assert_eq!(spend_txn.len(), 3);
        assert_eq!(spend_txn[0].input.len(), 1);
        check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
        assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
        check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
+       check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
 }
 
 #[test]
@@ -5406,6 +5313,7 @@ fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
 
        let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
        let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
+       assert_eq!(local_txn.len(), 1);
        assert_eq!(local_txn[0].input.len(), 1);
        check_spends!(local_txn[0], chan_1.3);
 
@@ -5426,10 +5334,13 @@ fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
        }
        let node_txn = {
                let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
+               assert_eq!(node_txn.len(), 3);
+               assert_eq!(node_txn[0], node_txn[2]);
+               assert_eq!(node_txn[1], local_txn[0]);
                assert_eq!(node_txn[0].input.len(), 1);
                assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
                check_spends!(node_txn[0], local_txn[0]);
-               vec![node_txn[0].clone(), node_txn[2].clone()]
+               vec![node_txn[0].clone()]
        };
 
        let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
@@ -5438,9 +5349,8 @@ fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
 
        // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
        let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
-       assert_eq!(spend_txn.len(), 2);
+       assert_eq!(spend_txn.len(), 1);
        check_spends!(spend_txn[0], node_txn[0]);
-       check_spends!(spend_txn[1], node_txn[1]);
 }
 
 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
@@ -5735,9 +5645,10 @@ fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
 
        // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
        let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
-       assert_eq!(spend_txn.len(), 2);
+       assert_eq!(spend_txn.len(), 3);
        check_spends!(spend_txn[0], local_txn[0]);
        check_spends!(spend_txn[1], htlc_timeout);
+       check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
 }
 
 #[test]
@@ -5751,8 +5662,8 @@ fn test_key_derivation_params() {
        // We manually create the node configuration to backup the seed.
        let seed = [42; 32];
        let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
-       let chain_monitor = test_utils::TestChainMonitor::new(Some(&chanmon_cfgs[0].chain_source), &chanmon_cfgs[0].tx_broadcaster, &chanmon_cfgs[0].logger, &chanmon_cfgs[0].fee_estimator, &chanmon_cfgs[0].persister);
-       let node = NodeCfg { chain_source: &chanmon_cfgs[0].chain_source, logger: &chanmon_cfgs[0].logger, tx_broadcaster: &chanmon_cfgs[0].tx_broadcaster, fee_estimator: &chanmon_cfgs[0].fee_estimator, chain_monitor, keys_manager, node_seed: seed };
+       let chain_monitor = test_utils::TestChainMonitor::new(Some(&chanmon_cfgs[0].chain_source), &chanmon_cfgs[0].tx_broadcaster, &chanmon_cfgs[0].logger, &chanmon_cfgs[0].fee_estimator, &chanmon_cfgs[0].persister, &keys_manager);
+       let node = NodeCfg { chain_source: &chanmon_cfgs[0].chain_source, logger: &chanmon_cfgs[0].logger, tx_broadcaster: &chanmon_cfgs[0].tx_broadcaster, fee_estimator: &chanmon_cfgs[0].fee_estimator, chain_monitor, keys_manager: &keys_manager, node_seed: seed };
        let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
        node_cfgs.remove(0);
        node_cfgs.insert(0, node);
@@ -5805,9 +5716,10 @@ fn test_key_derivation_params() {
        // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
        let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
        let spend_txn = check_spendable_outputs!(nodes[0], 1, new_keys_manager, 100000);
-       assert_eq!(spend_txn.len(), 2);
+       assert_eq!(spend_txn.len(), 3);
        check_spends!(spend_txn[0], local_txn_1[0]);
        check_spends!(spend_txn[1], htlc_timeout);
+       check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
 }
 
 #[test]
@@ -7086,7 +6998,8 @@ fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
        // We can have at most two valid local commitment tx, so both cases must be covered, and both txs must be checked to get them all as
        // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
 
-       let chanmon_cfgs = create_chanmon_cfgs(2);
+       let mut chanmon_cfgs = create_chanmon_cfgs(2);
+       chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
        let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
        let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
        let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
@@ -7288,7 +7201,7 @@ fn test_upfront_shutdown_script() {
        let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
        node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
        // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that  we disconnect peer
-       nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
+       nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
     assert!(regex::Regex::new(r"Got shutdown request with a scriptpubkey \([A-Fa-f0-9]+\) which did not match their previous scriptpubkey.").unwrap().is_match(check_closed_broadcast!(nodes[2], true).unwrap().data.as_str()));
        check_added_monitors!(nodes[2], 1);
 
@@ -7297,7 +7210,7 @@ fn test_upfront_shutdown_script() {
        nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
        let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
        // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
-       nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
+       nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
        let events = nodes[2].node.get_and_clear_pending_msg_events();
        assert_eq!(events.len(), 1);
        match events[0] {
@@ -7311,7 +7224,7 @@ fn test_upfront_shutdown_script() {
        nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
        let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
        node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
-       nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_1_shutdown);
+       nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
        let events = nodes[1].node.get_and_clear_pending_msg_events();
        assert_eq!(events.len(), 1);
        match events[0] {
@@ -7325,7 +7238,7 @@ fn test_upfront_shutdown_script() {
        nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
        let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
        node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
-       nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
+       nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
        let events = nodes[0].node.get_and_clear_pending_msg_events();
        assert_eq!(events.len(), 1);
        match events[0] {
@@ -7339,7 +7252,70 @@ fn test_upfront_shutdown_script() {
        nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
        let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
        node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
-       nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
+       nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
+       let events = nodes[0].node.get_and_clear_pending_msg_events();
+       assert_eq!(events.len(), 2);
+       match events[0] {
+               MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
+               _ => panic!("Unexpected event"),
+       }
+       match events[1] {
+               MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
+               _ => panic!("Unexpected event"),
+       }
+}
+
+#[test]
+fn test_upfront_shutdown_script_unsupport_segwit() {
+       // We test that channel is closed early
+       // if a segwit program is passed as upfront shutdown script,
+       // but the peer does not support segwit.
+       let chanmon_cfgs = create_chanmon_cfgs(2);
+       let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
+       let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
+       let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
+
+       nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
+
+       let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
+       open_channel.shutdown_scriptpubkey = Present(Builder::new().push_int(16)
+               .push_slice(&[0, 0])
+               .into_script());
+
+       let features = InitFeatures::known().clear_shutdown_anysegwit();
+       nodes[0].node.handle_open_channel(&nodes[0].node.get_our_node_id(), features, &open_channel);
+
+       let events = nodes[0].node.get_and_clear_pending_msg_events();
+       assert_eq!(events.len(), 1);
+       match events[0] {
+               MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
+                       assert_eq!(node_id, nodes[0].node.get_our_node_id());
+                       assert!(regex::Regex::new(r"Peer is signaling upfront_shutdown but has provided a non-accepted scriptpubkey format. script: (\([A-Fa-f0-9]+\))").unwrap().is_match(&*msg.data));
+               },
+               _ => panic!("Unexpected event"),
+       }
+}
+
+#[test]
+fn test_shutdown_script_any_segwit_allowed() {
+       let mut config = UserConfig::default();
+       config.channel_options.announced_channel = true;
+       config.peer_channel_config_limits.force_announced_channel_preference = false;
+       config.channel_options.commit_upfront_shutdown_pubkey = false;
+       let user_cfgs = [None, Some(config), None];
+       let chanmon_cfgs = create_chanmon_cfgs(3);
+       let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
+       let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
+       let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
+
+       //// We test if the remote peer accepts opt_shutdown_anysegwit, a witness program can be used on shutdown
+       let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
+       nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
+       let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
+       node_0_shutdown.scriptpubkey = Builder::new().push_int(16)
+               .push_slice(&[0, 0])
+               .into_script();
+       nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
        let events = nodes[0].node.get_and_clear_pending_msg_events();
        assert_eq!(events.len(), 2);
        match events[0] {
@@ -7352,6 +7328,73 @@ fn test_upfront_shutdown_script() {
        }
 }
 
+#[test]
+fn test_shutdown_script_any_segwit_not_allowed() {
+       let mut config = UserConfig::default();
+       config.channel_options.announced_channel = true;
+       config.peer_channel_config_limits.force_announced_channel_preference = false;
+       config.channel_options.commit_upfront_shutdown_pubkey = false;
+       let user_cfgs = [None, Some(config), None];
+       let chanmon_cfgs = create_chanmon_cfgs(3);
+       let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
+       let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
+       let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
+
+       //// We test that if the remote peer does not accept opt_shutdown_anysegwit, the witness program cannot be used on shutdown
+       let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
+       nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
+       let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
+       // Make an any segwit version script
+       node_0_shutdown.scriptpubkey = Builder::new().push_int(16)
+               .push_slice(&[0, 0])
+               .into_script();
+       let flags_no = InitFeatures::known().clear_shutdown_anysegwit();
+       nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &flags_no, &node_0_shutdown);
+       let events = nodes[0].node.get_and_clear_pending_msg_events();
+       assert_eq!(events.len(), 2);
+       match events[1] {
+               MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
+                       assert_eq!(node_id, nodes[1].node.get_our_node_id());
+                       assert_eq!(msg.data, "Got a nonstandard scriptpubkey (60020000) from remote peer".to_owned())
+               },
+               _ => panic!("Unexpected event"),
+       }
+       check_added_monitors!(nodes[0], 1);
+}
+
+#[test]
+fn test_shutdown_script_segwit_but_not_anysegwit() {
+       let mut config = UserConfig::default();
+       config.channel_options.announced_channel = true;
+       config.peer_channel_config_limits.force_announced_channel_preference = false;
+       config.channel_options.commit_upfront_shutdown_pubkey = false;
+       let user_cfgs = [None, Some(config), None];
+       let chanmon_cfgs = create_chanmon_cfgs(3);
+       let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
+       let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
+       let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
+
+       //// We test that if shutdown any segwit is supported and we send a witness script with 0 version, this is not accepted
+       let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
+       nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
+       let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
+       // Make a segwit script that is not a valid as any segwit
+       node_0_shutdown.scriptpubkey = Builder::new().push_int(0)
+               .push_slice(&[0, 0])
+               .into_script();
+       nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
+       let events = nodes[0].node.get_and_clear_pending_msg_events();
+       assert_eq!(events.len(), 2);
+       match events[1] {
+               MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
+                       assert_eq!(node_id, nodes[1].node.get_our_node_id());
+                       assert_eq!(msg.data, "Got a nonstandard scriptpubkey (00020000) from remote peer".to_owned())
+               },
+               _ => panic!("Unexpected event"),
+       }
+       check_added_monitors!(nodes[0], 1);
+}
+
 #[test]
 fn test_user_configurable_csv_delay() {
        // We test our channel constructors yield errors when we pass them absurd csv delay
@@ -7367,8 +7410,7 @@ fn test_user_configurable_csv_delay() {
        let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
 
        // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
-       let keys_manager: Arc<KeysInterface<ChanKeySigner = EnforcingChannelKeys>> = Arc::new(test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet));
-       if let Err(error) = Channel::new_outbound(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &keys_manager, nodes[1].node.get_our_node_id(), 1000000, 1000000, 0, &low_our_to_self_config) {
+       if let Err(error) = Channel::new_outbound(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), 1000000, 1000000, 0, &low_our_to_self_config) {
                match error {
                        APIError::APIMisuseError { err } => { assert!(regex::Regex::new(r"Configured with an unreasonable our_to_self_delay \(\d+\) putting user funds at risks").unwrap().is_match(err.as_str())); },
                        _ => panic!("Unexpected event"),
@@ -7379,7 +7421,7 @@ fn test_user_configurable_csv_delay() {
        nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
        let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
        open_channel.to_self_delay = 200;
-       if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &keys_manager, nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel, 0, &low_our_to_self_config) {
+       if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel, 0, &low_our_to_self_config) {
                match error {
                        ChannelError::Close(err) => { assert!(regex::Regex::new(r"Configured with an unreasonable our_to_self_delay \(\d+\) putting user funds at risks").unwrap().is_match(err.as_str()));  },
                        _ => panic!("Unexpected event"),
@@ -7405,7 +7447,7 @@ fn test_user_configurable_csv_delay() {
        nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
        let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
        open_channel.to_self_delay = 200;
-       if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &keys_manager, nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel, 0, &high_their_to_self_config) {
+       if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel, 0, &high_their_to_self_config) {
                match error {
                        ChannelError::Close(err) => { assert!(regex::Regex::new(r"They wanted our payments to be delayed by a needlessly long period\. Upper limit: \d+\. Actual: \d+").unwrap().is_match(err.as_str())); },
                        _ => panic!("Unexpected event"),
@@ -7417,17 +7459,22 @@ fn test_user_configurable_csv_delay() {
 fn test_data_loss_protect() {
        // We want to be sure that :
        // * we don't broadcast our Local Commitment Tx in case of fallen behind
+       //   (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
        // * we close channel in case of detecting other being fallen behind
        // * we are able to claim our own outputs thanks to to_remote being static
-       let keys_manager;
+       // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
        let persister;
        let logger;
        let fee_estimator;
        let tx_broadcaster;
        let chain_source;
+       let mut chanmon_cfgs = create_chanmon_cfgs(2);
+       // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
+       // during signing due to revoked tx
+       chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
+       let keys_manager = &chanmon_cfgs[0].keys_manager;
        let monitor;
        let node_state_0;
-       let chanmon_cfgs = create_chanmon_cfgs(2);
        let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
        let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
        let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
@@ -7437,7 +7484,7 @@ fn test_data_loss_protect() {
        // Cache node A state before any channel update
        let previous_node_state = nodes[0].node.encode();
        let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
-       nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.serialize_for_disk(&mut previous_chain_monitor_state).unwrap();
+       nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut previous_chain_monitor_state).unwrap();
 
        send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
        send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
@@ -7447,18 +7494,17 @@ fn test_data_loss_protect() {
 
        // Restore node A from previous state
        logger = test_utils::TestLogger::with_id(format!("node {}", 0));
-       let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut ::std::io::Cursor::new(previous_chain_monitor_state.0)).unwrap().1;
+       let mut chain_monitor = <(Option<BlockHash>, ChannelMonitor<EnforcingSigner>)>::read(&mut ::std::io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
        chain_source = test_utils::TestChainSource::new(Network::Testnet);
        tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
        fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
-       keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
        persister = test_utils::TestPersister::new();
-       monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister);
+       monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
        node_state_0 = {
                let mut channel_monitors = HashMap::new();
                channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
-               <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut ::std::io::Cursor::new(previous_node_state), ChannelManagerReadArgs {
-                       keys_manager: &keys_manager,
+               <(Option<BlockHash>, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut ::std::io::Cursor::new(previous_node_state), ChannelManagerReadArgs {
+                       keys_manager: keys_manager,
                        fee_estimator: &fee_estimator,
                        chain_monitor: &monitor,
                        logger: &logger,
@@ -7520,7 +7566,7 @@ fn test_data_loss_protect() {
        let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
        connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[0].clone()]}, 0);
        connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
-       let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
+       let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 1000000);
        assert_eq!(spend_txn.len(), 1);
        check_spends!(spend_txn[0], node_txn[0]);
 }
@@ -7745,7 +7791,8 @@ fn test_bump_penalty_txn_on_revoked_htlcs() {
        // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
        // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
 
-       let chanmon_cfgs = create_chanmon_cfgs(2);
+       let mut chanmon_cfgs = create_chanmon_cfgs(2);
+       chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
        let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
        let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
        let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
@@ -8115,7 +8162,7 @@ fn test_counterparty_raa_skip_no_crash() {
        // commitment transaction, we would have happily carried on and provided them the next
        // commitment transaction based on one RAA forward. This would probably eventually have led to
        // channel closure, but it would not have resulted in funds loss. Still, our
-       // EnforcingChannelKeys would have paniced as it doesn't like jumps into the future. Here, we
+       // EnforcingSigner would have paniced as it doesn't like jumps into the future. Here, we
        // check simply that the channel is closed in response to such an RAA, but don't check whether
        // we decide to punish our counterparty for revoking their funds (as we don't currently
        // implement that).
@@ -8126,11 +8173,13 @@ fn test_counterparty_raa_skip_no_crash() {
        let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
 
        let mut guard = nodes[0].node.channel_state.lock().unwrap();
-       let keys = &guard.by_id.get_mut(&channel_id).unwrap().holder_keys;
+       let keys = &guard.by_id.get_mut(&channel_id).unwrap().get_signer();
        const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
+       let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
+       // Must revoke without gaps
+       keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
        let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
                &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
-       let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
 
        nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
                &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
@@ -8182,10 +8231,10 @@ fn test_bump_txn_sanitize_tracking_maps() {
        connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn }, 130);
        connect_blocks(&nodes[0], 5, 130,  false, header_130.block_hash());
        {
-               let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
+               let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
                if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
-                       assert!(monitor.onchain_tx_handler.pending_claim_requests.is_empty());
-                       assert!(monitor.onchain_tx_handler.claimable_outpoints.is_empty());
+                       assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
+                       assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
                }
        }
 }
@@ -8316,14 +8365,14 @@ fn test_update_err_monitor_lockdown() {
        let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
        let persister = test_utils::TestPersister::new();
        let watchtower = {
-               let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
+               let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
                let monitor = monitors.get(&outpoint).unwrap();
                let mut w = test_utils::TestVecWriter(Vec::new());
-               monitor.serialize_for_disk(&mut w).unwrap();
-               let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
-                               &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
+               monitor.write(&mut w).unwrap();
+               let new_monitor = <(Option<BlockHash>, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
+                               &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
                assert!(new_monitor == *monitor);
-               let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister);
+               let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
                assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
                watchtower
        };
@@ -8375,14 +8424,14 @@ fn test_concurrent_monitor_claim() {
        let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
        let persister = test_utils::TestPersister::new();
        let watchtower_alice = {
-               let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
+               let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
                let monitor = monitors.get(&outpoint).unwrap();
                let mut w = test_utils::TestVecWriter(Vec::new());
-               monitor.serialize_for_disk(&mut w).unwrap();
-               let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
-                               &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
+               monitor.write(&mut w).unwrap();
+               let new_monitor = <(Option<BlockHash>, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
+                               &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
                assert!(new_monitor == *monitor);
-               let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister);
+               let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
                assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
                watchtower
        };
@@ -8401,14 +8450,14 @@ fn test_concurrent_monitor_claim() {
        let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
        let persister = test_utils::TestPersister::new();
        let watchtower_bob = {
-               let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
+               let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
                let monitor = monitors.get(&outpoint).unwrap();
                let mut w = test_utils::TestVecWriter(Vec::new());
-               monitor.serialize_for_disk(&mut w).unwrap();
-               let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
-                               &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
+               monitor.write(&mut w).unwrap();
+               let new_monitor = <(Option<BlockHash>, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
+                               &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
                assert!(new_monitor == *monitor);
-               let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister);
+               let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
                assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
                watchtower
        };
@@ -8586,7 +8635,7 @@ fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain
        // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
        let mut force_closing_node = 0; // Alice force-closes
        if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
-       nodes[force_closing_node].node.force_close_channel(&chan_ab.2);
+       nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
        check_closed_broadcast!(nodes[force_closing_node], false);
        check_added_monitors!(nodes[force_closing_node], 1);
        if go_onchain_before_fulfill {
@@ -8869,3 +8918,66 @@ fn test_duplicate_chan_id() {
        update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
        send_payment(&nodes[0], &[&nodes[1]], 8000000, 8_000_000);
 }
+
+#[test]
+fn test_error_chans_closed() {
+       // Test that we properly handle error messages, closing appropriate channels.
+       //
+       // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
+       // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
+       // we can test various edge cases around it to ensure we don't regress.
+       let chanmon_cfgs = create_chanmon_cfgs(3);
+       let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
+       let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
+       let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
+
+       // Create some initial channels
+       let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
+       let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
+       let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
+
+       assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
+       assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
+       assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
+
+       // Closing a channel from a different peer has no effect
+       nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
+       assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
+
+       // Closing one channel doesn't impact others
+       nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
+       check_added_monitors!(nodes[0], 1);
+       check_closed_broadcast!(nodes[0], false);
+       assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
+       assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_1.2 || nodes[0].node.list_usable_channels()[1].channel_id == chan_1.2);
+       assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2 || nodes[0].node.list_usable_channels()[1].channel_id == chan_3.2);
+
+       // A null channel ID should close all channels
+       let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
+       nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
+       check_added_monitors!(nodes[0], 2);
+       let events = nodes[0].node.get_and_clear_pending_msg_events();
+       assert_eq!(events.len(), 2);
+       match events[0] {
+               MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
+                       assert_eq!(msg.contents.flags & 2, 2);
+               },
+               _ => panic!("Unexpected event"),
+       }
+       match events[1] {
+               MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
+                       assert_eq!(msg.contents.flags & 2, 2);
+               },
+               _ => panic!("Unexpected event"),
+       }
+       // Note that at this point users of a standard PeerHandler will end up calling
+       // peer_disconnected with no_connection_possible set to false, duplicating the
+       // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
+       // users with their own peer handling logic. We duplicate the call here, however.
+       assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
+       assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
+
+       nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
+       assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
+       assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
+}
index 25553c7080fdaa46e9268978d8348e5be00140cb..3042b4d32e0a344e185ef9756654aefa759606aa 100644 (file)
@@ -33,9 +33,10 @@ use bitcoin::hash_types::{Txid, BlockHash};
 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
 
 use std::{cmp, fmt};
+use std::fmt::Debug;
 use std::io::Read;
 
-use util::events;
+use util::events::MessageSendEventsProvider;
 use util::ser::{Readable, Writeable, Writer, FixedLengthReader, HighZeroBytesDroppedVarInt};
 
 use ln::channelmanager::{PaymentPreimage, PaymentHash, PaymentSecret};
@@ -44,7 +45,7 @@ use ln::channelmanager::{PaymentPreimage, PaymentHash, PaymentSecret};
 pub(crate) const MAX_VALUE_MSAT: u64 = 21_000_000_0000_0000_000;
 
 /// An error in decoding a message or struct.
-#[derive(Debug)]
+#[derive(Clone, Debug)]
 pub enum DecodeError {
        /// A version byte specified something we don't know how to handle.
        /// Includes unknown realm byte in an OnionHopData packet
@@ -60,20 +61,19 @@ pub enum DecodeError {
        /// A length descriptor in the packet didn't describe the later data correctly
        BadLengthDescriptor,
        /// Error from std::io
-       Io(::std::io::Error),
+       Io(/// (C-not exported) as ErrorKind doesn't have a reasonable mapping
+        ::std::io::ErrorKind),
 }
 
 /// An init message to be sent or received from a peer
-#[derive(Clone)]
+#[derive(Clone, Debug, PartialEq)]
 pub struct Init {
-       #[cfg(not(feature = "fuzztarget"))]
-       pub(crate) features: InitFeatures,
-       #[cfg(feature = "fuzztarget")]
+       /// The relevant features which the sender supports
        pub features: InitFeatures,
 }
 
 /// An error message to be sent or received from a peer
-#[derive(Clone)]
+#[derive(Clone, Debug, PartialEq)]
 pub struct ErrorMessage {
        /// The channel ID involved in the error
        pub channel_id: [u8; 32],
@@ -85,7 +85,7 @@ pub struct ErrorMessage {
 }
 
 /// A ping message to be sent or received from a peer
-#[derive(Clone)]
+#[derive(Clone, Debug, PartialEq)]
 pub struct Ping {
        /// The desired response length
        pub ponglen: u16,
@@ -95,7 +95,7 @@ pub struct Ping {
 }
 
 /// A pong message to be sent or received from a peer
-#[derive(Clone)]
+#[derive(Clone, Debug, PartialEq)]
 pub struct Pong {
        /// The pong packet size.
        /// This field is not sent on the wire. byteslen zeros are sent.
@@ -103,7 +103,7 @@ pub struct Pong {
 }
 
 /// An open_channel message to be sent or received from a peer
-#[derive(Clone)]
+#[derive(Clone, Debug, PartialEq)]
 pub struct OpenChannel {
        /// The genesis hash of the blockchain where the channel is to be opened
        pub chain_hash: BlockHash,
@@ -146,7 +146,7 @@ pub struct OpenChannel {
 }
 
 /// An accept_channel message to be sent or received from a peer
-#[derive(Clone)]
+#[derive(Clone, Debug, PartialEq)]
 pub struct AcceptChannel {
        /// A temporary channel ID, until the funding outpoint is announced
        pub temporary_channel_id: [u8; 32],
@@ -181,7 +181,7 @@ pub struct AcceptChannel {
 }
 
 /// A funding_created message to be sent or received from a peer
-#[derive(Clone)]
+#[derive(Clone, Debug, PartialEq)]
 pub struct FundingCreated {
        /// A temporary channel ID, until the funding is established
        pub temporary_channel_id: [u8; 32],
@@ -194,7 +194,7 @@ pub struct FundingCreated {
 }
 
 /// A funding_signed message to be sent or received from a peer
-#[derive(Clone)]
+#[derive(Clone, Debug, PartialEq)]
 pub struct FundingSigned {
        /// The channel ID
        pub channel_id: [u8; 32],
@@ -203,7 +203,7 @@ pub struct FundingSigned {
 }
 
 /// A funding_locked message to be sent or received from a peer
-#[derive(Clone, PartialEq)]
+#[derive(Clone, Debug, PartialEq)]
 pub struct FundingLocked {
        /// The channel ID
        pub channel_id: [u8; 32],
@@ -212,7 +212,7 @@ pub struct FundingLocked {
 }
 
 /// A shutdown message to be sent or received from a peer
-#[derive(Clone, PartialEq)]
+#[derive(Clone, Debug, PartialEq)]
 pub struct Shutdown {
        /// The channel ID
        pub channel_id: [u8; 32],
@@ -222,7 +222,7 @@ pub struct Shutdown {
 }
 
 /// A closing_signed message to be sent or received from a peer
-#[derive(Clone, PartialEq)]
+#[derive(Clone, Debug, PartialEq)]
 pub struct ClosingSigned {
        /// The channel ID
        pub channel_id: [u8; 32],
@@ -233,7 +233,7 @@ pub struct ClosingSigned {
 }
 
 /// An update_add_htlc message to be sent or received from a peer
-#[derive(Clone, PartialEq)]
+#[derive(Clone, Debug, PartialEq)]
 pub struct UpdateAddHTLC {
        /// The channel ID
        pub channel_id: [u8; 32],
@@ -249,7 +249,7 @@ pub struct UpdateAddHTLC {
 }
 
 /// An update_fulfill_htlc message to be sent or received from a peer
-#[derive(Clone, PartialEq)]
+#[derive(Clone, Debug, PartialEq)]
 pub struct UpdateFulfillHTLC {
        /// The channel ID
        pub channel_id: [u8; 32],
@@ -260,7 +260,7 @@ pub struct UpdateFulfillHTLC {
 }
 
 /// An update_fail_htlc message to be sent or received from a peer
-#[derive(Clone, PartialEq)]
+#[derive(Clone, Debug, PartialEq)]
 pub struct UpdateFailHTLC {
        /// The channel ID
        pub channel_id: [u8; 32],
@@ -270,7 +270,7 @@ pub struct UpdateFailHTLC {
 }
 
 /// An update_fail_malformed_htlc message to be sent or received from a peer
-#[derive(Clone, PartialEq)]
+#[derive(Clone, Debug, PartialEq)]
 pub struct UpdateFailMalformedHTLC {
        /// The channel ID
        pub channel_id: [u8; 32],
@@ -282,7 +282,7 @@ pub struct UpdateFailMalformedHTLC {
 }
 
 /// A commitment_signed message to be sent or received from a peer
-#[derive(Clone, PartialEq)]
+#[derive(Clone, Debug, PartialEq)]
 pub struct CommitmentSigned {
        /// The channel ID
        pub channel_id: [u8; 32],
@@ -293,7 +293,7 @@ pub struct CommitmentSigned {
 }
 
 /// A revoke_and_ack message to be sent or received from a peer
-#[derive(Clone, PartialEq)]
+#[derive(Clone, Debug, PartialEq)]
 pub struct RevokeAndACK {
        /// The channel ID
        pub channel_id: [u8; 32],
@@ -304,7 +304,7 @@ pub struct RevokeAndACK {
 }
 
 /// An update_fee message to be sent or received from a peer
-#[derive(PartialEq, Clone)]
+#[derive(Clone, Debug, PartialEq)]
 pub struct UpdateFee {
        /// The channel ID
        pub channel_id: [u8; 32],
@@ -312,7 +312,7 @@ pub struct UpdateFee {
        pub feerate_per_kw: u32,
 }
 
-#[derive(PartialEq, Clone)]
+#[derive(Clone, Debug, PartialEq)]
 /// Proof that the sender knows the per-commitment secret of the previous commitment transaction.
 /// This is used to convince the recipient that the channel is at a certain commitment
 /// number even if they lost that data due to a local failure.  Of course, the peer may lie
@@ -326,7 +326,7 @@ pub struct DataLossProtect {
 }
 
 /// A channel_reestablish message to be sent or received from a peer
-#[derive(PartialEq, Clone)]
+#[derive(Clone, Debug, PartialEq)]
 pub struct ChannelReestablish {
        /// The channel ID
        pub channel_id: [u8; 32],
@@ -339,7 +339,7 @@ pub struct ChannelReestablish {
 }
 
 /// An announcement_signatures message to be sent or received from a peer
-#[derive(PartialEq, Clone, Debug)]
+#[derive(Clone, Debug, PartialEq)]
 pub struct AnnouncementSignatures {
        /// The channel ID
        pub channel_id: [u8; 32],
@@ -352,7 +352,7 @@ pub struct AnnouncementSignatures {
 }
 
 /// An address which can be used to connect to a remote peer
-#[derive(Clone, PartialEq, Debug)]
+#[derive(Clone, Debug, PartialEq)]
 pub enum NetAddress {
        /// An IPv4 address/port on which the peer is listening.
        IPv4 {
@@ -390,15 +390,6 @@ pub enum NetAddress {
        },
 }
 impl NetAddress {
-       fn get_id(&self) -> u8 {
-               match self {
-                       &NetAddress::IPv4 {..} => { 1 },
-                       &NetAddress::IPv6 {..} => { 2 },
-                       &NetAddress::OnionV2 {..} => { 3 },
-                       &NetAddress::OnionV3 {..} => { 4 },
-               }
-       }
-
        /// Strict byte-length of address descriptor, 1-byte type not recorded
        fn len(&self) -> u16 {
                match self {
@@ -479,7 +470,7 @@ impl Readable for Result<NetAddress, u8> {
 }
 
 /// The unsigned part of a node_announcement
-#[derive(PartialEq, Clone, Debug)]
+#[derive(Clone, Debug, PartialEq)]
 pub struct UnsignedNodeAnnouncement {
        /// The advertised features
        pub features: NodeFeatures,
@@ -498,7 +489,7 @@ pub struct UnsignedNodeAnnouncement {
        pub(crate) excess_address_data: Vec<u8>,
        pub(crate) excess_data: Vec<u8>,
 }
-#[derive(PartialEq, Clone, Debug)]
+#[derive(Clone, Debug, PartialEq)]
 /// A node_announcement message to be sent or received from a peer
 pub struct NodeAnnouncement {
        /// The signature by the node key
@@ -508,7 +499,7 @@ pub struct NodeAnnouncement {
 }
 
 /// The unsigned part of a channel_announcement
-#[derive(PartialEq, Clone, Debug)]
+#[derive(Clone, Debug, PartialEq)]
 pub struct UnsignedChannelAnnouncement {
        /// The advertised channel features
        pub features: ChannelFeatures,
@@ -527,7 +518,7 @@ pub struct UnsignedChannelAnnouncement {
        pub(crate) excess_data: Vec<u8>,
 }
 /// A channel_announcement message to be sent or received from a peer
-#[derive(PartialEq, Clone, Debug)]
+#[derive(Clone, Debug, PartialEq)]
 pub struct ChannelAnnouncement {
        /// Authentication of the announcement by the first public node
        pub node_signature_1: Signature,
@@ -542,7 +533,7 @@ pub struct ChannelAnnouncement {
 }
 
 /// The unsigned part of a channel_update
-#[derive(PartialEq, Clone, Debug)]
+#[derive(Clone, Debug, PartialEq)]
 pub struct UnsignedChannelUpdate {
        /// The genesis hash of the blockchain where the channel is to be opened
        pub chain_hash: BlockHash,
@@ -565,7 +556,7 @@ pub struct UnsignedChannelUpdate {
        pub(crate) excess_data: Vec<u8>,
 }
 /// A channel_update message to be sent or received from a peer
-#[derive(PartialEq, Clone, Debug)]
+#[derive(Clone, Debug, PartialEq)]
 pub struct ChannelUpdate {
        /// A signature of the channel update
        pub signature: Signature,
@@ -577,7 +568,7 @@ pub struct ChannelUpdate {
 /// UTXOs in a range of blocks. The recipient of a query makes a best
 /// effort to reply to the query using one or more reply_channel_range
 /// messages.
-#[derive(Clone, Debug)]
+#[derive(Clone, Debug, PartialEq)]
 pub struct QueryChannelRange {
        /// The genesis hash of the blockchain being queried
        pub chain_hash: BlockHash,
@@ -594,7 +585,7 @@ pub struct QueryChannelRange {
 /// not be a perfect view of the network. The short_channel_ids in the
 /// reply are encoded. We only support encoding_type=0 uncompressed
 /// serialization and do not support encoding_type=1 zlib serialization.
-#[derive(Clone, Debug)]
+#[derive(Clone, Debug, PartialEq)]
 pub struct ReplyChannelRange {
        /// The genesis hash of the blockchain being queried
        pub chain_hash: BlockHash,
@@ -602,9 +593,8 @@ pub struct ReplyChannelRange {
        pub first_blocknum: u32,
        /// The number of blocks included in the range of the reply
        pub number_of_blocks: u32,
-       /// Indicates if the query recipient maintains up-to-date channel
-       /// information for the chain_hash
-       pub full_information: bool,
+       /// True when this is the final reply for a query
+       pub sync_complete: bool,
        /// The short_channel_ids in the channel range
        pub short_channel_ids: Vec<u64>,
 }
@@ -617,7 +607,7 @@ pub struct ReplyChannelRange {
 /// reply_short_channel_ids_end message. The short_channel_ids sent in
 /// this query are encoded. We only support encoding_type=0 uncompressed
 /// serialization and do not support encoding_type=1 zlib serialization.
-#[derive(Clone, Debug)]
+#[derive(Clone, Debug, PartialEq)]
 pub struct QueryShortChannelIds {
        /// The genesis hash of the blockchain being queried
        pub chain_hash: BlockHash,
@@ -629,7 +619,7 @@ pub struct QueryShortChannelIds {
 /// query_short_channel_ids message. The query recipient makes a best
 /// effort to respond based on their local network view which may not be
 /// a perfect view of the network.
-#[derive(Clone, Debug)]
+#[derive(Clone, Debug, PartialEq)]
 pub struct ReplyShortChannelIdsEnd {
        /// The genesis hash of the blockchain that was queried
        pub chain_hash: BlockHash,
@@ -641,7 +631,7 @@ pub struct ReplyShortChannelIdsEnd {
 /// A gossip_timestamp_filter message is used by a node to request
 /// gossip relay for messages in the requested time range when the
 /// gossip_queries feature has been negotiated.
-#[derive(Clone, Debug)]
+#[derive(Clone, Debug, PartialEq)]
 pub struct GossipTimestampFilter {
        /// The genesis hash of the blockchain for channel and node information
        pub chain_hash: BlockHash,
@@ -658,7 +648,7 @@ enum EncodingType {
 }
 
 /// Used to put an error message in a LightningError
-#[derive(Clone)]
+#[derive(Clone, Debug)]
 pub enum ErrorAction {
        /// The peer took some action which made us think they were useless. Disconnect them.
        DisconnectPeer {
@@ -675,6 +665,7 @@ pub enum ErrorAction {
 }
 
 /// An Err type for failure to process messages.
+#[derive(Clone, Debug)]
 pub struct LightningError {
        /// A human-readable message describing the error
        pub err: String,
@@ -684,7 +675,7 @@ pub struct LightningError {
 
 /// Struct used to return values from revoke_and_ack messages, containing a bunch of commitment
 /// transaction updates if they were pending.
-#[derive(PartialEq, Clone)]
+#[derive(Clone, Debug, PartialEq)]
 pub struct CommitmentUpdate {
        /// update_add_htlc messages which should be sent
        pub update_add_htlcs: Vec<UpdateAddHTLC>,
@@ -703,7 +694,7 @@ pub struct CommitmentUpdate {
 /// The information we received from a peer along the route of a payment we originated. This is
 /// returned by ChannelMessageHandler::handle_update_fail_htlc to be passed into
 /// RoutingMessageHandler::handle_htlc_fail_channel_update to update our network map.
-#[derive(Clone)]
+#[derive(Clone, Debug, PartialEq)]
 pub enum HTLCFailChannelUpdate {
        /// We received an error which included a full ChannelUpdate message.
        ChannelUpdateMessage {
@@ -734,7 +725,7 @@ pub enum HTLCFailChannelUpdate {
 /// OptionalFeild simply gets Present if there are enough bytes to read into it), we have a
 /// separate enum type for them.
 /// (C-not exported) due to a free generic in T
-#[derive(Clone, PartialEq, Debug)]
+#[derive(Clone, Debug, PartialEq)]
 pub enum OptionalField<T> {
        /// Optional field is included in message
        Present(T),
@@ -746,7 +737,7 @@ pub enum OptionalField<T> {
 ///
 /// Messages MAY be called in parallel when they originate from different their_node_ids, however
 /// they MUST NOT be called in parallel when the two calls have the same their_node_id.
-pub trait ChannelMessageHandler : events::MessageSendEventsProvider + Send + Sync {
+pub trait ChannelMessageHandler : MessageSendEventsProvider + Send + Sync {
        //Channel init:
        /// Handle an incoming open_channel message from the given peer.
        fn handle_open_channel(&self, their_node_id: &PublicKey, their_features: InitFeatures, msg: &OpenChannel);
@@ -761,7 +752,7 @@ pub trait ChannelMessageHandler : events::MessageSendEventsProvider + Send + Syn
 
        // Channl close:
        /// Handle an incoming shutdown message from the given peer.
-       fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown);
+       fn handle_shutdown(&self, their_node_id: &PublicKey, their_features: &InitFeatures, msg: &Shutdown);
        /// Handle an incoming closing_signed message from the given peer.
        fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned);
 
@@ -810,7 +801,7 @@ pub trait ChannelMessageHandler : events::MessageSendEventsProvider + Send + Syn
 /// For `gossip_queries` messages there are potential DoS vectors when handling
 /// inbound queries. Implementors using an on-disk network graph should be aware of
 /// repeated disk I/O for queries accessing different parts of the network graph.
-pub trait RoutingMessageHandler : Send + Sync + events::MessageSendEventsProvider {
+pub trait RoutingMessageHandler : Send + Sync + MessageSendEventsProvider {
        /// Handle an incoming node_announcement message, returning true if it should be forwarded on,
        /// false or returning an Err otherwise.
        fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<bool, LightningError>;
@@ -919,7 +910,13 @@ impl PartialEq for OnionPacket {
        }
 }
 
-#[derive(Clone, PartialEq)]
+impl fmt::Debug for OnionPacket {
+       fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+               f.write_fmt(format_args!("OnionPacket version {} with hmac {:?}", self.version, &self.hmac[..]))
+       }
+}
+
+#[derive(Clone, Debug, PartialEq)]
 pub(crate) struct OnionErrorPacket {
        // This really should be a constant size slice, but the spec lets these things be up to 128KB?
        // (TODO) We limit it in decode to much lower...
@@ -939,18 +936,12 @@ impl fmt::Display for DecodeError {
        }
 }
 
-impl fmt::Debug for LightningError {
-       fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
-               f.write_str(self.err.as_str())
-       }
-}
-
 impl From<::std::io::Error> for DecodeError {
        fn from(e: ::std::io::Error) -> Self {
                if e.kind() == ::std::io::ErrorKind::UnexpectedEof {
                        DecodeError::ShortRead
                } else {
-                       DecodeError::Io(e)
+                       DecodeError::Io(e.kind())
                }
        }
 }
@@ -1534,14 +1525,12 @@ impl Writeable for UnsignedNodeAnnouncement {
                w.write_all(&self.rgb)?;
                self.alias.write(w)?;
 
-               let mut addrs_to_encode = self.addresses.clone();
-               addrs_to_encode.sort_by(|a, b| { a.get_id().cmp(&b.get_id()) });
                let mut addr_len = 0;
-               for addr in &addrs_to_encode {
+               for addr in self.addresses.iter() {
                        addr_len += 1 + addr.len();
                }
                (addr_len + self.excess_address_data.len() as u16).write(w)?;
-               for addr in addrs_to_encode {
+               for addr in self.addresses.iter() {
                        addr.write(w)?;
                }
                w.write_all(&self.excess_address_data[..])?;
@@ -1561,7 +1550,6 @@ impl Readable for UnsignedNodeAnnouncement {
 
                let addr_len: u16 = Readable::read(r)?;
                let mut addresses: Vec<NetAddress> = Vec::new();
-               let mut highest_addr_type = 0;
                let mut addr_readpos = 0;
                let mut excess = false;
                let mut excess_byte = 0;
@@ -1569,11 +1557,6 @@ impl Readable for UnsignedNodeAnnouncement {
                        if addr_len <= addr_readpos { break; }
                        match Readable::read(r) {
                                Ok(Ok(addr)) => {
-                                       if addr.get_id() < highest_addr_type {
-                                               // Addresses must be sorted in increasing order
-                                               return Err(DecodeError::InvalidValue);
-                                       }
-                                       highest_addr_type = addr.get_id();
                                        if addr_len < addr_readpos + 1 + addr.len() {
                                                return Err(DecodeError::BadLengthDescriptor);
                                        }
@@ -1727,7 +1710,7 @@ impl Readable for ReplyChannelRange {
                let chain_hash: BlockHash = Readable::read(r)?;
                let first_blocknum: u32 = Readable::read(r)?;
                let number_of_blocks: u32 = Readable::read(r)?;
-               let full_information: bool = Readable::read(r)?;
+               let sync_complete: bool = Readable::read(r)?;
 
                // We expect the encoding_len to always includes the 1-byte
                // encoding_type and that short_channel_ids are 8-bytes each
@@ -1755,7 +1738,7 @@ impl Readable for ReplyChannelRange {
                        chain_hash,
                        first_blocknum,
                        number_of_blocks,
-                       full_information,
+                       sync_complete,
                        short_channel_ids
                })
        }
@@ -1768,7 +1751,7 @@ impl Writeable for ReplyChannelRange {
                self.chain_hash.write(w)?;
                self.first_blocknum.write(w)?;
                self.number_of_blocks.write(w)?;
-               self.full_information.write(w)?;
+               self.sync_complete.write(w)?;
 
                encoding_len.write(w)?;
                (EncodingType::Uncompressed as u8).write(w)?;
@@ -2569,7 +2552,7 @@ mod tests {
                        chain_hash: expected_chain_hash,
                        first_blocknum: 756230,
                        number_of_blocks: 1500,
-                       full_information: true,
+                       sync_complete: true,
                        short_channel_ids: vec![0x000000000000008e, 0x0000000000003c69, 0x000000000045a6c4],
                };
 
@@ -2582,7 +2565,7 @@ mod tests {
                        assert_eq!(reply_channel_range.chain_hash, expected_chain_hash);
                        assert_eq!(reply_channel_range.first_blocknum, 756230);
                        assert_eq!(reply_channel_range.number_of_blocks, 1500);
-                       assert_eq!(reply_channel_range.full_information, true);
+                       assert_eq!(reply_channel_range.sync_complete, true);
                        assert_eq!(reply_channel_range.short_channel_ids[0], 0x000000000000008e);
                        assert_eq!(reply_channel_range.short_channel_ids[1], 0x0000000000003c69);
                        assert_eq!(reply_channel_range.short_channel_ids[2], 0x000000000045a6c4);
index 3484d8983f60fc0e9367993b5b5de3b4979dc8ff..f3d8b2e9489d5078dc79dbc42be835fa54fe56f5 100644 (file)
@@ -9,7 +9,7 @@
 
 //! The logic to build claims and bump in-flight transactions until confirmations.
 //!
-//! OnchainTxHandler objetcs are fully-part of ChannelMonitor and encapsulates all
+//! OnchainTxHandler objects are fully-part of ChannelMonitor and encapsulates all
 //! building, tracking, bumping and notifications functions.
 
 use bitcoin::blockdata::transaction::{Transaction, TxIn, TxOut, SigHashType};
@@ -24,17 +24,18 @@ use bitcoin::secp256k1;
 use ln::msgs::DecodeError;
 use ln::channelmanager::PaymentPreimage;
 use ln::chan_utils;
-use ln::chan_utils::{TxCreationKeys, HolderCommitmentTransaction};
+use ln::chan_utils::{TxCreationKeys, ChannelTransactionParameters, HolderCommitmentTransaction};
 use chain::chaininterface::{FeeEstimator, BroadcasterInterface, ConfirmationTarget, MIN_RELAY_FEE_SAT_PER_1000_WEIGHT};
 use chain::channelmonitor::{ANTI_REORG_DELAY, CLTV_SHARED_CLAIM_BUFFER, InputMaterial, ClaimRequest};
-use chain::keysinterface::ChannelKeys;
+use chain::keysinterface::{Sign, KeysInterface};
 use util::logger::Logger;
-use util::ser::{Readable, Writer, Writeable};
+use util::ser::{Readable, ReadableArgs, Writer, Writeable, VecWriter};
 use util::byte_utils;
 
 use std::collections::{HashMap, hash_map};
 use std::cmp;
 use std::ops::Deref;
+use std::mem::replace;
 
 const MAX_ALLOC_SIZE: usize = 64*1024;
 
@@ -239,19 +240,18 @@ impl Writeable for Option<Vec<Option<(usize, Signature)>>> {
 
 /// OnchainTxHandler receives claiming requests, aggregates them if it's sound, broadcast and
 /// do RBF bumping if possible.
-pub struct OnchainTxHandler<ChanSigner: ChannelKeys> {
+pub struct OnchainTxHandler<ChannelSigner: Sign> {
        destination_script: Script,
-       holder_commitment: Option<HolderCommitmentTransaction>,
+       holder_commitment: HolderCommitmentTransaction,
        // holder_htlc_sigs and prev_holder_htlc_sigs are in the order as they appear in the commitment
        // transaction outputs (hence the Option<>s inside the Vec). The first usize is the index in
-       // the set of HTLCs in the HolderCommitmentTransaction (including those which do not appear in
-       // the commitment transaction).
+       // the set of HTLCs in the HolderCommitmentTransaction.
        holder_htlc_sigs: Option<Vec<Option<(usize, Signature)>>>,
        prev_holder_commitment: Option<HolderCommitmentTransaction>,
        prev_holder_htlc_sigs: Option<Vec<Option<(usize, Signature)>>>,
-       on_holder_tx_csv: u16,
 
-       key_storage: ChanSigner,
+       signer: ChannelSigner,
+       pub(crate) channel_transaction_parameters: ChannelTransactionParameters,
 
        // Used to track claiming requests. If claim tx doesn't confirm before height timer expiration we need to bump
        // it (RBF or CPFP). If an input has been part of an aggregate tx at first claim try, we need to keep it within
@@ -287,7 +287,7 @@ pub struct OnchainTxHandler<ChanSigner: ChannelKeys> {
        secp_ctx: Secp256k1<secp256k1::All>,
 }
 
-impl<ChanSigner: ChannelKeys + Writeable> OnchainTxHandler<ChanSigner> {
+impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
        pub(crate) fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
                self.destination_script.write(writer)?;
                self.holder_commitment.write(writer)?;
@@ -295,9 +295,14 @@ impl<ChanSigner: ChannelKeys + Writeable> OnchainTxHandler<ChanSigner> {
                self.prev_holder_commitment.write(writer)?;
                self.prev_holder_htlc_sigs.write(writer)?;
 
-               self.on_holder_tx_csv.write(writer)?;
+               self.channel_transaction_parameters.write(writer)?;
 
-               self.key_storage.write(writer)?;
+               let mut key_data = VecWriter(Vec::new());
+               self.signer.write(&mut key_data)?;
+               assert!(key_data.0.len() < std::usize::MAX);
+               assert!(key_data.0.len() < std::u32::MAX as usize);
+               (key_data.0.len() as u32).write(writer)?;
+               writer.write_all(&key_data.0[..])?;
 
                writer.write_all(&byte_utils::be64_to_array(self.pending_claim_requests.len() as u64))?;
                for (ref ancestor_claim_txid, claim_tx_data) in self.pending_claim_requests.iter() {
@@ -335,8 +340,8 @@ impl<ChanSigner: ChannelKeys + Writeable> OnchainTxHandler<ChanSigner> {
        }
 }
 
-impl<ChanSigner: ChannelKeys + Readable> Readable for OnchainTxHandler<ChanSigner> {
-       fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
+impl<'a, K: KeysInterface> ReadableArgs<&'a K> for OnchainTxHandler<K::Signer> {
+       fn read<R: ::std::io::Read>(reader: &mut R, keys_manager: &'a K) -> Result<Self, DecodeError> {
                let destination_script = Readable::read(reader)?;
 
                let holder_commitment = Readable::read(reader)?;
@@ -344,9 +349,18 @@ impl<ChanSigner: ChannelKeys + Readable> Readable for OnchainTxHandler<ChanSigne
                let prev_holder_commitment = Readable::read(reader)?;
                let prev_holder_htlc_sigs = Readable::read(reader)?;
 
-               let on_holder_tx_csv = Readable::read(reader)?;
+               let channel_parameters = Readable::read(reader)?;
 
-               let key_storage = Readable::read(reader)?;
+               let keys_len: u32 = Readable::read(reader)?;
+               let mut keys_data = Vec::with_capacity(cmp::min(keys_len as usize, MAX_ALLOC_SIZE));
+               while keys_data.len() != keys_len as usize {
+                       // Read 1KB at a time to avoid accidentally allocating 4GB on corrupted channel keys
+                       let mut data = [0; 1024];
+                       let read_slice = &mut data[0..cmp::min(1024, keys_len as usize - keys_data.len())];
+                       reader.read_exact(read_slice)?;
+                       keys_data.extend_from_slice(read_slice);
+               }
+               let signer = keys_manager.read_chan_signer(&keys_data)?;
 
                let pending_claim_requests_len: u64 = Readable::read(reader)?;
                let mut pending_claim_requests = HashMap::with_capacity(cmp::min(pending_claim_requests_len as usize, MAX_ALLOC_SIZE / 128));
@@ -392,42 +406,42 @@ impl<ChanSigner: ChannelKeys + Readable> Readable for OnchainTxHandler<ChanSigne
                }
                let latest_height = Readable::read(reader)?;
 
+               let mut secp_ctx = Secp256k1::new();
+               secp_ctx.seeded_randomize(&keys_manager.get_secure_random_bytes());
+
                Ok(OnchainTxHandler {
                        destination_script,
                        holder_commitment,
                        holder_htlc_sigs,
                        prev_holder_commitment,
                        prev_holder_htlc_sigs,
-                       on_holder_tx_csv,
-                       key_storage,
+                       signer,
+                       channel_transaction_parameters: channel_parameters,
                        claimable_outpoints,
                        pending_claim_requests,
                        onchain_events_waiting_threshold_conf,
                        latest_height,
-                       secp_ctx: Secp256k1::new(),
+                       secp_ctx,
                })
        }
 }
 
-impl<ChanSigner: ChannelKeys> OnchainTxHandler<ChanSigner> {
-       pub(crate) fn new(destination_script: Script, keys: ChanSigner, on_holder_tx_csv: u16) -> Self {
-
-               let key_storage = keys;
-
+impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
+       pub(crate) fn new(destination_script: Script, signer: ChannelSigner, channel_parameters: ChannelTransactionParameters, holder_commitment: HolderCommitmentTransaction, secp_ctx: Secp256k1<secp256k1::All>) -> Self {
                OnchainTxHandler {
                        destination_script,
-                       holder_commitment: None,
+                       holder_commitment,
                        holder_htlc_sigs: None,
                        prev_holder_commitment: None,
                        prev_holder_htlc_sigs: None,
-                       on_holder_tx_csv,
-                       key_storage,
+                       signer,
+                       channel_transaction_parameters: channel_parameters,
                        pending_claim_requests: HashMap::new(),
                        claimable_outpoints: HashMap::new(),
                        onchain_events_waiting_threshold_conf: HashMap::new(),
                        latest_height: 0,
 
-                       secp_ctx: Secp256k1::new(),
+                       secp_ctx,
                }
        }
 
@@ -477,6 +491,8 @@ impl<ChanSigner: ChannelKeys> OnchainTxHandler<ChanSigner> {
 
        /// Lightning security model (i.e being able to redeem/timeout HTLC or penalize coutnerparty onchain) lays on the assumption of claim transactions getting confirmed before timelock expiration
        /// (CSV or CLTV following cases). In case of high-fee spikes, claim tx may stuck in the mempool, so you need to bump its feerate quickly using Replace-By-Fee or Child-Pay-For-Parent.
+       /// Panics if there are signing errors, because signing operations in reaction to on-chain events
+       /// are not expected to fail, and if they do, we may lose funds.
        fn generate_claim_tx<F: Deref, L: Deref>(&mut self, height: u32, cached_claim_datas: &ClaimTxBumpMaterial, fee_estimator: &F, logger: &L) -> Option<(Option<u32>, u32, Transaction)>
                where F::Target: FeeEstimator,
                                        L::Target: Logger,
@@ -589,45 +605,42 @@ impl<ChanSigner: ChannelKeys> OnchainTxHandler<ChanSigner> {
                        for (i, (outp, per_outp_material)) in cached_claim_datas.per_input_material.iter().enumerate() {
                                match per_outp_material {
                                        &InputMaterial::Revoked { ref per_commitment_point, ref counterparty_delayed_payment_base_key, ref counterparty_htlc_base_key, ref per_commitment_key, ref input_descriptor, ref amount, ref htlc, ref on_counterparty_tx_csv } => {
-                                               if let Ok(chan_keys) = TxCreationKeys::derive_new(&self.secp_ctx, &per_commitment_point, counterparty_delayed_payment_base_key, counterparty_htlc_base_key, &self.key_storage.pubkeys().revocation_basepoint, &self.key_storage.pubkeys().htlc_basepoint) {
+                                               if let Ok(tx_keys) = TxCreationKeys::derive_new(&self.secp_ctx, &per_commitment_point, counterparty_delayed_payment_base_key, counterparty_htlc_base_key, &self.signer.pubkeys().revocation_basepoint, &self.signer.pubkeys().htlc_basepoint) {
 
                                                        let witness_script = if let Some(ref htlc) = *htlc {
-                                                               chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &chan_keys.broadcaster_htlc_key, &chan_keys.countersignatory_htlc_key, &chan_keys.revocation_key)
+                                                               chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &tx_keys.broadcaster_htlc_key, &tx_keys.countersignatory_htlc_key, &tx_keys.revocation_key)
                                                        } else {
-                                                               chan_utils::get_revokeable_redeemscript(&chan_keys.revocation_key, *on_counterparty_tx_csv, &chan_keys.broadcaster_delayed_payment_key)
+                                                               chan_utils::get_revokeable_redeemscript(&tx_keys.revocation_key, *on_counterparty_tx_csv, &tx_keys.broadcaster_delayed_payment_key)
                                                        };
 
-                                                       if let Ok(sig) = self.key_storage.sign_justice_transaction(&bumped_tx, i, *amount, &per_commitment_key, htlc, &self.secp_ctx) {
-                                                               bumped_tx.input[i].witness.push(sig.serialize_der().to_vec());
-                                                               bumped_tx.input[i].witness[0].push(SigHashType::All as u8);
-                                                               if htlc.is_some() {
-                                                                       bumped_tx.input[i].witness.push(chan_keys.revocation_key.clone().serialize().to_vec());
-                                                               } else {
-                                                                       bumped_tx.input[i].witness.push(vec!(1));
-                                                               }
-                                                               bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
-                                                       } else { return None; }
-                                                       //TODO: panic ?
+                                                       let sig = self.signer.sign_justice_transaction(&bumped_tx, i, *amount, &per_commitment_key, htlc, &self.secp_ctx).expect("sign justice tx");
+                                                       bumped_tx.input[i].witness.push(sig.serialize_der().to_vec());
+                                                       bumped_tx.input[i].witness[0].push(SigHashType::All as u8);
+                                                       if htlc.is_some() {
+                                                               bumped_tx.input[i].witness.push(tx_keys.revocation_key.clone().serialize().to_vec());
+                                                       } else {
+                                                               bumped_tx.input[i].witness.push(vec!(1));
+                                                       }
+                                                       bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
 
                                                        log_trace!(logger, "Going to broadcast Penalty Transaction {} claiming revoked {} output {} from {} with new feerate {}...", bumped_tx.txid(), if *input_descriptor == InputDescriptors::RevokedOutput { "to_holder" } else if *input_descriptor == InputDescriptors::RevokedOfferedHTLC { "offered" } else if *input_descriptor == InputDescriptors::RevokedReceivedHTLC { "received" } else { "" }, outp.vout, outp.txid, new_feerate);
                                                }
                                        },
                                        &InputMaterial::CounterpartyHTLC { ref per_commitment_point, ref counterparty_delayed_payment_base_key, ref counterparty_htlc_base_key, ref preimage, ref htlc } => {
-                                               if let Ok(chan_keys) = TxCreationKeys::derive_new(&self.secp_ctx, &per_commitment_point, counterparty_delayed_payment_base_key, counterparty_htlc_base_key, &self.key_storage.pubkeys().revocation_basepoint, &self.key_storage.pubkeys().htlc_basepoint) {
-                                                       let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &chan_keys.broadcaster_htlc_key, &chan_keys.countersignatory_htlc_key, &chan_keys.revocation_key);
+                                               if let Ok(tx_keys) = TxCreationKeys::derive_new(&self.secp_ctx, &per_commitment_point, counterparty_delayed_payment_base_key, counterparty_htlc_base_key, &self.signer.pubkeys().revocation_basepoint, &self.signer.pubkeys().htlc_basepoint) {
+                                                       let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &tx_keys.broadcaster_htlc_key, &tx_keys.countersignatory_htlc_key, &tx_keys.revocation_key);
 
                                                        if !preimage.is_some() { bumped_tx.lock_time = htlc.cltv_expiry }; // Right now we don't aggregate time-locked transaction, if we do we should set lock_time before to avoid breaking hash computation
-                                                       if let Ok(sig) = self.key_storage.sign_counterparty_htlc_transaction(&bumped_tx, i, &htlc.amount_msat / 1000, &per_commitment_point, htlc, &self.secp_ctx) {
-                                                               bumped_tx.input[i].witness.push(sig.serialize_der().to_vec());
-                                                               bumped_tx.input[i].witness[0].push(SigHashType::All as u8);
-                                                               if let &Some(preimage) = preimage {
-                                                                       bumped_tx.input[i].witness.push(preimage.0.to_vec());
-                                                               } else {
-                                                                       // Due to BIP146 (MINIMALIF) this must be a zero-length element to relay.
-                                                                       bumped_tx.input[i].witness.push(vec![]);
-                                                               }
-                                                               bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
+                                                       let sig = self.signer.sign_counterparty_htlc_transaction(&bumped_tx, i, &htlc.amount_msat / 1000, &per_commitment_point, htlc, &self.secp_ctx).expect("sign counterparty HTLC tx");
+                                                       bumped_tx.input[i].witness.push(sig.serialize_der().to_vec());
+                                                       bumped_tx.input[i].witness[0].push(SigHashType::All as u8);
+                                                       if let &Some(preimage) = preimage {
+                                                               bumped_tx.input[i].witness.push(preimage.0.to_vec());
+                                                       } else {
+                                                               // Due to BIP146 (MINIMALIF) this must be a zero-length element to relay.
+                                                               bumped_tx.input[i].witness.push(vec![]);
                                                        }
+                                                       bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
                                                        log_trace!(logger, "Going to broadcast Claim Transaction {} claiming counterparty {} htlc output {} from {} with new feerate {}...", bumped_tx.txid(), if preimage.is_some() { "offered" } else { "received" }, outp.vout, outp.txid, new_feerate);
                                                }
                                        },
@@ -651,10 +664,10 @@ impl<ChanSigner: ChannelKeys> OnchainTxHandler<ChanSigner> {
                                                return None;
                                        },
                                        &InputMaterial::Funding { ref funding_redeemscript } => {
-                                               let signed_tx = self.get_fully_signed_holder_tx(funding_redeemscript).unwrap();
+                                               let signed_tx = self.get_fully_signed_holder_tx(funding_redeemscript);
                                                // Timer set to $NEVER given we can't bump tx without anchor outputs
                                                log_trace!(logger, "Going to broadcast Holder Transaction {} claiming funding output {} from {}...", signed_tx.txid(), outp.vout, outp.txid);
-                                               return Some((None, self.holder_commitment.as_ref().unwrap().feerate_per_kw, signed_tx));
+                                               return Some((None, self.holder_commitment.feerate_per_kw(), signed_tx));
                                        }
                                        _ => unreachable!()
                                }
@@ -892,92 +905,85 @@ impl<ChanSigner: ChannelKeys> OnchainTxHandler<ChanSigner> {
        }
 
        pub(crate) fn provide_latest_holder_tx(&mut self, tx: HolderCommitmentTransaction) {
-               self.prev_holder_commitment = self.holder_commitment.take();
-               self.holder_commitment = Some(tx);
+               self.prev_holder_commitment = Some(replace(&mut self.holder_commitment, tx));
+               self.holder_htlc_sigs = None;
        }
 
+       // Normally holder HTLCs are signed at the same time as the holder commitment tx.  However,
+       // in some configurations, the holder commitment tx has been signed and broadcast by a
+       // ChannelMonitor replica, so we handle that case here.
        fn sign_latest_holder_htlcs(&mut self) {
-               if let Some(ref holder_commitment) = self.holder_commitment {
-                       if let Ok(sigs) = self.key_storage.sign_holder_commitment_htlc_transactions(holder_commitment, &self.secp_ctx) {
-                               self.holder_htlc_sigs = Some(Vec::new());
-                               let ret = self.holder_htlc_sigs.as_mut().unwrap();
-                               for (htlc_idx, (holder_sig, &(ref htlc, _))) in sigs.iter().zip(holder_commitment.per_htlc.iter()).enumerate() {
-                                       if let Some(tx_idx) = htlc.transaction_output_index {
-                                               if ret.len() <= tx_idx as usize { ret.resize(tx_idx as usize + 1, None); }
-                                               ret[tx_idx as usize] = Some((htlc_idx, holder_sig.expect("Did not receive a signature for a non-dust HTLC")));
-                                       } else {
-                                               assert!(holder_sig.is_none(), "Received a signature for a dust HTLC");
-                                       }
-                               }
-                       }
+               if self.holder_htlc_sigs.is_none() {
+                       let (_sig, sigs) = self.signer.sign_holder_commitment_and_htlcs(&self.holder_commitment, &self.secp_ctx).expect("sign holder commitment");
+                       self.holder_htlc_sigs = Some(Self::extract_holder_sigs(&self.holder_commitment, sigs));
                }
        }
+
+       // Normally only the latest commitment tx and HTLCs need to be signed.  However, in some
+       // configurations we may have updated our holder commitment but a replica of the ChannelMonitor
+       // broadcast the previous one before we sync with it.  We handle that case here.
        fn sign_prev_holder_htlcs(&mut self) {
-               if let Some(ref holder_commitment) = self.prev_holder_commitment {
-                       if let Ok(sigs) = self.key_storage.sign_holder_commitment_htlc_transactions(holder_commitment, &self.secp_ctx) {
-                               self.prev_holder_htlc_sigs = Some(Vec::new());
-                               let ret = self.prev_holder_htlc_sigs.as_mut().unwrap();
-                               for (htlc_idx, (holder_sig, &(ref htlc, _))) in sigs.iter().zip(holder_commitment.per_htlc.iter()).enumerate() {
-                                       if let Some(tx_idx) = htlc.transaction_output_index {
-                                               if ret.len() <= tx_idx as usize { ret.resize(tx_idx as usize + 1, None); }
-                                               ret[tx_idx as usize] = Some((htlc_idx, holder_sig.expect("Did not receive a signature for a non-dust HTLC")));
-                                       } else {
-                                               assert!(holder_sig.is_none(), "Received a signature for a dust HTLC");
-                                       }
-                               }
+               if self.prev_holder_htlc_sigs.is_none() {
+                       if let Some(ref holder_commitment) = self.prev_holder_commitment {
+                               let (_sig, sigs) = self.signer.sign_holder_commitment_and_htlcs(holder_commitment, &self.secp_ctx).expect("sign previous holder commitment");
+                               self.prev_holder_htlc_sigs = Some(Self::extract_holder_sigs(holder_commitment, sigs));
                        }
                }
        }
 
-       //TODO: getting lastest holder transactions should be infaillible and result in us "force-closing the channel", but we may
+       fn extract_holder_sigs(holder_commitment: &HolderCommitmentTransaction, sigs: Vec<Signature>) -> Vec<Option<(usize, Signature)>> {
+               let mut ret = Vec::new();
+               for (htlc_idx, (holder_sig, htlc)) in sigs.iter().zip(holder_commitment.htlcs().iter()).enumerate() {
+                       let tx_idx = htlc.transaction_output_index.unwrap();
+                       if ret.len() <= tx_idx as usize { ret.resize(tx_idx as usize + 1, None); }
+                       ret[tx_idx as usize] = Some((htlc_idx, holder_sig.clone()));
+               }
+               ret
+       }
+
+       //TODO: getting lastest holder transactions should be infallible and result in us "force-closing the channel", but we may
        // have empty holder commitment transaction if a ChannelMonitor is asked to force-close just after Channel::get_outbound_funding_created,
        // before providing a initial commitment transaction. For outbound channel, init ChannelMonitor at Channel::funding_signed, there is nothing
        // to monitor before.
-       pub(crate) fn get_fully_signed_holder_tx(&mut self, funding_redeemscript: &Script) -> Option<Transaction> {
-               if let Some(ref mut holder_commitment) = self.holder_commitment {
-                       match self.key_storage.sign_holder_commitment(holder_commitment, &self.secp_ctx) {
-                               Ok(sig) => Some(holder_commitment.add_holder_sig(funding_redeemscript, sig)),
-                               Err(_) => return None,
-                       }
-               } else {
-                       None
-               }
+       pub(crate) fn get_fully_signed_holder_tx(&mut self, funding_redeemscript: &Script) -> Transaction {
+               let (sig, htlc_sigs) = self.signer.sign_holder_commitment_and_htlcs(&self.holder_commitment, &self.secp_ctx).expect("signing holder commitment");
+               self.holder_htlc_sigs = Some(Self::extract_holder_sigs(&self.holder_commitment, htlc_sigs));
+               self.holder_commitment.add_holder_sig(funding_redeemscript, sig)
        }
 
        #[cfg(any(test, feature="unsafe_revoked_tx_signing"))]
-       pub(crate) fn get_fully_signed_copy_holder_tx(&mut self, funding_redeemscript: &Script) -> Option<Transaction> {
-               if let Some(ref mut holder_commitment) = self.holder_commitment {
-                       let holder_commitment = holder_commitment.clone();
-                       match self.key_storage.sign_holder_commitment(&holder_commitment, &self.secp_ctx) {
-                               Ok(sig) => Some(holder_commitment.add_holder_sig(funding_redeemscript, sig)),
-                               Err(_) => return None,
-                       }
-               } else {
-                       None
-               }
+       pub(crate) fn get_fully_signed_copy_holder_tx(&mut self, funding_redeemscript: &Script) -> Transaction {
+               let (sig, htlc_sigs) = self.signer.unsafe_sign_holder_commitment_and_htlcs(&self.holder_commitment, &self.secp_ctx).expect("sign holder commitment");
+               self.holder_htlc_sigs = Some(Self::extract_holder_sigs(&self.holder_commitment, htlc_sigs));
+               self.holder_commitment.add_holder_sig(funding_redeemscript, sig)
        }
 
        pub(crate) fn get_fully_signed_htlc_tx(&mut self, outp: &::bitcoin::OutPoint, preimage: &Option<PaymentPreimage>) -> Option<Transaction> {
                let mut htlc_tx = None;
-               if self.holder_commitment.is_some() {
-                       let commitment_txid = self.holder_commitment.as_ref().unwrap().txid();
-                       if commitment_txid == outp.txid {
-                               self.sign_latest_holder_htlcs();
-                               if let &Some(ref htlc_sigs) = &self.holder_htlc_sigs {
-                                       let &(ref htlc_idx, ref htlc_sig) = htlc_sigs[outp.vout as usize].as_ref().unwrap();
-                                       htlc_tx = Some(self.holder_commitment.as_ref().unwrap()
-                                               .get_signed_htlc_tx(*htlc_idx, htlc_sig, preimage, self.on_holder_tx_csv));
-                               }
+               let commitment_txid = self.holder_commitment.trust().txid();
+               // Check if the HTLC spends from the current holder commitment
+               if commitment_txid == outp.txid {
+                       self.sign_latest_holder_htlcs();
+                       if let &Some(ref htlc_sigs) = &self.holder_htlc_sigs {
+                               let &(ref htlc_idx, ref htlc_sig) = htlc_sigs[outp.vout as usize].as_ref().unwrap();
+                               let trusted_tx = self.holder_commitment.trust();
+                               let counterparty_htlc_sig = self.holder_commitment.counterparty_htlc_sigs[*htlc_idx];
+                               htlc_tx = Some(trusted_tx
+                                       .get_signed_htlc_tx(&self.channel_transaction_parameters.as_holder_broadcastable(), *htlc_idx, &counterparty_htlc_sig, htlc_sig, preimage));
                        }
                }
-               if self.prev_holder_commitment.is_some() {
-                       let commitment_txid = self.prev_holder_commitment.as_ref().unwrap().txid();
+               // If the HTLC doesn't spend the current holder commitment, check if it spends the previous one
+               if htlc_tx.is_none() && self.prev_holder_commitment.is_some() {
+                       let commitment_txid = self.prev_holder_commitment.as_ref().unwrap().trust().txid();
                        if commitment_txid == outp.txid {
                                self.sign_prev_holder_htlcs();
                                if let &Some(ref htlc_sigs) = &self.prev_holder_htlc_sigs {
                                        let &(ref htlc_idx, ref htlc_sig) = htlc_sigs[outp.vout as usize].as_ref().unwrap();
-                                       htlc_tx = Some(self.prev_holder_commitment.as_ref().unwrap()
-                                               .get_signed_htlc_tx(*htlc_idx, htlc_sig, preimage, self.on_holder_tx_csv));
+                                       let holder_commitment = self.prev_holder_commitment.as_ref().unwrap();
+                                       let trusted_tx = holder_commitment.trust();
+                                       let counterparty_htlc_sig = holder_commitment.counterparty_htlc_sigs[*htlc_idx];
+                                       htlc_tx = Some(trusted_tx
+                                               .get_signed_htlc_tx(&self.channel_transaction_parameters.as_holder_broadcastable(), *htlc_idx, &counterparty_htlc_sig, htlc_sig, preimage));
                                }
                        }
                }
index bf2709cded67badeb799e261e66c324bbf1c3c46..551db24e9d7786f0a85816c00de8736dec8bcf6b 100644 (file)
@@ -219,7 +219,7 @@ impl msgs::ChannelUpdate {
                use bitcoin::secp256k1::ffi::Signature as FFISignature;
                use bitcoin::secp256k1::Signature;
                msgs::ChannelUpdate {
-                       signature: Signature::from(FFISignature::new()),
+                       signature: Signature::from(unsafe { FFISignature::new() }),
                        contents: msgs::UnsignedChannelUpdate {
                                chain_hash: BlockHash::hash(&vec![0u8][..]),
                                short_channel_id: 0,
index 890df356cc0e5eb1314ff2a17358364cabf9a265..d37476327ba02750a34f2fa0e8a8bce0dc62a167 100644 (file)
@@ -33,22 +33,133 @@ use routing::network_graph::NetGraphMsgHandler;
 use std::collections::{HashMap,hash_map,HashSet,LinkedList};
 use std::sync::{Arc, Mutex};
 use std::sync::atomic::{AtomicUsize, Ordering};
-use std::{cmp,error,hash,fmt};
+use std::{cmp, error, hash, fmt, mem};
 use std::ops::Deref;
 
 use bitcoin::hashes::sha256::Hash as Sha256;
 use bitcoin::hashes::sha256::HashEngine as Sha256Engine;
 use bitcoin::hashes::{HashEngine, Hash};
 
+/// A dummy struct which implements `RoutingMessageHandler` without storing any routing information
+/// or doing any processing. You can provide one of these as the route_handler in a MessageHandler.
+struct IgnoringMessageHandler{}
+impl MessageSendEventsProvider for IgnoringMessageHandler {
+       fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> { Vec::new() }
+}
+impl RoutingMessageHandler for IgnoringMessageHandler {
+       fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> { Ok(false) }
+       fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> { Ok(false) }
+       fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> { Ok(false) }
+       fn handle_htlc_fail_channel_update(&self, _update: &msgs::HTLCFailChannelUpdate) {}
+       fn get_next_channel_announcements(&self, _starting_point: u64, _batch_amount: u8) ->
+               Vec<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> { Vec::new() }
+       fn get_next_node_announcements(&self, _starting_point: Option<&PublicKey>, _batch_amount: u8) -> Vec<msgs::NodeAnnouncement> { Vec::new() }
+       fn sync_routing_table(&self, _their_node_id: &PublicKey, _init: &msgs::Init) {}
+       fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), LightningError> { Ok(()) }
+       fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), LightningError> { Ok(()) }
+       fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), LightningError> { Ok(()) }
+       fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), LightningError> { Ok(()) }
+}
+impl Deref for IgnoringMessageHandler {
+       type Target = IgnoringMessageHandler;
+       fn deref(&self) -> &Self { self }
+}
+
+/// A dummy struct which implements `ChannelMessageHandler` without having any channels.
+/// You can provide one of these as the route_handler in a MessageHandler.
+struct ErroringMessageHandler {
+       message_queue: Mutex<Vec<MessageSendEvent>>
+}
+impl ErroringMessageHandler {
+       /// Constructs a new ErroringMessageHandler
+       pub fn new() -> Self {
+               Self { message_queue: Mutex::new(Vec::new()) }
+       }
+       fn push_error(&self, node_id: &PublicKey, channel_id: [u8; 32]) {
+               self.message_queue.lock().unwrap().push(MessageSendEvent::HandleError {
+                       action: msgs::ErrorAction::SendErrorMessage {
+                               msg: msgs::ErrorMessage { channel_id, data: "We do not support channel messages, sorry.".to_owned() },
+                       },
+                       node_id: node_id.clone(),
+               });
+       }
+}
+impl MessageSendEventsProvider for ErroringMessageHandler {
+       fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
+               let mut res = Vec::new();
+               mem::swap(&mut res, &mut self.message_queue.lock().unwrap());
+               res
+       }
+}
+impl ChannelMessageHandler for ErroringMessageHandler {
+       // Any messages which are related to a specific channel generate an error message to let the
+       // peer know we don't care about channels.
+       fn handle_open_channel(&self, their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::OpenChannel) {
+               ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
+       }
+       fn handle_accept_channel(&self, their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::AcceptChannel) {
+               ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
+       }
+       fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
+               ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
+       }
+       fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
+               ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
+       }
+       fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) {
+               ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
+       }
+       fn handle_shutdown(&self, their_node_id: &PublicKey, _their_features: &InitFeatures, msg: &msgs::Shutdown) {
+               ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
+       }
+       fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
+               ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
+       }
+       fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
+               ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
+       }
+       fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
+               ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
+       }
+       fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
+               ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
+       }
+       fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
+               ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
+       }
+       fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
+               ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
+       }
+       fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
+               ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
+       }
+       fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
+               ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
+       }
+       fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
+               ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
+       }
+       fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
+               ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
+       }
+       fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {}
+       fn peer_connected(&self, _their_node_id: &PublicKey, _msg: &msgs::Init) {}
+       fn handle_error(&self, _their_node_id: &PublicKey, _msg: &msgs::ErrorMessage) {}
+}
+impl Deref for ErroringMessageHandler {
+       type Target = ErroringMessageHandler;
+       fn deref(&self) -> &Self { self }
+}
+
 /// Provides references to trait impls which handle different types of messages.
 pub struct MessageHandler<CM: Deref, RM: Deref> where
                CM::Target: ChannelMessageHandler,
                RM::Target: RoutingMessageHandler {
        /// A message handler which handles messages specific to channels. Usually this is just a
-       /// ChannelManager object.
+       /// ChannelManager object or a ErroringMessageHandler.
        pub chan_handler: CM,
        /// A message handler which handles messages updating our knowledge of the network channel
-       /// graph. Usually this is just a NetGraphMsgHandlerMonitor object.
+       /// graph. Usually this is just a NetGraphMsgHandlerMonitor object or an IgnoringMessageHandler.
        pub route_handler: RM,
 }
 
@@ -88,10 +199,9 @@ pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone {
 }
 
 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
-/// generate no further read_event/write_buffer_space_avail calls for the descriptor, only
-/// triggering a single socket_disconnected call (unless it was provided in response to a
-/// new_*_connection event, in which case no such socket_disconnected() must be called and the
-/// socket silently disconencted).
+/// generate no further read_event/write_buffer_space_avail/socket_disconnected calls for the
+/// descriptor.
+#[derive(Clone)]
 pub struct PeerHandleError {
        /// Used to indicate that we probably can't make any future connections to this peer, implying
        /// we should go ahead and force-close any channels we have with it.
@@ -183,7 +293,7 @@ fn _check_usize_is_32_or_64() {
 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
 /// SimpleRefPeerManager is the more appropriate type. Defining these type aliases prevents
 /// issues such as overly long function definitions.
-pub type SimpleArcPeerManager<SD, M, T, F, C, L> = Arc<PeerManager<SD, SimpleArcChannelManager<M, T, F, L>, Arc<NetGraphMsgHandler<Arc<C>, Arc<L>>>, Arc<L>>>;
+pub type SimpleArcPeerManager<SD, M, T, F, C, L> = PeerManager<SD, Arc<SimpleArcChannelManager<M, T, F, L>>, Arc<NetGraphMsgHandler<Arc<C>, Arc<L>>>, Arc<L>>;
 
 /// SimpleRefPeerManager is a type alias for a PeerManager reference, and is the reference
 /// counterpart to the SimpleArcPeerManager type alias. Use this type by default when you don't
@@ -243,6 +353,44 @@ macro_rules! encode_msg {
        }}
 }
 
+impl<Descriptor: SocketDescriptor, CM: Deref, L: Deref> PeerManager<Descriptor, CM, IgnoringMessageHandler, L> where
+               CM::Target: ChannelMessageHandler,
+               L::Target: Logger {
+       /// Constructs a new PeerManager with the given ChannelMessageHandler. No routing message
+       /// handler is used and network graph messages are ignored.
+       ///
+       /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
+       /// cryptographically secure random bytes.
+       ///
+       /// (C-not exported) as we can't export a PeerManager with a dummy route handler
+       pub fn new_channel_only(channel_message_handler: CM, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: L) -> Self {
+               Self::new(MessageHandler {
+                       chan_handler: channel_message_handler,
+                       route_handler: IgnoringMessageHandler{},
+               }, our_node_secret, ephemeral_random_data, logger)
+       }
+}
+
+impl<Descriptor: SocketDescriptor, RM: Deref, L: Deref> PeerManager<Descriptor, ErroringMessageHandler, RM, L> where
+               RM::Target: RoutingMessageHandler,
+               L::Target: Logger {
+       /// Constructs a new PeerManager with the given RoutingMessageHandler. No channel message
+       /// handler is used and messages related to channels will be ignored (or generate error
+       /// messages). Note that some other lightning implementations time-out connections after some
+       /// time if no channel is built with the peer.
+       ///
+       /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
+       /// cryptographically secure random bytes.
+       ///
+       /// (C-not exported) as we can't export a PeerManager with a dummy channel handler
+       pub fn new_routing_only(routing_message_handler: RM, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: L) -> Self {
+               Self::new(MessageHandler {
+                       chan_handler: ErroringMessageHandler::new(),
+                       route_handler: routing_message_handler,
+               }, our_node_secret, ephemeral_random_data, logger)
+       }
+}
+
 /// Manages and reacts to connection events. You probably want to use file descriptors as PeerIds.
 /// PeerIds may repeat, but only after socket_disconnected() has been called.
 impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref> PeerManager<Descriptor, CM, RM, L> where
@@ -678,11 +826,7 @@ impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref> PeerManager<D
                        // Setup and Control messages:
                        wire::Message::Init(msg) => {
                                if msg.features.requires_unknown_bits() {
-                                       log_info!(self.logger, "Peer global features required unknown version bits");
-                                       return Err(PeerHandleError{ no_connection_possible: true }.into());
-                               }
-                               if msg.features.requires_unknown_bits() {
-                                       log_info!(self.logger, "Peer local features required unknown version bits");
+                                       log_info!(self.logger, "Peer features required unknown version bits");
                                        return Err(PeerHandleError{ no_connection_possible: true }.into());
                                }
                                if peer.their_features.is_some() {
@@ -768,7 +912,7 @@ impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref> PeerManager<D
                        },
 
                        wire::Message::Shutdown(msg) => {
-                               self.message_handler.chan_handler.handle_shutdown(&peer.their_node_id.unwrap(), &msg);
+                               self.message_handler.chan_handler.handle_shutdown(&peer.their_node_id.unwrap(), peer.their_features.as_ref().unwrap(), &msg);
                        },
                        wire::Message::ClosingSigned(msg) => {
                                self.message_handler.chan_handler.handle_closing_signed(&peer.their_node_id.unwrap(), &msg);
@@ -1179,6 +1323,24 @@ impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref> PeerManager<D
                };
        }
 
+       /// Disconnect a peer given its node id.
+       ///
+       /// Set no_connection_possible to true to prevent any further connection with this peer,
+       /// force-closing any channels we have with it.
+       ///
+       /// If a peer is connected, this will call `disconnect_socket` on the descriptor for the peer,
+       /// so be careful about reentrancy issues.
+       pub fn disconnect_by_node_id(&self, node_id: PublicKey, no_connection_possible: bool) {
+               let mut peers_lock = self.peers.lock().unwrap();
+               if let Some(mut descriptor) = peers_lock.node_id_to_descriptor.remove(&node_id) {
+                       log_trace!(self.logger, "Disconnecting peer with id {} due to client request", node_id);
+                       peers_lock.peers.remove(&descriptor);
+                       peers_lock.peers_needing_send.remove(&descriptor);
+                       self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
+                       descriptor.disconnect_socket();
+               }
+       }
+
        /// This function should be called roughly once every 30 seconds.
        /// It will send pings to each peer and disconnect those which did not respond to the last round of pings.
 
index 6856bb16bcfc4bbb221542d92967f7e32fecfa69..13dc662642c62ccd8aabc9affd520a9ad927bb2a 100644 (file)
@@ -29,7 +29,7 @@ use ln::msgs::{QueryChannelRange, ReplyChannelRange, QueryShortChannelIds, Reply
 use ln::msgs;
 use util::ser::{Writeable, Readable, Writer};
 use util::logger::Logger;
-use util::events;
+use util::events::{MessageSendEvent, MessageSendEventsProvider};
 
 use std::{cmp, fmt};
 use std::sync::{RwLock, RwLockReadGuard};
@@ -40,8 +40,12 @@ use std::collections::btree_map::Entry as BtreeEntry;
 use std::ops::Deref;
 use bitcoin::hashes::hex::ToHex;
 
+/// The maximum number of extra bytes which we do not understand in a gossip message before we will
+/// refuse to relay the message.
+const MAX_EXCESS_BYTES_FOR_RELAY: usize = 1024;
+
 /// Represents the network as nodes and channels between them
-#[derive(PartialEq)]
+#[derive(Clone, PartialEq)]
 pub struct NetworkGraph {
        genesis_hash: BlockHash,
        channels: BTreeMap<u64, ChannelInfo>,
@@ -64,7 +68,7 @@ pub struct NetGraphMsgHandler<C: Deref, L: Deref> where C::Target: chain::Access
        pub network_graph: RwLock<NetworkGraph>,
        chain_access: Option<C>,
        full_syncs_requested: AtomicUsize,
-       pending_events: Mutex<Vec<events::MessageSendEvent>>,
+       pending_events: Mutex<Vec<MessageSendEvent>>,
        logger: L,
 }
 
@@ -146,13 +150,15 @@ macro_rules! secp_verify_sig {
 impl<C: Deref + Sync + Send, L: Deref + Sync + Send> RoutingMessageHandler for NetGraphMsgHandler<C, L> where C::Target: chain::Access, L::Target: Logger {
        fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
                self.network_graph.write().unwrap().update_node_from_announcement(msg, &self.secp_ctx)?;
-               Ok(msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty())
+               Ok(msg.contents.excess_data.len() <=  MAX_EXCESS_BYTES_FOR_RELAY &&
+                  msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
+                  msg.contents.excess_data.len() + msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
        }
 
        fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
                self.network_graph.write().unwrap().update_channel_from_announcement(msg, &self.chain_access, &self.secp_ctx)?;
                log_trace!(self.logger, "Added channel_announcement for {}{}", msg.contents.short_channel_id, if !msg.contents.excess_data.is_empty() { " with excess uninterpreted data!" } else { "" });
-               Ok(msg.contents.excess_data.is_empty())
+               Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
        }
 
        fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
@@ -171,7 +177,7 @@ impl<C: Deref + Sync + Send, L: Deref + Sync + Send> RoutingMessageHandler for N
 
        fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
                self.network_graph.write().unwrap().update_channel(msg, &self.secp_ctx)?;
-               Ok(msg.contents.excess_data.is_empty())
+               Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
        }
 
        fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)> {
@@ -251,7 +257,7 @@ impl<C: Deref + Sync + Send, L: Deref + Sync + Send> RoutingMessageHandler for N
                let number_of_blocks = 0xffffffff;
                log_debug!(self.logger, "Sending query_channel_range peer={}, first_blocknum={}, number_of_blocks={}", log_pubkey!(their_node_id), first_blocknum, number_of_blocks);
                let mut pending_events = self.pending_events.lock().unwrap();
-               pending_events.push(events::MessageSendEvent::SendChannelRangeQuery {
+               pending_events.push(MessageSendEvent::SendChannelRangeQuery {
                        node_id: their_node_id.clone(),
                        msg: QueryChannelRange {
                                chain_hash: self.network_graph.read().unwrap().genesis_hash,
@@ -271,22 +277,11 @@ impl<C: Deref + Sync + Send, L: Deref + Sync + Send> RoutingMessageHandler for N
        /// does not match our chain_hash will be rejected when the announcement is
        /// processed.
        fn handle_reply_channel_range(&self, their_node_id: &PublicKey, msg: ReplyChannelRange) -> Result<(), LightningError> {
-               log_debug!(self.logger, "Handling reply_channel_range peer={}, first_blocknum={}, number_of_blocks={}, full_information={}, scids={}", log_pubkey!(their_node_id), msg.first_blocknum, msg.number_of_blocks, msg.full_information, msg.short_channel_ids.len(),);
-
-               // Validate that the remote node maintains up-to-date channel
-               // information for chain_hash. Some nodes use the full_information
-               // flag to indicate multi-part messages so we must check whether
-               // we received SCIDs as well.
-               if !msg.full_information && msg.short_channel_ids.len() == 0 {
-                       return Err(LightningError {
-                               err: String::from("Received reply_channel_range with no information available"),
-                               action: ErrorAction::IgnoreError,
-                       });
-               }
+               log_debug!(self.logger, "Handling reply_channel_range peer={}, first_blocknum={}, number_of_blocks={}, sync_complete={}, scids={}", log_pubkey!(their_node_id), msg.first_blocknum, msg.number_of_blocks, msg.sync_complete, msg.short_channel_ids.len(),);
 
                log_debug!(self.logger, "Sending query_short_channel_ids peer={}, batch_size={}", log_pubkey!(their_node_id), msg.short_channel_ids.len());
                let mut pending_events = self.pending_events.lock().unwrap();
-               pending_events.push(events::MessageSendEvent::SendShortIdsQuery {
+               pending_events.push(MessageSendEvent::SendShortIdsQuery {
                        node_id: their_node_id.clone(),
                        msg: QueryShortChannelIds {
                                chain_hash: msg.chain_hash,
@@ -334,12 +329,12 @@ impl<C: Deref + Sync + Send, L: Deref + Sync + Send> RoutingMessageHandler for N
        }
 }
 
-impl<C: Deref, L: Deref> events::MessageSendEventsProvider for NetGraphMsgHandler<C, L>
+impl<C: Deref, L: Deref> MessageSendEventsProvider for NetGraphMsgHandler<C, L>
 where
        C::Target: chain::Access,
        L::Target: Logger,
 {
-       fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
+       fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
                let mut ret = Vec::new();
                let mut pending_events = self.pending_events.lock().unwrap();
                std::mem::swap(&mut ret, &mut pending_events);
@@ -347,7 +342,7 @@ where
        }
 }
 
-#[derive(PartialEq, Debug)]
+#[derive(Clone, Debug, PartialEq)]
 /// Details about one direction of a channel. Received
 /// within a channel update.
 pub struct DirectionalChannelInfo {
@@ -388,7 +383,7 @@ impl_writeable!(DirectionalChannelInfo, 0, {
        last_update_message
 });
 
-#[derive(PartialEq)]
+#[derive(Clone, Debug, PartialEq)]
 /// Details about a channel (both directions).
 /// Received within a channel announcement.
 pub struct ChannelInfo {
@@ -459,7 +454,7 @@ impl Writeable for RoutingFees {
        }
 }
 
-#[derive(PartialEq, Debug)]
+#[derive(Clone, Debug, PartialEq)]
 /// Information received in the latest node_announcement from this node.
 pub struct NodeAnnouncementInfo {
        /// Protocol features the node announced support for
@@ -525,7 +520,7 @@ impl Readable for NodeAnnouncementInfo {
        }
 }
 
-#[derive(PartialEq)]
+#[derive(Clone, Debug, PartialEq)]
 /// Details about a node in the network, known from the network announcement.
 pub struct NodeInfo {
        /// All valid channels a node has announced
@@ -698,7 +693,10 @@ impl NetworkGraph {
                                        }
                                }
 
-                               let should_relay = msg.excess_data.is_empty() && msg.excess_address_data.is_empty();
+                               let should_relay =
+                                       msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
+                                       msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
+                                       msg.excess_data.len() + msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY;
                                node.announcement_info = Some(NodeAnnouncementInfo {
                                        features: msg.features.clone(),
                                        last_update: msg.timestamp,
@@ -791,7 +789,8 @@ impl NetworkGraph {
                                node_two: msg.node_id_2.clone(),
                                two_to_one: None,
                                capacity_sats: utxo_value,
-                               announcement_message: if msg.excess_data.is_empty() { full_msg.cloned() } else { None },
+                               announcement_message: if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
+                                       { full_msg.cloned() } else { None },
                        };
 
                match self.channels.entry(msg.short_channel_id) {
@@ -920,7 +919,8 @@ impl NetworkGraph {
                                                        chan_was_enabled = false;
                                                }
 
-                                               let last_update_message = if msg.excess_data.is_empty() { full_msg.cloned() } else { None };
+                                               let last_update_message = if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
+                                                       { full_msg.cloned() } else { None };
 
                                                let updated_channel_dir_info = DirectionalChannelInfo {
                                                        enabled: chan_enabled,
@@ -1020,7 +1020,7 @@ impl NetworkGraph {
 mod tests {
        use chain;
        use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
-       use routing::network_graph::{NetGraphMsgHandler, NetworkGraph};
+       use routing::network_graph::{NetGraphMsgHandler, NetworkGraph, MAX_EXCESS_BYTES_FOR_RELAY};
        use ln::msgs::{Init, OptionalField, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
                UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate,
                ReplyChannelRange, ReplyShortChannelIdsEnd, QueryChannelRange, QueryShortChannelIds, MAX_VALUE_MSAT};
@@ -1142,7 +1142,7 @@ mod tests {
                };
 
                unsigned_announcement.timestamp += 1000;
-               unsigned_announcement.excess_data.push(1);
+               unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
                msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
                let announcement_with_data = NodeAnnouncement {
                        signature: secp_ctx.sign(&msghash, node_1_privkey),
@@ -1310,7 +1310,7 @@ mod tests {
 
                // Don't relay valid channels with excess data
                unsigned_announcement.short_channel_id += 1;
-               unsigned_announcement.excess_data.push(1);
+               unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
                msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
                let valid_announcement = ChannelAnnouncement {
                        node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
@@ -1440,7 +1440,7 @@ mod tests {
                }
 
                unsigned_channel_update.timestamp += 100;
-               unsigned_channel_update.excess_data.push(1);
+               unsigned_channel_update.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
                let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
                let valid_channel_update = ChannelUpdate {
                        signature: secp_ctx.sign(&msghash, node_1_privkey),
@@ -1740,7 +1740,7 @@ mod tests {
                                htlc_maximum_msat: OptionalField::Absent,
                                fee_base_msat: 10000,
                                fee_proportional_millionths: 20,
-                               excess_data: [1; 3].to_vec()
+                               excess_data: [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec()
                        };
                        let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
                        let valid_channel_update = ChannelUpdate {
@@ -1869,7 +1869,7 @@ mod tests {
                                alias: [0; 32],
                                addresses: Vec::new(),
                                excess_address_data: Vec::new(),
-                               excess_data: [1; 3].to_vec(),
+                               excess_data: [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec(),
                        };
                        let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
                        let valid_announcement = NodeAnnouncement {
@@ -2022,7 +2022,7 @@ mod tests {
                {
                        let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, ReplyChannelRange {
                                chain_hash,
-                               full_information: true,
+                               sync_complete: true,
                                first_blocknum: 0,
                                number_of_blocks: 2000,
                                short_channel_ids: vec![
@@ -2055,22 +2055,6 @@ mod tests {
                                _ => panic!("expected MessageSendEvent::SendShortIdsQuery"),
                        }
                }
-
-               // Test receipt of a reply that indicates the remote node does not maintain up-to-date
-               // information for the chain_hash. Because of discrepancies in implementation we use
-               // full_information=false and short_channel_ids=[] as the signal.
-               {
-                       // Handle the reply indicating the peer was unable to fulfill our request.
-                       let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, ReplyChannelRange {
-                               chain_hash,
-                               full_information: false,
-                               first_blocknum: 1000,
-                               number_of_blocks: 100,
-                               short_channel_ids: vec![],
-                       });
-                       assert!(result.is_err());
-                       assert_eq!(result.err().unwrap().err, "Received reply_channel_range with no information available");
-               }
        }
 
        #[test]
index dd18f1bc716af92748e500469a1edb3344a0451a..7819b06c0279650c17063dfaed81aebac610d884 100644 (file)
@@ -47,6 +47,7 @@ pub struct RouteHop {
        pub cltv_expiry_delta: u32,
 }
 
+/// (C-not exported)
 impl Writeable for Vec<RouteHop> {
        fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
                (self.len() as u8).write(writer)?;
@@ -62,6 +63,7 @@ impl Writeable for Vec<RouteHop> {
        }
 }
 
+/// (C-not exported)
 impl Readable for Vec<RouteHop> {
        fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Vec<RouteHop>, DecodeError> {
                let hops_count: u8 = Readable::read(reader)?;
@@ -3336,3 +3338,48 @@ mod tests {
        }
 
 }
+
+#[cfg(all(test, feature = "unstable"))]
+mod benches {
+       use super::*;
+       use util::logger::{Logger, Record};
+
+       use std::fs::File;
+       use test::Bencher;
+
+       struct DummyLogger {}
+       impl Logger for DummyLogger {
+               fn log(&self, _record: &Record) {}
+       }
+
+       #[bench]
+       fn generate_routes(bench: &mut Bencher) {
+               let mut d = File::open("net_graph-2021-02-12.bin").expect("Please fetch https://bitcoin.ninja/ldk-net_graph-879e309c128-2020-02-12.bin and place it at lightning/net_graph-2021-02-12.bin");
+               let graph = NetworkGraph::read(&mut d).unwrap();
+
+               // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
+               let mut path_endpoints = Vec::new();
+               let mut seed: usize = 0xdeadbeef;
+               'load_endpoints: for _ in 0..100 {
+                       loop {
+                               seed *= 0xdeadbeef;
+                               let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
+                               seed *= 0xdeadbeef;
+                               let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
+                               let amt = seed as u64 % 1_000_000;
+                               if get_route(src, &graph, dst, None, &[], amt, 42, &DummyLogger{}).is_ok() {
+                                       path_endpoints.push((src, dst, amt));
+                                       continue 'load_endpoints;
+                               }
+                       }
+               }
+
+               // ...then benchmark finding paths between the nodes we learned.
+               let mut idx = 0;
+               bench.iter(|| {
+                       let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
+                       assert!(get_route(src, &graph, dst, None, &[], amt, 42, &DummyLogger{}).is_ok());
+                       idx += 1;
+               });
+       }
+}
index 77329cba458753ddb53b1152c64dc73ba7c814a3..c23856b60c8d69fb412e04f2eb3934b8ac29ff35 100644 (file)
@@ -328,7 +328,7 @@ mod test {
                        key:   [u8; 32],
                        nonce: [u8; 8],
                        keystream: Vec<u8>,
-               };
+               }
                // taken from http://tools.ietf.org/html/draft-agl-tls-chacha20poly1305-04
                let test_vectors = vec!(
                        TestVector{
@@ -463,7 +463,7 @@ mod test {
                        key:   [u8; 32],
                        nonce: [u8; 12],
                        keystream: Vec<u8>,
-               };
+               }
                // taken from http://tools.ietf.org/html/draft-agl-tls-chacha20poly1305-04
                let test_vectors = vec!(
                        TestVector{
index 712b5937bab7ea2517f41cef155a7fe8d707c2b9..f43423d7c0c0af923a4ac8f08a562aea474f946c 100644 (file)
@@ -15,7 +15,7 @@ use ln::channelmanager::{BREAKDOWN_TIMEOUT, MAX_LOCAL_BREAKDOWN_TIMEOUT};
 /// Configuration we set when applicable.
 ///
 /// Default::default() provides sane defaults.
-#[derive(Clone, Debug)]
+#[derive(Copy, Clone, Debug)]
 pub struct ChannelHandshakeConfig {
        /// Confirmations we will wait for before considering the channel locked in.
        /// Applied only for inbound channels (see ChannelHandshakeLimits::max_minimum_depth for the
@@ -209,7 +209,7 @@ impl_writeable!(ChannelConfig, 8+1+1, {
 ///
 /// Default::default() provides sane defaults for most configurations
 /// (but currently with 0 relay fees!)
-#[derive(Clone, Debug)]
+#[derive(Copy, Clone, Debug)]
 pub struct UserConfig {
        /// Channel config that we propose to our counterparty.
        pub own_channel_config: ChannelHandshakeConfig,
index 5d0a196f31fb27d956ae4c314dc302e243a0ae33..2e9e793bdd806ec5205ece7f7b493df312d5ec31 100644 (file)
@@ -7,9 +7,9 @@
 // You may not use this file except in accordance with one or both of these
 // licenses.
 
-use ln::chan_utils::{HTLCOutputInCommitment, TxCreationKeys, ChannelPublicKeys, HolderCommitmentTransaction, PreCalculatedTxCreationKeys};
+use ln::chan_utils::{HTLCOutputInCommitment, ChannelPublicKeys, HolderCommitmentTransaction, CommitmentTransaction, ChannelTransactionParameters, TrustedCommitmentTransaction};
 use ln::{chan_utils, msgs};
-use chain::keysinterface::{ChannelKeys, InMemoryChannelKeys};
+use chain::keysinterface::{Sign, InMemorySigner};
 
 use std::cmp;
 use std::sync::{Mutex, Arc};
@@ -24,96 +24,120 @@ use util::ser::{Writeable, Writer, Readable};
 use std::io::Error;
 use ln::msgs::DecodeError;
 
-/// Enforces some rules on ChannelKeys calls. Eventually we will probably want to expose a variant
-/// of this which would essentially be what you'd want to run on a hardware wallet.
+/// Initial value for revoked commitment downward counter
+pub const INITIAL_REVOKED_COMMITMENT_NUMBER: u64 = 1 << 48;
+
+/// An implementation of Sign that enforces some policy checks.  The current checks
+/// are an incomplete set.  They include:
+///
+/// - When signing, the holder transaction has not been revoked
+/// - When revoking, the holder transaction has not been signed
+/// - The holder commitment number is monotonic and without gaps
+/// - The counterparty commitment number is monotonic and without gaps
+/// - The pre-derived keys and pre-built transaction in CommitmentTransaction were correctly built
+///
+/// Eventually we will probably want to expose a variant of this which would essentially
+/// be what you'd want to run on a hardware wallet.
 #[derive(Clone)]
-pub struct EnforcingChannelKeys {
-       pub inner: InMemoryChannelKeys,
-       commitment_number_obscure_and_last: Arc<Mutex<(Option<u64>, u64)>>,
+pub struct EnforcingSigner {
+       pub inner: InMemorySigner,
+       /// The last counterparty commitment number we signed, backwards counting
+       pub last_commitment_number: Arc<Mutex<Option<u64>>>,
+       /// The last holder commitment number we revoked, backwards counting
+       pub revoked_commitment: Arc<Mutex<u64>>,
+       pub disable_revocation_policy_check: bool,
 }
 
-impl EnforcingChannelKeys {
-       pub fn new(inner: InMemoryChannelKeys) -> Self {
+impl EnforcingSigner {
+       /// Construct an EnforcingSigner
+       pub fn new(inner: InMemorySigner) -> Self {
                Self {
                        inner,
-                       commitment_number_obscure_and_last: Arc::new(Mutex::new((None, 0))),
+                       last_commitment_number: Arc::new(Mutex::new(None)),
+                       revoked_commitment: Arc::new(Mutex::new(INITIAL_REVOKED_COMMITMENT_NUMBER)),
+                       disable_revocation_policy_check: false
                }
        }
-}
-
-impl EnforcingChannelKeys {
-       fn check_keys<T: secp256k1::Signing + secp256k1::Verification>(&self, secp_ctx: &Secp256k1<T>,
-                                                                      keys: &TxCreationKeys) {
-               let remote_points = self.inner.counterparty_pubkeys();
 
-               let keys_expected = TxCreationKeys::derive_new(secp_ctx,
-                                                              &keys.per_commitment_point,
-                                                              &remote_points.delayed_payment_basepoint,
-                                                              &remote_points.htlc_basepoint,
-                                                              &self.inner.pubkeys().revocation_basepoint,
-                                                              &self.inner.pubkeys().htlc_basepoint).unwrap();
-               if keys != &keys_expected { panic!("derived different per-tx keys") }
+       /// Construct an EnforcingSigner with externally managed storage
+       ///
+       /// Since there are multiple copies of this struct for each channel, some coordination is needed
+       /// so that all copies are aware of revocations.  A pointer to this state is provided here, usually
+       /// by an implementation of KeysInterface.
+       pub fn new_with_revoked(inner: InMemorySigner, revoked_commitment: Arc<Mutex<u64>>, disable_revocation_policy_check: bool) -> Self {
+               Self {
+                       inner,
+                       last_commitment_number: Arc::new(Mutex::new(None)),
+                       revoked_commitment,
+                       disable_revocation_policy_check
+               }
        }
 }
 
-impl ChannelKeys for EnforcingChannelKeys {
+impl Sign for EnforcingSigner {
        fn get_per_commitment_point<T: secp256k1::Signing + secp256k1::Verification>(&self, idx: u64, secp_ctx: &Secp256k1<T>) -> PublicKey {
                self.inner.get_per_commitment_point(idx, secp_ctx)
        }
 
        fn release_commitment_secret(&self, idx: u64) -> [u8; 32] {
-               // TODO: enforce the ChannelKeys contract - error here if we already signed this commitment
+               {
+                       let mut revoked = self.revoked_commitment.lock().unwrap();
+                       assert!(idx == *revoked || idx == *revoked - 1, "can only revoke the current or next unrevoked commitment - trying {}, revoked {}", idx, *revoked);
+                       *revoked = idx;
+               }
                self.inner.release_commitment_secret(idx)
        }
 
        fn pubkeys(&self) -> &ChannelPublicKeys { self.inner.pubkeys() }
-       fn key_derivation_params(&self) -> (u64, u64) { self.inner.key_derivation_params() }
+       fn channel_keys_id(&self) -> [u8; 32] { self.inner.channel_keys_id() }
 
-       fn sign_counterparty_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, feerate_per_kw: u32, commitment_tx: &Transaction, pre_keys: &PreCalculatedTxCreationKeys, htlcs: &[&HTLCOutputInCommitment], secp_ctx: &Secp256k1<T>) -> Result<(Signature, Vec<Signature>), ()> {
-               if commitment_tx.input.len() != 1 { panic!("lightning commitment transactions have a single input"); }
-               self.check_keys(secp_ctx, pre_keys.trust_key_derivation());
-               let obscured_commitment_transaction_number = (commitment_tx.lock_time & 0xffffff) as u64 | ((commitment_tx.input[0].sequence as u64 & 0xffffff) << 3*8);
+       fn sign_counterparty_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, commitment_tx: &CommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<(Signature, Vec<Signature>), ()> {
+               self.verify_counterparty_commitment_tx(commitment_tx, secp_ctx);
 
                {
-                       let mut commitment_data = self.commitment_number_obscure_and_last.lock().unwrap();
-                       if commitment_data.0.is_none() {
-                               commitment_data.0 = Some(obscured_commitment_transaction_number ^ commitment_data.1);
-                       }
-                       let commitment_number = obscured_commitment_transaction_number ^ commitment_data.0.unwrap();
-                       assert!(commitment_number == commitment_data.1 || commitment_number == commitment_data.1 + 1);
-                       commitment_data.1 = cmp::max(commitment_number, commitment_data.1)
+                       let mut last_commitment_number_guard = self.last_commitment_number.lock().unwrap();
+                       let actual_commitment_number = commitment_tx.commitment_number();
+                       let last_commitment_number = last_commitment_number_guard.unwrap_or(actual_commitment_number);
+                       // These commitment numbers are backwards counting.  We expect either the same as the previously encountered,
+                       // or the next one.
+                       assert!(last_commitment_number == actual_commitment_number || last_commitment_number - 1 == actual_commitment_number, "{} doesn't come after {}", actual_commitment_number, last_commitment_number);
+                       *last_commitment_number_guard = Some(cmp::min(last_commitment_number, actual_commitment_number))
                }
 
-               Ok(self.inner.sign_counterparty_commitment(feerate_per_kw, commitment_tx, pre_keys, htlcs, secp_ctx).unwrap())
-       }
-
-       fn sign_holder_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, holder_commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
-               // TODO: enforce the ChannelKeys contract - error if this commitment was already revoked
-               // TODO: need the commitment number
-               Ok(self.inner.sign_holder_commitment(holder_commitment_tx, secp_ctx).unwrap())
+               Ok(self.inner.sign_counterparty_commitment(commitment_tx, secp_ctx).unwrap())
        }
 
-       #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
-       fn unsafe_sign_holder_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, holder_commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
-               Ok(self.inner.unsafe_sign_holder_commitment(holder_commitment_tx, secp_ctx).unwrap())
-       }
-
-       fn sign_holder_commitment_htlc_transactions<T: secp256k1::Signing + secp256k1::Verification>(&self, holder_commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<Vec<Option<Signature>>, ()> {
-               let commitment_txid = holder_commitment_tx.txid();
+       fn sign_holder_commitment_and_htlcs<T: secp256k1::Signing + secp256k1::Verification>(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<(Signature, Vec<Signature>), ()> {
+               let trusted_tx = self.verify_holder_commitment_tx(commitment_tx, secp_ctx);
+               let commitment_txid = trusted_tx.txid();
                let holder_csv = self.inner.counterparty_selected_contest_delay();
 
-               for this_htlc in holder_commitment_tx.per_htlc.iter() {
-                       if this_htlc.0.transaction_output_index.is_some() {
-                               let htlc_tx = chan_utils::build_htlc_transaction(&commitment_txid, holder_commitment_tx.feerate_per_kw, holder_csv, &this_htlc.0, &holder_commitment_tx.keys.broadcaster_delayed_payment_key, &holder_commitment_tx.keys.revocation_key);
+               let revoked = self.revoked_commitment.lock().unwrap();
+               let commitment_number = trusted_tx.commitment_number();
+               if *revoked - 1 != commitment_number && *revoked - 2 != commitment_number {
+                       if !self.disable_revocation_policy_check {
+                               panic!("can only sign the next two unrevoked commitment numbers, revoked={} vs requested={} for {}",
+                                      *revoked, commitment_number, self.inner.commitment_seed[0])
+                       }
+               }
 
-                               let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&this_htlc.0, &holder_commitment_tx.keys);
+               for (this_htlc, sig) in trusted_tx.htlcs().iter().zip(&commitment_tx.counterparty_htlc_sigs) {
+                       assert!(this_htlc.transaction_output_index.is_some());
+                       let keys = trusted_tx.keys();
+                       let htlc_tx = chan_utils::build_htlc_transaction(&commitment_txid, trusted_tx.feerate_per_kw(), holder_csv, &this_htlc, &keys.broadcaster_delayed_payment_key, &keys.revocation_key);
 
-                               let sighash = hash_to_message!(&bip143::SigHashCache::new(&htlc_tx).signature_hash(0, &htlc_redeemscript, this_htlc.0.amount_msat / 1000, SigHashType::All)[..]);
-                               secp_ctx.verify(&sighash, this_htlc.1.as_ref().unwrap(), &holder_commitment_tx.keys.countersignatory_htlc_key).unwrap();
-                       }
+                       let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&this_htlc, &keys);
+
+                       let sighash = hash_to_message!(&bip143::SigHashCache::new(&htlc_tx).signature_hash(0, &htlc_redeemscript, this_htlc.amount_msat / 1000, SigHashType::All)[..]);
+                       secp_ctx.verify(&sighash, sig, &keys.countersignatory_htlc_key).unwrap();
                }
 
-               Ok(self.inner.sign_holder_commitment_htlc_transactions(holder_commitment_tx, secp_ctx).unwrap())
+               Ok(self.inner.sign_holder_commitment_and_htlcs(commitment_tx, secp_ctx).unwrap())
+       }
+
+       #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
+       fn unsafe_sign_holder_commitment_and_htlcs<T: secp256k1::Signing + secp256k1::Verification>(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<(Signature, Vec<Signature>), ()> {
+               Ok(self.inner.unsafe_sign_holder_commitment_and_htlcs(commitment_tx, secp_ctx).unwrap())
        }
 
        fn sign_justice_transaction<T: secp256k1::Signing + secp256k1::Verification>(&self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey, htlc: &Option<HTLCOutputInCommitment>, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
@@ -132,28 +156,44 @@ impl ChannelKeys for EnforcingChannelKeys {
                self.inner.sign_channel_announcement(msg, secp_ctx)
        }
 
-       fn on_accept(&mut self, channel_pubkeys: &ChannelPublicKeys, counterparty_selected_delay: u16, holder_selected_delay: u16) {
-               self.inner.on_accept(channel_pubkeys, counterparty_selected_delay, holder_selected_delay)
+       fn ready_channel(&mut self, channel_parameters: &ChannelTransactionParameters) {
+               self.inner.ready_channel(channel_parameters)
        }
 }
 
-impl Writeable for EnforcingChannelKeys {
+
+impl Writeable for EnforcingSigner {
        fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
                self.inner.write(writer)?;
-               let (obscure, last) = *self.commitment_number_obscure_and_last.lock().unwrap();
-               obscure.write(writer)?;
+               let last = *self.last_commitment_number.lock().unwrap();
                last.write(writer)?;
                Ok(())
        }
 }
 
-impl Readable for EnforcingChannelKeys {
+impl Readable for EnforcingSigner {
        fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
                let inner = Readable::read(reader)?;
-               let obscure_and_last = Readable::read(reader)?;
-               Ok(EnforcingChannelKeys {
-                       inner: inner,
-                       commitment_number_obscure_and_last: Arc::new(Mutex::new(obscure_and_last))
+               let last_commitment_number = Readable::read(reader)?;
+               Ok(EnforcingSigner {
+                       inner,
+                       last_commitment_number: Arc::new(Mutex::new(last_commitment_number)),
+                       revoked_commitment: Arc::new(Mutex::new(INITIAL_REVOKED_COMMITMENT_NUMBER)),
+                       disable_revocation_policy_check: false,
                })
        }
 }
+
+impl EnforcingSigner {
+       fn verify_counterparty_commitment_tx<'a, T: secp256k1::Signing + secp256k1::Verification>(&self, commitment_tx: &'a CommitmentTransaction, secp_ctx: &Secp256k1<T>) -> TrustedCommitmentTransaction<'a> {
+               commitment_tx.verify(&self.inner.get_channel_parameters().as_counterparty_broadcastable(),
+                                    self.inner.counterparty_pubkeys(), self.inner.pubkeys(), secp_ctx)
+                       .expect("derived different per-tx keys or built transaction")
+       }
+
+       fn verify_holder_commitment_tx<'a, T: secp256k1::Signing + secp256k1::Verification>(&self, commitment_tx: &'a CommitmentTransaction, secp_ctx: &Secp256k1<T>) -> TrustedCommitmentTransaction<'a> {
+               commitment_tx.verify(&self.inner.get_channel_parameters().as_holder_broadcastable(),
+                                    self.inner.pubkeys(), self.inner.counterparty_pubkeys(), secp_ctx)
+                       .expect("derived different per-tx keys or built transaction")
+       }
+}
index a2a45a7b3afc66372ff3e41e6655d9a199b67099..f67621c828ca521f4739d99ec5a54760310cb1a8 100644 (file)
@@ -13,6 +13,7 @@ use std::fmt;
 
 /// Indicates an error on the client's part (usually some variant of attempting to use too-low or
 /// too-high values)
+#[derive(Clone)]
 pub enum APIError {
        /// Indicates the API was wholly misused (see err for more). Cases where these can be returned
        /// are documented, but generally indicates some precondition of a function was violated.
index e667c4d726c5f2075907d9c9f4c2ea465fb8e137..90a1bdb4814f454de1c4f01d4639a58d36a761ac 100644 (file)
@@ -72,7 +72,7 @@ impl<'a, T> std::fmt::Display for DebugFundingInfo<'a, T> {
 }
 macro_rules! log_funding_info {
        ($key_storage: expr) => {
-               ::util::macro_logger::DebugFundingInfo($key_storage.get_funding_txo())
+               ::util::macro_logger::DebugFundingInfo(&$key_storage.get_funding_txo())
        }
 }
 
@@ -138,11 +138,11 @@ impl<'a> std::fmt::Display for DebugSpendable<'a> {
                        &SpendableOutputDescriptor::StaticOutput { ref outpoint, .. } => {
                                write!(f, "StaticOutput {}:{} marked for spending", outpoint.txid, outpoint.index)?;
                        }
-                       &SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, .. } => {
-                               write!(f, "DynamicOutputP2WSH {}:{} marked for spending", outpoint.txid, outpoint.index)?;
+                       &SpendableOutputDescriptor::DelayedPaymentOutput(ref descriptor) => {
+                               write!(f, "DelayedPaymentOutput {}:{} marked for spending", descriptor.outpoint.txid, descriptor.outpoint.index)?;
                        }
-                       &SpendableOutputDescriptor::StaticOutputCounterpartyPayment { ref outpoint, .. } => {
-                               write!(f, "DynamicOutputP2WPKH {}:{} marked for spending", outpoint.txid, outpoint.index)?;
+                       &SpendableOutputDescriptor::StaticPaymentOutput(ref descriptor) => {
+                               write!(f, "DynamicOutputP2WPKH {}:{} marked for spending", descriptor.outpoint.txid, descriptor.outpoint.index)?;
                        }
                }
                Ok(())
@@ -155,12 +155,17 @@ macro_rules! log_spendable {
        }
 }
 
+/// Create a new Record and log it. You probably don't want to use this macro directly,
+/// but it needs to be exported so `log_trace` etc can use it in external crates.
+#[macro_export]
 macro_rules! log_internal {
        ($logger: expr, $lvl:expr, $($arg:tt)+) => (
-               $logger.log(&::util::logger::Record::new($lvl, format_args!($($arg)+), module_path!(), file!(), line!()));
+               $logger.log(&$crate::util::logger::Record::new($lvl, format_args!($($arg)+), module_path!(), file!(), line!()));
        );
 }
 
+/// Log an error.
+#[macro_export]
 macro_rules! log_error {
        ($logger: expr, $($arg:tt)*) => (
                #[cfg(not(any(feature = "max_level_off")))]
@@ -189,6 +194,8 @@ macro_rules! log_debug {
        )
 }
 
+/// Log a trace log.
+#[macro_export]
 macro_rules! log_trace {
        ($logger: expr, $($arg:tt)*) => (
                #[cfg(not(any(feature = "max_level_off", feature = "max_level_error", feature = "max_level_warn", feature = "max_level_info", feature = "max_level_debug")))]
index a3cfaa9804e6e9f58c3521e6ab2d07c3862fd0b6..b8028ea97afcf454e00abb67ba503e8b02805dcd 100644 (file)
@@ -25,14 +25,16 @@ pub(crate) mod transaction_utils;
 
 #[macro_use]
 pub(crate) mod ser_macros;
+
+/// Logging macro utilities.
 #[macro_use]
-pub(crate) mod macro_logger;
+pub mod macro_logger;
 
 // These have to come after macro_logger to build
 pub mod logger;
 pub mod config;
 
-#[cfg(any(test, feature = "_test_utils"))]
+#[cfg(any(test, feature = "fuzztarget", feature = "_test_utils"))]
 pub mod test_utils;
 
 /// impls of traits that add exra enforcement on the way they're called. Useful for detecting state
index 961d4f1020073f8d76553374ef0cec394e217828..b718e228c93e8233ce799e7fa10c90b26cd89b9d 100644 (file)
@@ -31,7 +31,8 @@ use util::byte_utils;
 
 use util::byte_utils::{be64_to_array, be48_to_array, be32_to_array, be16_to_array, slice_to_be16, slice_to_be32, slice_to_be48, slice_to_be64};
 
-const MAX_BUF_SIZE: usize = 64 * 1024;
+/// serialization buffer size
+pub const MAX_BUF_SIZE: usize = 64 * 1024;
 
 /// A trait that is similar to std::io::Write but has one extra function which can be used to size
 /// buffers being written into.
@@ -706,8 +707,7 @@ macro_rules! impl_consensus_ser {
                        fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
                                match self.consensus_encode(WriterWriteAdaptor(writer)) {
                                        Ok(_) => Ok(()),
-                                       Err(consensus::encode::Error::Io(e)) => Err(e),
-                                       Err(_) => panic!("We shouldn't get a consensus::encode::Error unless our Write generated an std::io::Error"),
+                                       Err(e) => Err(e),
                                }
                        }
                }
@@ -717,7 +717,7 @@ macro_rules! impl_consensus_ser {
                                match consensus::encode::Decodable::consensus_decode(r) {
                                        Ok(t) => Ok(t),
                                        Err(consensus::encode::Error::Io(ref e)) if e.kind() == ::std::io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
-                                       Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e)),
+                                       Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e.kind())),
                                        Err(_) => Err(DecodeError::InvalidValue),
                                }
                        }
index c944e572cd4569deb44ee8d06180f64d2440ef41..d29a55f12010cfb3a057c959248e31de841a7482 100644 (file)
@@ -18,10 +18,10 @@ use chain::keysinterface;
 use ln::features::{ChannelFeatures, InitFeatures};
 use ln::msgs;
 use ln::msgs::OptionalField;
-use util::enforcing_trait_impls::EnforcingChannelKeys;
+use util::enforcing_trait_impls::{EnforcingSigner, INITIAL_REVOKED_COMMITMENT_NUMBER};
 use util::events;
 use util::logger::{Logger, Level, Record};
-use util::ser::{Readable, Writer, Writeable};
+use util::ser::{Readable, ReadableArgs, Writer, Writeable};
 
 use bitcoin::blockdata::constants::genesis_block;
 use bitcoin::blockdata::transaction::{Transaction, TxOut};
@@ -35,10 +35,11 @@ use bitcoin::secp256k1::{SecretKey, PublicKey, Secp256k1, Signature};
 use regex;
 
 use std::time::Duration;
-use std::sync::Mutex;
+use std::sync::{Mutex, Arc};
 use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
 use std::{cmp, mem};
 use std::collections::{HashMap, HashSet};
+use chain::keysinterface::InMemorySigner;
 
 pub struct TestVecWriter(pub Vec<u8>);
 impl Writer for TestVecWriter {
@@ -60,36 +61,51 @@ impl chaininterface::FeeEstimator for TestFeeEstimator {
        }
 }
 
+pub struct OnlyReadsKeysInterface {}
+impl keysinterface::KeysInterface for OnlyReadsKeysInterface {
+       type Signer = EnforcingSigner;
+
+       fn get_node_secret(&self) -> SecretKey { unreachable!(); }
+       fn get_destination_script(&self) -> Script { unreachable!(); }
+       fn get_shutdown_pubkey(&self) -> PublicKey { unreachable!(); }
+       fn get_channel_signer(&self, _inbound: bool, _channel_value_satoshis: u64) -> EnforcingSigner { unreachable!(); }
+       fn get_secure_random_bytes(&self) -> [u8; 32] { [0; 32] }
+
+       fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
+               EnforcingSigner::read(&mut std::io::Cursor::new(reader))
+       }
+}
+
 pub struct TestChainMonitor<'a> {
-       pub added_monitors: Mutex<Vec<(OutPoint, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>>,
+       pub added_monitors: Mutex<Vec<(OutPoint, channelmonitor::ChannelMonitor<EnforcingSigner>)>>,
        pub latest_monitor_update_id: Mutex<HashMap<[u8; 32], (OutPoint, u64)>>,
-       pub chain_monitor: chainmonitor::ChainMonitor<EnforcingChannelKeys, &'a TestChainSource, &'a chaininterface::BroadcasterInterface, &'a TestFeeEstimator, &'a TestLogger, &'a channelmonitor::Persist<EnforcingChannelKeys>>,
+       pub chain_monitor: chainmonitor::ChainMonitor<EnforcingSigner, &'a TestChainSource, &'a chaininterface::BroadcasterInterface, &'a TestFeeEstimator, &'a TestLogger, &'a channelmonitor::Persist<EnforcingSigner>>,
+       pub keys_manager: &'a TestKeysInterface,
        pub update_ret: Mutex<Option<Result<(), channelmonitor::ChannelMonitorUpdateErr>>>,
        // If this is set to Some(), after the next return, we'll always return this until update_ret
        // is changed:
        pub next_update_ret: Mutex<Option<Result<(), channelmonitor::ChannelMonitorUpdateErr>>>,
 }
 impl<'a> TestChainMonitor<'a> {
-       pub fn new(chain_source: Option<&'a TestChainSource>, broadcaster: &'a chaininterface::BroadcasterInterface, logger: &'a TestLogger, fee_estimator: &'a TestFeeEstimator, persister: &'a channelmonitor::Persist<EnforcingChannelKeys>) -> Self {
+       pub fn new(chain_source: Option<&'a TestChainSource>, broadcaster: &'a chaininterface::BroadcasterInterface, logger: &'a TestLogger, fee_estimator: &'a TestFeeEstimator, persister: &'a channelmonitor::Persist<EnforcingSigner>, keys_manager: &'a TestKeysInterface) -> Self {
                Self {
                        added_monitors: Mutex::new(Vec::new()),
                        latest_monitor_update_id: Mutex::new(HashMap::new()),
                        chain_monitor: chainmonitor::ChainMonitor::new(chain_source, broadcaster, logger, fee_estimator, persister),
+                       keys_manager,
                        update_ret: Mutex::new(None),
                        next_update_ret: Mutex::new(None),
                }
        }
 }
-impl<'a> chain::Watch for TestChainMonitor<'a> {
-       type Keys = EnforcingChannelKeys;
-
-       fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<EnforcingChannelKeys>) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
+impl<'a> chain::Watch<EnforcingSigner> for TestChainMonitor<'a> {
+       fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<EnforcingSigner>) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
                // At every point where we get a monitor update, we should be able to send a useful monitor
                // to a watchtower and disk...
                let mut w = TestVecWriter(Vec::new());
-               monitor.serialize_for_disk(&mut w).unwrap();
-               let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
-                       &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
+               monitor.write(&mut w).unwrap();
+               let new_monitor = <(Option<BlockHash>, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
+                       &mut ::std::io::Cursor::new(&w.0), self.keys_manager).unwrap().1;
                assert!(new_monitor == monitor);
                self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(), (funding_txo, monitor.get_latest_update_id()));
                self.added_monitors.lock().unwrap().push((funding_txo, monitor));
@@ -117,12 +133,12 @@ impl<'a> chain::Watch for TestChainMonitor<'a> {
                let update_res = self.chain_monitor.update_channel(funding_txo, update);
                // At every point where we get a monitor update, we should be able to send a useful monitor
                // to a watchtower and disk...
-               let monitors = self.chain_monitor.monitors.lock().unwrap();
+               let monitors = self.chain_monitor.monitors.read().unwrap();
                let monitor = monitors.get(&funding_txo).unwrap();
                w.0.clear();
-               monitor.serialize_for_disk(&mut w).unwrap();
-               let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
-                       &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
+               monitor.write(&mut w).unwrap();
+               let new_monitor = <(Option<BlockHash>, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
+                       &mut ::std::io::Cursor::new(&w.0), self.keys_manager).unwrap().1;
                assert!(new_monitor == *monitor);
                self.added_monitors.lock().unwrap().push((funding_txo, new_monitor));
 
@@ -156,12 +172,12 @@ impl TestPersister {
                *self.update_ret.lock().unwrap() = ret;
        }
 }
-impl channelmonitor::Persist<EnforcingChannelKeys> for TestPersister {
-       fn persist_new_channel(&self, _funding_txo: OutPoint, _data: &channelmonitor::ChannelMonitor<EnforcingChannelKeys>) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
+impl channelmonitor::Persist<EnforcingSigner> for TestPersister {
+       fn persist_new_channel(&self, _funding_txo: OutPoint, _data: &channelmonitor::ChannelMonitor<EnforcingSigner>) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
                self.update_ret.lock().unwrap().clone()
        }
 
-       fn update_persisted_channel(&self, _funding_txo: OutPoint, _update: &channelmonitor::ChannelMonitorUpdate, _data: &channelmonitor::ChannelMonitor<EnforcingChannelKeys>) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
+       fn update_persisted_channel(&self, _funding_txo: OutPoint, _update: &channelmonitor::ChannelMonitorUpdate, _data: &channelmonitor::ChannelMonitor<EnforcingSigner>) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
                self.update_ret.lock().unwrap().clone()
        }
 }
@@ -193,7 +209,7 @@ impl msgs::ChannelMessageHandler for TestChannelMessageHandler {
        fn handle_funding_created(&self, _their_node_id: &PublicKey, _msg: &msgs::FundingCreated) {}
        fn handle_funding_signed(&self, _their_node_id: &PublicKey, _msg: &msgs::FundingSigned) {}
        fn handle_funding_locked(&self, _their_node_id: &PublicKey, _msg: &msgs::FundingLocked) {}
-       fn handle_shutdown(&self, _their_node_id: &PublicKey, _msg: &msgs::Shutdown) {}
+       fn handle_shutdown(&self, _their_node_id: &PublicKey, _their_features: &InitFeatures, _msg: &msgs::Shutdown) {}
        fn handle_closing_signed(&self, _their_node_id: &PublicKey, _msg: &msgs::ClosingSigned) {}
        fn handle_update_add_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateAddHTLC) {}
        fn handle_update_fulfill_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFulfillHTLC) {}
@@ -237,12 +253,14 @@ fn get_dummy_channel_announcement(short_chan_id: u64) -> msgs::ChannelAnnounceme
                excess_data: Vec::new(),
        };
 
-       msgs::ChannelAnnouncement {
-               node_signature_1: Signature::from(FFISignature::new()),
-               node_signature_2: Signature::from(FFISignature::new()),
-               bitcoin_signature_1: Signature::from(FFISignature::new()),
-               bitcoin_signature_2: Signature::from(FFISignature::new()),
-               contents: unsigned_ann,
+       unsafe {
+               msgs::ChannelAnnouncement {
+                       node_signature_1: Signature::from(FFISignature::new()),
+                       node_signature_2: Signature::from(FFISignature::new()),
+                       bitcoin_signature_1: Signature::from(FFISignature::new()),
+                       bitcoin_signature_2: Signature::from(FFISignature::new()),
+                       contents: unsigned_ann,
+               }
        }
 }
 
@@ -250,7 +268,7 @@ fn get_dummy_channel_update(short_chan_id: u64) -> msgs::ChannelUpdate {
        use bitcoin::secp256k1::ffi::Signature as FFISignature;
        let network = Network::Testnet;
        msgs::ChannelUpdate {
-               signature: Signature::from(FFISignature::new()),
+               signature: Signature::from(unsafe { FFISignature::new() }),
                contents: msgs::UnsignedChannelUpdate {
                        chain_hash: genesis_block(network).header.block_hash(),
                        short_channel_id: short_chan_id,
@@ -401,19 +419,23 @@ impl Logger for TestLogger {
 }
 
 pub struct TestKeysInterface {
-       backing: keysinterface::KeysManager,
+       pub backing: keysinterface::KeysManager,
        pub override_session_priv: Mutex<Option<[u8; 32]>>,
        pub override_channel_id_priv: Mutex<Option<[u8; 32]>>,
+       pub disable_revocation_policy_check: bool,
+       revoked_commitments: Mutex<HashMap<[u8;32], Arc<Mutex<u64>>>>,
 }
 
 impl keysinterface::KeysInterface for TestKeysInterface {
-       type ChanKeySigner = EnforcingChannelKeys;
+       type Signer = EnforcingSigner;
 
        fn get_node_secret(&self) -> SecretKey { self.backing.get_node_secret() }
        fn get_destination_script(&self) -> Script { self.backing.get_destination_script() }
        fn get_shutdown_pubkey(&self) -> PublicKey { self.backing.get_shutdown_pubkey() }
-       fn get_channel_keys(&self, inbound: bool, channel_value_satoshis: u64) -> EnforcingChannelKeys {
-               EnforcingChannelKeys::new(self.backing.get_channel_keys(inbound, channel_value_satoshis))
+       fn get_channel_signer(&self, inbound: bool, channel_value_satoshis: u64) -> EnforcingSigner {
+               let keys = self.backing.get_channel_signer(inbound, channel_value_satoshis);
+               let revoked_commitment = self.make_revoked_commitment_cell(keys.commitment_seed);
+               EnforcingSigner::new_with_revoked(keys, revoked_commitment, self.disable_revocation_policy_check)
        }
 
        fn get_secure_random_bytes(&self) -> [u8; 32] {
@@ -430,19 +452,49 @@ impl keysinterface::KeysInterface for TestKeysInterface {
                }
                self.backing.get_secure_random_bytes()
        }
+
+       fn read_chan_signer(&self, buffer: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
+               let mut reader = std::io::Cursor::new(buffer);
+
+               let inner: InMemorySigner = Readable::read(&mut reader)?;
+               let revoked_commitment = self.make_revoked_commitment_cell(inner.commitment_seed);
+
+               let last_commitment_number = Readable::read(&mut reader)?;
+
+               Ok(EnforcingSigner {
+                       inner,
+                       last_commitment_number: Arc::new(Mutex::new(last_commitment_number)),
+                       revoked_commitment,
+                       disable_revocation_policy_check: self.disable_revocation_policy_check,
+               })
+       }
 }
 
+
 impl TestKeysInterface {
        pub fn new(seed: &[u8; 32], network: Network) -> Self {
                let now = Duration::from_secs(genesis_block(network).header.time as u64);
                Self {
-                       backing: keysinterface::KeysManager::new(seed, network, now.as_secs(), now.subsec_nanos()),
+                       backing: keysinterface::KeysManager::new(seed, now.as_secs(), now.subsec_nanos()),
                        override_session_priv: Mutex::new(None),
                        override_channel_id_priv: Mutex::new(None),
+                       disable_revocation_policy_check: false,
+                       revoked_commitments: Mutex::new(HashMap::new()),
                }
        }
-       pub fn derive_channel_keys(&self, channel_value_satoshis: u64, user_id_1: u64, user_id_2: u64) -> EnforcingChannelKeys {
-               EnforcingChannelKeys::new(self.backing.derive_channel_keys(channel_value_satoshis, user_id_1, user_id_2))
+       pub fn derive_channel_keys(&self, channel_value_satoshis: u64, id: &[u8; 32]) -> EnforcingSigner {
+               let keys = self.backing.derive_channel_keys(channel_value_satoshis, id);
+               let revoked_commitment = self.make_revoked_commitment_cell(keys.commitment_seed);
+               EnforcingSigner::new_with_revoked(keys, revoked_commitment, self.disable_revocation_policy_check)
+       }
+
+       fn make_revoked_commitment_cell(&self, commitment_seed: [u8; 32]) -> Arc<Mutex<u64>> {
+               let mut revoked_commitments = self.revoked_commitments.lock().unwrap();
+               if !revoked_commitments.contains_key(&commitment_seed) {
+                       revoked_commitments.insert(commitment_seed, Arc::new(Mutex::new(INITIAL_REVOKED_COMMITMENT_NUMBER)));
+               }
+               let cell = revoked_commitments.get(&commitment_seed).unwrap();
+               Arc::clone(cell)
        }
 }
 
index 64ea801c62527ebac914bc7681dbf6b3ceb5173f..1984b480586a7c1da99254c4cdf9413b9964720f 100644 (file)
@@ -7,7 +7,12 @@
 // You may not use this file except in accordance with one or both of these
 // licenses.
 
-use bitcoin::blockdata::transaction::TxOut;
+use bitcoin::blockdata::transaction::{Transaction, TxOut};
+use bitcoin::blockdata::script::Script;
+use bitcoin::consensus::Encodable;
+use bitcoin::consensus::encode::VarInt;
+
+use ln::msgs::MAX_VALUE_MSAT;
 
 use std::cmp::Ordering;
 
@@ -21,12 +26,60 @@ pub fn sort_outputs<T, C : Fn(&T, &T) -> Ordering>(outputs: &mut Vec<(TxOut, T)>
        });
 }
 
+fn get_dust_value(output_script: &Script) -> u64 {
+       //TODO: This belongs in rust-bitcoin (https://github.com/rust-bitcoin/rust-bitcoin/pull/566)
+       if output_script.is_op_return() {
+               0
+       } else if output_script.is_witness_program() {
+               294
+       } else {
+               546
+       }
+}
+
+/// Possibly adds a change output to the given transaction, always doing so if there are excess
+/// funds available beyond the requested feerate.
+/// Assumes at least one input will have a witness (ie spends a segwit output).
+/// Returns an Err(()) if the requested feerate cannot be met.
+pub(crate) fn maybe_add_change_output(tx: &mut Transaction, input_value: u64, witness_max_weight: usize, feerate_sat_per_1000_weight: u32, change_destination_script: Script) -> Result<(), ()> {
+       if input_value > MAX_VALUE_MSAT / 1000 { return Err(()); }
+
+       let mut output_value = 0;
+       for output in tx.output.iter() {
+               output_value += output.value;
+               if output_value >= input_value { return Err(()); }
+       }
+
+       let dust_value = get_dust_value(&change_destination_script);
+       let mut change_output = TxOut {
+               script_pubkey: change_destination_script,
+               value: 0,
+       };
+       let change_len = change_output.consensus_encode(&mut std::io::sink()).unwrap();
+       let mut weight_with_change: i64 = tx.get_weight() as i64 + 2 + witness_max_weight as i64 + change_len as i64 * 4;
+       // Include any extra bytes required to push an extra output.
+       weight_with_change += (VarInt(tx.output.len() as u64 + 1).len() - VarInt(tx.output.len() as u64).len()) as i64 * 4;
+       // When calculating weight, add two for the flag bytes
+       let change_value: i64 = (input_value - output_value) as i64 - weight_with_change * feerate_sat_per_1000_weight as i64 / 1000;
+       if change_value >= dust_value as i64 {
+               change_output.value = change_value as u64;
+               tx.output.push(change_output);
+       } else if (input_value - output_value) as i64 - (tx.get_weight() as i64 + 2 + witness_max_weight as i64) * feerate_sat_per_1000_weight as i64 / 1000 < 0 {
+               return Err(());
+       }
+
+       Ok(())
+}
+
 #[cfg(test)]
 mod tests {
        use super::*;
 
+       use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, OutPoint};
        use bitcoin::blockdata::script::{Script, Builder};
-       use bitcoin::blockdata::transaction::TxOut;
+       use bitcoin::hash_types::Txid;
+
+       use bitcoin::hashes::sha256d::Hash as Sha256dHash;
 
        use hex::decode;
 
@@ -158,4 +211,78 @@ mod tests {
                bip69_txout_test_1: TXOUT1.to_vec(),
                bip69_txout_test_2: TXOUT2.to_vec(),
        }
+
+       #[test]
+       fn test_tx_value_overrun() {
+               // If we have a bogus input amount or outputs valued more than inputs, we should fail
+               let mut tx = Transaction { version: 2, lock_time: 0, input: Vec::new(), output: vec![TxOut {
+                       script_pubkey: Script::new(), value: 1000
+               }] };
+               assert!(maybe_add_change_output(&mut tx, 21_000_000_0000_0001, 0, 253, Script::new()).is_err());
+               assert!(maybe_add_change_output(&mut tx, 400, 0, 253, Script::new()).is_err());
+               assert!(maybe_add_change_output(&mut tx, 4000, 0, 253, Script::new()).is_ok());
+       }
+
+       #[test]
+       fn test_tx_change_edge() {
+               // Check that we never add dust outputs
+               let mut tx = Transaction { version: 2, lock_time: 0, input: Vec::new(), output: Vec::new() };
+               let orig_wtxid = tx.wtxid();
+               // 9 sats isn't enough to pay fee on a dummy transaction...
+               assert_eq!(tx.get_weight() as u64, 40); // ie 10 vbytes
+               assert!(maybe_add_change_output(&mut tx, 9, 0, 253, Script::new()).is_err());
+               assert_eq!(tx.wtxid(), orig_wtxid); // Failure doesn't change the transaction
+               // but 10-564 is, just not enough to add a change output...
+               assert!(maybe_add_change_output(&mut tx, 10, 0, 253, Script::new()).is_ok());
+               assert_eq!(tx.output.len(), 0);
+               assert_eq!(tx.wtxid(), orig_wtxid); // If we don't add an output, we don't change the transaction
+               assert!(maybe_add_change_output(&mut tx, 564, 0, 253, Script::new()).is_ok());
+               assert_eq!(tx.output.len(), 0);
+               assert_eq!(tx.wtxid(), orig_wtxid); // If we don't add an output, we don't change the transaction
+               // 565 is also not enough, if we anticipate 2 more weight units pushing us up to the next vbyte
+               // (considering the two bytes for segwit flags)
+               assert!(maybe_add_change_output(&mut tx, 565, 2, 253, Script::new()).is_ok());
+               assert_eq!(tx.output.len(), 0);
+               assert_eq!(tx.wtxid(), orig_wtxid); // If we don't add an output, we don't change the transaction
+               // at 565 we can afford the change output at the dust limit (546)
+               assert!(maybe_add_change_output(&mut tx, 565, 0, 253, Script::new()).is_ok());
+               assert_eq!(tx.output.len(), 1);
+               assert_eq!(tx.output[0].value, 546);
+               assert_eq!(tx.output[0].script_pubkey, Script::new());
+               assert_eq!(tx.get_weight() / 4, 565-546); // New weight is exactly the fee we wanted.
+
+               tx.output.pop();
+               assert_eq!(tx.wtxid(), orig_wtxid); // The only change is the addition of one output.
+       }
+
+       #[test]
+       fn test_tx_extra_outputs() {
+               // Check that we correctly handle existing outputs
+               let mut tx = Transaction { version: 2, lock_time: 0, input: vec![TxIn {
+                       previous_output: OutPoint::new(Txid::from_hash(Sha256dHash::default()), 0), script_sig: Script::new(), witness: Vec::new(), sequence: 0,
+               }], output: vec![TxOut {
+                       script_pubkey: Builder::new().push_int(1).into_script(), value: 1000
+               }] };
+               let orig_wtxid = tx.wtxid();
+               let orig_weight = tx.get_weight();
+               assert_eq!(orig_weight / 4, 61);
+
+               // Input value of the output value + fee - 1 should fail:
+               assert!(maybe_add_change_output(&mut tx, 1000 + 61 + 100 - 1, 400, 250, Builder::new().push_int(2).into_script()).is_err());
+               assert_eq!(tx.wtxid(), orig_wtxid); // Failure doesn't change the transaction
+               // but one more input sat should succeed, without changing the transaction
+               assert!(maybe_add_change_output(&mut tx, 1000 + 61 + 100, 400, 250, Builder::new().push_int(2).into_script()).is_ok());
+               assert_eq!(tx.wtxid(), orig_wtxid); // If we don't add an output, we don't change the transaction
+               // In order to get a change output, we need to add 546 plus the output's weight / 4 (10)...
+               assert!(maybe_add_change_output(&mut tx, 1000 + 61 + 100 + 546 + 9, 400, 250, Builder::new().push_int(2).into_script()).is_ok());
+               assert_eq!(tx.wtxid(), orig_wtxid); // If we don't add an output, we don't change the transaction
+
+               assert!(maybe_add_change_output(&mut tx, 1000 + 61 + 100 + 546 + 10, 400, 250, Builder::new().push_int(2).into_script()).is_ok());
+               assert_eq!(tx.output.len(), 2);
+               assert_eq!(tx.output[1].value, 546);
+               assert_eq!(tx.output[1].script_pubkey, Builder::new().push_int(2).into_script());
+               assert_eq!(tx.get_weight() - orig_weight, 40); // Weight difference matches what we had to add above
+               tx.output.pop();
+               assert_eq!(tx.wtxid(), orig_wtxid); // The only change is the addition of one output.
+       }
 }