Skip to content

Commit

Permalink
Remove unnecessary byte_utils helpers
Browse files Browse the repository at this point in the history
Now that to_be_bytes is available under our current MSRV of 1.41, we
can use it instead of our own version.
  • Loading branch information
wpaulino committed Dec 1, 2022
1 parent ce15992 commit 1141cbb
Show file tree
Hide file tree
Showing 7 changed files with 37 additions and 85 deletions.
26 changes: 13 additions & 13 deletions lightning/src/chain/channelmonitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ struct CounterpartyCommitmentParameters {

impl Writeable for CounterpartyCommitmentParameters {
fn write<W: Writer>(&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),
Expand Down Expand Up @@ -945,7 +945,7 @@ impl<Signer: Sign> Writeable for ChannelMonitorImpl<Signer> {
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)?;
Expand All @@ -972,24 +972,24 @@ impl<Signer: Sign> Writeable for ChannelMonitorImpl<Signer> {
},
}

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,
Expand All @@ -999,13 +999,13 @@ impl<Signer: Sign> Writeable for ChannelMonitorImpl<Signer> {
}
}

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))?;
Expand All @@ -1023,7 +1023,7 @@ impl<Signer: Sign> Writeable for ChannelMonitorImpl<Signer> {
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[..])?;
}
Expand All @@ -1044,15 +1044,15 @@ impl<Signer: Sign> Writeable for ChannelMonitorImpl<Signer> {
}
}

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)?;
}
Expand Down
9 changes: 5 additions & 4 deletions lightning/src/chain/keysinterface.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand All @@ -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};
Expand Down Expand Up @@ -973,8 +974,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 {
Expand Down Expand Up @@ -1006,7 +1007,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(&params[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);
Expand Down
11 changes: 5 additions & 6 deletions lightning/src/chain/onchaintx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::*;
Expand Down Expand Up @@ -272,29 +271,29 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
(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)?;
}
Expand Down
3 changes: 1 addition & 2 deletions lightning/src/chain/package.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand Down Expand Up @@ -774,7 +773,7 @@ impl PackageTemplate {

impl Writeable for PackageTemplate {
fn write<W: Writer>(&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)?;
Expand Down
4 changes: 2 additions & 2 deletions lightning/src/ln/chan_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -310,7 +310,7 @@ impl Writeable for CounterpartyCommitmentSecrets {
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))?;
writer.write_all(&idx.to_be_bytes())?;
}
write_tlv_fields!(writer, {});
Ok(())
Expand Down
24 changes: 11 additions & 13 deletions lightning/src/ln/channelmanager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -2041,7 +2041,7 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
return Err(ReceiveError {
msg: "Upstream node set CLTV to the wrong value",
err_code: 18,
err_data: byte_utils::be32_to_array(cltv_expiry).to_vec()
err_data: cltv_expiry.to_be_bytes().to_vec()
})
}
// final_expiry_too_soon
Expand All @@ -2060,7 +2060,7 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
if hop_data.amt_to_forward > 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",
});
}
Expand Down Expand Up @@ -3439,9 +3439,9 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F

macro_rules! fail_htlc {
($htlc: expr, $payment_hash: expr) => {
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,
Expand Down Expand Up @@ -3895,9 +3895,8 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
let removed_source = self.claimable_htlcs.lock().unwrap().remove(payment_hash);
if let Some((_, mut sources)) = removed_source {
for htlc in sources.drain(..) {
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(
self.best_block.read().unwrap().height()));
let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
htlc_msat_height_data.extend_from_slice(&self.best_block.read().unwrap().height().to_be_bytes());
self.fail_htlc_backwards_internal(
HTLCSource::PreviousHopData(htlc.prev_hop), payment_hash,
HTLCFailReason::Reason { failure_code: 0x4000 | 15, data: htlc_msat_height_data },
Expand Down Expand Up @@ -4291,9 +4290,8 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
mem::drop(channel_state_lock);
if !valid_mpp {
for htlc in sources.drain(..) {
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(
self.best_block.read().unwrap().height()));
let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
htlc_msat_height_data.extend_from_slice(&self.best_block.read().unwrap().height().to_be_bytes());
self.fail_htlc_backwards_internal(
HTLCSource::PreviousHopData(htlc.prev_hop), &payment_hash,
HTLCFailReason::Reason { failure_code: 0x4000|15, data: htlc_msat_height_data },
Expand Down Expand Up @@ -6267,8 +6265,8 @@ where
// number of blocks we generally consider it to take to do a commitment update,
// just give up on it and fail the HTLC.
if height >= 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 {
failure_code: 0x4000 | 15,
data: htlc_msat_height_data
Expand Down
45 changes: 0 additions & 45 deletions lightning/src/util/byte_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand All @@ -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 {
Expand All @@ -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]);
}
}

0 comments on commit 1141cbb

Please sign in to comment.