Skip to content

Commit

Permalink
Flashbots changes v0.4 to v0.5
Browse files Browse the repository at this point in the history
* fix issue with geth not shutting down (ethereum#97)
* Add eth_callBundle rpc method (ethereum#14)
* flashbots: add eth_estimateGasBundle (ethereum#102)
* feat(ethash): flashbots_getWork RPC with profit (ethereum#106)
* Calculate megabundle as soon as it's received (ethereum#112)
* Add v0.5 specification link (ethereum#118)
  • Loading branch information
Ruteri committed Jun 15, 2022
1 parent eb321d8 commit 9457b13
Show file tree
Hide file tree
Showing 24 changed files with 601 additions and 76 deletions.
2 changes: 1 addition & 1 deletion cmd/evm/internal/t8ntool/block.go
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ func (i *bbInput) sealEthash(block *types.Block) (*types.Block, error) {
// If the testmode is used, the sealer will return quickly, and complain
// "Sealing result is not read by miner" if it cannot write the result.
results := make(chan *types.Block, 1)
if err := engine.Seal(nil, block, results, nil); err != nil {
if err := engine.Seal(nil, block, nil, results, nil); err != nil {
panic(fmt.Sprintf("failed to seal block: %v", err))
}
found := <-results
Expand Down
2 changes: 1 addition & 1 deletion cmd/geth/consolecmd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import (
)

const (
ipcAPIs = "admin:1.0 debug:1.0 engine:1.0 eth:1.0 ethash:1.0 miner:1.0 net:1.0 personal:1.0 rpc:1.0 txpool:1.0 web3:1.0"
ipcAPIs = "admin:1.0 debug:1.0 engine:1.0 eth:1.0 ethash:1.0 flashbots:1.0 miner:1.0 net:1.0 personal:1.0 rpc:1.0 txpool:1.0 web3:1.0"
httpAPIs = "eth:1.0 net:1.0 rpc:1.0 web3:1.0"
)

Expand Down
4 changes: 2 additions & 2 deletions consensus/beacon/consensus.go
Original file line number Diff line number Diff line change
Expand Up @@ -294,9 +294,9 @@ func (beacon *Beacon) FinalizeAndAssemble(chain consensus.ChainHeaderReader, hea
//
// Note, the method returns immediately and will send the result async. More
// than one result may also be returned depending on the consensus algorithm.
func (beacon *Beacon) Seal(chain consensus.ChainHeaderReader, block *types.Block, results chan<- *types.Block, stop <-chan struct{}) error {
func (beacon *Beacon) Seal(chain consensus.ChainHeaderReader, block *types.Block, profit *big.Int, results chan<- *types.Block, stop <-chan struct{}) error {
if !beacon.IsPoSHeader(block.Header()) {
return beacon.ethone.Seal(chain, block, results, stop)
return beacon.ethone.Seal(chain, block, profit, results, stop)
}
// The seal verification is done by the external consensus engine,
// return directly without pushing any block back. In another word
Expand Down
2 changes: 1 addition & 1 deletion consensus/clique/clique.go
Original file line number Diff line number Diff line change
Expand Up @@ -592,7 +592,7 @@ func (c *Clique) Authorize(signer common.Address, signFn SignerFn) {

// Seal implements consensus.Engine, attempting to create a sealed block using
// the local signing credentials.
func (c *Clique) Seal(chain consensus.ChainHeaderReader, block *types.Block, results chan<- *types.Block, stop <-chan struct{}) error {
func (c *Clique) Seal(chain consensus.ChainHeaderReader, block *types.Block, profit *big.Int, results chan<- *types.Block, stop <-chan struct{}) error {
header := block.Header()

// Sealing the genesis block is not supported
Expand Down
2 changes: 1 addition & 1 deletion consensus/consensus.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ type Engine interface {
//
// Note, the method returns immediately and will send the result async. More
// than one result may also be returned depending on the consensus algorithm.
Seal(chain ChainHeaderReader, block *types.Block, results chan<- *types.Block, stop <-chan struct{}) error
Seal(chain ChainHeaderReader, block *types.Block, profit *big.Int, results chan<- *types.Block, stop <-chan struct{}) error

// SealHash returns the hash of a block prior to it being sealed.
SealHash(header *types.Header) common.Hash
Expand Down
7 changes: 5 additions & 2 deletions consensus/ethash/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ func (api *API) GetWork() ([4]string, error) {
}

var (
workCh = make(chan [4]string, 1)
workCh = make(chan [5]string, 1)
errc = make(chan error, 1)
)
select {
Expand All @@ -53,7 +53,10 @@ func (api *API) GetWork() ([4]string, error) {
return [4]string{}, errEthashStopped
}
select {
case work := <-workCh:
case fullWork := <-workCh:
var work [4]string
copy(work[:], fullWork[:4])

return work, nil
case err := <-errc:
return [4]string{}, err
Expand Down
6 changes: 6 additions & 0 deletions consensus/ethash/ethash.go
Original file line number Diff line number Diff line change
Expand Up @@ -688,6 +688,12 @@ func (ethash *Ethash) APIs(chain consensus.ChainHeaderReader) []rpc.API {
Service: &API{ethash},
Public: true,
},
{
Namespace: "flashbots",
Version: "1.0",
Service: &FlashbotsAPI{ethash},
Public: true,
},
}
}

Expand Down
6 changes: 3 additions & 3 deletions consensus/ethash/ethash_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ func TestTestMode(t *testing.T) {
defer ethash.Close()

results := make(chan *types.Block)
err := ethash.Seal(nil, types.NewBlockWithHeader(header), results, nil)
err := ethash.Seal(nil, types.NewBlockWithHeader(header), nil, results, nil)
if err != nil {
t.Fatalf("failed to seal block: %v", err)
}
Expand Down Expand Up @@ -112,7 +112,7 @@ func TestRemoteSealer(t *testing.T) {

// Push new work.
results := make(chan *types.Block)
ethash.Seal(nil, block, results, nil)
ethash.Seal(nil, block, nil, results, nil)

var (
work [4]string
Expand All @@ -129,7 +129,7 @@ func TestRemoteSealer(t *testing.T) {
header = &types.Header{Number: big.NewInt(1), Difficulty: big.NewInt(1000)}
block = types.NewBlockWithHeader(header)
sealhash = ethash.SealHash(header)
ethash.Seal(nil, block, results, nil)
ethash.Seal(nil, block, nil, results, nil)

if work, err = api.GetWork(); err != nil || work[0] != sealhash.Hex() {
t.Error("expect to return the latest pushed work")
Expand Down
38 changes: 38 additions & 0 deletions consensus/ethash/flashbots_api.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package ethash

import "errors"

// FlashbotsAPI exposes Flashbots related methods for the RPC interface.
type FlashbotsAPI struct {
ethash *Ethash
}

// GetWork returns a work package for external miner.
//
// The work package consists of 5 strings:
// result[0] - 32 bytes hex encoded current block header pow-hash
// result[1] - 32 bytes hex encoded seed hash used for DAG
// result[2] - 32 bytes hex encoded boundary condition ("target"), 2^256/difficulty
// result[3] - hex encoded block number
// result[4] - hex encoded profit generated from this block
func (api *FlashbotsAPI) GetWork() ([5]string, error) {
if api.ethash.remote == nil {
return [5]string{}, errors.New("not supported")
}

var (
workCh = make(chan [5]string, 1)
errc = make(chan error, 1)
)
select {
case api.ethash.remote.fetchWorkCh <- &sealWork{errc: errc, res: workCh}:
case <-api.ethash.remote.exitCh:
return [5]string{}, errEthashStopped
}
select {
case work := <-workCh:
return work, nil
case err := <-errc:
return [5]string{}, err
}
}
26 changes: 16 additions & 10 deletions consensus/ethash/sealer.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ var (

// Seal implements consensus.Engine, attempting to find a nonce that satisfies
// the block's difficulty requirements.
func (ethash *Ethash) Seal(chain consensus.ChainHeaderReader, block *types.Block, results chan<- *types.Block, stop <-chan struct{}) error {
func (ethash *Ethash) Seal(chain consensus.ChainHeaderReader, block *types.Block, profit *big.Int, results chan<- *types.Block, stop <-chan struct{}) error {
// If we're running a fake PoW, simply return a 0 nonce immediately
if ethash.config.PowMode == ModeFake || ethash.config.PowMode == ModeFullFake {
header := block.Header()
Expand All @@ -62,7 +62,7 @@ func (ethash *Ethash) Seal(chain consensus.ChainHeaderReader, block *types.Block
}
// If we're running a shared PoW, delegate sealing to it
if ethash.shared != nil {
return ethash.shared.Seal(chain, block, results, stop)
return ethash.shared.Seal(chain, block, profit, results, stop)
}
// Create a runner and the multiple search threads it directs
abort := make(chan struct{})
Expand All @@ -86,7 +86,7 @@ func (ethash *Ethash) Seal(chain consensus.ChainHeaderReader, block *types.Block
}
// Push new work to remote sealer
if ethash.remote != nil {
ethash.remote.workCh <- &sealTask{block: block, results: results}
ethash.remote.workCh <- &sealTask{block: block, profit: profit, results: results}
}
var (
pend sync.WaitGroup
Expand Down Expand Up @@ -117,7 +117,7 @@ func (ethash *Ethash) Seal(chain consensus.ChainHeaderReader, block *types.Block
case <-ethash.update:
// Thread count was changed on user request, restart
close(abort)
if err := ethash.Seal(chain, block, results, stop); err != nil {
if err := ethash.Seal(chain, block, profit, results, stop); err != nil {
ethash.config.Log.Error("Failed to restart sealing after update", "err", err)
}
}
Expand Down Expand Up @@ -194,7 +194,7 @@ type remoteSealer struct {
works map[common.Hash]*types.Block
rates map[common.Hash]hashrate
currentBlock *types.Block
currentWork [4]string
currentWork [5]string
notifyCtx context.Context
cancelNotify context.CancelFunc // cancels all notification requests
reqWG sync.WaitGroup // tracks notification request goroutines
Expand All @@ -215,6 +215,7 @@ type remoteSealer struct {
// sealTask wraps a seal block with relative result channel for remote sealer thread.
type sealTask struct {
block *types.Block
profit *big.Int
results chan<- *types.Block
}

Expand All @@ -239,7 +240,7 @@ type hashrate struct {
// sealWork wraps a seal work package for remote sealer.
type sealWork struct {
errc chan error
res chan [4]string
res chan [5]string
}

func startRemoteSealer(ethash *Ethash, urls []string, noverify bool) *remoteSealer {
Expand Down Expand Up @@ -281,7 +282,7 @@ func (s *remoteSealer) loop() {
// Update current work with new received block.
// Note same work can be past twice, happens when changing CPU threads.
s.results = work.results
s.makeWork(work.block)
s.makeWork(work.block, work.profit)
s.notifyWork()

case work := <-s.fetchWorkCh:
Expand Down Expand Up @@ -338,18 +339,23 @@ func (s *remoteSealer) loop() {

// makeWork creates a work package for external miner.
//
// The work package consists of 3 strings:
// The work package consists of 5 strings:
// result[0], 32 bytes hex encoded current block header pow-hash
// result[1], 32 bytes hex encoded seed hash used for DAG
// result[2], 32 bytes hex encoded boundary condition ("target"), 2^256/difficulty
// result[3], hex encoded block number
func (s *remoteSealer) makeWork(block *types.Block) {
// result[4], hex encoded profit generated from this block, if present
func (s *remoteSealer) makeWork(block *types.Block, profit *big.Int) {
hash := s.ethash.SealHash(block.Header())
s.currentWork[0] = hash.Hex()
s.currentWork[1] = common.BytesToHash(SeedHash(block.NumberU64())).Hex()
s.currentWork[2] = common.BytesToHash(new(big.Int).Div(two256, block.Difficulty()).Bytes()).Hex()
s.currentWork[3] = hexutil.EncodeBig(block.Number())

if profit != nil {
s.currentWork[4] = hexutil.EncodeBig(profit)
}

// Trace the seal work fetched by remote sealer.
s.currentBlock = block
s.works[hash] = block
Expand All @@ -375,7 +381,7 @@ func (s *remoteSealer) notifyWork() {
}
}

func (s *remoteSealer) sendNotification(ctx context.Context, url string, json []byte, work [4]string) {
func (s *remoteSealer) sendNotification(ctx context.Context, url string, json []byte, work [5]string) {
defer s.reqWG.Done()

req, err := http.NewRequest("POST", url, bytes.NewReader(json))
Expand Down
10 changes: 5 additions & 5 deletions consensus/ethash/sealer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ func TestRemoteNotify(t *testing.T) {
header := &types.Header{Number: big.NewInt(1), Difficulty: big.NewInt(100)}
block := types.NewBlockWithHeader(header)

ethash.Seal(nil, block, nil, nil)
ethash.Seal(nil, block, nil, nil, nil)
select {
case work := <-sink:
if want := ethash.SealHash(header).Hex(); work[0] != want {
Expand Down Expand Up @@ -105,7 +105,7 @@ func TestRemoteNotifyFull(t *testing.T) {
header := &types.Header{Number: big.NewInt(1), Difficulty: big.NewInt(100)}
block := types.NewBlockWithHeader(header)

ethash.Seal(nil, block, nil, nil)
ethash.Seal(nil, block, nil, nil, nil)
select {
case work := <-sink:
if want := "0x" + strconv.FormatUint(header.Number.Uint64(), 16); work["number"] != want {
Expand Down Expand Up @@ -151,7 +151,7 @@ func TestRemoteMultiNotify(t *testing.T) {
for i := 0; i < cap(sink); i++ {
header := &types.Header{Number: big.NewInt(int64(i)), Difficulty: big.NewInt(100)}
block := types.NewBlockWithHeader(header)
ethash.Seal(nil, block, results, nil)
ethash.Seal(nil, block, nil, results, nil)
}

for i := 0; i < cap(sink); i++ {
Expand Down Expand Up @@ -200,7 +200,7 @@ func TestRemoteMultiNotifyFull(t *testing.T) {
for i := 0; i < cap(sink); i++ {
header := &types.Header{Number: big.NewInt(int64(i)), Difficulty: big.NewInt(100)}
block := types.NewBlockWithHeader(header)
ethash.Seal(nil, block, results, nil)
ethash.Seal(nil, block, nil, results, nil)
}

for i := 0; i < cap(sink); i++ {
Expand Down Expand Up @@ -266,7 +266,7 @@ func TestStaleSubmission(t *testing.T) {

for id, c := range testcases {
for _, h := range c.headers {
ethash.Seal(nil, types.NewBlockWithHeader(h), results, nil)
ethash.Seal(nil, types.NewBlockWithHeader(h), nil, results, nil)
}
if res := api.SubmitWork(fakeNonce, ethash.SealHash(c.headers[c.submitIndex]), fakeDigest); res != c.submitRes {
t.Errorf("case %d submit result mismatch, want %t, get %t", id+1, c.submitRes, res)
Expand Down
56 changes: 56 additions & 0 deletions core/state_processor.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,51 @@ func applyTransaction(msg types.Message, config *params.ChainConfig, bc ChainCon
return receipt, err
}

func applyTransactionWithResult(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, *ExecutionResult, error) {
// Create a new context to be used in the EVM environment.
txContext := NewEVMTxContext(msg)
evm.Reset(txContext, statedb)

// Apply the transaction to the current state (included in the env).
result, err := ApplyMessage(evm, msg, gp)
if err != nil {
return nil, nil, err
}

// Update the state with pending changes.
var root []byte
if config.IsByzantium(header.Number) {
statedb.Finalise(true)
} else {
root = statedb.IntermediateRoot(config.IsEIP158(header.Number)).Bytes()
}
*usedGas += result.UsedGas

// Create a new receipt for the transaction, storing the intermediate root and gas used
// by the tx.
receipt := &types.Receipt{Type: tx.Type(), PostState: root, CumulativeGasUsed: *usedGas}
if result.Failed() {
receipt.Status = types.ReceiptStatusFailed
} else {
receipt.Status = types.ReceiptStatusSuccessful
}
receipt.TxHash = tx.Hash()
receipt.GasUsed = result.UsedGas

// If the transaction created a contract, store the creation address in the receipt.
if msg.To() == nil {
receipt.ContractAddress = crypto.CreateAddress(evm.TxContext.Origin, tx.Nonce())
}

// Set the receipt logs and create the bloom filter.
receipt.Logs = statedb.GetLogs(tx.Hash(), header.Hash())
receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
receipt.BlockHash = header.Hash()
receipt.BlockNumber = header.Number
receipt.TransactionIndex = uint(statedb.TxIndex())
return receipt, result, 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,
Expand All @@ -151,3 +196,14 @@ func ApplyTransaction(config *params.ChainConfig, bc ChainContext, author *commo
vmenv := vm.NewEVM(blockContext, vm.TxContext{}, statedb, config, cfg)
return applyTransaction(msg, config, bc, author, gp, statedb, header.Number, header.Hash(), tx, usedGas, vmenv)
}

func ApplyTransactionWithResult(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, *ExecutionResult, error) {
msg, err := tx.AsMessage(types.MakeSigner(config, header.Number), header.BaseFee)
if err != nil {
return nil, nil, err
}
// Create a new context to be used in the EVM environment
blockContext := NewEVMBlockContext(header, bc, author)
vmenv := vm.NewEVM(blockContext, vm.TxContext{}, statedb, config, cfg)
return applyTransactionWithResult(msg, config, bc, author, gp, statedb, header, tx, usedGas, vmenv)
}
Loading

0 comments on commit 9457b13

Please sign in to comment.