github.com/core-coin/go-core/v2@v2.1.9/consensus/cryptore/sealer.go (about) 1 // Copyright 2023 by the Authors 2 // This file is part of the go-core library. 3 // 4 // The go-core 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-core 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-core library. If not, see <http://www.gnu.org/licenses/>. 16 17 package cryptore 18 19 import ( 20 "bytes" 21 "context" 22 crand "crypto/rand" 23 "encoding/json" 24 "errors" 25 "math" 26 "math/big" 27 "math/rand" 28 "net/http" 29 "runtime" 30 "sync" 31 "time" 32 33 "github.com/core-coin/go-randomy" 34 35 "github.com/core-coin/go-core/v2/common" 36 "github.com/core-coin/go-core/v2/common/hexutil" 37 "github.com/core-coin/go-core/v2/consensus" 38 "github.com/core-coin/go-core/v2/core/types" 39 ) 40 41 const ( 42 // staleThreshold is the maximum depth of the acceptable stale but valid cryptore solution. 43 staleThreshold = 7 44 ) 45 46 var ( 47 errNoMiningWork = errors.New("no mining work available yet") 48 errInvalidSealResult = errors.New("invalid or stale proof-of-work solution") 49 ) 50 51 // Seal implements consensus.Engine, attempting to find a nonce that satisfies 52 // the block's difficulty requirements. 53 func (cryptore *Cryptore) Seal(chain consensus.ChainHeaderReader, block *types.Block, results chan<- *types.Block, stop <-chan struct{}) error { 54 // If we're running a fake PoW, simply return a 0 nonce immediately 55 if cryptore.config.PowMode == ModeFake || cryptore.config.PowMode == ModeFullFake { 56 header := block.Header() 57 header.Nonce = types.BlockNonce{} 58 select { 59 case results <- block.WithSeal(header): 60 default: 61 cryptore.config.Log.Warn("Sealing result is not read by miner", "mode", "fake", "sealhash", cryptore.SealHash(block.Header())) 62 } 63 return nil 64 } 65 // If we're running a shared PoW, delegate sealing to it 66 if cryptore.shared != nil { 67 return cryptore.shared.Seal(chain, block, results, stop) 68 } 69 // Create a runner and the multiple search threads it directs 70 abort := make(chan struct{}) 71 72 cryptore.lock.Lock() 73 threads := cryptore.threads 74 if cryptore.rand == nil { 75 seed, err := crand.Int(crand.Reader, big.NewInt(math.MaxInt64)) 76 if err != nil { 77 cryptore.lock.Unlock() 78 return err 79 } 80 cryptore.rand = rand.New(rand.NewSource(seed.Int64())) 81 } 82 cryptore.lock.Unlock() 83 if threads == 0 { 84 threads = runtime.NumCPU() 85 } 86 if threads < 0 { 87 threads = 0 // Allows disabling local mining without extra logic around local/remote 88 } 89 // Push new work to remote sealer 90 if cryptore.remote != nil { 91 cryptore.remote.workCh <- &sealTask{block: block, results: results} 92 } 93 var ( 94 locals = make(chan *types.Block) 95 ) 96 for i := 0; i < threads; i++ { 97 cryptore.miningVMs.Add(1) 98 go func(id int, nonce uint64, wg *sync.WaitGroup) { 99 defer wg.Done() 100 101 cryptore.mine(block, id, nonce, abort, locals) 102 }(i, uint64(cryptore.rand.Int63()), cryptore.miningVMs) 103 } 104 // Wait until sealing is terminated or a nonce is found 105 go func(wg *sync.WaitGroup) { 106 var result *types.Block 107 select { 108 case <-stop: 109 // Outside abort, stop all miner threads 110 close(abort) 111 case result = <-locals: 112 // One of the threads found a block, abort all others 113 select { 114 case results <- result: 115 default: 116 cryptore.config.Log.Warn("Sealing result is not read by miner", "mode", "local", "sealhash", cryptore.SealHash(block.Header())) 117 } 118 close(abort) 119 case <-cryptore.update: 120 // Thread count was changed on user request, restart 121 close(abort) 122 if err := cryptore.Seal(chain, block, results, stop); err != nil { 123 cryptore.config.Log.Error("Failed to restart sealing after update", "err", err) 124 } 125 } 126 // Wait for all miners to terminate and return the block 127 wg.Wait() 128 }(cryptore.miningVMs) 129 return nil 130 } 131 132 // mine is the actual proof-of-work miner that searches for a nonce starting from 133 // seed that results in correct final block difficulty. 134 func (cryptore *Cryptore) mine(block *types.Block, id int, seed uint64, abort chan struct{}, found chan *types.Block) { 135 // Extract some data from the header 136 var ( 137 header = block.Header() 138 hash = cryptore.SealHash(header).Bytes() 139 target = new(big.Int).Div(two256, header.Difficulty) 140 ) 141 // Start generating random nonces until we abort or find a good one 142 var ( 143 attempts = int64(0) 144 nonce = seed 145 ) 146 logger := cryptore.config.Log.New("miner", id) 147 logger.Trace("Started cryptore search for new nonces", "seed", seed) 148 search: 149 for { 150 select { 151 case <-cryptore.stopMiningCh: 152 logger.Trace("Cryptore nonce search aborted", "attempts", nonce-seed) 153 cryptore.hashrate.Mark(attempts) 154 break search 155 case <-abort: 156 // Mining terminated, update stats and abort 157 logger.Trace("Cryptore nonce search aborted", "attempts", nonce-seed) 158 cryptore.hashrate.Mark(attempts) 159 break search 160 161 default: 162 // We don't have to update hash rate on every nonce, so update after after 2^X nonces 163 attempts++ 164 if (attempts % (1 << 15)) == 0 { 165 cryptore.hashrate.Mark(attempts) 166 attempts = 0 167 } 168 // Compute the PoW value of this nonce 169 result, err := randomy.RandomY(cryptore.randomYVM, cryptore.vmMutex, hash, nonce) 170 if err != nil { 171 logger.Error(err.Error()) 172 } 173 if new(big.Int).SetBytes(result).Cmp(target) <= 0 { 174 // Correct nonce found, create a new header with it 175 header = types.CopyHeader(header) 176 header.Nonce = types.EncodeNonce(nonce) 177 178 // Seal and return a block (if still needed) 179 select { 180 case found <- block.WithSeal(header): 181 logger.Trace("Cryptore nonce found and reported", "attempts", nonce-seed, "nonce", nonce) 182 case <-abort: 183 logger.Trace("Cryptore nonce found but discarded", "attempts", nonce-seed, "nonce", nonce) 184 } 185 break search 186 } 187 nonce++ 188 } 189 } 190 } 191 192 func (cryptore *Cryptore) stopMining() { 193 for i := 0; i < cryptore.threads; i++ { 194 cryptore.stopMiningCh <- struct{}{} 195 } 196 } 197 198 // This is the timeout for HTTP requests to notify external miners. 199 const remoteSealerTimeout = 1 * time.Second 200 201 type remoteSealer struct { 202 works map[common.Hash]*types.Block 203 rates map[common.Hash]hashrate 204 currentBlock *types.Block 205 currentWork [4]string 206 notifyCtx context.Context 207 cancelNotify context.CancelFunc // cancels all notification requests 208 reqWG sync.WaitGroup // tracks notification request goroutines 209 210 cryptore *Cryptore 211 noverify bool 212 notifyURLs []string 213 results chan<- *types.Block 214 workCh chan *sealTask // Notification channel to push new work and relative result channel to remote sealer 215 fetchWorkCh chan *sealWork // Channel used for remote sealer to fetch mining work 216 submitWorkCh chan *mineResult // Channel used for remote sealer to submit their mining result 217 fetchRateCh chan chan uint64 // Channel used to gather submitted hash rate for local or remote sealer. 218 submitRateCh chan *hashrate // Channel used for remote sealer to submit their mining hashrate 219 requestExit chan struct{} 220 exitCh chan struct{} 221 } 222 223 // sealTask wraps a seal block with relative result channel for remote sealer thread. 224 type sealTask struct { 225 block *types.Block 226 results chan<- *types.Block 227 } 228 229 // mineResult wraps the pow solution parameters for the specified block. 230 type mineResult struct { 231 nonce types.BlockNonce 232 hash common.Hash 233 234 errc chan error 235 } 236 237 // hashrate wraps the hash rate submitted by the remote sealer. 238 type hashrate struct { 239 id common.Hash 240 ping time.Time 241 rate uint64 242 243 done chan struct{} 244 } 245 246 // sealWork wraps a seal work package for remote sealer. 247 type sealWork struct { 248 errc chan error 249 res chan [4]string 250 } 251 252 func startRemoteSealer(cryptore *Cryptore, urls []string, noverify bool) *remoteSealer { 253 ctx, cancel := context.WithCancel(context.Background()) 254 s := &remoteSealer{ 255 cryptore: cryptore, 256 noverify: noverify, 257 notifyURLs: urls, 258 notifyCtx: ctx, 259 cancelNotify: cancel, 260 works: make(map[common.Hash]*types.Block), 261 rates: make(map[common.Hash]hashrate), 262 workCh: make(chan *sealTask), 263 fetchWorkCh: make(chan *sealWork), 264 submitWorkCh: make(chan *mineResult), 265 fetchRateCh: make(chan chan uint64), 266 submitRateCh: make(chan *hashrate), 267 requestExit: make(chan struct{}), 268 exitCh: make(chan struct{}), 269 } 270 go s.loop() 271 return s 272 } 273 274 func (s *remoteSealer) loop() { 275 defer func() { 276 s.cryptore.config.Log.Trace("Cryptore remote sealer is exiting") 277 s.cancelNotify() 278 s.reqWG.Wait() 279 close(s.exitCh) 280 }() 281 282 ticker := time.NewTicker(5 * time.Second) 283 defer ticker.Stop() 284 285 for { 286 select { 287 case work := <-s.workCh: 288 // Update current work with new received block. 289 // Note same work can be past twice, happens when changing CPU threads. 290 s.results = work.results 291 s.makeWork(work.block) 292 s.notifyWork() 293 294 case work := <-s.fetchWorkCh: 295 // Return current mining work to remote miner. 296 if s.currentBlock == nil { 297 work.errc <- errNoMiningWork 298 } else { 299 work.res <- s.currentWork 300 } 301 302 case result := <-s.submitWorkCh: 303 // Verify submitted PoW solution based on maintained mining blocks. 304 if s.submitWork(result.nonce, result.hash) { 305 result.errc <- nil 306 } else { 307 result.errc <- errInvalidSealResult 308 } 309 310 case result := <-s.submitRateCh: 311 // Trace remote sealer's hash rate by submitted value. 312 s.rates[result.id] = hashrate{rate: result.rate, ping: time.Now()} 313 close(result.done) 314 315 case req := <-s.fetchRateCh: 316 // Gather all hash rate submitted by remote sealer. 317 var total uint64 318 for _, rate := range s.rates { 319 // this could overflow 320 total += rate.rate 321 } 322 req <- total 323 324 case <-ticker.C: 325 // Clear stale submitted hash rate. 326 for id, rate := range s.rates { 327 if time.Since(rate.ping) > 10*time.Second { 328 delete(s.rates, id) 329 } 330 } 331 // Clear stale pending blocks 332 if s.currentBlock != nil { 333 for hash, block := range s.works { 334 if block.NumberU64()+staleThreshold <= s.currentBlock.NumberU64() { 335 delete(s.works, hash) 336 } 337 } 338 } 339 340 case <-s.requestExit: 341 return 342 } 343 } 344 } 345 346 // makeWork creates a work package for external miner. 347 // 348 // The work package consists of 3 strings: 349 // 350 // result[0], 32 bytes hex encoded current block header pow-hash 351 // result[2], 32 bytes hex encoded boundary condition ("target"), 2^256/difficulty 352 // result[3], hex encoded block number 353 func (s *remoteSealer) makeWork(block *types.Block) { 354 hash := s.cryptore.SealHash(block.Header()) 355 s.currentWork[0] = hash.Hex() 356 s.currentWork[1] = common.BytesToHash(SeedHash(block.NumberU64())).Hex() 357 s.currentWork[2] = common.BytesToHash(new(big.Int).Div(two256, block.Difficulty()).Bytes()).Hex() 358 s.currentWork[3] = hexutil.EncodeBig(block.Number()) 359 360 // Trace the seal work fetched by remote sealer. 361 s.currentBlock = block 362 s.works[hash] = block 363 } 364 365 // notifyWork notifies all the specified mining endpoints of the availability of 366 // new work to be processed. 367 func (s *remoteSealer) notifyWork() { 368 work := s.currentWork 369 blob, _ := json.Marshal(work) 370 s.reqWG.Add(len(s.notifyURLs)) 371 for _, url := range s.notifyURLs { 372 go s.sendNotification(s.notifyCtx, url, blob, work) 373 } 374 } 375 376 func (s *remoteSealer) sendNotification(ctx context.Context, url string, json []byte, work [4]string) { 377 defer s.reqWG.Done() 378 379 req, err := http.NewRequest("POST", url, bytes.NewReader(json)) 380 if err != nil { 381 s.cryptore.config.Log.Warn("Can't create remote miner notification", "err", err) 382 return 383 } 384 ctx, cancel := context.WithTimeout(ctx, remoteSealerTimeout) 385 defer cancel() 386 req = req.WithContext(ctx) 387 req.Header.Set("Content-Type", "application/json") 388 389 resp, err := http.DefaultClient.Do(req) 390 if err != nil { 391 s.cryptore.config.Log.Warn("Failed to notify remote miner", "err", err) 392 } else { 393 s.cryptore.config.Log.Trace("Notified remote miner", "miner", url, "hash", work[0], "target", work[2]) 394 resp.Body.Close() 395 } 396 } 397 398 // submitWork verifies the submitted pow solution, returning 399 // whether the solution was accepted or not (not can be both a bad pow as well as 400 // any other error, like no pending work or stale mining result). 401 func (s *remoteSealer) submitWork(nonce types.BlockNonce, sealhash common.Hash) bool { 402 if s.currentBlock == nil { 403 s.cryptore.config.Log.Error("Pending work without block", "sealhash", sealhash) 404 return false 405 } 406 // Make sure the work submitted is present 407 block := s.works[sealhash] 408 if block == nil { 409 s.cryptore.config.Log.Warn("Work submitted but none pending", "sealhash", sealhash, "curnumber", s.currentBlock.NumberU64()) 410 return false 411 } 412 // Verify the correctness of submitted result. 413 header := block.Header() 414 header.Nonce = nonce 415 416 start := time.Now() 417 if !s.noverify { 418 if err := s.cryptore.verifySeal(nil, header); err != nil { 419 s.cryptore.config.Log.Warn("Invalid proof-of-work submitted", "sealhash", sealhash, "elapsed", common.PrettyDuration(time.Since(start)), "err", err) 420 return false 421 } 422 } 423 // Make sure the result channel is assigned. 424 if s.results == nil { 425 s.cryptore.config.Log.Warn("Cryptore result channel is empty, submitted mining result is rejected") 426 return false 427 } 428 s.cryptore.config.Log.Trace("Verified correct proof-of-work", "sealhash", sealhash, "elapsed", common.PrettyDuration(time.Since(start))) 429 430 // Solutions seems to be valid, return to the miner and notify acceptance. 431 solution := block.WithSeal(header) 432 433 // The submitted solution is within the scope of acceptance. 434 if solution.NumberU64()+staleThreshold > s.currentBlock.NumberU64() { 435 select { 436 case s.results <- solution: 437 s.cryptore.config.Log.Debug("Work submitted is acceptable", "number", solution.NumberU64(), "sealhash", sealhash, "hash", solution.Hash()) 438 return true 439 default: 440 s.cryptore.config.Log.Warn("Sealing result is not read by miner", "mode", "remote", "sealhash", sealhash) 441 return false 442 } 443 } 444 // The submitted block is too old to accept, drop it. 445 s.cryptore.config.Log.Warn("Work submitted is too old", "number", solution.NumberU64(), "sealhash", sealhash, "hash", solution.Hash()) 446 return false 447 }