-
Notifications
You must be signed in to change notification settings - Fork 182
/
keeper.go
1380 lines (1187 loc) · 48.6 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/json"
"fmt"
"math"
"path/filepath"
"strconv"
"strings"
wasmvm "github.com/CosmWasm/wasmvm"
wasmvmtypes "github.com/CosmWasm/wasmvm/types"
"github.com/gogo/protobuf/proto"
"github.com/okex/exchain/libs/cosmos-sdk/codec"
"github.com/okex/exchain/libs/cosmos-sdk/store/prefix"
sdk "github.com/okex/exchain/libs/cosmos-sdk/types"
sdkerrors "github.com/okex/exchain/libs/cosmos-sdk/types/errors"
"github.com/okex/exchain/libs/cosmos-sdk/types/innertx"
"github.com/okex/exchain/libs/cosmos-sdk/x/auth/exported"
"github.com/okex/exchain/libs/tendermint/libs/log"
paramtypes "github.com/okex/exchain/x/params"
"github.com/okex/exchain/x/wasm/ioutils"
"github.com/okex/exchain/x/wasm/types"
"github.com/okex/exchain/x/wasm/watcher"
)
// contractMemoryLimit is the memory limit of each contract execution (in MiB)
// constant value so all nodes run with the same limit.
const ContractMemoryLimit = 32
const SupportedFeatures = "iterator,staking,stargate"
type contextKey int
const (
// private type creates an interface key for Context that cannot be accessed by any other package
contextKeyQueryStackSize contextKey = iota
)
// 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.WasmAddress, 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 sdk.WasmAddress, toAddr sdk.WasmAddress, amt sdk.Coins) 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.WasmAddress,
ibcPort string,
messages []wasmvmtypes.SubMsg,
origRspData []byte,
) ([]byte, error)
}
// Keeper will have a reference to Wasmer with it's own data directory.
type Keeper struct {
storeKey sdk.StoreKey
cdc *codec.CodecProxy
accountKeeper types.AccountKeeper
bank CoinTransferrer
portKeeper types.PortKeeper
capabilityKeeper types.CapabilityKeeper
wasmVM types.WasmerEngine
wasmVMQueryHandler WasmVMQueryHandler
wasmVMResponseHandler WasmVMResponseHandler
messenger Messenger
innertxKeeper innertx.InnerTxKeeper
// queryGasLimit is the max wasmvm gas that can be spent on executing a query with a contract
queryGasLimit uint64
paramSpace types.Subspace
gasRegister GasRegister
maxQueryStackSize uint32
ada types.DBAdapter
}
type defaultAdapter struct{}
func (d defaultAdapter) NewStore(ctx sdk.Context, storeKey sdk.StoreKey, pre []byte) sdk.KVStore {
store := ctx.KVStore(storeKey)
store = watcher.WrapWriteKVStore(store)
if len(pre) != 0 {
store = prefix.NewStore(store, pre)
}
return store
}
// NewKeeper creates a new contract Keeper instance
// If customEncoders is non-nil, we can use this to override some of the message handler, especially custom
func NewKeeper(
cdc *codec.CodecProxy,
storeKey sdk.StoreKey,
paramSpace paramtypes.Subspace,
accountKeeper types.AccountKeeper,
bankKeeper types.BankKeeper,
//distKeeper types.DistributionKeeper,
channelKeeper types.ChannelKeeper,
portKeeper types.PortKeeper,
capabilityKeeper types.CapabilityKeeper,
portSource types.ICS20TransferPortSource,
router MessageRouter,
queryRouter GRPCQueryRouter,
homeDir string,
wasmConfig types.WasmConfig,
supportedFeatures string,
opts ...Option,
) Keeper {
// set KeyTable if it has not already been set
if !paramSpace.HasKeyTable() {
paramSpace = paramSpace.WithKeyTable(types.ParamKeyTable())
}
watcher.SetWatchDataManager()
wasmStorageKey = storeKey
*wasmAccountKeeper = accountKeeper
*WasmbankKeeper = bankKeeper
k := newKeeper(cdc, storeKey, paramSpace, accountKeeper, bankKeeper, channelKeeper, portKeeper, capabilityKeeper, portSource, router, queryRouter, homeDir, wasmConfig, supportedFeatures, defaultAdapter{}, opts...)
*wasmGasRegister = k.gasRegister
accountKeeper.SetObserverKeeper(k)
return k
}
var (
nilwasmGasRegister = GasRegister(nil)
nilAccountKeeper = types.AccountKeeper(nil)
nilBankKeeper = types.BankKeeper(nil)
wasmStorageKey = sdk.StoreKey(sdk.NewKVStoreKey("wasm")) // need reset by NewKeeper
wasmAccountKeeper = &nilAccountKeeper //need reset by NewKeeper
WasmbankKeeper = &nilBankKeeper
wasmGasRegister = &nilwasmGasRegister
)
func NewSimulateKeeper(
cdc *codec.CodecProxy,
paramSpace types.Subspace,
accountKeeper types.AccountKeeper,
bankKeeper types.BankKeeper,
channelKeeper types.ChannelKeeper,
portKeeper types.PortKeeper,
capabilityKeeper types.CapabilityKeeper,
portSource types.ICS20TransferPortSource,
router MessageRouter,
queryRouter GRPCQueryRouter,
homeDir string,
wasmConfig types.WasmConfig,
supportedFeatures string,
opts ...Option,
) Keeper {
k := newKeeper(cdc, wasmStorageKey, paramSpace, *wasmAccountKeeper, *WasmbankKeeper, channelKeeper, portKeeper, capabilityKeeper, portSource, router, queryRouter, homeDir, wasmConfig, supportedFeatures, watcher.Adapter{}, opts...)
k.gasRegister = *wasmGasRegister
return k
}
func newKeeper(cdc *codec.CodecProxy,
storeKey sdk.StoreKey,
paramSpace types.Subspace,
accountKeeper types.AccountKeeper,
bankKeeper types.BankKeeper,
channelKeeper types.ChannelKeeper,
portKeeper types.PortKeeper,
capabilityKeeper types.CapabilityKeeper,
portSource types.ICS20TransferPortSource,
router MessageRouter,
queryRouter GRPCQueryRouter,
homeDir string,
wasmConfig types.WasmConfig,
supportedFeatures string,
ada types.DBAdapter,
opts ...Option,
) Keeper {
wasmer, err := wasmvm.NewVM(filepath.Join(homeDir, "wasm"), supportedFeatures, ContractMemoryLimit, wasmConfig.ContractDebugMode, wasmConfig.MemoryCacheSize)
if err != nil {
panic(err)
}
keeper := &Keeper{
storeKey: storeKey,
cdc: cdc,
wasmVM: wasmer,
accountKeeper: accountKeeper,
bank: NewBankCoinTransferrer(bankKeeper),
portKeeper: portKeeper,
capabilityKeeper: capabilityKeeper,
messenger: NewDefaultMessageHandler(router, channelKeeper, capabilityKeeper, cdc.GetProtocMarshal(), portSource),
queryGasLimit: wasmConfig.SmartQueryGasLimit,
paramSpace: paramSpace,
gasRegister: NewDefaultWasmGasRegister(),
ada: ada,
maxQueryStackSize: types.DefaultMaxQueryStackSize,
}
keeper.wasmVMQueryHandler = DefaultQueryPlugins(bankKeeper, channelKeeper, queryRouter, keeper)
for _, o := range opts {
o.apply(keeper)
}
// not updateable, yet
keeper.wasmVMResponseHandler = NewDefaultWasmVMContractResponseHandler(NewMessageDispatcher(keeper.messenger, keeper))
return *keeper
}
func (k Keeper) GetStoreKey() sdk.StoreKey {
return k.storeKey
}
func (k Keeper) IsContractMethodBlocked(ctx sdk.Context, contractAddr, method string) bool {
blockedMethods := k.GetContractMethodBlockedList(ctx, contractAddr)
return blockedMethods.IsMethodBlocked(method)
}
func (k Keeper) GetContractMethodBlockedList(ctx sdk.Context, contractAddr string) *types.ContractMethods {
return k.getContractMethodBlockedList(ctx, contractAddr)
}
func (k Keeper) getAllBlockedList(ctx sdk.Context) []*types.ContractMethods {
store := k.ada.NewStore(ctx, k.storeKey, nil)
it := sdk.KVStorePrefixIterator(store, types.GetContractMethodBlockedListPrefix(""))
defer it.Close()
var cms []*types.ContractMethods
for ; it.Valid(); it.Next() {
var method types.ContractMethods
err := proto.Unmarshal(it.Value(), &method)
if err != nil {
panic(err)
}
cms = append(cms, &method)
}
return cms
}
func (k Keeper) getContractMethodBlockedList(ctx sdk.Context, contractAddr string) *types.ContractMethods {
store := k.ada.NewStore(ctx, k.storeKey, nil)
key := types.GetContractMethodBlockedListPrefix(contractAddr)
data := store.Get(key)
var blockedMethods types.ContractMethods
err := proto.Unmarshal(data, &blockedMethods)
if err != nil {
panic(err)
}
return &blockedMethods
}
func (k Keeper) updateContractMethodBlockedList(ctx sdk.Context, blockedMethods *types.ContractMethods, isDelete bool) error {
oldBlockedMethods := k.getContractMethodBlockedList(ctx, blockedMethods.GetContractAddr())
if isDelete {
oldBlockedMethods.DeleteMethods(blockedMethods.Methods)
} else {
oldBlockedMethods.AddMethods(blockedMethods.Methods)
}
data, err := proto.Marshal(oldBlockedMethods)
if err != nil {
return err
}
store := k.ada.NewStore(ctx, k.storeKey, nil)
key := types.GetContractMethodBlockedListPrefix(blockedMethods.ContractAddr)
store.Set(key, data)
GetWasmParamsCache().SetNeedBlockedUpdate()
return nil
}
func (k Keeper) updateUploadAccessConfig(ctx sdk.Context, config types.AccessConfig) {
params := k.GetParams(ctx)
params.CodeUploadAccess = config
k.SetParams(ctx, params)
}
func (k Keeper) getUploadAccessConfig(ctx sdk.Context) types.AccessConfig {
//var a types.AccessConfig
//k.paramSpace.Get(ctx, types.ParamStoreKeyUploadAccess, &a)
//return a
return k.GetParams(ctx).CodeUploadAccess
}
func (k Keeper) getInstantiateAccessConfig(ctx sdk.Context) types.AccessType {
//var a types.AccessType
//k.paramSpace.Get(ctx, types.ParamStoreKeyInstantiateAccess, &a)
//return a
return k.GetParams(ctx).InstantiateDefaultPermission
}
// GetParams returns the total set of wasm parameters.
func (k Keeper) GetParams(ctx sdk.Context) types.Params {
var params types.Params
k.paramSpace.GetParamSet(ctx, ¶ms)
return params
}
func (k Keeper) InvokeExtraProposal(ctx sdk.Context, action string, extra string) error {
switch action {
case types.ActionModifyGasFactor:
return k.modifyGasFactor(ctx, extra)
}
return nil
}
// UpdateGasRegister warning, only use it in beginblock
func (k *Keeper) UpdateGasRegister(ctx sdk.Context) {
if ctx.IsCheckTx() || ctx.IsTraceTx() {
return
}
gasFactor := k.GetGasFactor(ctx)
if gasFactor != k.gasRegister.GetGasMultiplier() {
k.gasRegister.UpdateGasMultiplier(gasFactor)
}
return
}
func (k *Keeper) modifyGasFactor(ctx sdk.Context, extra string) error {
result, err := types.NewActionModifyGasFactor(extra)
if err != nil {
return err
}
value := result.MulInt64(int64(BaseGasMultiplier)).TruncateInt64()
if value <= 0 {
return types.ErrCodeInvalidGasFactor
}
k.SetGasFactor(ctx, uint64(value))
return nil
}
// get the gas factor
func (k Keeper) GetGasFactor(ctx sdk.Context) uint64 {
store := k.ada.NewStore(ctx, k.storeKey, nil)
if !store.Has(types.KeyGasFactorPrefix) {
return DefaultGasMultiplier
}
b := store.Get(types.KeyGasFactorPrefix)
if b != nil {
return sdk.BigEndianToUint64(b)
}
return DefaultGasMultiplier
}
// set the gas factor
func (k Keeper) SetGasFactor(ctx sdk.Context, factor uint64) {
store := k.ada.NewStore(ctx, k.storeKey, nil)
store.Set(types.KeyGasFactorPrefix, sdk.Uint64ToBigEndian(factor))
}
func (k Keeper) SetParams(ctx sdk.Context, ps types.Params) {
watcher.SetParams(ps)
k.paramSpace.SetParamSet(ctx, &ps)
GetWasmParamsCache().SetNeedParamsUpdate()
}
func (k Keeper) OnAccountUpdated(acc exported.Account) {
watcher.DeleteAccount(sdk.AccToAWasmddress(acc.GetAddress()))
}
func (k Keeper) create(ctx sdk.Context, creator sdk.WasmAddress, wasmCode []byte, instantiateAccess *types.AccessConfig, authZ AuthorizationPolicy) (codeID uint64, err error) {
if creator == nil {
return 0, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "cannot be nil")
}
if !authZ.CanCreateCode(k.getUploadAccessConfig(ctx), creator) {
return 0, sdkerrors.Wrap(sdkerrors.ErrUnauthorized, types.GenerateUnauthorizeError(k.GetParams(ctx).CodeUploadAccess.Permission))
}
// figure out proper instantiate access
defaultAccessConfig := k.getInstantiateAccessConfig(ctx).With(creator)
if instantiateAccess == nil {
instantiateAccess = &defaultAccessConfig
} else if !instantiateAccess.IsSubset(defaultAccessConfig) {
// we enforce this must be subset of default upload access
return 0, sdkerrors.Wrap(sdkerrors.ErrUnauthorized, "instantiate access must be subset of default upload access")
}
wasmCode, err = ioutils.Uncompress(wasmCode, uint64(types.MaxWasmSize))
if err != nil {
return 0, sdkerrors.Wrap(types.ErrCreateFailed, err.Error())
}
ctx.GasMeter().ConsumeGas(k.gasRegister.CompileCosts(len(wasmCode)), "Compiling WASM Bytecode")
checksum, err := k.wasmVM.Create(wasmCode)
if err != nil {
return 0, sdkerrors.Wrap(types.ErrCreateFailed, err.Error())
}
report, err := k.wasmVM.AnalyzeCode(checksum)
if err != nil {
return 0, sdkerrors.Wrap(types.ErrCreateFailed, err.Error())
}
codeID = k.autoIncrementID(ctx, types.KeyLastCodeID)
k.Logger(ctx).Debug("storing new contract", "features", report.RequiredFeatures, "code_id", codeID)
result, err := types.ConvertAccessConfig(*instantiateAccess)
if err != nil {
return 0, sdkerrors.Wrap(types.ErrCreateFailed, err.Error())
}
codeInfo := types.NewCodeInfo(checksum, creator, result)
k.storeCodeInfo(ctx, codeID, codeInfo)
evt := sdk.NewEvent(
types.EventTypeStoreCode,
sdk.NewAttribute(types.AttributeKeyCodeID, strconv.FormatUint(codeID, 10)),
)
for _, f := range strings.Split(report.RequiredFeatures, ",") {
evt.AppendAttributes(sdk.NewAttribute(types.AttributeKeyFeature, strings.TrimSpace(f)))
}
ctx.EventManager().EmitEvent(evt)
return codeID, nil
}
func (k Keeper) storeCodeInfo(ctx sdk.Context, codeID uint64, codeInfo types.CodeInfo) {
store := k.ada.NewStore(ctx, k.storeKey, nil)
// 0x01 | codeID (uint64) -> ContractInfo
store.Set(types.GetCodeKey(codeID), k.cdc.GetProtocMarshal().MustMarshal(&codeInfo))
}
func (k Keeper) importCode(ctx sdk.Context, codeID uint64, codeInfo types.CodeInfo, wasmCode []byte) error {
wasmCode, err := ioutils.Uncompress(wasmCode, uint64(types.MaxWasmSize))
if err != nil {
return sdkerrors.Wrap(types.ErrCreateFailed, err.Error())
}
newCodeHash, err := k.wasmVM.Create(wasmCode)
if err != nil {
return sdkerrors.Wrap(types.ErrCreateFailed, err.Error())
}
if !bytes.Equal(codeInfo.CodeHash, newCodeHash) {
return sdkerrors.Wrap(types.ErrInvalid, "code hashes not same")
}
store := k.ada.NewStore(ctx, k.storeKey, nil)
key := types.GetCodeKey(codeID)
if store.Has(key) {
return sdkerrors.Wrapf(types.ErrDuplicate, "duplicate code: %d", codeID)
}
// 0x01 | codeID (uint64) -> ContractInfo
store.Set(key, k.cdc.GetProtocMarshal().MustMarshal(&codeInfo))
return nil
}
func (k Keeper) instantiate(ctx sdk.Context, codeID uint64, creator, admin sdk.WasmAddress, initMsg []byte, label string, deposit sdk.Coins, authZ AuthorizationPolicy) (sdk.WasmAddress, []byte, error) {
//defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "instantiate")
// This method does not support parallel execution.
if ctx.ParaMsg() != nil {
ctx.ParaMsg().InvalidExecute = true
}
instanceCosts := k.gasRegister.NewContractInstanceCosts(k.IsPinnedCode(ctx, codeID), len(initMsg))
ctx.GasMeter().ConsumeGas(instanceCosts, "Loading CosmWasm module: instantiate")
// create contract address
contractAddress := k.generateContractAddress(ctx, codeID)
existingAcct := k.accountKeeper.GetAccount(ctx, sdk.WasmToAccAddress(contractAddress))
if existingAcct != nil {
return nil, nil, sdkerrors.Wrap(types.ErrAccountExists, existingAcct.GetAddress().String())
}
// deposit initial contract funds
if !deposit.IsZero() {
if err := k.bank.TransferCoins(ctx, creator, contractAddress, deposit); err != nil {
return nil, nil, err
}
} else {
// create an empty account (so we don't have issues later)
// TODO: can we remove this?
contractAccount := k.accountKeeper.NewAccountWithAddress(ctx, sdk.WasmToAccAddress(contractAddress))
k.accountKeeper.SetAccount(ctx, contractAccount)
}
// get contact info
store := k.ada.NewStore(ctx, k.storeKey, nil)
codeInfo := k.GetCodeInfo(ctx, codeID)
if codeInfo == nil {
return nil, nil, sdkerrors.Wrap(types.ErrNotFound, "code")
}
if !authZ.CanInstantiateContract(codeInfo.InstantiateConfig, creator) {
return nil, nil, sdkerrors.Wrap(sdkerrors.ErrUnauthorized, "can not instantiate")
}
// prepare params for contract instantiate call
env := types.NewEnv(ctx, contractAddress)
adapters := sdk.CoinsToCoinAdapters(deposit)
info := types.NewInfo(creator, adapters)
// create prefixed data store
// 0x03 | BuildContractAddress (sdk.WasmAddress)
prefixStore := prefix.NewStore(store, types.GetContractStorePrefix(contractAddress))
prefixStoreAdapter := types.NewStoreAdapter(prefixStore)
// prepare querier
querier := k.newQueryHandler(ctx, contractAddress)
// instantiate wasm contract
gas := k.runtimeGasForContract(ctx)
res, gasUsed, err := k.wasmVM.Instantiate(codeInfo.CodeHash, env, info, initMsg, prefixStoreAdapter, cosmwasmAPI, querier, k.gasMeter(ctx), gas, costJSONDeserialization)
k.consumeRuntimeGas(ctx, gasUsed)
if !ctx.IsCheckTx() && k.innertxKeeper != nil {
k.innertxKeeper.UpdateWasmInnerTx(ctx.TxBytes(), ctx.BlockHeight(), innertx.CosmosDepth, creator, contractAddress, innertx.CosmosCallType, types.InstantiateInnertxName, sdk.Coins{}, err, k.gasRegister.FromWasmVMGas(gasUsed), string(initMsg))
}
if err != nil {
return nil, nil, sdkerrors.Wrap(types.ErrInstantiateFailed, err.Error())
}
// persist instance first
createdAt := types.NewAbsoluteTxPosition(ctx)
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, sdkerrors.Wrap(types.ErrInstantiateFailed, err.Error())
}
if report.HasIBCEntryPoints {
// register IBC port
ibcPort, err := k.ensureIbcPort(ctx, 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)
k.addToContractCodeSecondaryIndex(ctx, contractAddress, historyEntry)
k.appendToContractHistory(ctx, contractAddress, historyEntry)
k.storeContractInfo(ctx, contractAddress, &contractInfo)
ctx.EventManager().EmitEvent(sdk.NewEvent(
types.EventTypeInstantiate,
sdk.NewAttribute(types.AttributeKeyContractAddr, contractAddress.String()),
sdk.NewAttribute(types.AttributeKeyCodeID, strconv.FormatUint(codeID, 10)),
))
data, err := k.handleContractResponse(ctx, contractAddress, contractInfo.IBCPortID, res.Messages, res.Attributes, res.Data, res.Events)
if err != nil {
return nil, nil, sdkerrors.Wrap(err, "dispatch")
}
return contractAddress, data, nil
}
// Execute executes the contract instance
func (k Keeper) execute(ctx sdk.Context, contractAddress sdk.WasmAddress, caller sdk.WasmAddress, msg []byte, coins sdk.Coins) ([]byte, error) {
//defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "execute")
contractInfo, codeInfo, prefixStore, err := k.contractInstance(ctx, contractAddress)
if err != nil {
return nil, err
}
executeCosts := k.gasRegister.InstantiateContractCosts(k.IsPinnedCode(ctx, contractInfo.CodeID), len(msg))
ctx.GasMeter().ConsumeGas(executeCosts, "Loading CosmWasm module: execute")
// add more funds
if !coins.IsZero() {
if err := k.bank.TransferCoins(ctx, caller, contractAddress, coins); err != nil {
return nil, err
}
}
env := types.NewEnv(ctx, contractAddress)
adapters := sdk.CoinsToCoinAdapters(coins)
info := types.NewInfo(caller, adapters)
// prepare querier
querier := k.newQueryHandler(ctx, contractAddress)
gas := k.runtimeGasForContract(ctx)
if k.GetParams(ctx).UseContractBlockedList {
var methodsMap map[string]interface{}
err = json.Unmarshal(msg, &methodsMap)
if err != nil {
return nil, err
}
for method := range methodsMap {
if k.IsContractMethodBlocked(ctx, contractAddress.String(), method) {
return nil, sdkerrors.Wrap(types.ErrExecuteFailed, fmt.Sprintf("%s method of contract %s is not allowed", contractAddress.String(), method))
}
}
}
res, gasUsed, execErr := k.wasmVM.Execute(codeInfo.CodeHash, env, info, msg, prefixStore, cosmwasmAPI, querier, k.gasMeter(ctx), gas, costJSONDeserialization)
k.consumeRuntimeGas(ctx, gasUsed)
if !ctx.IsCheckTx() && k.innertxKeeper != nil {
k.innertxKeeper.UpdateWasmInnerTx(ctx.TxBytes(), ctx.BlockHeight(), innertx.CosmosDepth, caller, contractAddress, innertx.CosmosCallType, types.ExecuteInnertxName, coins, err, k.gasRegister.FromWasmVMGas(gasUsed), string(msg))
}
if execErr != nil {
return nil, sdkerrors.Wrap(types.ErrExecuteFailed, execErr.Error())
}
ctx.EventManager().EmitEvent(sdk.NewEvent(
types.EventTypeExecute,
sdk.NewAttribute(types.AttributeKeyContractAddr, contractAddress.String()),
))
data, err := k.handleContractResponse(ctx, contractAddress, contractInfo.IBCPortID, res.Messages, res.Attributes, res.Data, res.Events)
if err != nil {
return nil, sdkerrors.Wrap(err, "dispatch")
}
return data, nil
}
func (k Keeper) migrate(ctx sdk.Context, contractAddress sdk.WasmAddress, caller sdk.WasmAddress, newCodeID uint64, msg []byte, authZ AuthorizationPolicy) ([]byte, error) {
//defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "migrate")
// This method does not support parallel execution.
if ctx.ParaMsg() != nil {
ctx.ParaMsg().InvalidExecute = true
}
migrateSetupCosts := k.gasRegister.InstantiateContractCosts(k.IsPinnedCode(ctx, newCodeID), len(msg))
ctx.GasMeter().ConsumeGas(migrateSetupCosts, "Loading CosmWasm module: migrate")
contractInfo := k.GetContractInfo(ctx, contractAddress)
if contractInfo == nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "unknown contract")
}
if !authZ.CanModifyContract(contractInfo.AdminAddr(), caller) {
return nil, sdkerrors.Wrap(sdkerrors.ErrUnauthorized, "can not migrate")
}
newCodeInfo := k.GetCodeInfo(ctx, newCodeID)
if newCodeInfo == nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "unknown code")
}
// check for IBC flag
switch report, err := k.wasmVM.AnalyzeCode(newCodeInfo.CodeHash); {
case err != nil:
return nil, sdkerrors.Wrap(types.ErrMigrationFailed, err.Error())
case !report.HasIBCEntryPoints && contractInfo.IBCPortID != "":
// prevent update to non ibc contract
return nil, sdkerrors.Wrap(types.ErrMigrationFailed, "requires ibc callbacks")
case report.HasIBCEntryPoints && contractInfo.IBCPortID == "":
// add ibc port
ibcPort, err := k.ensureIbcPort(ctx, contractAddress)
if err != nil {
return nil, err
}
contractInfo.IBCPortID = ibcPort
}
env := types.NewEnv(ctx, contractAddress)
// prepare querier
querier := k.newQueryHandler(ctx, contractAddress)
prefixStoreKey := types.GetContractStorePrefix(contractAddress)
prefixStore := k.ada.NewStore(ctx, k.storeKey, prefixStoreKey)
prefixAdapater := types.NewStoreAdapter(prefixStore)
gas := k.runtimeGasForContract(ctx)
res, gasUsed, err := k.wasmVM.Migrate(newCodeInfo.CodeHash, env, msg, &prefixAdapater, cosmwasmAPI, &querier, k.gasMeter(ctx), gas, costJSONDeserialization)
k.consumeRuntimeGas(ctx, gasUsed)
if !ctx.IsCheckTx() && k.innertxKeeper != nil {
k.innertxKeeper.UpdateWasmInnerTx(ctx.TxBytes(), ctx.BlockHeight(), innertx.CosmosDepth, caller, contractAddress, innertx.CosmosCallType, types.MigrateInnertxName, sdk.Coins{}, err, k.gasRegister.FromWasmVMGas(gasUsed), string(msg))
}
if err != nil {
return nil, sdkerrors.Wrap(types.ErrMigrationFailed, err.Error())
}
// delete old secondary index entry
k.removeFromContractCodeSecondaryIndex(ctx, contractAddress, k.getLastContractHistoryEntry(ctx, contractAddress))
// persist migration updates
historyEntry := contractInfo.AddMigration(ctx, newCodeID, msg)
k.appendToContractHistory(ctx, contractAddress, historyEntry)
k.addToContractCodeSecondaryIndex(ctx, contractAddress, historyEntry)
k.storeContractInfo(ctx, contractAddress, contractInfo)
ctx.EventManager().EmitEvent(sdk.NewEvent(
types.EventTypeMigrate,
sdk.NewAttribute(types.AttributeKeyCodeID, strconv.FormatUint(newCodeID, 10)),
sdk.NewAttribute(types.AttributeKeyContractAddr, contractAddress.String()),
))
data, err := k.handleContractResponse(ctx, contractAddress, contractInfo.IBCPortID, res.Messages, res.Attributes, res.Data, res.Events)
if err != nil {
return nil, sdkerrors.Wrap(err, "dispatch")
}
return data, nil
}
// Sudo allows priviledged 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)
func (k Keeper) Sudo(ctx sdk.Context, contractAddress sdk.WasmAddress, 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
}
sudoSetupCosts := k.gasRegister.InstantiateContractCosts(k.IsPinnedCode(ctx, contractInfo.CodeID), len(msg))
ctx.GasMeter().ConsumeGas(sudoSetupCosts, "Loading CosmWasm module: sudo")
env := types.NewEnv(ctx, contractAddress)
// prepare querier
querier := k.newQueryHandler(ctx, contractAddress)
gas := k.runtimeGasForContract(ctx)
res, gasUsed, execErr := k.wasmVM.Sudo(codeInfo.CodeHash, env, msg, prefixStore, cosmwasmAPI, querier, k.gasMeter(ctx), gas, costJSONDeserialization)
k.consumeRuntimeGas(ctx, gasUsed)
if execErr != nil {
return nil, sdkerrors.Wrap(types.ErrExecuteFailed, execErr.Error())
}
ctx.EventManager().EmitEvent(sdk.NewEvent(
types.EventTypeSudo,
sdk.NewAttribute(types.AttributeKeyContractAddr, contractAddress.String()),
))
data, err := k.handleContractResponse(ctx, contractAddress, contractInfo.IBCPortID, res.Messages, res.Attributes, res.Data, res.Events)
if err != nil {
return nil, sdkerrors.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.WasmAddress, reply wasmvmtypes.Reply) ([]byte, error) {
contractInfo, codeInfo, prefixStore, err := k.contractInstance(ctx, contractAddress)
if err != nil {
return nil, err
}
// always consider this pinned
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)
gas := k.runtimeGasForContract(ctx)
res, gasUsed, execErr := k.wasmVM.Reply(codeInfo.CodeHash, env, reply, prefixStore, cosmwasmAPI, querier, k.gasMeter(ctx), gas, costJSONDeserialization)
k.consumeRuntimeGas(ctx, gasUsed)
if execErr != nil {
return nil, sdkerrors.Wrap(types.ErrExecuteFailed, execErr.Error())
}
ctx.EventManager().EmitEvent(sdk.NewEvent(
types.EventTypeReply,
sdk.NewAttribute(types.AttributeKeyContractAddr, contractAddress.String()),
))
data, err := k.handleContractResponse(ctx, contractAddress, contractInfo.IBCPortID, res.Messages, res.Attributes, res.Data, res.Events)
if err != nil {
return nil, sdkerrors.Wrap(err, "dispatch")
}
return data, nil
}
// addToContractCodeSecondaryIndex adds element to the index for contracts-by-codeid queries
func (k Keeper) addToContractCodeSecondaryIndex(ctx sdk.Context, contractAddress sdk.WasmAddress, entry types.ContractCodeHistoryEntry) {
store := k.ada.NewStore(ctx, k.storeKey, nil)
store.Set(types.GetContractByCreatedSecondaryIndexKey(contractAddress, entry), []byte{})
}
// removeFromContractCodeSecondaryIndex removes element to the index for contracts-by-codeid queries
func (k Keeper) removeFromContractCodeSecondaryIndex(ctx sdk.Context, contractAddress sdk.WasmAddress, entry types.ContractCodeHistoryEntry) {
store := k.ada.NewStore(ctx, k.storeKey, nil)
store.Delete(types.GetContractByCreatedSecondaryIndexKey(contractAddress, entry))
}
// IterateContractsByCode iterates over all contracts with given codeID ASC on code update time.
func (k Keeper) IterateContractsByCode(ctx sdk.Context, codeID uint64, cb func(address sdk.WasmAddress) bool) {
prefixStore := k.ada.NewStore(ctx, k.storeKey, 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 sdk.Context, contractAddress, caller, newAdmin sdk.WasmAddress, authZ AuthorizationPolicy) (err error) {
// This method does not support parallel execution.
if ctx.ParaMsg() != nil {
ctx.ParaMsg().InvalidExecute = true
}
gas := ctx.GasMeter().GasConsumed()
defer func() {
if !ctx.IsCheckTx() && k.innertxKeeper != nil {
k.innertxKeeper.UpdateWasmInnerTx(ctx.TxBytes(), ctx.BlockHeight(), innertx.CosmosDepth, caller, contractAddress, innertx.CosmosCallType, types.SetContractAdminInnertxName, sdk.Coins{}, err, ctx.GasMeter().GasConsumed()-gas, "")
}
}()
contractInfo := k.GetContractInfo(ctx, contractAddress)
if contractInfo == nil {
return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "unknown contract")
}
if !authZ.CanModifyContract(contractInfo.AdminAddr(), caller) {
return sdkerrors.Wrap(sdkerrors.ErrUnauthorized, "can not modify contract")
}
contractInfo.Admin = newAdmin.String()
k.storeContractInfo(ctx, contractAddress, contractInfo)
return nil
}
func (k Keeper) appendToContractHistory(ctx sdk.Context, contractAddr sdk.WasmAddress, newEntries ...types.ContractCodeHistoryEntry) {
store := k.ada.NewStore(ctx, k.storeKey, nil)
// find last element position
var pos uint64
prefixStore := prefix.NewStore(store, types.GetContractCodeHistoryElementPrefix(contractAddr))
iter := prefixStore.ReverseIterator(nil, nil)
defer iter.Close()
if iter.Valid() {
pos = sdk.BigEndianToUint64(iter.Key())
}
// then store with incrementing position
for _, e := range newEntries {
pos++
key := types.GetContractCodeHistoryElementKey(contractAddr, pos)
store.Set(key, k.cdc.GetProtocMarshal().MustMarshal(&e)) //nolint:gosec
}
}
func (k Keeper) GetContractHistory(ctx sdk.Context, contractAddr sdk.WasmAddress) []types.ContractCodeHistoryEntry {
store := k.ada.NewStore(ctx, k.storeKey, types.GetContractCodeHistoryElementPrefix(contractAddr))
r := make([]types.ContractCodeHistoryEntry, 0)
iter := store.Iterator(nil, nil)
defer iter.Close()
for ; iter.Valid(); iter.Next() {
var e types.ContractCodeHistoryEntry
k.cdc.GetProtocMarshal().MustUnmarshal(iter.Value(), &e)
r = append(r, e)
}
return r
}
// getLastContractHistoryEntry returns the last element from history. To be used internally only as it panics when none exists
func (k Keeper) getLastContractHistoryEntry(ctx sdk.Context, contractAddr sdk.WasmAddress) types.ContractCodeHistoryEntry {
store := k.ada.NewStore(ctx, k.storeKey, types.GetContractCodeHistoryElementPrefix(contractAddr))
iter := store.ReverseIterator(nil, nil)
defer iter.Close()
var r types.ContractCodeHistoryEntry
if !iter.Valid() {
// all contracts have a history
panic(fmt.Sprintf("no history for %s", contractAddr.String()))
}
k.cdc.GetProtocMarshal().MustUnmarshal(iter.Value(), &r)
return r
}
// QuerySmart queries the smart contract itself.
func (k Keeper) QuerySmart(ctx sdk.Context, contractAddr sdk.WasmAddress, req []byte) ([]byte, error) {
//defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "query-smart")
// checks and increase query stack size
ctx, err := checkAndIncreaseQueryStackSize(ctx, k.maxQueryStackSize)
if err != nil {
return nil, err
}
contractInfo, codeInfo, prefixStore, err := k.contractInstance(ctx, contractAddr)
if err != nil {
return nil, err
}
smartQuerySetupCosts := k.gasRegister.InstantiateContractCosts(k.IsPinnedCode(ctx, contractInfo.CodeID), len(req))
ctx.GasMeter().ConsumeGas(smartQuerySetupCosts, "Loading CosmWasm module: query")
// prepare querier
querier := k.newQueryHandler(ctx, contractAddr)
env := types.NewEnv(ctx, contractAddr)
queryResult, gasUsed, qErr := k.wasmVM.Query(codeInfo.CodeHash, env, req, prefixStore, cosmwasmAPI, querier, k.gasMeter(ctx), k.runtimeGasForContract(ctx), costJSONDeserialization)
k.consumeRuntimeGas(ctx, gasUsed)
if qErr != nil {
return nil, sdkerrors.Wrap(types.ErrQueryFailed, qErr.Error())
}
return queryResult, nil
}
func checkAndIncreaseQueryStackSize(ctx sdk.Context, maxQueryStackSize uint32) (sdk.Context, error) {
var queryStackSize uint32
// read current value
if size := ctx.Context().Value(contextKeyQueryStackSize); size != nil {
queryStackSize = size.(uint32)
} else {
queryStackSize = 0
}
// increase
queryStackSize++
// did we go too far?
if queryStackSize > maxQueryStackSize {
return ctx, types.ErrExceedMaxQueryStackSize
}
// set updated stack size
contextCtx := context.WithValue(ctx.Context(), contextKeyQueryStackSize, queryStackSize)
ctx.SetContext(contextCtx)
return ctx, nil
}
// QueryRaw returns the contract's state for give key. Returns `nil` when key is `nil`.
func (k Keeper) QueryRaw(ctx sdk.Context, contractAddress sdk.WasmAddress, key []byte) []byte {
//defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "query-raw")
if key == nil {
return nil
}
prefixStoreKey := types.GetContractStorePrefix(contractAddress)
prefixStore := k.ada.NewStore(ctx, k.storeKey, prefixStoreKey)
return prefixStore.Get(key)
}
func (k Keeper) contractInstance(ctx sdk.Context, contractAddress sdk.WasmAddress) (types.ContractInfo, types.CodeInfo, types.StoreAdapter, error) {
store := k.ada.NewStore(ctx, k.storeKey, nil)
contractBz := store.Get(types.GetContractAddressKey(contractAddress))
if contractBz == nil {
return types.ContractInfo{}, types.CodeInfo{}, types.StoreAdapter{}, sdkerrors.Wrap(types.ErrNotFound, "contract")
}
var contractInfo types.ContractInfo
k.cdc.GetProtocMarshal().MustUnmarshal(contractBz, &contractInfo)
codeInfoBz := store.Get(types.GetCodeKey(contractInfo.CodeID))
if codeInfoBz == nil {
return contractInfo, types.CodeInfo{}, types.StoreAdapter{}, sdkerrors.Wrap(types.ErrNotFound, "code info")
}
var codeInfo types.CodeInfo
k.cdc.GetProtocMarshal().MustUnmarshal(codeInfoBz, &codeInfo)
prefixStoreKey := types.GetContractStorePrefix(contractAddress)
prefixStore := prefix.NewStore(store, prefixStoreKey)
return contractInfo, codeInfo, types.NewStoreAdapter(prefixStore), nil
}
func (k Keeper) GetContractInfo(ctx sdk.Context, contractAddress sdk.WasmAddress) *types.ContractInfo {
store := k.ada.NewStore(ctx, k.storeKey, nil)
var contract types.ContractInfo
contractBz := store.Get(types.GetContractAddressKey(contractAddress))
if contractBz == nil {
return nil
}
k.cdc.GetProtocMarshal().MustUnmarshal(contractBz, &contract)
return &contract
}
func (k Keeper) HasContractInfo(ctx sdk.Context, contractAddress sdk.WasmAddress) bool {
store := k.ada.NewStore(ctx, k.storeKey, nil)
return store.Has(types.GetContractAddressKey(contractAddress))
}
// storeContractInfo persists the ContractInfo. No secondary index updated here.
func (k Keeper) storeContractInfo(ctx sdk.Context, contractAddress sdk.WasmAddress, contract *types.ContractInfo) {
store := k.ada.NewStore(ctx, k.storeKey, nil)
store.Set(types.GetContractAddressKey(contractAddress), k.cdc.GetProtocMarshal().MustMarshal(contract))
}
func (k Keeper) IterateContractInfo(ctx sdk.Context, cb func(sdk.WasmAddress, types.ContractInfo) bool) {
prefixStore := k.ada.NewStore(ctx, k.storeKey, types.ContractKeyPrefix)
iter := prefixStore.Iterator(nil, nil)
defer iter.Close()
for ; iter.Valid(); iter.Next() {
var contract types.ContractInfo
k.cdc.GetProtocMarshal().MustUnmarshal(iter.Value(), &contract)
// cb returns true to stop early
if cb(iter.Key(), contract) {
break
}
}
}
// IterateContractState iterates through all elements of the key value store for the given contract address and passes
// them to the provided callback function. The callback method can return true to abort early.
func (k Keeper) IterateContractState(ctx sdk.Context, contractAddress sdk.WasmAddress, cb func(key, value []byte) bool) {
prefixStoreKey := types.GetContractStorePrefix(contractAddress)
prefixStore := k.ada.NewStore(ctx, k.storeKey, prefixStoreKey)
iter := prefixStore.Iterator(nil, nil)
defer iter.Close()
for ; iter.Valid(); iter.Next() {
if cb(iter.Key(), iter.Value()) {
break
}
}
}