Skip to main content

p2c_s2c/
hashes.rs

1// SPDX-License-Identifier: LGPL-3.0-or-later
2
3use bitcoin_hashes::{hash_newtype, sha256t, sha256t_tag};
4use secp256k1::Scalar;
5
6use crate::{AllowedKeysMarker, Full, XOnly};
7
8sha256t_tag! {
9    /// Tag used for in tagged hash for key tweaking for full keys.
10    pub struct Pay2ContractFullTag = hash_str("P2C-S2C-Full/P/1.0");
11}
12
13sha256t_tag! {
14    /// Tag used for in tagged hash for nonce tweaking for ECDSA signatures.
15    pub struct Sign2ContractFullTag = hash_str("P2C-S2C-Full/S/1.0");
16}
17
18sha256t_tag! {
19    /// Tag used for in tagged hash for key tweaking for x-only keys.
20    pub struct Pay2ContractTag = hash_str("P2C-S2C/P/1.0");
21}
22
23sha256t_tag! {
24    /// Tag used for in tagged hash for nonce tweaking for BIP-0340 (Schnorr) signatures.
25    pub struct Sign2ContractTag = hash_str("P2C-S2C/S/1.0");
26}
27
28sha256t_tag! {
29    /// Tag used for in tagged hash for key tweaking for full keys.
30    pub struct TapTweakTag = hash_str("TapTweak");
31}
32
33hash_newtype! {
34    /// Tagged hash used for key tweaking for full keys.
35    #[derive(Debug)]
36    pub struct Pay2ContractFullHash(sha256t::Hash<Pay2ContractFullTag>);
37
38    /// Tagged hash used for nonce tweaking for ECDSA signatures.
39    #[derive(Debug)]
40    pub struct Sign2ContractFullHash(sha256t::Hash<Sign2ContractFullTag>);
41
42    /// Tagged hash used for key tweaking for x-only keys.
43    #[derive(Debug)]
44    pub struct Pay2ContractHash(sha256t::Hash<Pay2ContractTag>);
45
46    /// Tagged hash used for nonce tweaking for BIP-0340 (Schnorr) signatures.
47    #[derive(Debug)]
48    pub struct Sign2ContractHash(sha256t::Hash<Sign2ContractTag>);
49
50    /// Tagged hash for Taproot outputs.
51    ///
52    /// This is identical to the type of the same name in rust-bitcoin, but has
53    /// a slightly different API for use in this crate.
54    #[derive(Debug)]
55    pub struct TapTweakHash(sha256t::Hash<TapTweakTag>);
56}
57
58/// A trait describing a hash that can be used to tweak a point (either a public
59/// key or a signature nonce) in this library.
60///
61/// Using this trait, you can tweak public keys or signatures. If you want to
62/// you want to tweak both, you probably want to use a hash which implements the
63/// [`PubkeyTweakHash`] trait, which ensures you are using a different domain-separated
64/// hash for your P2C commitments and your S2C commitments.
65///
66/// You can use the [`Pay2ContractHash`] or [`Pay2ContractFullHash`] types for this
67/// purpose, which are fine for non-production uses, but for a real application you
68/// should define your own hash type.
69pub trait TweakHash: bitcoin_hashes::Hash<Bytes = [u8; 32]> {
70    /// The BIP-0340 tag usad for this hash.
71    type HashTag: sha256t::Tag;
72
73    /// Whether to work with full keys and ECDSA signatures or x-only keys and
74    /// BIP-0340 (Schnorr) signatures.
75    ///
76    /// Must be set to either [`Full`] or [`XOnly`].
77    ///
78    /// When committing to the key, this determines whether to include its X coordinate.
79    /// See the docs for [`AllowedKeysMarker`] for more.
80    type AllowedKeys: AllowedKeysMarker;
81
82    /// Computes the tweak that should be added to a given public key to obtain a tweaked public key.
83    ///
84    /// The serialized key is accepted as a byte slice. However, the tweak computation
85    /// does no length-prefixing. The serialized key must therefore either be a fixed
86    /// length or contain its own length prefix.
87    fn compute_tweak(
88        serialized_key: &[u8],
89        data: &[u8],
90    ) -> Scalar {
91        use bitcoin_hashes::{sha256t::Tag as _, HashEngine as _};
92
93        let mut eng = Self::HashTag::engine();
94        eng.input(serialized_key);
95        eng.input(data); // no length prefix OK, since prefix data was fixed length
96
97        let bare_hash = sha256t::Hash::<Self::HashTag>::from_engine(eng);
98        Scalar::from_be_bytes(bare_hash.to_byte_array())
99            .expect("cryptographically unreachable")
100    }
101}
102
103/// Trait describing a hash which can be used specifically to tweak a public key,
104/// for use.
105pub trait PubkeyTweakHash: TweakHash + bitcoin_hashes::Hash<Bytes = [u8; 32]> {
106    /// The commitment type t
107    type SignatureTweakHash: TweakHash;
108}
109
110impl TweakHash for Pay2ContractHash {
111    type HashTag = Pay2ContractTag;
112    type AllowedKeys = XOnly;
113}
114
115impl PubkeyTweakHash for Pay2ContractHash {
116    type SignatureTweakHash = Sign2ContractHash;
117}
118
119impl TweakHash for Pay2ContractFullHash {
120    type HashTag = Pay2ContractFullTag;
121    type AllowedKeys = Full;
122}
123
124impl PubkeyTweakHash for Pay2ContractFullHash {
125    type SignatureTweakHash = Sign2ContractFullHash;
126}
127
128impl TweakHash for Sign2ContractHash {
129    type HashTag = Sign2ContractTag;
130    type AllowedKeys = XOnly;
131}
132
133impl TweakHash for Sign2ContractFullHash {
134    type HashTag = Sign2ContractFullTag;
135    type AllowedKeys = Full;
136}
137
138impl TweakHash for TapTweakHash {
139    type HashTag = TapTweakTag;
140    type AllowedKeys = XOnly;
141}
142
143#[cfg(test)]
144mod test {
145    use super::*;
146
147    use crate::TweakedKey;
148    
149    use secp256k1::XOnlyPublicKey;
150    
151    #[test]
152    #[rustfmt::skip]
153    fn taproot() {
154        /* Computable as
155        let dummy_hash = bitcoin::TapNodeHash::from_script(
156            bitcoin::Script::new(),
157            bitcoin::taproot::LeafVersion::TapScript,
158        );
159        */
160        let dummy_hash = [
161            0x83, 0xd9, 0x56, 0xa5, 0xb3, 0x61, 0x09, 0xf8,
162            0xf6, 0x67, 0xaa, 0x9b, 0x36, 0x6e, 0x84, 0x79,
163            0x94, 0x2e, 0x32, 0x39, 0x64, 0x55, 0xb5, 0xf4,
164            0x3b, 0x6d, 0xf9, 0x17, 0x76, 0x8e, 0x4d, 0x45,
165        ];
166
167        let untweaked: XOnlyPublicKey = "1112131405060708010203040506070801020304050607080102030405060708".parse().unwrap();
168        let p2c_tweaked = TweakedKey::<_, TapTweakHash>::new(&untweaked, &dummy_hash);
169        assert_eq!(
170            p2c_tweaked.as_inner().serialize(),
171            [
172                0x1c, 0xf7, 0xe5, 0x0f, 0x0b, 0xbf, 0x9a, 0x05,
173                0xb1, 0x2f, 0x09, 0x71, 0x5d, 0x4f, 0x31, 0x4a,
174                0x6f, 0xa9, 0x4c, 0xc7, 0xe5, 0xcb, 0xf4, 0x76,
175                0xf9, 0xeb, 0x1d, 0x01, 0x4e, 0xf4, 0xac, 0xef,
176            ],
177        );
178
179        /* The same key can be computed from
180        let secp = secp256k1::Secp256k1::new();
181        let bitcoin_tweaked = bitcoin::taproot::TaprootSpendInfo::new_key_spend(&secp, untweaked, Some(bitcoin::TapNodeHash::from_byte_array(dummy_hash)));
182        */
183    }
184}