Module: Nano::Work

Extended by:
Work
Included in:
Work
Defined in:
lib/nano/work.rb

Overview

This module is responsible for generating and validating the proof of work for a block hash

Constant Summary collapse

MAX_NONCE =

The maximum value a nonce can be

0xffffffffffffffff
WORK_THRESHOLD =

The minimum threshold a proof of work needs to meet to be valid.

Integer(0xffffffc000000000)

Instance Method Summary collapse

Instance Method Details

#compute_work(hash) ⇒ String

Compute the proof of work for the hash.

Parameters:

  • hash (String)

    the previous block hash to compute the work for.

Returns:

  • (String)

    the computed work as an 8 byte hex string.



25
26
27
# File 'lib/nano/work.rb', line 25

def compute_work(hash)
  NanocurrencyExt.compute_work(hash)
end

#is_work_valid?(hash, work) ⇒ Boolean

Checks if a proof of work is valid for the hash

Parameters:

  • hash (String)

    The block hash the work was calculated for.

  • work (String)

    The block work that was calculated for the hash.

Returns:

  • (Boolean)

    true if the work is valid and fits for the block hash.



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/nano/work.rb', line 34

def is_work_valid?(hash, work)
  hash_valid = Nano::Check.is_hash_valid?(hash)
  work_valid = Nano::Check.is_work_valid?(work)
  throw ArgumentError, "Invalid block hash" unless hash_valid
  throw ArgumentError, "Invalid work" unless work_valid

  hash_bin = Nano::Utils.hex_to_bin(hash)
  work_bin = Nano::Utils.hex_to_bin(work).reverse

  input = work_bin + hash_bin
  output_hex = Nano::Utils.bytes_to_hex(
    Blake2b.bytes(input, Blake2b::Key.none, 8).reverse
  )

  output_hex.to_i(16) >= WORK_THRESHOLD
end