referrerpolicy=no-referrer-when-downgrade

staging_xcm/
utils.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//! XCM utils for internal use.
18
19use crate::MAX_INSTRUCTIONS_TO_DECODE;
20
21use alloc::vec::Vec;
22use codec::{decode_vec_with_len, Compact, Decode};
23
24environmental::environmental!(instructions_count: u8);
25
26/// Decode a `vec` of XCM instructions.
27///
28/// This function keeps track of nested XCM instructions and enforces a total limit of
29/// `MAX_INSTRUCTIONS_TO_DECODE`.
30pub fn decode_xcm_instructions<I: codec::Input, T: Decode>(
31	input: &mut I,
32) -> Result<Vec<T>, codec::Error> {
33	instructions_count::using_once(&mut 0, || {
34		let vec_len: u32 = <Compact<u32>>::decode(input)?.into();
35		instructions_count::with(|count| {
36			*count = count.saturating_add(vec_len as u8);
37			if *count > MAX_INSTRUCTIONS_TO_DECODE {
38				return Err(codec::Error::from("Max instructions exceeded"))
39			}
40			Ok(())
41		})
42		.unwrap_or(Err(codec::Error::from("Error calling `instructions_count::with()`")))?;
43		let decoded_instructions = decode_vec_with_len(input, vec_len as usize)?;
44		Ok(decoded_instructions)
45	})
46}