-
Notifications
You must be signed in to change notification settings - Fork 409
/
types.go
468 lines (416 loc) · 13.1 KB
/
types.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
package types
import (
"encoding/hex"
"fmt"
"reflect"
wasmvmtypes "github.com/CosmWasm/wasmvm/v2/types"
"github.com/cosmos/gogoproto/proto"
errorsmod "cosmossdk.io/errors"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
)
const (
defaultMemoryCacheSize uint32 = 100 // in MiB
defaultSmartQueryGasLimit uint64 = 3_000_000
defaultContractDebugMode = false
// ContractAddrLen defines a valid address length for contracts
ContractAddrLen = 32
// SDKAddrLen defines a valid address length that was used in sdk address generation
SDKAddrLen = 20
)
func (m Model) ValidateBasic() error {
if len(m.Key) == 0 {
return errorsmod.Wrap(ErrEmpty, "key")
}
return nil
}
func (c CodeInfo) ValidateBasic() error {
if len(c.CodeHash) == 0 {
return errorsmod.Wrap(ErrEmpty, "code hash")
}
if _, err := sdk.AccAddressFromBech32(c.Creator); err != nil {
return errorsmod.Wrap(err, "creator")
}
if err := c.InstantiateConfig.ValidateBasic(); err != nil {
return errorsmod.Wrap(err, "instantiate config")
}
return nil
}
// NewCodeInfo fills a new CodeInfo struct
func NewCodeInfo(codeHash []byte, creator sdk.AccAddress, instantiatePermission AccessConfig) CodeInfo {
return CodeInfo{
CodeHash: codeHash,
Creator: creator.String(),
InstantiateConfig: instantiatePermission,
}
}
var AllCodeHistoryTypes = []ContractCodeHistoryOperationType{ContractCodeHistoryOperationTypeGenesis, ContractCodeHistoryOperationTypeInit, ContractCodeHistoryOperationTypeMigrate}
// NewContractInfo creates a new instance of a given WASM contract info
func NewContractInfo(codeID uint64, creator, admin sdk.AccAddress, label string, createdAt *AbsoluteTxPosition) ContractInfo {
var adminAddr string
if !admin.Empty() {
adminAddr = admin.String()
}
return ContractInfo{
CodeID: codeID,
Creator: creator.String(),
Admin: adminAddr,
Label: label,
Created: createdAt,
}
}
// validatable is an optional interface that can be implemented by an ContractInfoExtension to enable validation
type validatable interface {
ValidateBasic() error
}
// ValidateBasic does syntax checks on the data. If an extension is set and has the `ValidateBasic() error` method, then
// the method is called as well. It is recommend to implement `ValidateBasic` so that the data is verified in the setter
// but also in the genesis import process.
func (c *ContractInfo) ValidateBasic() error {
if c.CodeID == 0 {
return errorsmod.Wrap(ErrEmpty, "code id")
}
if _, err := sdk.AccAddressFromBech32(c.Creator); err != nil {
return errorsmod.Wrap(err, "creator")
}
if len(c.Admin) != 0 {
if _, err := sdk.AccAddressFromBech32(c.Admin); err != nil {
return errorsmod.Wrap(err, "admin")
}
}
if err := ValidateLabel(c.Label); err != nil {
return errorsmod.Wrap(err, "label")
}
if c.Extension == nil {
return nil
}
e, ok := c.Extension.GetCachedValue().(validatable)
if !ok {
return nil
}
if err := e.ValidateBasic(); err != nil {
return errorsmod.Wrap(err, "extension")
}
return nil
}
// SetExtension set new extension data. Calls `ValidateBasic() error` on non nil values when method is implemented by
// the extension.
func (c *ContractInfo) SetExtension(ext ContractInfoExtension) error {
if ext == nil {
c.Extension = nil
return nil
}
if e, ok := ext.(validatable); ok {
if err := e.ValidateBasic(); err != nil {
return err
}
}
codecAny, err := codectypes.NewAnyWithValue(ext)
if err != nil {
return errorsmod.Wrap(sdkerrors.ErrPackAny, err.Error())
}
c.Extension = codecAny
return nil
}
// ReadExtension copies the extension value to the pointer passed as argument so that there is no need to cast
// For example with a custom extension of type `MyContractDetails` it will look as following:
//
// var d MyContractDetails
// if err := info.ReadExtension(&d); err != nil {
// return nil, errorsmod.Wrap(err, "extension")
// }
func (c *ContractInfo) ReadExtension(e ContractInfoExtension) error {
rv := reflect.ValueOf(e)
if rv.Kind() != reflect.Ptr || rv.IsNil() {
return errorsmod.Wrap(sdkerrors.ErrInvalidType, "not a pointer")
}
if c.Extension == nil {
return nil
}
cached := c.Extension.GetCachedValue()
elem := reflect.ValueOf(cached).Elem()
if !elem.Type().AssignableTo(rv.Elem().Type()) {
return errorsmod.Wrapf(sdkerrors.ErrInvalidType, "extension is of type %s but argument of %s", elem.Type(), rv.Elem().Type())
}
rv.Elem().Set(elem)
return nil
}
func (c ContractInfo) InitialHistory(initMsg []byte) ContractCodeHistoryEntry {
return ContractCodeHistoryEntry{
Operation: ContractCodeHistoryOperationTypeInit,
CodeID: c.CodeID,
Updated: c.Created,
Msg: initMsg,
}
}
func (c *ContractInfo) AddMigration(ctx sdk.Context, codeID uint64, msg []byte) ContractCodeHistoryEntry {
h := ContractCodeHistoryEntry{
Operation: ContractCodeHistoryOperationTypeMigrate,
CodeID: codeID,
Updated: NewAbsoluteTxPosition(ctx),
Msg: msg,
}
c.CodeID = codeID
return h
}
// AdminAddr convert into sdk.AccAddress or nil when not set
func (c *ContractInfo) AdminAddr() sdk.AccAddress {
if c.Admin == "" {
return nil
}
admin, err := sdk.AccAddressFromBech32(c.Admin)
if err != nil { // should never happen
panic(err.Error())
}
return admin
}
// ContractInfoExtension defines the extension point for custom data to be stored with a contract info
type ContractInfoExtension interface {
proto.Message
String() string
}
var _ codectypes.UnpackInterfacesMessage = &ContractInfo{}
// UnpackInterfaces implements codectypes.UnpackInterfaces
func (c *ContractInfo) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error {
var details ContractInfoExtension
if err := unpacker.UnpackAny(c.Extension, &details); err != nil {
return err
}
return codectypes.UnpackInterfaces(details, unpacker)
}
// NewAbsoluteTxPosition gets a block position from the context
func NewAbsoluteTxPosition(ctx sdk.Context) *AbsoluteTxPosition {
// we must safely handle nil gas meters
var index uint64
meter := ctx.BlockGasMeter()
if meter != nil {
index = meter.GasConsumed()
}
height := ctx.BlockHeight()
if height < 0 {
panic(fmt.Sprintf("unsupported height: %d", height))
}
return &AbsoluteTxPosition{
BlockHeight: uint64(height),
TxIndex: index,
}
}
// LessThan can be used to sort
func (a *AbsoluteTxPosition) LessThan(b *AbsoluteTxPosition) bool {
if a == nil {
return true
}
if b == nil {
return false
}
return a.BlockHeight < b.BlockHeight || (a.BlockHeight == b.BlockHeight && a.TxIndex < b.TxIndex)
}
// AbsoluteTxPositionLen number of elements in byte representation
const AbsoluteTxPositionLen = 16
// Bytes encodes the object into a 16 byte representation with big endian block height and tx index.
func (a *AbsoluteTxPosition) Bytes() []byte {
if a == nil {
panic("object must not be nil")
}
r := make([]byte, AbsoluteTxPositionLen)
copy(r[0:], sdk.Uint64ToBigEndian(a.BlockHeight))
copy(r[8:], sdk.Uint64ToBigEndian(a.TxIndex))
return r
}
// ValidateBasic syntax checks
func (c ContractCodeHistoryEntry) ValidateBasic() error {
var found bool
for _, v := range AllCodeHistoryTypes {
if c.Operation == v {
found = true
break
}
}
if !found {
return ErrInvalid.Wrap("operation")
}
if c.CodeID == 0 {
return ErrEmpty.Wrap("code id")
}
if c.Updated == nil {
return ErrEmpty.Wrap("updated")
}
return errorsmod.Wrap(c.Msg.ValidateBasic(), "msg")
}
// NewEnv initializes the environment for a contract instance
func NewEnv(ctx sdk.Context, contractAddr sdk.AccAddress) wasmvmtypes.Env {
// safety checks before casting below
if ctx.BlockHeight() < 0 {
panic("Block height must never be negative")
}
nano := ctx.BlockTime().UnixNano()
if nano < 1 {
panic("Block (unix) time must never be empty or negative ")
}
env := wasmvmtypes.Env{
Block: wasmvmtypes.BlockInfo{
Height: uint64(ctx.BlockHeight()),
Time: wasmvmtypes.Uint64(nano),
ChainID: ctx.ChainID(),
},
Contract: wasmvmtypes.ContractInfo{
Address: contractAddr.String(),
},
}
if txCounter, ok := TXCounter(ctx); ok {
env.Transaction = &wasmvmtypes.TransactionInfo{Index: txCounter}
}
return env
}
// NewInfo initializes the MessageInfo for a contract instance
func NewInfo(creator sdk.AccAddress, deposit sdk.Coins) wasmvmtypes.MessageInfo {
return wasmvmtypes.MessageInfo{
Sender: creator.String(),
Funds: NewWasmCoins(deposit),
}
}
// NewWasmCoins translates between Cosmos SDK coins and Wasm coins
func NewWasmCoins(cosmosCoins sdk.Coins) (wasmCoins []wasmvmtypes.Coin) {
for _, coin := range cosmosCoins {
wasmCoin := wasmvmtypes.Coin{
Denom: coin.Denom,
Amount: coin.Amount.String(),
}
wasmCoins = append(wasmCoins, wasmCoin)
}
return wasmCoins
}
// VMConfig contains configurations that are passed on to CosmWasm VM.
type VMConfig struct {
// WasmLimits are the limits that are used for static validation of Wasm binaries.
WasmLimits wasmvmtypes.WasmLimits
}
// NodeConfig is the extra config required for wasm
type NodeConfig struct {
// SimulationGasLimit is the max gas to be used in a tx simulation call.
// When not set the consensus max block gas is used instead
SimulationGasLimit *uint64 `mapstructure:"simulation_gas_limit"`
// SmartQueryGasLimit is the max gas to be used in a smart query contract call
SmartQueryGasLimit uint64 `mapstructure:"query_gas_limit"`
// MemoryCacheSize in MiB not bytes
MemoryCacheSize uint32 `mapstructure:"memory_cache_size"`
// ContractDebugMode log what contract print
ContractDebugMode bool
}
// DefaultNodeConfig returns the default settings for NodeConfig
func DefaultNodeConfig() NodeConfig {
return NodeConfig{
SmartQueryGasLimit: defaultSmartQueryGasLimit,
MemoryCacheSize: defaultMemoryCacheSize,
ContractDebugMode: defaultContractDebugMode,
}
}
// DefaultConfigTemplate toml snippet with default values for app.toml
func DefaultConfigTemplate() string {
return ConfigTemplate(DefaultNodeConfig())
}
// ConfigTemplate toml snippet for app.toml
func ConfigTemplate(c NodeConfig) string {
simGasLimit := `# simulation_gas_limit =`
if c.SimulationGasLimit != nil {
simGasLimit = fmt.Sprintf(`simulation_gas_limit = %d`, *c.SimulationGasLimit)
}
return fmt.Sprintf(`
[wasm]
# Smart query gas limit is the max gas to be used in a smart query contract call
query_gas_limit = %d
# in-memory cache for Wasm contracts. Set to 0 to disable.
# The value is in MiB not bytes
memory_cache_size = %d
# Simulation gas limit is the max gas to be used in a tx simulation call.
# When not set the consensus max block gas is used instead
%s
`, c.SmartQueryGasLimit, c.MemoryCacheSize, simGasLimit)
}
// VerifyAddressLen ensures that the address matches the expected length
func VerifyAddressLen() func(addr []byte) error {
return func(addr []byte) error {
if len(addr) != ContractAddrLen && len(addr) != SDKAddrLen {
return sdkerrors.ErrInvalidAddress
}
return nil
}
}
// IsSubset will return true if the caller is the same as the superset,
// or if the caller is more restrictive than the superset.
func (a AccessType) IsSubset(superSet AccessType) bool {
switch superSet {
case AccessTypeEverybody:
// Everything is a subset of this
return a != AccessTypeUnspecified
case AccessTypeNobody:
// Only an exact match is a subset of this
return a == AccessTypeNobody
case AccessTypeAnyOfAddresses:
// Nobody or address(es)
return a == AccessTypeNobody || a == AccessTypeAnyOfAddresses
default:
return false
}
}
// IsSubset will return true if the caller is the same as the superset,
// or if the caller is more restrictive than the superset.
func (a AccessConfig) IsSubset(superSet AccessConfig) bool {
switch superSet.Permission {
case AccessTypeAnyOfAddresses:
// An exact match or nobody
return a.Permission == AccessTypeNobody || a.Permission == AccessTypeAnyOfAddresses && isSubset(superSet.Addresses, a.Addresses)
case AccessTypeUnspecified:
return false
default:
return a.Permission.IsSubset(superSet.Permission)
}
}
// return true when all elements in sub are also part of super
func isSubset(super, sub []string) bool {
if len(sub) == 0 {
return true
}
var matches int
for _, o := range sub {
for _, s := range super {
if o == s {
matches++
break
}
}
}
return matches == len(sub)
}
// AllAuthorizedAddresses returns the list of authorized addresses. Can be empty.
func (a AccessConfig) AllAuthorizedAddresses() []string {
if a.Permission == AccessTypeAnyOfAddresses {
return a.Addresses
}
return []string{}
}
type txContracts map[string]struct{}
type TxContracts struct {
// contracts contains the contracts (identified by checksum) which have already been executed in a transaction
contracts txContracts
}
func NewTxContracts() TxContracts {
c := make(txContracts, 0)
return TxContracts{contracts: c}
}
func (tc TxContracts) AddContract(checksum []byte) {
if len(checksum) == 0 {
return
}
hexHash := hex.EncodeToString(checksum)
tc.contracts[hexHash] = struct{}{}
}
func (tc TxContracts) Exists(checksum []byte) bool {
hexHash := hex.EncodeToString(checksum)
_, ok := tc.contracts[hexHash]
return ok
}
func (tc TxContracts) GetContracts() txContracts {
return tc.contracts
}