Пример #1
0
def testRaetPreSharedKeysNonPromiscous(tdir):

    alphaSigner = SimpleSigner()
    betaSigner = SimpleSigner()

    alphaPrivateer = Privateer()
    betaPrivateer = Privateer()

    logger.debug("Alpha's verkey {}".format(alphaSigner.verkey))
    logger.debug("Beta's verkey {}".format(betaSigner.verkey))

    alpha = RoadStack(name='alpha',
                      ha=genHa(),
                      sigkey=alphaSigner.naclSigner.keyhex,
                      prikey=alphaPrivateer.keyhex,
                      auto=AutoMode.never,
                      basedirpath=tdir)

    beta = RoadStack(name='beta',
                     ha=genHa(),
                     sigkey=betaSigner.naclSigner.keyhex,
                     prikey=betaPrivateer.keyhex,
                     main=True,
                     auto=AutoMode.never,
                      basedirpath=tdir)

    alpha.keep.dumpRemoteRoleData({
        "acceptance": Acceptance.accepted.value,
        "verhex": betaSigner.verkey,
        "pubhex": betaPrivateer.pubhex
    }, "beta")

    beta.keep.dumpRemoteRoleData({
        "acceptance": Acceptance.accepted.value,
        "verhex": alphaSigner.verkey,
        "pubhex": alphaPrivateer.pubhex
    }, "alpha")

    try:

        betaRemote = raet.road.estating.RemoteEstate(stack=alpha,
                                                     ha=beta.ha)

        alpha.addRemote(betaRemote)

        alpha.allow(uid=betaRemote.uid, cascade=True)

        handshake(alpha, beta)

        sendMsgs(alpha, beta, betaRemote)
    finally:
        cleanup(alpha, beta)
Пример #2
0
def testRaetPreSharedKeysNonPromiscous(tdir):
    alphaSigner = SimpleSigner()
    betaSigner = SimpleSigner()

    alphaPrivateer = Privateer()
    betaPrivateer = Privateer()

    logger.debug("Alpha's verkey {}".format(alphaSigner.naclSigner.verhex))
    logger.debug("Beta's verkey {}".format(betaSigner.naclSigner.verhex))

    alpha = RoadStack(name='alpha',
                      ha=genHa(),
                      sigkey=alphaSigner.naclSigner.keyhex,
                      prikey=alphaPrivateer.keyhex,
                      auto=AutoMode.never,
                      basedirpath=tdir)

    beta = RoadStack(name='beta',
                     ha=genHa(),
                     sigkey=betaSigner.naclSigner.keyhex,
                     prikey=betaPrivateer.keyhex,
                     main=True,
                     auto=AutoMode.never,
                     basedirpath=tdir)

    alpha.keep.dumpRemoteRoleData(
        {
            "acceptance": Acceptance.accepted.value,
            "verhex": betaSigner.naclSigner.verhex,
            "pubhex": betaPrivateer.pubhex
        }, "beta")

    beta.keep.dumpRemoteRoleData(
        {
            "acceptance": Acceptance.accepted.value,
            "verhex": alphaSigner.naclSigner.verhex,
            "pubhex": alphaPrivateer.pubhex
        }, "alpha")

    try:

        betaRemote = RemoteEstate(stack=alpha, ha=beta.ha)

        alpha.addRemote(betaRemote)

        alpha.allow(uid=betaRemote.uid, cascade=True)

        handshake(alpha, beta)

        sendMsgs(alpha, beta, betaRemote)
    finally:
        cleanup(alpha, beta)
Пример #3
0
def addNewStewardAndNode(looper,
                         creatorClient,
                         creatorWallet,
                         stewardName,
                         newNodeName,
                         tdir,
                         tconf,
                         allPluginsPath=None,
                         autoStart=True):
    newStewardWallet = addNewClient(STEWARD, looper, creatorClient,
                                    creatorWallet, stewardName)
    newSteward = TestClient(
        name=stewardName,
        nodeReg=None,
        ha=genHa(),
        # DEPR
        # signer=newStewardSigner,
        basedirpath=tdir)

    looper.add(newSteward)
    looper.run(newSteward.ensureConnectedToNodes())
    newNode = addNewNode(looper,
                         newSteward,
                         newStewardWallet,
                         newNodeName,
                         tdir,
                         tconf,
                         allPluginsPath,
                         autoStart=autoStart)
    return newSteward, newStewardWallet, newNode
Пример #4
0
def nodeRegsForCLI():
    nodeNames = ['Alpha', 'Beta', 'Gamma', 'Delta']
    has = [genHa(2) for _ in nodeNames]
    nodeNamesC = [n + 'C' for n in nodeNames]
    nodeReg = OrderedDict((n, has[i][0]) for i, n in enumerate(nodeNames))
    cliNodeReg = OrderedDict((n, has[i][1]) for i, n in enumerate(nodeNamesC))
    return adict(nodeReg=nodeReg, cliNodeReg=cliNodeReg)
def testAddNewClient(txnPoolNodeSet, tdirWithPoolTxns,
                     poolTxnStewardData, txnPoolCliNodeReg):
    with Looper(debug=True) as looper:
        name, pkseed, sigseed = poolTxnStewardData
        stewardSigner = SimpleSigner(seed=sigseed)
        client = TestClient(name=name, nodeReg=txnPoolCliNodeReg, ha=genHa(),
                            signer=stewardSigner, basedirpath=tdirWithPoolTxns)
        looper.add(client)
        looper.run(client.ensureConnectedToNodes())
        sigseed = b'55555555555555555555555555555555'
        pkseed = b'66666666666666666666666666666666'
        newSigner = SimpleSigner(sigseed)
        priver = Privateer(pkseed)
        req, = client.submit({
            TXN_TYPE: NEW_CLIENT,
            ORIGIN: client.defaultIdentifier,
            TARGET_NYM: newSigner.verstr,
            DATA: {
                "pubkey": priver.pubhex.decode(),
                "alias": "Robert"
            }
        })

        looper.run(eventually(checkSufficientRepliesRecvd, client.inBox,
                              req.reqId, 1,
                              retryWait=1, timeout=5))

        def chk():
            for node in txnPoolNodeSet:
                assert newSigner.verstr in node.clientAuthNr.clients

        looper.run(eventually(chk, retryWait=1, timeout=5))
Пример #6
0
def nodeRegsForCLI():
    nodeNames = ['Alpha', 'Beta', 'Gamma', 'Delta']
    has = [genHa(2) for _ in nodeNames]
    nodeNamesC = [n + 'C' for n in nodeNames]
    nodeReg = OrderedDict((n, has[i][0]) for i, n in enumerate(nodeNames))
    cliNodeReg = OrderedDict((n, has[i][1]) for i, n in enumerate(nodeNamesC))
    return adict(nodeReg=nodeReg, cliNodeReg=cliNodeReg)
Пример #7
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
def testNodesReceiveClientMsgs(txnPoolNodeSet, tdirWithPoolTxns,
                               poolTxnClientData, txnPoolCliNodeReg):

    with Looper(debug=True) as looper:
        name, pkseed, sigseed = poolTxnClientData
        signer = SimpleSigner(seed=sigseed)
        client = TestClient(name=name, nodeReg=txnPoolCliNodeReg, ha=genHa(),
                            signer=signer, basedirpath=tdirWithPoolTxns)
        looper.add(client)
        looper.run(client.ensureConnectedToNodes())
        sendReqsToNodesAndVerifySuffReplies(looper, client, 1)
Пример #9
0
def testNodesReceiveClientMsgs(txnPoolNodeSet, tdirWithPoolTxns,
                               poolTxnClientData, txnPoolCliNodeReg):

    with Looper(debug=True) as looper:
        name, pkseed, sigseed = poolTxnClientData
        signer = SimpleSigner(seed=sigseed)
        client = TestClient(name=name,
                            nodeReg=txnPoolCliNodeReg,
                            ha=genHa(),
                            signer=signer,
                            basedirpath=tdirWithPoolTxns)
        looper.add(client)
        looper.run(client.ensureConnectedToNodes())
        sendReqsToNodesAndVerifySuffReplies(looper, client, 1)
Пример #10
0
def testPromiscuousConnection(tdir):
    alpha = RoadStack(name='alpha',
                      ha=genHa(),
                      auto=AutoMode.always,
                      basedirpath=tdir)

    beta = RoadStack(name='beta',
                     ha=genHa(),
                     main=True,
                     auto=AutoMode.always,
                     basedirpath=tdir)

    try:
        betaRemote = RemoteEstate(stack=alpha, ha=beta.ha)
        alpha.addRemote(betaRemote)

        alpha.join(uid=betaRemote.uid, cascade=True)

        handshake(alpha, beta)

        sendMsgs(alpha, beta, betaRemote)
    finally:
        cleanup(alpha, beta)
Пример #11
0
def testRaetPreSharedKeysPromiscous(tdir):

    alphaSigner = SimpleSigner()
    betaSigner = SimpleSigner()

    logger.debug("Alpha's verkey {}".format(alphaSigner.verkey))
    logger.debug("Beta's verkey {}".format(betaSigner.verkey))

    alpha = RoadStack(name='alpha',
                      ha=genHa(),
                      sigkey=alphaSigner.naclSigner.keyhex,
                      auto=AutoMode.always,
                      basedirpath=tdir)

    beta = RoadStack(name='beta',
                     ha=genHa(),
                     sigkey=betaSigner.naclSigner.keyhex,
                     main=True,
                     auto=AutoMode.always,
                      basedirpath=tdir)

    try:

        betaRemote = raet.road.estating.RemoteEstate(stack=alpha,
                                                     ha=beta.ha,
                                                     verkey=betaSigner.verkey)

        alpha.addRemote(betaRemote)

        alpha.allow(uid=betaRemote.uid, cascade=True)

        handshake(alpha, beta)

        sendMsgs(alpha, beta, betaRemote)

    finally:
        cleanup(alpha, beta)
Пример #12
0
def testPromiscuousConnection(tdir):
    alpha = RoadStack(name='alpha',
                      ha=genHa(),
                      auto=AutoMode.always,
                      basedirpath=tdir)

    beta = RoadStack(name='beta',
                     ha=genHa(),
                     main=True,
                     auto=AutoMode.always,
                      basedirpath=tdir)

    try:
        betaRemote = raet.road.estating.RemoteEstate(stack=alpha,
                                                     ha=beta.ha)
        alpha.addRemote(betaRemote)

        alpha.join(uid=betaRemote.uid, cascade=True)

        handshake(alpha, beta)

        sendMsgs(alpha, beta, betaRemote)
    finally:
        cleanup(alpha, beta)
Пример #13
0
def testRaetPreSharedKeysPromiscous(tdir):
    alphaSigner = SimpleSigner()
    betaSigner = SimpleSigner()

    logger.debug("Alpha's verkey {}".format(alphaSigner.naclSigner.verhex))
    logger.debug("Beta's verkey {}".format(betaSigner.naclSigner.verhex))

    alpha = RoadStack(name='alpha',
                      ha=genHa(),
                      sigkey=alphaSigner.naclSigner.keyhex,
                      auto=AutoMode.always,
                      basedirpath=tdir)

    beta = RoadStack(name='beta',
                     ha=genHa(),
                     sigkey=betaSigner.naclSigner.keyhex,
                     main=True,
                     auto=AutoMode.always,
                     basedirpath=tdir)

    try:

        betaRemote = RemoteEstate(stack=alpha,
                                  ha=beta.ha,
                                  verkey=betaSigner.naclSigner.verhex)

        alpha.addRemote(betaRemote)

        alpha.allow(uid=betaRemote.uid, cascade=True)

        handshake(alpha, beta)

        sendMsgs(alpha, beta, betaRemote)

    finally:
        cleanup(alpha, beta)
Пример #14
0
def addNewNode(looper,
               stewardClient,
               stewardWallet,
               newNodeName,
               tdir,
               tconf,
               allPluginsPath=None,
               autoStart=True):
    sigseed = randomString(32).encode()
    nodeSigner = SimpleSigner(seed=sigseed)

    (nodeIp, nodePort), (clientIp, clientPort) = genHa(2)

    op = {
        TXN_TYPE: NEW_NODE,
        TARGET_NYM: nodeSigner.identifier,
        DATA: {
            NODE_IP: nodeIp,
            NODE_PORT: nodePort,
            CLIENT_IP: clientIp,
            CLIENT_PORT: clientPort,
            ALIAS: newNodeName
        }
    }

    req = stewardWallet.signOp(op)
    stewardClient.submitReqs(req)

    nodeCount = len(stewardClient.nodeReg)
    looper.run(
        eventually(checkSufficientRepliesRecvd,
                   stewardClient.inBox,
                   req.reqId,
                   1,
                   retryWait=1,
                   timeout=3 * nodeCount))
    initLocalKeep(newNodeName, tdir, sigseed, override=True)
    node = TestNode(newNodeName,
                    basedirpath=tdir,
                    config=tconf,
                    ha=(nodeIp, nodePort),
                    cliha=(clientIp, clientPort),
                    pluginPaths=allPluginsPath)
    if autoStart:
        looper.add(node)
    return node
Пример #15
0
def testAddNewClient(txnPoolNodeSet, tdirWithPoolTxns, poolTxnStewardData,
                     txnPoolCliNodeReg):
    with Looper(debug=True) as looper:
        name, pkseed, sigseed = poolTxnStewardData
        stewardSigner = SimpleSigner(seed=sigseed)
        client = TestClient(name=name,
                            nodeReg=txnPoolCliNodeReg,
                            ha=genHa(),
                            signer=stewardSigner,
                            basedirpath=tdirWithPoolTxns)
        looper.add(client)
        looper.run(client.ensureConnectedToNodes())
        sigseed = b'55555555555555555555555555555555'
        pkseed = b'66666666666666666666666666666666'
        newSigner = SimpleSigner(sigseed)
        priver = Privateer(pkseed)
        req, = client.submit({
            TXN_TYPE: NEW_CLIENT,
            ORIGIN: client.defaultIdentifier,
            TARGET_NYM: newSigner.verstr,
            DATA: {
                "pubkey": priver.pubhex.decode(),
                "alias": "Robert"
            }
        })

        looper.run(
            eventually(checkSufficientRepliesRecvd,
                       client.inBox,
                       req.reqId,
                       1,
                       retryWait=1,
                       timeout=5))

        def chk():
            for node in txnPoolNodeSet:
                assert newSigner.verstr in node.clientAuthNr.clients

        looper.run(eventually(chk, retryWait=1, timeout=5))
Пример #16
0
def verifierHA():
    return genHa()
Пример #17
0
def proverHA():
    return genHa()
Пример #18
0
def issuerHA():
    return genHa()
Пример #19
0
from ioflo.aid import getConsole

from plenum.common.looper import Looper
from plenum.common.util import getlogger
from plenum.server.node import Node
from plenum.test.helper import checkNodesConnected, checkProtocolInstanceSetup, \
    genHa, TestNode
from plenum.test.testing_utils import PortDispenser

logger = getlogger()

whitelist = ['discarding message', 'found legacy entry']

nodeReg = {
    'Alpha': (genHa(2)[0],),
    'Beta': (genHa(2)[0],),
    'Gamma': (genHa(2)[0],),
    'Delta': (genHa(2)[0],)}


def testNodesConnectsWhenOneNodeIsLate():
    with TemporaryDirectory() as td:
        with Looper() as looper:
            nodes = []
            names = list(nodeReg.keys())
            logger.debug("Node names: {}".format(names))

            def create(name):
                node = TestNode(name, nodeReg, basedirpath=td)
                looper.add(node)
Пример #20
0
from ioflo.aid import getConsole

from plenum.common.looper import Looper
from plenum.common.util import getlogger
from plenum.server.node import Node
from plenum.test.helper import checkNodesConnected, checkProtocolInstanceSetup, \
    genHa, TestNode
from plenum.test.testing_utils import PortDispenser

logger = getlogger()

whitelist = ['discarding message', 'found legacy entry']

nodeReg = {
    'Alpha': (genHa(2)[0], ),
    'Beta': (genHa(2)[0], ),
    'Gamma': (genHa(2)[0], ),
    'Delta': (genHa(2)[0], )
}


def testNodesConnectsWhenOneNodeIsLate():
    with TemporaryDirectory() as td:
        with Looper() as looper:
            nodes = []
            names = list(nodeReg.keys())
            logger.debug("Node names: {}".format(names))

            def create(name):
                node = TestNode(name, nodeReg, basedirpath=td)
Пример #21
0
def runAnonCredFlow():
    # 3 Sovrin clients acting as Issuer, Signer and Verifier
    issuerC, _ = genTestClient(nodes, tmpdir=tdir, peerHA=genHa())
    proverC, _ = genTestClient(nodes, tmpdir=tdir, peerHA=genHa())
    verifierC, _ = genTestClient(nodes, tmpdir=tdir, peerHA=genHa())

    looper.add(issuerC)
    looper.add(proverC)
    looper.add(verifierC)
    looper.run(issuerC.ensureConnectedToNodes(),
               proverC.ensureConnectedToNodes(),
               verifierC.ensureConnectedToNodes())
    # Adding signers
    # issuer.signers[issuerWallet.defaultId] = 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[proverWallet.defaultId] = proverSigner
    input()
    logger.display("Key pair for Prover created \n"
                   "Public key is {} \n"
                   "Private key is stored on disk\n".format(
                       proverWallet.defaultId))
    # verifier.signers[verifierWallet.defaultId] = verifierSigner
    input()
    logger.display("Key pair for Verifier created \n"
                   "Public key is {} \n"
                   "Private key is stored on disk\n".format(
                       verifierWallet.defaultId))

    # Issuer's attribute repository
    attrRepo = InMemoryAttrRepo()
    attrRepo.attributes = {proverWallet.defaultId: attributes}
    # issuer.attributeRepo = attrRepo
    name1 = "Qualifications"
    version1 = "1.0"
    ip = issuerC.peerHA[0]
    port = issuerC.peerHA[1]
    issuerId = issuerWallet.defaultId
    proverId = proverWallet.defaultId
    verifierId = verifierWallet.defaultId
    interactionId = 'LOGIN-1'

    issuer = IssuerModule.Issuer(issuerId, attrRepo)
    # Issuer publishes credential definition to Sovrin ledger
    credDef = issuer.addNewCredDef(attrNames,
                                   name1,
                                   version1,
                                   ip=ip,
                                   port=port)
    # issuer.credentialDefinitions = {(name1, version1): credDef}
    input()
    logger.display("Issuer: Creating version {} of credential definition"
                   " for {}".format(version1, name1))
    print("Credential definition: ")
    pprint.pprint(credDef.get())  # Pretty-printing the big object.
    input()
    op = {
        ORIGIN: issuerWallet.defaultId,
        TXN_TYPE: CRED_DEF,
        DATA: getCredDefTxnData(credDef)
    }
    logger.display("Issuer: Writing credential definition to "
                   "Sovrin Ledger...")
    submitAndCheck(looper, issuer, op, identifier=issuerWallet.defaultId)

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

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

    # Prover intends to prove certain attributes to a Verifier
    # Verifier issues a nonce
    input()
    logger.display("Prover: Requesting Nonce from verifier…")
    verifier = VerifierModule.Verifier(verifierId)
    logger.display("Verifier: Nonce received from prover"
                   " {}".format(proverId))
    nonce = verifier.generateNonce(interactionId)
    input()
    logger.display("Verifier: Nonce sent.")
    input()
    logger.display("Prover: Nonce received")
    prover.proofBuilders[proofBuilder.id]['nonce'] = nonce

    # Prover discovers Issuer's credential definition
    prover.credentialDefinitions = {(issuerId, attrNames): credDef}
    revealedAttrs = ["undergrad"]
    input()
    logger.display("Prover: Preparing proof for attributes: "
                   "{}".format(revealedAttrs))
    proofBuilder.setParams(encodedAttributes, revealedAttrs, nonce)
    prf = proofBuilder.prepareProof()
    logger.display("Prover: Proof prepared.")
    logger.display("Prover: Proof submitted")
    input()
    logger.display("Verifier: Proof received.")
    input()
    logger.display("Verifier: Looking up Credential Definition"
                   " on Sovrin Ledger...")
    prover.proofs[proofBuilder.id] = proofBuilder

    # Verifier fetches the credential definition from ledger
    verifier.credentialDefinitions = {(issuerId, name1, version1): credDef}
    # Verifier verifies proof
    logger.display("Verifier: Verifying proof...")
    verified = Verifier.verifyProof(pk, prf, nonce, encodedAttributes,
                                    revealedAttrs)
    input()
    logger.display("Verifier: Proof verified.")
    assert verified
    input()
    logger.display("Prover: Proof accepted.")
Пример #22
0
sponsor, _ = genTestClient(nodes, tmpdir=tdir)
sponsor.registerObserver(sponsorWallet.handleIncomingReply)
# whitelistClient(nodes, sponsor.name)
looper.add(sponsor)
looper.run(sponsor.ensureConnectedToNodes())
makePendingTxnsRequest(sponsor, sponsorWallet)

iNym = issuerWallet.defaultId
pNym = proverWallet.defaultId
vNym = verifierWallet.defaultId

for nym in (iNym, pNym, vNym):
    createNym(looper, nym, sponsor, sponsorWallet)

issuerHA = genHa()
proverHA = genHa()
verifierHA = genHa()


def runAnonCredFlow():
    # 3 Sovrin clients acting as Issuer, Signer and Verifier
    issuerC, _ = genTestClient(nodes, tmpdir=tdir, peerHA=genHa())
    proverC, _ = genTestClient(nodes, tmpdir=tdir, peerHA=genHa())
    verifierC, _ = genTestClient(nodes, tmpdir=tdir, peerHA=genHa())

    looper.add(issuerC)
    looper.add(proverC)
    looper.add(verifierC)
    looper.run(issuerC.ensureConnectedToNodes(),
               proverC.ensureConnectedToNodes(),
Пример #23
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.")
Пример #24
0
from ioflo.aid import getConsole

from plenum.common.looper import Looper
from plenum.common.util import getlogger
from plenum.server.node import Node
from plenum.test.helper import checkNodesConnected, checkProtocolInstanceSetup, \
    genHa
from plenum.test.testing_utils import PortDispenser

logger = getlogger()

whitelist = ['discarding message', 'found legacy entry']

nodeReg = {
    'Alpha': genHa(2)[0],
    'Beta': genHa(2)[0],
    'Gamma': genHa(2)[0],
    'Delta': genHa(2)[0]}


def testNodesConnectsWhenOneNodeIsLate():
    with TemporaryDirectory() as td:
        with Looper() as looper:
            nodes = []
            names = list(nodeReg.keys())
            logger.debug("Node names: {}".format(names))

            def create(name):
                node = Node(name, nodeReg, basedirpath=td)
                looper.add(node)
Пример #25
0
def acmeAgentPort():
    return genHa()[1]
Пример #26
0
def faberAgentPort():
    return genHa()[1]
Пример #27
0
def testConnectionWithHaChanged(tdir):
    console = getConsole()
    console.reinit(verbosity=console.Wordage.verbose)

    alphaSigner = SimpleSigner()
    betaSigner = SimpleSigner()

    alphaPrivateer = Privateer()
    betaPrivateer = Privateer()

    logger.debug("Alpha's verkey {}".format(alphaSigner.naclSigner.verhex))
    logger.debug("Beta's verkey {}".format(betaSigner.naclSigner.verhex))

    alpha = None

    def setupAlpha(ha):
        nonlocal alpha
        alpha = RoadStack(name='alpha',
                          ha=ha,
                          sigkey=alphaSigner.naclSigner.keyhex,
                          prikey=alphaPrivateer.keyhex,
                          auto=AutoMode.never,
                          basedirpath=tdir)

        alpha.keep.dumpRemoteRoleData(
            {
                "acceptance": Acceptance.accepted.value,
                "verhex": betaSigner.naclSigner.verhex,
                "pubhex": betaPrivateer.pubhex
            }, "beta")

    oldHa = genHa()
    setupAlpha(oldHa)

    beta = RoadStack(name='beta',
                     ha=genHa(),
                     sigkey=betaSigner.naclSigner.keyhex,
                     prikey=betaPrivateer.keyhex,
                     main=True,
                     auto=AutoMode.never,
                     basedirpath=tdir,
                     mutable=True)

    beta.keep.dumpRemoteRoleData(
        {
            "acceptance": Acceptance.accepted.value,
            "verhex": alphaSigner.naclSigner.verhex,
            "pubhex": alphaPrivateer.pubhex
        }, "alpha")

    try:
        betaRemote = RemoteEstate(stack=alpha, ha=beta.ha)
        alpha.addRemote(betaRemote)
        alpha.join(uid=betaRemote.uid, cascade=True)
        handshake(alpha, beta)
        sendMsgs(alpha, beta, betaRemote)
        logger.debug("beta knows alpha as {}".format(
            getRemote(beta, "alpha").ha))
        cleanup(alpha)

        newHa = genHa()
        logger.debug("alpha changing ha to {}".format(newHa))

        setupAlpha(newHa)
        betaRemote = RemoteEstate(stack=alpha, ha=beta.ha)
        alpha.addRemote(betaRemote)
        alpha.join(uid=betaRemote.uid, cascade=True)
        handshake(alpha, beta)
        sendMsgs(alpha, beta, betaRemote)
        logger.debug("beta knows alpha as {}".format(
            getRemote(beta, "alpha").ha))
    finally:
        cleanup(alpha, beta)