Add 'rlp/' from commit 'ea070971703129a14d47f73bc3f30cfd359ded6d'

git-subtree-dir: rlp
git-subtree-mainline: 502c639758
git-subtree-split: ea07097170
This commit is contained in:
David Palm 2018-07-03 10:24:20 +02:00
commit fefe267f73
13 changed files with 2026 additions and 0 deletions

13
rlp/Cargo.toml Normal file
View File

@ -0,0 +1,13 @@
[package]
description = "Recursive-length prefix encoding, decoding, and compression"
repository = "https://github.com/paritytech/parity"
license = "MIT/Apache-2.0"
name = "rlp"
version = "0.2.1"
authors = ["Parity Technologies <admin@parity.io>"]
[dependencies]
elastic-array = "0.10"
ethereum-types = "0.3"
rustc-hex = "1.0"
byteorder = "1.0"

201
rlp/LICENSE-APACHE2 Normal file
View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

19
rlp/LICENSE-MIT Normal file
View File

@ -0,0 +1,19 @@
Copyright (c) 2015-2017 Parity Technologies
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

8
rlp/README.md Normal file
View File

@ -0,0 +1,8 @@
# RLP
Recursive-length-prefix encoding, decoding, and compression in Rust.
## License
Unlike most parts of Parity, which fall under the GPLv3, this package is dual-licensed under MIT/Apache2 at the user's choice.
Find the associated license files in this directory as `LICENSE-MIT` and `LICENSE-APACHE2` respectively.

103
rlp/benches/rlp.rs Normal file
View File

@ -0,0 +1,103 @@
// Copyright 2015-2017 Parity Technologies
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! benchmarking for rlp
//! should be started with:
//! ```bash
//! multirust run nightly cargo bench
//! ```
#![feature(test)]
extern crate ethereum_types;
extern crate rlp;
extern crate test;
use ethereum_types::U256;
use rlp::{RlpStream, Rlp};
use test::Bencher;
#[bench]
fn bench_stream_u64_value(b: &mut Bencher) {
b.iter(|| {
// u64
let mut stream = RlpStream::new();
stream.append(&0x1023456789abcdefu64);
let _ = stream.out();
});
}
#[bench]
fn bench_decode_u64_value(b: &mut Bencher) {
b.iter(|| {
// u64
let data = vec![0x88, 0x10, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef];
let rlp = Rlp::new(&data);
let _: u64 = rlp.as_val().unwrap();
});
}
#[bench]
fn bench_stream_u256_value(b: &mut Bencher) {
b.iter(|| {
// u256
let mut stream = RlpStream::new();
let uint: U256 = "8090a0b0c0d0e0f00910203040506077000000000000000100000000000012f0".into();
stream.append(&uint);
let _ = stream.out();
});
}
#[bench]
fn bench_decode_u256_value(b: &mut Bencher) {
b.iter(|| {
// u256
let data = vec![0xa0, 0x80, 0x90, 0xa0, 0xb0, 0xc0, 0xd0, 0xe0, 0xf0, 0x09, 0x10, 0x20,
0x30, 0x40, 0x50, 0x60, 0x77, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0xf0];
let rlp = Rlp::new(&data);
let _ : U256 = rlp.as_val().unwrap();
});
}
#[bench]
fn bench_stream_nested_empty_lists(b: &mut Bencher) {
b.iter(|| {
// [ [], [[]], [ [], [[]] ] ]
let mut stream = RlpStream::new_list(3);
stream.begin_list(0);
stream.begin_list(1).begin_list(0);
stream.begin_list(2).begin_list(0).begin_list(1).begin_list(0);
let _ = stream.out();
});
}
#[bench]
fn bench_decode_nested_empty_lists(b: &mut Bencher) {
b.iter(|| {
// [ [], [[]], [ [], [[]] ] ]
let data = vec![0xc7, 0xc0, 0xc1, 0xc0, 0xc3, 0xc0, 0xc1, 0xc0];
let rlp = Rlp::new(&data);
let _v0: Vec<u16> = rlp.at(0).unwrap().as_list().unwrap();
let _v1: Vec<u16> = rlp.at(1).unwrap().at(0).unwrap().as_list().unwrap();
let nested_rlp = rlp.at(2).unwrap();
let _v2a: Vec<u16> = nested_rlp.at(0).unwrap().as_list().unwrap();
let _v2b: Vec<u16> = nested_rlp.at(1).unwrap().at(0).unwrap().as_list().unwrap();
});
}
#[bench]
fn bench_stream_1000_empty_lists(b: &mut Bencher) {
b.iter(|| {
let mut stream = RlpStream::new_list(1000);
for _ in 0..1000 {
stream.begin_list(0);
}
let _ = stream.out();
});
}

7
rlp/license-header Normal file
View File

@ -0,0 +1,7 @@
// Copyright 2015-2017 Parity Technologies
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

49
rlp/src/error.rs Normal file
View File

@ -0,0 +1,49 @@
// Copyright 2015-2017 Parity Technologies
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::fmt;
use std::error::Error as StdError;
#[derive(Debug, PartialEq, Eq, Clone)]
/// Error concerning the RLP decoder.
pub enum DecoderError {
/// Data has additional bytes at the end of the valid RLP fragment.
RlpIsTooBig,
/// Data has too few bytes for valid RLP.
RlpIsTooShort,
/// Expect an encoded list, RLP was something else.
RlpExpectedToBeList,
/// Expect encoded data, RLP was something else.
RlpExpectedToBeData,
/// Expected a different size list.
RlpIncorrectListLen,
/// Data length number has a prefixed zero byte, invalid for numbers.
RlpDataLenWithZeroPrefix,
/// List length number has a prefixed zero byte, invalid for numbers.
RlpListLenWithZeroPrefix,
/// Non-canonical (longer than necessary) representation used for data or list.
RlpInvalidIndirection,
/// Declared length is inconsistent with data specified after.
RlpInconsistentLengthAndData,
/// Declared length is invalid and results in overflow
RlpInvalidLength,
/// Custom rlp decoding error.
Custom(&'static str),
}
impl StdError for DecoderError {
fn description(&self) -> &str {
"builder error"
}
}
impl fmt::Display for DecoderError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self, f)
}
}

285
rlp/src/impls.rs Normal file
View File

@ -0,0 +1,285 @@
// Copyright 2015-2017 Parity Technologies
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::{cmp, mem, str};
use byteorder::{ByteOrder, BigEndian};
use bigint::{U128, U256, H64, H128, H160, H256, H512, H520, Bloom};
use traits::{Encodable, Decodable};
use stream::RlpStream;
use {Rlp, DecoderError};
pub fn decode_usize(bytes: &[u8]) -> Result<usize, DecoderError> {
match bytes.len() {
l if l <= mem::size_of::<usize>() => {
if bytes[0] == 0 {
return Err(DecoderError::RlpInvalidIndirection);
}
let mut res = 0usize;
for i in 0..l {
let shift = (l - 1 - i) * 8;
res = res + ((bytes[i] as usize) << shift);
}
Ok(res)
}
_ => Err(DecoderError::RlpIsTooBig),
}
}
impl Encodable for bool {
fn rlp_append(&self, s: &mut RlpStream) {
if *self {
s.encoder().encode_value(&[1]);
} else {
s.encoder().encode_value(&[0]);
}
}
}
impl Decodable for bool {
fn decode(rlp: &Rlp) -> Result<Self, DecoderError> {
rlp.decoder().decode_value(|bytes| {
match bytes.len() {
0 => Ok(false),
1 => Ok(bytes[0] != 0),
_ => Err(DecoderError::RlpIsTooBig),
}
})
}
}
impl<'a> Encodable for &'a [u8] {
fn rlp_append(&self, s: &mut RlpStream) {
s.encoder().encode_value(self);
}
}
impl Encodable for Vec<u8> {
fn rlp_append(&self, s: &mut RlpStream) {
s.encoder().encode_value(self);
}
}
impl Decodable for Vec<u8> {
fn decode(rlp: &Rlp) -> Result<Self, DecoderError> {
rlp.decoder().decode_value(|bytes| {
Ok(bytes.to_vec())
})
}
}
impl<T> Encodable for Option<T> where T: Encodable {
fn rlp_append(&self, s: &mut RlpStream) {
match *self {
None => {
s.begin_list(0);
},
Some(ref value) => {
s.begin_list(1);
s.append(value);
}
}
}
}
impl<T> Decodable for Option<T> where T: Decodable {
fn decode(rlp: &Rlp) -> Result<Self, DecoderError> {
let items = rlp.item_count()?;
match items {
1 => rlp.val_at(0).map(Some),
0 => Ok(None),
_ => Err(DecoderError::RlpIncorrectListLen),
}
}
}
impl Encodable for u8 {
fn rlp_append(&self, s: &mut RlpStream) {
if *self != 0 {
s.encoder().encode_value(&[*self]);
} else {
s.encoder().encode_value(&[]);
}
}
}
impl Decodable for u8 {
fn decode(rlp: &Rlp) -> Result<Self, DecoderError> {
rlp.decoder().decode_value(|bytes| {
match bytes.len() {
1 if bytes[0] != 0 => Ok(bytes[0]),
0 => Ok(0),
1 => Err(DecoderError::RlpInvalidIndirection),
_ => Err(DecoderError::RlpIsTooBig),
}
})
}
}
macro_rules! impl_encodable_for_u {
($name: ident, $func: ident, $size: expr) => {
impl Encodable for $name {
fn rlp_append(&self, s: &mut RlpStream) {
let leading_empty_bytes = self.leading_zeros() as usize / 8;
let mut buffer = [0u8; $size];
BigEndian::$func(&mut buffer, *self);
s.encoder().encode_value(&buffer[leading_empty_bytes..]);
}
}
}
}
macro_rules! impl_decodable_for_u {
($name: ident) => {
impl Decodable for $name {
fn decode(rlp: &Rlp) -> Result<Self, DecoderError> {
rlp.decoder().decode_value(|bytes| {
match bytes.len() {
0 | 1 => u8::decode(rlp).map(|v| v as $name),
l if l <= mem::size_of::<$name>() => {
if bytes[0] == 0 {
return Err(DecoderError::RlpInvalidIndirection);
}
let mut res = 0 as $name;
for i in 0..l {
let shift = (l - 1 - i) * 8;
res = res + ((bytes[i] as $name) << shift);
}
Ok(res)
}
_ => Err(DecoderError::RlpIsTooBig),
}
})
}
}
}
}
impl_encodable_for_u!(u16, write_u16, 2);
impl_encodable_for_u!(u32, write_u32, 4);
impl_encodable_for_u!(u64, write_u64, 8);
impl_decodable_for_u!(u16);
impl_decodable_for_u!(u32);
impl_decodable_for_u!(u64);
impl Encodable for usize {
fn rlp_append(&self, s: &mut RlpStream) {
(*self as u64).rlp_append(s);
}
}
impl Decodable for usize {
fn decode(rlp: &Rlp) -> Result<Self, DecoderError> {
u64::decode(rlp).map(|value| value as usize)
}
}
macro_rules! impl_encodable_for_hash {
($name: ident) => {
impl Encodable for $name {
fn rlp_append(&self, s: &mut RlpStream) {
s.encoder().encode_value(self);
}
}
}
}
macro_rules! impl_decodable_for_hash {
($name: ident, $size: expr) => {
impl Decodable for $name {
fn decode(rlp: &Rlp) -> Result<Self, DecoderError> {
rlp.decoder().decode_value(|bytes| match bytes.len().cmp(&$size) {
cmp::Ordering::Less => Err(DecoderError::RlpIsTooShort),
cmp::Ordering::Greater => Err(DecoderError::RlpIsTooBig),
cmp::Ordering::Equal => {
let mut t = [0u8; $size];
t.copy_from_slice(bytes);
Ok($name(t))
}
})
}
}
}
}
impl_encodable_for_hash!(H64);
impl_encodable_for_hash!(H128);
impl_encodable_for_hash!(H160);
impl_encodable_for_hash!(H256);
impl_encodable_for_hash!(H512);
impl_encodable_for_hash!(H520);
impl_encodable_for_hash!(Bloom);
impl_decodable_for_hash!(H64, 8);
impl_decodable_for_hash!(H128, 16);
impl_decodable_for_hash!(H160, 20);
impl_decodable_for_hash!(H256, 32);
impl_decodable_for_hash!(H512, 64);
impl_decodable_for_hash!(H520, 65);
impl_decodable_for_hash!(Bloom, 256);
macro_rules! impl_encodable_for_uint {
($name: ident, $size: expr) => {
impl Encodable for $name {
fn rlp_append(&self, s: &mut RlpStream) {
let leading_empty_bytes = $size - (self.bits() + 7) / 8;
let mut buffer = [0u8; $size];
self.to_big_endian(&mut buffer);
s.encoder().encode_value(&buffer[leading_empty_bytes..]);
}
}
}
}
macro_rules! impl_decodable_for_uint {
($name: ident, $size: expr) => {
impl Decodable for $name {
fn decode(rlp: &Rlp) -> Result<Self, DecoderError> {
rlp.decoder().decode_value(|bytes| {
if !bytes.is_empty() && bytes[0] == 0 {
Err(DecoderError::RlpInvalidIndirection)
} else if bytes.len() <= $size {
Ok($name::from(bytes))
} else {
Err(DecoderError::RlpIsTooBig)
}
})
}
}
}
}
impl_encodable_for_uint!(U256, 32);
impl_encodable_for_uint!(U128, 16);
impl_decodable_for_uint!(U256, 32);
impl_decodable_for_uint!(U128, 16);
impl<'a> Encodable for &'a str {
fn rlp_append(&self, s: &mut RlpStream) {
s.encoder().encode_value(self.as_bytes());
}
}
impl Encodable for String {
fn rlp_append(&self, s: &mut RlpStream) {
s.encoder().encode_value(self.as_bytes());
}
}
impl Decodable for String {
fn decode(rlp: &Rlp) -> Result<Self, DecoderError> {
rlp.decoder().decode_value(|bytes| {
match str::from_utf8(bytes) {
Ok(s) => Ok(s.to_owned()),
// consider better error type here
Err(_err) => Err(DecoderError::RlpExpectedToBeData),
}
})
}
}

101
rlp/src/lib.rs Normal file
View File

@ -0,0 +1,101 @@
// Copyright 2015-2017 Parity Technologies
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Recursive Length Prefix serialization crate.
//!
//! Allows encoding, decoding, and view onto rlp-slice
//!
//!# What should you use when?
//!
//!### Use `encode` function when:
//! * You want to encode something inline.
//! * You do not work on big set of data.
//! * You want to encode whole data structure at once.
//!
//!### Use `decode` function when:
//! * You want to decode something inline.
//! * You do not work on big set of data.
//! * You want to decode whole rlp at once.
//!
//!### Use `RlpStream` when:
//! * You want to encode something in portions.
//! * You encode a big set of data.
//!
//!### Use `Rlp` when:
//! * You need to handle data corruption errors.
//! * You are working on input data.
//! * You want to get view onto rlp-slice.
//! * You don't want to decode whole rlp at once.
extern crate byteorder;
extern crate ethereum_types as bigint;
extern crate elastic_array;
extern crate rustc_hex;
mod traits;
mod error;
mod rlpin;
mod stream;
mod impls;
use elastic_array::ElasticArray1024;
use std::borrow::Borrow;
pub use error::DecoderError;
pub use traits::{Decodable, Encodable};
pub use rlpin::{Rlp, RlpIterator, PayloadInfo, Prototype};
pub use stream::RlpStream;
/// The RLP encoded empty data (used to mean "null value").
pub const NULL_RLP: [u8; 1] = [0x80; 1];
/// The RLP encoded empty list.
pub const EMPTY_LIST_RLP: [u8; 1] = [0xC0; 1];
/// Shortcut function to decode trusted rlp
///
/// ```rust
/// extern crate rlp;
///
/// fn main () {
/// let data = vec![0x83, b'c', b'a', b't'];
/// let animal: String = rlp::decode(&data).expect("could not decode");
/// assert_eq!(animal, "cat".to_owned());
/// }
/// ```
pub fn decode<T>(bytes: &[u8]) -> Result<T, DecoderError> where T: Decodable {
let rlp = Rlp::new(bytes);
rlp.as_val()
}
pub fn decode_list<T>(bytes: &[u8]) -> Vec<T> where T: Decodable {
let rlp = Rlp::new(bytes);
rlp.as_list().expect("trusted rlp should be valid")
}
/// Shortcut function to encode structure into rlp.
///
/// ```rust
/// extern crate rlp;
///
/// fn main () {
/// let animal = "cat";
/// let out = rlp::encode(&animal).into_vec();
/// assert_eq!(out, vec![0x83, b'c', b'a', b't']);
/// }
/// ```
pub fn encode<E>(object: &E) -> ElasticArray1024<u8> where E: Encodable {
let mut stream = RlpStream::new();
stream.append(object);
stream.drain()
}
pub fn encode_list<E, K>(object: &[K]) -> ElasticArray1024<u8> where E: Encodable, K: Borrow<E> {
let mut stream = RlpStream::new();
stream.append_list(object);
stream.drain()
}

405
rlp/src/rlpin.rs Normal file
View File

@ -0,0 +1,405 @@
// Copyright 2015-2017 Parity Technologies
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::cell::Cell;
use std::fmt;
use rustc_hex::ToHex;
use impls::decode_usize;
use {Decodable, DecoderError};
/// rlp offset
#[derive(Copy, Clone, Debug)]
struct OffsetCache {
index: usize,
offset: usize,
}
impl OffsetCache {
fn new(index: usize, offset: usize) -> OffsetCache {
OffsetCache {
index: index,
offset: offset,
}
}
}
#[derive(Debug)]
/// RLP prototype
pub enum Prototype {
/// Empty
Null,
/// Value
Data(usize),
/// List
List(usize),
}
/// Stores basic information about item
pub struct PayloadInfo {
/// Header length in bytes
pub header_len: usize,
/// Value length in bytes
pub value_len: usize,
}
fn calculate_payload_info(header_bytes: &[u8], len_of_len: usize) -> Result<PayloadInfo, DecoderError> {
let header_len = 1 + len_of_len;
match header_bytes.get(1) {
Some(&0) => return Err(DecoderError::RlpDataLenWithZeroPrefix),
None => return Err(DecoderError::RlpIsTooShort),
_ => (),
}
if header_bytes.len() < header_len { return Err(DecoderError::RlpIsTooShort); }
let value_len = decode_usize(&header_bytes[1..header_len])?;
Ok(PayloadInfo::new(header_len, value_len))
}
impl PayloadInfo {
fn new(header_len: usize, value_len: usize) -> PayloadInfo {
PayloadInfo {
header_len: header_len,
value_len: value_len,
}
}
/// Total size of the RLP.
pub fn total(&self) -> usize { self.header_len + self.value_len }
/// Create a new object from the given bytes RLP. The bytes
pub fn from(header_bytes: &[u8]) -> Result<PayloadInfo, DecoderError> {
match header_bytes.first().cloned() {
None => Err(DecoderError::RlpIsTooShort),
Some(0...0x7f) => Ok(PayloadInfo::new(0, 1)),
Some(l @ 0x80...0xb7) => Ok(PayloadInfo::new(1, l as usize - 0x80)),
Some(l @ 0xb8...0xbf) => {
let len_of_len = l as usize - 0xb7;
calculate_payload_info(header_bytes, len_of_len)
}
Some(l @ 0xc0...0xf7) => Ok(PayloadInfo::new(1, l as usize - 0xc0)),
Some(l @ 0xf8...0xff) => {
let len_of_len = l as usize - 0xf7;
calculate_payload_info(header_bytes, len_of_len)
},
// we cant reach this place, but rust requires _ to be implemented
_ => { unreachable!(); }
}
}
}
/// Data-oriented view onto rlp-slice.
///
/// This is an immutable structure. No operations change it.
///
/// Should be used in places where, error handling is required,
/// eg. on input
#[derive(Debug)]
pub struct Rlp<'a> {
bytes: &'a [u8],
offset_cache: Cell<OffsetCache>,
count_cache: Cell<Option<usize>>,
}
impl<'a> Clone for Rlp<'a> {
fn clone(&self) -> Rlp<'a> {
Rlp {
bytes: self.bytes,
offset_cache: self.offset_cache.clone(),
count_cache: self.count_cache.clone(),
}
}
}
impl<'a> fmt::Display for Rlp<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match self.prototype() {
Ok(Prototype::Null) => write!(f, "null"),
Ok(Prototype::Data(_)) => write!(f, "\"0x{}\"", self.data().unwrap().to_hex()),
Ok(Prototype::List(len)) => {
write!(f, "[")?;
for i in 0..len-1 {
write!(f, "{}, ", self.at(i).unwrap())?;
}
write!(f, "{}", self.at(len - 1).unwrap())?;
write!(f, "]")
},
Err(err) => write!(f, "{:?}", err)
}
}
}
impl<'a, 'view> Rlp<'a> where 'a: 'view {
pub fn new(bytes: &'a [u8]) -> Rlp<'a> {
Rlp {
bytes: bytes,
offset_cache: Cell::new(OffsetCache::new(usize::max_value(), 0)),
count_cache: Cell::new(None)
}
}
pub fn as_raw(&'view self) -> &'a [u8] {
self.bytes
}
pub fn prototype(&self) -> Result<Prototype, DecoderError> {
// optimize? && return appropriate errors
if self.is_data() {
Ok(Prototype::Data(self.size()))
} else if self.is_list() {
self.item_count().map(Prototype::List)
} else {
Ok(Prototype::Null)
}
}
pub fn payload_info(&self) -> Result<PayloadInfo, DecoderError> {
BasicDecoder::payload_info(self.bytes)
}
pub fn data(&'view self) -> Result<&'a [u8], DecoderError> {
let pi = BasicDecoder::payload_info(self.bytes)?;
Ok(&self.bytes[pi.header_len..(pi.header_len + pi.value_len)])
}
pub fn item_count(&self) -> Result<usize, DecoderError> {
match self.is_list() {
true => match self.count_cache.get() {
Some(c) => Ok(c),
None => {
let c = self.iter().count();
self.count_cache.set(Some(c));
Ok(c)
}
},
false => Err(DecoderError::RlpExpectedToBeList),
}
}
pub fn size(&self) -> usize {
match self.is_data() {
// TODO: No panic on malformed data, but ideally would Err on no PayloadInfo.
true => BasicDecoder::payload_info(self.bytes).map(|b| b.value_len).unwrap_or(0),
false => 0
}
}
pub fn at(&'view self, index: usize) -> Result<Rlp<'a>, DecoderError> {
if !self.is_list() {
return Err(DecoderError::RlpExpectedToBeList);
}
// move to cached position if its index is less or equal to
// current search index, otherwise move to beginning of list
let c = self.offset_cache.get();
let (mut bytes, to_skip) = match c.index <= index {
true => (Rlp::consume(self.bytes, c.offset)?, index - c.index),
false => (self.consume_list_payload()?, index),
};
// skip up to x items
bytes = Rlp::consume_items(bytes, to_skip)?;
// update the cache
self.offset_cache.set(OffsetCache::new(index, self.bytes.len() - bytes.len()));
// construct new rlp
let found = BasicDecoder::payload_info(bytes)?;
Ok(Rlp::new(&bytes[0..found.header_len + found.value_len]))
}
pub fn is_null(&self) -> bool {
self.bytes.len() == 0
}
pub fn is_empty(&self) -> bool {
!self.is_null() && (self.bytes[0] == 0xc0 || self.bytes[0] == 0x80)
}
pub fn is_list(&self) -> bool {
!self.is_null() && self.bytes[0] >= 0xc0
}
pub fn is_data(&self) -> bool {
!self.is_null() && self.bytes[0] < 0xc0
}
pub fn is_int(&self) -> bool {
if self.is_null() {
return false;
}
match self.bytes[0] {
0...0x80 => true,
0x81...0xb7 => self.bytes[1] != 0,
b @ 0xb8...0xbf => self.bytes[1 + b as usize - 0xb7] != 0,
_ => false
}
}
pub fn iter(&'view self) -> RlpIterator<'a, 'view> {
self.into_iter()
}
pub fn as_val<T>(&self) -> Result<T, DecoderError> where T: Decodable {
T::decode(self)
}
pub fn as_list<T>(&self) -> Result<Vec<T>, DecoderError> where T: Decodable {
self.iter().map(|rlp| rlp.as_val()).collect()
}
pub fn val_at<T>(&self, index: usize) -> Result<T, DecoderError> where T: Decodable {
self.at(index)?.as_val()
}
pub fn list_at<T>(&self, index: usize) -> Result<Vec<T>, DecoderError> where T: Decodable {
self.at(index)?.as_list()
}
pub fn decoder(&self) -> BasicDecoder {
BasicDecoder::new(self.clone())
}
/// consumes first found prefix
fn consume_list_payload(&self) -> Result<&'a [u8], DecoderError> {
let item = BasicDecoder::payload_info(self.bytes)?;
let bytes = Rlp::consume(self.bytes, item.header_len)?;
Ok(bytes)
}
/// consumes fixed number of items
fn consume_items(bytes: &'a [u8], items: usize) -> Result<&'a [u8], DecoderError> {
let mut result = bytes;
for _ in 0..items {
let i = BasicDecoder::payload_info(result)?;
result = Rlp::consume(result, i.header_len + i.value_len)?;
}
Ok(result)
}
/// consumes slice prefix of length `len`
fn consume(bytes: &'a [u8], len: usize) -> Result<&'a [u8], DecoderError> {
match bytes.len() >= len {
true => Ok(&bytes[len..]),
false => Err(DecoderError::RlpIsTooShort),
}
}
}
/// Iterator over rlp-slice list elements.
pub struct RlpIterator<'a, 'view> where 'a: 'view {
rlp: &'view Rlp<'a>,
index: usize,
}
impl<'a, 'view> IntoIterator for &'view Rlp<'a> where 'a: 'view {
type Item = Rlp<'a>;
type IntoIter = RlpIterator<'a, 'view>;
fn into_iter(self) -> Self::IntoIter {
RlpIterator {
rlp: self,
index: 0,
}
}
}
impl<'a, 'view> Iterator for RlpIterator<'a, 'view> {
type Item = Rlp<'a>;
fn next(&mut self) -> Option<Rlp<'a>> {
let index = self.index;
let result = self.rlp.at(index).ok();
self.index += 1;
result
}
}
pub struct BasicDecoder<'a> {
rlp: Rlp<'a>
}
impl<'a> BasicDecoder<'a> {
pub fn new(rlp: Rlp<'a>) -> BasicDecoder<'a> {
BasicDecoder {
rlp: rlp
}
}
/// Return first item info.
fn payload_info(bytes: &[u8]) -> Result<PayloadInfo, DecoderError> {
let item = PayloadInfo::from(bytes)?;
match item.header_len.checked_add(item.value_len) {
Some(x) if x <= bytes.len() => Ok(item),
_ => Err(DecoderError::RlpIsTooShort),
}
}
pub fn decode_value<T, F>(&self, f: F) -> Result<T, DecoderError>
where F: Fn(&[u8]) -> Result<T, DecoderError> {
let bytes = self.rlp.as_raw();
match bytes.first().cloned() {
// RLP is too short.
None => Err(DecoderError::RlpIsTooShort),
// Single byte value.
Some(l @ 0...0x7f) => Ok(f(&[l])?),
// 0-55 bytes
Some(l @ 0x80...0xb7) => {
let last_index_of = 1 + l as usize - 0x80;
if bytes.len() < last_index_of {
return Err(DecoderError::RlpInconsistentLengthAndData);
}
let d = &bytes[1..last_index_of];
if l == 0x81 && d[0] < 0x80 {
return Err(DecoderError::RlpInvalidIndirection);
}
Ok(f(d)?)
},
// Longer than 55 bytes.
Some(l @ 0xb8...0xbf) => {
let len_of_len = l as usize - 0xb7;
let begin_of_value = 1 as usize + len_of_len;
if bytes.len() < begin_of_value {
return Err(DecoderError::RlpInconsistentLengthAndData);
}
let len = decode_usize(&bytes[1..begin_of_value])?;
let last_index_of_value = begin_of_value.checked_add(len)
.ok_or(DecoderError::RlpInvalidLength)?;
if bytes.len() < last_index_of_value {
return Err(DecoderError::RlpInconsistentLengthAndData);
}
Ok(f(&bytes[begin_of_value..last_index_of_value])?)
}
// We are reading value, not a list!
_ => Err(DecoderError::RlpExpectedToBeData)
}
}
}
#[cfg(test)]
mod tests {
use {Rlp, DecoderError};
#[test]
fn test_rlp_display() {
use rustc_hex::FromHex;
let data = "f84d0589010efbef67941f79b2a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a0c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470".from_hex().unwrap();
let rlp = Rlp::new(&data);
assert_eq!(format!("{}", rlp), "[\"0x05\", \"0x010efbef67941f79b2\", \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\", \"0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470\"]");
}
#[test]
fn length_overflow() {
let bs = [0xbf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe5];
let rlp = Rlp::new(&bs);
let res: Result<u8, DecoderError> = rlp.as_val();
assert_eq!(Err(DecoderError::RlpInvalidLength), res);
}
}

380
rlp/src/stream.rs Normal file
View File

@ -0,0 +1,380 @@
// Copyright 2015-2017 Parity Technologies
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::borrow::Borrow;
use byteorder::{ByteOrder, BigEndian};
use elastic_array::{ElasticArray16, ElasticArray1024};
use traits::Encodable;
#[derive(Debug, Copy, Clone)]
struct ListInfo {
position: usize,
current: usize,
max: Option<usize>,
}
impl ListInfo {
fn new(position: usize, max: Option<usize>) -> ListInfo {
ListInfo {
position: position,
current: 0,
max: max,
}
}
}
/// Appendable rlp encoder.
pub struct RlpStream {
unfinished_lists: ElasticArray16<ListInfo>,
buffer: ElasticArray1024<u8>,
finished_list: bool,
}
impl Default for RlpStream {
fn default() -> Self {
RlpStream::new()
}
}
impl RlpStream {
/// Initializes instance of empty `Stream`.
pub fn new() -> Self {
RlpStream {
unfinished_lists: ElasticArray16::new(),
buffer: ElasticArray1024::new(),
finished_list: false,
}
}
/// Initializes the `Stream` as a list.
pub fn new_list(len: usize) -> Self {
let mut stream = RlpStream::new();
stream.begin_list(len);
stream
}
/// Apends null to the end of stream, chainable.
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let mut stream = RlpStream::new_list(2);
/// stream.append_empty_data().append_empty_data();
/// let out = stream.out();
/// assert_eq!(out, vec![0xc2, 0x80, 0x80]);
/// }
/// ```
pub fn append_empty_data(&mut self) -> &mut Self {
// self push raw item
self.buffer.push(0x80);
// try to finish and prepend the length
self.note_appended(1);
// return chainable self
self
}
/// Drain the object and return the underlying ElasticArray. Panics if it is not finished.
pub fn drain(self) -> ElasticArray1024<u8> {
match self.is_finished() {
true => self.buffer,
false => panic!()
}
}
/// Appends raw (pre-serialised) RLP data. Use with caution. Chainable.
pub fn append_raw<'a>(&'a mut self, bytes: &[u8], item_count: usize) -> &'a mut Self {
// push raw items
self.buffer.append_slice(bytes);
// try to finish and prepend the length
self.note_appended(item_count);
// return chainable self
self
}
/// Appends value to the end of stream, chainable.
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let mut stream = RlpStream::new_list(2);
/// stream.append(&"cat").append(&"dog");
/// let out = stream.out();
/// assert_eq!(out, vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g']);
/// }
/// ```
pub fn append<'a, E>(&'a mut self, value: &E) -> &'a mut Self where E: Encodable {
self.finished_list = false;
value.rlp_append(self);
if !self.finished_list {
self.note_appended(1);
}
self
}
/// Appends list of values to the end of stream, chainable.
pub fn append_list<'a, E, K>(&'a mut self, values: &[K]) -> &'a mut Self where E: Encodable, K: Borrow<E> {
self.begin_list(values.len());
for value in values {
self.append(value.borrow());
}
self
}
/// Appends value to the end of stream, but do not count it as an appended item.
/// It's useful for wrapper types
pub fn append_internal<'a, E>(&'a mut self, value: &E) -> &'a mut Self where E: Encodable {
value.rlp_append(self);
self
}
/// Declare appending the list of given size, chainable.
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let mut stream = RlpStream::new_list(2);
/// stream.begin_list(2).append(&"cat").append(&"dog");
/// stream.append(&"");
/// let out = stream.out();
/// assert_eq!(out, vec![0xca, 0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g', 0x80]);
/// }
/// ```
pub fn begin_list(&mut self, len: usize) -> &mut RlpStream {
self.finished_list = false;
match len {
0 => {
// we may finish, if the appended list len is equal 0
self.buffer.push(0xc0u8);
self.note_appended(1);
self.finished_list = true;
},
_ => {
// payload is longer than 1 byte only for lists > 55 bytes
// by pushing always this 1 byte we may avoid unnecessary shift of data
self.buffer.push(0);
let position = self.buffer.len();
self.unfinished_lists.push(ListInfo::new(position, Some(len)));
},
}
// return chainable self
self
}
/// Declare appending the list of unknown size, chainable.
pub fn begin_unbounded_list(&mut self) -> &mut RlpStream {
self.finished_list = false;
// payload is longer than 1 byte only for lists > 55 bytes
// by pushing always this 1 byte we may avoid unnecessary shift of data
self.buffer.push(0);
let position = self.buffer.len();
self.unfinished_lists.push(ListInfo::new(position, None));
// return chainable self
self
}
/// Appends raw (pre-serialised) RLP data. Checks for size oveflow.
pub fn append_raw_checked<'a>(&'a mut self, bytes: &[u8], item_count: usize, max_size: usize) -> bool {
if self.estimate_size(bytes.len()) > max_size {
return false;
}
self.append_raw(bytes, item_count);
true
}
/// Calculate total RLP size for appended payload.
pub fn estimate_size<'a>(&'a self, add: usize) -> usize {
let total_size = self.buffer.len() + add;
let mut base_size = total_size;
for list in &self.unfinished_lists[..] {
let len = total_size - list.position;
if len > 55 {
let leading_empty_bytes = (len as u64).leading_zeros() as usize / 8;
let size_bytes = 8 - leading_empty_bytes;
base_size += size_bytes;
}
}
base_size
}
/// Returns current RLP size in bytes for the data pushed into the list.
pub fn len<'a>(&'a self) -> usize {
self.estimate_size(0)
}
/// Clear the output stream so far.
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let mut stream = RlpStream::new_list(3);
/// stream.append(&"cat");
/// stream.clear();
/// stream.append(&"dog");
/// let out = stream.out();
/// assert_eq!(out, vec![0x83, b'd', b'o', b'g']);
/// }
pub fn clear(&mut self) {
// clear bytes
self.buffer.clear();
// clear lists
self.unfinished_lists.clear();
}
/// Returns true if stream doesnt expect any more items.
///
/// ```rust
/// extern crate rlp;
/// use rlp::*;
///
/// fn main () {
/// let mut stream = RlpStream::new_list(2);
/// stream.append(&"cat");
/// assert_eq!(stream.is_finished(), false);
/// stream.append(&"dog");
/// assert_eq!(stream.is_finished(), true);
/// let out = stream.out();
/// assert_eq!(out, vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g']);
/// }
pub fn is_finished(&self) -> bool {
self.unfinished_lists.len() == 0
}
/// Get raw encoded bytes
pub fn as_raw(&self) -> &[u8] {
//&self.encoder.bytes
&self.buffer
}
/// Streams out encoded bytes.
///
/// panic! if stream is not finished.
pub fn out(self) -> Vec<u8> {
match self.is_finished() {
//true => self.encoder.out().into_vec(),
true => self.buffer.into_vec(),
false => panic!()
}
}
/// Try to finish lists
fn note_appended(&mut self, inserted_items: usize) -> () {
if self.unfinished_lists.len() == 0 {
return;
}
let back = self.unfinished_lists.len() - 1;
let should_finish = match self.unfinished_lists.get_mut(back) {
None => false,
Some(ref mut x) => {
x.current += inserted_items;
match x.max {
Some(ref max) if x.current > *max => panic!("You cannot append more items then you expect!"),
Some(ref max) => x.current == *max,
_ => false,
}
}
};
if should_finish {
let x = self.unfinished_lists.pop().unwrap();
let len = self.buffer.len() - x.position;
self.encoder().insert_list_payload(len, x.position);
self.note_appended(1);
}
self.finished_list = should_finish;
}
pub fn encoder(&mut self) -> BasicEncoder {
BasicEncoder::new(self)
}
/// Finalize current ubnbound list. Panics if no unbounded list has been opened.
pub fn complete_unbounded_list(&mut self) {
let list = self.unfinished_lists.pop().expect("No open list.");
if list.max.is_some() {
panic!("List type mismatch.");
}
let len = self.buffer.len() - list.position;
self.encoder().insert_list_payload(len, list.position);
self.note_appended(1);
}
}
pub struct BasicEncoder<'a> {
buffer: &'a mut ElasticArray1024<u8>,
}
impl<'a> BasicEncoder<'a> {
fn new(stream: &'a mut RlpStream) -> Self {
BasicEncoder {
buffer: &mut stream.buffer
}
}
fn insert_size(&mut self, size: usize, position: usize) -> u8 {
let size = size as u32;
let leading_empty_bytes = size.leading_zeros() as usize / 8;
let size_bytes = 4 - leading_empty_bytes as u8;
let mut buffer = [0u8; 4];
BigEndian::write_u32(&mut buffer, size);
self.buffer.insert_slice(position, &buffer[leading_empty_bytes..]);
size_bytes as u8
}
/// Inserts list prefix at given position
fn insert_list_payload(&mut self, len: usize, pos: usize) {
// 1 byte was already reserved for payload earlier
match len {
0...55 => {
self.buffer[pos - 1] = 0xc0u8 + len as u8;
},
_ => {
let inserted_bytes = self.insert_size(len, pos);
self.buffer[pos - 1] = 0xf7u8 + inserted_bytes;
}
};
}
/// Pushes encoded value to the end of buffer
pub fn encode_value(&mut self, value: &[u8]) {
match value.len() {
// just 0
0 => self.buffer.push(0x80u8),
// byte is its own encoding if < 0x80
1 if value[0] < 0x80 => self.buffer.push(value[0]),
// (prefix + length), followed by the string
len @ 1 ... 55 => {
self.buffer.push(0x80u8 + len as u8);
self.buffer.append_slice(value);
}
// (prefix + length of length), followed by the length, followd by the string
len => {
self.buffer.push(0);
let position = self.buffer.len();
let inserted_bytes = self.insert_size(len, position);
self.buffer[position - 1] = 0xb7 + inserted_bytes;
self.buffer.append_slice(value);
}
}
}
}

30
rlp/src/traits.rs Normal file
View File

@ -0,0 +1,30 @@
// Copyright 2015-2017 Parity Technologies
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Common RLP traits
use elastic_array::ElasticArray1024;
use {DecoderError, Rlp, RlpStream};
/// RLP decodable trait
pub trait Decodable: Sized {
/// Decode a value from RLP bytes
fn decode(rlp: &Rlp) -> Result<Self, DecoderError>;
}
/// Structure encodable to RLP
pub trait Encodable {
/// Append a value to the stream
fn rlp_append(&self, s: &mut RlpStream);
/// Get rlp-encoded bytes for this instance
fn rlp_bytes(&self) -> ElasticArray1024<u8> {
let mut s = RlpStream::new();
self.rlp_append(&mut s);
s.drain()
}
}

425
rlp/tests/tests.rs Normal file
View File

@ -0,0 +1,425 @@
// Copyright 2015-2017 Parity Technologies
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern crate ethereum_types as bigint;
extern crate rlp;
use std::{fmt, cmp};
use bigint::{U256, H160};
use rlp::{Encodable, Decodable, Rlp, RlpStream, DecoderError};
#[test]
fn rlp_at() {
let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g'];
{
let rlp = Rlp::new(&data);
assert!(rlp.is_list());
let animals: Vec<String> = rlp.as_list().unwrap();
assert_eq!(animals, vec!["cat".to_owned(), "dog".to_owned()]);
let cat = rlp.at(0).unwrap();
assert!(cat.is_data());
assert_eq!(cat.as_raw(), &[0x83, b'c', b'a', b't']);
assert_eq!(cat.as_val::<String>().unwrap(), "cat".to_owned());
let dog = rlp.at(1).unwrap();
assert!(dog.is_data());
assert_eq!(dog.as_raw(), &[0x83, b'd', b'o', b'g']);
assert_eq!(dog.as_val::<String>().unwrap(), "dog".to_owned());
let cat_again = rlp.at(0).unwrap();
assert!(cat_again.is_data());
assert_eq!(cat_again.as_raw(), &[0x83, b'c', b'a', b't']);
assert_eq!(cat_again.as_val::<String>().unwrap(), "cat".to_owned());
}
}
#[test]
fn rlp_at_err() {
let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o'];
{
let rlp = Rlp::new(&data);
assert!(rlp.is_list());
let cat_err = rlp.at(0).unwrap_err();
assert_eq!(cat_err, DecoderError::RlpIsTooShort);
let dog_err = rlp.at(1).unwrap_err();
assert_eq!(dog_err, DecoderError::RlpIsTooShort);
}
}
#[test]
fn rlp_iter() {
let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g'];
{
let rlp = Rlp::new(&data);
let mut iter = rlp.iter();
let cat = iter.next().unwrap();
assert!(cat.is_data());
assert_eq!(cat.as_raw(), &[0x83, b'c', b'a', b't']);
let dog = iter.next().unwrap();
assert!(dog.is_data());
assert_eq!(dog.as_raw(), &[0x83, b'd', b'o', b'g']);
let none = iter.next();
assert!(none.is_none());
let cat_again = rlp.at(0).unwrap();
assert!(cat_again.is_data());
assert_eq!(cat_again.as_raw(), &[0x83, b'c', b'a', b't']);
}
}
struct ETestPair<T>(T, Vec<u8>) where T: Encodable;
fn run_encode_tests<T>(tests: Vec<ETestPair<T>>)
where T: Encodable
{
for t in &tests {
let res = rlp::encode(&t.0);
assert_eq!(&res[..], &t.1[..]);
}
}
struct VETestPair<T>(Vec<T>, Vec<u8>) where T: Encodable;
fn run_encode_tests_list<T>(tests: Vec<VETestPair<T>>)
where T: Encodable
{
for t in &tests {
let res = rlp::encode_list(&t.0);
assert_eq!(&res[..], &t.1[..]);
}
}
#[test]
fn encode_u16() {
let tests = vec![
ETestPair(0u16, vec![0x80u8]),
ETestPair(0x100, vec![0x82, 0x01, 0x00]),
ETestPair(0xffff, vec![0x82, 0xff, 0xff]),
];
run_encode_tests(tests);
}
#[test]
fn encode_u32() {
let tests = vec![
ETestPair(0u32, vec![0x80u8]),
ETestPair(0x10000, vec![0x83, 0x01, 0x00, 0x00]),
ETestPair(0xffffff, vec![0x83, 0xff, 0xff, 0xff]),
];
run_encode_tests(tests);
}
#[test]
fn encode_u64() {
let tests = vec![
ETestPair(0u64, vec![0x80u8]),
ETestPair(0x1000000, vec![0x84, 0x01, 0x00, 0x00, 0x00]),
ETestPair(0xFFFFFFFF, vec![0x84, 0xff, 0xff, 0xff, 0xff]),
];
run_encode_tests(tests);
}
#[test]
fn encode_u256() {
let tests = vec![ETestPair(U256::from(0u64), vec![0x80u8]),
ETestPair(U256::from(0x1000000u64), vec![0x84, 0x01, 0x00, 0x00, 0x00]),
ETestPair(U256::from(0xffffffffu64),
vec![0x84, 0xff, 0xff, 0xff, 0xff]),
ETestPair(("8090a0b0c0d0e0f00910203040506077000000000000\
000100000000000012f0").into(),
vec![0xa0, 0x80, 0x90, 0xa0, 0xb0, 0xc0, 0xd0, 0xe0, 0xf0,
0x09, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x77, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x12, 0xf0])];
run_encode_tests(tests);
}
#[test]
fn encode_str() {
let tests = vec![ETestPair("cat", vec![0x83, b'c', b'a', b't']),
ETestPair("dog", vec![0x83, b'd', b'o', b'g']),
ETestPair("Marek", vec![0x85, b'M', b'a', b'r', b'e', b'k']),
ETestPair("", vec![0x80]),
ETestPair("Lorem ipsum dolor sit amet, consectetur adipisicing elit",
vec![0xb8, 0x38, b'L', b'o', b'r', b'e', b'm', b' ', b'i',
b'p', b's', b'u', b'm', b' ', b'd', b'o', b'l', b'o',
b'r', b' ', b's', b'i', b't', b' ', b'a', b'm', b'e',
b't', b',', b' ', b'c', b'o', b'n', b's', b'e', b'c',
b't', b'e', b't', b'u', b'r', b' ', b'a', b'd', b'i',
b'p', b'i', b's', b'i', b'c', b'i', b'n', b'g', b' ',
b'e', b'l', b'i', b't'])];
run_encode_tests(tests);
}
#[test]
fn encode_address() {
let tests = vec![
ETestPair(H160::from("ef2d6d194084c2de36e0dabfce45d046b37d1106"),
vec![0x94, 0xef, 0x2d, 0x6d, 0x19, 0x40, 0x84, 0xc2, 0xde,
0x36, 0xe0, 0xda, 0xbf, 0xce, 0x45, 0xd0, 0x46,
0xb3, 0x7d, 0x11, 0x06])
];
run_encode_tests(tests);
}
/// Vec<u8> (Bytes) is treated as a single value
#[test]
fn encode_vector_u8() {
let tests = vec![
ETestPair(vec![], vec![0x80]),
ETestPair(vec![0u8], vec![0]),
ETestPair(vec![0x15], vec![0x15]),
ETestPair(vec![0x40, 0x00], vec![0x82, 0x40, 0x00]),
];
run_encode_tests(tests);
}
#[test]
fn encode_vector_u64() {
let tests = vec![
VETestPair(vec![], vec![0xc0]),
VETestPair(vec![15u64], vec![0xc1, 0x0f]),
VETestPair(vec![1, 2, 3, 7, 0xff], vec![0xc6, 1, 2, 3, 7, 0x81, 0xff]),
VETestPair(vec![0xffffffff, 1, 2, 3, 7, 0xff], vec![0xcb, 0x84, 0xff, 0xff, 0xff, 0xff, 1, 2, 3, 7, 0x81, 0xff]),
];
run_encode_tests_list(tests);
}
#[test]
fn encode_vector_str() {
let tests = vec![VETestPair(vec!["cat", "dog"],
vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g'])];
run_encode_tests_list(tests);
}
struct DTestPair<T>(T, Vec<u8>) where T: Decodable + fmt::Debug + cmp::Eq;
struct VDTestPair<T>(Vec<T>, Vec<u8>) where T: Decodable + fmt::Debug + cmp::Eq;
fn run_decode_tests<T>(tests: Vec<DTestPair<T>>) where T: Decodable + fmt::Debug + cmp::Eq {
for t in &tests {
let res : Result<T, DecoderError> = rlp::decode(&t.1);
assert!(res.is_ok());
let res = res.unwrap();
assert_eq!(&res, &t.0);
}
}
fn run_decode_tests_list<T>(tests: Vec<VDTestPair<T>>) where T: Decodable + fmt::Debug + cmp::Eq {
for t in &tests {
let res: Vec<T> = rlp::decode_list(&t.1);
assert_eq!(res, t.0);
}
}
/// Vec<u8> (Bytes) is treated as a single value
#[test]
fn decode_vector_u8() {
let tests = vec![
DTestPair(vec![], vec![0x80]),
DTestPair(vec![0u8], vec![0]),
DTestPair(vec![0x15], vec![0x15]),
DTestPair(vec![0x40, 0x00], vec![0x82, 0x40, 0x00]),
];
run_decode_tests(tests);
}
#[test]
fn decode_untrusted_u8() {
let tests = vec![
DTestPair(0x0u8, vec![0x80]),
DTestPair(0x77u8, vec![0x77]),
DTestPair(0xccu8, vec![0x81, 0xcc]),
];
run_decode_tests(tests);
}
#[test]
fn decode_untrusted_u16() {
let tests = vec![
DTestPair(0x100u16, vec![0x82, 0x01, 0x00]),
DTestPair(0xffffu16, vec![0x82, 0xff, 0xff]),
];
run_decode_tests(tests);
}
#[test]
fn decode_untrusted_u32() {
let tests = vec![
DTestPair(0x10000u32, vec![0x83, 0x01, 0x00, 0x00]),
DTestPair(0xffffffu32, vec![0x83, 0xff, 0xff, 0xff]),
];
run_decode_tests(tests);
}
#[test]
fn decode_untrusted_u64() {
let tests = vec![
DTestPair(0x1000000u64, vec![0x84, 0x01, 0x00, 0x00, 0x00]),
DTestPair(0xFFFFFFFFu64, vec![0x84, 0xff, 0xff, 0xff, 0xff]),
];
run_decode_tests(tests);
}
#[test]
fn decode_untrusted_u256() {
let tests = vec![DTestPair(U256::from(0u64), vec![0x80u8]),
DTestPair(U256::from(0x1000000u64), vec![0x84, 0x01, 0x00, 0x00, 0x00]),
DTestPair(U256::from(0xffffffffu64),
vec![0x84, 0xff, 0xff, 0xff, 0xff]),
DTestPair(("8090a0b0c0d0e0f00910203040506077000000000000\
000100000000000012f0").into(),
vec![0xa0, 0x80, 0x90, 0xa0, 0xb0, 0xc0, 0xd0, 0xe0, 0xf0,
0x09, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x77, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x12, 0xf0])];
run_decode_tests(tests);
}
#[test]
fn decode_untrusted_str() {
let tests = vec![DTestPair("cat".to_owned(), vec![0x83, b'c', b'a', b't']),
DTestPair("dog".to_owned(), vec![0x83, b'd', b'o', b'g']),
DTestPair("Marek".to_owned(),
vec![0x85, b'M', b'a', b'r', b'e', b'k']),
DTestPair("".to_owned(), vec![0x80]),
DTestPair("Lorem ipsum dolor sit amet, consectetur adipisicing elit"
.to_owned(),
vec![0xb8, 0x38, b'L', b'o', b'r', b'e', b'm', b' ', b'i',
b'p', b's', b'u', b'm', b' ', b'd', b'o', b'l', b'o',
b'r', b' ', b's', b'i', b't', b' ', b'a', b'm', b'e',
b't', b',', b' ', b'c', b'o', b'n', b's', b'e', b'c',
b't', b'e', b't', b'u', b'r', b' ', b'a', b'd', b'i',
b'p', b'i', b's', b'i', b'c', b'i', b'n', b'g', b' ',
b'e', b'l', b'i', b't'])];
run_decode_tests(tests);
}
#[test]
fn decode_untrusted_address() {
let tests = vec![
DTestPair(H160::from("ef2d6d194084c2de36e0dabfce45d046b37d1106"),
vec![0x94, 0xef, 0x2d, 0x6d, 0x19, 0x40, 0x84, 0xc2, 0xde,
0x36, 0xe0, 0xda, 0xbf, 0xce, 0x45, 0xd0, 0x46,
0xb3, 0x7d, 0x11, 0x06])
];
run_decode_tests(tests);
}
#[test]
fn decode_untrusted_vector_u64() {
let tests = vec![
VDTestPair(vec![], vec![0xc0]),
VDTestPair(vec![15u64], vec![0xc1, 0x0f]),
VDTestPair(vec![1, 2, 3, 7, 0xff], vec![0xc6, 1, 2, 3, 7, 0x81, 0xff]),
VDTestPair(vec![0xffffffff, 1, 2, 3, 7, 0xff], vec![0xcb, 0x84, 0xff, 0xff, 0xff, 0xff, 1, 2, 3, 7, 0x81, 0xff]),
];
run_decode_tests_list(tests);
}
#[test]
fn decode_untrusted_vector_str() {
let tests = vec![VDTestPair(vec!["cat".to_owned(), "dog".to_owned()],
vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g'])];
run_decode_tests_list(tests);
}
#[test]
fn test_rlp_data_length_check()
{
let data = vec![0x84, b'c', b'a', b't'];
let rlp = Rlp::new(&data);
let as_val: Result<String, DecoderError> = rlp.as_val();
assert_eq!(Err(DecoderError::RlpInconsistentLengthAndData), as_val);
}
#[test]
fn test_rlp_long_data_length_check()
{
let mut data: Vec<u8> = vec![0xb8, 255];
for _ in 0..253 {
data.push(b'c');
}
let rlp = Rlp::new(&data);
let as_val: Result<String, DecoderError> = rlp.as_val();
assert_eq!(Err(DecoderError::RlpInconsistentLengthAndData), as_val);
}
#[test]
fn test_the_exact_long_string()
{
let mut data: Vec<u8> = vec![0xb8, 255];
for _ in 0..255 {
data.push(b'c');
}
let rlp = Rlp::new(&data);
let as_val: Result<String, DecoderError> = rlp.as_val();
assert!(as_val.is_ok());
}
#[test]
fn test_rlp_2bytes_data_length_check()
{
let mut data: Vec<u8> = vec![0xb9, 2, 255]; // 512+255
for _ in 0..700 {
data.push(b'c');
}
let rlp = Rlp::new(&data);
let as_val: Result<String, DecoderError> = rlp.as_val();
assert_eq!(Err(DecoderError::RlpInconsistentLengthAndData), as_val);
}
#[test]
fn test_rlp_nested_empty_list_encode() {
let mut stream = RlpStream::new_list(2);
stream.append_list(&(Vec::new() as Vec<u32>));
stream.append(&40u32);
assert_eq!(stream.drain()[..], [0xc2u8, 0xc0u8, 40u8][..]);
}
#[test]
fn test_rlp_list_length_overflow() {
let data: Vec<u8> = vec![0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00];
let rlp = Rlp::new(&data);
let as_val: Result<String, DecoderError> = rlp.val_at(0);
assert_eq!(Err(DecoderError::RlpIsTooShort), as_val);
}
#[test]
fn test_rlp_stream_size_limit() {
for limit in 40 .. 270 {
let item = [0u8; 1];
let mut stream = RlpStream::new();
while stream.append_raw_checked(&item, 1, limit) {}
assert_eq!(stream.drain().len(), limit);
}
}
#[test]
fn test_rlp_stream_unbounded_list() {
let mut stream = RlpStream::new();
stream.begin_unbounded_list();
stream.append(&40u32);
stream.append(&41u32);
assert!(!stream.is_finished());
stream.complete_unbounded_list();
assert!(stream.is_finished());
}