Python indy.error.IndyError() Examples

The following are 30 code examples of indy.error.IndyError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module indy.error , or try the search function .
Example #1
Source File: helper.py    From indy-plenum with Apache License 2.0 6 votes vote down vote up
def sdk_get_replies(looper, sdk_req_resp: Sequence, timeout=None):
    resp_tasks = [resp for _, resp in sdk_req_resp]
    # TODO: change timeout evaluating logic, when sdk will can tuning timeout from outside
    if timeout is None:
        timeout = waits.expectedTransactionExecutionTime(7)

    def get_res(task, done_list):
        if task in done_list:
            try:
                resp = json.loads(task.result())
            except IndyError as e:
                resp = e.error_code
        else:
            resp = ErrorCode.PoolLedgerTimeout
        return resp

    done, pending = looper.run(asyncio.wait(resp_tasks, timeout=timeout))
    if pending:
        for task in pending:
            task.cancel()
    ret = [(req, get_res(resp, done)) for req, resp in sdk_req_resp]
    return ret 
Example #2
Source File: anchor.py    From von-network with Apache License 2.0 6 votes vote down vote up
def submit_request(
        self, req_json: str, signed: bool = False, apply_taa=False
    ):
        try:
            if signed:
                if not self._did:
                    raise AnchorException("Cannot sign request: no DID")
                req = json.loads(req_json)
                if apply_taa and self._taa_accept:
                    req["taaAcceptance"] = self._taa_accept
                signer = SimpleSigner(self._did, self._seed)
                req["signature"] = signer.sign(req)
                req_json = json.dumps(req)
            rv_json = await ledger.submit_request(self._pool, req_json)
            await asyncio.sleep(0)
        except IndyError as e:
            raise AnchorException("Error submitting ledger transaction request") from e

        resp = json.loads(rv_json)
        if resp.get("op", "") in ("REQNACK", "REJECT"):
            raise AnchorException(
                "Ledger rejected transaction request: {}".format(resp["reason"])
            )

        return resp 
Example #3
Source File: set_did_metadata.py    From von-network with Apache License 2.0 6 votes vote down vote up
def set_did_metadata():
    try:
        print_log('\nOpening wallet ...\n')
        print(wallet_config)
        print(wallet_credentials)
        wallet_handle = await wallet.open_wallet(wallet_config, wallet_credentials)

        print_log('\nGenerating seed hash ...')
        seed_hash = sha256(did_seed.encode()).hexdigest()
        did_metadata = {**(metadata or {}), 'public': True, 'seed_hash': seed_hash}
        
        print_log('\nWriting metadata for DID ...')
        print_log('DID: ' + wallet_did)
        print_log('Metadata: ' + json.dumps(did_metadata))
        await did.set_did_metadata(wallet_handle, wallet_did, json.dumps(did_metadata))

    except IndyError as e:
        print('Error occurred: %s' % e) 
Example #4
Source File: indy_sdk_utils.py    From indy-agent with Apache License 2.0 6 votes vote down vote up
def did_for_key(wallet_handle, key):
    """ Retrieve DID for a given key from the non_secrets verkey to DID map.
    """
    _did = None
    try:
        _did = json.loads(
            await non_secrets.get_wallet_record(
                wallet_handle,
                'key-to-did',
                key,
                '{}'
            )
        )['value']
    except error.IndyError as e:
        if e.error_code is error.ErrorCode.WalletItemNotFound:
            pass
        else:
            raise e

    return _did 
Example #5
Source File: indy_provider.py    From aries-protocol-test-suite with Apache License 2.0 6 votes vote down vote up
def issue_credential_v1_0_issuer_create_credential_schema(self, name: str, version: str, attrs: [str]) -> str:
        (schema_id, schema) = await anoncreds.issuer_create_schema(
            self.did, name, version, json.dumps(attrs))
        try:
           # Check to see if the schema is already on the ledger
           request = await ledger.build_get_schema_request(self.did, schema_id)
           response = await ledger.submit_request(self.pool, request)
           resp = json.loads(response)
           if resp["result"]["seqNo"]:
              (_, schema) = await ledger.parse_get_schema_response(response)
              return schema_id
        except IndyError as e:
           pass
        # Try to write the schema to the ledger
        schema_request = await ledger.build_schema_request(self.did, schema)
        schema_request = await self._append_taa(schema_request)
        await ledger.sign_and_submit_request(self.pool, self.wallet, self.did, schema_request)
        return schema_id 
Example #6
Source File: indy.py    From aries-cloudagent-python with Apache License 2.0 6 votes vote down vote up
def open(self):
        """Start the search query."""
        query_json = json.dumps(self.tag_query or {})
        options_json = json.dumps(
            {
                "retrieveRecords": True,
                "retrieveTotalCount": False,
                "retrieveType": False,
                "retrieveValue": True,
                "retrieveTags": self.option("retrieveTags", True),
            }
        )
        try:
            self._handle = await non_secrets.open_wallet_search(
                self.store.wallet.handle, self.type_filter, query_json, options_json
            )
        except IndyError as x_indy:
            raise StorageSearchError(str(x_indy)) from x_indy 
Example #7
Source File: indy.py    From aries-cloudagent-python with Apache License 2.0 6 votes vote down vote up
def delete_record(self, record: StorageRecord):
        """
        Delete a record.

        Args:
            record: `StorageRecord` to delete

        Raises:
            StorageNotFoundError: If record not found
            StorageError: If a libindy error occurs

        """
        _validate_record(record)
        try:
            await non_secrets.delete_wallet_record(
                self._wallet.handle, record.type, record.id
            )
        except IndyError as x_indy:
            if x_indy.error_code == ErrorCode.WalletItemNotFound:
                raise StorageNotFoundError(f"Record not found: {record.id}")
            raise StorageError(str(x_indy)) 
Example #8
Source File: indy.py    From aries-cloudagent-python with Apache License 2.0 6 votes vote down vote up
def update_record_value(self, record: StorageRecord, value: str):
        """
        Update an existing stored record's value.

        Args:
            record: `StorageRecord` to update
            value: The new value

        Raises:
            StorageNotFoundError: If record not found
            StorageError: If a libindy error occurs

        """
        _validate_record(record)
        try:
            await non_secrets.update_wallet_record_value(
                self._wallet.handle, record.type, record.id, value
            )
        except IndyError as x_indy:
            if x_indy.error_code == ErrorCode.WalletItemNotFound:
                raise StorageNotFoundError(f"Record not found: {record.id}")
            raise StorageError(str(x_indy)) 
Example #9
Source File: indy.py    From aries-cloudagent-python with Apache License 2.0 6 votes vote down vote up
def add_record(self, record: StorageRecord):
        """
        Add a new record to the store.

        Args:
            record: `StorageRecord` to be stored

        """
        _validate_record(record)
        tags_json = json.dumps(record.tags) if record.tags else None
        try:
            await non_secrets.add_wallet_record(
                self._wallet.handle, record.type, record.id, record.value, tags_json
            )
        except IndyError as x_indy:
            if x_indy.error_code == ErrorCode.WalletItemAlreadyExists:
                raise StorageDuplicateError(
                    "Duplicate record ID: {}".format(record.id)
                ) from x_indy
            raise StorageError(str(x_indy)) from x_indy 
Example #10
Source File: indy.py    From aries-cloudagent-python with Apache License 2.0 6 votes vote down vote up
def get_signing_key(self, verkey: str) -> KeyInfo:
        """
        Fetch info for a signing keypair.

        Args:
            verkey: The verification key of the keypair

        Returns:
            A `KeyInfo` representing the keypair

        Raises:
            WalletNotFoundError: If no keypair is associated with the verification key
            WalletError: If there is a libindy error

        """
        try:
            metadata = await indy.crypto.get_key_metadata(self.handle, verkey)
        except IndyError as x_indy:
            if x_indy.error_code == ErrorCode.WalletItemNotFound:
                raise WalletNotFoundError("Unknown key: {}".format(verkey))
            else:
                raise IndyErrorHandler.wrap_error(
                    x_indy, "Wallet {} error".format(self.name), WalletError
                ) from x_indy
        return KeyInfo(verkey, json.loads(metadata) if metadata else {}) 
Example #11
Source File: indy.py    From aries-cloudagent-python with Apache License 2.0 6 votes vote down vote up
def remove(self):
        """
        Remove an existing wallet.

        Raises:
            WalletNotFoundError: If the wallet could not be found
            WalletError: If there was an libindy error

        """
        try:
            await indy.wallet.delete_wallet(
                config=json.dumps(self._wallet_config),
                credentials=json.dumps(self._wallet_access),
            )
        except IndyError as x_indy:
            if x_indy.error_code == ErrorCode.WalletNotFoundError:
                raise IndyErrorHandler.wrap_error(
                    x_indy, "Wallet {} not found".format(self.name), WalletNotFoundError
                ) from x_indy
            raise IndyErrorHandler.wrap_error(
                x_indy, "Wallet error", WalletError
            ) from x_indy 
Example #12
Source File: helper.py    From indy-plenum with Apache License 2.0 6 votes vote down vote up
def sdk_get_reply(looper, sdk_req_resp, timeout=None):
    req_json, resp_task = sdk_req_resp
    # TODO: change timeout evaluating logic, when sdk will can tuning timeout from outside
    if timeout is None:
        timeout = waits.expectedTransactionExecutionTime(7)
    try:
        resp = looper.run(asyncio.wait_for(resp_task, timeout=timeout))
        resp = json.loads(resp)
    except IndyError as e:
        resp = e.error_code
    except TimeoutError as e:
        resp = ErrorCode.PoolLedgerTimeout

    return req_json, resp


# TODO: Check places where sdk_get_replies used without sdk_check_reply
# We need to be sure that test behaviour don't need to check response
# validity 
Example #13
Source File: indy.py    From aries-cloudagent-python with Apache License 2.0 6 votes vote down vote up
def close(self):
        """Close the pool ledger."""
        if self.opened:
            exc = None
            for attempt in range(3):
                try:
                    await indy.pool.close_pool_ledger(self.pool_handle)
                except IndyError as err:
                    await asyncio.sleep(0.01)
                    exc = err
                    continue

                self.pool_handle = None
                self.opened = False
                exc = None
                break

            if exc:
                self.logger.error("Exception when closing pool ledger")
                self.ref_count += 1  # if we are here, we should have self.ref_lock
                self.close_task = None
                raise IndyErrorHandler.wrap_error(
                    exc, "Exception when closing pool ledger", LedgerError
                ) 
Example #14
Source File: indy.py    From aries-cloudagent-python with Apache License 2.0 6 votes vote down vote up
def get_revoc_reg_def(self, revoc_reg_id: str) -> dict:
        """Get revocation registry definition by ID."""
        public_info = await self.wallet.get_public_did()
        try:
            fetch_req = await indy.ledger.build_get_revoc_reg_def_request(
                public_info and public_info.did, revoc_reg_id
            )
            response_json = await self._submit(fetch_req, sign_did=public_info)
            (
                found_id,
                found_def_json,
            ) = await indy.ledger.parse_get_revoc_reg_def_response(response_json)
        except IndyError as e:
            logging.error(
                f"get_revoc_reg_def failed with revoc_reg_id={revoc_reg_id}. "
                f"{e.error_code}: {e.message}"
            )
            raise e

        assert found_id == revoc_reg_id
        return json.loads(found_def_json) 
Example #15
Source File: indy.py    From aries-cloudagent-python with Apache License 2.0 6 votes vote down vote up
def get_credential(self, credential_id: str) -> str:
        """
        Get a credential stored in the wallet.

        Args:
            credential_id: Credential id to retrieve

        """
        try:
            credential_json = await indy.anoncreds.prover_get_credential(
                self.wallet.handle, credential_id
            )
        except IndyError as err:
            if err.error_code == ErrorCode.WalletItemNotFound:
                raise WalletNotFoundError(
                    "Credential {} not found in wallet {}".format(
                        credential_id, self.wallet.name
                    )
                )
            else:
                raise IndyErrorHandler.wrap_error(
                    err, f"Error when fetching credential {credential_id}", HolderError
                ) from err

        return credential_json 
Example #16
Source File: indy.py    From aries-cloudagent-python with Apache License 2.0 5 votes vote down vote up
def delete_credential(self, credential_id: str):
        """
        Remove a credential stored in the wallet.

        Args:
            credential_id: Credential id to remove

        """
        try:
            indy_stor = IndyStorage(self.wallet)
            mime_types_record = await indy_stor.get_record(
                IndyHolder.RECORD_TYPE_MIME_TYPES,
                f"{IndyHolder.RECORD_TYPE_MIME_TYPES}::{credential_id}",
            )
            await indy_stor.delete_record(mime_types_record)
        except StorageNotFoundError:
            pass  # MIME types record not present: carry on

        try:
            await indy.anoncreds.prover_delete_credential(
                self.wallet.handle, credential_id
            )
        except IndyError as err:
            if err.error_code == ErrorCode.WalletItemNotFound:
                raise WalletNotFoundError(
                    "Credential {} not found in wallet {}".format(
                        credential_id, self.wallet.name
                    )
                )
            else:
                raise IndyErrorHandler.wrap_error(
                    err, "Error when deleting credential", HolderError
                ) from err 
Example #17
Source File: anchor.py    From von-network with Apache License 2.0 5 votes vote down vote up
def _open_pool(self):
        pool_name = "nodepool"
        pool_cfg = {}
        self._pool = None

        try:
            await pool.set_protocol_version(self._protocol)
        except IndyError as e:
            raise AnchorException("Error setting pool protocol version") from e

        # remove existing pool config by the same name in ledger browser mode
        try:
            pool_names = {cfg["pool"] for cfg in await pool.list_pools()}
            if pool_name in pool_names:
                await pool.delete_pool_ledger_config(pool_name)
        except IndyError as e:
            raise AnchorException("Error deleting existing pool configuration") from e

        try:
            await pool.create_pool_ledger_config(
                pool_name, json.dumps({"genesis_txn": await resolve_genesis_file()})
            )
        except IndyError as e:
            raise AnchorException("Error creating pool configuration") from e

        try:
            self._pool = await pool.open_pool_ledger(pool_name, json.dumps(pool_cfg))
        except IndyError as e:
            raise AnchorException("Error opening pool ledger connection") from e 
Example #18
Source File: indy.py    From aries-cloudagent-python with Apache License 2.0 5 votes vote down vote up
def fetch_credential_definition(self, credential_definition_id: str) -> dict:
        """
        Get a credential definition from the ledger by id.

        Args:
            credential_definition_id: The cred def id of the cred def to fetch

        """

        public_info = await self.wallet.get_public_did()
        public_did = public_info.did if public_info else None

        with IndyErrorHandler("Exception when building cred def request", LedgerError):
            request_json = await indy.ledger.build_get_cred_def_request(
                public_did, credential_definition_id
            )

        response_json = await self._submit(request_json, sign_did=public_info)

        with IndyErrorHandler("Exception when parsing cred def response", LedgerError):
            try:
                (
                    _,
                    parsed_credential_definition_json,
                ) = await indy.ledger.parse_get_cred_def_response(response_json)
                parsed_response = json.loads(parsed_credential_definition_json)
            except IndyError as error:
                if error.error_code == ErrorCode.LedgerNotFound:
                    parsed_response = None
                else:
                    raise

        if parsed_response and self.cache:
            await self.cache.set(
                f"credential_definition::{credential_definition_id}",
                parsed_response,
                self.cache_duration,
            )

        return parsed_response 
Example #19
Source File: template.py    From indy-dev with Apache License 2.0 5 votes vote down vote up
def issue_credential():
    try:
        await pool.set_protocol_version(PROTOCOL_VERSION)
        # Step 2 code goes here.

        # Step 3 code goes here.

        # Step 4 code goes here.

    except IndyError as e:
        print('Error occurred: %s' % e) 
Example #20
Source File: template.py    From indy-dev with Apache License 2.0 5 votes vote down vote up
def write_schema_and_cred_def():
    try:
        await pool.set_protocol_version(PROTOCOL_VERSION)
        # Step 2 code goes here.

        # Step 3 code goes here.

        # Step 4 code goes here.

    except IndyError as e:
        print('Error occurred: %s' % e) 
Example #21
Source File: template.py    From indy-dev with Apache License 2.0 5 votes vote down vote up
def write_nym_and_query_verkey():
    try:
        await pool.set_protocol_version(PROTOCOL_VERSION)
        # Step 2 code goes here.

        # Step 3 code goes here.

        # Step 4 code goes here.

        # Step 5 code goes here.

    except IndyError as e:
        print('Error occurred: %s' % e) 
Example #22
Source File: template.py    From indy-dev with Apache License 2.0 5 votes vote down vote up
def proof_negotiation():
    try:
        await pool.set_protocol_version(PROTOCOL_VERSION)
        # Step 2 code goes here.

        # Step 3 code goes here.

        # Step 4 code goes here.

        # Step 5 code goes here.

    except IndyError as e:
        print('Error occurred: %s' % e) 
Example #23
Source File: indy_provider.py    From aries-protocol-test-suite with Apache License 2.0 5 votes vote down vote up
def _open_pool(self, cfg):
        # Create the pool, but ignore the error if it already exists
        await pool.set_protocol_version(2)
        try:
            await pool.create_pool_ledger_config(self.pool_name, json.dumps(cfg))
        except IndyError as e:
            if e.error_code != ErrorCode.PoolLedgerConfigAlreadyExistsError:
                raise e
        self.pool = await pool.open_pool_ledger(self.pool_name, json.dumps(cfg)) 
Example #24
Source File: indy.py    From aries-cloudagent-python with Apache License 2.0 5 votes vote down vote up
def close(self):
        """Dispose of the search query."""
        try:
            if self._handle:
                await non_secrets.close_wallet_search(self._handle)
                self._handle = None
        except IndyError as x_indy:
            raise StorageSearchError(str(x_indy)) from x_indy 
Example #25
Source File: indy.py    From aries-cloudagent-python with Apache License 2.0 5 votes vote down vote up
def fetch(self, max_count: int) -> Sequence[StorageRecord]:
        """
        Fetch the next list of results from the store.

        Args:
            max_count: Max number of records to return

        Returns:
            A list of `StorageRecord`

        Raises:
            StorageSearchError: If the search query has not been opened

        """
        if not self.opened:
            raise StorageSearchError("Search query has not been opened")

        try:
            result_json = await non_secrets.fetch_wallet_search_next_records(
                self.store.wallet.handle, self._handle, max_count
            )
        except IndyError as x_indy:
            raise StorageSearchError(str(x_indy)) from x_indy

        results = json.loads(result_json)
        ret = []
        if results["records"]:
            for row in results["records"]:
                ret.append(
                    StorageRecord(
                        type=self._type_filter,
                        id=row["id"],
                        value=row["value"],
                        tags=row["tags"],
                    )
                )
        return ret 
Example #26
Source File: test_indy.py    From aries-cloudagent-python with Apache License 2.0 5 votes vote down vote up
def test_get_credential_x(self, mock_get_cred):
        mock_get_cred.side_effect = IndyError("unexpected failure")

        mock_wallet = async_mock.MagicMock()
        holder = IndyHolder(mock_wallet)

        with self.assertRaises(test_module.HolderError):
            await holder.get_credential("credential_id") 
Example #27
Source File: indy.py    From aries-cloudagent-python with Apache License 2.0 5 votes vote down vote up
def get_local_did(self, did: str) -> DIDInfo:
        """
        Find info for a local DID.

        Args:
            did: The DID to get info for

        Returns:
            A `DIDInfo` instance representing the found DID

        Raises:
            WalletNotFoundError: If the DID is not found
            WalletError: If there is a libindy error

        """

        try:
            info_json = await indy.did.get_my_did_with_meta(self.handle, did)
        except IndyError as x_indy:
            if x_indy.error_code == ErrorCode.WalletItemNotFound:
                raise WalletNotFoundError("Unknown DID: {}".format(did))
            raise IndyErrorHandler.wrap_error(
                x_indy, "Wallet {} error".format(self.name), WalletError
            ) from x_indy
        info = json.loads(info_json)
        return DIDInfo(
            did=info["did"],
            verkey=info["verkey"],
            metadata=json.loads(info["metadata"]) if info["metadata"] else {},
        ) 
Example #28
Source File: indy.py    From aries-cloudagent-python with Apache License 2.0 5 votes vote down vote up
def create(self, replace: bool = False):
        """
        Create a new wallet.

        Args:
            replace: Removes the old wallet if True

        Raises:
            WalletError: If there was a problem removing the wallet
            WalletError: IF there was a libindy error

        """
        if replace:
            try:
                await self.remove()
            except WalletNotFoundError:
                pass
        try:
            await indy.wallet.create_wallet(
                config=json.dumps(self._wallet_config),
                credentials=json.dumps(self._wallet_access),
            )
        except IndyError as x_indy:
            raise IndyErrorHandler.wrap_error(
                x_indy,
                "Wallet was not removed by SDK, {} may still be open".format(self.name)
                if x_indy.error_code == ErrorCode.WalletAlreadyExistsError
                else None,
                WalletError,
            ) from x_indy 
Example #29
Source File: error.py    From aries-cloudagent-python with Apache License 2.0 5 votes vote down vote up
def wrap_error(
        cls,
        err_value: IndyError,
        message: str = None,
        error_cls: Type[BaseError] = BaseError,
    ) -> BaseError:
        """Create an instance of BaseError from an IndyError."""
        err_msg = message or "Exception while performing indy operation"
        indy_message = hasattr(err_value, "message") and err_value.message
        if indy_message:
            err_msg += f": {indy_message}"
        err = error_cls(err_msg)
        err.__traceback__ = err_value.__traceback__
        return err 
Example #30
Source File: indy.py    From aries-cloudagent-python with Apache License 2.0 5 votes vote down vote up
def create_signing_key(
        self, seed: str = None, metadata: dict = None
    ) -> KeyInfo:
        """
        Create a new public/private signing keypair.

        Args:
            seed: Seed for key
            metadata: Optional metadata to store with the keypair

        Returns:
            A `KeyInfo` representing the new record

        Raises:
            WalletDuplicateError: If the resulting verkey already exists in the wallet
            WalletError: If there is a libindy error

        """
        args = {}
        if seed:
            args["seed"] = bytes_to_b64(validate_seed(seed))
        try:
            verkey = await indy.crypto.create_key(self.handle, json.dumps(args))
        except IndyError as x_indy:
            if x_indy.error_code == ErrorCode.WalletItemAlreadyExists:
                raise WalletDuplicateError("Verification key already present in wallet")
            raise IndyErrorHandler.wrap_error(
                x_indy, "Wallet {} error".format(self.name), WalletError
            ) from x_indy

        # must save metadata to allow identity check
        # otherwise get_key_metadata just returns WalletItemNotFound
        if metadata is None:
            metadata = {}
        await indy.crypto.set_key_metadata(self.handle, verkey, json.dumps(metadata))
        return KeyInfo(verkey, metadata)