diff --git a/crates/client/src/chain/goat_adaptor.rs b/crates/client/src/chain/goat_adaptor.rs index 288ed171..3f47702a 100644 --- a/crates/client/src/chain/goat_adaptor.rs +++ b/crates/client/src/chain/goat_adaptor.rs @@ -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; @@ -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>, - to_block: Option, + _to_block: Option, gate_way: IGatewayInstance, RootProvider>>, signer: EthereumWallet, } @@ -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, diff --git a/crates/client/src/client.rs b/crates/client/src/client.rs index 342ff458..224fb6ba 100644 --- a/crates/client/src/client.rs +++ b/crates/client/src/client.rs @@ -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; diff --git a/crates/identity/src/musig2.rs b/crates/identity/src/musig2.rs index 0f608652..c155b38a 100644 --- a/crates/identity/src/musig2.rs +++ b/crates/identity/src/musig2.rs @@ -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) } diff --git a/crates/store/src/localdb.rs b/crates/store/src/localdb.rs index 3026b7c9..9810406d 100644 --- a/crates/store/src/localdb.rs +++ b/crates/store/src/localdb.rs @@ -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 , @@ -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 = 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; @@ -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 = 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, diff --git a/crates/store/src/schema.rs b/crates/store/src/schema.rs index 02ea3d3b..2e3cea49 100644 --- a/crates/store/src/schema.rs +++ b/crates/store/src/schema.rs @@ -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, + pub partial_sigs: Vec<[String; COMMITTEE_PRE_SIGN_NUM]>, pub updated_at: i64, pub created_at: i64, } diff --git a/node/src/action.rs b/node/src/action.rs index 565809f1..edb548c1 100644 --- a/node/src/action.rs +++ b/node/src/action.rs @@ -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> { - Err("TODO".into()) - } - pub async fn get_committee_pubkeys( - client: &BitVM2Client, - instance_id: Uuid, - ) -> Result, Box> { - Err("TODO".into()) - } - pub async fn get_committee_partial_sigs( - client: &BitVM2Client, - instance_id: Uuid, - graph_id: Uuid, - ) -> Result, Box> { - Err("TODO".into()) - } - /// Determines whether the operator should participate in generating a new graph. /// /// Conditions: @@ -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? { @@ -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, @@ -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> { + pubkey: PublicKey, +) -> Result<(), Box> { 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, Box> { + 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()), } } @@ -1430,10 +1410,14 @@ pub async fn store_committee_partial_sigs( partial_sigs: [PartialSignature; COMMITTEE_PRE_SIGN_NUM], ) -> Result<(), Box> { let mut storage_process = client.local_db.acquire().await?; - let signs: Vec = partial_sigs.iter().map(|v| hex::encode(v.serialize())).collect(); + let signs_vec: Vec = 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| { + 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?) } @@ -1441,22 +1425,23 @@ pub async fn get_committee_partial_sigs( client: &BitVM2Client, instance_id: Uuid, graph_id: Uuid, -) -> Result<[PartialSignature; COMMITTEE_PRE_SIGN_NUM], Box> { +) -> Result, Box> { 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 = 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| { + let mut res: Vec<[PartialSignature; COMMITTEE_PRE_SIGN_NUM]> = vec![]; + for signs_item in nonce_collect.partial_sigs { + let signs_vec: Vec = 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| { format!("length wrong: expect {}, real {}", COMMITTEE_PRE_SIGN_NUM, v.len()) - })?; + })?) + } Ok(res) } } @@ -1509,6 +1494,7 @@ pub async fn store_graph( Ok(()) } +#[allow(dead_code)] pub async fn update_graph( client: &BitVM2Client, instance_id: Uuid, diff --git a/node/src/bitcoin/checker.rs b/node/src/bitcoin/checker.rs index 1a8d8a6c..48067174 100644 --- a/node/src/bitcoin/checker.rs +++ b/node/src/bitcoin/checker.rs @@ -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 { let dummy_block = match cli.get_block_hash(block_hei).await { Ok(bh) => bh, diff --git a/node/src/main.rs b/node/src/main.rs index fd16b252..d24cae97 100644 --- a/node/src/main.rs +++ b/node/src/main.rs @@ -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; @@ -191,7 +189,7 @@ async fn main() -> Result<(), Box> { 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!( diff --git a/node/src/metrics_service.rs b/node/src/metrics_service.rs index 6cf4837b..97970cbc 100644 --- a/node/src/metrics_service.rs +++ b/node/src/metrics_service.rs @@ -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(); @@ -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>, } @@ -47,10 +49,12 @@ async fn respond_with_metrics(state: State) -> impl IntoResponse type SharedRegistry = Arc>; 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) } diff --git a/node/src/rpc_service/bitvm2.rs b/node/src/rpc_service/bitvm2.rs index c416c26f..6d99bfaf 100644 --- a/node/src/rpc_service/bitvm2.rs +++ b/node/src/rpc_service/bitvm2.rs @@ -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, -} - #[derive(Debug, Deserialize)] pub struct GraphPresignCheckRequest { pub instance_id: String, @@ -88,18 +53,6 @@ pub struct GraphPresignCheckResponse { pub tx: Option, } -/// bridge-in: step3 -/// handler: relayer -#[derive(Debug, Deserialize)] -pub struct PegBTCMintRequest { - pub graph_ids: Vec, - 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 { diff --git a/node/src/rpc_service/handler/bitvm2_handler.rs b/node/src/rpc_service/handler/bitvm2_handler.rs index 4c12ce9d..20d869f5 100644 --- a/node/src/rpc_service/handler/bitvm2_handler.rs +++ b/node/src/rpc_service/handler/bitvm2_handler.rs @@ -67,83 +67,6 @@ pub async fn bridge_in_tx_prepare( } } -#[axum::debug_handler] -pub async fn create_graph( - State(app_state): State>, - Json(payload): Json, -) -> (StatusCode, Json) { - // TODO remove - let resp = GraphGenerateResponse { - instance_id: payload.instance_id.clone(), - graph_id: payload.graph_id.clone(), - graph_ipfs_unsigned_txns: "".to_string(), - }; - let mut resp_clone = resp.clone(); - let async_fn = || async move { - // TODO create graph - resp_clone.graph_ipfs_unsigned_txns = - "[https://ipfs.io/ipfs/QmXxwbk8eA2bmKBy7YEjm5w1zKiG7g6ebF1JYfqWvnLnhH/pegin.hex]" - .to_string(); - - let graph = Graph { - instance_id: Uuid::parse_str(&payload.instance_id)?, - graph_id: Uuid::parse_str(&payload.graph_id)?, - created_at: current_time_secs(), - updated_at: current_time_secs(), - ..Default::default() - }; - let mut storage_process = app_state.bitvm2_client.local_db.acquire().await?; - storage_process.update_graph(graph).await?; - Ok::>(resp_clone) - }; - match async_fn().await { - Ok(resp) => (StatusCode::OK, Json(resp)), - Err(err) => { - tracing::warn!("create_graph err:{:?}", err); - (StatusCode::INTERNAL_SERVER_ERROR, Json(resp)) - } - } -} - -#[axum::debug_handler] -pub async fn graph_presign( - Path(graph_id): Path, - State(app_state): State>, - Json(payload): Json, -) -> (StatusCode, Json) { - // TODO - let resp = GraphPresignResponse { - instance_id: payload.instance_id.clone(), - graph_id: graph_id.clone(), - graph_ipfs_committee_txns: vec![ - "https://ipfs.io/ipfs/QmXxwbk8eA2bmKBy7YEjm5w1zKiG7g6ebF1JYfqWvnLnhH/pegin.hex" - .to_string(), - ], - }; - let resp_clone = resp.clone(); - let async_fn = || async move { - //TODO update filed - let mut tx = app_state.bitvm2_client.local_db.start_transaction().await?; - let graph_id = Uuid::parse_str(&graph_id)?; - let instance_id = Uuid::parse_str(&payload.instance_id)?; - let mut instance = tx.get_instance(&instance_id).await?; - let mut graph = tx.get_graph(&graph_id).await?; - graph.graph_ipfs_base_url = payload.graph_ipfs_base_url; - instance.status = BridgeInStatus::Presigned.to_string(); - let _ = tx.update_instance(instance.clone()).await?; - let _ = tx.update_graph(graph.clone()).await?; - tx.commit().await?; - Ok::>(resp_clone) - }; - match async_fn().await { - Ok(resp) => (StatusCode::OK, Json(resp)), - Err(err) => { - tracing::warn!("graph_presign err:{:?}", err); - (StatusCode::INTERNAL_SERVER_ERROR, Json(resp)) - } - } -} - #[axum::debug_handler] pub async fn graph_presign_check( State(app_state): State>, @@ -177,30 +100,6 @@ pub async fn graph_presign_check( } } -#[axum::debug_handler] -pub async fn peg_btc_mint( - Path(instance_id): Path, - State(app_state): State>, - Json(payload): Json, -) -> (StatusCode, Json) { - // TODO remove - let async_fn = || async move { - let mut storage_process = app_state.bitvm2_client.local_db.acquire().await?; - let _graphs: Vec = storage_process.get_graphs(&payload.graph_ids).await?; - let instance_id = Uuid::parse_str(&instance_id)?; - let _instance = storage_process.get_instance(&instance_id).await?; - /// TODO create graph_ipfs_committee_sig - Ok::>(PegBTCMintResponse {}) - }; - match async_fn().await { - Ok(resp) => (StatusCode::OK, Json(resp)), - Err(err) => { - tracing::warn!("peg_btc_mint err:{:?}", err); - (StatusCode::INTERNAL_SERVER_ERROR, Json(PegBTCMintResponse {})) - } - } -} - #[axum::debug_handler] pub async fn create_instance( State(app_state): State>, diff --git a/node/src/rpc_service/mod.rs b/node/src/rpc_service/mod.rs index 66056891..235f5427 100644 --- a/node/src/rpc_service/mod.rs +++ b/node/src/rpc_service/mod.rs @@ -77,26 +77,20 @@ async fn root() -> &'static str { /// ///1.bridge-in: ///- front end call `bridge_in_tx_prepare`. step1 & step2.1. -///- backend action: -/// - call `create_graph` at step2.2; -/// - call `graph_presign` at step 2.3; -/// - call `peg_btc_mint` at step 3. +///- backend action create graph, presign graph, peg btc mint. ///- front end call `get_instance` to get the latest informationGet the latest information about bridge-in /// ///2.graph_overview: `graph_list` support /// ///3.node_overview: `get_nodes` support /// -///4.instance,graph query and update by api: `get_instance`, `get_graph`, `update_instance`,`update_graph` -/// -/// +///4.instance, graph query and update by api: `get_instance`, `get_graph`, `update_instance`,`update_graph` pub(crate) async fn serve( addr: String, db_path: String, registry: Arc>, ) -> anyhow::Result<()> { let app_state = AppState::create_arc_app_state(&db_path, registry).await?; - let add = app_state.clone(); let server = Router::new() .route("/", get(root)) .route("/v1/nodes", post(create_node)) @@ -109,13 +103,10 @@ pub(crate) async fn serve( .route("/v1/instances/{:id}", get(get_instance)) .route("/v1/instances/{:id}", put(update_instance)) .route("/v1/instances/action/bridge_in_tx_prepare", post(bridge_in_tx_prepare)) - .route("/v1/instances/{:id}/bridge_in/peg_gtc_mint", post(peg_btc_mint)) .route("/v1/instances/overview", get(get_instances_overview)) - .route("/v1/graphs", post(create_graph)) .route("/v1/graphs/{:id}", get(get_graph)) .route("/v1/graphs/{:id}", put(update_graph)) .route("/v1/graphs", get(get_graphs)) - .route("/v1/graphs/{:id}/presign", post(graph_presign)) .route("/v1/graphs/presign_check", post(graph_presign_check)) .route("/metrics", get(metrics_handler)) .layer(middleware::from_fn(print_req_and_resp_detail))