def _connectTo(self, matchedVars): if matchedVars.get('conn') == 'connect': envName = matchedVars.get('env_name') envError = self.canConnectToEnv(envName) if envError: self.print(envError, token=Token.Error) self._printConnectUsage() else: # TODO: Just for the time being that we cannot accidentally # connect to live network even if we have a ledger for live # nodes.Once we have `live` exposed to the world, # this would be changed. if envName == "live": self.print("Cannot connect to live environment. Contact" " Sovrin.org to find out more!") return True # Using `_activeClient` instead of `activeClient` since using # `_activeClient` will initialize a client if not done already if self._activeClient: self.print("Disconnecting from {}".format(envName)) self._activeClient = None config = getConfig() config.poolTransactionsFile = self.envs[envName].poolLedger config.domainTransactionsFile = \ self.envs[envName].domainLedger self.activeEnv = envName self._buildClientIfNotExists(config) self.print("Connecting to {}...".format(envName), Token.BoldGreen) # Prompt has to be changed, so it show the environment too self._setPrompt(self.currPromptText) self.ensureClientConnected() return True
def __init__(self, name, nodeRegistry=None, clientAuthNr=None, ha=None, cliname=None, cliha=None, basedirpath=None, primaryDecider=None, pluginPaths: Iterable[str] = None, storage=None, config=None): self.config = config or getConfig() self.graphStore = self.getGraphStorage(name) super().__init__(name=name, nodeRegistry=nodeRegistry, clientAuthNr=clientAuthNr, ha=ha, cliname=cliname, cliha=cliha, basedirpath=basedirpath, primaryDecider=primaryDecider, pluginPaths=pluginPaths, storage=storage, config=self.config) self._addTxnsToGraphIfNeeded() self.configLedger = self.getConfigLedger() self.ledgerManager.addLedger(2, self.configLedger, postCatchupCompleteClbk=self.postConfigLedgerCaughtUp, postTxnAddedToLedgerClbk=self.postTxnFromCatchupAddedToLedger) self.upgrader = self.getUpgrader() self.nodeMsgRouter.routes[Request] = self.processNodeRequest self.nodeAuthNr = self.defaultNodeAuthNr()
def __init__(self, name, nodeRegistry=None, clientAuthNr=None, ha=None, cliname=None, cliha=None, basedirpath=None, primaryDecider=None, pluginPaths: Iterable[str] = None, storage=None, config=None): self.config = config or getConfig() self.graphStore = self.getGraphStorage(name) super().__init__(name=name, nodeRegistry=nodeRegistry, clientAuthNr=clientAuthNr, ha=ha, cliname=cliname, cliha=cliha, basedirpath=basedirpath, primaryDecider=primaryDecider, pluginPaths=pluginPaths, storage=storage, config=self.config) self._addTxnsToGraphIfNeeded()
def writeAnonCredPlugin(baseDir, reloadTestModules: bool = False): config = getConfig() pluginsPath = os.path.expanduser(os.path.join(baseDir, config.PluginsDir)) if not os.path.exists(pluginsPath): os.makedirs(pluginsPath) initFile = pluginsPath + "/__init__.py" with open(initFile, "a"): pass modules_to_reload = ["sovrin.cli.cli"] test_modules_to_reload = [ "sovrin.test.helper", "sovrin.test.cli.helper" # "sovrin.test.anon_creds.anon_creds_demo" ] if reloadTestModules: modules_to_reload.extend(test_modules_to_reload) reload_module_code = \ "reload_modules = " + str(modules_to_reload) + "\n" \ "for m in reload_modules:\n" \ " try:\n" \ " module_obj = importlib.import_module(m)\n" \ " importlib.reload(module_obj)\n" \ " except AttributeError as ae:\n" \ " print(\"Plugin loading failed: module {}, detail: {}\".format(m, str(ae)))\n" \ "\n"
def getBulldogLogger(): config = getConfig() path = expanduser('{}'.format(config.baseDir)) filePath = '{}/bulldog.log'.format(path) try: if not exists(filePath): with open(filePath, mode='a+'): # we just want to create a file if not exists # don't do anything else with file handler pass log = getLogger() log.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s %(message)s') fileHandler = logging.FileHandler(filePath, mode='a') fileHandler.setLevel(logging.DEBUG) fileHandler.setFormatter(formatter) log.addHandler(fileHandler) return log except OSError: print('Could not create log file') raise Exception
def __init__(self, name: str, nodeReg: Dict[str, HA] = None, ha: Union[HA, Tuple[str, int]] = None, peerHA: Union[HA, Tuple[str, int]] = None, basedirpath: str = None, config=None, sighex: str = None): config = config or getConfig() super().__init__(name, nodeReg, ha, basedirpath, config, sighex) self.graphStore = self.getGraphStore() self.autoDiscloseAttributes = False self.requestedPendingTxns = False self.hasAnonCreds = bool(peerHA) if self.hasAnonCreds: self.peerHA = peerHA if isinstance(peerHA, HA) else HA(*peerHA) stackargs = dict(name=self.stackName, ha=peerHA, main=True, auto=AutoMode.always) self.peerMsgRoutes = [] self.peerMsgRouter = Router(*self.peerMsgRoutes) self.peerStack = SimpleStack(stackargs, msgHandler=self.handlePeerMessage) self.peerStack.sign = self.sign self.peerInbox = deque() self._observers = {} # type Dict[str, Callable] self._observerSet = set() # makes it easier to guard against duplicates
def createAgent(agentClass, name, wallet=None, basedirpath=None, port=None, loop=None, clientClass=Client): config = getConfig() if not wallet: wallet = Wallet(name) if not basedirpath: basedirpath = config.baseDir if not port: _, port = genHa() _, clientPort = genHa() client = clientClass(randomString(6), ha=("0.0.0.0", clientPort), basedirpath=basedirpath) return agentClass(basedirpath=basedirpath, client=client, wallet=wallet, port=port, loop=loop)
def newNode(self, nodeName: str): config = getConfig() createGenesisTxnFile(self.genesisTransactions, self.basedirpath, config.domainTransactionsFile, getTxnOrderedFields(), reset=False) nodesAdded = super().newNode(nodeName) return nodesAdded
def cleanupDataLocation(self): loc = os.path.join(self.baseDir, "data/clients", self.name) logger.debug('Cleaning up location {} of test client {}'.format( loc, self.name)) try: shutil.rmtree(loc) except Exception as ex: logger.debug( "Error while removing temporary directory {}".format(ex)) config = getConfig() if config.ReqReplyStore == "orientdb" or config.ClientIdentityGraph: try: self._getOrientDbStore().client.db_drop(self.name) logger.debug("Dropped db {}".format(self.name)) except Exception as ex: logger.debug("Error while dropping db {}: {}".format( self.name, ex))
def buildBulldogWallet(): config = getConfig() baseDir = os.path.expanduser(config.baseDir) seedFileName = 'bulldog-seed' seedFilePath = '{}/{}'.format(baseDir, seedFileName) seed = 'Bulldog0000000000000000000000000' # if seed file is available, read seed from it if os.path.isfile(seedFilePath): try: with open(seedFilePath, mode='r+') as file: seed = file.read().strip(' \t\n\r') except OSError as e: bulldogLogger.warn('Error occurred while reading seed file:' 'error:{}'.format(e)) raise e return buildAgentWallet('Bulldog', bytes(seed, encoding='utf-8'))
def __init__(self, basedirpath: str, client: Client = None, wallet: Wallet = None, port: int = None, loop=None): if not basedirpath: config = getConfig() basedirpath = basedirpath or os.path.expanduser(config.baseDir) portParam, = self.getPassedArgs() super().__init__('Thrift Bank', basedirpath, client, wallet, portParam or port, loop=loop) # maps invitation nonces to internal ids self._invites = { "77fbf9dc8c8e6acde33de98c6d747b28c": 1 }
def __init__(self, basedirpath: str, client: Client = None, wallet: Wallet = None, port: int = None, loop=None): if not basedirpath: config = getConfig() basedirpath = basedirpath or os.path.expanduser(config.baseDir) portParam, = self.getPassedArgs() super().__init__('Acme Corp', basedirpath, client, wallet, portParam or port, loop=loop) self.availableClaims = [] # maps invitation nonces to internal ids self._invites = { "57fbf9dc8c8e6acde33de98c6d747b28c": 1, "3a2eb72eca8b404e8d412c5bf79f2640": 2, "8513d1397e87cada4214e2a650f603eb": 3, "810b78be79f29fc81335abaa4ee1c5e8": 4 } self._attrDefJobCert = AttribDef('Acme Job Certificat', [AttribType('first_name', encode=True), AttribType('last_name', encode=True), AttribType('employee_status', encode=True), AttribType('experience', encode=True), AttribType('salary_bracket', encode=True)]) self._attrDefJobApp = AttribDef('Acme Job Application', [AttribType('first_name', encode=True), AttribType('last_name', encode=True), AttribType('phone_number', encode=True), AttribType('degree', encode=True), AttribType('status', encode=True), AttribType('ssn', encode=True)]) # maps internal ids to attributes self._attrsJobCert = { 1: self._attrDefJobCert.attribs( first_name="Alice", last_name="Garcia", employee_status="Permanent", experience="3 years", salary_bracket="between $50,000 to $100,000"), 2: self._attrDefJobCert.attribs( first_name="Carol", last_name="Atkinson", employee_status="Permanent", experience="2 years", salary_bracket="between $60,000 to $90,000"), 3: self._attrDefJobCert.attribs( first_name="Frank", last_name="Jeffrey", employee_status="Temporary", experience="4 years", salary_bracket="between $40,000 to $80,000"), 4: self._attrDefJobCert.attribs( first_name="Craig", last_name="Richards", employee_status="On Contract", experience="3 years", salary_bracket="between $50,000 to $70,000") } self._claimDefJobCertKey = ClaimDefinitionKey("Job-Certificate", "0.2", self.wallet.defaultId) self._claimDefJobAppKey = ClaimDefinitionKey("Job-Application", "0.2", self.wallet.defaultId)
plenum.common.util.loggingConfigured = False from plenum.common.looper import Looper from plenum.test.cli.helper import newKeyPair, checkAllNodesStarted, \ checkCmdValid from sovrin.common.config_util import getConfig from sovrin.test.cli.helper import newCLI, ensureNodesCreated, getLinkInvitation from sovrin.test.agent.conftest import faberIsRunning as runningFaber, \ emptyLooper, faberWallet, faberLinkAdded, acmeWallet, acmeLinkAdded, \ acmeIsRunning as runningAcme, faberAgentPort, acmeAgentPort, faberAgent, \ acmeAgent, thriftIsRunning as runningThrift, thriftAgentPort, thriftWallet,\ thriftAgent config = getConfig() @pytest.yield_fixture(scope="module") def looper(): with Looper(debug=False) as l: yield l # TODO: Probably need to remove @pytest.fixture("module") def nodesCli(looper, tdir, nodeNames): cli = newCLI(looper, tdir) cli.enterCmd("new node all") checkAllNodesStarted(cli, *nodeNames) return cli
def _getOrientDbStore(self): config = getConfig() return OrientDbStore(user=config.OrientDB["user"], password=config.OrientDB["password"], dbName=self.name, storageType=pyorient.STORAGE_TYPE_MEMORY)
def testLogsFilePresentForBulldogAgent(earlAcceptedBulldogInvitation): config = getConfig() path = expanduser('{}'.format(config.baseDir)) filePath = '{}/bulldog.log'.format(path) assert exists(filePath)
def __init__(self, basedirpath: str, client: Client = None, wallet: Wallet = None, port: int = None, loop=None): if not basedirpath: config = getConfig() basedirpath = basedirpath or os.path.expanduser(config.baseDir) portParam, = self.getPassedArgs() super().__init__('Faber College', basedirpath, client, wallet, portParam or port, loop=loop) self.availableClaims = [] # maps invitation nonces to internal ids self._invites = { "b1134a647eb818069c089e7694f63e6d": 1, "2a2eb72eca8b404e8d412c5bf79f2640": 2, "7513d1397e87cada4214e2a650f603eb": 3, "710b78be79f29fc81335abaa4ee1c5e8": 4 } self._attrDef = AttribDef('faber', [ AttribType('student_name', encode=True), AttribType('ssn', encode=True), AttribType('degree', encode=True), AttribType('year', encode=True), AttribType('status', encode=True) ]) # maps internal ids to attributes self._attrs = { 1: self._attrDef.attribs(student_name="Alice Garcia", ssn="123-45-6789", degree="Bachelor of Science, Marketing", year="2015", status="graduated"), 2: self._attrDef.attribs(student_name="Carol Atkinson", ssn="783-41-2695", degree="Bachelor of Science, Physics", year="2012", status="graduated"), 3: self._attrDef.attribs(student_name="Frank Jeffrey", ssn="996-54-1211", degree="Bachelor of Arts, History", year="2013", status="dropped"), 4: self._attrDef.attribs(student_name="Craig Richards", ssn="151-44-5876", degree="MBA, Finance", year="2015", status="graduated") } self._claimDefKey = ClaimDefinitionKey("Transcript", "1.2", self.wallet.defaultId)
def conf(tdir): return getConfig(tdir)
def __init__(self, basedirpath: str, client: Client = None, wallet: Wallet = None, port: int = None, loop=None): if not basedirpath: config = getConfig() basedirpath = basedirpath or os.path.expanduser(config.baseDir) portParam, = self.getPassedArgs() super().__init__('Bulldog', basedirpath, client, wallet, portParam or port, loop=loop, agentLogger=bulldogLogger) self.availableClaims = [] # maps invitation nonces to internal ids self._invites = {'2e9882ea71976ddf9': 1, "2d03828a7383ea3ad": 2} self._attrDef = AttribDef('bulldog', [ AttribType('title', encode=True), AttribType('first_name', encode=True), AttribType('last_name', encode=True), AttribType('address_1', encode=True), AttribType('address_2', encode=True), AttribType('address_3', encode=True), AttribType('postcode_zip', encode=True), AttribType('date_of_birth', encode=True), AttribType('account_type', encode=True), AttribType('year_opened', encode=True), AttribType('account_status', encode=True) ]) # maps internal ids to attributes self._attrs = { 1: self._attrDef.attribs(title='Mrs.', first_name='Alicia', last_name='Garcia', address_1='H-301', address_2='Street 1', address_3='UK', postcode_zip='G61 3NR', date_of_birth='December 28, 1990', account_type='savings', year_opened='2000', account_status='active'), 2: self._attrDef.attribs(title='Mrs.', first_name='Jay', last_name='Raj', address_1='222', address_2='Baker Street', address_3='UK', postcode_zip='G61 3NR', date_of_birth='January 15, 1980', account_type='savings', year_opened='1999', account_status='active') } claimVersionFileName = 'bulldog-claim-def-version.txt' claimVersionNumber = 0.8 claimVersionFilePath = '{}/{}'.format(basedirpath, claimVersionFileName) # get version number from file if os.path.isfile(claimVersionFilePath): try: with open(claimVersionFilePath, mode='r+') as file: claimVersionNumber = float(file.read()) + 0.1 file.seek(0) # increment version and update file file.write(str(claimVersionNumber)) file.truncate() except OSError as e: bulldogLogger.warn('Error occurred while reading version file:' 'error:{}'.format(e)) raise e except ValueError as e: bulldogLogger.warn('Invalid version number') raise e else: try: with open(claimVersionFilePath, mode='w') as file: file.write(str(claimVersionNumber)) except OSError as e: bulldogLogger.warn('Error creating version file {}'.format(e)) raise e self._claimDefKey = ClaimDefinitionKey('Banking-Relationship', str(claimVersionNumber), self.wallet.defaultId)