inital commit, which is clearly not initial

Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
This commit is contained in:
Uncle Stretch
2024-10-03 15:38:52 +03:00
commit 66719626bb
178 changed files with 41709 additions and 0 deletions

49
pallets/networks/Cargo.toml Executable file
View File

@@ -0,0 +1,49 @@
[package]
name = "ghost-networks"
license.workspace = true
authors.workspace = true
version.workspace = true
edition.workspace = true
homepage.workspace = true
repository.workspace = true
[dependencies]
scale-info = { workspace = true, features = ["derive"] }
codec = { workspace = true, features = ["max-encoded-len"] }
frame-benchmarking = { workspace = true, optional = true }
frame-support = { workspace = true }
frame-system = { workspace = true }
sp-runtime = { workspace = true }
sp-std = { workspace = true }
ghost-traits = { workspace = true }
[dev-dependencies]
primitives = { workspace = true }
pallet-balances = { workspace = true }
sp-io = { workspace = true }
[features]
default = ["std"]
std = [
"scale-info/std",
"codec/std",
"frame-support/std",
"frame-system/std",
"frame-benchmarking?/std",
"sp-runtime/std",
"sp-std/std",
"sp-io/std",
"ghost-traits/std",
"pallet-balances/std",
]
runtime-benchmarks = [
"frame-benchmarking/runtime-benchmarks",
"frame-support/runtime-benchmarks",
"frame-system/runtime-benchmarks",
"sp-runtime/runtime-benchmarks",
]
try-runtime = [
"frame-support/try-runtime",
"frame-system/try-runtime",
]

View File

@@ -0,0 +1,222 @@
#![cfg(feature = "runtime-benchmarks")]
use super::*;
use crate::Pallet as GhostNetworks;
use frame_benchmarking::v1::{benchmarks, BenchmarkError};
use sp_runtime::Saturating;
const MAX_NAME_LEN: u32 = 20;
const MAX_ENDPOINT_LEN: u32 = 150;
fn assert_last_event<T: Config>(generic_event: <T as Config>::RuntimeEvent) {
frame_system::Pallet::<T>::assert_last_event(generic_event.into());
}
fn prepare_network<T: Config>(
n: u32, m: u32,
) -> (<T as module::Config>::NetworkId, NetworkData) {
let chain_id: <T as module::Config>::NetworkId = Default::default();
let chain_id = chain_id.saturating_add((n + m).into());
let mut gatekeeper = b"0x".to_vec();
for i in 0..40 { gatekeeper.push(i); }
let mut topic_name = b"0x".to_vec();
for i in 0..64 { topic_name.push(i); }
let network = NetworkData {
chain_name: sp_std::vec![0x69; n as usize],
default_endpoint: sp_std::vec![0x69; m as usize],
gatekeeper,
topic_name,
finality_delay: Some(69),
release_delay: Some(69),
network_type: NetworkType::Evm,
incoming_fee: 0,
outgoing_fee: 0,
};
(chain_id, network)
}
fn create_network<T: Config>(
chain_id: <T as module::Config>::NetworkId,
network: NetworkData,
) -> Result<Option<NetworkData>, BenchmarkError> {
let prev_network = match GhostNetworks::<T>::get(&chain_id) {
Some(net) => net,
None => {
let authority = T::RegisterOrigin::try_successful_origin()
.map_err(|_| BenchmarkError::Weightless)?;
GhostNetworks::<T>::register_network(
authority.clone(), chain_id.clone(), network.clone()
).map_err(|_| BenchmarkError::Weightless)?;
network
}
};
Ok(Some(prev_network))
}
benchmarks! {
register_network {
let i in 1 .. MAX_NAME_LEN;
let j in 1 .. MAX_ENDPOINT_LEN;
let (chain_id, network) = prepare_network::<T>(i, j);
let authority = T::RegisterOrigin::try_successful_origin()
.map_err(|_| BenchmarkError::Weightless)?;
let prev_network = GhostNetworks::<T>::networks(chain_id.clone());
}: _<T::RuntimeOrigin>(authority, chain_id.clone(), network.clone())
verify {
assert_last_event::<T>(Event::NetworkRegistered {
chain_id: chain_id.clone(), network,
}.into());
assert_ne!(GhostNetworks::<T>::networks(chain_id.clone()), prev_network);
}
update_network_name {
let n in 1 .. MAX_NAME_LEN;
let name = sp_std::vec![0x42; n as usize];
let (chain_id, network) = prepare_network::<T>(1, 1);
let authority = T::UpdateOrigin::try_successful_origin()
.map_err(|_| BenchmarkError::Weightless)?;
let prev_network = create_network::<T>(chain_id.clone(), network.clone())?;
}: _<T::RuntimeOrigin>(authority, chain_id.clone(), name.clone())
verify {
assert_last_event::<T>(Event::NetworkNameUpdated {
chain_id: chain_id.clone(), chain_name: name,
}.into());
assert_ne!(GhostNetworks::<T>::networks(chain_id.clone()), prev_network);
}
update_network_endpoint {
let n in 1 .. MAX_ENDPOINT_LEN;
let endpoint = sp_std::vec![0x42; n as usize];
let (chain_id, network) = prepare_network::<T>(1, 1);
let authority = T::UpdateOrigin::try_successful_origin()
.map_err(|_| BenchmarkError::Weightless)?;
let prev_network = create_network::<T>(chain_id.clone(), network.clone())?;
}: _<T::RuntimeOrigin>(authority, chain_id.clone(), endpoint.clone())
verify {
assert_last_event::<T>(Event::NetworkEndpointUpdated {
chain_id: chain_id.clone(), default_endpoint: endpoint,
}.into());
assert_ne!(GhostNetworks::<T>::networks(chain_id.clone()), prev_network);
}
update_network_finality_delay {
let delay = Some(1337);
let (chain_id, network) = prepare_network::<T>(1, 1);
let authority = T::UpdateOrigin::try_successful_origin()
.map_err(|_| BenchmarkError::Weightless)?;
let prev_network = create_network::<T>(chain_id.clone(), network.clone())?;
}: _<T::RuntimeOrigin>(authority, chain_id.clone(), delay)
verify {
assert_last_event::<T>(Event::NetworkFinalityDelayUpdated {
chain_id: chain_id.clone(), finality_delay: delay,
}.into());
assert_ne!(GhostNetworks::<T>::networks(chain_id.clone()), prev_network);
}
update_network_release_delay {
let delay = Some(1337);
let (chain_id, network) = prepare_network::<T>(1, 1);
let authority = T::UpdateOrigin::try_successful_origin()
.map_err(|_| BenchmarkError::Weightless)?;
let prev_network = create_network::<T>(chain_id.clone(), network.clone())?;
}: _<T::RuntimeOrigin>(authority, chain_id.clone(), delay)
verify {
assert_last_event::<T>(Event::NetworkReleaseDelayUpdated {
chain_id: chain_id.clone(), release_delay: delay,
}.into());
assert_ne!(GhostNetworks::<T>::networks(chain_id.clone()), prev_network);
}
update_network_type {
let network_type = NetworkType::Utxo;
let (chain_id, network) = prepare_network::<T>(1, 1);
let authority = T::UpdateOrigin::try_successful_origin()
.map_err(|_| BenchmarkError::Weightless)?;
let prev_network = create_network::<T>(chain_id.clone(), network.clone())?;
}: _<T::RuntimeOrigin>(authority, chain_id.clone(), network_type.clone())
verify {
assert_last_event::<T>(Event::NetworkTypeUpdated {
chain_id: chain_id.clone(), network_type: network_type.clone(),
}.into());
assert_ne!(GhostNetworks::<T>::networks(chain_id.clone()), prev_network);
}
update_network_gatekeeper {
let mut gatekeeper = b"0x".to_vec();
for i in 0..40 { gatekeeper.push(i + 1); }
let (chain_id, network) = prepare_network::<T>(1, 1);
let authority = T::UpdateOrigin::try_successful_origin()
.map_err(|_| BenchmarkError::Weightless)?;
let prev_network = create_network::<T>(chain_id.clone(), network.clone())?;
}: _<T::RuntimeOrigin>(authority, chain_id.clone(), gatekeeper.clone())
verify {
assert_last_event::<T>(Event::NetworkGatekeeperUpdated {
chain_id: chain_id.clone(), gatekeeper,
}.into());
assert_ne!(GhostNetworks::<T>::networks(chain_id.clone()), prev_network);
}
update_network_topic_name {
let topic_name = b"0x9876543219876543219876543219876543219876543219876543219876543219".to_vec();
let (chain_id, network) = prepare_network::<T>(1, 1);
let authority = T::UpdateOrigin::try_successful_origin()
.map_err(|_| BenchmarkError::Weightless)?;
let prev_network = create_network::<T>(chain_id.clone(), network.clone())?;
}: _<T::RuntimeOrigin>(authority, chain_id.clone(), topic_name.clone())
verify {
assert_last_event::<T>(Event::NetworkTopicNameUpdated {
chain_id: chain_id.clone(), topic_name,
}.into());
assert_ne!(GhostNetworks::<T>::networks(chain_id.clone()), prev_network);
}
update_incoming_network_fee {
let incoming_fee = 1337;
let (chain_id, network) = prepare_network::<T>(1, 1);
let authority = T::UpdateOrigin::try_successful_origin()
.map_err(|_| BenchmarkError::Weightless)?;
let prev_network = create_network::<T>(chain_id.clone(), network.clone())?;
}: _<T::RuntimeOrigin>(authority, chain_id.clone(), incoming_fee)
verify {
assert_last_event::<T>(Event::NetworkIncomingFeeUpdated {
chain_id: chain_id.clone(), incoming_fee,
}.into());
assert_ne!(GhostNetworks::<T>::networks(chain_id.clone()), prev_network);
}
update_outgoing_network_fee {
let outgoing_fee = 1337;
let (chain_id, network) = prepare_network::<T>(1, 1);
let authority = T::UpdateOrigin::try_successful_origin()
.map_err(|_| BenchmarkError::Weightless)?;
let prev_network = create_network::<T>(chain_id.clone(), network.clone())?;
}: _<T::RuntimeOrigin>(authority, chain_id.clone(), outgoing_fee)
verify {
assert_last_event::<T>(Event::NetworkOutgoingFeeUpdated {
chain_id: chain_id.clone(), outgoing_fee,
}.into());
assert_ne!(GhostNetworks::<T>::networks(chain_id.clone()), prev_network);
}
remove_network {
let (chain_id, network) = prepare_network::<T>(1, 1);
let authority = T::RemoveOrigin::try_successful_origin()
.map_err(|_| BenchmarkError::Weightless)?;
let prev_network = create_network::<T>(chain_id.clone(), network.clone())?;
}: _<T::RuntimeOrigin>(authority, chain_id.clone())
verify {
assert_last_event::<T>(Event::NetworkRemoved {
chain_id: chain_id.clone(),
}.into());
assert_ne!(GhostNetworks::<T>::networks(chain_id.clone()), prev_network);
}
impl_benchmark_test_suite!(GhostNetworks, crate::mock::ExtBuilder::build(), crate::mock::Test);
}

538
pallets/networks/src/lib.rs Executable file
View File

@@ -0,0 +1,538 @@
#![cfg_attr(not(feature = "std"), no_std)]
#![allow(clippy::large_enum_variant)]
#![allow(clippy::too_many_arguments)]
use frame_support::{
pallet_prelude::*,
storage::PrefixIterator, traits::EnsureOrigin,
};
use frame_system::pallet_prelude::*;
use scale_info::TypeInfo;
use sp_runtime::{
traits::{AtLeast32BitUnsigned, Member},
DispatchResult,
};
use sp_std::prelude::*;
pub use ghost_traits::networks::{
NetworkDataBasicHandler, NetworkDataInspectHandler,
NetworkDataMutateHandler,
};
mod weights;
pub use module::*;
pub use crate::weights::WeightInfo;
#[cfg(any(feature = "runtime-benchmarks", test))]
mod benchmarking;
#[cfg(all(feature = "std", test))]
mod mock;
#[cfg(all(feature = "std", test))]
mod tests;
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
pub enum NetworkType {
Evm = 0,
Utxo = 1,
Undefined = 2,
}
impl Default for NetworkType {
fn default() -> Self { NetworkType::Evm }
}
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
pub struct NetworkData {
pub chain_name: Vec<u8>,
pub default_endpoint: Vec<u8>,
pub gatekeeper: Vec<u8>,
pub topic_name: Vec<u8>,
pub finality_delay: Option<u64>,
pub release_delay: Option<u64>,
pub network_type: NetworkType,
pub incoming_fee: u32,
pub outgoing_fee: u32,
}
#[frame_support::pallet]
pub mod module {
use super::*;
#[pallet::config]
pub trait Config: frame_system::Config {
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
/// The type used as a unique network id.
type NetworkId: Parameter
+ Member
+ Parameter
+ AtLeast32BitUnsigned
+ Default
+ Copy
+ Ord
+ TypeInfo
+ MaybeSerializeDeserialize
+ MaxEncodedLen;
/// The origin required to register new network.
type RegisterOrigin: EnsureOrigin<Self::RuntimeOrigin>;
/// The origin required to update network information.
type UpdateOrigin: EnsureOrigin<Self::RuntimeOrigin>;
/// The origin required to remove network.
type RemoveOrigin: EnsureOrigin<Self::RuntimeOrigin>;
/// Weight information for extrinsics in this module.
type WeightInfo: WeightInfo;
}
#[pallet::error]
pub enum Error<T> {
/// Network already registered.
NetworkAlreadyRegistered,
/// Network does not exist.
NetworkDoesNotExist,
/// Gatekeeper address length not 42 or prefix `0x` missed.
WrongGatekeeperAddress,
/// Topic name length not 66 or prefix `0x` missed.
WrongTopicName,
}
#[pallet::event]
#[pallet::generate_deposit(pub(crate) fn deposit_event)]
pub enum Event<T: Config> {
NetworkRegistered { chain_id: T::NetworkId, network: NetworkData },
NetworkNameUpdated { chain_id: T::NetworkId, chain_name: Vec<u8> },
NetworkEndpointUpdated { chain_id: T::NetworkId, default_endpoint: Vec<u8> },
NetworkFinalityDelayUpdated { chain_id: T::NetworkId, finality_delay: Option<u64> },
NetworkReleaseDelayUpdated { chain_id: T::NetworkId, release_delay: Option<u64> },
NetworkTypeUpdated { chain_id: T::NetworkId, network_type: NetworkType },
NetworkGatekeeperUpdated { chain_id: T::NetworkId, gatekeeper: Vec<u8> },
NetworkTopicNameUpdated { chain_id: T::NetworkId, topic_name: Vec<u8> },
NetworkIncomingFeeUpdated { chain_id: T::NetworkId, incoming_fee: u32 },
NetworkOutgoingFeeUpdated { chain_id: T::NetworkId, outgoing_fee: u32 },
NetworkRemoved { chain_id: T::NetworkId },
}
#[pallet::storage]
#[pallet::getter(fn networks)]
pub type Networks<T: Config> =
StorageMap<_, Twox64Concat, T::NetworkId, NetworkData, OptionQuery>;
#[pallet::genesis_config]
pub struct GenesisConfig<T: Config> {
pub networks: Vec<(T::NetworkId, Vec<u8>)>,
}
impl<T: Config> Default for GenesisConfig<T> {
fn default() -> Self {
Self { networks: vec![] }
}
}
#[pallet::genesis_build]
impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
fn build(&self) {
if !self.networks.is_empty() {
self.networks.iter().for_each(|(chain_id, network_metadata)| {
let network =
NetworkData::decode(&mut &network_metadata[..])
.expect("Error decoding NetworkData");
Pallet::<T>::do_register_network(chain_id.clone(), network)
.expect("Error registering network");
});
}
}
}
#[pallet::pallet]
#[pallet::without_storage_info]
pub struct Pallet<T>(PhantomData<T>);
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {}
#[pallet::call]
impl<T: Config> Pallet<T> {
#[pallet::call_index(0)]
#[pallet::weight(T::WeightInfo::register_network(
network.chain_name.len() as u32,
network.default_endpoint.len() as u32,
))]
pub fn register_network(
origin: OriginFor<T>,
chain_id: T::NetworkId,
network: NetworkData,
) -> DispatchResult {
T::RegisterOrigin::ensure_origin_or_root(origin)?;
Self::do_register_network(chain_id, network)
}
#[pallet::call_index(1)]
#[pallet::weight(T::WeightInfo::update_network_name(
chain_name.len() as u32,
))]
pub fn update_network_name(
origin: OriginFor<T>,
chain_id: T::NetworkId,
chain_name: Vec<u8>,
) -> DispatchResult {
T::UpdateOrigin::ensure_origin_or_root(origin)?;
Self::do_update_network_name(
chain_id,
chain_name,
)
}
#[pallet::call_index(2)]
#[pallet::weight(T::WeightInfo::update_network_endpoint(
default_endpoint.len() as u32
))]
pub fn update_network_endpoint(
origin: OriginFor<T>,
chain_id: T::NetworkId,
default_endpoint: Vec<u8>,
) -> DispatchResult {
T::UpdateOrigin::ensure_origin_or_root(origin)?;
Self::do_update_network_endpoint(
chain_id,
default_endpoint,
)
}
#[pallet::call_index(3)]
#[pallet::weight(T::WeightInfo::update_network_finality_delay())]
pub fn update_network_finality_delay(
origin: OriginFor<T>,
chain_id: T::NetworkId,
finality_delay: Option<u64>,
) -> DispatchResult {
T::UpdateOrigin::ensure_origin_or_root(origin)?;
Self::do_update_network_finality_delay(
chain_id,
finality_delay,
)
}
#[pallet::call_index(4)]
#[pallet::weight(T::WeightInfo::update_network_release_delay())]
pub fn update_network_release_delay(
origin: OriginFor<T>,
chain_id: T::NetworkId,
release_delay: Option<u64>,
) -> DispatchResult {
T::UpdateOrigin::ensure_origin_or_root(origin)?;
Self::do_update_network_release_delay(
chain_id,
release_delay,
)
}
#[pallet::call_index(5)]
#[pallet::weight(T::WeightInfo::update_network_type())]
pub fn update_network_type(
origin: OriginFor<T>,
chain_id: T::NetworkId,
network_type: NetworkType,
) -> DispatchResult {
T::UpdateOrigin::ensure_origin_or_root(origin)?;
Self::do_update_network_type(
chain_id,
network_type,
)
}
#[pallet::call_index(6)]
#[pallet::weight(T::WeightInfo::update_network_gatekeeper())]
pub fn update_network_gatekeeper(
origin: OriginFor<T>,
chain_id: T::NetworkId,
gatekeeper: Vec<u8>,
) -> DispatchResult {
T::UpdateOrigin::ensure_origin_or_root(origin)?;
Self::do_update_network_gatekeeper(
chain_id,
gatekeeper,
)
}
#[pallet::call_index(7)]
#[pallet::weight(T::WeightInfo::update_network_topic_name())]
pub fn update_network_topic_name(
origin: OriginFor<T>,
chain_id: T::NetworkId,
topic_name: Vec<u8>,
) -> DispatchResult {
T::UpdateOrigin::ensure_origin_or_root(origin)?;
Self::do_update_network_topic_name(
chain_id,
topic_name,
)
}
#[pallet::call_index(8)]
#[pallet::weight(T::WeightInfo::update_incoming_network_fee())]
pub fn update_incoming_network_fee(
origin: OriginFor<T>,
chain_id: T::NetworkId,
incoming_fee: u32,
) -> DispatchResult {
T::UpdateOrigin::ensure_origin_or_root(origin)?;
Self::do_update_incoming_network_fee(
chain_id,
incoming_fee,
)
}
#[pallet::call_index(9)]
#[pallet::weight(T::WeightInfo::update_outgoing_network_fee())]
pub fn update_outgoing_network_fee(
origin: OriginFor<T>,
chain_id: T::NetworkId,
outgoing_fee: u32,
) -> DispatchResult {
T::UpdateOrigin::ensure_origin_or_root(origin)?;
Self::do_update_outgoing_network_fee(
chain_id,
outgoing_fee,
)
}
#[pallet::call_index(10)]
#[pallet::weight(T::WeightInfo::remove_network())]
pub fn remove_network(
origin: OriginFor<T>,
chain_id: T::NetworkId,
) -> DispatchResult {
T::RemoveOrigin::ensure_origin_or_root(origin)?;
Self::do_remove_network(chain_id)
}
}
}
impl<T: Config> Pallet<T> {
/// Register a new network.
pub fn do_register_network(
chain_id: T::NetworkId,
network: NetworkData,
) -> DispatchResult {
Networks::<T>::try_mutate(&chain_id, |maybe_network| -> DispatchResult {
ensure!(maybe_network.is_none(), Error::<T>::NetworkAlreadyRegistered);
*maybe_network = Some(network.clone());
Ok(())
})?;
Self::deposit_event(Event::<T>::NetworkRegistered { chain_id, network });
Ok(())
}
/// Remove existent network.
pub fn do_remove_network(chain_id: T::NetworkId) -> DispatchResult {
Networks::<T>::try_mutate(&chain_id, |maybe_network| -> DispatchResult {
ensure!(maybe_network.is_some(), Error::<T>::NetworkDoesNotExist);
*maybe_network = None;
Ok(())
})?;
Self::deposit_event(Event::<T>::NetworkRemoved { chain_id });
Ok(())
}
/// Update existent network name.
pub fn do_update_network_name(
chain_id: T::NetworkId,
chain_name: Vec<u8>,
) -> DispatchResult {
Networks::<T>::try_mutate(&chain_id, |maybe_network| -> DispatchResult {
ensure!(maybe_network.is_some(), Error::<T>::NetworkDoesNotExist);
let net = maybe_network.as_mut().unwrap();
net.chain_name = chain_name.clone();
*maybe_network = Some(net.clone());
Ok(())
})?;
Self::deposit_event(Event::<T>::NetworkNameUpdated {
chain_id,
chain_name,
});
Ok(())
}
/// Update existent network default endpoint.
pub fn do_update_network_endpoint(
chain_id: T::NetworkId,
default_endpoint: Vec<u8>,
) -> DispatchResult {
Networks::<T>::try_mutate(&chain_id, |maybe_network| -> DispatchResult {
ensure!(maybe_network.is_some(), Error::<T>::NetworkDoesNotExist);
let net = maybe_network.as_mut().unwrap();
net.default_endpoint = default_endpoint.clone();
*maybe_network = Some(net.clone());
Ok(())
})?;
Self::deposit_event(Event::<T>::NetworkEndpointUpdated {
chain_id,
default_endpoint,
});
Ok(())
}
/// Update existent network default endpoint.
pub fn do_update_network_finality_delay(
chain_id: T::NetworkId,
finality_delay: Option<u64>,
) -> DispatchResult {
Networks::<T>::try_mutate(&chain_id, |maybe_network| -> DispatchResult {
ensure!(maybe_network.is_some(), Error::<T>::NetworkDoesNotExist);
let net = maybe_network.as_mut().unwrap();
net.finality_delay = finality_delay;
*maybe_network = Some(net.clone());
Ok(())
})?;
Self::deposit_event(Event::<T>::NetworkFinalityDelayUpdated {
chain_id,
finality_delay,
});
Ok(())
}
/// Update existent network default endpoint.
pub fn do_update_network_release_delay(
chain_id: T::NetworkId,
release_delay: Option<u64>,
) -> DispatchResult {
Networks::<T>::try_mutate(&chain_id, |maybe_network| -> DispatchResult {
ensure!(maybe_network.is_some(), Error::<T>::NetworkDoesNotExist);
let net = maybe_network.as_mut().unwrap();
net.release_delay = release_delay;
*maybe_network = Some(net.clone());
Ok(())
})?;
Self::deposit_event(Event::<T>::NetworkReleaseDelayUpdated {
chain_id,
release_delay,
});
Ok(())
}
/// Update existent network type.
pub fn do_update_network_type(
chain_id: T::NetworkId,
network_type: NetworkType,
) -> DispatchResult {
Networks::<T>::try_mutate(&chain_id, |maybe_network| -> DispatchResult {
ensure!(maybe_network.is_some(), Error::<T>::NetworkDoesNotExist);
let net = maybe_network.as_mut().unwrap();
net.network_type = network_type.clone();
*maybe_network = Some(net.clone());
Ok(())
})?;
Self::deposit_event(Event::<T>::NetworkTypeUpdated {
chain_id,
network_type,
});
Ok(())
}
/// Update existent network gatekeeper.
pub fn do_update_network_gatekeeper(
chain_id: T::NetworkId,
gatekeeper: Vec<u8>,
) -> DispatchResult {
ensure!(gatekeeper.len() == 42 && gatekeeper[0] == 48 && gatekeeper[1] == 120,
Error::<T>::WrongGatekeeperAddress);
Networks::<T>::try_mutate(&chain_id, |maybe_network| -> DispatchResult {
ensure!(maybe_network.is_some(), Error::<T>::NetworkDoesNotExist);
let net = maybe_network.as_mut().unwrap();
net.gatekeeper = gatekeeper.clone();
*maybe_network = Some(net.clone());
Ok(())
})?;
Self::deposit_event(Event::<T>::NetworkGatekeeperUpdated {
chain_id,
gatekeeper,
});
Ok(())
}
/// Update existent network gatekeeper's topic name.
pub fn do_update_network_topic_name(
chain_id: T::NetworkId,
topic_name: Vec<u8>,
) -> DispatchResult {
ensure!(topic_name.len() == 66 && topic_name[0] == 48 && topic_name[1] == 120,
Error::<T>::WrongTopicName);
Networks::<T>::try_mutate(&chain_id, |maybe_network| -> DispatchResult {
ensure!(maybe_network.is_some(), Error::<T>::NetworkDoesNotExist);
let net = maybe_network.as_mut().unwrap();
net.topic_name = topic_name.clone();
*maybe_network = Some(net.clone());
Ok(())
})?;
Self::deposit_event(Event::<T>::NetworkTopicNameUpdated {
chain_id,
topic_name,
});
Ok(())
}
pub fn do_update_incoming_network_fee(
chain_id: T::NetworkId,
incoming_fee: u32,
) -> DispatchResult {
Networks::<T>::try_mutate(&chain_id, |maybe_network| -> DispatchResult {
ensure!(maybe_network.is_some(), Error::<T>::NetworkDoesNotExist);
let net = maybe_network.as_mut().unwrap();
net.incoming_fee = incoming_fee.clone();
*maybe_network = Some(net.clone());
Ok(())
})?;
Self::deposit_event(Event::<T>::NetworkIncomingFeeUpdated {
chain_id,
incoming_fee,
});
Ok(())
}
pub fn do_update_outgoing_network_fee(
chain_id: T::NetworkId,
outgoing_fee: u32,
) -> DispatchResult {
Networks::<T>::try_mutate(&chain_id, |maybe_network| -> DispatchResult {
ensure!(maybe_network.is_some(), Error::<T>::NetworkDoesNotExist);
let net = maybe_network.as_mut().unwrap();
net.outgoing_fee = outgoing_fee.clone();
*maybe_network = Some(net.clone());
Ok(())
})?;
Self::deposit_event(Event::<T>::NetworkOutgoingFeeUpdated {
chain_id,
outgoing_fee,
});
Ok(())
}
}
impl<T: Config> NetworkDataBasicHandler for Pallet<T> {
type NetworkId = T::NetworkId;
}
impl<T: Config> NetworkDataInspectHandler<NetworkData> for Pallet<T> {
fn get(n: &Self::NetworkId) -> Option<NetworkData> {
Networks::<T>::get(n)
}
fn iter() -> PrefixIterator<(Self::NetworkId, NetworkData)> {
Networks::<T>::iter()
}
}
impl<T: Config> NetworkDataMutateHandler<NetworkData> for Pallet<T> {
fn register(chain_id: Self::NetworkId, network: NetworkData) -> DispatchResult {
Self::do_register_network(chain_id, network)
}
fn remove(chain_id: Self::NetworkId) -> DispatchResult {
Self::do_remove_network(chain_id)
}
}

104
pallets/networks/src/mock.rs Executable file
View File

@@ -0,0 +1,104 @@
use crate as ghost_networks;
use frame_system::EnsureSignedBy;
use frame_support::{
construct_runtime, ord_parameter_types, parameter_types, traits::{ConstU128, ConstU32, Everything}
};
pub use primitives::{
AccountId, Balance, Nonce, BlockNumber, Hash,
ReserveIdentifier, FreezeIdentifier,
};
use sp_runtime::{
traits::{BlakeTwo256, AccountIdLookup},
BuildStorage,
};
parameter_types! {
pub const BlockHashCount: BlockNumber = 250;
}
impl frame_system::Config for Test {
type RuntimeEvent = RuntimeEvent;
type BaseCallFilter = Everything;
type BlockWeights = ();
type BlockLength = ();
type RuntimeOrigin = RuntimeOrigin;
type RuntimeCall = RuntimeCall;
type RuntimeTask = ();
type Nonce = Nonce;
type Hash = Hash;
type Hashing = BlakeTwo256;
type AccountId = AccountId;
type Lookup = AccountIdLookup<Self::AccountId, ()>;
type Block = Block;
type BlockHashCount = BlockHashCount;
type DbWeight = ();
type Version = ();
type PalletInfo = PalletInfo;
type AccountData = pallet_balances::AccountData<Balance>;
type OnNewAccount = ();
type OnKilledAccount = ();
type SystemWeightInfo = ();
type SS58Prefix = ();
type OnSetCode = ();
type MaxConsumers = ConstU32<16>;
type SingleBlockMigrations = ();
type MultiBlockMigrator = ();
type PreInherents = ();
type PostInherents = ();
type PostTransactions = ();
}
impl pallet_balances::Config for Test {
type RuntimeEvent = RuntimeEvent;
type RuntimeHoldReason = ();
type RuntimeFreezeReason = ();
type WeightInfo = ();
type Balance = Balance;
type DustRemoval = ();
type ExistentialDeposit = ConstU128<1>;
type AccountStore = System;
type ReserveIdentifier = ReserveIdentifier;
type FreezeIdentifier = FreezeIdentifier;
type MaxLocks = ();
type MaxReserves = ConstU32<50>;
type MaxFreezes = ConstU32<50>;
}
ord_parameter_types! {
pub const RegistererAccount: AccountId = AccountId::from([1u8; 32]);
pub const UpdaterAccount: AccountId = AccountId::from([2u8; 32]);
pub const RemoverAccount: AccountId = AccountId::from([3u8; 32]);
pub const RandomAccount: AccountId = AccountId::from([4u8; 32]);
}
impl ghost_networks::Config for Test {
type RuntimeEvent = RuntimeEvent;
type NetworkId = u32;
type RegisterOrigin = EnsureSignedBy::<RegistererAccount, AccountId>;
type UpdateOrigin = EnsureSignedBy::<UpdaterAccount, AccountId>;
type RemoveOrigin = EnsureSignedBy::<RemoverAccount, AccountId>;
type WeightInfo = crate::weights::SubstrateWeight<Test>;
}
type Block = frame_system::mocking::MockBlockU32<Test>;
construct_runtime!(
pub enum Test {
System: frame_system,
Balances: pallet_balances,
GhostNetworks: ghost_networks,
}
);
pub(crate) struct ExtBuilder();
impl ExtBuilder {
pub(crate) fn build() -> sp_io::TestExternalities {
let t = frame_system::GenesisConfig::<Test>::default()
.build_storage()
.expect("Frame system builds valid default genesis config; qed");
let mut ext: sp_io::TestExternalities = t.into();
ext.execute_with(|| System::set_block_number(1));
ext
}
}

637
pallets/networks/src/tests.rs Executable file
View File

@@ -0,0 +1,637 @@
use mock::{
ExtBuilder, System, RegistererAccount, UpdaterAccount, RemoverAccount,
RandomAccount, GhostNetworks, Test, RuntimeEvent, RuntimeOrigin,
};
use frame_support::{assert_err, assert_ok};
use sp_runtime::DispatchError;
use super::*;
fn prepare_network_data() -> (u32, NetworkData) {
(1u32, NetworkData {
chain_name: "Ethereum".into(),
default_endpoint:
"https:://some-endpoint.my-server.com/v1/my-super-secret-key".into(),
finality_delay: Some(69),
release_delay: Some(69),
network_type: NetworkType::Evm,
gatekeeper: b"0x1234567891234567891234567891234567891234".to_vec(),
topic_name: b"0x12345678912345678912345678912345678912345678912345678912345678".to_vec(),
incoming_fee: 0,
outgoing_fee: 0,
})
}
fn register_and_check_network(chain_id: u32, network: NetworkData) {
assert_ok!(GhostNetworks::register_network(
RuntimeOrigin::signed(RegistererAccount::get()),
chain_id,
network.clone()));
assert_eq!(Networks::<Test>::get(chain_id), Some(network.clone()));
}
#[test]
fn could_add_network_from_authority() {
ExtBuilder::build()
.execute_with(|| {
let (chain_id, network) = prepare_network_data();
assert_eq!(Networks::<Test>::get(chain_id), None);
assert_ok!(GhostNetworks::register_network(
RuntimeOrigin::signed(RegistererAccount::get()),
chain_id,
network.clone(),
));
System::assert_last_event(RuntimeEvent::GhostNetworks(
crate::Event::NetworkRegistered {
chain_id, network: network.clone()
}));
assert_eq!(Networks::<Test>::get(chain_id), Some(network));
});
}
#[test]
fn could_not_add_network_from_random_account() {
ExtBuilder::build()
.execute_with(|| {
let (chain_id, network) = prepare_network_data();
assert_eq!(Networks::<Test>::get(chain_id), None);
assert_err!(GhostNetworks::register_network(
RuntimeOrigin::signed(RandomAccount::get()),
chain_id,
network.clone(),
), DispatchError::BadOrigin);
assert_err!(GhostNetworks::register_network(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id,
network.clone(),
), DispatchError::BadOrigin);
assert_err!(GhostNetworks::register_network(
RuntimeOrigin::signed(RemoverAccount::get()),
chain_id,
network,
), DispatchError::BadOrigin);
assert_eq!(Networks::<Test>::get(chain_id), None);
});
}
#[test]
fn could_update_network_name_from_authority_account() {
ExtBuilder::build()
.execute_with(|| {
let new_name = b"Polygon".to_vec();
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_ok!(GhostNetworks::update_network_name(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id, new_name.clone()));
System::assert_last_event(RuntimeEvent::GhostNetworks(
crate::Event::NetworkNameUpdated {
chain_id,
chain_name: new_name.clone() }));
let mut final_network = network.clone();
final_network.chain_name = new_name;
assert_eq!(Networks::<Test>::get(chain_id), Some(final_network.clone()));
assert_ne!(network, final_network);
});
}
#[test]
fn could_update_network_endpoint_from_authority_account() {
ExtBuilder::build()
.execute_with(|| {
let new_endpoint = b"https:://google.com".to_vec();
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_ok!(GhostNetworks::update_network_endpoint(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id, new_endpoint.clone()));
System::assert_last_event(RuntimeEvent::GhostNetworks(
crate::Event::NetworkEndpointUpdated {
chain_id,
default_endpoint: new_endpoint.clone() }));
let mut final_network = network.clone();
final_network.default_endpoint = new_endpoint;
assert_eq!(Networks::<Test>::get(chain_id), Some(final_network.clone()));
assert_ne!(network, final_network);
});
}
#[test]
fn could_update_network_finality_delay_from_authority_account() {
ExtBuilder::build()
.execute_with(|| {
let new_finality_delay = Some(1337);
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_ok!(GhostNetworks::update_network_finality_delay(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id, new_finality_delay));
System::assert_last_event(RuntimeEvent::GhostNetworks(
crate::Event::NetworkFinalityDelayUpdated {
chain_id,
finality_delay: new_finality_delay }));
let mut final_network = network.clone();
final_network.finality_delay = new_finality_delay;
assert_eq!(Networks::<Test>::get(chain_id), Some(final_network.clone()));
assert_ne!(network, final_network);
});
}
#[test]
fn could_update_network_release_delay_from_authority_account() {
ExtBuilder::build()
.execute_with(|| {
let new_release_delay = Some(1337);
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_ok!(GhostNetworks::update_network_release_delay(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id, new_release_delay));
System::assert_last_event(RuntimeEvent::GhostNetworks(
crate::Event::NetworkReleaseDelayUpdated {
chain_id,
release_delay: new_release_delay }));
let mut final_network = network.clone();
final_network.release_delay = new_release_delay;
assert_eq!(Networks::<Test>::get(chain_id), Some(final_network.clone()));
assert_ne!(network, final_network);
});
}
#[test]
fn could_update_network_type_from_authority_account() {
ExtBuilder::build()
.execute_with(|| {
let new_type = NetworkType::Utxo;
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_ok!(GhostNetworks::update_network_type(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id, new_type.clone()));
System::assert_last_event(RuntimeEvent::GhostNetworks(
crate::Event::NetworkTypeUpdated {
chain_id,
network_type: new_type.clone() }));
let mut final_network = network.clone();
final_network.network_type = new_type;
assert_eq!(Networks::<Test>::get(chain_id), Some(final_network.clone()));
assert_ne!(network, final_network);
});
}
#[test]
fn could_update_network_gatekeeper_from_authority_account() {
ExtBuilder::build()
.execute_with(|| {
let new_gatekeeper = b"0x9876543219876543219876543219876543219876".to_vec();
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_ok!(GhostNetworks::update_network_gatekeeper(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id, new_gatekeeper.clone()));
System::assert_last_event(RuntimeEvent::GhostNetworks(
crate::Event::NetworkGatekeeperUpdated {
chain_id,
gatekeeper: new_gatekeeper.clone() }));
let mut final_network = network.clone();
final_network.gatekeeper = new_gatekeeper;
assert_eq!(Networks::<Test>::get(chain_id), Some(final_network.clone()));
assert_ne!(network, final_network);
});
}
#[test]
fn could_update_network_topic_name_from_authority_account() {
ExtBuilder::build()
.execute_with(|| {
let new_topic_name = b"0x9876543219876543219876543219876543219876543219876543219876543219".to_vec();
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_ok!(GhostNetworks::update_network_topic_name(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id, new_topic_name.clone()));
System::assert_last_event(RuntimeEvent::GhostNetworks(
crate::Event::NetworkTopicNameUpdated {
chain_id,
topic_name: new_topic_name.clone() }));
let mut final_network = network.clone();
final_network.topic_name = new_topic_name;
assert_eq!(Networks::<Test>::get(chain_id), Some(final_network.clone()));
assert_ne!(network, final_network);
});
}
#[test]
fn could_update_incoming_network_fee_from_authority_account() {
ExtBuilder::build()
.execute_with(|| {
let new_incoming_fee = 69;
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_ok!(GhostNetworks::update_incoming_network_fee(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id, new_incoming_fee));
System::assert_last_event(RuntimeEvent::GhostNetworks(
crate::Event::NetworkIncomingFeeUpdated {
chain_id,
incoming_fee: new_incoming_fee }));
let mut final_network = network.clone();
final_network.incoming_fee = new_incoming_fee;
assert_eq!(Networks::<Test>::get(chain_id), Some(final_network.clone()));
assert_ne!(network, final_network);
});
}
#[test]
fn could_update_outgoing_network_fee_from_authority_account() {
ExtBuilder::build()
.execute_with(|| {
let new_outgoing_fee = 69;
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_ok!(GhostNetworks::update_outgoing_network_fee(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id, new_outgoing_fee));
System::assert_last_event(RuntimeEvent::GhostNetworks(
crate::Event::NetworkOutgoingFeeUpdated {
chain_id,
outgoing_fee: new_outgoing_fee }));
let mut final_network = network.clone();
final_network.outgoing_fee = new_outgoing_fee;
assert_eq!(Networks::<Test>::get(chain_id), Some(final_network.clone()));
assert_ne!(network, final_network);
});
}
#[test]
fn could_not_update_network_name_from_random_account() {
ExtBuilder::build()
.execute_with(|| {
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_err!(GhostNetworks::update_network_name(
RuntimeOrigin::signed(RegistererAccount::get()),
chain_id, "Binance".into()),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::update_network_name(
RuntimeOrigin::signed(RemoverAccount::get()),
chain_id, "Binance".into()),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::update_network_name(
RuntimeOrigin::signed(RandomAccount::get()),
chain_id, "Binance".into()),
DispatchError::BadOrigin);
assert_eq!(Networks::<Test>::get(chain_id), Some(network));
});
}
#[test]
fn could_not_update_network_endpoint_from_random_account() {
ExtBuilder::build()
.execute_with(|| {
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_err!(GhostNetworks::update_network_endpoint(
RuntimeOrigin::signed(RegistererAccount::get()),
chain_id, "https:://google.com".into()),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::update_network_endpoint(
RuntimeOrigin::signed(RemoverAccount::get()),
chain_id, "https:://google.com".into()),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::update_network_endpoint(
RuntimeOrigin::signed(RandomAccount::get()),
chain_id, "https:://google.com".into()),
DispatchError::BadOrigin);
assert_eq!(Networks::<Test>::get(chain_id), Some(network));
});
}
#[test]
fn could_not_update_network_finality_delay_from_random_account() {
ExtBuilder::build()
.execute_with(|| {
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_err!(GhostNetworks::update_network_finality_delay(
RuntimeOrigin::signed(RegistererAccount::get()),
chain_id, Some(1337)),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::update_network_finality_delay(
RuntimeOrigin::signed(RemoverAccount::get()),
chain_id, Some(1337)),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::update_network_finality_delay(
RuntimeOrigin::signed(RandomAccount::get()),
chain_id, Some(1337)),
DispatchError::BadOrigin);
assert_eq!(Networks::<Test>::get(chain_id), Some(network));
});
}
#[test]
fn could_not_update_network_release_delay_from_random_account() {
ExtBuilder::build()
.execute_with(|| {
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_err!(GhostNetworks::update_network_release_delay(
RuntimeOrigin::signed(RegistererAccount::get()),
chain_id, Some(1337)),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::update_network_release_delay(
RuntimeOrigin::signed(RemoverAccount::get()),
chain_id, Some(1337)),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::update_network_release_delay(
RuntimeOrigin::signed(RandomAccount::get()),
chain_id, Some(1337)),
DispatchError::BadOrigin);
assert_eq!(Networks::<Test>::get(chain_id), Some(network));
});
}
#[test]
fn could_not_update_network_type_from_random_account() {
ExtBuilder::build()
.execute_with(|| {
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_err!(GhostNetworks::update_network_type(
RuntimeOrigin::signed(RegistererAccount::get()),
chain_id, NetworkType::Utxo),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::update_network_type(
RuntimeOrigin::signed(RemoverAccount::get()),
chain_id, NetworkType::Utxo),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::update_network_type(
RuntimeOrigin::signed(RandomAccount::get()),
chain_id, NetworkType::Utxo),
DispatchError::BadOrigin);
assert_eq!(Networks::<Test>::get(chain_id), Some(network));
});
}
#[test]
fn could_not_update_network_gatekeeper_from_random_account() {
ExtBuilder::build()
.execute_with(|| {
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_err!(GhostNetworks::update_network_gatekeeper(
RuntimeOrigin::signed(RegistererAccount::get()),
chain_id, b"0x9876543219876543219876543219876543219876".to_vec()),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::update_network_gatekeeper(
RuntimeOrigin::signed(RemoverAccount::get()),
chain_id, b"0x9876543219876543219876543219876543219876".to_vec()),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::update_network_gatekeeper(
RuntimeOrigin::signed(RandomAccount::get()),
chain_id, b"0x9876543219876543219876543219876543219876".to_vec()),
DispatchError::BadOrigin);
assert_eq!(Networks::<Test>::get(chain_id), Some(network));
});
}
#[test]
fn could_not_update_network_topic_name_from_random_account() {
ExtBuilder::build()
.execute_with(|| {
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_err!(GhostNetworks::update_network_topic_name(
RuntimeOrigin::signed(RegistererAccount::get()),
chain_id, b"0x9876543219876543219876543219876543219876543219876543219876543219".to_vec()),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::update_network_topic_name(
RuntimeOrigin::signed(RemoverAccount::get()),
chain_id, b"0x9876543219876543219876543219876543219876543219876543219876543219".to_vec()),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::update_network_topic_name(
RuntimeOrigin::signed(RandomAccount::get()),
chain_id, b"0x9876543219876543219876543219876543219876543219876543219876543219".to_vec()),
DispatchError::BadOrigin);
assert_eq!(Networks::<Test>::get(chain_id), Some(network));
});
}
#[test]
fn could_not_update_network_incoming_fee_from_random_account() {
ExtBuilder::build()
.execute_with(|| {
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_err!(GhostNetworks::update_incoming_network_fee(
RuntimeOrigin::signed(RegistererAccount::get()),
chain_id, 69),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::update_incoming_network_fee(
RuntimeOrigin::signed(RemoverAccount::get()),
chain_id, 69),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::update_incoming_network_fee(
RuntimeOrigin::signed(RandomAccount::get()),
chain_id, 69),
DispatchError::BadOrigin);
assert_eq!(Networks::<Test>::get(chain_id), Some(network));
});
}
#[test]
fn could_not_update_network_outgoing_fee_from_random_account() {
ExtBuilder::build()
.execute_with(|| {
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_err!(GhostNetworks::update_outgoing_network_fee(
RuntimeOrigin::signed(RegistererAccount::get()),
chain_id, 69),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::update_outgoing_network_fee(
RuntimeOrigin::signed(RemoverAccount::get()),
chain_id, 69),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::update_outgoing_network_fee(
RuntimeOrigin::signed(RandomAccount::get()),
chain_id, 69),
DispatchError::BadOrigin);
assert_eq!(Networks::<Test>::get(chain_id), Some(network));
});
}
#[test]
fn could_not_update_name_for_non_existent_network() {
ExtBuilder::build()
.execute_with(|| {
let chain_id: u32 = 1;
assert_eq!(Networks::<Test>::get(chain_id), None);
assert_err!(GhostNetworks::update_network_name(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id, "Binance".into()),
crate::Error::<Test>::NetworkDoesNotExist);
assert_eq!(Networks::<Test>::get(chain_id), None);
});
}
#[test]
fn could_not_update_endpoint_for_non_existent_network() {
ExtBuilder::build()
.execute_with(|| {
let chain_id: u32 = 1;
assert_eq!(Networks::<Test>::get(chain_id), None);
assert_err!(GhostNetworks::update_network_endpoint(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id, "https:://google.com".into()),
crate::Error::<Test>::NetworkDoesNotExist);
assert_eq!(Networks::<Test>::get(chain_id), None);
});
}
#[test]
fn could_not_update_finality_delay_for_non_existent_network() {
ExtBuilder::build()
.execute_with(|| {
let chain_id: u32 = 1;
assert_eq!(Networks::<Test>::get(chain_id), None);
assert_err!(GhostNetworks::update_network_finality_delay(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id, Some(1337)),
crate::Error::<Test>::NetworkDoesNotExist);
assert_eq!(Networks::<Test>::get(chain_id), None);
});
}
#[test]
fn could_not_update_release_delay_for_non_existent_network() {
ExtBuilder::build()
.execute_with(|| {
let chain_id: u32 = 1;
assert_eq!(Networks::<Test>::get(chain_id), None);
assert_err!(GhostNetworks::update_network_release_delay(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id, Some(1337)),
crate::Error::<Test>::NetworkDoesNotExist);
assert_eq!(Networks::<Test>::get(chain_id), None);
});
}
#[test]
fn could_not_update_type_for_non_existent_network() {
ExtBuilder::build()
.execute_with(|| {
let chain_id: u32 = 1;
assert_eq!(Networks::<Test>::get(chain_id), None);
assert_err!(GhostNetworks::update_network_type(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id, NetworkType::Utxo),
crate::Error::<Test>::NetworkDoesNotExist);
assert_eq!(Networks::<Test>::get(chain_id), None);
});
}
#[test]
fn could_not_update_gatekeeper_for_non_existent_network() {
ExtBuilder::build()
.execute_with(|| {
let chain_id: u32 = 1;
assert_eq!(Networks::<Test>::get(chain_id), None);
assert_err!(GhostNetworks::update_network_gatekeeper(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id, b"0x9876543219876543219876543219876543219876".to_vec()),
crate::Error::<Test>::NetworkDoesNotExist);
assert_eq!(Networks::<Test>::get(chain_id), None);
});
}
#[test]
fn could_not_update_topic_name_for_non_existent_network() {
ExtBuilder::build()
.execute_with(|| {
let chain_id: u32 = 1;
assert_eq!(Networks::<Test>::get(chain_id), None);
assert_err!(GhostNetworks::update_network_topic_name(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id, b"0x9876543219876543219876543219876543219876543219876543219876543219".to_vec()),
crate::Error::<Test>::NetworkDoesNotExist);
assert_eq!(Networks::<Test>::get(chain_id), None);
});
}
#[test]
fn could_not_update_incoming_fee_for_non_existent_network() {
ExtBuilder::build()
.execute_with(|| {
let chain_id: u32 = 1;
assert_eq!(Networks::<Test>::get(chain_id), None);
assert_err!(GhostNetworks::update_incoming_network_fee(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id, 1337),
crate::Error::<Test>::NetworkDoesNotExist);
assert_eq!(Networks::<Test>::get(chain_id), None);
});
}
#[test]
fn could_not_update_outgoing_fee_for_non_existent_network() {
ExtBuilder::build()
.execute_with(|| {
let chain_id: u32 = 1;
assert_eq!(Networks::<Test>::get(chain_id), None);
assert_err!(GhostNetworks::update_outgoing_network_fee(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id, 1337),
crate::Error::<Test>::NetworkDoesNotExist);
assert_eq!(Networks::<Test>::get(chain_id), None);
});
}
#[test]
fn could_remove_network_from_authority_account() {
ExtBuilder::build()
.execute_with(|| {
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_ok!(GhostNetworks::remove_network(
RuntimeOrigin::signed(RemoverAccount::get()),
chain_id,
));
assert_eq!(Networks::<Test>::get(chain_id), None);
});
}
#[test]
fn could_not_remove_network_from_random_account() {
ExtBuilder::build()
.execute_with(|| {
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_err!(GhostNetworks::remove_network(
RuntimeOrigin::signed(RegistererAccount::get()),
chain_id),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::remove_network(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::remove_network(
RuntimeOrigin::signed(RandomAccount::get()),
chain_id),
DispatchError::BadOrigin);
assert_eq!(Networks::<Test>::get(chain_id), Some(network));
});
}
#[test]
fn could_not_remove_non_existent_network() {
ExtBuilder::build()
.execute_with(|| {
let chain_id: u32 = 1;
assert_eq!(Networks::<Test>::get(chain_id), None);
assert_err!(GhostNetworks::remove_network(
RuntimeOrigin::signed(RemoverAccount::get()),
chain_id),
crate::Error::<Test>::NetworkDoesNotExist);
assert_eq!(Networks::<Test>::get(chain_id), None);
});
}

325
pallets/networks/src/weights.rs Executable file
View File

@@ -0,0 +1,325 @@
// This file is part of Ghost Network.
// Ghost Network is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Ghost Network is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Ghost Network. If not, see <http://www.gnu.org/licenses/>.
//! Autogenerated weights for `ghost_networks`
//!
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
//! DATE: 2023-11-29, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! WORST CASE MAP SIZE: `1000000`
//! HOSTNAME: `ghost`, CPU: `Intel(R) Core(TM) i3-2310M CPU @ 2.10GHz`
//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("casper-dev"), DB CACHE: 1024
// Executed Command:
// ./target/production/ghost
// benchmark
// pallet
// --chain=casper-dev
// --steps=50
// --repeat=20
// --pallet=ghost_networks
// --extrinsic=*
// --execution=wasm
// --wasm-execution=compiled
// --header=./file_header.txt
// --output=./runtime/casper/src/weights/ghost_networks.rs
#![cfg_attr(rustfmt, rustfmt_skip)]
#![allow(unused_parens)]
#![allow(unused_imports)]
use frame_support::{
traits::Get,
weights::{
Weight, constants::RocksDbWeight
}
};
use sp_std::marker::PhantomData;
/// Weight functions needed for ghost_networks
pub trait WeightInfo {
fn register_network(n: u32, m: u32, ) -> Weight;
fn update_network_name(n: u32, ) -> Weight;
fn update_network_endpoint(n: u32, ) -> Weight;
fn update_network_finality_delay() -> Weight;
fn update_network_release_delay() -> Weight;
fn update_network_type() -> Weight;
fn update_network_gatekeeper() -> Weight;
fn update_network_topic_name() -> Weight;
fn update_incoming_network_fee() -> Weight;
fn update_outgoing_network_fee() -> Weight;
fn remove_network() -> Weight;
}
/// Weight for ghost_networks using the Substrate node and recommended hardware.
pub struct SubstrateWeight<T>(PhantomData<T>);
impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
/// The range of component `n` is `[1, 20]`.
/// The range of component `m` is `[1, 150]`.
fn register_network(_n: u32, _m: u32, ) -> Weight {
// Proof Size summary in bytes:
// Measured: `76`
// Estimated: `2551`
// Minimum execution time: 32_086 nanoseconds.
Weight::from_parts(33_092_855, 2551)
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
/// The range of component `n` is `[1, 20]`.
fn update_network_name(_n: u32, ) -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 34_496 nanoseconds.
Weight::from_parts(35_728_230, 2616)
// Standard Error: 2_591
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
/// The range of component `n` is `[1, 150]`.
fn update_network_endpoint(_n: u32, ) -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 34_666 nanoseconds.
Weight::from_parts(35_959_961, 2616)
// Standard Error: 381
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
fn update_network_finality_delay() -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 33_860 nanoseconds.
Weight::from_parts(34_995_000, 2616)
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
fn update_network_release_delay() -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 33_860 nanoseconds.
Weight::from_parts(34_995_000, 2616)
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
fn update_network_type() -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 34_976 nanoseconds.
Weight::from_parts(36_182_000, 2616)
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
fn update_network_gatekeeper() -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 34_768 nanoseconds.
Weight::from_parts(35_580_000, 2616)
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
fn update_network_topic_name() -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 34_768 nanoseconds.
Weight::from_parts(35_580_000, 2616)
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
fn update_incoming_network_fee() -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 34_768 nanoseconds.
Weight::from_parts(35_580_000, 2616)
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
fn update_outgoing_network_fee() -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 34_768 nanoseconds.
Weight::from_parts(35_580_000, 2616)
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
fn remove_network() -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 33_336 nanoseconds.
Weight::from_parts(34_609_000, 2616)
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
}
impl WeightInfo for () {
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
/// The range of component `n` is `[1, 20]`.
/// The range of component `m` is `[1, 150]`.
fn register_network(_n: u32, _m: u32, ) -> Weight {
// Proof Size summary in bytes:
// Measured: `76`
// Estimated: `2551`
// Minimum execution time: 32_086 nanoseconds.
Weight::from_parts(33_092_855, 2551)
.saturating_add(RocksDbWeight::get().reads(1))
.saturating_add(RocksDbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
/// The range of component `n` is `[1, 20]`.
fn update_network_name(_n: u32, ) -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 34_496 nanoseconds.
Weight::from_parts(35_728_230, 2616)
// Standard Error: 2_591
.saturating_add(RocksDbWeight::get().reads(1))
.saturating_add(RocksDbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
/// The range of component `n` is `[1, 150]`.
fn update_network_endpoint(_n: u32, ) -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 34_666 nanoseconds.
Weight::from_parts(35_959_961, 2616)
// Standard Error: 381
.saturating_add(RocksDbWeight::get().reads(1))
.saturating_add(RocksDbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
fn update_network_finality_delay() -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 33_860 nanoseconds.
Weight::from_parts(34_995_000, 2616)
.saturating_add(RocksDbWeight::get().reads(1))
.saturating_add(RocksDbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
fn update_network_release_delay() -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 33_860 nanoseconds.
Weight::from_parts(34_995_000, 2616)
.saturating_add(RocksDbWeight::get().reads(1))
.saturating_add(RocksDbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
fn update_network_type() -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 34_976 nanoseconds.
Weight::from_parts(36_182_000, 2616)
.saturating_add(RocksDbWeight::get().reads(1))
.saturating_add(RocksDbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
fn update_network_gatekeeper() -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 34_768 nanoseconds.
Weight::from_parts(35_580_000, 2616)
.saturating_add(RocksDbWeight::get().reads(1))
.saturating_add(RocksDbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
fn update_network_topic_name() -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 34_768 nanoseconds.
Weight::from_parts(35_580_000, 2616)
.saturating_add(RocksDbWeight::get().reads(1))
.saturating_add(RocksDbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
fn update_incoming_network_fee() -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 34_768 nanoseconds.
Weight::from_parts(35_580_000, 2616)
.saturating_add(RocksDbWeight::get().reads(1))
.saturating_add(RocksDbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
fn update_outgoing_network_fee() -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 34_768 nanoseconds.
Weight::from_parts(35_580_000, 2616)
.saturating_add(RocksDbWeight::get().reads(1))
.saturating_add(RocksDbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
fn remove_network() -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 33_336 nanoseconds.
Weight::from_parts(34_609_000, 2616)
.saturating_add(RocksDbWeight::get().reads(1))
.saturating_add(RocksDbWeight::get().writes(1))
}
}