#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;
pub mod weights;
pub use pallet::*;
use sp_core::OpaquePeerId as PeerId;
use sp_runtime::traits::StaticLookup;
use sp_std::{collections::btree_set::BTreeSet, iter::FromIterator, prelude::*};
pub use weights::WeightInfo;
type AccountIdLookupOf<T> = <<T as frame_system::Config>::Lookup as StaticLookup>::Source;
#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*;
#[pallet::pallet]
#[pallet::without_storage_info]
pub struct Pallet<T>(_);
#[pallet::config]
pub trait Config: frame_system::Config {
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
#[pallet::constant]
type MaxWellKnownNodes: Get<u32>;
#[pallet::constant]
type MaxPeerIdLength: Get<u32>;
type AddOrigin: EnsureOrigin<Self::RuntimeOrigin>;
type RemoveOrigin: EnsureOrigin<Self::RuntimeOrigin>;
type SwapOrigin: EnsureOrigin<Self::RuntimeOrigin>;
type ResetOrigin: EnsureOrigin<Self::RuntimeOrigin>;
type WeightInfo: WeightInfo;
}
#[pallet::storage]
#[pallet::getter(fn well_known_nodes)]
pub type WellKnownNodes<T> = StorageValue<_, BTreeSet<PeerId>, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn owners)]
pub type Owners<T: Config> = StorageMap<_, Blake2_128Concat, PeerId, T::AccountId>;
#[pallet::storage]
#[pallet::getter(fn additional_connection)]
pub type AdditionalConnections<T> =
StorageMap<_, Blake2_128Concat, PeerId, BTreeSet<PeerId>, ValueQuery>;
#[pallet::genesis_config]
#[derive(frame_support::DefaultNoBound)]
pub struct GenesisConfig<T: Config> {
pub nodes: Vec<(PeerId, T::AccountId)>,
}
#[pallet::genesis_build]
impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
fn build(&self) {
Pallet::<T>::initialize_nodes(&self.nodes);
}
}
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
NodeAdded { peer_id: PeerId, who: T::AccountId },
NodeRemoved { peer_id: PeerId },
NodeSwapped { removed: PeerId, added: PeerId },
NodesReset { nodes: Vec<(PeerId, T::AccountId)> },
NodeClaimed { peer_id: PeerId, who: T::AccountId },
ClaimRemoved { peer_id: PeerId, who: T::AccountId },
NodeTransferred { peer_id: PeerId, target: T::AccountId },
ConnectionsAdded { peer_id: PeerId, allowed_connections: Vec<PeerId> },
ConnectionsRemoved { peer_id: PeerId, allowed_connections: Vec<PeerId> },
}
#[pallet::error]
pub enum Error<T> {
PeerIdTooLong,
TooManyNodes,
AlreadyJoined,
NotExist,
AlreadyClaimed,
NotClaimed,
NotOwner,
PermissionDenied,
}
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
fn offchain_worker(now: frame_system::pallet_prelude::BlockNumberFor<T>) {
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<T: Config> Pallet<T> {
#[pallet::call_index(0)]
#[pallet::weight((T::WeightInfo::add_well_known_node(), DispatchClass::Operational))]
pub fn add_well_known_node(
origin: OriginFor<T>,
node: PeerId,
owner: AccountIdLookupOf<T>,
) -> DispatchResult {
T::AddOrigin::ensure_origin(origin)?;
let owner = T::Lookup::lookup(owner)?;
ensure!(node.0.len() < T::MaxPeerIdLength::get() as usize, Error::<T>::PeerIdTooLong);
let mut nodes = WellKnownNodes::<T>::get();
ensure!(nodes.len() < T::MaxWellKnownNodes::get() as usize, Error::<T>::TooManyNodes);
ensure!(!nodes.contains(&node), Error::<T>::AlreadyJoined);
nodes.insert(node.clone());
WellKnownNodes::<T>::put(&nodes);
<Owners<T>>::insert(&node, &owner);
Self::deposit_event(Event::NodeAdded { peer_id: node, who: owner });
Ok(())
}
#[pallet::call_index(1)]
#[pallet::weight((T::WeightInfo::remove_well_known_node(), DispatchClass::Operational))]
pub fn remove_well_known_node(origin: OriginFor<T>, node: PeerId) -> DispatchResult {
T::RemoveOrigin::ensure_origin(origin)?;
ensure!(node.0.len() < T::MaxPeerIdLength::get() as usize, Error::<T>::PeerIdTooLong);
let mut nodes = WellKnownNodes::<T>::get();
ensure!(nodes.contains(&node), Error::<T>::NotExist);
nodes.remove(&node);
WellKnownNodes::<T>::put(&nodes);
<Owners<T>>::remove(&node);
AdditionalConnections::<T>::remove(&node);
Self::deposit_event(Event::NodeRemoved { peer_id: node });
Ok(())
}
#[pallet::call_index(2)]
#[pallet::weight((T::WeightInfo::swap_well_known_node(), DispatchClass::Operational))]
pub fn swap_well_known_node(
origin: OriginFor<T>,
remove: PeerId,
add: PeerId,
) -> DispatchResult {
T::SwapOrigin::ensure_origin(origin)?;
ensure!(remove.0.len() < T::MaxPeerIdLength::get() as usize, Error::<T>::PeerIdTooLong);
ensure!(add.0.len() < T::MaxPeerIdLength::get() as usize, Error::<T>::PeerIdTooLong);
if remove == add {
return Ok(())
}
let mut nodes = WellKnownNodes::<T>::get();
ensure!(nodes.contains(&remove), Error::<T>::NotExist);
ensure!(!nodes.contains(&add), Error::<T>::AlreadyJoined);
nodes.remove(&remove);
nodes.insert(add.clone());
WellKnownNodes::<T>::put(&nodes);
Owners::<T>::swap(&remove, &add);
AdditionalConnections::<T>::swap(&remove, &add);
Self::deposit_event(Event::NodeSwapped { removed: remove, added: add });
Ok(())
}
#[pallet::call_index(3)]
#[pallet::weight((T::WeightInfo::reset_well_known_nodes(), DispatchClass::Operational))]
pub fn reset_well_known_nodes(
origin: OriginFor<T>,
nodes: Vec<(PeerId, T::AccountId)>,
) -> DispatchResult {
T::ResetOrigin::ensure_origin(origin)?;
ensure!(nodes.len() < T::MaxWellKnownNodes::get() as usize, Error::<T>::TooManyNodes);
Self::initialize_nodes(&nodes);
Self::deposit_event(Event::NodesReset { nodes });
Ok(())
}
#[pallet::call_index(4)]
#[pallet::weight(T::WeightInfo::claim_node())]
pub fn claim_node(origin: OriginFor<T>, node: PeerId) -> DispatchResult {
let sender = ensure_signed(origin)?;
ensure!(node.0.len() < T::MaxPeerIdLength::get() as usize, Error::<T>::PeerIdTooLong);
ensure!(!Owners::<T>::contains_key(&node), Error::<T>::AlreadyClaimed);
Owners::<T>::insert(&node, &sender);
Self::deposit_event(Event::NodeClaimed { peer_id: node, who: sender });
Ok(())
}
#[pallet::call_index(5)]
#[pallet::weight(T::WeightInfo::remove_claim())]
pub fn remove_claim(origin: OriginFor<T>, node: PeerId) -> DispatchResult {
let sender = ensure_signed(origin)?;
ensure!(node.0.len() < T::MaxPeerIdLength::get() as usize, Error::<T>::PeerIdTooLong);
let owner = Owners::<T>::get(&node).ok_or(Error::<T>::NotClaimed)?;
ensure!(owner == sender, Error::<T>::NotOwner);
ensure!(!WellKnownNodes::<T>::get().contains(&node), Error::<T>::PermissionDenied);
Owners::<T>::remove(&node);
AdditionalConnections::<T>::remove(&node);
Self::deposit_event(Event::ClaimRemoved { peer_id: node, who: sender });
Ok(())
}
#[pallet::call_index(6)]
#[pallet::weight(T::WeightInfo::transfer_node())]
pub fn transfer_node(
origin: OriginFor<T>,
node: PeerId,
owner: AccountIdLookupOf<T>,
) -> DispatchResult {
let sender = ensure_signed(origin)?;
let owner = T::Lookup::lookup(owner)?;
ensure!(node.0.len() < T::MaxPeerIdLength::get() as usize, Error::<T>::PeerIdTooLong);
let pre_owner = Owners::<T>::get(&node).ok_or(Error::<T>::NotClaimed)?;
ensure!(pre_owner == sender, Error::<T>::NotOwner);
Owners::<T>::insert(&node, &owner);
Self::deposit_event(Event::NodeTransferred { peer_id: node, target: owner });
Ok(())
}
#[pallet::call_index(7)]
#[pallet::weight(T::WeightInfo::add_connections())]
pub fn add_connections(
origin: OriginFor<T>,
node: PeerId,
connections: Vec<PeerId>,
) -> DispatchResult {
let sender = ensure_signed(origin)?;
ensure!(node.0.len() < T::MaxPeerIdLength::get() as usize, Error::<T>::PeerIdTooLong);
let owner = Owners::<T>::get(&node).ok_or(Error::<T>::NotClaimed)?;
ensure!(owner == sender, Error::<T>::NotOwner);
let mut nodes = AdditionalConnections::<T>::get(&node);
for add_node in connections.iter() {
if *add_node == node {
continue
}
nodes.insert(add_node.clone());
}
AdditionalConnections::<T>::insert(&node, nodes);
Self::deposit_event(Event::ConnectionsAdded {
peer_id: node,
allowed_connections: connections,
});
Ok(())
}
#[pallet::call_index(8)]
#[pallet::weight(T::WeightInfo::remove_connections())]
pub fn remove_connections(
origin: OriginFor<T>,
node: PeerId,
connections: Vec<PeerId>,
) -> DispatchResult {
let sender = ensure_signed(origin)?;
ensure!(node.0.len() < T::MaxPeerIdLength::get() as usize, Error::<T>::PeerIdTooLong);
let owner = Owners::<T>::get(&node).ok_or(Error::<T>::NotClaimed)?;
ensure!(owner == sender, Error::<T>::NotOwner);
let mut nodes = AdditionalConnections::<T>::get(&node);
for remove_node in connections.iter() {
nodes.remove(remove_node);
}
AdditionalConnections::<T>::insert(&node, nodes);
Self::deposit_event(Event::ConnectionsRemoved {
peer_id: node,
allowed_connections: connections,
});
Ok(())
}
}
}
impl<T: Config> Pallet<T> {
fn initialize_nodes(nodes: &Vec<(PeerId, T::AccountId)>) {
let peer_ids = nodes.iter().map(|item| item.0.clone()).collect::<BTreeSet<PeerId>>();
WellKnownNodes::<T>::put(&peer_ids);
for (node, who) in nodes.iter() {
Owners::<T>::insert(node, who);
}
}
fn get_authorized_nodes(node: &PeerId) -> Vec<PeerId> {
let mut nodes = AdditionalConnections::<T>::get(node);
let mut well_known_nodes = WellKnownNodes::<T>::get();
if well_known_nodes.contains(node) {
well_known_nodes.remove(node);
nodes.extend(well_known_nodes);
}
Vec::from_iter(nodes)
}
}