-
Notifications
You must be signed in to change notification settings - Fork 167
/
vm.go
259 lines (223 loc) · 7.48 KB
/
vm.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
package vm
//#include <stdint.h>
//#include <stdlib.h>
//#include <stddef.h>
// extern void cairoVMCall(char* contract_address, char* class_hash, char* entry_point_selector, char** calldata,
// size_t len_calldata, uintptr_t readerHandle, unsigned long long block_number,
// unsigned long long block_timestamp, char* chain_id);
//
// extern void cairoVMExecute(char* txns_json, char* classes_json, uintptr_t readerHandle, unsigned long long block_number,
// unsigned long long block_timestamp, char* chain_id, char* sequencer_address, char* paid_fees_on_l1_json,
// unsigned char skip_charge_fee, unsigned char skip_validate, char* gas_price, unsigned char legacy_json);
//
// #cgo vm_debug LDFLAGS: -L./rust/target/debug -ljuno_starknet_rs -lm -ldl
// #cgo !vm_debug LDFLAGS: -L./rust/target/release -ljuno_starknet_rs -lm -ldl
import "C"
import (
"encoding/json"
"errors"
"runtime/cgo"
"unsafe"
"github.com/NethermindEth/juno/core"
"github.com/NethermindEth/juno/core/felt"
"github.com/NethermindEth/juno/utils"
)
//go:generate mockgen -destination=../mocks/mock_vm.go -package=mocks github.com/NethermindEth/juno/vm VM
type VM interface {
Call(contractAddr, classHash, selector *felt.Felt, calldata []felt.Felt, blockNumber,
blockTimestamp uint64, state core.StateReader, network utils.Network,
) ([]*felt.Felt, error)
Execute(txns []core.Transaction, declaredClasses []core.Class, blockNumber, blockTimestamp uint64,
sequencerAddress *felt.Felt, state core.StateReader, network utils.Network, paidFeesOnL1 []*felt.Felt,
skipChargeFee, skipValidate bool, gasPrice *felt.Felt, legacyTraceJSON bool,
) ([]*felt.Felt, []json.RawMessage, error)
}
type vm struct {
log utils.SimpleLogger
}
func New(log utils.SimpleLogger) VM {
return &vm{
log: log,
}
}
// callContext manages the context that a Call instance executes on
type callContext struct {
// state that the call is running on
state core.StateReader
log utils.SimpleLogger
// err field to be possibly populated in case of an error in execution
err string
// response from the executed Cairo function
response []*felt.Felt
// fee amount taken per transaction during VM execution
actualFees []*felt.Felt
traces []json.RawMessage
}
func unwrapContext(readerHandle C.uintptr_t) *callContext {
context, ok := cgo.Handle(readerHandle).Value().(*callContext)
if !ok {
panic("cannot cast reader")
}
return context
}
//export JunoReportError
func JunoReportError(readerHandle C.uintptr_t, str *C.char) {
context := unwrapContext(readerHandle)
context.err = C.GoString(str)
}
//export JunoAppendTrace
func JunoAppendTrace(readerHandle C.uintptr_t, jsonBytes *C.void, bytesLen C.size_t) {
context := unwrapContext(readerHandle)
byteSlice := C.GoBytes(unsafe.Pointer(jsonBytes), C.int(bytesLen))
context.traces = append(context.traces, json.RawMessage(byteSlice))
}
//export JunoAppendResponse
func JunoAppendResponse(readerHandle C.uintptr_t, ptr unsafe.Pointer) {
context := unwrapContext(readerHandle)
context.response = append(context.response, makeFeltFromPtr(ptr))
}
//export JunoAppendActualFee
func JunoAppendActualFee(readerHandle C.uintptr_t, ptr unsafe.Pointer) {
context := unwrapContext(readerHandle)
context.actualFees = append(context.actualFees, makeFeltFromPtr(ptr))
}
func makeFeltFromPtr(ptr unsafe.Pointer) *felt.Felt {
return new(felt.Felt).SetBytes(C.GoBytes(ptr, felt.Bytes))
}
func makePtrFromFelt(val *felt.Felt) unsafe.Pointer {
feltBytes := val.Bytes()
//nolint:gocritic
return C.CBytes(feltBytes[:])
}
func (v *vm) Call(contractAddr, classHash, selector *felt.Felt, calldata []felt.Felt, blockNumber,
blockTimestamp uint64, state core.StateReader, network utils.Network,
) ([]*felt.Felt, error) {
context := &callContext{
state: state,
response: []*felt.Felt{},
log: v.log,
}
handle := cgo.NewHandle(context)
defer handle.Delete()
addrBytes := contractAddr.Bytes()
selectorBytes := selector.Bytes()
calldataPtrs := []*C.char{}
for _, data := range calldata {
bytes := data.Bytes()
//nolint:gocritic
calldataPtrs = append(calldataPtrs, (*C.char)(C.CBytes(bytes[:])))
}
calldataArrPtr := unsafe.Pointer(nil)
if len(calldataPtrs) > 0 {
calldataArrPtr = unsafe.Pointer(&calldataPtrs[0])
}
classHashPtr := (*byte)(nil)
if classHash != nil {
classHashBytes := classHash.Bytes()
classHashPtr = &classHashBytes[0]
}
chainID := C.CString(network.ChainIDString())
C.cairoVMCall((*C.char)(unsafe.Pointer(&addrBytes[0])),
(*C.char)(unsafe.Pointer(classHashPtr)),
(*C.char)(unsafe.Pointer(&selectorBytes[0])),
(**C.char)(calldataArrPtr),
C.size_t(len(calldataPtrs)),
C.uintptr_t(handle),
C.ulonglong(blockNumber),
C.ulonglong(blockTimestamp),
chainID)
for _, ptr := range calldataPtrs {
C.free(unsafe.Pointer(ptr))
}
C.free(unsafe.Pointer(chainID))
if len(context.err) > 0 {
return nil, errors.New(context.err)
}
return context.response, nil
}
// Execute executes a given transaction set and returns the gas spent per transaction
func (v *vm) Execute(txns []core.Transaction, declaredClasses []core.Class, blockNumber, blockTimestamp uint64,
sequencerAddress *felt.Felt, state core.StateReader, network utils.Network, paidFeesOnL1 []*felt.Felt,
skipChargeFee, skipValidate bool, gasPrice *felt.Felt, legacyTraceJSON bool,
) ([]*felt.Felt, []json.RawMessage, error) {
context := &callContext{
state: state,
log: v.log,
}
handle := cgo.NewHandle(context)
defer handle.Delete()
txnsJSON, classesJSON, err := marshalTxnsAndDeclaredClasses(txns, declaredClasses)
if err != nil {
return nil, nil, err
}
paidFeesOnL1Bytes, err := json.Marshal(paidFeesOnL1)
if err != nil {
return nil, nil, err
}
paidFeesOnL1CStr := cstring(paidFeesOnL1Bytes)
txnsJSONCstr := cstring(txnsJSON)
classesJSONCStr := cstring(classesJSON)
sequencerAddressBytes := sequencerAddress.Bytes()
gasPriceBytes := gasPrice.Bytes()
var skipChargeFeeByte byte
if skipChargeFee {
skipChargeFeeByte = 1
}
var skipValidateByte byte
if skipValidate {
skipValidateByte = 1
}
var legacyTraceJSONByte byte
if legacyTraceJSON {
legacyTraceJSONByte = 1
}
chainID := C.CString(network.ChainIDString())
C.cairoVMExecute(txnsJSONCstr,
classesJSONCStr,
C.uintptr_t(handle),
C.ulonglong(blockNumber),
C.ulonglong(blockTimestamp),
chainID,
(*C.char)(unsafe.Pointer(&sequencerAddressBytes[0])),
paidFeesOnL1CStr,
C.uchar(skipChargeFeeByte),
C.uchar(skipValidateByte),
(*C.char)(unsafe.Pointer(&gasPriceBytes[0])),
C.uchar(legacyTraceJSONByte),
)
C.free(unsafe.Pointer(classesJSONCStr))
C.free(unsafe.Pointer(paidFeesOnL1CStr))
C.free(unsafe.Pointer(txnsJSONCstr))
C.free(unsafe.Pointer(chainID))
if len(context.err) > 0 {
return nil, nil, errors.New(context.err)
}
return context.actualFees, context.traces, nil
}
func marshalTxnsAndDeclaredClasses(txns []core.Transaction, declaredClasses []core.Class) (json.RawMessage, json.RawMessage, error) {
txnJSONs := []json.RawMessage{}
for _, txn := range txns {
txnJSON, err := marshalTxn(txn)
if err != nil {
return nil, nil, err
}
txnJSONs = append(txnJSONs, txnJSON)
}
classJSONs := []json.RawMessage{}
for _, declaredClass := range declaredClasses {
declaredClassJSON, cErr := marshalDeclaredClass(declaredClass)
if cErr != nil {
return nil, nil, cErr
}
classJSONs = append(classJSONs, declaredClassJSON)
}
txnsJSON, err := json.Marshal(txnJSONs)
if err != nil {
return nil, nil, err
}
classesJSON, err := json.Marshal(classJSONs)
if err != nil {
return nil, nil, err
}
return txnsJSON, classesJSON, nil
}