-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathcompiler.rs
More file actions
2793 lines (2528 loc) · 109 KB
/
compiler.rs
File metadata and controls
2793 lines (2528 loc) · 109 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use bitcoin::bip152::HeaderAndShortIds;
use bitcoin::{
Amount, Block, CompactTarget, EcdsaSighashType, NetworkKind, OutPoint, PrivateKey, Script,
ScriptBuf, Sequence, Transaction, TxIn, TxMerkleNode, TxOut, Txid, WitnessMerkleNode, Wtxid,
absolute::LockTime,
consensus::Encodable,
ecdsa,
hashes::{Hash, serde_macros::serde_details::SerdeHash, sha256},
key::{Secp256k1, TapTweak},
opcodes::{
OP_0, OP_TRUE,
all::{OP_PUSHNUM_1, OP_RETURN},
},
p2p::{
ServiceFlags,
address::{AddrV2, AddrV2Message, Address},
message_blockdata::Inventory,
message_bloom::{BloomFlags, FilterAdd, FilterLoad},
message_compact_blocks::CmpctBlock,
message_filter::{GetCFCheckpt, GetCFHeaders, GetCFilters},
},
script::PushBytesBuf,
secp256k1::{self, Keypair, SecretKey},
sighash::{Prevouts, SighashCache, TapSighashType},
taproot::{LeafVersion, NodeInfo, TapLeafHash, TapNodeHash},
transaction,
};
use std::collections::HashMap;
use std::{any::Any, convert::TryInto, time::Duration};
use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
use crate::{
AddrNetwork, AddrRecord, Instruction, Operation, Program, TaprootKeypair, TaprootLeaf,
TaprootSpendInfo, bloom::filter_insert, generators::block::Header,
};
/// `Compiler` is responsible for compiling IR into a sequence of low-level actions to be performed
/// on a node (i.e. mapping `fuzzamoto_ir::Program` -> `CompiledProgram`).
pub struct Compiler {
secp_ctx: Secp256k1<bitcoin::secp256k1::All>,
variables: Vec<Box<dyn Any>>,
output: CompiledProgram,
connection_counter: usize,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
pub enum CompiledAction {
/// Create a new connection
Connect(usize, String),
/// Create a new connection and perform a version handshake
ConnectAndHandshake {
node: usize,
connection_type: String,
relay: bool,
starting_height: i32,
wtxidrelay: bool,
addrv2: bool,
erlay: bool,
time: u64,
send_compact: Option<bool>,
},
/// Send a message on one of the connections
SendRawMessage(usize, String, Vec<u8>),
/// Set mock time for all nodes in the test
SetTime(u64),
Probe,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
pub struct CompiledProgram {
pub actions: Vec<CompiledAction>,
pub metadata: CompiledMetadata,
}
pub type VariableIndex = usize;
pub type InstructionIndex = usize;
pub type ConnectionId = usize;
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
pub struct CompiledMetadata {
// Map from blockhash to (header_var, block_var, block_transactions_var, tx_var_indices)
block_tx_var_map: HashMap<bitcoin::BlockHash, (usize, usize, usize, Vec<usize>)>,
// Map from connection ids to connection variable indices.
connection_map: HashMap<ConnectionId, VariableIndex>,
// List of instruction indices that correspond to actions in the compiled program (does not include probe operation)
action_indices: Vec<InstructionIndex>,
// A vector representing where each variable is defined.
variable_indices: Vec<InstructionIndex>,
/// The number of non-probe instructions compiled
instructions: usize,
}
impl Default for CompiledMetadata {
fn default() -> Self {
Self::new()
}
}
impl CompiledMetadata {
#[must_use]
pub fn new() -> Self {
Self {
block_tx_var_map: HashMap::new(),
connection_map: HashMap::new(),
action_indices: Vec::new(),
variable_indices: Vec::new(),
instructions: 0,
}
}
/// Get the header var index, block var index, `block_transactions` var index, and list of
/// transaction variable indices for a given block hash.
#[must_use]
pub fn block_variables(
&self,
block_hash: &bitcoin::BlockHash,
) -> Option<(usize, usize, usize, &[usize])> {
self.block_tx_var_map.get(block_hash).map(
|(header_var, block_var, block_txs_var, tx_vars)| {
(*header_var, *block_var, *block_txs_var, tx_vars.as_slice())
},
)
}
/// Look up a block by its block variable index, returning the `block_transactions` var index
/// and the list of transaction variable indices that belong to it.
#[must_use]
pub fn block_vars_by_block_index(&self, block_var_index: usize) -> Option<(usize, &[usize])> {
self.block_tx_var_map
.values()
.find(|(_, block_var, _, _)| *block_var == block_var_index)
.map(|(_, _, block_txs_var, tx_vars)| (*block_txs_var, tx_vars.as_slice()))
}
// Get the list of instruction indices that correspond to actions in the compiled program
#[must_use]
pub fn instruction_indices(&self) -> &[InstructionIndex] {
&self.action_indices
}
// Get the list of instruction indices that correspond to variables in the compiled program
#[must_use]
pub fn variable_indices(&self) -> &[InstructionIndex] {
&self.variable_indices
}
#[must_use]
pub fn connection_map(&self) -> &HashMap<ConnectionId, VariableIndex> {
&self.connection_map
}
}
#[derive(Debug)]
pub enum CompilerError {
MiscError(String),
IncorrectNumberOfInputs,
VariableNotFound,
IncorrectVariableType,
}
impl std::fmt::Display for CompilerError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
CompilerError::MiscError(e) => write!(f, "Misc error: {e}"),
CompilerError::IncorrectNumberOfInputs => write!(f, "Incorrect number of inputs"),
CompilerError::VariableNotFound => write!(f, "Variable not found"),
CompilerError::IncorrectVariableType => write!(f, "Incorrect variable type"),
}
}
}
pub type CompilerResult = Result<CompiledProgram, CompilerError>;
#[derive(Clone, Debug)]
struct Scripts {
script_pubkey: Vec<u8>,
script_sig: Vec<u8>,
witness: Witness,
requires_signing: Option<SigningRequest>,
}
#[derive(Debug, Clone)]
enum SigningRequest {
Legacy {
operation: Operation,
private_key_var: usize,
sighash_var: usize,
},
Taproot {
spend_info_var: Option<usize>,
selected_leaf: Option<TaprootLeaf>,
annex_var: Option<usize>,
},
}
#[derive(Debug, Clone)]
struct Witness {
stack: Vec<Vec<u8>>,
}
fn build_control_block(
spend_info: &TaprootSpendInfo,
leaf: &TaprootLeaf,
annex_present: bool,
) -> Vec<u8> {
let mut control =
Vec::with_capacity(1 + spend_info.keypair.public_key.len() + 32 * leaf.merkle_branch.len());
let parity = spend_info.output_key_parity & 1;
let mut first_byte = leaf.version | parity;
if annex_present {
first_byte |= 0b10;
}
control.push(first_byte);
control.extend_from_slice(&spend_info.keypair.public_key);
for hash in &leaf.merkle_branch {
control.extend_from_slice(hash);
}
control
}
#[derive(Clone, Debug)]
struct Txo {
prev_out: ([u8; 32], u32),
scripts: Scripts,
value: u64,
}
impl Txo {
pub fn new() -> Self {
Self {
prev_out: ([0u8; 32], 0),
scripts: Scripts {
script_pubkey: Vec::new(),
script_sig: Vec::new(),
witness: Witness { stack: Vec::new() },
requires_signing: None,
},
value: 0,
}
}
}
#[derive(Clone)]
struct TxOutputs {
outputs: Vec<(Scripts, u64)>,
fees: u64,
}
#[derive(Clone)]
struct TxInput {
txo_var: usize,
sequence_var: usize,
}
#[derive(Clone)]
struct TxInputs {
inputs: Vec<TxInput>,
total_value: u64,
}
#[derive(Clone, Debug)]
struct Tx {
tx: Transaction,
txos: Vec<Txo>,
output_selector: usize,
id: Txid,
}
#[derive(Clone)]
struct CoinbaseInput {
sequence: usize,
total_value: u64,
}
#[derive(Clone)]
struct CoinbaseTx {
tx: Tx,
scripts: Vec<Scripts>,
}
#[derive(Clone, Debug)]
struct BlockTransactions {
txs: Vec<Tx>,
var_indices: Vec<usize>,
}
#[derive(Clone, Debug)]
struct PrefillTransactions {
indices: Vec<usize>,
}
#[derive(Clone, Debug)]
struct AddrList {
entries: Vec<(u32, Address)>,
}
#[derive(Clone, Debug)]
struct AddrListV2 {
entries: Vec<AddrV2Message>,
}
#[derive(Clone, Debug)]
struct HandshakeOpts {
relay: bool,
starting_height: i32,
wtxidrelay: bool,
addrv2: bool,
erlay: bool,
}
struct Nop;
impl Default for Compiler {
fn default() -> Self {
Self::new()
}
}
impl Compiler {
pub fn compile(&mut self, ir: &Program) -> CompilerResult {
let probing_insts = ir
.instructions
.iter()
.filter(|inst| matches!(inst.operation, Operation::Probe))
.count();
assert!(probing_insts <= 1);
let is_probing = probing_insts > 0;
if is_probing {
assert!(matches!(
ir.instructions.first().unwrap().operation,
Operation::Probe
));
}
self.connection_counter = ir.context.num_connections;
for instruction in &ir.instructions {
let actions_before = self
.output
.actions
.iter()
.filter(|action| !matches!(action, CompiledAction::Probe))
.count();
match instruction.operation.clone() {
Operation::Nop { .. }
| Operation::LoadNode(..)
| Operation::LoadConnection(..)
| Operation::LoadConnectionType(..)
| Operation::LoadDuration(..)
| Operation::LoadAddr(..)
| Operation::LoadAmount(..)
| Operation::LoadTxVersion(..)
| Operation::LoadBlockVersion(..)
| Operation::LoadLockTime(..)
| Operation::LoadSequence(..)
| Operation::LoadTime(..)
| Operation::LoadBlockHeight(..)
| Operation::LoadCompactFilterType(..)
| Operation::LoadMsgType(..)
| Operation::LoadBytes(..)
| Operation::LoadSize(..)
| Operation::LoadPrivateKey(..)
| Operation::LoadSigHashFlags(..)
| Operation::LoadHeader { .. }
| Operation::LoadTxo { .. }
| Operation::LoadTaprootAnnex { .. }
| Operation::LoadFilterLoad { .. }
| Operation::LoadFilterAdd { .. }
| Operation::LoadHandshakeOpts { .. }
| Operation::LoadNonce(..) => {
self.handle_load_operations(instruction);
}
Operation::TaprootScriptsUseAnnex | Operation::TaprootTxoUseAnnex => {
self.handle_taproot_conversions(instruction)?;
}
Operation::BuildTaprootTree { .. } => {
self.handle_build_taproot_tree(instruction)?;
}
Operation::BeginBlockTransactions
| Operation::AddTx
| Operation::EndBlockTransactions
| Operation::BuildBlock => {
self.handle_block_building_operations(instruction)?;
}
Operation::BeginBuildInventory
| Operation::EndBuildInventory
| Operation::AddTxidWithWitnessInv
| Operation::AddWtxidInv
| Operation::AddTxidInv
| Operation::AddCompactBlockInv
| Operation::AddBlockInv
| Operation::AddBlockWithWitnessInv
| Operation::AddFilteredBlockInv => {
self.handle_inventory_operations(instruction)?;
}
Operation::BeginBuildAddrList
| Operation::BeginBuildAddrListV2
| Operation::EndBuildAddrList
| Operation::EndBuildAddrListV2
| Operation::AddAddr
| Operation::AddAddrV2 => {
self.handle_addr_operations(instruction)?;
}
Operation::BeginWitnessStack
| Operation::AddWitness
| Operation::EndWitnessStack => {
self.handle_witness_operations(instruction)?;
}
Operation::BuildPayToWitnessScriptHash
| Operation::BuildPayToScriptHash
| Operation::BuildPayToAnchor
| Operation::BuildRawScripts
| Operation::BuildOpReturnScripts
| Operation::BuildPayToPubKey
| Operation::BuildPayToPubKeyHash
| Operation::BuildPayToWitnessPubKeyHash
| Operation::BuildPayToTaproot => {
self.handle_script_building_operations(instruction)?;
}
Operation::BuildFilterAddFromTx
| Operation::BuildFilterAddFromTxo
| Operation::AddTxToFilter
| Operation::AddTxoToFilter
| Operation::BeginBuildFilterLoad
| Operation::EndBuildFilterLoad => {
self.handle_filter_building_operations(instruction)?;
}
Operation::BeginBuildTx
| Operation::EndBuildTx
| Operation::BeginBuildTxInputs
| Operation::EndBuildTxInputs
| Operation::AddTxInput
| Operation::BeginBuildTxOutputs
| Operation::EndBuildTxOutputs
| Operation::AddTxOutput
| Operation::TakeTxo
| Operation::TakeCoinbaseTxo => {
self.handle_transaction_building_operations(instruction)?;
}
Operation::BeginBuildCoinbaseTx
| Operation::EndBuildCoinbaseTx
| Operation::BuildCoinbaseTxInput
| Operation::BeginBuildCoinbaseTxOutputs
| Operation::EndBuildCoinbaseTxOutputs
| Operation::AddCoinbaseTxOutput => {
self.handle_coinbase_building_operations(instruction)?;
}
Operation::AdvanceTime | Operation::SetTime => {
self.handle_time_operations(instruction)?;
}
Operation::BeginBuildBlockTxn
| Operation::EndBuildBlockTxn
| Operation::AddTxToBlockTxn => {
self.handle_bip152_blocktxn_operations(instruction)?;
}
Operation::AddConnection | Operation::AddConnectionWithHandshake { .. } => {
self.handle_new_connection_operations(instruction)?;
}
Operation::BeginPrefillTransactions
| Operation::AddPrefillTx
| Operation::EndPrefillTransactions
| Operation::BuildCompactBlockWithPrefill => {
self.handle_prefill_building_operations(instruction)?;
}
Operation::SendRawMessage
| Operation::SendTxNoWit
| Operation::SendTx
| Operation::SendGetData
| Operation::SendInv
| Operation::SendGetAddr
| Operation::SendAddr
| Operation::SendAddrV2
| Operation::SendHeader
| Operation::SendBlock
| Operation::SendBlockNoWit
| Operation::SendGetCFilters
| Operation::SendGetCFHeaders
| Operation::SendGetCFCheckpt
| Operation::SendFilterLoad
| Operation::SendFilterAdd
| Operation::SendFilterClear
| Operation::SendCompactBlock
| Operation::SendBlockTxn => {
self.handle_message_sending_operations(instruction)?;
}
Operation::Probe => {
self.handle_probe_operations(instruction);
}
}
// Record the instruction index for each action emitted by this instruction
let actions_after = self
.output
.actions
.iter()
.filter(|action| !matches!(action, CompiledAction::Probe))
.count();
for _ in actions_before..actions_after {
self.output
.metadata
.action_indices
.push(self.output.metadata.instructions);
}
if !matches!(instruction.operation, Operation::Probe) {
self.output.metadata.instructions += 1;
}
}
Ok(self.output.clone()) // TODO: do not clone
}
#[must_use]
pub fn new() -> Self {
Self {
// TODO: make this deterministic
secp_ctx: Secp256k1::new(),
variables: Vec::with_capacity(4096),
output: CompiledProgram {
actions: Vec::with_capacity(4096),
metadata: CompiledMetadata::new(),
},
connection_counter: 0,
}
}
fn update_connection_map(
&mut self,
connection_id: ConnectionId,
connection_var_index: VariableIndex,
) {
self.output
.metadata
.connection_map
.entry(connection_id)
.or_insert(connection_var_index);
}
fn handle_load_operation<T: 'static>(&mut self, value: T) {
self.append_variable(value);
}
fn handle_inventory_operations(
&mut self,
instruction: &Instruction,
) -> Result<(), CompilerError> {
match &instruction.operation {
Operation::BeginBuildInventory => {
self.append_variable(Vec::<Inventory>::new());
}
Operation::EndBuildInventory => {
let bytes_var = self
.get_input::<Vec<Inventory>>(&instruction.inputs, 0)?
.clone();
self.append_variable(bytes_var.clone());
}
Operation::AddTxidWithWitnessInv => {
let tx_var = self.get_input::<Tx>(&instruction.inputs, 1)?;
let inv = Inventory::WitnessTransaction(tx_var.tx.compute_txid());
let inventory_var = self.get_input_mut::<Vec<Inventory>>(&instruction.inputs, 0)?;
inventory_var.push(inv);
}
Operation::AddWtxidInv => {
let tx_var = self.get_input::<Tx>(&instruction.inputs, 1)?;
let inv = Inventory::WTx(tx_var.tx.compute_wtxid());
let inventory_var = self.get_input_mut::<Vec<Inventory>>(&instruction.inputs, 0)?;
inventory_var.push(inv);
}
Operation::AddTxidInv => {
let tx_var = self.get_input::<Tx>(&instruction.inputs, 1)?;
let inv = Inventory::Transaction(tx_var.tx.compute_txid());
let inventory_var = self.get_input_mut::<Vec<Inventory>>(&instruction.inputs, 0)?;
inventory_var.push(inv);
}
Operation::AddCompactBlockInv => {
let block_var = self.get_input::<bitcoin::Block>(&instruction.inputs, 1)?;
let inv = Inventory::CompactBlock(block_var.header.block_hash());
let inventory_var = self.get_input_mut::<Vec<Inventory>>(&instruction.inputs, 0)?;
inventory_var.push(inv);
}
Operation::AddBlockInv => {
let block_var = self.get_input::<bitcoin::Block>(&instruction.inputs, 1)?;
let inv = Inventory::Block(block_var.header.block_hash());
let inventory_var = self.get_input_mut::<Vec<Inventory>>(&instruction.inputs, 0)?;
inventory_var.push(inv);
}
Operation::AddBlockWithWitnessInv => {
let block_var = self.get_input::<bitcoin::Block>(&instruction.inputs, 1)?;
let inv = Inventory::WitnessBlock(block_var.header.block_hash());
let inventory_var = self.get_input_mut::<Vec<Inventory>>(&instruction.inputs, 0)?;
inventory_var.push(inv);
}
Operation::AddFilteredBlockInv => {
let block_var = self.get_input::<bitcoin::Block>(&instruction.inputs, 1)?;
let inv = Inventory::Unknown {
inv_type: 3, // MSG_FILTERED_BLOCK, see Bitcoin Core
hash: *block_var.header.block_hash().as_byte_array(),
};
let inventory_var = self.get_input_mut::<Vec<Inventory>>(&instruction.inputs, 0)?;
inventory_var.push(inv);
}
_ => unreachable!("Non-inventory operation passed to handle_inventory_operations"),
}
Ok(())
}
fn handle_addr_operations(&mut self, instruction: &Instruction) -> Result<(), CompilerError> {
match &instruction.operation {
Operation::BeginBuildAddrList => {
self.append_variable(AddrList {
entries: Vec::new(),
});
}
Operation::BeginBuildAddrListV2 => {
self.append_variable(AddrListV2 {
entries: Vec::new(),
});
}
Operation::AddAddr => {
let record = self.get_input::<AddrRecord>(&instruction.inputs, 1)?;
let addr_tuple = match record {
AddrRecord::V1 { .. } => Compiler::addr_v1_to_network_address(record),
AddrRecord::V2 { .. } => {
return Err(CompilerError::MiscError(
"AddAddr expects an addr (v1) record".to_string(),
));
}
};
let list = self.get_input_mut::<AddrList>(&instruction.inputs, 0)?;
list.entries.push(addr_tuple);
}
Operation::AddAddrV2 => {
let record = self.get_input::<AddrRecord>(&instruction.inputs, 1)?;
let entry = Compiler::addr_v2_to_message(record)?;
let list = self.get_input_mut::<AddrListV2>(&instruction.inputs, 0)?;
list.entries.push(entry);
}
Operation::EndBuildAddrList => {
let list = self.get_input::<AddrList>(&instruction.inputs, 0)?;
self.append_variable(list.entries.clone());
}
Operation::EndBuildAddrListV2 => {
let list = self.get_input::<AddrListV2>(&instruction.inputs, 0)?;
self.append_variable(list.entries.clone());
}
_ => unreachable!("Non-address operation passed to handle_addr_operations"),
}
Ok(())
}
fn addr_v1_to_network_address(record: &AddrRecord) -> (u32, Address) {
let (time, services, ip, port) = match record {
AddrRecord::V1 {
time,
services,
ip,
port,
} => (*time, *services, *ip, *port),
AddrRecord::V2 { .. } => unreachable!("caller filtered non-V1 record"),
};
let ipv6 = Ipv6Addr::from(ip);
let socket = if let Some(ipv4) = ipv6.to_ipv4() {
SocketAddr::V4(SocketAddrV4::new(ipv4, port))
} else {
SocketAddr::V6(SocketAddrV6::new(ipv6, port, 0, 0))
};
let services = Compiler::service_flags_from_bits(services);
(time, Address::new(&socket, services))
}
fn addr_v2_to_message(record: &AddrRecord) -> Result<AddrV2Message, CompilerError> {
let (time, services_bits, network, payload, port) = match record {
AddrRecord::V2 {
time,
services,
network,
payload,
port,
} => (*time, *services, network.clone(), payload.clone(), *port),
AddrRecord::V1 { .. } => {
return Err(CompilerError::MiscError(
"AddAddrV2 expects an addr v2 record".to_string(),
));
}
};
let services = Compiler::service_flags_from_bits(services_bits);
if matches!(network, AddrNetwork::TorV2) {
return Err(CompilerError::MiscError(
"BIP-0155 forbids gossiping torv2 addresses".to_string(),
));
}
if let Some(expected) = network.expected_payload_len() {
if payload.len() != expected {
return Err(CompilerError::MiscError(format!(
"addrv2 payload length {} for {} (expected {} per BIP-0155)",
payload.len(),
network,
expected
)));
}
} else if payload.len() > 512 {
return Err(CompilerError::MiscError(format!(
"addrv2 payload length {} exceeds 512-byte limit per BIP-0155",
payload.len()
)));
}
let addr = match network {
AddrNetwork::IPv4 => {
let octets: [u8; 4] = payload.as_slice().try_into().expect("length checked");
AddrV2::Ipv4(Ipv4Addr::from(octets))
}
AddrNetwork::IPv6 => {
let octets: [u8; 16] = payload.as_slice().try_into().expect("length checked");
AddrV2::Ipv6(Ipv6Addr::from(octets))
}
AddrNetwork::TorV2 => unreachable!("torv2 records rejected above"),
AddrNetwork::TorV3 => {
let bytes: [u8; 32] = payload.as_slice().try_into().expect("length checked");
AddrV2::TorV3(bytes)
}
AddrNetwork::I2p => {
let bytes: [u8; 32] = payload.as_slice().try_into().expect("length checked");
AddrV2::I2p(bytes)
}
AddrNetwork::Cjdns => {
let octets: [u8; 16] = payload.as_slice().try_into().expect("length checked");
AddrV2::Cjdns(Ipv6Addr::from(octets))
}
AddrNetwork::Yggdrasil => AddrV2::Unknown(AddrNetwork::Yggdrasil.id(), payload.clone()),
AddrNetwork::Unknown(id) => AddrV2::Unknown(id, payload.clone()),
};
Ok(AddrV2Message {
time,
services,
addr,
port,
})
}
fn service_flags_from_bits(bits: u64) -> ServiceFlags {
let mut flags = ServiceFlags::NONE;
for candidate in [
ServiceFlags::NETWORK,
ServiceFlags::GETUTXO,
ServiceFlags::BLOOM,
ServiceFlags::WITNESS,
ServiceFlags::COMPACT_FILTERS,
ServiceFlags::NETWORK_LIMITED,
ServiceFlags::P2P_V2,
] {
if bits & candidate.to_u64() != 0 {
flags.add(candidate);
}
}
flags
}
fn handle_witness_operations(
&mut self,
instruction: &Instruction,
) -> Result<(), CompilerError> {
match &instruction.operation {
Operation::BeginWitnessStack => {
self.append_variable(Witness { stack: Vec::new() });
}
Operation::AddWitness => {
let bytes_var = self.get_input::<Vec<u8>>(&instruction.inputs, 1)?.clone();
let witness_var = self.get_input_mut::<Witness>(&instruction.inputs, 0)?;
witness_var.stack.push(bytes_var);
}
Operation::EndWitnessStack => {
let witness_var = self.get_input::<Witness>(&instruction.inputs, 0)?;
self.append_variable(witness_var.clone());
}
_ => unreachable!("Non-witness operation passed to handle_witness_operations"),
}
Ok(())
}
fn handle_filter_building_operations(
&mut self,
instruction: &Instruction,
) -> Result<(), CompilerError> {
match &instruction.operation {
Operation::BeginBuildFilterLoad | Operation::EndBuildFilterLoad => {
let filter = self
.get_input::<FilterLoad>(&instruction.inputs, 0)?
.clone();
self.append_variable(filter);
}
Operation::AddTxToFilter => {
let tx_as_array = self
.get_input::<Tx>(&instruction.inputs, 1)?
.id
.as_raw_hash()
.as_byte_array()
.to_vec();
let mut_filter = self.get_input_mut::<FilterLoad>(&instruction.inputs, 0)?;
let n_hash_funcs = mut_filter.hash_funcs;
filter_insert(&mut mut_filter.filter, n_hash_funcs, &tx_as_array);
}
Operation::AddTxoToFilter => {
let txo = self.get_input::<Txo>(&instruction.inputs, 1)?.prev_out.0;
let mut_filter = self.get_input_mut::<FilterLoad>(&instruction.inputs, 0)?;
let n_hash_funcs = mut_filter.hash_funcs;
filter_insert(&mut mut_filter.filter, n_hash_funcs, &txo);
}
Operation::BuildFilterAddFromTx => {
let tx = self.get_input::<Tx>(&instruction.inputs, 0)?;
let filteradd = FilterAdd {
data: tx.id.as_raw_hash().as_byte_array().to_vec(),
};
self.append_variable(filteradd);
}
Operation::BuildFilterAddFromTxo => {
let txo = self.get_input::<Txo>(&instruction.inputs, 0)?;
let filteradd = FilterAdd {
data: txo.scripts.script_pubkey.clone(),
};
self.append_variable(filteradd);
}
_ => unreachable!(
"Non-filter-building operation passed to handle_filter_building_operations"
),
}
Ok(())
}
fn handle_taproot_conversions(
&mut self,
instruction: &Instruction,
) -> Result<(), CompilerError> {
match &instruction.operation {
Operation::TaprootScriptsUseAnnex => {
let mut scripts = self.get_input::<Scripts>(&instruction.inputs, 0)?.clone();
let annex_var = instruction
.inputs
.get(1)
.copied()
.ok_or(CompilerError::IncorrectNumberOfInputs)?;
self.get_input::<Vec<u8>>(&instruction.inputs, 1)?;
match &mut scripts.requires_signing {
Some(SigningRequest::Taproot {
annex_var: target, ..
}) => {
*target = Some(annex_var);
}
_ => {
return Err(CompilerError::MiscError(
"TaprootScriptsUseAnnex requires a taproot script".to_string(),
));
}
}
self.append_variable(scripts);
}
Operation::TaprootTxoUseAnnex => {
let mut txo = self.get_input::<Txo>(&instruction.inputs, 0)?.clone();
let annex_var = instruction
.inputs
.get(1)
.copied()
.ok_or(CompilerError::IncorrectNumberOfInputs)?;
self.get_input::<Vec<u8>>(&instruction.inputs, 1)?;
match &mut txo.scripts.requires_signing {
Some(SigningRequest::Taproot {
annex_var: target, ..
}) => {
*target = Some(annex_var);
}
_ => {
return Err(CompilerError::MiscError(
"TaprootTxoUseAnnex requires a taproot script".to_string(),
));
}
}
self.append_variable(txo);
}
_ => unreachable!("Unsupported taproot helper"),
}
Ok(())
}
fn handle_build_taproot_tree(
&mut self,
instruction: &Instruction,
) -> Result<(), CompilerError> {
let Operation::BuildTaprootTree {
secret_key,
script_leaf,
} = &instruction.operation
else {
unreachable!("Expected BuildTaprootTree operation");
};
// Create keypair from secret_key
let sk = SecretKey::from_slice(secret_key)
.map_err(|_| CompilerError::MiscError("invalid taproot secret key".to_string()))?;
let keypair_internal = Keypair::from_secret_key(&self.secp_ctx, &sk);
let (xonly, _) = keypair_internal.x_only_public_key();
let keypair = TaprootKeypair {
secret_key: sk.secret_bytes(),
public_key: xonly.serialize(),
};
let internal_key = xonly;
// Key-path only spend
if script_leaf.is_none() {
let spend_info = bitcoin::taproot::TaprootSpendInfo::new_key_spend(
&self.secp_ctx,
internal_key,
None,
);
let output_key_bytes = spend_info.output_key().to_x_only_public_key().serialize();
let push_bytes = PushBytesBuf::try_from(output_key_bytes.to_vec()).map_err(|_| {
CompilerError::MiscError("failed to encode taproot key bytes".to_string())
})?;
let script_pubkey = ScriptBuf::builder()
.push_opcode(OP_PUSHNUM_1)
.push_slice(&push_bytes)
.into_script();
self.append_variable(TaprootSpendInfo {
keypair,
merkle_root: None,
output_key: output_key_bytes,
output_key_parity: match spend_info.output_key_parity() {
secp256k1::Parity::Even => 0,
secp256k1::Parity::Odd => 1,
},
script_pubkey: script_pubkey.as_bytes().to_vec(),
leaves: Vec::new(),
selected_leaf: None,
});
return Ok(());
}
// Script-path spend with one leaf and merkle path
let leaf = script_leaf.as_ref().unwrap();
let version = LeafVersion::from_consensus(leaf.version).map_err(|e| {
CompilerError::MiscError(format!("invalid taproot leaf version: {e:?}"))
})?;
let script_buf = ScriptBuf::from(leaf.script.clone());
let mut node = NodeInfo::new_leaf_with_ver(script_buf.clone(), version);
for hash_bytes in &leaf.merkle_path {
let hash = TapNodeHash::from_slice(hash_bytes).map_err(|_| {
CompilerError::MiscError("invalid taproot merkle path hash".to_string())
})?;
node = NodeInfo::combine(node, NodeInfo::new_hidden_node(hash)).map_err(|e| {
CompilerError::MiscError(format!("failed to build taproot node: {e:?}"))
})?;
}
let spend_info =
bitcoin::taproot::TaprootSpendInfo::from_node_info(&self.secp_ctx, internal_key, node);
let output_key_bytes = spend_info.output_key().to_x_only_public_key().serialize();
let push_bytes = PushBytesBuf::try_from(output_key_bytes.to_vec()).map_err(|_| {
CompilerError::MiscError("failed to encode taproot key bytes".to_string())
})?;
let script_pubkey = ScriptBuf::builder()
.push_opcode(OP_PUSHNUM_1)
.push_slice(&push_bytes)
.into_script();
// Build the single leaf with its merkle branch
let control_block = spend_info
.control_block(&(script_buf.clone(), version))