KERI App API

keri.app.agenting

KERI keri.app.agenting module

class keri.app.agenting.HTTPMessenger(hab, wit, url, msgs=None, sent=None, doers=None, auth=None, **kwa)[source]

Send CESR messages to a witness over HTTP and capture responses.

__init__(hab, wit, url, msgs=None, sent=None, doers=None, auth=None, **kwa)[source]

Initialize HTTP messenger with queues and optional auth.

Parameters:
  • hab (Hab) – habitat for KEL parsing and db access.

  • wit (str) – qb64 witness identifier.

  • url (str) – http/https endpoint URL for the witness.

  • msgs (Deck | None) – outbound message queue.

  • sent (Deck | None) – response queue.

  • auth (str | None) – optional 2FA auth codes for witnesses.

msgDo(tymth=None, tock=0.0, **kwa)[source]

Doer loop that sends queued messages over HTTP.

responseDo(tymth=None, tock=0.0, **kwa)[source]

Doer loop that processes HTTP responses from the client and adds them into sent cues.

class keri.app.agenting.HTTPStreamMessenger(hab, wit, url, msg=b'', headers=None, **kwa)[source]

Stream a single CESR message via HTTP PUT and capture the response.

__init__(hab, wit, url, msg=b'', headers=None, **kwa)[source]

Initialize a single-request HTTP messenger and add the HTTP client Doer to this DoDoer.

Parameters:
  • hab (Hab) – habitat for KEL parsing and db access.

  • wit (str) – qb64 witness identifier.

  • url (str) – http/https endpoint URL for the witness.

  • msg (bytes) – CESR message body to send.

  • headers (dict | None) – extra HTTP headers.

recur(tyme, deeds=None)[source]

Poll for a response and stop once received.

class keri.app.agenting.Receiptor(hby, msgs=None, gets=None, cues=None)[source]

Receiptor is a parent task orchestrating both initial receipt retrieval of KEL events and subsequent retrieval of receipts for specific events based on queries.

__init__(hby, msgs=None, gets=None, cues=None)[source]

Initialize the Receiptor and create doers for processing and retrieving witness receipts.

Parameters:
  • hby (Habery) – Habery to pull identifiers and witnesses for those identifiers from

  • msgs (Deck) – KEL event messages to publish to witnesses for receipting Messages should have {“pre”: <str>, “sn”: <int>, “auths”: <dict>}

  • gets (Deck) – query messages of KEL events to retrieve receipts from witnesses for Messages should have {“pre”: <str>, “sn”: <int>}

  • cues (Deck) – outgoing cues of successful messages; currently the messages placed here are not used

catchup(pre, wit)[source]

A generator that catches up a target witness with the latest KEL state of a prefix. When adding a new Witness use this method to catch the witness up to the current state of the KEL

Returns:

a generator that sends the KEL to the witness

Parameters:
  • pre (str) – qualified base64 AID of the KEL to send

  • wit (str) – qualified base64 AID of the witness to send the KEL to

get(pre, sn=None)[source]

Queries a random witness for the receipt of the event at the sequence number for a prefix.

Returns:

a generator requesting receipts for event identified by pre and sn

Parameters:
  • pre (str) – qualified base64 identifier to gather a receipt for

  • sn – (Optiona[int]): sequence number of event to gather receipts for, latest is used if not provided

gitDo(tymth=None, tock=0.0, **kwa)[source]

A generator that obtains a witness receipts for key event messages specified in the query messages in the .gets buffer Intended to be used with doify to create a generator Doer.

Returns:

a Hio generator function to be used as a Doer.

Parameters:
  • tymth (function) – function returning cycle time for configuring this Doer’s cycle time.

  • tock (float) – cycle time for this Doer, default is 0.0 seconds.

Usage:

add result of doify on this method to doers list

receipt(pre, sn=None, auths=None)[source]

Returns a generator performing witness receipting of KEL events.

The returns a generator that will submit the designated event to witnesses for receipts using the synchronous witness API, then propagate the receipts to each of the other witnesses. Delegates to .catchup to catch up any new witnesses to the current state of the KEL.

Parameters:
  • pre (str) – qualified base64 identifier to gather receipts for

  • sn – (Optiona[int]): sequence number of event to gather receipts for, latest is used if not provided

  • auths – (Options[dict]): map of witness AIDs to (time,auth) tuples for providing TOTP auth for witnessing

Returns:

identifiers of witnesses that returned receipts.

Return type:

list

witDo(tymth=None, tock=0.0, **kwa)[source]

A generator that obtains witness receipts for one key event message at a tyme by processing all messages in the .msgs buffer and adds processed messages to cues. Catches up any new witnesses in “adds” to the current state of the KEL using self.catchup. Intended to be used with doify to create a generator Doer. Delegates to the internal receipt generator function.

Returns:

a Hio generator function to be used as a Doer.

Parameters:
  • tymth (function) – function returning cycle time for configuring this Doer’s cycle time.

  • tock (float) – cycle time for this Doer, default is 0.0 seconds.

Usage:

add result of doify on this method to doers list

class keri.app.agenting.TCPMessenger(hab, wit, url, msgs=None, sent=None, doers=None, **kwa)[source]

Send outbound CESR messages to a witness via TCP and parse inbound receipts.

__init__(hab, wit, url, msgs=None, sent=None, doers=None, **kwa)[source]

Initialize TCP messenger with queues and parser wiring.

Parameters:
  • hab (Hab) – habitat for KEL parsing and db access.

  • wit (str) – qb64 witness identifier.

  • url (str) – tcp endpoint URL for the witness.

  • msgs (Deck | None) – outbound message queue.

  • sent (Deck | None) – sent message queue.

msgDo(tymth=None, tock=0.0, **opts)[source]

Doer loop that parses inbound TCP messages into the Kevery.

receiptDo(tymth=None, tock=0.0, **kwa)[source]

Doer loop that sends queued messages over TCP.

class keri.app.agenting.TCPStreamMessenger(hab, wit, url, msgs=None, sent=None, doers=None, **kwa)[source]

Stream a CESR message to a witness via TCP and parse inbound receipts.

__init__(hab, wit, url, msgs=None, sent=None, doers=None, **kwa)[source]

Initialize TCP stream messenger with queues and parser wiring.

Parameters:
  • hab (Hab) – habitat for KEL parsing and db access.

  • wit (str) – qb64 witness identifier.

  • url (str) – tcp endpoint URL for the witness.

  • msgs (Deck | None) – outbound message queue.

  • sent (Deck | None) – sent message queue.

msgDo(tymth=None, tock=0.0, **opts)[source]

Doer loop that parses inbound TCP messages into the Kevery.

receiptDo(tymth=None, tock=0.0, **kwa)[source]

Doer loop that sends queued messages over TCP.

Pushes the original request to self.sent to signal completion

class keri.app.agenting.WitnessInquisitor(hby, msgs=None, klas=None, **kwa)[source]

Sends KEL and TEL query messages to different types of targets whether witnesses, controllers, or agents based on the locally available endpoint role records for the query target. Queries are performed by sending query messages either to a random witness or to the controller or agent that is the target of the query.

Removes all Doers and exits as Done once the query target has been sent the query message

TODO: possibly rename based on the fact that multiple types of targets are supported (controller, agent, witness)

__init__(hby, msgs=None, klas=None, **kwa)[source]

Initialize the WitnessInquisitor with the given parameters.

Parameters:
  • hby (Habery) – Habery context to use to retrieve the source Hab for reading endpoint role records

  • klas (class) – Type of messenger to use to send messages; defaults to HTTPMessenger; currently unused

  • msgs (decking.Deck) – query message buffer to be sent to the target or a random witness

hby

Habery context to use to retrieve the source Hab for reading endpoint role records

Type:

Habery

klas

Type of messenger to use to send messages; defaults to HTTPMessenger; currently unused

Type:

class

msgs

query message buffer to be sent to the target or a random witness

Type:

decking.Deck

sent

buffer for sent messages to track sent queries

Type:

decking.Deck

msgDo(tymth=None, tock=1.0, **opts)[source]

Signs and sends provided KEL and TEL query messages to query targets using HTTPMessenger or TCPMessenger. Uses a randomly selected witness if the query target is a witness, or uses the specified controller or agent when a controller or agent is specified.

Returns a Hio generator function that runs until all messages in .msgs are processed.

Usage:

add result of doify on this method to doers list

query(pre, r='logs', sn='0', fn='0', src=None, hab=None, anchor=None, wits=None, **kwa)[source]

Create a KEL query (qry) message against the attester for the prefix (pre) and place on the internal .msgs queue for processing by the .msgDo doer. May also contain an anchor to use to locate a key event. May specify the hab to use for signing and retrieving endpoint role records.

Parameters:
  • pre (str) – qb64 identifier prefix being queried for

  • r (str) – query route

  • sn (str) – optional specific hex str of sequence number to query for

  • fn (str) – optional specific hex str of sequence number to start with

  • src (str) – qb64 identifier prefix of source of query

  • hab (Hab) – Hab to use instead of src, if provided, to retrieve endpoint role records from and to perform signing

  • anchor (Seal) – anchored Seal to search for in the query target

  • wits (list)

telquery(ri, src=None, i=None, r='tels', hab=None, pre=None, wits=None, **kwa)[source]

Create a TEL Query message to search against a given registry, issuer, route, in the target prefixe’s (pre) records, and add that query message on the internal .msgs queue. May specify the hab to use for signing and retrieving endpoint role records.

Parameters:
  • ri (str) – qb64 identifier prefix of the registry being queried

  • src (str) – qb64 identifier prefix of source of query

  • i (str) – qb64 identifier prefix of the issuer of the registry being queried

  • r (str) – query route

  • hab (Hab) – Hab to use instead of src, if provided, to retrieve endpoint role records from and to perform signing

  • pre (str) – qb64 identifier prefix of the target being queried

  • wits (list) – witnesses to query

class keri.app.agenting.WitnessPublisher(hby, msgs=None, cues=None, **kwa)[source]

Sends messages to all current witnesses of given identifier (from hab) and exits.

Removes all Doers and exits as Done once all witnesses have been sent the message. Could be enhanced to have a once method that runs once and cleans up and an all method that runs and waits for more messages to receipt.

__init__(hby, msgs=None, cues=None, **kwa)[source]

Initialize with publish queue (msgs) and completion cues.

Parameters:
  • hby (Habery) – Habitat of the identifier to populate witnesses

  • msgs (Deck) – incoming messages to publish to witnesses

  • cues (Deck) – outgoing cues of successful messages

sendDo(tymth=None, tock=0.0, **opts)[source]

Doer loop that sends queued messages to each witness.

Pushes the original request to self.cues to signal completion

sent(said)[source]

Check if message with given SAID was sent

Parameters:

said (str) – qb64 SAID of message to check for

class keri.app.agenting.WitnessReceiptor(hby, msgs=None, cues=None, force=False, auths=None, **kwa)[source]

Sends receipt messages to all current witnesses of given identifier (from hab), waits for receipts from each of those witnesses, and propagates those receipts to each of the other witnesses after receiving the complete set.

Removes all Doers and exits as Done once all witnesses have been sent the entire receipt set. Could be enhanced to have a once method that runs once and cleans up and an all method that runs and waits for more messages to receipt.

__init__(hby, msgs=None, cues=None, force=False, auths=None, **kwa)[source]

For the current event, gather the current set of witnesses, send the event, gather all receipts and send them to all other witnesses

Parameters:
  • hby (Habery) – Habitat of the identifier to receipt witnesses

  • msgs (Deck) – events to send the event and receipt to all witnesses Messages should have {“pre”: <str>, “sn”: <int>, “auths”: <dict>}

  • cues (Deck) – outgoing cues of events confirmed as fully receipted Messages have {“pre”: <str>, “sn”: <int>, “auths”: <dict>}

  • force (bool) – True means to send witnesses all receipts even if we have a full complement.

  • auths (dict) – map of witness AIDs to (time,auth) tuples for providing TOTP auth for witnessing

receiptDo(tymth=None, tock=0.0, **kwa)[source]
Sends events, their receipts, receipt signatures, delegation chain, and location record

URLs between witnesses in the set of current witnesses.

Returns:

a doifiable Hio generator to perform event and receipt sending.

Usage:

add result of doify on this method to doers list

Parameters:
  • tymth (function) – function returning cycle time for configuring this Doer’s cycle time.

  • tock (float) – cycle time for this Doer, default is 0.0 seconds.

keri.app.agenting.httpClient(hab, wit)[source]

Create and return a http.client and http.ClientDoer for the witness

Parameters:
  • hab (Habitat) – Environment to use to look up witness URLs

  • wit (str) – qb64 identifier prefix of witness for which to create a client

Returns:

Http client for connecting to remote identifier ClientDoer: Doer for client

Return type:

Client

keri.app.agenting.mailbox(hab, cid)[source]

Finds and returns a mailbox, if any, based on the provided Mab and controller AID (cid).

Returns:

qb64 identifier prefix of the mailbox to use for the controller, or None if no mailbox found.

Return type:

str | None

Parameters:
  • hab (Hab) – Hab to use to look up witness URLs

  • cid (str) – qb64 identifier prefix of controller to find mailbox for

keri.app.agenting.messenger(hab, pre, auth=None)[source]

Create a Messenger (tcp or http) based on available endpoints

Parameters:
  • hab (Habitat) – Environment to use to look up witness URLs

  • pre (str) – qb64 identifier prefix of recipient to create a messanger for

  • auth (str) – optional auth code to send with any request for messenger

Returns:

witnesser for ensuring full reciepts

Return type:

Optional(TcpWitnesser, HTTPMessenger)

keri.app.agenting.messengerFrom(hab, pre, urls, auth=None)[source]

Create a Witnesser (tcp or http) based on provided endpoints

Parameters:
  • hab (Habitat) – Environment to use to look up witness URLs

  • pre (str) – qb64 identifier prefix of recipient to create a messanger for

  • urls (dict) – map of schemes to urls of available endpoints

  • auth (str) – optional auth code to send with any request for messenger

Returns:

witnesser for ensuring full reciepts

Return type:

Optional(TcpWitnesser, HTTPMessenger)

keri.app.agenting.schemes(db, eids)[source]

Creates a message bytearray of reply messages containing location records (URLs) and witness signatures, if any, for a given list of authorized endpoint role AIDs (eids).

Returns:

a bytearray of reply messages and their signatures

Parameters:
  • db (Baser) – Hab database used to retrieve location records and witness signatures

  • eids (list) – list of endpoint role AIDs (eids) to retrieve location records and witness signatures for

keri.app.agenting.streamMessengerFrom(hab, pre, urls, msg, headers=None)[source]

Create a stream messenger (HTTP or TCP) for a single outbound message.

Parameters:
  • hab (Habitat) – Environment to use to look up witness URLs

  • pre (str) – qb64 identifier prefix of recipient to create a messanger for

  • urls (dict) – map of schemes to urls of available endpoints

  • msg (bytes) – bytes of message to send

  • headers (dict) – optional headers to send with HTTP requests

Returns:

witnesser for ensuring full reciepts

Return type:

Optional(TcpWitnesser, HTTPMessenger)

keri.app.apping

KERI keri.app.apping module

class keri.app.apping.Consoler(db=None, console=None, **kwa)[source]

Manages a command-line serial console

Reads lines from a serial console, parses simple movement commands, and echoes feedback. Inherits lifecycle management (enter/recur/exit) from hio.base.doing.Doer.

db

Database instance used by this doer.

Type:

Baser

console

Serial console for input/output.

Type:

serialing.Console

__init__(db=None, console=None, **kwa)[source]

Initializes Consoler with optional database and console.

Parameters:
  • db (Baser, optional) – Database instance. Defaults to a new Baser instance if None.

  • console (serialing.Console, optional) – Serial console instance. Defaults to a new Console instance if None.

  • **kwa – Additional keyword arguments passed to Doer.

enter(*, temp=None)[source]

Opens the serial console resource.

Called by the Doer framework when entering the task context.

Parameters:

temp (bool, optional) – Unused. Reserved for interface compatibility.

Raises:

IOError – If the console cannot be opened.

exit()[source]

Closes the serial console resource.

Called by the Doer framework when leaving the task context.

recur(tyme)[source]

Reads one line from the console and dispatches a movement command.

Recognized commands (matched on the first character, case-insensitive):

  • r / right: turn right

  • l / left: turn left

  • w / walk: walk 1 step

  • s / stop: stop

Parameters:

tyme (float) – Current loop time provided by the Doist scheduler.

Returns:

Always False; signals the Doer to continue recurring.

Return type:

bool

keri.app.challenging

keri.vc.challenging module

class keri.app.challenging.ChallengeHandler(db, signaler)[source]

Handle challenge response peer to peer exn message

__init__(db, signaler)[source]

Initialize peer to peer challenge response messsage

handle(serder, attachments=None)[source]

Do route specific processsing of Challenge response messages

Parameters:
  • serder (Serder) – Serder of the exn challenge response message

  • attachments (list) – list of tuples of pather, CESR SAD path attachments to the exn event

keri.app.challenging.loadHandlers(db, signaler, exc)[source]

Load handlers for the peer-to-peer challenge response protocol

Parameters:
  • db (Baser) – database environment

  • signaler (Signaler) – Signaler for transient messages for the controller of the agent

  • exc (Exchanger) – Peer-to-peer message router

keri.app.configing

keri.app.configing module

class keri.app.configing.Configer(name='conf', base='main', filed=True, mode='r+b', fext='json', human=True, **kwa)[source]

Habitat config file reader/writer.

Extends filing.Filer to support reading and writing a single config file in one of four serialization formats determined by the file extension:

  • .json — HJSON (human-friendly superset of JSON) when human=True; strict JSON with two-space indentation when human=False.

  • .mgpk — MsgPack binary.

  • .cbor — CBOR binary.

human

When True and the file extension is .json, use HJSON for serialization. When False, use strict JSON.

Type:

bool

Example

Expected JSON/HJSON config file structure:

{
"dt": "2021-01-01T00:00:00.000000+00:00",
"nel":
{
    "dt": "2021-01-01T00:00:00.000000+00:00",
    "curls":
    [
    "tcp://localhost:5621/"
    ]
},
"iurls":
[
    "tcp://localhost:5620/?role=peer&name=tam"
],
"durls":
[
    "http://127.0.0.1:7723/oobi/EB...",
    "http://127.0.0.1:7723/oobi/EM..."
],
"wurls":
[
    "http://127.0.0.1:5644/.well-known/keri/oobi/EB..."
]
}
__init__(name='conf', base='main', filed=True, mode='r+b', fext='json', human=True, **kwa)[source]

Initialize and open the config file.

Parameters:
  • name (str) – Leaf name component used to differentiate multiple KERI installations on the same host. Defaults to "conf".

  • base (str) – Optional intermediate directory segment inserted between the head directory and name. An empty string omits this segment. Defaults to "main".

  • filed (bool) – True means .path is a file path; False means .path is a directory path. Defaults to True.

  • mode (str) – File open mode. Defaults to "r+b" (read/write binary without truncation).

  • fext (str) – File extension (without leading dot) used when filed=True. Determines the serialization format. Defaults to "json".

  • human (bool) – When True and fext is "json", use HJSON for put() and get(). Defaults to True.

  • **kwa – Additional keyword arguments forwarded to filing.Filer.

get(human=None)[source]

Read and deserialize the config file.

The deserialization format is determined by the file extension of .path:

  • .json — HJSON when human is truthy, strict JSON otherwise.

  • .mgpk — MsgPack.

  • .cbor — CBOR.

An empty file returns an empty dict without error.

Parameters:

human (bool, optional) – Override self.human for this call. None means use self.human. Defaults to None.

Returns:

Deserialized config data, or an empty dict if the file is

empty.

Return type:

dict

Raises:
  • ValueError – If the file is not open.

  • IOError – If the file extension is not .json, .mgpk, or .cbor.

put(data: dict, human=None)[source]

Serialize data and overwrite the config file.

Truncates the file before writing. The serialization format is determined by the file extension of .path:

  • .json — HJSON when human is truthy, strict JSON otherwise.

  • .mgpk — MsgPack.

  • .cbor — CBOR.

Parameters:
  • data (dict) – Data to serialize and write.

  • human (bool, optional) – Override self.human for this call. None means use self.human. Defaults to None.

Returns:

True on success.

Return type:

bool

Raises:
  • ValueError – If the file is not open.

  • IOError – If the file extension is not .json, .mgpk, or .cbor.

class keri.app.configing.ConfigerDoer(configer, **kwa)[source]

Doer that manages the lifecycle of a Configer instance.

Opens the Configer on enter() if it is not already open, and closes it on exit(), clearing the underlying file if the Configer was opened in temporary mode.

done

Completion flag. True when the doer has finished normally; False when it exited early due to close or abort.

Type:

bool

configer

The managed Configer instance.

Type:

Configer

Properties:
tyme (float): Relative cycle time obtained from the injected

tymth closure.

tymth (callable): Closure returned by Tymist.tymeth(). Calling

it returns the associated Tymist.tyme value.

tock (float): Desired interval in seconds between runs. Zero means

run as soon as possible. Must be non-negative.

__init__(configer, **kwa)[source]

Initialize the doer with a Configer instance.

Parameters:
  • configer (Configer) – The Configer instance to manage.

  • **kwa – Additional keyword arguments forwarded to doing.Doer.

enter(*, temp=None)[source]

Open the Configer if it is not already open.

Parameters:

temp (bool, optional) – Unused. Present for interface compatibility with the base Doer lifecycle. Defaults to None.

exit()[source]

Close the Configer, clearing its file if opened in temp mode.

keri.app.configing.openCF(cls=None, filed=True, **kwa)[source]

Return a context manager that opens a Configer instance.

Thin wrapper around filing.openFiler() with Configer as the default class and filed=True as the default.

Parameters:
  • cls (type, optional) – Filer subclass to instantiate. Defaults to Configer when None.

  • filed (bool) – True means .path is a file path rather than a directory path. Defaults to True.

  • **kwa – Additional keyword arguments forwarded to filing.openFiler().

Returns:

Context manager that yields an open

Configer instance.

Return type:

contextlib.AbstractContextManager

keri.app.delegating

KERI keri.app.delegating module

module for enveloping and forwarding KERI message

class keri.app.delegating.Anchorer(hby, proxy=None, auths=None, **kwa)[source]

Anchorer subclass of DoDoer Sends messages to Delegator of an identifier and wait for the anchoring event to be processed to ensure the inception or rotation event has been approved by the delegator.

Removes all Doers and exits as Done once the event has been anchored.

__init__(hby, proxy=None, auths=None, **kwa)[source]

Initialize Anchorer.

Parameters:
  • hby (Habery) – local controller database for this Anchorer

  • proxy (Hab) – optional proxy Habitat to use for sending messages

  • auths (list[str]) – TOTP authentication codes to send to witnesses to authorize event receipting

complete(prefixer, number, diger=None)[source]

Check for completed delegation for the specific delegation event

Parameters:
  • prefixer (Prefixer) – qb64 identifier prefix of event to check

  • number (Number.huge) – number of event to check

  • diger (Diger) – optional digest of event to verify

Returns:

True if delegation protocol is complete, False otherwise

Return type:

bool

delegation(pre, sn=None, proxy=None, auths=None)[source]

Add witness publishers by prefix and send delegation event to witnesses and place event on the delegation partial witness escrow.

Parameters:
  • pre (str) – qb64 identifier prefix of delegated identifier

  • sn (int) – optional sequence number of event to anchor, defaults to latest event

  • proxy (Hab) – optional proxy Habitat to use for sending messages

  • auths (list[str]) – TOTP authentication codes to send to witnesses to authorize event receipting

escrowDo(tymth, tock=1.0, **kwa)[source]

Process escrows of delegation events waiting to be completed.

Steps involve:
  1. Sending local event with sig to other participants

  2. Waiting for signature threshold to be met.

  3. If elected and delegated identifier, send complete event to delegator

  4. If delegated, wait for delegator’s anchored seal

  5. If elected, send event to witnesses and collect receipts.

  6. Otherwise, wait for fully receipted event

Parameters:
  • tymth (function) – injected function wrapper closure returned by .tymen() of Tymist instance. Calling tymth() returns associated Tymist .tyme.

  • tock (float) – injected initial tock value. Default to 1.0 to slow down processing

processEscrows()[source]

Process delegation escrows

processPartialWitnessEscrow()[source]

Process escrow of delegated events that do not have a full complement of receipts from witnesses yet. When receipting is complete, remove from escrow and cue up a message that the event is complete.

processUnanchoredEscrow()[source]

Process escrow of unanchored delegation events. Message processing will send this local controller’s event to witnesses.

processWitnessPublication()[source]

Process escrow of partially signed delegation events. Message processing waits for publication to the witnesses to complete then completes the delegation.

publishDelegator(pre)[source]

Publish the delegation event to my witnesses.

class keri.app.delegating.DelegateRequestHandler(hby, notifier)[source]

Handler for multisig group inception notification EXN messages

__init__(hby, notifier)[source]
Parameters:
handle(serder, attachments=None)[source]

Do route specific processsing of delegation request messages

Parameters:
  • serder (Serder) – Serder of the exn delegation request message

  • attachments (list) – list of tuples of pather, CESR SAD path attachments to the exn event

keri.app.delegating.delegateRequestExn(hab, delpre, evt, aids=None)[source]
Parameters:
  • hab (Hab) – database environment of sender

  • delpre (str) – qb64 AID of delegator

  • evt (bytes) – serialized and signed event requiring delegation approval

  • aids (list) – list of multisig AIDs participating

Returns:

keri.app.delegating.loadHandlers(hby, exc, notifier)[source]

Load handlers for the peer-to-peer delegation protocols

Parameters:
  • hby (Habery) – Database and keystore for environment

  • exc (Exchanger) – Peer-to-peer message router

  • notifier (Notifier) – Outbound notifications

keri.app.directing

KERI keri.app.directing module

simple direct mode demo support classes

class keri.app.directing.Directant(hab, server, verifier=None, exchanger=None, doers=None, **kwa)[source]

Subclass of DoDoer that accepts TCP connections and manages Reactants.

Responds to initiated connections from a remote Director by creating and running a Reactant per connection and scheduling it as a live doer. Connections that are cut off or whose timer has expired are closed and their Reactants removed. Only one scheduled doer is added directly: serviceDo.

Part of the scheduling hierarchy: Doist -> DoDoer -> … -> Doers. Inherits the tyme/tymth injected-dependency system from DoDoer; call .wind() to inject a Tymist before use.

hab

Local controller’s Habitat instance.

Type:

Habitat

verifier

Optional Verifier for TEL context processing. None if TEL processing is not required.

Type:

Verifier

exchanger

Optional Exchanger for exn message processing. None if not required.

server

TCP server instance, operated by a separate doer.

Type:

TCP Server

rants

Active Reactant instances keyed by connection address.

Type:

dict

done

Completion state set by DoDoer. True means completed normally. False or None means incomplete.

Type:

bool

opts

Injected options passed to the .do generator.

Type:

dict

doers

Scheduled Doer instances or generator functions.

Type:

list

__init__(hab, server, verifier=None, exchanger=None, doers=None, **kwa)[source]

Initialize instance and extend doers with serviceDo.

Parameters:
  • hab (Habitat) – Local controller’s Habitat instance.

  • server (TCP Server) – TCP server instance used to accept and track inbound connections.

  • verifier (Verifier, optional) – Verifier instance providing TEL context. Forwarded to each spawned Reactant. Defaults to None.

  • exchanger – optional Exchanger instance for exn message processing. Forwarded to each spawned Reactant. Defaults to None.

  • doers (list, optional) – Initial list of Doer instances or generator functions to schedule. serviceDo is always appended. Defaults to None.

  • **kwa – Additional keyword arguments forwarded to DoDoer.__init__.

closeConnection(ca)[source]

Flush, close, and clean up a connection and its associated Reactant.

Flushes pending send bytes on the remoter before removing it from the server. If a Reactant exists for the address, it is closed and removed from the doers list.

Parameters:

ca (tuple) – Connection address key used in server.ixes and rants.

serviceDo(tymth=None, tock=0.0, **opts)[source]

Doer that services inbound connections and manages Reactant lifecycle.

Each cycle iterates server.ixes. For each connection address:

  • If the connection is cut off, closeConnection is called.

  • If no Reactant exists for the address yet, one is created and extended into the running doers via self.extend.

  • If the connection has a positive tymeout and its timer has expired, closeConnection is called.

Parameters:
  • tymth (callable, optional) – Injected tymth closure from the Doist. Defaults to None.

  • tock (float, optional) – Injected initial tock value in seconds. Defaults to 0.0.

  • **opts – Additional injected options from the Doist.

Yields:

None – Yields control back to the scheduler on each cycle.

wind(tymth)[source]

Inject a new tymth closure and propagate it to the TCP server.

Overrides DoDoer.wind to ensure server.wind is called whenever the Tymist dependency changes.

Parameters:

tymth (callable) – Closure returned by Tymist.tymeth() that, when called, returns the current Tymist.tyme.

class keri.app.directing.Director(hab, client, **kwa)[source]

Base class for Direct Mode KERI Controller Doer with habitat and TCP client.

hab

Local controller’s Habitat instance.

Type:

Habitat

client

hio TCP client instance. Assumed to be operated by a separate doer.

Type:

Client

__init__(hab, client, **kwa)[source]

Initialize instance.

Parameters:
  • tymist (Tymist) – Tymist instance.

  • tock (float) – Seconds initial value of .tock.

  • hab (Habitat) – Habitat instance.

  • client (Client) – TCP Client instance. Assumes opened/closed elsewhere.

sendOwnEvent(sn)[source]

Utility to send own event at sequence number sn

sendOwnInception()[source]

Utility to send own inception on client

wind(tymth)[source]

Inject new tymist.tymth as new ._tymth. Changes tymist.tyme base. Updates winds .tymer .tymth

class keri.app.directing.Reactant(hab, remoter, verifier=None, exchanger=None, doers=None, **kwa)[source]

Subclass of DoDoer that processes incoming KERI message streams from a TCP remoter.

Wires together a TCP remoter, a Kevery (and optionally a Tevery), a Revery, and a Parser into three continuously-scheduled doers: msgDo, cueDo, and escrowDo. Each Reactant instance owns its own Kevery and parser bound to the remoter’s receive buffer, so multiple simultaneous remote connections each get independent processing state. Part of the scheduling hierarchy: Doist -> DoDoer -> … -> Doers. Inherits the tyme/tymth injected-dependency system from DoDoer; call .wind() to inject a Tymist before use.

hab

Local controller’s Habitat instance.

Type:

Habitat

verifier

Optional Verifier instance for TEL context. None if TEL processing is not required.

Type:

Verifier

exchanger

Optional Exchanger instance for exn message processing. None if not required.

remoter

TCP remoter used for both receive and transmit.

Type:

TCP Remoter

kevery

Event processor for incoming key events.

Type:

Kevery

tevery

Event processor for incoming transaction events. None when verifier is None.

Type:

Tevery

parser

Stream parser bound to remoter.rxbs.

Type:

Parser

done

Completion state set by DoDoer. True means completed normally. False or None means incomplete.

Type:

bool

opts

Injected options passed to the .do generator.

Type:

dict

doers

Scheduled Doer instances or generator functions.

Type:

list

__init__(hab, remoter, verifier=None, exchanger=None, doers=None, **kwa)[source]

Initialize instance and extend doers with msgDo, cueDo, escrowDo.

A Revery is always created and its router is registered on both kevery and, when verifier is provided, tevery.

Parameters:
  • hab (Habitat) – Local controller’s Habitat instance.

  • remoter (TCP Remoter) – TCP remoter used for both receive and transmit.

  • verifier (Verifier, optional) – Verifier instance providing TEL context. When provided a Tevery is created, bound to the parser, and its reply routes are registered. Defaults to None.

  • exchanger – optional Exchanger instance for exn message processing. Defaults to None.

  • doers (list, optional) – Initial list of Doer instances or generator functions to schedule. msgDo, cueDo, and escrowDo are always appended. Defaults to None.

  • **kwa – Additional keyword arguments forwarded to DoDoer.__init__.

cueDo(tymth=None, tock=0.0, **opts)[source]

Doer that drains kevery.cues and sends resulting receipt messages.

In each cycle, iterates hab.processCuesIter over kevery.cues. Each produced message is coerced to bytearray if it arrives as a list of chunks, then transmitted via sendMessage. Yields after each message to throttle output, then yields again at end of each cycle.

Parameters:
  • tymth (callable, optional) – Injected tymth closure from the Doist. Defaults to None.

  • tock (float, optional) – Injected initial tock value in seconds. Defaults to 0.0.

  • **opts – Additional injected options from the Doist.

Yields:

None – Yields control back to the scheduler on each cycle.

Returns:

Always False. Only reached on forced close.

Return type:

bool

escrowDo(tymth=None, tock=0.0, **opts)[source]

Doer that processes escrowed events on every cycle.

Calls kevery.processEscrows() each cycle and, when tevery is present, also calls tevery.processEscrows().

Parameters:
  • tymth (callable, optional) – Injected tymth closure from the Doist. Defaults to None.

  • tock (float, optional) – Injected initial tock value in seconds. Defaults to 0.0.

  • **opts – Additional injected options from the Doist.

Yields:

None – Yields control back to the scheduler on each cycle.

Returns:

Always False. Only reached on forced close.

Return type:

bool

msgDo(tymth=None, tock=0.0, **opts)[source]

Doer that continuously parses the incoming TCP message stream.

Delegates to Parser.parsator, which reads from remoter.rxbs and feeds events to kevery (and tevery when present).

Parameters:
  • tymth (callable, optional) – Injected tymth closure from the Doist. Defaults to None.

  • tock (float, optional) – Injected initial tock value in seconds. Defaults to 0.0.

  • **opts – Additional injected options from the Doist.

Yields:

None – Yields control back to the scheduler on each cycle.

Returns:

Done state from Parser.parsator. Only reached on forced close.

Return type:

bool

sendMessage(msg, label='')[source]

Transmit a message over the TCP remoter and log it.

Parameters:
  • msg (bytes) – Serialized message to transmit.

  • label (str, optional) – Descriptive label used in the log line. Defaults to empty string.

wind(tymth)[source]

Inject a new tymth closure and propagate it to the TCP remoter.

Overrides DoDoer.wind to ensure remoter.wind is called whenever the Tymist dependency changes.

Parameters:

tymth (callable) – Closure returned by Tymist.tymeth() that, when called, returns the current Tymist.tyme.

class keri.app.directing.Reactor(hab, client, verifier=None, exchanger=None, direct=True, doers=None, **kwa)[source]

Reactor Subclass of DoDoer with doers list from do generator methods: .msgDo, .cueDo, and .escrowDo. Enables continuous scheduling of doers (do generator instances or functions)

Implements Doist like functionality to allow nested scheduling of doers. Each DoDoer runs a list of doers like a Doist but using the tyme from its injected tymist as injected by its parent DoDoer or Doist.

Scheduling hierarchy: Doist->DoDoer…->DoDoer->Doers

Inherited Attributes:
.done is Boolean completion state:

True means completed Otherwise incomplete. Incompletion maybe due to close or abort.

.opts is dict of injected options for its generator .do .doers is list of Doers or Doer like generator functions

hab

Local controller’s Habitat instance.

Type:

Habitat

client

TCP client used for both receive and transmit.

Type:

TCP Client

verifier

Optional Verifier instance for TEL context. None if TEL processing is not required.

Type:

Verifier

exc

Optional Exchanger instance for peer-to-peer key-event exchange messages. None if not required.

direct

True means direct mode; cue’d receipts are processed immediately. False means indirect mode; cue’d receipts are skipped.

Type:

bool

kevery

Event processor for incoming key events.

Type:

Kevery

tvy

Event processor for incoming transaction events. None when verifier is None.

Type:

Tevery

parser

Stream parser bound to client.rxbs.

Type:

Parser

done

Completion state set by DoDoer. True means completed normally. False or None means incomplete.

Type:

bool

opts

Injected options passed to the .do generator.

Type:

dict

doers

Scheduled Doer instances or generator functions.

Type:

list

Inherited Properties:
.tyme is float relative cycle time of associated Tymist .tyme obtained

via injected .tymth function wrapper closure.

.tymth is function wrapper closure returned by Tymist .tymeth() method.

When .tymth is called it returns associated Tymist .tyme. .tymth provides injected dependency on Tymist tyme base.

.tock is float, desired time in seconds between runs or until next run,

non negative, zero means run asap

Properties:

Inherited Methods:

.wind injects ._tymth dependency from associated Tymist to get its .tyme

.__call__ makes instance callable

Appears as generator function that returns generator

.do is generator method that returns generator .enter is enter context action method .recur is recur context action method or generator method .clean is clean context action method .exit is exit context method .close is close context method .abort is abort context method

Overidden Methods:

Hidden:
._tymth is injected function wrapper closure returned by .tymen() of

associated Tymist instance that returns Tymist .tyme. when called.

._tock is hidden attribute for .tock property

__init__(hab, client, verifier=None, exchanger=None, direct=True, doers=None, **kwa)[source]

Initialize instance and extend doers with msgDo, escrowDo, cueDo.

Parameters:
  • hab (Habitat) – Local controller’s Habitat instance.

  • client (TCP Client) – TCP client used for both receive and transmit.

  • verifier (Verifier, optional) – Verifier instance providing TEL context. When provided a Tevery is created and bound to the parser. Defaults to None.

  • exchanger – optional Exchanger instance for exn message processing. Defaults to None.

  • direct (bool, optional) – True to process cue’d receipts in direct mode. False to skip cue’d receipt processing. Defaults to True.

  • doers (list, optional) – Initial list of Doer instances or generator functions to schedule. msgDo, escrowDo, and cueDo are always appended. Defaults to None.

  • **kwa – Additional keyword arguments forwarded to DoDoer.__init__.

cueDo(tymth=None, tock=0.0, **opts)[source]

Doer that drains kevery.cues and sends resulting receipt messages.

In each cycle, iterates hab.processCuesIter over kevery.cues and transmits each produced message via sendMessage. Yields after each message to throttle output, then yields again at end of each cycle.

Parameters:
  • tymth (callable, optional) – Injected tymth closure from the Doist. Defaults to None.

  • tock (float, optional) – Injected initial tock value in seconds. Defaults to 0.0.

  • **opts – Additional injected options from the Doist.

Yields:

None – Yields control back to the scheduler on each cycle.

Returns:

Always False. Only reached on forced close.

Return type:

bool

escrowDo(tymth=None, tock=0.0, **opts)[source]

Doer that processes escrowed events on every cycle.

Calls kevery.processEscrows() each cycle and, when tvy is present, also calls tvy.processEscrows().

Parameters:
  • tymth (callable, optional) – Injected tymth closure from the Doist. Defaults to None.

  • tock (float, optional) – Injected initial tock value in seconds. Defaults to 0.0.

  • **opts – Additional injected options from the Doist.

Yields:

None – Yields control back to the scheduler on each cycle.

Returns:

Always False. Only reached on forced close.

Return type:

bool

msgDo(tymth=None, tock=0.0, **opts)[source]

Doer that continuously parses the incoming TCP message stream.

Delegates to Parser.parsator, which reads from client.rxbs and feeds events to kevery (and tvy when present).

Parameters:
  • tymth (callable, optional) – Injected tymth closure from the Doist. Defaults to None.

  • tock (float, optional) – Injected initial tock value in seconds. Defaults to 0.0.

  • **opts – Additional injected options from the Doist.

Yields:

None – Yields control back to the scheduler on each cycle.

Returns:

Done state from Parser.parsator. Only reached on forced close.

Return type:

bool

sendMessage(msg, label='')[source]

Transmit a message over the TCP client and log it.

Parameters:
  • msg (bytes) – Serialized message to transmit.

  • label (str, optional) – Descriptive label used in the log line. Defaults to empty string.

wind(tymth)[source]

Inject a new tymth closure and propagate it to the TCP client.

Overrides DoDoer.wind to ensure client.wind is called whenever the

Tymist dependency changes.

Parameters:

tymth (callable) – Closure returned by Tymist.tymeth() that, when called, returns the current Tymist.tyme.

keri.app.directing.runController(doers, expire=0.0)[source]

Utiitity Function to create doist to run doers

keri.app.forwarding

KERI keri.app.forwarding module

module for enveloping and forwarding KERI message

class keri.app.forwarding.ForwardHandler(hby, mbx)[source]

Handler for forward exn messages used to envelope other KERI messages intended for another receiver. This handler acts as a mailbox for other identifiers and stores the messages in a local database.

Example message:

{
   "v": "KERI10JSON00011c_",                               // KERI Version String
   "t": "exn",                                             // peer to peer message ilk
   "dt": "2020-08-22T17:50:12.988921+00:00"
   "r": "/fwd",
   "q": {
      "pre": "EEBp64Aw2rsjdJpAR0e2qCq3jX7q7gLld3LjAwZgaLXU",
      "topic": "delegate"
    }
   "a": '{
      "v":"KERI10JSON000154_",
      "t":"dip",
      "d":"Er4bHXd4piEtsQat1mquwsNZXItvuoj_auCUyICmwyXI",
      "i":"Er4bHXd4piEtsQat1mquwsNZXItvuoj_auCUyICmwyXI",
      "s":"0",
      "kt":"1",
      "k":["DuK1x8ydpucu3480Jpd1XBfjnCwb3dZ3x5b1CJmuUphA"],
      "n":"EWWkjZkZDXF74O2bOQ4H5hu4nXDlKg2m4CBEBkUxibiU",
      "bt":"0",
      "b":[],
      "c":[],
      "a":[],
      "di":"Et78eYkh8A3H9w6Q87EC5OcijiVEJT8KyNtEGdpPVWV8"
   }
}-AABAA1o61PgMhwhi89FES_vwYeSbbWnVuELV_jv7Yv6f5zNiOLnj1ZZa4MW2c6Z_vZDt55QUnLaiaikE-d_ApsFEgCA
__init__(hby, mbx)[source]
Parameters:
  • hby (Habery) – database environment

  • mbx (Mailboxer) – message storage for store and forward

handle(serder, attachments=None)[source]

Do route specific processsing of IPEX protocol exn messages

Parameters:
  • serder (Serder) – Serder of the IPEX protocol exn message

  • attachments (list) – list of tuples of root pathers and CESR SAD path attachments to the exn event

class keri.app.forwarding.Poster(hby, mbx=None, evts=None, cues=None, **kwa)[source]

DoDoer that wraps any KERI event (KEL, TEL, Peer to Peer) in a /fwd exn envelope and delivers them to one of the target receiver’s witnesses for store and forward to the intended receiver

deliverDo(tymth=None, tock=0.0, **kwa)[source]
Returns: doifiable Doist compatible generator method that processes

a queue of messages and envelopes them in a fwd message and sends them to one of the witnesses of the receiver for store and forward.

Usage:

add result of doify on this method to doers list

send(dest, topic, serder, src=None, hab=None, attachment=None)[source]

Utility function to queue a msg on the Poster’s buffer for enveloping and forwarding to a witness

Parameters:
  • src (str) – qb64 identifier prefix of sender

  • hab (Hab) – Sender identifier habitat

  • dest (str)

  • topic (str) – topic of message

  • serder (Serder)

  • attachment (bytes) – attachment bytes

sendEventToDelegator(sender, hab, fn=0)[source]

Returns generator for sending event and waiting until send is complete

sent(said)[source]

Check if message with given SAID was sent

Parameters:

said (str) – qb64 SAID of message to check for

class keri.app.forwarding.StreamPoster(hby, recp, src=None, hab=None, mbx=None, topic=None, headers=None, essr=False, **kwa)[source]

DoDoer that wraps any KERI event (KEL, TEL, Peer to Peer) in a /fwd exn envelope and delivers them to one of the target receiver’s witnesses for store and forward to the intended receiver

deliver()[source]
Returns: doifiable Doist compatible generator method that processes

a queue of messages and envelopes them in a fwd message and sends them to one of the witnesses of the receiver for store and forward.

Usage:

add result of doify on this method to doers list

send(serder, attachment=None)[source]

Utility function to queue a msg on the Poster’s buffer for enveloping and forwarding to a witness

Parameters:
  • serder (Serder)

  • attachment (bytes) – attachment bytes

keri.app.forwarding.introduce(hab, wit)[source]

Clone and return hab KEL if lastest event has not been receipted by wit

Check to see if the target witness has already provided a receipt for the latest event for the identifier of hab, clone the KEL and return it as a bytearray so it can be sent to the target.

Parameters:
  • hab (Hab) – local environment for the identifier to propagate

  • wit (str) – qb64 identifier prefix of the receiver of KEL if not already receipted

Returns:

cloned KEL of hab

Return type:

bytearray

keri.app.grouping

KERI keri.app.grouping module

module for enveloping and forwarding KERI message

class keri.app.grouping.Counselor(hby, swain=None, proxy=None, **kwa)[source]

Multisig event handling coordinator for group multisig events including delegation events. Handles escrows for partially signed multisig events, delegation events, and witness receipts.

Doers:
  • swain (Anchorer): handles delegation anchoring

  • witq (WitnessInquisitor): queries witnesses for receipts

  • witDoer (Receiptor): sends witness receipts

  • escrowDo: processes escrows of group multisig identifiers waiting to be completed.

__init__(hby, swain=None, proxy=None, **kwa)[source]

Initialize Counselor.

Parameters:
  • hby (Habery) – database environment for local Habs

  • swain (Anchorer) – optional Anchorer for delegation anchoring

  • proxy (Hab) – optional proxy Hab to use for delegation anchoring if not using local Hab

complete(prefixer, number, diger=None)[source]

Check for completed multsig protocol for the specific event

Parameters:
  • prefixer (Prefixer) – qb64 identifier prefix of event to check

  • number (Number) – sequence number of event to check

  • diger (Diger) – optional digest of event to verify

Returns:

escrowDo(tymth, tock=1.0, **kwa)[source]

Process escrows of group multisig identifiers waiting to be completed.

Steps involve:
  1. Sending local event with sig to other participants

  2. Waiting for signature threshold to be met.

  3. If elected and delegated identifier, send complete event to delegator

  4. If delegated, wait for delegator’s anchored seal

  5. If elected, send event to witnesses and collect receipts.

  6. Otherwise, wait for fully receipted event

Parameters:
  • tymth (function) – injected function wrapper closure returned by .tymen() of Tymist instance. Calling tymth() returns associated Tymist .tyme.

  • tock (float) – injected initial tock value. Default to 1.0 to slow down processing

processDelegateEscrow()[source]

Process escrow of delegate group multisig identifiers that are waiting for delegator approval of a recent establishment event.

processEscrows()[source]

Process group multisig event escrows.

processPartialSignedEscrow()[source]

Process escrow of partially signed multisig group KEL events. Message processing will send this local controllers signature to all other participants then this escrow waits for signatures from all other participants

processPartialWitnessEscrow()[source]

Process escrow of group multisig events that do not have a full complement of receipts from witnesses yet. When receipting is complete, remove from escrow and cue up a message that the event is complete.

start(ghab, prefixer, number, diger)[source]

Begin processing of escrowed group multisig identifier

Escrow identifier for multisigs, witness receipts and delegation anchor

Parameters:
  • ghab (Hab) – group Habitat

  • prefixer (Prefixer) – prefixer of group identifier

  • number (Number) – number of event of group identifier

  • diger (Diger) – diger of event of group identifier

class keri.app.grouping.Multiplexor(hby, notifier)[source]

Multiplexor (mux) is responsible for coordinating peer-to-peer messages between group multisig participants

When new messages arrive the Mux will associate the SAID of the embedded messages with the exn message said as well as the sender. This will allow the controller of the participant in the group multisig to have knowledge of who has sent what messages and whether they match. In addition, if the controller of the local participant has already approved the messages embedded in this exn, the messages will be passed thru a non-local parser.

hby

database environment for local Habs

Type:

habbing.Habery

rtr

routes reply ‘rpy’ messages

Type:

Router

rvy

factory that processes reply ‘rpy’ messages

Type:

Revery

exc

processor and router for peer-to-peer msgs

Type:

Exchanger

kvy

factory for local processing of local event msgs

Type:

Kevery

psr

parses local messages for .kvy .rvy

Type:

Parser

notifier

stores notices for numan consumption

Type:

notifying.Notifier

Parameters

hby (habbing.Habery): database environment for local Habs notifier (notifying.Notifier): stores notices for numan consumption

__init__(hby, notifier)[source]

Create Multiplexor for local database and Habs

Parameters:
add(serder)[source]

Process /multisig message by associating the exn with the SAID of the embedded event section

Adds the exn message contained in serder to the set of messages received for a given set of embedded events. Ensures this is a /multisig message with the correct properties and then stores the SAID of the exn message and the prefix of the sender associated with the SAID of the embedded event section. Also sends the controller of the local participant a notice.

This method will extract and parse the embedded events if the local participant has already approved the events so that any addition signatures can be processed.

Parameters:

serder (SerderKERI) – peer-to-peer exn “/multisig” message to coordinate from other participants

Returns:

class keri.app.grouping.MultisigNotificationHandler(resource, mux)[source]

Handler for multisig coordination EXN messages

__init__(resource, mux)[source]

Create an exn handler for multisig messages

Parameters:
  • resource

  • mux

handle(serder, attachments=None)[source]

Do route specific processsing of multisig exn messages

Parameters:
  • serder (Serder) – Serder of the exn multisig message

  • attachments (list) – list of tuples of pather, CESR SAD path attachments to the exn event

keri.app.grouping.loadHandlers(exc, mux)[source]

Load handlers for the peer-to-peer distributed group multisig protocol

Parameters:
  • exc (Exchanger) – Peer-to-peer message router

  • mux (Multiplexor) – Multisig communication coordinator

keri.app.grouping.multisigExn(ghab, exn)[source]

Create a peer to peer message to propose a credential issuance from a multisig group identifier

Either rot or ixn are required but not both

Parameters:
  • ghab (GroupHab) – identifier Hab for ensorsing the message to send

  • exn (bytes) – CESR stream of serialized echange message, with signatures

Returns:

(Serder, bytes): Serder of exn message and CESR attachments

Return type:

tuple

keri.app.grouping.multisigInceptExn(hab, smids, rmids, icp, delegator=None)[source]
Parameters:
  • hab (Hab) – habitat of local multisig member AID

  • smids (list) – list of qb64 AIDs of members with signing authority

  • rmids (list) – list of qb64 AIDs of members with rotation authority

  • icp (bytes) – serialized inception event with CESR streamed attachments

  • delegator (str) – qb64 AID of Delegator is group multisig is a delegated AID

Returns:

(Serder, bytes): Serder of exn message and CESR attachments

Return type:

tuple

keri.app.grouping.multisigInteractExn(ghab, aids, ixn)[source]

Create a peer to peer message to propose a multisig group interaction event

Parameters:
  • ghab (GroupHab) – group Hab to endorse the message

  • aids (list) – qb64 identifier prefixes to include in the interaction event

  • ixn (bytes) – serialized interaction event with CESR streamed attachments

Returns:

(Serder, bytes): Serder of exn message and CESR attachments

Return type:

tuple

keri.app.grouping.multisigIssueExn(ghab, acdc, iss, anc)[source]

Create a peer to peer message to propose a credential creation from a multisig group identifier

Either rot or ixn are required but not both

Parameters:
  • ghab (GroupHab) – identifier Hab for ensorsing the message to send

  • acdc (bytes) – serialized Credential

  • iss (bytes) – CESR stream of serialized and TEL issuance event

  • anc (bytes) – CESR stream of serialized and signed anchoring event anchoring creation

Returns:

(Serder, bytes): Serder of exn message and CESR attachments

Return type:

tuple

keri.app.grouping.multisigRegistryInceptExn(ghab, usage, vcp, anc)[source]

Create a peer to peer message to propose a credential registry inception from a multisig group identifier

Either rot or ixn are required but not both

Parameters:
  • ghab (GroupHab) – identifier Hab for ensorsing the message to send

  • usage (str) – human readable reason for creating the credential registry

  • vcp (bytes) – serialized Credentials registry inception event

  • anc (bytes) – CESR stream of serialized and signed event anchoring registry inception event

Returns:

(Serder, bytes): Serder of exn message and CESR attachments

Return type:

tuple

keri.app.grouping.multisigRevokeExn(ghab, said, rev, anc)[source]

Create a peer to peer message to propose a credential revocation from a multisig group identifier

Either rot or ixn are required but not both

Parameters:
  • ghab (GroupHab) – identifier Hab for ensorsing the message to send

  • said (str) – qb64 SAID of credential being revoked

  • rev (bytes) – CESR stream of serialized and TEL revocation event

  • anc (bytes) – CESR stream of serialized and signed anchoring event anchoring revocation

Returns:

(Serder, bytes): Serder of exn message and CESR attachments

Return type:

tuple

keri.app.grouping.multisigRotateExn(ghab, smids, rmids, rot)[source]
Parameters:
  • ghab (GroupHab) – habitat of group multisig AID

  • smids (list) – list of qb64 AIDs of members with signing authority

  • rmids (list) – list of qb64 AIDs of members with rotation authority

  • rot (bytes) – serialized rotation event with CESR streamed attachments

Returns:

(Serder, bytes): Serder of exn message and CESR attachments

Return type:

tuple

keri.app.grouping.multisigRpyExn(ghab, rpy)[source]

Create a peer to peer message to propose a credential revocation from a multisig group identifier

Either rot or ixn are required but not both

Parameters:
  • ghab (GroupHab) – identifier Hab for ensorsing the message to send

  • rpy (bytes) – CESR stream of serialized and reply event

Returns:

(Serder, bytes): Serder of exn message and CESR attachments

Return type:

tuple

keri.app.habbing

KERI keri.app.habbing module

class keri.app.habbing.BaseHab(ks, db, cf, mgr, rtr, rvy, kvy, psr, *, name='test', ns=None, pre=None, temp=False)[source]

Hab class provides a given identifier controller’s local resource environment i.e. hab or habitat. Includes dependency injection of database, keystore, configuration file as well as Kevery and key store Manager.

ks

Injected. lmdb key store.

Type:

Keeper

db

Injected. lmdb data base for KEL etc.

Type:

basing.Baser

cf

Injected. Config file instance.

Type:

Configer

mgr

Injected. Creates and rotates keys in key store.

Type:

Manager

rtr

Injected. Routes reply rpy messages.

Type:

Router

rvy

Injected. Factory that processes reply rpy messages.

Type:

Revery

kvy

Injected. Factory for local processing of local event msgs.

Type:

Kevery

psr

Injected. Parses local messages for .kvy and .rvy.

Type:

Parser

name

Alias of controller.

Type:

str

pre

qb64 prefix of own local controller, or None if new.

Type:

str

temp

True means testing; use weak level when salty algo for stretching in key creation for incept and rotate of keys for this hab.pre.

Type:

bool

inited

True means fully initialized wrt databases, False means not yet fully initialized.

Type:

bool

delpre

Delegator prefix if any, else None.

Type:

str or None

__init__(ks, db, cf, mgr, rtr, rvy, kvy, psr, *, name='test', ns=None, pre=None, temp=False)[source]

Initialize instance.

Parameters:
  • ks (Keeper) – lmdb key store.

  • db (basing.Baser) – lmdb data base for KEL etc.

  • cf (Configer) – config file instance.

  • mgr (Manager) – creates and rotates keys in key store.

  • rtr (Router) – routes reply rpy messages.

  • rvy (Revery) – factory that processes reply rpy messages.

  • kvy (Kevery) – factory for local processing of local event msgs.

  • psr (Parser) – parses local messages for .kvy and .rvy.

  • name (str) – alias name for local controller of habitat.

  • pre (str or None) – qb64 identifier prefix of own local controller, else None.

  • temp (bool) – True means testing — use weak level when salty algo for stretching in key creation for incept and rotate of keys for this hab.pre.

property accepted

True if own prefix has been accepted into the local KEL.

Returns:

True if .pre is in .kevers, False otherwise.

Return type:

bool

decrypt(ser, verfers=None, **kwa)[source]

Decrypt given serialization ser using appropriate keys. Uses provided verfers or .kever.verfers to look up keys to decrypt.

Parameters:
  • ser (str, bytes, bytearray, or memoryview) – serialization to decrypt.

  • verfers (list[Verfer] or None) – Verfer instances to get public verifier keys to look up and convert to private decryption keys. None means use .kever.verfers. When group and verfers is not None, the provided verfers must be .kever.verfers.

Returns:

decrypted serialization.

Return type:

bytes

endorse(serder, last=False, framed=False, nested=False, gvrsn=(1, 0), genusify=False)[source]

Return msg with own endorsement of msg from serder with attached signature groups based on own pre transferable or non-transferable.

Parameters::

serder (Serder): instance of msg. last (bool): Affects which signature group code messagize will use

the seal type provided here, True means provide SealLast so messagize uses TransLastIdxSigGroups

Query messages should always use SealLast.

False means provide SealEvent so messagize uses TransIdxSigGroups

framed (bool): True means may assume each message plus its attachments

is isolated as frame when parsing so do not need attachment group when messagizing

False means may not assume eash message plus its attachments

is isolated as frame when parsing so do need attachment group when messagizing

nested (bool): True means messagize for non-top level

This forces non-native serializion to be embedded in non-native group code

False means messagize for top level of stream.

This allows bare non-native serialization of message

gvrsn (Versionage): CESR Genus version for attachment group codes or

nesting group code (useful when serder.gvrsn < 2) gvrsn = max(svrsn, gvrsn) where svrsn = serder.gvrsn

if serder.gvrsn else serder.pvrsn

genusify (bool): True means prepend genus version code from gvrsn before

serder to override default stream genus version

False means do nothing

Returns::

bytearray: endorsed message with attached signatures from messagize.

endsFor(pre)[source]

Load authorized endpoints for the provided AID.

Parameters:

pre (str) – qb64 aid for which to load ends.

Returns:

nested dict of role -> eid -> scheme -> endpoint.

Return type:

dict

exchange(*, receiver='', prior='', xid='', route='', modifiers=None, attributes=None, stamp=None, version=(1, 0), pvrsn=None, gvrsn=None, kind='JSON', framed=False, nested=False, genusify=False, embeds=None, eid=None, save=False)[source]

Build and return a signed exn message, optionally saving it to own db.

Parameters::

sender (str): qb64 of sender identifier (AID) receiver (str): qb64 of receiver identifier (AID) xid (str): qb64 of exchange ID which is SAID of exchange inception ‘xip’

if any

prior (str): qb64 of prior exchange event including ‘xip” if any route (str): ‘/’ delimited path identifier of data flow handler

(behavior) to processs the reply if any (equivalent of url path to resource)

modifiers (dict): modifiers field map (equvalent of http query string) attributes (dict): attributes field map (payload body) stamp (str): date-time-stamp RFC-3339 profile of ISO-8601 datetime of

creation of message or data, default is now.

version (Versionage): KERI protocol default version if psvrsn is None pvrsn (Versionage): KERI protocol version gvrsn (Versionage): CESR Genus version for attachment group codes or

nesting group code (useful when serder.gvrsn < 2) gvrsn = max(svrsn, gvrsn) where svrsn = serder.gvrsn

if serder.gvrsn else serder.pvrsn

kind (str): serialization for key event message

one of Kinds (“json”,”cbor”,”mgpk”,”cesr”)

framed (bool): True means may assume each message plus its attachments

is isolated as frame when parsing so do not need attachment group when messagizing

False means may not assume eash message plus its attachments

is isolated as frame when parsing so do need attachment group when messagizing

nested (bool): True means messagize for non-top level

This forces non-native serializion to be embedded in non-native group code

False means messagize for top level of stream.

This allows bare non-native serialization of message

genusify (bool): True means prepend genus version code from gvrsn before

serder to override default stream genus version

False means do nothing

embeds (dict or None): embedded message serders if any. eid (str or None): qb64 of endpoint provider identifier if any. save (bool): True means process local copy into db after building.

Returns::

bytearray: signed exchange message with count code and receipt couples (pre+cig).

fetchEnd(cid: str, role: str, eid: str)[source]

Return the endpoint record for the given controller, role, and endpoint provider.

Parameters:
  • cid (str) – qb64 identifier prefix of controller.

  • role (str) – endpoint role.

  • eid (str) – qb64 identifier prefix of endpoint provider.

Returns:

endpoint record instance, or None if not found.

Return type:

EndpointRecord or None

fetchEndAllowed(cid: str, role: str, eid: str)[source]

Return whether eid is allowed as endpoint provider for cid in role.

Parameters:
  • cid (str) – qb64 identifier prefix of controller authorizing endpoint provider eid in role.

  • role (str) – endpoint role such as controller, witness, watcher, etc.

  • eid (str) – qb64 identifier prefix of endpoint provider in role.

Returns:

True if eid is allowed, False if not, None if no endpoint record exists.

Return type:

bool or None

fetchEndAuthzed(cid: str, role: str, eid: str)[source]

Return whether eid is authorized (enabled or allowed) as endpoint provider for cid in role.

Parameters:
  • cid (str) – qb64 identifier prefix of controller authorizing endpoint provider eid in role.

  • role (str) – endpoint role such as controller, witness, watcher, etc.

  • eid (str) – qb64 identifier prefix of endpoint provider in role.

Returns:

True if eid is enabled or allowed, False if neither, None if no endpoint record exists.

Return type:

bool or None

fetchEndEnabled(cid: str, role: str, eid: str)[source]

Return whether eid is enabled as endpoint provider for cid in role.

Parameters:
  • cid (str) – qb64 identifier prefix of controller authorizing endpoint provider eid in role.

  • role (str) – endpoint role such as controller, witness, watcher, etc.

  • eid (str) – qb64 identifier prefix of endpoint provider in role.

Returns:

True if eid is enabled, False if not, None if no endpoint record exists.

Return type:

bool or None

fetchLoc(eid: str, scheme: str = 'http')[source]

Return the location record for the given endpoint provider and scheme.

Parameters:
  • eid (str) – qb64 identifier prefix of endpoint provider.

  • scheme (str) – url scheme. Default is Schemes.http.

Returns:

location record instance, or None if not found.

Return type:

LocationRecord or None

fetchRoleUrls(cid: str, *, role: str = '', scheme: str = '', eids=None, enabled: bool = True, allowed: bool = True)[source]

Return nested dicts of role -> eid -> scheme -> url for the given cid.

Parameters:
  • cid (str) – qb64 identifier prefix of the controller authorizing endpoint provider eid in role.

  • role (str) – endpoint role filter (e.g. controller, witness, watcher). Empty string means all roles.

  • scheme (str) – url scheme filter. Empty string means all schemes.

  • eids (list or None) – when provided, restrict results to only eids in this list.

  • enabled (bool) – True means include enabled endpoint providers.

  • allowed (bool) – True means include allowed endpoint providers.

Returns:

nested Mict keyed as rurls[role][eid][scheme],

where each leaf value is a url string.

Return type:

hicting.Mict

fetchUrl(eid: str, scheme: str = 'http')[source]

Return the url for the endpoint provider given by eid.

Parameters:
  • eid (str) – qb64 identifier prefix of endpoint provider.

  • scheme (str) – url scheme. Default is Schemes.http.

Returns:

url string for the endpoint provider (empty string when url is nullified), or None when no location record exists.

Return type:

str or None

fetchUrls(eid: str, scheme: str = '')[source]

Return urls keyed by scheme for the given eid.

Note

The caller is responsible for independently verifying that eid is allowed for a given cid and role. Entries with empty urls are excluded from the result.

Parameters:
  • eid (str) – qb64 identifier prefix of endpoint provider.

  • scheme (str) – url scheme filter. Empty string means all schemes.

Returns:

urls keyed by scheme for the given eid.

Return type:

hicting.Mict

fetchWitnessUrls(cid: str, scheme: str = '', eids=None, enabled: bool = True, allowed: bool = True)[source]

Fetch witness urls for witnesses of cid at latest key state, or enabled/allowed witnesses if not a witness at latest key state.

Parameters:
  • cid (str) – qb64 identifier prefix of controller whose witnesses are being fetched.

  • scheme (str) – url scheme filter. Empty string means all schemes.

  • eids (list or None) – when provided, restrict results to only eids in this list.

  • enabled (bool) – True means include enabled witnesses.

  • allowed (bool) – True means include allowed witnesses.

Returns:

nested Mict keyed as rurls[role][eid][scheme],

where each leaf value is a url string. Role is always witness for results from this method.

Return type:

hicting.Mict

getOwnEvent(sn, allowPartiallySigned=False)[source]

Return the event serder, controller signatures, and seal source duple for own event at sequence number sn.

Parameters:
  • sn (int) – sequence number of event.

  • allowPartiallySigned (bool) – True means attempt to load from partial signed escrow if not found in KEL.

Returns:

(serder, sigers, duple) where serder is the event Serder, sigers is a list of Siger instances, and duple is the seal source couple or None.

Return type:

tuple

Raises:

MissingEntryError – if no event is found for own prefix at sn.

incept(DnD, code, data, delpre, estOnly, isith, verfers, nsith, digers, toad, wits, kind='JSON', version=(1, 0))[source]

Creates Serder of inception event for provided parameters. Assumes injected dependencies were already setup.

Parameters:
  • DnD (bool) – True means add trait TraitDex.DnD which means do not allow delegated identifiers from this identifier. False (default) means do allow, and no trait is added.

  • code (str) – prefix derivation code, default Blake3.

  • data (list or None) – seal dicts.

  • delpre (str or None) – qb64 of delegator identifier prefix if any.

  • estOnly (bool or None) – True means add trait TraitDex.EstOnly which means only establishment events are allowed in the KEL for this Hab. False (default) means allow non-est events and no trait is added.

  • isith (int, str, list, or None) – incepting signing threshold as int, str hex, or list weighted if any, otherwise compute default from verfers.

  • verfers (list[Verfer]) – Verfer instances for initial signing keys.

  • nsith (int, str, list, or None) – next signing threshold as int, str hex, or list weighted if any, otherwise compute default from digers.

  • digers (list[Diger] or None) – Diger instances for next key digests.

  • toad (int, str, or None) – int or str hex of witness threshold if specified, else compute default based on number of wits (backers).

  • wits (list or None) – qb64 prefixes of witnesses if any.

  • kind (str) – serialization for key event message one of Kinds (“json”,”cbor”,”mgpk”,”cesr”)

  • version (Versionage) – version for key event message

Returns:

inception event serder.

Return type:

Serder

interact(*, data=None, kind='JSON', version=(1, 0), framed=False, nested=False, gvrsn=(1, 0), genusify=False)[source]

Perform interaction operation. Register interaction in database.

Parameters::

data (list or None): dicts of committed data such as seals. kind (str): serialization for key event message

one of Kinds (“json”,”cbor”,”mgpk”,”cesr”)

version (Versionage): version for key event message framed (bool): True means may assume each message plus its attachments

is isolated as frame when parsing so do not need attachment group when messagizing

False means may not assume eash message plus its attachments

is isolated as frame when parsing so do need attachment group when messagizing

nested (bool): True means messagize for non-top level

This forces non-native serializion to be embedded in non-native group code

False means messagize for top level of stream.

This allows bare non-native serialization of message

gvrsn (Versionage): CESR Genus version for attachment group codes or

nesting group code (useful when serder.gvrsn < 2) gvrsn = max(svrsn, gvrsn) where svrsn = serder.gvrsn

if serder.gvrsn else serder.pvrsn

genusify (bool): True means prepend genus version code from gvrsn before

serder to override default stream genus version

False means do nothing

Returns::

bytearray: interaction message with attached signatures.

Raises::

ValidationError: if the interaction event is improper.

property iserder

Return serder of inception event.

Returns:

own inception event serder.

Return type:

SerderKERI

Raises:

ConfigurationError – if inception event is missing from the KEL or the event store.

property kever

Returns kever for own .pre.

Returns:

Kever instance if accepted, else None.

Return type:

Kever or None

property kevers

Returns .db.kevers.

Returns:

mapping of qb64 prefix to Kever instances.

Return type:

dict

loadEndRole(cid, eid, role='controller', framed=False, nested=False, gvrsn=(1, 0), genusify=False)[source]

Load and return the messagized end role authorization record for the given cid, eid, and role from the database, including associated attachments.

Parameters::

cid (str): qb64 identifier prefix of controller. eid (str): qb64 identifier prefix of endpoint provider. role (str): endpoint role. Default is Roles.controller. framed (bool): True means may assume each message plus its attachments

is isolated as frame when parsing so do not need attachment group when messagizing

False means may not assume eash message plus its attachments

is isolated as frame when parsing so do need attachment group when messagizing

nested (bool): True means messagize for non-top level

This forces non-native serializion to be embedded in non-native group code

False means messagize for top level of stream.

This allows bare non-native serialization of message

gvrsn (Versionage): CESR Genus version for attachment group codes or

nesting group code (useful when serder.gvrsn < 2) gvrsn = max(svrsn, gvrsn) where svrsn = serder.gvrsn

if serder.gvrsn else serder.pvrsn

genusify (bool): True means prepend genus version code from gvrsn before

serder to override default stream genus version

False means do nothing

Returns::

bytearray: messagized end role record with attachments, or empty bytearray if not found or not enabled/allowed.

loadLocScheme(eid, scheme=None, framed=False, nested=False, gvrsn=(1, 0), genusify=False)[source]

Load and return messagized location scheme records for the given eid and optional scheme from the database, including associated attachments.

Parameters::

eid (str): qb64 identifier prefix of endpoint provider. scheme (str or None): url scheme filter. None means all schemes. framed (bool): True means may assume each message plus its attachments

is isolated as frame when parsing so do not need attachment group when messagizing

False means may not assume eash message plus its attachments

is isolated as frame when parsing so do need attachment group when messagizing

nested (bool): True means messagize for non-top level

This forces non-native serializion to be embedded in non-native group code

False means messagize for top level of stream.

This allows bare non-native serialization of message

gvrsn (Versionage): CESR Genus version for attachment group codes or

nesting group code (useful when serder.gvrsn < 2) gvrsn = max(svrsn, gvrsn) where svrsn = serder.gvrsn

if serder.gvrsn else serder.pvrsn

genusify (bool): True means prepend genus version code from gvrsn before

serder to override default stream genus version

False means do nothing

Returns::

bytearray: messagized location scheme records with attachments.

make(**kwa)[source]

Alias for .incept.

Parameters:

**kwa – keyword arguments forwarded to incept().

makeEndRole(eid, role='controller', allow=True, stamp=None, **kwa)[source]

Return a reply message allowing or disallowing endpoint provider eid in role.

Parameters:
  • eid (str) – qb64 of endpoint provider to be authorized.

  • role (str) – authorized role for eid. Default is Roles.controller.

  • allow (bool) – True means add eid at role as authorized. False means cut eid at role as unauthorized.

  • stamp (str or None) – date-time-stamp RFC-3339 profile of iso8601 datetime. None means use now.

  • **kwa – keyword arguments forwarded to eventing.reply, including: version (Version): version instance. kind (str): serialization kind.

Returns:

reply message.

Return type:

bytearray

makeLocScheme(url, eid=None, scheme='http', stamp=None, **kwa)[source]

Return a reply message of own url service endpoint at scheme.

Parameters::
url (str): url of endpoint. May have scheme missing or not. An

empty url nullifies the location.

eid (str or None): qb64 of endpoint provider to be authorized.

None means use own .pre.

scheme (str): url scheme; must match scheme in url if present.

Default is "http".

stamp (str or None): date-time-stamp RFC-3339 profile of iso8601

datetime. None means use now.

**kwa: keyword arguments forwarded to eventing.reply, including:

route (str): route path string indicating the data flow handler. data (list): dicts of committed data such as seals. dts (str): date-time-stamp of message at time of creation. version (Version): version instance. kind (str): serialization kind.

Returns::

bytearray: reply message.

msgOtherEvent(pre, sn, framed=False, nested=False, gvrsn=(1, 0), genusify=False)[source]

Return messagized bytearray message with attached signatures of the event at sequence number sn for pre, retrieved from the database.

Parameters::

pre (str): qb64 identifier prefix. sn (int): sequence number of event. framed (bool): True means may assume each message plus its attachments

is isolated as frame when parsing so do not need attachment group when messagizing

False means may not assume eash message plus its attachments

is isolated as frame when parsing so do need attachment group when messagizing

nested (bool): True means messagize for non-top level

This forces non-native serializion to be embedded in non-native group code

False means messagize for top level of stream.

This allows bare non-native serialization of message

gvrsn (Versionage): CESR Genus version for attachment group codes or

nesting group code (useful when serder.gvrsn < 2) gvrsn = max(svrsn, gvrsn) where svrsn = serder.gvrsn

if serder.gvrsn else serder.pvrsn

genusify (bool): True means prepend genus version code from gvrsn before

serder to override default stream genus version

False means do nothing

Returns::
msg (bytearray |None): messagized event with attached signatures,

or None if pre is not in kevers.

Raises::

MissingEntryError: if no event is found for pre at sn.

msgOwnEvent(sn, allowPartiallySigned=False, framed=False, nested=False, gvrsn=(1, 0), genusify=False)[source]

Messagize own event at sn with attachments if any.

Parameters::

sn (int): sequence number of event. allowPartiallySigned (bool): True means attempt to load from

partial signed escrow if not found in KEL.

framed (bool): True means may assume each message plus its attachments

is isolated as frame when parsing so do not need attachment group when messagizing

False means may not assume eash message plus its attachments

is isolated as frame when parsing so do need attachment group when messagizing

nested (bool): True means messagize for non-top level

This forces non-native serializion to be embedded in non-native group code

False means messagize for top level of stream.

This allows bare non-native serialization of message

gvrsn (Versionage): CESR Genus version for attachment group codes or

nesting group code (useful when serder.gvrsn < 2) gvrsn = max(svrsn, gvrsn) where svrsn = serder.gvrsn

if serder.gvrsn else serder.pvrsn

genusify (bool): True means prepend genus version code from gvrsn before

serder to override default stream genus version

False means do nothing

Returns::
msg (bytearray): qb64b serialization of own event at sn with

optionally attached signatures and seal source couple.

msgOwnInception(allowPartiallySigned=False, framed=False, nested=False, gvrsn=(1, 0), genusify=False)[source]

Return messagized own inception event with attached signatures, retrieved from the database.

Parameters::
allowPartiallySigned (bool): True means attempt to load from

partial signed escrow if not found in KEL.

framed (bool): True means may assume each message plus its attachments

is isolated as frame when parsing so do not need attachment group when messagizing

False means may not assume eash message plus its attachments

is isolated as frame when parsing so do need attachment group when messagizing

nested (bool): True means messagize for non-top level

This forces non-native serializion to be embedded in non-native group code

False means messagize for top level of stream.

This allows bare non-native serialization of message

gvrsn (Versionage): CESR Genus version for attachment group codes or

nesting group code (useful when serder.gvrsn < 2) gvrsn = max(svrsn, gvrsn) where svrsn = serder.gvrsn

if serder.gvrsn else serder.pvrsn

genusify (bool): True means prepend genus version code from gvrsn before

serder to override default stream genus version

False means do nothing

Returns::

msg (bytearray): messagized inception event with attached signatures.

property prefixes

Returns .db.prefixes.

Returns:

local prefixes for .db.

Return type:

OrderedSet

processCues(cues, gvrsn=(1, 0), version=(1, 0), kind='JSON')[source]

Return bytearray of messages resulting from processing all cues.

Parameters:
  • cues (deque) – cue dicts to process.

  • gvrsn (Versionage) – CESR genus version for attachment group codes.

  • version (Versionage) – KERI protocol version for generated receipt events.

  • kind (str) – Serialization kind for generated receipt events.

Returns:

concatenated outgoing messages.

Return type:

bytearray

processCuesIter(cues, gvrsn=(1, 0), version=(1, 0), kind='JSON')[source]

Iterate through cues and yield one or more msgs for each cue.

Parameters:
  • cues (deque) – cue dicts to process.

  • gvrsn (Versionage) – CESR genus version for attachment group codes.

  • version (Versionage) – KERI protocol version for generated receipt events.

  • kind (str) – Serialization kind for generated receipt events.

Yields:

bytearray – message(s) produced for each cue.

query(pre, src, query=None, **kwa)[source]

Create, sign, and return a qry message against the attester for the prefix.

Parameters:
  • pre (str) – qb64 identifier prefix being queried for.

  • src (str) – qb64 identifier prefix of attester being queried.

  • query (dict or None) – additional query modifiers to include in q.

  • **kwa – keyword arguments passed to eventing.query.

Returns:

signed query event.

Return type:

bytearray

receipt(serder, kind='JSON', version=(1, 0), framed=False, nested=False, gvrsn=(1, 0), genusify=False)[source]

Build own receipt rct message of serder with count code and receipt couples (pre+cig). Processes local copy into db to validate.

Parameters::

serder (Serder): event serder to receipt. kind (str): serialization for receipt message

one of Kinds (“json”,”cbor”,”mgpk”,”cesr”)

version (Versionage): KERI protocol default version for receipt framed (bool): True means may assume each message plus its attachments

is isolated as frame when parsing so do not need attachment group when messagizing

False means may not assume eash message plus its attachments

is isolated as frame when parsing so do need attachment group when messagizing

nested (bool): True means messagize for non-top level

This forces non-native serializion to be embedded in non-native group code

False means messagize for top level of stream.

This allows bare non-native serialization of message

gvrsn (Versionage): CESR Genus version for attachment group codes or

nesting group code (useful when serder.gvrsn < 2) gvrsn = max(svrsn, gvrsn) where svrsn = serder.gvrsn

if serder.gvrsn else serder.pvrsn

genusify (bool): True means prepend genus version code from gvrsn before

serder to override default stream genus version

False means do nothing

Returns::

bytearray: receipt message with attached signatures.

reconfigure(**kwa)[source]

Apply configuration from config file managed by .cf to this Hab. Assumes that .pre and signing keys have been set up in order to create own endpoint auth when provided in .cf.

Config file (JSON or HJSON) format:

{
    "dt": "2021-01-01T00:00:00.000000+00:00",
    "nel": {
        "dt": "2021-01-01T00:00:00.000000+00:00",
        "curls": [
            "tcp://localhost:5621/"
        ]
    },
    "iurls": [
        "tcp://localhost:5620/?role=peer&name=tam"
    ],
    "durls": [
        "http://127.0.0.1:7723/oobi/EBNaNu-M9P5cgrnfl2Fvymy4E_jvxxyjb70PRtiANlJy",
        "http://127.0.0.1:7723/oobi/EMhvwOlyEJ9kN4PrwCpr9Jsv7TxPhiYveZ0oP3lJzdEi"
    ],
    "wurls": [
        "http://127.0.0.1:5644/.well-known/keri/oobi/EBNaNu-M9P5cgrnfl2Fvymy4E_jvxxyjb70PRtiANlJy?name=Root"
    ]
}

Note

Config file is meant to be read only at init, not changed by the app at run time. Any dynamic app changes must go in the database, not the config file — that way we don’t have to worry about multiple writers to .cf. Use the config file to preload the database, not as a database. Config file may have named sections for Habery or individual Habs as needed.

Parameters::
**kwa: keyword arguments forwarded to makeEndRole and

makeLocScheme, including version and kind.

replay(pre=None, fn=0)[source]

Return replay of FEL (first-seen event log) for pre starting from fn. Default pre is own .pre.

Parameters:
  • pre (str or None) – qb64 str or bytes of identifier prefix. Default is own .pre.

  • fn (int) – first-seen ordering number to start from.

Returns:

serialized event log messages.

Return type:

bytearray

replayAll()[source]

Return replay of FEL (first-seen event log) for all prefixes.

Returns:

serialized event log messages for all prefixes.

Return type:

bytearray

reply(framed=False, nested=False, gvrsn=(1, 0), genusify=False, **kwa)[source]

Return own endorsed reply message.

Parameters::
framed (bool): True means may assume each message plus its attachments

is isolated as frame when parsing so do not need attachment group when messagizing

False means may not assume eash message plus its attachments

is isolated as frame when parsing so do need attachment group when messagizing

nested (bool): True means messagize for non-top level

This forces non-native serializion to be embedded in non-native group code

False means messagize for top level of stream.

This allows bare non-native serialization of message

gvrsn (Versionage): CESR Genus version for attachment group codes or

nesting group code (useful when serder.gvrsn < 2) gvrsn = max(svrsn, gvrsn) where svrsn = serder.gvrsn

if serder.gvrsn else serder.pvrsn

genusify (bool): True means prepend genus version code from gvrsn before

serder to override default stream genus version

False means do nothing

**kwa: keyword arguments forwarded to eventing.reply, including:

route (str): route path string indicating the data flow handler. data (list): dicts of committed data such as seals. dts (str): date-time-stamp of message at time of creation. version (Version): version instance. kind (str): serialization kind.

Returns::

bytearray: reply message.

replyEndRole(cid, role=None, eids=None, scheme='', **kwa)[source]

Return a reply message stream of end role authorization entries authed by the given cid from the reply database, including associated attachments, for dissemination of BADA reply data authentication proofs.

Note

Currently uses a promiscuous model for permitting endpoint discovery. Future versions will use an identity constraint graph to constrain discovery.

Behavior by argument combination:

  • cid only: end authz for all eids in all roles and loc url for all schemes at each eid (filtered by eids if provided).

  • cid + scheme: end authz for all eids in all roles and loc url for scheme at each eid.

  • cid + role: end authz for all eids in role and loc url for all schemes at each eid.

  • cid + role + scheme: end authz for all eids in role and loc url for scheme at each eid.

Parameters::
cid (str): qb64 identifier prefix of controller authorizing

endpoint provider eid.

role (str or None): endpoint role filter. None means all roles. eids (list or None): when provided, restrict results to only eids

in this list.

scheme (str): url scheme filter. Empty string means all schemes. **kwa: keyword arguments forwarded to eventing.reply, including:

route (str): route path string indicating the data flow handler. data (list): dicts of committed data such as seals. dts (str): date-time-stamp of message at time of creation. version (Version): version instance. kind (str): serialization kind.

Returns::

bytearray: reply message stream for end role entries.

replyLocScheme(eid, scheme='', **kwa)[source]

Return a reply message stream of location scheme entries authed by the given eid from the reply database, including associated attachments, for dissemination of BADA reply data authentication proofs.

Note

Currently uses a promiscuous model for permitting endpoint discovery. Future versions will use an identity constraint graph to constrain discovery.

Parameters::

eid (str): endpoint provider id. scheme (str): url scheme filter. Empty string means all schemes. **kwa: keyword arguments forwarded to eventing.reply, including:

route (str): route path string indicating the data flow handler. data (list): dicts of committed data such as seals. dts (str): date-time-stamp of message at time of creation. version (Version): version instance. kind (str): serialization kind.

Returns::

bytearray: reply message stream for location scheme entries.

replyToOobi(aid, role, eids=None, **kwa)[source]

Return a reply message stream of entries authed by the given aid for OOBI-initiated endpoint discovery, including associated attachments, for dissemination of BADA reply data authentication proofs.

Note

Currently uses a promiscuous model for permitting OOBI-initiated endpoint discovery. Future versions will use an identity constraint graph to constrain discovery.

This method is the entry point for initiating replies generated by replyEndRole() and/or replyLocScheme().

Parameters::

aid (str): qb64 of identifier in oobi; may be cid or eid. role (str): authorized role for eid. eids (list or None): when provided, restrict results to only eids

in this list.

**kwa: keyword arguments forwarded to eventing.reply, including:

route (str): route path string indicating the data flow handler. data (list): dicts of committed data such as seals. dts (str): date-time-stamp of message at time of creation. version (Version): version instance. kind (str): serialization kind.

Returns::

bytearray: reply message stream for OOBI endpoint entries.

rotate(*, verfers=None, digers=None, isith=None, nsith=None, toad=None, cuts=None, adds=None, data=None, kind='JSON', version=(1, 0), framed=False, nested=False, gvrsn=(1, 0), genusify=False)[source]

Perform rotation operation. Register rotation in database.

Parameters::

verfers (list or None): Verfer instances of public keys qb64. digers (list or None): Diger instances of public next key digests

qb64.

isith (int, str, or None): current signing threshold as int, str

hex, or list of str weights. Default is prior next sith.

nsith (int, str, or None): next signing threshold as int, str hex,

or list of str weights. Default is based on isith when None.

toad (int or str or None): hex of witness threshold after cuts and

adds.

cuts (list or None): qb64 prefixes of witnesses to be removed from

the witness list.

adds (list or None): qb64 prefixes of witnesses to be added to the

witness list.

data (list or None): dicts of committed data such as seals. kind (str): serialization for key event message

one of Kinds (“json”,”cbor”,”mgpk”,”cesr”)

version (Versionage): version for key event message framed (bool): True means may assume each message plus its attachments

is isolated as frame when parsing so do not need attachment group when messagizing

False means may not assume eash message plus its attachments

is isolated as frame when parsing so do need attachment group when messagizing

nested (bool): True means messagize for non-top level

This forces non-native serializion to be embedded in non-native group code

False means messagize for top level of stream.

This allows bare non-native serialization of message

gvrsn (Versionage): CESR Genus version for attachment group codes or

nesting group code (useful when serder.gvrsn < 2) gvrsn = max(svrsn, gvrsn) where svrsn = serder.gvrsn

if serder.gvrsn else serder.pvrsn

genusify (bool): True means prepend genus version code from gvrsn before

serder to override default stream genus version

False means do nothing

Returns::

bytearray: rotation message with attached signatures.

Raises::
ValidationError: if the new key set cannot satisfy the prior next

signing threshold, or if the rotation event is otherwise improper.

sign(ser, verfers=None, indexed=True, indices=None, ondices=None, **kwa)[source]

Sign given serialization ser using appropriate keys. Uses provided verfers or .kever.verfers to look up keys to sign.

Parameters:
  • ser (bytes) – serialization to sign.

  • verfers (list[Verfer] or None) – Verfer instances to get public verifier keys to look up private signing keys. None means use .kever.verfers. When group and verfers is not None, the provided verfers must be .kever.verfers.

  • indexed (bool) – when not mhab, True means use indexed signatures and return a list of Siger instances. False means do not use indexed signatures and return a list of Cigar instances.

  • indices (list[int] or None) – indices (offsets) when indexed is True. See Manager.sign.

  • ondices (list[int or None] or None) – other indices (offsets) when indexed is True. See Manager.sign.

Returns:

signed instances depending on indexed.

Return type:

list[Siger] or list[Cigar]

witness(serder, kind='JSON', version=(1, 0), framed=False, nested=False, gvrsn=(1, 0), genusify=False)[source]

Build own witness receipt rct message of serder with count code and witness indexed receipt signatures, if the key state of serder.pre shows that own pre is a current witness of the event in serder.

Note::

The caller must ensure that the serder being witnessed has been accepted as a valid event into this hab controller’s KEL before calling this method.

Parameters::

serder (Serder): event serder to witness. kind (str): serialization for receipt message

one of Kinds (“json”,”cbor”,”mgpk”,”cesr”)

version (Versionage): KERI protocol default version for receipt framed (bool): True means may assume each message plus its attachments

is isolated as frame when parsing so do not need attachment group when messagizing

False means may not assume eash message plus its attachments

is isolated as frame when parsing so do need attachment group when messagizing

nested (bool): True means messagize for non-top level

This forces non-native serializion to be embedded in non-native group code

False means messagize for top level of stream.

This allows bare non-native serialization of message

gvrsn (Versionage): CESR Genus version for attachment group codes or

nesting group code (useful when serder.gvrsn < 2) gvrsn = max(svrsn, gvrsn) where svrsn = serder.gvrsn

if serder.gvrsn else serder.pvrsn

genusify (bool): True means prepend genus version code from gvrsn before

serder to override default stream genus version

False means do nothing

Returns::

bytearray: witness receipt message with attached signatures.

Raises::
ValueError: if own prefix is transferable, if the key state for

serder.pre is missing, or if own prefix is not a witness of the event.

class keri.app.habbing.GroupHab(smids, mhab=None, rmids=None, **kwa)[source]

Local group (multisig) habitat for a given identifier controller.

Provides the local resource environment (hab or habitat) for a multisig group controller, including dependency injection of the database, keystore, configuration file, Kevery, and key store Manager.

Signing is performed through the local member hab (mhab) by walking its KEL to locate the correct contributed key material. MissingSignatureError is silently swallowed during inception and rotation processing so that group events can be created and stored with a single local member’s signature while awaiting the remaining co-signers’ contributions.

ks

LMDB key store. (Injected)

Type:

keeping.Keeper

db

LMDB database for KEL etc. (Injected)

Type:

basing.Baser

cf

Configuration file instance. (Injected)

Type:

configing.Configer

mgr

Creates and rotates keys in the key store. (Injected)

Type:

keeping.Manager

rtr

Routes reply rpy messages. (Injected)

Type:

routing.Router

rvy

Factory that processes reply rpy messages. (Injected)

Type:

routing.Revery

kvy

Factory for local processing of local event messages. (Injected)

Type:

eventing.Kevery

psr

Parses local messages for .kvy and .rvy. (Injected)

Type:

parsing.Parser

name

Alias of the controller.

Type:

str

pre

qb64 prefix of the own local controller, or None if new.

Type:

str

mhab

Local participant member hab of this group hab.

Type:

Hab or None

smids

qb64 prefixes of current signing members of the group.

Type:

list or None

rmids

qb64 prefixes of rotating members of the group. Defaults to a copy of smids when not supplied.

Type:

list or None

temp

True means testing — uses weak level when salty algo for stretching in key creation for incept and rotate of keys for this hab.pre.

Type:

bool

inited

True means fully initialized with respect to databases; False means not yet fully initialized.

Type:

bool

delpre

Delegator prefix if any, else None.

Type:

str or None

kevers

Kever instances from KELs in the local db, keyed by qb64 prefix. Read-through cache of states for KELs in db.states. (Read-only property)

Type:

dict

iserder

Own inception event. (Read-only property)

Type:

serdering.SerderKERI

prefixes

Local prefixes for .db. (Read-only property)

Type:

oset.OrderedSet

accepted

True means accepted into the local KEL, False otherwise. (Read-only property)

Type:

bool

__init__(smids, mhab=None, rmids=None, **kwa)[source]

Initialise a GroupHab instance.

Parameters:
  • smids (list[str]) – qb64 prefixes of the current signing members of the multisig group.

  • mhab (Hab or None) – Local participant member hab. The mhab.pre aid may appear in smids, rmids, or both.

  • rmids (list or None) – qb64 prefixes of the rotating members of the multisig group. Defaults to smids when None.

  • **kwa – Keyword arguments forwarded to BaseHab.__init__, including all injected dependencies (ks, db, cf, mgr, rtr, rvy, kvy, psr), name, pre, and temp.

incept(*, code='E', transferable=True, isith=None, nsith=None, toad=None, wits=None, delpre=None, estOnly=False, DnD=False, merfers, migers=None, data=None, kind='JSON', version=(1, 0))[source]

Finish setting up or making this GroupHab from parameters, including inception.

Assembles the group inception event from the collected member key material (merfers, migers), signs it via the local member hab (mhab), persists the habitat record, and processes the event through the local Kevery. MissingSignatureError is silently swallowed during delegated-identifier initialisation.

Assumes injected dependencies have already been set up.

Parameters:
  • code (str) – Prefix derivation code. Defaults to MtrDex.Blake3_256.

  • transferable (bool) – True means the prefix is transferable (default). False forces nsith='0' and code=MtrDex.Ed25519N.

  • isith (int, str, list, or None) – Incepting signing threshold as an int, hex str, or weighted list. Computed from verfers when None.

  • nsith (int, str, list, or None) – Next signing threshold as an int, hex str, or weighted list. Defaults to isith when None.

  • toad (int, str, or None) – Witness threshold as an int or hex str. Computed from the number of witnesses when None.

  • wits (list or None) – qb64 prefixes of witnesses, if any.

  • delpre (str or None) – qb64 delegator identifier prefix, if any.

  • estOnly (bool) – True adds TraitDex.EstOnly, restricting the KEL to establishment events only. Defaults to False.

  • DnD (bool) – True adds TraitDex.DnD, disallowing delegated identifiers from this identifier. Defaults to False.

  • merfers (list[Verfer]) – Verfer instances of the public signing keys contributed by each multisig group member. Exactly one key per member; the zeroth element of each member’s key list by convention.

  • migers (list or None) – Diger instances of the public next-key digests contributed by each multisig group member. None means no pre-rotation material is included.

  • data (list or None) – Seal dicts to embed in the inception event.

  • kind (str) – serialization value of Kinds (“json”,”cbor”,”mgpk”,”cesr”)

  • version (Versionage) – version for incept key event message

Raises:
  • ClosedError – If the key store, database, or config file is not open.

  • ConfigurationError – If inception event processing fails for any reason other than a missing signature.

query(pre, src, framed=False, nested=False, gvrsn=(1, 0), genusify=False, query=None, **kwa)[source]

Create, sign, and return a signed qry query message.

Builds a query event for pre directed at attester src, then endorses it through the local member hab (mhab) using the last event in mhab’s KEL.

Parameters:
  • pre (str) – qb64 identifier prefix being queried for.

  • src (str) – qb64 identifier prefix of the attester being queried.

  • query (dict or None) – Additional query modifiers to include in the q field. Defaults to an empty dict when None.

  • **kwa – Keyword arguments forwarded to query.

Returns:

Signed query message endorsed by mhab.

Return type:

bytearray

rotate(smids=None, rmids=None, serder=None, framed=False, nested=False, gvrsn=(1, 0), genusify=False, **kwa)[source]

Perform a rotation operation and update group member lists.

When serder is None, delegates entirely to BaseHab.rotate(**kwa) for a locally-driven rotation. When a pre-built rotation serder is provided, the local member hab signs it, the result is processed through the local Kevery, and the smids/rmids member lists are updated on both the instance and the persisted HabitatRecord.

Parameters:
  • smids (list or None) – Updated qb64 prefixes of signing members after rotation.

  • rmids (list or None) – Updated qb64 prefixes of rotating members after rotation.

  • serder (SerderKERI or None) – Pre-built rotation event serder. When None a rotation event is generated by BaseHab.rotate.

  • framed (bool) –

    True means may assume each message plus its attachments

    is isolated as frame when parsing so do not need attachment group when messagizing

    False means may not assume eash message plus its attachments

    is isolated as frame when parsing so do need attachment group when messagizing

  • nested (bool) –

    True means messagize for non-top level

    This forces non-native serializion to be embedded in non-native group code

    False means messagize for top level of stream.

    This allows bare non-native serialization of message

  • gvrsn (Versionage) –

    CESR Genus version for attachment group codes or nesting group code (useful when serder.gvrsn < 2) gvrsn = max(svrsn, gvrsn) where svrsn = serder.gvrsn

    if serder.gvrsn else serder.pvrsn

  • genusify (bool) –

    True means prepend genus version code from gvrsn before

    serder to override default stream genus version

    False means do nothing

  • **kwa – Keyword arguments forwarded to BaseHab.rotate when serder is None.

Returns:

Rotation message with attached signatures.

Return type:

bytearray

Raises:

ValidationError – If the habitat record for self.pre does not exist in the database, or if rotation event processing fails for any reason other than a missing signature.

sign(ser, verfers=None, indexed=True, rotated=False, indices=None, ondices=None)[source]

Sign a serialisation using the local member hab’s key material.

Walks the member hab’s (mhab) KEL to locate the latest event at which mhab contributed signing key material to the group, then delegates to mhab.sign with the appropriate current index (csi) and, for rotation events, the optional prior-next other index (pni).

By convention the contributed member key is always the zeroth element of the member’s signing key list, and the contributed member next-key digest is always the zeroth element of the member’s next-key digest list.

Parameters:
  • ser (bytes) – Serialisation to sign.

  • verfers (list or None) – Verfer instances representing the group’s current signing keys. None means use self.kever.verfers.

  • indexed (bool) – True means return indexed Siger instances; False means return unindexed Cigar instances. Defaults to True.

  • rotated (bool) – When True, compute dual-indexed signatures — the current signing index (csi) and the prior-next other index (pni) — for use in a rotation event. When False (default), only the current signing index is used and pni is set to None.

  • indices (list or None) – Explicit current signing indices. Passed through to Manager.sign; computed automatically when None.

  • ondices (list or None) – Explicit prior-next other indices. Passed through to Manager.sign; computed automatically when None.

Returns:

Signature instances over ser.

Return type:

list[Siger] or list[Cigar]

Raises:

ValueError – If mhab did not contribute to the group event identified by verfers.

witness(serder)[source]

Group habs cannot act as witnesses.

Parameters:

serder (SerderKERI) – Ignored.

Raises:

ValueError – Always — group habs are not valid witnesses and cannot provide witness receipts.

witnesser()[source]

Return whether this member hab holds the lowest-index signing key in the group.

The member holding the lowest signing index among all signatures currently recorded in the database is elected by convention to perform coordination duties on behalf of the group, such as submitting delegation and witnessing requests.

Returns:

True if mhab’s zeroth verfer matches the group signing key at the lowest recorded signer index; False otherwise, including when no signatures are found in the database for the current event.

Return type:

bool

class keri.app.habbing.Hab(**kwa)[source]

Local habitat for a given identifier controller.

Provides the local resource environment (hab or habitat) for a controller, including dependency injection of the database, keystore, configuration file, Kevery, and key store Manager.

ks

LMDB key store. (Injected)

Type:

keeping.Keeper

db

LMDB database for KEL etc. (Injected)

Type:

basing.Baser

cf

Configuration file instance. (Injected)

Type:

configing.Configer

mgr

Creates and rotates keys in the key store. (Injected)

Type:

keeping.Manager

rtr

Routes reply rpy messages. (Injected)

Type:

routing.Router

rvy

Factory that processes reply rpy messages. (Injected)

Type:

routing.Revery

kvy

Factory for local processing of local event messages. (Injected)

Type:

eventing.Kevery

psr

Parses local messages for .kvy and .rvy. (Injected)

Type:

parsing.Parser

name

Alias of the controller.

Type:

str

pre

qb64 prefix of the own local controller, or None if new.

Type:

str

temp

True means testing — uses weak level when salty algo for stretching in key creation for incept and rotate of keys for this hab.pre.

Type:

bool

inited

True means fully initialized with respect to databases; False means not yet fully initialized.

Type:

bool

delpre

Delegator prefix if any, else None.

Type:

str or None

kevers

Kever instances from KELs in the local db, keyed by qb64 prefix. Read-through cache of states for KELs in db.states. (Read-only property)

Type:

dict

iserder

Own inception event. (Read-only property)

Type:

serdering.SerderKERI

prefixes

Local prefixes for .db. (Read-only property)

Type:

oset.OrderedSet

accepted

True means accepted into the local KEL, False otherwise. (Read-only property)

Type:

bool

incept(*, secrecies=None, iridx=0, code='E', dcode='E', icode='A', transferable=True, isith=None, icount=1, nsith=None, ncount=None, toad=None, wits=None, delpre=None, estOnly=False, DnD=False, hidden=False, data=None, algo=None, salt=None, tier=None, kind='JSON', version=(1, 0))[source]

Finish setting up or making this Hab from parameters, including inception.

Assumes injected dependencies have already been set up. When secrecies are provided the key manager replays pre-loaded key pairs; otherwise it generates new keys via mgr.incept.

After key material is prepared the inception event is built, persisted to the habitat record store, and processed by the local Kevery. MissingSignatureError is silently swallowed during delegated-identifier initialisation.

Parameters:
  • secrecies (list or None) – List of secret seeds to pre-load key pairs. When provided, key pairs are replayed rather than generated. Defaults to None.

  • iridx (int) – Initial rotation index used after ingestion of secrecies. Defaults to 0.

  • code (str) – Prefix derivation code. Defaults to MtrDex.Blake3_256.

  • dcode (str) – Next-key derivation code. Defaults to MtrDex.Blake3_256.

  • icode (str) – Signing key derivation code. Defaults to MtrDex.Ed25519_Seed.

  • transferable (bool) – True means the prefix is transferable (default). False means non-transferable; forces ncount=0, nsith='0', and code=MtrDex.Ed25519N.

  • isith (int, str, list, or None) – Incepting signing threshold as an int, hex str, or weighted list. Computed from verfers when None.

  • icount (int) – Number of incepting signing keys. Defaults to 1.

  • nsith (int, str, list, or None) – Next signing threshold as an int, hex str, or weighted list. Defaults to isith when None.

  • ncount (int or None) – Number of next (pre-rotated) keys. Defaults to icount when None.

  • toad (int, str, or None) – Witness threshold as an int or hex str. Computed from the number of witnesses when None.

  • wits (list or None) – qb64 prefixes of witnesses, if any.

  • delpre (str or None) – qb64 delegator identifier prefix, if any.

  • estOnly (bool) – True adds TraitDex.EstOnly, restricting the KEL to establishment events only. Defaults to False.

  • DnD (bool) – True adds TraitDex.DnD, disallowing delegated identifiers from this identifier. Defaults to False.

  • hidden (bool) – When True the Hab is not saved to the habitat record store and its prefix is not added to self.prefixes. Defaults to False.

  • data (list or None) – Seal dicts to embed in the inception event.

  • algo (str or None) – Key-creation algorithm code used by the key manager when generating new keys.

  • salt (str or None) – qb64 salt for randomisation when the salty algorithm is used.

  • tier (str or None) – Security-criticality tier code used with the salty algorithm.

  • kind (str) – serialization value of Kinds (“json”,”cbor”,”mgpk”,”cesr”)

  • version (Versionage) – version for incept key event message

Raises:
  • ClosedError – If the key store, database, or config file is not open.

  • ConfigurationError – If inception event processing fails for any reason other than a missing signature.

rotate(*, isith=None, nsith=None, ncount=None, toad=None, cuts=None, adds=None, data=None, **kwa)[source]

Perform a rotation operation and register it in the database.

Advances the key state by replaying the pre-committed next keys (mgr.replay) or, when no pre-committed keys exist, generating a fresh set (mgr.rotate). Key store state is rolled back automatically if the rotation event fails validation, keeping the key store and KEL in sync (see issue #819). Stale private keys from the previous signing set are erased only after successful validation.

Parameters:
  • isith (int, str, list, or None) – Current signing threshold as an int, hex str, or weighted list. Defaults to the prior next threshold when None.

  • nsith (int, str, list, or None) – Next signing threshold as an int, hex str, or weighted list. Defaults to isith when None.

  • ncount (int or None) – Number of next (pre-rotated) keys. Defaults to the length of the prior next digers when None.

  • toad (int, str, or None) – Witness threshold after cuts and adds, as an int or hex str.

  • cuts (list or None) – qb64 prefixes of witnesses to remove.

  • adds (list or None) – qb64 prefixes of witnesses to add.

  • data (list or None) – Seal dicts to embed in the rotation event.

Returns:

Rotation message with attached signatures.

Return type:

bytearray

Raises:

Exception – Re-raises any exception raised by BaseHab.rotate after rolling back key store state.

class keri.app.habbing.Habery(*, name='test', base='', temp=False, ks=None, db=None, cf=None, clear=False, headDirPath=None, version=(1, 0), **kwa)[source]

Shared environment for a collection of Hab (Habitat) instances.

Provides a single keystore (Keeper), event database (Baser), and config file (Configer) that are shared among all Hab instances created within this environment. Also owns the Manager, Router, Revery, Kevery, and Parser used for key management and event processing.

name

Name used for the associated databases and config file.

Type:

str

base

Optional directory path segment inserted before name for hierarchical differentiation of databases. Empty string means no additional component.

Type:

str

temp

True means temporary storage and fast (test-suitable) salt stretching. False means persistent storage and tier-appropriate key stretching.

Type:

bool

ks

LMDB keystore instance.

Type:

Keeper

db

LMDB event database instance for KELs etc.

Type:

Baser

cf

Config file instance.

Type:

Configer

mgr

Key manager for creating and rotating keys. None until setup completes successfully.

Type:

Manager or None

rtr

Routes rpy (reply) messages to registered handlers.

Type:

Router

rvy

Processes rpy messages.

Type:

Revery

exc

Processes exn (exchange) messages.

Type:

Exchanger

kvy

Processes local key-event messages.

Type:

Kevery

psr

Parses framed local messages, dispatching to kvy, rvy, and exc.

Type:

Parser

habs

Hab instances keyed by their qb64 prefix. Use habByName to look up by name and habByPre to look up by prefix.

Type:

dict

inited

True once setup has completed successfully.

Type:

bool

__init__(*, name='test', base='', temp=False, ks=None, db=None, cf=None, clear=False, headDirPath=None, version=(1, 0), **kwa)[source]

Initialise a Habery instance.

Opens (or reuses) the keystore, event database, and config file, then calls setup if both db and ks are already open. When dependency-injected stores are not yet open (e.g. in an async context), setup must be called explicitly once they have been opened.

Parameters:
  • name (str) – Alias name for the shared environment, databases, and config file.

  • base (str) – Optional directory path segment inserted before name. Empty string means no additional component.

  • temp (bool) – True means use temporary storage in /tmp and fast salt-stretch methods suitable for testing.

  • ks (Keeper | None) – Existing open keystore to reuse. A new Keeper is created when None.

  • db (Baser | None) – Existing open event database to reuse. A new Baser is created when None.

  • cf (Configer | None) – Existing config file instance to reuse. A new Configer is created when None.

  • clear (bool) – When True, removes the resource directory on close.

  • headDirPath (str | None) – Override for the top-level directory path used when creating ks and db.

  • version (Versionage) – Parser attachment code table version.

  • **kwa – Keyword arguments forwarded to setup and stored in _inits for deferred initialisation. See setup for the full parameter list (seed, aeid, bran, pidx, algo, salt, tier, free).

close(clear=False)[source]

Close all managed resources (keystore, database, config file).

Parameters:

clear (bool) – When True, remove the resource directories in addition to closing them. Temporary resources (temp=True) are always cleared regardless of this flag.

deleteHab(name, ns=None)[source]

Remove a Hab from the database and from .habs.

Also removes the name-to-prefix mapping, the prefix from db.prefixes, and (if present) the entry from db.groups.

Parameters:
  • name (str) – Human-readable alias of the Hab to delete.

  • ns (str | None) – Namespace of the Hab. Defaults to "" when None.

Returns:

True if the Hab was found and successfully removed;

False if it was not found or if either database removal failed.

Return type:

bool

extractMerfersMigers(smids, rmids=None)[source]

Extract group signing key verfers and next-key-digest digers from member KELs.

For each signing member in smids, the first (and only permitted) current signing key verfer is appended to merfers. For each rotation member in rmids, the first (and only permitted) next key digest diger is appended to migers (members that have abandoned their identifier and have empty next digers are skipped).

Parameters:
  • smids (list[str]) – qb64 prefixes of the signing members of the multisig group. Each must have exactly one current signing key in .kevers.

  • rmids (list[str] | None) – qb64 prefixes of the rotation members. When None, smids is used for both signing and rotation. Each present member must have at most one next key digest in .kevers.

Returns:

A 2-tuple of

(merfers, migers) where merfers is the ordered list of current signing key verfers and migers is the ordered list of next key digest digers for the group.

Return type:

tuple[list[Verfer], list[Diger]]

Raises:

ConfigurationError – If any signing member has more than one current signing key, or if any rotation member has more than one next key digest.

habByName(name, ns=None)[source]

Return the Hab instance for a given name and optional namespace, or None.

Resolves the name to a prefix via db.names and then looks up the Hab in .habs.

Parameters:
  • name (str) – Human-readable alias of the Hab.

  • ns (str | None) – Namespace of the Hab. Defaults to "" when None.

Returns:

The matching Hab instance, or None if not

found.

Return type:

Hab | None

habByPre(pre)[source]

Return the Hab instance for a given prefix, or None.

Parameters:

pre (str) – qb64 AID prefix to look up.

Returns:

The Hab registered under pre, or None if

not found.

Return type:

Hab | None

joinGroupHab(pre, group, mhab, smids, rmids=None, ns=None)[source]

Join an existing multisig group as a participant without creating a new inception event.

Used when the group’s inception event was initiated by another participant and this node is joining after the fact. The group Hab is constructed, its prefix set to pre, and the record persisted directly rather than through Hab.make.

Parameters:
  • pre (str) – qb64 prefix of the already-established group identifier.

  • group (str) – Human-readable alias for the group identifier.

  • mhab (Hab) – The local participant Hab that is a member of this group.

  • smids (list[str]) – qb64 prefixes of the signing members.

  • rmids (list[str] | None) – qb64 prefixes of the rotation members. When None, smids is used for both. An empty list means the group is non-transferable after inception.

  • ns (str | None) – Optional namespace for the group identifier.

Returns:

The newly created and persisted GroupHab instance

with .pre set to pre.

Return type:

GroupHab

Raises:

ConfigurationError – If mhab.pre is not in smids or rmids, or if a member’s KEL is missing from .kevers.

joinSignifyGroupHab(pre, name, mhab, smids, rmids=None, ns=None)[source]

Join an existing Signify-managed multisig group as a participant without creating a new inception event.

Analogous to joinGroupHab but for SignifyGroupHab instances. The group Hab is constructed with the given pre, and the record is persisted directly.

Parameters:
  • pre (str) – qb64 prefix of the already-established group identifier.

  • name (str) – Human-readable alias for the group identifier.

  • mhab (Hab) – The local participant Hab that is a member of this group.

  • smids (list[str]) – qb64 prefixes of the signing members.

  • rmids (list[str] | None) – qb64 prefixes of the rotation members. When None, smids is used for both. An empty list means the group is non-transferable after inception.

  • ns (str | None) – Optional namespace for the group identifier.

Returns:

The newly created and persisted

SignifyGroupHab instance with .pre set to pre.

Return type:

SignifyGroupHab

Raises:

ConfigurationError – If mhab.pre is not in smids or rmids, or if a member’s KEL is missing from .kevers.

property kevers

All Kever instances from db.kevers, keyed by qb64 prefix.

Type:

dict

loadHabs()[source]

Load all Hab instances persisted in the database into .habs.

Called by setup after the keystore and event database are open and db.reload has already populated db.kevers and db.prefixes from stored key state, removing any orphaned hab records without valid key state.

Each record in db.habs is inspected to determine the correct Hab subclass:

  • GroupHabmid set, sid not set (local multisig group).

  • SignifyHabsid set, mid not set (Signify-managed single identifier).

  • SignifyGroupHab — both sid and mid set (Signify-managed multisig group).

  • Hab — neither sid nor mid set (standard local identifier).

After all habs are loaded, group habs have their .mhab (local member hab) populated from .habs. reconfigure is called both before and after loading.

Raises:

ConfigurationError – If a non-group Hab loaded from the database has not been accepted into its own local KEL.

makeGroupHab(group, mhab, smids, rmids=None, ns=None, **kwa)[source]

Create, persist, and return a new multisig GroupHab.

The KEL for each signing and rotation member must already be present in .kevers before calling this method. Current signing keys are extracted from each member’s latest establishment event to form the group’s inception keys (merfers), and next key digests form the group’s next key commitments (migers).

Parameters:
  • group (str) – Human-readable alias for the group identifier.

  • mhab (Hab) – The local participant Hab that is a member of this group.

  • smids (list[str]) – qb64 prefixes of the signing members. Each must have a KEL in .kevers and exactly one current signing key.

  • rmids (list[str] | None) – qb64 prefixes of the rotation members from which next key digests are extracted. When None, smids is used for both signing and rotation. An empty list produces a group identifier with no next key commitments (non-transferable after inception).

  • ns (str | None) – Optional namespace for the group identifier.

  • **kwa

    Keyword arguments forwarded to GroupHab.make. See makeHab for the full list; additionally:

    • DnD (bool): TraitDex.DnD to disallow delegated identifiers from this identifier.

Returns:

The newly created and persisted GroupHab instance.

Return type:

GroupHab

Raises:

ConfigurationError – If mhab.pre is not present in either smids or rmids, if a signing member’s KEL is missing from .kevers, if a rotation member’s KEL is missing from .kevers, or if any member has more than one current signing key or more than one next key digest.

makeHab(name, ns=None, cf=None, **kwa)[source]

Create, persist, and return a new local Hab.

The new Hab is registered in .habs keyed by its generated prefix.

Parameters:
  • name (str) – Human-readable alias for the new identifier.

  • ns (str | None) – Optional namespace for the identifier. Must not contain a '.' character.

  • cf (Configer | None) – Config file instance to use for this hab. Defaults to self.cf when None.

  • **kwa

    Keyword arguments forwarded to Hab.make:

    • secrecies (list): Pre-loaded key-pair secrets.

    • iridx (int): Initial rotation index after secret ingestion.

    • code (str): Prefix derivation code.

    • transferable (bool): True (default) for a transferable prefix; False for non-transferable.

    • isith (int | str | list): Inception signing threshold.

    • icount (int): Number of inception signing keys.

    • nsith (int | str | list): Next signing threshold.

    • ncount (int): Number of next (pre-rotated) keys.

    • toad (int | str): Witness threshold.

    • wits (list[str]): qb64 witness prefixes.

    • delpre (str): qb64 delegator prefix.

    • estOnly (str): TraitDex.EstOnly to restrict the KEL to establishment events only.

    • data (list | None): Seal dicts for the inception event.

Returns:

The newly created and persisted Hab instance.

Return type:

Hab

Raises:

ConfigurationError – If ns contains a '.' character.

makeSignifyGroupHab(name, mhab, smids, rmids=None, ns=None, **kwa)[source]

Create, persist, and return a new SignifyGroupHab (Signify-managed multisig group identifier).

Parameters:
  • name (str) – Human-readable alias for the group identifier.

  • mhab (Hab) – The local participant Hab that is a member of this group.

  • smids (list[str]) – qb64 prefixes of the signing members.

  • rmids (list[str] | None) – qb64 prefixes of the rotation members. When None, smids is used for both.

  • ns (str | None) – Optional namespace for the group identifier.

  • **kwa – Keyword arguments forwarded to SignifyGroupHab.make.

Returns:

The newly created and persisted

SignifyGroupHab instance.

Return type:

SignifyGroupHab

makeSignifyHab(name, ns=None, **kwa)[source]

Create, persist, and return a new SignifyHab (Signify-managed single identifier).

Parameters:
  • name (str) – Human-readable alias for the identifier.

  • ns (str | None) – Optional namespace for the identifier.

  • **kwa – Keyword arguments forwarded to SignifyHab.make.

Returns:

The newly created and persisted SignifyHab instance.

Return type:

SignifyHab

property prefixes

Local prefixes registered in db.prefixes.

Type:

OrderedSet

reconfigure()[source]

Apply configuration from the Configer config file to this Habery.

Reads the config file via self.cf.get() and processes any OOBI URLs found in the following keys, storing OobiRecord entries in the database:

  • iurls — introduction OOBI URLs written to db.oobis.

  • durls — delegation OOBI URLs written to db.oobis.

  • wurls — well-known (MFA) OOBI URLs written to db.woobi.

The config file is treated as read-only at initialisation time. Runtime state changes must be written to the database, not the config file. The config file is intended to pre-load the database, not to act as a live database.

Example config file (JSON or HJSON):

{
    "dt": "2021-01-01T00:00:00.000000+00:00",
    "nel": {
        "dt": "2021-01-01T00:00:00.000000+00:00",
        "curls": ["tcp://localhost:5621/"]
    },
    "iurls": [
        "tcp://localhost:5620/?role=peer&name=tam"
    ],
    "durls": [
        "http://127.0.0.1:7723/oobi/EBNaNu-M9P5cgrnfl2Fvymy4E_jvxxyjb70PRtiANlJy",
        "http://127.0.0.1:7723/oobi/EMhvwOlyEJ9kN4PrwCpr9Jsv7TxPhiYveZ0oP3lJzdEi"
    ],
    "wurls": [
        "http://127.0.0.1:5644/.well-known/keri/oobi/EBNaNu-M9P5cgrnfl2Fvymy4E_jvxxyjb70PRtiANlJy?name=Root"
    ]
}
setup(*, seed=None, aeid=None, bran=None, pidx=None, algo=None, salt=None, tier=None, free=False, temp=None)[source]

Finish initialisation of the Habery after db and ks are open.

Intended to be called once both .db and .ks have been opened. This separation allows dependency injection of database instances that may be opened asynchronously after __init__. The first successful call performs vacuous (initial) database setup.

Parameters:
  • seed (str | None) – qb64 private signing key (seed) for the aeid. Used to derive the private decryption key and to authenticate the Manager. This value is memory-only and must never be persisted to the database. It must be loaded exactly once when the process starts and stored on a separate device from the one running the Manager.

  • aeid (str | None) – qb64 non-transferable identifier prefix used for authentication and encryption of secrets in the keystore. When provided and different from the aeid already in the database, all secrets are re-encrypted under the new aeid; in this case seed must also be provided. An aeid change should require a second authentication factor in addition to seed.

  • bran (str | None) – Base64 string of at least 21 characters used as base material to derive seed via salt stretching. Allows alphanumeric passcodes (e.g. from a password manager) to serve as the key-store secret. Ignored when seed is provided.

  • pidx (int | None) – Initial prefix index for a vacuous (empty) keystore.

  • algo (str | None) – Key-pair generation algorithm ('randy' or 'salty'). Defaults to the root algorithm (salty) when None.

  • salt (str | None) – qb64 salt used for signing-key creation. A fresh random salt is generated when None.

  • tier (str | None) – Security tier (Tierage) controlling the cost of salt-to-seed stretching.

  • free (bool) – When True, releases (closes) resources when the associated Doer exits.

  • temp (bool | None) – When True, overrides the instance temp flag to use fast salt-stretch methods during setup.

Raises:
  • ClosedError – If .ks or .db is not open when called.

  • ValueError – If bran is shorter than 21 characters.

  • AuthError – If the provided seed does not authenticate the aeid stored in the keystore.

property signator

Signer and verifier for data-at-rest in this Habery environment. None until setup completes successfully.

Type:

Signator

class keri.app.habbing.HaberyDoer(habery, **kwa)[source]

Doer subclass that manages Habery lifecycle within a coroutine context.

Initializes the Habery on enter if not already inited, and closes it on exit if inited and free. Intended to drive Habery setup and teardown as part of a Doist-managed task graph.

habery

Habery instance whose lifecycle this doer manages.

Type:

Habery

Inherited Attributes:
done (bool): Completion state. True means finished normally;

False indicates incomplete due to close or abort.

tyme (float): Relative cycle time obtained from the injected

tymth closure.

tymth (callable): Injected closure returned by Tymist.tymeth().

Call it to get the current Tymist.tyme. Injected via wind().

tock (float): Desired seconds between recur calls. Zero means run

ASAP. Non-negative.

Note

Implements the Doer coroutine protocol: enter, recur, exit, close, and abort. See doing.Doer for the full interface.

__init__(habery, **kwa)[source]

Initializes HaberyDoer with the Habery instance to manage.

Parameters:
  • habery (Habery) – Habery instance to initialize and close during the doer lifecycle.

  • **kwa – Additional keyword arguments forwarded to Doer.__init__.

enter(*, temp=None)[source]

Enters the doer context and initializes Habery if not already inited.

Calls habery.setup() with its stored _inits parameters only when habery.inited is False. No-ops if Habery is already initialized.

Parameters:

temp (bool | None) – Unused in this implementation. Present for interface compatibility with the base Doer enter signature.

exit()[source]

Exits the doer context and closes Habery if inited and free.

Calls habery.close() with clear set to habery.temp, which causes database files to be removed when operating in temporary mode. No-ops if Habery is not inited or not free.

class keri.app.habbing.Signator(db, name='__signatory__', **kwa)[source]

Manages a non-transferable identifier used to sign and verify data at rest.

Creates a single non-transferable AID on first initialization and persists it in the Habery database. Subsequent instantiations with the same name rehydrate the existing AID. Intended for signing BADA data to ensure integrity at rest.

db

Database environment used for key state and prefix storage.

Type:

Baser

pre

Qualified Base64 AID prefix for the signing identifier.

Type:

str

__init__(db, name='__signatory__', **kwa)[source]

Initializes the Signator, creating a new signing AID if none exists for name.

Looks up name in the Habery prefix index. If absent, creates a new non-transferable, hidden Hab and pins its prefix. If present, rehydrates the existing Hab from the stored prefix.

Parameters:
  • db (Baser) – Database environment for key state and AID storage.

  • name (str) – Label used to look up or register the signing AID. Defaults to SIGNER.

  • **kwa – Additional keyword arguments forwarded to Hab.

sign(ser)[source]

Signs raw bytes using the Signator’s non-transferable private key.

Delegates to the underlying Hab’s sign method with indexed=False, returning the first (and only) Cigar signature object.

Parameters:

ser (bytes) – Raw byte data to sign.

Returns:

Non-indexed signature over ser using the current verfer’s

private key.

Return type:

Cigar

verify(ser, cigar)[source]

Verifies a Cigar signature against raw bytes using the current verfer.

Checks the raw signature in cigar against ser using the first verfer on the Signator’s current key event state (kever).

Parameters:
  • ser (bytes) – Raw byte data to verify against the signature.

  • cigar (Cigar) – Non-transferable signature to verify.

Returns:

True if the signature is cryptographically valid for ser,

False otherwise.

Return type:

bool

class keri.app.habbing.SignifyGroupHab(smids, mhab=None, rmids=None, **kwa)[source]

Remote-signer group (multisig) habitat.

Extends SignifyHab to support multisig group identifiers whose private keys are held by a remote Signify agent. Tracks the group signing member aids (smids) and rotating member aids (rmids) alongside the local participant member hab (mhab).

mhab

The local participant member hab for this group.

Type:

SignifyHab

smids

qb64 prefixes of current signing members of the group.

Type:

list[str]

rmids

qb64 prefixes of rotating members of the group. Defaults to smids when not supplied.

Type:

list[str]

incept(*, serder, sigers, **kwa)[source]

Finish setting up this SignifyGroupHab from a pre-built inception event.

Registers the group prefix, processes the inception event, persists the habitat record (including group member metadata), and marks the hab as initialised.

Parameters:
  • serder (SerderKERI) – Pre-built inception event serder. The prefix serder.ked["i"] is assigned to self.pre.

  • sigers (list[Siger]) – Siger instances carrying the remote agent’s signatures over serder.raw.

  • **kwa – Absorbed for API compatibility; not used.

processEvent(serder, sigers)[source]

Process an event through the local Kevery, tolerating missing signatures.

MissingSignatureError is silently swallowed so that multisig events can be created and stored with only a single local member’s signature, pending collection of the remaining co-signers’ contributions.

Parameters:
  • serder (SerderKERI) – Event serder to process.

  • sigers (list) – Signature instances over serder.raw.

Raises:

ValidationError – If the Kevery raises any exception other than MissingSignatureError.

rotate(*, smids=None, rmids=None, serder=None, sigers=None, **kwa)[source]

Perform a rotation operation and update group member lists.

Delegates the core rotation to SignifyHab.rotate, then updates the smids and rmids on both the instance and the persisted HabitatRecord.

Parameters:
  • smids (list or None) – Updated qb64 prefixes of signing members after rotation.

  • rmids (list or None) – Updated qb64 prefixes of rotating members after rotation.

  • serder (SerderKERI) – Pre-built rotation event serder.

  • sigers (list[Siger]) – Siger instances carrying the remote agent’s signatures over serder.raw.

  • **kwa – passed through to superclass rotate

Raises:

ValidationError – If the habitat record for self.pre does not exist in the database.

class keri.app.habbing.SignifyHab(**kwa)[source]

Remote-signer habitat for a given identifier controller.

Provides the local resource environment (hab or habitat) for a controller whose private keys are held by a remote signer (Signify agent), rather than locally. Inception and rotation events are supplied to make and rotate as pre-built, pre-signed serders; this class never generates or holds private key material, and its sign method always raises KeriError.

ks

LMDB key store. (Injected)

Type:

keeping.Keeper

db

LMDB database for KEL etc. (Injected)

Type:

basing.Baser

cf

Configuration file instance. (Injected)

Type:

configing.Configer

mgr

Creates and rotates keys in the key store. (Injected)

Type:

keeping.Manager

rtr

Routes reply rpy messages. (Injected)

Type:

routing.Router

rvy

Factory that processes reply rpy messages. (Injected)

Type:

routing.Revery

kvy

Factory for local processing of local event messages. (Injected)

Type:

eventing.Kevery

psr

Parses local messages for .kvy and .rvy. (Injected)

Type:

parsing.Parser

name

Alias of the controller.

Type:

str

pre

qb64 prefix of the own local controller, or None if new.

Type:

str

temp

True means testing — uses weak level when salty algo for stretching in key creation for incept and rotate of keys for this hab.pre.

Type:

bool

inited

True means fully initialized with respect to databases; False means not yet fully initialized.

Type:

bool

delpre

Delegator prefix if any, else None.

Type:

str or None

exchange(*, serder=None, save=False, sigers=None, source=None, bonds=None, wigers=None, cigars=None, framed=False, nested=False, gvrsn=(1, 0), genusify=False, **kwa)[source]

Messagize peer-to-peer exchange message from exchange msg serder with provided signatures. When save is True a local copy is parsed into the database for record keeping.

Parameters::

serder (SerderKERI): Pre-built exchange event serder. save (bool): When True, parse a copy of the assembled message

into the local database. Defaults to False.

sigers (list or None): Siger instances carrying signatures

over serder.raw.

source (SealEvent|SealLast|None): optiona modifier to sigers when provided
If SealEvent use attachment group code TransIdxSigGroups plus attach

triple pre+snu+dig made from (i,s,d) of seal plus ControllerIdxSigs plus attached indexed sigs in sigers

Elif SealLast use attachment group code TransLastIdxSigGroups plus

attach uniple pre made from (i,) of seal plus ControllerIdxSigs plus attached indexed sigs in sigers

Else None use ControllerIdxSigs plus attached indexed sigs in sigers

bonds (list[]|SealEvent|SealSource|SealLast|BlindState|BoundState|TypeMedia|None):

Non signature based authenticator typically an event reference or may Only v2 supports BlindState|BoundState|TypeMedia if bonds is not list convert to list.

wigers (list): optional list of Siger instances of witness index signatures cigars (list): optional list of Cigars instances of non-transferable non indexed

signatures from which to form receipt couples. Each cigar.vefer.qb64 is pre of receiptor and cigar.qb64 is signature

framed (bool): True means may assume each message plus its attachments

is isolated as frame when parsing so do not need attachment group when messagizing

False means may not assume eash message plus its attachments

is isolated as frame when parsing so do need attachment group when messagizing

nested (bool): True means messagize for non-top level

This forces non-native serializion to be embedded in non-native group code

False means messagize for top level of stream.

This allows bare non-native serialization of message

gvrsn (Versionage): CESR Genus version for attachment group codes or

nesting group code (useful when serder.gvrsn < 2) gvrsn = max(svrsn, gvrsn) where svrsn = serder.gvrsn

if serder.gvrsn else serder.pvrsn

genusify (bool): True means prepend genus version code from gvrsn before

serder to override default stream genus version

False means do nothing

**kwa: Absorbed for API compatibility; not used.

Returns::
msg (bytearray): Exchange message with count code and attached

signatures.

incept(*, serder=None, sigers=None, source=None, bonds=None, wigers=None, cigars=None, framed=False, nested=False, gvrsn=(1, 0), genusify=False, **kwa)[source]

Finish setting up this SignifyHab from a pre-built inception event.

Registers the prefix, processes the inception event through the local Kevery, persists the habitat record, and marks the hab as initialised.

Parameters:
  • serder (SerderKERI) – Pre-built inception event serder. The prefix serder.ked["i"] is assigned to self.pre.

  • sigers (list[Siger]|None) – Siger instances carrying the remote agent’s signatures over serder.raw.

  • source (SealEvent|SealLast|None) –

    optiona modifier to sigers when provided If SealEvent use attachment group code TransIdxSigGroups plus attach

    triple pre+snu+dig made from (i,s,d) of seal plus ControllerIdxSigs plus attached indexed sigs in sigers

    Elif SealLast use attachment group code TransLastIdxSigGroups plus

    attach uniple pre made from (i,) of seal plus ControllerIdxSigs plus attached indexed sigs in sigers

    Else None use ControllerIdxSigs plus attached indexed sigs in sigers

  • bonds (list[]|SealEvent|SealSource|SealLast|BlindState|BoundState|TypeMedia|None) – Non signature based authenticator typically an event reference or may Only v2 supports BlindState|BoundState|TypeMedia if bonds is not list convert to list.

  • wigers (list) – optional list of Siger instances of witness index signatures

  • cigars (list) – optional list of Cigars instances of non-transferable non indexed signatures from which to form receipt couples. Each cigar.vefer.qb64 is pre of receiptor and cigar.qb64 is signature

  • framed (bool) –

    True means may assume each message plus its attachments

    is isolated as frame when parsing so do not need attachment group when messagizing

    False means may not assume eash message plus its attachments

    is isolated as frame when parsing so do need attachment group when messagizing

  • nested (bool) –

    True means messagize for non-top level

    This forces non-native serializion to be embedded in non-native group code

    False means messagize for top level of stream.

    This allows bare non-native serialization of message

  • gvrsn (Versionage) –

    CESR Genus version for attachment group codes or nesting group code (useful when serder.gvrsn < 2) gvrsn = max(svrsn, gvrsn) where svrsn = serder.gvrsn

    if serder.gvrsn else serder.pvrsn

  • genusify (bool) –

    True means prepend genus version code from gvrsn before

    serder to override default stream genus version

    False means do nothing

  • **kwas – Absorbed for API compatibility; not used.

interact(*, serder=None, sigers=None, source=None, bonds=None, wigers=None, cigars=None, framed=False, nested=False, gvrsn=(1, 0), genusify=False, **kwa)[source]

Perform an interaction operation from a pre-built, pre-signed event.

Packages the provided serder and sigers into a message and processes it through the local Kevery to update key state.

Parameters::

serder (SerderKERI): Pre-built interaction event serder. sigers (list[Siger]): Siger instances carrying the remote

agent’s signatures over serder.raw.

source (SealEvent|SealLast|None): optiona modifier to sigers when provided
If SealEvent use attachment group code TransIdxSigGroups plus attach

triple pre+snu+dig made from (i,s,d) of seal plus ControllerIdxSigs plus attached indexed sigs in sigers

Elif SealLast use attachment group code TransLastIdxSigGroups plus

attach uniple pre made from (i,) of seal plus ControllerIdxSigs plus attached indexed sigs in sigers

Else None use ControllerIdxSigs plus attached indexed sigs in sigers

bonds (list[]|SealEvent|SealSource|SealLast|BlindState|BoundState|TypeMedia|None):

Non signature based authenticator typically an event reference or may Only v2 supports BlindState|BoundState|TypeMedia if bonds is not list convert to list.

wigers (list): optional list of Siger instances of witness index signatures cigars (list): optional list of Cigars instances of non-transferable non indexed

signatures from which to form receipt couples. Each cigar.vefer.qb64 is pre of receiptor and cigar.qb64 is signature

framed (bool): True means may assume each message plus its attachments

is isolated as frame when parsing so do not need attachment group when messagizing

False means may not assume eash message plus its attachments

is isolated as frame when parsing so do need attachment group when messagizing

nested (bool): True means messagize for non-top level

This forces non-native serializion to be embedded in non-native group code

False means messagize for top level of stream.

This allows bare non-native serialization of message

gvrsn (Versionage): CESR Genus version for attachment group codes or

nesting group code (useful when serder.gvrsn < 2) gvrsn = max(svrsn, gvrsn) where svrsn = serder.gvrsn

if serder.gvrsn else serder.pvrsn

genusify (bool): True means prepend genus version code from gvrsn before

serder to override default stream genus version

False means do nothing

**kwa: Absorbed for API compatibility; not used.

Returns::

bytearray: Interaction message with attached signatures.

processEvent(serder, sigers)[source]

Process an event through the local Kevery, re-raising all exceptions.

Unlike GroupHab.processEvent, this method does not swallow MissingSignatureError; any exception from the Kevery is wrapped in a ConfigurationError and re-raised.

Parameters::

serder (SerderKERI): Event serder to process. sigers (list[Siger]| None): Signature instances over

serder.raw.

Raises::
ConfigurationError: If the Kevery raises any exception during

event processing.

replyEndRole(cid, role=None, eids=None, scheme='', **kwa)[source]

Build a reply message stream for endpoint role authorisations.

Assembles a rpy message stream containing the KEL replay for cid plus any authorised endpoint role records and location scheme records relevant to the requested role and scheme filters. Uses a promiscuous discovery model — future versions may restrict discovery via an identity constraint graph.

The returned stream content depends on the combination of arguments:

  • cid only — end authz for all eids in all roles, loc URLs for all schemes at each eid (optionally restricted to eids).

  • cid + scheme — end authz for all eids in all roles, loc URL for scheme at each eid (optionally restricted to eids).

  • cid + role — end authz for all eids in role, loc URLs for all schemes at each eid (optionally restricted to eids).

  • cid + role + scheme — end authz for all eids in role, loc URL for scheme at each eid (optionally restricted to eids).

When role is Roles.witness and this hab is itself one of cid’s witnesses, the KEL replay is used as the authorisation instead of explicit end-role records.

Parameters::
cid (str): qb64 identifier prefix of the controller whose

endpoint authorisations are being requested.

role (str or None): Authorised role to filter by. None means

all roles.

eids (list or None): When provided, restricts returned records to

only the endpoint identifiers listed here.

scheme (str): URL scheme to filter location records by. An empty

string (default) means all schemes.

**kwa: keyword arguments forwarded to eventing.reply, including:

route (str): route path string indicating the data flow handler. data (list): dicts of committed data such as seals. dts (str): date-time-stamp of message at time of creation. version (Version): version instance. kind (str): serialization kind.

Returns::

bytearray: Concatenated reply message stream containing KEL replay, location scheme records, and end-role records.

rotate(*, serder=None, sigers=None, source=None, bonds=None, wigers=None, cigars=None, framed=False, nested=False, gvrsn=(1, 0), genusify=False, **kwa)[source]

Messagize a rotation operation from a pre-built, pre-signed event.

Packages the provided serder and sigers into a message and processes it through the local Kevery to update key state.

Parameters::

serder (SerderKERI): Pre-built rotation event serder. sigers (list[Siger]|None): Siger instances carrying the remote

agent’s signatures over serder.raw.

source (SealEvent|SealLast|None): optiona modifier to sigers when provided
If SealEvent use attachment group code TransIdxSigGroups plus attach

triple pre+snu+dig made from (i,s,d) of seal plus ControllerIdxSigs plus attached indexed sigs in sigers

Elif SealLast use attachment group code TransLastIdxSigGroups plus

attach uniple pre made from (i,) of seal plus ControllerIdxSigs plus attached indexed sigs in sigers

Else None use ControllerIdxSigs plus attached indexed sigs in sigers

bonds (list[]|SealEvent|SealSource|SealLast|BlindState|BoundState|TypeMedia|None):

Non signature based authenticator typically an event reference or may Only v2 supports BlindState|BoundState|TypeMedia if bonds is not list convert to list.

wigers (list): optional list of Siger instances of witness index signatures cigars (list): optional list of Cigars instances of non-transferable non indexed

signatures from which to form receipt couples. Each cigar.vefer.qb64 is pre of receiptor and cigar.qb64 is signature

framed (bool): True means may assume each message plus its attachments

is isolated as frame when parsing so do not need attachment group when messagizing

False means may not assume eash message plus its attachments

is isolated as frame when parsing so do need attachment group when messagizing

nested (bool): True means messagize for non-top level

This forces non-native serializion to be embedded in non-native group code

False means messagize for top level of stream.

This allows bare non-native serialization of message

gvrsn (Versionage): CESR Genus version for attachment group codes or

nesting group code (useful when serder.gvrsn < 2) gvrsn = max(svrsn, gvrsn) where svrsn = serder.gvrsn

if serder.gvrsn else serder.pvrsn

genusify (bool): True means prepend genus version code from gvrsn before

serder to override default stream genus version

False means do nothing

**kwa: Absorbed for API compatibility; not used.

Returns::

bytearray: Rotation message with attached signatures.

sign(ser, verfers=None, indexed=True, indices=None, ondices=None, **kwa)[source]

Signing is not supported for SignifyHab. So raises error.

Private keys are held by the remote Signify agent, so local signing is intentionally disabled.

Parameters::

ser (bytes): Serialization to sign. verfers (list or None): Ignored. indexed (bool): Ignored. indices (list or None): Ignored. ondices (list or None): Ignored. **kwa: Ignored.

Raises::

KeriError: Always because local signing is not permitted for this hab type.

keri.app.habbing.openHab(name='test', base='', salt=None, temp=True, cf=None, **kwa)[source]

Context manager that creates and yields a (Habery, Hab) pair, closing and optionally clearing resources on exit.

If a Hab with name already exists in the Habery it is reused; otherwise a new single-key Hab (icount=1, isith='1', ncount=1, nsith='1') is created via Habery.makeHab.

Parameters::

name (str): Name of the Hab (and the underlying shared databases). base (str): Optional path component for shared resources. See

openHby.

salt (bytes | None): Raw (not qb64) salt bytes passed to Habery.

Converted to qb64 internally. A fresh salt is generated when None.

temp (bool): True means use temporary databases. See openHby. cf (Configer | None): Optional Configer instance for loading

configuration data.

**kwa: Additional keyword arguments forwarded to Habery.makeHab.

When version is provided, it is also used for the shared Habery parser.

Yields::
tuple[Habery, Hab]: The shared Habery environment and the named

Hab instance.

keri.app.habbing.openHby(*, name='test', base='', temp=True, salt=None, **kwa)[source]

Context manager that creates and yields a Habery instance, closing and optionally clearing it on exit.

Parameters::

name (str): Name used for the shared databases and config file path. base (str): Optional path component inserted before name for

further hierarchical differentiation of databases. Empty string means no additional component.

temp (bool): When True, stores .ks, .db, and .cf in

/tmp and uses a fast (low-cost) salt-stretch method suitable for testing. When False, uses the resource tier specified by tier.

salt (str): qb64-encoded salt used for key-pair creation. A fresh

random salt is generated when None.

**kwa: Additional keyword arguments forwarded to Habery.__init__.

See Habery for the full list (seed, aeid, bran, pidx, algo, tier, free, version).

Yields::

Habery: Fully initialised Habery instance.

keri.app.httping

keri.peer.httping module

class keri.app.httping.CesrRequest(payload: dict, attachments: str)[source]
class keri.app.httping.Clienter[source]

Clienter is a DoDoer that manages hio HTTP clients using a ClientDoer for each HTTP request. It executes HTTP requests using a HIO HTTP Client run by a ClientDoer. Once a request has received a response then the corresponding Doer is removed from this Clienter.

Doers:
  • clientDo: Periodically checks for stale clients and removes them if they have not received a response within the specified timeout period.

__init__()[source]

Initialize clienter with an empty list of client tuples.

clients

Active client tuples, each containing a ClientDoer instance, an hio HTTP Client instance, and a datetime timestamp.

Type:

list[tuple]

doers

Doers managed by this Clienter, initialized with clientDo.

Type:

list

clientDo(tymth, tock=0.0, **kwa)[source]

Periodically prune stale clients

Process existing clients and prune any that have receieved a response longer than timeout

Parameters:
  • tymth (function) – injected function wrapper closure returned by .tymen() of Tymist instance. Calling tymth() returns associated Tymist .tyme.

  • tock (float) – injected initial tock value

remove(client)[source]

Find a client tuple by hio HTTP Client and remove it and its Doer from the Clienter.

Parameters:

client (http.clienting.Client) – The hio HTTP Client to remove from the Clienter.

request(method, url, body=None, headers=None)[source]

Perform an HTTP request using a hio http Client and ClientDoer and returns the Client.

Parameters:
  • method (str) – HTTP method to use (e.g., “GET”, “POST”)

  • url (str) – URL to send the request to

  • body (str or bytes, optional) – Body of the request, defaults to None

  • headers (dict, optional) – Headers to include in the request, defaults to None

Returns:

The hio HTTP Client used for the request, or None if an error occurs.

Return type:

http.clienting.Client

class keri.app.httping.SignatureValidationComponent(hby, pre)[source]

Validate SKWA signatures

process_request(req, resp)[source]

Process request to ensure has a valid signature from controller

Parameters:
  • req – Http request object

  • resp – Http response object

keri.app.httping.createCESRRequest(msg, client, dest, path=None)[source]

Turns a KERI message into a CESR http request against the provided hio http Client

Parameters

msg: KERI message parsable as Serder.raw dest (str): qb64 identifier prefix of destination controller client: hio http Client that will send the message as a CESR request path (str): path to post to

keri.app.httping.parseCesrHttpRequest(req)[source]

Parse Falcon HTTP request and create a CESR message from the body of the request and the two CESR HTTP headers (Date, Attachment).

Parameters

req (falcon.Request) http request object in CESR format:

keri.app.httping.streamCESRRequests(client, ims, dest, path=None, headers=None)[source]

Turns a stream of KERI messages into CESR http requests against the provided hio http Client

Parameters

client (Client): hio http Client that will send the message as a CESR request ims (bytearray): stream of KERI messages parsable as Serder.raw dest (str): qb64 identifier prefix of destination controller path (str): path to post to

Returns

int: Number of individual requests posted

keri.app.indirecting

KERI keri.app.indirecting module

simple indirect mode demo support classes

class keri.app.indirecting.HttpEnd(rxbs=None, mbx=None, qrycues=None)[source]

HTTP handler that accepts and KERI events POSTed as the body of a request with all attachments to the message as a CESR attachment HTTP header. KEL Messages are processed and added to the database of the provided Habitat.

This also handles req, exn and tel messages that respond with a KEL replay.

__init__(rxbs=None, mbx=None, qrycues=None)[source]

Create the KEL HTTP server from the Habitat with an optional Falcon App to register the routes with.

Parameters

rxbs (bytearray): output queue of bytes for message processing mbx (Mailboxer): Mailbox storage qrycues (Deck): inbound qry response queues

on_post(req, rep)[source]

Handles POST for KERI event messages.

Parameters:
  • req (Request)

  • rep (Response)

---
summary:  Accept KERI events with attachment headers and parse
description:  Accept KERI events with attachment headers and parse.
tags:
   - Events
requestBody:
   required: true
   content:
     application/json:
       schema:
         type: object
         description: KERI event message
responses:
   200:
      description: Mailbox query response for server sent events
   204:
      description: KEL or EXN event accepted.
on_put(req, rep)[source]

Handles PUT for KERI mbx event messages.

Parameters:
  • req (Request)

  • rep (Response)

---
summary:  Accept KERI events with attachment headers and parse
description:  Accept KERI events with attachment headers and parse.
tags:
   - Events
requestBody:
   required: true
   content:
     application/json:
       schema:
         type: object
         description: KERI event message
responses:
   200:
      description: Mailbox query response for server sent events
   204:
      description: KEL or EXN event accepted.
class keri.app.indirecting.Indirector(hab, client, direct=True, doers=None, **kwa)[source]

Base class for Indirect Mode KERI Controller Doer with habitat and TCP Clients for talking to witnesses

Subclass of DoDoer with doers list from do generator methods: .msgDo, .cueDo, and .escrowDo.

Enables continuous scheduling of doers (do generator instances or functions)

Implements Doist like functionality to allow nested scheduling of doers. Each DoDoer runs a list of doers like a Doist but using the tyme from its injected tymist as injected by its parent DoDoer or Doist.

Scheduling hierarchy: Doist->DoDoer…->DoDoer->Doers

.done is Boolean completion state

True means completed Otherwise incomplete. Incompletion maybe due to close or abort.

.opts is dict of injected options for its generator .do
.doers is list of Doers or Doer like generator functions
hab (Habitat

local controller’s context

client

hio TCP client instance. Assumes operated by another doer.

Type:

serving.Client

Properties:
tyme (float): relative cycle time of associated Tymist, obtained

via injected .tymth function wrapper closure.

tymth (function): function wrapper closure returned by Tymist .tymeth()

method. When .tymth is called it returns associated Tymist .tyme. .tymth provides injected dependency on Tymist tyme base.

tock (float): desired time in seconds between runs or until next run,

non negative, zero means run asap

.wind  injects ._tymth dependency from associated Tymist to get its .tyme
.__call__ makes instance callable

Appears as generator function that returns generator

.do is generator method that returns generator
.enter is enter context action method
.recur is recur context action method or generator method
.clean is clean context action method
.exit is exit context method
.close is close context method
.abort is abort context method
Hidden:
._tymth is injected function wrapper closure returned by .tymen() of

associated Tymist instance that returns Tymist .tyme. when called.

._tock is hidden attribute for .tock property

__init__(hab, client, direct=True, doers=None, **kwa)[source]

Initialize instance.

Inherited Parameters:

tymist is Tymist instance tock is float seconds initial value of .tock doers is list of doers (do generator instances, functions or methods)

Parameters:
  • context (hab is Habitat instance of local controller's)

  • instance (client is TCP Client)

  • Boolean (direct is) – False means indirect mode don’t process cue’ed receipts

  • receipts (True means direwct mode process cured) – False means indirect mode don’t process cue’ed receipts

cueDo(tymth=None, tock=0.0, **kwa)[source]
Returns doifiable Doist compatibile generator method (doer dog) to process

.kevery.cues deque

Doist Injected Attributes:

g.tock = tock # default tock attributes g.done = None # default done state g.opts

Parameters:
  • of (tymth is injected function wrapper closure returned by .tymen()) – Tymist instance. Calling tymth() returns associated Tymist .tyme.

  • value (tock is injected initial tock)

Usage:

add result of doify on this method to doers list

escrowDo(tymth=None, tock=0.0, **kwa)[source]
Returns doifiable Doist compatibile generator method (doer dog) to process

.kevery escrows.

Doist Injected Attributes:

g.tock = tock # default tock attributes g.done = None # default done state g.opts

Parameters:
  • of (tymth is injected function wrapper closure returned by .tymen()) – Tymist instance. Calling tymth() returns associated Tymist .tyme.

  • value (tock is injected initial tock)

Usage:

add result of doify on this method to doers list

msgDo(tymth=None, tock=0.0, **kwa)[source]
Returns doifiable Doist compatibile generator method (doer dog) to process

incoming message stream of .kevery

Doist Injected Attributes:

g.tock = tock # default tock attributes g.done = None # default done state g.opts

Parameters:
  • of (tymth is injected function wrapper closure returned by .tymen()) – Tymist instance. Calling tymth() returns associated Tymist .tyme.

  • value (tock is injected initial tock)

Usage:

add result of doify on this method to doers list

sendMessage(msg, label='')[source]

Sends message msg and loggers label if any

wind(tymth)[source]

Inject new tymist.tymth as new ._tymth. Changes tymist.tyme base. Updates winds .tymer .tymth

class keri.app.indirecting.MailboxDirector(hby, topics, ims=None, verifier=None, kvy=None, exc=None, rep=None, cues=None, rvy=None, tvy=None, witnesses=True, **kwa)[source]

Class for Indirect Mode KERI Controller Doer with habitat and TCP Clients for talking to witnesses

Subclass of DoDoer with doers list from do generator methods: .msgDo, .cueDo, and .escrowDo.

Enables continuous scheduling of doers (do generator instances or functions)

Implements Doist like functionality to allow nested scheduling of doers. Each DoDoer runs a list of doers like a Doist but using the tyme from its injected tymist as injected by its parent DoDoer or Doist.

Scheduling hierarchy: Doist->DoDoer…->DoDoer->Doers

.done is Boolean completion state

True means completed Otherwise incomplete. Incompletion maybe due to close or abort.

.opts is dict of injected options for its generator .do
.doers is list of Doers or Doer like generator functions
hby (Habitat

local controller’s context

Properties:

hby (Habery): the Habery in which mailbox messages are routed verifier (Verifier): TEL event acceptor and validator exchanger (Exchanger): Exchange (exn) message delivery component rep (Respondant): Respondant for reply messages cues (Deck): Queue for new actions to schedule shared between the Revery, Kevery (and Kever), and Tevery (and Tever)

.wind  injects ._tymth dependency from associated Tymist to get its .tyme
.__call__ makes instance callable

Appears as generator function that returns generator

.do is generator method that returns generator
.enter is enter context action method
.recur is recur context action method or generator method
.clean is clean context action method
.exit is exit context method
.close is close context method
.abort is abort context method
Hidden:
._tymth is injected function wrapper closure returned by .tymen() of

associated Tymist instance that returns Tymist .tyme. when called.

._tock is hidden attribute for .tock property

__init__(hby, topics, ims=None, verifier=None, kvy=None, exc=None, rep=None, cues=None, rvy=None, tvy=None, witnesses=True, **kwa)[source]

Initialize instance.

Inherited Parameters:

tymist is Tymist instance tock is float seconds initial value of .tock doers is list of doers (do generator instances, functions or methods)

Parameters:
  • context (hab is Habitat instance of local controller's)

  • instance (client is TCP Client)

  • Boolean (direct is) – False means indirect mode don’t process cue’ed receipts

  • receipts (True means direwct mode process cured) – False means indirect mode don’t process cue’ed receipts

addPollers(hab)[source]

add mailbox pollers for every witness for this prefix identifier

Parameters:

hab (Hab) – the Hab of the prefix

escrowDo(tymth=None, tock=0.0, **kwa)[source]
Returns doifiable Doist compatibile generator method (doer dog) to process

.kevery escrows.

Doist Injected Attributes:

g.tock = tock # default tock attributes g.done = None # default done state g.opts

Parameters:
  • of (tymth is injected function wrapper closure returned by .tymen()) – Tymist instance. Calling tymth() returns associated Tymist .tyme.

  • value (tock is injected initial tock)

Usage:

add result of doify on this method to doers list

msgDo(tymth=None, tock=0.0, **kwa)[source]
Returns doifiable Doist compatibile generator method (doer dog) to process

incoming message stream of .kevery

Doist Injected Attributes:

g.tock = tock # default tock attributes g.done = None # default done state g.opts

Parameters:
  • of (tymth is injected function wrapper closure returned by .tymen()) – Tymist instance. Calling tymth() returns associated Tymist .tyme.

  • value (tock is injected initial tock)

Usage:

add result of doify on this method to doers list

pollDo(tymth=None, tock=0.0, **kwa)[source]
Returns:

doifiable Doist compatible generator method

Usage:

add result of doify on this method to doers list

processPollIter()[source]

Iterate through cues and yields one or more responses for each cue.

Parameters:

cues (cues is deque of)

wind(tymth)[source]

Inject new tymist.tymth as new ._tymth. Changes tymist.tyme base. Updates winds .tymer .tymth

class keri.app.indirecting.Poller(hab, witness, topics, msgs=None, retry=1000, **kwa)[source]

Polls remote SSE endpoint for event that are KERI messages to be processed

__init__(hab, witness, topics, msgs=None, retry=1000, **kwa)[source]

Returns doist compatible doing.Doer that polls a witness for mailbox messages as SSE events

Parameters:
  • hab

  • witness

  • topics

  • msgs

eventDo(tymth=None, tock=0.0, **kwa)[source]
Returns:

doifiable Doist compatible generator method

Usage:

add result of doify on this method to doers list

class keri.app.indirecting.QueryEnd(hab, reger)[source]

Endpoint class for quering witness for KELs and TELs using HTTP GET

on_get(req, rep)[source]

Handles GET requests to query KEL or TEL events of a pre from a witness.

Parameters:
  • req (Request)

  • rep (Response)

Query Parameters:

typ (string): The type of event data to query for. Accepted values are: - ‘kel’: Retrieve KEL events for a specified ‘pre’. - ‘tel’: Retrieve TEL events based on ‘reg’ or ‘vcid’.

pre (string, optional): For ‘kel’ queries, the specific ‘pre’ to query. sn (int, optional): For “kel” queries. If provided, returns events with seq-num >= sn.

reg (string, optional): For ‘tel’ queries, registry pre. Required if vcid not provided. vcid (string, optional): For ‘tel’ queries, credential said. Required if reg not provided.

Response:
  • 200 OK: Returns event data in “application/cesr” format.

  • 400 Bad Request: Returned if required query parameters are missing or if an invalid typ is specified.

Example

  • /query?typ=kel&pre=ELZ1KBCFOmdj1RPu6kMUnzgMBTl4YsHfpw7wIGvLgW5W

  • /query?typ=kel&pre=ELZ1KBCFOmdj1RPu6kMUnzgMBTl4YsHfpw7wIGvLgW5W&sn=5

  • /query?typ=tel&reg=EHrbPfpRLU9wpFXTzGY-LIo2FjMiljjEnt238eWHb7yZ&vcid=EO5y0jMXS5XKTYBKjCUPmNKPr1FWcWhtKwB2Go2ozvr0

class keri.app.indirecting.ReceiptEnd(hab, inbound=None, outbound=None, aids=None)[source]

Endpoint class for Witnessing receipting functionality

Most times a witness will be able to return its receipt for an event inband. This API will provide that functionality. When an event needs to be escrowed, this POST API will return a 202 and also provides a generic GET API for retrieving a receipt for any event.

interceptDo(tymth=None, tock=0.0, **kwa)[source]
Returns doifiable Doist compatibile generator method (doer dog) to process

Kevery and Tevery cues deque

Usage:

add result of doify on this method to doers list

on_get(req, rep)[source]

Receipt GET endpoint handler

Parameters:
  • req (Request) – Falcon HTTP request object

  • rep (Response) – Falcon HTTP response object

on_post(req, rep)[source]

Receipt POST endpoint handler

Parameters:
  • req (Request) – Falcon HTTP request object

  • rep (Response) – Falcon HTTP response object

class keri.app.indirecting.WitnessStart(hab, parser, kvy, tvy, rvy, exc, cues=None, replies=None, responses=None, queries=None, **opts)[source]

Doer to print witness prefix after initialization

cueDo(tymth=None, tock=0.0, **kwa)[source]
Returns doifiable Doist compatibile generator method (doer dog) to process

.kevery.cues deque

Doist Injected Attributes:

g.tock = tock # default tock attributes g.done = None # default done state g.opts

Parameters:
  • of (tymth is injected function wrapper closure returned by .tymen()) – Tymist instance. Calling tymth() returns associated Tymist .tyme.

  • value (tock is injected initial tock)

Usage:

add result of doify on this method to doers list

escrowDo(tymth=None, tock=0.0, **kwa)[source]
Returns doifiable Doist compatibile generator method (doer dog) to process

.kevery and .tevery escrows.

Parameters:
  • tymth (function) – injected function wrapper closure returned by .tymen() of Tymist instance. Calling tymth() returns associated Tymist .tyme.

  • tock (float) – injected initial tock value

Usage:

add result of doify on this method to doers list

msgDo(tymth=None, tock=0.0, **kwa)[source]
Returns doifiable Doist compatibile generator method (doer dog) to process

incoming message stream of .kevery

Parameters:
  • tymth (function) – injected function wrapper closure returned by .tymen() of Tymist instance. Calling tymth() returns associated Tymist .tyme.

  • tock (float) – injected initial tock value

Usage:

add result of doify on this method to doers list

start(tymth=None, tock=0.0, **kwa)[source]

Prints witness name and prefix

Parameters:
  • tymth (function) – injected function wrapper closure returned by .tymen() of Tymist instance. Calling tymth() returns associated Tymist .tyme.

  • tock (float) – injected initial tock value

keri.app.indirecting.createHttpServer(host, port, app, keypath=None, certpath=None, cafilepath=None)[source]

Create an HTTP or HTTPS server depending on whether TLS key material is present :param host: host to bind to for this server, or None for default of ‘0.0.0.0’, all ifaces :type host: str :param port: port to listen on for all HTTP(s) server instances :type port: int :param app: WSGI application instance to pass to the http.Server instance :type app: Any :param keypath: the file path to the TLS private key :type keypath: string :param certpath: the file path to the TLS signed certificate (public key) :type certpath: string :param cafilepath: the file path to the TLS CA certificate chain file :type cafilepath: string

Returns:

hio.core.http.Server

keri.app.indirecting.setupWitness(hby, alias='witness', mbx=None, aids=None, tcpPort=5631, httpPort=5632, keypath=None, certpath=None, cafilepath=None, **kwa)[source]

Setup witness controller and doers

keri.app.keeping

KERI keri.app.keeping module

Terminology:

salt is 128 bit 16 char random bytes used as root entropy to derive seed or secret private key same as seed or secret for key pair seed or secret or private key is crypto suite length dependent random bytes public key

Example usage:

txn.put(
            did.encode(),
            json.dumps(certifiable_data).encode("utf-8")
        )
raw_data = txn.get(did.encode())
if raw_data is None:
    return None
return json.loads(raw_data)

ked = json.loads(raw[:size].decode("utf-8"))
raw = json.dumps(ked, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
class keri.app.keeping.Algoage(randy, salty, group, extern)
extern

Alias for field number 3

group

Alias for field number 2

randy

Alias for field number 0

salty

Alias for field number 1

class keri.app.keeping.Creator(**kwa)[source]

Class for creating a key pair based on algorithm.

Attributes:

Properties:

.create is method to create key pair

Hidden:

__init__(**kwa)[source]

Setup Creator.

Parameters:

create(**kwa)[source]

Returns tuple of signers one per key pair

property salt

salt property getter

property stem

stem property getter

property tier

tier property getter

class keri.app.keeping.Creatory(algo='salty')[source]

Factory class for creating Creator subclasses to create key pairs based on the provided algorithm.

Usage: creator = Creatory(algo=’salty’).make(salt=b’0123456789abcdef’)

Attributes:

Properties:

.create is method to create key pair
Hidden:

._create is method reference set to one of algorithm methods ._novelCreate ._indexCreate

__init__(algo='salty')[source]

Setup Creator.

Parameters:

algorithm (algo is str code for)

make(**kwa)[source]

Returns Creator subclass based on inited algo

class keri.app.keeping.Initage(aeid, pidx, salt, tier)
aeid

Alias for field number 0

pidx

Alias for field number 1

salt

Alias for field number 2

tier

Alias for field number 3

class keri.app.keeping.Keeper(headDirPath=None, perm=None, reopen=False, **kwa)[source]

Keeper sets up named sub databases for key pair storage (KS). Methods provide key pair creation, storage, and data signing.

Attributes: (inherited)

name (str): unique path component used in directory or file path name base (str): another unique path component inserted before name temp (bool): True means use /tmp directory headDirPath is head directory path path is full directory path perm is numeric os permissions for directory and/or file(s) filed (bool): True means .path ends in file. Otherwise .path ends in directory.

mode (str): file open mode if filed fext (str): file extension if filed file (File) opened is Boolean, True means directory created and if file then file is opened. False otherwise.

env (lmdb.env): LMDB main (super) database environment readonly (bool): True means open LMDB env as readonly

gbls

named sub DB whose values are global parameters for all prefixes Key is parameter labels Value is parameter:

parameters:
    aeid (bytes): fully qualified qb64 non-transferable identifier
        prefix for authentication via signing and asymmetric encryption
        of secrets using the associated (public, private) key pair.
        Secrets include both salts and private keys for all key sets
        in keeper. Defaults to empty which means no authentication
        or encryption of key sets.

    pidx (bytes): hex index of next prefix key-pair sequence to be incepted
    algo (str): default root algorithm for generating key pair
    salt (bytes): root salt for generating key pairs
    tier (bytes): default root security tier for root salt
Type:

Suber

pris

named sub DB whose keys are public key from key pair and values are private keys from key pair Key is public key (fully qualified qb64) Value is private key (fully qualified qb64)

Type:

CryptSignerSuber

pres

named sub DB whose values are prefixes or first public keys Key is first public key in key sequence for a prefix (fully qualified qb64) Value is prefix or first public key (temporary) (fully qualified qb64

Type:

CesrSuber

prms

named sub DB whose values are serialized dicts of PrePrm instance Key is identifier prefix (fully qualified qb64) Value is serialized parameter dict of public key parameters:

{
    pidx: ,
    algo: ,
    salt: ,
    stem: ,
    tier: ,
}
Type:

Komer

sits

named sub DB whose values are serialized dicts of PreSit instance Key is identifier prefix (fully qualified qb64) Value is serialized parameter dict of public key situation:

{
  old: { pubs: ridx, kidx,  dt },
  new: { pubs: ridx, kidx, dt },
  nxt: { pubs: ridx, kidx, dt }
}
Type:

Komer

.pubs

named sub DB whose values are serialized lists of public keys Enables lookup of public keys from prefix and ridx for replay of public keys by prefix in establishment event order. Key is prefix.ridx (rotation index as 32 char hex string) use riKey(pre, ri)

Value is serialized list of fully qualified public keys that are the current signing keys after the rotation given by rotation index

Type:

Komer

Properties:

__init__(headDirPath=None, perm=None, reopen=False, **kwa)[source]

Setup named sub databases.

Inherited Parameters:

name is str directory path name differentiator for main database. When system employs more than one keri database, name allows differentiating each instance by name. Default name=’main’. temp is boolean, assign to .temp. True then open in temporary directory, clear on close. Otherwise then open persistent directory, do not clear on close. Default temp=False. headDirPath is optional str head directory pathname for main database. If not provided use default .HeadDirpath. Default headDirPath=None. perm is numeric optional os dir permissions mode. Default perm=None. reopen is boolean, IF True then database will be reopened by this init. Default reopen=True.

Notes:

dupsort=True for sub DB means allow unique (key,pair) duplicates at a key. Duplicate means that is more than one value at a key but not a redundant copies a (key,value) pair per key. In other words the pair (key,value) must be unique both key and value in combination. Attempting to put the same (key,value) pair a second time does not add another copy.

Duplicates are inserted in lexocographic order by value, insertion order.

reopen(**kwa)[source]

Open sub databases

class keri.app.keeping.KeeperDoer(keeper, **kwa)[source]

Basic Keeper Doer ( LMDB Database )

Inherited Attributes:
.done is Boolean completion state:

True means completed Otherwise incomplete. Incompletion maybe due to close or abort.

.keeper is Keeper or LMDBer subclass
Inherited Properties:
.tyme is float relative cycle time of associated Tymist .tyme obtained

via injected .tymth function wrapper closure.

.tymth is function wrapper closure returned by Tymist .tymeth() method.

When .tymth is called it returns associated Tymist .tyme. .tymth provides injected dependency on Tymist tyme base.

.tock is float, desired time in seconds between runs or until next run,

non negative, zero means run asap

Properties:

.wind  injects ._tymth dependency from associated Tymist to get its .tyme
.__call__ makes instance callable

Appears as generator function that returns generator

.do is generator method that returns generator
.enter is enter context action method
.recur is recur context action method or generator method
.exit is exit context method
.close is close context method
.abort is abort context method
Hidden:
._tymth is injected function wrapper closure returned by .tymen() of

associated Tymist instance that returns Tymist .tyme. when called.

._tock is hidden attribute for .tock property

__init__(keeper, **kwa)[source]
Parameters:

instance (keeper is Keeper)

class keri.app.keeping.Manager(*, ks=None, seed=None, **kwa)[source]

Manages key pairs creation, storage, and signing Class for managing key pair creation, storage, retrieval, and message signing.

ks

key store LMDB database instance for storing public and private keys

Type:

Keeper

encrypter

instance for encrypting secrets. Public encryption key is derived from aeid (public signing key)

Type:

Encrypter

decrypter

instance for decrypting secrets. Private decryption key is derived seed (private signing key seed)

Type:

Decrypter

inited

True means fully initialized wrt database. False means not yet fully initialized

Type:

bool

Attributes (Hidden):

_seed (str): qb64 private-signing key (seed) for the aeid from which

the private decryption key is derived. If aeid stored in database is not empty then seed may required to do any key management operations. The seed value is memory only and MUST NOT be persisted to the database for the manager with which it is used. It MUST only be loaded once when the process that runs the Manager is initialized. Its presence acts as an authentication, authorization, and decryption secret for the Manager and must be stored on another device from the device that runs the Manager.

Properties:
aeid (str): authentication and encryption fully qualified qb64

non-transferable identifier prefix for authentication via signing and asymmetric encryption of secrets using the associated (public, private) key pair. Secrets include both salts and private keys for all key sets in keeper. Defaults to empty which means no authentication or encryption of key sets. Use initial attribute because keeper may not be open on init.

pidx (int): pidx prefix index.

Use initial attribute because keeper may not be open on init. Each sequence gets own pidx. Enables unique recreatable salting of key sequence based on pidx.

salt (str): qb64 of root salt. Makes random root salt if not provided

initial salt. Use inital attribute because keeper may not be open on init.

tier (str): initial security tier as value of Tierage. Use initial attribute

because keeper may not be open on init

Methods:

__init__(*, ks=None, seed=None, **kwa)[source]

Setup Manager.

Parameters:
  • ks (Keeper) – key store instance (LMDB)

  • seed (str) – qb64 private-signing key (seed) for the aeid from which the private decryption key may be derived. If aeid stored in database is not empty then seed may required to do any key management operations. The seed value is memory only and MUST NOT be persisted to the database for the manager with which it is used. It MUST only be loaded once when the process that runs the Manager is initialized. Its presence acts as an authentication, authorization, and decryption secret for the Manager and must be stored on another device from the device that runs the Manager. Currently only code MtrDex.Ed25519_Seed is supported.

Parameters: Passthrough to .setup for later initialization
aeid (str): qb64 of non-transferable identifier prefix for

authentication and encryption of secrets in keeper. If provided aeid (not None) and different from aeid stored in database then all secrets are re-encrypted using new aeid. In this case the provided seed must not be empty. A change in aeid should require a second authentication mechanism besides the seed.

pidx (int): index of next new created key pair sequence bound to a

given identifier prefix. Each sequence gets own pidx. Enables unique recreatable salting of key sequence based on pidx.

salt (str): qb64 of root salt. Makes random root salt if not provided tier (str): default security tier (Tierage) for root salt

property aeid

aeid property getter from key store db. Assumes db initialized. aeid is qb64 auth encrypt id prefix

property algo

also property getter from key store db. Assumes db initialized. algo is default root algorithm for creating key pairs

decrypt(qb64, pubs=None, verfers=None)[source]

Returns decrypted plaintext of encrypted qb64 ciphertext serialization.

Parameters:
  • qb64 (str | bytes | bytearray | memoryview) – fully qualified base64 ciphertext serialization to decrypt

  • pubs (list[str] | None) – of qb64 public keys to lookup private keys one of pubs or verfers is required. If both then verfers is ignored.

  • verfers (list[Verfer] | None) – Verfer instances of public keys one of pubs or verfers is required. If both then verfers is ignored. If not pubs then gets public key from verfer.qb64 used to lookup private keys

Returns:

decrypted plaintext

Return type:

plain (bytes)

incept(icodes=None, icount=1, icode='A', ncodes=None, ncount=1, ncode='A', dcode='E', algo=None, salt=None, stem=None, tier=None, rooted=True, transferable=True, temp=False)[source]
Returns tuple (verfers, digers) for inception event where
verfers is list of current public key verfers

public key is verfer.qb64

digers is list of next public key digers

digest to xor is diger.raw

Incept a prefix. Use first public key as temporary prefix. Must .repre later to move pubsit dict to correct permanent prefix. Store the dictified PreSit in the keeper under the first public key

Parameters:
  • str (ncodes is list of private key derivation codes qb64) – one per incepting key pair

  • provided (ncount is int count of next public keys when ncodes not)

  • keys (ncode is str derivation code qb64 of all ncount next public) – when icodes list not provided

  • str – one per next key pair

  • provided

  • keys – when ncodes not provided

  • MtrDex.Blake3_256 (dcode is str derivation code qb64 of next digers. Default is)

  • code (algo is str key creation algorithm)

  • used (salt is str qb64 salt for randomization when salty algorithm)

  • using (stem is path modifier used with salt to derive private keys when) – salty agorithms. if stem is None then uses pidx

  • algorithm (temp is Boolean. True is temporary for testing. It modifies tier of salty)

  • when (rooted is Boolean true means derive incept salt from root salt) – incept salt not provided. Otherwise use incept salt only

  • Boolean (transferable is) – derivation code. Default is transferable. Special case is non-transferable Use case for incept to use transferable = False is for basic derivation of non-transferable identifier prefix. When the derivation process of the identifier prefix is transferable then one should not use non-transferable for the associated public key(s).

  • transferable (True means each public key uses) – derivation code. Default is transferable. Special case is non-transferable Use case for incept to use transferable = False is for basic derivation of non-transferable identifier prefix. When the derivation process of the identifier prefix is transferable then one should not use non-transferable for the associated public key(s).

  • algorithm

When both ncodes is empty and ncount is 0 then the nxt is null and will

not be rotatable. This makes the identifier non-transferable in effect even when the identifier prefix is transferable.

ingest(secrecies, iridx=0, ncount=1, ncode='A', dcode='E', algo='salty', salt=None, stem=None, tier=None, rooted=True, transferable=True, temp=False)[source]

Ingest secrecies as a list of lists of secrets organized in event order to register the sets of secrets of associated externally generated keypair lists into the database.

Returns:

(ipre, veferies) where:
ipre is prefix index of ingested key pairs needed to fetch later

for replay

veferies is list of lists of all the verfers for the public keys from the private keys in secrecies in order of appearance.

Return type:

ret (tuple)

Essentially ingest ends with the current keys as the last key list in secrecies and the nxt keys are newly created as if a rotation to the last set of keys was performed. Unlike rotate, however, ingest does not delete any of the private keys it ingests. This must be done separately if desired.

Each list in secrecies is an ordered list of private keys corresponding to the public list in the key state for each establishment event in order. The first list are the keys for the inception event, the next list for the first rotation, and each subsequent list for the next rotation and so on.

May be used for import or recovery from backup. Method parameters specify the policy for generating new keys pairs for rotations that follow the ingested list of lists. The parameters are used to define how to rotate to new key pairs that follow the ingested sequence.

Parameters:
  • secrecies (algo is str key creation algorithm code for next after end of) – list of lists of fully qualified secrets (private keys)

  • iridx (int) – initial ridx at where set PubSit after ingestion enables database to store where initial replay should start from

  • ncount (int) – count of next public keys for next after end of secrecies

  • ncode (str) – derivation code qb64 of all ncount next public keys after end of secrecies

  • secrecies – Default is MtrDex.Blake3_256

  • secrecies

  • used (salt is str qb64 salt for randomization when salty algorithm) – for next after end of secrecies

  • using (stem is path modifier used with salt to derive private keys when) – salty agorithms. if stem is None then uses pidx

  • algorithm (tier is str security criticality tier code when using salty)

  • when (rooted is Boolean true means derive incept salt from root salt) – incept salt not provided. Otherwise use incept salt only

  • Boolean (transferable is) – derivation code. Default is transferable. Special case is non-transferable Use case for incept to use transferable = False is for basic derivation of non-transferable identifier prefix. When the derivation process of the identifier prefix is transferable then one should not use non-transferable for the associated public key(s).

  • transferable (True means each public key uses) – derivation code. Default is transferable. Special case is non-transferable Use case for incept to use transferable = False is for basic derivation of non-transferable identifier prefix. When the derivation process of the identifier prefix is transferable then one should not use non-transferable for the associated public key(s).

  • strech (temp is Boolean. True is temporary for testing. It modifies) – time of salty algorithm

move(old, new)[source]

Assigns new pre to old default .pres at old

Moves PrePrm and PreSit dicts in keeper db from old default pre to new pre db key The new pre is the newly derived prefix which may only be known some time after the original creation of the associated key pairs.

Paraameters:

old is str for old prefix of pubsit dict in keeper db new is str for new prefix to move pubsit dict to in keeper db

property pidx

pidx property getter from key store db. Assumes db initialized. pidx is prefix index int for next new key sequence

replay(pre, dcode='E', advance=True, erase=True)[source]

Returns duple (verfers, digers) associated with public key set from the key sequence for identifier prefix pre at rotation index ridx stored in db .pubs. Inception is at ridx == 0. Enables replay of preexisting public key sequence.

In returned duple:

verfers is list of current public key verfers. Public key is verfer.qb64. digers is list of next public key digers. Digest to xor is diger.raw.

If key sequence at ridx does already exist in .pubs database for pre then

raises ValueError.

If preexisting pubs for pre exist but .ridx is two large for preexisting

pubs then raises IndexError.

Parameters:
  • pre (str) – fully qualified qb64 identifier prefix

  • dcode (str) – derivation code for digers for next xor digest. Default is MtrDex.Blake3_256

  • advance (bool) – True means advance to next set of keys for replay

  • erase (bool) – True means erase old private keys made stale by advancement when advance is True otherwise ignore

rotate(pre, ncodes=None, ncount=1, ncode='A', dcode='E', transferable=True, temp=False, erase=True)[source]
Returns tuple (verfers, digers) for rotation event of keys for pre where
verfers is list of current public key verfers

public key is verfer.qb64

digers is list of next public key digers

digest to xor is diger.raw

Rotate a prefix. Store the updated dictified PreSit in the keeper under pre

Parameters:
  • pre (str)

  • ncodes (list) – of private key derivation codes qb64 str one per next key pair

  • ncount (int) – count of next public keys when icodes not provided

  • ncode (str) – derivation code qb64 of all ncount next public keys when ncodes not provided

  • i (dcode) – derivation code qb64 of next key digest of digers Default is MtrDex.Blake3_256

  • transferable (bool) – True means each public key uses transferable derivation code. Default is transferable. Special case is non-transferable Normally no use case for rotation to use transferable = False. When the derivation process of the identifier prefix is transferable then one should not use transferable = False for the associated public key(s).

  • temp (bool) – True is temporary for testing. It modifies tier of salty algorithm

  • erase (bool) – True means erase old private keys made stale by rotation

When both ncodes is empty and ncount is 0 then the nxt is null and will

not be rotatable. This makes the identifier non-transferable in effect even when the identifier prefix is transferable.

property salt

salt property getter from key store db. Assumes db initialized. salt is default root salt for new key sequence creation

property seed

seed property getter from ._seed. seed (str): qb64 from which aeid is derived

setup(aeid=None, pidx=None, algo=None, salt=None, tier=None)[source]

Setups manager root or global attributes and properties Assumes that .keeper db is open. If .keeper.gbls sub database has not been initialized for the first time then initializes from ._inits. This allows dependency injection of keepr db into manager instance prior to keeper db being opened to accomodate asynchronous process setup of db resources. Putting the db initialization here enables asynchronous opening of keeper db after keeper instance is instantiated. First call to .setup will initialize keeper db defaults if never before initialized (vacuous initialization).

Parameters:
  • aeid (str) – qb64 of non-transferable identifier prefix for authentication and encryption of secrets in keeper. If provided aeid (not None) and different from aeid stored in database then all secrets are re-encrypted using new aeid. In this case the provided seed must not be empty. A change in aeid should require a second authentication mechanism besides the secret. aeid same as current aeid no change innocuous aeid different but empty which unencrypts and removes aeid aeid different not empty which reencrypts and updates aeid

  • pidx (int) – index of next new created key pair sequence for given identifier prefix

  • algo (str) – root algorithm (randy or salty) for creating key pairs

  • salt (str) – qb64 of root salt. Makes random root salt if not provided

  • tier (str) – default security tier (Tierage) for root salt

sign(ser, pubs=None, verfers=None, indexed=True, indices=None, ondices=None, pre=None, path=None)[source]

Returns list of signatures of ser if indexed as Sigers else as Cigars with .verfer assigned.

Parameters:
  • ser (bytes) – serialization to sign

  • pubs (list[str] | None) – of qb64 public keys to lookup private keys one of pubs or verfers is required. If both then verfers is ignored.

  • verfers (list[Verfer] | None) – Verfer instances of public keys one of pubs or verfers is required. If both then verfers is ignored. If not pubs then gets public key from verfer.qb64

  • indexed (bool) –

    True means use use indexed signatures and return list of Siger instances. False means do not use indexed signatures and return list of Cigar instances

    When indexed True, each index is an offset that maps the offset in the coherent lists: pubs, verfers, signers (pris from keystore .ks) onto the appropriate offset into the signing keys or prior next keys lists of a key event as determined by the indices and ondices lists, or appropriate defaults when indices and/or ondices are not provided.

  • indices (list[int] | None) – indices (offsets) when indexed == True, to use for indexed signatures whose offset into the current keys or prior next list may differ from the order of appearance in the provided coherent pubs, verfers, signers lists. This allows witness indexed sigs or controller multi-sig where the parties do not share the same manager or ordering so the default ordering in pubs or verfers is wrong for the index. This sets the value of the index property of the returned Siger. When provided the length of indices must match the len of the coherent lists: pubs, verfers, signers (pris from keystore .ks) else raises ValueError. When not provided and indexed is True then use default index that is the offset into the coherent lists: pubs, verfers, signers (pris from keystore .ks)

  • ondices (list[int | None] | None) – other indices (offsets) when indexed is True for indexed signatures whose offset into the prior next list may differ from the order of appearance in the provided coherent pubs, verfers, signers lists. This allows partial rotation with reserve or custodial key management so that the index (hash of index) of the public key for the signature appears at a different index in the current key list from the prior next list. This sets the value of the ondex property of the returned Siger. When provided the length of indices must match the len of the coherent lists: pubs, verfers, signers (pris from keystore .ks) else raises ValueError. When no ondex is applicable to a given signature then the value of the entry in ondices MUST be None. When ondices is not provided then all sigers .ondex is None.

  • pre (str | None) – identity prefix (aid) of signer. Used for HDK salty algo key lookup or re-creation. Look up key path state and algo from local keystore .ks

  • path (tuple | None) – HDX randy algo signing key path tuple part of form (ridx, kidx) where ridx is the optional rotation index and kidx is the required zeroth key index of the key list. The fully HDK path is formed by looking up the stem and pidx using the pre and when provided the ridx and then computing the pidxes for each signing key. When indices is provided then the kidxes are computed by adding the index offset to the zeroth kidx. When indices is not provided then the kidxes are assumed to be all the keys in the key list computed from the local keystore by subtracting the kidx of the zeroth element of the following key list. When path is not provided then the default is all the kidxs of the key list from the current .new key info.

if neither pubs or verfers provided then returns empty list of signatures If pubs then ignores verfers otherwise uses verferss

Manager implement .sign method and tests sign(self,ser,pubs,indexed=True) checks for pris for pubs in db is not raises error then signs ser with eah pub returns list of sigers indexed else list of cigars if not

property tier

tier property getter from key store db. Assumes db initialized. tier is default root security tier for new key sequence creation

updateAeid(aeid, seed)[source]

Given seed belongs to aeid and encrypter, update aeid and re-encrypt all secrets

Parameters:
  • aeid (Optional(str)) – qb64 of new auth encrypt id (public signing key) aeid may match current aeid no change innocuous aeid may be empty which unencrypts and removes aeid aeid may be different not empty which reencrypts

  • seed (str) – qb64 of new seed from which new aeid is derived (private signing key seed)

class keri.app.keeping.ManagerDoer(manager, **kwa)[source]

Basic Manager Doer to initialize keystore database .ks

Inherited Attributes:
.done is Boolean completion state:

True means completed Otherwise incomplete. Incompletion maybe due to close or abort.

.manager is Manager subclass
Inherited Properties:
.tyme is float relative cycle time of associated Tymist .tyme obtained

via injected .tymth function wrapper closure.

.tymth is function wrapper closure returned by Tymist .tymeth() method.

When .tymth is called it returns associated Tymist .tyme. .tymth provides injected dependency on Tymist tyme base.

.tock is float, desired time in seconds between runs or until next run,

non negative, zero means run asap

Properties:

.wind  injects ._tymth dependency from associated Tymist to get its .tyme
.__call__ makes instance callable

Appears as generator function that returns generator

.do is generator method that returns generator
.enter is enter context action method
.recur is recur context action method or generator method
.exit is exit context method
.close is close context method
.abort is abort context method
Hidden:
._tymth is injected function wrapper closure returned by .tymen() of

associated Tymist instance that returns Tymist .tyme. when called.

._tock is hidden attribute for .tock property

__init__(manager, **kwa)[source]
Parameters:

manager (Manager) – instance

class keri.app.keeping.PrePrm(pidx: int = 0, algo: str = 'salty', salt: str = '', stem: str = '', tier: str = '')[source]

Prefix’s parameters for creating new key pairs

class keri.app.keeping.PreSit(old: ~keri.app.keeping.PubLot = <factory>, new: ~keri.app.keeping.PubLot = <factory>, nxt: ~keri.app.keeping.PubLot = <factory>)[source]

Prefix’s public key situation (sets of public kets)

class keri.app.keeping.PubLot(pubs: list = <factory>, ridx: int = 0, kidx: int = 0, dt: str = '')[source]

Public key list with indexes and datetime created .. attribute:: pubs

list of fully qualified Base64 public keys. Defaults to empty.

type:

list

ridx

rotation index of set of public keys at establishment event. Includes of key set at inception event is 0.

Type:

int

kidx

key index of starting key in key set in sequence wrt to all public keys. Example if each set has 3 keys then ridx 2 has kidx of 2*3 = 6.

Type:

int

dt

datetime in ISO8601 format of when key set was first created

Type:

str

class keri.app.keeping.PubSet(pubs: list = <factory>)[source]

Prefix’s public key set (list) at rotation index ridx

class keri.app.keeping.RandyCreator(**kwa)[source]

Class for creating a key pair based on re-randomizing each seed algorithm.

Attributes:

Properties:

.create is method to create key pair

Hidden:

__init__(**kwa)[source]

Setup Creator.

Parameters:

create(codes=None, count=1, code='A', transferable=True, **kwa)[source]

Returns list of signers one per kidx in kidxs

Parameters:
  • create (codes is list of derivation codes one per key pair to)

  • provided (code is derivation code to use for count key pairs if codes not)

  • provided

  • Boolean (transferable is)

  • nontrans (True means use trans deriv code. Otherwise)

class keri.app.keeping.SaltyCreator(salt=None, stem=None, tier=None, **kwa)[source]

Class for creating a key pair based on random salt plus path stretch algorithm.

.salter is salter instance

Properties:

.create is method to create key pair
Hidden:

._salter holds instance for .salter property

__init__(salt=None, stem=None, tier=None, **kwa)[source]

Setup Creator.

Parameters:
  • key (salt is unique salt from which to derive private)

  • keys. (stem is path modifier used with salt to derive private) – if stem is None then uses pidx

  • use. (tier is derivation criticality that determines how much hashing to)

create(codes=None, count=1, code='A', pidx=0, ridx=0, kidx=0, transferable=True, temp=False, **kwa)[source]

Returns list of signers one per kidx in kidxs

Parameters:
  • create (codes is list of derivation codes one per key pair to)

  • provided (code is derivation code to use for count key pairs if codes not)

  • provided

  • sequence (pidx is int prefix index for key pair)

  • set (temp is Boolean True means use temp stretch otherwise use time)

  • set

  • Boolean (transferable is)

  • nontrans (True means use trans deriv code. Otherwise)

  • set – by tier for streching

property salt

salt property getter

property stem

stem property getter

property tier

tier property getter

keri.app.keeping.openKS(name='test', **kwa)[source]

Returns contextmanager generated by openLMDB but with Keeper instance as KeyStore default name=”test” default temp=True,

openLMDB Parameters:

cls is Class instance of subclass instance name is str name of LMDBer dirPath so can have multiple databasers at different directory path names thar each use different name

temp is Boolean, True means open in temporary directory, clear on close Otherwise open in persistent directory, do not clear on close

keri.app.keeping.riKey(pre, ri)[source]

Returns bytes DB key from concatenation with ‘.’ of qualified Base64 prefix bytes pre and int ri (rotation index) of key rotation. Inception has ri == 0

keri.app.notifying

keri.app.notifying module

class keri.app.notifying.DicterSuber(*pa, klas: ~typing.Type[~keri.core.coring.Dicter] = <class 'keri.core.coring.Dicter'>, **kwa)[source]

Data serialization for Dicter and subclasses

Sub class of Suber where data is serialized Dicter instance or subclass Automatically serializes and deserializes using Dicter methods

__init__(*pa, klas: ~typing.Type[~keri.core.coring.Dicter] = <class 'keri.core.coring.Dicter'>, **kwa)[source]
Parameters:
  • db (LMDBer) – base db

  • subkey (str) – LMDB sub database key

cntAll()[source]

Return count over the all the items in subdb

Returns:

count of all items

get(keys: str | Iterable)[source]

Gets Sadder at keys

Parameters:

keys (tuple) – of key strs to be combined in order to form key

Returns:

instance at keys None: if no entry at keys

Return type:

Sadder

Usage:

Use walrus operator to catch and raise missing entry. Example:

if (creder := mydb.get(keys)) is None:
    raise ExceptionHere
use creder here
getTopItemIter(keys: str | Iterable = b'')[source]

Return iterator over the all the items in subdb

Parameters:

keys (tuple) – of key strs to be combined in order to form key

Returns:

of tuples of keys tuple and val serdering.SerderKERI for each entry in db

Return type:

iterator

pin(keys: str | Iterable, val: Dicter)[source]

Pins (sets) val at key made from keys. Overwrites.

Parameters:
  • keys (tuple) – of key strs to be combined in order to form key

  • val (Sadder) – instance

Returns:

True If successful. False otherwise.

Return type:

bool

put(keys: str | Iterable, val: Dicter)[source]

Puts val at key made from keys. Does not overwrite

Parameters:
  • keys (tuple) – of key strs to be combined in order to form key

  • val (Dicter) – instance

Returns:

True If successful, False otherwise, such as key

already in database.

Return type:

bool

rem(keys: str | Iterable)[source]

Removes entry at keys

Parameters:

keys (tuple) – of key strs to be combined in order to form key

Returns:

True if key exists so delete successful. False otherwise

Return type:

bool

class keri.app.notifying.Noter(name='not', headDirPath=None, reopen=True, **kwa)[source]

Noter stores Notifications generated by the agent that are intended to be read and dismissed by the controller of the agent.

__init__(name='not', headDirPath=None, reopen=True, **kwa)[source]
Parameters:
  • headDirPath

  • perm

  • reopen

  • kwa

add(note, cigar)[source]

Adds note to database, keyed by the datetime and said of the note.

Parameters:
  • note (Notice) – sad message content

  • cigar (Cigar) – non-transferable signature over note

get(rid)[source]

Adds note to database, keyed by the datetime and said of the note.

Parameters:

rid (str) – qb64 random ID of note to get

Returns:

(Notice, Cigar) = couple of notice object and accompanying signature

getNoteCnt()[source]

Return count over the all Notes

Returns:

count of all items

Return type:

int

getNotes(start=0, end=25)[source]

Returns list of tuples (note, cigar) of notes for controller of agent

Parameters:
  • start (int) – number of item to start

  • end (int) – number of last item to return

rem(rid)[source]

Remove note from database if it exists

Parameters:

rid (str) – qb64 random ID of note to remove

Returns:

True if deleted

Return type:

bool

reopen(**kwa)[source]
Parameters:

kwa

Returns:

update(note, cigar)[source]

Adds note to database, keyed by the datetime and said of the note.

Parameters:
  • note (Notice) – sad message content

  • cigar (Cigar) – non-transferable signature over note

class keri.app.notifying.Notice(raw=b'', pad=None, note=None)[source]

Notice is for creating notification messages for the controller of the agent

Sub class of Sadder that adds notification specific validation and properties

Inherited Properties:

.raw is bytes of serialized event only .pad is key event dict

Properties:

.datetime (str): ISO8601 formatted datetime of notice .pad (dict): payload of the notice

__init__(raw=b'', pad=None, note=None)[source]

Creates a serializer/deserializer for a ACDC Verifiable Credential in CESR Proof Format

Requires either raw or (crd and kind) to load credential from serialized form or in memory

Parameters:
  • raw (bytes) – is raw credential

  • pad (dict) – is populated data

property attrs

pad property getter

property datetime

issuer property getter

property read

read property getter

class keri.app.notifying.Notifier(hby, signaler=None, noter=None)[source]

Class for sending notifications to the controller of an agent.

The notifications are not just signals to reload data and not persistent messages that can be reread

__init__(hby, signaler=None, noter=None)[source]
Parameters:
  • hby (Habery) – habery database environment with Signator

  • noter (Noter) – database

  • signaler (Signaler) – signaler for sending signals to controller that new data is available

add(attrs)[source]

Add unread notice to the end of the current list of notices

Parameters:

attrs (dict) – body of a new unread notice to append to the current list of notices

Returns:

returns True if the notice was added

Return type:

bool

getNoteCnt()[source]

Return count over the all Notes

Returns:

count of all items

Return type:

int

getNotes(start=0, end=24)[source]

Returns list of tuples (note, cigar) of notes for controller of agent

Parameters:
  • start (int) – number of item to start

  • end (int) – number of last item to return

mar(rid)[source]

Mark as Read

Mark the note identified by the provided SAID as having been read by the controller of the agent

Parameters:

rid (str) – qb64 random ID of the Note to mark as read

Returns:

True means the note was marked as read, False otherwise

Return type:

bool

rem(rid)[source]

Mark as Read

Delete the note identified by the provided random ID

Parameters:

rid (str) – qb64 random ID of the Note to delete

Returns:

True means the note was deleted, False otherwise

Return type:

bool

keri.app.notifying.notice(attrs, dt=None, read=False)[source]
Parameters:
  • attrs (dict) – payload of the notice

  • dt (Optional(str, datetime)) – iso8601 formatted datetime of notice

  • read (bool) – message read indicator

Returns:

Notice instance

Return type:

Notice

keri.app.oobiing

keri.kli.common.oobiing module

class keri.app.oobiing.OobiRequestHandler(hby, notifier)[source]

Handler for oobi notification EXN messages

__init__(hby, notifier)[source]
Parameters:
handle(serder, attachments=None)[source]

Do route specific processsing of OOBI request messages

Parameters:
  • serder (Serder) – Serder of the exn OOBI request message

  • attachments (list) – list of tuples of pather, CESR SAD path attachments to the exn event

class keri.app.oobiing.OobiResource(hby)[source]

Resource for managing OOBIs

__init__(hby)[source]

Create Endpoints for discovery and resolution of OOBIs

Parameters:

hby (Habery) – identifier database environment

on_get_alias(req, rep, alias=None)[source]

OOBI GET endpoint

Parameters:
  • req – falcon.Request HTTP request

  • rep – falcon.Response HTTP response

  • alias – option route parameter for specific identifier to get

---
summary:  Get OOBI for specific identifier
description:  Generate OOBI for the identifier of the specified alias and role
tags:
   - OOBIs
parameters:
  - in: path
    name: alias
    schema:
      type: string
    required: true
    description: human readable alias for the identifier generate OOBI for
  - in: query
    name: role
    schema:
      type: string
    required: true
    description: role for which to generate OOBI
responses:
    200:
      description: An array of Identifier key state information
      content:
          application/json:
            schema:
                description: Key state information for current identifiers
                type: object
on_post(req, rep)[source]

Resolve OOBI endpoint.

Parameters:
  • req – falcon.Request HTTP request

  • rep – falcon.Response HTTP response

---
summary: Resolve OOBI and assign an alias for the remote identifier
description: Resolve OOBI URL or rpy message by process results of request
    and assign alias in contact data for resolved identifier
tags:
   - OOBIs
requestBody:
    required: true
    content:
      application/json:
        schema:
            description: OOBI
            properties:
                oobialias:
                  type: string
                  description: alias to assign to the identifier resolved from this OOBI
                  required: false
                url:
                  type: string
                  description:  URL OOBI
                rpy:
                  type: object
                  description: unsigned KERI rpy event message with endpoints
responses:
   202:
      description: OOBI resolution to key state successful
class keri.app.oobiing.Oobiery(hby, rvy=None, clienter=None, cues=None)[source]

Resolver for OOBIs

__init__(hby, rvy=None, clienter=None, cues=None)[source]

DoDoer to handle the request and parsing of OOBIs

Parameters:
  • hby (Habery) – database environment

  • clienter (Clienter) – DoDoer client provider responsible for managing HTTP client requests

  • cues (decking.Deck) – outbound cues from processing oobis

processClients()[source]

Process Client responses by parsing the messages and removing the client/doer

processFlows()[source]

Process OOBI URLs by requesting from the endpoint and parsing the results

processMOOBIs()[source]

Process Client responses by parsing the messages and removing the client/doer

processOobis()[source]

Process OOBI records loaded for discovery

There should be only one OOBIERY that minds the OOBI table, this should read from the table like an escrow

processReply(*, serder, diger, route, cigars=None, tsgs=None, **kwargs)[source]

Process one reply message for route = /introduce with either attached nontrans receipt couples in cigars or attached trans indexed sig groups in tsgs. Assumes already validated diger, dater, and route from serder.ked

Parameters:
  • serder (SerderKERI) – instance of reply msg (SAD)

  • diger (Diger) – instance from said in serder (SAD)

  • route (str) – reply route

  • cigars (list) – of Cigar instances that contain nontrans signing couple signature in .raw and public key in .verfer

  • tsgs (list) – tuples (quadruples) of form (prefixer, seqner, diger, [sigers]) where: prefixer is pre of trans endorser seqner is sequence number of trans endorser’s est evt for keys for sigs diger is digest of trans endorser’s est evt for keys for sigs [sigers] is list of indexed sigs from trans endorser’s keys from est evt

OobiRecord:

date: str = date time of reply message of the introduction

Reply Message:

{
  "v" : "KERI10JSON00011c_",
  "t" : "rpy",
  "d": "EZ-i0d8JZAoTNZH3ULaU6JR2nmwyvYAfSVPzhzS6b5CM",
  "dt": "2020-08-22T17:50:12.988921+00:00",
  "r" : "/introduce",
  "a" :
  {
     "cid": "ENcOes8_t2C7tck4X4j61fSm0sWkLbZrEZffq7mSn8On",
     "oobi":  "http://localhost:5632/oobi/ENcOes8_t2C7tck4X4j61fSm0sWkLbZrEZffq7mSn8On/witness",
  }
}
processRetries()[source]

Process Client responses by parsing the messages and removing the client/doer

registerReplyRoutes(router)[source]

Register the routes for processing messages embedded in rpy event messages

The Oobiery handles rpy messages with the /introduce route by processing the contained oobi

Parameters:

router (Router) – reply message router

scoobiDo(tymth=None, tock=0.0, **kwa)[source]
Returns doifiable Doist compatibile generator method (doer dog) to process

.exc responses and pass them on to the HTTPRespondant

Parameters:
  • tymth (function) – injected function wrapper closure returned by .tymen() of Tymist instance. Calling tymth() returns associated Tymist .tyme.

  • tock (float) – injected initial tock value

Usage:

add result of doify on this method to doers list

class keri.app.oobiing.Resultage(resolved, failed)
failed

Alias for field number 1

resolved

Alias for field number 0

keri.app.oobiing.loadHandlers(hby, exc, notifier)[source]

Load handlers for the peer-to-peer delegation protocols

Parameters:
  • hby (Habery) – Database and keystore for environment

  • exc (Exchanger) – Peer-to-peer message router

  • notifier (Notifier) – Outbound notifications

keri.app.oobiing.oobiRequestExn(hab, dest, oobi, version=(1, 0), pvrsn=None, gvrsn=(1, 0), framed=True, nested=False, genusify=False)[source]

Create oobi request exn and attachments

Parameters::

dest oobi version (Versionage): KERI protocol default version if psvrsn is None pvrsn (Versionage): KERI protocol version gvrsn (Versionage): CESR Genus version for attachment group codes or

nesting group code (useful when serder.gvrsn < 2) gvrsn = max(svrsn, gvrsn) where svrsn = serder.gvrsn

if serder.gvrsn else serder.pvrsn

framed (bool): True means may assume each message plus its attachments

is isolated as frame when parsing so do not need attachment group when messagizing

False means may not assume eash message plus its attachments

is isolated as frame when parsing so do need attachment group when messagizing

nested (bool): True means messagize for non-top level

This forces non-native serializion to be embedded in non-native group code

False means messagize for top level of stream.

This allows bare non-native serialization of message

genusify (bool): True means prepend genus version code from gvrsn before

serder to override default stream genus version

False means do nothing

keri.app.signaling

keri.app.signaling module

class keri.app.signaling.Signal(pad, ckey=None)[source]
__init__(pad, ckey=None)[source]

New Signal

Signals with a collapse key will replace any existing signal not yet read with a matching value as collapse key

Parameters:
  • pad (dict) – Attribute values that make up the payload of the signal

  • ckey (str) – The collapse key to use for

class keri.app.signaling.Signaler(signals=None)[source]

Class for sending signals to the controller of an agent.

The signals are just pings to reload data and not persistent messages that can be reread

__init__(signals=None)[source]

Parameters:

expireDo(tymth=None, tock=0.0, **kwa)[source]

Returns doifiable Doist compatible generator method (doer dog)

Usage:

add result of doify on this method to doers list

Parameters:
  • of (tymth is injected function wrapper closure returned by .tymen()) – Tymist instance. Calling tymth() returns associated Tymist .tyme.

  • value (tock is injected initial tock)

push(attrs, topic, ckey=None, dt=None)[source]
Parameters:
  • attrs (dict) – signal attributes to push to the cue

  • topic (str) – routing for recipient of message

  • ckey (str) – collapse key

  • dt (Optional(str, datetime)) – iso8601 formatted datetime of notice

Returns:

class keri.app.signaling.SignalsEnd(signals=None)[source]

HTTP handler that accepts and KERI events POSTed as the body of a request with all attachments to the message as a CESR attachment HTTP header. KEL Messages are processed and added to the database of the provided Habitat.

This also handles req, exn and tel messages that respond with a KEL replay.

__init__(signals=None)[source]

Create the MBX HTTP server from the Habitat with an optional Falcon App to register the routes with.

Parameters

rxbs (bytearray): output queue of bytes for message processing mbx (Mailboxer): Mailbox storage qrycues (Deck): inbound qry response queues

on_get(req, rep)[source]

Handles GET requests as a stream of SSE events :param req: :type req: Request :param rep: :type rep: Response

---
summary:  Stream Server-Sent Events for KERI mailbox for identifier
description:  Stream Server-Sent Events for KERI mailbox for identifier
tags:
   - Mailbox
responses:
   200:
      content:
         text/event-stream:
            schema:
               type: object
      description: Mailbox query response for server sent events
   204:
      description: KEL or EXN event accepted.
on_post(req, rep)[source]

Handles POST for KERI mailbox service.

Parameters:
  • req (Request)

  • rep (Response)

---
summary:  Stream Server-Sent Events for KERI mailbox for identifier
description:  Stream Server-Sent Events for KERI mailbox for identifier
tags:
   - Mailbox

responses:
   200:
      content:
         text/event-stream:
            schema:
               type: object
      description: Signal query response for server sent events
   204:
      description: KEL or EXN event accepted.
keri.app.signaling.loadEnds(app, *, signals=None)[source]

Load endpoints for agent to controller messages

Parameters:
  • app (falcon.App) – falcon.App to register handlers with:

  • signals (Deck) – messages for the mailbox stream

Returns:

keri.app.signaling.signal(attrs, topic, ckey=None, dt=None)[source]
Parameters:
  • attrs (dict) – payload of the notice

  • topic (str) – routing for recipient of message

  • dt (Optional(str, datetime)) – iso8601 formatted datetime of notice

  • ckey (str) – collapse key

Returns:

Notice instance

Return type:

Notice

keri.app.signing

KERI keri.app.signing module

keri.app.signing.signPaths(hab, serder, paths)[source]

Sign the SAD or SAIDs with the keys from the Habitat.

Sign the SADs or SAIDs of the SADs as identified by the paths.

Parameters:
  • hab (Habitat) – environment used to sign the SAD

  • serder (Union[Serder,Creder]) – the self addressing data (SAD)

  • paths (list[list]) – list of lists of path parts

Returns:

qb64 signature attachment

Return type:

str

keri.app.signing.transSeal(hab)[source]

Returns seal components and signing indices as appropriate for current state of Habitat

Parameters:

hab (Habitat) – environment that contains the information for the idenfitier prefix

Returns:

seal components with signing indices

Return type:

tuple

ToDo: NRR

indices for both hab.smids and hab.rmids

keri.app.specing

class keri.app.specing.SpecResource(app, title, resources, version='1.0.0', openapiVersion='3.0.2')[source]

Resource for OpenAPI spec

on_get(_, rep)[source]

GET endpoint for OpenAPI spec

Parameters:
  • _ – falcon.Request HTTP request

  • rep – falcon.Response HTTP response

keri.app.storing

keri.app.storing module

class keri.app.storing.Mailboxer(name='mbx', headDirPath=None, reopen=True, **kwa)[source]

Mailboxer stores exn messages in order and provider iterator access at an index.

__init__(name='mbx', headDirPath=None, reopen=True, **kwa)[source]
Parameters:
  • headDirPath

  • perm

  • reopen

  • kwa

Mailboxer uses two dbs for mailbox messages these are .tpcs and .msgs. The message index is in .tpcs (topics). Each .tpcs index key consists of topic.on where topic is bytes identifier or prefix/topic for message and on is serialized ordinal number to orders the appearance of a topic message. Each .tpcs val is the digest of the message. The message itself is stored in .msgs where the key is the msg digest and the value is the serialized messag itself. Multiple messages can share the same topic but with a different ordinal.

appendToTopic(topic, val)[source]

Appends val to end of db entries with same topic but with on incremented by 1 relative to last preexisting entry at topic.

Returns:

order number int, on, of appended entry.

Computes on as next on after last entry.

Return type:

on (int)

Parameters:
  • topic (bytes) – topic identifier for message

  • val (bytes) – msg digest

cloneTopicIter(topic, fn=0)[source]
Returns:

iterator of messages at topic

beginning with ordinal fn.

Return type:

triple (Iterator[(on, topic, msg)])

topic (Option(bytes|str)): key prefix combined with serialized on

to form full actual key. When key is empty then retrieves whole database.

fn (int): starting index ordinal number used with onKey(pre,on)

to form key at at which to initiate retrieval

ToDo looks like misuse of IoSet this should not be IoSet but simply Ordinal Numbered db. since should not be using hidden ion has not hidden.

delTopic(key, on=0)[source]

Removes topic index from .tpcs without deleting message from .msgs

Returns:

True if full key consisting of key and serialized on

exists in database so removed. False otherwise (not removed).

Return type:

result (boo)

getTopicMsgs(topic, fn=0)[source]
Returns:

belonging to topic indices with same topic but all

on >= fn i.e. all topic.on beginning with fn

Return type:

msgs (Iterable[bytes])

Parameters:
topic (Option(bytes|str)): key prefix combined with serialized on

to form full actual key. When key is empty then retrieves whole database.

fn (int): starting index ordinal number used with onKey(pre,on)

to form key at at which to initiate retrieval

reopen(**kwa)[source]
Parameters:

kwa

Returns:

storeMsg(topic, msg)[source]

Add exn event to mailbox topic and on that is 1 greater than last msg at topic.

Returns:

True if msg successfully stored and indexed at topic

False otherwise

Return type:

result (bool)

Parameters:
  • topic (str | bytes) – topic (Option(bytes|str)): key prefix combined with serialized on to form full actual key.

  • msg (bytes) – serialized message

class keri.app.storing.Respondant(hby, reps=None, cues=None, mbx=None, aids=None, **kwa)[source]

Respondant processes buffer of response messages from inbound ‘exn’ messages and routes them to the appropriate mailbox. If destination has witnesses, send response to one of the (randomly selected) witnesses. Otherwise store the response in the recipients mailbox locally.

__init__(hby, reps=None, cues=None, mbx=None, aids=None, **kwa)[source]

Creates Respondant that uses local environment to find the destination KEL and stores peer to peer messages in mbx, the mailboxer

Parameters:
  • hab (Habitat) – local environment

  • mbx (Mailboxer) – storage for local messages

cueDo(tymth=None, tock=0.0, **kwa)[source]
Returns doifiable Doist compatibile generator method (doer dog) to process

Kevery and Tevery cues deque

Usage:

add result of doify on this method to doers list

responseDo(tymth=None, tock=0.0, **kwa)[source]

Doifiable Doist compatibile generator method to process response messages from exn handlers. If dest is not in local environment, ignore the response (for now). If dest has witnesses, pick one at random and send the response to that witness for storage in the recipients mailbox on that witness. Otherwise this is a peer to peer HTTP message and should be stored in a mailbox locally for the recipient.

Usage:

add result of doify on this method to doers list

keri.app.watching

KERI keri.app.watching module

class keri.app.watching.AdjudicationDoer(adjudicator)[source]

Doer class responsible for process adjudication requests in an Adjudicator’s msgs

__init__(adjudicator)[source]

Create instance of Doer for performing key state adjudications

recur(tyme)[source]

Perform one pass over all adjudication requests

Parameters:

tyme (float) – relative cycle time

Returns:

class keri.app.watching.Adjudicator(hby, hab, msgs=None, cues=None)[source]

The Adjudicator of Key State

This class performs key state adjudication by checking any key state reported by the watcher set for a given watched AID and compares the reported values against the local key state for the watched AID and the key state of all other responding watchers. It uses a per-adjudication threshold to determine what is acceptable duplicity for each adjudication.

Cues are sent out for each round of adjudication with the following kins:

keyStateConsistent - Key state of all queries watchers is consistent with local key state keyStateLagging - Key state from some watchers is behind local key state and other watchers keyStateUpdate - A threshold satisfying number of watchers report new key state for watched AID keyStateDuplicitous - Duplicity has been detected on some set of watchers (provided in the cue)

Consumers of the Adjudicator’s cues are safe to retrieve new key state from one of the Watchers listed in the cue of keyStateUpdated is received. All other kins require controller intervention and should be bubbled up.

__init__(hby, hab, msgs=None, cues=None)[source]

Create instance of Adjudicator for adjudicating key state

Parameters:
  • hby (Habery) – database and Habitat environment

  • hab (Hab) – identifier database environment

  • msgs (Deck) – incoming requests to adjudicate key state

  • cues (Deck) – outgoing responses to adjudication of key state

adjudicate(watched, toad=None)[source]

Perform key state adjudication against the watched AID and provided threshold

If toad is not provided, the full set of watchers must come to consensus before keyStateUpdate will be reported.

Parameters:
  • watched (str) – qb64 AID to adjudicate for key state duplicity

  • toad (int) – threshold of acceptable duplicity amongst available watchers

performAdjudications()[source]

Process loop of existing messages requesting key state adjudication

class keri.app.watching.DiffState(pre: str, wit: str, state: Stateage, sn: int, dig: str)[source]

Difference between a remote KeyStateRecord and local for the same AID.

Uses Stateage to represent whether the remote KSR is even, ahead, behind or duplicitous

class keri.app.watching.Stateage(even, ahead, behind, duplicitous)
ahead

Alias for field number 1

behind

Alias for field number 2

duplicitous

Alias for field number 3

even

Alias for field number 0

keri.app.watching.diffState(wit, preksn, witksn)[source]

Return a record of the differences between the states provided by wit and local state

Parameters:
  • wit (str) – qb64 AID of entity reporting key state

  • preksn (KeyStateRecord) – Local key state of AID

  • witksn (KeyStateRecord) – Key state of AID as provided by wit

Returns:

record indicating the differenced between the two provided KSN records

Return type:

state (WitnessState)