Class: Bitcoin::Tx

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

Overview

Transaction class

Constant Summary collapse

MAX_STANDARD_VERSION =
2
MAX_STANDARD_TX_WEIGHT =

The maximum weight for transactions we’re willing to relay/mine

400000
MARKER =
0x00
FLAG =
0x01

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeTx

Returns a new instance of Tx.



24
25
26
27
28
29
# File 'lib/bitcoin/tx.rb', line 24

def initialize
  @inputs = []
  @outputs = []
  @version = 1
  @lock_time = 0
end

Instance Attribute Details

#flagObject

Returns the value of attribute flag.



19
20
21
# File 'lib/bitcoin/tx.rb', line 19

def flag
  @flag
end

#inputsObject (readonly) Also known as: in

Returns the value of attribute inputs.



20
21
22
# File 'lib/bitcoin/tx.rb', line 20

def inputs
  @inputs
end

#lock_timeObject

Returns the value of attribute lock_time.



22
23
24
# File 'lib/bitcoin/tx.rb', line 22

def lock_time
  @lock_time
end

#markerObject

Returns the value of attribute marker.



18
19
20
# File 'lib/bitcoin/tx.rb', line 18

def marker
  @marker
end

#outputsObject (readonly) Also known as: out

Returns the value of attribute outputs.



21
22
23
# File 'lib/bitcoin/tx.rb', line 21

def outputs
  @outputs
end

#versionObject

Returns the value of attribute version.



17
18
19
# File 'lib/bitcoin/tx.rb', line 17

def version
  @version
end

Class Method Details

.parse_from_payload(payload, non_witness: false) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/bitcoin/tx.rb', line 34

def self.parse_from_payload(payload, non_witness: false)
  buf = payload.is_a?(String) ? StringIO.new(payload) : payload
  tx = new
  tx.version = buf.read(4).unpack('V').first

  in_count = Bitcoin.unpack_var_int_from_io(buf)
  witness = false
  if in_count.zero? && !non_witness
    tx.marker = 0
    tx.flag = buf.read(1).unpack('c').first
    if tx.flag.zero?
      buf.pos -= 1
    else
      in_count = Bitcoin.unpack_var_int_from_io(buf)
      witness = true
    end
  end

  in_count.times do
    tx.inputs << TxIn.parse_from_payload(buf)
  end

  out_count = Bitcoin.unpack_var_int_from_io(buf)
  out_count.times do
    tx.outputs << TxOut.parse_from_payload(buf)
  end

  if witness
    in_count.times do |i|
      tx.inputs[i].script_witness = Bitcoin::ScriptWitness.parse_from_payload(buf)
    end
  end

  tx.lock_time = buf.read(4).unpack('V').first

  tx
end

Instance Method Details

#==(other) ⇒ Object



121
122
123
# File 'lib/bitcoin/tx.rb', line 121

def ==(other)
  to_payload == other.to_payload
end

#coinbase_tx?Boolean

Returns:

  • (Boolean)


113
114
115
# File 'lib/bitcoin/tx.rb', line 113

def coinbase_tx?
  inputs.length == 1 && inputs.first.coinbase?
end

#hashObject



72
73
74
# File 'lib/bitcoin/tx.rb', line 72

def hash
  to_payload.bth.to_i(16)
end

#serialize_old_formatObject

serialize tx with old tx format



126
127
128
129
130
131
132
# File 'lib/bitcoin/tx.rb', line 126

def serialize_old_format
  buf = [version].pack('V')
  buf << Bitcoin.pack_var_int(inputs.length) << inputs.map(&:to_payload).join
  buf << Bitcoin.pack_var_int(outputs.length) << outputs.map(&:to_payload).join
  buf << [lock_time].pack('V')
  buf
end

#serialize_witness_formatObject

serialize tx with segwit tx format github.com/bitcoin/bips/blob/master/bip-0144.mediawiki



136
137
138
139
140
141
142
# File 'lib/bitcoin/tx.rb', line 136

def serialize_witness_format
  buf = [version, MARKER, FLAG].pack('Vcc')
  buf << Bitcoin.pack_var_int(inputs.length) << inputs.map(&:to_payload).join
  buf << Bitcoin.pack_var_int(outputs.length) << outputs.map(&:to_payload).join
  buf << witness_payload << [lock_time].pack('V')
  buf
end

#sighash_for_input(input_index, output_script, hash_type: , sig_version: :base, amount: nil, skip_separator_index: 0) ⇒ Object

get signature hash the script code needs is the witnessScript but removing everything up to and including the last executed OP_CODESEPARATOR before the signature checking opcode being executed.

Parameters:

  • input_index (Integer)

    input index.

  • hash_type (Integer) (defaults to: )

    signature hash type

  • output_script (Bitcoin::Script)

    script pubkey or script code. if script pubkey is P2WSH, set witness script to this.

  • amount (Integer) (defaults to: nil)

    bitcoin amount locked in input. required for witness input only.

  • skip_separator_index (Integer) (defaults to: 0)

    If output_script is P2WSH and output_script contains any OP_CODESEPARATOR,

Raises:

  • (ArgumentError)


198
199
200
201
202
203
204
205
206
207
208
209
210
211
# File 'lib/bitcoin/tx.rb', line 198

def sighash_for_input(input_index, output_script, hash_type: SIGHASH_TYPE[:all],
                      sig_version: :base, amount: nil, skip_separator_index: 0)
  raise ArgumentError, 'input_index must be specified.' unless input_index
  raise ArgumentError, 'does not exist input corresponding to input_index.' if input_index >= inputs.size
  raise ArgumentError, 'script_pubkey must be specified.' unless output_script
  raise ArgumentError, 'unsupported sig version specified.' unless SIG_VERSION.include?(sig_version)

  if sig_version == :witness_v0 || Bitcoin.chain_params.fork_chain?
    raise ArgumentError, 'amount must be specified.' unless amount
    sighash_for_witness(input_index, output_script, hash_type, amount, skip_separator_index)
  else
    sighash_for_legacy(input_index, output_script, hash_type)
  end
end

#sizeObject

The serialized transaction size



172
173
174
# File 'lib/bitcoin/tx.rb', line 172

def size
  to_payload.bytesize
end

#standard?Boolean

check this tx is standard.

Returns:

  • (Boolean)


149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/bitcoin/tx.rb', line 149

def standard?
  return false if version > MAX_STANDARD_VERSION
  return false if weight > MAX_STANDARD_TX_WEIGHT
  inputs.each do |i|
    # Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed keys (remember the 520 byte limit on redeemScript size).
    # That works out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)+3=1627
    # bytes of scriptSig, which we round off to 1650 bytes for some minor future-proofing.
    # That's also enough to spend a 20-of-20 CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not considered standard.
    return false if i.script_sig.size > 1650
    return false unless i.script_sig.push_only?
  end
  data_count = 0
  outputs.each do |o|
    return false unless o.script_pubkey.standard?
    data_count += 1 if o.script_pubkey.op_return?
    # TODO add non P2SH multisig relay(permitbaremultisig)
    return false if o.dust?
  end
  return false if data_count > 1
  true
end

#to_hObject



235
236
237
238
239
240
# File 'lib/bitcoin/tx.rb', line 235

def to_h
  {
      txid: txid, hash: witness_hash.rhex, version: version, size: size, vsize: vsize, locktime: lock_time,
      vin: inputs.map(&:to_h), vout: outputs.map.with_index{|tx_out, index| tx_out.to_h.merge({n: index})}
  }
end

#to_hexString

convert tx to hex format.

Returns:

  • (String)

    tx with hex format.



109
110
111
# File 'lib/bitcoin/tx.rb', line 109

def to_hex
  to_payload.bth
end

#to_payloadObject



103
104
105
# File 'lib/bitcoin/tx.rb', line 103

def to_payload
  witness? ? serialize_witness_format : serialize_old_format
end

#tx_hashObject



76
77
78
# File 'lib/bitcoin/tx.rb', line 76

def tx_hash
  Bitcoin.double_sha256(serialize_old_format).bth
end

#txidObject



80
81
82
# File 'lib/bitcoin/tx.rb', line 80

def txid
  tx_hash.rhex
end

#valid?Boolean

Verify transaction validity.

Returns:

  • (Boolean)

    whether this tx is valid or not.



244
245
246
247
248
# File 'lib/bitcoin/tx.rb', line 244

def valid?
  state = Bitcoin::ValidationState.new
  validation = Bitcoin::Validation.new
  validation.check_tx(self, state) && state.valid?
end

#verify_input_sig(input_index, script_pubkey, amount: nil, flags: STANDARD_SCRIPT_VERIFY_FLAGS) ⇒ Object

verify input signature.

Parameters:

  • input_index (Integer)
  • script_pubkey (Bitcoin::Script)

    the script pubkey for target input.

  • amount (Integer) (defaults to: nil)

    the amount of bitcoin, require for witness program only.

  • flags (Array) (defaults to: STANDARD_SCRIPT_VERIFY_FLAGS)

    the flags used when execute script interpreter.



218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/bitcoin/tx.rb', line 218

def verify_input_sig(input_index, script_pubkey, amount: nil, flags: STANDARD_SCRIPT_VERIFY_FLAGS)
  script_sig = inputs[input_index].script_sig
  has_witness = inputs[input_index].has_witness?

  if script_pubkey.p2sh?
    flags << SCRIPT_VERIFY_P2SH
    redeem_script = Script.parse_from_payload(script_sig.chunks.last)
    script_pubkey = redeem_script if redeem_script.p2wpkh?
  end

  if has_witness || Bitcoin.chain_params.fork_chain?
    verify_input_sig_for_witness(input_index, script_pubkey, amount, flags)
  else
    verify_input_sig_for_legacy(input_index, script_pubkey, flags)
  end
end

#vsizeObject

The virtual transaction size (differs from size for witness transactions)



177
178
179
# File 'lib/bitcoin/tx.rb', line 177

def vsize
  (weight.to_f / 4).ceil
end

#weightObject

calculate tx weight weight = (legacy tx payload) * 3 + (witness tx payload)



183
184
185
186
187
188
189
# File 'lib/bitcoin/tx.rb', line 183

def weight
  if witness?
    serialize_old_format.bytesize * (WITNESS_SCALE_FACTOR - 1) + serialize_witness_format.bytesize
  else
    serialize_old_format.bytesize * WITNESS_SCALE_FACTOR
  end
end

#witness?Boolean

Returns:

  • (Boolean)


117
118
119
# File 'lib/bitcoin/tx.rb', line 117

def witness?
  !inputs.find { |i| !i.script_witness.empty? }.nil?
end

#witness_commitmentObject

get the witness commitment of coinbase tx. if this tx does not coinbase or not have commitment, return nil.



94
95
96
97
98
99
100
101
# File 'lib/bitcoin/tx.rb', line 94

def witness_commitment
  return nil unless coinbase_tx?
  outputs.each do |output|
    commitment = output.script_pubkey.witness_commitment
    return commitment if commitment
  end
  nil
end

#witness_hashObject



84
85
86
# File 'lib/bitcoin/tx.rb', line 84

def witness_hash
  Bitcoin.double_sha256(to_payload).bth
end

#witness_payloadObject



144
145
146
# File 'lib/bitcoin/tx.rb', line 144

def witness_payload
  inputs.map { |i| i.script_witness.to_payload }.join
end

#wtxidObject



88
89
90
# File 'lib/bitcoin/tx.rb', line 88

def wtxid
  witness_hash.rhex
end