-
Notifications
You must be signed in to change notification settings - Fork 411
/
keeper.go
1541 lines (1342 loc) · 55.2 KB
/
keeper.go
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
package keeper
import (
"bytes"
"context"
"encoding/binary"
"encoding/hex"
"fmt"
"math"
"reflect"
"strconv"
"strings"
"time"
wasmvm "github.com/CosmWasm/wasmvm/v2"
wasmvmtypes "github.com/CosmWasm/wasmvm/v2/types"
channeltypes "github.com/cosmos/ibc-go/v8/modules/core/04-channel/types"
"cosmossdk.io/collections"
corestoretypes "cosmossdk.io/core/store"
errorsmod "cosmossdk.io/errors"
"cosmossdk.io/log"
"cosmossdk.io/store/prefix"
storetypes "cosmossdk.io/store/types"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/runtime"
"github.com/cosmos/cosmos-sdk/telemetry"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
vestingexported "github.com/cosmos/cosmos-sdk/x/auth/vesting/exported"
"github.com/CosmWasm/wasmd/x/wasm/ioutils"
"github.com/CosmWasm/wasmd/x/wasm/types"
)
// contractMemoryLimit is the memory limit of each contract execution (in MiB)
// constant value so all nodes run with the same limit.
const contractMemoryLimit = 32
// Option is an extension point to instantiate keeper with non default values
type Option interface {
apply(*Keeper)
}
// WasmVMQueryHandler is an extension point for custom query handler implementations
type WasmVMQueryHandler interface {
// HandleQuery executes the requested query
HandleQuery(ctx sdk.Context, caller sdk.AccAddress, request wasmvmtypes.QueryRequest) ([]byte, error)
}
type CoinTransferrer interface {
// TransferCoins sends the coin amounts from the source to the destination with rules applied.
TransferCoins(ctx sdk.Context, fromAddr, toAddr sdk.AccAddress, amt sdk.Coins) error
}
// AccountPruner handles the balances and data cleanup for accounts that are pruned on contract instantiate.
// This is an extension point to attach custom logic
type AccountPruner interface {
// CleanupExistingAccount handles the cleanup process for balances and data of the given account. The persisted account
// type is already reset to base account at this stage.
// The method returns true when the account address can be reused. Unsupported account types are rejected by returning false
CleanupExistingAccount(ctx sdk.Context, existingAccount sdk.AccountI) (handled bool, err error)
}
// WasmVMResponseHandler is an extension point to handles the response data returned by a contract call.
type WasmVMResponseHandler interface {
// Handle processes the data returned by a contract invocation.
Handle(
ctx sdk.Context,
contractAddr sdk.AccAddress,
ibcPort string,
messages []wasmvmtypes.SubMsg,
origRspData []byte,
) ([]byte, error)
}
// list of account types that are accepted for wasm contracts. Chains importing wasmd
// can overwrite this list with the WithAcceptedAccountTypesOnContractInstantiation option.
var defaultAcceptedAccountTypes = map[reflect.Type]struct{}{
reflect.TypeOf(&authtypes.BaseAccount{}): {},
}
// Keeper will have a reference to Wasm Engine with it's own data directory.
type Keeper struct {
// The (unexposed) keys used to access the stores from the Context.
storeService corestoretypes.KVStoreService
cdc codec.Codec
accountKeeper types.AccountKeeper
bank CoinTransferrer
portKeeper types.PortKeeper
capabilityKeeper types.CapabilityKeeper
wasmVM types.WasmEngine
wasmVMQueryHandler WasmVMQueryHandler
wasmVMResponseHandler WasmVMResponseHandler
messenger Messenger
// queryGasLimit is the max wasmvm gas that can be spent on executing a query with a contract
queryGasLimit uint64
gasRegister types.GasRegister
maxQueryStackSize uint32
maxCallDepth uint32
acceptedAccountTypes map[reflect.Type]struct{}
accountPruner AccountPruner
params collections.Item[types.Params]
// propagate gov authZ to sub-messages
propagateGovAuthorization map[types.AuthorizationPolicyAction]struct{}
// the address capable of executing a MsgUpdateParams message. Typically, this
// should be the x/gov module account.
authority string
// wasmLimits contains the limits sent to wasmvm on init
wasmLimits wasmvmtypes.WasmLimits
}
func (k Keeper) getUploadAccessConfig(ctx context.Context) types.AccessConfig {
return k.GetParams(ctx).CodeUploadAccess
}
func (k Keeper) getInstantiateAccessConfig(ctx context.Context) types.AccessType {
return k.GetParams(ctx).InstantiateDefaultPermission
}
func (k Keeper) GetWasmLimits() wasmvmtypes.WasmLimits {
return k.wasmLimits
}
// GetParams returns the total set of wasm parameters.
func (k Keeper) GetParams(ctx context.Context) types.Params {
p, err := k.params.Get(ctx)
if err != nil {
panic(err)
}
return p
}
// SetParams sets all wasm parameters.
func (k Keeper) SetParams(ctx context.Context, ps types.Params) error {
return k.params.Set(ctx, ps)
}
// GetAuthority returns the x/wasm module's authority.
func (k Keeper) GetAuthority() string {
return k.authority
}
// GetGasRegister returns the x/wasm module's gas register.
func (k Keeper) GetGasRegister() types.GasRegister {
return k.gasRegister
}
func (k Keeper) create(ctx context.Context, creator sdk.AccAddress, wasmCode []byte, instantiateAccess *types.AccessConfig, authZ types.AuthorizationPolicy) (codeID uint64, checksum []byte, err error) {
if creator == nil {
return 0, checksum, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "cannot be nil")
}
sdkCtx := sdk.UnwrapSDKContext(ctx)
// figure out proper instantiate access
defaultAccessConfig := k.getInstantiateAccessConfig(sdkCtx).With(creator)
if instantiateAccess == nil {
instantiateAccess = &defaultAccessConfig
}
chainConfigs := types.ChainAccessConfigs{
Instantiate: defaultAccessConfig,
Upload: k.getUploadAccessConfig(sdkCtx),
}
if !authZ.CanCreateCode(chainConfigs, creator, *instantiateAccess) {
return 0, checksum, errorsmod.Wrap(sdkerrors.ErrUnauthorized, "can not create code")
}
if ioutils.IsGzip(wasmCode) {
sdkCtx.GasMeter().ConsumeGas(k.gasRegister.UncompressCosts(len(wasmCode)), "Uncompress gzip bytecode")
wasmCode, err = ioutils.Uncompress(wasmCode, int64(types.MaxWasmSize))
if err != nil {
return 0, checksum, types.ErrCreateFailed.Wrap(errorsmod.Wrap(err, "uncompress wasm archive").Error())
}
}
gasLeft := k.runtimeGasForContract(sdkCtx)
var gasUsed uint64
isSimulation := sdkCtx.ExecMode() == sdk.ExecModeSimulate
if isSimulation {
// only simulate storing the code, no files are written
checksum, gasUsed, err = k.wasmVM.SimulateStoreCode(wasmCode, gasLeft)
} else {
checksum, gasUsed, err = k.wasmVM.StoreCode(wasmCode, gasLeft)
}
k.consumeRuntimeGas(sdkCtx, gasUsed)
if err != nil {
return 0, checksum, errorsmod.Wrap(types.ErrCreateFailed, err.Error())
}
// simulation gets default value for capabilities
var requiredCapabilities string
if !isSimulation {
report, err := k.wasmVM.AnalyzeCode(checksum)
if err != nil {
return 0, checksum, errorsmod.Wrap(types.ErrCreateFailed, err.Error())
}
requiredCapabilities = report.RequiredCapabilities
}
codeID = k.mustAutoIncrementID(sdkCtx, types.KeySequenceCodeID)
k.Logger(sdkCtx).Debug("storing new contract", "capabilities", requiredCapabilities, "code_id", codeID)
codeInfo := types.NewCodeInfo(checksum, creator, *instantiateAccess)
k.mustStoreCodeInfo(sdkCtx, codeID, codeInfo)
evt := sdk.NewEvent(
types.EventTypeStoreCode,
sdk.NewAttribute(types.AttributeKeyChecksum, hex.EncodeToString(checksum)),
sdk.NewAttribute(types.AttributeKeyCodeID, strconv.FormatUint(codeID, 10)), // last element to be compatible with scripts
)
for _, f := range strings.Split(requiredCapabilities, ",") {
evt.AppendAttributes(sdk.NewAttribute(types.AttributeKeyRequiredCapability, strings.TrimSpace(f)))
}
sdkCtx.EventManager().EmitEvent(evt)
return codeID, checksum, nil
}
func (k Keeper) mustStoreCodeInfo(ctx context.Context, codeID uint64, codeInfo types.CodeInfo) {
store := k.storeService.OpenKVStore(ctx)
// 0x01 | codeID (uint64) -> ContractInfo
err := store.Set(types.GetCodeKey(codeID), k.cdc.MustMarshal(&codeInfo))
if err != nil {
panic(err)
}
}
func (k Keeper) importCode(ctx context.Context, codeID uint64, codeInfo types.CodeInfo, wasmCode []byte) error {
if ioutils.IsGzip(wasmCode) {
var err error
wasmCode, err = ioutils.Uncompress(wasmCode, math.MaxInt64)
if err != nil {
return types.ErrCreateFailed.Wrap(errorsmod.Wrap(err, "uncompress wasm archive").Error())
}
}
newCodeHash, err := k.wasmVM.StoreCodeUnchecked(wasmCode)
if err != nil {
return errorsmod.Wrap(types.ErrCreateFailed, err.Error())
}
if !bytes.Equal(codeInfo.CodeHash, newCodeHash) {
return errorsmod.Wrap(types.ErrInvalid, "code hashes not same")
}
store := k.storeService.OpenKVStore(ctx)
key := types.GetCodeKey(codeID)
ok, err := store.Has(key)
if err != nil {
return errorsmod.Wrap(err, "has code-id key")
}
if ok {
return errorsmod.Wrapf(types.ErrDuplicate, "duplicate code: %d", codeID)
}
// 0x01 | codeID (uint64) -> ContractInfo
return store.Set(key, k.cdc.MustMarshal(&codeInfo))
}
func (k Keeper) instantiate(
ctx context.Context,
codeID uint64,
creator, admin sdk.AccAddress,
initMsg []byte,
label string,
deposit sdk.Coins,
addressGenerator AddressGenerator,
authPolicy types.AuthorizationPolicy,
) (sdk.AccAddress, []byte, error) {
defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "instantiate")
if creator == nil {
return nil, nil, types.ErrEmpty.Wrap("creator")
}
sdkCtx := sdk.UnwrapSDKContext(ctx)
codeInfo := k.GetCodeInfo(ctx, codeID)
if codeInfo == nil {
return nil, nil, types.ErrNoSuchCodeFn(codeID).Wrapf("code id %d", codeID)
}
sdkCtx, discount := k.checkDiscountEligibility(sdkCtx, codeInfo.CodeHash, k.IsPinnedCode(sdkCtx, codeID))
setupCost := k.gasRegister.SetupContractCost(discount, len(initMsg))
sdkCtx.GasMeter().ConsumeGas(setupCost, "Loading CosmWasm module: instantiate")
if !authPolicy.CanInstantiateContract(codeInfo.InstantiateConfig, creator) {
return nil, nil, errorsmod.Wrap(sdkerrors.ErrUnauthorized, "can not instantiate")
}
contractAddress := addressGenerator(ctx, codeID, codeInfo.CodeHash)
if k.HasContractInfo(ctx, contractAddress) {
// This case must only happen for instantiate2 because instantiate is based on a counter in state.
// So we create an instantiate2 specific error message here even though technically this function
// is used for both cases.
return nil, nil, types.ErrDuplicate.Wrap("contract address already exists, try a different combination of creator, checksum and salt")
}
// check account
// every cosmos module can define custom account types when needed. The cosmos-sdk comes with extension points
// to support this and a set of base and vesting account types that we integrated in our default lists.
// But not all account types of other modules are known or may make sense for contracts, therefore we kept this
// decision logic also very flexible and extendable. We provide new options to overwrite the default settings via WithAcceptedAccountTypesOnContractInstantiation and
// WithPruneAccountTypesOnContractInstantiation as constructor arguments
existingAcct := k.accountKeeper.GetAccount(sdkCtx, contractAddress)
if existingAcct != nil {
if existingAcct.GetSequence() != 0 || existingAcct.GetPubKey() != nil {
return nil, nil, types.ErrAccountExists.Wrap("address is claimed by external account")
}
if _, accept := k.acceptedAccountTypes[reflect.TypeOf(existingAcct)]; accept {
// keep account and balance as it is
k.Logger(sdkCtx).Info("instantiate contract with existing account", "address", contractAddress.String())
} else {
// consider an account in the wasmd namespace spam and overwrite it.
k.Logger(sdkCtx).Info("pruning existing account for contract instantiation", "address", contractAddress.String())
contractAccount := k.accountKeeper.NewAccountWithAddress(sdkCtx, contractAddress)
k.accountKeeper.SetAccount(sdkCtx, contractAccount)
// also handle balance to not open cases where these accounts are abused and become liquid
switch handled, err := k.accountPruner.CleanupExistingAccount(sdkCtx, existingAcct); {
case err != nil:
return nil, nil, errorsmod.Wrap(err, "prune balance")
case !handled:
return nil, nil, types.ErrAccountExists.Wrap("address is claimed by external account")
}
}
} else {
// create an empty account (so we don't have issues later)
contractAccount := k.accountKeeper.NewAccountWithAddress(sdkCtx, contractAddress)
k.accountKeeper.SetAccount(sdkCtx, contractAccount)
}
// deposit initial contract funds
if !deposit.IsZero() {
if err := k.bank.TransferCoins(sdkCtx, creator, contractAddress, deposit); err != nil {
return nil, nil, err
}
}
// prepare params for contract instantiate call
env := types.NewEnv(sdkCtx, contractAddress)
info := types.NewInfo(creator, deposit)
// create prefixed data store
// 0x03 | BuildContractAddressClassic (sdk.AccAddress)
prefixStoreKey := types.GetContractStorePrefix(contractAddress)
vmStore := types.NewStoreAdapter(prefix.NewStore(runtime.KVStoreAdapter(k.storeService.OpenKVStore(sdkCtx)), prefixStoreKey))
// prepare querier
querier := k.newQueryHandler(sdkCtx, contractAddress)
// instantiate wasm contract
gasLeft := k.runtimeGasForContract(sdkCtx)
res, gasUsed, err := k.wasmVM.Instantiate(codeInfo.CodeHash, env, info, initMsg, vmStore, cosmwasmAPI, querier, k.gasMeter(sdkCtx), gasLeft, costJSONDeserialization)
k.consumeRuntimeGas(sdkCtx, gasUsed)
if err != nil {
return nil, nil, errorsmod.Wrap(types.ErrVMError, err.Error())
}
if res == nil {
// If this gets executed, that's a bug in wasmvm
return nil, nil, errorsmod.Wrap(types.ErrVMError, "internal wasmvm error")
}
if res.Err != "" {
return nil, nil, types.MarkErrorDeterministic(errorsmod.Wrap(types.ErrInstantiateFailed, res.Err))
}
// persist instance first
createdAt := types.NewAbsoluteTxPosition(sdkCtx)
contractInfo := types.NewContractInfo(codeID, creator, admin, label, createdAt)
// check for IBC flag
report, err := k.wasmVM.AnalyzeCode(codeInfo.CodeHash)
if err != nil {
return nil, nil, errorsmod.Wrap(types.ErrVMError, err.Error())
}
if report.HasIBCEntryPoints {
// register IBC port
ibcPort, err := k.ensureIbcPort(sdkCtx, contractAddress)
if err != nil {
return nil, nil, err
}
contractInfo.IBCPortID = ibcPort
}
// store contract before dispatch so that contract could be called back
historyEntry := contractInfo.InitialHistory(initMsg)
err = k.addToContractCodeSecondaryIndex(sdkCtx, contractAddress, historyEntry)
if err != nil {
return nil, nil, err
}
err = k.addToContractCreatorSecondaryIndex(sdkCtx, creator, historyEntry.Updated, contractAddress)
if err != nil {
return nil, nil, err
}
err = k.appendToContractHistory(sdkCtx, contractAddress, historyEntry)
if err != nil {
return nil, nil, err
}
k.mustStoreContractInfo(sdkCtx, contractAddress, &contractInfo)
sdkCtx.EventManager().EmitEvent(sdk.NewEvent(
types.EventTypeInstantiate,
sdk.NewAttribute(types.AttributeKeyContractAddr, contractAddress.String()),
sdk.NewAttribute(types.AttributeKeyCodeID, strconv.FormatUint(codeID, 10)),
))
sdkCtx = types.WithSubMsgAuthzPolicy(sdkCtx, authPolicy.SubMessageAuthorizationPolicy(types.AuthZActionInstantiate))
data, err := k.handleContractResponse(sdkCtx, contractAddress, contractInfo.IBCPortID, res.Ok.Messages, res.Ok.Attributes, res.Ok.Data, res.Ok.Events)
if err != nil {
return nil, nil, errorsmod.Wrap(err, "dispatch")
}
return contractAddress, data, nil
}
// Execute executes the contract instance
func (k Keeper) execute(ctx context.Context, contractAddress, caller sdk.AccAddress, msg []byte, coins sdk.Coins) ([]byte, error) {
defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "execute")
sdkCtx := sdk.UnwrapSDKContext(ctx)
contractInfo, codeInfo, prefixStore, err := k.contractInstance(ctx, contractAddress)
if err != nil {
return nil, err
}
sdkCtx, discount := k.checkDiscountEligibility(sdkCtx, codeInfo.CodeHash, k.IsPinnedCode(ctx, contractInfo.CodeID))
setupCost := k.gasRegister.SetupContractCost(discount, len(msg))
sdkCtx.GasMeter().ConsumeGas(setupCost, "Loading CosmWasm module: execute")
// add more funds
if !coins.IsZero() {
if err := k.bank.TransferCoins(sdkCtx, caller, contractAddress, coins); err != nil {
return nil, err
}
}
env := types.NewEnv(sdkCtx, contractAddress)
info := types.NewInfo(caller, coins)
// prepare querier
querier := k.newQueryHandler(sdkCtx, contractAddress)
gasLeft := k.runtimeGasForContract(sdkCtx)
res, gasUsed, execErr := k.wasmVM.Execute(codeInfo.CodeHash, env, info, msg, prefixStore, cosmwasmAPI, querier, k.gasMeter(sdkCtx), gasLeft, costJSONDeserialization)
k.consumeRuntimeGas(sdkCtx, gasUsed)
if execErr != nil {
return nil, errorsmod.Wrap(types.ErrVMError, execErr.Error())
}
if res == nil {
// If this gets executed, that's a bug in wasmvm
return nil, errorsmod.Wrap(types.ErrVMError, "internal wasmvm error")
}
if res.Err != "" {
return nil, types.MarkErrorDeterministic(errorsmod.Wrap(types.ErrExecuteFailed, res.Err))
}
sdkCtx.EventManager().EmitEvent(sdk.NewEvent(
types.EventTypeExecute,
sdk.NewAttribute(types.AttributeKeyContractAddr, contractAddress.String()),
))
data, err := k.handleContractResponse(sdkCtx, contractAddress, contractInfo.IBCPortID, res.Ok.Messages, res.Ok.Attributes, res.Ok.Data, res.Ok.Events)
if err != nil {
return nil, err
}
return data, nil
}
func (k Keeper) migrate(
ctx context.Context,
contractAddress sdk.AccAddress,
caller sdk.AccAddress,
newCodeID uint64,
msg []byte,
authZ types.AuthorizationPolicy,
) ([]byte, error) {
defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "migrate")
sdkCtx := sdk.UnwrapSDKContext(ctx)
contractInfo := k.GetContractInfo(ctx, contractAddress)
if contractInfo == nil {
return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "unknown contract")
}
if !authZ.CanModifyContract(contractInfo.AdminAddr(), caller) {
return nil, errorsmod.Wrap(sdkerrors.ErrUnauthorized, "can not migrate")
}
newCodeInfo := k.GetCodeInfo(ctx, newCodeID)
if newCodeInfo == nil {
return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "unknown code")
}
if !authZ.CanInstantiateContract(newCodeInfo.InstantiateConfig, caller) {
return nil, errorsmod.Wrap(sdkerrors.ErrUnauthorized, "to use new code")
}
// check for IBC flag
report, err := k.wasmVM.AnalyzeCode(newCodeInfo.CodeHash)
switch {
case err != nil:
return nil, errorsmod.Wrap(types.ErrVMError, err.Error())
case !report.HasIBCEntryPoints && contractInfo.IBCPortID != "":
// prevent update to non ibc contract
return nil, errorsmod.Wrap(types.ErrMigrationFailed, "requires ibc callbacks")
case report.HasIBCEntryPoints && contractInfo.IBCPortID == "":
// add ibc port
ibcPort, err := k.ensureIbcPort(sdkCtx, contractAddress)
if err != nil {
return nil, err
}
contractInfo.IBCPortID = ibcPort
}
var response *wasmvmtypes.Response
// check for migrate version
oldCodeInfo := k.GetCodeInfo(ctx, contractInfo.CodeID)
oldReport, err := k.wasmVM.AnalyzeCode(oldCodeInfo.CodeHash)
if err != nil {
return nil, errorsmod.Wrap(types.ErrVMError, err.Error())
}
// call migrate entrypoint, except if both migrate versions are set and the same value
if report.ContractMigrateVersion == nil ||
oldReport.ContractMigrateVersion == nil ||
*report.ContractMigrateVersion != *oldReport.ContractMigrateVersion {
response, err = k.callMigrateEntrypoint(sdkCtx, contractAddress, wasmvmtypes.Checksum(newCodeInfo.CodeHash), msg, newCodeID, caller, oldReport.ContractMigrateVersion)
if err != nil {
return nil, err
}
}
// delete old secondary index entry
err = k.removeFromContractCodeSecondaryIndex(ctx, contractAddress, k.mustGetLastContractHistoryEntry(sdkCtx, contractAddress))
if err != nil {
return nil, err
}
// persist migration updates
historyEntry := contractInfo.AddMigration(sdkCtx, newCodeID, msg)
err = k.appendToContractHistory(ctx, contractAddress, historyEntry)
if err != nil {
return nil, err
}
err = k.addToContractCodeSecondaryIndex(ctx, contractAddress, historyEntry)
if err != nil {
return nil, err
}
k.mustStoreContractInfo(ctx, contractAddress, contractInfo)
sdkCtx.EventManager().EmitEvent(sdk.NewEvent(
types.EventTypeMigrate,
sdk.NewAttribute(types.AttributeKeyCodeID, strconv.FormatUint(newCodeID, 10)),
sdk.NewAttribute(types.AttributeKeyContractAddr, contractAddress.String()),
))
var data []byte
// if migrate entry point was called
if response != nil {
sdkCtx = types.WithSubMsgAuthzPolicy(sdkCtx, authZ.SubMessageAuthorizationPolicy(types.AuthZActionMigrateContract))
data, err = k.handleContractResponse(
sdkCtx,
contractAddress,
contractInfo.IBCPortID,
response.Messages,
response.Attributes,
response.Data,
response.Events,
)
if err != nil {
return nil, errorsmod.Wrap(err, "dispatch")
}
return data, nil
}
return data, nil
}
func (k Keeper) callMigrateEntrypoint(
sdkCtx sdk.Context,
contractAddress sdk.AccAddress,
newChecksum wasmvmtypes.Checksum,
msg []byte,
newCodeID uint64,
senderAddress sdk.AccAddress,
oldMigrateVersion *uint64,
) (*wasmvmtypes.Response, error) {
sdkCtx, discount := k.checkDiscountEligibility(sdkCtx, newChecksum, k.IsPinnedCode(sdkCtx, newCodeID))
setupCost := k.gasRegister.SetupContractCost(discount, len(msg))
sdkCtx.GasMeter().ConsumeGas(setupCost, "Loading CosmWasm module: migrate")
env := types.NewEnv(sdkCtx, contractAddress)
// prepare querier
querier := k.newQueryHandler(sdkCtx, contractAddress)
prefixStoreKey := types.GetContractStorePrefix(contractAddress)
vmStore := types.NewStoreAdapter(prefix.NewStore(runtime.KVStoreAdapter(k.storeService.OpenKVStore(sdkCtx)), prefixStoreKey))
gasLeft := k.runtimeGasForContract(sdkCtx)
migrateInfo := wasmvmtypes.MigrateInfo{
Sender: senderAddress.String(),
OldMigrateVersion: oldMigrateVersion,
}
res, gasUsed, err := k.wasmVM.MigrateWithInfo(newChecksum, env, msg, migrateInfo, vmStore, cosmwasmAPI, &querier, k.gasMeter(sdkCtx), gasLeft, costJSONDeserialization)
k.consumeRuntimeGas(sdkCtx, gasUsed)
if err != nil {
return nil, errorsmod.Wrap(types.ErrVMError, err.Error())
}
if res == nil {
// If this gets executed, that's a bug in wasmvm
return nil, errorsmod.Wrap(types.ErrVMError, "internal wasmvm error")
}
if res.Err != "" {
return nil, types.MarkErrorDeterministic(errorsmod.Wrap(types.ErrMigrationFailed, res.Err))
}
return res.Ok, nil
}
// Sudo allows privileged access to a contract. This can never be called by an external tx, but only by
// another native Go module directly, or on-chain governance (if sudo proposals are enabled). Thus, the keeper doesn't
// place any access controls on it, that is the responsibility or the app developer (who passes the wasm.Keeper in app.go)
//
// Sub-messages returned from the sudo call to the contract are executed with the default authorization policy. This can be
// customized though by passing a new policy with the context. See types.WithSubMsgAuthzPolicy.
// The policy will be read in msgServer.selectAuthorizationPolicy and used for sub-message executions.
// This is an extension point for some very advanced scenarios only. Use with care!
func (k Keeper) Sudo(ctx context.Context, contractAddress sdk.AccAddress, msg []byte) ([]byte, error) {
defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "sudo")
contractInfo, codeInfo, prefixStore, err := k.contractInstance(ctx, contractAddress)
if err != nil {
return nil, err
}
sdkCtx := sdk.UnwrapSDKContext(ctx)
sdkCtx, discount := k.checkDiscountEligibility(sdkCtx, codeInfo.CodeHash, k.IsPinnedCode(ctx, contractInfo.CodeID))
setupCost := k.gasRegister.SetupContractCost(discount, len(msg))
sdkCtx.GasMeter().ConsumeGas(setupCost, "Loading CosmWasm module: sudo")
env := types.NewEnv(sdkCtx, contractAddress)
// prepare querier
querier := k.newQueryHandler(sdkCtx, contractAddress)
gasLeft := k.runtimeGasForContract(sdkCtx)
res, gasUsed, execErr := k.wasmVM.Sudo(codeInfo.CodeHash, env, msg, prefixStore, cosmwasmAPI, querier, k.gasMeter(sdkCtx), gasLeft, costJSONDeserialization)
k.consumeRuntimeGas(sdkCtx, gasUsed)
if execErr != nil {
return nil, errorsmod.Wrap(types.ErrVMError, execErr.Error())
}
if res == nil {
// If this gets executed, that's a bug in wasmvm
return nil, errorsmod.Wrap(types.ErrVMError, "internal wasmvm error")
}
if res.Err != "" {
return nil, types.MarkErrorDeterministic(errorsmod.Wrap(types.ErrExecuteFailed, res.Err))
}
sdkCtx.EventManager().EmitEvent(sdk.NewEvent(
types.EventTypeSudo,
sdk.NewAttribute(types.AttributeKeyContractAddr, contractAddress.String()),
))
// sudo submessages are executed with the default authorization policy
data, err := k.handleContractResponse(sdkCtx, contractAddress, contractInfo.IBCPortID, res.Ok.Messages, res.Ok.Attributes, res.Ok.Data, res.Ok.Events)
if err != nil {
return nil, errorsmod.Wrap(err, "dispatch")
}
return data, nil
}
// reply is only called from keeper internal functions (dispatchSubmessages) after processing the submessage
func (k Keeper) reply(ctx sdk.Context, contractAddress sdk.AccAddress, reply wasmvmtypes.Reply) ([]byte, error) {
contractInfo, codeInfo, prefixStore, err := k.contractInstance(ctx, contractAddress)
if err != nil {
return nil, err
}
replyCosts := k.gasRegister.ReplyCosts(true, reply)
ctx.GasMeter().ConsumeGas(replyCosts, "Loading CosmWasm module: reply")
env := types.NewEnv(ctx, contractAddress)
// prepare querier
querier := k.newQueryHandler(ctx, contractAddress)
gasLeft := k.runtimeGasForContract(ctx)
res, gasUsed, execErr := k.wasmVM.Reply(codeInfo.CodeHash, env, reply, prefixStore, cosmwasmAPI, querier, k.gasMeter(ctx), gasLeft, costJSONDeserialization)
k.consumeRuntimeGas(ctx, gasUsed)
if execErr != nil {
return nil, errorsmod.Wrap(types.ErrVMError, execErr.Error())
}
if res == nil {
// If this gets executed, that's a bug in wasmvm
return nil, errorsmod.Wrap(types.ErrVMError, "internal wasmvm error")
}
if res.Err != "" {
return nil, types.MarkErrorDeterministic(errorsmod.Wrap(types.ErrExecuteFailed, res.Err))
}
ctx.EventManager().EmitEvent(sdk.NewEvent(
types.EventTypeReply,
sdk.NewAttribute(types.AttributeKeyContractAddr, contractAddress.String()),
))
data, err := k.handleContractResponse(ctx, contractAddress, contractInfo.IBCPortID, res.Ok.Messages, res.Ok.Attributes, res.Ok.Data, res.Ok.Events)
if err != nil {
return nil, errorsmod.Wrap(err, "dispatch")
}
return data, nil
}
// addToContractCodeSecondaryIndex adds element to the index for contracts-by-codeid queries
func (k Keeper) addToContractCodeSecondaryIndex(ctx context.Context, contractAddress sdk.AccAddress, entry types.ContractCodeHistoryEntry) error {
store := k.storeService.OpenKVStore(ctx)
return store.Set(types.GetContractByCreatedSecondaryIndexKey(contractAddress, entry), []byte{})
}
// removeFromContractCodeSecondaryIndex removes element to the index for contracts-by-codeid queries
func (k Keeper) removeFromContractCodeSecondaryIndex(ctx context.Context, contractAddress sdk.AccAddress, entry types.ContractCodeHistoryEntry) error {
return k.storeService.OpenKVStore(ctx).Delete(types.GetContractByCreatedSecondaryIndexKey(contractAddress, entry))
}
// addToContractCreatorSecondaryIndex adds element to the index for contracts-by-creator queries
func (k Keeper) addToContractCreatorSecondaryIndex(ctx context.Context, creatorAddress sdk.AccAddress, position *types.AbsoluteTxPosition, contractAddress sdk.AccAddress) error {
store := k.storeService.OpenKVStore(ctx)
return store.Set(types.GetContractByCreatorSecondaryIndexKey(creatorAddress, position.Bytes(), contractAddress), []byte{})
}
// IterateContractsByCreator iterates over all contracts with given creator address in order of creation time asc.
func (k Keeper) IterateContractsByCreator(ctx context.Context, creator sdk.AccAddress, cb func(address sdk.AccAddress) bool) {
prefixStore := prefix.NewStore(runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)), types.GetContractsByCreatorPrefix(creator))
for iter := prefixStore.Iterator(nil, nil); iter.Valid(); iter.Next() {
key := iter.Key()
if cb(key[types.AbsoluteTxPositionLen:]) {
return
}
}
}
// IterateContractsByCode iterates over all contracts with given codeID ASC on code update time.
func (k Keeper) IterateContractsByCode(ctx context.Context, codeID uint64, cb func(address sdk.AccAddress) bool) {
prefixStore := prefix.NewStore(runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)), types.GetContractByCodeIDSecondaryIndexPrefix(codeID))
iter := prefixStore.Iterator(nil, nil)
defer iter.Close()
for ; iter.Valid(); iter.Next() {
key := iter.Key()
if cb(key[types.AbsoluteTxPositionLen:]) {
return
}
}
}
func (k Keeper) setContractAdmin(ctx context.Context, contractAddress, caller, newAdmin sdk.AccAddress, authZ types.AuthorizationPolicy) error {
sdkCtx := sdk.UnwrapSDKContext(ctx)
contractInfo := k.GetContractInfo(sdkCtx, contractAddress)
if contractInfo == nil {
return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "unknown contract")
}
if !authZ.CanModifyContract(contractInfo.AdminAddr(), caller) {
return errorsmod.Wrap(sdkerrors.ErrUnauthorized, "can not modify contract")
}
newAdminStr := newAdmin.String()
contractInfo.Admin = newAdminStr
k.mustStoreContractInfo(sdkCtx, contractAddress, contractInfo)
sdkCtx.EventManager().EmitEvent(sdk.NewEvent(
types.EventTypeUpdateContractAdmin,
sdk.NewAttribute(types.AttributeKeyContractAddr, contractAddress.String()),
sdk.NewAttribute(types.AttributeKeyNewAdmin, newAdminStr),
))
return nil
}
func (k Keeper) setContractLabel(ctx context.Context, contractAddress, caller sdk.AccAddress, newLabel string, authZ types.AuthorizationPolicy) error {
sdkCtx := sdk.UnwrapSDKContext(ctx)
contractInfo := k.GetContractInfo(sdkCtx, contractAddress)
if contractInfo == nil {
return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "unknown contract")
}
if !authZ.CanModifyContract(contractInfo.AdminAddr(), caller) {
return errorsmod.Wrap(sdkerrors.ErrUnauthorized, "can not modify contract")
}
contractInfo.Label = newLabel
k.mustStoreContractInfo(sdkCtx, contractAddress, contractInfo)
sdkCtx.EventManager().EmitEvent(sdk.NewEvent(
types.EventTypeUpdateContractLabel,
sdk.NewAttribute(types.AttributeKeyContractAddr, contractAddress.String()),
sdk.NewAttribute(types.AttributeKeyNewLabel, newLabel),
))
return nil
}
func (k Keeper) appendToContractHistory(ctx context.Context, contractAddr sdk.AccAddress, newEntries ...types.ContractCodeHistoryEntry) error {
store := k.storeService.OpenKVStore(ctx)
// find last element position
var pos uint64
prefixStore := prefix.NewStore(runtime.KVStoreAdapter(store), types.GetContractCodeHistoryElementPrefix(contractAddr))
iter := prefixStore.ReverseIterator(nil, nil)
defer iter.Close()
for ; iter.Valid(); iter.Next() {
if len(iter.Key()) == 8 { // add extra safety in a mixed contract length environment
pos = sdk.BigEndianToUint64(iter.Key())
break
}
}
// then store with incrementing position
for _, e := range newEntries {
pos++
key := types.GetContractCodeHistoryElementKey(contractAddr, pos)
if err := store.Set(key, k.cdc.MustMarshal(&e)); err != nil {
return err
}
}
return nil
}
func (k Keeper) GetContractHistory(ctx context.Context, contractAddr sdk.AccAddress) []types.ContractCodeHistoryEntry {
prefixStore := prefix.NewStore(runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)), types.GetContractCodeHistoryElementPrefix(contractAddr))
r := make([]types.ContractCodeHistoryEntry, 0)
iter := prefixStore.Iterator(nil, nil)
defer iter.Close()
for ; iter.Valid(); iter.Next() {
if len(iter.Key()) != 8 { // add extra safety in a mixed contract length environment
continue
}
var e types.ContractCodeHistoryEntry
k.cdc.MustUnmarshal(iter.Value(), &e)
r = append(r, e)
}
return r
}
// mustGetLastContractHistoryEntry returns the last element from history. To be used internally only as it panics when none exists
func (k Keeper) mustGetLastContractHistoryEntry(ctx context.Context, contractAddr sdk.AccAddress) types.ContractCodeHistoryEntry {
prefixStore := prefix.NewStore(runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)), types.GetContractCodeHistoryElementPrefix(contractAddr))
iter := prefixStore.ReverseIterator(nil, nil)
defer iter.Close()
var r types.ContractCodeHistoryEntry
for ; iter.Valid(); iter.Next() {
if len(iter.Key()) == 8 { // add extra safety in a mixed contract length environment
k.cdc.MustUnmarshal(iter.Value(), &r)
return r
}
}
// all contracts have a history
panic(fmt.Sprintf("no history for %s", contractAddr.String()))
}
// QuerySmart queries the smart contract itself.
func (k Keeper) QuerySmart(ctx context.Context, contractAddr sdk.AccAddress, req []byte) ([]byte, error) {
defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "query-smart")
// checks and increase query stack size
sdkCtx, err := checkAndIncreaseQueryStackSize(sdk.UnwrapSDKContext(ctx), k.maxQueryStackSize)
if err != nil {
return nil, err
}
contractInfo, codeInfo, prefixStore, err := k.contractInstance(sdkCtx, contractAddr)
if err != nil {
return nil, err
}
sdkCtx, discount := k.checkDiscountEligibility(sdkCtx, codeInfo.CodeHash, k.IsPinnedCode(ctx, contractInfo.CodeID))
setupCost := k.gasRegister.SetupContractCost(discount, len(req))
sdkCtx.GasMeter().ConsumeGas(setupCost, "Loading CosmWasm module: query")
// prepare querier
querier := k.newQueryHandler(sdkCtx, contractAddr)
env := types.NewEnv(sdkCtx, contractAddr)
queryResult, gasUsed, qErr := k.wasmVM.Query(codeInfo.CodeHash, env, req, prefixStore, cosmwasmAPI, querier, k.gasMeter(sdkCtx), k.runtimeGasForContract(sdkCtx), costJSONDeserialization)
k.consumeRuntimeGas(sdkCtx, gasUsed)
if qErr != nil {
return nil, errorsmod.Wrap(types.ErrVMError, qErr.Error())
}
if queryResult.Err != "" {
return nil, types.MarkErrorDeterministic(errorsmod.Wrap(types.ErrQueryFailed, queryResult.Err))
}
return queryResult.Ok, nil
}
func checkAndIncreaseQueryStackSize(ctx context.Context, maxQueryStackSize uint32) (sdk.Context, error) {
var queryStackSize uint32 = 0
if size, ok := types.QueryStackSize(ctx); ok {
queryStackSize = size
}
// increase
queryStackSize++
// did we go too far?
if queryStackSize > maxQueryStackSize {
return sdk.Context{}, types.ErrExceedMaxQueryStackSize
}
// set updated stack size
return types.WithQueryStackSize(sdk.UnwrapSDKContext(ctx), queryStackSize), nil
}
func checkAndIncreaseCallDepth(ctx context.Context, maxCallDepth uint32) (sdk.Context, error) {
var callDepth uint32 = 0
if size, ok := types.CallDepth(ctx); ok {
callDepth = size
}
// increase
callDepth++
// did we go too far?
if callDepth > maxCallDepth {
return sdk.Context{}, types.ErrExceedMaxCallDepth
}
// set updated stack size
return types.WithCallDepth(sdk.UnwrapSDKContext(ctx), callDepth), nil
}
// QueryRaw returns the contract's state for give key. Returns `nil` when key is `nil`.
func (k Keeper) QueryRaw(ctx context.Context, contractAddress sdk.AccAddress, key []byte) []byte {
defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "query-raw")
if key == nil {
return nil
}
prefixStoreKey := types.GetContractStorePrefix(contractAddress)
prefixStore := prefix.NewStore(runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)), prefixStoreKey)
return prefixStore.Get(key)
}
// internal helper function
func (k Keeper) contractInstance(ctx context.Context, contractAddress sdk.AccAddress) (types.ContractInfo, types.CodeInfo, wasmvm.KVStore, error) {
store := k.storeService.OpenKVStore(ctx)
contractBz, err := store.Get(types.GetContractAddressKey(contractAddress))
if err != nil {
return types.ContractInfo{}, types.CodeInfo{}, nil, err
}
if contractBz == nil {
return types.ContractInfo{}, types.CodeInfo{}, nil, types.ErrNoSuchContractFn(contractAddress.String()).
Wrapf("address %s", contractAddress.String())
}
var contractInfo types.ContractInfo
k.cdc.MustUnmarshal(contractBz, &contractInfo)
codeInfoBz, err := store.Get(types.GetCodeKey(contractInfo.CodeID))
if err != nil {
return types.ContractInfo{}, types.CodeInfo{}, nil, err
}
if codeInfoBz == nil {
return contractInfo, types.CodeInfo{}, nil, types.ErrNoSuchCodeFn(contractInfo.CodeID).
Wrapf("code id %d", contractInfo.CodeID)
}
var codeInfo types.CodeInfo
k.cdc.MustUnmarshal(codeInfoBz, &codeInfo)
prefixStoreKey := types.GetContractStorePrefix(contractAddress)
prefixStore := prefix.NewStore(runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)), prefixStoreKey)
return contractInfo, codeInfo, types.NewStoreAdapter(prefixStore), nil
}
func (k Keeper) LoadAsyncAckPacket(ctx context.Context, portID, channelID string, sequence uint64) (channeltypes.Packet, error) {
prefixStore, key := k.getAsyncAckStoreAndKey(ctx, portID, channelID, sequence)
packetBz := prefixStore.Get(key)
if len(packetBz) == 0 {
return channeltypes.Packet{}, types.ErrNotFound.Wrap("packet")
}
var packet channeltypes.Packet
// unmarshal packet
if err := k.cdc.Unmarshal(packetBz, &packet); err != nil {
return channeltypes.Packet{}, err
}
return packet, nil
}
func (k Keeper) StoreAsyncAckPacket(ctx context.Context, packet channeltypes.Packet) error {
prefixStore, key := k.getAsyncAckStoreAndKey(ctx, packet.DestinationPort, packet.DestinationChannel, packet.Sequence)
packetBz, err := k.cdc.Marshal(&packet)
if err != nil {
return err
}
prefixStore.Set(key, packetBz)
return nil
}
func (k Keeper) DeleteAsyncAckPacket(ctx context.Context, portID, channelID string, sequence uint64) {
prefixStore, key := k.getAsyncAckStoreAndKey(ctx, portID, channelID, sequence)
prefixStore.Delete(key)
}