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

Deposit test #232

Merged
merged 19 commits into from
Aug 27, 2024
Merged
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
4 changes: 1 addition & 3 deletions .github/workflows/basic.yml
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,7 @@ jobs:
]
db_file_path = "database"
num_verifiers = 4
min_relay_fee = 305
user_takes_after = 200
confirmation_treshold = 1
confirmation_threshold = 1
network = "regtest"
bitcoin_rpc_url = "http://127.0.0.1:18443"
bitcoin_rpc_user = "admin"
Expand Down
6 changes: 6 additions & 0 deletions circuits/src/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,12 @@ pub const PERIOD_CLAIM_MT_ROOTS: [[u8; 32]; NUM_ROUNDS] = [
pub const PERIOD_END_BLOCK_HEIGHTS: [u32; NUM_ROUNDS] = [0; NUM_ROUNDS];
/// Constant bridge amount in sats
pub const BRIDGE_AMOUNT_SATS: u64 = 100_000_000;
/// Constant withdrawal request txout value in sats
pub const WITHDRAWAL_EMPTY_UTXO_SATS: u64 = 550;
/// Constant block count for user to take deposit back if deposit does not happen
pub const DEPOSIT_USER_TAKES_AFTER: u32 = 5;
/// Constant block count for operator to take reimburse the bridge fund if they are honest
pub const OPERATOR_TAKES_AFTER: u32 = 5;
/// Empty leaf of a merkle tree
pub const EMPTYDATA: [u8; 32] = [
0xcb, 0x0c, 0x9f, 0x42, 0x64, 0x54, 0x6b, 0x15, 0xbe, 0x98, 0x01, 0xec, 0xb1, 0x1d, 0xf7, 0xe4,
Expand Down
3 changes: 2 additions & 1 deletion core/src/bin/operators_and_verifiers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ async fn main() {
config.bitcoin_rpc_password.clone(),
);

let (operator_clients, verifier_clients) = create_verifiers_and_operators(config, rpc).await;
let (operator_clients, verifier_clients) =
create_verifiers_and_operators("test_config.toml").await;

println!("Operator servers started: {:?}", operator_clients);
println!("Verifier servers started: {:?}", verifier_clients);
Expand Down
15 changes: 3 additions & 12 deletions core/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,8 @@ pub struct BridgeConfig {
pub operators_xonly_pks: Vec<secp256k1::XOnlyPublicKey>,
/// Number of operators.
pub num_operators: usize,
/// Number of operators.
/// Minimum relay fee.
pub min_relay_fee: u64,
/// User takes after.
pub user_takes_after: u32,
/// Threshold for confirmation.
pub confirmation_treshold: u32,
pub confirmation_threshold: u32,
/// Bitcoin remote procedure call URL.
pub bitcoin_rpc_url: String,
/// Bitcoin RPC user.
Expand Down Expand Up @@ -138,9 +133,7 @@ impl Default for BridgeConfig {
num_verifiers: 5,
operators_xonly_pks: vec![],
num_operators: 4,
min_relay_fee: 289,
user_takes_after: 200,
confirmation_treshold: 1,
confirmation_threshold: 1,
network: Network::Regtest,
bitcoin_rpc_url: "http://127.0.0.1:18443".to_string(),
bitcoin_rpc_user: "admin".to_string(),
Expand Down Expand Up @@ -238,11 +231,9 @@ mod tests {
let file_name = "2".to_string() + TEST_FILE;
let content = "[header1]
num_verifiers = 4
min_relay_fee = 289
user_takes_after = 200

[header2]
confirmation_treshold = 1
confirmation_threshold = 1
network = \"regtest\"
bitcoin_rpc_url = \"http://localhost:18443\"
bitcoin_rpc_user = \"admin\"
Expand Down
3 changes: 0 additions & 3 deletions core/src/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,6 @@ use bitcoin::BlockHash;
use clementine_circuits::constants::CLAIM_MERKLE_TREE_DEPTH;
use crypto_bigint::U256;

// pub const NUM_VERIFIERS: usize = 4;
// pub const NUM_USERS: usize = 4;

/// For connector tree utxos, we should wait some time for any verifier to burn the branch if preimage is revealed
pub const CONNECTOR_TREE_OPERATOR_TAKES_AFTER: u16 = 1;

Expand Down
3 changes: 0 additions & 3 deletions core/src/database/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,17 +78,14 @@ impl Database {
config: BridgeConfig,
database_name: &str,
) -> Result<BridgeConfig, BridgeError> {
println!("Creating database: {}", database_name);
let url = "postgresql://".to_owned()
+ config.db_user.as_str()
+ ":"
+ config.db_password.as_str()
+ "@"
+ config.db_host.as_str();
println!("url: {}", url);
let conn = sqlx::PgPool::connect(url.as_str()).await?;
Database::drop_database(config.clone(), database_name).await?;
println!("Dropped database");
let query = format!(
"CREATE DATABASE {} WITH OWNER {}",
database_name, config.db_user
Expand Down
2 changes: 0 additions & 2 deletions core/src/extended_rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,6 @@ where
recovery_taproot_address: &Address<NetworkUnchecked>,
evm_address: &EVMAddress,
amount_sats: u64,
user_takes_after: u32,
confirmation_block_count: u32,
network: bitcoin::Network,
) -> Result<(), BridgeError> {
Expand All @@ -301,7 +300,6 @@ where
recovery_taproot_address,
evm_address,
BRIDGE_AMOUNT_SATS,
user_takes_after,
network,
);

Expand Down
1 change: 1 addition & 0 deletions core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use serde::{Deserialize, Serialize};
pub mod actor;
pub mod cli;
pub mod config;
pub mod constants;
pub mod database;
pub mod env_writer;
pub mod errors;
Expand Down
11 changes: 8 additions & 3 deletions core/src/mock/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,20 @@ macro_rules! create_test_config {
/// Returns new `BridgeConfig`.
#[macro_export]
macro_rules! create_test_config_with_thread_name {
($config_file:expr) => {{
($config_file:expr, $suffix:expr) => {{
let suffix: String = $suffix.unwrap_or(&String::default()).to_string();
let handle = thread::current()
.name()
.unwrap()
.split(":")
.split(':')
.last()
.unwrap()
.to_owned();
.to_owned()
+ &suffix;

create_test_config!(handle, $config_file)
}};
($config_file:expr) => {{
create_test_config_with_thread_name!($config_file, Option::<&str>::None)
}};
}
24 changes: 19 additions & 5 deletions core/src/operator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,16 +98,24 @@ where
&recovery_taproot_address,
&evm_address,
BRIDGE_AMOUNT_SATS,
self.config.user_takes_after,
self.config.confirmation_treshold,
self.config.confirmation_threshold,
self.config.network,
)?;

// 2. Check if we alredy created a kickoff UTXO for this deposit UTXO
let kickoff_utxo = self.db.get_kickoff_utxo(deposit_outpoint).await?;

tracing::debug!(
"Kickoff UTXO for deposit UTXO: {:?} is: {:?}",
deposit_outpoint,
kickoff_utxo
);
// if we already have a kickoff UTXO for this deposit UTXO, return it
if let Some(kickoff_utxo) = kickoff_utxo {
tracing::debug!(
"Kickoff UTXO already exists for deposit UTXO: {:?}",
deposit_outpoint
);
let kickoff_sig_hash = sha256_hash!(
deposit_outpoint.txid,
deposit_outpoint.vout.to_be_bytes(),
Expand Down Expand Up @@ -148,6 +156,12 @@ where
self.config.network,
);

tracing::debug!(
"For operator index: {:?} Kickoff tx handler: {:#?}",
self.idx,
kickoff_tx_handler
);

let change_utxo = UTXO {
outpoint: OutPoint {
txid: kickoff_tx_handler.tx.compute_txid(),
Expand Down Expand Up @@ -204,7 +218,7 @@ where

/// Checks if utxo is valid, spendable by operator and not spent
/// Saves the utxo to the db
async fn set_operator_funding_utxo(&self, funding_utxo: UTXO) -> Result<(), BridgeError> {
async fn set_funding_utxo(&self, funding_utxo: UTXO) -> Result<(), BridgeError> {
self.db.set_funding_utxo(funding_utxo).await?;
Ok(())
}
Expand Down Expand Up @@ -308,8 +322,8 @@ where
.await
}

async fn set_operator_funding_utxo_rpc(&self, funding_utxo: UTXO) -> Result<(), BridgeError> {
self.set_operator_funding_utxo(funding_utxo).await
async fn set_funding_utxo_rpc(&self, funding_utxo: UTXO) -> Result<(), BridgeError> {
self.set_funding_utxo(funding_utxo).await
}

async fn new_withdrawal_sig_rpc(
Expand Down
85 changes: 56 additions & 29 deletions core/src/servers.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
//! # Servers
//!
//! Utilities for operator and verifier servers.

use crate::mock::common;
use crate::{config, create_extended_rpc};
use crate::{
config::BridgeConfig,
create_test_config, create_test_config_with_thread_name,
database::common::Database,
errors,
extended_rpc::ExtendedRpc,
Expand All @@ -18,6 +20,7 @@ use jsonrpsee::{
server::{Server, ServerHandle},
};
use operator::Operator;
use std::thread;
use traits::rpc::OperatorRpcServer;

/// Starts a server for a verifier.
Expand All @@ -28,7 +31,14 @@ pub async fn create_verifier_server<R>(
where
R: RpcApiWrapper,
{
println!("Database created");
let _ = Database::create_database(config.clone(), &config.db_name).await?;
let database = Database::new(config.clone()).await.unwrap();
database
.run_sql_file("../scripts/schema.sql")
.await
.unwrap();
database.close().await;
// let config = create_test_config!(config.db_name, config);
let server = match Server::builder()
.build(format!("{}:{}", config.host, config.port))
.await
Expand Down Expand Up @@ -61,6 +71,14 @@ pub async fn create_operator_server<R>(
where
R: RpcApiWrapper,
{
let _ = Database::create_database(config.clone(), &config.db_name).await?;
let database = Database::new(config.clone()).await.unwrap();
database
.run_sql_file("../scripts/schema.sql")
.await
.unwrap();
database.close().await;

let operator = Operator::new(config.clone(), rpc).await?;

let server = match Server::builder()
Expand Down Expand Up @@ -97,33 +115,37 @@ where
/// # Panics
///
/// Panics if there was an error while creating any of the servers.
pub async fn create_verifiers_and_operators<R>(
config: BridgeConfig,
rpc: ExtendedRpc<R>,
pub async fn create_verifiers_and_operators(
config_name: &str,
// rpc: ExtendedRpc<R>,
) -> (
Vec<(HttpClient, ServerHandle, std::net::SocketAddr)>, // Verifier clients
Vec<(HttpClient, ServerHandle, std::net::SocketAddr)>, // Operator clients
)
where
R: RpcApiWrapper,
{
) {
let mut config = create_test_config_with_thread_name!(config_name);
let rpc = create_extended_rpc!(config);
let all_verifiers_secret_keys = config.all_verifiers_secret_keys.clone().unwrap_or_else(|| {
panic!("All secret keys of the verifiers are required for testing");
});
let verifier_futures = all_verifiers_secret_keys
.iter()
.enumerate()
.map(|(i, sk)| {
create_verifier_server(
BridgeConfig {
secret_key: *sk,
port: 0, // Use the index to calculate the port
db_name: config.db_name.clone() + &"verifier".to_string() + &i.to_string(),
db_user: config.db_user.clone() + &"verifier".to_string() + &i.to_string(),
..config.clone()
},
rpc.clone(),
)
let i = i.to_string();
let rpc = rpc.clone();
async move {
let config_with_new_db =
create_test_config_with_thread_name!(config_name, Some(&i.to_string()));
create_verifier_server(
BridgeConfig {
secret_key: *sk,
port: 0, // Use the index to calculate the port
..config_with_new_db
},
rpc,
)
.await
}
})
.collect::<Vec<_>>();
let verifier_endpoints = futures::future::try_join_all(verifier_futures)
Expand All @@ -138,16 +160,21 @@ where
.iter()
.enumerate()
.map(|(i, sk)| {
create_verifier_server(
BridgeConfig {
secret_key: *sk,
port: 0, // Use the index to calculate the port
db_name: config.db_name.clone() + &"operator".to_string() + &i.to_string(),
db_user: config.db_user.clone() + &"operator".to_string() + &i.to_string(),
..config.clone()
},
rpc.clone(),
)
let i = (i + 1000).to_string();
let rpc = rpc.clone();
async move {
let config_with_new_db =
create_test_config_with_thread_name!(config_name, Some(&i.to_string()));
create_operator_server(
BridgeConfig {
secret_key: *sk,
port: 0, // Use the index to calculate the port
..config_with_new_db
},
rpc,
)
.await
}
})
.collect::<Vec<_>>();
let operator_endpoints = futures::future::try_join_all(operator_futures)
Expand Down
8 changes: 4 additions & 4 deletions core/src/traits/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ pub trait VerifierRpc {
/// - Generate random pubNonces, secNonces
/// - Save pubNonces and secNonces to a in-memory db
/// - Return pubNonces
async fn new_deposit_rpc(
async fn verifier_new_deposit_rpc(
&self,
deposit_utxo: OutPoint,
deposit_outpoint: OutPoint,
recovery_taproot_address: Address<NetworkUnchecked>,
evm_address: EVMAddress,
) -> Result<Vec<MuSigPubNonce>, BridgeError>;
Expand Down Expand Up @@ -64,8 +64,8 @@ pub trait OperatorRpc {
evm_address: EVMAddress,
) -> Result<(UTXO, secp256k1::schnorr::Signature), BridgeError>;

#[method(name = "set_operator_funding_utxo")]
async fn set_operator_funding_utxo_rpc(&self, funding_utxo: UTXO) -> Result<(), BridgeError>;
#[method(name = "set_funding_utxo")]
async fn set_funding_utxo_rpc(&self, funding_utxo: UTXO) -> Result<(), BridgeError>;

#[method(name = "new_withdrawal_sig")]
/// Gets the withdrawal utxo from citrea,
Expand Down
Loading