### Setup KERI Development Environment Source: https://keripy.readthedocs.io/en/latest/_sources/readme.rst Steps to set up a Python virtual environment for KERI development. This includes creating the environment, activating it, and installing project dependencies from a requirements file. ```shell python3 -m venv keripy source keripy/bin/activate pip install -r requirements.txt ``` -------------------------------- ### Setup Habery with Database and Key Services Source: https://keripy.readthedocs.io/en/latest/_modules/keri/app/habbing The `setup` method configures the Habery instance, assuming the database (`.db`) and key services (`.ks`) have been opened. It handles dependency injection for these services and allows for asynchronous setup, enabling .db and .ks to open after the Baser and Keeper instances are created. This method initializes databases if they are empty. ```python [docs] def setup(self, *, seed=None, aeid=None, bran=None, pidx=None, algo=None, salt=None, tier=None, free=False, temp=None, ): """ Setup Habery. Assumes that both .db and .ks have been opened. This allows dependency injection of .db and .ks into Habery instance prior to .db and .kx being opened to accomodate asynchronous process setup of these resources. Putting the .db and .ks associated initialization here enables asynchronous opening .db and .ks after Baser and Keeper instances are instantiated. First call to .setup will initialize databases (vacuous initialization). Parameters: 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. 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 prikey must not be empty. A change in aeid should require a second authentication mechanism besides the prikey. bran (str): Base64 21 char string that is used as base material for seed. bran allows alphanumeric passcodes generated by key managers like 1password to be Okey store for seed. pidx (int): Initial prefix index for vacuous ks algo (str): algorithm (randy or salty) for creating key pairs default is root algo which defaults to salty salt (str): qb64 salt for creating key pairs tier (str): security tier for generating keys from salt (Tierage) free (boo): free resources by closing on Doer exit if any temp (bool): True means use shortcuts for testing. Use quick method to stretch salts for seeds such as bran salt to seed or key creation of Habs. Otherwise use more resources set by tier to stretch """ if not (self.ks.opened and self.db.opened): raise kering.ClosedError("Attempt to setup Habitat with closed " "database, .ks or .db.") self.free = True if free else False if bran and not seed: # create seed from stretch of bran as salt if len(bran) < 21: raise ValueError(f"Bran (passcode seed material) too short.") bran = coring.MtrDex.Salt_128 + 'A' + bran[:21] # qb64 salt for seed signer = coring.Salter(qb64=bran).signer(transferable=False, tier=tier, temp=temp) seed = signer.qb64 ``` -------------------------------- ### Setup Hab Instance Source: https://keripy.readthedocs.io/en/latest/keri_app The `setup` function initializes or configures a Hab instance. It accepts various parameters for setting up the Hab, including seed data, authentication elements, and cryptographic algorithm details. The `temp` parameter suggests the possibility of temporary Hab configurations. ```python setup(_*_ , _seed =None_, _aeid =None_, _bran =None_, _pidx =None_, _algo =None_, _salt =None_, _tier =None_, _free =False_, _temp =None_)[source]¶ ``` -------------------------------- ### Indirector Start Method Source: https://keripy.readthedocs.io/en/latest/_modules/keri/app/indirecting The start method initializes the witness and prints its name and prefix once the habitat is in an initialized state. It yields control until the habitat is ready. ```python def start(self, tymth=None, tock=0.0): """ Prints witness name and prefix Parameters: tymth (function): injected function wrapper closure returned by .tymen() of Tymist instance. Calling tymth() returns associated Tymist .tyme. tock (float): injected initial tock value """ self.wind(tymth) self.tock = tock _ = (yield self.tock) while not self.hab.inited: yield self.tock print("Witness", self.hab.name, ":", self.hab.pre) ``` -------------------------------- ### Initialize Regery and Setup Source: https://keripy.readthedocs.io/en/latest/_modules/keri/vdr/credentialing Initializes the Regery class, which manages local registries. It sets up the registry database and loads existing registries if the reger is already open. The setup method ensures the reger is open and loads all registered registries. ```python class Regery: def __init__(self, hby, name="test", base="", reger=None, temp=False, cues=None): self.hby = hby self.name = name self.base = base self.temp = temp self.cues = cues if cues is not None else decking.Deck() self.reger = reger if reger is not None else Reger(name=self.name, base=base, db=self.hby.db, temp=temp, reopen=True) self.tvy = eventing.Tevery(reger=self.reger, db=self.hby.db, local=True, lax=True) self.psr = parsing.Parser(framed=True, kvy=self.hby.kvy, tvy=self.tvy) self.regs = {} # List of local registries self.inited = False if self.reger.opened: self.setup() def setup(self): if not self.reger.opened: raise kering.ClosedError("Attempt to setup Regery with closed " "reger.") self.loadRegistries() self.inited = True ``` -------------------------------- ### Setup Habery with Dependency Injection Source: https://keripy.readthedocs.io/en/latest/keri_app Initializes the Habery instance, allowing for dependency injection of database (.db) and key store (.ks) components. This is crucial for asynchronous resource setup, enabling .db and .ks to be opened after Baser and Keeper instances are created. The first call to .setup initializes the databases. ```python def setup(self, *, seed: str = None, aeid: str = None, bran: str = None, pidx: int = None, algo: str = None, salt: str = None, tier: str = None, free: bool = None, temp: bool = None): """Setup Habery. Assumes that both .db and .ks have been opened. This allows dependency injection of .db and .ks into Habery instance prior to .db and .kx being opened to accomodate asynchronous process setup of these resources. Putting the .db and .ks associated initialization here enables asynchronous opening .db and .ks after Baser and Keeper instances are instantiated. First call to .setup will initialize databases (vacuous initialization). Parameters: 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. 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 prikey must not be empty. A change in aeid should require a second authentication mechanism besides the prikey. bran (_str_) – Base64 21 char string that is used as base material for seed. bran allows alphanumeric passcodes generated by key managers like 1password to be Okey store for seed. pidx (_int_) – Initial prefix index for vacuous ks algo (_str_) – algorithm (randy or salty) for creating key pairs default is root algo which defaults to salty salt (_str_) – qb64 salt for creating key pairs tier (_str_) – security tier for generating keys from salt (Tierage) free (_boo_) – free resources by closing on Doer exit if any temp (_bool_) – True means use shortcuts for testing. Use quick method to stretch salts for seeds such as bran salt to seed or key creation of Habs. Otherwise use more resources set by tier to stretch """ pass ``` -------------------------------- ### GET /db/getTopItems Source: https://keripy.readthedocs.io/en/latest/_modules/keri/db/dbing Iterates over a specific branch of the database starting from a given key. It returns full keys and their associated values within that branch. ```APIDOC ## GET /db/getTopItems ### Description Iterates over a branch of `db` given by `key`. Returns an iterator of (full key, val) tuples over a branch of the db given by the top key, where the full key is the complete database key for the value, not a truncated top key. Works for both `dupsort==False` and `dupsort==True`. ### Method GET ### Endpoint `/db/getTopItems` ### Parameters #### Path Parameters None #### Query Parameters - **db** (lmdb._Database) - Required - An instance of a named sub database with `dupsort==False`. - **key** (bytes) - Optional - The starting key for the branch iteration. If empty, starts from the beginning of the database. ### Request Example ```json { "db": "my_database", "key": "cHJvZHVjdA=" } ``` ### Response #### Success Response (200) - **items** (iterator) - An iterator yielding (full key, val) tuples. #### Response Example ```json [ ["product.electronics.tv", "4K Smart TV"], ["product.electronics.phone", "Latest Smartphone"] ] ``` #### Error Response (e.g., 404) - **message** (string) - Indicates if the iterator is empty or an error occurred. ``` -------------------------------- ### Get First Seen Event Messages with Attachments Source: https://keripy.readthedocs.io/en/latest/_modules/keri/vdr/viring Retrieves an iterator of event messages with attachments, ordered by their first seen time, starting from a specified order number. ```APIDOC ## GET /events/first_seen_with_attachments ### Description Returns an iterator of first seen event messages with attachments for the TEL prefix, starting at a specified order number. This effectively provides a replay of events in their first seen order, including attachments. ### Method GET ### Endpoint /events/first_seen_with_attachments ### Parameters #### Query Parameters - **pre** (bytes) - Required - The qb64 identifier prefix of the registry state TEL. - **fn** (int) - Required - The first seen ordinal number to start from. ### Request Example ```json { "pre": "EAEa2k7kC9z3f4x9R0p8x1g6z5v7y2b3t4q5w6e7r8t9y0u1i2o3p4a5s6d7f8g9h0j1k2l3z4x5c6v7b8n9m0", "fn": 100 } ``` ### Response #### Success Response (200) - **iterator** (iterator) - An iterator yielding bytearrays, where each bytearray represents a serialized event message with attachments. #### Response Example ```json [ "bytearray_representation_of_event_msg_1", "bytearray_representation_of_event_msg_2" ] ``` ``` -------------------------------- ### keri.end.ending.setup Source: https://keripy.readthedocs.io/en/latest/keri_end Sets up and returns a list of doers to run the controller. ```APIDOC ## keri.end.ending.setup ### Description Setup and return doers list to run controller. ### Method N/A (Function) ### Parameters #### Path Parameters N/A #### Query Parameters - **name** (str) - Optional - Default 'who' - **temp** (bool) - Optional - Default False - **tymth** (callable) - Optional - **isith** (callable) - Optional - **count** (int) - Optional - Default 1 - **remotePort** (int) - Optional - Default 5621 - **localPort** (int) - Optional - Default 5620 - **webPort** (int) - Optional - Default 8081 #### Request Body N/A ### Request Example N/A ### Response N/A #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### keri.app.indirecting.setupWitness Source: https://keripy.readthedocs.io/en/latest/keri_app Sets up the witness controller and associated doers. ```APIDOC ## POST /websites/keripy_readthedocs_io_en/keri/app/indirecting/setupWitness ### Description Setup witness controller and doers. ### Method POST ### Endpoint /websites/keripy_readthedocs_io_en/keri/app/indirecting/setupWitness ### Parameters #### Query Parameters - **hby** (object) - Required - The "Habery" instance. - **alias** (string) - Optional - Alias for the witness controller. Defaults to 'witness'. - **mbx** (object) - Optional - Mailbox object. - **aids** (list) - Optional - List of agent identifiers. - **tcpPort** (int) - Optional - TCP port for the witness. Defaults to 5631. - **httpPort** (int) - Optional - HTTP port for the witness. Defaults to 5632. - **keypath** (string) - Optional - The file path to the TLS private key. - **certpath** (string) - Optional - The file path to the TLS signed certificate (public key). - **cafilepath** (string) - Optional - The file path to the TLS CA certificate chain file. ### Response #### Success Response (200) - **result** (object) - The result of setting up the witness controller and doers. #### Response Example ```json { "result": "" } ``` ``` -------------------------------- ### Get Next Signed Event Receipt Items in KeriPy Source: https://keripy.readthedocs.io/en/latest/_modules/keri/db/basing Returns duplicate items (key, val) from the 'vres' database starting after a given key. If 'key' is empty, it starts from the first key. If 'skip' is False and 'key' is not empty, it includes items at the specified 'key'. Duplicates are retrieved in insertion order. ```python def getVreItemsNext(self, key=b'', skip=True): """ Use snKey() Return all dups of partial signed escrowed event quintuple items at next key after key. Item is (key, val) where proem has already been stripped from val val is Quinlet is edig + spre + ssnu + sdig +sig If key is b'' empty then returns dup items at first key. If skip is False and key is not b'' empty then returns dup items at key Returns empty list if no entry at key Duplicates are retrieved in insertion order. """ return self.getIoItemsNext(self.vres, key, skip) ``` -------------------------------- ### GET /getItemIter Source: https://keripy.readthedocs.io/en/latest/_modules/keri/db/subing Returns an iterator that yields key-value pairs for all items in a subdatabase whose keys start with a specified prefix. If no keys are provided, it iterates over all items in the subdatabase. ```APIDOC ## GET /getItemIter ### Description Returns an iterator that yields key-value pairs for all items in a subdatabase whose keys start with a specified prefix. If no keys are provided, it iterates over all items in the subdatabase. ### Method GET ### Endpoint /getItemIter ### Parameters #### Query Parameters - **keys** (Union[str, bytes], optional) - Defaults to `b""`. The key or iterable of key strings/bytes to form the key prefix. Returns all items if empty. ### Request Example To get all items: ```bash GET /getItemIter ``` To get items with a specific key prefix: ```bash GET /getItemIter?keys=prefix1,prefix2 ``` ### Response #### Success Response (200) - **iterator** - An iterator yielding tuples of `(key, val)`, where `key` is the item's key and `val` is the item's value. The iteration stops when all matching items are retrieved. #### Response Example (This endpoint returns an iterator, so a direct JSON response example is not applicable. The client would iterate over the response.) ```python # Example usage in client code response = requests.get('/getItemIter?keys=prefix1', stream=True) for line in response.iter_lines(): if line: key, val = line.decode('utf-8').split(':', 1) print(f"Key: {key}, Value: {val}") ``` ``` -------------------------------- ### Create/Setup Habitat Instance Source: https://keripy.readthedocs.io/en/latest/keri_app The make method finalizes the setup or creation of a Hab instance, including inception. It assumes that injected dependencies have already been configured. This method allows for detailed parameterization of key derivation, signing thresholds, witness configurations, and data commitments. ```python def make(*_ , _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_)[source]: """Finish setting up or making Hab from parameters includes inception. Assumes injected dependencies were already setup. Parameters: * **secrecies** (_list_ _|__None_) – list of secrets to preload key pairs if any * **iridx** (_int_) – initial rotation index after ingestion of secrecies * **code** (_str_) – prefix derivation code default Blake3 * **icode** (_str_) – signing key code default Ed25519 * **dcode** (_str_) – next key derivation code default Blake3 * **transferable** (_bool_) – True means pre is transferable (default) False means pre is nontransferable * **isith** (_int_ _|__str_ _|__list_ _|__None_) – incepting signing threshold as int, str hex, or list weighted if any, otherwise compute default from verfers * **icount** (_int_) – incepting key count for number of keys. default 1 * **nsith** (_int_ _,__str_ _,__list_ _|__None_) – next signing threshold as int, str hex or list weighted if any, otherwise compute default from digers * **ncount** (_int_ _|__None_) – next key count for number of next keys * **toad** (int |str| None) – int or str hex of witness threshold if specified else compute default based on number of wits (backers) * **wits** (_list_ _|__None_) – qb64 prefixes of witnesses if any * **delpre** (_str_ _|__None_) – qb64 of delegator identifier prefix if any * **estOnly** (_bool_ _|__None_) – True means add trait eventing.TraitCodex.EstOnly which means only establishment events allowed in KEL for this Hab False (default) means allows non-est events and no trait is added. * **DnD** (_bool_) – True means add trait of eventing.TraitCodex.DnD which means do not allow delegated identifiers from this identifier False (default) means do allow and no trait is added. * **hidden** (_bool_) – A hidden Hab is not included in the list of Habs. * **data** (_list_ _|__None_) – seal dicts algo is str key creation algorithm code * **salt** (_str_) – qb64 salt for randomization when salty algorithm used * **tier** (_str_) – is str security criticality tier code when using salty algorithm """ pass ``` -------------------------------- ### Get List of Notes Source: https://keripy.readthedocs.io/en/latest/_modules/keri/app/notifying Retrieves a list of notes within a specified range (start and end). It verifies the signature of each note during retrieval. If any note's signature is invalid, it raises a ValidationError. ```python def getNotes(self, start=0, end=24): """ 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 """ notesigs = self.noter.getNotes(start, end) notes = [] for note, cig in notesigs: if not self.hby.signator.verify(ser=note.raw, cigar=cig): raise kering.ValidationError("note stored without valid signature") notes.append(note) return notes ``` -------------------------------- ### Initialize Keripy Environment Source: https://keripy.readthedocs.io/en/latest/_modules/keri/app/habbing This snippet shows the initialization of the Keripy environment, which sets up the keystore, database, and configuration manager. It handles parameters for naming, temporary storage, clearing resources, and directory overrides. ```python def __init__(self, *, name='test', base="", temp=False, ks=None, db=None, cf=None, clear=False, headDirPath=None, **kwa): """ Initialize instance. Parameters: name (str): alias name for shared environment config databases etc. base (str): optional directory path segment inserted before name that allows further differentiation with a hierarchy. "" means optional. temp (bool): True means use temporary or limited resources testing. Store .ks, .db, and .cf in /tmp Use quick method to stretch salts for seeds such as bran salt to seed or key creation of Habs. Otherwise use more resources set by tier to stretch ks (Keeper): keystore lmdb subclass instance db (Baser): database lmdb subclass instance cf (Configer): config file instance clear (bool): True means remove resource directory upon close when reopening False means do not remove directory upon close when reopening headDirPath (str): directory override Parameters: Passed through via kwa to setup for later init 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. 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 Haberyare re-encrypted using new aeid. In this case the provided prikey must not be empty. A change in aeid should require a second authentication mechanism besides the prikey. bran (str): Base64 22 char string that is used as base material for seed. bran allows alphanumeric passcodes generated by key managers like 1password to be key store for seed. pidx (int): Initial prefix index for vacuous ks algo (str): algorithm (randy or salty) for creating key pairs default is root algo which defaults to salty salt (str): qb64 salt for creating key pairs tier (str): security tier for generating keys from salt (Tierage) free (boo): free resources by closing on Doer exit if any temp (bool): See above """ self.name = name self.base = base self.temp = temp self.ks = ks if ks is not None else keeping.Keeper(name=self.name, base=self.base, temp=self.temp, reopen=True, clear=clear, headDirPath=headDirPath) self.db = db if db is not None else basing.Baser(name=self.name, base=self.base, temp=self.temp, reopen=True, clear=clear, ``` -------------------------------- ### getLdeItemsNextIter (get iterator of next likely duplicate event items) Source: https://keripy.readthedocs.io/en/latest/_modules/keri/db/basing Returns an iterator for likely duplicate escrowed event dig items starting from the next key after the provided key. The `val` has had the proem already stripped. If `skip` is `False` and the provided `key` is not empty, it returns items starting from the provided `key`. Items are retrieved in insertion order. ```APIDOC ## GET /getLdeItemsNextIter ### Description Returns an iterator over likely duplicate escrowed event dig items at the next key after the provided `key`. The `val` has had the proem already stripped. If `key` is empty (`b''`), it returns duplicate items at the first key. If `skip` is `False` and `key` is not empty, it returns duplicate items starting at `key`. Duplicates are retrieved in insertion order. ### Method GET ### Endpoint `/getLdeItemsNextIter` ### Parameters #### Query Parameters - **key** (bytes) - Optional - The key after which to start retrieving items. Defaults to `b''` (empty bytes). - **skip** (boolean) - Optional - If `True` (default), skips the provided `key`. If `False`, includes the provided `key` if it's not empty. ### Request Example ```json { "key": "start_key", "skip": false } ``` ### Response #### Success Response (200) - **iterator** (iterator) - An iterator yielding objects with `key` (bytes) and `val` (bytes) for the likely duplicate escrowed event dig items. #### Response Example ```json // Example of iterating through results: for item in response.json()['iterator']: print(f"Key: {item['key']}, Value: {item['val']}") ``` ``` -------------------------------- ### Get Items Iterator from DB Source: https://keripy.readthedocs.io/en/latest/keri_db Returns an iterator over tuples of (key, val) for items in a sub-database whose keys start with a given prefix. It supports optional decryption for the values. If keys are empty, it iterates over all items. ```python def getItemIter(self, _keys : str | Iterable = b''_, _decrypter : Decrypter | None = None_)[source]¶ """ Returns: of tuples (key, val) over the all the items in subdb whose key startswith key made from keys. Keys may be keyspace prefix to return branches of key space. When keys is empty then returns all items in subdb Return type: iterator (Iterator) decrypter (coring.Decrypter): optional. If provided assumes value in db was encrypted and so decrypts before converting to Signer. Parameters: keys (_Iterator_) – tuple of bytes or strs that may be a truncation of a full keys tuple in in order to get all the items from multiple branches of the key space. If keys is empty then gets all items in database. """ pass ``` -------------------------------- ### Setup Key Manager Source: https://keripy.readthedocs.io/en/latest/keri_app Initializes or updates the key manager's global attributes and properties. This includes setting the authentication identifier, key pair index, hashing algorithm, salt, and security tier. ```APIDOC ## POST /setup ### Description 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 accommodate 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). ### Method POST ### Endpoint /setup ### Parameters #### Query Parameters - **aeid** (str) - Optional - 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) - Optional - Index of next new created key pair sequence for given identifier prefix. - **algo** (str) - Optional - Root algorithm (randy or salty) for creating key pairs. - **salt** (str) - Optional - qb64 of root salt. Makes random root salt if not provided. - **tier** (str) - Optional - Default security tier (Tierage) for root salt. ### Request Example ```json { "aeid": "Eis_P9dI-01o-y72_A6_oQx9V1gLg76h8G7r326o", "pidx": 1, "algo": "salty", "salt": "some_salt_qb64", "tier": "High" } ``` ### Response #### Success Response (200) - **message** (str) - Confirmation message indicating setup is complete. #### Response Example ```json { "message": "Key manager setup complete." } ``` ``` -------------------------------- ### Get IO Item Iterator (Python) Source: https://keripy.readthedocs.io/en/latest/_modules/keri/db/koming Returns an iterator for all items in a subdatabase whose keys start with a given prefix. If no prefix is provided, it iterates through all items. Each item is yielded as a (key, value) tuple. ```python def getIoItemIter(self, keys: Union[str, Iterable]=b""): """ Returns: items (Iterator): tuple (key, val) over the all the items in subdb whose key startswith effective key made from keys. Keys may be keyspace prefix to return branches of key space. When keys is empty then returns all items in subdb. Parameters: keys (Iterable): tuple of bytes or strs that may be a truncation of a full keys tuple in in order to get all the items from multiple branches of the key space. If keys is empty then gets all items in database. Append "" to end of keys Iterable to ensure get properly separated top branch key. """ for iokey, val in self.db.getTopItemIter(db=self.sdb, key=self._tokey(keys)): yield (self._tokeys(iokey), self.deserializer(val)) ``` -------------------------------- ### KERI App Booting API Source: https://keripy.readthedocs.io/en/latest/keri_app Documentation for the booting components of the KERI application. ```APIDOC ## KERI App Booting API ### Description This section provides documentation for the booting functionalities within the KERI application. No specific classes or functions are detailed in the provided text. ``` -------------------------------- ### getLdeItemsNext (get next likely duplicate event items) Source: https://keripy.readthedocs.io/en/latest/_modules/keri/db/basing Retrieves all duplicate items (key, value pairs) of likely duplicate escrowed event dig items starting from the next key after the provided key. If `skip` is `False` and the provided `key` is not empty, it returns items starting from the provided `key`. Returns an empty list if no entry is found. Items are retrieved in insertion order. ```APIDOC ## GET /getLdeItemsNext ### Description Retrieves all duplicate items (key, val) of likely duplicate escrowed event dig items at the next key after the provided `key`. The `val` has had the proem already stripped. If `key` is empty (`b''`), it returns duplicate items at the first key. If `skip` is `False` and `key` is not empty, it returns duplicate items starting at `key`. Returns an empty list if no entry is found. Duplicates are retrieved in insertion order. ### Method GET ### Endpoint `/getLdeItemsNext` ### Parameters #### Query Parameters - **key** (bytes) - Optional - The key after which to start retrieving items. Defaults to `b''` (empty bytes). - **skip** (boolean) - Optional - If `True` (default), skips the provided `key`. If `False`, includes the provided `key` if it's not empty. ### Request Example ```json { "key": "start_key", "skip": false } ``` ### Response #### Success Response (200) - **items** (list of objects) - A list where each object contains `key` (bytes) and `val` (bytes) of the likely duplicate escrowed event dig items. #### Response Example ```json { "items": [ {"key": "item_key1", "val": "item_value1"}, {"key": "item_key2", "val": "item_value2"} ] } ``` ``` -------------------------------- ### Get Value by Keys Source: https://keripy.readthedocs.io/en/latest/keri_db Retrieves a value from the database using a composite key formed from provided key strings. The value is decoded as UTF-8. Returns None if no entry exists at the specified keys. Includes usage example with walrus operator. ```python def get(self, _keys: Union[str, Iterable]) -> str: """ Gets val at keys Parameters: keys (tuple): of key strs to be combined in order to form key Returns: decoded as utf-8 None if no entry at keys Return type: data (str) Usage: Use walrus operator to catch and raise missing entry if (data := mydb.get(keys)) is None: > raise ExceptionHere use data here """ pass ``` -------------------------------- ### Get Items from LMDB Set Source: https://keripy.readthedocs.io/en/latest/_modules/keri/db/dbing Retrieves a list of (iokey, val) tuples for entries in an LMDB set that share the same apparent effective key. The iokey includes a hidden ordinal key suffix for insertion ordering. This function allows specifying a starting ordinal value for retrieval. ```Python def getIoSetItems(self, db, key, *, ion=0, sep=b'.'): """ Returns: items (list): list of tuples (iokey, val) of entries in set of with same apparent effective key. iokey includes the ordinal key suffix Uses hidden ordinal key suffix for insertion ordering. Parameters: db (lmdb._Database): instance of named sub db with dupsort==False key (bytes): Apparent effective key ion (int): starting ordinal value, default 0 """ with self.env.begin(db=db, write=False, buffers=True) as txn: items = [] ``` -------------------------------- ### Setup KERI Controller (Python) Source: https://keripy.readthedocs.io/en/latest/_modules/keri/end/ending Sets up and returns a list of doers to run the KERI controller. This includes initializing the Habery, creating a habitat, setting up a wirelog for test vectors, and creating a Falcon application with loaded endpoints. It also sets up a web server to serve the application. ```python [docs] def setup(name="who", temp=False, tymth=None, isith=None, count=1, remotePort=5621, localPort=5620, webPort=8081): """ Setup and return doers list to run controller """ # setup habery with resources hby = habbing.Habery(name=name, base="endo", temp=True, free=True) hbyDoer = habbing.HaberyDoer(habery=hby) # setup doer # make hab hab = hby.makeHab(name=name, isith=isith, icount=count) # setup wirelog to create test vectors path = os.path.dirname(__file__) path = os.path.join(path, 'logs') wl = wiring.WireLog(samed=True, filed=True, name=name, prefix='keri', reopen=True, headDirPath=path) wireDoer = wiring.WireLogDoer(wl=wl) # setup doer # client = tcp.Client(host='127.0.0.1', port=remotePort, wl=wl) # clientDoer = tcp.ClientDoer(client=client) # setup doer # director = directing.Director(hab=hab, client=client, tock=0.125) # reactor = directing.Reactor(hab=hab, client=client) # must do it here to inject into Falcon endpoint resource instances myapp = falcon.App(cors_enable=True) # falcon.App instances are callable WSGI apps loadEnds(myapp, tymth=tymth, hby=hby) webServer = http.Server(name="keri.wsgi.server", app=myapp, port=webPort, wl=wl) webServerDoer = http.ServerDoer(server=webServer) # server = tcp.Server(host="", port=localPort, wl=wl) # serverDoer = tcp.ServerDoer(server=server) # setup doer ``` -------------------------------- ### WitnessStart Class Source: https://keripy.readthedocs.io/en/latest/keri_app The WitnessStart class is a Doer to print witness prefix after initialization. ```APIDOC ## Class WitnessStart ### Description Doer to print witness prefix after initialization. ### Parameters: - **hab** - Required - - **parser** - Required - - **kvy** - Required - - **tvy** - Required - - **rvy** - Required - - **exc** - Required - - **cues** - Optional - - **replies** - Optional - - **responses** - Optional - - **queries** - Optional - - **opts** - Optional - ### Methods: #### `start(_tymth =None_, _tock =0.0_)[source]` Prints witness name and prefix. Parameters: * **tymth** (_function_) – injected function wrapper closure returned by .tymen() of Tymist instance. Calling tymth() returns associated Tymist .tyme. * **tock** (_float_) – injected initial tock value ``` -------------------------------- ### Open LMDB Database and Get Max Key Size (Python) Source: https://keripy.readthedocs.io/en/latest/_modules/keri/db/dbing Demonstrates how to open an LMDB database using the 'lmdb' library and retrieve its maximum key size. This snippet requires the 'lmdb' library to be installed. It takes a database path as input and returns the max key size as an integer. ```python # -*- encoding: utf-8 -*- """ keri.db.dbing module """ import lmdb db = lmdb.open("/tmp/keri_db_setup_test") db.max_key_size() 511 ``` -------------------------------- ### Setup Verifier Instance - Python Source: https://keripy.readthedocs.io/en/latest/_modules/keri/vdr/verifying Performs delayed initialization of the Verifier instance by creating necessary components like Tevery, Parser, and CacheResolver. This method should be called only after the associated Habery context has been fully initialized. ```python def setup(self): """ Delayed initialization of instance by createing .tvy and .psr. Should not be called until .hab is initialized """ self.tvy = eventing.Tevery(reger=self.reger, db=self.hby.db, local=False) self.psr = parsing.Parser(framed=True, kvy=self.hby.kvy, tvy=self.tvy) self.resolver = scheming.CacheResolver(db=self.hby.db) self.inited = True ``` -------------------------------- ### Get Next Duplicate Items with LMDB Source: https://keripy.readthedocs.io/en/latest/_modules/keri/db/dbing Returns a list of all duplicate items (key-value pairs) at the next key following a given key in an LMDB database, maintaining insertion order. If `key` is empty, it starts from the first key. The proem is stripped from the value. Assumes `dupsort=True`. Handles `lmdb.BadValsizeError`. ```python def getIoItemsNext(self, db, key=b"", skip=True): """ Return list of all dup items at next key after key in db in insertion order. Item is (key, val) with proem stripped from val stored in db. If key == b'' then returns list of dup items at first key in db. If skip is False and key is not empty then returns dup items at key Returns empty list if no entries at next key after key If key is empty then gets io items (key, io value) at first key in db Use the return key from items as next key for next call to function in order to iterate through the database Assumes DB opened with dupsort=True Parameters: db is opened named sub db with dupsort=True key is bytes of key within sub db's keyspace or empty string skip is Boolean If True skips to next key if key is not empty string Othewise don't skip for first pass """ with self.env.begin(db=db, write=False, buffers=True) as txn: cursor = txn.cursor() items = [] if cursor.set_range(key): # moves to first_dup at key found = True if skip and key and cursor.key() == key: # skip to next key found = cursor.next_nodup() # skip to next key not dup if any if found: # slice off prepended ordering prefix on value in item items = [(key, val[33:]) for key, val in cursor.iternext_dup(keys=True)] return items ``` -------------------------------- ### Install KERI Python Packages Source: https://keripy.readthedocs.io/en/latest/_sources/readme.rst Installs essential Python packages for KERI using pip. This command installs multiple packages in a single operation, ensuring all dependencies are met efficiently. Alternatively, packages can be installed individually. ```shell $ pip3 install -U lmdb pysodium blake3 msgpack simplejson cbor2 ``` ```shell $ pip3 install -U lmdb $ pip3 install -U pysodium $ pip3 install -U blake3 $ pip3 install -U msgpack $ pip3 install -U simplejson $ pip3 install -U cbor2 ``` -------------------------------- ### Setup Witness Controller with keri.app.indirecting Source: https://keripy.readthedocs.io/en/latest/keri_app Sets up a witness controller and its associated doers. This function configures the networking ports and optional TLS settings for the witness. ```python from keri.app.indirecting import setupWitness # Example setup for a witness hby = setup_habery_instance() setupWitness(hby=hby, alias='my_witness', tcpPort=5631, httpPort=5632) ``` -------------------------------- ### Install Individual KERI Python Packages Source: https://keripy.readthedocs.io/en/latest/readme Installs each required Python package for KERI individually using pip. This approach allows for selective installation or reinstallation of specific dependencies. ```bash pip3 install -U lmdb pip3 install -U pysodium pip3 install -U blake3 pip3 install -U msgpack pip3 install -U simplejson pip3 install -U cbor2 ``` -------------------------------- ### LMDB Database Initialization Source: https://keripy.readthedocs.io/en/latest/keri_db Demonstrates the basic initialization of an LMDB database using the `lmdb.open()` function. It also shows how to check the maximum key size. ```python import lmdb db = lmdb.open(“/tmp/keri_db_setup_test”) db.max_key_size() 511 ``` -------------------------------- ### Get a Serder object from the database by key Source: https://keripy.readthedocs.io/en/latest/_modules/keri/db/subing This method retrieves a Serder object from the database based on the provided keys. If an entry exists at the specified key, it returns the corresponding Serder object; otherwise, it returns None. The 'keys' parameter is a tuple of strings used to form the database key. An example demonstrates using the walrus operator to handle cases where the entry might be missing. ```python def get(self, keys: Union[str, Iterable]): """ Gets Serder at keys Parameters: keys (tuple): of key strs to be combined in order to form key Returns: Serder: None: if no entry at keys Usage: Use walrus operator to catch and raise missing entry if (srder := mydb.get(keys)) is None: raise ExceptionHere use srdr here """ val = self.db.getVal(db=self.sdb, key=self._tokey(keys)) return self.klas(raw=bytes(val)) if val is not None else None ```