/
cache.go
634 lines (548 loc) · 15.4 KB
/
cache.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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
package core
import (
"errors"
"fmt"
"math/big"
"strings"
"sync"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/p2p/enode"
"github.com/hashicorp/golang-lru"
)
type TransactionType uint8
const (
ValueTransferTxn TransactionType = iota
ContractCallTxn
ContractDeployTxn
)
type AccessType uint8
const (
// common access type list for both V1 and V2 model.
// the first 4 are used by both models
// last 3 are used by V2 in alignment with EEA specs
ReadOnly AccessType = iota
Transact
ContractDeploy
FullAccess
// below access types are only used by V2 model
ContractCall
TransactAndContractCall
TransactAndContractDeploy
ContractCallAndDeploy
)
type PermissionModelType uint8
const (
V1 PermissionModelType = iota
V2
Default
)
type OrgStatus uint8
const (
OrgPendingApproval OrgStatus = iota + 1
OrgApproved
OrgPendingSuspension
OrgSuspended
)
type OrgInfo struct {
OrgId string `json:"orgId"`
FullOrgId string `json:"fullOrgId"`
ParentOrgId string `json:"parentOrgId"`
UltimateParent string `json:"ultimateParent"`
Level *big.Int `json:"level"`
SubOrgList []string `json:"subOrgList"`
Status OrgStatus `json:"status"`
}
type NodeStatus uint8
const (
NodePendingApproval NodeStatus = iota + 1
NodeApproved
NodeDeactivated
NodeBlackListed
NodeRecoveryInitiated
)
type AcctStatus uint8
const (
AcctPendingApproval AcctStatus = iota + 1
AcctActive
AcctInactive
AcctSuspended
AcctBlacklisted
AdminRevoked
AcctRecoveryInitiated
AcctRecoveryCompleted
)
type NodeInfo struct {
OrgId string `json:"orgId"`
Url string `json:"url"`
Status NodeStatus `json:"status"`
}
type RoleInfo struct {
OrgId string `json:"orgId"`
RoleId string `json:"roleId"`
IsVoter bool `json:"isVoter"`
IsAdmin bool `json:"isAdmin"`
Access AccessType `json:"access"`
Active bool `json:"active"`
}
type AccountInfo struct {
OrgId string `json:"orgId"`
RoleId string `json:"roleId"`
AcctId common.Address `json:"acctId"`
IsOrgAdmin bool `json:"isOrgAdmin"`
Status AcctStatus `json:"status"`
}
type OrgDetailInfo struct {
NodeList []NodeInfo `json:"nodeList"`
RoleList []RoleInfo `json:"roleList"`
AcctList []AccountInfo `json:"acctList"`
SubOrgList []string `json:"subOrgList"`
}
var syncStarted = false
var defaultAccess = FullAccess
var qip714BlockReached = false
var networkBootUpCompleted = false
var networkAdminRole string
var orgAdminRole string
var PermissionModel = Default
var PermissionTransactionAllowedFunc func(_sender common.Address, _target common.Address, _value *big.Int, _gasPrice *big.Int, _gasLimit *big.Int, _payload []byte, _transactionType TransactionType) error
var (
OrgInfoMap *OrgCache
NodeInfoMap *NodeCache
RoleInfoMap *RoleCache
AcctInfoMap *AcctCache
)
type OrgKey struct {
OrgId string
}
type OrgCache struct {
c *lru.Cache
mux sync.Mutex
evicted bool
populateCacheFunc func(orgId string) (*OrgInfo, error)
}
func (o *OrgCache) PopulateCacheFunc(cf func(string) (*OrgInfo, error)) {
o.populateCacheFunc = cf
}
func NewOrgCache(cacheSize int) *OrgCache {
orgCache := OrgCache{evicted: false}
onEvictedFunc := func(k interface{}, v interface{}) {
orgCache.evicted = true
}
orgCache.c, _ = lru.NewWithEvict(cacheSize, onEvictedFunc)
return &orgCache
}
type RoleKey struct {
OrgId string
RoleId string
}
type RoleCache struct {
c *lru.Cache
evicted bool
populateCacheFunc func(*RoleKey) (*RoleInfo, error)
}
func (r *RoleCache) PopulateCacheFunc(cf func(*RoleKey) (*RoleInfo, error)) {
r.populateCacheFunc = cf
}
func NewRoleCache(cacheSize int) *RoleCache {
roleCache := RoleCache{evicted: false}
onEvictedFunc := func(k interface{}, v interface{}) {
roleCache.evicted = true
}
roleCache.c, _ = lru.NewWithEvict(cacheSize, onEvictedFunc)
return &roleCache
}
type NodeKey struct {
OrgId string
Url string
}
type NodeCache struct {
c *lru.Cache
evicted bool
populateCacheFunc func(string) (*NodeInfo, error)
populateAndValidateFunc func(string, string) bool
}
func (n *NodeCache) PopulateValidateFunc(cf func(string, string) bool) {
n.populateAndValidateFunc = cf
}
func (n *NodeCache) PopulateCacheFunc(cf func(string) (*NodeInfo, error)) {
n.populateCacheFunc = cf
}
func NewNodeCache(cacheSize int) *NodeCache {
nodeCache := NodeCache{evicted: false}
onEvictedFunc := func(k interface{}, v interface{}) {
nodeCache.evicted = true
}
nodeCache.c, _ = lru.NewWithEvict(cacheSize, onEvictedFunc)
return &nodeCache
}
type AccountKey struct {
AcctId common.Address
}
type AcctCache struct {
c *lru.Cache
evicted bool
populateCacheFunc func(account common.Address) (*AccountInfo, error)
}
func (a *AcctCache) PopulateCacheFunc(cf func(common.Address) (*AccountInfo, error)) {
a.populateCacheFunc = cf
}
func NewAcctCache(cacheSize int) *AcctCache {
acctCache := AcctCache{evicted: false}
onEvictedFunc := func(k interface{}, v interface{}) {
acctCache.evicted = true
}
acctCache.c, _ = lru.NewWithEvict(cacheSize, onEvictedFunc)
return &acctCache
}
func SetSyncStatus() {
syncStarted = true
}
func GetSyncStatus() bool {
return syncStarted
}
// sets default access to read only
func setDefaultAccess() {
if PermissionsEnabled() {
defaultAccess = ReadOnly
}
}
// sets the qip714block reached as true
func SetQIP714BlockReached() {
qip714BlockReached = true
setDefaultAccess()
}
// sets the network boot completed as true
func SetNetworkBootUpCompleted() {
networkBootUpCompleted = true
setDefaultAccess()
}
// return bool to indicate if permissions is enabled
func PermissionsEnabled() bool {
if PermissionModel == V2 {
return qip714BlockReached
} else {
return qip714BlockReached && networkBootUpCompleted
}
}
// sets default access to readonly and initializes the values for
// network admin role and org admin role
func SetDefaults(nwRoleId, oaRoleId string, permissionV2 bool) {
networkAdminRole = nwRoleId
orgAdminRole = oaRoleId
if permissionV2 {
PermissionModel = V2
} else {
PermissionModel = V1
}
}
func GetDefaults() (string, string, AccessType) {
return networkAdminRole, orgAdminRole, defaultAccess
}
func GetNodeUrl(enodeId string, ip string, port uint16, raftport uint16, isRaft bool) string {
if isRaft {
return fmt.Sprintf("enode://%s@%s:%d?discport=0&raftport=%d", enodeId, strings.Trim(ip, "\x00"), port, raftport)
}
return fmt.Sprintf("enode://%s@%s:%d?discport=0", enodeId, strings.Trim(ip, "\x00"), port)
}
func (o *OrgCache) UpsertOrg(orgId, parentOrg, ultimateParent string, level *big.Int, status OrgStatus) {
defer o.mux.Unlock()
o.mux.Lock()
var key OrgKey
if parentOrg == "" {
key = OrgKey{OrgId: orgId}
} else {
key = OrgKey{OrgId: parentOrg + "." + orgId}
pkey := OrgKey{OrgId: parentOrg}
if ent, ok := o.c.Get(pkey); ok {
porg := ent.(*OrgInfo)
if !containsKey(porg.SubOrgList, key.OrgId) {
porg.SubOrgList = append(porg.SubOrgList, key.OrgId)
o.c.Add(pkey, porg)
}
}
}
norg := &OrgInfo{orgId, key.OrgId, parentOrg, ultimateParent, level, nil, status}
o.c.Add(key, norg)
}
func (o *OrgCache) UpsertOrgWithSubOrgList(orgRec *OrgInfo) {
var key OrgKey
if orgRec.ParentOrgId == "" {
key = OrgKey{OrgId: orgRec.OrgId}
} else {
key = OrgKey{OrgId: orgRec.ParentOrgId + "." + orgRec.OrgId}
}
orgRec.FullOrgId = key.OrgId
o.c.Add(key, orgRec)
}
func containsKey(s []string, e string) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
func (o *OrgCache) GetOrg(orgId string) (*OrgInfo, error) {
key := OrgKey{OrgId: orgId}
if ent, ok := o.c.Get(key); ok {
return ent.(*OrgInfo), nil
}
// check if the org cache is evicted. if yes we need
// fetch the record from the contract
if o.evicted {
// call cache population function to populate from contract
orgRec, err := o.populateCacheFunc(orgId)
if err != nil {
return nil, err
}
// insert the received record into cache
o.UpsertOrgWithSubOrgList(orgRec)
//return the record
return orgRec, nil
}
return nil, errors.New("Org does not exist")
}
func (o *OrgCache) GetOrgList() []OrgInfo {
olist := make([]OrgInfo, len(o.c.Keys()))
for i, k := range o.c.Keys() {
v, _ := o.c.Get(k)
vp := v.(*OrgInfo)
olist[i] = *vp
}
return olist
}
func (n *NodeCache) UpsertNode(orgId string, url string, status NodeStatus) {
key := NodeKey{OrgId: orgId, Url: url}
n.c.Add(key, &NodeInfo{orgId, url, status})
}
func (n *NodeCache) GetNodeByUrl(url string) (*NodeInfo, error) {
for _, k := range n.c.Keys() {
ent := k.(NodeKey)
if ent.Url == url {
v, _ := n.c.Get(ent)
return v.(*NodeInfo), nil
}
}
// check if the node cache is evicted. if yes we need
// fetch the record from the contract
if n.evicted {
// call cache population function to populate from contract
nodeRec, err := n.populateCacheFunc(url)
if err != nil {
return nil, err
}
// insert the received record into cache
n.UpsertNode(nodeRec.OrgId, nodeRec.Url, nodeRec.Status)
//return the record
return nodeRec, err
}
return nil, errors.New("Node does not exist")
}
func (n *NodeCache) GetNodeList() []NodeInfo {
olist := make([]NodeInfo, len(n.c.Keys()))
for i, k := range n.c.Keys() {
v, _ := n.c.Get(k)
vp := v.(*NodeInfo)
olist[i] = *vp
}
return olist
}
func (a *AcctCache) UpsertAccount(orgId string, role string, acct common.Address, orgAdmin bool, status AcctStatus) {
key := AccountKey{acct}
a.c.Add(key, &AccountInfo{orgId, role, acct, orgAdmin, status})
}
func (a *AcctCache) GetAccount(acct common.Address) (*AccountInfo, error) {
if v, ok := a.c.Get(AccountKey{acct}); ok {
return v.(*AccountInfo), nil
}
// check if the account cache is evicted. if yes we need
// fetch the record from the contract
if a.evicted {
// call function to populate cache with the record
acctRec, err := a.populateCacheFunc(acct)
// insert the received record into cache
if err != nil {
return nil, err
}
a.UpsertAccount(acctRec.OrgId, acctRec.RoleId, acctRec.AcctId, acctRec.IsOrgAdmin, acctRec.Status)
//return the record
return acctRec, nil
}
return nil, nil
}
func (a *AcctCache) GetAcctList() []AccountInfo {
alist := make([]AccountInfo, len(a.c.Keys()))
for i, k := range a.c.Keys() {
v, _ := a.c.Get(k)
vp := v.(*AccountInfo)
alist[i] = *vp
}
return alist
}
func (a *AcctCache) GetAcctListOrg(orgId string) []AccountInfo {
var alist []AccountInfo
for _, k := range a.c.Keys() {
v, _ := a.c.Get(k)
vp := v.(*AccountInfo)
if vp.OrgId == orgId {
alist = append(alist, *vp)
}
}
return alist
}
func (a *AcctCache) GetAcctListRole(orgId, roleId string) []AccountInfo {
var alist []AccountInfo
for _, k := range a.c.Keys() {
v, _ := a.c.Get(k)
vp := v.(*AccountInfo)
orgRec, err := OrgInfoMap.GetOrg(vp.OrgId)
if err != nil {
return nil
}
if vp.RoleId == roleId && (vp.OrgId == orgId || (orgRec != nil && orgRec.UltimateParent == orgId)) {
alist = append(alist, *vp)
}
}
return alist
}
func (r *RoleCache) UpsertRole(orgId string, role string, voter bool, admin bool, access AccessType, active bool) {
key := RoleKey{orgId, role}
r.c.Add(key, &RoleInfo{orgId, role, voter, admin, access, active})
}
func (r *RoleCache) GetRole(orgId string, roleId string) (*RoleInfo, error) {
key := RoleKey{OrgId: orgId, RoleId: roleId}
if ent, ok := r.c.Get(key); ok {
return ent.(*RoleInfo), nil
}
// check if the role cache is evicted. if yes we need
// fetch the record from the contract
if r.evicted {
// call cache population function to populate from contract
roleRec, err := r.populateCacheFunc(&RoleKey{RoleId: roleId, OrgId: orgId})
if err != nil {
return nil, err
}
// insert the received record into cache
r.UpsertRole(roleRec.OrgId, roleRec.RoleId, roleRec.IsVoter, roleRec.IsAdmin, roleRec.Access, roleRec.Active)
//return the record
return roleRec, nil
}
return nil, errors.New("Invalid role")
}
func (r *RoleCache) GetRoleList() []RoleInfo {
rlist := make([]RoleInfo, len(r.c.Keys()))
for i, k := range r.c.Keys() {
v, _ := r.c.Get(k)
vp := v.(*RoleInfo)
rlist[i] = *vp
}
return rlist
}
// Returns the access type for an account. If not found returns
// default access
func GetAcctAccess(acctId common.Address) AccessType {
// check if the org status is fine to do the transaction
a, _ := AcctInfoMap.GetAccount(acctId)
if a != nil && a.Status == AcctActive {
// get the org details and ultimate org details. check org status
// if the org is not approved or pending suspension
if checkIfOrgActive(a.OrgId) {
if a.RoleId == networkAdminRole || a.RoleId == orgAdminRole {
return FullAccess
}
if r, _ := RoleInfoMap.GetRole(a.OrgId, a.RoleId); r != nil && r.Active {
return r.Access
}
if o, _ := OrgInfoMap.GetOrg(a.OrgId); o != nil {
if r, _ := RoleInfoMap.GetRole(o.UltimateParent, a.RoleId); r != nil && r.Active {
return r.Access
}
}
}
}
return defaultAccess
}
//checks if the given org is active in the network
func checkIfOrgActive(orgId string) bool {
o, _ := OrgInfoMap.GetOrg(orgId)
if o != nil && o.Status != OrgSuspended {
u, _ := OrgInfoMap.GetOrg(o.UltimateParent)
if u == nil {
return true
}
if u != nil && u.Status != OrgSuspended {
return true
}
}
return false
}
// checks if the passed account is linked to a org admin or
// network admin role
func CheckIfAdminAccount(acctId common.Address) bool {
if !PermissionsEnabled() {
return true
}
a, _ := AcctInfoMap.GetAccount(acctId)
if a != nil && a.Status == AcctActive {
if checkIfOrgActive(a.OrgId) {
if a.RoleId == networkAdminRole || a.RoleId == orgAdminRole {
return true
}
if r, _ := RoleInfoMap.GetRole(a.OrgId, a.RoleId); r != nil && r.Active && r.IsAdmin {
return true
}
if o, _ := OrgInfoMap.GetOrg(a.OrgId); o != nil {
if r, _ := RoleInfoMap.GetRole(o.UltimateParent, a.RoleId); r != nil && r.Active && r.IsAdmin {
return true
}
}
}
}
return false
}
// validates if the account can transact from the current node
func ValidateNodeForTxn(hexnodeId string, from common.Address) bool {
if !PermissionsEnabled() || hexnodeId == "" {
return true
}
passedEnodeId, err := enode.ParseV4(hexnodeId)
if err != nil {
return false
}
ac, _ := AcctInfoMap.GetAccount(from)
if ac == nil {
return true
}
acOrgRec, err := OrgInfoMap.GetOrg(ac.OrgId)
if err != nil {
return false
}
// scan through the node list and validate
for _, n := range NodeInfoMap.GetNodeList() {
orgRec, err := OrgInfoMap.GetOrg(n.OrgId)
if err != nil {
return false
}
if orgRec.UltimateParent == acOrgRec.UltimateParent {
recEnodeId, _ := enode.ParseV4(n.Url)
if recEnodeId.ID() == passedEnodeId.ID() && n.Status == NodeApproved {
return true
}
}
}
if NodeInfoMap.evicted {
return NodeInfoMap.populateAndValidateFunc(hexnodeId, acOrgRec.UltimateParent)
}
return false
}
func IsV2Permission() bool {
return PermissionModel == V2
}
// checks if the account permission allows the transaction to be executed
func IsTransactionAllowed(from common.Address, to common.Address, value *big.Int, gasPrice *big.Int, gasLimit *big.Int, payload []byte, transactionType TransactionType) error {
//if we have not reached QIP714 block return full access
if !PermissionsEnabled() {
return nil
}
return PermissionTransactionAllowedFunc(from, to, value, gasPrice, gasLimit, payload, transactionType)
}