aboutsummaryrefslogtreecommitdiff
path: root/src/transaction
diff options
context:
space:
mode:
Diffstat (limited to 'src/transaction')
-rw-r--r--src/transaction/accesslist.rs105
-rw-r--r--src/transaction/eip1559.rs194
-rw-r--r--src/transaction/eip2930.rs180
-rw-r--r--src/transaction/legacy.rs148
-rw-r--r--src/transaction/rlp.rs98
5 files changed, 725 insertions, 0 deletions
diff --git a/src/transaction/accesslist.rs b/src/transaction/accesslist.rs
new file mode 100644
index 0000000..507b73e
--- /dev/null
+++ b/src/transaction/accesslist.rs
@@ -0,0 +1,105 @@
+//! Module with EIP-2930 access list type definition with RLP encoding and JSON
+//! serialization implementation.
+
+use crate::{account::Address, serialization, transaction::rlp};
+use serde::Deserialize;
+
+/// An Ethereum virtual machine storage slot.
+#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, Hash, Ord, PartialOrd, PartialEq)]
+#[serde(transparent)]
+pub struct StorageSlot(#[serde(with = "serialization::bytearray")] pub [u8; 32]);
+
+impl StorageSlot {
+ /// RLP encodes a storage slot.
+ pub fn rlp_encode(&self) -> Vec<u8> {
+ rlp::bytes(&self.0)
+ }
+}
+
+/// An EIP-2930 access list.
+#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
+#[serde(transparent)]
+pub struct AccessList(pub Vec<(Address, Vec<StorageSlot>)>);
+
+impl AccessList {
+ /// RLP encodes a storage slot.
+ pub fn rlp_encode(&self) -> Vec<u8> {
+ rlp::iter(self.0.iter().map(|(address, slots)| {
+ rlp::list(&[
+ &rlp::bytes(&**address),
+ &rlp::iter(slots.iter().map(StorageSlot::rlp_encode)),
+ ])
+ }))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use hex_literal::hex;
+ use serde_json::json;
+
+ #[test]
+ fn deserialize_json() {
+ assert_eq!(
+ serde_json::from_value::<AccessList>(json!([
+ [
+ "0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae",
+ [
+ "0x0000000000000000000000000000000000000000000000000000000000000003",
+ "0x0000000000000000000000000000000000000000000000000000000000000007",
+ ]
+ ],
+ ["0xbb9bc244d798123fde783fcc1c72d3bb8c189413", [],],
+ ]))
+ .unwrap(),
+ AccessList(vec![
+ (
+ Address(hex!("de0b295669a9fd93d5f28d9ec85e40f4cb697bae")),
+ vec![
+ StorageSlot(hex!(
+ "0000000000000000000000000000000000000000000000000000000000000003"
+ )),
+ StorageSlot(hex!(
+ "0000000000000000000000000000000000000000000000000000000000000007"
+ ))
+ ]
+ ),
+ (
+ Address(hex!("bb9bc244d798123fde783fcc1c72d3bb8c189413")),
+ vec![]
+ )
+ ]),
+ )
+ }
+
+ #[test]
+ fn rlp_encode() {
+ assert_eq!(
+ AccessList(vec![
+ (
+ Address(hex!("de0b295669a9fd93d5f28d9ec85e40f4cb697bae")),
+ vec![
+ StorageSlot(hex!(
+ "0000000000000000000000000000000000000000000000000000000000000003"
+ )),
+ StorageSlot(hex!(
+ "0000000000000000000000000000000000000000000000000000000000000007"
+ ))
+ ]
+ ),
+ (
+ Address(hex!("bb9bc244d798123fde783fcc1c72d3bb8c189413")),
+ vec![]
+ )
+ ])
+ .rlp_encode(),
+ hex!(
+ "f872f85994de0b295669a9fd93d5f28d9ec85e40f4cb697baef842a000000000
+ 00000000000000000000000000000000000000000000000000000003a0000000
+ 0000000000000000000000000000000000000000000000000000000007d694bb
+ 9bc244d798123fde783fcc1c72d3bb8c189413c0"
+ ),
+ );
+ }
+}
diff --git a/src/transaction/eip1559.rs b/src/transaction/eip1559.rs
new file mode 100644
index 0000000..d8fa713
--- /dev/null
+++ b/src/transaction/eip1559.rs
@@ -0,0 +1,194 @@
+//! EIp-1559 Ethereum transaction with base gas pricing type definition and RLP encoding.
+
+use crate::{
+ account::{Address, Signature},
+ serialization,
+ transaction::accesslist::AccessList,
+ transaction::rlp,
+};
+use ethnum::{AsU256 as _, U256};
+use serde::Deserialize;
+
+/// An EIP-1559 Ethereum transaction.
+#[derive(Clone, Debug, Deserialize, PartialEq)]
+pub struct Eip1559Transaction {
+ /// The chain ID for the transaction.
+ #[serde(rename = "chainId")]
+ #[serde(with = "serialization::u256")]
+ pub chain_id: U256,
+ /// The nonce for the transaction.
+ #[serde(with = "serialization::u256")]
+ pub nonce: U256,
+ /// The gas price in Wei for the transaction.
+ #[serde(rename = "maxPriorityFeePerGas")]
+ #[serde(with = "serialization::u256")]
+ pub max_priority_fee_per_gas: U256,
+ #[serde(rename = "maxFeePerGas")]
+ #[serde(with = "serialization::u256")]
+ pub max_fee_per_gas: U256,
+ /// The gas limit for the transaction.
+ #[serde(rename = "gasLimit")]
+ #[serde(with = "serialization::u256")]
+ pub gas_limit: U256,
+ /// The target address for the transaction. This can also be `None` to
+ /// indicate a contract creation transaction.
+ pub to: Option<Address>,
+ /// The amount of Ether to send with the transaction.
+ #[serde(with = "serialization::u256")]
+ pub value: U256,
+ /// The calldata to use for the transaction.
+ #[serde(with = "serialization::bytes")]
+ pub data: Vec<u8>,
+ /// List of addresses and storage keys that the transaction plans to access.
+ #[serde(default)]
+ #[serde(rename = "accessList")]
+ pub access_list: AccessList,
+}
+
+impl Eip1559Transaction {
+ /// Returns the RLP encoded transaction with an optional signature.
+ pub fn rlp_encode(&self, signature: Option<Signature>) -> Vec<u8> {
+ let fields = [
+ rlp::uint(self.chain_id),
+ rlp::uint(self.nonce),
+ rlp::uint(self.max_priority_fee_per_gas),
+ rlp::uint(self.max_fee_per_gas),
+ rlp::uint(self.gas_limit),
+ self.to
+ .map_or_else(|| rlp::bytes(b""), |to| rlp::bytes(&*to)),
+ rlp::uint(self.value),
+ rlp::bytes(&self.data),
+ self.access_list.rlp_encode(),
+ ];
+
+ let tail = signature.map(|signature| {
+ [
+ rlp::uint(signature.y_parity.as_u256()),
+ rlp::uint(U256::from_be_bytes(signature.r)),
+ rlp::uint(U256::from_be_bytes(signature.s)),
+ ]
+ });
+
+ [
+ &[0x02][..],
+ &rlp::iter(fields.iter().chain(tail.iter().flatten())),
+ ]
+ .concat()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::transaction::accesslist::StorageSlot;
+ use hex_literal::hex;
+ use serde_json::json;
+
+ #[test]
+ fn deserialize_json() {
+ let mut tx = json!({
+ "chainId": "0xff",
+ "nonce": 42,
+ "maxPriorityFeePerGas": 13.37e9,
+ "maxFeePerGas": 42e9,
+ "gasLimit": 21000,
+ "value": "13370000000000000000",
+ "data": "0x",
+ });
+ assert_eq!(
+ serde_json::from_value::<Eip1559Transaction>(tx.clone()).unwrap(),
+ Eip1559Transaction {
+ chain_id: 255.as_u256(),
+ nonce: 42.as_u256(),
+ max_priority_fee_per_gas: 13.37e9.as_u256(),
+ max_fee_per_gas: 42e9.as_u256(),
+ gas_limit: 21_000.as_u256(),
+ to: None,
+ value: 13.37e18.as_u256(),
+ data: vec![],
+ access_list: AccessList::default(),
+ }
+ );
+
+ tx["to"] = json!("0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef");
+ tx["accessList"] = json!([[
+ "0x0000000000000000000000000000000000000000",
+ ["0x0000000000000000000000000000000000000000000000000000000000000000",],
+ ]]);
+ let deserialized = serde_json::from_value::<Eip1559Transaction>(tx).unwrap();
+ assert_eq!(
+ deserialized.to.unwrap(),
+ Address(hex!("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef")),
+ );
+ assert_eq!(
+ deserialized.access_list,
+ AccessList(vec![(Address::default(), vec![StorageSlot::default()])]),
+ );
+ }
+
+ #[test]
+ fn encode() {
+ assert_eq!(
+ Eip1559Transaction {
+ chain_id: 1.as_u256(),
+ nonce: 66.as_u256(),
+ max_priority_fee_per_gas: 28e9.as_u256(),
+ max_fee_per_gas: 42e9.as_u256(),
+ gas_limit: 30_000.as_u256(),
+ to: Some(Address(hex!("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef"))),
+ value: 13.37e18.as_u256(),
+ data: vec![],
+ access_list: AccessList::default(),
+ }
+ .rlp_encode(None),
+ hex!(
+ "02f10142850684ee18008509c765240082753094deadbeefdeadbeefdeadbeefdeadbeefde
+ adbeef88b98bc829a6f9000080c0"
+ )
+ .to_owned(),
+ );
+ assert_eq!(
+ Eip1559Transaction {
+ chain_id: 1.as_u256(),
+ nonce: 777.as_u256(),
+ max_priority_fee_per_gas: 28e9.as_u256(),
+ max_fee_per_gas: 42e9.as_u256(),
+ gas_limit: 100_000.as_u256(),
+ to: None,
+ value: 0.as_u256(),
+ data: hex!(
+ "363d3d373d3d3d363d73deadbeefdeadbeefdeadbeefdeadbeefdeadbeef5af43d82803e90
+ 3d91602b57fd5bf3"
+ )
+ .to_vec(),
+ access_list: AccessList(vec![
+ (
+ Address(hex!("1111111111111111111111111111111111111111")),
+ vec![
+ StorageSlot(hex!(
+ "a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0"
+ )),
+ StorageSlot(hex!(
+ "a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1"
+ )),
+ ],
+ ),
+ (
+ Address(hex!("2222222222222222222222222222222222222222")),
+ vec![],
+ ),
+ ]),
+ }
+ .rlp_encode(None),
+ hex!(
+ "02f8b801820309850684ee18008509c7652400830186a08080ad363d3d373d3d
+ 3d363d73deadbeefdeadbeefdeadbeefdeadbeefdeadbeef5af43d82803e903d
+ 91602b57fd5bf3f872f859941111111111111111111111111111111111111111
+ f842a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0
+ a0a0a0a0a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1
+ a1a1a1a1d6942222222222222222222222222222222222222222c0"
+ )
+ .to_vec(),
+ );
+ }
+}
diff --git a/src/transaction/eip2930.rs b/src/transaction/eip2930.rs
new file mode 100644
index 0000000..17ba2a1
--- /dev/null
+++ b/src/transaction/eip2930.rs
@@ -0,0 +1,180 @@
+//! EIp-2930 Ethereum transaction with access list type definition and RLP encoding.
+
+use crate::{
+ account::{Address, Signature},
+ serialization,
+ transaction::accesslist::AccessList,
+ transaction::rlp,
+};
+use ethnum::{AsU256 as _, U256};
+use serde::Deserialize;
+
+/// An EIP-2930 Ethereum transaction.
+#[derive(Clone, Debug, Deserialize, PartialEq)]
+pub struct Eip2930Transaction {
+ /// The chain ID for the transaction.
+ #[serde(rename = "chainId")]
+ #[serde(with = "serialization::u256")]
+ pub chain_id: U256,
+ /// The nonce for the transaction.
+ #[serde(with = "serialization::u256")]
+ pub nonce: U256,
+ /// The gas price in Wei for the transaction.
+ #[serde(rename = "gasPrice")]
+ #[serde(with = "serialization::u256")]
+ pub gas_price: U256,
+ /// The gas limit for the transaction.
+ #[serde(rename = "gasLimit")]
+ #[serde(with = "serialization::u256")]
+ pub gas_limit: U256,
+ /// The target address for the transaction. This can also be `None` to
+ /// indicate a contract creation transaction.
+ pub to: Option<Address>,
+ /// The amount of Ether to send with the transaction.
+ #[serde(with = "serialization::u256")]
+ pub value: U256,
+ /// The calldata to use for the transaction.
+ #[serde(with = "serialization::bytes")]
+ pub data: Vec<u8>,
+ /// List of addresses and storage keys that the transaction plans to access.
+ #[serde(rename = "accessList")]
+ pub access_list: AccessList,
+}
+
+impl Eip2930Transaction {
+ /// Returns the RLP encoded transaction with an optional signature.
+ pub fn rlp_encode(&self, signature: Option<Signature>) -> Vec<u8> {
+ let fields = [
+ rlp::uint(self.chain_id),
+ rlp::uint(self.nonce),
+ rlp::uint(self.gas_price),
+ rlp::uint(self.gas_limit),
+ self.to
+ .map_or_else(|| rlp::bytes(b""), |to| rlp::bytes(&*to)),
+ rlp::uint(self.value),
+ rlp::bytes(&self.data),
+ self.access_list.rlp_encode(),
+ ];
+
+ let tail = signature.map(|signature| {
+ [
+ rlp::uint(signature.y_parity.as_u256()),
+ rlp::uint(U256::from_be_bytes(signature.r)),
+ rlp::uint(U256::from_be_bytes(signature.s)),
+ ]
+ });
+
+ [
+ &[0x01][..],
+ &rlp::iter(fields.iter().chain(tail.iter().flatten())),
+ ]
+ .concat()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::transaction::accesslist::StorageSlot;
+ use hex_literal::hex;
+ use serde_json::json;
+
+ #[test]
+ fn deserialize_json() {
+ let mut tx = json!({
+ "chainId": "0xff",
+ "nonce": 42,
+ "gasPrice": 13.37e9,
+ "gasLimit": 21000,
+ "value": "13370000000000000000",
+ "data": "0x",
+ "accessList": [],
+ });
+ assert_eq!(
+ serde_json::from_value::<Eip2930Transaction>(tx.clone()).unwrap(),
+ Eip2930Transaction {
+ chain_id: 255.as_u256(),
+ nonce: 42.as_u256(),
+ gas_price: 13.37e9.as_u256(),
+ gas_limit: 21_000.as_u256(),
+ to: None,
+ value: 13.37e18.as_u256(),
+ data: vec![],
+ access_list: AccessList::default(),
+ }
+ );
+
+ tx["to"] = json!("0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef");
+ assert_eq!(
+ serde_json::from_value::<Eip2930Transaction>(tx)
+ .unwrap()
+ .to
+ .unwrap(),
+ Address(hex!("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef")),
+ );
+ }
+
+ #[test]
+ fn encode() {
+ assert_eq!(
+ Eip2930Transaction {
+ chain_id: 1.as_u256(),
+ nonce: 66.as_u256(),
+ gas_price: 42e9.as_u256(),
+ gas_limit: 30_000.as_u256(),
+ to: Some(Address(hex!("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef"))),
+ value: 13.37e18.as_u256(),
+ data: vec![],
+ access_list: AccessList::default(),
+ }
+ .rlp_encode(None),
+ hex!(
+ "01eb01428509c765240082753094deadbeefdeadbeefdeadbeefdeadbeefdead
+ beef88b98bc829a6f9000080c0"
+ )
+ .to_owned(),
+ );
+ assert_eq!(
+ Eip2930Transaction {
+ chain_id: 1.as_u256(),
+ nonce: 777.as_u256(),
+ gas_price: 42e9.as_u256(),
+ gas_limit: 100_000.as_u256(),
+ to: None,
+ value: 0.as_u256(),
+ data: hex!(
+ "363d3d373d3d3d363d73deadbeefdeadbeefdeadbeefdeadbeefdeadbeef5af43d82803e90
+ 3d91602b57fd5bf3"
+ )
+ .to_vec(),
+ access_list: AccessList(vec![
+ (
+ Address(hex!("1111111111111111111111111111111111111111")),
+ vec![
+ StorageSlot(hex!(
+ "a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0"
+ )),
+ StorageSlot(hex!(
+ "a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1"
+ )),
+ ],
+ ),
+ (
+ Address(hex!("2222222222222222222222222222222222222222")),
+ vec![],
+ ),
+ ]),
+ }
+ .rlp_encode(None),
+ hex!(
+ "01f8b2018203098509c7652400830186a08080ad363d3d373d3d3d363d73dead
+ beefdeadbeefdeadbeefdeadbeefdeadbeef5af43d82803e903d91602b57fd5b
+ f3f872f859941111111111111111111111111111111111111111f842a0a0a0a0
+ a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a1a1
+ a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1d694
+ 2222222222222222222222222222222222222222c0"
+ )
+ .to_vec(),
+ );
+ }
+}
diff --git a/src/transaction/legacy.rs b/src/transaction/legacy.rs
new file mode 100644
index 0000000..71eb1d6
--- /dev/null
+++ b/src/transaction/legacy.rs
@@ -0,0 +1,148 @@
+//! Legacy Ethereum transaction type definition and RLP encoding.
+
+use crate::{
+ account::{Address, Signature},
+ serialization,
+ transaction::rlp,
+};
+use ethnum::{AsU256 as _, U256};
+use serde::Deserialize;
+
+/// A Legacy Ethereum transaction.
+#[derive(Clone, Debug, Deserialize, PartialEq)]
+pub struct LegacyTransaction {
+ /// The nonce for the transaction.
+ #[serde(with = "serialization::u256")]
+ pub nonce: U256,
+ /// The gas price in Wei for the transaction.
+ #[serde(rename = "gasPrice", with = "serialization::u256")]
+ pub gas_price: U256,
+ /// The gas limit for the transaction.
+ #[serde(rename = "gasLimit", with = "serialization::u256")]
+ pub gas_limit: U256,
+ /// The target address for the transaction. This can also be `None` to
+ /// indicate a contract creation transaction.
+ pub to: Option<Address>,
+ /// The amount of Ether to send with the transaction.
+ #[serde(with = "serialization::u256")]
+ pub value: U256,
+ /// The calldata to use for the transaction.
+ #[serde(with = "serialization::bytes")]
+ pub data: Vec<u8>,
+ /// Optional chain ID for the transaction.
+ #[serde(default, rename = "chainId", with = "serialization::u256::option")]
+ pub chain_id: Option<U256>,
+}
+
+impl LegacyTransaction {
+ /// Returns the RLP encoded transaction with an optional signature.
+ pub fn rlp_encode(&self, signature: Option<Signature>) -> Vec<u8> {
+ let fields = [
+ rlp::uint(self.nonce),
+ rlp::uint(self.gas_price),
+ rlp::uint(self.gas_limit),
+ self.to
+ .map_or_else(|| rlp::bytes(b""), |to| rlp::bytes(&*to)),
+ rlp::uint(self.value),
+ rlp::bytes(&self.data),
+ ];
+
+ let tail = signature
+ .map(|signature| {
+ (
+ self.chain_id.map_or(signature.v().as_u256(), |chain_id| {
+ signature.v_replay_protected(chain_id)
+ }),
+ U256::from_be_bytes(signature.r),
+ U256::from_be_bytes(signature.s),
+ )
+ })
+ .or_else(|| Some((self.chain_id?, U256::ZERO, U256::ZERO)))
+ .map(|(v, r, s)| [rlp::uint(v), rlp::uint(r), rlp::uint(s)]);
+
+ rlp::iter(fields.iter().chain(tail.iter().flatten()))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use hex_literal::hex;
+ use serde_json::json;
+
+ #[test]
+ fn deserialize_json() {
+ let mut tx = json!({
+ "chainId": "0xff",
+ "nonce": 42,
+ "gasPrice": 13.37e9,
+ "gasLimit": 21000,
+ "value": "13370000000000000000",
+ "data": "0x",
+ });
+ assert_eq!(
+ serde_json::from_value::<LegacyTransaction>(tx.clone()).unwrap(),
+ LegacyTransaction {
+ chain_id: Some(255.as_u256()),
+ nonce: 42.as_u256(),
+ gas_price: 13.37e9.as_u256(),
+ gas_limit: 21_000.as_u256(),
+ to: None,
+ value: 13.37e18.as_u256(),
+ data: vec![],
+ }
+ );
+
+ tx["to"] = json!("0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef");
+ assert_eq!(
+ serde_json::from_value::<LegacyTransaction>(tx)
+ .unwrap()
+ .to
+ .unwrap(),
+ Address(hex!("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef")),
+ );
+ }
+
+ #[test]
+ fn encode() {
+ assert_eq!(
+ LegacyTransaction {
+ chain_id: Some(1.as_u256()),
+ nonce: 66.as_u256(),
+ gas_price: 42e9.as_u256(),
+ gas_limit: 30_000.as_u256(),
+ to: Some(Address(hex!("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef"))),
+ value: 13.37e18.as_u256(),
+ data: vec![],
+ }
+ .rlp_encode(None),
+ hex!(
+ "ec428509c765240082753094deadbeefdeadbeefdeadbeefdeadbeefdeadbeef
+ 88b98bc829a6f9000080018080"
+ )
+ .to_owned(),
+ );
+ assert_eq!(
+ LegacyTransaction {
+ chain_id: Some(1.as_u256()),
+ nonce: 777.as_u256(),
+ gas_price: 42e9.as_u256(),
+ gas_limit: 100_000.as_u256(),
+ to: None,
+ value: 0.as_u256(),
+ data: hex!(
+ "363d3d373d3d3d363d73deadbeefdeadbeefdeadbeefdeadbeefdeadbeef5af43d82803e90
+ 3d91602b57fd5bf3"
+ )
+ .to_vec(),
+ }
+ .rlp_encode(None),
+ hex!(
+ "f8408203098509c7652400830186a08080ad363d3d373d3d3d363d73deadbeef
+ deadbeefdeadbeefdeadbeefdeadbeef5af43d82803e903d91602b57fd5bf301
+ 8080"
+ )
+ .to_vec(),
+ );
+ }
+}
diff --git a/src/transaction/rlp.rs b/src/transaction/rlp.rs
new file mode 100644
index 0000000..beb0747
--- /dev/null
+++ b/src/transaction/rlp.rs
@@ -0,0 +1,98 @@
+//! Tiny (and inefficient) RLP encoding implementation.
+
+use ethnum::U256;
+
+/// RLP encode a list.
+pub fn list(items: &[&[u8]]) -> Vec<u8> {
+ let total_len = items.iter().map(|item| item.len()).sum();
+ let mut buf = len(total_len, 0xc0);
+ for item in items {
+ buf.extend_from_slice(item);
+ }
+ buf
+}
+
+/// RLP encodes an iterator as a list.
+pub fn iter<U, I>(items: I) -> Vec<u8>
+where
+ U: AsRef<[u8]>,
+ I: IntoIterator<Item = U>,
+{
+ let collected = items.into_iter().collect::<Vec<_>>();
+ let items = collected.iter().map(U::as_ref).collect::<Vec<_>>();
+ list(&items)
+}
+
+/// RLP encode some bytes.
+pub fn bytes(bytes: &[u8]) -> Vec<u8> {
+ match bytes {
+ [x] if *x < 0x80 => vec![*x],
+ _ => {
+ let mut buf = len(bytes.len(), 0x80);
+ buf.extend_from_slice(bytes);
+ buf
+ }
+ }
+}
+
+/// RLP encode a length.
+pub fn len(len: usize, offset: u8) -> Vec<u8> {
+ if len < 56 {
+ vec![len as u8 + offset]
+ } else {
+ let bl_buf = len.to_be_bytes();
+ let bl = {
+ let start = len.leading_zeros() / 8;
+ &bl_buf[start as usize..]
+ };
+ let mut buf = vec![bl.len() as u8 + offset + 55];
+ buf.extend_from_slice(bl);
+ buf
+ }
+}
+
+/// RLP encode a unsigned integer. This ensures that it is shortned to its
+/// shortest little endian byte representation.
+pub fn uint(value: U256) -> Vec<u8> {
+ let start = value.leading_zeros() / 8;
+ bytes(&value.to_be_bytes()[start as usize..])
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn length_encoding() {
+ assert_eq!(len(1024, 0x80), [0xb9, 0x04, 0x00]);
+ }
+
+ #[test]
+ fn examples() {
+ // RLP encoding examples taken from the Ethereum wiki
+ // <https://eth.wiki/en/fundamentals/rlp>
+ assert_eq!(bytes(b"dog"), b"\x83dog");
+ assert_eq!(
+ list(&[&bytes(b"cat"), &bytes(b"dog")]),
+ b"\xc8\x83cat\x83dog"
+ );
+ assert_eq!(bytes(b""), [0x80]);
+ assert_eq!(list(&[]), [0xc0]);
+ assert_eq!(uint(U256::ZERO), [0x80]);
+ assert_eq!(bytes(b"\0"), [0x00]);
+ assert_eq!(uint(U256::new(15)), [0x0f]);
+ assert_eq!(uint(U256::new(1024)), [0x82, 0x04, 0x00]);
+ assert_eq!(
+ list(&[
+ &list(&[]),
+ &list(&[&list(&[])]),
+ &list(&[&list(&[]), &list(&[&list(&[])]),]),
+ ]),
+ [0xc7, 0xc0, 0xc1, 0xc0, 0xc3, 0xc0, 0xc1, 0xc0],
+ );
+ assert_eq!(
+ bytes(b"Lorem ipsum dolor sit amet, consectetur adipisicing elit"),
+ b"\xb8\x38Lorem ipsum dolor sit amet, consectetur adipisicing elit"
+ );
+ }
+}