class Bitcoin::BlockHeader

Block Header

Attributes

bits[RW]
merkle_root[RW]
nonce[RW]
prev_hash[RW]
time[RW]
version[RW]

Public Class Methods

new(version, prev_hash, merkle_root, time, bits, nonce) click to toggle source
# File lib/bitcoin/block_header.rb, line 15
def initialize(version, prev_hash, merkle_root, time, bits, nonce)
  @version = version
  @prev_hash = prev_hash
  @merkle_root = merkle_root
  @time = time
  @bits = bits
  @nonce = nonce
end
parse_from_payload(payload) click to toggle source
# File lib/bitcoin/block_header.rb, line 24
def self.parse_from_payload(payload)
  version, prev_hash, merkle_root, time, bits, nonce = payload.unpack('Va32a32VVV')
  new(version, prev_hash.bth, merkle_root.bth, time, bits, nonce)
end

Public Instance Methods

==(other) click to toggle source
# File lib/bitcoin/block_header.rb, line 78
def ==(other)
  other && other.to_payload == to_payload
end
block_hash() click to toggle source
# File lib/bitcoin/block_header.rb, line 45
def block_hash
  calc_hash
end
block_id() click to toggle source

block hash(big endian)

# File lib/bitcoin/block_header.rb, line 50
def block_id
  block_hash.rhex
end
difficulty_target() click to toggle source

compute difficulty target from bits.

# File lib/bitcoin/block_header.rb, line 34
def difficulty_target
  exponent = ((bits >> 24) & 0xff)
  mantissa = bits & 0x7fffff
  mantissa *= -1 if (bits & 0x800000) > 0
  (mantissa * 2 ** (8 * (exponent - 3)))
end
hash() click to toggle source
# File lib/bitcoin/block_header.rb, line 41
def hash
  calc_hash.to_i(16)
end
to_payload() click to toggle source
# File lib/bitcoin/block_header.rb, line 29
def to_payload
  [version, prev_hash.htb, merkle_root.htb, time, bits, nonce].pack('Va32a32VVV')
end
valid?() click to toggle source

evaluate block header

# File lib/bitcoin/block_header.rb, line 55
def valid?
  valid_pow? && valid_timestamp?
end
valid_pow?() click to toggle source

evaluate valid proof of work.

# File lib/bitcoin/block_header.rb, line 60
def valid_pow?
  block_id.hex < difficulty_target
end
valid_timestamp?() click to toggle source

evaluate valid timestamp. en.bitcoin.it/wiki/Block_timestamp

# File lib/bitcoin/block_header.rb, line 66
def valid_timestamp?
  time <= Time.now.to_i + Bitcoin::MAX_FUTURE_BLOCK_TIME
end
work() click to toggle source

compute chain work of this block. @return [Integer] a chain work.

# File lib/bitcoin/block_header.rb, line 72
def work
  target = difficulty_target
  return 0 if target < 1
  115792089237316195423570985008687907853269984665640564039457584007913129639936.div(target + 1) # 115792089237316195423570985008687907853269984665640564039457584007913129639936 is 2**256
end

Private Instance Methods

calc_hash() click to toggle source
# File lib/bitcoin/block_header.rb, line 84
def calc_hash
  Bitcoin.double_sha256(to_payload).bth
end