simplicity/policy/
key.rs

1// SPDX-License-Identifier: CC0-1.0
2
3use bitcoin_miniscript::{MiniscriptKey, ToPublicKey};
4use elements::bitcoin::key::XOnlyPublicKey;
5use hashes::sha256;
6use std::fmt::{Debug, Display};
7
8/// Public key which can be converted to a hash type.
9pub trait SimplicityKey: Clone + Eq + Ord + Debug + Display + std::hash::Hash {
10    /// SHA 256 hash associated with this key, used in the sha256 fragment.
11    type Sha256: Clone + Eq + Ord + Display + Debug + std::hash::Hash;
12}
13
14impl<Pk: MiniscriptKey> SimplicityKey for Pk {
15    type Sha256 = <Pk as MiniscriptKey>::Sha256;
16}
17
18/// Public key which can be converted to a (x-only) public key which can be used in Simplicity.
19pub trait ToXOnlyPubkey: SimplicityKey {
20    /// Convert the key to an x-only public key.
21    fn to_x_only_pubkey(&self) -> XOnlyPublicKey;
22
23    /// Convert the generic associated [`SimplicityKey::Sha256`] to [`sha256::Hash`].
24    fn to_sha256(hash: &Self::Sha256) -> sha256::Hash;
25}
26
27impl<Pk: ToPublicKey> ToXOnlyPubkey for Pk {
28    fn to_x_only_pubkey(&self) -> XOnlyPublicKey {
29        <Pk as ToPublicKey>::to_x_only_pubkey(self)
30    }
31
32    fn to_sha256(hash: &Self::Sha256) -> sha256::Hash {
33        <Pk as ToPublicKey>::to_sha256(hash)
34    }
35}
36
37/// Object which can translate one key type to another, including all associated hashes.
38pub trait Translator<P, Q, E>
39where
40    P: SimplicityKey,
41    Q: SimplicityKey,
42{
43    /// Translates public keys `P` → `Q`.
44    fn pk(&mut self, pk: &P) -> Result<Q, E>;
45
46    /// Translates SHA 256 hashes `P::Sha256` → `Q::Sha256`.
47    fn sha256(&mut self, sha256: &P::Sha256) -> Result<Q::Sha256, E>;
48}