Esempio n. 1
0
    def _dump():
        logger = getlogger()

        cli = ctx['current_cli']
        nocli = {"cli": False}
        wrts = ''.join(cli.cli.output.writes)
        logger.info('=========================================', extra=nocli)
        logger.info('|             OUTPUT DUMP               |', extra=nocli)
        logger.info('-----------------------------------------', extra=nocli)
        for w in wrts.splitlines():
            logger.info('> ' + w, extra=nocli)
        logger.info('=========================================', extra=nocli)
    def __init__(self,
                 name: str,
                 basedirpath: str,
                 client: Client = None,
                 wallet: Wallet = None,
                 port: int = None,
                 loop=None,
                 config=None,
                 endpointArgs=None):

        config = config or getConfig()
        basedirpath = basedirpath or os.path.expanduser(config.baseDir)

        portParam, _ = self.getPassedArgs()

        self.logger = getlogger()

        super().__init__(name,
                         basedirpath,
                         client,
                         wallet,
                         portParam or port,
                         loop=loop,
                         config=config,
                         endpointArgs=endpointArgs)

        self.claimVersionNumber = 0.01

        # available claims to anyone whose connection is accepted by the agent
        self.availableClaimsToAll = []

        # available claims only for certain invitation (by nonce)
        self.availableClaimsByNonce = {}

        # mapping between specific identifier and available claims which would
        # have been available once they have provided requested information
        # like proof etc.
        self.availableClaimsByIdentifier = {}

        self._invites = {}

        self.updateClaimVersionFile(self.getClaimVersionFileName())
Esempio n. 3
0
from sovrin_client.agent.caching import Caching
from sovrin_client.agent.endpoint import ZEndpoint, REndpoint
from sovrin_client.agent.walleted import Walleted
from sovrin_client.anon_creds.sovrin_issuer import SovrinIssuer
from sovrin_client.anon_creds.sovrin_prover import SovrinProver
from sovrin_client.anon_creds.sovrin_verifier import SovrinVerifier
from sovrin_client.client.client import Client
from sovrin_client.client.wallet.wallet import Wallet
from sovrin_common.config import agentLoggingLevel
from sovrin_common.config_util import getConfig
from sovrin_common.identity import Identity
from sovrin_common.strict_types import strict_types, decClassMethods
from stp_core.network.port_dispenser import genHa
from plenum.common.util import randomString

logger = getlogger()
logger.setLevel(agentLoggingLevel)


@decClassMethods(strict_types())
class Agent(Motor, AgentNet):
    def __init__(self,
                 name: str = None,
                 basedirpath: str = None,
                 client: Client = None,
                 port: int = None,
                 loop=None,
                 config=None,
                 endpointArgs=None):

        self.endpoint = None
Esempio n. 4
0
import time
from ledger.ledger import Ledger
from ledger.merkle_verifier import MerkleVerifier
from ledger.util import F

from plenum.common.exceptions import RemoteNotFound
from plenum.common.startable import LedgerState
from plenum.common.types import LedgerStatus, CatchupRep, ConsistencyProof, f, \
    CatchupReq, ConsProofRequest
from plenum.common.util import getMaxFailures
from plenum.common.config_util import getConfig
from plenum.common.log import getlogger
from plenum.server.has_action_queue import HasActionQueue

logger = getlogger()


class LedgerManager(HasActionQueue):
    def __init__(self, owner, ownedByNode: bool=True):
        self.owner = owner
        self.ownedByNode = ownedByNode
        self.config = getConfig()
        # Needs to schedule actions. The owner of the manager has the
        # responsibility of calling its `_serviceActions` method periodically.
        HasActionQueue.__init__(self)

        # Holds ledgers of different types with their info like the ledger
        # object, various callbacks, state (can be synced, is already synced,
        # etc).
        self.ledgers = {}   # type: Dict[int, Dict[str, Any]]
Esempio n. 5
0
class PortDispenser:
    """
    This class provides a system-wide mechanism to provide a available socket
    ports for testing. Tests should call getNext to get the next available port.
    There is no guarantee of sequential port numbers, as other tests running
    concurrently might grab a port before one process is done getting all the
    ports it needs. This should pose no problem, as tests shouldn't depend on
    port numbers. It leverages the filesystem lock mechanism to ensure there
    are no overlaps.
    """

    maxportretries = 3
    logger = log.getlogger()

    def __init__(self,
                 ip: str,
                 filename: str = None,
                 minPort=6000,
                 maxPort=9999):
        self.ip = ip
        self.FILE = filename or os.path.join(
            tempfile.gettempdir(), 'plenum-portmutex.{}.txt'.format(ip))
        self.minPort = minPort
        self.maxPort = maxPort
        self.initFile()

    def initFile(self):
        if not os.path.exists(self.FILE):
            with open(self.FILE, "w") as file:
                file.write(str(self.minPort))

    def get(self, count: int = 1, readOnly: bool = False, recurlvl=0):
        with open(self.FILE, "r+") as file:
            portalocker.lock(file, portalocker.LOCK_EX)
            ports = []
            while len(ports) < count:
                file.seek(0)
                port = int(file.readline())
                if readOnly:
                    return port
                port += 1
                if port > self.maxPort:
                    port = self.minPort
                file.seek(0)
                file.write(str(port))
                try:
                    checkPortAvailable(("", port))
                    ports.append(port)
                    self.logger.debug("new port dispensed: {}".format(port))
                except:
                    if recurlvl < self.maxportretries:
                        self.logger.debug(
                            "port {} unavailable, trying again...".format(
                                port))
                    else:
                        self.logger.debug(
                            "port {} unavailable, max retries {} "
                            "reached".format(port, self.maxportretries))
                        raise
            return ports

    def getNext(self, count: int = 1):
        has = [HA(self.ip, port) for port in self.get(count)]
        if len(has) == 1:
            return has[0]
        else:
            return has
Esempio n. 6
0
import logging

# The following setup of logging needs to happen before everything else
from plenum.common.log import getlogger
from sovrin.anon_creds.cred_def import CredDef
from sovrin.anon_creds.issuer import InMemoryAttrRepo
from sovrin.anon_creds.proof_builder import ProofBuilder
from sovrin.anon_creds.verifier import Verifier

from plenum.common.txn_util import createGenesisTxnFile
from ioflo.aid.consoling import Console

logging.root.handlers = []
# setupLogging(DISPLAY_LOG_LEVEL,
#              Console.Wordage.mute)
logger = getlogger("anon_creds_demo")

from plenum.client.signer import SimpleSigner
from plenum.common.looper import Looper
from plenum.common.txn import DATA, ORIGIN
from plenum.common.txn import TXN_TYPE
from plenum.test.helper import genHa, ensureElectionsDone, \
    checkNodesConnected, genNodeReg

from sovrin.test.helper import genTestClient, submitAndCheck, createNym, \
    TestNodeSet, _newWallet, makePendingTxnsRequest
from sovrin.common.txn import CRED_DEF, SPONSOR, getTxnOrderedFields
from sovrin.test.conftest import genesisTxns
from sovrin.common.util import getCredDefTxnData, getConfig
import sovrin.anon_creds.issuer as IssuerModule
import sovrin.anon_creds.prover as ProverModule
Esempio n. 7
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. 8
0
import importlib

import os

from plenum.common.util import getConfig
from plenum.common.log import getlogger

pluginsLoaded = {}  # Dict(baseDir, List[plugin names])
pluginsNotFound = {}  # Dict(baseDir, List[plugin names])

logger = getlogger("plugin-loader")


def loadPlugins(baseDir):
    global pluginsLoaded

    alreadyLoadedPlugins = pluginsLoaded.get(baseDir)
    i = 0
    if alreadyLoadedPlugins:
        logger.debug("Plugins {} are already loaded from basedir: {}".format(
            alreadyLoadedPlugins, baseDir))
    else:
        logger.debug(
            "Plugin loading started to load plugins from basedir: {}".format(
                baseDir))

        config = getConfig()
        pluginsDirPath = os.path.expanduser(
            os.path.join(baseDir, config.PluginsDir))

        if not os.path.exists(pluginsDirPath):
Esempio n. 9
0
from importlib.util import module_from_spec, spec_from_file_location
import os

from plenum.common.config_util import getConfig
from plenum.common.log import getlogger

pluginsLoaded = {}  # Dict(baseDir, List[plugin names])
pluginsNotFound = {}  # Dict(baseDir, List[plugin names])

logger = getlogger("plugin-loader")


def loadPlugins(baseDir):
    global pluginsLoaded

    alreadyLoadedPlugins = pluginsLoaded.get(baseDir)
    i = 0
    if alreadyLoadedPlugins:
        logger.debug("Plugins {} are already loaded from basedir: {}".format(
            alreadyLoadedPlugins, baseDir))
    else:
        logger.debug(
            "Plugin loading started to load plugins from basedir: {}".format(
                baseDir))

        config = getConfig()
        pluginsDirPath = os.path.expanduser(os.path.join(
            baseDir, config.PluginsDir))

        if not os.path.exists(pluginsDirPath):
            os.makedirs(pluginsDirPath)