Module: Ethereum::Ethash

Defined in:
lib/ethereum/ethash.rb

Constant Summary collapse

EPOCH_LENGTH =
::Ethash::EPOCH_LENGTH
CACHE_BY_SEED_MAX =
32

Class Method Summary collapse

Class Method Details

.cache_by_file(block_number, data = nil) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/ethereum/ethash.rb', line 31

def cache_by_file(block_number, data=nil)
  path = "/tmp/ruby_ethereum_hashimoto_cache_#{block_number}"
  if data
    File.open(path, 'wb') {|f| f.write Marshal.dump(data) }
  else
    if File.exist?(path)
      File.open(path, 'rb') {|f| Marshal.load f.read }
    else
      nil
    end
  end
end

.cache_by_seedObject



27
28
29
# File 'lib/ethereum/ethash.rb', line 27

def cache_by_seed
  @cache_by_seed ||= {} # ordered hash
end

.get_cache(blknum) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/ethereum/ethash.rb', line 44

def get_cache(blknum)
  seed = get_seed blknum

  if cache_by_seed.has_key?(seed)
    c = cache_by_seed.delete seed # pop
    cache_by_seed[seed] = c # and append at end
    return c
  end

  if c = cache_by_file(Utils.encode_hex(seed))
    cache_by_seed[seed] = c
    return c
  end

  # Use c++ implementation or ethash_ruby
  c = ::Ethash.mkcache_bytes blknum
  #c = EthashRuby::Cache.new(blknum).to_a

  cache_by_seed[seed] = c
  cache_by_file Utils.encode_hex(seed), c
  if cache_by_seed.size > CACHE_BY_SEED_MAX
    cache_by_seed.delete cache_by_seed.keys.first # remove last recently accessed
  end

  c
end

.get_seed(block_number) ⇒ Object



18
19
20
21
22
23
24
25
# File 'lib/ethereum/ethash.rb', line 18

def get_seed(block_number)
  epoch_no = block_number / EPOCH_LENGTH
  while seeds.size <= epoch_no
    seeds.push Ethereum::Utils.keccak256(seeds.last)
  end

  seeds[epoch_no]
end

.hashimoto_light(blknum, cache, mining_hash, bin_nonce) ⇒ Object



71
72
73
74
# File 'lib/ethereum/ethash.rb', line 71

def hashimoto_light(blknum, cache, mining_hash, bin_nonce)
  nonce = Utils.big_endian_to_int(bin_nonce)
  ::Ethash.hashimoto_light blknum, cache, mining_hash, nonce
end

.seedsObject



14
15
16
# File 'lib/ethereum/ethash.rb', line 14

def seeds
  @seeds ||= ["\x00"*32]
end