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

Split AddressTrait #720

Merged
merged 6 commits into from
Aug 23, 2023
Merged
Show file tree
Hide file tree
Changes from 2 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
12 changes: 2 additions & 10 deletions adapters/celestia/src/celestia.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use prost::Message;
use serde::{Deserialize, Serialize};
use sov_rollup_interface::da::{BlockHeaderTrait as BlockHeader, CountedBufReader};
use sov_rollup_interface::services::da::SlotData;
use sov_rollup_interface::AddressTrait;
use sov_rollup_interface::BasicAddress;
pub use tendermint::block::Header as TendermintHeader;
use tendermint::block::Height;
use tendermint::crypto::default::Sha256;
Expand Down Expand Up @@ -370,14 +370,6 @@ impl<'a> TryFrom<&'a [u8]> for H160 {
}
}

impl From<[u8; 32]> for H160 {
citizen-stig marked this conversation as resolved.
Show resolved Hide resolved
fn from(value: [u8; 32]) -> Self {
let mut addr = [0u8; 20];
addr.copy_from_slice(&value[12..]);
Self(addr)
}
}

impl FromStr for H160 {
type Err = hex::FromHexError;

Expand All @@ -396,7 +388,7 @@ impl Display for H160 {
}
}

impl AddressTrait for H160 {}
impl BasicAddress for H160 {}

pub fn parse_pfb_namespace(
group: NamespaceGroup,
Expand Down
21 changes: 1 addition & 20 deletions adapters/celestia/src/verifier/address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use std::str::FromStr;
use bech32::WriteBase32;
use borsh::{BorshDeserialize, BorshSerialize};
use serde::{Deserialize, Serialize};
use sov_rollup_interface::AddressTrait;
use thiserror::Error;

/// Human Readable Part: "celestia" for Celestia network
Expand Down Expand Up @@ -52,17 +51,6 @@ impl<'a> TryFrom<&'a [u8]> for CelestiaAddress {
}
}

/// Panics if any element is not in range 0..32 (u5)
/// TODO: Will be removed after https://github.com/Sovereign-Labs/sovereign-sdk/issues/493
impl From<[u8; 32]> for CelestiaAddress {
fn from(value: [u8; 32]) -> Self {
for item in value {
bech32::u5::try_from_u8(item).unwrap();
}
Self(value)
}
}

impl Display for CelestiaAddress {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let mut w = bech32::Bech32Writer::new(HRP, VARIANT, f)?;
Expand Down Expand Up @@ -116,7 +104,7 @@ impl FromStr for CelestiaAddress {
}
}

impl AddressTrait for CelestiaAddress {}
impl sov_rollup_interface::BasicAddress for CelestiaAddress {}

#[cfg(test)]
mod tests {
Expand Down Expand Up @@ -232,12 +220,5 @@ mod tests {
fn test_borsh(input in proptest::array::uniform20(0u8..=255)) {
check_borsh(input);
}

#[test]
fn test_try_from_array(arr in proptest::array::uniform32(0u8..32)) {
let address = CelestiaAddress::from(arr);
let output = format!("{}", address);
prop_assert!(output.starts_with("celestia"));
}
}
}
8 changes: 4 additions & 4 deletions examples/demo-rollup/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use demo_stf::runtime::GenesisConfig;
pub use rollup::{new_rollup_with_celestia_da, Rollup};
use sov_db::ledger_db::LedgerDB;
use sov_modules_api::default_context::DefaultContext;
use sov_rollup_interface::AddressTrait;
use sov_rollup_interface::BasicAddress;

/// The rollup stores its data in the namespace b"sov-test" on Celestia
/// You can change this constant to point your rollup at a different namespace
Expand All @@ -38,10 +38,10 @@ pub struct HexKey {
/// address, simply change the value of the SEQUENCER_DA_ADDRESS to your own address.
/// For example:
/// ```rust,no_run
/// const SEQUENCER_DA_ADDRESS: [u8;47] = *b"celestia1qp09ysygcx6npted5yc0au6k9lner05yvs9208";
/// const SEQUENCER_DA_ADDRESS: &str = "celestia1qp09ysygcx6npted5yc0au6k9lner05yvs9208";
/// ```
pub fn get_genesis_config<D: AddressTrait>(
sequencer_da_address: D,
pub fn get_genesis_config<A: BasicAddress>(
sequencer_da_address: A,
) -> GenesisConfig<DefaultContext> {
let hex_key: HexKey = serde_json::from_slice(include_bytes!(
"../../test-data/keys/token_deployer_private_key.json"
Expand Down
3 changes: 2 additions & 1 deletion examples/demo-simple-stf/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,8 @@ pub struct DaAddress {
pub addr: [u8; 32],
}

impl AddressTrait for DaAddress {}
impl BasicAddress for DaAddress {}
impl RollupAddress for DaAddress {}

```

Expand Down
64 changes: 5 additions & 59 deletions examples/demo-simple-stf/tests/stf_test.rs
Original file line number Diff line number Diff line change
@@ -1,75 +1,21 @@
use std::fmt::Display;
use std::str::FromStr;

use demo_simple_stf::{ApplySlotResult, CheckHashPreimageStf};
use sov_rollup_interface::mocks::{MockBlob, MockBlock, MockValidityCond, MockZkvm};
use sov_rollup_interface::mocks::{MockAddress, MockBlob, MockBlock, MockValidityCond, MockZkvm};
use sov_rollup_interface::stf::StateTransitionFunction;
use sov_rollup_interface::AddressTrait;

#[derive(PartialEq, Debug, Clone, Eq, serde::Serialize, serde::Deserialize, Hash)]
pub struct DaAddress {
pub addr: [u8; 32],
}

impl AddressTrait for DaAddress {}

impl AsRef<[u8]> for DaAddress {
fn as_ref(&self) -> &[u8] {
&self.addr
}
}

impl From<[u8; 32]> for DaAddress {
fn from(addr: [u8; 32]) -> Self {
DaAddress { addr }
}
}

impl FromStr for DaAddress {
type Err = hex::FromHexError;

fn from_str(s: &str) -> Result<Self, Self::Err> {
// Remove the "0x" prefix, if it exists.
let s = s.strip_prefix("0x").unwrap_or(s);
let mut addr = [0u8; 32];
hex::decode_to_slice(s, &mut addr)?;
Ok(DaAddress { addr })
}
}

impl<'a> TryFrom<&'a [u8]> for DaAddress {
type Error = anyhow::Error;

fn try_from(addr: &'a [u8]) -> Result<Self, Self::Error> {
if addr.len() != 32 {
anyhow::bail!("Address must be 32 bytes long");
}
let mut addr_bytes = [0u8; 32];
addr_bytes.copy_from_slice(addr);
Ok(Self { addr: addr_bytes })
}
}

impl Display for DaAddress {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self.addr)
}
}

#[test]
fn test_stf() {
let address = DaAddress { addr: [1; 32] };
let address = MockAddress { addr: [1; 32] };
let preimage = vec![0; 32];

let test_blob = MockBlob::<DaAddress>::new(preimage, address, [0; 32]);
let test_blob = MockBlob::<MockAddress>::new(preimage, address, [0; 32]);
let stf = &mut CheckHashPreimageStf::<MockValidityCond>::default();

let data = MockBlock::default();
let mut blobs = [test_blob];

StateTransitionFunction::<MockZkvm, MockBlob<DaAddress>>::init_chain(stf, ());
StateTransitionFunction::<MockZkvm, MockBlob<MockAddress>>::init_chain(stf, ());

let result = StateTransitionFunction::<MockZkvm, MockBlob<DaAddress>>::apply_slot(
let result = StateTransitionFunction::<MockZkvm, MockBlob<MockAddress>>::apply_slot(
stf,
(),
&data,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ impl<C: sov_modules_api::Context> SequencerRegistry<C> {
}

/// Checks whether `sender` is a registered sequencer.
pub fn is_sender_allowed<T: sov_modules_api::AddressTrait>(
pub fn is_sender_allowed<T: sov_rollup_interface::BasicAddress>(
&self,
sender: &T,
working_set: &mut WorkingSet<C::Storage>,
Expand Down
4 changes: 2 additions & 2 deletions module-system/sov-modules-api/src/default_context.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#[cfg(feature = "native")]
use serde::{Deserialize, Serialize};
use sha2::Digest;
use sov_rollup_interface::AddressTrait;
use sov_rollup_interface::RollupAddress;
#[cfg(feature = "native")]
use sov_state::ProverStorage;
use sov_state::{ArrayWitness, DefaultStorageSpec, ZkStorage};
Expand Down Expand Up @@ -67,7 +67,7 @@ impl Context for ZkDefaultContext {
}

impl PublicKey for DefaultPublicKey {
fn to_address<A: AddressTrait>(&self) -> A {
fn to_address<A: RollupAddress>(&self) -> A {
let pub_key_hash = {
let mut hasher = <ZkDefaultContext as Spec>::Hasher::new();
hasher.update(self.pub_key);
Expand Down
15 changes: 9 additions & 6 deletions module-system/sov-modules-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,9 @@ pub use error::Error;
pub use prefix::Prefix;
pub use response::CallResponse;
use serde::{Deserialize, Serialize};
pub use sov_rollup_interface::{digest, AddressTrait};
use sov_rollup_interface::BasicAddress;
// TODO: Check this.
pub use sov_rollup_interface::{digest, RollupAddress};
citizen-stig marked this conversation as resolved.
Show resolved Hide resolved
use sov_state::{Storage, Witness, WorkingSet};
use thiserror::Error;

Expand All @@ -65,7 +67,8 @@ impl AsRef<[u8]> for Address {
}
}

impl AddressTrait for Address {}
impl BasicAddress for Address {}
impl RollupAddress for Address {}

#[cfg_attr(feature = "native", derive(schemars::JsonSchema))]
#[derive(PartialEq, Clone, Copy, Eq, borsh::BorshDeserialize, borsh::BorshSerialize, Hash)]
Expand Down Expand Up @@ -142,7 +145,7 @@ pub enum NonInstantiable {}

/// PublicKey used in the Module System.
pub trait PublicKey {
fn to_address<A: AddressTrait>(&self) -> A;
fn to_address<A: RollupAddress>(&self) -> A;
}

/// A PrivateKey used in the Module System.
Expand All @@ -153,7 +156,7 @@ pub trait PrivateKey {
fn generate() -> Self;
fn pub_key(&self) -> Self::PublicKey;
fn sign(&self, msg: &[u8]) -> Self::Signature;
fn to_address<A: AddressTrait>(&self) -> A {
fn to_address<A: RollupAddress>(&self) -> A {
self.pub_key().to_address::<A>()
}
}
Expand All @@ -170,7 +173,7 @@ pub trait PrivateKey {
pub trait Spec {
/// The Address type used on the rollup. Typically calculated as the hash of a public key.
#[cfg(feature = "native")]
type Address: AddressTrait
type Address: RollupAddress
+ BorshSerialize
+ BorshDeserialize
+ Sync
Expand All @@ -183,7 +186,7 @@ pub trait Spec {

/// The Address type used on the rollup. Typically calculated as the hash of a public key.
#[cfg(not(feature = "native"))]
type Address: AddressTrait + BorshSerialize + BorshDeserialize;
type Address: RollupAddress + BorshSerialize + BorshDeserialize;

/// Authenticated state storage used by the rollup. Typically some variant of a merkle-patricia trie.
type Storage: Storage + Clone + Send + Sync;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

#![allow(unused_imports)]

use sov_modules_api::{AddressTrait, Context, ModuleInfo};
use sov_modules_api::{Context, ModuleInfo, RollupAddress};

#[derive(ModuleInfo)]
struct TestModule<C: Context> {
Expand Down
6 changes: 3 additions & 3 deletions module-system/sov-modules-stf-template/src/app_template.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use borsh::BorshDeserialize;
use sov_modules_api::{Context, DispatchCall};
use sov_rollup_interface::da::{BlobReaderTrait, CountedBufReader, DaSpec};
use sov_rollup_interface::stf::{BatchReceipt, TransactionReceipt};
use sov_rollup_interface::{AddressTrait, Buf};
use sov_rollup_interface::{BasicAddress, Buf};
use sov_state::StateCheckpoint;
use tracing::{debug, error};

Expand Down Expand Up @@ -39,7 +39,7 @@ pub struct AppTemplate<
phantom_da: PhantomData<DA>,
}

pub(crate) enum ApplyBatchError<A: AddressTrait> {
pub(crate) enum ApplyBatchError<A: BasicAddress> {
// Contains batch hash
Ignored([u8; 32]),
Slashed {
Expand All @@ -50,7 +50,7 @@ pub(crate) enum ApplyBatchError<A: AddressTrait> {
},
}

impl<A: AddressTrait> From<ApplyBatchError<A>> for BatchReceipt<SequencerOutcome<A>, TxEffect> {
impl<A: BasicAddress> From<ApplyBatchError<A>> for BatchReceipt<SequencerOutcome<A>, TxEffect> {
fn from(value: ApplyBatchError<A>) -> Self {
match value {
ApplyBatchError::Ignored(hash) => BatchReceipt {
Expand Down
4 changes: 2 additions & 2 deletions module-system/sov-modules-stf-template/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use sov_rollup_interface::da::{BlobReaderTrait, DaSpec};
use sov_rollup_interface::services::da::SlotData;
use sov_rollup_interface::stf::{SlotResult, StateTransitionFunction};
use sov_rollup_interface::zk::{ValidityCondition, Zkvm};
use sov_rollup_interface::AddressTrait;
use sov_rollup_interface::BasicAddress;
use sov_state::{StateCheckpoint, Storage, WorkingSet};
use tracing::info;
pub use tx_verifier::RawTx;
Expand Down Expand Up @@ -42,7 +42,7 @@ pub enum TxEffect {

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
/// Represents the different outcomes that can occur for a sequencer after batch processing.
pub enum SequencerOutcome<A: AddressTrait> {
pub enum SequencerOutcome<A: BasicAddress> {
/// Sequencer receives reward amount in defined token and can withdraw its deposit
Rewarded(u64),
/// Sequencer loses its deposit and receives no reward
Expand Down
4 changes: 2 additions & 2 deletions module-system/utils/sov-data-generators/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use sov_modules_stf_template::{Batch, RawTx, SequencerOutcome, TxEffect};
use sov_rollup_interface::da::DaSpec;
use sov_rollup_interface::mocks::{MockAddress, MockBlob, MockDaSpec};
use sov_rollup_interface::stf::BatchReceipt;
use sov_rollup_interface::AddressTrait;
use sov_rollup_interface::RollupAddress;

pub mod bank_data;
pub mod election_data;
Expand All @@ -24,7 +24,7 @@ pub fn new_test_blob_from_batch(
MockBlob::new(data, address, hash)
}

pub fn has_tx_events<A: AddressTrait>(
pub fn has_tx_events<A: RollupAddress>(
apply_blob_outcome: &BatchReceipt<SequencerOutcome<A>, TxEffect>,
) -> bool {
let events = apply_blob_outcome
Expand Down
4 changes: 2 additions & 2 deletions rollup-interface/src/state_machine/da.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};

use crate::zk::ValidityCondition;
use crate::AddressTrait;
use crate::BasicAddress;

/// A specification for the types used by a DA layer.
pub trait DaSpec {
Expand Down Expand Up @@ -166,7 +166,7 @@ pub trait BlobReaderTrait: Serialize + DeserializeOwned + Send + Sync + 'static
type Data: Buf;

/// The type used to represent addresses on the DA layer.
type Address: AddressTrait;
type Address: BasicAddress;

/// Returns the address (on the DA layer) of the entity which submitted the blob transaction
fn sender(&self) -> Self::Address;
Expand Down
Loading