Class: Cryptocol::Blockchain
- Inherits:
-
Object
- Object
- Cryptocol::Blockchain
- Defined in:
- lib/cryptocol.rb
Class Method Summary collapse
Instance Method Summary collapse
- #hash(block) ⇒ Object
-
#initialize ⇒ Blockchain
constructor
A new instance of Blockchain.
- #last_block ⇒ Object
- #new_block(proof, previousHash) ⇒ Object
- #new_transaction(sender, recipient, amount) ⇒ Object
- #proof_of_work(last_proof) ⇒ Object
Constructor Details
#initialize ⇒ Blockchain
Returns a new instance of Blockchain.
6 7 8 9 10 11 |
# File 'lib/cryptocol.rb', line 6 def initialize() @chain = [] @current_transactions = [] # creating the genesis block new_block(100, 1) end |
Class Method Details
.hash(block) ⇒ Object
58 59 60 61 |
# File 'lib/cryptocol.rb', line 58 def self.hash(block) block_string = block.to_json Digest::SHA256.hexdigest block_string end |
.valid_proof(last_proof, proof) ⇒ Object
63 64 65 66 67 68 |
# File 'lib/cryptocol.rb', line 63 def self.valid_proof(last_proof, proof) guess = "#{last_proof}#{proof}" guess_hash = Digest::SHA256.hexdigest guess guess_hash.to_s[-4..-1] == '0000' end |
Instance Method Details
#hash(block) ⇒ Object
54 55 56 |
# File 'lib/cryptocol.rb', line 54 def hash(block) Blockchain.hash(block) end |
#last_block ⇒ Object
50 51 52 |
# File 'lib/cryptocol.rb', line 50 def last_block @chain[-1] end |
#new_block(proof, previousHash) ⇒ Object
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
# File 'lib/cryptocol.rb', line 13 def new_block(proof, previousHash) block = { :index => @chain.count + 1, :timestamp => Time.now.to_i, :transactions => @current_transactions, :proof => proof, :previous_hash => previousHash ||= self.hash(@chain[-1]) } # Reset the current transactions @transactions = [] @chain.push(block) block end |
#new_transaction(sender, recipient, amount) ⇒ Object
39 40 41 42 43 44 45 46 47 48 |
# File 'lib/cryptocol.rb', line 39 def new_transaction(sender, recipient, amount) @current_transactions.push({ :sender => sender, :recipient => recipient, :amount => amount }) # return the index where the transaction will be added to @chain.index last_block end |
#proof_of_work(last_proof) ⇒ Object
30 31 32 33 34 35 36 37 |
# File 'lib/cryptocol.rb', line 30 def proof_of_work(last_proof) proof = 0 while !Blockchain.valid_proof(last_proof, proof) do proof += 1 end proof end |