From: Matt Corallo <649246+TheBlueMatt@users.noreply.github.com> Date: Wed, 4 Aug 2021 22:58:14 +0000 (+0000) Subject: Merge pull request #1004 from TheBlueMatt/2021-07-forward-event X-Git-Tag: v0.0.100~10 X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=commitdiff_plain;h=69ee4860848d5992b238eca3343141004d9d1572;hp=50f47ecc05b5ade369872a8b3580301bdd977a83;p=rust-lightning Merge pull request #1004 from TheBlueMatt/2021-07-forward-event Add a `PaymentForwarded` Event --- diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index ebca7680..34337769 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -5,6 +5,7 @@ on: [push, pull_request] jobs: build: strategy: + fail-fast: false matrix: platform: [ ubuntu-latest ] toolchain: [ stable, @@ -15,8 +16,8 @@ jobs: 1.41.0, # 1.45.2 is MSRV for lightning-net-tokio, lightning-block-sync, and coverage generation 1.45.2, - # 1.49.0 is MSRV for no_std builds using hashbrown - 1.49.0] + # 1.47.0 will be the MSRV for no-std builds using hashbrown once core2 is updated + 1.47.0] include: - toolchain: stable build-net-tokio: true @@ -25,10 +26,18 @@ jobs: platform: macos-latest build-net-tokio: true build-no-std: true + - toolchain: beta + platform: macos-latest + build-net-tokio: true + build-no-std: true - toolchain: stable platform: windows-latest build-net-tokio: true build-no-std: true + - toolchain: beta + platform: windows-latest + build-net-tokio: true + build-no-std: true - toolchain: beta build-net-tokio: true build-no-std: true @@ -40,8 +49,8 @@ jobs: build-net-tokio: true build-no-std: false coverage: true - - toolchain: 1.49.0 - build-no-std: true + - toolchain: 1.47.0 + build-no-std: false runs-on: ${{ matrix.platform }} steps: - name: Checkout source code @@ -86,19 +95,19 @@ jobs: - name: Test on Rust ${{ matrix.toolchain }} with net-tokio and full code-linking for coverage generation if: matrix.coverage run: RUSTFLAGS="-C link-dead-code" cargo test --verbose --color always - - name: Test on no_std bullds Rust ${{ matrix.toolchain }} + - name: Test on no-std bullds Rust ${{ matrix.toolchain }} if: "matrix.build-no-std && !matrix.coverage" run: | cd lightning - cargo test --verbose --color always --no-default-features --features no_std - # check if there is a conflict between no_std and the default std feature - cargo test --verbose --color always --features no_std + cargo test --verbose --color always --no-default-features --features no-std + # check if there is a conflict between no-std and the default std feature + cargo test --verbose --color always --features no-std cd .. - - name: Test on no_std bullds Rust ${{ matrix.toolchain }} and full code-linking for coverage generation + - name: Test on no-std builds Rust ${{ matrix.toolchain }} and full code-linking for coverage generation if: "matrix.build-no-std && matrix.coverage" run: | cd lightning - RUSTFLAGS="-C link-dead-code" cargo test --verbose --color always --no-default-features --features no_std + RUSTFLAGS="-C link-dead-code" cargo test --verbose --color always --no-default-features --features no-std cd .. - name: Test on Rust ${{ matrix.toolchain }} if: "! matrix.build-net-tokio" @@ -261,4 +270,4 @@ jobs: rustup component add clippy - name: Run default clippy linting run: | - cargo clippy -- -Aclippy::erasing_op -Aclippy::never_loop -Aclippy::if_same_then_else + cargo clippy -- -Aclippy::erasing_op -Aclippy::never_loop -Aclippy::if_same_then_else -Dclippy::try_err diff --git a/ci/check-compiles.sh b/ci/check-compiles.sh index 79c2d92b..2bc31007 100755 --- a/ci/check-compiles.sh +++ b/ci/check-compiles.sh @@ -6,4 +6,4 @@ cargo check cargo doc cargo doc --document-private-items cd fuzz && cargo check --features=stdin_fuzz -cd ../lightning && cargo check --no-default-features --features=no_std +cd ../lightning && cargo check --no-default-features --features=no-std diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index 7c3d4206..3b6d027d 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -19,7 +19,7 @@ stdin_fuzz = [] [dependencies] afl = { version = "0.4", optional = true } lightning = { path = "../lightning", features = ["fuzztarget"] } -bitcoin = { version = "0.26", features = ["fuzztarget", "secp-lowmemory"] } +bitcoin = { version = "0.27", 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 } diff --git a/lightning-background-processor/Cargo.toml b/lightning-background-processor/Cargo.toml index 9849ac44..1659ffd3 100644 --- a/lightning-background-processor/Cargo.toml +++ b/lightning-background-processor/Cargo.toml @@ -10,7 +10,7 @@ Utilities to perform required background tasks for Rust Lightning. edition = "2018" [dependencies] -bitcoin = "0.26" +bitcoin = "0.27" lightning = { version = "0.0.99", path = "../lightning", features = ["allow_wallclock_use"] } lightning-persister = { version = "0.0.99", path = "../lightning-persister" } diff --git a/lightning-background-processor/src/lib.rs b/lightning-background-processor/src/lib.rs index 0b886f7b..55ac14c0 100644 --- a/lightning-background-processor/src/lib.rs +++ b/lightning-background-processor/src/lib.rs @@ -41,9 +41,7 @@ use std::ops::Deref; /// for unilateral chain closure fees are at risk. pub struct BackgroundProcessor { stop_thread: Arc, - /// May be used to retrieve and handle the error if `BackgroundProcessor`'s thread - /// exits due to an error while persisting. - pub thread_handle: JoinHandle>, + thread_handle: Option>>, } #[cfg(not(test))] @@ -84,21 +82,25 @@ ChannelManagerPersister for Fun where } impl BackgroundProcessor { - /// Start a background thread that takes care of responsibilities enumerated in the top-level - /// documentation. + /// Start a background thread that takes care of responsibilities enumerated in the [top-level + /// documentation]. /// - /// If `persist_manager` returns an error, then this thread will return said error (and - /// `start()` will need to be called again to restart the `BackgroundProcessor`). Users should - /// wait on [`thread_handle`]'s `join()` method to be able to tell if and when an error is - /// returned, or implement `persist_manager` such that an error is never returned to the - /// `BackgroundProcessor` + /// The thread runs indefinitely unless the object is dropped, [`stop`] is called, or + /// `persist_manager` returns an error. In case of an error, the error is retrieved by calling + /// either [`join`] or [`stop`]. + /// + /// Typically, users should either implement [`ChannelManagerPersister`] to never return an + /// error or call [`join`] and handle any error that may arise. For the latter case, the + /// `BackgroundProcessor` must be restarted by calling `start` again after handling the error. /// /// `persist_manager` is responsible for writing out the [`ChannelManager`] to disk, and/or /// uploading to one or more backup services. See [`ChannelManager::write`] for writing out a /// [`ChannelManager`]. See [`FilesystemPersister::persist_manager`] for Rust-Lightning's /// provided implementation. /// - /// [`thread_handle`]: BackgroundProcessor::thread_handle + /// [top-level documentation]: Self + /// [`join`]: Self::join + /// [`stop`]: Self::stop /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager /// [`ChannelManager::write`]: lightning::ln::channelmanager::ChannelManager#impl-Writeable /// [`FilesystemPersister::persist_manager`]: lightning_persister::FilesystemPersister::persist_manager @@ -158,13 +160,53 @@ impl BackgroundProcessor { } } }); - Self { stop_thread: stop_thread_clone, thread_handle: handle } + Self { stop_thread: stop_thread_clone, thread_handle: Some(handle) } + } + + /// Join `BackgroundProcessor`'s thread, returning any error that occurred while persisting + /// [`ChannelManager`]. + /// + /// # Panics + /// + /// This function panics if the background thread has panicked such as while persisting or + /// handling events. + /// + /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager + pub fn join(mut self) -> Result<(), std::io::Error> { + assert!(self.thread_handle.is_some()); + self.join_thread() + } + + /// Stop `BackgroundProcessor`'s thread, returning any error that occurred while persisting + /// [`ChannelManager`]. + /// + /// # Panics + /// + /// This function panics if the background thread has panicked such as while persisting or + /// handling events. + /// + /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager + pub fn stop(mut self) -> Result<(), std::io::Error> { + assert!(self.thread_handle.is_some()); + self.stop_and_join_thread() } - /// Stop `BackgroundProcessor`'s thread. - pub fn stop(self) -> Result<(), std::io::Error> { + fn stop_and_join_thread(&mut self) -> Result<(), std::io::Error> { self.stop_thread.store(true, Ordering::Release); - self.thread_handle.join().unwrap() + self.join_thread() + } + + fn join_thread(&mut self) -> Result<(), std::io::Error> { + match self.thread_handle.take() { + Some(handle) => handle.join().unwrap(), + None => Ok(()), + } + } +} + +impl Drop for BackgroundProcessor { + fn drop(&mut self) { + self.stop_and_join_thread().unwrap(); } } @@ -416,7 +458,13 @@ mod tests { let persister = |_: &_| Err(std::io::Error::new(std::io::ErrorKind::Other, "test")); let event_handler = |_| {}; let bg_processor = BackgroundProcessor::start(persister, event_handler, nodes[0].chain_monitor.clone(), nodes[0].node.clone(), nodes[0].peer_manager.clone(), nodes[0].logger.clone()); - let _ = bg_processor.thread_handle.join().unwrap().expect_err("Errored persisting manager: test"); + match bg_processor.join() { + Ok(_) => panic!("Expected error persisting manager"), + Err(e) => { + assert_eq!(e.kind(), std::io::ErrorKind::Other); + assert_eq!(e.get_ref().unwrap().to_string(), "test"); + }, + } } #[test] diff --git a/lightning-block-sync/Cargo.toml b/lightning-block-sync/Cargo.toml index b72d91cd..36bb5af9 100644 --- a/lightning-block-sync/Cargo.toml +++ b/lightning-block-sync/Cargo.toml @@ -14,7 +14,7 @@ rest-client = [ "serde", "serde_json", "chunked_transfer" ] rpc-client = [ "serde", "serde_json", "chunked_transfer" ] [dependencies] -bitcoin = "0.26" +bitcoin = "0.27" lightning = { version = "0.0.99", path = "../lightning" } tokio = { version = "1.0", features = [ "io-util", "net", "time" ], optional = true } serde = { version = "1.0", features = ["derive"], optional = true } diff --git a/lightning-block-sync/src/http.rs b/lightning-block-sync/src/http.rs index 89054a23..0721babf 100644 --- a/lightning-block-sync/src/http.rs +++ b/lightning-block-sync/src/http.rs @@ -636,7 +636,10 @@ pub(crate) mod client_tests { #[test] fn connect_to_unresolvable_host() { match HttpClient::connect(("example.invalid", 80)) { - Err(e) => assert_eq!(e.kind(), std::io::ErrorKind::Other), + Err(e) => { + assert!(e.to_string().contains("failed to lookup address information") || + e.to_string().contains("No such host"), "{:?}", e); + }, Ok(_) => panic!("Expected error"), } } diff --git a/lightning-invoice/Cargo.toml b/lightning-invoice/Cargo.toml index ae37382f..404f12d7 100644 --- a/lightning-invoice/Cargo.toml +++ b/lightning-invoice/Cargo.toml @@ -9,11 +9,11 @@ keywords = [ "lightning", "bitcoin", "invoice", "BOLT11" ] readme = "README.md" [dependencies] -bech32 = "0.7" +bech32 = "0.8" lightning = { version = "0.0.99", path = "../lightning" } secp256k1 = { version = "0.20", features = ["recovery"] } num-traits = "0.2.8" -bitcoin_hashes = "0.9.4" +bitcoin_hashes = "0.10" [dev-dependencies] lightning = { version = "0.0.99", path = "../lightning", features = ["_test_utils"] } diff --git a/lightning-invoice/fuzz/Cargo.toml b/lightning-invoice/fuzz/Cargo.toml index 68a0d4e0..eb583a41 100644 --- a/lightning-invoice/fuzz/Cargo.toml +++ b/lightning-invoice/fuzz/Cargo.toml @@ -15,7 +15,7 @@ honggfuzz_fuzz = ["honggfuzz"] honggfuzz = { version = "0.5", optional = true } afl = { version = "0.4", optional = true } lightning-invoice = { path = ".."} -bech32 = "0.7" +bech32 = "0.8" # Prevent this from interfering with workspaces [workspace] diff --git a/lightning-invoice/src/de.rs b/lightning-invoice/src/de.rs index 9c5120e4..dbcb74e0 100644 --- a/lightning-invoice/src/de.rs +++ b/lightning-invoice/src/de.rs @@ -250,7 +250,13 @@ impl FromStr for SignedRawInvoice { type Err = ParseError; fn from_str(s: &str) -> Result { - let (hrp, data) = bech32::decode(s)?; + let (hrp, data, var) = bech32::decode(s)?; + + if var == bech32::Variant::Bech32m { + // Consider Bech32m addresses to be "Invalid Checksum", since that is what we'd get if + // we didn't support Bech32m (which lightning does not use). + return Err(ParseError::Bech32Error(bech32::Error::InvalidChecksum)); + } if data.len() < 104 { return Err(ParseError::TooShortDataPart); diff --git a/lightning-invoice/src/ser.rs b/lightning-invoice/src/ser.rs index 5c7b4aa8..7d9ca9eb 100644 --- a/lightning-invoice/src/ser.rs +++ b/lightning-invoice/src/ser.rs @@ -117,7 +117,7 @@ impl Display for SignedRawInvoice { let mut data = self.raw_invoice.data.to_base32(); data.extend_from_slice(&self.signature.to_base32()); - bech32::encode_to_fmt(f, &hrp, data).expect("HRP is valid")?; + bech32::encode_to_fmt(f, &hrp, data, bech32::Variant::Bech32).expect("HRP is valid")?; Ok(()) } diff --git a/lightning-net-tokio/Cargo.toml b/lightning-net-tokio/Cargo.toml index d855529f..928eab7a 100644 --- a/lightning-net-tokio/Cargo.toml +++ b/lightning-net-tokio/Cargo.toml @@ -11,7 +11,7 @@ For Rust-Lightning clients which wish to make direct connections to Lightning P2 edition = "2018" [dependencies] -bitcoin = "0.26" +bitcoin = "0.27" lightning = { version = "0.0.99", path = "../lightning" } tokio = { version = "1.0", features = [ "io-util", "macros", "rt", "sync", "net", "time" ] } diff --git a/lightning-persister/Cargo.toml b/lightning-persister/Cargo.toml index 9ce4e8f6..81c69d0f 100644 --- a/lightning-persister/Cargo.toml +++ b/lightning-persister/Cargo.toml @@ -12,7 +12,7 @@ Utilities to manage Rust-Lightning channel data persistence and retrieval. unstable = ["lightning/unstable"] [dependencies] -bitcoin = "0.26" +bitcoin = "0.27" lightning = { version = "0.0.99", path = "../lightning" } libc = "0.2" diff --git a/lightning-persister/src/util.rs b/lightning-persister/src/util.rs index 1825980a..73b28985 100644 --- a/lightning-persister/src/util.rs +++ b/lightning-persister/src/util.rs @@ -135,7 +135,7 @@ mod tests { // Create the channel data file and make it a directory. fs::create_dir_all(get_full_filepath(path.clone(), filename.to_string())).unwrap(); match write_to_file(path.clone(), filename.to_string(), &test_writeable) { - Err(e) => assert_eq!(e.kind(), io::ErrorKind::Other), + Err(e) => assert_eq!(e.raw_os_error(), Some(libc::EISDIR)), _ => panic!("Unexpected Ok(())") } fs::remove_dir_all(path).unwrap(); @@ -178,7 +178,7 @@ mod tests { match write_to_file(path, filename, &test_writeable) { Err(e) => { #[cfg(not(target_os = "windows"))] - assert_eq!(e.kind(), io::ErrorKind::Other); + assert_eq!(e.raw_os_error(), Some(libc::EISDIR)); #[cfg(target_os = "windows")] assert_eq!(e.kind(), io::ErrorKind::PermissionDenied); } diff --git a/lightning/Cargo.toml b/lightning/Cargo.toml index 32c0d0af..8580a53a 100644 --- a/lightning/Cargo.toml +++ b/lightning/Cargo.toml @@ -26,25 +26,32 @@ max_level_debug = [] unsafe_revoked_tx_signing = [] unstable = [] -no_std = ["hashbrown"] -std = [] +no-std = ["hashbrown", "bitcoin/no-std", "core2/alloc"] +std = ["bitcoin/std"] default = ["std"] [dependencies] -bitcoin = "0.26" +bitcoin = { version = "0.27", default-features = false, features = ["secp-recovery"] } +# TODO remove this once rust-bitcoin PR #637 is released +secp256k1 = { version = "0.20.2", default-features = false, features = ["alloc"] } hashbrown = { version = "0.11", optional = true } hex = { version = "0.3", optional = true } regex = { version = "0.1.80", optional = true } +core2 = { version = "0.3.0", optional = true, default-features = false } + [dev-dependencies] hex = "0.3" regex = "0.1.80" +# TODO remove this once rust-bitcoin PR #637 is released +secp256k1 = { version = "0.20.2", default-features = false, features = ["alloc"] } [dev-dependencies.bitcoin] -version = "0.26" -features = ["bitcoinconsensus"] +version = "0.27" +default-features = false +features = ["bitcoinconsensus", "secp-recovery"] [package.metadata.docs.rs] features = ["allow_wallclock_use"] # When https://github.com/rust-lang/rust/issues/43781 complies with our MSVR, we can add nice banners in the docs for the methods behind this feature-gate. diff --git a/lightning/src/chain/channelmonitor.rs b/lightning/src/chain/channelmonitor.rs index cec3f41c..7904d9bd 100644 --- a/lightning/src/chain/channelmonitor.rs +++ b/lightning/src/chain/channelmonitor.rs @@ -53,7 +53,7 @@ use util::events::Event; use prelude::*; use core::{cmp, mem}; -use std::io::Error; +use io::{self, Error}; use core::ops::Deref; use sync::Mutex; @@ -88,7 +88,7 @@ pub struct ChannelMonitorUpdate { pub const CLOSED_CHANNEL_UPDATE_ID: u64 = core::u64::MAX; impl Writeable for ChannelMonitorUpdate { - fn write(&self, w: &mut W) -> Result<(), ::std::io::Error> { + fn write(&self, w: &mut W) -> Result<(), io::Error> { write_ver_prefix!(w, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION); self.update_id.write(w)?; (self.updates.len() as u64).write(w)?; @@ -100,7 +100,7 @@ impl Writeable for ChannelMonitorUpdate { } } impl Readable for ChannelMonitorUpdate { - fn read(r: &mut R) -> Result { + fn read(r: &mut R) -> Result { let _ver = read_ver_prefix!(r, SERIALIZATION_VERSION); let update_id: u64 = Readable::read(r)?; let len: u64 = Readable::read(r)?; @@ -295,7 +295,7 @@ struct CounterpartyCommitmentTransaction { } impl Writeable for CounterpartyCommitmentTransaction { - fn write(&self, w: &mut W) -> Result<(), ::std::io::Error> { + fn write(&self, w: &mut W) -> Result<(), io::Error> { w.write_all(&byte_utils::be64_to_array(self.per_htlc.len() as u64))?; for (ref txid, ref htlcs) in self.per_htlc.iter() { w.write_all(&txid[..])?; @@ -313,7 +313,7 @@ impl Writeable for CounterpartyCommitmentTransaction { } } impl Readable for CounterpartyCommitmentTransaction { - fn read(r: &mut R) -> Result { + fn read(r: &mut R) -> Result { let counterparty_commitment_transaction = { let per_htlc_len: u64 = Readable::read(r)?; let mut per_htlc = HashMap::with_capacity(cmp::min(per_htlc_len as usize, MAX_ALLOC_SIZE / 64)); @@ -2461,7 +2461,8 @@ impl ChannelMonitorImpl { output: outp.clone(), }); break; - } else if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script { + } + if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script { if broadcasted_holder_revokable_script.0 == outp.script_pubkey { spendable_output = Some(SpendableOutputDescriptor::DelayedPaymentOutput(DelayedPaymentOutputDescriptor { outpoint: OutPoint { txid: tx.txid(), index: i as u16 }, @@ -2474,7 +2475,8 @@ impl ChannelMonitorImpl { })); break; } - } else if self.counterparty_payment_script == outp.script_pubkey { + } + if self.counterparty_payment_script == outp.script_pubkey { spendable_output = Some(SpendableOutputDescriptor::StaticPaymentOutput(StaticPaymentOutputDescriptor { outpoint: OutPoint { txid: tx.txid(), index: i as u16 }, output: outp.clone(), @@ -2482,11 +2484,13 @@ impl ChannelMonitorImpl { channel_value_satoshis: self.channel_value_satoshis, })); break; - } else if outp.script_pubkey == self.shutdown_script { + } + if outp.script_pubkey == self.shutdown_script { spendable_output = Some(SpendableOutputDescriptor::StaticOutput { outpoint: OutPoint { txid: tx.txid(), index: i as u16 }, output: outp.clone(), }); + break; } } if let Some(spendable_output) = spendable_output { @@ -2591,7 +2595,7 @@ const MAX_ALLOC_SIZE: usize = 64*1024; impl<'a, Signer: Sign, K: KeysInterface> ReadableArgs<&'a K> for (BlockHash, ChannelMonitor) { - fn read(reader: &mut R, keys_manager: &'a K) -> Result { + fn read(reader: &mut R, keys_manager: &'a K) -> Result { macro_rules! unwrap_obj { ($key: expr) => { match $key { diff --git a/lightning/src/chain/keysinterface.rs b/lightning/src/chain/keysinterface.rs index d7ff2a63..7356dad8 100644 --- a/lightning/src/chain/keysinterface.rs +++ b/lightning/src/chain/keysinterface.rs @@ -39,7 +39,7 @@ use ln::msgs::UnsignedChannelAnnouncement; use prelude::*; use core::sync::atomic::{AtomicUsize, Ordering}; -use std::io::Error; +use io::{self, Error}; use ln::msgs::{DecodeError, MAX_VALUE_MSAT}; /// Information about a spendable output to a P2WSH script. See @@ -699,7 +699,7 @@ impl Writeable for InMemorySigner { } impl Readable for InMemorySigner { - fn read(reader: &mut R) -> Result { + fn read(reader: &mut R) -> Result { let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION); let funding_key = Readable::read(reader)?; @@ -1039,7 +1039,7 @@ impl KeysInterface for KeysManager { } fn read_chan_signer(&self, reader: &[u8]) -> Result { - InMemorySigner::read(&mut std::io::Cursor::new(reader)) + InMemorySigner::read(&mut io::Cursor::new(reader)) } fn sign_invoice(&self, invoice_preimage: Vec) -> Result { diff --git a/lightning/src/chain/onchaintx.rs b/lightning/src/chain/onchaintx.rs index cd283146..44bbfc2d 100644 --- a/lightning/src/chain/onchaintx.rs +++ b/lightning/src/chain/onchaintx.rs @@ -32,6 +32,7 @@ use util::logger::Logger; use util::ser::{Readable, ReadableArgs, Writer, Writeable, VecWriter}; use util::byte_utils; +use io; use prelude::*; use alloc::collections::BTreeMap; use core::cmp; @@ -94,7 +95,7 @@ impl_writeable_tlv_based_enum!(OnchainEvent, ;); impl Readable for Option>> { - fn read(reader: &mut R) -> Result { + fn read(reader: &mut R) -> Result { match Readable::read(reader)? { 0u8 => Ok(None), 1u8 => { @@ -115,7 +116,7 @@ impl Readable for Option>> { } impl Writeable for Option>> { - fn write(&self, writer: &mut W) -> Result<(), ::std::io::Error> { + fn write(&self, writer: &mut W) -> Result<(), io::Error> { match self { &Some(ref vec) => { 1u8.write(writer)?; @@ -191,7 +192,7 @@ const SERIALIZATION_VERSION: u8 = 1; const MIN_SERIALIZATION_VERSION: u8 = 1; impl OnchainTxHandler { - pub(crate) fn write(&self, writer: &mut W) -> Result<(), ::std::io::Error> { + pub(crate) fn write(&self, writer: &mut W) -> Result<(), io::Error> { write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION); self.destination_script.write(writer)?; @@ -242,7 +243,7 @@ impl OnchainTxHandler { } impl<'a, K: KeysInterface> ReadableArgs<&'a K> for OnchainTxHandler { - fn read(reader: &mut R, keys_manager: &'a K) -> Result { + fn read(reader: &mut R, keys_manager: &'a K) -> Result { let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION); let destination_script = Readable::read(reader)?; @@ -285,7 +286,7 @@ impl<'a, K: KeysInterface> ReadableArgs<&'a K> for OnchainTxHandler { for _ in 0..locktimed_packages_len { let locktime = Readable::read(reader)?; let packages_len: u64 = Readable::read(reader)?; - let mut packages = Vec::with_capacity(cmp::min(packages_len as usize, MAX_ALLOC_SIZE / std::mem::size_of::())); + let mut packages = Vec::with_capacity(cmp::min(packages_len as usize, MAX_ALLOC_SIZE / core::mem::size_of::())); for _ in 0..packages_len { packages.push(Readable::read(reader)?); } diff --git a/lightning/src/chain/package.rs b/lightning/src/chain/package.rs index b5c1ffdf..a86add4b 100644 --- a/lightning/src/chain/package.rs +++ b/lightning/src/chain/package.rs @@ -31,6 +31,8 @@ use util::byte_utils; use util::logger::Logger; use util::ser::{Readable, Writer, Writeable}; +use io; +use prelude::*; use core::cmp; use core::mem; use core::ops::Deref; @@ -395,8 +397,8 @@ impl PackageSolvingData { PackageSolvingData::RevokedOutput(_) => output_conf_height + 1, PackageSolvingData::RevokedHTLCOutput(_) => output_conf_height + 1, PackageSolvingData::CounterpartyOfferedHTLCOutput(_) => output_conf_height + 1, - PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => std::cmp::max(outp.htlc.cltv_expiry, output_conf_height + 1), - PackageSolvingData::HolderHTLCOutput(ref outp) => std::cmp::max(outp.cltv_expiry, output_conf_height + 1), + PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => cmp::max(outp.htlc.cltv_expiry, output_conf_height + 1), + PackageSolvingData::HolderHTLCOutput(ref outp) => cmp::max(outp.cltv_expiry, output_conf_height + 1), PackageSolvingData::HolderFundingOutput(_) => output_conf_height + 1, }; absolute_timelock @@ -682,7 +684,7 @@ impl PackageTemplate { } impl Writeable for PackageTemplate { - fn write(&self, writer: &mut W) -> Result<(), ::std::io::Error> { + fn write(&self, writer: &mut W) -> Result<(), io::Error> { writer.write_all(&byte_utils::be64_to_array(self.inputs.len() as u64))?; for (ref outpoint, ref rev_outp) in self.inputs.iter() { outpoint.write(writer)?; @@ -699,7 +701,7 @@ impl Writeable for PackageTemplate { } impl Readable for PackageTemplate { - fn read(reader: &mut R) -> Result { + fn read(reader: &mut R) -> Result { let inputs_count = ::read(reader)?; let mut inputs: Vec<(BitcoinOutPoint, PackageSolvingData)> = Vec::with_capacity(cmp::min(inputs_count as usize, MAX_ALLOC_SIZE / 128)); for _ in 0..inputs_count { diff --git a/lightning/src/lib.rs b/lightning/src/lib.rs index 14445710..e6ecd1f3 100644 --- a/lightning/src/lib.rs +++ b/lightning/src/lib.rs @@ -28,30 +28,119 @@ #![allow(bare_trait_objects)] #![allow(ellipsis_inclusive_range_patterns)] +#![cfg_attr(all(not(feature = "std"), not(test)), no_std)] + #![cfg_attr(all(any(test, feature = "_test_utils"), feature = "unstable"), feature(test))] #[cfg(all(any(test, feature = "_test_utils"), feature = "unstable"))] extern crate test; +#[cfg(not(any(feature = "std", feature = "no-std")))] +compile_error!("at least one of the `std` or `no-std` features must be enabled"); + +#[macro_use] extern crate alloc; extern crate bitcoin; +#[cfg(any(test, feature = "std"))] extern crate core; + #[cfg(any(test, feature = "_test_utils"))] extern crate hex; #[cfg(any(test, feature = "fuzztarget", feature = "_test_utils"))] extern crate regex; +#[cfg(not(feature = "std"))] extern crate core2; + #[macro_use] pub mod util; pub mod chain; pub mod ln; pub mod routing; +#[cfg(feature = "std")] +use std::io; +#[cfg(not(feature = "std"))] +use core2::io; + +#[cfg(not(feature = "std"))] +mod io_extras { + use core2::io::{self, Read, Write}; + + /// A writer which will move data into the void. + pub struct Sink { + _priv: (), + } + + /// Creates an instance of a writer which will successfully consume all data. + pub const fn sink() -> Sink { + Sink { _priv: () } + } + + impl core2::io::Write for Sink { + #[inline] + fn write(&mut self, buf: &[u8]) -> core2::io::Result { + Ok(buf.len()) + } + + #[inline] + fn flush(&mut self) -> core2::io::Result<()> { + Ok(()) + } + } + + pub fn copy(reader: &mut R, writer: &mut W) -> Result + where + R: Read, + W: Write, + { + let mut count = 0; + let mut buf = [0u8; 64]; + + loop { + match reader.read(&mut buf) { + Ok(0) => break, + Ok(n) => { writer.write_all(&buf[0..n])?; count += n as u64; }, + Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}, + Err(e) => return Err(e.into()), + }; + } + Ok(count) + } + + pub fn read_to_end(mut d: D) -> Result, io::Error> { + let mut result = vec![]; + let mut buf = [0u8; 64]; + loop { + match d.read(&mut buf) { + Ok(0) => break, + Ok(n) => result.extend_from_slice(&buf[0..n]), + Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}, + Err(e) => return Err(e.into()), + }; + } + Ok(result) + } +} + +#[cfg(feature = "std")] +mod io_extras { + pub fn read_to_end(mut d: D) -> Result, ::std::io::Error> { + let mut buf = Vec::new(); + d.read_to_end(&mut buf)?; + Ok(buf) + } + + pub use std::io::{copy, sink}; +} + mod prelude { #[cfg(feature = "hashbrown")] extern crate hashbrown; - pub use alloc::{vec, vec::Vec, string::String, collections::VecDeque}; + pub use alloc::{vec, vec::Vec, string::String, collections::VecDeque, boxed::Box}; #[cfg(not(feature = "hashbrown"))] pub use std::collections::{HashMap, HashSet, hash_map}; #[cfg(feature = "hashbrown")] pub use self::hashbrown::{HashMap, HashSet, hash_map}; + + pub use alloc::borrow::ToOwned; + pub use alloc::string::ToString; } #[cfg(feature = "std")] diff --git a/lightning/src/ln/chan_utils.rs b/lightning/src/ln/chan_utils.rs index 6e0e5085..4690d298 100644 --- a/lightning/src/ln/chan_utils.rs +++ b/lightning/src/ln/chan_utils.rs @@ -31,6 +31,7 @@ use bitcoin::secp256k1::{Secp256k1, Signature, Message}; use bitcoin::secp256k1::Error as SecpError; use bitcoin::secp256k1; +use io; use prelude::*; use core::cmp; use ln::chan_utils; @@ -167,7 +168,7 @@ impl CounterpartyCommitmentSecrets { } impl Writeable for CounterpartyCommitmentSecrets { - fn write(&self, writer: &mut W) -> Result<(), ::std::io::Error> { + fn write(&self, writer: &mut W) -> Result<(), io::Error> { for &(ref secret, ref idx) in self.old_secrets.iter() { writer.write_all(secret)?; writer.write_all(&byte_utils::be64_to_array(*idx))?; @@ -177,7 +178,7 @@ impl Writeable for CounterpartyCommitmentSecrets { } } impl Readable for CounterpartyCommitmentSecrets { - fn read(reader: &mut R) -> Result { + fn read(reader: &mut R) -> Result { let mut old_secrets = [([0; 32], 1 << 48); 49]; for &mut (ref mut secret, ref mut idx) in old_secrets.iter_mut() { *secret = Readable::read(reader)?; diff --git a/lightning/src/ln/chanmon_update_fail_tests.rs b/lightning/src/ln/chanmon_update_fail_tests.rs index c3a2f5af..720190ec 100644 --- a/lightning/src/ln/chanmon_update_fail_tests.rs +++ b/lightning/src/ln/chanmon_update_fail_tests.rs @@ -40,6 +40,7 @@ use ln::functional_test_utils::*; use util::test_utils; +use io; use prelude::*; use sync::{Arc, Mutex}; @@ -122,7 +123,7 @@ fn test_monitor_and_persister_update_fail() { let mut w = test_utils::TestVecWriter(Vec::new()); monitor.write(&mut w).unwrap(); let new_monitor = <(BlockHash, ChannelMonitor)>::read( - &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1; + &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1; assert!(new_monitor == *monitor); let chain_mon = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager); assert!(chain_mon.watch_channel(outpoint, new_monitor).is_ok()); diff --git a/lightning/src/ln/channel.rs b/lightning/src/ln/channel.rs index b9a63f1c..f80377b7 100644 --- a/lightning/src/ln/channel.rs +++ b/lightning/src/ln/channel.rs @@ -41,6 +41,7 @@ use util::errors::APIError; use util::config::{UserConfig,ChannelConfig}; use util::scid_utils::scid_from_parts; +use io; use prelude::*; use core::{cmp,mem,fmt}; use core::ops::Deref; @@ -4522,7 +4523,7 @@ impl_writeable_tlv_based_enum!(InboundHTLCRemovalReason,; ); impl Writeable for ChannelUpdateStatus { - fn write(&self, writer: &mut W) -> Result<(), ::std::io::Error> { + fn write(&self, writer: &mut W) -> Result<(), io::Error> { // We only care about writing out the current state as it was announced, ie only either // Enabled or Disabled. In the case of DisabledStaged, we most recently announced the // channel as enabled, so we write 0. For EnabledStaged, we similarly write a 1. @@ -4537,7 +4538,7 @@ impl Writeable for ChannelUpdateStatus { } impl Readable for ChannelUpdateStatus { - fn read(reader: &mut R) -> Result { + fn read(reader: &mut R) -> Result { Ok(match ::read(reader)? { 0 => ChannelUpdateStatus::Enabled, 1 => ChannelUpdateStatus::Disabled, @@ -4547,7 +4548,7 @@ impl Readable for ChannelUpdateStatus { } impl Writeable for Channel { - fn write(&self, writer: &mut W) -> Result<(), ::std::io::Error> { + fn write(&self, writer: &mut W) -> Result<(), io::Error> { // Note that we write out as if remove_uncommitted_htlcs_and_mark_paused had just been // called. @@ -4780,7 +4781,7 @@ impl Writeable for Channel { const MAX_ALLOC_SIZE: usize = 64*1024; impl<'a, Signer: Sign, K: Deref> ReadableArgs<&'a K> for Channel where K::Target: KeysInterface { - fn read(reader: &mut R, keys_source: &'a K) -> Result { + fn read(reader: &mut R, keys_source: &'a K) -> Result { let ver = read_ver_prefix!(reader, SERIALIZATION_VERSION); let user_id = Readable::read(reader)?; diff --git a/lightning/src/ln/channelmanager.rs b/lightning/src/ln/channelmanager.rs index ad9a7e29..afbfd0ee 100644 --- a/lightning/src/ln/channelmanager.rs +++ b/lightning/src/ln/channelmanager.rs @@ -60,10 +60,11 @@ use util::chacha20::{ChaCha20, ChaChaReader}; use util::logger::{Logger, Level}; use util::errors::APIError; +use io; use prelude::*; use core::{cmp, mem}; use core::cell::RefCell; -use std::io::{Cursor, Read}; +use io::{Cursor, Read}; use sync::{Arc, Condvar, Mutex, MutexGuard, RwLock, RwLockReadGuard}; use core::sync::atomic::{AtomicUsize, Ordering}; use core::time::Duration; @@ -4029,7 +4030,7 @@ where result = NotifyOption::DoPersist; } - let mut pending_events = std::mem::replace(&mut *self.pending_events.lock().unwrap(), vec![]); + let mut pending_events = mem::replace(&mut *self.pending_events.lock().unwrap(), vec![]); if !pending_events.is_empty() { result = NotifyOption::DoPersist; } @@ -4649,7 +4650,7 @@ impl_writeable_tlv_based!(HTLCPreviousHopData, { }); impl Writeable for ClaimableHTLC { - fn write(&self, writer: &mut W) -> Result<(), ::std::io::Error> { + fn write(&self, writer: &mut W) -> Result<(), io::Error> { let payment_data = match &self.onion_payload { OnionPayload::Invoice(data) => Some(data.clone()), _ => None, @@ -4753,7 +4754,7 @@ impl Writeable f F::Target: FeeEstimator, L::Target: Logger, { - fn write(&self, writer: &mut W) -> Result<(), ::std::io::Error> { + fn write(&self, writer: &mut W) -> Result<(), io::Error> { let _consistency_lock = self.total_consistency_lock.write().unwrap(); write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION); @@ -4949,7 +4950,7 @@ impl<'a, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> F::Target: FeeEstimator, L::Target: Logger, { - fn read(reader: &mut R, args: ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>) -> Result { + fn read(reader: &mut R, args: ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>) -> Result { let (blockhash, chan_manager) = <(BlockHash, ChannelManager)>::read(reader, args)?; Ok((blockhash, Arc::new(chan_manager))) } @@ -4963,7 +4964,7 @@ impl<'a, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> F::Target: FeeEstimator, L::Target: Logger, { - fn read(reader: &mut R, mut args: ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>) -> Result { + fn read(reader: &mut R, mut args: ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>) -> Result { let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION); let genesis_hash: BlockHash = Readable::read(reader)?; @@ -5153,10 +5154,8 @@ impl<'a, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> mod tests { use bitcoin::hashes::Hash; use bitcoin::hashes::sha256::Hash as Sha256; - use core::sync::atomic::{AtomicBool, Ordering}; use core::time::Duration; use ln::{PaymentPreimage, PaymentHash, PaymentSecret}; - use ln::channelmanager::PersistenceNotifier; use ln::features::{InitFeatures, InvoiceFeatures}; use ln::functional_test_utils::*; use ln::msgs; @@ -5164,12 +5163,15 @@ mod tests { use routing::router::{get_keysend_route, get_route}; use util::events::{Event, MessageSendEvent, MessageSendEventsProvider}; use util::test_utils; - use std::sync::Arc; - use std::thread; #[cfg(feature = "std")] #[test] fn test_wait_timeout() { + use ln::channelmanager::PersistenceNotifier; + use sync::Arc; + use core::sync::atomic::{AtomicBool, Ordering}; + use std::thread; + let persistence_notifier = Arc::new(PersistenceNotifier::new()); let thread_notifier = Arc::clone(&persistence_notifier); @@ -5219,6 +5221,12 @@ mod tests { let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]); let nodes = create_network(3, &node_cfgs, &node_chanmgrs); + // All nodes start with a persistable update pending as `create_network` connects each node + // with all other nodes to make most tests simpler. + assert!(nodes[0].node.await_persistable_update_timeout(Duration::from_millis(1))); + assert!(nodes[1].node.await_persistable_update_timeout(Duration::from_millis(1))); + assert!(nodes[2].node.await_persistable_update_timeout(Duration::from_millis(1))); + let mut chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()); // We check that the channel info nodes have doesn't change too early, even though we try diff --git a/lightning/src/ln/features.rs b/lightning/src/ln/features.rs index eb0100db..e78fa3d5 100644 --- a/lightning/src/ln/features.rs +++ b/lightning/src/ln/features.rs @@ -22,6 +22,7 @@ //! [BOLT #9]: https://github.com/lightningnetwork/lightning-rfc/blob/master/09-features.md //! [messages]: crate::ln::msgs +use io; use prelude::*; use core::{cmp, fmt}; use core::marker::PhantomData; @@ -89,6 +90,28 @@ mod sealed { )* ]; } + + impl alloc::fmt::Display for Features<$context> { + fn fmt(&self, fmt: &mut alloc::fmt::Formatter) -> Result<(), alloc::fmt::Error> { + $( + $( + fmt.write_fmt(format_args!("{}: {}, ", stringify!($required_feature), + if <$context as $required_feature>::requires_feature(&self.flags) { "required" } + else if <$context as $required_feature>::supports_feature(&self.flags) { "supported" } + else { "not supported" }))?; + )* + $( + fmt.write_fmt(format_args!("{}: {}, ", stringify!($optional_feature), + if <$context as $optional_feature>::requires_feature(&self.flags) { "required" } + else if <$context as $optional_feature>::supports_feature(&self.flags) { "supported" } + else { "not supported" }))?; + )* + )* + fmt.write_fmt(format_args!("unknown flags: {}", + if self.requires_unknown_bits() { "required" } + else if self.supports_unknown_bits() { "supported" } else { "none" })) + } + } }; } @@ -361,7 +384,7 @@ pub type InvoiceFeatures = Features; impl InitFeatures { /// Writes all features present up to, and including, 13. - pub(crate) fn write_up_to_13(&self, w: &mut W) -> Result<(), ::std::io::Error> { + pub(crate) fn write_up_to_13(&self, w: &mut W) -> Result<(), io::Error> { let len = cmp::min(2, self.flags.len()); w.size_hint(len + 2); (len as u16).write(w)?; @@ -566,6 +589,7 @@ impl Features { pub(crate) fn requires_data_loss_protect(&self) -> bool { ::requires_feature(&self.flags) } + #[cfg(test)] pub(crate) fn supports_data_loss_protect(&self) -> bool { ::supports_feature(&self.flags) } @@ -669,7 +693,7 @@ impl Features { } impl Writeable for Features { - fn write(&self, w: &mut W) -> Result<(), ::std::io::Error> { + fn write(&self, w: &mut W) -> Result<(), io::Error> { w.size_hint(self.flags.len() + 2); (self.flags.len() as u16).write(w)?; for f in self.flags.iter().rev() { // Swap back to big-endian @@ -680,7 +704,7 @@ impl Writeable for Features { } impl Readable for Features { - fn read(r: &mut R) -> Result { + fn read(r: &mut R) -> Result { let mut flags: Vec = Readable::read(r)?; flags.reverse(); // Swap to little-endian Ok(Self { diff --git a/lightning/src/ln/functional_test_utils.rs b/lightning/src/ln/functional_test_utils.rs index bea2990c..807bb20f 100644 --- a/lightning/src/ln/functional_test_utils.rs +++ b/lightning/src/ln/functional_test_utils.rs @@ -39,6 +39,7 @@ use bitcoin::hash_types::BlockHash; use bitcoin::secp256k1::key::PublicKey; +use io; use prelude::*; use core::cell::RefCell; use std::rc::Rc; @@ -239,7 +240,7 @@ impl<'a, 'b, 'c> Drop for Node<'a, 'b, 'c> { let mut w = test_utils::TestVecWriter(Vec::new()); let network_graph_ser = self.net_graph_msg_handler.network_graph.read().unwrap(); network_graph_ser.write(&mut w).unwrap(); - let network_graph_deser = ::read(&mut ::std::io::Cursor::new(&w.0)).unwrap(); + let network_graph_deser = ::read(&mut io::Cursor::new(&w.0)).unwrap(); assert!(network_graph_deser == *self.net_graph_msg_handler.network_graph.read().unwrap()); let net_graph_msg_handler = NetGraphMsgHandler::from_net_graph( Some(self.chain_source), self.logger, network_graph_deser @@ -277,7 +278,7 @@ impl<'a, 'b, 'c> Drop for Node<'a, 'b, 'c> { let mut w = test_utils::TestVecWriter(Vec::new()); old_monitor.write(&mut w).unwrap(); let (_, deserialized_monitor) = <(BlockHash, ChannelMonitor)>::read( - &mut ::std::io::Cursor::new(&w.0), self.keys_manager).unwrap(); + &mut io::Cursor::new(&w.0), self.keys_manager).unwrap(); deserialized_monitors.push(deserialized_monitor); } } @@ -292,7 +293,7 @@ impl<'a, 'b, 'c> Drop for Node<'a, 'b, 'c> { let mut w = test_utils::TestVecWriter(Vec::new()); self.node.write(&mut w).unwrap(); - <(BlockHash, ChannelManager)>::read(&mut ::std::io::Cursor::new(w.0), ChannelManagerReadArgs { + <(BlockHash, ChannelManager)>::read(&mut io::Cursor::new(w.0), ChannelManagerReadArgs { default_config: *self.node.get_current_default_configuration(), keys_manager: self.keys_manager, fee_estimator: &test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }, @@ -1420,6 +1421,13 @@ pub fn create_network<'a, 'b: 'a, 'c: 'b>(node_count: usize, cfgs: &'b Vec)> - ::read(&mut std::io::Cursor::new(&chan_manager_serialized.0[..]), ChannelManagerReadArgs { + ::read(&mut io::Cursor::new(&chan_manager_serialized.0[..]), ChannelManagerReadArgs { default_config: Default::default(), keys_manager, fee_estimator: node_cfgs[0].fee_estimator, @@ -7748,7 +7749,7 @@ fn test_data_loss_protect() { // Restore node A from previous state logger = test_utils::TestLogger::with_id(format!("node {}", 0)); - let mut chain_monitor = <(BlockHash, ChannelMonitor)>::read(&mut ::std::io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1; + let mut chain_monitor = <(BlockHash, ChannelMonitor)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1; chain_source = test_utils::TestChainSource::new(Network::Testnet); tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))}; fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }; @@ -7757,7 +7758,7 @@ fn test_data_loss_protect() { node_state_0 = { let mut channel_monitors = HashMap::new(); channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor); - <(BlockHash, ChannelManager)>::read(&mut ::std::io::Cursor::new(previous_node_state), ChannelManagerReadArgs { + <(BlockHash, ChannelManager)>::read(&mut io::Cursor::new(previous_node_state), ChannelManagerReadArgs { keys_manager: keys_manager, fee_estimator: &fee_estimator, chain_monitor: &monitor, @@ -8852,7 +8853,7 @@ fn test_update_err_monitor_lockdown() { let mut w = test_utils::TestVecWriter(Vec::new()); monitor.write(&mut w).unwrap(); let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor)>::read( - &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1; + &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1; assert!(new_monitor == *monitor); let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager); assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok()); @@ -8914,7 +8915,7 @@ fn test_concurrent_monitor_claim() { let mut w = test_utils::TestVecWriter(Vec::new()); monitor.write(&mut w).unwrap(); let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor)>::read( - &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1; + &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1; assert!(new_monitor == *monitor); let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager); assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok()); @@ -8943,7 +8944,7 @@ fn test_concurrent_monitor_claim() { let mut w = test_utils::TestVecWriter(Vec::new()); monitor.write(&mut w).unwrap(); let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor)>::read( - &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1; + &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1; assert!(new_monitor == *monitor); let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager); assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok()); diff --git a/lightning/src/ln/msgs.rs b/lightning/src/ln/msgs.rs index 85672f4c..0042cf51 100644 --- a/lightning/src/ln/msgs.rs +++ b/lightning/src/ln/msgs.rs @@ -35,7 +35,8 @@ use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures}; use prelude::*; use core::{cmp, fmt}; use core::fmt::Debug; -use std::io::Read; +use io::{self, Read}; +use io_extras::read_to_end; use util::events::MessageSendEventsProvider; use util::logger; @@ -64,7 +65,7 @@ pub enum DecodeError { BadLengthDescriptor, /// Error from std::io Io(/// (C-not exported) as ErrorKind doesn't have a reasonable mapping - ::std::io::ErrorKind), + io::ErrorKind), /// The message included zlib-compressed values, which we don't support. UnsupportedCompression, } @@ -420,7 +421,7 @@ impl NetAddress { } impl Writeable for NetAddress { - fn write(&self, writer: &mut W) -> Result<(), ::std::io::Error> { + fn write(&self, writer: &mut W) -> Result<(), io::Error> { match self { &NetAddress::IPv4 { ref addr, ref port } => { 1u8.write(writer)?; @@ -979,9 +980,9 @@ impl fmt::Display for DecodeError { } } -impl From<::std::io::Error> for DecodeError { - fn from(e: ::std::io::Error) -> Self { - if e.kind() == ::std::io::ErrorKind::UnexpectedEof { +impl From for DecodeError { + fn from(e: io::Error) -> Self { + if e.kind() == io::ErrorKind::UnexpectedEof { DecodeError::ShortRead } else { DecodeError::Io(e.kind()) @@ -990,7 +991,7 @@ impl From<::std::io::Error> for DecodeError { } impl Writeable for OptionalField