forked from Consensys/quorum
/
permission.go
416 lines (374 loc) · 14.1 KB
/
permission.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
package permission
import (
"fmt"
"math/big"
"sync"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/eth"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/p2p/enode"
"github.com/ethereum/go-ethereum/params"
pcore "github.com/ethereum/go-ethereum/permission/core"
ptype "github.com/ethereum/go-ethereum/permission/core/types"
)
// This is to make sure all contract instances are ready and initialized
//
// Required to be call after standard service start lifecycle
func (p *PermissionCtrl) AfterStart() error {
log.Debug("permission service: binding contracts")
err := <-p.errorChan // capture any error happened during asyncStart. Also wait here if asyncStart is not yet finish
if err != nil {
return err
}
if err = p.contract.BindContracts(); err != nil {
return fmt.Errorf("populateInitPermissions failed to bind contracts: %v", err)
}
// populate the initial list of permissioned nodes and account accesses
if err := p.populateInitPermissions(params.DEFAULT_ORGCACHE_SIZE, params.DEFAULT_ROLECACHE_SIZE,
params.DEFAULT_NODECACHE_SIZE, params.DEFAULT_ACCOUNTCACHE_SIZE); err != nil {
return fmt.Errorf("populateInitPermissions failed: %v", err)
}
// set the function point for transaction allowed check
pcore.PermissionTransactionAllowedFunc = p.IsTransactionAllowed
setPermissionService(p)
// set the default access to ReadOnly
pcore.SetDefaults(p.permConfig.NwAdminRole, p.permConfig.OrgAdminRole, p.IsV2Permission())
for _, f := range []func() error{
p.monitorQIP714Block, // monitor block number to activate new permissions controls
p.backend.ManageOrgPermissions, // monitor org management related events
p.backend.ManageNodePermissions, // monitor org level Node management events
p.backend.ManageRolePermissions, // monitor org level role management events
p.backend.ManageAccountPermissions, // monitor org level account management events
} {
if err := f(); err != nil {
return err
}
}
log.Info("permission service: is now ready")
return nil
}
// start service asynchronously due to dependencies
func (p *PermissionCtrl) asyncStart() {
var ethereum *eth.Ethereum
// will be blocked here until Node is up
if err := p.node.Service(ðereum); err != nil {
p.errorChan <- fmt.Errorf("dependent ethereum service not started")
return
}
defer func() {
p.errorChan <- nil
}()
// for cases where the node is joining an existing network, permission service
// can be brought up only after block syncing is complete. This function
// waits for block syncing before the starting permissions
p.startWaitGroup.Add(1)
go func(_wg *sync.WaitGroup) {
log.Debug("permission service: waiting for downloader")
stopChan, stopSubscription := ptype.SubscribeStopEvent()
pollingTicker := time.NewTicker(10 * time.Millisecond)
defer func(start time.Time) {
log.Debug("permission service: downloader completed", "took", time.Since(start))
stopSubscription.Unsubscribe()
pollingTicker.Stop()
_wg.Done()
}(time.Now())
for {
select {
case <-pollingTicker.C:
if pcore.GetSyncStatus() && !ethereum.Downloader().Synchronising() {
return
}
case <-stopChan:
return
}
}
}(p.startWaitGroup) // wait for downloader to sync if any
log.Debug("permission service: waiting for all dependencies to be ready")
p.startWaitGroup.Wait()
client, err := p.node.Attach()
if err != nil {
p.errorChan <- fmt.Errorf("unable to create rpc client: %v", err)
return
}
p.ethClnt = ethclient.NewClient(client)
p.eth = ethereum
p.isRaft = p.eth.BlockChain().Config().Istanbul == nil && p.eth.BlockChain().Config().Clique == nil
p.updateBackEnd()
}
// monitors QIP714Block and set default access
func (p *PermissionCtrl) monitorQIP714Block() error {
// if QIP714block is not given, set the default access
// to readonly
if p.eth.BlockChain().Config().QIP714Block == nil || p.eth.BlockChain().Config().IsQIP714(p.eth.BlockChain().CurrentBlock().Number()) {
pcore.SetQIP714BlockReached()
return nil
}
//QIP714block is given, monitor block count
go func() {
chainHeadCh := make(chan core.ChainHeadEvent, 1)
headSub := p.eth.BlockChain().SubscribeChainHeadEvent(chainHeadCh)
defer headSub.Unsubscribe()
stopChan, stopSubscription := ptype.SubscribeStopEvent()
defer stopSubscription.Unsubscribe()
for {
select {
case head := <-chainHeadCh:
if p.eth.BlockChain().Config().IsQIP714(head.Block.Number()) {
pcore.SetQIP714BlockReached()
return
}
case <-stopChan:
return
}
}
}()
return nil
}
func (p *PermissionCtrl) instantiateCache(orgCacheSize, roleCacheSize, nodeCacheSize, accountCacheSize int) {
// instantiate the cache objects for permissions
pcore.OrgInfoMap = pcore.NewOrgCache(orgCacheSize)
pcore.OrgInfoMap.PopulateCacheFunc(p.populateOrgToCache)
pcore.RoleInfoMap = pcore.NewRoleCache(roleCacheSize)
pcore.RoleInfoMap.PopulateCacheFunc(p.populateRoleToCache)
pcore.NodeInfoMap = pcore.NewNodeCache(nodeCacheSize)
pcore.NodeInfoMap.PopulateCacheFunc(p.populateNodeCache)
pcore.NodeInfoMap.PopulateValidateFunc(p.populateNodeCacheAndValidate)
pcore.AcctInfoMap = pcore.NewAcctCache(accountCacheSize)
pcore.AcctInfoMap.PopulateCacheFunc(p.populateAccountToCache)
}
// Thus function checks if the initial network boot up status and if no
// populates permissions model with details from permission-config.json
func (p *PermissionCtrl) populateInitPermissions(orgCacheSize, roleCacheSize, nodeCacheSize, accountCacheSize int) error {
p.instantiateCache(orgCacheSize, roleCacheSize, nodeCacheSize, accountCacheSize)
networkInitialized, err := p.contract.GetNetworkBootStatus()
if err != nil {
// handle the scenario of no contract code.
log.Warn("Failed to retrieve network boot status ", "err", err)
return err
}
if !networkInitialized {
p.backend.MonitorNetworkBootUp()
if err := p.bootupNetwork(); err != nil {
return err
}
} else {
//populate orgs, nodes, roles and accounts from contract
for _, f := range []func() error{
p.populateOrgsFromContract,
p.populateNodesFromContract,
p.populateRolesFromContract,
p.populateAccountsFromContract,
} {
if err := f(); err != nil {
return err
}
}
pcore.SetNetworkBootUpCompleted()
}
return nil
}
// initialize the permissions model and populate initial values
func (p *PermissionCtrl) bootupNetwork() error {
if _, err := p.contract.SetPolicy(p.permConfig.NwAdminOrg, p.permConfig.NwAdminRole, p.permConfig.OrgAdminRole); err != nil {
log.Error("bootupNetwork SetPolicy failed", "err", err)
return err
}
if _, err := p.contract.Init(p.permConfig.SubOrgBreadth, p.permConfig.SubOrgDepth); err != nil {
log.Error("bootupNetwork init failed", "err", err)
return err
}
pcore.OrgInfoMap.UpsertOrg(p.permConfig.NwAdminOrg, "", p.permConfig.NwAdminOrg, big.NewInt(1), pcore.OrgApproved)
pcore.RoleInfoMap.UpsertRole(p.permConfig.NwAdminOrg, p.permConfig.NwAdminRole, true, true, pcore.FullAccess, true)
// populate the initial Node list from static-nodes.json
if err := p.populateStaticNodesToContract(); err != nil {
return err
}
// populate initial account access to full access
if err := p.populateInitAccountAccess(); err != nil {
return err
}
// update network status to boot completed
if err := p.updateNetworkStatus(); err != nil {
log.Error("failed to updated network boot status", "error", err)
return err
}
return nil
}
// populates the account access details from contract into cache
func (p *PermissionCtrl) populateAccountsFromContract() error {
if numberOfRoles, err := p.contract.GetNumberOfAccounts(); err == nil {
iOrgNum := numberOfRoles.Uint64()
for k := uint64(0); k < iOrgNum; k++ {
if addr, org, role, status, orgAdmin, err := p.contract.GetAccountDetailsFromIndex(big.NewInt(int64(k))); err == nil {
pcore.AcctInfoMap.UpsertAccount(org, role, addr, orgAdmin, pcore.AcctStatus(int(status.Int64())))
}
}
} else {
return err
}
return nil
}
// populates the role details from contract into cache
func (p *PermissionCtrl) populateRolesFromContract() error {
if numberOfRoles, err := p.contract.GetNumberOfRoles(); err == nil {
iOrgNum := numberOfRoles.Uint64()
for k := uint64(0); k < iOrgNum; k++ {
if roleStruct, err := p.contract.GetRoleDetailsFromIndex(big.NewInt(int64(k))); err == nil {
pcore.RoleInfoMap.UpsertRole(roleStruct.OrgId, roleStruct.RoleId, roleStruct.Voter, roleStruct.Admin, pcore.AccessType(int(roleStruct.AccessType.Int64())), roleStruct.Active)
}
}
} else {
return err
}
return nil
}
// populates the Node details from contract into cache
func (p *PermissionCtrl) populateNodesFromContract() error {
if numberOfNodes, err := p.contract.GetNumberOfNodes(); err == nil {
iOrgNum := numberOfNodes.Uint64()
for k := uint64(0); k < iOrgNum; k++ {
if orgId, url, status, err := p.contract.GetNodeDetailsFromIndex(big.NewInt(int64(k))); err == nil {
pcore.NodeInfoMap.UpsertNode(orgId, url, pcore.NodeStatus(int(status.Int64())))
}
}
} else {
return err
}
return nil
}
// populates the org details from contract into cache
func (p *PermissionCtrl) populateOrgsFromContract() error {
if numberOfOrgs, err := p.contract.GetNumberOfOrgs(); err == nil {
iOrgNum := numberOfOrgs.Uint64()
for k := uint64(0); k < iOrgNum; k++ {
if orgId, porgId, ultParent, level, status, err := p.contract.GetOrgInfo(big.NewInt(int64(k))); err == nil {
pcore.OrgInfoMap.UpsertOrg(orgId, porgId, ultParent, level, pcore.OrgStatus(int(status.Int64())))
}
}
} else {
return err
}
return nil
}
// Reads the node list from static-nodes.json and populates into the contract
func (p *PermissionCtrl) populateStaticNodesToContract() error {
nodes := p.node.Server().Config.StaticNodes
for _, node := range nodes {
url := pcore.GetNodeUrl(node.EnodeID(), node.IP().String(), uint16(node.TCP()), uint16(node.RaftPort()), p.isRaft)
_, err := p.contract.AddAdminNode(url)
if err != nil {
log.Warn("Failed to propose node", "err", err, "enode", node.EnodeID())
return err
}
pcore.NodeInfoMap.UpsertNode(p.permConfig.NwAdminOrg, url, 2)
}
return nil
}
// Invokes the initAccounts function of smart contract to set the initial
// set of accounts access to full access
func (p *PermissionCtrl) populateInitAccountAccess() error {
for _, a := range p.permConfig.Accounts {
_, er := p.contract.AddAdminAccount(a)
if er != nil {
log.Warn("Error adding permission initial account list", "err", er, "account", a)
return er
}
pcore.AcctInfoMap.UpsertAccount(p.permConfig.NwAdminOrg, p.permConfig.NwAdminRole, a, true, 2)
}
return nil
}
// updates network boot status to true
func (p *PermissionCtrl) updateNetworkStatus() error {
_, err := p.contract.UpdateNetworkBootStatus()
if err != nil {
log.Warn("Failed to udpate network boot status ", "err", err)
return err
}
return nil
}
// getter to get an account record from the contract
func (p *PermissionCtrl) populateAccountToCache(acctId common.Address) (*pcore.AccountInfo, error) {
account, orgId, roleId, status, isAdmin, err := p.contract.GetAccountDetails(acctId)
if err != nil {
return nil, err
}
if status.Int64() == 0 {
return nil, ptype.ErrAccountNotThere
}
return &pcore.AccountInfo{AcctId: account, OrgId: orgId, RoleId: roleId, Status: pcore.AcctStatus(status.Int64()), IsOrgAdmin: isAdmin}, nil
}
// getter to get a org record from the contract
func (p *PermissionCtrl) populateOrgToCache(orgId string) (*pcore.OrgInfo, error) {
org, parentOrgId, ultimateParentId, orgLevel, orgStatus, err := p.contract.GetOrgDetails(orgId)
if err != nil {
return nil, err
}
if orgStatus.Int64() == 0 {
return nil, ptype.ErrOrgDoesNotExists
}
orgInfo := pcore.OrgInfo{OrgId: org, ParentOrgId: parentOrgId, UltimateParent: ultimateParentId, Status: pcore.OrgStatus(orgStatus.Int64()), Level: orgLevel}
// now need to build the list of sub orgs for this org
subOrgIndexes, err := p.contract.GetSubOrgIndexes(orgId)
if err != nil {
return nil, err
}
if len(subOrgIndexes) == 0 {
return &orgInfo, nil
}
// range through the sub org indexes and get the org ids to populate the suborg list
for _, s := range subOrgIndexes {
subOrgId, _, _, _, _, err := p.contract.GetOrgInfo(s)
if err != nil {
return nil, err
}
orgInfo.SubOrgList = append(orgInfo.SubOrgList, orgId+"."+subOrgId)
}
return &orgInfo, nil
}
// getter to get a role record from the contract
func (p *PermissionCtrl) populateRoleToCache(roleKey *pcore.RoleKey) (*pcore.RoleInfo, error) {
roleDetails, err := p.contract.GetRoleDetails(roleKey.RoleId, roleKey.OrgId)
if err != nil {
return nil, err
}
if roleDetails.OrgId == "" {
return nil, ptype.ErrInvalidRole
}
return &pcore.RoleInfo{OrgId: roleDetails.OrgId, RoleId: roleDetails.RoleId, IsVoter: roleDetails.Voter, IsAdmin: roleDetails.Admin, Access: pcore.AccessType(roleDetails.AccessType.Int64()), Active: roleDetails.Active}, nil
}
// getter to get a role record from the contract
func (p *PermissionCtrl) populateNodeCache(url string) (*pcore.NodeInfo, error) {
orgId, url, status, err := p.contract.GetNodeDetails(url)
if err != nil {
return nil, err
}
if status.Int64() == 0 {
return nil, ptype.ErrNodeDoesNotExists
}
return &pcore.NodeInfo{OrgId: orgId, Url: url, Status: pcore.NodeStatus(status.Int64())}, nil
}
// getter to get a Node record from the contract
func (p *PermissionCtrl) populateNodeCacheAndValidate(hexNodeId, ultimateParentId string) bool {
txnAllowed := false
passedEnode, _ := enode.ParseV4(hexNodeId)
if numberOfNodes, err := p.contract.GetNumberOfNodes(); err == nil {
numNodes := numberOfNodes.Uint64()
for k := uint64(0); k < numNodes; k++ {
if orgId, url, status, err := p.contract.GetNodeDetailsFromIndex(big.NewInt(int64(k))); err == nil {
if orgRec, err := pcore.OrgInfoMap.GetOrg(orgId); err != nil {
if orgRec.UltimateParent == ultimateParentId {
recEnode, _ := enode.ParseV4(url)
if recEnode.ID() == passedEnode.ID() {
txnAllowed = true
pcore.NodeInfoMap.UpsertNode(orgId, url, pcore.NodeStatus(int(status.Int64())))
}
}
}
}
}
}
return txnAllowed
}