Class: Dcha::Block

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

Overview

:nodoc:

Constant Summary collapse

GENESIS =

rubocop:disable Metrics/LineLength

Block.new(index: 0, parent_hash: 0, time: 0, root_hash: "\0", proof: 'lvew')

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Block

Returns a new instance of Block.



6
7
8
9
10
# File 'lib/dcha/block.rb', line 6

def initialize(options = {})
  @time = Time.now.to_i
  @proof = ''
  options.each { |k, v| send("#{k}=", v) }
end

Instance Attribute Details

#hashObject

Returns the value of attribute hash.



4
5
6
# File 'lib/dcha/block.rb', line 4

def hash
  @hash
end

#indexObject

Returns the value of attribute index.



4
5
6
# File 'lib/dcha/block.rb', line 4

def index
  @index
end

#parent_hashObject

Returns the value of attribute parent_hash.



4
5
6
# File 'lib/dcha/block.rb', line 4

def parent_hash
  @parent_hash
end

#proofObject

Returns the value of attribute proof.



4
5
6
# File 'lib/dcha/block.rb', line 4

def proof
  @proof
end

#root_hashObject

Returns the value of attribute root_hash.



4
5
6
# File 'lib/dcha/block.rb', line 4

def root_hash
  @root_hash
end

#timeObject

Returns the value of attribute time.



4
5
6
# File 'lib/dcha/block.rb', line 4

def time
  @time
end

Instance Method Details

#bodyObject



18
19
20
# File 'lib/dcha/block.rb', line 18

def body
  [index, time, root_hash, parent_hash]
end

#make_proofObject



26
27
28
29
30
31
# File 'lib/dcha/block.rb', line 26

def make_proof
  @hash = Digest::SHA256.hexdigest(body.join)
  letters = ('a'..'z').to_a
  @proof << letters.sample until valid_proof?
  self
end

#valid_after?(previous_block) ⇒ Boolean

Returns:

  • (Boolean)


12
13
14
15
16
# File 'lib/dcha/block.rb', line 12

def valid_after?(previous_block)
  (previous_block.hash == parent_hash) &&
    (hash == Digest::SHA256.hexdigest(body.join)) &&
    valid_proof?
end

#valid_proof?Boolean

Returns:

  • (Boolean)


22
23
24
# File 'lib/dcha/block.rb', line 22

def valid_proof?
  Digest::SHA256.hexdigest((body + [proof]).join).start_with?('abc')
end