Skip to content

Commit

Permalink
Merge pull request lightningdevkit#3324 from tnull/2024-09-rustfmt-ut…
Browse files Browse the repository at this point in the history
…il-1

`rustfmt`: Run on `util/*` (1/2)
  • Loading branch information
TheBlueMatt authored Oct 1, 2024
2 parents c7627df + d68a484 commit 4147de2
Show file tree
Hide file tree
Showing 12 changed files with 475 additions and 303 deletions.
18 changes: 11 additions & 7 deletions lightning/src/util/atomic_counter.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
//! A simple atomic counter that uses mutexes if the platform doesn't support atomic u64s.

#[cfg(target_has_atomic = "64")]
use core::sync::atomic::{AtomicU64, Ordering};
#[cfg(not(target_has_atomic = "64"))]
use crate::sync::Mutex;
#[cfg(target_has_atomic = "64")]
use core::sync::atomic::{AtomicU64, Ordering};

pub(crate) struct AtomicCounter {
#[cfg(target_has_atomic = "64")]
Expand All @@ -22,23 +22,27 @@ impl AtomicCounter {
}
}
pub(crate) fn next(&self) -> u64 {
#[cfg(target_has_atomic = "64")] {
#[cfg(target_has_atomic = "64")]
{
self.counter.fetch_add(1, Ordering::AcqRel)
}
#[cfg(not(target_has_atomic = "64"))] {
#[cfg(not(target_has_atomic = "64"))]
{
let mut mtx = self.counter.lock().unwrap();
*mtx += 1;
*mtx - 1
}
}
#[cfg(test)]
pub(crate) fn set_counter(&self, count: u64) {
#[cfg(target_has_atomic = "64")] {
#[cfg(target_has_atomic = "64")]
{
self.counter.store(count, Ordering::Release);
}
#[cfg(not(target_has_atomic = "64"))] {
#[cfg(not(target_has_atomic = "64"))]
{
let mut mtx = self.counter.lock().unwrap();
*mtx = count;
*mtx = count;
}
}
}
40 changes: 23 additions & 17 deletions lightning/src/util/base32.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,10 @@ pub enum Alphabet {
/// RFC4648 encoding.
RFC4648 {
/// Whether to use padding.
padding: bool
padding: bool,
},
/// Zbase32 encoding.
ZBase32
ZBase32,
}

impl Alphabet {
Expand All @@ -60,9 +60,7 @@ impl Alphabet {
}
ret
},
Self::ZBase32 => {
Self::encode_data(data, ZBASE_ALPHABET)
},
Self::ZBase32 => Self::encode_data(data, ZBASE_ALPHABET),
};
ret.truncate(output_length);

Expand All @@ -79,7 +77,9 @@ impl Alphabet {
Self::RFC4648 { padding } => {
let mut unpadded_data_length = data.len();
if *padding {
if data.len() % 8 != 0 { return Err(()); }
if data.len() % 8 != 0 {
return Err(());
}
data.iter().rev().take(6).for_each(|&c| {
if c == b'=' {
unpadded_data_length -= 1;
Expand All @@ -88,13 +88,14 @@ impl Alphabet {
}
(&data[..unpadded_data_length], RFC4648_INV_ALPHABET)
},
Self::ZBase32 => {
(data, ZBASE_INV_ALPHABET)
}
Self::ZBase32 => (data, ZBASE_INV_ALPHABET),
};
// If the string has more characters than are required to alphabet_encode the number of bytes
// decodable, treat the string as invalid.
match data.len() % 8 { 1|3|6 => return Err(()), _ => {} }
match data.len() % 8 {
1 | 3 | 6 => return Err(()),
_ => {},
}
Ok(Self::decode_data(data, alphabet)?)
}

Expand Down Expand Up @@ -175,9 +176,13 @@ mod tests {
("6n9hq", &[0xf0, 0xbf, 0xc7]),
("4t7ye", &[0xd4, 0x7a, 0x04]),
("6im5sdy", &[0xf5, 0x57, 0xbb, 0x0c]),
("ybndrfg8ejkmcpqxot1uwisza345h769", &[0x00, 0x44, 0x32, 0x14, 0xc7, 0x42, 0x54, 0xb6,
0x35, 0xcf, 0x84, 0x65, 0x3a, 0x56, 0xd7, 0xc6,
0x75, 0xbe, 0x77, 0xdf])
(
"ybndrfg8ejkmcpqxot1uwisza345h769",
&[
0x00, 0x44, 0x32, 0x14, 0xc7, 0x42, 0x54, 0xb6, 0x35, 0xcf, 0x84, 0x65, 0x3a, 0x56,
0xd7, 0xc6, 0x75, 0xbe, 0x77, 0xdf,
],
),
];

#[test]
Expand Down Expand Up @@ -242,7 +247,9 @@ mod tests {
}

for (input, encoded) in RFC4648_NON_PADDED_TEST_VECTORS {
let res = &Alphabet::RFC4648 { padding: false }.decode(std::str::from_utf8(encoded).unwrap()).unwrap();
let res = &Alphabet::RFC4648 { padding: false }
.decode(std::str::from_utf8(encoded).unwrap())
.unwrap();
assert_eq!(&res[..], &input[..]);
}
}
Expand All @@ -251,9 +258,8 @@ mod tests {
fn padding() {
let num_padding = [0, 6, 4, 3, 1];
for i in 1..6 {
let encoded = Alphabet::RFC4648 { padding: true }.encode(
(0..(i as u8)).collect::<Vec<u8>>().as_ref()
);
let encoded = Alphabet::RFC4648 { padding: true }
.encode((0..(i as u8)).collect::<Vec<u8>>().as_ref());
assert_eq!(encoded.len(), 8);
for j in 0..(num_padding[i % 5]) {
assert_eq!(encoded.as_bytes()[encoded.len() - j - 1], b'=');
Expand Down
24 changes: 12 additions & 12 deletions lightning/src/util/byte_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,23 +9,23 @@

#[inline]
pub fn slice_to_be48(v: &[u8]) -> u64 {
((v[0] as u64) << 8*5) |
((v[1] as u64) << 8*4) |
((v[2] as u64) << 8*3) |
((v[3] as u64) << 8*2) |
((v[4] as u64) << 8*1) |
((v[5] as u64) << 8*0)
((v[0] as u64) << 8 * 5)
| ((v[1] as u64) << 8 * 4)
| ((v[2] as u64) << 8 * 3)
| ((v[3] as u64) << 8 * 2)
| ((v[4] as u64) << 8 * 1)
| ((v[5] as u64) << 8 * 0)
}
#[inline]
pub fn be48_to_array(u: u64) -> [u8; 6] {
assert!(u & 0xffff_0000_0000_0000 == 0);
let mut v = [0; 6];
v[0] = ((u >> 8*5) & 0xff) as u8;
v[1] = ((u >> 8*4) & 0xff) as u8;
v[2] = ((u >> 8*3) & 0xff) as u8;
v[3] = ((u >> 8*2) & 0xff) as u8;
v[4] = ((u >> 8*1) & 0xff) as u8;
v[5] = ((u >> 8*0) & 0xff) as u8;
v[0] = ((u >> 8 * 5) & 0xff) as u8;
v[1] = ((u >> 8 * 4) & 0xff) as u8;
v[2] = ((u >> 8 * 3) & 0xff) as u8;
v[3] = ((u >> 8 * 2) & 0xff) as u8;
v[4] = ((u >> 8 * 1) & 0xff) as u8;
v[5] = ((u >> 8 * 0) & 0xff) as u8;
v
}

Expand Down
23 changes: 16 additions & 7 deletions lightning/src/util/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,7 @@ pub struct ChannelHandshakeLimits {
///
/// Default value: `2016`, which we also enforce as a maximum value so you can tweak config to
/// reduce the loss of having useless locked funds (if your peer accepts)
pub their_to_self_delay: u16
pub their_to_self_delay: u16,
}

impl Default for ChannelHandshakeLimits {
Expand Down Expand Up @@ -582,7 +582,9 @@ pub struct ChannelConfig {
impl ChannelConfig {
/// Applies the given [`ChannelConfigUpdate`] as a partial update to the [`ChannelConfig`].
pub fn apply(&mut self, update: &ChannelConfigUpdate) {
if let Some(forwarding_fee_proportional_millionths) = update.forwarding_fee_proportional_millionths {
if let Some(forwarding_fee_proportional_millionths) =
update.forwarding_fee_proportional_millionths
{
self.forwarding_fee_proportional_millionths = forwarding_fee_proportional_millionths;
}
if let Some(forwarding_fee_base_msat) = update.forwarding_fee_base_msat {
Expand All @@ -594,7 +596,9 @@ impl ChannelConfig {
if let Some(max_dust_htlc_exposure_msat) = update.max_dust_htlc_exposure_msat {
self.max_dust_htlc_exposure = max_dust_htlc_exposure_msat;
}
if let Some(force_close_avoidance_max_fee_satoshis) = update.force_close_avoidance_max_fee_satoshis {
if let Some(force_close_avoidance_max_fee_satoshis) =
update.force_close_avoidance_max_fee_satoshis
{
self.force_close_avoidance_max_fee_satoshis = force_close_avoidance_max_fee_satoshis;
}
}
Expand Down Expand Up @@ -683,11 +687,15 @@ pub struct ChannelConfigUpdate {
impl From<ChannelConfig> for ChannelConfigUpdate {
fn from(config: ChannelConfig) -> ChannelConfigUpdate {
ChannelConfigUpdate {
forwarding_fee_proportional_millionths: Some(config.forwarding_fee_proportional_millionths),
forwarding_fee_proportional_millionths: Some(
config.forwarding_fee_proportional_millionths,
),
forwarding_fee_base_msat: Some(config.forwarding_fee_base_msat),
cltv_expiry_delta: Some(config.cltv_expiry_delta),
max_dust_htlc_exposure_msat: Some(config.max_dust_htlc_exposure),
force_close_avoidance_max_fee_satoshis: Some(config.force_close_avoidance_max_fee_satoshis),
force_close_avoidance_max_fee_satoshis: Some(
config.force_close_avoidance_max_fee_satoshis,
),
}
}
}
Expand Down Expand Up @@ -760,8 +768,9 @@ impl crate::util::ser::Readable for LegacyChannelConfig {
});
let max_dust_htlc_exposure_msat_fixed_limit =
max_dust_htlc_exposure_msat_fixed_limit.unwrap_or(5_000_000);
let max_dust_htlc_exposure_msat = max_dust_htlc_exposure_enum
.unwrap_or(MaxDustHTLCExposure::FixedLimitMsat(max_dust_htlc_exposure_msat_fixed_limit));
let max_dust_htlc_exposure_msat = max_dust_htlc_exposure_enum.unwrap_or(
MaxDustHTLCExposure::FixedLimitMsat(max_dust_htlc_exposure_msat_fixed_limit),
);
Ok(Self {
options: ChannelConfig {
forwarding_fee_proportional_millionths,
Expand Down
28 changes: 16 additions & 12 deletions lightning/src/util/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ pub enum APIError {
/// are documented, but generally indicates some precondition of a function was violated.
APIMisuseError {
/// A human-readable error message
err: String
err: String,
},
/// Due to a high feerate, we were unable to complete the request.
/// For example, this may be returned if the feerate implies we cannot open a channel at the
Expand All @@ -33,20 +33,20 @@ pub enum APIError {
/// A human-readable error message
err: String,
/// The feerate which was too high.
feerate: u32
feerate: u32,
},
/// A malformed Route was provided (eg overflowed value, node id mismatch, overly-looped route,
/// too-many-hops, etc).
InvalidRoute {
/// A human-readable error message
err: String
err: String,
},
/// We were unable to complete the request as the Channel required to do so is unable to
/// complete the request (or was not found). This can take many forms, including disconnected
/// peer, channel at capacity, channel shutting down, etc.
ChannelUnavailable {
/// A human-readable error message
err: String
err: String,
},
/// An attempt to call [`chain::Watch::watch_channel`]/[`chain::Watch::update_channel`]
/// returned a [`ChannelMonitorUpdateStatus::InProgress`] indicating the persistence of a
Expand Down Expand Up @@ -74,11 +74,15 @@ pub enum APIError {
impl fmt::Debug for APIError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
APIError::APIMisuseError {ref err} => write!(f, "Misuse error: {}", err),
APIError::FeeRateTooHigh {ref err, ref feerate} => write!(f, "{} feerate: {}", err, feerate),
APIError::InvalidRoute {ref err} => write!(f, "Invalid route provided: {}", err),
APIError::ChannelUnavailable {ref err} => write!(f, "Channel unavailable: {}", err),
APIError::MonitorUpdateInProgress => f.write_str("Client indicated a channel monitor update is in progress but not yet complete"),
APIError::APIMisuseError { ref err } => write!(f, "Misuse error: {}", err),
APIError::FeeRateTooHigh { ref err, ref feerate } => {
write!(f, "{} feerate: {}", err, feerate)
},
APIError::InvalidRoute { ref err } => write!(f, "Invalid route provided: {}", err),
APIError::ChannelUnavailable { ref err } => write!(f, "Channel unavailable: {}", err),
APIError::MonitorUpdateInProgress => f.write_str(
"Client indicated a channel monitor update is in progress but not yet complete",
),
APIError::IncompatibleShutdownScript { ref script } => {
write!(f, "Provided a scriptpubkey format not accepted by peer: {}", script)
},
Expand All @@ -101,9 +105,9 @@ impl_writeable_tlv_based_enum_upgradable!(APIError,
#[inline]
pub(crate) fn get_onion_debug_field(error_code: u16) -> (&'static str, usize) {
match error_code & 0xff {
4|5|6 => ("sha256_of_onion", 32),
11|12 => ("htlc_msat", 8),
13|18 => ("cltv_expiry", 4),
4 | 5 | 6 => ("sha256_of_onion", 32),
11 | 12 => ("htlc_msat", 8),
13 | 18 => ("cltv_expiry", 4),
19 => ("incoming_htlc_msat", 8),
20 => ("flags", 2),
_ => ("", 0),
Expand Down
22 changes: 10 additions & 12 deletions lightning/src/util/fuzz_wrappers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,17 @@
// licenses.

macro_rules! hash_to_message {
($slice: expr) => {
($slice: expr) => {{
#[cfg(not(fuzzing))]
{
#[cfg(not(fuzzing))]
{
::bitcoin::secp256k1::Message::from_digest_slice($slice).unwrap()
}
#[cfg(fuzzing)]
{
match ::bitcoin::secp256k1::Message::from_digest_slice($slice) {
Ok(msg) => msg,
Err(_) => ::bitcoin::secp256k1::Message::from_digest([1; 32])
}
::bitcoin::secp256k1::Message::from_digest_slice($slice).unwrap()
}
#[cfg(fuzzing)]
{
match ::bitcoin::secp256k1::Message::from_digest_slice($slice) {
Ok(msg) => msg,
Err(_) => ::bitcoin::secp256k1::Message::from_digest([1; 32]),
}
}
}
}};
}
Loading

0 comments on commit 4147de2

Please sign in to comment.