Class: Bitcoin::Builder::BlockBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/bitcoin/builder.rb

Overview

DSL to create a Bitcoin::Protocol::Block used by Builder#create_block.

block = blk("00".ljust(32, 'f')) do |b|
  b.prev_block "\x00"*32
  b.tx do |t|
    t.input {|i| i.coinbase }
    t.output do |o|
      o.value 5000000000;
      o.to Bitcoin::Key.generate.addr
    end
  end
end

See Bitcoin::Builder::TxBuilder for details on building transactions.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeBlockBuilder

Returns a new instance of BlockBuilder.



48
49
50
# File 'lib/bitcoin/builder.rb', line 48

def initialize
  @block = P::Block.new(nil)
end

Instance Attribute Details

#prev_block(hash) ⇒ Object

set the hash of the previous block.



58
59
60
# File 'lib/bitcoin/builder.rb', line 58

def prev_block(hash) # rubocop:disable Style/TrivialAccessors
  @prev_block = hash
end

#time(time) ⇒ Object

set the block timestamp (defaults to current time).



63
64
65
# File 'lib/bitcoin/builder.rb', line 63

def time(time) # rubocop:disable Style/TrivialAccessors
  @time = time
end

#version(v) ⇒ Object

specify block version. this is usually not necessary. defaults to 1.



53
54
55
# File 'lib/bitcoin/builder.rb', line 53

def version(v) # rubocop:disable Style/TrivialAccessors
  @version = v
end

Instance Method Details

#block(target) ⇒ Object

create the block according to values specified via DSL.



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/bitcoin/builder.rb', line 79

def block(target)
  @version ||= nil
  @mrkl_root ||= nil
  @time ||= nil

  @block.ver = @version || 1
  @block.prev_block = @prev_block.htb.reverse
  @block.mrkl_root = @mrkl_root
  @block.time = @time || Time.now.to_i
  @block.nonce = 0
  @block.mrkl_root = Bitcoin.hash_mrkl_tree(@block.tx.map(&:hash)).last.htb.reverse
  find_hash(target)
  block = P::Block.new(@block.to_payload)
  raise 'Payload Error' unless block.to_payload == @block.to_payload
  block
end

#tx(tx = nil) ⇒ Object

add transactions to the block (see TxBuilder).



68
69
70
71
72
73
74
75
76
# File 'lib/bitcoin/builder.rb', line 68

def tx(tx = nil)
  tx ||= begin
    c = TxBuilder.new
    yield c
    c.tx
  end
  @block.tx << tx
  tx
end