Skip to content

Commit

Permalink
Merge branch 'main' into cctl-modify-verbosity
Browse files Browse the repository at this point in the history
  • Loading branch information
marijanp authored Jul 16, 2024
2 parents 640b807 + abda197 commit f660259
Show file tree
Hide file tree
Showing 29 changed files with 256 additions and 65 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
43 changes: 40 additions & 3 deletions kairos-cli/src/client.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
use axum_extra::routing::TypedPath;
use casper_client::types::{DeployBuilder, DeployHash, ExecutableDeployItem, TimeDiff, Timestamp};
use casper_client_types::{crypto::SecretKey, runtime_args, ContractHash, RuntimeArgs, U512};
use kairos_server::routes::contract_hash::ContractHashPath;
use kairos_server::routes::deposit::DepositPath;
use kairos_server::routes::get_nonce::GetNoncePath;
use kairos_server::PublicKey;
use reqwest::Url;
use serde::{Deserialize, Serialize};
use std::fmt;
Expand All @@ -17,7 +20,7 @@ pub enum KairosClientError {
ResponseErrorWithCode(u16, String),
DecodeError(String),
CasperClientError(String),
KairosServerError(String),
KairosServerError(u16, String),
}

impl std::error::Error for KairosClientError {}
Expand Down Expand Up @@ -83,14 +86,48 @@ pub fn deposit(
.header("Content-Type", "application/json")
.json(&deploy)
.send()
.map_err(KairosClientError::from)?
.error_for_status();

match response {
Err(err) => Err(KairosClientError::from(err)),
Ok(response) => response
.json::<DeployHash>()
.map_err(KairosClientError::from),
}
}

pub fn get_nonce(base_url: &Url, account: &PublicKey) -> Result<u64, KairosClientError> {
let response = reqwest::blocking::Client::new()
.post(base_url.join(GetNoncePath::PATH).unwrap())
.header("Content-Type", "application/json")
.json(&account)
.send()
.map_err(KairosClientError::from)?
.error_for_status();

match response {
Err(err) => Err(KairosClientError::from(err)),
Ok(response) => response.json::<u64>().map_err(KairosClientError::from),
}
}

pub fn contract_hash(base_url: &Url) -> Result<ContractHash, KairosClientError> {
let response = reqwest::blocking::Client::new()
.get(base_url.join(ContractHashPath::PATH).unwrap())
.header("Content-Type", "application/json")
.send()
.map_err(KairosClientError::from)?;

let status = response.status();
if !status.is_success() {
Err(KairosClientError::KairosServerError(status.to_string()))
Err(KairosClientError::KairosServerError(
status.as_u16(),
status.to_string(),
))
} else {
response
.json::<DeployHash>()
.json::<ContractHash>()
.map_err(KairosClientError::from)
}
}
9 changes: 7 additions & 2 deletions kairos-cli/src/commands/deposit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,13 @@ pub fn run(args: Args, kairos_server_address: Url) -> Result<String, CliError> {
error: err.to_string(),
})?;

let contract_hash_bytes = <[u8; 32]>::from_hex(contract_hash)?;
let contract_hash = ContractHash::new(contract_hash_bytes);
let contract_hash = match contract_hash {
Some(contract_hash_string) => {
let contract_hash_bytes = <[u8; 32]>::from_hex(contract_hash_string)?;
ContractHash::new(contract_hash_bytes)
}
None => client::contract_hash(&kairos_server_address)?,
};

client::deposit(
&kairos_server_address,
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
22 changes: 17 additions & 5 deletions kairos-cli/src/commands/transfer.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::client::KairosClientError;
use crate::client::{self, KairosClientError};
use crate::common::args::{AmountArg, NonceArg, PrivateKeyPathArg, RecipientArg};
use crate::error::CliError;

Expand Down Expand Up @@ -30,15 +30,19 @@ pub fn run(args: Args, kairos_server_address: Url) -> Result<String, CliError> {
let amount: u64 = args.amount.field;
let signer =
Signer::from_private_key_file(args.private_key_path.field).map_err(CryptoError::from)?;
let nonce = args.nonce.val;
let signer_public_key = signer.to_public_key()?;
let nonce = match args.nonce.val {
None => client::get_nonce(&kairos_server_address, &signer_public_key)?,
Some(nonce) => nonce,
};

// 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()?,
public_key: signer_public_key,
payload: SigningPayload::new(nonce, Transfer::new(recipient, amount))
.try_into()
.unwrap(),
Expand All @@ -47,5 +51,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())
}
}
22 changes: 17 additions & 5 deletions kairos-cli/src/commands/withdraw.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::client::KairosClientError;
use crate::client::{self, KairosClientError};
use crate::common::args::{AmountArg, NonceArg, PrivateKeyPathArg};
use crate::error::CliError;

Expand Down Expand Up @@ -27,15 +27,19 @@ pub fn run(args: Args, kairos_server_address: Url) -> Result<String, CliError> {
let amount: u64 = args.amount.field;
let signer =
Signer::from_private_key_file(args.private_key_path.field).map_err(CryptoError::from)?;
let nonce = args.nonce.val;
let signer_public_key = signer.to_public_key()?;
let nonce = match args.nonce.val {
None => client::get_nonce(&kairos_server_address, &signer_public_key)?,
Some(nonce) => nonce,
};

// 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()?,
public_key: signer_public_key,
payload: SigningPayload::new(nonce, Withdrawal::new(amount))
.try_into()
.unwrap(),
Expand All @@ -44,5 +48,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())
}
}
4 changes: 2 additions & 2 deletions kairos-cli/src/common/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,13 @@ pub struct PrivateKeyPathArg {
#[derive(Args, Debug)]
pub struct NonceArg {
#[arg(id = "nonce", long, short, value_name = "NUM")]
pub val: u64,
pub val: Option<u64>,
}

#[derive(Args, Debug)]
pub struct ContractHashArg {
#[arg(id = "contract-hash", long, short = 'c', value_name = "CONTRACT_HASH")]
pub field: String,
pub field: Option<String>,
}

#[derive(Args, Debug)]
Expand Down
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
14 changes: 2 additions & 12 deletions kairos-cli/tests/cli_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,6 @@ async fn deposit_successful_with_ed25519() {
cmd.arg("--kairos-server-address")
.arg(kairos.url.as_str())
.arg("deposit")
.arg("--contract-hash")
.arg(contract_hash.to_string())
.arg("--amount")
.arg("123")
.arg("--private-key")
Expand Down Expand Up @@ -103,8 +101,6 @@ fn transfer_successful_with_secp256k1() {
.arg(recipient)
.arg("--amount")
.arg("123")
.arg("--nonce")
.arg("0")
.arg("--private-key")
.arg(secret_key_path);

Expand All @@ -122,8 +118,6 @@ fn withdraw_successful_with_ed25519() {
cmd.arg("withdraw")
.arg("--amount")
.arg("123")
.arg("--nonce")
.arg("0")
.arg("--private-key")
.arg(secret_key_path);

Expand Down Expand Up @@ -199,9 +193,7 @@ fn transfer_invalid_recipient() {
.arg("--amount")
.arg("123")
.arg("--private-key")
.arg(secret_key_path)
.arg("--nonce")
.arg("0");
.arg(secret_key_path);

cmd.assert()
.failure()
Expand All @@ -220,9 +212,7 @@ fn transfer_valid_recipient() {
.arg("--amount")
.arg("123")
.arg("--private-key")
.arg(secret_key_path)
.arg("--nonce")
.arg("0");
.arg(secret_key_path);

cmd.assert()
.failure()
Expand Down
10 changes: 10 additions & 0 deletions kairos-prover/kairos-circuit-logic/src/account_trie.rs
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,16 @@ impl<Db: DatabaseGet<Account>> AccountTrie<SnapshotBuilder<Db, Account>> {
Ok(())
}
}

/// Returns the nonce for an accounts public key if it's known, returns an error if unknown.
pub fn get_nonce_for(&self, account: &PublicKey) -> Result<u64, TxnErr> {
let [account_hash] = hash_buffers([account]);

let account = self.txn.get_exclude_from_txn(&account_hash)?;
let account = account.ok_or("Unknown account")?;

Ok(account.nonce)
}
}

/// An account in the trie.
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;
Loading

0 comments on commit f660259

Please sign in to comment.