Skip to main content

wsts/
btc.rs

1use bitcoin::{
2    absolute::LockTime,
3    consensus::Encodable,
4    secp256k1::{self, Secp256k1, Verification, XOnlyPublicKey},
5    sighash::{Prevouts, SighashCache},
6    taproot::{LeafVersion, Signature},
7    transaction::Version,
8    Amount, OutPoint, Script, ScriptBuf, Sequence, TapLeafHash, TapNodeHash, TapSighash,
9    TapSighashType, Transaction, TxIn, TxOut, Witness,
10};
11
12use std::sync::LazyLock;
13
14/// A dummy Schnorr signature.
15static DUMMY_SIGNATURE: LazyLock<Signature> = LazyLock::new(|| Signature {
16    signature: secp256k1::schnorr::Signature::from_slice(&[0; 64]).unwrap(),
17    sighash_type: TapSighashType::All,
18});
19
20/// An error type that wraps the various bitcoin related arrors which we may encounter
21#[derive(Debug, thiserror::Error)]
22pub enum Error {
23    /// An IO error was returned from the [`bitcoin`] library. This is usually an
24    /// error that occurred during encoding/decoding of bitcoin types.
25    #[error("an io error was returned from the bitcoin library: {0}")]
26    BitcoinIo(#[source] bitcoin::io::Error),
27    /// An error was returned from the bitcoinconsensus library.
28    #[error("error returned from libbitcoinconsensus: {0}")]
29    BitcoinConsensus(bitcoinconsensus::Error),
30    /// Taproot error
31    #[error("an error occurred when constructing the taproot signing digest: {0}")]
32    Taproot(#[from] bitcoin::sighash::TaprootError),
33}
34
35/// An unspent transaction output, which contains all of the information needed to identify or spend
36#[derive(Debug, Clone, Copy, PartialEq)]
37pub struct Utxo {
38    /// The outpoint of the signers' UTXO
39    pub outpoint: OutPoint,
40    /// The amount associated with the above UTXO
41    pub amount: u64,
42    /// The public key used to create the key-spend only taproot script.
43    pub public_key: XOnlyPublicKey,
44}
45
46impl Utxo {
47    /// Create a TxIn object for the signers' UTXO
48    ///
49    /// The signers' UTXO is always a key-spend only taproot UTXO, so a
50    /// valid signature is all that is needed to spend it.
51    fn as_tx_input(&self, signature: &Signature) -> TxIn {
52        TxIn {
53            previous_output: self.outpoint,
54            sequence: Sequence::ZERO,
55            witness: Witness::p2tr_key_spend(signature),
56            script_sig: ScriptBuf::new(),
57        }
58    }
59
60    /// Construct the UTXO associated with this outpoint.
61    fn as_tx_output<C: Verification>(
62        &self,
63        secp: &Secp256k1<C>,
64        merkle_root: Option<TapNodeHash>,
65    ) -> TxOut {
66        Self::new_tx_output(secp, self.public_key, self.amount, merkle_root)
67    }
68
69    /// Construct the new signers' UTXO
70    ///
71    /// The signers' UTXO is always a key-spend only taproot UTXO.
72    fn new_tx_output<C: Verification>(
73        secp: &Secp256k1<C>,
74        public_key: XOnlyPublicKey,
75        sats: u64,
76        merkle_root: Option<TapNodeHash>,
77    ) -> TxOut {
78        TxOut {
79            value: Amount::from_sat(sats),
80            script_pubkey: ScriptBuf::new_p2tr(secp, public_key, merkle_root),
81        }
82    }
83}
84
85/// A transaction which we will use to see if we can construct a valid signature
86pub struct UnsignedTx {
87    /// utxo
88    pub utxo: Utxo,
89    /// tx
90    pub tx: Transaction,
91}
92
93impl UnsignedTx {
94    const AMOUNT: u64 = 0;
95
96    /// Construct an unsigned mock transaction.
97    ///
98    /// This will use the provided `aggregate_key` to construct
99    /// a [`Transaction`] with a single input and output with value 0.
100    pub fn new(signer_public_key: XOnlyPublicKey) -> Self {
101        let utxo = Utxo {
102            outpoint: OutPoint::null(),
103            amount: Self::AMOUNT,
104            public_key: signer_public_key,
105        };
106
107        let tx = Transaction {
108            version: Version::TWO,
109            lock_time: LockTime::ZERO,
110            input: vec![utxo.as_tx_input(&DUMMY_SIGNATURE)],
111            output: vec![TxOut {
112                value: Amount::from_sat(Self::AMOUNT),
113                script_pubkey: ScriptBuf::new_op_return([]),
114            }],
115        };
116
117        Self { tx, utxo }
118    }
119
120    /// Gets the sighash for the signers' input UTXO which needs to be signed
121    /// before the transaction can be broadcast.
122    pub fn compute_sighash<C: Verification>(
123        &self,
124        secp: &Secp256k1<C>,
125        merkle_root: Option<TapNodeHash>,
126    ) -> Result<TapSighash, Error> {
127        let prevouts = [self.utxo.as_tx_output(secp, merkle_root)];
128        let mut sighasher = SighashCache::new(&self.tx);
129
130        sighasher
131            .taproot_key_spend_signature_hash(0, &Prevouts::All(&prevouts), TapSighashType::All)
132            .map_err(Into::into)
133    }
134
135    /// Gets the sighash for the signers' input UTXO which needs to be signed
136    /// before the transaction can be broadcast, using a script spend from the passed script
137    pub fn compute_script_sighash<C: Verification>(
138        &self,
139        secp: &Secp256k1<C>,
140        merkle_root: Option<TapNodeHash>,
141        script: &Script,
142    ) -> Result<TapSighash, Error> {
143        let prevouts = [self.utxo.as_tx_output(secp, merkle_root)];
144        let mut sighasher = SighashCache::new(&self.tx);
145        let leaf_hash = TapLeafHash::from_script(script, LeafVersion::TapScript);
146
147        sighasher
148            .taproot_script_spend_signature_hash(
149                0,
150                &Prevouts::All(&prevouts),
151                leaf_hash,
152                TapSighashType::All,
153            )
154            .map_err(Into::into)
155    }
156
157    /// Tests if the provided taproot [`Signature`] is valid for spending the
158    /// signers' UTXO. This function will return  [`Error::BitcoinConsensus`]
159    /// error if the transaction fails verification, passing the underlying error
160    /// from [`bitcoinconsensus`].
161    pub fn verify_signature<C: Verification>(
162        &self,
163        secp: &Secp256k1<C>,
164        signature: &Signature,
165        merkle_root: Option<TapNodeHash>,
166    ) -> Result<(), Error> {
167        let witness = Witness::p2tr_key_spend(signature);
168        self.verify_witness(secp, witness, merkle_root)
169    }
170
171    /// Tests if the provided taproot [`Witness`] is valid for spending the
172    /// signers' UTXO. This function will return  [`Error::BitcoinConsensus`]
173    /// error if the transaction fails verification, passing the underlying error
174    /// from [`bitcoinconsensus`].
175    pub fn verify_witness<C: Verification>(
176        &self,
177        secp: &Secp256k1<C>,
178        witness: Witness,
179        merkle_root: Option<TapNodeHash>,
180    ) -> Result<(), Error> {
181        // Create a copy of the transaction so that we don't modify the
182        // transaction stored in the struct.
183        let mut tx = self.tx.clone();
184
185        // Set the witness data on the input from the provided signature.
186        tx.input[0].witness = witness;
187
188        // Encode the transaction to bytes (needed by the bitcoinconsensus
189        // library).
190        let mut tx_bytes: Vec<u8> = Vec::new();
191        tx.consensus_encode(&mut tx_bytes)
192            .map_err(Error::BitcoinIo)?;
193
194        // Get the prevout for the signers' UTXO.
195        let prevout = self.utxo.as_tx_output(secp, merkle_root);
196        let prevout_script_bytes = prevout.script_pubkey.as_script().as_bytes();
197
198        // Create the bitcoinconsensus UTXO object.
199        let prevout_utxo = bitcoinconsensus::Utxo {
200            script_pubkey: prevout_script_bytes.as_ptr(),
201            script_pubkey_len: prevout_script_bytes.len() as u32,
202            value: Self::AMOUNT as i64,
203        };
204
205        // We specify the flags to include all pre-taproot and taproot
206        // verifications explicitly.
207        // https://github.com/rust-bitcoin/rust-bitcoinconsensus/blob/master/src/lib.rs
208        let flags = bitcoinconsensus::VERIFY_ALL_PRE_TAPROOT | bitcoinconsensus::VERIFY_TAPROOT;
209
210        // Verify that the transaction updated with the provided signature can
211        // successfully spend the signers' UTXO. Note that the amount is not
212        // used in the verification process for taproot spends, only the
213        // signature.
214        bitcoinconsensus::verify_with_flags(
215            prevout_script_bytes,
216            Self::AMOUNT,
217            &tx_bytes,
218            Some(&[prevout_utxo]),
219            0,
220            flags,
221        )
222        .map_err(Error::BitcoinConsensus)
223    }
224}
225
226#[cfg(test)]
227mod test {
228    use super::*;
229    use crate::{
230        compute,
231        taproot::{test_helpers, SchnorrProof},
232        traits::{Aggregator, Signer},
233        v2,
234    };
235    use bitcoin::key::TapTweak;
236
237    use bitcoin::{
238        blockdata::{
239            locktime::absolute,
240            script::{Builder, PushBytesBuf},
241        },
242        opcodes::all::*,
243        taproot::{LeafVersion, TaprootBuilder},
244    };
245    use rand_core::OsRng;
246
247    #[test]
248    fn verify_sig_tapscript() {
249        // Generate a DKG aggregate key.
250        let num_keys: u32 = 10;
251        let num_parties: u32 = 4;
252        let threshold: u32 = 7;
253        let signer_ids: Vec<Vec<u32>> = [
254            [1, 2, 3].to_vec(),
255            [4, 5].to_vec(),
256            [6, 7, 8].to_vec(),
257            [9, 10].to_vec(),
258        ]
259        .to_vec();
260        let mut signers: Vec<v2::Signer> = signer_ids
261            .iter()
262            .enumerate()
263            .map(|(id, ids)| {
264                v2::Signer::new(
265                    id.try_into().unwrap(),
266                    ids,
267                    num_parties,
268                    num_keys,
269                    threshold,
270                    &mut OsRng,
271                )
272            })
273            .collect();
274
275        let polys = match test_helpers::dkg(&mut signers, &mut OsRng) {
276            Ok(polys) => polys,
277            Err(secret_errors) => {
278                panic!("Got secret errors from DKG: {secret_errors:?}");
279            }
280        };
281
282        let mut signing_set = [signers[0].clone(), signers[1].clone(), signers[3].clone()].to_vec();
283        let key_ids = signing_set
284            .iter()
285            .flat_map(|s| s.get_key_ids())
286            .collect::<Vec<u32>>();
287        let mut sig_agg = v2::Aggregator::new(num_keys, threshold);
288        sig_agg.init(&polys).expect("aggregator init failed");
289        let wsts_public_key = sig_agg.poly[0];
290        let wsts_public_key_bytes = wsts_public_key.x().to_bytes();
291
292        // the sBTC accept script must be of the form
293        //
294        //     <sbtc_payload> DROP <signers_pubkey> CHECKSIGVERIFY
295        //
296        // with a variable sized  <sbtc_payload> up to 159-bytes
297
298        let sbtc_payload = [255u8; 159];
299        let mut push_bytes = PushBytesBuf::new();
300        push_bytes.extend_from_slice(&sbtc_payload).unwrap();
301
302        let accept_script = Builder::new()
303            .push_slice(push_bytes)
304            .push_opcode(OP_DROP)
305            .push_slice(wsts_public_key_bytes)
306            .push_opcode(OP_CHECKSIG)
307            .into_script();
308
309        println!("Accept script {accept_script}");
310
311        // Generate keys for the depositor
312        let secp = Secp256k1::new();
313        let depositor_secret_key = secp256k1::SecretKey::new(&mut OsRng);
314        let depositor_keypair = secp256k1::Keypair::from_secret_key(&secp, &depositor_secret_key);
315        let (depositor_public_key, _) = depositor_keypair.x_only_public_key();
316
317        // the reject script must be of the form
318        //
319        //     <lock_time> CHECKSEQUENCEVERIFY <reclaim script>
320        //
321        let reject_script = Builder::new()
322            .push_lock_time(absolute::LockTime::ZERO)
323            .push_opcode(OP_CSV)
324            .push_opcode(OP_DROP)
325            .push_x_only_key(&depositor_public_key)
326            .push_opcode(OP_CHECKSIG)
327            .into_script();
328
329        println!("Reject script {reject_script}");
330
331        // BIP-341 defines the NUMS field element as the hash of the x-coord of G
332        let nums_x_data =
333            hex::decode("50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0")
334                .unwrap();
335        let nums_public_key = bitcoin::XOnlyPublicKey::from_slice(&nums_x_data).unwrap();
336
337        let spend_info = TaprootBuilder::new()
338            .add_leaf(1, accept_script.clone())
339            .unwrap()
340            .add_leaf(1, reject_script.clone())
341            .unwrap()
342            .finalize(&secp, nums_public_key)
343            .expect("failed to finalize taproot_spend_info");
344
345        println!("TaprootSpendInfo {spend_info:?}");
346
347        let spend_internal_key = spend_info.internal_key();
348        let merkle_root = spend_info.merkle_root();
349
350        let unsigned = UnsignedTx::new(spend_internal_key);
351
352        // first sign using the depositor key and reject script
353        let sighash = unsigned
354            .compute_script_sighash(&secp, merkle_root, &reject_script)
355            .expect("failed to compute taproot sighash");
356        let message = secp256k1::Message::from_digest_slice(sighash.as_ref())
357            .expect("Failed to create message");
358
359        let schnorr_sig = secp.sign_schnorr(&message, &depositor_keypair);
360        let taproot_sig = bitcoin::taproot::Signature {
361            signature: schnorr_sig,
362            sighash_type: TapSighashType::All,
363        };
364
365        let control_block = spend_info
366            .control_block(&(reject_script.clone(), LeafVersion::TapScript))
367            .expect("insert the reject script into the tree");
368
369        println!("ControlBlock {control_block:?}");
370
371        let mut witness = Witness::new();
372        witness.push(taproot_sig.to_vec());
373        witness.push(reject_script.as_bytes());
374        witness.push(control_block.serialize());
375
376        unsigned
377            .verify_witness(&secp, witness, merkle_root)
378            .expect("signature verification failed");
379
380        // next sign using the aggregate key and the accept script
381        let sighash = unsigned
382            .compute_script_sighash(&secp, merkle_root, &accept_script)
383            .expect("failed to compute taproot sighash");
384        let message: &[u8] = sighash.as_ref();
385
386        let (nonces, sig_shares) =
387            test_helpers::sign_schnorr(message, &mut signing_set, &mut OsRng);
388        let proof = match sig_agg.sign_schnorr(message, &nonces, &sig_shares, &key_ids) {
389            Err(e) => panic!("Aggregator sign failed: {e:?}"),
390            Ok(proof) => proof,
391        };
392        let proof_bytes = proof.to_bytes();
393        let schnorr_sig = bitcoin::secp256k1::schnorr::Signature::from_slice(&proof_bytes)
394            .expect("Failed to parse Signature from slice");
395        let taproot_sig = bitcoin::taproot::Signature {
396            signature: schnorr_sig,
397            sighash_type: TapSighashType::All,
398        };
399
400        let control_block = spend_info
401            .control_block(&(accept_script.clone(), LeafVersion::TapScript))
402            .expect("insert the accept script into the control block");
403
404        println!("ControlBlock {control_block:?}");
405
406        let mut witness = Witness::new();
407        witness.push(taproot_sig.to_vec());
408        witness.push(accept_script.as_bytes());
409        witness.push(control_block.serialize());
410
411        unsigned
412            .verify_witness(&secp, witness, merkle_root)
413            .expect("signature verification failed");
414    }
415
416    #[test]
417    fn verify_sig_no_merkle_root() {
418        verify_sig(None)
419    }
420
421    #[test]
422    fn verify_sig_some_merkle_root() {
423        verify_sig(Some([0u8; 32]));
424    }
425
426    fn verify_sig(raw_merkle_root: Option<[u8; 32]>) {
427        let merkle_root = raw_merkle_root.map(TapNodeHash::assume_hidden);
428        let secp = Secp256k1::new();
429
430        // Generate a key pair which will serve as the signers' aggregate key.
431        let secret_key = secp256k1::SecretKey::new(&mut OsRng);
432        let keypair = secp256k1::Keypair::from_secret_key(&secp, &secret_key);
433        let tweaked = keypair.tap_tweak(&secp, merkle_root);
434        let (aggregate_key, _) = keypair.x_only_public_key();
435
436        // Create a new transaction using the aggregate key.
437        let unsigned = UnsignedTx::new(aggregate_key);
438
439        let sighash = unsigned
440            .compute_sighash(&secp, merkle_root)
441            .expect("failed to compute taproot sighash");
442
443        // Sign the taproot sighash.
444        let message = secp256k1::Message::from_digest_slice(sighash.as_ref())
445            .expect("Failed to create message");
446
447        // first test a standard schnorr signature
448
449        // [1] Verify the correct signature, which should succeed.
450        let schnorr_sig = secp.sign_schnorr(&message, &tweaked.to_keypair());
451        let taproot_sig = bitcoin::taproot::Signature {
452            signature: schnorr_sig,
453            sighash_type: TapSighashType::All,
454        };
455        unsigned
456            .verify_signature(&secp, &taproot_sig, merkle_root)
457            .expect("signature verification failed");
458
459        // [2] Verify the correct signature, but with a different sighash type,
460        // which should fail.
461        let taproot_sig = bitcoin::taproot::Signature {
462            signature: schnorr_sig,
463            sighash_type: TapSighashType::None,
464        };
465        unsigned
466            .verify_signature(&secp, &taproot_sig, merkle_root)
467            .expect_err("signature verification should have failed");
468
469        // [3] Verify an incorrect signature with the correct sighash type,
470        // which should fail. In this case we've created the signature using
471        // the untweaked keypair.
472        let schnorr_sig = secp.sign_schnorr(&message, &keypair);
473        let taproot_sig = bitcoin::taproot::Signature {
474            signature: schnorr_sig,
475            sighash_type: TapSighashType::All,
476        };
477        unsigned
478            .verify_signature(&secp, &taproot_sig, merkle_root)
479            .expect_err("signature verification should have failed");
480
481        // [4] Verify an incorrect signature with the correct sighash type, which
482        // should fail. In this case we use a completely newly generated keypair.
483        let secret_key = secp256k1::SecretKey::new(&mut OsRng);
484        let keypair = secp256k1::Keypair::from_secret_key(&secp, &secret_key);
485        let schnorr_sig = secp.sign_schnorr(&message, &keypair);
486        let taproot_sig = bitcoin::taproot::Signature {
487            signature: schnorr_sig,
488            sighash_type: TapSighashType::All,
489        };
490        unsigned
491            .verify_signature(&secp, &taproot_sig, merkle_root)
492            .expect_err("signature verification should have failed");
493
494        // [5] Same as [4], but using its tweaked key.
495        let tweaked = keypair.tap_tweak(&secp, merkle_root);
496        let schnorr_sig = secp.sign_schnorr(&message, &tweaked.to_keypair());
497        let taproot_sig = bitcoin::taproot::Signature {
498            signature: schnorr_sig,
499            sighash_type: TapSighashType::All,
500        };
501        unsigned
502            .verify_signature(&secp, &taproot_sig, merkle_root)
503            .expect_err("signature verification should have failed");
504
505        // now test a WSTS signature
506
507        // Generate a DKG aggregate key.
508        let num_keys: u32 = 10;
509        let num_parties: u32 = 4;
510        let threshold: u32 = 7;
511        let signer_ids: Vec<Vec<u32>> = [
512            [1, 2, 3].to_vec(),
513            [4, 5].to_vec(),
514            [6, 7, 8].to_vec(),
515            [9, 10].to_vec(),
516        ]
517        .to_vec();
518        let mut signers: Vec<v2::Signer> = signer_ids
519            .iter()
520            .enumerate()
521            .map(|(id, ids)| {
522                v2::Signer::new(
523                    id.try_into().unwrap(),
524                    ids,
525                    num_parties,
526                    num_keys,
527                    threshold,
528                    &mut OsRng,
529                )
530            })
531            .collect();
532
533        let polys = match test_helpers::dkg(&mut signers, &mut OsRng) {
534            Ok(polys) => polys,
535            Err(secret_errors) => {
536                panic!("Got secret errors from DKG: {secret_errors:?}");
537            }
538        };
539
540        let mut signing_set = [signers[0].clone(), signers[1].clone(), signers[3].clone()].to_vec();
541        let key_ids = signing_set
542            .iter()
543            .flat_map(|s| s.get_key_ids())
544            .collect::<Vec<u32>>();
545        let mut sig_agg = v2::Aggregator::new(num_keys, threshold);
546        sig_agg.init(&polys).expect("aggregator init failed");
547        let tweaked_public_key = compute::tweaked_public_key(&sig_agg.poly[0], raw_merkle_root);
548        // taproot code within both wsts and libsecp256k1 will take care of tweaking the key
549        let aggregate_key = XOnlyPublicKey::from_slice(&sig_agg.poly[0].x().to_bytes())
550            .expect("failed to make XOnlyPublicKey");
551
552        // Create a new transaction using the aggregate key.
553        let unsigned = UnsignedTx::new(aggregate_key);
554
555        let sighash = unsigned
556            .compute_sighash(&secp, merkle_root)
557            .expect("failed to compute taproot sighash");
558
559        // Sign the taproot sighash.
560        let message: &[u8] = sighash.as_ref();
561        let (nonces, sig_shares) =
562            test_helpers::sign(message, &mut signing_set, &mut OsRng, raw_merkle_root);
563        let proof =
564            match sig_agg.sign_taproot(message, &nonces, &sig_shares, &key_ids, raw_merkle_root) {
565                Err(e) => panic!("Aggregator sign failed: {e:?}"),
566                Ok(proof) => proof,
567            };
568        // now ser/de the proof
569        let proof_bytes = proof.to_bytes();
570        let proof_deser = SchnorrProof::from(proof_bytes);
571
572        assert_eq!(proof, proof_deser);
573        assert!(proof_deser.verify(&tweaked_public_key.x(), message));
574
575        // [1] Verify the correct signature, which should succeed.
576        let schnorr_sig = bitcoin::secp256k1::schnorr::Signature::from_slice(&proof_bytes)
577            .expect("Failed to parse Signature from slice");
578        let taproot_sig = bitcoin::taproot::Signature {
579            signature: schnorr_sig,
580            sighash_type: TapSighashType::All,
581        };
582        unsigned
583            .verify_signature(&secp, &taproot_sig, merkle_root)
584            .expect("signature verification failed");
585
586        // [2] Verify the correct signature, but with a different sighash type,
587        // which should fail.
588        let taproot_sig = bitcoin::taproot::Signature {
589            signature: schnorr_sig,
590            sighash_type: TapSighashType::None,
591        };
592        unsigned
593            .verify_signature(&secp, &taproot_sig, merkle_root)
594            .expect_err("signature verification should have failed");
595    }
596}