-
Notifications
You must be signed in to change notification settings - Fork 11.4k
/
Copy pathauthority.rs
4495 lines (4103 loc) · 175 KB
/
authority.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
// Copyright (c) 2021, Facebook, Inc. and its affiliates
// Copyright (c) Mysten Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
use crate::authority::authority_store_types::{StoreObject, StoreObjectWrapper};
use crate::verify_indexes::verify_indexes;
use anyhow::anyhow;
use arc_swap::{ArcSwap, Guard};
use async_trait::async_trait;
use chrono::prelude::*;
use fastcrypto::encoding::Base58;
use fastcrypto::encoding::Encoding;
use fastcrypto::hash::MultisetHash;
use futures::stream::FuturesUnordered;
use itertools::Itertools;
use move_binary_format::CompiledModule;
use move_bytecode_utils::module_cache::GetModule;
use move_core_types::language_storage::ModuleId;
use move_core_types::value::MoveStructLayout;
use mysten_metrics::{TX_TYPE_SHARED_OBJ_TX, TX_TYPE_SINGLE_WRITER_TX};
use parking_lot::Mutex;
use prometheus::{
register_histogram_vec_with_registry, register_histogram_with_registry,
register_int_counter_vec_with_registry, register_int_counter_with_registry,
register_int_gauge_vec_with_registry, register_int_gauge_with_registry, Histogram, IntCounter,
IntCounterVec, IntGauge, IntGaugeVec, Registry,
};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use std::{
collections::{HashMap, HashSet},
fs,
pin::Pin,
sync::Arc,
thread,
};
use sui_config::node::StateDebugDumpConfig;
use sui_config::NodeConfig;
use sui_types::execution::DynamicallyLoadedObjectMetadata;
use tap::{TapFallible, TapOptional};
use tokio::sync::mpsc::unbounded_channel;
use tokio::sync::oneshot;
use tokio_retry::strategy::{jitter, ExponentialBackoff};
use tracing::{debug, error, info, instrument, trace, warn, Instrument};
use self::authority_store::ExecutionLockWriteGuard;
use self::authority_store_pruner::AuthorityStorePruningMetrics;
pub use authority_notify_read::EffectsNotifyRead;
pub use authority_store::{AuthorityStore, ResolverWrapper, UpdateType};
use mysten_metrics::{monitored_scope, spawn_monitored_task};
use once_cell::sync::OnceCell;
use shared_crypto::intent::{Intent, IntentScope};
use sui_archival::reader::ArchiveReaderBalancer;
use sui_config::certificate_deny_config::CertificateDenyConfig;
use sui_config::genesis::Genesis;
use sui_config::node::{
AuthorityStorePruningConfig, DBCheckpointConfig, ExpensiveSafetyCheckConfig,
};
use sui_config::transaction_deny_config::TransactionDenyConfig;
use sui_framework::{BuiltInFramework, SystemPackage};
use sui_json_rpc_types::{
DevInspectResults, DryRunTransactionBlockResponse, EventFilter, SuiEvent, SuiMoveValue,
SuiObjectDataFilter, SuiTransactionBlockData, SuiTransactionBlockEffects,
SuiTransactionBlockEvents, TransactionFilter,
};
use sui_macros::{fail_point, fail_point_async};
use sui_protocol_config::{ProtocolConfig, SupportedProtocolVersions};
use sui_storage::indexes::{CoinInfo, ObjectIndexChanges};
use sui_storage::key_value_store::{TransactionKeyValueStore, TransactionKeyValueStoreTrait};
use sui_storage::key_value_store_metrics::KeyValueStoreMetrics;
use sui_storage::IndexStore;
use sui_types::authenticator_state::get_authenticator_state;
use sui_types::committee::{EpochId, ProtocolVersion};
use sui_types::crypto::{default_hash, AuthoritySignInfo, Signer};
use sui_types::digests::ChainIdentifier;
use sui_types::digests::TransactionEventsDigest;
use sui_types::dynamic_field::{DynamicFieldInfo, DynamicFieldName, DynamicFieldType};
use sui_types::effects::{
SignedTransactionEffects, TransactionEffects, TransactionEffectsAPI, TransactionEvents,
VerifiedCertifiedTransactionEffects, VerifiedSignedTransactionEffects,
};
use sui_types::error::{ExecutionError, UserInputError};
use sui_types::event::{Event, EventID};
use sui_types::executable_transaction::VerifiedExecutableTransaction;
use sui_types::gas::{GasCostSummary, SuiGasStatus};
use sui_types::inner_temporary_store::{
InnerTemporaryStore, ObjectMap, TemporaryModuleResolver, TxCoins, WrittenObjects,
};
use sui_types::message_envelope::Message;
use sui_types::messages_checkpoint::{
CertifiedCheckpointSummary, CheckpointCommitment, CheckpointContents, CheckpointContentsDigest,
CheckpointDigest, CheckpointSequenceNumber, CheckpointSummary, CheckpointTimestamp,
VerifiedCheckpoint,
};
use sui_types::messages_checkpoint::{CheckpointRequest, CheckpointResponse};
use sui_types::messages_consensus::AuthorityCapabilities;
use sui_types::messages_grpc::{
HandleTransactionResponse, ObjectInfoRequest, ObjectInfoRequestKind, ObjectInfoResponse,
TransactionInfoRequest, TransactionInfoResponse, TransactionStatus,
};
use sui_types::metrics::{BytecodeVerifierMetrics, LimitsMetrics};
use sui_types::object::{MoveObject, Owner, PastObjectRead, OBJECT_START_VERSION};
use sui_types::storage::{ObjectKey, ObjectStore, WriteKind};
use sui_types::sui_system_state::epoch_start_sui_system_state::EpochStartSystemStateTrait;
use sui_types::sui_system_state::SuiSystemStateTrait;
use sui_types::sui_system_state::{get_sui_system_state, SuiSystemState};
use sui_types::{
base_types::*,
committee::Committee,
crypto::AuthoritySignature,
error::{SuiError, SuiResult},
fp_ensure,
object::{Object, ObjectFormatOptions, ObjectRead},
transaction::*,
SUI_SYSTEM_ADDRESS,
};
use sui_types::{is_system_package, TypeTag};
use typed_store::Map;
use crate::authority::authority_per_epoch_store::{AuthorityPerEpochStore, CertTxGuard};
use crate::authority::authority_per_epoch_store_pruner::AuthorityPerEpochStorePruner;
use crate::authority::authority_store::{ExecutionLockReadGuard, InputKey, ObjectLockStatus};
use crate::authority::authority_store_pruner::AuthorityStorePruner;
use crate::authority::epoch_start_configuration::EpochStartConfigTrait;
use crate::authority::epoch_start_configuration::EpochStartConfiguration;
use crate::checkpoints::checkpoint_executor::CheckpointExecutor;
use crate::checkpoints::CheckpointStore;
use crate::consensus_adapter::ConsensusAdapter;
use crate::epoch::committee_store::CommitteeStore;
use crate::execution_driver::execution_process;
use crate::module_cache_metrics::ResolverMetrics;
use crate::stake_aggregator::StakeAggregator;
use crate::state_accumulator::{StateAccumulator, WrappedObject};
use crate::subscription_handler::SubscriptionHandler;
use crate::{transaction_input_checker, transaction_manager::TransactionManager};
#[cfg(test)]
#[path = "unit_tests/authority_tests.rs"]
pub mod authority_tests;
#[cfg(test)]
#[path = "unit_tests/batch_transaction_tests.rs"]
mod batch_transaction_tests;
#[cfg(test)]
#[path = "unit_tests/move_integration_tests.rs"]
pub mod move_integration_tests;
#[cfg(test)]
#[path = "unit_tests/gas_tests.rs"]
mod gas_tests;
#[cfg(test)]
#[path = "unit_tests/batch_verification_tests.rs"]
mod batch_verification_tests;
#[cfg(any(test, feature = "test-utils"))]
pub mod authority_test_utils;
pub mod authority_per_epoch_store;
pub mod authority_per_epoch_store_pruner;
pub mod authority_store_pruner;
pub mod authority_store_tables;
pub mod authority_store_types;
pub mod epoch_start_configuration;
pub mod test_authority_builder;
pub(crate) mod authority_notify_read;
pub(crate) mod authority_store;
pub static CHAIN_IDENTIFIER: OnceCell<ChainIdentifier> = OnceCell::new();
/// Prometheus metrics which can be displayed in Grafana, queried and alerted on
pub struct AuthorityMetrics {
tx_orders: IntCounter,
total_certs: IntCounter,
total_cert_attempts: IntCounter,
total_effects: IntCounter,
pub shared_obj_tx: IntCounter,
sponsored_tx: IntCounter,
tx_already_processed: IntCounter,
num_input_objs: Histogram,
num_shared_objects: Histogram,
batch_size: Histogram,
handle_transaction_latency: Histogram,
execute_certificate_latency_single_writer: Histogram,
execute_certificate_latency_shared_object: Histogram,
execute_certificate_with_effects_latency: Histogram,
internal_execution_latency: Histogram,
prepare_certificate_latency: Histogram,
commit_certificate_latency: Histogram,
db_checkpoint_latency: Histogram,
pub(crate) transaction_manager_num_enqueued_certificates: IntCounterVec,
pub(crate) transaction_manager_num_missing_objects: IntGauge,
pub(crate) transaction_manager_num_pending_certificates: IntGauge,
pub(crate) transaction_manager_num_executing_certificates: IntGauge,
pub(crate) transaction_manager_num_ready: IntGauge,
pub(crate) transaction_manager_object_cache_size: IntGauge,
pub(crate) transaction_manager_object_cache_hits: IntCounter,
pub(crate) transaction_manager_object_cache_misses: IntCounter,
pub(crate) transaction_manager_object_cache_evictions: IntCounter,
pub(crate) transaction_manager_package_cache_size: IntGauge,
pub(crate) transaction_manager_package_cache_hits: IntCounter,
pub(crate) transaction_manager_package_cache_misses: IntCounter,
pub(crate) transaction_manager_package_cache_evictions: IntCounter,
pub(crate) execution_driver_executed_transactions: IntCounter,
pub(crate) execution_driver_dispatch_queue: IntGauge,
pub(crate) skipped_consensus_txns: IntCounter,
pub(crate) skipped_consensus_txns_cache_hit: IntCounter,
/// Post processing metrics
post_processing_total_events_emitted: IntCounter,
post_processing_total_tx_indexed: IntCounter,
post_processing_total_tx_had_event_processed: IntCounter,
post_processing_total_failures: IntCounter,
pending_notify_read: IntGauge,
/// Consensus handler metrics
pub consensus_handler_processed_batches: IntCounter,
pub consensus_handler_processed_bytes: IntCounter,
pub consensus_handler_processed: IntCounterVec,
pub consensus_handler_num_low_scoring_authorities: IntGauge,
pub consensus_handler_scores: IntGaugeVec,
pub consensus_committed_subdags: IntCounterVec,
pub consensus_committed_certificates: IntGaugeVec,
pub consensus_committed_user_transactions: IntGaugeVec,
pub limits_metrics: Arc<LimitsMetrics>,
/// bytecode verifier metrics for tracking timeouts
pub bytecode_verifier_metrics: Arc<BytecodeVerifierMetrics>,
pub authenticator_state_update_failed: IntCounter,
}
// Override default Prom buckets for positive numbers in 0-50k range
const POSITIVE_INT_BUCKETS: &[f64] = &[
1., 2., 5., 10., 20., 50., 100., 200., 500., 1000., 2000., 5000., 10000., 20000., 50000.,
];
const LATENCY_SEC_BUCKETS: &[f64] = &[
0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 20.,
30., 60., 90.,
];
impl AuthorityMetrics {
pub fn new(registry: &prometheus::Registry) -> AuthorityMetrics {
let execute_certificate_latency = register_histogram_vec_with_registry!(
"authority_state_execute_certificate_latency",
"Latency of executing certificates, including waiting for inputs",
&["tx_type"],
LATENCY_SEC_BUCKETS.to_vec(),
registry,
)
.unwrap();
let execute_certificate_latency_single_writer =
execute_certificate_latency.with_label_values(&[TX_TYPE_SINGLE_WRITER_TX]);
let execute_certificate_latency_shared_object =
execute_certificate_latency.with_label_values(&[TX_TYPE_SHARED_OBJ_TX]);
Self {
tx_orders: register_int_counter_with_registry!(
"total_transaction_orders",
"Total number of transaction orders",
registry,
)
.unwrap(),
total_certs: register_int_counter_with_registry!(
"total_transaction_certificates",
"Total number of transaction certificates handled",
registry,
)
.unwrap(),
total_cert_attempts: register_int_counter_with_registry!(
"total_handle_certificate_attempts",
"Number of calls to handle_certificate",
registry,
)
.unwrap(),
// total_effects == total transactions finished
total_effects: register_int_counter_with_registry!(
"total_transaction_effects",
"Total number of transaction effects produced",
registry,
)
.unwrap(),
shared_obj_tx: register_int_counter_with_registry!(
"num_shared_obj_tx",
"Number of transactions involving shared objects",
registry,
)
.unwrap(),
sponsored_tx: register_int_counter_with_registry!(
"num_sponsored_tx",
"Number of sponsored transactions",
registry,
)
.unwrap(),
tx_already_processed: register_int_counter_with_registry!(
"num_tx_already_processed",
"Number of transaction orders already processed previously",
registry,
)
.unwrap(),
num_input_objs: register_histogram_with_registry!(
"num_input_objects",
"Distribution of number of input TX objects per TX",
POSITIVE_INT_BUCKETS.to_vec(),
registry,
)
.unwrap(),
num_shared_objects: register_histogram_with_registry!(
"num_shared_objects",
"Number of shared input objects per TX",
POSITIVE_INT_BUCKETS.to_vec(),
registry,
)
.unwrap(),
batch_size: register_histogram_with_registry!(
"batch_size",
"Distribution of size of transaction batch",
POSITIVE_INT_BUCKETS.to_vec(),
registry,
)
.unwrap(),
handle_transaction_latency: register_histogram_with_registry!(
"authority_state_handle_transaction_latency",
"Latency of handling transactions",
LATENCY_SEC_BUCKETS.to_vec(),
registry,
)
.unwrap(),
execute_certificate_latency_single_writer,
execute_certificate_latency_shared_object,
execute_certificate_with_effects_latency: register_histogram_with_registry!(
"authority_state_execute_certificate_with_effects_latency",
"Latency of executing certificates with effects, including waiting for inputs",
LATENCY_SEC_BUCKETS.to_vec(),
registry,
)
.unwrap(),
internal_execution_latency: register_histogram_with_registry!(
"authority_state_internal_execution_latency",
"Latency of actual certificate executions",
LATENCY_SEC_BUCKETS.to_vec(),
registry,
)
.unwrap(),
prepare_certificate_latency: register_histogram_with_registry!(
"authority_state_prepare_certificate_latency",
"Latency of executing certificates, before committing the results",
LATENCY_SEC_BUCKETS.to_vec(),
registry,
)
.unwrap(),
commit_certificate_latency: register_histogram_with_registry!(
"authority_state_commit_certificate_latency",
"Latency of committing certificate execution results",
LATENCY_SEC_BUCKETS.to_vec(),
registry,
)
.unwrap(),
db_checkpoint_latency: register_histogram_with_registry!(
"db_checkpoint_latency",
"Latency of checkpointing dbs",
LATENCY_SEC_BUCKETS.to_vec(),
registry,
).unwrap(),
transaction_manager_num_enqueued_certificates: register_int_counter_vec_with_registry!(
"transaction_manager_num_enqueued_certificates",
"Current number of certificates enqueued to TransactionManager",
&["result"],
registry,
)
.unwrap(),
transaction_manager_num_missing_objects: register_int_gauge_with_registry!(
"transaction_manager_num_missing_objects",
"Current number of missing objects in TransactionManager",
registry,
)
.unwrap(),
transaction_manager_num_pending_certificates: register_int_gauge_with_registry!(
"transaction_manager_num_pending_certificates",
"Number of certificates pending in TransactionManager, with at least 1 missing input object",
registry,
)
.unwrap(),
transaction_manager_num_executing_certificates: register_int_gauge_with_registry!(
"transaction_manager_num_executing_certificates",
"Number of executing certificates, including queued and actually running certificates",
registry,
)
.unwrap(),
transaction_manager_num_ready: register_int_gauge_with_registry!(
"transaction_manager_num_ready",
"Number of ready transactions in TransactionManager",
registry,
)
.unwrap(),
transaction_manager_object_cache_size: register_int_gauge_with_registry!(
"transaction_manager_object_cache_size",
"Current size of object-availability cache in TransactionManager",
registry,
)
.unwrap(),
transaction_manager_object_cache_hits: register_int_counter_with_registry!(
"transaction_manager_object_cache_hits",
"Number of object-availability cache hits in TransactionManager",
registry,
)
.unwrap(),
transaction_manager_object_cache_misses: register_int_counter_with_registry!(
"transaction_manager_object_cache_misses",
"Number of object-availability cache misses in TransactionManager",
registry,
)
.unwrap(),
transaction_manager_object_cache_evictions: register_int_counter_with_registry!(
"transaction_manager_object_cache_evictions",
"Number of object-availability cache evictions in TransactionManager",
registry,
)
.unwrap(),
transaction_manager_package_cache_size: register_int_gauge_with_registry!(
"transaction_manager_package_cache_size",
"Current size of package-availability cache in TransactionManager",
registry,
)
.unwrap(),
transaction_manager_package_cache_hits: register_int_counter_with_registry!(
"transaction_manager_package_cache_hits",
"Number of package-availability cache hits in TransactionManager",
registry,
)
.unwrap(),
transaction_manager_package_cache_misses: register_int_counter_with_registry!(
"transaction_manager_package_cache_misses",
"Number of package-availability cache misses in TransactionManager",
registry,
)
.unwrap(),
transaction_manager_package_cache_evictions: register_int_counter_with_registry!(
"transaction_manager_package_cache_evictions",
"Number of package-availability cache evictions in TransactionManager",
registry,
)
.unwrap(),
execution_driver_executed_transactions: register_int_counter_with_registry!(
"execution_driver_executed_transactions",
"Cumulative number of transaction executed by execution driver",
registry,
)
.unwrap(),
execution_driver_dispatch_queue: register_int_gauge_with_registry!(
"execution_driver_dispatch_queue",
"Number of transaction pending in execution driver dispatch queue",
registry,
)
.unwrap(),
skipped_consensus_txns: register_int_counter_with_registry!(
"skipped_consensus_txns",
"Total number of consensus transactions skipped",
registry,
)
.unwrap(),
skipped_consensus_txns_cache_hit: register_int_counter_with_registry!(
"skipped_consensus_txns_cache_hit",
"Total number of consensus transactions skipped because of local cache hit",
registry,
)
.unwrap(),
post_processing_total_events_emitted: register_int_counter_with_registry!(
"post_processing_total_events_emitted",
"Total number of events emitted in post processing",
registry,
)
.unwrap(),
post_processing_total_tx_indexed: register_int_counter_with_registry!(
"post_processing_total_tx_indexed",
"Total number of txes indexed in post processing",
registry,
)
.unwrap(),
post_processing_total_tx_had_event_processed: register_int_counter_with_registry!(
"post_processing_total_tx_had_event_processed",
"Total number of txes finished event processing in post processing",
registry,
)
.unwrap(),
post_processing_total_failures: register_int_counter_with_registry!(
"post_processing_total_failures",
"Total number of failure in post processing",
registry,
)
.unwrap(),
pending_notify_read: register_int_gauge_with_registry!(
"pending_notify_read",
"Pending notify read requests",
registry,
)
.unwrap(),
consensus_handler_processed_batches: register_int_counter_with_registry!(
"consensus_handler_processed_batches",
"Number of batches processed by consensus_handler",
registry
).unwrap(),
consensus_handler_processed_bytes: register_int_counter_with_registry!(
"consensus_handler_processed_bytes",
"Number of bytes processed by consensus_handler",
registry
).unwrap(),
consensus_handler_processed: register_int_counter_vec_with_registry!("consensus_handler_processed", "Number of transactions processed by consensus handler", &["class"], registry)
.unwrap(),
consensus_handler_num_low_scoring_authorities: register_int_gauge_with_registry!(
"consensus_handler_num_low_scoring_authorities",
"Number of low scoring authorities based on reputation scores from consensus",
registry
).unwrap(),
consensus_handler_scores: register_int_gauge_vec_with_registry!(
"consensus_handler_scores",
"scores from consensus for each authority",
&["authority"],
registry,
).unwrap(),
consensus_committed_subdags: register_int_counter_vec_with_registry!(
"consensus_committed_subdags",
"Number of committed subdags, sliced by author",
&["authority"],
registry,
).unwrap(),
consensus_committed_certificates: register_int_gauge_vec_with_registry!(
"consensus_committed_certificates",
"Number of committed certificates, sliced by author",
&["authority"],
registry,
).unwrap(),
consensus_committed_user_transactions: register_int_gauge_vec_with_registry!(
"consensus_committed_user_transactions",
"Number of committed user transactions, sliced by submitter",
&["authority"],
registry,
).unwrap(),
limits_metrics: Arc::new(LimitsMetrics::new(registry)),
bytecode_verifier_metrics: Arc::new(BytecodeVerifierMetrics::new(registry)),
authenticator_state_update_failed: register_int_counter_with_registry!(
"authenticator_state_update_failed",
"Number of failed authenticator state updates",
registry,
)
.unwrap(),
}
}
}
/// a Trait object for `Signer` that is:
/// - Pin, i.e. confined to one place in memory (we don't want to copy private keys).
/// - Sync, i.e. can be safely shared between threads.
///
/// Typically instantiated with Box::pin(keypair) where keypair is a `KeyPair`
///
pub type StableSyncAuthoritySigner = Pin<Arc<dyn Signer<AuthoritySignature> + Send + Sync>>;
pub struct AuthorityState {
// Fixed size, static, identity of the authority
/// The name of this authority.
pub name: AuthorityName,
/// The signature key of the authority.
pub secret: StableSyncAuthoritySigner,
/// The database
pub database: Arc<AuthorityStore>, // TODO: remove pub
epoch_store: ArcSwap<AuthorityPerEpochStore>,
pub indexes: Option<Arc<IndexStore>>,
pub subscription_handler: Arc<SubscriptionHandler>,
pub(crate) checkpoint_store: Arc<CheckpointStore>,
committee_store: Arc<CommitteeStore>,
/// Manages pending certificates and their missing input objects.
transaction_manager: Arc<TransactionManager>,
/// Shuts down the execution task. Used only in testing.
#[allow(unused)]
tx_execution_shutdown: Mutex<Option<oneshot::Sender<()>>>,
pub metrics: Arc<AuthorityMetrics>,
_pruner: AuthorityStorePruner,
_authority_per_epoch_pruner: AuthorityPerEpochStorePruner,
/// Take db checkpoints af different dbs
db_checkpoint_config: DBCheckpointConfig,
/// Config controlling what kind of expensive safety checks to perform.
expensive_safety_check_config: ExpensiveSafetyCheckConfig,
transaction_deny_config: TransactionDenyConfig,
certificate_deny_config: CertificateDenyConfig,
/// Config for state dumping on forks
debug_dump_config: StateDebugDumpConfig,
}
/// The authority state encapsulates all state, drives execution, and ensures safety.
///
/// Note the authority operations can be accessed through a read ref (&) and do not
/// require &mut. Internally a database is synchronized through a mutex lock.
///
/// Repeating valid commands should produce no changes and return no error.
impl AuthorityState {
pub fn is_validator(&self, epoch_store: &AuthorityPerEpochStore) -> bool {
epoch_store.committee().authority_exists(&self.name)
}
pub fn is_fullnode(&self, epoch_store: &AuthorityPerEpochStore) -> bool {
!self.is_validator(epoch_store)
}
pub fn committee_store(&self) -> &Arc<CommitteeStore> {
&self.committee_store
}
pub fn clone_committee_store(&self) -> Arc<CommitteeStore> {
self.committee_store.clone()
}
pub fn get_epoch_state_commitments(
&self,
epoch: EpochId,
) -> SuiResult<Option<Vec<CheckpointCommitment>>> {
let commitments =
self.checkpoint_store
.get_epoch_last_checkpoint(epoch)?
.map(|checkpoint| {
checkpoint
.end_of_epoch_data
.as_ref()
.expect("Last checkpoint of epoch expected to have EndOfEpochData")
.epoch_commitments
.clone()
});
Ok(commitments)
}
/// This is a private method and should be kept that way. It doesn't check whether
/// the provided transaction is a system transaction, and hence can only be called internally.
async fn handle_transaction_impl(
&self,
transaction: VerifiedTransaction,
epoch_store: &Arc<AuthorityPerEpochStore>,
) -> SuiResult<VerifiedSignedTransaction> {
let (_gas_status, input_objects) = transaction_input_checker::check_transaction_input(
&self.database,
epoch_store.protocol_config(),
epoch_store.reference_gas_price(),
epoch_store.epoch(),
transaction.data().transaction_data(),
transaction.tx_signatures(),
&self.transaction_deny_config,
&self.metrics.bytecode_verifier_metrics,
)?;
let owned_objects = input_objects.filter_owned_objects();
let signed_transaction = VerifiedSignedTransaction::new(
epoch_store.epoch(),
transaction,
self.name,
&*self.secret,
);
// Check and write locks, to signed transaction, into the database
// The call to self.set_transaction_lock checks the lock is not conflicting,
// and returns ConflictingTransaction error in case there is a lock on a different
// existing transaction.
self.set_transaction_lock(&owned_objects, signed_transaction.clone(), epoch_store)
.await?;
Ok(signed_transaction)
}
/// Initiate a new transaction.
pub async fn handle_transaction(
&self,
epoch_store: &Arc<AuthorityPerEpochStore>,
transaction: VerifiedTransaction,
) -> SuiResult<HandleTransactionResponse> {
fp_ensure!(
!transaction.is_system_tx(),
SuiError::InvalidSystemTransaction
);
let tx_digest = *transaction.digest();
debug!("handle_transaction");
// Ensure an idempotent answer. This is checked before the system_tx check so that
// a validator is able to return the signed system tx if it was already signed locally.
if let Some((_, status)) = self.get_transaction_status(&tx_digest, epoch_store)? {
return Ok(HandleTransactionResponse { status });
}
// CRITICAL! Validators should never sign an external system transaction.
fp_ensure!(
!transaction.is_system_tx(),
SuiError::InvalidSystemTransaction
);
let _metrics_guard = self.metrics.handle_transaction_latency.start_timer();
self.metrics.tx_orders.inc();
// The should_accept_user_certs check here is best effort, because
// between a validator signs a tx and a cert is formed, the validator
// could close the window.
if !epoch_store
.get_reconfig_state_read_lock_guard()
.should_accept_user_certs()
{
return Err(SuiError::ValidatorHaltedAtEpochEnd);
}
// Checks to see if the transaction has expired
if match &transaction.inner().data().transaction_data().expiration() {
TransactionExpiration::None => false,
TransactionExpiration::Epoch(epoch) => *epoch < epoch_store.epoch(),
} {
return Err(SuiError::TransactionExpired);
}
let signed = self.handle_transaction_impl(transaction, epoch_store).await;
match signed {
Ok(s) => Ok(HandleTransactionResponse {
status: TransactionStatus::Signed(s.into_inner().into_sig()),
}),
// It happens frequently that while we are checking the validity of the transaction, it
// has just been executed.
// In that case, we could still return Ok to avoid showing confusing errors.
Err(err) => Ok(HandleTransactionResponse {
status: self
.get_transaction_status(&tx_digest, epoch_store)?
.ok_or(err)?
.1,
}),
}
}
pub(crate) fn check_system_overload(
&self,
consensus_adapter: &Arc<ConsensusAdapter>,
tx_data: &SenderSignedData,
) -> SuiResult {
self.transaction_manager.check_execution_overload(tx_data)?;
consensus_adapter.check_consensus_overload()?;
Ok(())
}
/// Executes a transaction that's known to have correct effects.
/// For such transaction, we don't have to wait for consensus to set shared object
/// locks because we already know the shared object versions based on the effects.
/// This function can be called by a fullnode only.
#[instrument(level = "trace", skip_all)]
pub async fn fullnode_execute_certificate_with_effects(
&self,
transaction: &VerifiedExecutableTransaction,
// NOTE: the caller of this must promise to wait until it
// knows for sure this tx is finalized, namely, it has seen a
// CertifiedTransactionEffects or at least f+1 identifical effects
// digests matching this TransactionEffectsEnvelope, before calling
// this function, in order to prevent a byzantine validator from
// giving us incorrect effects.
effects: &VerifiedCertifiedTransactionEffects,
epoch_store: &Arc<AuthorityPerEpochStore>,
) -> SuiResult {
assert!(self.is_fullnode(epoch_store));
let _metrics_guard = self
.metrics
.execute_certificate_with_effects_latency
.start_timer();
let digest = *transaction.digest();
debug!("execute_certificate_with_effects");
fp_ensure!(
*effects.data().transaction_digest() == digest,
SuiError::ErrorWhileProcessingCertificate {
err: "effects/tx digest mismatch".to_string()
}
);
if transaction.contains_shared_object() {
epoch_store
.acquire_shared_locks_from_effects(transaction, effects.data(), &self.database)
.await?;
}
let expected_effects_digest = effects.digest();
self.transaction_manager
.enqueue(vec![transaction.clone()], epoch_store)?;
let observed_effects = self
.database
.notify_read_executed_effects(vec![digest])
.instrument(tracing::debug_span!(
"notify_read_effects_in_execute_certificate_with_effects"
))
.await?
.pop()
.expect("notify_read_effects should return exactly 1 element");
let observed_effects_digest = observed_effects.digest();
if &observed_effects_digest != expected_effects_digest {
panic!(
"Locally executed effects do not match canonical effects! expected_effects_digest={:?} observed_effects_digest={:?} expected_effects={:?} observed_effects={:?} input_objects={:?}",
expected_effects_digest, observed_effects_digest, effects.data(), observed_effects, transaction.data().transaction_data().input_objects()
);
}
Ok(())
}
/// Executes a certificate for its effects.
#[instrument(level = "trace", skip_all)]
pub async fn execute_certificate(
&self,
certificate: &VerifiedCertificate,
epoch_store: &Arc<AuthorityPerEpochStore>,
) -> SuiResult<VerifiedSignedTransactionEffects> {
let _metrics_guard = if certificate.contains_shared_object() {
self.metrics
.execute_certificate_latency_shared_object
.start_timer()
} else {
self.metrics
.execute_certificate_latency_single_writer
.start_timer()
};
debug!("execute_certificate");
self.metrics.total_cert_attempts.inc();
if !certificate.contains_shared_object() {
// Shared object transactions need to be sequenced by Narwhal before enqueueing
// for execution, done in AuthorityPerEpochStore::handle_consensus_transaction().
// For owned object transactions, they can be enqueued for execution immediately.
self.enqueue_certificates_for_execution(vec![certificate.clone()], epoch_store)?;
}
let effects = self.notify_read_effects(certificate).await?;
self.sign_effects(effects, epoch_store)
}
/// Internal logic to execute a certificate.
///
/// Guarantees that
/// - If input objects are available, return no permanent failure.
/// - Execution and output commit are atomic. i.e. outputs are only written to storage,
/// on successful execution; crashed execution has no observable effect and can be retried.
///
/// It is caller's responsibility to ensure input objects are available and locks are set.
/// If this cannot be satisfied by the caller, execute_certificate() should be called instead.
///
/// Should only be called within sui-core.
#[instrument(level = "trace", skip_all)]
pub async fn try_execute_immediately(
&self,
certificate: &VerifiedExecutableTransaction,
expected_effects_digest: Option<TransactionEffectsDigest>,
epoch_store: &Arc<AuthorityPerEpochStore>,
) -> SuiResult<(TransactionEffects, Option<ExecutionError>)> {
let _scope = monitored_scope("Execution::try_execute_immediately");
let _metrics_guard = self.metrics.internal_execution_latency.start_timer();
let tx_digest = *certificate.digest();
debug!("execute_certificate_internal");
// This acquires a lock on the tx digest to prevent multiple concurrent executions of the
// same tx. While we don't need this for safety (tx sequencing is ultimately atomic), it is
// very common to receive the same tx multiple times simultaneously due to gossip, so we
// may as well hold the lock and save the cpu time for other requests.
let tx_guard = epoch_store.acquire_tx_guard(certificate).await?;
self.process_certificate(tx_guard, certificate, expected_effects_digest, epoch_store)
.await
.tap_err(|e| info!(?tx_digest, "process_certificate failed: {e}"))
}
/// Test only wrapper for `try_execute_immediately()` above, useful for checking errors if the
/// pre-conditions are not satisfied, and executing change epoch transactions.
pub async fn try_execute_for_test(
&self,
certificate: &VerifiedCertificate,
) -> SuiResult<(VerifiedSignedTransactionEffects, Option<ExecutionError>)> {
let epoch_store = self.epoch_store_for_testing();
let (effects, execution_error_opt) = self
.try_execute_immediately(
&VerifiedExecutableTransaction::new_from_certificate(certificate.clone()),
None,
&epoch_store,
)
.await?;
let signed_effects = self.sign_effects(effects, &epoch_store)?;
Ok((signed_effects, execution_error_opt))
}
pub async fn notify_read_effects(
&self,
certificate: &VerifiedCertificate,
) -> SuiResult<TransactionEffects> {
let tx_digest = *certificate.digest();
Ok(self
.database
.notify_read_executed_effects(vec![tx_digest])
.await?
.pop()
.expect("notify_read_effects should return exactly 1 element"))
}
async fn check_owned_locks(&self, owned_object_refs: &[ObjectRef]) -> SuiResult {
self.database
.check_owned_object_locks_exist(owned_object_refs)
}
/// This function captures the required state to debug a forked transaction.
/// The dump is written to a file in dir `path`, with name prefixed by the transaction digest.
/// NOTE: Since this info escapes the validator context,
/// make sure not to leak any private info here
pub(crate) fn debug_dump_transaction_state(
&self,
tx_digest: &TransactionDigest,
effects: &TransactionEffects,
expected_effects_digest: TransactionEffectsDigest,
inner_temporary_store: &InnerTemporaryStore,
certificate: &VerifiedExecutableTransaction,
debug_dump_config: &StateDebugDumpConfig,
) -> SuiResult<PathBuf> {
let dump_dir = debug_dump_config
.dump_file_directory
.as_ref()
.cloned()
.unwrap_or(std::env::temp_dir());
let epoch_store = self.load_epoch_store_one_call_per_task();
NodeStateDump::new(
tx_digest,
effects,
expected_effects_digest,
&self.database,
&epoch_store,
inner_temporary_store,
certificate,
)?
.write_to_file(&dump_dir)
.map_err(|e| SuiError::FileIOError(e.to_string()))
}
#[instrument(level = "trace", skip_all)]
pub(crate) async fn process_certificate(
&self,
tx_guard: CertTxGuard,
certificate: &VerifiedExecutableTransaction,
expected_effects_digest: Option<TransactionEffectsDigest>,
epoch_store: &Arc<AuthorityPerEpochStore>,
) -> SuiResult<(TransactionEffects, Option<ExecutionError>)> {
let digest = *certificate.digest();
// The cert could have been processed by a concurrent attempt of the same cert, so check if
// the effects have already been written.
if let Some(effects) = self.database.get_executed_effects(&digest)? {
tx_guard.release();
return Ok((effects, None));
}
let execution_guard = self
.database
.execution_lock_for_executable_transaction(certificate)
.await;
// Any caller that verifies the signatures on the certificate will have already checked the
// epoch. But paths that don't verify sigs (e.g. execution from checkpoint, reading from db)
// present the possibility of an epoch mismatch. If this cert is not finalzied in previous
// epoch, then it's invalid.
let execution_guard = match execution_guard {
Ok(execution_guard) => execution_guard,
Err(err) => {
tx_guard.release();
return Err(err);