referrerpolicy=no-referrer-when-downgrade

staging_xcm/v5/
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::v4::{BodyId, BodyPart};
21use crate::{
22	v4::{Junction as OldJunction, NetworkId as OldNetworkId},
23	VersionedLocation,
24};
25use bounded_collections::{BoundedSlice, BoundedVec, ConstU32};
26use codec::{self, Decode, DecodeWithMemTracking, Encode, MaxEncodedLen};
27use hex_literal::hex;
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
107/// The genesis hash of the Westend testnet. Used to identify it.
108pub const WESTEND_GENESIS_HASH: [u8; 32] =
109	hex!["e143f23803ac50e8f6f8e62695d1ce9e4e1d68aa36c1cd2cfd15340213f3423e"];
110
111/// The genesis hash of the Rococo testnet. Used to identify it.
112pub const ROCOCO_GENESIS_HASH: [u8; 32] =
113	hex!["6408de7737c59c238890533af25896a2c20608d8b380bb01029acb392781063e"];
114
115/// Dummy genesis hash used instead of defunct networks like Wococo (and soon Rococo).
116pub const DUMMY_GENESIS_HASH: [u8; 32] = [0; 32];
117
118/// A global identifier of a data structure existing within consensus.
119///
120/// Maintenance note: Networks with global consensus and which are practically bridgeable within the
121/// Polkadot ecosystem are given preference over explicit naming in this enumeration.
122#[derive(
123	Copy,
124	Clone,
125	Eq,
126	PartialEq,
127	Ord,
128	PartialOrd,
129	Encode,
130	Decode,
131	DecodeWithMemTracking,
132	Debug,
133	TypeInfo,
134	MaxEncodedLen,
135	Serialize,
136	Deserialize,
137)]
138pub enum NetworkId {
139	/// Network specified by the first 32 bytes of its genesis block.
140	ByGenesis([u8; 32]),
141	/// Network defined by the first 32-bytes of the hash and number of some block it contains.
142	ByFork { block_number: u64, block_hash: [u8; 32] },
143	/// The Polkadot mainnet Relay-chain.
144	Polkadot,
145	/// The Kusama canary-net Relay-chain.
146	Kusama,
147	/// An Ethereum network specified by its chain ID.
148	#[codec(index = 7)]
149	Ethereum {
150		/// The EIP-155 chain ID.
151		#[codec(compact)]
152		chain_id: u64,
153	},
154	/// The Bitcoin network, including hard-forks supported by Bitcoin Core development team.
155	#[codec(index = 8)]
156	BitcoinCore,
157	/// The Bitcoin network, including hard-forks supported by Bitcoin Cash developers.
158	#[codec(index = 9)]
159	BitcoinCash,
160	/// The Polkadot Bulletin chain.
161	#[codec(index = 10)]
162	PolkadotBulletin,
163}
164
165impl From<OldNetworkId> for Option<NetworkId> {
166	fn from(old: OldNetworkId) -> Self {
167		Some(NetworkId::from(old))
168	}
169}
170
171impl From<OldNetworkId> for NetworkId {
172	fn from(old: OldNetworkId) -> Self {
173		use OldNetworkId::*;
174		match old {
175			ByGenesis(hash) => Self::ByGenesis(hash),
176			ByFork { block_number, block_hash } => Self::ByFork { block_number, block_hash },
177			Polkadot => Self::Polkadot,
178			Kusama => Self::Kusama,
179			Westend => Self::ByGenesis(WESTEND_GENESIS_HASH),
180			Rococo => Self::ByGenesis(ROCOCO_GENESIS_HASH),
181			Wococo => Self::ByGenesis(DUMMY_GENESIS_HASH),
182			Ethereum { chain_id } => Self::Ethereum { chain_id },
183			BitcoinCore => Self::BitcoinCore,
184			BitcoinCash => Self::BitcoinCash,
185			PolkadotBulletin => Self::PolkadotBulletin,
186		}
187	}
188}
189
190impl From<NetworkId> for Junction {
191	fn from(n: NetworkId) -> Self {
192		Self::GlobalConsensus(n)
193	}
194}
195
196impl From<[u8; 32]> for Junction {
197	fn from(id: [u8; 32]) -> Self {
198		Self::AccountId32 { network: None, id }
199	}
200}
201
202impl From<BoundedVec<u8, ConstU32<32>>> for Junction {
203	fn from(key: BoundedVec<u8, ConstU32<32>>) -> Self {
204		key.as_bounded_slice().into()
205	}
206}
207
208impl<'a> From<BoundedSlice<'a, u8, ConstU32<32>>> for Junction {
209	fn from(key: BoundedSlice<'a, u8, ConstU32<32>>) -> Self {
210		let mut data = [0u8; 32];
211		data[..key.len()].copy_from_slice(&key[..]);
212		Self::GeneralKey { length: key.len() as u8, data }
213	}
214}
215
216impl<'a> TryFrom<&'a Junction> for BoundedSlice<'a, u8, ConstU32<32>> {
217	type Error = ();
218	fn try_from(key: &'a Junction) -> Result<Self, ()> {
219		match key {
220			Junction::GeneralKey { length, data } =>
221				BoundedSlice::try_from(&data[..data.len().min(*length as usize)]).map_err(|_| ()),
222			_ => Err(()),
223		}
224	}
225}
226
227impl From<[u8; 20]> for Junction {
228	fn from(key: [u8; 20]) -> Self {
229		Self::AccountKey20 { network: None, key }
230	}
231}
232
233impl From<u64> for Junction {
234	fn from(index: u64) -> Self {
235		Self::AccountIndex64 { network: None, index }
236	}
237}
238
239impl From<u128> for Junction {
240	fn from(id: u128) -> Self {
241		Self::GeneralIndex(id)
242	}
243}
244
245impl TryFrom<OldJunction> for Junction {
246	type Error = ();
247	fn try_from(value: OldJunction) -> Result<Self, ()> {
248		use OldJunction::*;
249		Ok(match value {
250			Parachain(id) => Self::Parachain(id),
251			AccountId32 { network: maybe_network, id } =>
252				Self::AccountId32 { network: maybe_network.map(|network| network.into()), id },
253			AccountIndex64 { network: maybe_network, index } =>
254				Self::AccountIndex64 { network: maybe_network.map(|network| network.into()), index },
255			AccountKey20 { network: maybe_network, key } =>
256				Self::AccountKey20 { network: maybe_network.map(|network| network.into()), key },
257			PalletInstance(index) => Self::PalletInstance(index),
258			GeneralIndex(id) => Self::GeneralIndex(id),
259			GeneralKey { length, data } => Self::GeneralKey { length, data },
260			OnlyChild => Self::OnlyChild,
261			Plurality { id, part } => Self::Plurality { id, part },
262			GlobalConsensus(network) => Self::GlobalConsensus(network.into()),
263		})
264	}
265}
266
267impl Junction {
268	/// Convert `self` into a `Location` containing 0 parents.
269	///
270	/// Similar to `Into::into`, except that this method can be used in a const evaluation context.
271	pub fn into_location(self) -> Location {
272		Location::new(0, [self])
273	}
274
275	/// Convert `self` into a `Location` containing `n` parents.
276	///
277	/// Similar to `Self::into_location`, with the added ability to specify the number of parent
278	/// junctions.
279	pub fn into_exterior(self, n: u8) -> Location {
280		Location::new(n, [self])
281	}
282
283	/// Convert `self` into a `VersionedLocation` containing 0 parents.
284	///
285	/// Similar to `Into::into`, except that this method can be used in a const evaluation context.
286	pub fn into_versioned(self) -> VersionedLocation {
287		self.into_location().into_versioned()
288	}
289
290	/// Remove the `NetworkId` value.
291	pub fn remove_network_id(&mut self) {
292		use Junction::*;
293		match self {
294			AccountId32 { ref mut network, .. } |
295			AccountIndex64 { ref mut network, .. } |
296			AccountKey20 { ref mut network, .. } => *network = None,
297			_ => {},
298		}
299	}
300}
301
302#[cfg(test)]
303mod tests {
304	use super::*;
305	use alloc::vec;
306
307	#[test]
308	fn junction_round_trip_works() {
309		let j = Junction::GeneralKey { length: 32, data: [1u8; 32] };
310		let k = Junction::try_from(OldJunction::try_from(j).unwrap()).unwrap();
311		assert_eq!(j, k);
312
313		let j = OldJunction::GeneralKey { length: 32, data: [1u8; 32] };
314		let k = OldJunction::try_from(Junction::try_from(j).unwrap()).unwrap();
315		assert_eq!(j, k);
316
317		let j = Junction::from(BoundedVec::try_from(vec![1u8, 2, 3, 4]).unwrap());
318		let k = Junction::try_from(OldJunction::try_from(j).unwrap()).unwrap();
319		assert_eq!(j, k);
320		let s: BoundedSlice<_, _> = (&k).try_into().unwrap();
321		assert_eq!(s, &[1u8, 2, 3, 4][..]);
322
323		let j = OldJunction::GeneralKey { length: 32, data: [1u8; 32] };
324		let k = OldJunction::try_from(Junction::try_from(j).unwrap()).unwrap();
325		assert_eq!(j, k);
326	}
327}