class Cryptoruby::Blockchain

Attributes

blocks[RW]
difficult[RW]
index[R]

Public Class Methods

new(difficult = 0) click to toggle source
# File lib/cryptoruby/blockchain.rb, line 9
def initialize(difficult = 0)
  @blocks     = []
  @index      = 0
  @difficult  = difficult
  generate_genesis_block
end

Public Instance Methods

<<(data) click to toggle source
# File lib/cryptoruby/blockchain.rb, line 21
def <<(data)
  add_block(data)
end
add_block(data) click to toggle source
# File lib/cryptoruby/blockchain.rb, line 16
def add_block(data)
  @index += 1
  @blocks << Block.new(index: index, previous_hash: last_block.hash, data: data, difficult: @difficult, blockchain: self)
end
export() click to toggle source
# File lib/cryptoruby/blockchain.rb, line 46
def export
  {
    difficult: difficult,
    blocks: blocks.map{ |block|
      {
        index: block.index,
        previous_hash: block.previous_hash,
        data: block.data,
        timestamp: block.timestamp,
        hash: block.hash,
        difficult: block.difficult,
        nonce: block.nonce
      }
    }
  }
end
is_valid?() click to toggle source
# File lib/cryptoruby/blockchain.rb, line 25
def is_valid?
  blocks[1..-1].sort_by{|block| block.index }.each_with_index do |current_block, index|
    previous_block = blocks[index]

    if current_block.hash != current_block.digest_hash
      p "Hash is different from digest on block of index #{index + 1}"
      return false
    end

    if current_block.index != previous_block.index + 1
      p 'Index is not sequential'
      return false
    end
    if current_block.previous_hash != previous_block.hash
      p 'Previous hash doesnt match with the current one'
      return false
    end
  end
  return true
end
last_block() click to toggle source
# File lib/cryptoruby/blockchain.rb, line 63
def last_block
  @blocks.last
end

Private Instance Methods

generate_genesis_block() click to toggle source
# File lib/cryptoruby/blockchain.rb, line 69
def generate_genesis_block
  @blocks << Block.new(index: 0, blockchain: self, difficult: @difficult)
end