Class: Bitcoin::Script

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

Defined Under Namespace

Classes: ScriptOpcodeError

Constant Summary collapse

OP_1 =
81
OP_TRUE =
81
OP_0 =
0
OP_FALSE =
0
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_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 =
{}
OPCODES_METHOD =
SIGHASH_TYPE =
{ all: 1, none: 2, single: 3, anyonecanpay: 128 }

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(bytes, offset = 0) ⇒ Script

create a new script. bytes is typically input_script + output_script



140
141
142
143
144
145
# File 'lib/bitcoin/script.rb', line 140

def initialize(bytes, offset=0)
  @raw = bytes
  @stack, @stack_alt, @exec_stack = [], [], []
  @chunks = parse(bytes, offset)
  @do_exec = true
end

Instance Attribute Details

#chunksObject (readonly)

Returns the value of attribute chunks.



137
138
139
# File 'lib/bitcoin/script.rb', line 137

def chunks
  @chunks
end

#debugObject (readonly)

Returns the value of attribute debug.



137
138
139
# File 'lib/bitcoin/script.rb', line 137

def debug
  @debug
end

#rawObject (readonly)

Returns the value of attribute raw.



137
138
139
# File 'lib/bitcoin/script.rb', line 137

def raw
  @raw
end

Class Method Details

.binary_from_string(script_string) ⇒ Object

raw script binary of a string representation



297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
# File 'lib/bitcoin/script.rb', line 297

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?(Fixnum)
             i < 256 ? [i].pack("C") : [OpenSSL::BN.new(i.to_s,10).to_hex].pack("H*")
           else
             i
           end if i
  }
  buf
end

.drop_signatures(script_pubkey, drop_signatures) ⇒ Object



397
398
399
400
# File 'lib/bitcoin/script.rb', line 397

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(script_string) ⇒ Object

script object of a string representation



290
291
292
# File 'lib/bitcoin/script.rb', line 290

def self.from_string(script_string)
  new(binary_from_string(script_string))
end

.is_canonical_pubkey?(pubkey) ⇒ Boolean

Returns:

  • (Boolean)


1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
# File 'lib/bitcoin/script.rb', line 1094

def self.is_canonical_pubkey?(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_canonical_signature?(sig) ⇒ Boolean

Returns:

  • (Boolean)


1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
# File 'lib/bitcoin/script.rb', line 1110

def self.is_canonical_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*")

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

  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

  # TODO: add/port rest from bitcoind

  true
end

.pack_pushdata(data) ⇒ Object



253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
# File 'lib/bitcoin/script.rb', line 253

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



274
275
276
277
278
279
280
281
282
283
284
285
286
287
# File 'lib/bitcoin/script.rb', line 274

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

.to_address_script(address) ⇒ Object



541
542
543
544
545
546
547
# File 'lib/bitcoin/script.rb', line 541

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)
  end
end

.to_hash160_script(hash160) ⇒ Object

generate hash160 tx for given address



529
530
531
532
533
# File 'lib/bitcoin/script.rb', line 529

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 tx for given pubkeys, expecting m signatures



550
551
552
553
# File 'lib/bitcoin/script.rb', line 550

def self.to_multisig_script(m, *pubkeys)
  pubs = pubkeys.map{|pk|p=[pk].pack("H*"); [p.bytesize].pack("C") + p}
  [ [80 + m.to_i].pack("C"), *pubs, [80 + pubs.size].pack("C"), "\xAE"].join
end

.to_multisig_script_sig(*sigs) ⇒ Object



580
581
582
# File 'lib/bitcoin/script.rb', line 580

def self.to_multisig_script_sig(*sigs)
  from_string("0 #{sigs.map{|s|s.unpack('H*')[0]}.join(' ')}").raw
end

.to_p2sh_script(p2sh) ⇒ Object



535
536
537
538
539
# File 'lib/bitcoin/script.rb', line 535

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



523
524
525
526
# File 'lib/bitcoin/script.rb', line 523

def self.to_pubkey_script(pubkey)
  pk = [pubkey].pack("H*")
  [[pk.bytesize].pack("C"), pk, "\xAC"].join
end

.to_pubkey_script_sig(signature, pubkey) ⇒ Object

generate pubkey script sig for given signature and pubkey



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

def self.to_pubkey_script_sig(signature, pubkey)
  hash_type = "\x01"
  #pubkey = [pubkey].pack("H*") if pubkey.bytesize != 65
  return [ [signature.bytesize+1].pack("C"), signature, hash_type ].join unless pubkey

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

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

  [ [signature.bytesize+1].pack("C"), signature, hash_type, [pubkey.bytesize].pack("C"), pubkey ].join
end

.to_signature_pubkey_script(*a) ⇒ Object

alias for #to_pubkey_script_sig



576
577
578
# File 'lib/bitcoin/script.rb', line 576

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

Instance Method Details

#cast_to_bignum(buf) ⇒ Object



961
962
963
964
965
966
967
# File 'lib/bitcoin/script.rb', line 961

def cast_to_bignum(buf)
  case buf
  when Numeric; buf
  when String; 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_string(buf) ⇒ Object



969
970
971
972
973
974
975
# File 'lib/bitcoin/script.rb', line 969

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

#codehash_script(opcode) ⇒ Object



988
989
990
991
992
993
# File 'lib/bitcoin/script.rb', line 988

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

#get_addressObject

get single address, or first for multisig script



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

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)



508
509
510
511
512
513
514
# File 'lib/bitcoin/script.rb', line 508

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?
  []
end

#get_hash160Object

get the hash160 for this hash160 or pubkey script



477
478
479
480
481
# File 'lib/bitcoin/script.rb', line 477

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?
end

#get_hash160_addressObject

get the hash160 address for this hash160 script



484
485
486
# File 'lib/bitcoin/script.rb', line 484

def get_hash160_address
  Bitcoin.hash160_to_address(get_hash160)
end

#get_multisig_addressesObject

get the pubkey addresses for this multisig script



494
495
496
497
498
499
500
501
# File 'lib/bitcoin/script.rb', line 494

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
  }.compact
end

#get_multisig_pubkeysObject

get the public keys for this multisig script



489
490
491
# File 'lib/bitcoin/script.rb', line 489

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

#get_p2sh_addressObject



503
504
505
# File 'lib/bitcoin/script.rb', line 503

def get_p2sh_address
  Bitcoin.hash160_to_p2sh_address(get_hash160)
end

#get_pubkeyObject

get the public key for this pubkey script



466
467
468
469
# File 'lib/bitcoin/script.rb', line 466

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



472
473
474
# File 'lib/bitcoin/script.rb', line 472

def get_pubkey_address
  Bitcoin.pubkey_to_address(get_pubkey)
end

#get_signatures_requiredObject



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

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

#inner_p2sh!(script = nil) ⇒ Object



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

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

#inner_p2sh?Boolean

Returns:

  • (Boolean)


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

def inner_p2sh?; @inner_p2sh; end

#invalidObject



393
394
395
# File 'lib/bitcoin/script.rb', line 393

def invalid
  @script_invalid = true; nil
end

#invalid?Boolean

Returns:

  • (Boolean)


327
328
329
# File 'lib/bitcoin/script.rb', line 327

def invalid?
  @script_invalid ||= false
end

#is_hash160?Boolean

is this a hash160 (address) tx

Returns:

  • (Boolean)


442
443
444
445
446
447
# File 'lib/bitcoin/script.rb', line 442

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 tx

Returns:

  • (Boolean)


450
451
452
453
# File 'lib/bitcoin/script.rb', line 450

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

#is_pay_to_script_hash?Boolean Also known as: is_p2sh?

Returns:

  • (Boolean)


422
423
424
425
426
# File 'lib/bitcoin/script.rb', line 422

def is_pay_to_script_hash?
  return false  unless @chunks[-2].is_a?(String)
  @chunks.size >= 3 && @chunks[-3] == OP_HASH160 &&
    @chunks[-2].bytesize == 20 && @chunks[-1] == OP_EQUAL
end

#is_pubkey?Boolean Also known as: is_send_to_ip?

is this a pubkey tx

Returns:

  • (Boolean)


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

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

#is_standard?Boolean

check if script is in one of the recognized standard formats

Returns:

  • (Boolean)


430
431
432
# File 'lib/bitcoin/script.rb', line 430

def is_standard?
  is_pubkey? || is_hash160? || is_multisig? || is_p2sh?
end

#op_0Object

An empty array of bytes is pushed onto the stack.



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

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

#op_0notequalObject



713
714
715
716
# File 'lib/bitcoin/script.rb', line 713

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



787
788
789
# File 'lib/bitcoin/script.rb', line 787

def op_1
  @stack << 1
end

#op_1addObject

1 is added to the input.



737
738
739
740
# File 'lib/bitcoin/script.rb', line 737

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

#op_1negateObject

The number -1 is pushed onto the stack.



822
823
824
# File 'lib/bitcoin/script.rb', line 822

def op_1negate
  @stack << -1
end

#op_1subObject



742
743
744
745
# File 'lib/bitcoin/script.rb', line 742

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

#op_2divObject

The input is divided by 2. Currently disabled.



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

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

#op_2dropObject

Removes the top two stack items.



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

def op_2drop
  @stack.pop(2)
end

#op_2dupObject

Duplicates the top two stack items.



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

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

#op_2mulObject

The input is multiplied by 2. Currently disabled.



731
732
733
734
# File 'lib/bitcoin/script.rb', line 731

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.



802
803
804
805
# File 'lib/bitcoin/script.rb', line 802

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

#op_2swapObject

Swaps the top two pairs of items.



808
809
810
811
812
# File 'lib/bitcoin/script.rb', line 808

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

#op_3dupObject

Duplicates the top three stack items.



927
928
929
# File 'lib/bitcoin/script.rb', line 927

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

#op_absObject

The input is made positive.



719
720
721
722
# File 'lib/bitcoin/script.rb', line 719

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

#op_addObject

a is added to b.



672
673
674
675
# File 'lib/bitcoin/script.rb', line 672

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.



660
661
662
663
# File 'lib/bitcoin/script.rb', line 660

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.



666
667
668
669
# File 'lib/bitcoin/script.rb', line 666

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

#op_checkmultisig(check_callback) ⇒ 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



1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
# File 'lib/bitcoin/script.rb', line 1044

def op_checkmultisig(check_callback)
  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 = drop_sigs = pop_string(n_sigs)

  @stack.pop if @stack[-1] && cast_to_bignum(@stack[-1]) == 0 # remove OP_0 from stack

  if inner_p2sh?
    script_code = @inner_script_code || to_binary_without_signatures(drop_sigs)
    drop_sigs = nil
  else
    script_code, drop_sigs = nil, nil
  end

  success = true
  while success && n_sigs > 0
    sig, pub = sigs.pop, pubkeys.pop
    signature, hash_type = parse_sig(sig)
    if check_callback.call(pub, signature, hash_type, drop_sigs, script_code)
      n_sigs -= 1
    else
      sigs << sig
    end
    n_pubkeys -= 1
    success = false if n_sigs > n_pubkeys
  end

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

#op_checksig(check_callback) ⇒ 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



999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
# File 'lib/bitcoin/script.rb', line 999

def op_checksig(check_callback)
  return invalid if @stack.size < 2
  pubkey = @stack.pop
  #return (@stack << 0) unless Bitcoin::Script.is_canonical_pubkey?(pubkey) # only for isStandard
  drop_sigs      = [ @stack[-1] ]

  signature = cast_to_string(@stack.pop)
  #return (@stack << 0) unless Bitcoin::Script.is_canonical_signature?(signature) # only for isStandard
  return (@stack << 0) if signature == ""

  sig, hash_type = parse_sig(signature)

  if inner_p2sh?
    script_code = @inner_script_code || to_binary_without_signatures(drop_sigs)
    drop_sigs = nil
  else
    script_code, drop_sigs = nil, nil
  end

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

#op_checksigverify(check_callback) ⇒ Object



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

def op_checksigverify(check_callback)
  op_checksig(check_callback)
  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.



984
985
986
# File 'lib/bitcoin/script.rb', line 984

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

#op_depthObject

Puts the number of stack items onto the stack.



827
828
829
# File 'lib/bitcoin/script.rb', line 827

def op_depth
  @stack << @stack.size
end

#op_dropObject

Removes the top stack item.



754
755
756
# File 'lib/bitcoin/script.rb', line 754

def op_drop
  @stack.pop
end

#op_dupObject

Duplicates the top stack item.



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

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.



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

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

#op_endifObject

Ends an if/else block.



887
888
889
890
# File 'lib/bitcoin/script.rb', line 887

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

#op_equalObject

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



759
760
761
762
763
# File 'lib/bitcoin/script.rb', line 759

def op_equal
  #a, b = @stack.pop(2)
  a, b = pop_int(2)
  @stack << (a == b ? 1 : 0)
end

#op_equalverifyObject

Same as OP_EQUAL, but runs OP_VERIFY afterward.



777
778
779
# File 'lib/bitcoin/script.rb', line 777

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.



645
646
647
# File 'lib/bitcoin/script.rb', line 645

def op_fromaltstack
  @stack << @stack_alt.pop
end

#op_greaterthanObject

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



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

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.



702
703
704
705
# File 'lib/bitcoin/script.rb', line 702

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.



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

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.



634
635
636
637
# File 'lib/bitcoin/script.rb', line 634

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.



861
862
863
864
865
866
867
868
# File 'lib/bitcoin/script.rb', line 861

def op_if
  value = false
  if @do_exec
    return if @stack.size < 1
    value = pop_int == 1 ? true : false
  end
  @exec_stack << value
end

#op_ifdupObject

If the input is true, duplicate it.



815
816
817
818
819
# File 'lib/bitcoin/script.rb', line 815

def op_ifdup
  if cast_to_bignum(@stack.last) != 0
    @stack << @stack.last
  end
end

#op_lessthanObject

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



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

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.



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

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

#op_maxObject

Returns the larger of a and b.



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

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

#op_minObject

Returns the smaller of a and b.



792
793
794
# File 'lib/bitcoin/script.rb', line 792

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

#op_negateObject

The sign of the input is flipped.



748
749
750
751
# File 'lib/bitcoin/script.rb', line 748

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

#op_nipObject

Removes the second-to-top stack item.



932
933
934
# File 'lib/bitcoin/script.rb', line 932

def op_nip
  @stack.delete_at(-2)
end

#op_nopObject

Does nothing



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

def op_nop; end

#op_nop1Object

op_eval: en.bitcoin.it/wiki/BIP_0012

the BIP was never accepted and must be handled as old OP_NOP1


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

def op_nop1; end

#op_nop10Object



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

def op_nop10; end

#op_nop2Object



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

def op_nop2; end

#op_nop3Object



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

def op_nop3; end

#op_nop4Object



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

def op_nop4; end

#op_nop5Object



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

def op_nop5; end

#op_nop6Object



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

def op_nop6; end

#op_nop7Object



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

def op_nop7; end

#op_nop8Object



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

def op_nop8; end

#op_nop9Object



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

def op_nop9; end

#op_notObject

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



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

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.



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

def op_notif
  value = false
  if @do_exec
    return if @stack.size < 1
    value = pop_int == 1 ? false : true
  end
  @exec_stack << value
end

#op_numequalObject

Returns 1 if the numbers are equal, 0 otherwise.



838
839
840
841
# File 'lib/bitcoin/script.rb', line 838

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.



978
979
980
# File 'lib/bitcoin/script.rb', line 978

def op_numequalverify
  op_numequal; op_verify
end

#op_numnotequalObject

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



844
845
846
847
# File 'lib/bitcoin/script.rb', line 844

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.



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

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.



893
894
895
896
897
# File 'lib/bitcoin/script.rb', line 893

def op_pick
  pos = pop_int
  item = @stack[-(pos+1)]
  @stack << item if item
end

#op_returnObject

Marks transaction as invalid.



850
851
852
# File 'lib/bitcoin/script.rb', line 850

def op_return
  @script_invalid = true; nil
end

#op_ripemd160Object

The input is hashed using RIPEMD-160.



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

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.



900
901
902
903
904
905
906
907
908
# File 'lib/bitcoin/script.rb', line 900

def op_roll
  pos = pop_int
  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.



911
912
913
914
# File 'lib/bitcoin/script.rb', line 911

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.



616
617
618
619
# File 'lib/bitcoin/script.rb', line 616

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

#op_sha256Object

The input is hashed using SHA-256.



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

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

#op_sizeObject

Returns the length of the input string.



937
938
939
940
941
942
943
944
# File 'lib/bitcoin/script.rb', line 937

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.



678
679
680
681
# File 'lib/bitcoin/script.rb', line 678

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

#op_swapObject

The top two items on the stack are swapped.



655
656
657
# File 'lib/bitcoin/script.rb', line 655

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.



640
641
642
# File 'lib/bitcoin/script.rb', line 640

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.



650
651
652
# File 'lib/bitcoin/script.rb', line 650

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



947
948
949
# File 'lib/bitcoin/script.rb', line 947

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.



766
767
768
769
770
771
772
773
774
# File 'lib/bitcoin/script.rb', line 766

def op_verify
  res = pop_int
  if res == 0
    @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.



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

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



153
154
155
156
157
158
159
160
161
162
163
164
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/bitcoin/script.rb', line 153

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

    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 <= 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 Exception => ex
  # bail out! #run returns false but serialization roundtrips still create the right payload.
  @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(check_callback) ⇒ Object

pay_to_script_hash: en.bitcoin.it/wiki/BIP_0016

<sig> OP_CHECKSIG | OP_HASH160 <script_hash> OP_EQUAL



405
406
407
408
409
410
411
412
413
414
415
416
417
# File 'lib/bitcoin/script.rb', line 405

def pay_to_script_hash(check_callback)
  return false if @chunks.size < 4
  *rest, script, _, script_hash, _ = @chunks
  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]
  rest.delete_at(0) if rest[0] && cast_to_bignum(rest[0]) == 0

  script = self.class.new(to_binary(rest) + script).inner_p2sh!(script)
  result = script.run(&check_callback)
  @debug = script.debug
  result
end

#pop_int(count = nil) ⇒ Object



951
952
953
954
# File 'lib/bitcoin/script.rb', line 951

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



956
957
958
959
# File 'lib/bitcoin/script.rb', line 956

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

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

run the script. check_callback is called for OP_CHECKSIG operations



332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
# File 'lib/bitcoin/script.rb', line 332

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

  #p [to_string, block_timestamp, is_p2sh?]
  @script_invalid = true if @raw.bytesize > 10_000

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

  @debug = []
  @chunks.each{|chunk|
    break if invalid?

    @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 Fixnum
      if DISABLED_OPCODES.include?(chunk)
        @script_invalid = true
        @debug << "DISABLED_#{OPCODES[chunk]}"
        break
      end

      next 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
        (m.arity == 1) ? m.call(check_callback) : m.call  # invoke opcode method
      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
      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 [0, ''].include?(@stack.pop)
  true
end

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



237
238
239
240
241
242
243
244
# File 'lib/bitcoin/script.rb', line 237

def to_binary(chunks=nil)
  (chunks || @chunks).map{|chunk|
    case chunk
    when Fixnum; [chunk].pack("C*")
    when String; self.class.pack_pushdata(chunk)
    end
  }.join
end

#to_binary_without_signatures(drop_signatures, chunks = nil) ⇒ Object



248
249
250
# File 'lib/bitcoin/script.rb', line 248

def to_binary_without_signatures(drop_signatures, chunks=nil)
  to_binary( (chunks || @chunks).select{|i| drop_signatures.none?{|e| e == i } } )
end

#to_string(chunks = nil) ⇒ Object

string representation of the script



215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
# File 'lib/bitcoin/script.rb', line 215

def to_string(chunks=nil)
  string = ""
  (chunks || @chunks).each.with_index{|i,idx|
    string << " " unless idx == 0
    string << case i
    when Fixnum
      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



456
457
458
459
460
461
462
463
# File 'lib/bitcoin/script.rb', line 456

def type
  if is_hash160?;     :hash160
  elsif is_pubkey?;   :pubkey
  elsif is_multisig?; :multisig
  elsif is_p2sh?;     :p2sh
  else;               :unknown
  end
end