Skip to main content

p2c_s2c/
lib.rs

1// SPDX-License-Identifier: LGPL-3.0-or-later
2
3//! Pay-to-Contract / Sign-to-Contract
4//!
5//! This library provides support for the Pay-to-Contract (P2C) construction, which
6//! transforms secp256k1 signing keys into cryptographic commitments to arbitrary
7//! data, as well as the Sign-to-Contract (S2C) construction, which does the same
8//! for ECDSA or BIP-0340 (Schnorr) signatures produced by the same keys.
9//!
10//! It is intended for use within
11//! [smart contracts unchained](https://zmnscpxj.github.io/bitcoin/unchained.html)
12//! in which S2C signatures are used with P2C keys. However, in principle the two
13//! constructions are indepedent and there is no need to use them together.
14//!
15//! The library provides three main tools:
16//!
17//! * The [`TweakedKey`] type which represents a public key or keypair to which a
18//!   P2C tweak has been applied;
19//! * The [`TweakableKey`] trait which allows ordinary key types to be tweaked to
20//!   construct a `TweakedKey`;
21//! * The [`TweakHash`] trait which defines which hash types can be used to compute
22//!   these tweaks.
23//!
24//! We have provided the [`Pay2ContractHash`] and [`Pay2ContractFullHash`] which
25//! implement the `TweakHash` trait, but for production uses, you should define
26//! your own hash.
27//!
28//! # Example (BIP-0340 Signing)
29//!
30//! ```rust
31//! use p2c_s2c::secp256k1::{Secp256k1, SecretKey, Keypair};
32//! use p2c_s2c::{TweakedKey, Pay2ContractHash};
33//!
34//! let secp = Secp256k1::new();
35//!
36//! // Untweaked key
37//! let sk: SecretKey = "0101010101010101010101010101010101010101010101010101010101010101"
38//!     .parse()
39//!     .unwrap();
40//! let keypair = sk.keypair(&secp);
41//!
42//! // P2C-tweaked signing key
43//! let prog = b"this is a thing I'm committing in the pubkey";
44//! let tweaked_keypair = TweakedKey::<_, Pay2ContractHash>::new(&keypair, prog);
45//! let tweaked_xpk = tweaked_keypair.to_x_only_public_key();
46//!
47//! // Alternately, can compute the public key from the untweaked public key.
48//! let untweaked_xpk = keypair.x_only_public_key().0;
49//! assert_eq!(
50//!     tweaked_xpk,
51//!     TweakedKey::new(&untweaked_xpk, prog),
52//! );
53//!
54//! // Can verify P2C commitment.
55//! assert!(tweaked_xpk.verify_key_commitment(&untweaked_xpk, prog));
56//!
57//! // S2C-tweaked signature
58//! let wit = b"this is a thing I'm committing in the signature";
59//! let msg = b"this is the message I'm actually signing";
60//! let (sig, nonce) = tweaked_keypair.sign_schnorr(&secp, msg, wit);
61//!
62//! // Signature verifies as a normal signature
63//! secp.verify_schnorr(&sig, msg, tweaked_xpk.as_inner())
64//!     .unwrap();
65//!
66//! // With original nonce, can also verify S2C commitment
67//! assert!(tweaked_xpk.verify_schnorr_commitment(&sig, &nonce, wit));
68//! ```
69
70mod hashes;
71mod key;
72mod signature;
73
74/// Re-export of the `bitcoin_hashes` crate.
75pub extern crate bitcoin_hashes;
76/// Re-export of the `secp256k1` crate.
77pub extern crate secp256k1;
78
79pub use crate::hashes::{Pay2ContractHash, Sign2ContractHash, Pay2ContractFullHash, Sign2ContractFullHash,TweakHash, PubkeyTweakHash};
80pub use crate::key::{TweakableKey, TweakedKey};
81
82use secp256k1::ffi::CPtr as _;
83use secp256k1::{
84    ecdsa, schnorr, Keypair, Message, PublicKey, Secp256k1, SecretKey, Signing,
85    Verification, XOnlyPublicKey,
86};
87
88use crate::signature::NonceFnData;
89
90impl<H: TweakHash<AllowedKeys = XOnly>> TweakedKey<Keypair, H> {
91    /// Tweaks a [`SecretKey`] using P2C to create a new [`TweakedKey`]`<Keypair, _>`.
92    ///
93    /// If you are calling this method, there may be a more efficient way to factor
94    /// your code to obtain a [`Keypair`] and to call [`Self::new`] instead.
95    /// This will avoid re-computing the public key corresponding to your secret key.
96    pub fn from_secret_key(
97        untweaked_key: &SecretKey,
98        data: &[u8],
99    ) -> Self {
100        // FIXME: in rust-secp 0.33 we will be able to avoid these
101        let secp = Secp256k1::signing_only();
102        let untweaked = Keypair::from_secret_key(&secp, untweaked_key);
103        Self::new(&untweaked, data)
104    }
105
106    /// The public part of the keypair.
107    ///
108    /// This returns another [`TweakedKey`]; if you want a [`XOnlyPublicKey`], you
109    /// must call `as_inner` on the returned value.
110    pub fn to_x_only_public_key(&self) -> TweakedKey<XOnlyPublicKey, H> {
111        self.map_ref(|kp| kp.x_only_public_key().0)
112    }
113
114    /// Produces an BIP-0340 (Schnorr) signature which S2C-commits to the given data.
115    pub fn sign_schnorr<C: Signing + Verification>(
116        &self,
117        secp: &Secp256k1<C>,
118        msg: &[u8],
119        s2c_data: &[u8],
120    ) -> (schnorr::Signature, XOnlyPublicKey)
121    where
122        H: PubkeyTweakHash,
123        H::SignatureTweakHash: TweakHash<AllowedKeys = XOnly>,
124    {
125        let mut data = NonceFnData {
126            ctx: secp,
127            data: s2c_data,
128            original_nonce: None,
129        };
130
131        let ext_params = secp256k1::ffi::SchnorrSigExtraParams::new(
132            Some(crate::signature::s2c_schnorr_nonce_fn::<C, H::SignatureTweakHash>),
133            core::ptr::addr_of_mut!(data).cast(),
134        );
135
136        unsafe {
137            // SAFETY: ffi call; all parameters chosen correctly
138            let mut ret = [0u8; secp256k1::constants::SCHNORR_SIGNATURE_SIZE];
139            assert!(
140                secp256k1::ffi::secp256k1_schnorrsig_sign_custom(
141                    secp.ctx().as_ptr().cast_const(),
142                    ret.as_mut_ptr(),
143                    msg.as_c_ptr(),
144                    msg.len(),
145                    self.as_inner().as_c_ptr(),
146                    &ext_params,
147                ) == 1
148            );
149            (
150                schnorr::Signature::from_byte_array(ret),
151                data.original_nonce.unwrap().x_only_public_key().0,
152            )
153        }
154    }
155}
156
157impl<H: TweakHash<AllowedKeys = Full>> TweakedKey<(SecretKey, PublicKey), H> {
158    /// The public part of the keypair.
159    ///
160    /// This returns a [`TweakedKey`]; if you want a [`PublicKey`], you
161    /// must call `as_inner` on the returned value.
162    pub fn to_public_key(&self) -> TweakedKey<PublicKey, H> {
163        self.map_ref(|kp| kp.1)
164    }
165
166    /// Produces an ECDSA signature which S2C-commits to the given data.
167    pub fn sign_ecdsa<C: Signing + Verification>(
168        &self,
169        secp: &Secp256k1<C>,
170        msg: impl Into<Message>,
171        s2c_data: &[u8],
172    ) -> (ecdsa::Signature, PublicKey)
173    where
174        H: PubkeyTweakHash,
175        H::SignatureTweakHash: TweakHash<AllowedKeys = Full>,
176    {
177        let msg = msg.into();
178        let mut data = NonceFnData {
179            ctx: secp,
180            data: s2c_data,
181            original_nonce: None,
182        };
183
184        unsafe {
185            // SAFETY: ffi call; all parameters chosen correctly
186            let mut ret = secp256k1::ffi::Signature::new();
187            assert!(
188                secp256k1::ffi::secp256k1_ecdsa_sign(
189                    secp.ctx().as_ptr().cast_const(),
190                    &mut ret,
191                    msg.as_c_ptr(),
192                    self.as_inner().0.as_c_ptr(),
193                    Some(crate::signature::s2c_ecdsa_nonce_fn::<C, H::SignatureTweakHash>),
194                    core::ptr::addr_of_mut!(data).cast(),
195                ) == 1
196            );
197            (ret.into(), data.original_nonce.unwrap())
198        }
199    }
200}
201
202/// Trait simulating a type-level boolean.
203///
204/// This trait is only implemented for [`Full`] and [`XOnly`], depending
205/// whether you want to work with BIP-0340 (Schnorr) or ECDSA signatures.
206///
207/// We do not allow using the same tweaked hash with both types of signatures.
208/// It is inadvisable to do so, because the tweaks are computed slightly
209/// differently in each case (for full keys we hash the prefix bit, while for
210/// x-only keys we hash only the x coordinate), which may lead to surprising
211/// behavior.
212///
213/// Please file an issue if you have a use-case for this.
214pub trait AllowedKeysMarker: private::Sealed {
215    /// The length of a serialized key, in bytes.
216    type Serialized: bitcoin_hashes::IsByteArray;
217}
218
219/// Only allow full keys and ECDSA signatures.
220pub enum Full {}
221/// Only allow x-only keys and BIP-0340 (Schnorr) signatures.
222pub enum XOnly {}
223
224impl AllowedKeysMarker for Full {
225    type Serialized = [u8; 33];
226}
227
228impl AllowedKeysMarker for XOnly {
229    type Serialized = [u8; 32];
230}
231
232mod private {
233    pub trait Sealed {}
234    impl Sealed for super::Full {}
235    impl Sealed for super::XOnly {}
236}
237
238
239#[cfg(test)]
240mod tests_x_only {
241    use super::*;
242
243    fn test_data() -> (
244        Secp256k1<secp256k1::All>,
245        TweakedKey<Keypair, Pay2ContractHash>,
246        TweakedKey<XOnlyPublicKey, Pay2ContractHash>,
247    ) {
248        let secp = Secp256k1::new();
249
250        // Public, untweaked key.
251        let sk: SecretKey = "0101010101010101010101010101010101010101010101010101010101010101"
252            .parse()
253            .unwrap();
254        let keypair = sk.keypair(&secp);
255        let (x_only, _parity) = keypair.x_only_public_key();
256
257        // Tweaked key (generated in three ways)
258        let prog = b"this is a thing I'm committing in the pubkey";
259        let tweaked_keypair_1 = TweakedKey::from_secret_key(&sk, prog);
260        let tweaked_keypair_2 = TweakedKey::new(&keypair, prog);
261        assert_eq!(tweaked_keypair_1, tweaked_keypair_2);
262
263        let tweaked_pk = tweaked_keypair_1.to_x_only_public_key();
264        let tweaked_pk_1 = TweakedKey::new(&x_only, prog);
265        assert_eq!(tweaked_pk, tweaked_pk_1);
266        
267        assert!(tweaked_pk.verify_key_commitment(&x_only,  prog));
268
269        let prog2 = b"this is NOT a thing I'm committing in the pubkey";
270        let tweaked_keypair_3 = TweakedKey::from_secret_key(&sk, prog2);
271        assert_ne!(tweaked_keypair_1, tweaked_keypair_3);
272        let tweaked_keypair_3 = TweakedKey::from_secret_key(&sk, prog2);
273        assert_ne!(tweaked_keypair_1, tweaked_keypair_3);
274
275        // After having done above sanity checks, return the data so we can do a real test.
276        (secp, tweaked_keypair_1, tweaked_pk)
277    }
278
279    #[test]
280    fn end_to_end_schnorr() {
281        let (secp, tweaked_keypair, tweaked_pk) = test_data();
282
283        // Tweaked signature
284        let wit = b"this is a thing I'm committing in the signature";
285        let msg = b"this is the message I'm actually signing";
286        let (sig, nonce) = tweaked_keypair.sign_schnorr(&secp, msg, wit);
287
288        // Signature verifies as a normal signature
289        let xonly = tweaked_pk.as_inner();
290        secp.verify_schnorr(&sig, msg, &xonly)
291            .unwrap();
292
293        // With original nonce, can also verify commitment
294        assert!(tweaked_pk.verify_schnorr_commitment(&sig, &nonce, wit));
295        let wit2 = b"this is NOT a thing I'm committing in the signature";
296        assert!(!tweaked_pk.verify_schnorr_commitment(&sig, &nonce, wit2));
297    }
298}
299
300#[cfg(test)]
301mod tests_ecdsa {
302    use super::*;
303
304    fn test_data() -> (
305        Secp256k1<secp256k1::All>,
306        TweakedKey<(SecretKey, PublicKey), Pay2ContractFullHash>,
307        TweakedKey<PublicKey, Pay2ContractFullHash>,
308    ) {
309        let secp = Secp256k1::new();
310
311        // Public, untweaked key.
312        let sk: SecretKey = "0101010101010101010101010101010101010101010101010101010101010101"
313            .parse()
314            .unwrap();
315        let pk = sk.public_key(&secp);
316
317        // Tweaked key (generated in three ways)
318        let prog = b"this is a thing I'm committing in the pubkey";
319        let tweaked_keypair = TweakedKey::new(&(sk, pk), prog);
320
321        let tweaked_pk = tweaked_keypair.to_public_key();
322        let tweaked_pk_1 = TweakedKey::new(&pk, prog);
323        assert_eq!(tweaked_pk, tweaked_pk_1);
324        
325        assert!(tweaked_pk.verify_key_commitment(&pk, prog));
326
327        let prog2 = b"this is NOT a thing I'm committing in the pubkey";
328        let tweaked_keypair_2 = TweakedKey::new(&(sk, pk), prog2);
329        assert_ne!(tweaked_keypair, tweaked_keypair_2);
330        let tweaked_keypair_2 = TweakedKey::new(&(sk, pk), prog2);
331        assert_ne!(tweaked_keypair, tweaked_keypair_2);
332
333        // After having done above sanity checks, return the data so we can do a real test.
334        (secp, tweaked_keypair, tweaked_pk)
335    }
336
337    #[test]
338    fn end_to_end_ecdsa() {
339        let (secp, tweaked_keypair, tweaked_pk) = test_data();
340
341        // Tweaked signature
342        let wit = b"this is a thing I'm committing in the signature";
343        let msg = Message::from_digest(*b"the sentence is a digest I swear");
344        let (sig, nonce) = tweaked_keypair.sign_ecdsa(&secp, msg, wit);
345
346        // Signature verifies as a normal signature
347        let pk= tweaked_pk.as_inner();
348        secp.verify_ecdsa(msg, &sig, &pk)
349            .unwrap();
350
351        // With original nonce, can also verify commitment
352        assert!(tweaked_pk.verify_ecdsa_commitment(&sig, &nonce, wit));
353        let wit2 = b"this is NOT a thing I'm committing in the signature";
354        assert!(!tweaked_pk.verify_ecdsa_commitment(&sig, &nonce, wit2));
355    }
356}