referrerpolicy=no-referrer-when-downgrade

staging_xcm/v3/
junction.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//! Support data structures for `MultiLocation`, primarily the `Junction` datatype.
18
19use super::{Junctions, MultiLocation};
20use crate::{
21	v4::{Junction as NewJunction, NetworkId as NewNetworkId},
22	VersionedLocation,
23};
24use bounded_collections::{BoundedSlice, BoundedVec, ConstU32};
25use codec::{self, Decode, DecodeWithMemTracking, Encode, MaxEncodedLen};
26use scale_info::TypeInfo;
27use serde::{Deserialize, Serialize};
28
29/// A global identifier of a data structure existing within consensus.
30///
31/// Maintenance note: Networks with global consensus and which are practically bridgeable within the
32/// Polkadot ecosystem are given preference over explicit naming in this enumeration.
33#[derive(
34	Copy,
35	Clone,
36	Eq,
37	PartialEq,
38	Ord,
39	PartialOrd,
40	Encode,
41	Decode,
42	DecodeWithMemTracking,
43	Debug,
44	TypeInfo,
45	MaxEncodedLen,
46	Serialize,
47	Deserialize,
48)]
49#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
50#[scale_info(replace_segment("staging_xcm", "xcm"))]
51pub enum NetworkId {
52	/// Network specified by the first 32 bytes of its genesis block.
53	ByGenesis([u8; 32]),
54	/// Network defined by the first 32-bytes of the hash and number of some block it contains.
55	ByFork { block_number: u64, block_hash: [u8; 32] },
56	/// The Polkadot mainnet Relay-chain.
57	Polkadot,
58	/// The Kusama canary-net Relay-chain.
59	Kusama,
60	/// The Westend testnet Relay-chain.
61	Westend,
62	/// The Rococo testnet Relay-chain.
63	Rococo,
64	/// The Wococo testnet Relay-chain.
65	Wococo,
66	/// An Ethereum network specified by its chain ID.
67	Ethereum {
68		/// The EIP-155 chain ID.
69		#[codec(compact)]
70		chain_id: u64,
71	},
72	/// The Bitcoin network, including hard-forks supported by Bitcoin Core development team.
73	BitcoinCore,
74	/// The Bitcoin network, including hard-forks supported by Bitcoin Cash developers.
75	BitcoinCash,
76	/// The Polkadot Bulletin chain.
77	PolkadotBulletin,
78}
79
80impl From<NewNetworkId> for Option<NetworkId> {
81	fn from(new: NewNetworkId) -> Self {
82		Some(NetworkId::from(new))
83	}
84}
85
86impl From<NewNetworkId> for NetworkId {
87	fn from(new: NewNetworkId) -> Self {
88		use NewNetworkId::*;
89		match new {
90			ByGenesis(hash) => Self::ByGenesis(hash),
91			ByFork { block_number, block_hash } => Self::ByFork { block_number, block_hash },
92			Polkadot => Self::Polkadot,
93			Kusama => Self::Kusama,
94			Westend => Self::Westend,
95			Rococo => Self::Rococo,
96			Wococo => Self::Wococo,
97			Ethereum { chain_id } => Self::Ethereum { chain_id },
98			BitcoinCore => Self::BitcoinCore,
99			BitcoinCash => Self::BitcoinCash,
100			PolkadotBulletin => Self::PolkadotBulletin,
101		}
102	}
103}
104
105/// An identifier of a pluralistic body.
106#[derive(
107	Copy,
108	Clone,
109	Eq,
110	PartialEq,
111	Ord,
112	PartialOrd,
113	Encode,
114	Decode,
115	DecodeWithMemTracking,
116	Debug,
117	TypeInfo,
118	MaxEncodedLen,
119	Serialize,
120	Deserialize,
121)]
122#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
123#[scale_info(replace_segment("staging_xcm", "xcm"))]
124pub enum BodyId {
125	/// The only body in its context.
126	Unit,
127	/// A named body.
128	Moniker([u8; 4]),
129	/// An indexed body.
130	Index(#[codec(compact)] u32),
131	/// The unambiguous executive body (for Polkadot, this would be the Polkadot council).
132	Executive,
133	/// The unambiguous technical body (for Polkadot, this would be the Technical Committee).
134	Technical,
135	/// The unambiguous legislative body (for Polkadot, this could be considered the opinion of a
136	/// majority of lock-voters).
137	Legislative,
138	/// The unambiguous judicial body (this doesn't exist on Polkadot, but if it were to get a
139	/// "grand oracle", it may be considered as that).
140	Judicial,
141	/// The unambiguous defense body (for Polkadot, an opinion on the topic given via a public
142	/// referendum on the `staking_admin` track).
143	Defense,
144	/// The unambiguous administration body (for Polkadot, an opinion on the topic given via a
145	/// public referendum on the `general_admin` track).
146	Administration,
147	/// The unambiguous treasury body (for Polkadot, an opinion on the topic given via a public
148	/// referendum on the `treasurer` track).
149	Treasury,
150}
151
152/// A part of a pluralistic body.
153#[derive(
154	Copy,
155	Clone,
156	Eq,
157	PartialEq,
158	Ord,
159	PartialOrd,
160	Encode,
161	Decode,
162	DecodeWithMemTracking,
163	Debug,
164	TypeInfo,
165	MaxEncodedLen,
166	Serialize,
167	Deserialize,
168)]
169#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
170#[scale_info(replace_segment("staging_xcm", "xcm"))]
171pub enum BodyPart {
172	/// The body's declaration, under whatever means it decides.
173	Voice,
174	/// A given number of members of the body.
175	Members {
176		#[codec(compact)]
177		count: u32,
178	},
179	/// A given number of members of the body, out of some larger caucus.
180	Fraction {
181		#[codec(compact)]
182		nom: u32,
183		#[codec(compact)]
184		denom: u32,
185	},
186	/// No less than the given proportion of members of the body.
187	AtLeastProportion {
188		#[codec(compact)]
189		nom: u32,
190		#[codec(compact)]
191		denom: u32,
192	},
193	/// More than the given proportion of members of the body.
194	MoreThanProportion {
195		#[codec(compact)]
196		nom: u32,
197		#[codec(compact)]
198		denom: u32,
199	},
200}
201
202impl BodyPart {
203	/// Returns `true` if the part represents a strict majority (> 50%) of the body in question.
204	pub fn is_majority(&self) -> bool {
205		match self {
206			BodyPart::Fraction { nom, denom } if *nom * 2 > *denom => true,
207			BodyPart::AtLeastProportion { nom, denom } if *nom * 2 > *denom => true,
208			BodyPart::MoreThanProportion { nom, denom } if *nom * 2 >= *denom => true,
209			_ => false,
210		}
211	}
212}
213
214/// A single item in a path to describe the relative location of a consensus system.
215///
216/// Each item assumes a pre-existing location as its context and is defined in terms of it.
217#[derive(
218	Copy,
219	Clone,
220	Eq,
221	PartialEq,
222	Ord,
223	PartialOrd,
224	Encode,
225	Decode,
226	DecodeWithMemTracking,
227	Debug,
228	TypeInfo,
229	MaxEncodedLen,
230	Serialize,
231	Deserialize,
232)]
233#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
234#[scale_info(replace_segment("staging_xcm", "xcm"))]
235pub enum Junction {
236	/// An indexed parachain belonging to and operated by the context.
237	///
238	/// Generally used when the context is a Polkadot Relay-chain.
239	Parachain(#[codec(compact)] u32),
240	/// A 32-byte identifier for an account of a specific network that is respected as a sovereign
241	/// endpoint within the context.
242	///
243	/// Generally used when the context is a Substrate-based chain.
244	AccountId32 { network: Option<NetworkId>, id: [u8; 32] },
245	/// An 8-byte index for an account of a specific network that is respected as a sovereign
246	/// endpoint within the context.
247	///
248	/// May be used when the context is a Frame-based chain and includes e.g. an indices pallet.
249	AccountIndex64 {
250		network: Option<NetworkId>,
251		#[codec(compact)]
252		index: u64,
253	},
254	/// A 20-byte identifier for an account of a specific network that is respected as a sovereign
255	/// endpoint within the context.
256	///
257	/// May be used when the context is an Ethereum or Bitcoin chain or smart-contract.
258	AccountKey20 { network: Option<NetworkId>, key: [u8; 20] },
259	/// An instanced, indexed pallet that forms a constituent part of the context.
260	///
261	/// Generally used when the context is a Frame-based chain.
262	// TODO XCMv4 inner should be `Compact<u32>`.
263	PalletInstance(u8),
264	/// A non-descript index within the context location.
265	///
266	/// Usage will vary widely owing to its generality.
267	///
268	/// NOTE: Try to avoid using this and instead use a more specific item.
269	GeneralIndex(#[codec(compact)] u128),
270	/// A nondescript array datum, 32 bytes, acting as a key within the context
271	/// location.
272	///
273	/// Usage will vary widely owing to its generality.
274	///
275	/// NOTE: Try to avoid using this and instead use a more specific item.
276	// Note this is implemented as an array with a length rather than using `BoundedVec` owing to
277	// the bound for `Copy`.
278	GeneralKey { length: u8, data: [u8; 32] },
279	/// The unambiguous child.
280	///
281	/// Not currently used except as a fallback when deriving context.
282	OnlyChild,
283	/// A pluralistic body existing within consensus.
284	///
285	/// Typical to be used to represent a governance origin of a chain, but could in principle be
286	/// used to represent things such as multisigs also.
287	Plurality { id: BodyId, part: BodyPart },
288	/// A global network capable of externalizing its own consensus. This is not generally
289	/// meaningful outside of the universal level.
290	GlobalConsensus(NetworkId),
291}
292
293impl From<NetworkId> for Junction {
294	fn from(n: NetworkId) -> Self {
295		Self::GlobalConsensus(n)
296	}
297}
298
299impl From<[u8; 32]> for Junction {
300	fn from(id: [u8; 32]) -> Self {
301		Self::AccountId32 { network: None, id }
302	}
303}
304
305impl From<BoundedVec<u8, ConstU32<32>>> for Junction {
306	fn from(key: BoundedVec<u8, ConstU32<32>>) -> Self {
307		key.as_bounded_slice().into()
308	}
309}
310
311impl<'a> From<BoundedSlice<'a, u8, ConstU32<32>>> for Junction {
312	fn from(key: BoundedSlice<'a, u8, ConstU32<32>>) -> Self {
313		let mut data = [0u8; 32];
314		data[..key.len()].copy_from_slice(&key[..]);
315		Self::GeneralKey { length: key.len() as u8, data }
316	}
317}
318
319impl<'a> TryFrom<&'a Junction> for BoundedSlice<'a, u8, ConstU32<32>> {
320	type Error = ();
321	fn try_from(key: &'a Junction) -> Result<Self, ()> {
322		match key {
323			Junction::GeneralKey { length, data } =>
324				BoundedSlice::try_from(&data[..data.len().min(*length as usize)]).map_err(|_| ()),
325			_ => Err(()),
326		}
327	}
328}
329
330impl From<[u8; 20]> for Junction {
331	fn from(key: [u8; 20]) -> Self {
332		Self::AccountKey20 { network: None, key }
333	}
334}
335
336impl From<u64> for Junction {
337	fn from(index: u64) -> Self {
338		Self::AccountIndex64 { network: None, index }
339	}
340}
341
342impl From<u128> for Junction {
343	fn from(id: u128) -> Self {
344		Self::GeneralIndex(id)
345	}
346}
347
348impl TryFrom<NewJunction> for Junction {
349	type Error = ();
350
351	fn try_from(value: NewJunction) -> Result<Self, Self::Error> {
352		use NewJunction::*;
353		Ok(match value {
354			Parachain(id) => Self::Parachain(id),
355			AccountId32 { network: maybe_network, id } =>
356				Self::AccountId32 { network: maybe_network.map(|network| network.into()), id },
357			AccountIndex64 { network: maybe_network, index } =>
358				Self::AccountIndex64 { network: maybe_network.map(|network| network.into()), index },
359			AccountKey20 { network: maybe_network, key } =>
360				Self::AccountKey20 { network: maybe_network.map(|network| network.into()), key },
361			PalletInstance(index) => Self::PalletInstance(index),
362			GeneralIndex(id) => Self::GeneralIndex(id),
363			GeneralKey { length, data } => Self::GeneralKey { length, data },
364			OnlyChild => Self::OnlyChild,
365			Plurality { id, part } => Self::Plurality { id, part },
366			GlobalConsensus(network) => Self::GlobalConsensus(network.into()),
367		})
368	}
369}
370
371impl Junction {
372	/// Convert `self` into a `MultiLocation` containing 0 parents.
373	///
374	/// Similar to `Into::into`, except that this method can be used in a const evaluation context.
375	pub const fn into_location(self) -> MultiLocation {
376		MultiLocation { parents: 0, interior: Junctions::X1(self) }
377	}
378
379	/// Convert `self` into a `MultiLocation` containing `n` parents.
380	///
381	/// Similar to `Self::into_location`, with the added ability to specify the number of parent
382	/// junctions.
383	pub const fn into_exterior(self, n: u8) -> MultiLocation {
384		MultiLocation { parents: n, interior: Junctions::X1(self) }
385	}
386
387	/// Convert `self` into a `VersionedLocation` containing 0 parents.
388	///
389	/// Similar to `Into::into`, except that this method can be used in a const evaluation context.
390	pub const fn into_versioned(self) -> VersionedLocation {
391		self.into_location().into_versioned()
392	}
393
394	/// Remove the `NetworkId` value.
395	pub fn remove_network_id(&mut self) {
396		use Junction::*;
397		match self {
398			AccountId32 { ref mut network, .. } |
399			AccountIndex64 { ref mut network, .. } |
400			AccountKey20 { ref mut network, .. } => *network = None,
401			_ => {},
402		}
403	}
404}