Class: Cryptolakase::Blockchain

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeBlockchain

Returns a new instance of Blockchain.



9
10
11
12
13
14
15
# File 'lib/cryptolakase.rb', line 9

def initialize()
  @chain = []
  @current_transactions = []

  #generate genesis block
  new_block(100,1)
end

Instance Attribute Details

#chainObject (readonly)

Returns the value of attribute chain.



7
8
9
# File 'lib/cryptolakase.rb', line 7

def chain
  @chain
end

Class Method Details

.hash(block) ⇒ Object



63
64
65
66
67
68
# File 'lib/cryptolakase.rb', line 63

def self.hash(block)
  # return SHA256 for the given block
  block_string = block.to_json

  Digest::SHA256.hexdigest(block_string)
end

.valid_proof(last_proof, proof) ⇒ Object



70
71
72
73
74
75
76
# File 'lib/cryptolakase.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

Instance Method Details

#hash(block) ⇒ Object



59
60
61
# File 'lib/cryptolakase.rb', line 59

def hash(block)
  Blockchain.hash(block)
end

#last_blockObject



43
44
45
# File 'lib/cryptolakase.rb', line 43

def last_block
  @chain[-1]
end

#new_block(proof, previous_hash) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/cryptolakase.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, recipient, amount) ⇒ Object



33
34
35
36
37
38
39
40
41
# File 'lib/cryptolakase.rb', line 33

def new_transaction(sender, recipient, amount)
  @current_transactions.push({
    :sender => sender,
    :recipient => recipient,
    :amount => amount
  })

  @chain.index(last_block)
end

#proof_of_work(last_proof) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
# File 'lib/cryptolakase.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
  # gdfsdfsd..0000

  proof = 0
  while !Blockchain.valid_proof(last_proof, proof) do
    proof += 1
  end

  proof
end