-
Notifications
You must be signed in to change notification settings - Fork 13
/
main.rs
1459 lines (1342 loc) · 54.2 KB
/
main.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
#![cfg_attr(feature = "strict", deny(warnings))]
use std::collections::{HashMap, HashSet, VecDeque};
use std::fmt::Display;
use std::fs::File;
use std::io::Read;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time;
use std::time::Instant;
use bitcoin_pool_identification::{
parse_json, Pool, PoolIdentification, DEFAULT_MAINNET_POOL_LIST,
};
use miningpool_observer_shared::bitcoincore_rpc::bitcoin;
use miningpool_observer_shared::bitcoincore_rpc::bitcoin::{
address::NetworkUnchecked, address::ParseError, hash_types::Txid, hashes::Hash, Address,
Amount, Block,
};
use miningpool_observer_shared::bitcoincore_rpc::jsonrpc::serde_json;
use miningpool_observer_shared::config::PoolIdentificationConfig;
use simple_logger::SimpleLogger;
use miningpool_observer_shared::bitcoincore_rpc::json::{
GetBlockTemplateModes, GetBlockTemplateResult, GetBlockTemplateRules, GetBlockTxFeesResult,
ScanTxOutRequest,
};
use miningpool_observer_shared::bitcoincore_rpc::jsonrpc;
use miningpool_observer_shared::bitcoincore_rpc::{Auth, Client, Error, RpcApi};
use miningpool_observer_shared::chrono;
use miningpool_observer_shared::diesel;
use miningpool_observer_shared::{
config, db_pool, model as shared_model, prometheus_metric_server,
};
use crate::model::TxInfo;
mod db;
mod metrics;
mod model;
mod processing;
const WAIT_TIME_BETWEEN_TEMPLATE_QUERIES: time::Duration = time::Duration::from_secs(10);
const WAIT_TIME_BETWEEN_CONNPOOL_GETCONNECTION: time::Duration = time::Duration::from_secs(1);
const WAIT_TIME_BETWEEN_UTXO_SET_SCANS: time::Duration = time::Duration::from_secs(60 * 60 * 3); // 3 hours
const WAIT_TIME_BETWEEN_FAILED_UTXO_SET_SCANS: time::Duration = time::Duration::from_secs(60 * 5); // 5 minutes
const WAIT_TIME_BETWEEN_SANCTIONED_ADDRESS_UPDATES: time::Duration =
time::Duration::from_secs(60 * 60 * 24); // 1 day
const WAIT_TIME_BETWEEN_POOL_IDENTIFICATOIN_DATASET_UPDATES: time::Duration =
time::Duration::from_secs(60 * 60 * 24); // 1 day
const TIMEOUT_UTXO_SET_SCANS: time::Duration = time::Duration::from_secs(60 * 8); // 8 minutes
const MAX_OLD_TEMPLATES: usize = 15;
const TIMEOUT_HTTP_GET_REQUEST: u64 = 10; // seconds
const LOG_TARGET_RPC: &str = "rpc";
const LOG_TARGET_REIDUNKNOWNPOOLS: &str = "re-id_unknown_pools";
const LOG_TARGET_UTXOSETSCAN: &str = "utxo_set_scan";
const LOG_TARGET_STATS: &str = "stats";
const LOG_TARGET_DBPOOL: &str = "dbpool";
const LOG_TARGET_STARTUP: &str = "startup";
const LOG_TARGET_RETAG_TX: &str = "retagtx";
const LOG_TARGET_UPDATE_SANCTIONED_ADDRESSES: &str = "sanctionupdate";
const LOG_TARGET_UPDATE_POOL_ID_DATASET: &str = "pooldataupdate";
fn main() {
let config = match config::load_daemon_config() {
Ok(config) => config,
Err(e) => panic!("Could not load the configuration: {}", e),
};
metrics::RUNTIME_START_TIME.set(
time::SystemTime::now()
.duration_since(time::UNIX_EPOCH)
.unwrap()
.as_secs() as i64,
);
match SimpleLogger::new()
.with_utc_timestamps()
.with_level(config.log_level)
.init()
{
Ok(_) => (),
Err(e) => panic!("Could not setup logger: {}", e),
}
let rpc_client = match Client::new(&config.rpc_url.clone(), config.rpc_auth.clone()) {
Ok(config) => config,
Err(e) => panic!("Could not setup the Bitcoin Core RPC client: {}", e),
};
match rpc_client.get_blockchain_info() {
Ok(blockchaininfo) => {
log::info!(target: LOG_TARGET_STARTUP, "Successfully connected to the Bitcoin Core RPC server: chain={}, blocks={}, verification progress={}.", blockchaininfo.chain, blockchaininfo.blocks, blockchaininfo.verification_progress);
}
Err(e) => {
log::error!(target: LOG_TARGET_STARTUP, "Could not connect to the Bitcoin Core RPC server. Is the user/password correct?: {}", e);
panic!("Could not connect to the Bitcoin Core RPC server.")
}
}
let conn_pool = match db_pool::new(&config.database_url) {
Ok(pool) => pool,
Err(e) => panic!("Could not create a Postgres connection pool: {}", e),
};
log::info!(
target: LOG_TARGET_STARTUP,
"Succesfully created a database connection pool with a max size of {} connections.",
conn_pool.max_size()
);
if config.prometheus.enable {
if let Err(e) = prometheus_metric_server::start_http_server(&config.prometheus.address) {
log::error!(
target: LOG_TARGET_STARTUP,
"Could not start the Prometheus Metrics Server on {}: {}",
config.prometheus.address,
e
);
panic!("Could not start the Prometheus Metrics Server.")
}
} else {
log::info!(
target: LOG_TARGET_STARTUP,
"Not starting the Prometheus Metric Server as it is disabled via the config file."
)
}
startup_db_mirgation(&conn_pool);
// Sanctioned addresses updater
// Download the list before we start and then periodically update it.
if let Err(e) = start_sanctioned_addresses_updater_thread(
config.sanctioned_addresses_url,
conn_pool.clone(),
) {
panic!(
"During startup: Could not update the sanctioned address list: {}",
e
);
}
// Sanctioned UTXO (re)scan
let utxo_set_scan_conn_pool = match db_pool::new(&config.database_url) {
Ok(pool) => pool,
Err(e) => panic!(
"During startup: Could not create a Postgres connection pool: {}",
e
),
};
let user_pass = match get_user_pass(&config.rpc_auth) {
Ok(x) => x,
Err(e) => panic!(
"During startup: Could not extract the Bitcoin Core RPC credentials: {}",
e
),
};
// Mining pool identification
let miningpool_identification_data: model::SharedPoolIDData = Arc::new(Mutex::new(
parse_json(DEFAULT_MAINNET_POOL_LIST)
.expect("the default pool dataset should be parseable"),
));
start_pool_identification_update_thread(
miningpool_identification_data.clone(),
config.pool_identification.clone().dataset_url,
);
// Build a custom transport here to be able to configure the timeout.
let custom_timeout_transport = jsonrpc::simple_http::Builder::new()
.url(&config.rpc_url.clone())
.expect("invalid rpc url")
.auth(user_pass.0.expect("rpc user is empty"), user_pass.1)
.timeout(TIMEOUT_UTXO_SET_SCANS)
.build();
let custom_timeout_rpc_client =
jsonrpc::client::Client::with_transport(custom_timeout_transport);
let rpc_client_utxo_set_scan = Client::from_jsonrpc(custom_timeout_rpc_client);
start_sanctioned_utxos_scan_thread(rpc_client_utxo_set_scan, utxo_set_scan_conn_pool);
// Retry pool identification for "Unkown" pools
let reid_conn_pool = match db_pool::new(&config.database_url) {
Ok(pool) => pool,
Err(e) => panic!(
"During startup: Could not create a Postgres connection pool: {}",
e
),
};
let reid_rpc_client = match Client::new(&config.rpc_url.clone(), config.rpc_auth.clone()) {
Ok(config) => config,
Err(e) => panic!(
"During startup: Could not setup the Bitcoin Core RPC client: {}",
e
),
};
start_retry_unknown_pool_identification_thread(
reid_rpc_client,
reid_conn_pool,
miningpool_identification_data.clone(),
config.pool_identification.clone(),
);
match rpc_client.get_network_info() {
Ok(network_info) => {
let version = network_info.subversion.replace('/', "").replace(':', " ");
log::info!(
target: LOG_TARGET_STARTUP,
"Block templates are generated by Bitcoin Core with version {}.",
version
);
match conn_pool.get() {
Ok(mut conn) => {
if let Err(e) = db::update_node_info(&version, &mut conn) {
log::error!(
target: LOG_TARGET_STARTUP,
"Could not update the node information in the database: {}",
e
);
panic!("During startup: Could not update the node information in the database.");
}
}
Err(e) => {
log::error!(
target: LOG_TARGET_STARTUP,
"Could not get a connection from the connection pool: {}",
e
);
panic!("During startup: Could not get a database connection from the connection pool.");
}
}
}
Err(e) => {
log::error!(target: LOG_TARGET_STARTUP, "Could not connect to the Bitcoin Core RPC server. Is the user/password correct?: {}", e);
panic!("Could not connect to the Bitcoin Core RPC server.")
}
}
if config.retag_transactions {
let retag_conn_pool = match db_pool::new(&config.database_url) {
Ok(pool) => pool,
Err(e) => panic!(
"During startup: Could not create a Postgres connection pool: {}",
e
),
};
let retag_rpc_client = match Client::new(&config.rpc_url.clone(), config.rpc_auth.clone()) {
Ok(config) => config,
Err(e) => panic!(
"During startup: Could not setup the Bitcoin Core RPC client: {}",
e
),
};
retag_transactions(retag_rpc_client, retag_conn_pool);
}
main_loop(
&rpc_client,
&conn_pool,
config.pool_identification.clone(),
miningpool_identification_data,
);
}
fn startup_db_mirgation(conn_pool: &db_pool::PgPool) {
match conn_pool.get() {
Ok(mut conn) => {
match db::run_migrations(&mut conn) {
Ok(_) => log::info!(
target: LOG_TARGET_STARTUP,
"Database migrations successful."
),
Err(e) => {
log::error!(
target: LOG_TARGET_STARTUP,
"Could not run the PostgreSQL database migration: {}",
e
);
panic!("During startup: Could not run the PostgreSQL database migration.");
}
};
}
Err(e) => {
log::error!(
target: LOG_TARGET_STARTUP,
"Could not get a connection from the connection pool: {}",
e
);
panic!("During startup: Could not get a database connection from the connection pool.");
}
}
}
fn main_loop(
rpc: &Client,
db_pool: &db_pool::PgPool,
pool_identification_config: config::PoolIdentificationConfig,
pools: model::SharedPoolIDData,
) {
// stores up to the last MAX_OLD_TEMPLATES GetBlockTemplateResults to lookup older templates
// based on miner block timestamps.
let mut last_templates: VecDeque<GetBlockTemplateResult> =
VecDeque::with_capacity(MAX_OLD_TEMPLATES);
loop {
metrics::RUNTIME_TEMPLATES_IN_MEMORY.set(last_templates.len() as i64);
let current_template = match rpc.get_block_template(
GetBlockTemplateModes::Template,
&[
GetBlockTemplateRules::SegWit,
GetBlockTemplateRules::Taproot,
],
&[],
) {
Ok(t) => t,
Err(e) => {
log::error!(
target: LOG_TARGET_RPC,
"Could not get a block template from the Bitcoin Core RPC server: {}",
e
);
metrics::ERROR_RPC.inc();
thread::sleep(WAIT_TIME_BETWEEN_TEMPLATE_QUERIES);
continue;
}
};
metrics::RUNTIME_REQUESTED_TEMPLATES.inc();
log_template_infos(¤t_template);
// if we don't have any templates yet, just add the current_template
// and finish the loop early.
if last_templates.is_empty() {
last_templates.push_back(current_template);
thread::sleep(WAIT_TIME_BETWEEN_TEMPLATE_QUERIES);
continue;
}
let previous_template = match last_templates.make_contiguous().last() {
Some(t) => t,
None => {
processing::log_processing_error(&format!(
"Could not get the previous_template from last_templates (size: {}).",
last_templates.len()
));
metrics::ERROR_PROCESSING.inc(); // TODO: this can be remove as log_processing_error already increases it
panic!("last_templates should not be empty.");
}
};
// To detect if a block has been mined, we check the if the previous block hashes
// of the previous_template and the current_template are different. If they are
// the same, no block has been mined and we wait before getting a new template.
if previous_template.previous_block_hash == current_template.previous_block_hash {
last_templates.push_back(current_template);
if last_templates.len() > MAX_OLD_TEMPLATES {
last_templates.pop_front();
}
thread::sleep(WAIT_TIME_BETWEEN_TEMPLATE_QUERIES);
continue;
}
// The previous block hash of the previous_template and the current_template are
// different. This means the chain tip changed. We request the block with the
// current_templates previous block hash. In most cases, this should be the block
// that was just mined.
let bitcoin_block = match rpc.get_block(¤t_template.previous_block_hash) {
Ok(b) => {
metrics::RUNTIME_REQUESTED_BLOCKS.inc();
b
}
Err(e) => {
log::error!(
target: LOG_TARGET_RPC,
"Could not get the block with the hash {} from the Bitcoin Core RPC server: {}",
current_template.previous_block_hash,
e
);
log::error!(
target: LOG_TARGET_RPC,
"Skipping the processing of block {}.",
current_template.previous_block_hash
);
metrics::ERROR_RPC.inc();
thread::sleep(WAIT_TIME_BETWEEN_TEMPLATE_QUERIES);
continue;
}
};
// When something changed, we can't be sure if the templates in last_templates
// are actually templates for the block we just requested. For example, two block
// might have arrived at our node in rapid succession and we didn't query for a
// template in between.
// To check that we can compare the block with one of our last_templates, we
// compare the previous block hashes of block and the previous_template.
// Only if the hashes are equal, we can compare the template and block.
// If they are not equal, we might have skipped one or more blocks.
if bitcoin_block.header.prev_blockhash != previous_template.previous_block_hash {
log::warn!(
target: processing::LOG_TARGET_PROCESSING,
"Can't compare the previous_template to the new block. Was there a reorg or multiple blocks found in rapid succession?",
);
metrics::RUNTIME_SKIPPED_BLOCK_EVENTS.inc();
// We can however still compare the previous_template to it's respective block.
let hash_of_missed_block = match rpc.get_block_hash(previous_template.height) {
Ok(hash) => hash,
Err(e) => {
log::error!(
target: LOG_TARGET_RPC,
"Could not get the block hash of block {} from the Bitcoin Core RPC server: {}",
previous_template.height,
e
);
thread::sleep(WAIT_TIME_BETWEEN_TEMPLATE_QUERIES);
continue;
}
};
let bitcoin_block = match rpc.get_block(&hash_of_missed_block) {
Ok(b) => {
metrics::RUNTIME_REQUESTED_BLOCKS.inc();
b
}
Err(e) => {
log::error!(
target: LOG_TARGET_RPC,
"Could not get the block with the hash {} from the Bitcoin Core RPC server: {}",
current_template.previous_block_hash,
e
);
log::error!(
target: LOG_TARGET_RPC,
"Skipping the processing of block missed block {}.",
current_template.previous_block_hash
);
thread::sleep(WAIT_TIME_BETWEEN_TEMPLATE_QUERIES);
continue;
}
};
// TODO: Once Bitcoin Core v22 with getblock verbosity level 2 is released
// and rust-bitcoincore-rpc has can get the block and fees in on RPC call,
// then the above getblock call and this can be merged.
let block_tx_fees = match rpc.get_block_txid_fee(&hash_of_missed_block) {
Ok(b) => b,
Err(e) => {
log::error!(target: LOG_TARGET_RPC, "Could not get the txids and fees for block with the hash {} from the Bitcoin Core RPC server: {}", current_template.previous_block_hash, e);
log::error!(
target: processing::LOG_TARGET_PROCESSING,
"Skipping the processing of block {}.",
current_template.previous_block_hash
);
metrics::ERROR_RPC.inc();
thread::sleep(WAIT_TIME_BETWEEN_TEMPLATE_QUERIES);
continue;
}
};
log::info!(
target: LOG_TARGET_STATS,
"Processing missed block {} mined by {}",
bitcoin_block.block_hash(),
match bitcoin_block.identify_pool(pool_identification_config.clone().network, &pools.lock().unwrap()) {
Some(result) => result.pool.name,
None => "UNKNOWN".to_string(),
}
);
process(
rpc,
db_pool,
&bitcoin_block,
&block_tx_fees,
&mut last_templates,
pools.clone(),
pool_identification_config.clone(),
);
last_templates.push_back(current_template);
continue;
}
// TODO: Once Bitcoin Core v22 with getblock verbosity level 2 is released
// and rust-bitcoincore-rpc has can get the block and fees in on RPC call,
// then the above getblock call and this can be merged.
let block_tx_fees = match rpc.get_block_txid_fee(¤t_template.previous_block_hash) {
Ok(b) => b,
Err(e) => {
log::error!(target: LOG_TARGET_RPC, "Could not get the txids and fees for block with the hash {} from the Bitcoin Core RPC server: {}", current_template.previous_block_hash, e);
log::error!(
target: processing::LOG_TARGET_PROCESSING,
"Skipping the processing of block {}.",
current_template.previous_block_hash
);
metrics::ERROR_RPC.inc();
thread::sleep(WAIT_TIME_BETWEEN_TEMPLATE_QUERIES);
continue;
}
};
log::info!(
target: LOG_TARGET_STATS,
"New block detected {} mined by {}",
bitcoin_block.block_hash(),
match bitcoin_block.identify_pool(pool_identification_config.network.clone(), &pools.lock().unwrap()) {
Some(result) => result.pool.name,
None => "UNKNOWN".to_string(),
}
);
process(
rpc,
db_pool,
&bitcoin_block,
&block_tx_fees,
&mut last_templates,
pools.clone(),
pool_identification_config.clone(),
);
}
}
fn process(
rpc: &Client,
db_pool: &db_pool::PgPool,
bitcoin_block: &Block,
block_tx_fees: &GetBlockTxFeesResult,
last_templates: &mut VecDeque<GetBlockTemplateResult>,
pools: model::SharedPoolIDData,
pool_identification_config: PoolIdentificationConfig,
) {
let block_tx_data = processing::build_block_tx_data(bitcoin_block, block_tx_fees);
// For best possible comparison we want to compare a template and a block
// where our template was generated at the same time as the pool generated
// his template. As we can't know when exactly the pool generated his
// template, we assume that it must have been before or at the
// timestamp included in the block headder. During mining, the miners likely
// engages in nTime rolling, which increases the timestamp in the block header.
// Additionally, we don't know if the pools clock is accurate.
//
// Thus, to aid template selection, we pick the template sharing the most transactions
// with the block out of the templates generated before the timestamp in the block header.
let template = select_best_template_for_block(last_templates, block_tx_data.txids.clone());
let template_tx_data = processing::build_template_tx_data(template);
let template_tx_packages = processing::build_packages(&template_tx_data.txinfos);
let template_pkg_feerates: Vec<f32> =
template_tx_packages.iter().map(|p| p.feerate()).collect();
let template_pkg_weights: Vec<i64> = template_tx_packages
.iter()
.map(|p| p.weight() as i64)
.collect();
let block_tx_packages = processing::build_packages(&block_tx_data.txinfos);
let block_pkg_feerates: Vec<f32> = block_tx_packages.iter().map(|p| p.feerate()).collect();
let block_pkg_weights: Vec<i64> = block_tx_packages
.iter()
.map(|p| p.weight() as i64)
.collect();
// Set diffs to get the transactions that are in the block
// but not in the template and the other way around.
let txids_only_in_block: HashSet<&Txid> = block_tx_data
.txids
.difference(&template_tx_data.txids)
.collect();
let txids_only_in_template: HashSet<&Txid> = template_tx_data
.txids
.difference(&block_tx_data.txids)
.collect();
let shared_tx: usize = block_tx_data
.txids
.intersection(&template_tx_data.txids)
.count();
log::info!(
target: LOG_TARGET_STATS,
"Transactions in block: shared={}, missing={}, extra={}",
shared_tx,
txids_only_in_template.len(),
txids_only_in_block.len()
);
let mut connection = &mut match db_pool.get() {
Ok(c) => c,
Err(e) => {
log::error!(
target: LOG_TARGET_DBPOOL,
"Could not get a connection from the connection pool. Retrying in {:?}. Error: {}",
WAIT_TIME_BETWEEN_CONNPOOL_GETCONNECTION,
e
);
metrics::ERROR_DBPOOL.inc();
thread::sleep(WAIT_TIME_BETWEEN_CONNPOOL_GETCONNECTION);
match db_pool.get() {
Ok(c) => c,
Err(e) => {
log::error!(target: LOG_TARGET_DBPOOL, "Could not get a connection from the connection pool. Skipping processing of block {}: {}", bitcoin_block.block_hash(), e);
metrics::ERROR_DBPOOL.inc();
return;
}
}
}
};
let sanctioned_addresses: HashSet<String> = match db::sanctioned_addresses(&mut connection) {
Ok(addresses) => addresses.iter().map(|a| a.address.clone()).collect(),
Err(e) => {
processing::log_processing_error(&format!("Could not load the sanctioned addresses from the database. Using empty list of addresses: {}", e));
HashSet::new()
}
};
let sanctioned_utxos = match db::get_sanctioned_utxos(&mut connection) {
Ok(utxos) => utxos,
Err(e) => {
processing::log_processing_error(&format!("Could not load the sanctioned utxos from the database. Using empty UTXO set. Error: {}", e));
vec![]
}
};
let outpoint_to_sanctioned_utxo_map =
processing::build_outpoint_to_sanctioned_utxo_map(&sanctioned_utxos);
let sanctioned_missing_tx = processing::get_sanctioned_missing_tx_count(
&txids_only_in_template,
&template_tx_data,
&outpoint_to_sanctioned_utxo_map,
&sanctioned_addresses,
);
let block_fees: Amount =
Amount::from_sat(block_tx_fees.tx.iter().map(|tx| tx.fee.to_sat()).sum());
let template_fees: Amount =
Amount::from_sat(template.transactions.iter().map(|tx| tx.fee.to_sat()).sum());
let missing_tx: i32 = txids_only_in_template.len() as i32;
let extra_tx: i32 = txids_only_in_block.len() as i32;
let block = processing::build_block(
bitcoin_block,
template,
&template_tx_data.txid_to_txinfo_map,
&template_pkg_weights,
&template_pkg_feerates,
&block_pkg_weights,
&block_pkg_feerates,
missing_tx,
sanctioned_missing_tx as i32,
extra_tx,
shared_tx as i32,
&block_fees,
&template_fees,
&outpoint_to_sanctioned_utxo_map,
&sanctioned_addresses,
pools,
pool_identification_config.network,
);
let block_id = match db::insert_block(&block, &mut connection) {
Ok(id) => id,
Err(e) => {
processing::log_processing_error(&format!("Could not insert the block into the database. Skipping the remaining processing. Error: {}", e));
return;
}
};
let mut transactions: HashMap<Vec<u8>, shared_model::Transaction> = HashMap::new();
let conflicting_transactions = processing::build_conflicting_transactions(
block_id,
&txids_only_in_template,
&template_tx_data.txid_to_txinfo_map,
&txids_only_in_block,
&block_tx_data.txid_to_txinfo_map,
&mut transactions,
&outpoint_to_sanctioned_utxo_map,
&sanctioned_addresses,
);
if !conflicting_transactions.is_empty() {
log::info!(
target: LOG_TARGET_STATS,
"Between the template and the block are {} sets of conflicting transactions.",
conflicting_transactions.len()
);
metrics::STAT_CONFLICTING_TRANSACTION_SETS.inc_by(conflicting_transactions.len() as u64);
}
let template_txid_to_mempool_age = mempool_age_seconds(rpc, &txids_only_in_template);
let transactions_only_in_template = processing::build_transactions_only_in_template(
block_id,
&txids_only_in_template,
&template_tx_data.txid_to_txinfo_map,
&template_txid_to_mempool_age,
&mut transactions,
&outpoint_to_sanctioned_utxo_map,
&sanctioned_addresses,
);
let transactions_only_in_block = processing::build_transactions_only_in_block(
block_id,
&txids_only_in_block,
&block_tx_data.txid_to_txinfo_map,
&mut transactions,
&outpoint_to_sanctioned_utxo_map,
&sanctioned_addresses,
);
let sanctioned_transaction_infos = processing::build_sanctioned_transaction_infos(
block_id,
&block_tx_data,
&template_tx_data.txids,
&template_tx_data.txid_to_txinfo_map,
&txids_only_in_block,
&outpoint_to_sanctioned_utxo_map,
&sanctioned_addresses,
&mut transactions,
);
if !sanctioned_transaction_infos.is_empty() {
log::info!(
target: LOG_TARGET_STATS,
"There are a total of {} sanctioned transactions in this template and block.",
sanctioned_transaction_infos.len()
);
metrics::STAT_SANCTIONED_TRANSACTIONS.inc_by(sanctioned_transaction_infos.len() as u64);
}
let debug_template_selection_infos = processing::build_debug_template_selection_infos(
block_id,
last_templates,
block_tx_data.txids,
template.current_time,
);
if let Err(e) =
db::insert_transactions(transactions.values().cloned().collect(), &mut connection)
{
processing::log_processing_error(&format!("Could not insert the transactions into the database. Skipping the remaining processing. Unclean database state! Error: {}", e));
return;
}
if let Err(e) =
db::insert_transactions_only_in_block(transactions_only_in_block, &mut connection)
{
processing::log_processing_error(&format!("Could not insert the transactions_only_in_block into the database. Skipping the remaining processing. Unclean database state! Error: {}", e));
return;
}
if let Err(e) =
db::insert_transactions_only_in_template(transactions_only_in_template, &mut connection)
{
processing::log_processing_error(&format!("Could not insert the transactions_only_in_template into the database. Skipping the remaining processing. Unclean database state! Error: {}", e));
return;
}
if let Err(e) =
db::insert_sanctioned_transaction_infos(sanctioned_transaction_infos, &mut connection)
{
processing::log_processing_error(&format!("Could not insert the sanctioned_transaction_infos into the database. Skipping the remaining processing. Unclean database state! Error: {}", e));
return;
}
if let Err(e) = db::insert_conflicting_transactions(conflicting_transactions, &mut connection) {
processing::log_processing_error(&format!("Could not insert the conflicting_transactions into the database. Skipping the remaining processing. Unclean database state! Error: {}", e));
return;
}
let newly_sactioned_utxos =
processing::build_newly_created_sanctioned_utxos(bitcoin_block, &sanctioned_addresses);
if !newly_sactioned_utxos.is_empty() {
log::info!(target: "sanctioned_utxos", "Inserting {} new sanctioned UTXOs into the database.", newly_sactioned_utxos.len());
if let Err(e) = db::insert_sanctioned_utxos(&newly_sactioned_utxos, &mut connection) {
processing::log_processing_error(&format!("Could not insert the newly_sactioned_utxos into the database. Skipping the remaining processing. Unclean database state! Error: {}", e));
return;
}
}
if let Err(e) =
db::insert_debug_template_selection_infos(debug_template_selection_infos, &mut connection)
{
log::warn!(target: processing::LOG_TARGET_PROCESSING, "Could not insert the debug_template_selection_infos into the database. Non-critical. Error: {}", e);
return;
}
last_templates.clear();
}
fn select_best_template_for_block(
last_templates: &VecDeque<GetBlockTemplateResult>,
block_txids: HashSet<Txid>,
) -> &GetBlockTemplateResult {
assert!(!last_templates.is_empty());
last_templates
.iter()
.min_by_key(|t| {
let template_txids: HashSet<Txid> = t.transactions.iter().map(|t| t.txid).collect();
let extra = block_txids.difference(&template_txids).count();
let missing = template_txids.difference(&block_txids).count();
missing + extra
})
.unwrap() // we can unwrap the Option here as we WILL find a minimum if the last_templates is not empty (which is asserted).
}
fn log_template_infos(t: &GetBlockTemplateResult) {
let template_sigops = t
.transactions
.iter()
.map(|tx| tx.sigops as u64)
.sum::<u64>();
log::info!(
target: LOG_TARGET_STATS,
"New Template based on {} | height {} | {} tx | coinbase {} | sigops {}",
t.previous_block_hash,
t.height,
t.transactions.len(),
t.coinbase_value,
template_sigops,
);
metrics::STAT_CURRENT_TEMPLATE_TRANSACTIONS_GAUGE.set(t.transactions.len() as i64);
metrics::STAT_CURRENT_TEMPLATE_COINBASE_VALUE_GAUGE.set(t.coinbase_value.to_sat() as i64);
metrics::STAT_CURRENT_TEMPLATE_SIGOPS_GAUGE.set(template_sigops as i64);
}
fn scantxoutset_sanctioned_tx(
addrs: Vec<String>,
rpc: &Client,
) -> Result<
(
Vec<shared_model::SanctionedUtxo>,
shared_model::SanctionedUtxoScanInfo,
),
Error,
> {
log::info!(
target: LOG_TARGET_UTXOSETSCAN,
"Starting UTXO set scan for Sanctioned UTXOs with {} addresses.",
addrs.len()
);
let descriptors: Vec<ScanTxOutRequest> = addrs
.iter()
.filter(|addr| {
let address: Result<Address<NetworkUnchecked>, ParseError> = addr.parse();
match address {
Ok(_) => true,
Err(e) => {
log::warn!("Could not parse address='{}' - skipping: {}", addr, e);
false
}
}
})
.map(|addr| ScanTxOutRequest::Single(format!("addr({})", addr)))
.collect();
let start = Instant::now();
let scan_result = rpc.scan_tx_out_set_blocking(&descriptors)?;
let duration = start.elapsed();
log::info!(
target: LOG_TARGET_UTXOSETSCAN,
"Completed UTXO set scan for Sanctioned UTXOs in {} seconds: {} Sanctioned UTXOs found",
duration.as_secs(),
scan_result.unspents.len()
);
let scan_info = shared_model::SanctionedUtxoScanInfo {
end_time: chrono::Utc::now().naive_utc(),
end_height: scan_result.height.unwrap_or_default() as i32,
duration_seconds: duration.as_secs() as i32,
utxo_count: scan_result.unspents.len() as i32,
utxo_amount: scan_result.total_amount.to_sat() as i64,
};
let utxos = scan_result
.unspents
.iter()
.map(|utxo| {
let mut txid_reversed = utxo.txid.to_byte_array().to_vec();
txid_reversed.reverse();
shared_model::SanctionedUtxo {
txid: txid_reversed,
vout: utxo.vout as i32,
script_pubkey: utxo.script_pub_key.to_bytes(),
amount: utxo.amount.to_sat() as i64,
height: utxo.height as i32,
}
})
.collect();
Ok((utxos, scan_info))
}
fn start_sanctioned_utxos_scan_thread(rpc_client: Client, db_pool: db_pool::PgPool) {
thread::spawn(move || loop {
let mut conn = &mut match db_pool.get() {
Ok(c) => c,
Err(e) => {
log::error!(
target: LOG_TARGET_UTXOSETSCAN,
"Could not get a connection from the db_pool. Retrying in {:?}. Error: {}",
WAIT_TIME_BETWEEN_FAILED_UTXO_SET_SCANS,
e
);
thread::sleep(WAIT_TIME_BETWEEN_FAILED_UTXO_SET_SCANS);
continue;
}
};
let sanctioned_addresses: Vec<String> = match db::sanctioned_addresses(&mut conn) {
Ok(sa) => sa.iter().map(|a| a.address.clone()).collect(),
Err(e) => {
log::error!(
target: LOG_TARGET_UTXOSETSCAN,
"Could not load sanctioned addressses from the database. Retrying in {:?}. Error: {}",
WAIT_TIME_BETWEEN_FAILED_UTXO_SET_SCANS,
e
);
thread::sleep(WAIT_TIME_BETWEEN_FAILED_UTXO_SET_SCANS);
continue;
}
};
let (sanctioned_utxos, scan_info): (
Vec<shared_model::SanctionedUtxo>,
shared_model::SanctionedUtxoScanInfo,
) = match scantxoutset_sanctioned_tx(sanctioned_addresses, &rpc_client) {
Ok(scan_results) => scan_results,
Err(e) => {
log::error!(
target: LOG_TARGET_UTXOSETSCAN,
"Could not scan the UTXO set for sanctioned UTXOs. Retrying in {:?}. Error: {}",
WAIT_TIME_BETWEEN_FAILED_UTXO_SET_SCANS,
e
);
metrics::ERROR_RPC.inc();
thread::sleep(WAIT_TIME_BETWEEN_FAILED_UTXO_SET_SCANS);
continue;
}
};
if let Err(err) = db::insert_sanctioned_utxo_scan_info(&scan_info, &mut conn) {
log::error!(
target: LOG_TARGET_UTXOSETSCAN,
"Could not insert UTXO Set scan information into the database: {}",
err
);
} else if let Err(err) = db::clean_and_insert_sanctioned_utxos(&sanctioned_utxos, &mut conn)
{
log::error!(
target: LOG_TARGET_UTXOSETSCAN,
"Could not insert UTXO Set scan information into the database: {}",
err
);
};
log::info!(
target: LOG_TARGET_UTXOSETSCAN,
"Waiting {} seconds before the next UTXO set rescan",
WAIT_TIME_BETWEEN_UTXO_SET_SCANS.as_secs()
);
thread::sleep(WAIT_TIME_BETWEEN_UTXO_SET_SCANS);
});
}
fn retag_transactions(rpc_client: Client, db_pool: db_pool::PgPool) {
thread::spawn(move || {
log::info!(
target: LOG_TARGET_RETAG_TX,
"Starting to retag transactions. This might take a while.",
);
let mut conn = &mut match db_pool.get() {
Ok(c) => c,
Err(e) => {
log::error!(
target: LOG_TARGET_RETAG_TX,
"Could not get a connection from the db_pool. Error: {}",
e
);
return;
}
};
let transactions_in_db = match db::all_transactions(&mut conn) {
Ok(blocks) => blocks,
Err(e) => {
log::error!(
target: LOG_TARGET_RETAG_TX,
"Could not load transactions from database: {}",
e
);
return;
}
};
let sanctioned_addresses = match db::sanctioned_addresses(&mut conn) {
Ok(addresses) => addresses.iter().map(|a| a.address.clone()).collect(),
Err(e) => {
log::error!(
target: LOG_TARGET_RETAG_TX,
"Could not load sanctioned addresses from database: {}",
e
);
return;