Class: TokenChain::Receiver

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

Instance Method Summary collapse

Instance Method Details

#initialize_chain(anchor) ⇒ Object



8
9
10
11
12
13
# File 'lib/token_chain/receiver.rb', line 8

def initialize_chain(anchor)
  @generator = Generator.new anchor
  @generator.generate(10).each_with_index do |token, i|
    ReceivableToken.create token, anchor: anchor, sequence: i
  end
end

#validate!(token) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/token_chain/receiver.rb', line 15

def validate!(token)
  receivable = ReceivableToken.find(token)

  if receivable.nil?
    raise UnknownTokenError.new("Invalid token")
  elsif ! receivable.available?
    raise InvalidTokenError.new("Token was previously submitted")
  else # it's a valid, available token
    response = { result: 'success' }

    anchor = receivable.anchor
    incoming_token_seq = receivable.sequence

    if incoming_token_seq > 0
      response[:warning] = 'Token submitted out of sequence.'
    end

    # resequence and prune
    ReceivableToken.where(anchor: anchor).each do |rt|
      old_sequence = rt.sequence
      new_sequence = old_sequence - (incoming_token_seq + 1)
      rt.sequence = new_sequence
      if rt.sequence >= -10
        rt.save
      else
        rt.delete
      end
    end

    # replentish tokens
    first_new_token_seq = 9 - incoming_token_seq
    (first_new_token_seq..9).each do |sequence|
      ReceivableToken.create @generator.generate,
        anchor: anchor,
        sequence: sequence
    end

    return response
  end
end