ethash_test.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // Copyright 2017 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. package ethash
  17. import (
  18. "io/ioutil"
  19. "math/big"
  20. "math/rand"
  21. "os"
  22. "sync"
  23. "testing"
  24. "github.com/ethereum/go-ethereum/core/types"
  25. )
  26. // Tests that ethash works correctly in test mode.
  27. func TestTestMode(t *testing.T) {
  28. head := &types.Header{Number: big.NewInt(1), Difficulty: big.NewInt(100)}
  29. ethash := NewTester()
  30. block, err := ethash.Seal(nil, types.NewBlockWithHeader(head), nil)
  31. if err != nil {
  32. t.Fatalf("failed to seal block: %v", err)
  33. }
  34. head.Nonce = types.EncodeNonce(block.Nonce())
  35. head.MixDigest = block.MixDigest()
  36. if err := ethash.VerifySeal(nil, head); err != nil {
  37. t.Fatalf("unexpected verification error: %v", err)
  38. }
  39. }
  40. // This test checks that cache lru logic doesn't crash under load.
  41. // It reproduces https://github.com/ethereum/go-ethereum/issues/14943
  42. func TestCacheFileEvict(t *testing.T) {
  43. tmpdir, err := ioutil.TempDir("", "ethash-test")
  44. if err != nil {
  45. t.Fatal(err)
  46. }
  47. defer os.RemoveAll(tmpdir)
  48. e := New(Config{CachesInMem: 3, CachesOnDisk: 10, CacheDir: tmpdir, PowMode: ModeTest})
  49. workers := 8
  50. epochs := 100
  51. var wg sync.WaitGroup
  52. wg.Add(workers)
  53. for i := 0; i < workers; i++ {
  54. go verifyTest(&wg, e, i, epochs)
  55. }
  56. wg.Wait()
  57. }
  58. func verifyTest(wg *sync.WaitGroup, e *Ethash, workerIndex, epochs int) {
  59. defer wg.Done()
  60. const wiggle = 4 * epochLength
  61. r := rand.New(rand.NewSource(int64(workerIndex)))
  62. for epoch := 0; epoch < epochs; epoch++ {
  63. block := int64(epoch)*epochLength - wiggle/2 + r.Int63n(wiggle)
  64. if block < 0 {
  65. block = 0
  66. }
  67. head := &types.Header{Number: big.NewInt(block), Difficulty: big.NewInt(100)}
  68. e.VerifySeal(nil, head)
  69. }
  70. }