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

Watchtower get params #373

Merged
merged 14 commits into from
Dec 10, 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
3 changes: 3 additions & 0 deletions core/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ pub struct BridgeConfig {
pub host: String,
/// Port of the operator or the verifier
pub port: u16,
/// Entitiy index.
pub index: u32,
/// Bitcoin network to work on.
pub network: Network,
/// Secret key for the operator or the verifier.
Expand Down Expand Up @@ -128,6 +130,7 @@ impl Default for BridgeConfig {
Self {
host: "127.0.0.1".to_string(),
port: 3030,
index: 0,
secret_key: secp256k1::SecretKey::new(&mut secp256k1::rand::thread_rng()),
verifiers_public_keys: vec![],
num_verifiers: 7,
Expand Down
5 changes: 0 additions & 5 deletions core/src/mock/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,6 @@ pub fn get_test_config(configuration_file: &str) -> Result<BridgeConfig, BridgeE
config.db_name = env_config.db_name;
};

#[cfg(test)]
{
config.port = 0;
}

Ok(config)
}

Expand Down
4 changes: 1 addition & 3 deletions core/src/rpc/clementine.proto
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@ message AssertEmptyPublicKey {
}

message WinternitzPubkey {
uint32 d = 1;
uint32 n0 = 2;
repeated bytes digit_pubkey = 3;
}

Expand Down Expand Up @@ -216,7 +214,7 @@ service ClementineVerifier {

message WatchtowerParams {
uint32 watchtower_id = 1;
// Winternitz pubkeys for each operator's timetxs.
// Flattened list of Winternitz pubkeys for each operator's timetxs.
repeated WinternitzPubkey winternitz_pubkeys = 2;
}

Expand Down
6 changes: 1 addition & 5 deletions core/src/rpc/clementine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,6 @@ pub struct AssertEmptyPublicKey {
}
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct WinternitzPubkey {
#[prost(uint32, tag = "1")]
pub d: u32,
#[prost(uint32, tag = "2")]
pub n0: u32,
#[prost(bytes = "vec", repeated, tag = "3")]
pub digit_pubkey: ::prost::alloc::vec::Vec<::prost::alloc::vec::Vec<u8>>,
}
Expand Down Expand Up @@ -206,7 +202,7 @@ pub struct VerifierPublicKeys {
pub struct WatchtowerParams {
#[prost(uint32, tag = "1")]
pub watchtower_id: u32,
/// Winternitz pubkeys for each operator's timetxs.
/// Flattened list of Winternitz pubkeys for each operator's timetxs.
#[prost(message, repeated, tag = "2")]
pub winternitz_pubkeys: ::prost::alloc::vec::Vec<WinternitzPubkey>,
}
Expand Down
57 changes: 55 additions & 2 deletions core/src/rpc/watchtower.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use super::clementine::{
clementine_watchtower_server::ClementineWatchtower, Empty, WatchtowerParams,
clementine_watchtower_server::ClementineWatchtower, Empty, WatchtowerParams, WinternitzPubkey,
};
use crate::watchtower::Watchtower;
use tonic::{async_trait, Request, Response, Status};
Expand All @@ -12,6 +12,59 @@ impl ClementineWatchtower for Watchtower {
&self,
_request: Request<Empty>,
) -> Result<Response<WatchtowerParams>, Status> {
todo!()
let winternitz_pubkeys: Vec<WinternitzPubkey> = self
.get_winternitz_public_keys()
.await?
.into_iter()
.map(|wpks| WinternitzPubkey {
digit_pubkey: wpks.iter().map(|inner| inner.to_vec()).collect(),
})
.collect::<Vec<WinternitzPubkey>>();

Ok(Response::new(WatchtowerParams {
watchtower_id: self.config.index,
winternitz_pubkeys,
}))
}
}

#[cfg(test)]
mod tests {
use crate::{
mock::database::create_test_config_with_thread_name,
rpc::clementine::{clementine_watchtower_server::ClementineWatchtower, Empty},
servers::create_actors_grpc,
watchtower::Watchtower,
};
use tonic::Request;

#[tokio::test]
#[serial_test::serial]
async fn watchtower_get_params() {
let mut config = create_test_config_with_thread_name("test_config.toml", None).await;
let (verifiers, operators, _, _watchtowers) = create_actors_grpc(config.clone(), 2).await;

config.verifier_endpoints = Some(
verifiers
.iter()
.map(|v| format!("http://{}", v.0))
.collect(),
);
config.operator_endpoints = Some(
operators
.iter()
.map(|o| format!("http://{}", o.0))
.collect(),
);
let watchtower = Watchtower::new(config.clone()).await.unwrap();

let params = watchtower
.get_params(Request::new(Empty {}))
.await
.unwrap()
.into_inner();

assert_eq!(params.watchtower_id, watchtower.config.index);
assert!(params.winternitz_pubkeys.len() == config.num_operators * config.num_time_txs);
}
}
70 changes: 60 additions & 10 deletions core/src/servers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@
//! Utilities for operator and verifier servers.
use crate::aggregator;
use crate::aggregator::Aggregator;
use crate::database::Database;
use crate::mock::database::create_test_config_with_thread_name;
use crate::rpc::clementine::clementine_aggregator_server::ClementineAggregatorServer;
use crate::rpc::clementine::clementine_operator_server::ClementineOperatorServer;
use crate::rpc::clementine::clementine_verifier_server::ClementineVerifierServer;
use crate::rpc::clementine::clementine_watchtower_server::ClementineWatchtowerServer;
use crate::traits::rpc::AggregatorServer;
use crate::watchtower::Watchtower;
use crate::{
config::BridgeConfig,
errors,
Expand Down Expand Up @@ -309,6 +312,28 @@ pub async fn create_aggregator_grpc_server(
Ok((addr,))
}

pub async fn create_watchtower_grpc_server(
config: BridgeConfig,
) -> Result<(std::net::SocketAddr,), BridgeError> {
let addr = format!("{}:{}", config.host, config.port).parse().unwrap();
let watchtower = Watchtower::new(config).await?;
let svc = ClementineWatchtowerServer::new(watchtower);
let handle = tonic::transport::Server::builder()
.add_service(svc)
.serve(addr);

tokio::spawn(async move {
if let Err(e) = handle.await {
tracing::error!("gRPC server error: {:?}", e);
panic!("gRPC server error: {:?}", e);
}
});
tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;

tracing::info!("Watchtower gRPC server started with address: {}", addr);
Ok((addr,))
}

/// Starts operators, verifiers and aggergator gRPC servers. This function's intended use is for
/// tests.
///
Expand All @@ -322,20 +347,20 @@ pub async fn create_aggregator_grpc_server(
/// Panics if there was an error while creating any of the servers.
// #[tracing::instrument(ret(level = tracing::Level::TRACE))]
#[allow(clippy::type_complexity)] // Enabling tracing::instrument causes this.
pub async fn create_verifiers_and_operators_grpc(
config_name: &str,
// rpc: ExtendedRpc<R>,
pub async fn create_actors_grpc(
config: BridgeConfig,
number_of_watchtowers: u32,
) -> (
Vec<(std::net::SocketAddr,)>, // Verifier clients
Vec<(std::net::SocketAddr,)>, // Operator clients
(std::net::SocketAddr,), // Aggregator client
Vec<(std::net::SocketAddr,)>, // Watchtower clients
) {
let config = create_test_config_with_thread_name(config_name, None).await;
let start_port = config.port;
let rpc = ExtendedRpc::new(
config.bitcoin_rpc_url,
config.bitcoin_rpc_user,
config.bitcoin_rpc_password,
config.bitcoin_rpc_url.clone(),
config.bitcoin_rpc_user.clone(),
config.bitcoin_rpc_password.clone(),
)
.await;
let all_verifiers_secret_keys = config.all_verifiers_secret_keys.clone().unwrap_or_else(|| {
Expand All @@ -349,9 +374,13 @@ pub async fn create_verifiers_and_operators_grpc(
// println!("Port: {}", port);
let i = i.to_string();
let rpc = rpc.clone();
let mut config_with_new_db = config.clone();
async move {
let config_with_new_db =
create_test_config_with_thread_name(config_name, Some(&i.to_string())).await;
config_with_new_db.db_name += &i;
Database::initialize_database(&config_with_new_db)
.await
.unwrap();

let verifier = create_verifier_grpc_server(
BridgeConfig {
secret_key: *sk,
Expand Down Expand Up @@ -434,5 +463,26 @@ pub async fn create_verifiers_and_operators_grpc(
.await
.unwrap();

(verifier_endpoints, operator_endpoints, aggregator)
let port = port + 1;
println!("Watchtower start port: {}", port);
let wathctower_futures = (0..number_of_watchtowers)
.map(|i| {
let verifier_configs = verifier_configs.clone();

create_watchtower_grpc_server(BridgeConfig {
port: port + i as u16,
..verifier_configs[0].clone()
})
})
.collect::<Vec<_>>();
let wathctower_endpoints = futures::future::try_join_all(wathctower_futures)
.await
.unwrap();

(
verifier_endpoints,
operator_endpoints,
aggregator,
wathctower_endpoints,
)
}
127 changes: 125 additions & 2 deletions core/src/watchtower.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,130 @@
use crate::{database::Database, extended_rpc::ExtendedRpc};
use crate::{
actor::{Actor, WinternitzDerivationPath},
config::BridgeConfig,
database::Database,
errors::BridgeError,
extended_rpc::ExtendedRpc,
};
use bitvm::signatures::winternitz;

#[derive(Debug, Clone)]
pub struct Watchtower {
_rpc: ExtendedRpc,
_erpc: ExtendedRpc,
_db: Database,
pub actor: Actor,
pub config: BridgeConfig,
}

impl Watchtower {
pub async fn new(config: BridgeConfig) -> Result<Self, BridgeError> {
let _erpc = ExtendedRpc::new(
config.bitcoin_rpc_url.clone(),
config.bitcoin_rpc_user.clone(),
config.bitcoin_rpc_password.clone(),
)
.await;
let _db = Database::new(&config).await?;
let actor = Actor::new(
config.secret_key,
config.winternitz_secret_key,
config.network,
);

Ok(Self {
_erpc,
_db,
actor,
config,
})
}

/// Generates Winternitz public keys for every operator and time_tx pair and
/// returns them.
///
/// # Returns
///
/// - [`Vec<Vec<winternitz::PublicKey>>`]: Winternitz public key for
/// `operator index` row and `time_tx index` column.
pub async fn get_winternitz_public_keys(
&self,
) -> Result<Vec<winternitz::PublicKey>, BridgeError> {
let mut winternitz_pubkeys = Vec::new();

for operator in 0..self.config.num_operators as u32 {
for time_tx in 0..self.config.num_time_txs as u32 {
let path = WinternitzDerivationPath {
message_length: 480,
log_d: 4,
tx_type: crate::actor::TxType::TimeTx,
index: None,
operator_idx: Some(operator),
watchtower_idx: None,
time_tx_idx: Some(time_tx),
};

winternitz_pubkeys.push(self.actor.derive_winternitz_pk(path)?);
}
}

Ok(winternitz_pubkeys)
}
}

#[cfg(test)]
mod tests {
use crate::{
mock::database::create_test_config_with_thread_name, servers::create_actors_grpc,
watchtower::Watchtower,
};

#[tokio::test]
#[serial_test::serial]
async fn new_watchtower() {
let mut config = create_test_config_with_thread_name("test_config.toml", None).await;
let (verifiers, operators, _, _should_not_panic) =
create_actors_grpc(config.clone(), 1).await;

config.verifier_endpoints = Some(
verifiers
.iter()
.map(|v| format!("http://{}", v.0))
.collect(),
);
config.operator_endpoints = Some(
operators
.iter()
.map(|o| format!("http://{}", o.0))
.collect(),
);

let _should_not_panic = Watchtower::new(config.clone()).await.unwrap();
}

#[tokio::test]
#[serial_test::serial]
async fn get_winternitz_public_keys() {
let mut config = create_test_config_with_thread_name("test_config.toml", None).await;
let (verifiers, operators, _, _watchtowers) = create_actors_grpc(config.clone(), 2).await;

config.verifier_endpoints = Some(
verifiers
.iter()
.map(|v| format!("http://{}", v.0))
.collect(),
);
config.operator_endpoints = Some(
operators
.iter()
.map(|o| format!("http://{}", o.0))
.collect(),
);

let watchtower = Watchtower::new(config.clone()).await.unwrap();
let winternitz_public_keys = watchtower.get_winternitz_public_keys().await.unwrap();

assert_eq!(
winternitz_public_keys.len(),
config.num_operators * config.num_time_txs
);
}
}
3 changes: 2 additions & 1 deletion core/tests/data/test_config.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Host and port of the current actor (operator or verifier)
# Host, port and index of the current actor (operator, verifier, or watchtower)
host = "127.0.0.1"
port = 17000
index = 0

# Secret key of the current actor (operator or verifier)
secret_key = "3333333333333333333333333333333333333333333333333333333333333333"
Expand Down
Loading
Loading