Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merge MuSig2 functions into ekrem/new-architecture #206

Merged
merged 21 commits into from
Aug 9, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 50 additions & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ risc0-zkvm = "0.21.0"
serde = { version = "1.0", default-features = false }
serde_json = "1.0.108"
byteorder = "1.5.0"
secp256k1 = "0.29.0"
secp256k1 = {version="0.29.0", features=["serde"]}
crypto-bigint = { version = "=0.5.5", default-features = false }
thiserror = "1.0.57"
tracing = { version = "0.1.40", default-features = false }
Expand All @@ -28,6 +28,7 @@ sqlx = { version = "0.7.4", default-features = false }
k256 = { version = "=0.13.3", default-features = false }
risc0-build = "0.21.0"
bitcoin-mock-rpc = { git = "https://github.com/chainwayxyz/bitcoin-mock-rpc", tag = "v0.0.5" }
musig2 = "0.0.11"

# Always optimize; building and running the guest takes much longer without optimization.
[profile.dev]
Expand Down
1 change: 1 addition & 0 deletions core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ clap = { workspace = true, features = ["derive"] }
toml = { workspace = true }
sqlx = { workspace = true, features = ["runtime-tokio", "postgres"] }
bitcoin-mock-rpc = { workspace = true }
musig2 = { version = "0.0.11" }
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we can use workspace=true here


[features]
default = []
Expand Down
9 changes: 9 additions & 0 deletions core/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,9 @@ pub enum BridgeError {
#[error("InvalidKickoffUtxo")]
InvalidKickoffUtxo,

#[error("KeyAggContextError")]
KeyAggContextError,

#[error("NoncesNotFound")]
NoncesNotFound,

Expand Down Expand Up @@ -224,3 +227,9 @@ impl From<sqlx::Error> for BridgeError {
BridgeError::DatabaseError(err)
}
}

impl From<musig2::errors::KeyAggError> for BridgeError {
fn from(_err: musig2::errors::KeyAggError) -> Self {
BridgeError::KeyAggContextError
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pls propogate the original message in this

}
}
3 changes: 1 addition & 2 deletions core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ pub mod errors;
pub mod extended_rpc;
pub mod merkle;
pub mod mock;
pub mod musig;
pub mod operator;
pub mod script_builder;
pub mod servers;
Expand All @@ -24,7 +25,6 @@ pub mod transaction_builder;
pub mod user;
pub mod utils;
pub mod verifier;
pub mod musig;

pub type ConnectorUTXOTree = Vec<Vec<OutPoint>>;
pub type HashTree = Vec<Vec<HashType>>;
Expand All @@ -38,7 +38,6 @@ pub struct EVMAddress(#[serde(with = "hex::serde")] pub [u8; 20]);
/// Type alias for withdrawal payment, HashType is taproot script hash
pub type WithdrawalPayment = (Txid, HashType);


#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct PsbtOutPoint {
/// The referenced transaction's txid.
Expand Down
119 changes: 75 additions & 44 deletions core/src/musig.rs
Original file line number Diff line number Diff line change
@@ -1,50 +1,81 @@
use secp256k1::{schnorr, Keypair};
use bitcoin::Network;
use crypto_bigint::rand_core::OsRng;
use musig2::{
secp::Point, secp256k1::Scalar, sign_partial, AggNonce, FirstRound, KeyAggContext,
PartialSignature, SecNonce, SecNonceSpices,
};
use secp256k1::{rand::Rng, schnorr, Keypair, PublicKey};

pub type MusigPubNonce = [u8; 32];
pub type MusigSecNonce = [u8; 32];
pub type MusigAggNonce = [u8; 32];
use crate::{actor::Actor, errors::BridgeError};

// We can directly use the musig2 crate for this
// No need for extra types etc.
pub type MusigPubNonce = [u8; 66];
pub type MusigSecNonce = [u8; 64];
// pub type MusigAggNonce = [u8; 66];
pub type MusigPartialSignature = [u8; 32];

pub fn nonce_pair(_key: &secp256k1::Keypair) -> (MusigSecNonce, MusigPubNonce) {
// let kp = keypair_to(key);
// zkp::new_musig_nonce_pair(
// &SECP,
// MusigSessionId::assume_unique_per_nonce_gen(rand::random()),
// None,
// Some(kp.secret_key()),
// kp.public_key(),
// None,
// Some(rand::random()),
// ).expect("non-zero session id")
([0u8; 32] as MusigSecNonce, [0u8; 32] as MusigPubNonce)
pub fn create_key_agg_ctx(pks: Vec<PublicKey>) -> Result<KeyAggContext, BridgeError> {
let musig_pks: Vec<musig2::secp256k1::PublicKey> = pks
.iter()
.map(|pk| musig2::secp256k1::PublicKey::from_slice(&pk.serialize()).unwrap())
.collect::<Vec<musig2::secp256k1::PublicKey>>();
Ok(KeyAggContext::new(musig_pks)?)
}

pub fn partial_sign(
pubkeys: impl IntoIterator<Item = secp256k1::PublicKey>,
agg_nonce: MusigAggNonce,
key: &secp256k1::Keypair,
sec_nonce: MusigSecNonce,
sighash: [u8; 32],
tweak: Option<[u8; 32]>,
other_sigs: Option<&[MusigPartialSignature]>,
) -> (MusigPartialSignature, Option<schnorr::Signature>) {
// let agg = if let Some(tweak) = tweak {
// tweaked_key_agg(pubkeys, tweak).0
// } else {
// key_agg(pubkeys)
// };
pub fn get_agg_pubkey(key_agg_ctx: &KeyAggContext) -> PublicKey {
PublicKey::from_slice(
&key_agg_ctx
.aggregated_pubkey::<musig2::secp256k1::PublicKey>()
.serialize(),
)
.unwrap()
}

// let msg = zkp::Message::from_digest(sighash);
// let session = MusigSession::new(&SECP, &agg, agg_nonce, msg);
// let my_sig = session.partial_sign(&SECP, sec_nonce, &keypair_to(&key), &agg)
// .expect("nonce not reused");
// let final_sig = if let Some(others) = other_sigs {
// let mut sigs = Vec::with_capacity(others.len() + 1);
// sigs.extend_from_slice(others);
// sigs.push(my_sig);
// Some(session.partial_sig_agg(&sigs))
// } else {
// None
// };
([0u8;32] as MusigPartialSignature, None)
}
pub fn nonce_pair(
keypair: &secp256k1::Keypair,
rng: &mut impl Rng,
pks: Vec<PublicKey>,
) -> (MusigSecNonce, MusigPubNonce) {
let key_agg_ctx = create_key_agg_ctx(pks).unwrap();
let musig_pubkey =
musig2::secp256k1::PublicKey::from_slice(&keypair.public_key().serialize()).unwrap();
let idx = key_agg_ctx.pubkey_index(musig_pubkey).unwrap();
let agg_pubkey: musig2::secp256k1::PublicKey = key_agg_ctx.aggregated_pubkey();
let rnd = rng.gen::<[u8; 32]>();
let spices = SecNonceSpices::new().with_seckey(
musig2::secp256k1::SecretKey::from_slice(&keypair.secret_key().secret_bytes()).unwrap(),
);
let first_round = FirstRound::new(key_agg_ctx, rnd, idx, spices.clone()).unwrap();
// This part is also done when generating the first round, so I guess we can make it more
// efficient if we only store the nonce_seed since we can recreate everything using it.
let sec_nonce = SecNonce::build(rnd)
.with_pubkey(musig_pubkey)
.with_aggregated_pubkey(agg_pubkey)
.with_extra_input(&(idx as u32).to_be_bytes())
.with_spices(spices)
.build();
(sec_nonce.into(), first_round.our_public_nonce().into())
}

pub fn partial_sign(
pks: Vec<PublicKey>,
sec_nonce: MusigSecNonce,
agg_nonce: AggNonce,
keypair: &secp256k1::Keypair,
sighash: [u8; 32],
// tweak: Option<[u8; 32]>,
// other_sigs: Option<&[MusigPartialSignature]>,
) -> MusigPartialSignature {
let key_agg_ctx = create_key_agg_ctx(pks).unwrap();
let musig_sec_nonce = SecNonce::from_bytes(&sec_nonce).unwrap();
let partial_signature: [u8; 32] = sign_partial(
&key_agg_ctx,
musig2::secp256k1::SecretKey::from_slice(&keypair.secret_key().secret_bytes()).unwrap(),
musig_sec_nonce,
&agg_nonce,
&sighash,
)
.unwrap();
partial_signature
}
2 changes: 1 addition & 1 deletion core/src/operator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ where
/// Saves the utxo to the db
async fn set_operator_funding_utxo_rpc(
&self,
_funding_utxo: &OutPoint,
_funding_utxo: &OutPoint,
) -> Result<(), BridgeError> {
unimplemented!();
}
Expand Down
3 changes: 0 additions & 3 deletions core/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ lazy_static::lazy_static! {
XOnlyPublicKey::from_str("93c7378d96518a75448821c4f7c8f4bae7ce60f804d03d1f0628dd5dd0f5de51").unwrap();
}


pub fn calculate_merkle_root(leaves: Vec<HashType>) -> HashType {
let mut hashes = leaves;

Expand All @@ -59,8 +58,6 @@ pub fn calculate_merkle_root(leaves: Vec<HashType>) -> HashType {
hashes[0]
}



pub fn parse_hex_to_btc_tx(
tx_hex: &str,
) -> Result<bitcoin::blockdata::transaction::Transaction, bitcoin::consensus::encode::Error> {
Expand Down
Loading