Update to parity-scale-codec (#3232)

* WIP: update codec

* WIP

* compiling

* WIP

* rename parity-scale-codec to codec

* WIP

* fix

* remove old comments

* use published crates

* fix expected error msg

* bump version

* fmt and fix

* remove old comment

* fix wrong decoding impl

* implement encode like for structures

* undo removal of old pending changes

* trailingzeroinput

* Apply suggestions from code review

Co-Authored-By: Bastian Köcher <bkchr@users.noreply.github.com>
Co-Authored-By: DemiMarie-parity <48690212+DemiMarie-parity@users.noreply.github.com>

* update codec

* fmt

* version is 1.0.0

* show more error

* fmt
This commit is contained in:
thiolliere
2019-08-06 19:36:23 +02:00
committed by Bastian Köcher
parent a0d442333f
commit 4ed67e03a4
211 changed files with 867 additions and 682 deletions
@@ -22,7 +22,7 @@ use serde::Serialize;
use rstd::prelude::*;
use crate::ConsensusEngineId;
use crate::codec::{Decode, Encode, Input};
use crate::codec::{Decode, Encode, Input, Error};
/// Generic header digest.
#[derive(PartialEq, Eq, Clone, Encode, Decode)]
@@ -221,27 +221,29 @@ impl<Hash: Encode> Encode for DigestItem<Hash> {
}
}
impl<Hash: Encode> codec::EncodeLike for DigestItem<Hash> {}
impl<Hash: Decode> Decode for DigestItem<Hash> {
#[allow(deprecated)]
fn decode<I: Input>(input: &mut I) -> Option<Self> {
fn decode<I: Input>(input: &mut I) -> Result<Self, Error> {
let item_type: DigestItemType = Decode::decode(input)?;
match item_type {
DigestItemType::ChangesTrieRoot => Some(DigestItem::ChangesTrieRoot(
DigestItemType::ChangesTrieRoot => Ok(DigestItem::ChangesTrieRoot(
Decode::decode(input)?,
)),
DigestItemType::PreRuntime => {
let vals: (ConsensusEngineId, Vec<u8>) = Decode::decode(input)?;
Some(DigestItem::PreRuntime(vals.0, vals.1))
Ok(DigestItem::PreRuntime(vals.0, vals.1))
},
DigestItemType::Consensus => {
let vals: (ConsensusEngineId, Vec<u8>) = Decode::decode(input)?;
Some(DigestItem::Consensus(vals.0, vals.1))
Ok(DigestItem::Consensus(vals.0, vals.1))
}
DigestItemType::Seal => {
let vals: (ConsensusEngineId, Vec<u8>) = Decode::decode(input)?;
Some(DigestItem::Seal(vals.0, vals.1))
Ok(DigestItem::Seal(vals.0, vals.1))
},
DigestItemType::Other => Some(DigestItem::Other(
DigestItemType::Other => Ok(DigestItem::Other(
Decode::decode(input)?,
)),
}
@@ -305,7 +307,7 @@ impl<'a, Hash> DigestItemRef<'a, Hash> {
/// Try to match this digest item to the given opaque item identifier; if it matches, then
/// try to cast to the given datatype; if that works, return it.
pub fn try_to<T: Decode>(&self, id: OpaqueDigestItemId) -> Option<T> {
self.try_as_raw(id).and_then(|mut x| Decode::decode(&mut x))
self.try_as_raw(id).and_then(|mut x| Decode::decode(&mut x).ok())
}
}
@@ -340,6 +342,8 @@ impl<'a, Hash: Encode> Encode for DigestItemRef<'a, Hash> {
}
}
impl<'a, Hash: Encode> codec::EncodeLike for DigestItemRef<'a, Hash> {}
#[cfg(test)]
mod tests {
use super::*;
@@ -19,7 +19,7 @@
#[cfg(feature = "std")]
use serde::{Serialize, Deserialize};
use crate::codec::{Decode, Encode, Input, Output};
use crate::codec::{Decode, Encode, Input, Output, Error};
/// Era period
pub type Period = u64;
@@ -111,20 +111,22 @@ impl Encode for Era {
}
}
impl codec::EncodeLike for Era {}
impl Decode for Era {
fn decode<I: Input>(input: &mut I) -> Option<Self> {
fn decode<I: Input>(input: &mut I) -> Result<Self, Error> {
let first = input.read_byte()?;
if first == 0 {
Some(Era::Immortal)
Ok(Era::Immortal)
} else {
let encoded = first as u64 + ((input.read_byte()? as u64) << 8);
let period = 2 << (encoded % (1 << 4));
let quantize_factor = (period >> 12).max(1);
let phase = (encoded >> 4) * quantize_factor;
if period >= 4 && phase < period {
Some(Era::Mortal(period, phase))
Ok(Era::Mortal(period, phase))
} else {
None
Err("Invalid period and phase".into())
}
}
}
@@ -20,7 +20,7 @@
use serde::Serialize;
#[cfg(feature = "std")]
use log::debug;
use crate::codec::{Decode, Encode, Codec, Input, Output, HasCompact, EncodeAsRef};
use crate::codec::{Decode, Encode, Codec, Input, Output, HasCompact, EncodeAsRef, Error};
use crate::traits::{
self, Member, SimpleArithmetic, SimpleBitOps, MaybeDisplay, Hash as HashT, MaybeSerializeDebug,
MaybeSerializeDebugButNotDeserialize
@@ -60,8 +60,8 @@ impl<Number, Hash> Decode for Header<Number, Hash> where
Hash: HashT,
Hash::Output: Decode,
{
fn decode<I: Input>(input: &mut I) -> Option<Self> {
Some(Header {
fn decode<I: Input>(input: &mut I) -> Result<Self, Error> {
Ok(Header {
parent_hash: Decode::decode(input)?,
number: <<Number as HasCompact>::Type>::decode(input)?.into(),
state_root: Decode::decode(input)?,
@@ -85,6 +85,12 @@ impl<Number, Hash> Encode for Header<Number, Hash> where
}
}
impl<Number, Hash> codec::EncodeLike for Header<Number, Hash> where
Number: HasCompact + Copy + Into<u128>,
Hash: HashT,
Hash::Output: Encode,
{}
impl<Number, Hash> traits::Header for Header<Number, Hash> where
Number: Member + MaybeSerializeDebug + ::rstd::hash::Hash + MaybeDisplay + SimpleArithmetic + Codec + Copy + Into<u128>,
Hash: HashT,
@@ -21,7 +21,7 @@ use std::fmt;
use rstd::prelude::*;
use runtime_io::blake2_256;
use crate::codec::{Decode, Encode, Input};
use crate::codec::{Decode, Encode, Input, Error};
use crate::traits::{self, Member, MaybeDisplay, SignedExtension, Checkable, Extrinsic};
use super::CheckedExtrinsic;
@@ -131,7 +131,7 @@ where
Call: Decode,
Extra: SignedExtension,
{
fn decode<I: Input>(input: &mut I) -> Option<Self> {
fn decode<I: Input>(input: &mut I) -> Result<Self, Error> {
// This is a little more complicated than usual since the binary format must be compatible
// with substrate's generic `Vec<u8>` type. Basically this just means accepting that there
// will be a prefix of vector length (we don't need
@@ -143,10 +143,10 @@ where
let is_signed = version & 0b1000_0000 != 0;
let version = version & 0b0111_1111;
if version != TRANSACTION_VERSION {
return None
return Err("Invalid transaction version".into());
}
Some(UncheckedExtrinsic {
Ok(UncheckedExtrinsic {
signature: if is_signed { Some(Decode::decode(input)?) } else { None },
function: Decode::decode(input)?,
})
@@ -245,7 +245,7 @@ mod tests {
fn unsigned_codec_should_work() {
let ux = Ex::new_unsigned(vec![0u8; 0]);
let encoded = ux.encode();
assert_eq!(Ex::decode(&mut &encoded[..]), Some(ux));
assert_eq!(Ex::decode(&mut &encoded[..]), Ok(ux));
}
#[test]
@@ -257,7 +257,7 @@ mod tests {
TestExtra
);
let encoded = ux.encode();
assert_eq!(Ex::decode(&mut &encoded[..]), Some(ux));
assert_eq!(Ex::decode(&mut &encoded[..]), Ok(ux));
}
#[test]
@@ -270,7 +270,7 @@ mod tests {
TestExtra
);
let encoded = ux.encode();
assert_eq!(Ex::decode(&mut &encoded[..]), Some(ux));
assert_eq!(Ex::decode(&mut &encoded[..]), Ok(ux));
}
#[test]