Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(sdk): SignedTransaction abstraction #11432

Merged
merged 26 commits into from
Oct 18, 2024
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
ace979e
Checkout trait SignedTransaction from emhane/signed-tx-trait
emhane Oct 2, 2024
f758c85
Checkout SignedTransaction getter trait methods from emhane/tx-signed-2
emhane Oct 2, 2024
d08c5c1
Fix export SignedTransaction
emhane Oct 2, 2024
21af26e
Remove duplicate file
emhane Oct 4, 2024
c147f66
Remove deprecated method
emhane Oct 4, 2024
cfd372f
Add super traits for SignedTransaction
emhane Oct 5, 2024
9d1473e
Define SignedTransaction::Transaction and SignedTransaction::Signature
emhane Oct 5, 2024
e46aada
Add getter trait method SignedTransaction::tx_hash
emhane Oct 5, 2024
6302e9b
Move SignedTransaction into reth-primitives-traits
emhane Oct 5, 2024
fc81039
Define trait Signature and add as trait bound for SignedTransaction::…
emhane Oct 5, 2024
3294a4e
Fix conflicts and lint
emhane Oct 5, 2024
fdf5bae
Fix lint
emhane Oct 5, 2024
e61f0f8
Fix docs
emhane Oct 5, 2024
4c8e217
feat: expose Op node network_config helper (#11506)
mattsse Oct 5, 2024
00f899f
Fix merge conflicts
emhane Oct 5, 2024
6de34e9
Merge branch 'main' into emhane/signed-tx-trait
emhane Oct 7, 2024
d5ebe55
Remove optimism code from reth-primitives-traits
emhane Oct 8, 2024
86eaa11
Remove trait methods from SignedTransaction related to rlp encoding
emhane Oct 8, 2024
6239a6b
Remove Signature trait from scope
emhane Oct 8, 2024
a232b2a
Remove trait bound SigneableTransaction off SignedTransaction::Transa…
emhane Oct 8, 2024
5ea4e68
Revert changes to Makefile
emhane Oct 8, 2024
cbaa53f
Merge branch 'main' into emhane/signed-tx-trait
emhane Oct 8, 2024
d19d0c6
Merge branch 'main' into emhane/signed-tx-trait
emhane Oct 17, 2024
086c866
Move module signed_tx->transaction::signed
emhane Oct 17, 2024
3461829
Update docs
emhane Oct 17, 2024
e785d3b
Remove redundant trait methods from SignedTransaction
emhane Oct 18, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 15 additions & 12 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions crates/primitives-traits/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,4 @@ arbitrary = [
"dep:proptest-arbitrary-interop",
]
serde-bincode-compat = ["serde_with", "alloy-consensus/serde-bincode-compat"]
optimism = []
6 changes: 6 additions & 0 deletions crates/primitives-traits/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ pub use constants::gas_units::{format_gas, format_gas_throughput};
pub mod account;
pub use account::{Account, Bytecode};

pub mod signed_tx;
pub use signed_tx::SignedTransaction;

pub mod signature;
pub use signature::Signature;

mod integer_list;
pub use integer_list::{IntegerList, IntegerListError};

Expand Down
33 changes: 33 additions & 0 deletions crates/primitives-traits/src/signature.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
//! Signature abstraction

use alloy_primitives::{Parity, U256};

/// A signature.
pub trait Signature: Sized + Send + Sync {
/// Decodes RLP-encoded signature, w.r.t. chain ID.
fn decode_with_eip155_chain_id(buf: &mut &[u8]) -> alloy_rlp::Result<(Self, Option<u64>)>;
}

impl Signature for alloy_primitives::Signature {
fn decode_with_eip155_chain_id(buf: &mut &[u8]) -> alloy_rlp::Result<(Self, Option<u64>)> {
let v: Parity = alloy_rlp::Decodable::decode(buf)?;
let r: U256 = alloy_rlp::Decodable::decode(buf)?;
let s: U256 = alloy_rlp::Decodable::decode(buf)?;

#[cfg(not(feature = "optimism"))]
if matches!(v, Parity::Parity(_)) {
return Err(alloy_rlp::Error::Custom("invalid parity for legacy transaction"));
}

#[cfg(feature = "optimism")]
// pre bedrock system transactions were sent from the zero address as legacy
// transactions with an empty signature
//
// NOTE: this is very hacky and only relevant for op-mainnet pre bedrock
if matches!(v, Parity::Parity(false)) && r.is_zero() && s.is_zero() {
return Ok((Self::new(r, s, Parity::Parity(false)), None))
}

Ok((Self::new(r, s, v), v.chain_id()))
}
}
138 changes: 138 additions & 0 deletions crates/primitives-traits/src/signed_tx.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
//! API of a signed transaction, w.r.t. network stack.

use alloc::fmt;
use core::hash::Hash;

use alloy_consensus::{SignableTransaction, TxLegacy};
use alloy_eips::eip2718::{Decodable2718, Encodable2718};
use alloy_primitives::{keccak256, Address, TxHash, B256};

use crate::Signature;

/// A signed transaction.
pub trait SignedTransaction:
fmt::Debug
+ Clone
+ PartialEq
+ Eq
+ Hash
+ Send
+ Sync
+ serde::Serialize
+ for<'a> serde::Deserialize<'a>
+ alloy_rlp::Encodable
+ alloy_rlp::Decodable
+ Encodable2718
+ Decodable2718
{
/// Transaction type that is signed.
type Transaction: SignableTransaction<Self::Signature>;

/// Signature type that results from signing transaction.
type Signature: Signature;

/// Returns reference to transaction hash.
fn tx_hash(&self) -> &TxHash;

/// Returns reference to transaction.
fn transaction(&self) -> &Self::Transaction;

/// Returns reference to signature.
fn signature(&self) -> &Self::Signature;

/// Recover signer from signature and hash.
///
/// Returns `None` if the transaction's signature is invalid following [EIP-2](https://eips.ethereum.org/EIPS/eip-2), see also `reth_primitives::transaction::recover_signer`.
///
/// Note:
///
/// This can fail for some early ethereum mainnet transactions pre EIP-2, use
/// [`Self::recover_signer_unchecked`] if you want to recover the signer without ensuring that
/// the signature has a low `s` value.
fn recover_signer(&self) -> Option<Address>;

/// Recover signer from signature and hash _without ensuring that the signature has a low `s`
/// value_.
///
/// Returns `None` if the transaction's signature is invalid, see also
/// `reth_primitives::transaction::recover_signer_unchecked`.
fn recover_signer_unchecked(&self) -> Option<Address>;

/// Output the length of the `encode_inner(out`, true). Note to assume that `with_header` is
/// only `true`.
fn payload_len_inner(&self) -> usize;

/// Returns the length without an RLP header - this is used for eth/68 sizes.
fn length_without_header(&self) -> usize;

/// Decodes legacy transaction from the data buffer.
///
/// This should be used _only_ be used in general transaction decoding methods, which have
/// already ensured that the input is a legacy transaction with the following format:
/// `rlp(legacy_tx)`
///
/// Legacy transactions are encoded as lists, so the input should start with a RLP list header.
///
/// This expects `rlp(legacy_tx)`
// TODO: make buf advancement semantics consistent with `decode_enveloped_typed_transaction`,
// so decoding methods do not need to manually advance the buffer
fn decode_rlp_legacy_transaction(data: &mut &[u8]) -> alloy_rlp::Result<Self>;

/// Decodes legacy transaction from the data buffer into a tuple.
///
/// This expects `rlp(legacy_tx)`
///
/// Refer to the docs for [`Self::decode_rlp_legacy_transaction`] for details on the exact
/// format expected.
fn decode_rlp_legacy_transaction_tuple(
data: &mut &[u8],
) -> alloy_rlp::Result<(TxLegacy, TxHash, Self::Signature)> {
// keep this around, so we can use it to calculate the hash
let original_encoding = *data;

let header = alloy_rlp::Header::decode(data)?;
let remaining_len = data.len();

let transaction_payload_len = header.payload_length;

if transaction_payload_len > remaining_len {
return Err(alloy_rlp::Error::InputTooShort)
}

let mut transaction = TxLegacy {
nonce: alloy_rlp::Decodable::decode(data)?,
gas_price: alloy_rlp::Decodable::decode(data)?,
gas_limit: alloy_rlp::Decodable::decode(data)?,
to: alloy_rlp::Decodable::decode(data)?,
value: alloy_rlp::Decodable::decode(data)?,
input: alloy_rlp::Decodable::decode(data)?,
chain_id: None,
};
let (signature, extracted_id) = Self::Signature::decode_with_eip155_chain_id(data)?;
transaction.chain_id = extracted_id;

// check the new length, compared to the original length and the header length
let decoded = remaining_len - data.len();
if decoded != transaction_payload_len {
return Err(alloy_rlp::Error::UnexpectedLength)
}

let tx_length = header.payload_length + header.length();
let hash = keccak256(&original_encoding[..tx_length]);
Ok((transaction, hash, signature))
}

/// Create a new signed transaction from a transaction and its signature.
///
/// This will also calculate the transaction hash using its encoding.
fn from_transaction_and_signature(
transaction: Self::Transaction,
signature: Self::Signature,
) -> Self;

/// Calculate transaction hash, eip2728 transaction does not contain rlp header and start with
/// tx type.
fn recalculate_hash(&self) -> B256 {
keccak256(self.encoded_2718())
}
}
2 changes: 2 additions & 0 deletions crates/primitives/src/traits/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
//! Abstractions of primitive data types

pub mod block;
pub mod transaction;

pub use block::{body::BlockBody, Block};
pub use transaction::signed::SignedTransaction;

pub use alloy_consensus::BlockHeader;
7 changes: 4 additions & 3 deletions crates/primitives/src/transaction/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ use core::mem;
use derive_more::{AsRef, Deref};
use once_cell::sync::Lazy;
use rayon::prelude::{IntoParallelIterator, ParallelIterator};
use reth_primitives_traits::Signature as _;
use serde::{Deserialize, Serialize};
use signature::{decode_with_eip155_chain_id, with_eip155_parity};

pub use error::{
InvalidTransactionError, TransactionConversionError, TryFromRecoveredTransactionError,
Expand All @@ -31,7 +31,8 @@ pub use sidecar::{BlobTransaction, BlobTransactionSidecar};

pub use compat::FillTxEnv;
pub use signature::{
extract_chain_id, legacy_parity, recover_signer, recover_signer_unchecked, Signature,
extract_chain_id, legacy_parity, recover_signer, recover_signer_unchecked, with_eip155_parity,
Signature,
};
pub use tx_type::{
TxType, EIP1559_TX_TYPE_ID, EIP2930_TX_TYPE_ID, EIP4844_TX_TYPE_ID, EIP7702_TX_TYPE_ID,
Expand Down Expand Up @@ -1251,7 +1252,7 @@ impl TransactionSigned {
input: Decodable::decode(data)?,
chain_id: None,
};
let (signature, extracted_id) = decode_with_eip155_chain_id(data)?;
let (signature, extracted_id) = Signature::decode_with_eip155_chain_id(data)?;
transaction.chain_id = extracted_id;

// check the new length, compared to the original length and the header length
Expand Down
28 changes: 2 additions & 26 deletions crates/primitives/src/transaction/signature.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::transaction::util::secp256k1;
use alloy_primitives::{Address, Parity, B256, U256};
use alloy_rlp::{Decodable, Error as RlpError};
use alloy_rlp::Error as RlpError;

pub use alloy_primitives::Signature;

Expand All @@ -16,30 +16,6 @@ const SECP256K1N_HALF: U256 = U256::from_be_bytes([
0x5D, 0x57, 0x6E, 0x73, 0x57, 0xA4, 0x50, 0x1D, 0xDF, 0xE9, 0x2F, 0x46, 0x68, 0x1B, 0x20, 0xA0,
]);

pub(crate) fn decode_with_eip155_chain_id(
buf: &mut &[u8],
) -> alloy_rlp::Result<(Signature, Option<u64>)> {
let v: Parity = Decodable::decode(buf)?;
let r: U256 = Decodable::decode(buf)?;
let s: U256 = Decodable::decode(buf)?;

#[cfg(not(feature = "optimism"))]
if matches!(v, Parity::Parity(_)) {
return Err(alloy_rlp::Error::Custom("invalid parity for legacy transaction"));
}

#[cfg(feature = "optimism")]
// pre bedrock system transactions were sent from the zero address as legacy
// transactions with an empty signature
//
// NOTE: this is very hacky and only relevant for op-mainnet pre bedrock
if matches!(v, Parity::Parity(false)) && r.is_zero() && s.is_zero() {
return Ok((Signature::new(r, s, Parity::Parity(false)), None))
}

Ok((Signature::new(r, s, v), v.chain_id()))
}

/// Recover signer from message hash, _without ensuring that the signature has a low `s`
/// value_.
///
Expand Down Expand Up @@ -90,7 +66,7 @@ pub fn legacy_parity(signature: &Signature, chain_id: Option<u64>) -> Parity {
}

/// Returns a signature with the given chain ID applied to the `v` value.
pub(crate) fn with_eip155_parity(signature: &Signature, chain_id: Option<u64>) -> Signature {
pub fn with_eip155_parity(signature: &Signature, chain_id: Option<u64>) -> Signature {
Signature::new(signature.r(), signature.s(), legacy_parity(signature, chain_id))
}

Expand Down
Loading