referrerpolicy=no-referrer-when-downgrade

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