forked from scrtlabs/SecretNetwork
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.go
524 lines (455 loc) Β· 17.6 KB
/
lib.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
package cosmwasm
import (
"encoding/json"
"fmt"
"github.com/scrtlabs/SecretNetwork/go-cosmwasm/api"
types "github.com/scrtlabs/SecretNetwork/go-cosmwasm/types"
v010types "github.com/scrtlabs/SecretNetwork/go-cosmwasm/types/v010"
v1types "github.com/scrtlabs/SecretNetwork/go-cosmwasm/types/v1"
)
// CodeHash represents an ID for a given wasm code blob, must be generated from this library
type CodeHash []byte
// WasmCode is an alias for raw bytes of the wasm compiled code
type WasmCode []byte
// KVStore is a reference to some sub-kvstore that is valid for one instance of a code
type KVStore = api.KVStore
// GoAPI is a reference to some "precompiles", go callbacks
type GoAPI = api.GoAPI
// Querier lets us make read-only queries on other modules
type Querier = types.Querier
// GasMeter is a read-only version of the sdk gas meter
type GasMeter = api.GasMeter
// Wasmer is the main entry point to this library.
// You should create an instance with it's own subdirectory to manage state inside,
// and call it for all cosmwasm code related actions.
type Wasmer struct {
cache api.Cache
}
// NewWasmer creates a new binding, with the given dataDir where
// it can store raw wasm and the pre-compile cache.
// cacheSize sets the size of an optional in-memory LRU cache for prepared VMs.
// They allow popular contracts to be executed very rapidly (no loading overhead),
// but require ~32-64MB each in memory usage.
func NewWasmer(dataDir string, supportedFeatures string, cacheSize uint64, moduleCacheSize uint16) (*Wasmer, error) {
cache, err := api.InitCache(dataDir, supportedFeatures, cacheSize)
if err != nil {
return nil, err
}
err = api.InitEnclaveRuntime(moduleCacheSize)
if err != nil {
return nil, err
}
return &Wasmer{cache: cache}, nil
}
// Cleanup should be called when no longer using this to free resources on the rust-side
func (w *Wasmer) Cleanup() {
api.ReleaseCache(w.cache)
}
// Create will compile the wasm code, and store the resulting pre-compile
// as well as the original code. Both can be referenced later via CodeID
// This must be done one time for given code, after which it can be
// instatitated many times, and each instance called many times.
//
// For example, the code for all ERC-20 contracts should be the same.
// This function stores the code for that contract only once, but it can
// be instantiated with custom inputs in the future.
//
// TODO: return gas cost? Add gas limit??? there is no metering here...
func (w *Wasmer) Create(code WasmCode) (CodeHash, error) {
return api.Create(w.cache, code)
}
// GetCode will load the original wasm code for the given code id.
// This will only succeed if that code id was previously returned from
// a call to Create.
//
// This can be used so that the (short) code id (hash) is stored in the iavl tree
// and the larger binary blobs (wasm and pre-compiles) are all managed by the
// rust library
func (w *Wasmer) GetCode(code CodeHash) (WasmCode, error) {
return api.GetCode(w.cache, code)
}
// This struct helps us to distinguish between v0.10 contract response and v1 contract response
type ContractExecResponse struct {
V1 *V1ContractExecResponse `json:"v1,omitempty"`
V010 *V010ContractExecResponse `json:"v010,omitempty"`
InternaReplyEnclaveSig []byte `json:"internal_reply_enclave_sig"`
InternalMsgId []byte `json:"internal_msg_id"`
IBCBasic *v1types.IBCBasicResult `json:"ibc_basic,omitempty"`
IBCPacketReceive *v1types.IBCReceiveResult `json:"ibc_packet_receive,omitempty"`
IBCChannelOpen *v1types.IBCOpenChannelResult `json:"ibc_open_channel,omitempty"`
}
type V010ContractExecResponse struct {
Ok *v010types.HandleResponse `json:"Ok,omitempty"`
Err *types.StdError `json:"Err,omitempty"`
}
type V1ContractExecResponse struct {
Ok *v1types.Response `json:"Ok,omitempty"`
Err *types.StdError `json:"Err,omitempty"`
}
type V010orV1ContractInitResponse struct {
V1 *V1ContractInitResponse `json:"v1,omitempty"`
V010 *V010ContractInitResponse `json:"v010,omitempty"`
InternaReplyEnclaveSig []byte `json:"internal_reply_enclave_sig"`
InternalMsgId []byte `json:"internal_msg_id"`
}
type V010ContractInitResponse struct {
Ok *v010types.InitResponse `json:"Ok,omitempty"`
Err *types.StdError `json:"Err,omitempty"`
}
type V1ContractInitResponse struct {
Ok *v1types.Response `json:"Ok,omitempty"`
Err *types.StdError `json:"Err,omitempty"`
}
// Instantiate will create a new contract based on the given codeID.
// We can set the initMsg (contract "genesis") here, and it then receives
// an account and address and can be invoked (Execute) many times.
//
// Storage should be set with a PrefixedKVStore that this code can safely access.
//
// Under the hood, we may recompile the wasm, use a cached native compile, or even use a cached instance
// for performance.
func (w *Wasmer) Instantiate(
codeId CodeHash,
env types.Env,
initMsg []byte,
store KVStore,
goapi GoAPI,
querier Querier,
gasMeter GasMeter,
gasLimit uint64,
sigInfo types.SigInfo,
admin []byte,
// data, contractKey, adminProof, gasUsed, error
) (interface{}, []byte, []byte, uint64, error) {
paramBin, err := json.Marshal(env)
if err != nil {
return nil, nil, nil, 0, err
}
sigInfoBin, err := json.Marshal(sigInfo)
if err != nil {
return nil, nil, nil, 0, err
}
data, gasUsed, err := api.Instantiate(w.cache, codeId, paramBin, initMsg, &gasMeter, store, &goapi, &querier, gasLimit, sigInfoBin, admin)
if err != nil {
return nil, nil, nil, gasUsed, err
}
key := data[0:64]
adminProof := data[64:96]
data = data[96:]
var respV010orV1 V010orV1ContractInitResponse
err = json.Unmarshal(data, &respV010orV1)
if err != nil {
// unidentified response π€·
return nil, nil, nil, gasUsed, fmt.Errorf("instantiate: cannot parse response from json: %w", err)
}
isOutputAddressedToReply := len(respV010orV1.InternaReplyEnclaveSig) > 0 && len(respV010orV1.InternalMsgId) > 0
// init v0.10 response
if respV010orV1.V010 != nil {
if respV010orV1.V010.Err != nil {
return v1types.DataWithInternalReplyInfo{
InternalMsgId: respV010orV1.InternalMsgId,
InternaReplyEnclaveSig: respV010orV1.InternaReplyEnclaveSig,
Data: []byte(respV010orV1.V010.Err.GenericErr.Msg),
}, nil, nil, gasUsed, fmt.Errorf("%+v", respV010orV1.V010.Err)
}
if respV010orV1.V010.Ok != nil {
if isOutputAddressedToReply {
respV010orV1.V010.Ok.Data, err = AppendReplyInternalDataToData(respV010orV1.V010.Ok.Data, respV010orV1.InternaReplyEnclaveSig, respV010orV1.InternalMsgId)
if err != nil {
return nil, nil, nil, gasUsed, fmt.Errorf("cannot serialize v0.10 DataWithInternalReplyInfo into binary : %w", err)
}
}
return respV010orV1.V010.Ok, key, adminProof, gasUsed, nil
}
}
// init v1 response
if respV010orV1.V1 != nil {
if respV010orV1.V1.Err != nil {
return v1types.DataWithInternalReplyInfo{
InternalMsgId: respV010orV1.InternalMsgId,
InternaReplyEnclaveSig: respV010orV1.InternaReplyEnclaveSig,
Data: []byte(respV010orV1.V1.Err.GenericErr.Msg),
}, nil, nil, gasUsed, fmt.Errorf("%+v", respV010orV1.V1.Err)
}
if respV010orV1.V1.Ok != nil {
if isOutputAddressedToReply {
respV010orV1.V1.Ok.Data, err = AppendReplyInternalDataToData(respV010orV1.V1.Ok.Data, respV010orV1.InternaReplyEnclaveSig, respV010orV1.InternalMsgId)
if err != nil {
return nil, nil, nil, gasUsed, fmt.Errorf("cannot serialize v1 DataWithInternalReplyInfo into binary: %w", err)
}
}
return respV010orV1.V1.Ok, key, adminProof, gasUsed, nil
}
}
return nil, nil, nil, gasUsed, fmt.Errorf("instantiate: cannot detect response type (v0.10 or v1)")
}
func AppendReplyInternalDataToData(data []byte, internaReplyEnclaveSig []byte, internalMsgId []byte) ([]byte, error) {
dataWithInternalReply := v1types.DataWithInternalReplyInfo{
InternaReplyEnclaveSig: internaReplyEnclaveSig,
InternalMsgId: internalMsgId,
Data: data,
}
return json.Marshal(dataWithInternalReply)
}
// Execute calls a given contract. Since the only difference between contracts with the same CodeID is the
// data in their local storage, and their address in the outside world, we need no ContractID here.
// (That is a detail for the external, sdk-facing, side).
//
// The caller is responsible for passing the correct `store` (which must have been initialized exactly once),
// and setting the env with relevant info on this instance (address, balance, etc)
func (w *Wasmer) Execute(
code CodeHash,
env types.Env,
executeMsg []byte,
store KVStore,
goapi GoAPI,
querier Querier,
gasMeter GasMeter,
gasLimit uint64,
sigInfo types.SigInfo,
handleType types.HandleType,
) (interface{}, uint64, error) {
paramBin, err := json.Marshal(env)
if err != nil {
return nil, 0, err
}
sigInfoBin, err := json.Marshal(sigInfo)
if err != nil {
return nil, 0, err
}
data, gasUsed, err := api.Handle(w.cache, code, paramBin, executeMsg, &gasMeter, store, &goapi, &querier, gasLimit, sigInfoBin, handleType)
if err != nil {
return nil, gasUsed, err
}
var resp ContractExecResponse
err = json.Unmarshal(data, &resp)
if err != nil {
// unidentified response π€·
return nil, gasUsed, fmt.Errorf("handle: cannot parse response from json: %w", err)
}
isOutputAddressedToReply := len(resp.InternaReplyEnclaveSig) > 0 && len(resp.InternalMsgId) > 0
// handle v0.10 response
if resp.V010 != nil {
if resp.V010.Err != nil { //nolint:gocritic
return v1types.DataWithInternalReplyInfo{
InternalMsgId: resp.InternalMsgId,
InternaReplyEnclaveSig: resp.InternaReplyEnclaveSig,
Data: []byte(resp.V010.Err.GenericErr.Msg),
}, gasUsed, fmt.Errorf("%+v", resp.V010.Err)
} else if resp.V010.Ok != nil {
if isOutputAddressedToReply {
resp.V010.Ok.Data, err = AppendReplyInternalDataToData(resp.V010.Ok.Data, resp.InternaReplyEnclaveSig, resp.InternalMsgId)
if err != nil {
return nil, gasUsed, fmt.Errorf("cannot serialize v0.10 DataWithInternalReplyInfo into binary : %w", err)
}
}
return resp.V010.Ok, gasUsed, nil
} else {
return nil, gasUsed, fmt.Errorf("cannot parse v0.10 handle response: %+v", resp)
}
}
// handle v1 response
if resp.V1 != nil {
if resp.V1.Err != nil { //nolint:gocritic
return v1types.DataWithInternalReplyInfo{
InternalMsgId: resp.InternalMsgId,
InternaReplyEnclaveSig: resp.InternaReplyEnclaveSig,
Data: []byte(resp.V1.Err.GenericErr.Msg),
}, gasUsed, fmt.Errorf("%+v", resp.V1.Err)
} else if resp.V1.Ok != nil {
if isOutputAddressedToReply {
resp.V1.Ok.Data, err = AppendReplyInternalDataToData(resp.V1.Ok.Data, resp.InternaReplyEnclaveSig, resp.InternalMsgId)
if err != nil {
return nil, gasUsed, fmt.Errorf("cannot serialize v1 DataWithInternalReplyInfo into binary: %w", err)
}
}
return resp.V1.Ok, gasUsed, nil
} else {
return nil, gasUsed, fmt.Errorf("cannot parse v1 handle response: %+v", resp)
}
}
if resp.IBCBasic != nil {
if resp.IBCBasic.Err != nil { //nolint:gocritic
return nil, gasUsed, fmt.Errorf("%+v", resp.IBCBasic.Err)
} else if resp.IBCBasic.Ok != nil {
return resp.IBCBasic.Ok, gasUsed, nil
} else {
return nil, gasUsed, fmt.Errorf("cannot parse IBCBasic response: %+v", resp)
}
}
if resp.IBCPacketReceive != nil {
if resp.IBCPacketReceive.Err != nil { //nolint:gocritic
return nil, gasUsed, fmt.Errorf("%+v", resp.IBCPacketReceive.Err)
} else if resp.IBCPacketReceive.Ok != nil {
return resp.IBCPacketReceive.Ok, gasUsed, nil
} else {
return nil, gasUsed, fmt.Errorf("cannot parse IBCPacketReceive response: %+v", resp)
}
}
if resp.IBCChannelOpen != nil {
if resp.IBCChannelOpen.Err != nil { //nolint:gocritic
return nil, gasUsed, fmt.Errorf("%+v", resp.IBCChannelOpen.Err)
} else if resp.IBCChannelOpen.Ok != nil {
// ibc_channel_open actually returns no data
return resp.IBCChannelOpen.Ok, gasUsed, nil
} else {
return nil, gasUsed, fmt.Errorf("cannot parse IBCChannelOpen response: %+v", resp)
}
}
return nil, gasUsed, fmt.Errorf("handle: cannot detect response type (v0.10 or v1)")
}
// Query allows a client to execute a contract-specific query. If the result is not empty, it should be
// valid json-encoded data to return to the client.
// The meaning of path and data can be determined by the code. Path is the suffix of the abci.QueryRequest.Path
func (w *Wasmer) Query(
code CodeHash,
env types.Env,
queryMsg []byte,
store KVStore,
goapi GoAPI,
querier Querier,
gasMeter GasMeter,
gasLimit uint64,
) ([]byte, uint64, error) {
paramBin, err := json.Marshal(env)
if err != nil {
return nil, 0, err
}
data, gasUsed, err := api.Query(w.cache, code, paramBin, queryMsg, &gasMeter, store, &goapi, &querier, gasLimit)
if err != nil {
return nil, gasUsed, err
}
var resp types.ContractQueryResponse
err = json.Unmarshal(data, &resp)
if err != nil {
return nil, gasUsed, err
}
if resp.Query == nil {
return nil, gasUsed, fmt.Errorf("query: cannot detect response type")
}
if resp.Query.Err != nil {
return nil, gasUsed, fmt.Errorf("%v", resp.Query.Err)
}
if resp.Query.Ok != nil {
return resp.Query.Ok, gasUsed, nil
}
return nil, gasUsed, fmt.Errorf("query: cannot detect response type")
}
// AnalyzeCode returns a report of static analysis of the wasm contract (uncompiled).
// This contract must have been stored in the cache previously (via Create).
// Only info currently returned is if it exposes all ibc entry points, but this may grow later
func (w *Wasmer) AnalyzeCode(
codeHash []byte,
) (*v1types.AnalysisReport, error) {
return api.AnalyzeCode(w.cache, codeHash)
}
// Migrate will migrate an existing contract to a new code binary.
// This takes storage of the data from the original contract and the CodeID of the new contract that should
// replace it. This allows it to run a migration step if needed, or return an error if unable to migrate
// the given data.
//
// MigrateMsg has some data on how to perform the migration.
func (w *Wasmer) Migrate(
newCodeId CodeHash,
env types.Env,
migrateMsg []byte,
store KVStore,
goapi GoAPI,
querier Querier,
gasMeter GasMeter,
gasLimit uint64,
sigInfo types.SigInfo,
admin []byte,
adminProof []byte,
// data, contractKey, adminProof, gasUsed, error
) (interface{}, []byte, []byte, uint64, error) {
paramBin, err := json.Marshal(env)
if err != nil {
return nil, nil, nil, 0, err
}
sigInfoBin, err := json.Marshal(sigInfo)
if err != nil {
return nil, nil, nil, 0, err
}
data, gasUsed, err := api.Migrate(w.cache, newCodeId, paramBin, migrateMsg, &gasMeter, store, &goapi, &querier, gasLimit, sigInfoBin, admin, adminProof)
if err != nil {
return nil, nil, nil, gasUsed, err
}
newContractKey := data[0:64]
proof := data[64:96]
data = data[96:]
var respV010orV1 ContractExecResponse
err = json.Unmarshal(data, &respV010orV1)
if err != nil {
// unidentified response π€·
return nil, nil, nil, gasUsed, fmt.Errorf("migrate: cannot parse response from json: %w", err)
}
isOutputAddressedToReply := len(respV010orV1.InternaReplyEnclaveSig) > 0 && len(respV010orV1.InternalMsgId) > 0
// init v0.10 response
if respV010orV1.V010 != nil {
if respV010orV1.V010.Err != nil {
return v1types.DataWithInternalReplyInfo{
InternalMsgId: respV010orV1.InternalMsgId,
InternaReplyEnclaveSig: respV010orV1.InternaReplyEnclaveSig,
Data: []byte(respV010orV1.V010.Err.GenericErr.Msg),
}, nil, nil, gasUsed, fmt.Errorf("%+v", respV010orV1.V010.Err)
}
if respV010orV1.V010.Ok != nil {
if isOutputAddressedToReply {
respV010orV1.V010.Ok.Data, err = AppendReplyInternalDataToData(respV010orV1.V010.Ok.Data, respV010orV1.InternaReplyEnclaveSig, respV010orV1.InternalMsgId)
if err != nil {
return nil, nil, nil, gasUsed, fmt.Errorf("cannot serialize v0.10 DataWithInternalReplyInfo into binary : %w", err)
}
}
return respV010orV1.V010.Ok, newContractKey, proof, gasUsed, nil
}
}
// init v1 response
if respV010orV1.V1 != nil {
if respV010orV1.V1.Err != nil {
return v1types.DataWithInternalReplyInfo{
InternalMsgId: respV010orV1.InternalMsgId,
InternaReplyEnclaveSig: respV010orV1.InternaReplyEnclaveSig,
Data: []byte(respV010orV1.V1.Err.GenericErr.Msg),
}, nil, nil, gasUsed, fmt.Errorf("%+v", respV010orV1.V1.Err)
}
if respV010orV1.V1.Ok != nil {
if isOutputAddressedToReply {
respV010orV1.V1.Ok.Data, err = AppendReplyInternalDataToData(respV010orV1.V1.Ok.Data, respV010orV1.InternaReplyEnclaveSig, respV010orV1.InternalMsgId)
if err != nil {
return nil, nil, nil, gasUsed, fmt.Errorf("cannot serialize v1 DataWithInternalReplyInfo into binary: %w", err)
}
}
return respV010orV1.V1.Ok, newContractKey, proof, gasUsed, nil
}
}
return nil, nil, nil, gasUsed, fmt.Errorf("migrate: cannot detect response type (v0.10 or v1)")
}
// UpdateAdmin will update or clear a contract admin.
func (w *Wasmer) UpdateAdmin(
newCodeId CodeHash,
env types.Env,
store KVStore,
goapi GoAPI,
querier Querier,
gasMeter GasMeter,
gasLimit uint64,
sigInfo types.SigInfo,
currentAdmin []byte,
currentAdminProof []byte,
newAdmin []byte,
) ([]byte, error) {
paramBin, err := json.Marshal(env)
if err != nil {
return nil, err
}
sigInfoBin, err := json.Marshal(sigInfo)
if err != nil {
return nil, err
}
newAdminProof, err := api.UpdateAdmin(w.cache, newCodeId, paramBin, &gasMeter, store, &goapi, &querier, gasLimit, sigInfoBin, currentAdmin, currentAdminProof, newAdmin)
if err != nil {
return nil, err
}
return newAdminProof, nil
}