From 0b3f59503d8ad3f5053a7fcf9b307d1ed24d59af Mon Sep 17 00:00:00 2001 From: Kaichao Sun Date: Thu, 11 Mar 2021 16:46:12 +0800 Subject: [PATCH 1/7] split test modules --- frame/node-authorization/src/lib.rs | 436 +------------------------- frame/node-authorization/src/mock.rs | 103 ++++++ frame/node-authorization/src/tests.rs | 370 ++++++++++++++++++++++ 3 files changed, 478 insertions(+), 431 deletions(-) create mode 100644 frame/node-authorization/src/mock.rs create mode 100644 frame/node-authorization/src/tests.rs diff --git a/frame/node-authorization/src/lib.rs b/frame/node-authorization/src/lib.rs index 090be28492630..9926b3a10d0a6 100644 --- a/frame/node-authorization/src/lib.rs +++ b/frame/node-authorization/src/lib.rs @@ -37,6 +37,11 @@ // Ensure we're `no_std` when compiling for Wasm. #![cfg_attr(not(feature = "std"), no_std)] +#[cfg(test)] +mod mock; +#[cfg(test)] +mod tests; + use sp_core::OpaquePeerId as PeerId; use sp_std::{ collections::btree_set::BTreeSet, @@ -433,434 +438,3 @@ impl Module { Vec::from_iter(nodes) } } - -#[cfg(test)] -mod tests { - use super::*; - use crate as pallet_node_authorization; - - use frame_support::{assert_ok, assert_noop, parameter_types, ord_parameter_types}; - use frame_system::EnsureSignedBy; - use sp_core::H256; - use sp_runtime::{traits::{BlakeTwo256, IdentityLookup, BadOrigin}, testing::Header}; - - type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; - type Block = frame_system::mocking::MockBlock; - - frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { - System: frame_system::{Module, Call, Config, Storage, Event}, - NodeAuthorization: pallet_node_authorization::{ - Module, Call, Storage, Config, Event, - }, - } - ); - - parameter_types! { - pub const BlockHashCount: u64 = 250; - } - impl frame_system::Config for Test { - type BaseCallFilter = (); - type DbWeight = (); - type BlockWeights = (); - type BlockLength = (); - type Origin = Origin; - type Index = u64; - type BlockNumber = u64; - type Hash = H256; - type Call = Call; - type Hashing = BlakeTwo256; - type AccountId = u64; - type Lookup = IdentityLookup; - type Header = Header; - type Event = Event; - type BlockHashCount = BlockHashCount; - type Version = (); - type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); - type SystemWeightInfo = (); - type SS58Prefix = (); - } - - ord_parameter_types! { - pub const One: u64 = 1; - pub const Two: u64 = 2; - pub const Three: u64 = 3; - pub const Four: u64 = 4; - } - parameter_types! { - pub const MaxWellKnownNodes: u32 = 4; - pub const MaxPeerIdLength: u32 = 2; - } - impl Config for Test { - type Event = Event; - type MaxWellKnownNodes = MaxWellKnownNodes; - type MaxPeerIdLength = MaxPeerIdLength; - type AddOrigin = EnsureSignedBy; - type RemoveOrigin = EnsureSignedBy; - type SwapOrigin = EnsureSignedBy; - type ResetOrigin = EnsureSignedBy; - type WeightInfo = (); - } - - fn test_node(id: u8) -> PeerId { - PeerId(vec![id]) - } - - fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); - pallet_node_authorization::GenesisConfig:: { - nodes: vec![(test_node(10), 10), (test_node(20), 20), (test_node(30), 30)], - }.assimilate_storage(&mut t).unwrap(); - t.into() - } - - #[test] - fn add_well_known_node_works() { - new_test_ext().execute_with(|| { - assert_noop!( - NodeAuthorization::add_well_known_node(Origin::signed(2), test_node(15), 15), - BadOrigin - ); - assert_noop!( - NodeAuthorization::add_well_known_node(Origin::signed(1), PeerId(vec![1, 2, 3]), 15), - Error::::PeerIdTooLong - ); - assert_noop!( - NodeAuthorization::add_well_known_node(Origin::signed(1), test_node(20), 20), - Error::::AlreadyJoined - ); - - assert_ok!( - NodeAuthorization::add_well_known_node(Origin::signed(1), test_node(15), 15) - ); - assert_eq!( - WellKnownNodes::get(), - BTreeSet::from_iter(vec![test_node(10), test_node(15), test_node(20), test_node(30)]) - ); - assert_eq!(Owners::::get(test_node(10)), 10); - assert_eq!(Owners::::get(test_node(20)), 20); - assert_eq!(Owners::::get(test_node(30)), 30); - assert_eq!(Owners::::get(test_node(15)), 15); - - assert_noop!( - NodeAuthorization::add_well_known_node(Origin::signed(1), test_node(25), 25), - Error::::TooManyNodes - ); - }); - } - - #[test] - fn remove_well_known_node_works() { - new_test_ext().execute_with(|| { - assert_noop!( - NodeAuthorization::remove_well_known_node(Origin::signed(3), test_node(20)), - BadOrigin - ); - assert_noop!( - NodeAuthorization::remove_well_known_node(Origin::signed(2), PeerId(vec![1, 2, 3])), - Error::::PeerIdTooLong - ); - assert_noop!( - NodeAuthorization::remove_well_known_node(Origin::signed(2), test_node(40)), - Error::::NotExist - ); - - AdditionalConnections::insert( - test_node(20), - BTreeSet::from_iter(vec![test_node(40)]) - ); - assert!(AdditionalConnections::contains_key(test_node(20))); - - assert_ok!( - NodeAuthorization::remove_well_known_node(Origin::signed(2), test_node(20)) - ); - assert_eq!( - WellKnownNodes::get(), - BTreeSet::from_iter(vec![test_node(10), test_node(30)]) - ); - assert!(!Owners::::contains_key(test_node(20))); - assert!(!AdditionalConnections::contains_key(test_node(20))); - }); - } - - #[test] - fn swap_well_known_node_works() { - new_test_ext().execute_with(|| { - assert_noop!( - NodeAuthorization::swap_well_known_node( - Origin::signed(4), test_node(20), test_node(5) - ), - BadOrigin - ); - assert_noop!( - NodeAuthorization::swap_well_known_node( - Origin::signed(3), PeerId(vec![1, 2, 3]), test_node(20) - ), - Error::::PeerIdTooLong - ); - assert_noop!( - NodeAuthorization::swap_well_known_node( - Origin::signed(3), test_node(20), PeerId(vec![1, 2, 3]) - ), - Error::::PeerIdTooLong - ); - - assert_ok!( - NodeAuthorization::swap_well_known_node( - Origin::signed(3), test_node(20), test_node(20) - ) - ); - assert_eq!( - WellKnownNodes::get(), - BTreeSet::from_iter(vec![test_node(10), test_node(20), test_node(30)]) - ); - - assert_noop!( - NodeAuthorization::swap_well_known_node( - Origin::signed(3), test_node(15), test_node(5) - ), - Error::::NotExist - ); - assert_noop!( - NodeAuthorization::swap_well_known_node( - Origin::signed(3), test_node(20), test_node(30) - ), - Error::::AlreadyJoined - ); - - AdditionalConnections::insert( - test_node(20), - BTreeSet::from_iter(vec![test_node(15)]) - ); - assert_ok!( - NodeAuthorization::swap_well_known_node( - Origin::signed(3), test_node(20), test_node(5) - ) - ); - assert_eq!( - WellKnownNodes::get(), - BTreeSet::from_iter(vec![test_node(5), test_node(10), test_node(30)]) - ); - assert!(!Owners::::contains_key(test_node(20))); - assert_eq!(Owners::::get(test_node(5)), 20); - assert!(!AdditionalConnections::contains_key(test_node(20))); - assert_eq!( - AdditionalConnections::get(test_node(5)), - BTreeSet::from_iter(vec![test_node(15)]) - ); - }); - } - - #[test] - fn reset_well_known_nodes_works() { - new_test_ext().execute_with(|| { - assert_noop!( - NodeAuthorization::reset_well_known_nodes( - Origin::signed(3), - vec![(test_node(15), 15), (test_node(5), 5), (test_node(20), 20)] - ), - BadOrigin - ); - assert_noop!( - NodeAuthorization::reset_well_known_nodes( - Origin::signed(4), - vec![ - (test_node(15), 15), - (test_node(5), 5), - (test_node(20), 20), - (test_node(25), 25), - ] - ), - Error::::TooManyNodes - ); - - assert_ok!( - NodeAuthorization::reset_well_known_nodes( - Origin::signed(4), - vec![(test_node(15), 15), (test_node(5), 5), (test_node(20), 20)] - ) - ); - assert_eq!( - WellKnownNodes::get(), - BTreeSet::from_iter(vec![test_node(5), test_node(15), test_node(20)]) - ); - assert_eq!(Owners::::get(test_node(5)), 5); - assert_eq!(Owners::::get(test_node(15)), 15); - assert_eq!(Owners::::get(test_node(20)), 20); - }); - } - - #[test] - fn claim_node_works() { - new_test_ext().execute_with(|| { - assert_noop!( - NodeAuthorization::claim_node(Origin::signed(1), PeerId(vec![1, 2, 3])), - Error::::PeerIdTooLong - ); - assert_noop!( - NodeAuthorization::claim_node(Origin::signed(1), test_node(20)), - Error::::AlreadyClaimed - ); - - assert_ok!(NodeAuthorization::claim_node(Origin::signed(15), test_node(15))); - assert_eq!(Owners::::get(test_node(15)), 15); - }); - } - - #[test] - fn remove_claim_works() { - new_test_ext().execute_with(|| { - assert_noop!( - NodeAuthorization::remove_claim(Origin::signed(15), PeerId(vec![1, 2, 3])), - Error::::PeerIdTooLong - ); - assert_noop!( - NodeAuthorization::remove_claim(Origin::signed(15), test_node(15)), - Error::::NotClaimed - ); - - assert_noop!( - NodeAuthorization::remove_claim(Origin::signed(15), test_node(20)), - Error::::NotOwner - ); - - assert_noop!( - NodeAuthorization::remove_claim(Origin::signed(20), test_node(20)), - Error::::PermissionDenied - ); - - Owners::::insert(test_node(15), 15); - AdditionalConnections::insert( - test_node(15), - BTreeSet::from_iter(vec![test_node(20)]) - ); - assert_ok!(NodeAuthorization::remove_claim(Origin::signed(15), test_node(15))); - assert!(!Owners::::contains_key(test_node(15))); - assert!(!AdditionalConnections::contains_key(test_node(15))); - }); - } - - #[test] - fn transfer_node_works() { - new_test_ext().execute_with(|| { - assert_noop!( - NodeAuthorization::transfer_node(Origin::signed(15), PeerId(vec![1, 2, 3]), 10), - Error::::PeerIdTooLong - ); - assert_noop!( - NodeAuthorization::transfer_node(Origin::signed(15), test_node(15), 10), - Error::::NotClaimed - ); - - assert_noop!( - NodeAuthorization::transfer_node(Origin::signed(15), test_node(20), 10), - Error::::NotOwner - ); - - assert_ok!(NodeAuthorization::transfer_node(Origin::signed(20), test_node(20), 15)); - assert_eq!(Owners::::get(test_node(20)), 15); - }); - } - - #[test] - fn add_connections_works() { - new_test_ext().execute_with(|| { - assert_noop!( - NodeAuthorization::add_connections( - Origin::signed(15), PeerId(vec![1, 2, 3]), vec![test_node(5)] - ), - Error::::PeerIdTooLong - ); - assert_noop!( - NodeAuthorization::add_connections( - Origin::signed(15), test_node(15), vec![test_node(5)] - ), - Error::::NotClaimed - ); - - assert_noop!( - NodeAuthorization::add_connections( - Origin::signed(15), test_node(20), vec![test_node(5)] - ), - Error::::NotOwner - ); - - assert_ok!( - NodeAuthorization::add_connections( - Origin::signed(20), - test_node(20), - vec![test_node(15), test_node(5), test_node(25), test_node(20)] - ) - ); - assert_eq!( - AdditionalConnections::get(test_node(20)), - BTreeSet::from_iter(vec![test_node(5), test_node(15), test_node(25)]) - ); - }); - } - - #[test] - fn remove_connections_works() { - new_test_ext().execute_with(|| { - assert_noop!( - NodeAuthorization::remove_connections( - Origin::signed(15), PeerId(vec![1, 2, 3]), vec![test_node(5)] - ), - Error::::PeerIdTooLong - ); - assert_noop!( - NodeAuthorization::remove_connections( - Origin::signed(15), test_node(15), vec![test_node(5)] - ), - Error::::NotClaimed - ); - - assert_noop!( - NodeAuthorization::remove_connections( - Origin::signed(15), test_node(20), vec![test_node(5)] - ), - Error::::NotOwner - ); - - AdditionalConnections::insert( - test_node(20), - BTreeSet::from_iter(vec![test_node(5), test_node(15), test_node(25)]) - ); - assert_ok!( - NodeAuthorization::remove_connections( - Origin::signed(20), - test_node(20), - vec![test_node(15), test_node(5)] - ) - ); - assert_eq!( - AdditionalConnections::get(test_node(20)), - BTreeSet::from_iter(vec![test_node(25)]) - ); - }); - } - - #[test] - fn get_authorized_nodes_works() { - new_test_ext().execute_with(|| { - AdditionalConnections::insert( - test_node(20), - BTreeSet::from_iter(vec![test_node(5), test_node(15), test_node(25)]) - ); - - let mut authorized_nodes = Module::::get_authorized_nodes(&test_node(20)); - authorized_nodes.sort(); - assert_eq!( - authorized_nodes, - vec![test_node(5), test_node(10), test_node(15), test_node(25), test_node(30)] - ); - }); - } -} diff --git a/frame/node-authorization/src/mock.rs b/frame/node-authorization/src/mock.rs new file mode 100644 index 0000000000000..79a7350d82da8 --- /dev/null +++ b/frame/node-authorization/src/mock.rs @@ -0,0 +1,103 @@ +// This file is part of Substrate. + +// Copyright (C) 2019-2021 Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Test environment for node-authorization pallet. + +use super::*; +use crate as pallet_node_authorization; + +use frame_support::{parameter_types, ord_parameter_types}; +use frame_system::EnsureSignedBy; +use sp_core::H256; +use sp_runtime::{traits::{BlakeTwo256, IdentityLookup}, testing::Header}; + +type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; +type Block = frame_system::mocking::MockBlock; + +frame_support::construct_runtime!( + pub enum Test where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + System: frame_system::{Module, Call, Config, Storage, Event}, + NodeAuthorization: pallet_node_authorization::{ + Module, Call, Storage, Config, Event, + }, + } +); + +parameter_types! { + pub const BlockHashCount: u64 = 250; +} +impl frame_system::Config for Test { + type BaseCallFilter = (); + type DbWeight = (); + type BlockWeights = (); + type BlockLength = (); + type Origin = Origin; + type Index = u64; + type BlockNumber = u64; + type Hash = H256; + type Call = Call; + type Hashing = BlakeTwo256; + type AccountId = u64; + type Lookup = IdentityLookup; + type Header = Header; + type Event = Event; + type BlockHashCount = BlockHashCount; + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = (); + type OnNewAccount = (); + type OnKilledAccount = (); + type SystemWeightInfo = (); + type SS58Prefix = (); +} + +ord_parameter_types! { + pub const One: u64 = 1; + pub const Two: u64 = 2; + pub const Three: u64 = 3; + pub const Four: u64 = 4; +} +parameter_types! { + pub const MaxWellKnownNodes: u32 = 4; + pub const MaxPeerIdLength: u32 = 2; +} +impl Config for Test { + type Event = Event; + type MaxWellKnownNodes = MaxWellKnownNodes; + type MaxPeerIdLength = MaxPeerIdLength; + type AddOrigin = EnsureSignedBy; + type RemoveOrigin = EnsureSignedBy; + type SwapOrigin = EnsureSignedBy; + type ResetOrigin = EnsureSignedBy; + type WeightInfo = (); +} + +fn test_node(id: u8) -> PeerId { + PeerId(vec![id]) +} + +pub fn new_test_ext() -> sp_io::TestExternalities { + let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + pallet_node_authorization::GenesisConfig:: { + nodes: vec![(test_node(10), 10), (test_node(20), 20), (test_node(30), 30)], + }.assimilate_storage(&mut t).unwrap(); + t.into() +} \ No newline at end of file diff --git a/frame/node-authorization/src/tests.rs b/frame/node-authorization/src/tests.rs new file mode 100644 index 0000000000000..f151d8b3c3c25 --- /dev/null +++ b/frame/node-authorization/src/tests.rs @@ -0,0 +1,370 @@ +// This file is part of Substrate. + +// Copyright (C) 2019-2021 Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Tests for node-authorization pallet. + +use super::*; +use crate::mock::*; +use frame_support::{assert_ok, assert_noop}; +use sp_runtime::traits::BadOrigin; + +fn test_node(id: u8) -> PeerId { + PeerId(vec![id]) +} + +#[test] +fn add_well_known_node_works() { + new_test_ext().execute_with(|| { + assert_noop!( + NodeAuthorization::add_well_known_node(Origin::signed(2), test_node(15), 15), + BadOrigin + ); + assert_noop!( + NodeAuthorization::add_well_known_node(Origin::signed(1), PeerId(vec![1, 2, 3]), 15), + Error::::PeerIdTooLong + ); + assert_noop!( + NodeAuthorization::add_well_known_node(Origin::signed(1), test_node(20), 20), + Error::::AlreadyJoined + ); + + assert_ok!( + NodeAuthorization::add_well_known_node(Origin::signed(1), test_node(15), 15) + ); + assert_eq!( + WellKnownNodes::get(), + BTreeSet::from_iter(vec![test_node(10), test_node(15), test_node(20), test_node(30)]) + ); + assert_eq!(Owners::::get(test_node(10)), 10); + assert_eq!(Owners::::get(test_node(20)), 20); + assert_eq!(Owners::::get(test_node(30)), 30); + assert_eq!(Owners::::get(test_node(15)), 15); + + assert_noop!( + NodeAuthorization::add_well_known_node(Origin::signed(1), test_node(25), 25), + Error::::TooManyNodes + ); + }); +} + +#[test] +fn remove_well_known_node_works() { + new_test_ext().execute_with(|| { + assert_noop!( + NodeAuthorization::remove_well_known_node(Origin::signed(3), test_node(20)), + BadOrigin + ); + assert_noop!( + NodeAuthorization::remove_well_known_node(Origin::signed(2), PeerId(vec![1, 2, 3])), + Error::::PeerIdTooLong + ); + assert_noop!( + NodeAuthorization::remove_well_known_node(Origin::signed(2), test_node(40)), + Error::::NotExist + ); + + AdditionalConnections::insert( + test_node(20), + BTreeSet::from_iter(vec![test_node(40)]) + ); + assert!(AdditionalConnections::contains_key(test_node(20))); + + assert_ok!( + NodeAuthorization::remove_well_known_node(Origin::signed(2), test_node(20)) + ); + assert_eq!( + WellKnownNodes::get(), + BTreeSet::from_iter(vec![test_node(10), test_node(30)]) + ); + assert!(!Owners::::contains_key(test_node(20))); + assert!(!AdditionalConnections::contains_key(test_node(20))); + }); +} + +#[test] +fn swap_well_known_node_works() { + new_test_ext().execute_with(|| { + assert_noop!( + NodeAuthorization::swap_well_known_node( + Origin::signed(4), test_node(20), test_node(5) + ), + BadOrigin + ); + assert_noop!( + NodeAuthorization::swap_well_known_node( + Origin::signed(3), PeerId(vec![1, 2, 3]), test_node(20) + ), + Error::::PeerIdTooLong + ); + assert_noop!( + NodeAuthorization::swap_well_known_node( + Origin::signed(3), test_node(20), PeerId(vec![1, 2, 3]) + ), + Error::::PeerIdTooLong + ); + + assert_ok!( + NodeAuthorization::swap_well_known_node( + Origin::signed(3), test_node(20), test_node(20) + ) + ); + assert_eq!( + WellKnownNodes::get(), + BTreeSet::from_iter(vec![test_node(10), test_node(20), test_node(30)]) + ); + + assert_noop!( + NodeAuthorization::swap_well_known_node( + Origin::signed(3), test_node(15), test_node(5) + ), + Error::::NotExist + ); + assert_noop!( + NodeAuthorization::swap_well_known_node( + Origin::signed(3), test_node(20), test_node(30) + ), + Error::::AlreadyJoined + ); + + AdditionalConnections::insert( + test_node(20), + BTreeSet::from_iter(vec![test_node(15)]) + ); + assert_ok!( + NodeAuthorization::swap_well_known_node( + Origin::signed(3), test_node(20), test_node(5) + ) + ); + assert_eq!( + WellKnownNodes::get(), + BTreeSet::from_iter(vec![test_node(5), test_node(10), test_node(30)]) + ); + assert!(!Owners::::contains_key(test_node(20))); + assert_eq!(Owners::::get(test_node(5)), 20); + assert!(!AdditionalConnections::contains_key(test_node(20))); + assert_eq!( + AdditionalConnections::get(test_node(5)), + BTreeSet::from_iter(vec![test_node(15)]) + ); + }); +} + +#[test] +fn reset_well_known_nodes_works() { + new_test_ext().execute_with(|| { + assert_noop!( + NodeAuthorization::reset_well_known_nodes( + Origin::signed(3), + vec![(test_node(15), 15), (test_node(5), 5), (test_node(20), 20)] + ), + BadOrigin + ); + assert_noop!( + NodeAuthorization::reset_well_known_nodes( + Origin::signed(4), + vec![ + (test_node(15), 15), + (test_node(5), 5), + (test_node(20), 20), + (test_node(25), 25), + ] + ), + Error::::TooManyNodes + ); + + assert_ok!( + NodeAuthorization::reset_well_known_nodes( + Origin::signed(4), + vec![(test_node(15), 15), (test_node(5), 5), (test_node(20), 20)] + ) + ); + assert_eq!( + WellKnownNodes::get(), + BTreeSet::from_iter(vec![test_node(5), test_node(15), test_node(20)]) + ); + assert_eq!(Owners::::get(test_node(5)), 5); + assert_eq!(Owners::::get(test_node(15)), 15); + assert_eq!(Owners::::get(test_node(20)), 20); + }); +} + +#[test] +fn claim_node_works() { + new_test_ext().execute_with(|| { + assert_noop!( + NodeAuthorization::claim_node(Origin::signed(1), PeerId(vec![1, 2, 3])), + Error::::PeerIdTooLong + ); + assert_noop!( + NodeAuthorization::claim_node(Origin::signed(1), test_node(20)), + Error::::AlreadyClaimed + ); + + assert_ok!(NodeAuthorization::claim_node(Origin::signed(15), test_node(15))); + assert_eq!(Owners::::get(test_node(15)), 15); + }); +} + +#[test] +fn remove_claim_works() { + new_test_ext().execute_with(|| { + assert_noop!( + NodeAuthorization::remove_claim(Origin::signed(15), PeerId(vec![1, 2, 3])), + Error::::PeerIdTooLong + ); + assert_noop!( + NodeAuthorization::remove_claim(Origin::signed(15), test_node(15)), + Error::::NotClaimed + ); + + assert_noop!( + NodeAuthorization::remove_claim(Origin::signed(15), test_node(20)), + Error::::NotOwner + ); + + assert_noop!( + NodeAuthorization::remove_claim(Origin::signed(20), test_node(20)), + Error::::PermissionDenied + ); + + Owners::::insert(test_node(15), 15); + AdditionalConnections::insert( + test_node(15), + BTreeSet::from_iter(vec![test_node(20)]) + ); + assert_ok!(NodeAuthorization::remove_claim(Origin::signed(15), test_node(15))); + assert!(!Owners::::contains_key(test_node(15))); + assert!(!AdditionalConnections::contains_key(test_node(15))); + }); +} + +#[test] +fn transfer_node_works() { + new_test_ext().execute_with(|| { + assert_noop!( + NodeAuthorization::transfer_node(Origin::signed(15), PeerId(vec![1, 2, 3]), 10), + Error::::PeerIdTooLong + ); + assert_noop!( + NodeAuthorization::transfer_node(Origin::signed(15), test_node(15), 10), + Error::::NotClaimed + ); + + assert_noop!( + NodeAuthorization::transfer_node(Origin::signed(15), test_node(20), 10), + Error::::NotOwner + ); + + assert_ok!(NodeAuthorization::transfer_node(Origin::signed(20), test_node(20), 15)); + assert_eq!(Owners::::get(test_node(20)), 15); + }); +} + +#[test] +fn add_connections_works() { + new_test_ext().execute_with(|| { + assert_noop!( + NodeAuthorization::add_connections( + Origin::signed(15), PeerId(vec![1, 2, 3]), vec![test_node(5)] + ), + Error::::PeerIdTooLong + ); + assert_noop!( + NodeAuthorization::add_connections( + Origin::signed(15), test_node(15), vec![test_node(5)] + ), + Error::::NotClaimed + ); + + assert_noop!( + NodeAuthorization::add_connections( + Origin::signed(15), test_node(20), vec![test_node(5)] + ), + Error::::NotOwner + ); + + assert_ok!( + NodeAuthorization::add_connections( + Origin::signed(20), + test_node(20), + vec![test_node(15), test_node(5), test_node(25), test_node(20)] + ) + ); + assert_eq!( + AdditionalConnections::get(test_node(20)), + BTreeSet::from_iter(vec![test_node(5), test_node(15), test_node(25)]) + ); + }); +} + +#[test] +fn remove_connections_works() { + new_test_ext().execute_with(|| { + assert_noop!( + NodeAuthorization::remove_connections( + Origin::signed(15), PeerId(vec![1, 2, 3]), vec![test_node(5)] + ), + Error::::PeerIdTooLong + ); + assert_noop!( + NodeAuthorization::remove_connections( + Origin::signed(15), test_node(15), vec![test_node(5)] + ), + Error::::NotClaimed + ); + + assert_noop!( + NodeAuthorization::remove_connections( + Origin::signed(15), test_node(20), vec![test_node(5)] + ), + Error::::NotOwner + ); + + AdditionalConnections::insert( + test_node(20), + BTreeSet::from_iter(vec![test_node(5), test_node(15), test_node(25)]) + ); + assert_ok!( + NodeAuthorization::remove_connections( + Origin::signed(20), + test_node(20), + vec![test_node(15), test_node(5)] + ) + ); + assert_eq!( + AdditionalConnections::get(test_node(20)), + BTreeSet::from_iter(vec![test_node(25)]) + ); + }); +} + +#[test] +fn get_authorized_nodes_works() { + new_test_ext().execute_with(|| { + AdditionalConnections::insert( + test_node(20), + BTreeSet::from_iter(vec![test_node(5), test_node(15), test_node(25)]) + ); + + let mut authorized_nodes = Module::::get_authorized_nodes(&test_node(20)); + authorized_nodes.sort(); + assert_eq!( + authorized_nodes, + vec![test_node(5), test_node(10), test_node(15), test_node(25), test_node(30)] + ); + }); +} \ No newline at end of file From c032acb52a5e09c174ff8a6f2a97da38395084c4 Mon Sep 17 00:00:00 2001 From: Kaichao Sun Date: Fri, 12 Mar 2021 10:47:09 +0800 Subject: [PATCH 2/7] use FRAME v2. --- frame/node-authorization/src/lib.rs | 364 +++++++++++++----------- frame/node-authorization/src/mock.rs | 7 +- frame/node-authorization/src/tests.rs | 38 ++- frame/node-authorization/src/weights.rs | 48 ++++ 4 files changed, 268 insertions(+), 189 deletions(-) create mode 100644 frame/node-authorization/src/weights.rs diff --git a/frame/node-authorization/src/lib.rs b/frame/node-authorization/src/lib.rs index 9926b3a10d0a6..dc8f226b61ac0 100644 --- a/frame/node-authorization/src/lib.rs +++ b/frame/node-authorization/src/lib.rs @@ -42,117 +42,130 @@ mod mock; #[cfg(test)] mod tests; +pub mod weights; + use sp_core::OpaquePeerId as PeerId; use sp_std::{ collections::btree_set::BTreeSet, iter::FromIterator, - prelude::*, -}; -use codec::Decode; -use frame_support::{ - decl_module, decl_storage, decl_event, decl_error, - ensure, weights::{DispatchClass, Weight}, traits::{Get, EnsureOrigin}, }; -use frame_system::ensure_signed; - -pub trait WeightInfo { - fn add_well_known_node() -> Weight; - fn remove_well_known_node() -> Weight; - fn swap_well_known_node() -> Weight; - fn reset_well_known_nodes() -> Weight; - fn claim_node() -> Weight; - fn remove_claim() -> Weight; - fn transfer_node() -> Weight; - fn add_connections() -> Weight; - fn remove_connections() -> Weight; -} - -impl WeightInfo for () { - fn add_well_known_node() -> Weight { 50_000_000 } - fn remove_well_known_node() -> Weight { 50_000_000 } - fn swap_well_known_node() -> Weight { 50_000_000 } - fn reset_well_known_nodes() -> Weight { 50_000_000 } - fn claim_node() -> Weight { 50_000_000 } - fn remove_claim() -> Weight { 50_000_000 } - fn transfer_node() -> Weight { 50_000_000 } - fn add_connections() -> Weight { 50_000_000 } - fn remove_connections() -> Weight { 50_000_000 } -} +pub use pallet::*; +pub use weights::WeightInfo; + +#[frame_support::pallet] +pub mod pallet { + use super::*; + use frame_support::{ + dispatch::DispatchResult, + pallet_prelude::*, + }; + use frame_system::pallet_prelude::*; + + #[pallet::pallet] + #[pallet::generate_store(pub(super) trait Store)] + pub struct Pallet(_); + + /// The module configuration trait + #[pallet::config] + pub trait Config: frame_system::Config { + /// The overarching event type. + type Event: From> + IsType<::Event>; + + /// The maximum number of well known nodes that are allowed to set + type MaxWellKnownNodes: Get; -pub trait Config: frame_system::Config { - /// The event type of this module. - type Event: From> + Into<::Event>; - - /// The maximum number of well known nodes that are allowed to set - type MaxWellKnownNodes: Get; + /// The maximum length in bytes of PeerId + type MaxPeerIdLength: Get; - /// The maximum length in bytes of PeerId - type MaxPeerIdLength: Get; + /// The origin which can add a well known node. + type AddOrigin: EnsureOrigin; - /// The origin which can add a well known node. - type AddOrigin: EnsureOrigin; + /// The origin which can remove a well known node. + type RemoveOrigin: EnsureOrigin; - /// The origin which can remove a well known node. - type RemoveOrigin: EnsureOrigin; + /// The origin which can swap the well known nodes. + type SwapOrigin: EnsureOrigin; - /// The origin which can swap the well known nodes. - type SwapOrigin: EnsureOrigin; + /// The origin which can reset the well known nodes. + type ResetOrigin: EnsureOrigin; - /// The origin which can reset the well known nodes. - type ResetOrigin: EnsureOrigin; + /// Weight information for extrinsics in this pallet. + type WeightInfo: WeightInfo; + } - /// Weight information for extrinsics in this pallet. - type WeightInfo: WeightInfo; -} + /// The set of well known nodes. This is stored sorted (just by value). + #[pallet::storage] + #[pallet::getter(fn well_known_nodes)] + pub type WellKnownNodes = StorageValue<_, BTreeSet, ValueQuery>; + + /// A map that maintains the ownership of each node. + #[pallet::storage] + #[pallet::getter(fn owners)] + pub type Owners = StorageMap< + _, + Blake2_128Concat, + PeerId, + T::AccountId, + ValueQuery, + >; + + /// The additional adapative connections of each node. + #[pallet::storage] + #[pallet::getter(fn additional_connection)] + pub type AdditionalConnections = StorageMap< + _, + Blake2_128Concat, + PeerId, + BTreeSet, + ValueQuery, + >; + + #[pallet::genesis_config] + pub struct GenesisConfig { + pub nodes: Vec<(PeerId, T::AccountId)>, + } -decl_storage! { - trait Store for Module as NodeAuthorization { - /// The set of well known nodes. This is stored sorted (just by value). - pub WellKnownNodes get(fn well_known_nodes): BTreeSet; - /// A map that maintains the ownership of each node. - pub Owners get(fn owners): - map hasher(blake2_128_concat) PeerId => T::AccountId; - /// The additional adapative connections of each node. - pub AdditionalConnections get(fn additional_connection): - map hasher(blake2_128_concat) PeerId => BTreeSet; + #[cfg(feature = "std")] + impl Default for GenesisConfig { + fn default() -> Self { + Self { nodes: Vec::new() } + } } - add_extra_genesis { - config(nodes): Vec<(PeerId, T::AccountId)>; - build(|config: &GenesisConfig| { - >::initialize_nodes(&config.nodes) - }) + + #[pallet::genesis_build] + impl GenesisBuild for GenesisConfig { + fn build(&self) { + Pallet::::initialize_nodes(&self.nodes); + } } -} -decl_event! { - pub enum Event where - ::AccountId, - { + #[pallet::event] + #[pallet::generate_deposit(pub(super) fn deposit_event)] + #[pallet::metadata(T::AccountId = "AccountId")] + pub enum Event { /// The given well known node was added. - NodeAdded(PeerId, AccountId), + NodeAdded(PeerId, T::AccountId), /// The given well known node was removed. NodeRemoved(PeerId), /// The given well known node was swapped; first item was removed, /// the latter was added. NodeSwapped(PeerId, PeerId), /// The given well known nodes were reset. - NodesReset(Vec<(PeerId, AccountId)>), + NodesReset(Vec<(PeerId, T::AccountId)>), /// The given node was claimed by a user. - NodeClaimed(PeerId, AccountId), + NodeClaimed(PeerId, T::AccountId), /// The given claim was removed by its owner. - ClaimRemoved(PeerId, AccountId), + ClaimRemoved(PeerId, T::AccountId), /// The node was transferred to another account. - NodeTransferred(PeerId, AccountId), + NodeTransferred(PeerId, T::AccountId), /// The allowed connections were added to a node. ConnectionsAdded(PeerId, Vec), /// The allowed connections were removed from a node. ConnectionsRemoved(PeerId, Vec), } -} -decl_error! { - /// Error for the node authorization module. - pub enum Error for Module { + #[pallet::error] + pub enum Error { /// The PeerId is too long. PeerIdTooLong, /// Too many well known nodes. @@ -170,41 +183,65 @@ decl_error! { /// No permisson to perform specific operation. PermissionDenied, } -} - -decl_module! { - pub struct Module for enum Call where origin: T::Origin { - /// The maximum number of authorized well known nodes - const MaxWellKnownNodes: u32 = T::MaxWellKnownNodes::get(); - - /// The maximum length in bytes of PeerId - const MaxPeerIdLength: u32 = T::MaxPeerIdLength::get(); - type Error = Error; - - fn deposit_event() = default; + #[pallet::hooks] + impl Hooks> for Pallet { + /// Set reserved node every block. It may not be enabled depends on the offchain + /// worker settings when starting the node. + fn offchain_worker(now: T::BlockNumber) { + let network_state = sp_io::offchain::network_state(); + match network_state { + Err(_) => log::error!( + target: "runtime::node-authorization", + "Error: failed to get network state of node at {:?}", + now, + ), + Ok(state) => { + let encoded_peer = state.peer_id.0; + match Decode::decode(&mut &encoded_peer[..]) { + Err(_) => log::error!( + target: "runtime::node-authorization", + "Error: failed to decode PeerId at {:?}", + now, + ), + Ok(node) => sp_io::offchain::set_authorized_nodes( + Self::get_authorized_nodes(&PeerId(node)), + true + ) + } + } + } + } + } + #[pallet::call] + impl Pallet { /// Add a node to the set of well known nodes. If the node is already claimed, the owner /// will be updated and keep the existing additional connection unchanged. /// /// May only be called from `T::AddOrigin`. /// /// - `node`: identifier of the node. - #[weight = (T::WeightInfo::add_well_known_node(), DispatchClass::Operational)] - pub fn add_well_known_node(origin, node: PeerId, owner: T::AccountId) { + #[pallet::weight((T::WeightInfo::add_well_known_node(), DispatchClass::Operational))] + pub fn add_well_known_node( + origin: OriginFor, + node: PeerId, + owner: T::AccountId + ) -> DispatchResult { T::AddOrigin::ensure_origin(origin)?; ensure!(node.0.len() < T::MaxPeerIdLength::get() as usize, Error::::PeerIdTooLong); - let mut nodes = WellKnownNodes::get(); + let mut nodes = WellKnownNodes::::get(); ensure!(nodes.len() < T::MaxWellKnownNodes::get() as usize, Error::::TooManyNodes); ensure!(!nodes.contains(&node), Error::::AlreadyJoined); nodes.insert(node.clone()); - WellKnownNodes::put(&nodes); + WellKnownNodes::::put(&nodes); >::insert(&node, &owner); - Self::deposit_event(RawEvent::NodeAdded(node, owner)); + Self::deposit_event(Event::NodeAdded(node, owner)); + Ok(()) } /// Remove a node from the set of well known nodes. The ownership and additional @@ -213,21 +250,22 @@ decl_module! { /// May only be called from `T::RemoveOrigin`. /// /// - `node`: identifier of the node. - #[weight = (T::WeightInfo::remove_well_known_node(), DispatchClass::Operational)] - pub fn remove_well_known_node(origin, node: PeerId) { + #[pallet::weight((T::WeightInfo::remove_well_known_node(), DispatchClass::Operational))] + pub fn remove_well_known_node(origin: OriginFor, node: PeerId) -> DispatchResult { T::RemoveOrigin::ensure_origin(origin)?; ensure!(node.0.len() < T::MaxPeerIdLength::get() as usize, Error::::PeerIdTooLong); - let mut nodes = WellKnownNodes::get(); + let mut nodes = WellKnownNodes::::get(); ensure!(nodes.contains(&node), Error::::NotExist); nodes.remove(&node); - WellKnownNodes::put(&nodes); + WellKnownNodes::::put(&nodes); >::remove(&node); - AdditionalConnections::remove(&node); + AdditionalConnections::::remove(&node); - Self::deposit_event(RawEvent::NodeRemoved(node)); + Self::deposit_event(Event::NodeRemoved(node)); + Ok(()) } /// Swap a well known node to another. Both the ownership and additional connections @@ -237,26 +275,34 @@ decl_module! { /// /// - `remove`: the node which will be moved out from the list. /// - `add`: the node which will be put in the list. - #[weight = (T::WeightInfo::swap_well_known_node(), DispatchClass::Operational)] - pub fn swap_well_known_node(origin, remove: PeerId, add: PeerId) { + #[pallet::weight((T::WeightInfo::swap_well_known_node(), DispatchClass::Operational))] + pub fn swap_well_known_node( + origin: OriginFor, + remove: PeerId, + add: PeerId + ) -> DispatchResult { T::SwapOrigin::ensure_origin(origin)?; - ensure!(remove.0.len() < T::MaxPeerIdLength::get() as usize, Error::::PeerIdTooLong); + ensure!( + remove.0.len() < T::MaxPeerIdLength::get() as usize, + Error::::PeerIdTooLong + ); ensure!(add.0.len() < T::MaxPeerIdLength::get() as usize, Error::::PeerIdTooLong); if remove == add { return Ok(()) } - let mut nodes = WellKnownNodes::get(); + let mut nodes = WellKnownNodes::::get(); ensure!(nodes.contains(&remove), Error::::NotExist); ensure!(!nodes.contains(&add), Error::::AlreadyJoined); nodes.remove(&remove); nodes.insert(add.clone()); - WellKnownNodes::put(&nodes); + WellKnownNodes::::put(&nodes); Owners::::swap(&remove, &add); - AdditionalConnections::swap(&remove, &add); + AdditionalConnections::::swap(&remove, &add); - Self::deposit_event(RawEvent::NodeSwapped(remove, add)); + Self::deposit_event(Event::NodeSwapped(remove, add)); + Ok(()) } /// Reset all the well known nodes. This will not remove the ownership and additional @@ -266,29 +312,34 @@ decl_module! { /// May only be called from `T::ResetOrigin`. /// /// - `nodes`: the new nodes for the allow list. - #[weight = (T::WeightInfo::reset_well_known_nodes(), DispatchClass::Operational)] - pub fn reset_well_known_nodes(origin, nodes: Vec<(PeerId, T::AccountId)>) { + #[pallet::weight((T::WeightInfo::reset_well_known_nodes(), DispatchClass::Operational))] + pub fn reset_well_known_nodes( + origin: OriginFor, + nodes: Vec<(PeerId, T::AccountId)> + ) -> DispatchResult { T::ResetOrigin::ensure_origin(origin)?; ensure!(nodes.len() < T::MaxWellKnownNodes::get() as usize, Error::::TooManyNodes); Self::initialize_nodes(&nodes); - Self::deposit_event(RawEvent::NodesReset(nodes)); + Self::deposit_event(Event::NodesReset(nodes)); + Ok(()) } /// A given node can be claimed by anyone. The owner should be the first to know its /// PeerId, so claim it right away! /// /// - `node`: identifier of the node. - #[weight = T::WeightInfo::claim_node()] - pub fn claim_node(origin, node: PeerId) { + #[pallet::weight(T::WeightInfo::claim_node())] + pub fn claim_node(origin: OriginFor, node: PeerId) -> DispatchResult { let sender = ensure_signed(origin)?; ensure!(node.0.len() < T::MaxPeerIdLength::get() as usize, Error::::PeerIdTooLong); ensure!(!Owners::::contains_key(&node),Error::::AlreadyClaimed); Owners::::insert(&node, &sender); - Self::deposit_event(RawEvent::NodeClaimed(node, sender)); + Self::deposit_event(Event::NodeClaimed(node, sender)); + Ok(()) } /// A claim can be removed by its owner and get back the reservation. The additional @@ -296,27 +347,32 @@ decl_module! { /// needs to reach consensus among the network participants. /// /// - `node`: identifier of the node. - #[weight = T::WeightInfo::remove_claim()] - pub fn remove_claim(origin, node: PeerId) { + #[pallet::weight(T::WeightInfo::remove_claim())] + pub fn remove_claim(origin: OriginFor, node: PeerId) -> DispatchResult { let sender = ensure_signed(origin)?; ensure!(node.0.len() < T::MaxPeerIdLength::get() as usize, Error::::PeerIdTooLong); ensure!(Owners::::contains_key(&node), Error::::NotClaimed); ensure!(Owners::::get(&node) == sender, Error::::NotOwner); - ensure!(!WellKnownNodes::get().contains(&node), Error::::PermissionDenied); + ensure!(!WellKnownNodes::::get().contains(&node), Error::::PermissionDenied); Owners::::remove(&node); - AdditionalConnections::remove(&node); + AdditionalConnections::::remove(&node); - Self::deposit_event(RawEvent::ClaimRemoved(node, sender)); + Self::deposit_event(Event::ClaimRemoved(node, sender)); + Ok(()) } /// A node can be transferred to a new owner. /// /// - `node`: identifier of the node. /// - `owner`: new owner of the node. - #[weight = T::WeightInfo::transfer_node()] - pub fn transfer_node(origin, node: PeerId, owner: T::AccountId) { + #[pallet::weight(T::WeightInfo::transfer_node())] + pub fn transfer_node( + origin: OriginFor, + node: PeerId, + owner: T::AccountId + ) -> DispatchResult { let sender = ensure_signed(origin)?; ensure!(node.0.len() < T::MaxPeerIdLength::get() as usize, Error::::PeerIdTooLong); @@ -325,26 +381,27 @@ decl_module! { Owners::::insert(&node, &owner); - Self::deposit_event(RawEvent::NodeTransferred(node, owner)); + Self::deposit_event(Event::NodeTransferred(node, owner)); + Ok(()) } /// Add additional connections to a given node. /// /// - `node`: identifier of the node. /// - `connections`: additonal nodes from which the connections are allowed. - #[weight = T::WeightInfo::add_connections()] + #[pallet::weight(T::WeightInfo::add_connections())] pub fn add_connections( - origin, + origin: OriginFor, node: PeerId, connections: Vec - ) { + ) -> DispatchResult { let sender = ensure_signed(origin)?; ensure!(node.0.len() < T::MaxPeerIdLength::get() as usize, Error::::PeerIdTooLong); ensure!(Owners::::contains_key(&node), Error::::NotClaimed); ensure!(Owners::::get(&node) == sender, Error::::NotOwner); - let mut nodes = AdditionalConnections::get(&node); + let mut nodes = AdditionalConnections::::get(&node); for add_node in connections.iter() { if *add_node == node { @@ -353,73 +410,48 @@ decl_module! { nodes.insert(add_node.clone()); } - AdditionalConnections::insert(&node, nodes); + AdditionalConnections::::insert(&node, nodes); - Self::deposit_event(RawEvent::ConnectionsAdded(node, connections)); + Self::deposit_event(Event::ConnectionsAdded(node, connections)); + Ok(()) } /// Remove additional connections of a given node. /// /// - `node`: identifier of the node. /// - `connections`: additonal nodes from which the connections are not allowed anymore. - #[weight = T::WeightInfo::remove_connections()] + #[pallet::weight(T::WeightInfo::remove_connections())] pub fn remove_connections( - origin, + origin: OriginFor, node: PeerId, connections: Vec - ) { + ) -> DispatchResult { let sender = ensure_signed(origin)?; ensure!(node.0.len() < T::MaxPeerIdLength::get() as usize, Error::::PeerIdTooLong); ensure!(Owners::::contains_key(&node), Error::::NotClaimed); ensure!(Owners::::get(&node) == sender, Error::::NotOwner); - let mut nodes = AdditionalConnections::get(&node); + let mut nodes = AdditionalConnections::::get(&node); for remove_node in connections.iter() { nodes.remove(remove_node); } - AdditionalConnections::insert(&node, nodes); - - Self::deposit_event(RawEvent::ConnectionsRemoved(node, connections)); - } + AdditionalConnections::::insert(&node, nodes); - /// Set reserved node every block. It may not be enabled depends on the offchain - /// worker settings when starting the node. - fn offchain_worker(now: T::BlockNumber) { - let network_state = sp_io::offchain::network_state(); - match network_state { - Err(_) => log::error!( - target: "runtime::node-authorization", - "Error: failed to get network state of node at {:?}", - now, - ), - Ok(state) => { - let encoded_peer = state.peer_id.0; - match Decode::decode(&mut &encoded_peer[..]) { - Err(_) => log::error!( - target: "runtime::node-authorization", - "Error: failed to decode PeerId at {:?}", - now, - ), - Ok(node) => sp_io::offchain::set_authorized_nodes( - Self::get_authorized_nodes(&PeerId(node)), - true - ) - } - } - } + Self::deposit_event(Event::ConnectionsRemoved(node, connections)); + Ok(()) } } } -impl Module { +impl Pallet { fn initialize_nodes(nodes: &Vec<(PeerId, T::AccountId)>) { let peer_ids = nodes.iter() .map(|item| item.0.clone()) .collect::>(); - WellKnownNodes::put(&peer_ids); + WellKnownNodes::::put(&peer_ids); for (node, who) in nodes.iter() { Owners::::insert(node, who); @@ -427,9 +459,9 @@ impl Module { } fn get_authorized_nodes(node: &PeerId) -> Vec { - let mut nodes = AdditionalConnections::get(node); + let mut nodes = AdditionalConnections::::get(node); - let mut well_known_nodes = WellKnownNodes::get(); + let mut well_known_nodes = WellKnownNodes::::get(); if well_known_nodes.contains(node) { well_known_nodes.remove(node); nodes.extend(well_known_nodes); diff --git a/frame/node-authorization/src/mock.rs b/frame/node-authorization/src/mock.rs index 79a7350d82da8..0bef277d34e93 100644 --- a/frame/node-authorization/src/mock.rs +++ b/frame/node-authorization/src/mock.rs @@ -20,7 +20,10 @@ use super::*; use crate as pallet_node_authorization; -use frame_support::{parameter_types, ord_parameter_types}; +use frame_support::{ + parameter_types, ord_parameter_types, + traits::GenesisBuild, +}; use frame_system::EnsureSignedBy; use sp_core::H256; use sp_runtime::{traits::{BlakeTwo256, IdentityLookup}, testing::Header}; @@ -90,7 +93,7 @@ impl Config for Test { type WeightInfo = (); } -fn test_node(id: u8) -> PeerId { +pub fn test_node(id: u8) -> PeerId { PeerId(vec![id]) } diff --git a/frame/node-authorization/src/tests.rs b/frame/node-authorization/src/tests.rs index f151d8b3c3c25..5027994ea04c7 100644 --- a/frame/node-authorization/src/tests.rs +++ b/frame/node-authorization/src/tests.rs @@ -22,10 +22,6 @@ use crate::mock::*; use frame_support::{assert_ok, assert_noop}; use sp_runtime::traits::BadOrigin; -fn test_node(id: u8) -> PeerId { - PeerId(vec![id]) -} - #[test] fn add_well_known_node_works() { new_test_ext().execute_with(|| { @@ -46,7 +42,7 @@ fn add_well_known_node_works() { NodeAuthorization::add_well_known_node(Origin::signed(1), test_node(15), 15) ); assert_eq!( - WellKnownNodes::get(), + WellKnownNodes::::get(), BTreeSet::from_iter(vec![test_node(10), test_node(15), test_node(20), test_node(30)]) ); assert_eq!(Owners::::get(test_node(10)), 10); @@ -77,21 +73,21 @@ fn remove_well_known_node_works() { Error::::NotExist ); - AdditionalConnections::insert( + AdditionalConnections::::insert( test_node(20), BTreeSet::from_iter(vec![test_node(40)]) ); - assert!(AdditionalConnections::contains_key(test_node(20))); + assert!(AdditionalConnections::::contains_key(test_node(20))); assert_ok!( NodeAuthorization::remove_well_known_node(Origin::signed(2), test_node(20)) ); assert_eq!( - WellKnownNodes::get(), + WellKnownNodes::::get(), BTreeSet::from_iter(vec![test_node(10), test_node(30)]) ); assert!(!Owners::::contains_key(test_node(20))); - assert!(!AdditionalConnections::contains_key(test_node(20))); + assert!(!AdditionalConnections::::contains_key(test_node(20))); }); } @@ -123,7 +119,7 @@ fn swap_well_known_node_works() { ) ); assert_eq!( - WellKnownNodes::get(), + WellKnownNodes::::get(), BTreeSet::from_iter(vec![test_node(10), test_node(20), test_node(30)]) ); @@ -140,7 +136,7 @@ fn swap_well_known_node_works() { Error::::AlreadyJoined ); - AdditionalConnections::insert( + AdditionalConnections::::insert( test_node(20), BTreeSet::from_iter(vec![test_node(15)]) ); @@ -150,14 +146,14 @@ fn swap_well_known_node_works() { ) ); assert_eq!( - WellKnownNodes::get(), + WellKnownNodes::::get(), BTreeSet::from_iter(vec![test_node(5), test_node(10), test_node(30)]) ); assert!(!Owners::::contains_key(test_node(20))); assert_eq!(Owners::::get(test_node(5)), 20); - assert!(!AdditionalConnections::contains_key(test_node(20))); + assert!(!AdditionalConnections::::contains_key(test_node(20))); assert_eq!( - AdditionalConnections::get(test_node(5)), + AdditionalConnections::::get(test_node(5)), BTreeSet::from_iter(vec![test_node(15)]) ); }); @@ -193,7 +189,7 @@ fn reset_well_known_nodes_works() { ) ); assert_eq!( - WellKnownNodes::get(), + WellKnownNodes::::get(), BTreeSet::from_iter(vec![test_node(5), test_node(15), test_node(20)]) ); assert_eq!(Owners::::get(test_node(5)), 5); @@ -242,13 +238,13 @@ fn remove_claim_works() { ); Owners::::insert(test_node(15), 15); - AdditionalConnections::insert( + AdditionalConnections::::insert( test_node(15), BTreeSet::from_iter(vec![test_node(20)]) ); assert_ok!(NodeAuthorization::remove_claim(Origin::signed(15), test_node(15))); assert!(!Owners::::contains_key(test_node(15))); - assert!(!AdditionalConnections::contains_key(test_node(15))); + assert!(!AdditionalConnections::::contains_key(test_node(15))); }); } @@ -305,7 +301,7 @@ fn add_connections_works() { ) ); assert_eq!( - AdditionalConnections::get(test_node(20)), + AdditionalConnections::::get(test_node(20)), BTreeSet::from_iter(vec![test_node(5), test_node(15), test_node(25)]) ); }); @@ -334,7 +330,7 @@ fn remove_connections_works() { Error::::NotOwner ); - AdditionalConnections::insert( + AdditionalConnections::::insert( test_node(20), BTreeSet::from_iter(vec![test_node(5), test_node(15), test_node(25)]) ); @@ -346,7 +342,7 @@ fn remove_connections_works() { ) ); assert_eq!( - AdditionalConnections::get(test_node(20)), + AdditionalConnections::::get(test_node(20)), BTreeSet::from_iter(vec![test_node(25)]) ); }); @@ -355,7 +351,7 @@ fn remove_connections_works() { #[test] fn get_authorized_nodes_works() { new_test_ext().execute_with(|| { - AdditionalConnections::insert( + AdditionalConnections::::insert( test_node(20), BTreeSet::from_iter(vec![test_node(5), test_node(15), test_node(25)]) ); diff --git a/frame/node-authorization/src/weights.rs b/frame/node-authorization/src/weights.rs new file mode 100644 index 0000000000000..3d01e40d67ac3 --- /dev/null +++ b/frame/node-authorization/src/weights.rs @@ -0,0 +1,48 @@ +// This file is part of Substrate. + +// Copyright (C) 2021 Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Autogenerated weights for pallet_node_authorization + +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use sp_std::marker::PhantomData; + +pub trait WeightInfo { + fn add_well_known_node() -> Weight; + fn remove_well_known_node() -> Weight; + fn swap_well_known_node() -> Weight; + fn reset_well_known_nodes() -> Weight; + fn claim_node() -> Weight; + fn remove_claim() -> Weight; + fn transfer_node() -> Weight; + fn add_connections() -> Weight; + fn remove_connections() -> Weight; +} + +impl WeightInfo for () { + fn add_well_known_node() -> Weight { 50_000_000 } + fn remove_well_known_node() -> Weight { 50_000_000 } + fn swap_well_known_node() -> Weight { 50_000_000 } + fn reset_well_known_nodes() -> Weight { 50_000_000 } + fn claim_node() -> Weight { 50_000_000 } + fn remove_claim() -> Weight { 50_000_000 } + fn transfer_node() -> Weight { 50_000_000 } + fn add_connections() -> Weight { 50_000_000 } + fn remove_connections() -> Weight { 50_000_000 } +} From 398566e049a511afdb53364adebace3e1d262565 Mon Sep 17 00:00:00 2001 From: Kaichao Sun Date: Fri, 12 Mar 2021 10:54:05 +0800 Subject: [PATCH 3/7] expose constants --- frame/node-authorization/src/lib.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/frame/node-authorization/src/lib.rs b/frame/node-authorization/src/lib.rs index dc8f226b61ac0..5f0b3f87427ea 100644 --- a/frame/node-authorization/src/lib.rs +++ b/frame/node-authorization/src/lib.rs @@ -72,9 +72,11 @@ pub mod pallet { type Event: From> + IsType<::Event>; /// The maximum number of well known nodes that are allowed to set + #[pallet::constant] type MaxWellKnownNodes: Get; /// The maximum length in bytes of PeerId + #[pallet::constant] type MaxPeerIdLength: Get; /// The origin which can add a well known node. From 6f8a117089b86a89558773bca8ab279a505c053d Mon Sep 17 00:00:00 2001 From: Kaichao Sun Date: Fri, 12 Mar 2021 11:07:12 +0800 Subject: [PATCH 4/7] owner storage change to optional query. --- frame/node-authorization/src/lib.rs | 17 ++++++++--------- frame/node-authorization/src/tests.rs | 20 ++++++++++---------- 2 files changed, 18 insertions(+), 19 deletions(-) diff --git a/frame/node-authorization/src/lib.rs b/frame/node-authorization/src/lib.rs index 5f0b3f87427ea..a16946492d9d7 100644 --- a/frame/node-authorization/src/lib.rs +++ b/frame/node-authorization/src/lib.rs @@ -108,7 +108,6 @@ pub mod pallet { Blake2_128Concat, PeerId, T::AccountId, - ValueQuery, >; /// The additional adapative connections of each node. @@ -354,8 +353,8 @@ pub mod pallet { let sender = ensure_signed(origin)?; ensure!(node.0.len() < T::MaxPeerIdLength::get() as usize, Error::::PeerIdTooLong); - ensure!(Owners::::contains_key(&node), Error::::NotClaimed); - ensure!(Owners::::get(&node) == sender, Error::::NotOwner); + let owner = Owners::::get(&node).ok_or(Error::::NotClaimed)?; + ensure!(owner == sender, Error::::NotOwner); ensure!(!WellKnownNodes::::get().contains(&node), Error::::PermissionDenied); Owners::::remove(&node); @@ -378,8 +377,8 @@ pub mod pallet { let sender = ensure_signed(origin)?; ensure!(node.0.len() < T::MaxPeerIdLength::get() as usize, Error::::PeerIdTooLong); - ensure!(Owners::::contains_key(&node), Error::::NotClaimed); - ensure!(Owners::::get(&node) == sender, Error::::NotOwner); + let pre_owner = Owners::::get(&node).ok_or(Error::::NotClaimed)?; + ensure!(pre_owner == sender, Error::::NotOwner); Owners::::insert(&node, &owner); @@ -400,8 +399,8 @@ pub mod pallet { let sender = ensure_signed(origin)?; ensure!(node.0.len() < T::MaxPeerIdLength::get() as usize, Error::::PeerIdTooLong); - ensure!(Owners::::contains_key(&node), Error::::NotClaimed); - ensure!(Owners::::get(&node) == sender, Error::::NotOwner); + let owner = Owners::::get(&node).ok_or(Error::::NotClaimed)?; + ensure!(owner == sender, Error::::NotOwner); let mut nodes = AdditionalConnections::::get(&node); @@ -431,8 +430,8 @@ pub mod pallet { let sender = ensure_signed(origin)?; ensure!(node.0.len() < T::MaxPeerIdLength::get() as usize, Error::::PeerIdTooLong); - ensure!(Owners::::contains_key(&node), Error::::NotClaimed); - ensure!(Owners::::get(&node) == sender, Error::::NotOwner); + let owner = Owners::::get(&node).ok_or(Error::::NotClaimed)?; + ensure!(owner == sender, Error::::NotOwner); let mut nodes = AdditionalConnections::::get(&node); diff --git a/frame/node-authorization/src/tests.rs b/frame/node-authorization/src/tests.rs index 5027994ea04c7..c3f4a6c658297 100644 --- a/frame/node-authorization/src/tests.rs +++ b/frame/node-authorization/src/tests.rs @@ -45,10 +45,10 @@ fn add_well_known_node_works() { WellKnownNodes::::get(), BTreeSet::from_iter(vec![test_node(10), test_node(15), test_node(20), test_node(30)]) ); - assert_eq!(Owners::::get(test_node(10)), 10); - assert_eq!(Owners::::get(test_node(20)), 20); - assert_eq!(Owners::::get(test_node(30)), 30); - assert_eq!(Owners::::get(test_node(15)), 15); + assert_eq!(Owners::::get(test_node(10)), Some(10)); + assert_eq!(Owners::::get(test_node(20)), Some(20)); + assert_eq!(Owners::::get(test_node(30)), Some(30)); + assert_eq!(Owners::::get(test_node(15)), Some(15)); assert_noop!( NodeAuthorization::add_well_known_node(Origin::signed(1), test_node(25), 25), @@ -150,7 +150,7 @@ fn swap_well_known_node_works() { BTreeSet::from_iter(vec![test_node(5), test_node(10), test_node(30)]) ); assert!(!Owners::::contains_key(test_node(20))); - assert_eq!(Owners::::get(test_node(5)), 20); + assert_eq!(Owners::::get(test_node(5)), Some(20)); assert!(!AdditionalConnections::::contains_key(test_node(20))); assert_eq!( AdditionalConnections::::get(test_node(5)), @@ -192,9 +192,9 @@ fn reset_well_known_nodes_works() { WellKnownNodes::::get(), BTreeSet::from_iter(vec![test_node(5), test_node(15), test_node(20)]) ); - assert_eq!(Owners::::get(test_node(5)), 5); - assert_eq!(Owners::::get(test_node(15)), 15); - assert_eq!(Owners::::get(test_node(20)), 20); + assert_eq!(Owners::::get(test_node(5)), Some(5)); + assert_eq!(Owners::::get(test_node(15)), Some(15)); + assert_eq!(Owners::::get(test_node(20)), Some(20)); }); } @@ -211,7 +211,7 @@ fn claim_node_works() { ); assert_ok!(NodeAuthorization::claim_node(Origin::signed(15), test_node(15))); - assert_eq!(Owners::::get(test_node(15)), 15); + assert_eq!(Owners::::get(test_node(15)), Some(15)); }); } @@ -266,7 +266,7 @@ fn transfer_node_works() { ); assert_ok!(NodeAuthorization::transfer_node(Origin::signed(20), test_node(20), 15)); - assert_eq!(Owners::::get(test_node(20)), 15); + assert_eq!(Owners::::get(test_node(20)), Some(15)); }); } From 0cb4056ab8bb677343ce09e4266d7bdfb6c607dd Mon Sep 17 00:00:00 2001 From: Kaichao Sun Date: Fri, 12 Mar 2021 11:12:02 +0800 Subject: [PATCH 5/7] bump node auth to v3.0.0 --- Cargo.lock | 2 +- frame/node-authorization/Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7194b5820f894..c174239f1d2c4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5094,7 +5094,7 @@ dependencies = [ [[package]] name = "pallet-node-authorization" -version = "2.0.0" +version = "3.0.0" dependencies = [ "frame-support", "frame-system", diff --git a/frame/node-authorization/Cargo.toml b/frame/node-authorization/Cargo.toml index 245db9176f740..786eb84d1e523 100644 --- a/frame/node-authorization/Cargo.toml +++ b/frame/node-authorization/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pallet-node-authorization" -version = "2.0.0" +version = "3.0.0" authors = ["Parity Technologies "] edition = "2018" license = "Apache-2.0" From 0b7682bee1f198cadfe835848bdb4dbcc5649809 Mon Sep 17 00:00:00 2001 From: Kaichao Sun Date: Fri, 12 Mar 2021 13:28:15 +0800 Subject: [PATCH 6/7] fix build --- frame/node-authorization/src/lib.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/frame/node-authorization/src/lib.rs b/frame/node-authorization/src/lib.rs index a16946492d9d7..5f233549c73ca 100644 --- a/frame/node-authorization/src/lib.rs +++ b/frame/node-authorization/src/lib.rs @@ -48,6 +48,7 @@ use sp_core::OpaquePeerId as PeerId; use sp_std::{ collections::btree_set::BTreeSet, iter::FromIterator, + prelude::*, }; pub use pallet::*; pub use weights::WeightInfo; From bae0c036e61222256d654c4b3b7392ec7729fd2b Mon Sep 17 00:00:00 2001 From: Kaichao Sun Date: Fri, 12 Mar 2021 14:16:07 +0800 Subject: [PATCH 7/7] styling better --- frame/node-authorization/src/mock.rs | 2 +- frame/node-authorization/src/tests.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/frame/node-authorization/src/mock.rs b/frame/node-authorization/src/mock.rs index 0bef277d34e93..2983d081739d5 100644 --- a/frame/node-authorization/src/mock.rs +++ b/frame/node-authorization/src/mock.rs @@ -103,4 +103,4 @@ pub fn new_test_ext() -> sp_io::TestExternalities { nodes: vec![(test_node(10), 10), (test_node(20), 20), (test_node(30), 30)], }.assimilate_storage(&mut t).unwrap(); t.into() -} \ No newline at end of file +} diff --git a/frame/node-authorization/src/tests.rs b/frame/node-authorization/src/tests.rs index c3f4a6c658297..d80c6da7376bc 100644 --- a/frame/node-authorization/src/tests.rs +++ b/frame/node-authorization/src/tests.rs @@ -363,4 +363,4 @@ fn get_authorized_nodes_works() { vec![test_node(5), test_node(10), test_node(15), test_node(25), test_node(30)] ); }); -} \ No newline at end of file +}