-
Notifications
You must be signed in to change notification settings - Fork 872
Expand file tree
/
Copy pathscript_tests.cs
More file actions
1569 lines (1367 loc) · 75.5 KB
/
script_tests.cs
File metadata and controls
1569 lines (1367 loc) · 75.5 KB
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
using NBitcoin.Crypto;
using NBitcoin.DataEncoders;
using NBitcoin.Protocol;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
#if !NOCONSENSUSLIB
using System.Net.Http;
#endif
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using Newtonsoft.Json.Linq;
using System.Runtime.InteropServices;
using FsCheck;
using System.Net.Http;
using System.IO.Compression;
using Xunit.Abstractions;
namespace NBitcoin.Tests
{
public class script_tests
{
ITestOutputHelper Log;
public script_tests(ITestOutputHelper outputHelper)
{
Log = outputHelper;
}
static Dictionary<string, OpcodeType> mapOpNames = new Dictionary<string, OpcodeType>();
public static Script ParseScript(string s)
{
MemoryStream result = new MemoryStream();
if (mapOpNames.Count == 0)
{
mapOpNames = new Dictionary<string, OpcodeType>(Op._OpcodeByName);
foreach (var kv in mapOpNames.ToArray())
{
if (kv.Key.StartsWith("OP_", StringComparison.Ordinal))
{
var name = kv.Key.Substring(3, kv.Key.Length - 3);
mapOpNames.AddOrReplace(name, kv.Value);
}
}
}
var words = s.Split(' ', '\t', '\n');
foreach (string w in words)
{
if (w == "")
continue;
if (w.All(l => l.IsDigit()) ||
(w.StartsWith("-") && w.Substring(1).All(l => l.IsDigit())))
{
// Number
long n = long.Parse(w);
Op.GetPushOp(n).WriteTo(result);
}
else if (w.StartsWith("0x") && HexEncoder.IsWellFormed(w.Substring(2)))
{
// Raw hex data, inserted NOT pushed onto stack:
var raw = Encoders.Hex.DecodeData(w.Substring(2));
result.Write(raw, 0, raw.Length);
}
else if (w.Length >= 2 && w.StartsWith("'") && w.EndsWith("'"))
{
// Single-quoted string, pushed as data. NOTE: this is poor-man's
// parsing, spaces/tabs/newlines in single-quoted strings won't work.
var b = TestUtils.ToBytes(w.Substring(1, w.Length - 2));
Op.GetPushOp(b).WriteTo(result);
}
else if (mapOpNames.ContainsKey(w))
{
// opcode, e.g. OP_ADD or ADD:
result.WriteByte((byte)mapOpNames[w]);
}
else
{
Assert.Fail("Invalid test");
return null;
}
}
return new Script(result.ToArray());
}
[Fact]
[Trait("UnitTest", "UnitTest")]
public void CanParseNOPs()
{
new Script("OP_NOP1 OP_NOP2 OP_NOP3 OP_NOP4 OP_NOP5 OP_NOP6 OP_NOP7 OP_NOP8 OP_NOP9");
}
[Fact]
[Trait("UnitTest", "UnitTest")]
public void BIP65_tests()
{
BIP65_testsCore(
Utils.UnixTimeToDateTime(510000000),
Utils.UnixTimeToDateTime(509999999),
false);
BIP65_testsCore(
Utils.UnixTimeToDateTime(510000000),
Utils.UnixTimeToDateTime(510000000),
true);
BIP65_testsCore(
Utils.UnixTimeToDateTime(510000000),
Utils.UnixTimeToDateTime(510000001),
true);
BIP65_testsCore(
1000,
999,
false);
BIP65_testsCore(
1000,
1000,
true);
BIP65_testsCore(
1000,
1001,
true);
//Bad comparison
BIP65_testsCore(
1000,
Utils.UnixTimeToDateTime(510000001),
false);
BIP65_testsCore(
Utils.UnixTimeToDateTime(510000001),
1000,
false);
Script s = new Script(OpcodeType.OP_CHECKLOCKTIMEVERIFY);
Assert.Equal("OP_CLTV", s.ToString());
s = new Script("OP_CHECKLOCKTIMEVERIFY");
Assert.Equal("OP_CLTV", s.ToString());
s = new Script("OP_NOP2");
Assert.Equal("OP_CLTV", s.ToString());
s = new Script("OP_HODL");
Assert.Equal("OP_CLTV", s.ToString());
}
private void BIP65_testsCore(LockTime target, LockTime now, bool expectedResult)
{
Transaction tx = Network.CreateTransaction();
tx.Inputs.Add();
tx.Outputs.Add(new TxOut()
{
ScriptPubKey = new Script(Op.GetPushOp(target.Value), OpcodeType.OP_CHECKLOCKTIMEVERIFY)
});
Transaction spending = Network.CreateTransaction();
spending.LockTime = now;
spending.Inputs.Add(new TxIn(tx.Outputs.AsCoins().First().Outpoint, new Script()));
spending.Inputs[0].Sequence = 1;
Assert.Equal(expectedResult, spending.Inputs.AsIndexedInputs().First().VerifyScript(tx.Outputs[0]));
spending.Inputs[0].Sequence = uint.MaxValue;
Assert.False(spending.Inputs.AsIndexedInputs().First().VerifyScript(tx.Outputs[0]));
}
[Fact]
[Trait("UnitTest", "UnitTest")]
public void CanUseCompactVarInt()
{
var tests = new[]{
new object[]{0UL, new byte[]{0}},
new object[]{1UL, new byte[]{1}},
new object[]{127UL, new byte[]{0x7F}},
new object[]{128UL, new byte[]{0x80, 0x00}},
new object[]{255UL, new byte[]{0x80, 0x7F}},
new object[]{256UL, new byte[]{0x81, 0x00}},
new object[]{16383UL, new byte[]{0xFE, 0x7F}},
//new object[]{16384UL, new byte[]{0xFF, 0x00}},
//new object[]{16511UL, new byte[]{0x80, 0xFF, 0x7F}},
//new object[]{65535UL, new byte[]{0x82, 0xFD, 0x7F}},
new object[]{(ulong)1 << 32, new byte[]{0x8E, 0xFE, 0xFE, 0xFF, 0x00}},
};
foreach (var test in tests)
{
ulong val = (ulong)test[0];
byte[] expectedBytes = (byte[])test[1];
AssertEx.CollectionEquals(new CompactVarInt(val, sizeof(ulong)).ToBytes(), expectedBytes);
AssertEx.CollectionEquals(new CompactVarInt(val, sizeof(uint)).ToBytes(), expectedBytes);
var compact = new CompactVarInt(sizeof(ulong));
compact.ReadWrite(expectedBytes, Network.Main);
Assert.Equal(val, compact.ToLong());
compact = new CompactVarInt(sizeof(uint));
compact.ReadWrite(expectedBytes, Network.Main);
Assert.Equal(val, compact.ToLong());
}
foreach (var i in Enumerable.Range(0, 65535 * 4))
{
var compact = new CompactVarInt((ulong)i, sizeof(ulong));
var bytes = compact.ToBytes();
compact = new CompactVarInt(sizeof(ulong));
compact.ReadWrite(bytes, Network.Main);
Assert.Equal((ulong)i, compact.ToLong());
}
}
[Fact]
[Trait("UnitTest", "UnitTest")]
public void CanExtractScriptCode()
{
var script = new Script("022b1300040df7414c0251433b7a2516e81689b02e33299c87ae870b5c9407b761 OP_DEPTH 3 OP_EQUAL OP_IF OP_SWAP 020524b8de0a1b57478f2d0e07aa9ea375b736f072281b3749fea044392bccfc52 OP_CHECKSIGVERIFY OP_CODESEPARATOR OP_CHECKSIG OP_ELSE 0 OP_CLTV OP_DROP OP_CHECKSIG OP_ENDIF");
Assert.Throws<ArgumentOutOfRangeException>(() => script.ExtractScriptCode(-2));
Assert.Throws<ArgumentOutOfRangeException>(() => script.ExtractScriptCode(1));
Assert.Equal("OP_CHECKSIG OP_ELSE 0 OP_CLTV OP_DROP OP_CHECKSIG OP_ENDIF", script.ExtractScriptCode(0).ToString());
Assert.Equal(script, script.ExtractScriptCode(-1));
}
[Fact]
[Trait("UnitTest", "UnitTest")]
public void CanCompressScript2()
{
var key = new Key(true);
var script = PayToPubkeyHashTemplate.Instance.GenerateScriptPubKey(key.PubKey.Hash);
var compressed = script.ToCompressedBytes();
Assert.Equal(21, compressed.Length);
Assert.Equal(script.ToString(), new Script(compressed, true).ToString());
}
[Fact]
[Trait("UnitTest", "UnitTest")]
public void CanParseAndGeneratePayToTaprootScripts()
{
var pubkey = new TaprootPubKey(Encoders.Hex.DecodeData("53a1f6e454df1aa2776a2814a721372d6258050de330b3c6d10ee8f4e0dda343"));
var scriptPubKey = new Script("1 53a1f6e454df1aa2776a2814a721372d6258050de330b3c6d10ee8f4e0dda343");
#pragma warning disable CS0618 // Type or member is obsolete
Assert.Equal(scriptPubKey, PayToTaprootTemplate.Instance.GenerateScriptPubKey(pubkey));
#pragma warning restore CS0618 // Type or member is obsolete
Assert.Equal(pubkey, PayToTaprootTemplate.Instance.ExtractScriptPubKeyParameters(scriptPubKey));
// signature has wrong length
scriptPubKey = new Script("1 53a1f6e454df1aa2776a2814a721372d6258050de330b3c6d10ee8f4e0dda34300");
Assert.Null(PayToTaprootTemplate.Instance.ExtractScriptPubKeyParameters(scriptPubKey));
// segwit version is missing
scriptPubKey = new Script("53a1f6e454df1aa2776a2814a721372d6258050de330b3c6d10ee8f4e0dda343");
Assert.Null(PayToTaprootTemplate.Instance.ExtractScriptPubKeyParameters(scriptPubKey));
// too many witnesses
scriptPubKey = new Script("1 53a1f6e454df1aa2776a2814a721372d6258050de330b3c6d10ee8f4e0dda343 00");
Assert.Null(PayToTaprootTemplate.Instance.ExtractScriptPubKeyParameters(scriptPubKey));
var sig = TaprootSignature.Parse(Encoders.Hex.DecodeData("e907831f80848d1069a5371b402410364bdf1c5f8307b0084c55f1ce2dca821525f66a4a85ea8b71e482a74f382d2ce5ebeee8fdb2172f477df4900d310536c0"));
var witScript = new WitScript("e907831f80848d1069a5371b402410364bdf1c5f8307b0084c55f1ce2dca821525f66a4a85ea8b71e482a74f382d2ce5ebeee8fdb2172f477df4900d310536c0");
Assert.Equal(witScript, PayToTaprootTemplate.Instance.GenerateWitScript(sig));
var annex = new byte[] { 0x50 };
witScript = new WitScript("e907831f80848d1069a5371b402410364bdf1c5f8307b0084c55f1ce2dca821525f66a4a85ea8b71e482a74f382d2ce5ebeee8fdb2172f477df4900d310536c0 50");
Assert.Equal(witScript, PayToTaprootTemplate.Instance.GenerateWitScript(sig, annex));
// first byte of annex is not 0x50
annex = new byte[] { 0x00 };
Assert.Throws<ArgumentException>(() => PayToTaprootTemplate.Instance.GenerateWitScript(sig, annex));
// annex is empty
annex = new byte[] { };
Assert.Throws<ArgumentException>(() => PayToTaprootTemplate.Instance.GenerateWitScript(sig, annex));
witScript = new WitScript("e907831f80848d1069a5371b402410364bdf1c5f8307b0084c55f1ce2dca821525f66a4a85ea8b71e482a74f382d2ce5ebeee8fdb2172f477df4900d310536c0");
Assert.Equal(sig.ToBytes(), PayToTaprootTemplate.Instance.ExtractWitScriptParameters(witScript).TransactionSignature.ToBytes());
Assert.Null(PayToTaprootTemplate.Instance.ExtractWitScriptParameters(witScript).Annex);
witScript = new WitScript("e907831f80848d1069a5371b402410364bdf1c5f8307b0084c55f1ce2dca821525f66a4a85ea8b71e482a74f382d2ce5ebeee8fdb2172f477df4900d310536c0 50");
annex = new byte[] { 0x50 };
Assert.Equal(sig.ToBytes(), PayToTaprootTemplate.Instance.ExtractWitScriptParameters(witScript).TransactionSignature.ToBytes());
Assert.Equal(annex, PayToTaprootTemplate.Instance.ExtractWitScriptParameters(witScript).Annex);
// first byte of annex is not 0x50
witScript = new WitScript("e907831f80848d1069a5371b402410364bdf1c5f8307b0084c55f1ce2dca821525f66a4a85ea8b71e482a74f382d2ce5ebeee8fdb2172f477df4900d310536c0 10");
Assert.Null(PayToTaprootTemplate.Instance.ExtractWitScriptParameters(witScript));
// annex is empty
witScript = new WitScript("e907831f80848d1069a5371b402410364bdf1c5f8307b0084c55f1ce2dca821525f66a4a85ea8b71e482a74f382d2ce5ebeee8fdb2172f477df4900d310536c0");
Assert.Null(PayToTaprootTemplate.Instance.ExtractWitScriptParameters(witScript).Annex);
}
[Fact]
[Trait("UnitTest", "UnitTest")]
public void PayToMultiSigTemplateShouldAcceptNonKeyParameters()
{
var tx = Transaction.Parse("0100000002f9cbafc519425637ba4227f8d0a0b7160b4e65168193d5af39747891de98b5b5000000006b4830450221008dd619c563e527c47d9bd53534a770b102e40faa87f61433580e04e271ef2f960220029886434e18122b53d5decd25f1f4acb2480659fea20aabd856987ba3c3907e0121022b78b756e2258af13779c1a1f37ea6800259716ca4b7f0b87610e0bf3ab52a01ffffffff42e7988254800876b69f24676b3e0205b77be476512ca4d970707dd5c60598ab00000000fd260100483045022015bd0139bcccf990a6af6ec5c1c52ed8222e03a0d51c334df139968525d2fcd20221009f9efe325476eb64c3958e4713e9eefe49bf1d820ed58d2112721b134e2a1a53034930460221008431bdfa72bc67f9d41fe72e94c88fb8f359ffa30b33c72c121c5a877d922e1002210089ef5fc22dd8bfc6bf9ffdb01a9862d27687d424d1fefbab9e9c7176844a187a014c9052483045022015bd0139bcccf990a6af6ec5c1c52ed8222e03a0d51c334df139968525d2fcd20221009f9efe325476eb64c3958e4713e9eefe49bf1d820ed58d2112721b134e2a1a5303210378d430274f8c5ec1321338151e9f27f4c676a008bdf8638d07c0b6be9ab35c71210378d430274f8c5ec1321338151e9f27f4c676a008bdf8638d07c0b6be9ab35c7153aeffffffff01a08601000000000017a914d8dacdadb7462ae15cd906f1878706d0da8660e68700000000", Network.Main);
var redeemScript = PayToScriptHashTemplate.Instance.ExtractScriptSigParameters(tx.Inputs[1].ScriptSig).RedeemScript;
var result = PayToMultiSigTemplate.Instance.ExtractScriptPubKeyParameters(redeemScript);
Assert.Equal(2, result.PubKeys.Length);
Assert.Equal(2, result.SignatureCount);
Assert.Single(result.InvalidPubKeys);
}
[Fact]
[Trait("UnitTest", "UnitTest")]
public void PayToPubkeyHashTemplateDoNotCrashOnInvalidSig()
{
var data = Encoders.Hex.DecodeData("035c030441ef8fa580553f149a5422ba4b0038d160b07a28e6fe2e1041b940fe95b1553c040000000000000050db680300000000000002b0466f722050696572636520616e64205061756c");
PayToPubkeyHashTemplate.Instance.ExtractScriptSigParameters(new Script(data));
}
[Fact]
[Trait("UnitTest", "UnitTest")]
public void CanCompressScript()
{
var key = new Key(true);
//Pay to pubkey hash (encoded as 21 bytes)
var script = PayToPubkeyHashTemplate.Instance.GenerateScriptPubKey(key.PubKey.Hash);
AssertCompressed(script, 21);
script = PayToPubkeyHashTemplate.Instance.GenerateScriptPubKey(key.PubKey.Decompress().Hash);
AssertCompressed(script, 21);
//Pay to script hash (encoded as 21 bytes)
script = PayToScriptHashTemplate.Instance.GenerateScriptPubKey(script);
AssertCompressed(script, 21);
//Pay to pubkey starting with 0x02, 0x03 or 0x04 (encoded as 33 bytes)
script = PayToPubkeyTemplate.Instance.GenerateScriptPubKey(key.PubKey);
script = AssertCompressed(script, 33);
var readenKey = PayToPubkeyTemplate.Instance.ExtractScriptPubKeyParameters(script);
AssertEx.CollectionEquals(readenKey.ToBytes(), key.PubKey.ToBytes());
script = PayToPubkeyTemplate.Instance.GenerateScriptPubKey(key.PubKey.Decompress());
script = AssertCompressed(script, 33);
readenKey = PayToPubkeyTemplate.Instance.ExtractScriptPubKeyParameters(script);
AssertEx.CollectionEquals(readenKey.ToBytes(), key.PubKey.Decompress().ToBytes());
//Other scripts up to 121 bytes require 1 byte + script length.
script = new Script(Enumerable.Range(0, 60).Select(_ => (Op)OpcodeType.OP_RETURN).ToArray());
AssertCompressed(script, 61);
script = new Script(Enumerable.Range(0, 120).Select(_ => (Op)OpcodeType.OP_RETURN).ToArray());
AssertCompressed(script, 121);
//Above that, scripts up to 16505 bytes require 2 bytes + script length.
script = new Script(Enumerable.Range(0, 122).Select(_ => (Op)OpcodeType.OP_RETURN).ToArray());
AssertCompressed(script, 124);
}
private Script AssertCompressed(Script script, int expectedSize)
{
var compressor = new ScriptCompressor(script);
var compressed = compressor.ToBytes();
Assert.Equal(expectedSize, compressed.Length);
compressor = new ScriptCompressor();
compressor.ReadWrite(compressed, Network);
AssertEx.CollectionEquals(compressor.GetScript().ToBytes(), script.ToBytes());
var compressed2 = compressor.ToBytes();
AssertEx.CollectionEquals(compressed, compressed2);
return compressor.GetScript();
}
[Fact]
[Trait("Core", "Core")]
public void sig_validinvalid()
{
Assert.False(TransactionSignature.IsValid(new byte[0]));
var sigs = JArray.Parse(File.ReadAllText("data/sig_canonical.json"));
foreach (var sig in sigs)
{
Assert.True(TransactionSignature.IsValid(Encoders.Hex.DecodeData(sig.ToString())));
}
sigs = JArray.Parse(File.ReadAllText("data/sig_noncanonical.json"));
foreach (var sig in sigs)
{
if (((HexEncoder)Encoders.Hex).IsValid(sig.ToString()))
{
Assert.False(TransactionSignature.IsValid(Encoders.Hex.DecodeData(sig.ToString())));
}
}
}
[Fact]
[Trait("Core", "Core")]
public void script_json_tests()
{
EnsureHasLibConsensus();
var tests = TestCase.read_json("data/script_tests.json");
foreach (var test in tests)
{
if (test.Count == 1)
continue;
int i = 0;
Script wit = null;
Money amount = Money.Zero;
if (test[i] is JArray)
{
var array = (JArray)test[i];
for (int ii = 0; ii < array.Count - 1; ii++)
{
wit += Encoders.Hex.DecodeData(array[ii].ToString());
}
amount = Money.Coins(((JValue)(array[array.Count - 1])).Value<decimal>());
i++;
}
var scriptSig = ParseScript((string)test[i++]);
var scriptPubKey = ParseScript((string)test[i++]);
var flag = ParseFlag((string)test[i++]);
var expectedError = ParseScriptError((string)test[i++]);
var comment = i < test.Count ? (string)test[i++] : "no comment";
Assert.Equal(scriptSig.ToString(), new Script(scriptSig.ToString()).ToString());
Assert.Equal(scriptPubKey.ToString(), new Script(scriptPubKey.ToString()).ToString());
AssertVerifyScript(wit, amount, scriptSig, scriptPubKey, flag, test.Index, comment, expectedError);
}
}
private void AssertVerifyScript(WitScript wit, Money amount, Script scriptSig, Script scriptPubKey, ScriptVerify flags, int testIndex, string comment, ScriptError expectedError)
{
if (flags.HasFlag(ScriptVerify.CleanStack))
{
flags |= ScriptVerify.Witness;
flags |= ScriptVerify.P2SH;
}
var creditingTransaction = CreateCreditingTransaction(scriptPubKey, amount);
var spendingTransaction = CreateSpendingTransaction(wit, scriptSig, creditingTransaction);
spendingTransaction.Inputs.FindIndexedInput(0).VerifyScript(new TxOut(amount, scriptPubKey), flags, out var actual);
Assert.True(expectedError == actual, "Test : " + testIndex + " " + comment);
#if !NOCONSENSUSLIB
var ok = Script.VerifyScriptConsensus(scriptPubKey, spendingTransaction, 0, amount, flags);
// If the spendingTransaction correctly spends the scriptPubKey but the expected error is not okay
// because of a policy flags then, we ignore the test; otherwise assert everything the expected result
// is the expected one.
if (ok && (expectedError != ScriptError.OK) && (flags & ~ScriptVerify.Consensus) != 0)
return;
Assert.True(ok == (expectedError == ScriptError.OK), "[ConsensusLib] Test : " + testIndex + " " + comment);
#endif
}
private void EnsureHasLibConsensus()
{
#if !NOCONSENSUSLIB
var bitcoinPath = NodeBuilder.EnsureDownloaded(NodeDownloadData.Bitcoin.v0_17_0);
string libConsensusDll = null;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
libConsensusDll = "libbitcoinconsensus-0.dll";
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
libConsensusDll = "libbitcoinconsensus.0.dylib";
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
libConsensusDll = "libbitcoinconsensus.so";
}
else
{
throw new NotSupportedException("Unknown operating system");
}
bitcoinPath = Path.GetDirectoryName(bitcoinPath);
var libConsensusPath = Path.Combine(bitcoinPath, "..", "lib", libConsensusDll);
libConsensusPath = Path.GetFullPath(libConsensusPath);
try
{
File.Copy(libConsensusPath, $"./{libConsensusDll}", overwrite: false);
}
catch (IOException)
{
}
#endif
}
private static Transaction CreateSpendingTransaction(WitScript wit, Script scriptSig, Transaction creditingTransaction)
{
var spendingTransaction = Network.CreateTransaction();
spendingTransaction.Inputs.Add(new OutPoint(creditingTransaction, 0), scriptSig, wit ?? WitScript.Empty);
spendingTransaction.Outputs.Add(creditingTransaction.Outputs[0].Value, new Script());
return spendingTransaction;
}
private static Transaction CreateCreditingTransaction(Script scriptPubKey, Money amount = null)
{
amount = amount ?? Money.Zero;
var creditingTransaction = Network.CreateTransaction();
creditingTransaction.Version = 1;
creditingTransaction.LockTime = LockTime.Zero;
creditingTransaction.Inputs.Add(scriptSig: new Script(OpcodeType.OP_0, OpcodeType.OP_0), sequence: Sequence.Final);
creditingTransaction.Outputs.Add(amount, scriptPubKey);
return creditingTransaction;
}
private ScriptError ParseScriptError(string str)
{
if (str == "OK")
return ScriptError.OK;
if (str == "EVAL_FALSE")
return ScriptError.EvalFalse;
if (str == "BAD_OPCODE")
return ScriptError.BadOpCode;
if (str == "UNBALANCED_CONDITIONAL")
return ScriptError.UnbalancedConditional;
if (str == "OP_RETURN")
return ScriptError.OpReturn;
if (str == "VERIFY")
return ScriptError.Verify;
if (str == "INVALID_ALTSTACK_OPERATION")
return ScriptError.InvalidAltStackOperation;
if (str == "INVALID_STACK_OPERATION")
return ScriptError.InvalidStackOperation;
if (str == "EQUALVERIFY")
return ScriptError.EqualVerify;
if (str == "DISABLED_OPCODE")
return ScriptError.DisabledOpCode;
if (str == "UNKNOWN_ERROR")
return ScriptError.UnknownError;
if (str == "DISCOURAGE_UPGRADABLE_NOPS")
return ScriptError.DiscourageUpgradableNops;
if (str == "PUSH_SIZE")
return ScriptError.PushSize;
if (str == "OP_COUNT")
return ScriptError.OpCount;
if (str == "STACK_SIZE")
return ScriptError.StackSize;
if (str == "SCRIPT_SIZE")
return ScriptError.ScriptSize;
if (str == "PUBKEY_COUNT")
return ScriptError.PubkeyCount;
if (str == "SIG_COUNT")
return ScriptError.SigCount;
if (str == "SIG_PUSHONLY")
return ScriptError.SigPushOnly;
if (str == "MINIMALDATA")
return ScriptError.MinimalData;
if (str == "PUBKEYTYPE")
return ScriptError.PubKeyType;
if (str == "SIG_DER")
return ScriptError.SigDer;
if (str == "WITNESS_MALLEATED")
return ScriptError.WitnessMalleated;
if (str == "WITNESS_MALLEATED_P2SH")
return ScriptError.WitnessMalleatedP2SH;
if (str == "WITNESS_PROGRAM_WITNESS_EMPTY")
return ScriptError.WitnessProgramEmpty;
if (str == "WITNESS_PROGRAM_MISMATCH")
return ScriptError.WitnessProgramMissmatch;
if (str == "WITNESS_PROGRAM_WRONG_LENGTH")
return ScriptError.WitnessProgramWrongLength;
if (str == "WITNESS_UNEXPECTED")
return ScriptError.WitnessUnexpected;
if (str == "SIG_HIGH_S")
return ScriptError.SigHighS;
if (str == "SIG_HASHTYPE")
return ScriptError.SigHashType;
if (str == "SIG_NULLDUMMY")
return ScriptError.SigNullDummy;
if (str == "CLEANSTACK")
return ScriptError.CleanStack;
if (str == "DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM")
return ScriptError.DiscourageUpgradableWitnessProgram;
if (str == "NULLFAIL")
return ScriptError.NullFail;
if (str == "NEGATIVE_LOCKTIME")
return ScriptError.NegativeLockTime;
if (str == "UNSATISFIED_LOCKTIME")
return ScriptError.UnsatisfiedLockTime;
if (str == "MINIMALIF")
return ScriptError.MinimalIf;
if (str == "WITNESS_PUBKEYTYPE")
return ScriptError.WitnessPubkeyType;
throw new NotSupportedException(str);
}
private ScriptVerify ParseFlag(string flag)
{
ScriptVerify result = ScriptVerify.None;
foreach (var p in flag.Split(',', '|').Select(p => p.Trim().ToUpperInvariant()))
{
if (p == "P2SH")
result |= ScriptVerify.P2SH;
else if (p == "STRICTENC")
result |= ScriptVerify.StrictEnc;
else if (p == "MINIMALDATA")
{
result |= ScriptVerify.MinimalData;
}
else if (p == "DERSIG")
{
result |= ScriptVerify.DerSig;
}
else if (p == "SIGPUSHONLY")
{
result |= ScriptVerify.SigPushOnly;
}
else if (p == "NULLDUMMY")
{
result |= ScriptVerify.NullDummy;
}
else if (p == "LOW_S")
{
result |= ScriptVerify.LowS;
}
else if (p == "")
{
}
else if (p == "DISCOURAGE_UPGRADABLE_NOPS")
{
result |= ScriptVerify.DiscourageUpgradableNops;
}
else if (p == "CLEANSTACK")
{
result |= ScriptVerify.CleanStack;
}
else if (p == "WITNESS")
{
result |= ScriptVerify.Witness;
}
else if (p == "DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM")
{
result |= ScriptVerify.DiscourageUpgradableWitnessProgram;
}
else if (p == "CHECKSEQUENCEVERIFY")
{
result |= ScriptVerify.CheckSequenceVerify;
}
else if (p == "NULLFAIL")
{
result |= ScriptVerify.NullFail;
}
else if (p == "MINIMALIF")
{
result |= ScriptVerify.MinimalIf;
}
else if (p == "WITNESS_PUBKEYTYPE")
{
result |= ScriptVerify.WitnessPubkeyType;
}
else if (p == "TAPROOT")
{
result |= ScriptVerify.Taproot;
}
else if (p == "CHECKLOCKTIMEVERIFY")
{
result |= ScriptVerify.CheckLockTimeVerify;
}
else
throw new NotSupportedException(p);
}
return result;
}
[Fact]
[Trait("Core", "Core")]
public void script_standard_push()
{
for (int i = -1; i < 1000; i++)
{
Script script = new Script(Op.GetPushOp(i).ToBytes());
Assert.True(script.IsPushOnly, "Number " + i + " is not pure push.");
Assert.True(script.HasCanonicalPushes, "Number " + i + " push is not canonical.");
}
for (int i = 0; i < 1000; i++)
{
var data = Enumerable.Range(0, i).Select(_ => (byte)0x49).ToArray();
Script script = new Script(Op.GetPushOp(data).ToBytes());
Assert.True(script.IsPushOnly, "Length " + i + " is not pure push.");
Assert.True(script.HasCanonicalPushes, "Length " + i + " push is not canonical.");
}
}
Script sign_multisig(Script scriptPubKey, Key[] keys, Transaction transaction)
{
uint256 hash = transaction.GetSignatureHash(scriptPubKey, 0, SigHash.All);
List<Op> ops = new List<Op>();
//CScript result;
//
// NOTE: CHECKMULTISIG has an unfortunate bug; it requires
// one extra item on the stack, before the signatures.
// Putting OP_0 on the stack is the workaround;
// fixing the bug would mean splitting the block chain (old
// clients would not accept new CHECKMULTISIG transactions,
// and vice-versa)
//
ops.Add(OpcodeType.OP_0);
foreach (Key key in keys)
{
var vchSig = key.Sign(hash).ToDER().ToList();
vchSig.Add((byte)SigHash.All);
ops.Add(Op.GetPushOp(vchSig.ToArray()));
}
return new Script(ops.ToArray());
}
Script sign_multisig(Script scriptPubKey, Key key, Transaction transaction)
{
return sign_multisig(scriptPubKey, new Key[] { key }, transaction);
}
ScriptVerify flags = ScriptVerify.P2SH | ScriptVerify.StrictEnc;
[Fact]
[Trait("Core", "Core")]
public void script_CHECKMULTISIG12()
{
EnsureHasLibConsensus();
Key key1 = new Key(true);
Key key2 = new Key(false);
Key key3 = new Key(true);
Script scriptPubKey12 = new Script(
OpcodeType.OP_1,
Op.GetPushOp(key1.PubKey.ToBytes()),
Op.GetPushOp(key2.PubKey.ToBytes()),
OpcodeType.OP_2,
OpcodeType.OP_CHECKMULTISIG
);
Transaction txFrom12 = Network.CreateTransaction();
txFrom12.Inputs.Add();
txFrom12.Outputs.Add(new TxOut());
txFrom12.Outputs[0].ScriptPubKey = scriptPubKey12;
Transaction txTo12 = Network.CreateTransaction();
txTo12.Inputs.Add(new TxIn());
txTo12.Outputs.Add(new TxOut());
txTo12.Inputs[0].PrevOut.N = 0;
txTo12.Inputs[0].PrevOut.Hash = txFrom12.GetHash();
txTo12.Outputs[0].Value = 1UL;
txTo12.Inputs[0].ScriptSig = sign_multisig(scriptPubKey12, key1, txTo12);
AssertValidScript(txFrom12.Outputs[0], txTo12, 0, flags);
txTo12.Outputs[0].Value = 2UL;
AssertInvalidScript(txFrom12.Outputs[0], txTo12, 0, flags);
txTo12.Inputs[0].ScriptSig = sign_multisig(scriptPubKey12, key2, txTo12);
AssertValidScript(txFrom12.Outputs[0], txTo12, 0, flags);
txTo12.Inputs[0].ScriptSig = sign_multisig(scriptPubKey12, key3, txTo12);
AssertInvalidScript(txFrom12.Outputs[0], txTo12, 0, flags);
}
[Fact]
[Trait("Core", "Core")]
public void script_CHECKMULTISIG23()
{
EnsureHasLibConsensus();
Key key1 = new Key(true);
Key key2 = new Key(false);
Key key3 = new Key(true);
Key key4 = new Key(false);
Script scriptPubKey23 = new Script(
OpcodeType.OP_2,
Op.GetPushOp(key1.PubKey.ToBytes()),
Op.GetPushOp(key2.PubKey.ToBytes()),
Op.GetPushOp(key3.PubKey.ToBytes()),
OpcodeType.OP_3,
OpcodeType.OP_CHECKMULTISIG
);
var txFrom23 = Network.CreateTransaction();
txFrom23.Inputs.Add();
txFrom23.Outputs.Add(new TxOut());
txFrom23.Outputs[0].ScriptPubKey = scriptPubKey23;
var txTo23 = Network.CreateTransaction();
txTo23.Inputs.Add(new TxIn());
txTo23.Outputs.Add(new TxOut());
txTo23.Inputs[0].PrevOut.N = 0;
txTo23.Inputs[0].PrevOut.Hash = txFrom23.GetHash();
txTo23.Outputs[0].Value = 1UL;
var keys = new Key[] { key1, key2 };
txTo23.Inputs[0].ScriptSig = sign_multisig(scriptPubKey23, keys, txTo23);
AssertValidScript(txFrom23.Outputs[0], txTo23, 0, flags);
keys = new Key[] { key1, key3 };
txTo23.Inputs[0].ScriptSig = sign_multisig(scriptPubKey23, keys, txTo23);
AssertValidScript(txFrom23.Outputs[0], txTo23, 0, flags);
keys = new Key[] { key2, key3 };
txTo23.Inputs[0].ScriptSig = sign_multisig(scriptPubKey23, keys, txTo23);
AssertValidScript(txFrom23.Outputs[0], txTo23, 0, flags);
keys = new Key[] { key2, key2 }; // Can't re-use sig
txTo23.Inputs[0].ScriptSig = sign_multisig(scriptPubKey23, keys, txTo23);
AssertInvalidScript(txFrom23.Outputs[0], txTo23, 0, flags);
keys = new Key[] { key2, key1 }; // sigs must be in correct order
txTo23.Inputs[0].ScriptSig = sign_multisig(scriptPubKey23, keys, txTo23);
AssertInvalidScript(txFrom23.Outputs[0], txTo23, 0, flags);
keys = new Key[] { key3, key2 }; // sigs must be in correct order
txTo23.Inputs[0].ScriptSig = sign_multisig(scriptPubKey23, keys, txTo23);
AssertInvalidScript(txFrom23.Outputs[0], txTo23, 0, flags);
keys = new Key[] { key4, key2 };// sigs must match pubkeys
txTo23.Inputs[0].ScriptSig = sign_multisig(scriptPubKey23, keys, txTo23);
AssertInvalidScript(txFrom23.Outputs[0], txTo23, 0, flags);
keys = new Key[] { key1, key4 };// sigs must match pubkeys
txTo23.Inputs[0].ScriptSig = sign_multisig(scriptPubKey23, keys, txTo23);
AssertInvalidScript(txFrom23.Outputs[0], txTo23, 0, flags);
keys = new Key[0]; // Must have signatures
txTo23.Inputs[0].ScriptSig = sign_multisig(scriptPubKey23, keys, txTo23);
AssertInvalidScript(txFrom23.Outputs[0], txTo23, 0, flags);
}
private void AssertInvalidScript(TxOut txOut, Transaction tx, int n, ScriptVerify verify)
{
Assert.False(tx.Inputs.FindIndexedInput(n).VerifyScript(txOut, verify, out _));
#if !NOCONSENSUSLIB
Assert.False(Script.VerifyScriptConsensus(txOut.ScriptPubKey, tx, (uint)n, flags));
#endif
}
private void AssertValidScript(TxOut txOut, Transaction tx, int n, ScriptVerify verify)
{
Assert.True(tx.Inputs.FindIndexedInput(n).VerifyScript(txOut, verify, out _));
#if !NOCONSENSUSLIB
Assert.True(Script.VerifyScriptConsensus(txOut.ScriptPubKey, tx, (uint)n, flags & ScriptVerify.Consensus));
#endif
}
[Fact]
[Trait("Core", "Core")]
public void script_single_hashtype()
{
var tx = Transaction.Parse("010000000390d31c6107013d754529d8818eff285fe40a3e7635f6930fec5d12eb02107a43010000006b483045022100f40815ae3c81a0dd851cc8d376d6fd226c88416671346a9033468cca2cdcc6c202204f764623903e6c4bed1b734b75d82c40f1725e4471a55ad4f51218f86130ac038321033d710ab45bb54ac99618ad23b3c1da661631aa25f23bfe9d22b41876f1d46e4effffffff3ff04a68e22bdd52e7c8cb848156d2d158bd5515b3c50adabc87d0ca2cd3482d010000006a4730440220598d263c107004008e9e26baa1e770be30fd31ee55ded1898f7c00da05a75977022045536bead322ca246779698b9c3df3003377090f41afeca7fb2ce9e328ec4af2832102b738b531def73020bd637f32935924cc88549c8206976226d968edd3a42fc2d7ffffffff46a8dc8970eb96622f27a516adcf40e0fcec5731e7556e174f2a271aef6861c7010000006b483045022100c5b90a777a9fdc90c208dbef7290d1fc1be651f47151ee4ccff646872a454cf90220640cfbc4550446968fbbe9d12528f3adf7d87b31541569c59e790db8a220482583210391332546e22bbe8fe3af54addfad6f8b83d05fa4f5e047593d4c07ae938795beffffffff028036be26000000001976a914ddfb29efad43a667465ac59ff14dc6442a1adfca88ac3d5cba01000000001976a914b64dde7a505a13ca986c40e86e984a8dc81368b688ac00000000", Network.Main);
var scriptPubKey = new Script("OP_DUP OP_HASH160 34fea2c5a75414fd945273ae2d029ce1f28dafcf OP_EQUALVERIFY OP_CHECKSIG");
var txout = tx.Outputs.CreateNewTxOut(Money.Zero, scriptPubKey);
Assert.True(tx.Inputs.AsIndexedInputs().ToArray()[2].VerifyScript(txout, out ScriptError error));
}
[Fact]
[Trait("Core", "Core")]
public void script_combineSigs()
{
Key[] keys = new[] { new Key(), new Key(), new Key() };
var txFrom = CreateCreditingTransaction(keys[0].PubKey.Hash.ScriptPubKey);
var txTo = CreateSpendingTransaction(null, new Script(), txFrom);
Script scriptPubKey = txFrom.Outputs[0].ScriptPubKey;
Script scriptSig = txTo.Inputs[0].ScriptSig;
Script empty = new Script();
Script combined = Script.CombineSignatures(scriptPubKey, txTo, 0, empty, empty);
Assert.True(combined.ToBytes().Length == 0);
// Single signature case:
SignSignature(keys, txFrom, txTo, 0); // changes scriptSig
scriptSig = txTo.Inputs[0].ScriptSig;
combined = Script.CombineSignatures(scriptPubKey, txTo, 0, scriptSig, empty);
Assert.True(combined == scriptSig);
combined = Script.CombineSignatures(scriptPubKey, txTo, 0, empty, scriptSig);
Assert.True(combined == scriptSig);
Script scriptSigCopy = scriptSig.Clone();
// Signing again will give a different, valid signature:
SignSignature(keys, txFrom, txTo, 0);
scriptSig = txTo.Inputs[0].ScriptSig;
combined = Script.CombineSignatures(scriptPubKey, txTo, 0, scriptSigCopy, scriptSig);
Assert.True(combined == scriptSigCopy || combined == scriptSig);
// P2SH, single-signature case:
Script pkSingle = PayToPubkeyTemplate.Instance.GenerateScriptPubKey(keys[0].PubKey);
scriptPubKey = pkSingle.Hash.ScriptPubKey;
txFrom.Outputs[0].ScriptPubKey = scriptPubKey;
txTo.Inputs[0].PrevOut = new OutPoint(txFrom, 0);
SignSignature(keys, txFrom, txTo, 0, pkSingle);
scriptSig = txTo.Inputs[0].ScriptSig;
combined = Script.CombineSignatures(scriptPubKey, txTo, 0, scriptSig, empty);
Assert.True(combined == scriptSig);
combined = Script.CombineSignatures(scriptPubKey, txTo, 0, empty, scriptSig);
scriptSig = txTo.Inputs[0].ScriptSig;
Assert.True(combined == scriptSig);
scriptSigCopy = scriptSig.Clone();
SignSignature(keys, txFrom, txTo, 0);
scriptSig = txTo.Inputs[0].ScriptSig;
combined = Script.CombineSignatures(scriptPubKey, txTo, 0, scriptSigCopy, scriptSig);
Assert.True(combined == scriptSigCopy || combined == scriptSig);
// dummy scriptSigCopy with placeholder, should always choose non-placeholder:
scriptSigCopy = new Script(OpcodeType.OP_0, Op.GetPushOp(pkSingle.ToBytes()));
combined = Script.CombineSignatures(scriptPubKey, txTo, 0, scriptSigCopy, scriptSig);
Assert.True(combined == scriptSig);
combined = Script.CombineSignatures(scriptPubKey, txTo, 0, scriptSig, scriptSigCopy);
Assert.True(combined == scriptSig);
// Hardest case: Multisig 2-of-3
scriptPubKey = PayToMultiSigTemplate.Instance.GenerateScriptPubKey(2, keys.Select(k => k.PubKey).ToArray());
txFrom.Outputs[0].ScriptPubKey = scriptPubKey;
txTo.Inputs[0].PrevOut = new OutPoint(txFrom, 0);
SignSignature(keys, txFrom, txTo, 0);
scriptSig = txTo.Inputs[0].ScriptSig;
combined = Script.CombineSignatures(scriptPubKey, txTo, 0, scriptSig, empty);
Assert.True(combined == scriptSig);
combined = Script.CombineSignatures(scriptPubKey, txTo, 0, empty, scriptSig);
Assert.True(combined == scriptSig);
// A couple of partially-signed versions:
uint256 hash1 = txTo.GetSignatureHash(scriptPubKey, 0, SigHash.All);
var sig1 = new TransactionSignature(keys[0].Sign(hash1), SigHash.All);
uint256 hash2 = txTo.GetSignatureHash(scriptPubKey, 0, SigHash.None);
var sig2 = new TransactionSignature(keys[1].Sign(hash2), SigHash.None);
uint256 hash3 = txTo.GetSignatureHash(scriptPubKey, 0, SigHash.Single);
var sig3 = new TransactionSignature(keys[2].Sign(hash3), SigHash.Single);
// Not fussy about order (or even existence) of placeholders or signatures:
Script partial1a = new Script() + OpcodeType.OP_0 + Op.GetPushOp(sig1.ToBytes()) + OpcodeType.OP_0;
Script partial1b = new Script() + OpcodeType.OP_0 + OpcodeType.OP_0 + Op.GetPushOp(sig1.ToBytes());
Script partial2a = new Script() + OpcodeType.OP_0 + Op.GetPushOp(sig2.ToBytes());
Script partial2b = new Script() + Op.GetPushOp(sig2.ToBytes()) + OpcodeType.OP_0;
Script partial3a = new Script() + Op.GetPushOp(sig3.ToBytes());
Script partial3b = new Script() + OpcodeType.OP_0 + OpcodeType.OP_0 + Op.GetPushOp(sig3.ToBytes());
Script partial3c = new Script() + OpcodeType.OP_0 + Op.GetPushOp(sig3.ToBytes()) + OpcodeType.OP_0;
Script complete12 = new Script() + OpcodeType.OP_0 + Op.GetPushOp(sig1.ToBytes()) + Op.GetPushOp(sig2.ToBytes());
Script complete13 = new Script() + OpcodeType.OP_0 + Op.GetPushOp(sig1.ToBytes()) + Op.GetPushOp(sig3.ToBytes());
Script complete23 = new Script() + OpcodeType.OP_0 + Op.GetPushOp(sig2.ToBytes()) + Op.GetPushOp(sig3.ToBytes());
combined = Script.CombineSignatures(scriptPubKey, txTo, 0, partial1a, partial1b);
Assert.True(combined == partial1a);
combined = Script.CombineSignatures(scriptPubKey, txTo, 0, partial1a, partial2a);
Assert.True(combined == complete12);
combined = Script.CombineSignatures(scriptPubKey, txTo, 0, partial2a, partial1a);
Assert.True(combined == complete12);
combined = Script.CombineSignatures(scriptPubKey, txTo, 0, partial1b, partial2b);
Assert.True(combined == complete12);
combined = Script.CombineSignatures(scriptPubKey, txTo, 0, partial3b, partial1b);
Assert.True(combined == complete13);
combined = Script.CombineSignatures(scriptPubKey, txTo, 0, partial2a, partial3a);
Assert.True(combined == complete23);
combined = Script.CombineSignatures(scriptPubKey, txTo, 0, partial3b, partial2b);
Assert.True(combined == complete23);
combined = Script.CombineSignatures(scriptPubKey, txTo, 0, partial3b, partial3a);
Assert.True(combined == partial3c);
}
private void SignSignature(Key[] keys, Transaction txFrom, Transaction txTo, int n, params Script[] knownRedeems)
{
Network.Main.CreateTransactionBuilder()
.AddKeys(keys)
.AddKnownRedeems(knownRedeems)
.AddCoins(txFrom)
.SignTransactionInPlace(txTo);
}
[Fact]
[Trait("Core", "Core")]
public void script_PushData()
{
// Check that PUSHDATA1, PUSHDATA2, and PUSHDATA4 create the same value on
// the stack as the 1-75 opcodes do.
var direct = new Script(new byte[] { 1, 0x5a });
var pushdata1 = new Script(new byte[] { (byte)OpcodeType.OP_PUSHDATA1, 1, 0x5a });
var pushdata2 = new Script(new byte[] { (byte)OpcodeType.OP_PUSHDATA2, 1, 0, 0x5a });
var pushdata4 = new Script(new byte[] { (byte)OpcodeType.OP_PUSHDATA4, 1, 0, 0, 0, 0x5a });
var context = new ScriptEvaluationContext()
{
ScriptVerify = ScriptVerify.P2SH
};
var directStack = context.Clone();
Assert.True(directStack.EvalScript(direct, new TransactionChecker(Network.CreateTransaction(), 0), HashVersion.Original));