Class: Dcha::Chain
- Inherits:
-
Object
- Object
- Dcha::Chain
- Defined in:
- lib/dcha/chain.rb
Overview
:nodoc:
Instance Attribute Summary collapse
-
#blocks ⇒ Object
readonly
Returns the value of attribute blocks.
Instance Method Summary collapse
- #add_block(block) ⇒ Object
- #create_and_add_block(root_hash) ⇒ Object
-
#initialize ⇒ Chain
constructor
A new instance of Chain.
- #replace_with(new_blocks) ⇒ Object
- #valid_chain?(blocks = @blocks) ⇒ Boolean
Constructor Details
#initialize ⇒ Chain
Returns a new instance of Chain.
6 7 8 |
# File 'lib/dcha/chain.rb', line 6 def initialize @blocks = [Block::GENESIS] end |
Instance Attribute Details
#blocks ⇒ Object (readonly)
Returns the value of attribute blocks.
4 5 6 |
# File 'lib/dcha/chain.rb', line 4 def blocks @blocks end |
Instance Method Details
#add_block(block) ⇒ Object
10 11 12 13 14 15 16 17 18 19 |
# File 'lib/dcha/chain.rb', line 10 def add_block(block) blocks << block if block.valid_after?(blocks.last) unless valid_chain? @blocks = @blocks[0..-2] return false end true end |
#create_and_add_block(root_hash) ⇒ Object
21 22 23 24 25 26 27 |
# File 'lib/dcha/chain.rb', line 21 def create_and_add_block(root_hash) add_block(Block.new( index: blocks.last.index + 1, parent_hash: blocks.last.hash, root_hash: root_hash ).make_proof) end |
#replace_with(new_blocks) ⇒ Object
29 30 31 32 33 34 35 |
# File 'lib/dcha/chain.rb', line 29 def replace_with(new_blocks) new_blocks = [Block::GENESIS] + new_blocks return unless valid_chain?(new_blocks) && new_blocks.length > blocks.length @blocks = new_blocks true end |
#valid_chain?(blocks = @blocks) ⇒ Boolean
37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/dcha/chain.rb', line 37 def valid_chain?(blocks = @blocks) valid = true blocks.each.with_index(0) do |block, idx| valid &&= if idx.zero? Oj.dump(block) == Oj.dump(Block::GENESIS) else block.valid_after?(blocks[idx - 1]) end end valid end |