bitcoin/blockdata/
witness.rs

1// SPDX-License-Identifier: CC0-1.0
2
3//! Witness
4//!
5//! This module contains the [`Witness`] struct and related methods to operate on it
6//!
7
8use core::fmt;
9use core::ops::Index;
10
11use io::{Read, Write};
12
13use crate::consensus::encode::{Error, MAX_VEC_SIZE};
14use crate::consensus::{Decodable, Encodable, WriteExt};
15use crate::crypto::ecdsa;
16use crate::prelude::*;
17use crate::taproot::{
18    self, LeafScript, LeafVersion, TAPROOT_ANNEX_PREFIX, TAPROOT_CONTROL_BASE_SIZE,
19    TAPROOT_LEAF_MASK,
20};
21use crate::{Script, VarInt};
22
23/// The Witness is the data used to unlock bitcoin since the [segwit upgrade].
24///
25/// Can be logically seen as an array of bytestrings, i.e. `Vec<Vec<u8>>`, and it is serialized on the wire
26/// in that format. You can convert between this type and `Vec<Vec<u8>>` by using [`Witness::from_slice`]
27/// and [`Witness::to_vec`].
28///
29/// For serialization and deserialization performance it is stored internally as a single `Vec`,
30/// saving some allocations.
31///
32/// [segwit upgrade]: <https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki>
33#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
34pub struct Witness {
35    /// Contains the witness `Vec<Vec<u8>>` serialization without the initial varint indicating the
36    /// number of elements (which is stored in `witness_elements`).
37    content: Vec<u8>,
38
39    /// The number of elements in the witness.
40    ///
41    /// Stored separately (instead of as a VarInt in the initial part of content) so that methods
42    /// like [`Witness::push`] don't have to shift the entire array.
43    witness_elements: usize,
44
45    /// This is the valid index pointing to the beginning of the index area. This area is 4 *
46    /// stack_size bytes at the end of the content vector which stores the indices of each item.
47    indices_start: usize,
48}
49
50impl fmt::Debug for Witness {
51    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
52        if f.alternate() {
53            fmt_debug_pretty(self, f)
54        } else {
55            fmt_debug(self, f)
56        }
57    }
58}
59
60fn fmt_debug(w: &Witness, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
61    #[rustfmt::skip]
62    let comma_or_close = |current_index, last_index| {
63        if current_index == last_index { "]" } else { ", " }
64    };
65
66    f.write_str("Witness: { ")?;
67    write!(f, "indices: {}, ", w.witness_elements)?;
68    write!(f, "indices_start: {}, ", w.indices_start)?;
69    f.write_str("witnesses: [")?;
70
71    let instructions = w.iter();
72    match instructions.len().checked_sub(1) {
73        Some(last_instruction) => {
74            for (i, instruction) in instructions.enumerate() {
75                let bytes = instruction.iter();
76                match bytes.len().checked_sub(1) {
77                    Some(last_byte) => {
78                        f.write_str("[")?;
79                        for (j, byte) in bytes.enumerate() {
80                            write!(f, "{:#04x}", byte)?;
81                            f.write_str(comma_or_close(j, last_byte))?;
82                        }
83                    }
84                    None => {
85                        // This is possible because the varint is not part of the instruction (see Iter).
86                        write!(f, "[]")?;
87                    }
88                }
89                f.write_str(comma_or_close(i, last_instruction))?;
90            }
91        }
92        None => {
93            // Witnesses can be empty because the 0x00 var int is not stored in content.
94            write!(f, "]")?;
95        }
96    }
97
98    f.write_str(" }")
99}
100
101fn fmt_debug_pretty(w: &Witness, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
102    f.write_str("Witness: {\n")?;
103    writeln!(f, "    indices: {},", w.witness_elements)?;
104    writeln!(f, "    indices_start: {},", w.indices_start)?;
105    f.write_str("    witnesses: [\n")?;
106
107    for instruction in w.iter() {
108        f.write_str("        [")?;
109        for (j, byte) in instruction.iter().enumerate() {
110            if j > 0 {
111                f.write_str(", ")?;
112            }
113            write!(f, "{:#04x}", byte)?;
114        }
115        f.write_str("],\n")?;
116    }
117
118    writeln!(f, "    ],")?;
119    writeln!(f, "}}")
120}
121
122/// An iterator returning individual witness elements.
123pub struct Iter<'a> {
124    inner: &'a [u8],
125    indices_start: usize,
126    current_index: usize,
127}
128
129impl Decodable for Witness {
130    fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, Error> {
131        let witness_elements = VarInt::consensus_decode(r)?.0 as usize;
132        // Minimum size of witness element is 1 byte, so if the count is
133        // greater than MAX_VEC_SIZE we must return an error.
134        if witness_elements > MAX_VEC_SIZE {
135            return Err(self::Error::OversizedVectorAllocation {
136                requested: witness_elements,
137                max: MAX_VEC_SIZE,
138            });
139        }
140        if witness_elements == 0 {
141            Ok(Witness::default())
142        } else {
143            // Leave space at the head for element positions.
144            // We will rotate them to the end of the Vec later.
145            let witness_index_space = witness_elements * 4;
146            let mut cursor = witness_index_space;
147
148            // this number should be determined as high enough to cover most witness, and low enough
149            // to avoid wasting space without reallocating
150            let mut content = vec![0u8; cursor + 128];
151
152            for i in 0..witness_elements {
153                let element_size_varint = VarInt::consensus_decode(r)?;
154                let element_size_varint_len = element_size_varint.size();
155                let element_size = element_size_varint.0 as usize;
156                let required_len = cursor
157                    .checked_add(element_size)
158                    .ok_or(self::Error::OversizedVectorAllocation {
159                        requested: usize::MAX,
160                        max: MAX_VEC_SIZE,
161                    })?
162                    .checked_add(element_size_varint_len)
163                    .ok_or(self::Error::OversizedVectorAllocation {
164                        requested: usize::MAX,
165                        max: MAX_VEC_SIZE,
166                    })?;
167
168                if required_len > MAX_VEC_SIZE + witness_index_space {
169                    return Err(self::Error::OversizedVectorAllocation {
170                        requested: required_len,
171                        max: MAX_VEC_SIZE,
172                    });
173                }
174
175                // We will do content.rotate_left(witness_index_space) later.
176                // Encode the position's value AFTER we rotate left.
177                encode_cursor(&mut content, 0, i, cursor - witness_index_space);
178
179                resize_if_needed(&mut content, required_len);
180                element_size_varint.consensus_encode(
181                    &mut &mut content[cursor..cursor + element_size_varint_len],
182                )?;
183                cursor += element_size_varint_len;
184                r.read_exact(&mut content[cursor..cursor + element_size])?;
185                cursor += element_size;
186            }
187            content.truncate(cursor);
188            // Index space is now at the end of the Vec
189            content.rotate_left(witness_index_space);
190            Ok(Witness { content, witness_elements, indices_start: cursor - witness_index_space })
191        }
192    }
193}
194
195/// Correctness Requirements: value must always fit within u32
196#[inline]
197fn encode_cursor(bytes: &mut [u8], start_of_indices: usize, index: usize, value: usize) {
198    let start = start_of_indices + index * 4;
199    let end = start + 4;
200    bytes[start..end]
201        .copy_from_slice(&u32::to_ne_bytes(value.try_into().expect("Larger than u32")));
202}
203
204#[inline]
205fn decode_cursor(bytes: &[u8], start_of_indices: usize, index: usize) -> Option<usize> {
206    let start = start_of_indices + index * 4;
207    let end = start + 4;
208    if end > bytes.len() {
209        None
210    } else {
211        Some(u32::from_ne_bytes(bytes[start..end].try_into().expect("is u32 size")) as usize)
212    }
213}
214
215fn resize_if_needed(vec: &mut Vec<u8>, required_len: usize) {
216    if required_len >= vec.len() {
217        let mut new_len = vec.len().max(1);
218        while new_len <= required_len {
219            new_len *= 2;
220        }
221        vec.resize(new_len, 0);
222    }
223}
224
225impl Encodable for Witness {
226    fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
227        let len = VarInt::from(self.witness_elements);
228        len.consensus_encode(w)?;
229        let content_with_indices_len = self.content.len();
230        let indices_size = self.witness_elements * 4;
231        let content_len = content_with_indices_len - indices_size;
232        w.emit_slice(&self.content[..content_len])?;
233        Ok(content_len + len.size())
234    }
235}
236
237impl Witness {
238    /// Creates a new empty [`Witness`].
239    #[inline]
240    pub const fn new() -> Self {
241        Witness { content: Vec::new(), witness_elements: 0, indices_start: 0 }
242    }
243
244    /// Creates a witness required to spend a P2WPKH output.
245    ///
246    /// The witness will be made up of the DER encoded signature + sighash_type followed by the
247    /// serialized public key. Also useful for spending a P2SH-P2WPKH output.
248    ///
249    /// It is expected that `pubkey` is related to the secret key used to create `signature`.
250    pub fn p2wpkh(signature: &ecdsa::Signature, pubkey: &secp256k1::PublicKey) -> Witness {
251        let mut witness = Witness::new();
252        witness.push_slice(&signature.serialize());
253        witness.push_slice(&pubkey.serialize());
254        witness
255    }
256
257    /// Creates a witness required to do a key path spend of a P2TR output.
258    pub fn p2tr_key_spend(signature: &taproot::Signature) -> Witness {
259        let mut witness = Witness::new();
260        witness.push_slice(&signature.serialize());
261        witness
262    }
263
264    /// Creates a [`Witness`] object from a slice of bytes slices where each slice is a witness item.
265    pub fn from_slice<T: AsRef<[u8]>>(slice: &[T]) -> Self {
266        let witness_elements = slice.len();
267        let index_size = witness_elements * 4;
268        let content_size = slice
269            .iter()
270            .map(|elem| elem.as_ref().len() + VarInt::from(elem.as_ref().len()).size())
271            .sum();
272
273        let mut content = vec![0u8; content_size + index_size];
274        let mut cursor = 0usize;
275        for (i, elem) in slice.iter().enumerate() {
276            encode_cursor(&mut content, content_size, i, cursor);
277            let elem_len_varint = VarInt::from(elem.as_ref().len());
278            elem_len_varint
279                .consensus_encode(&mut &mut content[cursor..cursor + elem_len_varint.size()])
280                .expect("writers on vec don't errors, space granted by content_size");
281            cursor += elem_len_varint.size();
282            content[cursor..cursor + elem.as_ref().len()].copy_from_slice(elem.as_ref());
283            cursor += elem.as_ref().len();
284        }
285
286        Witness { witness_elements, content, indices_start: content_size }
287    }
288
289    /// Convenience method to create an array of byte-arrays from this witness.
290    pub fn to_vec(&self) -> Vec<Vec<u8>> { self.iter().map(|s| s.to_vec()).collect() }
291
292    /// Returns `true` if the witness contains no element.
293    pub fn is_empty(&self) -> bool { self.witness_elements == 0 }
294
295    /// Returns a struct implementing [`Iterator`].
296    pub fn iter(&self) -> Iter<'_> {
297        Iter { inner: self.content.as_slice(), indices_start: self.indices_start, current_index: 0 }
298    }
299
300    /// Returns the number of elements this witness holds.
301    pub fn len(&self) -> usize { self.witness_elements }
302
303    /// Returns the number of bytes this witness contributes to a transactions total size.
304    pub fn size(&self) -> usize {
305        let mut size: usize = 0;
306
307        size += VarInt::from(self.witness_elements).size();
308        size += self
309            .iter()
310            .map(|witness_element| {
311                VarInt::from(witness_element.len()).size() + witness_element.len()
312            })
313            .sum::<usize>();
314
315        size
316    }
317
318    /// Clear the witness.
319    pub fn clear(&mut self) {
320        self.content.clear();
321        self.witness_elements = 0;
322        self.indices_start = 0;
323    }
324
325    /// Push a new element on the witness, requires an allocation.
326    pub fn push<T: AsRef<[u8]>>(&mut self, new_element: T) {
327        self.push_slice(new_element.as_ref());
328    }
329
330    /// Push a new element slice onto the witness stack.
331    fn push_slice(&mut self, new_element: &[u8]) {
332        self.witness_elements += 1;
333        let previous_content_end = self.indices_start;
334        let element_len_varint = VarInt::from(new_element.len());
335        let current_content_len = self.content.len();
336        let new_item_total_len = element_len_varint.size() + new_element.len();
337        self.content.resize(current_content_len + new_item_total_len + 4, 0);
338
339        self.content[previous_content_end..].rotate_right(new_item_total_len);
340        self.indices_start += new_item_total_len;
341        encode_cursor(
342            &mut self.content,
343            self.indices_start,
344            self.witness_elements - 1,
345            previous_content_end,
346        );
347
348        let end_varint = previous_content_end + element_len_varint.size();
349        element_len_varint
350            .consensus_encode(&mut &mut self.content[previous_content_end..end_varint])
351            .expect("writers on vec don't error, space granted through previous resize");
352        self.content[end_varint..end_varint + new_element.len()].copy_from_slice(new_element);
353    }
354
355    /// Pushes, as a new element on the witness, an ECDSA signature.
356    ///
357    /// Pushes the DER encoded signature + sighash_type, requires an allocation.
358    pub fn push_ecdsa_signature(&mut self, signature: &ecdsa::Signature) {
359        self.push_slice(&signature.serialize())
360    }
361
362    fn element_at(&self, index: usize) -> Option<&[u8]> {
363        let varint = VarInt::consensus_decode(&mut &self.content[index..]).ok()?;
364        let start = index + varint.size();
365        Some(&self.content[start..start + varint.0 as usize])
366    }
367
368    /// Returns the last element in the witness, if any.
369    pub fn last(&self) -> Option<&[u8]> {
370        if self.witness_elements == 0 {
371            None
372        } else {
373            self.nth(self.witness_elements - 1)
374        }
375    }
376
377    /// Returns the second-to-last element in the witness, if any.
378    pub fn second_to_last(&self) -> Option<&[u8]> {
379        if self.witness_elements <= 1 {
380            None
381        } else {
382            self.nth(self.witness_elements - 2)
383        }
384    }
385
386    /// Returns the third-to-last element in the witness, if any.
387    pub fn third_to_last(&self) -> Option<&[u8]> {
388        if self.witness_elements <= 2 {
389            None
390        } else {
391            self.nth(self.witness_elements - 3)
392        }
393    }
394
395    /// Return the nth element in the witness, if any
396    pub fn nth(&self, index: usize) -> Option<&[u8]> {
397        let pos = decode_cursor(&self.content, self.indices_start, index)?;
398        self.element_at(pos)
399    }
400
401    /// Get leaf script following BIP341 rules regarding accounting for an annex.
402    ///
403    /// This method is broken: it's called `tapscript` but it's actually returning a leaf script.
404    /// We're not going to fix it because someone might be relying on it thinking leaf script and
405    /// tapscript are the same thing (they are not). Instead, this is deprecated and will be
406    /// removed in the next breaking release. You need to use `taproot_leaf_script` and if you
407    /// intended to use it as leaf script, just access the `script` field of the returned type. If
408    /// you intended tapscript specifically you have to check the version first and bail if it's not
409    /// `LeafVersion::TapScript`.
410    ///
411    /// This does not guarantee that this represents a P2TR [`Witness`]. It
412    /// merely gets the second to last or third to last element depending on
413    /// the first byte of the last element being equal to 0x50.
414    ///
415    /// See [`Script::is_p2tr`] to check whether this is actually a Taproot witness.
416    #[deprecated = "use `taproot_leaf_script` and check leaf version, if applicable"]
417    pub fn tapscript(&self) -> Option<&Script> {
418        match P2TrSpend::from_witness(self) {
419            // Note: the method is named "tapscript" but historically it was actually returning
420            // leaf script. This is broken but we now keep the behavior the same to not subtly
421            // break someone.
422            Some(P2TrSpend::Script { leaf_script, .. }) => Some(leaf_script),
423            _ => None,
424        }
425    }
426
427    /// Returns the leaf script with its version but without the merkle proof.
428    ///
429    /// This does not guarantee that this represents a P2TR [`Witness`]. It
430    /// merely gets the second to last or third to last element depending on
431    /// the first byte of the last element being equal to 0x50 and the associated
432    /// version.
433    pub fn taproot_leaf_script(&self) -> Option<LeafScript<&Script>> {
434        match P2TrSpend::from_witness(self) {
435            Some(P2TrSpend::Script { leaf_script, control_block, .. })
436                if control_block.len() >= TAPROOT_CONTROL_BASE_SIZE =>
437            {
438                let version =
439                    LeafVersion::from_consensus(control_block[0] & TAPROOT_LEAF_MASK).ok()?;
440                Some(LeafScript { version, script: leaf_script })
441            }
442            _ => None,
443        }
444    }
445
446    /// Get the taproot control block following BIP341 rules.
447    ///
448    /// This does not guarantee that this represents a P2TR [`Witness`]. It
449    /// merely gets the last or second to last element depending on the first
450    /// byte of the last element being equal to 0x50.
451    ///
452    /// See [`Script::is_p2tr`] to check whether this is actually a Taproot witness.
453    pub fn taproot_control_block(&self) -> Option<&[u8]> {
454        match P2TrSpend::from_witness(self) {
455            Some(P2TrSpend::Script { control_block, .. }) => Some(control_block),
456            _ => None,
457        }
458    }
459
460    /// Get the taproot annex following BIP341 rules.
461    ///
462    /// This does not guarantee that this represents a P2TR [`Witness`].
463    ///
464    /// See [`Script::is_p2tr`] to check whether this is actually a Taproot witness.
465    pub fn taproot_annex(&self) -> Option<&[u8]> { P2TrSpend::from_witness(self)?.annex() }
466
467    /// Get the p2wsh witness script following BIP141 rules.
468    ///
469    /// This does not guarantee that this represents a P2WS [`Witness`]. See
470    /// [Script::is_p2wsh](crate::blockdata::script::Script::is_p2wsh) to
471    /// check whether this is actually a P2WSH witness.
472    pub fn witness_script(&self) -> Option<&Script> { self.last().map(Script::from_bytes) }
473}
474
475impl Index<usize> for Witness {
476    type Output = [u8];
477
478    fn index(&self, index: usize) -> &Self::Output { self.nth(index).expect("Out of Bounds") }
479}
480
481/// Represents a possible Taproot spend.
482///
483/// Taproot can be spent as key spend or script spend and, depending on which it is, different data
484/// is in the witness. This type helps representing that data more cleanly when parsing the witness
485/// because there are a lot of conditions that make reasoning hard. It's better to parse it at one
486/// place and pass it along.
487///
488/// This type is so far private but it could be published eventually. The design is geared towards
489/// it but it's not fully finished.
490enum P2TrSpend<'a> {
491    Key {
492        // This field is technically present in witness in case of key spend but none of our code
493        // uses it yet. Rather than deleting it, it's kept here commented as documentation and as
494        // an easy way to add it if anything needs it - by just uncommenting.
495        // signature: &'a [u8],
496        annex: Option<&'a [u8]>,
497    },
498    Script {
499        leaf_script: &'a Script,
500        control_block: &'a [u8],
501        annex: Option<&'a [u8]>,
502    },
503}
504
505impl<'a> P2TrSpend<'a> {
506    /// Parses `Witness` to determine what kind of taproot spend this is.
507    ///
508    /// Note: this assumes `witness` is a taproot spend. The function cannot figure it out for sure
509    /// (without knowing the output), so it doesn't attempt to check anything other than what is
510    /// required for the program to not crash.
511    ///
512    /// In other words, if the caller is certain that the witness is a valid p2tr spend (e.g.
513    /// obtained from Bitcoin Core) then it's OK to unwrap this but not vice versa - `Some` does
514    /// not imply correctness.
515    fn from_witness(witness: &'a Witness) -> Option<Self> {
516        // BIP341 says:
517        //   If there are at least two witness elements, and the first byte of
518        //   the last element is 0x50, this last element is called annex a
519        //   and is removed from the witness stack.
520        //
521        // However here we're not removing anything, so we have to adjust the numbers to account
522        // for the fact that annex is still there.
523        match witness.len() {
524            0 => None,
525            1 => Some(P2TrSpend::Key {
526                /* signature: witness.last().expect("len > 0") ,*/ annex: None,
527            }),
528            2 if witness.last().expect("len > 0").starts_with(&[TAPROOT_ANNEX_PREFIX]) => {
529                let spend = P2TrSpend::Key {
530                    // signature: witness.second_to_last().expect("len > 1"),
531                    annex: witness.last(),
532                };
533                Some(spend)
534            }
535            // 2 => this is script spend without annex - same as when there are 3+ elements and the
536            //   last one does NOT start with TAPROOT_ANNEX_PREFIX. This is handled in the catchall
537            //   arm.
538            3.. if witness.last().expect("len > 0").starts_with(&[TAPROOT_ANNEX_PREFIX]) => {
539                let spend = P2TrSpend::Script {
540                    leaf_script: Script::from_bytes(witness.third_to_last().expect("len > 2")),
541                    control_block: witness.second_to_last().expect("len > 1"),
542                    annex: witness.last(),
543                };
544                Some(spend)
545            }
546            _ => {
547                let spend = P2TrSpend::Script {
548                    leaf_script: Script::from_bytes(witness.second_to_last().expect("len > 1")),
549                    control_block: witness.last().expect("len > 0"),
550                    annex: None,
551                };
552                Some(spend)
553            }
554        }
555    }
556
557    fn annex(&self) -> Option<&'a [u8]> {
558        match self {
559            P2TrSpend::Key { annex, .. } => *annex,
560            P2TrSpend::Script { annex, .. } => *annex,
561        }
562    }
563}
564
565impl<'a> Iterator for Iter<'a> {
566    type Item = &'a [u8];
567
568    fn next(&mut self) -> Option<Self::Item> {
569        let index = decode_cursor(self.inner, self.indices_start, self.current_index)?;
570        let varint = VarInt::consensus_decode(&mut &self.inner[index..]).ok()?;
571        let start = index + varint.size();
572        let end = start + varint.0 as usize;
573        let slice = &self.inner[start..end];
574        self.current_index += 1;
575        Some(slice)
576    }
577
578    fn size_hint(&self) -> (usize, Option<usize>) {
579        let total_count = (self.inner.len() - self.indices_start) / 4;
580        let remaining = total_count - self.current_index;
581        (remaining, Some(remaining))
582    }
583}
584
585impl<'a> ExactSizeIterator for Iter<'a> {}
586
587impl<'a> IntoIterator for &'a Witness {
588    type IntoIter = Iter<'a>;
589    type Item = &'a [u8];
590
591    fn into_iter(self) -> Self::IntoIter { self.iter() }
592}
593
594// Serde keep backward compatibility with old Vec<Vec<u8>> format
595#[cfg(feature = "serde")]
596impl serde::Serialize for Witness {
597    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
598    where
599        S: serde::Serializer,
600    {
601        use serde::ser::SerializeSeq;
602
603        let human_readable = serializer.is_human_readable();
604        let mut seq = serializer.serialize_seq(Some(self.witness_elements))?;
605
606        for elem in self.iter() {
607            if human_readable {
608                seq.serialize_element(&crate::serde_utils::SerializeBytesAsHex(elem))?;
609            } else {
610                seq.serialize_element(&elem)?;
611            }
612        }
613        seq.end()
614    }
615}
616
617#[cfg(feature = "serde")]
618impl<'de> serde::Deserialize<'de> for Witness {
619    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
620    where
621        D: serde::Deserializer<'de>,
622    {
623        struct Visitor; // Human-readable visitor.
624        impl<'de> serde::de::Visitor<'de> for Visitor {
625            type Value = Witness;
626
627            fn expecting(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
628                write!(f, "a sequence of hex arrays")
629            }
630
631            fn visit_seq<A: serde::de::SeqAccess<'de>>(
632                self,
633                mut a: A,
634            ) -> Result<Self::Value, A::Error> {
635                use hex::FromHex;
636                use hex::HexToBytesError::*;
637                use serde::de::{self, Unexpected};
638
639                let mut ret = match a.size_hint() {
640                    Some(len) => Vec::with_capacity(len),
641                    None => Vec::new(),
642                };
643
644                while let Some(elem) = a.next_element::<String>()? {
645                    let vec = Vec::<u8>::from_hex(&elem).map_err(|e| match e {
646                        InvalidChar(ref e) => match core::char::from_u32(e.invalid_char().into()) {
647                            Some(c) => de::Error::invalid_value(
648                                Unexpected::Char(c),
649                                &"a valid hex character",
650                            ),
651                            None => de::Error::invalid_value(
652                                Unexpected::Unsigned(e.invalid_char().into()),
653                                &"a valid hex character",
654                            ),
655                        },
656                        OddLengthString(ref e) =>
657                            de::Error::invalid_length(e.length(), &"an even length string"),
658                    })?;
659                    ret.push(vec);
660                }
661                Ok(Witness::from_slice(&ret))
662            }
663        }
664
665        if deserializer.is_human_readable() {
666            deserializer.deserialize_seq(Visitor)
667        } else {
668            let vec: Vec<Vec<u8>> = serde::Deserialize::deserialize(deserializer)?;
669            Ok(Witness::from_slice(&vec))
670        }
671    }
672}
673
674impl From<Vec<Vec<u8>>> for Witness {
675    fn from(vec: Vec<Vec<u8>>) -> Self { Witness::from_slice(&vec) }
676}
677
678impl From<&[&[u8]]> for Witness {
679    fn from(slice: &[&[u8]]) -> Self { Witness::from_slice(slice) }
680}
681
682impl From<&[Vec<u8>]> for Witness {
683    fn from(slice: &[Vec<u8>]) -> Self { Witness::from_slice(slice) }
684}
685
686impl From<Vec<&[u8]>> for Witness {
687    fn from(vec: Vec<&[u8]>) -> Self { Witness::from_slice(&vec) }
688}
689
690impl Default for Witness {
691    fn default() -> Self { Self::new() }
692}
693
694#[cfg(test)]
695mod test {
696    use hex::test_hex_unwrap as hex;
697
698    use super::*;
699    use crate::consensus::{deserialize, serialize};
700    use crate::sighash::EcdsaSighashType;
701    use crate::Transaction;
702
703    fn append_u32_vec(mut v: Vec<u8>, n: &[u32]) -> Vec<u8> {
704        for &num in n {
705            v.extend_from_slice(&num.to_ne_bytes());
706        }
707        v
708    }
709
710    #[test]
711    fn witness_debug_can_display_empty_instruction() {
712        let witness = Witness {
713            witness_elements: 1,
714            content: append_u32_vec(vec![], &[0]),
715            indices_start: 2,
716        };
717        println!("{:?}", witness);
718    }
719
720    #[test]
721    fn test_push() {
722        let mut witness = Witness::default();
723        assert_eq!(witness.last(), None);
724        assert_eq!(witness.second_to_last(), None);
725        assert_eq!(witness.nth(0), None);
726        assert_eq!(witness.nth(1), None);
727        assert_eq!(witness.nth(2), None);
728        assert_eq!(witness.nth(3), None);
729        witness.push(&vec![0u8]);
730        let expected = Witness {
731            witness_elements: 1,
732            content: append_u32_vec(vec![1u8, 0], &[0]),
733            indices_start: 2,
734        };
735        assert_eq!(witness, expected);
736        assert_eq!(witness.last(), Some(&[0u8][..]));
737        assert_eq!(witness.second_to_last(), None);
738        assert_eq!(witness.nth(0), Some(&[0u8][..]));
739        assert_eq!(witness.nth(1), None);
740        assert_eq!(witness.nth(2), None);
741        assert_eq!(witness.nth(3), None);
742        assert_eq!(&witness[0], &[0u8][..]);
743        witness.push(&vec![2u8, 3u8]);
744        let expected = Witness {
745            witness_elements: 2,
746            content: append_u32_vec(vec![1u8, 0, 2, 2, 3], &[0, 2]),
747            indices_start: 5,
748        };
749        assert_eq!(witness, expected);
750        assert_eq!(witness.last(), Some(&[2u8, 3u8][..]));
751        assert_eq!(witness.second_to_last(), Some(&[0u8][..]));
752        assert_eq!(witness.nth(0), Some(&[0u8][..]));
753        assert_eq!(witness.nth(1), Some(&[2u8, 3u8][..]));
754        assert_eq!(witness.nth(2), None);
755        assert_eq!(witness.nth(3), None);
756        assert_eq!(&witness[0], &[0u8][..]);
757        assert_eq!(&witness[1], &[2u8, 3u8][..]);
758        witness.push(&vec![4u8, 5u8]);
759        let expected = Witness {
760            witness_elements: 3,
761            content: append_u32_vec(vec![1u8, 0, 2, 2, 3, 2, 4, 5], &[0, 2, 5]),
762            indices_start: 8,
763        };
764        assert_eq!(witness, expected);
765        assert_eq!(witness.last(), Some(&[4u8, 5u8][..]));
766        assert_eq!(witness.second_to_last(), Some(&[2u8, 3u8][..]));
767        assert_eq!(witness.nth(0), Some(&[0u8][..]));
768        assert_eq!(witness.nth(1), Some(&[2u8, 3u8][..]));
769        assert_eq!(witness.nth(2), Some(&[4u8, 5u8][..]));
770        assert_eq!(witness.nth(3), None);
771        assert_eq!(&witness[0], &[0u8][..]);
772        assert_eq!(&witness[1], &[2u8, 3u8][..]);
773        assert_eq!(&witness[2], &[4u8, 5u8][..]);
774    }
775
776    #[test]
777    fn test_iter_len() {
778        let mut witness = Witness::default();
779        for i in 0..5 {
780            assert_eq!(witness.iter().len(), i);
781            witness.push(&vec![0u8]);
782        }
783        let mut iter = witness.iter();
784        for i in (0..=5).rev() {
785            assert_eq!(iter.len(), i);
786            iter.next();
787        }
788    }
789
790    #[test]
791    fn test_push_ecdsa_sig() {
792        // The very first signature in block 734,958
793        let sig_bytes =
794            hex!("304402207c800d698f4b0298c5aac830b822f011bb02df41eb114ade9a6702f364d5e39c0220366900d2a60cab903e77ef7dd415d46509b1f78ac78906e3296f495aa1b1b541");
795        let signature = secp256k1::ecdsa::Signature::from_der(&sig_bytes).unwrap();
796        let mut witness = Witness::default();
797        let signature = crate::ecdsa::Signature { signature, sighash_type: EcdsaSighashType::All };
798        witness.push_ecdsa_signature(&signature);
799        let expected_witness = vec![hex!(
800            "304402207c800d698f4b0298c5aac830b822f011bb02df41eb114ade9a6702f364d5e39c0220366900d2a60cab903e77ef7dd415d46509b1f78ac78906e3296f495aa1b1b54101")
801            ];
802        assert_eq!(witness.to_vec(), expected_witness);
803    }
804
805    #[test]
806    fn test_witness() {
807        let w0 = hex!("03d2e15674941bad4a996372cb87e1856d3652606d98562fe39c5e9e7e413f2105");
808        let w1 = hex!("000000");
809        let witness_vec = vec![w0.clone(), w1.clone()];
810        let witness_serialized: Vec<u8> = serialize(&witness_vec);
811        let witness = Witness {
812            content: append_u32_vec(witness_serialized[1..].to_vec(), &[0, 34]),
813            witness_elements: 2,
814            indices_start: 38,
815        };
816        for (i, el) in witness.iter().enumerate() {
817            assert_eq!(witness_vec[i], el);
818        }
819        assert_eq!(witness.last(), Some(&w1[..]));
820        assert_eq!(witness.second_to_last(), Some(&w0[..]));
821        assert_eq!(witness.nth(0), Some(&w0[..]));
822        assert_eq!(witness.nth(1), Some(&w1[..]));
823        assert_eq!(witness.nth(2), None);
824        assert_eq!(&witness[0], &w0[..]);
825        assert_eq!(&witness[1], &w1[..]);
826
827        let w_into = Witness::from_slice(&witness_vec);
828        assert_eq!(w_into, witness);
829
830        assert_eq!(witness_serialized, serialize(&witness));
831    }
832
833    #[test]
834    fn test_get_tapscript() {
835        let tapscript = hex!("deadbeef");
836        let control_block = hex!("02");
837        // annex starting with 0x50 causes the branching logic.
838        let annex = hex!("50");
839
840        let witness_vec = vec![tapscript.clone(), control_block.clone()];
841        let witness_vec_annex = vec![tapscript.clone(), control_block, annex];
842
843        let witness_serialized: Vec<u8> = serialize(&witness_vec);
844        let witness_serialized_annex: Vec<u8> = serialize(&witness_vec_annex);
845
846        let witness = deserialize::<Witness>(&witness_serialized[..]).unwrap();
847        let witness_annex = deserialize::<Witness>(&witness_serialized_annex[..]).unwrap();
848
849        // With or without annex, the tapscript should be returned.
850        assert_eq!(witness.tapscript(), Some(Script::from_bytes(&tapscript[..])));
851        assert_eq!(witness_annex.tapscript(), Some(Script::from_bytes(&tapscript[..])));
852    }
853
854    #[test]
855    fn test_get_tapscript_from_keypath() {
856        let signature = hex!("deadbeef");
857        // annex starting with 0x50 causes the branching logic.
858        let annex = hex!("50");
859
860        let witness_vec = vec![signature.clone()];
861        let witness_vec_annex = vec![signature.clone(), annex];
862
863        let witness_serialized: Vec<u8> = serialize(&witness_vec);
864        let witness_serialized_annex: Vec<u8> = serialize(&witness_vec_annex);
865
866        let witness = deserialize::<Witness>(&witness_serialized[..]).unwrap();
867        let witness_annex = deserialize::<Witness>(&witness_serialized_annex[..]).unwrap();
868
869        // With or without annex, no tapscript should be returned.
870        assert_eq!(witness.tapscript(), None);
871        assert_eq!(witness_annex.tapscript(), None);
872    }
873
874    #[test]
875    fn get_taproot_leaf_script() {
876        let tapscript = hex!("deadbeef");
877        let control_block =
878            hex!("c0ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
879        // annex starting with 0x50 causes the branching logic.
880        let annex = hex!("50");
881
882        let witness_vec = vec![tapscript.clone(), control_block.clone()];
883        let witness_vec_annex = vec![tapscript.clone(), control_block, annex];
884
885        let witness_serialized: Vec<u8> = serialize(&witness_vec);
886        let witness_serialized_annex: Vec<u8> = serialize(&witness_vec_annex);
887
888        let witness = deserialize::<Witness>(&witness_serialized[..]).unwrap();
889        let witness_annex = deserialize::<Witness>(&witness_serialized_annex[..]).unwrap();
890
891        let expected_leaf_script =
892            LeafScript { version: LeafVersion::TapScript, script: Script::from_bytes(&tapscript) };
893
894        // With or without annex, the tapscript should be returned.
895        assert_eq!(witness.taproot_leaf_script().unwrap(), expected_leaf_script);
896        assert_eq!(witness_annex.taproot_leaf_script().unwrap(), expected_leaf_script);
897    }
898
899    #[test]
900    fn test_get_control_block() {
901        let tapscript = hex!("deadbeef");
902        let control_block = hex!("02");
903        // annex starting with 0x50 causes the branching logic.
904        let annex = hex!("50");
905        let signature = vec![0xff; 64];
906
907        let witness_vec = vec![tapscript.clone(), control_block.clone()];
908        let witness_vec_annex = vec![tapscript.clone(), control_block.clone(), annex.clone()];
909        let witness_vec_key_spend_annex = vec![signature, annex];
910
911        let witness_serialized: Vec<u8> = serialize(&witness_vec);
912        let witness_serialized_annex: Vec<u8> = serialize(&witness_vec_annex);
913        let witness_serialized_key_spend_annex: Vec<u8> = serialize(&witness_vec_key_spend_annex);
914
915        let witness = deserialize::<Witness>(&witness_serialized[..]).unwrap();
916        let witness_annex = deserialize::<Witness>(&witness_serialized_annex[..]).unwrap();
917        let witness_key_spend_annex =
918            deserialize::<Witness>(&witness_serialized_key_spend_annex[..]).unwrap();
919
920        // With or without annex, the tapscript should be returned.
921        assert_eq!(witness.taproot_control_block(), Some(&control_block[..]));
922        assert_eq!(witness_annex.taproot_control_block(), Some(&control_block[..]));
923        assert!(witness_key_spend_annex.taproot_control_block().is_none())
924    }
925
926    #[test]
927    fn test_get_annex() {
928        let tapscript = hex!("deadbeef");
929        let control_block = hex!("02");
930        // annex starting with 0x50 causes the branching logic.
931        let annex = hex!("50");
932
933        let witness_vec = vec![tapscript.clone(), control_block.clone()];
934        let witness_vec_annex = vec![tapscript.clone(), control_block.clone(), annex.clone()];
935
936        let witness_serialized: Vec<u8> = serialize(&witness_vec);
937        let witness_serialized_annex: Vec<u8> = serialize(&witness_vec_annex);
938
939        let witness = deserialize::<Witness>(&witness_serialized[..]).unwrap();
940        let witness_annex = deserialize::<Witness>(&witness_serialized_annex[..]).unwrap();
941
942        // With or without annex, the tapscript should be returned.
943        assert_eq!(witness.taproot_annex(), None);
944        assert_eq!(witness_annex.taproot_annex(), Some(&annex[..]));
945
946        // Now for keyspend
947        let signature = hex!("deadbeef");
948        // annex starting with 0x50 causes the branching logic.
949        let annex = hex!("50");
950
951        let witness_vec = vec![signature.clone()];
952        let witness_vec_annex = vec![signature.clone(), annex.clone()];
953
954        let witness_serialized: Vec<u8> = serialize(&witness_vec);
955        let witness_serialized_annex: Vec<u8> = serialize(&witness_vec_annex);
956
957        let witness = deserialize::<Witness>(&witness_serialized[..]).unwrap();
958        let witness_annex = deserialize::<Witness>(&witness_serialized_annex[..]).unwrap();
959
960        // With or without annex, the tapscript should be returned.
961        assert_eq!(witness.taproot_annex(), None);
962        assert_eq!(witness_annex.taproot_annex(), Some(&annex[..]));
963    }
964
965    #[test]
966    fn test_tx() {
967        const S: &str = "02000000000102b44f26b275b8ad7b81146ba3dbecd081f9c1ea0dc05b97516f56045cfcd3df030100000000ffffffff1cb4749ae827c0b75f3d0a31e63efc8c71b47b5e3634a4c698cd53661cab09170100000000ffffffff020b3a0500000000001976a9143ea74de92762212c96f4dd66c4d72a4deb20b75788ac630500000000000016001493a8dfd1f0b6a600ab01df52b138cda0b82bb7080248304502210084622878c94f4c356ce49c8e33a063ec90f6ee9c0208540888cfab056cd1fca9022014e8dbfdfa46d318c6887afd92dcfa54510e057565e091d64d2ee3a66488f82c0121026e181ffb98ebfe5a64c983073398ea4bcd1548e7b971b4c175346a25a1c12e950247304402203ef00489a0d549114977df2820fab02df75bebb374f5eee9e615107121658cfa02204751f2d1784f8e841bff6d3bcf2396af2f1a5537c0e4397224873fbd3bfbe9cf012102ae6aa498ce2dd204e9180e71b4fb1260fe3d1a95c8025b34e56a9adf5f278af200000000";
968        let tx_bytes = hex!(S);
969        let tx: Transaction = deserialize(&tx_bytes).unwrap();
970
971        let expected_wit = ["304502210084622878c94f4c356ce49c8e33a063ec90f6ee9c0208540888cfab056cd1fca9022014e8dbfdfa46d318c6887afd92dcfa54510e057565e091d64d2ee3a66488f82c01", "026e181ffb98ebfe5a64c983073398ea4bcd1548e7b971b4c175346a25a1c12e95"];
972        for (i, wit_el) in tx.input[0].witness.iter().enumerate() {
973            assert_eq!(expected_wit[i], wit_el.to_lower_hex_string());
974        }
975        assert_eq!(expected_wit[1], tx.input[0].witness.last().unwrap().to_lower_hex_string());
976        assert_eq!(
977            expected_wit[0],
978            tx.input[0].witness.second_to_last().unwrap().to_lower_hex_string()
979        );
980        assert_eq!(expected_wit[0], tx.input[0].witness.nth(0).unwrap().to_lower_hex_string());
981        assert_eq!(expected_wit[1], tx.input[0].witness.nth(1).unwrap().to_lower_hex_string());
982        assert_eq!(None, tx.input[0].witness.nth(2));
983        assert_eq!(expected_wit[0], tx.input[0].witness[0].to_lower_hex_string());
984        assert_eq!(expected_wit[1], tx.input[0].witness[1].to_lower_hex_string());
985
986        let tx_bytes_back = serialize(&tx);
987        assert_eq!(tx_bytes_back, tx_bytes);
988    }
989
990    #[test]
991    fn fuzz_cases() {
992        let bytes = hex!("26ff0000000000c94ce592cf7a4cbb68eb00ce374300000057cd0000000000000026");
993        assert!(deserialize::<Witness>(&bytes).is_err()); // OversizedVectorAllocation
994
995        let bytes = hex!("24000000ffffffffffffffffffffffff");
996        assert!(deserialize::<Witness>(&bytes).is_err()); // OversizedVectorAllocation
997    }
998
999    #[cfg(feature = "serde")]
1000    #[test]
1001    fn test_serde_bincode() {
1002        use bincode;
1003
1004        let old_witness_format = vec![vec![0u8], vec![2]];
1005        let new_witness_format = Witness::from_slice(&old_witness_format);
1006
1007        let old = bincode::serialize(&old_witness_format).unwrap();
1008        let new = bincode::serialize(&new_witness_format).unwrap();
1009
1010        assert_eq!(old, new);
1011
1012        let back: Witness = bincode::deserialize(&new).unwrap();
1013        assert_eq!(new_witness_format, back);
1014    }
1015
1016    #[cfg(feature = "serde")]
1017    #[test]
1018    fn test_serde_human() {
1019        use serde_json;
1020
1021        let witness = Witness::from_slice(&[vec![0u8, 123, 75], vec![2u8, 6, 3, 7, 8]]);
1022
1023        let json = serde_json::to_string(&witness).unwrap();
1024
1025        assert_eq!(json, r#"["007b4b","0206030708"]"#);
1026
1027        let back: Witness = serde_json::from_str(&json).unwrap();
1028        assert_eq!(witness, back);
1029    }
1030}
1031
1032#[cfg(bench)]
1033mod benches {
1034    use test::{black_box, Bencher};
1035
1036    use super::Witness;
1037
1038    #[bench]
1039    pub fn bench_big_witness_to_vec(bh: &mut Bencher) {
1040        let raw_witness = [[1u8]; 5];
1041        let witness = Witness::from_slice(&raw_witness);
1042
1043        bh.iter(|| {
1044            black_box(witness.to_vec());
1045        });
1046    }
1047
1048    #[bench]
1049    pub fn bench_witness_to_vec(bh: &mut Bencher) {
1050        let raw_witness = vec![vec![1u8]; 3];
1051        let witness = Witness::from_slice(&raw_witness);
1052
1053        bh.iter(|| {
1054            black_box(witness.to_vec());
1055        });
1056    }
1057}