Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
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
18 changes: 7 additions & 11 deletions crates/client/src/chain/goat_adaptor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,12 @@ use crate::chain::goat_adaptor::IGateway::IGatewayInstance;
use alloy::primitives::TxHash;
use alloy::{
eips::BlockNumberOrTag,
network::{
Ethereum, EthereumWallet, NetworkWallet, TransactionBuilder, TxSigner, TxSignerSync,
eip2718::Encodable2718,
},
network::{Ethereum, EthereumWallet, NetworkWallet, eip2718::Encodable2718},
primitives::{Address as EvmAddress, Bytes, ChainId, FixedBytes, U256},
providers::{Provider, ProviderBuilder, RootProvider},
rpc::types::TransactionRequest,
signers::{Signer, local::PrivateKeySigner},
sol,
sol_types::SolEvent,
transports::http::{Client, Http, reqwest::Url},
};
use anyhow::format_err;
Expand Down Expand Up @@ -112,10 +108,10 @@ pub struct GoatInitConfig {
}
pub struct GoatAdaptor {
chain_id: ChainId,
gateway_address: EvmAddress,
gateway_creation_block: u64,
_gateway_address: EvmAddress,
_gateway_creation_block: u64,
provider: RootProvider<Http<Client>>,
to_block: Option<BlockNumberOrTag>,
_to_block: Option<BlockNumberOrTag>,
gate_way: IGatewayInstance<Http<Client>, RootProvider<Http<Client>>>,
signer: EthereumWallet,
}
Expand Down Expand Up @@ -555,10 +551,10 @@ impl GoatAdaptor {
};
let provider = ProviderBuilder::new().on_http(config.rpc_url);
Self {
gateway_address: config.gateway_address,
gateway_creation_block: config.gateway_creation_block,
_gateway_address: config.gateway_address,
_gateway_creation_block: config.gateway_creation_block,
provider: provider.clone(),
to_block: config.to_block,
_to_block: config.to_block,
gate_way: IGateway::new(config.gateway_address, provider),
signer: EthereumWallet::new(signer),
chain_id,
Expand Down
4 changes: 1 addition & 3 deletions crates/client/src/client.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
use crate::chain::chain::Chain;
use crate::chain::chain_adaptor::{
ChainAdaptor, GoatNetwork, OperatorData, PeginData, get_chain_adaptor,
};
use crate::chain::chain_adaptor::{GoatNetwork, OperatorData, PeginData, get_chain_adaptor};
use crate::chain::goat_adaptor::GoatInitConfig;
use crate::esplora::get_esplora_url;
use anyhow::format_err;
Expand Down
2 changes: 1 addition & 1 deletion crates/identity/src/musig2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ impl MuSig2StateMachine {
// all key pair can be represented by identity::keypair
pub fn generate_musig2_key() -> secp256k1::Keypair {
let secp = Secp256k1::new();
let (secret_key, public_key) = secp.generate_keypair(&mut rand::thread_rng());
let (secret_key, _) = secp.generate_keypair(&mut rand::thread_rng());
secp256k1::Keypair::from_secret_key(&secp, &secret_key)
}

Expand Down
8 changes: 5 additions & 3 deletions crates/store/src/localdb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -582,7 +582,7 @@ impl<'a> StorageProcessor<'a> {
graph_id: Uuid,
nonces: &[[String; COMMITTEE_PRE_SIGN_NUM]],
committee_pubkey: String,
partial_sigs: &[String],
partial_sigs: &[[String; COMMITTEE_PRE_SIGN_NUM]],
) -> anyhow::Result<()> {
let nonce_collect = sqlx::query_as!(
NonceCollect ,
Expand All @@ -597,7 +597,8 @@ impl<'a> StorageProcessor<'a> {
if let Some(nonce_collect) = nonce_collect {
let mut stored_nonces: Vec<[String; COMMITTEE_PRE_SIGN_NUM]> =
serde_json::from_str(&nonce_collect.nonces)?;
let mut stored_sigs: Vec<String> = serde_json::from_str(&nonce_collect.partial_sigs)?;
let mut stored_sigs: Vec<[String; COMMITTEE_PRE_SIGN_NUM]> =
serde_json::from_str(&nonce_collect.partial_sigs)?;
nonces.append(&mut stored_nonces);
partial_sigs.append(&mut stored_sigs);
created_at = nonce_collect.created_at;
Expand Down Expand Up @@ -633,7 +634,8 @@ impl<'a> StorageProcessor<'a> {
Some(nonce_collect) => {
let stored_nonces: Vec<[String; COMMITTEE_PRE_SIGN_NUM]> =
serde_json::from_str(&nonce_collect.nonces)?;
let stored_sigs: Vec<String> = serde_json::from_str(&nonce_collect.partial_sigs)?;
let stored_sigs: Vec<[String; COMMITTEE_PRE_SIGN_NUM]> =
serde_json::from_str(&nonce_collect.partial_sigs)?;
Ok(Some(NonceCollectMetaData {
instance_id,
graph_id,
Expand Down
2 changes: 1 addition & 1 deletion crates/store/src/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,7 @@ pub struct NonceCollectMetaData {
pub graph_id: Uuid,
pub nonces: Vec<[String; COMMITTEE_PRE_SIGN_NUM]>,
pub committee_pubkey: String,
pub partial_sigs: Vec<String>,
pub partial_sigs: Vec<[String; COMMITTEE_PRE_SIGN_NUM]>,
pub updated_at: i64,
pub created_at: i64,
}
92 changes: 39 additions & 53 deletions node/src/action.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,28 +233,6 @@ pub mod todo_funcs {
use std::io::{BufReader, BufWriter};
use std::path::Path;

/// Database related
pub async fn store_committee_pubkeys(
client: &BitVM2Client,
instance_id: Uuid,
pubkey: PublicKey,
) -> Result<(), Box<dyn std::error::Error>> {
Err("TODO".into())
}
pub async fn get_committee_pubkeys(
client: &BitVM2Client,
instance_id: Uuid,
) -> Result<Vec<PublicKey>, Box<dyn std::error::Error>> {
Err("TODO".into())
}
pub async fn get_committee_partial_sigs(
client: &BitVM2Client,
instance_id: Uuid,
graph_id: Uuid,
) -> Result<Vec<[PartialSignature; COMMITTEE_PRE_SIGN_NUM]>, Box<dyn std::error::Error>> {
Err("TODO".into())
}

/// Determines whether the operator should participate in generating a new graph.
///
/// Conditions:
Expand Down Expand Up @@ -781,23 +759,18 @@ pub async fn recv_and_dispatch(
committee_member_pubkey: keypair.public_key().into(),
committee_members_num: env::get_committee_member_num(),
});
todo_funcs::store_committee_pubkeys(
&client,
receive_data.instance_id,
keypair.public_key().into(),
)
.await?;
store_committee_pubkeys(&client, receive_data.instance_id, keypair.public_key().into())
.await?;
send_to_peer(swarm, GOATMessage::from_typed(Actor::All, &message_content)?)?;
}
(GOATMessageContent::CreateGraphPrepare(receive_data), Actor::Operator) => {
todo_funcs::store_committee_pubkeys(
store_committee_pubkeys(
&client,
receive_data.instance_id,
receive_data.committee_member_pubkey,
)
.await?;
let collected_keys =
todo_funcs::get_committee_pubkeys(&client, receive_data.instance_id).await?;
let collected_keys = get_committee_pubkeys(&client, receive_data.instance_id).await?;
if collected_keys.len() == receive_data.committee_members_num
&& todo_funcs::should_generate_graph(&client, &receive_data).await?
{
Expand Down Expand Up @@ -928,7 +901,7 @@ pub async fn recv_and_dispatch(
receive_data.committee_partial_sigs,
)
.await?;
let collected_partial_sigs = todo_funcs::get_committee_partial_sigs(
let collected_partial_sigs = get_committee_partial_sigs(
&client,
receive_data.instance_id,
receive_data.graph_id,
Expand Down Expand Up @@ -1406,19 +1379,26 @@ pub async fn get_committee_pub_nonces(
}
}

pub async fn get_committee_pubkey(
pub async fn store_committee_pubkeys(
client: &BitVM2Client,
instance_id: Uuid,
graph_id: Uuid,
) -> Result<PublicKey, Box<dyn std::error::Error>> {
pubkey: PublicKey,
) -> Result<(), Box<dyn std::error::Error>> {
let mut storage_process = client.local_db.acquire().await?;
match storage_process.get_nonces(instance_id, graph_id).await? {
None => {
Err(format!("instance id:{}, graph id:{} not found ", instance_id, graph_id).into())
}
Some(nonce_collect) => {
Ok(PublicKey::from_str(nonce_collect.committee_pubkey.as_str()).expect("decode pubkey"))
}
Ok(storage_process.store_pubkeys(instance_id, &vec![pubkey.to_string()]).await?)
}
pub async fn get_committee_pubkeys(
client: &BitVM2Client,
instance_id: Uuid,
) -> Result<Vec<PublicKey>, Box<dyn std::error::Error>> {
let mut storage_process = client.local_db.acquire().await?;
match storage_process.get_pubkeys(instance_id).await? {
None => Ok(vec![]),
Some(meta_data) => Ok(meta_data
.pubkeys
.iter()
.map(|v| PublicKey::from_str(v).expect("fail to decode to public key"))
.collect()),
}
}

Expand All @@ -1430,33 +1410,38 @@ pub async fn store_committee_partial_sigs(
partial_sigs: [PartialSignature; COMMITTEE_PRE_SIGN_NUM],
) -> Result<(), Box<dyn std::error::Error>> {
let mut storage_process = client.local_db.acquire().await?;
let signs: Vec<String> = partial_sigs.iter().map(|v| hex::encode(v.serialize())).collect();
let signs_vec: Vec<String> = partial_sigs.iter().map(|v| hex::encode(v.serialize())).collect();
let signs_arr: [String; COMMITTEE_PRE_SIGN_NUM] =
signs_vec.try_into().map_err(|v: Vec<String>| {
format!("length wrong: expect {}, real {}", COMMITTEE_PRE_SIGN_NUM, v.len())
})?;

Ok(storage_process
.store_nonces(instance_id, graph_id, &[], committee_pubkey.to_string(), &signs)
.store_nonces(instance_id, graph_id, &[], committee_pubkey.to_string(), &vec![signs_arr])
.await?)
}

pub async fn get_committee_partial_sigs(
client: &BitVM2Client,
instance_id: Uuid,
graph_id: Uuid,
) -> Result<[PartialSignature; COMMITTEE_PRE_SIGN_NUM], Box<dyn std::error::Error>> {
) -> Result<Vec<[PartialSignature; COMMITTEE_PRE_SIGN_NUM]>, Box<dyn std::error::Error>> {
let mut storage_process = client.local_db.acquire().await?;
match storage_process.get_nonces(instance_id, graph_id).await? {
None => {
Err(format!("instance id:{}, graph id:{} not found ", instance_id, graph_id).into())
}
Some(nonce_collect) => {
let signs_vec: Vec<PartialSignature> = nonce_collect
.partial_sigs
.iter()
.map(|v| PartialSignature::from_hex(v).expect("failed to decode partial sigs"))
.collect();
let res: [PartialSignature; COMMITTEE_PRE_SIGN_NUM] =
signs_vec.try_into().map_err(|v: Vec<PartialSignature>| {
let mut res: Vec<[PartialSignature; COMMITTEE_PRE_SIGN_NUM]> = vec![];
for signs_item in nonce_collect.partial_sigs {
let signs_vec: Vec<PartialSignature> = signs_item
.iter()
.map(|v| PartialSignature::from_str(v).expect("fail to decode pub nonce"))
.collect();
res.push(signs_vec.try_into().map_err(|v: Vec<PartialSignature>| {
format!("length wrong: expect {}, real {}", COMMITTEE_PRE_SIGN_NUM, v.len())
})?;
})?)
}
Ok(res)
}
}
Expand Down Expand Up @@ -1509,6 +1494,7 @@ pub async fn store_graph(
Ok(())
}

#[allow(dead_code)]
pub async fn update_graph(
client: &BitVM2Client,
instance_id: Uuid,
Expand Down
2 changes: 1 addition & 1 deletion node/src/bitcoin/checker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ use anyhow::{Result, bail};
use bitcoin::hashes::Hash;
use bitcoin::{Amount, Block, Network, Transaction, Txid};
use esplora_client::AsyncClient;
use futures::StreamExt;
use spv::verify_merkle_proof;
use spv::{BitcoinMerkleTree, CircuitBlockHeader, CircuitTransaction, MMRGuest, MMRHost, SPV};

/// Fetch block at specific height
#[allow(dead_code)]
pub async fn fetch_block(cli: &AsyncClient, block_hei: u32) -> Result<Block> {
let dummy_block = match cli.get_block_hash(block_hei).await {
Ok(bh) => bh,
Expand Down
6 changes: 2 additions & 4 deletions node/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,7 @@ use std::str::FromStr;
use std::sync::{Arc, Mutex};
use std::{error::Error, net::Ipv4Addr, time::Duration};
use tokio::{io, io::AsyncBufReadExt, select};

use tracing_subscriber::{EnvFilter, Layer, util::SubscriberInitExt};

use tracing_subscriber::EnvFilter;
use zeroize::Zeroizing;

use bitvm2_lib::actors::Actor;
Expand Down Expand Up @@ -191,7 +189,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
swarm.listen_on("/ip4/0.0.0.0/tcp/0".parse()?)?;

// run a http server for front-end
let address = loop {
let _address = loop {
if let SwarmEvent::NewListenAddr { address, .. } = swarm.select_next_some().await {
if address.iter().any(|e| e == Protocol::Ip4(Ipv4Addr::LOCALHOST)) {
tracing::debug!(
Expand Down
4 changes: 4 additions & 0 deletions node/src/metrics_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ use tokio::time::Instant;

const METRICS_CONTENT_TYPE: &str = "application/openmetrics-text;charset=utf-8;version=1.0.0";

#[allow(dead_code)]
pub(crate) async fn metrics_server(registry: Registry) -> Result<(), std::io::Error> {
// Serve on localhost.
let addr: SocketAddr = ([127, 0, 0, 1], 0).into();
Expand All @@ -33,6 +34,7 @@ pub(crate) async fn metrics_server(registry: Registry) -> Result<(), std::io::Er
}

#[derive(Clone)]
#[allow(dead_code)]
pub(crate) struct MetricService {
reg: Arc<Mutex<Registry>>,
}
Expand All @@ -47,10 +49,12 @@ async fn respond_with_metrics(state: State<MetricService>) -> impl IntoResponse
type SharedRegistry = Arc<Mutex<Registry>>;

impl MetricService {
#[allow(dead_code)]
fn new(registry: Registry) -> Self {
Self { reg: Arc::new(Mutex::new(registry)) }
}

#[allow(dead_code)]
fn get_reg(&self) -> SharedRegistry {
Arc::clone(&self.reg)
}
Expand Down
47 changes: 0 additions & 47 deletions node/src/rpc_service/bitvm2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,41 +40,6 @@ pub struct BridgeInTransactionPreparerRequest {
#[derive(Deserialize, Serialize)]
pub struct BridgeInTransactionPrepareResponse {}

/// bridge-in step2.2 BridgeInTransactionPrepare
/// deps: BridgeInTransactionPrepare
/// handler: Operator creates a graph record in database and broadcast the new graph to peers
/// calculate staking amount according to the peg-in amount
#[derive(Debug, Deserialize)]
pub struct GraphGenerateRequest {
pub instance_id: String, // UUID
pub graph_id: String,
}

// UI can go next(step2.3) once one operator responds
#[derive(Deserialize, Serialize, Clone, Default)]
pub struct GraphGenerateResponse {
pub instance_id: String,
pub graph_id: String,
// unsigned_txns, operator signature, this steps ask operator to publish unsigned txns
pub graph_ipfs_unsigned_txns: String,
}

/// bridge-in step 2.3
/// handler: committee
#[derive(Debug, Deserialize)]
pub struct GraphPresignRequest {
pub instance_id: String,
pub graph_ipfs_base_url: String, // the root directory of all graph_ipfs_* files
}

// Committee publishs txn signatures in ipfs url
#[derive(Clone, Deserialize, Serialize)]
pub struct GraphPresignResponse {
pub instance_id: String,
pub graph_id: String,
pub graph_ipfs_committee_txns: Vec<String>,
}

#[derive(Debug, Deserialize)]
pub struct GraphPresignCheckRequest {
pub instance_id: String,
Expand All @@ -88,18 +53,6 @@ pub struct GraphPresignCheckResponse {
pub tx: Option<Instance>,
}

/// bridge-in: step3
/// handler: relayer
#[derive(Debug, Deserialize)]
pub struct PegBTCMintRequest {
pub graph_ids: Vec<String>,
pub pegin_txid: String,
// TODO: https://github.com/GOATNetwork/bitvm2-L2-contracts/blob/main/contracts/Gateway.sol#L43
}

#[derive(Deserialize, Serialize)]
pub struct PegBTCMintResponse {}

/// get tx detail
#[derive(Debug, Deserialize)]
pub struct InstanceListRequest {
Expand Down
Loading
Loading