Class: Bitcoin::Script

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

Defined Under Namespace

Classes: ScriptOpcodeError

Constant Summary collapse

OP_0 =
0
OP_FALSE =
0
OP_1 =
81
OP_TRUE =
81
OP_2 =
0x52
OP_3 =
0x53
OP_4 =
0x54
OP_5 =
0x55
OP_6 =
0x56
OP_7 =
0x57
OP_8 =
0x58
OP_9 =
0x59
OP_10 =
0x5a
OP_11 =
0x5b
OP_12 =
0x5c
OP_13 =
0x5d
OP_14 =
0x5e
OP_15 =
0x5f
OP_16 =
0x60
OP_PUSHDATA0 =
0
OP_PUSHDATA1 =
76
OP_PUSHDATA2 =
77
OP_PUSHDATA4 =
78
OP_PUSHDATA_INVALID =

0xEE

238
OP_NOP =
97
OP_DUP =
118
OP_HASH160 =
169
OP_EQUAL =
135
OP_VERIFY =
105
OP_EQUALVERIFY =
136
OP_CHECKSIG =
172
OP_CHECKSIGVERIFY =
173
OP_CHECKMULTISIG =
174
OP_CHECKMULTISIGVERIFY =
175
OP_TOALTSTACK =
107
OP_FROMALTSTACK =
108
OP_TUCK =
125
OP_SWAP =
124
OP_BOOLAND =
154
OP_ADD =
147
OP_SUB =
148
OP_GREATERTHANOREQUAL =
162
OP_DROP =
117
OP_HASH256 =
170
OP_SHA256 =
168
OP_SHA1 =
167
OP_RIPEMD160 =
166
OP_NOP1 =
176
OP_NOP2 =
177
OP_NOP3 =
178
OP_NOP4 =
179
OP_NOP5 =
180
OP_NOP6 =
181
OP_NOP7 =
182
OP_NOP8 =
183
OP_NOP9 =
184
OP_NOP10 =
185
OP_CODESEPARATOR =
171
OP_MIN =
163
OP_MAX =
164
OP_2OVER =
112
OP_2ROT =
113
OP_2SWAP =
114
OP_IFDUP =
115
OP_DEPTH =
116
OP_1NEGATE =
79
OP_WITHIN =
165
OP_NUMEQUAL =
156
OP_NUMEQUALVERIFY =
157
OP_LESSTHAN =
159
OP_LESSTHANOREQUAL =
161
OP_GREATERTHAN =
160
OP_NOT =
145
OP_0NOTEQUAL =
146
OP_ABS =
144
OP_1ADD =
139
OP_1SUB =
140
OP_NEGATE =
143
OP_BOOLOR =
155
OP_NUMNOTEQUAL =
158
OP_RETURN =
106
OP_OVER =
120
OP_IF =
99
OP_NOTIF =
100
OP_ELSE =
103
OP_ENDIF =
104
OP_PICK =
121
OP_SIZE =
130
OP_VER =
98
OP_ROLL =
122
OP_ROT =
123
OP_2DROP =
109
OP_2DUP =
110
OP_3DUP =
111
OP_NIP =
119
OP_CAT =
126
OP_SUBSTR =
127
OP_LEFT =
128
OP_RIGHT =
129
OP_INVERT =
131
OP_AND =
132
OP_OR =
133
OP_XOR =
134
OP_2MUL =
141
OP_2DIV =
142
OP_MUL =
149
OP_DIV =
150
OP_MOD =
151
OP_LSHIFT =
152
OP_RSHIFT =
153
OP_INVALIDOPCODE =
0xff
OPCODES =
Hash[*constants.grep(/^OP_/).map{|i| [const_get(i), i.to_s]
OPCODES_ALIAS =
{
  "OP_TRUE"  => OP_1,
  "OP_FALSE" => OP_0,
  "OP_EVAL" => OP_NOP1,
  "OP_CHECKHASHVERIFY" => OP_NOP2,
}
DISABLED_OPCODES =
[
  OP_CAT, OP_SUBSTR, OP_LEFT, OP_RIGHT, OP_INVERT,
  OP_AND, OP_OR, OP_XOR, OP_2MUL, OP_2DIV, OP_MUL,
  OP_DIV, OP_MOD, OP_LSHIFT, OP_RSHIFT
]
OP_2_16 =
(82..96).to_a
OPCODES_PARSE_BINARY =
{}
OPCODES_PARSE_STRING =
{}
SIGHASH_TYPE =
{
  all: 1,
  none: 2,
  single: 3,
  forkid: 64,
  anyonecanpay: 128
}.freeze
OPCODES_METHOD =

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input_script, previous_output_script = nil) ⇒ Script

create a new script. bytes is typically input_script + output_script



165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
# File 'lib/bitcoin/script.rb', line 165

def initialize(input_script, previous_output_script=nil)
  @raw_byte_sizes = [input_script.bytesize, previous_output_script ? previous_output_script.bytesize : 0]
  @input_script, @previous_output_script = input_script, previous_output_script
  @parse_invalid = nil
  @inner_p2sh = nil
  @script_codeseparator_index = nil

  @raw = if @previous_output_script
           @input_script + [ Bitcoin::Script::OP_CODESEPARATOR ].pack("C") + @previous_output_script
         else
           @input_script
         end

  @chunks = parse(@input_script)

  if previous_output_script
    @script_codeseparator_index = @chunks.size
    @chunks << Bitcoin::Script::OP_CODESEPARATOR
    @chunks += parse(@previous_output_script)
  end

  @stack, @stack_alt, @exec_stack = [], [], []
  @last_codeseparator_index = 0
  @do_exec = true
end

Instance Attribute Details

#chunksObject (readonly)

Returns the value of attribute chunks.



161
162
163
# File 'lib/bitcoin/script.rb', line 161

def chunks
  @chunks
end

#debugObject (readonly)

Returns the value of attribute debug.



161
162
163
# File 'lib/bitcoin/script.rb', line 161

def debug
  @debug
end

#rawObject (readonly)

Returns the value of attribute raw.



161
162
163
# File 'lib/bitcoin/script.rb', line 161

def raw
  @raw
end

#stackObject (readonly)

Returns the value of attribute stack.



161
162
163
# File 'lib/bitcoin/script.rb', line 161

def stack
  @stack
end

Class Method Details

.add_sig_to_multisig_script_sig(sig, script_sig, hash_type = ) ⇒ Object

take a multisig script sig (or p2sh multisig script sig) and add another signature to it after the OP_0. Used to sign a tx by multiple parties. Signatures must be in the same order as the pubkeys in the output script being redeemed.



881
882
883
884
885
# File 'lib/bitcoin/script.rb', line 881

def self.add_sig_to_multisig_script_sig(sig, script_sig, hash_type = SIGHASH_TYPE[:all])
  signature = sig + [hash_type].pack("C*")
  offset = script_sig.empty? ? 0 : 1
  script_sig.insert(offset, pack_pushdata(signature))
end

.binary_from_string(script_string) ⇒ Object

raw script binary of a string representation



404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
# File 'lib/bitcoin/script.rb', line 404

def self.binary_from_string(script_string)
  buf = ""
  script_string.split(" ").each{|i|
    i = if opcode = OPCODES_PARSE_STRING[i]
      opcode
    else
      case i
      when /OP_PUSHDATA/             # skip
      when /OP_(.+)$/;               raise ScriptOpcodeError, "#{i} not defined!"
      when /\(opcode\-(\d+)\)/;      $1.to_i
      when "(opcode";                # skip  # fix invalid opcode parsing
      when /^(\d+)\)/;               $1.to_i # fix invalid opcode parsing
      when /(\d+):(\d+):(.+)?/
        pushdata, len, data = $1.to_i, $2.to_i, $3
        pack_pushdata_align(pushdata, len, [data].pack("H*"))
      else
        data = [i].pack("H*")
        pack_pushdata(data)
      end
    end

    buf << if i.is_a?(Bitcoin::Integer)
             i < 256 ? [i].pack("C") : [OpenSSL::BN.new(i.to_s,10).to_hex].pack("H*")
           else
             i
           end if i
  }
  buf
end

.check_pubkey_encoding?(pubkey, opts = {}) ⇒ Boolean

Returns:

  • (Boolean)


1548
1549
1550
1551
# File 'lib/bitcoin/script.rb', line 1548

def self.check_pubkey_encoding?(pubkey, opts={})
  return false if opts[:verify_strictenc] && !is_compressed_or_uncompressed_pub_key?(pubkey)
  true
end

.check_signature_encoding?(sig, opts = {}) ⇒ Boolean

Loosely matches CheckSignatureEncoding()

Returns:

  • (Boolean)


1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
# File 'lib/bitcoin/script.rb', line 1567

def self.check_signature_encoding?(sig, opts={})
  return true  if sig.bytesize == 0
  return false if (opts[:verify_dersig] || opts[:verify_low_s] || opts[:verify_strictenc]) and !is_der_signature?(sig)
  return false if opts[:verify_low_s] && !is_low_der_signature?(sig)

  if opts[:verify_strictenc]
    return false unless is_defined_hashtype_signature?(sig)

    hash_type = sig.unpack('C*')[-1]
    uses_forkid = (hash_type&SIGHASH_TYPE[:forkid]) != 0
    return false if opts[:fork_id] && !uses_forkid
    return false if !opts[:fork_id] && uses_forkid
  end

  true
end

.compare_big_endian(c1, c2) ⇒ Object

Compares two arrays of bytes



1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
# File 'lib/bitcoin/script.rb', line 1620

def self.compare_big_endian(c1, c2)
  c1, c2 = c1.dup, c2.dup # Clone the arrays

  while c1.size > c2.size
    return 1 if c1.shift > 0
  end

  while c2.size > c1.size
    return -1 if c2.shift > 0
  end

  c1.size.times{|idx| return c1[idx] - c2[idx] if c1[idx] != c2[idx] }
  0
end

.decode_OP_N(opcode) ⇒ Object

Converts OP_0,1,2,…,16 into 0, 1, 2, …, 16. Returns nil for other opcodes.



979
980
981
982
983
984
985
986
987
988
# File 'lib/bitcoin/script.rb', line 979

def self.decode_OP_N(opcode)
  if opcode == OP_0
    return 0
  end
  if opcode.is_a?(Bitcoin::Integer) && opcode >= OP_1 && opcode <= OP_16
    return opcode - (OP_1 - 1);
  else
    nil
  end
end

.drop_signatures(script_pubkey, drop_signatures) ⇒ Object



518
519
520
521
# File 'lib/bitcoin/script.rb', line 518

def self.drop_signatures(script_pubkey, drop_signatures)
  script = new(script_pubkey).to_string.split(" ").delete_if{|c| drop_signatures.include?(c) }.join(" ")
  script_pubkey = binary_from_string(script)
end

.from_string(input_script, previous_output_script = nil) ⇒ Object

script object of a string representation



393
394
395
396
397
398
399
# File 'lib/bitcoin/script.rb', line 393

def self.from_string(input_script, previous_output_script=nil)
  if previous_output_script
    new(binary_from_string(input_script), binary_from_string(previous_output_script))
  else
    new(binary_from_string(input_script))
  end
end

.is_compressed_or_uncompressed_pub_key?(pubkey) ⇒ Boolean

Returns:

  • (Boolean)


1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
# File 'lib/bitcoin/script.rb', line 1553

def self.is_compressed_or_uncompressed_pub_key?(pubkey)
  return false if pubkey.bytesize < 33 # "Non-canonical public key: too short"
  case pubkey[0]
  when "\x04"
    return false if pubkey.bytesize != 65 # "Non-canonical public key: invalid length for uncompressed key"
  when "\x02", "\x03"
    return false if pubkey.bytesize != 33 # "Non-canonical public key: invalid length for compressed key"
  else
    return false # "Non-canonical public key: compressed nor uncompressed"
  end
  true
end

.is_defined_hashtype_signature?(sig) ⇒ Boolean

Returns:

  • (Boolean)


1656
1657
1658
1659
1660
1661
1662
1663
1664
# File 'lib/bitcoin/script.rb', line 1656

def self.is_defined_hashtype_signature?(sig)
  return false if sig.empty?

  s = sig.unpack("C*")
  hash_type = s[-1] & (~(SIGHASH_TYPE[:anyonecanpay] | SIGHASH_TYPE[:forkid]))
  return false if hash_type < SIGHASH_TYPE[:all]   ||  hash_type > SIGHASH_TYPE[:single] # Non-canonical signature: unknown hashtype byte

  true
end

.is_der_signature?(sig) ⇒ Boolean

Loosely correlates with IsDERSignature() from interpreter.cpp

Returns:

  • (Boolean)


1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
# File 'lib/bitcoin/script.rb', line 1585

def self.is_der_signature?(sig)
  return false if sig.bytesize < 9 # Non-canonical signature: too short
  return false if sig.bytesize > 73 # Non-canonical signature: too long

  s = sig.unpack("C*")

  return false if s[0] != 0x30 # Non-canonical signature: wrong type
  return false if s[1] != s.size-3 # Non-canonical signature: wrong length marker

  length_r = s[3]
  return false if (5 + length_r) >= s.size # Non-canonical signature: S length misplaced
  length_s = s[5+length_r]
  return false if (length_r + length_s + 7) != s.size # Non-canonical signature: R+S length mismatch

  return false if s[2] != 0x02 # Non-canonical signature: R value type mismatch

  return false if length_r == 0 # Non-canonical signature: R length is zero

  r_val = s.slice(4, length_r)
  return false if r_val[0] & 0x80 != 0 # Non-canonical signature: R value negative

  return false if length_r > 1 && (r_val[0] == 0x00) && !(r_val[1] & 0x80 != 0) # Non-canonical signature: R value excessively padded

  s_val = s.slice(6 + length_r, length_s)
  return false if s[6 + length_r - 2] != 0x02 # Non-canonical signature: S value type mismatch

  return false if length_s == 0 # Non-canonical signature: S length is zero
  return false if (s_val[0] & 0x80) != 0 # Non-canonical signature: S value negative

  return false if length_s > 1 && (s_val[0] == 0x00) && !(s_val[1] & 0x80) # Non-canonical signature: S value excessively padded

  true
end

.is_low_der_signature?(sig) ⇒ Boolean

Loosely correlates with IsLowDERSignature() from interpreter.cpp

Returns:

  • (Boolean)


1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
# File 'lib/bitcoin/script.rb', line 1636

def self.is_low_der_signature?(sig)
  s = sig.unpack("C*")

  length_r = s[3]
  length_s = s[5+length_r]
  s_val = s.slice(6 + length_r, length_s)

  # If the S value is above the order of the curve divided by two, its
  # complement modulo the order could have been used instead, which is
  # one byte shorter when encoded correctly.
  max_mod_half_order = [
    0x7f,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
    0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
    0x5d,0x57,0x6e,0x73,0x57,0xa4,0x50,0x1d,
    0xdf,0xe9,0x2f,0x46,0x68,0x1b,0x20,0xa0]

  compare_big_endian(s_val, [0]) > 0 &&
    compare_big_endian(s_val, max_mod_half_order) <= 0
end

.pack_pushdata(data) ⇒ Object



356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
# File 'lib/bitcoin/script.rb', line 356

def self.pack_pushdata(data)
  size = data.bytesize

  if data.bitcoin_pushdata
    size = data.bitcoin_pushdata_length
    pack_pushdata_align(data.bitcoin_pushdata, size, data)
  else
    head = if size < OP_PUSHDATA1
             [size].pack("C")
           elsif size <= 0xff
             [OP_PUSHDATA1, size].pack("CC")
           elsif size <= 0xffff
             [OP_PUSHDATA2, size].pack("Cv")
           #elsif size <= 0xffffffff
           else
             [OP_PUSHDATA4, size].pack("CV")
           end
    head + data
  end
end

.pack_pushdata_align(pushdata, len, data) ⇒ Object



377
378
379
380
381
382
383
384
385
386
387
388
389
390
# File 'lib/bitcoin/script.rb', line 377

def self.pack_pushdata_align(pushdata, len, data)
  case pushdata
  when OP_PUSHDATA1
    [OP_PUSHDATA1, len].pack("CC") + data
  when OP_PUSHDATA2
    [OP_PUSHDATA2, len].pack("Cv") + data
  when OP_PUSHDATA4
    [OP_PUSHDATA4, len].pack("CV") + data
  when OP_PUSHDATA_INVALID
    data
  else # OP_PUSHDATA0
    [len].pack("C") + data
  end
end

.sort_p2sh_multisig_signatures(script_sig, sig_hash) ⇒ Object

Sort signatures in the given script_sig according to the order of pubkeys in the redeem script. Also needs the sig_hash to match signatures to pubkeys.



896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
# File 'lib/bitcoin/script.rb', line 896

def self.sort_p2sh_multisig_signatures script_sig, sig_hash
  script = new(script_sig)
  redeem_script = new(script.chunks[-1])
  pubkeys = redeem_script.get_multisig_pubkeys

  # find the pubkey for each signature by trying to verify it
  sigs = Hash[script.chunks[1...-1].map.with_index do |sig, idx|
    pubkey = pubkeys.map {|key|
      Bitcoin::Key.new(nil, key.hth).verify(sig_hash, sig) ? key : nil }.compact.first
    raise "Key for signature ##{idx} not found in redeem script!"  unless pubkey
    [pubkey, sig]
  end]

  [OP_0].pack("C*") + pubkeys.map {|k| sigs[k] ? pack_pushdata(sigs[k]) : nil }.join +
    pack_pushdata(redeem_script.raw)
end

.to_address_script(address) ⇒ Object

generate hash160 or p2sh output script, depending on the type of the given address. see #to_hash160_script and #to_p2sh_script.



803
804
805
806
807
808
809
810
811
812
# File 'lib/bitcoin/script.rb', line 803

def self.to_address_script(address)
  hash160 = Bitcoin.hash160_from_address(address)
  case Bitcoin.address_type(address)
  when :hash160; to_hash160_script(hash160)
  when :p2sh;    to_p2sh_script(hash160)
  when :witness_v0_keyhash, :witness_v0_scripthash
    witness_version, witness_program_hex = Bitcoin.decode_segwit_address(address)
    to_witness_script(witness_version, witness_program_hex)
  end
end

.to_hash160_script(hash160) ⇒ Object

generate hash160 tx for given address. returns a raw binary script of the form:

OP_DUP OP_HASH160 <hash160> OP_EQUALVERIFY OP_CHECKSIG


763
764
765
766
767
# File 'lib/bitcoin/script.rb', line 763

def self.to_hash160_script(hash160)
  return nil  unless hash160
  #  DUP   HASH160  length  hash160    EQUALVERIFY  CHECKSIG
  [ ["76", "a9",    "14",   hash160,   "88",        "ac"].join ].pack("H*")
end

.to_multisig_script(m, *pubkeys) ⇒ Object

generate multisig output script for given pubkeys, expecting m signatures. returns a raw binary script of the form:

<m> <pubkey> [<pubkey> ...] <n_pubkeys> OP_CHECKMULTISIG


817
818
819
820
821
822
823
824
825
826
# File 'lib/bitcoin/script.rb', line 817

def self.to_multisig_script(m, *pubkeys)
  raise "invalid m-of-n number" unless [m, pubkeys.size].all?{|i| (0..20).include?(i) }
  raise "invalid m-of-n number" if pubkeys.size < m
  pubs = pubkeys.map{|pk| pack_pushdata([pk].pack("H*")) }

  m = m > 16 ?              pack_pushdata([m].pack("C"))              : [80 + m.to_i].pack("C")
  n = pubkeys.size > 16 ?   pack_pushdata([pubkeys.size].pack("C"))   : [80 + pubs.size].pack("C")

  [ m, *pubs, n, [OP_CHECKMULTISIG].pack("C")].join
end

.to_multisig_script_sig(*sigs) ⇒ Object

generate input script sig spending a multisig output script. returns a raw binary script sig of the form:

OP_0 <sig> [<sig> ...]


870
871
872
873
874
875
# File 'lib/bitcoin/script.rb', line 870

def self.to_multisig_script_sig(*sigs)
  hash_type = sigs.last.is_a?(Numeric) ? sigs.pop : SIGHASH_TYPE[:all]
  partial_script = [OP_0].pack("C*")
  sigs.reverse_each{ |sig| partial_script = add_sig_to_multisig_script_sig(sig, partial_script, hash_type) }
  partial_script
end

.to_op_return_script(data = nil) ⇒ Object

generate OP_RETURN output script with given data. returns a raw binary script of the form:

OP_RETURN <data>


830
831
832
833
834
# File 'lib/bitcoin/script.rb', line 830

def self.to_op_return_script(data = nil)
  buf = [ OP_RETURN ].pack("C")
  return buf unless data
  return buf + pack_pushdata( [data].pack("H*") )
end

.to_p2sh_multisig_script(*args) ⇒ Object

generate p2sh multisig output script for given args. returns the p2sh output script, and the redeem script needed to spend it. see #to_multisig_script for the redeem script, and #to_p2sh_script for the p2sh script.



856
857
858
859
860
# File 'lib/bitcoin/script.rb', line 856

def self.to_p2sh_multisig_script(*args)
  redeem_script = to_multisig_script(*args)
  p2sh_script = to_p2sh_script(Bitcoin.hash160(redeem_script.hth))
  return p2sh_script, redeem_script
end

.to_p2sh_multisig_script_sig(redeem_script, *sigs) ⇒ Object

generate input script sig spending a p2sh-multisig output script. returns a raw binary script sig of the form:

OP_0 <sig> [<sig> ...] <redeem_script>


890
891
892
# File 'lib/bitcoin/script.rb', line 890

def self.to_p2sh_multisig_script_sig(redeem_script, *sigs)
  to_multisig_script_sig(*sigs.flatten) + pack_pushdata(redeem_script)
end

.to_p2sh_script(p2sh) ⇒ Object

generate p2sh output script for given p2sh hash160. returns a raw binary script of the form:

OP_HASH160 <p2sh> OP_EQUAL


771
772
773
774
775
# File 'lib/bitcoin/script.rb', line 771

def self.to_p2sh_script(p2sh)
  return nil  unless p2sh
  # HASH160  length  hash  EQUAL
  [ ["a9",   "14",   p2sh, "87"].join ].pack("H*")
end

.to_pubkey_script(pubkey) ⇒ Object

generate pubkey tx script for given pubkey. returns a raw binary script of the form:

<pubkey> OP_CHECKSIG


757
758
759
# File 'lib/bitcoin/script.rb', line 757

def self.to_pubkey_script(pubkey)
  pack_pushdata([pubkey].pack("H*")) + [ OP_CHECKSIG ].pack("C")
end

.to_pubkey_script_sig(signature, pubkey, hash_type = ) ⇒ Object

generate input script sig spending a pubkey output with given signature and pubkey. returns a raw binary script sig of the form:

<signature> [<pubkey>]


839
840
841
842
843
844
845
846
847
848
849
850
851
# File 'lib/bitcoin/script.rb', line 839

def self.to_pubkey_script_sig(signature, pubkey, hash_type = SIGHASH_TYPE[:all])
  buf = pack_pushdata(signature + [hash_type].pack("C"))
  return buf unless pubkey

  expected_size = case pubkey[0]
                  when "\x04"; 65
                  when "\x02", "\x03"; 33
                  end

  raise "pubkey is not in binary form" if !expected_size || pubkey.bytesize != expected_size

  return buf + pack_pushdata(pubkey)
end

.to_signature_pubkey_script(*a) ⇒ Object

alias for #to_pubkey_script_sig



863
864
865
# File 'lib/bitcoin/script.rb', line 863

def self.to_signature_pubkey_script(*a)
  to_pubkey_script_sig(*a)
end

.to_witness_hash160_script(hash160) ⇒ Object

generate p2wpkh tx for given address. returns a raw binary script of the form: 0 <hash160>



789
790
791
792
# File 'lib/bitcoin/script.rb', line 789

def self.to_witness_hash160_script(hash160)
  return nil  unless hash160
  to_witness_script(0, hash160)
end

.to_witness_p2sh_script(p2sh) ⇒ Object

generate p2wsh output script for given p2sh sha256. returns a raw binary script of the form: 0 <p2sh>



796
797
798
799
# File 'lib/bitcoin/script.rb', line 796

def self.to_witness_p2sh_script(p2sh)
  return nil  unless p2sh
  to_witness_script(0, p2sh)
end

.to_witness_script(witness_version, witness_program_hex) ⇒ Object

generate pay-to-witness output script for given witness_version and witness_program. returns a raw binary script of the form: <witness_version> <witness_program>



780
781
782
783
784
785
# File 'lib/bitcoin/script.rb', line 780

def self.to_witness_script(witness_version, witness_program_hex)
  return nil unless (0..16).include?(witness_version)
  return nil unless witness_program_hex
  version = witness_version != 0 ? 0x50 + witness_version : 0 # 0x50 for OP_1.. codes
  [version].pack('C') + pack_pushdata(witness_program_hex.htb)
end

Instance Method Details

#append_number(number) ⇒ Object

Adds the opcode corresponding to the given number. Returns self.



335
336
337
338
339
340
341
342
343
344
345
# File 'lib/bitcoin/script.rb', line 335

def append_number(number)
  opcode =
    case number
    when -1 then OP_1NEGATE
    when 0 then OP_0
    when 1 then OP_1
    when 2..16 then OP_2 + (16 - number)
    end
  raise "No opcode for number #{number}" if opcode.nil?
  append_opcode(opcode)
end

#append_opcode(opcode) ⇒ Object

Adds opcode (OP_0, OP_1, … OP_CHECKSIG etc.) Returns self.



324
325
326
327
328
329
330
331
332
# File 'lib/bitcoin/script.rb', line 324

def append_opcode(opcode)
  raise "Opcode should be an integer" if !opcode.is_a?(Bitcoin::Integer)
  if opcode >= OP_0 && opcode <= 0xff
    @chunks << opcode
  else
    raise "Opcode should be within [0x00, 0xff]"
  end
  self
end

#append_pushdata(pushdata_string) ⇒ Object

Adds binary string as pushdata. Pushdata will be encoded in the most compact form (unless the string contains internal info about serialization that’s added by Script class) Returns self.



350
351
352
353
354
# File 'lib/bitcoin/script.rb', line 350

def append_pushdata(pushdata_string)
  raise "Pushdata should be a string" if !pushdata_string.is_a?(String)
  @chunks << pushdata_string
  self
end

#cast_to_bignum(buf) ⇒ Object



1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
# File 'lib/bitcoin/script.rb', line 1375

def cast_to_bignum(buf)
  return (invalid; 0) unless buf
  case buf
  when Numeric
    invalid if OpenSSL::BN.new(buf.to_s).to_s(0).unpack("N")[0] > 4
    buf
  when String
    invalid if buf.bytesize > 4
    OpenSSL::BN.new([buf.bytesize].pack("N") + buf.reverse, 0).to_i
  else; raise TypeError, 'cast_to_bignum: failed to cast: %s (%s)' % [buf, buf.class]
  end
end

#cast_to_bool(buf) ⇒ Object



1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
# File 'lib/bitcoin/script.rb', line 1397

def cast_to_bool(buf)
  buf = cast_to_string(buf).unpack("C*")
  size = buf.size
  buf.each.with_index{|byte,index|
    if byte != 0
      # Can be negative zero
      if (index == (size-1)) && byte == 0x80
        return false
      else
        return true
      end
    end
  }
  return false
end

#cast_to_string(buf) ⇒ Object



1388
1389
1390
1391
1392
1393
1394
1395
# File 'lib/bitcoin/script.rb', line 1388

def cast_to_string(buf)
  return (invalid; "") unless buf
  case buf
  when Numeric; OpenSSL::BN.new(buf.to_s).to_s(0)[4..-1].reverse
  when String; buf;
  else; raise TypeError, 'cast_to_string: failed to cast: %s (%s)' % [buf, buf.class]
  end
end

#check_pushes(push_only = true, canonical_only = false, buf) ⇒ Object



633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
# File 'lib/bitcoin/script.rb', line 633

def check_pushes(push_only=true, canonical_only=false, buf)
  program = buf.unpack("C*")
  until program.empty?
    opcode = program.shift
    if opcode > OP_16
      return false if push_only
      next
    end
    if opcode < OP_PUSHDATA1 && opcode > OP_0
      # Could have used an OP_n code, rather than a 1-byte push.
      return false if canonical_only && opcode == 1 && program[0] <= 16
      program.shift(opcode)
    end
    if opcode == OP_PUSHDATA1
      len = program.shift(1)[0]
      # Could have used a normal n-byte push, rather than OP_PUSHDATA1.
      return false if canonical_only && len < OP_PUSHDATA1
      program.shift(len)
    end
    if opcode == OP_PUSHDATA2
      len = program.shift(2).pack("C*").unpack("v")[0]
      # Could have used an OP_PUSHDATA1.
      return false if canonical_only && len <= 0xff
      program.shift(len)
    end
    if opcode == OP_PUSHDATA4
      len = program.shift(4).pack("C*").unpack("V")[0]
      # Could have used an OP_PUSHDATA2.
      return false if canonical_only && len <= 0xffff
      program.shift(len)
    end
  end
  true
rescue
  # catch parsing errors
  false
end

#codehash_script(opcode) ⇒ Object



1425
1426
1427
1428
1429
1430
# File 'lib/bitcoin/script.rb', line 1425

def codehash_script(opcode)
  # CScript scriptCode(pbegincodehash, pend);
  script    = to_string(@chunks[(@codehash_start||0)...@chunks.size-@chunks.reverse.index(opcode)])
  checkhash = Bitcoin.hash160(Bitcoin::Script.binary_from_string(script).unpack("H*")[0])
  [script, checkhash]
end

#codeseparator_countObject



923
924
925
# File 'lib/bitcoin/script.rb', line 923

def codeseparator_count
  @chunks.select{|c|c == Bitcoin::Script::OP_CODESEPARATOR}.length
end

#get_addressObject

get single address, or first for multisig script



750
751
752
753
# File 'lib/bitcoin/script.rb', line 750

def get_address
  addrs = get_addresses
  addrs.is_a?(Array) ? addrs[0] : addrs
end

#get_addressesObject

get all addresses this script corresponds to (if possible)



735
736
737
738
739
740
741
742
743
744
745
746
747
# File 'lib/bitcoin/script.rb', line 735

def get_addresses
  return [get_pubkey_address]    if is_pubkey?
  return [get_hash160_address]   if is_hash160?
  return get_multisig_addresses  if is_multisig?
  return [get_p2sh_address]      if is_p2sh?

  if is_witness_v0_keyhash? || is_witness_v0_scripthash?
    program_hex = chunks[1].unpack("H*").first
    return [Bitcoin.encode_segwit_address(0, program_hex)]
  end

  []
end

#get_hash160Object

get the hash160 for this hash160 or pubkey script



696
697
698
699
700
701
702
# File 'lib/bitcoin/script.rb', line 696

def get_hash160
  return @chunks[2..-3][0].unpack("H*")[0]  if is_hash160?
  return @chunks[-2].unpack("H*")[0]        if is_p2sh?
  return Bitcoin.hash160(get_pubkey)        if is_pubkey?
  return @chunks[1].unpack("H*")[0]         if is_witness_v0_keyhash?
  return @chunks[1].unpack("H*")[0]         if is_witness_v0_scripthash?
end

#get_hash160_addressObject

get the hash160 address for this hash160 script



705
706
707
# File 'lib/bitcoin/script.rb', line 705

def get_hash160_address
  Bitcoin.hash160_to_address(get_hash160)
end

#get_keys_providedObject



918
919
920
921
# File 'lib/bitcoin/script.rb', line 918

def get_keys_provided
  return false  unless is_multisig?
  @chunks[-2] - 80
end

#get_multisig_addressesObject

get the pubkey addresses for this multisig script



715
716
717
718
719
720
721
722
# File 'lib/bitcoin/script.rb', line 715

def get_multisig_addresses
  get_multisig_pubkeys.map{|pub|
    begin
      Bitcoin::Key.new(nil, pub.unpack("H*")[0]).addr
    rescue OpenSSL::PKey::ECError, OpenSSL::PKey::EC::Point::Error
    end
  }
end

#get_multisig_pubkeysObject

get the public keys for this multisig script



710
711
712
# File 'lib/bitcoin/script.rb', line 710

def get_multisig_pubkeys
  1.upto(@chunks[-2] - 80).map{|i| @chunks[i] }
end

#get_op_return_dataObject

get the data possibly included in an OP_RETURN script



729
730
731
732
# File 'lib/bitcoin/script.rb', line 729

def get_op_return_data
  return nil  unless is_op_return?
  cast_to_string(@chunks[1]).unpack("H*")[0]  if @chunks[1]
end

#get_p2sh_addressObject



724
725
726
# File 'lib/bitcoin/script.rb', line 724

def get_p2sh_address
  Bitcoin.hash160_to_p2sh_address(get_hash160)
end

#get_pubkeyObject

get the public key for this pubkey script



685
686
687
688
# File 'lib/bitcoin/script.rb', line 685

def get_pubkey
  return @chunks[0].unpack("H*")[0] if @chunks.size == 1
  is_pubkey? ? @chunks[0].unpack("H*")[0] : nil
end

#get_pubkey_addressObject

get the pubkey address for this pubkey script



691
692
693
# File 'lib/bitcoin/script.rb', line 691

def get_pubkey_address
  Bitcoin.pubkey_to_address(get_pubkey)
end

#get_signatures_requiredObject



913
914
915
916
# File 'lib/bitcoin/script.rb', line 913

def get_signatures_required
  return false unless is_multisig?
  @chunks[0] - 80
end

#inner_p2sh!(script = nil) ⇒ Object



542
# File 'lib/bitcoin/script.rb', line 542

def inner_p2sh!(script=nil); @inner_p2sh = true; @inner_script_code = script; self; end

#inner_p2sh?Boolean

Returns:

  • (Boolean)


543
# File 'lib/bitcoin/script.rb', line 543

def inner_p2sh?; @inner_p2sh; end

#inner_p2sh_scriptObject

get the inner p2sh script



546
547
548
549
550
551
552
553
554
# File 'lib/bitcoin/script.rb', line 546

def inner_p2sh_script
  return nil if @chunks.size < 4
  *rest, script, _, script_hash, _ = @chunks
  script = rest.pop if script == OP_CODESEPARATOR
  script, script_hash = cast_to_string(script), cast_to_string(script_hash)

  return nil unless Bitcoin.hash160(script.unpack("H*")[0]) == script_hash.unpack("H*")[0]
  script
end

#invalidObject



514
515
516
# File 'lib/bitcoin/script.rb', line 514

def invalid
  @script_invalid = true; nil
end

#invalid?Boolean

Returns:

  • (Boolean)


434
435
436
# File 'lib/bitcoin/script.rb', line 434

def invalid?
  @script_invalid ||= false
end

#is_hash160?Boolean

is this a hash160 (address) script

Returns:

  • (Boolean)


590
591
592
593
594
595
# File 'lib/bitcoin/script.rb', line 590

def is_hash160?
  return false  if @chunks.size != 5
  (@chunks[0..1] + @chunks[-2..-1]) ==
    [OP_DUP, OP_HASH160, OP_EQUALVERIFY, OP_CHECKSIG] &&
    @chunks[2].is_a?(String) && @chunks[2].bytesize == 20
end

#is_multisig?Boolean

is this a multisig script

Returns:

  • (Boolean)


598
599
600
601
# File 'lib/bitcoin/script.rb', line 598

def is_multisig?
  return false  if @chunks.size < 4 || !@chunks[-2].is_a?(Bitcoin::Integer)
  @chunks[-1] == OP_CHECKMULTISIG and get_multisig_pubkeys.all?{|c| c.is_a?(String) }
end

#is_op_return?Boolean

is this an op_return script

Returns:

  • (Boolean)


604
605
606
# File 'lib/bitcoin/script.rb', line 604

def is_op_return?
  @chunks[0] == OP_RETURN && @chunks.size <= 2
end

#is_pay_to_script_hash?Boolean Also known as: is_p2sh?

is this a :script_hash (pay-to-script-hash/p2sh) script?

Returns:

  • (Boolean)


557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
# File 'lib/bitcoin/script.rb', line 557

def is_pay_to_script_hash?
  @inner_p2sh ||= false
  return false if @inner_p2sh
  if @previous_output_script
    chunks = Bitcoin::Script.new(@previous_output_script).chunks
    chunks.size == 3 &&
    chunks[-3] == OP_HASH160 &&
    chunks[-2].is_a?(String) && chunks[-2].bytesize == 20 &&
    chunks[-1] == OP_EQUAL
  else
    @chunks.size >= 3 &&
    @chunks[-3] == OP_HASH160 &&
    @chunks[-2].is_a?(String) && @chunks[-2].bytesize == 20 &&
    @chunks[-1] == OP_EQUAL &&
    # make sure the script_sig matches the p2sh hash from the pk_script (if there is one)
    (@chunks.size > 3 ? pay_to_script_hash(nil, nil, :check) : true)
  end
end

#is_pubkey?Boolean Also known as: is_send_to_ip?

is this a pubkey script

Returns:

  • (Boolean)


583
584
585
586
# File 'lib/bitcoin/script.rb', line 583

def is_pubkey?
  return false if @chunks.size != 2
  (@chunks[1] == OP_CHECKSIG) && @chunks[0] && (@chunks[0].is_a?(String)) && @chunks[0] != OP_RETURN
end

#is_push_only?(script_data = nil) ⇒ Boolean

Verify the script is only pushing data onto the stack

Returns:

  • (Boolean)


624
625
626
# File 'lib/bitcoin/script.rb', line 624

def is_push_only?(script_data=nil)
  check_pushes(true, false, (script_data||@input_script))
end

#is_standard?Boolean

check if script is in one of the recognized standard formats

Returns:

  • (Boolean)


578
579
580
# File 'lib/bitcoin/script.rb', line 578

def is_standard?
  is_pubkey? || is_hash160? || is_multisig? || is_p2sh?  || is_op_return? || is_witness_v0_keyhash? || is_witness_v0_scripthash?
end

#is_witness?Boolean

is this a witness script

Returns:

  • (Boolean)


609
610
611
# File 'lib/bitcoin/script.rb', line 609

def is_witness?
  @chunks.length == 2 && (0..16).include?(@chunks[0]) && @chunks[1].is_a?(String)
end

#is_witness_v0_keyhash?Boolean

is this a witness pubkey script

Returns:

  • (Boolean)


614
615
616
# File 'lib/bitcoin/script.rb', line 614

def is_witness_v0_keyhash?
  is_witness? && @chunks[0] == 0 && @chunks[1].bytesize == 20
end

#is_witness_v0_scripthash?Boolean

is this a witness script hash

Returns:

  • (Boolean)


619
620
621
# File 'lib/bitcoin/script.rb', line 619

def is_witness_v0_scripthash?
  is_witness? && @chunks[0] == 0 && @chunks[1].bytesize == 32
end

#op_0Object

An empty array of bytes is pushed onto the stack.



1186
1187
1188
# File 'lib/bitcoin/script.rb', line 1186

def op_0
  @stack << "" # []
end

#op_0notequalObject



1117
1118
1119
1120
# File 'lib/bitcoin/script.rb', line 1117

def op_0notequal
  a = pop_int
  @stack << (a != 0 ? 1 : 0)
end

#op_1Object

The number 1 is pushed onto the stack. Same as OP_TRUE



1191
1192
1193
# File 'lib/bitcoin/script.rb', line 1191

def op_1
  @stack << 1
end

#op_1addObject

1 is added to the input.



1141
1142
1143
1144
# File 'lib/bitcoin/script.rb', line 1141

def op_1add
  a = pop_int
  @stack << (a + 1)
end

#op_1negateObject

The number -1 is pushed onto the stack.



1226
1227
1228
# File 'lib/bitcoin/script.rb', line 1226

def op_1negate
  @stack << -1
end

#op_1subObject

1 is subtracted from the input.



1147
1148
1149
1150
# File 'lib/bitcoin/script.rb', line 1147

def op_1sub
  a = pop_int
  @stack << (a - 1)
end

#op_2divObject

The input is divided by 2. Currently disabled.



1129
1130
1131
1132
# File 'lib/bitcoin/script.rb', line 1129

def op_2div
  a = pop_int
  @stack << (a >> 1)
end

#op_2dropObject

Removes the top two stack items.



1331
1332
1333
# File 'lib/bitcoin/script.rb', line 1331

def op_2drop
  @stack.pop(2)
end

#op_2dupObject

Duplicates the top two stack items.



1336
1337
1338
# File 'lib/bitcoin/script.rb', line 1336

def op_2dup
  @stack.push(*@stack[-2..-1])
end

#op_2mulObject

The input is multiplied by 2. Currently disabled.



1135
1136
1137
1138
# File 'lib/bitcoin/script.rb', line 1135

def op_2mul
  a = pop_int
  @stack << (a << 1)
end

#op_2overObject

Copies the pair of items two spaces back in the stack to the front.



1206
1207
1208
1209
# File 'lib/bitcoin/script.rb', line 1206

def op_2over
  @stack << @stack[-4]
  @stack << @stack[-4]
end

#op_2rotObject

The fifth and sixth items back are moved to the top of the stack.



1306
1307
1308
1309
# File 'lib/bitcoin/script.rb', line 1306

def op_2rot
  return invalid if @stack.size < 6
  @stack[-6..-1] = [ *@stack[-4..-1], *@stack[-6..-5] ]
end

#op_2swapObject

Swaps the top two pairs of items.



1212
1213
1214
1215
1216
# File 'lib/bitcoin/script.rb', line 1212

def op_2swap
  p1 = @stack.pop(2)
  p2 = @stack.pop(2)
  @stack += p1 += p2
end

#op_3dupObject

Duplicates the top three stack items.



1341
1342
1343
# File 'lib/bitcoin/script.rb', line 1341

def op_3dup
  @stack.push(*@stack[-3..-1])
end

#op_absObject

The input is made positive.



1123
1124
1125
1126
# File 'lib/bitcoin/script.rb', line 1123

def op_abs
  a = pop_int
  @stack << a.abs
end

#op_addObject

a is added to b.



1076
1077
1078
1079
# File 'lib/bitcoin/script.rb', line 1076

def op_add
  a, b = pop_int(2)
  @stack << a + b
end

#op_boolandObject

If both a and b are not 0, the output is 1. Otherwise 0.



1064
1065
1066
1067
# File 'lib/bitcoin/script.rb', line 1064

def op_booland
  a, b = pop_int(2)
  @stack << (![a,b].any?{|n| n == 0 } ? 1 : 0)
end

#op_boolorObject

If a or b is not 0, the output is 1. Otherwise 0.



1070
1071
1072
1073
# File 'lib/bitcoin/script.rb', line 1070

def op_boolor
  a, b = pop_int(2)
  @stack << ( (a != 0 || b != 0) ? 1 : 0 )
end

#op_checkmultisig(check_callback, opts = {}) ⇒ Object

do a CHECKMULTISIG operation on the current stack, asking check_callback to do the actual signature verification.

CHECKMULTISIG does a m-of-n signatures verification on scripts of the form:

0 <sig1> <sig2> | 2 <pub1> <pub2> 2 OP_CHECKMULTISIG
0 <sig1> <sig2> | 2 <pub1> <pub2> <pub3> 3 OP_CHECKMULTISIG
0 <sig1> <sig2> <sig3> | 3 <pub1> <pub2> <pub3> 3 OP_CHECKMULTISIG

see en.bitcoin.it/wiki/BIP_0011 for details. see github.com/bitcoin/bitcoin/blob/master/src/script.cpp#L931

TODO: validate signature order TODO: take global opcode count



1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
# File 'lib/bitcoin/script.rb', line 1494

def op_checkmultisig(check_callback, opts={})
  return invalid if @stack.size < 1
  n_pubkeys = pop_int
  return invalid  unless (0..20).include?(n_pubkeys)
  #return invalid  if (nOpCount += n_pubkeys) > 201
  return invalid if @stack.size < n_pubkeys
  pubkeys = pop_string(n_pubkeys)

  return invalid if @stack.size < 1
  n_sigs = pop_int
  return invalid if n_sigs < 0 || n_sigs > n_pubkeys
  return invalid if @stack.size < n_sigs
  sigs = pop_string(n_sigs)
  drop_sigs = sigs.dup

  # Bitcoin-core removes an extra item from the stack
  @stack.pop

  subscript = sighash_subscript(drop_sigs, opts)

  success = true
  while success && n_sigs > 0
    sig, pub = sigs.pop, pubkeys.pop
    return (@stack << 0) unless Bitcoin::Script.check_pubkey_encoding?(pub, opts)
    return invalid unless Bitcoin::Script.check_signature_encoding?(sig, opts)
    unless sig && sig.size > 0
      success = false
      break
    end
    signature, hash_type = parse_sig(sig)
    if pub.size > 0 && check_callback.call(pub, signature, hash_type, subscript)
      n_sigs -= 1
    else
      sigs << sig
    end
    n_pubkeys -= 1
    success = false if n_sigs > n_pubkeys
  end

  @stack << (success ? 1 : 0)
end

#op_checkmultisigverify(check_callback, opts = {}) ⇒ Object

Same as OP_CHECKMULTISIG, but OP_VERIFY is executed afterward.



1537
1538
1539
1540
# File 'lib/bitcoin/script.rb', line 1537

def op_checkmultisigverify(check_callback, opts={})
  op_checkmultisig(check_callback, opts)
  op_verify
end

#op_checksig(check_callback, opts = {}) ⇒ Object

do a CHECKSIG operation on the current stack, asking check_callback to do the actual signature verification. This is used by Protocol::Tx#verify_input_signature



1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
# File 'lib/bitcoin/script.rb', line 1436

def op_checksig(check_callback, opts={})
  return invalid if @stack.size < 2
  pubkey = cast_to_string(@stack.pop)
  return (@stack << 0) unless Bitcoin::Script.check_pubkey_encoding?(pubkey, opts)
  drop_sigs      = [ cast_to_string(@stack[-1]) ]

  signature = cast_to_string(@stack.pop)
  return invalid unless Bitcoin::Script.check_signature_encoding?(signature, opts)
  return (@stack << 0) if signature == ""

  sig, hash_type = parse_sig(signature)

  subscript = sighash_subscript(drop_sigs, opts)

  if check_callback == nil # for tests
    @stack << 1
  else # real signature check callback
    @stack <<
      ((check_callback.call(pubkey, sig, hash_type, subscript) == true) ? 1 : 0)
  end
end

#op_checksigverify(check_callback, opts = {}) ⇒ Object

Same as OP_CHECKSIG, but OP_VERIFY is executed afterward.



1476
1477
1478
1479
# File 'lib/bitcoin/script.rb', line 1476

def op_checksigverify(check_callback, opts={})
  op_checksig(check_callback, opts)
  op_verify
end

#op_codeseparatorObject

All of the signature checking words will only match signatures to the data after the most recently-executed OP_CODESEPARATOR.



1420
1421
1422
1423
# File 'lib/bitcoin/script.rb', line 1420

def op_codeseparator
  @codehash_start = @chunks.size - @chunks.reverse.index(OP_CODESEPARATOR)
  @last_codeseparator_index = @chunk_last_index
end

#op_depthObject

Puts the number of stack items onto the stack.



1231
1232
1233
# File 'lib/bitcoin/script.rb', line 1231

def op_depth
  @stack << @stack.size
end

#op_dropObject

Removes the top stack item.



1159
1160
1161
# File 'lib/bitcoin/script.rb', line 1159

def op_drop
  @stack.pop
end

#op_dupObject

Duplicates the top stack item.



1009
1010
1011
# File 'lib/bitcoin/script.rb', line 1009

def op_dup
  @stack << (@stack[-1].dup rescue @stack[-1])
end

#op_elseObject

If the preceding OP_IF or OP_NOTIF or OP_ELSE was not executed then these statements are and if the preceding OP_IF or OP_NOTIF or OP_ELSE was executed then these statements are not.



1285
1286
1287
1288
# File 'lib/bitcoin/script.rb', line 1285

def op_else
  return if @exec_stack.empty?
  @exec_stack[-1] = !@exec_stack[-1]
end

#op_endifObject

Ends an if/else block.



1291
1292
1293
1294
# File 'lib/bitcoin/script.rb', line 1291

def op_endif
  return if @exec_stack.empty?
  @exec_stack.pop
end

#op_equalObject

Returns 1 if the inputs are exactly equal, 0 otherwise.



1164
1165
1166
1167
# File 'lib/bitcoin/script.rb', line 1164

def op_equal
  a, b = pop_string(2)
  @stack << (a == b ? 1 : 0)
end

#op_equalverifyObject

Same as OP_EQUAL, but runs OP_VERIFY afterward.



1181
1182
1183
# File 'lib/bitcoin/script.rb', line 1181

def op_equalverify
  op_equal; op_verify
end

#op_fromaltstackObject

Puts the input onto the top of the main stack. Removes it from the alt stack.



1049
1050
1051
# File 'lib/bitcoin/script.rb', line 1049

def op_fromaltstack
  @stack << @stack_alt.pop
end

#op_greaterthanObject

Returns 1 if a is greater than b, 0 otherwise.



1100
1101
1102
1103
# File 'lib/bitcoin/script.rb', line 1100

def op_greaterthan
  a, b = pop_int(2)
  @stack << (a > b ? 1 : 0)
end

#op_greaterthanorequalObject

Returns 1 if a is greater than or equal to b, 0 otherwise.



1106
1107
1108
1109
# File 'lib/bitcoin/script.rb', line 1106

def op_greaterthanorequal
  a, b = pop_int(2)
  @stack << (a >= b ? 1 : 0)
end

#op_hash160Object

The input is hashed twice: first with SHA-256 and then with RIPEMD-160.



1026
1027
1028
1029
# File 'lib/bitcoin/script.rb', line 1026

def op_hash160
  buf = pop_string
  @stack << Digest::RMD160.digest(Digest::SHA256.digest(buf))
end

#op_hash256Object

The input is hashed two times with SHA-256.



1038
1039
1040
1041
# File 'lib/bitcoin/script.rb', line 1038

def op_hash256
  buf = pop_string
  @stack << Digest::SHA256.digest(Digest::SHA256.digest(buf))
end

#op_ifObject

If the top stack value is not 0, the statements are executed. The top stack value is removed.



1265
1266
1267
1268
1269
1270
1271
1272
# File 'lib/bitcoin/script.rb', line 1265

def op_if
  value = false
  if @do_exec
    (invalid; return) if @stack.size < 1
    value = cast_to_bool(pop_string) == false ? false : true
  end
  @exec_stack << value
end

#op_ifdupObject

If the input is true, duplicate it.



1219
1220
1221
1222
1223
# File 'lib/bitcoin/script.rb', line 1219

def op_ifdup
  if cast_to_bool(@stack.last) == true
    @stack << @stack.last
  end
end

#op_lessthanObject

Returns 1 if a is less than b, 0 otherwise.



1088
1089
1090
1091
# File 'lib/bitcoin/script.rb', line 1088

def op_lessthan
  a, b = pop_int(2)
  @stack << (a < b ? 1 : 0)
end

#op_lessthanorequalObject

Returns 1 if a is less than or equal to b, 0 otherwise.



1094
1095
1096
1097
# File 'lib/bitcoin/script.rb', line 1094

def op_lessthanorequal
  a, b = pop_int(2)
  @stack << (a <= b ? 1 : 0)
end

#op_maxObject

Returns the larger of a and b.



1201
1202
1203
# File 'lib/bitcoin/script.rb', line 1201

def op_max
  @stack << pop_int(2).max
end

#op_minObject

Returns the smaller of a and b.



1196
1197
1198
# File 'lib/bitcoin/script.rb', line 1196

def op_min
  @stack << pop_int(2).min
end

#op_negateObject

The sign of the input is flipped.



1153
1154
1155
1156
# File 'lib/bitcoin/script.rb', line 1153

def op_negate
  a = pop_int
  @stack << -a
end

#op_nipObject

Removes the second-to-top stack item.



1346
1347
1348
# File 'lib/bitcoin/script.rb', line 1346

def op_nip
  @stack.delete_at(-2)
end

#op_nopObject

Does nothing



996
# File 'lib/bitcoin/script.rb', line 996

def op_nop; end

#op_nop1Object



997
# File 'lib/bitcoin/script.rb', line 997

def op_nop1; end

#op_nop10Object



1006
# File 'lib/bitcoin/script.rb', line 1006

def op_nop10; end

#op_nop2Object



998
# File 'lib/bitcoin/script.rb', line 998

def op_nop2; end

#op_nop3Object



999
# File 'lib/bitcoin/script.rb', line 999

def op_nop3; end

#op_nop4Object



1000
# File 'lib/bitcoin/script.rb', line 1000

def op_nop4; end

#op_nop5Object



1001
# File 'lib/bitcoin/script.rb', line 1001

def op_nop5; end

#op_nop6Object



1002
# File 'lib/bitcoin/script.rb', line 1002

def op_nop6; end

#op_nop7Object



1003
# File 'lib/bitcoin/script.rb', line 1003

def op_nop7; end

#op_nop8Object



1004
# File 'lib/bitcoin/script.rb', line 1004

def op_nop8; end

#op_nop9Object



1005
# File 'lib/bitcoin/script.rb', line 1005

def op_nop9; end

#op_notObject

If the input is 0 or 1, it is flipped. Otherwise the output will be 0.



1112
1113
1114
1115
# File 'lib/bitcoin/script.rb', line 1112

def op_not
  a = pop_int
  @stack << (a == 0 ? 1 : 0)
end

#op_notifObject

If the top stack value is 0, the statements are executed. The top stack value is removed.



1275
1276
1277
1278
1279
1280
1281
1282
# File 'lib/bitcoin/script.rb', line 1275

def op_notif
  value = false
  if @do_exec
    (invalid; return) if @stack.size < 1
    value = cast_to_bool(pop_string) == false ? true : false
  end
  @exec_stack << value
end

#op_numequalObject

Returns 1 if the numbers are equal, 0 otherwise.



1242
1243
1244
1245
# File 'lib/bitcoin/script.rb', line 1242

def op_numequal
  a, b = pop_int(2)
  @stack << (a == b ? 1 : 0)
end

#op_numequalverifyObject

Same as OP_NUMEQUAL, but runs OP_VERIFY afterward.



1414
1415
1416
# File 'lib/bitcoin/script.rb', line 1414

def op_numequalverify
  op_numequal; op_verify
end

#op_numnotequalObject

Returns 1 if the numbers are not equal, 0 otherwise.



1248
1249
1250
1251
# File 'lib/bitcoin/script.rb', line 1248

def op_numnotequal
  a, b = pop_int(2)
  @stack << (a != b ? 1 : 0)
end

#op_overObject

Copies the second-to-top stack item to the top.



1259
1260
1261
1262
# File 'lib/bitcoin/script.rb', line 1259

def op_over
  item = @stack[-2]
  @stack << item if item
end

#op_pickObject

The item n back in the stack is copied to the top.



1297
1298
1299
1300
1301
1302
1303
# File 'lib/bitcoin/script.rb', line 1297

def op_pick
  return invalid if @stack.size < 2
  pos = pop_int
  return invalid if (pos < 0) || (pos >= @stack.size)
  item = @stack[-(pos+1)]
  @stack << item if item
end

#op_returnObject

Marks transaction as invalid.



1254
1255
1256
# File 'lib/bitcoin/script.rb', line 1254

def op_return
  @script_invalid = true; nil
end

#op_ripemd160Object

The input is hashed using RIPEMD-160.



1032
1033
1034
1035
# File 'lib/bitcoin/script.rb', line 1032

def op_ripemd160
  buf = pop_string
  @stack << Digest::RMD160.digest(buf)
end

#op_rollObject

The item n back in the stack is moved to the top.



1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
# File 'lib/bitcoin/script.rb', line 1312

def op_roll
  return invalid if @stack.size < 2
  pos = pop_int
  return invalid if (pos < 0) || (pos >= @stack.size)
  idx = -(pos+1)
  item = @stack[idx]
  if item
    @stack.delete_at(idx)
    @stack << item if item
  end
end

#op_rotObject

The top three items on the stack are rotated to the left.



1325
1326
1327
1328
# File 'lib/bitcoin/script.rb', line 1325

def op_rot
  return if @stack.size < 3
  @stack[-3..-1] = [ @stack[-2], @stack[-1], @stack[-3] ]
end

#op_sha1Object

The input is hashed using SHA-1.



1020
1021
1022
1023
# File 'lib/bitcoin/script.rb', line 1020

def op_sha1
  buf = pop_string
  @stack << Digest::SHA1.digest(buf)
end

#op_sha256Object

The input is hashed using SHA-256.



1014
1015
1016
1017
# File 'lib/bitcoin/script.rb', line 1014

def op_sha256
  buf = pop_string
  @stack << Digest::SHA256.digest(buf)
end

#op_sizeObject

Returns the length of the input string.



1351
1352
1353
1354
1355
1356
1357
1358
# File 'lib/bitcoin/script.rb', line 1351

def op_size
  item = @stack[-1]
  size = case item
         when String; item.bytesize
         when Numeric; OpenSSL::BN.new(item.to_s).to_mpi.size - 4
         end
  @stack << size
end

#op_subObject

b is subtracted from a.



1082
1083
1084
1085
# File 'lib/bitcoin/script.rb', line 1082

def op_sub
  a, b = pop_int(2)
  @stack << a - b
end

#op_swapObject

The top two items on the stack are swapped.



1059
1060
1061
# File 'lib/bitcoin/script.rb', line 1059

def op_swap
  @stack[-2..-1] = @stack[-2..-1].reverse if @stack[-2]
end

#op_toaltstackObject

Puts the input onto the top of the alt stack. Removes it from the main stack.



1044
1045
1046
# File 'lib/bitcoin/script.rb', line 1044

def op_toaltstack
  @stack_alt << @stack.pop
end

#op_tuckObject

The item at the top of the stack is copied and inserted before the second-to-top item.



1054
1055
1056
# File 'lib/bitcoin/script.rb', line 1054

def op_tuck
  @stack[-2..-1] = [ @stack[-1], *@stack[-2..-1] ]
end

#op_verObject

Transaction is invalid unless occuring in an unexecuted OP_IF branch



1361
1362
1363
# File 'lib/bitcoin/script.rb', line 1361

def op_ver
  invalid if @do_exec
end

#op_verifyObject

Marks transaction as invalid if top stack value is not true. True is removed, but false is not.



1170
1171
1172
1173
1174
1175
1176
1177
1178
# File 'lib/bitcoin/script.rb', line 1170

def op_verify
  res = pop_int
  if cast_to_bool(res) == false
    @stack << res
    @script_invalid = true # raise 'transaction invalid' ?
  else
    @script_invalid = false
  end
end

#op_withinObject

Returns 1 if x is within the specified range (left-inclusive), 0 otherwise.



1236
1237
1238
1239
# File 'lib/bitcoin/script.rb', line 1236

def op_within
  bn1, bn2, bn3 = pop_int(3)
  @stack << ( (bn2 <= bn1 && bn1 < bn3) ? 1 : 0 )
end

#parse(bytes, offset = 0) ⇒ Object

parse raw script



197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
# File 'lib/bitcoin/script.rb', line 197

def parse(bytes, offset=0)
  program = bytes.unpack("C*")
  chunks = []
  until program.empty?
    opcode = program.shift

    if (opcode > 0) && (opcode < OP_PUSHDATA1)
      len, tmp = opcode, program[0]
      chunks << program.shift(len).pack("C*")

      # 0x16 = 22 due to OP_2_16 from_string parsing
      if len == 1 && tmp && tmp <= 22
        chunks.last.bitcoin_pushdata = OP_PUSHDATA0
        chunks.last.bitcoin_pushdata_length = len
      else
        raise "invalid OP_PUSHDATA0" if len != chunks.last.bytesize
      end
    elsif (opcode == OP_PUSHDATA1)
      len = program.shift(1)[0]
      chunks << program.shift(len).pack("C*")

      unless len > OP_PUSHDATA1 && len <= 0xff
        chunks.last.bitcoin_pushdata = OP_PUSHDATA1
        chunks.last.bitcoin_pushdata_length = len
      else
        raise "invalid OP_PUSHDATA1" if len != chunks.last.bytesize
      end
    elsif (opcode == OP_PUSHDATA2)
      len = program.shift(2).pack("C*").unpack("v")[0]
      chunks << program.shift(len).pack("C*")

      unless len > 0xff && len <= 0xffff
        chunks.last.bitcoin_pushdata = OP_PUSHDATA2
        chunks.last.bitcoin_pushdata_length = len
      else
        raise "invalid OP_PUSHDATA2" if len != chunks.last.bytesize
      end
    elsif (opcode == OP_PUSHDATA4)
      len = program.shift(4).pack("C*").unpack("V")[0]
      chunks << program.shift(len).pack("C*")

      unless len > 0xffff # && len <= 0xffffffff
        chunks.last.bitcoin_pushdata = OP_PUSHDATA4
        chunks.last.bitcoin_pushdata_length = len
      else
        raise "invalid OP_PUSHDATA4" if len != chunks.last.bytesize
      end
    else
      chunks << opcode
    end
  end
  chunks
rescue => ex
  # bail out! #run returns false but serialization roundtrips still create the right payload.
  chunks.pop if ex.message.include?("invalid OP_PUSHDATA")
  @parse_invalid = true
  c = bytes.unpack("C*").pack("C*")
  c.bitcoin_pushdata = OP_PUSHDATA_INVALID
  c.bitcoin_pushdata_length = c.bytesize
  chunks << c
end

#pay_to_script_hash(block_timestamp, opts, check_callback) ⇒ Object

pay_to_script_hash: en.bitcoin.it/wiki/BIP_0016

<sig> OP_CHECKSIG | OP_HASH160 <script_hash> OP_EQUAL



526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
# File 'lib/bitcoin/script.rb', line 526

def pay_to_script_hash(block_timestamp, opts, check_callback)
  return false if @chunks.size < 4
  *rest, script, _, script_hash, _ = @chunks
  script = rest.pop if script == OP_CODESEPARATOR
  script, script_hash = cast_to_string(script), cast_to_string(script_hash)

  return false unless Bitcoin.hash160(script.unpack("H*")[0]) == script_hash.unpack("H*")[0]
  return true  if check_callback == :check

  script = self.class.new(to_binary(rest) + script).inner_p2sh!(script)
  result = script.run(block_timestamp, opts, &check_callback)
  @debug = script.debug
  @stack = script.stack # Set the execution stack to match the redeem script, so checks on stack contents at end of script execution validate correctly
  result
end

#pop_int(count = nil) ⇒ Object



1365
1366
1367
1368
# File 'lib/bitcoin/script.rb', line 1365

def pop_int(count=nil)
  return cast_to_bignum(@stack.pop) unless count
  @stack.pop(count).map{|i| cast_to_bignum(i) }
end

#pop_string(count = nil) ⇒ Object



1370
1371
1372
1373
# File 'lib/bitcoin/script.rb', line 1370

def pop_string(count=nil)
  return cast_to_string(@stack.pop) unless count
  @stack.pop(count).map{|i| cast_to_string(i) }
end

#pushes_are_canonical?(script_data = nil) ⇒ Boolean

Make sure opcodes used to push data match their intended length ranges

Returns:

  • (Boolean)


629
630
631
# File 'lib/bitcoin/script.rb', line 629

def pushes_are_canonical?(script_data=nil)
  check_pushes(false, true, (script_data||@raw))
end

#run(block_timestamp = Time.now.to_i, opts = {}, &check_callback) ⇒ Object

run the script. check_callback is called for OP_CHECKSIG operations



439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
# File 'lib/bitcoin/script.rb', line 439

def run(block_timestamp=Time.now.to_i, opts={}, &check_callback)
  return false if @parse_invalid

  #p [to_string, block_timestamp, is_p2sh?]
  @script_invalid = true if @raw_byte_sizes.any?{|size| size > 10_000 }
  @last_codeseparator_index = 0

  if block_timestamp >= 1333238400 # Pay to Script Hash (BIP 0016)
    return pay_to_script_hash(block_timestamp, opts, check_callback)  if is_p2sh?
  end

  @debug = []
  @chunks.each.with_index{|chunk,idx|
    break if invalid?
    @chunk_last_index = idx

    @debug << @stack.map{|i| i.unpack("H*") rescue i}
    @do_exec = @exec_stack.count(false) == 0 ? true : false
    #p [@stack, @do_exec]

    case chunk
    when Bitcoin::Integer
      if DISABLED_OPCODES.include?(chunk)
        @script_invalid = true
        @debug << "DISABLED_#{OPCODES[chunk]}"
        break
      end

      next @debug.pop  unless (@do_exec || (OP_IF <= chunk && chunk <= OP_ENDIF))

      case chunk
      when *OPCODES_METHOD.keys
        m = method( n=OPCODES_METHOD[chunk] )
        @debug << n.to_s.upcase
        # invoke opcode method
        case m.arity
        when 0
          m.call
        when 1
          m.call(check_callback)
        when -2 # One fixed parameter, one optional
          m.call(check_callback, opts)
        else
          puts "Bitcoin::Script: opcode #{name} method parameters invalid"
        end
      when *OP_2_16
        @stack << OP_2_16.index(chunk) + 2
        @debug << "OP_#{chunk-80}"
      else
        name = OPCODES[chunk] || chunk
        puts "Bitcoin::Script: opcode #{name} unkown or not implemented\n#{to_string.inspect}"
        raise "opcode #{name} unkown or not implemented"
      end
    when String
      if @do_exec
        @debug << "PUSH DATA #{chunk.unpack("H*")[0]}"
        @stack << chunk
      else
        @debug.pop
      end
    end
  }
  @debug << @stack.map{|i| i.unpack("H*") rescue i } #if @do_exec

  if @script_invalid
    @stack << 0
    @debug << "INVALID TRANSACTION"
  end

  @debug << "RESULT"
  return false if @stack.empty?
  return false if cast_to_bool(@stack.pop) == false
  true
end

#sighash_subscript(drop_sigs, opts = {}) ⇒ Object



1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
# File 'lib/bitcoin/script.rb', line 1458

def sighash_subscript(drop_sigs, opts = {})
  if opts[:fork_id]
    drop_sigs.reject! do |signature|
      if signature && signature.size > 0
        _, hash_type = parse_sig(signature)
        (hash_type&SIGHASH_TYPE[:forkid]) != 0
      end
    end
  end

  if inner_p2sh? && @inner_script_code
    ::Bitcoin::Script.new(@inner_script_code).to_binary_without_signatures(drop_sigs)
  else
    to_binary_without_signatures(drop_sigs)
  end
end

#sigops_count_accurate(is_accurate) ⇒ Object

This matches CScript::GetSigOpCount(bool fAccurate) Note: this does not cover P2SH script which is to be unserialized

and checked explicitly when validating blocks.


930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
# File 'lib/bitcoin/script.rb', line 930

def sigops_count_accurate(is_accurate)
  count = 0
  last_opcode = nil
  @chunks.each do |chunk| # pushdate or opcode
    if chunk == OP_CHECKSIG || chunk == OP_CHECKSIGVERIFY
      count += 1
    elsif chunk == OP_CHECKMULTISIG || chunk == OP_CHECKMULTISIGVERIFY
      # Accurate mode counts exact number of pubkeys required (not signatures, but pubkeys!). Only used in P2SH scripts.
      # Inaccurate mode counts every multisig as 20 signatures.
      if is_accurate && last_opcode && last_opcode.is_a?(Bitcoin::Integer) && last_opcode >= OP_1 && last_opcode <= OP_16
        count += ::Bitcoin::Script.decode_OP_N(last_opcode)
      else
        count += 20
      end
    end
    last_opcode = chunk
  end
  count
end

#sigops_count_for_p2shObject

This method applies to script_sig that is an input for p2sh output. Bitcoind has somewhat special way to return count for invalid input scripts: it returns 0 when the opcode can’t be parsed or when it’s over OP_16. Also, if the OP_N is used anywhere it’s treated as 0-length data. See CScript::GetSigOpCount(const CScript& scriptSig) in bitcoind.



955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
# File 'lib/bitcoin/script.rb', line 955

def sigops_count_for_p2sh
  # This is a pay-to-script-hash scriptPubKey;
  # get the last item that the scriptSig
  # pushes onto the stack:

  return 0 if @chunks.size == 0

  data = nil
  @chunks.each do |chunk|
    case chunk
    when Bitcoin::Integer
      data = ""
      return 0 if chunk > OP_16
    when String
      data = chunk
    end
  end
  return 0 if data == ""

  ::Bitcoin::Script.new(data).sigops_count_accurate(true)
end

#subscript_codeseparator(separator_index) ⇒ Object

Returns a script that deleted the script before the index specified by separator_index.



312
313
314
315
316
317
318
319
320
# File 'lib/bitcoin/script.rb', line 312

def subscript_codeseparator(separator_index)
  buf = []
  process_separator_index = 0
  (chunks || @chunks).each{|chunk|
    buf << chunk if process_separator_index == separator_index
    process_separator_index += 1 if chunk == OP_CODESEPARATOR and process_separator_index < separator_index
  }
  to_binary(buf)
end

#to_binary(chunks = nil) ⇒ Object Also known as: to_payload



282
283
284
285
286
287
288
289
290
# File 'lib/bitcoin/script.rb', line 282

def to_binary(chunks=nil)

  (chunks || @chunks).map{|chunk|
    case chunk
    when Bitcoin::Integer; [chunk].pack("C*")
    when String; self.class.pack_pushdata(chunk)
    end
  }.join
end

#to_binary_without_signatures(drop_signatures, chunks = nil) ⇒ Object



293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
# File 'lib/bitcoin/script.rb', line 293

def to_binary_without_signatures(drop_signatures, chunks=nil)
  buf = []
  (chunks || @chunks).each.with_index{|chunk,idx|
    if chunk == OP_CODESEPARATOR and idx <= @last_codeseparator_index
      buf.clear
    elsif chunk == OP_CODESEPARATOR
      if idx == @script_codeseparator_index
        break
      else
        # skip
      end
    elsif drop_signatures.none?{|e| e == chunk }
      buf << chunk
    end
  }
  to_binary(buf)
end

#to_string(chunks = nil) ⇒ Object

string representation of the script



260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# File 'lib/bitcoin/script.rb', line 260

def to_string(chunks=nil)
  string = ""
  (chunks || @chunks).each.with_index{|i,idx|
    string << " " unless idx == 0
    string << case i
    when Bitcoin::Integer
      if opcode = OPCODES_PARSE_BINARY[i]
        opcode
      else
        "(opcode-#{i})"
      end
    when String
      if i.bitcoin_pushdata
        "#{i.bitcoin_pushdata}:#{i.bitcoin_pushdata_length}:".force_encoding('binary') + i.unpack("H*")[0]
      else
        i.unpack("H*")[0]
      end
    end
  }
  string
end

#typeObject

get type of this tx



672
673
674
675
676
677
678
679
680
681
682
# File 'lib/bitcoin/script.rb', line 672

def type
  if is_hash160?;                 :hash160
  elsif is_pubkey?;               :pubkey
  elsif is_multisig?;             :multisig
  elsif is_p2sh?;                 :p2sh
  elsif is_op_return?;            :op_return
  elsif is_witness_v0_keyhash?;   :witness_v0_keyhash
  elsif is_witness_v0_scripthash?;:witness_v0_scripthash
  else;                           :unknown
  end
end