Skip to content

Commit

Permalink
Split out xp runtime (paritytech#169)
Browse files Browse the repository at this point in the history
* Split out xp-runtime

* Commit xp-runtime

* Move xss_check() to xp-runtime
  • Loading branch information
liuchengxu authored Aug 2, 2020
1 parent a03396c commit 5cac55e
Show file tree
Hide file tree
Showing 22 changed files with 167 additions and 85 deletions.
20 changes: 19 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ members = [
"cli",
"runtime",
"primitives",
"primitives/runtime",
"primitives/mining/common",
"primitives/mining/staking",
"rpc",
Expand Down
4 changes: 2 additions & 2 deletions frame/balances/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ frame-benchmarking = { git = "https:/paritytech/substrate.git", tag
frame-support = { git = "https:/paritytech/substrate.git", tag = "v2.0.0-rc4", default-features = false }
frame-system = { git = "https:/paritytech/substrate.git", tag = "v2.0.0-rc4", default-features = false }

chainx-primitives = { path = "../../primitives", default-features = false }
xp-runtime = { path = "../../primitives/runtime", default-features = false }

[dev-dependencies]
sp-io = { git = "https:/paritytech/substrate.git", tag = "v2.0.0-rc4", default-features = false }
Expand All @@ -38,6 +38,6 @@ std = [
"frame-support/std",
"frame-system/std",

"chainx-primitives/std",
"xp-runtime/std",
]
runtime-benchmarks = ["frame-benchmarking"]
2 changes: 1 addition & 1 deletion frame/balances/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ use sp_runtime::{
use sp_std::prelude::*;
use sp_std::{cmp, convert::Infallible, fmt::Debug, mem, ops::BitOr, result};

use chainx_primitives::Memo;
use xp_runtime::Memo;

pub use self::imbalances::{NegativeImbalance, PositiveImbalance};

Expand Down
27 changes: 27 additions & 0 deletions primitives/runtime/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
[package]
name = "xp-runtime"
version = "0.1.0"
authors = ["ChainX community <https://www.chainx.org>"]
edition = "2018"

[dependencies]
codec = { package = "parity-scale-codec", version = "1.3.1", default-features = false }
serde = { version = "1.0.101", optional = true, features = ["derive"] }

sp-core = { git = "https:/paritytech/substrate.git", tag = "v2.0.0-rc4", default-features = false }
sp-runtime = { git = "https:/paritytech/substrate.git", tag = "v2.0.0-rc4", default-features = false }
sp-std = { git = "https:/paritytech/substrate.git", tag = "v2.0.0-rc4", default-features = false }

[dev-dependencies]
hex = "0.4"

[features]
default = ["std"]
std = [
"codec/std",
"serde/std",

"sp-core/std",
"sp-runtime/std",
"sp-std/std",
]
76 changes: 76 additions & 0 deletions primitives/runtime/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
//! ChainX Runtime Modules shared primitive types.

#![warn(missing_docs)]
#![cfg_attr(not(feature = "std"), no_std)]

use codec::{Decode, Encode};
#[cfg(feature = "std")]
use serde::{Deserialize, Serialize};
use sp_runtime::{DispatchError, DispatchResult};
use sp_std::prelude::Vec;

const MAXIMUM_MEMO_LEN: u8 = 128;

/// Returns Ok(_) if the input slice passes the xss check.
///
/// Although xss is imperceptible on-chain, we want to make it
/// look safer off-chain.
#[inline]
pub fn xss_check(input: &[u8]) -> DispatchResult {
if input.contains(&b'<') || input.contains(&b'>') {
Err(DispatchError::Other(
"'<' and '>' are not allowed, which could be abused off-chain.",
))?;
}
Ok(())
}

/// Type for leaving a note when sending a transaction.
#[derive(PartialEq, Eq, Clone, sp_core::RuntimeDebug, Encode, Decode, Default)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub struct Memo(Vec<u8>);

impl From<Vec<u8>> for Memo {
fn from(raw: Vec<u8>) -> Self {
Self(raw)
}
}

impl From<&[u8]> for Memo {
fn from(raw: &[u8]) -> Self {
Self(raw.to_vec())
}
}

impl AsRef<[u8]> for Memo {
fn as_ref(&self) -> &[u8] {
self.0.as_slice()
}
}

#[cfg(feature = "std")]
impl std::fmt::Display for Memo {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", String::from_utf8_lossy(&self.0))
}
}

#[cfg(not(feature = "std"))]
impl core::fmt::Display for Memo {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{:?}", self.0)
}
}

impl Memo {
/// Returns true if the inner byte length is in the range of [0, 128] and passes the xss check.
pub fn check_validity(&self) -> DispatchResult {
if self.0.len() > MAXIMUM_MEMO_LEN as usize {
Err(DispatchError::Other(
"transaction memo too long, valid byte length range: [0, 128]",
))
} else {
xss_check(&self.0)
}
}
}
54 changes: 1 addition & 53 deletions primitives/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
use sp_runtime::{
generic,
traits::{BlakeTwo256, IdentifyAccount, Verify},
DispatchError, DispatchResult, MultiSignature, OpaqueExtrinsic,
MultiSignature, OpaqueExtrinsic,
};
use sp_std::prelude::Vec;

Expand Down Expand Up @@ -59,58 +59,6 @@ pub type Precision = u8;
pub type AddrStr = Vec<u8>;
pub type AssetId = u32;

/// Type for leaving a note when sending a transaction.
#[derive(PartialEq, Eq, Clone, sp_core::RuntimeDebug, codec::Encode, codec::Decode, Default)]
#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))]
pub struct Memo(Vec<u8>);

impl From<Vec<u8>> for Memo {
fn from(raw: Vec<u8>) -> Self {
Self(raw)
}
}

impl From<&[u8]> for Memo {
fn from(raw: &[u8]) -> Self {
Self(raw.to_vec())
}
}

impl AsRef<[u8]> for Memo {
fn as_ref(&self) -> &[u8] {
self.0.as_slice()
}
}

#[cfg(feature = "std")]
impl std::fmt::Display for Memo {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", String::from_utf8_lossy(&self.0))
}
}

#[cfg(not(feature = "std"))]
impl core::fmt::Display for Memo {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{:?}", self.0)
}
}

const MAXIMUM_MEMO_LEN: u8 = 128;

impl Memo {
/// Returns true if the inner byte length is in the range of [0, 128] and passes the xss check.
pub fn check_validity(&self) -> DispatchResult {
if self.0.len() > MAXIMUM_MEMO_LEN as usize {
Err(DispatchError::Other(
"transaction memo too long, the range of valid byte length: [0, 128]",
))
} else {
xpallet_support::xss_check(&self.0)
}
}
}

/// App-specific crypto used for reporting equivocation/misbehavior in BABE and
/// GRANDPA. Any rewards for misbehavior reporting will be paid out to this
/// account.
Expand Down
2 changes: 2 additions & 0 deletions runtime/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ pallet-transaction-payment-rpc-runtime-api = { path = "../frame/transaction-paym

# ChainX primitives
chainx-primitives = { path = "../primitives", default-features = false }
xp-runtime = { path = "../primitives/runtime", default-features = false }
xp-mining-staking = { path = "../primitives/mining/staking", default-features = false }

# ChainX pallets
Expand Down Expand Up @@ -133,6 +134,7 @@ std = [
"pallet-transaction-payment-rpc-runtime-api/std",

"chainx-primitives/std",
"xp-runtime/std",
"xp-mining-staking/std",

"xpallet-protocol/std",
Expand Down
11 changes: 6 additions & 5 deletions runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,9 @@ use frame_system::{EnsureOneOf, EnsureRoot};
use pallet_grandpa::fg_primitives;
use pallet_grandpa::{AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList};
use pallet_im_online::sr25519::AuthorityId as ImOnlineId;
use pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo;

use xpallet_contracts_rpc_runtime_api::ContractExecResult;
use xpallet_mining_staking::{RpcNominatorLedger, ValidatorInfo};
use xpallet_support::RpcBalance;

Expand All @@ -60,16 +62,15 @@ pub use frame_support::{
StorageValue,
};
pub use pallet_timestamp::Call as TimestampCall;
pub use pallet_transaction_payment::{Multiplier, TargetedFeeAdjustment};

pub use chainx_primitives::{
AccountId, AccountIndex, AddrStr, AssetId, Balance, BlockNumber, Hash, Index, Memo, Moment,
Name, Signature, Token,
AccountId, AccountIndex, AddrStr, AssetId, Balance, BlockNumber, Hash, Index, Moment, Name,
Signature, Token,
};
use pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo;
use xpallet_contracts_rpc_runtime_api::ContractExecResult;
pub use xp_runtime::Memo;

// xpallet re-exports
pub use pallet_transaction_payment::{Multiplier, TargetedFeeAdjustment};
pub use xpallet_assets::{
AssetInfo, AssetRestriction, AssetRestrictions, AssetType, Chain, TotalAssetInfo,
WithdrawalLimit,
Expand Down
2 changes: 2 additions & 0 deletions xpallets/assets/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ frame-system = { git = "https:/paritytech/substrate.git", tag = "v2.

# ChainX primitives
chainx-primitives = { path = "../../primitives", default-features = false }
xp-runtime = { path = "../../primitives/runtime", default-features = false }

# ChainX pallets
xpallet-protocol = { path = "../protocol", default-features = false }
Expand Down Expand Up @@ -46,6 +47,7 @@ std = [
"frame-system/std",

"chainx-primitives/std",
"xp-runtime/std",

"xpallet-protocol/std",
"xpallet-support/std",
Expand Down
3 changes: 2 additions & 1 deletion xpallets/assets/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ use frame_support::{
use frame_system::{self as system, ensure_root, ensure_signed};

// ChainX
use chainx_primitives::{AssetId, Desc, Memo, Token};
use chainx_primitives::{AssetId, Desc, Token};
use xp_runtime::Memo;
use xpallet_support::{debug, ensure_with_errorlog, info};

use self::trigger::AssetChangedTrigger;
Expand Down
8 changes: 5 additions & 3 deletions xpallets/assets/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@ use sp_runtime::RuntimeDebug;
use sp_std::{collections::btree_map::BTreeMap, prelude::*, result, slice::Iter};

use frame_support::dispatch::{DispatchError, DispatchResult};

// ChainX
pub use chainx_primitives::{Desc, Memo, Precision, Token};
pub use chainx_primitives::{Desc, Precision, Token};
pub use xp_runtime::Memo;

use super::{BalanceOf, Error, Trait};

Expand Down Expand Up @@ -262,7 +264,7 @@ pub fn is_valid_token_name<T: Trait>(name: &[u8]) -> DispatchResult {
if name.len() > MAX_TOKEN_LEN || name.is_empty() {
Err(Error::<T>::InvalidAssetNameLen)?;
}
xpallet_support::xss_check(name)?;
xp_runtime::xss_check(name)?;
for c in name.iter() {
if is_ascii_invisible(c) {
Err(Error::<T>::InvalidAsscii)?;
Expand All @@ -276,7 +278,7 @@ pub fn is_valid_desc<T: Trait>(desc: &[u8]) -> DispatchResult {
if desc.len() > MAX_DESC_LEN {
Err(Error::<T>::InvalidDescLen)?;
}
xpallet_support::xss_check(desc)?;
xp_runtime::xss_check(desc)?;
for c in desc.iter() {
if is_ascii_invisible(c) {
Err(Error::<T>::InvalidAsscii)?;
Expand Down
Loading

0 comments on commit 5cac55e

Please sign in to comment.