github.com/kisexp/xdchain@v0.0.0-20211206025815-490d6b732aa7/permission/permission_test.go (about)

     1  package permission
     2  
     3  import (
     4  	"crypto/ecdsa"
     5  	"encoding/json"
     6  	"errors"
     7  	"fmt"
     8  	"io/ioutil"
     9  	"log"
    10  	"math/big"
    11  	"os"
    12  	"strconv"
    13  	"testing"
    14  
    15  	"github.com/kisexp/xdchain/accounts"
    16  	"github.com/kisexp/xdchain/accounts/abi/bind"
    17  	"github.com/kisexp/xdchain/accounts/abi/bind/backends"
    18  	"github.com/kisexp/xdchain/accounts/keystore"
    19  	"github.com/kisexp/xdchain/common"
    20  	"github.com/kisexp/xdchain/common/hexutil"
    21  	"github.com/kisexp/xdchain/consensus/ethash"
    22  	"github.com/kisexp/xdchain/core"
    23  	"github.com/kisexp/xdchain/crypto"
    24  	"github.com/kisexp/xdchain/eth"
    25  	"github.com/kisexp/xdchain/internal/ethapi"
    26  	"github.com/kisexp/xdchain/miner"
    27  	"github.com/kisexp/xdchain/node"
    28  	"github.com/kisexp/xdchain/p2p"
    29  	"github.com/kisexp/xdchain/params"
    30  	pcore "github.com/kisexp/xdchain/permission/core"
    31  	ptype "github.com/kisexp/xdchain/permission/core/types"
    32  	v1 "github.com/kisexp/xdchain/permission/v1"
    33  	v1bind "github.com/kisexp/xdchain/permission/v1/bind"
    34  	v2 "github.com/kisexp/xdchain/permission/v2"
    35  	v2bind "github.com/kisexp/xdchain/permission/v2/bind"
    36  	"github.com/stretchr/testify/assert"
    37  )
    38  
    39  const (
    40  	arbitraryNetworkAdminOrg   = "NETWORK_ADMIN"
    41  	arbitraryNetworkAdminRole  = "NETWORK_ADMIN_ROLE"
    42  	arbitraryOrgAdminRole      = "ORG_ADMIN_ROLE"
    43  	arbitraryNode1             = "enode://ac6b1096ca56b9f6d004b779ae3728bf83f8e22453404cc3cef16a3d9b96608bc67c4b30db88e0a5a6c6390213f7acbe1153ff6d23ce57380104288ae19373ef@127.0.0.1:21000?discport=0&raftport=50401"
    44  	arbitraryNode2             = "enode://0ba6b9f606a43a95edc6247cdb1c1e105145817be7bcafd6b2c0ba15d58145f0dc1a194f70ba73cd6f4cdd6864edc7687f311254c7555cc32e4d45aeb1b80416@127.0.0.1:21001?discport=0&raftport=50402"
    45  	arbitraryNode3             = "enode://579f786d4e2830bbcc02815a27e8a9bacccc9605df4dc6f20bcc1a6eb391e7225fff7cb83e5b4ecd1f3a94d8b733803f2f66b7e871961e7b029e22c155c3a778@127.0.0.1:21002?discport=0&raftport=50403"
    46  	arbitraryNode4             = "enode://3d9ca5956b38557aba991e31cf510d4df641dce9cc26bfeb7de082f0c07abb6ede3a58410c8f249dabeecee4ad3979929ac4c7c496ad20b8cfdd061b7401b4f5@127.0.0.1:21003?discport=0&raftport=50404"
    47  	arbitraryNode4withHostName = "enode://3d9ca5956b38557aba991e31cf510d4df641dce9cc26bfeb7de082f0c07abb6ede3a58410c8f249dabeecee4ad3979929ac4c7c496ad20b8cfdd061b7401b4f5@lcoalhost:21003?discport=0&raftport=50404"
    48  	arbitraryOrgToAdd          = "ORG1"
    49  	arbitrarySubOrg            = "SUB1"
    50  	arbitrartNewRole1          = "NEW_ROLE_1"
    51  	arbitrartNewRole2          = "NEW_ROLE_2"
    52  	orgCacheSize               = 4
    53  	roleCacheSize              = 4
    54  	nodeCacheSize              = 2
    55  	accountCacheSize           = 4
    56  )
    57  
    58  var ErrAccountsLinked = errors.New("Accounts linked to the role. Cannot be removed")
    59  var ErrPendingApproval = errors.New("Pending approvals for the organization. Approve first")
    60  var ErrAcctBlacklisted = errors.New("Blacklisted account. Operation not allowed")
    61  var ErrNodeBlacklisted = errors.New("Blacklisted node. Operation not allowed")
    62  
    63  var (
    64  	guardianKey     *ecdsa.PrivateKey
    65  	guardianAccount accounts.Account
    66  	contrBackend    bind.ContractBackend
    67  	ethereum        *eth.Ethereum
    68  	stack           *node.Node
    69  	guardianAddress common.Address
    70  	v2Flag          bool
    71  
    72  	permUpgrAddress, permInterfaceAddress, permImplAddress, voterManagerAddress,
    73  	nodeManagerAddress, roleManagerAddress, accountManagerAddress, orgManagerAddress common.Address
    74  )
    75  
    76  func TestMain(m *testing.M) {
    77  	var v2FlagVer = []bool{false}
    78  	var ret int
    79  	for i := range v2FlagVer {
    80  		v2Flag = v2FlagVer[i]
    81  		ret = m.Run()
    82  		if ret != 0 {
    83  			os.Exit(ret)
    84  		}
    85  	}
    86  	os.Exit(ret)
    87  }
    88  
    89  func setup() {
    90  	var err error
    91  	t := log.New(os.Stdout, "", 0)
    92  
    93  	ksdir, _, err := tmpKeyStore(false)
    94  	defer os.RemoveAll(ksdir)
    95  
    96  	if err != nil {
    97  		t.Fatalf("failed to create keystore: %v\n", err)
    98  	}
    99  	nodeKey, _ := crypto.GenerateKey()
   100  	guardianKey, _ = crypto.GenerateKey()
   101  
   102  	// Create a network-less protocol stack and start an Ethereum service within
   103  	stack, _ = node.New(&node.Config{
   104  		DataDir:           "",
   105  		KeyStoreDir:       ksdir,
   106  		UseLightweightKDF: true,
   107  		P2P: p2p.Config{
   108  			PrivateKey: nodeKey,
   109  		},
   110  	})
   111  
   112  	ksbackend := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
   113  	guardianAccount, err = ksbackend.ImportECDSA(guardianKey, "foo")
   114  	guardianAddress = guardianAccount.Address
   115  	if err != nil {
   116  		t.Fatal(err)
   117  	}
   118  	err = ksbackend.TimedUnlock(guardianAccount, "foo", 0)
   119  	if err != nil {
   120  		t.Fatal("failed to unlock")
   121  	}
   122  
   123  	genesisAlloc := map[common.Address]core.GenesisAccount{
   124  		guardianAddress: {
   125  			Balance: big.NewInt(100000000000000),
   126  		},
   127  	}
   128  	ethConf := &eth.Config{
   129  		Genesis: &core.Genesis{Config: params.AllEthashProtocolChanges, GasLimit: 10000000000, Alloc: genesisAlloc},
   130  		Miner:   miner.Config{Etherbase: guardianAddress},
   131  		Ethash: ethash.Config{
   132  			PowMode: ethash.ModeTest,
   133  		},
   134  	}
   135  
   136  	_, err = eth.New(stack, ethConf)
   137  	if err != nil {
   138  		t.Fatalf("failed to register Ethereum protocol: %v", err)
   139  	}
   140  	if err := stack.Lifecycle(&ethereum); err != nil {
   141  		t.Fatal(err)
   142  	}
   143  	contrBackend = backends.NewSimulatedBackendFrom(ethereum)
   144  
   145  	var permUpgrInstance *v1bind.PermUpgr
   146  	var permUpgrInstanceE *v2bind.PermUpgr
   147  
   148  	guardianTransactor := bind.NewKeyedTransactor(guardianKey)
   149  
   150  	if v2Flag {
   151  		permUpgrAddress, _, permUpgrInstanceE, err = v2bind.DeployPermUpgr(guardianTransactor, contrBackend, guardianAddress)
   152  		if err != nil {
   153  			t.Fatal(err)
   154  		}
   155  		permInterfaceAddress, _, _, err = v2bind.DeployPermInterface(guardianTransactor, contrBackend, permUpgrAddress)
   156  		if err != nil {
   157  			t.Fatal(err)
   158  		}
   159  		nodeManagerAddress, _, _, err = v2bind.DeployNodeManager(guardianTransactor, contrBackend, permUpgrAddress)
   160  		if err != nil {
   161  			t.Fatal(err)
   162  		}
   163  		roleManagerAddress, _, _, err = v2bind.DeployRoleManager(guardianTransactor, contrBackend, permUpgrAddress)
   164  		if err != nil {
   165  			t.Fatal(err)
   166  		}
   167  		accountManagerAddress, _, _, err = v2bind.DeployAcctManager(guardianTransactor, contrBackend, permUpgrAddress)
   168  		if err != nil {
   169  			t.Fatal(err)
   170  		}
   171  		orgManagerAddress, _, _, err = v2bind.DeployOrgManager(guardianTransactor, contrBackend, permUpgrAddress)
   172  		if err != nil {
   173  			t.Fatal(err)
   174  		}
   175  		voterManagerAddress, _, _, err = v2bind.DeployVoterManager(guardianTransactor, contrBackend, permUpgrAddress)
   176  		if err != nil {
   177  			t.Fatal(err)
   178  		}
   179  		permImplAddress, _, _, err = v2bind.DeployPermImpl(guardianTransactor, contrBackend, permUpgrAddress, orgManagerAddress, roleManagerAddress, accountManagerAddress, voterManagerAddress, nodeManagerAddress)
   180  		if err != nil {
   181  			t.Fatal(err)
   182  		}
   183  		// call init
   184  		if _, err := permUpgrInstanceE.Init(guardianTransactor, permInterfaceAddress, permImplAddress); err != nil {
   185  			t.Fatal(err)
   186  		}
   187  	} else {
   188  		permUpgrAddress, _, permUpgrInstance, err = v1bind.DeployPermUpgr(guardianTransactor, contrBackend, guardianAddress)
   189  		if err != nil {
   190  			t.Fatal(err)
   191  		}
   192  		permInterfaceAddress, _, _, err = v1bind.DeployPermInterface(guardianTransactor, contrBackend, permUpgrAddress)
   193  		if err != nil {
   194  			t.Fatal(err)
   195  		}
   196  		nodeManagerAddress, _, _, err = v1bind.DeployNodeManager(guardianTransactor, contrBackend, permUpgrAddress)
   197  		if err != nil {
   198  			t.Fatal(err)
   199  		}
   200  		roleManagerAddress, _, _, err = v1bind.DeployRoleManager(guardianTransactor, contrBackend, permUpgrAddress)
   201  		if err != nil {
   202  			t.Fatal(err)
   203  		}
   204  		accountManagerAddress, _, _, err = v1bind.DeployAcctManager(guardianTransactor, contrBackend, permUpgrAddress)
   205  		if err != nil {
   206  			t.Fatal(err)
   207  		}
   208  		orgManagerAddress, _, _, err = v1bind.DeployOrgManager(guardianTransactor, contrBackend, permUpgrAddress)
   209  		if err != nil {
   210  			t.Fatal(err)
   211  		}
   212  		voterManagerAddress, _, _, err = v1bind.DeployVoterManager(guardianTransactor, contrBackend, permUpgrAddress)
   213  		if err != nil {
   214  			t.Fatal(err)
   215  		}
   216  		permImplAddress, _, _, err = v1bind.DeployPermImpl(guardianTransactor, contrBackend, permUpgrAddress, orgManagerAddress, roleManagerAddress, accountManagerAddress, voterManagerAddress, nodeManagerAddress)
   217  		if err != nil {
   218  			t.Fatal(err)
   219  		}
   220  		// call init
   221  		if _, err := permUpgrInstance.Init(guardianTransactor, permInterfaceAddress, permImplAddress); err != nil {
   222  			t.Fatal(err)
   223  		}
   224  	}
   225  	fmt.Printf("current block is %v\n", ethereum.BlockChain().CurrentBlock().Number().Int64())
   226  }
   227  
   228  func TestPermissionCtrl_AfterStart(t *testing.T) {
   229  	testObject := typicalPermissionCtrl(t, v2Flag)
   230  
   231  	err := testObject.AfterStart()
   232  
   233  	assert.NoError(t, err)
   234  	if testObject.IsV2Permission() {
   235  		var contract *v2.Init
   236  		contract, _ = testObject.contract.(*v2.Init)
   237  		assert.NotNil(t, contract.PermOrg)
   238  		assert.NotNil(t, contract.PermRole)
   239  		assert.NotNil(t, contract.PermNode)
   240  		assert.NotNil(t, contract.PermAcct)
   241  		assert.NotNil(t, contract.PermInterf)
   242  		assert.NotNil(t, contract.PermUpgr)
   243  	} else {
   244  		var contract *v1.Init
   245  		contract, _ = testObject.contract.(*v1.Init)
   246  		assert.NotNil(t, contract.PermOrg)
   247  		assert.NotNil(t, contract.PermRole)
   248  		assert.NotNil(t, contract.PermNode)
   249  		assert.NotNil(t, contract.PermAcct)
   250  		assert.NotNil(t, contract.PermInterf)
   251  		assert.NotNil(t, contract.PermUpgr)
   252  	}
   253  
   254  	isNetworkInitialized, err := testObject.contract.GetNetworkBootStatus()
   255  	assert.NoError(t, err)
   256  	assert.True(t, isNetworkInitialized)
   257  }
   258  
   259  func TestPermissionCtrl_PopulateInitPermissions_AfterNetworkIsInitialized(t *testing.T) {
   260  	testObject := typicalPermissionCtrl(t, v2Flag)
   261  	assert.NoError(t, testObject.AfterStart())
   262  
   263  	err := testObject.populateInitPermissions(orgCacheSize, roleCacheSize, nodeCacheSize, accountCacheSize)
   264  
   265  	assert.NoError(t, err)
   266  
   267  	// assert cache
   268  	assert.Equal(t, 1, len(pcore.OrgInfoMap.GetOrgList()))
   269  	cachedOrg := pcore.OrgInfoMap.GetOrgList()[0]
   270  	assert.Equal(t, arbitraryNetworkAdminOrg, cachedOrg.OrgId)
   271  	assert.Equal(t, arbitraryNetworkAdminOrg, cachedOrg.FullOrgId)
   272  	assert.Equal(t, arbitraryNetworkAdminOrg, cachedOrg.UltimateParent)
   273  	assert.Equal(t, "", cachedOrg.ParentOrgId)
   274  	assert.Equal(t, pcore.OrgApproved, cachedOrg.Status)
   275  	assert.Equal(t, 0, len(cachedOrg.SubOrgList))
   276  	assert.Equal(t, big.NewInt(1), cachedOrg.Level)
   277  
   278  	assert.Equal(t, 1, len(pcore.RoleInfoMap.GetRoleList()))
   279  	cachedRole := pcore.RoleInfoMap.GetRoleList()[0]
   280  	assert.Equal(t, arbitraryNetworkAdminOrg, cachedRole.OrgId)
   281  	assert.Equal(t, arbitraryNetworkAdminRole, cachedRole.RoleId)
   282  	assert.True(t, cachedRole.Active)
   283  	assert.True(t, cachedRole.IsAdmin)
   284  	assert.True(t, cachedRole.IsVoter)
   285  	assert.Equal(t, pcore.FullAccess, cachedRole.Access)
   286  
   287  	assert.Equal(t, 0, len(pcore.NodeInfoMap.GetNodeList()))
   288  
   289  	assert.Equal(t, 1, len(pcore.AcctInfoMap.GetAcctList()))
   290  	cachedAccount := pcore.AcctInfoMap.GetAcctList()[0]
   291  	assert.Equal(t, arbitraryNetworkAdminOrg, cachedAccount.OrgId)
   292  	assert.Equal(t, arbitraryNetworkAdminRole, cachedAccount.RoleId)
   293  	assert.Equal(t, pcore.AcctActive, cachedAccount.Status)
   294  	assert.True(t, cachedAccount.IsOrgAdmin)
   295  	assert.Equal(t, guardianAddress, cachedAccount.AcctId)
   296  }
   297  
   298  func typicalQuorumControlsAPI(t *testing.T) *QuorumControlsAPI {
   299  	pc := typicalPermissionCtrl(t, v2Flag)
   300  	if !assert.NoError(t, pc.AfterStart()) {
   301  		t.Fail()
   302  	}
   303  	if !assert.NoError(t, pc.populateInitPermissions(orgCacheSize, roleCacheSize, nodeCacheSize, accountCacheSize)) {
   304  		t.Fail()
   305  	}
   306  	return NewQuorumControlsAPI(pc)
   307  }
   308  
   309  func TestQuorumControlsAPI_ListAPIs(t *testing.T) {
   310  	testObject := typicalQuorumControlsAPI(t)
   311  
   312  	orgDetails, err := testObject.GetOrgDetails(arbitraryNetworkAdminOrg)
   313  	assert.NoError(t, err)
   314  	assert.Equal(t, orgDetails.AcctList[0].AcctId, guardianAddress)
   315  	assert.Equal(t, orgDetails.RoleList[0].RoleId, arbitraryNetworkAdminRole)
   316  
   317  	orgDetails, err = testObject.GetOrgDetails("XYZ")
   318  	assert.Equal(t, err, errors.New("Org does not exist"))
   319  
   320  	// test NodeList
   321  	assert.Equal(t, len(testObject.NodeList()), 0)
   322  	// test AcctList
   323  	assert.True(t, len(testObject.AcctList()) > 0, "expected non zero account list")
   324  	// test OrgList
   325  	assert.True(t, len(testObject.OrgList()) > 0, "expected non zero org list")
   326  	// test RoleList
   327  	assert.True(t, len(testObject.RoleList()) > 0, "expected non zero org list")
   328  }
   329  
   330  func TestQuorumControlsAPI_OrgAPIs(t *testing.T) {
   331  	testObject := typicalQuorumControlsAPI(t)
   332  	invalidTxa := ethapi.SendTxArgs{From: getArbitraryAccount()}
   333  
   334  	// test AddOrg
   335  	orgAdminKey, _ := crypto.GenerateKey()
   336  	orgAdminAddress := crypto.PubkeyToAddress(orgAdminKey.PublicKey)
   337  
   338  	txa := ethapi.SendTxArgs{From: guardianAddress}
   339  	_, err := testObject.AddOrg(arbitraryOrgToAdd, arbitraryNode1, orgAdminAddress, invalidTxa)
   340  	assert.Equal(t, err, errors.New("Invalid account id"))
   341  
   342  	_, err = testObject.AddOrg(arbitraryOrgToAdd, arbitraryNode1, orgAdminAddress, txa)
   343  	assert.NoError(t, err)
   344  
   345  	_, err = testObject.AddOrg(arbitraryOrgToAdd, arbitraryNode1, orgAdminAddress, txa)
   346  	assert.Equal(t, err, ErrPendingApproval)
   347  
   348  	_, err = testObject.ApproveOrg(arbitraryOrgToAdd, arbitraryNode1, orgAdminAddress, invalidTxa)
   349  	assert.Equal(t, err, errors.New("Invalid account id"))
   350  
   351  	_, err = testObject.ApproveOrg("XYZ", arbitraryNode1, orgAdminAddress, txa)
   352  	assert.Equal(t, err, errors.New("Nothing to approve"))
   353  
   354  	_, err = testObject.ApproveOrg(arbitraryOrgToAdd, arbitraryNode1, orgAdminAddress, txa)
   355  	assert.NoError(t, err)
   356  
   357  	pcore.OrgInfoMap.UpsertOrg(arbitraryOrgToAdd, "", arbitraryOrgToAdd, big.NewInt(1), pcore.OrgApproved)
   358  	_, err = testObject.UpdateOrgStatus(arbitraryOrgToAdd, uint8(SuspendOrg), invalidTxa)
   359  	assert.Equal(t, err, errors.New("Invalid account id"))
   360  
   361  	_, err = testObject.UpdateOrgStatus(arbitraryOrgToAdd, uint8(SuspendOrg), txa)
   362  	assert.NoError(t, err)
   363  
   364  	pcore.OrgInfoMap.UpsertOrg(arbitraryOrgToAdd, "", arbitraryOrgToAdd, big.NewInt(1), pcore.OrgSuspended)
   365  	_, err = testObject.ApproveOrgStatus(arbitraryOrgToAdd, uint8(SuspendOrg), invalidTxa)
   366  	assert.Equal(t, err, errors.New("Invalid account id"))
   367  
   368  	_, err = testObject.ApproveOrgStatus(arbitraryOrgToAdd, uint8(SuspendOrg), txa)
   369  	assert.NoError(t, err)
   370  
   371  	_, err = testObject.AddSubOrg(arbitraryNetworkAdminOrg, arbitrarySubOrg, "", invalidTxa)
   372  	assert.Equal(t, err, errors.New("Invalid account id"))
   373  
   374  	_, err = testObject.AddSubOrg(arbitraryNetworkAdminOrg, arbitrarySubOrg, "", txa)
   375  	assert.NoError(t, err)
   376  	pcore.OrgInfoMap.UpsertOrg(arbitrarySubOrg, arbitraryNetworkAdminOrg, arbitraryNetworkAdminOrg, big.NewInt(2), pcore.OrgApproved)
   377  
   378  	suborg := "ABC.12345"
   379  	_, err = testObject.AddSubOrg(arbitraryNetworkAdminOrg, suborg, "", txa)
   380  	assert.Equal(t, err, errors.New("Org id cannot contain special characters"))
   381  
   382  	_, err = testObject.AddSubOrg(arbitraryNetworkAdminOrg, "", "", txa)
   383  	assert.Equal(t, err, errors.New("Invalid input"))
   384  
   385  	// caching tests - cache size for org is 4. add 4 sub orgs
   386  	// this will result in cache eviction
   387  	// get org details after this
   388  	for i := 0; i < orgCacheSize; i++ {
   389  		subOrgId := "TESTSUBORG" + strconv.Itoa(i)
   390  		_, err = testObject.AddSubOrg(arbitraryNetworkAdminOrg, subOrgId, "", txa)
   391  		assert.NoError(t, err)
   392  		pcore.OrgInfoMap.UpsertOrg(subOrgId, arbitraryNetworkAdminOrg, arbitraryNetworkAdminOrg, big.NewInt(2), pcore.OrgApproved)
   393  	}
   394  
   395  	assert.Equal(t, orgCacheSize, len(pcore.OrgInfoMap.GetOrgList()))
   396  
   397  	orgDetails, _ := testObject.GetOrgDetails(arbitraryNetworkAdminOrg)
   398  	assert.Equal(t, orgDetails.AcctList[0].AcctId, guardianAddress)
   399  	assert.Equal(t, orgDetails.RoleList[0].RoleId, arbitraryNetworkAdminRole)
   400  }
   401  
   402  func testConnectionAllowed(t *testing.T, q *QuorumControlsAPI, url string, expected bool) {
   403  	enode, ip, port, raftPort, err := ptype.GetNodeDetails(url, false, false)
   404  	if q.permCtrl.IsV2Permission() {
   405  		assert.NoError(t, err)
   406  		connAllowed := q.ConnectionAllowed(enode, ip, port, raftPort)
   407  		assert.Equal(t, expected, connAllowed)
   408  	} else {
   409  		assert.Equal(t, isNodePermissionedV1(url, enode, enode, "INCOMING"), expected)
   410  	}
   411  }
   412  
   413  func TestQuorumControlsAPI_NodeAPIs(t *testing.T) {
   414  	testObject := typicalQuorumControlsAPI(t)
   415  	invalidTxa := ethapi.SendTxArgs{From: getArbitraryAccount()}
   416  	txa := ethapi.SendTxArgs{From: guardianAddress}
   417  
   418  	testObject.permCtrl.isRaft = true
   419  	_, err := testObject.AddNode(arbitraryNetworkAdminOrg, arbitraryNode2, invalidTxa)
   420  	assert.Equal(t, err, errors.New("Invalid account id"))
   421  	testConnectionAllowed(t, testObject, arbitraryNode2, false)
   422  
   423  	_, err = testObject.AddNode(arbitraryNetworkAdminOrg, arbitraryNode2, txa)
   424  	assert.NoError(t, err)
   425  	pcore.NodeInfoMap.UpsertNode(arbitraryNetworkAdminOrg, arbitraryNode2, pcore.NodeApproved)
   426  	testConnectionAllowed(t, testObject, arbitraryNode2, true)
   427  
   428  	_, err = testObject.UpdateNodeStatus(arbitraryNetworkAdminOrg, arbitraryNode2, uint8(SuspendNode), invalidTxa)
   429  	assert.Equal(t, err, errors.New("Invalid account id"))
   430  
   431  	_, err = testObject.UpdateNodeStatus(arbitraryNetworkAdminOrg, arbitraryNode2, uint8(SuspendNode), txa)
   432  	assert.NoError(t, err)
   433  	pcore.NodeInfoMap.UpsertNode(arbitraryNetworkAdminOrg, arbitraryNode2, pcore.NodeDeactivated)
   434  	testConnectionAllowed(t, testObject, arbitraryNode2, false)
   435  
   436  	_, err = testObject.UpdateNodeStatus(arbitraryNetworkAdminOrg, arbitraryNode2, uint8(ActivateSuspendedNode), txa)
   437  	assert.NoError(t, err)
   438  	pcore.NodeInfoMap.UpsertNode(arbitraryNetworkAdminOrg, arbitraryNode2, pcore.NodeApproved)
   439  	testConnectionAllowed(t, testObject, arbitraryNode2, true)
   440  
   441  	_, err = testObject.UpdateNodeStatus(arbitraryNetworkAdminOrg, arbitraryNode2, uint8(BlacklistNode), txa)
   442  	assert.NoError(t, err)
   443  	pcore.NodeInfoMap.UpsertNode(arbitraryNetworkAdminOrg, arbitraryNode2, pcore.NodeBlackListed)
   444  
   445  	_, err = testObject.UpdateNodeStatus(arbitraryNetworkAdminOrg, arbitraryNode2, uint8(ActivateSuspendedNode), txa)
   446  	assert.Equal(t, err, ErrNodeBlacklisted)
   447  
   448  	_, err = testObject.RecoverBlackListedNode(arbitraryNetworkAdminOrg, arbitraryNode2, invalidTxa)
   449  	assert.Equal(t, err, errors.New("Invalid account id"))
   450  
   451  	_, err = testObject.RecoverBlackListedNode(arbitraryNetworkAdminOrg, arbitraryNode2, txa)
   452  	assert.NoError(t, err)
   453  	pcore.NodeInfoMap.UpsertNode(arbitraryNetworkAdminOrg, arbitraryNode2, pcore.NodeRecoveryInitiated)
   454  
   455  	_, err = testObject.ApproveBlackListedNodeRecovery(arbitraryNetworkAdminOrg, arbitraryNode2, invalidTxa)
   456  	assert.Equal(t, err, errors.New("Invalid account id"))
   457  
   458  	_, err = testObject.ApproveBlackListedNodeRecovery(arbitraryNetworkAdminOrg, arbitraryNode2, txa)
   459  	assert.NoError(t, err)
   460  	pcore.NodeInfoMap.UpsertNode(arbitraryNetworkAdminOrg, arbitraryNode2, pcore.NodeApproved)
   461  
   462  	// caching tests - cache size for Node is 3. add 2 nodes which will
   463  	// result in Node eviction from cache. get evicted Node details using api
   464  	_, err = testObject.AddNode(arbitraryNetworkAdminOrg, arbitraryNode3, txa)
   465  	assert.NoError(t, err)
   466  	pcore.NodeInfoMap.UpsertNode(arbitraryNetworkAdminOrg, arbitraryNode3, pcore.NodeApproved)
   467  
   468  	testObject.permCtrl.isRaft = true
   469  	_, err = testObject.AddNode(arbitraryNetworkAdminOrg, arbitraryNode4withHostName, txa)
   470  	assert.Equal(t, err, ptype.ErrHostNameNotSupported)
   471  
   472  	_, err = testObject.AddNode(arbitraryNetworkAdminOrg, arbitraryNode4, txa)
   473  	assert.NoError(t, err)
   474  	pcore.NodeInfoMap.UpsertNode(arbitraryNetworkAdminOrg, arbitraryNode4, pcore.NodeApproved)
   475  
   476  	assert.Equal(t, nodeCacheSize, len(pcore.NodeInfoMap.GetNodeList()))
   477  	nodeInfo, err := pcore.NodeInfoMap.GetNodeByUrl(arbitraryNode4)
   478  	assert.True(t, err == nil, "Node fetch returned error")
   479  	assert.Equal(t, pcore.NodeApproved, nodeInfo.Status)
   480  }
   481  
   482  func testTransactionAllowed(t *testing.T, q *QuorumControlsAPI, txa ethapi.SendTxArgs, expected bool) {
   483  	actAllowed := q.TransactionAllowed(txa)
   484  	assert.Equal(t, expected, actAllowed)
   485  }
   486  
   487  func TestQuorumControlsAPI_TransactionAllowed(t *testing.T) {
   488  	testObject := typicalQuorumControlsAPI(t)
   489  
   490  	if testObject.permCtrl.IsV2Permission() {
   491  
   492  		acct := getArbitraryAccount()
   493  		txa := ethapi.SendTxArgs{From: guardianAddress}
   494  		payload := hexutil.Bytes(([]byte("0x43d3e767000000000000000000000000000000000000000000000000000000000000000a"))[:])
   495  		value := hexutil.Big(*(big.NewInt(10)))
   496  
   497  		transactionTxa := ethapi.SendTxArgs{From: acct, To: &guardianAddress, Value: &value}
   498  		contractCallTxa := ethapi.SendTxArgs{From: acct, To: &guardianAddress, Data: &payload}
   499  		contractCreateTxa := ethapi.SendTxArgs{From: acct, To: &common.Address{}, Data: &payload}
   500  
   501  		for i := 0; i < 8; i++ {
   502  			roleId := arbitrartNewRole1 + strconv.Itoa(i)
   503  			_, err := testObject.AddNewRole(arbitraryNetworkAdminOrg, roleId, uint8(i), false, false, txa)
   504  			assert.NoError(t, err)
   505  			pcore.RoleInfoMap.UpsertRole(arbitraryNetworkAdminOrg, roleId, false, false, pcore.AccessType(uint8(i)), true)
   506  
   507  			if i == 0 {
   508  				_, err = testObject.AddAccountToOrg(acct, arbitraryNetworkAdminOrg, roleId, txa)
   509  				assert.NoError(t, err)
   510  			} else {
   511  				_, err = testObject.ChangeAccountRole(acct, arbitraryNetworkAdminOrg, roleId, txa)
   512  				assert.NoError(t, err)
   513  			}
   514  
   515  			switch pcore.AccessType(uint8(i)) {
   516  			case pcore.ReadOnly:
   517  				testTransactionAllowed(t, testObject, transactionTxa, false)
   518  				testTransactionAllowed(t, testObject, contractCallTxa, false)
   519  				testTransactionAllowed(t, testObject, contractCreateTxa, false)
   520  
   521  			case pcore.Transact:
   522  				testTransactionAllowed(t, testObject, transactionTxa, true)
   523  				testTransactionAllowed(t, testObject, contractCallTxa, false)
   524  				testTransactionAllowed(t, testObject, contractCreateTxa, false)
   525  
   526  			case pcore.ContractDeploy:
   527  				testTransactionAllowed(t, testObject, transactionTxa, false)
   528  				testTransactionAllowed(t, testObject, contractCallTxa, false)
   529  				testTransactionAllowed(t, testObject, contractCreateTxa, true)
   530  
   531  			case pcore.FullAccess:
   532  				testTransactionAllowed(t, testObject, transactionTxa, true)
   533  				testTransactionAllowed(t, testObject, contractCallTxa, true)
   534  				testTransactionAllowed(t, testObject, contractCreateTxa, true)
   535  
   536  			case pcore.ContractCall:
   537  				testTransactionAllowed(t, testObject, transactionTxa, false)
   538  				testTransactionAllowed(t, testObject, contractCallTxa, true)
   539  				testTransactionAllowed(t, testObject, contractCreateTxa, false)
   540  
   541  			case pcore.TransactAndContractCall:
   542  				testTransactionAllowed(t, testObject, transactionTxa, true)
   543  				testTransactionAllowed(t, testObject, contractCallTxa, true)
   544  				testTransactionAllowed(t, testObject, contractCreateTxa, false)
   545  
   546  			case pcore.TransactAndContractDeploy:
   547  				testTransactionAllowed(t, testObject, transactionTxa, true)
   548  				testTransactionAllowed(t, testObject, contractCallTxa, false)
   549  				testTransactionAllowed(t, testObject, contractCreateTxa, true)
   550  			case pcore.ContractCallAndDeploy:
   551  				testTransactionAllowed(t, testObject, transactionTxa, false)
   552  				testTransactionAllowed(t, testObject, contractCallTxa, true)
   553  				testTransactionAllowed(t, testObject, contractCreateTxa, true)
   554  
   555  			}
   556  
   557  		}
   558  	}
   559  
   560  }
   561  
   562  func TestQuorumControlsAPI_RoleAndAccountsAPIs(t *testing.T) {
   563  	testObject := typicalQuorumControlsAPI(t)
   564  	invalidTxa := ethapi.SendTxArgs{From: getArbitraryAccount()}
   565  	acct := getArbitraryAccount()
   566  	txa := ethapi.SendTxArgs{From: guardianAddress, To: &acct}
   567  
   568  	pcore.SetNetworkBootUpCompleted()
   569  	pcore.SetQIP714BlockReached()
   570  
   571  	_, err := testObject.AssignAdminRole(arbitraryNetworkAdminOrg, acct, arbitraryNetworkAdminRole, invalidTxa)
   572  	assert.Equal(t, err, errors.New("Invalid account id"))
   573  
   574  	_, _ = testObject.AssignAdminRole(arbitraryNetworkAdminOrg, acct, arbitraryNetworkAdminRole, txa)
   575  	pcore.AcctInfoMap.UpsertAccount(arbitraryNetworkAdminOrg, arbitraryNetworkAdminRole, acct, true, pcore.AcctPendingApproval)
   576  
   577  	_, err = testObject.ApproveAdminRole(arbitraryNetworkAdminOrg, acct, invalidTxa)
   578  	assert.Equal(t, err, errors.New("Invalid account id"))
   579  	testTransactionAllowed(t, testObject, ethapi.SendTxArgs{From: acct, To: &acct}, false)
   580  
   581  	_, err = testObject.ApproveAdminRole(arbitraryNetworkAdminOrg, acct, invalidTxa)
   582  	assert.Equal(t, err, errors.New("Invalid account id"))
   583  
   584  	_, err = testObject.ApproveAdminRole(arbitraryNetworkAdminOrg, acct, txa)
   585  	assert.NoError(t, err)
   586  	pcore.AcctInfoMap.UpsertAccount(arbitraryNetworkAdminOrg, arbitraryNetworkAdminRole, acct, true, pcore.AcctActive)
   587  	testTransactionAllowed(t, testObject, ethapi.SendTxArgs{From: acct, To: &acct}, true)
   588  
   589  	_, err = testObject.AddNewRole(arbitraryNetworkAdminOrg, arbitrartNewRole1, uint8(pcore.FullAccess), false, false, invalidTxa)
   590  	assert.Equal(t, err, errors.New("Invalid account id"))
   591  
   592  	_, err = testObject.AddNewRole(arbitraryNetworkAdminOrg, arbitrartNewRole1, uint8(pcore.FullAccess), false, false, txa)
   593  	assert.NoError(t, err)
   594  	pcore.RoleInfoMap.UpsertRole(arbitraryNetworkAdminOrg, arbitrartNewRole1, false, false, pcore.FullAccess, true)
   595  
   596  	acct = getArbitraryAccount()
   597  	_, err = testObject.AddAccountToOrg(acct, arbitraryNetworkAdminOrg, arbitrartNewRole1, invalidTxa)
   598  	assert.Equal(t, err, errors.New("Invalid account id"))
   599  
   600  	_, err = testObject.AddAccountToOrg(acct, arbitraryNetworkAdminOrg, arbitrartNewRole1, txa)
   601  	assert.NoError(t, err)
   602  	pcore.AcctInfoMap.UpsertAccount(arbitraryNetworkAdminOrg, arbitrartNewRole1, acct, true, pcore.AcctActive)
   603  
   604  	_, err = testObject.RemoveRole(arbitraryNetworkAdminOrg, arbitrartNewRole1, invalidTxa)
   605  	assert.Equal(t, err, errors.New("Invalid account id"))
   606  
   607  	_, err = testObject.RemoveRole(arbitraryNetworkAdminOrg, arbitrartNewRole1, txa)
   608  	assert.Equal(t, err, ErrAccountsLinked)
   609  
   610  	_, err = testObject.AddNewRole(arbitraryNetworkAdminOrg, arbitrartNewRole2, uint8(pcore.FullAccess), false, false, txa)
   611  	assert.NoError(t, err)
   612  	pcore.RoleInfoMap.UpsertRole(arbitraryNetworkAdminOrg, arbitrartNewRole2, false, false, pcore.FullAccess, true)
   613  
   614  	_, err = testObject.ChangeAccountRole(acct, arbitraryNetworkAdminOrg, arbitrartNewRole2, invalidTxa)
   615  	assert.Equal(t, err, errors.New("Invalid account id"))
   616  
   617  	_, err = testObject.ChangeAccountRole(acct, arbitraryNetworkAdminOrg, arbitrartNewRole2, txa)
   618  	assert.NoError(t, err)
   619  
   620  	_, err = testObject.RemoveRole(arbitraryNetworkAdminOrg, arbitrartNewRole1, txa)
   621  	assert.Equal(t, err, ErrAccountsLinked)
   622  
   623  	_, err = testObject.UpdateAccountStatus(arbitraryNetworkAdminOrg, acct, uint8(SuspendAccount), invalidTxa)
   624  	assert.Equal(t, err, errors.New("Invalid account id"))
   625  
   626  	_, err = testObject.UpdateAccountStatus(arbitraryNetworkAdminOrg, acct, uint8(SuspendAccount), txa)
   627  	assert.NoError(t, err)
   628  	pcore.AcctInfoMap.UpsertAccount(arbitraryNetworkAdminOrg, arbitrartNewRole2, acct, true, pcore.AcctSuspended)
   629  	testTransactionAllowed(t, testObject, ethapi.SendTxArgs{From: acct, To: &acct}, false)
   630  
   631  	_, err = testObject.UpdateAccountStatus(arbitraryNetworkAdminOrg, acct, uint8(ActivateSuspendedAccount), txa)
   632  	assert.NoError(t, err)
   633  	pcore.AcctInfoMap.UpsertAccount(arbitraryNetworkAdminOrg, arbitrartNewRole2, acct, true, pcore.AcctActive)
   634  
   635  	_, err = testObject.UpdateAccountStatus(arbitraryNetworkAdminOrg, acct, uint8(BlacklistAccount), txa)
   636  	assert.NoError(t, err)
   637  	pcore.AcctInfoMap.UpsertAccount(arbitraryNetworkAdminOrg, arbitrartNewRole2, acct, true, pcore.AcctBlacklisted)
   638  	testTransactionAllowed(t, testObject, ethapi.SendTxArgs{From: acct, To: &acct}, false)
   639  
   640  	_, err = testObject.UpdateAccountStatus(arbitraryNetworkAdminOrg, acct, uint8(ActivateSuspendedAccount), txa)
   641  	assert.Equal(t, err, ErrAcctBlacklisted)
   642  
   643  	_, err = testObject.RecoverBlackListedAccount(arbitraryNetworkAdminOrg, acct, invalidTxa)
   644  	assert.Equal(t, err, errors.New("Invalid account id"))
   645  
   646  	_, err = testObject.RecoverBlackListedAccount(arbitraryNetworkAdminOrg, acct, txa)
   647  	assert.NoError(t, err)
   648  	pcore.AcctInfoMap.UpsertAccount(arbitraryNetworkAdminOrg, arbitrartNewRole2, acct, true, pcore.AcctRecoveryInitiated)
   649  	_, err = testObject.ApproveBlackListedAccountRecovery(arbitraryNetworkAdminOrg, acct, txa)
   650  	assert.NoError(t, err)
   651  	pcore.AcctInfoMap.UpsertAccount(arbitraryNetworkAdminOrg, arbitrartNewRole2, acct, true, pcore.AcctActive)
   652  
   653  	// check role cache. the cache size is set to 4
   654  	// insert 4 records and then retrieve the 1st role
   655  	for i := 0; i < roleCacheSize; i++ {
   656  		roleId := "TESTROLE" + strconv.Itoa(i)
   657  		_, err = testObject.AddNewRole(arbitraryNetworkAdminOrg, roleId, uint8(pcore.FullAccess), false, false, txa)
   658  		assert.NoError(t, err)
   659  		pcore.RoleInfoMap.UpsertRole(arbitraryNetworkAdminOrg, roleId, false, false, pcore.FullAccess, true)
   660  	}
   661  
   662  	assert.Equal(t, roleCacheSize, len(pcore.RoleInfoMap.GetRoleList()))
   663  	roleInfo, err := pcore.RoleInfoMap.GetRole(arbitraryNetworkAdminOrg, arbitrartNewRole1)
   664  	assert.True(t, err == nil, "error encountered")
   665  
   666  	assert.Equal(t, roleInfo.RoleId, arbitrartNewRole1)
   667  
   668  	// check account cache
   669  	var AccountArray [4]common.Address
   670  	AccountArray[0] = common.StringToAddress("0fbdc686b912d7722dc86510934589e0aaf3b55a")
   671  	AccountArray[1] = common.StringToAddress("9186eb3d20cbd1f5f992a950d808c4495153abd5")
   672  	AccountArray[2] = common.StringToAddress("0638e1574728b6d862dd5d3a3e0942c3be47d996")
   673  	AccountArray[3] = common.StringToAddress("ae9bc6cd5145e67fbd1887a5145271fd182f0ee7")
   674  
   675  	for i := 0; i < accountCacheSize; i++ {
   676  		_, err = testObject.AddAccountToOrg(AccountArray[i], arbitraryNetworkAdminOrg, arbitrartNewRole1, txa)
   677  		assert.NoError(t, err)
   678  		pcore.AcctInfoMap.UpsertAccount(arbitraryNetworkAdminOrg, arbitrartNewRole1, AccountArray[i], false, pcore.AcctActive)
   679  	}
   680  	assert.Equal(t, accountCacheSize, len(pcore.AcctInfoMap.GetAcctList()))
   681  
   682  	acctInfo, err := pcore.AcctInfoMap.GetAccount(acct)
   683  	assert.True(t, err == nil, "error encountered")
   684  	assert.True(t, acctInfo != nil, "account details nil")
   685  }
   686  
   687  func getArbitraryAccount() common.Address {
   688  	acctKey, _ := crypto.GenerateKey()
   689  	return crypto.PubkeyToAddress(acctKey.PublicKey)
   690  }
   691  
   692  func typicalPermissionCtrl(t *testing.T, v2Flag bool) *PermissionCtrl {
   693  	setup() // need to be called before to mak sure the Node is in initial state
   694  
   695  	pconfig := &ptype.PermissionConfig{
   696  		UpgrdAddress:   permUpgrAddress,
   697  		InterfAddress:  permInterfaceAddress,
   698  		ImplAddress:    permImplAddress,
   699  		NodeAddress:    nodeManagerAddress,
   700  		AccountAddress: accountManagerAddress,
   701  		RoleAddress:    roleManagerAddress,
   702  		VoterAddress:   voterManagerAddress,
   703  		OrgAddress:     orgManagerAddress,
   704  		NwAdminOrg:     arbitraryNetworkAdminOrg,
   705  		NwAdminRole:    arbitraryNetworkAdminRole,
   706  		OrgAdminRole:   arbitraryOrgAdminRole,
   707  		Accounts: []common.Address{
   708  			guardianAddress,
   709  		},
   710  		SubOrgDepth:   big.NewInt(10),
   711  		SubOrgBreadth: big.NewInt(10),
   712  	}
   713  	if v2Flag {
   714  		pconfig.PermissionsModel = ptype.PERMISSION_V2
   715  	} else {
   716  		pconfig.PermissionsModel = ptype.PERMISSION_V1
   717  	}
   718  	testObject, err := NewQuorumPermissionCtrl(stack, pconfig, false)
   719  	if err != nil {
   720  		t.Fatal(err)
   721  	}
   722  
   723  	testObject.ethClnt = contrBackend
   724  	testObject.eth = ethereum
   725  
   726  	// set contract and backend's contract as asyncStart won't get called
   727  	testObject.contract = NewPermissionContractService(testObject.ethClnt, testObject.IsV2Permission(), testObject.key, testObject.permConfig, false, false)
   728  	if v2Flag {
   729  		b := testObject.backend.(*v2.Backend)
   730  		b.Contr = testObject.contract.(*v2.Init)
   731  	} else {
   732  		b := testObject.backend.(*v1.Backend)
   733  		b.Contr = testObject.contract.(*v1.Init)
   734  	}
   735  
   736  	// Start the Node and assemble the JavaScript console around it
   737  	// we can start now as the APIs are already registered
   738  	if err = stack.Start(); err != nil {
   739  		t.Fatalf("failed to start test stack: %v", err)
   740  	}
   741  
   742  	go func() {
   743  		testObject.errorChan <- nil
   744  	}()
   745  	return testObject
   746  }
   747  
   748  func tmpKeyStore(encrypted bool) (string, *keystore.KeyStore, error) {
   749  	d, err := ioutil.TempDir("", "Eth-keystore-test")
   750  	if err != nil {
   751  		return "", nil, err
   752  	}
   753  	newKs := keystore.NewPlaintextKeyStore
   754  	if encrypted {
   755  		newKs = func(kd string) *keystore.KeyStore {
   756  			return keystore.NewKeyStore(kd, keystore.LightScryptN, keystore.LightScryptP)
   757  		}
   758  	}
   759  	return d, newKs(d), err
   760  }
   761  
   762  func TestPermissionCtrl_whenUpdateFile(t *testing.T) {
   763  	testObject := typicalPermissionCtrl(t, v2Flag)
   764  	assert.NoError(t, testObject.AfterStart())
   765  
   766  	err := testObject.populateInitPermissions(orgCacheSize, roleCacheSize, nodeCacheSize, accountCacheSize)
   767  	assert.NoError(t, err)
   768  
   769  	d, _ := ioutil.TempDir("", "qdata")
   770  	defer os.RemoveAll(d)
   771  
   772  	testObject.dataDir = d
   773  	ptype.UpdatePermissionedNodes(testObject.node, d, arbitraryNode1, ptype.NodeAdd, true)
   774  
   775  	permFile, _ := os.Create(d + "/" + "permissioned-nodes.json")
   776  
   777  	ptype.UpdateFile("testFile", arbitraryNode2, ptype.NodeAdd, false)
   778  	ptype.UpdateFile(permFile.Name(), arbitraryNode2, ptype.NodeAdd, false)
   779  	ptype.UpdateFile(permFile.Name(), arbitraryNode2, ptype.NodeAdd, true)
   780  	ptype.UpdateFile(permFile.Name(), arbitraryNode2, ptype.NodeAdd, true)
   781  	ptype.UpdateFile(permFile.Name(), arbitraryNode1, ptype.NodeAdd, false)
   782  	ptype.UpdateFile(permFile.Name(), arbitraryNode1, ptype.NodeDelete, false)
   783  	ptype.UpdateFile(permFile.Name(), arbitraryNode1, ptype.NodeDelete, false)
   784  
   785  	blob, _ := ioutil.ReadFile(permFile.Name())
   786  	var nodeList []string
   787  	if err := json.Unmarshal(blob, &nodeList); err != nil {
   788  		t.Fatal("Failed to load nodes list from file", "fileName", permFile, "err", err)
   789  		return
   790  	}
   791  	assert.Equal(t, len(nodeList), 1)
   792  	ptype.UpdatePermissionedNodes(testObject.node, d, arbitraryNode1, ptype.NodeAdd, true)
   793  	ptype.UpdatePermissionedNodes(testObject.node, d, arbitraryNode1, ptype.NodeDelete, true)
   794  
   795  	blob, _ = ioutil.ReadFile(permFile.Name())
   796  	if err := json.Unmarshal(blob, &nodeList); err != nil {
   797  		t.Fatal("Failed to load nodes list from file", "fileName", permFile, "err", err)
   798  		return
   799  	}
   800  	assert.Equal(t, len(nodeList), 1)
   801  
   802  	ptype.UpdateDisallowedNodes(d, arbitraryNode2, ptype.NodeAdd)
   803  	ptype.UpdateDisallowedNodes(d, arbitraryNode2, ptype.NodeDelete)
   804  	blob, _ = ioutil.ReadFile(d + "/" + "disallowed-nodes.json")
   805  	if err := json.Unmarshal(blob, &nodeList); err != nil {
   806  		t.Fatal("Failed to load nodes list from file", "fileName", permFile, "err", err)
   807  		return
   808  	}
   809  	assert.Equal(t, len(nodeList), 0)
   810  
   811  }
   812  
   813  func TestParsePermissionConfig(t *testing.T) {
   814  	d, _ := ioutil.TempDir("", "qdata")
   815  	defer os.RemoveAll(d)
   816  
   817  	_, err := ptype.ParsePermissionConfig(d)
   818  	assert.True(t, err != nil, "expected file not there error")
   819  
   820  	fileName := d + "/permission-config.json"
   821  	os.Create(fileName)
   822  	_, err = ptype.ParsePermissionConfig(d)
   823  	assert.True(t, err != nil, "expected unmarshalling error")
   824  
   825  	// write permission-config.json into the temp dir
   826  	var tmpPermCofig ptype.PermissionConfig
   827  	tmpPermCofig.NwAdminOrg = arbitraryNetworkAdminOrg
   828  	tmpPermCofig.NwAdminRole = arbitraryNetworkAdminRole
   829  	tmpPermCofig.OrgAdminRole = arbitraryOrgAdminRole
   830  	tmpPermCofig.InterfAddress = common.Address{}
   831  	tmpPermCofig.ImplAddress = common.Address{}
   832  	tmpPermCofig.UpgrdAddress = common.Address{}
   833  	tmpPermCofig.VoterAddress = common.Address{}
   834  	tmpPermCofig.RoleAddress = common.Address{}
   835  	tmpPermCofig.OrgAddress = common.Address{}
   836  	tmpPermCofig.NodeAddress = common.Address{}
   837  	tmpPermCofig.SubOrgBreadth = new(big.Int)
   838  	tmpPermCofig.SubOrgDepth = new(big.Int)
   839  
   840  	blob, _ := json.Marshal(tmpPermCofig)
   841  	if err := ioutil.WriteFile(fileName, blob, 0644); err != nil {
   842  		t.Fatal("Error writing new Node info to file", "fileName", fileName, "err", err)
   843  	}
   844  	_, err = ptype.ParsePermissionConfig(d)
   845  	assert.True(t, err != nil, "permission model not given error")
   846  
   847  	_ = os.Remove(fileName)
   848  	tmpPermCofig.PermissionsModel = "ABCD"
   849  	blob, _ = json.Marshal(tmpPermCofig)
   850  	if err := ioutil.WriteFile(fileName, blob, 0644); err != nil {
   851  		t.Fatal("Error writing new Node info to file", "fileName", fileName, "err", err)
   852  	}
   853  
   854  	_, err = ptype.ParsePermissionConfig(d)
   855  	assert.True(t, err != nil, "invalid permission model error")
   856  	if err := ioutil.WriteFile(fileName, blob, 0644); err != nil {
   857  		t.Fatal("Error writing new Node info to file", "fileName", fileName, "err", err)
   858  	}
   859  
   860  	_ = os.Remove(fileName)
   861  	tmpPermCofig.PermissionsModel = "v1"
   862  	blob, _ = json.Marshal(tmpPermCofig)
   863  	if err := ioutil.WriteFile(fileName, blob, 0644); err != nil {
   864  		t.Fatal("Error writing new Node info to file", "fileName", fileName, "err", err)
   865  	}
   866  
   867  	_, err = ptype.ParsePermissionConfig(d)
   868  	assert.True(t, err != nil, "expected account not given  error")
   869  
   870  	_ = os.Remove(fileName)
   871  	tmpPermCofig.Accounts = append(tmpPermCofig.Accounts, common.StringToAddress("0xed9d02e382b34818e88b88a309c7fe71e65f419d"))
   872  	blob, _ = json.Marshal(tmpPermCofig)
   873  	if err := ioutil.WriteFile(fileName, blob, 0644); err != nil {
   874  		t.Fatal("Error writing new Node info to file", "fileName", fileName, "err", err)
   875  	}
   876  
   877  	_, err = ptype.ParsePermissionConfig(d)
   878  	assert.True(t, err != nil, "expected sub org depth not set error")
   879  
   880  	_ = os.Remove(fileName)
   881  	tmpPermCofig.SubOrgBreadth.Set(big.NewInt(4))
   882  	tmpPermCofig.SubOrgDepth.Set(big.NewInt(4))
   883  	blob, _ = json.Marshal(tmpPermCofig)
   884  	if err := ioutil.WriteFile(fileName, blob, 0644); err != nil {
   885  		t.Fatal("Error writing new Node info to file", "fileName", fileName, "err", err)
   886  	}
   887  
   888  	_, err = ptype.ParsePermissionConfig(d)
   889  	assert.True(t, err != nil, "expected contract address error")
   890  
   891  	_ = os.Remove(fileName)
   892  	tmpPermCofig.InterfAddress = common.StringToAddress("0xed9d02e382b34818e88b88a309c7fe71e65f419d")
   893  	blob, _ = json.Marshal(tmpPermCofig)
   894  	if err := ioutil.WriteFile(fileName, blob, 0644); err != nil {
   895  		t.Fatal("Error writing new Node info to file", "fileName", fileName, "err", err)
   896  	}
   897  	permConfig, _ := ptype.ParsePermissionConfig(d)
   898  	assert.False(t, permConfig.IsEmpty(), "expected non empty object")
   899  }
   900  
   901  func TestIsTransactionAllowed_V1(t *testing.T) {
   902  	testObject := typicalQuorumControlsAPI(t)
   903  	pcore.PermissionTransactionAllowedFunc = testObject.permCtrl.IsTransactionAllowed
   904  	var Acct1 = common.BytesToAddress([]byte("permission"))
   905  	var Acct2 = common.BytesToAddress([]byte("perm-test"))
   906  	pcore.SetDefaults(arbitraryNetworkAdminRole, arbitraryOrgAdminRole, false)
   907  	pcore.SetQIP714BlockReached()
   908  	pcore.SetNetworkBootUpCompleted()
   909  	pcore.OrgInfoMap = pcore.NewOrgCache(params.DEFAULT_ORGCACHE_SIZE)
   910  	pcore.RoleInfoMap = pcore.NewRoleCache(params.DEFAULT_ROLECACHE_SIZE)
   911  	pcore.AcctInfoMap = pcore.NewAcctCache(params.DEFAULT_ACCOUNTCACHE_SIZE)
   912  
   913  	pcore.OrgInfoMap.UpsertOrg(arbitraryOrgAdminRole, "", arbitraryOrgAdminRole, big.NewInt(1), pcore.OrgApproved)
   914  	pcore.RoleInfoMap.UpsertRole(arbitraryOrgAdminRole, "ROLE1", false, false, pcore.Transact, true)
   915  	pcore.RoleInfoMap.UpsertRole(arbitraryOrgAdminRole, "ROLE2", false, false, pcore.ContractDeploy, true)
   916  	pcore.RoleInfoMap.UpsertRole(arbitraryOrgAdminRole, "ROLE3", false, false, pcore.FullAccess, true)
   917  	var Acct3 = common.BytesToAddress([]byte("permission-test1"))
   918  	var Acct4 = common.BytesToAddress([]byte("permission-test2"))
   919  
   920  	pcore.AcctInfoMap.UpsertAccount(arbitraryOrgAdminRole, "ROLE1", Acct1, false, pcore.AcctActive)
   921  	pcore.AcctInfoMap.UpsertAccount(arbitraryOrgAdminRole, "ROLE2", Acct2, false, pcore.AcctActive)
   922  	pcore.AcctInfoMap.UpsertAccount(arbitraryOrgAdminRole, "ROLE3", Acct3, false, pcore.AcctActive)
   923  
   924  	type args struct {
   925  		address         common.Address
   926  		transactionType pcore.TransactionType
   927  	}
   928  	tests := []struct {
   929  		name    string
   930  		args    args
   931  		wantErr bool
   932  	}{
   933  		{
   934  			name:    "Account with transact permission calling value transfer",
   935  			args:    args{address: Acct1, transactionType: pcore.ValueTransferTxn},
   936  			wantErr: false,
   937  		},
   938  		{
   939  			name:    "Account with transact permission calling value contract call transaction",
   940  			args:    args{address: Acct1, transactionType: pcore.ContractCallTxn},
   941  			wantErr: false,
   942  		},
   943  		{
   944  			name:    "Account with transact permission calling contract deploy",
   945  			args:    args{address: Acct1, transactionType: pcore.ContractDeployTxn},
   946  			wantErr: true,
   947  		},
   948  		{
   949  			name:    "Account with contract permission deploy calling value transfer",
   950  			args:    args{address: Acct2, transactionType: pcore.ValueTransferTxn},
   951  			wantErr: false,
   952  		},
   953  		{
   954  			name:    "Account with contract deploy permission calling value contract call transaction",
   955  			args:    args{address: Acct2, transactionType: pcore.ContractCallTxn},
   956  			wantErr: false,
   957  		},
   958  		{
   959  			name:    "Account with contract deploy permission calling contract deploy",
   960  			args:    args{address: Acct2, transactionType: pcore.ContractDeployTxn},
   961  			wantErr: false,
   962  		},
   963  		{
   964  			name:    "Account with full permission calling value transfer",
   965  			args:    args{address: Acct3, transactionType: pcore.ValueTransferTxn},
   966  			wantErr: false,
   967  		},
   968  		{
   969  			name:    "Account with full permission calling value contract call transaction",
   970  			args:    args{address: Acct3, transactionType: pcore.ContractCallTxn},
   971  			wantErr: false,
   972  		},
   973  		{
   974  			name:    "Account with full permission calling contract deploy",
   975  			args:    args{address: Acct3, transactionType: pcore.ContractDeployTxn},
   976  			wantErr: false,
   977  		},
   978  		{
   979  			name:    "un-permissioned account calling value transfer",
   980  			args:    args{address: Acct4, transactionType: pcore.ValueTransferTxn},
   981  			wantErr: true,
   982  		},
   983  		{
   984  			name:    "un-permissioned account calling contract call transaction",
   985  			args:    args{address: Acct4, transactionType: pcore.ContractCallTxn},
   986  			wantErr: true,
   987  		},
   988  		{
   989  			name:    "un-permissioned account calling contract deploy",
   990  			args:    args{address: Acct4, transactionType: pcore.ContractDeployTxn},
   991  			wantErr: true,
   992  		},
   993  	}
   994  	for _, tt := range tests {
   995  		t.Run(tt.name, func(t *testing.T) {
   996  			if err := pcore.IsTransactionAllowed(tt.args.address, common.Address{}, nil, nil, nil, nil, tt.args.transactionType); (err != nil) != tt.wantErr {
   997  				t.Errorf("IsTransactionAllowed() error = %v, wantErr %v", err, tt.wantErr)
   998  			}
   999  		})
  1000  	}
  1001  }