Skip to content

feat: add setcode transaction type for compatibility#189

Merged
FletcherMan merged 1 commit intomainfrom
setcode_tx
Apr 24, 2025
Merged

feat: add setcode transaction type for compatibility#189
FletcherMan merged 1 commit intomainfrom
setcode_tx

Conversation

@FletcherMan
Copy link
Copy Markdown
Collaborator

@FletcherMan FletcherMan commented Apr 23, 2025

1. Purpose or design rationale of this PR

...

2. PR title

Your PR title must follow conventional commits (as we are doing squash merge for each PR), so it must start with one of the following types:

  • build: Changes that affect the build system or external dependencies (example scopes: yarn, eslint, typescript)
  • ci: Changes to our CI configuration files and scripts (example scopes: vercel, github, cypress)
  • docs: Documentation-only changes
  • feat: A new feature
  • fix: A bug fix
  • perf: A code change that improves performance
  • refactor: A code change that doesn't fix a bug, or add a feature, or improves performance
  • style: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)
  • test: Adding missing tests or correcting existing tests

3. Deployment tag versioning

Has the version in params/version.go been updated?

  • This PR doesn't involve a new deployment, git tag, docker image tag, and it doesn't affect traces
  • Yes

4. Breaking change label

Does this PR have the breaking-change label?

  • This PR is not a breaking change
  • Yes

Summary by CodeRabbit

  • New Features

    • Introduced support for EIP-7702 "SetCode" transactions, enabling temporary code installation at the signer's address.
    • Added new transaction type with fields for authorizations, signatures, and delegation handling.
    • Included methods to access and validate authorization lists and authorities within transactions.
  • Bug Fixes

    • Improved JSON serialization and deserialization for the new transaction type, including strict validation of required fields.
  • Tests

    • Added tests to verify delegation address parsing for the new transaction type.
  • Chores

    • Updated the patch version number to 5.

@FletcherMan FletcherMan requested a review from a team as a code owner April 23, 2025 08:40
@FletcherMan FletcherMan requested review from twcctop and removed request for a team April 23, 2025 08:40
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 23, 2025

Walkthrough

This set of changes introduces a new EIP-7702 "SetCode" transaction type, including its data structures, JSON marshaling/unmarshaling logic, and cryptographic signature handling. New types for 256-bit unsigned integers and transaction authorizations are added, along with associated methods for serialization and validation. The transaction processing code is extended to recognize and process the new transaction type, including extracting authorization lists and authorities. Supporting utilities for delegation address parsing and signing are provided, and tests ensure correct delegation parsing. The patch version is incremented to reflect these updates.

Changes

File(s) Change Summary
common/hexutil/json.go Added a U256 type for 256-bit unsigned integers, with methods for JSON/text marshaling and unmarshaling, and string conversion.
core/types/gen_authorization.go Introduced generated JSON marshaling/unmarshaling logic for the SetCodeAuthorization type, including strict required field validation and conversion between internal and JSON representations.
core/types/transaction.go Added the SetCodeTxType constant, and two new methods to the Transaction type: SetCodeAuthorizations (returns authorizations if the transaction is a SetCodeTx) and SetCodeAuthorities (returns deduplicated authority addresses from authorizations). Updated the transaction decoding logic to recognize the new type.
core/types/transaction_marshalling.go Extended transaction JSON marshaling/unmarshaling to support the new SetCodeTx type, including handling of the new AuthorizationList field and validation/conversion of all required fields and signatures.
core/types/tx_setcode.go Introduced the SetCodeTx type for EIP-7702 transactions, the SetCodeAuthorization struct, and supporting functions/methods for delegation address parsing, signing, signature verification, copying, RLP encoding/decoding, and gas price calculation. Implements the full lifecycle for SetCode transactions.
core/types/tx_setcode_test.go Added tests for the ParseDelegation function, covering valid and invalid delegation address scenarios.
params/version.go Incremented the VersionPatch constant from 3 to 5.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant JSON
    participant Transaction
    participant SetCodeTx
    participant SetCodeAuthorization

    User->>JSON: Submit SetCodeTx JSON
    JSON->>Transaction: UnmarshalJSON
    Transaction->>SetCodeTx: Decode fields
    SetCodeTx->>SetCodeAuthorization: Unmarshal authorizations
    SetCodeAuthorization->>SetCodeAuthorization: Validate signature fields
    SetCodeTx->>Transaction: Return SetCodeTx instance
    Transaction->>User: Transaction object with authorizations
Loading
sequenceDiagram
    participant Signer
    participant SetCodeAuthorization
    participant ECDSA

    Signer->>SetCodeAuthorization: Request signature
    SetCodeAuthorization->>ECDSA: Compute sigHash, sign with private key
    ECDSA-->>SetCodeAuthorization: Signature (V, R, S)
    SetCodeAuthorization-->>Signer: Signed authorization
Loading

Suggested reviewers

  • r3aker86
  • curryxbo

Poem

In bytes and blocks, a change arrives,
With SetCodeTx, new code survives.
Authorizations checked with care,
Delegations parsed from here to there.
Marshaling, signing, all in flow—
Patch five hops on, the rabbits know!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (5)
core/types/tx_setcode_test.go (1)

25-70: Test coverage for delegation address parsing.

This test validates the ParseDelegation function which is critical for the SetCode transaction type. The test uses table-driven testing to cover:

  • Valid delegation with proper prefix and address
  • Various error scenarios (incorrect address lengths, wrong prefixes, missing components)

This helps ensure robust handling of delegation designators in the new transaction type.

However, it would be beneficial to add assertions to verify the actual parsed address value in the success case, not just that parsing succeeded.

-	if !ok && tt.want != nil {
-		t.Fatalf("failed to parse, want %s", tt.want.Hex())
-	}
+	if !ok && tt.want != nil {
+		t.Fatalf("failed to parse, want %s", tt.want.Hex())
+	} else if ok && tt.want != nil && *tt.want != got {
+		t.Fatalf("parsed %s, want %s", got.Hex(), tt.want.Hex())
+	}
core/types/gen_authorization.go (1)

18-26: Minor: avoid shadowing the exported type name

The inner alias type SetCodeAuthorization struct { … } shadows the exported type name declared below (l.72).
This is harmless but can be confusing when stepping through with a debugger.

A more conventional pattern:

type setCodeAuthorizationJSON struct { … }

Not a blocker – just a small readability gain.

core/types/transaction_marshalling.go (1)

497-500: Prefer non‑panicking conversion for fee caps

uint256.MustFromBig will panic on overflow.
For external JSON input this is avoidable foot‑gun – we already call the non‑panicking form (FromBig) a few lines above for chainId.

-itx.GasTipCap  = uint256.MustFromBig((*big.Int)(dec.MaxPriorityFeePerGas))
-itx.GasFeeCap  = uint256.MustFromBig((*big.Int)(dec.MaxFeePerGas))
+if itx.GasTipCap, overflow = uint256.FromBig((*big.Int)(dec.MaxPriorityFeePerGas)); overflow {
+    return errors.New("'maxPriorityFeePerGas' overflows uint256")
+}
+if itx.GasFeeCap, overflow = uint256.FromBig((*big.Int)(dec.MaxFeePerGas)); overflow {
+    return errors.New("'maxFeePerGas' overflows uint256")
+}
core/types/tx_setcode.go (2)

90-106: Validate signature immediately after signing

SignSetCode returns an authorisation that might have an invalid (non‑canonical) signature if crypto.Sign is ever swapped or called with a non‑homestead rule set.
Defensive check keeps invariants local.

 sig, err := crypto.Sign(sighash[:], prv)
 if err != nil {
     return SetCodeAuthorization{}, err
 }
- r, s, _ := decodeSignature(sig)
+ r, s, _ := decodeSignature(sig)
+ if !crypto.ValidateSignatureValues(sig[64], r, s, true) {
+     return SetCodeAuthorization{}, errors.New("signSetCode produced invalid signature values")
+ }

197-206: Minor optimisation: avoid negative intermediate in gas price calc

When gasFeeCap < baseFee, dst.Sub(GasFeeCap, baseFee) produces a negative value only to be discarded.
Using Math.Min‑style logic is clearer & avoids a heap alloc under the hood.

if baseFee == nil || tx.GasFeeCap.CmpUint64(0) == 0 {
    return dst.Set(tx.GasFeeCap.ToBig())
}
cap := tx.GasFeeCap.ToBig()
if cap.Cmp(baseFee) < 0 {
    return dst.Set(cap) // gasFeeCap already lower than baseFee
}
…
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 151913b and ccf2847.

📒 Files selected for processing (7)
  • common/hexutil/json.go (2 hunks)
  • core/types/gen_authorization.go (1 hunks)
  • core/types/transaction.go (3 hunks)
  • core/types/transaction_marshalling.go (3 hunks)
  • core/types/tx_setcode.go (1 hunks)
  • core/types/tx_setcode_test.go (1 hunks)
  • params/version.go (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
core/types/gen_authorization.go (2)
core/types/tx_setcode.go (1)
  • SetCodeAuthorization (72-79)
common/hexutil/json.go (2)
  • U256 (233-233)
  • Uint64 (275-275)
core/types/tx_setcode.go (6)
common/types.go (1)
  • BytesToAddress (206-210)
common/hexutil/json.go (3)
  • Bytes (40-40)
  • U256 (233-233)
  • Uint64 (275-275)
core/types/gen_authorization.go (2)
  • SetCodeAuthorization (18-25)
  • SetCodeAuthorization (38-45)
crypto/crypto.go (3)
  • ValidateSignatureValues (264-275)
  • SignatureLength (41-41)
  • Keccak256 (78-86)
core/types/transaction.go (3)
  • ErrInvalidSig (36-36)
  • TxData (80-100)
  • SetCodeTxType (54-54)
rlp/decode.go (1)
  • DecodeBytes (92-106)
🔇 Additional comments (8)
common/hexutil/json.go (3)

27-27: New dependency added for uint256 support.

The code adds a dependency on the holiman/uint256 package to provide proper handling of 256-bit unsigned integers. This is important for supporting the new transaction type's authorization fields.


35-35: Added reflection type for uint256.Int.

This allows the package to properly handle type errors during unmarshaling operations for the new U256 type, consistent with how other types are handled in this file.


231-271: New U256 type implementation for 256-bit unsigned integer marshaling.

The implementation follows the established pattern of other numeric types in this file, providing:

  1. JSON marshaling/unmarshaling with 0x prefix
  2. Text marshaling/unmarshaling
  3. String representation

The code correctly handles edge cases like empty strings and provides proper error handling. This new type is essential for serializing the SetCodeAuthorization fields in the new transaction type.

A few implementation details worth noting:

  • Lines 248-253 handle the empty string case which uint256.Int would otherwise reject
  • The implementation ensures strict hex format validation
  • Appropriate error types are returned for JSON unmarshaling errors
params/version.go (1)

27-27:

Details

❓ Verification inconclusive

Version patch increment for the new transaction type.

The patch version is incremented from 3 to 5, reflecting the addition of the EIP-7702 SetCode transaction type and its supporting structures.

Let's verify what was in prior versions:


🏁 Script executed:

#!/bin/bash
# Check git history for the version number
git log -p -- params/version.go | grep -A 2 "VersionPatch ="

Length of output: 0


Manual verification required for VersionPatch bump

The automated git log -p check didn’t return any history for VersionPatch. Please confirm that the patch version in params/version.go was intentionally incremented from 3 to 5 to reflect the EIP‑7702 SetCode transaction addition:

• File & line: params/version.go:27
• Suggested commands:

  • git log --oneline -n 20 -- params/version.go
  • git blame -L27,27 params/version.go
core/types/transaction.go (4)

54-54: Added SetCodeTxType constant.

The new transaction type constant (0x04) is defined for the EIP-7702 SetCode transaction, continuing the sequential numbering pattern of existing transaction types.


208-209: Added support for decoding SetCodeTx transactions.

The decodeTyped method is extended to recognize and instantiate the new SetCodeTx type when decoding typed transactions. This is a necessary extension to support the new transaction type.


472-479: Added method to access SetCodeTx authorizations.

The SetCodeAuthorizations method provides access to the authorization list from SetCodeTx transactions, returning nil for other transaction types. This accessor method follows the pattern of existing transaction data accessors.


483-502: Added method to extract unique authority addresses.

The SetCodeAuthorities method extracts and deduplicates authority addresses from the authorization list, which is useful for validation and processing of SetCode transactions.

The implementation correctly:

  1. Handles non-SetCodeTx transactions by returning nil
  2. Skips invalid authorizations where Authority() returns an error
  3. Deduplicates addresses using a map
  4. Pre-allocates the result slice with a capacity matching the auth list

Comment on lines +62 to +66
if dec.V == nil {
return errors.New("missing required field 'yParity' for SetCodeAuthorization")
}
s.V = uint8(*dec.V)
if dec.R == nil {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Validate yParity range when parsing JSON

yParity is expected to be exactly 0 or 1 (EIP‑2 / EIP‑155 rules).
If a larger value arrives over the wire we silently truncate it with uint8(*dec.V), which can mask malformed or malicious payloads.

  s.V = uint8(*dec.V)
+ if s.V != 0 && s.V != 1 {
+   return errors.New("invalid yParity value: must be 0 or 1")
+ }

Comment on lines +47 to +51
AuthorizationList []SetCodeAuthorization `json:"authorizationList,omitempty"`
V *hexutil.Big `json:"v"`
R *hexutil.Big `json:"r"`
S *hexutil.Big `json:"s"`
YParity *hexutil.Uint64 `json:"yParity,omitempty"`
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider pointer‑vs‑slice semantics for authorizationList

AuthorizationList []SetCodeAuthorization is a value slice.
During (un)marshal we rely on nil vs. “empty slice” to distinguish “field omitted” from “present but empty”.
Because Go serialises an empty slice as [], clients can still send {"authorizationList":[]} – our later nil check (l.512‑514) will pass even though the list is empty.

If an empty list is invalid you should:

if dec.AuthorizationList == nil || len(dec.AuthorizationList) == 0 {
    return errors.New("authorizationList must contain at least one entry")
}

Comment on lines +470 to +516
case SetCodeTxType:
var itx SetCodeTx
inner = &itx
if dec.ChainID == nil {
return errors.New("missing required field 'chainId' in transaction")
}
var overflow bool
itx.ChainID, overflow = uint256.FromBig(dec.ChainID.ToInt())
if overflow {
return errors.New("'chainId' value overflows uint256")
}
if dec.Nonce == nil {
return errors.New("missing required field 'nonce' in transaction")
}
itx.Nonce = uint64(*dec.Nonce)
if dec.To == nil {
return errors.New("missing required field 'to' in transaction")
}
itx.To = *dec.To
if dec.Gas == nil {
return errors.New("missing required field 'gas' for txdata")
}
itx.Gas = uint64(*dec.Gas)
if dec.MaxPriorityFeePerGas == nil {
return errors.New("missing required field 'maxPriorityFeePerGas' for txdata")
}
itx.GasTipCap = uint256.MustFromBig((*big.Int)(dec.MaxPriorityFeePerGas))
if dec.MaxFeePerGas == nil {
return errors.New("missing required field 'maxFeePerGas' for txdata")
}
itx.GasFeeCap = uint256.MustFromBig((*big.Int)(dec.MaxFeePerGas))
if dec.Value == nil {
return errors.New("missing required field 'value' in transaction")
}
itx.Value = uint256.MustFromBig((*big.Int)(dec.Value))
if dec.Input == nil {
return errors.New("missing required field 'input' in transaction")
}
itx.Data = *dec.Input
if dec.AccessList != nil {
itx.AccessList = *dec.AccessList
}
if dec.AuthorizationList == nil {
return errors.New("missing required field 'authorizationList' in transaction")
}
itx.AuthList = dec.AuthorizationList

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Sanity‑check each authorisation entry during decoding

We trust every element in authorizationList but never validate:

  • auth.ChainID matches the tx ChainID
  • auth.Address is unique (no duplicates)
  • auth.Authority() succeeds and signature is valid
  • auth.Nonce monotonicity / replay rules

Adding a tight loop here prevents malformed txs from reaching deeper consensus code.

for i, a := range dec.AuthorizationList {
    if a.ChainID.Cmp(itx.ChainID) != 0 {
        return fmt.Errorf("authorizationList[%d].chainId mismatch", i)
    }
    if _, err := a.Authority(); err != nil {
        return fmt.Errorf("authorizationList[%d] invalid signature: %w", i, err)
    }
    // TODO: duplicate / nonce checks as per consensus rules
}

Comment thread core/types/tx_setcode.go
Comment on lines +208 to +210
func (tx *SetCodeTx) rawSignatureValues() (v, r, s *big.Int) {
return tx.V.ToBig(), tx.R.ToBig(), tx.S.ToBig()
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Guard against nil signature fields

rawSignatureValues() blindly dereferences tx.V/R/S.
A freshly‑constructed SetCodeTx (before signing) will panic.

-func (tx *SetCodeTx) rawSignatureValues() (v, r, s *big.Int) {
-    return tx.V.ToBig(), tx.R.ToBig(), tx.S.ToBig()
+func (tx *SetCodeTx) rawSignatureValues() (v, r, s *big.Int) {
+    if tx.V == nil || tx.R == nil || tx.S == nil {
+        return nil, nil, nil
+    }
+    return tx.V.ToBig(), tx.R.ToBig(), tx.S.ToBig()
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func (tx *SetCodeTx) rawSignatureValues() (v, r, s *big.Int) {
return tx.V.ToBig(), tx.R.ToBig(), tx.S.ToBig()
}
func (tx *SetCodeTx) rawSignatureValues() (v, r, s *big.Int) {
if tx.V == nil || tx.R == nil || tx.S == nil {
return nil, nil, nil
}
return tx.V.ToBig(), tx.R.ToBig(), tx.S.ToBig()
}

@FletcherMan FletcherMan merged commit c59ecb3 into main Apr 24, 2025
1 check passed
@FletcherMan FletcherMan deleted the setcode_tx branch April 24, 2025 01:11
FletcherMan added a commit that referenced this pull request Apr 24, 2025
FletcherMan added a commit that referenced this pull request Apr 24, 2025
@coderabbitai coderabbitai Bot mentioned this pull request Sep 2, 2025
13 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants