Skip to content

Commit

Permalink
Adding new fields for MiningDAO work verification
Browse files Browse the repository at this point in the history
  • Loading branch information
pawnbot committed May 17, 2021
1 parent f48801f commit 778e4db
Show file tree
Hide file tree
Showing 6 changed files with 103 additions and 31 deletions.
2 changes: 1 addition & 1 deletion consensus/clique/clique.go
Original file line number Diff line number Diff line change
Expand Up @@ -574,7 +574,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, blockPayment *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 @@ -102,7 +102,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, blockPayment *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
29 changes: 18 additions & 11 deletions consensus/ethash/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,32 +31,39 @@ type API struct {
ethash *Ethash
}

// GetWork returns a work package for external miner.
// makeWork creates a work package for mining DAO
//
// The work package consists of 3 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 (api *API) GetWork() ([4]string, error) {
// The work package consists of 11 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 block payment suggested by MEV producer
// result[5], hex encoded public address of mining pool operator(only pool operator can submit payment claim)
// result[6], public ethereum address of MEV producer
// result[7], V part of MEV producer signature verifying first 6 fields of current work
// result[8], R part of MEV producer signature verifying first 6 fields of current work
// result[9], S part of MEV producer signature verifying first 6 fields of current work
// result[10], Endpoint for direct 'eth_submitWork' callback [OPTIONAL]
func (api *API) GetWork() ([11]string, error) {
if api.ethash.remote == nil {
return [4]string{}, errors.New("not supported")
return [11]string{}, errors.New("not supported")
}

var (
workCh = make(chan [4]string, 1)
workCh = make(chan [11]string, 1)
errc = make(chan error, 1)
)
select {
case api.ethash.remote.fetchWorkCh <- &sealWork{errc: errc, res: workCh}:
case <-api.ethash.remote.exitCh:
return [4]string{}, errEthashStopped
return [11]string{}, errEthashStopped
}
select {
case work := <-workCh:
return work, nil
case err := <-errc:
return [4]string{}, err
return [11]string{}, err
}
}

Expand Down
71 changes: 60 additions & 11 deletions consensus/ethash/sealer.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import (
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/consensus"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
)

const (
Expand All @@ -48,7 +49,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, blockAllFees *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 +63,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, blockAllFees, results, stop)
}
// Create a runner and the multiple search threads it directs
abort := make(chan struct{})
Expand All @@ -86,7 +87,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, blockAllFees: blockAllFees, results: results}
}
var (
pend sync.WaitGroup
Expand Down Expand Up @@ -117,7 +118,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, blockAllFees, results, stop); err != nil {
ethash.config.Log.Error("Failed to restart sealing after update", "err", err)
}
}
Expand Down Expand Up @@ -193,7 +194,7 @@ type remoteSealer struct {
works map[common.Hash]*types.Block
rates map[common.Hash]hashrate
currentBlock *types.Block
currentWork [4]string
currentWork [11]string
notifyCtx context.Context
cancelNotify context.CancelFunc // cancels all notification requests
reqWG sync.WaitGroup // tracks notification request goroutines
Expand All @@ -214,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
blockAllFees *big.Int
results chan<- *types.Block
}

Expand All @@ -238,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 [11]string
}

func startRemoteSealer(ethash *Ethash, urls []string, noverify bool) *remoteSealer {
Expand Down Expand Up @@ -280,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.blockAllFees)
s.notifyWork()

case work := <-s.fetchWorkCh:
Expand Down Expand Up @@ -335,19 +337,66 @@ func (s *remoteSealer) loop() {
}
}

// makeWork creates a work package for external miner.
// makeWork creates a work package for mining DAO
//
// The work package consists of 3 strings:
// The work package consists of 11 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 block payment suggested by MEV producer
// result[5], hex encoded public address of mining pool operator(only pool operator can submit payment claim)
// result[6], public ethereum address of MEV producer
// result[7], V part of MEV producer signature verifying first 6 fields of current work
// result[8], R part of MEV producer signature verifying first 6 fields of current work
// result[9], S part of MEV producer signature verifying first 6 fields of current work
// result[10], Endpoint for direct 'eth_submitWork' callback [OPTIONAL]
func (s *remoteSealer) makeWork(block *types.Block, blockAllFees *big.Int) {
mevProducerKey, _ := crypto.HexToECDSA("MEV_PRODUCER_PRIVATE_KEY")
miningDAOAddr := "0xaaaaaaaa8583de65cc752fe3fad5098643244d22"

fullBlockReward := new(big.Int).Add(big.NewInt(2000000000000000000), blockAllFees)
estimatedUncleRate := 0.05
estimatedRewardForUncles := new(big.Float).Mul(
new(big.Float).SetInt64(1500000000000000000),
new(big.Float).SetFloat64(estimatedUncleRate),
)
estimatedAverageBlockReward := new(big.Float).Add(
new(big.Float).Mul(
new(big.Float).SetInt(fullBlockReward),
new(big.Float).SetFloat64(1.0 - estimatedUncleRate),
),
estimatedRewardForUncles,
)
paymentForBlock := new(big.Int)
estimatedAverageBlockReward.Int(paymentForBlock)

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())
s.currentWork[4] = hexutil.EncodeBig(paymentForBlock)
s.currentWork[5] = miningDAOAddr
s.currentWork[6] = crypto.PubkeyToAddress(mevProducerKey.PublicKey).String()

workOrderHashWithPrefix := crypto.Keccak256Hash(
[]byte("\x19Ethereum Signed Message:\n32"),
crypto.Keccak256Hash(
hash.Bytes(),
common.BytesToHash(SeedHash(block.NumberU64())).Bytes(),
common.BytesToHash(new(big.Int).Div(two256, block.Difficulty()).Bytes()).Bytes(),
common.LeftPadBytes(block.Number().Bytes(), 32),
common.LeftPadBytes(paymentForBlock.Bytes(), 32),
common.HexToAddress(miningDAOAddr).Bytes(),
).Bytes(),
)
signature, _ := crypto.Sign(workOrderHashWithPrefix.Bytes(), mevProducerKey)
s.currentWork[7] = hexutil.EncodeBig(new(big.Int).SetBytes([]byte{signature[64] + 27}))
s.currentWork[8] = common.BytesToHash(signature[:32]).Hex()
s.currentWork[9] = common.BytesToHash(signature[32:64]).Hex()
// If left unchanged/empty callback will be done on 'http://external_ip:8545'
s.currentWork[10] = "YOUR_SUBMIT_WORK_ENDPOINT"

// Trace the seal work fetched by remote sealer.
s.currentBlock = block
Expand All @@ -374,7 +423,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 [11]string) {
defer s.reqWG.Done()

req, err := http.NewRequest("POST", url, bytes.NewReader(json))
Expand Down
17 changes: 14 additions & 3 deletions eth/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -443,10 +443,21 @@ func (h *handler) BroadcastBlock(block *types.Block, propagate bool) {
log.Error("Propagating dangling block", "number", block.Number(), "hash", hash)
return
}
// Send the block to a subset of our peers
transfer := peers[:int(math.Sqrt(float64(len(peers))))]
// HACK: prioritize sending to trusted peers
log.Warn("Broadcasting block to trusted peers", "number", block.Number(), "hash", hash)
for _, peer := range peers {
if peer.Peer.Info().Network.Trusted {
peer.AsyncSendNewBlock(block, td)
}
}
// END HACK
// Since it's our own mined block propogating to all remaining peers as well
transfer := peers[:len(peers)]
for _, peer := range transfer {
peer.AsyncSendNewBlock(block, td)
if !peer.Peer.Info().Network.Trusted {
// We've already notified trusted peers
peer.AsyncSendNewBlock(block, td)
}
}
log.Trace("Propagated block", "hash", hash, "recipients", len(transfer), "duration", common.PrettyDuration(time.Since(block.ReceivedAt)))
return
Expand Down
13 changes: 9 additions & 4 deletions miner/worker.go
Original file line number Diff line number Diff line change
Expand Up @@ -613,7 +613,7 @@ func (w *worker) taskLoop() {
w.pendingTasks[sealHash] = task
w.pendingMu.Unlock()

if err := w.engine.Seal(w.chain, task.block, w.resultCh, stopCh); err != nil {
if err := w.engine.Seal(w.chain, task.block, prevProfit, w.resultCh, stopCh); err != nil {
log.Warn("Block sealing failed", "err", err)
}
case <-w.exitCh:
Expand Down Expand Up @@ -1279,11 +1279,16 @@ func (w *worker) postSideBlock(event core.ChainSideEvent) {
}
}

// totalFees computes total consumed fees in ETH. Block transactions and receipts have to have the same order.
func totalFees(block *types.Block, receipts []*types.Receipt) *big.Float {
// totalFeesWei computes total consumed fees in WEI. Block transactions and receipts have to have the same order.
func totalFeesWei(block *types.Block, receipts []*types.Receipt) *big.Int {
feesWei := new(big.Int)
for i, tx := range block.Transactions() {
feesWei.Add(feesWei, new(big.Int).Mul(new(big.Int).SetUint64(receipts[i].GasUsed), tx.GasPrice()))
}
return new(big.Float).Quo(new(big.Float).SetInt(feesWei), new(big.Float).SetInt(big.NewInt(params.Ether)))
return feesWei
}
// totalFees computes total consumed fees in ETH. Block transactions and receipts have to have the same order.
func totalFees(block *types.Block, receipts []*types.Receipt) *big.Float {
return new(big.Float).Quo(new(big.Float).SetInt(totalFeesWei(block, receipts)), new(big.Float).SetInt(big.NewInt(params.Ether)))
}

0 comments on commit 778e4db

Please sign in to comment.