Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

systems crate #3472

Merged
merged 4 commits into from
Jul 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changelog/unreleased/improvements/3472-systems-crate.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
- Added a new namada_systems crate to contain abstract systems interfaces,
previously added to core crate. Also switched to use the concrete
storage error and result type instead of the generic associated
type which reduces the amount of typing needed one the caller side.
([\#3472](https://github.com/anoma/namada/pull/3472))
16 changes: 16 additions & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ members = [
"crates/shielded_token",
"crates/state",
"crates/storage",
"crates/systems",
"crates/test_utils",
"crates/tests",
"crates/token",
Expand Down
38 changes: 1 addition & 37 deletions crates/core/src/ibc.rs
Original file line number Diff line number Diff line change
@@ -1,54 +1,18 @@
//! IBC-related data types

use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Display;
use std::str::FromStr;

use borsh::{BorshDeserialize, BorshSchema, BorshSerialize};
use data_encoding::{DecodePartial, HEXLOWER, HEXLOWER_PERMISSIVE};
pub use ibc::*;
use masp_primitives::transaction::components::ValueSum;
use masp_primitives::transaction::TransparentAddress;
use namada_macros::BorshDeserializer;
#[cfg(feature = "migrations")]
use namada_migrations::*;
use serde::{Deserialize, Serialize};

use super::address::HASH_LEN;
use crate::address::Address;
use crate::hash::Hash;
use crate::masp::TAddrData;
use crate::{storage, token};

/// Abstract IBC storage read interface
pub trait Read<S> {
/// Storage error
type Err;

/// Extract MASP transaction from IBC envelope
fn try_extract_masp_tx_from_envelope(
tx_data: &[u8],
) -> Result<Option<masp_primitives::transaction::Transaction>, Self::Err>;

/// Apply relevant IBC packets to the changed balances structure
fn apply_ibc_packet(
storage: &S,
tx_data: &[u8],
acc: ChangedBalances,
keys_changed: &BTreeSet<storage::Key>,
) -> Result<ChangedBalances, Self::Err>;
}

/// Balances changed by a transaction
#[derive(Default, Debug, Clone)]
pub struct ChangedBalances {
/// Map between MASP transparent address and namada types
pub decoder: BTreeMap<TransparentAddress, TAddrData>,
/// Balances before the tx
pub pre: BTreeMap<TransparentAddress, ValueSum<Address, token::Amount>>,
/// Balances after the tx
pub post: BTreeMap<TransparentAddress, ValueSum<Address, token::Amount>>,
}

/// IBC token hash derived from a denomination.
#[derive(
Expand All @@ -69,7 +33,7 @@ pub struct ChangedBalances {
#[repr(transparent)]
pub struct IbcTokenHash(pub [u8; HASH_LEN]);

impl std::fmt::Display for IbcTokenHash {
impl Display for IbcTokenHash {
#[inline(always)]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", HEXLOWER.encode(&self.0))
Expand Down
2 changes: 0 additions & 2 deletions crates/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,7 @@ pub mod arith;
pub mod bytes;
#[cfg(any(test, feature = "control_flow"))]
pub mod control_flow;
pub mod governance;
pub mod hints;
pub mod proof_of_stake;

// TODO(namada#3248): only re-export v037 `tendermint-rs`
pub use {masp_primitives, tendermint, tendermint_proto};
Expand Down
35 changes: 0 additions & 35 deletions crates/core/src/parameters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,41 +12,6 @@ use super::hash::Hash;
use super::time::DurationSecs;
use super::token;
use crate::borsh::{BorshDeserialize, BorshSchema, BorshSerialize};
use crate::storage;

/// Abstract parameters storage keys interface
pub trait Keys {
/// Key for implicit VP
fn implicit_vp_key() -> storage::Key;
}

/// Abstract parameters storage read interface
pub trait Read<S> {
/// Storage error
type Err;

/// Read all parameters
fn read(storage: &S) -> Result<Parameters, Self::Err>;

/// Read MASP epoch multiplier
fn masp_epoch_multiplier(storage: &S) -> Result<u64, Self::Err>;

/// Read the the epoch duration parameter from store
fn epoch_duration_parameter(
storage: &S,
) -> Result<EpochDuration, Self::Err>;

/// Helper function to retrieve the `is_native_token_transferable` protocol
/// parameter from storage
fn is_native_token_transferable(storage: &S) -> Result<bool, Self::Err>;
}

/// Abstract parameters storage write interface
pub trait Write<S>: Read<S> {
/// Write all parameters
fn write(storage: &mut S, parameters: &Parameters)
-> Result<(), Self::Err>;
}

/// Protocol parameters
#[derive(
Expand Down
61 changes: 0 additions & 61 deletions crates/core/src/token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,73 +14,12 @@ use namada_migrations::*;
use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::address::Address;
use crate::arith::{self, checked, CheckedAdd, CheckedSub};
use crate::dec::{Dec, POS_DECIMAL_PRECISION};
use crate::storage;
use crate::storage::{DbKeySeg, KeySeg};
use crate::uint::{self, Uint, I256};

/// Abstract token keys interface
pub trait Keys {
/// Key for transparent token balance
fn balance_key(token: &Address, owner: &Address) -> storage::Key;

/// Returns the owner address if the given storage key is a balance key for
/// the given token.
fn is_balance_key<'a>(
token_addr: &Address,
key: &'a storage::Key,
) -> Option<&'a Address>;

/// Check if the given storage key is a balance key for an unspecified
/// token. If it is, return the token and owner address.
fn is_any_token_balance_key(key: &storage::Key) -> Option<[&Address; 2]>;

/// Obtain a storage key for the multitoken minter.
fn minter_key(token_addr: &Address) -> storage::Key;
}

/// Abstract token storage read interface
pub trait Read<S> {
/// Storage error
type Err;
}

/// Abstract token storage write interface
pub trait Write<S>: Read<S> {
/// Transfer `token` from `src` to `dest`. Returns an `Err` if `src` has
/// insufficient balance or if the transfer the `dest` would overflow (This
/// can only happen if the total supply doesn't fit in `token::Amount`).
fn transfer(
storage: &mut S,
token: &Address,
src: &Address,
dest: &Address,
amount: Amount,
) -> Result<(), Self::Err>;

/// Burn a specified amount of tokens from some address. If the burn amount
/// is larger than the total balance of the given address, then the
/// remaining balance is burned. The total supply of the token is
/// properly adjusted.
fn burn_tokens(
storage: &mut S,
token: &Address,
source: &Address,
amount: Amount,
) -> Result<(), Self::Err>;

/// Credit tokens to an account, to be used only by protocol. In
/// transactions, this would get rejected by the default `vp_token`.
fn credit_tokens(
storage: &mut S,
token: &Address,
dest: &Address,
amount: Amount,
) -> Result<(), Self::Err>;
}

/// Amount in micro units. For different granularity another representation
/// might be more appropriate.
#[derive(
Expand Down
1 change: 1 addition & 0 deletions crates/ethereum_bridge/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ namada_parameters = {path = "../parameters"}
namada_proof_of_stake = {path = "../proof_of_stake", default-features = false}
namada_state = {path = "../state"}
namada_storage = {path = "../storage"}
namada_systems = { path = "../systems" }
namada_trans_token = {path = "../trans_token"}
namada_tx = {path = "../tx"}
namada_vote_ext = {path = "../vote_ext"}
Expand Down
2 changes: 1 addition & 1 deletion crates/ethereum_bridge/src/vp/bridge_pool_vp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@ use namada_core::eth_bridge_pool::{
use namada_core::ethereum_events::EthAddress;
use namada_core::hints;
use namada_core::storage::Key;
use namada_core::token::{self, Amount};
use namada_core::uint::I320;
use namada_state::{ResultExt, StateRead};
use namada_systems::trans_token::{self as token, Amount};
use namada_tx::BatchedTxRef;
use namada_vp::native_vp::{self, Ctx, NativeVp, StorageReader, VpEvaluator};

Expand Down
2 changes: 1 addition & 1 deletion crates/ethereum_bridge/src/vp/eth_bridge_vp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ use namada_core::address::Address;
use namada_core::booleans::BoolResultUnitExt;
use namada_core::collections::HashSet;
use namada_core::storage::Key;
use namada_core::token::{self, Amount};
use namada_state::StateRead;
use namada_systems::trans_token::{self as token, Amount};
use namada_tx::BatchedTxRef;
use namada_vp::native_vp::{self, Ctx, NativeVp, StorageReader, VpEvaluator};

Expand Down
2 changes: 1 addition & 1 deletion crates/ethereum_bridge/src/vp/nut_vp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ use std::marker::PhantomData;
use namada_core::address::{Address, InternalAddress};
use namada_core::booleans::BoolResultUnitExt;
use namada_core::storage::Key;
use namada_core::token::{self, Amount};
use namada_state::StateRead;
use namada_systems::trans_token::{self as token, Amount};
use namada_tx::BatchedTxRef;
use namada_vp::native_vp::{self, Ctx, NativeVp, VpEvaluator};
use namada_vp::VpEnv;
Expand Down
1 change: 1 addition & 0 deletions crates/governance/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ namada_macros = { path = "../macros" }
namada_migrations = { path= "../migrations", optional = true }
namada_parameters = { path = "../parameters" }
namada_state = { path = "../state" }
namada_systems = { path = "../systems" }
namada_trans_token = { path = "../trans_token" }
namada_tx = { path = "../tx" }
namada_vp = { path = "../vp" }
Expand Down
10 changes: 3 additions & 7 deletions crates/governance/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ pub mod utils;
pub mod vp;

use namada_state::StorageRead;
pub use namada_systems::governance::*;
pub use storage::proposal::{InitProposalData, ProposalType, VoteProposalData};
pub use storage::vote::ProposalVote;
pub use storage::{init_proposal, is_proposal_accepted, vote_proposal};
Expand All @@ -46,16 +47,11 @@ pub const ADDRESS: Address = address::GOV;
#[derive(Debug)]
pub struct Store<S>(PhantomData<S>);

impl<S> namada_core::governance::Read<S> for Store<S>
impl<S> Read<S> for Store<S>
where
S: StorageRead,
{
type Err = namada_state::StorageError;

fn is_proposal_accepted(
storage: &S,
tx_data: &[u8],
) -> Result<bool, Self::Err> {
fn is_proposal_accepted(storage: &S, tx_data: &[u8]) -> Result<bool> {
storage::is_proposal_accepted(storage, tx_data)
}
}
13 changes: 4 additions & 9 deletions crates/governance/src/vp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@ use std::marker::PhantomData;
use borsh::BorshDeserialize;
use namada_core::arith::{self, checked};
use namada_core::booleans::{BoolResultUnitExt, ResultBoolExt};
use namada_core::storage;
use namada_core::storage::Epoch;
use namada_core::{proof_of_stake, storage, token};
use namada_state::{StateRead, StorageRead};
use namada_systems::{proof_of_stake, trans_token as token};
use namada_tx::action::{Action, GovAction, Read};
use namada_tx::BatchedTxRef;
use namada_vp::native_vp::{Ctx, CtxPreStorageRead, NativeVp, VpEvaluator};
Expand Down Expand Up @@ -65,10 +66,7 @@ where
S: StateRead,
CA: 'static + Clone,
EVAL: 'static + VpEvaluator<'ctx, S, CA, EVAL>,
PoS: proof_of_stake::Read<
CtxPreStorageRead<'view, 'ctx, S, CA, EVAL>,
Err = namada_state::StorageError,
>,
PoS: proof_of_stake::Read<CtxPreStorageRead<'view, 'ctx, S, CA, EVAL>>,
TokenKeys: token::Keys,
{
type Error = Error;
Expand Down Expand Up @@ -219,10 +217,7 @@ where
S: StateRead,
CA: 'static + Clone,
EVAL: 'static + VpEvaluator<'ctx, S, CA, EVAL>,
PoS: proof_of_stake::Read<
CtxPreStorageRead<'view, 'ctx, S, CA, EVAL>,
Err = namada_state::StorageError,
>,
PoS: proof_of_stake::Read<CtxPreStorageRead<'view, 'ctx, S, CA, EVAL>>,
TokenKeys: token::Keys,
{
/// Instantiate a Governance VP
Expand Down
Loading