Class: Cryptoruby::Blockchain
- Inherits:
-
Object
- Object
- Cryptoruby::Blockchain
- Defined in:
- lib/cryptoruby/block.rb,
lib/cryptoruby/blockchain.rb
Defined Under Namespace
Classes: Block
Instance Attribute Summary collapse
-
#blocks ⇒ Object
Returns the value of attribute blocks.
-
#difficult ⇒ Object
Returns the value of attribute difficult.
-
#index ⇒ Object
readonly
Returns the value of attribute index.
Instance Method Summary collapse
- #<<(data) ⇒ Object
- #add_block(data) ⇒ Object
- #export ⇒ Object
-
#initialize(difficult = 0) ⇒ Blockchain
constructor
A new instance of Blockchain.
- #is_valid? ⇒ Boolean
- #last_block ⇒ Object
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
#blocks ⇒ Object
Returns the value of attribute blocks.
6 7 8 |
# File 'lib/cryptoruby/blockchain.rb', line 6 def blocks @blocks end |
#difficult ⇒ Object
Returns the value of attribute difficult.
6 7 8 |
# File 'lib/cryptoruby/blockchain.rb', line 6 def difficult @difficult end |
#index ⇒ Object (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 |
#export ⇒ Object
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., hash: block.hash, difficult: block.difficult, nonce: block.nonce } } } end |
#is_valid? ⇒ 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_block ⇒ Object
63 64 65 |
# File 'lib/cryptoruby/blockchain.rb', line 63 def last_block @blocks.last end |