Module: Ethereum::EthashRuby::Utils

Included in:
Cache, Hashimoto
Defined in:
lib/ethereum/ethash_ruby/utils.rb

Instance Method Summary collapse

Instance Method Details

#decode_int(s) ⇒ Object

Assumes little endian bit ordering (same as Intel architectures)



43
44
45
# File 'lib/ethereum/ethash_ruby/utils.rb', line 43

def decode_int(s)
  s && !s.empty? ? s.unpack('L<').first : 0
end

#deserialize_hash(h) ⇒ Object



30
31
32
33
34
35
# File 'lib/ethereum/ethash_ruby/utils.rb', line 30

def deserialize_hash(h)
  (h.size / WORD_BYTES).times.map do |i|
    i *= WORD_BYTES
    decode_int h[i, WORD_BYTES]
  end
end

#encode_int(i) ⇒ Object



37
38
39
40
# File 'lib/ethereum/ethash_ruby/utils.rb', line 37

def encode_int(i)
  # `pack('L<`) will introduce leading zeros
  Ethereum::Utils.int_to_big_endian(i).reverse
end

#hash_words(x, &block) ⇒ Object



20
21
22
23
24
# File 'lib/ethereum/ethash_ruby/utils.rb', line 20

def hash_words(x, &block)
  x = serialize_hash(x) if x.instance_of?(Array)
  y = block.call(x)
  deserialize_hash(y)
end

#keccak256(x) ⇒ Object



14
15
16
17
18
# File 'lib/ethereum/ethash_ruby/utils.rb', line 14

def keccak256(x)
  hash_words(x) do |v|
    Ethereum::Utils.keccak256(v)
  end
end

#keccak512(x) ⇒ Object

sha3 hash function, outputs 64 bytes



8
9
10
11
12
# File 'lib/ethereum/ethash_ruby/utils.rb', line 8

def keccak512(x)
  hash_words(x) do |v|
    Ethereum::Utils.keccak512(v)
  end
end

#serialize_hash(h) ⇒ Object



26
27
28
# File 'lib/ethereum/ethash_ruby/utils.rb', line 26

def serialize_hash(h)
  h.map {|x| zpad(encode_int(x), WORD_BYTES) }.join
end

#zpad(s, len) ⇒ Object



47
48
49
# File 'lib/ethereum/ethash_ruby/utils.rb', line 47

def zpad(s, len)
  s + "\x00" * [0, len - s.size].max
end