-
Notifications
You must be signed in to change notification settings - Fork 65
/
mod.rs
1422 lines (1308 loc) · 55.8 KB
/
mod.rs
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
mod http;
#[cfg(feature = "zeromq")]
mod zmq;
use crate::chainhooks::bitcoin::{
evaluate_bitcoin_chainhooks_on_chain_event, handle_bitcoin_hook_action,
BitcoinChainhookOccurrence, BitcoinChainhookOccurrencePayload, BitcoinTriggerChainhook,
};
use crate::chainhooks::stacks::{
evaluate_stacks_chainhooks_on_chain_event, handle_stacks_hook_action,
StacksChainhookOccurrence, StacksChainhookOccurrencePayload,
};
use crate::chainhooks::types::{
ChainhookConfig, ChainhookFullSpecification, ChainhookSpecification,
};
use crate::indexer::bitcoin::{
build_http_client, download_and_parse_block_with_retry, standardize_bitcoin_block,
BitcoinBlockFullBreakdown,
};
use crate::indexer::{Indexer, IndexerConfig};
use crate::monitoring::{start_serving_prometheus_metrics, PrometheusMonitoring};
use crate::utils::{send_request, Context};
use bitcoincore_rpc::bitcoin::{BlockHash, Txid};
use bitcoincore_rpc::{Auth, Client, RpcApi};
use chainhook_types::{
BitcoinBlockData, BitcoinBlockSignaling, BitcoinChainEvent, BitcoinChainUpdatedWithBlocksData,
BitcoinChainUpdatedWithReorgData, BitcoinNetwork, BlockIdentifier, BlockchainEvent,
StacksChainEvent, StacksNetwork, StacksNodeConfig, TransactionIdentifier,
};
use hiro_system_kit;
use hiro_system_kit::slog;
use rocket::config::{self, Config, LogLevel};
use rocket::data::{Limits, ToByteUnit};
use rocket::serde::Deserialize;
use rocket::Shutdown;
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::error::Error;
use std::net::{IpAddr, Ipv4Addr};
use std::path::PathBuf;
use std::str;
use std::str::FromStr;
use std::sync::mpsc::{Receiver, Sender};
use std::sync::{Arc, Mutex, RwLock};
pub const DEFAULT_INGESTION_PORT: u16 = 20445;
#[derive(Deserialize)]
pub struct NewTransaction {
pub txid: String,
pub status: String,
pub raw_result: String,
pub raw_tx: String,
}
#[derive(Clone, Debug)]
pub enum Event {
BitcoinChainEvent(BitcoinChainEvent),
StacksChainEvent(StacksChainEvent),
}
pub enum DataHandlerEvent {
Process(BitcoinChainhookOccurrencePayload),
Terminate,
}
#[derive(Debug, Clone)]
pub struct EventObserverConfig {
pub chainhook_config: Option<ChainhookConfig>,
pub bitcoin_rpc_proxy_enabled: bool,
pub ingestion_port: u16,
pub bitcoind_rpc_username: String,
pub bitcoind_rpc_password: String,
pub bitcoind_rpc_url: String,
pub bitcoin_block_signaling: BitcoinBlockSignaling,
pub display_logs: bool,
pub cache_path: String,
pub bitcoin_network: BitcoinNetwork,
pub stacks_network: StacksNetwork,
pub data_handler_tx: Option<crossbeam_channel::Sender<DataHandlerEvent>>,
pub prometheus_monitoring_port: Option<u16>,
}
#[derive(Deserialize, Debug, Clone)]
pub struct EventObserverConfigOverrides {
pub ingestion_port: Option<u16>,
pub bitcoind_rpc_username: Option<String>,
pub bitcoind_rpc_password: Option<String>,
pub bitcoind_rpc_url: Option<String>,
pub bitcoind_zmq_url: Option<String>,
pub stacks_node_rpc_url: Option<String>,
pub display_logs: Option<bool>,
pub cache_path: Option<String>,
pub bitcoin_network: Option<String>,
pub stacks_network: Option<String>,
}
impl EventObserverConfig {
pub fn get_cache_path_buf(&self) -> PathBuf {
let mut path_buf = PathBuf::new();
path_buf.push(&self.cache_path);
path_buf
}
pub fn get_bitcoin_config(&self) -> BitcoinConfig {
let bitcoin_config = BitcoinConfig {
username: self.bitcoind_rpc_username.clone(),
password: self.bitcoind_rpc_password.clone(),
rpc_url: self.bitcoind_rpc_url.clone(),
network: self.bitcoin_network.clone(),
bitcoin_block_signaling: self.bitcoin_block_signaling.clone(),
};
bitcoin_config
}
pub fn get_chainhook_store(&self) -> ChainhookStore {
let mut chainhook_store = ChainhookStore::new();
// If authorization not required, we create a default ChainhookConfig
if let Some(ref chainhook_config) = self.chainhook_config {
let mut chainhook_config = chainhook_config.clone();
chainhook_store
.predicates
.stacks_chainhooks
.append(&mut chainhook_config.stacks_chainhooks);
chainhook_store
.predicates
.bitcoin_chainhooks
.append(&mut chainhook_config.bitcoin_chainhooks);
}
chainhook_store
}
pub fn get_stacks_node_config(&self) -> &StacksNodeConfig {
match self.bitcoin_block_signaling {
BitcoinBlockSignaling::Stacks(ref config) => config,
_ => unreachable!(),
}
}
/// Helper to allow overriding some default fields in creating a new EventObserverConfig.
///
/// *Note: This is used by external crates, so it should not be removed, even if not used internally by Chainhook.*
pub fn new_using_overrides(
overrides: Option<&EventObserverConfigOverrides>,
) -> Result<EventObserverConfig, String> {
let bitcoin_network =
if let Some(network) = overrides.and_then(|c| c.bitcoin_network.as_ref()) {
BitcoinNetwork::from_str(network)?
} else {
BitcoinNetwork::Regtest
};
let stacks_network =
if let Some(network) = overrides.and_then(|c| c.stacks_network.as_ref()) {
StacksNetwork::from_str(network)?
} else {
StacksNetwork::Devnet
};
let config = EventObserverConfig {
bitcoin_rpc_proxy_enabled: false,
chainhook_config: None,
ingestion_port: overrides
.and_then(|c| c.ingestion_port)
.unwrap_or(DEFAULT_INGESTION_PORT),
bitcoind_rpc_username: overrides
.and_then(|c| c.bitcoind_rpc_username.clone())
.unwrap_or("devnet".to_string()),
bitcoind_rpc_password: overrides
.and_then(|c| c.bitcoind_rpc_password.clone())
.unwrap_or("devnet".to_string()),
bitcoind_rpc_url: overrides
.and_then(|c| c.bitcoind_rpc_url.clone())
.unwrap_or("http://localhost:18443".to_string()),
bitcoin_block_signaling: overrides
.and_then(|c| c.bitcoind_zmq_url.as_ref())
.map(|url| BitcoinBlockSignaling::ZeroMQ(url.clone()))
.unwrap_or(BitcoinBlockSignaling::Stacks(
StacksNodeConfig::default_localhost(
overrides
.and_then(|c| c.ingestion_port)
.unwrap_or(DEFAULT_INGESTION_PORT),
),
)),
display_logs: overrides.and_then(|c| c.display_logs).unwrap_or(false),
cache_path: overrides
.and_then(|c| c.cache_path.clone())
.unwrap_or("cache".to_string()),
bitcoin_network,
stacks_network,
data_handler_tx: None,
prometheus_monitoring_port: None,
};
Ok(config)
}
}
#[derive(Deserialize, Debug)]
pub struct ContractReadonlyCall {
pub okay: bool,
pub result: String,
}
#[derive(Clone, Debug, PartialEq)]
pub enum ObserverCommand {
ProcessBitcoinBlock(BitcoinBlockFullBreakdown),
CacheBitcoinBlock(BitcoinBlockData),
PropagateBitcoinChainEvent(BlockchainEvent),
PropagateStacksChainEvent(StacksChainEvent),
PropagateStacksMempoolEvent(StacksChainMempoolEvent),
RegisterPredicate(ChainhookFullSpecification),
EnablePredicate(ChainhookSpecification),
DeregisterBitcoinPredicate(String),
DeregisterStacksPredicate(String),
ExpireBitcoinPredicate(HookExpirationData),
ExpireStacksPredicate(HookExpirationData),
NotifyBitcoinTransactionProxied,
Terminate,
}
#[derive(Clone, Debug, PartialEq)]
pub struct HookExpirationData {
pub hook_uuid: String,
pub block_height: u64,
}
#[derive(Clone, Debug, PartialEq)]
pub enum StacksChainMempoolEvent {
TransactionsAdmitted(Vec<MempoolAdmissionData>),
TransactionDropped(String),
}
#[derive(Clone, Debug, PartialEq)]
pub struct MempoolAdmissionData {
pub tx_data: String,
pub tx_description: String,
}
#[derive(Clone, Debug)]
pub struct PredicateEvaluationReport {
pub predicates_evaluated: BTreeMap<String, BTreeSet<BlockIdentifier>>,
pub predicates_triggered: BTreeMap<String, BTreeSet<BlockIdentifier>>,
pub predicates_expired: BTreeMap<String, BTreeSet<BlockIdentifier>>,
}
impl PredicateEvaluationReport {
pub fn new() -> PredicateEvaluationReport {
PredicateEvaluationReport {
predicates_evaluated: BTreeMap::new(),
predicates_triggered: BTreeMap::new(),
predicates_expired: BTreeMap::new(),
}
}
pub fn track_evaluation(&mut self, uuid: &str, block_identifier: &BlockIdentifier) {
self.predicates_evaluated
.entry(uuid.to_string())
.and_modify(|e| {
e.insert(block_identifier.clone());
})
.or_insert_with(|| {
let mut set = BTreeSet::new();
set.insert(block_identifier.clone());
set
});
}
pub fn track_trigger(&mut self, uuid: &str, blocks: &Vec<&BlockIdentifier>) {
for block_id in blocks.into_iter() {
self.predicates_triggered
.entry(uuid.to_string())
.and_modify(|e| {
e.insert((*block_id).clone());
})
.or_insert_with(|| {
let mut set = BTreeSet::new();
set.insert((*block_id).clone());
set
});
}
}
pub fn track_expiration(&mut self, uuid: &str, block_identifier: &BlockIdentifier) {
self.predicates_expired
.entry(uuid.to_string())
.and_modify(|e| {
e.insert(block_identifier.clone());
})
.or_insert_with(|| {
let mut set = BTreeSet::new();
set.insert(block_identifier.clone());
set
});
}
}
#[derive(Clone, Debug)]
pub enum ObserverEvent {
Error(String),
Fatal(String),
Info(String),
BitcoinChainEvent((BitcoinChainEvent, PredicateEvaluationReport)),
StacksChainEvent((StacksChainEvent, PredicateEvaluationReport)),
NotifyBitcoinTransactionProxied,
PredicateRegistered(ChainhookSpecification),
PredicateDeregistered(ChainhookSpecification),
PredicateEnabled(ChainhookSpecification),
BitcoinPredicateTriggered(BitcoinChainhookOccurrencePayload),
StacksPredicateTriggered(StacksChainhookOccurrencePayload),
PredicatesTriggered(usize),
Terminate,
StacksChainMempoolEvent(StacksChainMempoolEvent),
}
#[derive(Debug, Clone, Deserialize, Serialize)]
/// JSONRPC Request
pub struct BitcoinRPCRequest {
/// The name of the RPC call
pub method: String,
/// Parameters to the RPC call
pub params: serde_json::Value,
/// Identifier for this Request, which should appear in the response
pub id: serde_json::Value,
/// jsonrpc field, MUST be "2.0"
pub jsonrpc: serde_json::Value,
}
#[derive(Debug, Clone)]
pub struct BitcoinConfig {
pub username: String,
pub password: String,
pub rpc_url: String,
pub network: BitcoinNetwork,
pub bitcoin_block_signaling: BitcoinBlockSignaling,
}
#[derive(Debug, Clone)]
pub struct ChainhookStore {
pub predicates: ChainhookConfig,
}
impl ChainhookStore {
pub fn new() -> Self {
Self {
predicates: ChainhookConfig {
stacks_chainhooks: vec![],
bitcoin_chainhooks: vec![],
},
}
}
}
#[derive(Debug, Clone)]
pub struct BitcoinBlockDataCached {
pub block: BitcoinBlockData,
pub processed_by_sidecar: bool,
}
pub struct ObserverSidecar {
pub bitcoin_blocks_mutator: Option<(
crossbeam_channel::Sender<(Vec<BitcoinBlockDataCached>, Vec<BlockIdentifier>)>,
crossbeam_channel::Receiver<Vec<BitcoinBlockDataCached>>,
)>,
pub bitcoin_chain_event_notifier: Option<crossbeam_channel::Sender<HandleBlock>>,
}
impl ObserverSidecar {
fn perform_bitcoin_sidecar_mutations(
&self,
blocks: Vec<BitcoinBlockDataCached>,
blocks_ids_to_rollback: Vec<BlockIdentifier>,
ctx: &Context,
) -> Vec<BitcoinBlockDataCached> {
if let Some(ref block_mutator) = self.bitcoin_blocks_mutator {
ctx.try_log(|logger| slog::info!(logger, "Sending blocks to pre-processor",));
let _ = block_mutator
.0
.send((blocks.clone(), blocks_ids_to_rollback));
ctx.try_log(|logger| slog::info!(logger, "Waiting for blocks from pre-processor",));
match block_mutator.1.recv() {
Ok(updated_blocks) => {
ctx.try_log(|logger| slog::info!(logger, "Block received from pre-processor",));
updated_blocks
}
Err(e) => {
ctx.try_log(|logger| {
slog::error!(
logger,
"Unable to receive block from pre-processor {}",
e.to_string()
)
});
blocks
}
}
} else {
blocks
}
}
fn notify_chain_event(&self, chain_event: &BitcoinChainEvent, _ctx: &Context) {
if let Some(ref notifier) = self.bitcoin_chain_event_notifier {
match chain_event {
BitcoinChainEvent::ChainUpdatedWithBlocks(data) => {
for block in data.new_blocks.iter() {
let _ = notifier.send(HandleBlock::ApplyBlock(block.clone()));
}
}
BitcoinChainEvent::ChainUpdatedWithReorg(data) => {
for block in data.blocks_to_rollback.iter() {
let _ = notifier.send(HandleBlock::UndoBlock(block.clone()));
}
for block in data.blocks_to_apply.iter() {
let _ = notifier.send(HandleBlock::ApplyBlock(block.clone()));
}
}
}
}
}
}
pub fn start_event_observer(
config: EventObserverConfig,
observer_commands_tx: Sender<ObserverCommand>,
observer_commands_rx: Receiver<ObserverCommand>,
observer_events_tx: Option<crossbeam_channel::Sender<ObserverEvent>>,
observer_sidecar: Option<ObserverSidecar>,
ctx: Context,
) -> Result<(), Box<dyn Error>> {
match config.bitcoin_block_signaling {
BitcoinBlockSignaling::ZeroMQ(ref url) => {
ctx.try_log(|logger| {
slog::info!(logger, "Observing Bitcoin chain events via ZeroMQ: {}", url)
});
let context_cloned = ctx.clone();
let event_observer_config_moved = config.clone();
let observer_commands_tx_moved = observer_commands_tx.clone();
let _ = hiro_system_kit::thread_named("Chainhook event observer").spawn(move || {
let future = start_bitcoin_event_observer(
event_observer_config_moved,
observer_commands_tx_moved,
observer_commands_rx,
observer_events_tx,
observer_sidecar,
context_cloned,
);
let _ = hiro_system_kit::nestable_block_on(future);
});
}
BitcoinBlockSignaling::Stacks(ref _url) => {
// Start chainhook event observer
let context_cloned = ctx.clone();
let event_observer_config_moved = config.clone();
let observer_commands_tx_moved = observer_commands_tx.clone();
let _ = hiro_system_kit::thread_named("Chainhook event observer").spawn(move || {
let future = start_stacks_event_observer(
event_observer_config_moved,
observer_commands_tx_moved,
observer_commands_rx,
observer_events_tx,
observer_sidecar,
context_cloned,
);
let _ = hiro_system_kit::nestable_block_on(future);
});
ctx.try_log(|logger| {
slog::info!(
logger,
"Listening on port {} for Stacks chain events",
config.get_stacks_node_config().ingestion_port
)
});
ctx.try_log(|logger| {
slog::info!(logger, "Observing Bitcoin chain events via Stacks node")
});
}
}
Ok(())
}
pub async fn start_bitcoin_event_observer(
config: EventObserverConfig,
_observer_commands_tx: Sender<ObserverCommand>,
observer_commands_rx: Receiver<ObserverCommand>,
observer_events_tx: Option<crossbeam_channel::Sender<ObserverEvent>>,
observer_sidecar: Option<ObserverSidecar>,
ctx: Context,
) -> Result<(), Box<dyn Error>> {
let chainhook_store = config.get_chainhook_store();
#[cfg(feature = "zeromq")]
{
let ctx_moved = ctx.clone();
let config_moved = config.clone();
let _ = hiro_system_kit::thread_named("ZMQ handler").spawn(move || {
let future =
zmq::start_zeromq_runloop(&config_moved, _observer_commands_tx, &ctx_moved);
let _ = hiro_system_kit::nestable_block_on(future);
});
}
let prometheus_monitoring = PrometheusMonitoring::new();
prometheus_monitoring.stx_metrics_set_registered_predicates(
chainhook_store.predicates.stacks_chainhooks.len() as u64,
);
prometheus_monitoring.btc_metrics_set_registered_predicates(
chainhook_store.predicates.bitcoin_chainhooks.len() as u64,
);
if let Some(port) = config.prometheus_monitoring_port {
let registry_moved = prometheus_monitoring.registry.clone();
let ctx_cloned = ctx.clone();
let _ = std::thread::spawn(move || {
let _ = hiro_system_kit::nestable_block_on(start_serving_prometheus_metrics(
port,
registry_moved,
ctx_cloned,
));
});
}
// This loop is used for handling background jobs, emitted by HTTP calls.
start_observer_commands_handler(
config,
chainhook_store,
observer_commands_rx,
observer_events_tx,
None,
prometheus_monitoring,
observer_sidecar,
ctx,
)
.await
}
pub async fn start_stacks_event_observer(
config: EventObserverConfig,
observer_commands_tx: Sender<ObserverCommand>,
observer_commands_rx: Receiver<ObserverCommand>,
observer_events_tx: Option<crossbeam_channel::Sender<ObserverEvent>>,
observer_sidecar: Option<ObserverSidecar>,
ctx: Context,
) -> Result<(), Box<dyn Error>> {
let indexer_config = IndexerConfig {
bitcoind_rpc_url: config.bitcoind_rpc_url.clone(),
bitcoind_rpc_username: config.bitcoind_rpc_username.clone(),
bitcoind_rpc_password: config.bitcoind_rpc_password.clone(),
stacks_network: StacksNetwork::Devnet,
bitcoin_network: BitcoinNetwork::Regtest,
bitcoin_block_signaling: config.bitcoin_block_signaling.clone(),
};
let indexer = Indexer::new(indexer_config.clone());
let log_level = if config.display_logs {
if cfg!(feature = "cli") {
LogLevel::Critical
} else {
LogLevel::Debug
}
} else {
LogLevel::Off
};
let ingestion_port = config.get_stacks_node_config().ingestion_port;
let bitcoin_rpc_proxy_enabled = config.bitcoin_rpc_proxy_enabled;
let bitcoin_config = config.get_bitcoin_config();
let chainhook_store = config.get_chainhook_store();
let indexer_rw_lock = Arc::new(RwLock::new(indexer));
let background_job_tx_mutex = Arc::new(Mutex::new(observer_commands_tx.clone()));
let prometheus_monitoring = PrometheusMonitoring::new();
prometheus_monitoring.stx_metrics_set_registered_predicates(
chainhook_store.predicates.stacks_chainhooks.len() as u64,
);
prometheus_monitoring.btc_metrics_set_registered_predicates(
chainhook_store.predicates.bitcoin_chainhooks.len() as u64,
);
if let Some(port) = config.prometheus_monitoring_port {
let registry_moved = prometheus_monitoring.registry.clone();
let ctx_cloned = ctx.clone();
let _ = std::thread::spawn(move || {
let _ = hiro_system_kit::nestable_block_on(start_serving_prometheus_metrics(
port,
registry_moved,
ctx_cloned,
));
});
}
let limits = Limits::default().limit("json", 20.megabytes());
let mut shutdown_config = config::Shutdown::default();
shutdown_config.ctrlc = false;
shutdown_config.grace = 0;
shutdown_config.mercy = 0;
let ingestion_config = Config {
port: ingestion_port,
workers: 3,
address: IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)),
keep_alive: 5,
temp_dir: std::env::temp_dir().into(),
log_level: log_level.clone(),
cli_colors: false,
limits,
shutdown: shutdown_config,
..Config::default()
};
let mut routes = rocket::routes![
http::handle_ping,
http::handle_new_bitcoin_block,
http::handle_new_stacks_block,
http::handle_new_microblocks,
http::handle_new_mempool_tx,
http::handle_drop_mempool_tx,
http::handle_new_attachement,
http::handle_mined_block,
http::handle_mined_microblock,
];
if bitcoin_rpc_proxy_enabled {
routes.append(&mut routes![http::handle_bitcoin_rpc_call]);
routes.append(&mut routes![http::handle_bitcoin_wallet_rpc_call]);
}
let ctx_cloned = ctx.clone();
let ignite = rocket::custom(ingestion_config)
.manage(indexer_rw_lock)
.manage(background_job_tx_mutex)
.manage(bitcoin_config)
.manage(ctx_cloned)
.manage(prometheus_monitoring.clone())
.mount("/", routes)
.ignite()
.await?;
let ingestion_shutdown = Some(ignite.shutdown());
let _ = std::thread::spawn(move || {
let _ = hiro_system_kit::nestable_block_on(ignite.launch());
});
// This loop is used for handling background jobs, emitted by HTTP calls.
start_observer_commands_handler(
config,
chainhook_store,
observer_commands_rx,
observer_events_tx,
ingestion_shutdown,
prometheus_monitoring,
observer_sidecar,
ctx,
)
.await
}
pub fn get_bitcoin_proof(
bitcoin_client_rpc: &Client,
transaction_identifier: &TransactionIdentifier,
block_identifier: &BlockIdentifier,
) -> Result<String, String> {
let txid =
Txid::from_str(&transaction_identifier.get_hash_bytes_str()).expect("unable to build txid");
let block_hash =
BlockHash::from_str(&block_identifier.hash[2..]).expect("unable to build block_hash");
let res = bitcoin_client_rpc.get_tx_out_proof(&vec![txid], Some(&block_hash));
match res {
Ok(proof) => Ok(format!("0x{}", hex::encode(&proof))),
Err(e) => Err(format!(
"failed collecting proof for transaction {}: {}",
transaction_identifier.hash,
e.to_string()
)),
}
}
pub fn gather_proofs<'a>(
trigger: &BitcoinTriggerChainhook<'a>,
proofs: &mut HashMap<&'a TransactionIdentifier, String>,
config: &EventObserverConfig,
ctx: &Context,
) {
let bitcoin_client_rpc = Client::new(
&config.bitcoind_rpc_url,
Auth::UserPass(
config.bitcoind_rpc_username.to_string(),
config.bitcoind_rpc_password.to_string(),
),
)
.expect("unable to build http client");
for (transactions, block) in trigger.apply.iter() {
for transaction in transactions.iter() {
if !proofs.contains_key(&transaction.transaction_identifier) {
ctx.try_log(|logger| {
slog::info!(
logger,
"Collecting proof for transaction {}",
transaction.transaction_identifier.hash
)
});
match get_bitcoin_proof(
&bitcoin_client_rpc,
&transaction.transaction_identifier,
&block.block_identifier,
) {
Ok(proof) => {
proofs.insert(&transaction.transaction_identifier, proof);
}
Err(e) => {
ctx.try_log(|logger| slog::error!(logger, "{e}"));
}
}
}
}
}
}
pub enum HandleBlock {
ApplyBlock(BitcoinBlockData),
UndoBlock(BitcoinBlockData),
}
pub async fn start_observer_commands_handler(
config: EventObserverConfig,
mut chainhook_store: ChainhookStore,
observer_commands_rx: Receiver<ObserverCommand>,
observer_events_tx: Option<crossbeam_channel::Sender<ObserverEvent>>,
ingestion_shutdown: Option<Shutdown>,
prometheus_monitoring: PrometheusMonitoring,
observer_sidecar: Option<ObserverSidecar>,
ctx: Context,
) -> Result<(), Box<dyn Error>> {
let mut chainhooks_occurrences_tracker: HashMap<String, u64> = HashMap::new();
let networks = (&config.bitcoin_network, &config.stacks_network);
let mut bitcoin_block_store: HashMap<BlockIdentifier, BitcoinBlockDataCached> = HashMap::new();
let http_client = build_http_client();
let store_update_required = observer_sidecar
.as_ref()
.and_then(|s| s.bitcoin_blocks_mutator.as_ref())
.is_some();
loop {
let command = match observer_commands_rx.recv() {
Ok(cmd) => cmd,
Err(e) => {
if let Some(ref tx) = observer_events_tx {
let _ = tx.send(ObserverEvent::Error(format!("Channel error: {:?}", e)));
}
continue;
}
};
match command {
ObserverCommand::Terminate => {
ctx.try_log(|logger| slog::info!(logger, "Handling Termination command"));
if let Some(ingestion_shutdown) = ingestion_shutdown {
ingestion_shutdown.notify();
}
if let Some(ref tx) = observer_events_tx {
let _ = tx.send(ObserverEvent::Info("Terminating event observer".into()));
let _ = tx.send(ObserverEvent::Terminate);
}
break;
}
ObserverCommand::ProcessBitcoinBlock(mut block_data) => {
let block_hash = block_data.hash.to_string();
let block = loop {
match standardize_bitcoin_block(
block_data.clone(),
&config.bitcoin_network,
&ctx,
) {
Ok(block) => break block,
Err((e, retry)) => {
ctx.try_log(|logger| {
slog::error!(logger, "Error standardizing block: {}", e)
});
if retry {
block_data = match download_and_parse_block_with_retry(
&http_client,
&block_hash,
&config.get_bitcoin_config(),
&ctx,
)
.await
{
Ok(block) => block,
Err(e) => {
ctx.try_log(|logger| {
slog::warn!(
logger,
"unable to download_and_parse_block: {}",
e.to_string()
)
});
continue;
}
};
}
}
};
};
prometheus_monitoring.btc_metrics_ingest_block(block.block_identifier.index);
bitcoin_block_store.insert(
block.block_identifier.clone(),
BitcoinBlockDataCached {
block,
processed_by_sidecar: false,
},
);
}
ObserverCommand::CacheBitcoinBlock(block) => {
bitcoin_block_store.insert(
block.block_identifier.clone(),
BitcoinBlockDataCached {
block,
processed_by_sidecar: false,
},
);
}
ObserverCommand::PropagateBitcoinChainEvent(blockchain_event) => {
ctx.try_log(|logger| {
slog::info!(logger, "Handling PropagateBitcoinChainEvent command")
});
let mut confirmed_blocks = vec![];
// Update Chain event before propagation
let chain_event = match blockchain_event {
BlockchainEvent::BlockchainUpdatedWithHeaders(data) => {
let mut blocks_to_mutate = vec![];
let mut new_blocks = vec![];
for header in data.new_headers.iter() {
if store_update_required {
let Some(block) =
bitcoin_block_store.remove(&header.block_identifier)
else {
continue;
};
blocks_to_mutate.push(block);
} else {
let Some(cache) = bitcoin_block_store.get(&header.block_identifier)
else {
continue;
};
new_blocks.push(cache.block.clone());
};
}
if let Some(ref sidecar) = observer_sidecar {
let updated_blocks = sidecar.perform_bitcoin_sidecar_mutations(
blocks_to_mutate,
vec![],
&ctx,
);
for cache in updated_blocks.into_iter() {
bitcoin_block_store
.insert(cache.block.block_identifier.clone(), cache.clone());
new_blocks.push(cache.block);
}
}
for header in data.confirmed_headers.iter() {
match bitcoin_block_store.remove(&header.block_identifier) {
Some(res) => {
confirmed_blocks.push(res.block);
}
None => {
ctx.try_log(|logger| {
slog::error!(
logger,
"Unable to retrieve confirmed bitcoin block {}",
header.block_identifier
)
});
}
}
}
BitcoinChainEvent::ChainUpdatedWithBlocks(
BitcoinChainUpdatedWithBlocksData {
new_blocks,
confirmed_blocks: confirmed_blocks.clone(),
},
)
}
BlockchainEvent::BlockchainUpdatedWithReorg(data) => {
let mut blocks_to_rollback = vec![];
let mut blocks_to_mutate = vec![];
let mut blocks_to_apply = vec![];
for header in data.headers_to_apply.iter() {
if store_update_required {
let Some(block) =
bitcoin_block_store.remove(&header.block_identifier)
else {
continue;
};
blocks_to_mutate.push(block);
} else {
let Some(cache) = bitcoin_block_store.get(&header.block_identifier)
else {
continue;
};
blocks_to_apply.push(cache.block.clone());
};
}
let mut blocks_ids_to_rollback: Vec<BlockIdentifier> = vec![];
for header in data.headers_to_rollback.iter() {
match bitcoin_block_store.get(&header.block_identifier) {
Some(cache) => {
blocks_ids_to_rollback.push(header.block_identifier.clone());
blocks_to_rollback.push(cache.block.clone());
}
None => {
ctx.try_log(|logger| {
slog::error!(
logger,
"Unable to retrieve bitcoin block {}",
header.block_identifier
)
});
}
}
}
if let Some(ref sidecar) = observer_sidecar {
let updated_blocks = sidecar.perform_bitcoin_sidecar_mutations(
blocks_to_mutate,
blocks_ids_to_rollback,
&ctx,
);
for cache in updated_blocks.into_iter() {
bitcoin_block_store
.insert(cache.block.block_identifier.clone(), cache.clone());
blocks_to_apply.push(cache.block);
}
}
for header in data.confirmed_headers.iter() {
match bitcoin_block_store.remove(&header.block_identifier) {
Some(res) => {
confirmed_blocks.push(res.block);
}
None => {
ctx.try_log(|logger| {
slog::error!(
logger,
"Unable to retrieve confirmed bitcoin block {}",
header.block_identifier
)
});
}
}
}
match blocks_to_apply
.iter()
.max_by_key(|b| b.block_identifier.index)
{
Some(highest_tip_block) => prometheus_monitoring.btc_metrics_set_reorg(
highest_tip_block.timestamp.into(),
blocks_to_apply.len() as u64,
blocks_to_rollback.len() as u64,
),
None => {}
}
BitcoinChainEvent::ChainUpdatedWithReorg(BitcoinChainUpdatedWithReorgData {
blocks_to_apply,
blocks_to_rollback,
confirmed_blocks: confirmed_blocks.clone(),
})
}
};
if let Some(ref sidecar) = observer_sidecar {
sidecar.notify_chain_event(&chain_event, &ctx)
}
// process hooks
let mut hooks_ids_to_deregister = vec![];
let mut requests = vec![];
let mut report = PredicateEvaluationReport::new();
let bitcoin_chainhooks = chainhook_store
.predicates
.bitcoin_chainhooks