Skip to content

Commit 36f7427

Browse files
committed
Add assertions in the FeeRate constructor
Disallow negative, NaN, infinite or subnormal fee rate values.
1 parent 6bae52e commit 36f7427

1 file changed

Lines changed: 46 additions & 3 deletions

File tree

src/types.rs

Lines changed: 46 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -51,14 +51,28 @@ impl AsRef<[u8]> for KeychainKind {
5151
pub struct FeeRate(f32);
5252

5353
impl FeeRate {
54+
/// Create a new instance checking the value provided
55+
///
56+
/// Panics if the value is not [normal](https://doc.rust-lang.org/std/primitive.f32.html#method.is_normal) (except if it's a positive zero) or negative.
57+
fn new_checked(value: f32) -> Self {
58+
assert!(value.is_normal() || value == 0.0);
59+
assert!(value.is_sign_positive());
60+
61+
FeeRate(value)
62+
}
63+
5464
/// Create a new instance of [`FeeRate`] given a float fee rate in btc/kvbytes
65+
///
66+
/// Panics if the value is not [normal](https://doc.rust-lang.org/std/primitive.f32.html#method.is_normal) (except if it's a positive zero) or negative.
5567
pub fn from_btc_per_kvb(btc_per_kvb: f32) -> Self {
56-
FeeRate(btc_per_kvb * 1e5)
68+
FeeRate::new_checked(btc_per_kvb * 1e5)
5769
}
5870

5971
/// Create a new instance of [`FeeRate`] given a float fee rate in satoshi/vbyte
60-
pub const fn from_sat_per_vb(sat_per_vb: f32) -> Self {
61-
FeeRate(sat_per_vb)
72+
///
73+
/// Panics if the value is not [normal](https://doc.rust-lang.org/std/primitive.f32.html#method.is_normal) (except if it's a positive zero) or negative.
74+
pub fn from_sat_per_vb(sat_per_vb: f32) -> Self {
75+
FeeRate::new_checked(sat_per_vb)
6276
}
6377

6478
/// Create a new [`FeeRate`] with the default min relay fee value
@@ -251,4 +265,33 @@ mod tests {
251265
const _MY_RATE: FeeRate = FeeRate::from_sat_per_vb(10.0);
252266
const _MIN_RELAY: FeeRate = FeeRate::default_min_relay_fee();
253267
}
268+
269+
#[test]
270+
#[should_panic]
271+
fn test_invalid_feerate_neg_zero() {
272+
let _ = FeeRate::from_sat_per_vb(-0.0);
273+
}
274+
275+
#[test]
276+
#[should_panic]
277+
fn test_invalid_feerate_neg_value() {
278+
let _ = FeeRate::from_sat_per_vb(-5.0);
279+
}
280+
281+
#[test]
282+
#[should_panic]
283+
fn test_invalid_feerate_nan() {
284+
let _ = FeeRate::from_sat_per_vb(f32::NAN);
285+
}
286+
287+
#[test]
288+
#[should_panic]
289+
fn test_invalid_feerate_inf() {
290+
let _ = FeeRate::from_sat_per_vb(f32::INFINITY);
291+
}
292+
293+
#[test]
294+
fn test_invalid_feerate_pos_zero() {
295+
let _ = FeeRate::from_sat_per_vb(0.0);
296+
}
254297
}

0 commit comments

Comments
 (0)