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
use std::collections::{BTreeMap, HashSet};

use chainhook_types::{BitcoinNetwork, StacksNetwork};
use reqwest::Url;
use serde::ser::{SerializeSeq, Serializer};
use serde::{de, Deserialize, Deserializer, Serialize};

use schemars::JsonSchema;

use crate::utils::MAX_BLOCK_HEIGHTS_ENTRIES;

#[derive(Deserialize, Debug, Clone)]
pub struct ChainhookConfig {
    pub stacks_chainhooks: Vec<StacksChainhookSpecification>,
    pub bitcoin_chainhooks: Vec<BitcoinChainhookSpecification>,
}

impl ChainhookConfig {
    pub fn new() -> ChainhookConfig {
        ChainhookConfig {
            stacks_chainhooks: vec![],
            bitcoin_chainhooks: vec![],
        }
    }

    pub fn register_full_specification(
        &mut self,
        networks: (&BitcoinNetwork, &StacksNetwork),
        hook: ChainhookFullSpecification,
    ) -> Result<ChainhookSpecification, String> {
        let spec = match hook {
            ChainhookFullSpecification::Stacks(hook) => {
                let spec = hook.into_selected_network_specification(networks.1)?;
                self.stacks_chainhooks.push(spec.clone());
                ChainhookSpecification::Stacks(spec)
            }
            ChainhookFullSpecification::Bitcoin(hook) => {
                let spec = hook.into_selected_network_specification(networks.0)?;
                self.bitcoin_chainhooks.push(spec.clone());
                ChainhookSpecification::Bitcoin(spec)
            }
        };
        Ok(spec)
    }

    pub fn enable_specification(&mut self, predicate_spec: &mut ChainhookSpecification) {
        match predicate_spec {
            ChainhookSpecification::Stacks(spec_to_enable) => {
                for spec in self.stacks_chainhooks.iter_mut() {
                    if spec.uuid.eq(&spec_to_enable.uuid) {
                        spec.enabled = true;
                        spec_to_enable.enabled = true;
                        break;
                    }
                }
            }
            ChainhookSpecification::Bitcoin(spec_to_enable) => {
                for spec in self.bitcoin_chainhooks.iter_mut() {
                    if spec.uuid.eq(&spec_to_enable.uuid) {
                        spec.enabled = true;
                        spec_to_enable.enabled = true;
                        break;
                    }
                }
            }
        };
    }

    pub fn register_specification(&mut self, spec: ChainhookSpecification) -> Result<(), String> {
        match spec {
            ChainhookSpecification::Stacks(spec) => {
                let spec = spec.clone();
                self.stacks_chainhooks.push(spec);
            }
            ChainhookSpecification::Bitcoin(spec) => {
                let spec = spec.clone();
                self.bitcoin_chainhooks.push(spec);
            }
        };
        Ok(())
    }

    pub fn deregister_stacks_hook(
        &mut self,
        hook_uuid: String,
    ) -> Option<StacksChainhookSpecification> {
        let mut i = 0;
        while i < self.stacks_chainhooks.len() {
            if self.stacks_chainhooks[i].uuid == hook_uuid {
                let hook = self.stacks_chainhooks.remove(i);
                return Some(hook);
            } else {
                i += 1;
            }
        }
        None
    }

    pub fn deregister_bitcoin_hook(
        &mut self,
        hook_uuid: String,
    ) -> Option<BitcoinChainhookSpecification> {
        let mut i = 0;
        while i < self.bitcoin_chainhooks.len() {
            if self.bitcoin_chainhooks[i].uuid == hook_uuid {
                let hook = self.bitcoin_chainhooks.remove(i);
                return Some(hook);
            } else {
                i += 1;
            }
        }
        None
    }

    pub fn expire_stacks_hook(&mut self, hook_uuid: String, block_height: u64) {
        let mut i = 0;
        while i < self.stacks_chainhooks.len() {
            if ChainhookSpecification::stacks_key(&self.stacks_chainhooks[i].uuid) == hook_uuid {
                self.stacks_chainhooks[i].expired_at = Some(block_height);
                break;
            } else {
                i += 1;
            }
        }
    }

    pub fn expire_bitcoin_hook(&mut self, hook_uuid: String, block_height: u64) {
        let mut i = 0;
        while i < self.bitcoin_chainhooks.len() {
            if ChainhookSpecification::bitcoin_key(&self.bitcoin_chainhooks[i].uuid) == hook_uuid {
                self.bitcoin_chainhooks[i].expired_at = Some(block_height);
                break;
            } else {
                i += 1;
            }
        }
    }
}

impl Serialize for ChainhookConfig {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut seq = serializer.serialize_seq(Some(
            self.bitcoin_chainhooks.len() + self.stacks_chainhooks.len(),
        ))?;
        for chainhook in self.bitcoin_chainhooks.iter() {
            seq.serialize_element(chainhook)?;
        }
        for chainhook in self.stacks_chainhooks.iter() {
            seq.serialize_element(chainhook)?;
        }
        seq.end()
    }
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum ChainhookSpecification {
    Bitcoin(BitcoinChainhookSpecification),
    Stacks(StacksChainhookSpecification),
}

impl ChainhookSpecification {
    pub fn either_stx_or_btc_key(uuid: &str) -> String {
        format!("predicate:{}", uuid)
    }

    pub fn stacks_key(uuid: &str) -> String {
        format!("predicate:{}", uuid)
    }

    pub fn bitcoin_key(uuid: &str) -> String {
        format!("predicate:{}", uuid)
    }

    pub fn key(&self) -> String {
        match &self {
            Self::Bitcoin(data) => Self::bitcoin_key(&data.uuid),
            Self::Stacks(data) => Self::stacks_key(&data.uuid),
        }
    }

    pub fn deserialize_specification(spec: &str) -> Result<ChainhookSpecification, String> {
        let spec: ChainhookSpecification = serde_json::from_str(spec)
            .map_err(|e| format!("unable to deserialize predicate {}", e.to_string()))?;
        Ok(spec)
    }

    pub fn uuid(&self) -> &str {
        match &self {
            Self::Bitcoin(data) => &data.uuid,
            Self::Stacks(data) => &data.uuid,
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct BitcoinChainhookSpecification {
    pub uuid: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub owner_uuid: Option<String>,
    pub name: String,
    pub network: BitcoinNetwork,
    pub version: u32,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub blocks: Option<Vec<u64>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_block: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_block: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expire_after_occurrence: Option<u64>,
    pub predicate: BitcoinPredicateType,
    pub action: HookAction,
    pub include_proof: bool,
    pub include_inputs: bool,
    pub include_outputs: bool,
    pub include_witness: bool,
    pub enabled: bool,
    pub expired_at: Option<u64>,
}

impl BitcoinChainhookSpecification {
    pub fn key(&self) -> String {
        ChainhookSpecification::bitcoin_key(&self.uuid)
    }
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case", tag = "chain")]
pub enum ChainhookFullSpecification {
    Bitcoin(BitcoinChainhookFullSpecification),
    Stacks(StacksChainhookFullSpecification),
}

impl ChainhookFullSpecification {
    pub fn validate(&self) -> Result<(), String> {
        match &self {
            Self::Bitcoin(data) => {
                for (_, spec) in data.networks.iter() {
                    let _ = spec.action.validate()?;
                    if let Some(end_block) = spec.end_block {
                        let start_block = spec.start_block.unwrap_or(0);
                        if start_block > end_block {
                            return Err(
                                "Chainhook specification field `end_block` should be greater than `start_block`."
                                    .into(),
                            );
                        }
                        if (end_block - start_block) > MAX_BLOCK_HEIGHTS_ENTRIES {
                            return Err(format!("Chainhook specification exceeds max number of blocks to scan. Maximum: {}, Attempted: {}", MAX_BLOCK_HEIGHTS_ENTRIES, (end_block - start_block)));
                        }
                    }
                }
            }
            Self::Stacks(data) => {
                for (_, spec) in data.networks.iter() {
                    let _ = spec.action.validate()?;
                    if let Some(end_block) = spec.end_block {
                        let start_block = spec.start_block.unwrap_or(0);
                        if start_block > end_block {
                            return Err(
                                "Chainhook specification field `end_block` should be greater than `start_block`."
                                    .into(),
                            );
                        }
                        if (end_block - start_block) > MAX_BLOCK_HEIGHTS_ENTRIES {
                            return Err(format!("Chainhook specification exceeds max number of blocks to scan. Maximum: {}, Attempted: {}", MAX_BLOCK_HEIGHTS_ENTRIES, (end_block - start_block)));
                        }
                    }
                }
            }
        }
        Ok(())
    }

    pub fn get_uuid(&self) -> &str {
        match &self {
            Self::Bitcoin(data) => &data.uuid,
            Self::Stacks(data) => &data.uuid,
        }
    }

    pub fn deserialize_specification(
        spec: &str,
        _key: &str,
    ) -> Result<ChainhookFullSpecification, String> {
        let spec: ChainhookFullSpecification = serde_json::from_str(spec)
            .map_err(|e| format!("unable to deserialize predicate {}", e.to_string()))?;
        Ok(spec)
    }
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
pub struct BitcoinChainhookFullSpecification {
    pub uuid: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub owner_uuid: Option<String>,
    pub name: String,
    pub version: u32,
    pub networks: BTreeMap<BitcoinNetwork, BitcoinChainhookNetworkSpecification>,
}

impl BitcoinChainhookFullSpecification {
    pub fn into_selected_network_specification(
        mut self,
        network: &BitcoinNetwork,
    ) -> Result<BitcoinChainhookSpecification, String> {
        let spec = self
            .networks
            .remove(network)
            .ok_or("Network unknown".to_string())?;
        Ok(BitcoinChainhookSpecification {
            uuid: self.uuid,
            owner_uuid: self.owner_uuid,
            name: self.name,
            network: network.clone(),
            version: self.version,
            start_block: spec.start_block,
            end_block: spec.end_block,
            blocks: spec.blocks,
            expire_after_occurrence: spec.expire_after_occurrence,
            predicate: spec.predicate,
            action: spec.action,
            include_proof: spec.include_proof.unwrap_or(false),
            include_inputs: spec.include_inputs.unwrap_or(false),
            include_outputs: spec.include_outputs.unwrap_or(false),
            include_witness: spec.include_witness.unwrap_or(false),
            enabled: false,
            expired_at: None,
        })
    }
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
pub struct BitcoinChainhookNetworkSpecification {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub blocks: Option<Vec<u64>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_block: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_block: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expire_after_occurrence: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub include_proof: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub include_inputs: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub include_outputs: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub include_witness: Option<bool>,
    #[serde(rename = "if_this")]
    pub predicate: BitcoinPredicateType,
    #[serde(rename = "then_that")]
    pub action: HookAction,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
pub struct StacksChainhookFullSpecification {
    pub uuid: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub owner_uuid: Option<String>,
    pub name: String,
    pub version: u32,
    pub networks: BTreeMap<StacksNetwork, StacksChainhookNetworkSpecification>,
}

impl StacksChainhookFullSpecification {
    pub fn into_selected_network_specification(
        mut self,
        network: &StacksNetwork,
    ) -> Result<StacksChainhookSpecification, String> {
        let spec = self
            .networks
            .remove(network)
            .ok_or("Network unknown".to_string())?;
        Ok(StacksChainhookSpecification {
            uuid: self.uuid,
            owner_uuid: self.owner_uuid,
            name: self.name,
            network: network.clone(),
            version: self.version,
            start_block: spec.start_block,
            end_block: spec.end_block,
            blocks: spec.blocks,
            capture_all_events: spec.capture_all_events,
            decode_clarity_values: spec.decode_clarity_values,
            expire_after_occurrence: spec.expire_after_occurrence,
            include_contract_abi: spec.include_contract_abi,
            predicate: spec.predicate,
            action: spec.action,
            enabled: false,
            expired_at: None,
        })
    }
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
pub struct StacksChainhookNetworkSpecification {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub blocks: Option<Vec<u64>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_block: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_block: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expire_after_occurrence: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub capture_all_events: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub decode_clarity_values: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub include_contract_abi: Option<bool>,
    #[serde(rename = "if_this")]
    pub predicate: StacksPredicate,
    #[serde(rename = "then_that")]
    pub action: HookAction,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum HookAction {
    HttpPost(HttpHook),
    FileAppend(FileHook),
    Noop,
}

impl HookAction {
    pub fn validate(&self) -> Result<(), String> {
        match &self {
            HookAction::HttpPost(spec) => {
                let _ = Url::parse(&spec.url)
                    .map_err(|e| format!("hook action url invalid ({})", e.to_string()))?;
            }
            HookAction::FileAppend(_) => {}
            HookAction::Noop => {}
        }
        Ok(())
    }
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub struct HttpHook {
    pub url: String,
    pub authorization_header: String,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub struct FileHook {
    pub path: String,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
pub struct ScriptTemplate {
    pub instructions: Vec<ScriptInstruction>,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ScriptInstruction {
    Opcode(u8),
    RawBytes(Vec<u8>),
    Placeholder(String, u8),
}

impl ScriptTemplate {
    pub fn parse(template: &str) -> Result<ScriptTemplate, String> {
        let raw_instructions = template
            .split_ascii_whitespace()
            .map(|c| c.to_string())
            .collect::<Vec<_>>();
        let mut instructions = vec![];
        for raw_instruction in raw_instructions.into_iter() {
            if raw_instruction.starts_with("{") {
                let placeholder = &raw_instruction[1..raw_instruction.len() - 1];
                let (name, size) = match placeholder.split_once(":") {
                    Some(res) => res,
                    None => return Err(format!("malformed placeholder {}: should be {{placeholder-name:number-of-bytes}} (ex: {{id:4}}", raw_instruction))
                };
                let size = match size.parse::<u8>() {
                    Ok(res) => res,
                    Err(_) => return Err(format!("malformed placeholder {}: should be {{placeholder-name:number-of-bytes}} (ex: {{id:4}}", raw_instruction))
                };
                instructions.push(ScriptInstruction::Placeholder(name.to_string(), size));
            } else if let Some(opcode) = opcode_to_hex(&raw_instruction) {
                instructions.push(ScriptInstruction::Opcode(opcode));
            } else if let Ok(bytes) = hex::decode(&raw_instruction) {
                instructions.push(ScriptInstruction::RawBytes(bytes));
            } else {
                return Err(format!("unable to handle instruction {}", raw_instruction));
            }
        }
        Ok(ScriptTemplate { instructions })
    }
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub struct BitcoinTransactionFilterPredicate {
    pub predicate: BitcoinPredicateType,
}

impl BitcoinTransactionFilterPredicate {
    pub fn new(predicate: BitcoinPredicateType) -> BitcoinTransactionFilterPredicate {
        BitcoinTransactionFilterPredicate { predicate }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case", tag = "scope")]
pub enum BitcoinPredicateType {
    Block,
    Txid(ExactMatchingRule),
    Inputs(InputPredicate),
    Outputs(OutputPredicate),
    StacksProtocol(StacksOperations),
    OrdinalsProtocol(OrdinalOperations),
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum InputPredicate {
    Txid(TxinPredicate),
    WitnessScript(MatchingRule),
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum OutputPredicate {
    OpReturn(MatchingRule),
    P2pkh(ExactMatchingRule),
    P2sh(ExactMatchingRule),
    P2wpkh(ExactMatchingRule),
    P2wsh(ExactMatchingRule),
    Descriptor(DescriptorMatchingRule),
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case", tag = "operation")]
pub enum StacksOperations {
    StackerRewarded,
    BlockCommitted,
    LeaderRegistered,
    StxTransferred,
    StxLocked,
}

#[derive(Clone, Debug, Serialize, Deserialize, Hash, PartialEq, Eq, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum OrdinalsMetaProtocol {
    All,
    #[serde(rename = "brc-20")]
    Brc20,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
pub struct InscriptionFeedData {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub meta_protocols: Option<HashSet<OrdinalsMetaProtocol>>,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
#[serde(rename_all = "snake_case", tag = "operation")]
pub enum OrdinalOperations {
    InscriptionFeed(InscriptionFeedData),
}

pub fn get_stacks_canonical_magic_bytes(network: &BitcoinNetwork) -> [u8; 2] {
    match network {
        BitcoinNetwork::Mainnet => *b"X2",
        BitcoinNetwork::Testnet => *b"T2",
        BitcoinNetwork::Regtest => *b"id",
        BitcoinNetwork::Signet => unreachable!(),
    }
}

pub struct PoxConfig {
    pub genesis_block_height: u64,
    pub prepare_phase_len: u64,
    pub reward_phase_len: u64,
    pub rewarded_addresses_per_block: usize,
}

impl PoxConfig {
    pub fn get_pox_cycle_len(&self) -> u64 {
        self.prepare_phase_len + self.reward_phase_len
    }

    pub fn get_pox_cycle_id(&self, block_height: u64) -> u64 {
        (block_height.saturating_sub(self.genesis_block_height)) / self.get_pox_cycle_len()
    }

    pub fn get_pos_in_pox_cycle(&self, block_height: u64) -> u64 {
        (block_height.saturating_sub(self.genesis_block_height)) % self.get_pox_cycle_len()
    }

    pub fn get_burn_address(&self) -> &str {
        match self.genesis_block_height {
            666050 => "1111111111111111111114oLvT2",
            2000000 => "burn-address-regtest",
            _ => "burn-address",
        }
    }
}

const POX_CONFIG_MAINNET: PoxConfig = PoxConfig {
    genesis_block_height: 666050,
    prepare_phase_len: 100,
    reward_phase_len: 2100,
    rewarded_addresses_per_block: 2,
};

const POX_CONFIG_TESTNET: PoxConfig = PoxConfig {
    genesis_block_height: 2000000,
    prepare_phase_len: 50,
    reward_phase_len: 1050,
    rewarded_addresses_per_block: 2,
};

const POX_CONFIG_DEVNET: PoxConfig = PoxConfig {
    genesis_block_height: 100,
    prepare_phase_len: 4,
    reward_phase_len: 10,
    rewarded_addresses_per_block: 2,
};

pub fn get_canonical_pox_config(network: &BitcoinNetwork) -> PoxConfig {
    match network {
        BitcoinNetwork::Mainnet => POX_CONFIG_MAINNET,
        BitcoinNetwork::Testnet => POX_CONFIG_TESTNET,
        BitcoinNetwork::Regtest => POX_CONFIG_DEVNET,
        BitcoinNetwork::Signet => unreachable!(),
    }
}

#[derive(Debug, Clone, PartialEq)]
#[repr(u8)]
pub enum StacksOpcodes {
    BlockCommit = '[' as u8,
    KeyRegister = '^' as u8,
    StackStx = 'x' as u8,
    PreStx = 'p' as u8,
    TransferStx = '$' as u8,
}

impl TryFrom<u8> for StacksOpcodes {
    type Error = ();

    fn try_from(v: u8) -> Result<Self, Self::Error> {
        match v {
            x if x == StacksOpcodes::BlockCommit as u8 => Ok(StacksOpcodes::BlockCommit),
            x if x == StacksOpcodes::KeyRegister as u8 => Ok(StacksOpcodes::KeyRegister),
            x if x == StacksOpcodes::StackStx as u8 => Ok(StacksOpcodes::StackStx),
            x if x == StacksOpcodes::PreStx as u8 => Ok(StacksOpcodes::PreStx),
            x if x == StacksOpcodes::TransferStx as u8 => Ok(StacksOpcodes::TransferStx),
            _ => Err(()),
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub struct TxinPredicate {
    pub txid: String,
    pub vout: u32,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum BlockIdentifierIndexRule {
    Equals(u64),
    HigherThan(u64),
    LowerThan(u64),
    Between(u64, u64),
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum Scope {
    Inputs,
    Outputs,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum MatchingRule {
    Equals(String),
    StartsWith(String),
    EndsWith(String),
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ExactMatchingRule {
    Equals(String),
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub struct DescriptorMatchingRule {
    // expression defines the bitcoin descriptor.
    pub expression: String,
    #[serde(default, deserialize_with = "deserialize_descriptor_range")]
    pub range: Option<[u32; 2]>,
}

// deserialize_descriptor_range makes sure that the range value is valid.
fn deserialize_descriptor_range<'de, D>(deserializer: D) -> Result<Option<[u32; 2]>, D::Error>
where
    D: Deserializer<'de>,
{
    let range: [u32; 2] = Deserialize::deserialize(deserializer)?;
    if !(range[0] < range[1]) {
        Err(de::Error::custom(
            "First element of 'range' must be lower than the second element",
        ))
    } else {
        Ok(Some(range))
    }
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum BlockIdentifierHashRule {
    Equals(String),
    BuildsOff(String),
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct StacksChainhookSpecification {
    pub uuid: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub owner_uuid: Option<String>,
    pub name: String,
    pub network: StacksNetwork,
    pub version: u32,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub blocks: Option<Vec<u64>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_block: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_block: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expire_after_occurrence: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub capture_all_events: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub decode_clarity_values: Option<bool>,
    pub include_contract_abi: Option<bool>,
    #[serde(rename = "predicate")]
    pub predicate: StacksPredicate,
    pub action: HookAction,
    pub enabled: bool,
    pub expired_at: Option<u64>,
}

impl StacksChainhookSpecification {
    pub fn key(&self) -> String {
        ChainhookSpecification::stacks_key(&self.uuid)
    }

    pub fn is_predicate_targeting_block_header(&self) -> bool {
        match &self.predicate {
            StacksPredicate::BlockHeight(_)
            // | &StacksPredicate::BitcoinBlockHeight(_)
            => true,
            _ => false,
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
#[serde(tag = "scope")]
pub enum StacksPredicate {
    BlockHeight(BlockIdentifierIndexRule),
    ContractDeployment(StacksContractDeploymentPredicate),
    ContractCall(StacksContractCallBasedPredicate),
    PrintEvent(StacksPrintEventBasedPredicate),
    FtEvent(StacksFtEventBasedPredicate),
    NftEvent(StacksNftEventBasedPredicate),
    StxEvent(StacksStxEventBasedPredicate),
    Txid(ExactMatchingRule),
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub struct StacksContractCallBasedPredicate {
    pub contract_identifier: String,
    pub method: String,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
// #[serde(tag = "type", content = "rule")]
pub enum StacksContractDeploymentPredicate {
    Deployer(String),
    ImplementTrait(StacksTrait),
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum StacksTrait {
    Sip09,
    Sip10,
    #[serde(rename = "*")]
    Any,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
#[serde(untagged)]
pub enum StacksPrintEventBasedPredicate {
    Contains {
        contract_identifier: String,
        contains: String,
    },
    MatchesRegex {
        contract_identifier: String,
        #[serde(rename = "matches_regex")]
        regex: String,
    },
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub struct StacksFtEventBasedPredicate {
    pub asset_identifier: String,
    pub actions: Vec<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub struct StacksNftEventBasedPredicate {
    pub asset_identifier: String,
    pub actions: Vec<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub struct StacksStxEventBasedPredicate {
    pub actions: Vec<String>,
}

pub fn opcode_to_hex(asm: &str) -> Option<u8> {
    match asm {
        "OP_PUSHBYTES_0" => Some(0x00),
        // Push the next byte as an array onto the stack
        "OP_PUSHBYTES_1" => Some(0x01),
        // Push the next 2 bytes as an array onto the stack
        "OP_PUSHBYTES_2" => Some(0x02),
        // Push the next 2 bytes as an array onto the stack
        "OP_PUSHBYTES_3" => Some(0x03),
        // Push the next 4 bytes as an array onto the stack
        "OP_PUSHBYTES_4" => Some(0x04),
        // Push the next 5 bytes as an array onto the stack
        "OP_PUSHBYTES_5" => Some(0x05),
        // Push the next 6 bytes as an array onto the stack
        "OP_PUSHBYTES_6" => Some(0x06),
        // Push the next 7 bytes as an array onto the stack
        "OP_PUSHBYTES_7" => Some(0x07),
        // Push the next 8 bytes as an array onto the stack
        "OP_PUSHBYTES_8" => Some(0x08),
        // Push the next 9 bytes as an array onto the stack
        "OP_PUSHBYTES_9" => Some(0x09),
        // Push the next 10 bytes as an array onto the stack
        "OP_PUSHBYTES_10" => Some(0x0a),
        // Push the next 11 bytes as an array onto the stack
        "OP_PUSHBYTES_11" => Some(0x0b),
        // Push the next 12 bytes as an array onto the stack
        "OP_PUSHBYTES_12" => Some(0x0c),
        // Push the next 13 bytes as an array onto the stack
        "OP_PUSHBYTES_13" => Some(0x0d),
        // Push the next 14 bytes as an array onto the stack
        "OP_PUSHBYTES_14" => Some(0x0e),
        // Push the next 15 bytes as an array onto the stack
        "OP_PUSHBYTES_15" => Some(0x0f),
        // Push the next 16 bytes as an array onto the stack
        "OP_PUSHBYTES_16" => Some(0x10),
        // Push the next 17 bytes as an array onto the stack
        "OP_PUSHBYTES_17" => Some(0x11),
        // Push the next 18 bytes as an array onto the stack
        "OP_PUSHBYTES_18" => Some(0x12),
        // Push the next 19 bytes as an array onto the stack
        "OP_PUSHBYTES_19" => Some(0x13),
        // Push the next 20 bytes as an array onto the stack
        "OP_PUSHBYTES_20" => Some(0x14),
        // Push the next 21 bytes as an array onto the stack
        "OP_PUSHBYTES_21" => Some(0x15),
        // Push the next 22 bytes as an array onto the stack
        "OP_PUSHBYTES_22" => Some(0x16),
        // Push the next 23 bytes as an array onto the stack
        "OP_PUSHBYTES_23" => Some(0x17),
        // Push the next 24 bytes as an array onto the stack
        "OP_PUSHBYTES_24" => Some(0x18),
        // Push the next 25 bytes as an array onto the stack
        "OP_PUSHBYTES_25" => Some(0x19),
        // Push the next 26 bytes as an array onto the stack
        "OP_PUSHBYTES_26" => Some(0x1a),
        // Push the next 27 bytes as an array onto the stack
        "OP_PUSHBYTES_27" => Some(0x1b),
        // Push the next 28 bytes as an array onto the stack
        "OP_PUSHBYTES_28" => Some(0x1c),
        // Push the next 29 bytes as an array onto the stack
        "OP_PUSHBYTES_29" => Some(0x1d),
        // Push the next 30 bytes as an array onto the stack
        "OP_PUSHBYTES_30" => Some(0x1e),
        // Push the next 31 bytes as an array onto the stack
        "OP_PUSHBYTES_31" => Some(0x1f),
        // Push the next 32 bytes as an array onto the stack
        "OP_PUSHBYTES_32" => Some(0x20),
        // Push the next 33 bytes as an array onto the stack
        "OP_PUSHBYTES_33" => Some(0x21),
        // Push the next 34 bytes as an array onto the stack
        "OP_PUSHBYTES_34" => Some(0x22),
        // Push the next 35 bytes as an array onto the stack
        "OP_PUSHBYTES_35" => Some(0x23),
        // Push the next 36 bytes as an array onto the stack
        "OP_PUSHBYTES_36" => Some(0x24),
        // Push the next 37 bytes as an array onto the stack
        "OP_PUSHBYTES_37" => Some(0x25),
        // Push the next 38 bytes as an array onto the stack
        "OP_PUSHBYTES_38" => Some(0x26),
        // Push the next 39 bytes as an array onto the stack
        "OP_PUSHBYTES_39" => Some(0x27),
        // Push the next 40 bytes as an array onto the stack
        "OP_PUSHBYTES_40" => Some(0x28),
        // Push the next 41 bytes as an array onto the stack
        "OP_PUSHBYTES_41" => Some(0x29),
        // Push the next 42 bytes as an array onto the stack
        "OP_PUSHBYTES_42" => Some(0x2a),
        // Push the next 43 bytes as an array onto the stack
        "OP_PUSHBYTES_43" => Some(0x2b),
        // Push the next 44 bytes as an array onto the stack
        "OP_PUSHBYTES_44" => Some(0x2c),
        // Push the next 45 bytes as an array onto the stack
        "OP_PUSHBYTES_45" => Some(0x2d),
        // Push the next 46 bytes as an array onto the stack
        "OP_PUSHBYTES_46" => Some(0x2e),
        // Push the next 47 bytes as an array onto the stack
        "OP_PUSHBYTES_47" => Some(0x2f),
        // Push the next 48 bytes as an array onto the stack
        "OP_PUSHBYTES_48" => Some(0x30),
        // Push the next 49 bytes as an array onto the stack
        "OP_PUSHBYTES_49" => Some(0x31),
        // Push the next 50 bytes as an array onto the stack
        "OP_PUSHBYTES_50" => Some(0x32),
        // Push the next 51 bytes as an array onto the stack
        "OP_PUSHBYTES_51" => Some(0x33),
        // Push the next 52 bytes as an array onto the stack
        "OP_PUSHBYTES_52" => Some(0x34),
        // Push the next 53 bytes as an array onto the stack
        "OP_PUSHBYTES_53" => Some(0x35),
        // Push the next 54 bytes as an array onto the stack
        "OP_PUSHBYTES_54" => Some(0x36),
        // Push the next 55 bytes as an array onto the stack
        "OP_PUSHBYTES_55" => Some(0x37),
        // Push the next 56 bytes as an array onto the stack
        "OP_PUSHBYTES_56" => Some(0x38),
        // Push the next 57 bytes as an array onto the stack
        "OP_PUSHBYTES_57" => Some(0x39),
        // Push the next 58 bytes as an array onto the stack
        "OP_PUSHBYTES_58" => Some(0x3a),
        // Push the next 59 bytes as an array onto the stack
        "OP_PUSHBYTES_59" => Some(0x3b),
        // Push the next 60 bytes as an array onto the stack
        "OP_PUSHBYTES_60" => Some(0x3c),
        // Push the next 61 bytes as an array onto the stack
        "OP_PUSHBYTES_61" => Some(0x3d),
        // Push the next 62 bytes as an array onto the stack
        "OP_PUSHBYTES_62" => Some(0x3e),
        // Push the next 63 bytes as an array onto the stack
        "OP_PUSHBYTES_63" => Some(0x3f),
        // Push the next 64 bytes as an array onto the stack
        "OP_PUSHBYTES_64" => Some(0x40),
        // Push the next 65 bytes as an array onto the stack
        "OP_PUSHBYTES_65" => Some(0x41),
        // Push the next 66 bytes as an array onto the stack
        "OP_PUSHBYTES_66" => Some(0x42),
        // Push the next 67 bytes as an array onto the stack
        "OP_PUSHBYTES_67" => Some(0x43),
        // Push the next 68 bytes as an array onto the stack
        "OP_PUSHBYTES_68" => Some(0x44),
        // Push the next 69 bytes as an array onto the stack
        "OP_PUSHBYTES_69" => Some(0x45),
        // Push the next 70 bytes as an array onto the stack
        "OP_PUSHBYTES_70" => Some(0x46),
        // Push the next 71 bytes as an array onto the stack
        "OP_PUSHBYTES_71" => Some(0x47),
        // Push the next 72 bytes as an array onto the stack
        "OP_PUSHBYTES_72" => Some(0x48),
        // Push the next 73 bytes as an array onto the stack
        "OP_PUSHBYTES_73" => Some(0x49),
        // Push the next 74 bytes as an array onto the stack
        "OP_PUSHBYTES_74" => Some(0x4a),
        // Push the next 75 bytes as an array onto the stack
        "OP_PUSHBYTES_75" => Some(0x4b),
        // Read the next byte as N; push the next N bytes as an array onto the stack
        "OP_PUSHDATA1" => Some(0x4c),
        // Read the next 2 bytes as N; push the next N bytes as an array onto the stack
        "OP_PUSHDATA2" => Some(0x4d),
        // Read the next 4 bytes as N; push the next N bytes as an array onto the stack
        "OP_PUSHDATA4" => Some(0x4e),
        // Push the array `0x81` onto the stack
        "OP_PUSHNUM_NEG1" => Some(0x4f),
        // Synonym for OP_RETURN
        "OP_RESERVED" => Some(0x50),
        // Push the number `0x01` onto the stack
        "OP_PUSHNUM_1" => Some(0x51),
        // Push the number `0x02` onto the stack
        "OP_PUSHNUM_2" => Some(0x52),
        // Push the number `0x03` onto the stack
        "OP_PUSHNUM_3" => Some(0x53),
        // Push the number `0x04` onto the stack
        "OP_PUSHNUM_4" => Some(0x54),
        // Push the number `0x05` onto the stack
        "OP_PUSHNUM_5" => Some(0x55),
        // Push the number `0x06` onto the stack
        "OP_PUSHNUM_6" => Some(0x56),
        // Push the number `0x07` onto the stack
        "OP_PUSHNUM_7" => Some(0x57),
        // Push the number `0x08` onto the stack
        "OP_PUSHNUM_8" => Some(0x58),
        // Push the number `0x09` onto the stack
        "OP_PUSHNUM_9" => Some(0x59),
        // Push the number `0x0a` onto the stack
        "OP_PUSHNUM_10" => Some(0x5a),
        // Push the number `0x0b` onto the stack
        "OP_PUSHNUM_11" => Some(0x5b),
        // Push the number `0x0c` onto the stack
        "OP_PUSHNUM_12" => Some(0x5c),
        // Push the number `0x0d` onto the stack
        "OP_PUSHNUM_13" => Some(0x5d),
        // Push the number `0x0e` onto the stack
        "OP_PUSHNUM_14" => Some(0x5e),
        // Push the number `0x0f` onto the stack
        "OP_PUSHNUM_15" => Some(0x5f),
        // Push the number `0x10` onto the stack
        "OP_PUSHNUM_16" => Some(0x60),
        // Does nothing
        "OP_NOP" => Some(0x61),
        // Synonym for OP_RETURN
        "OP_VER" => Some(0x62),
        // Pop and execute the next statements if a nonzero element was popped
        "OP_IF" => Some(0x63),
        // Pop and execute the next statements if a zero element was popped
        "OP_NOTIF" => Some(0x64),
        // Fail the script unconditionally, does not even need to be executed
        "OP_VERIF" => Some(0x65),
        // Fail the script unconditionally, does not even need to be executed
        "OP_VERNOTIF" => Some(0x66),
        // Execute statements if those after the previous OP_IF were not, and vice-versa.
        // If there is no previous OP_IF, this acts as a RETURN.
        "OP_ELSE" => Some(0x67),
        // Pop and execute the next statements if a zero element was popped
        "OP_ENDIF" => Some(0x68),
        // If the top value is zero or the stack is empty, fail; otherwise, pop the stack
        "OP_VERIFY" => Some(0x69),
        // Fail the script immediately. (Must be executed.)
        "OP_RETURN" => Some(0x6a),
        // Pop one element from the main stack onto the alt stack
        "OP_TOALTSTACK" => Some(0x6b),
        // Pop one element from the alt stack onto the main stack
        "OP_FROMALTSTACK" => Some(0x6c),
        // Drops the top two stack items
        "OP_2DROP" => Some(0x6d),
        // Duplicates the top two stack items as AB -> ABAB
        "OP_2DUP" => Some(0x6e),
        // Duplicates the two three stack items as ABC -> ABCABC
        "OP_3DUP" => Some(0x6f),
        // Copies the two stack items of items two spaces back to
        // the front, as xxAB -> ABxxAB
        "OP_2OVER" => Some(0x70),
        // Moves the two stack items four spaces back to the front,
        // as xxxxAB -> ABxxxx
        "OP_2ROT" => Some(0x71),
        // Swaps the top two pairs, as ABCD -> CDAB
        "OP_2SWAP" => Some(0x72),
        // Duplicate the top stack element unless it is zero
        "OP_IFDUP" => Some(0x73),
        // Push the current number of stack items onto the stack
        "OP_DEPTH" => Some(0x74),
        // Drops the top stack item
        "OP_DROP" => Some(0x75),
        // Duplicates the top stack item
        "OP_DUP" => Some(0x76),
        // Drops the second-to-top stack item
        "OP_NIP" => Some(0x77),
        // Copies the second-to-top stack item, as xA -> AxA
        "OP_OVER" => Some(0x78),
        // Pop the top stack element as N. Copy the Nth stack element to the top
        "OP_PICK" => Some(0x79),
        // Pop the top stack element as N. Move the Nth stack element to the top
        "OP_ROLL" => Some(0x7a),
        // Rotate the top three stack items, as [top next1 next2] -> [next2 top next1]
        "OP_ROT" => Some(0x7b),
        // Swap the top two stack items
        "OP_SWAP" => Some(0x7c),
        // Copy the top stack item to before the second item, as [top next] -> [top next top]
        "OP_TUCK" => Some(0x7d),
        // Fail the script unconditionally, does not even need to be executed
        "OP_CAT" => Some(0x7e),
        // Fail the script unconditionally, does not even need to be executed
        "OP_SUBSTR" => Some(0x7f),
        // Fail the script unconditionally, does not even need to be executed
        "OP_LEFT" => Some(0x80),
        // Fail the script unconditionally, does not even need to be executed
        "OP_RIGHT" => Some(0x81),
        // Pushes the length of the top stack item onto the stack
        "OP_SIZE" => Some(0x82),
        // Fail the script unconditionally, does not even need to be executed
        "OP_INVERT" => Some(0x83),
        // Fail the script unconditionally, does not even need to be executed
        "OP_AND" => Some(0x84),
        // Fail the script unconditionally, does not even need to be executed
        "OP_OR" => Some(0x85),
        // Fail the script unconditionally, does not even need to be executed
        "OP_XOR" => Some(0x86),
        // Pushes 1 if the inputs are exactly equal, 0 otherwise
        "OP_EQUAL" => Some(0x87),
        // Returns success if the inputs are exactly equal, failure otherwise
        "OP_EQUALVERIFY" => Some(0x88),
        // Synonym for OP_RETURN
        "OP_RESERVED1" => Some(0x89),
        // Synonym for OP_RETURN
        "OP_RESERVED2" => Some(0x8a),
        // Increment the top stack element in place
        "OP_1ADD" => Some(0x8b),
        // Decrement the top stack element in place
        "OP_1SUB" => Some(0x8c),
        // Fail the script unconditionally, does not even need to be executed
        "OP_2MUL" => Some(0x8d),
        // Fail the script unconditionally, does not even need to be executed
        "OP_2DIV" => Some(0x8e),
        // Multiply the top stack item by -1 in place
        "OP_NEGATE" => Some(0x8f),
        // Absolute value the top stack item in place
        "OP_ABS" => Some(0x90),
        // Map 0 to 1 and everything else to 0, in place
        "OP_NOT" => Some(0x91),
        // Map 0 to 0 and everything else to 1, in place
        "OP_0NOTEQUAL" => Some(0x92),
        // Pop two stack items and push their sum
        "OP_ADD" => Some(0x93),
        // Pop two stack items and push the second minus the top
        "OP_SUB" => Some(0x94),
        // Fail the script unconditionally, does not even need to be executed
        "OP_MUL" => Some(0x95),
        // Fail the script unconditionally, does not even need to be executed
        "OP_DIV" => Some(0x96),
        // Fail the script unconditionally, does not even need to be executed
        "OP_MOD" => Some(0x97),
        // Fail the script unconditionally, does not even need to be executed
        "OP_LSHIFT" => Some(0x98),
        // Fail the script unconditionally, does not even need to be executed
        "OP_RSHIFT" => Some(0x99),
        // Pop the top two stack items and push 1 if both are nonzero, else push 0
        "OP_BOOLAND" => Some(0x9a),
        // Pop the top two stack items and push 1 if either is nonzero, else push 0
        "OP_BOOLOR" => Some(0x9b),
        // Pop the top two stack items and push 1 if both are numerically equal, else push 0
        "OP_NUMEQUAL" => Some(0x9c),
        // Pop the top two stack items and return success if both are numerically equal, else return failure
        "OP_NUMEQUALVERIFY" => Some(0x9d),
        // Pop the top two stack items and push 0 if both are numerically equal, else push 1
        "OP_NUMNOTEQUAL" => Some(0x9e),
        // Pop the top two items; push 1 if the second is less than the top, 0 otherwise
        "OP_LESSTHAN" => Some(0x9f),
        // Pop the top two items; push 1 if the second is greater than the top, 0 otherwise
        "OP_GREATERTHAN" => Some(0xa0),
        // Pop the top two items; push 1 if the second is <= the top, 0 otherwise
        "OP_LESSTHANOREQUAL" => Some(0xa1),
        // Pop the top two items; push 1 if the second is >= the top, 0 otherwise
        "OP_GREATERTHANOREQUAL" => Some(0xa2),
        // Pop the top two items; push the smaller
        "OP_MIN" => Some(0xa3),
        // Pop the top two items; push the larger
        "OP_MAX" => Some(0xa4),
        // Pop the top three items; if the top is >= the second and < the third, push 1, otherwise push 0
        "OP_WITHIN" => Some(0xa5),
        // Pop the top stack item and push its RIPEMD160 hash
        "OP_RIPEMD160" => Some(0xa6),
        // Pop the top stack item and push its SHA1 hash
        "OP_SHA1" => Some(0xa7),
        // Pop the top stack item and push its SHA256 hash
        "OP_SHA256" => Some(0xa8),
        // Pop the top stack item and push its RIPEMD(SHA256) hash
        "OP_HASH160" => Some(0xa9),
        // Pop the top stack item and push its SHA256(SHA256) hash
        "OP_HASH256" => Some(0xaa),
        // Ignore this and everything preceding when deciding what to sign when signature-checking
        "OP_CODESEPARATOR" => Some(0xab),
        // <https://en.bitcoin.it/wiki/OP_CHECKSIG> pushing 1/0 for success/failure
        "OP_CHECKSIG" => Some(0xac),
        // <https://en.bitcoin.it/wiki/OP_CHECKSIG> returning success/failure
        "OP_CHECKSIGVERIFY" => Some(0xad),
        // Pop N, N pubkeys, M, M signatures, a dummy (due to bug in reference code), and verify that all M signatures are valid.
        // Push 1 for "all valid", 0 otherwise
        "OP_CHECKMULTISIG" => Some(0xae),
        // Like the above but return success/failure
        "OP_CHECKMULTISIGVERIFY" => Some(0xaf),
        // Does nothing
        "OP_NOP1" => Some(0xb0),
        // <https://github.com/bitcoin/bips/blob/master/bip-0065.mediawiki>
        "OP_CLTV" => Some(0xb1),
        // <https://github.com/bitcoin/bips/blob/master/bip-0112.mediawiki>
        "OP_CSV" => Some(0xb2),
        // Does nothing
        "OP_NOP4" => Some(0xb3),
        // Does nothing
        "OP_NOP5" => Some(0xb4),
        // Does nothing
        "OP_NOP6" => Some(0xb5),
        // Does nothing
        "OP_NOP7" => Some(0xb6),
        // Does nothing
        "OP_NOP8" => Some(0xb7),
        // Does nothing
        "OP_NOP9" => Some(0xb8),
        // Does nothing
        "OP_NOP10" => Some(0xb9),
        // Every other opcode acts as OP_RETURN
        // Synonym for OP_RETURN
        "OP_RETURN_186" => Some(0xba),
        // Synonym for OP_RETURN
        "OP_RETURN_187" => Some(0xbb),
        // Synonym for OP_RETURN
        "OP_RETURN_188" => Some(0xbc),
        // Synonym for OP_RETURN
        "OP_RETURN_189" => Some(0xbd),
        // Synonym for OP_RETURN
        "OP_RETURN_190" => Some(0xbe),
        // Synonym for OP_RETURN
        "OP_RETURN_191" => Some(0xbf),
        // Synonym for OP_RETURN
        "OP_RETURN_192" => Some(0xc0),
        // Synonym for OP_RETURN
        "OP_RETURN_193" => Some(0xc1),
        // Synonym for OP_RETURN
        "OP_RETURN_194" => Some(0xc2),
        // Synonym for OP_RETURN
        "OP_RETURN_195" => Some(0xc3),
        // Synonym for OP_RETURN
        "OP_RETURN_196" => Some(0xc4),
        // Synonym for OP_RETURN
        "OP_RETURN_197" => Some(0xc5),
        // Synonym for OP_RETURN
        "OP_RETURN_198" => Some(0xc6),
        // Synonym for OP_RETURN
        "OP_RETURN_199" => Some(0xc7),
        // Synonym for OP_RETURN
        "OP_RETURN_200" => Some(0xc8),
        // Synonym for OP_RETURN
        "OP_RETURN_201" => Some(0xc9),
        // Synonym for OP_RETURN
        "OP_RETURN_202" => Some(0xca),
        // Synonym for OP_RETURN
        "OP_RETURN_203" => Some(0xcb),
        // Synonym for OP_RETURN
        "OP_RETURN_204" => Some(0xcc),
        // Synonym for OP_RETURN
        "OP_RETURN_205" => Some(0xcd),
        // Synonym for OP_RETURN
        "OP_RETURN_206" => Some(0xce),
        // Synonym for OP_RETURN
        "OP_RETURN_207" => Some(0xcf),
        // Synonym for OP_RETURN
        "OP_RETURN_208" => Some(0xd0),
        // Synonym for OP_RETURN
        "OP_RETURN_209" => Some(0xd1),
        // Synonym for OP_RETURN
        "OP_RETURN_210" => Some(0xd2),
        // Synonym for OP_RETURN
        "OP_RETURN_211" => Some(0xd3),
        // Synonym for OP_RETURN
        "OP_RETURN_212" => Some(0xd4),
        // Synonym for OP_RETURN
        "OP_RETURN_213" => Some(0xd5),
        // Synonym for OP_RETURN
        "OP_RETURN_214" => Some(0xd6),
        // Synonym for OP_RETURN
        "OP_RETURN_215" => Some(0xd7),
        // Synonym for OP_RETURN
        "OP_RETURN_216" => Some(0xd8),
        // Synonym for OP_RETURN
        "OP_RETURN_217" => Some(0xd9),
        // Synonym for OP_RETURN
        "OP_RETURN_218" => Some(0xda),
        // Synonym for OP_RETURN
        "OP_RETURN_219" => Some(0xdb),
        // Synonym for OP_RETURN
        "OP_RETURN_220" => Some(0xdc),
        // Synonym for OP_RETURN
        "OP_RETURN_221" => Some(0xdd),
        // Synonym for OP_RETURN
        "OP_RETURN_222" => Some(0xde),
        // Synonym for OP_RETURN
        "OP_RETURN_223" => Some(0xdf),
        // Synonym for OP_RETURN
        "OP_RETURN_224" => Some(0xe0),
        // Synonym for OP_RETURN
        "OP_RETURN_225" => Some(0xe1),
        // Synonym for OP_RETURN
        "OP_RETURN_226" => Some(0xe2),
        // Synonym for OP_RETURN
        "OP_RETURN_227" => Some(0xe3),
        // Synonym for OP_RETURN
        "OP_RETURN_228" => Some(0xe4),
        // Synonym for OP_RETURN
        "OP_RETURN_229" => Some(0xe5),
        // Synonym for OP_RETURN
        "OP_RETURN_230" => Some(0xe6),
        // Synonym for OP_RETURN
        "OP_RETURN_231" => Some(0xe7),
        // Synonym for OP_RETURN
        "OP_RETURN_232" => Some(0xe8),
        // Synonym for OP_RETURN
        "OP_RETURN_233" => Some(0xe9),
        // Synonym for OP_RETURN
        "OP_RETURN_234" => Some(0xea),
        // Synonym for OP_RETURN
        "OP_RETURN_235" => Some(0xeb),
        // Synonym for OP_RETURN
        "OP_RETURN_236" => Some(0xec),
        // Synonym for OP_RETURN
        "OP_RETURN_237" => Some(0xed),
        // Synonym for OP_RETURN
        "OP_RETURN_238" => Some(0xee),
        // Synonym for OP_RETURN
        "OP_RETURN_239" => Some(0xef),
        // Synonym for OP_RETURN
        "OP_RETURN_240" => Some(0xf0),
        // Synonym for OP_RETURN
        "OP_RETURN_241" => Some(0xf1),
        // Synonym for OP_RETURN
        "OP_RETURN_242" => Some(0xf2),
        // Synonym for OP_RETURN
        "OP_RETURN_243" => Some(0xf3),
        // Synonym for OP_RETURN
        "OP_RETURN_244" => Some(0xf4),
        // Synonym for OP_RETURN
        "OP_RETURN_245" => Some(0xf5),
        // Synonym for OP_RETURN
        "OP_RETURN_246" => Some(0xf6),
        // Synonym for OP_RETURN
        "OP_RETURN_247" => Some(0xf7),
        // Synonym for OP_RETURN
        "OP_RETURN_248" => Some(0xf8),
        // Synonym for OP_RETURN
        "OP_RETURN_249" => Some(0xf9),
        // Synonym for OP_RETURN
        "OP_RETURN_250" => Some(0xfa),
        // Synonym for OP_RETURN
        "OP_RETURN_251" => Some(0xfb),
        // Synonym for OP_RETURN
        "OP_RETURN_252" => Some(0xfc),
        // Synonym for OP_RETURN
        "OP_RETURN_253" => Some(0xfd),
        // Synonym for OP_RETURN
        "OP_RETURN_254" => Some(0xfe),
        // Synonym for OP_RETURN
        "OP_RETURN_255" => Some(0xff),
        _ => None,
    }
}