From: Matt Corallo <649246+TheBlueMatt@users.noreply.github.com> Date: Mon, 24 May 2021 21:02:50 +0000 (+0000) Subject: Merge pull request #851 from TheBlueMatt/2021-03-holding-cell-clear-msg-get X-Git-Tag: v0.0.98~20 X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=commitdiff_plain;h=3a0356fe308ba29916d00f3376cd57ce6613f3d0;hp=34fcd99f51502b98e448955720828682eb38a9f5;p=rust-lightning Merge pull request #851 from TheBlueMatt/2021-03-holding-cell-clear-msg-get Clean up and more liberally free holding cell HTLCs (without re-entrancy) --- diff --git a/lightning/src/chain/chainmonitor.rs b/lightning/src/chain/chainmonitor.rs index f708bfe9..a9b570d5 100644 --- a/lightning/src/chain/chainmonitor.rs +++ b/lightning/src/chain/chainmonitor.rs @@ -39,7 +39,7 @@ use util::events::Event; use std::collections::{HashMap, hash_map}; use std::sync::RwLock; -use std::ops::Deref; +use core::ops::Deref; /// An implementation of [`chain::Watch`] for monitoring channels. /// diff --git a/lightning/src/chain/channelmonitor.rs b/lightning/src/chain/channelmonitor.rs index 62cb740e..8526ce51 100644 --- a/lightning/src/chain/channelmonitor.rs +++ b/lightning/src/chain/channelmonitor.rs @@ -52,9 +52,9 @@ use util::byte_utils; use util::events::Event; use std::collections::{HashMap, HashSet}; -use std::{cmp, mem}; +use core::{cmp, mem}; use std::io::Error; -use std::ops::Deref; +use core::ops::Deref; use std::sync::Mutex; /// An update generated by the underlying Channel itself which contains some new information the @@ -85,7 +85,7 @@ pub struct ChannelMonitorUpdate { /// then we allow the `ChannelManager` to send a `ChannelMonitorUpdate` with this update ID, /// with the update providing said payment preimage. No other update types are allowed after /// force-close. -pub const CLOSED_CHANNEL_UPDATE_ID: u64 = std::u64::MAX; +pub const CLOSED_CHANNEL_UPDATE_ID: u64 = core::u64::MAX; impl Writeable for ChannelMonitorUpdate { fn write(&self, w: &mut W) -> Result<(), ::std::io::Error> { @@ -101,7 +101,7 @@ impl Readable for ChannelMonitorUpdate { fn read(r: &mut R) -> Result { let update_id: u64 = Readable::read(r)?; let len: u64 = Readable::read(r)?; - let mut updates = Vec::with_capacity(cmp::min(len as usize, MAX_ALLOC_SIZE / ::std::mem::size_of::())); + let mut updates = Vec::with_capacity(cmp::min(len as usize, MAX_ALLOC_SIZE / ::core::mem::size_of::())); for _ in 0..len { updates.push(Readable::read(r)?); } @@ -1932,7 +1932,7 @@ impl ChannelMonitorImpl { for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() { if let Some(transaction_output_index) = htlc.transaction_output_index { - claim_requests.push(ClaimRequest { absolute_timelock: ::std::u32::MAX, aggregable: false, outpoint: BitcoinOutPoint { txid: holder_tx.txid, vout: transaction_output_index as u32 }, + claim_requests.push(ClaimRequest { absolute_timelock: ::core::u32::MAX, aggregable: false, outpoint: BitcoinOutPoint { txid: holder_tx.txid, vout: transaction_output_index as u32 }, witness_data: InputMaterial::HolderHTLC { preimage: if !htlc.offered { if let Some(preimage) = self.payment_preimages.get(&htlc.payment_hash) { @@ -2594,7 +2594,7 @@ impl ChannelMonitorImpl { fn is_paying_spendable_output(&mut self, tx: &Transaction, height: u32, logger: &L) where L::Target: Logger { let mut spendable_output = None; for (i, outp) in tx.output.iter().enumerate() { // There is max one spendable output for any channel tx, including ones generated by us - if i > ::std::u16::MAX as usize { + if i > ::core::u16::MAX as usize { // While it is possible that an output exists on chain which is greater than the // 2^16th output in a given transaction, this is only possible if the output is not // in a lightning transaction and was instead placed there by some third party who diff --git a/lightning/src/chain/keysinterface.rs b/lightning/src/chain/keysinterface.rs index 249a2f52..114ceec2 100644 --- a/lightning/src/chain/keysinterface.rs +++ b/lightning/src/chain/keysinterface.rs @@ -38,7 +38,7 @@ use ln::chan_utils::{HTLCOutputInCommitment, make_funding_redeemscript, ChannelP use ln::msgs::UnsignedChannelAnnouncement; use std::collections::HashSet; -use std::sync::atomic::{AtomicUsize, Ordering}; +use core::sync::atomic::{AtomicUsize, Ordering}; use std::io::Error; use ln::msgs::{DecodeError, MAX_VALUE_MSAT}; @@ -857,7 +857,7 @@ impl KeysManager { /// onchain output detection for which a corresponding delayed_payment_key must be derived. pub fn derive_channel_keys(&self, channel_value_satoshis: u64, params: &[u8; 32]) -> InMemorySigner { let chan_id = byte_utils::slice_to_be64(¶ms[0..8]); - assert!(chan_id <= std::u32::MAX as u64); // Otherwise the params field wasn't created by us + assert!(chan_id <= core::u32::MAX as u64); // Otherwise the params field wasn't created by us let mut unique_start = Sha256::engine(); unique_start.input(params); unique_start.input(&self.seed); @@ -1039,7 +1039,7 @@ impl KeysInterface for KeysManager { fn get_channel_signer(&self, _inbound: bool, channel_value_satoshis: u64) -> Self::Signer { let child_ix = self.channel_child_index.fetch_add(1, Ordering::AcqRel); - assert!(child_ix <= std::u32::MAX as usize); + assert!(child_ix <= core::u32::MAX as usize); let mut id = [0; 32]; id[0..8].copy_from_slice(&byte_utils::be64_to_array(child_ix as u64)); id[8..16].copy_from_slice(&byte_utils::be64_to_array(self.starting_time_nanos as u64)); diff --git a/lightning/src/chain/mod.rs b/lightning/src/chain/mod.rs index 2d62016e..42c74da1 100644 --- a/lightning/src/chain/mod.rs +++ b/lightning/src/chain/mod.rs @@ -246,7 +246,7 @@ pub struct WatchedOutput { pub script_pubkey: Script, } -impl Listen for std::ops::Deref { +impl Listen for core::ops::Deref { fn block_connected(&self, block: &Block, height: u32) { (**self).block_connected(block, height); } @@ -256,7 +256,7 @@ impl Listen for std::ops::Deref { } } -impl Listen for (T, U) +impl Listen for (T, U) where T::Target: Listen, U::Target: Listen, diff --git a/lightning/src/lib.rs b/lightning/src/lib.rs index 9bf94704..3c09f386 100644 --- a/lightning/src/lib.rs +++ b/lightning/src/lib.rs @@ -32,6 +32,7 @@ #[cfg(all(any(test, feature = "_test_utils"), feature = "unstable"))] extern crate test; extern crate bitcoin; +extern crate core; #[cfg(any(test, feature = "_test_utils"))] extern crate hex; #[cfg(any(test, feature = "fuzztarget", feature = "_test_utils"))] extern crate regex; diff --git a/lightning/src/ln/chan_utils.rs b/lightning/src/ln/chan_utils.rs index 44385796..9b44d119 100644 --- a/lightning/src/ln/chan_utils.rs +++ b/lightning/src/ln/chan_utils.rs @@ -31,12 +31,12 @@ use bitcoin::secp256k1::{Secp256k1, Signature, Message}; use bitcoin::secp256k1::Error as SecpError; use bitcoin::secp256k1; -use std::cmp; +use core::cmp; use ln::chan_utils; use util::transaction_utils::sort_outputs; use ln::channel::INITIAL_COMMITMENT_NUMBER; use std::io::Read; -use std::ops::Deref; +use core::ops::Deref; use chain; // Maximum size of a serialized HTLCOutputInCommitment diff --git a/lightning/src/ln/channel.rs b/lightning/src/ln/channel.rs index 639ac844..dbc63c95 100644 --- a/lightning/src/ln/channel.rs +++ b/lightning/src/ln/channel.rs @@ -39,9 +39,8 @@ use util::errors::APIError; use util::config::{UserConfig,ChannelConfig}; use util::scid_utils::scid_from_parts; -use std; -use std::{cmp,mem,fmt}; -use std::ops::Deref; +use core::{cmp,mem,fmt}; +use core::ops::Deref; #[cfg(any(test, feature = "fuzztarget"))] use std::sync::Mutex; use bitcoin::hashes::hex::ToHex; @@ -1220,7 +1219,7 @@ impl Channel { // on-chain ChannelsMonitors during block rescan. Ideally we'd figure out a way to drop // these, but for now we just have to treat them as normal. - let mut pending_idx = std::usize::MAX; + let mut pending_idx = core::usize::MAX; for (idx, htlc) in self.pending_inbound_htlcs.iter().enumerate() { if htlc.htlc_id == htlc_id_arg { assert_eq!(htlc.payment_hash, payment_hash_calc); @@ -1243,7 +1242,7 @@ impl Channel { break; } } - if pending_idx == std::usize::MAX { + if pending_idx == core::usize::MAX { return Err(ChannelError::Ignore("Unable to find a pending HTLC which matched the given HTLC ID".to_owned())); } @@ -1342,7 +1341,7 @@ impl Channel { // on-chain ChannelsMonitors during block rescan. Ideally we'd figure out a way to drop // these, but for now we just have to treat them as normal. - let mut pending_idx = std::usize::MAX; + let mut pending_idx = core::usize::MAX; for (idx, htlc) in self.pending_inbound_htlcs.iter().enumerate() { if htlc.htlc_id == htlc_id_arg { match htlc.state { @@ -1359,7 +1358,7 @@ impl Channel { pending_idx = idx; } } - if pending_idx == std::usize::MAX { + if pending_idx == core::usize::MAX { return Err(ChannelError::Ignore("Unable to find a pending HTLC which matched the given HTLC ID".to_owned())); } @@ -4390,8 +4389,8 @@ impl Writeable for Channel { let mut key_data = VecWriter(Vec::new()); self.holder_signer.write(&mut key_data)?; - assert!(key_data.0.len() < std::usize::MAX); - assert!(key_data.0.len() < std::u32::MAX as usize); + assert!(key_data.0.len() < core::usize::MAX); + assert!(key_data.0.len() < core::u32::MAX as usize); (key_data.0.len() as u32).write(writer)?; writer.write_all(&key_data.0[..])?; diff --git a/lightning/src/ln/channelmanager.rs b/lightning/src/ln/channelmanager.rs index 9f9820c1..190fb2bc 100644 --- a/lightning/src/ln/channelmanager.rs +++ b/lightning/src/ln/channelmanager.rs @@ -61,15 +61,15 @@ use util::chacha20::{ChaCha20, ChaChaReader}; use util::logger::Logger; use util::errors::APIError; -use std::{cmp, mem}; +use core::{cmp, mem}; use std::collections::{HashMap, hash_map, HashSet}; use std::io::{Cursor, Read}; use std::sync::{Arc, Condvar, Mutex, MutexGuard, RwLock, RwLockReadGuard}; -use std::sync::atomic::{AtomicUsize, Ordering}; -use std::time::Duration; +use core::sync::atomic::{AtomicUsize, Ordering}; +use core::time::Duration; #[cfg(any(test, feature = "allow_wallclock_use"))] use std::time::Instant; -use std::ops::Deref; +use core::ops::Deref; use bitcoin::hashes::hex::ToHex; // We hold various information about HTLC relay in the HTLC objects in Channel itself: @@ -1923,7 +1923,7 @@ impl ChannelMana // be absurd. We ensure this by checking that at least 500 (our stated public contract on when // broadcast_node_announcement panics) of the maximum-length addresses would fit in a 64KB // message... - const HALF_MESSAGE_IS_ADDRS: u32 = ::std::u16::MAX as u32 / (NetAddress::MAX_LEN as u32 + 1) / 2; + const HALF_MESSAGE_IS_ADDRS: u32 = ::core::u16::MAX as u32 / (NetAddress::MAX_LEN as u32 + 1) / 2; #[deny(const_err)] #[allow(dead_code)] // ...by failing to compile if the number of addresses that would be half of a message is @@ -4895,9 +4895,9 @@ impl<'a, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> mod tests { use ln::channelmanager::PersistenceNotifier; use std::sync::Arc; - use std::sync::atomic::{AtomicBool, Ordering}; + use core::sync::atomic::{AtomicBool, Ordering}; use std::thread; - use std::time::Duration; + use core::time::Duration; #[test] fn test_wait_timeout() { diff --git a/lightning/src/ln/features.rs b/lightning/src/ln/features.rs index 99e5cd09..cbe8cedf 100644 --- a/lightning/src/ln/features.rs +++ b/lightning/src/ln/features.rs @@ -22,8 +22,8 @@ //! [BOLT #9]: https://github.com/lightningnetwork/lightning-rfc/blob/master/09-features.md //! [messages]: crate::ln::msgs -use std::{cmp, fmt}; -use std::marker::PhantomData; +use core::{cmp, fmt}; +use core::marker::PhantomData; use bitcoin::bech32; use bitcoin::bech32::{Base32Len, FromBase32, ToBase32, u5, WriteBase32}; diff --git a/lightning/src/ln/functional_test_utils.rs b/lightning/src/ln/functional_test_utils.rs index c1ea9072..c1500508 100644 --- a/lightning/src/ln/functional_test_utils.rs +++ b/lightning/src/ln/functional_test_utils.rs @@ -39,10 +39,10 @@ use bitcoin::hash_types::BlockHash; use bitcoin::secp256k1::key::PublicKey; -use std::cell::RefCell; +use core::cell::RefCell; use std::rc::Rc; use std::sync::Mutex; -use std::mem; +use core::mem; use std::collections::HashMap; pub const CHAN_CONFIRM_DEPTH: u32 = 10; @@ -557,7 +557,7 @@ pub fn create_chan_between_nodes_with_value_confirm_second<'a, 'b, 'c>(node_recv } pub fn create_chan_between_nodes_with_value_confirm<'a, 'b, 'c, 'd>(node_a: &'a Node<'b, 'c, 'd>, node_b: &'a Node<'b, 'c, 'd>, tx: &Transaction) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) { - let conf_height = std::cmp::max(node_a.best_block_info().1 + 1, node_b.best_block_info().1 + 1); + let conf_height = core::cmp::max(node_a.best_block_info().1 + 1, node_b.best_block_info().1 + 1); create_chan_between_nodes_with_value_confirm_first(node_a, node_b, tx, conf_height); confirm_transaction_at(node_a, tx, conf_height); connect_blocks(node_a, CHAN_CONFIRM_DEPTH - 1); diff --git a/lightning/src/ln/functional_tests.rs b/lightning/src/ln/functional_tests.rs index 17602e27..9f1769ff 100644 --- a/lightning/src/ln/functional_tests.rs +++ b/lightning/src/ln/functional_tests.rs @@ -51,7 +51,7 @@ use bitcoin::secp256k1::key::{PublicKey,SecretKey}; use regex; use std::collections::{BTreeSet, HashMap, HashSet}; -use std::default::Default; +use core::default::Default; use std::sync::Mutex; use ln::functional_test_utils::*; diff --git a/lightning/src/ln/msgs.rs b/lightning/src/ln/msgs.rs index 5ae6955d..3c1a549a 100644 --- a/lightning/src/ln/msgs.rs +++ b/lightning/src/ln/msgs.rs @@ -32,8 +32,8 @@ use bitcoin::hash_types::{Txid, BlockHash}; use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures}; -use std::{cmp, fmt}; -use std::fmt::Debug; +use core::{cmp, fmt}; +use core::fmt::Debug; use std::io::Read; use util::events::MessageSendEventsProvider; diff --git a/lightning/src/ln/onchaintx.rs b/lightning/src/ln/onchaintx.rs index c7b79bf2..a51f2651 100644 --- a/lightning/src/ln/onchaintx.rs +++ b/lightning/src/ln/onchaintx.rs @@ -33,9 +33,9 @@ use util::ser::{Readable, ReadableArgs, Writer, Writeable, VecWriter}; use util::byte_utils; use std::collections::HashMap; -use std::cmp; -use std::ops::Deref; -use std::mem::replace; +use core::cmp; +use core::ops::Deref; +use core::mem::replace; const MAX_ALLOC_SIZE: usize = 64*1024; @@ -220,7 +220,7 @@ impl Readable for Option>> { 0u8 => Ok(None), 1u8 => { let vlen: u64 = Readable::read(reader)?; - let mut ret = Vec::with_capacity(cmp::min(vlen as usize, MAX_ALLOC_SIZE / ::std::mem::size_of::>())); + let mut ret = Vec::with_capacity(cmp::min(vlen as usize, MAX_ALLOC_SIZE / ::core::mem::size_of::>())); for _ in 0..vlen { ret.push(match Readable::read(reader)? { 0u8 => None, @@ -320,8 +320,8 @@ impl OnchainTxHandler { let mut key_data = VecWriter(Vec::new()); self.signer.write(&mut key_data)?; - assert!(key_data.0.len() < std::usize::MAX); - assert!(key_data.0.len() < std::u32::MAX as usize); + assert!(key_data.0.len() < core::usize::MAX); + assert!(key_data.0.len() < core::u32::MAX as usize); (key_data.0.len() as u32).write(writer)?; writer.write_all(&key_data.0[..])?; @@ -711,7 +711,7 @@ impl OnchainTxHandler { log_trace!(logger, "Updating claims view at height {} with {} matched transactions and {} claim requests", height, txn_matched.len(), claimable_outpoints.len()); let mut new_claims = Vec::new(); let mut aggregated_claim = HashMap::new(); - let mut aggregated_soonest = ::std::u32::MAX; + let mut aggregated_soonest = ::core::u32::MAX; // Try to aggregate outputs if their timelock expiration isn't imminent (absolute_timelock // <= CLTV_SHARED_CLAIM_BUFFER) and they don't require an immediate nLockTime (aggregable). diff --git a/lightning/src/ln/onion_route_tests.rs b/lightning/src/ln/onion_route_tests.rs index 6f178d21..e3184fc6 100644 --- a/lightning/src/ln/onion_route_tests.rs +++ b/lightning/src/ln/onion_route_tests.rs @@ -32,7 +32,7 @@ use bitcoin::hashes::Hash; use bitcoin::secp256k1::Secp256k1; use bitcoin::secp256k1::key::SecretKey; -use std::default::Default; +use core::default::Default; use std::io; use ln::functional_test_utils::*; diff --git a/lightning/src/ln/onion_utils.rs b/lightning/src/ln/onion_utils.rs index 6d9118e2..07686a21 100644 --- a/lightning/src/ln/onion_utils.rs +++ b/lightning/src/ln/onion_utils.rs @@ -28,7 +28,7 @@ use bitcoin::secp256k1::ecdh::SharedSecret; use bitcoin::secp256k1; use std::io::Cursor; -use std::ops::Deref; +use core::ops::Deref; pub(super) struct OnionKeys { #[cfg(test)] diff --git a/lightning/src/ln/peer_channel_encryptor.rs b/lightning/src/ln/peer_channel_encryptor.rs index d38d5ae6..dd8619bf 100644 --- a/lightning/src/ln/peer_channel_encryptor.rs +++ b/lightning/src/ln/peer_channel_encryptor.rs @@ -25,7 +25,7 @@ use bitcoin::hashes::hex::ToHex; /// Maximum Lightning message data length according to /// [BOLT-8](https://github.com/lightningnetwork/lightning-rfc/blob/v1.0/08-transport.md#lightning-message-specification) /// and [BOLT-1](https://github.com/lightningnetwork/lightning-rfc/blob/master/01-messaging.md#lightning-message-format): -pub const LN_MAX_MSG_LEN: usize = ::std::u16::MAX as usize; // Must be equal to 65535 +pub const LN_MAX_MSG_LEN: usize = ::core::u16::MAX as usize; // Must be equal to 65535 // Sha256("Noise_XK_secp256k1_ChaChaPoly_SHA256") const NOISE_CK: [u8; 32] = [0x26, 0x40, 0xf5, 0x2e, 0xeb, 0xcd, 0x9e, 0x88, 0x29, 0x58, 0x95, 0x1c, 0x79, 0x42, 0x50, 0xee, 0xdb, 0x28, 0x00, 0x2c, 0x05, 0xd7, 0xdc, 0x2e, 0xa0, 0xf1, 0x95, 0x40, 0x60, 0x42, 0xca, 0xf1]; @@ -715,7 +715,7 @@ mod tests { #[test] fn max_msg_len_limit_value() { assert_eq!(LN_MAX_MSG_LEN, 65535); - assert_eq!(LN_MAX_MSG_LEN, ::std::u16::MAX as usize); + assert_eq!(LN_MAX_MSG_LEN, ::core::u16::MAX as usize); } #[test] diff --git a/lightning/src/ln/peer_handler.rs b/lightning/src/ln/peer_handler.rs index f9e79429..097e9928 100644 --- a/lightning/src/ln/peer_handler.rs +++ b/lightning/src/ln/peer_handler.rs @@ -32,9 +32,10 @@ use routing::network_graph::NetGraphMsgHandler; use std::collections::{HashMap,hash_map,HashSet,LinkedList}; use std::sync::{Arc, Mutex}; -use std::sync::atomic::{AtomicUsize, Ordering}; -use std::{cmp, error, hash, fmt, mem}; -use std::ops::Deref; +use core::sync::atomic::{AtomicUsize, Ordering}; +use core::{cmp, hash, fmt, mem}; +use core::ops::Deref; +use std::error; use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::hashes::sha256::HashEngine as Sha256Engine; @@ -1420,9 +1421,8 @@ mod tests { use bitcoin::secp256k1::Secp256k1; use bitcoin::secp256k1::key::{SecretKey, PublicKey}; - use std; use std::sync::{Arc, Mutex}; - use std::sync::atomic::Ordering; + use core::sync::atomic::Ordering; #[derive(Clone)] struct FileDescriptor { @@ -1435,8 +1435,8 @@ mod tests { } } impl Eq for FileDescriptor { } - impl std::hash::Hash for FileDescriptor { - fn hash(&self, hasher: &mut H) { + impl core::hash::Hash for FileDescriptor { + fn hash(&self, hasher: &mut H) { self.fd.hash(hasher) } } diff --git a/lightning/src/ln/reorg_tests.rs b/lightning/src/ln/reorg_tests.rs index e5feeb25..6906e724 100644 --- a/lightning/src/ln/reorg_tests.rs +++ b/lightning/src/ln/reorg_tests.rs @@ -23,7 +23,7 @@ use bitcoin::blockdata::block::{Block, BlockHeader}; use bitcoin::hash_types::BlockHash; use std::collections::HashMap; -use std::mem; +use core::mem; use ln::functional_test_utils::*; diff --git a/lightning/src/ln/wire.rs b/lightning/src/ln/wire.rs index 12e77d07..532ebbf3 100644 --- a/lightning/src/ln/wire.rs +++ b/lightning/src/ln/wire.rs @@ -105,8 +105,8 @@ impl MessageType { } } -impl ::std::fmt::Display for MessageType { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { +impl ::core::fmt::Display for MessageType { + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}", self.0) } } @@ -396,12 +396,12 @@ mod tests { #[test] fn read_unknown_message() { - let buffer = &byte_utils::be16_to_array(::std::u16::MAX); + let buffer = &byte_utils::be16_to_array(::core::u16::MAX); let mut reader = ::std::io::Cursor::new(buffer); let message = read(&mut reader).unwrap(); match message { - Message::Unknown(MessageType(::std::u16::MAX)) => (), - _ => panic!("Expected message type {}; found: {}", ::std::u16::MAX, message.type_id()), + Message::Unknown(MessageType(::core::u16::MAX)) => (), + _ => panic!("Expected message type {}; found: {}", ::core::u16::MAX, message.type_id()), } } @@ -411,7 +411,7 @@ mod tests { let mut buffer = Vec::new(); assert!(write(&message, &mut buffer).is_ok()); - let type_length = ::std::mem::size_of::(); + let type_length = ::core::mem::size_of::(); let (type_bytes, payload_bytes) = buffer.split_at(type_length); assert_eq!(byte_utils::slice_to_be16(type_bytes), msgs::Pong::TYPE); assert_eq!(payload_bytes, &ENCODED_PONG[type_length..]); diff --git a/lightning/src/routing/network_graph.rs b/lightning/src/routing/network_graph.rs index 765a3430..ee73dc0e 100644 --- a/lightning/src/routing/network_graph.rs +++ b/lightning/src/routing/network_graph.rs @@ -32,13 +32,13 @@ use util::logger::Logger; use util::events::{MessageSendEvent, MessageSendEventsProvider}; use util::scid_utils::{block_from_scid, scid_from_parts, MAX_SCID_BLOCK}; -use std::{cmp, fmt}; +use core::{cmp, fmt}; use std::sync::{RwLock, RwLockReadGuard}; -use std::sync::atomic::{AtomicUsize, Ordering}; +use core::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Mutex; use std::collections::BTreeMap; use std::collections::btree_map::Entry as BtreeEntry; -use std::ops::Deref; +use core::ops::Deref; use bitcoin::hashes::hex::ToHex; /// The maximum number of extra bytes which we do not understand in a gossip message before we will @@ -423,7 +423,7 @@ where fn get_and_clear_pending_msg_events(&self) -> Vec { let mut ret = Vec::new(); let mut pending_events = self.pending_events.lock().unwrap(); - std::mem::swap(&mut ret, &mut pending_events); + core::mem::swap(&mut ret, &mut pending_events); ret } } diff --git a/lightning/src/routing/router.rs b/lightning/src/routing/router.rs index ca7f30e3..ba964d73 100644 --- a/lightning/src/routing/router.rs +++ b/lightning/src/routing/router.rs @@ -21,9 +21,9 @@ use routing::network_graph::{NetworkGraph, RoutingFees}; use util::ser::{Writeable, Readable}; use util::logger::Logger; -use std::cmp; +use core::cmp; use std::collections::{HashMap, BinaryHeap}; -use std::ops::Deref; +use core::ops::Deref; /// A hop in a route #[derive(Clone, PartialEq)] @@ -3872,7 +3872,7 @@ mod tests { 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 std::hash::{BuildHasher, Hasher}; + use core::hash::{BuildHasher, Hasher}; let seed = std::collections::hash_map::RandomState::new().build_hasher().finish(); println!("Using seed of {}", seed); seed diff --git a/lightning/src/util/chacha20.rs b/lightning/src/util/chacha20.rs index c23856b6..e8c6e229 100644 --- a/lightning/src/util/chacha20.rs +++ b/lightning/src/util/chacha20.rs @@ -13,13 +13,13 @@ use std::io; #[cfg(not(feature = "fuzztarget"))] mod real_chacha { - use std::cmp; + use core::cmp; use util::byte_utils::{slice_to_le32, le32_to_array}; #[derive(Clone, Copy, PartialEq, Eq)] #[allow(non_camel_case_types)] struct u32x4(pub u32, pub u32, pub u32, pub u32); - impl ::std::ops::Add for u32x4 { + impl ::core::ops::Add for u32x4 { type Output = u32x4; fn add(self, rhs: u32x4) -> u32x4 { u32x4(self.0.wrapping_add(rhs.0), @@ -28,7 +28,7 @@ mod real_chacha { self.3.wrapping_add(rhs.3)) } } - impl ::std::ops::Sub for u32x4 { + impl ::core::ops::Sub for u32x4 { type Output = u32x4; fn sub(self, rhs: u32x4) -> u32x4 { u32x4(self.0.wrapping_sub(rhs.0), @@ -37,19 +37,19 @@ mod real_chacha { self.3.wrapping_sub(rhs.3)) } } - impl ::std::ops::BitXor for u32x4 { + impl ::core::ops::BitXor for u32x4 { type Output = u32x4; fn bitxor(self, rhs: u32x4) -> u32x4 { u32x4(self.0 ^ rhs.0, self.1 ^ rhs.1, self.2 ^ rhs.2, self.3 ^ rhs.3) } } - impl ::std::ops::Shr for u32x4 { + impl ::core::ops::Shr for u32x4 { type Output = u32x4; fn shr(self, rhs: u32x4) -> u32x4 { u32x4(self.0 >> rhs.0, self.1 >> rhs.1, self.2 >> rhs.2, self.3 >> rhs.3) } } - impl ::std::ops::Shl for u32x4 { + impl ::core::ops::Shl for u32x4 { type Output = u32x4; fn shl(self, rhs: u32x4) -> u32x4 { u32x4(self.0 << rhs.0, self.1 << rhs.1, self.2 << rhs.2, self.3 << rhs.3) @@ -318,7 +318,7 @@ impl<'a, R: io::Read> io::Read for ChaChaReader<'a, R> { #[cfg(test)] mod test { - use std::iter::repeat; + use core::iter::repeat; use super::ChaCha20; diff --git a/lightning/src/util/enforcing_trait_impls.rs b/lightning/src/util/enforcing_trait_impls.rs index c2908836..32c17af6 100644 --- a/lightning/src/util/enforcing_trait_impls.rs +++ b/lightning/src/util/enforcing_trait_impls.rs @@ -11,7 +11,7 @@ use ln::chan_utils::{HTLCOutputInCommitment, ChannelPublicKeys, HolderCommitment use ln::{chan_utils, msgs}; use chain::keysinterface::{Sign, InMemorySigner, BaseSign}; -use std::cmp; +use core::cmp; use std::sync::{Mutex, Arc}; use bitcoin::blockdata::transaction::{Transaction, SigHashType}; diff --git a/lightning/src/util/errors.rs b/lightning/src/util/errors.rs index f67621c8..b47e134e 100644 --- a/lightning/src/util/errors.rs +++ b/lightning/src/util/errors.rs @@ -9,7 +9,7 @@ //! Error types live here. -use std::fmt; +use core::fmt; /// Indicates an error on the client's part (usually some variant of attempting to use too-low or /// too-high values) diff --git a/lightning/src/util/events.rs b/lightning/src/util/events.rs index 599ed2af..b7b8bf31 100644 --- a/lightning/src/util/events.rs +++ b/lightning/src/util/events.rs @@ -23,7 +23,7 @@ use bitcoin::blockdata::script::Script; use bitcoin::secp256k1::key::PublicKey; -use std::time::Duration; +use core::time::Duration; /// An Event which you should probably take some action in response to. /// diff --git a/lightning/src/util/logger.rs b/lightning/src/util/logger.rs index 2cf0f136..df2b7f70 100644 --- a/lightning/src/util/logger.rs +++ b/lightning/src/util/logger.rs @@ -14,8 +14,8 @@ //! The second one, client-side by implementing check against Record Level field. //! Each module may have its own Logger or share one. -use std::cmp; -use std::fmt; +use core::cmp; +use core::fmt; static LOG_LEVEL_NAMES: [&'static str; 6] = ["OFF", "ERROR", "WARN", "INFO", "DEBUG", "TRACE"]; diff --git a/lightning/src/util/macro_logger.rs b/lightning/src/util/macro_logger.rs index 330d31b6..c4630c63 100644 --- a/lightning/src/util/macro_logger.rs +++ b/lightning/src/util/macro_logger.rs @@ -17,11 +17,9 @@ use bitcoin::secp256k1::key::PublicKey; use routing::router::Route; use ln::chan_utils::HTLCType; -use std; - pub(crate) struct DebugPubKey<'a>(pub &'a PublicKey); -impl<'a> std::fmt::Display for DebugPubKey<'a> { - fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { +impl<'a> core::fmt::Display for DebugPubKey<'a> { + fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> { for i in self.0.serialize().iter() { write!(f, "{:02x}", i)?; } @@ -35,8 +33,8 @@ macro_rules! log_pubkey { } pub(crate) struct DebugBytes<'a>(pub &'a [u8]); -impl<'a> std::fmt::Display for DebugBytes<'a> { - fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { +impl<'a> core::fmt::Display for DebugBytes<'a> { + fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> { for i in self.0 { write!(f, "{:02x}", i)?; } @@ -50,8 +48,8 @@ macro_rules! log_bytes { } pub(crate) struct DebugFundingChannelId<'a>(pub &'a Txid, pub u16); -impl<'a> std::fmt::Display for DebugFundingChannelId<'a> { - fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { +impl<'a> core::fmt::Display for DebugFundingChannelId<'a> { + fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> { for i in (OutPoint { txid: self.0.clone(), index: self.1 }).to_channel_id().iter() { write!(f, "{:02x}", i)?; } @@ -65,8 +63,8 @@ macro_rules! log_funding_channel_id { } pub(crate) struct DebugFundingInfo<'a, T: 'a>(pub &'a (OutPoint, T)); -impl<'a, T> std::fmt::Display for DebugFundingInfo<'a, T> { - fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { +impl<'a, T> core::fmt::Display for DebugFundingInfo<'a, T> { + fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> { DebugBytes(&(self.0).0.to_channel_id()[..]).fmt(f) } } @@ -77,8 +75,8 @@ macro_rules! log_funding_info { } pub(crate) struct DebugRoute<'a>(pub &'a Route); -impl<'a> std::fmt::Display for DebugRoute<'a> { - fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { +impl<'a> core::fmt::Display for DebugRoute<'a> { + fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> { for (idx, p) in self.0.paths.iter().enumerate() { writeln!(f, "path {}:", idx)?; for h in p.iter() { @@ -95,8 +93,8 @@ macro_rules! log_route { } pub(crate) struct DebugTx<'a>(pub &'a Transaction); -impl<'a> std::fmt::Display for DebugTx<'a> { - fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { +impl<'a> core::fmt::Display for DebugTx<'a> { + fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> { if self.0.input.len() >= 1 && self.0.input.iter().any(|i| !i.witness.is_empty()) { if self.0.input.len() == 1 && self.0.input[0].witness.last().unwrap().len() == 71 && (self.0.input[0].sequence >> 8*3) as u8 == 0x80 { @@ -134,8 +132,8 @@ macro_rules! log_tx { } pub(crate) struct DebugSpendable<'a>(pub &'a SpendableOutputDescriptor); -impl<'a> std::fmt::Display for DebugSpendable<'a> { - fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { +impl<'a> core::fmt::Display for DebugSpendable<'a> { + fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> { match self.0 { &SpendableOutputDescriptor::StaticOutput { ref outpoint, .. } => { write!(f, "StaticOutput {}:{} marked for spending", outpoint.txid, outpoint.index)?; diff --git a/lightning/src/util/message_signing.rs b/lightning/src/util/message_signing.rs index b73ba2b4..1ad1ea5e 100644 --- a/lightning/src/util/message_signing.rs +++ b/lightning/src/util/message_signing.rs @@ -82,7 +82,7 @@ pub fn verify(msg: &[u8], sig: &str, pk: PublicKey) -> bool { #[cfg(test)] mod test { - use std::str::FromStr; + use core::str::FromStr; use util::message_signing::{sign, recover_pk, verify}; use bitcoin::secp256k1::key::ONE_KEY; use bitcoin::secp256k1::{PublicKey, Secp256k1}; diff --git a/lightning/src/util/poly1305.rs b/lightning/src/util/poly1305.rs index d5173f2e..c6dbb43d 100644 --- a/lightning/src/util/poly1305.rs +++ b/lightning/src/util/poly1305.rs @@ -7,7 +7,7 @@ // This is a port of Andrew Moons poly1305-donna // https://github.com/floodyberry/poly1305-donna -use std::cmp::min; +use core::cmp::min; use util::byte_utils::{slice_to_le32, le32_to_array}; #[derive(Clone, Copy)] @@ -205,7 +205,7 @@ impl Poly1305 { #[cfg(test)] mod test { - use std::iter::repeat; + use core::iter::repeat; use util::poly1305::Poly1305; diff --git a/lightning/src/util/ser.rs b/lightning/src/util/ser.rs index c31fcaa1..66c89aa8 100644 --- a/lightning/src/util/ser.rs +++ b/lightning/src/util/ser.rs @@ -12,9 +12,9 @@ use std::io::{Read, Write}; use std::collections::HashMap; -use std::hash::Hash; +use core::hash::Hash; use std::sync::Mutex; -use std::cmp; +use core::cmp; use bitcoin::secp256k1::Signature; use bitcoin::secp256k1::key::{PublicKey, SecretKey}; @@ -25,7 +25,7 @@ use bitcoin::consensus; use bitcoin::consensus::Encodable; use bitcoin::hashes::sha256d::Hash as Sha256dHash; use bitcoin::hash_types::{Txid, BlockHash}; -use std::marker::Sized; +use core::marker::Sized; use ln::msgs::DecodeError; use ln::{PaymentPreimage, PaymentHash, PaymentSecret}; use util::byte_utils; diff --git a/lightning/src/util/test_utils.rs b/lightning/src/util/test_utils.rs index 00c346a8..c167c341 100644 --- a/lightning/src/util/test_utils.rs +++ b/lightning/src/util/test_utils.rs @@ -36,10 +36,10 @@ use bitcoin::secp256k1::recovery::RecoverableSignature; use regex; -use std::time::Duration; +use core::time::Duration; use std::sync::{Mutex, Arc}; -use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; -use std::{cmp, mem}; +use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use core::{cmp, mem}; use std::collections::{HashMap, HashSet, VecDeque}; use chain::keysinterface::InMemorySigner; @@ -624,8 +624,8 @@ impl OnRegisterOutput { } } -impl std::fmt::Debug for OnRegisterOutput { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Debug for OnRegisterOutput { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("OnRegisterOutput") .field("outpoint", &self.outpoint()) .field("script_pubkey", self.script_pubkey()) diff --git a/lightning/src/util/transaction_utils.rs b/lightning/src/util/transaction_utils.rs index 1984b480..34d0fb27 100644 --- a/lightning/src/util/transaction_utils.rs +++ b/lightning/src/util/transaction_utils.rs @@ -14,7 +14,7 @@ use bitcoin::consensus::encode::VarInt; use ln::msgs::MAX_VALUE_MSAT; -use std::cmp::Ordering; +use core::cmp::Ordering; pub fn sort_outputs Ordering>(outputs: &mut Vec<(TxOut, T)>, tie_breaker: C) { outputs.sort_unstable_by(|a, b| {