From 9b4844e85361d66bd7e51f3a974a571a682ef27c Mon Sep 17 00:00:00 2001
From: Gavin Wood <gavin@parity.io>
Date: Thu, 8 Apr 2021 20:58:06 +0200
Subject: [PATCH] Introduce plurality XCM locations (#2846)

* Introduce plurality XCM locations

* Add RelayedFrom
---
 polkadot/xcm/src/v0/junction.rs       | 62 +++++++++++++++++++++++----
 polkadot/xcm/src/v0/mod.rs            | 18 +++++++-
 polkadot/xcm/src/v0/multi_location.rs | 23 ++++++++++
 polkadot/xcm/xcm-executor/src/lib.rs  |  8 ++++
 4 files changed, 101 insertions(+), 10 deletions(-)

diff --git a/polkadot/xcm/src/v0/junction.rs b/polkadot/xcm/src/v0/junction.rs
index b5493cd31fe..fd0104a48fe 100644
--- a/polkadot/xcm/src/v0/junction.rs
+++ b/polkadot/xcm/src/v0/junction.rs
@@ -32,6 +32,41 @@ pub enum NetworkId {
 	Kusama,
 }
 
+/// An identifier of a pluralistic body.
+#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, Debug)]
+pub enum BodyId {
+	/// The only body in its context.
+	Unit,
+	/// A named body.
+	Named(Vec<u8>),
+	/// An indexed body.
+	// TODO: parity-scale-codec#262: Change to be a tuple.
+	Index { #[codec(compact)] id: u32 },
+	/// The unambiguous executive body (for Polkadot, this would be the Polkadot council).
+	Executive,
+	/// The unambiguous technical body (for Polkadot, this would be the Technical Committee).
+	Technical,
+	/// The unambiguous legislative body (for Polkadot, this could be considered the opinion of a majority of
+	/// lock-voters).
+	Legislative,
+	/// The unambiguous judicial body (this doesn't exist on Polkadot, but if it were to get a "grand oracle", it
+	/// may be considered as that).
+	Judicial,
+}
+
+/// A part of a pluralistic body.
+#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, Debug)]
+pub enum BodyPart {
+	/// The body's declaration, under whatever means it decides.
+	Voice,
+	/// A given number of members of the body.
+	Members { #[codec(compact)] count: u32 },
+	/// No less than the given proportion of members of the body.
+	AtLeastProportion { #[codec(compact)] nom: u32, #[codec(compact)] denom: u32 },
+	/// More than than the given proportion of members of the body.
+	MoreThanProportion { #[codec(compact)] nom: u32, #[codec(compact)] denom: u32 },
+}
+
 /// A single item in a path to describe the relative location of a consensus system.
 ///
 /// Each item assumes a pre-existing location as its context and is defined in terms of it.
@@ -85,21 +120,30 @@ pub enum Junction {
 	///
 	/// Not currently used except as a fallback when deriving ancestry.
 	OnlyChild,
+	/// A pluralistic body existing within consensus.
+	///
+	/// Typical to be used to represent a governance origin of a chain, but could in principle be used to represent
+	/// things such as multisigs also.
+	Plurality { id: BodyId, part: BodyPart },
 }
 
 impl Junction {
-	pub fn is_sub_consensus(&self) -> bool {
+	/// Returns true if this junction can be considered an interior part of its context. This is generally `true`,
+	/// except for the `Parent` item.
+	pub fn is_interior(&self) -> bool {
 		match self {
 			Junction::Parent => false,
 
-			Junction::Parachain { .. } |
-			Junction::AccountId32 { .. } |
-			Junction::AccountIndex64 { .. } |
-			Junction::AccountKey20 { .. } |
-			Junction::PalletInstance { .. } |
-			Junction::GeneralIndex { .. } |
-			Junction::GeneralKey(..) |
-			Junction::OnlyChild => true,
+			Junction::Parachain { .. }
+			| Junction::AccountId32 { .. }
+			| Junction::AccountIndex64 { .. }
+			| Junction::AccountKey20 { .. }
+			| Junction::PalletInstance { .. }
+			| Junction::GeneralIndex { .. }
+			| Junction::GeneralKey(..)
+			| Junction::OnlyChild
+			| Junction::Plurality { .. }
+			=> true,
 		}
 	}
 }
diff --git a/polkadot/xcm/src/v0/mod.rs b/polkadot/xcm/src/v0/mod.rs
index e2add536425..3beb0ee98e8 100644
--- a/polkadot/xcm/src/v0/mod.rs
+++ b/polkadot/xcm/src/v0/mod.rs
@@ -227,6 +227,20 @@ pub enum Xcm<Call> {
 		#[codec(compact)] sender: u32,
 		#[codec(compact)] recipient: u32,
 	},
+
+	/// A message to indicate that the embedded XCM is actually arriving on behalf of some consensus
+	/// location within the origin.
+	///
+	/// Safety: No concerns.
+	///
+	/// Kind: *Instruction*
+	///
+	/// Errors:
+	#[codec(index = 10)]
+	RelayedFrom {
+		who: MultiLocation,
+		message: alloc::boxed::Box<Xcm<Call>>,
+	},
 }
 
 impl<Call> From<Xcm<Call>> for VersionedXcm<Call> {
@@ -268,7 +282,9 @@ impl<Call> Xcm<Call> {
 			HrmpChannelClosing { initiator, sender, recipient}
 			=> HrmpChannelClosing { initiator, sender, recipient},
 			Transact { origin_type, require_weight_at_most, call}
-			=> Transact { origin_type, require_weight_at_most, call: call.into() }
+			=> Transact { origin_type, require_weight_at_most, call: call.into() },
+			RelayedFrom { who, message }
+			=> RelayedFrom { who, message: alloc::boxed::Box::new((*message).into()) },
 		}
 	}
 }
diff --git a/polkadot/xcm/src/v0/multi_location.rs b/polkadot/xcm/src/v0/multi_location.rs
index f2ac7f891e5..2dd448c745b 100644
--- a/polkadot/xcm/src/v0/multi_location.rs
+++ b/polkadot/xcm/src/v0/multi_location.rs
@@ -539,6 +539,23 @@ impl MultiLocation {
 		}
 	}
 
+	/// Mutate `self` so that it is suffixed with `prefix`. The correct normalised form is returned, removing any
+	/// internal `Parent`s.
+	///
+	/// Does not modify `self` and returns `Err` with `prefix` in case of overflow.
+	pub fn append_with(&mut self, suffix: MultiLocation) -> Result<(), MultiLocation> {
+		let mut prefix = suffix;
+		core::mem::swap(self, &mut prefix);
+		match self.prepend_with(prefix) {
+			Ok(()) => Ok(()),
+			Err(prefix) => {
+				let mut suffix = prefix;
+				core::mem::swap(self, &mut suffix);
+				Err(suffix)
+			}
+		}
+	}
+
 	/// Mutate `self` so that it is prefixed with `prefix`. The correct normalised form is returned, removing any
 	/// internal `Parent`s.
 	///
@@ -566,6 +583,12 @@ impl MultiLocation {
 		}
 		Ok(())
 	}
+
+	/// Returns true iff `self` is an interior location. For this it may not contain any `Junction`s for which
+	/// `Junction::is_interior` returns `false`. This
+	pub fn is_interior(&self) -> bool {
+		self.iter().all(Junction::is_interior)
+	}
 }
 
 impl From<MultiLocation> for VersionedMultiLocation {
diff --git a/polkadot/xcm/xcm-executor/src/lib.rs b/polkadot/xcm/xcm-executor/src/lib.rs
index 885b7a78c47..143ab111383 100644
--- a/polkadot/xcm/xcm-executor/src/lib.rs
+++ b/polkadot/xcm/xcm-executor/src/lib.rs
@@ -182,6 +182,14 @@ impl<Config: config::Config> XcmExecutor<Config> {
 				Config::ResponseHandler::on_response(origin, query_id, response);
 				None
 			}
+			(origin, Xcm::RelayedFrom { who, message }) => {
+				ensure!(who.is_interior(), XcmError::EscalationOfPrivilege);
+				let mut origin = origin;
+				origin.append_with(who).map_err(|_| XcmError::MultiLocationFull)?;
+				let surplus = Self::do_execute_xcm(origin, top_level, *message, weight_credit, None, trader)?;
+				total_surplus = total_surplus.saturating_add(surplus);
+				None
+			}
 			_ => Err(XcmError::UnhandledXcmMessage)?,	// Unhandled XCM message.
 		};
 
-- 
GitLab