mirror of
https://github.com/logos-blockchain/lssa.git
synced 2026-01-02 05:13:08 +00:00
feat: enhance rustfmt config
This commit is contained in:
parent
72d20a3546
commit
a714e3c563
10
.github/workflows/ci.yml
vendored
10
.github/workflows/ci.yml
vendored
@ -21,10 +21,14 @@ jobs:
|
|||||||
name: ubuntu-latest-pipeline
|
name: ubuntu-latest-pipeline
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- name: Install toolchain
|
|
||||||
uses: actions-rs/toolchain@v1
|
- name: Install active toolchain
|
||||||
|
run: rustup install
|
||||||
|
|
||||||
|
- name: Install nightly toolchain for rustfmt
|
||||||
|
run: rustup install nightly --profile minimal --component rustfmt
|
||||||
|
|
||||||
- name: lint - ubuntu-latest
|
- name: lint - ubuntu-latest
|
||||||
if: success() || failure()
|
|
||||||
run: chmod 777 ./ci_scripts/lint-ubuntu.sh && ./ci_scripts/lint-ubuntu.sh
|
run: chmod 777 ./ci_scripts/lint-ubuntu.sh && ./ci_scripts/lint-ubuntu.sh
|
||||||
- name: test ubuntu-latest
|
- name: test ubuntu-latest
|
||||||
if: success() || failure()
|
if: success() || failure()
|
||||||
|
|||||||
@ -1,8 +1,8 @@
|
|||||||
set -e
|
set -e
|
||||||
|
|
||||||
cargo install taplo-cli --locked
|
cargo +nightly fmt -- --check
|
||||||
|
|
||||||
cargo fmt -- --check
|
cargo install taplo-cli --locked
|
||||||
taplo fmt --check
|
taplo fmt --check
|
||||||
|
|
||||||
RISC0_SKIP_BUILD=1 cargo clippy --workspace --all-targets -- -D warnings
|
RISC0_SKIP_BUILD=1 cargo clippy --workspace --all-targets -- -D warnings
|
||||||
|
|||||||
@ -6,7 +6,7 @@ use crate::transaction::EncodedTransaction;
|
|||||||
pub type HashType = [u8; 32];
|
pub type HashType = [u8; 32];
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
///Our own hasher.
|
/// Our own hasher.
|
||||||
/// Currently it is SHA256 hasher wrapper. May change in a future.
|
/// Currently it is SHA256 hasher wrapper. May change in a future.
|
||||||
pub struct OwnHasher {}
|
pub struct OwnHasher {}
|
||||||
|
|
||||||
|
|||||||
@ -4,8 +4,8 @@ pub mod rpc_primitives;
|
|||||||
pub mod sequencer_client;
|
pub mod sequencer_client;
|
||||||
pub mod transaction;
|
pub mod transaction;
|
||||||
|
|
||||||
//Module for tests utility functions
|
// Module for tests utility functions
|
||||||
//TODO: Compile only for tests
|
// TODO: Compile only for tests
|
||||||
pub mod test_utils;
|
pub mod test_utils;
|
||||||
pub type HashType = [u8; 32];
|
pub type HashType = [u8; 32];
|
||||||
|
|
||||||
|
|||||||
@ -1,6 +1,7 @@
|
|||||||
use serde_json::{Value, to_value};
|
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
|
|
||||||
|
use serde_json::{Value, to_value};
|
||||||
|
|
||||||
#[derive(serde::Serialize)]
|
#[derive(serde::Serialize)]
|
||||||
pub struct RpcParseError(pub String);
|
pub struct RpcParseError(pub String);
|
||||||
|
|
||||||
|
|||||||
@ -9,11 +9,14 @@
|
|||||||
//!
|
//!
|
||||||
//! The main entrypoint here is the [Message](enum.Message.html). The others are just building
|
//! The main entrypoint here is the [Message](enum.Message.html). The others are just building
|
||||||
//! blocks and you should generally work with `Message` instead.
|
//! blocks and you should generally work with `Message` instead.
|
||||||
use serde::de::{Deserializer, Error, Unexpected, Visitor};
|
|
||||||
use serde::ser::{SerializeStruct, Serializer};
|
|
||||||
use serde_json::{Result as JsonResult, Value};
|
|
||||||
use std::fmt::{Formatter, Result as FmtResult};
|
use std::fmt::{Formatter, Result as FmtResult};
|
||||||
|
|
||||||
|
use serde::{
|
||||||
|
de::{Deserializer, Error, Unexpected, Visitor},
|
||||||
|
ser::{SerializeStruct, Serializer},
|
||||||
|
};
|
||||||
|
use serde_json::{Result as JsonResult, Value};
|
||||||
|
|
||||||
use super::errors::RpcError;
|
use super::errors::RpcError;
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||||
@ -69,6 +72,7 @@ impl Request {
|
|||||||
id: self.id.clone(),
|
id: self.id.clone(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Answer the request with an error.
|
/// Answer the request with an error.
|
||||||
pub fn error(&self, error: RpcError) -> Message {
|
pub fn error(&self, error: RpcError) -> Message {
|
||||||
Message::Response(Response {
|
Message::Response(Response {
|
||||||
@ -207,6 +211,7 @@ impl Message {
|
|||||||
id,
|
id,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Create a top-level error (without an ID).
|
/// Create a top-level error (without an ID).
|
||||||
pub fn error(error: RpcError) -> Self {
|
pub fn error(error: RpcError) -> Self {
|
||||||
Message::Response(Response {
|
Message::Response(Response {
|
||||||
@ -215,6 +220,7 @@ impl Message {
|
|||||||
id: Value::Null,
|
id: Value::Null,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A constructor for a notification.
|
/// A constructor for a notification.
|
||||||
pub fn notification(method: String, params: Value) -> Self {
|
pub fn notification(method: String, params: Value) -> Self {
|
||||||
Message::Notification(Notification {
|
Message::Notification(Notification {
|
||||||
@ -223,6 +229,7 @@ impl Message {
|
|||||||
params,
|
params,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A constructor for a response.
|
/// A constructor for a response.
|
||||||
pub fn response(id: Value, result: Result<Value, RpcError>) -> Self {
|
pub fn response(id: Value, result: Result<Value, RpcError>) -> Self {
|
||||||
Message::Response(Response {
|
Message::Response(Response {
|
||||||
@ -231,6 +238,7 @@ impl Message {
|
|||||||
id,
|
id,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns id or Null if there is no id.
|
/// Returns id or Null if there is no id.
|
||||||
pub fn id(&self) -> Value {
|
pub fn id(&self) -> Value {
|
||||||
match self {
|
match self {
|
||||||
@ -315,10 +323,7 @@ impl From<Message> for Vec<u8> {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use serde_json::Value;
|
use serde_json::{Value, de::from_slice, json, ser::to_vec};
|
||||||
use serde_json::de::from_slice;
|
|
||||||
use serde_json::json;
|
|
||||||
use serde_json::ser::to_vec;
|
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
|||||||
@ -1,14 +1,15 @@
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
use crate::parse_request;
|
|
||||||
|
|
||||||
use super::errors::RpcParseError;
|
|
||||||
use super::parser::RpcRequest;
|
|
||||||
use super::parser::parse_params;
|
|
||||||
use nssa_core::program::ProgramId;
|
use nssa_core::program::ProgramId;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
|
|
||||||
|
use super::{
|
||||||
|
errors::RpcParseError,
|
||||||
|
parser::{RpcRequest, parse_params},
|
||||||
|
};
|
||||||
|
use crate::parse_request;
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
#[derive(Serialize, Deserialize, Debug)]
|
||||||
pub struct HelloRequest {}
|
pub struct HelloRequest {}
|
||||||
|
|
||||||
|
|||||||
@ -1,13 +1,13 @@
|
|||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
//Requests
|
// Requests
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
#[derive(Serialize, Deserialize, Debug)]
|
||||||
pub struct SendTxRequest {
|
pub struct SendTxRequest {
|
||||||
pub transaction: Vec<u8>,
|
pub transaction: Vec<u8>,
|
||||||
}
|
}
|
||||||
|
|
||||||
//Responses
|
// Responses
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
#[derive(Serialize, Deserialize, Debug)]
|
||||||
pub struct SendTxResponse {
|
pub struct SendTxResponse {
|
||||||
@ -15,7 +15,7 @@ pub struct SendTxResponse {
|
|||||||
pub tx_hash: String,
|
pub tx_hash: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
//General
|
// General
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize)]
|
#[derive(Debug, Clone, Serialize)]
|
||||||
pub struct SequencerRpcRequest {
|
pub struct SequencerRpcRequest {
|
||||||
@ -31,7 +31,7 @@ impl SequencerRpcRequest {
|
|||||||
jsonrpc: "2.0".to_string(),
|
jsonrpc: "2.0".to_string(),
|
||||||
method,
|
method,
|
||||||
params: payload,
|
params: payload,
|
||||||
//ToDo: Correct checking of id
|
// ToDo: Correct checking of id
|
||||||
id: 1,
|
id: 1,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,24 +1,26 @@
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
use super::rpc_primitives::requests::{
|
|
||||||
GetAccountBalanceRequest, GetAccountBalanceResponse, GetBlockDataRequest, GetBlockDataResponse,
|
|
||||||
GetGenesisIdRequest, GetGenesisIdResponse, GetInitialTestnetAccountsRequest,
|
|
||||||
};
|
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use json::{SendTxRequest, SendTxResponse, SequencerRpcRequest, SequencerRpcResponse};
|
use json::{SendTxRequest, SendTxResponse, SequencerRpcRequest, SequencerRpcResponse};
|
||||||
use nssa_core::program::ProgramId;
|
use nssa_core::program::ProgramId;
|
||||||
use reqwest::Client;
|
use reqwest::Client;
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
|
|
||||||
use crate::error::{SequencerClientError, SequencerRpcError};
|
use super::rpc_primitives::requests::{
|
||||||
use crate::rpc_primitives::requests::{
|
GetAccountBalanceRequest, GetAccountBalanceResponse, GetBlockDataRequest, GetBlockDataResponse,
|
||||||
GetAccountRequest, GetAccountResponse, GetAccountsNoncesRequest, GetAccountsNoncesResponse,
|
GetGenesisIdRequest, GetGenesisIdResponse, GetInitialTestnetAccountsRequest,
|
||||||
GetLastBlockRequest, GetLastBlockResponse, GetProgramIdsRequest, GetProgramIdsResponse,
|
};
|
||||||
GetProofForCommitmentRequest, GetProofForCommitmentResponse, GetTransactionByHashRequest,
|
use crate::{
|
||||||
GetTransactionByHashResponse,
|
error::{SequencerClientError, SequencerRpcError},
|
||||||
|
rpc_primitives::requests::{
|
||||||
|
GetAccountRequest, GetAccountResponse, GetAccountsNoncesRequest, GetAccountsNoncesResponse,
|
||||||
|
GetLastBlockRequest, GetLastBlockResponse, GetProgramIdsRequest, GetProgramIdsResponse,
|
||||||
|
GetProofForCommitmentRequest, GetProofForCommitmentResponse, GetTransactionByHashRequest,
|
||||||
|
GetTransactionByHashResponse,
|
||||||
|
},
|
||||||
|
sequencer_client::json::AccountInitialData,
|
||||||
|
transaction::{EncodedTransaction, NSSATransaction},
|
||||||
};
|
};
|
||||||
use crate::sequencer_client::json::AccountInitialData;
|
|
||||||
use crate::transaction::{EncodedTransaction, NSSATransaction};
|
|
||||||
|
|
||||||
pub mod json;
|
pub mod json;
|
||||||
|
|
||||||
@ -62,7 +64,7 @@ impl SequencerClient {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
///Get block data at `block_id` from sequencer
|
/// Get block data at `block_id` from sequencer
|
||||||
pub async fn get_block(
|
pub async fn get_block(
|
||||||
&self,
|
&self,
|
||||||
block_id: u64,
|
block_id: u64,
|
||||||
@ -78,7 +80,7 @@ impl SequencerClient {
|
|||||||
Ok(resp_deser)
|
Ok(resp_deser)
|
||||||
}
|
}
|
||||||
|
|
||||||
///Get last known `blokc_id` from sequencer
|
/// Get last known `blokc_id` from sequencer
|
||||||
pub async fn get_last_block(&self) -> Result<GetLastBlockResponse, SequencerClientError> {
|
pub async fn get_last_block(&self) -> Result<GetLastBlockResponse, SequencerClientError> {
|
||||||
let block_req = GetLastBlockRequest {};
|
let block_req = GetLastBlockRequest {};
|
||||||
|
|
||||||
@ -91,7 +93,8 @@ impl SequencerClient {
|
|||||||
Ok(resp_deser)
|
Ok(resp_deser)
|
||||||
}
|
}
|
||||||
|
|
||||||
///Get account public balance for `account_id`. `account_id` must be a valid hex-string for 32 bytes.
|
/// Get account public balance for `account_id`. `account_id` must be a valid hex-string for 32
|
||||||
|
/// bytes.
|
||||||
pub async fn get_account_balance(
|
pub async fn get_account_balance(
|
||||||
&self,
|
&self,
|
||||||
account_id: String,
|
account_id: String,
|
||||||
@ -109,7 +112,8 @@ impl SequencerClient {
|
|||||||
Ok(resp_deser)
|
Ok(resp_deser)
|
||||||
}
|
}
|
||||||
|
|
||||||
///Get accounts nonces for `account_ids`. `account_ids` must be a list of valid hex-strings for 32 bytes.
|
/// Get accounts nonces for `account_ids`. `account_ids` must be a list of valid hex-strings for
|
||||||
|
/// 32 bytes.
|
||||||
pub async fn get_accounts_nonces(
|
pub async fn get_accounts_nonces(
|
||||||
&self,
|
&self,
|
||||||
account_ids: Vec<String>,
|
account_ids: Vec<String>,
|
||||||
@ -142,7 +146,7 @@ impl SequencerClient {
|
|||||||
Ok(resp_deser)
|
Ok(resp_deser)
|
||||||
}
|
}
|
||||||
|
|
||||||
///Get transaction details for `hash`.
|
/// Get transaction details for `hash`.
|
||||||
pub async fn get_transaction_by_hash(
|
pub async fn get_transaction_by_hash(
|
||||||
&self,
|
&self,
|
||||||
hash: String,
|
hash: String,
|
||||||
@ -160,7 +164,7 @@ impl SequencerClient {
|
|||||||
Ok(resp_deser)
|
Ok(resp_deser)
|
||||||
}
|
}
|
||||||
|
|
||||||
///Send transaction to sequencer
|
/// Send transaction to sequencer
|
||||||
pub async fn send_tx_public(
|
pub async fn send_tx_public(
|
||||||
&self,
|
&self,
|
||||||
transaction: nssa::PublicTransaction,
|
transaction: nssa::PublicTransaction,
|
||||||
@ -180,7 +184,7 @@ impl SequencerClient {
|
|||||||
Ok(resp_deser)
|
Ok(resp_deser)
|
||||||
}
|
}
|
||||||
|
|
||||||
///Send transaction to sequencer
|
/// Send transaction to sequencer
|
||||||
pub async fn send_tx_private(
|
pub async fn send_tx_private(
|
||||||
&self,
|
&self,
|
||||||
transaction: nssa::PrivacyPreservingTransaction,
|
transaction: nssa::PrivacyPreservingTransaction,
|
||||||
@ -200,7 +204,7 @@ impl SequencerClient {
|
|||||||
Ok(resp_deser)
|
Ok(resp_deser)
|
||||||
}
|
}
|
||||||
|
|
||||||
///Get genesis id from sequencer
|
/// Get genesis id from sequencer
|
||||||
pub async fn get_genesis_id(&self) -> Result<GetGenesisIdResponse, SequencerClientError> {
|
pub async fn get_genesis_id(&self) -> Result<GetGenesisIdResponse, SequencerClientError> {
|
||||||
let genesis_req = GetGenesisIdRequest {};
|
let genesis_req = GetGenesisIdRequest {};
|
||||||
|
|
||||||
@ -216,7 +220,7 @@ impl SequencerClient {
|
|||||||
Ok(resp_deser)
|
Ok(resp_deser)
|
||||||
}
|
}
|
||||||
|
|
||||||
///Get initial testnet accounts from sequencer
|
/// Get initial testnet accounts from sequencer
|
||||||
pub async fn get_initial_testnet_accounts(
|
pub async fn get_initial_testnet_accounts(
|
||||||
&self,
|
&self,
|
||||||
) -> Result<Vec<AccountInitialData>, SequencerClientError> {
|
) -> Result<Vec<AccountInitialData>, SequencerClientError> {
|
||||||
@ -234,7 +238,7 @@ impl SequencerClient {
|
|||||||
Ok(resp_deser)
|
Ok(resp_deser)
|
||||||
}
|
}
|
||||||
|
|
||||||
///Get proof for commitment
|
/// Get proof for commitment
|
||||||
pub async fn get_proof_for_commitment(
|
pub async fn get_proof_for_commitment(
|
||||||
&self,
|
&self,
|
||||||
commitment: nssa_core::Commitment,
|
commitment: nssa_core::Commitment,
|
||||||
|
|||||||
@ -3,15 +3,15 @@ use crate::{
|
|||||||
transaction::{EncodedTransaction, NSSATransaction},
|
transaction::{EncodedTransaction, NSSATransaction},
|
||||||
};
|
};
|
||||||
|
|
||||||
//Helpers
|
// Helpers
|
||||||
|
|
||||||
pub fn sequencer_sign_key_for_testing() -> nssa::PrivateKey {
|
pub fn sequencer_sign_key_for_testing() -> nssa::PrivateKey {
|
||||||
nssa::PrivateKey::try_new([37; 32]).unwrap()
|
nssa::PrivateKey::try_new([37; 32]).unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
//Dummy producers
|
// Dummy producers
|
||||||
|
|
||||||
///Produce dummy block with
|
/// Produce dummy block with
|
||||||
///
|
///
|
||||||
/// `id` - block id, provide zero for genesis
|
/// `id` - block id, provide zero for genesis
|
||||||
///
|
///
|
||||||
|
|||||||
@ -1,7 +1,6 @@
|
|||||||
use borsh::{BorshDeserialize, BorshSerialize};
|
use borsh::{BorshDeserialize, BorshSerialize};
|
||||||
use log::info;
|
use log::info;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use sha2::{Digest, digest::FixedOutput};
|
use sha2::{Digest, digest::FixedOutput};
|
||||||
|
|
||||||
pub type HashType = [u8; 32];
|
pub type HashType = [u8; 32];
|
||||||
@ -41,10 +40,10 @@ pub enum TxKind {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
|
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
|
||||||
///General transaction object
|
/// General transaction object
|
||||||
pub struct EncodedTransaction {
|
pub struct EncodedTransaction {
|
||||||
pub tx_kind: TxKind,
|
pub tx_kind: TxKind,
|
||||||
///Encoded blobs of data
|
/// Encoded blobs of data
|
||||||
pub encoded_transaction_data: Vec<u8>,
|
pub encoded_transaction_data: Vec<u8>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -1,8 +1,8 @@
|
|||||||
use base64::{Engine, engine::general_purpose::STANDARD as BASE64};
|
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
use actix_web::dev::ServerHandle;
|
use actix_web::dev::ServerHandle;
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
|
use base64::{Engine, engine::general_purpose::STANDARD as BASE64};
|
||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
use common::{
|
use common::{
|
||||||
sequencer_client::SequencerClient,
|
sequencer_client::SequencerClient,
|
||||||
@ -96,13 +96,13 @@ pub async fn post_test(residual: (ServerHandle, JoinHandle<Result<()>>, TempDir)
|
|||||||
let wallet_home = wallet::helperfunctions::get_home().unwrap();
|
let wallet_home = wallet::helperfunctions::get_home().unwrap();
|
||||||
let persistent_data_home = wallet_home.join("storage.json");
|
let persistent_data_home = wallet_home.join("storage.json");
|
||||||
|
|
||||||
//Removing persistent accounts after run to not affect other executions
|
// Removing persistent accounts after run to not affect other executions
|
||||||
//Not necessary an error, if fails as there is tests for failure scenario
|
// Not necessary an error, if fails as there is tests for failure scenario
|
||||||
let _ = std::fs::remove_file(persistent_data_home)
|
let _ = std::fs::remove_file(persistent_data_home)
|
||||||
.inspect_err(|err| warn!("Failed to remove persistent data with err {err:#?}"));
|
.inspect_err(|err| warn!("Failed to remove persistent data with err {err:#?}"));
|
||||||
|
|
||||||
//At this point all of the references to sequencer_core must be lost.
|
// At this point all of the references to sequencer_core must be lost.
|
||||||
//So they are dropped and tempdirs will be dropped too,
|
// So they are dropped and tempdirs will be dropped too,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn main_tests_runner() -> Result<()> {
|
pub async fn main_tests_runner() -> Result<()> {
|
||||||
|
|||||||
@ -1,5 +1,4 @@
|
|||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
|
|
||||||
use integration_tests::main_tests_runner;
|
use integration_tests::main_tests_runner;
|
||||||
|
|
||||||
pub const NUM_THREADS: usize = 8;
|
pub const NUM_THREADS: usize = 8;
|
||||||
|
|||||||
@ -1,4 +1,3 @@
|
|||||||
use anyhow::Result;
|
|
||||||
use std::{
|
use std::{
|
||||||
collections::HashMap,
|
collections::HashMap,
|
||||||
path::PathBuf,
|
path::PathBuf,
|
||||||
@ -7,6 +6,7 @@ use std::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
use actix_web::dev::ServerHandle;
|
use actix_web::dev::ServerHandle;
|
||||||
|
use anyhow::Result;
|
||||||
use common::{PINATA_BASE58, sequencer_client::SequencerClient};
|
use common::{PINATA_BASE58, sequencer_client::SequencerClient};
|
||||||
use log::info;
|
use log::info;
|
||||||
use nssa::{AccountId, ProgramDeploymentTransaction, program::Program};
|
use nssa::{AccountId, ProgramDeploymentTransaction, program::Program};
|
||||||
@ -31,10 +31,10 @@ use crate::{
|
|||||||
ACC_RECEIVER, ACC_RECEIVER_PRIVATE, ACC_SENDER, ACC_SENDER_PRIVATE,
|
ACC_RECEIVER, ACC_RECEIVER_PRIVATE, ACC_SENDER, ACC_SENDER_PRIVATE,
|
||||||
NSSA_PROGRAM_FOR_TEST_DATA_CHANGER, TIME_TO_WAIT_FOR_BLOCK_SECONDS,
|
NSSA_PROGRAM_FOR_TEST_DATA_CHANGER, TIME_TO_WAIT_FOR_BLOCK_SECONDS,
|
||||||
fetch_privacy_preserving_tx, make_private_account_input_from_str,
|
fetch_privacy_preserving_tx, make_private_account_input_from_str,
|
||||||
make_public_account_input_from_str, replace_home_dir_with_temp_dir_in_configs,
|
make_public_account_input_from_str, post_test, pre_test,
|
||||||
tps_test_utils::TpsTestManager,
|
replace_home_dir_with_temp_dir_in_configs, tps_test_utils::TpsTestManager,
|
||||||
|
verify_commitment_is_in_state,
|
||||||
};
|
};
|
||||||
use crate::{post_test, pre_test, verify_commitment_is_in_state};
|
|
||||||
|
|
||||||
type TestFunction = fn(PathBuf) -> Pin<Box<dyn Future<Output = ()>>>;
|
type TestFunction = fn(PathBuf) -> Pin<Box<dyn Future<Output = ()>>>;
|
||||||
|
|
||||||
@ -276,8 +276,8 @@ pub fn prepare_function_map() -> HashMap<String, TestFunction> {
|
|||||||
assert_eq!(account.nonce, 0);
|
assert_eq!(account.nonce, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// This test creates a new token using the token program. After creating the token, the test executes a
|
/// This test creates a new token using the token program. After creating the token, the test
|
||||||
/// token transfer to a new account.
|
/// executes a token transfer to a new account.
|
||||||
#[nssa_integration_test]
|
#[nssa_integration_test]
|
||||||
pub async fn test_success_token_program() {
|
pub async fn test_success_token_program() {
|
||||||
info!("########## test_success_token_program ##########");
|
info!("########## test_success_token_program ##########");
|
||||||
@ -364,7 +364,8 @@ pub fn prepare_function_map() -> HashMap<String, TestFunction> {
|
|||||||
]
|
]
|
||||||
);
|
);
|
||||||
|
|
||||||
// Check the status of the token holding account with the total supply is the expected after the execution
|
// Check the status of the token holding account with the total supply is the expected after
|
||||||
|
// the execution
|
||||||
let supply_acc = seq_client
|
let supply_acc = seq_client
|
||||||
.get_account(supply_account_id.to_string())
|
.get_account(supply_account_id.to_string())
|
||||||
.await
|
.await
|
||||||
@ -374,8 +375,8 @@ pub fn prepare_function_map() -> HashMap<String, TestFunction> {
|
|||||||
// The account must be owned by the token program
|
// The account must be owned by the token program
|
||||||
assert_eq!(supply_acc.program_owner, Program::token().id());
|
assert_eq!(supply_acc.program_owner, Program::token().id());
|
||||||
// The data of a token definition account has the following layout:
|
// The data of a token definition account has the following layout:
|
||||||
// [ 0x01 || corresponding_token_definition_id (32 bytes) || balance (little endian 16 bytes) ]
|
// [ 0x01 || corresponding_token_definition_id (32 bytes) || balance (little endian 16
|
||||||
// First byte of the data equal to 1 means it's a token holding account
|
// bytes) ] First byte of the data equal to 1 means it's a token holding account
|
||||||
assert_eq!(supply_acc.data[0], 1);
|
assert_eq!(supply_acc.data[0], 1);
|
||||||
// Bytes from 1 to 33 represent the id of the token this account is associated with.
|
// Bytes from 1 to 33 represent the id of the token this account is associated with.
|
||||||
// In this example, this is a token account of the newly created token, so it is expected
|
// In this example, this is a token account of the newly created token, so it is expected
|
||||||
@ -403,7 +404,8 @@ pub fn prepare_function_map() -> HashMap<String, TestFunction> {
|
|||||||
info!("Waiting for next block creation");
|
info!("Waiting for next block creation");
|
||||||
tokio::time::sleep(Duration::from_secs(TIME_TO_WAIT_FOR_BLOCK_SECONDS)).await;
|
tokio::time::sleep(Duration::from_secs(TIME_TO_WAIT_FOR_BLOCK_SECONDS)).await;
|
||||||
|
|
||||||
// Check the status of the account at `supply_account_id` is the expected after the execution
|
// Check the status of the account at `supply_account_id` is the expected after the
|
||||||
|
// execution
|
||||||
let supply_acc = seq_client
|
let supply_acc = seq_client
|
||||||
.get_account(supply_account_id.to_string())
|
.get_account(supply_account_id.to_string())
|
||||||
.await
|
.await
|
||||||
@ -420,7 +422,8 @@ pub fn prepare_function_map() -> HashMap<String, TestFunction> {
|
|||||||
30
|
30
|
||||||
);
|
);
|
||||||
|
|
||||||
// Check the status of the account at `recipient_account_id` is the expected after the execution
|
// Check the status of the account at `recipient_account_id` is the expected after the
|
||||||
|
// execution
|
||||||
let recipient_acc = seq_client
|
let recipient_acc = seq_client
|
||||||
.get_account(recipient_account_id.to_string())
|
.get_account(recipient_account_id.to_string())
|
||||||
.await
|
.await
|
||||||
@ -439,8 +442,9 @@ pub fn prepare_function_map() -> HashMap<String, TestFunction> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// This test creates a new private token using the token program. After creating the token, the test executes a
|
/// This test creates a new private token using the token program. After creating the token, the
|
||||||
/// private token transfer to a new account. All accounts are owned except definition.
|
/// test executes a private token transfer to a new account. All accounts are owned except
|
||||||
|
/// definition.
|
||||||
#[nssa_integration_test]
|
#[nssa_integration_test]
|
||||||
pub async fn test_success_token_program_private_owned() {
|
pub async fn test_success_token_program_private_owned() {
|
||||||
info!("########## test_success_token_program_private_owned ##########");
|
info!("########## test_success_token_program_private_owned ##########");
|
||||||
@ -559,7 +563,8 @@ pub fn prepare_function_map() -> HashMap<String, TestFunction> {
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
assert!(verify_commitment_is_in_state(new_commitment2, &seq_client).await);
|
assert!(verify_commitment_is_in_state(new_commitment2, &seq_client).await);
|
||||||
|
|
||||||
// Transfer additional 7 tokens from `supply_acc` to the account at account_id `recipient_account_id`
|
// Transfer additional 7 tokens from `supply_acc` to the account at account_id
|
||||||
|
// `recipient_account_id`
|
||||||
let subcommand = TokenProgramAgnosticSubcommand::Send {
|
let subcommand = TokenProgramAgnosticSubcommand::Send {
|
||||||
from: make_private_account_input_from_str(&supply_account_id.to_string()),
|
from: make_private_account_input_from_str(&supply_account_id.to_string()),
|
||||||
to: Some(make_private_account_input_from_str(
|
to: Some(make_private_account_input_from_str(
|
||||||
@ -593,8 +598,8 @@ pub fn prepare_function_map() -> HashMap<String, TestFunction> {
|
|||||||
assert!(verify_commitment_is_in_state(new_commitment2, &seq_client).await);
|
assert!(verify_commitment_is_in_state(new_commitment2, &seq_client).await);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// This test creates a new private token using the token program. After creating the token, the test executes a
|
/// This test creates a new private token using the token program. After creating the token, the
|
||||||
/// private token transfer to a new account.
|
/// test executes a private token transfer to a new account.
|
||||||
#[nssa_integration_test]
|
#[nssa_integration_test]
|
||||||
pub async fn test_success_token_program_private_claiming_path() {
|
pub async fn test_success_token_program_private_claiming_path() {
|
||||||
info!("########## test_success_token_program_private_claiming_path ##########");
|
info!("########## test_success_token_program_private_claiming_path ##########");
|
||||||
@ -728,8 +733,9 @@ pub fn prepare_function_map() -> HashMap<String, TestFunction> {
|
|||||||
assert!(verify_commitment_is_in_state(new_commitment2, &seq_client).await);
|
assert!(verify_commitment_is_in_state(new_commitment2, &seq_client).await);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// This test creates a new public token using the token program. After creating the token, the test executes a
|
/// This test creates a new public token using the token program. After creating the token, the
|
||||||
/// shielded token transfer to a new account. All accounts are owned except definition.
|
/// test executes a shielded token transfer to a new account. All accounts are owned except
|
||||||
|
/// definition.
|
||||||
#[nssa_integration_test]
|
#[nssa_integration_test]
|
||||||
pub async fn test_success_token_program_shielded_owned() {
|
pub async fn test_success_token_program_shielded_owned() {
|
||||||
info!("########## test_success_token_program_shielded_owned ##########");
|
info!("########## test_success_token_program_shielded_owned ##########");
|
||||||
@ -833,7 +839,8 @@ pub fn prepare_function_map() -> HashMap<String, TestFunction> {
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
assert!(verify_commitment_is_in_state(new_commitment2, &seq_client).await);
|
assert!(verify_commitment_is_in_state(new_commitment2, &seq_client).await);
|
||||||
|
|
||||||
// Transfer additional 7 tokens from `supply_acc` to the account at account_id `recipient_account_id`
|
// Transfer additional 7 tokens from `supply_acc` to the account at account_id
|
||||||
|
// `recipient_account_id`
|
||||||
let subcommand = TokenProgramAgnosticSubcommand::Send {
|
let subcommand = TokenProgramAgnosticSubcommand::Send {
|
||||||
from: make_public_account_input_from_str(&supply_account_id.to_string()),
|
from: make_public_account_input_from_str(&supply_account_id.to_string()),
|
||||||
to: Some(make_private_account_input_from_str(
|
to: Some(make_private_account_input_from_str(
|
||||||
@ -862,8 +869,9 @@ pub fn prepare_function_map() -> HashMap<String, TestFunction> {
|
|||||||
assert!(verify_commitment_is_in_state(new_commitment2, &seq_client).await);
|
assert!(verify_commitment_is_in_state(new_commitment2, &seq_client).await);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// This test creates a new private token using the token program. After creating the token, the test executes a
|
/// This test creates a new private token using the token program. After creating the token, the
|
||||||
/// deshielded token transfer to a new account. All accounts are owned except definition.
|
/// test executes a deshielded token transfer to a new account. All accounts are owned
|
||||||
|
/// except definition.
|
||||||
#[nssa_integration_test]
|
#[nssa_integration_test]
|
||||||
pub async fn test_success_token_program_deshielded_owned() {
|
pub async fn test_success_token_program_deshielded_owned() {
|
||||||
info!("########## test_success_token_program_deshielded_owned ##########");
|
info!("########## test_success_token_program_deshielded_owned ##########");
|
||||||
@ -977,7 +985,8 @@ pub fn prepare_function_map() -> HashMap<String, TestFunction> {
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
assert!(verify_commitment_is_in_state(new_commitment1, &seq_client).await);
|
assert!(verify_commitment_is_in_state(new_commitment1, &seq_client).await);
|
||||||
|
|
||||||
// Transfer additional 7 tokens from `supply_acc` to the account at account_id `recipient_account_id`
|
// Transfer additional 7 tokens from `supply_acc` to the account at account_id
|
||||||
|
// `recipient_account_id`
|
||||||
let subcommand = TokenProgramAgnosticSubcommand::Send {
|
let subcommand = TokenProgramAgnosticSubcommand::Send {
|
||||||
from: make_private_account_input_from_str(&supply_account_id.to_string()),
|
from: make_private_account_input_from_str(&supply_account_id.to_string()),
|
||||||
to: Some(make_public_account_input_from_str(
|
to: Some(make_public_account_input_from_str(
|
||||||
@ -1425,7 +1434,8 @@ pub fn prepare_function_map() -> HashMap<String, TestFunction> {
|
|||||||
|
|
||||||
// The program is the data changer and takes one account as input.
|
// The program is the data changer and takes one account as input.
|
||||||
// We pass an uninitialized account and we expect after execution to be owned by the data
|
// We pass an uninitialized account and we expect after execution to be owned by the data
|
||||||
// changer program (NSSA account claiming mechanism) with data equal to [0] (due to program logic)
|
// changer program (NSSA account claiming mechanism) with data equal to [0] (due to program
|
||||||
|
// logic)
|
||||||
let data_changer = Program::new(bytecode).unwrap();
|
let data_changer = Program::new(bytecode).unwrap();
|
||||||
let account_id: AccountId = "11".repeat(16).parse().unwrap();
|
let account_id: AccountId = "11".repeat(16).parse().unwrap();
|
||||||
let message = nssa::public_transaction::Message::try_new(
|
let message = nssa::public_transaction::Message::try_new(
|
||||||
@ -1617,7 +1627,7 @@ pub fn prepare_function_map() -> HashMap<String, TestFunction> {
|
|||||||
let wallet_config = fetch_config().await.unwrap();
|
let wallet_config = fetch_config().await.unwrap();
|
||||||
let old_seq_poll_retry_delay_millis = wallet_config.seq_poll_retry_delay_millis;
|
let old_seq_poll_retry_delay_millis = wallet_config.seq_poll_retry_delay_millis;
|
||||||
|
|
||||||
//Change config field
|
// Change config field
|
||||||
let command = Command::Config(ConfigSubcommand::Set {
|
let command = Command::Config(ConfigSubcommand::Set {
|
||||||
key: "seq_poll_retry_delay_millis".to_string(),
|
key: "seq_poll_retry_delay_millis".to_string(),
|
||||||
value: "1000".to_string(),
|
value: "1000".to_string(),
|
||||||
@ -1628,7 +1638,7 @@ pub fn prepare_function_map() -> HashMap<String, TestFunction> {
|
|||||||
|
|
||||||
assert_eq!(wallet_config.seq_poll_retry_delay_millis, 1000);
|
assert_eq!(wallet_config.seq_poll_retry_delay_millis, 1000);
|
||||||
|
|
||||||
//Return how it was at the beginning
|
// Return how it was at the beginning
|
||||||
let command = Command::Config(ConfigSubcommand::Set {
|
let command = Command::Config(ConfigSubcommand::Set {
|
||||||
key: "seq_poll_retry_delay_millis".to_string(),
|
key: "seq_poll_retry_delay_millis".to_string(),
|
||||||
value: old_seq_poll_retry_delay_millis.to_string(),
|
value: old_seq_poll_retry_delay_millis.to_string(),
|
||||||
|
|||||||
@ -19,8 +19,8 @@ pub(crate) struct TpsTestManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl TpsTestManager {
|
impl TpsTestManager {
|
||||||
/// Generates public account keypairs. These are used to populate the config and to generate valid
|
/// Generates public account keypairs. These are used to populate the config and to generate
|
||||||
/// public transactions for the tps test.
|
/// valid public transactions for the tps test.
|
||||||
pub(crate) fn new(target_tps: u64, number_transactions: usize) -> Self {
|
pub(crate) fn new(target_tps: u64, number_transactions: usize) -> Self {
|
||||||
let public_keypairs = (1..(number_transactions + 2))
|
let public_keypairs = (1..(number_transactions + 2))
|
||||||
.map(|i| {
|
.map(|i| {
|
||||||
@ -43,7 +43,6 @@ impl TpsTestManager {
|
|||||||
Duration::from_secs_f64(number_transactions as f64 / self.target_tps as f64)
|
Duration::from_secs_f64(number_transactions as f64 / self.target_tps as f64)
|
||||||
}
|
}
|
||||||
|
|
||||||
///
|
|
||||||
/// Build a batch of public transactions to submit to the node.
|
/// Build a batch of public transactions to submit to the node.
|
||||||
pub fn build_public_txs(&self) -> Vec<PublicTransaction> {
|
pub fn build_public_txs(&self) -> Vec<PublicTransaction> {
|
||||||
// Create valid public transactions
|
// Create valid public transactions
|
||||||
@ -70,8 +69,8 @@ impl TpsTestManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Generates a sequencer configuration with initial balance in a number of public accounts.
|
/// Generates a sequencer configuration with initial balance in a number of public accounts.
|
||||||
/// The transactions generated with the function `build_public_txs` will be valid in a node started
|
/// The transactions generated with the function `build_public_txs` will be valid in a node
|
||||||
/// with the config from this method.
|
/// started with the config from this method.
|
||||||
pub(crate) fn generate_tps_test_config(&self) -> SequencerConfig {
|
pub(crate) fn generate_tps_test_config(&self) -> SequencerConfig {
|
||||||
// Create public public keypairs
|
// Create public public keypairs
|
||||||
let initial_public_accounts = self
|
let initial_public_accounts = self
|
||||||
|
|||||||
@ -6,7 +6,8 @@ use rand::{RngCore, rngs::OsRng};
|
|||||||
use sha2::Digest;
|
use sha2::Digest;
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
///Ephemeral secret key holder. Non-clonable as intended for one-time use. Produces ephemeral public keys. Can produce shared secret for sender.
|
/// Ephemeral secret key holder. Non-clonable as intended for one-time use. Produces ephemeral
|
||||||
|
/// public keys. Can produce shared secret for sender.
|
||||||
pub struct EphemeralKeyHolder {
|
pub struct EphemeralKeyHolder {
|
||||||
ephemeral_secret_key: EphemeralSecretKey,
|
ephemeral_secret_key: EphemeralSecretKey,
|
||||||
}
|
}
|
||||||
|
|||||||
@ -11,7 +11,7 @@ pub mod ephemeral_key_holder;
|
|||||||
pub mod secret_holders;
|
pub mod secret_holders;
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||||
///Entrypoint to key management
|
/// Entrypoint to key management
|
||||||
pub struct KeyChain {
|
pub struct KeyChain {
|
||||||
secret_spending_key: SecretSpendingKey,
|
secret_spending_key: SecretSpendingKey,
|
||||||
pub private_key_holder: PrivateKeyHolder,
|
pub private_key_holder: PrivateKeyHolder,
|
||||||
@ -21,8 +21,8 @@ pub struct KeyChain {
|
|||||||
|
|
||||||
impl KeyChain {
|
impl KeyChain {
|
||||||
pub fn new_os_random() -> Self {
|
pub fn new_os_random() -> Self {
|
||||||
//Currently dropping SeedHolder at the end of initialization.
|
// Currently dropping SeedHolder at the end of initialization.
|
||||||
//Now entirely sure if we need it in the future.
|
// Now entirely sure if we need it in the future.
|
||||||
let seed_holder = SeedHolder::new_os_random();
|
let seed_holder = SeedHolder::new_os_random();
|
||||||
let secret_spending_key = seed_holder.produce_top_secret_key_holder();
|
let secret_spending_key = seed_holder.produce_top_secret_key_holder();
|
||||||
|
|
||||||
@ -56,8 +56,7 @@ impl KeyChain {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use aes_gcm::aead::OsRng;
|
use aes_gcm::aead::OsRng;
|
||||||
use base58::ToBase58;
|
use base58::ToBase58;
|
||||||
use k256::AffinePoint;
|
use k256::{AffinePoint, elliptic_curve::group::GroupEncoding};
|
||||||
use k256::elliptic_curve::group::GroupEncoding;
|
|
||||||
use rand::RngCore;
|
use rand::RngCore;
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|||||||
@ -9,22 +9,23 @@ use serde::{Deserialize, Serialize};
|
|||||||
use sha2::{Digest, digest::FixedOutput};
|
use sha2::{Digest, digest::FixedOutput};
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
///Seed holder. Non-clonable to ensure that different holders use different seeds.
|
/// Seed holder. Non-clonable to ensure that different holders use different seeds.
|
||||||
/// Produces `TopSecretKeyHolder` objects.
|
/// Produces `TopSecretKeyHolder` objects.
|
||||||
pub struct SeedHolder {
|
pub struct SeedHolder {
|
||||||
//ToDo: Needs to be vec as serde derives is not implemented for [u8; 64]
|
// ToDo: Needs to be vec as serde derives is not implemented for [u8; 64]
|
||||||
pub(crate) seed: Vec<u8>,
|
pub(crate) seed: Vec<u8>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||||
///Secret spending key object. Can produce `PrivateKeyHolder` objects.
|
/// Secret spending key object. Can produce `PrivateKeyHolder` objects.
|
||||||
pub struct SecretSpendingKey(pub(crate) [u8; 32]);
|
pub struct SecretSpendingKey(pub(crate) [u8; 32]);
|
||||||
|
|
||||||
pub type IncomingViewingSecretKey = Scalar;
|
pub type IncomingViewingSecretKey = Scalar;
|
||||||
pub type OutgoingViewingSecretKey = Scalar;
|
pub type OutgoingViewingSecretKey = Scalar;
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||||
///Private key holder. Produces public keys. Can produce account_id. Can produce shared secret for recepient.
|
/// Private key holder. Produces public keys. Can produce account_id. Can produce shared secret for
|
||||||
|
/// recepient.
|
||||||
pub struct PrivateKeyHolder {
|
pub struct PrivateKeyHolder {
|
||||||
pub nullifier_secret_key: NullifierSecretKey,
|
pub nullifier_secret_key: NullifierSecretKey,
|
||||||
pub(crate) incoming_viewing_secret_key: IncomingViewingSecretKey,
|
pub(crate) incoming_viewing_secret_key: IncomingViewingSecretKey,
|
||||||
@ -51,7 +52,7 @@ impl SeedHolder {
|
|||||||
hash = hmac_sha512::HMAC::mac(hash, "NSSA_seed");
|
hash = hmac_sha512::HMAC::mac(hash, "NSSA_seed");
|
||||||
}
|
}
|
||||||
|
|
||||||
//Safe unwrap
|
// Safe unwrap
|
||||||
*hash.first_chunk::<32>().unwrap()
|
*hash.first_chunk::<32>().unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -10,9 +10,9 @@ pub type PublicKey = AffinePoint;
|
|||||||
|
|
||||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||||
pub struct NSSAUserData {
|
pub struct NSSAUserData {
|
||||||
///Map for all user public accounts
|
/// Map for all user public accounts
|
||||||
pub pub_account_signing_keys: HashMap<nssa::AccountId, nssa::PrivateKey>,
|
pub pub_account_signing_keys: HashMap<nssa::AccountId, nssa::PrivateKey>,
|
||||||
///Map for all user private accounts
|
/// Map for all user private accounts
|
||||||
pub user_private_accounts: HashMap<nssa::AccountId, (KeyChain, nssa_core::account::Account)>,
|
pub user_private_accounts: HashMap<nssa::AccountId, (KeyChain, nssa_core::account::Account)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -124,7 +124,7 @@ impl NSSAUserData {
|
|||||||
|
|
||||||
impl Default for NSSAUserData {
|
impl Default for NSSAUserData {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
//Safe unwrap as maps are empty
|
// Safe unwrap as maps are empty
|
||||||
Self::new_with_accounts(HashMap::default(), HashMap::default()).unwrap()
|
Self::new_with_accounts(HashMap::default(), HashMap::default()).unwrap()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -43,10 +43,10 @@ impl<T> MemPoolHandle<T> {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
|
||||||
|
|
||||||
use tokio::test;
|
use tokio::test;
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
async fn test_mempool_new() {
|
async fn test_mempool_new() {
|
||||||
let (mut pool, _handle): (MemPool<u64>, _) = MemPool::new(10);
|
let (mut pool, _handle): (MemPool<u64>, _) = MemPool::new(10);
|
||||||
|
|||||||
@ -1,11 +1,11 @@
|
|||||||
use crate::program::ProgramId;
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
#[cfg(feature = "host")]
|
#[cfg(feature = "host")]
|
||||||
use std::{fmt::Display, str::FromStr};
|
use std::{fmt::Display, str::FromStr};
|
||||||
|
|
||||||
#[cfg(feature = "host")]
|
#[cfg(feature = "host")]
|
||||||
use base58::{FromBase58, ToBase58};
|
use base58::{FromBase58, ToBase58};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use crate::program::ProgramId;
|
||||||
|
|
||||||
pub type Nonce = u128;
|
pub type Nonce = u128;
|
||||||
pub type Data = Vec<u8>;
|
pub type Data = Vec<u8>;
|
||||||
@ -99,9 +99,8 @@ impl Display for AccountId {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use crate::program::DEFAULT_PROGRAM_ID;
|
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use crate::program::DEFAULT_PROGRAM_ID;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_zero_balance_account_data_creation() {
|
fn test_zero_balance_account_data_creation() {
|
||||||
|
|||||||
@ -38,12 +38,13 @@ impl PrivacyPreservingCircuitOutput {
|
|||||||
#[cfg(feature = "host")]
|
#[cfg(feature = "host")]
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
|
use risc0_zkvm::serde::from_slice;
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::{
|
use crate::{
|
||||||
Commitment, Nullifier, NullifierPublicKey,
|
Commitment, Nullifier, NullifierPublicKey,
|
||||||
account::{Account, AccountId, AccountWithMetadata},
|
account::{Account, AccountId, AccountWithMetadata},
|
||||||
};
|
};
|
||||||
use risc0_zkvm::serde::from_slice;
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_privacy_preserving_circuit_output_to_bytes_is_compatible_with_from_slice() {
|
fn test_privacy_preserving_circuit_output_to_bytes_is_compatible_with_from_slice() {
|
||||||
|
|||||||
@ -1,25 +1,20 @@
|
|||||||
// TODO: Consider switching to deriving Borsh
|
// TODO: Consider switching to deriving Borsh
|
||||||
#[cfg(feature = "host")]
|
#[cfg(feature = "host")]
|
||||||
use std::io::Cursor;
|
use std::io::Cursor;
|
||||||
|
|
||||||
#[cfg(feature = "host")]
|
#[cfg(feature = "host")]
|
||||||
use std::io::Read;
|
use std::io::Read;
|
||||||
|
|
||||||
use crate::account::Account;
|
|
||||||
|
|
||||||
use crate::account::AccountId;
|
|
||||||
#[cfg(feature = "host")]
|
|
||||||
use crate::encryption::shared_key_derivation::Secp256k1Point;
|
|
||||||
|
|
||||||
use crate::encryption::Ciphertext;
|
|
||||||
|
|
||||||
#[cfg(feature = "host")]
|
|
||||||
use crate::error::NssaCoreError;
|
|
||||||
|
|
||||||
use crate::Commitment;
|
|
||||||
#[cfg(feature = "host")]
|
#[cfg(feature = "host")]
|
||||||
use crate::Nullifier;
|
use crate::Nullifier;
|
||||||
use crate::NullifierPublicKey;
|
#[cfg(feature = "host")]
|
||||||
|
use crate::encryption::shared_key_derivation::Secp256k1Point;
|
||||||
|
#[cfg(feature = "host")]
|
||||||
|
use crate::error::NssaCoreError;
|
||||||
|
use crate::{
|
||||||
|
Commitment, NullifierPublicKey,
|
||||||
|
account::{Account, AccountId},
|
||||||
|
encryption::Ciphertext,
|
||||||
|
};
|
||||||
|
|
||||||
impl Account {
|
impl Account {
|
||||||
pub fn to_bytes(&self) -> Vec<u8> {
|
pub fn to_bytes(&self) -> Vec<u8> {
|
||||||
@ -55,7 +50,7 @@ impl Account {
|
|||||||
cursor.read_exact(&mut u128_bytes)?;
|
cursor.read_exact(&mut u128_bytes)?;
|
||||||
let nonce = u128::from_le_bytes(u128_bytes);
|
let nonce = u128::from_le_bytes(u128_bytes);
|
||||||
|
|
||||||
//data
|
// data
|
||||||
cursor.read_exact(&mut u32_bytes)?;
|
cursor.read_exact(&mut u32_bytes)?;
|
||||||
let data_length = u32::from_le_bytes(u32_bytes);
|
let data_length = u32::from_le_bytes(u32_bytes);
|
||||||
let mut data = vec![0; data_length as usize];
|
let mut data = vec![0; data_length as usize];
|
||||||
|
|||||||
@ -1,5 +1,3 @@
|
|||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
use k256::{
|
use k256::{
|
||||||
AffinePoint, EncodedPoint, FieldBytes, ProjectivePoint,
|
AffinePoint, EncodedPoint, FieldBytes, ProjectivePoint,
|
||||||
elliptic_curve::{
|
elliptic_curve::{
|
||||||
@ -7,6 +5,7 @@ use k256::{
|
|||||||
sec1::{FromEncodedPoint, ToEncodedPoint},
|
sec1::{FromEncodedPoint, ToEncodedPoint},
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use crate::{SharedSecretKey, encryption::Scalar};
|
use crate::{SharedSecretKey, encryption::Scalar};
|
||||||
|
|
||||||
|
|||||||
@ -1,8 +1,8 @@
|
|||||||
use crate::account::{Account, AccountWithMetadata};
|
use risc0_zkvm::{DeserializeOwned, guest::env, serde::Deserializer};
|
||||||
use risc0_zkvm::serde::Deserializer;
|
|
||||||
use risc0_zkvm::{DeserializeOwned, guest::env};
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use crate::account::{Account, AccountWithMetadata};
|
||||||
|
|
||||||
pub type ProgramId = [u32; 8];
|
pub type ProgramId = [u32; 8];
|
||||||
pub type InstructionData = Vec<u32>;
|
pub type InstructionData = Vec<u32>;
|
||||||
pub const DEFAULT_PROGRAM_ID: ProgramId = [0; 8];
|
pub const DEFAULT_PROGRAM_ID: ProgramId = [0; 8];
|
||||||
@ -103,7 +103,8 @@ pub fn validate_execution(
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 6. If a post state has default program owner, the pre state must have been a default account
|
// 6. If a post state has default program owner, the pre state must have been a default
|
||||||
|
// account
|
||||||
if post.program_owner == DEFAULT_PROGRAM_ID && pre.account != Account::default() {
|
if post.program_owner == DEFAULT_PROGRAM_ID && pre.account != Account::default() {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -16,8 +16,10 @@ const MESSAGE_ENCODING_PREFIX: &[u8; MESSAGE_ENCODING_PREFIX_LEN] =
|
|||||||
|
|
||||||
impl Message {
|
impl Message {
|
||||||
/// Serializes a `Message` into bytes in the following layout:
|
/// Serializes a `Message` into bytes in the following layout:
|
||||||
/// PREFIX || <program_id> (4 bytes LE) * 8 || account_ids_len (4 bytes LE) || account_ids (32 bytes * N) || nonces_len (4 bytes LE) || nonces (16 bytes LE * M) || instruction_data_len || instruction_data (4 bytes LE * K)
|
/// PREFIX || <program_id> (4 bytes LE) * 8 || account_ids_len (4 bytes LE) || account_ids (32
|
||||||
/// Integers and words are encoded in little-endian byte order, and fields appear in the above order.
|
/// bytes * N) || nonces_len (4 bytes LE) || nonces (16 bytes LE * M) || instruction_data_len ||
|
||||||
|
/// instruction_data (4 bytes LE * K) Integers and words are encoded in little-endian byte
|
||||||
|
/// order, and fields appear in the above order.
|
||||||
pub(crate) fn to_bytes(&self) -> Vec<u8> {
|
pub(crate) fn to_bytes(&self) -> Vec<u8> {
|
||||||
let mut bytes = MESSAGE_ENCODING_PREFIX.to_vec();
|
let mut bytes = MESSAGE_ENCODING_PREFIX.to_vec();
|
||||||
// program_id: [u32; 8]
|
// program_id: [u32; 8]
|
||||||
|
|||||||
@ -24,7 +24,5 @@ pub use privacy_preserving_transaction::{
|
|||||||
pub use program_deployment_transaction::ProgramDeploymentTransaction;
|
pub use program_deployment_transaction::ProgramDeploymentTransaction;
|
||||||
pub use program_methods::PRIVACY_PRESERVING_CIRCUIT_ID;
|
pub use program_methods::PRIVACY_PRESERVING_CIRCUIT_ID;
|
||||||
pub use public_transaction::PublicTransaction;
|
pub use public_transaction::PublicTransaction;
|
||||||
pub use signature::PrivateKey;
|
pub use signature::{PrivateKey, PublicKey, Signature};
|
||||||
pub use signature::PublicKey;
|
|
||||||
pub use signature::Signature;
|
|
||||||
pub use state::V02State;
|
pub use state::V02State;
|
||||||
|
|||||||
@ -43,6 +43,7 @@ impl MerkleTree {
|
|||||||
(1 << (capacity_depth - tree_depth)) - 1
|
(1 << (capacity_depth - tree_depth)) - 1
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Number of levels required to hold all nodes
|
/// Number of levels required to hold all nodes
|
||||||
fn depth(&self) -> usize {
|
fn depth(&self) -> usize {
|
||||||
self.length.next_power_of_two().trailing_zeros() as usize
|
self.length.next_power_of_two().trailing_zeros() as usize
|
||||||
|
|||||||
@ -6,9 +6,11 @@ use nssa_core::{
|
|||||||
};
|
};
|
||||||
use risc0_zkvm::{ExecutorEnv, InnerReceipt, Receipt, default_prover};
|
use risc0_zkvm::{ExecutorEnv, InnerReceipt, Receipt, default_prover};
|
||||||
|
|
||||||
use crate::{error::NssaError, program::Program};
|
use crate::{
|
||||||
|
error::NssaError,
|
||||||
use crate::program_methods::{PRIVACY_PRESERVING_CIRCUIT_ELF, PRIVACY_PRESERVING_CIRCUIT_ID};
|
program::Program,
|
||||||
|
program_methods::{PRIVACY_PRESERVING_CIRCUIT_ELF, PRIVACY_PRESERVING_CIRCUIT_ID},
|
||||||
|
};
|
||||||
|
|
||||||
/// Proof of the privacy preserving execution circuit
|
/// Proof of the privacy preserving execution circuit
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
@ -95,6 +97,7 @@ mod tests {
|
|||||||
account::{Account, AccountId, AccountWithMetadata},
|
account::{Account, AccountId, AccountWithMetadata},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
use super::*;
|
||||||
use crate::{
|
use crate::{
|
||||||
privacy_preserving_transaction::circuit::execute_and_prove,
|
privacy_preserving_transaction::circuit::execute_and_prove,
|
||||||
program::Program,
|
program::Program,
|
||||||
@ -104,8 +107,6 @@ mod tests {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn prove_privacy_preserving_execution_circuit_public_and_private_pre_accounts() {
|
fn prove_privacy_preserving_execution_circuit_public_and_private_pre_accounts() {
|
||||||
let recipient_keys = test_private_account_keys_1();
|
let recipient_keys = test_private_account_keys_1();
|
||||||
|
|||||||
@ -5,13 +5,12 @@ use nssa_core::{
|
|||||||
account::{Account, AccountWithMetadata},
|
account::{Account, AccountWithMetadata},
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::error::NssaError;
|
use super::{message::Message, witness_set::WitnessSet};
|
||||||
use crate::privacy_preserving_transaction::circuit::Proof;
|
use crate::{
|
||||||
use crate::privacy_preserving_transaction::message::EncryptedAccountData;
|
AccountId, V02State,
|
||||||
use crate::{AccountId, V02State};
|
error::NssaError,
|
||||||
|
privacy_preserving_transaction::{circuit::Proof, message::EncryptedAccountData},
|
||||||
use super::message::Message;
|
};
|
||||||
use super::witness_set::WitnessSet;
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct PrivacyPreservingTransaction {
|
pub struct PrivacyPreservingTransaction {
|
||||||
|
|||||||
@ -1,13 +1,14 @@
|
|||||||
use crate::program_methods::{AUTHENTICATED_TRANSFER_ELF, PINATA_ELF, TOKEN_ELF};
|
|
||||||
use nssa_core::{
|
use nssa_core::{
|
||||||
account::AccountWithMetadata,
|
account::AccountWithMetadata,
|
||||||
program::{InstructionData, ProgramId, ProgramOutput},
|
program::{InstructionData, ProgramId, ProgramOutput},
|
||||||
};
|
};
|
||||||
|
|
||||||
use risc0_zkvm::{ExecutorEnv, ExecutorEnvBuilder, default_executor, serde::to_vec};
|
use risc0_zkvm::{ExecutorEnv, ExecutorEnvBuilder, default_executor, serde::to_vec};
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
|
|
||||||
use crate::error::NssaError;
|
use crate::{
|
||||||
|
error::NssaError,
|
||||||
|
program_methods::{AUTHENTICATED_TRANSFER_ELF, PINATA_ELF, TOKEN_ELF},
|
||||||
|
};
|
||||||
|
|
||||||
/// Maximum number of cycles for a public execution.
|
/// Maximum number of cycles for a public execution.
|
||||||
/// TODO: Make this variable when fees are implemented
|
/// TODO: Make this variable when fees are implemented
|
||||||
@ -107,13 +108,15 @@ impl Program {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use crate::program_methods::{
|
|
||||||
AUTHENTICATED_TRANSFER_ELF, AUTHENTICATED_TRANSFER_ID, PINATA_ELF, PINATA_ID, TOKEN_ELF,
|
|
||||||
TOKEN_ID,
|
|
||||||
};
|
|
||||||
use nssa_core::account::{Account, AccountId, AccountWithMetadata};
|
use nssa_core::account::{Account, AccountId, AccountWithMetadata};
|
||||||
|
|
||||||
use crate::program::Program;
|
use crate::{
|
||||||
|
program::Program,
|
||||||
|
program_methods::{
|
||||||
|
AUTHENTICATED_TRANSFER_ELF, AUTHENTICATED_TRANSFER_ID, PINATA_ELF, PINATA_ID,
|
||||||
|
TOKEN_ELF, TOKEN_ID,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
impl Program {
|
impl Program {
|
||||||
/// A program that changes the nonce of an account
|
/// A program that changes the nonce of an account
|
||||||
|
|||||||
@ -39,9 +39,8 @@ impl WitnessSet {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use crate::AccountId;
|
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use crate::AccountId;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_for_message_constructor() {
|
fn test_for_message_constructor() {
|
||||||
|
|||||||
@ -4,7 +4,6 @@ mod public_key;
|
|||||||
|
|
||||||
pub use private_key::PrivateKey;
|
pub use private_key::PrivateKey;
|
||||||
pub use public_key::PublicKey;
|
pub use public_key::PublicKey;
|
||||||
|
|
||||||
use rand::{RngCore, rngs::OsRng};
|
use rand::{RngCore, rngs::OsRng};
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
|||||||
@ -1,9 +1,8 @@
|
|||||||
use nssa_core::account::AccountId;
|
use nssa_core::account::AccountId;
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
use crate::{PrivateKey, error::NssaError};
|
use crate::{PrivateKey, error::NssaError};
|
||||||
|
|
||||||
use sha2::{Digest, Sha256};
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct PublicKey([u8; 32]);
|
pub struct PublicKey([u8; 32]);
|
||||||
|
|
||||||
|
|||||||
@ -1,14 +1,17 @@
|
|||||||
|
use std::collections::{HashMap, HashSet};
|
||||||
|
|
||||||
|
use nssa_core::{
|
||||||
|
Commitment, CommitmentSetDigest, DUMMY_COMMITMENT, MembershipProof, Nullifier,
|
||||||
|
account::{Account, AccountId},
|
||||||
|
program::ProgramId,
|
||||||
|
};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
error::NssaError, merkle_tree::MerkleTree,
|
error::NssaError, merkle_tree::MerkleTree,
|
||||||
privacy_preserving_transaction::PrivacyPreservingTransaction, program::Program,
|
privacy_preserving_transaction::PrivacyPreservingTransaction, program::Program,
|
||||||
program_deployment_transaction::ProgramDeploymentTransaction,
|
program_deployment_transaction::ProgramDeploymentTransaction,
|
||||||
public_transaction::PublicTransaction,
|
public_transaction::PublicTransaction,
|
||||||
};
|
};
|
||||||
use nssa_core::{
|
|
||||||
Commitment, CommitmentSetDigest, DUMMY_COMMITMENT, MembershipProof, Nullifier,
|
|
||||||
account::Account, account::AccountId, program::ProgramId,
|
|
||||||
};
|
|
||||||
use std::collections::{HashMap, HashSet};
|
|
||||||
|
|
||||||
pub(crate) struct CommitmentSet {
|
pub(crate) struct CommitmentSet {
|
||||||
merkle_tree: MerkleTree,
|
merkle_tree: MerkleTree,
|
||||||
@ -241,6 +244,13 @@ pub mod tests {
|
|||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use nssa_core::{
|
||||||
|
Commitment, Nullifier, NullifierPublicKey, NullifierSecretKey, SharedSecretKey,
|
||||||
|
account::{Account, AccountId, AccountWithMetadata, Nonce},
|
||||||
|
encryption::{EphemeralPublicKey, IncomingViewingPublicKey, Scalar},
|
||||||
|
program::ProgramId,
|
||||||
|
};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
PublicKey, PublicTransaction, V02State,
|
PublicKey, PublicTransaction, V02State,
|
||||||
error::NssaError,
|
error::NssaError,
|
||||||
@ -253,13 +263,6 @@ pub mod tests {
|
|||||||
signature::PrivateKey,
|
signature::PrivateKey,
|
||||||
};
|
};
|
||||||
|
|
||||||
use nssa_core::{
|
|
||||||
Commitment, Nullifier, NullifierPublicKey, NullifierSecretKey, SharedSecretKey,
|
|
||||||
account::{Account, AccountId, AccountWithMetadata, Nonce},
|
|
||||||
encryption::{EphemeralPublicKey, IncomingViewingPublicKey, Scalar},
|
|
||||||
program::ProgramId,
|
|
||||||
};
|
|
||||||
|
|
||||||
fn transfer_transaction(
|
fn transfer_transaction(
|
||||||
from: AccountId,
|
from: AccountId,
|
||||||
from_key: PrivateKey,
|
from_key: PrivateKey,
|
||||||
@ -577,7 +580,8 @@ pub mod tests {
|
|||||||
V02State::new_with_genesis_accounts(&initial_data, &[]).with_test_programs();
|
V02State::new_with_genesis_accounts(&initial_data, &[]).with_test_programs();
|
||||||
let account_id = AccountId::new([1; 32]);
|
let account_id = AccountId::new([1; 32]);
|
||||||
let account = state.get_account_by_id(&account_id);
|
let account = state.get_account_by_id(&account_id);
|
||||||
// Assert the target account only differs from the default account in the program owner field
|
// Assert the target account only differs from the default account in the program owner
|
||||||
|
// field
|
||||||
assert_ne!(account.program_owner, Account::default().program_owner);
|
assert_ne!(account.program_owner, Account::default().program_owner);
|
||||||
assert_eq!(account.balance, Account::default().balance);
|
assert_eq!(account.balance, Account::default().balance);
|
||||||
assert_eq!(account.nonce, Account::default().nonce);
|
assert_eq!(account.nonce, Account::default().nonce);
|
||||||
@ -2103,7 +2107,7 @@ pub mod tests {
|
|||||||
|
|
||||||
let message = public_transaction::Message::try_new(
|
let message = public_transaction::Message::try_new(
|
||||||
program.id(),
|
program.id(),
|
||||||
vec![to, from], //The chain_caller program permutes the account order in the chain call
|
vec![to, from], // The chain_caller program permutes the account order in the call
|
||||||
vec![0],
|
vec![0],
|
||||||
instruction,
|
instruction,
|
||||||
)
|
)
|
||||||
|
|||||||
11
rustfmt.toml
11
rustfmt.toml
@ -1 +1,12 @@
|
|||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
|
newline_style = "Unix"
|
||||||
|
use_field_init_shorthand = true
|
||||||
|
use_try_shorthand = true
|
||||||
|
group_imports = "StdExternalCrate"
|
||||||
|
imports_granularity = "Crate"
|
||||||
|
normalize_comments = true
|
||||||
|
reorder_impl_items = true
|
||||||
|
wrap_comments = true
|
||||||
|
comment_width = 100
|
||||||
|
format_code_in_doc_comments = true
|
||||||
|
|||||||
@ -13,7 +13,7 @@ pub struct SequencerBlockStore {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl SequencerBlockStore {
|
impl SequencerBlockStore {
|
||||||
///Starting database at the start of new chain.
|
/// Starting database at the start of new chain.
|
||||||
/// Creates files if necessary.
|
/// Creates files if necessary.
|
||||||
///
|
///
|
||||||
/// ATTENTION: Will overwrite genesis block.
|
/// ATTENTION: Will overwrite genesis block.
|
||||||
@ -40,7 +40,7 @@ impl SequencerBlockStore {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
///Reopening existing database
|
/// Reopening existing database
|
||||||
pub fn open_db_restart(location: &Path, signing_key: nssa::PrivateKey) -> Result<Self> {
|
pub fn open_db_restart(location: &Path, signing_key: nssa::PrivateKey) -> Result<Self> {
|
||||||
SequencerBlockStore::open_db_with_genesis(location, None, signing_key)
|
SequencerBlockStore::open_db_with_genesis(location, None, signing_key)
|
||||||
}
|
}
|
||||||
@ -94,11 +94,11 @@ pub(crate) fn block_to_transactions_map(block: &Block) -> HashMap<HashType, u64>
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
|
||||||
|
|
||||||
use common::{block::HashableBlockData, test_utils::sequencer_sign_key_for_testing};
|
use common::{block::HashableBlockData, test_utils::sequencer_sign_key_for_testing};
|
||||||
use tempfile::tempdir;
|
use tempfile::tempdir;
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_get_transaction_by_hash() {
|
fn test_get_transaction_by_hash() {
|
||||||
let temp_dir = tempdir().unwrap();
|
let temp_dir = tempdir().unwrap();
|
||||||
|
|||||||
@ -1,8 +1,9 @@
|
|||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||||
///Helperstruct for account serialization
|
/// Helperstruct for account serialization
|
||||||
pub struct AccountInitialData {
|
pub struct AccountInitialData {
|
||||||
/// Hex encoded account id
|
/// Hex encoded account id
|
||||||
pub account_id: String,
|
pub account_id: String,
|
||||||
@ -19,26 +20,26 @@ pub struct CommitmentsInitialData {
|
|||||||
// TODO: Provide default values
|
// TODO: Provide default values
|
||||||
#[derive(Clone, Serialize, Deserialize)]
|
#[derive(Clone, Serialize, Deserialize)]
|
||||||
pub struct SequencerConfig {
|
pub struct SequencerConfig {
|
||||||
///Home dir of sequencer storage
|
/// Home dir of sequencer storage
|
||||||
pub home: PathBuf,
|
pub home: PathBuf,
|
||||||
///Override rust log (env var logging level)
|
/// Override rust log (env var logging level)
|
||||||
pub override_rust_log: Option<String>,
|
pub override_rust_log: Option<String>,
|
||||||
///Genesis id
|
/// Genesis id
|
||||||
pub genesis_id: u64,
|
pub genesis_id: u64,
|
||||||
///If `True`, then adds random sequence of bytes to genesis block
|
/// If `True`, then adds random sequence of bytes to genesis block
|
||||||
pub is_genesis_random: bool,
|
pub is_genesis_random: bool,
|
||||||
///Maximum number of transactions in block
|
/// Maximum number of transactions in block
|
||||||
pub max_num_tx_in_block: usize,
|
pub max_num_tx_in_block: usize,
|
||||||
///Mempool maximum size
|
/// Mempool maximum size
|
||||||
pub mempool_max_size: usize,
|
pub mempool_max_size: usize,
|
||||||
///Interval in which blocks produced
|
/// Interval in which blocks produced
|
||||||
pub block_create_timeout_millis: u64,
|
pub block_create_timeout_millis: u64,
|
||||||
///Port to listen
|
/// Port to listen
|
||||||
pub port: u16,
|
pub port: u16,
|
||||||
///List of initial accounts data
|
/// List of initial accounts data
|
||||||
pub initial_accounts: Vec<AccountInitialData>,
|
pub initial_accounts: Vec<AccountInitialData>,
|
||||||
///List of initial commitments
|
/// List of initial commitments
|
||||||
pub initial_commitments: Vec<CommitmentsInitialData>,
|
pub initial_commitments: Vec<CommitmentsInitialData>,
|
||||||
///Sequencer own signing key
|
/// Sequencer own signing key
|
||||||
pub signing_key: [u8; 32],
|
pub signing_key: [u8; 32],
|
||||||
}
|
}
|
||||||
|
|||||||
@ -53,8 +53,8 @@ impl SequencerCore {
|
|||||||
let signing_key = nssa::PrivateKey::try_new(config.signing_key).unwrap();
|
let signing_key = nssa::PrivateKey::try_new(config.signing_key).unwrap();
|
||||||
let genesis_block = hashable_data.into_block(&signing_key);
|
let genesis_block = hashable_data.into_block(&signing_key);
|
||||||
|
|
||||||
//Sequencer should panic if unable to open db,
|
// Sequencer should panic if unable to open db,
|
||||||
//as fixing this issue may require actions non-native to program scope
|
// as fixing this issue may require actions non-native to program scope
|
||||||
let block_store = SequencerBlockStore::open_db_with_genesis(
|
let block_store = SequencerBlockStore::open_db_with_genesis(
|
||||||
&config.home.join("rocksdb"),
|
&config.home.join("rocksdb"),
|
||||||
Some(genesis_block),
|
Some(genesis_block),
|
||||||
@ -100,8 +100,9 @@ impl SequencerCore {
|
|||||||
(this, mempool_handle)
|
(this, mempool_handle)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// If there are stored blocks ahead of the current height, this method will load and process all transaction
|
/// If there are stored blocks ahead of the current height, this method will load and process
|
||||||
/// in them in the order they are stored. The NSSA state will be updated accordingly.
|
/// all transaction in them in the order they are stored. The NSSA state will be updated
|
||||||
|
/// accordingly.
|
||||||
fn sync_state_with_stored_blocks(&mut self) {
|
fn sync_state_with_stored_blocks(&mut self) {
|
||||||
let mut next_block_id = self.sequencer_config.genesis_id + 1;
|
let mut next_block_id = self.sequencer_config.genesis_id + 1;
|
||||||
while let Ok(block) = self.block_store.get_block_at_id(next_block_id) {
|
while let Ok(block) = self.block_store.get_block_at_id(next_block_id) {
|
||||||
@ -181,10 +182,15 @@ impl SequencerCore {
|
|||||||
|
|
||||||
self.chain_height = new_block_height;
|
self.chain_height = new_block_height;
|
||||||
|
|
||||||
// TODO: Consider switching to `tracing` crate to have more structured and consistent logs e.g.
|
// TODO: Consider switching to `tracing` crate to have more structured and consistent logs
|
||||||
|
// e.g.
|
||||||
//
|
//
|
||||||
// ```
|
// ```
|
||||||
// info!(num_txs = num_txs_in_block, time = now.elapsed(), "Created block");
|
// info!(
|
||||||
|
// num_txs = num_txs_in_block,
|
||||||
|
// time = now.elapsed(),
|
||||||
|
// "Created block"
|
||||||
|
// );
|
||||||
// ```
|
// ```
|
||||||
log::info!(
|
log::info!(
|
||||||
"Created block with {} transactions in {} seconds",
|
"Created block with {} transactions in {} seconds",
|
||||||
@ -244,9 +250,8 @@ mod tests {
|
|||||||
use common::test_utils::sequencer_sign_key_for_testing;
|
use common::test_utils::sequencer_sign_key_for_testing;
|
||||||
use nssa::PrivateKey;
|
use nssa::PrivateKey;
|
||||||
|
|
||||||
use crate::config::AccountInitialData;
|
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use crate::config::AccountInitialData;
|
||||||
|
|
||||||
fn parse_unwrap_tx_body_into_nssa_tx(tx_body: EncodedTransaction) -> NSSATransaction {
|
fn parse_unwrap_tx_body_into_nssa_tx(tx_body: EncodedTransaction) -> NSSATransaction {
|
||||||
NSSATransaction::try_from(&tx_body)
|
NSSATransaction::try_from(&tx_body)
|
||||||
|
|||||||
@ -9,16 +9,15 @@ use common::{
|
|||||||
transaction::EncodedTransaction,
|
transaction::EncodedTransaction,
|
||||||
};
|
};
|
||||||
use mempool::MemPoolHandle;
|
use mempool::MemPoolHandle;
|
||||||
|
pub use net_utils::*;
|
||||||
use sequencer_core::SequencerCore;
|
use sequencer_core::SequencerCore;
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
|
|
||||||
pub use net_utils::*;
|
|
||||||
use tokio::sync::Mutex;
|
use tokio::sync::Mutex;
|
||||||
|
|
||||||
use self::types::err_rpc::RpcErr;
|
use self::types::err_rpc::RpcErr;
|
||||||
|
|
||||||
//ToDo: Add necessary fields
|
// ToDo: Add necessary fields
|
||||||
pub struct JsonHandler {
|
pub struct JsonHandler {
|
||||||
sequencer_state: Arc<Mutex<SequencerCore>>,
|
sequencer_state: Arc<Mutex<SequencerCore>>,
|
||||||
mempool_handle: MemPoolHandle<EncodedTransaction>,
|
mempool_handle: MemPoolHandle<EncodedTransaction>,
|
||||||
|
|||||||
@ -1,15 +1,13 @@
|
|||||||
use std::io;
|
use std::{io, sync::Arc};
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use actix_cors::Cors;
|
use actix_cors::Cors;
|
||||||
use actix_web::{App, Error as HttpError, HttpResponse, HttpServer, http, middleware, web};
|
use actix_web::{App, Error as HttpError, HttpResponse, HttpServer, http, middleware, web};
|
||||||
use common::transaction::EncodedTransaction;
|
use common::{
|
||||||
use futures::Future;
|
rpc_primitives::{RpcConfig, message::Message},
|
||||||
use futures::FutureExt;
|
transaction::EncodedTransaction,
|
||||||
|
};
|
||||||
|
use futures::{Future, FutureExt};
|
||||||
use log::info;
|
use log::info;
|
||||||
|
|
||||||
use common::rpc_primitives::RpcConfig;
|
|
||||||
use common::rpc_primitives::message::Message;
|
|
||||||
use mempool::MemPoolHandle;
|
use mempool::MemPoolHandle;
|
||||||
use sequencer_core::SequencerCore;
|
use sequencer_core::SequencerCore;
|
||||||
use tokio::sync::Mutex;
|
use tokio::sync::Mutex;
|
||||||
|
|||||||
@ -3,11 +3,6 @@ use std::collections::HashMap;
|
|||||||
use actix_web::Error as HttpError;
|
use actix_web::Error as HttpError;
|
||||||
use base58::FromBase58;
|
use base58::FromBase58;
|
||||||
use base64::{Engine, engine::general_purpose};
|
use base64::{Engine, engine::general_purpose};
|
||||||
use log::warn;
|
|
||||||
use nssa::{self, program::Program};
|
|
||||||
use sequencer_core::{TransactionMalformationError, config::AccountInitialData};
|
|
||||||
use serde_json::Value;
|
|
||||||
|
|
||||||
use common::{
|
use common::{
|
||||||
HashType,
|
HashType,
|
||||||
block::HashableBlockData,
|
block::HashableBlockData,
|
||||||
@ -18,19 +13,20 @@ use common::{
|
|||||||
requests::{
|
requests::{
|
||||||
GetAccountBalanceRequest, GetAccountBalanceResponse, GetAccountRequest,
|
GetAccountBalanceRequest, GetAccountBalanceResponse, GetAccountRequest,
|
||||||
GetAccountResponse, GetAccountsNoncesRequest, GetAccountsNoncesResponse,
|
GetAccountResponse, GetAccountsNoncesRequest, GetAccountsNoncesResponse,
|
||||||
GetInitialTestnetAccountsRequest, GetProgramIdsRequest, GetProgramIdsResponse,
|
GetBlockDataRequest, GetBlockDataResponse, GetGenesisIdRequest, GetGenesisIdResponse,
|
||||||
GetProofForCommitmentRequest, GetProofForCommitmentResponse,
|
GetInitialTestnetAccountsRequest, GetLastBlockRequest, GetLastBlockResponse,
|
||||||
GetTransactionByHashRequest, GetTransactionByHashResponse,
|
GetProgramIdsRequest, GetProgramIdsResponse, GetProofForCommitmentRequest,
|
||||||
|
GetProofForCommitmentResponse, GetTransactionByHashRequest,
|
||||||
|
GetTransactionByHashResponse, HelloRequest, HelloResponse, SendTxRequest,
|
||||||
|
SendTxResponse,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
transaction::{EncodedTransaction, NSSATransaction},
|
transaction::{EncodedTransaction, NSSATransaction},
|
||||||
};
|
};
|
||||||
|
use log::warn;
|
||||||
use common::rpc_primitives::requests::{
|
use nssa::{self, program::Program};
|
||||||
GetBlockDataRequest, GetBlockDataResponse, GetGenesisIdRequest, GetGenesisIdResponse,
|
use sequencer_core::{TransactionMalformationError, config::AccountInitialData};
|
||||||
GetLastBlockRequest, GetLastBlockResponse, HelloRequest, HelloResponse, SendTxRequest,
|
use serde_json::Value;
|
||||||
SendTxResponse,
|
|
||||||
};
|
|
||||||
|
|
||||||
use super::{JsonHandler, respond, types::err_rpc::RpcErr};
|
use super::{JsonHandler, respond, types::err_rpc::RpcErr};
|
||||||
|
|
||||||
@ -91,7 +87,8 @@ impl JsonHandler {
|
|||||||
let authenticated_tx = sequencer_core::transaction_pre_check(transaction)
|
let authenticated_tx = sequencer_core::transaction_pre_check(transaction)
|
||||||
.inspect_err(|err| warn!("Error at pre_check {err:#?}"))?;
|
.inspect_err(|err| warn!("Error at pre_check {err:#?}"))?;
|
||||||
|
|
||||||
// TODO: Do we need a timeout here? It will be usable if we have too many transactions to process
|
// TODO: Do we need a timeout here? It will be usable if we have too many transactions to
|
||||||
|
// process
|
||||||
self.mempool_handle
|
self.mempool_handle
|
||||||
.push(authenticated_tx.into())
|
.push(authenticated_tx.into())
|
||||||
.await
|
.await
|
||||||
@ -318,11 +315,9 @@ impl JsonHandler {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use crate::{JsonHandler, rpc_handler};
|
|
||||||
use base58::ToBase58;
|
use base58::ToBase58;
|
||||||
use base64::{Engine, engine::general_purpose};
|
use base64::{Engine, engine::general_purpose};
|
||||||
use common::{test_utils::sequencer_sign_key_for_testing, transaction::EncodedTransaction};
|
use common::{test_utils::sequencer_sign_key_for_testing, transaction::EncodedTransaction};
|
||||||
|
|
||||||
use sequencer_core::{
|
use sequencer_core::{
|
||||||
SequencerCore,
|
SequencerCore,
|
||||||
config::{AccountInitialData, SequencerConfig},
|
config::{AccountInitialData, SequencerConfig},
|
||||||
@ -331,6 +326,8 @@ mod tests {
|
|||||||
use tempfile::tempdir;
|
use tempfile::tempdir;
|
||||||
use tokio::sync::Mutex;
|
use tokio::sync::Mutex;
|
||||||
|
|
||||||
|
use crate::{JsonHandler, rpc_handler};
|
||||||
|
|
||||||
fn sequencer_config_for_tests() -> SequencerConfig {
|
fn sequencer_config_for_tests() -> SequencerConfig {
|
||||||
let tempdir = tempdir().unwrap();
|
let tempdir = tempdir().unwrap();
|
||||||
let home = tempdir.path().to_path_buf();
|
let home = tempdir.path().to_path_buf();
|
||||||
|
|||||||
@ -1,6 +1,5 @@
|
|||||||
use log::debug;
|
|
||||||
|
|
||||||
use common::rpc_primitives::errors::{RpcError, RpcParseError};
|
use common::rpc_primitives::errors::{RpcError, RpcParseError};
|
||||||
|
use log::debug;
|
||||||
use sequencer_core::TransactionMalformationError;
|
use sequencer_core::TransactionMalformationError;
|
||||||
|
|
||||||
pub struct RpcErr(pub RpcError);
|
pub struct RpcErr(pub RpcError);
|
||||||
|
|||||||
@ -1,11 +1,8 @@
|
|||||||
use std::path::PathBuf;
|
use std::{fs::File, io::BufReader, path::PathBuf};
|
||||||
|
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use sequencer_core::config::SequencerConfig;
|
use sequencer_core::config::SequencerConfig;
|
||||||
|
|
||||||
use std::fs::File;
|
|
||||||
use std::io::BufReader;
|
|
||||||
|
|
||||||
pub fn from_file(config_home: PathBuf) -> Result<SequencerConfig> {
|
pub fn from_file(config_home: PathBuf) -> Result<SequencerConfig> {
|
||||||
let file = File::open(config_home)?;
|
let file = File::open(config_home)?;
|
||||||
let reader = BufReader::new(file);
|
let reader = BufReader::new(file);
|
||||||
|
|||||||
@ -80,7 +80,7 @@ pub async fn main_runner() -> Result<()> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//ToDo: Add restart on failures
|
// ToDo: Add restart on failures
|
||||||
let (_, main_loop_handle) = startup_sequencer(app_config).await?;
|
let (_, main_loop_handle) = startup_sequencer(app_config).await?;
|
||||||
|
|
||||||
main_loop_handle.await??;
|
main_loop_handle.await??;
|
||||||
|
|||||||
@ -1,5 +1,4 @@
|
|||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
|
|
||||||
use sequencer_runner::main_runner;
|
use sequencer_runner::main_runner;
|
||||||
|
|
||||||
pub const NUM_THREADS: usize = 4;
|
pub const NUM_THREADS: usize = 4;
|
||||||
|
|||||||
@ -8,33 +8,33 @@ use rocksdb::{
|
|||||||
|
|
||||||
pub mod error;
|
pub mod error;
|
||||||
|
|
||||||
///Maximal size of stored blocks in base
|
/// Maximal size of stored blocks in base
|
||||||
///
|
///
|
||||||
///Used to control db size
|
/// Used to control db size
|
||||||
///
|
///
|
||||||
///Currently effectively unbounded.
|
/// Currently effectively unbounded.
|
||||||
pub const BUFF_SIZE_ROCKSDB: usize = usize::MAX;
|
pub const BUFF_SIZE_ROCKSDB: usize = usize::MAX;
|
||||||
|
|
||||||
///Size of stored blocks cache in memory
|
/// Size of stored blocks cache in memory
|
||||||
///
|
///
|
||||||
///Keeping small to not run out of memory
|
/// Keeping small to not run out of memory
|
||||||
pub const CACHE_SIZE: usize = 1000;
|
pub const CACHE_SIZE: usize = 1000;
|
||||||
|
|
||||||
///Key base for storing metainformation about id of first block in db
|
/// Key base for storing metainformation about id of first block in db
|
||||||
pub const DB_META_FIRST_BLOCK_IN_DB_KEY: &str = "first_block_in_db";
|
pub const DB_META_FIRST_BLOCK_IN_DB_KEY: &str = "first_block_in_db";
|
||||||
///Key base for storing metainformation about id of last current block in db
|
/// Key base for storing metainformation about id of last current block in db
|
||||||
pub const DB_META_LAST_BLOCK_IN_DB_KEY: &str = "last_block_in_db";
|
pub const DB_META_LAST_BLOCK_IN_DB_KEY: &str = "last_block_in_db";
|
||||||
///Key base for storing metainformation which describe if first block has been set
|
/// Key base for storing metainformation which describe if first block has been set
|
||||||
pub const DB_META_FIRST_BLOCK_SET_KEY: &str = "first_block_set";
|
pub const DB_META_FIRST_BLOCK_SET_KEY: &str = "first_block_set";
|
||||||
|
|
||||||
///Key base for storing snapshot which describe block id
|
/// Key base for storing snapshot which describe block id
|
||||||
pub const DB_SNAPSHOT_BLOCK_ID_KEY: &str = "block_id";
|
pub const DB_SNAPSHOT_BLOCK_ID_KEY: &str = "block_id";
|
||||||
|
|
||||||
///Name of block column family
|
/// Name of block column family
|
||||||
pub const CF_BLOCK_NAME: &str = "cf_block";
|
pub const CF_BLOCK_NAME: &str = "cf_block";
|
||||||
///Name of meta column family
|
/// Name of meta column family
|
||||||
pub const CF_META_NAME: &str = "cf_meta";
|
pub const CF_META_NAME: &str = "cf_meta";
|
||||||
///Name of snapshot column family
|
/// Name of snapshot column family
|
||||||
pub const CF_SNAPSHOT_NAME: &str = "cf_snapshot";
|
pub const CF_SNAPSHOT_NAME: &str = "cf_snapshot";
|
||||||
|
|
||||||
pub type DbResult<T> = Result<T, DbError>;
|
pub type DbResult<T> = Result<T, DbError>;
|
||||||
@ -47,7 +47,7 @@ impl RocksDBIO {
|
|||||||
pub fn open_or_create(path: &Path, start_block: Option<Block>) -> DbResult<Self> {
|
pub fn open_or_create(path: &Path, start_block: Option<Block>) -> DbResult<Self> {
|
||||||
let mut cf_opts = Options::default();
|
let mut cf_opts = Options::default();
|
||||||
cf_opts.set_max_write_buffer_number(16);
|
cf_opts.set_max_write_buffer_number(16);
|
||||||
//ToDo: Add more column families for different data
|
// ToDo: Add more column families for different data
|
||||||
let cfb = ColumnFamilyDescriptor::new(CF_BLOCK_NAME, cf_opts.clone());
|
let cfb = ColumnFamilyDescriptor::new(CF_BLOCK_NAME, cf_opts.clone());
|
||||||
let cfmeta = ColumnFamilyDescriptor::new(CF_META_NAME, cf_opts.clone());
|
let cfmeta = ColumnFamilyDescriptor::new(CF_META_NAME, cf_opts.clone());
|
||||||
let cfsnapshot = ColumnFamilyDescriptor::new(CF_SNAPSHOT_NAME, cf_opts.clone());
|
let cfsnapshot = ColumnFamilyDescriptor::new(CF_SNAPSHOT_NAME, cf_opts.clone());
|
||||||
@ -62,7 +62,7 @@ impl RocksDBIO {
|
|||||||
);
|
);
|
||||||
|
|
||||||
let dbio = Self {
|
let dbio = Self {
|
||||||
//There is no point in handling this from runner code
|
// There is no point in handling this from runner code
|
||||||
db: db.unwrap(),
|
db: db.unwrap(),
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -86,7 +86,7 @@ impl RocksDBIO {
|
|||||||
pub fn destroy(path: &Path) -> DbResult<()> {
|
pub fn destroy(path: &Path) -> DbResult<()> {
|
||||||
let mut cf_opts = Options::default();
|
let mut cf_opts = Options::default();
|
||||||
cf_opts.set_max_write_buffer_number(16);
|
cf_opts.set_max_write_buffer_number(16);
|
||||||
//ToDo: Add more column families for different data
|
// ToDo: Add more column families for different data
|
||||||
let _cfb = ColumnFamilyDescriptor::new(CF_BLOCK_NAME, cf_opts.clone());
|
let _cfb = ColumnFamilyDescriptor::new(CF_BLOCK_NAME, cf_opts.clone());
|
||||||
let _cfmeta = ColumnFamilyDescriptor::new(CF_META_NAME, cf_opts.clone());
|
let _cfmeta = ColumnFamilyDescriptor::new(CF_META_NAME, cf_opts.clone());
|
||||||
let _cfsnapshot = ColumnFamilyDescriptor::new(CF_SNAPSHOT_NAME, cf_opts.clone());
|
let _cfsnapshot = ColumnFamilyDescriptor::new(CF_SNAPSHOT_NAME, cf_opts.clone());
|
||||||
|
|||||||
@ -72,9 +72,8 @@ impl WalletChainStore {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use crate::config::InitialAccountData;
|
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use crate::config::InitialAccountData;
|
||||||
|
|
||||||
fn create_initial_accounts() -> Vec<InitialAccountData> {
|
fn create_initial_accounts() -> Vec<InitialAccountData> {
|
||||||
let initial_acc1 = serde_json::from_str(
|
let initial_acc1 = serde_json::from_str(
|
||||||
|
|||||||
@ -66,31 +66,31 @@ impl TokenHolding {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
///Represents generic chain CLI subcommand
|
/// Represents generic chain CLI subcommand
|
||||||
#[derive(Subcommand, Debug, Clone)]
|
#[derive(Subcommand, Debug, Clone)]
|
||||||
pub enum AccountSubcommand {
|
pub enum AccountSubcommand {
|
||||||
///Get account data
|
/// Get account data
|
||||||
Get {
|
Get {
|
||||||
///Flag to get raw account data
|
/// Flag to get raw account data
|
||||||
#[arg(short, long)]
|
#[arg(short, long)]
|
||||||
raw: bool,
|
raw: bool,
|
||||||
///Valid 32 byte base58 string with privacy prefix
|
/// Valid 32 byte base58 string with privacy prefix
|
||||||
#[arg(short, long)]
|
#[arg(short, long)]
|
||||||
account_id: String,
|
account_id: String,
|
||||||
},
|
},
|
||||||
///Produce new public or private account
|
/// Produce new public or private account
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
New(NewSubcommand),
|
New(NewSubcommand),
|
||||||
///Sync private accounts
|
/// Sync private accounts
|
||||||
SyncPrivate {},
|
SyncPrivate {},
|
||||||
}
|
}
|
||||||
|
|
||||||
///Represents generic register CLI subcommand
|
/// Represents generic register CLI subcommand
|
||||||
#[derive(Subcommand, Debug, Clone)]
|
#[derive(Subcommand, Debug, Clone)]
|
||||||
pub enum NewSubcommand {
|
pub enum NewSubcommand {
|
||||||
///Register new public account
|
/// Register new public account
|
||||||
Public {},
|
Public {},
|
||||||
///Register new private account
|
/// Register new private account
|
||||||
Private {},
|
Private {},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -3,19 +3,19 @@ use clap::Subcommand;
|
|||||||
|
|
||||||
use crate::{SubcommandReturnValue, WalletCore, cli::WalletSubcommand};
|
use crate::{SubcommandReturnValue, WalletCore, cli::WalletSubcommand};
|
||||||
|
|
||||||
///Represents generic chain CLI subcommand
|
/// Represents generic chain CLI subcommand
|
||||||
#[derive(Subcommand, Debug, Clone)]
|
#[derive(Subcommand, Debug, Clone)]
|
||||||
pub enum ChainSubcommand {
|
pub enum ChainSubcommand {
|
||||||
///Get current block id from sequencer
|
/// Get current block id from sequencer
|
||||||
CurrentBlockId {},
|
CurrentBlockId {},
|
||||||
///Get block at id from sequencer
|
/// Get block at id from sequencer
|
||||||
Block {
|
Block {
|
||||||
#[arg(short, long)]
|
#[arg(short, long)]
|
||||||
id: u64,
|
id: u64,
|
||||||
},
|
},
|
||||||
///Get transaction at hash from sequencer
|
/// Get transaction at hash from sequencer
|
||||||
Transaction {
|
Transaction {
|
||||||
///hash - valid 32 byte hex string
|
/// hash - valid 32 byte hex string
|
||||||
#[arg(short, long)]
|
#[arg(short, long)]
|
||||||
hash: String,
|
hash: String,
|
||||||
},
|
},
|
||||||
|
|||||||
@ -3,7 +3,7 @@ use clap::Subcommand;
|
|||||||
|
|
||||||
use crate::{SubcommandReturnValue, WalletCore, cli::WalletSubcommand};
|
use crate::{SubcommandReturnValue, WalletCore, cli::WalletSubcommand};
|
||||||
|
|
||||||
///Represents generic config CLI subcommand
|
/// Represents generic config CLI subcommand
|
||||||
#[derive(Subcommand, Debug, Clone)]
|
#[derive(Subcommand, Debug, Clone)]
|
||||||
pub enum ConfigSubcommand {
|
pub enum ConfigSubcommand {
|
||||||
/// Command to explicitly setup config and storage
|
/// Command to explicitly setup config and storage
|
||||||
|
|||||||
@ -9,34 +9,35 @@ use crate::{
|
|||||||
helperfunctions::{AccountPrivacyKind, parse_addr_with_privacy_prefix},
|
helperfunctions::{AccountPrivacyKind, parse_addr_with_privacy_prefix},
|
||||||
};
|
};
|
||||||
|
|
||||||
///Represents generic CLI subcommand for a wallet working with native token transfer program
|
/// Represents generic CLI subcommand for a wallet working with native token transfer program
|
||||||
#[derive(Subcommand, Debug, Clone)]
|
#[derive(Subcommand, Debug, Clone)]
|
||||||
pub enum AuthTransferSubcommand {
|
pub enum AuthTransferSubcommand {
|
||||||
///Initialize account under authenticated transfer program
|
/// Initialize account under authenticated transfer program
|
||||||
Init {
|
Init {
|
||||||
///account_id - valid 32 byte base58 string with privacy prefix
|
/// account_id - valid 32 byte base58 string with privacy prefix
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
account_id: String,
|
account_id: String,
|
||||||
},
|
},
|
||||||
///Send native tokens from one account to another with variable privacy
|
/// Send native tokens from one account to another with variable privacy
|
||||||
///
|
///
|
||||||
///If receiver is private, then `to` and (`to_npk` , `to_ipk`) is a mutually exclusive patterns.
|
/// If receiver is private, then `to` and (`to_npk` , `to_ipk`) is a mutually exclusive
|
||||||
|
/// patterns.
|
||||||
///
|
///
|
||||||
///First is used for owned accounts, second otherwise.
|
/// First is used for owned accounts, second otherwise.
|
||||||
Send {
|
Send {
|
||||||
///from - valid 32 byte base58 string with privacy prefix
|
/// from - valid 32 byte base58 string with privacy prefix
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
from: String,
|
from: String,
|
||||||
///to - valid 32 byte base58 string with privacy prefix
|
/// to - valid 32 byte base58 string with privacy prefix
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
to: Option<String>,
|
to: Option<String>,
|
||||||
///to_npk - valid 32 byte hex string
|
/// to_npk - valid 32 byte hex string
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
to_npk: Option<String>,
|
to_npk: Option<String>,
|
||||||
///to_ipk - valid 33 byte hex string
|
/// to_ipk - valid 33 byte hex string
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
to_ipk: Option<String>,
|
to_ipk: Option<String>,
|
||||||
///amount - amount of balance to move
|
/// amount - amount of balance to move
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
amount: u128,
|
amount: u128,
|
||||||
},
|
},
|
||||||
@ -193,112 +194,114 @@ impl WalletSubcommand for AuthTransferSubcommand {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
///Represents generic CLI subcommand for a wallet working with native token transfer program
|
/// Represents generic CLI subcommand for a wallet working with native token transfer program
|
||||||
#[derive(Subcommand, Debug, Clone)]
|
#[derive(Subcommand, Debug, Clone)]
|
||||||
pub enum NativeTokenTransferProgramSubcommand {
|
pub enum NativeTokenTransferProgramSubcommand {
|
||||||
///Send native token transfer from `from` to `to` for `amount`
|
/// Send native token transfer from `from` to `to` for `amount`
|
||||||
///
|
///
|
||||||
/// Public operation
|
/// Public operation
|
||||||
Public {
|
Public {
|
||||||
///from - valid 32 byte hex string
|
/// from - valid 32 byte hex string
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
from: String,
|
from: String,
|
||||||
///to - valid 32 byte hex string
|
/// to - valid 32 byte hex string
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
to: String,
|
to: String,
|
||||||
///amount - amount of balance to move
|
/// amount - amount of balance to move
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
amount: u128,
|
amount: u128,
|
||||||
},
|
},
|
||||||
///Private execution
|
/// Private execution
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
Private(NativeTokenTransferProgramSubcommandPrivate),
|
Private(NativeTokenTransferProgramSubcommandPrivate),
|
||||||
///Send native token transfer from `from` to `to` for `amount`
|
/// Send native token transfer from `from` to `to` for `amount`
|
||||||
///
|
///
|
||||||
/// Deshielded operation
|
/// Deshielded operation
|
||||||
Deshielded {
|
Deshielded {
|
||||||
///from - valid 32 byte hex string
|
/// from - valid 32 byte hex string
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
from: String,
|
from: String,
|
||||||
///to - valid 32 byte hex string
|
/// to - valid 32 byte hex string
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
to: String,
|
to: String,
|
||||||
///amount - amount of balance to move
|
/// amount - amount of balance to move
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
amount: u128,
|
amount: u128,
|
||||||
},
|
},
|
||||||
///Shielded execution
|
/// Shielded execution
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
Shielded(NativeTokenTransferProgramSubcommandShielded),
|
Shielded(NativeTokenTransferProgramSubcommandShielded),
|
||||||
}
|
}
|
||||||
|
|
||||||
///Represents generic shielded CLI subcommand for a wallet working with native token transfer program
|
/// Represents generic shielded CLI subcommand for a wallet working with native token transfer
|
||||||
|
/// program
|
||||||
#[derive(Subcommand, Debug, Clone)]
|
#[derive(Subcommand, Debug, Clone)]
|
||||||
pub enum NativeTokenTransferProgramSubcommandShielded {
|
pub enum NativeTokenTransferProgramSubcommandShielded {
|
||||||
///Send native token transfer from `from` to `to` for `amount`
|
/// Send native token transfer from `from` to `to` for `amount`
|
||||||
///
|
///
|
||||||
/// Shielded operation
|
/// Shielded operation
|
||||||
ShieldedOwned {
|
ShieldedOwned {
|
||||||
///from - valid 32 byte hex string
|
/// from - valid 32 byte hex string
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
from: String,
|
from: String,
|
||||||
///to - valid 32 byte hex string
|
/// to - valid 32 byte hex string
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
to: String,
|
to: String,
|
||||||
///amount - amount of balance to move
|
/// amount - amount of balance to move
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
amount: u128,
|
amount: u128,
|
||||||
},
|
},
|
||||||
///Send native token transfer from `from` to `to` for `amount`
|
/// Send native token transfer from `from` to `to` for `amount`
|
||||||
///
|
///
|
||||||
/// Shielded operation
|
/// Shielded operation
|
||||||
ShieldedForeign {
|
ShieldedForeign {
|
||||||
///from - valid 32 byte hex string
|
/// from - valid 32 byte hex string
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
from: String,
|
from: String,
|
||||||
///to_npk - valid 32 byte hex string
|
/// to_npk - valid 32 byte hex string
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
to_npk: String,
|
to_npk: String,
|
||||||
///to_ipk - valid 33 byte hex string
|
/// to_ipk - valid 33 byte hex string
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
to_ipk: String,
|
to_ipk: String,
|
||||||
///amount - amount of balance to move
|
/// amount - amount of balance to move
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
amount: u128,
|
amount: u128,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
///Represents generic private CLI subcommand for a wallet working with native token transfer program
|
/// Represents generic private CLI subcommand for a wallet working with native token transfer
|
||||||
|
/// program
|
||||||
#[derive(Subcommand, Debug, Clone)]
|
#[derive(Subcommand, Debug, Clone)]
|
||||||
pub enum NativeTokenTransferProgramSubcommandPrivate {
|
pub enum NativeTokenTransferProgramSubcommandPrivate {
|
||||||
///Send native token transfer from `from` to `to` for `amount`
|
/// Send native token transfer from `from` to `to` for `amount`
|
||||||
///
|
///
|
||||||
/// Private operation
|
/// Private operation
|
||||||
PrivateOwned {
|
PrivateOwned {
|
||||||
///from - valid 32 byte hex string
|
/// from - valid 32 byte hex string
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
from: String,
|
from: String,
|
||||||
///to - valid 32 byte hex string
|
/// to - valid 32 byte hex string
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
to: String,
|
to: String,
|
||||||
///amount - amount of balance to move
|
/// amount - amount of balance to move
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
amount: u128,
|
amount: u128,
|
||||||
},
|
},
|
||||||
///Send native token transfer from `from` to `to` for `amount`
|
/// Send native token transfer from `from` to `to` for `amount`
|
||||||
///
|
///
|
||||||
/// Private operation
|
/// Private operation
|
||||||
PrivateForeign {
|
PrivateForeign {
|
||||||
///from - valid 32 byte hex string
|
/// from - valid 32 byte hex string
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
from: String,
|
from: String,
|
||||||
///to_npk - valid 32 byte hex string
|
/// to_npk - valid 32 byte hex string
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
to_npk: String,
|
to_npk: String,
|
||||||
///to_ipk - valid 33 byte hex string
|
/// to_ipk - valid 33 byte hex string
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
to_ipk: String,
|
to_ipk: String,
|
||||||
///amount - amount of balance to move
|
/// amount - amount of balance to move
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
amount: u128,
|
amount: u128,
|
||||||
},
|
},
|
||||||
|
|||||||
@ -9,15 +9,15 @@ use crate::{
|
|||||||
helperfunctions::{AccountPrivacyKind, parse_addr_with_privacy_prefix},
|
helperfunctions::{AccountPrivacyKind, parse_addr_with_privacy_prefix},
|
||||||
};
|
};
|
||||||
|
|
||||||
///Represents generic CLI subcommand for a wallet working with pinata program
|
/// Represents generic CLI subcommand for a wallet working with pinata program
|
||||||
#[derive(Subcommand, Debug, Clone)]
|
#[derive(Subcommand, Debug, Clone)]
|
||||||
pub enum PinataProgramAgnosticSubcommand {
|
pub enum PinataProgramAgnosticSubcommand {
|
||||||
///Claim pinata
|
/// Claim pinata
|
||||||
Claim {
|
Claim {
|
||||||
///to_account_id - valid 32 byte base58 string with privacy prefix
|
/// to_account_id - valid 32 byte base58 string with privacy prefix
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
to_account_id: String,
|
to_account_id: String,
|
||||||
///solution - solution to pinata challenge
|
/// solution - solution to pinata challenge
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
solution: u128,
|
solution: u128,
|
||||||
},
|
},
|
||||||
@ -59,48 +59,48 @@ impl WalletSubcommand for PinataProgramAgnosticSubcommand {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
///Represents generic CLI subcommand for a wallet working with pinata program
|
/// Represents generic CLI subcommand for a wallet working with pinata program
|
||||||
#[derive(Subcommand, Debug, Clone)]
|
#[derive(Subcommand, Debug, Clone)]
|
||||||
pub enum PinataProgramSubcommand {
|
pub enum PinataProgramSubcommand {
|
||||||
///Public execution
|
/// Public execution
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
Public(PinataProgramSubcommandPublic),
|
Public(PinataProgramSubcommandPublic),
|
||||||
///Private execution
|
/// Private execution
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
Private(PinataProgramSubcommandPrivate),
|
Private(PinataProgramSubcommandPrivate),
|
||||||
}
|
}
|
||||||
|
|
||||||
///Represents generic public CLI subcommand for a wallet working with pinata program
|
/// Represents generic public CLI subcommand for a wallet working with pinata program
|
||||||
#[derive(Subcommand, Debug, Clone)]
|
#[derive(Subcommand, Debug, Clone)]
|
||||||
pub enum PinataProgramSubcommandPublic {
|
pub enum PinataProgramSubcommandPublic {
|
||||||
// TODO: Testnet only. Refactor to prevent compilation on mainnet.
|
// TODO: Testnet only. Refactor to prevent compilation on mainnet.
|
||||||
// Claim piñata prize
|
// Claim piñata prize
|
||||||
Claim {
|
Claim {
|
||||||
///pinata_account_id - valid 32 byte hex string
|
/// pinata_account_id - valid 32 byte hex string
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
pinata_account_id: String,
|
pinata_account_id: String,
|
||||||
///winner_account_id - valid 32 byte hex string
|
/// winner_account_id - valid 32 byte hex string
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
winner_account_id: String,
|
winner_account_id: String,
|
||||||
///solution - solution to pinata challenge
|
/// solution - solution to pinata challenge
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
solution: u128,
|
solution: u128,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
///Represents generic private CLI subcommand for a wallet working with pinata program
|
/// Represents generic private CLI subcommand for a wallet working with pinata program
|
||||||
#[derive(Subcommand, Debug, Clone)]
|
#[derive(Subcommand, Debug, Clone)]
|
||||||
pub enum PinataProgramSubcommandPrivate {
|
pub enum PinataProgramSubcommandPrivate {
|
||||||
// TODO: Testnet only. Refactor to prevent compilation on mainnet.
|
// TODO: Testnet only. Refactor to prevent compilation on mainnet.
|
||||||
// Claim piñata prize
|
// Claim piñata prize
|
||||||
ClaimPrivateOwned {
|
ClaimPrivateOwned {
|
||||||
///pinata_account_id - valid 32 byte hex string
|
/// pinata_account_id - valid 32 byte hex string
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
pinata_account_id: String,
|
pinata_account_id: String,
|
||||||
///winner_account_id - valid 32 byte hex string
|
/// winner_account_id - valid 32 byte hex string
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
winner_account_id: String,
|
winner_account_id: String,
|
||||||
///solution - solution to pinata challenge
|
/// solution - solution to pinata challenge
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
solution: u128,
|
solution: u128,
|
||||||
},
|
},
|
||||||
|
|||||||
@ -9,17 +9,17 @@ use crate::{
|
|||||||
helperfunctions::{AccountPrivacyKind, parse_addr_with_privacy_prefix},
|
helperfunctions::{AccountPrivacyKind, parse_addr_with_privacy_prefix},
|
||||||
};
|
};
|
||||||
|
|
||||||
///Represents generic CLI subcommand for a wallet working with token program
|
/// Represents generic CLI subcommand for a wallet working with token program
|
||||||
#[derive(Subcommand, Debug, Clone)]
|
#[derive(Subcommand, Debug, Clone)]
|
||||||
pub enum TokenProgramAgnosticSubcommand {
|
pub enum TokenProgramAgnosticSubcommand {
|
||||||
///Produce a new token
|
/// Produce a new token
|
||||||
///
|
///
|
||||||
///Currently the only supported privacy options is for public definition
|
/// Currently the only supported privacy options is for public definition
|
||||||
New {
|
New {
|
||||||
///definition_account_id - valid 32 byte base58 string with privacy prefix
|
/// definition_account_id - valid 32 byte base58 string with privacy prefix
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
definition_account_id: String,
|
definition_account_id: String,
|
||||||
///supply_account_id - valid 32 byte base58 string with privacy prefix
|
/// supply_account_id - valid 32 byte base58 string with privacy prefix
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
supply_account_id: String,
|
supply_account_id: String,
|
||||||
#[arg(short, long)]
|
#[arg(short, long)]
|
||||||
@ -27,25 +27,26 @@ pub enum TokenProgramAgnosticSubcommand {
|
|||||||
#[arg(short, long)]
|
#[arg(short, long)]
|
||||||
total_supply: u128,
|
total_supply: u128,
|
||||||
},
|
},
|
||||||
///Send tokens from one account to another with variable privacy
|
/// Send tokens from one account to another with variable privacy
|
||||||
///
|
///
|
||||||
///If receiver is private, then `to` and (`to_npk` , `to_ipk`) is a mutually exclusive patterns.
|
/// If receiver is private, then `to` and (`to_npk` , `to_ipk`) is a mutually exclusive
|
||||||
|
/// patterns.
|
||||||
///
|
///
|
||||||
///First is used for owned accounts, second otherwise.
|
/// First is used for owned accounts, second otherwise.
|
||||||
Send {
|
Send {
|
||||||
///from - valid 32 byte base58 string with privacy prefix
|
/// from - valid 32 byte base58 string with privacy prefix
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
from: String,
|
from: String,
|
||||||
///to - valid 32 byte base58 string with privacy prefix
|
/// to - valid 32 byte base58 string with privacy prefix
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
to: Option<String>,
|
to: Option<String>,
|
||||||
///to_npk - valid 32 byte hex string
|
/// to_npk - valid 32 byte hex string
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
to_npk: Option<String>,
|
to_npk: Option<String>,
|
||||||
///to_ipk - valid 33 byte hex string
|
/// to_ipk - valid 33 byte hex string
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
to_ipk: Option<String>,
|
to_ipk: Option<String>,
|
||||||
///amount - amount of balance to move
|
/// amount - amount of balance to move
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
amount: u128,
|
amount: u128,
|
||||||
},
|
},
|
||||||
@ -90,11 +91,13 @@ impl WalletSubcommand for TokenProgramAgnosticSubcommand {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
(AccountPrivacyKind::Private, AccountPrivacyKind::Private) => {
|
(AccountPrivacyKind::Private, AccountPrivacyKind::Private) => {
|
||||||
//ToDo: maybe implement this one. It is not immediately clear why definition should be private.
|
// ToDo: maybe implement this one. It is not immediately clear why
|
||||||
|
// definition should be private.
|
||||||
anyhow::bail!("Unavailable privacy pairing")
|
anyhow::bail!("Unavailable privacy pairing")
|
||||||
}
|
}
|
||||||
(AccountPrivacyKind::Private, AccountPrivacyKind::Public) => {
|
(AccountPrivacyKind::Private, AccountPrivacyKind::Public) => {
|
||||||
//ToDo: Probably valid. If definition is not public, but supply is it is very suspicious.
|
// ToDo: Probably valid. If definition is not public, but supply is it is
|
||||||
|
// very suspicious.
|
||||||
anyhow::bail!("Unavailable privacy pairing")
|
anyhow::bail!("Unavailable privacy pairing")
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -195,27 +198,27 @@ impl WalletSubcommand for TokenProgramAgnosticSubcommand {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
///Represents generic CLI subcommand for a wallet working with token_program
|
/// Represents generic CLI subcommand for a wallet working with token_program
|
||||||
#[derive(Subcommand, Debug, Clone)]
|
#[derive(Subcommand, Debug, Clone)]
|
||||||
pub enum TokenProgramSubcommand {
|
pub enum TokenProgramSubcommand {
|
||||||
///Public execution
|
/// Public execution
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
Public(TokenProgramSubcommandPublic),
|
Public(TokenProgramSubcommandPublic),
|
||||||
///Private execution
|
/// Private execution
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
Private(TokenProgramSubcommandPrivate),
|
Private(TokenProgramSubcommandPrivate),
|
||||||
///Deshielded execution
|
/// Deshielded execution
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
Deshielded(TokenProgramSubcommandDeshielded),
|
Deshielded(TokenProgramSubcommandDeshielded),
|
||||||
///Shielded execution
|
/// Shielded execution
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
Shielded(TokenProgramSubcommandShielded),
|
Shielded(TokenProgramSubcommandShielded),
|
||||||
}
|
}
|
||||||
|
|
||||||
///Represents generic public CLI subcommand for a wallet working with token_program
|
/// Represents generic public CLI subcommand for a wallet working with token_program
|
||||||
#[derive(Subcommand, Debug, Clone)]
|
#[derive(Subcommand, Debug, Clone)]
|
||||||
pub enum TokenProgramSubcommandPublic {
|
pub enum TokenProgramSubcommandPublic {
|
||||||
//Create a new token using the token program
|
// Create a new token using the token program
|
||||||
CreateNewToken {
|
CreateNewToken {
|
||||||
#[arg(short, long)]
|
#[arg(short, long)]
|
||||||
definition_account_id: String,
|
definition_account_id: String,
|
||||||
@ -226,7 +229,7 @@ pub enum TokenProgramSubcommandPublic {
|
|||||||
#[arg(short, long)]
|
#[arg(short, long)]
|
||||||
total_supply: u128,
|
total_supply: u128,
|
||||||
},
|
},
|
||||||
//Transfer tokens using the token program
|
// Transfer tokens using the token program
|
||||||
TransferToken {
|
TransferToken {
|
||||||
#[arg(short, long)]
|
#[arg(short, long)]
|
||||||
sender_account_id: String,
|
sender_account_id: String,
|
||||||
@ -237,10 +240,10 @@ pub enum TokenProgramSubcommandPublic {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
///Represents generic private CLI subcommand for a wallet working with token_program
|
/// Represents generic private CLI subcommand for a wallet working with token_program
|
||||||
#[derive(Subcommand, Debug, Clone)]
|
#[derive(Subcommand, Debug, Clone)]
|
||||||
pub enum TokenProgramSubcommandPrivate {
|
pub enum TokenProgramSubcommandPrivate {
|
||||||
//Create a new token using the token program
|
// Create a new token using the token program
|
||||||
CreateNewTokenPrivateOwned {
|
CreateNewTokenPrivateOwned {
|
||||||
#[arg(short, long)]
|
#[arg(short, long)]
|
||||||
definition_account_id: String,
|
definition_account_id: String,
|
||||||
@ -251,7 +254,7 @@ pub enum TokenProgramSubcommandPrivate {
|
|||||||
#[arg(short, long)]
|
#[arg(short, long)]
|
||||||
total_supply: u128,
|
total_supply: u128,
|
||||||
},
|
},
|
||||||
//Transfer tokens using the token program
|
// Transfer tokens using the token program
|
||||||
TransferTokenPrivateOwned {
|
TransferTokenPrivateOwned {
|
||||||
#[arg(short, long)]
|
#[arg(short, long)]
|
||||||
sender_account_id: String,
|
sender_account_id: String,
|
||||||
@ -260,14 +263,14 @@ pub enum TokenProgramSubcommandPrivate {
|
|||||||
#[arg(short, long)]
|
#[arg(short, long)]
|
||||||
balance_to_move: u128,
|
balance_to_move: u128,
|
||||||
},
|
},
|
||||||
//Transfer tokens using the token program
|
// Transfer tokens using the token program
|
||||||
TransferTokenPrivateForeign {
|
TransferTokenPrivateForeign {
|
||||||
#[arg(short, long)]
|
#[arg(short, long)]
|
||||||
sender_account_id: String,
|
sender_account_id: String,
|
||||||
///recipient_npk - valid 32 byte hex string
|
/// recipient_npk - valid 32 byte hex string
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
recipient_npk: String,
|
recipient_npk: String,
|
||||||
///recipient_ipk - valid 33 byte hex string
|
/// recipient_ipk - valid 33 byte hex string
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
recipient_ipk: String,
|
recipient_ipk: String,
|
||||||
#[arg(short, long)]
|
#[arg(short, long)]
|
||||||
@ -275,10 +278,10 @@ pub enum TokenProgramSubcommandPrivate {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
///Represents deshielded public CLI subcommand for a wallet working with token_program
|
/// Represents deshielded public CLI subcommand for a wallet working with token_program
|
||||||
#[derive(Subcommand, Debug, Clone)]
|
#[derive(Subcommand, Debug, Clone)]
|
||||||
pub enum TokenProgramSubcommandDeshielded {
|
pub enum TokenProgramSubcommandDeshielded {
|
||||||
//Transfer tokens using the token program
|
// Transfer tokens using the token program
|
||||||
TransferTokenDeshielded {
|
TransferTokenDeshielded {
|
||||||
#[arg(short, long)]
|
#[arg(short, long)]
|
||||||
sender_account_id: String,
|
sender_account_id: String,
|
||||||
@ -289,10 +292,10 @@ pub enum TokenProgramSubcommandDeshielded {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
///Represents generic shielded CLI subcommand for a wallet working with token_program
|
/// Represents generic shielded CLI subcommand for a wallet working with token_program
|
||||||
#[derive(Subcommand, Debug, Clone)]
|
#[derive(Subcommand, Debug, Clone)]
|
||||||
pub enum TokenProgramSubcommandShielded {
|
pub enum TokenProgramSubcommandShielded {
|
||||||
//Transfer tokens using the token program
|
// Transfer tokens using the token program
|
||||||
TransferTokenShieldedOwned {
|
TransferTokenShieldedOwned {
|
||||||
#[arg(short, long)]
|
#[arg(short, long)]
|
||||||
sender_account_id: String,
|
sender_account_id: String,
|
||||||
@ -301,14 +304,14 @@ pub enum TokenProgramSubcommandShielded {
|
|||||||
#[arg(short, long)]
|
#[arg(short, long)]
|
||||||
balance_to_move: u128,
|
balance_to_move: u128,
|
||||||
},
|
},
|
||||||
//Transfer tokens using the token program
|
// Transfer tokens using the token program
|
||||||
TransferTokenShieldedForeign {
|
TransferTokenShieldedForeign {
|
||||||
#[arg(short, long)]
|
#[arg(short, long)]
|
||||||
sender_account_id: String,
|
sender_account_id: String,
|
||||||
///recipient_npk - valid 32 byte hex string
|
/// recipient_npk - valid 32 byte hex string
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
recipient_npk: String,
|
recipient_npk: String,
|
||||||
///recipient_ipk - valid 33 byte hex string
|
/// recipient_ipk - valid 33 byte hex string
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
recipient_ipk: String,
|
recipient_ipk: String,
|
||||||
#[arg(short, long)]
|
#[arg(short, long)]
|
||||||
|
|||||||
@ -27,8 +27,9 @@ pub struct PersistentAccountDataPrivate {
|
|||||||
pub key_chain: KeyChain,
|
pub key_chain: KeyChain,
|
||||||
}
|
}
|
||||||
|
|
||||||
//Big difference in enum variants sizes
|
// Big difference in enum variants sizes
|
||||||
//however it is improbable, that we will have that much accounts, that it will substantialy affect memory
|
// however it is improbable, that we will have that much accounts, that it will substantialy affect
|
||||||
|
// memory
|
||||||
#[allow(clippy::large_enum_variant)]
|
#[allow(clippy::large_enum_variant)]
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub enum InitialAccountData {
|
pub enum InitialAccountData {
|
||||||
@ -36,8 +37,9 @@ pub enum InitialAccountData {
|
|||||||
Private(InitialAccountDataPrivate),
|
Private(InitialAccountDataPrivate),
|
||||||
}
|
}
|
||||||
|
|
||||||
//Big difference in enum variants sizes
|
// Big difference in enum variants sizes
|
||||||
//however it is improbable, that we will have that much accounts, that it will substantialy affect memory
|
// however it is improbable, that we will have that much accounts, that it will substantialy affect
|
||||||
|
// memory
|
||||||
#[allow(clippy::large_enum_variant)]
|
#[allow(clippy::large_enum_variant)]
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub enum PersistentAccountData {
|
pub enum PersistentAccountData {
|
||||||
@ -113,19 +115,19 @@ pub struct GasConfig {
|
|||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct WalletConfig {
|
pub struct WalletConfig {
|
||||||
///Override rust log (env var logging level)
|
/// Override rust log (env var logging level)
|
||||||
pub override_rust_log: Option<String>,
|
pub override_rust_log: Option<String>,
|
||||||
///Sequencer URL
|
/// Sequencer URL
|
||||||
pub sequencer_addr: String,
|
pub sequencer_addr: String,
|
||||||
///Sequencer polling duration for new blocks in milliseconds
|
/// Sequencer polling duration for new blocks in milliseconds
|
||||||
pub seq_poll_timeout_millis: u64,
|
pub seq_poll_timeout_millis: u64,
|
||||||
///Sequencer polling max number of blocks
|
/// Sequencer polling max number of blocks
|
||||||
pub seq_poll_max_blocks: usize,
|
pub seq_poll_max_blocks: usize,
|
||||||
///Sequencer polling max number error retries
|
/// Sequencer polling max number error retries
|
||||||
pub seq_poll_max_retries: u64,
|
pub seq_poll_max_retries: u64,
|
||||||
///Sequencer polling error retry delay in milliseconds
|
/// Sequencer polling error retry delay in milliseconds
|
||||||
pub seq_poll_retry_delay_millis: u64,
|
pub seq_poll_retry_delay_millis: u64,
|
||||||
///Initial accounts for wallet
|
/// Initial accounts for wallet
|
||||||
pub initial_accounts: Vec<InitialAccountData>,
|
pub initial_accounts: Vec<InitialAccountData>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -1,13 +1,13 @@
|
|||||||
use base64::{Engine, engine::general_purpose::STANDARD as BASE64};
|
|
||||||
use nssa_core::account::Nonce;
|
|
||||||
use rand::{RngCore, rngs::OsRng};
|
|
||||||
use std::{path::PathBuf, str::FromStr};
|
use std::{path::PathBuf, str::FromStr};
|
||||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
|
||||||
|
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
|
use base64::{Engine, engine::general_purpose::STANDARD as BASE64};
|
||||||
use key_protocol::key_protocol_core::NSSAUserData;
|
use key_protocol::key_protocol_core::NSSAUserData;
|
||||||
use nssa::Account;
|
use nssa::Account;
|
||||||
|
use nssa_core::account::Nonce;
|
||||||
|
use rand::{RngCore, rngs::OsRng};
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
HOME_DIR_ENV_VAR,
|
HOME_DIR_ENV_VAR,
|
||||||
|
|||||||
@ -1,22 +1,20 @@
|
|||||||
use std::{path::PathBuf, sync::Arc};
|
use std::{path::PathBuf, sync::Arc};
|
||||||
|
|
||||||
|
use anyhow::Result;
|
||||||
use base64::{Engine, engine::general_purpose::STANDARD as BASE64};
|
use base64::{Engine, engine::general_purpose::STANDARD as BASE64};
|
||||||
|
use chain_storage::WalletChainStore;
|
||||||
|
use clap::{Parser, Subcommand};
|
||||||
use common::{
|
use common::{
|
||||||
block::HashableBlockData,
|
block::HashableBlockData,
|
||||||
sequencer_client::SequencerClient,
|
sequencer_client::SequencerClient,
|
||||||
transaction::{EncodedTransaction, NSSATransaction},
|
transaction::{EncodedTransaction, NSSATransaction},
|
||||||
};
|
};
|
||||||
|
|
||||||
use anyhow::Result;
|
|
||||||
use chain_storage::WalletChainStore;
|
|
||||||
use config::WalletConfig;
|
use config::WalletConfig;
|
||||||
use log::info;
|
use log::info;
|
||||||
use nssa::{
|
use nssa::{
|
||||||
Account, AccountId, privacy_preserving_transaction::message::EncryptedAccountData,
|
Account, AccountId, privacy_preserving_transaction::message::EncryptedAccountData,
|
||||||
program::Program,
|
program::Program,
|
||||||
};
|
};
|
||||||
|
|
||||||
use clap::{Parser, Subcommand};
|
|
||||||
use nssa_core::{Commitment, MembershipProof};
|
use nssa_core::{Commitment, MembershipProof};
|
||||||
use tokio::io::AsyncWriteExt;
|
use tokio::io::AsyncWriteExt;
|
||||||
|
|
||||||
@ -28,10 +26,7 @@ use crate::{
|
|||||||
token_program::TokenProgramAgnosticSubcommand,
|
token_program::TokenProgramAgnosticSubcommand,
|
||||||
},
|
},
|
||||||
config::PersistentStorage,
|
config::PersistentStorage,
|
||||||
helperfunctions::fetch_persistent_storage,
|
helperfunctions::{fetch_config, fetch_persistent_storage, get_home, produce_data_for_storage},
|
||||||
};
|
|
||||||
use crate::{
|
|
||||||
helperfunctions::{fetch_config, get_home, produce_data_for_storage},
|
|
||||||
poller::TxPoller,
|
poller::TxPoller,
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -77,7 +72,7 @@ impl WalletCore {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
///Store persistent data at home
|
/// Store persistent data at home
|
||||||
pub async fn store_persistent_data(&self) -> Result<PathBuf> {
|
pub async fn store_persistent_data(&self) -> Result<PathBuf> {
|
||||||
let home = get_home()?;
|
let home = get_home()?;
|
||||||
let storage_path = home.join("storage.json");
|
let storage_path = home.join("storage.json");
|
||||||
@ -93,7 +88,7 @@ impl WalletCore {
|
|||||||
Ok(storage_path)
|
Ok(storage_path)
|
||||||
}
|
}
|
||||||
|
|
||||||
///Store persistent data at home
|
/// Store persistent data at home
|
||||||
pub async fn store_config_changes(&self) -> Result<PathBuf> {
|
pub async fn store_config_changes(&self) -> Result<PathBuf> {
|
||||||
let home = get_home()?;
|
let home = get_home()?;
|
||||||
let config_path = home.join("wallet_config.json");
|
let config_path = home.join("wallet_config.json");
|
||||||
@ -119,7 +114,7 @@ impl WalletCore {
|
|||||||
.generate_new_privacy_preserving_transaction_key_chain()
|
.generate_new_privacy_preserving_transaction_key_chain()
|
||||||
}
|
}
|
||||||
|
|
||||||
///Get account balance
|
/// Get account balance
|
||||||
pub async fn get_account_balance(&self, acc: AccountId) -> Result<u128> {
|
pub async fn get_account_balance(&self, acc: AccountId) -> Result<u128> {
|
||||||
Ok(self
|
Ok(self
|
||||||
.sequencer_client
|
.sequencer_client
|
||||||
@ -128,7 +123,7 @@ impl WalletCore {
|
|||||||
.balance)
|
.balance)
|
||||||
}
|
}
|
||||||
|
|
||||||
///Get accounts nonces
|
/// Get accounts nonces
|
||||||
pub async fn get_accounts_nonces(&self, accs: Vec<AccountId>) -> Result<Vec<u128>> {
|
pub async fn get_accounts_nonces(&self, accs: Vec<AccountId>) -> Result<Vec<u128>> {
|
||||||
Ok(self
|
Ok(self
|
||||||
.sequencer_client
|
.sequencer_client
|
||||||
@ -137,7 +132,7 @@ impl WalletCore {
|
|||||||
.nonces)
|
.nonces)
|
||||||
}
|
}
|
||||||
|
|
||||||
///Get account
|
/// Get account
|
||||||
pub async fn get_account_public(&self, account_id: AccountId) -> Result<Account> {
|
pub async fn get_account_public(&self, account_id: AccountId) -> Result<Account> {
|
||||||
let response = self
|
let response = self
|
||||||
.sequencer_client
|
.sequencer_client
|
||||||
@ -163,7 +158,7 @@ impl WalletCore {
|
|||||||
Some(Commitment::new(&keys.nullifer_public_key, account))
|
Some(Commitment::new(&keys.nullifer_public_key, account))
|
||||||
}
|
}
|
||||||
|
|
||||||
///Poll transactions
|
/// Poll transactions
|
||||||
pub async fn poll_native_token_transfer(&self, hash: String) -> Result<NSSATransaction> {
|
pub async fn poll_native_token_transfer(&self, hash: String) -> Result<NSSATransaction> {
|
||||||
let transaction_encoded = self.poller.poll_tx(hash).await?;
|
let transaction_encoded = self.poller.poll_tx(hash).await?;
|
||||||
let tx_base64_decode = BASE64.decode(transaction_encoded)?;
|
let tx_base64_decode = BASE64.decode(transaction_encoded)?;
|
||||||
@ -215,23 +210,23 @@ impl WalletCore {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
///Represents CLI command for a wallet
|
/// Represents CLI command for a wallet
|
||||||
#[derive(Subcommand, Debug, Clone)]
|
#[derive(Subcommand, Debug, Clone)]
|
||||||
#[clap(about)]
|
#[clap(about)]
|
||||||
pub enum Command {
|
pub enum Command {
|
||||||
///Authenticated transfer subcommand
|
/// Authenticated transfer subcommand
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
AuthTransfer(AuthTransferSubcommand),
|
AuthTransfer(AuthTransferSubcommand),
|
||||||
///Generic chain info subcommand
|
/// Generic chain info subcommand
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
ChainInfo(ChainSubcommand),
|
ChainInfo(ChainSubcommand),
|
||||||
///Account view and sync subcommand
|
/// Account view and sync subcommand
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
Account(AccountSubcommand),
|
Account(AccountSubcommand),
|
||||||
///Pinata program interaction subcommand
|
/// Pinata program interaction subcommand
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
Pinata(PinataProgramAgnosticSubcommand),
|
Pinata(PinataProgramAgnosticSubcommand),
|
||||||
///Token program interaction subcommand
|
/// Token program interaction subcommand
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
Token(TokenProgramAgnosticSubcommand),
|
Token(TokenProgramAgnosticSubcommand),
|
||||||
/// Check the wallet can connect to the node and builtin local programs
|
/// Check the wallet can connect to the node and builtin local programs
|
||||||
@ -242,7 +237,7 @@ pub enum Command {
|
|||||||
Config(ConfigSubcommand),
|
Config(ConfigSubcommand),
|
||||||
}
|
}
|
||||||
|
|
||||||
///To execute commands, env var NSSA_WALLET_HOME_DIR must be set into directory with config
|
/// To execute commands, env var NSSA_WALLET_HOME_DIR must be set into directory with config
|
||||||
///
|
///
|
||||||
/// All account adresses must be valid 32 byte base58 strings.
|
/// All account adresses must be valid 32 byte base58 strings.
|
||||||
///
|
///
|
||||||
|
|||||||
@ -6,9 +6,9 @@ use wallet::{Args, execute_continious_run, execute_subcommand};
|
|||||||
pub const NUM_THREADS: usize = 2;
|
pub const NUM_THREADS: usize = 2;
|
||||||
|
|
||||||
// TODO #169: We have sample configs for sequencer, but not for wallet
|
// TODO #169: We have sample configs for sequencer, but not for wallet
|
||||||
// TODO #168: Why it requires config as a directory? Maybe better to deduce directory from config file path?
|
// TODO #168: Why it requires config as a directory? Maybe better to deduce directory from config
|
||||||
// TODO #172: Why it requires config as env var while sequencer_runner accepts as argument?
|
// file path? TODO #172: Why it requires config as env var while sequencer_runner accepts as
|
||||||
// TODO #171: Running pinata doesn't give output about transaction hash and etc.
|
// argument? TODO #171: Running pinata doesn't give output about transaction hash and etc.
|
||||||
fn main() -> Result<()> {
|
fn main() -> Result<()> {
|
||||||
let runtime = Builder::new_multi_thread()
|
let runtime = Builder::new_multi_thread()
|
||||||
.worker_threads(NUM_THREADS)
|
.worker_threads(NUM_THREADS)
|
||||||
|
|||||||
@ -7,7 +7,7 @@ use log::{info, warn};
|
|||||||
use crate::config::WalletConfig;
|
use crate::config::WalletConfig;
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
///Helperstruct to poll transactions
|
/// Helperstruct to poll transactions
|
||||||
pub struct TxPoller {
|
pub struct TxPoller {
|
||||||
pub polling_max_blocks_to_query: usize,
|
pub polling_max_blocks_to_query: usize,
|
||||||
pub polling_max_error_attempts: u64,
|
pub polling_max_error_attempts: u64,
|
||||||
|
|||||||
@ -15,7 +15,8 @@ impl WalletCore {
|
|||||||
Program,
|
Program,
|
||||||
impl FnOnce(&Account, &Account) -> Result<(), ExecutionFailureKind>,
|
impl FnOnce(&Account, &Account) -> Result<(), ExecutionFailureKind>,
|
||||||
) {
|
) {
|
||||||
// Instruction must be: [0x01 || amount (little-endian 16 bytes) || 0x00 || 0x00 || 0x00 || 0x00 || 0x00 || 0x00].
|
// Instruction must be: [0x01 || amount (little-endian 16 bytes) || 0x00 || 0x00 || 0x00 ||
|
||||||
|
// 0x00 || 0x00 || 0x00].
|
||||||
let mut instruction = [0; 23];
|
let mut instruction = [0; 23];
|
||||||
instruction[0] = 0x01;
|
instruction[0] = 0x01;
|
||||||
instruction[1..17].copy_from_slice(&amount.to_le_bytes());
|
instruction[1..17].copy_from_slice(&amount.to_le_bytes());
|
||||||
@ -103,7 +104,8 @@ impl WalletCore {
|
|||||||
) -> Result<SendTxResponse, ExecutionFailureKind> {
|
) -> Result<SendTxResponse, ExecutionFailureKind> {
|
||||||
let account_ids = vec![sender_account_id, recipient_account_id];
|
let account_ids = vec![sender_account_id, recipient_account_id];
|
||||||
let program_id = nssa::program::Program::token().id();
|
let program_id = nssa::program::Program::token().id();
|
||||||
// Instruction must be: [0x01 || amount (little-endian 16 bytes) || 0x00 || 0x00 || 0x00 || 0x00 || 0x00 || 0x00].
|
// Instruction must be: [0x01 || amount (little-endian 16 bytes) || 0x00 || 0x00 || 0x00 ||
|
||||||
|
// 0x00 || 0x00 || 0x00].
|
||||||
let mut instruction = [0; 23];
|
let mut instruction = [0; 23];
|
||||||
instruction[0] = 0x01;
|
instruction[0] = 0x01;
|
||||||
instruction[1..17].copy_from_slice(&amount.to_le_bytes());
|
instruction[1..17].copy_from_slice(&amount.to_le_bytes());
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user