class KeyValueChain::DriveKVChain

Public Class Methods

new(path) click to toggle source
# File lib/key_value_chain.rb, line 51
def initialize(path)
  @path = path
  @last_block_hash = "0000000000000000000000000000000000000000"
  self[""]
end

Public Instance Methods

[](key) click to toggle source
# File lib/key_value_chain.rb, line 56
def [](key)
  prev = "0000000000000000000000000000000000000000"
  value = ""
  File.open(@path, "a+") do |f|
    f.each_line do |line|
      h = JSON.parse(line)
      raise "Broken Blockchain, invalid hashes" unless h["prevBlock"] == prev
      prev = Digest::SHA1.hexdigest line.chomp
      raise "Broken Blockchain, invalid nonce" unless prev[0,4] == "0000"
      value = h["value"] if h["key"] == key
    end
  end
  @last_block_hash = prev
  value
end
[]=(key,value) click to toggle source
# File lib/key_value_chain.rb, line 72
def []=(key,value)
  pair = KVPair.new(@last_block_hash, key, value)
  open(@path, 'a') { |f|
    f.puts pair.to_json
  }
  @last_block_hash = pair.to_hash
end