Class: ProofOfWork

Inherits:
Object
  • Object
show all
Defined in:
lib/proof_of_work.rb

Constant Summary collapse

VERSION =
1

Class Method Summary collapse

Class Method Details

.generate(identifier, options = {}) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/proof_of_work.rb', line 7

def generate(identifier, options = {})
  options[:now]           ||= Time.now
  options[:bits]          ||= 20
  options[:extension]     ||= ""
  options[:salt_chars]    ||= 8
  options[:stamp_seconds] ||= false

  timestamp = if !!options[:stamp_seconds]
                options[:now].strftime("%y%m%d%H%M%S")
              else
                options[:now].strftime("%y%m%d")
              end

  challenge = "%s:" * 6 % [
    VERSION,
    options[:bits],
    timestamp,
    identifier,
    options[:extension],
    salt(options[:salt_chars])
  ]

  challenge + hashcash(challenge, options[:bits])
end

.valid?(stamp, options = {}) {|extension| ... } ⇒ Boolean

Yields:

  • (extension)

Returns:

  • (Boolean)


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/proof_of_work.rb', line 32

def valid?(stamp, options = {})
  _, bits_claim, date, identifier, extension, rand, counter = stamp.split(":")

  return false if options[:identifier] && options[:identifier] != identifier
  return false if options[:bits] && options[:bits].to_i > bits_claim.to_i

  if options[:expiration_date]
    return false if date < options[:expiration_date].strftime("%y%m%d%H%M%S")
  end

  hex_digits = (bits_claim.to_i/4.0).floor.to_i

  sha1 = OpenSSL::Digest::SHA1.new
  sha1 << stamp

  is_valid = sha1.hexdigest.start_with?("0" * hex_digits)
  yield(extension) if block_given?

  is_valid
end