-
Notifications
You must be signed in to change notification settings - Fork 4
/
runtime.go
402 lines (347 loc) · 10.4 KB
/
runtime.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
/*
* Copyright (C) 2018 The ZeepinChain Authors
* This file is part of The ZeepinChain library.
*
* The ZeepinChain is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ZeepinChain is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with The ZeepinChain. If not, see <http://www.gnu.org/licenses/>.
*/
package embed
import (
"bytes"
"io"
"math/big"
"reflect"
"sort"
"github.com/zeepin/ZeepinChain/common"
"github.com/zeepin/ZeepinChain/common/serialization"
"github.com/zeepin/ZeepinChain/core/types"
vm "github.com/zeepin/ZeepinChain/embed/simulator"
vmtypes "github.com/zeepin/ZeepinChain/embed/simulator/types"
"github.com/zeepin/ZeepinChain/errors"
scommon "github.com/zeepin/ZeepinChain/smartcontract/common"
"github.com/zeepin/ZeepinChain/smartcontract/event"
"github.com/zeepin/ZeepinChain-Crypto/keypair"
)
// HeaderGetNextConsensus put current block time to vm stack
func RuntimeGetTime(service *EmbeddedService, engine *vm.ExecutionEngine) error {
vm.PushData(engine, int(service.Time))
return nil
}
// RuntimeCheckWitness provide check permissions service
// If param address isn't exist in authorization list, check fail
func RuntimeCheckWitness(service *EmbeddedService, engine *vm.ExecutionEngine) error {
data, err := vm.PopByteArray(engine)
if err != nil {
return err
}
var result bool
if len(data) == 20 {
address, err := common.AddressParseFromBytes(data)
if err != nil {
return err
}
result = service.ContextRef.CheckWitness(address)
} else {
pk, err := keypair.DeserializePublicKey(data)
if err != nil {
return errors.NewDetailErr(err, errors.ErrNoCode, "[RuntimeCheckWitness] data invalid.")
}
result = service.ContextRef.CheckWitness(types.AddressFromPubKey(pk))
}
vm.PushData(engine, result)
return nil
}
func RuntimeSerialize(service *EmbeddedService, engine *vm.ExecutionEngine) error {
item := vm.PopStackItem(engine)
buf, err := SerializeStackItem(item)
if err != nil {
return err
}
vm.PushData(engine, buf)
return nil
}
func RuntimeDeserialize(service *EmbeddedService, engine *vm.ExecutionEngine) error {
data, err := vm.PopByteArray(engine)
if err != nil {
return err
}
bf := bytes.NewBuffer(data)
item, err := DeserializeStackItem(bf)
if err != nil {
return err
}
if item == nil {
return nil
}
vm.PushData(engine, item)
return nil
}
// RuntimeNotify put smart contract execute event notify to notifications
func RuntimeNotify(service *EmbeddedService, engine *vm.ExecutionEngine) error {
item := vm.PopStackItem(engine)
context := service.ContextRef.CurrentContext()
service.Notifications = append(service.Notifications, &event.NotifyEventInfo{ContractAddress: context.ContractAddress, States: scommon.ConvertEmbededTypeHexString(item)})
return nil
}
// RuntimeLog push smart contract execute event log to client
func RuntimeLog(service *EmbeddedService, engine *vm.ExecutionEngine) error {
item, err := vm.PopByteArray(engine)
if err != nil {
return err
}
context := service.ContextRef.CurrentContext()
txHash := service.Tx.Hash()
event.PushSmartCodeEvent(txHash, 0, event.EVENT_LOG, &event.LogEventArgs{TxHash: txHash, ContractAddress: context.ContractAddress, Message: string(item)})
return nil
}
func RuntimeGetTrigger(service *EmbeddedService, engine *vm.ExecutionEngine) error {
vm.PushData(engine, 0)
return nil
}
func SerializeStackItem(item vmtypes.StackItems) ([]byte, error) {
if CircularRefAndDepthDetection(item) {
return nil, errors.NewErr("runtime serialize: can not serialize circular reference data")
}
bf := new(bytes.Buffer)
err := serializeStackItem(item, common.NewLimitedWriter(bf, uint64(vm.MAX_BYTEARRAY_SIZE)))
if err != nil {
return nil, err
}
return bf.Bytes(), nil
}
func serializeStackItem(item vmtypes.StackItems, w io.Writer) error {
switch item.(type) {
case *vmtypes.ByteArray:
if err := serialization.WriteByte(w, vmtypes.ByteArrayType); err != nil {
return errors.NewErr("Serialize ByteArray stackItems error: " + err.Error())
}
ba, _ := item.GetByteArray()
if err := serialization.WriteVarBytes(w, ba); err != nil {
return errors.NewErr("Serialize ByteArray stackItems error: " + err.Error())
}
case *vmtypes.Boolean:
if err := serialization.WriteByte(w, vmtypes.BooleanType); err != nil {
return errors.NewErr("Serialize Boolean StackItems error: " + err.Error())
}
b, _ := item.GetBoolean()
if err := serialization.WriteBool(w, b); err != nil {
return errors.NewErr("Serialize Boolean stackItems error: " + err.Error())
}
case *vmtypes.Integer:
if err := serialization.WriteByte(w, vmtypes.IntegerType); err != nil {
return errors.NewErr("Serialize Integer stackItems error: " + err.Error())
}
i, _ := item.GetByteArray()
if err := serialization.WriteVarBytes(w, i); err != nil {
return errors.NewErr("Serialize Integer stackItems error: " + err.Error())
}
case *vmtypes.Array:
if err := serialization.WriteByte(w, vmtypes.ArrayType); err != nil {
return errors.NewErr("Serialize Array stackItems error: " + err.Error())
}
a, _ := item.GetArray()
if err := serialization.WriteVarUint(w, uint64(len(a))); err != nil {
return errors.NewErr("Serialize Array stackItems error: " + err.Error())
}
for _, v := range a {
err := serializeStackItem(v, w)
if err != nil {
return err
}
}
case *vmtypes.Struct:
if err := serialization.WriteByte(w, vmtypes.StructType); err != nil {
return errors.NewErr("Serialize Struct stackItems error: " + err.Error())
}
s, _ := item.GetStruct()
if err := serialization.WriteVarUint(w, uint64(len(s))); err != nil {
return errors.NewErr("Serialize Struct stackItems error: " + err.Error())
}
for _, v := range s {
err := serializeStackItem(v, w)
if err != nil {
return err
}
}
case *vmtypes.Map:
var unsortKey []string
mp, _ := item.GetMap()
keyMap := make(map[string]vmtypes.StackItems, 0)
if err := serialization.WriteByte(w, vmtypes.MapType); err != nil {
return errors.NewErr("Serialize Map stackItems error: " + err.Error())
}
if err := serialization.WriteVarUint(w, uint64(len(mp))); err != nil {
return errors.NewErr("Serialize Map stackItems error: " + err.Error())
}
for k := range mp {
switch k.(type) {
case *vmtypes.ByteArray, *vmtypes.Integer:
ba, _ := k.GetByteArray()
key := string(ba)
if key == "" {
return errors.NewErr("Serialize Map error: invalid key type")
}
unsortKey = append(unsortKey, key)
keyMap[key] = k
default:
return errors.NewErr("Unsupport map key type.")
}
}
sort.Strings(unsortKey)
for _, v := range unsortKey {
key := keyMap[v]
err := serializeStackItem(key, w)
if err != nil {
return err
}
err = serializeStackItem(mp[key], w)
if err != nil {
return err
}
}
default:
return errors.NewErr("unknown type")
}
return nil
}
func DeserializeStackItem(r io.Reader) (items vmtypes.StackItems, err error) {
t, err := serialization.ReadByte(r)
if err != nil {
return nil, errors.NewErr("Deserialize error: " + err.Error())
}
switch t {
case vmtypes.ByteArrayType:
b, err := serialization.ReadVarBytes(r)
if err != nil {
return nil, errors.NewErr("Deserialize stackItems ByteArray error: " + err.Error())
}
return vmtypes.NewByteArray(b), nil
case vmtypes.BooleanType:
b, err := serialization.ReadBool(r)
if err != nil {
return nil, errors.NewErr("Deserialize stackItems Boolean error: " + err.Error())
}
return vmtypes.NewBoolean(b), nil
case vmtypes.IntegerType:
b, err := serialization.ReadVarBytes(r)
if err != nil {
return nil, errors.NewErr("Deserialize stackItems Integer error: " + err.Error())
}
return vmtypes.NewInteger(new(big.Int).SetBytes(b)), nil
case vmtypes.ArrayType, vmtypes.StructType:
count, err := serialization.ReadVarUint(r, 0)
if err != nil {
return nil, errors.NewErr("Deserialize stackItems error: " + err.Error())
}
var arr []vmtypes.StackItems
for count > 0 {
item, err := DeserializeStackItem(r)
if err != nil {
return nil, err
}
arr = append(arr, item)
count--
}
if t == vmtypes.StructType {
return vmtypes.NewStruct(arr), nil
}
return vmtypes.NewArray(arr), nil
case vmtypes.MapType:
count, err := serialization.ReadVarUint(r, 0)
if err != nil {
return nil, errors.NewErr("Deserialize stackItems map error: " + err.Error())
}
mp := vmtypes.NewMap()
for count > 0 {
key, err := DeserializeStackItem(r)
if err != nil {
return nil, err
}
value, err := DeserializeStackItem(r)
if err != nil {
return nil, err
}
m, _ := mp.GetMap()
m[key] = value
count--
}
return mp, nil
default:
return nil, errors.NewErr("unknown type")
}
return nil, nil
}
func CircularRefAndDepthDetection(value vmtypes.StackItems) bool {
return circularRefAndDepthDetection(value, make(map[uintptr]bool), 0)
}
func circularRefAndDepthDetection(value vmtypes.StackItems, visited map[uintptr]bool, depth int) bool {
if depth > vmtypes.MAX_STRCUT_DEPTH {
return true
}
switch value.(type) {
case *vmtypes.Array:
a, _ := value.GetArray()
if len(a) == 0 {
return false
}
p := reflect.ValueOf(a).Pointer()
if visited[p] {
return true
}
visited[p] = true
for _, v := range a {
if circularRefAndDepthDetection(v, visited, depth+1) {
return true
}
}
delete(visited, p)
return false
case *vmtypes.Struct:
s, _ := value.GetStruct()
if len(s) == 0 {
return false
}
p := reflect.ValueOf(s).Pointer()
if visited[p] {
return true
}
visited[p] = true
for _, v := range s {
if circularRefAndDepthDetection(v, visited, depth+1) {
return true
}
}
delete(visited, p)
return false
case *vmtypes.Map:
mp, _ := value.GetMap()
p := reflect.ValueOf(mp).Pointer()
if visited[p] {
return true
}
visited[p] = true
for k, v := range mp {
if circularRefAndDepthDetection(k, visited, depth+1) {
return true
}
if circularRefAndDepthDetection(v, visited, depth+1) {
return true
}
}
delete(visited, p)
return false
default:
return false
}
return false
}