Example #1
0
def runAgent(agentClass,
             name,
             wallet=None,
             basedirpath=None,
             port=None,
             startRunning=True,
             bootstrap=False):
    config = getConfig()

    if not wallet:
        wallet = Wallet(name)
    if not basedirpath:
        basedirpath = config.baseDir
    if not port:
        _, port = genHa()

    _, clientPort = genHa()
    client = Client(randomString(6),
                    ha=("0.0.0.0", clientPort),
                    basedirpath=basedirpath)

    agent = agentClass(basedirpath=basedirpath,
                       client=client,
                       wallet=wallet,
                       port=port)
    if startRunning:
        if bootstrap:
            agent.bootstrap()
        with Looper(debug=True) as looper:
            looper.add(agent)
            logger.debug("Running {} now (port: {})".format(name, port))
            looper.run()
    else:
        return agent
Example #2
0
 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()
Example #3
0
 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):
     config = config or getConfig()
     super().__init__(name, nodeReg, ha, basedirpath, config)
     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=name,
                          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
Example #4
0
 def cleanupDataLocation(self):
     loc = os.path.join(self.baseDir, "data/clients")
     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))
Example #5
0
def runAlice(name=None,
             wallet=None,
             basedirpath=None,
             port=None,
             startRunning=True):
    # TODO: Copied code from `runFaber`, need to refactor
    name = name or 'Alice Jones'
    wallet = wallet or Wallet(name)
    config = getConfig()
    basedirpath = basedirpath or os.path.expanduser(config.baseDir)
    if not port:
        _, port = genHa()
    _, clientPort = genHa()
    client = Client(randomString(6),
                    ha=("0.0.0.0", clientPort),
                    basedirpath=basedirpath)

    def listClaims(msg):
        body, frm = msg
        """
        body = {
            "type": <some type>,
            "identifier": <id>,
            "nonce": <nonce>,
            "signature" : <sig>
        }
        """
        # TODO: Need to do nonce verification here
        data = json.loads(body)
        print(data)
        # wallet.knownIds[data['identifier']] =
        # TODO: Send claims

    handlers = {AVAIL_CLAIM_LIST: listClaims}

    alice = AliceAgent(name,
                       basedirpath=basedirpath,
                       client=client,
                       port=port,
                       handlers=handlers)
    if startRunning:
        with Looper(debug=True) as looper:
            looper.add(alice)
            logger.debug("Running Faber now...")
            looper.run()
    else:
        return alice
Example #6
0
    def __init__(self,
                 basedirpath: str,
                 client: Client=None,
                 wallet: Wallet=None,
                 port: int=None):
        if not basedirpath:
            config = getConfig()
            basedirpath = basedirpath or os.path.expanduser(config.baseDir)

        super().__init__('Acme Corp', basedirpath, client, wallet, port)

        self._seqNos = {
            ("Job-Certificate", "0.1"): (None, None)
        }

        self._attributes = {
            "57fbf9dc8c8e6acde33de98c6d747b28c": {
                "employee_name": "Alice Garcia",
                "employee_status": "Permanent",
                "experience": "3 years",
                "salary_bracket": "between $50,000 to $100,000"
            },
            "3a2eb72eca8b404e8d412c5bf79f2640": {
                "employee_name": "Carol Atkinson",
                "employee_status": "Permanent",
                "experience": "2 years",
                "salary_bracket": "between $60,000 to $90,000"
            },
            "8513d1397e87cada4214e2a650f603eb": {
                "employee_name": "Frank Jeffrey",
                "employee_status": "Temporary",
                "experience": "4 years",
                "salary_bracket": "between $40,000 to $80,000"
            },
            "810b78be79f29fc81335abaa4ee1c5e8": {
                "employee_name": "Craig Richards",
                "employee_status": "On Contract",
                "experience": "3 years",
                "salary_bracket": "between $50,000 to $70,000"
            },
        }
Example #7
0
    def __init__(self,
                 basedirpath: str,
                 client: Client = None,
                 wallet: Wallet = None,
                 port: int = None):
        if not basedirpath:
            config = getConfig()
            basedirpath = basedirpath or os.path.expanduser(config.baseDir)

        super().__init__('Faber College', basedirpath, client, wallet, port)
        self._seqNos = {("Transcript", "1.2"): (None, None)}
        self._attributes = {
            "b1134a647eb818069c089e7694f63e6d": {
                "student_name": "Alice Garcia",
                "ssn": "123456789",
                "degree": "Bachelor of Science, Marketing",
                "year": "2015",
                "status": "graduated"
            },
            "2a2eb72eca8b404e8d412c5bf79f2640": {
                "student_name": "Carol Atkinson",
                "ssn": "783412695",
                "degree": "Bachelor of Science, Physics",
                "year": "2012",
                "status": "graduated"
            },
            "7513d1397e87cada4214e2a650f603eb": {
                "student_name": "Frank Jeffrey",
                "ssn": "996541211",
                "degree": "Bachelor of Arts, History",
                "year": "2013",
                "status": "dropped"
            },
            "710b78be79f29fc81335abaa4ee1c5e8": {
                "student_name": "Craig Richards",
                "ssn": "151445876",
                "degree": "MBA, Finance",
                "year": "2014",
                "status": "graduated"
            }
        }
Example #8
0
from anoncreds.protocol.types import SerFmt
from plenum.common.txn import NAME, VERSION, TYPE, IP, PORT, KEYS
from plenum.common.util import randomString
from plenum.test.eventually import eventually
from plenum.test.helper import genHa
from sovrin.client.wallet.cred_def import CredDef, IssuerPubKey
from sovrin.common.util import getConfig
from sovrin.test.helper import createNym, _newWallet

# noinspection PyUnresolvedReferences
from anoncreds.test.conftest import staticPrimes

# TODO Make a fixture for creating a client with a anon-creds features
#  enabled.

config = getConfig()


@pytest.fixture(scope="module")
def issuerWallet():
    return _newWallet()


@pytest.fixture(scope="module")
def proverWallet():
    return _newWallet()


@pytest.fixture(scope="module")
def verifierWallet():
    return _newWallet()
Example #9
0
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

    anonPluginFilePath = pluginsPath + "/anoncreds.py"
    anonPluginContent = "" \
                        "import importlib\n" \
                        "\n" \
                        "import anoncreds.protocol.issuer\n" \
                        "import anoncreds.protocol.verifier\n" \
                        "import anoncreds.protocol.prover\n" \
                        "\n" \
                        "import sovrin.anon_creds.issuer\n" \
                        "import sovrin.anon_creds.verifier\n"\
                        "import sovrin.anon_creds.prover\n" \
                        "\n" \
                        "Name = \"Anon creds\"\n" \
                        "Version = 1.1\n" \
                        "SovrinVersion = 1.1\n" \
                        "\n" \
                        "sovrin.anon_creds.issuer.Credential = anoncreds.protocol.types.Credential\n" \
                        "sovrin.anon_creds.issuer.AttribType = anoncreds.protocol.types.AttribType\n" \
                        "sovrin.anon_creds.issuer.AttribDef = anoncreds.protocol.types.AttribDef\n" \
                        "sovrin.anon_creds.issuer.Attribs = anoncreds.protocol.types.Attribs\n" \
                        "sovrin.anon_creds.issuer.AttrRepo = anoncreds.protocol.attribute_repo.AttrRepo\n" \
                        "sovrin.anon_creds.issuer.InMemoryAttrRepo = anoncreds.protocol.attribute_repo.InMemoryAttrRepo\n" \
                        "sovrin.anon_creds.issuer.Issuer = anoncreds.protocol.issuer.Issuer\n" \
                        "sovrin.anon_creds.prover.Prover = anoncreds.protocol.prover.Prover\n" \
                        "sovrin.anon_creds.verifier.Verifier = anoncreds.protocol.verifier.Verifier\n" \
                        "sovrin.anon_creds.proof_builder.ProofBuilder = anoncreds.protocol.proof_builder.ProofBuilder\n" \
                        "sovrin.anon_creds.proof_builder.Proof = anoncreds.protocol.types.Proof\n" \
                        "sovrin.anon_creds.cred_def.CredDef = anoncreds.protocol.credential_definition.CredentialDefinition\n" \

    modules_to_reload = ["sovrin.cli.cli"]
    test_modules_to_reload = [
        "sovrin.test.helper", "sovrin.test.cli.helper",
        "sovrin.test.anon_creds.conftest",
        "sovrin.test.anon_creds.test_anon_creds",
        # "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"

    anonPluginContent += reload_module_code
    with open(anonPluginFilePath, "a") as f:
        f.write(anonPluginContent)
Example #10
0
def gennedTdir(genesisTxns, tdir, domainTxnOrderedFields):
    config = getConfig(tdir)
    createGenesisTxnFile(genesisTxns, tdir, config.domainTransactionsFile,
                         domainTxnOrderedFields)
    return tdir
Example #11
0
def conf(tdir):
    return getConfig(tdir)
Example #12
0
 def _getOrientDbStore(self):
     config = getConfig()
     return OrientDbStore(user=config.OrientDB["user"],
                          password=config.OrientDB["password"],
                          dbName=self.name,
                          storageType=pyorient.STORAGE_TYPE_MEMORY)