|
| 1 | +// Copyright (C) Parity Technologies (UK) Ltd. |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +// you may not use this file except in compliance with the License. |
| 6 | +// You may obtain a copy of the License at |
| 7 | +// |
| 8 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +// |
| 10 | +// Unless required by applicable law or agreed to in writing, software |
| 11 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +// See the License for the specific language governing permissions and |
| 14 | +// limitations under the License. |
| 15 | + |
| 16 | +//! A pallet for scheduling and syncing key-value pairs (roots) with arbitrary destinations. |
| 17 | +//! |
| 18 | +//! The pallet provides functionality to: |
| 19 | +//! - Schedule roots for syncing using `schedule_for_sync` |
| 20 | +//! - Automatically process scheduled roots during `on_idle` hooks |
| 21 | +//! |
| 22 | +//! The actual sending/syncing of roots is implemented by the `OnSend` trait, which can be |
| 23 | +//! customized for specific use cases like cross-chain communication. |
| 24 | +//! |
| 25 | +//! Basically, this is a simple `on_idle` hook that can schedule data with a ring buffer and send |
| 26 | +//! data. |
| 27 | +
|
| 28 | +#![cfg_attr(not(feature = "std"), no_std)] |
| 29 | + |
| 30 | +extern crate alloc; |
| 31 | + |
| 32 | +use alloc::{collections::VecDeque, vec::Vec}; |
| 33 | +use frame_support::pallet_prelude::Weight; |
| 34 | + |
| 35 | +pub mod impls; |
| 36 | + |
| 37 | +#[cfg(test)] |
| 38 | +mod mock; |
| 39 | +#[cfg(test)] |
| 40 | +mod tests; |
| 41 | + |
| 42 | +pub use pallet::*; |
| 43 | + |
| 44 | +const LOG_TARGET: &str = "runtime::bridge-proof-root-sync"; |
| 45 | + |
| 46 | +/// A trait for sending/syncing roots, for example, to other chains. |
| 47 | +pub trait OnSend<Key, Value> { |
| 48 | + /// Process a list of roots (key-value pairs) for sending. |
| 49 | + /// |
| 50 | + /// # Arguments |
| 51 | + /// |
| 52 | + /// * `roots` - A vector of roots where each root is a tuple of (key, value). Roots are ordered |
| 53 | + /// from the oldest (index 0) to the newest (last index). |
| 54 | + fn on_send(roots: &Vec<(Key, Value)>); |
| 55 | + |
| 56 | + /// Returns the weight consumed by `on_send`. |
| 57 | + fn on_send_weight() -> Weight; |
| 58 | +} |
| 59 | + |
| 60 | +#[impl_trait_for_tuples::impl_for_tuples(8)] |
| 61 | +impl<Key, Value> OnSend<Key, Value> for Tuple { |
| 62 | + fn on_send(roots: &Vec<(Key, Value)>) { |
| 63 | + for_tuples!( #( Tuple::on_send(roots);) * ); |
| 64 | + } |
| 65 | + |
| 66 | + fn on_send_weight() -> Weight { |
| 67 | + let mut weight: Weight = Default::default(); |
| 68 | + for_tuples!( #( weight.saturating_accrue(Tuple::on_send_weight()); )* ); |
| 69 | + weight |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +#[frame_support::pallet] |
| 74 | +pub mod pallet { |
| 75 | + use super::*; |
| 76 | + use frame_support::{pallet_prelude::*, sp_runtime::SaturatedConversion, weights::WeightMeter}; |
| 77 | + use frame_system::pallet_prelude::*; |
| 78 | + |
| 79 | + #[pallet::pallet] |
| 80 | + pub struct Pallet<T, I = ()>(_); |
| 81 | + |
| 82 | + /// The pallet configuration trait. |
| 83 | + #[pallet::config] |
| 84 | + pub trait Config<I: 'static = ()>: frame_system::Config { |
| 85 | + /// The key type used to identify stored values of type `T::Value`. |
| 86 | + type Key: Parameter; |
| 87 | + |
| 88 | + /// The type of the root value. |
| 89 | + type Value: Parameter; |
| 90 | + |
| 91 | + /// Maximum number of roots to retain in `RootsToSend` storage. |
| 92 | + /// This setting prevents unbounded growth of the on-chain state. |
| 93 | + /// If we hit this number, we start removing the oldest data from `RootsToSend`. |
| 94 | + #[pallet::constant] |
| 95 | + type RootsToKeep: Get<u32>; |
| 96 | + |
| 97 | + /// Maximum number of roots to drain and send with `T::OnSend`. |
| 98 | + #[pallet::constant] |
| 99 | + type MaxRootsToSend: Get<u32>; |
| 100 | + |
| 101 | + /// Means for sending/syncing roots. |
| 102 | + type OnSend: OnSend<Self::Key, Self::Value>; |
| 103 | + } |
| 104 | + |
| 105 | + /// A ring-buffer storage of roots (key-value pairs) that need to be sent/synced to other |
| 106 | + /// chains. When the buffer reaches its capacity limit defined by `T::RootsToKeep`, the oldest |
| 107 | + /// elements are removed. The elements are drained and processed in order by `T::OnSend` during |
| 108 | + /// `on_idle` up to `T::MaxRootsToSend` elements at a time. |
| 109 | + #[pallet::storage] |
| 110 | + #[pallet::unbounded] |
| 111 | + pub type RootsToSend<T: Config<I>, I: 'static = ()> = |
| 112 | + StorageValue<_, VecDeque<(T::Key, T::Value)>, ValueQuery>; |
| 113 | + |
| 114 | + #[pallet::hooks] |
| 115 | + impl<T: Config<I>, I: 'static> Hooks<BlockNumberFor<T>> for Pallet<T, I> { |
| 116 | + fn on_idle(_n: BlockNumberFor<T>, limit: Weight) -> Weight { |
| 117 | + let mut meter = WeightMeter::with_limit(limit); |
| 118 | + if meter.try_consume(Self::on_idle_weight()).is_err() { |
| 119 | + tracing::debug!( |
| 120 | + target: LOG_TARGET, |
| 121 | + ?limit, |
| 122 | + on_idle_weight = ?Self::on_idle_weight(), |
| 123 | + "Not enough weight for on_idle.", |
| 124 | + ); |
| 125 | + return meter.consumed(); |
| 126 | + } |
| 127 | + |
| 128 | + // Send roots. |
| 129 | + RootsToSend::<T, I>::mutate(|roots| { |
| 130 | + let range_for_send = |
| 131 | + 0..core::cmp::min(T::MaxRootsToSend::get().saturated_into(), roots.len()); |
| 132 | + T::OnSend::on_send(&roots.drain(range_for_send).collect::<Vec<_>>()) |
| 133 | + }); |
| 134 | + |
| 135 | + meter.consumed() |
| 136 | + } |
| 137 | + } |
| 138 | + |
| 139 | + impl<T: Config<I>, I: 'static> Pallet<T, I> { |
| 140 | + /// The worst-case weight of [`Self::on_idle`]. |
| 141 | + fn on_idle_weight() -> Weight { |
| 142 | + T::DbWeight::get() |
| 143 | + .reads_writes(1, 1) |
| 144 | + .saturating_add(T::OnSend::on_send_weight()) |
| 145 | + } |
| 146 | + |
| 147 | + /// Schedule new data to be synced by `T::OnSend` means. |
| 148 | + /// |
| 149 | + /// The roots are stored in a ring buffer with limited capacity as defined by |
| 150 | + /// `T::RootsToKeep`. When the buffer reaches its capacity limit, the oldest elements are |
| 151 | + /// removed. The elements will be drained and processed in order by `T::OnSend` during |
| 152 | + /// `on_idle` up to `T::MaxRootsToSend` elements at a time. |
| 153 | + pub fn schedule_for_sync(key: T::Key, value: T::Value) { |
| 154 | + RootsToSend::<T, I>::mutate(|roots| { |
| 155 | + // Add to schedules. |
| 156 | + roots.push_back((key, value)); |
| 157 | + |
| 158 | + // Remove from the front up to the `T::RootsToKeep` limit. |
| 159 | + let max = T::RootsToKeep::get(); |
| 160 | + while roots.len() > (max as usize) { |
| 161 | + let _ = roots.pop_front(); |
| 162 | + } |
| 163 | + }); |
| 164 | + } |
| 165 | + } |
| 166 | +} |
0 commit comments