bitcoin_internals/
script.rs

1// SPDX-License-Identifier: CC0-1.0
2
3//! Internal script related helper functions and types.
4
5/// Reads a `usize` from an iterator.
6///
7/// A script push data instruction includes the length of the data being pushed, this function reads
8/// that length from an iterator (encoded in either 1, 2, or 4 bytes).
9// We internally use implementation based on iterator so that it automatically advances as needed.
10pub fn read_push_data_len(
11    data: &mut core::slice::Iter<'_, u8>,
12    size: PushDataLenLen,
13) -> Result<usize, EarlyEndOfScriptError> {
14    // The `size` enum enforces that the maximum shift will be 32 and
15    // that we can only ever read up to 4 bytes.
16    let size = size as usize;
17
18    if data.len() < size {
19        return Err(EarlyEndOfScriptError);
20    };
21
22    let mut ret = 0;
23    for (i, item) in data.take(size).enumerate() {
24        ret |= usize::from(*item) << (i * 8);
25    }
26    Ok(ret)
27}
28
29/// The number of bytes used to encode an unsigned integer as the length of a push data instruction.
30///
31/// This makes it easier to prove correctness of `next_push_data_len` and `read_push_data_len`.
32#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)]
33pub enum PushDataLenLen {
34    /// Unsigned integer comprising of a single byte.
35    One = 1,
36    /// Unsigned integer comprising of two bytes.
37    Two = 2,
38    /// Unsigned integer comprising of four bytes.
39    Four = 4,
40}
41
42/// Indicates that we tried to read more bytes from the script than available.
43#[derive(Debug)]
44pub struct EarlyEndOfScriptError;
45
46#[cfg(test)]
47mod tests {
48    use super::*;
49
50    #[test]
51    fn reads_4_bytes() {
52        let bytes = [0x01, 0x23, 0x45, 0x67];
53        let want = u32::from_le_bytes([0x01, 0x23, 0x45, 0x67]);
54        let got = read_push_data_len(&mut bytes.iter(), PushDataLenLen::Four).unwrap();
55        assert_eq!(got, want as usize)
56    }
57
58    #[test]
59    fn reads_2_bytes() {
60        let bytes = [0x01, 0x23];
61        let want = u16::from_le_bytes([0x01, 0x23]);
62        let got = read_push_data_len(&mut bytes.iter(), PushDataLenLen::Two).unwrap();
63        assert_eq!(got, want as usize)
64    }
65
66    #[test]
67    fn reads_1_byte() {
68        let bytes = [0x01];
69        let want = 0x01;
70        let got = read_push_data_len(&mut bytes.iter(), PushDataLenLen::One).unwrap();
71        assert_eq!(got, want as usize)
72    }
73}