all: refactor so NewBlock, WithBody take types.Body #29482 (#1605)

This commit is contained in:
Daniel Liu 2025-10-08 13:12:35 +08:00 committed by GitHub
parent c74515fcca
commit 3efe26df08
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
20 changed files with 71 additions and 47 deletions

View file

@ -850,7 +850,7 @@ func (x *XDPoS_v1) Finalize(chain consensus.ChainReader, header *types.Header, s
header.UncleHash = types.CalcUncleHash(nil) header.UncleHash = types.CalcUncleHash(nil)
// Assemble and return the final block for sealing // Assemble and return the final block for sealing
return types.NewBlock(header, txs, nil, receipts, trie.NewStackTrie(nil)), nil return types.NewBlock(header, &types.Body{Transactions: txs}, receipts, trie.NewStackTrie(nil)), nil
} }
// Authorize injects a private key into the consensus engine to mint new blocks // Authorize injects a private key into the consensus engine to mint new blocks

View file

@ -440,7 +440,7 @@ func (x *XDPoS_v2) Finalize(chain consensus.ChainReader, header *types.Header, s
header.UncleHash = types.CalcUncleHash(nil) header.UncleHash = types.CalcUncleHash(nil)
// Assemble and return the final block for sealing // Assemble and return the final block for sealing
return types.NewBlock(header, txs, nil, receipts, trie.NewStackTrie(nil)), nil return types.NewBlock(header, &types.Body{Transactions: txs}, receipts, trie.NewStackTrie(nil)), nil
} }
// Authorize injects a private key into the consensus engine to mint new blocks with. // Authorize injects a private key into the consensus engine to mint new blocks with.

View file

@ -589,7 +589,7 @@ func (c *Clique) Finalize(chain consensus.ChainReader, header *types.Header, sta
header.UncleHash = types.CalcUncleHash(nil) header.UncleHash = types.CalcUncleHash(nil)
// Assemble and return the final block for sealing // Assemble and return the final block for sealing
return types.NewBlock(header, txs, nil, receipts, trie.NewStackTrie(nil)), nil return types.NewBlock(header, &types.Body{Transactions: txs}, receipts, trie.NewStackTrie(nil)), nil
} }
// Authorize injects a private key into the consensus engine to mint new blocks // Authorize injects a private key into the consensus engine to mint new blocks

View file

@ -437,7 +437,7 @@ func (ethash *Ethash) Finalize(chain consensus.ChainReader, header *types.Header
header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number)) header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number))
// Header seems complete, assemble into a block and return // Header seems complete, assemble into a block and return
return types.NewBlock(header, txs, uncles, receipts, trie.NewStackTrie(nil)), nil return types.NewBlock(header, &types.Body{Transactions: txs, Uncles: uncles}, receipts, trie.NewStackTrie(nil)), nil
} }
// Some weird constants to avoid constant memory allocs for them. // Some weird constants to avoid constant memory allocs for them.

View file

@ -382,7 +382,7 @@ func createBlockFromHeader(bc *core.BlockChain, customHeader *types.Header, txs
} }
header.GasUsed = *gasUsed header.GasUsed = *gasUsed
block = types.NewBlock(&header, txs, nil, receipts, trie.NewStackTrie(nil)) block = types.NewBlock(&header, &types.Body{Transactions: txs}, receipts, trie.NewStackTrie(nil))
} }
return block, nil return block, nil

View file

@ -917,7 +917,7 @@ func createBlockFromHeader(bc *core.BlockChain, customHeader *types.Header, txs
header.Coinbase = signerAddress header.Coinbase = signerAddress
sealHeader(bc, &header, signerAddress, signerFunction) sealHeader(bc, &header, signerAddress, signerFunction)
block = types.NewBlock(&header, txs, nil, receipts, trie.NewStackTrie(nil)) block = types.NewBlock(&header, &types.Body{Transactions: txs}, receipts, trie.NewStackTrie(nil))
} }
return block, nil return block, nil

View file

@ -261,7 +261,7 @@ func (g *Genesis) ToBlock(db ethdb.Database) *types.Block {
statedb.Commit(false) statedb.Commit(false)
statedb.Database().TrieDB().Commit(root, true) statedb.Database().TrieDB().Commit(root, true)
return types.NewBlock(head, nil, nil, nil, trie.NewStackTrie(nil)) return types.NewBlock(head, nil, nil, trie.NewStackTrie(nil))
} }
// Commit writes the block and state of a genesis specification to the database. // Commit writes the block and state of a genesis specification to the database.

View file

@ -575,7 +575,7 @@ func ReadBlock(db ethdb.Reader, hash common.Hash, number uint64) *types.Block {
return nil return nil
} }
// Reassemble the block and return // Reassemble the block and return
return types.NewBlockWithHeader(header).WithBody(body.Transactions, body.Uncles) return types.NewBlockWithHeader(header).WithBody(*body)
} }
// WriteBlock serializes a block into the database, header and body separately. // WriteBlock serializes a block into the database, header and body separately.
@ -630,7 +630,11 @@ func ReadBadBlock(db ethdb.Reader, hash common.Hash) *types.Block {
} }
for _, bad := range badBlocks { for _, bad := range badBlocks {
if bad.Header.Hash() == hash { if bad.Header.Hash() == hash {
return types.NewBlockWithHeader(bad.Header).WithBody(bad.Body.Transactions, bad.Body.Uncles) block := types.NewBlockWithHeader(bad.Header)
if bad.Body != nil {
block = block.WithBody(*bad.Body)
}
return block
} }
} }
return nil return nil
@ -649,7 +653,11 @@ func ReadAllBadBlocks(db ethdb.Reader) []*types.Block {
} }
var blocks []*types.Block var blocks []*types.Block
for _, bad := range badBlocks { for _, bad := range badBlocks {
blocks = append(blocks, types.NewBlockWithHeader(bad.Header).WithBody(bad.Body.Transactions, bad.Body.Uncles)) block := types.NewBlockWithHeader(bad.Header)
if bad.Body != nil {
block = block.WithBody(*bad.Body)
}
blocks = append(blocks, block)
} }
return blocks return blocks
} }

View file

@ -97,7 +97,7 @@ func TestLookupStorage(t *testing.T) {
tx3 := types.NewTransaction(3, common.BytesToAddress([]byte{0x33}), big.NewInt(333), 3333, big.NewInt(33333), []byte{0x33, 0x33, 0x33}) tx3 := types.NewTransaction(3, common.BytesToAddress([]byte{0x33}), big.NewInt(333), 3333, big.NewInt(33333), []byte{0x33, 0x33, 0x33})
txs := []*types.Transaction{tx1, tx2, tx3} txs := []*types.Transaction{tx1, tx2, tx3}
block := types.NewBlock(&types.Header{Root: types.EmptyRootHash, Number: big.NewInt(314)}, txs, nil, nil, newHasher()) block := types.NewBlock(&types.Header{Root: types.EmptyRootHash, Number: big.NewInt(314)}, &types.Body{Transactions: txs}, nil, newHasher())
// Check that no transactions entries are in a pristine database // Check that no transactions entries are in a pristine database
for i, tx := range txs { for i, tx := range txs {

View file

@ -287,5 +287,5 @@ func GenerateBadBlock(t *testing.T, parent *types.Block, engine consensus.Engine
} }
header.Root = common.BytesToHash(hasher.Sum(nil)) header.Root = common.BytesToHash(hasher.Sum(nil))
// Assemble and return the final block for sealing // Assemble and return the final block for sealing
return types.NewBlock(header, txs, nil, receipts, trie.NewStackTrie(nil)) return types.NewBlock(header, &types.Body{Transactions: txs}, receipts, trie.NewStackTrie(nil))
} }

View file

@ -86,7 +86,7 @@ func (bc *testBlockChain) CurrentBlock() *types.Block {
return types.NewBlock(&types.Header{ return types.NewBlock(&types.Header{
Root: types.EmptyRootHash, Root: types.EmptyRootHash,
GasLimit: atomic.LoadUint64(&bc.gasLimit), GasLimit: atomic.LoadUint64(&bc.gasLimit),
}, nil, nil, nil, trie.NewStackTrie(nil)) }, nil, nil, trie.NewStackTrie(nil))
} }
func (bc *testBlockChain) GetBlock(hash common.Hash, number uint64) *types.Block { func (bc *testBlockChain) GetBlock(hash common.Hash, number uint64) *types.Block {

View file

@ -23,6 +23,7 @@ import (
"io" "io"
"math/big" "math/big"
"reflect" "reflect"
"slices"
"sort" "sort"
"sync/atomic" "sync/atomic"
"time" "time"
@ -226,17 +227,21 @@ type storageblock struct {
TD *big.Int TD *big.Int
} }
// NewBlock creates a new block. The input data is copied, // NewBlock creates a new block. The input data is copied, changes to header and to the
// changes to header and to the field values will not affect the // field values will not affect the block.
// block.
// //
// The values of TxHash, UncleHash, ReceiptHash and Bloom in header // The body elements and the receipts are used to recompute and overwrite the
// are ignored and set to values derived from the given txs, uncles // relevant portions of the header.
// and receipts. func NewBlock(header *Header, body *Body, receipts []*Receipt, hasher TrieHasher) *Block {
func NewBlock(header *Header, txs []*Transaction, uncles []*Header, receipts []*Receipt, hasher TrieHasher) *Block { if body == nil {
b := &Block{header: CopyHeader(header), td: new(big.Int)} body = &Body{}
}
var (
b = NewBlockWithHeader(header)
txs = body.Transactions
uncles = body.Uncles
)
// TODO: panic if len(txs) != len(receipts)
if len(txs) == 0 { if len(txs) == 0 {
b.header.TxHash = EmptyTxsHash b.header.TxHash = EmptyTxsHash
} else { } else {
@ -265,13 +270,6 @@ func NewBlock(header *Header, txs []*Transaction, uncles []*Header, receipts []*
return b return b
} }
// NewBlockWithHeader creates a block with the given header data. The
// header data is copied, changes to header and to the field values
// will not affect the block.
func NewBlockWithHeader(header *Header) *Block {
return &Block{header: CopyHeader(header)}
}
// CopyHeader creates a deep copy of a block header to prevent side effects from // CopyHeader creates a deep copy of a block header to prevent side effects from
// modifying a header variable. // modifying a header variable.
func CopyHeader(h *Header) *Header { func CopyHeader(h *Header) *Header {
@ -411,6 +409,13 @@ func CalcUncleHash(uncles []*Header) common.Hash {
return rlpHash(uncles) return rlpHash(uncles)
} }
// NewBlockWithHeader creates a block with the given header data. The
// header data is copied, changes to header and to the field values
// will not affect the block.
func NewBlockWithHeader(header *Header) *Block {
return &Block{header: CopyHeader(header)}
}
// WithSeal returns a new block with the data from b but the header replaced with // WithSeal returns a new block with the data from b but the header replaced with
// the sealed one. // the sealed one.
func (b *Block) WithSeal(header *Header) *Block { func (b *Block) WithSeal(header *Header) *Block {
@ -423,16 +428,16 @@ func (b *Block) WithSeal(header *Header) *Block {
} }
} }
// WithBody returns a new block with the given transaction and uncle contents. // WithBody returns a new block with the original header and a deep copy of the
func (b *Block) WithBody(transactions []*Transaction, uncles []*Header) *Block { // provided body.
func (b *Block) WithBody(body Body) *Block {
block := &Block{ block := &Block{
header: CopyHeader(b.header), header: b.header,
transactions: make([]*Transaction, len(transactions)), transactions: slices.Clone(body.Transactions),
uncles: make([]*Header, len(uncles)), uncles: make([]*Header, len(body.Uncles)),
} }
copy(block.transactions, transactions) for i := range body.Uncles {
for i := range uncles { block.uncles[i] = CopyHeader(body.Uncles[i])
block.uncles[i] = CopyHeader(uncles[i])
} }
return block return block
} }

View file

@ -210,5 +210,5 @@ func makeBenchBlock() *Block {
Extra: []byte("benchmark uncle"), Extra: []byte("benchmark uncle"),
} }
} }
return NewBlock(header, txs, uncles, receipts, newHasher()) return NewBlock(header, &Body{Transactions: txs, Uncles: uncles}, receipts, newHasher())
} }

View file

@ -325,7 +325,7 @@ func New(stack *node.Node, config *ethconfig.Config, XDCXServ *XDCx.XDCX, lendin
return block, false, err return block, false, err
} }
header.Validator = sighash header.Validator = sighash
return types.NewBlockWithHeader(header).WithBody(block.Transactions(), block.Uncles()), true, nil return types.NewBlockWithHeader(header).WithBody(*block.Body()), true, nil
} }
return block, false, nil return block, false, nil
} }

View file

@ -1526,7 +1526,7 @@ func (d *Downloader) importBlockResults(results []*fetchResult) error {
) )
blocks := make([]*types.Block, len(results)) blocks := make([]*types.Block, len(results))
for i, result := range results { for i, result := range results {
blocks[i] = types.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles) blocks[i] = types.NewBlockWithHeader(result.Header).WithBody(result.body())
} }
if index, err := d.blockchain.InsertChain(blocks); err != nil { if index, err := d.blockchain.InsertChain(blocks); err != nil {
if index < len(results) { if index < len(results) {
@ -1694,7 +1694,7 @@ func (d *Downloader) commitFastSyncData(results []*fetchResult, stateSync *state
blocks := make([]*types.Block, len(results)) blocks := make([]*types.Block, len(results))
receipts := make([]types.Receipts, len(results)) receipts := make([]types.Receipts, len(results))
for i, result := range results { for i, result := range results {
blocks[i] = types.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles) blocks[i] = types.NewBlockWithHeader(result.Header).WithBody(result.body())
receipts[i] = result.Receipts receipts[i] = result.Receipts
} }
if index, err := d.blockchain.InsertReceiptChain(blocks, receipts); err != nil { if index, err := d.blockchain.InsertReceiptChain(blocks, receipts); err != nil {
@ -1705,7 +1705,7 @@ func (d *Downloader) commitFastSyncData(results []*fetchResult, stateSync *state
} }
func (d *Downloader) commitPivotBlock(result *fetchResult) error { func (d *Downloader) commitPivotBlock(result *fetchResult) error {
block := types.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles) block := types.NewBlockWithHeader(result.Header).WithBody(result.body())
log.Debug("Committing fast sync pivot as new head", "number", block.Number(), "hash", block.Hash()) log.Debug("Committing fast sync pivot as new head", "number", block.Number(), "hash", block.Hash())
if _, err := d.blockchain.InsertReceiptChain([]*types.Block{block}, []types.Receipts{result.Receipts}); err != nil { if _, err := d.blockchain.InsertReceiptChain([]*types.Block{block}, []types.Receipts{result.Receipts}); err != nil {
return err return err

View file

@ -83,6 +83,14 @@ func newFetchResult(header *types.Header, fastSync bool) *fetchResult {
return item return item
} }
// body returns a representation of the fetch result as a types.Body object.
func (f *fetchResult) body() types.Body {
return types.Body{
Transactions: f.Transactions,
Uncles: f.Uncles,
}
}
// SetBodyDone flags the body as finished. // SetBodyDone flags the body as finished.
func (f *fetchResult) SetBodyDone() { func (f *fetchResult) SetBodyDone() {
if v := atomic.LoadInt32(&f.pending); (v & (1 << bodyType)) != 0 { if v := atomic.LoadInt32(&f.pending); (v & (1 << bodyType)) != 0 {

View file

@ -556,7 +556,7 @@ func (f *Fetcher) loop() {
// Mark the body matched, reassemble if still unknown // Mark the body matched, reassemble if still unknown
matched = true matched = true
if f.getBlock(hash) == nil { if f.getBlock(hash) == nil {
block := types.NewBlockWithHeader(announce.header).WithBody(task.transactions[i], task.uncles[i]) block := types.NewBlockWithHeader(announce.header).WithBody(types.Body{Transactions: task.transactions[i], Uncles: task.uncles[i]})
block.ReceivedAt = task.time block.ReceivedAt = task.time
blocks = append(blocks, block) blocks = append(blocks, block)
} else { } else {

View file

@ -40,7 +40,7 @@ var (
testKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") testKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
testAddress = crypto.PubkeyToAddress(testKey.PublicKey) testAddress = crypto.PubkeyToAddress(testKey.PublicKey)
genesis = core.GenesisBlockForTesting(testdb, testAddress, big.NewInt(1000000000)) genesis = core.GenesisBlockForTesting(testdb, testAddress, big.NewInt(1000000000))
unknownBlock = types.NewBlock(&types.Header{Root: types.EmptyRootHash, GasLimit: params.GenesisGasLimit}, nil, nil, nil, trie.NewStackTrie(nil)) unknownBlock = types.NewBlock(&types.Header{Root: types.EmptyRootHash, GasLimit: params.GenesisGasLimit}, nil, nil, trie.NewStackTrie(nil))
) )
// makeChain creates a chain of n blocks starting at and including parent. // makeChain creates a chain of n blocks starting at and including parent.

View file

@ -208,7 +208,11 @@ func (ec *Client) getBlock(ctx context.Context, method string, args ...interface
} }
txs[i] = tx.tx txs[i] = tx.tx
} }
return types.NewBlockWithHeader(head).WithBody(txs, uncles), nil return types.NewBlockWithHeader(head).WithBody(
types.Body{
Transactions: txs,
Uncles: uncles,
}), nil
} }
// HeaderByHash returns the block header with the given hash. // HeaderByHash returns the block header with the given hash.

View file

@ -534,8 +534,7 @@ func (w *worker) updateSnapshot() {
w.snapshotBlock = types.NewBlock( w.snapshotBlock = types.NewBlock(
w.current.header, w.current.header,
w.current.txs, &types.Body{Transactions: w.current.txs},
nil,
w.current.receipts, w.current.receipts,
trie.NewStackTrie(nil), trie.NewStackTrie(nil),
) )