-
Notifications
You must be signed in to change notification settings - Fork 11.1k
/
transaction.rs
3353 lines (3032 loc) · 116 KB
/
transaction.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 super::{base_types::*, error::*, SUI_BRIDGE_OBJECT_ID};
use crate::authenticator_state::ActiveJwk;
use crate::committee::{Committee, EpochId, ProtocolVersion};
use crate::crypto::{
default_hash, AuthoritySignInfo, AuthoritySignInfoTrait, AuthoritySignature,
AuthorityStrongQuorumSignInfo, DefaultHash, Ed25519SuiSignature, EmptySignInfo,
RandomnessRound, Signature, Signer, SuiSignatureInner, ToFromBytes,
};
use crate::digests::{CertificateDigest, SenderSignedDataDigest};
use crate::digests::{ChainIdentifier, ConsensusCommitDigest, ZKLoginInputsDigest};
use crate::execution::SharedInput;
use crate::message_envelope::{Envelope, Message, TrustedEnvelope, VerifiedEnvelope};
use crate::messages_checkpoint::CheckpointTimestamp;
use crate::messages_consensus::{ConsensusCommitPrologue, ConsensusCommitPrologueV2};
use crate::object::{MoveObject, Object, Owner};
use crate::programmable_transaction_builder::ProgrammableTransactionBuilder;
use crate::signature::{GenericSignature, VerifyParams};
use crate::signature_verification::{
verify_sender_signed_data_message_signatures, VerifiedDigestCache,
};
use crate::{
SUI_AUTHENTICATOR_STATE_OBJECT_ID, SUI_AUTHENTICATOR_STATE_OBJECT_SHARED_VERSION,
SUI_CLOCK_OBJECT_ID, SUI_CLOCK_OBJECT_SHARED_VERSION, SUI_FRAMEWORK_PACKAGE_ID,
SUI_RANDOMNESS_STATE_OBJECT_ID, SUI_SYSTEM_STATE_OBJECT_ID,
SUI_SYSTEM_STATE_OBJECT_SHARED_VERSION,
};
use enum_dispatch::enum_dispatch;
use fastcrypto::{encoding::Base64, hash::HashFunction};
use itertools::Either;
use move_core_types::ident_str;
use move_core_types::identifier::IdentStr;
use move_core_types::{identifier::Identifier, language_storage::TypeTag};
use nonempty::{nonempty, NonEmpty};
use serde::{Deserialize, Serialize};
use shared_crypto::intent::{Intent, IntentMessage, IntentScope};
use std::fmt::Write;
use std::fmt::{Debug, Display, Formatter};
use std::iter::once;
use std::sync::Arc;
use std::{
collections::{BTreeMap, BTreeSet, HashSet},
hash::Hash,
iter,
};
use strum::IntoStaticStr;
use sui_protocol_config::{ProtocolConfig, SupportedProtocolVersions};
use tap::Pipe;
use tracing::trace;
pub const TEST_ONLY_GAS_UNIT_FOR_TRANSFER: u64 = 10_000;
pub const TEST_ONLY_GAS_UNIT_FOR_OBJECT_BASICS: u64 = 50_000;
pub const TEST_ONLY_GAS_UNIT_FOR_PUBLISH: u64 = 70_000;
pub const TEST_ONLY_GAS_UNIT_FOR_STAKING: u64 = 50_000;
pub const TEST_ONLY_GAS_UNIT_FOR_GENERIC: u64 = 50_000;
pub const TEST_ONLY_GAS_UNIT_FOR_SPLIT_COIN: u64 = 10_000;
// For some transactions we may either perform heavy operations or touch
// objects that are storage expensive. That may happen (and often is the case)
// because the object touched are set up in genesis and carry no storage cost
// (and thus rebate) on first usage.
pub const TEST_ONLY_GAS_UNIT_FOR_HEAVY_COMPUTATION_STORAGE: u64 = 5_000_000;
pub const GAS_PRICE_FOR_SYSTEM_TX: u64 = 1;
pub const DEFAULT_VALIDATOR_GAS_PRICE: u64 = 1000;
const BLOCKED_MOVE_FUNCTIONS: [(ObjectID, &str, &str); 0] = [];
#[cfg(test)]
#[cfg(feature = "test-utils")]
#[path = "unit_tests/messages_tests.rs"]
mod messages_tests;
#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
pub enum CallArg {
// contains no structs or objects
Pure(Vec<u8>),
// an object
Object(ObjectArg),
}
impl CallArg {
pub const SUI_SYSTEM_MUT: Self = Self::Object(ObjectArg::SUI_SYSTEM_MUT);
pub const CLOCK_IMM: Self = Self::Object(ObjectArg::SharedObject {
id: SUI_CLOCK_OBJECT_ID,
initial_shared_version: SUI_CLOCK_OBJECT_SHARED_VERSION,
mutable: false,
});
pub const CLOCK_MUT: Self = Self::Object(ObjectArg::SharedObject {
id: SUI_CLOCK_OBJECT_ID,
initial_shared_version: SUI_CLOCK_OBJECT_SHARED_VERSION,
mutable: true,
});
pub const AUTHENTICATOR_MUT: Self = Self::Object(ObjectArg::SharedObject {
id: SUI_AUTHENTICATOR_STATE_OBJECT_ID,
initial_shared_version: SUI_AUTHENTICATOR_STATE_OBJECT_SHARED_VERSION,
mutable: true,
});
}
#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy, Serialize, Deserialize)]
pub enum ObjectArg {
// A Move object, either immutable, or owned mutable.
ImmOrOwnedObject(ObjectRef),
// A Move object that's shared.
// SharedObject::mutable controls whether caller asks for a mutable reference to shared object.
SharedObject {
id: ObjectID,
initial_shared_version: SequenceNumber,
mutable: bool,
},
// A Move object that can be received in this transaction.
Receiving(ObjectRef),
}
fn type_tag_validity_check(
tag: &TypeTag,
config: &ProtocolConfig,
starting_count: &mut usize,
) -> UserInputResult<()> {
let mut stack = vec![(tag, 1)];
while let Some((tag, depth)) = stack.pop() {
*starting_count += 1;
fp_ensure!(
*starting_count < config.max_type_arguments() as usize,
UserInputError::SizeLimitExceeded {
limit: "maximum type arguments in a call transaction".to_string(),
value: config.max_type_arguments().to_string()
}
);
fp_ensure!(
depth < config.max_type_argument_depth(),
UserInputError::SizeLimitExceeded {
limit: "maximum type argument depth in a call transaction".to_string(),
value: config.max_type_argument_depth().to_string()
}
);
match tag {
TypeTag::Bool
| TypeTag::U8
| TypeTag::U64
| TypeTag::U128
| TypeTag::Address
| TypeTag::Signer
| TypeTag::U16
| TypeTag::U32
| TypeTag::U256 => (),
TypeTag::Vector(t) => {
stack.push((t, depth + 1));
}
TypeTag::Struct(s) => {
let next_depth = depth + 1;
stack.extend(s.type_params.iter().map(|t| (t, next_depth)));
}
}
}
Ok(())
}
#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
pub struct ChangeEpoch {
/// The next (to become) epoch ID.
pub epoch: EpochId,
/// The protocol version in effect in the new epoch.
pub protocol_version: ProtocolVersion,
/// The total amount of gas charged for storage during the epoch.
pub storage_charge: u64,
/// The total amount of gas charged for computation during the epoch.
pub computation_charge: u64,
/// The amount of storage rebate refunded to the txn senders.
pub storage_rebate: u64,
/// The non-refundable storage fee.
pub non_refundable_storage_fee: u64,
/// Unix timestamp when epoch started
pub epoch_start_timestamp_ms: u64,
/// System packages (specifically framework and move stdlib) that are written before the new
/// epoch starts. This tracks framework upgrades on chain. When executing the ChangeEpoch txn,
/// the validator must write out the modules below. Modules are provided with the version they
/// will be upgraded to, their modules in serialized form (which include their package ID), and
/// a list of their transitive dependencies.
pub system_packages: Vec<(SequenceNumber, Vec<Vec<u8>>, Vec<ObjectID>)>,
}
#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
pub struct GenesisTransaction {
pub objects: Vec<GenesisObject>,
}
#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
pub enum GenesisObject {
RawObject {
data: crate::object::Data,
owner: crate::object::Owner,
},
}
impl GenesisObject {
pub fn id(&self) -> ObjectID {
match self {
GenesisObject::RawObject { data, .. } => data.id(),
}
}
}
#[derive(Debug, Hash, PartialEq, Eq, Clone, Serialize, Deserialize)]
pub struct AuthenticatorStateExpire {
/// expire JWKs that have a lower epoch than this
pub min_epoch: u64,
/// The initial version of the authenticator object that it was shared at.
pub authenticator_obj_initial_shared_version: SequenceNumber,
}
impl AuthenticatorStateExpire {
pub fn authenticator_obj_initial_shared_version(&self) -> SequenceNumber {
self.authenticator_obj_initial_shared_version
}
}
#[derive(Debug, Hash, PartialEq, Eq, Clone, Serialize, Deserialize)]
pub struct AuthenticatorStateUpdate {
/// Epoch of the authenticator state update transaction
pub epoch: u64,
/// Consensus round of the authenticator state update
pub round: u64,
/// newly active jwks
pub new_active_jwks: Vec<ActiveJwk>,
/// The initial version of the authenticator object that it was shared at.
pub authenticator_obj_initial_shared_version: SequenceNumber,
// to version this struct, do not add new fields. Instead, add a AuthenticatorStateUpdateV2 to
// TransactionKind.
}
impl AuthenticatorStateUpdate {
pub fn authenticator_obj_initial_shared_version(&self) -> SequenceNumber {
self.authenticator_obj_initial_shared_version
}
}
#[derive(Debug, Hash, PartialEq, Eq, Clone, Serialize, Deserialize)]
pub struct RandomnessStateUpdate {
/// Epoch of the randomness state update transaction
pub epoch: u64,
/// Randomness round of the update
pub randomness_round: RandomnessRound,
/// Updated random bytes
pub random_bytes: Vec<u8>,
/// The initial version of the randomness object that it was shared at.
pub randomness_obj_initial_shared_version: SequenceNumber,
// to version this struct, do not add new fields. Instead, add a RandomnessStateUpdateV2 to
// TransactionKind.
}
impl RandomnessStateUpdate {
pub fn randomness_obj_initial_shared_version(&self) -> SequenceNumber {
self.randomness_obj_initial_shared_version
}
}
#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize, IntoStaticStr)]
pub enum TransactionKind {
/// A transaction that allows the interleaving of native commands and Move calls
ProgrammableTransaction(ProgrammableTransaction),
/// A system transaction that will update epoch information on-chain.
/// It will only ever be executed once in an epoch.
/// The argument is the next epoch number, which is critical
/// because it ensures that this transaction has a unique digest.
/// This will eventually be translated to a Move call during execution.
/// It also doesn't require/use a gas object.
/// A validator will not sign a transaction of this kind from outside. It only
/// signs internally during epoch changes.
///
/// The ChangeEpoch enumerant is now deprecated (but the ChangeEpoch struct is still used by
/// EndOfEpochTransaction below).
ChangeEpoch(ChangeEpoch),
Genesis(GenesisTransaction),
ConsensusCommitPrologue(ConsensusCommitPrologue),
AuthenticatorStateUpdate(AuthenticatorStateUpdate),
/// EndOfEpochTransaction replaces ChangeEpoch with a list of transactions that are allowed to
/// run at the end of the epoch.
EndOfEpochTransaction(Vec<EndOfEpochTransactionKind>),
RandomnessStateUpdate(RandomnessStateUpdate),
// V2 ConsensusCommitPrologue also includes the digest of the current consensus output.
ConsensusCommitPrologueV2(ConsensusCommitPrologueV2),
// .. more transaction types go here
}
/// EndOfEpochTransactionKind
#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize, IntoStaticStr)]
pub enum EndOfEpochTransactionKind {
ChangeEpoch(ChangeEpoch),
AuthenticatorStateCreate,
AuthenticatorStateExpire(AuthenticatorStateExpire),
RandomnessStateCreate,
DenyListStateCreate,
BridgeStateCreate(ChainIdentifier),
BridgeCommitteeInit(SequenceNumber),
}
impl EndOfEpochTransactionKind {
pub fn new_change_epoch(
next_epoch: EpochId,
protocol_version: ProtocolVersion,
storage_charge: u64,
computation_charge: u64,
storage_rebate: u64,
non_refundable_storage_fee: u64,
epoch_start_timestamp_ms: u64,
system_packages: Vec<(SequenceNumber, Vec<Vec<u8>>, Vec<ObjectID>)>,
) -> Self {
Self::ChangeEpoch(ChangeEpoch {
epoch: next_epoch,
protocol_version,
storage_charge,
computation_charge,
storage_rebate,
non_refundable_storage_fee,
epoch_start_timestamp_ms,
system_packages,
})
}
pub fn new_authenticator_state_expire(
min_epoch: u64,
authenticator_obj_initial_shared_version: SequenceNumber,
) -> Self {
Self::AuthenticatorStateExpire(AuthenticatorStateExpire {
min_epoch,
authenticator_obj_initial_shared_version,
})
}
pub fn new_authenticator_state_create() -> Self {
Self::AuthenticatorStateCreate
}
pub fn new_randomness_state_create() -> Self {
Self::RandomnessStateCreate
}
pub fn new_deny_list_state_create() -> Self {
Self::DenyListStateCreate
}
pub fn new_bridge_create(chain_identifier: ChainIdentifier) -> Self {
Self::BridgeStateCreate(chain_identifier)
}
pub fn init_bridge_committee(bridge_shared_version: SequenceNumber) -> Self {
Self::BridgeCommitteeInit(bridge_shared_version)
}
fn input_objects(&self) -> Vec<InputObjectKind> {
match self {
Self::ChangeEpoch(_) => {
vec![InputObjectKind::SharedMoveObject {
id: SUI_SYSTEM_STATE_OBJECT_ID,
initial_shared_version: SUI_SYSTEM_STATE_OBJECT_SHARED_VERSION,
mutable: true,
}]
}
Self::AuthenticatorStateCreate => vec![],
Self::AuthenticatorStateExpire(expire) => {
vec![InputObjectKind::SharedMoveObject {
id: SUI_AUTHENTICATOR_STATE_OBJECT_ID,
initial_shared_version: expire.authenticator_obj_initial_shared_version(),
mutable: true,
}]
}
Self::RandomnessStateCreate => vec![],
Self::DenyListStateCreate => vec![],
Self::BridgeStateCreate(_) => vec![],
Self::BridgeCommitteeInit(bridge_version) => vec![
InputObjectKind::SharedMoveObject {
id: SUI_BRIDGE_OBJECT_ID,
initial_shared_version: *bridge_version,
mutable: true,
},
InputObjectKind::SharedMoveObject {
id: SUI_SYSTEM_STATE_OBJECT_ID,
initial_shared_version: SUI_SYSTEM_STATE_OBJECT_SHARED_VERSION,
mutable: true,
},
],
}
}
fn shared_input_objects(&self) -> impl Iterator<Item = SharedInputObject> + '_ {
match self {
Self::ChangeEpoch(_) => {
Either::Left(vec![SharedInputObject::SUI_SYSTEM_OBJ].into_iter())
}
Self::AuthenticatorStateExpire(expire) => Either::Left(
vec![SharedInputObject {
id: SUI_AUTHENTICATOR_STATE_OBJECT_ID,
initial_shared_version: expire.authenticator_obj_initial_shared_version(),
mutable: true,
}]
.into_iter(),
),
Self::AuthenticatorStateCreate => Either::Right(iter::empty()),
Self::RandomnessStateCreate => Either::Right(iter::empty()),
Self::DenyListStateCreate => Either::Right(iter::empty()),
Self::BridgeStateCreate(_) => Either::Right(iter::empty()),
Self::BridgeCommitteeInit(bridge_version) => Either::Left(
vec![
SharedInputObject {
id: SUI_BRIDGE_OBJECT_ID,
initial_shared_version: *bridge_version,
mutable: true,
},
SharedInputObject::SUI_SYSTEM_OBJ,
]
.into_iter(),
),
}
}
fn validity_check(&self, config: &ProtocolConfig) -> UserInputResult {
match self {
Self::ChangeEpoch(_) => (),
Self::AuthenticatorStateCreate | Self::AuthenticatorStateExpire(_) => {
// Transaction should have been rejected earlier (or never formed).
assert!(config.enable_jwk_consensus_updates());
}
Self::RandomnessStateCreate => {
// Transaction should have been rejected earlier (or never formed).
assert!(config.random_beacon());
}
Self::DenyListStateCreate => {
// Transaction should have been rejected earlier (or never formed).
assert!(config.enable_coin_deny_list());
}
Self::BridgeStateCreate(_) | Self::BridgeCommitteeInit(_) => {
// Transaction should have been rejected earlier (or never formed).
assert!(config.enable_bridge());
}
}
Ok(())
}
}
impl VersionedProtocolMessage for TransactionKind {
fn check_version_supported(&self, protocol_config: &ProtocolConfig) -> SuiResult {
// When adding new cases, they must be guarded by a feature flag and return
// UnsupportedFeatureError if the flag is not set.
match &self {
TransactionKind::ChangeEpoch(_)
| TransactionKind::Genesis(_)
| TransactionKind::ConsensusCommitPrologue(_) => Ok(()),
TransactionKind::ProgrammableTransaction(pt) => {
// NB: we don't use the `receiving_objects` method here since we don't want to check
// for any validity requirements such as duplicate receiving inputs at this point.
if !protocol_config.receiving_objects_supported() {
let has_receiving_objects = pt
.inputs
.iter()
.any(|arg| !arg.receiving_objects().is_empty());
if has_receiving_objects {
return Err(SuiError::UnsupportedFeatureError {
error: format!(
"receiving objects is not supported at {:?}",
protocol_config.version
),
});
}
}
Ok(())
}
TransactionKind::AuthenticatorStateUpdate(_) => {
if protocol_config.enable_jwk_consensus_updates() {
Ok(())
} else {
Err(SuiError::UnsupportedFeatureError {
error: "authenticator state updates not enabled".to_string(),
})
}
}
TransactionKind::RandomnessStateUpdate(_) => {
if protocol_config.random_beacon() {
Ok(())
} else {
Err(SuiError::UnsupportedFeatureError {
error: "randomness state updates not enabled".to_string(),
})
}
}
TransactionKind::EndOfEpochTransaction(txns) => {
if !protocol_config.end_of_epoch_transaction_supported() {
Err(SuiError::UnsupportedFeatureError {
error: "EndOfEpochTransaction is not supported".to_string(),
})
} else {
for tx in txns {
match tx {
EndOfEpochTransactionKind::ChangeEpoch(_) => (),
EndOfEpochTransactionKind::AuthenticatorStateCreate
| EndOfEpochTransactionKind::AuthenticatorStateExpire(_) => {
if !protocol_config.enable_jwk_consensus_updates() {
return Err(SuiError::UnsupportedFeatureError {
error: "authenticator state updates not enabled"
.to_string(),
});
}
}
EndOfEpochTransactionKind::RandomnessStateCreate => {
if !protocol_config.random_beacon() {
return Err(SuiError::UnsupportedFeatureError {
error: "random beacon not enabled".to_string(),
});
}
}
EndOfEpochTransactionKind::DenyListStateCreate => {
if !protocol_config.enable_coin_deny_list() {
return Err(SuiError::UnsupportedFeatureError {
error: "coin deny list not enabled".to_string(),
});
}
}
EndOfEpochTransactionKind::BridgeStateCreate(_) => {
if !protocol_config.enable_bridge() {
return Err(SuiError::UnsupportedFeatureError {
error: "bridge not enabled".to_string(),
});
}
}
EndOfEpochTransactionKind::BridgeCommitteeInit(_) => {
if !protocol_config.enable_bridge() {
return Err(SuiError::UnsupportedFeatureError {
error: "bridge not enabled".to_string(),
});
}
}
}
}
Ok(())
}
}
TransactionKind::ConsensusCommitPrologueV2(_) => {
if protocol_config.include_consensus_digest_in_prologue() {
Ok(())
} else {
Err(SuiError::UnsupportedFeatureError {
error: "ConsensusCommitPrologueV2 is not supported".to_string(),
})
}
}
}
}
}
impl CallArg {
fn input_objects(&self) -> Vec<InputObjectKind> {
match self {
CallArg::Pure(_) => vec![],
CallArg::Object(ObjectArg::ImmOrOwnedObject(object_ref)) => {
vec![InputObjectKind::ImmOrOwnedMoveObject(*object_ref)]
}
CallArg::Object(ObjectArg::SharedObject {
id,
initial_shared_version,
mutable,
}) => {
let id = *id;
let initial_shared_version = *initial_shared_version;
let mutable = *mutable;
vec![InputObjectKind::SharedMoveObject {
id,
initial_shared_version,
mutable,
}]
}
// Receiving objects are not part of the input objects.
CallArg::Object(ObjectArg::Receiving(_)) => vec![],
}
}
fn receiving_objects(&self) -> Vec<ObjectRef> {
match self {
CallArg::Pure(_) => vec![],
CallArg::Object(o) => match o {
ObjectArg::ImmOrOwnedObject(_) => vec![],
ObjectArg::SharedObject { .. } => vec![],
ObjectArg::Receiving(obj_ref) => vec![*obj_ref],
},
}
}
pub fn validity_check(&self, config: &ProtocolConfig) -> UserInputResult {
match self {
CallArg::Pure(p) => {
fp_ensure!(
p.len() < config.max_pure_argument_size() as usize,
UserInputError::SizeLimitExceeded {
limit: "maximum pure argument size".to_string(),
value: config.max_pure_argument_size().to_string()
}
);
}
CallArg::Object(_) => (),
}
Ok(())
}
}
impl From<bool> for CallArg {
fn from(b: bool) -> Self {
// unwrap safe because every u8 value is BCS-serializable
CallArg::Pure(bcs::to_bytes(&b).unwrap())
}
}
impl From<u8> for CallArg {
fn from(n: u8) -> Self {
// unwrap safe because every u8 value is BCS-serializable
CallArg::Pure(bcs::to_bytes(&n).unwrap())
}
}
impl From<u16> for CallArg {
fn from(n: u16) -> Self {
// unwrap safe because every u16 value is BCS-serializable
CallArg::Pure(bcs::to_bytes(&n).unwrap())
}
}
impl From<u32> for CallArg {
fn from(n: u32) -> Self {
// unwrap safe because every u32 value is BCS-serializable
CallArg::Pure(bcs::to_bytes(&n).unwrap())
}
}
impl From<u64> for CallArg {
fn from(n: u64) -> Self {
// unwrap safe because every u64 value is BCS-serializable
CallArg::Pure(bcs::to_bytes(&n).unwrap())
}
}
impl From<u128> for CallArg {
fn from(n: u128) -> Self {
// unwrap safe because every u128 value is BCS-serializable
CallArg::Pure(bcs::to_bytes(&n).unwrap())
}
}
impl From<&Vec<u8>> for CallArg {
fn from(v: &Vec<u8>) -> Self {
// unwrap safe because every vec<u8> value is BCS-serializable
CallArg::Pure(bcs::to_bytes(v).unwrap())
}
}
impl From<ObjectRef> for CallArg {
fn from(obj: ObjectRef) -> Self {
CallArg::Object(ObjectArg::ImmOrOwnedObject(obj))
}
}
impl ObjectArg {
pub const SUI_SYSTEM_MUT: Self = Self::SharedObject {
id: SUI_SYSTEM_STATE_OBJECT_ID,
initial_shared_version: SUI_SYSTEM_STATE_OBJECT_SHARED_VERSION,
mutable: true,
};
pub fn id(&self) -> ObjectID {
match self {
ObjectArg::Receiving((id, _, _))
| ObjectArg::ImmOrOwnedObject((id, _, _))
| ObjectArg::SharedObject { id, .. } => *id,
}
}
}
// Add package IDs, `ObjectID`, for types defined in modules.
fn add_type_tag_packages(packages: &mut BTreeSet<ObjectID>, type_argument: &TypeTag) {
let mut stack = vec![type_argument];
while let Some(cur) = stack.pop() {
match cur {
TypeTag::Bool
| TypeTag::U8
| TypeTag::U64
| TypeTag::U128
| TypeTag::Address
| TypeTag::Signer
| TypeTag::U16
| TypeTag::U32
| TypeTag::U256 => (),
TypeTag::Vector(inner) => stack.push(inner),
TypeTag::Struct(struct_tag) => {
packages.insert(struct_tag.address.into());
stack.extend(struct_tag.type_params.iter())
}
}
}
}
/// A series of commands where the results of one command can be used in future
/// commands
#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
pub struct ProgrammableTransaction {
/// Input objects or primitive values
pub inputs: Vec<CallArg>,
/// The commands to be executed sequentially. A failure in any command will
/// result in the failure of the entire transaction.
pub commands: Vec<Command>,
}
/// A single command in a programmable transaction.
#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
pub enum Command {
/// A call to either an entry or a public Move function
MoveCall(Box<ProgrammableMoveCall>),
/// `(Vec<forall T:key+store. T>, address)`
/// It sends n-objects to the specified address. These objects must have store
/// (public transfer) and either the previous owner must be an address or the object must
/// be newly created.
TransferObjects(Vec<Argument>, Argument),
/// `(&mut Coin<T>, Vec<u64>)` -> `Vec<Coin<T>>`
/// It splits off some amounts into a new coins with those amounts
SplitCoins(Argument, Vec<Argument>),
/// `(&mut Coin<T>, Vec<Coin<T>>)`
/// It merges n-coins into the first coin
MergeCoins(Argument, Vec<Argument>),
/// Publishes a Move package. It takes the package bytes and a list of the package's transitive
/// dependencies to link against on-chain.
Publish(Vec<Vec<u8>>, Vec<ObjectID>),
/// `forall T: Vec<T> -> vector<T>`
/// Given n-values of the same type, it constructs a vector. For non objects or an empty vector,
/// the type tag must be specified.
MakeMoveVec(Option<TypeTag>, Vec<Argument>),
/// Upgrades a Move package
/// Takes (in order):
/// 1. A vector of serialized modules for the package.
/// 2. A vector of object ids for the transitive dependencies of the new package.
/// 3. The object ID of the package being upgraded.
/// 4. An argument holding the `UpgradeTicket` that must have been produced from an earlier command in the same
/// programmable transaction.
Upgrade(Vec<Vec<u8>>, Vec<ObjectID>, ObjectID, Argument),
}
/// An argument to a programmable transaction command
#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy, Serialize, Deserialize)]
pub enum Argument {
/// The gas coin. The gas coin can only be used by-ref, except for with
/// `TransferObjects`, which can use it by-value.
GasCoin,
/// One of the input objects or primitive values (from
/// `ProgrammableTransaction` inputs)
Input(u16),
/// The result of another command (from `ProgrammableTransaction` commands)
Result(u16),
/// Like a `Result` but it accesses a nested result. Currently, the only usage
/// of this is to access a value from a Move call with multiple return values.
NestedResult(u16, u16),
}
/// The command for calling a Move function, either an entry function or a public
/// function (which cannot return references).
#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
pub struct ProgrammableMoveCall {
/// The package containing the module and function.
pub package: ObjectID,
/// The specific module in the package containing the function.
pub module: Identifier,
/// The function to be called.
pub function: Identifier,
/// The type arguments to the function.
pub type_arguments: Vec<TypeTag>,
/// The arguments to the function.
pub arguments: Vec<Argument>,
}
impl ProgrammableMoveCall {
fn input_objects(&self) -> Vec<InputObjectKind> {
let ProgrammableMoveCall {
package,
type_arguments,
..
} = self;
let mut packages = BTreeSet::from([*package]);
for type_argument in type_arguments {
add_type_tag_packages(&mut packages, type_argument)
}
packages
.into_iter()
.map(InputObjectKind::MovePackage)
.collect()
}
pub fn validity_check(&self, config: &ProtocolConfig) -> UserInputResult {
let is_blocked = BLOCKED_MOVE_FUNCTIONS.contains(&(
self.package,
self.module.as_str(),
self.function.as_str(),
));
fp_ensure!(!is_blocked, UserInputError::BlockedMoveFunction);
let mut type_arguments_count = 0;
for tag in &self.type_arguments {
type_tag_validity_check(tag, config, &mut type_arguments_count)?;
}
fp_ensure!(
self.arguments.len() < config.max_arguments() as usize,
UserInputError::SizeLimitExceeded {
limit: "maximum arguments in a move call".to_string(),
value: config.max_arguments().to_string()
}
);
Ok(())
}
fn is_input_arg_used(&self, arg: u16) -> bool {
self.arguments
.iter()
.any(|a| matches!(a, Argument::Input(inp) if *inp == arg))
}
}
impl Command {
pub fn move_call(
package: ObjectID,
module: Identifier,
function: Identifier,
type_arguments: Vec<TypeTag>,
arguments: Vec<Argument>,
) -> Self {
Command::MoveCall(Box::new(ProgrammableMoveCall {
package,
module,
function,
type_arguments,
arguments,
}))
}
fn input_objects(&self) -> Vec<InputObjectKind> {
match self {
Command::Upgrade(_, deps, package_id, _) => deps
.iter()
.map(|id| InputObjectKind::MovePackage(*id))
.chain(Some(InputObjectKind::MovePackage(*package_id)))
.collect(),
Command::Publish(_, deps) => deps
.iter()
.map(|id| InputObjectKind::MovePackage(*id))
.collect(),
Command::MoveCall(c) => c.input_objects(),
Command::MakeMoveVec(Some(t), _) => {
let mut packages = BTreeSet::new();
add_type_tag_packages(&mut packages, t);
packages
.into_iter()
.map(InputObjectKind::MovePackage)
.collect()
}
Command::MakeMoveVec(None, _)
| Command::TransferObjects(_, _)
| Command::SplitCoins(_, _)
| Command::MergeCoins(_, _) => vec![],
}
}
fn non_system_packages_to_be_published(&self) -> Option<&Vec<Vec<u8>>> {
match self {
Command::Upgrade(v, _, _, _) => Some(v),
Command::Publish(v, _) => Some(v),
Command::MoveCall(_)
| Command::TransferObjects(_, _)
| Command::SplitCoins(_, _)
| Command::MergeCoins(_, _)
| Command::MakeMoveVec(_, _) => None,
}
}
fn validity_check(&self, config: &ProtocolConfig) -> UserInputResult {
match self {
Command::MoveCall(call) => call.validity_check(config)?,
Command::TransferObjects(args, _)
| Command::MergeCoins(_, args)
| Command::SplitCoins(_, args) => {
fp_ensure!(!args.is_empty(), UserInputError::EmptyCommandInput);
fp_ensure!(
args.len() < config.max_arguments() as usize,
UserInputError::SizeLimitExceeded {
limit: "maximum arguments in a programmable transaction command"
.to_string(),
value: config.max_arguments().to_string()
}
);
}
Command::MakeMoveVec(ty_opt, args) => {
// ty_opt.is_none() ==> !args.is_empty()
fp_ensure!(
ty_opt.is_some() || !args.is_empty(),
UserInputError::EmptyCommandInput
);
if let Some(ty) = ty_opt {
let mut type_arguments_count = 0;
type_tag_validity_check(ty, config, &mut type_arguments_count)?;
}
fp_ensure!(
args.len() < config.max_arguments() as usize,
UserInputError::SizeLimitExceeded {
limit: "maximum arguments in a programmable transaction command"
.to_string(),
value: config.max_arguments().to_string()
}
);
}
Command::Publish(modules, deps) | Command::Upgrade(modules, deps, _, _) => {
fp_ensure!(!modules.is_empty(), UserInputError::EmptyCommandInput);
fp_ensure!(
modules.len() < config.max_modules_in_publish() as usize,
UserInputError::SizeLimitExceeded {
limit: "maximum modules in a programmable transaction upgrade command"
.to_string(),
value: config.max_modules_in_publish().to_string()
}
);
if let Some(max_package_dependencies) = config.max_package_dependencies_as_option()
{
fp_ensure!(
deps.len() < max_package_dependencies as usize,
UserInputError::SizeLimitExceeded {
limit: "maximum package dependencies".to_string(),
value: max_package_dependencies.to_string()
}
);
};
}
};
Ok(())
}
fn is_input_arg_used(&self, input_arg: u16) -> bool {
match self {
Command::MoveCall(c) => c.is_input_arg_used(input_arg),
Command::TransferObjects(args, arg)
| Command::MergeCoins(arg, args)
| Command::SplitCoins(arg, args) => args
.iter()
.chain(once(arg))
.any(|a| matches!(a, Argument::Input(inp) if *inp == input_arg)),
Command::MakeMoveVec(_, args) => args
.iter()
.any(|a| matches!(a, Argument::Input(inp) if *inp == input_arg)),
Command::Upgrade(_, _, _, arg) => {
matches!(arg, Argument::Input(inp) if *inp == input_arg)
}
Command::Publish(_, _) => false,
}
}
}
pub fn write_sep<T: Display>(
f: &mut Formatter<'_>,
items: impl IntoIterator<Item = T>,
sep: &str,
) -> std::fmt::Result {
let mut xs = items.into_iter();
let Some(x) = xs.next() else {
return Ok(());
};
write!(f, "{x}")?;
for x in xs {
write!(f, "{sep}{x}")?;
}
Ok(())
}
impl ProgrammableTransaction {
pub fn input_objects(&self) -> UserInputResult<Vec<InputObjectKind>> {
let ProgrammableTransaction { inputs, commands } = self;
let input_arg_objects = inputs
.iter()
.flat_map(|arg| arg.input_objects())
.collect::<Vec<_>>();
// all objects, not just mutable, must be unique
let mut used = HashSet::new();
if !input_arg_objects.iter().all(|o| used.insert(o.object_id())) {
return Err(UserInputError::DuplicateObjectRefInput);
}
// do not duplicate packages referred to in commands
let command_input_objects: BTreeSet<InputObjectKind> = commands
.iter()
.flat_map(|command| command.input_objects())
.collect();
Ok(input_arg_objects
.into_iter()
.chain(command_input_objects)
.collect())
}