github.com/klaytn/klaytn@v1.12.1/consensus/gxhash/gxhash.go (about) 1 // Modifications Copyright 2018 The klaytn Authors 2 // Copyright 2017 The go-ethereum Authors 3 // This file is part of the go-ethereum library. 4 // 5 // The go-ethereum library is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Lesser General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // The go-ethereum library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Lesser General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public License 16 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 17 // 18 // This file is derived from consensus/ethash/ethash.go (2018/06/04). 19 // Modified and improved for the klaytn development. 20 21 package gxhash 22 23 import ( 24 "errors" 25 "fmt" 26 "math" 27 "math/big" 28 "math/rand" 29 "os" 30 "path/filepath" 31 "reflect" 32 "runtime" 33 "strconv" 34 "sync" 35 "time" 36 "unsafe" 37 38 "github.com/hashicorp/golang-lru/simplelru" 39 "github.com/klaytn/klaytn/consensus" 40 "github.com/klaytn/klaytn/log" 41 "github.com/klaytn/klaytn/networks/rpc" 42 "github.com/rcrowley/go-metrics" 43 44 mmap "github.com/edsrzf/mmap-go" 45 "github.com/klaytn/klaytn/common" 46 ) 47 48 var ErrInvalidDumpMagic = errors.New("invalid dump magic") 49 50 var ( 51 // maxUint256 is a big integer representing 2^256-1 52 maxUint256 = new(big.Int).Exp(common.Big2, common.Big256, common.Big0) 53 54 // sharedGxhash is a full instance that can be shared between multiple users. 55 sharedGxhash = New(Config{"", 3, 0, "", 1, 0, ModeNormal}) 56 57 // algorithmRevision is the data structure version used for file naming. 58 algorithmRevision = 23 59 60 // dumpMagic is a dataset dump header to sanity check a data dump. 61 dumpMagic = []uint32{0xbaddcafe, 0xfee1dead} 62 63 logger = log.NewModuleLogger(log.ConsensusGxhash) 64 ) 65 66 // isLittleEndian returns whether the local system is running in little or big 67 // endian byte order. 68 func isLittleEndian() bool { 69 n := uint32(0x01020304) 70 return *(*byte)(unsafe.Pointer(&n)) == 0x04 71 } 72 73 // memoryMap tries to memory map a file of uint32s for read only access. 74 func memoryMap(path string) (*os.File, mmap.MMap, []uint32, error) { 75 file, err := os.OpenFile(path, os.O_RDONLY, 0o644) 76 if err != nil { 77 return nil, nil, nil, err 78 } 79 mem, buffer, err := memoryMapFile(file, false) 80 if err != nil { 81 file.Close() 82 return nil, nil, nil, err 83 } 84 for i, magic := range dumpMagic { 85 if buffer[i] != magic { 86 mem.Unmap() 87 file.Close() 88 return nil, nil, nil, ErrInvalidDumpMagic 89 } 90 } 91 return file, mem, buffer[len(dumpMagic):], err 92 } 93 94 // memoryMapFile tries to memory map an already opened file descriptor. 95 func memoryMapFile(file *os.File, write bool) (mmap.MMap, []uint32, error) { 96 // Try to memory map the file 97 flag := mmap.RDONLY 98 if write { 99 flag = mmap.RDWR 100 } 101 mem, err := mmap.Map(file, flag, 0) 102 if err != nil { 103 return nil, nil, err 104 } 105 // Yay, we managed to memory map the file, here be dragons 106 var view []uint32 107 header := (*reflect.SliceHeader)(unsafe.Pointer(&view)) 108 header.Data = (*reflect.SliceHeader)(unsafe.Pointer(&mem)).Data 109 header.Cap = len(mem) / 4 110 header.Len = header.Cap 111 return mem, view, nil 112 } 113 114 // memoryMapAndGenerate tries to memory map a temporary file of uint32s for write 115 // access, fill it with the data from a generator and then move it into the final 116 // path requested. 117 func memoryMapAndGenerate(path string, size uint64, generator func(buffer []uint32)) (*os.File, mmap.MMap, []uint32, error) { 118 // Ensure the data folder exists 119 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { 120 return nil, nil, nil, err 121 } 122 // Create a huge temporary empty file to fill with data 123 temp := path + "." + strconv.Itoa(rand.Int()) 124 125 dump, err := os.Create(temp) 126 if err != nil { 127 return nil, nil, nil, err 128 } 129 if err = dump.Truncate(int64(len(dumpMagic))*4 + int64(size)); err != nil { 130 return nil, nil, nil, err 131 } 132 // Memory map the file for writing and fill it with the generator 133 mem, buffer, err := memoryMapFile(dump, true) 134 if err != nil { 135 dump.Close() 136 return nil, nil, nil, err 137 } 138 copy(buffer, dumpMagic) 139 140 data := buffer[len(dumpMagic):] 141 generator(data) 142 143 if err := mem.Unmap(); err != nil { 144 return nil, nil, nil, err 145 } 146 if err := dump.Close(); err != nil { 147 return nil, nil, nil, err 148 } 149 if err := os.Rename(temp, path); err != nil { 150 return nil, nil, nil, err 151 } 152 return memoryMap(path) 153 } 154 155 // lru tracks caches or datasets by their last use time, keeping at most N of them. 156 type lru struct { 157 what string 158 new func(epoch uint64) interface{} 159 mu sync.Mutex 160 // Items are kept in a LRU cache, but there is a special case: 161 // We always keep an item for (highest seen epoch) + 1 as the 'future item'. 162 cache *simplelru.LRU 163 future uint64 164 futureItem interface{} 165 } 166 167 // newlru create a new least-recently-used cache for either the verification caches 168 // or the mining datasets. 169 func newlru(what string, maxItems int, new func(epoch uint64) interface{}) *lru { 170 if maxItems <= 0 { 171 maxItems = 1 172 } 173 cache, _ := simplelru.NewLRU(maxItems, func(key, value interface{}) { 174 logger.Trace("Evicted gxhash "+what, "epoch", key) 175 }) 176 return &lru{what: what, new: new, cache: cache} 177 } 178 179 // get retrieves or creates an item for the given epoch. The first return value is always 180 // non-nil. The second return value is non-nil if lru thinks that an item will be useful in 181 // the near future. 182 func (lru *lru) get(epoch uint64) (item, future interface{}) { 183 lru.mu.Lock() 184 defer lru.mu.Unlock() 185 186 // Get or create the item for the requested epoch. 187 item, ok := lru.cache.Get(epoch) 188 if !ok { 189 if lru.future > 0 && lru.future == epoch { 190 item = lru.futureItem 191 } else { 192 logger.Trace("Requiring new gxhash "+lru.what, "epoch", epoch) 193 item = lru.new(epoch) 194 } 195 lru.cache.Add(epoch, item) 196 } 197 // Update the 'future item' if epoch is larger than previously seen. 198 if epoch < maxEpoch-1 && lru.future < epoch+1 { 199 logger.Trace("Requiring new future gxhash "+lru.what, "epoch", epoch+1) 200 future = lru.new(epoch + 1) 201 lru.future = epoch + 1 202 lru.futureItem = future 203 } 204 return item, future 205 } 206 207 // cache wraps an gxhash cache with some metadata to allow easier concurrent use. 208 type cache struct { 209 epoch uint64 // Epoch for which this cache is relevant 210 dump *os.File // File descriptor of the memory mapped cache 211 mmap mmap.MMap // Memory map itself to unmap before releasing 212 cache []uint32 // The actual cache data content (may be memory mapped) 213 once sync.Once // Ensures the cache is generated only once 214 } 215 216 // newCache creates a new gxhash verification cache and returns it as a plain Go 217 // interface to be usable in an LRU cache. 218 func newCache(epoch uint64) interface{} { 219 return &cache{epoch: epoch} 220 } 221 222 // generate ensures that the cache content is generated before use. 223 func (c *cache) generate(dir string, limit int, test bool) { 224 c.once.Do(func() { 225 size := cacheSize(c.epoch*epochLength + 1) 226 seed := seedHash(c.epoch*epochLength + 1) 227 if test { 228 size = 1024 229 } 230 // If we don't store anything on disk, generate and return. 231 if dir == "" { 232 c.cache = make([]uint32, size/4) 233 generateCache(c.cache, c.epoch, seed) 234 return 235 } 236 // Disk storage is needed, this will get fancy 237 var endian string 238 if !isLittleEndian() { 239 endian = ".be" 240 } 241 path := filepath.Join(dir, fmt.Sprintf("cache-R%d-%x%s", algorithmRevision, seed[:8], endian)) 242 locallogger := logger.NewWith("epoch", c.epoch) 243 244 // We're about to mmap the file, ensure that the mapping is cleaned up when the 245 // cache becomes unused. 246 runtime.SetFinalizer(c, (*cache).finalizer) 247 248 // Try to load the file from disk and memory map it 249 var err error 250 c.dump, c.mmap, c.cache, err = memoryMap(path) 251 if err == nil { 252 locallogger.Debug("Loaded old gxhash cache from disk") 253 return 254 } 255 locallogger.Debug("Failed to load old gxhash cache", "err", err) 256 257 // No previous cache available, create a new cache file to fill 258 c.dump, c.mmap, c.cache, err = memoryMapAndGenerate(path, size, func(buffer []uint32) { generateCache(buffer, c.epoch, seed) }) 259 if err != nil { 260 locallogger.Error("Failed to generate mapped gxhash cache", "err", err) 261 262 c.cache = make([]uint32, size/4) 263 generateCache(c.cache, c.epoch, seed) 264 } 265 // Iterate over all previous instances and delete old ones 266 for ep := int(c.epoch) - limit; ep >= 0; ep-- { 267 seed := seedHash(uint64(ep)*epochLength + 1) 268 path := filepath.Join(dir, fmt.Sprintf("cache-R%d-%x%s", algorithmRevision, seed[:8], endian)) 269 os.Remove(path) 270 } 271 }) 272 } 273 274 // finalizer unmaps the memory and closes the file. 275 func (c *cache) finalizer() { 276 if c.mmap != nil { 277 c.mmap.Unmap() 278 c.dump.Close() 279 c.mmap, c.dump = nil, nil 280 } 281 } 282 283 // dataset wraps an gxhash dataset with some metadata to allow easier concurrent use. 284 type dataset struct { 285 epoch uint64 // Epoch for which this cache is relevant 286 dump *os.File // File descriptor of the memory mapped cache 287 mmap mmap.MMap // Memory map itself to unmap before releasing 288 dataset []uint32 // The actual cache data content 289 once sync.Once // Ensures the cache is generated only once 290 } 291 292 // newDataset creates a new gxhash mining dataset and returns it as a plain Go 293 // interface to be usable in an LRU cache. 294 func newDataset(epoch uint64) interface{} { 295 return &dataset{epoch: epoch} 296 } 297 298 // generate ensures that the dataset content is generated before use. 299 func (d *dataset) generate(dir string, limit int, test bool) { 300 d.once.Do(func() { 301 csize := cacheSize(d.epoch*epochLength + 1) 302 dsize := datasetSize(d.epoch*epochLength + 1) 303 seed := seedHash(d.epoch*epochLength + 1) 304 if test { 305 csize = 1024 306 dsize = 32 * 1024 307 } 308 // If we don't store anything on disk, generate and return 309 if dir == "" { 310 cache := make([]uint32, csize/4) 311 generateCache(cache, d.epoch, seed) 312 313 d.dataset = make([]uint32, dsize/4) 314 generateDataset(d.dataset, d.epoch, cache) 315 } 316 // Disk storage is needed, this will get fancy 317 var endian string 318 if !isLittleEndian() { 319 endian = ".be" 320 } 321 path := filepath.Join(dir, fmt.Sprintf("full-R%d-%x%s", algorithmRevision, seed[:8], endian)) 322 localLogger := logger.NewWith("epoch", d.epoch) 323 324 // We're about to mmap the file, ensure that the mapping is cleaned up when the 325 // cache becomes unused. 326 runtime.SetFinalizer(d, (*dataset).finalizer) 327 328 // Try to load the file from disk and memory map it 329 var err error 330 d.dump, d.mmap, d.dataset, err = memoryMap(path) 331 if err == nil { 332 localLogger.Debug("Loaded old gxhash dataset from disk") 333 return 334 } 335 localLogger.Debug("Failed to load old gxhash dataset", "err", err) 336 337 // No previous dataset available, create a new dataset file to fill 338 cache := make([]uint32, csize/4) 339 generateCache(cache, d.epoch, seed) 340 341 d.dump, d.mmap, d.dataset, err = memoryMapAndGenerate(path, dsize, func(buffer []uint32) { generateDataset(buffer, d.epoch, cache) }) 342 if err != nil { 343 localLogger.Error("Failed to generate mapped gxhash dataset", "err", err) 344 345 d.dataset = make([]uint32, dsize/2) 346 generateDataset(d.dataset, d.epoch, cache) 347 } 348 // Iterate over all previous instances and delete old ones 349 for ep := int(d.epoch) - limit; ep >= 0; ep-- { 350 seed := seedHash(uint64(ep)*epochLength + 1) 351 path := filepath.Join(dir, fmt.Sprintf("full-R%d-%x%s", algorithmRevision, seed[:8], endian)) 352 os.Remove(path) 353 } 354 }) 355 } 356 357 // finalizer closes any file handlers and memory maps open. 358 func (d *dataset) finalizer() { 359 if d.mmap != nil { 360 d.mmap.Unmap() 361 d.dump.Close() 362 d.mmap, d.dump = nil, nil 363 } 364 } 365 366 // MakeCache generates a new gxhash cache and optionally stores it to disk. 367 func MakeCache(block uint64, dir string) { 368 c := cache{epoch: block / epochLength} 369 c.generate(dir, math.MaxInt32, false) 370 } 371 372 // MakeDataset generates a new gxhash dataset and optionally stores it to disk. 373 func MakeDataset(block uint64, dir string) { 374 d := dataset{epoch: block / epochLength} 375 d.generate(dir, math.MaxInt32, false) 376 } 377 378 // Mode defines the type and amount of PoW verification an gxhash engine makes. 379 type Mode uint 380 381 const ( 382 ModeNormal Mode = iota 383 ModeShared 384 ModeTest 385 ModeFake 386 ModeFullFake 387 ) 388 389 // Config are the configuration parameters of the gxhash. 390 type Config struct { 391 CacheDir string 392 CachesInMem int 393 CachesOnDisk int 394 DatasetDir string 395 DatasetsInMem int 396 DatasetsOnDisk int 397 PowMode Mode 398 } 399 400 // Gxhash is a consensus engine based on proot-of-work implementing the gxhash 401 // algorithm. 402 type Gxhash struct { 403 config Config 404 405 caches *lru // In memory caches to avoid regenerating too often 406 datasets *lru // In memory datasets to avoid regenerating too often 407 408 // Mining related fields 409 rand *rand.Rand // Properly seeded random source for nonces 410 threads int // Number of threads to mine on if mining 411 update chan struct{} // Notification channel to update mining parameters 412 hashrate metrics.Meter // Meter tracking the average hashrate 413 414 // The fields below are hooks for testing 415 shared *Gxhash // Shared PoW verifier to avoid cache regeneration 416 fakeFail uint64 // Block number which fails PoW check even in fake mode 417 fakeDelay time.Duration // Time delay to sleep for before returning from verify 418 419 lock sync.Mutex // Ensures thread safety for the in-memory caches and mining fields 420 } 421 422 // New creates a full sized gxhash PoW scheme. 423 func New(config Config) *Gxhash { 424 if config.CachesInMem <= 0 { 425 logger.Error("One gxhash cache must always be in memory", "requested", config.CachesInMem) 426 config.CachesInMem = 1 427 } 428 if config.CacheDir != "" && config.CachesOnDisk > 0 { 429 logger.Debug("Disk storage enabled for gxhash caches", "dir", config.CacheDir, "count", config.CachesOnDisk) 430 } 431 if config.DatasetDir != "" && config.DatasetsOnDisk > 0 { 432 logger.Debug("Disk storage enabled for gxhash DAGs", "dir", config.DatasetDir, "count", config.DatasetsOnDisk) 433 } 434 return &Gxhash{ 435 config: config, 436 caches: newlru("cache", config.CachesInMem, newCache), 437 datasets: newlru("dataset", config.DatasetsInMem, newDataset), 438 update: make(chan struct{}), 439 hashrate: metrics.NewMeter(), 440 } 441 } 442 443 // NewTester creates a small sized gxhash PoW scheme useful only for testing 444 // purposes. 445 func NewTester() *Gxhash { 446 return New(Config{CachesInMem: 1, PowMode: ModeTest}) 447 } 448 449 // NewFaker creates a gxhash consensus engine with a fake PoW scheme that accepts 450 // all blocks' seal as valid, though they still have to conform to the Klaytn 451 // consensus rules. 452 func NewFaker() *Gxhash { 453 return &Gxhash{ 454 config: Config{ 455 PowMode: ModeFake, 456 }, 457 } 458 } 459 460 // NewFakeFailer creates a gxhash consensus engine with a fake PoW scheme that 461 // accepts all blocks as valid apart from the single one specified, though they 462 // still have to conform to the Klaytn consensus rules. 463 func NewFakeFailer(fail uint64) *Gxhash { 464 return &Gxhash{ 465 config: Config{ 466 PowMode: ModeFake, 467 }, 468 fakeFail: fail, 469 } 470 } 471 472 // NewFakeDelayer creates a gxhash consensus engine with a fake PoW scheme that 473 // accepts all blocks as valid, but delays verifications by some time, though 474 // they still have to conform to the Klaytn consensus rules. 475 func NewFakeDelayer(delay time.Duration) *Gxhash { 476 return &Gxhash{ 477 config: Config{ 478 PowMode: ModeFake, 479 }, 480 fakeDelay: delay, 481 } 482 } 483 484 // NewFullFaker creates an gxhash consensus engine with a full fake scheme that 485 // accepts all blocks as valid, without checking any consensus rules whatsoever. 486 func NewFullFaker() *Gxhash { 487 return &Gxhash{ 488 config: Config{ 489 PowMode: ModeFullFake, 490 }, 491 } 492 } 493 494 // NewShared creates a full sized gxhash PoW shared between all requesters running 495 // in the same process. 496 func NewShared() *Gxhash { 497 return &Gxhash{shared: sharedGxhash} 498 } 499 500 // cache tries to retrieve a verification cache for the specified block number 501 // by first checking against a list of in-memory caches, then against caches 502 // stored on disk, and finally generating one if none can be found. 503 func (gxhash *Gxhash) cache(block uint64) *cache { 504 epoch := block / epochLength 505 currentI, futureI := gxhash.caches.get(epoch) 506 current := currentI.(*cache) 507 508 // Wait for generation finish. 509 current.generate(gxhash.config.CacheDir, gxhash.config.CachesOnDisk, gxhash.config.PowMode == ModeTest) 510 511 // If we need a new future cache, now's a good time to regenerate it. 512 if futureI != nil { 513 future := futureI.(*cache) 514 go future.generate(gxhash.config.CacheDir, gxhash.config.CachesOnDisk, gxhash.config.PowMode == ModeTest) 515 } 516 return current 517 } 518 519 // dataset tries to retrieve a mining dataset for the specified block number 520 // by first checking against a list of in-memory datasets, then against DAGs 521 // stored on disk, and finally generating one if none can be found. 522 func (gxhash *Gxhash) dataset(block uint64) *dataset { 523 epoch := block / epochLength 524 currentI, futureI := gxhash.datasets.get(epoch) 525 current := currentI.(*dataset) 526 527 // Wait for generation finish. 528 current.generate(gxhash.config.DatasetDir, gxhash.config.DatasetsOnDisk, gxhash.config.PowMode == ModeTest) 529 530 // If we need a new future dataset, now's a good time to regenerate it. 531 if futureI != nil { 532 future := futureI.(*dataset) 533 go future.generate(gxhash.config.DatasetDir, gxhash.config.DatasetsOnDisk, gxhash.config.PowMode == ModeTest) 534 } 535 536 return current 537 } 538 539 // Threads returns the number of mining threads currently enabled. This doesn't 540 // necessarily mean that mining is running! 541 func (gxhash *Gxhash) Threads() int { 542 gxhash.lock.Lock() 543 defer gxhash.lock.Unlock() 544 545 return gxhash.threads 546 } 547 548 // SetThreads updates the number of mining threads currently enabled. Calling 549 // this method does not start mining, only sets the thread count. If zero is 550 // specified, the miner will use all cores of the machine. Setting a thread 551 // count below zero is allowed and will cause the miner to idle, without any 552 // work being done. 553 func (gxhash *Gxhash) SetThreads(threads int) { 554 gxhash.lock.Lock() 555 defer gxhash.lock.Unlock() 556 557 // If we're running a shared PoW, set the thread count on that instead 558 if gxhash.shared != nil { 559 gxhash.shared.SetThreads(threads) 560 return 561 } 562 // Update the threads and ping any running seal to pull in any changes 563 gxhash.threads = threads 564 select { 565 case gxhash.update <- struct{}{}: 566 default: 567 } 568 } 569 570 // Hashrate implements PoW, returning the measured rate of the search invocations 571 // per second over the last minute. 572 func (gxhash *Gxhash) Hashrate() float64 { 573 return gxhash.hashrate.Rate1() 574 } 575 576 // APIs implements consensus.Engine, returning the user facing RPC APIs. Currently 577 // that is empty. 578 func (gxhash *Gxhash) APIs(chain consensus.ChainReader) []rpc.API { 579 return nil 580 } 581 582 // SeedHash is the seed to use for generating a verification cache and the mining 583 // dataset. 584 func SeedHash(block uint64) []byte { 585 return seedHash(block) 586 } 587 588 // Protocol implements consensus.Engine.Protocol 589 func (gxhash *Gxhash) Protocol() consensus.Protocol { 590 return consensus.KlayProtocol 591 }