conversion.rs 6.86 KB
Newer Older
Gavin Wood's avatar
Gavin Wood committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Copyright 2020 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.

// Polkadot is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Polkadot is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Polkadot.  If not, see <http://www.gnu.org/licenses/>.

Shawn Tabrizi's avatar
Shawn Tabrizi committed
17
18
use parity_scale_codec::{Decode, Encode};
use sp_std::{borrow::Borrow, convert::TryFrom, prelude::*, result::Result};
Gavin Wood's avatar
Gavin Wood committed
19
use xcm::latest::{MultiLocation, OriginKind};
Gavin Wood's avatar
Gavin Wood committed
20
21

/// Generic third-party conversion trait. Use this when you don't want to force the user to use default
Denis_P's avatar
Denis_P committed
22
/// implementations of `From` and `Into` for the types you wish to convert between.
Gavin Wood's avatar
Gavin Wood committed
23
24
25
26
///
/// One of `convert`/`convert_ref` and `reverse`/`reverse_ref` MUST be implemented. If possible, implement
/// `convert_ref`, since this will never result in a clone. Use `convert` when you definitely need to consume
/// the source value.
Alexander Popiak's avatar
Alexander Popiak committed
27
28
29
///
/// Can be amalgamated into tuples. If any of the tuple elements converts into `Ok(_)` it short circuits. Otherwise returns
/// the `Err(_)` of the last failing conversion (or `Err(())` for ref conversions).
Gavin Wood's avatar
Gavin Wood committed
30
31
pub trait Convert<A: Clone, B: Clone> {
	/// Convert from `value` (of type `A`) into an equivalent value of type `B`, `Err` if not possible.
Shawn Tabrizi's avatar
Shawn Tabrizi committed
32
33
34
	fn convert(value: A) -> Result<B, A> {
		Self::convert_ref(&value).map_err(|_| value)
	}
Gavin Wood's avatar
Gavin Wood committed
35
36
37
38
	fn convert_ref(value: impl Borrow<A>) -> Result<B, ()> {
		Self::convert(value.borrow().clone()).map_err(|_| ())
	}
	/// Convert from `value` (of type `B`) into an equivalent value of type `A`, `Err` if not possible.
Shawn Tabrizi's avatar
Shawn Tabrizi committed
39
40
41
	fn reverse(value: B) -> Result<A, B> {
		Self::reverse_ref(&value).map_err(|_| value)
	}
Gavin Wood's avatar
Gavin Wood committed
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
	fn reverse_ref(value: impl Borrow<B>) -> Result<A, ()> {
		Self::reverse(value.borrow().clone()).map_err(|_| ())
	}
}

#[impl_trait_for_tuples::impl_for_tuples(30)]
impl<A: Clone, B: Clone> Convert<A, B> for Tuple {
	fn convert(value: A) -> Result<B, A> {
		for_tuples!( #(
			let value = match Tuple::convert(value) {
				Ok(result) => return Ok(result),
				Err(v) => v,
			};
		)* );
		Err(value)
	}
	fn reverse(value: B) -> Result<A, B> {
		for_tuples!( #(
			let value = match Tuple::reverse(value) {
				Ok(result) => return Ok(result),
				Err(v) => v,
			};
		)* );
		Err(value)
	}
	fn convert_ref(value: impl Borrow<A>) -> Result<B, ()> {
		let value = value.borrow();
		for_tuples!( #(
			match Tuple::convert_ref(value) {
				Ok(result) => return Ok(result),
				Err(_) => (),
			}
		)* );
		Err(())
	}
	fn reverse_ref(value: impl Borrow<B>) -> Result<A, ()> {
		let value = value.borrow();
		for_tuples!( #(
			match Tuple::reverse_ref(value.clone()) {
				Ok(result) => return Ok(result),
				Err(_) => (),
			}
		)* );
		Err(())
	}
}

/// Simple pass-through which implements `BytesConversion` while not doing any conversion.
pub struct Identity;
impl<T: Clone> Convert<T, T> for Identity {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
92
93
94
95
96
97
	fn convert(value: T) -> Result<T, T> {
		Ok(value)
	}
	fn reverse(value: T) -> Result<T, T> {
		Ok(value)
	}
Gavin Wood's avatar
Gavin Wood committed
98
99
100
101
}

/// Implementation of `Convert` trait using `TryFrom`.
pub struct JustTry;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
102
103
104
impl<Source: TryFrom<Dest> + Clone, Dest: TryFrom<Source> + Clone> Convert<Source, Dest>
	for JustTry
{
Gavin Wood's avatar
Gavin Wood committed
105
106
107
108
109
110
111
112
113
114
115
	fn convert(value: Source) -> Result<Dest, Source> {
		Dest::try_from(value.clone()).map_err(|_| value)
	}
	fn reverse(value: Dest) -> Result<Source, Dest> {
		Source::try_from(value.clone()).map_err(|_| value)
	}
}

/// Implementation of `Convert<_, Vec<u8>>` using the parity scale codec.
pub struct Encoded;
impl<T: Clone + Encode + Decode> Convert<T, Vec<u8>> for Encoded {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
116
117
118
	fn convert_ref(value: impl Borrow<T>) -> Result<Vec<u8>, ()> {
		Ok(value.borrow().encode())
	}
Gavin Wood's avatar
Gavin Wood committed
119
120
121
122
123
124
125
126
127
128
129
	fn reverse_ref(bytes: impl Borrow<Vec<u8>>) -> Result<T, ()> {
		T::decode(&mut &bytes.borrow()[..]).map_err(|_| ())
	}
}

/// Implementation of `Convert<Vec<u8>, _>` using the parity scale codec.
pub struct Decoded;
impl<T: Clone + Encode + Decode> Convert<Vec<u8>, T> for Decoded {
	fn convert_ref(bytes: impl Borrow<Vec<u8>>) -> Result<T, ()> {
		T::decode(&mut &bytes.borrow()[..]).map_err(|_| ())
	}
Shawn Tabrizi's avatar
Shawn Tabrizi committed
130
131
132
	fn reverse_ref(value: impl Borrow<T>) -> Result<Vec<u8>, ()> {
		Ok(value.borrow().encode())
	}
Gavin Wood's avatar
Gavin Wood committed
133
134
}

Denis_P's avatar
Denis_P committed
135
/// A converter `trait` for origin types.
Alexander Popiak's avatar
Alexander Popiak committed
136
137
138
139
140
141
///
/// Can be amalgamated into tuples. If any of the tuple elements returns `Ok(_)`, it short circuits. Else, the `Err(_)`
/// of the last tuple item is returned. Each intermediate `Err(_)` might return a different `origin` of type `Origin`
/// which is passed to the next convert item.
///
/// ```rust
142
/// # use xcm::latest::{MultiLocation, Junctions, Junction, OriginKind};
Alexander Popiak's avatar
Alexander Popiak committed
143
144
145
146
147
/// # use xcm_executor::traits::ConvertOrigin;
/// // A convertor that will bump the para id and pass it to the next one.
/// struct BumpParaId;
/// impl ConvertOrigin<u32> for BumpParaId {
/// 	fn convert_origin(origin: MultiLocation, _: OriginKind) -> Result<u32, MultiLocation> {
148
149
150
/// 		match origin.interior() {
/// 			Junctions::X1(Junction::Parachain(id)) if origin.parent_count() == 0 => {
/// 				Err(Junctions::X1(Junction::Parachain(id + 1)).into())
Alexander Popiak's avatar
Alexander Popiak committed
151
152
153
154
155
156
157
158
159
/// 			}
/// 			_ => unreachable!()
/// 		}
/// 	}
/// }
///
/// struct AcceptPara7;
/// impl ConvertOrigin<u32> for AcceptPara7 {
/// 	fn convert_origin(origin: MultiLocation, _: OriginKind) -> Result<u32, MultiLocation> {
160
161
/// 		match origin.interior() {
/// 			Junctions::X1(Junction::Parachain(id)) if id == &7 && origin.parent_count() == 0 => {
Alexander Popiak's avatar
Alexander Popiak committed
162
163
164
165
166
167
168
/// 				Ok(7)
/// 			}
/// 			_ => Err(origin)
/// 		}
/// 	}
/// }
/// # fn main() {
169
/// let origin: MultiLocation = Junctions::X1(Junction::Parachain(6)).into();
Alexander Popiak's avatar
Alexander Popiak committed
170
171
172
173
174
175
/// assert!(
/// 	<(BumpParaId, AcceptPara7) as ConvertOrigin<u32>>::convert_origin(origin, OriginKind::Native)
/// 		.is_ok()
/// );
/// # }
/// ```
Gavin Wood's avatar
Gavin Wood committed
176
pub trait ConvertOrigin<Origin> {
Alexander Popiak's avatar
Alexander Popiak committed
177
	/// Attempt to convert `origin` to the generic `Origin` whilst consuming it.
Gavin Wood's avatar
Gavin Wood committed
178
179
180
181
182
183
184
	fn convert_origin(origin: MultiLocation, kind: OriginKind) -> Result<Origin, MultiLocation>;
}

#[impl_trait_for_tuples::impl_for_tuples(30)]
impl<O> ConvertOrigin<O> for Tuple {
	fn convert_origin(origin: MultiLocation, kind: OriginKind) -> Result<O, MultiLocation> {
		for_tuples!( #(
Alexander Popiak's avatar
Alexander Popiak committed
185
186
187
188
			let origin = match Tuple::convert_origin(origin, kind) {
				Err(o) => o,
				r => return r
			};
Gavin Wood's avatar
Gavin Wood committed
189
		)* );
Alexander Popiak's avatar
Alexander Popiak committed
190
191
192
193
194
195
		log::trace!(
			target: "xcm::convert_origin",
			"could not convert: origin: {:?}, kind: {:?}",
			origin,
			kind,
		);
Gavin Wood's avatar
Gavin Wood committed
196
197
198
199
		Err(origin)
	}
}

Alexander Popiak's avatar
Alexander Popiak committed
200
201
/// Means of inverting a location: given a location which describes a `target` interpreted from the
/// `source`, this will provide the corresponding location which describes the `source`.
Gavin Wood's avatar
Gavin Wood committed
202
pub trait InvertLocation {
203
	fn invert_location(l: &MultiLocation) -> Result<MultiLocation, ()>;
Gavin Wood's avatar
Gavin Wood committed
204
}