This repository has been archived by the owner on May 13, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 346
/
snative.go
495 lines (428 loc) · 15.6 KB
/
snative.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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
// Copyright 2017 Monax Industries Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package evm
import (
"fmt"
"reflect"
"strings"
"github.com/hyperledger/burrow/acm"
"github.com/hyperledger/burrow/crypto"
"github.com/hyperledger/burrow/crypto/sha3"
"github.com/hyperledger/burrow/execution/errors"
"github.com/hyperledger/burrow/execution/evm/abi"
"github.com/hyperledger/burrow/logging"
"github.com/hyperledger/burrow/logging/structure"
"github.com/hyperledger/burrow/permission"
)
//
// SNative (from 'secure natives') are native (go) contracts that are dispatched
// based on account permissions and can access and modify an account's permissions
//
// Metadata for SNative contract. Acts as a call target from the EVM. Can be
// used to generate bindings in a smart contract languages.
type SNativeContractDescription struct {
// Comment describing purpose of SNative contract and reason for assembling
// the particular functions
Comment string
// Name of the SNative contract
Name string
functionsByID map[abi.FunctionID]*SNativeFunctionDescription
functions []*SNativeFunctionDescription
}
// Metadata for SNative functions. Act as call targets for the EVM when
// collected into an SNativeContractDescription. Can be used to generate
// bindings in a smart contract languages.
type SNativeFunctionDescription struct {
// Comment describing function's purpose, parameters, and return value
Comment string
// Function name (used to form signature)
Name string
// Function arguments
Arguments reflect.Type
// Function return values
Returns reflect.Type
// The abi
Abi abi.FunctionSpec
// Permissions required to call function
PermFlag permission.PermFlag
// Native function to which calls will be dispatched when a containing
F func(stateWriter Interface, caller crypto.Address, gas *uint64, logger *logging.Logger,
v interface{}) (interface{}, error)
}
func registerSNativeContracts() {
for _, contract := range SNativeContracts() {
if !RegisterNativeContract(contract.Address(), contract.Dispatch) {
panic(fmt.Errorf("could not register SNative contract %s because address %s already registered",
contract.Address(), contract.Name))
}
}
}
// Returns a map of all SNative contracts defined indexed by name
func SNativeContracts() map[string]*SNativeContractDescription {
contracts := []*SNativeContractDescription{
NewSNativeContract(`
* Interface for managing Secure Native authorizations.
* @dev This interface describes the functions exposed by the SNative permissions layer in burrow.
`,
"Permissions",
&SNativeFunctionDescription{Comment: `
* @notice Adds a role to an account
* @param Account account address
* @param Role role name
* @return result whether role was added
`,
Name: "addRole",
PermFlag: permission.AddRole,
Arguments: reflect.TypeOf(addRoleArgs{}),
Returns: reflect.TypeOf(addRoleRets{}),
F: addRole},
&SNativeFunctionDescription{Comment: `
* @notice Removes a role from an account
* @param Account account address
* @param Role role name
* @return result whether role was removed
`,
Name: "removeRole",
PermFlag: permission.RemoveRole,
Arguments: reflect.TypeOf(removeRoleArgs{}),
Returns: reflect.TypeOf(removeRoleRets{}),
F: removeRole},
&SNativeFunctionDescription{Comment: `
* @notice Indicates whether an account has a role
* @param Account account address
* @param Role role name
* @return result whether account has role
`,
Name: "hasRole",
PermFlag: permission.HasRole,
Arguments: reflect.TypeOf(hasRoleArgs{}),
Returns: reflect.TypeOf(hasRoleRets{}),
F: hasRole},
&SNativeFunctionDescription{Comment: `
* @notice Sets the permission flags for an account. Makes them explicitly set (on or off).
* @param Account account address
* @param Permission the base permissions flags to set for the account
* @param Set whether to set or unset the permissions flags at the account level
* @return The permission flag that was set as uint64
`,
Name: "setBase",
PermFlag: permission.SetBase,
Arguments: reflect.TypeOf(setBaseArgs{}),
Returns: reflect.TypeOf(setBaseRets{}),
F: setBase},
&SNativeFunctionDescription{Comment: `
* @notice Unsets the permissions flags for an account. Causes permissions being unset to fall through to global permissions.
* @param Account account address
* @param Permission the permissions flags to unset for the account
* @return The permission flag that was unset as uint64
`,
Name: "unsetBase",
PermFlag: permission.UnsetBase,
Arguments: reflect.TypeOf(unsetBaseArgs{}),
Returns: reflect.TypeOf(unsetBaseRets{}),
F: unsetBase},
&SNativeFunctionDescription{Comment: `
* @notice Indicates whether an account has a subset of permissions set
* @param Account account address
* @param Permission the permissions flags (mask) to check whether enabled against base permissions for the account
* @return result whether account has the passed permissions flags set
`,
Name: "hasBase",
PermFlag: permission.HasBase,
Arguments: reflect.TypeOf(hasBaseArgs{}),
Returns: reflect.TypeOf(hasBaseRets{}),
F: hasBase},
&SNativeFunctionDescription{Comment: `
* @notice Sets the global (default) permissions flags for the entire chain
* @param Permission the permissions flags to set
* @param Set whether to set (or unset) the permissions flags
* @return The permission flag that was set as uint64
`,
Name: "setGlobal",
PermFlag: permission.SetGlobal,
Arguments: reflect.TypeOf(setGlobalArgs{}),
Returns: reflect.TypeOf(setGlobalRets{}),
F: setGlobal},
),
}
contractMap := make(map[string]*SNativeContractDescription, len(contracts))
for _, contract := range contracts {
if _, ok := contractMap[contract.Name]; ok {
// If this happens we have a pseudo compile time error that will be caught
// on native.go init()
panic(fmt.Errorf("duplicate contract with name %s defined. "+
"Contract names must be unique", contract.Name))
}
contractMap[contract.Name] = contract
}
return contractMap
}
// Create a new SNative contract description object by passing a comment, name
// and a list of member functions descriptions
func NewSNativeContract(comment, name string,
functions ...*SNativeFunctionDescription) *SNativeContractDescription {
functionsByID := make(map[abi.FunctionID]*SNativeFunctionDescription, len(functions))
for _, f := range functions {
f.Abi = *abi.SpecFromStructReflect(f.Name, f.Arguments, f.Returns)
fid := f.Abi.FunctionID
otherF, ok := functionsByID[fid]
if ok {
panic(fmt.Errorf("function with ID %x already defined: %s", fid, otherF.Signature()))
}
functionsByID[fid] = f
}
return &SNativeContractDescription{
Comment: comment,
Name: name,
functionsByID: functionsByID,
functions: functions,
}
}
// This function is designed to be called from the EVM once a SNative contract
// has been selected. It is also placed in a registry by registerSNativeContracts
// So it can be looked up by SNative address
func (contract *SNativeContractDescription) Dispatch(st Interface, caller crypto.Address,
args []byte, gas *uint64, logger *logging.Logger) (output []byte, err error) {
logger = logger.With(structure.ScopeKey, "Dispatch", "contract_name", contract.Name)
if len(args) < abi.FunctionIDSize {
return nil, errors.ErrorCodef(errors.ErrorCodeNativeFunction,
"SNatives dispatch requires a 4-byte function identifier but arguments are only %v bytes long",
len(args))
}
var id abi.FunctionID
copy(id[:], args)
function, err := contract.FunctionByID(id)
if err != nil {
return nil, err
}
logger.TraceMsg("Dispatching to function",
"caller", caller,
"function_name", function.Name)
remainingArgs := args[abi.FunctionIDSize:]
// check if we have permission to call this function
if !HasPermission(st, caller, function.PermFlag) {
return nil, errors.LacksSNativePermission{Address: caller, SNative: function.Name}
}
nativeArgs := reflect.New(function.Arguments).Interface()
err = abi.UnpackIntoStruct(function.Abi.Inputs, remainingArgs, nativeArgs)
if err != nil {
return nil, err
}
nativeRets, err := function.F(st, caller, gas, logger, nativeArgs)
if err != nil {
return nil, err
}
err = st.Error()
if err != nil {
return nil, fmt.Errorf("state error in %v: %v", function, err)
}
return abi.PackIntoStruct(function.Abi.Outputs, nativeRets)
}
// We define the address of an SNative contact as the last 20 bytes of the sha3
// hash of its name
func (contract *SNativeContractDescription) Address() (address crypto.Address) {
hash := sha3.Sha3([]byte(contract.Name))
copy(address[:], hash[len(hash)-crypto.AddressLength:])
return
}
// Get function by calling identifier FunctionSelector
func (contract *SNativeContractDescription) FunctionByID(id abi.FunctionID) (*SNativeFunctionDescription, errors.CodedError) {
f, ok := contract.functionsByID[id]
if !ok {
return nil,
errors.ErrorCodef(errors.ErrorCodeNativeFunction, "unknown SNative function with ID %x", id)
}
return f, nil
}
// Get function by name
func (contract *SNativeContractDescription) FunctionByName(name string) (*SNativeFunctionDescription, error) {
for _, f := range contract.functions {
if f.Name == name {
return f, nil
}
}
return nil, fmt.Errorf("unknown SNative function with name %s", name)
}
// Get functions in order of declaration
func (contract *SNativeContractDescription) Functions() []*SNativeFunctionDescription {
functions := make([]*SNativeFunctionDescription, len(contract.functions))
copy(functions, contract.functions)
return functions
}
//
// SNative functions
//
// Get function signature
func (function *SNativeFunctionDescription) Signature() string {
argTypeNames := make([]string, len(function.Abi.Inputs))
for i, arg := range function.Abi.Inputs {
argTypeNames[i] = arg.EVM.GetSignature()
}
return fmt.Sprintf("%s(%s)", function.Name,
strings.Join(argTypeNames, ","))
}
// Get number of function arguments
func (function *SNativeFunctionDescription) NArgs() int {
return len(function.Abi.Inputs)
}
func (fn *SNativeFunctionDescription) String() string {
return fmt.Sprintf("SNativeFunction{Name: %s; Inputs: %d; Outputs: %d}",
fn.Name, len(fn.Abi.Inputs), len(fn.Abi.Outputs))
}
// Permission function defintions
// TODO: catch errors, log em, return 0s to the vm (should some errors cause exceptions though?)
type hasBaseArgs struct {
Account crypto.Address
Permission uint64
}
type hasBaseRets struct {
Result bool
}
func hasBase(state Interface, caller crypto.Address, gas *uint64, logger *logging.Logger,
a interface{}) (interface{}, error) {
args := a.(*hasBaseArgs)
if !state.Exists(args.Account) {
return false, fmt.Errorf("unknown account %s", args.Account)
}
permN := permission.PermFlag(args.Permission) // already shifted
if !permN.IsValid() {
return false, permission.ErrInvalidPermission(permN)
}
hasPermission := HasPermission(state, args.Account, permN)
logger.Trace.Log("function", "hasBase",
"address", args.Account.String(),
"perm_flag", fmt.Sprintf("%b", permN),
"has_permission", hasPermission)
return hasBaseRets{Result: hasPermission}, nil
}
type setBaseArgs struct {
Account crypto.Address
Permission uint64
Set bool
}
type setBaseRets struct {
Result uint64
}
func setBase(stateWriter Interface, caller crypto.Address, gas *uint64,
logger *logging.Logger, a interface{}) (interface{}, error) {
args := a.(*setBaseArgs)
exists := stateWriter.Exists(args.Account)
if !exists {
return false, fmt.Errorf("unknown account %s", args.Account)
}
permN := permission.PermFlag(args.Permission)
if !permN.IsValid() {
return 0, permission.ErrInvalidPermission(permN)
}
stateWriter.SetPermission(args.Account, permN, args.Set)
logger.Trace.Log("function", "setBase", "address", args.Account.String(),
"permission_flag", fmt.Sprintf("%b", permN),
"permission_value", args.Permission)
return setBaseRets{Result: uint64(permN)}, nil
}
type unsetBaseArgs struct {
Account crypto.Address
Permission uint64
}
type unsetBaseRets struct {
Result uint64
}
func unsetBase(stateWriter Interface, caller crypto.Address, gas *uint64, logger *logging.Logger,
a interface{}) (r interface{}, err error) {
args := a.(*unsetBaseArgs)
if !stateWriter.Exists(args.Account) {
return false, fmt.Errorf("unknown account %s", args.Account)
}
permN := permission.PermFlag(args.Permission)
if !permN.IsValid() {
return 0, permission.ErrInvalidPermission(permN)
}
stateWriter.UnsetPermission(args.Account, permN)
logger.Trace.Log("function", "unsetBase", "address", args.Account.String(),
"perm_flag", fmt.Sprintf("%b", permN),
"permission_flag", fmt.Sprintf("%b", permN))
return unsetBaseRets{Result: uint64(permN)}, nil
}
type setGlobalArgs struct {
Permission uint64
Set bool
}
type setGlobalRets struct {
Result uint64
}
func setGlobal(stateWriter Interface, caller crypto.Address, gas *uint64,
logger *logging.Logger, a interface{}) (interface{}, error) {
args := a.(*setGlobalArgs)
permN := permission.PermFlag(args.Permission)
if !permN.IsValid() {
return 0, permission.ErrInvalidPermission(permN)
}
stateWriter.SetPermission(acm.GlobalPermissionsAddress, permN, args.Set)
logger.Trace.Log("function", "setGlobal",
"permission_flag", fmt.Sprintf("%b", permN),
"permission_value", args.Set)
return setGlobalRets{Result: uint64(permN)}, nil
}
type hasRoleArgs struct {
Account crypto.Address
Role string
}
type hasRoleRets struct {
Result bool
}
func hasRole(st Interface, caller crypto.Address, gas *uint64,
logger *logging.Logger, a interface{}) (interface{}, error) {
args := a.(*hasRoleArgs)
perms := st.GetPermissions(args.Account)
if err := st.Error(); err != nil {
return false, fmt.Errorf("hasRole could not get permissions: %v", err)
}
hasRole := perms.HasRole(args.Role)
logger.Trace.Log("function", "hasRole", "address", args.Account.String(),
"role", args.Role,
"has_role", hasRole)
return hasRoleRets{Result: hasRole}, nil
}
type addRoleArgs struct {
Account crypto.Address
Role string
}
type addRoleRets struct {
Result bool
}
func addRole(stateWriter Interface, caller crypto.Address, gas *uint64, logger *logging.Logger,
v interface{}) (interface{}, error) {
args := v.(*addRoleArgs)
roleAdded := stateWriter.AddRole(args.Account, args.Role)
logger.Trace.Log("function", "addRole", "address", args.Account.String(),
"role", args.Role,
"role_added", roleAdded)
return addRoleRets{Result: roleAdded}, nil
}
type removeRoleArgs struct {
Account crypto.Address
Role string
}
type removeRoleRets struct {
Result bool
}
func removeRole(stateWriter Interface, caller crypto.Address, gas *uint64, logger *logging.Logger,
a interface{}) (interface{}, error) {
args := a.(*removeRoleArgs)
roleRemoved := stateWriter.RemoveRole(args.Account, args.Role)
logger.Trace.Log("function", "removeRole", "address", args.Account.String(),
"role", args.Role,
"role_removed", roleRemoved)
return removeRoleRets{Result: roleRemoved}, nil
}