diff --git a/crates/bitvm2/src/committee/api.rs b/crates/bitvm2/src/committee/api.rs index 442315fe..5da72cbf 100644 --- a/crates/bitvm2/src/committee/api.rs +++ b/crates/bitvm2/src/committee/api.rs @@ -1,7 +1,7 @@ use crate::types::Bitvm2Graph; -use anyhow::{Result, bail}; +use anyhow::{bail, Result}; use bitcoin::PublicKey; -use bitcoin::{TapSighashType, Witness, hex::FromHex, key::Keypair}; +use bitcoin::{hex::FromHex, key::Keypair, TapSighashType, Witness}; use goat::connectors::{connector_0::Connector0, connector_5::Connector5, connector_d::ConnectorD}; use goat::contexts::base::generate_n_of_n_public_key; use goat::transactions::signing_musig2::{ @@ -11,7 +11,7 @@ use goat::transactions::{ base::BaseTransaction, pre_signed::PreSignedTransaction, pre_signed_musig2::get_nonce_message, signing_musig2::generate_taproot_partial_signature, }; -use musig2::{AggNonce, PartialSignature, PubNonce, SecNonce, secp256k1::schnorr::Signature}; +use musig2::{secp256k1::schnorr::Signature, AggNonce, PartialSignature, PubNonce, SecNonce}; use sha2::{Digest, Sha256}; pub const COMMITTEE_PRE_SIGN_NUM: usize = 5; diff --git a/crates/bitvm2/src/committee/mod.rs b/crates/bitvm2/src/committee/mod.rs index 3a281e03..3b048931 100644 --- a/crates/bitvm2/src/committee/mod.rs +++ b/crates/bitvm2/src/committee/mod.rs @@ -1,7 +1,7 @@ mod api; pub use api::{ - COMMITTEE_PRE_SIGN_NUM, committee_pre_sign, generate_keypair_from_seed, - generate_nonce_from_seed, key_aggregation, nonce_aggregation, nonces_aggregation, - push_committee_pre_signatures, signature_aggregation_and_push, + committee_pre_sign, generate_keypair_from_seed, generate_nonce_from_seed, key_aggregation, + nonce_aggregation, nonces_aggregation, push_committee_pre_signatures, + signature_aggregation_and_push, COMMITTEE_PRE_SIGN_NUM, }; diff --git a/crates/bitvm2/src/keys.rs b/crates/bitvm2/src/keys.rs index fcd2f41d..597f2edd 100644 --- a/crates/bitvm2/src/keys.rs +++ b/crates/bitvm2/src/keys.rs @@ -1,10 +1,10 @@ use super::{ - committee::{COMMITTEE_PRE_SIGN_NUM, generate_keypair_from_seed, generate_nonce_from_seed}, + committee::{generate_keypair_from_seed, generate_nonce_from_seed, COMMITTEE_PRE_SIGN_NUM}, operator::generate_wots_keys, types::{WotsPublicKeys, WotsSecretKeys}, }; use bitcoin::key::Keypair; -use musig2::{PubNonce, SecNonce, secp256k1::schnorr::Signature}; +use musig2::{secp256k1::schnorr::Signature, PubNonce, SecNonce}; use sha2::{Digest, Sha256}; use uuid::Uuid; diff --git a/crates/bitvm2/src/operator/api.rs b/crates/bitvm2/src/operator/api.rs index f29a52b9..5b8cbe74 100644 --- a/crates/bitvm2/src/operator/api.rs +++ b/crates/bitvm2/src/operator/api.rs @@ -1,19 +1,19 @@ use crate::types::{ - Bitvm2Graph, Bitvm2Parameters, CustomInputs, Groth16Proof, Groth16WotsPublicKeys, - Groth16WotsSignatures, PublicInputs, VerifyingKey, WotsPublicKeys, WotsSecretKeys, - get_magic_bytes, + get_magic_bytes, Bitvm2Graph, Bitvm2Parameters, CustomInputs, Groth16Proof, + Groth16WotsPublicKeys, Groth16WotsSignatures, PublicInputs, VerifyingKey, WotsPublicKeys, + WotsSecretKeys, }; -use anyhow::{Result, bail}; +use anyhow::{bail, Result}; use bitcoin::Transaction; -use bitcoin::{Amount, OutPoint, Witness, XOnlyPublicKey, key::Keypair}; +use bitcoin::{key::Keypair, Amount, OutPoint, Witness, XOnlyPublicKey}; use bitvm::chunk::api::{ - NUM_HASH, NUM_PUBS, NUM_U256, api_generate_full_tapscripts, api_generate_partial_script, - generate_signatures_lit, type_conversion_utils::utils_raw_witnesses_from_signatures, + api_generate_full_tapscripts, api_generate_partial_script, generate_signatures_lit, + type_conversion_utils::utils_raw_witnesses_from_signatures, NUM_HASH, NUM_PUBS, NUM_U256, }; use bitvm::signatures::{ - signing_winternitz::{LOG_D, WinternitzPublicKey, WinternitzSecret, WinternitzSigningInputs}, + signing_winternitz::{WinternitzPublicKey, WinternitzSecret, WinternitzSigningInputs, LOG_D}, winternitz::Parameters, - wots_api::{wots_hash, wots256}, + wots_api::{wots256, wots_hash}, }; use bitvm::treepp::*; use goat::commitments::{CommitmentMessageId, KICKOFF_MSG_SIZE, NUM_KICKOFF}; @@ -28,8 +28,8 @@ use goat::transactions::{ assert::assert_final::AssertFinalTransaction, assert::assert_initial::AssertInitialTransaction, assert::utils::{ - AllCommitConnectorsE, AssertCommitConnectorsF, COMMIT_TX_NUM, - convert_to_connector_c_commits_public_key, + convert_to_connector_c_commits_public_key, AllCommitConnectorsE, AssertCommitConnectorsF, + COMMIT_TX_NUM, }, base::Input, challenge::ChallengeTransaction, diff --git a/crates/bitvm2/src/pegin.rs b/crates/bitvm2/src/pegin.rs index 0b355ac1..4b4e1925 100644 --- a/crates/bitvm2/src/pegin.rs +++ b/crates/bitvm2/src/pegin.rs @@ -1,6 +1,6 @@ use bitcoin::opcodes::all::OP_RETURN; use bitcoin::script::Instruction; -use bitcoin::{Network, Script, script}; +use bitcoin::{script, Network, Script}; use crate::types::get_magic_bytes; diff --git a/crates/bitvm2/src/types.rs b/crates/bitvm2/src/types.rs index 7615966f..ad55ab66 100644 --- a/crates/bitvm2/src/types.rs +++ b/crates/bitvm2/src/types.rs @@ -1,7 +1,7 @@ use bitcoin::TapNodeHash; -use bitcoin::{Address, Amount, Network, PrivateKey, PublicKey, XOnlyPublicKey, key::Keypair}; +use bitcoin::{key::Keypair, Address, Amount, Network, PrivateKey, PublicKey, XOnlyPublicKey}; use bitvm::chunk::api::{ - NUM_HASH, NUM_PUBS, NUM_U256, PublicKeys as ApiWotsPublicKeys, Signatures as ApiWotsSignatures, + PublicKeys as ApiWotsPublicKeys, Signatures as ApiWotsSignatures, NUM_HASH, NUM_PUBS, NUM_U256, }; use bitvm::signatures::signing_winternitz::{WinternitzPublicKey, WinternitzSecret}; use goat::commitments::NUM_KICKOFF; @@ -15,7 +15,7 @@ use goat::transactions::{ kick_off::KickOffTransaction, peg_in::peg_in::PegInTransaction, peg_out_confirm::PreKickoffTransaction, take_1::Take1Transaction, take_2::Take2Transaction, }; -use rand::{Rng, distributions::Alphanumeric}; +use rand::{distributions::Alphanumeric, Rng}; use secp256k1::SECP256K1; use serde::{Deserialize, Serialize}; @@ -172,7 +172,7 @@ pub fn get_magic_bytes(net: &Network) -> Vec { } pub mod node_serializer { - use serde::{self, Deserialize, Deserializer, Serializer, ser::Error}; + use serde::{self, ser::Error, Deserialize, Deserializer, Serializer}; use std::str::FromStr; pub mod address { @@ -203,7 +203,7 @@ pub mod node_serializer { use crate::types::WotsPublicKeys; use bitvm::chunk::api::{NUM_HASH, NUM_PUBS, NUM_U256}; use bitvm::signatures::signing_winternitz::WinternitzPublicKey; - use bitvm::signatures::wots_api::{wots_hash, wots256}; + use bitvm::signatures::wots_api::{wots256, wots_hash}; use goat::commitments::NUM_KICKOFF; use std::collections::HashMap; @@ -214,17 +214,17 @@ pub mod node_serializer { let mut pubkeys_map: HashMap>> = HashMap::new(); let mut index = 0; // wots pk for groth16 proof - for pk in pubkeys.1.0 { + for pk in pubkeys.1 .0 { let v: Vec> = pk.iter().map(|x| x.to_vec()).collect(); pubkeys_map.insert(index, v); index += 1; } - for pk in pubkeys.1.1 { + for pk in pubkeys.1 .1 { let v: Vec> = pk.iter().map(|x| x.to_vec()).collect(); pubkeys_map.insert(index, v); index += 1; } - for pk in pubkeys.1.2 { + for pk in pubkeys.1 .2 { let v: Vec> = pk.iter().map(|x| x.to_vec()).collect(); pubkeys_map.insert(index, v); index += 1; @@ -359,11 +359,11 @@ pub mod node_serializer { pub mod wots_seckeys { use serde::de::{SeqAccess, Visitor}; use serde::ser::SerializeTuple; - use serde::{Deserializer, Serializer, de::Error as DeError, ser::Error}; + use serde::{de::Error as DeError, ser::Error, Deserializer, Serializer}; use std::fmt; use crate::types::{ - Groth16WotsSecretKeys, KickoffWotsSecretKeys, NUM_KICKOFF, NUM_SIGS, WotsSecretKeys, + Groth16WotsSecretKeys, KickoffWotsSecretKeys, WotsSecretKeys, NUM_KICKOFF, NUM_SIGS, }; pub fn serialize(keys: &WotsSecretKeys, serializer: S) -> Result @@ -445,7 +445,7 @@ pub mod node_serializer { #[cfg(test)] mod tests { use crate::operator::generate_wots_keys; - use crate::types::{WotsPublicKeys, WotsSecretKeys, node_serializer}; + use crate::types::{node_serializer, WotsPublicKeys, WotsSecretKeys}; use serde::{Deserialize, Serialize}; use std::fmt::Debug; diff --git a/crates/bitvm2/src/verifier/api.rs b/crates/bitvm2/src/verifier/api.rs index b2c3a38a..949cd585 100644 --- a/crates/bitvm2/src/verifier/api.rs +++ b/crates/bitvm2/src/verifier/api.rs @@ -1,15 +1,14 @@ use crate::types::{ Bitvm2Graph, Groth16WotsPublicKeys, Groth16WotsSignatures, VerifyingKey, WotsPublicKeys, }; -use anyhow::{Result, bail}; +use anyhow::{bail, Result}; use bitcoin::{Address, Amount, Transaction}; use bitvm::chunk::api::{ - NUM_TAPS, - type_conversion_utils::{RawWitness, script_to_witness, utils_signatures_from_raw_witnesses}, - validate_assertions, + type_conversion_utils::{script_to_witness, utils_signatures_from_raw_witnesses, RawWitness}, + validate_assertions, NUM_TAPS, }; use bitvm::treepp::*; -use goat::connectors::connector_c::{ConnectorC, get_commit_from_assert_commit_tx}; +use goat::connectors::connector_c::{get_commit_from_assert_commit_tx, ConnectorC}; use goat::transactions::assert::utils::*; use goat::transactions::{base::BaseTransaction, pre_signed::PreSignedTransaction}; diff --git a/crates/client/src/chain/goat_adaptor.rs b/crates/client/src/chain/goat_adaptor.rs index 3f47702a..f3c449a8 100644 --- a/crates/client/src/chain/goat_adaptor.rs +++ b/crates/client/src/chain/goat_adaptor.rs @@ -5,13 +5,13 @@ use crate::chain::goat_adaptor::IGateway::IGatewayInstance; use alloy::primitives::TxHash; use alloy::{ eips::BlockNumberOrTag, - network::{Ethereum, EthereumWallet, NetworkWallet, eip2718::Encodable2718}, + network::{eip2718::Encodable2718, Ethereum, EthereumWallet, NetworkWallet}, primitives::{Address as EvmAddress, Bytes, ChainId, FixedBytes, U256}, providers::{Provider, ProviderBuilder, RootProvider}, rpc::types::TransactionRequest, - signers::{Signer, local::PrivateKeySigner}, + signers::{local::PrivateKeySigner, Signer}, sol, - transports::http::{Client, Http, reqwest::Url}, + transports::http::{reqwest::Url, Client, Http}, }; use anyhow::format_err; use async_trait::async_trait; @@ -282,7 +282,7 @@ impl ChainAdaptor for GoatAdaptor { .await?; Ok(WithdrawData { pegin_txid: res._0.0, - operator_address: res._1.0.0, + operator_address: res._1.0 .0, status: res._2.into(), instance_id: Uuid::from_slice(res._3.as_slice())?, lock_amount: res._4, diff --git a/crates/client/src/client.rs b/crates/client/src/client.rs index db89b721..e7f1b0a5 100644 --- a/crates/client/src/client.rs +++ b/crates/client/src/client.rs @@ -1,6 +1,6 @@ use crate::chain::chain::Chain; use crate::chain::chain_adaptor::{ - BitcoinTx, GoatNetwork, OperatorData, PeginData, get_chain_adaptor, + get_chain_adaptor, BitcoinTx, GoatNetwork, OperatorData, PeginData, }; use crate::chain::goat_adaptor::GoatInitConfig; use crate::esplora::get_esplora_url; diff --git a/crates/identity/src/musig2.rs b/crates/identity/src/musig2.rs index c155b38a..4ddd46b8 100644 --- a/crates/identity/src/musig2.rs +++ b/crates/identity/src/musig2.rs @@ -2,8 +2,8 @@ use rand::RngCore; use secp256k1::{Secp256k1, SecretKey}; use std::string::String; -use musig2::KeyAggContext; use musig2::k256::PublicKey; +use musig2::KeyAggContext; use musig2::{ CompactSignature, FirstRound, PartialSignature, PubNonce, SecNonceSpices, SecondRound, }; diff --git a/crates/spv/src/header_chain.rs b/crates/spv/src/header_chain.rs index c1d980fc..3ac756af 100644 --- a/crates/spv/src/header_chain.rs +++ b/crates/spv/src/header_chain.rs @@ -1,7 +1,7 @@ use bitcoin::{ - BlockHash, CompactTarget, TxMerkleNode, block::{Header, Version}, hashes::Hash, + BlockHash, CompactTarget, TxMerkleNode, }; use borsh::{BorshDeserialize, BorshSerialize}; use serde::{Deserialize, Serialize}; diff --git a/crates/spv/src/merkle_tree.rs b/crates/spv/src/merkle_tree.rs index 7fed80ee..bb58ecc4 100644 --- a/crates/spv/src/merkle_tree.rs +++ b/crates/spv/src/merkle_tree.rs @@ -137,9 +137,9 @@ pub fn verify_merkle_proof( mod tests { use crate::transaction::CircuitTransaction; - use bitcoin::Block; use bitcoin::hashes::Hash; use bitcoin::hex::FromHex; + use bitcoin::Block; use super::*; diff --git a/crates/store/src/ipfs.rs b/crates/store/src/ipfs.rs index c18a72ed..3c3fc98b 100644 --- a/crates/store/src/ipfs.rs +++ b/crates/store/src/ipfs.rs @@ -1,7 +1,7 @@ -use anyhow::{Result, bail}; +use anyhow::{bail, Result}; use futures::TryStreamExt; -use reqwest::Client; use reqwest::multipart::{Form, Part}; +use reqwest::Client; use serde::Deserialize; use std::path::Path; use tokio::fs::File; diff --git a/crates/store/src/localdb.rs b/crates/store/src/localdb.rs index 9810406d..88602945 100644 --- a/crates/store/src/localdb.rs +++ b/crates/store/src/localdb.rs @@ -1,13 +1,13 @@ use crate::schema::NODE_STATUS_OFFLINE; use crate::schema::NODE_STATUS_ONLINE; use crate::{ - COMMITTEE_PRE_SIGN_NUM, GrapRpcQueryData, Graph, Instance, Message, Node, NodesOverview, - NonceCollect, NonceCollectMetaData, PubKeyCollect, PubKeyCollectMetaData, + GrapRpcQueryData, Graph, Instance, Message, Node, NodesOverview, NonceCollect, + NonceCollectMetaData, PubKeyCollect, PubKeyCollectMetaData, COMMITTEE_PRE_SIGN_NUM, }; use sqlx::migrate::Migrator; use sqlx::pool::PoolConnection; use sqlx::types::Uuid; -use sqlx::{Row, Sqlite, SqliteConnection, SqlitePool, Transaction, migrate::MigrateDatabase}; +use sqlx::{migrate::MigrateDatabase, Row, Sqlite, SqliteConnection, SqlitePool, Transaction}; use std::time::{SystemTime, UNIX_EPOCH}; #[derive(Clone)] diff --git a/node/src/action.rs b/node/src/action.rs index d88623ba..a4dffc07 100644 --- a/node/src/action.rs +++ b/node/src/action.rs @@ -3,7 +3,7 @@ use crate::middleware::AllBehaviours; use crate::rpc_service::current_time_secs; use anyhow::Result; use bitcoin::PublicKey; -use bitcoin::{Amount, Network, OutPoint, Txid, key::Keypair}; +use bitcoin::{key::Keypair, Amount, Network, OutPoint, Txid}; use bitvm2_lib::actors::Actor; use bitvm2_lib::keys::*; use bitvm2_lib::types::{ @@ -17,7 +17,7 @@ use goat::transactions::take_1::Take1Transaction; use goat::transactions::take_2::Take2Transaction; use goat::transactions::{assert::utils::COMMIT_TX_NUM, pre_signed::PreSignedTransaction}; use libp2p::gossipsub::MessageId; -use libp2p::{PeerId, Swarm, gossipsub}; +use libp2p::{gossipsub, PeerId, Swarm}; use musig2::{AggNonce, PartialSignature, PubNonce, SecNonce}; use reqwest::Request; use serde::de::DeserializeOwned; @@ -223,7 +223,7 @@ pub mod todo_funcs { use bitcoin::{ Address, EcdsaSighashType, ScriptBuf, Sequence, Transaction, TxIn, TxOut, Witness, }; - use bitcoin_script::{Script, script}; + use bitcoin_script::{script, Script}; use bitvm::chunk::api::NUM_TAPS; use bitvm2_lib::types::WotsPublicKeys; use client::chain::chain_adaptor::WithdrawStatus; diff --git a/node/src/bitcoin/checker.rs b/node/src/bitcoin/checker.rs index 48067174..7e68ce99 100644 --- a/node/src/bitcoin/checker.rs +++ b/node/src/bitcoin/checker.rs @@ -1,4 +1,4 @@ -use anyhow::{Result, bail}; +use anyhow::{bail, Result}; use bitcoin::hashes::Hash; use bitcoin::{Amount, Block, Network, Transaction, Txid}; use esplora_client::AsyncClient; @@ -139,7 +139,7 @@ pub async fn check_pegin_tx( mod tests { use super::*; use esplora_client::Builder; - use futures::{StreamExt, stream}; + use futures::{stream, StreamExt}; #[tokio::test] async fn test_check_pegin_tx() { // tx: https://mempool.space/testnet/tx/e413208c6644d51f4f3adf3a5aad425da817ac825e56352e7164de1e2a4d9394 diff --git a/node/src/env.rs b/node/src/env.rs index cfb916df..a9893039 100644 --- a/node/src/env.rs +++ b/node/src/env.rs @@ -1,6 +1,6 @@ use alloy::eips::BlockNumberOrTag; use alloy::primitives::Address as EvmAddress; -use bitcoin::{Network, PublicKey, key::Keypair}; +use bitcoin::{key::Keypair, Network, PublicKey}; use bitvm2_lib::keys::NodeMasterKey; use client::chain::goat_adaptor::GoatInitConfig; use reqwest::Url; diff --git a/node/src/main.rs b/node/src/main.rs index d24cae97..d4f433ee 100644 --- a/node/src/main.rs +++ b/node/src/main.rs @@ -1,8 +1,8 @@ #![feature(trivial_bounds)] use base64::Engine; -use clap::{Parser, Subcommand, command}; -use libp2p::PeerId; +use clap::{command, Parser, Subcommand}; use libp2p::futures::StreamExt; +use libp2p::PeerId; use libp2p::{gossipsub, kad, mdns, multiaddr::Protocol, noise, swarm::SwarmEvent, tcp, yamux}; use libp2p_metrics::Registry; use std::collections::HashMap; @@ -20,6 +20,7 @@ mod bitcoin; mod env; mod metrics_service; mod middleware; +mod relayer_action; mod rpc_service; use crate::action::GOATMessage; diff --git a/node/src/metrics_service.rs b/node/src/metrics_service.rs index 97970cbc..a01e3d95 100644 --- a/node/src/metrics_service.rs +++ b/node/src/metrics_service.rs @@ -6,15 +6,15 @@ use std::{ use crate::rpc_service::AppState; use axum::middleware::Next; use axum::{ - Router, extract::Request, extract::State, http::StatusCode, response::IntoResponse, - routing::get, + extract::Request, extract::State, http::StatusCode, response::IntoResponse, routing::get, + Router, }; use http::HeaderMap; use libp2p_metrics::Registry; use prometheus_client::encoding::text::encode; use prometheus_client::metrics::counter::Counter; use prometheus_client::metrics::family::Family; -use prometheus_client::metrics::histogram::{Histogram, exponential_buckets}; +use prometheus_client::metrics::histogram::{exponential_buckets, Histogram}; use tokio::net::TcpListener; use tokio::time::Instant; diff --git a/node/src/relayer_action.rs b/node/src/relayer_action.rs new file mode 100644 index 00000000..96d94d1d --- /dev/null +++ b/node/src/relayer_action.rs @@ -0,0 +1,182 @@ +use bitvm2_lib::actors::Actor; +use client::client::BitVM2Client; +use goat::{ + constants::{CONNECTOR_3_TIMELOCK, CONNECTOR_4_TIMELOCK}, + utils::num_blocks_per_network, +}; +use libp2p::Swarm; +use store::GraphStatus; +use uuid::Uuid; + +use crate::{ + action::{ + send_to_peer, todo_funcs::tx_on_chain, AssertSent, GOATMessage, GOATMessageContent, + KickoffReady, KickoffSent, Take1Ready, Take2Ready, + }, + env::get_network, + middleware::AllBehaviours, +}; + +mod todo_funcs { + use bitcoin::Txid; + use goat::transactions::assert::utils::COMMIT_TX_NUM; + use store::GraphStatus; + + use super::*; + + pub async fn get_initialized_graphs( + client: &BitVM2Client, + ) -> Result, Box> { + // call L2 contract : getInitializedInstanceIds + // returns Vec<(instance_id, graph_id)> + Err("TODO".into()) + } + + pub async fn get_avaiable_graphs_by_status( + client: &BitVM2Client, + status: GraphStatus, + ) -> Result, Box> { + // If instance corresponding to the graph has already been consumed, the graph is excluded. + // When a graph enters the take1/take2 status, mark its corresponding instance as consumed. + Err("TODO".into()) + } + + pub async fn get_graph_kickoff_txid( + client: &BitVM2Client, + graph_id: Uuid, + ) -> Result> { + Err("TODO".into()) + } + + pub type AssertTxids = (Txid, [Txid; COMMIT_TX_NUM], Txid); + pub async fn get_graph_assert_txids( + client: &BitVM2Client, + graph_id: Uuid, + ) -> Result> { + Err("TODO".into()) + } +} + +pub async fn scan_bridge_in_prepare( + swarm: &mut Swarm, + client: &BitVM2Client, +) -> Result<(), Box> { + // scan bridge-in-prepare message & send CreateInstance message + Err("TODO".into()) +} + +pub async fn scan_bridge_in( + swarm: &mut Swarm, + client: &BitVM2Client, +) -> Result<(), Box> { + // scan bridge-in tx & relay to L2 contract: postPeginData & postOperatorData + Err("TODO".into()) +} + +pub async fn scan_withdraw( + swarm: &mut Swarm, + client: &BitVM2Client, +) -> Result<(), Box> { + let graphs = todo_funcs::get_initialized_graphs(client).await?; + for (instance_id, graph_id) in graphs { + let message_content = + GOATMessageContent::KickoffReady(KickoffReady { instance_id, graph_id }); + send_to_peer(swarm, GOATMessage::from_typed(Actor::Operator, &message_content)?)?; + // TODO: Avoid sending duplicate messages frequently + } + Err("TODO".into()) +} + +pub async fn scan_kickoff( + swarm: &mut Swarm, + client: &BitVM2Client, +) -> Result<(), Box> { + let graphs = + todo_funcs::get_avaiable_graphs_by_status(client, GraphStatus::CommitteePresigned).await?; + for (instance_id, graph_id) in graphs { + let kickoff_txid = todo_funcs::get_graph_kickoff_txid(&client, graph_id).await?; + if tx_on_chain(client, &kickoff_txid).await? { + let message_content = GOATMessageContent::KickoffSent(KickoffSent { + instance_id, + graph_id, + kickoff_txid, + }); + send_to_peer(swarm, GOATMessage::from_typed(Actor::All, &message_content)?)?; + // TODO: Avoid sending duplicate messages frequently + } + } + Err("TODO".into()) +} + +pub async fn scan_assert( + swarm: &mut Swarm, + client: &BitVM2Client, +) -> Result<(), Box> { + let graphs_a = + todo_funcs::get_avaiable_graphs_by_status(client, GraphStatus::Challenge).await?; + let graphs_b = todo_funcs::get_avaiable_graphs_by_status(client, GraphStatus::KickOff).await?; // in case challenger never broadcast ChallengeSent + let graphs = vec![graphs_a, graphs_b].concat(); + for (instance_id, graph_id) in graphs { + let (assert_init_txid, assert_commit_txids, assert_final_txid) = + todo_funcs::get_graph_assert_txids(client, graph_id).await?; + if tx_on_chain(client, &assert_final_txid).await? { + let message_content = GOATMessageContent::AssertSent(AssertSent { + instance_id, + graph_id, + assert_init_txid, + assert_commit_txids, + assert_final_txid, + }); + send_to_peer(swarm, GOATMessage::from_typed(Actor::All, &message_content)?)?; + // TODO: Avoid sending duplicate messages frequently + } + } + Err("TODO".into()) +} + +pub async fn scan_take1( + swarm: &mut Swarm, + client: &BitVM2Client, +) -> Result<(), Box> { + let graphs = todo_funcs::get_avaiable_graphs_by_status(client, GraphStatus::KickOff).await?; + let current_height = client.esplora.get_height().await?; + let lock_blocks = num_blocks_per_network(get_network(), CONNECTOR_3_TIMELOCK); + for (instance_id, graph_id) in graphs { + let kickoff_txid = todo_funcs::get_graph_kickoff_txid(&client, graph_id).await?; + if let Some(kickoff_height) = + client.esplora.get_tx_status(&kickoff_txid).await?.block_height + { + if kickoff_height + lock_blocks > current_height { + let message_content = + GOATMessageContent::Take1Ready(Take1Ready { instance_id, graph_id }); + send_to_peer(swarm, GOATMessage::from_typed(Actor::Operator, &message_content)?)?; + // TODO: Avoid sending duplicate messages frequently + } + } + } + Err("TODO".into()) +} + +pub async fn scan_take2( + swarm: &mut Swarm, + client: &BitVM2Client, +) -> Result<(), Box> { + let graphs = todo_funcs::get_avaiable_graphs_by_status(client, GraphStatus::Assert).await?; + let current_height = client.esplora.get_height().await?; + let lock_blocks = num_blocks_per_network(get_network(), CONNECTOR_4_TIMELOCK); + for (instance_id, graph_id) in graphs { + let (_, _, assert_final_txid) = + todo_funcs::get_graph_assert_txids(&client, graph_id).await?; + if let Some(assert_height) = + client.esplora.get_tx_status(&assert_final_txid).await?.block_height + { + if assert_height + lock_blocks > current_height { + let message_content = + GOATMessageContent::Take2Ready(Take2Ready { instance_id, graph_id }); + send_to_peer(swarm, GOATMessage::from_typed(Actor::Operator, &message_content)?)?; + // TODO: Avoid sending duplicate messages frequently + } + } + } + Err("TODO".into()) +} diff --git a/node/src/rpc_service/handler/bitvm2_handler.rs b/node/src/rpc_service/handler/bitvm2_handler.rs index 20d869f5..680f3c00 100644 --- a/node/src/rpc_service/handler/bitvm2_handler.rs +++ b/node/src/rpc_service/handler/bitvm2_handler.rs @@ -1,8 +1,8 @@ use crate::rpc_service::bitvm2::*; use crate::rpc_service::node::ALIVE_TIME_JUDGE_THRESHOLD; -use crate::rpc_service::{AppState, current_time_secs}; -use axum::Json; +use crate::rpc_service::{current_time_secs, AppState}; use axum::extract::{Path, Query, State}; +use axum::Json; use bitcoin::Txid; use esplora_client::AsyncClient; use http::StatusCode; diff --git a/node/src/rpc_service/handler/node_handler.rs b/node/src/rpc_service/handler/node_handler.rs index 5d536b70..2ab1d40e 100644 --- a/node/src/rpc_service/handler/node_handler.rs +++ b/node/src/rpc_service/handler/node_handler.rs @@ -1,14 +1,14 @@ use crate::rpc_service::node::{ - ALIVE_TIME_JUDGE_THRESHOLD, NodeDesc, NodeListResponse, NodeOverViewResponse, NodeQueryParams, - UpdateOrInsertNodeRequest, + NodeDesc, NodeListResponse, NodeOverViewResponse, NodeQueryParams, UpdateOrInsertNodeRequest, + ALIVE_TIME_JUDGE_THRESHOLD, }; -use crate::rpc_service::{AppState, current_time_secs}; -use axum::Json; +use crate::rpc_service::{current_time_secs, AppState}; use axum::extract::{Path, Query, State}; +use axum::Json; use http::StatusCode; use std::sync::Arc; use std::time::UNIX_EPOCH; -use store::{NODE_STATUS_OFFLINE, NODE_STATUS_ONLINE, Node}; +use store::{Node, NODE_STATUS_OFFLINE, NODE_STATUS_ONLINE}; #[axum::debug_handler] pub async fn create_node( diff --git a/node/src/rpc_service/mod.rs b/node/src/rpc_service/mod.rs index fd5560a8..1982577e 100644 --- a/node/src/rpc_service/mod.rs +++ b/node/src/rpc_service/mod.rs @@ -5,7 +5,7 @@ mod handler; mod node; use crate::env::get_bitvm2_client_config; -use crate::metrics_service::{MetricsState, metrics_handler, metrics_middleware}; +use crate::metrics_service::{metrics_handler, metrics_middleware, MetricsState}; use crate::rpc_service::handler::{bitvm2_handler::*, node_handler::*}; use axum::body::Body; use axum::extract::Request; @@ -13,8 +13,9 @@ use axum::middleware::Next; use axum::response::Response; use axum::routing::put; use axum::{ - Router, middleware, + middleware, routing::{get, post}, + Router, }; use bitcoin::Network; use bitvm2_lib::actors::Actor;