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

Implement new RPC functions in gRPC #359

Merged
merged 15 commits into from
Nov 5, 2024
29 changes: 26 additions & 3 deletions core/src/aggregator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use crate::{
aggregate_nonces, aggregate_partial_signatures, AggregateFromPublicKeys, MuSigAggNonce,
MuSigPartialSignature, MuSigPubNonce,
},
rpc::clementine::clementine_verifier_client::ClementineVerifierClient,
traits::rpc::AggregatorServer,
utils::handle_taproot_witness_new,
ByteArray32, ByteArray66, EVMAddress, UTXO,
Expand All @@ -16,6 +17,7 @@ use bitcoin::{address::NetworkUnchecked, Address, OutPoint};
use bitcoin::{hashes::Hash, Txid};
use bitcoincore_rpc::RawTx;
use secp256k1::schnorr;
use tonic::transport::Uri;

/// Aggregator struct.
/// This struct is responsible for aggregating partial signatures from the verifiers.
Expand All @@ -27,22 +29,43 @@ use secp256k1::schnorr;
/// For now, we do not have the last bit.
#[derive(Debug, Clone)]
pub struct Aggregator {
config: BridgeConfig,
nofn_xonly_pk: secp256k1::XOnlyPublicKey,
pub(crate) config: BridgeConfig,
pub(crate) nofn_xonly_pk: secp256k1::XOnlyPublicKey,
pub(crate) verifier_clients: Vec<ClementineVerifierClient<tonic::transport::Channel>>,
}

impl Aggregator {
#[tracing::instrument(err(level = tracing::Level::ERROR), ret(level = tracing::Level::TRACE))]
// #[tracing::instrument(err(level = tracing::Level::ERROR), ret(level = tracing::Level::TRACE))]
pub async fn new(config: BridgeConfig) -> Result<Self, BridgeError> {
let nofn_xonly_pk = secp256k1::XOnlyPublicKey::from_musig2_pks(
config.verifiers_public_keys.clone(),
None,
false,
);

tracing::info!(
"Aggregator initialized with verifiers: {:?}",
config.verifier_endpoints
);

let verifier_clients =
futures::future::try_join_all(config.verifier_endpoints.clone().unwrap().iter().map(
|endpoint| {
let endpoint_clone = endpoint.clone();
async move {
let uri = Uri::try_from(endpoint_clone).unwrap(); // handle unwrap safely in real code
let client = ClementineVerifierClient::connect(uri).await.unwrap();
Ok::<_, Box<dyn std::error::Error>>(client)
}
},
))
.await
.unwrap();

Ok(Aggregator {
config,
nofn_xonly_pk,
verifier_clients,
})
}

Expand Down
13 changes: 13 additions & 0 deletions core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,19 @@ pub type InscriptionTxs = (OutPoint, Txid);
#[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct EVMAddress(#[serde(with = "hex::serde")] pub [u8; 20]);

impl TryFrom<Vec<u8>> for EVMAddress {
type Error = &'static str;

fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
if value.len() == 20 {
let mut arr = [0u8; 20];
arr.copy_from_slice(&value);
Ok(EVMAddress(arr))
} else {
Err("Expected a Vec<u8> of length 20")
}
}
}
/// Type alias for withdrawal payment, HashType is taproot script hash
// pub type WithdrawalPayment = (Txid, HashType);

Expand Down
2 changes: 1 addition & 1 deletion core/src/mock/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ pub async fn create_test_config(db_name: &str, config_file: &str) -> BridgeConfi
initialize_logger(5).unwrap();

let mut config = common::get_test_config(config_file).unwrap();
config.db_name = db_name.to_owned();
config.db_name = db_name.to_string();
Database::initialize_database(&config).await.unwrap();

config
Expand Down
15 changes: 3 additions & 12 deletions core/src/musig2.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::{errors::BridgeError, ByteArray32, ByteArray64, ByteArray66};
use bitcoin::hashes::Hash;
use bitcoin::TapNodeHash;
use musig2::{sign_partial, AggNonce, KeyAggContext, SecNonce, SecNonceSpices};
use musig2::{sign_partial, AggNonce, KeyAggContext, SecNonce};
use secp256k1::{rand::Rng, PublicKey};

// We can directly use the musig2 crate for this
Expand Down Expand Up @@ -121,20 +121,11 @@ pub fn aggregate_partial_signatures(
// see https://medium.com/blockstream/musig-dn-schnorr-multisignatures-with-verifiably-deterministic-nonces-27424b5df9d6#e3b6.
#[tracing::instrument(skip(rng), ret(level = tracing::Level::TRACE))]
pub fn nonce_pair(
keypair: &secp256k1::Keypair,
keypair: &secp256k1::Keypair, // TODO: Remove this field
rng: &mut impl Rng,
) -> (MuSigSecNonce, MuSigPubNonce) {
let musig_pubkey: musig2::secp256k1::PublicKey =
musig2::secp256k1::PublicKey::from_slice(&keypair.public_key().serialize()).unwrap();
let rnd = rng.gen::<[u8; 32]>();
let spices = SecNonceSpices::new().with_seckey(
musig2::secp256k1::SecretKey::from_slice(&keypair.secret_key().secret_bytes()).unwrap(),
);

let sec_nonce = SecNonce::build(rnd)
.with_pubkey(musig_pubkey)
.with_spices(spices)
.build();
let sec_nonce = SecNonce::build(rnd).build();

let pub_nonce = ByteArray66(sec_nonce.public_nonce().into());
let sec_nonce: [u8; 64] = sec_nonce.into();
Expand Down
2 changes: 1 addition & 1 deletion core/src/operator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ where
R: RpcApiWrapper,
{
/// Creates a new `Operator`.
#[tracing::instrument(skip_all, err(level = tracing::Level::ERROR))]
// #[tracing::instrument(skip_all, err(level = tracing::Level::ERROR))]
pub async fn new(config: BridgeConfig, rpc: ExtendedRpc<R>) -> Result<Self, BridgeError> {
// let num_verifiers = config.verifiers_public_keys.len();

Expand Down
Loading
Loading