Skip to content

Commit

Permalink
Merge branch 'main' into contract-hash-registry
Browse files Browse the repository at this point in the history
  • Loading branch information
koxu1996 authored Jul 16, 2024
2 parents 3494d29 + b7b8b33 commit 41ded51
Show file tree
Hide file tree
Showing 20 changed files with 92 additions and 34 deletions.
6 changes: 5 additions & 1 deletion .env
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
KAIROS_SERVER_SOCKET_ADDR="127.0.0.1:7893"
# Make sure this matches the default in the nix module and kairos-cli args
KAIROS_SERVER_SOCKET_ADDR="0.0.0.0:9999"
KAIROS_PROVER_SERVER_SOCKET_ADDR="127.0.0.1:7894"
# In development the socket and url should match
KAIROS_PROVER_SERVER_URL="http://127.0.0.1:7894"
Expand All @@ -9,4 +10,7 @@ RISC0_DEV_MODE=1;
# FIXME this is a dummy value that fixes a regression that prevented server startup
KAIROS_SERVER_CASPER_RPC="http://127.0.0.1:11101/rpc"
KAIROS_SERVER_CASPER_SSE="http://127.0.0.1:18101/events/main"
KAIROS_SERVER_CASPER_SYNC_INTERVAL=10

KAIROS_SERVER_DEMO_CONTRACT_HASH="0000000000000000000000000000000000000000000000000000000000000000"
KAIROS_SERVER_SECRET_KEY_FILE="./testdata/users/user-1/secret_key.pem"
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion kairos-cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,10 @@ license.workspace = true
default = ["demo"]
all-tests = ["cctl-tests"]
cctl-tests = []
demo = ["dep:kairos-test-utils", "dep:tokio"]
demo = ["dep:kairos-test-utils", "dep:tokio", "dep:dotenvy"]

[dependencies]
dotenvy = { version = "0.15", optional = true }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["std", "env-filter"] }
casper-client.workspace = true
Expand Down
3 changes: 3 additions & 0 deletions kairos-cli/bin/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ use std::process;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};

fn main() {
#[cfg(feature = "demo")]
let _ = dotenvy::dotenv();

tracing_subscriber::registry()
.with(EnvFilter::try_from_default_env().unwrap_or_else(|_| "warn".into()))
.with(tracing_subscriber::fmt::layer())
Expand Down
4 changes: 2 additions & 2 deletions kairos-cli/src/commands/run_cctl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,10 @@ pub fn run() -> Result<String, CliError> {
.expect("Expected at least one node after successful network run");
let casper_rpc_url = format!("http://localhost:{}/rpc", node.port.rpc_port);

println!("You can find demo key pairs in `{:?}`", network.working_dir);

println!("Before running the Kairos CLI in another terminal, set the following environment variables:");
println!("export KAIROS_CONTRACT_HASH={}", contract_hash);
println!("export DEMO_KEYS={}/assets/users", network.working_dir.display());
println!("export KAIROS_SERVER_DEMO_CONTRACT_HASH={}", contract_hash);
println!("export KAIROS_SERVER_CASPER_RPC={}", casper_rpc_url);

let _ = tokio::signal::ctrl_c().await;
Expand Down
12 changes: 10 additions & 2 deletions kairos-cli/src/commands/transfer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ pub fn run(args: Args, kairos_server_address: Url) -> Result<String, CliError> {
// TODO: Create transaction and sign it with `signer`.

// TODO: Send transaction to the network, using Rust SDK.
reqwest::blocking::Client::new()
let res = reqwest::blocking::Client::new()
.post(kairos_server_address.join(TransferPath::PATH).unwrap())
.json(&PayloadBody {
public_key: signer.to_public_key()?,
Expand All @@ -47,5 +47,13 @@ pub fn run(args: Args, kairos_server_address: Url) -> Result<String, CliError> {
.send()
.map_err(KairosClientError::from)?;

Ok("ok".to_string())
if res.status().is_success() {
Ok("Transfer successfully sent to L2".to_string())
} else {
Err(KairosClientError::ResponseErrorWithCode(
res.status().as_u16(),
res.text().unwrap_or_default(),
)
.into())
}
}
12 changes: 10 additions & 2 deletions kairos-cli/src/commands/withdraw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ pub fn run(args: Args, kairos_server_address: Url) -> Result<String, CliError> {
// TODO: Create transaction and sign it with `signer`.

// TODO: Send transaction to the network, using Rust SDK.
reqwest::blocking::Client::new()
let res = reqwest::blocking::Client::new()
.post(kairos_server_address.join(WithdrawPath::PATH).unwrap())
.json(&PayloadBody {
public_key: signer.to_public_key()?,
Expand All @@ -44,5 +44,13 @@ pub fn run(args: Args, kairos_server_address: Url) -> Result<String, CliError> {
.send()
.map_err(KairosClientError::from)?;

Ok("ok".to_string())
if res.status().is_success() {
Ok("Withdrawal successfully sent to L2".to_string())
} else {
Err(KairosClientError::ResponseErrorWithCode(
res.status().as_u16(),
res.text().unwrap_or_default(),
)
.into())
}
}
1 change: 1 addition & 0 deletions kairos-cli/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use reqwest::Url;
pub struct Cli {
#[command(subcommand)]
pub command: Command,
// Make sure matches the default in `../.env` and the nix module.
#[arg(long, value_name = "URL", default_value = "http://0.0.0.0:9999")]
pub kairos_server_address: Url,
}
Expand Down
11 changes: 11 additions & 0 deletions kairos-server/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,26 @@ pub struct ServerConfig {
pub socket_addr: SocketAddr,
pub casper_rpc: Url,
pub casper_sse: Url,
pub casper_sync_interval: Duration,
pub kairos_demo_contract_hash: ContractHash,
pub batch_config: BatchConfig,
}

impl ServerConfig {
pub fn from_env() -> Result<Self, String> {
let socket_addr = parse_env_as::<SocketAddr>("KAIROS_SERVER_SOCKET_ADDR")?;

let casper_rpc = parse_env_as::<Url>("KAIROS_SERVER_CASPER_RPC")?;
let casper_sse = parse_env_as::<Url>("KAIROS_SERVER_CASPER_SSE")?;
let casper_sync_interval =
parse_env_as::<u64>("KAIROS_SERVER_CASPER_SYNC_INTERVAL").map(Duration::from_secs)?;

if casper_sync_interval.as_secs() == 0 {
return Err("Casper sync interval must be greater than 0".to_string());
}

let batch_config = BatchConfig::from_env()?;

let secret_key_file =
parse_env_as_opt::<String>("KAIROS_SERVER_SECRET_KEY_FILE")?.map(PathBuf::from);

Expand Down Expand Up @@ -53,6 +63,7 @@ impl ServerConfig {
socket_addr,
casper_rpc,
casper_sse,
casper_sync_interval,
kairos_demo_contract_hash,
batch_config,
})
Expand Down
18 changes: 0 additions & 18 deletions kairos-server/src/l1_sync/interval_trigger.rs

This file was deleted.

2 changes: 0 additions & 2 deletions kairos-server/src/l1_sync/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
pub mod error;
pub mod event_manager;
pub mod service;

pub mod interval_trigger;
16 changes: 15 additions & 1 deletion kairos-server/src/l1_sync/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ use super::event_manager::EventManager;

use tokio::sync::mpsc;
use tokio::sync::oneshot;
use tokio::time;

use std::sync::Arc;
use std::{sync::Arc, time::Duration};

pub enum SyncCommand {
TriggerSync(oneshot::Sender<()>),
Expand Down Expand Up @@ -45,6 +46,19 @@ impl L1SyncService {

Ok(())
}

pub async fn run_periodic_sync(&self, interval: Duration) {
let mut interval = time::interval(interval);

loop {
interval.tick().await;

tracing::debug!("Triggering periodic L1 sync");
let _ = self.trigger_sync().await.map_err(|e| {
tracing::error!("Unable to trigger sync: {}", e);
});
}
}
}

/// Handles incoming commands and delegates tasks to EventManager.
Expand Down
3 changes: 2 additions & 1 deletion kairos-server/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ pub fn app_router(state: ServerState) -> Router {

pub async fn run_l1_sync(server_state: Arc<ServerStateInner>) {
// Extra check: make sure the default dummy value of contract hash was changed.
let sync_interval = server_state.server_config.casper_sync_interval;
let contract_hash = server_state.server_config.kairos_demo_contract_hash;
if contract_hash == ContractHash::default() {
tracing::warn!(
Expand All @@ -61,7 +62,7 @@ pub async fn run_l1_sync(server_state: Arc<ServerStateInner>) {
// Run periodic synchronization.
// TODO: Add additional SSE trigger.
tokio::spawn(async move {
l1_sync::interval_trigger::run(l1_sync_service.into()).await;
l1_sync_service.run_periodic_sync(sync_interval).await;
});
}

Expand Down
2 changes: 1 addition & 1 deletion kairos-server/src/routes/deposit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ pub async fn deposit_handler(
let response = put_deploy(
expected_rpc_id.clone(),
state.server_config.casper_rpc.as_str(),
casper_client::Verbosity::High,
casper_client::Verbosity::Low,
body,
)
.await
Expand Down
2 changes: 1 addition & 1 deletion kairos-server/src/state/submit_batch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ pub async fn submit_proof_to_contract(
let r = casper_client::put_deploy(
casper_client::JsonRpcId::Number(random()),
casper_rpc.as_str(),
casper_client::Verbosity::High,
casper_client::Verbosity::Low,
deploy,
)
.await
Expand Down
6 changes: 5 additions & 1 deletion kairos-server/src/state/trie.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,11 @@ pub fn spawn_state_thread(
tracing::trace!("Trie State Thread received message: {:?}", msg);
match msg {
TrieStateThreadMsg::Transaction(txn, responder) => {
let res = state.batch_state.execute_transaction(txn);
let res = state.batch_state.execute_transaction(txn).map_err(|e| {
tracing::warn!("Error executing transaction: {:?}", e);
e
});

responder.send(res).unwrap_or_else(|err| {
tracing::warn!(
"Transaction submitter hung up before receiving response: {}",
Expand Down
3 changes: 3 additions & 0 deletions kairos-server/tests/transactions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use axum_test::{TestServer, TestServerConfig};
use reqwest::Url;
use std::collections::HashSet;
use std::sync::{Arc, OnceLock};
use std::time::Duration;
use tokio::sync::RwLock;
use tracing_subscriber::{prelude::*, EnvFilter};

Expand Down Expand Up @@ -52,6 +53,8 @@ fn new_test_app_with_casper_node(casper_rpc_url: &Url, casper_sse_url: &Url) ->
socket_addr: "0.0.0.0:0".parse().unwrap(),
casper_rpc: casper_rpc_url.clone(),
casper_sse: casper_sse_url.clone(),
// For testing purposes, we set the sync interval to be fast
casper_sync_interval: Duration::from_secs(5),
kairos_demo_contract_hash: ContractHash::default(),
batch_config: BatchConfig {
max_batch_size: None,
Expand Down
3 changes: 3 additions & 0 deletions kairos-test-utils/src/kairos.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use casper_client_types::ContractHash;
use reqwest::Url;
use std::io;
use std::net::{SocketAddr, TcpListener};
use std::time::Duration;
use tokio::net::TcpStream;

use kairos_server::config::{BatchConfig, ServerConfig};
Expand Down Expand Up @@ -47,6 +48,8 @@ impl Kairos {
socket_addr,
casper_rpc: casper_rpc.clone(),
casper_sse: casper_sse.clone(),
// We want a short sync interval for tests.
casper_sync_interval: Duration::from_secs(5),
kairos_demo_contract_hash: kairos_demo_contract_hash.unwrap_or_default(),
batch_config,
};
Expand Down
10 changes: 10 additions & 0 deletions nixos/modules/kairos.nix
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,15 @@ in
'';
};

casperSyncInterval = mkOption {
type = types.int;
default = 10;
example = 10;
description = ''
The interval in seconds to between calls to the casper node to sync the deploys.
'';
};

prover = mkOption {
description = "Prover server related options";
default = { };
Expand Down Expand Up @@ -142,6 +151,7 @@ in
KAIROS_SERVER_SOCKET_ADDR = "${cfg.bindAddress}:${builtins.toString cfg.port}";
KAIROS_SERVER_CASPER_RPC = cfg.casperRpcUrl;
KAIROS_SERVER_CASPER_SSE = cfg.casperSseUrl;
KAIROS_SERVER_CASPER_SYNC_INTERVAL = builtins.toString cfg.casperSyncInterval;
KAIROS_SERVER_DEMO_CONTRACT_HASH = cfg.demoContractHash;
KAIROS_PROVER_SERVER_URL = "${cfg.prover.protocol}://${cfg.prover.bindAddress}:${builtins.toString cfg.prover.port}";
} // optionalAttrs (!builtins.isNull cfg.prover.maxBatchSize) {
Expand Down
8 changes: 7 additions & 1 deletion nixos/tests/end-to-end.nix
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ nixosTest {
services.kairos = {
casperRpcUrl = "http://localhost:${builtins.toString config.services.cctl.port}/rpc";
casperSseUrl = "http://localhost:18101/events/main"; # has to be hardcoded since it's not configurable atm
casperSyncInterval = 5;
demoContractHash = "0000000000000000000000000000000000000000000000000000000000000000";
};

Expand All @@ -81,6 +82,7 @@ nixosTest {
testScript = ''
import json
import backoff
import time
# Utils
def verify_deploy_success(json_data):
Expand Down Expand Up @@ -129,10 +131,14 @@ nixosTest {
wait_for_successful_deploy(deposit_deploy_hash)
# wait for l2 to sync with l1 every 10 seconds
time.sleep(12)
# transfer
beneficiary = client.succeed("cat ${clientUsersDirectory}/user-3/public_key_hex")
transfer_output = client.succeed("kairos-cli --kairos-server-address http://kairos transfer --nonce 0 --amount 1000 --recipient {} --private-key {}".format(beneficiary, depositor_private_key))
assert "ok\n" in transfer_output
assert "Transfer successfully sent to L2\n" in transfer_output, "The transfer command was not successful: {}".format(transfer_output)
# TODO test withdraw
Expand Down

0 comments on commit 41ded51

Please sign in to comment.