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

parallel bloom calculation #445

Merged
merged 27 commits into from
Oct 15, 2021
Merged
Show file tree
Hide file tree
Changes from 26 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
9281410
parallel bloom calculation
steventranjs Oct 9, 2021
c4bc9de
indent
steventranjs Oct 9, 2021
3ced244
add condition if bloomJobs not nil
steventranjs Oct 9, 2021
6615ccf
add handler for worker
steventranjs Oct 9, 2021
faf3de5
fix format
steventranjs Oct 9, 2021
67f5e0a
bloomWorker should exit when all txs have been processed
steventranjs Oct 9, 2021
58bff6a
rename BloomPair => BloomHash
steventranjs Oct 9, 2021
d829350
merge with develop
steventranjs Oct 11, 2021
f6501f7
add size to map
steventranjs Oct 11, 2021
9b5ebc4
rename & unique variable
steventranjs Oct 11, 2021
234f49f
bloomJobs => bloomProcessors
steventranjs Oct 11, 2021
1b7348c
fix
steventranjs Oct 11, 2021
6be63ca
only assign bloom if empty
steventranjs Oct 11, 2021
4648bd7
abstraction method for processing receipt bloom
steventranjs Oct 13, 2021
7ee2d64
remove duplicate receipt_processor
steventranjs Oct 13, 2021
8bdc9a5
rename Processor
steventranjs Oct 13, 2021
a5567c4
fix ReceiptProcessor
steventranjs Oct 13, 2021
f692fe9
fix ReceiptBloomGenertor typo
steventranjs Oct 15, 2021
7d629e1
reduce worker to 1
steventranjs Oct 15, 2021
5a43a3f
remove empty wg
steventranjs Oct 15, 2021
4ac37c3
add defence code to check if channel is closed
steventranjs Oct 15, 2021
9b080d5
remove nil
steventranjs Oct 15, 2021
a3236ab
format fix
steventranjs Oct 15, 2021
790ea7d
remove thread pool
steventranjs Oct 15, 2021
105e007
use max 100 worker capacity
steventranjs Oct 15, 2021
f61d1ed
reduce worker size
steventranjs Oct 15, 2021
0ae31c9
refactor startWorker
steventranjs Oct 15, 2021
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/chain_makers.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ func (b *BlockGen) AddTxWithChain(bc *BlockChain, tx *types.Transaction) {
b.SetCoinbase(common.Address{})
}
b.statedb.Prepare(tx.Hash(), common.Hash{}, len(b.txs))
receipt, err := ApplyTransaction(b.config, bc, &b.header.Coinbase, b.gasPool, b.statedb, b.header, tx, &b.header.GasUsed, vm.Config{})
receipt, err := ApplyTransaction(b.config, bc, &b.header.Coinbase, b.gasPool, b.statedb, b.header, tx, &b.header.GasUsed, vm.Config{}, NewReceiptBloomGenerator())
if err != nil {
panic(err)
}
Expand Down
68 changes: 68 additions & 0 deletions core/receipt_processor.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package core

import (
"bytes"
"sync"

"github.com/ethereum/go-ethereum/core/types"
)

type ReceiptProcessor interface {
Apply(receipt *types.Receipt)
}

var (
_ ReceiptProcessor = (*ReceiptBloomGenerator)(nil)
_ ReceiptProcessor = (*AsyncReceiptBloomGenerator)(nil)
)

func NewReceiptBloomGenerator() *ReceiptBloomGenerator {
return &ReceiptBloomGenerator{}
}

type ReceiptBloomGenerator struct {
}

func (p *ReceiptBloomGenerator) Apply(receipt *types.Receipt) {
receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
}

func NewAsyncReceiptBloomGenerator(txNums int) *AsyncReceiptBloomGenerator {
generator := &AsyncReceiptBloomGenerator{
receipts: make(chan *types.Receipt, txNums),
}
generator.startWorker(1)
return generator
}

type AsyncReceiptBloomGenerator struct {
receipts chan *types.Receipt
wg sync.WaitGroup
isClosed bool
}

func (p *AsyncReceiptBloomGenerator) startWorker(workerSize int) {
p.wg.Add(workerSize)
for i := 0; i < workerSize; i++ {
go func() {
defer p.wg.Done()
for receipt := range p.receipts {
if receipt != nil && bytes.Equal(receipt.Bloom[:], types.EmptyBloom[:]) {
receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
}
}
}()
}
}

func (p *AsyncReceiptBloomGenerator) Apply(receipt *types.Receipt) {
if !p.isClosed {
p.receipts <- receipt
}
}

func (p *AsyncReceiptBloomGenerator) Close() {
close(p.receipts)
p.isClosed = true
p.wg.Wait()
}
20 changes: 14 additions & 6 deletions core/state_processor.go
Original file line number Diff line number Diff line change
Expand Up @@ -390,9 +390,14 @@ func (p *StateProcessor) Process(block *types.Block, statedb *state.StateDB, cfg
blockContext := NewEVMBlockContext(header, p.bc, nil)
vmenv := vm.NewEVM(blockContext, vm.TxContext{}, statedb, p.config, cfg)

txNum := len(block.Transactions())
// Iterate over and process the individual transactions
posa, isPoSA := p.engine.(consensus.PoSA)
commonTxs := make([]*types.Transaction, 0, len(block.Transactions()))
commonTxs := make([]*types.Transaction, 0, txNum)

// initilise bloom processors
bloomProcessors := NewAsyncReceiptBloomGenerator(txNum)

// usually do have two tx, one for validator set contract, another for system reward contract.
systemTxs := make([]*types.Transaction, 0, 2)
for i, tx := range block.Transactions() {
Expand All @@ -410,14 +415,15 @@ func (p *StateProcessor) Process(block *types.Block, statedb *state.StateDB, cfg
return statedb, nil, nil, 0, err
}
statedb.Prepare(tx.Hash(), block.Hash(), i)
receipt, err := applyTransaction(msg, p.config, p.bc, nil, gp, statedb, header, tx, usedGas, vmenv)
receipt, err := applyTransaction(msg, p.config, p.bc, nil, gp, statedb, header, tx, usedGas, vmenv, bloomProcessors)
if err != nil {
return statedb, nil, nil, 0, fmt.Errorf("could not apply tx %d [%v]: %w", i, tx.Hash().Hex(), err)
}

commonTxs = append(commonTxs, tx)
receipts = append(receipts, receipt)
}
bloomProcessors.Close()

// Finalize the block, applying any consensus engine specific extras (e.g. block rewards)
err := p.engine.Finalize(p.bc, header, statedb, &commonTxs, block.Uncles(), &receipts, &systemTxs, usedGas)
Expand All @@ -431,7 +437,7 @@ func (p *StateProcessor) Process(block *types.Block, statedb *state.StateDB, cfg
return statedb, receipts, allLogs, *usedGas, nil
}

func applyTransaction(msg types.Message, config *params.ChainConfig, bc ChainContext, author *common.Address, gp *GasPool, statedb *state.StateDB, header *types.Header, tx *types.Transaction, usedGas *uint64, evm *vm.EVM) (*types.Receipt, error) {
func applyTransaction(msg types.Message, config *params.ChainConfig, bc ChainContext, author *common.Address, gp *GasPool, statedb *state.StateDB, header *types.Header, tx *types.Transaction, usedGas *uint64, evm *vm.EVM, receiptProcessors ...ReceiptProcessor) (*types.Receipt, error) {
// Create a new context to be used in the EVM environment.
txContext := NewEVMTxContext(msg)
evm.Reset(txContext, statedb)
Expand Down Expand Up @@ -469,18 +475,20 @@ func applyTransaction(msg types.Message, config *params.ChainConfig, bc ChainCon

// Set the receipt logs and create the bloom filter.
receipt.Logs = statedb.GetLogs(tx.Hash())
receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
receipt.BlockHash = statedb.BlockHash()
receipt.BlockNumber = header.Number
receipt.TransactionIndex = uint(statedb.TxIndex())
for _, receiptProcessor := range receiptProcessors {
receiptProcessor.Apply(receipt)
}
return receipt, err
}

// ApplyTransaction attempts to apply a transaction to the given state database
// and uses the input parameters for its environment. It returns the receipt
// for the transaction, gas used and an error if the transaction failed,
// indicating the block was invalid.
func ApplyTransaction(config *params.ChainConfig, bc ChainContext, author *common.Address, gp *GasPool, statedb *state.StateDB, header *types.Header, tx *types.Transaction, usedGas *uint64, cfg vm.Config) (*types.Receipt, error) {
func ApplyTransaction(config *params.ChainConfig, bc ChainContext, author *common.Address, gp *GasPool, statedb *state.StateDB, header *types.Header, tx *types.Transaction, usedGas *uint64, cfg vm.Config, receiptProcessors ...ReceiptProcessor) (*types.Receipt, error) {
msg, err := tx.AsMessage(types.MakeSigner(config, header.Number))
if err != nil {
return nil, err
Expand All @@ -493,5 +501,5 @@ func ApplyTransaction(config *params.ChainConfig, bc ChainContext, author *commo
vm.EVMInterpreterPool.Put(ite)
vm.EvmPool.Put(vmenv)
}()
return applyTransaction(msg, config, bc, author, gp, statedb, header, tx, usedGas, vmenv)
return applyTransaction(msg, config, bc, author, gp, statedb, header, tx, usedGas, vmenv, receiptProcessors...)
}
2 changes: 2 additions & 0 deletions core/types/bloom9.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ const (
BloomBitLength = 8 * BloomByteLength
)

var EmptyBloom = Bloom{}

// Bloom represents a 2048 bit bloom filter.
type Bloom [BloomByteLength]byte

Expand Down
4 changes: 4 additions & 0 deletions core/types/transaction.go
Original file line number Diff line number Diff line change
Expand Up @@ -479,6 +479,10 @@ func (t *TransactionsByPriceAndNonce) Pop() {
heap.Pop(&t.heads)
}

func (t *TransactionsByPriceAndNonce) CurrentSize() int {
return len(t.heads)
}

// Message is a fully derived transaction and implements core.Message
//
// NOTE: In a future PR this will be removed.
Expand Down
2 changes: 1 addition & 1 deletion eth/catalyst/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ type blockExecutionEnv struct {

func (env *blockExecutionEnv) commitTransaction(tx *types.Transaction, coinbase common.Address) error {
vmconfig := *env.chain.GetVMConfig()
receipt, err := core.ApplyTransaction(env.chain.Config(), env.chain, &coinbase, env.gasPool, env.state, env.header, tx, &env.header.GasUsed, vmconfig)
receipt, err := core.ApplyTransaction(env.chain.Config(), env.chain, &coinbase, env.gasPool, env.state, env.header, tx, &env.header.GasUsed, vmconfig, core.NewReceiptBloomGenerator())
if err != nil {
return err
}
Expand Down
15 changes: 12 additions & 3 deletions miner/worker.go
Original file line number Diff line number Diff line change
Expand Up @@ -736,10 +736,10 @@ func (w *worker) updateSnapshot() {
w.snapshotState = w.current.state.Copy()
}

func (w *worker) commitTransaction(tx *types.Transaction, coinbase common.Address) ([]*types.Log, error) {
func (w *worker) commitTransaction(tx *types.Transaction, coinbase common.Address, receiptProcessors ...core.ReceiptProcessor) ([]*types.Log, error) {
snap := w.current.state.Snapshot()

receipt, err := core.ApplyTransaction(w.chainConfig, w.chain, &coinbase, w.current.gasPool, w.current.state, w.current.header, tx, &w.current.header.GasUsed, *w.chain.GetVMConfig())
receipt, err := core.ApplyTransaction(w.chainConfig, w.chain, &coinbase, w.current.gasPool, w.current.state, w.current.header, tx, &w.current.header.GasUsed, *w.chain.GetVMConfig(), receiptProcessors...)
if err != nil {
w.current.state.RevertToSnapshot(snap)
return nil, err
Expand Down Expand Up @@ -769,6 +769,14 @@ func (w *worker) commitTransactions(txs *types.TransactionsByPriceAndNonce, coin
log.Debug("Time left for mining work", "left", (*delay - w.config.DelayLeftOver).String(), "leftover", w.config.DelayLeftOver)
defer stopTimer.Stop()
}

// initilise bloom processors
processorCapacity := 100
if txs.CurrentSize() < processorCapacity {
processorCapacity = txs.CurrentSize()
}
bloomProcessors := core.NewAsyncReceiptBloomGenerator(processorCapacity)

LOOP:
for {
// In the following three cases, we will interrupt the execution of the transaction.
Expand Down Expand Up @@ -824,7 +832,7 @@ LOOP:
// Start executing the transaction
w.current.state.Prepare(tx.Hash(), common.Hash{}, w.current.tcount)

logs, err := w.commitTransaction(tx, coinbase)
logs, err := w.commitTransaction(tx, coinbase, bloomProcessors)
switch {
case errors.Is(err, core.ErrGasLimitReached):
// Pop the current out-of-gas transaction without shifting in the next from the account
Expand Down Expand Up @@ -859,6 +867,7 @@ LOOP:
txs.Shift()
}
}
bloomProcessors.Close()

if !w.isRunning() && len(coalescedLogs) > 0 {
// We don't push the pendingLogsEvent while we are mining. The reason is that
Expand Down