Skip to content

Commit

Permalink
fix errors in musig2 and co
Browse files Browse the repository at this point in the history
  • Loading branch information
mmtftr committed Feb 3, 2025
1 parent 1dad8fe commit 5568b65
Show file tree
Hide file tree
Showing 9 changed files with 181 additions and 155 deletions.
9 changes: 5 additions & 4 deletions core/src/aggregator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ use bitcoin::{
Address, OutPoint, XOnlyPublicKey,
};
use bitcoin::{hashes::Hash, Txid};
use bitcoincore_rpc::RawTx;
use secp256k1::musig::{MusigAggNonce, MusigPartialSignature};

/// Aggregator struct.
Expand Down Expand Up @@ -230,7 +231,7 @@ impl Aggregator {
// println!("MOVE_TX: {:?}", tx);
// println!("MOVE_TXID: {:?}", tx.tx.compute_txid());
let message = Message::from_digest(
tx.calculate_script_spend_sighash(0, 0, None)?
tx.calculate_script_spend_sighash_indexed(0, 0, bitcoin::TapSighashType::Default)?
.to_byte_array(),
);
let final_sig = aggregate_partial_signatures(
Expand Down Expand Up @@ -354,9 +355,9 @@ impl Aggregator {
self.config.network,
)?;
let move_tx_witness_elements = vec![move_tx_sig.serialize().to_vec()];
set_p2tr_script_spend_witness(&mut move_tx_handler, &move_tx_witness_elements, 0, 0)?;
move_tx_handler.set_p2tr_script_spend_witness(&move_tx_witness_elements, 0, 0)?;

let txid = move_tx_handler.txid;
Ok((move_tx_handler.tx.raw_hex(), txid))
let txid = *move_tx_handler.get_txid();
Ok((move_tx_handler.get_cached_tx().raw_hex(), txid))
}
}
4 changes: 2 additions & 2 deletions core/src/builder/address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ pub fn generate_deposit_address(
amount: Amount,
network: bitcoin::Network,
user_takes_after: u16,
) -> (Address, TaprootSpendInfo, &[ScriptBuf]) {
) -> (Address, TaprootSpendInfo, [ScriptBuf; 2]) {
let deposit_script =
builder::script::create_deposit_script(nofn_xonly_pk, user_evm_address, amount);

Expand All @@ -143,7 +143,7 @@ pub fn generate_deposit_address(
(
taproot_addr.0,
taproot_addr.1,
&[deposit_script, script_timelock],
[deposit_script, script_timelock],
)
}

Expand Down
4 changes: 2 additions & 2 deletions core/src/builder/transaction/input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,8 +191,8 @@ impl SpentTxIn {
&self.spendable
}

pub fn get_witness(&self) -> Option<&Witness> {
self.witness.as_ref()
pub fn get_witness(&self) -> &Option<Witness> {
&self.witness
}

pub fn set_witness(&mut self, witness: Witness) {
Expand Down
6 changes: 2 additions & 4 deletions core/src/builder/transaction/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,13 @@ pub use crate::builder::transaction::operator_assert::*;
pub use crate::builder::transaction::operator_collateral::*;
pub use crate::builder::transaction::operator_reimburse::*;
use crate::builder::transaction::output::UnspentTxOut;
pub use crate::builder::transaction::txhandler::TxHandler;
use crate::builder::transaction::txhandler::DEFAULT_SEQUENCE;
pub use crate::builder::transaction::txhandler::*;
use crate::errors::BridgeError;
use crate::EVMAddress;
use bitcoin::address::NetworkUnchecked;
use bitcoin::Transaction;
use bitcoin::{absolute, Address, Amount, OutPoint, TxIn, TxOut, XOnlyPublicKey};
use input::create_tx_ins;
use txhandler::TxHandlerBuilder;
pub use txhandler::Unsigned;

mod challenge;
Expand Down Expand Up @@ -94,7 +92,7 @@ pub fn create_move_to_vault_txhandler(
value: bridge_amount_sats,
script_pubkey: deposit_address.script_pubkey(),
},
deposit_scripts.to_vec(),
deposit_scripts.into(),
Some(deposit_taproot_spend_info.clone()),
),
DEFAULT_SEQUENCE,
Expand Down
39 changes: 18 additions & 21 deletions core/src/builder/transaction/txhandler.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,10 @@
use crate::errors::BridgeError;
use crate::utils::{self, SECP};
use bitcoin::hashes::Hash;
use bitcoin::sighash::SighashCache;
use bitcoin::taproot::{self, LeafVersion};
use bitcoin::transaction::Version;
use bitcoin::{
absolute, Amount, OutPoint, Script, Sequence, TapNodeHash, Transaction, TxIn, Witness,
};
use bitcoin::{
taproot::TaprootSpendInfo, ScriptBuf, TapLeafHash, TapSighash, TapSighashType, TxOut, Txid,
};
use bitcoin::{absolute, OutPoint, Script, Sequence, Transaction, Witness};
use bitcoin::{TapLeafHash, TapSighash, TapSighashType, TxOut, Txid};
use std::default;
use std::marker::PhantomData;

use super::input::{SpendableTxIn, SpentTxIn};
Expand Down Expand Up @@ -61,6 +56,10 @@ impl<T: State> TxHandler<T> {
}

impl TxHandler<Unsigned> {
pub fn get_cached_tx(&self) -> &Transaction {
&self.cached_tx
}

pub fn get_txid(&self) -> &Txid {
// Not sure if this should be public
&self.cached_txid
Expand Down Expand Up @@ -164,17 +163,6 @@ impl TxHandler<Unsigned> {
}

impl TxHandler<Unsigned> {
pub fn get_output_as_spendable(&self, idx: usize) -> SpendableTxIn {
SpendableTxIn::from(
OutPoint {
txid: self.cached_txid,
vout: idx as u32,
},
self.txouts[idx].txout().clone(),
self.txouts[idx].scripts().clone(),
self.txouts[idx].spendinfo().clone(),
)
}
/// Constructs the witness for a script path spend of a transaction input.
///
/// # Arguments
Expand Down Expand Up @@ -220,6 +208,7 @@ impl TxHandler<Unsigned> {
witness.push(spend_control_block.serialize());

txin.set_witness(witness);
self.cached_tx.input[txin_index].witness = txin.get_witness().as_ref().unwrap().clone();

Ok(())
}
Expand Down Expand Up @@ -257,21 +246,23 @@ impl TxHandler<Unsigned> {

// txin.set_witness(witness);

// self.cached_tx.input[txin_index].witness = txin.get_witness().as_ref().unwrap().clone();
// Ok(())
// }

pub fn set_p2tr_key_spend_witness(
tx: &mut TxHandler<Unsigned>,
&mut self,
signature: &taproot::Signature,
txin_index: usize,
) -> Result<(), BridgeError> {
let txin = tx
let txin = self
.txins
.get_mut(txin_index)
.ok_or(BridgeError::TxInputNotFound)?;

if txin.get_witness().is_none() {
txin.set_witness(Witness::p2tr_key_spend(signature));
self.cached_tx.input[txin_index].witness = txin.get_witness().as_ref().unwrap().clone();

Ok(())
} else {
Expand All @@ -289,6 +280,12 @@ pub struct TxHandlerBuilder {
txouts: Vec<UnspentTxOut>,
}

impl Default for TxHandlerBuilder {
fn default() -> Self {
Self::new()
}
}

impl TxHandlerBuilder {
pub fn new() -> TxHandlerBuilder {
TxHandlerBuilder {
Expand Down
69 changes: 42 additions & 27 deletions core/src/musig2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,12 @@ pub fn partial_sign(
mod tests {
use super::{nonce_pair, MuSigNoncePair, Musig2Mode};
use crate::{
builder::{self, transaction::TxHandler},
builder::{
self,
transaction::{
input::SpendableTxIn, output::UnspentTxOut, TxHandler, TxHandlerBuilder,
},
},
errors::BridgeError,
musig2::{
aggregate_nonces, aggregate_partial_signatures, create_key_agg_cache, from_secp_xonly,
Expand All @@ -238,7 +243,7 @@ mod tests {
opcodes::all::OP_CHECKSIG,
script,
secp256k1::{schnorr, Message, PublicKey},
Amount, OutPoint, ScriptBuf, TapNodeHash, TxOut, Txid, XOnlyPublicKey,
Amount, OutPoint, ScriptBuf, Sequence, TapNodeHash, TxOut, Txid, XOnlyPublicKey,
};
use secp256k1::{musig::MusigPartialSignature, rand::Rng};
use std::vec;
Expand Down Expand Up @@ -514,21 +519,24 @@ mod tests {
vout: 0,
};

let tx_outs = builder::transaction::create_tx_outs(vec![(
Amount::from_sat(99_000_000),
receiving_address.script_pubkey(),
)]);
let tx_ins = builder::transaction::create_tx_ins(vec![utxo].into());
let dummy_tx = builder::transaction::create_btc_tx(tx_ins, tx_outs);
let mut tx_details = TxHandler {
txid: dummy_tx.compute_txid(),
tx: dummy_tx,
prevouts: vec![prevout],
prev_scripts: vec![scripts],
prev_taproot_spend_infos: vec![Some(sending_address_spend_info.clone())],
out_scripts: vec![vec![]],
out_taproot_spend_infos: vec![None],
};
let mut builder = TxHandlerBuilder::new();
builder = builder
.add_input(
SpendableTxIn::from_checked(
utxo,
prevout.clone(),
scripts.clone(),
Some(sending_address_spend_info.clone()),
)
.unwrap(),
Sequence::ENABLE_RBF_NO_LOCKTIME,
)
.add_output(UnspentTxOut::from_partial(TxOut {
value: Amount::from_sat(99_000_000),
script_pubkey: receiving_address.script_pubkey(),
}));

let mut tx_details = builder.finalize();

let message = Message::from_digest(
tx_details
Expand Down Expand Up @@ -625,19 +633,26 @@ mod tests {
)]);
let tx_ins = builder::transaction::input::create_tx_ins(vec![utxo].into());
let dummy_tx = builder::transaction::create_btc_tx(tx_ins, tx_outs);
let mut tx_details = TxHandler {
txid: dummy_tx.compute_txid(),
tx: dummy_tx,
prevouts: vec![prevout],
prev_scripts: vec![scripts],
prev_taproot_spend_infos: vec![Some(sending_address_spend_info.clone())],
out_scripts: vec![vec![]],
out_taproot_spend_infos: vec![None],
};
let mut tx_details = TxHandlerBuilder::new()
.add_input(
SpendableTxIn::from_checked(
utxo,
prevout,
scripts,
Some(sending_address_spend_info.clone()),
)
.unwrap(),
Sequence::ENABLE_RBF_NO_LOCKTIME,
)
.add_output(UnspentTxOut::from_partial(TxOut {
value: Amount::from_sat(99_000_000),
script_pubkey: receiving_address.script_pubkey(),
}))
.finalize();

let message = Message::from_digest(
tx_details
.calculate_script_spend_sighash(0, 0, None)
.calculate_script_spend_sighash_indexed(0, 0, bitcoin::TapSighashType::Default)
.unwrap()
.to_byte_array(),
);
Expand Down
8 changes: 6 additions & 2 deletions core/src/rpc/aggregator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,11 @@ impl Aggregator {
self.config.bridge_amount_sats,
self.config.network,
)?;
let sighash = move_txhandler.calculate_script_spend_sighash(0, 0, None)?;
let sighash = move_txhandler.calculate_script_spend_sighash_indexed(
0,
0,
bitcoin::TapSighashType::Default,
)?;

// aggregate partial signatures
let _final_sig = crate::musig2::aggregate_partial_signatures(
Expand All @@ -376,7 +380,7 @@ impl Aggregator {
.map_err(|x| BridgeError::Error(format!("Aggregating MoveTx signatures failed {}", x)))?;

// everything is fine, return the signed move tx
let _move_tx = move_txhandler.tx;
let _move_tx = move_txhandler.get_cached_tx();
// TODO: Sign the transaction correctly after we create taproot witness generation functions
Ok(RawSignedMoveTx { raw_tx: vec![1, 2] })
}
Expand Down
6 changes: 5 additions & 1 deletion core/src/rpc/verifier.rs
Original file line number Diff line number Diff line change
Expand Up @@ -774,7 +774,11 @@ impl ClementineVerifier for Verifier {
self.config.network,
)?;

let move_tx_sighash = move_txhandler.calculate_script_spend_sighash(0, 0, None)?;
let move_tx_sighash = move_txhandler.calculate_script_spend_sighash_indexed(
0,
0,
bitcoin::TapSighashType::Default,
)?;

let agg_nonce = match in_stream.message().await.unwrap().unwrap().params.unwrap() {
Params::MoveTxAggNonce(aggnonce) => MusigAggNonce::from_slice(&aggnonce)
Expand Down
Loading

0 comments on commit 5568b65

Please sign in to comment.