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

Update subxt to bounded types #1212

Merged
merged 3 commits into from
Oct 17, 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
7 changes: 4 additions & 3 deletions pallets/dmail/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ use scale_info::prelude::string::String;

use frame_system::RawOrigin;
use polkadot_sdk::frame_benchmarking::benchmarks;
use polkadot_sdk::frame_system;
use polkadot_sdk::{frame_system, sp_runtime};
use scale_codec::Encode;
use sp_runtime::BoundedVec;
use time_primitives::{DmailPath, DmailTo, DMAIL_PATH_LEN, DMAIL_TO_LEN};

benchmarks! {
Expand All @@ -22,8 +23,8 @@ benchmarks! {
for _ in 0..b {
path.push('b');
}
let to = DmailTo::truncate_from(to.as_str().encode());
let path = DmailPath::truncate_from(path.as_str().encode());
let to = DmailTo(BoundedVec::truncate_from(to.as_str().encode()));
let path = DmailPath(BoundedVec::truncate_from(path.as_str().encode()));
}: _(RawOrigin::Signed([0u8; 32].into()), to, path)
verify {}

Expand Down
2 changes: 1 addition & 1 deletion pallets/dmail/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ pub mod pallet {
#[pallet::call]
impl<T: Config> Pallet<T> {
#[pallet::call_index(0)]
#[pallet::weight(T::WeightInfo::send_email(to.len() as u32, path.len() as u32))]
#[pallet::weight(T::WeightInfo::send_email(to.0.len() as u32, path.0.len() as u32))]
pub fn send_email(origin: OriginFor<T>, to: DmailTo, path: DmailPath) -> DispatchResult {
let owner = ensure_signed(origin)?;
let message = DmailMessage { owner, to, path };
Expand Down
7 changes: 4 additions & 3 deletions pallets/dmail/src/tests.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
use crate::mock::*;
use crate::Event;

use polkadot_sdk::{frame_support, frame_system};
use polkadot_sdk::{frame_support, frame_system, sp_runtime};

use frame_support::assert_ok;
use frame_system::RawOrigin;
use scale_codec::Encode;
use sp_runtime::BoundedVec;
use time_primitives::{DmailMessage, DmailPath, DmailTo};

#[test]
fn test_dmail_event() {
let to: DmailTo = DmailTo::truncate_from("Self".encode());
let path: DmailPath = DmailPath::truncate_from("//self".encode());
let to: DmailTo = DmailTo(BoundedVec::truncate_from("Self".encode()));
let path: DmailPath = DmailPath(BoundedVec::truncate_from("//self".encode()));
let sender: AccountId = [1; 32].into();
let event = DmailMessage {
owner: sender.clone(),
Expand Down
7 changes: 4 additions & 3 deletions pallets/networks/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ use crate::Pallet;

use frame_system::RawOrigin;
use polkadot_sdk::frame_benchmarking::benchmarks;
use polkadot_sdk::frame_system;
use polkadot_sdk::{frame_system, sp_runtime};
use scale_codec::Encode;
use scale_info::prelude::string::String;
use sp_runtime::BoundedVec;
use time_primitives::{
ChainName, ChainNetwork, Network, NetworkConfig, CHAIN_NAME_LEN, CHAIN_NET_LEN,
};
Expand All @@ -22,8 +23,8 @@ fn mock_network_config() -> NetworkConfig {
fn mock_network(chain_name: String, chain_network: String) -> Network {
Network {
id: 42,
chain_name: ChainName::truncate_from(chain_name.as_str().encode()),
chain_network: ChainNetwork::truncate_from(chain_network.as_str().encode()),
chain_name: ChainName(BoundedVec::truncate_from(chain_name.as_str().encode())),
chain_network: ChainNetwork(BoundedVec::truncate_from(chain_network.as_str().encode())),
gateway: [0; 32],
gateway_block: 99,
config: mock_network_config(),
Expand Down
2 changes: 1 addition & 1 deletion pallets/networks/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ pub mod pallet {
/// 3. Emit the [`Event::NetworkRegistered`] event with the new `NetworkId`.
/// 4. Return `Ok(())` to indicate success.
#[pallet::call_index(0)]
#[pallet::weight(T::WeightInfo::register_network(network.chain_name.len() as u32, network.chain_network.len() as u32))]
#[pallet::weight(T::WeightInfo::register_network(network.chain_name.0.len() as u32, network.chain_network.0.len() as u32))]
pub fn register_network(origin: OriginFor<T>, network: Network) -> DispatchResult {
T::AdminOrigin::ensure_origin(origin)?;
Self::insert_network(&network)?;
Expand Down
7 changes: 4 additions & 3 deletions pallets/networks/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ use crate::{self as pallet_networks};
use crate::{mock::*, Error};
use frame_support::{assert_noop, assert_ok};
use frame_system::RawOrigin;
use polkadot_sdk::{frame_support, frame_system};
use polkadot_sdk::{frame_support, frame_system, sp_runtime};
use scale_codec::Encode;
use sp_runtime::BoundedVec;
use time_primitives::{ChainName, ChainNetwork, Network, NetworkConfig};

fn mock_network_config() -> NetworkConfig {
Expand All @@ -18,8 +19,8 @@ fn mock_network_config() -> NetworkConfig {
fn mock_network() -> Network {
Network {
id: 42,
chain_name: ChainName::truncate_from("Ethereum".encode()),
chain_network: ChainNetwork::truncate_from("Mainnet".encode()),
chain_name: ChainName(BoundedVec::truncate_from("Ethereum".encode())),
chain_network: ChainNetwork(BoundedVec::truncate_from("Mainnet".encode())),
gateway: [0; 32],
gateway_block: 99,
config: mock_network_config(),
Expand Down
10 changes: 5 additions & 5 deletions pallets/shards/src/benchmarking.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
use super::*;
use crate::Pallet;

use polkadot_sdk::{
frame_benchmarking, frame_support, frame_system, pallet_balances, sp_core, sp_std,
};

use frame_benchmarking::benchmarks;
use frame_support::traits::{Currency, Get};
use frame_system::RawOrigin;
use polkadot_sdk::{
frame_benchmarking, frame_support, frame_system, pallet_balances, sp_core, sp_runtime, sp_std,
};
use sp_runtime::BoundedVec;

use sp_std::vec;
use sp_std::vec::Vec;
Expand Down Expand Up @@ -69,7 +69,7 @@ pub fn get_commitment(member: [u8; 32]) -> Commitment {
panic!("Invalid member")
},
};
Commitment::truncate_from(vec![commitment])
Commitment(BoundedVec::truncate_from(vec![commitment]))
}
pub fn get_proof_of_knowledge(member: [u8; 32]) -> ProofOfKnowledge {
match member {
Expand Down
12 changes: 6 additions & 6 deletions pallets/shards/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -254,10 +254,10 @@ pub mod pallet {
);
let threshold = ShardThreshold::<T>::get(shard_id).unwrap_or_default();
ensure!(
commitment.len() == threshold as usize,
commitment.0.len() == threshold as usize,
Error::<T>::CommitmentLenNotEqualToThreshold
);
for c in &commitment {
for c in &commitment.0 {
ensure!(
VerifyingKey::from_bytes(*c).is_ok(),
Error::<T>::InvalidVerifyingKeyInCommitment
Expand All @@ -267,7 +267,7 @@ pub mod pallet {
T::Members::member_peer_id(&member).ok_or(Error::<T>::MemberPeerIdNotFound)?;
schnorr_evm::proof_of_knowledge::verify_proof_of_knowledge(
&peer_id,
&commitment,
&commitment.0,
proof_of_knowledge,
)
.map_err(|_| Error::<T>::InvalidProofOfKnowledge)?;
Expand All @@ -277,7 +277,7 @@ pub mod pallet {
.filter_map(|(_, status)| status.commitment().cloned())
.reduce(|mut group_commitment, commitment| {
for (group_commitment, commitment) in
group_commitment.iter_mut().zip(commitment.iter())
group_commitment.0.iter_mut().zip(commitment.0.iter())
{
*group_commitment = VerifyingKey::new(
VerifyingKey::from_bytes(*group_commitment)
Expand Down Expand Up @@ -327,7 +327,7 @@ pub mod pallet {
.all(|(_, status)| status == MemberStatus::Ready)
{
<ShardState<T>>::insert(shard_id, ShardStatus::Online);
Self::deposit_event(Event::ShardOnline(shard_id, commitment[0]));
Self::deposit_event(Event::ShardOnline(shard_id, commitment.0[0]));
T::Tasks::shard_online(shard_id, network);
}
Ok(())
Expand Down Expand Up @@ -612,7 +612,7 @@ pub mod pallet {
/// 1. Retrieves the commitment [`Vec<TssPublicKey>`] associated with the `shard_id` from [`ShardCommitment`].
/// 2. Returns the first element of the commitment [`TssPublicKey`] if it exists; otherwise, returns `None`.
fn tss_public_key(shard_id: ShardId) -> Option<TssPublicKey> {
ShardCommitment::<T>::get(shard_id).map(|commitment| commitment[0])
ShardCommitment::<T>::get(shard_id).map(|commitment| commitment.0[0])
}
}
}
8 changes: 4 additions & 4 deletions pallets/shards/src/tests.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
use crate::mock::*;
use crate::{Event, ShardMembers, ShardNetwork, ShardState};

use polkadot_sdk::{frame_support, frame_system, pallet_balances, sp_core};
use polkadot_sdk::{frame_support, frame_system, pallet_balances, sp_core, sp_runtime};

use frame_support::assert_ok;
use frame_support::traits::{Currency, Get};
use frame_system::RawOrigin;

use schnorr_evm::k256::elliptic_curve::PrimeField;
use schnorr_evm::k256::{ProjectivePoint, Scalar};
use schnorr_evm::proof_of_knowledge::construct_proof_of_knowledge;
use schnorr_evm::VerifyingKey;
use sp_runtime::BoundedVec;

use time_primitives::{
AccountId, Commitment, NetworkId, PeerId, PublicKey, ShardId, ShardStatus, ShardsInterface,
Expand Down Expand Up @@ -88,7 +88,7 @@ fn create_shard(shard_id: ShardId, shard: &[Member], threshold: u16) {
assert_ok!(Shards::commit(
RawOrigin::Signed(member.account_id.clone()).into(),
shard_id as _,
Commitment::truncate_from(member.commitment(threshold)),
Commitment(BoundedVec::truncate_from(member.commitment(threshold))),
member.proof_of_knowledge(),
));
roll(1);
Expand Down Expand Up @@ -139,7 +139,7 @@ fn test_register_shard() {
assert_ok!(Shards::commit(
RawOrigin::Signed(member.account_id.clone()).into(),
shard_id as _,
Commitment::truncate_from(member.commitment(threshold)),
Commitment(BoundedVec::truncate_from(member.commitment(threshold))),
member.proof_of_knowledge(),
));
}
Expand Down
7 changes: 4 additions & 3 deletions pallets/tasks/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ use frame_support::traits::OnInitialize;
use frame_system::RawOrigin;
use pallet_networks::NetworkGatewayAddress;
use pallet_shards::{ShardCommitment, ShardState};
use polkadot_sdk::{frame_benchmarking, frame_support, frame_system, sp_std};
use polkadot_sdk::{frame_benchmarking, frame_support, frame_system, sp_runtime, sp_std};
use sp_runtime::BoundedVec;
use sp_std::vec;
use time_primitives::{
Commitment, GmpEvents, NetworkId, ShardStatus, ShardsInterface, Task, TaskResult,
Expand All @@ -32,7 +33,7 @@ fn create_simple_task<T: Config + pallet_shards::Config>() {
1,
);
ShardState::<T>::insert(shard_id, ShardStatus::Online);
ShardCommitment::<T>::insert(shard_id, Commitment::truncate_from(vec![PUBKEY]));
ShardCommitment::<T>::insert(shard_id, Commitment(BoundedVec::truncate_from(vec![PUBKEY])));
Pallet::<T>::shard_online(shard_id, ETHEREUM);
Pallet::<T>::create_task(ETHEREUM, Task::ReadGatewayEvents { blocks: 0..10 });
}
Expand All @@ -44,7 +45,7 @@ benchmarks! {
NetworkGatewayAddress::<T>::insert(0, [0; 32]);
create_simple_task::<T>();
Pallet::<T>::on_initialize(frame_system::Pallet::<T>::block_number());
let result = TaskResult::ReadGatewayEvents { events: GmpEvents::truncate_from(vec![]), signature: SIGNATURE };
let result = TaskResult::ReadGatewayEvents { events: GmpEvents(BoundedVec::truncate_from(vec![])), signature: SIGNATURE };
}: _(RawOrigin::Signed([0u8; 32].into()), 0, result) verify {}

schedule_tasks {
Expand Down
4 changes: 2 additions & 2 deletions pallets/tasks/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -317,15 +317,15 @@ pub mod pallet {
TaskResult::ReadGatewayEvents { events, signature },
) => {
// verify signature
let bytes = time_primitives::encode_gmp_events(task_id, &events);
let bytes = time_primitives::encode_gmp_events(task_id, &events.0);
Self::verify_signature(shard, &bytes, signature)?;
// start next batch
let start = blocks.end;
let size = T::Networks::next_batch_size(network, start) as u64;
let end = start + size;
Self::create_task(network, Task::ReadGatewayEvents { blocks: start..end });
// process events
for event in events {
for event in events.0 {
match event {
GmpEvent::ShardRegistered(pubkey) => {
ShardRegistered::<T>::insert(pubkey, ());
Expand Down
11 changes: 6 additions & 5 deletions pallets/tasks/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ use crate::{BatchIdCounter, ShardRegistered};
use frame_support::assert_ok;
use frame_system::RawOrigin;
use pallet_shards::{ShardCommitment, ShardState};
use polkadot_sdk::{frame_support, frame_system};
use polkadot_sdk::{frame_support, frame_system, sp_runtime};
use scale_codec::Encode;
use sp_runtime::BoundedVec;
use time_primitives::{
traits::IdentifyAccount, Commitment, ErrorMsg, GatewayMessage, GatewayOp, GmpEvent, GmpEvents,
GmpMessage, MockTssSigner, NetworkId, PublicKey, ShardId, ShardStatus, ShardsInterface, Task,
Expand All @@ -21,7 +22,7 @@ fn create_shard(network: NetworkId, n: u8, t: u16) -> ShardId {
}
let shard_id = Shards::create_shard(network, members, t).0;
let pub_key = MockTssSigner::new(shard_id).public_key();
ShardCommitment::<Test>::insert(shard_id, Commitment::truncate_from(vec![pub_key]));
ShardCommitment::<Test>::insert(shard_id, Commitment(BoundedVec::truncate_from(vec![pub_key])));
ShardState::<Test>::insert(shard_id, ShardStatus::Online);
Tasks::shard_online(shard_id, network);
shard_id
Expand All @@ -43,7 +44,7 @@ fn register_shard(shard: ShardId) {
fn submit_gateway_events(shard: ShardId, task_id: TaskId, events: &[GmpEvent]) {
let signature = MockTssSigner::new(shard).sign_gmp_events(task_id, events);
let result = TaskResult::ReadGatewayEvents {
events: GmpEvents::truncate_from(events.to_vec()),
events: GmpEvents(BoundedVec::truncate_from(events.to_vec())),
signature,
};
assert_ok!(Tasks::submit_task_result(
Expand All @@ -58,7 +59,7 @@ fn submit_submission_error(account: PublicKey, task: TaskId, error: &str) {
RawOrigin::Signed(account.into_account()).into(),
task,
TaskResult::SubmitGatewayMessage {
error: ErrorMsg::truncate_from(error.encode())
error: ErrorMsg(BoundedVec::truncate_from(error.encode()))
}
));
}
Expand Down Expand Up @@ -230,7 +231,7 @@ fn test_msg_execution_error_completes_submit_task() {
submit_submission_error(account, 1, "error message");
assert_eq!(
Tasks::get_task_result(1),
Some(Err(ErrorMsg::truncate_from("error message".encode())))
Some(Err(ErrorMsg(BoundedVec::truncate_from("error message".encode()))))
);
})
}
Expand Down
6 changes: 4 additions & 2 deletions primitives/src/dmail.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@ use scale_info::TypeInfo;
pub const DMAIL_TO_LEN: u32 = 64;
pub const DMAIL_PATH_LEN: u32 = 64;

pub type DmailTo = BoundedVec<u8, ConstU32<DMAIL_TO_LEN>>;
pub type DmailPath = BoundedVec<u8, ConstU32<DMAIL_PATH_LEN>>;
#[derive(Encode, Decode, TypeInfo, PartialEq, Eq, Clone, Debug)]
pub struct DmailTo(pub BoundedVec<u8, ConstU32<DMAIL_TO_LEN>>);
#[derive(Encode, Decode, TypeInfo, PartialEq, Eq, Clone, Debug)]
pub struct DmailPath(pub BoundedVec<u8, ConstU32<DMAIL_PATH_LEN>>);

#[derive(Encode, Decode, TypeInfo, PartialEq, Eq, Clone, Debug)]
pub struct DmailMessage {
Expand Down
6 changes: 4 additions & 2 deletions primitives/src/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@ pub const CHAIN_NAME_LEN: u32 = 50;
pub const CHAIN_NET_LEN: u32 = 50;

pub type NetworkId = u16;
pub type ChainName = BoundedVec<u8, ConstU32<CHAIN_NAME_LEN>>;
pub type ChainNetwork = BoundedVec<u8, ConstU32<CHAIN_NET_LEN>>;
#[derive(Encode, Decode, TypeInfo, PartialEq, Eq, Clone, Debug, Serialize, Deserialize)]
pub struct ChainName(pub BoundedVec<u8, ConstU32<CHAIN_NAME_LEN>>);
#[derive(Encode, Decode, TypeInfo, PartialEq, Eq, Clone, Debug, Serialize, Deserialize)]
pub struct ChainNetwork(pub BoundedVec<u8, ConstU32<CHAIN_NET_LEN>>);

#[derive(Clone, Debug, Eq, PartialEq, Encode, Decode, TypeInfo, Serialize, Deserialize)]
pub struct Network {
Expand Down
3 changes: 2 additions & 1 deletion primitives/src/shard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ pub type TssHash = [u8; 32];
pub type PeerId = [u8; 32];
pub type ShardId = u64;
pub type ProofOfKnowledge = [u8; 65];
pub type Commitment = BoundedVec<TssPublicKey, ConstU32<MAX_SHARD_SIZE>>;
#[derive(Encode, Decode, TypeInfo, PartialEq, Eq, Clone, Debug)]
pub struct Commitment(pub BoundedVec<TssPublicKey, ConstU32<MAX_SHARD_SIZE>>);

#[cfg(feature = "std")]
pub mod serde_tss_public_key {
Expand Down
8 changes: 6 additions & 2 deletions primitives/src/task.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,13 @@ pub fn encode_gmp_events(task_id: TaskId, events: &[GmpEvent]) -> Vec<u8> {
const MAX_GMP_EVENTS: u32 = 1_000;
const MAX_ERROR_LEN: u32 = 500;
/// Bounded vec alias for GMP events submitted in results
pub type GmpEvents = BoundedVec<GmpEvent, ConstU32<MAX_GMP_EVENTS>>;
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(Encode, Decode, TypeInfo, PartialEq, Eq, Clone, Debug)]
pub struct GmpEvents(pub BoundedVec<GmpEvent, ConstU32<MAX_GMP_EVENTS>>);
/// Bounded vec alias for SubmitGatewayMessage error
pub type ErrorMsg = BoundedVec<u8, ConstU32<MAX_ERROR_LEN>>;
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(Encode, Decode, TypeInfo, PartialEq, Eq, Clone, Debug)]
pub struct ErrorMsg(pub BoundedVec<u8, ConstU32<MAX_ERROR_LEN>>);

#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Decode, Encode, TypeInfo, PartialEq)]
Expand Down
8 changes: 3 additions & 5 deletions runtimes/testnet/src/tests.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
/// Integration tests
use crate::*;

//use polkadot_sdk::*;

use frame_support::assert_ok;
use frame_support::traits::{OnFinalize, OnInitialize, WhitelistedStorageKeys};
use frame_system::RawOrigin;
use pallet_shards::ShardMembers;
// use pallet_tasks::TaskSigner;
use sp_core::hexdisplay::HexDisplay;
use sp_core::Pair;
use sp_runtime::BoundedVec;
use std::collections::HashSet;
use time_primitives::{
AccountId, ElectionsInterface, Network, NetworkConfig, NetworkId, PublicKey, ShardStatus,
Expand All @@ -32,8 +30,8 @@ fn get_peer_id(random_num: [u8; 32]) -> [u8; 32] {
fn network() -> Network {
Network {
id: ETHEREUM,
chain_name: ChainName::truncate_from("ethereum".encode()),
chain_network: ChainNetwork::truncate_from("dev".encode()),
chain_name: ChainName(BoundedVec::truncate_from("ethereum".encode())),
chain_network: ChainNetwork(BoundedVec::truncate_from("dev".encode())),
gateway: [0u8; 32],
gateway_block: 0,
config: NetworkConfig {
Expand Down
Loading
Loading