/
sc_tool.go
236 lines (200 loc) · 7.32 KB
/
sc_tool.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
package vm
import (
"encoding/hex"
"errors"
"fmt"
"reflect"
"regexp"
"github.com/Venachain/Venachain/common/bcwasmutil"
"github.com/Venachain/Venachain/common"
"github.com/Venachain/Venachain/common/byteutil"
"github.com/Venachain/Venachain/crypto"
"github.com/Venachain/Venachain/log"
"github.com/Venachain/Venachain/rlp"
)
const (
nameRegPattarn = `^[a-zA-Z0-9_\p{Han}]{1,128}$`
emailRegPattarn = `^[a-zA-Z0-9]+@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}`
ipRegPattarn = `^(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)){3}$` //`(2(5[0-5]{1}|[0-4]\d{1})|[0-1]?\d{1,2})(\.(2(5[0-5]{1}|[0-4]\d{1})|[0-1]?\d{1,2})){3}`//`((25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))`//`(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)`
telePhonePattarn = "^[0-9]{3,13}$" //"^[0-9-()()]{7,18}"
mobilePhonePattarn = "^[0-9]{3,13}$"
)
var (
errFuncNotFoundInExportFuncs = errors.New("the func not found in export function set")
errParamsNumInvalid = errors.New("the number of params is invalid")
)
var (
errUnsupportedRole = errors.New("Unsupported role ")
errNoPermission = errors.New("No Permission ")
errAlreadySetSuperAdmin = errors.New("Already Set SuperAdmin ")
errParamInvalid = errors.New("param is invalid")
errEncodeFailure = errors.New("encode failure ")
errContactNameNotExist = errors.New("contract name not exist")
errNameInvalid = errors.New("[CNS] name format is invalid")
errVersionInvalid = errors.New("[CNS] version format is invalid")
errAddressInvalid = errors.New("[CNS] address format is invalid")
errNotOwner = errors.New("[CNS] not owner of registered contract")
errSysContractCNSInvoked = errors.New("[CNS] system contract can not be cns invoked")
errEmptyValue = errors.New("Empty value")
errIPUnsupported = errors.New("Unsupported IP address ")
errUsernameUnsupported = errors.New("Unsupported Username ")
errNameUnsupported = errors.New("Unsupported name ")
errOrgnizationUnsupported = errors.New("Unsupported Orgnization ")
errEmailUnsupported = errors.New("Unsupported email address ")
errPhoneUnsupported = errors.New("Unsupported phone number ")
errValidatorCountInvalid = errors.New("Validator Count Invalid")
//errAuthenticationFailed = errors.New("Authentication failed !!!")
errAlreadySetEvidence = errors.New("This id Already exsit")
errEvidenceNotFound = errors.New("Evidence Not Found")
errBPGetFalseResult = errors.New("Bullet Proof get result false")
errAlreadySetPid = errors.New("This pid Already exsit")
)
var (
ZeroAddress = common.Address{}
)
var fwErrNotOwner = errors.New("FW : error, only contract owner can set firewall setting")
func execSC(input []byte, fns SCExportFns) (string, []byte, error) {
txType, fnName, fn, params, err := retrieveFnAndParams(input, fns)
if nil != err {
log.Error("failed to retrieve func name and params.", "error", err, "function", fnName)
return fnName, nil, err
}
//execute system contract method
//all the export method of system contracts must return two results,
//first result type is: primitive type, second result type: error
result := reflect.ValueOf(fn).Call(params)
if err, ok := result[1].Interface().(error); ok {
log.Error("execute system contract failed.", "funcName", fnName, "error", err)
return fnName, MakeReturnBytes([]byte(newInternalErrorResult(err).String())), err
}
//vm run successfully, so return nil
return fnName, toContractReturnValueType(txType, result[0]), nil
}
func toContractReturnValueType(txType int, val reflect.Value) []byte {
defer func() {
if e := recover(); nil != e {
err := fmt.Errorf("toContractReturnValueType:%+v", e)
log.Error("toContractReturnValueType", "error", err, "value type", val.Kind())
}
}()
switch val.Kind() {
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return toContractReturnValueUintType(txType, val.Uint())
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return toContractReturnValueIntType(txType, val.Int())
case reflect.String:
return toContractReturnValueStringType(txType, []byte(val.String()))
case reflect.Slice:
return toContractReturnValueStringType(txType, val.Bytes())
case reflect.Struct:
{
return toContractReturnValueStructType(txType, val.Interface())
}
//case reflect.Bool:
//case reflect.Float64, reflect.Float32:
// case reflect.Array
}
panic("unsupported type")
}
func retrieveFnAndParams(input []byte, fns SCExportFns) (txType int, fnName string, fn SCExportFn, fnParams []reflect.Value, err error) {
defer func() {
if e := recover(); nil != e {
fn, fnParams, err = nil, nil, fmt.Errorf("parse tx data failed:%+v", e)
log.Error("Failed to parse tx data", "error", err, "input", input)
}
}()
var args [][]byte
if err := rlp.DecodeBytes(input, &args); nil != err {
log.Error("Failed to verify input of system contract,Decode rlp input failed", "error", err)
return 0, "", nil, nil, err
}
txType = int(common.BytesToInt64(args[0]))
fnName = string(args[1])
var ok bool
if fn, ok = fns[fnName]; !ok {
return 0, fnName, nil, nil, errFuncNotFoundInExportFuncs
}
fnType := reflect.TypeOf(fn)
paramNum := fnType.NumIn()
if paramNum != len(args)-2 {
log.Warn("params number invalid. ", "expected:", paramNum, "got:", len(args)-2)
return 0, fnName, nil, nil, errParamsNumInvalid
}
fnParams = make([]reflect.Value, paramNum)
for i := 0; i < paramNum; i++ {
targetType := fnType.In(i).String()
inputByte := args[i+2]
fnParams[i] = byteutil.ConvertBytesTo(inputByte, targetType)
}
return txType, fnName, fn, fnParams, nil
}
func CheckPublicKeyFormat(pub string) error {
b, err := hex.DecodeString(pub)
if err != nil {
return err
}
// nodeid = pubkey[1:]
b = append([]byte{4}, b...)
_, err = crypto.UnmarshalPubkey(b)
if err != nil {
return err
}
return nil
}
// Name Format
// Length: 2~128
// `^[a-zA-Z0-9_]\w{1,127}$`
func checkNameFormat(name string) (bool, error) {
b, err := regexp.Match(nameRegPattarn, []byte(name))
if err != nil {
return false, err
}
if !b {
err = errNameUnsupported
}
return b, err
}
func checkIpFormat(ip string) (bool, error) {
b, err := regexp.Match(ipRegPattarn, []byte(ip))
if err != nil {
return false, err
}
if !b {
err = errIPUnsupported
}
return b, err
}
// Email Format
// xxx@xxx.xxx
// total length <= 64
func checkEmailFormat(email string) (bool, error) {
b, err := regexp.Match(emailRegPattarn, []byte(email))
if err != nil {
return false, err
}
if len(email) > 64 {
return false, nil
}
if !b {
err = errEmailUnsupported
}
return b, nil
}
func checkPhoneFormat(phone string) (bool, error) {
b1, err1 := regexp.Match(telePhonePattarn, []byte(phone))
b2, err2 := regexp.Match(mobilePhonePattarn, []byte(phone))
if b1 || b2 {
return true, nil
}
if !b1 {
return b1, err1
}
return b2, err2
}
// generate state key compatible with bcwasm state key
func generateStateKey(key string) []byte {
return bcwasmutil.SerilizString(key)
}
func recoveryStateKey(key []byte) string {
return bcwasmutil.DeserilizeString(key)
}