aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorNicholas Rodrigues Lordello <[email protected]>2021-08-20 13:54:43 +0000
committerNicholas Rodrigues Lordello <[email protected]>2021-08-20 13:54:43 +0000
commitc05487949a5cb9808945b5bdd174e14fdd7e51ea (patch)
tree8d51bbe6968aae3bd99f8664f31214e84464c64d
parentf2817a2f4db1eb23fb6f422b937e161324a35d54 (diff)
Add support for multiple transaction formats
Additionally, transaction signing is now from file instead of being from command line arguments
-rw-r--r--.devcontainer/Dockerfile12
-rw-r--r--.devcontainer/devcontainer.json29
-rw-r--r--Cargo.lock45
-rw-r--r--Cargo.toml2
-rw-r--r--src/account.rs8
-rw-r--r--src/account/address.rs25
-rw-r--r--src/account/signature.rs20
-rw-r--r--src/cmd/sign.rs180
-rw-r--r--src/main.rs1
-rw-r--r--src/mnemonic.rs2
-rw-r--r--src/serialization.rs129
-rw-r--r--src/transaction.rs232
-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
17 files changed, 1100 insertions, 310 deletions
diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile
deleted file mode 100644
index 3734556..0000000
--- a/.devcontainer/Dockerfile
+++ /dev/null
@@ -1,12 +0,0 @@
-FROM mcr.microsoft.com/vscode/devcontainers/rust:0-1
-
-RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \
- && apt-get -y install --no-install-recommends wabt binaryen
-RUN curl -sL https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-12/wasi-sdk_12.0_amd64.deb -o /tmp/wasi-sdk.deb \
- && dpkg -i /tmp/wasi-sdk.deb \
- && rm /tmp/wasi-sdk.deb
-RUN rustup update \
- && rustup target add wasm32-wasi \
- && rustup toolchain install nightly --component llvm-tools-preview
-
-ENV CC_wasm32_wasi=/opt/wasi-sdk/bin/clang
diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json
deleted file mode 100644
index 99f6bb1..0000000
--- a/.devcontainer/devcontainer.json
+++ /dev/null
@@ -1,29 +0,0 @@
-{
- "name": "Rust",
- "build": {
- "dockerfile": "Dockerfile"
- },
- "runArgs": [
- "--cap-add=SYS_PTRACE",
- "--security-opt",
- "seccomp=unconfined"
- ],
-
- "settings": {
- "lldb.executable": "/usr/bin/lldb",
- "files.watcherExclude": {
- "**/target/**": true
- },
- "rust-analyzer.checkOnSave.command": "clippy"
- },
-
- "extensions": [
- "vadimcn.vscode-lldb",
- "mutantdino.resourcemonitor",
- "matklad.rust-analyzer",
- "tamasfe.even-better-toml",
- "serayuzgur.crates"
- ],
-
- "remoteUser": "vscode"
-}
diff --git a/Cargo.lock b/Cargo.lock
index e7d4152..532be76 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -132,6 +132,8 @@ dependencies = [
"hmac",
"pbkdf2",
"secp256k1",
+ "serde",
+ "serde_json",
"sha2",
"sha3",
"structopt",
@@ -179,6 +181,12 @@ dependencies = [
]
[[package]]
+name = "itoa"
+version = "0.4.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dd25036021b0de88a0aff6b850051563c6516d0bf53f8638938edbb9de732736"
+
+[[package]]
name = "keccak"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -254,6 +262,12 @@ dependencies = [
]
[[package]]
+name = "ryu"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "71d301d4193d031abdd79ff7e3dd721168a9572ef3fe51a1517aba235bd8f86e"
+
+[[package]]
name = "secp256k1"
version = "0.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -272,6 +286,37 @@ dependencies = [
]
[[package]]
+name = "serde"
+version = "1.0.127"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f03b9878abf6d14e6779d3f24f07b2cfa90352cfec4acc5aab8f1ac7f146fae8"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.127"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a024926d3432516606328597e0f224a51355a493b49fdd67e9209187cbe55ecc"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.66"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "336b10da19a12ad094b59d870ebde26a45402e5b470add4b5fd03c5048a32127"
+dependencies = [
+ "itoa",
+ "ryu",
+ "serde",
+]
+
+[[package]]
name = "sha2"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
diff --git a/Cargo.toml b/Cargo.toml
index 9cfdc49..9114d2e 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -12,6 +12,8 @@ hex = "0.4"
hmac = { version = "0.11", features = ["std"] }
pbkdf2 = { version = "0.8", default-features = false }
secp256k1 = { version = "0.20", features = ["recovery"] }
+serde = { version = "1", features = ["derive"] }
+serde_json = "1"
sha2 = "0.9"
sha3 = "0.9"
structopt = "0.3"
diff --git a/src/account.rs b/src/account.rs
index 511d6aa..eda93bf 100644
--- a/src/account.rs
+++ b/src/account.rs
@@ -5,7 +5,7 @@ mod signature;
pub use self::{
address::Address,
- signature::{Parity, Signature},
+ signature::{Signature, YParity},
};
use crate::hash;
use anyhow::Result;
@@ -65,8 +65,8 @@ impl PrivateKey {
Signature {
y_parity: match recovery_id.to_i32() {
- 0 => Parity::Even,
- 1 => Parity::Odd,
+ 0 => YParity::Even,
+ 1 => YParity::Odd,
n => unreachable!("non 0 or 1 signature y-parity bit {}", n),
},
r: raw_signature[..32].try_into().unwrap(),
@@ -109,7 +109,7 @@ mod tests {
assert_eq!(
key.sign(message),
Signature {
- y_parity: Parity::Odd,
+ y_parity: YParity::Odd,
r: hex!("408790f153cbfa2722fc708a57d97a43b24429724cf060df7c915d468c43bd84"),
s: hex!("61c96aac95ce37d7a31087b6634f4a3ea439a9f704b5c818584fa2a32fa83859"),
},
diff --git a/src/account/address.rs b/src/account/address.rs
index ea62cc0..1f3383c 100644
--- a/src/account/address.rs
+++ b/src/account/address.rs
@@ -1,5 +1,6 @@
-use crate::hash;
+use crate::{hash, serialization};
use hex::FromHexError;
+use serde::Deserialize;
use std::{
fmt::{self, Debug, Display, Formatter},
ops::{Deref, DerefMut},
@@ -7,8 +8,9 @@ use std::{
};
/// An Ethereum public address.
-#[derive(Copy, Clone, Default, Eq, PartialEq)]
-pub struct Address(pub [u8; 20]);
+#[derive(Copy, Clone, Default, Deserialize, Eq, Ord, PartialEq, PartialOrd)]
+#[serde(transparent)]
+pub struct Address(#[serde(with = "serialization::bytearray")] pub [u8; 20]);
impl Address {
/// Creates an address from a slice.
@@ -101,6 +103,7 @@ impl FromStr for Address {
#[cfg(test)]
mod tests {
use super::*;
+ use serde_json::json;
#[test]
fn checksum_address() {
@@ -112,4 +115,20 @@ mod tests {
assert_eq!(address.to_string(), *s);
}
}
+
+ #[test]
+ fn deserialize_address() {
+ assert_eq!(
+ serde_json::from_value::<Address>(json!("0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE"))
+ .unwrap(),
+ Address([0xee; 20]),
+ )
+ }
+
+ #[test]
+ fn deserialize_address_requires_0x_prefix() {
+ let without_prefix = "EeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";
+ assert!(without_prefix.parse::<Address>().is_ok());
+ assert!(serde_json::from_value::<Address>(json!(without_prefix)).is_err());
+ }
}
diff --git a/src/account/signature.rs b/src/account/signature.rs
index 012aea5..f017756 100644
--- a/src/account/signature.rs
+++ b/src/account/signature.rs
@@ -1,23 +1,29 @@
//! Module containing signature data model.
-use ethnum::U256;
+use ethnum::{AsU256, U256};
use std::fmt::{self, Display, Formatter};
-/// Signature Y-parity value.
+/// The parity of the y-value of a secp256k1 signature.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[repr(u8)]
-pub enum Parity {
+pub enum YParity {
/// Even parity.
Even = 0,
/// Odd parity.
Odd = 1,
}
+impl AsU256 for YParity {
+ fn as_u256(self) -> U256 {
+ U256::new(self as _)
+ }
+}
+
/// A secp256k1 signature.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Signature {
/// Signature V value in Electrum notation.
- pub y_parity: Parity,
+ pub y_parity: YParity,
/// Signature R value.
pub r: [u8; 32],
/// Signature S value.
@@ -32,7 +38,7 @@ impl Signature {
/// Returns the signature's V value with EIP-155 chain replay protection.
pub fn v_replay_protected(&self, chain_id: U256) -> U256 {
- U256::new(self.y_parity as _) + chain_id * 2 + 35
+ self.y_parity.as_u256() + chain_id * 2 + 35
}
}
@@ -55,7 +61,7 @@ mod tests {
#[test]
fn replay_protection() {
let signature = Signature {
- y_parity: Parity::Even,
+ y_parity: YParity::Even,
r: [1; 32],
s: [2; 32],
};
@@ -65,7 +71,7 @@ mod tests {
#[test]
fn signature_to_string() {
let signature = Signature {
- y_parity: Parity::Even,
+ y_parity: YParity::Even,
r: [1; 32],
s: [2; 32],
};
diff --git a/src/cmd/sign.rs b/src/cmd/sign.rs
index dd3203d..85aec8b 100644
--- a/src/cmd/sign.rs
+++ b/src/cmd/sign.rs
@@ -1,13 +1,11 @@
//! Module implementing the `sign` subcommand for generating ECDSA signatures.
use crate::{
- account::Address,
cmd::{self, AccountOptions},
hash,
- transaction::Transaction,
+ transaction::{LegacyTransaction, Transaction},
};
-use anyhow::{anyhow, Context as _, Result};
-use ethnum::U256;
+use anyhow::{ensure, Context as _, Result};
use std::{convert::TryInto, path::PathBuf};
use structopt::StructOpt;
@@ -24,18 +22,19 @@ pub struct Options {
enum Data {
/// Sign an Ethereum transaction.
Transaction {
- #[structopt(flatten)]
- transaction: TransactionOptions,
-
- /// The chain ID to sign this transaction for. Use 0 to indicate no
- /// relay protection should be used.
- #[structopt(short, long, env)]
- chain_id: U256,
+ /// Path to transaction to sign in JSON format.
+ #[structopt(name = "MESSAGE")]
+ transaction: PathBuf,
/// Only output the transaction signature instead of the RLP-encoded
/// signed transaction.
#[structopt(long)]
signature_only: bool,
+
+ /// Force allowing legacy transactions without a chain ID for relay
+ /// protection. Use this care!
+ #[structopt(long)]
+ allow_missing_relay_protection: bool,
},
/// Sign an Ethereum message.
@@ -55,93 +54,45 @@ enum Data {
},
}
-#[derive(Debug, StructOpt)]
-struct TransactionOptions {
- /// The transaction nonce.
- #[structopt(short, long)]
- nonce: U256,
-
- /// The value of the transaction. This can be either a decimal GWei
- /// value, or a "0x"-prefixed hexadecimal Wei value.
- #[structopt(short = "p", long, parse(try_from_str = gwei))]
- gas_price: U256,
-
- /// The gas limit for the transaction. Can use `M` and `K` suffixes for
- /// million and thousand respectively.
- #[structopt(short, long, default_value = "21K", parse(try_from_str = gas))]
- gas: U256,
-
- /// The transaction recipient. Omit for contract creation transactions.
- #[structopt(short, long)]
- to: Option<Address>,
-
- /// The value of the transaction. This can be either a decimal Ether
- /// value, or a "0x"-prefixed hexadecimal Wei value.
- #[structopt(short, long, default_value = "0", parse(try_from_str = ether))]
- value: U256,
-
- /// The transaction input calldata.
- #[structopt(short, long, default_value = "0x", parse(try_from_str = cmd::permissive_hex))]
- data: Box<[u8]>,
-}
-
-impl Data {
- fn message(&self) -> Result<[u8; 32]> {
- match self {
- Data::Transaction {
- transaction,
- chain_id,
- ..
- } => Ok(hash::keccak256(
- &transaction.as_parameters().signing_message(*chain_id),
- )),
- Data::Message { message } => {
- let bytes = cmd::read_input(message)?;
-
+pub fn run(options: Options) -> Result<()> {
+ let account = options.account.private_key()?;
+ match options.data {
+ Data::Transaction {
+ transaction,
+ signature_only,
+ allow_missing_relay_protection,
+ } => {
+ let transaction =
+ serde_json::from_slice::<Transaction>(&cmd::read_input(&transaction)?)?;
+ if let Transaction::Legacy(LegacyTransaction { chain_id: None, .. }) = &transaction {
+ ensure!(
+ allow_missing_relay_protection,
+ "Signed legacy transaction without chain ID. \
+ Use `--allow-missing-relay-protection` if this was intentional.",
+ );
+ }
+ let signature = account.sign(transaction.signing_message());
+ if signature_only {
+ println!("{}", signature);
+ } else {
+ println!("0x{}", hex::encode(transaction.encode(signature)));
+ }
+ }
+ Data::Message { message } => {
+ let bytes = cmd::read_input(&message)?;
+ let message = hash::keccak256({
let mut buffer = Vec::with_capacity(46 + bytes.len());
buffer.extend_from_slice(b"\x19Ethereum Signed Message:\n");
buffer.extend_from_slice(bytes.len().to_string().as_bytes());
buffer.extend_from_slice(&bytes);
-
- Ok(hash::keccak256(&buffer))
- }
- Data::Raw { message } => Ok(*message),
+ buffer
+ });
+ println!("{}", account.sign(message));
}
- }
-}
-
-impl TransactionOptions {
- fn as_parameters(&self) -> Transaction {
- Transaction {
- nonce: self.nonce,
- gas_price: self.gas_price,
- gas: self.gas,
- to: self.to,
- value: self.value,
- data: self.data.clone().into(),
+ Data::Raw { message } => {
+ println!("{}", account.sign(message));
}
}
-}
-
-pub fn run(options: Options) -> Result<()> {
- let message = options.data.message()?;
- let signature = options.account.private_key()?.sign(message);
-
- match options.data {
- Data::Transaction {
- transaction,
- chain_id,
- signature_only: false,
- } => println!(
- "0x{}",
- hex::encode(
- transaction
- .as_parameters()
- .encode(chain_id, Some(signature))
- )
- ),
- _ => println!("{}", signature),
- }
Ok(())
}
@@ -150,50 +101,3 @@ fn permissive_hex_digest(s: &str) -> Result<[u8; 32]> {
.try_into()
.context("message for signing must be exactly 32 bytes long")
}
-
-fn ether(s: &str) -> Result<U256> {
- parse_unit(s, 18)
-}
-
-fn gwei(s: &str) -> Result<U256> {
- parse_unit(s, 9)
-}
-
-fn parse_unit(s: &str, decimals: u8) -> Result<U256> {
- if let Some(hex) = s.strip_prefix("0x") {
- Ok(U256::from_str_radix(hex, 16)?)
- } else {
- let radix = U256::new(10).pow(decimals as _);
- let (n, frac) = match s.find('.') {
- Some(i) => {
- let (n, frac) = s.split_at(i);
- let frac = {
- let digits = &frac[1..];
- let offset = decimals
- .checked_sub(digits.len().try_into()?)
- .ok_or_else(|| anyhow!("fractional part too long"))?;
- digits.parse::<U256>()? * U256::new(10).pow(offset as _)
- };
-
- (n.parse::<U256>()?, frac)
- }
- None => (s.parse::<U256>()?, U256::ZERO),
- };
-
- Ok(n.checked_mul(radix)
- .and_then(|n| n.checked_add(frac))
- .ok_or_else(|| anyhow!("Ξ value too high"))?)
- }
-}
-
-fn gas(s: &str) -> Result<U256> {
- let (n, radix) = match s.as_bytes().last().map(u8::to_ascii_lowercase) {
- Some(b'm') => (&s[..s.len() - 1], 1_000_000),
- Some(b'k') => (&s[..s.len() - 1], 1_000),
- _ => (s, 1),
- };
-
- n.parse::<U256>()?
- .checked_mul(U256::new(radix))
- .ok_or_else(|| anyhow!("gas limit too high"))
-}
diff --git a/src/main.rs b/src/main.rs
index 01480e7..dcba758 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -4,6 +4,7 @@ mod hash;
mod hdk;
mod mnemonic;
mod rand;
+mod serialization;
mod transaction;
#[cfg(test)]
diff --git a/src/mnemonic.rs b/src/mnemonic.rs
index 02f9f25..5121e40 100644
--- a/src/mnemonic.rs
+++ b/src/mnemonic.rs
@@ -94,7 +94,7 @@ impl Mnemonic {
let checksum_mask = (1 << bit_offset) - 1;
ensure!(
- hash[0] >> (8 - bit_offset) == (acc & checksum_mask) as _,
+ hash[0] >> (8 - bit_offset) == (acc & checksum_mask) as u8,
"mnemonic checksum verification failure",
);
diff --git a/src/serialization.rs b/src/serialization.rs
new file mode 100644
index 0000000..c972f86
--- /dev/null
+++ b/src/serialization.rs
@@ -0,0 +1,129 @@
+//! Module with JSON serialization helpers.
+
+/// `U256` serialization methods.
+pub mod u256 {
+ use ethnum::{AsU256 as _, U256};
+ use serde::de::{self, Deserializer, Visitor};
+ use std::fmt::{self, Formatter};
+
+ struct U256Visitor;
+
+ impl<'de> Visitor<'de> for U256Visitor {
+ type Value = U256;
+
+ fn expecting(&self, f: &mut Formatter) -> fmt::Result {
+ f.write_str("number, decimal string or '0x-' prefixed hexadecimal string")
+ }
+
+ fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
+ where
+ E: de::Error,
+ {
+ Ok(v.as_u256())
+ }
+
+ fn visit_u128<E>(self, v: u128) -> Result<Self::Value, E>
+ where
+ E: de::Error,
+ {
+ Ok(v.as_u256())
+ }
+
+ fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>
+ where
+ E: de::Error,
+ {
+ if v.fract() != 0. {
+ return Err(de::Error::custom(
+ "invalid conversion from floating point number \
+ with fractional part to 256-bit integer",
+ ));
+ }
+ if !(0.0..(1_u64 << 53) as _).contains(&v) {
+ return Err(de::Error::custom(
+ "invalid conversion from floating point number \
+ outside of valid integer range [0, 2^53)",
+ ));
+ }
+
+ Ok(v.as_u256())
+ }
+
+ fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
+ where
+ E: de::Error,
+ {
+ let (src, radix) = match v.strip_prefix("0x") {
+ Some(v) => (v, 16),
+ None => (v, 10),
+ };
+ U256::from_str_radix(src, radix).map_err(de::Error::custom)
+ }
+ }
+
+ pub fn deserialize<'de, D>(deserializer: D) -> Result<U256, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ deserializer.deserialize_any(U256Visitor)
+ }
+
+ pub mod option {
+ use super::*;
+ use serde::Deserialize;
+
+ #[derive(Deserialize)]
+ #[serde(transparent)]
+ struct Helper(#[serde(with = "super")] U256);
+
+ pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<U256>, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ let option = Option::deserialize(deserializer)?;
+ Ok(option.map(|Helper(v)| v))
+ }
+ }
+}
+
+/// Dynamic byte array serialization methods.
+pub mod bytes {
+ use serde::{
+ de::{self, Deserializer},
+ Deserialize as _,
+ };
+ use std::borrow::Cow;
+
+ pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ let s = Cow::<str>::deserialize(deserializer)?;
+ let s = s
+ .strip_prefix("0x")
+ .ok_or_else(|| de::Error::custom("storage slot missing '0x' prefix"))?;
+ hex::decode(s).map_err(de::Error::custom)
+ }
+}
+
+/// Fixed byte array serialization methods.
+pub mod bytearray {
+ use serde::{
+ de::{self, Deserializer},
+ Deserialize as _,
+ };
+ use std::borrow::Cow;
+
+ pub fn deserialize<'de, D, const N: usize>(deserializer: D) -> Result<[u8; N], D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ let mut value = [0_u8; N];
+ let s = Cow::<str>::deserialize(deserializer)?;
+ let s = s
+ .strip_prefix("0x")
+ .ok_or_else(|| de::Error::custom("storage slot missing '0x' prefix"))?;
+ hex::decode_to_slice(s, &mut value).map_err(de::Error::custom)?;
+ Ok(value)
+ }
+}
diff --git a/src/transaction.rs b/src/transaction.rs
index 5c473f2..bc3b8bc 100644
--- a/src/transaction.rs
+++ b/src/transaction.rs
@@ -1,112 +1,71 @@
//! Module defining Ethereum transaction data as well as an RLP encoding
//! implementation.
-use crate::{
- account::{Address, Signature},
- hash,
+pub mod accesslist;
+mod eip1559;
+mod eip2930;
+mod legacy;
+mod rlp;
+
+pub use self::{
+ eip1559::Eip1559Transaction, eip2930::Eip2930Transaction, legacy::LegacyTransaction,
};
-use ethnum::U256;
+use crate::{account::Signature, hash};
+use serde::{
+ de::{self, Deserializer},
+ Deserialize,
+};
+use serde_json::Map as JsonObject;
/// An Ethereum transaction.
#[derive(Clone, Debug)]
-pub struct Transaction {
- /// The nonce for the transaction.
- pub nonce: U256,
- /// The gas price in Wei for the transaction.
- pub gas_price: U256,
- /// The gas limit for the transaction.
- pub gas: 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.
- pub value: U256,
- /// The calldata to use for the transaction.
- pub data: Vec<u8>,
+pub enum Transaction {
+ Legacy(LegacyTransaction),
+ Eip2930(Eip2930Transaction),
+ Eip1559(Eip1559Transaction),
}
impl Transaction {
/// Returns the RLP encoded transaction with an optional signature.
- pub fn encode(&self, chain_id: U256, signature: Option<Signature>) -> Vec<u8> {
- // NOTE: This is currently not at all optimal in terms of memory
- // allocations, but we don't really care.
- let (v, r, s) = signature.map_or((chain_id, U256::ZERO, U256::ZERO), |signature| {
- (
- signature.v_replay_protected(chain_id),
- U256::from_be_bytes(signature.r),
- U256::from_be_bytes(signature.s),
- )
- });
-
- rlp::list(&[
- &rlp::uint(self.nonce)[..],
- &rlp::uint(self.gas_price),
- &rlp::uint(self.gas),
- &self
- .to
- .map_or_else(|| rlp::bytes(b""), |to| rlp::bytes(&*to)),
- &rlp::uint(self.value),
- &rlp::bytes(&self.data),
- &rlp::uint(v),
- &rlp::uint(r),
- &rlp::uint(s),
- ])
+ pub fn signing_message(&self) -> [u8; 32] {
+ hash::keccak256(self.rlp_encode(None))
}
/// Returns the 32-byte message used for signing.
- pub fn signing_message(&self, chain_id: U256) -> [u8; 32] {
- hash::keccak256(self.encode(chain_id, None))
- }
-}
-
-/// Tiny RLP encoding implementation.
-mod rlp {
- use ethnum::U256;
-
- /// 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
- }
- }
+ pub fn encode(&self, signature: Signature) -> Vec<u8> {
+ self.rlp_encode(Some(signature))
}
- /// 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);
+ /// Returns the RLP encoded transaction with an optional signature.
+ fn rlp_encode(&self, signature: Option<Signature>) -> Vec<u8> {
+ match self {
+ Transaction::Legacy(tx) => tx.rlp_encode(signature),
+ Transaction::Eip2930(tx) => tx.rlp_encode(signature),
+ Transaction::Eip1559(tx) => tx.rlp_encode(signature),
}
- buf
}
+}
- /// RLP encode a length.
- pub fn len(len: usize, offset: u8) -> Vec<u8> {
- if len < 56 {
- vec![len as u8 + offset]
+impl<'de> Deserialize<'de> for Transaction {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ let json = JsonObject::deserialize(deserializer)?;
+ if json.contains_key("maxPriorityFeePerGas") || json.contains_key("maxFeePerGas") {
+ Ok(Transaction::Eip1559(
+ serde_json::from_value(json.into()).map_err(de::Error::custom)?,
+ ))
+ } else if json.contains_key("accessList") {
+ Ok(Transaction::Eip2930(
+ serde_json::from_value(json.into()).map_err(de::Error::custom)?,
+ ))
} 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
+ Ok(Transaction::Legacy(
+ serde_json::from_value(json.into()).map_err(de::Error::custom)?,
+ ))
}
}
-
- /// 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)]
@@ -114,44 +73,85 @@ mod tests {
use super::*;
use crate::{account::PrivateKey, ganache::DETERMINISTIC_PRIVATE_KEY};
use hex_literal::hex;
+ use serde_json::{json, Value};
- const CHAIN_ID: U256 = U256::new(0x1337);
-
- fn transaction() -> Transaction {
- Transaction {
- nonce: U256::new(7777),
- gas_price: U256::new(100_000_000_000),
- gas: U256::new(150_000),
- to: Some(Address(hex!("7070707070707070707070707070707070707070"))),
- value: U256::new(42_000_000_000_000_000_000),
- data: hex!("01020304").into(),
- }
+ fn sign_encode(tx: Value) -> Vec<u8> {
+ let tx = serde_json::from_value::<Transaction>(tx).unwrap();
+ let key = PrivateKey::new(DETERMINISTIC_PRIVATE_KEY).unwrap();
+ let signature = key.sign(tx.signing_message());
+ tx.encode(signature)
}
#[test]
- fn rlp_encode_for_signing() {
+ fn encode_signed_transaction() {
assert_eq!(
- transaction().encode(CHAIN_ID, None),
+ sign_encode(json!({
+ "nonce": 0,
+ "gasPrice": 0,
+ "gasLimit": 21000,
+ "to": "0x0000000000000000000000000000000000000000",
+ "value": 0,
+ "data": "0x",
+ })),
hex!(
- "f6821e6185174876e800830249f0947070707070707070707070707070707070
- 707070890246ddf9797668000084010203048213378080"
+ "f85f808082520894000000000000000000000000000000000000000080801ca0
+ 0f1c0e95b7050ac3df5ac3b69a7d41e0b815da462fcd30954b1c37b58ca71c16
+ a068dab467ad79359967a3df1bcfc17292a3839288d05274d0e3e391f8b50841
+ 0b"
),
- )
- }
-
- #[test]
- fn rlp_encode_with_signature() {
- let key = PrivateKey::new(DETERMINISTIC_PRIVATE_KEY).unwrap();
- let signature = key.sign(transaction().signing_message(CHAIN_ID));
-
+ );
+ assert_eq!(
+ sign_encode(json!({
+ "chainId": 1,
+ "nonce": 0,
+ "gasPrice": 0,
+ "gasLimit": 21000,
+ "to": "0x0000000000000000000000000000000000000000",
+ "value": 0,
+ "data": "0x",
+ })),
+ hex!(
+ "f85f8080825208940000000000000000000000000000000000000000808025a0
+ c97442e361bf3940bec722b240c699de22302469756436bbcc5a150a93309b08
+ a02fd3e68ed327dea3d085ec16a8589ebf7871e5a990669f67be82a70cd9dfb4
+ f7"
+ ),
+ );
+ assert_eq!(
+ sign_encode(json!({
+ "chainId": 1,
+ "nonce": 0,
+ "gasPrice": 0,
+ "gasLimit": 21000,
+ "to": "0x0000000000000000000000000000000000000000",
+ "value": 0,
+ "data": "0x",
+ "accessList": [],
+ })),
+ hex!(
+ "01f8610180808252089400000000000000000000000000000000000000008080
+ c080a04366d11301b0a233d0f311f93083583ed316c2ebd7246ccd93f1a320b2
+ 57fd65a02e3df28ccda84b829403a04f2d142416f01bdf7036dba12b66e4add6
+ 4d59455e"
+ ),
+ );
assert_eq!(
- transaction().encode(CHAIN_ID, Some(signature)),
+ sign_encode(json!({
+ "chainId": 1,
+ "nonce": 0,
+ "maxPriorityFeePerGas": 0,
+ "maxFeePerGas": 0,
+ "gasLimit": 21000,
+ "to": "0x0000000000000000000000000000000000000000",
+ "value": 0,
+ "data": "0x",
+ })),
hex!(
- "f876821e6185174876e800830249f09470707070707070707070707070707070
- 70707070890246ddf979766800008401020304822691a076382953503398303f
- e8c3e3d235e8f71adc39fb90fcda99514e324d96bad253a044351903896d0b6f
- 8a3ee9543c1e23ec3bab29a4ae5cae1a6b7b2c811105264f"
+ "02f8620180808082520894000000000000000000000000000000000000000080
+ 80c001a0290dbdecbc884b4cb827015fe0cd7ac90df1a5634d52a2845c21afac
+ ca14b803a03e848dd1a342e5528beff99c42876cf091a68e2090dbbced5a5f7f
+ 392d3abcda"
),
- )
+ );
}
}
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"
+ );
+ }
+}