Class: Cryptoruby::Blockchain

Inherits:
Object
  • Object
show all
Defined in:
lib/cryptoruby/block.rb,
lib/cryptoruby/blockchain.rb

Defined Under Namespace

Classes: Block

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(difficult = 0) ⇒ Blockchain

Returns a new instance of Blockchain.



9
10
11
12
13
14
# File 'lib/cryptoruby/blockchain.rb', line 9

def initialize(difficult = 0)
  @blocks     = []
  @index      = 0
  @difficult  = difficult
  generate_genesis_block
end

Instance Attribute Details

#blocksObject

Returns the value of attribute blocks.



6
7
8
# File 'lib/cryptoruby/blockchain.rb', line 6

def blocks
  @blocks
end

#difficultObject

Returns the value of attribute difficult.



6
7
8
# File 'lib/cryptoruby/blockchain.rb', line 6

def difficult
  @difficult
end

#indexObject (readonly)

Returns the value of attribute index.



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

def index
  @index
end

Instance Method Details

#<<(data) ⇒ Object



21
22
23
# File 'lib/cryptoruby/blockchain.rb', line 21

def <<(data)
  add_block(data)
end

#add_block(data) ⇒ Object



16
17
18
19
# 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

#exportObject



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# 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?Boolean

Returns:

  • (Boolean)


25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# 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_blockObject



63
64
65
# File 'lib/cryptoruby/blockchain.rb', line 63

def last_block
  @blocks.last
end