Skip to content

Commit 98c935d

Browse files
lightclientjorgemmsilva
authored andcommitted
all: refactor so NewBlock, WithBody take types.Body (ethereum#29482)
* all: refactor so NewBlock(..) and WithBody(..) take a types.Body * core: fixup comments, remove txs != receipts panic * core/types: add empty withdrawls to body if len == 0
1 parent 996d297 commit 98c935d

File tree

23 files changed

+81
-76
lines changed

23 files changed

+81
-76
lines changed

beacon/engine/types.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -250,7 +250,7 @@ func ExecutableDataToBlock(params ExecutableData, versionedHashes []common.Hash,
250250
BlobGasUsed: params.BlobGasUsed,
251251
ParentBeaconRoot: beaconRoot,
252252
}
253-
block := types.NewBlockWithHeader(header).WithBody(txs, nil /* uncles */).WithWithdrawals(params.Withdrawals)
253+
block := types.NewBlockWithHeader(header).WithBody(types.Body{Transactions: txs, Uncles: nil, Withdrawals: params.Withdrawals})
254254
if block.Hash() != params.BlockHash {
255255
return nil, fmt.Errorf("blockhash mismatch, want %x, got %x", params.BlockHash, block.Hash())
256256
}

beacon/types/exec_payload.go

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -63,9 +63,7 @@ func convertPayload[T payloadType](payload T, parentRoot *zrntcommon.Root) (*typ
6363
panic("unsupported block type")
6464
}
6565

66-
block := types.NewBlockWithHeader(&header)
67-
block = block.WithBody(transactions, nil)
68-
block = block.WithWithdrawals(withdrawals)
66+
block := types.NewBlockWithHeader(&header).WithBody(types.Body{Transactions: transactions, Withdrawals: withdrawals})
6967
if hash := block.Hash(); hash != expectedHash {
7068
return nil, fmt.Errorf("Sanity check failed, payload hash does not match (expected %x, got %x)", expectedHash, hash)
7169
}

cmd/evm/internal/t8ntool/block.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@ func (i *bbInput) ToBlock() *types.Block {
160160
if i.Header.Difficulty != nil {
161161
header.Difficulty = i.Header.Difficulty
162162
}
163-
return types.NewBlockWithHeader(header).WithBody(i.Txs, i.Ommers).WithWithdrawals(i.Withdrawals)
163+
return types.NewBlockWithHeader(header).WithBody(types.Body{Transactions: i.Txs, Uncles: i.Ommers, Withdrawals: i.Withdrawals})
164164
}
165165

166166
// SealBlock seals the given block using the configured engine.

consensus/beacon/consensus.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -388,7 +388,7 @@ func (beacon *Beacon) FinalizeAndAssemble(chain consensus.ChainHeaderReader, hea
388388
header.Root = state.IntermediateRoot(true)
389389

390390
// Assemble and return the final block.
391-
return types.NewBlockWithWithdrawals(header, body.Transactions, body.Uncles, receipts, body.Withdrawals, trie.NewStackTrie(nil)), nil
391+
return types.NewBlock(header, body, receipts, trie.NewStackTrie(nil)), nil
392392
}
393393

394394
// Seal generates a new sealing request for the given input block and pushes

consensus/clique/clique.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -597,7 +597,7 @@ func (c *Clique) FinalizeAndAssemble(chain consensus.ChainHeaderReader, header *
597597
header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number))
598598

599599
// Assemble and return the final block for sealing.
600-
return types.NewBlock(header, body.Transactions, nil, receipts, trie.NewStackTrie(nil)), nil
600+
return types.NewBlock(header, &types.Body{Transactions: body.Transactions}, receipts, trie.NewStackTrie(nil)), nil
601601
}
602602

603603
// Authorize injects a private key into the consensus engine to mint new blocks

consensus/ethash/consensus.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -520,7 +520,7 @@ func (ethash *Ethash) FinalizeAndAssemble(chain consensus.ChainHeaderReader, hea
520520
header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number))
521521

522522
// Header seems complete, assemble into a block and return
523-
return types.NewBlock(header, body.Transactions, body.Uncles, receipts, trie.NewStackTrie(nil)), nil
523+
return types.NewBlock(header, &types.Body{Transactions: body.Transactions, Uncles: body.Uncles}, receipts, trie.NewStackTrie(nil)), nil
524524
}
525525

526526
// SealHash returns the hash of a block prior to it being sealed.

core/genesis.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -476,7 +476,7 @@ func (g *Genesis) ToBlock() *types.Block {
476476
}
477477
}
478478
}
479-
return types.NewBlock(head, nil, nil, nil, trie.NewStackTrie(nil)).WithWithdrawals(withdrawals)
479+
return types.NewBlock(head, &types.Body{Withdrawals: withdrawals}, nil, trie.NewStackTrie(nil))
480480
}
481481

482482
// Commit writes the block and state of a genesis specification to the database.

core/rawdb/accessors_chain.go

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -753,7 +753,7 @@ func ReadBlock(db ethdb.Reader, hash common.Hash, number uint64) *types.Block {
753753
if body == nil {
754754
return nil
755755
}
756-
return types.NewBlockWithHeader(header).WithBody(body.Transactions, body.Uncles).WithWithdrawals(body.Withdrawals)
756+
return types.NewBlockWithHeader(header).WithBody(*body)
757757
}
758758

759759
// WriteBlock serializes a block into the database, header and body separately.
@@ -843,7 +843,11 @@ func ReadBadBlock(db ethdb.Reader, hash common.Hash) *types.Block {
843843
}
844844
for _, bad := range badBlocks {
845845
if bad.Header.Hash() == hash {
846-
return types.NewBlockWithHeader(bad.Header).WithBody(bad.Body.Transactions, bad.Body.Uncles).WithWithdrawals(bad.Body.Withdrawals)
846+
block := types.NewBlockWithHeader(bad.Header)
847+
if bad.Body != nil {
848+
block = block.WithBody(*bad.Body)
849+
}
850+
return block
847851
}
848852
}
849853
return nil
@@ -862,7 +866,11 @@ func ReadAllBadBlocks(db ethdb.Reader) []*types.Block {
862866
}
863867
var blocks []*types.Block
864868
for _, bad := range badBlocks {
865-
blocks = append(blocks, types.NewBlockWithHeader(bad.Header).WithBody(bad.Body.Transactions, bad.Body.Uncles).WithWithdrawals(bad.Body.Withdrawals))
869+
block := types.NewBlockWithHeader(bad.Header)
870+
if bad.Body != nil {
871+
block = block.WithBody(*bad.Body)
872+
}
873+
blocks = append(blocks, block)
866874
}
867875
return blocks
868876
}

core/rawdb/accessors_chain_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -640,7 +640,7 @@ func makeTestBlocks(nblock int, txsPerBlock int) []*types.Block {
640640
Number: big.NewInt(int64(i)),
641641
Extra: []byte("test block"),
642642
}
643-
blocks[i] = types.NewBlockWithHeader(header).WithBody(txs, nil)
643+
blocks[i] = types.NewBlockWithHeader(header).WithBody(types.Body{Transactions: txs})
644644
blocks[i].Hash() // pre-cache the block hash
645645
}
646646
return blocks

core/rawdb/accessors_indexes_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ func TestLookupStorage(t *testing.T) {
7676
tx3 := types.NewTransaction(3, common.BytesToAddress([]byte{0x33}), big.NewInt(333), 3333, big.NewInt(33333), []byte{0x33, 0x33, 0x33})
7777
txs := []*types.Transaction{tx1, tx2, tx3}
7878

79-
block := types.NewBlock(&types.Header{Number: big.NewInt(314)}, txs, nil, nil, newTestHasher())
79+
block := types.NewBlock(&types.Header{Number: big.NewInt(314)}, &types.Body{Transactions: txs}, nil, newTestHasher())
8080

8181
// Check that no transactions entries are in a pristine database
8282
for i, tx := range txs {

core/rawdb/chain_iterator_test.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ func TestChainIterator(t *testing.T) {
3434
var block *types.Block
3535
var txs []*types.Transaction
3636
to := common.BytesToAddress([]byte{0x11})
37-
block = types.NewBlock(&types.Header{Number: big.NewInt(int64(0))}, nil, nil, nil, newTestHasher()) // Empty genesis block
37+
block = types.NewBlock(&types.Header{Number: big.NewInt(int64(0))}, nil, nil, newTestHasher()) // Empty genesis block
3838
WriteBlock(chainDb, block)
3939
WriteCanonicalHash(chainDb, block.Hash(), block.NumberU64())
4040
for i := uint64(1); i <= 10; i++ {
@@ -60,7 +60,7 @@ func TestChainIterator(t *testing.T) {
6060
})
6161
}
6262
txs = append(txs, tx)
63-
block = types.NewBlock(&types.Header{Number: big.NewInt(int64(i))}, []*types.Transaction{tx}, nil, nil, newTestHasher())
63+
block = types.NewBlock(&types.Header{Number: big.NewInt(int64(i))}, &types.Body{Transactions: types.Transactions{tx}}, nil, newTestHasher())
6464
WriteBlock(chainDb, block)
6565
WriteCanonicalHash(chainDb, block.Hash(), block.NumberU64())
6666
}
@@ -111,7 +111,7 @@ func TestIndexTransactions(t *testing.T) {
111111
to := common.BytesToAddress([]byte{0x11})
112112

113113
// Write empty genesis block
114-
block = types.NewBlock(&types.Header{Number: big.NewInt(int64(0))}, nil, nil, nil, newTestHasher())
114+
block = types.NewBlock(&types.Header{Number: big.NewInt(int64(0))}, nil, nil, newTestHasher())
115115
WriteBlock(chainDb, block)
116116
WriteCanonicalHash(chainDb, block.Hash(), block.NumberU64())
117117

@@ -138,7 +138,7 @@ func TestIndexTransactions(t *testing.T) {
138138
})
139139
}
140140
txs = append(txs, tx)
141-
block = types.NewBlock(&types.Header{Number: big.NewInt(int64(i))}, []*types.Transaction{tx}, nil, nil, newTestHasher())
141+
block = types.NewBlock(&types.Header{Number: big.NewInt(int64(i))}, &types.Body{Transactions: types.Transactions{tx}}, nil, newTestHasher())
142142
WriteBlock(chainDb, block)
143143
WriteCanonicalHash(chainDb, block.Hash(), block.NumberU64())
144144
}

core/state_processor_test.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -417,10 +417,11 @@ func GenerateBadBlock(parent *types.Block, engine consensus.Engine, txs types.Tr
417417
header.ParentBeaconRoot = &beaconRoot
418418
}
419419
// Assemble and return the final block for sealing
420+
body := &types.Body{Transactions: txs}
420421
if config.IsShanghai(header.Number, header.Time) {
421-
return types.NewBlockWithWithdrawals(header, txs, nil, receipts, []*types.Withdrawal{}, trie.NewStackTrie(nil))
422+
body.Withdrawals = []*types.Withdrawal{}
422423
}
423-
return types.NewBlock(header, txs, nil, receipts, trie.NewStackTrie(nil))
424+
return types.NewBlock(header, body, receipts, trie.NewStackTrie(nil))
424425
}
425426

426427
var (

core/txpool/legacypool/legacypool_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ func (bc *testBlockChain) CurrentBlock() *types.Header {
8787
}
8888

8989
func (bc *testBlockChain) GetBlock(hash common.Hash, number uint64) *types.Block {
90-
return types.NewBlock(bc.CurrentBlock(), nil, nil, nil, trie.NewStackTrie(nil))
90+
return types.NewBlock(bc.CurrentBlock(), nil, nil, trie.NewStackTrie(nil))
9191
}
9292

9393
func (bc *testBlockChain) StateAt(common.Hash) (*state.StateDB, error) {

core/types/block.go

Lines changed: 26 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import (
2323
"io"
2424
"math/big"
2525
"reflect"
26+
"slices"
2627
"sync/atomic"
2728
"time"
2829

@@ -217,13 +218,19 @@ type extblock struct {
217218
// NewBlock creates a new block. The input data is copied, changes to header and to the
218219
// field values will not affect the block.
219220
//
220-
// The values of TxHash, UncleHash, ReceiptHash and Bloom in header
221-
// are ignored and set to values derived from the given txs, uncles
222-
// and receipts.
223-
func NewBlock(header *Header, txs []*Transaction, uncles []*Header, receipts []*Receipt, hasher TrieHasher) *Block {
224-
b := &Block{header: CopyHeader(header)}
221+
// The body elements and the receipts are used to recompute and overwrite the
222+
// relevant portions of the header.
223+
func NewBlock(header *Header, body *Body, receipts []*Receipt, hasher TrieHasher) *Block {
224+
if body == nil {
225+
body = &Body{}
226+
}
227+
var (
228+
b = NewBlockWithHeader(header)
229+
txs = body.Transactions
230+
uncles = body.Uncles
231+
withdrawals = body.Withdrawals
232+
)
225233

226-
// TODO: panic if len(txs) != len(receipts)
227234
if len(txs) == 0 {
228235
b.header.TxHash = EmptyTxsHash
229236
} else {
@@ -249,27 +256,18 @@ func NewBlock(header *Header, txs []*Transaction, uncles []*Header, receipts []*
249256
}
250257
}
251258

252-
return b
253-
}
254-
255-
// NewBlockWithWithdrawals creates a new block with withdrawals. The input data is copied,
256-
// changes to header and to the field values will not affect the block.
257-
//
258-
// The values of TxHash, UncleHash, ReceiptHash and Bloom in header are ignored and set to
259-
// values derived from the given txs, uncles and receipts.
260-
func NewBlockWithWithdrawals(header *Header, txs []*Transaction, uncles []*Header, receipts []*Receipt, withdrawals []*Withdrawal, hasher TrieHasher) *Block {
261-
b := NewBlock(header, txs, uncles, receipts, hasher)
262-
263259
if withdrawals == nil {
264260
b.header.WithdrawalsHash = nil
265261
} else if len(withdrawals) == 0 {
266262
b.header.WithdrawalsHash = &EmptyWithdrawalsHash
263+
b.withdrawals = Withdrawals{}
267264
} else {
268-
h := DeriveSha(Withdrawals(withdrawals), hasher)
269-
b.header.WithdrawalsHash = &h
265+
hash := DeriveSha(Withdrawals(withdrawals), hasher)
266+
b.header.WithdrawalsHash = &hash
267+
b.withdrawals = slices.Clone(withdrawals)
270268
}
271269

272-
return b.WithWithdrawals(withdrawals)
270+
return b
273271
}
274272

275273
// CopyHeader creates a deep copy of a block header.
@@ -453,31 +451,17 @@ func (b *Block) WithSeal(header *Header) *Block {
453451
}
454452
}
455453

456-
// WithBody returns a copy of the block with the given transaction and uncle contents.
457-
func (b *Block) WithBody(transactions []*Transaction, uncles []*Header) *Block {
458-
block := &Block{
459-
header: b.header,
460-
transactions: make([]*Transaction, len(transactions)),
461-
uncles: make([]*Header, len(uncles)),
462-
withdrawals: b.withdrawals,
463-
}
464-
copy(block.transactions, transactions)
465-
for i := range uncles {
466-
block.uncles[i] = CopyHeader(uncles[i])
467-
}
468-
return block
469-
}
470-
471-
// WithWithdrawals returns a copy of the block containing the given withdrawals.
472-
func (b *Block) WithWithdrawals(withdrawals []*Withdrawal) *Block {
454+
// WithBody returns a new block with the original header and a deep copy of the
455+
// provided body.
456+
func (b *Block) WithBody(body Body) *Block {
473457
block := &Block{
474458
header: b.header,
475-
transactions: b.transactions,
476-
uncles: b.uncles,
459+
transactions: slices.Clone(body.Transactions),
460+
uncles: make([]*Header, len(body.Uncles)),
461+
withdrawals: slices.Clone(body.Withdrawals),
477462
}
478-
if withdrawals != nil {
479-
block.withdrawals = make([]*Withdrawal, len(withdrawals))
480-
copy(block.withdrawals, withdrawals)
463+
for i := range body.Uncles {
464+
block.uncles[i] = CopyHeader(body.Uncles[i])
481465
}
482466
return block
483467
}

core/types/block_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -254,7 +254,7 @@ func makeBenchBlock() *Block {
254254
Extra: []byte("benchmark uncle"),
255255
}
256256
}
257-
return NewBlock(header, txs, uncles, receipts, blocktest.NewHasher())
257+
return NewBlock(header, &Body{Transactions: txs, Uncles: uncles}, receipts, blocktest.NewHasher())
258258
}
259259

260260
func TestRlpDecodeParentHash(t *testing.T) {

eth/catalyst/api_test.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -779,7 +779,7 @@ func setBlockhash(data *engine.ExecutableData) *engine.ExecutableData {
779779
Extra: data.ExtraData,
780780
MixDigest: data.Random,
781781
}
782-
block := types.NewBlockWithHeader(header).WithBody(txs, nil /* uncles */)
782+
block := types.NewBlockWithHeader(header).WithBody(types.Body{Transactions: txs})
783783
data.BlockHash = block.Hash()
784784
return data
785785
}
@@ -935,7 +935,7 @@ func TestNewPayloadOnInvalidTerminalBlock(t *testing.T) {
935935
Extra: data.ExtraData,
936936
MixDigest: data.Random,
937937
}
938-
block := types.NewBlockWithHeader(header).WithBody(txs, nil /* uncles */)
938+
block := types.NewBlockWithHeader(header).WithBody(types.Body{Transactions: txs})
939939
data.BlockHash = block.Hash()
940940
// Send the new payload
941941
resp2, err := api.NewPayloadV1(data)
@@ -1554,7 +1554,7 @@ func TestBlockToPayloadWithBlobs(t *testing.T) {
15541554
},
15551555
}
15561556

1557-
block := types.NewBlock(&header, txs, nil, nil, trie.NewStackTrie(nil))
1557+
block := types.NewBlock(&header, &types.Body{Transactions: txs}, nil, trie.NewStackTrie(nil))
15581558
envelope := engine.BlockToExecutableData(block, nil, sidecars)
15591559
var want int
15601560
for _, tx := range txs {

eth/downloader/downloader.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1504,7 +1504,7 @@ func (d *Downloader) importBlockResults(results []*fetchResult) error {
15041504
)
15051505
blocks := make([]*types.Block, len(results))
15061506
for i, result := range results {
1507-
blocks[i] = types.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles).WithWithdrawals(result.Withdrawals)
1507+
blocks[i] = types.NewBlockWithHeader(result.Header).WithBody(result.body())
15081508
}
15091509
// Downloaded blocks are always regarded as trusted after the
15101510
// transition. Because the downloaded chain is guided by the
@@ -1726,7 +1726,7 @@ func (d *Downloader) commitSnapSyncData(results []*fetchResult, stateSync *state
17261726
blocks := make([]*types.Block, len(results))
17271727
receipts := make([]types.Receipts, len(results))
17281728
for i, result := range results {
1729-
blocks[i] = types.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles).WithWithdrawals(result.Withdrawals)
1729+
blocks[i] = types.NewBlockWithHeader(result.Header).WithBody(result.body())
17301730
receipts[i] = result.Receipts
17311731
}
17321732
if index, err := d.blockchain.InsertReceiptChain(blocks, receipts, d.ancientLimit); err != nil {
@@ -1737,7 +1737,7 @@ func (d *Downloader) commitSnapSyncData(results []*fetchResult, stateSync *state
17371737
}
17381738

17391739
func (d *Downloader) commitPivotBlock(result *fetchResult) error {
1740-
block := types.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles).WithWithdrawals(result.Withdrawals)
1740+
block := types.NewBlockWithHeader(result.Header).WithBody(result.body())
17411741
log.Debug("Committing snap sync pivot as new head", "number", block.Number(), "hash", block.Hash())
17421742

17431743
// Commit the pivot block as the new head, will require full sync from here on

eth/downloader/queue.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,15 @@ func newFetchResult(header *types.Header, fastSync bool) *fetchResult {
8787
return item
8888
}
8989

90+
// body returns a representation of the fetch result as a types.Body object.
91+
func (f *fetchResult) body() types.Body {
92+
return types.Body{
93+
Transactions: f.Transactions,
94+
Uncles: f.Uncles,
95+
Withdrawals: f.Withdrawals,
96+
}
97+
}
98+
9099
// SetBodyDone flags the body as finished.
91100
func (f *fetchResult) SetBodyDone() {
92101
if v := f.pending.Load(); (v & (1 << bodyType)) != 0 {

ethclient/ethclient.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,12 @@ func (ec *Client) getBlock(ctx context.Context, method string, args ...interface
191191
}
192192
txs[i] = tx.tx
193193
}
194-
return types.NewBlockWithHeader(head).WithBody(txs, uncles).WithWithdrawals(body.Withdrawals), nil
194+
return types.NewBlockWithHeader(head).WithBody(
195+
types.Body{
196+
Transactions: txs,
197+
Uncles: uncles,
198+
Withdrawals: body.Withdrawals,
199+
}), nil
195200
}
196201

197202
// HeaderByHash returns the block header with the given hash.

internal/era/era.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ func (e *Era) GetBlockByNumber(num uint64) (*types.Block, error) {
151151
if err := rlp.Decode(r, &body); err != nil {
152152
return nil, err
153153
}
154-
return types.NewBlockWithHeader(&header).WithBody(body.Transactions, body.Uncles), nil
154+
return types.NewBlockWithHeader(&header).WithBody(body), nil
155155
}
156156

157157
// Accumulator reads the accumulator entry in the Era1 file.

internal/era/iterator.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ func (it *Iterator) Block() (*types.Block, error) {
7373
if err := rlp.Decode(it.inner.Body, &body); err != nil {
7474
return nil, err
7575
}
76-
return types.NewBlockWithHeader(&header).WithBody(body.Transactions, body.Uncles), nil
76+
return types.NewBlockWithHeader(&header).WithBody(body), nil
7777
}
7878

7979
// Receipts returns the receipts for the iterator's current position.

0 commit comments

Comments
 (0)