Class: Rubychain::Chain

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

Defined Under Namespace

Classes: InvalidBlockError

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeChain

Initialize a new blockchain by creating a new array with the Genesis block



10
11
12
# File 'lib/rubychain/chain.rb', line 10

def initialize
  @blockchain = [create_genesis_block]
end

Instance Attribute Details

#blockchainObject (readonly)

Returns the value of attribute blockchain.



4
5
6
# File 'lib/rubychain/chain.rb', line 4

def blockchain
  @blockchain
end

Instance Method Details

#add_next_block(prev_block, data) ⇒ Object

#add_next_block => Adds a new block to the blockchain with the given data it will raise an error if the previous_block hash does not match the last_block in our blockchain



17
18
19
20
21
22
23
# File 'lib/rubychain/chain.rb', line 17

def add_next_block(prev_block, data)
  if valid_block?(prev_block)
    blockchain << next_block(data)
  else
    raise InvalidBlockError
  end
end

#find_block(hash) ⇒ Object

#find_block(hash) => Returns a block from the blockchain with the given hash



39
40
41
# File 'lib/rubychain/chain.rb', line 39

def find_block(hash)
  blockchain.select{|block| block if block.hash == hash}.first
end

#genesis_blockObject

#genesis_block => Returns the Genesis block



27
28
29
# File 'lib/rubychain/chain.rb', line 27

def genesis_block
  blockchain.first
end

#last_blockObject

#last_block => Returns the last block that was added to the blockchain



33
34
35
# File 'lib/rubychain/chain.rb', line 33

def last_block
  blockchain.last
end