class Rubychain::Chain
Attributes
blockchain[R]
Public Class Methods
new()
click to toggle source
Initialize a new blockchain by creating a new array with the Genesis block
# File lib/rubychain/chain.rb, line 10 def initialize @blockchain = [create_genesis_block] end
Public Instance Methods
add_next_block(prev_block, data)
click to toggle source
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
# 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)
click to toggle source
find_block
(hash) => Returns a block from the blockchain with the given hash
# File lib/rubychain/chain.rb, line 39 def find_block(hash) blockchain.select{|block| block if block.hash == hash}.first end
genesis_block()
click to toggle source
genesis_block
=> Returns the Genesis block
# File lib/rubychain/chain.rb, line 27 def genesis_block blockchain.first end
last_block()
click to toggle source
last_block
=> Returns the last block that was added to the blockchain
# File lib/rubychain/chain.rb, line 33 def last_block blockchain.last end
Private Instance Methods
create_genesis_block()
click to toggle source
# File lib/rubychain/chain.rb, line 56 def create_genesis_block() Block.new(0, Time.now, "Genesis Block", 0) end
next_block(data)
click to toggle source
# File lib/rubychain/chain.rb, line 49 def next_block(data) index = last_block.index + 1 timestamp = Time.now hash = last_block.hash Block.new(index, timestamp, data, hash) end
valid_block?(prev_block)
click to toggle source
# File lib/rubychain/chain.rb, line 45 def valid_block?(prev_block) prev_block.hash == last_block.hash end