Class: Blockchain

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/tulipmania/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/tulipmania/blockchain.rb', line 9

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

Class Method Details

.from_json(data) ⇒ Object



49
50
51
52
53
# File 'lib/tulipmania/blockchain.rb', line 49

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



22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/tulipmania/blockchain.rb', line 22

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, timestamp: timestamp1637 )
  else
    block = Block.next( @chain.last, txs, timestamp: timestamp1637 )
  end
  @chain << block
end

#as_jsonObject



38
39
40
# File 'lib/tulipmania/blockchain.rb', line 38

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

#timestamp1637Object



13
14
15
16
17
18
19
20
# File 'lib/tulipmania/blockchain.rb', line 13

def timestamp1637
  ## change year to 1637 :-)
  ##   note: time (uses signed integer e.g. epoch/unix time starting in 1970 with 0)
  ##  todo: add nano/mili-seconds - why? why not? possible?
  now = Time.now.utc.to_datetime
  past = DateTime.new( 1637, now.month, now.mday, now.hour, now.min, now.sec, now.zone )
  past
end

#transactionsObject



42
43
44
45
# File 'lib/tulipmania/blockchain.rb', line 42

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