Esempio n. 1
0
def clientFromSigner(signer, looper, nodeSet, tdir):
    wallet = Wallet(signer.identifier)
    wallet.addIdentifier(signer)
    s = genTestClient(nodeSet, tmpdir=tdir, identifier=signer.identifier)
    looper.add(s)
    looper.run(s.ensureConnectedToNodes())
    return s
Esempio n. 2
0
def addRole(looper, creatorClient, creatorWallet, name, useDid=True,
            addVerkey=True, role=None):
    wallet = Wallet(name)
    signer = DidSigner() if useDid else SimpleSigner()
    idr, _ = wallet.addIdentifier(signer=signer)
    verkey = wallet.getVerkey(idr) if addVerkey else None
    createNym(looper, idr, creatorClient, creatorWallet, verkey=verkey,
              role=role)
    return wallet
Esempio n. 3
0
def nonSponsor(looper, nodeSet, tdir):
    sseed = b'this is a secret sponsor seed...'
    signer = SimpleSigner(seed=sseed)
    c, _ = genTestClient(nodeSet, tmpdir=tdir, usePoolLedger=True)
    w = Wallet(c.name)
    w.addIdentifier(signer=signer)
    c.registerObserver(w.handleIncomingReply)
    looper.add(c)
    looper.run(c.ensureConnectedToNodes())
    return c, w
Esempio n. 4
0
def createNym(looper, nym, creatorClient, creatorWallet: Wallet, role=None):
    idy = Identity(identifier=nym, role=role)
    creatorWallet.addSponsoredIdentity(idy)
    reqs = creatorWallet.preparePending()
    creatorClient.submitReqs(*reqs)

    def check():
        assert creatorWallet._sponsored[nym].seqNo

    looper.run(eventually(check, timeout=2))
Esempio n. 5
0
def anotherSponsor(genned, steward, stewardWallet, tdir, looper):
    sseed = b'this is 1 secret sponsor seed...'
    signer = SimpleSigner(seed=sseed)
    c, _ = genTestClient(genned, tmpdir=tdir)
    w = Wallet(c.name)
    w.addSigner(signer=signer)
    c.registerObserver(w.handleIncomingReply)
    looper.add(c)
    looper.run(c.ensureConnectedToNodes())
    createNym(looper, signer.verstr, steward, stewardWallet, SPONSOR)
    return c, w
Esempio n. 6
0
def anotherSponsor(nodeSet, steward, stewardWallet, tdir, looper):
    sseed = b'this is 1 secret sponsor seed...'
    signer = SimpleSigner(seed=sseed)
    c, _ = genTestClient(nodeSet, tmpdir=tdir, usePoolLedger=True)
    w = Wallet(c.name)
    w.addIdentifier(signer=signer)
    c.registerObserver(w.handleIncomingReply)
    looper.add(c)
    looper.run(c.ensureConnectedToNodes())
    createNym(looper, signer.identifier, steward, stewardWallet,
              role=SPONSOR, verkey=signer.verkey)
    return c, w
Esempio n. 7
0
def testNonSponsoredNymCanDoGetNym(nodeSet, addedSponsor, sponsorWallet, tdir,
                                   looper):
    signer = SimpleSigner()
    someClient, _ = genTestClient(nodeSet, tmpdir=tdir, usePoolLedger=True)
    wallet = Wallet(someClient.name)
    wallet.addIdentifier(signer=signer)
    someClient.registerObserver(wallet.handleIncomingReply)
    looper.add(someClient)
    looper.run(someClient.ensureConnectedToNodes())
    needle = sponsorWallet.defaultId
    makeGetNymRequest(someClient, wallet, needle)
    looper.run(eventually(someClient.hasNym, needle, retryWait=1, timeout=5))
Esempio n. 8
0
def testCredDefSecretKey(tdir, staticPrimes):
    GVT = issuer.AttribDef('gvt', [
        issuer.AttribType('name', encode=True),
        issuer.AttribType('age', encode=False),
        issuer.AttribType('sex', encode=True)
    ])
    sprimes = staticPrimes["prime1"]
    # sk = CredDefSecretKey(*sprimes)
    sk = CredDefSecretKey(*sprimes)
    cd = cred_def.CredDef(322324, GVT.attribNames())

    wallet = Wallet("testWallet")
    # cdsk = CredDefSk(name, version, serializedSk)
    wallet.addCredDefSk(str(sk))
    stored = wallet.getCredDefSk(CredDefKey(name, version))
    assert serializedSk == stored.secretKey
Esempio n. 9
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
Esempio n. 10
0
 def addTxnsForCompletedRequestsInWallet(self, reqs: Iterable,
                                         wallet: Wallet):
     for req in reqs:
         reply, status = self.client.getReply(req.reqId)
         if status == "CONFIRMED":
             # TODO Figure out the actual implementation of
             # TODO     `buildCompletedTxnFromReply`. This is just a stub
             # TODO     implementation
             txn = buildCompletedTxnFromReply(req, reply)
             # TODO Move this logic in wallet
             if txn['txnType'] == ATTRIB and txn['data'] is not None:
                 attr = list(txn['data'].keys())[0]
                 if attr in wallet.attributeEncKeys:
                     key = wallet.attributeEncKeys.pop(attr)
                     txn['secretKey'] = key
             wallet.addCompletedTxn(txn)
Esempio n. 11
0
 def __init__(self,
              name: str,
              basedirpath: str,
              client: Client = None,
              wallet: Wallet = None,
              port: int = None):
     super().__init__(name, basedirpath, client, port)
     self._wallet = wallet or Wallet(name)
     obs = self._wallet.handleIncomingReply
     if not self.client.hasObserver(obs):
         self.client.registerObserver(obs)
     self._wallet.pendSyncRequests()
     prepared = self._wallet.preparePending()
     self.client.submitReqs(*prepared)
     self.loop = asyncio.get_event_loop()
     self.msgHandlers = {
         ERROR: self._handleError,
         AVAIL_CLAIM_LIST: self._handleAcceptInviteResponse,
         CLAIMS: self._handleReqClaimResponse,
         ACCEPT_INVITE: self._acceptInvite,
         REQUEST_CLAIM_ATTRS: self._returnClaimAttrs,
         REQUEST_CLAIM: self._reqClaim,
         CLAIM_ATTRS: self._handleClaimAttrs,
         EVENT: self._eventHandler
     }
Esempio n. 12
0
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)
Esempio n. 13
0
def testNewKeyChangesWalletsDefaultId(be, do, poolNodesStarted,
                                      aliceCLI, connectedToTest):
    mywallet = Wallet('my wallet')
    keyseed='a'*32
    idr, _ = mywallet.addIdentifier(seed=keyseed.encode("utf-8"))

    be(aliceCLI)

    do('connect test', within=3, expect=connectedToTest)

    do('new key with seed {}'.format(keyseed))

    do('send NYM dest={}'.format(idr))

    do('new key with seed 11111111111111111111111111111111')

    do('send NYM dest={}'.format(idr),
       within=3,
       expect=["Nym {} added".format(idr)]
    )
Esempio n. 14
0
def genesisTxns(stewardWallet: Wallet):
    nym = stewardWallet.defaultId
    return [
        {
            TXN_TYPE: NYM,
            TARGET_NYM: nym,
            TXN_ID:
            "9c86b273ff34fce19d6b804eff5a3f5747ada4eaa22f1d49c01e52ddb7875b4b",
            ROLE: STEWARD,
            VERKEY: stewardWallet.getVerkey()
        },
    ]
Esempio n. 15
0
 def __init__(self,
              name: str,
              basedirpath: str,
              client: Client = None,
              wallet: Wallet = None,
              port: int = None,
              loop=None,
              attrRepo=None):
     Agent.__init__(self, name, basedirpath, client, port, loop=loop)
     self._wallet = wallet or Wallet(name)
     self._attrRepo = attrRepo or AttributeRepoInMemory()
     Walleted.__init__(self)
     if self.client:
         self._initIssuerProverVerifier()
Esempio n. 16
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
Esempio n. 17
0
def stewardWallet(poolTxnStewardData):
    name, sigseed = poolTxnStewardData
    wallet = Wallet('steward')
    signer = SimpleSigner(seed=sigseed)
    wallet.addIdentifier(signer=signer)
    return wallet
Esempio n. 18
0
def sponsorWallet():
    wallet = Wallet('sponsor')
    seed = b'sponsors are people too.........'
    wallet.addIdentifier(seed=seed)
    return wallet
Esempio n. 19
0
def clientAndWallet1(client1Signer, looper, nodeSet, tdir, up):
    client, wallet = genTestClient(nodeSet, tmpdir=tdir, usePoolLedger=True)
    wallet = Wallet(client.name)
    wallet.addIdentifier(signer=client1Signer)
    return client, wallet
Esempio n. 20
0
 def _(name):
     wallet = Wallet(name)
     wallet.addIdentifier(signer=DidSigner())
     return wallet
Esempio n. 21
0
def testGetAttribute(nodeSet, addedSponsor, sponsorWallet: Wallet, sponsor,
                     userIdA, addedRawAttribute, attributeData):
    assert attributeData in [
        a.value for a in sponsorWallet.getAttributesForNym(userIdA)
    ]
Esempio n. 22
0
def testAnonCredFlow(genned, looper, tdir, nodeSet, issuerWallet: Wallet,
                     proverWallet: Wallet, verifierWallet, addedIPV):

    # Don't move the following import outside of this method, otherwise that
    # client class doesn't gets reloaded and it doesn't get updated with the
    # correct plugin class/methods and it gives an error.
    # (for permanent solution bug is created: #130181205)
    from sovrin.test.helper import genTestClient

    BYU = IssuerModule.AttribDef('BYU', [
        IssuerModule.AttribType("first_name", encode=True),
        IssuerModule.AttribType("last_name", encode=True),
        IssuerModule.AttribType("birth_date", encode=True),
        IssuerModule.AttribType("expire_date", encode=True),
        IssuerModule.AttribType("undergrad", encode=True),
        IssuerModule.AttribType("postgrad", encode=True)
    ])

    setupLogging(DISPLAY_LOG_LEVEL, Console.Wordage.mute)
    logger = getlogger("test_anon_creds")
    logging.root.addHandler(DemoHandler(partial(out, logger)))
    logging.root.handlers = []

    attributes = BYU.attribs(first_name="John",
                             last_name="Doe",
                             birth_date="1970-01-01",
                             expire_date="2300-01-01",
                             undergrad="True",
                             postgrad="False")

    attrNames = tuple(attributes.keys())
    # 3 Sovrin clients acting as Issuer, Signer and Verifier
    issuerC, _ = genTestClient(nodeSet, tmpdir=tdir, peerHA=genHa())
    proverC, _ = genTestClient(nodeSet, tmpdir=tdir, peerHA=genHa())
    verifierC, _ = genTestClient(nodeSet, tmpdir=tdir, peerHA=genHa())

    looper.add(issuerC)
    looper.add(proverC)
    looper.add(verifierC)
    looper.run(issuerC.ensureConnectedToNodes(),
               proverC.ensureConnectedToNodes(),
               verifierC.ensureConnectedToNodes())
    makePendingTxnsRequest(issuerC, issuerWallet)
    makePendingTxnsRequest(proverC, proverWallet)
    makePendingTxnsRequest(verifierC, verifierWallet)
    # Adding signers
    # issuer.signers[issuerSigner.identifier] = issuerSigner
    logger.display("Key pair for Issuer created \n"
                   "Public key is {} \n"
                   "Private key is stored on disk\n".format(
                       issuerWallet.defaultId))
    # prover.signers[proverSigner.identifier] = proverSigner
    logger.display("Key pair for Prover created \n"
                   "Public key is {} \n"
                   "Private key is stored on disk\n".format(
                       proverWallet.defaultId))
    # verifier.signers[verifierSigner.identifier] = verifierSigner
    logger.display("Key pair for Verifier created \n"
                   "Public key is {} \n"
                   "Private key is stored on disk\n".format(
                       verifierWallet.defaultId))

    # TODO BYU.name is used here instead of issuerSigner.identifier due to
    #  tight coupling in Attribs.encoded()
    issuerId = BYU.name
    proverId = proverWallet.defaultId
    # Issuer's attribute repository
    attrRepo = IssuerModule.InMemoryAttrRepo()
    attrRepo.attributes = {proverId: attributes}

    name1 = "Qualifications"
    version1 = "1.0"
    ip = issuerC.peerHA[0]
    port = issuerC.peerHA[1]
    interactionId = 'LOGIN-1'

    # This is the issuer entity
    issuer = IssuerModule.Issuer(issuerId, attrRepo)
    # issuer.attributeRepo = attrRepo
    # Issuer publishes credential definition to Sovrin ledger

    csk = CredDefSecretKey(*staticPrimes().get("prime1"))
    cskId = issuerWallet.addCredDefSk(str(csk))
    credDef = CredDef(seqNo=None,
                      attrNames=attrNames,
                      name=name1,
                      version=version1,
                      origin=issuerWallet.defaultId,
                      secretKey=cskId)
    # credDef = issuer.addNewCredDef(attrNames, name1, version1,
    #                                p_prime="prime1", q_prime="prime1", ip=ip,
    #                                port=port)
    # issuer.credentialDefinitions = {(name1, version1): credDef}
    logger.display("Issuer: Creating version {} of credential definition"
                   " for {}".format(version1, name1))
    print("Credential definition: ")
    pprint.pprint(credDef.get())  # Pretty-printing the big object.
    pending = issuerWallet.addCredDef(credDef)
    reqs = issuerWallet.preparePending()
    # op = {TXN_TYPE: CRED_DEF,
    #       DATA: getCredDefTxnData(credDef)}
    logger.display("Issuer: Writing credential definition to "
                   "Sovrin Ledger...")
    issuerC.submitReqs(*reqs)

    def chk():
        assert issuerWallet.getCredDef(
            (name1, version1, issuerWallet.defaultId)).seqNo is not None

    looper.run(eventually(chk, retryWait=.1, timeout=30))

    # submitAndCheck(looper, issuerC, issuerWallet, op)

    # Prover requests Issuer for credential (out of band)
    logger.display("Prover: Requested credential from Issuer")
    # Issuer issues a credential for prover
    logger.display("Issuer: Creating credential for "
                   "{}".format(proverWallet.defaultId))

    encodedAttributes = attributes.encoded()
    revealedAttrs = ["undergrad"]

    prover = ProverModule.Prover(proverId)
    pk = {issuerId: prover.getPk(credDef)}
    proofBuilder = ProofBuilderModule.ProofBuilder(pk)
    proofId = proofBuilder.id
    prover.proofBuilders[proofId] = proofBuilder
    cred = issuer.createCred(proverId, name1, version1,
                             proofBuilder.U[issuerId])
    logger.display("Prover: Received credential from "
                   "{}".format(issuerWallet.defaultId))

    # Prover intends to prove certain attributes to a Verifier
    # Verifier issues a nonce
    logger.display("Prover: Requesting Nonce from verifier…")
    logger.display("Verifier: Nonce received from prover"
                   " {}".format(proverId))

    verifierId = verifierWallet.defaultId
    verifier = VerifierModule.Verifier(verifierId)
    nonce = verifier.generateNonce(interactionId)
    logger.display("Verifier: Nonce sent.")
    logger.display("Prover: Nonce received")

    presentationToken = {
        issuerId: (cred[0], cred[1], proofBuilder.vprime[issuerId] + cred[2])
    }
    # Prover discovers Issuer's credential definition
    logger.display("Prover: Preparing proof for attributes: "
                   "{}".format(revealedAttrs))
    proofBuilder.setParams(presentationToken, revealedAttrs, nonce)
    prf = ProofBuilderModule.ProofBuilder.prepareProof(
        credDefPks=proofBuilder.credDefPks,
        masterSecret=proofBuilder.masterSecret,
        creds=presentationToken,
        encodedAttrs=encodedAttributes,
        revealedAttrs=revealedAttrs,
        nonce=nonce)
    logger.display("Prover: Proof prepared.")
    logger.display("Prover: Proof submitted")
    logger.display("Verifier: Proof received.")
    logger.display("Verifier: Looking up Credential Definition"
                   " on Sovrin Ledger...")

    # Verifier fetches the credential definition from ledger
    verifier.credentialDefinitions = {(issuerId, name1, version1): credDef}
    verified = VerifierModule.Verifier.verifyProof(pk, prf, nonce,
                                                   attributes.encoded(),
                                                   revealedAttrs)
    # Verifier verifies proof
    logger.display("Verifier: Verifying proof...")
    logger.display("Verifier: Proof verified.")
    assert verified
    logger.display("Prover: Proof accepted.")
Esempio n. 23
0
def buildAgentWallet(name, seed):
    wallet = Wallet(name)
    wallet.addIdentifier(signer=SimpleSigner(seed=seed))
    return wallet
Esempio n. 24
0
def wallet():
    return Wallet('my wallet')
Esempio n. 25
0
def _newWallet(name=None):
    signer = SimpleSigner()
    w = Wallet(name or signer.identifier)
    w.addIdentifier(signer=signer)
    return w
Esempio n. 26
0
def faberWallet():
    name = "FaberCollege"
    wallet = Wallet(name)
    return wallet
Esempio n. 27
0
def aliceWallet():
    name = "Alice"
    wallet = Wallet(name)
    return wallet
Esempio n. 28
0
 def __init__(self, client=None):
     self.client = client
     self.wallet = Wallet(self.client)  # created only once per organization
     self.userWallets = {}  # type: Dict[str, Wallet]
Esempio n. 29
0
def stewardWallet():
    wallet = Wallet('steward')
    seed = b'is a pit   seed, or somepin else'
    wallet.addSigner(seed=seed)
    assert wallet.defaultId == 'LRtO/oin94hzKKCVG4GOG1eMuH7uVMJ3txDUHBX2BqY='
    return wallet
Esempio n. 30
0
def acmeWallet():
    name = "Acme"
    wallet = Wallet(name)
    return wallet