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.
- 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.
- 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.
- 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.
- 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:
- 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
- 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.- console
Serial console for input/output.
- Type:
serialing.Console
- __init__(db=None, console=None, **kwa)[source]
Initializes Consoler with optional database and console.
- 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 rightl/left: turn leftw/walk: walk 1 steps/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
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.Filerto 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) whenhuman=True; strict JSON with two-space indentation whenhuman=False..mgpk— MsgPack binary..cbor— CBOR binary.
- human
When
Trueand the file extension is.json, use HJSON for serialization. WhenFalse, 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) –
Truemeans.pathis a file path;Falsemeans.pathis a directory path. Defaults toTrue.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
Trueandfextis"json", use HJSON forput()andget(). Defaults toTrue.**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 whenhumanis truthy, strict JSON otherwise..mgpk— MsgPack..cbor— CBOR.
An empty file returns an empty dict without error.
- Parameters:
human (bool, optional) – Override
self.humanfor this call.Nonemeans useself.human. Defaults toNone.- 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
dataand overwrite the config file.Truncates the file before writing. The serialization format is determined by the file extension of
.path:.json— HJSON whenhumanis truthy, strict JSON otherwise..mgpk— MsgPack..cbor— CBOR.
- Parameters:
data (dict) – Data to serialize and write.
human (bool, optional) – Override
self.humanfor this call.Nonemeans useself.human. Defaults toNone.
- Returns:
Trueon 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
Configerinstance.Opens the
Configeronenter()if it is not already open, and closes it onexit(), clearing the underlying file if theConfigerwas opened in temporary mode.- done
Completion flag.
Truewhen the doer has finished normally;Falsewhen it exited early due to close or abort.- Type:
bool
- Properties:
- tyme (float): Relative cycle time obtained from the injected
tymthclosure.- tymth (callable): Closure returned by
Tymist.tymeth(). Calling it returns the associated
Tymist.tymevalue.- 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
Configerinstance.- Parameters:
configer (Configer) – The
Configerinstance to manage.**kwa – Additional keyword arguments forwarded to
doing.Doer.
- keri.app.configing.openCF(cls=None, filed=True, **kwa)[source]
Return a context manager that opens a Configer instance.
Thin wrapper around
filing.openFiler()withConfigeras the default class andfiled=Trueas the default.- Parameters:
cls (type, optional) – Filer subclass to instantiate. Defaults to
ConfigerwhenNone.filed (bool) –
Truemeans.pathis a file path rather than a directory path. Defaults toTrue.**kwa – Additional keyword arguments forwarded to
filing.openFiler().
- Returns:
- Context manager that yields an open
Configerinstance.
- 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.
- complete(prefixer, number, diger=None)[source]
Check for completed delegation for the specific delegation event
- 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:
Sending local event with sig to other participants
Waiting for signature threshold to be met.
If elected and delegated identifier, send complete event to delegator
If delegated, wait for delegator’s anchored seal
If elected, send event to witnesses and collect receipts.
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
- 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.
- class keri.app.delegating.DelegateRequestHandler(hby, notifier)[source]
Handler for multisig group inception notification EXN messages
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:
- 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.
- 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
- 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:
- exchanger
Optional Exchanger instance for exn message processing. None if not required.
- remoter
TCP remoter used for both receive and transmit.
- Type:
TCP Remoter
- 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
- 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:
- 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
- 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
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
- 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
- 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
- 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.
- complete(prefixer, number, diger=None)[source]
Check for completed multsig protocol for the specific event
- Parameters:
Returns:
- escrowDo(tymth, tock=1.0, **kwa)[source]
Process escrows of group multisig identifiers waiting to be completed.
- Steps involve:
Sending local event with sig to other participants
Waiting for signature threshold to be met.
If elected and delegated identifier, send complete event to delegator
If delegated, wait for delegator’s anchored seal
If elected, send event to witnesses and collect receipts.
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.
- 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.
- 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:
- notifier
stores notices for numan consumption
- Type:
- 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:
hby (habbing.Habery) – database environment for local Habs
notifier (notifying.Notifier) – stores notices for numan consumption
- 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
- 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.
- db
Injected. lmdb data base for KEL etc.
- Type:
- 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
rpymessages.rvy (Revery) – factory that processes reply
rpymessages.kvy (Kevery) – factory for local processing of local event msgs.
psr (Parser) – parses local messages for
.kvyand.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
.preis in.kevers, False otherwise.- Return type:
bool
- decrypt(ser, verfers=None, **kwa)[source]
Decrypt given serialization
serusing appropriate keys. Uses provided verfers or.kever.verfersto 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
exnmessage, 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
eidis allowed as endpoint provider forcidinrole.- Parameters:
cid (str) – qb64 identifier prefix of controller authorizing endpoint provider
eidin role.role (str) – endpoint role such as controller, witness, watcher, etc.
eid (str) – qb64 identifier prefix of endpoint provider in role.
- Returns:
True if
eidis 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
eidis authorized (enabled or allowed) as endpoint provider forcidinrole.- Parameters:
cid (str) – qb64 identifier prefix of controller authorizing endpoint provider
eidin role.role (str) – endpoint role such as controller, witness, watcher, etc.
eid (str) – qb64 identifier prefix of endpoint provider in role.
- Returns:
True if
eidis 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
eidis enabled as endpoint provider forcidinrole.- Parameters:
cid (str) – qb64 identifier prefix of controller authorizing endpoint provider
eidin role.role (str) – endpoint role such as controller, witness, watcher, etc.
eid (str) – qb64 identifier prefix of endpoint provider in role.
- Returns:
True if
eidis 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
eidin 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.
- nested Mict keyed as
- 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
eidis allowed for a givencidand 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
cidat 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
witnessfor results from this method.
- nested Mict keyed as
- 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)whereserderis the event Serder,sigersis a list of Siger instances, anddupleis 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.DnDwhich 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.EstOnlywhich 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, androlefrom 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 attachmentsis 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
eidand optionalschemefrom 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
eidinrole.- Parameters:
eid (str) – qb64 of endpoint provider to be authorized.
role (str) – authorized role for
eid. Default isRoles.controller.allow (bool) – True means add
eidatroleas authorized. False means cuteidatroleas 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
snforpre, 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
preis not in kevers.
- Raises::
MissingEntryError: if no event is found for
preatsn.
- 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
snwith optionally attached signatures and seal source couple.
- msg (bytearray): qb64b serialization of own event at
- 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
qrymessage 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
rctmessage 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
.cfto this Hab. Assumes that.preand 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
makeEndRoleand makeLocScheme, includingversionandkind.
- **kwa: keyword arguments forwarded to
- replay(pre=None, fn=0)[source]
Return replay of FEL (first-seen event log) for
prestarting fromfn. 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
cidfrom 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:
cidonly: end authz for all eids in all roles and loc url for all schemes at each eid (filtered byeidsif provided).cid+scheme: end authz for all eids in all roles and loc url forschemeat each eid.cid+role: end authz for all eids inroleand loc url for all schemes at each eid.cid+role+scheme: end authz for all eids inroleand loc url forschemeat 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
eidfrom 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
aidfor 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/orreplyLocScheme().- 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.
- **kwa: keyword arguments forwarded to
- 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
serusing appropriate keys. Uses provided verfers or.kever.verfersto 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
indexedis True. SeeManager.sign.ondices (list[int or None] or None) – other indices (offsets) when
indexedis True. SeeManager.sign.
- Returns:
signed instances depending on
indexed.- Return type:
- witness(serder, kind='JSON', version=(1, 0), framed=False, nested=False, gvrsn=(1, 0), genusify=False)[source]
Build own witness receipt
rctmessage of serder with count code and witness indexed receipt signatures, if the key state ofserder.preshows 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.preis 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.MissingSignatureErroris 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:
- db
LMDB database for KEL etc. (Injected)
- Type:
- cf
Configuration file instance. (Injected)
- Type:
- mgr
Creates and rotates keys in the key store. (Injected)
- Type:
- rtr
Routes reply
rpymessages. (Injected)- Type:
- rvy
Factory that processes reply
rpymessages. (Injected)- Type:
- kvy
Factory for local processing of local event messages. (Injected)
- Type:
- psr
Parses local messages for
.kvyand.rvy. (Injected)- Type:
- name
Alias of the controller.
- Type:
str
- pre
qb64 prefix of the own local controller, or
Noneif new.- Type:
str
- 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
smidswhen not supplied.- Type:
list or None
- temp
Truemeans 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
Truemeans fully initialized with respect to databases;Falsemeans 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
Truemeans accepted into the local KEL,Falseotherwise. (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.preaid may appear insmids,rmids, or both.rmids (list or None) – qb64 prefixes of the rotating members of the multisig group. Defaults to
smidswhenNone.**kwa – Keyword arguments forwarded to
BaseHab.__init__, including all injected dependencies (ks,db,cf,mgr,rtr,rvy,kvy,psr),name,pre, andtemp.
- 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.MissingSignatureErroris 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) –
Truemeans the prefix is transferable (default).Falseforcesnsith='0'andcode=MtrDex.Ed25519N.isith (int, str, list, or None) – Incepting signing threshold as an int, hex str, or weighted list. Computed from
verferswhenNone.nsith (int, str, list, or None) – Next signing threshold as an int, hex str, or weighted list. Defaults to
isithwhenNone.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) –
TrueaddsTraitDex.EstOnly, restricting the KEL to establishment events only. Defaults toFalse.DnD (bool) –
TrueaddsTraitDex.DnD, disallowing delegated identifiers from this identifier. Defaults toFalse.merfers (list[Verfer]) –
Verferinstances 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) –
Digerinstances of the public next-key digests contributed by each multisig group member.Nonemeans 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
qryquery message.Builds a query event for
predirected at attestersrc, then endorses it through the local member hab (mhab) using the last event inmhab’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
qfield. Defaults to an empty dict whenNone.**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
serderisNone, delegates entirely toBaseHab.rotate(**kwa)for a locally-driven rotation. When a pre-built rotationserderis provided, the local member hab signs it, the result is processed through the local Kevery, and thesmids/rmidsmember lists are updated on both the instance and the persistedHabitatRecord.- 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
Nonea rotation event is generated byBaseHab.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.rotatewhenserderisNone.
- Returns:
Rotation message with attached signatures.
- Return type:
bytearray
- Raises:
ValidationError – If the habitat record for
self.predoes 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 whichmhabcontributed signing key material to the group, then delegates tomhab.signwith 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) –
Verferinstances representing the group’s current signing keys.Nonemeans useself.kever.verfers.indexed (bool) –
Truemeans return indexedSigerinstances;Falsemeans return unindexedCigarinstances. Defaults toTrue.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. WhenFalse(default), only the current signing index is used andpniis set toNone.indices (list or None) – Explicit current signing indices. Passed through to
Manager.sign; computed automatically whenNone.ondices (list or None) – Explicit prior-next other indices. Passed through to
Manager.sign; computed automatically whenNone.
- Returns:
Signature instances over
ser.- Return type:
- Raises:
ValueError – If
mhabdid not contribute to the group event identified byverfers.
- 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:
Trueifmhab’s zeroth verfer matches the group signing key at the lowest recorded signer index;Falseotherwise, 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:
- db
LMDB database for KEL etc. (Injected)
- Type:
- cf
Configuration file instance. (Injected)
- Type:
- mgr
Creates and rotates keys in the key store. (Injected)
- Type:
- rtr
Routes reply
rpymessages. (Injected)- Type:
- rvy
Factory that processes reply
rpymessages. (Injected)- Type:
- kvy
Factory for local processing of local event messages. (Injected)
- Type:
- psr
Parses local messages for
.kvyand.rvy. (Injected)- Type:
- name
Alias of the controller.
- Type:
str
- pre
qb64 prefix of the own local controller, or
Noneif new.- Type:
str
- temp
Truemeans 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
Truemeans fully initialized with respect to databases;Falsemeans 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
Truemeans accepted into the local KEL,Falseotherwise. (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
secreciesare provided the key manager replays pre-loaded key pairs; otherwise it generates new keys viamgr.incept.After key material is prepared the inception event is built, persisted to the habitat record store, and processed by the local Kevery.
MissingSignatureErroris 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 to0.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) –
Truemeans the prefix is transferable (default).Falsemeans non-transferable; forcesncount=0,nsith='0', andcode=MtrDex.Ed25519N.isith (int, str, list, or None) – Incepting signing threshold as an int, hex str, or weighted list. Computed from
verferswhenNone.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
isithwhenNone.ncount (int or None) – Number of next (pre-rotated) keys. Defaults to
icountwhenNone.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) –
TrueaddsTraitDex.EstOnly, restricting the KEL to establishment events only. Defaults toFalse.DnD (bool) –
TrueaddsTraitDex.DnD, disallowing delegated identifiers from this identifier. Defaults toFalse.hidden (bool) – When
Truethe Hab is not saved to the habitat record store and its prefix is not added toself.prefixes. Defaults toFalse.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
isithwhenNone.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.rotateafter 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 allHabinstances created within this environment. Also owns theManager,Router,Revery,Kevery, andParserused 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
namefor hierarchical differentiation of databases. Empty string means no additional component.- Type:
str
- temp
Truemeans temporary storage and fast (test-suitable) salt stretching.Falsemeans persistent storage and tier-appropriate key stretching.- Type:
bool
- mgr
Key manager for creating and rotating keys.
Noneuntilsetupcompletes successfully.- Type:
Manager or None
- habs
Habinstances keyed by their qb64 prefix. UsehabByNameto look up by name andhabByPreto look up by prefix.- Type:
dict
- inited
Trueoncesetuphas 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
Haberyinstance.Opens (or reuses) the keystore, event database, and config file, then calls
setupif bothdbandksare already open. When dependency-injected stores are not yet open (e.g. in an async context),setupmust 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) –
Truemeans use temporary storage in/tmpand fast salt-stretch methods suitable for testing.ks (Keeper | None) – Existing open keystore to reuse. A new
Keeperis created whenNone.db (Baser | None) – Existing open event database to reuse. A new
Baseris created whenNone.cf (Configer | None) – Existing config file instance to reuse. A new
Configeris created whenNone.clear (bool) – When
True, removes the resource directory onclose.headDirPath (str | None) – Override for the top-level directory path used when creating
ksanddb.version (Versionage) – Parser attachment code table version.
**kwa – Keyword arguments forwarded to
setupand stored in_initsfor deferred initialisation. Seesetupfor 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
Habfrom the database and from.habs.Also removes the name-to-prefix mapping, the prefix from
db.prefixes, and (if present) the entry fromdb.groups.- Parameters:
name (str) – Human-readable alias of the
Habto delete.ns (str | None) – Namespace of the
Hab. Defaults to""whenNone.
- Returns:
Trueif theHabwas found and successfully removed;Falseif 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 tomerfers. For each rotation member inrmids, the first (and only permitted) next key digest diger is appended tomigers(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,smidsis 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)wheremerfersis the ordered list of current signing key verfers andmigersis the ordered list of next key digest digers for the group.
- Return type:
- 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
Habinstance for a given name and optional namespace, orNone.Resolves the name to a prefix via
db.namesand then looks up theHabin.habs.- Parameters:
name (str) – Human-readable alias of the
Hab.ns (str | None) – Namespace of the
Hab. Defaults to""whenNone.
- Returns:
- The matching
Habinstance, orNoneif not found.
- The matching
- Return type:
Hab | None
- habByPre(pre)[source]
Return the
Habinstance for a given prefix, orNone.- Parameters:
pre (str) – qb64 AID prefix to look up.
- Returns:
- The
Habregistered underpre, orNoneif not found.
- The
- 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
Habis constructed, its prefix set topre, and the record persisted directly rather than throughHab.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
Habthat 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,smidsis 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
GroupHabinstance with
.preset topre.
- The newly created and persisted
- Return type:
- Raises:
ConfigurationError – If
mhab.preis not insmidsorrmids, 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
joinGroupHabbut forSignifyGroupHabinstances. The groupHabis constructed with the givenpre, 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
Habthat 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,smidsis 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
SignifyGroupHabinstance with.preset topre.
- Return type:
- Raises:
ConfigurationError – If
mhab.preis not insmidsorrmids, or if a member’s KEL is missing from.kevers.
- property kevers
All
Keverinstances fromdb.kevers, keyed by qb64 prefix.- Type:
dict
- loadHabs()[source]
Load all
Habinstances persisted in the database into.habs.Called by
setupafter the keystore and event database are open anddb.reloadhas already populateddb.keversanddb.prefixesfrom stored key state, removing any orphaned hab records without valid key state.Each record in
db.habsis inspected to determine the correctHabsubclass:GroupHab—midset,sidnot set (local multisig group).SignifyHab—sidset,midnot set (Signify-managed single identifier).SignifyGroupHab— bothsidandmidset (Signify-managed multisig group).Hab— neithersidnormidset (standard local identifier).
After all habs are loaded, group habs have their
.mhab(local member hab) populated from.habs.reconfigureis called both before and after loading.- Raises:
ConfigurationError – If a non-group
Habloaded 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
.keversbefore 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
Habthat is a member of this group.smids (list[str]) – qb64 prefixes of the signing members. Each must have a KEL in
.keversand exactly one current signing key.rmids (list[str] | None) – qb64 prefixes of the rotation members from which next key digests are extracted. When
None,smidsis 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. SeemakeHabfor the full list; additionally:DnD(bool):TraitDex.DnDto disallow delegated identifiers from this identifier.
- Returns:
The newly created and persisted
GroupHabinstance.- Return type:
- Raises:
ConfigurationError – If
mhab.preis not present in eithersmidsorrmids, 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
Habis registered in.habskeyed 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.cfwhenNone.**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;Falsefor 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.EstOnlyto restrict the KEL to establishment events only.data(list | None): Seal dicts for the inception event.
- Returns:
The newly created and persisted
Habinstance.- Return type:
- Raises:
ConfigurationError – If
nscontains 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
Habthat 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,smidsis 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
SignifyGroupHabinstance.
- Return type:
- 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
SignifyHabinstance.- Return type:
- property prefixes
Local prefixes registered in
db.prefixes.- Type:
OrderedSet
- reconfigure()[source]
Apply configuration from the
Configerconfig file to thisHabery.Reads the config file via
self.cf.get()and processes any OOBI URLs found in the following keys, storingOobiRecordentries in the database:iurls— introduction OOBI URLs written todb.oobis.durls— delegation OOBI URLs written todb.oobis.wurls— well-known (MFA) OOBI URLs written todb.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
Haberyafterdbandksare open.Intended to be called once both
.dband.kshave 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 theManager. 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 theManager.aeid (str | None) – qb64 non-transferable identifier prefix used for authentication and encryption of secrets in the keystore. When provided and different from the
aeidalready in the database, all secrets are re-encrypted under the newaeid; in this caseseedmust also be provided. Anaeidchange should require a second authentication factor in addition toseed.bran (str | None) – Base64 string of at least 21 characters used as base material to derive
seedvia salt stretching. Allows alphanumeric passcodes (e.g. from a password manager) to serve as the key-store secret. Ignored whenseedis 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) whenNone.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 associatedDoerexits.temp (bool | None) – When
True, overrides the instancetempflag to use fast salt-stretch methods during setup.
- Raises:
ClosedError – If
.ksor.dbis not open when called.ValueError – If
branis shorter than 21 characters.AuthError – If the provided
seeddoes not authenticate theaeidstored in the keystore.
- 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.
- Inherited Attributes:
- done (bool): Completion state.
Truemeans finished normally; Falseindicates incomplete due to close or abort.- tyme (float): Relative cycle time obtained from the injected
tymthclosure.- tymth (callable): Injected closure returned by
Tymist.tymeth(). Call it to get the current
Tymist.tyme. Injected viawind().- tock (float): Desired seconds between
recurcalls. Zero means run ASAP. Non-negative.
- done (bool): Completion state.
Note
Implements the Doer coroutine protocol:
enter,recur,exit,close, andabort. Seedoing.Doerfor 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.
- 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.
- 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:
- 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
SignifyHabto 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:
- smids
qb64 prefixes of current signing members of the group.
- Type:
list[str]
- rmids
qb64 prefixes of rotating members of the group. Defaults to
smidswhen 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 toself.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.
MissingSignatureErroris 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 thesmidsandrmidson both the instance and the persistedHabitatRecord.- 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.predoes 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
makeandrotateas pre-built, pre-signed serders; this class never generates or holds private key material, and itssignmethod always raisesKeriError.- ks
LMDB key store. (Injected)
- Type:
- db
LMDB database for KEL etc. (Injected)
- Type:
- cf
Configuration file instance. (Injected)
- Type:
- mgr
Creates and rotates keys in the key store. (Injected)
- Type:
- rtr
Routes reply
rpymessages. (Injected)- Type:
- rvy
Factory that processes reply
rpymessages. (Injected)- Type:
- kvy
Factory for local processing of local event messages. (Injected)
- Type:
- psr
Parses local messages for
.kvyand.rvy. (Injected)- Type:
- name
Alias of the controller.
- Type:
str
- pre
qb64 prefix of the own local controller, or
Noneif new.- Type:
str
- temp
Truemeans 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
Truemeans fully initialized with respect to databases;Falsemeans 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
saveisTruea 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 messageinto 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 toself.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 swallowMissingSignatureError; any exception from the Kevery is wrapped in aConfigurationErrorand 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
rpymessage stream containing the KEL replay forcidplus 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:
cidonly — end authz for all eids in all roles, loc URLs for all schemes at each eid (optionally restricted toeids).cid+scheme— end authz for all eids in all roles, loc URL forschemeat each eid (optionally restricted toeids).cid+role— end authz for all eids inrole, loc URLs for all schemes at each eid (optionally restricted toeids).cid+role+scheme— end authz for all eids inrole, loc URL forschemeat each eid (optionally restricted toeids).
When
roleisRoles.witnessand this hab is itself one ofcid’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.
Nonemeans 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
Habwithnamealready exists in theHaberyit is reused; otherwise a new single-keyHab(icount=1, isith='1', ncount=1, nsith='1') is created viaHabery.makeHab.- Parameters::
name (str): Name of the
Hab(and the underlying shared databases). base (str): Optional path component for shared resources. SeeopenHby.- salt (bytes | None): Raw (not qb64) salt bytes passed to
Habery. Converted to qb64 internally. A fresh salt is generated when
None.
temp (bool):
Truemeans use temporary databases. SeeopenHby. cf (Configer | None): OptionalConfigerinstance for loadingconfiguration data.
- **kwa: Additional keyword arguments forwarded to
Habery.makeHab. When
versionis provided, it is also used for the sharedHaberyparser.
- salt (bytes | None): Raw (not qb64) salt bytes passed to
- Yields::
- tuple[Habery, Hab]: The shared
Haberyenvironment and the named Habinstance.
- tuple[Habery, Hab]: The shared
- keri.app.habbing.openHby(*, name='test', base='', temp=True, salt=None, **kwa)[source]
Context manager that creates and yields a
Haberyinstance, 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
nameforfurther hierarchical differentiation of databases. Empty string means no additional component.
- temp (bool): When
True, stores.ks,.db, and.cfin /tmpand uses a fast (low-cost) salt-stretch method suitable for testing. WhenFalse, uses the resource tier specified bytier.- 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
Haberyfor the full list (seed,aeid,bran,pidx,algo,tier,free,version).
- temp (bool): When
- Yields::
Habery: Fully initialised
Haberyinstance.
keri.app.httping
keri.peer.httping module
- 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
ClientDoerinstance, an hio HTTPClientinstance, and adatetimetimestamp.- 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
- 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
- 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
- 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
- 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®=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
- 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
- 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.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:
- 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
- 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:
- 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:
- 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:
- 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:
- 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:
- .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:
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.
- 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
- 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.
- encrypter
instance for encrypting secrets. Public encryption key is derived from aeid (public signing key)
- Type:
- decrypter
instance for decrypting secrets. Private decryption key is derived seed (private signing key seed)
- Type:
- 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
- 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:
- 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.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
- 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:
- 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
- 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
- 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
- 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
- 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
- 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
- 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
keri.app.oobiing
keri.kli.common.oobiing module
- class keri.app.oobiing.OobiRequestHandler(hby, notifier)[source]
Handler for oobi notification EXN messages
- 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
- processClients()[source]
Process Client responses by parsing the messages and removing the client/doer
- 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
- 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.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
- 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)
- 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.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
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
- 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
- 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
- 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
- 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)