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