-
Notifications
You must be signed in to change notification settings - Fork 17
/
run_code.go
346 lines (307 loc) · 9.99 KB
/
run_code.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
package handlers
import (
"context"
"net/http"
"time"
"github.com/baking-bad/bcdhub/internal/bcd"
"github.com/baking-bad/bcdhub/internal/bcd/ast"
"github.com/baking-bad/bcdhub/internal/bcd/consts"
"github.com/baking-bad/bcdhub/internal/bcd/tezerrors"
"github.com/baking-bad/bcdhub/internal/config"
"github.com/baking-bad/bcdhub/internal/models/bigmapdiff"
"github.com/baking-bad/bcdhub/internal/models/protocol"
"github.com/baking-bad/bcdhub/internal/models/types"
"github.com/baking-bad/bcdhub/internal/noderpc"
"github.com/baking-bad/bcdhub/internal/parsers"
"github.com/baking-bad/bcdhub/internal/parsers/operations"
"github.com/baking-bad/bcdhub/internal/parsers/protocols"
"github.com/gin-gonic/gin"
"github.com/pkg/errors"
)
// RunOperation -
func RunOperation() gin.HandlerFunc {
return func(c *gin.Context) {
ctx := c.MustGet("context").(*config.Context)
var req getContractRequest
if err := c.ShouldBindUri(&req); handleError(c, ctx.Storage, err, http.StatusNotFound) {
return
}
var reqRunOp runOperationRequest
if err := c.ShouldBindJSON(&reqRunOp); handleError(c, ctx.Storage, err, http.StatusBadRequest) {
return
}
state, err := ctx.Blocks.Last(c.Request.Context())
if handleError(c, ctx.Storage, err, 0) {
return
}
predecessor, err := ctx.Blocks.Get(c.Request.Context(), state.Level-1)
if handleError(c, ctx.Storage, err, 0) {
return
}
parameters, err := buildParametersForExecution(c.Request.Context(), ctx, req.Address, state.Protocol.SymLink, reqRunOp.Name, reqRunOp.Data)
if handleError(c, ctx.Storage, err, 0) {
return
}
counter, err := ctx.RPC.GetCounter(c, reqRunOp.Source)
if handleError(c, ctx.Storage, err, 0) {
return
}
params, err := json.Marshal(parameters)
if handleError(c, ctx.Storage, err, 0) {
return
}
response, err := ctx.RPC.RunOperationLight(
c,
state.Protocol.ChainID,
state.Hash,
reqRunOp.Source,
req.Address,
0, // fee
state.Protocol.Constants.HardGasLimitPerOperation,
state.Protocol.Constants.HardStorageLimitPerOperation,
counter+1,
reqRunOp.Amount,
params,
)
if handleError(c, ctx.Storage, err, 0) {
return
}
header := noderpc.Header{
Level: state.Level,
Protocol: state.Protocol.Hash,
Timestamp: state.Timestamp,
ChainID: state.Protocol.ChainID,
Hash: state.Hash,
Predecessor: predecessor.Hash,
}
parserParams, err := operations.NewParseParams(
c.Request.Context(),
ctx,
operations.WithProtocol(&state.Protocol),
operations.WithHead(header),
)
if handleError(c, ctx.Storage, err, 0) {
return
}
parser := operations.NewGroup(parserParams)
store := parsers.NewTestStore()
if err := parser.Parse(c.Request.Context(), response, store); handleError(c, ctx.Storage, err, 0) {
return
}
operations := store.ListOperations()
resp := make([]Operation, len(operations))
for i := range operations {
op, err := prepareOperation(c.Request.Context(), ctx, *operations[i], true)
if handleError(c, ctx.Storage, err, 0) {
return
}
resp[i] = op
}
c.SecureJSON(http.StatusOK, resp)
}
}
// RunCode godoc
// @Summary Execute entrypoint with passed arguments
// @Description Execute entrypoint with passed arguments
// @Tags contract
// @ID run-code
// @Param network path string true "Network"
// @Param address path string true "KT address" minlength(36) maxlength(36)
// @Param body body runCodeRequest true "Request body"
// @Accept json
// @Produce json
// @Success 200 {array} Operation
// @Failure 400 {object} Error
// @Failure 404 {object} Error
// @Failure 500 {object} Error
// @Router /v1/contract/{network}/{address}/entrypoints/trace [post]
func RunCode() gin.HandlerFunc {
return func(c *gin.Context) {
ctx := c.MustGet("context").(*config.Context)
var req getContractRequest
if err := c.ShouldBindUri(&req); handleError(c, ctx.Storage, err, http.StatusNotFound) {
return
}
var reqRunCode runCodeRequest
if err := c.ShouldBindJSON(&reqRunCode); handleError(c, ctx.Storage, err, http.StatusBadRequest) {
return
}
state, err := ctx.Blocks.Last(c.Request.Context())
if handleError(c, ctx.Storage, err, 0) {
return
}
scriptBytes, err := getScriptBytes(c.Request.Context(), ctx.Cache, req.Address, state.Protocol.SymLink)
if handleError(c, ctx.Storage, err, 0) {
return
}
input, err := buildParametersForExecution(c.Request.Context(), ctx, req.Address, state.Protocol.SymLink, reqRunCode.Name, reqRunCode.Data)
if handleError(c, ctx.Storage, err, 0) {
return
}
storage, err := ctx.RPC.GetScriptStorageRaw(c, req.Address, 0)
if handleError(c, ctx.Storage, err, 0) {
return
}
main := Operation{
IndexedTime: time.Now().UTC().UnixNano(),
Protocol: state.Protocol.Hash,
Network: req.Network,
Timestamp: time.Now().UTC(),
Source: reqRunCode.Source,
Destination: req.Address,
GasLimit: reqRunCode.GasLimit,
Amount: reqRunCode.Amount,
Kind: types.OperationKindTransaction.String(),
Level: state.Level,
Status: consts.Applied,
Entrypoint: input.Entrypoint,
}
response, err := ctx.RPC.RunCode(c, scriptBytes, storage, input.Value, state.Protocol.ChainID, reqRunCode.Source, reqRunCode.Sender, input.Entrypoint, state.Protocol.Hash, reqRunCode.Amount, reqRunCode.GasLimit)
if err != nil {
var e noderpc.InvalidNodeResponse
if errors.As(err, &e) {
main.Status = consts.Failed
errs, err := tezerrors.ParseArray(e.Raw)
if err != nil {
handleError(c, ctx.Storage, e, 0)
return
}
main.Errors = errs
if err := formatErrors(main.Errors, &main); err != nil {
handleError(c, ctx.Storage, err, 0)
return
}
c.SecureJSON(http.StatusOK, []Operation{main})
return
}
handleError(c, ctx.Storage, err, 0)
return
}
script, err := ast.NewScript(scriptBytes)
if handleError(c, ctx.Storage, err, 0) {
return
}
parameterType, err := script.ParameterType()
if handleError(c, ctx.Storage, err, 0) {
return
}
if err := setParatemetersWithType(input, parameterType, &main); handleError(c, ctx.Storage, err, 0) {
return
}
main.Storage = response.Storage
if err := setSimulateStorageDiff(c, ctx, response, state.Protocol, script, &main); handleError(c, ctx.Storage, err, 0) {
return
}
operations, err := parseAppliedRunCode(c, ctx, response, script, &main, state.Protocol)
if handleError(c, ctx.Storage, err, 0) {
return
}
c.SecureJSON(http.StatusOK, operations)
}
}
func parseAppliedRunCode(c context.Context, ctx *config.Context, response noderpc.RunCodeResponse, script *ast.Script, main *Operation, proto protocol.Protocol) ([]Operation, error) {
operations := []Operation{*main}
for i := range response.Operations {
var op Operation
op.Kind = response.Operations[i].Kind
op.Amount = *response.Operations[i].Amount
op.Source = response.Operations[i].Source
op.Destination = *response.Operations[i].Destination
op.Status = consts.Applied
op.Network = main.Network
op.Timestamp = main.Timestamp
op.Protocol = main.Protocol
op.Level = main.Level
op.Internal = true
if bcd.IsContract(op.Destination) {
var s *ast.Script
if op.Destination == main.Destination || op.Destination == consts.NullContract {
s = script
} else {
var err error
s, err = getScript(c, ctx.Cache, op.Destination, proto.SymLink)
if err != nil {
return nil, err
}
}
parameterType, err := s.ParameterType()
if err != nil {
return nil, err
}
if err := setParameters(response.Operations[i].Parameters, parameterType, &op); err != nil {
return nil, err
}
if response.Operations[i].Result != nil {
op.Storage = response.Operations[i].Result.Storage
if err := setSimulateStorageDiff(c, ctx, response, proto, s, &op); err != nil {
return nil, err
}
}
}
operations = append(operations, op)
}
return operations, nil
}
func parseBigMapDiffs(c context.Context, ctx *config.Context, response noderpc.RunCodeResponse, script *ast.Script, operation *Operation, proto protocol.Protocol) ([]bigmapdiff.BigMapDiff, error) {
model := operation.ToModel()
model.AST = script
model.ProtocolID = proto.ID
specific, err := protocols.Get(ctx, proto.Hash)
if err != nil {
return nil, err
}
nodeOperation := noderpc.Operation{
Kind: operation.Kind,
Source: operation.Source,
Fee: operation.Fee,
Counter: operation.Counter,
GasLimit: operation.GasLimit,
StorageLimit: operation.StorageLimit,
Amount: &operation.Amount,
Destination: &operation.Destination,
Delegate: operation.Delegate,
Result: &noderpc.OperationResult{
Status: consts.Applied,
Storage: response.Storage,
LazyStorageDiff: response.LazyStorageDiffs,
},
}
store := parsers.NewTestStore()
switch operation.Kind {
case types.OperationKindTransaction.String():
err = specific.StorageParser.ParseTransaction(c, nodeOperation, &model, store)
case types.OperationKindOrigination.String(), types.OperationKindOriginationNew.String():
err = specific.StorageParser.ParseOrigination(c, nodeOperation, &model, store)
}
if err != nil {
return nil, err
}
bmd := make([]bigmapdiff.BigMapDiff, len(model.BigMapDiffs))
for i := range model.BigMapDiffs {
bmd[i] = *model.BigMapDiffs[i]
}
return bmd, nil
}
func setSimulateStorageDiff(c context.Context, ctx *config.Context, response noderpc.RunCodeResponse, proto protocol.Protocol, script *ast.Script, operation *Operation) error {
if len(response.Storage) == 0 || !bcd.IsContract(operation.Destination) || operation.Status != consts.Applied {
return nil
}
bmd, err := parseBigMapDiffs(c, ctx, response, script, operation, proto)
if err != nil {
return err
}
storageType, err := script.StorageType()
if err != nil {
return err
}
destination, err := ctx.Accounts.Get(c, operation.Destination)
if err != nil {
return err
}
storageDiff, err := getStorageDiff(c, ctx, destination.ID, bmd, operation.Storage, storageType, operation)
if err != nil {
return err
}
operation.StorageDiff = storageDiff
return nil
}