Class: Blockchain

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/centralbank/blockchain.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(chain = []) ⇒ Blockchain

Returns a new instance of Blockchain.



9
10
11
# File 'lib/centralbank/blockchain.rb', line 9

def initialize( chain=[] )
  @chain = chain
end

Class Method Details

.from_json(data) ⇒ Object



40
41
42
43
44
# File 'lib/centralbank/blockchain.rb', line 40

def self.from_json( data )
  ## note: assumes data is an array of block records/objects in json
  chain = data.map { |h| Block.from_h( h ) }
  self.new( chain )
end

Instance Method Details

#<<(txs) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/centralbank/blockchain.rb', line 13

def <<( txs )
  ## todo: check if is block or array
  ##   if array (of transactions) - auto-add (build) block
  ##   allow block - why? why not?
  ##  for now just use transactions (keep it simple :-)

  if @chain.size == 0
    block = Block.first( txs )
  else
    block = Block.next( @chain.last, txs )
  end
  @chain << block
end

#as_jsonObject



29
30
31
# File 'lib/centralbank/blockchain.rb', line 29

def as_json
  @chain.map { |block| block.to_h }
end

#transactionsObject



33
34
35
36
# File 'lib/centralbank/blockchain.rb', line 33

def transactions
  ## "accumulate" get all transactions from all blocks "reduced" into a single array
  @chain.reduce( [] ) { |acc, block| acc + block.transactions }
end