Merge pull request #60 from vacp2p/refactor-cont

Refactor continued
This commit is contained in:
tyshko-rostyslav 2025-04-23 08:56:46 +02:00 committed by GitHub
commit a9b7f061fe
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
28 changed files with 127 additions and 260 deletions

19
Cargo.lock generated
View File

@ -13,6 +13,7 @@ dependencies = [
"env_logger",
"hex",
"k256",
"lazy_static",
"log",
"rand 0.8.5",
"serde",
@ -1150,24 +1151,6 @@ dependencies = [
"libc",
]
[[package]]
name = "core_primitives"
version = "0.1.0"
dependencies = [
"anyhow",
"common",
"elliptic-curve",
"env_logger",
"log",
"monotree",
"secp256k1-zkp",
"sequencer_core",
"serde",
"serde_json",
"sha2 0.10.8",
"storage",
]
[[package]]
name = "cpp_demangle"
version = "0.4.4"

View File

@ -17,7 +17,6 @@ members = [
"sequencer_core",
"common",
"sc_core",
"core_primitives",
]
[workspace.dependencies]
@ -30,7 +29,7 @@ actix = "0.13.0"
actix-cors = "0.6.1"
futures = "0.3"
actix-rt = "*"
lazy_static = "1.5.0"
env_logger = "0.10"
log = "0.4"
lru = "0.7.8"

View File

@ -15,6 +15,7 @@ rand.workspace = true
elliptic-curve.workspace = true
hex.workspace = true
aes-gcm.workspace = true
lazy_static.workspace = true
[dependencies.utxo]
path = "../utxo"

View File

@ -2,16 +2,21 @@ use elliptic_curve::{
consts::{B0, B1},
generic_array::GenericArray,
};
use lazy_static::lazy_static;
use sha2::digest::typenum::{UInt, UTerm};
pub const NULLIFIER_SECRET_CONST: [u8; 32] = [
38, 29, 97, 210, 148, 172, 75, 220, 36, 249, 27, 111, 73, 14, 250, 38, 55, 87, 164, 169, 95,
101, 135, 28, 212, 241, 107, 46, 162, 60, 59, 93,
];
pub const VIEVING_SECRET_CONST: [u8; 32] = [
97, 23, 175, 117, 11, 48, 215, 162, 150, 103, 46, 195, 179, 178, 93, 52, 137, 190, 202, 60,
254, 87, 112, 250, 57, 242, 117, 206, 195, 149, 213, 206,
];
lazy_static! {
pub static ref NULLIFIER_SECRET_CONST: [u8; 32] =
hex::decode(std::env::var("NULLIFIER_SECRET_CONST").unwrap())
.unwrap()
.try_into()
.unwrap();
pub static ref VIEWING_SECRET_CONST: [u8; 32] =
hex::decode(std::env::var("VIEWING_SECRET_CONST").unwrap())
.unwrap()
.try_into()
.unwrap();
}
pub type CipherText = Vec<u8>;
pub type Nonce = GenericArray<u8, UInt<UInt<UInt<UInt<UTerm, B1>, B1>, B0>, B0>>;

View File

@ -112,10 +112,9 @@ mod tests {
Aes256Gcm,
};
use constants_types::{CipherText, Nonce};
use constants_types::{NULLIFIER_SECRET_CONST, VIEVING_SECRET_CONST};
use constants_types::{NULLIFIER_SECRET_CONST, VIEWING_SECRET_CONST};
use elliptic_curve::ff::Field;
use elliptic_curve::group::prime::PrimeCurveAffine;
use elliptic_curve::group::GroupEncoding;
use k256::{AffinePoint, ProjectivePoint, Scalar};
use super::*;
@ -360,9 +359,9 @@ mod tests {
);
println!(
"Nullifier constant {:?}",
hex::encode(NULLIFIER_SECRET_CONST)
hex::encode(*NULLIFIER_SECRET_CONST)
);
println!("Viewing constatnt {:?}", hex::encode(VIEVING_SECRET_CONST));
println!("Viewing constatnt {:?}", hex::encode(*VIEWING_SECRET_CONST));
println!();
println!("======Holders======");

View File

@ -4,7 +4,7 @@ use k256::{AffinePoint, FieldBytes, Scalar};
use rand::{rngs::OsRng, RngCore};
use sha2::{digest::FixedOutput, Digest};
use super::constants_types::{NULLIFIER_SECRET_CONST, VIEVING_SECRET_CONST};
use super::constants_types::{NULLIFIER_SECRET_CONST, VIEWING_SECRET_CONST};
#[derive(Debug)]
///Seed holder. Non-clonable to ensure that different holders use different seeds.
@ -63,7 +63,7 @@ impl TopSecretKeyHolder {
let mut hasher = sha2::Sha256::new();
hasher.update(self.secret_spending_key.to_bytes());
hasher.update(NULLIFIER_SECRET_CONST);
hasher.update(*NULLIFIER_SECRET_CONST);
let hash = <TreeHashType>::from(hasher.finalize_fixed());
@ -74,7 +74,7 @@ impl TopSecretKeyHolder {
let mut hasher = sha2::Sha256::new();
hasher.update(self.secret_spending_key.to_bytes());
hasher.update(VIEVING_SECRET_CONST);
hasher.update(*VIEWING_SECRET_CONST);
let hash = <TreeHashType>::from(hasher.finalize_fixed());

View File

@ -1,4 +1,5 @@
set -e
curl -L https://risczero.com/install | bash
/Users/runner/.risc0/bin/rzup install
source env.sh
RUSTFLAGS="-D warnings" cargo build

View File

@ -1,4 +1,5 @@
set -e
curl -L https://risczero.com/install | bash
/home/runner/.risc0/bin/rzup install
source env.sh
RUSTFLAGS="-D warnings" cargo build

View File

@ -2,6 +2,7 @@ set -e
curl -L https://risczero.com/install | bash
/home/runner/.risc0/bin/rzup install
source env.sh
cargo install taplo-cli --locked
cargo fmt -- --check

View File

@ -2,5 +2,6 @@ set -e
curl -L https://risczero.com/install | bash
/home/runner/.risc0/bin/rzup install
source env.sh
cargo test --release

View File

@ -125,9 +125,6 @@ impl Default for NullifierSparseMerkleTree {
mod tests {
use super::*;
use crate::nullifier::UTXONullifier;
use monotree::database::MemoryDB;
use monotree::hasher::Blake3;
use monotree::Monotree;
fn create_nullifier(hash: TreeHashType) -> UTXONullifier {
UTXONullifier { utxo_hash: hash }

View File

@ -1,27 +0,0 @@
[package]
name = "core_primitives"
version = "0.1.0"
edition = "2021"
[dependencies]
anyhow.workspace = true
serde_json.workspace = true
env_logger.workspace = true
log.workspace = true
serde.workspace = true
sha2.workspace = true
elliptic-curve.workspace = true
monotree.workspace = true
[dependencies.secp256k1-zkp]
workspace = true
features = ["std", "rand-std", "rand", "serde", "global-context"]
[dependencies.storage]
path = "../storage"
[dependencies.sequencer_core]
path = "../sequencer_core"
[dependencies.common]
path = "../common"

View File

@ -1,16 +0,0 @@
use crate::merkle_tree_public::CommitmentHashType;
use monotree::database::MemoryDB;
use monotree::hasher::Blake3;
use monotree::Monotree;
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq, Eq)]
pub struct Commitment {
pub commitment_hash: CommitmentHashType,
}
pub struct CommitmentsSparseMerkleTree {
pub curr_root: Option<CommitmentHashType>,
pub tree: Monotree<MemoryDB, Blake3>,
pub hasher: Blake3,
}

View File

@ -1,5 +0,0 @@
pub mod commitment;
pub mod merkle_tree_public;
pub mod nullifier;
pub mod transaction;
pub mod utxo;

View File

@ -1,2 +0,0 @@
pub type TreeHashType = [u8; 32];
pub type CommitmentHashType = Vec<u8>;

View File

@ -1,18 +0,0 @@
use crate::merkle_tree_public::TreeHashType;
use monotree::database::MemoryDB;
use monotree::hasher::Blake3;
use monotree::Monotree;
use serde::{Deserialize, Serialize};
//ToDo: Update Nullifier model, when it is clear
#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq, Eq)]
///General nullifier object
pub struct UTXONullifier {
pub utxo_hash: TreeHashType,
}
pub struct NullifierSparseMerkleTree {
pub curr_root: Option<TreeHashType>,
pub tree: Monotree<MemoryDB, Blake3>,
pub hasher: Blake3,
}

View File

@ -1,70 +0,0 @@
use serde::{Deserialize, Serialize};
use crate::merkle_tree_public::TreeHashType;
use elliptic_curve::{
consts::{B0, B1},
generic_array::GenericArray,
};
use secp256k1_zkp::PedersenCommitment;
use sha2::digest::typenum::{UInt, UTerm};
pub type CipherText = Vec<u8>;
pub type Nonce = GenericArray<u8, UInt<UInt<UInt<UInt<UTerm, B1>, B1>, B0>, B0>>;
#[derive(Debug, Serialize, Deserialize, Clone, Copy)]
pub enum TxKind {
Public,
Private,
Shielded,
Deshielded,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
///General transaction object
pub struct Transaction {
pub hash: TreeHashType,
pub tx_kind: TxKind,
///Tx input data (public part)
pub execution_input: Vec<u8>,
///Tx output data (public_part)
pub execution_output: Vec<u8>,
///Tx input utxo commitments
pub utxo_commitments_spent_hashes: Vec<TreeHashType>,
///Tx output utxo commitments
pub utxo_commitments_created_hashes: Vec<TreeHashType>,
///Tx output nullifiers
pub nullifier_created_hashes: Vec<TreeHashType>,
///Execution proof (private part)
pub execution_proof_private: String,
///Encoded blobs of data
pub encoded_data: Vec<(CipherText, Vec<u8>)>,
///Transaction senders ephemeral pub key
pub ephemeral_pub_key: Vec<u8>,
///Public (Pedersen) commitment
pub commitment: PedersenCommitment,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
///General transaction object
pub struct TransactionPayload {
pub tx_kind: TxKind,
///Tx input data (public part)
pub execution_input: Vec<u8>,
///Tx output data (public_part)
pub execution_output: Vec<u8>,
///Tx input utxo commitments
pub utxo_commitments_spent_hashes: Vec<TreeHashType>,
///Tx output utxo commitments
pub utxo_commitments_created_hashes: Vec<TreeHashType>,
///Tx output nullifiers
pub nullifier_created_hashes: Vec<TreeHashType>,
///Execution proof (private part)
pub execution_proof_private: String,
///Encoded blobs of data
pub encoded_data: Vec<(CipherText, Vec<u8>)>,
///Transaction senders ephemeral pub key
pub ephemeral_pub_key: Vec<u8>,
///Public (Pedersen) commitment
pub commitment: PedersenCommitment,
}

View File

@ -1,26 +0,0 @@
use common::{merkle_tree_public::TreeHashType, nullifier::UTXONullifier, AccountId};
use serde::{Deserialize, Serialize};
///Raw asset data
pub type Asset = Vec<u8>;
#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
///Container for raw utxo payload
pub struct UTXO {
pub hash: TreeHashType,
pub owner: AccountId,
pub nullifier: Option<UTXONullifier>,
pub asset: Asset,
// TODO: change to u256
pub amount: u128,
pub privacy_flag: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UTXOPayload {
pub owner: AccountId,
pub asset: Asset,
// TODO: change to u256
pub amount: u128,
pub privacy_flag: bool,
}

2
env.sh Normal file
View File

@ -0,0 +1,2 @@
export NULLIFIER_SECRET_CONST="261d61d294ac4bdc24f91b6f490efa263757a4a95f65871cd4f16b2ea23c3b5d"
export VIEWING_SECRET_CONST="6117af750b30d7a296672ec3b3b25d3489beca3cfe5770fa39f275cec395d5ce"

View File

@ -4,6 +4,15 @@ use accounts::account_core::{AccountAddress, AccountPublicMask};
use common::merkle_tree_public::TreeHashType;
use serde::{ser::SerializeStruct, Serialize};
pub const PUBLIC_SC_CONTEXT: &str = "PublicSCContext";
pub const CALLER_ADDRESS: &str = "caller_address";
pub const CALLER_BALANCE: &str = "caller_balance";
pub const ACCOUNT_MASKS_KEYS_SORTED: &str = "account_masks_keys_sorted";
pub const ACCOUNT_MASKS_VALUES_SORTED: &str = "account_masks_values_sorted";
pub const NULLIFIER_STORE_ROOT: &str = "nullifier_store_root";
pub const COMMITMENT_STORE_ROOT: &str = "commitment_store_root";
pub const PUT_TX_STORE_ROOT: &str = "put_tx_store_root";
///Strucutre, representing context, given to a smart contract on a call
pub struct PublicSCContext {
pub caller_address: AccountAddress,
@ -26,15 +35,15 @@ impl Serialize for PublicSCContext {
self.account_masks.values().cloned().collect();
account_mask_values.sort_by(|left, right| left.address.cmp(&right.address));
let mut s = serializer.serialize_struct("PublicSCContext", 7)?;
let mut s = serializer.serialize_struct(PUBLIC_SC_CONTEXT, 7)?;
s.serialize_field("caller_address", &self.caller_address)?;
s.serialize_field("caller_balance", &self.caller_balance)?;
s.serialize_field("account_masks_keys_sorted", &account_masks_keys)?;
s.serialize_field("account_masks_values_sorted", &account_mask_values)?;
s.serialize_field("nullifier_store_root", &self.nullifier_store_root)?;
s.serialize_field("commitment_store_root", &self.comitment_store_root)?;
s.serialize_field("put_tx_store_root", &self.pub_tx_store_root)?;
s.serialize_field(CALLER_ADDRESS, &self.caller_address)?;
s.serialize_field(CALLER_BALANCE, &self.caller_balance)?;
s.serialize_field(ACCOUNT_MASKS_KEYS_SORTED, &account_masks_keys)?;
s.serialize_field(ACCOUNT_MASKS_VALUES_SORTED, &account_mask_values)?;
s.serialize_field(NULLIFIER_STORE_ROOT, &self.nullifier_store_root)?;
s.serialize_field(COMMITMENT_STORE_ROOT, &self.comitment_store_root)?;
s.serialize_field(PUT_TX_STORE_ROOT, &self.pub_tx_store_root)?;
s.end()
}

View File

@ -33,6 +33,28 @@ use crate::types::{
},
};
pub const WRITE_REGISTER_ACCOUNT: &str = "write_register_account";
pub const EXECUTE_SUBSCENARIO: &str = "execute_subscenario";
pub const GET_BLOCK: &str = "get_block";
pub const GET_LAST_BLOCK: &str = "get_last_block";
pub const EXECUTE_SCENARIO_SPLIT: &str = "execute_scenario_split";
pub const EXECUTE_SCENARIO_MULTIPLE_SEND: &str = "execute_scenario_multiple_send";
pub const SHOW_ACCOUNT_PUBLIC_BALANCE: &str = "show_account_public_balance";
pub const SHOW_ACCOUNT_UTXO: &str = "show_account_utxo";
pub const SHOW_TRANSACTION: &str = "show_transaction";
pub const WRITE_DEPOSIT_PUBLIC_BALANCE: &str = "write_deposit_public_balance";
pub const WRITE_MINT_UTXO: &str = "write_mint_utxo";
pub const WRITE_MINT_UTXO_MULTIPLE_ASSETS: &str = "write_mint_utxo_multiple_assets";
pub const WRITE_SEND_UTXO_PRIVATE: &str = "write_send_utxo_private";
pub const WRITE_SEND_UTXO_SHIELDED: &str = "write_send_utxo_shielded";
pub const WRITE_SEND_UTXO_DESHIELDED: &str = "write_send_utxo_deshielded";
pub const WRITE_SPLIT_UTXO: &str = "write_split_utxo";
pub const SUCCESS: &str = "success";
pub const ACCOUNT_NOT_FOUND: &str = "Account not found";
pub const TRANSACTION_NOT_FOUND: &str = "Transaction not found";
use super::{respond, types::err_rpc::RpcErr, JsonHandler};
impl JsonHandler {
@ -83,7 +105,7 @@ impl JsonHandler {
}
let helperstruct = ExecuteSubscenarioResponse {
scenario_result: "success".to_string(),
scenario_result: SUCCESS.to_string(),
};
respond(helperstruct)
@ -105,7 +127,7 @@ impl JsonHandler {
}
let helperstruct = ExecuteScenarioSplitResponse {
scenario_result: "success".to_string(),
scenario_result: SUCCESS.to_string(),
};
respond(helperstruct)
@ -127,7 +149,7 @@ impl JsonHandler {
}
let helperstruct = ExecuteScenarioMultipleSendResponse {
scenario_result: "success".to_string(),
scenario_result: SUCCESS.to_string(),
};
respond(helperstruct)
@ -201,7 +223,7 @@ impl JsonHandler {
let acc = under_guard
.acc_map
.get(&acc_addr)
.ok_or(RpcError::new_internal_error(None, "Account not found"))?;
.ok_or(RpcError::new_internal_error(None, ACCOUNT_NOT_FOUND))?;
acc.balance
}
@ -243,7 +265,7 @@ impl JsonHandler {
let acc = under_guard
.acc_map
.get_mut(&acc_addr)
.ok_or(RpcError::new_internal_error(None, "Account not found"))?;
.ok_or(RpcError::new_internal_error(None, ACCOUNT_NOT_FOUND))?;
let utxo = acc
.utxo_tree
@ -253,7 +275,7 @@ impl JsonHandler {
})?
.ok_or(RpcError::new_internal_error(
None,
"UTXO does not exist in tree",
"UTXO does not exist in the tree",
))?;
(utxo.asset.clone(), utxo.amount)
@ -289,7 +311,7 @@ impl JsonHandler {
let tx = under_guard
.pub_tx_store
.get_tx(tx_hash)
.ok_or(RpcError::new_internal_error(None, "Transactio not found"))?;
.ok_or(RpcError::new_internal_error(None, TRANSACTION_NOT_FOUND))?;
ShowTransactionResponse {
hash: req.tx_hash,
@ -360,7 +382,7 @@ impl JsonHandler {
};
let helperstruct = WriteDepositPublicBalanceResponse {
status: "success".to_string(),
status: SUCCESS.to_string(),
};
respond(helperstruct)
@ -387,7 +409,7 @@ impl JsonHandler {
};
let helperstruct = WriteMintPrivateUTXOResponse {
status: "success".to_string(),
status: SUCCESS.to_string(),
utxo: UTXOShortEssentialStruct {
hash: hex::encode(utxo.hash),
commitment_hash: hex::encode(commitment_hash),
@ -426,7 +448,7 @@ impl JsonHandler {
};
let helperstruct = WriteMintPrivateUTXOMultipleAssetsResponse {
status: "success".to_string(),
status: SUCCESS.to_string(),
utxos: utxos
.into_iter()
.zip(commitment_hashes)
@ -488,7 +510,7 @@ impl JsonHandler {
let acc = under_guard
.acc_map
.get_mut(&acc_addr_sender)
.ok_or(RpcError::new_internal_error(None, "Account not found"))?;
.ok_or(RpcError::new_internal_error(None, ACCOUNT_NOT_FOUND))?;
acc.utxo_tree
.get_item(utxo_hash)
@ -509,7 +531,7 @@ impl JsonHandler {
};
let helperstruct = WriteSendPrivateUTXOResponse {
status: "success".to_string(),
status: SUCCESS.to_string(),
utxo_result: UTXOShortEssentialStruct {
hash: hex::encode(new_utxo_rec.hash),
asset: new_utxo_rec.asset.clone(),
@ -562,7 +584,7 @@ impl JsonHandler {
};
let helperstruct = WriteSendShieldedUTXOResponse {
status: "success".to_string(),
status: SUCCESS.to_string(),
utxo_result: UTXOShortEssentialStruct {
hash: hex::encode(new_utxo_rec.hash),
asset: new_utxo_rec.asset.clone(),
@ -623,7 +645,7 @@ impl JsonHandler {
let acc = under_guard
.acc_map
.get_mut(&acc_addr_sender)
.ok_or(RpcError::new_internal_error(None, "Account not found"))?;
.ok_or(RpcError::new_internal_error(None, ACCOUNT_NOT_FOUND))?;
acc.utxo_tree
.get_item(utxo_hash)
@ -649,7 +671,7 @@ impl JsonHandler {
};
let helperstruct = WriteSendDeshieldedUTXOResponse {
status: "success".to_string(),
status: SUCCESS.to_string(),
};
respond(helperstruct)
@ -716,7 +738,7 @@ impl JsonHandler {
let acc = under_guard
.acc_map
.get_mut(&acc_addr_sender)
.ok_or(RpcError::new_internal_error(None, "Account not found"))?;
.ok_or(RpcError::new_internal_error(None, ACCOUNT_NOT_FOUND))?;
acc.utxo_tree
.get_item(utxo_hash)
@ -742,7 +764,7 @@ impl JsonHandler {
};
let helperstruct = WriteSendSplitUTXOResponse {
status: "success".to_string(),
status: SUCCESS.to_string(),
utxo_results: new_utxos
.into_iter()
.zip(commitment_hashes)
@ -760,31 +782,29 @@ impl JsonHandler {
pub async fn process_request_internal(&self, request: Request) -> Result<Value, RpcErr> {
match request.method.as_ref() {
//Todo : Add handling of more JSON RPC methods
"write_register_account" => self.process_register_account(request).await,
"execute_subscenario" => self.process_request_execute_subscenario(request).await,
"get_block" => self.process_get_block_data(request).await,
"get_last_block" => self.process_get_last_block(request).await,
"execute_scenario_split" => self.process_request_execute_scenario_split(request).await,
"execute_scenario_multiple_send" => {
WRITE_REGISTER_ACCOUNT => self.process_register_account(request).await,
EXECUTE_SUBSCENARIO => self.process_request_execute_subscenario(request).await,
GET_BLOCK => self.process_get_block_data(request).await,
GET_LAST_BLOCK => self.process_get_last_block(request).await,
EXECUTE_SCENARIO_SPLIT => self.process_request_execute_scenario_split(request).await,
EXECUTE_SCENARIO_MULTIPLE_SEND => {
self.process_request_execute_scenario_multiple_send(request)
.await
}
"show_account_public_balance" => {
self.process_show_account_public_balance(request).await
}
"show_account_utxo" => self.process_show_account_utxo_request(request).await,
"show_transaction" => self.process_show_transaction(request).await,
"write_deposit_public_balance" => {
SHOW_ACCOUNT_PUBLIC_BALANCE => self.process_show_account_public_balance(request).await,
SHOW_ACCOUNT_UTXO => self.process_show_account_utxo_request(request).await,
SHOW_TRANSACTION => self.process_show_transaction(request).await,
WRITE_DEPOSIT_PUBLIC_BALANCE => {
self.process_write_deposit_public_balance(request).await
}
"write_mint_utxo" => self.process_write_mint_utxo(request).await,
"write_mint_utxo_multiple_assets" => {
WRITE_MINT_UTXO => self.process_write_mint_utxo(request).await,
WRITE_MINT_UTXO_MULTIPLE_ASSETS => {
self.process_write_mint_utxo_multiple_assets(request).await
}
"write_send_utxo_private" => self.process_write_send_private_utxo(request).await,
"write_send_utxo_shielded" => self.process_write_send_shielded_utxo(request).await,
"write_send_utxo_deshielded" => self.process_write_send_deshielded_utxo(request).await,
"write_split_utxo" => self.process_write_send_split_utxo(request).await,
WRITE_SEND_UTXO_PRIVATE => self.process_write_send_private_utxo(request).await,
WRITE_SEND_UTXO_SHIELDED => self.process_write_send_shielded_utxo(request).await,
WRITE_SEND_UTXO_DESHIELDED => self.process_write_send_deshielded_utxo(request).await,
WRITE_SPLIT_UTXO => self.process_write_send_split_utxo(request).await,
_ => Err(RpcErr(RpcError::method_not_found(request.method))),
}
}

View File

@ -1,5 +1,4 @@
use ark_bn254::Fr;
// use ark_ff::{BigInteger, PrimeField};
use light_poseidon::{Poseidon, PoseidonBytesHasher};
#[allow(unused)]

View File

@ -260,7 +260,7 @@ impl SequencerCore {
#[cfg(test)]
mod tests {
use super::*;
use std::{fmt::format, path::PathBuf};
use std::path::PathBuf;
use common::transaction::{Transaction, TxKind};
use rand::Rng;

View File

@ -16,6 +16,8 @@ use super::JsonHandler;
pub const SHUTDOWN_TIMEOUT_SECS: u64 = 10;
pub const NETWORK: &str = "network";
fn rpc_handler(
message: web::Json<Message>,
handler: web::Data<JsonHandler>,
@ -51,7 +53,7 @@ pub fn new_http_server(
polling_config,
limits_config,
} = config;
info!(target:"network", "Starting http server at {}", addr);
info!(target:NETWORK, "Starting http server at {}", addr);
let handler = web::Data::new(JsonHandler {
polling_config,
sequencer_state: seuquencer_core.clone(),

View File

@ -16,6 +16,17 @@ use common::rpc_primitives::requests::{
use super::{respond, types::err_rpc::RpcErr, JsonHandler};
pub const HELLO: &str = "hello";
pub const REGISTER_ACCOUNT: &str = "register_account";
pub const SEND_TX: &str = "send_tx";
pub const GET_BLOCK: &str = "get_block";
pub const GET_GENESIS: &str = "get_genesis";
pub const GET_LAST_BLOCK: &str = "get_last_block";
pub const HELLO_FROM_SEQUENCER: &str = "HELLO_FROM_SEQUENCER";
pub const SUCCESS: &str = "Success";
impl JsonHandler {
pub async fn process(&self, message: Message) -> Result<Message, HttpError> {
let id = message.id();
@ -38,7 +49,7 @@ impl JsonHandler {
let _hello_request = HelloRequest::parse(Some(request.params))?;
let helperstruct = HelloResponse {
greeting: "HELLO_FROM_SEQUENCER".to_string(),
greeting: HELLO_FROM_SEQUENCER.to_string(),
};
respond(helperstruct)
@ -58,7 +69,7 @@ impl JsonHandler {
}
let helperstruct = RegisterAccountResponse {
status: "Success".to_string(),
status: SUCCESS.to_string(),
};
respond(helperstruct)
@ -77,7 +88,7 @@ impl JsonHandler {
}
let helperstruct = SendTxResponse {
status: "Success".to_string(),
status: SUCCESS.to_string(),
};
respond(helperstruct)
@ -130,12 +141,12 @@ impl JsonHandler {
pub async fn process_request_internal(&self, request: Request) -> Result<Value, RpcErr> {
match request.method.as_ref() {
"hello" => self.process_temp_hello(request).await,
"register_account" => self.process_register_account_request(request).await,
"send_tx" => self.process_send_tx(request).await,
"get_block" => self.process_get_block_data(request).await,
"get_genesis" => self.process_get_genesis(request).await,
"get_last_block" => self.process_get_last_block(request).await,
HELLO => self.process_temp_hello(request).await,
REGISTER_ACCOUNT => self.process_register_account_request(request).await,
SEND_TX => self.process_send_tx(request).await,
GET_BLOCK => self.process_get_block_data(request).await,
GET_GENESIS => self.process_get_genesis(request).await,
GET_LAST_BLOCK => self.process_get_last_block(request).await,
_ => Err(RpcErr(RpcError::method_not_found(request.method))),
}
}

View File

@ -1,2 +1 @@
pub mod err_rpc;
pub mod parse;

View File

@ -1 +0,0 @@

View File

@ -10,6 +10,8 @@ use tokio::sync::Mutex;
pub mod config;
pub const RUST_LOG: &str = "RUST_LOG";
#[derive(Parser, Debug)]
#[clap(version)]
struct Args {
@ -29,7 +31,7 @@ pub async fn main_runner() -> Result<()> {
if let Some(ref rust_log) = app_config.override_rust_log {
info!("RUST_LOG env var set to {rust_log:?}");
std::env::set_var("RUST_LOG", rust_log);
std::env::set_var(RUST_LOG, rust_log);
}
env_logger::init();