/
script.rb
1674 lines (1435 loc) · 48.6 KB
/
script.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
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
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
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
326
327
328
329
330
331
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
392
393
394
395
396
397
398
399
400
401
402
403
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
433
434
435
436
437
438
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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
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
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# encoding: ascii-8bit
require 'bitcoin'
class Bitcoin::Script
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 = 238 # 0xEE
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] }.flatten]
OPCODES[0] = "0"
OPCODES[81] = "1"
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.each{|k,v| OPCODES_PARSE_BINARY[k] = v }
OP_2_16.each{|i| OPCODES_PARSE_BINARY[i] = (OP_2_16.index(i)+2).to_s }
OPCODES_PARSE_STRING = {}
OPCODES.each{|k,v| OPCODES_PARSE_STRING[v] = k }
OPCODES_ALIAS.each{|k,v| OPCODES_PARSE_STRING[k] = v }
2.upto(16).each{|i| OPCODES_PARSE_STRING["OP_#{i}"] = OP_2_16[i-2] }
2.upto(16).each{|i| OPCODES_PARSE_STRING["#{i}" ] = OP_2_16[i-2] }
[1,2,4].each{|i| OPCODES_PARSE_STRING.delete("OP_PUSHDATA#{i}") }
SIGHASH_TYPE = {
all: 1,
none: 2,
single: 3,
forkid: 64,
anyonecanpay: 128
}.freeze
attr_reader :raw, :chunks, :debug, :stack
# create a new script. +bytes+ is typically input_script + output_script
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
class ::String
attr_accessor :bitcoin_pushdata
attr_accessor :bitcoin_pushdata_length
end
# parse raw script
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
# string representation of the script
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
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
alias :to_payload :to_binary
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
# Returns a script that deleted the script before the index specified by separator_index.
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
# Adds opcode (OP_0, OP_1, ... OP_CHECKSIG etc.)
# Returns self.
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
# Adds the opcode corresponding to the given number. Returns self.
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
# 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.
def append_pushdata(pushdata_string)
raise "Pushdata should be a string" if !pushdata_string.is_a?(String)
@chunks << pushdata_string
self
end
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
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
# script object of a string representation
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
class ScriptOpcodeError < StandardError; end
# raw script binary of a string representation
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
def invalid?
@script_invalid ||= false
end
# run the script. +check_callback+ is called for OP_CHECKSIG operations
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
def invalid
@script_invalid = true; nil
end
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
# pay_to_script_hash: https://en.bitcoin.it/wiki/BIP_0016
#
# <sig> {<pub> OP_CHECKSIG} | OP_HASH160 <script_hash> OP_EQUAL
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
def inner_p2sh!(script=nil); @inner_p2sh = true; @inner_script_code = script; self; end
def inner_p2sh?; @inner_p2sh; end
# get the inner p2sh script
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
# is this a :script_hash (pay-to-script-hash/p2sh) script?
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
alias :is_p2sh? :is_pay_to_script_hash?
# check if script is in one of the recognized standard formats
def is_standard?
is_pubkey? || is_hash160? || is_multisig? || is_p2sh? || is_op_return? || is_witness_v0_keyhash? || is_witness_v0_scripthash?
end
# is this a pubkey script
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
alias :is_send_to_ip? :is_pubkey?
# is this a hash160 (address) script
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 this a multisig script
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 this an op_return script
def is_op_return?
@chunks[0] == OP_RETURN && @chunks.size <= 2
end
# is this a witness script
def is_witness?
@chunks.length == 2 && (0..16).include?(@chunks[0]) && @chunks[1].is_a?(String)
end
# is this a witness pubkey script
def is_witness_v0_keyhash?
is_witness? && @chunks[0] == 0 && @chunks[1].bytesize == 20
end
# is this a witness script hash
def is_witness_v0_scripthash?
is_witness? && @chunks[0] == 0 && @chunks[1].bytesize == 32
end
# Verify the script is only pushing data onto the stack
def is_push_only?(script_data=nil)
check_pushes(true, false, (script_data||@input_script))
end
# Make sure opcodes used to push data match their intended length ranges
def pushes_are_canonical?(script_data=nil)
check_pushes(false, true, (script_data||@raw))
end
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
# get type of this tx
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
# get the public key for this pubkey script
def get_pubkey
return @chunks[0].unpack("H*")[0] if @chunks.size == 1
is_pubkey? ? @chunks[0].unpack("H*")[0] : nil
end
# get the pubkey address for this pubkey script
def get_pubkey_address
Bitcoin.pubkey_to_address(get_pubkey)
end
# get the hash160 for this hash160 or pubkey script
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 the hash160 address for this hash160 script
def get_hash160_address
Bitcoin.hash160_to_address(get_hash160)
end
# get the public keys for this multisig script
def get_multisig_pubkeys
1.upto(@chunks[-2] - 80).map{|i| @chunks[i] }
end
# get the pubkey addresses for this multisig script
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
def get_p2sh_address
Bitcoin.hash160_to_p2sh_address(get_hash160)
end
# get the data possibly included in an OP_RETURN script
def get_op_return_data
return nil unless is_op_return?
cast_to_string(@chunks[1]).unpack("H*")[0] if @chunks[1]
end
# get all addresses this script corresponds to (if possible)
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 single address, or first for multisig script
def get_address
addrs = get_addresses
addrs.is_a?(Array) ? addrs[0] : addrs
end
# generate pubkey tx script for given +pubkey+. returns a raw binary script of the form:
# <pubkey> OP_CHECKSIG
def self.to_pubkey_script(pubkey)
pack_pushdata([pubkey].pack("H*")) + [ OP_CHECKSIG ].pack("C")
end
# generate hash160 tx for given +address+. returns a raw binary script of the form:
# OP_DUP OP_HASH160 <hash160> OP_EQUALVERIFY OP_CHECKSIG
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
# generate p2sh output script for given +p2sh+ hash160. returns a raw binary script of the form:
# OP_HASH160 <p2sh> OP_EQUAL
def self.to_p2sh_script(p2sh)
return nil unless p2sh
# HASH160 length hash EQUAL
[ ["a9", "14", p2sh, "87"].join ].pack("H*")
end
# 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>
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
# generate p2wpkh tx for given +address+. returns a raw binary script of the form:
# 0 <hash160>
def self.to_witness_hash160_script(hash160)
return nil unless hash160
to_witness_script(0, hash160)
end
# generate p2wsh output script for given +p2sh+ sha256. returns a raw binary script of the form:
# 0 <p2sh>
def self.to_witness_p2sh_script(p2sh)
return nil unless p2sh
to_witness_script(0, p2sh)
end
# generate hash160 or p2sh output script, depending on the type of the given +address+.
# see #to_hash160_script and #to_p2sh_script.
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
# 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
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
# generate OP_RETURN output script with given data. returns a raw binary script of the form:
# OP_RETURN <data>
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
# generate input script sig spending a pubkey output with given +signature+ and +pubkey+.
# returns a raw binary script sig of the form:
# <signature> [<pubkey>]
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
# 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.
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
# alias for #to_pubkey_script_sig
def self.to_signature_pubkey_script(*a)
to_pubkey_script_sig(*a)
end
# generate input script sig spending a multisig output script.
# returns a raw binary script sig of the form:
# OP_0 <sig> [<sig> ...]
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
# 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.
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
# 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>
def self.to_p2sh_multisig_script_sig(redeem_script, *sigs)
to_multisig_script_sig(*sigs.flatten) + pack_pushdata(redeem_script)
end
# 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.
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
def get_signatures_required
return false unless is_multisig?
@chunks[0] - 80
end
def get_keys_provided
return false unless is_multisig?
@chunks[-2] - 80
end
def codeseparator_count
@chunks.select{|c|c == Bitcoin::Script::OP_CODESEPARATOR}.length
end
# This matches CScript::GetSigOpCount(bool fAccurate)
# Note: this does not cover P2SH script which is to be unserialized
# and checked explicitly when validating blocks.
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
# 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.
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
# Converts OP_{0,1,2,...,16} into 0, 1, 2, ..., 16.
# Returns nil for other opcodes.
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
## OPCODES
# Does nothing
def op_nop; end
def op_nop1; end
def op_nop2; end
def op_nop3; end
def op_nop4; end