-
Notifications
You must be signed in to change notification settings - Fork 6
/
lib.rs
670 lines (658 loc) · 29 KB
/
lib.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
//! Indexes historical block data into the PostreSQL database instance.
#![warn(clippy::disallowed_types)]
use crate::event::process_event;
use async_lock::Mutex;
use async_trait::async_trait;
use lazy_static::lazy_static;
use once_cell::sync::OnceCell;
use rustc_hash::FxHashMap as HashMap;
use std::sync::{
atomic::{AtomicBool, Ordering},
Arc, RwLock,
};
use subvt_config::Config;
use subvt_persistence::postgres::network::PostgreSQLNetworkStorage;
use subvt_service_common::Service;
use subvt_substrate_client::SubstrateClient;
use subvt_types::substrate::error::DecodeError;
use subvt_types::substrate::event::SubstrateEvent;
use subvt_types::substrate::metadata::get_metadata_expected_block_time_millis;
use subvt_types::substrate::ValidityAttestation;
use subvt_types::{
crypto::AccountId,
substrate::{Era, EraStakers, ValidatorStake},
};
mod event;
mod extrinsic;
mod metrics;
lazy_static! {
static ref CONFIG: Config = Config::default();
static ref IS_BUSY: AtomicBool = AtomicBool::new(false);
}
#[derive(Default)]
pub struct BlockProcessor;
#[derive(Default)]
struct RuntimeInformation {
pub era_index: u32,
pub epoch_index: u64,
}
impl BlockProcessor {
async fn persist_era_validators_and_stakers(
&self,
substrate_client: &SubstrateClient,
postgres: &PostgreSQLNetworkStorage,
era: &Era,
block_hash: &str,
active_validator_account_ids: &[AccountId],
era_stakers: &EraStakers,
) -> anyhow::Result<()> {
log::info!("Persist era #{} validators.", era.index);
let all_validator_account_ids = substrate_client
.get_all_validator_account_ids(block_hash)
.await?;
let bonded_account_id_map = substrate_client
.get_bonded_account_id_map(&all_validator_account_ids, block_hash)
.await?;
let validator_stake_map = {
let mut validator_stake_map: HashMap<AccountId, ValidatorStake> = HashMap::default();
for validator_stake in &era_stakers.stakers {
validator_stake_map.insert(validator_stake.account.id, validator_stake.clone());
}
validator_stake_map
};
let validator_prefs_map = substrate_client
.get_era_validator_prefs(era.index, block_hash)
.await?;
postgres
.save_era_validators(
era.index,
active_validator_account_ids,
&all_validator_account_ids,
&bonded_account_id_map,
&validator_stake_map,
&validator_prefs_map,
)
.await?;
postgres.save_era_stakers(era_stakers).await?;
log::info!("Persisted era #{} validators and stakers.", era.index);
Ok(())
}
async fn persist_era_reward_points(
&self,
substrate_client: &SubstrateClient,
postgres: &PostgreSQLNetworkStorage,
block_hash: &str,
era_index: u32,
) -> anyhow::Result<()> {
if !postgres.era_exists(era_index).await? {
log::info!(
"Era {} does not exist in the database. Cannot persist reward points.",
era_index
);
return Ok(());
}
let era_reward_points = substrate_client
.get_era_reward_points(era_index, block_hash)
.await?;
postgres
.update_era_reward_points(era_index, era_reward_points.total)
.await?;
let mut era_reward_points_map: HashMap<AccountId, u32> = HashMap::default();
era_reward_points
.individual
.iter()
.for_each(|(account_id_32, reward_points)| {
let account_id_bytes: &[u8; 32] = account_id_32.as_ref();
let account_id = AccountId::new(*account_id_bytes);
era_reward_points_map.insert(account_id, *reward_points);
});
postgres
.update_era_validator_reward_points(era_index, era_reward_points_map)
.await?;
log::info!("Era {} rewards persisted.", era_index);
Ok(())
}
async fn process_block(
&self,
substrate_client: &mut SubstrateClient,
runtime_information: &Arc<RwLock<RuntimeInformation>>,
postgres: &PostgreSQLNetworkStorage,
block_number: u64,
persist_era_reward_points: bool,
) -> anyhow::Result<()> {
let block_hash = substrate_client.get_block_hash(block_number).await?;
let block_header = substrate_client.get_block_header(&block_hash).await?;
let maybe_validator_index = block_header.get_validator_index();
let runtime_upgrade_info = substrate_client
.get_last_runtime_upgrade_info(&block_hash)
.await?;
// check metadata version
if substrate_client.last_runtime_upgrade_info.spec_version
!= runtime_upgrade_info.spec_version
{
log::info!(
"Different runtime version #{} than client's #{}. Will reset metadata.",
runtime_upgrade_info.spec_version,
substrate_client.last_runtime_upgrade_info.spec_version
);
substrate_client
.set_metadata_at_block(block_number, &block_hash)
.await?;
log::info!(
"Runtime {} metadata fetched.",
substrate_client.last_runtime_upgrade_info.spec_version
);
}
let (last_era_index, last_epoch_index) = {
let runtime_information = runtime_information.read().unwrap();
(
runtime_information.era_index,
runtime_information.epoch_index,
)
};
let active_era = substrate_client.get_active_era(&block_hash).await?;
let current_epoch = substrate_client.get_current_epoch(&block_hash).await?;
let active_validator_account_ids = substrate_client
.get_active_validator_account_ids(&block_hash)
.await?;
if last_epoch_index != current_epoch.index || last_era_index != active_era.index {
let era_stakers = substrate_client
.get_era_stakers(&active_era, &block_hash)
.await?;
if last_epoch_index != current_epoch.index {
log::info!("New epoch. Persist epoch, and persist era if it doesn't exist.");
let total_stake = substrate_client
.get_era_total_stake(active_era.index, &block_hash)
.await?;
postgres
.save_era(&active_era, total_stake, &era_stakers)
.await?;
postgres
.save_epoch(¤t_epoch, active_era.index)
.await?;
// save session para validators
if let Some(para_validator_indices) = substrate_client
.get_paras_active_validator_indices(&block_hash)
.await?
{
log::info!(
"Persist {} session para validators.",
para_validator_indices.len()
);
let para_validator_groups = substrate_client
.get_para_validator_groups(&block_hash)
.await?;
for (group_index, group_para_validator_indices) in
para_validator_groups.iter().enumerate()
{
for group_para_validator_index in group_para_validator_indices {
let active_validator_index =
para_validator_indices[*group_para_validator_index as usize];
let active_validator_account_id =
active_validator_account_ids[active_validator_index as usize];
postgres
.save_session_para_validator(
active_era.index,
current_epoch.index,
&active_validator_account_id,
active_validator_index,
group_index as u32,
*group_para_validator_index,
)
.await?;
}
}
} else {
log::info!("Parachains not active at this block height.");
}
}
if last_era_index != active_era.index {
let era_stakers = substrate_client
.get_era_stakers(&active_era, &block_hash)
.await?;
self.persist_era_validators_and_stakers(
substrate_client,
postgres,
&active_era,
block_hash.as_str(),
&active_validator_account_ids,
&era_stakers,
)
.await?;
// update last era
let last_era_total_validator_reward = substrate_client
.get_era_total_validator_reward(active_era.index - 1, &block_hash)
.await?;
postgres
.update_era_total_validator_reward(
active_era.index - 1,
last_era_total_validator_reward,
)
.await?;
self.persist_era_reward_points(
substrate_client,
postgres,
&block_hash,
active_era.index - 1,
)
.await?;
}
}
if persist_era_reward_points {
self.persist_era_reward_points(
substrate_client,
postgres,
&block_hash,
active_era.index,
)
.await?;
}
{
let mut runtime_information = runtime_information.write().unwrap();
runtime_information.era_index = active_era.index;
runtime_information.epoch_index = current_epoch.index;
}
let event_results = substrate_client.get_block_events(&block_hash).await?;
log::info!(
"Got {} events for block #{}.",
event_results.len(),
block_number
);
let extrinsic_results = substrate_client.get_block_extrinsics(&block_hash).await?;
log::info!(
"Got {} extrinsics for block #{}.",
extrinsic_results.len(),
block_number
);
let block_timestamp = substrate_client.get_block_timestamp(&block_hash).await?;
let maybe_author_account_id = if let Some(validator_index) = maybe_validator_index {
active_validator_account_ids
.get(validator_index)
.map(|a| a.to_owned())
} else {
None
};
let runtime_version = substrate_client.last_runtime_upgrade_info.spec_version as i16;
postgres
.save_finalized_block(
&block_hash,
&block_header,
block_timestamp,
maybe_author_account_id,
(active_era.index, current_epoch.index as u32),
(14, runtime_version),
)
.await?;
// process/persist events
let mut extrinsic_event_map: HashMap<u32, Vec<(usize, SubstrateEvent)>> =
HashMap::default();
for (index, event_result) in event_results.iter().enumerate() {
match event_result {
Ok(event) => {
if let Some(extrinsic_index) = event.get_extrinsic_index() {
if let Some(extrinsic_events) =
extrinsic_event_map.get_mut(&extrinsic_index)
{
extrinsic_events.push((index, event.clone()))
} else {
extrinsic_event_map
.insert(extrinsic_index, vec![(index, event.clone())]);
}
}
if let Err(error) = process_event(
substrate_client,
postgres,
current_epoch.index,
&block_hash,
block_number,
block_timestamp,
index,
event,
)
.await
{
let error_log = format!(
"Error while processing event #{index} of block #{block_number}: {error:?}",
);
log::error!("{}", error_log);
metrics::event_process_error_count().inc();
postgres
.save_event_process_error_log(
&block_hash,
block_number,
index,
"process",
&error_log,
)
.await?;
}
}
Err(decode_error) => match decode_error {
DecodeError::Error(error_log) => {
metrics::event_process_error_count().inc();
postgres
.save_event_process_error_log(
&block_hash,
block_number,
index,
"decode",
error_log,
)
.await?;
panic!("Panic due to event decode error: {error_log:?}");
/*
log::error!("Event decode error - skip the rest of the events in block: {error_log:?}");
break;
*/
}
},
}
}
// persist extrinsics
for (index, extrinsic_result) in extrinsic_results.iter().enumerate() {
match extrinsic_result {
Ok(extrinsic) => {
// check events for batch & batch_all
if let Err(error) = self
.process_extrinsic(
substrate_client,
postgres,
block_hash.clone(),
block_number,
&active_validator_account_ids,
index,
false,
&None,
None,
None,
extrinsic_event_map
.get_mut(&(index as u32))
.unwrap_or(&mut vec![]),
false,
extrinsic,
)
.await
{
let error_log = format!(
"Error while processing extrinsic #{index} of block #{block_number}: {error:?}",
);
log::error!("{}", error_log);
metrics::extrinsic_process_error_count().inc();
postgres
.save_extrinsic_process_error_log(
&block_hash,
block_number,
index,
"process",
&error_log,
)
.await?;
}
}
Err(decode_error) => match decode_error {
DecodeError::Error(error_log) => {
metrics::extrinsic_process_error_count().inc();
postgres
.save_extrinsic_process_error_log(
&block_hash,
block_number,
index,
"decode",
error_log,
)
.await?;
panic!("Panic due to extrinsic decode error: {error_log}");
}
},
}
}
// para core assignments
if let Ok(Some(para_core_assignments)) = substrate_client
.get_para_core_assignments(&block_hash)
.await
{
for para_core_assignment in ¶_core_assignments {
postgres
.save_para_core_assignment(&block_hash, para_core_assignment)
.await?;
}
log::debug!(
"Processed {} para core scheduler assignments.",
para_core_assignments.len()
);
} else if let Ok(Some(para_core_assignments)) = substrate_client
.get_para_core_assignments_legacy(&block_hash)
.await
{
for para_core_assignment in ¶_core_assignments {
postgres
.save_para_core_assignment(&block_hash, para_core_assignment)
.await?;
}
log::debug!(
"Processed {} para core scheduler assignments.",
para_core_assignments.len()
);
}
// para groups
let para_groups = substrate_client
.get_para_validator_groups(&block_hash)
.await?;
// para votes
if let Some(votes) = substrate_client.get_para_votes(&block_hash).await? {
let session_index: u32 = votes.session;
let mut total_vote_count = 0;
for backing in &votes.backing_validators_per_candidate {
let para_id: u32 = backing.0.descriptor.para_id.into();
// get scheduled para validators from previous block
total_vote_count += backing.1.len();
let mut voted_para_validator_indices = vec![];
for validator_vote in &backing.1 {
let para_validator_index = validator_vote.0 .0;
let is_explicit = match validator_vote.1 {
ValidityAttestation::Implicit(_) => false,
ValidityAttestation::Explicit(_) => true,
};
voted_para_validator_indices.push(para_validator_index);
postgres
.save_para_vote(
&block_hash,
session_index,
para_id,
para_validator_index,
Some(is_explicit),
)
.await?;
}
// save missing votes
if let Some(first_para_validator_index) = voted_para_validator_indices.first() {
for para_group in ¶_groups {
if para_group.contains(first_para_validator_index) {
for para_validator_index in para_group {
if !voted_para_validator_indices.contains(para_validator_index) {
postgres
.save_para_vote(
&block_hash,
session_index,
para_id,
*para_validator_index,
None,
)
.await?;
}
}
break;
}
}
}
}
log::debug!(
"Processed {} para votes for {} paras.",
total_vote_count,
votes.backing_validators_per_candidate.len(),
);
}
// notify
postgres
.notify_block_processed(block_number, block_hash)
.await?;
Ok(())
}
}
/// Service implementation.
#[async_trait(?Send)]
impl Service for BlockProcessor {
fn get_metrics_server_addr() -> (&'static str, u16) {
(
CONFIG.metrics.host.as_str(),
CONFIG.metrics.block_processor_port,
)
}
async fn run(&'static self) -> anyhow::Result<()> {
loop {
if IS_BUSY.load(Ordering::SeqCst) {
let delay_seconds = CONFIG.common.recovery_retry_seconds;
log::warn!(
"Busy processing past blocks. Hold re-instantiation for {} seconds.",
delay_seconds
);
tokio::time::sleep(std::time::Duration::from_secs(delay_seconds)).await;
continue;
}
let error_cell: Arc<OnceCell<anyhow::Error>> = Arc::new(OnceCell::new());
let block_subscription_substrate_client = SubstrateClient::new(
CONFIG.substrate.rpc_url.as_str(),
CONFIG.substrate.network_id,
CONFIG.substrate.connection_timeout_seconds,
CONFIG.substrate.request_timeout_seconds,
)
.await?;
let block_processor_substrate_client = Arc::new(Mutex::new(
SubstrateClient::new(
CONFIG.substrate.rpc_url.as_str(),
CONFIG.substrate.network_id,
CONFIG.substrate.connection_timeout_seconds,
CONFIG.substrate.request_timeout_seconds,
)
.await?,
));
let runtime_information = Arc::new(RwLock::new(RuntimeInformation::default()));
let postgres = Arc::new(
PostgreSQLNetworkStorage::new(&CONFIG, CONFIG.get_network_postgres_url()).await?,
);
// init extrinsic and event process error count metrics
metrics::extrinsic_process_error_count()
.set(postgres.get_extrinsic_process_error_log_count().await? as i64);
metrics::event_process_error_count()
.set(postgres.get_event_process_error_log_count().await? as i64);
block_subscription_substrate_client.subscribe_to_finalized_blocks(
CONFIG.substrate.request_timeout_seconds,
|finalized_block_header| async {
let error_cell = error_cell.clone();
if let Some(error) = error_cell.get() {
return Err(anyhow::anyhow!("{:?}", error));
}
let finalized_block_number = match finalized_block_header.get_number() {
Ok(block_number) => block_number,
Err(error) => {
log::error!("Cannot get block number for header: {:?}", finalized_block_header);
return Err(anyhow::anyhow!("{:?}", error));
}
};
metrics::target_finalized_block_number().set(finalized_block_number as i64);
if IS_BUSY.load(Ordering::SeqCst) {
log::debug!("Busy processing past blocks. Skip block #{} for now.", finalized_block_number);
return Ok(());
}
let block_processor_substrate_client = block_processor_substrate_client.clone();
let runtime_information = runtime_information.clone();
let postgres = postgres.clone();
IS_BUSY.store(true, Ordering::SeqCst);
tokio::spawn(async move {
let mut block_processor_substrate_client = block_processor_substrate_client.lock().await;
let processed_block_height = match postgres.get_processed_block_height().await {
Ok(processed_block_height) => processed_block_height,
Err(error) => {
log::error!("Cannot get processed block height from the database: {:?}", error);
let _ = error_cell.set(error);
IS_BUSY.store(false, Ordering::SeqCst);
return;
}
};
if processed_block_height < (finalized_block_number - 1) {
let mut block_number = std::cmp::max(
processed_block_height,
CONFIG.block_processor.start_block_number
);
while block_number <= finalized_block_number {
log::info!(
"Process block #{}. Target #{}.",
block_number,
finalized_block_number
);
let start = std::time::Instant::now();
let process_result = self.process_block(
&mut block_processor_substrate_client,
&runtime_information,
&postgres,
block_number,
false,
).await;
metrics::block_processing_time_ms().observe(start.elapsed().as_millis() as f64);
match process_result {
Ok(_) => {
metrics::processed_finalized_block_number().set(block_number as i64);
block_number += 1
},
Err(error) => {
log::error!("{:?}", error);
log::error!(
"History block processing failed for block #{}.",
block_number,
);
let _ = error_cell.set(error);
break;
}
}
}
} else {
// update current era reward points every 3 minutes
let blocks_per_3_minutes = 3 * 60 * 1000
/ get_metadata_expected_block_time_millis(&block_processor_substrate_client.metadata).unwrap();
log::info!("Process block #{}.", finalized_block_number);
let start = std::time::Instant::now();
let update_result = self.process_block(
&mut block_processor_substrate_client,
&runtime_information,
&postgres,
finalized_block_number,
finalized_block_number % blocks_per_3_minutes == 0,
).await;
metrics::block_processing_time_ms().observe(start.elapsed().as_millis() as f64);
match update_result {
Ok(_) => {
metrics::processed_finalized_block_number().set(finalized_block_number as i64);
},
Err(error) => {
log::error!("{:?}", error);
log::error!(
"Block processing failed for finalized block #{}. Will try again with the next block.",
finalized_block_header.get_number().unwrap_or(0),
);
let _ = error_cell.set(error);
}
}
}
IS_BUSY.store(false, Ordering::SeqCst);
});
Ok(())
}).await;
let delay_seconds = CONFIG.common.recovery_retry_seconds;
log::error!(
"Finalized block subscription exited. Will refresh connection and subscription after {} seconds.",
delay_seconds
);
tokio::time::sleep(std::time::Duration::from_secs(delay_seconds)).await;
}
}
}