psbt/
coders.rs

1// Modern, minimalistic & standard-compliant cold wallet library.
2//
3// SPDX-License-Identifier: Apache-2.0
4//
5// Written in 2020-2024 by
6//     Dr Maxim Orlovsky <orlovsky@lnp-bp.org>
7//
8// Copyright (C) 2020-2024 LNP/BP Standards Association. All rights reserved.
9// Copyright (C) 2020-2024 Dr Maxim Orlovsky. All rights reserved.
10//
11// Licensed under the Apache License, Version 2.0 (the "License");
12// you may not use this file except in compliance with the License.
13// You may obtain a copy of the License at
14//
15//     http://www.apache.org/licenses/LICENSE-2.0
16//
17// Unless required by applicable law or agreed to in writing, software
18// distributed under the License is distributed on an "AS IS" BASIS,
19// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20// See the License for the specific language governing permissions and
21// limitations under the License.
22
23use std::io::{self, Cursor, Read, Write};
24use std::string::FromUtf8Error;
25
26use amplify::num::u7;
27use amplify::{confinement, Array, Bytes, Bytes32, Bytes4, IoError, Wrapper};
28use derive::{
29    Bip340Sig, ByteStr, CompressedPk, ConsensusDataError, ConsensusDecode, ConsensusDecodeError,
30    ConsensusEncode, ControlBlock, DerivationPath, Idx, InternalPk, InvalidLeafVer, InvalidTree,
31    KeyOrigin, LeafInfo, LeafScript, LeafVer, LegacyPk, LegacySig, LockHeight, LockTime,
32    LockTimestamp, NonStandardValue, Outpoint, RedeemScript, Sats, ScriptBytes, ScriptPubkey,
33    SeqNo, SigError, SigScript, SighashType, TapDerivation, TapLeafHash, TapNodeHash, TapTree, Tx,
34    TxOut, TxVer, Txid, UncompressedPk, VarInt, VarIntArray, Vout, Witness, WitnessScript, XOnlyPk,
35    XkeyDecodeError, XkeyOrigin, Xpub, XpubFp,
36};
37
38use crate::keys::KeyValue;
39use crate::{
40    GlobalKey, InputKey, KeyData, KeyMap, KeyPair, KeyType, Map, MapName, ModifiableFlags,
41    OutputKey, PropKey, Psbt, PsbtUnsupportedVer, PsbtVer, UnsignedTx, UnsignedTxIn, ValueData,
42};
43
44#[derive(Clone, PartialEq, Eq, Debug, Display, Error, From)]
45#[display(inner)]
46pub enum DecodeError {
47    #[from]
48    #[from(io::Error)]
49    Io(IoError),
50
51    #[from]
52    #[from(SigError)]
53    #[from(ConsensusDataError)]
54    #[from(PsbtUnsupportedVer)]
55    #[from(XkeyDecodeError)]
56    #[from(InvalidTree)]
57    #[from(InvalidLeafVer)]
58    #[from(NonStandardValue<u8>)]
59    #[from(confinement::Error)]
60    Psbt(PsbtError),
61}
62
63impl From<ConsensusDecodeError> for DecodeError {
64    fn from(e: ConsensusDecodeError) -> Self {
65        match e {
66            ConsensusDecodeError::Io(e) => DecodeError::Io(e),
67            ConsensusDecodeError::Data(data) => data.into(),
68        }
69    }
70}
71
72/// TODO #44: Split PsbtError into a specific error types
73#[derive(Clone, PartialEq, Eq, Debug, Display, Error, From)]
74#[display(doc_comments)]
75pub enum PsbtError {
76    /// unexpected end of data.
77    UnexpectedEod,
78
79    /// PSBT data are followed by some excessive bytes.
80    DataNotConsumed,
81
82    /// invalid magic bytes {0}.
83    InvalidMagic(Bytes<5>),
84
85    /// {0} key {1:#02x} must not be present in PSBT {2}.
86    UnexpectedKey(MapName, u8, PsbtVer),
87
88    /// {0} key {1:#02x} is deprecated not be present in PSBT {2}.
89    DeprecatedKey(MapName, u8, PsbtVer),
90
91    /// {0} key {1:#02x} required for PSBT {2} is not present.
92    RequiredKeyAbsent(MapName, u8, PsbtVer),
93
94    /// repeated {0} key {1:#02x}.
95    RepeatedKey(MapName, u8),
96
97    /// repeated proprietary {0} key {1}.
98    RepeatedPropKey(MapName, PropKey),
99
100    /// repeated unknown {0} key {1:#02x}.
101    RepeatedUnknownKey(MapName, u8),
102
103    /// {0} key {1:#02x} must not contain additional key data.
104    NonEmptyKeyData(MapName, u8, KeyData),
105
106    #[from]
107    #[display(inner)]
108    UnsupportedVersion(PsbtUnsupportedVer),
109
110    /// Provided transaction in `PSBT_GLOBAL_UNSIGNED_TX` contains non-empty `sigScript`.
111    SignedTx,
112
113    /// invalid lock height value {0}.
114    InvalidLockHeight(u32),
115
116    /// invalid lock timestamp {0}.
117    InvalidLockTimestamp(u32),
118
119    /// invalid compressed pubkey data.
120    InvalidComprPubkey(Bytes<33>),
121
122    /// invalid compressed pubkey data.
123    InvalidUncomprPubkey(Bytes<65>),
124
125    /// invalid BIP340 (x-only) pubkey data.
126    InvalidXonlyPubkey(Bytes<32>),
127
128    #[from]
129    #[display(inner)]
130    InvalidSig(SigError),
131
132    #[from]
133    #[display(inner)]
134    InvalidSighash(NonStandardValue<u8>),
135
136    #[from]
137    #[display(inner)]
138    InvalidXub(XkeyDecodeError),
139
140    /// one of xpubs has an unhardened derivation index
141    XpubUnhardenedOrigin,
142
143    /// derivation path has invalid length
144    InvalidDerivationPath,
145
146    /// unrecognized public key encoding starting with flag {0:#04x}.
147    UnrecognizedKeyFormat(u8),
148
149    /// proof of reserves is not a valid UTF-8 string. {0}.
150    InvalidPorString(FromUtf8Error),
151
152    /// tap tree has invalid depth {0} exceeding 128 consensus restriction.
153    InvalidTapLeafDepth(u8),
154
155    /// tap tree has script which is tool arge ({0} bytes) and exceeds consensus script limits.
156    InvalidTapLeafScriptSize(usize),
157
158    #[from]
159    #[display(inner)]
160    InvalidTapLeafVer(InvalidLeafVer),
161
162    #[from]
163    #[display(inner)]
164    InvalidTapTree(InvalidTree),
165
166    #[from]
167    #[display(inner)]
168    Consensus(ConsensusDataError),
169
170    #[from]
171    #[display(inner)]
172    Confinement(confinement::Error),
173}
174
175impl From<DecodeError> for PsbtError {
176    fn from(err: DecodeError) -> Self {
177        match err {
178            DecodeError::Psbt(e) => e,
179            DecodeError::Io(_) => PsbtError::UnexpectedEod,
180        }
181    }
182}
183
184pub trait Encode {
185    fn encode(&self, writer: &mut dyn Write) -> Result<usize, IoError>;
186}
187
188impl<T: Encode> Encode for &'_ T {
189    fn encode(&self, writer: &mut dyn Write) -> Result<usize, IoError> { (*self).encode(writer) }
190}
191
192pub trait Decode
193where Self: Sized
194{
195    fn decode(reader: &mut impl Read) -> Result<Self, DecodeError>;
196    fn deserialize(bytes: impl AsRef<[u8]>) -> Result<Self, PsbtError> {
197        let bytes = bytes.as_ref();
198        let mut cursor = Cursor::new(bytes);
199        let me = Self::decode(&mut cursor)?;
200        if cursor.position() != bytes.len() as u64 {
201            return Err(PsbtError::DataNotConsumed);
202        }
203        Ok(me)
204    }
205}
206
207impl Psbt {
208    const MAGIC: [u8; 5] = *b"psbt\xFF";
209
210    pub fn encode(&self, ver: PsbtVer, writer: &mut dyn Write) -> Result<usize, IoError> {
211        let mut counter = Self::MAGIC.len();
212        writer.write_all(&Self::MAGIC)?;
213
214        counter += self.encode_map(ver, writer)?;
215
216        for input in &self.inputs {
217            counter += input.encode_map(ver, writer)?;
218        }
219
220        for output in &self.outputs {
221            counter += output.encode_map(ver, writer)?;
222        }
223
224        Ok(counter)
225    }
226
227    pub fn encode_vec(&self, ver: PsbtVer, writer: &mut Vec<u8>) -> usize {
228        self.encode(ver, writer).expect("in-memory encoding can't error")
229    }
230
231    pub fn serialize(&self, ver: PsbtVer) -> Vec<u8> {
232        let mut vec = Vec::new();
233        self.encode_vec(ver, &mut vec);
234        vec
235    }
236
237    pub fn decode(reader: &mut impl Read) -> Result<Self, DecodeError> {
238        let mut magic = Self::MAGIC;
239        reader.read_exact(&mut magic)?;
240        if magic != Self::MAGIC {
241            return Err(PsbtError::InvalidMagic(magic.into()).into());
242        }
243
244        let map = Map::<GlobalKey>::parse(MapName::Global, reader)?;
245        let version = map
246            .singular
247            .get(&GlobalKey::Version)
248            .map(PsbtVer::deserialize)
249            .transpose()?
250            .unwrap_or(PsbtVer::V0);
251        let mut psbt = Psbt::create(PsbtVer::V0);
252        psbt.parse_map(version, map)?;
253
254        for input in &mut psbt.inputs {
255            let map = Map::<InputKey>::parse(MapName::Input, reader)?;
256            input.parse_map(version, map)?;
257        }
258
259        for output in &mut psbt.outputs {
260            let map = Map::<OutputKey>::parse(MapName::Output, reader)?;
261            output.parse_map(version, map)?;
262        }
263
264        Ok(psbt)
265    }
266
267    pub fn deserialize(data: impl AsRef<[u8]>) -> Result<Self, PsbtError> {
268        let data = data.as_ref();
269        let mut cursor = Cursor::new(data);
270        let psbt = Psbt::decode(&mut cursor)?;
271        if cursor.position() != data.len() as u64 {
272            return Err(PsbtError::DataNotConsumed);
273        }
274        Ok(psbt)
275    }
276}
277
278impl<T: KeyType, K: Encode, V: Encode> Encode for KeyPair<T, K, V> {
279    fn encode(&self, writer: &mut dyn Write) -> Result<usize, IoError> {
280        let mut counter = 0;
281
282        let key_len = {
283            let mut sink = io::Sink::default();
284            self.key_data.encode(&mut sink).expect("sink write doesn't fail")
285        } + 1;
286        counter += VarInt::with(key_len).encode(writer)?;
287        counter += self.key_type.into_u8().encode(writer)?;
288        counter += self.key_data.encode(writer)?;
289
290        let value_len = {
291            let mut sink = io::Sink::default();
292            self.value_data.encode(&mut sink).expect("sink write doesn't fail")
293        };
294        counter += VarInt::with(value_len).encode(writer)?;
295        counter += self.value_data.encode(writer)?;
296
297        Ok(counter)
298    }
299}
300
301impl<T: KeyType> Decode for KeyValue<T> {
302    fn decode(reader: &mut impl Read) -> Result<Self, DecodeError> {
303        let key_len = VarInt::decode(reader)?;
304        if key_len == 0u64 {
305            return Ok(KeyValue::Separator);
306        }
307
308        let key_type = T::from_u8(u8::decode(reader)?);
309        let mut key_data = vec![0u8; key_len.to_usize() - 1];
310        reader.read_exact(key_data.as_mut_slice())?;
311
312        let value_len = VarInt::decode(reader)?;
313        let mut value_data = vec![0u8; value_len.to_usize()];
314        reader.read_exact(value_data.as_mut_slice())?;
315
316        Ok(KeyValue::Pair(KeyPair {
317            key_type,
318            key_data: KeyData::from(key_data),
319            value_data: ValueData::from(value_data),
320        }))
321    }
322}
323
324impl Encode for PropKey {
325    fn encode(&self, writer: &mut dyn Write) -> Result<usize, IoError> {
326        let mut counter = self.identifier.len();
327        let len = VarInt::with(counter);
328        counter += len.encode(writer)?;
329
330        writer.write_all(self.identifier.as_bytes())?;
331        counter += VarInt::new(self.subtype).encode(writer)?;
332        counter += self.data.len();
333        writer.write_all(&self.data)?;
334
335        Ok(counter)
336    }
337}
338
339impl Decode for PropKey {
340    fn decode(reader: &mut impl Read) -> Result<Self, DecodeError> {
341        let len = VarInt::decode(reader)?;
342        let mut identifier = vec![0u8; len.to_usize()];
343        reader.read_exact(&mut identifier)?;
344        let identifier = String::from_utf8_lossy(&identifier).to_string();
345
346        let subtype = VarInt::decode(reader)?.to_u64();
347
348        let mut data = Vec::<u8>::new();
349        reader.read_to_end(&mut data)?;
350
351        Ok(PropKey {
352            identifier,
353            subtype,
354            data: data.into(),
355        })
356    }
357}
358
359impl Encode for ModifiableFlags {
360    fn encode(&self, writer: &mut dyn Write) -> Result<usize, IoError> {
361        self.to_standard_u8().encode(writer)
362    }
363}
364
365impl Decode for ModifiableFlags {
366    fn decode(reader: &mut impl Read) -> Result<Self, DecodeError> {
367        let val = u8::decode(reader)?;
368        Ok(Self::from_standard_u8(val))
369    }
370}
371
372impl Encode for PsbtVer {
373    fn encode(&self, writer: &mut dyn Write) -> Result<usize, IoError> {
374        self.to_standard_u32().encode(writer)
375    }
376}
377
378impl Decode for PsbtVer {
379    fn decode(reader: &mut impl Read) -> Result<Self, DecodeError> {
380        let ver = u32::decode(reader)?;
381        PsbtVer::try_from_standard_u32(ver).map_err(DecodeError::from)
382    }
383}
384
385impl Encode for Xpub {
386    fn encode(&self, writer: &mut dyn Write) -> Result<usize, IoError> {
387        writer.write_all(&self.encode())?;
388        Ok(78)
389    }
390}
391
392impl Decode for Xpub {
393    fn decode(reader: &mut impl Read) -> Result<Self, DecodeError> {
394        let mut buf = [0u8; 78];
395        reader.read_exact(&mut buf)?;
396        Xpub::decode(buf).map_err(DecodeError::from)
397    }
398}
399
400impl Encode for XpubFp {
401    fn encode(&self, writer: &mut dyn Write) -> Result<usize, IoError> {
402        self.into_inner().encode(writer)
403    }
404}
405
406impl Decode for XpubFp {
407    fn decode(reader: &mut impl Read) -> Result<Self, DecodeError> {
408        Bytes4::decode(reader).map(Self::from_inner)
409    }
410}
411
412impl Encode for XkeyOrigin {
413    fn encode(&self, writer: &mut dyn Write) -> Result<usize, IoError> {
414        Ok(self.master_fp().encode(writer)? + self.as_derivation().encode(writer)?)
415    }
416}
417
418impl Decode for XkeyOrigin {
419    fn decode(reader: &mut impl Read) -> Result<Self, DecodeError> {
420        let master_fp = XpubFp::decode(reader)?;
421        let derivation = DerivationPath::decode(reader)?;
422        Ok(XkeyOrigin::new(master_fp, derivation))
423    }
424}
425
426impl<I: Idx> Encode for DerivationPath<I> {
427    fn encode(&self, writer: &mut dyn Write) -> Result<usize, IoError> {
428        let mut counter = 0;
429        for index in self {
430            counter += index.index().encode(writer)?;
431        }
432        Ok(counter)
433    }
434}
435
436impl<I: Idx> Decode for DerivationPath<I> {
437    fn decode(reader: &mut impl Read) -> Result<Self, DecodeError> {
438        let mut derivation = DerivationPath::<I>::new();
439        let mut buf = Vec::new();
440        reader.read_to_end(&mut buf)?;
441        let mut iter = buf.chunks_exact(4);
442        for val in iter.by_ref() {
443            let index = u32::decode(&mut Cursor::new(val)).expect("fixed size");
444            derivation.push(I::try_from_index(index).map_err(|_| PsbtError::XpubUnhardenedOrigin)?);
445        }
446        if !iter.remainder().is_empty() {
447            return Err(PsbtError::InvalidDerivationPath.into());
448        }
449        Ok(derivation)
450    }
451}
452
453impl Encode for CompressedPk {
454    fn encode(&self, writer: &mut dyn Write) -> Result<usize, IoError> {
455        writer.write_all(&self.to_byte_array())?;
456        Ok(33)
457    }
458}
459
460impl Decode for CompressedPk {
461    fn decode(reader: &mut impl Read) -> Result<Self, DecodeError> {
462        let mut buf = [0u8; 33];
463        reader.read_exact(&mut buf)?;
464        CompressedPk::from_byte_array(buf)
465            .map_err(|_| PsbtError::InvalidComprPubkey(buf.into()).into())
466    }
467}
468
469impl Encode for UncompressedPk {
470    fn encode(&self, writer: &mut dyn Write) -> Result<usize, IoError> {
471        writer.write_all(&self.to_byte_array())?;
472        Ok(65)
473    }
474}
475
476impl Decode for UncompressedPk {
477    fn decode(reader: &mut impl Read) -> Result<Self, DecodeError> {
478        let mut buf = [0u8; 65];
479        reader.read_exact(&mut buf)?;
480        UncompressedPk::from_byte_array(buf)
481            .map_err(|_| PsbtError::InvalidUncomprPubkey(buf.into()).into())
482    }
483}
484
485impl Encode for LegacyPk {
486    fn encode(&self, writer: &mut dyn Write) -> Result<usize, IoError> {
487        if self.compressed {
488            CompressedPk::from(self.pubkey).encode(writer)
489        } else {
490            UncompressedPk::from(self.pubkey).encode(writer)
491        }
492    }
493}
494
495impl Decode for LegacyPk {
496    fn decode(reader: &mut impl Read) -> Result<Self, DecodeError> {
497        let mut buf = [0u8; 65];
498        reader.read_exact(&mut buf[..33])?;
499        match buf[0] {
500            0x02 | 0x03 => CompressedPk::decode(&mut Cursor::new(&buf[..33])).map(Self::from),
501            0x04 => {
502                reader.read_exact(&mut buf[33..])?;
503                UncompressedPk::decode(&mut Cursor::new(buf)).map(Self::from)
504            }
505            other => Err(PsbtError::UnrecognizedKeyFormat(other).into()),
506        }
507    }
508}
509
510impl Encode for XOnlyPk {
511    fn encode(&self, writer: &mut dyn Write) -> Result<usize, IoError> {
512        writer.write_all(&self.to_byte_array())?;
513        Ok(32)
514    }
515}
516
517impl Decode for XOnlyPk {
518    fn decode(reader: &mut impl Read) -> Result<Self, DecodeError> {
519        let mut buf = [0u8; 32];
520        reader.read_exact(&mut buf)?;
521        XOnlyPk::from_byte_array(buf).map_err(|_| PsbtError::InvalidXonlyPubkey(buf.into()).into())
522    }
523}
524
525impl Encode for InternalPk {
526    fn encode(&self, writer: &mut dyn Write) -> Result<usize, IoError> {
527        writer.write_all(&self.to_byte_array())?;
528        Ok(32)
529    }
530}
531
532impl Decode for InternalPk {
533    fn decode(reader: &mut impl Read) -> Result<Self, DecodeError> {
534        let mut buf = [0u8; 32];
535        reader.read_exact(&mut buf)?;
536        InternalPk::from_byte_array(buf)
537            .map_err(|_| PsbtError::InvalidXonlyPubkey(buf.into()).into())
538    }
539}
540
541impl Encode for KeyOrigin {
542    fn encode(&self, writer: &mut dyn Write) -> Result<usize, IoError> {
543        Ok(self.master_fp().encode(writer)? + self.derivation().encode(writer)?)
544    }
545}
546
547impl Decode for KeyOrigin {
548    fn decode(reader: &mut impl Read) -> Result<Self, DecodeError> {
549        let master_fp = XpubFp::decode(reader)?;
550        let derivation = DerivationPath::decode(reader)?;
551        Ok(KeyOrigin::new(master_fp, derivation))
552    }
553}
554
555impl Encode for LegacySig {
556    fn encode(&self, writer: &mut dyn Write) -> Result<usize, IoError> {
557        let sig = self.sig.serialize_der();
558        writer.write_all(sig.as_ref())?;
559        self.sighash_type.to_consensus_u8().encode(writer)?;
560        Ok(sig.len() + 1)
561    }
562}
563
564impl Decode for LegacySig {
565    fn decode(reader: &mut impl Read) -> Result<Self, DecodeError> {
566        let mut buf = Vec::with_capacity(78);
567        reader.read_to_end(&mut buf)?;
568        LegacySig::from_bytes(&buf).map_err(DecodeError::from)
569    }
570}
571
572impl Encode for Bip340Sig {
573    fn encode(&self, writer: &mut dyn Write) -> Result<usize, IoError> {
574        let mut counter = 64;
575        writer.write_all(&self.sig[..])?;
576        if let Some(sighash_type) = self.sighash_type {
577            counter += sighash_type.to_consensus_u8().encode(writer)?;
578        }
579        Ok(counter)
580    }
581}
582
583impl Decode for Bip340Sig {
584    fn decode(reader: &mut impl Read) -> Result<Self, DecodeError> {
585        let mut buf = Vec::with_capacity(65);
586        reader.read_to_end(&mut buf)?;
587        Bip340Sig::from_bytes(&buf).map_err(DecodeError::from)
588    }
589}
590
591impl Encode for SighashType {
592    fn encode(&self, writer: &mut dyn Write) -> Result<usize, IoError> {
593        self.to_consensus_u32().encode(writer)
594    }
595}
596
597impl Decode for SighashType {
598    fn decode(reader: &mut impl Read) -> Result<Self, DecodeError> {
599        u32::decode(reader).map(Self::from_consensus_u32)
600    }
601}
602
603impl Encode for UnsignedTx {
604    fn encode(&self, writer: &mut dyn Write) -> Result<usize, IoError> {
605        let mut counter = 0;
606        counter += self.version.encode(writer)?;
607        counter += VarInt::with(self.inputs.len()).encode(writer)?;
608        for input in &self.inputs {
609            counter += input.encode(writer)?;
610        }
611        counter += VarInt::with(self.outputs.len()).encode(writer)?;
612        for output in &self.outputs {
613            counter += output.encode(writer)?;
614        }
615        counter += self.lock_time.encode(writer)?;
616        Ok(counter)
617    }
618}
619
620impl Decode for UnsignedTx {
621    fn decode(reader: &mut impl Read) -> Result<Self, DecodeError> {
622        let version = TxVer::decode(reader)?;
623
624        let input_count = VarInt::decode(reader)?;
625        let mut inputs = Vec::with_capacity(input_count.to_usize());
626        for _ in 0..input_count.to_usize() {
627            inputs.push(UnsignedTxIn::decode(reader)?);
628        }
629
630        let output_count = VarInt::decode(reader)?;
631        let mut outputs = Vec::with_capacity(output_count.to_usize());
632        for _ in 0..output_count.to_usize() {
633            outputs.push(TxOut::decode(reader)?);
634        }
635
636        let lock_time = LockTime::decode(reader)?;
637
638        Ok(UnsignedTx {
639            version,
640            inputs: VarIntArray::try_from(inputs)?,
641            outputs: VarIntArray::try_from(outputs)?,
642            lock_time,
643        })
644    }
645}
646
647impl Encode for UnsignedTxIn {
648    fn encode(&self, writer: &mut dyn Write) -> Result<usize, IoError> {
649        let mut counter = 0;
650        counter += self.prev_output.encode(writer)?;
651        counter += VarInt::new(0).encode(writer)?;
652        counter += self.sequence.encode(writer)?;
653        Ok(counter)
654    }
655}
656
657impl Decode for UnsignedTxIn {
658    fn decode(reader: &mut impl Read) -> Result<Self, DecodeError> {
659        let prev_output = Outpoint::decode(reader)?;
660        let sig_script_len = VarInt::decode(reader)?;
661        if sig_script_len != 0u64 {
662            return Err(PsbtError::SignedTx.into());
663        }
664        let sequence = SeqNo::decode(reader)?;
665        Ok(UnsignedTxIn {
666            prev_output,
667            sequence,
668        })
669    }
670}
671
672macro_rules! psbt_code_using_consensus {
673    ($ty:ty) => {
674        psbt_encode_from_consensus!($ty);
675        psbt_decode_from_consensus!($ty);
676    };
677}
678
679struct WriteWrap<'a>(&'a mut dyn Write);
680impl Write for WriteWrap<'_> {
681    fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
682    fn flush(&mut self) -> io::Result<()> { self.0.flush() }
683}
684
685macro_rules! psbt_encode_from_consensus {
686    ($ty:ty) => {
687        impl Encode for $ty {
688            fn encode(&self, writer: &mut dyn Write) -> Result<usize, IoError> {
689                let mut wrap = WriteWrap(writer);
690                self.consensus_encode(&mut wrap)
691            }
692        }
693    };
694}
695
696macro_rules! psbt_decode_from_consensus {
697    ($ty:ty) => {
698        impl Decode for $ty {
699            fn decode(reader: &mut impl Read) -> Result<Self, DecodeError> {
700                Self::consensus_decode(reader).map_err(DecodeError::from)
701            }
702        }
703    };
704}
705
706psbt_code_using_consensus!(Tx);
707psbt_code_using_consensus!(TxVer);
708psbt_code_using_consensus!(TxOut);
709psbt_code_using_consensus!(Outpoint);
710psbt_code_using_consensus!(Txid);
711psbt_code_using_consensus!(Vout);
712psbt_code_using_consensus!(SeqNo);
713psbt_code_using_consensus!(LockTime);
714
715impl Encode for LockTimestamp {
716    fn encode(&self, writer: &mut dyn Write) -> Result<usize, IoError> {
717        self.to_consensus_u32().encode(writer)
718    }
719}
720
721impl Decode for LockTimestamp {
722    fn decode(reader: &mut impl Read) -> Result<Self, DecodeError> {
723        let val = u32::decode(reader)?;
724        Self::try_from_consensus_u32(val).map_err(|e| PsbtError::InvalidLockTimestamp(e.0).into())
725    }
726}
727
728impl Encode for LockHeight {
729    fn encode(&self, writer: &mut dyn Write) -> Result<usize, IoError> {
730        self.to_consensus_u32().encode(writer)
731    }
732}
733
734impl Decode for LockHeight {
735    fn decode(reader: &mut impl Read) -> Result<Self, DecodeError> {
736        let val = u32::decode(reader)?;
737        Self::try_from_consensus_u32(val).map_err(|e| PsbtError::InvalidLockHeight(e.0).into())
738    }
739}
740
741psbt_code_using_consensus!(Witness);
742psbt_code_using_consensus!(ControlBlock);
743
744impl Encode for ScriptBytes {
745    fn encode(&self, writer: &mut dyn Write) -> Result<usize, IoError> {
746        RawBytes(self.as_inner()).encode(writer)
747    }
748}
749
750impl Decode for ScriptBytes {
751    fn decode(reader: &mut impl Read) -> Result<Self, DecodeError> {
752        let bytes = RawBytes::<ByteStr>::decode(reader)?;
753        Ok(ScriptBytes::from_inner(bytes.0.into_inner()))
754    }
755}
756
757impl Encode for ScriptPubkey {
758    fn encode(&self, writer: &mut dyn Write) -> Result<usize, IoError> {
759        self.as_script_bytes().encode(writer)
760    }
761}
762
763impl Decode for ScriptPubkey {
764    fn decode(reader: &mut impl Read) -> Result<Self, DecodeError> {
765        ScriptBytes::decode(reader).map(Self::from_inner)
766    }
767}
768
769impl Encode for LeafScript {
770    fn encode(&self, writer: &mut dyn Write) -> Result<usize, IoError> {
771        let mut counter = self.version.to_consensus_u8().encode(writer)?;
772        counter += self.script.encode(writer)?;
773        Ok(counter)
774    }
775}
776
777impl Decode for LeafScript {
778    fn decode(reader: &mut impl Read) -> Result<Self, DecodeError> {
779        let version = LeafVer::from_consensus_u8(u8::decode(reader)?)?;
780        let script = ScriptBytes::decode(reader)?;
781        Ok(Self { version, script })
782    }
783}
784
785impl Encode for WitnessScript {
786    fn encode(&self, writer: &mut dyn Write) -> Result<usize, IoError> {
787        self.as_script_bytes().encode(writer)
788    }
789}
790
791impl Decode for WitnessScript {
792    fn decode(reader: &mut impl Read) -> Result<Self, DecodeError> {
793        ScriptBytes::decode(reader).map(Self::from_inner)
794    }
795}
796
797impl Encode for RedeemScript {
798    fn encode(&self, writer: &mut dyn Write) -> Result<usize, IoError> {
799        self.as_script_bytes().encode(writer)
800    }
801}
802
803impl Decode for RedeemScript {
804    fn decode(reader: &mut impl Read) -> Result<Self, DecodeError> {
805        ScriptBytes::decode(reader).map(Self::from_inner)
806    }
807}
808
809impl Encode for SigScript {
810    fn encode(&self, writer: &mut dyn Write) -> Result<usize, IoError> {
811        self.as_script_bytes().encode(writer)
812    }
813}
814
815impl Decode for SigScript {
816    fn decode(reader: &mut impl Read) -> Result<Self, DecodeError> {
817        ScriptBytes::decode(reader).map(Self::from_inner)
818    }
819}
820
821/// A compact size unsigned integer representing the number of leaf hashes, followed by a list
822/// of leaf hashes, followed by the 4 byte master key fingerprint concatenated with the
823/// derivation path of the public key. The derivation path is represented as 32-bit little
824/// endian unsigned integer indexes concatenated with each other.
825impl Encode for TapDerivation {
826    fn encode(&self, writer: &mut dyn Write) -> Result<usize, IoError> {
827        let no = VarInt::with(self.leaf_hashes.len());
828        let mut counter = no.encode(writer)?;
829        for leaf_hash in &self.leaf_hashes {
830            counter += leaf_hash.encode(writer)?;
831        }
832        counter += self.origin.encode(writer)?;
833        Ok(counter)
834    }
835}
836
837impl Decode for TapDerivation {
838    fn decode(reader: &mut impl Read) -> Result<Self, DecodeError> {
839        let no = VarInt::decode(reader)?;
840        let mut leaf_hashes = Vec::with_capacity(no.to_usize());
841        for _ in 0..no.to_usize() {
842            leaf_hashes.push(TapLeafHash::decode(reader)?);
843        }
844        let origin = KeyOrigin::decode(reader)?;
845        Ok(Self {
846            leaf_hashes,
847            origin,
848        })
849    }
850}
851
852/// One or more tuples representing the depth, leaf version, and script for a leaf in the
853/// Taproot tree, allowing the entire tree to be reconstructed. The tuples must be in depth
854/// first search order so that the tree is correctly reconstructed. Each tuple is an 8-bit
855/// unsigned integer representing the depth in the Taproot tree for this script, an 8-bit
856/// unsigned integer representing the leaf version, the length of the script as a compact size
857/// unsigned integer, and the script itself.
858impl Encode for TapTree {
859    fn encode(&self, writer: &mut dyn Write) -> Result<usize, IoError> {
860        let mut counter = 0;
861        for leaf in self {
862            counter += leaf.depth.to_u8().encode(writer)?;
863            counter += leaf.script.version.to_consensus_u8().encode(writer)?;
864            counter += leaf.script.script.len_var_int().encode(writer)?;
865            counter += leaf.script.script.encode(writer)?;
866        }
867        Ok(counter)
868    }
869}
870
871impl Decode for TapTree {
872    fn decode(reader: &mut impl Read) -> Result<Self, DecodeError> {
873        let mut path = Vec::new();
874        loop {
875            let depth = match u8::decode(reader) {
876                Err(DecodeError::Psbt(PsbtError::UnexpectedEod)) => break,
877                Err(DecodeError::Io(io)) if io.kind() == io::ErrorKind::UnexpectedEof => break,
878                Err(err) => return Err(err),
879                Ok(depth) => {
880                    u7::try_from(depth).map_err(|_| PsbtError::InvalidTapLeafDepth(depth))?
881                }
882            };
883            let ver = LeafVer::from_consensus_u8(u8::decode(reader)?)?;
884            let len = VarInt::decode(reader)?;
885            let mut script = vec![0u8; len.to_usize()];
886            reader.read_exact(&mut script)?;
887            let len = script.len();
888            path.push(LeafInfo {
889                depth,
890                script: LeafScript::with_bytes(ver, script)
891                    .map_err(|_| PsbtError::InvalidTapLeafScriptSize(len))?,
892            });
893        }
894        TapTree::from_leaves(path).map_err(DecodeError::from)
895    }
896}
897
898impl Encode for TapLeafHash {
899    fn encode(&self, writer: &mut dyn Write) -> Result<usize, IoError> {
900        self.into_inner().encode(writer)
901    }
902}
903
904impl Decode for TapLeafHash {
905    fn decode(reader: &mut impl Read) -> Result<Self, DecodeError> {
906        Bytes32::decode(reader).map(Self::from_inner)
907    }
908}
909
910impl Encode for TapNodeHash {
911    fn encode(&self, writer: &mut dyn Write) -> Result<usize, IoError> {
912        self.into_inner().encode(writer)
913    }
914}
915
916impl Decode for TapNodeHash {
917    fn decode(reader: &mut impl Read) -> Result<Self, DecodeError> {
918        Bytes32::decode(reader).map(Self::from_inner)
919    }
920}
921
922psbt_code_using_consensus!(Sats);
923psbt_code_using_consensus!(u8);
924psbt_code_using_consensus!(u32);
925psbt_code_using_consensus!(VarInt);
926
927#[derive(From)]
928pub(crate) struct RawBytes<T: AsRef<[u8]>>(pub T);
929
930impl<T: AsRef<[u8]>> Encode for RawBytes<T> {
931    fn encode(&self, writer: &mut dyn Write) -> Result<usize, IoError> {
932        let bytes = self.0.as_ref();
933        writer.write_all(bytes)?;
934        Ok(bytes.len())
935    }
936}
937
938impl Decode for RawBytes<Vec<u8>> {
939    fn decode(reader: &mut impl Read) -> Result<Self, DecodeError> {
940        let mut buf = Vec::new();
941        reader.read_to_end(&mut buf)?;
942        Ok(Self(buf))
943    }
944}
945
946impl Decode for RawBytes<ByteStr> {
947    fn decode(reader: &mut impl Read) -> Result<Self, DecodeError> {
948        let mut buf = Vec::new();
949        reader.read_to_end(&mut buf)?;
950        Ok(ByteStr::from(buf).into())
951    }
952}
953
954impl<const LEN: usize> Encode for Array<u8, LEN> {
955    fn encode(&self, writer: &mut dyn Write) -> Result<usize, IoError> {
956        writer.write_all(self.as_inner())?;
957        Ok(LEN)
958    }
959}
960
961impl<const LEN: usize> Decode for Array<u8, LEN> {
962    fn decode(reader: &mut impl Read) -> Result<Self, DecodeError> {
963        let mut buf = [0u8; LEN];
964        reader.read_exact(&mut buf)?;
965        Ok(Self::from_inner(buf))
966    }
967}
968
969impl<T: Encode> Encode for Option<T> {
970    fn encode(&self, writer: &mut dyn Write) -> Result<usize, IoError> {
971        Ok(match self {
972            Some(data) => data.encode(writer)?,
973            None => 0,
974        })
975    }
976}
977
978impl Encode for Box<dyn Encode> {
979    fn encode(&self, writer: &mut dyn Write) -> Result<usize, IoError> {
980        self.as_ref().encode(writer)
981    }
982}
983
984impl<A: Encode, B: Encode> Encode for (A, B) {
985    fn encode(&self, writer: &mut dyn Write) -> Result<usize, IoError> {
986        Ok(self.0.encode(writer)? + self.1.encode(writer)?)
987    }
988}
989
990impl<A: Decode, B: Decode> Decode for (A, B) {
991    fn decode(reader: &mut impl Read) -> Result<Self, DecodeError> {
992        let a = A::decode(reader)?;
993        let b = B::decode(reader)?;
994        Ok((a, b))
995    }
996}
997
998impl Encode for () {
999    fn encode(&self, _writer: &mut dyn Write) -> Result<usize, IoError> { Ok(0) }
1000}
1001
1002impl Decode for () {
1003    fn decode(_reader: &mut impl Read) -> Result<Self, DecodeError> { Ok(()) }
1004}