Merge pull request #1028 from lightning-signer/2021-08-no-std

Actual no_std support
This commit is contained in:
Matt Corallo 2021-08-03 17:06:59 +00:00 committed by GitHub
commit 57feb26307
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
29 changed files with 297 additions and 187 deletions

View file

@ -16,7 +16,7 @@ jobs:
1.41.0,
# 1.45.2 is MSRV for lightning-net-tokio, lightning-block-sync, and coverage generation
1.45.2,
# 1.47.0 will be the MSRV for no_std builds using hashbrown once core2 is updated
# 1.47.0 will be the MSRV for no-std builds using hashbrown once core2 is updated
1.47.0]
include:
- toolchain: stable
@ -95,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"

View file

@ -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

View file

@ -26,25 +26,32 @@ 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 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.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.

View file

@ -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<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&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: ::std::io::Read>(r: &mut R) -> Result<Self, DecodeError> {
fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
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<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&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: ::std::io::Read>(r: &mut R) -> Result<Self, DecodeError> {
fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
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<Signer = Signer>> ReadableArgs<&'a K>
for (BlockHash, ChannelMonitor<Signer>) {
fn read<R: ::std::io::Read>(reader: &mut R, keys_manager: &'a K) -> Result<Self, DecodeError> {
fn read<R: io::Read>(reader: &mut R, keys_manager: &'a K) -> Result<Self, DecodeError> {
macro_rules! unwrap_obj {
($key: expr) => {
match $key {

View file

@ -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<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
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<Self::Signer, DecodeError> {
InMemorySigner::read(&mut std::io::Cursor::new(reader))
InMemorySigner::read(&mut io::Cursor::new(reader))
}
fn sign_invoice(&self, invoice_preimage: Vec<u8>) -> Result<RecoverableSignature, ()> {

View file

@ -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<Vec<Option<(usize, Signature)>>> {
fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
match Readable::read(reader)? {
0u8 => Ok(None),
1u8 => {
@ -115,7 +116,7 @@ impl Readable for Option<Vec<Option<(usize, Signature)>>> {
}
impl Writeable for Option<Vec<Option<(usize, Signature)>>> {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&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<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
pub(crate) fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
pub(crate) fn write<W: Writer>(&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<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
}
impl<'a, K: KeysInterface> ReadableArgs<&'a K> for OnchainTxHandler<K::Signer> {
fn read<R: ::std::io::Read>(reader: &mut R, keys_manager: &'a K) -> Result<Self, DecodeError> {
fn read<R: io::Read>(reader: &mut R, keys_manager: &'a K) -> Result<Self, DecodeError> {
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<K::Signer> {
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::<PackageTemplate>()));
let mut packages = Vec::with_capacity(cmp::min(packages_len as usize, MAX_ALLOC_SIZE / core::mem::size_of::<PackageTemplate>()));
for _ in 0..packages_len {
packages.push(Readable::read(reader)?);
}

View file

@ -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<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&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<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
let inputs_count = <u64 as Readable>::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 {

View file

@ -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<usize> {
Ok(buf.len())
}
#[inline]
fn flush(&mut self) -> core2::io::Result<()> {
Ok(())
}
}
pub fn copy<R: ?Sized, W: ?Sized>(reader: &mut R, writer: &mut W) -> Result<u64, io::Error>
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<D: io::Read>(mut d: D) -> Result<alloc::vec::Vec<u8>, 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<D: ::std::io::Read>(mut d: D) -> Result<Vec<u8>, ::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")]

View file

@ -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<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&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<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
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)?;

View file

@ -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<EnforcingSigner>)>::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());

View file

@ -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<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&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<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
Ok(match <u8 as Readable>::read(reader)? {
0 => ChannelUpdateStatus::Enabled,
1 => ChannelUpdateStatus::Disabled,
@ -4537,7 +4538,7 @@ impl Readable for ChannelUpdateStatus {
}
impl<Signer: Sign> Writeable for Channel<Signer> {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&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<Signer: Sign> Writeable for Channel<Signer> {
const MAX_ALLOC_SIZE: usize = 64*1024;
impl<'a, Signer: Sign, K: Deref> ReadableArgs<&'a K> for Channel<Signer>
where K::Target: KeysInterface<Signer = Signer> {
fn read<R : ::std::io::Read>(reader: &mut R, keys_source: &'a K) -> Result<Self, DecodeError> {
fn read<R : io::Read>(reader: &mut R, keys_source: &'a K) -> Result<Self, DecodeError> {
let ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
let user_id = Readable::read(reader)?;

View file

@ -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<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&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<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> Writeable f
F::Target: FeeEstimator,
L::Target: Logger,
{
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&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<R: ::std::io::Read>(reader: &mut R, args: ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>) -> Result<Self, DecodeError> {
fn read<R: io::Read>(reader: &mut R, args: ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>) -> Result<Self, DecodeError> {
let (blockhash, chan_manager) = <(BlockHash, ChannelManager<Signer, M, T, K, F, L>)>::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<R: ::std::io::Read>(reader: &mut R, mut args: ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>) -> Result<Self, DecodeError> {
fn read<R: io::Read>(reader: &mut R, mut args: ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>) -> Result<Self, DecodeError> {
let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
let genesis_hash: BlockHash = Readable::read(reader)?;

View file

@ -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<sealed::InvoiceContext>;
impl InitFeatures {
/// Writes all features present up to, and including, 13.
pub(crate) fn write_up_to_13<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
pub(crate) fn write_up_to_13<W: Writer>(&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<T: sealed::ShutdownAnySegwit> Features<T> {
}
impl<T: sealed::Context> Writeable for Features<T> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&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<T: sealed::Context> Writeable for Features<T> {
}
impl<T: sealed::Context> Readable for Features<T> {
fn read<R: ::std::io::Read>(r: &mut R) -> Result<Self, DecodeError> {
fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
let mut flags: Vec<u8> = Readable::read(r)?;
flags.reverse(); // Swap to little-endian
Ok(Self {

View file

@ -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 = <NetworkGraph>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap();
let network_graph_deser = <NetworkGraph>::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<EnforcingSigner>)>::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<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut ::std::io::Cursor::new(w.0), ChannelManagerReadArgs {
<(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::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) },

View file

@ -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<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>
::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<EnforcingSigner>)>::read(&mut ::std::io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::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<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut ::std::io::Cursor::new(previous_node_state), ChannelManagerReadArgs {
<(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::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<EnforcingSigner>)>::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<EnforcingSigner>)>::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<EnforcingSigner>)>::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());

View file

@ -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<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&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<io::Error> 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<Script> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
match *self {
OptionalField::Present(ref script) => {
// Note that Writeable for script includes the 16-bit length tag for us
@ -1017,7 +1018,7 @@ impl Readable for OptionalField<Script> {
}
impl Writeable for OptionalField<u64> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
match *self {
OptionalField::Present(ref value) => {
value.write(w)?;
@ -1065,7 +1066,7 @@ impl_writeable!(AnnouncementSignatures, 32+8+64*2, {
});
impl Writeable for ChannelReestablish {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
w.size_hint(if let OptionalField::Present(..) = self.data_loss_protect { 32+2*8+33+32 } else { 32+2*8 });
self.channel_id.write(w)?;
self.next_local_commitment_number.write(w)?;
@ -1142,7 +1143,7 @@ impl_writeable!(FundingLocked, 32+33, {
});
impl Writeable for Init {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
// global_features gets the bottom 13 bits of our features, and local_features gets all of
// our relevant feature bits. This keeps us compatible with old nodes.
self.features.write_up_to_13(w)?;
@ -1231,7 +1232,7 @@ impl_writeable_len_match!(OnionErrorPacket, {
});
impl Writeable for OnionPacket {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
w.size_hint(1 + 33 + 20*65 + 32);
self.version.write(w)?;
match self.public_key {
@ -1269,7 +1270,7 @@ impl_writeable!(UpdateAddHTLC, 32+8+8+32+4+1366, {
});
impl Writeable for FinalOnionHopData {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
w.size_hint(32 + 8 - (self.total_msat.leading_zeros()/8) as usize);
self.payment_secret.0.write(w)?;
HighZeroBytesDroppedVarInt(self.total_msat).write(w)
@ -1285,7 +1286,7 @@ impl Readable for FinalOnionHopData {
}
impl Writeable for OnionHopData {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
w.size_hint(33);
// Note that this should never be reachable if Rust-Lightning generated the message, as we
// check values are sane long before we get here, though its possible in the future
@ -1386,7 +1387,7 @@ impl Readable for OnionHopData {
}
impl Writeable for Ping {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
w.size_hint(self.byteslen as usize + 4);
self.ponglen.write(w)?;
vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
@ -1408,7 +1409,7 @@ impl Readable for Ping {
}
impl Writeable for Pong {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
w.size_hint(self.byteslen as usize + 2);
vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
Ok(())
@ -1428,7 +1429,7 @@ impl Readable for Pong {
}
impl Writeable for UnsignedChannelAnnouncement {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
w.size_hint(2 + 32 + 8 + 4*33 + self.features.byte_count() + self.excess_data.len());
self.features.write(w)?;
self.chain_hash.write(w)?;
@ -1452,11 +1453,7 @@ impl Readable for UnsignedChannelAnnouncement {
node_id_2: Readable::read(r)?,
bitcoin_key_1: Readable::read(r)?,
bitcoin_key_2: Readable::read(r)?,
excess_data: {
let mut excess_data = vec![];
r.read_to_end(&mut excess_data)?;
excess_data
},
excess_data: read_to_end(r)?,
})
}
}
@ -1473,7 +1470,7 @@ impl_writeable_len_match!(ChannelAnnouncement, {
});
impl Writeable for UnsignedChannelUpdate {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
let mut size = 64 + self.excess_data.len();
let mut message_flags: u8 = 0;
if let OptionalField::Present(_) = self.htlc_maximum_msat {
@ -1514,11 +1511,7 @@ impl Readable for UnsignedChannelUpdate {
fee_base_msat: Readable::read(r)?,
fee_proportional_millionths: Readable::read(r)?,
htlc_maximum_msat: if has_htlc_maximum_msat { Readable::read(r)? } else { OptionalField::Absent },
excess_data: {
let mut excess_data = vec![];
r.read_to_end(&mut excess_data)?;
excess_data
},
excess_data: read_to_end(r)?,
})
}
}
@ -1532,7 +1525,7 @@ impl_writeable_len_match!(ChannelUpdate, {
});
impl Writeable for ErrorMessage {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
w.size_hint(32 + 2 + self.data.len());
self.channel_id.write(w)?;
(self.data.len() as u16).write(w)?;
@ -1547,9 +1540,8 @@ impl Readable for ErrorMessage {
channel_id: Readable::read(r)?,
data: {
let mut sz: usize = <u16 as Readable>::read(r)? as usize;
let mut data = vec![];
let data_len = r.read_to_end(&mut data)?;
sz = cmp::min(data_len, sz);
let data = read_to_end(r)?;
sz = cmp::min(data.len(), sz);
match String::from_utf8(data[..sz as usize].to_vec()) {
Ok(s) => s,
Err(_) => return Err(DecodeError::InvalidValue),
@ -1560,7 +1552,7 @@ impl Readable for ErrorMessage {
}
impl Writeable for UnsignedNodeAnnouncement {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
w.size_hint(76 + self.features.byte_count() + self.addresses.len()*38 + self.excess_address_data.len() + self.excess_data.len());
self.features.write(w)?;
self.timestamp.write(w)?;
@ -1630,7 +1622,7 @@ impl Readable for UnsignedNodeAnnouncement {
}
Vec::new()
};
r.read_to_end(&mut excess_data)?;
excess_data.extend(read_to_end(r)?.iter());
Ok(UnsignedNodeAnnouncement {
features,
timestamp,
@ -1687,7 +1679,7 @@ impl Readable for QueryShortChannelIds {
}
impl Writeable for QueryShortChannelIds {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
// Calculated from 1-byte encoding_type plus 8-bytes per short_channel_id
let encoding_len: u16 = 1 + self.short_channel_ids.len() as u16 * 8;
@ -1718,7 +1710,7 @@ impl Readable for ReplyShortChannelIdsEnd {
}
impl Writeable for ReplyShortChannelIdsEnd {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
w.size_hint(32 + 1);
self.chain_hash.write(w)?;
self.full_information.write(w)?;
@ -1753,7 +1745,7 @@ impl Readable for QueryChannelRange {
}
impl Writeable for QueryChannelRange {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
w.size_hint(32 + 4 + 4);
self.chain_hash.write(w)?;
self.first_blocknum.write(w)?;
@ -1803,7 +1795,7 @@ impl Readable for ReplyChannelRange {
}
impl Writeable for ReplyChannelRange {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
let encoding_len: u16 = 1 + self.short_channel_ids.len() as u16 * 8;
w.size_hint(32 + 4 + 4 + 1 + 2 + encoding_len as usize);
self.chain_hash.write(w)?;
@ -1835,7 +1827,7 @@ impl Readable for GossipTimestampFilter {
}
impl Writeable for GossipTimestampFilter {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
w.size_hint(32 + 4 + 4);
self.chain_hash.write(w)?;
self.first_timestamp.write(w)?;
@ -1863,8 +1855,8 @@ mod tests {
use bitcoin::secp256k1::key::{PublicKey,SecretKey};
use bitcoin::secp256k1::{Secp256k1, Message};
use io::Cursor;
use prelude::*;
use std::io::Cursor;
#[test]
fn encoding_channel_reestablish_no_secret() {

View file

@ -33,9 +33,9 @@ use bitcoin::secp256k1;
use bitcoin::secp256k1::Secp256k1;
use bitcoin::secp256k1::key::SecretKey;
use io;
use prelude::*;
use core::default::Default;
use std::io;
use ln::functional_test_utils::*;

View file

@ -27,7 +27,7 @@ use bitcoin::secp256k1::ecdh::SharedSecret;
use bitcoin::secp256k1;
use prelude::*;
use std::io::Cursor;
use io::Cursor;
use core::convert::TryInto;
use core::ops::Deref;
@ -480,6 +480,7 @@ pub(super) fn process_onion_failure<T: secp256k1::Signing, L: Deref>(secp_ctx: &
#[cfg(test)]
mod tests {
use io;
use prelude::*;
use ln::PaymentHash;
use ln::features::{ChannelFeatures, NodeFeatures};
@ -648,7 +649,7 @@ mod tests {
}
}
impl Writeable for RawOnionHopData {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
writer.write_all(&self.data[..])
}
}

View file

@ -31,13 +31,14 @@ use util::logger::Logger;
use routing::network_graph::NetGraphMsgHandler;
use prelude::*;
use io;
use alloc::collections::LinkedList;
use alloc::fmt::Debug;
use sync::{Arc, Mutex};
use core::sync::atomic::{AtomicUsize, Ordering};
use core::{cmp, hash, fmt, mem};
use core::ops::Deref;
use std::error;
#[cfg(feature = "std")] use std::error;
use bitcoin::hashes::sha256::Hash as Sha256;
use bitcoin::hashes::sha256::HashEngine as Sha256Engine;
@ -230,6 +231,8 @@ impl fmt::Display for PeerHandleError {
formatter.write_str("Peer Sent Invalid Data")
}
}
#[cfg(feature = "std")]
impl error::Error for PeerHandleError {
fn description(&self) -> &str {
"Peer Sent Invalid Data"
@ -801,7 +804,7 @@ impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref> PeerManager<D
peer.pending_read_buffer = [0; 18].to_vec();
peer.pending_read_is_header = true;
let mut reader = ::std::io::Cursor::new(&msg_data[..]);
let mut reader = io::Cursor::new(&msg_data[..]);
let message_result = wire::read(&mut reader);
let message = match message_result {
Ok(x) => x,

View file

@ -18,6 +18,7 @@
//!
//! [BOLT #1]: https://github.com/lightningnetwork/lightning-rfc/blob/master/01-messaging.md
use io;
use ln::msgs;
use util::ser::{Readable, Writeable, Writer};
@ -119,7 +120,7 @@ impl ::core::fmt::Display for MessageType {
/// # Errors
///
/// Returns an error if the message payload code not be decoded as the specified type.
pub fn read<R: ::std::io::Read>(buffer: &mut R) -> Result<Message, msgs::DecodeError> {
pub fn read<R: io::Read>(buffer: &mut R) -> Result<Message, msgs::DecodeError> {
let message_type = <u16 as Readable>::read(buffer)?;
match message_type {
msgs::Init::TYPE => {
@ -218,7 +219,7 @@ pub fn read<R: ::std::io::Read>(buffer: &mut R) -> Result<Message, msgs::DecodeE
/// # Errors
///
/// Returns an I/O error if the write could not be completed.
pub fn write<M: Encode + Writeable, W: Writer>(message: &M, buffer: &mut W) -> Result<(), ::std::io::Error> {
pub fn write<M: Encode + Writeable, W: Writer>(message: &M, buffer: &mut W) -> Result<(), io::Error> {
M::TYPE.write(buffer)?;
message.write(buffer)
}
@ -361,35 +362,35 @@ mod tests {
#[test]
fn read_empty_buffer() {
let buffer = [];
let mut reader = ::std::io::Cursor::new(buffer);
let mut reader = io::Cursor::new(buffer);
assert!(read(&mut reader).is_err());
}
#[test]
fn read_incomplete_type() {
let buffer = &ENCODED_PONG[..1];
let mut reader = ::std::io::Cursor::new(buffer);
let mut reader = io::Cursor::new(buffer);
assert!(read(&mut reader).is_err());
}
#[test]
fn read_empty_payload() {
let buffer = &ENCODED_PONG[..2];
let mut reader = ::std::io::Cursor::new(buffer);
let mut reader = io::Cursor::new(buffer);
assert!(read(&mut reader).is_err());
}
#[test]
fn read_invalid_message() {
let buffer = &ENCODED_PONG[..4];
let mut reader = ::std::io::Cursor::new(buffer);
let mut reader = io::Cursor::new(buffer);
assert!(read(&mut reader).is_err());
}
#[test]
fn read_known_message() {
let buffer = &ENCODED_PONG[..];
let mut reader = ::std::io::Cursor::new(buffer);
let mut reader = io::Cursor::new(buffer);
let message = read(&mut reader).unwrap();
match message {
Message::Pong(_) => (),
@ -400,7 +401,7 @@ mod tests {
#[test]
fn read_unknown_message() {
let buffer = &::core::u16::MAX.to_be_bytes();
let mut reader = ::std::io::Cursor::new(buffer);
let mut reader = io::Cursor::new(buffer);
let message = read(&mut reader).unwrap();
match message {
Message::Unknown(MessageType(::core::u16::MAX)) => (),
@ -426,7 +427,7 @@ mod tests {
let mut buffer = Vec::new();
assert!(write(&message, &mut buffer).is_ok());
let mut reader = ::std::io::Cursor::new(buffer);
let mut reader = io::Cursor::new(buffer);
let decoded_message = read(&mut reader).unwrap();
match decoded_message {
Message::Pong(msgs::Pong { byteslen: 2u16 }) => (),
@ -464,7 +465,7 @@ mod tests {
}
fn check_init_msg(buffer: Vec<u8>, expect_unknown: bool) {
let mut reader = ::std::io::Cursor::new(buffer);
let mut reader = io::Cursor::new(buffer);
let decoded_msg = read(&mut reader).unwrap();
match decoded_msg {
Message::Init(msgs::Init { features }) => {
@ -483,7 +484,7 @@ mod tests {
fn read_lnd_node_announcement() {
// Taken from lnd v0.9.0-beta.
let buffer = vec![1, 1, 91, 164, 146, 213, 213, 165, 21, 227, 102, 33, 105, 179, 214, 21, 221, 175, 228, 93, 57, 177, 191, 127, 107, 229, 31, 50, 21, 81, 179, 71, 39, 18, 35, 2, 89, 224, 110, 123, 66, 39, 148, 246, 177, 85, 12, 19, 70, 226, 173, 132, 156, 26, 122, 146, 71, 213, 247, 48, 93, 190, 185, 177, 12, 172, 0, 3, 2, 162, 161, 94, 103, 195, 37, 2, 37, 242, 97, 140, 2, 111, 69, 85, 39, 118, 30, 221, 99, 254, 120, 49, 103, 22, 170, 227, 111, 172, 164, 160, 49, 68, 138, 116, 16, 22, 206, 107, 51, 153, 255, 97, 108, 105, 99, 101, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 1, 172, 21, 0, 2, 38, 7];
let mut reader = ::std::io::Cursor::new(buffer);
let mut reader = io::Cursor::new(buffer);
let decoded_msg = read(&mut reader).unwrap();
match decoded_msg {
Message::NodeAnnouncement(msgs::NodeAnnouncement { contents: msgs::UnsignedNodeAnnouncement { features, ..}, ..}) => {
@ -500,7 +501,7 @@ mod tests {
fn read_lnd_chan_announcement() {
// Taken from lnd v0.9.0-beta.
let buffer = vec![1, 0, 82, 238, 153, 33, 128, 87, 215, 2, 28, 241, 140, 250, 98, 255, 56, 5, 79, 240, 214, 231, 172, 35, 240, 171, 44, 9, 78, 91, 8, 193, 102, 5, 17, 178, 142, 106, 180, 183, 46, 38, 217, 212, 25, 236, 69, 47, 92, 217, 181, 221, 161, 205, 121, 201, 99, 38, 158, 216, 186, 193, 230, 86, 222, 6, 206, 67, 22, 255, 137, 212, 141, 161, 62, 134, 76, 48, 241, 54, 50, 167, 187, 247, 73, 27, 74, 1, 129, 185, 197, 153, 38, 90, 255, 138, 39, 161, 102, 172, 213, 74, 107, 88, 150, 90, 0, 49, 104, 7, 182, 184, 194, 219, 181, 172, 8, 245, 65, 226, 19, 228, 101, 145, 25, 159, 52, 31, 58, 93, 53, 59, 218, 91, 37, 84, 103, 17, 74, 133, 33, 35, 2, 203, 101, 73, 19, 94, 175, 122, 46, 224, 47, 168, 128, 128, 25, 26, 25, 214, 52, 247, 43, 241, 117, 52, 206, 94, 135, 156, 52, 164, 143, 234, 58, 185, 50, 185, 140, 198, 174, 71, 65, 18, 105, 70, 131, 172, 137, 0, 164, 51, 215, 143, 117, 119, 217, 241, 197, 177, 227, 227, 170, 199, 114, 7, 218, 12, 107, 30, 191, 236, 203, 21, 61, 242, 48, 192, 90, 233, 200, 199, 111, 162, 68, 234, 54, 219, 1, 233, 66, 5, 82, 74, 84, 211, 95, 199, 245, 202, 89, 223, 102, 124, 62, 166, 253, 253, 90, 180, 118, 21, 61, 110, 37, 5, 96, 167, 0, 0, 6, 34, 110, 70, 17, 26, 11, 89, 202, 175, 18, 96, 67, 235, 91, 191, 40, 195, 79, 58, 94, 51, 42, 31, 199, 178, 183, 60, 241, 136, 145, 15, 0, 2, 65, 0, 0, 1, 0, 0, 2, 37, 242, 97, 140, 2, 111, 69, 85, 39, 118, 30, 221, 99, 254, 120, 49, 103, 22, 170, 227, 111, 172, 164, 160, 49, 68, 138, 116, 16, 22, 206, 107, 3, 54, 61, 144, 88, 171, 247, 136, 208, 99, 9, 135, 37, 201, 178, 253, 136, 0, 185, 235, 68, 160, 106, 110, 12, 46, 21, 125, 204, 18, 75, 234, 16, 3, 42, 171, 28, 52, 224, 11, 30, 30, 253, 156, 148, 175, 203, 121, 250, 111, 122, 195, 84, 122, 77, 183, 56, 135, 101, 88, 41, 60, 191, 99, 232, 85, 2, 36, 17, 156, 11, 8, 12, 189, 177, 68, 88, 28, 15, 207, 21, 179, 151, 56, 226, 158, 148, 3, 120, 113, 177, 243, 184, 17, 173, 37, 46, 222, 16];
let mut reader = ::std::io::Cursor::new(buffer);
let mut reader = io::Cursor::new(buffer);
let decoded_msg = read(&mut reader).unwrap();
match decoded_msg {
Message::ChannelAnnouncement(msgs::ChannelAnnouncement { contents: msgs::UnsignedChannelAnnouncement { features, ..}, ..}) => {

View file

@ -32,6 +32,7 @@ use util::logger::{Logger, Level};
use util::events::{MessageSendEvent, MessageSendEventsProvider};
use util::scid_utils::{block_from_scid, scid_from_parts, MAX_SCID_BLOCK};
use io;
use prelude::*;
use alloc::collections::{BTreeMap, btree_map::Entry as BtreeEntry};
use core::{cmp, fmt};
@ -611,7 +612,7 @@ const SERIALIZATION_VERSION: u8 = 1;
const MIN_SERIALIZATION_VERSION: u8 = 1;
impl Writeable for NetworkGraph {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
self.genesis_hash.write(writer)?;
@ -632,7 +633,7 @@ impl Writeable for NetworkGraph {
}
impl Readable for NetworkGraph {
fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
fn read<R: io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
let genesis_hash: BlockHash = Readable::read(reader)?;
@ -1087,6 +1088,7 @@ mod tests {
use bitcoin::secp256k1::key::{PublicKey, SecretKey};
use bitcoin::secp256k1::{All, Secp256k1};
use io;
use prelude::*;
use sync::Arc;
@ -1996,7 +1998,7 @@ mod tests {
assert!(!network.get_nodes().is_empty());
assert!(!network.get_channels().is_empty());
network.write(&mut w).unwrap();
assert!(<NetworkGraph>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);
assert!(<NetworkGraph>::read(&mut io::Cursor::new(&w.0)).unwrap() == *network);
}
#[test]

View file

@ -21,6 +21,7 @@ use routing::network_graph::{NetworkGraph, RoutingFees};
use util::ser::{Writeable, Readable};
use util::logger::Logger;
use io;
use prelude::*;
use alloc::collections::BinaryHeap;
use core::cmp;
@ -74,7 +75,7 @@ const SERIALIZATION_VERSION: u8 = 1;
const MIN_SERIALIZATION_VERSION: u8 = 1;
impl Writeable for Route {
fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
(self.paths.len() as u64).write(writer)?;
for hops in self.paths.iter() {
@ -89,7 +90,7 @@ impl Writeable for Route {
}
impl Readable for Route {
fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
let path_count: u64 = Readable::read(reader)?;
let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
@ -3830,7 +3831,7 @@ mod tests {
}
}
#[cfg(not(feature = "no_std"))]
#[cfg(not(feature = "no-std"))]
pub(super) fn random_init_seed() -> u64 {
// Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
use core::hash::{BuildHasher, Hasher};
@ -3838,11 +3839,11 @@ mod tests {
println!("Using seed of {}", seed);
seed
}
#[cfg(not(feature = "no_std"))]
#[cfg(not(feature = "no-std"))]
use util::ser::Readable;
#[test]
#[cfg(not(feature = "no_std"))]
#[cfg(not(feature = "no-std"))]
fn generate_routes() {
let mut d = match super::test_utils::get_route_file() {
Ok(f) => f,
@ -3870,7 +3871,7 @@ mod tests {
}
#[test]
#[cfg(not(feature = "no_std"))]
#[cfg(not(feature = "no-std"))]
fn generate_routes_mpp() {
let mut d = match super::test_utils::get_route_file() {
Ok(f) => f,
@ -3898,7 +3899,7 @@ mod tests {
}
}
#[cfg(all(test, not(feature = "no_std")))]
#[cfg(all(test, not(feature = "no-std")))]
pub(crate) mod test_utils {
use std::fs::File;
/// Tries to open a network graph file, or panics with a URL to fetch it.
@ -3925,7 +3926,7 @@ pub(crate) mod test_utils {
}
}
#[cfg(all(test, feature = "unstable", not(feature = "no_std")))]
#[cfg(all(test, feature = "unstable", not(feature = "no-std")))]
mod benches {
use super::*;
use util::logger::{Logger, Record};

View file

@ -9,7 +9,7 @@
// You may not use this file except in accordance with one or both of these
// licenses.
use std::io;
use io;
#[cfg(not(feature = "fuzztarget"))]
mod real_chacha {

View file

@ -11,6 +11,7 @@ use ln::chan_utils::{HTLCOutputInCommitment, ChannelPublicKeys, HolderCommitment
use ln::{chan_utils, msgs};
use chain::keysinterface::{Sign, InMemorySigner, BaseSign};
use io;
use prelude::*;
use core::cmp;
use sync::{Mutex, Arc};
@ -22,7 +23,7 @@ use bitcoin::secp256k1;
use bitcoin::secp256k1::key::{SecretKey, PublicKey};
use bitcoin::secp256k1::{Secp256k1, Signature};
use util::ser::{Writeable, Writer, Readable};
use std::io::Error;
use io::Error;
use ln::msgs::DecodeError;
/// Initial value for revoked commitment downward counter
@ -181,7 +182,7 @@ impl Writeable for EnforcingSigner {
}
impl Readable for EnforcingSigner {
fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
let inner = Readable::read(reader)?;
let last_commitment_number = Readable::read(reader)?;
Ok(EnforcingSigner {

View file

@ -23,6 +23,7 @@ use bitcoin::blockdata::script::Script;
use bitcoin::secp256k1::key::PublicKey;
use io;
use prelude::*;
use core::time::Duration;
use core::ops::Deref;
@ -153,7 +154,7 @@ pub enum Event {
}
impl Writeable for Event {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
match self {
&Event::FundingGenerationReady { .. } => {
0u8.write(writer)?;
@ -222,7 +223,7 @@ impl Writeable for Event {
}
}
impl MaybeReadable for Event {
fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
match Readable::read(reader)? {
0u8 => Ok(None),
1u8 => {

View file

@ -11,7 +11,8 @@
//! as ChannelsManagers and ChannelMonitors.
use prelude::*;
use std::io::{Read, Write};
use io::{self, Read, Write};
use io_extras::{copy, sink};
use core::hash::Hash;
use sync::Mutex;
use core::cmp;
@ -42,7 +43,7 @@ pub const MAX_BUF_SIZE: usize = 64 * 1024;
/// (C-not exported) as we only export serialization to/from byte arrays instead
pub trait Writer {
/// Writes the given buf out. See std::io::Write::write_all for more
fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error>;
fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error>;
/// Hints that data of the given size is about the be written. This may not always be called
/// prior to data being written and may be safely ignored.
fn size_hint(&mut self, size: usize);
@ -50,8 +51,8 @@ pub trait Writer {
impl<W: Write> Writer for W {
#[inline]
fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
<Self as ::std::io::Write>::write_all(self, buf)
fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
<Self as io::Write>::write_all(self, buf)
}
#[inline]
fn size_hint(&mut self, _size: usize) { }
@ -60,16 +61,16 @@ impl<W: Write> Writer for W {
pub(crate) struct WriterWriteAdaptor<'a, W: Writer + 'a>(pub &'a mut W);
impl<'a, W: Writer + 'a> Write for WriterWriteAdaptor<'a, W> {
#[inline]
fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
self.0.write_all(buf)
}
#[inline]
fn write(&mut self, buf: &[u8]) -> Result<usize, ::std::io::Error> {
fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> {
self.0.write_all(buf)?;
Ok(buf.len())
}
#[inline]
fn flush(&mut self) -> Result<(), ::std::io::Error> {
fn flush(&mut self) -> Result<(), io::Error> {
Ok(())
}
}
@ -77,7 +78,7 @@ impl<'a, W: Writer + 'a> Write for WriterWriteAdaptor<'a, W> {
pub(crate) struct VecWriter(pub Vec<u8>);
impl Writer for VecWriter {
#[inline]
fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
self.0.extend_from_slice(buf);
Ok(())
}
@ -92,7 +93,7 @@ impl Writer for VecWriter {
pub(crate) struct LengthCalculatingWriter(pub usize);
impl Writer for LengthCalculatingWriter {
#[inline]
fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
self.0 += buf.len();
Ok(())
}
@ -119,7 +120,7 @@ impl<R: Read> FixedLengthReader<R> {
#[inline]
pub fn eat_remaining(&mut self) -> Result<(), DecodeError> {
::std::io::copy(self, &mut ::std::io::sink()).unwrap();
copy(self, &mut sink()).unwrap();
if self.bytes_read != self.total_bytes {
Err(DecodeError::ShortRead)
} else {
@ -129,7 +130,7 @@ impl<R: Read> FixedLengthReader<R> {
}
impl<R: Read> Read for FixedLengthReader<R> {
#[inline]
fn read(&mut self, dest: &mut [u8]) -> Result<usize, ::std::io::Error> {
fn read(&mut self, dest: &mut [u8]) -> Result<usize, io::Error> {
if self.total_bytes == self.bytes_read {
Ok(0)
} else {
@ -158,7 +159,7 @@ impl<R: Read> ReadTrackingReader<R> {
}
impl<R: Read> Read for ReadTrackingReader<R> {
#[inline]
fn read(&mut self, dest: &mut [u8]) -> Result<usize, ::std::io::Error> {
fn read(&mut self, dest: &mut [u8]) -> Result<usize, io::Error> {
match self.read.read(dest) {
Ok(0) => Ok(0),
Ok(len) => {
@ -175,7 +176,7 @@ impl<R: Read> Read for ReadTrackingReader<R> {
/// (C-not exported) as we only export serialization to/from byte arrays instead
pub trait Writeable {
/// Writes self out to the given Writer
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error>;
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error>;
/// Writes self out to a Vec<u8>
fn encode(&self) -> Vec<u8> {
@ -206,7 +207,7 @@ pub trait Writeable {
}
impl<'a, T: Writeable> Writeable for &'a T {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> { (*self).write(writer) }
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { (*self).write(writer) }
}
/// A trait that various rust-lightning types implement allowing them to be read in from a Read
@ -252,7 +253,7 @@ impl<T: Readable> Readable for OptionDeserWrapper<T> {
pub(crate) struct VecWriteWrapper<'a, T: Writeable>(pub &'a Vec<T>);
impl<'a, T: Writeable> Writeable for VecWriteWrapper<'a, T> {
#[inline]
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
for ref v in self.0.iter() {
v.write(writer)?;
}
@ -283,7 +284,7 @@ impl<T: Readable> Readable for VecReadWrapper<T> {
pub(crate) struct U48(pub u64);
impl Writeable for U48 {
#[inline]
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
writer.write_all(&be48_to_array(self.0))
}
}
@ -306,7 +307,7 @@ impl Readable for U48 {
pub(crate) struct BigSize(pub u64);
impl Writeable for BigSize {
#[inline]
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
match self.0 {
0...0xFC => {
(self.0 as u8).write(writer)
@ -370,13 +371,13 @@ macro_rules! impl_writeable_primitive {
($val_type:ty, $len: expr) => {
impl Writeable for $val_type {
#[inline]
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
writer.write_all(&self.to_be_bytes())
}
}
impl Writeable for HighZeroBytesDroppedVarInt<$val_type> {
#[inline]
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
// Skip any full leading 0 bytes when writing (in BE):
writer.write_all(&self.0.to_be_bytes()[(self.0.leading_zeros()/8) as usize..$len])
}
@ -424,7 +425,7 @@ impl_writeable_primitive!(u16, 2);
impl Writeable for u8 {
#[inline]
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
writer.write_all(&[*self])
}
}
@ -439,7 +440,7 @@ impl Readable for u8 {
impl Writeable for bool {
#[inline]
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
writer.write_all(&[if *self {1} else {0}])
}
}
@ -461,7 +462,7 @@ macro_rules! impl_array {
impl Writeable for [u8; $size]
{
#[inline]
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
w.write_all(self)
}
}
@ -494,7 +495,7 @@ impl<K, V> Writeable for HashMap<K, V>
V: Writeable
{
#[inline]
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
(self.len() as u16).write(w)?;
for (key, value) in self.iter() {
key.write(w)?;
@ -522,7 +523,7 @@ impl<K, V> Readable for HashMap<K, V>
// Vectors
impl Writeable for Vec<u8> {
#[inline]
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
(self.len() as u16).write(w)?;
w.write_all(&self)
}
@ -540,7 +541,7 @@ impl Readable for Vec<u8> {
}
impl Writeable for Vec<Signature> {
#[inline]
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
(self.len() as u16).write(w)?;
for e in self.iter() {
e.write(w)?;
@ -566,7 +567,7 @@ impl Readable for Vec<Signature> {
}
impl Writeable for Script {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
(self.len() as u16).write(w)?;
w.write_all(self.as_bytes())
}
@ -582,7 +583,7 @@ impl Readable for Script {
}
impl Writeable for PublicKey {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
self.serialize().write(w)
}
#[inline]
@ -602,7 +603,7 @@ impl Readable for PublicKey {
}
impl Writeable for SecretKey {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
let mut ser = [0; SECRET_KEY_SIZE];
ser.copy_from_slice(&self[..]);
ser.write(w)
@ -624,7 +625,7 @@ impl Readable for SecretKey {
}
impl Writeable for Sha256dHash {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
w.write_all(&self[..])
}
}
@ -639,7 +640,7 @@ impl Readable for Sha256dHash {
}
impl Writeable for Signature {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
self.serialize_compact().write(w)
}
#[inline]
@ -659,7 +660,7 @@ impl Readable for Signature {
}
impl Writeable for PaymentPreimage {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
self.0.write(w)
}
}
@ -672,7 +673,7 @@ impl Readable for PaymentPreimage {
}
impl Writeable for PaymentHash {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
self.0.write(w)
}
}
@ -685,7 +686,7 @@ impl Readable for PaymentHash {
}
impl Writeable for PaymentSecret {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
self.0.write(w)
}
}
@ -698,7 +699,7 @@ impl Readable for PaymentSecret {
}
impl<T: Writeable> Writeable for Box<T> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
T::write(&**self, w)
}
}
@ -710,7 +711,7 @@ impl<T: Readable> Readable for Box<T> {
}
impl<T: Writeable> Writeable for Option<T> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
match *self {
None => 0u8.write(w)?,
Some(ref data) => {
@ -736,7 +737,7 @@ impl<T: Readable> Readable for Option<T>
}
impl Writeable for Txid {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
w.write_all(&self[..])
}
}
@ -751,7 +752,7 @@ impl Readable for Txid {
}
impl Writeable for BlockHash {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
w.write_all(&self[..])
}
}
@ -766,7 +767,7 @@ impl Readable for BlockHash {
}
impl Writeable for OutPoint {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
self.txid.write(w)?;
self.vout.write(w)?;
Ok(())
@ -787,7 +788,7 @@ impl Readable for OutPoint {
macro_rules! impl_consensus_ser {
($bitcoin_type: ty) => {
impl Writeable for $bitcoin_type {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
match self.consensus_encode(WriterWriteAdaptor(writer)) {
Ok(_) => Ok(()),
Err(e) => Err(e),
@ -799,7 +800,7 @@ macro_rules! impl_consensus_ser {
fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
match consensus::encode::Decodable::consensus_decode(r) {
Ok(t) => Ok(t),
Err(consensus::encode::Error::Io(ref e)) if e.kind() == ::std::io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
Err(consensus::encode::Error::Io(ref e)) if e.kind() == io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e.kind())),
Err(_) => Err(DecodeError::InvalidValue),
}
@ -817,7 +818,7 @@ impl<T: Readable> Readable for Mutex<T> {
}
}
impl<T: Writeable> Writeable for Mutex<T> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
self.lock().unwrap().write(w)
}
}
@ -830,7 +831,7 @@ impl<A: Readable, B: Readable> Readable for (A, B) {
}
}
impl<A: Writeable, B: Writeable> Writeable for (A, B) {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
self.0.write(w)?;
self.1.write(w)
}
@ -845,7 +846,7 @@ impl<A: Readable, B: Readable, C: Readable> Readable for (A, B, C) {
}
}
impl<A: Writeable, B: Writeable, C: Writeable> Writeable for (A, B, C) {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
self.0.write(w)?;
self.1.write(w)?;
self.2.write(w)

View file

@ -200,7 +200,7 @@ macro_rules! decode_tlv_stream {
macro_rules! impl_writeable {
($st:ident, $len: expr, {$($field:ident),*}) => {
impl ::util::ser::Writeable for $st {
fn write<W: ::util::ser::Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: ::util::ser::Writer>(&self, w: &mut W) -> Result<(), $crate::io::Error> {
if $len != 0 {
w.size_hint($len);
}
@ -235,7 +235,7 @@ macro_rules! impl_writeable {
}
impl ::util::ser::Readable for $st {
fn read<R: ::std::io::Read>(r: &mut R) -> Result<Self, ::ln::msgs::DecodeError> {
fn read<R: $crate::io::Read>(r: &mut R) -> Result<Self, ::ln::msgs::DecodeError> {
Ok(Self {
$($field: ::util::ser::Readable::read(r)?),*
})
@ -246,7 +246,7 @@ macro_rules! impl_writeable {
macro_rules! impl_writeable_len_match {
($struct: ident, $cmp: tt, ($calc_len: expr), {$({$match: pat, $length: expr}),*}, {$($field:ident),*}) => {
impl Writeable for $struct {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), $crate::io::Error> {
let len = match *self {
$($match => $length,)*
};
@ -282,7 +282,7 @@ macro_rules! impl_writeable_len_match {
}
impl ::util::ser::Readable for $struct {
fn read<R: ::std::io::Read>(r: &mut R) -> Result<Self, DecodeError> {
fn read<R: $crate::io::Read>(r: &mut R) -> Result<Self, DecodeError> {
Ok(Self {
$($field: Readable::read(r)?),*
})
@ -387,7 +387,7 @@ macro_rules! init_tlv_field_var {
macro_rules! impl_writeable_tlv_based {
($st: ident, {$(($type: expr, $field: ident, $fieldty: ident)),* $(,)*}) => {
impl ::util::ser::Writeable for $st {
fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), $crate::io::Error> {
write_tlv_fields!(writer, {
$(($type, self.$field, $fieldty)),*
});
@ -412,7 +412,7 @@ macro_rules! impl_writeable_tlv_based {
}
impl ::util::ser::Readable for $st {
fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, ::ln::msgs::DecodeError> {
fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Self, ::ln::msgs::DecodeError> {
$(
init_tlv_field_var!($field, $fieldty);
)*
@ -445,7 +445,7 @@ macro_rules! impl_writeable_tlv_based_enum {
),* $(,)*;
$(($tuple_variant_id: expr, $tuple_variant_name: ident)),* $(,)*) => {
impl ::util::ser::Writeable for $st {
fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), $crate::io::Error> {
match self {
$($st::$variant_name { $(ref $field),* } => {
let id: u8 = $variant_id;
@ -465,7 +465,7 @@ macro_rules! impl_writeable_tlv_based_enum {
}
impl ::util::ser::Readable for $st {
fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, ::ln::msgs::DecodeError> {
fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Self, ::ln::msgs::DecodeError> {
let id: u8 = ::util::ser::Readable::read(reader)?;
match id {
$($variant_id => {
@ -500,8 +500,8 @@ macro_rules! impl_writeable_tlv_based_enum {
#[cfg(test)]
mod tests {
use io::{self, Cursor};
use prelude::*;
use std::io::Cursor;
use ln::msgs::DecodeError;
use util::ser::{Writeable, HighZeroBytesDroppedVarInt, VecWriter};
use bitcoin::secp256k1::PublicKey;
@ -685,7 +685,7 @@ mod tests {
do_test!(concat!("fd00fe", "02", "0226"), None, None, None, Some(550));
}
fn do_simple_test_tlv_write() -> Result<(), ::std::io::Error> {
fn do_simple_test_tlv_write() -> Result<(), io::Error> {
let mut stream = VecWriter(Vec::new());
stream.0.clear();

View file

@ -37,6 +37,7 @@ use bitcoin::secp256k1::recovery::RecoverableSignature;
use regex;
use io;
use prelude::*;
use core::time::Duration;
use sync::{Mutex, Arc};
@ -46,7 +47,7 @@ use chain::keysinterface::InMemorySigner;
pub struct TestVecWriter(pub Vec<u8>);
impl Writer for TestVecWriter {
fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
self.0.extend_from_slice(buf);
Ok(())
}
@ -75,7 +76,7 @@ impl keysinterface::KeysInterface for OnlyReadsKeysInterface {
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))
EnforcingSigner::read(&mut io::Cursor::new(reader))
}
fn sign_invoice(&self, _invoice_preimage: Vec<u8>) -> Result<RecoverableSignature, ()> { unreachable!(); }
}
@ -114,7 +115,7 @@ impl<'a> chain::Watch<EnforcingSigner> for TestChainMonitor<'a> {
let mut w = TestVecWriter(Vec::new());
monitor.write(&mut w).unwrap();
let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
&mut ::std::io::Cursor::new(&w.0), self.keys_manager).unwrap().1;
&mut io::Cursor::new(&w.0), self.keys_manager).unwrap().1;
assert!(new_monitor == monitor);
self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(), (funding_txo, monitor.get_latest_update_id()));
self.added_monitors.lock().unwrap().push((funding_txo, monitor));
@ -136,7 +137,7 @@ impl<'a> chain::Watch<EnforcingSigner> for TestChainMonitor<'a> {
let mut w = TestVecWriter(Vec::new());
update.write(&mut w).unwrap();
assert!(channelmonitor::ChannelMonitorUpdate::read(
&mut ::std::io::Cursor::new(&w.0)).unwrap() == update);
&mut io::Cursor::new(&w.0)).unwrap() == update);
if let Some(exp) = self.expect_channel_force_closed.lock().unwrap().take() {
assert_eq!(funding_txo.to_channel_id(), exp.0);
@ -155,7 +156,7 @@ impl<'a> chain::Watch<EnforcingSigner> for TestChainMonitor<'a> {
w.0.clear();
monitor.write(&mut w).unwrap();
let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
&mut ::std::io::Cursor::new(&w.0), self.keys_manager).unwrap().1;
&mut io::Cursor::new(&w.0), self.keys_manager).unwrap().1;
assert!(new_monitor == *monitor);
self.added_monitors.lock().unwrap().push((funding_txo, new_monitor));
@ -481,7 +482,7 @@ impl keysinterface::KeysInterface for TestKeysInterface {
}
fn read_chan_signer(&self, buffer: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
let mut reader = std::io::Cursor::new(buffer);
let mut reader = io::Cursor::new(buffer);
let inner: InMemorySigner = Readable::read(&mut reader)?;
let revoked_commitment = self.make_revoked_commitment_cell(inner.commitment_seed);

View file

@ -15,6 +15,7 @@ use bitcoin::consensus::encode::VarInt;
use ln::msgs::MAX_VALUE_MSAT;
use prelude::*;
use io_extras::sink;
use core::cmp::Ordering;
pub fn sort_outputs<T, C : Fn(&T, &T) -> Ordering>(outputs: &mut Vec<(TxOut, T)>, tie_breaker: C) {
@ -56,7 +57,7 @@ pub(crate) fn maybe_add_change_output(tx: &mut Transaction, input_value: u64, wi
script_pubkey: change_destination_script,
value: 0,
};
let change_len = change_output.consensus_encode(&mut std::io::sink()).unwrap();
let change_len = change_output.consensus_encode(&mut sink()).unwrap();
let mut weight_with_change: i64 = tx.get_weight() as i64 + 2 + witness_max_weight as i64 + change_len as i64 * 4;
// Include any extra bytes required to push an extra output.
weight_with_change += (VarInt(tx.output.len() as u64 + 1).len() - VarInt(tx.output.len() as u64).len()) as i64 * 4;