Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.

Commit 19f6665

Browse files
authored
Remove BoundedVec half-impls in xcm (#6636)
* Replace sp-core dependency with more primitive crates * Remove BoundedVec half-impls in xcm * Fixes * Bump bounded-collections * Address review comments * Bump bounded-collections * Fix benchmarks * Fixes * Fixes * cargo fmt * Fix tests * Update url * Bump url to 2.3.1 * Bump anyhow * Use bounded-collections in pallet-xcm * Update substrate
1 parent d528437 commit 19f6665

File tree

13 files changed

+233
-264
lines changed

13 files changed

+233
-264
lines changed

Cargo.lock

Lines changed: 190 additions & 189 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

node/zombienet-backchannel/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ edition.workspace = true
1010

1111
[dependencies]
1212
tokio = { version = "1.24.2", default-features = false, features = ["macros", "net", "rt-multi-thread", "sync"] }
13-
url = "2.0.0"
13+
url = "2.3.1"
1414
tokio-tungstenite = "0.17"
1515
futures-util = "0.3.23"
1616
lazy_static = "1.4.0"

xcm/Cargo.toml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,12 @@ authors.workspace = true
66
edition.workspace = true
77

88
[dependencies]
9+
bounded-collections = { version = "0.1.4", default-features = false }
910
derivative = { version = "2.2.0", default-features = false, features = [ "use_core" ] }
1011
impl-trait-for-tuples = "0.2.2"
1112
log = { version = "0.4.17", default-features = false }
1213
parity-scale-codec = { version = "3.3.0", default-features = false, features = [ "derive", "max-encoded-len" ] }
1314
scale-info = { version = "2.1.2", default-features = false, features = ["derive"] }
14-
sp-core = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
1515
sp-weights = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
1616
serde = { version = "1.0.136", optional = true, features = ["derive"] }
1717
xcm-procedural = { path = "procedural" }
@@ -23,9 +23,9 @@ sp-io = { git = "https://github.com/paritytech/substrate", branch = "master" }
2323
default = ["std"]
2424
wasm-api = []
2525
std = [
26+
"bounded-collections/std",
2627
"parity-scale-codec/std",
2728
"scale-info/std",
2829
"serde",
29-
"sp-core/std",
3030
"sp-weights/std",
3131
]

xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ use frame_benchmarking::{benchmarks, BenchmarkError};
2121
use frame_support::dispatch::GetDispatchInfo;
2222
use sp_std::vec;
2323
use xcm::{
24-
latest::{prelude::*, MaybeErrorCode, Weight},
24+
latest::{prelude::*, MaxDispatchErrorLen, MaybeErrorCode, Weight},
2525
DoubleEncoded,
2626
};
2727
use xcm_executor::{ExecutorError, FeesMode};
@@ -360,9 +360,9 @@ benchmarks! {
360360

361361
expect_transact_status {
362362
let mut executor = new_executor::<T>(Default::default());
363-
// 1024 is an overestimate but should be good enough until we have `max_encoded_len`.
364-
// Eventually it should be replaced by `DispatchError::max_encoded_len()`.
365-
let worst_error = || MaybeErrorCode::Error(vec![0; 1024]);
363+
let worst_error = || -> MaybeErrorCode {
364+
vec![0; MaxDispatchErrorLen::get() as usize].into()
365+
};
366366
executor.set_transact_status(worst_error());
367367

368368
let instruction = Instruction::ExpectTransactStatus(worst_error());
@@ -430,7 +430,7 @@ benchmarks! {
430430

431431
clear_transact_status {
432432
let mut executor = new_executor::<T>(Default::default());
433-
executor.set_transact_status(MaybeErrorCode::Error(b"MyError".to_vec()));
433+
executor.set_transact_status(b"MyError".to_vec().into());
434434

435435
let instruction = Instruction::ClearTransactStatus;
436436
let xcm = Xcm(vec![instruction]);

xcm/pallet-xcm/Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ version.workspace = true
66

77

88
[dependencies]
9+
bounded-collections = { version = "0.1.4", default-features = false }
910
codec = { package = "parity-scale-codec", version = "3.3.0", default-features = false, features = ["derive"] }
1011
scale-info = { version = "2.1.2", default-features = false, features = ["derive"] }
1112
serde = { version = "1.0.137", optional = true, features = ["derive"] }
@@ -31,6 +32,7 @@ xcm-builder = { path = "../xcm-builder" }
3132
[features]
3233
default = ["std"]
3334
std = [
35+
"bounded-collections/std",
3436
"codec/std",
3537
"scale-info/std",
3638
"serde",

xcm/pallet-xcm/src/benchmarking.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,10 @@
1515
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
1616

1717
use super::*;
18+
use bounded_collections::{ConstU32, WeakBoundedVec};
1819
use frame_benchmarking::{benchmarks, BenchmarkError, BenchmarkResult};
1920
use frame_support::weights::Weight;
2021
use frame_system::RawOrigin;
21-
use sp_core::{bounded::WeakBoundedVec, ConstU32};
2222
use sp_std::prelude::*;
2323
use xcm::{latest::prelude::*, v2};
2424

xcm/src/v2/junction.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,9 @@
1818
1919
use super::{BodyId, BodyPart, Junctions, MultiLocation, NetworkId};
2020
use crate::v3::Junction as NewJunction;
21+
use bounded_collections::{ConstU32, WeakBoundedVec};
2122
use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
2223
use scale_info::TypeInfo;
23-
use sp_core::{bounded::WeakBoundedVec, ConstU32};
2424

2525
/// A single item in a path to describe the relative location of a consensus system.
2626
///

xcm/src/v2/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,11 +59,11 @@ use super::{
5959
DoubleEncoded, GetWeight,
6060
};
6161
use alloc::{vec, vec::Vec};
62+
use bounded_collections::{ConstU32, WeakBoundedVec};
6263
use core::{fmt::Debug, result};
6364
use derivative::Derivative;
6465
use parity_scale_codec::{self, Decode, Encode, MaxEncodedLen};
6566
use scale_info::TypeInfo;
66-
use sp_core::{bounded::WeakBoundedVec, ConstU32};
6767

6868
mod junction;
6969
mod multiasset;

xcm/src/v3/mod.rs

Lines changed: 23 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ use super::v2::{
2222
};
2323
use crate::{DoubleEncoded, GetWeight};
2424
use alloc::{vec, vec::Vec};
25+
use bounded_collections::{parameter_types, BoundedVec};
2526
use core::{
2627
convert::{TryFrom, TryInto},
2728
fmt::Debug,
@@ -200,14 +201,20 @@ pub mod prelude {
200201
}
201202
}
202203

203-
#[derive(Clone, Eq, PartialEq, Encode, Decode, Debug, TypeInfo)]
204+
parameter_types! {
205+
pub MaxPalletNameLen: u32 = 48;
206+
/// Maximum size of the encoded error code coming from a `Dispatch` result, used for
207+
/// `MaybeErrorCode`. This is not (yet) enforced, so it's just an indication of expectation.
208+
pub MaxDispatchErrorLen: u32 = 128;
209+
pub MaxPalletsInfo: u32 = 64;
210+
}
211+
212+
#[derive(Clone, Eq, PartialEq, Encode, Decode, Debug, TypeInfo, MaxEncodedLen)]
204213
pub struct PalletInfo {
205214
#[codec(compact)]
206215
index: u32,
207-
// TODO: Change to `BoundedVec` so `MaxEncodedLen` derive will work.
208-
name: Vec<u8>,
209-
// TODO: Change to `BoundedVec` so `MaxEncodedLen` derive will work.
210-
module_name: Vec<u8>,
216+
name: BoundedVec<u8, MaxPalletNameLen>,
217+
module_name: BoundedVec<u8, MaxPalletNameLen>,
211218
#[codec(compact)]
212219
major: u32,
213220
#[codec(compact)]
@@ -216,8 +223,6 @@ pub struct PalletInfo {
216223
patch: u32,
217224
}
218225

219-
const MAX_NAME_LEN: usize = 48;
220-
221226
impl PalletInfo {
222227
pub fn new(
223228
index: u32,
@@ -227,44 +232,25 @@ impl PalletInfo {
227232
minor: u32,
228233
patch: u32,
229234
) -> result::Result<Self, Error> {
230-
if name.len() > MAX_NAME_LEN || module_name.len() > MAX_NAME_LEN {
231-
return Err(Error::Overflow)
232-
}
233-
Ok(Self { index, name, module_name, major, minor, patch })
234-
}
235-
}
235+
let name = BoundedVec::try_from(name).map_err(|_| Error::Overflow)?;
236+
let module_name = BoundedVec::try_from(module_name).map_err(|_| Error::Overflow)?;
236237

237-
impl MaxEncodedLen for PalletInfo {
238-
fn max_encoded_len() -> usize {
239-
parity_scale_codec::Compact::<u32>::max_encoded_len() * 4 + (MAX_NAME_LEN + 1) * 2
238+
Ok(Self { index, name, module_name, major, minor, patch })
240239
}
241240
}
242241

243-
#[derive(Clone, Eq, PartialEq, Encode, Decode, Debug, TypeInfo)]
242+
#[derive(Clone, Eq, PartialEq, Encode, Decode, Debug, TypeInfo, MaxEncodedLen)]
244243
pub enum MaybeErrorCode {
245244
Success,
246-
// TODO: Change to a `BoundedVec` so that deriving `MaxEncodedLen` works.
247-
Error(Vec<u8>),
248-
TruncatedError(Vec<u8>),
249-
}
250-
251-
/// Maximum size of the encoded error code coming from a `Dispatch` result, used for
252-
/// `MaybeErrorCode`. This is not (yet) enforced, so it's just an indication of expectation.
253-
const MAX_DISPATCH_ERROR_LEN: usize = 128;
254-
255-
impl MaxEncodedLen for MaybeErrorCode {
256-
fn max_encoded_len() -> usize {
257-
MAX_DISPATCH_ERROR_LEN + 3
258-
}
245+
Error(BoundedVec<u8, MaxDispatchErrorLen>),
246+
TruncatedError(BoundedVec<u8, MaxDispatchErrorLen>),
259247
}
260248

261249
impl From<Vec<u8>> for MaybeErrorCode {
262-
fn from(mut v: Vec<u8>) -> Self {
263-
if v.len() <= MAX_DISPATCH_ERROR_LEN {
264-
MaybeErrorCode::Error(v)
265-
} else {
266-
v.truncate(MAX_DISPATCH_ERROR_LEN);
267-
MaybeErrorCode::TruncatedError(v)
250+
fn from(v: Vec<u8>) -> Self {
251+
match BoundedVec::try_from(v) {
252+
Ok(error) => MaybeErrorCode::Error(error),
253+
Err(error) => MaybeErrorCode::TruncatedError(BoundedVec::truncate_from(error)),
268254
}
269255
}
270256
}
@@ -275,26 +261,6 @@ impl Default for MaybeErrorCode {
275261
}
276262
}
277263

278-
/// Maximum number of pallets which we expect to be returned in `PalletsInfo`.
279-
const MAX_PALLETS_INFO_LEN: usize = 64;
280-
281-
#[derive(Clone, Eq, PartialEq, Encode, Decode, Debug, TypeInfo)]
282-
pub struct VecPalletInfo(Vec<PalletInfo>);
283-
impl TryFrom<Vec<PalletInfo>> for VecPalletInfo {
284-
type Error = Error;
285-
fn try_from(v: Vec<PalletInfo>) -> result::Result<Self, Error> {
286-
if v.len() > MAX_PALLETS_INFO_LEN {
287-
return Err(Error::Overflow)
288-
}
289-
Ok(VecPalletInfo(v))
290-
}
291-
}
292-
impl MaxEncodedLen for VecPalletInfo {
293-
fn max_encoded_len() -> usize {
294-
PalletInfo::max_encoded_len() * MAX_PALLETS_INFO_LEN
295-
}
296-
}
297-
298264
/// Response data to a query.
299265
#[derive(Clone, Eq, PartialEq, Encode, Decode, Debug, TypeInfo, MaxEncodedLen)]
300266
pub enum Response {
@@ -307,8 +273,7 @@ pub enum Response {
307273
/// An XCM version.
308274
Version(super::Version),
309275
/// The index, instance name, pallet name and version of some pallets.
310-
// TODO: Change to a `BoundedVec` so that deriving `MaxEncodedLen` works.
311-
PalletsInfo(VecPalletInfo),
276+
PalletsInfo(BoundedVec<PalletInfo, MaxPalletsInfo>),
312277
/// The status of a dispatch attempt using `Transact`.
313278
DispatchResult(MaybeErrorCode),
314279
}

xcm/xcm-builder/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ log = { version = "0.4.17", default-features = false }
2424
polkadot-parachain = { path = "../../parachain", default-features = false }
2525

2626
[dev-dependencies]
27-
sp-core = { git = "https://github.com/paritytech/substrate", branch = "master" }
27+
primitive-types = "0.12.1"
2828
pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "master" }
2929
pallet-xcm = { path = "../pallet-xcm" }
3030
polkadot-runtime-parachains = { path = "../../runtime/parachains" }

xcm/xcm-builder/src/tests/transacting.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,7 @@ fn report_failed_transact_status_should_work() {
147147
let r = XcmExecutor::<TestConfig>::execute_xcm(Parent, message, hash, weight_limit);
148148
assert_eq!(r, Outcome::Complete(Weight::from_parts(70, 70)));
149149
let expected_msg = Xcm(vec![QueryResponse {
150-
response: Response::DispatchResult(MaybeErrorCode::Error(vec![2])),
150+
response: Response::DispatchResult(vec![2].into()),
151151
query_id: 42,
152152
max_weight: Weight::from_parts(5000, 5000),
153153
querier: Some(Here.into()),
@@ -197,7 +197,7 @@ fn expect_failed_transact_status_should_work() {
197197
require_weight_at_most: Weight::from_parts(50, 50),
198198
call: TestCall::OnlyRoot(Weight::from_parts(50, 50), None).encode().into(),
199199
},
200-
ExpectTransactStatus(MaybeErrorCode::Error(vec![2])),
200+
ExpectTransactStatus(vec![2].into()),
201201
]);
202202
let hash = fake_message_hash(&message);
203203
let weight_limit = Weight::from_parts(70, 70);
@@ -210,7 +210,7 @@ fn expect_failed_transact_status_should_work() {
210210
require_weight_at_most: Weight::from_parts(50, 50),
211211
call: TestCall::Any(Weight::from_parts(50, 50), None).encode().into(),
212212
},
213-
ExpectTransactStatus(MaybeErrorCode::Error(vec![2])),
213+
ExpectTransactStatus(vec![2].into()),
214214
]);
215215
let hash = fake_message_hash(&message);
216216
let weight_limit = Weight::from_parts(70, 70);

xcm/xcm-builder/tests/mock/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ use frame_support::{
2020
weights::Weight,
2121
};
2222
use parity_scale_codec::Encode;
23-
use sp_core::H256;
23+
use primitive_types::H256;
2424
use sp_runtime::{testing::Header, traits::IdentityLookup, AccountId32};
2525
use sp_std::cell::RefCell;
2626

xcm/xcm-executor/src/lib.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -773,7 +773,8 @@ impl<Config: config::Config> XcmExecutor<Config> {
773773
})
774774
.collect::<Result<Vec<_>, XcmError>>()?;
775775
let QueryResponseInfo { destination, query_id, max_weight } = response_info;
776-
let response = Response::PalletsInfo(pallets.try_into()?);
776+
let response =
777+
Response::PalletsInfo(pallets.try_into().map_err(|_| XcmError::Overflow)?);
777778
let querier = Self::to_querier(self.cloned_origin(), &destination)?;
778779
let instruction = QueryResponse { query_id, response, max_weight, querier };
779780
let message = Xcm(vec![instruction]);

0 commit comments

Comments
 (0)