bitcoin_units/
weight.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
// SPDX-License-Identifier: CC0-1.0

//! Implements `Weight` and associated features.

use core::fmt;
use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign};

#[cfg(feature = "arbitrary")]
use arbitrary::{Arbitrary, Unstructured};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// The factor that non-witness serialization data is multiplied by during weight calculation.
pub const WITNESS_SCALE_FACTOR: usize = 4;

/// Represents block weight - the weight of a transaction or block.
///
/// This is an integer newtype representing [`Weight`] in `wu`. It provides protection against mixing
/// up the types as well as basic formatting features.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct Weight(u64);

impl Weight {
    /// 0 wu.
    ///
    /// Equivalent to [`MIN`](Self::MIN), may better express intent in some contexts.
    pub const ZERO: Weight = Weight(0);

    /// Minimum possible value (0 wu).
    ///
    /// Equivalent to [`ZERO`](Self::ZERO), may better express intent in some contexts.
    pub const MIN: Weight = Weight(u64::MIN);

    /// Maximum possible value.
    pub const MAX: Weight = Weight(u64::MAX);

    /// The factor that non-witness serialization data is multiplied by during weight calculation.
    pub const WITNESS_SCALE_FACTOR: u64 = WITNESS_SCALE_FACTOR as u64;

    /// The maximum allowed weight for a block, see BIP 141 (network rule).
    pub const MAX_BLOCK: Weight = Weight(4_000_000);

    /// The minimum transaction weight for a valid serialized transaction.
    pub const MIN_TRANSACTION: Weight = Weight(Self::WITNESS_SCALE_FACTOR * 60);

    /// Directly constructs [`Weight`] from weight units.
    pub const fn from_wu(wu: u64) -> Self { Weight(wu) }

    /// Directly constructs [`Weight`] from usize weight units.
    pub const fn from_wu_usize(wu: usize) -> Self { Weight(wu as u64) }

    /// Constructs [`Weight`] from kilo weight units returning [`None`] if an overflow occurred.
    pub fn from_kwu(wu: u64) -> Option<Self> { wu.checked_mul(1000).map(Weight) }

    /// Constructs [`Weight`] from virtual bytes, returning [`None`] if an overflow occurred.
    pub fn from_vb(vb: u64) -> Option<Self> {
        vb.checked_mul(Self::WITNESS_SCALE_FACTOR).map(Weight::from_wu)
    }

    /// Constructs [`Weight`] from virtual bytes panicking if an overflow occurred.
    ///
    /// # Panics
    ///
    /// If the conversion from virtual bytes overflows.
    pub const fn from_vb_unwrap(vb: u64) -> Weight {
        match vb.checked_mul(Self::WITNESS_SCALE_FACTOR) {
            Some(weight) => Weight(weight),
            None => panic!("checked_mul overflowed"),
        }
    }

    /// Constructs [`Weight`] from virtual bytes without an overflow check.
    pub const fn from_vb_unchecked(vb: u64) -> Self { Weight::from_wu(vb * 4) }

    /// Constructs [`Weight`] from witness size.
    pub const fn from_witness_data_size(witness_size: u64) -> Self { Weight(witness_size) }

    /// Constructs [`Weight`] from non-witness size.
    pub const fn from_non_witness_data_size(non_witness_size: u64) -> Self {
        Weight(non_witness_size * Self::WITNESS_SCALE_FACTOR)
    }

    /// Returns raw weight units.
    ///
    /// Can be used instead of `into()` to avoid inference issues.
    pub const fn to_wu(self) -> u64 { self.0 }

    /// Converts to kilo weight units rounding down.
    pub const fn to_kwu_floor(self) -> u64 { self.0 / 1000 }

    /// Converts to vB rounding down.
    pub const fn to_vbytes_floor(self) -> u64 { self.0 / Self::WITNESS_SCALE_FACTOR }

    /// Converts to vB rounding up.
    pub const fn to_vbytes_ceil(self) -> u64 {
        (self.0 + Self::WITNESS_SCALE_FACTOR - 1) / Self::WITNESS_SCALE_FACTOR
    }

    /// Checked addition.
    ///
    /// Computes `self + rhs` returning [`None`] if an overflow occurred.
    pub fn checked_add(self, rhs: Self) -> Option<Self> { self.0.checked_add(rhs.0).map(Self) }

    /// Checked subtraction.
    ///
    /// Computes `self - rhs` returning [`None`] if an overflow occurred.
    pub fn checked_sub(self, rhs: Self) -> Option<Self> { self.0.checked_sub(rhs.0).map(Self) }

    /// Checked multiplication.
    ///
    /// Computes `self * rhs` returning [`None`] if an overflow occurred.
    pub fn checked_mul(self, rhs: u64) -> Option<Self> { self.0.checked_mul(rhs).map(Self) }

    /// Checked division.
    ///
    /// Computes `self / rhs` returning [`None`] if `rhs == 0`.
    pub fn checked_div(self, rhs: u64) -> Option<Self> { self.0.checked_div(rhs).map(Self) }
}

/// Alternative will display the unit.
impl fmt::Display for Weight {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if f.alternate() {
            write!(f, "{} wu", self.0)
        } else {
            fmt::Display::fmt(&self.0, f)
        }
    }
}

impl From<Weight> for u64 {
    fn from(value: Weight) -> Self { value.to_wu() }
}

impl Add for Weight {
    type Output = Weight;

    fn add(self, rhs: Weight) -> Self::Output { Weight(self.0 + rhs.0) }
}

impl AddAssign for Weight {
    fn add_assign(&mut self, rhs: Self) { self.0 += rhs.0 }
}

impl Sub for Weight {
    type Output = Weight;

    fn sub(self, rhs: Weight) -> Self::Output { Weight(self.0 - rhs.0) }
}

impl SubAssign for Weight {
    fn sub_assign(&mut self, rhs: Self) { self.0 -= rhs.0 }
}

impl Mul<u64> for Weight {
    type Output = Weight;

    fn mul(self, rhs: u64) -> Self::Output { Weight(self.0 * rhs) }
}

impl Mul<Weight> for u64 {
    type Output = Weight;

    fn mul(self, rhs: Weight) -> Self::Output { Weight(self * rhs.0) }
}

impl MulAssign<u64> for Weight {
    fn mul_assign(&mut self, rhs: u64) { self.0 *= rhs }
}

impl Div<u64> for Weight {
    type Output = Weight;

    fn div(self, rhs: u64) -> Self::Output { Weight(self.0 / rhs) }
}

impl Div<Weight> for Weight {
    type Output = u64;

    fn div(self, rhs: Weight) -> Self::Output { self.to_wu() / rhs.to_wu() }
}

impl DivAssign<u64> for Weight {
    fn div_assign(&mut self, rhs: u64) { self.0 /= rhs }
}

impl core::iter::Sum for Weight {
    fn sum<I>(iter: I) -> Self
    where
        I: Iterator<Item = Self>,
    {
        Weight(iter.map(Weight::to_wu).sum())
    }
}

impl<'a> core::iter::Sum<&'a Weight> for Weight {
    fn sum<I>(iter: I) -> Self
    where
        I: Iterator<Item = &'a Weight>,
    {
        iter.cloned().sum()
    }
}

crate::impl_parse_str_from_int_infallible!(Weight, u64, from_wu);

#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for Weight {
    fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
        let w = u64::arbitrary(u)?;
        Ok(Weight(w))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn weight_constructor() {
        assert_eq!(Weight::ZERO, Weight::from_wu(0));
        assert_eq!(Weight::ZERO, Weight::from_wu_usize(0_usize));
    }

    #[test]
    fn kilo_weight_constructor() {
        assert_eq!(Weight(1_000), Weight::from_kwu(1).expect("expected weight unit"));
    }

    #[test]
    #[should_panic]
    fn kilo_weight_constructor_panic() {
        Weight::from_kwu(u64::MAX).expect("expected weight unit");
    }

    #[test]
    fn from_vb() {
        let w = Weight::from_vb(1).expect("expected weight unit");
        assert_eq!(Weight(4), w);

        let w = Weight::from_vb(u64::MAX);
        assert_eq!(None, w);
    }

    #[test]
    fn from_vb_const() {
        const WU: Weight = Weight::from_vb_unwrap(1);
        assert_eq!(Weight(4), WU);
    }

    #[test]
    fn from_vb_unchecked() {
        let w = Weight::from_vb_unchecked(1);
        assert_eq!(Weight(4), w);
    }

    #[test]
    #[cfg(debug_assertions)]
    #[should_panic]
    fn from_vb_unchecked_panic() { Weight::from_vb_unchecked(u64::MAX); }

    #[test]
    fn from_witness_data_size() {
        let witness_data_size = 1;
        assert_eq!(Weight(witness_data_size), Weight::from_witness_data_size(witness_data_size));
    }

    #[test]
    fn from_non_witness_data_size() {
        assert_eq!(Weight(4), Weight::from_non_witness_data_size(1));
    }

    #[test]
    fn to_kwu_floor() {
        assert_eq!(1, Weight(1_000).to_kwu_floor());
    }

    #[test]
    fn to_vb_floor() {
        assert_eq!(1, Weight(4).to_vbytes_floor());
        assert_eq!(1, Weight(5).to_vbytes_floor());
    }

    #[test]
    fn to_vb_ceil() {
        assert_eq!(1, Weight(4).to_vbytes_ceil());
        assert_eq!(2, Weight(5).to_vbytes_ceil());
    }

    #[test]
    fn checked_add() {
        let result = Weight(1).checked_add(Weight(1)).expect("expected weight unit");
        assert_eq!(Weight(2), result);

        let result = Weight::MAX.checked_add(Weight(1));
        assert_eq!(None, result);
    }

    #[test]
    fn checked_sub() {
        let result = Weight(1).checked_sub(Weight(1)).expect("expected weight unit");
        assert_eq!(Weight::ZERO, result);

        let result = Weight::MIN.checked_sub(Weight(1));
        assert_eq!(None, result);
    }

    #[test]
    fn checked_mul() {
        let result = Weight(2).checked_mul(2).expect("expected weight unit");
        assert_eq!(Weight(4), result);

        let result = Weight::MAX.checked_mul(2);
        assert_eq!(None, result);
    }

    #[test]
    fn checked_div() {
        let result = Weight(2).checked_div(2).expect("expected weight unit");
        assert_eq!(Weight(1), result);

        let result = Weight(2).checked_div(0);
        assert_eq!(None, result);
    }
}