-
Notifications
You must be signed in to change notification settings - Fork 11.3k
/
Copy pathauthority.rs
3254 lines (2955 loc) · 126 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 anyhow::anyhow;
use arc_swap::{ArcSwap, Guard};
use chrono::prelude::*;
use fastcrypto::encoding::Base58;
use fastcrypto::encoding::Encoding;
use fastcrypto::traits::KeyPair;
use itertools::izip;
use itertools::Itertools;
use move_binary_format::compatibility::Compatibility;
use move_binary_format::CompiledModule;
use move_core_types::account_address::AccountAddress;
use move_core_types::identifier::Identifier;
use move_core_types::language_storage::{ModuleId, StructTag};
use move_core_types::parser::parse_struct_tag;
use mysten_metrics::spawn_monitored_task;
use parking_lot::Mutex;
use prometheus::{
register_histogram_with_registry, register_int_counter_vec_with_registry,
register_int_counter_with_registry, register_int_gauge_with_registry, Histogram, IntCounter,
IntCounterVec, IntGauge, Registry,
};
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;
use std::{collections::HashMap, pin::Pin};
use sui_config::node::{AuthorityStorePruningConfig, StateSnapshotConfig};
use sui_types::crypto::AuthoritySignInfo;
use sui_types::error::UserInputError;
use sui_types::intent::Intent;
use sui_types::intent::IntentScope;
use sui_types::message_envelope::Message;
use sui_types::parse_sui_struct_tag;
use sui_types::sui_system_state::SuiSystemStateTrait;
use sui_types::MOVE_STDLIB_OBJECT_ID;
use sui_types::SUI_FRAMEWORK_OBJECT_ID;
use tap::TapFallible;
use tokio::sync::mpsc::unbounded_channel;
use tokio::sync::oneshot;
use tokio_retry::strategy::{jitter, ExponentialBackoff};
use tracing::{debug, error, error_span, info, instrument, trace, warn, Instrument};
pub use authority_notify_read::EffectsNotifyRead;
pub use authority_store::{AuthorityStore, ResolverWrapper, UpdateType};
use narwhal_config::{
Committee as ConsensusCommittee, WorkerCache as ConsensusWorkerCache,
WorkerId as ConsensusWorkerId,
};
use sui_adapter::{adapter, execution_mode};
use sui_config::genesis::Genesis;
use sui_json_rpc_types::{
type_and_fields_from_move_struct, DevInspectResults, DryRunTransactionResponse, SuiEvent,
SuiEventEnvelope, SuiMoveValue, SuiTransactionEvents,
};
use sui_macros::nondeterministic;
use sui_protocol_config::{ProtocolConfig, SupportedProtocolVersions};
use sui_storage::indexes::{ObjectIndexChanges, MAX_GET_OWNED_OBJECT_SIZE};
use sui_storage::write_ahead_log::WriteAheadLog;
use sui_storage::{
event_store::{EventStore, EventStoreType, StoredEvent},
write_ahead_log::{DBTxGuard, TxGuard},
IndexStore,
};
use sui_types::committee::{EpochId, ProtocolVersion};
use sui_types::crypto::{sha3_hash, AuthorityKeyPair, NetworkKeyPair, Signer};
use sui_types::dynamic_field::{DynamicFieldInfo, DynamicFieldName, DynamicFieldType, Field};
use sui_types::event::{Event, EventID};
use sui_types::gas::{GasCostSummary, GasPrice, SuiCostTable, SuiGasStatus};
use sui_types::messages_checkpoint::{
CheckpointContents, CheckpointContentsDigest, CheckpointDigest, CheckpointSequenceNumber,
CheckpointSummary, CheckpointTimestamp, VerifiedCheckpoint,
};
use sui_types::messages_checkpoint::{CheckpointRequest, CheckpointResponse};
use sui_types::object::{MoveObject, Owner, PastObjectRead};
use sui_types::query::{EventQuery, TransactionQuery};
use sui_types::storage::{ObjectKey, WriteKind};
use sui_types::sui_system_state::{SuiSystemState, Table};
use sui_types::temporary_store::InnerTemporaryStore;
pub use sui_types::temporary_store::TemporaryStore;
use sui_types::{
base_types::*,
committee::Committee,
crypto::AuthoritySignature,
error::{SuiError, SuiResult},
fp_ensure,
messages::*,
object::{Object, ObjectFormatOptions, ObjectRead},
SUI_FRAMEWORK_ADDRESS,
};
use crate::authority::authority_per_epoch_store::{
AuthorityPerEpochStore, EpochStartConfiguration,
};
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::checkpoints::CheckpointStore;
use crate::epoch::committee_store::CommitteeStore;
use crate::epoch::epoch_metrics::EpochMetrics;
use crate::execution_driver::execution_process;
use crate::module_cache_metrics::ResolverMetrics;
use crate::stake_aggregator::StakeAggregator;
use crate::{
event_handler::EventHandler, transaction_input_checker, transaction_manager::TransactionManager,
};
use sui_adapter::execution_engine;
use sui_types::digests::TransactionEventsDigest;
#[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/tbls_tests.rs"]
mod tbls_tests;
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(crate) mod authority_notify_read;
pub(crate) mod authority_store;
pub(crate) const MAX_TX_RECOVERY_RETRY: u32 = 3;
// Reject a transaction if the number of pending transactions depending on the object
// is above the threshold.
pub(crate) const MAX_PER_OBJECT_EXECUTION_QUEUE_LENGTH: usize = 1000;
type CertTxGuard<'a> =
DBTxGuard<'a, TrustedExecutableTransaction, (InnerTemporaryStore, TransactionEffects)>;
pub type ReconfigConsensusMessage = (
AuthorityKeyPair,
NetworkKeyPair,
ConsensusCommittee,
Vec<(ConsensusWorkerId, NetworkKeyPair)>,
ConsensusWorkerCache,
);
pub type VerifiedTransactionBatch = Vec<(
VerifiedTransaction,
TransactionEffects,
TransactionEvents,
Option<(EpochId, CheckpointSequenceNumber)>,
)>;
/// 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,
tx_already_processed: IntCounter,
num_input_objs: Histogram,
num_shared_objects: Histogram,
batch_size: Histogram,
handle_transaction_latency: Histogram,
execute_certificate_latency: Histogram,
execute_certificate_with_effects_latency: Histogram,
internal_execution_latency: Histogram,
prepare_certificate_latency: Histogram,
commit_certificate_latency: Histogram,
state_snapshot_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) execution_driver_executed_transactions: IntCounter,
pub(crate) skipped_consensus_txns: IntCounter,
/// Post processing metrics
post_processing_total_events_emitted: IntCounter,
post_processing_total_tx_indexed: IntCounter,
post_processing_total_tx_had_event_processed: 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,
}
// 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.5, 5., 10., 20., 30., 60., 90.,
];
impl AuthorityMetrics {
pub fn new(registry: &prometheus::Registry) -> AuthorityMetrics {
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(),
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: register_histogram_with_registry!(
"authority_state_execute_certificate_latency",
"Latency of executing certificates, including waiting for inputs",
LATENCY_SEC_BUCKETS.to_vec(),
registry,
)
.unwrap(),
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(),
state_snapshot_checkpoint_latency: register_histogram_with_registry!(
"state_snapshot_checkpoint_latency",
"Latency of checkpointing perpetual db",
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(),
execution_driver_executed_transactions: register_int_counter_with_registry!(
"execution_driver_executed_transactions",
"Cumulative number of transaction executed by execution driver",
registry,
)
.unwrap(),
skipped_consensus_txns: register_int_counter_with_registry!(
"skipped_consensus_txns",
"Total number of consensus transactions skipped",
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(),
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()
}
}
}
/// 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>,
indexes: Option<Arc<IndexStore>>,
pub event_handler: Option<Arc<EventHandler>>,
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>,
_objects_pruner: AuthorityStorePruner,
_authority_per_epoch_pruner: AuthorityPerEpochStorePruner,
/// Take snapshot of the live object set at the end of epoch
enable_state_snapshot: bool,
}
/// 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()
}
/// 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.as_ref(),
&transaction.data().intent_message.value,
)
.await?;
for (object_id, queue_len) in self.transaction_manager.objects_queue_len(
input_objects
.mutable_inputs()
.into_iter()
.map(|r| r.0)
.collect(),
) {
// When this occurs, most likely transactions piled up on a shared object.
if queue_len >= MAX_PER_OBJECT_EXECUTION_QUEUE_LENGTH {
return Err(SuiError::TooManyTransactionsPendingOnObject {
object_id,
queue_len,
threshold: MAX_PER_OBJECT_EXECUTION_QUEUE_LENGTH,
});
}
}
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,
) -> Result<HandleTransactionResponse, SuiError> {
let tx_digest = *transaction.digest();
debug!(
"handle_transaction with transaction data: {:?}",
&transaction.data().intent_message.value
);
// 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,
}),
}
}
/// 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 = self.metrics.execute_certificate_latency.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.
// They are done in AuthorityPerEpochStore::handle_consensus_transaction(),
// which will enqueue this certificate for execution.
// For owned object transactions, we can enqueue the certificate 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,
epoch_store: &Arc<AuthorityPerEpochStore>,
) -> SuiResult<TransactionEffects> {
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.
//
// Note that this lock has some false contention (since it uses a MutexTable), so you can't
// assume that different txes can execute concurrently. This is probably the fastest way
// to do this, since the false contention can be made arbitrarily low (no cost for 1.0 -
// epsilon of txes) while solutions without false contention have slightly higher cost
// for every tx.
let tx_guard = epoch_store.acquire_tx_guard(certificate).await?;
self.process_certificate(tx_guard, certificate, epoch_store)
.await
.tap_err(|e| debug!(?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> {
let epoch_store = self.epoch_store_for_testing();
let effects = self
.try_execute_immediately(
&VerifiedExecutableTransaction::new_from_certificate(certificate.clone()),
&epoch_store,
)
.await?;
self.sign_effects(effects, &epoch_store)
}
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)
}
#[instrument(level = "trace", skip_all)]
pub(crate) async fn process_certificate(
&self,
tx_guard: CertTxGuard<'_>,
certificate: &VerifiedExecutableTransaction,
epoch_store: &Arc<AuthorityPerEpochStore>,
) -> SuiResult<TransactionEffects> {
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);
}
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);
}
};
// Since we obtain a reference to the epoch store before taking the execution lock, it's
// possible that reconfiguration has happened and they no longer match.
if *execution_guard != epoch_store.epoch() {
tx_guard.release();
debug!("The epoch of the execution_guard doesn't match the epoch store");
return Err(SuiError::WrongEpoch {
expected_epoch: epoch_store.epoch(),
actual_epoch: *execution_guard,
});
}
// first check to see if we have already executed and committed the tx
// to the WAL
if let Some((inner_temporary_storage, effects)) =
epoch_store.wal().get_execution_output(&digest)?
{
self.commit_cert_and_notify(
certificate,
inner_temporary_storage,
&effects,
tx_guard,
execution_guard,
epoch_store,
)
.await?;
return Ok(effects);
}
// Errors originating from prepare_certificate may be transient (failure to read locks) or
// non-transient (transaction input is invalid, move vm errors). However, all errors from
// this function occur before we have written anything to the db, so we commit the tx
// guard and rely on the client to retry the tx (if it was transient).
let (inner_temporary_store, effects) = match self
.prepare_certificate(&execution_guard, certificate, epoch_store)
.await
{
Err(e) => {
debug!(name = ?self.name, ?digest, "Error preparing transaction: {e}");
tx_guard.release();
return Err(e);
}
Ok(res) => res,
};
// Write tx output to WAL as first commit phase. In second phase
// we write from WAL to permanent storage. The purpose of this scheme
// is to allow for retrying phase 2 from phase 1 in the case where we
// fail mid-write. We prefer this over making the write to permanent
// storage atomic as this allows for sharding storage across nodes, which
// would be more difficult in the alternative.
epoch_store
.wal()
.write_execution_output(&digest, (inner_temporary_store.clone(), effects.clone()))?;
// Insert an await in between write_execution_output and commit so that tests can observe
// and test the interruption.
#[cfg(any(test, msim))]
tokio::task::yield_now().await;
self.commit_cert_and_notify(
certificate,
inner_temporary_store,
&effects,
tx_guard,
execution_guard,
epoch_store,
)
.await?;
Ok(effects)
}
async fn commit_cert_and_notify(
&self,
certificate: &VerifiedExecutableTransaction,
inner_temporary_store: InnerTemporaryStore,
effects: &TransactionEffects,
tx_guard: CertTxGuard<'_>,
_execution_guard: ExecutionLockReadGuard<'_>,
epoch_store: &Arc<AuthorityPerEpochStore>,
) -> SuiResult {
let input_object_count = inner_temporary_store.objects.len();
let shared_object_count = effects.shared_objects.len();
// If commit_certificate returns an error, tx_guard will be dropped and the certificate
// will be persisted in the log for later recovery.
let output_keys: Vec<_> = inner_temporary_store
.written
.iter()
.map(|(_, ((id, seq, _), obj, _))| InputKey(*id, (!obj.is_package()).then_some(*seq)))
.collect();
let events = inner_temporary_store.events.clone();
self.commit_certificate(inner_temporary_store, certificate, effects, epoch_store)
.await?;
// Notifies transaction manager about available input objects. This allows the transaction
// manager to schedule ready transactions.
//
// REQUIRED: this must be called after commit_certificate() (above), to ensure
// TransactionManager can receive the notifications for objects that it did not find
// in the objects table.
//
// REQUIRED: this must be called before tx_guard.commit_tx() (below), to ensure
// TransactionManager can get the notifications after the node crashes and restarts.
self.transaction_manager
.objects_available(output_keys, epoch_store);
// commit_certificate finished, the tx is fully committed to the store.
tx_guard.commit_tx();
// index certificate
let _ = self
.post_process_one_tx(certificate, effects, &events, epoch_store)
.await
.tap_err(|e| error!("tx post processing failed: {e}"));
// Update metrics.
self.metrics.total_effects.inc();
self.metrics.total_certs.inc();
if shared_object_count > 0 {
self.metrics.shared_obj_tx.inc();
}
self.metrics
.num_input_objs
.observe(input_object_count as f64);
self.metrics
.num_shared_objects
.observe(shared_object_count as f64);
self.metrics
.batch_size
.observe(certificate.data().intent_message.value.kind.batch_size() as f64);
Ok(())
}
/// prepare_certificate validates the transaction input, and executes the certificate,
/// returning effects, output objects, events, etc.
///
/// It reads state from the db (both owned and shared locks), but it has no side effects.
///
/// It can be generally understood that a failure of prepare_certificate indicates a
/// non-transient error, e.g. the transaction input is somehow invalid, the correct
/// locks are not held, etc. However, this is not entirely true, as a transient db read error
/// may also cause this function to fail.
#[instrument(level = "trace", skip_all)]
async fn prepare_certificate(
&self,
_execution_guard: &ExecutionLockReadGuard<'_>,
certificate: &VerifiedExecutableTransaction,
epoch_store: &Arc<AuthorityPerEpochStore>,
) -> SuiResult<(InnerTemporaryStore, TransactionEffects)> {
let _metrics_guard = self.metrics.prepare_certificate_latency.start_timer();
// check_certificate_input also checks shared object locks when loading the shared objects.
let (gas_status, input_objects) = transaction_input_checker::check_certificate_input(
&self.database,
epoch_store,
certificate,
)
.await?;
let owned_object_refs = input_objects.filter_owned_objects();
self.check_owned_locks(&owned_object_refs).await?;
let shared_object_refs = input_objects.filter_shared_objects();
let transaction_dependencies = input_objects.transaction_dependencies();
let temporary_store = TemporaryStore::new(
self.database.clone(),
input_objects,
*certificate.digest(),
epoch_store.protocol_config(),
);
let transaction_data = &certificate.data().intent_message.value;
let (kind, signer, gas) = transaction_data.execution_parts();
let (inner_temp_store, effects, _execution_error) =
execution_engine::execute_transaction_to_effects::<execution_mode::Normal, _>(
shared_object_refs,
temporary_store,
kind,
signer,
&gas,
*certificate.digest(),
transaction_dependencies,
epoch_store.move_vm(),
gas_status,
&epoch_store.epoch_start_configuration().epoch_data(),
epoch_store.protocol_config(),
);
Ok((inner_temp_store, effects))
}
/// Notifies TransactionManager about an executed certificate.
pub fn certificate_executed(
&self,
digest: &TransactionDigest,
epoch_store: &Arc<AuthorityPerEpochStore>,
) {
self.transaction_manager
.certificate_executed(digest, epoch_store)
}
pub async fn dry_exec_transaction(
&self,
transaction: TransactionData,
transaction_digest: TransactionDigest,
) -> Result<DryRunTransactionResponse, anyhow::Error> {
let epoch_store = self.load_epoch_store_one_call_per_task();
if !self.is_fullnode(&epoch_store) {
return Err(anyhow!("dry-exec is only support on fullnodes"));
}
let (gas_status, input_objects) = transaction_input_checker::check_transaction_input(
&self.database,
epoch_store.as_ref(),
&transaction,
)
.await?;
let shared_object_refs = input_objects.filter_shared_objects();