bc/
coding.rs

1// Bitcoin protocol consensus library.
2//
3// SPDX-License-Identifier: Apache-2.0
4//
5// Written in 2019-2024 by
6//     Dr Maxim Orlovsky <orlovsky@lnp-bp.org>
7//
8// Copyright (C) 2019-2024 LNP/BP Standards Association. All rights reserved.
9//
10// Licensed under the Apache License, Version 2.0 (the "License");
11// you may not use this file except in compliance with the License.
12// You may obtain a copy of the License at
13//
14//     http://www.apache.org/licenses/LICENSE-2.0
15//
16// Unless required by applicable law or agreed to in writing, software
17// distributed under the License is distributed on an "AS IS" BASIS,
18// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19// See the License for the specific language governing permissions and
20// limitations under the License.
21
22use std::io::{self, Cursor, Read, Write};
23
24use amplify::confinement::{Confined, MediumBlob, SmallBlob, TinyBlob, U32};
25use amplify::{confinement, ByteArray, Bytes32, IoError, Wrapper};
26
27use crate::{
28    Annex, BlockHash, BlockHeader, BlockMerkleRoot, ControlBlock, InternalPk, InvalidLeafVer,
29    LeafVer, LockTime, Outpoint, Parity, RedeemScript, Sats, ScriptBytes, ScriptPubkey, SeqNo,
30    SigScript, Sighash, TapBranchHash, TapLeafHash, TapMerklePath, TapScript, Tx, TxIn, TxOut,
31    TxVer, Txid, Vout, Witness, WitnessScript, LIB_NAME_BITCOIN, TAPROOT_ANNEX_PREFIX,
32};
33
34/// Bitcoin consensus allows arrays which length is encoded as VarInt to grow up
35/// to 64-bit values. However, at the same time no consensus rule allows any
36/// block data structure to exceed 2^32 bytes (4GB), and any change to that rule
37/// will be a hardfork. So for practical reasons we are safe to restrict the
38/// maximum size here with just 32 bits.
39pub type VarIntArray<T, const MIN_LEN: usize = 0> = Confined<Vec<T>, MIN_LEN, U32>;
40
41pub type VarIntBytes<const MIN_LEN: usize = 0> = Confined<Vec<u8>, MIN_LEN, U32>;
42
43/// A variable-length unsigned integer.
44#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Default)]
45#[derive(StrictType, StrictEncode, StrictDecode)]
46#[strict_type(lib = LIB_NAME_BITCOIN)]
47pub struct VarInt(pub u64);
48
49#[allow(clippy::len_without_is_empty)] // VarInt has no concept of 'is_empty'.
50impl VarInt {
51    pub const fn new(u: u64) -> Self { VarInt(u) }
52
53    pub fn with(u: impl Into<usize>) -> Self { VarInt(u.into() as u64) }
54
55    /// Gets the length of this VarInt when encoded.
56    ///
57    /// Returns 1 for 0..=0xFC, 3 for 0xFD..=(2^16-1), 5 for 0x10000..=(2^32-1),
58    /// and 9 otherwise.
59    #[inline]
60    pub const fn len(&self) -> usize {
61        match self.0 {
62            0..=0xFC => 1,
63            0xFD..=0xFFFF => 3,
64            0x10000..=0xFFFFFFFF => 5,
65            _ => 9,
66        }
67    }
68
69    pub const fn to_u64(&self) -> u64 { self.0 }
70    pub const fn into_u64(self) -> u64 { self.0 }
71    pub fn to_usize(&self) -> usize {
72        usize::try_from(self.0).expect("transaction too large for a non-64 bit platform")
73    }
74    pub fn into_usize(self) -> usize { self.to_usize() }
75}
76
77impl<U: Into<u64> + Copy> PartialEq<U> for VarInt {
78    fn eq(&self, other: &U) -> bool { self.0.eq(&(*other).into()) }
79}
80
81pub trait LenVarInt {
82    fn len_var_int(&self) -> VarInt;
83}
84
85impl<T, const MIN_LEN: usize> LenVarInt for VarIntArray<T, MIN_LEN> {
86    fn len_var_int(&self) -> VarInt { VarInt::with(self.len()) }
87}
88
89#[derive(Wrapper, WrapperMut, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Default, Debug, From)]
90#[derive(StrictType, StrictEncode, StrictDecode)]
91#[strict_type(lib = LIB_NAME_BITCOIN)]
92#[wrapper(Deref, Index, RangeOps, BorrowSlice, Hex)]
93#[wrapper_mut(DerefMut, IndexMut, RangeMut, BorrowSliceMut)]
94pub struct ByteStr(VarIntBytes);
95
96impl AsRef<[u8]> for ByteStr {
97    fn as_ref(&self) -> &[u8] { self.0.as_slice() }
98}
99
100impl From<Vec<u8>> for ByteStr {
101    fn from(value: Vec<u8>) -> Self {
102        Self(Confined::try_from(value).expect("byte string size exceeds 4GB"))
103    }
104}
105
106impl From<TinyBlob> for ByteStr {
107    fn from(vec: TinyBlob) -> Self { ByteStr(Confined::from_checked(vec.release())) }
108}
109
110impl From<SmallBlob> for ByteStr {
111    fn from(vec: SmallBlob) -> Self { ByteStr(Confined::from_checked(vec.release())) }
112}
113
114impl From<MediumBlob> for ByteStr {
115    fn from(vec: MediumBlob) -> Self { ByteStr(Confined::from_checked(vec.release())) }
116}
117
118impl ByteStr {
119    pub fn len_var_int(&self) -> VarInt { VarInt(self.len() as u64) }
120
121    pub fn into_vec(self) -> Vec<u8> { self.0.release() }
122}
123
124#[cfg(feature = "serde")]
125mod _serde {
126    use amplify::hex::{FromHex, ToHex};
127    use serde_crate::de::Error;
128    use serde_crate::{Deserialize, Deserializer, Serialize, Serializer};
129
130    use super::*;
131
132    impl Serialize for ByteStr {
133        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
134        where S: Serializer {
135            if serializer.is_human_readable() {
136                serializer.serialize_str(&self.to_hex())
137            } else {
138                serializer.serialize_bytes(self.as_slice())
139            }
140        }
141    }
142
143    impl<'de> Deserialize<'de> for ByteStr {
144        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
145        where D: Deserializer<'de> {
146            if deserializer.is_human_readable() {
147                String::deserialize(deserializer).and_then(|string| {
148                    Self::from_hex(&string).map_err(|_| D::Error::custom("wrong hex data"))
149                })
150            } else {
151                let bytes = Vec::<u8>::deserialize(deserializer)?;
152                Ok(Self::from(bytes))
153            }
154        }
155    }
156}
157
158#[derive(Clone, PartialEq, Eq, Debug, Display, Error, From)]
159#[display(inner)]
160pub enum ConsensusDecodeError {
161    #[from]
162    #[from(io::Error)]
163    Io(IoError),
164
165    #[display(inner)]
166    #[from]
167    #[from(InvalidLeafVer)]
168    #[from(confinement::Error)]
169    Data(ConsensusDataError),
170}
171
172#[derive(Copy, Clone, PartialEq, Eq, Debug, Display, Error, From)]
173#[display(doc_comments)]
174pub enum ConsensusDataError {
175    /// consensus data are followed by some excessive bytes.
176    DataNotConsumed,
177
178    /// not a minimally-encoded variable integer.
179    NonMinimalVarInt,
180
181    /// invalid BIP340 (x-only) pubkey data.
182    InvalidXonlyPubkey(Bytes32),
183
184    /// taproot Merkle path length exceeds BIP-341 consensus limit of 128
185    /// elements.
186    LongTapMerklePath,
187
188    /// Merkle path in the `PSBT_IN_TAP_TREE` is not encoded correctly.
189    InvalidTapMerklePath,
190
191    #[from]
192    #[display(inner)]
193    InvalidLeafVer(InvalidLeafVer),
194
195    /// invalid first annex byte `{0:#02x}`, which must be `0x50`.
196    WrongAnnexFirstByte(u8),
197
198    #[from]
199    #[display(inner)]
200    Confined(confinement::Error),
201
202    /// unsupported Segwit flag {0}.
203    UnsupportedSegwitFlag(u8),
204}
205
206pub trait ConsensusEncode {
207    fn consensus_encode(&self, writer: &mut impl Write) -> Result<usize, IoError>;
208    fn consensus_serialize(&self) -> Vec<u8> {
209        let mut buf = Vec::new();
210        self.consensus_encode(&mut buf).expect("in-memory writing can't fail");
211        buf
212    }
213}
214
215pub trait ConsensusDecode
216where Self: Sized
217{
218    fn consensus_decode(reader: &mut impl Read) -> Result<Self, ConsensusDecodeError>;
219    fn consensus_deserialize(bytes: impl AsRef<[u8]>) -> Result<Self, ConsensusDecodeError> {
220        let mut cursor = Cursor::new(bytes.as_ref());
221        let me = Self::consensus_decode(&mut cursor)?;
222        if cursor.position() as usize != bytes.as_ref().len() {
223            return Err(ConsensusDataError::DataNotConsumed.into());
224        }
225        Ok(me)
226    }
227}
228
229impl ConsensusEncode for BlockHeader {
230    fn consensus_encode(&self, writer: &mut impl Write) -> Result<usize, IoError> {
231        let mut counter = self.version.consensus_encode(writer)?;
232        counter += self.prev_block_hash.consensus_encode(writer)?;
233        counter += self.merkle_root.consensus_encode(writer)?;
234        counter += self.time.consensus_encode(writer)?;
235        counter += self.bits.consensus_encode(writer)?;
236        counter += self.nonce.consensus_encode(writer)?;
237        Ok(counter)
238    }
239}
240
241impl ConsensusDecode for BlockHeader {
242    fn consensus_decode(reader: &mut impl Read) -> Result<Self, ConsensusDecodeError> {
243        let version = i32::consensus_decode(reader)?;
244        let prev_block_hash = BlockHash::consensus_decode(reader)?;
245        let merkle_root = BlockMerkleRoot::consensus_decode(reader)?;
246        let time = u32::consensus_decode(reader)?;
247        let bits = u32::consensus_decode(reader)?;
248        let nonce = u32::consensus_decode(reader)?;
249        Ok(BlockHeader {
250            version,
251            prev_block_hash,
252            merkle_root,
253            time,
254            bits,
255            nonce,
256        })
257    }
258}
259
260impl ConsensusEncode for BlockHash {
261    fn consensus_encode(&self, writer: &mut impl Write) -> Result<usize, IoError> {
262        writer.write_all(&self.to_byte_array())?;
263        Ok(32)
264    }
265}
266
267impl ConsensusDecode for BlockHash {
268    fn consensus_decode(reader: &mut impl Read) -> Result<Self, ConsensusDecodeError> {
269        <[u8; 32]>::consensus_decode(reader).map(Self::from)
270    }
271}
272
273impl ConsensusEncode for BlockMerkleRoot {
274    fn consensus_encode(&self, writer: &mut impl Write) -> Result<usize, IoError> {
275        writer.write_all(&self.to_byte_array())?;
276        Ok(32)
277    }
278}
279
280impl ConsensusDecode for BlockMerkleRoot {
281    fn consensus_decode(reader: &mut impl Read) -> Result<Self, ConsensusDecodeError> {
282        <[u8; 32]>::consensus_decode(reader).map(Self::from)
283    }
284}
285
286impl ConsensusEncode for Tx {
287    fn consensus_encode(&self, writer: &mut impl Write) -> Result<usize, IoError> {
288        let mut counter = self.version.consensus_encode(writer)?;
289        if self.is_segwit() && !self.inputs.is_empty() {
290            0x00_u8.consensus_encode(writer)?;
291            0x01_u8.consensus_encode(writer)?;
292            counter += 2;
293        }
294        counter += self.inputs.consensus_encode(writer)?;
295        counter += self.outputs.consensus_encode(writer)?;
296        if self.is_segwit() {
297            for input in self.inputs() {
298                counter += input.witness.consensus_encode(writer)?;
299            }
300        }
301        counter += self.lock_time.consensus_encode(writer)?;
302        Ok(counter)
303    }
304}
305
306impl ConsensusDecode for Tx {
307    fn consensus_decode(reader: &mut impl Read) -> Result<Self, ConsensusDecodeError> {
308        let version = TxVer::consensus_decode(reader)?;
309        let prefix = VarInt::consensus_decode(reader)?;
310
311        let segwit = prefix == 0u8;
312        let mut inputs = if segwit {
313            // SegWit
314            let flag = u8::consensus_decode(reader)?;
315            if flag != 0x01 {
316                Err(ConsensusDataError::UnsupportedSegwitFlag(flag))?
317            }
318            VarIntArray::<TxIn>::consensus_decode(reader)?
319        } else {
320            // our prefix is the number of inputs
321            let mut inputs = Vec::with_capacity(prefix.to_usize());
322            for _ in 0..prefix.to_u64() {
323                inputs.push(TxIn::consensus_decode(reader)?);
324            }
325            VarIntArray::try_from(inputs)?
326        };
327
328        let outputs = VarIntArray::consensus_decode(reader)?;
329        if segwit {
330            for input in &mut inputs {
331                input.witness = Witness::consensus_decode(reader)?;
332            }
333        }
334        let lock_time = LockTime::consensus_decode(reader)?;
335
336        Ok(Tx {
337            version,
338            inputs,
339            outputs,
340            lock_time,
341        })
342    }
343}
344
345impl ConsensusEncode for TxVer {
346    fn consensus_encode(&self, writer: &mut impl Write) -> Result<usize, IoError> {
347        self.to_consensus_i32().consensus_encode(writer)
348    }
349}
350
351impl ConsensusDecode for TxVer {
352    fn consensus_decode(reader: &mut impl Read) -> Result<Self, ConsensusDecodeError> {
353        i32::consensus_decode(reader).map(Self::from_consensus_i32)
354    }
355}
356
357impl ConsensusEncode for TxIn {
358    fn consensus_encode(&self, writer: &mut impl Write) -> Result<usize, IoError> {
359        let mut counter = self.prev_output.consensus_encode(writer)?;
360        counter += self.sig_script.consensus_encode(writer)?;
361        counter += self.sequence.consensus_encode(writer)?;
362        Ok(counter)
363    }
364}
365
366impl ConsensusDecode for TxIn {
367    fn consensus_decode(reader: &mut impl Read) -> Result<Self, ConsensusDecodeError> {
368        let prev_output = Outpoint::consensus_decode(reader)?;
369        let sig_script = SigScript::consensus_decode(reader)?;
370        let sequence = SeqNo::consensus_decode(reader)?;
371        Ok(TxIn {
372            prev_output,
373            sig_script,
374            sequence,
375            witness: none!(),
376        })
377    }
378}
379
380impl ConsensusEncode for TxOut {
381    fn consensus_encode(&self, writer: &mut impl Write) -> Result<usize, IoError> {
382        let mut counter = self.value.consensus_encode(writer)?;
383        counter += self.script_pubkey.consensus_encode(writer)?;
384        Ok(counter)
385    }
386}
387
388impl ConsensusDecode for TxOut {
389    fn consensus_decode(reader: &mut impl Read) -> Result<Self, ConsensusDecodeError> {
390        let value = Sats::consensus_decode(reader)?;
391        let script_pubkey = ScriptPubkey::consensus_decode(reader)?;
392        Ok(TxOut {
393            value,
394            script_pubkey,
395        })
396    }
397}
398
399impl ConsensusEncode for Outpoint {
400    fn consensus_encode(&self, writer: &mut impl Write) -> Result<usize, IoError> {
401        let mut counter = self.txid.consensus_encode(writer)?;
402        counter += self.vout.consensus_encode(writer)?;
403        Ok(counter)
404    }
405}
406
407impl ConsensusDecode for Outpoint {
408    fn consensus_decode(reader: &mut impl Read) -> Result<Self, ConsensusDecodeError> {
409        let txid = Txid::consensus_decode(reader)?;
410        let vout = Vout::consensus_decode(reader)?;
411        Ok(Outpoint { txid, vout })
412    }
413}
414
415impl ConsensusEncode for Txid {
416    fn consensus_encode(&self, writer: &mut impl Write) -> Result<usize, IoError> {
417        writer.write_all(&self.to_byte_array())?;
418        Ok(32)
419    }
420}
421
422impl ConsensusDecode for Txid {
423    fn consensus_decode(reader: &mut impl Read) -> Result<Self, ConsensusDecodeError> {
424        <[u8; 32]>::consensus_decode(reader).map(Self::from)
425    }
426}
427
428impl ConsensusEncode for Vout {
429    fn consensus_encode(&self, writer: &mut impl Write) -> Result<usize, IoError> {
430        self.into_u32().consensus_encode(writer)
431    }
432}
433
434impl ConsensusDecode for Vout {
435    fn consensus_decode(reader: &mut impl Read) -> Result<Self, ConsensusDecodeError> {
436        u32::consensus_decode(reader).map(Self::from)
437    }
438}
439
440impl ConsensusEncode for SeqNo {
441    fn consensus_encode(&self, writer: &mut impl Write) -> Result<usize, IoError> {
442        self.to_consensus_u32().consensus_encode(writer)
443    }
444}
445
446impl ConsensusDecode for SeqNo {
447    fn consensus_decode(reader: &mut impl Read) -> Result<Self, ConsensusDecodeError> {
448        u32::consensus_decode(reader).map(Self::from_consensus_u32)
449    }
450}
451
452impl ConsensusEncode for LockTime {
453    fn consensus_encode(&self, writer: &mut impl Write) -> Result<usize, IoError> {
454        self.to_consensus_u32().consensus_encode(writer)
455    }
456}
457
458impl ConsensusDecode for LockTime {
459    fn consensus_decode(reader: &mut impl Read) -> Result<Self, ConsensusDecodeError> {
460        u32::consensus_decode(reader).map(Self::from_consensus_u32)
461    }
462}
463
464impl ConsensusEncode for ScriptBytes {
465    fn consensus_encode(&self, writer: &mut impl Write) -> Result<usize, IoError> {
466        self.as_var_int_bytes().consensus_encode(writer)
467    }
468}
469
470impl ConsensusDecode for ScriptBytes {
471    fn consensus_decode(reader: &mut impl Read) -> Result<Self, ConsensusDecodeError> {
472        VarIntArray::consensus_decode(reader).map(Self::from_inner)
473    }
474}
475
476impl ConsensusEncode for ScriptPubkey {
477    fn consensus_encode(&self, writer: &mut impl Write) -> Result<usize, IoError> {
478        self.as_script_bytes().consensus_encode(writer)
479    }
480}
481
482impl ConsensusDecode for ScriptPubkey {
483    fn consensus_decode(reader: &mut impl Read) -> Result<Self, ConsensusDecodeError> {
484        ScriptBytes::consensus_decode(reader).map(Self::from_inner)
485    }
486}
487
488impl ConsensusEncode for WitnessScript {
489    fn consensus_encode(&self, writer: &mut impl Write) -> Result<usize, IoError> {
490        self.as_script_bytes().consensus_encode(writer)
491    }
492}
493
494impl ConsensusDecode for WitnessScript {
495    fn consensus_decode(reader: &mut impl Read) -> Result<Self, ConsensusDecodeError> {
496        ScriptBytes::consensus_decode(reader).map(Self::from_inner)
497    }
498}
499
500impl ConsensusEncode for RedeemScript {
501    fn consensus_encode(&self, writer: &mut impl Write) -> Result<usize, IoError> {
502        self.as_script_bytes().consensus_encode(writer)
503    }
504}
505
506impl ConsensusDecode for RedeemScript {
507    fn consensus_decode(reader: &mut impl Read) -> Result<Self, ConsensusDecodeError> {
508        ScriptBytes::consensus_decode(reader).map(Self::from_inner)
509    }
510}
511
512impl ConsensusEncode for TapScript {
513    fn consensus_encode(&self, writer: &mut impl Write) -> Result<usize, IoError> {
514        self.as_script_bytes().consensus_encode(writer)
515    }
516}
517
518impl ConsensusDecode for TapScript {
519    fn consensus_decode(reader: &mut impl Read) -> Result<Self, ConsensusDecodeError> {
520        ScriptBytes::consensus_decode(reader).map(Self::from_inner)
521    }
522}
523
524impl ConsensusEncode for SigScript {
525    fn consensus_encode(&self, writer: &mut impl Write) -> Result<usize, IoError> {
526        self.as_script_bytes().consensus_encode(writer)
527    }
528}
529
530impl ConsensusDecode for SigScript {
531    fn consensus_decode(reader: &mut impl Read) -> Result<Self, ConsensusDecodeError> {
532        ScriptBytes::consensus_decode(reader).map(Self::from_inner)
533    }
534}
535
536impl ConsensusEncode for Annex {
537    fn consensus_encode(&self, writer: &mut impl Write) -> Result<usize, IoError> {
538        self.as_var_int_bytes().consensus_encode(writer)
539    }
540}
541
542impl ConsensusDecode for Annex {
543    fn consensus_decode(reader: &mut impl Read) -> Result<Self, ConsensusDecodeError> {
544        let bytes = VarIntBytes::<1>::consensus_decode(reader)?;
545        if bytes[0] != TAPROOT_ANNEX_PREFIX {
546            return Err(ConsensusDataError::WrongAnnexFirstByte(bytes[0]).into());
547        }
548        Ok(Self::from(bytes))
549    }
550}
551
552impl ConsensusEncode for Witness {
553    fn consensus_encode(&self, writer: &mut impl Write) -> Result<usize, IoError> {
554        self.as_var_int_array().consensus_encode(writer)
555    }
556}
557
558impl ConsensusDecode for Witness {
559    fn consensus_decode(reader: &mut impl Read) -> Result<Self, ConsensusDecodeError> {
560        VarIntArray::consensus_decode(reader).map(Self::from_inner)
561    }
562}
563
564impl ConsensusEncode for InternalPk {
565    fn consensus_encode(&self, writer: &mut impl Write) -> Result<usize, IoError> {
566        writer.write_all(&self.to_byte_array())?;
567        Ok(32)
568    }
569}
570
571impl ConsensusEncode for TapBranchHash {
572    fn consensus_encode(&self, writer: &mut impl Write) -> Result<usize, IoError> {
573        writer.write_all(&self.to_byte_array())?;
574        Ok(32)
575    }
576}
577
578impl ConsensusDecode for TapBranchHash {
579    fn consensus_decode(reader: &mut impl Read) -> Result<Self, ConsensusDecodeError> {
580        let mut buf = [0u8; 32];
581        reader.read_exact(&mut buf)?;
582        Ok(TapBranchHash::from_byte_array(buf))
583    }
584}
585
586impl ConsensusDecode for InternalPk {
587    fn consensus_decode(reader: &mut impl Read) -> Result<Self, ConsensusDecodeError> {
588        let mut buf = [0u8; 32];
589        reader.read_exact(&mut buf)?;
590        InternalPk::from_byte_array(buf)
591            .map_err(|_| ConsensusDataError::InvalidXonlyPubkey(buf.into()).into())
592    }
593}
594
595impl ConsensusEncode for ControlBlock {
596    fn consensus_encode(&self, writer: &mut impl Write) -> Result<usize, IoError> {
597        let mut counter = 1;
598
599        let first_byte =
600            self.leaf_version.to_consensus_u8() & self.output_key_parity.to_consensus_u8();
601        first_byte.consensus_encode(writer)?;
602
603        counter += self.internal_pk.consensus_encode(writer)?;
604        for step in &self.merkle_branch {
605            counter += step.consensus_encode(writer)?;
606        }
607
608        Ok(counter)
609    }
610}
611
612impl ConsensusDecode for ControlBlock {
613    fn consensus_decode(reader: &mut impl Read) -> Result<Self, ConsensusDecodeError> {
614        let first_byte = u8::consensus_decode(reader)?;
615        let leaf_version = LeafVer::from_consensus_u8(first_byte & 0xFE)?;
616        let output_key_parity = Parity::from_consensus_u8(first_byte & 0x01).expect("binary value");
617
618        let internal_key = InternalPk::consensus_decode(reader)?;
619
620        let mut buf = vec![];
621        reader.read_to_end(&mut buf)?;
622        let mut iter = buf.chunks_exact(32);
623        let merkle_branch = iter.by_ref().map(TapBranchHash::from_slice_unsafe);
624        let merkle_branch = TapMerklePath::try_from_iter(merkle_branch)
625            .map_err(|_| ConsensusDataError::LongTapMerklePath)?;
626        if !iter.remainder().is_empty() {
627            return Err(ConsensusDataError::InvalidTapMerklePath.into());
628        }
629
630        Ok(ControlBlock {
631            leaf_version,
632            output_key_parity,
633            internal_pk: internal_key,
634            merkle_branch,
635        })
636    }
637}
638
639impl ConsensusEncode for Sats {
640    fn consensus_encode(&self, writer: &mut impl Write) -> Result<usize, IoError> {
641        self.0.consensus_encode(writer)
642    }
643}
644
645impl ConsensusDecode for Sats {
646    fn consensus_decode(reader: &mut impl Read) -> Result<Self, ConsensusDecodeError> {
647        u64::consensus_decode(reader).map(Self)
648    }
649}
650
651impl ConsensusEncode for Sighash {
652    fn consensus_encode(&self, writer: &mut impl Write) -> Result<usize, IoError> {
653        self.to_byte_array().consensus_encode(writer)
654    }
655}
656
657impl ConsensusEncode for TapLeafHash {
658    fn consensus_encode(&self, writer: &mut impl Write) -> Result<usize, IoError> {
659        self.to_byte_array().consensus_encode(writer)
660    }
661}
662
663impl ConsensusEncode for VarInt {
664    fn consensus_encode(&self, writer: &mut impl Write) -> Result<usize, IoError> {
665        match self.0 {
666            0..=0xFC => {
667                (self.0 as u8).consensus_encode(writer)?;
668                Ok(1)
669            }
670            0xFD..=0xFFFF => {
671                0xFDu8.consensus_encode(writer)?;
672                (self.0 as u16).consensus_encode(writer)?;
673                Ok(3)
674            }
675            0x10000..=0xFFFFFFFF => {
676                0xFEu8.consensus_encode(writer)?;
677                (self.0 as u32).consensus_encode(writer)?;
678                Ok(5)
679            }
680            _ => {
681                0xFFu8.consensus_encode(writer)?;
682                self.0.consensus_encode(writer)?;
683                Ok(9)
684            }
685        }
686    }
687}
688
689impl ConsensusDecode for VarInt {
690    fn consensus_decode(reader: &mut impl Read) -> Result<Self, ConsensusDecodeError> {
691        let n = u8::consensus_decode(reader)?;
692        match n {
693            0xFF => {
694                let x = u64::consensus_decode(reader)?;
695                if x < 0x100000000 {
696                    Err(ConsensusDataError::NonMinimalVarInt)?
697                } else {
698                    Ok(VarInt::new(x))
699                }
700            }
701            0xFE => {
702                let x = u32::consensus_decode(reader)?;
703                if x < 0x10000 {
704                    Err(ConsensusDataError::NonMinimalVarInt)?
705                } else {
706                    Ok(VarInt::new(x as u64))
707                }
708            }
709            0xFD => {
710                let x = u16::consensus_decode(reader)?;
711                if x < 0xFD {
712                    Err(ConsensusDataError::NonMinimalVarInt)?
713                } else {
714                    Ok(VarInt::with(x))
715                }
716            }
717            n => Ok(VarInt::with(n)),
718        }
719    }
720}
721
722impl ConsensusEncode for ByteStr {
723    fn consensus_encode(&self, writer: &mut impl Write) -> Result<usize, IoError> {
724        self.0.consensus_encode(writer)
725    }
726}
727
728impl ConsensusDecode for ByteStr {
729    fn consensus_decode(reader: &mut impl Read) -> Result<Self, ConsensusDecodeError> {
730        VarIntArray::consensus_decode(reader).map(Self::from_inner)
731    }
732}
733
734impl<T: ConsensusEncode, const MIN_LEN: usize> ConsensusEncode for VarIntArray<T, MIN_LEN> {
735    fn consensus_encode(&self, writer: &mut impl Write) -> Result<usize, IoError> {
736        let mut counter = self.len_var_int().consensus_encode(writer)?;
737        for item in self {
738            counter += item.consensus_encode(writer)?;
739        }
740        Ok(counter)
741    }
742}
743
744impl<T: ConsensusDecode, const MIN_LEN: usize> ConsensusDecode for VarIntArray<T, MIN_LEN> {
745    fn consensus_decode(reader: &mut impl Read) -> Result<Self, ConsensusDecodeError> {
746        let len = VarInt::consensus_decode(reader)?;
747        let mut arr = Vec::new();
748        for _ in 0..len.0 {
749            arr.push(T::consensus_decode(reader)?);
750        }
751        VarIntArray::<T, MIN_LEN>::try_from(arr).map_err(ConsensusDecodeError::from)
752    }
753}
754
755impl ConsensusEncode for u8 {
756    fn consensus_encode(&self, writer: &mut impl Write) -> Result<usize, IoError> {
757        writer.write_all(&[*self])?;
758        Ok(1)
759    }
760}
761
762impl ConsensusDecode for u8 {
763    fn consensus_decode(reader: &mut impl Read) -> Result<Self, ConsensusDecodeError> {
764        let mut buf = [0u8; (Self::BITS / 8) as usize];
765        reader.read_exact(&mut buf)?;
766        Ok(Self::from_le_bytes(buf))
767    }
768}
769
770impl ConsensusEncode for u16 {
771    fn consensus_encode(&self, writer: &mut impl Write) -> Result<usize, IoError> {
772        writer.write_all(&self.to_le_bytes())?;
773        Ok(2)
774    }
775}
776
777impl ConsensusDecode for u16 {
778    fn consensus_decode(reader: &mut impl Read) -> Result<Self, ConsensusDecodeError> {
779        let mut buf = [0u8; (Self::BITS / 8) as usize];
780        reader.read_exact(&mut buf)?;
781        Ok(Self::from_le_bytes(buf))
782    }
783}
784
785impl ConsensusEncode for u32 {
786    fn consensus_encode(&self, writer: &mut impl Write) -> Result<usize, IoError> {
787        writer.write_all(&self.to_le_bytes())?;
788        Ok(4)
789    }
790}
791
792impl ConsensusDecode for u32 {
793    fn consensus_decode(reader: &mut impl Read) -> Result<Self, ConsensusDecodeError> {
794        let mut buf = [0u8; (Self::BITS / 8) as usize];
795        reader.read_exact(&mut buf)?;
796        Ok(Self::from_le_bytes(buf))
797    }
798}
799
800impl ConsensusEncode for i32 {
801    fn consensus_encode(&self, writer: &mut impl Write) -> Result<usize, IoError> {
802        writer.write_all(&self.to_le_bytes())?;
803        Ok(4)
804    }
805}
806
807impl ConsensusDecode for i32 {
808    fn consensus_decode(reader: &mut impl Read) -> Result<Self, ConsensusDecodeError> {
809        let mut buf = [0u8; (Self::BITS / 8) as usize];
810        reader.read_exact(&mut buf)?;
811        Ok(Self::from_le_bytes(buf))
812    }
813}
814
815impl ConsensusEncode for u64 {
816    fn consensus_encode(&self, writer: &mut impl Write) -> Result<usize, IoError> {
817        writer.write_all(&self.to_le_bytes())?;
818        Ok(8)
819    }
820}
821
822impl ConsensusDecode for u64 {
823    fn consensus_decode(reader: &mut impl Read) -> Result<Self, ConsensusDecodeError> {
824        let mut buf = [0u8; (Self::BITS / 8) as usize];
825        reader.read_exact(&mut buf)?;
826        Ok(Self::from_le_bytes(buf))
827    }
828}
829
830impl ConsensusEncode for Bytes32 {
831    fn consensus_encode(&self, writer: &mut impl Write) -> Result<usize, IoError> {
832        writer.write_all(&self.to_byte_array())?;
833        Ok(8)
834    }
835}
836
837impl ConsensusEncode for [u8; 32] {
838    fn consensus_encode(&self, writer: &mut impl Write) -> Result<usize, IoError> {
839        writer.write_all(self)?;
840        Ok(8)
841    }
842}
843
844impl ConsensusDecode for [u8; 32] {
845    fn consensus_decode(reader: &mut impl Read) -> Result<Self, ConsensusDecodeError> {
846        let mut buf = [0u8; 32];
847        reader.read_exact(&mut buf)?;
848        Ok(buf)
849    }
850}
851
852#[cfg(test)]
853mod tests {
854    use super::*;
855
856    fn serialize(t: &impl ConsensusEncode) -> Vec<u8> {
857        let mut vec = Vec::new();
858        t.consensus_encode(&mut vec).unwrap();
859        vec
860    }
861
862    fn deserialize<T: ConsensusDecode>(d: impl AsRef<[u8]>) -> Result<T, ConsensusDecodeError> {
863        T::consensus_deserialize(d)
864    }
865
866    fn deserialize_partial<T: ConsensusDecode>(
867        d: impl AsRef<[u8]>,
868    ) -> Result<T, ConsensusDataError> {
869        let mut cursor = Cursor::new(d.as_ref());
870        T::consensus_decode(&mut cursor).map_err(|err| match err {
871            ConsensusDecodeError::Data(e) => e,
872            ConsensusDecodeError::Io(_) => unreachable!(),
873        })
874    }
875
876    #[test]
877    fn serialize_int_test() {
878        // u8
879        assert_eq!(serialize(&1u8), vec![1u8]);
880        assert_eq!(serialize(&0u8), vec![0u8]);
881        assert_eq!(serialize(&255u8), vec![255u8]);
882        // u16
883        assert_eq!(serialize(&1u16), vec![1u8, 0]);
884        assert_eq!(serialize(&256u16), vec![0u8, 1]);
885        assert_eq!(serialize(&5000u16), vec![136u8, 19]);
886        // u32
887        assert_eq!(serialize(&1u32), vec![1u8, 0, 0, 0]);
888        assert_eq!(serialize(&256u32), vec![0u8, 1, 0, 0]);
889        assert_eq!(serialize(&5000u32), vec![136u8, 19, 0, 0]);
890        assert_eq!(serialize(&500000u32), vec![32u8, 161, 7, 0]);
891        assert_eq!(serialize(&168430090u32), vec![10u8, 10, 10, 10]);
892        // i32
893        assert_eq!(serialize(&-1i32), vec![255u8, 255, 255, 255]);
894        assert_eq!(serialize(&-256i32), vec![0u8, 255, 255, 255]);
895        assert_eq!(serialize(&-5000i32), vec![120u8, 236, 255, 255]);
896        assert_eq!(serialize(&-500000i32), vec![224u8, 94, 248, 255]);
897        assert_eq!(serialize(&-168430090i32), vec![246u8, 245, 245, 245]);
898        assert_eq!(serialize(&1i32), vec![1u8, 0, 0, 0]);
899        assert_eq!(serialize(&256i32), vec![0u8, 1, 0, 0]);
900        assert_eq!(serialize(&5000i32), vec![136u8, 19, 0, 0]);
901        assert_eq!(serialize(&500000i32), vec![32u8, 161, 7, 0]);
902        assert_eq!(serialize(&168430090i32), vec![10u8, 10, 10, 10]);
903        // u64
904        assert_eq!(serialize(&1u64), vec![1u8, 0, 0, 0, 0, 0, 0, 0]);
905        assert_eq!(serialize(&256u64), vec![0u8, 1, 0, 0, 0, 0, 0, 0]);
906        assert_eq!(serialize(&5000u64), vec![136u8, 19, 0, 0, 0, 0, 0, 0]);
907        assert_eq!(serialize(&500000u64), vec![32u8, 161, 7, 0, 0, 0, 0, 0]);
908        assert_eq!(serialize(&723401728380766730u64), vec![10u8, 10, 10, 10, 10, 10, 10, 10]);
909    }
910
911    #[test]
912    fn serialize_varint_test() {
913        assert_eq!(serialize(&VarInt(10)), vec![10u8]);
914        assert_eq!(serialize(&VarInt(0xFC)), vec![0xFCu8]);
915        assert_eq!(serialize(&VarInt(0xFD)), vec![0xFDu8, 0xFD, 0]);
916        assert_eq!(serialize(&VarInt(0xFFF)), vec![0xFDu8, 0xFF, 0xF]);
917        assert_eq!(serialize(&VarInt(0xF0F0F0F)), vec![0xFEu8, 0xF, 0xF, 0xF, 0xF]);
918        assert_eq!(serialize(&VarInt(0xF0F0F0F0F0E0)), vec![
919            0xFFu8, 0xE0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0, 0
920        ]);
921        assert_eq!(
922            test_varint_encode(0xFF, &0x100000000_u64.to_le_bytes()).unwrap(),
923            VarInt(0x100000000)
924        );
925        assert_eq!(test_varint_encode(0xFE, &0x10000_u64.to_le_bytes()).unwrap(), VarInt(0x10000));
926        assert_eq!(test_varint_encode(0xFD, &0xFD_u64.to_le_bytes()).unwrap(), VarInt(0xFD));
927
928        // Test that length calc is working correctly
929        test_varint_len(VarInt(0), 1);
930        test_varint_len(VarInt(0xFC), 1);
931        test_varint_len(VarInt(0xFD), 3);
932        test_varint_len(VarInt(0xFFFF), 3);
933        test_varint_len(VarInt(0x10000), 5);
934        test_varint_len(VarInt(0xFFFFFFFF), 5);
935        test_varint_len(VarInt(0xFFFFFFFF + 1), 9);
936        test_varint_len(VarInt(u64::MAX), 9);
937    }
938
939    fn test_varint_len(varint: VarInt, expected: usize) {
940        let mut encoder = vec![];
941        assert_eq!(varint.consensus_encode(&mut encoder).unwrap(), expected);
942        assert_eq!(varint.len(), expected);
943    }
944
945    fn test_varint_encode(n: u8, x: &[u8]) -> Result<VarInt, ConsensusDataError> {
946        let mut input = [0u8; 9];
947        input[0] = n;
948        input[1..x.len() + 1].copy_from_slice(x);
949        deserialize_partial::<VarInt>(&input)
950    }
951
952    #[test]
953    fn deserialize_nonminimal_vec() {
954        // Check the edges for variant int
955        assert_eq!(
956            test_varint_encode(0xFF, &(0x100000000_u64 - 1).to_le_bytes()).unwrap_err(),
957            ConsensusDataError::NonMinimalVarInt
958        );
959        assert_eq!(
960            test_varint_encode(0xFE, &(0x10000_u64 - 1).to_le_bytes()).unwrap_err(),
961            ConsensusDataError::NonMinimalVarInt
962        );
963        assert_eq!(
964            test_varint_encode(0xFD, &(0xFD_u64 - 1).to_le_bytes()).unwrap_err(),
965            ConsensusDataError::NonMinimalVarInt
966        );
967
968        assert_eq!(
969            deserialize::<VarIntArray<u8>>(&[0xfd, 0x00, 0x00]).unwrap_err(),
970            ConsensusDataError::NonMinimalVarInt.into()
971        );
972        assert_eq!(
973            deserialize::<VarIntArray<u8>>(&[0xfd, 0xfc, 0x00]).unwrap_err(),
974            ConsensusDataError::NonMinimalVarInt.into()
975        );
976        assert_eq!(
977            deserialize::<VarIntArray<u8>>(&[0xfd, 0xfc, 0x00]).unwrap_err(),
978            ConsensusDataError::NonMinimalVarInt.into()
979        );
980        assert_eq!(
981            deserialize::<VarIntArray<u8>>(&[0xfe, 0xff, 0x00, 0x00, 0x00]).unwrap_err(),
982            ConsensusDataError::NonMinimalVarInt.into()
983        );
984        assert_eq!(
985            deserialize::<VarIntArray<u8>>(&[0xfe, 0xff, 0xff, 0x00, 0x00]).unwrap_err(),
986            ConsensusDataError::NonMinimalVarInt.into()
987        );
988        assert_eq!(
989            deserialize::<VarIntArray<u8>>(&[0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
990                .unwrap_err(),
991            ConsensusDataError::NonMinimalVarInt.into()
992        );
993        assert_eq!(
994            deserialize::<VarIntArray<u8>>(&[0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00])
995                .unwrap_err(),
996            ConsensusDataError::NonMinimalVarInt.into()
997        );
998
999        let mut vec_256 = vec![0; 259];
1000        vec_256[0] = 0xfd;
1001        vec_256[1] = 0x00;
1002        vec_256[2] = 0x01;
1003        assert!(deserialize::<VarIntArray<u8>>(&vec_256).is_ok());
1004
1005        let mut vec_253 = vec![0; 256];
1006        vec_253[0] = 0xfd;
1007        vec_253[1] = 0xfd;
1008        vec_253[2] = 0x00;
1009        assert!(deserialize::<VarIntArray<u8>>(&vec_253).is_ok());
1010    }
1011
1012    #[test]
1013    fn deserialize_int_test() {
1014        // u8
1015        assert_eq!(deserialize([58u8]).ok(), Some(58u8));
1016
1017        // u16
1018        assert_eq!(deserialize([0x01u8, 0x02]).ok(), Some(0x0201u16));
1019        assert_eq!(deserialize([0xABu8, 0xCD]).ok(), Some(0xCDABu16));
1020        assert_eq!(deserialize([0xA0u8, 0x0D]).ok(), Some(0xDA0u16));
1021        let failure16: Result<u16, _> = deserialize([1u8]);
1022        assert!(failure16.is_err());
1023
1024        // u32
1025        assert_eq!(deserialize([0xABu8, 0xCD, 0, 0]).ok(), Some(0xCDABu32));
1026        assert_eq!(deserialize([0xA0u8, 0x0D, 0xAB, 0xCD]).ok(), Some(0xCDAB0DA0u32));
1027
1028        let failure32: Result<u32, _> = deserialize([1u8, 2, 3]);
1029        assert!(failure32.is_err());
1030
1031        // i32
1032        assert_eq!(deserialize([0xABu8, 0xCD, 0, 0]).ok(), Some(0xCDABi32));
1033        assert_eq!(deserialize([0xA0u8, 0x0D, 0xAB, 0x2D]).ok(), Some(0x2DAB0DA0i32));
1034
1035        assert_eq!(deserialize([0, 0, 0, 0]).ok(), Some(-0_i32));
1036        assert_eq!(deserialize([0, 0, 0, 0]).ok(), Some(0_i32));
1037
1038        assert_eq!(deserialize([0xFF, 0xFF, 0xFF, 0xFF]).ok(), Some(-1_i32));
1039        assert_eq!(deserialize([0xFE, 0xFF, 0xFF, 0xFF]).ok(), Some(-2_i32));
1040        assert_eq!(deserialize([0x01, 0xFF, 0xFF, 0xFF]).ok(), Some(-255_i32));
1041        assert_eq!(deserialize([0x02, 0xFF, 0xFF, 0xFF]).ok(), Some(-254_i32));
1042
1043        let failurei32: Result<i32, _> = deserialize([1u8, 2, 3]);
1044        assert!(failurei32.is_err());
1045
1046        // u64
1047        assert_eq!(deserialize([0xABu8, 0xCD, 0, 0, 0, 0, 0, 0]).ok(), Some(0xCDABu64));
1048        assert_eq!(
1049            deserialize([0xA0u8, 0x0D, 0xAB, 0xCD, 0x99, 0, 0, 0x99]).ok(),
1050            Some(0x99000099CDAB0DA0u64)
1051        );
1052        let failure64: Result<u64, _> = deserialize([1u8, 2, 3, 4, 5, 6, 7]);
1053        assert!(failure64.is_err());
1054    }
1055}