-
Notifications
You must be signed in to change notification settings - Fork 1
/
Script.scala
2044 lines (1927 loc) · 69.8 KB
/
Script.scala
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
package scoin
import java.io.{
ByteArrayInputStream,
ByteArrayOutputStream,
InputStream,
OutputStream
}
import scala.annotation.tailrec
import scala.collection.mutable.ArrayBuffer
import scodec.bits.ByteVector
import scoin.Crypto._
/** script execution flags
*/
object ScriptFlags {
val SCRIPT_VERIFY_NONE = 0
// Evaluate P2SH subscripts (softfork safe, BIP16).
val SCRIPT_VERIFY_P2SH = 1 << 0
// Passing a non-strict-DER signature or one with undefined hashtype to a checksig operation causes script failure.
// Evaluating a pubkey that is not (0x04 + 64 bytes) or (0x02 or 0x03 + 32 bytes) by checksig causes script failure.
// (softfork safe, but not used or intended as a consensus rule).
val SCRIPT_VERIFY_STRICTENC = 1 << 1
// Passing a non-strict-DER signature to a checksig operation causes script failure (softfork safe, BIP62 rule 1)
val SCRIPT_VERIFY_DERSIG = 1 << 2
// Passing a non-strict-DER signature or one with S > order/2 to a checksig operation causes script failure
// (softfork safe, BIP62 rule 5).
val SCRIPT_VERIFY_LOW_S = 1 << 3
// verify dummy stack item consumed by CHECKMULTISIG is of zero-length (softfork safe, BIP62 rule 7).
val SCRIPT_VERIFY_NULLDUMMY = 1 << 4
// Using a non-push operator in the scriptSig causes script failure (softfork safe, BIP62 rule 2).
val SCRIPT_VERIFY_SIGPUSHONLY = 1 << 5
// Require minimal encodings for all push operations (OP_0... OP_16, OP_1NEGATE where possible, direct
// pushes up to 75 bytes, OP_PUSHDATA up to 255 bytes, OP_PUSHDATA2 for anything larger). Evaluating
// any other push causes the script to fail (BIP62 rule 3).
// In addition, whenever a stack element is interpreted as a number, it must be of minimal length (BIP62 rule 4).
// (softfork safe)
val SCRIPT_VERIFY_MINIMALDATA = 1 << 6
// Discourage use of NOPs reserved for upgrades (NOP1-10)
//
// Provided so that nodes can avoid accepting or mining transactions
// containing executed NOP's whose meaning may change after a soft-fork,
// thus rendering the script invalid; with this flag set executing
// discouraged NOPs fails the script. This verification flag will never be
// a mandatory flag applied to scripts in a block. NOPs that are not
// executed, e.g. within an unexecuted IF ENDIF block, are *not* rejected.
val SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS = 1 << 7
// Require that only a single stack element remains after evaluation. This changes the success criterion from
// "At least one stack element must remain, and when interpreted as a boolean, it must be true" to
// "Exactly one stack element must remain, and when interpreted as a boolean, it must be true".
// (softfork safe, BIP62 rule 6)
// Note: CLEANSTACK should never be used without P2SH.
val SCRIPT_VERIFY_CLEANSTACK = 1 << 8
// Verify CHECKLOCKTIMEVERIFY
//
// See BIP65 for details.
val SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY = 1 << 9
// See BIP112 for details
val SCRIPT_VERIFY_CHECKSEQUENCEVERIFY = 1 << 10
// support CHECKSEQUENCEVERIFY opcode
//
// Support segregated witness
//
val SCRIPT_VERIFY_WITNESS = 1 << 11
// Making v2-v16 witness program non-standard
//
val SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM = 1 << 12
// Segwit script only: Require the argument of OP_IF/NOTIF to be exactly 0x01 or empty vector
//
val SCRIPT_VERIFY_MINIMALIF = 1 << 13
// Signature(s) must be empty vector if an CHECK(MULTI)SIG operation failed
//
val SCRIPT_VERIFY_NULLFAIL = 1 << 14
// Public keys in segregated witness scripts must be compressed
//
val SCRIPT_VERIFY_WITNESS_PUBKEYTYPE = 1 << 15
// Making OP_CODESEPARATOR and FindAndDelete fail any non-segwit scripts
//
val SCRIPT_VERIFY_CONST_SCRIPTCODE = 1 << 16
/** Mandatory script verification flags that all new blocks must comply with
* for them to be valid. (but old blocks may not comply with) Currently just
* P2SH, but in the future other flags may be added, such as a soft-fork to
* enforce strict DER encoding.
*
* Failing one of these tests may trigger a DoS ban - see CheckInputs() for
* details.
*/
val MANDATORY_SCRIPT_VERIFY_FLAGS = SCRIPT_VERIFY_P2SH
/** Standard script verification flags that standard transactions will comply
* with. However scripts violating these flags may still be present in valid
* blocks and we must accept those blocks.
*/
val STANDARD_SCRIPT_VERIFY_FLAGS = MANDATORY_SCRIPT_VERIFY_FLAGS |
SCRIPT_VERIFY_DERSIG |
SCRIPT_VERIFY_STRICTENC |
SCRIPT_VERIFY_MINIMALDATA |
SCRIPT_VERIFY_NULLDUMMY |
SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS |
SCRIPT_VERIFY_CLEANSTACK |
SCRIPT_VERIFY_MINIMALIF |
SCRIPT_VERIFY_NULLFAIL |
SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY |
SCRIPT_VERIFY_CHECKSEQUENCEVERIFY |
SCRIPT_VERIFY_LOW_S |
SCRIPT_VERIFY_WITNESS |
SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM |
SCRIPT_VERIFY_WITNESS_PUBKEYTYPE |
SCRIPT_VERIFY_CONST_SCRIPTCODE
/** For convenience, standard but not mandatory verify flags. */
val STANDARD_NOT_MANDATORY_VERIFY_FLAGS =
STANDARD_SCRIPT_VERIFY_FLAGS & ~MANDATORY_SCRIPT_VERIFY_FLAGS
}
object Script {
import Protocol._
import ScriptFlags._
import scoin.ScriptElt._
type Stack = List[ByteVector]
private val True = ByteVector.fromByte(1)
private val False = ByteVector.empty
/** parse a script from a input stream of binary data
*
* @param input
* input stream
* @param stack
* initial command stack
* @return
* an updated command stack
*/
@tailrec
def parse(
input: InputStream,
stack: collection.immutable.Vector[ScriptElt] = Vector.empty[ScriptElt]
): List[ScriptElt] = {
val code = input.read()
code match {
case -1 => stack.toList
case 0 => parse(input, stack :+ OP_0)
case opCode if opCode > 0 && opCode < 0x4c =>
parse(input, stack :+ OP_PUSHDATA(bytes(input, opCode), opCode))
case 0x4c =>
parse(input, stack :+ OP_PUSHDATA(bytes(input, uint8(input)), 0x4c))
case 0x4d =>
parse(input, stack :+ OP_PUSHDATA(bytes(input, uint16(input)), 0x4d))
case 0x4e =>
parse(input, stack :+ OP_PUSHDATA(bytes(input, uint32(input)), 0x4e))
case opCode if code2elt.contains(opCode) =>
parse(input, stack :+ code2elt(opCode))
case opCode =>
parse(
input,
stack :+ OP_INVALID(opCode)
) // unknown/invalid ops can be parsed but not executed
}
}
def parse(blob: ByteVector): List[ScriptElt] = if (blob.length > 10000)
throw new RuntimeException("script is too large")
else parse(new ByteArrayInputStream(blob.toArray))
def parse(blob: Array[Byte]): List[ScriptElt] = parse(ByteVector.view(blob))
@tailrec
def write(script: Seq[ScriptElt], out: OutputStream): Unit = script match {
case Nil => ()
case OP_PUSHDATA(data, length) :: tail
if data.length < 0x4c && data.length == length =>
out.write(data.length.toInt); out.write(data.toArray); write(tail, out)
case OP_PUSHDATA(data, 0x4c) :: tail if data.length < 0xff =>
writeUInt8(0x4c, out); writeUInt8(data.length.toInt, out);
out.write(data.toArray); write(tail, out)
case OP_PUSHDATA(data, 0x4d) :: tail if data.length < 0xffff =>
writeUInt8(0x4d, out); writeUInt16(data.length.toInt, out);
out.write(data.toArray); write(tail, out)
case OP_PUSHDATA(data, 0x4e) :: tail if data.length < 0xffffffff =>
writeUInt8(0x4e, out); writeUInt32(data.length, out);
out.write(data.toArray); write(tail, out)
case op @ OP_PUSHDATA(_, _) :: _ =>
throw new RuntimeException(s"invalid element $op")
case head :: tail => out.write(elt2code(head)); write(tail, out)
}
def write(script: Seq[ScriptElt]): ByteVector = {
val out = new ByteArrayOutputStream()
write(script, out)
ByteVector.view(out.toByteArray)
}
def isUpgradableNop(op: ScriptElt) = op match {
case OP_NOP1 | OP_NOP4 | OP_NOP5 | OP_NOP6 | OP_NOP7 | OP_NOP8 | OP_NOP9 |
OP_NOP10 =>
true
case _ => false
}
def isSimpleValue(op: ScriptElt) = op match {
case OP_1NEGATE | OP_0 | OP_1 | OP_2 | OP_3 | OP_4 | OP_5 | OP_6 | OP_7 |
OP_8 | OP_9 | OP_10 | OP_11 | OP_12 | OP_13 | OP_14 | OP_15 | OP_16 =>
true
case _ => false
}
def simpleValue(op: ScriptElt): Byte = {
require(isSimpleValue(op))
if (op == OP_0) 0 else (elt2code(op) - 0x50).toByte
}
def isDisabled(op: ScriptElt) = op match {
case 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 =>
true
case _ => false
}
def cost(op: ScriptElt): Int = op match {
case _ if isSimpleValue(op) => 0
case OP_PUSHDATA(_, _) => 0
case OP_RESERVED => 0
case _ => 1
}
def encodeNumber(value: Long): ByteVector = {
if (value == 0) ByteVector.empty
else {
val result = ArrayBuffer.empty[Byte]
val neg = value < 0
var absvalue = if (neg) -value else value
while (absvalue > 0) {
result += (absvalue & 0xff).toByte
absvalue >>= 8
}
// - If the most significant byte is >= 0x80 and the value is positive, push a
// new zero-byte to make the significant byte < 0x80 again.
// - If the most significant byte is >= 0x80 and the value is negative, push a
// new 0x80 byte that will be popped off when converting to an integral.
// - If the most significant byte is < 0x80 and the value is negative, add
// 0x80 to it, since it will be subtracted and interpreted as a negative when
// converting to an integral.
if ((result.last & 0x80) != 0) {
result += {
if (neg) 0x80.toByte else 0
}
} else if (neg) {
result(result.length - 1) = (result(result.length - 1) | 0x80).toByte
}
ByteVector.view(result.toArray)
}
}
def decodeNumber(
input: ByteVector,
checkMinimalEncoding: Boolean,
maximumSize: Int = 4
): Long = {
if (input.isEmpty) 0
else if (input.length > maximumSize)
throw new RuntimeException(
s"number cannot be encoded on more than $maximumSize bytes"
)
else {
if (checkMinimalEncoding) {
// Check that the number is encoded with the minimum possible
// number of bytes.
//
// If the most-significant-byte - excluding the sign bit - is zero
// then we're not minimal. Note how this test also rejects the
// negative-zero encoding, 0x80.
if ((input.last & 0x7f) == 0) {
// One exception: if there's more than one byte and the most
// significant bit of the second-most-significant-byte is set
// it would conflict with the sign bit. An example of this case
// is +-255, which encode to 0xff00 and 0xff80 respectively.
// (big-endian).
if (input.size <= 1 || (input(input.size - 2) & 0x80) == 0) {
throw new RuntimeException("non-minimally encoded script number")
}
}
}
var result = 0L
for (i <- input.toSeq.indices) {
result |= (input(i) & 0xffL) << (8 * i)
}
// If the input vector's most significant byte is 0x80, remove it from
// the result's msb and return a negative.
if ((input.last & 0x80) != 0)
-(result & ~(0x80L << (8 * (input.size - 1))))
else
result
}
}
def castToBoolean(input: ByteVector): Boolean = input.toSeq.reverse match {
case head +: tail if head == 0x80.toByte && tail.forall(_ == 0) => false
case something if something.exists(_ != 0) => true
case _ => false
}
def isPushOnly(script: Seq[ScriptElt]): Boolean = !script.exists {
case op if isSimpleValue(op) => false
case OP_PUSHDATA(_, _) => false
case _ => true
}
def isPayToScript(script: Seq[ScriptElt]): Boolean = script match {
case OP_HASH160 :: OP_PUSHDATA(multisigAddress, _) :: OP_EQUAL :: Nil
if multisigAddress.length == 20 =>
true
case _ => false
}
def isPayToScript(script: ByteVector): Boolean =
script.length == 23 && script(0) == elt2code(OP_HASH160).toByte && script(
1
) == 0x14 && script(22) == elt2code(OP_EQUAL).toByte
def isNativeWitnessScript(script: Seq[ScriptElt]): Boolean = script match {
case (OP_0 | OP_1 | OP_2 | OP_3 | OP_4 | OP_5 | OP_6 | OP_7 | OP_8 | OP_9 |
OP_10 | OP_11 | OP_12 | OP_13 | OP_14 | OP_15 |
OP_16) :: OP_PUSHDATA(witnessProgram, _) :: Nil
if witnessProgram.length >= 2 && witnessProgram.length <= 40 =>
true
case _ => false
}
def isNativeWitnessScript(script: ByteVector): Boolean =
isNativeWitnessScript(parse(script))
def removeSignature(
script: List[ScriptElt],
signature: ByteVector
): List[ScriptElt] = {
val toRemove = OP_PUSHDATA(signature)
script.filterNot(_ == toRemove)
}
def removeSignatures(
script: List[ScriptElt],
sigs: List[ByteVector]
): List[ScriptElt] = sigs.foldLeft(script)(removeSignature)
def checkLockTime(
lockTime: Long,
tx: Transaction,
inputIndex: Int
): Boolean = {
// There are two kinds of nLockTime: lock-by-blockheight
// and lock-by-blocktime, distinguished by whether
// nLockTime < LOCKTIME_THRESHOLD.
//
// We want to compare apples to apples, so fail the script
// unless the type of nLockTime being tested is the same as
// the nLockTime in the transaction.
if (
!(
(tx.lockTime < Transaction.LOCKTIME_THRESHOLD && lockTime < Transaction.LOCKTIME_THRESHOLD) ||
(tx.lockTime >= Transaction.LOCKTIME_THRESHOLD && lockTime >= Transaction.LOCKTIME_THRESHOLD)
)
) {
return false
}
// Now that we know we're comparing apples-to-apples, the
// comparison is a simple numeric one.
if (lockTime > tx.lockTime)
return false
// Finally the nLockTime feature can be disabled and thus
// CHECKLOCKTIMEVERIFY bypassed if every txin has been
// finalized by setting nSequence to maxint. The
// transaction would be allowed into the blockchain, making
// the opcode ineffective.
//
// Testing if this vin is not final is sufficient to
// prevent this condition. Alternatively we could test all
// inputs, but testing just this input minimizes the data
// required to prove correct CHECKLOCKTIMEVERIFY execution.
if (tx.txIn(inputIndex).isFinal)
return false
true
}
def checkSequence(
sequence: Long,
tx: Transaction,
inputIndex: Int
): Boolean = {
// Relative lock times are supported by comparing the passed
// in operand to the sequence number of the input.
val txToSequence = tx.txIn(inputIndex).sequence
// Fail if the transaction's version number is not set high
// enough to trigger BIP 68 rules.
if (tx.version < 2)
return false
// Sequence numbers with their most significant bit set are not
// consensus constrained. Testing that the transaction's sequence
// number do not have this bit set prevents using this property
// to get around a CHECKSEQUENCEVERIFY check.
if ((txToSequence & TxIn.SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0)
return false
// Mask off any bits that do not have consensus-enforced meaning
// before doing the integer comparisons
val nLockTimeMask =
TxIn.SEQUENCE_LOCKTIME_TYPE_FLAG | TxIn.SEQUENCE_LOCKTIME_MASK
val txToSequenceMasked = txToSequence & nLockTimeMask
val nSequenceMasked = sequence & nLockTimeMask
// There are two kinds of nSequence: lock-by-blockheight
// and lock-by-blocktime, distinguished by whether
// nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG.
//
// We want to compare apples to apples, so fail the script
// unless the type of nSequenceMasked being tested is the same as
// the nSequenceMasked in the transaction.
if (
!(
(txToSequenceMasked < TxIn.SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked < TxIn.SEQUENCE_LOCKTIME_TYPE_FLAG) ||
(txToSequenceMasked >= TxIn.SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked >= TxIn.SEQUENCE_LOCKTIME_TYPE_FLAG)
)
) {
return false
}
// Now that we know we're comparing apples-to-apples, the
// comparison is a simple numeric one.
if (nSequenceMasked > txToSequenceMasked)
return false
true
}
/** Execution context of a tx script. A script is always executed in the
* "context" of a transaction that is being verified.
*
* @param tx
* transaction that is being verified
* @param inputIndex
* 0-based index of the tx input that is being processed
*/
case class Context(tx: Transaction, inputIndex: Int, amount: Satoshi) {
require(
inputIndex >= 0 && inputIndex < tx.txIn.length,
"invalid input index"
)
}
object Runner {
/** This class represents the state of the script execution engine
*
* @param conditions
* current "position" wrt if/notif/else/endif
* @param altstack
* initial alternate stack
* @param opCount
* initial op count
* @param scriptCode
* initial script (can be modified by OP_CODESEPARATOR for example)
*/
case class State(
conditions: List[Boolean],
altstack: Stack,
opCount: Int,
scriptCode: List[ScriptElt]
)
type Callback = (List[ScriptElt], Stack, State) => Boolean
}
/** Bitcoin script runner
*
* @param context
* script execution context
* @param scriptFlag
* script flags
* @param callback
* optional callback
*/
class Runner(
context: Context,
scriptFlag: Int = MANDATORY_SCRIPT_VERIFY_FLAGS,
callback: Option[Runner.Callback] = None
) {
import Runner._
def checkSignature(
pubKey: ByteVector,
sigBytes: ByteVector,
scriptCode: ByteVector,
signatureVersion: Int
): Boolean = {
if (sigBytes.isEmpty) false
else if (!Crypto.checkSignatureEncoding(sigBytes, scriptFlag))
throw new RuntimeException("invalid signature")
else if (
!Crypto.checkPubKeyEncoding(pubKey, scriptFlag, signatureVersion)
) throw new RuntimeException("invalid public key")
else if (!Crypto.isPubKeyValidLax(pubKey))
false // see how this is different from above ?
else {
val sigHashFlags = sigBytes.last & 0xff
// sig hash is the last byte
val sigBytes1 = sigBytes.take(sigBytes.length - 1) // drop sig hash
if (sigBytes1.isEmpty) false
else {
val hash = Transaction.hashForSigning(
context.tx,
context.inputIndex,
scriptCode,
sigHashFlags,
context.amount,
signatureVersion
)
val result = Crypto.verifySignature(
hash,
Crypto.der2compact(sigBytes1),
PublicKey.fromBin(pubKey)
)
result
}
}
}
def checkSignatures(
pubKeys: Seq[ByteVector],
sigs: Seq[ByteVector],
scriptCode: ByteVector,
signatureVersion: Int
): Boolean = sigs match {
case Nil => true
case _ if sigs.length > pubKeys.length => false
case sig :: _ if !Crypto.checkSignatureEncoding(sig, scriptFlag) =>
throw new RuntimeException("invalid signature")
case sig :: _ =>
if (checkSignature(pubKeys.head, sig, scriptCode, signatureVersion))
checkSignatures(pubKeys.tail, sigs.tail, scriptCode, signatureVersion)
else
checkSignatures(pubKeys.tail, sigs, scriptCode, signatureVersion)
}
def checkMinimalEncoding: Boolean =
(scriptFlag & SCRIPT_VERIFY_MINIMALDATA) != 0
def decodeNumber(input: ByteVector, maximumSize: Int = 4): Long =
Script.decodeNumber(input, checkMinimalEncoding, maximumSize)
/** execute a serialized script, starting from an empty stack
*
* @param script
* serialized script
* @return
* the stack created by the script
*/
def run(script: ByteVector): Stack = run(parse(script))
/** execute a script, starting from an empty stack
*
* @return
* the stack created by the script
*/
def run(script: List[ScriptElt]): Stack =
run(script, List.empty[ByteVector])
/** execute a serialized script, starting from an existing stack
*
* @param script
* serialized script
* @param stack
* initial stack
* @return
* the stack updated by the script
*/
def run(script: ByteVector, stack: Stack): Stack = run(parse(script), stack)
def run(script: List[ScriptElt], stack: Stack): Stack =
run(script, stack, SigVersion.SIGVERSION_BASE)
/** execute a script, starting from an existing stack
*
* @param script
* serialized script
* @param stack
* initial stack
* @param signatureVersion
* signature version (0: use pre-segwit tx hash, 1: use segwit tx hash)
* @return
* the stack updated by the script
*/
def run(
script: List[ScriptElt],
stack: Stack,
signatureVersion: Int
): Stack =
run(
script,
stack,
State(
conditions = List.empty[Boolean],
altstack = List.empty[ByteVector],
opCount = 0,
scriptCode = script
),
signatureVersion
)
/** execute a bitcoin script
*
* @param script
* script
* @param stack
* initial stack
* @param state
* initial state
* @return
* the stack updated by the script
*/
@tailrec
final def run(
script: List[ScriptElt],
stack: Stack,
state: State,
signatureVersion: Int
): Stack = {
import state._
callback.map(f => f(script, stack, state))
if ((stack.length + altstack.length) > 1000)
throw new RuntimeException(
s"stack is too large: stack size = ${stack.length} alt stack size = ${altstack.length}"
)
if (opCount > 201)
throw new RuntimeException("operation count is over the limit")
script match {
// first, things that are always checked even in non-executed IF branches
case Nil if conditions.nonEmpty =>
throw new RuntimeException("IF/ENDIF imbalance")
case Nil => stack
case op :: _ if isDisabled(op) =>
throw new RuntimeException(s"$op isdisabled")
case OP_CODESEPARATOR :: _
if signatureVersion == SigVersion.SIGVERSION_BASE && (scriptFlag & SCRIPT_VERIFY_CONST_SCRIPTCODE) != 0 =>
throw new RuntimeException(
"Using OP_CODESEPARATOR in non-witness script"
)
case OP_VERIF :: _ =>
throw new RuntimeException("OP_VERIF is always invalid")
case OP_VERNOTIF :: _ =>
throw new RuntimeException("OP_VERNOTIF is always invalid")
case OP_PUSHDATA(data, _) :: _ if data.size > MaxScriptElementSize =>
throw new RuntimeException("Push value size limit exceeded")
// check whether we are in a non-executed IF branch
case OP_IF :: tail if conditions.contains(false) =>
run(
tail,
stack,
state.copy(conditions = false :: conditions, opCount = opCount + 1),
signatureVersion
)
case OP_IF :: tail =>
stack match {
case True :: stacktail
if signatureVersion == SigVersion.SIGVERSION_WITNESS_V0 && (scriptFlag & SCRIPT_VERIFY_MINIMALIF) != 0 =>
run(
tail,
stacktail,
state
.copy(conditions = true :: conditions, opCount = opCount + 1),
signatureVersion
)
case False :: stacktail
if signatureVersion == SigVersion.SIGVERSION_WITNESS_V0 && (scriptFlag & SCRIPT_VERIFY_MINIMALIF) != 0 =>
run(
tail,
stacktail,
state.copy(
conditions = false :: conditions,
opCount = opCount + 1
),
signatureVersion
)
case _ :: stacktail
if signatureVersion == SigVersion.SIGVERSION_WITNESS_V0 && (scriptFlag & SCRIPT_VERIFY_MINIMALIF) != 0 =>
throw new RuntimeException("OP_IF argument must be minimal")
case head :: stacktail if castToBoolean(head) =>
run(
tail,
stacktail,
state
.copy(conditions = true :: conditions, opCount = opCount + 1),
signatureVersion
)
case head :: stacktail =>
run(
tail,
stacktail,
state.copy(
conditions = false :: conditions,
opCount = opCount + 1
),
signatureVersion
)
case _ => throw new MatchError(stack)
}
case OP_NOTIF :: tail if conditions.contains(false) =>
run(
tail,
stack,
state.copy(conditions = true :: conditions, opCount = opCount + 1),
signatureVersion
)
case OP_NOTIF :: tail =>
stack match {
case False :: stacktail
if signatureVersion == SigVersion.SIGVERSION_WITNESS_V0 && (scriptFlag & SCRIPT_VERIFY_MINIMALIF) != 0 =>
run(
tail,
stacktail,
state
.copy(conditions = true :: conditions, opCount = opCount + 1),
signatureVersion
)
case True :: stacktail
if signatureVersion == SigVersion.SIGVERSION_WITNESS_V0 && (scriptFlag & SCRIPT_VERIFY_MINIMALIF) != 0 =>
run(
tail,
stacktail,
state.copy(
conditions = false :: conditions,
opCount = opCount + 1
),
signatureVersion
)
case _ :: stacktail
if signatureVersion == SigVersion.SIGVERSION_WITNESS_V0 && (scriptFlag & SCRIPT_VERIFY_MINIMALIF) != 0 =>
throw new RuntimeException("OP_NOTIF argument must be minimal")
case head :: stacktail if castToBoolean(head) =>
run(
tail,
stacktail,
state.copy(
conditions = false :: conditions,
opCount = opCount + 1
),
signatureVersion
)
case head :: stacktail =>
run(
tail,
stacktail,
state
.copy(conditions = true :: conditions, opCount = opCount + 1),
signatureVersion
)
case _ => throw new MatchError(stack)
}
case OP_ELSE :: tail =>
run(
tail,
stack,
state.copy(
conditions = !conditions.head :: conditions.tail,
opCount = opCount + 1
),
signatureVersion
)
case OP_ENDIF :: tail =>
run(
tail,
stack,
state.copy(conditions = conditions.tail, opCount = opCount + 1),
signatureVersion
)
case head :: tail if conditions.contains(false) =>
run(
tail,
stack,
state.copy(opCount = opCount + cost(head)),
signatureVersion
)
// and now, things that are checked only in an executed IF branch
case OP_0 :: tail =>
run(tail, ByteVector.empty :: stack, state, signatureVersion)
case op :: tail if isSimpleValue(op) =>
run(
tail,
encodeNumber(simpleValue(op)) :: stack,
state,
signatureVersion
)
case OP_NOP :: tail =>
run(tail, stack, state.copy(opCount = opCount + 1), signatureVersion)
case op :: tail
if isUpgradableNop(
op
) && ((scriptFlag & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) != 0) =>
throw new RuntimeException("use of upgradable NOP is discouraged")
case op :: tail if isUpgradableNop(op) =>
run(tail, stack, state.copy(opCount = opCount + 1), signatureVersion)
case OP_1ADD :: tail if stack.isEmpty =>
throw new RuntimeException("cannot run OP_1ADD on am empty stack")
case OP_1ADD :: tail =>
run(
tail,
encodeNumber(decodeNumber(stack.head) + 1) :: stack.tail,
state.copy(opCount = opCount + 1),
signatureVersion
)
case OP_1SUB :: tail if stack.isEmpty =>
throw new RuntimeException("cannot run OP_1SUB on am empty stack")
case OP_1SUB :: tail =>
run(
tail,
encodeNumber(decodeNumber(stack.head) - 1) :: stack.tail,
state.copy(opCount = opCount + 1),
signatureVersion
)
case OP_ABS :: tail if stack.isEmpty =>
throw new RuntimeException("cannot run OP_ABS on am empty stack")
case OP_ABS :: tail =>
run(
tail,
encodeNumber(Math.abs(decodeNumber(stack.head))) :: stack.tail,
state.copy(opCount = opCount + 1),
signatureVersion
)
case OP_ADD :: tail =>
stack match {
case a :: b :: stacktail =>
val x = decodeNumber(a)
val y = decodeNumber(b)
val result = x + y
run(
tail,
encodeNumber(result) :: stacktail,
state.copy(opCount = opCount + 1),
signatureVersion
)
case _ =>
throw new RuntimeException(
"cannot run OP_ADD on a stack with less than 2 elements"
)
}
case OP_BOOLAND :: tail =>
stack match {
case x1 :: x2 :: stacktail =>
val n1 = decodeNumber(x1)
val n2 = decodeNumber(x2)
val result = if (n1 != 0 && n2 != 0) 1 else 0
run(
tail,
encodeNumber(result) :: stacktail,
state.copy(opCount = opCount + 1),
signatureVersion
)
case _ =>
throw new RuntimeException(
"cannot run OP_BOOLAND on a stack with less than 2 elements"
)
}
case OP_BOOLOR :: tail =>
stack match {
case x1 :: x2 :: stacktail =>
val n1 = decodeNumber(x1)
val n2 = decodeNumber(x2)
val result = if (n1 != 0 || n2 != 0) 1 else 0
run(
tail,
encodeNumber(result) :: stacktail,
state.copy(opCount = opCount + 1),
signatureVersion
)
case _ =>
throw new RuntimeException(
"cannot run OP_BOOLOR on a stack with less than 2 elements"
)
}
case OP_CHECKLOCKTIMEVERIFY :: tail
if (scriptFlag & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY) != 0 =>
stack match {
case head :: _ =>
// Note that elsewhere numeric opcodes are limited to
// operands in the range -2**31+1 to 2**31-1, however it is
// legal for opcodes to produce results exceeding that
// range. This limitation is implemented by CScriptNum's
// default 4-byte limit.
//
// If we kept to that limit we'd have a year 2038 problem,
// even though the nLockTime field in transactions
// themselves is uint32 which only becomes meaningless
// after the year 2106.
//
// Thus as a special case we tell CScriptNum to accept up
// to 5-byte bignums, which are good until 2**39-1, well
// beyond the 2**32-1 limit of the nLockTime field itself.
val locktime = decodeNumber(head, maximumSize = 5)
if (locktime < 0)
throw new RuntimeException("CLTV lock time cannot be negative")
if (!checkLockTime(locktime, context.tx, context.inputIndex))
throw new RuntimeException("unsatisfied CLTV lock time")
// stack is not popped: we use stack here and not stacktail !!
run(
tail,
stack,
state.copy(opCount = opCount + 1),
signatureVersion
)
case _ =>
throw new RuntimeException(
"cannot run OP_CHECKLOCKTIMEVERIFY on an empty stack"
)
}
case OP_CHECKLOCKTIMEVERIFY :: _
if (scriptFlag & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) != 0 =>
throw new RuntimeException("use of upgradable NOP is discouraged")
case OP_CHECKLOCKTIMEVERIFY :: tail =>
run(tail, stack, state.copy(opCount = opCount + 1), signatureVersion)
case OP_CHECKSEQUENCEVERIFY :: tail
if (scriptFlag & SCRIPT_VERIFY_CHECKSEQUENCEVERIFY) != 0 =>
stack match {
case head :: _ =>
// nSequence, like nLockTime, is a 32-bit unsigned integer
// field. See the comment in CHECKLOCKTIMEVERIFY regarding
// 5-byte numeric operands.
val sequence = decodeNumber(head, maximumSize = 5)
// In the rare event that the argument may be < 0 due to
// some arithmetic being done first, you can always use
// 0 MAX CHECKSEQUENCEVERIFY.
if (sequence < 0)
throw new RuntimeException("CSV lock time cannot be negative")
// To provide for future soft-fork extensibility, if the
// operand has the disabled lock-time flag set,
// CHECKSEQUENCEVERIFY behaves as a NOP.
if ((sequence & TxIn.SEQUENCE_LOCKTIME_DISABLE_FLAG) == 0) {
// Actually compare the specified inverse sequence number
// with the input.
if (!checkSequence(sequence, context.tx, context.inputIndex))
throw new RuntimeException("unsatisfied CSV lock time")
}
// stack is not popped: we use stack here and not stacktail !!
run(
tail,
stack,
state.copy(opCount = opCount + 1),
signatureVersion
)
case _ =>
throw new RuntimeException(
"cannot run OP_CHECKSEQUENCEVERIFY on an empty stack"
)
}
case OP_CHECKSEQUENCEVERIFY :: _
if (scriptFlag & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) != 0 =>
throw new RuntimeException("use of upgradable NOP is discouraged")
case OP_CHECKSEQUENCEVERIFY :: tail =>
run(tail, stack, state.copy(opCount = opCount + 1), signatureVersion)
case OP_CHECKSIG :: tail =>
stack match {
case pubKey :: sigBytes :: stacktail =>
// remove signature from script
val scriptCode1 =
if (signatureVersion == SigVersion.SIGVERSION_BASE) {
val scriptCode1 = removeSignature(scriptCode, sigBytes)