psbt/
maps.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::collections::BTreeMap;
24use std::io::{Read, Write};
25
26use amplify::{Bytes20, Bytes32, IoError};
27use derive::{
28    Bip340Sig, ByteStr, ControlBlock, InternalPk, KeyOrigin, LeafScript, LegacyPk, LegacySig,
29    LockHeight, LockTime, LockTimestamp, RedeemScript, Sats, ScriptPubkey, SeqNo, SigScript,
30    SighashType, TapDerivation, TapLeafHash, TapNodeHash, TapTree, Tx, TxOut, TxVer, Txid, VarInt,
31    Vout, Witness, WitnessScript, XOnlyPk, XkeyOrigin, Xpub,
32};
33use indexmap::IndexMap;
34
35use crate::coders::RawBytes;
36use crate::keys::KeyValue;
37use crate::{
38    Decode, DecodeError, Encode, GlobalKey, Input, InputKey, KeyPair, KeyType, ModifiableFlags,
39    Output, OutputKey, PropKey, Psbt, PsbtError, PsbtVer, UnsignedTx,
40};
41
42pub type KeyData = ByteStr;
43
44#[derive(Wrapper, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Default, Debug, Display, From)]
45#[wrapper(Deref, Index, RangeOps, AsSlice, BorrowSlice, Hex)]
46#[display(LowerHex)]
47#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(transparent))]
48pub struct ValueData(ByteStr);
49
50impl From<Vec<u8>> for ValueData {
51    fn from(vec: Vec<u8>) -> Self { ByteStr::from(vec).into() }
52}
53
54#[derive(Clone, Eq, PartialEq, Debug, Display, Error)]
55#[display("proprietary key '{0}' is already present")]
56pub struct KeyAlreadyPresent(pub PropKey);
57
58#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug, Display)]
59#[display(lowercase)]
60pub enum MapName {
61    Global,
62    Input,
63    Output,
64}
65
66#[derive(Clone, Eq, PartialEq, Debug)]
67pub struct Map<K: KeyType> {
68    pub name: MapName,
69    pub singular: BTreeMap<K, ValueData>,
70    pub plural: BTreeMap<K, BTreeMap<KeyData, ValueData>>,
71    pub proprietary: IndexMap<PropKey, ValueData>,
72    pub unknown: IndexMap<u8, IndexMap<KeyData, ValueData>>,
73}
74
75impl<K: KeyType> Map<K> {
76    fn new(name: MapName) -> Self {
77        Map {
78            name,
79            singular: empty!(),
80            plural: empty!(),
81            proprietary: empty!(),
82            unknown: empty!(),
83        }
84    }
85
86    pub fn parse(name: MapName, stream: &mut impl Read) -> Result<Self, DecodeError> {
87        let mut map = Map::<K>::new(name);
88
89        while let KeyValue::<K>::Pair(pair) = KeyValue::<K>::decode(stream)? {
90            if map.singular.contains_key(&pair.key_type) {
91                return Err(PsbtError::RepeatedKey(name, pair.key_type.to_u8()).into());
92            }
93            if pair.key_type.is_proprietary() {
94                let prop_key = PropKey::deserialize(pair.key_data)?;
95                if map.proprietary.contains_key(&prop_key) {
96                    return Err(PsbtError::RepeatedPropKey(name, prop_key).into());
97                }
98                map.proprietary.insert(prop_key, pair.value_data);
99            } else if K::STANDARD.contains(&pair.key_type) {
100                if pair.key_type.has_key_data() {
101                    let submap = map.plural.entry(pair.key_type).or_default();
102                    if submap.insert(pair.key_data, pair.value_data).is_some() {
103                        return Err(PsbtError::RepeatedKey(name, pair.key_type.to_u8()).into());
104                    }
105                } else {
106                    if !pair.key_data.is_empty() {
107                        return Err(PsbtError::NonEmptyKeyData(
108                            name,
109                            pair.key_type.to_u8(),
110                            pair.key_data,
111                        )
112                        .into());
113                    }
114                    map.singular.insert(pair.key_type, pair.value_data);
115                }
116            } else {
117                let submap = map.unknown.entry(pair.key_type.to_u8()).or_default();
118                if submap.contains_key(&pair.key_data) {
119                    return Err(PsbtError::RepeatedUnknownKey(name, pair.key_type.to_u8()).into());
120                }
121                submap.insert(pair.key_data, pair.value_data);
122            }
123        }
124
125        Ok(map)
126    }
127
128    pub fn check(&self, version: PsbtVer) -> Result<(), PsbtError> {
129        for key_type in self.singular.keys().chain(self.plural.keys()) {
130            if version < key_type.present_since() {
131                return Err(PsbtError::UnexpectedKey(self.name, key_type.to_u8(), version));
132            }
133            if matches!(key_type.deprecated_since(), Some(depr) if version >= depr) {
134                return Err(PsbtError::DeprecatedKey(self.name, key_type.to_u8(), version));
135            }
136        }
137        for key_type in K::STANDARD {
138            if key_type.is_required()
139                && version >= key_type.present_since()
140                && matches!(key_type.deprecated_since(), Some(depr) if version < depr)
141                && ((key_type.has_key_data() && !self.plural.contains_key(key_type))
142                    || (!key_type.has_key_data() && !self.singular.contains_key(key_type)))
143            {
144                return Err(PsbtError::RequiredKeyAbsent(self.name, key_type.to_u8(), version));
145            }
146        }
147        Ok(())
148    }
149}
150
151pub trait KeyMap: Sized {
152    type Keys: KeyType;
153    const PROPRIETARY_TYPE: Self::Keys;
154
155    fn encode_map(&self, version: PsbtVer, writer: &mut dyn Write) -> Result<usize, IoError> {
156        let mut counter = 0;
157
158        for key_type in Self::Keys::STANDARD.iter().filter(|kt| kt.is_allowed(version)) {
159            let iter = unsafe {
160                // We need this hack since Rust borrower checker can't see that the
161                // reference actually doesn't escape the scope
162                #[allow(clippy::missing_transmute_annotations)]
163                ::core::mem::transmute::<
164                    _,
165                    Vec<KeyPair<Self::Keys, Box<dyn Encode + 'static>, Box<dyn Encode + 'static>>>,
166                >(self.retrieve_key_pair(version, *key_type))
167            }
168            .into_iter();
169            for pair in iter {
170                counter += pair.encode(writer)?;
171            }
172        }
173
174        for (key_type, submap) in self._unknown_map() {
175            for (key_data, value_data) in submap {
176                let pair = KeyPair::new(
177                    Self::Keys::unknown(*key_type),
178                    RawBytes(key_data),
179                    RawBytes(value_data),
180                );
181                counter += pair.encode(writer)?;
182            }
183        }
184
185        for (key_data, value_data) in self._proprietary_map() {
186            let pair = KeyPair::new(Self::PROPRIETARY_TYPE, key_data, RawBytes(value_data));
187            counter += pair.encode(writer)?;
188        }
189
190        counter += 1;
191        writer.write_all(&[0])?;
192
193        Ok(counter)
194    }
195
196    fn parse_map(&mut self, version: PsbtVer, map: Map<Self::Keys>) -> Result<(), PsbtError> {
197        map.check(version)?;
198
199        for (k, v) in map.singular {
200            self.insert_singular(k, v)?;
201        }
202        for (k, submap) in map.plural {
203            for (d, v) in submap {
204                self.insert_plural(k, d, v)?;
205            }
206        }
207        for (p, v) in map.proprietary {
208            self.insert_proprietary(p, v);
209        }
210        for (k, submap) in map.unknown {
211            for (d, v) in submap {
212                self.insert_unknown(k, d, v);
213            }
214        }
215        Ok(())
216    }
217
218    #[doc(hidden)]
219    fn _proprietary_map(&self) -> &IndexMap<PropKey, ValueData>;
220    #[doc(hidden)]
221    fn _proprietary_map_mut(&mut self) -> &mut IndexMap<PropKey, ValueData>;
222
223    fn has_proprietary(&self, key: &PropKey) -> bool { self.proprietary(key).is_some() }
224    fn proprietary(&self, key: &PropKey) -> Option<&ValueData> { self._proprietary_map().get(key) }
225    fn proprietary_mut(&mut self, key: &PropKey) -> Option<&mut ValueData> {
226        self._proprietary_map_mut().get_mut(key)
227    }
228    fn push_proprietary(
229        &mut self,
230        key: PropKey,
231        value: impl Into<ValueData>,
232    ) -> Result<bool, KeyAlreadyPresent> {
233        let value = value.into();
234        if let Some(existing) = self.proprietary(&key) {
235            if &value != existing {
236                Err(KeyAlreadyPresent(key))
237            } else {
238                Ok(false)
239            }
240        } else {
241            self._proprietary_map_mut().insert(key, value);
242            Ok(true)
243        }
244    }
245    fn remove_proprietary(&mut self, key: &PropKey) -> Option<ValueData> {
246        self._proprietary_map_mut().shift_remove(key)
247    }
248
249    #[doc(hidden)]
250    fn _unknown_map(&self) -> &IndexMap<u8, IndexMap<KeyData, ValueData>>;
251    #[doc(hidden)]
252    fn _unknown_map_mut(&mut self) -> &mut IndexMap<u8, IndexMap<KeyData, ValueData>>;
253
254    #[allow(clippy::type_complexity)]
255    fn retrieve_key_pair<'enc>(
256        &'enc self,
257        version: PsbtVer,
258        key_type: Self::Keys,
259    ) -> Vec<KeyPair<Self::Keys, Box<dyn Encode + 'enc>, Box<dyn Encode + 'enc>>>;
260
261    fn insert_singular(
262        &mut self,
263        key_type: Self::Keys,
264        value_data: ValueData,
265    ) -> Result<(), PsbtError>;
266
267    fn insert_plural(
268        &mut self,
269        key_type: Self::Keys,
270        key_data: KeyData,
271        value_data: ValueData,
272    ) -> Result<(), PsbtError>;
273
274    fn insert_proprietary(&mut self, prop_key: PropKey, value_data: ValueData) {
275        self._proprietary_map_mut().insert(prop_key, value_data);
276    }
277
278    fn insert_unknown(&mut self, key_type: u8, key_data: KeyData, value_data: ValueData) {
279        self._unknown_map_mut().entry(key_type).or_default().insert(key_data, value_data);
280    }
281}
282
283macro_rules! once {
284    ($expr:expr) => {
285        vec![KeyPair::boxed(Self::PROPRIETARY_TYPE, (), $expr)]
286    };
287}
288macro_rules! option {
289    ($expr:expr) => {
290        $expr.as_ref().map(|e| KeyPair::boxed(Self::PROPRIETARY_TYPE, (), e)).into_iter().collect()
291    };
292}
293macro_rules! option_raw {
294    ($expr:expr) => {
295        $expr
296            .as_ref()
297            .map(|e| KeyPair::boxed(Self::PROPRIETARY_TYPE, (), RawBytes(e)))
298            .into_iter()
299            .collect()
300    };
301}
302macro_rules! iter {
303    ($expr:expr) => {
304        $expr.iter().map(|(k, v)| KeyPair::boxed(Self::PROPRIETARY_TYPE, k, v)).collect()
305    };
306}
307macro_rules! iter_raw {
308    ($expr:expr) => {
309        $expr.iter().map(|(k, v)| KeyPair::boxed(Self::PROPRIETARY_TYPE, k, RawBytes(v))).collect()
310    };
311}
312
313impl KeyMap for Psbt {
314    type Keys = GlobalKey;
315    const PROPRIETARY_TYPE: Self::Keys = GlobalKey::Proprietary;
316
317    fn _proprietary_map(&self) -> &IndexMap<PropKey, ValueData> { &self.proprietary }
318    fn _unknown_map(&self) -> &IndexMap<u8, IndexMap<KeyData, ValueData>> { &self.unknown }
319    fn _proprietary_map_mut(&mut self) -> &mut IndexMap<PropKey, ValueData> {
320        &mut self.proprietary
321    }
322    fn _unknown_map_mut(&mut self) -> &mut IndexMap<u8, IndexMap<KeyData, ValueData>> {
323        &mut self.unknown
324    }
325
326    fn retrieve_key_pair<'enc>(
327        &'enc self,
328        version: PsbtVer,
329        key_type: Self::Keys,
330    ) -> Vec<KeyPair<Self::Keys, Box<dyn Encode + 'enc>, Box<dyn Encode + 'enc>>> {
331        let mut pairs = match key_type {
332            GlobalKey::UnsignedTx => once!(self.to_unsigned_tx()),
333            GlobalKey::Xpub => iter!(self.xpubs),
334            GlobalKey::TxVersion => once!(self.tx_version),
335            GlobalKey::FallbackLocktime => option!(self.fallback_locktime),
336            GlobalKey::InputCount => once!(VarInt::with(self.inputs.len())),
337            GlobalKey::OutputCount => once!(VarInt::with(self.outputs.len())),
338            GlobalKey::TxModifiable => option!(self.tx_modifiable),
339            GlobalKey::Version => once!(version),
340
341            GlobalKey::Proprietary | GlobalKey::Unknown(_) => unreachable!(),
342        };
343        pairs.iter_mut().for_each(|pair| pair.key_type = key_type);
344        pairs
345    }
346
347    fn insert_singular(
348        &mut self,
349        key_type: Self::Keys,
350        value_data: ValueData,
351    ) -> Result<(), PsbtError> {
352        match key_type {
353            GlobalKey::UnsignedTx => {
354                self.reset_from_unsigned_tx(UnsignedTx::deserialize(value_data)?)
355            }
356            GlobalKey::TxVersion => self.tx_version = TxVer::deserialize(value_data)?,
357            GlobalKey::FallbackLocktime => {
358                self.fallback_locktime = Some(LockTime::deserialize(value_data)?)
359            }
360            GlobalKey::InputCount => self.reset_inputs(VarInt::deserialize(value_data)?.to_usize()),
361            GlobalKey::OutputCount => {
362                self.reset_outputs(VarInt::deserialize(value_data)?.to_usize())
363            }
364            GlobalKey::TxModifiable => {
365                self.tx_modifiable = Some(ModifiableFlags::deserialize(value_data)?)
366            }
367            GlobalKey::Version => self.version = PsbtVer::deserialize(value_data)?,
368
369            GlobalKey::Xpub => unreachable!(),
370            GlobalKey::Proprietary | GlobalKey::Unknown(_) => unreachable!(),
371        }
372        Ok(())
373    }
374
375    fn insert_plural(
376        &mut self,
377        key_type: Self::Keys,
378        key_data: KeyData,
379        value_data: ValueData,
380    ) -> Result<(), PsbtError> {
381        match key_type {
382            GlobalKey::Xpub => {
383                let xpub = Xpub::deserialize(key_data)?;
384                let origin = XkeyOrigin::deserialize(value_data)?;
385                self.xpubs.insert(xpub, origin);
386            }
387
388            GlobalKey::UnsignedTx
389            | GlobalKey::TxVersion
390            | GlobalKey::FallbackLocktime
391            | GlobalKey::InputCount
392            | GlobalKey::OutputCount
393            | GlobalKey::TxModifiable
394            | GlobalKey::Version => unreachable!(),
395
396            GlobalKey::Proprietary | GlobalKey::Unknown(_) => unreachable!(),
397        }
398        Ok(())
399    }
400}
401
402impl KeyMap for Input {
403    type Keys = InputKey;
404    const PROPRIETARY_TYPE: Self::Keys = InputKey::Proprietary;
405
406    fn _proprietary_map(&self) -> &IndexMap<PropKey, ValueData> { &self.proprietary }
407    fn _unknown_map(&self) -> &IndexMap<u8, IndexMap<KeyData, ValueData>> { &self.unknown }
408    fn _proprietary_map_mut(&mut self) -> &mut IndexMap<PropKey, ValueData> {
409        &mut self.proprietary
410    }
411    fn _unknown_map_mut(&mut self) -> &mut IndexMap<u8, IndexMap<KeyData, ValueData>> {
412        &mut self.unknown
413    }
414
415    fn retrieve_key_pair<'enc>(
416        &'enc self,
417        _: PsbtVer,
418        key_type: Self::Keys,
419    ) -> Vec<KeyPair<Self::Keys, Box<dyn Encode + 'enc>, Box<dyn Encode + 'enc>>> {
420        let mut pairs = match key_type {
421            InputKey::NonWitnessUtxo => option!(self.non_witness_tx),
422            InputKey::WitnessUtxo => option!(self.witness_utxo),
423            InputKey::PartialSig => iter!(self.partial_sigs),
424            InputKey::SighashType => option!(self.sighash_type),
425            InputKey::RedeemScript => option!(self.redeem_script),
426            InputKey::WitnessScript => option!(self.witness_script),
427            InputKey::Bip32Derivation => iter!(self.bip32_derivation),
428            InputKey::FinalScriptSig => option!(self.final_script_sig),
429            InputKey::FinalWitness => option!(self.final_witness),
430            InputKey::PorCommitment => option_raw!(self.proof_of_reserves),
431            InputKey::Ripemd160 => iter_raw!(self.ripemd160),
432            InputKey::Sha256 => iter_raw!(self.sha256),
433            InputKey::Hash160 => iter_raw!(self.hash160),
434            InputKey::Hash256 => iter_raw!(self.hash256),
435            InputKey::PreviousTxid => once!(self.previous_outpoint.txid),
436            InputKey::OutputIndex => once!(self.previous_outpoint.vout),
437            InputKey::Sequence => option!(self.sequence_number),
438            InputKey::RequiredTimeLock => option!(self.required_time_lock),
439            InputKey::RequiredHeightLock => option!(self.required_height_lock),
440            InputKey::TapKeySig => option!(self.tap_key_sig),
441            InputKey::TapScriptSig => iter!(self.tap_script_sig),
442            InputKey::TapLeafScript => iter!(self.tap_leaf_script),
443            InputKey::TapBip32Derivation => {
444                iter!(self.tap_bip32_derivation)
445            }
446            InputKey::TapInternalKey => option!(self.tap_internal_key),
447            InputKey::TapMerkleRoot => option!(self.tap_merkle_root),
448
449            InputKey::Proprietary | InputKey::Unknown(_) => unreachable!(),
450        };
451        pairs.iter_mut().for_each(|pair| pair.key_type = key_type);
452        pairs
453    }
454
455    fn insert_singular(
456        &mut self,
457        key_type: Self::Keys,
458        value_data: ValueData,
459    ) -> Result<(), PsbtError> {
460        match key_type {
461            InputKey::NonWitnessUtxo => self.non_witness_tx = Some(Tx::deserialize(value_data)?),
462            InputKey::WitnessUtxo => self.witness_utxo = Some(TxOut::deserialize(value_data)?),
463            InputKey::SighashType => {
464                self.sighash_type = Some(SighashType::deserialize(value_data)?)
465            }
466            InputKey::RedeemScript => {
467                self.redeem_script = Some(RedeemScript::deserialize(value_data)?)
468            }
469            InputKey::WitnessScript => {
470                self.witness_script = Some(WitnessScript::deserialize(value_data)?)
471            }
472            InputKey::FinalScriptSig => {
473                self.final_script_sig = Some(SigScript::deserialize(value_data)?)
474            }
475            InputKey::FinalWitness => self.final_witness = Some(Witness::deserialize(value_data)?),
476            InputKey::PorCommitment => {
477                let bytes = RawBytes::<Vec<u8>>::deserialize(value_data)?;
478                let por = String::from_utf8(bytes.0).map_err(PsbtError::InvalidPorString)?;
479                self.proof_of_reserves = Some(por)
480            }
481
482            InputKey::PreviousTxid => self.previous_outpoint.txid = Txid::deserialize(value_data)?,
483            InputKey::OutputIndex => self.previous_outpoint.vout = Vout::deserialize(value_data)?,
484            InputKey::Sequence => self.sequence_number = Some(SeqNo::deserialize(value_data)?),
485            InputKey::RequiredTimeLock => {
486                self.required_time_lock = Some(LockTimestamp::deserialize(value_data)?)
487            }
488            InputKey::RequiredHeightLock => {
489                self.required_height_lock = Some(LockHeight::deserialize(value_data)?)
490            }
491
492            InputKey::TapKeySig => self.tap_key_sig = Some(Bip340Sig::deserialize(value_data)?),
493            InputKey::TapInternalKey => {
494                self.tap_internal_key = Some(InternalPk::deserialize(value_data)?)
495            }
496            InputKey::TapMerkleRoot => {
497                self.tap_merkle_root = Some(TapNodeHash::deserialize(value_data)?)
498            }
499
500            InputKey::PartialSig
501            | InputKey::Bip32Derivation
502            | InputKey::Ripemd160
503            | InputKey::Sha256
504            | InputKey::Hash160
505            | InputKey::Hash256
506            | InputKey::TapScriptSig
507            | InputKey::TapLeafScript
508            | InputKey::TapBip32Derivation => unreachable!(),
509
510            InputKey::Proprietary | InputKey::Unknown(_) => unreachable!(),
511        }
512        Ok(())
513    }
514
515    fn insert_plural(
516        &mut self,
517        key_type: Self::Keys,
518        key_data: KeyData,
519        value_data: ValueData,
520    ) -> Result<(), PsbtError> {
521        match key_type {
522            InputKey::NonWitnessUtxo
523            | InputKey::WitnessUtxo
524            | InputKey::SighashType
525            | InputKey::RedeemScript
526            | InputKey::WitnessScript
527            | InputKey::FinalScriptSig
528            | InputKey::FinalWitness
529            | InputKey::PorCommitment
530            | InputKey::TapKeySig
531            | InputKey::TapInternalKey
532            | InputKey::TapMerkleRoot => unreachable!(),
533
534            InputKey::PreviousTxid
535            | InputKey::OutputIndex
536            | InputKey::Sequence
537            | InputKey::RequiredTimeLock
538            | InputKey::RequiredHeightLock => unreachable!(),
539
540            InputKey::PartialSig => {
541                let pk = LegacyPk::deserialize(key_data)?;
542                let sig = LegacySig::deserialize(value_data)?;
543                self.partial_sigs.insert(pk, sig);
544            }
545            InputKey::Bip32Derivation => {
546                let pk = LegacyPk::deserialize(key_data)?;
547                let origin = KeyOrigin::deserialize(value_data)?;
548                self.bip32_derivation.insert(pk, origin);
549            }
550            InputKey::Ripemd160 => {
551                let hash = Bytes20::deserialize(key_data)?;
552                self.ripemd160.insert(hash, value_data.into());
553            }
554            InputKey::Sha256 => {
555                let hash = Bytes32::deserialize(key_data)?;
556                self.sha256.insert(hash, value_data.into());
557            }
558            InputKey::Hash160 => {
559                let hash = Bytes20::deserialize(key_data)?;
560                self.hash160.insert(hash, value_data.into());
561            }
562            InputKey::Hash256 => {
563                let hash = Bytes32::deserialize(key_data)?;
564                self.hash256.insert(hash, value_data.into());
565            }
566            InputKey::TapScriptSig => {
567                let (internal_pk, leaf_hash) = <(XOnlyPk, TapLeafHash)>::deserialize(key_data)?;
568                let sig = Bip340Sig::deserialize(value_data)?;
569                self.tap_script_sig.insert((internal_pk, leaf_hash), sig);
570            }
571            InputKey::TapLeafScript => {
572                let control_block = ControlBlock::deserialize(key_data)?;
573                let leaf_script = LeafScript::deserialize(value_data)?;
574                self.tap_leaf_script.insert(control_block, leaf_script);
575            }
576            InputKey::TapBip32Derivation => {
577                let pk = XOnlyPk::deserialize(key_data)?;
578                let derivation = TapDerivation::deserialize(value_data)?;
579                self.tap_bip32_derivation.insert(pk, derivation);
580            }
581
582            InputKey::Proprietary | InputKey::Unknown(_) => unreachable!(),
583        }
584        Ok(())
585    }
586}
587
588impl KeyMap for Output {
589    type Keys = OutputKey;
590    const PROPRIETARY_TYPE: Self::Keys = OutputKey::Proprietary;
591
592    fn _proprietary_map(&self) -> &IndexMap<PropKey, ValueData> { &self.proprietary }
593    fn _proprietary_map_mut(&mut self) -> &mut IndexMap<PropKey, ValueData> {
594        &mut self.proprietary
595    }
596
597    fn _unknown_map(&self) -> &IndexMap<u8, IndexMap<KeyData, ValueData>> { &self.unknown }
598    fn _unknown_map_mut(&mut self) -> &mut IndexMap<u8, IndexMap<KeyData, ValueData>> {
599        &mut self.unknown
600    }
601
602    fn retrieve_key_pair<'enc>(
603        &'enc self,
604        _: PsbtVer,
605        key_type: Self::Keys,
606    ) -> Vec<KeyPair<Self::Keys, Box<dyn Encode + 'enc>, Box<dyn Encode + 'enc>>> {
607        let mut pairs = match key_type {
608            OutputKey::RedeemScript => option!(self.redeem_script),
609            OutputKey::WitnessScript => option!(self.witness_script),
610            OutputKey::Bip32Derivation => iter!(self.bip32_derivation),
611            OutputKey::Amount => once!(self.amount),
612            OutputKey::Script => once!(&self.script),
613            OutputKey::TapInternalKey => option!(self.tap_internal_key),
614            OutputKey::TapTree => option!(self.tap_tree),
615            OutputKey::TapBip32Derivation => {
616                iter!(self.tap_bip32_derivation)
617            }
618
619            OutputKey::Proprietary | OutputKey::Unknown(_) => unreachable!(),
620        };
621        pairs.iter_mut().for_each(|pair| pair.key_type = key_type);
622        pairs
623    }
624
625    fn insert_singular(
626        &mut self,
627        key_type: Self::Keys,
628        value_data: ValueData,
629    ) -> Result<(), PsbtError> {
630        match key_type {
631            OutputKey::RedeemScript => {
632                self.redeem_script = Some(RedeemScript::deserialize(value_data)?)
633            }
634            OutputKey::WitnessScript => {
635                self.witness_script = Some(WitnessScript::deserialize(value_data)?)
636            }
637            OutputKey::Amount => self.amount = Sats::deserialize(value_data)?,
638            OutputKey::Script => self.script = ScriptPubkey::deserialize(value_data)?,
639            OutputKey::TapInternalKey => {
640                self.tap_internal_key = Some(InternalPk::deserialize(value_data)?)
641            }
642            OutputKey::TapTree => self.tap_tree = Some(TapTree::deserialize(value_data)?),
643
644            OutputKey::Bip32Derivation | OutputKey::TapBip32Derivation => unreachable!(),
645
646            OutputKey::Proprietary | OutputKey::Unknown(_) => unreachable!(),
647        }
648        Ok(())
649    }
650
651    fn insert_plural(
652        &mut self,
653        key_type: Self::Keys,
654        key_data: KeyData,
655        value_data: ValueData,
656    ) -> Result<(), PsbtError> {
657        match key_type {
658            OutputKey::RedeemScript
659            | OutputKey::WitnessScript
660            | OutputKey::Amount
661            | OutputKey::Script
662            | OutputKey::TapInternalKey
663            | OutputKey::TapTree => unreachable!(),
664
665            OutputKey::Bip32Derivation => {
666                let pk = LegacyPk::deserialize(key_data)?;
667                let origin = KeyOrigin::deserialize(value_data)?;
668                self.bip32_derivation.insert(pk, origin);
669            }
670            OutputKey::TapBip32Derivation => {
671                let pk = XOnlyPk::deserialize(key_data)?;
672                let derivation = TapDerivation::deserialize(value_data)?;
673                self.tap_bip32_derivation.insert(pk, derivation);
674            }
675
676            OutputKey::Proprietary | OutputKey::Unknown(_) => unreachable!(),
677        }
678        Ok(())
679    }
680}