class JoseCryptodemo::Blockchain

Attributes

chain[R]

Public Class Methods

hash(block) click to toggle source
# File lib/jose_cryptodemo.rb, line 63
def self.hash(block)
  block_string = block.to_json
  
  # return SHA256 for the given block
  Digest::SHA256.hexdigest(block_string)
end
new() click to toggle source
# File lib/jose_cryptodemo.rb, line 9
def initialize()
  @chain = []
  @current_transactions = []
  
  # generate genesis block
  new_block(100, 1)
end
valid_proof(last_proof, proof) click to toggle source
# File lib/jose_cryptodemo.rb, line 70
def self.valid_proof(last_proof, proof)
  # return true if the resulting hash has 4 leading zeros
  guess = "#{last_proof}#{proof}"
  guess_hash = Digest::SHA256.hexdigest(guess)
  
  guess_hash.to_s[-4..-1] == '0000'
end

Public Instance Methods

hash(block) click to toggle source
# File lib/jose_cryptodemo.rb, line 59
def hash(block)
  Blockchain.hash(block)
end
last_block() click to toggle source
# File lib/jose_cryptodemo.rb, line 43
def last_block
  @chain[-1]
end
new_block(proof, previous_hash) click to toggle source
# File lib/jose_cryptodemo.rb, line 17
def new_block(proof, previous_hash)
  block = {
    :index => @chain.count + 1,
    :timestamp => Time.now.to_i,
    :transactions => @current_transactions,
    :proof => proof,
    :previous_hash => previous_hash ||= self.hash(@chain[-1])
  }
  
  @current_transactions = []
  
  @chain.push(block)
  
  block
end
new_transaction(sender, recipent, amount) click to toggle source
# File lib/jose_cryptodemo.rb, line 33
def new_transaction(sender, recipent, amount)
  @current_transactions.push({
    :sender => sender,
    :recipent => recipent,
    :amount => amount
  })
  
  @chain.index(last_block)
end
proof_of_work(last_proof) click to toggle source
# File lib/jose_cryptodemo.rb, line 47
def proof_of_work(last_proof)
  # calculates a number that concatenated to the last_proof will return a hash with 4 leading zeros
  # efc26373838..0000
  
  proof = 0
  while !Blockchain.valid_proof(last_proof, proof) do
    proof += 1
  end
  
  proof
end