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

DI - IBC #3509

Merged
merged 22 commits into from
Aug 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
d070074
add namada_systems crate with systems' abstract interfaces
tzemanovic Jul 2, 2024
7992a2e
update systems crates to use namada_systems
tzemanovic Jul 2, 2024
98aa9df
systems: use the concrete storage error and result type
tzemanovic Jul 2, 2024
c64c7aa
changelog: add #3472
tzemanovic Jul 9, 2024
d6040cd
shielded_token: replace parameters dep with DI
tzemanovic Jun 28, 2024
0db2cd8
shielded_token: replace trans_token dep with DI
tzemanovic Jul 3, 2024
7b10412
system/test: add a test for no cross-system deps
tzemanovic Jun 28, 2024
0fc23dd
changelog: add #3466
tzemanovic Jul 9, 2024
07a83ec
governance: replace deps on other systems with DI
tzemanovic Jul 3, 2024
1fbb9fd
changelog: add #3482
tzemanovic Jul 9, 2024
1f256f1
proof_of_stake: refactor out pos_queries mod
tzemanovic Jul 5, 2024
3d21076
proof_of_stake: replace governance dep with DI
tzemanovic Jul 4, 2024
32d8fbe
proof_of_stake: replace parameters dep with DI
tzemanovic Jul 10, 2024
4f5989d
proof_of_stake: replace trans_token dep with DI
tzemanovic Jul 11, 2024
8a4512b
test/systems: check PoS cross-system deps and allow if optional
tzemanovic Jul 11, 2024
a2c6d0f
PoS: replace optional cross-system deps too
tzemanovic Jul 12, 2024
aa570a1
changelog: add #3497
tzemanovic Jul 11, 2024
683eb85
ibc: replace parameters dep with DI
tzemanovic Jul 12, 2024
98cbeb8
ibc: replace gov dep with DI
tzemanovic Jul 16, 2024
46c8fae
ibc: replace token dep with DI
tzemanovic Jul 18, 2024
3fa3eb2
test/systems: check IBC cross-system deps
tzemanovic Jul 26, 2024
f67da93
changelog: add #3509
tzemanovic Jul 29, 2024
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
2 changes: 2 additions & 0 deletions .changelog/unreleased/improvements/3466-di-shielded-token.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
- Replaced cross-system dependencies in namada_shielded_token crate with
dependency-injection. ([\#3466](https://github.com/anoma/namada/pull/3466))
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))
2 changes: 2 additions & 0 deletions .changelog/unreleased/improvements/3482-di-gov.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
- Replaced cross-system dependencies in namada_governance crate with dependency-
injection. ([\#3482](https://github.com/anoma/namada/pull/3482))
2 changes: 2 additions & 0 deletions .changelog/unreleased/improvements/3497-di-pos.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
- Replaced cross-system dependencies in namada_proof_of_stake crate with
dependency-injection. ([\#3497](https://github.com/anoma/namada/pull/3497))
2 changes: 2 additions & 0 deletions .changelog/unreleased/improvements/3509-di-ibc.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
- Replaced cross-system dependencies in namada_ibc crate with dependency-
injection. ([\#3509](https://github.com/anoma/namada/pull/3509))
21 changes: 20 additions & 1 deletion 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: 25 additions & 13 deletions crates/benches/native_vps.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ use namada_apps_lib::validation::{
IbcVpContext, MaspVp, MultitokenVp, ParametersVp, PgfVp, PosVp,
};
use namada_apps_lib::wallet::defaults;
use namada_apps_lib::{governance, proof_of_stake, storage, token};
use namada_apps_lib::{governance, parameters, proof_of_stake, storage, token};
use namada_node::bench_utils::{
generate_foreign_key_tx, BenchShell, BenchShieldedCtx,
ALBERT_PAYMENT_ADDRESS, ALBERT_SPENDING_KEY, BERTHA_PAYMENT_ADDRESS,
Expand Down Expand Up @@ -110,9 +110,11 @@ fn governance(c: &mut Criterion) {
"minimal_proposal" => {
let content_section =
Section::ExtraData(Code::new(vec![], None));
let params =
proof_of_stake::storage::read_pos_params(&shell.state)
.unwrap();
let params = proof_of_stake::storage::read_pos_params::<
_,
governance::Store<_>,
>(&shell.state)
.unwrap();
let voting_start_epoch =
Epoch(2 + params.pipeline_len + params.unbonding_len);
// Must start after current epoch
Expand Down Expand Up @@ -163,9 +165,11 @@ fn governance(c: &mut Criterion) {
None,
));

let params =
proof_of_stake::storage::read_pos_params(&shell.state)
.unwrap();
let params = proof_of_stake::storage::read_pos_params::<
_,
governance::Store<_>,
>(&shell.state)
.unwrap();
let voting_start_epoch =
Epoch(2 + params.pipeline_len + params.unbonding_len);
// Must start after current epoch
Expand Down Expand Up @@ -1670,16 +1674,20 @@ fn ibc_vp_validate_action(c: &mut Criterion) {

let exec_ctx = IbcVpContext::new(ibc.ctx.pre());
let ctx = Rc::new(RefCell::new(exec_ctx));
let mut actions = IbcActions::new(ctx.clone(), verifiers.clone());
let mut actions =
IbcActions::<_, parameters::Store<_>, token::Store<()>>::new(
ctx.clone(),
verifiers.clone(),
);
actions.set_validation_params(ibc.validation_params().unwrap());

let module = TransferModule::new(ctx.clone(), verifiers);
actions.add_transfer_module(module);
let module = NftTransferModule::new(ctx);
let module = NftTransferModule::<_, token::Store<()>>::new(ctx);
actions.add_transfer_module(module);

group.bench_function(bench_name, |b| {
b.iter(|| actions.validate(&tx_data).unwrap())
b.iter(|| actions.validate::<Transfer>(&tx_data).unwrap())
});
}

Expand Down Expand Up @@ -1727,16 +1735,20 @@ fn ibc_vp_execute_action(c: &mut Criterion) {
let exec_ctx = IbcVpContext::new(ibc.ctx.pre());
let ctx = Rc::new(RefCell::new(exec_ctx));

let mut actions = IbcActions::new(ctx.clone(), verifiers.clone());
let mut actions =
IbcActions::<_, parameters::Store<_>, token::Store<()>>::new(
ctx.clone(),
verifiers.clone(),
);
actions.set_validation_params(ibc.validation_params().unwrap());

let module = TransferModule::new(ctx.clone(), verifiers);
actions.add_transfer_module(module);
let module = NftTransferModule::new(ctx);
let module = NftTransferModule::<_, token::Store<()>>::new(ctx);
actions.add_transfer_module(module);

group.bench_function(bench_name, |b| {
b.iter(|| actions.execute(&tx_data).unwrap())
b.iter(|| actions.execute::<token::Transfer>(&tx_data).unwrap())
});
}

Expand Down
13 changes: 0 additions & 13 deletions crates/core/src/governance.rs

This file was deleted.

130 changes: 93 additions & 37 deletions crates/core/src/ibc.rs
Original file line number Diff line number Diff line change
@@ -1,54 +1,21 @@
//! IBC-related data types

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

use borsh::{BorshDeserialize, BorshSchema, BorshSerialize};
use data_encoding::{DecodePartial, HEXLOWER, HEXLOWER_PERMISSIVE};
use ibc::core::host::types::identifiers::{ChannelId, PortId};
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>>,
}
use crate::token;

/// IBC token hash derived from a denomination.
#[derive(
Expand All @@ -69,7 +36,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 Expand Up @@ -106,3 +73,92 @@ impl FromStr for IbcTxDataRefs {
serde_json::from_str(s)
}
}

/// The target of a PGF payment
#[derive(
Debug,
Clone,
PartialEq,
Serialize,
Deserialize,
Ord,
Eq,
PartialOrd,
BorshDeserializer,
Hash,
)]
pub struct PGFIbcTarget {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I moved this here from gov (crates/governance/src/storage/proposal.rs) as it's being used from ibc actions - it's mostly just for passing could fields with borsh encoding

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

makes sense

/// The target address on the target chain
pub target: String,
/// The amount of token to fund the target address
pub amount: token::Amount,
/// Port ID to fund
pub port_id: PortId,
/// Channel ID to fund
pub channel_id: ChannelId,
}

impl BorshSerialize for PGFIbcTarget {
fn serialize<W: std::io::Write>(
&self,
writer: &mut W,
) -> std::io::Result<()> {
BorshSerialize::serialize(&self.target, writer)?;
BorshSerialize::serialize(&self.amount, writer)?;
BorshSerialize::serialize(&self.port_id.to_string(), writer)?;
BorshSerialize::serialize(&self.channel_id.to_string(), writer)
}
}

impl borsh::BorshDeserialize for PGFIbcTarget {
fn deserialize_reader<R: std::io::Read>(
reader: &mut R,
) -> std::io::Result<Self> {
use std::io::{Error, ErrorKind};
let target: String = BorshDeserialize::deserialize_reader(reader)?;
let amount: token::Amount =
BorshDeserialize::deserialize_reader(reader)?;
let port_id: String = BorshDeserialize::deserialize_reader(reader)?;
let port_id: PortId = port_id.parse().map_err(|err| {
Error::new(
ErrorKind::InvalidData,
format!("Error decoding port ID: {}", err),
)
})?;
let channel_id: String = BorshDeserialize::deserialize_reader(reader)?;
let channel_id: ChannelId = channel_id.parse().map_err(|err| {
Error::new(
ErrorKind::InvalidData,
format!("Error decoding channel ID: {}", err),
)
})?;
Ok(Self {
target,
amount,
port_id,
channel_id,
})
}
}

impl borsh::BorshSchema for PGFIbcTarget {
fn add_definitions_recursively(
definitions: &mut BTreeMap<
borsh::schema::Declaration,
borsh::schema::Definition,
>,
) {
let fields = borsh::schema::Fields::NamedFields(vec![
("target".into(), String::declaration()),
("amount".into(), token::Amount::declaration()),
("port_id".into(), String::declaration()),
("channel_id".into(), String::declaration()),
]);
let definition = borsh::schema::Definition::Struct { fields };
definitions.insert(Self::declaration(), definition);
}

fn declaration() -> borsh::schema::Declaration {
std::any::type_name::<Self>().into()
}
}
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
Loading