tapyrus 0.5.0

General purpose library for using and interoperating with Tapyrus.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
// Rust Bitcoin Library
// Written in 2014 by
//     Andrew Poelstra <apoelstra@wpsoftware.net>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication
// along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
//

//! Script
//!
//! Scripts define Bitcoin's digital signature scheme: a signature is formed
//! from a script (the second half of which is defined by a coin to be spent,
//! and the first half provided by the spending transaction), and is valid
//! iff the script leaves `TRUE` on the stack after being evaluated.
//! Bitcoin's script is a stack-based assembly language similar in spirit to
//! Forth.
//!
//! This module provides the structures and functions needed to support scripts.
//!

use std::default::Default;
use std::{error, fmt, io};
use std::str::FromStr;

#[cfg(feature = "serde")] use serde;

use crate::hash_types::{ScriptHash, WScriptHash};
use crate::blockdata::opcodes;
use crate::blockdata::transaction::OutPoint;
use crate::consensus::{deserialize, encode, Decodable, Encodable};
use crate::consensus::encode::serialize_hex;
use crate::hashes::hex::FromHex;
use crate::hashes::{sha256, Hash};

#[cfg(feature="bitcoinconsensus")] use bitcoinconsensus;
#[cfg(feature="bitcoinconsensus")] use std::convert;

use crate::util::key::PublicKey;

#[derive(Clone, Default, PartialOrd, Ord, PartialEq, Eq, Hash)]
/// A Bitcoin script
pub struct Script(Box<[u8]>);

impl fmt::Debug for Script {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("Script(")?;
        self.fmt_asm(f)?;
        f.write_str(")")
    }
}

impl fmt::Display for Script {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(self, f)
    }
}

impl fmt::LowerHex for Script {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for &ch in self.0.iter() {
            write!(f, "{:02x}", ch)?;
        }
        Ok(())
    }
}

impl fmt::UpperHex for Script {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for &ch in self.0.iter() {
            write!(f, "{:02X}", ch)?;
        }
        Ok(())
    }
}

#[derive(PartialEq, Eq, Debug, Clone)]
/// An object which can be used to construct a script piece by piece
pub struct Builder(Vec<u8>, Option<opcodes::All>);
display_from_debug!(Builder);

/// Ways that a script might fail. Not everything is split up as
/// much as it could be; patches welcome if more detailed errors
/// would help you.
#[derive(PartialEq, Eq, Debug, Clone)]
pub enum Error {
    /// Something did a non-minimal push; for more information see
    /// `https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki#Push_operators`
    NonMinimalPush,
    /// Some opcode expected a parameter, but it was missing or truncated
    EarlyEndOfScript,
    /// Tried to read an array off the stack as a number when it was more than 4 bytes
    NumericOverflow,
    #[cfg(feature="bitcoinconsensus")]
    /// Error validating the script with bitcoinconsensus library
    BitcoinConsensus(bitcoinconsensus::Error),
    #[cfg(feature="bitcoinconsensus")]
    /// Can not find the spent output
    UnknownSpentOutput(OutPoint),
    #[cfg(feature="bitcoinconsensus")]
    /// Can not serialize the spending transaction
    SerializationError
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let str = match *self {
            Error::NonMinimalPush => "non-minimal datapush",
            Error::EarlyEndOfScript => "unexpected end of script",
            Error::NumericOverflow => "numeric overflow (number on stack larger than 4 bytes)",
            #[cfg(feature="bitcoinconsensus")]
            Error::BitcoinConsensus(ref _n) => "bitcoinconsensus verification failed",
            #[cfg(feature="bitcoinconsensus")]
            Error::UnknownSpentOutput(ref _point) => "unknown spent output Transaction::verify()",
            #[cfg(feature="bitcoinconsensus")]
            Error::SerializationError => "can not serialize the spending transaction in Transaction::verify()",
        };
        f.write_str(str)
    }
}

#[allow(deprecated)]
impl error::Error for Error {
    fn description(&self) -> &str {
        "description() is deprecated; use Display"
    }
}

#[cfg(feature="bitcoinconsensus")]
#[doc(hidden)]
impl convert::From<bitcoinconsensus::Error> for Error {
    fn from(err: bitcoinconsensus::Error) -> Error {
        match err {
            _ => Error::BitcoinConsensus(err)
        }
    }
}

#[derive(PartialEq, Eq, Debug, Clone)]
/// Error associated with multisig handling
pub enum MultisigError {
    /// script is not multisig
    IsNotMultisig,
    /// invalid script
    InvalidScript,
}

impl fmt::Display for MultisigError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let str = match *self {
            MultisigError::IsNotMultisig => "script is not multisig",
            MultisigError::InvalidScript => "invalid script",
        };
        f.write_str(str)
    }
}

/// Helper to encode an integer in script format
fn build_scriptint(n: i64) -> Vec<u8> {
    if n == 0 { return vec![] }

    let neg = n < 0;

    let mut abs = if neg { -n } else { n } as usize;
    let mut v = vec![];
    while abs > 0xFF {
        v.push((abs & 0xFF) as u8);
        abs >>= 8;
    }
    // If the number's value causes the sign bit to be set, we need an extra
    // byte to get the correct value and correct sign bit
    if abs & 0x80 != 0 {
        v.push(abs as u8);
        v.push(if neg { 0x80u8 } else { 0u8 });
    }
    // Otherwise we just set the sign bit ourselves
    else {
        abs |= if neg { 0x80 } else { 0 };
        v.push(abs as u8);
    }
    v
}

/// Helper to decode an integer in script format
/// Notice that this fails on overflow: the result is the same as in
/// bitcoind, that only 4-byte signed-magnitude values may be read as
/// numbers. They can be added or subtracted (and a long time ago,
/// multiplied and divided), and this may result in numbers which
/// can't be written out in 4 bytes or less. This is ok! The number
/// just can't be read as a number again.
/// This is a bit crazy and subtle, but it makes sense: you can load
/// 32-bit numbers and do anything with them, which back when mult/div
/// was allowed, could result in up to a 64-bit number. We don't want
/// overflow since that's surprising --- and we don't want numbers that
/// don't fit in 64 bits (for efficiency on modern processors) so we
/// simply say, anything in excess of 32 bits is no longer a number.
/// This is basically a ranged type implementation.
pub fn read_scriptint(v: &[u8]) -> Result<i64, Error> {
    let len = v.len();
    if len == 0 { return Ok(0); }
    if len > 4 { return Err(Error::NumericOverflow); }

    let (mut ret, sh) = v.iter()
                         .fold((0, 0), |(acc, sh), n| (acc + ((*n as i64) << sh), sh + 8));
    if v[len - 1] & 0x80 != 0 {
        ret &= (1 << (sh - 1)) - 1;
        ret = -ret;
    }
    Ok(ret)
}

/// This is like "`read_scriptint` then map 0 to false and everything
/// else as true", except that the overflow rules don't apply.
#[inline]
pub fn read_scriptbool(v: &[u8]) -> bool {
    !(v.is_empty() ||
        ((v[v.len() - 1] == 0 || v[v.len() - 1] == 0x80) &&
         v.iter().rev().skip(1).all(|&w| w == 0)))
}

/// Read a script-encoded unsigned integer
pub fn read_uint(data: &[u8], size: usize) -> Result<usize, Error> {
    if data.len() < size {
        Err(Error::EarlyEndOfScript)
    } else {
        let mut ret = 0;
        for (i, item) in data.iter().take(size).enumerate() {
            ret += (*item as usize) << (i * 8);
        }
        Ok(ret)
    }
}

/// Error occured with colored coin
#[derive(Debug)]
pub enum ColoredCoinError {
    /// original script is not based p2pkh and p2sh
    UnsuppotedScriptType,
}


/// The types of scripts
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ScriptType {
    /// pay-to-pubkey
    P2pk,
    /// pay-to-pubkey-hash
    P2pkh,
    /// pay-to-multisig
    P2ms,
    /// pay-to-script-hash
    P2sh,
    /// colored pay-to-pubkey-hash
    Cp2pkh,
    /// colored pay-to-script-hash
    Cp2sh,
    /// op_return script
    Nulldata,
    /// non-standard script
    NonStandard,
}

impl fmt::Display for ScriptType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(match *self {
            ScriptType::P2pk => "pubkey",
            ScriptType::P2pkh => "pubkeyhash",
            ScriptType::P2ms => "multisig",
            ScriptType::P2sh => "scripthash",
            ScriptType::Cp2pkh => "coloredpubkeyhash",
            ScriptType::Cp2sh => "coloredscripthash",
            ScriptType::Nulldata => "nulldata",
            ScriptType::NonStandard => "nonstandard"
        })
    }
}

impl FromStr for ScriptType {
    type Err = ();
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "pubkey" => Ok(ScriptType::P2pk),
            "pubkeyhash" => Ok(ScriptType::P2pkh),
            "multisig" => Ok(ScriptType::P2ms),
            "scripthash" => Ok(ScriptType::P2sh),
            "coloredpubkeyhash" => Ok(ScriptType::Cp2pkh),
            "coloredscripthash" => Ok(ScriptType::Cp2sh),
            "nulldata" => Ok(ScriptType::Nulldata),
            "nonstandard" => Ok(ScriptType::NonStandard),
            _ => Err(()),
        }
    }
}

impl Script {
    /// Creates a new empty script
    pub fn new() -> Script { Script(vec![].into_boxed_slice()) }

    /// The length in bytes of the script
    pub fn len(&self) -> usize { self.0.len() }

    /// Whether the script is the empty script
    pub fn is_empty(&self) -> bool { self.0.is_empty() }

    /// Returns the script data
    pub fn as_bytes(&self) -> &[u8] { &self.0 }

    /// Returns a copy of the script data
    pub fn to_bytes(&self) -> Vec<u8> { self.0.clone().into_vec() }

    /// Convert the script into a byte vector
    pub fn into_bytes(self) -> Vec<u8> { self.0.into_vec() }

    /// Compute the P2SH output corresponding to this redeem script
    pub fn to_p2sh(&self) -> Script {
        Builder::new().push_opcode(opcodes::all::OP_HASH160)
                      .push_slice(&ScriptHash::hash(&self.0)[..])
                      .push_opcode(opcodes::all::OP_EQUAL)
                      .into_script()
    }

    /// Compute the P2WSH output corresponding to this witnessScript (aka the "witness redeem
    /// script")
    pub fn to_v0_p2wsh(&self) -> Script {
        Builder::new().push_int(0)
                      .push_slice(&WScriptHash::hash(&self.0)[..])
                      .into_script()
    }

    /// Checks whether a script pubkey is a p2sh output
    #[inline]
    pub fn is_p2sh(&self) -> bool {
        self.0.len() == 23 &&
        self.0[0] == opcodes::all::OP_HASH160.into_u8() &&
        self.0[1] == opcodes::all::OP_PUSHBYTES_20.into_u8() &&
        self.0[22] == opcodes::all::OP_EQUAL.into_u8()
    }

    /// Checks whether a script pubkey is a p2pkh output
    #[inline]
    pub fn is_p2pkh(&self) -> bool {
        self.0.len() == 25 &&
        self.0[0] == opcodes::all::OP_DUP.into_u8() &&
        self.0[1] == opcodes::all::OP_HASH160.into_u8() &&
        self.0[2] == opcodes::all::OP_PUSHBYTES_20.into_u8() &&
        self.0[23] == opcodes::all::OP_EQUALVERIFY.into_u8() &&
        self.0[24] == opcodes::all::OP_CHECKSIG.into_u8()
    }

    /// Checks whether a script pubkey is a p2pk output
    #[inline]
    pub fn is_p2pk(&self) -> bool {
        (self.0.len() == 67 &&
            self.0[0] == opcodes::all::OP_PUSHBYTES_65.into_u8() &&
            self.0[66] == opcodes::all::OP_CHECKSIG.into_u8())
     || (self.0.len() == 35 &&
            self.0[0] == opcodes::all::OP_PUSHBYTES_33.into_u8() &&
            self.0[34] == opcodes::all::OP_CHECKSIG.into_u8())
    }

    /// Checks whether a script pubkey is a Segregated Witness (segwit) program.
    #[inline]
    pub fn is_witness_program(&self) -> bool {
        // A scriptPubKey (or redeemScript as defined in BIP16/P2SH) that consists of a 1-byte
        // push opcode (for 0 to 16) followed by a data push between 2 and 40 bytes gets a new
        // special meaning. The value of the first push is called the "version byte". The following
        // byte vector pushed is called the "witness program".
        let min_vernum: u8 = opcodes::all::OP_PUSHNUM_1.into_u8();
        let max_vernum: u8 = opcodes::all::OP_PUSHNUM_16.into_u8();
        self.0.len() >= 4
            && self.0.len() <= 42
            // Version 0 or PUSHNUM_1-PUSHNUM_16
            && (self.0[0] == 0 || self.0[0] >= min_vernum && self.0[0] <= max_vernum)
            // Second byte push opcode 2-40 bytes
            && self.0[1] >= opcodes::all::OP_PUSHBYTES_2.into_u8()
            && self.0[1] <= opcodes::all::OP_PUSHBYTES_40.into_u8()
            // Check that the rest of the script has the correct size
            && self.0.len() - 2 == self.0[1] as usize
    }

    /// Checks whether a script pubkey is a p2wsh output
    #[inline]
    pub fn is_v0_p2wsh(&self) -> bool {
        self.0.len() == 34 &&
        self.0[0] == opcodes::all::OP_PUSHBYTES_0.into_u8() &&
        self.0[1] == opcodes::all::OP_PUSHBYTES_32.into_u8()
    }

    /// Checks whether a script pubkey is a p2wpkh output
    #[inline]
    pub fn is_v0_p2wpkh(&self) -> bool {
        self.0.len() == 22 &&
            self.0[0] == opcodes::all::OP_PUSHBYTES_0.into_u8() &&
            self.0[1] == opcodes::all::OP_PUSHBYTES_20.into_u8()
    }

    /// Check if this is an OP_RETURN output
    pub fn is_op_return (&self) -> bool {
        !self.0.is_empty() && (opcodes::All::from(self.0[0]) == opcodes::all::OP_RETURN)
    }

    /// Whether a script can be proven to have no satisfying input
    pub fn is_provably_unspendable(&self) -> bool {
        !self.0.is_empty() && (opcodes::All::from(self.0[0]).classify() == opcodes::Class::ReturnOp ||
                               opcodes::All::from(self.0[0]).classify() == opcodes::Class::IllegalOp)
    }

    /// Check if a script pubkey is a cp2pkh output
    pub fn is_cp2pkh(&self) -> bool {
        self.0.len() == 60 &&
        self.0[0] == opcodes::all::OP_PUSHBYTES_33.into_u8() &&
        TokenTypes::is_valid(&self.0[1]) &&
        self.0[34] == opcodes::all::OP_COLOR.into_u8() &&
        self.0[35] == opcodes::all::OP_DUP.into_u8() &&
        self.0[36] == opcodes::all::OP_HASH160.into_u8() &&
        self.0[37] == opcodes::all::OP_PUSHBYTES_20.into_u8() &&
        self.0[58] == opcodes::all::OP_EQUALVERIFY.into_u8() &&
        self.0[59] == opcodes::all::OP_CHECKSIG.into_u8()
    }

    /// Check if a script pubkey is a cp2sh output
    pub fn is_cp2sh(&self) -> bool {
        self.0.len() == 58 &&
        self.0[0] == opcodes::all::OP_PUSHBYTES_33.into_u8() &&
        TokenTypes::is_valid(&self.0[1]) &&
        self.0[34] == opcodes::all::OP_COLOR.into_u8() &&
        self.0[35] == opcodes::all::OP_HASH160.into_u8() &&
        self.0[36] == opcodes::all::OP_PUSHBYTES_20.into_u8() &&
        self.0[57] == opcodes::all::OP_EQUAL.into_u8()
    }

    /// Check if a script pubkey is a colored coin script
    pub fn is_colored(&self) -> bool {
        self.is_cp2pkh() || self.is_cp2sh()
    }

    /// Check if a script pubkey is multisig script
    pub fn is_multisig(&self) -> bool {
        if self.0.len() < 4 || *self.0.last().unwrap() != opcodes::all::OP_CHECKMULTISIG.into_u8() {
            return false;
        }
        let required_count = match opcodes::All::from(self.0[0]).classify() {
            opcodes::Class::PushNum(i) => i,
            _ => { return false }
        };
        let pubkey_count = match opcodes::All::from(self.0[self.0.len() - 2]).classify() {
            opcodes::Class::PushNum(i) => i,
            _ => { return false }
        };
        required_count <= pubkey_count
    }

    /// Return public keys for multisig script, and the number of signatures required
    pub fn get_multisig_pubkeys(&self) -> Result<(i32, Vec<PublicKey>), MultisigError> {
        if !self.is_multisig() {
            return Err(MultisigError::IsNotMultisig);
        }

        let mut required = None;
        let mut pubkeys = vec![];
        for ins in self.instructions_minimal() {
            if ins.is_err() {
                return Err(MultisigError::InvalidScript);
            }
            match ins.ok().unwrap() {
                Instruction::Op(op) => {
                    if required.is_none() {
                        required = match op.classify() {
                            opcodes::Class::PushNum(i) => Some(i),
                            _ => { return Err(MultisigError::IsNotMultisig) }
                        };
                    }
                }
                Instruction::PushBytes(bytes) => {
                    match PublicKey::from_slice(bytes) {
                        Ok(key) => { pubkeys.push(key) },
                        _ => { return Err(MultisigError::IsNotMultisig) }
                    }
                }
            }
        }
        if let Some(required) = required {
            Ok((required, pubkeys))
        } else {
            Err(MultisigError::InvalidScript)
        }
    }

    /// Create new script with color identifier
    pub fn add_color(&self, color_id: ColorIdentifier) -> Result<Script, ColoredCoinError> {
        if !self.is_p2pkh() && !self.is_p2sh() {
            return Err(ColoredCoinError::UnsuppotedScriptType);
        }
        let mut payload = vec![];
        payload.push(opcodes::all::OP_PUSHBYTES_33.into_u8());
        payload.extend(encode::serialize(&color_id));
        payload.push(opcodes::all::OP_COLOR.into_u8());
        payload.extend(self.to_bytes());
        Ok(Script::from(payload))
    }

    /// Iterate over the script in the form of `Instruction`s, which are an enum covering
    /// opcodes, datapushes and errors. At most one error will be returned and then the
    /// iterator will end. To instead iterate over the script as sequence of bytes, treat
    /// it as a slice using `script[..]` or convert it to a vector using `into_bytes()`.
    ///
    /// To force minimal pushes, use [instructions_minimal].
    pub fn instructions(&self) -> Instructions<'_> {
        Instructions {
            data: &self.0[..],
            enforce_minimal: false,
        }
    }

     /// Iterate over the script in the form of `Instruction`s while enforcing
    /// minimal pushes.
    pub fn instructions_minimal(&self) -> Instructions<'_> {
        Instructions {
            data: &self.0[..],
            enforce_minimal: true,
        }
    }

    #[cfg(feature="bitcoinconsensus")]
    /// verify spend of an input script
    /// # Parameters
    ///  * index - the input index in spending which is spending this transaction
    ///  * amount - the amount this script guards
    ///  * spending - the transaction that attempts to spend the output holding this script
    pub fn verify (&self, index: usize, amount: u64, spending: &[u8]) -> Result<(), Error> {
        Ok(bitcoinconsensus::verify (&self.0[..], amount, spending, index)?)
    }

    /// Write the assembly decoding of the script to the formatter.
    pub fn fmt_asm(&self, f: &mut dyn fmt::Write) -> fmt::Result {
        let mut index = 0;
        while index < self.0.len() {
            let opcode = opcodes::All::from(self.0[index]);
            index += 1;

            let data_len = if let opcodes::Class::PushBytes(n) = opcode.classify() {
                n as usize
            } else {
                match opcode {
                    opcodes::all::OP_PUSHDATA1 => {
                        if self.0.len() < index + 1 {
                            f.write_str("<unexpected end>")?;
                            break;
                        }
                        match read_uint(&self.0[index..], 1) {
                            Ok(n) => { index += 1; n }
                            Err(_) => { f.write_str("<bad length>")?; break; }
                        }
                    }
                    opcodes::all::OP_PUSHDATA2 => {
                        if self.0.len() < index + 2 {
                            f.write_str("<unexpected end>")?;
                            break;
                        }
                        match read_uint(&self.0[index..], 2) {
                            Ok(n) => { index += 2; n }
                            Err(_) => { f.write_str("<bad length>")?; break; }
                        }
                    }
                    opcodes::all::OP_PUSHDATA4 => {
                        if self.0.len() < index + 4 {
                            f.write_str("<unexpected end>")?;
                            break;
                        }
                        match read_uint(&self.0[index..], 4) {
                            Ok(n) => { index += 4; n }
                            Err(_) => { f.write_str("<bad length>")?; break; }
                        }
                    }
                    _ => 0
                }
            };

            if index > 1 { f.write_str(" ")?; }
            // Write the opcode
            if opcode == opcodes::all::OP_PUSHBYTES_0 {
                f.write_str("OP_0")?;
            } else {
                write!(f, "{:?}", opcode)?;
            }
            // Write any pushdata
            if data_len > 0 {
                f.write_str(" ")?;
                if index + data_len <= self.0.len() {
                    for ch in &self.0[index..index + data_len] {
                            write!(f, "{:02x}", ch)?;
                    }
                    index += data_len;
                } else {
                    f.write_str("<push past end>")?;
                    break;
                }
            }
        }
        Ok(())
    }

    /// Get the assembly decoding of the script.
    pub fn asm(&self) -> String {
        let mut buf = String::new();
        self.fmt_asm(&mut buf).unwrap();
        buf
    }

    /// Extract a color_id and a remaining script
    /// Return None if script is not colored coin
    pub fn split_color(&self) -> Option<(ColorIdentifier, Script)> {
        if self.is_colored() {
            let color_id = deserialize(&self[1..34]).expect("unexpect color_id");
            Some((color_id, Script::from(Vec::from(&self[35..]))))
        } else {
            None
        }
    }

    /// Return script type.
    pub fn script_type(&self) -> ScriptType {
        if self.is_p2pk() {
            ScriptType::P2pk
        } else if self.is_p2pkh() {
            ScriptType::P2pkh
        } else if self.is_multisig() {
            ScriptType::P2ms
        } else if self.is_p2sh() {
            ScriptType::P2sh
        } else if self.is_op_return() {
            ScriptType::Nulldata
        } else if self.is_cp2pkh() {
            ScriptType::Cp2pkh
        } else if self.is_cp2sh() {
            ScriptType::Cp2sh
        } else {
            ScriptType::NonStandard
        }
    }
}

/// Creates a new script from an existing vector
impl From<Vec<u8>> for Script {
    fn from(v: Vec<u8>) -> Script { Script(v.into_boxed_slice()) }
}

impl_index_newtype!(Script, u8);

/// A "parsed opcode" which allows iterating over a Script in a more sensible way
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Instruction<'a> {
    /// Push a bunch of data
    PushBytes(&'a [u8]),
    /// Some non-push opcode
    Op(opcodes::All),
}

/// Iterator over a script returning parsed opcodes
pub struct Instructions<'a> {
    data: &'a [u8],
    enforce_minimal: bool,
}

impl<'a> Iterator for Instructions<'a> {
    type Item = Result<Instruction<'a>, Error>;

    fn next(&mut self) -> Option<Result<Instruction<'a>, Error>> {
        if self.data.is_empty() {
            return None;
        }

        match opcodes::All::from(self.data[0]).classify() {
            opcodes::Class::PushBytes(n) => {
                let n = n as usize;
                if self.data.len() < n + 1 {
                    self.data = &[];  // Kill iterator so that it does not return an infinite stream of errors
                    return Some(Err(Error::EarlyEndOfScript));
                }
                if self.enforce_minimal
                    && n == 1 && (self.data[1] == 0x81 || (self.data[1] > 0 && self.data[1] <= 16)) {
                        self.data = &[];
                        return Some(Err(Error::NonMinimalPush));
                    }
                let ret = Some(Ok(Instruction::PushBytes(&self.data[1..n+1])));
                self.data = &self.data[n + 1..];
                ret
            }
            opcodes::Class::Ordinary(opcodes::Ordinary::OP_PUSHDATA1) => {
                if self.data.len() < 2 {
                    self.data = &[];
                    return Some(Err(Error::EarlyEndOfScript));
                }
                let n = match read_uint(&self.data[1..], 1) {
                    Ok(n) => n,
                    Err(e) => {
                        self.data = &[];
                        return Some(Err(e));
                    }
                };
                if self.data.len() < n + 2 {
                    self.data = &[];
                    return Some(Err(Error::EarlyEndOfScript));
                }
                if self.enforce_minimal && n < 76 {
                    self.data = &[];
                    return Some(Err(Error::NonMinimalPush));
                }
                let ret = Some(Ok(Instruction::PushBytes(&self.data[2..n+2])));
                self.data = &self.data[n + 2..];
                ret
            }
            opcodes::Class::Ordinary(opcodes::Ordinary::OP_PUSHDATA2) => {
                if self.data.len() < 3 {
                    self.data = &[];
                    return Some(Err(Error::EarlyEndOfScript));
                }
                let n = match read_uint(&self.data[1..], 2) {
                    Ok(n) => n,
                    Err(e) => {
                        self.data = &[];
                        return Some(Err(e));
                    }
                };
                if self.enforce_minimal && n < 0x100 {
                    self.data = &[];
                    return Some(Err(Error::NonMinimalPush));
                }
                if self.data.len() < n + 3 {
                    self.data = &[];
                    return Some(Err(Error::EarlyEndOfScript));
                }
                let ret = Some(Ok(Instruction::PushBytes(&self.data[3..n + 3])));
                self.data = &self.data[n + 3..];
                ret
            }
            opcodes::Class::Ordinary(opcodes::Ordinary::OP_PUSHDATA4) => {
                if self.data.len() < 5 {
                    self.data = &[];
                    return Some(Err(Error::EarlyEndOfScript));
                }
                let n = match read_uint(&self.data[1..], 4) {
                    Ok(n) => n,
                    Err(e) => {
                        self.data = &[];
                        return Some(Err(e));
                    }
                };
                if self.enforce_minimal && n < 0x10000 {
                    self.data = &[];
                    return Some(Err(Error::NonMinimalPush));
                }
                if self.data.len() < n + 5 {
                    self.data = &[];
                    return Some(Err(Error::EarlyEndOfScript));
                }
                let ret = Some(Ok(Instruction::PushBytes(&self.data[5..n + 5])));
                self.data = &self.data[n + 5..];
                ret
            }
            // Everything else we can push right through
            _ => {
                let ret = Some(Ok(Instruction::Op(opcodes::All::from(self.data[0]))));
                self.data = &self.data[1..];
                ret
            }
        }
    }
}

impl Builder {
    /// Creates a new empty script
    pub fn new() -> Builder {
        Builder(vec![], None)
    }

    /// The length in bytes of the script
    pub fn len(&self) -> usize { self.0.len() }

    /// Whether the script is the empty script
    pub fn is_empty(&self) -> bool { self.0.is_empty() }

    /// Adds instructions to push an integer onto the stack. Integers are
    /// encoded as little-endian signed-magnitude numbers, but there are
    /// dedicated opcodes to push some small integers.
    pub fn push_int(self, data: i64) -> Builder {
        // We can special-case -1, 1-16
        if data == -1 || (1..=16).contains(&data) {
            let opcode = opcodes::All::from(
                (data - 1 + opcodes::OP_TRUE.into_u8() as i64) as u8
            );
            self.push_opcode(opcode)
        }
        // We can also special-case zero
        else if data == 0 {
            self.push_opcode(opcodes::OP_FALSE)
        }
        // Otherwise encode it as data
        else { self.push_scriptint(data) }
    }

    /// Adds instructions to push an integer onto the stack, using the explicit
    /// encoding regardless of the availability of dedicated opcodes.
    pub fn push_scriptint(self, data: i64) -> Builder {
        self.push_slice(&build_scriptint(data))
    }

    /// Adds instructions to push some arbitrary data onto the stack
    pub fn push_slice(mut self, data: &[u8]) -> Builder {
        // Start with a PUSH opcode
        match data.len() as u64 {
            n if n < opcodes::Ordinary::OP_PUSHDATA1 as u64 => { self.0.push(n as u8); },
            n if n < 0x100 => {
                self.0.push(opcodes::Ordinary::OP_PUSHDATA1.into_u8());
                self.0.push(n as u8);
            },
            n if n < 0x10000 => {
                self.0.push(opcodes::Ordinary::OP_PUSHDATA2.into_u8());
                self.0.push((n % 0x100) as u8);
                self.0.push((n / 0x100) as u8);
            },
            n if n < 0x100000000 => {
                self.0.push(opcodes::Ordinary::OP_PUSHDATA4.into_u8());
                self.0.push((n % 0x100) as u8);
                self.0.push(((n / 0x100) % 0x100) as u8);
                self.0.push(((n / 0x10000) % 0x100) as u8);
                self.0.push((n / 0x1000000) as u8);
            }
            _ => panic!("tried to put a 4bn+ sized object into a script!")
        }
        // Then push the raw bytes
        self.0.extend(data.iter().cloned());
        self.1 = None;
        self
    }

    /// Pushes a public key
    pub fn push_key(self, key: &PublicKey) -> Builder {
        if key.compressed {
            self.push_slice(&key.key.serialize()[..])
        } else {
            self.push_slice(&key.key.serialize_uncompressed()[..])
        }
    }

    /// Adds a single opcode to the script
    pub fn push_opcode(mut self, data: opcodes::All) -> Builder {
        self.0.push(data.into_u8());
        self.1 = Some(data);
        self
    }

    /// Adds an `OP_VERIFY` to the script, unless the most-recently-added
    /// opcode has an alternate `VERIFY` form, in which case that opcode
    /// is replaced. e.g. `OP_CHECKSIG` will become `OP_CHECKSIGVERIFY`.
    pub fn push_verify(mut self) -> Builder {
        match self.1 {
            Some(opcodes::all::OP_EQUAL) => {
                self.0.pop();
                self.push_opcode(opcodes::all::OP_EQUALVERIFY)
            },
            Some(opcodes::all::OP_NUMEQUAL) => {
                self.0.pop();
                self.push_opcode(opcodes::all::OP_NUMEQUALVERIFY)
            },
            Some(opcodes::all::OP_CHECKSIG) => {
                self.0.pop();
                self.push_opcode(opcodes::all::OP_CHECKSIGVERIFY)
            },
            Some(opcodes::all::OP_CHECKMULTISIG) => {
                self.0.pop();
                self.push_opcode(opcodes::all::OP_CHECKMULTISIGVERIFY)
            },
            _ => self.push_opcode(opcodes::all::OP_VERIFY),
        }
    }

    /// Converts the `Builder` into an unmodifiable `Script`
    pub fn into_script(self) -> Script {
        Script(self.0.into_boxed_slice())
    }
}

/// Adds an individual opcode to the script
impl Default for Builder {
    fn default() -> Builder { Builder::new() }
}

/// Creates a new script from an existing vector
impl From<Vec<u8>> for Builder {
    fn from(v: Vec<u8>) -> Builder {
        let script = Script(v.into_boxed_slice());
        let last_op = match script.instructions().last() {
            Some(Ok(Instruction::Op(op))) => Some(op),
            _ => None,
        };
        Builder(script.into_bytes(), last_op)
    }
}

impl_index_newtype!(Builder, u8);

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Script {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        use std::fmt::Formatter;

        struct Visitor;
        impl<'de> serde::de::Visitor<'de> for Visitor {
            type Value = Script;

            fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
                formatter.write_str("a script")
            }

            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                let v = Vec::from_hex(v).map_err(E::custom)?;
                Ok(Script::from(v))
            }

            fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                self.visit_str(v)
            }

            fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                self.visit_str(&v)
            }
        }

        deserializer.deserialize_str(Visitor)
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for Script {
    /// User-facing serialization for `Script`.
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&format!("{:x}", self))
    }
}

// Network serialization
impl Encodable for Script {
    #[inline]
    fn consensus_encode<S: io::Write>(
        &self,
        s: S,
    ) -> Result<usize, encode::Error> {
        self.0.consensus_encode(s)
    }
}

impl Decodable for Script {
    #[inline]
    fn consensus_decode<D: io::Read>(d: D) -> Result<Self, encode::Error> {
        Ok(Script(Decodable::consensus_decode(d)?))
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
struct ColorIdentifierPayload(sha256::Hash);

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
/// ColorIdentifier
pub struct ColorIdentifier {
    /// Token type
    pub token_type: TokenTypes,
    payload: ColorIdentifierPayload,
}

impl ColorIdentifier {
    /// initialize ColorIdentifier with type Reissuable
    pub fn reissuable(script_pubkey: Script) -> Self {
        let mut enc = sha256::Hash::engine();
        script_pubkey.consensus_encode(&mut enc).unwrap();
        let hash = sha256::Hash::from_engine(enc);
        ColorIdentifier {
            token_type: TokenTypes::Reissuable,
            payload: ColorIdentifierPayload(hash)
        }
    }

    /// initialize ColorIdentifier with type Non Reissuable
    pub fn non_reissuable(out_point: OutPoint) -> Self {
        let mut enc = sha256::Hash::engine();
        out_point.consensus_encode(&mut enc).unwrap();
        let hash = sha256::Hash::from_engine(enc);
        ColorIdentifier {
            token_type: TokenTypes::NonReissuable,
            payload: ColorIdentifierPayload(hash)
        }
    }

    /// initialize ColorIdentifier with type Nft
    pub fn nft(out_point: OutPoint) -> Self {
        let mut enc = sha256::Hash::engine();
        out_point.consensus_encode(&mut enc).unwrap();
        let hash = sha256::Hash::from_engine(enc);
        ColorIdentifier {
            token_type: TokenTypes::Nft,
            payload: ColorIdentifierPayload(hash)
        }
    }

    /// return true if this is colored coin
    pub fn is_colored(&self) -> bool {
        self.token_type != TokenTypes::None
    }

    /// return true if this is uncolored coin(TPC)
    pub fn is_default(&self) -> bool {
        self.token_type == TokenTypes::None
    }

    /// Initialize ColorIdentifier from slice
    pub fn from_slice(data: &[u8]) -> Result<Self, encode::Error> {
        deserialize(data).map_err(|_| encode::Error::ParseFailed("invalid color identifier"))
    }

    /// Initialize ColorIdentifier from hex string
    pub fn from_hex(hex: &str) -> Result<Self, encode::Error> {
        let bytes = Vec::from_hex(hex).map_err(|_| encode::Error::ParseFailed("invalid color identifier"))?;
        ColorIdentifier::from_slice(&bytes)
    }
}

impl Default for ColorIdentifier {
    fn default() -> Self {
        ColorIdentifier {
            token_type: TokenTypes::None,
            payload: ColorIdentifierPayload(sha256::Hash::default())
        }
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for ColorIdentifier {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        use std::fmt::Formatter;

        struct Visitor;
        impl<'de> serde::de::Visitor<'de> for Visitor {
            type Value = ColorIdentifier;

            fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
                formatter.write_str("a color identifier")
            }

            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                let bytes = Vec::from_hex(v).map_err(E::custom)?;
                let color_identifier: ColorIdentifier = deserialize(&bytes).map_err(E::custom)?;
                Ok(color_identifier)
            }

            fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                self.visit_str(v)
            }

            fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                self.visit_str(&v)
            }
        }

        deserializer.deserialize_str(Visitor)
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for ColorIdentifier {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&format!("{}", self))
    }
}

impl Encodable for ColorIdentifier {
    #[inline]
    fn consensus_encode<S: io::Write>(
        &self,
        mut s: S,
    ) -> Result<usize, encode::Error> {
        let mut len = (self.token_type.clone() as u8).consensus_encode(&mut s)?;
        len += self.payload.0.into_inner().consensus_encode(s)?;
        Ok(len)
    }
}

impl Decodable for ColorIdentifier {
    #[inline]
    fn consensus_decode<D: io::Read>(mut d: D) -> Result<Self, encode::Error> {
        let bytes: [u8; 33] = Decodable::consensus_decode(&mut d)?;
        let token_type = match bytes[0] {
            0x00 => TokenTypes::None,
            0xC1 => TokenTypes::Reissuable,
            0xC2 => TokenTypes::NonReissuable,
            0xC3 => TokenTypes::Nft,
            _ => return Err(encode::Error::ParseFailed("invalid token type."))
        };

        let payload = sha256::Hash::from_slice(&bytes[1..]).map_err(|_| encode::Error::ParseFailed("invalid payload."))?;
        Ok(ColorIdentifier {
            token_type,
            payload: ColorIdentifierPayload(payload)
        })
    }
}

impl std::fmt::Display for ColorIdentifier {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", serialize_hex(self))
    }
}

/// Token types
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum TokenTypes {
    /// TPC
    None = 0x00,
    /// Reissuable
    Reissuable = 0xc1,
    /// Non reissuable
    NonReissuable = 0xc2,
    /// Non fungible token
    Nft = 0xc3,
}

impl TokenTypes {
    /// return true if token type is supported
    pub fn is_valid(token_type: &u8) -> bool {
        [TokenTypes::None,
            TokenTypes::Reissuable,
            TokenTypes::NonReissuable,
            TokenTypes::Nft].iter().any(|e| e.clone() as u8 == *token_type)
    }
}

#[cfg(test)]
mod test {
    use std::str::FromStr;

    use super::*;
    use super::build_scriptint;

    use crate::consensus::encode::{deserialize, serialize};
    use crate::blockdata::opcodes;
    use crate::util::key::PublicKey;
    use crate::hash_types::Txid;
    use crate::hashes::hex::FromHex;

    #[test]
    fn script() {
        let mut comp = vec![];
        let mut script = Builder::new();
        assert_eq!(&script[..], &comp[..]);

        // small ints
        script = script.push_int(1);  comp.push(81u8); assert_eq!(&script[..], &comp[..]);
        script = script.push_int(0);  comp.push(0u8);  assert_eq!(&script[..], &comp[..]);
        script = script.push_int(4);  comp.push(84u8); assert_eq!(&script[..], &comp[..]);
        script = script.push_int(-1); comp.push(79u8); assert_eq!(&script[..], &comp[..]);
        // forced scriptint
        script = script.push_scriptint(4); comp.extend([1u8, 4].iter().cloned()); assert_eq!(&script[..], &comp[..]);
        // big ints
        script = script.push_int(17); comp.extend([1u8, 17].iter().cloned()); assert_eq!(&script[..], &comp[..]);
        script = script.push_int(10000); comp.extend([2u8, 16, 39].iter().cloned()); assert_eq!(&script[..], &comp[..]);
        // notice the sign bit set here, hence the extra zero/128 at the end
        script = script.push_int(10000000); comp.extend([4u8, 128, 150, 152, 0].iter().cloned()); assert_eq!(&script[..], &comp[..]);
        script = script.push_int(-10000000); comp.extend([4u8, 128, 150, 152, 128].iter().cloned()); assert_eq!(&script[..], &comp[..]);

        // data
        script = script.push_slice("NRA4VR".as_bytes()); comp.extend([6u8, 78, 82, 65, 52, 86, 82].iter().cloned()); assert_eq!(&script[..], &comp[..]);

        // keys
        let keystr = "21032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af";
        let key = PublicKey::from_str(&keystr[2..]).unwrap();
        script = script.push_key(&key); comp.extend(Vec::from_hex(keystr).unwrap().iter().cloned()); assert_eq!(&script[..], &comp[..]);
        let keystr = "41042e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af191923a2964c177f5b5923ae500fca49e99492d534aa3759d6b25a8bc971b133";
        let key = PublicKey::from_str(&keystr[2..]).unwrap();
        script = script.push_key(&key); comp.extend(Vec::from_hex(keystr).unwrap().iter().cloned()); assert_eq!(&script[..], &comp[..]);

        // opcodes
        script = script.push_opcode(opcodes::all::OP_CHECKSIG); comp.push(0xACu8); assert_eq!(&script[..], &comp[..]);
        script = script.push_opcode(opcodes::all::OP_CHECKSIG); comp.push(0xACu8); assert_eq!(&script[..], &comp[..]);
    }

    #[test]
    fn script_builder() {
        // from txid 3bb5e6434c11fb93f64574af5d116736510717f2c595eb45b52c28e31622dfff which was in my mempool when I wrote the test
        let script = Builder::new().push_opcode(opcodes::all::OP_DUP)
                                   .push_opcode(opcodes::all::OP_HASH160)
                                   .push_slice(&Vec::from_hex("16e1ae70ff0fa102905d4af297f6912bda6cce19").unwrap())
                                   .push_opcode(opcodes::all::OP_EQUALVERIFY)
                                   .push_opcode(opcodes::all::OP_CHECKSIG)
                                   .into_script();
        assert_eq!(&format!("{:x}", script), "76a91416e1ae70ff0fa102905d4af297f6912bda6cce1988ac");
    }

    #[test]
    fn script_builder_verify() {
        let simple = Builder::new()
            .push_verify()
            .into_script();
        assert_eq!(format!("{:x}", simple), "69");
        let simple2 = Builder::from(vec![])
            .push_verify()
            .into_script();
        assert_eq!(format!("{:x}", simple2), "69");

        let nonverify = Builder::new()
            .push_verify()
            .push_verify()
            .into_script();
        assert_eq!(format!("{:x}", nonverify), "6969");
        let nonverify2 = Builder::from(vec![0x69])
            .push_verify()
            .into_script();
        assert_eq!(format!("{:x}", nonverify2), "6969");

        let equal = Builder::new()
            .push_opcode(opcodes::all::OP_EQUAL)
            .push_verify()
            .into_script();
        assert_eq!(format!("{:x}", equal), "88");
        let equal2 = Builder::from(vec![0x87])
            .push_verify()
            .into_script();
        assert_eq!(format!("{:x}", equal2), "88");

        let numequal = Builder::new()
            .push_opcode(opcodes::all::OP_NUMEQUAL)
            .push_verify()
            .into_script();
        assert_eq!(format!("{:x}", numequal), "9d");
        let numequal2 = Builder::from(vec![0x9c])
            .push_verify()
            .into_script();
        assert_eq!(format!("{:x}", numequal2), "9d");

        let checksig = Builder::new()
            .push_opcode(opcodes::all::OP_CHECKSIG)
            .push_verify()
            .into_script();
        assert_eq!(format!("{:x}", checksig), "ad");
        let checksig2 = Builder::from(vec![0xac])
            .push_verify()
            .into_script();
        assert_eq!(format!("{:x}", checksig2), "ad");

        let checkmultisig = Builder::new()
            .push_opcode(opcodes::all::OP_CHECKMULTISIG)
            .push_verify()
            .into_script();
        assert_eq!(format!("{:x}", checkmultisig), "af");
        let checkmultisig2 = Builder::from(vec![0xae])
            .push_verify()
            .into_script();
        assert_eq!(format!("{:x}", checkmultisig2), "af");

        let trick_slice = Builder::new()
            .push_slice(&[0xae]) // OP_CHECKMULTISIG
            .push_verify()
            .into_script();
        assert_eq!(format!("{:x}", trick_slice), "01ae69");
        let trick_slice2 = Builder::from(vec![0x01, 0xae])
            .push_verify()
            .into_script();
        assert_eq!(format!("{:x}", trick_slice2), "01ae69");
   }

    #[test]
    fn script_serialize() {
        let hex_script = Vec::from_hex("6c493046022100f93bb0e7d8db7bd46e40132d1f8242026e045f03a0efe71bbb8e3f475e970d790221009337cd7f1f929f00cc6ff01f03729b069a7c21b59b1736ddfee5db5946c5da8c0121033b9b137ee87d5a812d6f506efdd37f0affa7ffc310711c06c7f3e097c9447c52").unwrap();
        let script: Result<Script, _> = deserialize(&hex_script);
        assert!(script.is_ok());
        assert_eq!(serialize(&script.unwrap()), hex_script);
    }

    #[test]
    fn scriptint_round_trip() {
        assert_eq!(build_scriptint(-1), vec![0x81]);
        assert_eq!(build_scriptint(255), vec![255, 0]);
        assert_eq!(build_scriptint(256), vec![0, 1]);
        assert_eq!(build_scriptint(257), vec![1, 1]);
        assert_eq!(build_scriptint(511), vec![255, 1]);
        for &i in [10, 100, 255, 256, 1000, 10000, 25000, 200000, 5000000, 1000000000,
                             (1 << 31) - 1, -((1 << 31) - 1)].iter() {
            assert_eq!(Ok(i), read_scriptint(&build_scriptint(i)));
            assert_eq!(Ok(-i), read_scriptint(&build_scriptint(-i)));
        }
        assert!(read_scriptint(&build_scriptint(1 << 31)).is_err());
        assert!(read_scriptint(&build_scriptint(-(1 << 31))).is_err());
    }

    #[test]
    fn provably_unspendable_test() {
        // p2pk
        assert_eq!(hex_script!("410446ef0102d1ec5240f0d061a4246c1bdef63fc3dbab7733052fbbf0ecd8f41fc26bf049ebb4f9527f374280259e7cfa99c48b0e3f39c51347a19a5819651503a5ac").is_provably_unspendable(), false);
        assert_eq!(hex_script!("4104ea1feff861b51fe3f5f8a3b12d0f4712db80e919548a80839fc47c6a21e66d957e9c5d8cd108c7a2d2324bad71f9904ac0ae7336507d785b17a2c115e427a32fac").is_provably_unspendable(), false);
        // p2pkhash
        assert_eq!(hex_script!("76a914ee61d57ab51b9d212335b1dba62794ac20d2bcf988ac").is_provably_unspendable(), false);
        assert_eq!(hex_script!("6aa9149eb21980dc9d413d8eac27314938b9da920ee53e87").is_provably_unspendable(), true);
    }

    #[test]
    fn op_return_test() {
        assert_eq!(hex_script!("6aa9149eb21980dc9d413d8eac27314938b9da920ee53e87").is_op_return(), true);
        assert_eq!(hex_script!("76a914ee61d57ab51b9d212335b1dba62794ac20d2bcf988ac").is_op_return(), false);
        assert_eq!(hex_script!("").is_op_return(), false);
    }

    #[test]
    #[cfg(feature = "serde")]
    fn script_json_serialize() {
        use serde_json;

        let original = hex_script!("827651a0698faaa9a8a7a687");
        let json = serde_json::to_value(&original).unwrap();
        assert_eq!(json, serde_json::Value::String("827651a0698faaa9a8a7a687".to_owned()));
        let des = serde_json::from_value(json).unwrap();
        assert_eq!(original, des);
    }

    #[test]
    #[cfg(feature = "serde")]
    fn color_id_json_serialize() {
        use serde_json;
        let bytes = Vec::from_hex("c3ec2fd806701a3f55808cbec3922c38dafaa3070c48c803e9043ee3642c660b46").unwrap();
        let color_identifier: ColorIdentifier = deserialize(&bytes).unwrap();
        let json = serde_json::to_value(&color_identifier).unwrap();
        assert_eq!(json, serde_json::Value::String("c3ec2fd806701a3f55808cbec3922c38dafaa3070c48c803e9043ee3642c660b46".to_owned()));
        let result = serde_json::from_value(json).unwrap();
        assert_eq!(color_identifier, result);

        let invalid_token_type =
            serde_json::Value::String("c0ec2fd806701a3f55808cbec3922c38dafaa3070c48c803e9043ee3642c660b46".to_owned());
        let result: Result<ColorIdentifier, _> = serde_json::from_value(invalid_token_type);
        assert_eq!(result.is_err(), true);

        let too_short = serde_json::Value::String("c1ec2fd806701a3f55808cbec3922c38dafaa3070c48c803e9043ee3642c660b".to_owned());
        let result: Result<ColorIdentifier, _> = serde_json::from_value(too_short);
        assert_eq!(result.is_err(), true);

        let too_long = serde_json::Value::String("c1ec2fd806701a3f55808cbec3922c38dafaa3070c48c803e9043ee3642c660b46ff".to_owned());
        let result: Result<ColorIdentifier, _> = serde_json::from_value(too_long);
        assert_eq!(result.is_err(), true);
    }

    #[test]
    fn script_asm() {
        assert_eq!(hex_script!("6363636363686868686800").asm(),
                   "OP_IF OP_IF OP_IF OP_IF OP_IF OP_ENDIF OP_ENDIF OP_ENDIF OP_ENDIF OP_ENDIF OP_0");
        assert_eq!(hex_script!("6363636363686868686800").asm(),
                   "OP_IF OP_IF OP_IF OP_IF OP_IF OP_ENDIF OP_ENDIF OP_ENDIF OP_ENDIF OP_ENDIF OP_0");
        assert_eq!(hex_script!("2102715e91d37d239dea832f1460e91e368115d8ca6cc23a7da966795abad9e3b699ac").asm(),
                   "OP_PUSHBYTES_33 02715e91d37d239dea832f1460e91e368115d8ca6cc23a7da966795abad9e3b699 OP_CHECKSIG");
        // Elements Alpha peg-out transaction with some signatures removed for brevity. Mainly to test PUSHDATA1
        assert_eq!(hex_script!("0047304402202457e78cc1b7f50d0543863c27de75d07982bde8359b9e3316adec0aec165f2f02200203fd331c4e4a4a02f48cf1c291e2c0d6b2f7078a784b5b3649fca41f8794d401004cf1552103244e602b46755f24327142a0517288cebd159eccb6ccf41ea6edf1f601e9af952103bbbacc302d19d29dbfa62d23f37944ae19853cf260c745c2bea739c95328fcb721039227e83246bd51140fe93538b2301c9048be82ef2fb3c7fc5d78426ed6f609ad210229bf310c379b90033e2ecb07f77ecf9b8d59acb623ab7be25a0caed539e2e6472103703e2ed676936f10b3ce9149fa2d4a32060fb86fa9a70a4efe3f21d7ab90611921031e9b7c6022400a6bb0424bbcde14cff6c016b91ee3803926f3440abf5c146d05210334667f975f55a8455d515a2ef1c94fdfa3315f12319a14515d2a13d82831f62f57ae").asm(),
                   "OP_0 OP_PUSHBYTES_71 304402202457e78cc1b7f50d0543863c27de75d07982bde8359b9e3316adec0aec165f2f02200203fd331c4e4a4a02f48cf1c291e2c0d6b2f7078a784b5b3649fca41f8794d401 OP_0 OP_PUSHDATA1 552103244e602b46755f24327142a0517288cebd159eccb6ccf41ea6edf1f601e9af952103bbbacc302d19d29dbfa62d23f37944ae19853cf260c745c2bea739c95328fcb721039227e83246bd51140fe93538b2301c9048be82ef2fb3c7fc5d78426ed6f609ad210229bf310c379b90033e2ecb07f77ecf9b8d59acb623ab7be25a0caed539e2e6472103703e2ed676936f10b3ce9149fa2d4a32060fb86fa9a70a4efe3f21d7ab90611921031e9b7c6022400a6bb0424bbcde14cff6c016b91ee3803926f3440abf5c146d05210334667f975f55a8455d515a2ef1c94fdfa3315f12319a14515d2a13d82831f62f57ae");
    }

    #[test]
    fn script_p2sh_p2p2k_template() {
        // random outputs I picked out of the mempool
        assert!(hex_script!("76a91402306a7c23f3e8010de41e9e591348bb83f11daa88ac").is_p2pkh());
        assert!(!hex_script!("76a91402306a7c23f3e8010de41e9e591348bb83f11daa88ac").is_p2sh());
        assert!(!hex_script!("76a91402306a7c23f3e8010de41e9e591348bb83f11daa88ad").is_p2pkh());
        assert!(!hex_script!("").is_p2pkh());
        assert!(hex_script!("a914acc91e6fef5c7f24e5c8b3f11a664aa8f1352ffd87").is_p2sh());
        assert!(!hex_script!("a914acc91e6fef5c7f24e5c8b3f11a664aa8f1352ffd87").is_p2pkh());
        assert!(!hex_script!("a314acc91e6fef5c7f24e5c8b3f11a664aa8f1352ffd87").is_p2sh());
    }

    #[test]
    fn script_p2pk() {
        assert!(hex_script!("21021aeaf2f8638a129a3156fbe7e5ef635226b0bafd495ff03afe2c843d7e3a4b51ac").is_p2pk());
        assert!(hex_script!("410496b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52da7589379515d4e0a604f8141781e62294721166bf621e73a82cbf2342c858eeac").is_p2pk());
    }

    #[test]
    fn script_cp2pkh() {
        // cp2pkh
        assert!(hex_script!("21c3ec2fd806701a3f55808cbec3922c38dafaa3070c48c803e9043ee3642c660b46bc76a91446c2fbfbecc99a63148fa076de58cf29b0bcf0b088ac").is_cp2pkh());
        // cp2sh
        assert!(!hex_script!("21c3ec2fd806701a3f55808cbec3922c38dafaa3070c48c803e9043ee3642c660b46bca9147620a79e8657d066cff10e21228bf983cf546ac687").is_cp2pkh());
        // p2pkh
        assert!(!hex_script!("76a91446c2fbfbecc99a63148fa076de58cf29b0bcf0b088ac").is_cp2pkh());
        // invalid type
        assert!(!hex_script!("21c4ec2fd806701a3f55808cbec3922c38dafaa3070c48c803e9043ee3642c660b46bc76a91446c2fbfbecc99a63148fa076de58cf29b0bcf0b088ac").is_cp2pkh());
    }

    #[test]
    fn script_cp2sh() {
        // cp2sh
        assert!(hex_script!("21c3ec2fd806701a3f55808cbec3922c38dafaa3070c48c803e9043ee3642c660b46bca9147620a79e8657d066cff10e21228bf983cf546ac687").is_cp2sh());
        // cp2pkh
        assert!(!hex_script!("21c3ec2fd806701a3f55808cbec3922c38dafaa3070c48c803e9043ee3642c660b46bc76a91446c2fbfbecc99a63148fa076de58cf29b0bcf0b088ac").is_cp2sh());
        // p2sh
        assert!(!hex_script!("a9147620a79e8657d066cff10e21228bf983cf546ac687").is_cp2sh());
        // invalid type
        assert!(!hex_script!("21c4ec2fd806701a3f55808cbec3922c38dafaa3070c48c803e9043ee3642c660b46bca9147620a79e8657d066cff10e21228bf983cf546ac687").is_cp2sh());
    }

    #[test]
    fn script_multisig() {
        let multisig = hex_script!("522102a5613bd857b7048924264d1e70e08fb2a7e6527d32b7ab1bb993ac59964ff39721021ac43c7ff740014c3b33737ede99c967e4764553d1b2b83db77c83b8715fa72d2102df2089105c77f266fa11a9d33f05c735234075f2e8780824c6b709415f9fb48553ae");
        let invalid = hex_script!("542102a5613bd857b7048924264d1e70e08fb2a7e6527d32b7ab1bb993ac59964ff39721021ac43c7ff740014c3b33737ede99c967e4764553d1b2b83db77c83b8715fa72d2102df2089105c77f266fa11a9d33f05c735234075f2e8780824c6b709415f9fb48553ae");
        let invalid_sig_count = hex_script!("752102a5613bd857b7048924264d1e70e08fb2a7e6527d32b7ab1bb993ac59964ff39721021ac43c7ff740014c3b33737ede99c967e4764553d1b2b83db77c83b8715fa72d2102df2089105c77f266fa11a9d33f05c735234075f2e8780824c6b709415f9fb48553ae");
        let invalid_pubkey_count = hex_script!("522102a5613bd857b7048924264d1e70e08fb2a7e6527d32b7ab1bb993ac59964ff39721021ac43c7ff740014c3b33737ede99c967e4764553d1b2b83db77c83b8715fa72d2102df2089105c77f266fa11a9d33f05c735234075f2e8780824c6b709415f9fb48575ae");
        let p2pkh = hex_script!("76a91446c2fbfbecc99a63148fa076de58cf29b0bcf0b088ac");
        let p2sh = hex_script!("a9147620a79e8657d066cff10e21228bf983cf546ac687");

        // multisig
        assert!(multisig.is_multisig());
        // invalid multisig(too many required keys)
        assert!(!invalid.is_multisig());
        // invalid multisig(invalid sig count)
        assert!(!invalid_sig_count.is_multisig());
        // invalid multisig(invalid pubkey count)
        assert!(!invalid_pubkey_count.is_multisig());

        // p2pkh
        assert!(!p2pkh.is_multisig());
        // p2sh
        assert!(!p2sh.is_multisig());

        let pubkeys = vec![
            PublicKey::from_str("02a5613bd857b7048924264d1e70e08fb2a7e6527d32b7ab1bb993ac59964ff397").unwrap(),
            PublicKey::from_str("021ac43c7ff740014c3b33737ede99c967e4764553d1b2b83db77c83b8715fa72d").unwrap(),
            PublicKey::from_str("02df2089105c77f266fa11a9d33f05c735234075f2e8780824c6b709415f9fb485").unwrap(),
        ];
        assert_eq!(multisig.get_multisig_pubkeys(), Ok((2, pubkeys)));

        assert_eq!(invalid.get_multisig_pubkeys(), Err(MultisigError::IsNotMultisig));
    }

    #[test]
    fn script_type() {
        let p2pk = hex_script!("2102a5613bd857b7048924264d1e70e08fb2a7e6527d32b7ab1bb993ac59964ff397ac");
        let p2pkh = hex_script!("76a91446c2fbfbecc99a63148fa076de58cf29b0bcf0b088ac");
        let multisig = hex_script!("522102a5613bd857b7048924264d1e70e08fb2a7e6527d32b7ab1bb993ac59964ff39721021ac43c7ff740014c3b33737ede99c967e4764553d1b2b83db77c83b8715fa72d2102df2089105c77f266fa11a9d33f05c735234075f2e8780824c6b709415f9fb48553ae");
        let p2sh = hex_script!("a9147620a79e8657d066cff10e21228bf983cf546ac687");
        let op_return = hex_script!("6aa9149eb21980dc9d413d8eac27314938b9da920ee53e87");
        let cp2pkh = hex_script!("21c3ec2fd806701a3f55808cbec3922c38dafaa3070c48c803e9043ee3642c660b46bc76a91446c2fbfbecc99a63148fa076de58cf29b0bcf0b088ac");
        let cp2sh = hex_script!("21c3ec2fd806701a3f55808cbec3922c38dafaa3070c48c803e9043ee3642c660b46bca9147620a79e8657d066cff10e21228bf983cf546ac687");
        let non_standard = hex_script!("00");

        // p2pk
        assert_eq!(p2pk.script_type(), ScriptType::P2pk);
        assert_eq!(format!("{}", p2pk.script_type()), "pubkey");
        assert_eq!(ScriptType::from_str("pubkey"), Ok(ScriptType::P2pk));
        // p2pkh
        assert_eq!(p2pkh.script_type(), ScriptType::P2pkh);
        assert_eq!(format!("{}", p2pkh.script_type()), "pubkeyhash");
        assert_eq!(ScriptType::from_str("pubkeyhash"), Ok(ScriptType::P2pkh));
        // multisig
        assert_eq!(multisig.script_type(), ScriptType::P2ms);
        assert_eq!(format!("{}", multisig.script_type()), "multisig");
        assert_eq!(ScriptType::from_str("multisig"), Ok(ScriptType::P2ms));
        // p2sh
        assert_eq!(p2sh.script_type(), ScriptType::P2sh);
        assert_eq!(format!("{}", p2sh.script_type()), "scripthash");
        assert_eq!(ScriptType::from_str("scripthash"), Ok(ScriptType::P2sh));
        // op-return
        assert_eq!(op_return.script_type(), ScriptType::Nulldata);
        assert_eq!(format!("{}", op_return.script_type()), "nulldata");
        assert_eq!(ScriptType::from_str("nulldata"), Ok(ScriptType::Nulldata));
        // cp2pkh
        assert_eq!(cp2pkh.script_type(), ScriptType::Cp2pkh);
        assert_eq!(format!("{}", cp2pkh.script_type()), "coloredpubkeyhash");
        assert_eq!(ScriptType::from_str("coloredpubkeyhash"), Ok(ScriptType::Cp2pkh));
        // cp2sh
        assert_eq!(cp2sh.script_type(), ScriptType::Cp2sh);
        assert_eq!(format!("{}", cp2sh.script_type()), "coloredscripthash");
        assert_eq!(ScriptType::from_str("coloredscripthash"), Ok(ScriptType::Cp2sh));
        // non-standard
        assert_eq!(non_standard.script_type(), ScriptType::NonStandard);
        assert_eq!(format!("{}", non_standard.script_type()), "nonstandard");
        assert_eq!(ScriptType::from_str("nonstandard"), Ok(ScriptType::NonStandard));
    }

    #[test]
    fn is_colored_test() {
        // cp2pkh
        assert!(hex_script!("21c3ec2fd806701a3f55808cbec3922c38dafaa3070c48c803e9043ee3642c660b46bc76a91446c2fbfbecc99a63148fa076de58cf29b0bcf0b088ac").is_colored());
        // cp2sh
        assert!(hex_script!("21c3ec2fd806701a3f55808cbec3922c38dafaa3070c48c803e9043ee3642c660b46bca9147620a79e8657d066cff10e21228bf983cf546ac687").is_colored());
        // p2pkh
        assert!(!hex_script!("76a91446c2fbfbecc99a63148fa076de58cf29b0bcf0b088ac").is_colored());
        // p2sh
        assert!(!hex_script!("a9147620a79e8657d066cff10e21228bf983cf546ac687").is_colored());
    }

    #[test]
    fn color_identifier_test() {
        let color_id = ColorIdentifier::reissuable(hex_script!("76a91446c2fbfbecc99a63148fa076de58cf29b0bcf0b088ac"));
        assert_eq!(color_id.token_type, TokenTypes::Reissuable);
        assert_eq!(color_id.is_colored(), true);
        assert_eq!(color_id.is_default(), false);

        let color_id = ColorIdentifier::non_reissuable(OutPoint::default());
        assert_eq!(color_id.token_type, TokenTypes::NonReissuable);
        assert_eq!(color_id.is_colored(), true);
        assert_eq!(color_id.is_default(), false);

        let color_id = ColorIdentifier::nft(OutPoint::default());
        assert_eq!(color_id.token_type, TokenTypes::Nft);
        assert_eq!(color_id.is_colored(), true);
        assert_eq!(color_id.is_default(), false);

        let color_id = ColorIdentifier::default();
        assert_eq!(color_id.token_type, TokenTypes::None);
        assert_eq!(color_id.is_colored(), false);
        assert_eq!(color_id.is_default(), true);
    }

    #[test]
    fn color_from_slice_test() {
        let color_id = ColorIdentifier::from_hex("c3ec2fd806701a3f55808cbec3922c38dafaa3070c48c803e9043ee3642c660b46").unwrap();
        assert_eq!(color_id.token_type, TokenTypes::Nft);

        let color_id = ColorIdentifier::from_slice(&Vec::from_hex("c3ec2fd806701a3f55808cbec3922c38dafaa3070c48c803e9043ee3642c660b46").unwrap()).unwrap();
        assert_eq!(color_id.token_type, TokenTypes::Nft);
    }

    #[test]
    fn split_color_test() {
        let out_point = OutPoint::new(Txid::from_hex("0101010101010101010101010101010101010101010101010101010101010101").unwrap(), 1);
        let p2pkh = hex_script!("76a91446c2fbfbecc99a63148fa076de58cf29b0bcf0b088ac");

        // p2pkh -> cp2pkh
        let cp2pkh = p2pkh.add_color(ColorIdentifier::nft(out_point)).unwrap();

        // cp2pkh -> (color_id, p2pkh)
        let (color_id, script) = cp2pkh.split_color().unwrap();
        assert_eq!(format!("{}", color_id), "c3ec2fd806701a3f55808cbec3922c38dafaa3070c48c803e9043ee3642c660b46");
        assert_eq!(script, p2pkh);

        // p2pkh -> None
        assert_eq!(p2pkh.split_color(), None);
    }

    #[test]
    fn token_type_is_valid() {
        assert!(TokenTypes::is_valid(&0x00));
        assert!(TokenTypes::is_valid(&0xc1));
        assert!(TokenTypes::is_valid(&0xc2));
        assert!(TokenTypes::is_valid(&0xc3));
        assert!(!TokenTypes::is_valid(&0xc4));
    }

    #[test]
    fn add_color_test() {
        let out_point = OutPoint::new(Txid::from_hex("0101010101010101010101010101010101010101010101010101010101010101").unwrap(), 1);
        let color_id = ColorIdentifier::nft(out_point);
        let p2pkh = hex_script!("76a91446c2fbfbecc99a63148fa076de58cf29b0bcf0b088ac");
        let p2sh = hex_script!("a9147620a79e8657d066cff10e21228bf983cf546ac687");
        let op_return = hex_script!("6aa9149eb21980dc9d413d8eac27314938b9da920ee53e87");

        // p2pkh -> cp2pkh
        let cp2pkh = p2pkh.add_color(color_id.clone()).unwrap();
        assert!(cp2pkh.is_cp2pkh());
        assert_eq!(hex::encode(cp2pkh.to_bytes()), "21c3ec2fd806701a3f55808cbec3922c38dafaa3070c48c803e9043ee3642c660b46bc76a91446c2fbfbecc99a63148fa076de58cf29b0bcf0b088ac");

        // p2sh -> cp2sh
        let cp2sh = p2sh.add_color(color_id.clone()).unwrap();
        assert!(cp2sh.is_cp2sh());
        assert_eq!(hex::encode(cp2sh.to_bytes()), "21c3ec2fd806701a3f55808cbec3922c38dafaa3070c48c803e9043ee3642c660b46bca9147620a79e8657d066cff10e21228bf983cf546ac687");

        // op_return -> err
        let op_return = op_return.add_color(color_id.clone());
        assert!(op_return.is_err());
    }

    #[test]
    fn serialize_color_id() {
        let out_point = OutPoint::new(Txid::from_hex("0101010101010101010101010101010101010101010101010101010101010101").unwrap(), 1);
        let color_id = ColorIdentifier::nft(out_point);

        assert_eq!(format!("{}",color_id), "c3ec2fd806701a3f55808cbec3922c38dafaa3070c48c803e9043ee3642c660b46");

        let hex_script = Vec::from_hex("c3ec2fd806701a3f55808cbec3922c38dafaa3070c48c803e9043ee3642c660b46").unwrap();
        let script: Result<ColorIdentifier, _> = deserialize(&hex_script);
        assert!(script.is_ok());
        let color_id = script.unwrap();
        assert_eq!(color_id.token_type, TokenTypes::Nft);
        assert_eq!(serialize(&color_id), hex_script);

        let invalid_token_type =
            "c0ec2fd806701a3f55808cbec3922c38dafaa3070c48c803e9043ee3642c660b46";
        let bytes = Vec::from_hex(invalid_token_type).unwrap();
        let result: Result<ColorIdentifier, _> = deserialize(&bytes);
        assert_eq!(result.is_err(), true);

        let too_short = "c1ec2fd806701a3f55808cbec3922c38dafaa3070c48c803e9043ee3642c660b";
        let bytes = Vec::from_hex(too_short).unwrap();
        let result: Result<ColorIdentifier, _> = deserialize(&bytes);
        assert_eq!(result.is_err(), true);

        let too_long = "c1ec2fd806701a3f55808cbec3922c38dafaa3070c48c803e9043ee3642c660b46ff";
        let bytes = Vec::from_hex(too_long).unwrap();
        let result: Result<ColorIdentifier, _> = deserialize(&bytes);
        assert_eq!(result.is_err(), true);
    }

    #[test]
    fn p2sh_p2wsh_conversion() {
        // Test vectors taken from Core tests/data/script_tests.json
        // bare p2wsh
        let redeem_script = hex_script!("410479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8ac");
        let expected_witout = hex_script!("0020b95237b48faaa69eb078e1170be3b5cbb3fddf16d0a991e14ad274f7b33a4f64");
        assert!(redeem_script.to_v0_p2wsh().is_v0_p2wsh());
        assert_eq!(redeem_script.to_v0_p2wsh(), expected_witout);

        // p2sh
        let redeem_script = hex_script!("0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8");
        let expected_p2shout = hex_script!("a91491b24bf9f5288532960ac687abb035127b1d28a587");
        assert!(redeem_script.to_p2sh().is_p2sh());
        assert_eq!(redeem_script.to_p2sh(), expected_p2shout);

        // p2sh-p2wsh
        let redeem_script = hex_script!("410479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8ac");
        let expected_witout = hex_script!("0020b95237b48faaa69eb078e1170be3b5cbb3fddf16d0a991e14ad274f7b33a4f64");
        let expected_out = hex_script!("a914f386c2ba255cc56d20cfa6ea8b062f8b5994551887");
        assert!(redeem_script.to_p2sh().is_p2sh());
        assert!(redeem_script.to_p2sh().to_v0_p2wsh().is_v0_p2wsh());
        assert_eq!(redeem_script.to_v0_p2wsh(), expected_witout);
        assert_eq!(redeem_script.to_v0_p2wsh().to_p2sh(), expected_out);
    }

    #[test]
    fn test_iterator() {
        let zero = hex_script!("00");
        let zeropush = hex_script!("0100");

        let nonminimal = hex_script!("4c0169b2");      // PUSHDATA1 for no reason
        let minimal = hex_script!("0169b2");           // minimal
        let nonminimal_alt = hex_script!("026900b2");  // non-minimal number but minimal push (should be OK)

        let v_zero: Result<Vec<Instruction>, Error> = zero.instructions_minimal().collect();
        let v_zeropush: Result<Vec<Instruction>, Error> = zeropush.instructions_minimal().collect();

        let v_min: Result<Vec<Instruction>, Error> = minimal.instructions_minimal().collect();
        let v_nonmin: Result<Vec<Instruction>, Error> = nonminimal.instructions_minimal().collect();
        let v_nonmin_alt: Result<Vec<Instruction>, Error> = nonminimal_alt.instructions_minimal().collect();
        let slop_v_min: Result<Vec<Instruction>, Error> = minimal.instructions().collect();
        let slop_v_nonmin: Result<Vec<Instruction>, Error> = nonminimal.instructions().collect();
        let slop_v_nonmin_alt: Result<Vec<Instruction>, Error> = nonminimal_alt.instructions().collect();

        assert_eq!(
            v_zero.unwrap(),
            vec![
                Instruction::PushBytes(&[]),
            ]
        );
        assert_eq!(
            v_zeropush.unwrap(),
            vec![
                Instruction::PushBytes(&[0]),
            ]
        );

        assert_eq!(
            v_min.clone().unwrap(),
            vec![
                Instruction::PushBytes(&[105]),
                Instruction::Op(opcodes::OP_NOP3),
            ]
        );

        assert_eq!(
            v_nonmin.err().unwrap(),
            Error::NonMinimalPush
        );

        assert_eq!(
            v_nonmin_alt.clone().unwrap(),
            vec![
                Instruction::PushBytes(&[105, 0]),
                Instruction::Op(opcodes::OP_NOP3),
            ]
        );

        assert_eq!(v_min.clone().unwrap(), slop_v_min.unwrap());
        assert_eq!(v_min.unwrap(), slop_v_nonmin.unwrap());
        assert_eq!(v_nonmin_alt.unwrap(), slop_v_nonmin_alt.unwrap());
    }

	#[test]
    fn script_ord() {
        let script_1 = Builder::new().push_slice(&[1,2,3,4]).into_script();
        let script_2 = Builder::new().push_int(10).into_script();
        let script_3 = Builder::new().push_int(15).into_script();
        let script_4 = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script();

        assert!(script_1 < script_2);
        assert!(script_2 < script_3);
        assert!(script_3 < script_4);

        assert!(script_1 <= script_1);
        assert!(script_1 >= script_1);

        assert!(script_4 > script_3);
        assert!(script_3 > script_2);
        assert!(script_2 > script_1);
    }

	#[test]
	#[cfg(feature="bitcoinconsensus")]
	fn test_bitcoinconsensus () {
		// a random segwit transaction from the blockchain using native segwit
		let spent = Builder::from(Vec::from_hex("0020701a8d401c84fb13e6baf169d59684e17abd9fa216c8cc5b9fc63d622ff8c58d").unwrap()).into_script();
		let spending = Vec::from_hex("010000000001011f97548fbbe7a0db7588a66e18d803d0089315aa7d4cc28360b6ec50ef36718a0100000000ffffffff02df1776000000000017a9146c002a686959067f4866b8fb493ad7970290ab728757d29f0000000000220020701a8d401c84fb13e6baf169d59684e17abd9fa216c8cc5b9fc63d622ff8c58d04004730440220565d170eed95ff95027a69b313758450ba84a01224e1f7f130dda46e94d13f8602207bdd20e307f062594022f12ed5017bbf4a055a06aea91c10110a0e3bb23117fc014730440220647d2dc5b15f60bc37dc42618a370b2a1490293f9e5c8464f53ec4fe1dfe067302203598773895b4b16d37485cbe21b337f4e4b650739880098c592553add7dd4355016952210375e00eb72e29da82b89367947f29ef34afb75e8654f6ea368e0acdfd92976b7c2103a1b26313f430c4b15bb1fdce663207659d8cac749a0e53d70eff01874496feff2103c96d495bfdd5ba4145e3e046fee45e84a8a48ad05bd8dbb395c011a32cf9f88053ae00000000").unwrap();
		spent.verify(0, 18393430, spending.as_slice()).unwrap();
	}
}