/
ScriptPubKey.scala
1310 lines (1122 loc) · 47 KB
/
ScriptPubKey.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 org.bitcoins.core.protocol.script
import org.bitcoins.core.consensus.Consensus
import org.bitcoins.core.crypto._
import org.bitcoins.core.script.bitwise.{OP_EQUAL, OP_EQUALVERIFY}
import org.bitcoins.core.script.constant.{BytesToPushOntoStack, _}
import org.bitcoins.core.script.control.{
ConditionalOperation,
OP_ELSE,
OP_ENDIF,
OP_IF,
OP_NOTIF,
OP_RETURN
}
import org.bitcoins.core.script.crypto.{
OP_CHECKMULTISIG,
OP_CHECKMULTISIGVERIFY,
OP_CHECKSIG,
OP_HASH160
}
import org.bitcoins.core.script.locktime.{
OP_CHECKLOCKTIMEVERIFY,
OP_CHECKSEQUENCEVERIFY
}
import org.bitcoins.core.script.reserved.UndefinedOP_NOP
import org.bitcoins.core.script.stack.{OP_DROP, OP_DUP}
import org.bitcoins.core.util._
import scala.util.{Failure, Success, Try}
/**
* Created by chris on 12/26/15.
*/
sealed abstract class ScriptPubKey extends Script
/** Trait for all Non-SegWit ScriptPubKeys */
sealed trait NonWitnessScriptPubKey extends ScriptPubKey
/** Trait for all raw, non-nested ScriptPubKeys (no P2SH)
*
* Note that all WitnessScriptPubKeys including P2WPKH are not
* considered to be non-nested and hence not RawScriptPubKeys.
*/
sealed trait RawScriptPubKey extends NonWitnessScriptPubKey
/**
* Represents a
* [[https://bitcoin.org/en/developer-guide#pay-to-public-key-hash-p2pkh pay-to-pubkey hash script pubkey]]
*
* Format: `OP_DUP OP_HASH160 <PubKeyHash> OP_EQUALVERIFY OP_CHECKSIG`
*/
sealed trait P2PKHScriptPubKey extends RawScriptPubKey {
def pubKeyHash: Sha256Hash160Digest =
Sha256Hash160Digest(asm(asm.length - 3).bytes)
override def toString = s"pkh($pubKeyHash)"
}
object P2PKHScriptPubKey extends ScriptFactory[P2PKHScriptPubKey] {
private case class P2PKHScriptPubKeyImpl(
override val asm: Vector[ScriptToken])
extends P2PKHScriptPubKey {
override def toString = s"P2PKHScriptPubKeyImpl($pubKeyHash)"
}
def apply(pubKey: ECPublicKey): P2PKHScriptPubKey = {
val hash = CryptoUtil.sha256Hash160(pubKey.bytes)
P2PKHScriptPubKey(hash)
}
def apply(hash: Sha256Hash160Digest): P2PKHScriptPubKey = {
val pushOps = BitcoinScriptUtil.calculatePushOp(hash.bytes)
val asm = Seq(OP_DUP, OP_HASH160) ++ pushOps ++ Seq(
ScriptConstant(hash.bytes),
OP_EQUALVERIFY,
OP_CHECKSIG)
P2PKHScriptPubKey(asm)
}
def fromAsm(asm: Seq[ScriptToken]): P2PKHScriptPubKey = {
buildScript(asm.toVector,
P2PKHScriptPubKeyImpl(_),
isP2PKHScriptPubKey(_),
"Given asm was not a p2pkh scriptPubKey, got: " + asm)
}
def apply(asm: Seq[ScriptToken]): P2PKHScriptPubKey = fromAsm(asm)
/** Checks if the given asm matches the pattern for
* [[org.bitcoins.core.protocol.script.P2PKHScriptPubKey P2PKHScriptPubKey]] */
def isP2PKHScriptPubKey(asm: Seq[ScriptToken]): Boolean = {
asm match {
case Seq(OP_DUP,
OP_HASH160,
_: BytesToPushOntoStack,
_: ScriptConstant,
OP_EQUALVERIFY,
OP_CHECKSIG) =>
true
case _ => false
}
}
}
/**
* Represents a multisignature script public key
* https://bitcoin.org/en/developer-guide#multisig
* Format: <m> <A pubkey> [B pubkey] [C pubkey...] <n> OP_CHECKMULTISIG
*/
sealed trait MultiSignatureScriptPubKey extends RawScriptPubKey {
/** Returns the amount of required signatures for this multisignature script pubkey output */
def requiredSigs: Int = {
val asmWithoutPushOps = asm.filterNot(_.isInstanceOf[BytesToPushOntoStack])
val opCheckMultiSigIndex =
if (asm.indexOf(OP_CHECKMULTISIG) != -1)
asmWithoutPushOps.indexOf(OP_CHECKMULTISIG)
else asmWithoutPushOps.indexOf(OP_CHECKMULTISIGVERIFY)
//magic number 2 represents the maxSig operation and the OP_CHECKMULTISIG operation at the end of the asm
val numSigsRequired = asmWithoutPushOps(
opCheckMultiSigIndex - maxSigs.toInt - 2)
numSigsRequired match {
case x: ScriptNumber => x.toInt
case c: ScriptConstant
if ScriptNumber(c.hex).toLong <= Consensus.maxPublicKeysPerMultiSig =>
ScriptNumber(c.hex).toInt
case _ =>
throw new RuntimeException(
"The first element of the multisignature pubkey must be a script number operation\n" +
"operation: " + numSigsRequired +
"\nscriptPubKey: " + this)
}
}
/** The maximum amount of signatures for this multisignature script pubkey output */
def maxSigs: Int = {
if (checkMultiSigIndex == -1 || checkMultiSigIndex == 0) {
//means that we do not have a max signature requirement
0
} else {
asm(checkMultiSigIndex - 1) match {
case x: ScriptNumber => x.toInt
case c: ScriptConstant
if ScriptNumber(c.hex).toLong <= Consensus.maxPublicKeysPerMultiSig =>
ScriptNumber(c.hex).toInt
case x =>
throw new RuntimeException(
"The element preceding a OP_CHECKMULTISIG operation in a multisignature pubkey must be a script number operation, got: " + x)
}
}
}
/** Gives the `OP_CHECKMULTISIG` or `OP_CHECKMULTISIGVERIFY` index inside of asm */
private def checkMultiSigIndex: Int = {
if (asm.indexOf(OP_CHECKMULTISIG) != -1) asm.indexOf(OP_CHECKMULTISIG)
else asm.indexOf(OP_CHECKMULTISIGVERIFY)
}
/** Returns the public keys encoded into the `scriptPubKey` */
def publicKeys: Seq[ECPublicKey] = {
asm
.filter(_.isInstanceOf[ScriptConstant])
.slice(1, maxSigs + 1)
.map(key => ECPublicKey(key.hex))
}
override def toString = s"multi($requiredSigs,${publicKeys.mkString(",")})"
}
object MultiSignatureScriptPubKey
extends ScriptFactory[MultiSignatureScriptPubKey] {
private case class MultiSignatureScriptPubKeyImpl(
override val asm: Vector[ScriptToken])
extends MultiSignatureScriptPubKey {
override def toString =
s"MultiSignatureScriptPubKey($requiredSigs, $maxSigs, ${publicKeys.mkString(", ")})"
}
def apply(
requiredSigs: Int,
pubKeys: Seq[ECPublicKey]): MultiSignatureScriptPubKey = {
require(
requiredSigs <= Consensus.maxPublicKeysPerMultiSig,
"We cannot have more required signatures than: " +
Consensus.maxPublicKeysPerMultiSig + " got: " + requiredSigs
)
require(pubKeys.length <= Consensus.maxPublicKeysPerMultiSig,
"We cannot have more public keys than " +
Consensus.maxPublicKeysPerMultiSig + " got: " + pubKeys.length)
val required = ScriptNumberOperation.fromNumber(requiredSigs) match {
case Some(scriptNumOp) => Seq(scriptNumOp)
case None =>
val scriptNum = ScriptNumber(requiredSigs)
val pushOps = BitcoinScriptUtil.calculatePushOp(scriptNum.bytes)
pushOps ++ Seq(scriptNum)
}
val possible = ScriptNumberOperation.fromNumber(pubKeys.length) match {
case Some(scriptNumOp) => Seq(scriptNumOp)
case None =>
val scriptNum = ScriptNumber(pubKeys.length)
val pushOps = BitcoinScriptUtil.calculatePushOp(scriptNum)
pushOps ++ Seq(scriptNum)
}
val pubKeysWithPushOps: Seq[Seq[ScriptToken]] = for {
pubKey <- pubKeys
pushOps = BitcoinScriptUtil.calculatePushOp(pubKey.bytes)
constant = ScriptConstant(pubKey.bytes)
} yield pushOps ++ Seq(constant)
val asm: Seq[ScriptToken] = required ++ pubKeysWithPushOps.flatten ++ possible ++ Seq(
OP_CHECKMULTISIG)
MultiSignatureScriptPubKey(asm)
}
def fromAsm(asm: Seq[ScriptToken]): MultiSignatureScriptPubKey = {
buildScript(asm.toVector,
MultiSignatureScriptPubKeyImpl(_),
isMultiSignatureScriptPubKey(_),
"Given asm was not a MultSignatureScriptPubKey, got: " + asm)
}
def apply(asm: Seq[ScriptToken]): MultiSignatureScriptPubKey = fromAsm(asm)
/** Determines if the given script tokens are a multisignature `scriptPubKey` */
def isMultiSignatureScriptPubKey(asm: Seq[ScriptToken]): Boolean = {
val isNotEmpty = asm.size > 0
val containsMultiSigOp = asm.contains(OP_CHECKMULTISIG) || asm.contains(
OP_CHECKMULTISIGVERIFY)
//we need either the first or second asm operation to indicate how many signatures are required
val hasRequiredSignaturesTry = Try {
asm.headOption match {
case None => false
case Some(token) =>
//this is for the case that we have more than 16 public keys, the
//first operation will be a push op, the second operation being the actual number of keys
if (token.isInstanceOf[BytesToPushOntoStack])
isValidPubKeyNumber(asm.tail.head)
else isValidPubKeyNumber(token)
}
}
//the second to last asm operation should be the maximum amount of public keys
val hasMaximumSignaturesTry = Try {
asm(asm.length - 2) match {
case token: ScriptToken => isValidPubKeyNumber(token)
}
}
val standardOps = asm.filter(
op =>
op.isInstanceOf[ScriptNumber] || op == OP_CHECKMULTISIG ||
op == OP_CHECKMULTISIGVERIFY || op.isInstanceOf[ScriptConstant] || op
.isInstanceOf[BytesToPushOntoStack])
(hasRequiredSignaturesTry, hasMaximumSignaturesTry) match {
case (Success(hasRequiredSignatures), Success(hasMaximumSignatures)) =>
val result = isNotEmpty && containsMultiSigOp && hasRequiredSignatures &&
hasMaximumSignatures && standardOps.size == asm.size
result
case (Success(_), Failure(_)) => false
case (Failure(_), Success(_)) => false
case (Failure(_), Failure(_)) => false
}
}
/**
* Checks that the given script token is with the range of the maximum amount of
* public keys we can have in a
* [[org.bitcoins.core.protocol.script.MultiSignatureScriptPubKey MultiSignatureScriptPubKey]]
*/
private def isValidPubKeyNumber(token: ScriptToken): Boolean = token match {
case constant: ScriptConstant =>
constant.isInstanceOf[ScriptNumber] ||
ScriptNumber(constant.bytes) <= ScriptNumber(
Consensus.maxPublicKeysPerMultiSig)
case _: ScriptToken => false
}
}
/**
* Represents a [[https://bitcoin.org/en/developer-guide#pay-to-script-hash-p2sh pay-to-scripthash public key]]
* Format: `OP_HASH160 <Hash160(redeemScript)> OP_EQUAL`
*/
sealed trait P2SHScriptPubKey extends NonWitnessScriptPubKey {
/** The hash of the script for which this scriptPubKey is being created from */
def scriptHash: Sha256Hash160Digest =
Sha256Hash160Digest(asm(asm.length - 2).bytes)
override def toString = s"sh($scriptHash)"
}
object P2SHScriptPubKey extends ScriptFactory[P2SHScriptPubKey] {
private case class P2SHScriptPubKeyImpl(override val asm: Vector[ScriptToken])
extends P2SHScriptPubKey {
override def toString = s"P2SHScriptPubKey($scriptHash)"
}
def apply(scriptPubKey: ScriptPubKey): P2SHScriptPubKey = {
val hash = CryptoUtil.sha256Hash160(scriptPubKey.asmBytes)
P2SHScriptPubKey(hash)
}
def apply(hash: Sha256Hash160Digest): P2SHScriptPubKey = {
val pushOps = BitcoinScriptUtil.calculatePushOp(hash.bytes)
val asm = Seq(OP_HASH160) ++ pushOps ++ Seq(ScriptConstant(hash.bytes),
OP_EQUAL)
P2SHScriptPubKey(asm)
}
/** Checks if the given asm matches the pattern for
* [[org.bitcoins.core.protocol.script.P2SHScriptPubKey P2SHScriptPubKey]] */
def isP2SHScriptPubKey(asm: Seq[ScriptToken]): Boolean = asm match {
case Seq(OP_HASH160,
_: BytesToPushOntoStack,
_: ScriptConstant,
OP_EQUAL) =>
true
case _ => false
}
def fromAsm(asm: Seq[ScriptToken]): P2SHScriptPubKey = {
buildScript(asm.toVector,
P2SHScriptPubKeyImpl(_),
isP2SHScriptPubKey(_),
"Given asm was not a p2sh scriptPubkey, got: " + asm)
}
def apply(asm: Seq[ScriptToken]): P2SHScriptPubKey = fromAsm(asm)
}
/**
* Represents a [[https://bitcoin.org/en/developer-guide#pubkey pay to public key script public key]]
* Format: `<pubkey> OP_CHECKSIG`
*/
sealed trait P2PKScriptPubKey extends RawScriptPubKey {
def publicKey: ECPublicKey =
ECPublicKey(BitcoinScriptUtil.filterPushOps(asm).head.bytes)
override def toString = s"pk($publicKey)"
}
object P2PKScriptPubKey extends ScriptFactory[P2PKScriptPubKey] {
private case class P2PKScriptPubKeyImpl(override val asm: Vector[ScriptToken])
extends P2PKScriptPubKey {
override def toString = s"P2PKScriptPubKeyImpl($publicKey)"
}
def apply(pubKey: ECPublicKey): P2PKScriptPubKey = {
val pushOps = BitcoinScriptUtil.calculatePushOp(pubKey.bytes)
val asm = pushOps ++ Seq(ScriptConstant(pubKey.bytes), OP_CHECKSIG)
P2PKScriptPubKey(asm)
}
def fromAsm(asm: Seq[ScriptToken]): P2PKScriptPubKey = {
buildScript(asm.toVector,
P2PKScriptPubKeyImpl(_),
isP2PKScriptPubKey(_),
"Given asm was not a p2pk scriptPubKey, got: " + asm)
}
def apply(asm: Seq[ScriptToken]): P2PKScriptPubKey = fromAsm(asm)
/** Sees if the given asm matches the
* [[org.bitcoins.core.protocol.script.P2PKHScriptPubKey P2PKHScriptPubKey]] pattern */
def isP2PKScriptPubKey(asm: Seq[ScriptToken]): Boolean = asm match {
case Seq(_: BytesToPushOntoStack, _: ScriptConstant, OP_CHECKSIG) => true
case _ => false
}
}
sealed trait LockTimeScriptPubKey extends RawScriptPubKey {
/** Determines the nested `ScriptPubKey` inside the `LockTimeScriptPubKey` */
def nestedScriptPubKey: RawScriptPubKey = {
val bool: Boolean = asm.head.isInstanceOf[ScriptNumberOperation]
bool match {
case true => RawScriptPubKey(asm.slice(3, asm.length))
case false => RawScriptPubKey(asm.slice(4, asm.length))
}
}
/** The relative locktime value (i.e. the amount of time the output should remain unspendable) */
def locktime: ScriptNumber = {
asm.head match {
case scriptNumOp: ScriptNumberOperation =>
ScriptNumber(scriptNumOp.toLong)
case _: BytesToPushOntoStack => ScriptNumber(asm(1).hex)
case _: ScriptConstant | _: ScriptOperation =>
throw new IllegalArgumentException(
"In a LockTimeScriptPubKey, " +
"the first asm must be either a ScriptNumberOperation (i.e. OP_5), or the BytesToPushOntoStack " +
"for the proceeding ScriptConstant.")
}
}
}
object LockTimeScriptPubKey extends ScriptFactory[LockTimeScriptPubKey] {
def fromAsm(asm: Seq[ScriptToken]): LockTimeScriptPubKey = {
require(isValidLockTimeScriptPubKey(asm))
if (asm.contains(OP_CHECKLOCKTIMEVERIFY)) CLTVScriptPubKey(asm)
else if (asm.contains(OP_CHECKSEQUENCEVERIFY)) CSVScriptPubKey(asm)
else
throw new IllegalArgumentException(
"Given asm was not a LockTimeScriptPubKey, got: " + asm)
}
def isValidLockTimeScriptPubKey(asm: Seq[ScriptToken]): Boolean = {
CLTVScriptPubKey.isCLTVScriptPubKey(asm) || CSVScriptPubKey
.isCSVScriptPubKey(asm)
}
}
/**
* Represents a scriptPubKey that contains `OP_CHECKLOCKTIMEVERIFY.`
* Adds an absolute/defined locktime condition to any scriptPubKey.
* [[https://github.com/bitcoin/bips/blob/master/bip-0065.mediawiki BIP65]]
* Format: `<locktime> OP_CLTV OP_DROP <scriptPubKey>`
*/
sealed trait CLTVScriptPubKey extends LockTimeScriptPubKey
object CLTVScriptPubKey extends ScriptFactory[CLTVScriptPubKey] {
private case class CLTVScriptPubKeyImpl(override val asm: Vector[ScriptToken])
extends CLTVScriptPubKey {
override def toString = s"CLTVScriptPubKey($locktime, $nestedScriptPubKey)"
}
def fromAsm(asm: Seq[ScriptToken]): CLTVScriptPubKey = {
buildScript(asm.toVector,
CLTVScriptPubKeyImpl(_),
isCLTVScriptPubKey(_),
"Given asm was not a CLTVScriptPubKey, got: " + asm)
}
def apply(asm: Seq[ScriptToken]): CLTVScriptPubKey = fromAsm(asm)
def apply(
locktime: ScriptNumber,
scriptPubKey: ScriptPubKey): CLTVScriptPubKey = {
val scriptOp = BitcoinScriptUtil.minimalScriptNumberRepresentation(locktime)
val scriptNum: Seq[ScriptToken] =
if (scriptOp.isInstanceOf[ScriptNumberOperation]) {
Seq(scriptOp)
} else {
val pushOpsLockTime = BitcoinScriptUtil.calculatePushOp(locktime.bytes)
pushOpsLockTime ++ Seq(ScriptConstant(locktime.bytes))
}
val cltvAsm = Seq(OP_CHECKLOCKTIMEVERIFY, OP_DROP)
val scriptPubKeyAsm = scriptPubKey.asm
val asm = scriptNum ++ cltvAsm ++ scriptPubKeyAsm
CLTVScriptPubKey(asm)
}
def isCLTVScriptPubKey(asm: Seq[ScriptToken]): Boolean = {
if (asm.isEmpty) {
false
} else if (asm.head.isInstanceOf[BytesToPushOntoStack]) {
val tailTokens = asm.slice(4, asm.length)
if (P2SHScriptPubKey.isP2SHScriptPubKey(tailTokens) || tailTokens
.contains(OP_CHECKLOCKTIMEVERIFY)) return false
asm.slice(0, 4) match {
case Seq(_: BytesToPushOntoStack,
_: ScriptConstant,
OP_CHECKLOCKTIMEVERIFY,
OP_DROP) =>
validScriptAfterLockTime(tailTokens)
case _ => false
}
} else {
val tailTokens = asm.slice(3, asm.length)
if (P2SHScriptPubKey.isP2SHScriptPubKey(tailTokens) || tailTokens
.contains(OP_CHECKLOCKTIMEVERIFY)) return false
asm.slice(0, 3) match {
case Seq(_: ScriptNumberOperation, OP_CHECKLOCKTIMEVERIFY, OP_DROP) =>
validScriptAfterLockTime(tailTokens)
case _ => false
}
}
}
/**
* We need this check because sometimes we can get very lucky in having a non valid
* lock time script that has the first 4 bytes as a valid locktime script
* and then the bytes after the first 4 bytes gets lucky and is parsed by our
* [[org.bitcoins.core.serializers.script.ScriptParser ScriptParser]]
* A good way to see if this is _actually_ a valid script is by checking if we have any
* [[org.bitcoins.core.script.reserved.UndefinedOP_NOP UndefinedOP_NOP]] in the script,
* which means we definitely don't have a valid locktime script
*
* See this example of what happened before we added this check:
* [[https://travis-ci.org/bitcoin-s/bitcoin-s-core/builds/201652191#L2526 Travis CI]]
*/
def validScriptAfterLockTime(asm: Seq[ScriptToken]): Boolean = {
!asm.exists(_.isInstanceOf[UndefinedOP_NOP])
}
}
/**
* Represents a scriptPubKey that contains
* [[org.bitcoins.core.script.locktime.OP_CHECKSEQUENCEVERIFY OP_CHECKSEQUENCEVERIFY]]
* Adds a relative lockTime condition to any `scriptPubKey`.
* [[https://github.com/bitcoin/bips/blob/master/bip-0112.mediawiki BIP112]]
* Format: `<locktime> OP_CSV OP_DROP <scriptPubKey>`
*/
sealed trait CSVScriptPubKey extends LockTimeScriptPubKey
object CSVScriptPubKey extends ScriptFactory[CSVScriptPubKey] {
private case class CSVScriptPubKeyImpl(override val asm: Vector[ScriptToken])
extends CSVScriptPubKey {
override def toString = s"CSVScriptPubKey($locktime, $nestedScriptPubKey)"
}
def fromAsm(asm: Seq[ScriptToken]): CSVScriptPubKey = {
buildScript(asm.toVector,
CSVScriptPubKeyImpl(_),
isCSVScriptPubKey(_),
"Given asm was not a CSVScriptPubKey, got: " + asm)
}
def apply(asm: Seq[ScriptToken]): CSVScriptPubKey = fromAsm(asm)
def apply(
relativeLockTime: ScriptNumber,
scriptPubKey: ScriptPubKey): CSVScriptPubKey = {
val scriptOp =
BitcoinScriptUtil.minimalScriptNumberRepresentation(relativeLockTime)
val scriptNum: Seq[ScriptToken] =
if (scriptOp.isInstanceOf[ScriptNumberOperation]) {
Seq(scriptOp)
} else {
val pushOpsLockTime =
BitcoinScriptUtil.calculatePushOp(relativeLockTime.bytes)
pushOpsLockTime ++ Seq(ScriptConstant(relativeLockTime.bytes))
}
val csvAsm = Seq(OP_CHECKSEQUENCEVERIFY, OP_DROP)
val scriptPubKeyAsm = scriptPubKey.asm
val asm = scriptNum ++ csvAsm ++ scriptPubKeyAsm
CSVScriptPubKey(asm)
}
def isCSVScriptPubKey(asm: Seq[ScriptToken]): Boolean = {
if (asm.head.isInstanceOf[BytesToPushOntoStack]) {
val tailTokens = asm.slice(4, asm.length)
if (P2SHScriptPubKey.isP2SHScriptPubKey(tailTokens) || tailTokens
.contains(OP_CHECKSEQUENCEVERIFY)) return false
asm.slice(0, 4) match {
case Seq(_: BytesToPushOntoStack,
_: ScriptConstant,
OP_CHECKSEQUENCEVERIFY,
OP_DROP) =>
CLTVScriptPubKey.validScriptAfterLockTime(tailTokens)
case _ => false
}
} else {
val tailTokens = asm.slice(3, asm.length)
if (P2SHScriptPubKey.isP2SHScriptPubKey(tailTokens) || tailTokens
.contains(OP_CHECKSEQUENCEVERIFY)) return false
asm.slice(0, 3) match {
case Seq(_: ScriptNumberOperation, OP_CHECKSEQUENCEVERIFY, OP_DROP) =>
CLTVScriptPubKey.validScriptAfterLockTime(tailTokens)
case _ => false
}
}
}
}
/** Currently only supports a single OP_IF ... OP_ELSE ... OP_ENDIF ScriptPubKey */
sealed trait ConditionalScriptPubKey extends RawScriptPubKey {
def conditional: ConditionalOperation
require(asm.headOption.contains(conditional),
s"ConditionalScriptPubKey must begin with $conditional")
require(asm.last.equals(OP_ENDIF),
"ConditionalScriptPubKey must end in OP_ENDIF")
val (isValidConditional: Boolean, opElseIndexOpt: Option[Int]) = {
ConditionalScriptPubKey.isConditionalScriptPubKeyWithElseIndex(asm,
conditional)
}
require(isValidConditional, "Must be valid ConditionalScriptPubKey syntax")
require(opElseIndexOpt.isDefined,
"ConditionalScriptPubKey has to contain OP_ELSE asm token")
val opElseIndex: Int = opElseIndexOpt.get
require(!P2SHScriptPubKey.isP2SHScriptPubKey(trueSPK.asm) && !P2SHScriptPubKey
.isP2SHScriptPubKey(falseSPK.asm),
"ConditionalScriptPubKey cannot wrap P2SH")
require(
!WitnessScriptPubKey
.isWitnessScriptPubKey(trueSPK.asm) && !WitnessScriptPubKey
.isWitnessScriptPubKey(falseSPK.asm),
"ConditionalScriptPubKey cannot wrap SegWit ScriptPubKey"
)
def firstSPK: RawScriptPubKey = {
RawScriptPubKey
.fromAsm(asm.slice(1, opElseIndex))
}
def secondSPK: RawScriptPubKey = {
RawScriptPubKey
.fromAsm(asm.slice(opElseIndex + 1, asm.length - 1))
}
def trueSPK: RawScriptPubKey = {
conditional match {
case OP_IF => firstSPK
case OP_NOTIF => secondSPK
}
}
def falseSPK: RawScriptPubKey = {
conditional match {
case OP_IF => secondSPK
case OP_NOTIF => firstSPK
}
}
}
object ConditionalScriptPubKey {
/** Validates the correctness of the conditional syntax.
* If valid, also returns the index of the first outer-most OP_ELSE
*/
def isConditionalScriptPubKeyWithElseIndex(
asm: Seq[ScriptToken],
conditional: ConditionalOperation): (Boolean, Option[Int]) = {
val headIsConditional = asm.headOption.contains(conditional)
lazy val endsWithEndIf = asm.last == OP_ENDIF
var opElseIndexOpt: Option[Int] = None
lazy val validConditionalTree = {
// Already validate that the first token is OP_IF, go to tail
// and start with depth 1 and no OP_ELSE found for that depth
val opElsePendingOpt = asm.zipWithIndex.tail
.foldLeft[Option[Vector[Boolean]]](Some(Vector(false))) {
case (None, _) => // Invalid tree case, do no computation
None
case (Some(Vector()), _) => // Case of additional asm after final OP_ENDIF
None
case (Some(opElseFoundAtDepth), (OP_IF | OP_NOTIF, _)) =>
// Increase depth by one with OP_ELSE yet to be found for this depth
Some(opElseFoundAtDepth :+ false)
case (Some(opElseFoundAtDepth), (OP_ELSE, asmIndex)) =>
if (opElseFoundAtDepth == Vector(false)) {
// If first OP_ELSE at depth 1, set opElseIndex
opElseIndexOpt = Some(asmIndex)
}
if (opElseFoundAtDepth.last) {
// If OP_ELSE already found at this depth, invalid
None
} else {
// Otherwise, set to found at this depth
Some(
opElseFoundAtDepth.updated(opElseFoundAtDepth.length - 1, true))
}
case (Some(opElseFoundAtDepth), (OP_ENDIF, _)) =>
if (opElseFoundAtDepth.last) {
// If OP_ELSE found at this depth then valid, decrease depth by 1
Some(opElseFoundAtDepth.dropRight(1))
} else {
// Otherwise, invalid
None
}
case (Some(opElseFoundAtDepth), (_, _)) =>
// Token not related to conditional structure, ignore
Some(opElseFoundAtDepth)
}
// We should end on OP_ENDIF which will take us to depth 0
opElsePendingOpt.contains(Vector.empty)
}
(headIsConditional && endsWithEndIf && validConditionalTree, opElseIndexOpt)
}
def apply(
conditional: ConditionalOperation,
trueSPK: RawScriptPubKey,
falseSPK: RawScriptPubKey): ConditionalScriptPubKey = {
conditional match {
case OP_IF =>
(trueSPK, falseSPK) match {
case (multisig: MultiSignatureScriptPubKey,
timeout: CLTVScriptPubKey) =>
MultiSignatureWithTimeoutScriptPubKey(multisig, timeout)
case _ =>
NonStandardIfConditionalScriptPubKey(trueSPK, falseSPK)
}
case OP_NOTIF =>
NonStandardNotIfConditionalScriptPubKey(falseSPK, trueSPK)
}
}
}
sealed trait IfConditionalScriptPubKey extends ConditionalScriptPubKey {
override def conditional: ConditionalOperation = OP_IF
}
object NonStandardIfConditionalScriptPubKey
extends ScriptFactory[IfConditionalScriptPubKey] {
private case class NonStandardIfConditionalScriptPubKeyImpl(
override val asm: Vector[ScriptToken])
extends IfConditionalScriptPubKey {
override def toString: String =
s"IfConditionalScriptPubKey($trueSPK, $falseSPK)"
}
override def fromAsm(asm: Seq[ScriptToken]): IfConditionalScriptPubKey = {
buildScript(
asm = asm.toVector,
constructor = NonStandardIfConditionalScriptPubKeyImpl.apply,
invariant = isNonStandardIfConditionalScriptPubKey,
errorMsg = "Given asm was not a NonStandardIfConditionalScriptPubKey, got: " + asm
)
}
def apply(
trueSPK: RawScriptPubKey,
falseSPK: RawScriptPubKey): IfConditionalScriptPubKey = {
val asm = Vector(OP_IF) ++ trueSPK.asm ++ Vector(OP_ELSE) ++ falseSPK.asm ++ Vector(
OP_ENDIF)
fromAsm(asm)
}
def isNonStandardIfConditionalScriptPubKey(asm: Seq[ScriptToken]): Boolean = {
val validIf = ConditionalScriptPubKey
.isConditionalScriptPubKeyWithElseIndex(asm, OP_IF)
._1
val isMultiSigWithTimeout = MultiSignatureWithTimeoutScriptPubKey
.isMultiSignatureWithTimeoutScriptPubKey(asm)
validIf && !isMultiSigWithTimeout
}
}
sealed trait MultiSignatureWithTimeoutScriptPubKey
extends IfConditionalScriptPubKey {
require(
MultiSignatureScriptPubKey.isMultiSignatureScriptPubKey(super.firstSPK.asm),
"True case must be MultiSignatureSPK")
require(CLTVScriptPubKey.isCLTVScriptPubKey(super.secondSPK.asm),
"False case must be CLTVSPK")
override def firstSPK: MultiSignatureScriptPubKey = {
MultiSignatureScriptPubKey.fromAsm(asm.slice(1, opElseIndex))
}
override def secondSPK: CLTVScriptPubKey = {
CLTVScriptPubKey.fromAsm(asm.slice(opElseIndex + 1, asm.length - 1))
}
override def trueSPK: MultiSignatureScriptPubKey = firstSPK
override def falseSPK: CLTVScriptPubKey = secondSPK
def multiSigSPK: MultiSignatureScriptPubKey = firstSPK
def timeoutSPK: CLTVScriptPubKey = secondSPK
def requiredSigs: Int = multiSigSPK.requiredSigs
def maxSigs: Int = multiSigSPK.maxSigs
def timeout: Int = timeoutSPK.locktime.toInt
}
object MultiSignatureWithTimeoutScriptPubKey
extends ScriptFactory[MultiSignatureWithTimeoutScriptPubKey] {
private case class MultiSignatureWithTimeoutScriptPubKeyImpl(
override val asm: Vector[ScriptToken])
extends MultiSignatureWithTimeoutScriptPubKey {
override def toString: String =
s"MultiSignatureWithTimeoutScriptPubKey($trueSPK, $falseSPK)"
}
override def fromAsm(
asm: Seq[ScriptToken]): MultiSignatureWithTimeoutScriptPubKey = {
buildScript(
asm = asm.toVector,
constructor = MultiSignatureWithTimeoutScriptPubKeyImpl.apply,
invariant = isMultiSignatureWithTimeoutScriptPubKey,
errorMsg =
s"Given asm was not a MultiSignatureWithTimeoutScriptPubKey, got: $asm"
)
}
def apply(
multiSigSPK: MultiSignatureScriptPubKey,
cltvSPK: CLTVScriptPubKey): MultiSignatureWithTimeoutScriptPubKey = {
val asm = Vector(OP_IF) ++ multiSigSPK.asm ++ Vector(OP_ELSE) ++ cltvSPK.asm ++ Vector(
OP_ENDIF)
fromAsm(asm)
}
def isMultiSignatureWithTimeoutScriptPubKey(
asm: Seq[ScriptToken]): Boolean = {
val (validIf, opElseIndexOpt) = ConditionalScriptPubKey
.isConditionalScriptPubKeyWithElseIndex(asm, OP_IF)
lazy val validMultiSigWithCLTV = opElseIndexOpt match {
case Some(opElseIndex) =>
MultiSignatureScriptPubKey
.isMultiSignatureScriptPubKey(asm.slice(1, opElseIndex)) && CLTVScriptPubKey
.isCLTVScriptPubKey(asm.slice(opElseIndex + 1, asm.length - 1))
case _ => false
}
validIf && validMultiSigWithCLTV
}
}
sealed trait NotIfConditionalScriptPubKey extends ConditionalScriptPubKey {
override def conditional: ConditionalOperation = OP_NOTIF
}
object NonStandardNotIfConditionalScriptPubKey
extends ScriptFactory[NotIfConditionalScriptPubKey] {
private case class NonStandardNotIfConditionalScriptPubKeyImpl(
override val asm: Vector[ScriptToken])
extends NotIfConditionalScriptPubKey {
override def toString: String =
s"NotIfConditionalScriptPubKey($falseSPK, $trueSPK)"
}
override def fromAsm(asm: Seq[ScriptToken]): NotIfConditionalScriptPubKey = {
buildScript(
asm = asm.toVector,
constructor = NonStandardNotIfConditionalScriptPubKeyImpl.apply,
invariant = isNonStandardNotIfConditionalScriptPubKey,
errorMsg = "Given asm was not a NotIfConditionalScriptPubKey, got: " + asm
)
}
def apply(
falseSPK: RawScriptPubKey,
trueSPK: RawScriptPubKey): NotIfConditionalScriptPubKey = {
val asm = Vector(OP_NOTIF) ++ falseSPK.asm ++ Vector(OP_ELSE) ++ trueSPK.asm ++ Vector(
OP_ENDIF)
fromAsm(asm)
}
def isNonStandardNotIfConditionalScriptPubKey(
asm: Seq[ScriptToken]): Boolean = {
ConditionalScriptPubKey
.isConditionalScriptPubKeyWithElseIndex(asm, OP_NOTIF)
._1
}
}
/** The type for ScriptPubKeys of the form:
* OP_IF
* <Public Key>
* OP_ELSE
* <Timeout> OP_CHECKLOCKTIMEVERIFY OP_DROP
* <Timeout Public Key>
* OP_ENDIF
* OP_CHECKSIG
*/
sealed trait P2PKWithTimeoutScriptPubKey extends RawScriptPubKey {
lazy val pubKey: ECPublicKey =
ECPublicKey.fromBytes(asm(2).bytes)
lazy val lockTime: ScriptNumber = ScriptNumber.fromBytes(asm(5).bytes)
lazy val timeoutPubKey: ECPublicKey =
ECPublicKey.fromBytes(asm(9).bytes)
}
object P2PKWithTimeoutScriptPubKey
extends ScriptFactory[P2PKWithTimeoutScriptPubKey] {
private case class P2PKWithTimeoutScriptPubKeyImpl(asm: Vector[ScriptToken])
extends P2PKWithTimeoutScriptPubKey
override def fromAsm(asm: Seq[ScriptToken]): P2PKWithTimeoutScriptPubKey = {
buildScript(
asm = asm.toVector,
constructor = P2PKWithTimeoutScriptPubKeyImpl.apply,
invariant = isP2PKWithTimeoutScriptPubKey,
errorMsg = s"Given asm was not a P2PKWithTimeoutScriptPubKey, got $asm"
)
}
def apply(
pubKey: ECPublicKey,
lockTime: ScriptNumber,
timeoutPubKey: ECPublicKey): P2PKWithTimeoutScriptPubKey = {
val timeoutAsm = CLTVScriptPubKey(lockTime, EmptyScriptPubKey).asm.toVector
val pubKeyAsm = BitcoinScriptUtil
.calculatePushOp(pubKey.bytes)
.toVector ++ Vector(ScriptConstant(pubKey.bytes))
val timeoutPubKeyAsm = BitcoinScriptUtil
.calculatePushOp(timeoutPubKey.bytes)
.toVector ++ Vector(ScriptConstant(timeoutPubKey.bytes))
P2PKWithTimeoutScriptPubKeyImpl(
Vector(Vector(OP_IF),
pubKeyAsm,
Vector(OP_ELSE),
timeoutAsm,
timeoutPubKeyAsm,
Vector(OP_ENDIF, OP_CHECKSIG)).flatten
)
}
def isP2PKWithTimeoutScriptPubKey(asm: Seq[ScriptToken]): Boolean = {
if (asm.length == 12) {
val pubKey = ECPublicKey.fromBytes(asm(2).bytes)
val lockTimeTry = Try(ScriptNumber.fromBytes(asm(5).bytes))
val timeoutPubKey = ECPublicKey.fromBytes(asm(9).bytes)
lockTimeTry match {
case Success(lockTime) =>
asm == P2PKWithTimeoutScriptPubKey(pubKey, lockTime, timeoutPubKey).asm
case Failure(_) => false
}
} else {
false
}
}
}
sealed trait NonStandardScriptPubKey extends RawScriptPubKey
object NonStandardScriptPubKey extends ScriptFactory[NonStandardScriptPubKey] {
private case class NonStandardScriptPubKeyImpl(
override val asm: Vector[ScriptToken])
extends NonStandardScriptPubKey {
override def toString = s"NonStandardScriptPubKey($asm)"
}
def fromAsm(asm: Seq[ScriptToken]): NonStandardScriptPubKey = {
//everything can be a NonStandardScriptPubkey, thus the trivially true function
buildScript(asm.toVector, NonStandardScriptPubKeyImpl(_), { _ =>
true
}, "")
}
def apply(asm: Seq[ScriptToken]): NonStandardScriptPubKey = fromAsm(asm)
}
/** Represents the empty ScriptPubKey */
case object EmptyScriptPubKey extends RawScriptPubKey {
override def asm: Seq[ScriptToken] = Vector.empty
}
object RawScriptPubKey extends ScriptFactory[RawScriptPubKey] {
val empty: RawScriptPubKey = fromAsm(Nil)
def fromAsm(asm: Seq[ScriptToken]): RawScriptPubKey = asm match {
case Nil => EmptyScriptPubKey
case _ if P2PKWithTimeoutScriptPubKey.isP2PKWithTimeoutScriptPubKey(asm) =>
P2PKWithTimeoutScriptPubKey.fromAsm(asm)
case _
if MultiSignatureWithTimeoutScriptPubKey
.isMultiSignatureWithTimeoutScriptPubKey(asm) =>
MultiSignatureWithTimeoutScriptPubKey.fromAsm(asm)
case _
if NonStandardIfConditionalScriptPubKey
.isNonStandardIfConditionalScriptPubKey(asm) =>
NonStandardIfConditionalScriptPubKey.fromAsm(asm)
case _
if NonStandardNotIfConditionalScriptPubKey
.isNonStandardNotIfConditionalScriptPubKey(asm) =>
NonStandardNotIfConditionalScriptPubKey.fromAsm(asm)
case _ if P2PKHScriptPubKey.isP2PKHScriptPubKey(asm) =>
P2PKHScriptPubKey(asm)
case _ if P2PKScriptPubKey.isP2PKScriptPubKey(asm) => P2PKScriptPubKey(asm)
case _ if MultiSignatureScriptPubKey.isMultiSignatureScriptPubKey(asm) =>
MultiSignatureScriptPubKey(asm)
case _ if CLTVScriptPubKey.isCLTVScriptPubKey(asm) => CLTVScriptPubKey(asm)
case _ if CSVScriptPubKey.isCSVScriptPubKey(asm) => CSVScriptPubKey(asm)
case _ if WitnessCommitment.isWitnessCommitment(asm) =>
WitnessCommitment(asm)
case _ => NonStandardScriptPubKey(asm)
}
def apply(asm: Seq[ScriptToken]): RawScriptPubKey = fromAsm(asm)
}