github.com/intfoundation/intchain@v0.0.0-20220727031208-4316ad31ca73/miner/remote_agent.go (about)

     1  // Copyright 2015 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package miner
    18  
    19  import (
    20  	"errors"
    21  	"math/big"
    22  	"sync"
    23  	"sync/atomic"
    24  	"time"
    25  
    26  	"github.com/intfoundation/intchain/common"
    27  	"github.com/intfoundation/intchain/consensus"
    28  	"github.com/intfoundation/intchain/core/types"
    29  	"github.com/intfoundation/intchain/log"
    30  )
    31  
    32  type hashrate struct {
    33  	ping time.Time
    34  	rate uint64
    35  }
    36  
    37  type RemoteAgent struct {
    38  	mu sync.Mutex
    39  
    40  	quitCh   chan struct{}
    41  	workCh   chan *Work
    42  	returnCh chan<- *Result
    43  
    44  	chain       consensus.ChainReader
    45  	engine      consensus.Engine
    46  	currentWork *Work
    47  	work        map[common.Hash]*Work
    48  
    49  	hashrateMu sync.RWMutex
    50  	hashrate   map[common.Hash]hashrate
    51  
    52  	running int32 // running indicates whether the agent is active. Call atomically
    53  }
    54  
    55  func NewRemoteAgent(chain consensus.ChainReader, engine consensus.Engine) *RemoteAgent {
    56  	return &RemoteAgent{
    57  		chain:    chain,
    58  		engine:   engine,
    59  		work:     make(map[common.Hash]*Work),
    60  		hashrate: make(map[common.Hash]hashrate),
    61  	}
    62  }
    63  
    64  func (a *RemoteAgent) SubmitHashrate(id common.Hash, rate uint64) {
    65  	a.hashrateMu.Lock()
    66  	defer a.hashrateMu.Unlock()
    67  
    68  	a.hashrate[id] = hashrate{time.Now(), rate}
    69  }
    70  
    71  func (a *RemoteAgent) Work() chan<- *Work {
    72  	return a.workCh
    73  }
    74  
    75  func (a *RemoteAgent) SetReturnCh(returnCh chan<- *Result) {
    76  	a.returnCh = returnCh
    77  }
    78  
    79  func (a *RemoteAgent) Start() {
    80  	if !atomic.CompareAndSwapInt32(&a.running, 0, 1) {
    81  		return
    82  	}
    83  	a.quitCh = make(chan struct{})
    84  	a.workCh = make(chan *Work, 1)
    85  	go a.loop(a.workCh, a.quitCh)
    86  }
    87  
    88  func (a *RemoteAgent) Stop() {
    89  	if !atomic.CompareAndSwapInt32(&a.running, 1, 0) {
    90  		return
    91  	}
    92  	close(a.quitCh)
    93  	close(a.workCh)
    94  }
    95  
    96  // GetHashRate returns the accumulated hashrate of all identifier combined
    97  func (a *RemoteAgent) GetHashRate() (tot int64) {
    98  	a.hashrateMu.RLock()
    99  	defer a.hashrateMu.RUnlock()
   100  
   101  	// this could overflow
   102  	for _, hashrate := range a.hashrate {
   103  		tot += int64(hashrate.rate)
   104  	}
   105  	return
   106  }
   107  
   108  func (a *RemoteAgent) GetWork() ([3]string, error) {
   109  	a.mu.Lock()
   110  	defer a.mu.Unlock()
   111  
   112  	var res [3]string
   113  
   114  	if a.currentWork != nil {
   115  		block := a.currentWork.Block
   116  
   117  		res[0] = block.HashNoNonce().Hex()
   118  		//seedHash := ethash.SeedHash(block.NumberU64())
   119  		//res[1] = common.BytesToHash(seedHash).Hex()
   120  		// Calculate the "target" to be returned to the external miner
   121  		n := big.NewInt(1)
   122  		n.Lsh(n, 255)
   123  		n.Div(n, block.Difficulty())
   124  		n.Lsh(n, 1)
   125  		res[2] = common.BytesToHash(n.Bytes()).Hex()
   126  
   127  		a.work[block.HashNoNonce()] = a.currentWork
   128  		return res, nil
   129  	}
   130  	return res, errors.New("No work available yet, don't panic.")
   131  }
   132  
   133  // SubmitWork tries to inject a pow solution into the remote agent, returning
   134  // whether the solution was accepted or not (not can be both a bad pow as well as
   135  // any other error, like no work pending).
   136  func (a *RemoteAgent) SubmitWork(nonce types.BlockNonce, mixDigest, hash common.Hash) bool {
   137  	a.mu.Lock()
   138  	defer a.mu.Unlock()
   139  
   140  	// Make sure the work submitted is present
   141  	work := a.work[hash]
   142  	if work == nil {
   143  		log.Info("Work submitted but none pending", "hash", hash)
   144  		return false
   145  	}
   146  	// Make sure the Engine solutions is indeed valid
   147  	result := work.Block.Header()
   148  	result.Nonce = nonce
   149  	result.MixDigest = mixDigest
   150  
   151  	if err := a.engine.VerifySeal(a.chain, result); err != nil {
   152  		log.Warn("Invalid proof-of-work submitted", "hash", hash, "err", err)
   153  		return false
   154  	}
   155  	block := work.Block.WithSeal(result)
   156  
   157  	// Solutions seems to be valid, return to the miner and notify acceptance
   158  	a.returnCh <- &Result{Work: work, Block: block}
   159  	delete(a.work, hash)
   160  
   161  	return true
   162  }
   163  
   164  // loop monitors mining events on the work and quit channels, updating the internal
   165  // state of the remote miner until a termination is requested.
   166  //
   167  // Note, the reason the work and quit channels are passed as parameters is because
   168  // RemoteAgent.Start() constantly recreates these channels, so the loop code cannot
   169  // assume data stability in these member fields.
   170  func (a *RemoteAgent) loop(workCh chan *Work, quitCh chan struct{}) {
   171  	ticker := time.NewTicker(5 * time.Second)
   172  	defer ticker.Stop()
   173  
   174  	for {
   175  		select {
   176  		case <-quitCh:
   177  			return
   178  		case work := <-workCh:
   179  			a.mu.Lock()
   180  			a.currentWork = work
   181  			a.mu.Unlock()
   182  		case <-ticker.C:
   183  			// cleanup
   184  			a.mu.Lock()
   185  			for hash, work := range a.work {
   186  				if time.Since(work.createdAt) > 7*(12*time.Second) {
   187  					delete(a.work, hash)
   188  				}
   189  			}
   190  			a.mu.Unlock()
   191  
   192  			a.hashrateMu.Lock()
   193  			for id, hashrate := range a.hashrate {
   194  				if time.Since(hashrate.ping) > 10*time.Second {
   195  					delete(a.hashrate, id)
   196  				}
   197  			}
   198  			a.hashrateMu.Unlock()
   199  		}
   200  	}
   201  }