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

feat(core/types): Block RLP overriding #133

Merged
merged 14 commits into from
Feb 13, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 1 addition & 1 deletion core/state/state.libevm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ func TestGetSetExtra(t *testing.T) {
// test deep copying.
payloads := types.RegisterExtras[
types.NOOPHeaderHooks, *types.NOOPHeaderHooks,
types.NOOPBodyHooks, *types.NOOPBodyHooks,
types.NOOPBlockBodyHooks, *types.NOOPBlockBodyHooks,
*accountExtra,
]().StateAccount

Expand Down
6 changes: 3 additions & 3 deletions core/state/state_object.libevm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ func TestStateObjectEmpty(t *testing.T) {
registerAndSet: func(acc *types.StateAccount) {
types.RegisterExtras[
types.NOOPHeaderHooks, *types.NOOPHeaderHooks,
types.NOOPBodyHooks, *types.NOOPBodyHooks,
types.NOOPBlockBodyHooks, *types.NOOPBlockBodyHooks,
bool,
]().StateAccount.Set(acc, false)
},
Expand All @@ -59,7 +59,7 @@ func TestStateObjectEmpty(t *testing.T) {
registerAndSet: func(*types.StateAccount) {
types.RegisterExtras[
types.NOOPHeaderHooks, *types.NOOPHeaderHooks,
types.NOOPBodyHooks, *types.NOOPBodyHooks,
types.NOOPBlockBodyHooks, *types.NOOPBlockBodyHooks,
bool,
]()
},
Expand All @@ -70,7 +70,7 @@ func TestStateObjectEmpty(t *testing.T) {
registerAndSet: func(acc *types.StateAccount) {
types.RegisterExtras[
types.NOOPHeaderHooks, *types.NOOPHeaderHooks,
types.NOOPBodyHooks, *types.NOOPBodyHooks,
types.NOOPBlockBodyHooks, *types.NOOPBlockBodyHooks,
bool,
]().StateAccount.Set(acc, true)
},
Expand Down
122 changes: 109 additions & 13 deletions core/types/backwards_compat.libevm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,11 @@ import (
"github.com/ava-labs/libevm/rlp"
)

func TestBodyRLPBackwardsCompatibility(t *testing.T) {
newTx := func(nonce uint64) *Transaction { return NewTx(&LegacyTx{Nonce: nonce}) }
newHdr := func(hashLow byte) *Header { return &Header{ParentHash: common.Hash{hashLow}} }
newWithdraw := func(idx uint64) *Withdrawal { return &Withdrawal{Index: idx} }
func newTx(nonce uint64) *Transaction { return NewTx(&LegacyTx{Nonce: nonce}) }
func newHdr(parentHashHigh byte) *Header { return &Header{ParentHash: common.Hash{parentHashHigh}} }
func newWithdraw(idx uint64) *Withdrawal { return &Withdrawal{Index: idx} }

func blockBodyRLPTestInputs() []*Body {
// We build up test-case [Body] instances from the Cartesian product of each
// of these components.
txMatrix := [][]*Transaction{
Expand All @@ -61,8 +61,11 @@ func TestBodyRLPBackwardsCompatibility(t *testing.T) {
}
}
}
return bodies
}

for _, body := range bodies {
func TestBodyRLPBackwardsCompatibility(t *testing.T) {
for _, body := range blockBodyRLPTestInputs() {
t.Run("", func(t *testing.T) {
t.Cleanup(func() {
if t.Failed() {
Expand All @@ -86,8 +89,10 @@ func TestBodyRLPBackwardsCompatibility(t *testing.T) {
t.Run("Decode", func(t *testing.T) {
got := new(Body)
err := rlp.DecodeBytes(wantRLP, got)
require.NoErrorf(t, err, "rlp.DecodeBytes(rlp.EncodeToBytes(%T), %T) resulted in %s",
(*withoutMethods)(body), got, pretty.Sprint(got))
require.NoErrorf(
t, err, "rlp.DecodeBytes(rlp.EncodeToBytes(%T), %T) resulted in %s",
(*withoutMethods)(body), got, pretty.Sprint(got),
)
ARR4N marked this conversation as resolved.
Show resolved Hide resolved

want := body
// Regular RLP decoding will never leave these non-optional
Expand All @@ -112,17 +117,94 @@ func TestBodyRLPBackwardsCompatibility(t *testing.T) {
}
}

func TestBlockRLPBackwardsCompatibility(t *testing.T) {
TestOnlyClearRegisteredExtras()
t.Cleanup(TestOnlyClearRegisteredExtras)

RegisterExtras[
NOOPHeaderHooks, *NOOPHeaderHooks,
NOOPBlockBodyHooks, *NOOPBlockBodyHooks, // types under test
struct{},
]()

// Note that there are also a number of tests in `block_test.go` that ensure
// backwards compatibility as [NOOPBlockBodyHooks] are used by default when
// nothing is registered (the above registration is only for completeness).

for _, body := range blockBodyRLPTestInputs() {
t.Run("", func(t *testing.T) {
// [Block] doesn't export most of its fields so uses [extblock] as a
// proxy for RLP encoding, which is what we therefore use as the
// backwards-compatible gold standard.
hdr := newHdr(99)
block := extblock{
Header: hdr,
Txs: body.Transactions,
Uncles: body.Uncles,
Withdrawals: body.Withdrawals,
}

// We've added [extblock.EncodeRLP] and [extblock.DecodeRLP] for our
// hooks.
type withoutMethods extblock

wantRLP, err := rlp.EncodeToBytes(withoutMethods(block))
require.NoErrorf(t, err, "rlp.EncodeToBytes([%T with methods stripped])", block)

// Our input to RLP might not be the canonical RLP output.
var wantBlock extblock
err = rlp.DecodeBytes(wantRLP, (*withoutMethods)(&wantBlock))
require.NoErrorf(t, err, "rlp.DecodeBytes(..., [%T with methods stripped])", &wantBlock)

t.Run("Encode", func(t *testing.T) {
b := NewBlockWithHeader(hdr).WithBody(*body).WithWithdrawals(body.Withdrawals)
got, err := rlp.EncodeToBytes(b)
require.NoErrorf(t, err, "rlp.EncodeToBytes(%T)", b)

assert.Equalf(t, wantRLP, got, "expect %T RLP identical to that from %T struct stripped of methods", got, extblock{})
})

t.Run("Decode", func(t *testing.T) {
var gotBlock Block
err := rlp.DecodeBytes(wantRLP, &gotBlock)
require.NoErrorf(t, err, "rlp.DecodeBytes(..., %T)", &gotBlock)

got := extblock{
gotBlock.Header(),
gotBlock.Transactions(),
gotBlock.Uncles(),
gotBlock.Withdrawals(),
nil, // unexported libevm hooks
}

opts := cmp.Options{
cmp.Comparer((*Header).equalHash),
cmp.Comparer((*Transaction).equalHash),
cmpopts.IgnoreUnexported(extblock{}),
}
if diff := cmp.Diff(wantBlock, got, opts); diff != "" {
t.Errorf("rlp.DecodeBytes([RLP from %T stripped of methods], ...) diff (-want +got):\n%s", extblock{}, diff)
}
})
})
}
}

// cChainBodyExtras carries the same additional fields as the Avalanche C-Chain
// (ava-labs/coreth) [Body] and implements [BodyHooks] to achieve equivalent RLP
// {en,de}coding.
// (ava-labs/coreth) [Body] and implements [BlockBodyHooks] to achieve
// equivalent RLP {en,de}coding.
//
// It is not intended as a full test of ava-labs/coreth existing functionality,
// which should be implemented when that module consumes libevm, but as proof of
// equivalence of the [rlp.Fields] approach.
type cChainBodyExtras struct {
Version uint32
ExtData *[]byte
}

var _ BodyHooks = (*cChainBodyExtras)(nil)
var _ BlockBodyHooks = (*cChainBodyExtras)(nil)

func (e *cChainBodyExtras) RLPFieldsForEncoding(b *Body) *rlp.Fields {
func (e *cChainBodyExtras) BodyRLPFieldsForEncoding(b *Body) *rlp.Fields {
// The Avalanche C-Chain uses all of the geth required fields (but none of
// the optional ones) so there's no need to explicitly list them. This
// pattern might not be ideal for readability but is used here for
Expand All @@ -132,13 +214,13 @@ func (e *cChainBodyExtras) RLPFieldsForEncoding(b *Body) *rlp.Fields {
// compatibility so this is safe to do, but only for the required fields.
return &rlp.Fields{
Required: append(
NOOPBodyHooks{}.RLPFieldsForEncoding(b).Required,
NOOPBlockBodyHooks{}.BodyRLPFieldsForEncoding(b).Required,
e.Version, e.ExtData,
),
}
}

func (e *cChainBodyExtras) RLPFieldPointersForDecoding(b *Body) *rlp.Fields {
func (e *cChainBodyExtras) BodyRLPFieldPointersForDecoding(b *Body) *rlp.Fields {
// An alternative to the pattern used above is to explicitly list all
// fields for better introspection.
return &rlp.Fields{
Expand All @@ -151,6 +233,20 @@ func (e *cChainBodyExtras) RLPFieldPointersForDecoding(b *Body) *rlp.Fields {
}
}

// See [cChainBodyExtras] intent.

func (e *cChainBodyExtras) Copy() *cChainBodyExtras {
panic("unimplemented")
}

func (e *cChainBodyExtras) BlockRLPFieldsForEncoding(b *BlockRLPProxy) *rlp.Fields {
panic("unimplemented")
qdm12 marked this conversation as resolved.
Show resolved Hide resolved
}

func (e *cChainBodyExtras) BlockRLPFieldPointersForDecoding(b *BlockRLPProxy) *rlp.Fields {
panic("unimplemented")
qdm12 marked this conversation as resolved.
Show resolved Hide resolved
}

func TestBodyRLPCChainCompat(t *testing.T) {
qdm12 marked this conversation as resolved.
Show resolved Hide resolved
// The inputs to this test were used to generate the expected RLP with
// ava-labs/coreth. This serves as both an example of how to use [BodyHooks]
Expand Down
2 changes: 1 addition & 1 deletion core/types/backwards_compat_diffpkg.libevm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ func TestHeaderRLPBackwardsCompatibility(t *testing.T) {
register: func() {
RegisterExtras[
NOOPHeaderHooks, *NOOPHeaderHooks,
NOOPBodyHooks, *NOOPBodyHooks,
NOOPBlockBodyHooks, *NOOPBlockBodyHooks,
struct{},
]()
},
Expand Down
11 changes: 10 additions & 1 deletion core/types/block.go
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,8 @@ type Block struct {
// inter-peer block relay.
ReceivedAt time.Time
ReceivedFrom interface{}

extra *pseudo.Type // See [RegisterExtras]
}

// "external" block encoding. used for eth protocol, etc.
Expand All @@ -219,6 +221,8 @@ type extblock struct {
Txs []*Transaction
Uncles []*Header
Withdrawals []*Withdrawal `rlp:"optional"`

hooks BlockBodyHooks // libevm: MUST be unexported + populated from [Block.hooks]
}

// NewBlock creates a new block. The input data is copied, changes to header and to the
Expand Down Expand Up @@ -318,6 +322,7 @@ func CopyHeader(h *Header) *Header {
// DecodeRLP decodes a block from RLP.
func (b *Block) DecodeRLP(s *rlp.Stream) error {
var eb extblock
eb.hooks = b.hooks()
_, size, _ := s.Kind()
if err := s.Decode(&eb); err != nil {
return err
Expand All @@ -334,13 +339,14 @@ func (b *Block) EncodeRLP(w io.Writer) error {
Txs: b.transactions,
Uncles: b.uncles,
Withdrawals: b.withdrawals,
hooks: b.hooks(),
})
}

// Body returns the non-header content of the block.
// Note the returned data is not an independent copy.
func (b *Block) Body() *Body {
return &Body{b.transactions, b.uncles, b.withdrawals, nil /* unexported extras field */}
return &Body{b.transactions, b.uncles, b.withdrawals, b.cloneExtra()}
Copy link
Collaborator

Choose a reason for hiding this comment

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

do we want to clone? Wondering given we don't really deep copy any other field

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Here's my thinking:

I've been bitten really hard in the past by bugs caused by a lack of it (queue 📣 🦀) so by default I tend to give my API users at least a choice or signal. Forcing them to have a pointer payload is only a subtle hint while the use of pseudo.Type really obscures things for someone who just wants to use libevm without knowing its internals.

Not including it feels like setting a trap for a libevm consumer to walk straight into. WDYT?

Copy link
Collaborator

Choose a reason for hiding this comment

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

Deep copy is great, especially by default.
But I am worrying a bit about performance, and wondering why most of these calls don't deep copy things. Changing them to deep copy the extra might result in a noticeable performance impact.
Ideally we should benchmark and measure all this, but.... first I'm lazy, second we're trying to get this done fast, third it looks like geth doesn't deep copy for performance? What do you think? 🤔

Copy link
Collaborator Author

@ARR4N ARR4N Feb 13, 2025

Choose a reason for hiding this comment

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

This doesn't force a deep copy on the user as they're free to return the original. Any performance issues here, measured per block, are almost certainly dwarfed by those measured per storage R/W operation. As an example, I benchmarked the impact of a change from the rlpgen code for Header.EncodeRLP() to one using rlp.Fields (likely larger than a copy here) and it only adds 1.5μs (i.e. 1.5 millionths of a second) on my laptop.

I think we're far more likely to shoot ourselves in the foot due to a missed copy than we are to take a meaningful performance hit, and we can always revisit performance while we aren't guaranteed the opportunity to revisit a catastrophic bug.

}

// Accessors for body data. These do not return a copy because the content
Expand Down Expand Up @@ -458,6 +464,7 @@ func (b *Block) WithSeal(header *Header) *Block {
transactions: b.transactions,
uncles: b.uncles,
withdrawals: b.withdrawals,
extra: b.cloneExtra(),
ARR4N marked this conversation as resolved.
Show resolved Hide resolved
}
}

Expand All @@ -468,6 +475,7 @@ func (b *Block) WithBody(body Body) *Block {
transactions: make([]*Transaction, len(body.Transactions)),
uncles: make([]*Header, len(body.Uncles)),
withdrawals: b.withdrawals,
extra: body.cloneExtra(),
}
copy(block.transactions, body.Transactions)
for i := range body.Uncles {
Expand All @@ -482,6 +490,7 @@ func (b *Block) WithWithdrawals(withdrawals []*Withdrawal) *Block {
header: b.header,
transactions: b.transactions,
uncles: b.uncles,
extra: b.cloneExtra(),
ARR4N marked this conversation as resolved.
Show resolved Hide resolved
}
if withdrawals != nil {
block.withdrawals = make([]*Withdrawal, len(withdrawals))
Expand Down
Loading