-
Notifications
You must be signed in to change notification settings - Fork 1
/
adaptor.go
97 lines (81 loc) · 2.19 KB
/
adaptor.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
package bridge
import (
"fmt"
"github.com/BeDreamCoder/uwavm/contract/go/pb"
"github.com/BeDreamCoder/uwavm/vm/gas"
)
// ContractError indicates the error of the contract running result
type ContractError struct {
Status int
Message string
}
// Error implements error interface
func (c *ContractError) Error() string {
return fmt.Sprintf("contract error status:%d message:%s", c.Status, c.Message)
}
// contractHandle 为vm.Context的实现,
// 它组合了合约内核态数据(cts)以及用户态的虚拟机数据(instance)
type contractHandle struct {
cts *ContractState
instance Instance
release func()
}
func (c *contractHandle) Invoke(method string, args map[string][]byte) (*pb.Response, error) {
c.cts.Method = method
c.cts.Args = args
err := c.instance.Exec("")
if err != nil {
return nil, err
}
if c.cts.Output == nil {
return nil, &ContractError{
Status: 500,
Message: "internal error",
}
}
return c.cts.Output, nil
}
func (c *contractHandle) ResourceUsed() gas.Limits {
return c.instance.ResourceUsed()
}
func (c *contractHandle) ReleaseCache() error {
// release the context of instance
c.instance.Release()
c.release()
return nil
}
// vmImpl 为vm.VirtualMachine的实现
// 它是vmContextImpl的工厂类,根据不同的虚拟机类型(Executor)生成对应的vmContextImpl
type vmImpl struct {
name string
state *StateManager
exec Executor
}
func (v *vmImpl) GetName() string {
return v.name
}
func (v *vmImpl) NewVM(state *ContractState) (Contract, error) {
ctx := v.state.CreateContractState()
ctx.ContractName = state.ContractName
ctx.Language = state.Language
ctx.Caller = state.Caller
release := func() {
v.state.DestroyContractState(ctx)
}
instance, err := v.exec.NewCreatorInstance(ctx)
if err != nil {
v.state.DestroyContractState(ctx)
return nil, err
}
return &contractHandle{
cts: ctx,
instance: instance,
release: release,
}, nil
}
func (v *vmImpl) DeployContract(args map[string][]byte) (*pb.Response, gas.Limits, error) {
return v.exec.DeployContract(args)
}
func (v *vmImpl) InvokeContract(method string, args map[string][]byte) (*pb.Response, gas.Limits, error) {
return v.exec.InvokeContract(method, args)
}