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 7fffd59 commit 840cf90
Show file tree
Hide file tree
Showing 9 changed files with 49 additions and 101 deletions.
26 changes: 13 additions & 13 deletions lightning/src/chain/channelmonitor.rs
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
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
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
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
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
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 @@ -2053,7 +2053,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 @@ -2072,7 +2072,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 @@ -3451,9 +3451,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 @@ -3909,9 +3909,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());
let source = HTLCSource::PreviousHopData(htlc.prev_hop);
let reason = HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data);
let receiver = HTLCDestination::FailedPayment { payment_hash: *payment_hash };
Expand Down Expand Up @@ -4306,9 +4305,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());
let source = HTLCSource::PreviousHopData(htlc.prev_hop);
let reason = HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data);
let receiver = HTLCDestination::FailedPayment { payment_hash };
Expand Down Expand Up @@ -6283,8 +6281,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(0x4000 | 15, htlc_msat_height_data),
Expand Down
10 changes: 5 additions & 5 deletions lightning/src/ln/functional_tests.rs
Expand Up @@ -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};
Expand Down Expand Up @@ -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[..]);
}

Expand Down Expand Up @@ -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[..]);
}

Expand Down
18 changes: 7 additions & 11 deletions lightning/src/ln/onion_route_tests.rs
Expand Up @@ -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;

Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Expand Down

0 comments on commit 840cf90

Please sign in to comment.