Skip to content

Commit

Permalink
implement fallback
Browse files Browse the repository at this point in the history
  • Loading branch information
Andrew Plaza committed Sep 1, 2021
1 parent 6c11e05 commit 03be6ea
Show file tree
Hide file tree
Showing 13 changed files with 149 additions and 146 deletions.
101 changes: 1 addition & 100 deletions Cargo.lock

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

3 changes: 1 addition & 2 deletions core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,8 @@ dyn-clone = "1.0"
hex = "0.4"

runtime-version = { package = "sp-version", git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.9" }
pallet-indices = { package = "pallet-indices", git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.9" }
pallet-democracy = { package = "pallet-democracy", git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.9" }
pallet-identity = { package = "pallet-identity", git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.9" }
frame-support = { package = "frame-support", git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.9" }

primitives = { package = "sp-core", git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.9" }
runtime-primitives = { package = "sp-runtime", git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.9" }
Expand Down
21 changes: 15 additions & 6 deletions core/src/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,14 @@ impl Decoder {
))
})?;
log::trace!("Resolved {:?}", new_type);
self.decode_single(module, spec, new_type, data, cursor, is_compact)?
let mut saved_cursor = *cursor;
let resolved = self.decode_single(module, spec, new_type, data, cursor, is_compact);
if resolved.is_err() {
if let Some(fallback) = self.types.try_fallback(self.chain.as_str(), spec, module, v) {
return Ok(self.decode_single(module, spec, fallback, data, &mut saved_cursor, is_compact)?);
}
}
resolved?
}
}
RustTypeMarker::Unit(u) => SubstrateType::Unit(u.to_string()),
Expand Down Expand Up @@ -714,20 +721,18 @@ impl Decoder {
),
])))
}
/*
"Data" => {
log::trace!("Data::cursor={}", *cursor);
let identity_data: pallet_identity::Data = Decode::decode(&mut &data[*cursor..])?;
let identity_data: substrate_types::Data = Decode::decode(&mut &data[*cursor..])?;
match &identity_data {
pallet_identity::Data::None => (),
pallet_identity::Data::Raw(v) => *cursor += v.len(),
substrate_types::Data::None => (),
substrate_types::Data::Raw(v) => *cursor += v.len(),
_ => *cursor += 32,
};
// for the enum byte
*cursor += 1;
Ok(Some(SubstrateType::Data(identity_data)))
}
*/
"Call" | "GenericCall" => {
let types = self.decode_call(spec, data, cursor)?;
Ok(Some(SubstrateType::Call(types)))
Expand Down Expand Up @@ -880,6 +885,10 @@ mod tests {
Some(&RustTypeMarker::I128)
}

fn try_fallback(&self, _chain: &str, _spec: u32, _module: &str, _ty: &str) -> Option<&RustTypeMarker> {
None
}

fn get_extrinsic_ty(&self, _chain: &str, _spec: u32, _ty: &str) -> Option<&RustTypeMarker> {
None
}
Expand Down
4 changes: 4 additions & 0 deletions core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ pub trait TypeDetective: fmt::Debug + dyn_clone::DynClone + Send + Sync {
/// Get a 'RustTypeMarker'
fn get(&self, chain: &str, spec: u32, module: &str, ty: &str) -> Option<&RustTypeMarker>;

/// Some types have a fallback type that may be decoded into if the original
/// type fails.
fn try_fallback(&self, chain: &str, spec: u32, module: &str, ty: &str) -> Option<&RustTypeMarker>;

/// get a type specific to decoding extrinsics
fn get_extrinsic_ty(&self, chain: &str, spec: u32, ty: &str) -> Option<&RustTypeMarker>;
}
Expand Down
10 changes: 5 additions & 5 deletions core/src/substrate_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
//! Display Implementation
mod remote;
mod data;

use self::remote::*;
use crate::{Error, SetField};
Expand All @@ -28,10 +29,11 @@ use primitives::crypto::{Ss58AddressFormat, Ss58Codec};
use serde::Serialize;
use std::{convert::TryFrom, fmt};

pub use self::data::Data;

pub type Address = runtime_primitives::MultiAddress<AccountId32, u32>;
pub type Vote = pallet_democracy::Vote;
pub type Conviction = pallet_democracy::Conviction;
// pub type Data = pallet_identity::Data;

/// A 'stateful' version of [RustTypeMarker](enum.RustTypeMarker.html).
/// 'Std' variant is not here like in RustTypeMarker.
Expand All @@ -58,10 +60,8 @@ pub enum SubstrateType {
// u32 and [u8; 32] for its index/id
#[serde(with = "RemoteAddress")]
Address(Address),
/*
#[serde(with = "RemoteData")]
/// Data Identity Type
Data(Data),
*/
/// SignedExtension Type
SignedExtra(String),

Expand Down Expand Up @@ -146,7 +146,7 @@ impl fmt::Display for SubstrateType {
runtime_primitives::MultiAddress::Address32(ary) => write!(f, "Address32: {:?}", ary),
runtime_primitives::MultiAddress::Address20(ary) => write!(f, "Address20: {:?}", ary),
},
// SubstrateType::Data(d) => write!(f, "{:?}", d),
SubstrateType::Data(d) => write!(f, "{:?}", d),
SubstrateType::SignedExtra(v) => write!(f, "{}", v),
SubstrateType::Unit(u) => write!(f, "{}", u),
SubstrateType::Composite(v) => {
Expand Down
97 changes: 97 additions & 0 deletions core/src/substrate_types/data.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of substrate-desub.
//
// substrate-desub 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.
//
// substrate-desub 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 substrate-desub. If not, see <http://www.gnu.org/licenses/>.

//! Copy of this: https://substrate.dev/rustdocs/latest/pallet_identity/enum.Data.html
//! For the purpose of Decoding the Data field.
//! Because of the specificity/complexity of decoding:
//! - `BoundedVec` includes private tuple fields with no getters so Serde `remote` does not work
//! - `Data` has a special way of encoding/decoding
//! Data impl is copied over and must be maintaned against substrate master.

use codec::{Decode, Encode};
use serde::{Serialize, Deserialize};
use std::iter::once;


/// Either underlying data blob if it is at most 32 bytes, or a hash of it. If the data is greater
/// than 32-bytes then it will be truncated when encoding.
///
/// Can also be `None`.
#[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
pub enum Data {
/// No data here.
None,
/// The data is stored directly.
Raw(Vec<u8>),
/// Only the Blake2 hash of the data is stored. The preimage of the hash may be retrieved
/// through some hash-lookup service.
BlakeTwo256([u8; 32]),
/// Only the SHA2-256 hash of the data is stored. The preimage of the hash may be retrieved
/// through some hash-lookup service.
Sha256([u8; 32]),
/// Only the Keccak-256 hash of the data is stored. The preimage of the hash may be retrieved
/// through some hash-lookup service.
Keccak256([u8; 32]),
/// Only the SHA3-256 hash of the data is stored. The preimage of the hash may be retrieved
/// through some hash-lookup service.
ShaThree256([u8; 32]),
}

impl Decode for Data {
fn decode<I: codec::Input>(input: &mut I) -> Result<Self, codec::Error> {
let b = input.read_byte()?;
Ok(match b {
0 => Data::None,
n @ 1 ..= 33 => {
let mut r = vec![0u8; n as usize - 1];
input.read(&mut r[..])?;
Data::Raw(r)
}
34 => Data::BlakeTwo256(<[u8; 32]>::decode(input)?),
35 => Data::Sha256(<[u8; 32]>::decode(input)?),
36 => Data::Keccak256(<[u8; 32]>::decode(input)?),
37 => Data::ShaThree256(<[u8; 32]>::decode(input)?),
_ => return Err(codec::Error::from("invalid leading byte")),
})
}
}

impl Encode for Data {
fn encode(&self) -> Vec<u8> {
match self {
Data::None => vec![0u8; 1],
Data::Raw(ref x) => {
let l = x.len().min(32);
let mut r = vec![l as u8 + 1; l + 1];
r[1..].copy_from_slice(&x[..l as usize]);
r
}
Data::BlakeTwo256(ref h) => once(34u8).chain(h.iter().cloned()).collect(),
Data::Sha256(ref h) => once(35u8).chain(h.iter().cloned()).collect(),
Data::Keccak256(ref h) => once(36u8).chain(h.iter().cloned()).collect(),
Data::ShaThree256(ref h) => once(37u8).chain(h.iter().cloned()).collect(),
}
}
}
impl codec::EncodeLike for Data {}

impl Default for Data {
fn default() -> Self {
Self::None
}
}

Loading

0 comments on commit 03be6ea

Please sign in to comment.