Merge pull request #816 from valentinewallace/remove-simple-outer-arcs
authorMatt Corallo <649246+TheBlueMatt@users.noreply.github.com>
Wed, 3 Mar 2021 00:02:44 +0000 (16:02 -0800)
committerGitHub <noreply@github.com>
Wed, 3 Mar 2021 00:02:44 +0000 (16:02 -0800)
Remove simple outer arcs

42 files changed:
.github/workflows/build.yml
background-processor/Cargo.toml
c-bindings-gen/README.md [new file with mode: 0644]
c-bindings-gen/src/main.rs
c-bindings-gen/src/types.rs
fuzz/Cargo.toml
fuzz/src/chanmon_consistency.rs
fuzz/src/full_stack.rs
genbindings.sh
lightning-block-sync/Cargo.toml
lightning-block-sync/src/init.rs
lightning-c-bindings/Cargo.toml
lightning-c-bindings/include/lightning.h
lightning-c-bindings/include/lightningpp.hpp
lightning-c-bindings/src/c_types/mod.rs
lightning-c-bindings/src/chain/chainmonitor.rs
lightning-c-bindings/src/chain/keysinterface.rs
lightning-c-bindings/src/chain/mod.rs
lightning-c-bindings/src/ln/chan_utils.rs
lightning-c-bindings/src/ln/channelmanager.rs
lightning-c-bindings/src/ln/msgs.rs
lightning-c-bindings/src/routing/network_graph.rs
lightning-net-tokio/Cargo.toml
lightning-persister/Cargo.toml
lightning-persister/src/lib.rs
lightning-persister/src/util.rs
lightning/Cargo.toml
lightning/src/chain/chainmonitor.rs
lightning/src/chain/channelmonitor.rs
lightning/src/chain/keysinterface.rs
lightning/src/lib.rs
lightning/src/ln/chanmon_update_fail_tests.rs
lightning/src/ln/channel.rs
lightning/src/ln/channelmanager.rs
lightning/src/ln/functional_test_utils.rs
lightning/src/ln/functional_tests.rs
lightning/src/ln/onchaintx.rs
lightning/src/ln/onion_route_tests.rs
lightning/src/ln/peer_handler.rs
lightning/src/util/macro_logger.rs
lightning/src/util/ser.rs
lightning/src/util/test_utils.rs

index e4fe497fa3b6d3d8307d6392f6c2847751bdd6d2..628d620a5dc67cf048bd4e641ecb6c8e1dc16986 100644 (file)
@@ -202,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
 
index 71fbbbff83f0929818dd3a02371266aee91addc2..1a4dc488436bbf3d3450d50087cff6bf7f6468b7 100644 (file)
@@ -7,7 +7,7 @@ edition = "2018"
 # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
 
 [dependencies]
-bitcoin = "0.24"
+bitcoin = "0.26"
 lightning = { version = "0.0.12", path = "../lightning", features = ["allow_wallclock_use"] }
 lightning-persister = { version = "0.0.1", path = "../lightning-persister" }
 
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 a40875d95cf83209bb7ec2008b76c9b54012f853..5b99cd681819df8ad6643272224cc97d57e8bc17 100644 (file)
@@ -835,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();
index e7244039f4bcc5a32ab230b9f0a22640c56f28fd..7fc7e4cd905cff8d1cc66cd39aba44988b38c535 100644 (file)
@@ -587,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!(); }
        }
 
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 e180805f2361a079c9608dfb9cf27d9ee8d629c0..d6a106bb7d01a80d632193b32c74b89bc8d21a04 100644 (file)
@@ -126,7 +126,7 @@ impl chain::Watch<EnforcingSigner> 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<EnforcingSigner>)>::
+               let deserialized_monitor = <(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());
index 7f301fa35a1e9d4a3fd63a86fc92aeea77f387df..3774d0dce839848cb7034fbf041da52c78e60142 100644 (file)
@@ -263,7 +263,7 @@ 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_signer(&self, inbound: bool, channel_value_satoshis: u64) -> EnforcingSigner {
@@ -624,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
@@ -643,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)
@@ -651,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
@@ -673,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
                //
@@ -692,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
                //
@@ -701,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)
@@ -709,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
@@ -731,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)
@@ -746,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
@@ -791,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)
@@ -811,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)
@@ -840,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
@@ -868,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)
@@ -896,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 1ca2f6e8e886d1463d24bc9da55ae487ab04fde3..bfeda6bcdaebac000f32e4d1968355395c314821 100755 (executable)
@@ -44,8 +44,16 @@ 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:
@@ -171,6 +179,9 @@ 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++ $CFLAGS -std=c++11 -flto -O2 demo.cpp target/release/libldk.a -ldl
index aec6d1404c098f0fe4b58b6af73ba40e6299e503..c454de395e27d1c5bb95034ca5f5a6318c134ca6 100644 (file)
@@ -13,7 +13,7 @@ rest-client = [ "serde", "serde_json", "chunked_transfer" ]
 rpc-client = [ "serde", "serde_json", "chunked_transfer" ]
 
 [dependencies]
-bitcoin = "0.24"
+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 }
index da9895ae7213f0a529aa7d77f4d84f8ca8d077fd..24080b15acb1aa208eca0982e83f01a60117ab29 100644 (file)
@@ -38,7 +38,6 @@ use lightning::chain;
 ///
 /// use lightning_block_sync::*;
 ///
-/// use std::cell::RefCell;
 /// use std::io::Cursor;
 ///
 /// async fn init_sync<
@@ -83,7 +82,7 @@ use lightning::chain;
 ///
 ///    // Synchronize any channel monitors and the channel manager to be on the best block.
 ///    let mut cache = UnboundedCache::new();
-///    let mut monitor_listener = (RefCell::new(monitor), &*tx_broadcaster, &*fee_estimator, &*logger);
+///    let mut monitor_listener = (monitor, &*tx_broadcaster, &*fee_estimator, &*logger);
 ///    let listeners = vec![
 ///            (monitor_block_hash, &mut monitor_listener as &mut dyn chain::Listen),
 ///            (manager_block_hash, &mut manager as &mut dyn chain::Listen),
@@ -92,7 +91,7 @@ use lightning::chain;
 ///            block_source, Network::Bitcoin, &mut cache, listeners).await.unwrap();
 ///
 ///    // Allow the chain monitor to watch any channels.
-///    let monitor = monitor_listener.0.into_inner();
+///    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.
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 28e54f4f3a9d84c306693548e2b27c443af6120a..8076e251b85ed9039859d20a1df09320007a610e 100644 (file)
@@ -7,7 +7,7 @@
 #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
     */
@@ -3451,6 +3451,25 @@ typedef struct LDKAccess {
    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.
@@ -3629,7 +3648,7 @@ typedef struct LDKChannelMessageHandler {
    /**
     * Handle an incoming shutdown message from the given peer.
     */
-   void (*handle_shutdown)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKShutdown *NONNULL_PTR msg);
+   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.
     */
@@ -5117,6 +5136,11 @@ enum LDKAccessError AccessError_clone(const enum LDKAccessError *NONNULL_PTR ori
  */
 void Access_free(struct LDKAccess this_ptr);
 
+/**
+ * Calls the free function if one is set
+ */
+void Listen_free(struct LDKListen this_ptr);
+
 /**
  * Calls the free function if one is set
  */
@@ -5667,8 +5691,8 @@ void KeysManager_free(struct LDKKeysManager this_ptr);
 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 Sign 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
  * 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.
@@ -6029,6 +6053,8 @@ struct LDKMessageSendEventsProvider ChannelManager_as_MessageSendEventsProvider(
 
 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.
  */
index bd499ce6ed6c2237b69159099d8ba4c5d70b1f36..78193157c19c652b4fbf36fdacb9fa79509091f0 100644 (file)
@@ -702,6 +702,21 @@ public:
        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;
index 074aef25e84089698864306680aab11136adbe65..0a96f3e7d6789d0ad0be381022db26bb78b727ed 100644 (file)
@@ -72,8 +72,8 @@ pub enum Secp256k1Error {
        InvalidSecretKey,
        InvalidRecoveryId,
        InvalidTweak,
+       TweakCheckFailed,
        NotEnoughMemory,
-       CallbackPanicked,
 }
 impl Secp256k1Error {
        pub(crate) fn from_rust(err: SecpError) -> Self {
@@ -85,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,
                }
        }
index 3b306635defdb8dd220334f5946c183c450af4f7..de47fcb572f2ea177fe841abec29fd520fbf361c 100644 (file)
@@ -140,19 +140,19 @@ pub extern "C" fn ChainMonitor_as_Watch(this_arg: &ChainMonitor) -> crate::chain
 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_inner()) }, *unsafe { Box::from_raw(monitor.take_inner()) });
+       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_inner()) }, *unsafe { Box::from_raw(update.take_inner()) });
+       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 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()
 }
@@ -178,7 +178,7 @@ pub extern "C" fn ChainMonitor_as_EventsProvider(this_arg: &ChainMonitor) -> cra
 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 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 3cb70e7d81813d6f20df9c0507568491cecf6270..9235f8ec38a3924f183e1ffcb43cbb9f7648f7cf 100644 (file)
@@ -900,7 +900,7 @@ pub extern "C" fn InMemorySigner_clone(orig: &InMemorySigner) -> InMemorySigner
 #[must_use]
 #[no_mangle]
 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(&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, channel_keys_id.data);
+       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 }
 }
 
@@ -972,7 +972,7 @@ pub extern "C" fn InMemorySigner_get_channel_parameters(this_arg: &InMemorySigne
 #[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 }, &bitcoin::secp256k1::Secp256k1::new());
+       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
 }
@@ -986,7 +986,7 @@ pub extern "C" fn InMemorySigner_sign_counterparty_payment_input(this_arg: &InMe
 #[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 }, &bitcoin::secp256k1::Secp256k1::new());
+       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
 }
@@ -1026,17 +1026,17 @@ pub extern "C" fn InMemorySigner_as_Sign(this_arg: &InMemorySigner) -> crate::ch
 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 = unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }.get_per_commitment_point(idx, &bitcoin::secp256k1::Secp256k1::new());
+       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 InMemorySigner_Sign_release_commitment_secret(this_arg: *const c_void, mut idx: u64) -> crate::c_types::ThirtyTwoBytes {
-       let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }.release_commitment_secret(idx);
+       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 InMemorySigner_Sign_pubkeys(this_arg: *const c_void) -> crate::ln::chan_utils::ChannelPublicKeys {
-       let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }.pubkeys();
+       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 InMemorySigner_Sign_set_pubkeys(trait_self_arg: &Sign) {
@@ -1048,48 +1048,48 @@ extern "C" fn InMemorySigner_Sign_set_pubkeys(trait_self_arg: &Sign) {
 }
 #[must_use]
 extern "C" fn InMemorySigner_Sign_channel_keys_id(this_arg: *const c_void) -> crate::c_types::ThirtyTwoBytes {
-       let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }.channel_keys_id();
+       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 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 = unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }.sign_counterparty_commitment(unsafe { &*commitment_tx.inner }, &bitcoin::secp256k1::Secp256k1::new());
+       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 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 = unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }.sign_holder_commitment_and_htlcs(unsafe { &*commitment_tx.inner }, &bitcoin::secp256k1::Secp256k1::new());
+       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 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 nativeInMemorySigner) }.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 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 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 = unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }.sign_counterparty_htlc_transaction(&htlc_tx.into_bitcoin(), input, amount, &per_commitment_point.into_rust(), unsafe { &*htlc.inner }, &bitcoin::secp256k1::Secp256k1::new());
+       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 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 = unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }.sign_closing_transaction(&closing_tx.into_bitcoin(), &bitcoin::secp256k1::Secp256k1::new());
+       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 InMemorySigner_Sign_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 nativeInMemorySigner) }.sign_channel_announcement(unsafe { &*msg.inner }, &bitcoin::secp256k1::Secp256k1::new());
+       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 InMemorySigner_Sign_ready_channel(this_arg: *mut c_void, channel_parameters: &crate::ln::chan_utils::ChannelTransactionParameters) {
-       unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }.ready_channel(unsafe { &*channel_parameters.inner })
+       <nativeInMemorySigner as SignTraitImport<>>::ready_channel(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, unsafe { &*channel_parameters.inner })
 }
 
 #[no_mangle]
@@ -1176,8 +1176,8 @@ pub extern "C" fn KeysManager_new(seed: *const [u8; 32], mut starting_time_secs:
        KeysManager { inner: Box::into_raw(Box::new(ret)), is_owned: true }
 }
 
-/// Derive an old set of Sign 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
 /// 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.
@@ -1204,7 +1204,7 @@ pub extern "C" fn KeysManager_derive_channel_keys(this_arg: &KeysManager, mut ch
 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, &bitcoin::secp256k1::Secp256k1::new());
+       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
 }
@@ -1235,32 +1235,32 @@ pub extern "C" fn KeysManager_as_KeysInterface(this_arg: &KeysManager) -> crate:
 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_signer(this_arg: *const c_void, mut _inbound: bool, mut channel_value_satoshis: u64) -> crate::chain::keysinterface::Sign {
-       let mut ret = unsafe { &mut *(this_arg as *mut nativeKeysManager) }.get_channel_signer(_inbound, channel_value_satoshis);
+       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 = unsafe { &mut *(this_arg as *mut nativeKeysManager) }.read_chan_signer(reader.to_slice());
+       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 ad02608bcbef32e07616ebc37d18312edc934d66..fb72263f39c45ee5dcc6110d4f50384d3bb75712 100644 (file)
@@ -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.
 ///
index 4a73e5d01e0f4e6ea79db2e9161299388ec15b62..a32feb6e21442f0acab40ca2034ec926b9115493 100644 (file)
@@ -19,7 +19,7 @@ pub extern "C" fn build_commitment_secret(commitment_seed: *const [u8; 32], mut
 /// 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_SecretKeyErrorZ {
-       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 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,7 +32,7 @@ pub extern "C" fn derive_private_key(mut per_commitment_point: crate::c_types::P
 /// 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_PublicKeyErrorZ {
-       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 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,7 +48,7 @@ pub extern "C" fn derive_public_key(mut per_commitment_point: crate::c_types::Pu
 /// 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_SecretKeyErrorZ {
-       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 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,7 +66,7 @@ pub extern "C" fn derive_private_revocation_key(per_commitment_secret: *const [u
 /// 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_PublicKeyErrorZ {
-       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 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
 }
@@ -380,7 +380,7 @@ pub extern "C" fn ChannelPublicKeys_read(ser: crate::c_types::u8slice) -> crate:
 #[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(&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 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
 }
@@ -390,7 +390,7 @@ pub extern "C" fn TxCreationKeys_derive_new(mut per_commitment_point: crate::c_t
 #[must_use]
 #[no_mangle]
 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 }, &bitcoin::secp256k1::Secp256k1::new());
+       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
 }
@@ -1140,7 +1140,7 @@ pub extern "C" fn BuiltCommitmentTransaction_get_sighash_all(this_arg: &BuiltCom
 #[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, &bitcoin::secp256k1::Secp256k1::new());
+       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)
 }
 
@@ -1273,7 +1273,7 @@ pub extern "C" fn CommitmentTransaction_trust(this_arg: &CommitmentTransaction)
 #[must_use]
 #[no_mangle]
 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 }, &bitcoin::secp256k1::Secp256k1::new());
+       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
 }
@@ -1352,7 +1352,7 @@ pub extern "C" fn TrustedCommitmentTransaction_keys(this_arg: &TrustedCommitment
 #[must_use]
 #[no_mangle]
 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 }, &bitcoin::secp256k1::Secp256k1::new());
+       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
 }
index 1aa7282ac112d065f2cd2cae0fec1decd2d56fa2..a175a2ce917a8ceeca8bdb96efc88c73f0a145e9 100644 (file)
@@ -707,7 +707,7 @@ pub extern "C" fn ChannelManager_as_MessageSendEventsProvider(this_arg: &Channel
 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 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()
 }
@@ -733,11 +733,38 @@ pub extern "C" fn ChannelManager_as_EventsProvider(this_arg: &ChannelManager) ->
 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 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) {
@@ -804,66 +831,66 @@ pub extern "C" fn ChannelManager_as_ChannelMessageHandler(this_arg: &ChannelMana
 }
 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_inner()) }, 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_inner()) }, 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 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()
 }
index dd60efa03c1a480d8cb41d00d6a7d28fb2529462..4425e24cbb6deba2d6920b20c3328004b7d1a0e6 100644 (file)
@@ -4123,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.
@@ -4181,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 })
index 157dbc4225e9ab0a559bdbe2f14c2b316252ceb0..51d92a18c80795ae3e78574eae2ce48fa1686ccd 100644 (file)
@@ -220,69 +220,69 @@ pub extern "C" fn NetGraphMsgHandler_as_RoutingMessageHandler(this_arg: &NetGrap
 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 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 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 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 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 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) {
-       unsafe { &mut *(this_arg as *mut nativeNetGraphMsgHandler) }.sync_routing_table(&their_node_id.into_rust(), unsafe { &*init_msg.inner })
+       <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 = unsafe { &mut *(this_arg as *mut nativeNetGraphMsgHandler) }.handle_reply_channel_range(&their_node_id.into_rust(), *unsafe { Box::from_raw(msg.take_inner()) });
+       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 = unsafe { &mut *(this_arg as *mut nativeNetGraphMsgHandler) }.handle_reply_short_channel_ids_end(&their_node_id.into_rust(), *unsafe { Box::from_raw(msg.take_inner()) });
+       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 = unsafe { &mut *(this_arg as *mut nativeNetGraphMsgHandler) }.handle_query_channel_range(&_their_node_id.into_rust(), *unsafe { Box::from_raw(_msg.take_inner()) });
+       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 = unsafe { &mut *(this_arg as *mut nativeNetGraphMsgHandler) }.handle_query_short_channel_ids(&_their_node_id.into_rust(), *unsafe { Box::from_raw(_msg.take_inner()) });
+       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 = unsafe { &mut *(this_arg as *mut nativeNetGraphMsgHandler) }.get_and_clear_pending_msg_events();
+       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()
 }
@@ -308,7 +308,7 @@ pub extern "C" fn NetGraphMsgHandler_as_MessageSendEventsProvider(this_arg: &Net
 use lightning::util::events::MessageSendEventsProvider as MessageSendEventsProviderTraitImport;
 #[must_use]
 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 = unsafe { &mut *(this_arg as *mut nativeNetGraphMsgHandler) }.get_and_clear_pending_msg_events();
+       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()
 }
@@ -1023,7 +1023,7 @@ pub extern "C" fn NetworkGraph_new(mut genesis_hash: crate::c_types::ThirtyTwoBy
 #[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 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
 }
@@ -1052,7 +1052,7 @@ 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 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
 }
@@ -1090,7 +1090,7 @@ 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 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
 }
index 9165388066da3082f6e427bb6664c3dcb08bd2ff..587fe1b12a913798c5cf6e2511a82f1f4f9336ef 100644 (file)
@@ -10,7 +10,7 @@ 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 = "1.0", features = [ "io-util", "macros", "rt", "sync", "net", "time" ] }
 
index d8be01c926b5d649b7f5955dbab14a325c63e2d4..fa71dc0d4dd9e9e0ac67e0acfd0014abd2aa8215 100644 (file)
@@ -8,7 +8,7 @@ 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"
 
@@ -16,7 +16,7 @@ libc = "0.2"
 winapi = { version = "0.3", features = ["winbase"] }
 
 [dev-dependencies.bitcoin]
-version = "0.24"
+version = "0.26"
 features = ["bitcoinconsensus"]
 
 [dev-dependencies]
index 6f414a09f8df80f8fc7b83b73fc24f691fb30890..2226bcba6095373f7ae3dc2f7b3db2f7cf5e034c 100644 (file)
@@ -17,6 +17,7 @@ use lightning::util::logger::Logger;
 use lightning::util::ser::Writeable;
 use std::fs;
 use std::io::Error;
+use std::path::PathBuf;
 use std::sync::Arc;
 
 #[cfg(test)]
@@ -75,6 +76,12 @@ impl FilesystemPersister {
                self.path_to_channel_data.clone()
        }
 
+       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>(
@@ -88,54 +95,55 @@ impl FilesystemPersister {
              F: FeeEstimator,
              L: Logger
        {
-               util::write_to_file(data_dir, "manager".to_string(), manager)
+               let path = PathBuf::from(data_dir);
+               util::write_to_file(path, "manager".to_string(), manager)
        }
 
        #[cfg(test)]
        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_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 {
+                       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<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);
+                               if let Ok((_, loaded_monitor)) =
+                                       <(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<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_channel_data.clone(), filename, monitor)
+               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<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr> {
                let filename = format!("{}_{}", funding_txo.txid.to_hex(), funding_txo.index);
-               util::write_to_file(self.path_to_channel_data.clone(), filename, monitor)
+               util::write_to_file(self.path_to_monitor_data(), filename, monitor)
                  .map_err(|_| ChannelMonitorUpdateErr::PermanentFailure)
        }
 }
index daacb00f0cc3856449ead179c15554ae0c1a5a72..1825980ad891fcb257cdaf956150a526ac5e326d 100644 (file)
@@ -17,10 +17,9 @@ pub(crate) trait DiskWriteable {
        fn write_to_file(&self, writer: &mut fs::File) -> Result<(), std::io::Error>;
 }
 
-pub(crate) fn get_full_filepath(filepath: String, filename: String) -> String {
-       let mut path = PathBuf::from(filepath);
-       path.push(filename);
-       path.to_str().unwrap().to_string()
+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")]
@@ -40,7 +39,7 @@ fn path_to_windows_str<T: AsRef<OsStr>>(path: T) -> Vec<winapi::shared::ntdef::W
 }
 
 #[allow(bare_trait_objects)]
-pub(crate) fn write_to_file<D: DiskWriteable>(path: String, filename: String, data: &D) -> std::io::Result<()> {
+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
@@ -92,6 +91,7 @@ mod tests {
        use std::fs;
        use std::io;
        use std::io::Write;
+       use std::path::PathBuf;
 
        struct TestWriteable{}
        impl DiskWriteable for TestWriteable {
@@ -113,7 +113,7 @@ mod tests {
                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(path.to_string(), filename, &test_writeable) {
+               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")
                }
@@ -131,10 +131,10 @@ mod tests {
        fn test_rename_failure() {
                let test_writeable = TestWriteable{};
                let filename = "test_rename_failure_filename";
-               let path = "test_rename_failure_dir";
+               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.to_string(), filename.to_string())).unwrap();
-               match write_to_file(path.to_string(), filename.to_string(), &test_writeable) {
+               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(())")
                }
@@ -151,9 +151,9 @@ mod tests {
                }
 
                let filename = "test_diskwriteable_failure";
-               let path = "test_diskwriteable_failure_dir";
+               let path = PathBuf::from("test_diskwriteable_failure_dir");
                let test_writeable = FailingWriteable{};
-               match write_to_file(path.to_string(), filename.to_string(), &test_writeable) {
+               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");
@@ -170,7 +170,7 @@ mod tests {
        fn test_tmp_file_creation_failure() {
                let test_writeable = TestWriteable{};
                let filename = "test_tmp_file_creation_failure_filename".to_string();
-               let path = "test_tmp_file_creation_failure_dir".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()));
index 0b51a3992731636736917d3ebcde7e37215d5b38..f02813bfd3c2bbfa64365aef65f128cf77ec130c 100644 (file)
@@ -27,13 +27,13 @@ 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]
index 4cb9128d92fdbd826bf92f2cd62c5a25cd401dff..de826d054d3716bd41df35e03706ac3e900c1322 100644 (file)
@@ -43,7 +43,7 @@ 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.
@@ -64,7 +64,7 @@ pub struct ChainMonitor<ChannelSigner: Sign, C: Deref, T: Deref, F: Deref, L: De
         P::Target: channelmonitor::Persist<ChannelSigner>,
 {
        /// The monitors
-       pub monitors: Mutex<HashMap<OutPoint, ChannelMonitor<ChannelSigner>>>,
+       pub monitors: RwLock<HashMap<OutPoint, ChannelMonitor<ChannelSigner>>>,
        chain_source: Option<C>,
        broadcaster: T,
        logger: L,
@@ -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,
@@ -177,7 +177,7 @@ where C::Target: chain::Filter,
        ///
        /// [`chain::Filter`]: ../trait.Filter.html
        fn watch_channel(&self, funding_outpoint: OutPoint, monitor: ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr> {
-               let mut monitors = self.monitors.lock().unwrap();
+               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");
@@ -209,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");
 
@@ -222,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);
                                }
@@ -245,8 +245,8 @@ 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
        }
@@ -261,8 +261,8 @@ impl<ChannelSigner: Sign, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref> even
 {
        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 71490dd6e0e1af4de7b19b71e8699da47d5c2f46..034854810c6c0c885364091bb2b4ce0d96ca62e5 100644 (file)
@@ -50,11 +50,11 @@ use util::ser::{Readable, ReadableArgs, MaybeReadable, Writer, Writeable, U48};
 use util::byte_utils;
 use util::events::Event;
 
-use std::cell::RefCell;
 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.
@@ -626,6 +626,13 @@ impl Readable for ChannelMonitorUpdateStep {
 /// 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,
 
@@ -724,6 +731,17 @@ pub struct ChannelMonitor<Signer: Sign> {
 /// Used only in testing and fuzztarget to check serialization roundtrips don't change the
 /// underlying object
 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 ||
@@ -770,6 +788,12 @@ impl<Signer: Sign> Writeable for ChannelMonitor<Signer> {
                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:
@@ -951,7 +975,7 @@ impl<Signer: Sign> Writeable for ChannelMonitor<Signer> {
 }
 
 impl<Signer: Sign> ChannelMonitor<Signer> {
-       pub(crate) fn new(keys: Signer, shutdown_pubkey: &PublicKey,
+       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,
@@ -972,8 +996,6 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
                let channel_keys_id = keys.channel_keys_id();
                let holder_revocation_basepoint = keys.pubkeys().revocation_basepoint;
 
-               let secp_ctx = Secp256k1::new();
-
                // block for Rust 1.34 compat
                let (holder_commitment_tx, current_holder_commitment_number) = {
                        let trusted_tx = initial_holder_commitment_tx.trust();
@@ -994,60 +1016,262 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
                };
 
                let onchain_tx_handler =
-                       OnchainTxHandler::new(destination_script.clone(), keys, channel_parameters.clone(), initial_holder_commitment_tx);
+                       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,
 
-                       channel_keys_id,
-                       holder_revocation_basepoint,
-                       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: counterparty_channel_parameters.selected_contest_delay,
+                               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,
+                               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,
+                               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).
@@ -1099,10 +1323,6 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
                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<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.
@@ -1179,7 +1399,7 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
 
        /// 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,
@@ -1232,10 +1452,6 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
                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,
@@ -1288,21 +1504,14 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
                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
@@ -1313,22 +1522,12 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
                &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);
@@ -1716,15 +1915,6 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
                (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;
@@ -1750,11 +1940,8 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
                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!");
                let commitment_tx = self.onchain_tx_handler.get_fully_signed_copy_holder_tx(&self.funding_redeemscript);
                let txid = commitment_tx.txid();
@@ -1776,17 +1963,6 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
                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,
@@ -1908,8 +2084,6 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
                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,
@@ -2299,7 +2473,7 @@ pub trait Persist<ChannelSigner: Sign>: Send + Sync {
        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 (RefCell<ChannelMonitor<Signer>>, T, F, L)
+impl<Signer: Sign, T: Deref, F: Deref, L: Deref> chain::Listen for (ChannelMonitor<Signer>, T, F, L)
 where
        T::Target: BroadcasterInterface,
        F::Target: FeeEstimator,
@@ -2307,11 +2481,11 @@ where
 {
        fn block_connected(&self, block: &Block, height: u32) {
                let txdata: Vec<_> = block.txdata.iter().enumerate().collect();
-               self.0.borrow_mut().block_connected(&block.header, &txdata, height, &*self.1, &*self.2, &*self.3);
+               self.0.block_connected(&block.header, &txdata, height, &*self.1, &*self.2, &*self.3);
        }
 
        fn block_disconnected(&self, header: &BlockHeader, height: u32) {
-               self.0.borrow_mut().block_disconnected(header, height, &*self.1, &*self.2, &*self.3);
+               self.0.block_disconnected(header, height, &*self.1, &*self.2, &*self.3);
        }
 }
 
@@ -2558,52 +2732,57 @@ impl<'a, Signer: Sign, K: KeysInterface<Signer = Signer>> ReadableArgs<&'a K>
                let lockdown_from_offchain = Readable::read(reader)?;
                let holder_tx_signed = Readable::read(reader)?;
 
+               let mut secp_ctx = Secp256k1::new();
+               secp_ctx.seeded_randomize(&keys_manager.get_secure_random_bytes());
+
                Ok((last_block_hash.clone(), ChannelMonitor {
-                       latest_update_id,
-                       commitment_transaction_number_obscure_factor,
+                       inner: Mutex::new(ChannelMonitorImpl {
+                               latest_update_id,
+                               commitment_transaction_number_obscure_factor,
 
-                       destination_script,
-                       broadcasted_holder_revokable_script,
-                       counterparty_payment_script,
-                       shutdown_script,
+                               destination_script,
+                               broadcasted_holder_revokable_script,
+                               counterparty_payment_script,
+                               shutdown_script,
 
-                       channel_keys_id,
-                       holder_revocation_basepoint,
-                       funding_info,
-                       current_counterparty_commitment_txid,
-                       prev_counterparty_commitment_txid,
+                               channel_keys_id,
+                               holder_revocation_basepoint,
+                               funding_info,
+                               current_counterparty_commitment_txid,
+                               prev_counterparty_commitment_txid,
 
-                       counterparty_tx_cache,
-                       funding_redeemscript,
-                       channel_value_satoshis,
-                       their_cur_revocation_points,
+                               counterparty_tx_cache,
+                               funding_redeemscript,
+                               channel_value_satoshis,
+                               their_cur_revocation_points,
 
-                       on_holder_tx_csv,
+                               on_holder_tx_csv,
 
-                       commitment_secrets,
-                       counterparty_claimable_outpoints,
-                       counterparty_commitment_txn_on_chain,
-                       counterparty_hash_commitment_number,
+                               commitment_secrets,
+                               counterparty_claimable_outpoints,
+                               counterparty_commitment_txn_on_chain,
+                               counterparty_hash_commitment_number,
 
-                       prev_holder_signed_commitment_tx,
-                       current_holder_commitment_tx,
-                       current_counterparty_commitment_number,
-                       current_holder_commitment_number,
+                               prev_holder_signed_commitment_tx,
+                               current_holder_commitment_tx,
+                               current_counterparty_commitment_number,
+                               current_holder_commitment_number,
 
-                       payment_preimages,
-                       pending_monitor_events,
-                       pending_events,
+                               payment_preimages,
+                               pending_monitor_events,
+                               pending_events,
 
-                       onchain_events_waiting_threshold_conf,
-                       outputs_to_watch,
+                               onchain_events_waiting_threshold_conf,
+                               outputs_to_watch,
 
-                       onchain_tx_handler,
+                               onchain_tx_handler,
 
-                       lockdown_from_offchain,
-                       holder_tx_signed,
+                               lockdown_from_offchain,
+                               holder_tx_signed,
 
-                       last_block_hash,
-                       secp_ctx: Secp256k1::new(),
+                               last_block_hash,
+                               secp_ctx,
+                       }),
                }))
        }
 }
@@ -2681,7 +2860,7 @@ 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));
                                }
                        }
                }
@@ -2718,12 +2897,12 @@ mod tests {
                };
                // 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()),
-                                                     &channel_parameters,
-                                                     Script::new(), 46, 0,
-                                                     HolderCommitmentTransaction::dummy());
+               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();
@@ -2739,14 +2918,14 @@ 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);
 
@@ -2755,7 +2934,7 @@ mod tests {
                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);
 
@@ -2763,7 +2942,7 @@ mod tests {
                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);
        }
 
index 9d3b955861dbfca672fabf614ab4378f58aaa6a7..89557b43670202f700c38939c3ff5506bb44b63e 100644 (file)
@@ -744,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,
@@ -794,33 +796,38 @@ 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 Sign 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
        /// 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.
@@ -1017,7 +1024,7 @@ impl KeysInterface for KeysManager {
        }
 
        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");
index 7310a49aef53ac6f1432df78c0e04103002836ab..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
index 8fc773f68ae2f20e718b0c89c252f243572b6eb9..d764bc782152e5170f434060226d412c4156c916 100644 (file)
@@ -102,7 +102,7 @@ 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.write(&mut w).unwrap();
index 95dcde2c25c6ba1bd3210fd34a54af6a2e4cb1b6..2bbe367de75e8d8749e11216ea53d76355aad62c 100644 (file)
@@ -521,13 +521,16 @@ impl<Signer: Sign> Channel<Signer> {
 
                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,
-                       secp_ctx: Secp256k1::new(),
+                       secp_ctx,
                        channel_value_satoshis,
 
                        latest_monitor_update_id: 0,
@@ -755,13 +758,16 @@ impl<Signer: Sign> Channel<Signer> {
                        }
                } 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),
-                       secp_ctx: Secp256k1::new(),
+                       secp_ctx,
 
                        latest_monitor_update_id: 0,
 
@@ -1564,13 +1570,13 @@ impl<Signer: Sign> Channel<Signer> {
                let funding_redeemscript = self.get_funding_redeemscript();
                let funding_txo_script = funding_redeemscript.to_v0_p2wsh();
                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 mut channel_monitor = ChannelMonitor::new(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 = 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);
 
                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);
 
@@ -1634,13 +1640,13 @@ impl<Signer: Sign> Channel<Signer> {
                let funding_txo = self.get_funding_txo().unwrap();
                let funding_txo_script = funding_redeemscript.to_v0_p2wsh();
                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 mut channel_monitor = ChannelMonitor::new(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 = 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);
 
                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);
 
@@ -4081,7 +4087,8 @@ impl<Signer: Sign> Channel<Signer> {
                        signature = res.0;
                        htlc_signatures = res.1;
 
-                       log_trace!(logger, "Signed remote commitment tx {} with redeemscript {} -> {}",
+                       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()[..]));
@@ -4608,13 +4615,16 @@ impl<'a, Signer: Sign, K: Deref> ReadableArgs<&'a K> for Channel<Signer>
                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,
-                       secp_ctx: Secp256k1::new(),
+                       secp_ctx,
                        channel_value_satoshis,
 
                        latest_monitor_update_id,
index 7af34e86e9b5c383a20ea84c790cfe557a936c24..0eca37f2c9faa3e2f38a26b77ec299df1478b0bb 100644 (file)
@@ -766,7 +766,8 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
        /// 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(),
@@ -4129,6 +4130,9 @@ impl<'a, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
 
                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,
@@ -4137,7 +4141,7 @@ impl<'a, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
 
                        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,
index 219417d562f2cbd6a503510f9725594487e90c3d..f0937817bdccd1fba55753efd95202a89ed67ec1 100644 (file)
@@ -168,7 +168,7 @@ 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.write(&mut w).unwrap();
@@ -305,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;
index ea33bb561444bf3048141844e619b14f2959ea70..fdf5d2006754930276c70ad0c802df4a8c6a6348 100644 (file)
@@ -3517,8 +3517,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);
@@ -4314,7 +4314,7 @@ 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.write(&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 };
@@ -4423,7 +4423,7 @@ 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.write(&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();
@@ -4515,7 +4515,7 @@ 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.write(&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 };
@@ -4572,7 +4572,7 @@ fn test_manager_serialize_deserialize_inconsistent_monitor() {
        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.write(&mut writer).unwrap();
                node_0_stale_monitors_serialized.push(writer.0);
@@ -4591,7 +4591,7 @@ 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.write(&mut writer).unwrap();
                node_0_monitors_serialized.push(writer.0);
@@ -7479,7 +7479,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.write(&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);
@@ -8226,10 +8226,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());
                }
        }
 }
@@ -8360,7 +8360,7 @@ 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.write(&mut w).unwrap();
@@ -8419,7 +8419,7 @@ 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.write(&mut w).unwrap();
@@ -8445,7 +8445,7 @@ 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.write(&mut w).unwrap();
index 7228a687aca6eee88a670ab35a46bba3bb77443c..f3d8b2e9489d5078dc79dbc42be835fa54fe56f5 100644 (file)
@@ -406,6 +406,9 @@ impl<'a, K: KeysInterface> ReadableArgs<&'a K> for OnchainTxHandler<K::Signer> {
                }
                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,
@@ -418,13 +421,13 @@ impl<'a, K: KeysInterface> ReadableArgs<&'a K> for OnchainTxHandler<K::Signer> {
                        pending_claim_requests,
                        onchain_events_waiting_threshold_conf,
                        latest_height,
-                       secp_ctx: Secp256k1::new(),
+                       secp_ctx,
                })
        }
 }
 
 impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
-       pub(crate) fn new(destination_script: Script, signer: ChannelSigner, channel_parameters: ChannelTransactionParameters, holder_commitment: HolderCommitmentTransaction) -> Self {
+       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,
@@ -438,7 +441,7 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                        onchain_events_waiting_threshold_conf: HashMap::new(),
                        latest_height: 0,
 
-                       secp_ctx: Secp256k1::new(),
+                       secp_ctx,
                }
        }
 
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 6edd954152a0385c4733427985a580fd2ba11343..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,
 }
 
@@ -242,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
index ab2b6ceea797235e149d7a8b6a2e50103f45494a..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())
        }
 }
 
index 1d24e26408fba830603cb3f95b9b4bbd20354d57..b718e228c93e8233ce799e7fa10c90b26cd89b9d 100644 (file)
@@ -707,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),
                                }
                        }
                }
index afc6e598e76edccffdfe022c04d693a6f78ad0d6..9f87795e31e7b5a1dbcf86f8468671a2b6c7b9a6 100644 (file)
@@ -69,7 +69,7 @@ impl keysinterface::KeysInterface for OnlyReadsKeysInterface {
        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] { 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))
@@ -133,7 +133,7 @@ impl<'a> chain::Watch<EnforcingSigner> 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.write(&mut w).unwrap();
@@ -253,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,
+               }
        }
 }
 
@@ -266,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,