-
Notifications
You must be signed in to change notification settings - Fork 648
/
errors.rs
1291 lines (1229 loc) · 50.1 KB
/
errors.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
use crate::hash::CryptoHash;
use crate::serialize::dec_format;
use crate::shard_layout::ShardLayoutError;
use crate::sharding::ChunkHash;
use crate::types::{AccountId, Balance, EpochId, Gas, Nonce};
use borsh::{BorshDeserialize, BorshSerialize};
use near_crypto::PublicKey;
use near_primitives_core::types::ProtocolVersion;
use near_schema_checker_lib::ProtocolSchema;
use std::fmt::{Debug, Display};
/// Error returned in the ExecutionOutcome in case of failure
#[derive(
BorshSerialize,
BorshDeserialize,
Debug,
Clone,
PartialEq,
Eq,
serde::Deserialize,
serde::Serialize,
ProtocolSchema,
)]
pub enum TxExecutionError {
/// An error happened during Action execution
ActionError(ActionError),
/// An error happened during Transaction execution
InvalidTxError(InvalidTxError),
}
impl std::error::Error for TxExecutionError {}
impl Display for TxExecutionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
match self {
TxExecutionError::ActionError(e) => write!(f, "{}", e),
TxExecutionError::InvalidTxError(e) => write!(f, "{}", e),
}
}
}
impl From<ActionError> for TxExecutionError {
fn from(error: ActionError) -> Self {
TxExecutionError::ActionError(error)
}
}
impl From<InvalidTxError> for TxExecutionError {
fn from(error: InvalidTxError) -> Self {
TxExecutionError::InvalidTxError(error)
}
}
/// Error returned from `Runtime::apply`
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RuntimeError {
/// An unexpected integer overflow occurred. The likely issue is an invalid state or the transition.
UnexpectedIntegerOverflow(String),
/// An error happened during TX verification and account charging.
InvalidTxError(InvalidTxError),
/// Unexpected error which is typically related to the node storage corruption.
/// It's possible the input state is invalid or malicious.
StorageError(StorageError),
/// An error happens if `check_balance` fails, which is likely an indication of an invalid state.
BalanceMismatchError(Box<BalanceMismatchError>),
/// The incoming receipt didn't pass the validation, it's likely a malicious behaviour.
ReceiptValidationError(ReceiptValidationError),
/// Error when accessing validator information. Happens inside epoch manager.
ValidatorError(EpochError),
}
impl std::fmt::Display for RuntimeError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
f.write_str(&format!("{:?}", self))
}
}
impl std::error::Error for RuntimeError {}
/// Contexts in which `StorageError::MissingTrieValue` error might occur.
#[derive(
Debug,
Clone,
PartialEq,
Eq,
serde::Deserialize,
serde::Serialize,
BorshSerialize,
BorshDeserialize,
ProtocolSchema,
)]
pub enum MissingTrieValueContext {
/// Missing trie value when reading from TrieIterator.
TrieIterator,
/// Missing trie value when reading from TriePrefetchingStorage.
TriePrefetchingStorage,
/// Missing trie value when reading from TrieMemoryPartialStorage.
TrieMemoryPartialStorage,
/// Missing trie value when reading from TrieStorage.
TrieStorage,
}
impl MissingTrieValueContext {
pub fn metrics_label(&self) -> &str {
match self {
Self::TrieIterator => "trie_iterator",
Self::TriePrefetchingStorage => "trie_prefetching_storage",
Self::TrieMemoryPartialStorage => "trie_memory_partial_storage",
Self::TrieStorage => "trie_storage",
}
}
}
/// Errors which may occur during working with trie storages, storing
/// trie values (trie nodes and state values) by their hashes.
#[derive(
Debug,
Clone,
PartialEq,
Eq,
serde::Deserialize,
serde::Serialize,
BorshSerialize,
BorshDeserialize,
ProtocolSchema,
)]
pub enum StorageError {
/// Key-value db internal failure
StorageInternalError,
/// Requested trie value by its hash which is missing in storage.
MissingTrieValue(MissingTrieValueContext, CryptoHash),
/// Found trie node which shouldn't be part of state. Raised during
/// validation of state sync parts where incorrect node was passed.
/// TODO (#8997): consider including hash of trie node.
UnexpectedTrieValue,
/// Either invalid state or key-value db is corrupted.
/// For PartialStorage it cannot be corrupted.
/// Error message is unreliable and for debugging purposes only. It's also probably ok to
/// panic in every place that produces this error.
/// We can check if db is corrupted by verifying everything in the state trie.
StorageInconsistentState(String),
/// Flat storage error, meaning that it doesn't support some block anymore.
/// We guarantee that such block cannot become final, thus block processing
/// must resume normally.
FlatStorageBlockNotSupported(String),
/// In-memory trie could not be loaded for some reason.
MemTrieLoadingError(String),
/// Indicates that a resharding operation on flat storage is already in progress,
/// when it wasn't expected to be so.
FlatStorageReshardingAlreadyInProgress,
}
impl std::fmt::Display for StorageError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
f.write_str(&format!("{:?}", self))
}
}
impl std::error::Error for StorageError {}
/// An error happened during TX execution
#[derive(
BorshSerialize,
BorshDeserialize,
Debug,
Clone,
PartialEq,
Eq,
serde::Deserialize,
serde::Serialize,
ProtocolSchema,
)]
pub enum InvalidTxError {
/// Happens if a wrong AccessKey used or AccessKey has not enough permissions
InvalidAccessKeyError(InvalidAccessKeyError),
/// TX signer_id is not a valid [`AccountId`]
InvalidSignerId {
signer_id: String,
},
/// TX signer_id is not found in a storage
SignerDoesNotExist {
signer_id: AccountId,
},
/// Transaction nonce must be `account[access_key].nonce + 1`.
InvalidNonce {
tx_nonce: Nonce,
ak_nonce: Nonce,
},
/// Transaction nonce is larger than the upper bound given by the block height
NonceTooLarge {
tx_nonce: Nonce,
upper_bound: Nonce,
},
/// TX receiver_id is not a valid AccountId
InvalidReceiverId {
receiver_id: String,
},
/// TX signature is not valid
InvalidSignature,
/// Account does not have enough balance to cover TX cost
NotEnoughBalance {
signer_id: AccountId,
#[serde(with = "dec_format")]
balance: Balance,
#[serde(with = "dec_format")]
cost: Balance,
},
/// Signer account doesn't have enough balance after transaction.
LackBalanceForState {
/// An account which doesn't have enough balance to cover storage.
signer_id: AccountId,
/// Required balance to cover the state.
#[serde(with = "dec_format")]
amount: Balance,
},
/// An integer overflow occurred during transaction cost estimation.
CostOverflow,
/// Transaction parent block hash doesn't belong to the current chain
InvalidChain,
/// Transaction has expired
Expired,
/// An error occurred while validating actions of a Transaction.
ActionsValidation(ActionsValidationError),
/// The size of serialized transaction exceeded the limit.
TransactionSizeExceeded {
size: u64,
limit: u64,
},
/// Transaction version is invalid.
InvalidTransactionVersion,
// Error occurred during storage access
StorageError(StorageError),
/// The receiver shard of the transaction is too congested to accept new
/// transactions at the moment.
ShardCongested {
/// The congested shard.
shard_id: u32,
/// A value between 0 (no congestion) and 1 (max congestion).
congestion_level: ordered_float::NotNan<f64>,
},
/// The receiver shard of the transaction missed several chunks and rejects
/// new transaction until it can make progress again.
ShardStuck {
/// The shard that fails making progress.
shard_id: u32,
/// The number of blocks since the last included chunk of the shard.
missed_chunks: u64,
},
}
impl From<StorageError> for InvalidTxError {
fn from(error: StorageError) -> Self {
InvalidTxError::StorageError(error)
}
}
impl std::error::Error for InvalidTxError {}
#[derive(
BorshSerialize,
BorshDeserialize,
Debug,
Clone,
PartialEq,
Eq,
serde::Deserialize,
serde::Serialize,
ProtocolSchema,
)]
pub enum InvalidAccessKeyError {
/// The access key identified by the `public_key` doesn't exist for the account
AccessKeyNotFound { account_id: AccountId, public_key: Box<PublicKey> },
/// Transaction `receiver_id` doesn't match the access key receiver_id
ReceiverMismatch { tx_receiver: AccountId, ak_receiver: String },
/// Transaction method name isn't allowed by the access key
MethodNameMismatch { method_name: String },
/// Transaction requires a full permission access key.
RequiresFullAccess,
/// Access Key does not have enough allowance to cover transaction cost
NotEnoughAllowance {
account_id: AccountId,
public_key: Box<PublicKey>,
#[serde(with = "dec_format")]
allowance: Balance,
#[serde(with = "dec_format")]
cost: Balance,
},
/// Having a deposit with a function call action is not allowed with a function call access key.
DepositWithFunctionCall,
}
/// Describes the error for validating a list of actions.
#[derive(
BorshSerialize,
BorshDeserialize,
Debug,
Clone,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
ProtocolSchema,
)]
pub enum ActionsValidationError {
/// The delete action must be a final aciton in transaction
DeleteActionMustBeFinal,
/// The total prepaid gas (for all given actions) exceeded the limit.
TotalPrepaidGasExceeded { total_prepaid_gas: Gas, limit: Gas },
/// The number of actions exceeded the given limit.
TotalNumberOfActionsExceeded { total_number_of_actions: u64, limit: u64 },
/// The total number of bytes of the method names exceeded the limit in a Add Key action.
AddKeyMethodNamesNumberOfBytesExceeded { total_number_of_bytes: u64, limit: u64 },
/// The length of some method name exceeded the limit in a Add Key action.
AddKeyMethodNameLengthExceeded { length: u64, limit: u64 },
/// Integer overflow during a compute.
IntegerOverflow,
/// Invalid account ID.
InvalidAccountId { account_id: String },
/// The size of the contract code exceeded the limit in a DeployContract action.
ContractSizeExceeded { size: u64, limit: u64 },
/// The length of the method name exceeded the limit in a Function Call action.
FunctionCallMethodNameLengthExceeded { length: u64, limit: u64 },
/// The length of the arguments exceeded the limit in a Function Call action.
FunctionCallArgumentsLengthExceeded { length: u64, limit: u64 },
/// An attempt to stake with a public key that is not convertible to ristretto.
UnsuitableStakingKey { public_key: Box<PublicKey> },
/// The attached amount of gas in a FunctionCall action has to be a positive number.
FunctionCallZeroAttachedGas,
/// There should be the only one DelegateAction
DelegateActionMustBeOnlyOne,
/// The transaction includes a feature that the current protocol version
/// does not support.
///
/// Note: we stringify the protocol feature name instead of using
/// `ProtocolFeature` here because we don't want to leak the internals of
/// that type into observable borsh serialization.
UnsupportedProtocolFeature { protocol_feature: String, version: ProtocolVersion },
}
/// Describes the error for validating a receipt.
#[derive(
BorshSerialize,
BorshDeserialize,
Debug,
Clone,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
ProtocolSchema,
)]
pub enum ReceiptValidationError {
/// The `predecessor_id` of a Receipt is not valid.
InvalidPredecessorId { account_id: String },
/// The `receiver_id` of a Receipt is not valid.
InvalidReceiverId { account_id: String },
/// The `signer_id` of an ActionReceipt is not valid.
InvalidSignerId { account_id: String },
/// The `receiver_id` of a DataReceiver within an ActionReceipt is not valid.
InvalidDataReceiverId { account_id: String },
/// The length of the returned data exceeded the limit in a DataReceipt.
ReturnedValueLengthExceeded { length: u64, limit: u64 },
/// The number of input data dependencies exceeds the limit in an ActionReceipt.
NumberInputDataDependenciesExceeded { number_of_input_data_dependencies: u64, limit: u64 },
/// An error occurred while validating actions of an ActionReceipt.
ActionsValidation(ActionsValidationError),
/// Receipt is bigger than the limit.
ReceiptSizeExceeded { size: u64, limit: u64 },
}
impl Display for ReceiptValidationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
match self {
ReceiptValidationError::InvalidPredecessorId { account_id } => {
write!(f, "The predecessor_id `{}` of a Receipt is not valid.", account_id)
}
ReceiptValidationError::InvalidReceiverId { account_id } => {
write!(f, "The receiver_id `{}` of a Receipt is not valid.", account_id)
}
ReceiptValidationError::InvalidSignerId { account_id } => {
write!(f, "The signer_id `{}` of an ActionReceipt is not valid.", account_id)
}
ReceiptValidationError::InvalidDataReceiverId { account_id } => write!(
f,
"The receiver_id `{}` of a DataReceiver within an ActionReceipt is not valid.",
account_id
),
ReceiptValidationError::ReturnedValueLengthExceeded { length, limit } => write!(
f,
"The length of the returned data {} exceeded the limit {} in a DataReceipt",
length, limit
),
ReceiptValidationError::NumberInputDataDependenciesExceeded { number_of_input_data_dependencies, limit } => write!(
f,
"The number of input data dependencies {} exceeded the limit {} in an ActionReceipt",
number_of_input_data_dependencies, limit
),
ReceiptValidationError::ActionsValidation(e) => write!(f, "{}", e),
ReceiptValidationError::ReceiptSizeExceeded { size, limit } => write!(
f,
"The size of the receipt exceeded the limit: {} > {}",
size, limit
),
}
}
}
impl std::error::Error for ReceiptValidationError {}
impl Display for ActionsValidationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
match self {
ActionsValidationError::DeleteActionMustBeFinal => {
write!(f, "The delete action must be the last action in transaction")
}
ActionsValidationError::TotalPrepaidGasExceeded { total_prepaid_gas, limit } => {
write!(f, "The total prepaid gas {} exceeds the limit {}", total_prepaid_gas, limit)
}
ActionsValidationError::TotalNumberOfActionsExceeded {total_number_of_actions, limit } => {
write!(
f,
"The total number of actions {} exceeds the limit {}",
total_number_of_actions, limit
)
}
ActionsValidationError::AddKeyMethodNamesNumberOfBytesExceeded { total_number_of_bytes, limit } => write!(
f,
"The total number of bytes in allowed method names {} exceeds the maximum allowed number {} in a AddKey action",
total_number_of_bytes, limit
),
ActionsValidationError::AddKeyMethodNameLengthExceeded { length, limit } => write!(
f,
"The length of some method name {} exceeds the maximum allowed length {} in a AddKey action",
length, limit
),
ActionsValidationError::IntegerOverflow => write!(
f,
"Integer overflow during a compute",
),
ActionsValidationError::InvalidAccountId { account_id } => write!(
f,
"Invalid account ID `{}`",
account_id
),
ActionsValidationError::ContractSizeExceeded { size, limit } => write!(
f,
"The length of the contract size {} exceeds the maximum allowed size {} in a DeployContract action",
size, limit
),
ActionsValidationError::FunctionCallMethodNameLengthExceeded { length, limit } => write!(
f,
"The length of the method name {} exceeds the maximum allowed length {} in a FunctionCall action",
length, limit
),
ActionsValidationError::FunctionCallArgumentsLengthExceeded { length, limit } => write!(
f,
"The length of the arguments {} exceeds the maximum allowed length {} in a FunctionCall action",
length, limit
),
ActionsValidationError::UnsuitableStakingKey { public_key } => write!(
f,
"The staking key must be ristretto compatible ED25519 key. {} is provided instead.",
public_key,
),
ActionsValidationError::FunctionCallZeroAttachedGas => write!(
f,
"The attached amount of gas in a FunctionCall action has to be a positive number",
),
ActionsValidationError::DelegateActionMustBeOnlyOne => write!(
f,
"The actions can contain the ony one DelegateAction"
),
ActionsValidationError::UnsupportedProtocolFeature { protocol_feature, version } => write!(
f,
"Transaction requires protocol feature {} / version {} which is not supported by the current protocol version",
protocol_feature,
version,
),
}
}
}
impl std::error::Error for ActionsValidationError {}
/// An error happened during Action execution
#[derive(
BorshSerialize,
BorshDeserialize,
Debug,
Clone,
PartialEq,
Eq,
serde::Deserialize,
serde::Serialize,
ProtocolSchema,
)]
pub struct ActionError {
/// Index of the failed action in the transaction.
/// Action index is not defined if ActionError.kind is `ActionErrorKind::LackBalanceForState`
pub index: Option<u64>,
/// The kind of ActionError happened
pub kind: ActionErrorKind,
}
impl std::error::Error for ActionError {}
#[derive(
BorshSerialize,
BorshDeserialize,
Debug,
Clone,
PartialEq,
Eq,
serde::Deserialize,
serde::Serialize,
ProtocolSchema,
)]
pub enum ActionErrorKind {
/// Happens when CreateAccount action tries to create an account with account_id which is already exists in the storage
AccountAlreadyExists { account_id: AccountId },
/// Happens when TX receiver_id doesn't exist (but action is not Action::CreateAccount)
AccountDoesNotExist { account_id: AccountId },
/// A top-level account ID can only be created by registrar.
CreateAccountOnlyByRegistrar {
account_id: AccountId,
registrar_account_id: AccountId,
predecessor_id: AccountId,
},
/// A newly created account must be under a namespace of the creator account
CreateAccountNotAllowed { account_id: AccountId, predecessor_id: AccountId },
/// Administrative actions like `DeployContract`, `Stake`, `AddKey`, `DeleteKey`. can be proceed only if sender=receiver
/// or the first TX action is a `CreateAccount` action
ActorNoPermission { account_id: AccountId, actor_id: AccountId },
/// Account tries to remove an access key that doesn't exist
DeleteKeyDoesNotExist { account_id: AccountId, public_key: Box<PublicKey> },
/// The public key is already used for an existing access key
AddKeyAlreadyExists { account_id: AccountId, public_key: Box<PublicKey> },
/// Account is staking and can not be deleted
DeleteAccountStaking { account_id: AccountId },
/// ActionReceipt can't be completed, because the remaining balance will not be enough to cover storage.
LackBalanceForState {
/// An account which needs balance
account_id: AccountId,
/// Balance required to complete an action.
#[serde(with = "dec_format")]
amount: Balance,
},
/// Account is not yet staked, but tries to unstake
TriesToUnstake { account_id: AccountId },
/// The account doesn't have enough balance to increase the stake.
TriesToStake {
account_id: AccountId,
#[serde(with = "dec_format")]
stake: Balance,
#[serde(with = "dec_format")]
locked: Balance,
#[serde(with = "dec_format")]
balance: Balance,
},
InsufficientStake {
account_id: AccountId,
#[serde(with = "dec_format")]
stake: Balance,
#[serde(with = "dec_format")]
minimum_stake: Balance,
},
/// An error occurred during a `FunctionCall` Action, parameter is debug message.
FunctionCallError(FunctionCallError),
/// Error occurs when a new `ActionReceipt` created by the `FunctionCall` action fails
/// receipt validation.
NewReceiptValidationError(ReceiptValidationError),
/// Error occurs when a `CreateAccount` action is called on a NEAR-implicit or ETH-implicit account.
/// See NEAR-implicit account creation NEP: <https://github.com/nearprotocol/NEPs/pull/71>.
/// Also, see ETH-implicit account creation NEP: <https://github.com/near/NEPs/issues/518>.
///
/// TODO(#8598): This error is named very poorly. A better name would be
/// `OnlyNamedAccountCreationAllowed`.
OnlyImplicitAccountCreationAllowed { account_id: AccountId },
/// Delete account whose state is large is temporarily banned.
DeleteAccountWithLargeState { account_id: AccountId },
/// Signature does not match the provided actions and given signer public key.
DelegateActionInvalidSignature,
/// Receiver of the transaction doesn't match Sender of the delegate action
DelegateActionSenderDoesNotMatchTxReceiver { sender_id: AccountId, receiver_id: AccountId },
/// Delegate action has expired. `max_block_height` is less than actual block height.
DelegateActionExpired,
/// The given public key doesn't exist for Sender account
DelegateActionAccessKeyError(InvalidAccessKeyError),
/// DelegateAction nonce must be greater sender[public_key].nonce
DelegateActionInvalidNonce { delegate_nonce: Nonce, ak_nonce: Nonce },
/// DelegateAction nonce is larger than the upper bound given by the block height
DelegateActionNonceTooLarge { delegate_nonce: Nonce, upper_bound: Nonce },
/// Non-refundable storage transfer to an existing account is not allowed according to NEP-491.
NonRefundableTransferToExistingAccount { account_id: AccountId },
}
impl From<ActionErrorKind> for ActionError {
fn from(e: ActionErrorKind) -> ActionError {
ActionError { index: None, kind: e }
}
}
impl Display for InvalidTxError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
match self {
InvalidTxError::InvalidSignerId { signer_id } => {
write!(f, "Invalid signer account ID {:?} according to requirements", signer_id)
}
InvalidTxError::SignerDoesNotExist { signer_id } => {
write!(f, "Signer {:?} does not exist", signer_id)
}
InvalidTxError::InvalidAccessKeyError(access_key_error) => {
Display::fmt(&access_key_error, f)
}
InvalidTxError::InvalidNonce { tx_nonce, ak_nonce } => write!(
f,
"Transaction nonce {} must be larger than nonce of the used access key {}",
tx_nonce, ak_nonce
),
InvalidTxError::InvalidReceiverId { receiver_id } => {
write!(f, "Invalid receiver account ID {:?} according to requirements", receiver_id)
}
InvalidTxError::InvalidSignature => {
write!(f, "Transaction is not signed with the given public key")
}
InvalidTxError::NotEnoughBalance { signer_id, balance, cost } => write!(
f,
"Sender {:?} does not have enough balance {} for operation costing {}",
signer_id, balance, cost
),
InvalidTxError::LackBalanceForState { signer_id, amount } => {
write!(f, "Failed to execute, because the account {:?} wouldn't have enough balance to cover storage, required to have {} yoctoNEAR more", signer_id, amount)
}
InvalidTxError::CostOverflow => {
write!(f, "Transaction gas or balance cost is too high")
}
InvalidTxError::InvalidChain => {
write!(f, "Transaction parent block hash doesn't belong to the current chain")
}
InvalidTxError::Expired => {
write!(f, "Transaction has expired")
}
InvalidTxError::ActionsValidation(error) => {
write!(f, "Transaction actions validation error: {}", error)
}
InvalidTxError::NonceTooLarge { tx_nonce, upper_bound } => {
write!(
f,
"Transaction nonce {} must be smaller than the access key nonce upper bound {}",
tx_nonce, upper_bound
)
}
InvalidTxError::TransactionSizeExceeded { size, limit } => {
write!(f, "Size of serialized transaction {} exceeded the limit {}", size, limit)
}
InvalidTxError::InvalidTransactionVersion => {
write!(f, "Transaction version is invalid")
}
InvalidTxError::StorageError(error) => {
write!(f, "Storage error: {}", error)
}
InvalidTxError::ShardCongested { shard_id, congestion_level } => {
write!(f, "Shard {shard_id} is currently at congestion level {congestion_level:.3} and rejects new transactions.")
}
InvalidTxError::ShardStuck { shard_id, missed_chunks } => {
write!(
f,
"Shard {shard_id} missed {missed_chunks} chunks and rejects new transactions."
)
}
}
}
}
impl From<InvalidAccessKeyError> for InvalidTxError {
fn from(error: InvalidAccessKeyError) -> Self {
InvalidTxError::InvalidAccessKeyError(error)
}
}
impl Display for InvalidAccessKeyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
match self {
InvalidAccessKeyError::AccessKeyNotFound { account_id, public_key } => write!(
f,
"Signer {:?} doesn't have access key with the given public_key {}",
account_id, public_key
),
InvalidAccessKeyError::ReceiverMismatch { tx_receiver, ak_receiver } => write!(
f,
"Transaction receiver_id {:?} doesn't match the access key receiver_id {:?}",
tx_receiver, ak_receiver
),
InvalidAccessKeyError::MethodNameMismatch { method_name } => write!(
f,
"Transaction method name {:?} isn't allowed by the access key",
method_name
),
InvalidAccessKeyError::RequiresFullAccess => {
write!(f, "Invalid access key type. Full-access keys are required for transactions that have multiple or non-function-call actions")
}
InvalidAccessKeyError::NotEnoughAllowance {
account_id,
public_key,
allowance,
cost,
} => write!(
f,
"Access Key {:?}:{} does not have enough balance {} for transaction costing {}",
account_id, public_key, allowance, cost
),
InvalidAccessKeyError::DepositWithFunctionCall => {
write!(f, "Having a deposit with a function call action is not allowed with a function call access key.")
}
}
}
}
impl std::error::Error for InvalidAccessKeyError {}
/// Happens when the input balance doesn't match the output balance in Runtime apply.
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize, ProtocolSchema)]
pub struct BalanceMismatchError {
// Input balances
#[serde(with = "dec_format")]
pub incoming_validator_rewards: Balance,
#[serde(with = "dec_format")]
pub initial_accounts_balance: Balance,
#[serde(with = "dec_format")]
pub incoming_receipts_balance: Balance,
#[serde(with = "dec_format")]
pub processed_delayed_receipts_balance: Balance,
#[serde(with = "dec_format")]
pub initial_postponed_receipts_balance: Balance,
#[serde(with = "dec_format")]
pub forwarded_buffered_receipts_balance: Balance,
// Output balances
#[serde(with = "dec_format")]
pub final_accounts_balance: Balance,
#[serde(with = "dec_format")]
pub outgoing_receipts_balance: Balance,
#[serde(with = "dec_format")]
pub new_delayed_receipts_balance: Balance,
#[serde(with = "dec_format")]
pub final_postponed_receipts_balance: Balance,
#[serde(with = "dec_format")]
pub tx_burnt_amount: Balance,
#[serde(with = "dec_format")]
pub slashed_burnt_amount: Balance,
#[serde(with = "dec_format")]
pub new_buffered_receipts_balance: Balance,
#[serde(with = "dec_format")]
pub other_burnt_amount: Balance,
}
impl Display for BalanceMismatchError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
// Using saturating add to avoid overflow in display
let initial_balance = self
.incoming_validator_rewards
.saturating_add(self.initial_accounts_balance)
.saturating_add(self.incoming_receipts_balance)
.saturating_add(self.processed_delayed_receipts_balance)
.saturating_add(self.initial_postponed_receipts_balance)
.saturating_add(self.forwarded_buffered_receipts_balance);
let final_balance = self
.final_accounts_balance
.saturating_add(self.outgoing_receipts_balance)
.saturating_add(self.new_delayed_receipts_balance)
.saturating_add(self.final_postponed_receipts_balance)
.saturating_add(self.tx_burnt_amount)
.saturating_add(self.slashed_burnt_amount)
.saturating_add(self.other_burnt_amount)
.saturating_add(self.new_buffered_receipts_balance);
write!(
f,
"Balance Mismatch Error. The input balance {} doesn't match output balance {}\n\
Inputs:\n\
\tIncoming validator rewards sum: {}\n\
\tInitial accounts balance sum: {}\n\
\tIncoming receipts balance sum: {}\n\
\tProcessed delayed receipts balance sum: {}\n\
\tInitial postponed receipts balance sum: {}\n\
\tForwarded buffered receipts sum: {}\n\
Outputs:\n\
\tFinal accounts balance sum: {}\n\
\tOutgoing receipts balance sum: {}\n\
\tNew delayed receipts balance sum: {}\n\
\tFinal postponed receipts balance sum: {}\n\
\tTx fees burnt amount: {}\n\
\tSlashed amount: {}\n\
\tNew buffered receipts balance sum: {}\n\
\tOther burnt amount: {}",
initial_balance,
final_balance,
self.incoming_validator_rewards,
self.initial_accounts_balance,
self.incoming_receipts_balance,
self.processed_delayed_receipts_balance,
self.initial_postponed_receipts_balance,
self.forwarded_buffered_receipts_balance,
self.final_accounts_balance,
self.outgoing_receipts_balance,
self.new_delayed_receipts_balance,
self.final_postponed_receipts_balance,
self.tx_burnt_amount,
self.slashed_burnt_amount,
self.new_buffered_receipts_balance,
self.other_burnt_amount,
)
}
}
impl std::error::Error for BalanceMismatchError {}
#[derive(BorshSerialize, BorshDeserialize, Debug, Clone, PartialEq, Eq, ProtocolSchema)]
pub struct IntegerOverflowError;
impl std::fmt::Display for IntegerOverflowError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
f.write_str(&format!("{:?}", self))
}
}
impl std::error::Error for IntegerOverflowError {}
impl From<IntegerOverflowError> for InvalidTxError {
fn from(_: IntegerOverflowError) -> Self {
InvalidTxError::CostOverflow
}
}
impl From<IntegerOverflowError> for RuntimeError {
fn from(err: IntegerOverflowError) -> Self {
RuntimeError::UnexpectedIntegerOverflow(err.to_string())
}
}
impl From<StorageError> for RuntimeError {
fn from(e: StorageError) -> Self {
RuntimeError::StorageError(e)
}
}
impl From<BalanceMismatchError> for RuntimeError {
fn from(e: BalanceMismatchError) -> Self {
RuntimeError::BalanceMismatchError(Box::new(e))
}
}
impl From<InvalidTxError> for RuntimeError {
fn from(e: InvalidTxError) -> Self {
RuntimeError::InvalidTxError(e)
}
}
impl From<EpochError> for RuntimeError {
fn from(e: EpochError) -> Self {
RuntimeError::ValidatorError(e)
}
}
impl Display for ActionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
write!(f, "Action #{}: {}", self.index.unwrap_or_default(), self.kind)
}
}
impl Display for ActionErrorKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
match self {
ActionErrorKind::AccountAlreadyExists { account_id } => {
write!(f, "Can't create a new account {:?}, because it already exists", account_id)
}
ActionErrorKind::AccountDoesNotExist { account_id } => write!(
f,
"Can't complete the action because account {:?} doesn't exist",
account_id
),
ActionErrorKind::ActorNoPermission { actor_id, account_id } => write!(
f,
"Actor {:?} doesn't have permission to account {:?} to complete the action",
actor_id, account_id
),
ActionErrorKind::LackBalanceForState { account_id, amount } => write!(
f,
"The account {} wouldn't have enough balance to cover storage, required to have {} yoctoNEAR more",
account_id, amount
),
ActionErrorKind::TriesToUnstake { account_id } => {
write!(f, "Account {:?} is not yet staked, but tries to unstake", account_id)
}
ActionErrorKind::TriesToStake { account_id, stake, locked, balance } => write!(
f,
"Account {:?} tries to stake {}, but has staked {} and only has {}",
account_id, stake, locked, balance
),
ActionErrorKind::CreateAccountOnlyByRegistrar { account_id, registrar_account_id, predecessor_id } => write!(
f,
"A top-level account ID {:?} can't be created by {:?}, short top-level account IDs can only be created by {:?}",
account_id, predecessor_id, registrar_account_id,
),
ActionErrorKind::CreateAccountNotAllowed { account_id, predecessor_id } => write!(
f,
"A sub-account ID {:?} can't be created by account {:?}",
account_id, predecessor_id,
),
ActionErrorKind::DeleteKeyDoesNotExist { account_id, .. } => write!(
f,
"Account {:?} tries to remove an access key that doesn't exist",
account_id
),
ActionErrorKind::AddKeyAlreadyExists { public_key, .. } => write!(
f,
"The public key {:?} is already used for an existing access key",
public_key
),
ActionErrorKind::DeleteAccountStaking { account_id } => {
write!(f, "Account {:?} is staking and can not be deleted", account_id)
}
ActionErrorKind::FunctionCallError(s) => write!(f, "{:?}", s),
ActionErrorKind::NewReceiptValidationError(e) => {
write!(f, "An new action receipt created during a FunctionCall is not valid: {}", e)
}
ActionErrorKind::InsufficientStake { account_id, stake, minimum_stake } => write!(f, "Account {} tries to stake {} but minimum required stake is {}", account_id, stake, minimum_stake),
ActionErrorKind::OnlyImplicitAccountCreationAllowed { account_id } => write!(f, "CreateAccount action is called on hex-characters account of length 64 {}", account_id),
ActionErrorKind::DeleteAccountWithLargeState { account_id } => write!(f, "The state of account {} is too large and therefore cannot be deleted", account_id),
ActionErrorKind::DelegateActionInvalidSignature => write!(f, "DelegateAction is not signed with the given public key"),
ActionErrorKind::DelegateActionSenderDoesNotMatchTxReceiver { sender_id, receiver_id } => write!(f, "Transaction receiver {} doesn't match DelegateAction sender {}", receiver_id, sender_id),
ActionErrorKind::DelegateActionExpired => write!(f, "DelegateAction has expired"),
ActionErrorKind::DelegateActionAccessKeyError(access_key_error) => Display::fmt(&access_key_error, f),
ActionErrorKind::DelegateActionInvalidNonce { delegate_nonce, ak_nonce } => write!(f, "DelegateAction nonce {} must be larger than nonce of the used access key {}", delegate_nonce, ak_nonce),
ActionErrorKind::DelegateActionNonceTooLarge { delegate_nonce, upper_bound } => write!(f, "DelegateAction nonce {} must be smaller than the access key nonce upper bound {}", delegate_nonce, upper_bound),
ActionErrorKind::NonRefundableTransferToExistingAccount { account_id} => {
write!(f, "Can't make non-refundable storage transfer to {} because it already exists", account_id)
}
}
}
}
#[derive(Eq, PartialEq, Clone)]
pub enum EpochError {
/// Error calculating threshold from given stakes for given number of seats.
/// Only should happened if calling code doesn't check for integer value of stake > number of seats.
ThresholdError {
stake_sum: Balance,
num_seats: u64,
},
/// Requesting validators for an epoch that wasn't computed yet.
EpochOutOfBounds(EpochId),
/// Missing block hash in the storage (means there is some structural issue).
MissingBlock(CryptoHash),
/// Error due to IO (DB read/write, serialization, etc.).
IOErr(String),
/// Given account ID is not a validator in the given epoch ID.
NotAValidator(AccountId, EpochId),
/// Error getting information for a shard
ShardingError(String),
NotEnoughValidators {
num_validators: u64,
num_shards: u64,
},
/// Error selecting validators for a chunk.
ChunkValidatorSelectionError(String),
/// Error selecting chunk producer for a shard.
ChunkProducerSelectionError(String),
}
impl std::error::Error for EpochError {}
impl Display for EpochError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
EpochError::ThresholdError { stake_sum, num_seats } => write!(
f,
"Total stake {} must be higher than the number of seats {}",
stake_sum, num_seats
),
EpochError::EpochOutOfBounds(epoch_id) => {
write!(f, "Epoch {:?} is out of bounds", epoch_id)
}
EpochError::MissingBlock(hash) => write!(f, "Missing block {}", hash),
EpochError::IOErr(err) => write!(f, "IO: {}", err),
EpochError::NotAValidator(account_id, epoch_id) => {
write!(f, "{} is not a validator in epoch {:?}", account_id, epoch_id)
}
EpochError::ShardingError(err) => write!(f, "Sharding Error: {}", err),
EpochError::NotEnoughValidators { num_shards, num_validators } => {
write!(f, "There were not enough validator proposals to fill all shards. num_proposals: {}, num_shards: {}", num_validators, num_shards)
}
EpochError::ChunkValidatorSelectionError(err) => {
write!(f, "Error selecting validators for a chunk: {}", err)
}
EpochError::ChunkProducerSelectionError(err) => {
write!(f, "Error selecting chunk producer: {}", err)
}
}
}