mirror of
https://github.com/logos-blockchain/lssa.git
synced 2026-03-18 18:03:07 +00:00
feat: add nursery clippy lints
This commit is contained in:
parent
e3b93b6e9a
commit
aa462b66eb
@ -248,3 +248,11 @@ clippy.let-underscore-untyped = "allow"
|
||||
# Reason: this lint is actually bad as it forces to use wildcard `..` instead of
|
||||
# field-by-field `_` which may lead to subtle bugs when new fields are added to the struct.
|
||||
clippy.unneeded-field-pattern = "allow"
|
||||
|
||||
# Nursery
|
||||
clippy.nursery = { level = "deny", priority = -1 }
|
||||
|
||||
# Reason: this is okay if it compiles.
|
||||
clippy.future-not-send = "allow"
|
||||
# Reason: this is actually a good lint, but currently it gives a lot of false-positives.
|
||||
clippy.significant-drop-tightening = "allow"
|
||||
|
||||
@ -50,6 +50,6 @@ impl FromStr for BasicAuth {
|
||||
|
||||
impl From<BasicAuth> for BasicAuthCredentials {
|
||||
fn from(value: BasicAuth) -> Self {
|
||||
BasicAuthCredentials::new(value.username, value.password)
|
||||
Self::new(value.username, value.password)
|
||||
}
|
||||
}
|
||||
|
||||
@ -22,7 +22,7 @@ pub enum SequencerClientError {
|
||||
|
||||
impl From<SequencerRpcError> for SequencerClientError {
|
||||
fn from(value: SequencerRpcError) -> Self {
|
||||
SequencerClientError::InternalError(value)
|
||||
Self::InternalError(value)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -48,7 +48,7 @@ impl FromStr for HashType {
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
let mut bytes = [0_u8; 32];
|
||||
hex::decode_to_slice(s, &mut bytes)?;
|
||||
Ok(HashType(bytes))
|
||||
Ok(Self(bytes))
|
||||
}
|
||||
}
|
||||
|
||||
@ -66,7 +66,7 @@ impl From<HashType> for [u8; 32] {
|
||||
|
||||
impl From<[u8; 32]> for HashType {
|
||||
fn from(bytes: [u8; 32]) -> Self {
|
||||
HashType(bytes)
|
||||
Self(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
@ -74,7 +74,7 @@ impl TryFrom<Vec<u8>> for HashType {
|
||||
type Error = <[u8; 32] as TryFrom<Vec<u8>>>::Error;
|
||||
|
||||
fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
|
||||
Ok(HashType(value.try_into()?))
|
||||
Ok(Self(value.try_into()?))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -9,7 +9,7 @@ pub struct RpcParseError(pub String);
|
||||
///
|
||||
/// It is expected that that this struct has impls From<_> all other RPC errors
|
||||
/// like [`RpcBlockError`](crate::types::blocks::RpcBlockError).
|
||||
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq)]
|
||||
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq, Eq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct RpcError {
|
||||
#[serde(flatten)]
|
||||
@ -23,7 +23,7 @@ pub struct RpcError {
|
||||
pub data: Option<Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq)]
|
||||
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq, Eq)]
|
||||
#[serde(tag = "name", content = "cause", rename_all = "SCREAMING_SNAKE_CASE")]
|
||||
pub enum RpcErrorKind {
|
||||
RequestValidationError(RpcRequestValidationErrorKind),
|
||||
@ -31,7 +31,7 @@ pub enum RpcErrorKind {
|
||||
InternalError(Value),
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq)]
|
||||
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq, Eq)]
|
||||
#[serde(tag = "name", content = "info", rename_all = "SCREAMING_SNAKE_CASE")]
|
||||
pub enum RpcRequestValidationErrorKind {
|
||||
MethodNotFound { method_name: String },
|
||||
@ -50,8 +50,8 @@ impl RpcError {
|
||||
///
|
||||
/// Mostly for completeness, doesn't do anything but filling in the corresponding fields.
|
||||
#[must_use]
|
||||
pub fn new(code: i64, message: String, data: Option<Value>) -> Self {
|
||||
RpcError {
|
||||
pub const fn new(code: i64, message: String, data: Option<Value>) -> Self {
|
||||
Self {
|
||||
code,
|
||||
message,
|
||||
data,
|
||||
@ -70,12 +70,12 @@ impl RpcError {
|
||||
)));
|
||||
}
|
||||
};
|
||||
RpcError::new(-32_602, "Invalid params".to_owned(), Some(value))
|
||||
Self::new(-32_602, "Invalid params".to_owned(), Some(value))
|
||||
}
|
||||
|
||||
/// Create a server error.
|
||||
pub fn server_error<E: serde::Serialize>(e: Option<E>) -> Self {
|
||||
RpcError::new(
|
||||
Self::new(
|
||||
-32_000,
|
||||
"Server error".to_owned(),
|
||||
e.map(|v| to_value(v).expect("Must be representable in JSON")),
|
||||
@ -85,7 +85,7 @@ impl RpcError {
|
||||
/// Create a parse error.
|
||||
#[must_use]
|
||||
pub fn parse_error(e: String) -> Self {
|
||||
RpcError {
|
||||
Self {
|
||||
code: -32_700,
|
||||
message: "Parse error".to_owned(),
|
||||
data: Some(Value::String(e.clone())),
|
||||
@ -97,7 +97,7 @@ impl RpcError {
|
||||
|
||||
#[must_use]
|
||||
pub fn serialization_error(e: &str) -> Self {
|
||||
RpcError::new_internal_error(Some(Value::String(e.to_owned())), e)
|
||||
Self::new_internal_error(Some(Value::String(e.to_owned())), e)
|
||||
}
|
||||
|
||||
/// Helper method to define extract `INTERNAL_ERROR` in separate `RpcErrorKind`
|
||||
@ -117,7 +117,7 @@ impl RpcError {
|
||||
|
||||
#[must_use]
|
||||
pub fn new_internal_error(error_data: Option<Value>, info: &str) -> Self {
|
||||
RpcError {
|
||||
Self {
|
||||
code: -32_000,
|
||||
message: "Server error".to_owned(),
|
||||
data: error_data,
|
||||
@ -129,7 +129,7 @@ impl RpcError {
|
||||
}
|
||||
|
||||
fn new_handler_error(error_data: Option<Value>, error_struct: Value) -> Self {
|
||||
RpcError {
|
||||
Self {
|
||||
code: -32_000,
|
||||
message: "Server error".to_owned(),
|
||||
data: error_data,
|
||||
@ -140,7 +140,7 @@ impl RpcError {
|
||||
/// Create a method not found error.
|
||||
#[must_use]
|
||||
pub fn method_not_found(method: String) -> Self {
|
||||
RpcError {
|
||||
Self {
|
||||
code: -32_601,
|
||||
message: "Method not found".to_owned(),
|
||||
data: Some(Value::String(method.clone())),
|
||||
@ -175,20 +175,20 @@ impl From<std::convert::Infallible> for RpcError {
|
||||
impl fmt::Display for ServerError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
ServerError::Timeout => write!(f, "ServerError: Timeout"),
|
||||
ServerError::Closed => write!(f, "ServerError: Closed"),
|
||||
Self::Timeout => write!(f, "ServerError: Timeout"),
|
||||
Self::Closed => write!(f, "ServerError: Closed"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ServerError> for RpcError {
|
||||
fn from(e: ServerError) -> RpcError {
|
||||
fn from(e: ServerError) -> Self {
|
||||
let error_data = match to_value(&e) {
|
||||
Ok(value) => value,
|
||||
Err(_err) => {
|
||||
return RpcError::new_internal_error(None, "Failed to serialize ServerError");
|
||||
return Self::new_internal_error(None, "Failed to serialize ServerError");
|
||||
}
|
||||
};
|
||||
RpcError::new_internal_error(Some(error_data), e.to_string().as_str())
|
||||
Self::new_internal_error(Some(error_data), e.to_string().as_str())
|
||||
}
|
||||
}
|
||||
|
||||
@ -56,7 +56,7 @@ impl<'de> serde::Deserialize<'de> for Version {
|
||||
}
|
||||
|
||||
/// An RPC request.
|
||||
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq)]
|
||||
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq, Eq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
#[expect(
|
||||
clippy::partial_pub_fields,
|
||||
@ -112,7 +112,7 @@ impl Request {
|
||||
clippy::partial_pub_fields,
|
||||
reason = "We don't want to allow access to the version, but the others are public for ease of use"
|
||||
)]
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Response {
|
||||
jsonrpc: Version,
|
||||
pub result: Result<Value, RpcError>,
|
||||
@ -160,7 +160,7 @@ impl<'de> serde::Deserialize<'de> for Response {
|
||||
return Err(err);
|
||||
}
|
||||
};
|
||||
Ok(Response {
|
||||
Ok(Self {
|
||||
jsonrpc: Version,
|
||||
result,
|
||||
id: wr.id,
|
||||
@ -173,7 +173,7 @@ impl<'de> serde::Deserialize<'de> for Response {
|
||||
clippy::partial_pub_fields,
|
||||
reason = "We don't want to allow access to the version, but the others are public for ease of use"
|
||||
)]
|
||||
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq)]
|
||||
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq, Eq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Notification {
|
||||
jsonrpc: Version,
|
||||
@ -227,7 +227,7 @@ impl Message {
|
||||
#[must_use]
|
||||
pub fn request(method: String, params: Value) -> Self {
|
||||
let id = Value::from("dontcare");
|
||||
Message::Request(Request {
|
||||
Self::Request(Request {
|
||||
jsonrpc: Version,
|
||||
method,
|
||||
params,
|
||||
@ -237,8 +237,8 @@ impl Message {
|
||||
|
||||
/// Create a top-level error (without an ID).
|
||||
#[must_use]
|
||||
pub fn error(error: RpcError) -> Self {
|
||||
Message::Response(Response {
|
||||
pub const fn error(error: RpcError) -> Self {
|
||||
Self::Response(Response {
|
||||
jsonrpc: Version,
|
||||
result: Err(error),
|
||||
id: Value::Null,
|
||||
@ -247,8 +247,8 @@ impl Message {
|
||||
|
||||
/// A constructor for a notification.
|
||||
#[must_use]
|
||||
pub fn notification(method: String, params: Value) -> Self {
|
||||
Message::Notification(Notification {
|
||||
pub const fn notification(method: String, params: Value) -> Self {
|
||||
Self::Notification(Notification {
|
||||
jsonrpc: Version,
|
||||
method,
|
||||
params,
|
||||
@ -257,8 +257,8 @@ impl Message {
|
||||
|
||||
/// A constructor for a response.
|
||||
#[must_use]
|
||||
pub fn response(id: Value, result: Result<Value, RpcError>) -> Self {
|
||||
Message::Response(Response {
|
||||
pub const fn response(id: Value, result: Result<Value, RpcError>) -> Self {
|
||||
Self::Response(Response {
|
||||
jsonrpc: Version,
|
||||
result,
|
||||
id,
|
||||
@ -269,29 +269,30 @@ impl Message {
|
||||
#[must_use]
|
||||
pub fn id(&self) -> Value {
|
||||
match self {
|
||||
Message::Request(req) => req.id.clone(),
|
||||
Message::Response(response) => response.id.clone(),
|
||||
Message::Notification(_) | Message::Batch(_) | Message::UnmatchedSub(_) => Value::Null,
|
||||
Self::Request(req) => req.id.clone(),
|
||||
Self::Response(response) => response.id.clone(),
|
||||
Self::Notification(_) | Self::Batch(_) | Self::UnmatchedSub(_) => Value::Null,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Message> for String {
|
||||
fn from(val: Message) -> Self {
|
||||
::serde_json::ser::to_string(&val).unwrap()
|
||||
::serde_json::ser::to_string(&val).expect("message serialization to json should not fail")
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Message> for Vec<u8> {
|
||||
fn from(val: Message) -> Self {
|
||||
::serde_json::ser::to_vec(&val).unwrap()
|
||||
::serde_json::ser::to_vec(&val)
|
||||
.expect("message serialization to json bytes should not fail")
|
||||
}
|
||||
}
|
||||
|
||||
/// A broken message.
|
||||
///
|
||||
/// Protocol-level errors.
|
||||
#[derive(Debug, Clone, PartialEq, serde::Deserialize)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
|
||||
#[serde(untagged)]
|
||||
pub enum Broken {
|
||||
/// It was valid JSON, but doesn't match the form of a JSONRPC 2.0 message.
|
||||
@ -309,10 +310,10 @@ impl Broken {
|
||||
#[must_use]
|
||||
pub fn reply(&self) -> Message {
|
||||
match self {
|
||||
Broken::Unmatched(_) => Message::error(RpcError::parse_error(
|
||||
Self::Unmatched(_) => Message::error(RpcError::parse_error(
|
||||
"JSON RPC Request format was expected".to_owned(),
|
||||
)),
|
||||
Broken::SyntaxError(e) => Message::error(RpcError::parse_error(e.clone())),
|
||||
Self::SyntaxError(e) => Message::error(RpcError::parse_error(e.clone())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -30,7 +30,7 @@ pub struct RpcConfig {
|
||||
|
||||
impl Default for RpcConfig {
|
||||
fn default() -> Self {
|
||||
RpcConfig {
|
||||
Self {
|
||||
addr: "0.0.0.0:3040".to_owned(),
|
||||
cors_allowed_origins: vec!["*".to_owned()],
|
||||
limits_config: RpcLimitsConfig::default(),
|
||||
@ -41,7 +41,7 @@ impl Default for RpcConfig {
|
||||
impl RpcConfig {
|
||||
#[must_use]
|
||||
pub fn new(addr: &str) -> Self {
|
||||
RpcConfig {
|
||||
Self {
|
||||
addr: addr.to_owned(),
|
||||
..Default::default()
|
||||
}
|
||||
@ -49,7 +49,7 @@ impl RpcConfig {
|
||||
|
||||
#[must_use]
|
||||
pub fn with_port(port: u16) -> Self {
|
||||
RpcConfig {
|
||||
Self {
|
||||
addr: format!("0.0.0.0:{port}"),
|
||||
..Default::default()
|
||||
}
|
||||
|
||||
@ -19,10 +19,11 @@ pub trait RpcRequest: Sized {
|
||||
}
|
||||
|
||||
pub fn parse_params<T: DeserializeOwned>(value: Option<Value>) -> Result<T, RpcParseError> {
|
||||
if let Some(value) = value {
|
||||
serde_json::from_value(value)
|
||||
.map_err(|err| RpcParseError(format!("Failed parsing args: {err}")))
|
||||
} else {
|
||||
Err(RpcParseError("Require at least one parameter".to_owned()))
|
||||
}
|
||||
value.map_or_else(
|
||||
|| Err(RpcParseError("Require at least one parameter".to_owned())),
|
||||
|value| {
|
||||
serde_json::from_value(value)
|
||||
.map_err(|err| RpcParseError(format!("Failed parsing args: {err}")))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@ -16,18 +16,18 @@ impl NSSATransaction {
|
||||
#[must_use]
|
||||
pub fn hash(&self) -> HashType {
|
||||
HashType(match self {
|
||||
NSSATransaction::Public(tx) => tx.hash(),
|
||||
NSSATransaction::PrivacyPreserving(tx) => tx.hash(),
|
||||
NSSATransaction::ProgramDeployment(tx) => tx.hash(),
|
||||
Self::Public(tx) => tx.hash(),
|
||||
Self::PrivacyPreserving(tx) => tx.hash(),
|
||||
Self::ProgramDeployment(tx) => tx.hash(),
|
||||
})
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn affected_public_account_ids(&self) -> Vec<AccountId> {
|
||||
match self {
|
||||
NSSATransaction::ProgramDeployment(tx) => tx.affected_public_account_ids(),
|
||||
NSSATransaction::Public(tx) => tx.affected_public_account_ids(),
|
||||
NSSATransaction::PrivacyPreserving(tx) => tx.affected_public_account_ids(),
|
||||
Self::ProgramDeployment(tx) => tx.affected_public_account_ids(),
|
||||
Self::Public(tx) => tx.affected_public_account_ids(),
|
||||
Self::PrivacyPreserving(tx) => tx.affected_public_account_ids(),
|
||||
}
|
||||
}
|
||||
|
||||
@ -35,21 +35,21 @@ impl NSSATransaction {
|
||||
pub fn transaction_stateless_check(self) -> Result<Self, TransactionMalformationError> {
|
||||
// Stateless checks here
|
||||
match self {
|
||||
NSSATransaction::Public(tx) => {
|
||||
Self::Public(tx) => {
|
||||
if tx.witness_set().is_valid_for(tx.message()) {
|
||||
Ok(NSSATransaction::Public(tx))
|
||||
Ok(Self::Public(tx))
|
||||
} else {
|
||||
Err(TransactionMalformationError::InvalidSignature)
|
||||
}
|
||||
}
|
||||
NSSATransaction::PrivacyPreserving(tx) => {
|
||||
Self::PrivacyPreserving(tx) => {
|
||||
if tx.witness_set().signatures_are_valid_for(tx.message()) {
|
||||
Ok(NSSATransaction::PrivacyPreserving(tx))
|
||||
Ok(Self::PrivacyPreserving(tx))
|
||||
} else {
|
||||
Err(TransactionMalformationError::InvalidSignature)
|
||||
}
|
||||
}
|
||||
NSSATransaction::ProgramDeployment(tx) => Ok(NSSATransaction::ProgramDeployment(tx)),
|
||||
Self::ProgramDeployment(tx) => Ok(Self::ProgramDeployment(tx)),
|
||||
}
|
||||
}
|
||||
|
||||
@ -58,13 +58,9 @@ impl NSSATransaction {
|
||||
state: &mut V02State,
|
||||
) -> Result<Self, nssa::error::NssaError> {
|
||||
match &self {
|
||||
NSSATransaction::Public(tx) => state.transition_from_public_transaction(tx),
|
||||
NSSATransaction::PrivacyPreserving(tx) => {
|
||||
state.transition_from_privacy_preserving_transaction(tx)
|
||||
}
|
||||
NSSATransaction::ProgramDeployment(tx) => {
|
||||
state.transition_from_program_deployment_transaction(tx)
|
||||
}
|
||||
Self::Public(tx) => state.transition_from_public_transaction(tx),
|
||||
Self::PrivacyPreserving(tx) => state.transition_from_privacy_preserving_transaction(tx),
|
||||
Self::ProgramDeployment(tx) => state.transition_from_program_deployment_transaction(tx),
|
||||
}
|
||||
.inspect_err(|err| warn!("Error at transition {err:#?}"))?;
|
||||
|
||||
@ -99,7 +95,7 @@ pub enum TxKind {
|
||||
ProgramDeployment,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, thiserror::Error)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
|
||||
pub enum TransactionMalformationError {
|
||||
#[error("Invalid signature(-s)")]
|
||||
InvalidSignature,
|
||||
|
||||
@ -41,7 +41,6 @@ fn main() {
|
||||
|
||||
// Unpack the input account pre state
|
||||
let [pre_state] = pre_states
|
||||
.clone()
|
||||
.try_into()
|
||||
.unwrap_or_else(|_| panic!("Input pre states should consist of a single account"));
|
||||
|
||||
|
||||
@ -48,7 +48,7 @@ async fn main() {
|
||||
let hello_world_bytecode: Vec<u8> = std::fs::read(hello_world_path).unwrap();
|
||||
let hello_world = Program::new(hello_world_bytecode).unwrap();
|
||||
let dependencies: HashMap<ProgramId, Program> =
|
||||
[(hello_world.id(), hello_world)].into_iter().collect();
|
||||
std::iter::once((hello_world.id(), hello_world)).collect();
|
||||
let program_with_dependencies = ProgramWithDependencies::new(simple_tail_call, dependencies);
|
||||
|
||||
let accounts = vec![PrivacyPreservingAccount::PrivateOwned(account_id)];
|
||||
|
||||
@ -5,7 +5,7 @@ use leptos_router::components::A;
|
||||
use crate::format_utils;
|
||||
|
||||
/// Get CSS class for bedrock status
|
||||
fn status_class(status: &BedrockStatus) -> &'static str {
|
||||
const fn status_class(status: &BedrockStatus) -> &'static str {
|
||||
match status {
|
||||
BedrockStatus::Pending => "status-pending",
|
||||
BedrockStatus::Safe => "status-safe",
|
||||
|
||||
@ -3,7 +3,7 @@ use leptos::prelude::*;
|
||||
use leptos_router::components::A;
|
||||
|
||||
/// Get transaction type name and CSS class
|
||||
fn transaction_type_info(tx: &Transaction) -> (&'static str, &'static str) {
|
||||
const fn transaction_type_info(tx: &Transaction) -> (&'static str, &'static str) {
|
||||
match tx {
|
||||
Transaction::Public(_) => ("Public", "tx-type-public"),
|
||||
Transaction::PrivacyPreserving(_) => ("Privacy-Preserving", "tx-type-private"),
|
||||
|
||||
@ -42,7 +42,7 @@ pub struct IndexerConfig {
|
||||
}
|
||||
|
||||
impl IndexerConfig {
|
||||
pub fn from_path(config_path: &Path) -> Result<IndexerConfig> {
|
||||
pub fn from_path(config_path: &Path) -> Result<Self> {
|
||||
let file = File::open(config_path).with_context(|| {
|
||||
format!("Failed to open indexer config at {}", config_path.display())
|
||||
})?;
|
||||
|
||||
@ -35,7 +35,7 @@ impl From<nssa_core::account::AccountId> for AccountId {
|
||||
impl From<AccountId> for nssa_core::account::AccountId {
|
||||
fn from(value: AccountId) -> Self {
|
||||
let AccountId { value } = value;
|
||||
nssa_core::account::AccountId::new(value)
|
||||
Self::new(value)
|
||||
}
|
||||
}
|
||||
|
||||
@ -68,7 +68,7 @@ impl TryFrom<Account> for nssa_core::account::Account {
|
||||
nonce,
|
||||
} = value;
|
||||
|
||||
Ok(nssa_core::account::Account {
|
||||
Ok(Self {
|
||||
program_owner: program_owner.into(),
|
||||
balance,
|
||||
data: data.try_into()?,
|
||||
@ -87,7 +87,7 @@ impl TryFrom<Data> for nssa_core::account::Data {
|
||||
type Error = nssa_core::account::data::DataTooBigError;
|
||||
|
||||
fn try_from(value: Data) -> Result<Self, Self::Error> {
|
||||
nssa_core::account::Data::try_from(value.0)
|
||||
Self::try_from(value.0)
|
||||
}
|
||||
}
|
||||
|
||||
@ -103,7 +103,7 @@ impl From<nssa_core::Commitment> for Commitment {
|
||||
|
||||
impl From<Commitment> for nssa_core::Commitment {
|
||||
fn from(value: Commitment) -> Self {
|
||||
nssa_core::Commitment::from_byte_array(value.0)
|
||||
Self::from_byte_array(value.0)
|
||||
}
|
||||
}
|
||||
|
||||
@ -115,7 +115,7 @@ impl From<nssa_core::Nullifier> for Nullifier {
|
||||
|
||||
impl From<Nullifier> for nssa_core::Nullifier {
|
||||
fn from(value: Nullifier) -> Self {
|
||||
nssa_core::Nullifier::from_byte_array(value.0)
|
||||
Self::from_byte_array(value.0)
|
||||
}
|
||||
}
|
||||
|
||||
@ -143,7 +143,7 @@ impl From<nssa_core::encryption::Ciphertext> for Ciphertext {
|
||||
|
||||
impl From<Ciphertext> for nssa_core::encryption::Ciphertext {
|
||||
fn from(value: Ciphertext) -> Self {
|
||||
nssa_core::encryption::Ciphertext::from_inner(value.0)
|
||||
Self::from_inner(value.0)
|
||||
}
|
||||
}
|
||||
|
||||
@ -155,7 +155,7 @@ impl From<nssa_core::encryption::EphemeralPublicKey> for EphemeralPublicKey {
|
||||
|
||||
impl From<EphemeralPublicKey> for nssa_core::encryption::EphemeralPublicKey {
|
||||
fn from(value: EphemeralPublicKey) -> Self {
|
||||
nssa_core::encryption::shared_key_derivation::Secp256k1Point(value.0)
|
||||
Self(value.0)
|
||||
}
|
||||
}
|
||||
|
||||
@ -173,7 +173,7 @@ impl From<nssa::Signature> for Signature {
|
||||
impl From<Signature> for nssa::Signature {
|
||||
fn from(value: Signature) -> Self {
|
||||
let Signature(sig_value) = value;
|
||||
nssa::Signature { value: sig_value }
|
||||
Self { value: sig_value }
|
||||
}
|
||||
}
|
||||
|
||||
@ -187,7 +187,7 @@ impl TryFrom<PublicKey> for nssa::PublicKey {
|
||||
type Error = nssa::error::NssaError;
|
||||
|
||||
fn try_from(value: PublicKey) -> Result<Self, Self::Error> {
|
||||
nssa::PublicKey::try_new(value.0)
|
||||
Self::try_new(value.0)
|
||||
}
|
||||
}
|
||||
|
||||
@ -203,7 +203,7 @@ impl From<nssa::privacy_preserving_transaction::circuit::Proof> for Proof {
|
||||
|
||||
impl From<Proof> for nssa::privacy_preserving_transaction::circuit::Proof {
|
||||
fn from(value: Proof) -> Self {
|
||||
nssa::privacy_preserving_transaction::circuit::Proof::from_inner(value.0)
|
||||
Self::from_inner(value.0)
|
||||
}
|
||||
}
|
||||
|
||||
@ -505,12 +505,12 @@ impl From<ProgramDeploymentTransaction> for nssa::ProgramDeploymentTransaction {
|
||||
impl From<common::transaction::NSSATransaction> for Transaction {
|
||||
fn from(value: common::transaction::NSSATransaction) -> Self {
|
||||
match value {
|
||||
common::transaction::NSSATransaction::Public(tx) => Transaction::Public(tx.into()),
|
||||
common::transaction::NSSATransaction::Public(tx) => Self::Public(tx.into()),
|
||||
common::transaction::NSSATransaction::PrivacyPreserving(tx) => {
|
||||
Transaction::PrivacyPreserving(tx.into())
|
||||
Self::PrivacyPreserving(tx.into())
|
||||
}
|
||||
common::transaction::NSSATransaction::ProgramDeployment(tx) => {
|
||||
Transaction::ProgramDeployment(tx.into())
|
||||
Self::ProgramDeployment(tx.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -521,15 +521,9 @@ impl TryFrom<Transaction> for common::transaction::NSSATransaction {
|
||||
|
||||
fn try_from(value: Transaction) -> Result<Self, Self::Error> {
|
||||
match value {
|
||||
Transaction::Public(tx) => {
|
||||
Ok(common::transaction::NSSATransaction::Public(tx.try_into()?))
|
||||
}
|
||||
Transaction::PrivacyPreserving(tx) => Ok(
|
||||
common::transaction::NSSATransaction::PrivacyPreserving(tx.try_into()?),
|
||||
),
|
||||
Transaction::ProgramDeployment(tx) => Ok(
|
||||
common::transaction::NSSATransaction::ProgramDeployment(tx.into()),
|
||||
),
|
||||
Transaction::Public(tx) => Ok(Self::Public(tx.try_into()?)),
|
||||
Transaction::PrivacyPreserving(tx) => Ok(Self::PrivacyPreserving(tx.try_into()?)),
|
||||
Transaction::ProgramDeployment(tx) => Ok(Self::ProgramDeployment(tx.into())),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -683,6 +677,6 @@ impl From<common::HashType> for HashType {
|
||||
|
||||
impl From<HashType> for common::HashType {
|
||||
fn from(value: HashType) -> Self {
|
||||
common::HashType(value.0)
|
||||
Self(value.0)
|
||||
}
|
||||
}
|
||||
|
||||
@ -71,8 +71,8 @@ pub enum ProgramIdParseError {
|
||||
impl Display for ProgramIdParseError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
ProgramIdParseError::InvalidBase58(err) => write!(f, "invalid base58: {err:?}"),
|
||||
ProgramIdParseError::InvalidLength(len) => {
|
||||
Self::InvalidBase58(err) => write!(f, "invalid base58: {err:?}"),
|
||||
Self::InvalidLength(len) => {
|
||||
write!(f, "invalid length: expected 32 bytes, got {len}")
|
||||
}
|
||||
}
|
||||
@ -93,7 +93,7 @@ impl FromStr for ProgramId {
|
||||
for (i, chunk) in bytes.chunks_exact(4).enumerate() {
|
||||
arr[i] = u32::from_le_bytes(chunk.try_into().unwrap());
|
||||
}
|
||||
Ok(ProgramId(arr))
|
||||
Ok(Self(arr))
|
||||
}
|
||||
}
|
||||
|
||||
@ -125,7 +125,7 @@ impl FromStr for AccountId {
|
||||
}
|
||||
let mut value = [0_u8; 32];
|
||||
value.copy_from_slice(&bytes);
|
||||
Ok(AccountId { value })
|
||||
Ok(Self { value })
|
||||
}
|
||||
}
|
||||
|
||||
@ -174,7 +174,7 @@ impl FromStr for Signature {
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
let mut bytes = [0_u8; 64];
|
||||
hex::decode_to_slice(s, &mut bytes)?;
|
||||
Ok(Signature(bytes))
|
||||
Ok(Self(bytes))
|
||||
}
|
||||
}
|
||||
|
||||
@ -194,11 +194,11 @@ impl Transaction {
|
||||
/// Get the hash of the transaction
|
||||
#[expect(clippy::same_name_method, reason = "This is handy")]
|
||||
#[must_use]
|
||||
pub fn hash(&self) -> &self::HashType {
|
||||
pub const fn hash(&self) -> &self::HashType {
|
||||
match self {
|
||||
Transaction::Public(tx) => &tx.hash,
|
||||
Transaction::PrivacyPreserving(tx) => &tx.hash,
|
||||
Transaction::ProgramDeployment(tx) => &tx.hash,
|
||||
Self::Public(tx) => &tx.hash,
|
||||
Self::PrivacyPreserving(tx) => &tx.hash,
|
||||
Self::ProgramDeployment(tx) => &tx.hash,
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -338,7 +338,7 @@ impl FromStr for HashType {
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
let mut bytes = [0_u8; 32];
|
||||
hex::decode_to_slice(s, &mut bytes)?;
|
||||
Ok(HashType(bytes))
|
||||
Ok(Self(bytes))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -16,7 +16,7 @@ pub struct IndexerHandle {
|
||||
server_handle: Option<jsonrpsee::server::ServerHandle>,
|
||||
}
|
||||
impl IndexerHandle {
|
||||
fn new(addr: SocketAddr, server_handle: jsonrpsee::server::ServerHandle) -> Self {
|
||||
const fn new(addr: SocketAddr, server_handle: jsonrpsee::server::ServerHandle) -> Self {
|
||||
Self {
|
||||
addr,
|
||||
server_handle: Some(server_handle),
|
||||
@ -24,7 +24,7 @@ impl IndexerHandle {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn addr(&self) -> SocketAddr {
|
||||
pub const fn addr(&self) -> SocketAddr {
|
||||
self.addr
|
||||
}
|
||||
|
||||
|
||||
@ -252,7 +252,7 @@ struct Subscription<T> {
|
||||
}
|
||||
|
||||
impl<T> Subscription<T> {
|
||||
fn new(sink: SubscriptionSink) -> Self {
|
||||
const fn new(sink: SubscriptionSink) -> Self {
|
||||
Self {
|
||||
sink,
|
||||
_marker: std::marker::PhantomData,
|
||||
|
||||
@ -158,8 +158,8 @@ pub enum UrlProtocol {
|
||||
impl std::fmt::Display for UrlProtocol {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
UrlProtocol::Http => write!(f, "http"),
|
||||
UrlProtocol::Ws => write!(f, "ws"),
|
||||
Self::Http => write!(f, "http"),
|
||||
Self::Ws => write!(f, "ws"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -53,7 +53,7 @@ impl TestContext {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn builder() -> TestContextBuilder {
|
||||
pub const fn builder() -> TestContextBuilder {
|
||||
TestContextBuilder::new()
|
||||
}
|
||||
|
||||
@ -271,7 +271,7 @@ impl TestContext {
|
||||
|
||||
/// Get reference to the wallet.
|
||||
#[must_use]
|
||||
pub fn wallet(&self) -> &WalletCore {
|
||||
pub const fn wallet(&self) -> &WalletCore {
|
||||
&self.wallet
|
||||
}
|
||||
|
||||
@ -281,19 +281,19 @@ impl TestContext {
|
||||
}
|
||||
|
||||
/// Get mutable reference to the wallet.
|
||||
pub fn wallet_mut(&mut self) -> &mut WalletCore {
|
||||
pub const fn wallet_mut(&mut self) -> &mut WalletCore {
|
||||
&mut self.wallet
|
||||
}
|
||||
|
||||
/// Get reference to the sequencer client.
|
||||
#[must_use]
|
||||
pub fn sequencer_client(&self) -> &SequencerClient {
|
||||
pub const fn sequencer_client(&self) -> &SequencerClient {
|
||||
&self.sequencer_client
|
||||
}
|
||||
|
||||
/// Get reference to the indexer client.
|
||||
#[must_use]
|
||||
pub fn indexer_client(&self) -> &IndexerClient {
|
||||
pub const fn indexer_client(&self) -> &IndexerClient {
|
||||
&self.indexer_client
|
||||
}
|
||||
|
||||
@ -384,7 +384,7 @@ impl BlockingTestContext {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn ctx(&self) -> &TestContext {
|
||||
pub const fn ctx(&self) -> &TestContext {
|
||||
self.ctx.as_ref().expect("TestContext is set")
|
||||
}
|
||||
}
|
||||
@ -395,7 +395,7 @@ pub struct TestContextBuilder {
|
||||
}
|
||||
|
||||
impl TestContextBuilder {
|
||||
fn new() -> Self {
|
||||
const fn new() -> Self {
|
||||
Self {
|
||||
initial_data: None,
|
||||
sequencer_partial_config: None,
|
||||
@ -409,7 +409,7 @@ impl TestContextBuilder {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_sequencer_partial_config(
|
||||
pub const fn with_sequencer_partial_config(
|
||||
mut self,
|
||||
sequencer_partial_config: config::SequencerPartialConfig,
|
||||
) -> Self {
|
||||
|
||||
@ -118,7 +118,7 @@ impl TpsTestManager {
|
||||
}
|
||||
}
|
||||
|
||||
fn generate_sequencer_partial_config() -> SequencerPartialConfig {
|
||||
const fn generate_sequencer_partial_config() -> SequencerPartialConfig {
|
||||
SequencerPartialConfig {
|
||||
max_num_tx_in_block: 300,
|
||||
max_block_size: ByteSize::mb(500),
|
||||
|
||||
@ -216,12 +216,7 @@ fn new_wallet_rust_with_default_config(password: &str) -> Result<WalletCore> {
|
||||
let config_path = tempdir.path().join("wallet_config.json");
|
||||
let storage_path = tempdir.path().join("storage.json");
|
||||
|
||||
WalletCore::new_init_storage(
|
||||
config_path.clone(),
|
||||
storage_path.clone(),
|
||||
None,
|
||||
password.to_owned(),
|
||||
)
|
||||
WalletCore::new_init_storage(config_path, storage_path, None, password.to_owned())
|
||||
}
|
||||
|
||||
fn load_existing_ffi_wallet(home: &Path) -> Result<*mut WalletHandle> {
|
||||
|
||||
@ -23,7 +23,7 @@ impl FromStr for ChainIndex {
|
||||
}
|
||||
|
||||
if s == "/" {
|
||||
return Ok(ChainIndex(vec![]));
|
||||
return Ok(Self(vec![]));
|
||||
}
|
||||
|
||||
let uprooted_substring = s.strip_prefix("/").unwrap();
|
||||
@ -55,14 +55,14 @@ impl Display for ChainIndex {
|
||||
|
||||
impl Default for ChainIndex {
|
||||
fn default() -> Self {
|
||||
ChainIndex::from_str("/").expect("Root parsing failure")
|
||||
Self::from_str("/").expect("Root parsing failure")
|
||||
}
|
||||
}
|
||||
|
||||
impl ChainIndex {
|
||||
#[must_use]
|
||||
pub fn root() -> Self {
|
||||
ChainIndex::default()
|
||||
Self::default()
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
@ -76,42 +76,42 @@ impl ChainIndex {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn next_in_line(&self) -> Option<ChainIndex> {
|
||||
pub fn next_in_line(&self) -> Option<Self> {
|
||||
let mut chain = self.0.clone();
|
||||
// ToDo: Add overflow check
|
||||
if let Some(last_p) = chain.last_mut() {
|
||||
*last_p = last_p.checked_add(1)?;
|
||||
}
|
||||
|
||||
Some(ChainIndex(chain))
|
||||
Some(Self(chain))
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn previous_in_line(&self) -> Option<ChainIndex> {
|
||||
pub fn previous_in_line(&self) -> Option<Self> {
|
||||
let mut chain = self.0.clone();
|
||||
if let Some(last_p) = chain.last_mut() {
|
||||
*last_p = last_p.checked_sub(1)?;
|
||||
}
|
||||
|
||||
Some(ChainIndex(chain))
|
||||
Some(Self(chain))
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn parent(&self) -> Option<ChainIndex> {
|
||||
pub fn parent(&self) -> Option<Self> {
|
||||
if self.0.is_empty() {
|
||||
None
|
||||
} else {
|
||||
let last = self.0.len().checked_sub(1)?;
|
||||
Some(ChainIndex(self.0[..last].to_vec()))
|
||||
Some(Self(self.0[..last].to_vec()))
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn nth_child(&self, child_id: u32) -> ChainIndex {
|
||||
pub fn nth_child(&self, child_id: u32) -> Self {
|
||||
let mut chain = self.0.clone();
|
||||
chain.push(child_id);
|
||||
|
||||
ChainIndex(chain)
|
||||
Self(chain)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
@ -131,17 +131,17 @@ impl ChainIndex {
|
||||
Some(res)
|
||||
}
|
||||
|
||||
fn shuffle_iter(&self) -> impl Iterator<Item = ChainIndex> {
|
||||
fn shuffle_iter(&self) -> impl Iterator<Item = Self> {
|
||||
self.0
|
||||
.iter()
|
||||
.permutations(self.0.len())
|
||||
.unique()
|
||||
.map(|item| ChainIndex(item.into_iter().copied().collect()))
|
||||
.map(|item| Self(item.into_iter().copied().collect()))
|
||||
}
|
||||
|
||||
pub fn chain_ids_at_depth(depth: usize) -> impl Iterator<Item = ChainIndex> {
|
||||
let mut stack = vec![ChainIndex(vec![0; depth])];
|
||||
let mut cumulative_stack = vec![ChainIndex(vec![0; depth])];
|
||||
pub fn chain_ids_at_depth(depth: usize) -> impl Iterator<Item = Self> {
|
||||
let mut stack = vec![Self(vec![0; depth])];
|
||||
let mut cumulative_stack = vec![Self(vec![0; depth])];
|
||||
|
||||
while let Some(top_id) = stack.pop() {
|
||||
if let Some(collapsed_id) = top_id.collapse_back() {
|
||||
@ -155,9 +155,9 @@ impl ChainIndex {
|
||||
cumulative_stack.into_iter().unique()
|
||||
}
|
||||
|
||||
pub fn chain_ids_at_depth_rev(depth: usize) -> impl Iterator<Item = ChainIndex> {
|
||||
let mut stack = vec![ChainIndex(vec![0; depth])];
|
||||
let mut cumulative_stack = vec![ChainIndex(vec![0; depth])];
|
||||
pub fn chain_ids_at_depth_rev(depth: usize) -> impl Iterator<Item = Self> {
|
||||
let mut stack = vec![Self(vec![0; depth])];
|
||||
let mut cumulative_stack = vec![Self(vec![0; depth])];
|
||||
|
||||
while let Some(top_id) = stack.pop() {
|
||||
if let Some(collapsed_id) = top_id.collapse_back() {
|
||||
|
||||
@ -19,16 +19,13 @@ impl ChildKeysPublic {
|
||||
if 2_u32.pow(31) > cci {
|
||||
// Non-harden
|
||||
hash_input.extend_from_slice(self.cpk.value());
|
||||
hash_input.extend_from_slice(&cci.to_le_bytes());
|
||||
|
||||
hmac_sha512::HMAC::mac(hash_input, self.ccc)
|
||||
} else {
|
||||
// Harden
|
||||
hash_input.extend_from_slice(self.csk.value());
|
||||
hash_input.extend_from_slice(&(cci).to_le_bytes());
|
||||
|
||||
hmac_sha512::HMAC::mac(hash_input, self.ccc)
|
||||
}
|
||||
hash_input.extend_from_slice(&cci.to_le_bytes());
|
||||
|
||||
hmac_sha512::HMAC::mac(hash_input, self.ccc)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -104,17 +104,14 @@ impl NSSAUserData {
|
||||
}
|
||||
|
||||
/// Returns the signing key for public transaction signatures
|
||||
#[must_use]
|
||||
pub fn get_pub_account_signing_key(
|
||||
&self,
|
||||
account_id: nssa::AccountId,
|
||||
) -> Option<&nssa::PrivateKey> {
|
||||
// First seek in defaults
|
||||
if let Some(key) = self.default_pub_account_signing_keys.get(&account_id) {
|
||||
Some(key)
|
||||
// Then seek in tree
|
||||
} else {
|
||||
self.public_key_tree.get_node(account_id).map(Into::into)
|
||||
}
|
||||
self.default_pub_account_signing_keys
|
||||
.get(&account_id)
|
||||
.or_else(|| self.public_key_tree.get_node(account_id).map(Into::into))
|
||||
}
|
||||
|
||||
/// Generated new private key for privacy preserving transactions
|
||||
@ -137,17 +134,14 @@ impl NSSAUserData {
|
||||
}
|
||||
|
||||
/// Returns the signing key for public transaction signatures
|
||||
#[must_use]
|
||||
pub fn get_private_account(
|
||||
&self,
|
||||
account_id: nssa::AccountId,
|
||||
) -> Option<&(KeyChain, nssa_core::account::Account)> {
|
||||
// First seek in defaults
|
||||
if let Some(key) = self.default_user_private_accounts.get(&account_id) {
|
||||
Some(key)
|
||||
// Then seek in tree
|
||||
} else {
|
||||
self.private_key_tree.get_node(account_id).map(Into::into)
|
||||
}
|
||||
self.default_user_private_accounts
|
||||
.get(&account_id)
|
||||
.or_else(|| self.private_key_tree.get_node(account_id).map(Into::into))
|
||||
}
|
||||
|
||||
/// Returns the signing key for public transaction signatures
|
||||
|
||||
@ -49,7 +49,7 @@ pub struct MemPoolHandle<T> {
|
||||
}
|
||||
|
||||
impl<T> MemPoolHandle<T> {
|
||||
fn new(sender: Sender<T>) -> Self {
|
||||
const fn new(sender: Sender<T>) -> Self {
|
||||
Self { sender }
|
||||
}
|
||||
|
||||
|
||||
@ -88,17 +88,17 @@ impl std::fmt::Debug for AccountId {
|
||||
|
||||
impl AccountId {
|
||||
#[must_use]
|
||||
pub fn new(value: [u8; 32]) -> Self {
|
||||
pub const fn new(value: [u8; 32]) -> Self {
|
||||
Self { value }
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn value(&self) -> &[u8; 32] {
|
||||
pub const fn value(&self) -> &[u8; 32] {
|
||||
&self.value
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn into_value(self) -> [u8; 32] {
|
||||
pub const fn into_value(self) -> [u8; 32] {
|
||||
self.value
|
||||
}
|
||||
}
|
||||
@ -127,7 +127,7 @@ impl FromStr for AccountId {
|
||||
}
|
||||
let mut value = [0_u8; 32];
|
||||
value.copy_from_slice(&bytes);
|
||||
Ok(AccountId { value })
|
||||
Ok(Self { value })
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -91,18 +91,16 @@ pub fn compute_digest_for_path(
|
||||
.unwrap();
|
||||
let mut level_index = proof.0;
|
||||
for node in &proof.1 {
|
||||
let mut bytes = [0_u8; 64];
|
||||
let is_left_child = level_index & 1 == 0;
|
||||
if is_left_child {
|
||||
let mut bytes = [0_u8; 64];
|
||||
bytes[..32].copy_from_slice(&result);
|
||||
bytes[32..].copy_from_slice(node);
|
||||
result = Impl::hash_bytes(&bytes).as_bytes().try_into().unwrap();
|
||||
} else {
|
||||
let mut bytes = [0_u8; 64];
|
||||
bytes[..32].copy_from_slice(node);
|
||||
bytes[32..].copy_from_slice(&result);
|
||||
result = Impl::hash_bytes(&bytes).as_bytes().try_into().unwrap();
|
||||
}
|
||||
result = Impl::hash_bytes(&bytes).as_bytes().try_into().unwrap();
|
||||
level_index >>= 1;
|
||||
}
|
||||
result
|
||||
|
||||
@ -69,13 +69,13 @@ impl Account {
|
||||
|
||||
impl Commitment {
|
||||
#[must_use]
|
||||
pub fn to_byte_array(&self) -> [u8; 32] {
|
||||
pub const fn to_byte_array(&self) -> [u8; 32] {
|
||||
self.0
|
||||
}
|
||||
|
||||
#[cfg(feature = "host")]
|
||||
#[must_use]
|
||||
pub fn from_byte_array(bytes: [u8; 32]) -> Self {
|
||||
pub const fn from_byte_array(bytes: [u8; 32]) -> Self {
|
||||
Self(bytes)
|
||||
}
|
||||
|
||||
@ -90,7 +90,7 @@ impl Commitment {
|
||||
|
||||
impl NullifierPublicKey {
|
||||
#[must_use]
|
||||
pub fn to_byte_array(&self) -> [u8; 32] {
|
||||
pub const fn to_byte_array(&self) -> [u8; 32] {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
@ -98,13 +98,13 @@ impl NullifierPublicKey {
|
||||
#[cfg(feature = "host")]
|
||||
impl Nullifier {
|
||||
#[must_use]
|
||||
pub fn to_byte_array(&self) -> [u8; 32] {
|
||||
pub const fn to_byte_array(&self) -> [u8; 32] {
|
||||
self.0
|
||||
}
|
||||
|
||||
#[cfg(feature = "host")]
|
||||
#[must_use]
|
||||
pub fn from_byte_array(bytes: [u8; 32]) -> Self {
|
||||
pub const fn from_byte_array(bytes: [u8; 32]) -> Self {
|
||||
Self(bytes)
|
||||
}
|
||||
|
||||
@ -137,7 +137,7 @@ impl Ciphertext {
|
||||
|
||||
#[cfg(feature = "host")]
|
||||
#[must_use]
|
||||
pub fn from_inner(inner: Vec<u8>) -> Self {
|
||||
pub const fn from_inner(inner: Vec<u8>) -> Self {
|
||||
Self(inner)
|
||||
}
|
||||
|
||||
@ -175,7 +175,7 @@ impl Secp256k1Point {
|
||||
|
||||
impl AccountId {
|
||||
#[must_use]
|
||||
pub fn to_bytes(&self) -> [u8; 32] {
|
||||
pub const fn to_bytes(&self) -> [u8; 32] {
|
||||
*self.value()
|
||||
}
|
||||
}
|
||||
|
||||
@ -44,7 +44,7 @@ impl EncryptionScheme {
|
||||
commitment: &Commitment,
|
||||
output_index: u32,
|
||||
) -> Ciphertext {
|
||||
let mut buffer = account.to_bytes().clone();
|
||||
let mut buffer = account.to_bytes();
|
||||
Self::symmetric_transform(&mut buffer, shared_secret, commitment, output_index);
|
||||
Ciphertext(buffer)
|
||||
}
|
||||
|
||||
@ -32,7 +32,7 @@ impl std::fmt::Debug for Secp256k1Point {
|
||||
|
||||
impl Secp256k1Point {
|
||||
#[must_use]
|
||||
pub fn from_scalar(value: Scalar) -> Secp256k1Point {
|
||||
pub fn from_scalar(value: Scalar) -> Self {
|
||||
let x_bytes: FieldBytes = value.into();
|
||||
let x = k256::Scalar::from_repr(x_bytes).unwrap();
|
||||
|
||||
@ -49,7 +49,7 @@ pub type EphemeralPublicKey = Secp256k1Point;
|
||||
pub type ViewingPublicKey = Secp256k1Point;
|
||||
impl From<&EphemeralSecretKey> for EphemeralPublicKey {
|
||||
fn from(value: &EphemeralSecretKey) -> Self {
|
||||
Secp256k1Point::from_scalar(*value)
|
||||
Self::from_scalar(*value)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -16,7 +16,12 @@ impl From<&NullifierPublicKey> for AccountId {
|
||||
let mut bytes = [0; 64];
|
||||
bytes[0..32].copy_from_slice(PRIVATE_ACCOUNT_ID_PREFIX);
|
||||
bytes[32..].copy_from_slice(&value.0);
|
||||
AccountId::new(Impl::hash_bytes(&bytes).as_bytes().try_into().unwrap())
|
||||
Self::new(
|
||||
Impl::hash_bytes(&bytes)
|
||||
.as_bytes()
|
||||
.try_into()
|
||||
.expect("Conversion should not fail"),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@ -36,7 +41,12 @@ impl From<&NullifierSecretKey> for NullifierPublicKey {
|
||||
bytes.extend_from_slice(value);
|
||||
bytes.extend_from_slice(SUFFIX_1);
|
||||
bytes.extend_from_slice(SUFFIX_2);
|
||||
Self(Impl::hash_bytes(&bytes).as_bytes().try_into().unwrap())
|
||||
Self(
|
||||
Impl::hash_bytes(&bytes)
|
||||
.as_bytes()
|
||||
.try_into()
|
||||
.expect("hash should be exactly 32 bytes long"),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -42,7 +42,7 @@ impl From<(&ProgramId, &PdaSeed)> for AccountId {
|
||||
bytemuck::try_cast_slice(value.0).expect("ProgramId should be castable to &[u8]");
|
||||
bytes[32..64].copy_from_slice(program_id_bytes);
|
||||
bytes[64..].copy_from_slice(&value.1.0);
|
||||
AccountId::new(
|
||||
Self::new(
|
||||
Impl::hash_bytes(&bytes)
|
||||
.as_bytes()
|
||||
.try_into()
|
||||
@ -85,6 +85,7 @@ impl ChainedCall {
|
||||
}
|
||||
|
||||
/// Represents the final state of an `Account` after a program execution.
|
||||
///
|
||||
/// A post state may optionally request that the executing program
|
||||
/// becomes the owner of the account (a “claim”). This is used to signal
|
||||
/// that the program intends to take ownership of the account.
|
||||
@ -99,7 +100,7 @@ impl AccountPostState {
|
||||
/// Creates a post state without a claim request.
|
||||
/// The executing program is not requesting ownership of the account.
|
||||
#[must_use]
|
||||
pub fn new(account: Account) -> Self {
|
||||
pub const fn new(account: Account) -> Self {
|
||||
Self {
|
||||
account,
|
||||
claim: false,
|
||||
@ -110,7 +111,7 @@ impl AccountPostState {
|
||||
/// This indicates that the executing program intends to claim the
|
||||
/// account as its own and is allowed to mutate it.
|
||||
#[must_use]
|
||||
pub fn new_claimed(account: Account) -> Self {
|
||||
pub const fn new_claimed(account: Account) -> Self {
|
||||
Self {
|
||||
account,
|
||||
claim: true,
|
||||
@ -128,18 +129,18 @@ impl AccountPostState {
|
||||
/// Returns `true` if this post state requests that the account
|
||||
/// be claimed (owned) by the executing program.
|
||||
#[must_use]
|
||||
pub fn requires_claim(&self) -> bool {
|
||||
pub const fn requires_claim(&self) -> bool {
|
||||
self.claim
|
||||
}
|
||||
|
||||
/// Returns the underlying account
|
||||
#[must_use]
|
||||
pub fn account(&self) -> &Account {
|
||||
pub const fn account(&self) -> &Account {
|
||||
&self.account
|
||||
}
|
||||
|
||||
/// Returns the underlying account
|
||||
pub fn account_mut(&mut self) -> &mut Account {
|
||||
pub const fn account_mut(&mut self) -> &mut Account {
|
||||
&mut self.account
|
||||
}
|
||||
|
||||
@ -174,7 +175,7 @@ impl WrappedBalanceSum {
|
||||
/// Returns [`None`] if balance sum overflows `lo + hi * 2^128` representation, which is not
|
||||
/// expected in practical scenarios.
|
||||
fn from_balances(balances: impl Iterator<Item = u128>) -> Option<Self> {
|
||||
let mut wrapped = WrappedBalanceSum { lo: 0, hi: 0 };
|
||||
let mut wrapped = Self { lo: 0, hi: 0 };
|
||||
|
||||
for balance in balances {
|
||||
let (new_sum, did_overflow) = wrapped.lo.overflowing_add(balance);
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
pub(crate) const DEFAULT_VALUES: [[u8; 32]; 32] = [
|
||||
pub const DEFAULT_VALUES: [[u8; 32]; 32] = [
|
||||
[
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0,
|
||||
|
||||
@ -156,7 +156,7 @@ fn hash_value(value: &Value) -> Node {
|
||||
hasher.finalize().into()
|
||||
}
|
||||
|
||||
fn prev_power_of_two(x: usize) -> usize {
|
||||
const fn prev_power_of_two(x: usize) -> usize {
|
||||
if x == 0 {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@ -27,7 +27,7 @@ impl Proof {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn from_inner(inner: Vec<u8>) -> Self {
|
||||
pub const fn from_inner(inner: Vec<u8>) -> Self {
|
||||
Self(inner)
|
||||
}
|
||||
|
||||
@ -47,7 +47,7 @@ pub struct ProgramWithDependencies {
|
||||
|
||||
impl ProgramWithDependencies {
|
||||
#[must_use]
|
||||
pub fn new(program: Program, dependencies: HashMap<ProgramId, Program>) -> Self {
|
||||
pub const fn new(program: Program, dependencies: HashMap<ProgramId, Program>) -> Self {
|
||||
Self {
|
||||
program,
|
||||
dependencies,
|
||||
@ -57,7 +57,7 @@ impl ProgramWithDependencies {
|
||||
|
||||
impl From<Program> for ProgramWithDependencies {
|
||||
fn from(program: Program) -> Self {
|
||||
ProgramWithDependencies::new(program, HashMap::new())
|
||||
Self::new(program, HashMap::new())
|
||||
}
|
||||
}
|
||||
|
||||
@ -328,7 +328,7 @@ mod tests {
|
||||
let shared_secret_2 = SharedSecretKey::new(&esk_2, &recipient_keys.vpk());
|
||||
|
||||
let (output, proof) = execute_and_prove(
|
||||
vec![sender_pre.clone(), recipient],
|
||||
vec![sender_pre, recipient],
|
||||
Program::serialize_instruction(balance_to_move).unwrap(),
|
||||
vec![1, 2],
|
||||
vec![0xdead_beef1, 0xdead_beef2],
|
||||
|
||||
@ -155,12 +155,12 @@ pub mod tests {
|
||||
)];
|
||||
|
||||
Message {
|
||||
public_account_ids: public_account_ids.clone(),
|
||||
nonces: nonces.clone(),
|
||||
public_post_states: public_post_states.clone(),
|
||||
encrypted_private_post_states: encrypted_private_post_states.clone(),
|
||||
new_commitments: new_commitments.clone(),
|
||||
new_nullifiers: new_nullifiers.clone(),
|
||||
public_account_ids,
|
||||
nonces,
|
||||
public_post_states,
|
||||
encrypted_private_post_states,
|
||||
new_commitments,
|
||||
new_nullifiers,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -25,7 +25,7 @@ pub struct PrivacyPreservingTransaction {
|
||||
|
||||
impl PrivacyPreservingTransaction {
|
||||
#[must_use]
|
||||
pub fn new(message: Message, witness_set: WitnessSet) -> Self {
|
||||
pub const fn new(message: Message, witness_set: WitnessSet) -> Self {
|
||||
Self {
|
||||
message,
|
||||
witness_set,
|
||||
@ -129,12 +129,12 @@ impl PrivacyPreservingTransaction {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn message(&self) -> &Message {
|
||||
pub const fn message(&self) -> &Message {
|
||||
&self.message
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn witness_set(&self) -> &WitnessSet {
|
||||
pub const fn witness_set(&self) -> &WitnessSet {
|
||||
&self.witness_set
|
||||
}
|
||||
|
||||
|
||||
@ -47,7 +47,7 @@ impl WitnessSet {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn proof(&self) -> &Proof {
|
||||
pub const fn proof(&self) -> &Proof {
|
||||
&self.proof
|
||||
}
|
||||
|
||||
@ -57,7 +57,7 @@ impl WitnessSet {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn from_raw_parts(
|
||||
pub const fn from_raw_parts(
|
||||
signatures_and_public_keys: Vec<(Signature, PublicKey)>,
|
||||
proof: Proof,
|
||||
) -> Self {
|
||||
|
||||
@ -33,7 +33,7 @@ impl Program {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn id(&self) -> ProgramId {
|
||||
pub const fn id(&self) -> ProgramId {
|
||||
self.id
|
||||
}
|
||||
|
||||
@ -142,7 +142,7 @@ mod tests {
|
||||
pub fn nonce_changer_program() -> Self {
|
||||
use test_program_methods::{NONCE_CHANGER_ELF, NONCE_CHANGER_ID};
|
||||
|
||||
Program {
|
||||
Self {
|
||||
id: NONCE_CHANGER_ID,
|
||||
elf: NONCE_CHANGER_ELF.to_vec(),
|
||||
}
|
||||
@ -153,7 +153,7 @@ mod tests {
|
||||
pub fn extra_output_program() -> Self {
|
||||
use test_program_methods::{EXTRA_OUTPUT_ELF, EXTRA_OUTPUT_ID};
|
||||
|
||||
Program {
|
||||
Self {
|
||||
id: EXTRA_OUTPUT_ID,
|
||||
elf: EXTRA_OUTPUT_ELF.to_vec(),
|
||||
}
|
||||
@ -164,7 +164,7 @@ mod tests {
|
||||
pub fn missing_output_program() -> Self {
|
||||
use test_program_methods::{MISSING_OUTPUT_ELF, MISSING_OUTPUT_ID};
|
||||
|
||||
Program {
|
||||
Self {
|
||||
id: MISSING_OUTPUT_ID,
|
||||
elf: MISSING_OUTPUT_ELF.to_vec(),
|
||||
}
|
||||
@ -175,7 +175,7 @@ mod tests {
|
||||
pub fn program_owner_changer() -> Self {
|
||||
use test_program_methods::{PROGRAM_OWNER_CHANGER_ELF, PROGRAM_OWNER_CHANGER_ID};
|
||||
|
||||
Program {
|
||||
Self {
|
||||
id: PROGRAM_OWNER_CHANGER_ID,
|
||||
elf: PROGRAM_OWNER_CHANGER_ELF.to_vec(),
|
||||
}
|
||||
@ -186,7 +186,7 @@ mod tests {
|
||||
pub fn simple_balance_transfer() -> Self {
|
||||
use test_program_methods::{SIMPLE_BALANCE_TRANSFER_ELF, SIMPLE_BALANCE_TRANSFER_ID};
|
||||
|
||||
Program {
|
||||
Self {
|
||||
id: SIMPLE_BALANCE_TRANSFER_ID,
|
||||
elf: SIMPLE_BALANCE_TRANSFER_ELF.to_vec(),
|
||||
}
|
||||
@ -197,7 +197,7 @@ mod tests {
|
||||
pub fn data_changer() -> Self {
|
||||
use test_program_methods::{DATA_CHANGER_ELF, DATA_CHANGER_ID};
|
||||
|
||||
Program {
|
||||
Self {
|
||||
id: DATA_CHANGER_ID,
|
||||
elf: DATA_CHANGER_ELF.to_vec(),
|
||||
}
|
||||
@ -208,7 +208,7 @@ mod tests {
|
||||
pub fn minter() -> Self {
|
||||
use test_program_methods::{MINTER_ELF, MINTER_ID};
|
||||
|
||||
Program {
|
||||
Self {
|
||||
id: MINTER_ID,
|
||||
elf: MINTER_ELF.to_vec(),
|
||||
}
|
||||
@ -219,7 +219,7 @@ mod tests {
|
||||
pub fn burner() -> Self {
|
||||
use test_program_methods::{BURNER_ELF, BURNER_ID};
|
||||
|
||||
Program {
|
||||
Self {
|
||||
id: BURNER_ID,
|
||||
elf: BURNER_ELF.to_vec(),
|
||||
}
|
||||
@ -229,7 +229,7 @@ mod tests {
|
||||
pub fn chain_caller() -> Self {
|
||||
use test_program_methods::{CHAIN_CALLER_ELF, CHAIN_CALLER_ID};
|
||||
|
||||
Program {
|
||||
Self {
|
||||
id: CHAIN_CALLER_ID,
|
||||
elf: CHAIN_CALLER_ELF.to_vec(),
|
||||
}
|
||||
@ -239,7 +239,7 @@ mod tests {
|
||||
pub fn claimer() -> Self {
|
||||
use test_program_methods::{CLAIMER_ELF, CLAIMER_ID};
|
||||
|
||||
Program {
|
||||
Self {
|
||||
id: CLAIMER_ID,
|
||||
elf: CLAIMER_ELF.to_vec(),
|
||||
}
|
||||
@ -249,7 +249,7 @@ mod tests {
|
||||
pub fn changer_claimer() -> Self {
|
||||
use test_program_methods::{CHANGER_CLAIMER_ELF, CHANGER_CLAIMER_ID};
|
||||
|
||||
Program {
|
||||
Self {
|
||||
id: CHANGER_CLAIMER_ID,
|
||||
elf: CHANGER_CLAIMER_ELF.to_vec(),
|
||||
}
|
||||
@ -259,7 +259,7 @@ mod tests {
|
||||
pub fn noop() -> Self {
|
||||
use test_program_methods::{NOOP_ELF, NOOP_ID};
|
||||
|
||||
Program {
|
||||
Self {
|
||||
id: NOOP_ID,
|
||||
elf: NOOP_ELF.to_vec(),
|
||||
}
|
||||
@ -271,7 +271,7 @@ mod tests {
|
||||
MALICIOUS_AUTHORIZATION_CHANGER_ELF, MALICIOUS_AUTHORIZATION_CHANGER_ID,
|
||||
};
|
||||
|
||||
Program {
|
||||
Self {
|
||||
id: MALICIOUS_AUTHORIZATION_CHANGER_ID,
|
||||
elf: MALICIOUS_AUTHORIZATION_CHANGER_ELF.to_vec(),
|
||||
}
|
||||
|
||||
@ -7,7 +7,7 @@ pub struct Message {
|
||||
|
||||
impl Message {
|
||||
#[must_use]
|
||||
pub fn new(bytecode: Vec<u8>) -> Self {
|
||||
pub const fn new(bytecode: Vec<u8>) -> Self {
|
||||
Self { bytecode }
|
||||
}
|
||||
|
||||
|
||||
@ -13,7 +13,7 @@ pub struct ProgramDeploymentTransaction {
|
||||
|
||||
impl ProgramDeploymentTransaction {
|
||||
#[must_use]
|
||||
pub fn new(message: Message) -> Self {
|
||||
pub const fn new(message: Message) -> Self {
|
||||
Self { message }
|
||||
}
|
||||
|
||||
@ -44,7 +44,7 @@ impl ProgramDeploymentTransaction {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn affected_public_account_ids(&self) -> Vec<AccountId> {
|
||||
pub const fn affected_public_account_ids(&self) -> Vec<AccountId> {
|
||||
vec![]
|
||||
}
|
||||
}
|
||||
|
||||
@ -50,7 +50,7 @@ impl Message {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn new_preserialized(
|
||||
pub const fn new_preserialized(
|
||||
program_id: ProgramId,
|
||||
account_ids: Vec<AccountId>,
|
||||
nonces: Vec<Nonce>,
|
||||
|
||||
@ -23,7 +23,7 @@ pub struct PublicTransaction {
|
||||
|
||||
impl PublicTransaction {
|
||||
#[must_use]
|
||||
pub fn new(message: Message, witness_set: WitnessSet) -> Self {
|
||||
pub const fn new(message: Message, witness_set: WitnessSet) -> Self {
|
||||
Self {
|
||||
message,
|
||||
witness_set,
|
||||
@ -31,12 +31,12 @@ impl PublicTransaction {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn message(&self) -> &Message {
|
||||
pub const fn message(&self) -> &Message {
|
||||
&self.message
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn witness_set(&self) -> &WitnessSet {
|
||||
pub const fn witness_set(&self) -> &WitnessSet {
|
||||
&self.witness_set
|
||||
}
|
||||
|
||||
|
||||
@ -47,7 +47,7 @@ impl WitnessSet {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn from_raw_parts(signatures_and_public_keys: Vec<(Signature, PublicKey)>) -> Self {
|
||||
pub const fn from_raw_parts(signatures_and_public_keys: Vec<(Signature, PublicKey)>) -> Self {
|
||||
Self {
|
||||
signatures_and_public_keys,
|
||||
}
|
||||
|
||||
@ -33,7 +33,7 @@ impl PrivateKey {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn value(&self) -> &[u8; 32] {
|
||||
pub const fn value(&self) -> &[u8; 32] {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
@ -44,7 +44,7 @@ impl PublicKey {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn value(&self) -> &[u8; 32] {
|
||||
pub const fn value(&self) -> &[u8; 32] {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
@ -18,7 +18,7 @@ pub const MAX_NUMBER_CHAINED_CALLS: usize = 10;
|
||||
|
||||
#[derive(Clone, BorshSerialize, BorshDeserialize)]
|
||||
#[cfg_attr(test, derive(Debug, PartialEq, Eq))]
|
||||
pub(crate) struct CommitmentSet {
|
||||
pub struct CommitmentSet {
|
||||
merkle_tree: MerkleTree,
|
||||
commitments: HashMap<Commitment, usize>,
|
||||
root_history: HashSet<CommitmentSetDigest>,
|
||||
@ -54,7 +54,7 @@ impl CommitmentSet {
|
||||
/// Initializes an empty `CommitmentSet` with a given capacity.
|
||||
/// If the capacity is not a `power_of_two`, then capacity is taken
|
||||
/// to be the next `power_of_two`.
|
||||
pub(crate) fn with_capacity(capacity: usize) -> CommitmentSet {
|
||||
pub(crate) fn with_capacity(capacity: usize) -> Self {
|
||||
Self {
|
||||
merkle_tree: MerkleTree::with_capacity(capacity),
|
||||
commitments: HashMap::new(),
|
||||
@ -68,7 +68,7 @@ impl CommitmentSet {
|
||||
struct NullifierSet(BTreeSet<Nullifier>);
|
||||
|
||||
impl NullifierSet {
|
||||
fn new() -> Self {
|
||||
const fn new() -> Self {
|
||||
Self(BTreeSet::new())
|
||||
}
|
||||
|
||||
@ -242,7 +242,7 @@ impl V02State {
|
||||
self.public_state
|
||||
.get(&account_id)
|
||||
.cloned()
|
||||
.unwrap_or(Account::default())
|
||||
.unwrap_or_else(Account::default)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
@ -250,7 +250,7 @@ impl V02State {
|
||||
self.private_state.0.get_proof_for(commitment)
|
||||
}
|
||||
|
||||
pub(crate) fn programs(&self) -> &HashMap<ProgramId, Program> {
|
||||
pub(crate) const fn programs(&self) -> &HashMap<ProgramId, Program> {
|
||||
&self.programs
|
||||
}
|
||||
|
||||
@ -631,8 +631,7 @@ pub mod tests {
|
||||
|
||||
fn lp_supply_init() -> u128 {
|
||||
// isqrt(vault_a_balance_init * vault_b_balance_init) = isqrt(5_000 * 2_500) = 3535
|
||||
(BalanceForTests::vault_a_balance_init() * BalanceForTests::vault_b_balance_init())
|
||||
.isqrt()
|
||||
(Self::vault_a_balance_init() * Self::vault_b_balance_init()).isqrt()
|
||||
}
|
||||
}
|
||||
|
||||
@ -642,16 +641,13 @@ pub mod tests {
|
||||
fn pool_definition_id() -> AccountId {
|
||||
amm_core::compute_pool_pda(
|
||||
Program::amm().id(),
|
||||
IdForTests::token_a_definition_id(),
|
||||
IdForTests::token_b_definition_id(),
|
||||
Self::token_a_definition_id(),
|
||||
Self::token_b_definition_id(),
|
||||
)
|
||||
}
|
||||
|
||||
fn token_lp_definition_id() -> AccountId {
|
||||
amm_core::compute_liquidity_token_pda(
|
||||
Program::amm().id(),
|
||||
IdForTests::pool_definition_id(),
|
||||
)
|
||||
amm_core::compute_liquidity_token_pda(Program::amm().id(), Self::pool_definition_id())
|
||||
}
|
||||
|
||||
fn token_a_definition_id() -> AccountId {
|
||||
@ -683,16 +679,16 @@ pub mod tests {
|
||||
fn vault_a_id() -> AccountId {
|
||||
amm_core::compute_vault_pda(
|
||||
Program::amm().id(),
|
||||
IdForTests::pool_definition_id(),
|
||||
IdForTests::token_a_definition_id(),
|
||||
Self::pool_definition_id(),
|
||||
Self::token_a_definition_id(),
|
||||
)
|
||||
}
|
||||
|
||||
fn vault_b_id() -> AccountId {
|
||||
amm_core::compute_vault_pda(
|
||||
Program::amm().id(),
|
||||
IdForTests::pool_definition_id(),
|
||||
IdForTests::token_b_definition_id(),
|
||||
Self::pool_definition_id(),
|
||||
Self::token_b_definition_id(),
|
||||
)
|
||||
}
|
||||
}
|
||||
@ -2199,7 +2195,7 @@ pub mod tests {
|
||||
vec![],
|
||||
vec![],
|
||||
vec![],
|
||||
&program.clone().into(),
|
||||
&program.into(),
|
||||
);
|
||||
|
||||
assert!(matches!(result, Err(NssaError::ProgramProveFailed(_))));
|
||||
@ -4205,7 +4201,7 @@ pub mod tests {
|
||||
|
||||
// Prepare new state of account
|
||||
let account_metadata = {
|
||||
let mut acc = authorized_account.clone();
|
||||
let mut acc = authorized_account;
|
||||
acc.account.program_owner = Program::claimer().id();
|
||||
acc
|
||||
};
|
||||
|
||||
@ -37,7 +37,7 @@ impl ExecutionState {
|
||||
};
|
||||
let mut chained_calls = VecDeque::from_iter([(initial_call, None)]);
|
||||
|
||||
let mut execution_state = ExecutionState {
|
||||
let mut execution_state = Self {
|
||||
pre_states: Vec::new(),
|
||||
post_states: HashMap::new(),
|
||||
};
|
||||
@ -324,10 +324,9 @@ fn compute_circuit_output(
|
||||
|
||||
output.new_commitments.push(commitment_post);
|
||||
output.ciphertexts.push(encrypted_account);
|
||||
output_index = match output_index.checked_add(1) {
|
||||
Some(val) => val,
|
||||
None => panic!("Too many private accounts, output index overflow"),
|
||||
}
|
||||
output_index = output_index
|
||||
.checked_add(1)
|
||||
.unwrap_or_else(|| panic!("Too many private accounts, output index overflow"));
|
||||
}
|
||||
_ => panic!("Invalid visibility mask value"),
|
||||
}
|
||||
|
||||
@ -97,7 +97,7 @@ impl TryFrom<&Data> for PoolDefinition {
|
||||
type Error = std::io::Error;
|
||||
|
||||
fn try_from(data: &Data) -> Result<Self, Self::Error> {
|
||||
PoolDefinition::try_from_slice(data.as_ref())
|
||||
Self::try_from_slice(data.as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
@ -109,7 +109,7 @@ impl From<&PoolDefinition> for Data {
|
||||
BorshSerialize::serialize(definition, &mut data)
|
||||
.expect("Serialization to Vec should not fail");
|
||||
|
||||
Data::try_from(data).expect("Token definition encoded data should fit into Data")
|
||||
Self::try_from(data).expect("Token definition encoded data should fit into Data")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -156,7 +156,7 @@ pub fn add_liquidity(
|
||||
pool_definition_lp_auth.is_authorized = true;
|
||||
let call_token_lp = ChainedCall::new(
|
||||
token_program_id,
|
||||
vec![pool_definition_lp_auth.clone(), user_holding_lp.clone()],
|
||||
vec![pool_definition_lp_auth, user_holding_lp.clone()],
|
||||
&token_core::Instruction::Mint {
|
||||
amount_to_mint: delta_lp,
|
||||
},
|
||||
|
||||
@ -134,7 +134,7 @@ pub fn new_definition(
|
||||
|
||||
let call_token_lp = ChainedCall::new(
|
||||
token_program_id,
|
||||
vec![pool_lp_auth.clone(), user_holding_lp.clone()],
|
||||
vec![pool_lp_auth, user_holding_lp.clone()],
|
||||
&instruction,
|
||||
)
|
||||
.with_pda_seeds(vec![compute_liquidity_token_pda_seed(pool.account_id)]);
|
||||
@ -151,5 +151,5 @@ pub fn new_definition(
|
||||
AccountPostState::new(user_holding_lp.account),
|
||||
];
|
||||
|
||||
(post_states.clone(), chained_calls)
|
||||
(post_states, chained_calls)
|
||||
}
|
||||
|
||||
@ -108,7 +108,7 @@ pub fn remove_liquidity(
|
||||
reserve_a: pool_def_data.reserve_a - withdraw_amount_a,
|
||||
reserve_b: pool_def_data.reserve_b - withdraw_amount_b,
|
||||
active,
|
||||
..pool_def_data.clone()
|
||||
..pool_def_data
|
||||
};
|
||||
|
||||
pool_post.data = Data::from(&pool_post_definition);
|
||||
|
||||
@ -107,7 +107,7 @@ impl BalanceForTests {
|
||||
|
||||
fn lp_supply_init() -> u128 {
|
||||
// sqrt(vault_a_reserve_init * vault_b_reserve_init) = sqrt(1000 * 500) = 707
|
||||
(BalanceForTests::vault_a_reserve_init() * BalanceForTests::vault_b_reserve_init()).isqrt()
|
||||
(Self::vault_a_reserve_init() * Self::vault_b_reserve_init()).isqrt()
|
||||
}
|
||||
|
||||
fn vault_a_swap_test_1() -> u128 {
|
||||
@ -365,7 +365,7 @@ impl IdForTests {
|
||||
}
|
||||
|
||||
fn token_lp_definition_id() -> AccountId {
|
||||
compute_liquidity_token_pda(AMM_PROGRAM_ID, IdForTests::pool_definition_id())
|
||||
compute_liquidity_token_pda(AMM_PROGRAM_ID, Self::pool_definition_id())
|
||||
}
|
||||
|
||||
fn user_token_a_id() -> AccountId {
|
||||
@ -383,24 +383,24 @@ impl IdForTests {
|
||||
fn pool_definition_id() -> AccountId {
|
||||
compute_pool_pda(
|
||||
AMM_PROGRAM_ID,
|
||||
IdForTests::token_a_definition_id(),
|
||||
IdForTests::token_b_definition_id(),
|
||||
Self::token_a_definition_id(),
|
||||
Self::token_b_definition_id(),
|
||||
)
|
||||
}
|
||||
|
||||
fn vault_a_id() -> AccountId {
|
||||
compute_vault_pda(
|
||||
AMM_PROGRAM_ID,
|
||||
IdForTests::pool_definition_id(),
|
||||
IdForTests::token_a_definition_id(),
|
||||
Self::pool_definition_id(),
|
||||
Self::token_a_definition_id(),
|
||||
)
|
||||
}
|
||||
|
||||
fn vault_b_id() -> AccountId {
|
||||
compute_vault_pda(
|
||||
AMM_PROGRAM_ID,
|
||||
IdForTests::pool_definition_id(),
|
||||
IdForTests::token_b_definition_id(),
|
||||
Self::pool_definition_id(),
|
||||
Self::token_b_definition_id(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@ -92,7 +92,7 @@ impl TryFrom<&Data> for TokenDefinition {
|
||||
type Error = std::io::Error;
|
||||
|
||||
fn try_from(data: &Data) -> Result<Self, Self::Error> {
|
||||
TokenDefinition::try_from_slice(data.as_ref())
|
||||
Self::try_from_slice(data.as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
@ -104,7 +104,7 @@ impl From<&TokenDefinition> for Data {
|
||||
BorshSerialize::serialize(definition, &mut data)
|
||||
.expect("Serialization to Vec should not fail");
|
||||
|
||||
Data::try_from(data).expect("Token definition encoded data should fit into Data")
|
||||
Self::try_from(data).expect("Token definition encoded data should fit into Data")
|
||||
}
|
||||
}
|
||||
|
||||
@ -128,17 +128,17 @@ pub enum TokenHolding {
|
||||
|
||||
impl TokenHolding {
|
||||
#[must_use]
|
||||
pub fn zeroized_clone_from(other: &Self) -> Self {
|
||||
pub const fn zeroized_clone_from(other: &Self) -> Self {
|
||||
match other {
|
||||
TokenHolding::Fungible { definition_id, .. } => TokenHolding::Fungible {
|
||||
Self::Fungible { definition_id, .. } => Self::Fungible {
|
||||
definition_id: *definition_id,
|
||||
balance: 0,
|
||||
},
|
||||
TokenHolding::NftMaster { definition_id, .. } => TokenHolding::NftMaster {
|
||||
Self::NftMaster { definition_id, .. } => Self::NftMaster {
|
||||
definition_id: *definition_id,
|
||||
print_balance: 0,
|
||||
},
|
||||
TokenHolding::NftPrintedCopy { definition_id, .. } => TokenHolding::NftPrintedCopy {
|
||||
Self::NftPrintedCopy { definition_id, .. } => Self::NftPrintedCopy {
|
||||
definition_id: *definition_id,
|
||||
owned: false,
|
||||
},
|
||||
@ -146,16 +146,16 @@ impl TokenHolding {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn zeroized_from_definition(
|
||||
pub const fn zeroized_from_definition(
|
||||
definition_id: AccountId,
|
||||
definition: &TokenDefinition,
|
||||
) -> Self {
|
||||
match definition {
|
||||
TokenDefinition::Fungible { .. } => TokenHolding::Fungible {
|
||||
TokenDefinition::Fungible { .. } => Self::Fungible {
|
||||
definition_id,
|
||||
balance: 0,
|
||||
},
|
||||
TokenDefinition::NonFungible { .. } => TokenHolding::NftPrintedCopy {
|
||||
TokenDefinition::NonFungible { .. } => Self::NftPrintedCopy {
|
||||
definition_id,
|
||||
owned: false,
|
||||
},
|
||||
@ -163,11 +163,11 @@ impl TokenHolding {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn definition_id(&self) -> AccountId {
|
||||
pub const fn definition_id(&self) -> AccountId {
|
||||
match self {
|
||||
TokenHolding::Fungible { definition_id, .. }
|
||||
| TokenHolding::NftMaster { definition_id, .. }
|
||||
| TokenHolding::NftPrintedCopy { definition_id, .. } => *definition_id,
|
||||
Self::Fungible { definition_id, .. }
|
||||
| Self::NftMaster { definition_id, .. }
|
||||
| Self::NftPrintedCopy { definition_id, .. } => *definition_id,
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -176,7 +176,7 @@ impl TryFrom<&Data> for TokenHolding {
|
||||
type Error = std::io::Error;
|
||||
|
||||
fn try_from(data: &Data) -> Result<Self, Self::Error> {
|
||||
TokenHolding::try_from_slice(data.as_ref())
|
||||
Self::try_from_slice(data.as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
@ -188,7 +188,7 @@ impl From<&TokenHolding> for Data {
|
||||
BorshSerialize::serialize(holding, &mut data)
|
||||
.expect("Serialization to Vec should not fail");
|
||||
|
||||
Data::try_from(data).expect("Token holding encoded data should fit into Data")
|
||||
Self::try_from(data).expect("Token holding encoded data should fit into Data")
|
||||
}
|
||||
}
|
||||
|
||||
@ -227,7 +227,7 @@ impl TryFrom<&Data> for TokenMetadata {
|
||||
type Error = std::io::Error;
|
||||
|
||||
fn try_from(data: &Data) -> Result<Self, Self::Error> {
|
||||
TokenMetadata::try_from_slice(data.as_ref())
|
||||
Self::try_from_slice(data.as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
@ -239,6 +239,6 @@ impl From<&TokenMetadata> for Data {
|
||||
BorshSerialize::serialize(metadata, &mut data)
|
||||
.expect("Serialization to Vec should not fail");
|
||||
|
||||
Data::try_from(data).expect("Token metadata encoded data should fit into Data")
|
||||
Self::try_from(data).expect("Token metadata encoded data should fit into Data")
|
||||
}
|
||||
}
|
||||
|
||||
@ -72,11 +72,11 @@ impl SequencerStore {
|
||||
Ok(self.dbio.latest_block_meta()?)
|
||||
}
|
||||
|
||||
pub fn genesis_id(&self) -> u64 {
|
||||
pub const fn genesis_id(&self) -> u64 {
|
||||
self.genesis_id
|
||||
}
|
||||
|
||||
pub fn signing_key(&self) -> &nssa::PrivateKey {
|
||||
pub const fn signing_key(&self) -> &nssa::PrivateKey {
|
||||
&self.signing_key
|
||||
}
|
||||
|
||||
@ -201,7 +201,7 @@ mod tests {
|
||||
|
||||
// Add a new block
|
||||
let tx = common::test_utils::produce_dummy_empty_transaction();
|
||||
let block = common::test_utils::produce_dummy_block(1, None, vec![tx.clone()]);
|
||||
let block = common::test_utils::produce_dummy_block(1, None, vec![tx]);
|
||||
let block_hash = block.header.hash;
|
||||
let block_msg_id = [1; 32];
|
||||
|
||||
@ -237,7 +237,7 @@ mod tests {
|
||||
|
||||
// Add a new block with Pending status
|
||||
let tx = common::test_utils::produce_dummy_empty_transaction();
|
||||
let block = common::test_utils::produce_dummy_block(1, None, vec![tx.clone()]);
|
||||
let block = common::test_utils::produce_dummy_block(1, None, vec![tx]);
|
||||
let block_id = block.header.block_id;
|
||||
|
||||
let dummy_state = V02State::new_with_genesis_accounts(&[], &[]);
|
||||
|
||||
@ -69,7 +69,7 @@ pub struct BedrockConfig {
|
||||
}
|
||||
|
||||
impl SequencerConfig {
|
||||
pub fn from_path(config_home: &Path) -> Result<SequencerConfig> {
|
||||
pub fn from_path(config_home: &Path) -> Result<Self> {
|
||||
let file = File::open(config_home)?;
|
||||
let reader = BufReader::new(file);
|
||||
|
||||
@ -77,6 +77,6 @@ impl SequencerConfig {
|
||||
}
|
||||
}
|
||||
|
||||
fn default_max_block_size() -> ByteSize {
|
||||
const fn default_max_block_size() -> ByteSize {
|
||||
ByteSize::mib(1)
|
||||
}
|
||||
|
||||
@ -281,19 +281,19 @@ impl<BC: BlockSettlementClientTrait, IC: IndexerClientTrait> SequencerCore<BC, I
|
||||
Ok((tx, msg_id))
|
||||
}
|
||||
|
||||
pub fn state(&self) -> &nssa::V02State {
|
||||
pub const fn state(&self) -> &nssa::V02State {
|
||||
&self.state
|
||||
}
|
||||
|
||||
pub fn block_store(&self) -> &SequencerStore {
|
||||
pub const fn block_store(&self) -> &SequencerStore {
|
||||
&self.store
|
||||
}
|
||||
|
||||
pub fn chain_height(&self) -> u64 {
|
||||
pub const fn chain_height(&self) -> u64 {
|
||||
self.chain_height
|
||||
}
|
||||
|
||||
pub fn sequencer_config(&self) -> &SequencerConfig {
|
||||
pub const fn sequencer_config(&self) -> &SequencerConfig {
|
||||
&self.sequencer_config
|
||||
}
|
||||
|
||||
@ -302,20 +302,17 @@ impl<BC: BlockSettlementClientTrait, IC: IndexerClientTrait> SequencerCore<BC, I
|
||||
/// All pending blocks with an ID less than or equal to `last_finalized_block_id`
|
||||
/// are removed from the database.
|
||||
pub fn clean_finalized_blocks_from_db(&mut self, last_finalized_block_id: u64) -> Result<()> {
|
||||
if let Some(first_pending_block_id) = self
|
||||
.get_pending_blocks()?
|
||||
self.get_pending_blocks()?
|
||||
.iter()
|
||||
.map(|block| block.header.block_id)
|
||||
.min()
|
||||
{
|
||||
info!("Clearing pending blocks up to id: {last_finalized_block_id}");
|
||||
// TODO: Delete blocks instead of marking them as finalized.
|
||||
// Current approach is used because we still have `GetBlockDataRequest`.
|
||||
(first_pending_block_id..=last_finalized_block_id)
|
||||
.try_for_each(|id| self.store.mark_block_as_finalized(id))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
.map_or(Ok(()), |first_pending_block_id| {
|
||||
info!("Clearing pending blocks up to id: {last_finalized_block_id}");
|
||||
// TODO: Delete blocks instead of marking them as finalized.
|
||||
// Current approach is used because we still have `GetBlockDataRequest`.
|
||||
(first_pending_block_id..=last_finalized_block_id)
|
||||
.try_for_each(|id| self.store.mark_block_as_finalized(id))
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns the list of stored pending blocks.
|
||||
|
||||
@ -42,13 +42,10 @@ fn respond<T: Serialize>(val: T) -> Result<Value, RpcErr> {
|
||||
|
||||
#[must_use]
|
||||
pub fn rpc_error_responce_inverter(err: RpcError) -> RpcError {
|
||||
let mut content: Option<Value> = None;
|
||||
if err.error_struct.is_some() {
|
||||
content = match err.error_struct.clone().unwrap() {
|
||||
RpcErrorKind::HandlerError(val) | RpcErrorKind::InternalError(val) => Some(val),
|
||||
RpcErrorKind::RequestValidationError(vall) => Some(serde_json::to_value(vall).unwrap()),
|
||||
};
|
||||
}
|
||||
let content = err.error_struct.map(|error| match error {
|
||||
RpcErrorKind::HandlerError(val) | RpcErrorKind::InternalError(val) => val,
|
||||
RpcErrorKind::RequestValidationError(vall) => serde_json::to_value(vall).unwrap(),
|
||||
});
|
||||
RpcError {
|
||||
error_struct: None,
|
||||
code: err.code,
|
||||
|
||||
@ -80,7 +80,7 @@ impl SequencerHandle {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn addr(&self) -> SocketAddr {
|
||||
pub const fn addr(&self) -> SocketAddr {
|
||||
self.addr
|
||||
}
|
||||
}
|
||||
|
||||
@ -18,7 +18,7 @@ pub enum DbError {
|
||||
|
||||
impl DbError {
|
||||
#[must_use]
|
||||
pub fn rocksdb_cast_message(rerr: rocksdb::Error, message: Option<String>) -> Self {
|
||||
pub const fn rocksdb_cast_message(rerr: rocksdb::Error, message: Option<String>) -> Self {
|
||||
Self::RocksDbError {
|
||||
error: rerr,
|
||||
additional_info: message,
|
||||
@ -26,7 +26,7 @@ impl DbError {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn borsh_cast_message(berr: borsh::io::Error, message: Option<String>) -> Self {
|
||||
pub const fn borsh_cast_message(berr: borsh::io::Error, message: Option<String>) -> Self {
|
||||
Self::SerializationError {
|
||||
error: berr,
|
||||
additional_info: message,
|
||||
@ -34,7 +34,7 @@ impl DbError {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn db_interaction_error(message: String) -> Self {
|
||||
pub const fn db_interaction_error(message: String) -> Self {
|
||||
Self::DbInteractionError {
|
||||
additional_info: message,
|
||||
}
|
||||
|
||||
@ -92,10 +92,7 @@ impl RocksDBIO {
|
||||
let dbio = Self { db };
|
||||
|
||||
let is_start_set = dbio.get_meta_is_first_block_set()?;
|
||||
|
||||
if is_start_set {
|
||||
Ok(dbio)
|
||||
} else {
|
||||
if !is_start_set {
|
||||
let block_id = genesis_block.header.block_id;
|
||||
dbio.put_meta_last_block_in_db(block_id)?;
|
||||
dbio.put_meta_first_block_in_db(genesis_block)?;
|
||||
@ -104,9 +101,9 @@ impl RocksDBIO {
|
||||
// First breakpoint setup
|
||||
dbio.put_breakpoint(0, initial_state)?;
|
||||
dbio.put_meta_last_breakpoint_id(0)?;
|
||||
|
||||
Ok(dbio)
|
||||
}
|
||||
|
||||
Ok(dbio)
|
||||
}
|
||||
|
||||
pub fn destroy(path: &Path) -> DbResult<()> {
|
||||
@ -494,7 +491,7 @@ impl RocksDBIO {
|
||||
acc_to_tx_map
|
||||
.entry(acc_id)
|
||||
.and_modify(|tx_hashes| tx_hashes.push(tx_hash.into()))
|
||||
.or_insert(vec![tx_hash.into()]);
|
||||
.or_insert_with(|| vec![tx_hash.into()]);
|
||||
}
|
||||
}
|
||||
|
||||
@ -932,10 +929,12 @@ impl RocksDBIO {
|
||||
.transactions
|
||||
.iter()
|
||||
.find(|tx| tx.hash().0 == tx_hash)
|
||||
.ok_or(DbError::db_interaction_error(format!(
|
||||
"Missing transaction in block {} with hash {:#?}",
|
||||
block.header.block_id, tx_hash
|
||||
)))?;
|
||||
.ok_or_else(|| {
|
||||
DbError::db_interaction_error(format!(
|
||||
"Missing transaction in block {} with hash {:#?}",
|
||||
block.header.block_id, tx_hash
|
||||
))
|
||||
})?;
|
||||
|
||||
tx_batch.push(transaction.clone());
|
||||
}
|
||||
@ -993,17 +992,15 @@ mod tests {
|
||||
fn transfer(amount: u128, nonce: u128, direction: bool) -> NSSATransaction {
|
||||
let from;
|
||||
let to;
|
||||
let sign_key;
|
||||
|
||||
if direction {
|
||||
let sign_key = if direction {
|
||||
from = acc1();
|
||||
to = acc2();
|
||||
sign_key = acc1_sign_key();
|
||||
acc1_sign_key()
|
||||
} else {
|
||||
from = acc2();
|
||||
to = acc1();
|
||||
sign_key = acc2_sign_key();
|
||||
}
|
||||
acc2_sign_key()
|
||||
};
|
||||
|
||||
common::test_utils::create_transaction_native_token_transfer(
|
||||
from, nonce, to, amount, &sign_key,
|
||||
|
||||
@ -76,10 +76,7 @@ impl RocksDBIO {
|
||||
let dbio = Self { db };
|
||||
|
||||
let is_start_set = dbio.get_meta_is_first_block_set()?;
|
||||
|
||||
if is_start_set {
|
||||
Ok(dbio)
|
||||
} else {
|
||||
if !is_start_set {
|
||||
let block_id = genesis_block.header.block_id;
|
||||
dbio.put_meta_first_block_in_db(genesis_block, genesis_msg_id)?;
|
||||
dbio.put_meta_is_first_block_set()?;
|
||||
@ -90,9 +87,9 @@ impl RocksDBIO {
|
||||
hash: genesis_block.header.hash,
|
||||
msg_id: genesis_msg_id,
|
||||
})?;
|
||||
|
||||
Ok(dbio)
|
||||
}
|
||||
|
||||
Ok(dbio)
|
||||
}
|
||||
|
||||
pub fn destroy(path: &Path) -> DbResult<()> {
|
||||
|
||||
@ -36,7 +36,7 @@ fn main() {
|
||||
let chained_call = ChainedCall {
|
||||
program_id: transfer_program_id,
|
||||
instruction_data,
|
||||
pre_states: vec![authorised_sender.clone(), receiver.clone()],
|
||||
pre_states: vec![authorised_sender, receiver.clone()],
|
||||
pda_seeds: vec![],
|
||||
};
|
||||
|
||||
|
||||
@ -47,7 +47,7 @@ pub enum WalletFfiError {
|
||||
impl WalletFfiError {
|
||||
/// Check if it's [`WalletFfiError::Success`] or panic.
|
||||
pub fn unwrap(self) {
|
||||
let WalletFfiError::Success = self else {
|
||||
let Self::Success = self else {
|
||||
panic!("Called `unwrap()` on error value `{self:#?}`");
|
||||
};
|
||||
}
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
use core::slice;
|
||||
use std::{ffi::c_char, ptr};
|
||||
|
||||
use nssa::{Account, Data};
|
||||
use nssa::Data;
|
||||
use nssa_core::encryption::shared_key_derivation::Secp256k1Point;
|
||||
|
||||
use crate::error::WalletFfiError;
|
||||
@ -143,20 +143,20 @@ impl Default for FfiTransferResult {
|
||||
impl FfiBytes32 {
|
||||
/// Create from a 32-byte array.
|
||||
#[must_use]
|
||||
pub fn from_bytes(bytes: [u8; 32]) -> Self {
|
||||
pub const fn from_bytes(bytes: [u8; 32]) -> Self {
|
||||
Self { data: bytes }
|
||||
}
|
||||
|
||||
/// Create from an `AccountId`.
|
||||
#[must_use]
|
||||
pub fn from_account_id(id: &nssa::AccountId) -> Self {
|
||||
pub const fn from_account_id(id: &nssa::AccountId) -> Self {
|
||||
Self { data: *id.value() }
|
||||
}
|
||||
}
|
||||
|
||||
impl FfiPrivateAccountKeys {
|
||||
#[must_use]
|
||||
pub fn npk(&self) -> nssa_core::NullifierPublicKey {
|
||||
pub const fn npk(&self) -> nssa_core::NullifierPublicKey {
|
||||
nssa_core::NullifierPublicKey(self.nullifier_public_key.data)
|
||||
}
|
||||
|
||||
@ -182,7 +182,7 @@ impl From<u128> for FfiU128 {
|
||||
|
||||
impl From<FfiU128> for u128 {
|
||||
fn from(value: FfiU128) -> Self {
|
||||
u128::from_le_bytes(value.data)
|
||||
Self::from_le_bytes(value.data)
|
||||
}
|
||||
}
|
||||
|
||||
@ -194,7 +194,7 @@ impl From<&nssa::AccountId> for FfiBytes32 {
|
||||
|
||||
impl From<FfiBytes32> for nssa::AccountId {
|
||||
fn from(bytes: FfiBytes32) -> Self {
|
||||
nssa::AccountId::new(bytes.data)
|
||||
Self::new(bytes.data)
|
||||
}
|
||||
}
|
||||
|
||||
@ -217,7 +217,7 @@ impl From<nssa::Account> for FfiAccount {
|
||||
let program_owner = FfiProgramId {
|
||||
data: value.program_owner,
|
||||
};
|
||||
FfiAccount {
|
||||
Self {
|
||||
program_owner,
|
||||
balance: value.balance.into(),
|
||||
data,
|
||||
@ -240,7 +240,7 @@ impl TryFrom<&FfiAccount> for nssa::Account {
|
||||
} else {
|
||||
Data::default()
|
||||
};
|
||||
Ok(Account {
|
||||
Ok(Self {
|
||||
program_owner: value.program_owner.data,
|
||||
balance: value.balance.into(),
|
||||
data,
|
||||
@ -261,7 +261,7 @@ impl TryFrom<&FfiPublicAccountKey> for nssa::PublicKey {
|
||||
type Error = WalletFfiError;
|
||||
|
||||
fn try_from(value: &FfiPublicAccountKey) -> Result<Self, Self::Error> {
|
||||
let public_key = nssa::PublicKey::try_new(value.public_key.data)
|
||||
let public_key = Self::try_new(value.public_key.data)
|
||||
.map_err(|_err| WalletFfiError::InvalidTypeConversion)?;
|
||||
Ok(public_key)
|
||||
}
|
||||
|
||||
@ -298,6 +298,6 @@ mod tests {
|
||||
let config = create_sample_wallet_config();
|
||||
let accs = create_sample_persistent_accounts();
|
||||
|
||||
let _ = WalletChainStore::new(config.clone(), accs, HashMap::new()).unwrap();
|
||||
let _ = WalletChainStore::new(config, accs, HashMap::new()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
use anyhow::Result;
|
||||
use anyhow::{Context as _, Result};
|
||||
use clap::Subcommand;
|
||||
use itertools::Itertools as _;
|
||||
use key_protocol::key_management::key_tree::chain_index::ChainIndex;
|
||||
@ -79,7 +79,7 @@ impl WalletSubcommand for NewSubcommand {
|
||||
wallet_core: &mut WalletCore,
|
||||
) -> Result<SubcommandReturnValue> {
|
||||
match self {
|
||||
NewSubcommand::Public { cci, label } => {
|
||||
Self::Public { cci, label } => {
|
||||
if let Some(label) = &label
|
||||
&& wallet_core
|
||||
.storage
|
||||
@ -116,7 +116,7 @@ impl WalletSubcommand for NewSubcommand {
|
||||
|
||||
Ok(SubcommandReturnValue::RegisterAccount { account_id })
|
||||
}
|
||||
NewSubcommand::Private { cci, label } => {
|
||||
Self::Private { cci, label } => {
|
||||
if let Some(label) = &label
|
||||
&& wallet_core
|
||||
.storage
|
||||
@ -166,7 +166,7 @@ impl WalletSubcommand for AccountSubcommand {
|
||||
wallet_core: &mut WalletCore,
|
||||
) -> Result<SubcommandReturnValue> {
|
||||
match self {
|
||||
AccountSubcommand::Get {
|
||||
Self::Get {
|
||||
raw,
|
||||
keys,
|
||||
account_id,
|
||||
@ -185,7 +185,7 @@ impl WalletSubcommand for AccountSubcommand {
|
||||
}
|
||||
AccountPrivacyKind::Private => wallet_core
|
||||
.get_account_private(account_id)
|
||||
.ok_or(anyhow::anyhow!("Private account not found in storage"))?,
|
||||
.context("Private account not found in storage")?,
|
||||
};
|
||||
|
||||
// Helper closure to display keys for the account
|
||||
@ -196,7 +196,7 @@ impl WalletSubcommand for AccountSubcommand {
|
||||
.storage
|
||||
.user_data
|
||||
.get_pub_account_signing_key(account_id)
|
||||
.ok_or(anyhow::anyhow!("Public account not found in storage"))?;
|
||||
.context("Public account not found in storage")?;
|
||||
|
||||
let public_key = PublicKey::new_from_private_key(private_key);
|
||||
println!("pk {}", hex::encode(public_key.value()));
|
||||
@ -206,7 +206,7 @@ impl WalletSubcommand for AccountSubcommand {
|
||||
.storage
|
||||
.user_data
|
||||
.get_private_account(account_id)
|
||||
.ok_or(anyhow::anyhow!("Private account not found in storage"))?;
|
||||
.context("Private account not found in storage")?;
|
||||
|
||||
println!("npk {}", hex::encode(key.nullifer_public_key.0));
|
||||
println!("vpk {}", hex::encode(key.viewing_public_key.to_bytes()));
|
||||
@ -226,7 +226,7 @@ impl WalletSubcommand for AccountSubcommand {
|
||||
}
|
||||
|
||||
if raw {
|
||||
let account_hr: HumanReadableAccount = account.clone().into();
|
||||
let account_hr: HumanReadableAccount = account.into();
|
||||
println!("{}", serde_json::to_string(&account_hr).unwrap());
|
||||
|
||||
return Ok(SubcommandReturnValue::Empty);
|
||||
@ -242,10 +242,8 @@ impl WalletSubcommand for AccountSubcommand {
|
||||
|
||||
Ok(SubcommandReturnValue::Empty)
|
||||
}
|
||||
AccountSubcommand::New(new_subcommand) => {
|
||||
new_subcommand.handle_subcommand(wallet_core).await
|
||||
}
|
||||
AccountSubcommand::SyncPrivate => {
|
||||
Self::New(new_subcommand) => new_subcommand.handle_subcommand(wallet_core).await,
|
||||
Self::SyncPrivate => {
|
||||
let curr_last_block = wallet_core
|
||||
.sequencer_client
|
||||
.get_last_block()
|
||||
@ -268,17 +266,15 @@ impl WalletSubcommand for AccountSubcommand {
|
||||
|
||||
Ok(SubcommandReturnValue::SyncedToBlock(curr_last_block))
|
||||
}
|
||||
AccountSubcommand::List { long } => {
|
||||
Self::List { long } => {
|
||||
let user_data = &wallet_core.storage.user_data;
|
||||
let labels = &wallet_core.storage.labels;
|
||||
|
||||
let format_with_label = |prefix: &str, id: nssa::AccountId| {
|
||||
let id_str = id.to_string();
|
||||
if let Some(label) = labels.get(&id_str) {
|
||||
format!("{prefix} [{label}]")
|
||||
} else {
|
||||
prefix.to_owned()
|
||||
}
|
||||
labels
|
||||
.get(&id_str)
|
||||
.map_or_else(|| prefix.to_owned(), |label| format!("{prefix} [{label}]"))
|
||||
};
|
||||
|
||||
if !long {
|
||||
@ -378,7 +374,7 @@ impl WalletSubcommand for AccountSubcommand {
|
||||
|
||||
Ok(SubcommandReturnValue::Empty)
|
||||
}
|
||||
AccountSubcommand::Label { account_id, label } => {
|
||||
Self::Label { account_id, label } => {
|
||||
let (account_id_str, _) = parse_addr_with_privacy_prefix(&account_id)?;
|
||||
|
||||
// Check if label is already used by a different account
|
||||
@ -422,29 +418,32 @@ fn format_account_details(account: &Account) -> (String, String) {
|
||||
o if *o == auth_tr_prog_id => {
|
||||
let account_hr: HumanReadableAccount = account.clone().into();
|
||||
(
|
||||
"Account owned by authenticated transfer program".to_string(),
|
||||
"Account owned by authenticated transfer program".to_owned(),
|
||||
serde_json::to_string(&account_hr).unwrap(),
|
||||
)
|
||||
}
|
||||
o if *o == token_prog_id => {
|
||||
if let Ok(token_def) = TokenDefinition::try_from(&account.data) {
|
||||
o if *o == token_prog_id => TokenDefinition::try_from(&account.data)
|
||||
.map(|token_def| {
|
||||
(
|
||||
"Definition account owned by token program".to_owned(),
|
||||
serde_json::to_string(&token_def).unwrap(),
|
||||
)
|
||||
} else if let Ok(token_hold) = TokenHolding::try_from(&account.data) {
|
||||
(
|
||||
"Holding account owned by token program".to_string(),
|
||||
serde_json::to_string(&token_hold).unwrap(),
|
||||
)
|
||||
} else {
|
||||
})
|
||||
.or_else(|_| {
|
||||
TokenHolding::try_from(&account.data).map(|token_hold| {
|
||||
(
|
||||
"Holding account owned by token program".to_owned(),
|
||||
serde_json::to_string(&token_hold).unwrap(),
|
||||
)
|
||||
})
|
||||
})
|
||||
.unwrap_or_else(|_| {
|
||||
let account_hr: HumanReadableAccount = account.clone().into();
|
||||
(
|
||||
"Unknown token program account".to_owned(),
|
||||
serde_json::to_string(&account_hr).unwrap(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}),
|
||||
_ => {
|
||||
let account_hr: HumanReadableAccount = account.clone().into();
|
||||
(
|
||||
|
||||
@ -31,17 +31,17 @@ impl WalletSubcommand for ChainSubcommand {
|
||||
wallet_core: &mut WalletCore,
|
||||
) -> Result<SubcommandReturnValue> {
|
||||
match self {
|
||||
ChainSubcommand::CurrentBlockId => {
|
||||
Self::CurrentBlockId => {
|
||||
let latest_block_res = wallet_core.sequencer_client.get_last_block().await?;
|
||||
|
||||
println!("Last block id is {}", latest_block_res.last_block);
|
||||
}
|
||||
ChainSubcommand::Block { id } => {
|
||||
Self::Block { id } => {
|
||||
let block_res = wallet_core.sequencer_client.get_block(id).await?;
|
||||
|
||||
println!("Last block id is {:#?}", block_res.block);
|
||||
}
|
||||
ChainSubcommand::Transaction { hash } => {
|
||||
Self::Transaction { hash } => {
|
||||
let tx_res = wallet_core
|
||||
.sequencer_client
|
||||
.get_transaction_by_hash(hash)
|
||||
|
||||
@ -29,7 +29,7 @@ impl WalletSubcommand for ConfigSubcommand {
|
||||
wallet_core: &mut WalletCore,
|
||||
) -> Result<SubcommandReturnValue> {
|
||||
match self {
|
||||
ConfigSubcommand::Get { all, key } => {
|
||||
Self::Get { all, key } => {
|
||||
if all {
|
||||
let config_str =
|
||||
serde_json::to_string_pretty(&wallet_core.storage.wallet_config)?;
|
||||
@ -86,7 +86,7 @@ impl WalletSubcommand for ConfigSubcommand {
|
||||
println!("Please provide a key or use --all flag");
|
||||
}
|
||||
}
|
||||
ConfigSubcommand::Set { key, value } => {
|
||||
Self::Set { key, value } => {
|
||||
match key.as_str() {
|
||||
"override_rust_log" => {
|
||||
wallet_core.storage.wallet_config.override_rust_log = Some(value);
|
||||
@ -122,7 +122,7 @@ impl WalletSubcommand for ConfigSubcommand {
|
||||
|
||||
wallet_core.store_config_changes().await?;
|
||||
}
|
||||
ConfigSubcommand::Description { key } => match key.as_str() {
|
||||
Self::Description { key } => match key.as_str() {
|
||||
"override_rust_log" => {
|
||||
println!("Value of variable RUST_LOG to override, affects logging");
|
||||
}
|
||||
|
||||
@ -104,7 +104,7 @@ impl WalletSubcommand for AmmProgramAgnosticSubcommand {
|
||||
wallet_core: &mut WalletCore,
|
||||
) -> Result<SubcommandReturnValue> {
|
||||
match self {
|
||||
AmmProgramAgnosticSubcommand::New {
|
||||
Self::New {
|
||||
user_holding_a,
|
||||
user_holding_b,
|
||||
user_holding_lp,
|
||||
@ -150,7 +150,7 @@ impl WalletSubcommand for AmmProgramAgnosticSubcommand {
|
||||
}
|
||||
}
|
||||
}
|
||||
AmmProgramAgnosticSubcommand::Swap {
|
||||
Self::Swap {
|
||||
user_holding_a,
|
||||
user_holding_b,
|
||||
amount_in,
|
||||
@ -185,7 +185,7 @@ impl WalletSubcommand for AmmProgramAgnosticSubcommand {
|
||||
}
|
||||
}
|
||||
}
|
||||
AmmProgramAgnosticSubcommand::AddLiquidity {
|
||||
Self::AddLiquidity {
|
||||
user_holding_a,
|
||||
user_holding_b,
|
||||
user_holding_lp,
|
||||
@ -233,7 +233,7 @@ impl WalletSubcommand for AmmProgramAgnosticSubcommand {
|
||||
}
|
||||
}
|
||||
}
|
||||
AmmProgramAgnosticSubcommand::RemoveLiquidity {
|
||||
Self::RemoveLiquidity {
|
||||
user_holding_a,
|
||||
user_holding_b,
|
||||
user_holding_lp,
|
||||
|
||||
@ -51,7 +51,7 @@ impl WalletSubcommand for AuthTransferSubcommand {
|
||||
wallet_core: &mut WalletCore,
|
||||
) -> Result<SubcommandReturnValue> {
|
||||
match self {
|
||||
AuthTransferSubcommand::Init { account_id } => {
|
||||
Self::Init { account_id } => {
|
||||
let (account_id, addr_privacy) = parse_addr_with_privacy_prefix(&account_id)?;
|
||||
|
||||
match addr_privacy {
|
||||
@ -98,7 +98,7 @@ impl WalletSubcommand for AuthTransferSubcommand {
|
||||
|
||||
Ok(SubcommandReturnValue::Empty)
|
||||
}
|
||||
AuthTransferSubcommand::Send {
|
||||
Self::Send {
|
||||
from,
|
||||
to,
|
||||
to_npk,
|
||||
@ -307,7 +307,7 @@ impl WalletSubcommand for NativeTokenTransferProgramSubcommandPrivate {
|
||||
wallet_core: &mut WalletCore,
|
||||
) -> Result<SubcommandReturnValue> {
|
||||
match self {
|
||||
NativeTokenTransferProgramSubcommandPrivate::PrivateOwned { from, to, amount } => {
|
||||
Self::PrivateOwned { from, to, amount } => {
|
||||
let from: AccountId = from.parse().unwrap();
|
||||
let to: AccountId = to.parse().unwrap();
|
||||
|
||||
@ -333,7 +333,7 @@ impl WalletSubcommand for NativeTokenTransferProgramSubcommandPrivate {
|
||||
|
||||
Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash })
|
||||
}
|
||||
NativeTokenTransferProgramSubcommandPrivate::PrivateForeign {
|
||||
Self::PrivateForeign {
|
||||
from,
|
||||
to_npk,
|
||||
to_vpk,
|
||||
@ -383,7 +383,7 @@ impl WalletSubcommand for NativeTokenTransferProgramSubcommandShielded {
|
||||
wallet_core: &mut WalletCore,
|
||||
) -> Result<SubcommandReturnValue> {
|
||||
match self {
|
||||
NativeTokenTransferProgramSubcommandShielded::ShieldedOwned { from, to, amount } => {
|
||||
Self::ShieldedOwned { from, to, amount } => {
|
||||
let from: AccountId = from.parse().unwrap();
|
||||
let to: AccountId = to.parse().unwrap();
|
||||
|
||||
@ -409,7 +409,7 @@ impl WalletSubcommand for NativeTokenTransferProgramSubcommandShielded {
|
||||
|
||||
Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash })
|
||||
}
|
||||
NativeTokenTransferProgramSubcommandShielded::ShieldedForeign {
|
||||
Self::ShieldedForeign {
|
||||
from,
|
||||
to_npk,
|
||||
to_vpk,
|
||||
@ -450,13 +450,13 @@ impl WalletSubcommand for NativeTokenTransferProgramSubcommand {
|
||||
wallet_core: &mut WalletCore,
|
||||
) -> Result<SubcommandReturnValue> {
|
||||
match self {
|
||||
NativeTokenTransferProgramSubcommand::Private(private_subcommand) => {
|
||||
Self::Private(private_subcommand) => {
|
||||
private_subcommand.handle_subcommand(wallet_core).await
|
||||
}
|
||||
NativeTokenTransferProgramSubcommand::Shielded(shielded_subcommand) => {
|
||||
Self::Shielded(shielded_subcommand) => {
|
||||
shielded_subcommand.handle_subcommand(wallet_core).await
|
||||
}
|
||||
NativeTokenTransferProgramSubcommand::Deshielded { from, to, amount } => {
|
||||
Self::Deshielded { from, to, amount } => {
|
||||
let from: AccountId = from.parse().unwrap();
|
||||
let to: AccountId = to.parse().unwrap();
|
||||
|
||||
@ -482,7 +482,7 @@ impl WalletSubcommand for NativeTokenTransferProgramSubcommand {
|
||||
|
||||
Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash })
|
||||
}
|
||||
NativeTokenTransferProgramSubcommand::Public { from, to, amount } => {
|
||||
Self::Public { from, to, amount } => {
|
||||
let from: AccountId = from.parse().unwrap();
|
||||
let to: AccountId = to.parse().unwrap();
|
||||
|
||||
|
||||
@ -28,7 +28,7 @@ impl WalletSubcommand for PinataProgramAgnosticSubcommand {
|
||||
wallet_core: &mut WalletCore,
|
||||
) -> Result<SubcommandReturnValue> {
|
||||
let underlying_subcommand = match self {
|
||||
PinataProgramAgnosticSubcommand::Claim { to } => {
|
||||
Self::Claim { to } => {
|
||||
let (to, to_addr_privacy) = parse_addr_with_privacy_prefix(&to)?;
|
||||
|
||||
match to_addr_privacy {
|
||||
@ -99,7 +99,7 @@ impl WalletSubcommand for PinataProgramSubcommandPublic {
|
||||
wallet_core: &mut WalletCore,
|
||||
) -> Result<SubcommandReturnValue> {
|
||||
match self {
|
||||
PinataProgramSubcommandPublic::Claim {
|
||||
Self::Claim {
|
||||
pinata_account_id,
|
||||
winner_account_id,
|
||||
} => {
|
||||
@ -135,7 +135,7 @@ impl WalletSubcommand for PinataProgramSubcommandPrivate {
|
||||
wallet_core: &mut WalletCore,
|
||||
) -> Result<SubcommandReturnValue> {
|
||||
match self {
|
||||
PinataProgramSubcommandPrivate::ClaimPrivateOwned {
|
||||
Self::ClaimPrivateOwned {
|
||||
pinata_account_id,
|
||||
winner_account_id,
|
||||
} => {
|
||||
@ -182,10 +182,10 @@ impl WalletSubcommand for PinataProgramSubcommand {
|
||||
wallet_core: &mut WalletCore,
|
||||
) -> Result<SubcommandReturnValue> {
|
||||
match self {
|
||||
PinataProgramSubcommand::Private(private_subcommand) => {
|
||||
Self::Private(private_subcommand) => {
|
||||
private_subcommand.handle_subcommand(wallet_core).await
|
||||
}
|
||||
PinataProgramSubcommand::Public(public_subcommand) => {
|
||||
Self::Public(public_subcommand) => {
|
||||
public_subcommand.handle_subcommand(wallet_core).await
|
||||
}
|
||||
}
|
||||
|
||||
@ -100,7 +100,7 @@ impl WalletSubcommand for TokenProgramAgnosticSubcommand {
|
||||
wallet_core: &mut WalletCore,
|
||||
) -> Result<SubcommandReturnValue> {
|
||||
match self {
|
||||
TokenProgramAgnosticSubcommand::New {
|
||||
Self::New {
|
||||
definition_account_id,
|
||||
supply_account_id,
|
||||
name,
|
||||
@ -156,7 +156,7 @@ impl WalletSubcommand for TokenProgramAgnosticSubcommand {
|
||||
|
||||
underlying_subcommand.handle_subcommand(wallet_core).await
|
||||
}
|
||||
TokenProgramAgnosticSubcommand::Send {
|
||||
Self::Send {
|
||||
from,
|
||||
to,
|
||||
to_npk,
|
||||
@ -246,7 +246,7 @@ impl WalletSubcommand for TokenProgramAgnosticSubcommand {
|
||||
|
||||
underlying_subcommand.handle_subcommand(wallet_core).await
|
||||
}
|
||||
TokenProgramAgnosticSubcommand::Burn {
|
||||
Self::Burn {
|
||||
definition,
|
||||
holder,
|
||||
amount,
|
||||
@ -298,7 +298,7 @@ impl WalletSubcommand for TokenProgramAgnosticSubcommand {
|
||||
|
||||
underlying_subcommand.handle_subcommand(wallet_core).await
|
||||
}
|
||||
TokenProgramAgnosticSubcommand::Mint {
|
||||
Self::Mint {
|
||||
definition,
|
||||
holder,
|
||||
holder_npk,
|
||||
@ -653,7 +653,7 @@ impl WalletSubcommand for TokenProgramSubcommandPublic {
|
||||
wallet_core: &mut WalletCore,
|
||||
) -> Result<SubcommandReturnValue> {
|
||||
match self {
|
||||
TokenProgramSubcommandPublic::TransferToken {
|
||||
Self::TransferToken {
|
||||
sender_account_id,
|
||||
recipient_account_id,
|
||||
balance_to_move,
|
||||
@ -667,7 +667,7 @@ impl WalletSubcommand for TokenProgramSubcommandPublic {
|
||||
.await?;
|
||||
Ok(SubcommandReturnValue::Empty)
|
||||
}
|
||||
TokenProgramSubcommandPublic::BurnToken {
|
||||
Self::BurnToken {
|
||||
definition_account_id,
|
||||
holder_account_id,
|
||||
amount,
|
||||
@ -681,7 +681,7 @@ impl WalletSubcommand for TokenProgramSubcommandPublic {
|
||||
.await?;
|
||||
Ok(SubcommandReturnValue::Empty)
|
||||
}
|
||||
TokenProgramSubcommandPublic::MintToken {
|
||||
Self::MintToken {
|
||||
definition_account_id,
|
||||
holder_account_id,
|
||||
amount,
|
||||
@ -705,7 +705,7 @@ impl WalletSubcommand for TokenProgramSubcommandPrivate {
|
||||
wallet_core: &mut WalletCore,
|
||||
) -> Result<SubcommandReturnValue> {
|
||||
match self {
|
||||
TokenProgramSubcommandPrivate::TransferTokenPrivateOwned {
|
||||
Self::TransferTokenPrivateOwned {
|
||||
sender_account_id,
|
||||
recipient_account_id,
|
||||
balance_to_move,
|
||||
@ -742,7 +742,7 @@ impl WalletSubcommand for TokenProgramSubcommandPrivate {
|
||||
|
||||
Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash })
|
||||
}
|
||||
TokenProgramSubcommandPrivate::TransferTokenPrivateForeign {
|
||||
Self::TransferTokenPrivateForeign {
|
||||
sender_account_id,
|
||||
recipient_npk,
|
||||
recipient_vpk,
|
||||
@ -788,7 +788,7 @@ impl WalletSubcommand for TokenProgramSubcommandPrivate {
|
||||
|
||||
Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash })
|
||||
}
|
||||
TokenProgramSubcommandPrivate::BurnTokenPrivateOwned {
|
||||
Self::BurnTokenPrivateOwned {
|
||||
definition_account_id,
|
||||
holder_account_id,
|
||||
amount,
|
||||
@ -825,7 +825,7 @@ impl WalletSubcommand for TokenProgramSubcommandPrivate {
|
||||
|
||||
Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash })
|
||||
}
|
||||
TokenProgramSubcommandPrivate::MintTokenPrivateOwned {
|
||||
Self::MintTokenPrivateOwned {
|
||||
definition_account_id,
|
||||
holder_account_id,
|
||||
amount,
|
||||
@ -862,7 +862,7 @@ impl WalletSubcommand for TokenProgramSubcommandPrivate {
|
||||
|
||||
Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash })
|
||||
}
|
||||
TokenProgramSubcommandPrivate::MintTokenPrivateForeign {
|
||||
Self::MintTokenPrivateForeign {
|
||||
definition_account_id,
|
||||
holder_npk,
|
||||
holder_vpk,
|
||||
@ -919,7 +919,7 @@ impl WalletSubcommand for TokenProgramSubcommandDeshielded {
|
||||
wallet_core: &mut WalletCore,
|
||||
) -> Result<SubcommandReturnValue> {
|
||||
match self {
|
||||
TokenProgramSubcommandDeshielded::TransferTokenDeshielded {
|
||||
Self::TransferTokenDeshielded {
|
||||
sender_account_id,
|
||||
recipient_account_id,
|
||||
balance_to_move,
|
||||
@ -953,7 +953,7 @@ impl WalletSubcommand for TokenProgramSubcommandDeshielded {
|
||||
|
||||
Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash })
|
||||
}
|
||||
TokenProgramSubcommandDeshielded::BurnTokenDeshieldedOwned {
|
||||
Self::BurnTokenDeshieldedOwned {
|
||||
definition_account_id,
|
||||
holder_account_id,
|
||||
amount,
|
||||
@ -987,7 +987,7 @@ impl WalletSubcommand for TokenProgramSubcommandDeshielded {
|
||||
|
||||
Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash })
|
||||
}
|
||||
TokenProgramSubcommandDeshielded::MintTokenDeshielded {
|
||||
Self::MintTokenDeshielded {
|
||||
definition_account_id,
|
||||
holder_account_id,
|
||||
amount,
|
||||
@ -1031,7 +1031,7 @@ impl WalletSubcommand for TokenProgramSubcommandShielded {
|
||||
wallet_core: &mut WalletCore,
|
||||
) -> Result<SubcommandReturnValue> {
|
||||
match self {
|
||||
TokenProgramSubcommandShielded::TransferTokenShieldedForeign {
|
||||
Self::TransferTokenShieldedForeign {
|
||||
sender_account_id,
|
||||
recipient_npk,
|
||||
recipient_vpk,
|
||||
@ -1072,7 +1072,7 @@ impl WalletSubcommand for TokenProgramSubcommandShielded {
|
||||
|
||||
Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash })
|
||||
}
|
||||
TokenProgramSubcommandShielded::TransferTokenShieldedOwned {
|
||||
Self::TransferTokenShieldedOwned {
|
||||
sender_account_id,
|
||||
recipient_account_id,
|
||||
balance_to_move,
|
||||
@ -1106,7 +1106,7 @@ impl WalletSubcommand for TokenProgramSubcommandShielded {
|
||||
|
||||
Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash })
|
||||
}
|
||||
TokenProgramSubcommandShielded::BurnTokenShielded {
|
||||
Self::BurnTokenShielded {
|
||||
definition_account_id,
|
||||
holder_account_id,
|
||||
amount,
|
||||
@ -1140,7 +1140,7 @@ impl WalletSubcommand for TokenProgramSubcommandShielded {
|
||||
|
||||
Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash })
|
||||
}
|
||||
TokenProgramSubcommandShielded::MintTokenShieldedOwned {
|
||||
Self::MintTokenShieldedOwned {
|
||||
definition_account_id,
|
||||
holder_account_id,
|
||||
amount,
|
||||
@ -1174,7 +1174,7 @@ impl WalletSubcommand for TokenProgramSubcommandShielded {
|
||||
|
||||
Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash })
|
||||
}
|
||||
TokenProgramSubcommandShielded::MintTokenShieldedForeign {
|
||||
Self::MintTokenShieldedForeign {
|
||||
definition_account_id,
|
||||
holder_npk,
|
||||
holder_vpk,
|
||||
@ -1226,7 +1226,7 @@ impl WalletSubcommand for CreateNewTokenProgramSubcommand {
|
||||
wallet_core: &mut WalletCore,
|
||||
) -> Result<SubcommandReturnValue> {
|
||||
match self {
|
||||
CreateNewTokenProgramSubcommand::NewPrivateDefPrivateSupp {
|
||||
Self::NewPrivateDefPrivateSupp {
|
||||
definition_account_id,
|
||||
supply_account_id,
|
||||
name,
|
||||
@ -1265,7 +1265,7 @@ impl WalletSubcommand for CreateNewTokenProgramSubcommand {
|
||||
|
||||
Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash })
|
||||
}
|
||||
CreateNewTokenProgramSubcommand::NewPrivateDefPublicSupp {
|
||||
Self::NewPrivateDefPublicSupp {
|
||||
definition_account_id,
|
||||
supply_account_id,
|
||||
name,
|
||||
@ -1301,7 +1301,7 @@ impl WalletSubcommand for CreateNewTokenProgramSubcommand {
|
||||
|
||||
Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash })
|
||||
}
|
||||
CreateNewTokenProgramSubcommand::NewPublicDefPrivateSupp {
|
||||
Self::NewPublicDefPrivateSupp {
|
||||
definition_account_id,
|
||||
supply_account_id,
|
||||
name,
|
||||
@ -1337,7 +1337,7 @@ impl WalletSubcommand for CreateNewTokenProgramSubcommand {
|
||||
|
||||
Ok(SubcommandReturnValue::PrivacyPreservingTransfer { tx_hash })
|
||||
}
|
||||
CreateNewTokenProgramSubcommand::NewPublicDefPublicSupp {
|
||||
Self::NewPublicDefPublicSupp {
|
||||
definition_account_id,
|
||||
supply_account_id,
|
||||
name,
|
||||
@ -1363,19 +1363,19 @@ impl WalletSubcommand for TokenProgramSubcommand {
|
||||
wallet_core: &mut WalletCore,
|
||||
) -> Result<SubcommandReturnValue> {
|
||||
match self {
|
||||
TokenProgramSubcommand::Create(creation_subcommand) => {
|
||||
Self::Create(creation_subcommand) => {
|
||||
creation_subcommand.handle_subcommand(wallet_core).await
|
||||
}
|
||||
TokenProgramSubcommand::Private(private_subcommand) => {
|
||||
Self::Private(private_subcommand) => {
|
||||
private_subcommand.handle_subcommand(wallet_core).await
|
||||
}
|
||||
TokenProgramSubcommand::Public(public_subcommand) => {
|
||||
Self::Public(public_subcommand) => {
|
||||
public_subcommand.handle_subcommand(wallet_core).await
|
||||
}
|
||||
TokenProgramSubcommand::Deshielded(deshielded_subcommand) => {
|
||||
Self::Deshielded(deshielded_subcommand) => {
|
||||
deshielded_subcommand.handle_subcommand(wallet_core).await
|
||||
}
|
||||
TokenProgramSubcommand::Shielded(shielded_subcommand) => {
|
||||
Self::Shielded(shielded_subcommand) => {
|
||||
shielded_subcommand.handle_subcommand(wallet_core).await
|
||||
}
|
||||
}
|
||||
|
||||
@ -70,7 +70,7 @@ pub struct Label(String);
|
||||
|
||||
impl Label {
|
||||
#[must_use]
|
||||
pub fn new(label: String) -> Self {
|
||||
pub const fn new(label: String) -> Self {
|
||||
Self(label)
|
||||
}
|
||||
}
|
||||
@ -507,7 +507,7 @@ impl Default for WalletConfig {
|
||||
}
|
||||
|
||||
impl WalletConfig {
|
||||
pub fn from_path_or_initialize_default(config_path: &Path) -> Result<WalletConfig> {
|
||||
pub fn from_path_or_initialize_default(config_path: &Path) -> Result<Self> {
|
||||
match std::fs::File::open(config_path) {
|
||||
Ok(file) => {
|
||||
let reader = std::io::BufReader::new(file);
|
||||
@ -532,7 +532,7 @@ impl WalletConfig {
|
||||
.truncate(true)
|
||||
.open(config_path)?;
|
||||
|
||||
let config = WalletConfig::default();
|
||||
let config = Self::default();
|
||||
let default_config_serialized = serde_json::to_vec_pretty(&config).unwrap();
|
||||
|
||||
file.write_all(&default_config_serialized)?;
|
||||
@ -545,7 +545,7 @@ impl WalletConfig {
|
||||
}
|
||||
|
||||
pub fn apply_overrides(&mut self, overrides: WalletConfigOverrides) {
|
||||
let WalletConfig {
|
||||
let Self {
|
||||
override_rust_log,
|
||||
sequencer_addr,
|
||||
seq_poll_timeout,
|
||||
|
||||
@ -58,16 +58,12 @@ fn get_home_nssa_var() -> Result<PathBuf> {
|
||||
fn get_home_default_path() -> Result<PathBuf> {
|
||||
std::env::home_dir()
|
||||
.map(|path| path.join(".nssa").join("wallet"))
|
||||
.ok_or(anyhow::anyhow!("Failed to get HOME"))
|
||||
.context("Failed to get HOME")
|
||||
}
|
||||
|
||||
/// Get home dir for wallet.
|
||||
pub fn get_home() -> Result<PathBuf> {
|
||||
if let Ok(home) = get_home_nssa_var() {
|
||||
Ok(home)
|
||||
} else {
|
||||
get_home_default_path()
|
||||
}
|
||||
get_home_nssa_var().or_else(|_| get_home_default_path())
|
||||
}
|
||||
|
||||
/// Fetch config path from default home
|
||||
|
||||
@ -150,13 +150,13 @@ impl WalletCore {
|
||||
|
||||
/// Get configuration with applied overrides
|
||||
#[must_use]
|
||||
pub fn config(&self) -> &WalletConfig {
|
||||
pub const fn config(&self) -> &WalletConfig {
|
||||
&self.storage.wallet_config
|
||||
}
|
||||
|
||||
/// Get storage
|
||||
#[must_use]
|
||||
pub fn storage(&self) -> &WalletChainStore {
|
||||
pub const fn storage(&self) -> &WalletChainStore {
|
||||
&self.storage
|
||||
}
|
||||
|
||||
@ -505,17 +505,17 @@ impl WalletCore {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn config_path(&self) -> &PathBuf {
|
||||
pub const fn config_path(&self) -> &PathBuf {
|
||||
&self.config_path
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn storage_path(&self) -> &PathBuf {
|
||||
pub const fn storage_path(&self) -> &PathBuf {
|
||||
&self.storage_path
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn config_overrides(&self) -> &Option<WalletConfigOverrides> {
|
||||
pub const fn config_overrides(&self) -> &Option<WalletConfigOverrides> {
|
||||
&self.config_overrides
|
||||
}
|
||||
}
|
||||
|
||||
@ -18,7 +18,7 @@ pub struct TxPoller {
|
||||
|
||||
impl TxPoller {
|
||||
#[must_use]
|
||||
pub fn new(config: &WalletConfig, client: Arc<SequencerClient>) -> Self {
|
||||
pub const fn new(config: &WalletConfig, client: Arc<SequencerClient>) -> Self {
|
||||
Self {
|
||||
polling_delay: config.seq_poll_timeout,
|
||||
polling_max_blocks_to_query: config.seq_tx_poll_max_blocks,
|
||||
|
||||
@ -22,12 +22,12 @@ pub enum PrivacyPreservingAccount {
|
||||
|
||||
impl PrivacyPreservingAccount {
|
||||
#[must_use]
|
||||
pub fn is_public(&self) -> bool {
|
||||
pub const fn is_public(&self) -> bool {
|
||||
matches!(&self, Self::Public(_))
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn is_private(&self) -> bool {
|
||||
pub const fn is_private(&self) -> bool {
|
||||
matches!(
|
||||
&self,
|
||||
Self::PrivateOwned(_) | Self::PrivateForeign { npk: _, vpk: _ }
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user