Class: Node

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(address:) ⇒ Node

Returns a new instance of Node.



6
7
8
9
10
11
# File 'lib/centralbank/node.rb', line 6

def initialize( address: )
  @id     = SecureRandom.uuid
  @peers  = []
  @wallet = Wallet.new( address )
  @bank   = Bank.new @wallet.address
end

Instance Attribute Details

#bankObject (readonly)

Returns the value of attribute bank.



4
5
6
# File 'lib/centralbank/node.rb', line 4

def bank
  @bank
end

#idObject (readonly)

Returns the value of attribute id.



4
5
6
# File 'lib/centralbank/node.rb', line 4

def id
  @id
end

#peersObject (readonly)

Returns the value of attribute peers.



4
5
6
# File 'lib/centralbank/node.rb', line 4

def peers
  @peers
end

#walletObject (readonly)

Returns the value of attribute wallet.



4
5
6
# File 'lib/centralbank/node.rb', line 4

def wallet
  @wallet
end

Instance Method Details

#on_add_peer(host, port) ⇒ Object



15
16
17
18
19
20
21
# File 'lib/centralbank/node.rb', line 15

def on_add_peer( host, port )
  @peers << [host, port]
  @peers.uniq!
  # TODO/FIX: no need to send to every peer, just the new one
  send_chain_to_peers
  @bank.pending.each { |tx| send_transaction_to_peers( tx ) }
end

#on_add_transaction(from, to, amount, id) ⇒ Object



28
29
30
31
32
33
34
35
36
37
# File 'lib/centralbank/node.rb', line 28

def on_add_transaction( from, to, amount, id )
  ## note: for now must always pass in id - why? why not? possible tx without id???
  tx = Tx.new( from, to, amount, id )
  if @bank.sufficient_funds?( tx.from, tx.amount ) && @bank.add_transaction( tx )
    send_transaction_to_peers( tx )
    return true
  else
    return false
  end
end

#on_delete_peer(index) ⇒ Object



23
24
25
# File 'lib/centralbank/node.rb', line 23

def on_delete_peer( index )
  @peers.delete_at( index )
end

#on_mine!Object



50
51
52
53
# File 'lib/centralbank/node.rb', line 50

def on_mine!
  @bank.mine_block!
  send_chain_to_peers
end

#on_resolve(data) ⇒ Object



55
56
57
58
59
60
61
62
63
# File 'lib/centralbank/node.rb', line 55

def on_resolve( data )
  chain_new = Blockchain.from_json( data )
  if @bank.resolve!( chain_new )
    send_chain_to_peers
    return true
  else
    return false
  end
end

#on_send(to, amount) ⇒ Object



39
40
41
42
43
44
45
46
47
# File 'lib/centralbank/node.rb', line 39

def on_send( to, amount )
  tx = @wallet.generate_transaction( to, amount )
  if @bank.sufficient_funds?( tx.from, tx.amount ) && @bank.add_transaction( tx )
    send_transaction_to_peers( tx )
    return true
  else
    return false
  end
end