From: Wilmer Paulino Date: Thu, 1 Dec 2022 22:45:46 +0000 (-0800) Subject: Remove unnecessary byte_utils helpers X-Git-Tag: v0.0.113~15^2 X-Git-Url: http://git.bitcoin.ninja/?a=commitdiff_plain;h=444fce71f4075527c81ac76b1e2bb440d468ecf0;p=rust-lightning Remove unnecessary byte_utils helpers Now that to_be_bytes is available under our current MSRV of 1.41, we can use it instead of our own version. --- diff --git a/lightning/src/chain/channelmonitor.rs b/lightning/src/chain/channelmonitor.rs index df4296392..585b64646 100644 --- a/lightning/src/chain/channelmonitor.rs +++ b/lightning/src/chain/channelmonitor.rs @@ -291,7 +291,7 @@ struct CounterpartyCommitmentParameters { impl Writeable for CounterpartyCommitmentParameters { fn write(&self, w: &mut W) -> Result<(), io::Error> { - w.write_all(&byte_utils::be64_to_array(0))?; + w.write_all(&(0 as u64).to_be_bytes())?; write_tlv_fields!(w, { (0, self.counterparty_delayed_payment_base_key, required), (2, self.counterparty_htlc_base_key, required), @@ -945,7 +945,7 @@ impl Writeable for ChannelMonitorImpl { self.channel_keys_id.write(writer)?; self.holder_revocation_basepoint.write(writer)?; writer.write_all(&self.funding_info.0.txid[..])?; - writer.write_all(&byte_utils::be16_to_array(self.funding_info.0.index))?; + writer.write_all(&self.funding_info.0.index.to_be_bytes())?; self.funding_info.1.write(writer)?; self.current_counterparty_commitment_txid.write(writer)?; self.prev_counterparty_commitment_txid.write(writer)?; @@ -972,24 +972,24 @@ impl Writeable for ChannelMonitorImpl { }, } - writer.write_all(&byte_utils::be16_to_array(self.on_holder_tx_csv))?; + writer.write_all(&self.on_holder_tx_csv.to_be_bytes())?; self.commitment_secrets.write(writer)?; macro_rules! serialize_htlc_in_commitment { ($htlc_output: expr) => { writer.write_all(&[$htlc_output.offered as u8; 1])?; - writer.write_all(&byte_utils::be64_to_array($htlc_output.amount_msat))?; - writer.write_all(&byte_utils::be32_to_array($htlc_output.cltv_expiry))?; + writer.write_all(&$htlc_output.amount_msat.to_be_bytes())?; + writer.write_all(&$htlc_output.cltv_expiry.to_be_bytes())?; writer.write_all(&$htlc_output.payment_hash.0[..])?; $htlc_output.transaction_output_index.write(writer)?; } } - writer.write_all(&byte_utils::be64_to_array(self.counterparty_claimable_outpoints.len() as u64))?; + writer.write_all(&(self.counterparty_claimable_outpoints.len() as u64).to_be_bytes())?; for (ref txid, ref htlc_infos) in self.counterparty_claimable_outpoints.iter() { writer.write_all(&txid[..])?; - writer.write_all(&byte_utils::be64_to_array(htlc_infos.len() as u64))?; + writer.write_all(&(htlc_infos.len() as u64).to_be_bytes())?; for &(ref htlc_output, ref htlc_source) in htlc_infos.iter() { debug_assert!(htlc_source.is_none() || Some(**txid) == self.current_counterparty_commitment_txid || Some(**txid) == self.prev_counterparty_commitment_txid, @@ -999,13 +999,13 @@ impl Writeable for ChannelMonitorImpl { } } - writer.write_all(&byte_utils::be64_to_array(self.counterparty_commitment_txn_on_chain.len() as u64))?; + writer.write_all(&(self.counterparty_commitment_txn_on_chain.len() as u64).to_be_bytes())?; for (ref txid, commitment_number) in self.counterparty_commitment_txn_on_chain.iter() { writer.write_all(&txid[..])?; writer.write_all(&byte_utils::be48_to_array(*commitment_number))?; } - writer.write_all(&byte_utils::be64_to_array(self.counterparty_hash_commitment_number.len() as u64))?; + writer.write_all(&(self.counterparty_hash_commitment_number.len() as u64).to_be_bytes())?; for (ref payment_hash, commitment_number) in self.counterparty_hash_commitment_number.iter() { writer.write_all(&payment_hash.0[..])?; writer.write_all(&byte_utils::be48_to_array(*commitment_number))?; @@ -1023,7 +1023,7 @@ impl Writeable for ChannelMonitorImpl { writer.write_all(&byte_utils::be48_to_array(self.current_counterparty_commitment_number))?; writer.write_all(&byte_utils::be48_to_array(self.current_holder_commitment_number))?; - writer.write_all(&byte_utils::be64_to_array(self.payment_preimages.len() as u64))?; + writer.write_all(&(self.payment_preimages.len() as u64).to_be_bytes())?; for payment_preimage in self.payment_preimages.values() { writer.write_all(&payment_preimage.0[..])?; } @@ -1044,15 +1044,15 @@ impl Writeable for ChannelMonitorImpl { } } - writer.write_all(&byte_utils::be64_to_array(self.pending_events.len() as u64))?; + writer.write_all(&(self.pending_events.len() as u64).to_be_bytes())?; for event in self.pending_events.iter() { event.write(writer)?; } self.best_block.block_hash().write(writer)?; - writer.write_all(&byte_utils::be32_to_array(self.best_block.height()))?; + writer.write_all(&self.best_block.height().to_be_bytes())?; - writer.write_all(&byte_utils::be64_to_array(self.onchain_events_awaiting_threshold_conf.len() as u64))?; + writer.write_all(&(self.onchain_events_awaiting_threshold_conf.len() as u64).to_be_bytes())?; for ref entry in self.onchain_events_awaiting_threshold_conf.iter() { entry.write(writer)?; } diff --git a/lightning/src/chain/keysinterface.rs b/lightning/src/chain/keysinterface.rs index 104841b96..677b36ad6 100644 --- a/lightning/src/chain/keysinterface.rs +++ b/lightning/src/chain/keysinterface.rs @@ -31,7 +31,7 @@ use bitcoin::secp256k1::ecdh::SharedSecret; use bitcoin::secp256k1::ecdsa::RecoverableSignature; use bitcoin::{PackedLockTime, secp256k1, Sequence, Witness}; -use crate::util::{byte_utils, transaction_utils}; +use crate::util::transaction_utils; use crate::util::crypto::{hkdf_extract_expand_twice, sign}; use crate::util::ser::{Writeable, Writer, Readable, ReadableArgs}; @@ -43,6 +43,7 @@ use crate::ln::msgs::UnsignedChannelAnnouncement; use crate::ln::script::ShutdownScript; use crate::prelude::*; +use core::convert::TryInto; use core::sync::atomic::{AtomicUsize, Ordering}; use crate::io::{self, Error}; use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT}; @@ -969,8 +970,8 @@ impl KeysManager { inbound_pmt_key_bytes.copy_from_slice(&inbound_payment_key[..]); let mut rand_bytes_unique_start = Sha256::engine(); - rand_bytes_unique_start.input(&byte_utils::be64_to_array(starting_time_secs)); - rand_bytes_unique_start.input(&byte_utils::be32_to_array(starting_time_nanos)); + rand_bytes_unique_start.input(&starting_time_secs.to_be_bytes()); + rand_bytes_unique_start.input(&starting_time_nanos.to_be_bytes()); rand_bytes_unique_start.input(seed); let mut res = KeysManager { @@ -1002,7 +1003,7 @@ impl KeysManager { } /// Derive an old Sign containing per-channel secrets based on a key derivation parameters. 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]); + let chan_id = u64::from_be_bytes(params[0..8].try_into().unwrap()); let mut unique_start = Sha256::engine(); unique_start.input(params); unique_start.input(&self.seed); diff --git a/lightning/src/chain/onchaintx.rs b/lightning/src/chain/onchaintx.rs index abbd047de..a0850dfb2 100644 --- a/lightning/src/chain/onchaintx.rs +++ b/lightning/src/chain/onchaintx.rs @@ -37,7 +37,6 @@ use crate::chain::package::PackageSolvingData; use crate::chain::package::PackageTemplate; use crate::util::logger::Logger; use crate::util::ser::{Readable, ReadableArgs, MaybeReadable, Writer, Writeable, VecWriter}; -use crate::util::byte_utils; use crate::io; use crate::prelude::*; @@ -272,29 +271,29 @@ impl OnchainTxHandler { (key_data.0.len() as u32).write(writer)?; writer.write_all(&key_data.0[..])?; - writer.write_all(&byte_utils::be64_to_array(self.pending_claim_requests.len() as u64))?; + writer.write_all(&(self.pending_claim_requests.len() as u64).to_be_bytes())?; for (ref ancestor_claim_txid, request) in self.pending_claim_requests.iter() { ancestor_claim_txid.write(writer)?; request.write(writer)?; } - writer.write_all(&byte_utils::be64_to_array(self.claimable_outpoints.len() as u64))?; + writer.write_all(&(self.claimable_outpoints.len() as u64).to_be_bytes())?; for (ref outp, ref claim_and_height) in self.claimable_outpoints.iter() { outp.write(writer)?; claim_and_height.0.write(writer)?; claim_and_height.1.write(writer)?; } - writer.write_all(&byte_utils::be64_to_array(self.locktimed_packages.len() as u64))?; + writer.write_all(&(self.locktimed_packages.len() as u64).to_be_bytes())?; for (ref locktime, ref packages) in self.locktimed_packages.iter() { locktime.write(writer)?; - writer.write_all(&byte_utils::be64_to_array(packages.len() as u64))?; + writer.write_all(&(packages.len() as u64).to_be_bytes())?; for ref package in packages.iter() { package.write(writer)?; } } - writer.write_all(&byte_utils::be64_to_array(self.onchain_events_awaiting_threshold_conf.len() as u64))?; + writer.write_all(&(self.onchain_events_awaiting_threshold_conf.len() as u64).to_be_bytes())?; for ref entry in self.onchain_events_awaiting_threshold_conf.iter() { entry.write(writer)?; } diff --git a/lightning/src/chain/package.rs b/lightning/src/chain/package.rs index 1307ad0eb..7ccabb50b 100644 --- a/lightning/src/chain/package.rs +++ b/lightning/src/chain/package.rs @@ -27,7 +27,6 @@ use crate::ln::msgs::DecodeError; use crate::chain::chaininterface::{FeeEstimator, ConfirmationTarget, MIN_RELAY_FEE_SAT_PER_1000_WEIGHT}; use crate::chain::keysinterface::Sign; use crate::chain::onchaintx::OnchainTxHandler; -use crate::util::byte_utils; use crate::util::logger::Logger; use crate::util::ser::{Readable, Writer, Writeable}; @@ -774,7 +773,7 @@ impl PackageTemplate { impl Writeable for PackageTemplate { fn write(&self, writer: &mut W) -> Result<(), io::Error> { - writer.write_all(&byte_utils::be64_to_array(self.inputs.len() as u64))?; + writer.write_all(&(self.inputs.len() as u64).to_be_bytes())?; for (ref outpoint, ref rev_outp) in self.inputs.iter() { outpoint.write(writer)?; rev_outp.write(writer)?; diff --git a/lightning/src/ln/chan_utils.rs b/lightning/src/ln/chan_utils.rs index 4a66f85e2..77aec9f23 100644 --- a/lightning/src/ln/chan_utils.rs +++ b/lightning/src/ln/chan_utils.rs @@ -24,7 +24,7 @@ use bitcoin::hash_types::{Txid, PubkeyHash}; use crate::ln::{PaymentHash, PaymentPreimage}; use crate::ln::msgs::DecodeError; use crate::util::ser::{Readable, Writeable, Writer}; -use crate::util::{byte_utils, transaction_utils}; +use crate::util::transaction_utils; use bitcoin::secp256k1::{SecretKey, PublicKey, Scalar}; use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature, Message}; @@ -310,7 +310,7 @@ impl Writeable for CounterpartyCommitmentSecrets { fn write(&self, writer: &mut W) -> Result<(), io::Error> { for &(ref secret, ref idx) in self.old_secrets.iter() { writer.write_all(secret)?; - writer.write_all(&byte_utils::be64_to_array(*idx))?; + writer.write_all(&idx.to_be_bytes())?; } write_tlv_fields!(writer, {}); Ok(()) diff --git a/lightning/src/ln/channelmanager.rs b/lightning/src/ln/channelmanager.rs index 2281198b1..1e833b704 100644 --- a/lightning/src/ln/channelmanager.rs +++ b/lightning/src/ln/channelmanager.rs @@ -54,7 +54,7 @@ use crate::ln::wire::Encode; use crate::chain::keysinterface::{Sign, KeysInterface, KeysManager, Recipient}; use crate::util::config::{UserConfig, ChannelConfig}; use crate::util::events::{Event, EventHandler, EventsProvider, MessageSendEvent, MessageSendEventsProvider, ClosureReason, HTLCDestination}; -use crate::util::{byte_utils, events}; +use crate::util::events; use crate::util::wakers::{Future, Notifier}; use crate::util::scid_utils::fake_scid; use crate::util::ser::{BigSize, FixedLengthReader, Readable, ReadableArgs, MaybeReadable, Writeable, Writer, VecWriter}; @@ -2053,7 +2053,7 @@ impl ChannelManager ChannelManager amt_msat { return Err(ReceiveError { err_code: 19, - err_data: byte_utils::be64_to_array(amt_msat).to_vec(), + err_data: amt_msat.to_be_bytes().to_vec(), msg: "Upstream node sent less than we were supposed to receive in payment", }); } @@ -3451,9 +3451,9 @@ impl ChannelManager { - let mut htlc_msat_height_data = byte_utils::be64_to_array($htlc.value).to_vec(); + let mut htlc_msat_height_data = $htlc.value.to_be_bytes().to_vec(); htlc_msat_height_data.extend_from_slice( - &byte_utils::be32_to_array(self.best_block.read().unwrap().height()), + &self.best_block.read().unwrap().height().to_be_bytes(), ); failed_forwards.push((HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id: $htlc.prev_hop.short_channel_id, @@ -3909,9 +3909,8 @@ impl ChannelManager ChannelManager= htlc.cltv_expiry - HTLC_FAIL_BACK_BUFFER { - let mut htlc_msat_height_data = byte_utils::be64_to_array(htlc.value).to_vec(); - htlc_msat_height_data.extend_from_slice(&byte_utils::be32_to_array(height)); + let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec(); + htlc_msat_height_data.extend_from_slice(&height.to_be_bytes()); timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.prev_hop.clone()), payment_hash.clone(), HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data), diff --git a/lightning/src/ln/functional_tests.rs b/lightning/src/ln/functional_tests.rs index fdbe401f7..2010a691d 100644 --- a/lightning/src/ln/functional_tests.rs +++ b/lightning/src/ln/functional_tests.rs @@ -30,7 +30,7 @@ use crate::ln::features::{ChannelFeatures, NodeFeatures}; use crate::ln::msgs; use crate::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction}; use crate::util::enforcing_trait_impls::EnforcingSigner; -use crate::util::{byte_utils, test_utils}; +use crate::util::test_utils; use crate::util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose, ClosureReason, HTLCDestination}; use crate::util::errors::APIError; use crate::util::ser::{Writeable, ReadableArgs}; @@ -4100,8 +4100,8 @@ fn do_test_htlc_timeout(send_partial_mpp: bool) { nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]); commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false); // 100_000 msat as u64, followed by the height at which we failed back above - let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec(); - expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1)); + let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec(); + expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes()); expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]); } @@ -6974,8 +6974,8 @@ fn test_check_htlc_underpaying() { commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true); // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32 - let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec(); - expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH)); + let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec(); + expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes()); expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]); } diff --git a/lightning/src/ln/onion_route_tests.rs b/lightning/src/ln/onion_route_tests.rs index 2bf36ffba..b69f57403 100644 --- a/lightning/src/ln/onion_route_tests.rs +++ b/lightning/src/ln/onion_route_tests.rs @@ -25,7 +25,7 @@ use crate::ln::msgs::{ChannelMessageHandler, ChannelUpdate}; use crate::ln::wire::Encode; use crate::util::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider}; use crate::util::ser::{Writeable, Writer}; -use crate::util::{byte_utils, test_utils}; +use crate::util::test_utils; use crate::util::config::{UserConfig, ChannelConfig}; use crate::util::errors::APIError; @@ -1053,8 +1053,8 @@ fn test_phantom_final_incorrect_cltv_expiry() { commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false); // Ensure the payment fails with the expected error. - let expected_cltv = 82; - let error_data = byte_utils::be32_to_array(expected_cltv).to_vec(); + let expected_cltv: u32 = 82; + let error_data = expected_cltv.to_be_bytes().to_vec(); let mut fail_conditions = PaymentFailedConditions::new() .blamed_scid(phantom_scid) .expected_htlc_error_data(18, &error_data); @@ -1144,10 +1144,8 @@ fn test_phantom_failure_too_low_recv_amt() { commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false); // Ensure the payment fails with the expected error. - let mut error_data = byte_utils::be64_to_array(bad_recv_amt_msat).to_vec(); - error_data.extend_from_slice( - &byte_utils::be32_to_array(nodes[1].node.best_block.read().unwrap().height()), - ); + let mut error_data = bad_recv_amt_msat.to_be_bytes().to_vec(); + error_data.extend_from_slice(&nodes[1].node.best_block.read().unwrap().height().to_be_bytes()); let mut fail_conditions = PaymentFailedConditions::new() .blamed_scid(phantom_scid) .expected_htlc_error_data(0x4000 | 15, &error_data); @@ -1242,10 +1240,8 @@ fn test_phantom_failure_reject_payment() { commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false); // Ensure the payment fails with the expected error. - let mut error_data = byte_utils::be64_to_array(recv_amt_msat).to_vec(); - error_data.extend_from_slice( - &byte_utils::be32_to_array(nodes[1].node.best_block.read().unwrap().height()), - ); + let mut error_data = recv_amt_msat.to_be_bytes().to_vec(); + error_data.extend_from_slice(&nodes[1].node.best_block.read().unwrap().height().to_be_bytes()); let mut fail_conditions = PaymentFailedConditions::new() .blamed_scid(phantom_scid) .expected_htlc_error_data(0x4000 | 15, &error_data); diff --git a/lightning/src/util/byte_utils.rs b/lightning/src/util/byte_utils.rs index eac00241d..419a6b73a 100644 --- a/lightning/src/util/byte_utils.rs +++ b/lightning/src/util/byte_utils.rs @@ -17,34 +17,6 @@ pub fn slice_to_be48(v: &[u8]) -> u64 { ((v[5] as u64) << 8*0) } #[inline] -pub fn slice_to_be64(v: &[u8]) -> u64 { - ((v[0] as u64) << 8*7) | - ((v[1] as u64) << 8*6) | - ((v[2] as u64) << 8*5) | - ((v[3] as u64) << 8*4) | - ((v[4] as u64) << 8*3) | - ((v[5] as u64) << 8*2) | - ((v[6] as u64) << 8*1) | - ((v[7] as u64) << 8*0) -} - -#[inline] -pub fn be16_to_array(u: u16) -> [u8; 2] { - let mut v = [0; 2]; - v[0] = ((u >> 8*1) & 0xff) as u8; - v[1] = ((u >> 8*0) & 0xff) as u8; - v -} -#[inline] -pub fn be32_to_array(u: u32) -> [u8; 4] { - let mut v = [0; 4]; - v[0] = ((u >> 8*3) & 0xff) as u8; - v[1] = ((u >> 8*2) & 0xff) as u8; - v[2] = ((u >> 8*1) & 0xff) as u8; - v[3] = ((u >> 8*0) & 0xff) as u8; - v -} -#[inline] pub fn be48_to_array(u: u64) -> [u8; 6] { assert!(u & 0xffff_0000_0000_0000 == 0); let mut v = [0; 6]; @@ -56,19 +28,6 @@ pub fn be48_to_array(u: u64) -> [u8; 6] { v[5] = ((u >> 8*0) & 0xff) as u8; v } -#[inline] -pub fn be64_to_array(u: u64) -> [u8; 8] { - let mut v = [0; 8]; - v[0] = ((u >> 8*7) & 0xff) as u8; - v[1] = ((u >> 8*6) & 0xff) as u8; - v[2] = ((u >> 8*5) & 0xff) as u8; - v[3] = ((u >> 8*4) & 0xff) as u8; - v[4] = ((u >> 8*3) & 0xff) as u8; - v[5] = ((u >> 8*2) & 0xff) as u8; - v[6] = ((u >> 8*1) & 0xff) as u8; - v[7] = ((u >> 8*0) & 0xff) as u8; - v -} #[cfg(test)] mod tests { @@ -77,10 +36,6 @@ mod tests { #[test] fn test_all() { assert_eq!(slice_to_be48(&[0xde, 0xad, 0xbe, 0xef, 0x1b, 0xad]), 0xdeadbeef1bad); - assert_eq!(slice_to_be64(&[0xde, 0xad, 0xbe, 0xef, 0x1b, 0xad, 0x1d, 0xea]), 0xdeadbeef1bad1dea); - assert_eq!(be16_to_array(0xdead), [0xde, 0xad]); - assert_eq!(be32_to_array(0xdeadbeef), [0xde, 0xad, 0xbe, 0xef]); assert_eq!(be48_to_array(0xdeadbeef1bad), [0xde, 0xad, 0xbe, 0xef, 0x1b, 0xad]); - assert_eq!(be64_to_array(0xdeadbeef1bad1dea), [0xde, 0xad, 0xbe, 0xef, 0x1b, 0xad, 0x1d, 0xea]); } }