sapio_ctv_emulator_trait/
emulator.rs

1// Copyright Judica, Inc 2021
2//
3// This Source Code Form is subject to the terms of the Mozilla Public
4//  License, v. 2.0. If a copy of the MPL was not distributed with this
5//  file, You can obtain one at https://mozilla.org/MPL/2.0/.
6
7//! definitions of emulator traits required to use as a trait object in low-level libraries.
8use bitcoin::hashes::sha256;
9use bitcoin::util::psbt::PartiallySignedTransaction;
10pub use sapio_base::Clause;
11use std::fmt;
12use std::sync::Arc;
13/// Errors that an emulator might throw
14#[derive(Debug)]
15pub enum EmulatorError {
16    /// Wraps an issue caused in a Network/IO context
17    /// (TODO: Prevents serialization/deserialization)
18    NetworkIssue(std::io::Error),
19    /// Error was caused by BIP32
20    BIP32Error(bitcoin::util::bip32::Error),
21}
22impl fmt::Display for EmulatorError {
23    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24        write!(f, "{:?}", self)
25    }
26}
27impl std::error::Error for EmulatorError {}
28
29impl From<std::io::Error> for EmulatorError {
30    fn from(e: std::io::Error) -> EmulatorError {
31        EmulatorError::NetworkIssue(e)
32    }
33}
34
35impl From<bitcoin::util::bip32::Error> for EmulatorError {
36    fn from(e: bitcoin::util::bip32::Error) -> EmulatorError {
37        EmulatorError::BIP32Error(e)
38    }
39}
40
41/// `CTVEmulator` trait is used to make the method in which CheckTemplateVerify
42/// is stubbed out with.
43pub trait CTVEmulator: Sync + Send {
44    /// For a given transaction hash, gets the corresponding Clause that the
45    /// Emulator would satisfy.
46    fn get_signer_for(&self, h: sha256::Hash) -> Result<Clause, EmulatorError>;
47    /// Adds the Emulators signature to the PSBT, if any.
48    fn sign(
49        &self,
50        b: PartiallySignedTransaction,
51    ) -> Result<PartiallySignedTransaction, EmulatorError>;
52}
53
54/// A wrapper for an optional internal emulator trait object. If no emulator is
55/// provided, then it defaults to using actual CheckTemplateVerify Clauses.
56pub type NullEmulator = Arc<dyn CTVEmulator>;
57
58/// a type tag that can be tossed inside an Arc to get CTV
59pub struct CTVAvailable;
60impl CTVEmulator for CTVAvailable {
61    fn get_signer_for(&self, h: sha256::Hash) -> Result<Clause, EmulatorError> {
62        Ok(Clause::TxTemplate(h))
63    }
64    fn sign(
65        &self,
66        b: PartiallySignedTransaction,
67    ) -> Result<PartiallySignedTransaction, EmulatorError> {
68        Ok(b)
69    }
70}