From 0dfcacd22c23f69b6526c9c6507d21427a2b7ccb Mon Sep 17 00:00:00 2001 From: Devrandom Date: Sun, 1 Aug 2021 18:22:06 +0200 Subject: [PATCH] Actual no_std support --- lightning/Cargo.toml | 12 ++- lightning/src/chain/channelmonitor.rs | 12 +-- lightning/src/chain/keysinterface.rs | 6 +- lightning/src/chain/onchaintx.rs | 11 +-- lightning/src/chain/package.rs | 10 ++- lightning/src/lib.rs | 90 ++++++++++++++++++- lightning/src/ln/chan_utils.rs | 5 +- lightning/src/ln/chanmon_update_fail_tests.rs | 3 +- lightning/src/ln/channel.rs | 9 +- lightning/src/ln/channelmanager.rs | 13 +-- lightning/src/ln/features.rs | 7 +- lightning/src/ln/functional_test_utils.rs | 7 +- lightning/src/ln/functional_tests.rs | 13 +-- lightning/src/ln/msgs.rs | 70 +++++++-------- lightning/src/ln/onion_route_tests.rs | 2 +- lightning/src/ln/onion_utils.rs | 5 +- lightning/src/ln/peer_handler.rs | 7 +- lightning/src/ln/wire.rs | 25 +++--- lightning/src/routing/network_graph.rs | 8 +- lightning/src/routing/router.rs | 5 +- lightning/src/util/chacha20.rs | 2 +- lightning/src/util/enforcing_trait_impls.rs | 5 +- lightning/src/util/events.rs | 5 +- lightning/src/util/ser.rs | 87 +++++++++--------- lightning/src/util/ser_macros.rs | 20 ++--- lightning/src/util/test_utils.rs | 13 +-- lightning/src/util/transaction_utils.rs | 3 +- 27 files changed, 282 insertions(+), 173 deletions(-) diff --git a/lightning/Cargo.toml b/lightning/Cargo.toml index 9a2861d69..8bbdfe95a 100644 --- a/lightning/Cargo.toml +++ b/lightning/Cargo.toml @@ -26,25 +26,31 @@ max_level_debug = [] unsafe_revoked_tx_signing = [] unstable = [] -no_std = ["hashbrown", "bitcoin/no-std"] +no_std = ["hashbrown", "bitcoin/no-std", "core2/alloc"] std = ["bitcoin/std"] default = ["std"] [dependencies] -bitcoin = "0.27" +bitcoin = { version = "0.27", default-features = false, features = ["secp-recovery"] } +# TODO maybe bitcoin no-std should pull in this feature? +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" +secp256k1 = { version = "0.20.2", default-features = false, features = ["alloc"] } [dev-dependencies.bitcoin] version = "0.27" -features = ["bitcoinconsensus"] +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 a8ec8ee97..e3485e7a7 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)?; @@ -293,7 +293,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[..])?; @@ -311,7 +311,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)); @@ -2581,7 +2581,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 d7ff2a633..7356dad8e 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 cd2831465..44bbfc2d6 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 b5c1ffdf9..a86add4b9 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 5c414b7b2..e1ae9433e 100644 --- a/lightning/src/lib.rs +++ b/lightning/src/lib.rs @@ -28,31 +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 6e0e50858..4690d298a 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 90519f286..00b681341 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 e08b8af49..10641d0ab 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; @@ -4512,7 +4513,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. @@ -4527,7 +4528,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, @@ -4537,7 +4538,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. @@ -4770,7 +4771,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 0aa3f1d0b..7e42705c2 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; @@ -3990,7 +3991,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; } @@ -4610,7 +4611,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, @@ -4714,7 +4715,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); @@ -4910,7 +4911,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))) } @@ -4924,7 +4925,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)?; diff --git a/lightning/src/ln/features.rs b/lightning/src/ln/features.rs index b90748aa8..e78fa3d50 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; @@ -383,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)?; @@ -692,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 @@ -703,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 792a48268..feeb691b1 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) }, diff --git a/lightning/src/ln/functional_tests.rs b/lightning/src/ln/functional_tests.rs index a13b06d8d..7e9eb4c96 100644 --- a/lightning/src/ln/functional_tests.rs +++ b/lightning/src/ln/functional_tests.rs @@ -51,6 +51,7 @@ use bitcoin::secp256k1::key::{PublicKey,SecretKey}; use regex; +use io; use prelude::*; use alloc::collections::BTreeSet; use core::default::Default; @@ -4549,7 +4550,7 @@ fn test_dup_htlc_onchain_fails_on_reload() { let mut channel_monitors = HashMap::new(); channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor); <(BlockHash, ChannelManager)> - ::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, @@ -7746,7 +7747,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) }; @@ -7755,7 +7756,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, @@ -8850,7 +8851,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()); @@ -8912,7 +8913,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()); @@ -8941,7 +8942,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 85672f4cd..0042cf51b 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