referrerpolicy=no-referrer-when-downgrade

polkadot_runtime_parachains/
dmp.rs

1// Copyright (C) Parity Technologies (UK) Ltd.
2// This file is part of Polkadot.
3
4// Polkadot is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// Polkadot is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with Polkadot.  If not, see <http://www.gnu.org/licenses/>.
16
17//! To prevent Out of Memory errors on the `DownwardMessageQueue`, an
18//! exponential fee factor (`DeliveryFeeFactor`) is set. The fee factor
19//! increments exponentially after the number of messages in the
20//! `DownwardMessageQueue` passes a threshold. This threshold is set as:
21//!
22//! ```ignore
23//! // Maximum max sized messages that can be send to
24//! // the DownwardMessageQueue before it runs out of memory
25//! max_messages = MAX_POSSIBLE_ALLOCATION / max_downward_message_size
26//! threshold = max_messages / THRESHOLD_FACTOR
27//! ```
28//! Based on the THRESHOLD_FACTOR, the threshold is set as a fraction of the
29//! total messages. The `DeliveryFeeFactor` increases for a message over the
30//! threshold by:
31//!
32//! `DeliveryFeeFactor = DeliveryFeeFactor *
33//! (EXPONENTIAL_FEE_BASE + MESSAGE_SIZE_FEE_BASE * encoded_message_size_in_KB)`
34//!
35//! And decreases when the number of messages in the `DownwardMessageQueue` fall
36//! below the threshold by:
37//!
38//! `DeliveryFeeFactor = DeliveryFeeFactor / EXPONENTIAL_FEE_BASE`
39//!
40//! As an extra defensive measure, a `max_messages` hard
41//! limit is set to the number of messages in the DownwardMessageQueue. Messages
42//! that would increase the number of messages in the queue above this hard
43//! limit are dropped.
44
45use crate::{
46	configuration::{self, HostConfiguration},
47	initializer, paras, FeeTracker, GetMinFeeFactor,
48};
49use alloc::vec::Vec;
50use core::fmt;
51use frame_support::pallet_prelude::*;
52use frame_system::pallet_prelude::BlockNumberFor;
53use polkadot_primitives::{DownwardMessage, Hash, Id as ParaId, InboundDownwardMessage};
54use sp_core::MAX_POSSIBLE_ALLOCATION;
55use sp_runtime::{
56	traits::{BlakeTwo256, Hash as HashT, SaturatedConversion},
57	FixedU128,
58};
59use xcm::latest::SendError;
60
61pub use pallet::*;
62
63#[cfg(test)]
64mod tests;
65
66const THRESHOLD_FACTOR: u32 = 2;
67
68/// An error sending a downward message.
69#[derive(Debug)]
70pub enum QueueDownwardMessageError {
71	/// The message being sent exceeds the configured max message size.
72	ExceedsMaxMessageSize,
73	/// The destination is unknown.
74	Unroutable,
75}
76
77impl From<QueueDownwardMessageError> for SendError {
78	fn from(err: QueueDownwardMessageError) -> Self {
79		match err {
80			QueueDownwardMessageError::ExceedsMaxMessageSize => SendError::ExceedsMaxMessageSize,
81			QueueDownwardMessageError::Unroutable => SendError::Unroutable,
82		}
83	}
84}
85
86/// An error returned by [`Pallet::check_processed_downward_messages`] that indicates an acceptance
87/// check didn't pass.
88pub(crate) enum ProcessedDownwardMessagesAcceptanceErr {
89	/// If there are pending messages then `processed_downward_messages` should be at least 1,
90	AdvancementRule,
91	/// `processed_downward_messages` should not be greater than the number of pending messages.
92	Underflow { processed_downward_messages: u32, dmq_length: u32 },
93}
94
95impl fmt::Debug for ProcessedDownwardMessagesAcceptanceErr {
96	fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
97		use ProcessedDownwardMessagesAcceptanceErr::*;
98		match *self {
99			AdvancementRule => {
100				write!(fmt, "DMQ is not empty, but processed_downward_messages is 0",)
101			},
102			Underflow { processed_downward_messages, dmq_length } => write!(
103				fmt,
104				"processed_downward_messages = {}, but dmq_length is only {}",
105				processed_downward_messages, dmq_length,
106			),
107		}
108	}
109}
110
111#[frame_support::pallet]
112pub mod pallet {
113	use super::*;
114
115	#[pallet::pallet]
116	#[pallet::without_storage_info]
117	pub struct Pallet<T>(_);
118
119	#[pallet::config]
120	pub trait Config: frame_system::Config + configuration::Config + paras::Config {}
121
122	/// The downward messages addressed for a certain para.
123	#[pallet::storage]
124	pub type DownwardMessageQueues<T: Config> = StorageMap<
125		_,
126		Twox64Concat,
127		ParaId,
128		Vec<InboundDownwardMessage<BlockNumberFor<T>>>,
129		ValueQuery,
130	>;
131
132	/// A mapping that stores the downward message queue MQC head for each para.
133	///
134	/// Each link in this chain has a form:
135	/// `(prev_head, B, H(M))`, where
136	/// - `prev_head`: is the previous head hash or zero if none.
137	/// - `B`: is the relay-chain block number in which a message was appended.
138	/// - `H(M)`: is the hash of the message being appended.
139	#[pallet::storage]
140	pub(crate) type DownwardMessageQueueHeads<T: Config> =
141		StorageMap<_, Twox64Concat, ParaId, Hash, ValueQuery>;
142
143	/// The factor to multiply the base delivery fee by.
144	#[pallet::storage]
145	pub(crate) type DeliveryFeeFactor<T: Config> =
146		StorageMap<_, Twox64Concat, ParaId, FixedU128, ValueQuery, GetMinFeeFactor<Pallet<T>>>;
147}
148/// Routines and getters related to downward message passing.
149impl<T: Config> Pallet<T> {
150	/// Block initialization logic, called by initializer.
151	pub(crate) fn initializer_initialize(_now: BlockNumberFor<T>) -> Weight {
152		Weight::zero()
153	}
154
155	/// Block finalization logic, called by initializer.
156	pub(crate) fn initializer_finalize() {}
157
158	/// Called by the initializer to note that a new session has started.
159	pub(crate) fn initializer_on_new_session(
160		_notification: &initializer::SessionChangeNotification<BlockNumberFor<T>>,
161		outgoing_paras: &[ParaId],
162	) {
163		Self::perform_outgoing_para_cleanup(outgoing_paras);
164	}
165
166	/// Iterate over all paras that were noted for offboarding and remove all the data
167	/// associated with them.
168	fn perform_outgoing_para_cleanup(outgoing: &[ParaId]) {
169		for outgoing_para in outgoing {
170			Self::clean_dmp_after_outgoing(outgoing_para);
171		}
172	}
173
174	/// Remove all relevant storage items for an outgoing parachain.
175	fn clean_dmp_after_outgoing(outgoing_para: &ParaId) {
176		DownwardMessageQueues::<T>::remove(outgoing_para);
177		DownwardMessageQueueHeads::<T>::remove(outgoing_para);
178	}
179
180	/// Determine whether enqueuing a downward message to a specific recipient para would result
181	/// in an error. If this returns `Ok(())` the caller can be certain that a call to
182	/// `queue_downward_message` with the same parameters will be successful.
183	pub fn can_queue_downward_message(
184		config: &HostConfiguration<BlockNumberFor<T>>,
185		para: &ParaId,
186		msg: &DownwardMessage,
187	) -> Result<(), QueueDownwardMessageError> {
188		let serialized_len = msg.len() as u32;
189		if serialized_len > config.max_downward_message_size {
190			return Err(QueueDownwardMessageError::ExceedsMaxMessageSize)
191		}
192
193		// Hard limit on Queue size
194		if Self::dmq_length(*para) > Self::dmq_max_length(config.max_downward_message_size) {
195			return Err(QueueDownwardMessageError::ExceedsMaxMessageSize)
196		}
197
198		// If the head exists, we assume the parachain is legit and exists.
199		if !paras::Heads::<T>::contains_key(para) {
200			return Err(QueueDownwardMessageError::Unroutable)
201		}
202
203		Ok(())
204	}
205
206	/// Enqueue a downward message to a specific recipient para.
207	///
208	/// When encoded, the message should not exceed the `config.max_downward_message_size`.
209	/// Otherwise, the message won't be sent and `Err` will be returned.
210	///
211	/// It is possible to send a downward message to a non-existent para. That, however, would lead
212	/// to a dangling storage. If the caller cannot statically prove that the recipient exists
213	/// then the caller should perform a runtime check.
214	pub fn queue_downward_message(
215		config: &HostConfiguration<BlockNumberFor<T>>,
216		para: ParaId,
217		msg: DownwardMessage,
218	) -> Result<(), QueueDownwardMessageError> {
219		let serialized_len = msg.len();
220		Self::can_queue_downward_message(config, &para, &msg)?;
221
222		let inbound =
223			InboundDownwardMessage { msg, sent_at: frame_system::Pallet::<T>::block_number() };
224
225		// obtain the new link in the MQC and update the head.
226		DownwardMessageQueueHeads::<T>::mutate(para, |head| {
227			let new_head =
228				BlakeTwo256::hash_of(&(*head, inbound.sent_at, T::Hashing::hash_of(&inbound.msg)));
229			*head = new_head;
230		});
231
232		let q_len = DownwardMessageQueues::<T>::mutate(para, |v| {
233			v.push(inbound);
234			v.len()
235		});
236
237		let threshold =
238			Self::dmq_max_length(config.max_downward_message_size).saturating_div(THRESHOLD_FACTOR);
239		if q_len > (threshold as usize) {
240			Self::increase_fee_factor(para, serialized_len as u128);
241		}
242
243		Ok(())
244	}
245
246	/// Checks if the number of processed downward messages is valid.
247	pub(crate) fn check_processed_downward_messages(
248		para: ParaId,
249		relay_parent_number: BlockNumberFor<T>,
250		processed_downward_messages: u32,
251	) -> Result<(), ProcessedDownwardMessagesAcceptanceErr> {
252		let dmq_length = Self::dmq_length(para);
253
254		if dmq_length > 0 && processed_downward_messages == 0 {
255			// The advancement rule is for at least one downwards message to be processed
256			// if the queue is non-empty at the relay-parent. Downwards messages are annotated
257			// with the block number, so we compare the earliest (first) against the relay parent.
258			let contents = Self::dmq_contents(para);
259
260			// sanity: if dmq_length is >0 this should always be 'Some'.
261			if contents.get(0).map_or(false, |msg| msg.sent_at <= relay_parent_number) {
262				return Err(ProcessedDownwardMessagesAcceptanceErr::AdvancementRule)
263			}
264		}
265
266		// Note that we might be allowing a parachain to signal that it's processed
267		// messages that hadn't been placed in the queue at the relay_parent.
268		// only 'stupid' parachains would do it and we don't (and can't) force anyone
269		// to act on messages, so the lenient approach is fine here.
270		if dmq_length < processed_downward_messages {
271			return Err(ProcessedDownwardMessagesAcceptanceErr::Underflow {
272				processed_downward_messages,
273				dmq_length,
274			})
275		}
276
277		Ok(())
278	}
279
280	/// Prunes the specified number of messages from the downward message queue of the given para.
281	pub(crate) fn prune_dmq(para: ParaId, processed_downward_messages: u32) {
282		let q_len = DownwardMessageQueues::<T>::mutate(para, |q| {
283			let processed_downward_messages = processed_downward_messages as usize;
284			if processed_downward_messages > q.len() {
285				// reaching this branch is unexpected due to the constraint established by
286				// `check_processed_downward_messages`. But better be safe than sorry.
287				q.clear();
288			} else {
289				*q = q.split_off(processed_downward_messages);
290			}
291			q.len()
292		});
293
294		let config = configuration::ActiveConfig::<T>::get();
295		let threshold =
296			Self::dmq_max_length(config.max_downward_message_size).saturating_div(THRESHOLD_FACTOR);
297		if q_len <= (threshold as usize) {
298			Self::decrease_fee_factor(para);
299		}
300	}
301
302	/// Returns the Head of Message Queue Chain for the given para or `None` if there is none
303	/// associated with it.
304	#[cfg(test)]
305	fn dmq_mqc_head(para: ParaId) -> Hash {
306		DownwardMessageQueueHeads::<T>::get(&para)
307	}
308
309	/// Returns the number of pending downward messages addressed to the given para.
310	///
311	/// Returns 0 if the para doesn't have an associated downward message queue.
312	pub(crate) fn dmq_length(para: ParaId) -> u32 {
313		DownwardMessageQueues::<T>::decode_len(&para)
314			.unwrap_or(0)
315			.saturated_into::<u32>()
316	}
317
318	fn dmq_max_length(max_downward_message_size: u32) -> u32 {
319		MAX_POSSIBLE_ALLOCATION.checked_div(max_downward_message_size).unwrap_or(0)
320	}
321
322	/// Returns the downward message queue contents for the given para.
323	///
324	/// The most recent messages are the latest in the vector.
325	pub(crate) fn dmq_contents(
326		recipient: ParaId,
327	) -> Vec<InboundDownwardMessage<BlockNumberFor<T>>> {
328		DownwardMessageQueues::<T>::get(&recipient)
329	}
330
331	/// Make the parachain reachable for downward messages.
332	///
333	/// Only useable in benchmarks or tests.
334	#[cfg(any(feature = "runtime-benchmarks", feature = "std"))]
335	pub fn make_parachain_reachable(para: impl Into<ParaId>) {
336		let para = para.into();
337		crate::paras::Heads::<T>::insert(para, para.encode());
338	}
339}
340
341impl<T: Config> FeeTracker for Pallet<T> {
342	type Id = ParaId;
343
344	fn get_fee_factor(id: Self::Id) -> FixedU128 {
345		DeliveryFeeFactor::<T>::get(id)
346	}
347
348	fn set_fee_factor(id: Self::Id, val: FixedU128) {
349		<DeliveryFeeFactor<T>>::set(id, val);
350	}
351}
352
353#[cfg(feature = "runtime-benchmarks")]
354impl<T: Config> crate::EnsureForParachain for Pallet<T> {
355	fn ensure(para: ParaId) {
356		Self::make_parachain_reachable(para);
357	}
358}