KERI Core API
keri.core.coring
keri.core.coring module
- class keri.core.coring.BextCodex(StrB64_L0: str = '4A', StrB64_L1: str = '5A', StrB64_L2: str = '6A', StrB64_Big_L0: str = '7AAA', StrB64_Big_L1: str = '8AAA', StrB64_Big_L2: str = '9AAA')[source]
BextCodex is codex of all variable sized Base64 Text (Bext) derivation codes. Only provide defined codes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
- class keri.core.coring.Bexter(raw=None, qb64b=None, qb64=None, qb2=None, code='4A', bext=None, **kwa)[source]
Bexter is subclass of Matter, cryptographic material, for variable length strings that only contain Base64 URL safe characters, i.e. Base64 text (bext). When created using the ‘bext’ paramaeter, the encoded matter in qb64 format in the text domain is more compact than would be the case if the string were passed in as raw bytes. The text is used as is to form the value part of the qb64 version not including the leader.
Due to ambiguity that arises from pre-padding bext whose length is a multiple of three with one or more ‘A’ chars. Any bext that starts with an ‘A’ and whose length is either a multiple of 3 or 4 may not round trip. Bext with a leading ‘A’ whose length is a multiple of four may have the leading ‘A’ stripped when round tripping.
Bexter(bext=’ABBB’).bext == ‘BBB’ Bexter(bext=’BBB’).bext == ‘BBB’ Bexter(bext=’ABBB’).qb64 == ‘4AABABBB’ == Bexter(bext=’BBB’).qb64
To avoid this problem, only use for applications of base 64 strings that never start with ‘A’
Examples: base64 text strings:
bext = “” qb64 = ‘4AAA’
bext = “-” qb64 = ‘6AABAAA-’
bext = “-A” qb64 = ‘5AABAA-A’
bext = “-A-” qb64 = ‘4AABA-A-’
bext = “-A-B” qb64 = ‘4AAB-A-B’
- Example uses:
CESR encoded paths for nested SADs and SAIDs CESR encoded fractionally weighted threshold expressions
Attributes:
Inherited Properties: (See Matter)
- Properties:
.bext is the Base64 text value, .qb64 with text code and leader removed.
Inherited Hidden Properties: (See Matter)
- ._rawify(self, bext)
- Codes:
StrB64_L0: str = ‘4A’ # String Base64 Only Leader Size 0 StrB64_L1: str = ‘5A’ # String Base64 Only Leader Size 1 StrB64_L2: str = ‘6A’ # String Base64 Only Leader Size 2 StrB64_Big_L0: str = ‘7AAA’ # String Base64 Only Big Leader Size 0 StrB64_Big_L1: str = ‘8AAA’ # String Base64 Only Big Leader Size 1 StrB64_Big_L2: str = ‘9AAA’ # String Base64 Only Big Leader Size 2
- __init__(raw=None, qb64b=None, qb64=None, qb2=None, code='4A', bext=None, **kwa)[source]
- Inherited Parameters: (see Matter)
raw is bytes of unqualified crypto material usable for crypto operations qb64b is bytes of fully qualified crypto material qb64 is str or bytes of fully qualified crypto material qb2 is bytes of fully qualified crypto material code is str of derivation code index is int of count of attached receipts for CryCntDex codes
- Parameters:
string (bext is the variable sized Base64 text)
- property bext
Base64 text value portion of qualified b64 str Returns the value portion of .qb64 with text code and leader removed
- Type:
Property bext
- class keri.core.coring.Cigar(verfer=None, **kwa)[source]
- Cigar is Matter subclass holding a nonindexed signature with verfer property.
From Matter .raw is signature and .code is signature cipher suite
- Adds .verfer property to hold Verfer instance of associated verifier public key
Verfer’s .raw as verifier key and .code is verifier cipher suite.
See Matter for inherited attributes and properties:
Attributes:
- Properties: (Inherited)
.code is str derivation code to indicate cypher suite .size is size (int): number of quadlets when variable sized material besides
full derivation code else None
.raw is bytes crypto material only without code .qb64 is str in Base64 fully qualified with derivation code + crypto mat .qb64b is bytes in Base64 fully qualified with derivation code + crypto mat .qb2 is bytes in binary with derivation code + crypto material .transferable is Boolean, True when transferable derivation code False otherwise .digestive is Boolean, True when digest derivation code False otherwise
- Properties:
.verfer is verfer of public key used to verify signature
- Hidden:
._code is str value for .code property ._size is int value for .size property ._raw is bytes value for .raw property ._infil is method to compute fully qualified Base64 from .raw and .code ._exfil is method to extract .code and .raw from fully qualified Base64
Methods:
- Hidden:
._pad is method to compute .pad property ._code is str value for .code property ._raw is bytes value for .raw property ._index is int value for .index property ._infil is method to compute fully qualified Base64 from .raw and .code ._exfil is method to extract .code and .raw from fully qualified Base64
- property verfer
Property verfer: Returns Verfer instance Assumes ._verfer is correctly assigned
- class keri.core.coring.Dater(raw=None, qb64b=None, qb64=None, qb2=None, code='1AAG', dts=None, **kwa)[source]
Dater is subclass of Matter, cryptographic material, for RFC-3339 profile of ISO-8601 formatted datetimes.
Dater provides a custom Base64 coding of an ASCII RFC-3339 profile of an ISO-8601 datetime by replacing (using translate) the three non-Base64 characters, ‘:.+’ with the Base64 equivalents, ‘cdp’ respectively.
Dater provides a more compact representation than would be obtained by converting the raw ASCII RFC-3339 profile ISO-8601 datetime to Base64. Dater supports datetimes as attached crypto material in replay of events for the datetime of when the event was first seen. The datetime textual representation is restricted to a specific 32 byte variant (profile) of ISO-8601 datetime with microseconds and UTC offset in HH:MM (See RFC-3339). Uses default initialization derivation code = MtrDex.DateTime. Raises error on init if code not MtrDex.DateTime
Examples: given RFC-3339 profiles of ISO-8601 datetime strings:
‘2020-08-22T17:50:09.988921+00:00’ ‘2020-08-22T17:50:09.988921-01:00’
The fully encoded qualified Base64, .qb64 versions are respectively
‘1AAG2020-08-22T17c50c09d988921p00c00’ ‘1AAG2020-08-22T17c50c09d988921-01c00’
The qualified binary version, .qb2 is the Base64 decoding the qualified Base64, qb64, ‘1AAG2020-08-22T17c50c09d988921p00c00’
The raw binary of the fully encoded version is the Base64 decoding of the the datetime only portion, ‘2020-08-22T17c50c09d988921p00c00’
Use the properties to get the different representations .dts is ASCII RFC-3339 of ISO-8601 .qb64 is qualified Base64 encoding with derivation code proem and ‘:.+’
replaced with ‘cdp’
.qb2 is qualified binary decoding of the .qb64 .code is text CESR derivation code .raw is binary version of the converted datetime only portion of .qb64
Example uses: attached first seen couples with fn+dt
Attributes:
- Inherited Properties: (See Matter)
.pad is int number of pad chars given raw .code is str derivation code to indicate cypher suite .raw is bytes crypto material only without code .index is int count of attached crypto material by context (receipts) .qb64 is str in Base64 fully qualified with derivation code + crypto mat .qb64b is bytes in Base64 fully qualified with derivation code + crypto mat .qb2 is bytes in binary with derivation code + crypto material .transferable is Boolean, True when transferable derivation code False otherwise
- Properties:
.dts is the ISO-8601 datetime string
- Hidden:
._pad is method to compute .pad property ._code is str value for .code property ._raw is bytes value for .raw property ._index is int value for .index property ._infil is method to compute fully qualified Base64 from .raw and .code ._exfil is method to extract .code and .raw from fully qualified Base64
Methods:
- __init__(raw=None, qb64b=None, qb64=None, qb2=None, code='1AAG', dts=None, **kwa)[source]
- Inherited Parameters: (see Matter)
raw is bytes of unqualified crypto material usable for crypto operations qb64b is bytes of fully qualified crypto material qb64 is str or bytes of fully qualified crypto material qb2 is bytes of fully qualified crypto material code is str of derivation code index is int of count of attached receipts for CryCntDex codes
- Parameters:
bytes (dts is the ISO-8601 datetime as str or)
- property datetime
Property datetime: Returns datetime.datetime instance converted from .dts
- property dts
date-time-stamp str Returns .qb64 translated to RFC-3339 profile of ISO 8601 datetime str
- Type:
Property dts
- property dtsb
date-time-stamp bytes Returns .qb64 translated to RFC-3339 profile of ISO 8601 datetime bytes
- Type:
Property dtsb
- class keri.core.coring.DecimalCodex(Decimal_L0: str = '4H', Decimal_L1: str = '5H', Decimal_L2: str = '6H', Decimal_Big_L0: str = '7AAH', Decimal_Big_L1: str = '8AAH', Decimal_Big_L2: str = '9AAH')[source]
DecimalCodex is codex of all variable sized Base64 String representation of decimal numbers both signed and unsigned, float and int. Only provide defined codes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
- class keri.core.coring.Decimer(raw=None, qb64b=None, qb64=None, qb2=None, code='4H', dns=None, decimal=None, **kwa)[source]
Decimer is subclass of Matter, for variable length decimal number strings (dns) that are translated to Base64 and converted in Base2 raw for compactness. Decimer encoded decimal number strings only contain Base64 URL safe characters that map to decimal number strings that can be converted to decimal numbers. These strings support signed and unsigned, int and float. The numeric value can be retrieved with the .decimal property.
When created using the dns parameter, the encoded matter in qb64 format in the text domain is more compact than would be the case if the string were Base64 encoded from a utf-8 decimal string.
Example
Decimer(dns=’-5.6’).qb64 == ‘BBB’ Decimer(dns=’-5.6’).raw == ‘BBB’ Decimer(dns=’-5.6’).dns == ‘-5.6’ Decimer(dns=’-5.6’).decimal == -5.6 Decimer(decimal=-5.6).dns = ‘-5.6’
Attributes: (See Matter)
Inherited Properties: (See Matter)
- Properties:
.dns (str): decimal number string .decimal (int|float): decimal number
Inherited Hidden Properties: (See Matter)
- ._rawify(self, dns)
- Codes: (See DecimalCodex or DecDex)
Decimal_L0: str = ‘4H’ # Decimal B64 string float and int lead size 0 Decimal_L1: str = ‘5H’ # Decimal B64string float and int lead size 1 Decimal_L2: str = ‘6H’ # Decimal B64string float and intlead size 2 Decimal_Big_L0: str = ‘7AAH’ # Decimal B64string float and int big lead size 0 Decimal_Big_L1: str = ‘8AAH’ # Decimal B64string float and int big lead size 1 Decimal_Big_L2: str = ‘9AAH’ # Decimal B64string float and int big lead size 2
- __init__(raw=None, qb64b=None, qb64=None, qb2=None, code='4H', dns=None, decimal=None, **kwa)[source]
- Inherited Parameters: (see Matter)
raw is bytes of unqualified crypto material usable for crypto operations qb64b is bytes of fully qualified crypto material qb64 is str or bytes of fully qualified crypto material qb2 is bytes of fully qualified crypto material code is str of derivation code index is int of count of attached receipts for CryCntDex codes
- Parameters:
dns (str|bytes) – decimal number string
decimal (int|float) – decimal number
- property decimal
raw as int or float
- Returns:
.raw converted to int or float as appropriate
- Return type:
decimal (int|float)
- Type:
Property decimal
- property dns
Returns decoded raw as dns
- Returns:
decoded raw decimal number string
- Return type:
dns (str)
- class keri.core.coring.Dicter(raw=b'', pad=None, dicter=None, label='i')[source]
Dicter class is base class for objects that can be stored in a Suber
Dicter classes can be initialized by a dict and then expose bytes of JSON in the .raw property Subclasses can add semantically appropriate properties that extract / add specific keys to the underlying dict .pad
- __init__(raw=b'', pad=None, dicter=None, label='i')[source]
Create Dicter from either raw bytes, pad dict, or other dicter instance
- Parameters:
raw (bytes) – raw JSON of dicter class
pad (dict) – data dict for class:
dicter (Dicter) – dicter instance to clone
label (str) – field name of the SAID field.
- property pad
pad property getter
- pretty(*, size=1024)[source]
Returns str JSON of .ked with pretty formatting
ToDo: add default size limit on pretty when used for syslog UDP MCU like 1024 for ogler.logger
- property raw
raw property getter
- property rid
ID of dict data as str
- class keri.core.coring.DigCodex(Blake3_256: str = 'E', Blake2b_256: str = 'F', Blake2s_256: str = 'G', SHA3_256: str = 'H', SHA2_256: str = 'I', Blake3_512: str = '0D', Blake2b_512: str = '0E', SHA3_512: str = '0F', SHA2_512: str = '0G')[source]
DigCodex is codex all digest derivation codes. This is needed to ensure delegated inception using a self-addressing derivation i.e. digest derivation code. Only provide defined codes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
- class keri.core.coring.Diger(raw=None, code='E', ser=None, strict=True, **kwa)[source]
Diger is Matter subclass with method to verify digest of serialization
See Matter for inherited attributes and properties:
- compare()[source]
compares provide digest given ser to this digest of ser. enables digest agility of different digest algos to compare.
- __init__(raw=None, code='E', ser=None, strict=True, **kwa)[source]
Initialize attributes
- Inherited Parameters:
See Matter
- Parameters:
ser (bytes) – serialization from which raw is computed if not raw
strict (bool) –
True means enforce code must be in DigDex False means do not enfoce code in DigDex this allows
subclasses to enforce different codex
- compare(ser, dig=None, diger=None)[source]
- Returns True if dig and .qb64 or .qb64b match or
if both .raw and dig are valid digests of ser Otherwise returns False
- Parameters:
serialization (ser is bytes)
self (diger is Diger instance of digest of ser to compare with)
self
precedence (if both supplied dig takes)
- If both match then as optimization returns True and does not verify either
as digest of ser
- Else If both have same code but do not match then as optimization returns False
and does not verify if either is digest of ser
- Else recalcs both digests using each one’s code to verify they
they are both digests of ser regardless of matching codes.
- class keri.core.coring.Digestage(klas, size, length)
- klas
Alias for field number 0
- length
Alias for field number 2
- size
Alias for field number 1
- class keri.core.coring.IceMapDom[source]
Base class for frozen dataclasses (such as codexes) that support map syntax Adds support for dunder methods for map syntax dc[name]. Converts exceptions from attribute syntax to raise map syntax when using map syntax.
Enables frozen dataclass instances to use Mapping item syntax
- class keri.core.coring.Ilker(qb64b=None, qb64=None, qb2=None, tag='', ilk='', **kwa)[source]
Ilker is subclass of Tagger, cryptographic material, for formatted message types (ilks) in Base64. Leverages Tagger support compact special fixed size primitives with non-empty soft part and empty raw part.
Ilker provides a more compact representation than would be obtained by converting the raw ASCII representation to Base64.
Attributes:
- Inherited Properties: (See Tagger)
code (str): hard part of derivation code to indicate cypher suite hard (str): hard part of derivation code. alias for code soft (str): soft part of derivation code fs any.
Empty when ss = 0.
both (str): hard + soft parts of full text code size (int | None): Number of quadlets/triplets of chars/bytes including
lead bytes of variable sized material (fs = None). Converted value of the soft part (of len ss) of full derivation code.
Otherwise None when not variably sized (fs != None)
fullSize (int): full size of primitive raw (bytes): crypto material only. Not derivation code or lead bytes. qb64 (str): Base64 fully qualified with derivation code + crypto mat qb64b (bytes): Base64 fully qualified with derivation code + crypto mat qb2 (bytes): binary with derivation code + crypto material transferable (bool): True means transferable derivation code False otherwise digestive (bool): True means digest derivation code False otherwise prefixive (bool): True means identifier prefix derivation code False otherwise special (bool): True when soft is special raw is empty and fixed size composable (bool): True when .qb64b and .qb2 are 24 bit aligned and round trip tag (str): B64 primitive without prepad (strips prepad from soft)
- Properties:
ilk (str): message type from Ilks of Ilkage
- Inherited Hidden: (See Tagger)
_code (str): value for .code property _soft (str): soft value of full code _raw (bytes): value for .raw property _rawSize(): _leadSize(): _special(): _infil(): creates qb64b from .raw and .code (fully qualified Base64) _binfil(): creates qb2 from .raw and .code (fully qualified Base2) _exfil(): extracts .code and .raw from qb64b (fully qualified Base64) _bexfil(): extracts .code and .raw from qb2 (fully qualified Base2)
Hidden:
Methods:
- __init__(qb64b=None, qb64=None, qb2=None, tag='', ilk='', **kwa)[source]
- Inherited Parameters: (see Tagger)
- raw (bytes | bytearray | None): unqualified crypto material usable
for crypto operations.
code (str): stable (hard) part of derivation code soft (str | bytes): soft part for special codes rize (int | None): raw size in bytes when variable sized material not
including lead bytes if any Otherwise None
qb64b (bytes | None): fully qualified crypto material Base64 qb64 (str | bytes | None): fully qualified crypto material Base64 qb2 (bytes | None): fully qualified crypto material Base2 strip (bool): True means strip (delete) matter from input stream
bytearray after parsing qb64b or qb2. False means do not strip
tag (str | bytes): Base64 plain. Prepad is added as needed.
- Parameters:
ilk (str) – message type from Ilks of Ilkage
- property ilk
- Returns:
B64 primitive without prepad (strips prepad from soft)
- Return type:
tag (str)
Alias for self.tag
- class keri.core.coring.LabelCodex(Empty: str = '1AAP', Tag1: str = '0J', Tag2: str = '0K', Tag3: str = 'X', Tag4: str = '1AAF', Tag5: str = '0L', Tag6: str = '0M', Tag7: str = 'Y', Tag8: str = '1AAN', Tag9: str = '0N', Tag10: str = '0O', Tag11: str = 'Z', StrB64_L0: str = '4A', StrB64_L1: str = '5A', StrB64_L2: str = '6A', StrB64_Big_L0: str = '7AAA', StrB64_Big_L1: str = '8AAA', StrB64_Big_L2: str = '9AAA', Label1: str = 'V', Label2: str = 'W', Bytes_L0: str = '4B', Bytes_L1: str = '5B', Bytes_L2: str = '6B', Bytes_Big_L0: str = '7AAB', Bytes_Big_L1: str = '8AAB', Bytes_Big_L2: str = '9AAB')[source]
LabelCodex is codex of codes to compactly ser/des labels and string values in maps or lists.
Only provide defined codes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
- class keri.core.coring.Labeler(label=None, text=None, raw=None, code=None, soft=None, **kwa)[source]
Labeler is subclass of Matter for CESR native field map labels and/or generic textual field values. Labeler auto sizes the instance code to minimize the total encoded size of associated field label or textual field value.
Attributes:
- Inherited Properties:
(See Matter)
- Properties:
label (str): base value without encoding
- Inherited Hidden:
(See Matter)
Hidden:
Methods:
- __init__(label=None, text=None, raw=None, code=None, soft=None, **kwa)[source]
- Inherited Parameters:
(see Matter)
- Parameters:
label (str|bytes) – base value before encoding as label A valid label must match rules for attribute name
text (str|bytes) – base value for encoding as text, Can be any str or bytes
- property label
Extracts and returns label from .code and .soft or .code and .raw
- Returns:
- base value without encoding. Must match rules for
attribute name
- Return type:
label (str)
- property text
Extracts and returns text from .code and .soft or .code and .raw
- Returns:
base value without encoding
- Return type:
text (str)
- class keri.core.coring.LargeVarRawSizeCodex(Lead0_Big: str = '7', Lead1_Big: str = '8', Lead2_Big: str = '9')[source]
LargeVarRawSizeCodex is codex all selector characters for the three large variable raw size tables that act as one table but with different leader byte sizes.
Only provide defined codes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
- class keri.core.coring.MapDom[source]
Base class for mutable dataclasses that support map syntax Adds support for dunder methods for map syntax dc[name]. Converts exceptions from attribute syntax to raise map syntax when using map syntax.
Enables dataclass instances to use Mapping item syntax
- class keri.core.coring.Matter(raw=None, code='B', soft='', rize=None, qb64b=None, qb64=None, qb2=None, strip=False, **kwa)[source]
Matter is fully qualified cryptographic material primitive base class for non-indexed primitives.
Sub classes are derivation code and key event element context specific.
Includes the following attributes and properties:
- Class Attributes:
Codex (MatterCodex): MtrDex Hards (dict): hard sizes keyed by qb64 selector Bards (dict): hard size keyed by qb2 selector Sizes (dict): sizes tables for codes Codes (dict): maps code name to code Names (dict): maps code to code name Pad (str): B64 pad char for xtra size pre-padded soft values
Class Methods:
Attributes:
- Properties:
code (str): hard part of derivation code to indicate cypher suite hard (str): hard part of derivation code. alias for code soft (str | bytes): soft part of full code exclusive of xs xtra prepad.
Empty when ss = 0.
both (str): hard + soft parts of full text code size (int | None): Number of quadlets/triplets of chars/bytes including
lead bytes of variable sized material (fs = None). Converted value of the soft part (of len ss) of full derivation code.
Otherwise None when not variably sized (fs != None)
fullSize (int): full size of primitive raw (bytes): crypto material only. Not derivation code or lead bytes. qb64 (str): Base64 fully qualified with derivation code + crypto mat qb64b (bytes): Base64 fully qualified with derivation code + crypto mat qb2 (bytes): binary with derivation code + crypto material transferable (bool): True means transferable derivation code False otherwise digestive (bool): True means digest derivation code False otherwise prefixive (bool): True means identifier prefix derivation code False otherwise special (bool): True when soft is special raw is empty and fixed size composable (bool): True when .qb64b and .qb2 are 24 bit aligned and round trip
- Hidden:
_code (str): value for .code property _soft (str): soft value of full code _raw (bytes): value for .raw property _rawSize(): _fullSize(): _leadSize(): _special(): _infil(): creates qb64b from .raw and .code (fully qualified Base64) _binfil(): creates qb2 from .raw and .code (fully qualified Base2) _exfil(): extracts .code and .raw from qb64b (fully qualified Base64) _bexfil(): extracts .code and .raw from qb2 (fully qualified Base2)
Special soft values are indicated when fn in table is None and ss > 0.
- __init__(raw=None, code='B', soft='', rize=None, qb64b=None, qb64=None, qb2=None, strip=False, **kwa)[source]
Validate as fully qualified :param raw: unqualified crypto material usable
for crypto operations.
- Parameters:
code (str) – stable (hard) part of derivation code
soft (str | bytes) – soft part exclusive of prepad for special codes
rize (int | None) – raw size in bytes when variable sized material not including lead bytes if any Otherwise None
qb64b (str | bytes | bytearray | memoryview | None) – fully qualified crypto material Base64. When str, encodes as utf-8. Strips when bytearray and strip is True.
qb64 (str | bytes | bytearray | memoryview | None) – fully qualified crypto material Base64. When str, encodes as utf-8. Ignores strip
qb2 (bytes | bytearray | memoryview | None) – fully qualified crypto material Base2. Strips when bytearray and strip is True.
strip (bool) – True means strip (delete) matter from input stream bytearray after parsing qb64b or qb2. False means do not strip
- Needs either (raw and code and optionally rsize)
or qb64b or qb64 or qb2
Otherwise raises EmptyMaterialError When raw and code and optional rsize provided
then validate that code is correct for length of raw, rsize, computed size from Sizes and assign .raw
- Else when qb64b or qb64 or qb2 provided extract and assign
.raw and .code and .size and .rsize
- property both
Returns: both (str): hard + soft parts of full text code
- property code
- Returns:
hard part only of full text code.
- Return type:
code (str)
Getter for ._code. Makes ._code read only
Some codes only have a hard part. Soft part may be for variable sized matter or for special codes that are code only (raw is empty)
- property composable
True when both .qb64b and .qb2 are 24 bit aligned and round trip using encodeB64 and decodeB64. False otherwise
- Type:
composable (bool)
- property digestive
Property digestable: Returns True if identifier has digest derivation code,
False otherwise
- property fullSize
Full size of primitive for both fixed and variable size primitives
- Returns:
full size of primitive in bytes
- Return type:
fullsize (int)
Fixed size codes returns fs from .Sizes Variable size codes where fs==None computes fs from .size and sizes
- property hard
Returns: hard (str): hard part only of full text code. Alias for .code.
- property name
Returns: name (str): code name for self.code. Used for annotation for primitives like Matter
- property prefixive
Property prefixive: Returns True if identifier has prefix derivation code,
False otherwise
- property qb2
Property qb2: Returns Fully Qualified Binary Version Bytes
- property qb64
Property qb64: Returns Fully Qualified Base64 Version Assumes self.raw and self.code are correctly populated
- property qb64b
Property qb64b: Returns Fully Qualified Base64 Version encoded as bytes Assumes self.raw and self.code are correctly populated
- property raw
Returns ._raw Makes .raw read only
- property size
- Returns:
- Number of variably sized b64 quadlets/b2 triplets
in primitive when varibly sized
None when not variably sized when (fs!=None)
- Return type:
size(int | None)
Number of quadlets/triplets of chars/bytes of variable sized material or None when not variably sized.
Converted qb64 value to int of soft ss portion of full text code when variably sized primitive material (fs == None).
- property soft
- Returns:
soft part only of full text code.
- Return type:
soft (str)
Getter for ._soft. Make ._soft read only
- property special
- True when self.code has special self.soft i.e. when
fs is not None and ss > 0 and fs = hs + ss and ls = 0 i.e. (fs fixed and soft not empty and raw is empty and no lead)
False otherwise
- Type:
special (bool)
- property transferable
Property transferable: Returns True if identifier does not have non-transferable derivation code,
False otherwise
- class keri.core.coring.MatterCodex(Ed25519_Seed: str = 'A', Ed25519N: str = 'B', X25519: str = 'C', Ed25519: str = 'D', Blake3_256: str = 'E', Blake2b_256: str = 'F', Blake2s_256: str = 'G', SHA3_256: str = 'H', SHA2_256: str = 'I', ECDSA_256k1_Seed: str = 'J', Ed448_Seed: str = 'K', X448: str = 'L', Short: str = 'M', Big: str = 'N', X25519_Private: str = 'O', X25519_Cipher_Seed: str = 'P', ECDSA_256r1_Seed: str = 'Q', Tall: str = 'R', Large: str = 'S', Great: str = 'T', Vast: str = 'U', Label1: str = 'V', Label2: str = 'W', Tag3: str = 'X', Tag7: str = 'Y', Tag11: str = 'Z', Salt_256: str = 'a', Salt_128: str = '0A', Ed25519_Sig: str = '0B', ECDSA_256k1_Sig: str = '0C', Blake3_512: str = '0D', Blake2b_512: str = '0E', SHA3_512: str = '0F', SHA2_512: str = '0G', Long: str = '0H', ECDSA_256r1_Sig: str = '0I', Tag1: str = '0J', Tag2: str = '0K', Tag5: str = '0L', Tag6: str = '0M', Tag9: str = '0N', Tag10: str = '0O', GramHeadNeck: str = '0P', GramHead: str = '0Q', GramHeadAIDNeck: str = '0R', GramHeadAID: str = '0S', ECDSA_256k1N: str = '1AAA', ECDSA_256k1: str = '1AAB', Ed448N: str = '1AAC', Ed448: str = '1AAD', Ed448_Sig: str = '1AAE', Tag4: str = '1AAF', DateTime: str = '1AAG', X25519_Cipher_Salt: str = '1AAH', ECDSA_256r1N: str = '1AAI', ECDSA_256r1: str = '1AAJ', Null: str = '1AAK', No: str = '1AAL', Yes: str = '1AAM', Tag8: str = '1AAN', Escape: str = '1AAO', Empty: str = '1AAP', TBD0S: str = '1__-', TBD0: str = '1___', TBD1S: str = '2__-', TBD1: str = '2___', TBD2S: str = '3__-', TBD2: str = '3___', StrB64_L0: str = '4A', StrB64_L1: str = '5A', StrB64_L2: str = '6A', StrB64_Big_L0: str = '7AAA', StrB64_Big_L1: str = '8AAA', StrB64_Big_L2: str = '9AAA', Bytes_L0: str = '4B', Bytes_L1: str = '5B', Bytes_L2: str = '6B', Bytes_Big_L0: str = '7AAB', Bytes_Big_L1: str = '8AAB', Bytes_Big_L2: str = '9AAB', X25519_Cipher_L0: str = '4C', X25519_Cipher_L1: str = '5C', X25519_Cipher_L2: str = '6C', X25519_Cipher_Big_L0: str = '7AAC', X25519_Cipher_Big_L1: str = '8AAC', X25519_Cipher_Big_L2: str = '9AAC', X25519_Cipher_QB64_L0: str = '4D', X25519_Cipher_QB64_L1: str = '5D', X25519_Cipher_QB64_L2: str = '6D', X25519_Cipher_QB64_Big_L0: str = '7AAD', X25519_Cipher_QB64_Big_L1: str = '8AAD', X25519_Cipher_QB64_Big_L2: str = '9AAD', X25519_Cipher_QB2_L0: str = '4E', X25519_Cipher_QB2_L1: str = '5E', X25519_Cipher_QB2_L2: str = '6E', X25519_Cipher_QB2_Big_L0: str = '7AAE', X25519_Cipher_QB2_Big_L1: str = '8AAE', X25519_Cipher_QB2_Big_L2: str = '9AAE', HPKEBase_Cipher_L0: str = '4F', HPKEBase_Cipher_L1: str = '5F', HPKEBase_Cipher_L2: str = '6F', HPKEBase_Cipher_Big_L0: str = '7AAF', HPKEBase_Cipher_Big_L1: str = '8AAF', HPKEBase_Cipher_Big_L2: str = '9AAF', Decimal_L0: str = '4H', Decimal_L1: str = '5H', Decimal_L2: str = '6H', Decimal_Big_L0: str = '7AAH', Decimal_Big_L1: str = '8AAH', Decimal_Big_L2: str = '9AAH')[source]
MatterCodex is codex code (stable) part of all matter derivation codes. Only provide defined codes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
- class keri.core.coring.NonTransCodex(Ed25519N: str = 'B', ECDSA_256k1N: str = '1AAA', Ed448N: str = '1AAC', ECDSA_256r1N: str = '1AAI')[source]
NonTransCodex is codex all non-transferable derivation codes Only provide defined codes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
- class keri.core.coring.NonceCodex(Empty: str = '1AAP', Salt_128: str = '0A', Salt_256: str = 'a', Blake3_256: str = 'E', Blake2b_256: str = 'F', Blake2s_256: str = 'G', SHA3_256: str = 'H', SHA2_256: str = 'I', Blake3_512: str = '0D', Blake2b_512: str = '0E', SHA3_512: str = '0F', SHA2_512: str = '0G')[source]
NonceCodex is codex all derivation codes for salty nonces (UUIDs) either as random numbers or as digests deterministically derived from salty nonces.
Only provide defined codes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
- class keri.core.coring.Noncer(raw=None, code='0A', qb64b=None, nonce=None, **kwa)[source]
Noncer is Diger subclass for UUIDs as salty nonces or UUIDs as digest deterministically derived from salty nonces
Attributes:
Inherited Properties: (see Diger)
- Properties:
- nonce (str): round trippable nonce value that is empty string when nonce
is empty. Otherwise qb64 of nonce.
- nonceb (bytes): round trippable nonce value that is empty string when nonce
is empty. Otherwise qb64 of nonce.
Methods:
Hidden:
- __init__(raw=None, code='0A', qb64b=None, nonce=None, **kwa)[source]
Checks for .code in NonceDex so valid noncive code
Inherited Parameters: (see Diger)
- Parameters:
nonce (str|bytes|None) – round trippable nonce value with nonce property that accounts for empty nonce indicated by empty string. Otherwise nonce is qb64 of nonce value
- property nonce
Property nonce: :returns:
- Either empty str when Nonce is NonceDex.Empty or
qb64 of nonce primitive otherwise
- Return type:
nonce (str)
- property nonceb
Property nonceb: :returns:
- Either empty bytes when Nonce is NonceDex.Empty or
qb64b of nonce primitive otherwise
- Return type:
nonce (bytes)
- class keri.core.coring.NumCodex(Short: str = 'M', Long: str = '0H', Tall: str = 'R', Big: str = 'N', Large: str = 'S', Great: str = 'T', Huge: str = '0A', Vast: str = 'U')[source]
NumCodex is codex of Base64 derivation codes for compactly representing numbers across a wide rage of sizes.
Only provide defined codes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
- class keri.core.coring.Number(raw=None, qb64b=None, qb64=None, qb2=None, code=None, num=None, numh=None, sn=None, snh=None, **kwa)[source]
Number is subclass of Matter, cryptographic material, for ordinal counting whole numbers (non-negative integers) up to a maximum size of 16 bytes, 256 ** 16 - 1. Examples uses are sequence numbers or first seen ordering numbers or thresholds. Seqner provides fully qualified format for ordinals (sequence numbers etc) when provided as attached cryptographic material elements.
Useful when parsing attached receipt groupings with sn from stream or database
Uses default initialization code = CryTwoDex.Salt_128 Raises error on init if code not CryTwoDex.Salt_128
Attributes:
- Inherited Properties: (See Matter)
code (str): hard part of derivation code to indicate cypher suite both (int): hard and soft parts of full text code size (int): Number of triplets of bytes including lead bytes
(quadlets of chars) of variable sized material. Value of soft size, ss, part of full text code. Otherwise None.
rize (int): number of bytes of raw material not including lead bytes raw (bytes): crypto material only without code qb64 (str): Base64 fully qualified with derivation code + crypto mat qb64b (bytes): Base64 fully qualified with derivation code + crypto mat qb2 (bytes): binary with derivation code + crypto material transferable (bool): True means transferable derivation code False otherwise digestive (bool): True means digest derivation code False otherwise
- Properties:
num (int): int representation of number humh (str): hex string representation of number with no leading zeros sn (int): alias for num snh (str): alias for numh huge (str): qb64 of num but with code NumDex.Huge so 24 char compatible
with fixed size seq num for lexicographic lmdb key space
- positive (bool): True if .num > 0, False otherwise. Because .num must be
non-negative, .positive == False means .num == 0
inceptive (bool): True means .num == 0 False otherwise.
- Hidden:
_code (str): value for .code property _raw (bytes): value for .raw property _rsize (bytes): value for .rsize property. Raw size in bytes when
variable sized material else None.
- _size (int): value for .size property. Number of triplets of bytes
including lead bytes (quadlets of chars) of variable sized material else None.
- _infil (types.MethodType): creates qb64b from .raw and .code
(fully qualified Base64)
- _exfil (types.MethodType): extracts .code and .raw from qb64b
(fully qualified Base64)
Methods:
- __init__(raw=None, qb64b=None, qb64=None, qb2=None, code=None, num=None, numh=None, sn=None, snh=None, **kwa)[source]
- Inherited Parameters: (see Matter)
raw (bytes): unqualified crypto material usable for crypto operations code (str | None): stable (hard) part of derivation code.
None means pick code based on value of num or numh otherwise raise error
rize (int): raw size in bytes when variable sized material else None qb64b (bytes): fully qualified crypto material Base64 qb64 (str, bytes): fully qualified crypto material Base64 qb2 (bytes): fully qualified crypto material Base2 strip (bool): True means strip (delete) matter from input stream bytearray after parsing qb64b or qb2. False means do not strip
- Parameters:
num (int | str | None) – non-negative int number or hex str of int number or 0 if None
numh (str) – hex string equivalent of non-negative int number
sn (int | str | None) – alias of num for backwards compat with Seqner
snh (str) – alias of numh for backwards compat with Seqner
Note: int(“0xab”, 16) is also valid since int recognizes 0x hex prefix
- property huge
Provides number value as qb64 but with code NumDex.huge. This is the same as Seqner.qb64. Raises error if too big.
- Returns:
qb64 of num coded as NumDex.Huge
- Return type:
huge (str)
- property inceptive
Returns True if .num == 0 False otherwise.
- property num
number as int Returns .raw converted to int
- Type:
Property num
- property numh
number as hex string no leading zeros Returns .num int converted to hex str
- Type:
Property numh
- property positive
Returns True if .num is strictly positive non-zero False otherwise. Because valid number .num must be non-negative, positive False also means that .num is zero.
- property sn
Sequence number, sn property getter to mimic Seqner interface :returns: alias for num :rtype: sn (int)
- property snh
Sequence number hex str, snh property getter to mimic Seqner interface :returns: alias for numh :rtype: snh (hex str)
- validate(inceptive=None)[source]
- Return type:
self (Number)
- Raises:
ValidationError – when .num is invalid ordinal such as sequence number or first seen number etc.
- Parameters:
inceptive (bool) – raise ValidationError whan .num invalid None means exception when .num < 0 True means exception when .num != 0 False means exception when .num < 1
- class keri.core.coring.Pather(raw=None, qb64b=None, qb64=None, qb2=None, code='4A', parts=None, path=None, relative=False, pathive=True, **kwa)[source]
Pather is Matter subclass that provides path and route functionality. It provides support for SAD Path language specific functionality. When path parts contain only Base64 characters not including ‘-’, the path will be compactly encoded with special path separator ‘-’ as a variable length StrBase64. Otherwise paths are encoded as variable length Bytes. Pather allows the specification of paths as a list of field parts which will be converted to the compact Base64 URL safe character representation when possible. Paths may be relative or absolute. A special, escape secquence is used to encode relative paths in Base64
Pather can traverse paths that maintain Base64 URL character safety by leveraging the fact that SADs must have static field ordering. Any field label can be replaced by its field ordinal to allow for path specification and traversal for any field labels that contain non-Base64 URL safe characters.
Inherited Properties and Attributes: (See Matter class)
- Properties:
- path (str): ‘/’ separated path. Absolute paths start with ‘/’.
Relative paths do not.
- parts (tuple): parts of path, absolute path has zeroth part as
empty string. Bare absolute path has zeroth and first part as empty strings.
- rparts (tuple): parts of path in relative form. No leading ‘/’ in
associated path
Examples
path = “AAAA” makes path = “/AAAA” path = “AAA/BBB” with relative == True path = “/@AA/BBB” with pathive == False
- __init__(raw=None, qb64b=None, qb64=None, qb2=None, code='4A', parts=None, path=None, relative=False, pathive=True, **kwa)[source]
- Inherited Parameters: (see Bexter)
raw is bytes of unqualified crypto material usable for crypto operations qb64b is bytes of fully qualified crypto material qb64 is str or bytes of fully qualified crypto material qb2 is bytes of fully qualified crypto material code is str of derivation code index is int of count of attached receipts for CryCntDex codes relative (bool): True means relative paths allowed
False means all paths are forced to be absolute
- pathive (bool): True means must satisfy valid pathed material path
False means must only satisfy valid route path
- Parameters:
parts (NonStringIterable) – of path parts
path (str|bytes|NonStringIterable) – as either ‘/’ delimited string or as NonStringIterable of path parts.
- property parts
Path as a tuple of path parts
- Returns:
- parts of path, absolute path has zeroth part as
empty string. Bare absolute path has zeroth and first part as empty strings.
- Return type:
parts (tuple)
- property path
Extracts and returns path from .code and .raw
- Returns:
- ‘/’ separated path. Absolute paths start with ‘/’.
Relative paths do not.
- Return type:
path (str)
- resolve(sad)[source]
Recurses thru sad dict following self.parts
- Parameters:
sad (dict or list) – the next component
- Returns:
Value at the end of the path
- root(root)[source]
Returns a new Pather anchored at new root
Returns a new Pather anchoring this path at the new root specified by root.
- property rparts
Path as a tuple of path parts but in relative form. Associate path would not have leading ‘/’
- Returns:
- parts of path in relative form. No leading ‘/’ in
associated path
- Return type:
rparts (tuple)
- startswith(pather)[source]
Returns True if pather.path text is the root of self.path text
- Parameters:
pather (Pather) – the path to check against self
- Returns:
True if pather is the root of self
- Return type:
bool
- strip(root)[source]
Returns a new Pather with root stipped off the front if it exists
Returns a new Pather with root stripped off the front
- tail(serder)[source]
Recurses thru value following .path and returns terminal value
Finds the value at this path and applies the version string rules of the serder to serialize the value at ptr.
- Parameters:
serder (Serder) – the versioned dict to in which to resolve .path
- Returns:
Value at the end of the path
- Return type:
bytes
- class keri.core.coring.PreCodex(Ed25519N: str = 'B', Ed25519: str = 'D', Blake3_256: str = 'E', Blake2b_256: str = 'F', Blake2s_256: str = 'G', SHA3_256: str = 'H', SHA2_256: str = 'I', Blake3_512: str = '0D', Blake2b_512: str = '0E', SHA3_512: str = '0F', SHA2_512: str = '0G', ECDSA_256k1N: str = '1AAA', ECDSA_256k1: str = '1AAB', Ed448N: str = '1AAC', Ed448: str = '1AAD', Ed448_Sig: str = '1AAE', ECDSA_256r1N: str = '1AAI', ECDSA_256r1: str = '1AAJ')[source]
PreCodex is codex all identifier prefix derivation codes. This is needed to verify valid inception events. Only provide defined codes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
- class keri.core.coring.PreNonDigCodex(Ed25519N: str = 'B', Ed25519: str = 'D', ECDSA_256k1N: str = '1AAA', ECDSA_256k1: str = '1AAB', Ed448N: str = '1AAC', Ed448: str = '1AAD', ECDSA_256r1N: str = '1AAI', ECDSA_256r1: str = '1AAJ')[source]
PreNonDigCodex is codex all prefixive but non-digestive derivation codes Only provide defined codes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
- class keri.core.coring.Prefixer(**kwa)[source]
Prefixer is Matter subclass for autonomic identifier AID prefix
Attributes:
Inherited Properties: (see Matter)
Properties:
Methods:
Hidden:
- class keri.core.coring.Sadder(raw=b'', ked=None, sad=None, kind=None, saidify=False, code='E')[source]
Sadder is self addressed data (SAD) serializer-deserializer class
Instance creation of a Sadder does not verifiy it .said property it merely extracts it. In order to ensure Sadder instance has a verified .said then must call .saider.verify(sad=self.ked)
Has the following public properties:
- Properties:
raw (bytes): of serialized event only ked (dict): self addressed data dict kind (str): serialization kind coring.Serials such as JSON, CBOR, MGPK, CESR size (int): number of bytes in serialization version (Versionage): protocol version (Major, Minor) proto (str): Protocolage value as protocol identifier such as KERI, ACDC label (str): Saidage value as said field label saider (Saider): of SAID of this SAD .ked[‘d’] if present said (str): SAID of .saider qb64 saidb (bytes): SAID of .saider qb64b pretty (str): Pretty JSON of this SAD
- Hidden Attributes:
._raw is bytes of serialized event only ._ked is key event dict ._kind is serialization kind string value (see namedtuple coring.Serials)
supported kinds are ‘json’, ‘cbor’, ‘msgpack’, ‘binary’
._size is int of number of bytes in serialed event only ._version is Versionage instance of event version ._proto (str): Protocolage value as protocol type identifier ._saider (Saider): instance for this Sadder’s SAID
Note
loads and jumps of json use str whereas cbor and msgpack use bytes
- __init__(raw=b'', ked=None, sad=None, kind=None, saidify=False, code='E')[source]
Deserialize if raw provided does not verify assumes embedded said is valid Serialize if ked provided but not raw verifies if verify is True? When serializing if kind provided then use kind instead of field in ked
- Parameters:
raw (bytes) – serialized event
None (kind is serialization kind string value or) – if None its deserialized from raw
None – supported kinds are ‘json’, ‘cbor’, ‘msgpack’, ‘binary’ if kind is None then its extracted from ked or raw
saidify (bool) – True means compute said for ked
.saider (code is .diger default digest code for computing said)
- compare(said=None)[source]
Returns True if said and either .saider.qb64 or .saider.qb64b match via string equality ==
Convenience method to allow comparison of own .saider digest self.raw with some other purported said of self.raw
- Parameters:
.said (said is qb64b or qb64 SAID of ser to compare with)
- property ked
ked property getter
- property kind
kind property getter
- pretty(*, size=1024)[source]
Returns str JSON of .ked with pretty formatting
ToDo: add default size limit on pretty when used for syslog UDP MCU like 1024 for ogler.logger
- property proto
proto property getter protocol identifier type value of Protocolage such as ‘KERI’ or ‘ACDC’
- Returns:
Protocolage value as protocol type
- Return type:
(str)
- property raw
raw property getter
- property said
Returns str qb64 of .ked[“d”] (said when ked is SAD) said (self-addressing identifier) property getter
- property saidb
Returns bytes qb64b of .ked[“d”] (said when ked is SAD) said (self-addressing identifier) property getter
- property saider
Returns Diger of digest of self.raw diger (digest material) property getter
- property size
size property getter
- property version
version property getter
- Return type:
(Versionage)
- class keri.core.coring.Saidage(dollar, at, id_, i, d)
- at
Alias for field number 1
- d
Alias for field number 4
- dollar
Alias for field number 0
- i
Alias for field number 3
- id_
Alias for field number 2
- class keri.core.coring.Saider(raw=None, *, code=None, sad=None, kind=None, label='d', ignore=None, **kwa)[source]
Saider is Matter subclass for self-addressing identifier prefix using derivation as determined by code from ked
- Properties: (inherited)
code (str): derivation code to indicate cypher suite size (int): number of quadlets when variable sized material besides
full derivation code else None
raw (bytes): crypto material only without code qb64 (str): Base64 fully qualified with derivation code + crypto mat qb64b (bytes): Base64 fully qualified with derivation code + crypto mat qb2 (bytes): binary with derivation code + crypto material transferable (bool): True means transferable derivation code False otherwise digestive (bool): True means digest derivation code False otherwise
- Hidden:
_code (str): value for .code property _size (int): value for .size property _raw (bytes): value for .raw property _infil (types.MethodType): creates qb64b from .raw and .code
(fully qualified Base64)
- _exfil (types.MethodType): extracts .code and .raw from qb64b
(fully qualified Base64)
_derive (types.MethodType): derives said (.qb64 ) _verify (types.MethodType): verifies said ((.qb64 ) against a given sad
- __init__(raw=None, *, code=None, sad=None, kind=None, label='d', ignore=None, **kwa)[source]
See Matter.__init__ for inherited parameters
- Parameters:
sad (dict) – self addressed data to serialize and inject said
kind (str) – serialization algorithm of sad, one of Serials used to override that given by ‘v’ field if any in sad otherwise default is Serials.json
label (str) – Saidage value as said field label
ignore (list) – fields to ignore when generating SAID
- derive(sad, code=None, **kwa)[source]
- Returns:
- (raw, sad) raw said as derived from serialized dict
and modified sad during derivation.
- Return type:
result (tuple)
- Parameters:
sad (dict) – self addressed data to be serialized
code (str) – digest type code from DigDex.
kind (str) – serialization algorithm of sad, one of Serials used to override that given by ‘v’ field if any in sad otherwise default is Serials.json
label (str) – Saidage value of said field labelin which to inject dummy
- classmethod saidify(sad: dict, *, code: str = 'E', kind: str = None, label: str = 'd', ignore: list = None, **kwa)[source]
Derives said from sad and injects it into copy of sad and said and injected sad
- Returns:
- of the form (saider, sad) where saider is Saider
instance generated from sad using code and sad is copy of parameter sad but with its label id field filled in with generated said from saider
- Return type:
result (tuple)
- Parameters:
sad (dict) – serializable dict
code (str) – digest type code from DigDex
kind (str) – serialization algorithm of sad, one of Serials used to override that given by ‘v’ field if any in sad otherwise default is Serials.json
label (str) – Saidage value as said field label in which to inject said
ignore (list) – fields to ignore when generating SAID
- verify(sad, *, prefixed=False, versioned=True, code=None, kind=None, label='d', ignore=None, **kwa)[source]
- Returns:
- True means derivation from sad with dummy label
field value replacement for ._code matches .qb64. False otherwise If prefixed is True then also validates that label field of provided sad also matches .qb64. False otherwise If versioned is True and provided sad includes version field ‘v’ then also validates that version field ‘v’ of provided sad matches the version field of modified sad that results from the derivation process. The size chars in the version field are set to the size of the sad during derivation. False otherwise.
- Return type:
result (bool)
- Parameters:
sad (dict) – self addressed data to be serialized
prefixed (bool) – True means also verify if labeled field in sad matches own .qb64
versioned (bool)
code (str) – digest type code from DigDex.
kind (str) – serialization algorithm of sad, one of Serials used to override that given by ‘v’ field if any in sad otherwise default is Serials.json
label (str) – Saidage value of said field label in which to inject dummy
ignore (list) – fields to ignore when generating SAID
- class keri.core.coring.Seqner(raw=None, qb64b=None, qb64=None, qb2=None, code='0A', sn=None, snh=None, **kwa)[source]
Seqner is subclass of Matter, cryptographic material, for fully qualified fixed serialization sized ordinal numbers such as sequence numbers or first seen numbers.
The serialization is forced to a fixed size (single code) so that it may be used for lexocographically ordered namespaces such as database indices. That code is MtrDex.Salt_128
Default initialization code = MtrDex.Salt_128 Raises error on init if code is not MtrDex.Salt_128
Attributes:
- Inherited Properties: (See Matter)
.pad is int number of pad chars given raw .code is str derivation code to indicate cypher suite .raw is bytes crypto material only without code .index is int count of attached crypto material by context (receipts) .qb64 is str in Base64 fully qualified with derivation code + crypto mat .qb64b is bytes in Base64 fully qualified with derivation code + crypto mat .qb2 is bytes in binary with derivation code + crypto material .transferable is Boolean, True when transferable derivation code False otherwise
- Properties:
.sn is int sequence number .snh is hex string representation of sequence number no leading zeros
- Hidden:
._pad is method to compute .pad property ._code is str value for .code property ._raw is bytes value for .raw property ._index is int value for .index property ._infil is method to compute fully qualified Base64 from .raw and .code ._exfil is method to extract .code and .raw from fully qualified Base64
Methods:
- __init__(raw=None, qb64b=None, qb64=None, qb2=None, code='0A', sn=None, snh=None, **kwa)[source]
- Inherited Parameters: (see Matter)
raw is bytes of unqualified crypto material usable for crypto operations qb64b is bytes of fully qualified crypto material qb64 is str or bytes of fully qualified crypto material qb2 is bytes of fully qualified crypto material code is str of derivation code index is int of count of attached receipts for CryCntDex codes
- Parameters:
sn (int | str | None) – some form of ordinal number int or hex str
snh (str | None) – hex string of ordinal number
- property sn
sequence number as int Returns .raw converted to int
- Type:
Property sn
- property snh
sequence number as hex Returns .sn int converted to hex str
- Type:
Property snh
- class keri.core.coring.Sizage(hs, ss, xs, fs, ls)
- fs
Alias for field number 3
- hs
Alias for field number 0
- ls
Alias for field number 4
- ss
Alias for field number 1
- xs
Alias for field number 2
- class keri.core.coring.SmallVarRawSizeCodex(Lead0: str = '4', Lead1: str = '5', Lead2: str = '6')[source]
SmallVarRawSizeCodex is codex all selector characters for the three small variable raw size tables that act as one table but with different leader byte sizes.
Only provide defined codes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
- class keri.core.coring.TagCodex(Tag1: str = '0J', Tag2: str = '0K', Tag3: str = 'X', Tag4: str = '1AAF', Tag5: str = '0L', Tag6: str = '0M', Tag7: str = 'Y', Tag8: str = '1AAN', Tag9: str = '0N', Tag10: str = '0O', Tag11: str = 'Z')[source]
TagCodex is codex of Base64 derivation codes for compactly representing various small Base64 tag values as special code soft part values.
Only provide defined codes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
- class keri.core.coring.Tagger(tag='', soft='', code=None, **kwa)[source]
Tagger is subclass of Matter, cryptographic material, for compact special fixed size primitive with non-empty soft part and empty raw part.
Tagger provides a more compact representation of small Base64 values in as soft part of code rather than would be obtained by by using a small raw part whose ASCII representation is converted to Base64.
Attributes:
- Inherited Properties: (See Matter)
code (str): hard part of derivation code to indicate cypher suite hard (str): hard part of derivation code. alias for code soft (str): soft part of derivation code fs any.
Empty when ss = 0.
both (str): hard + soft parts of full text code size (int | None): Number of quadlets/triplets of chars/bytes including
lead bytes of variable sized material (fs = None). Converted value of the soft part (of len ss) of full derivation code.
Otherwise None when not variably sized (fs != None)
fullSize (int): full size of primitive raw (bytes): crypto material only. Not derivation code or lead bytes. qb64 (str): Base64 fully qualified with derivation code + crypto mat qb64b (bytes): Base64 fully qualified with derivation code + crypto mat qb2 (bytes): binary with derivation code + crypto material transferable (bool): True means transferable derivation code False otherwise digestive (bool): True means digest derivation code False otherwise prefixive (bool): True means identifier prefix derivation code False otherwise special (bool): True when soft is special raw is empty and fixed size composable (bool): True when .qb64b and .qb2 are 24 bit aligned and round trip
- Properties:
tag (str): B64 .soft portion of code but without prepad
- Inherited Hidden: (See Matter)
_code (str): value for .code property _soft (str): soft value of full code _raw (bytes): value for .raw property _rawSize(): _leadSize(): _special(): _infil(): creates qb64b from .raw and .code (fully qualified Base64) _binfil(): creates qb2 from .raw and .code (fully qualified Base2) _exfil(): extracts .code and .raw from qb64b (fully qualified Base64) _bexfil(): extracts .code and .raw from qb2 (fully qualified Base2)
Hidden:
Methods:
- __init__(tag='', soft='', code=None, **kwa)[source]
- Inherited Parameters: (see Matter)
- raw (bytes | bytearray | None): unqualified crypto material usable
for crypto operations.
code (str): stable (hard) part of derivation code soft (str | bytes): soft part for special codes rize (int | None): raw size in bytes when variable sized material not
including lead bytes if any Otherwise None
qb64b (bytes | None): fully qualified crypto material Base64 qb64 (str | bytes | None): fully qualified crypto material Base64 qb2 (bytes | None): fully qualified crypto material Base2 strip (bool): True means strip (delete) matter from input stream
bytearray after parsing qb64b or qb2. False means do not strip
- Parameters:
tag (str | bytes) – Base64 automatic sets code given size of tag
- property tag
Returns: tag (str): B64 primitive without prepad (alias of self.soft)
- class keri.core.coring.TextCodex(Bytes_L0: str = '4B', Bytes_L1: str = '5B', Bytes_L2: str = '6B', Bytes_Big_L0: str = '7AAB', Bytes_Big_L1: str = '8AAB', Bytes_Big_L2: str = '9AAB')[source]
TextCodex is codex of all variable sized byte string (Text) derivation codes. Only provide defined codes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
- class keri.core.coring.Texter(raw=None, qb64b=None, qb64=None, qb2=None, code='4B', text=None, **kwa)[source]
Texter is subclass of Matter, cryptographic material, for variable length text strings as bytes not unicode. Unicode strings converted to bytes.
Attributes:
- Inherited Properties: (See Matter)
- size (int | None): Number of quadlets/triplets of chars/bytes including
lead bytes of variable sized material (fs = None). Converted value of the soft part (of len ss) of full derivation code.
Otherwise None when not variably sized (fs != None)
- Properties:
text (str): unqaulified text str without CESR code and leader.
Inherited Hidden Properties: (See Matter)
Methods:
- Codes:
Bytes_L0: str = ‘4B’ # Byte String lead size 0 Bytes_L1: str = ‘5B’ # Byte String lead size 1 Bytes_L2: str = ‘6B’ # Byte String lead size 2 Bytes_Big_L0: str = ‘7AAB’ # Byte String big lead size 0 Bytes_Big_L1: str = ‘8AAB’ # Byte String big lead size 1 Bytes_Big_L2: str = ‘9AAB’ # Byte String big lead size 2
- __init__(raw=None, qb64b=None, qb64=None, qb2=None, code='4B', text=None, **kwa)[source]
- Inherited Parameters: (see Matter)
raw (bytes|None): of unqualified variable sized text string qb64b (bytes|None): fully qualified text domain of raw/text qb64 (str|bytes|None): fully qualified text domain of raw/text qb2 (bytes|None): fully qualified binary domain of raw/text code (str): hard part of derivation code in text domain
- Parameters:
text (str|bytes|None) – unqualified variable sized text string as either same as raw but may be as str, so handles encoding/decoding to/from bytes/str
- property text
raw as str
- Type:
Property text
- class keri.core.coring.Tholder(*, thold=None, limen=None, sith=None, **kwa)[source]
Tholder is KERI Signing Threshold Satisfaction class .satisfy method evaluates satisfaction based on ordered list of indices of verified signatures where indices correspond to offsets in key list of associated signatures.
Has the following public properties:
- Properties:
.weighted is Boolean True if fractional weighted threshold False if numeric .size is int of minimum size of keys list
when weighted is size of keys list when unweighted is size of int thold since don’t have anyway
to know size of keys list in this case
- .limen is qualified b64b signing threshold suitable for CESR serialization.
either Number.qb64b or Bexter.qb64b. The b64 portion of limen with code stripped (Bexter.bext) of
[[“1/2”, “1/2”, “1/4”, “1/4”, “1/4”], [“1”, “1”]] is ‘1s2c1s2c1s4c1s4c1s4a1c1’ basically slash is ‘s’, comma is ‘c’,
ANDed clauses are delimited by ‘a’. Each clause top level weight may be optionally a weighted set of weights delimited by ‘k’ for the weight on the set and ‘v’ for the weights in the set. [[{‘1/3’: [‘1/2’, ‘1/2’, ‘1/2’]}, ‘1/2’, {‘1/2’: [‘1’, ‘1’]}],
[‘1/2’, {‘1/2’: [‘1’, ‘1’]}]]
b’4AAKA1s3k1s2v1s2v1s2c1s2c1s2k1v1a1s2c1s2k1v1’
- .sith is original signing threshold suitable for value to be serialized
- as json, cbor, mgpk in key event message as either:
non-negative hex number str or list of str rational number fractions >= 0 and <= 1 or list of list of str rational number fractions >= 0 and <= 1 list of list of weighted map of weights
- .thold is parsed signing threshold suitable for calculating satisfaction.
either as int or list of Fractions
.num is int signing threshold when not ._weighted
- .satisfy returns bool, True means list of verified signature key indices
- satisfies the threshold, False otherwise.
- Static Methods:
- weight (str): converts weight str expression into either int or Fraction
else raises ValueError must satisfy 0 <= w <= 1 Ensures strict proper rational number fraction of ints or 0 or 1
- Hidden:
._weighted is Boolean, True if fractional weighted threshold False if numeric ._size is int minimum size of of keys list ._sith is signing threshold for .sith property ._thold is signing threshold for .thold propery ._bexter is Bexter instance of weighted signing threshold or None ._number is Number instance of integer threshold or None ._satisfy is method reference of threshold specified verification method ._satisfy_numeric is numeric threshold verification method ._satisfy_weighted is fractional weighted threshold verification method
- __init__(*, thold=None, limen=None, sith=None, **kwa)[source]
Accepts signing threshold in various forms so that may output correct forms for serialization and/or calculation of satisfaction.
The thold representation is meant to accept thresholds from computable expressions for satisfaction of a threshold
The limen representation is meant to parse threshold expressions from CESR serializations of key event message fields or attachments. Limen is passed to Matter to process and accepts all Matter kwa including strip which is useful when extracting from a CESR stream.
The sith representation is meant to parse threhold expressions from deserializations of JSON, CBOR, or MGPK key event message fields or the command line or configuration files.
- Parameters:
threshold (sith is signing) –
- the satisfaction of a threshold and is expressed as either:
int of threshold number (M of N) fractional weight clauses which may be expressed as either:
- sequence of either Fractions or tuples of Fraction and
sequence of Fractions
- sequence of sequence of either Fractions or tuples of
Fraction and sequence of Fractions
threshold –
Number.qb64 or .qb64b of integer threshold or Bexter.qb64 or .qb64b of fractional weight clauses which may be either:
Base64 delimited clauses of fractions Base64 delimited clauses of fractions
threshold –
- non-negative int of threshold number (M-of-N threshold)
next threshold may be zero
- non-negative hex string of threshold number (M-of-N threshold)
next threshold may be zero
- fractional weight clauses which may be expressed as either:
sequence of rational number fraction strings >= 0 and <= 1 sequence of either rational number fraction strings >= 0 and <= 1 or map with key rational number string and value as sequence of rational number fraction strings rational number fraction string sequence of sequences of rational number fraction strings >= 0 and <= 1 sequence of sequnces of either rational number fraction strings or map with key rational number fraction string with value sequence of rationaly number fraction strings
JSON serialized str of the above:
- property json
Returns json serialization of sith expression
Essentially JSON list of lists of strings
- property limen
limen property getter
- property num
sith property getter
- satisfy(indices)[source]
Returns True if indices list of verified signature key indices satisfies threshold, False otherwise.
- Parameters:
indices (indices is list of non-negative) – of verified signatures. the indices may be in any order, they are normalized herein
- property sith
sith property getter
- property size
size property getter
- property thold
thold property getter
- static weight(w: str) Fraction[source]
Returns valid weight from w else raises error (ValueError or TypeError). w expression must evaluate to 0, 1, or strict proper rational fraction. w expression must be 0 <= w <= 1 Else raises ValueError w must not be float else raises TypeError When not int w must be ratio of integers n/d else raise ValueError.
- Parameters:
w (str) – threshold weight expression
- property weighted
weighted property getter
- class keri.core.coring.Traitor(qb64b=None, qb64=None, qb2=None, tag='', trait='', **kwa)[source]
Traitor is subclass of Tagger, cryptographic material, for formatted configuration traits for key events in Base64. Leverages Tagger support of compact special fixed size primitives with non-empty soft part and empty raw part.
Traitor provides a more compact representation than would be obtained by converting the raw ASCII representation to Base64.
Attributes:
- Inherited Properties: (See Tagger)
code (str): hard part of derivation code to indicate cypher suite hard (str): hard part of derivation code. alias for code soft (str): soft part of derivation code fs any.
Empty when ss = 0.
both (str): hard + soft parts of full text code size (int | None): Number of quadlets/triplets of chars/bytes including
lead bytes of variable sized material (fs = None). Converted value of the soft part (of len ss) of full derivation code.
Otherwise None when not variably sized (fs != None)
fullSize (int): full size of primitive raw (bytes): crypto material only. Not derivation code or lead bytes. qb64 (str): Base64 fully qualified with derivation code + crypto mat qb64b (bytes): Base64 fully qualified with derivation code + crypto mat qb2 (bytes): binary with derivation code + crypto material transferable (bool): True means transferable derivation code False otherwise digestive (bool): True means digest derivation code False otherwise prefixive (bool): True means identifier prefix derivation code False otherwise special (bool): True when soft is special raw is empty and fixed size composable (bool): True when .qb64b and .qb2 are 24 bit aligned and round trip tag (str): B64 primitive without prepad (strips prepad from soft)
- Properties:
trait (str): configuration trait B64 from TraitDex
- Inherited Hidden: (See Tagger)
_code (str): value for .code property _soft (str): soft value of full code _raw (bytes): value for .raw property _rawSize(): _leadSize(): _special(): _infil(): creates qb64b from .raw and .code (fully qualified Base64) _binfil(): creates qb2 from .raw and .code (fully qualified Base2) _exfil(): extracts .code and .raw from qb64b (fully qualified Base64) _bexfil(): extracts .code and .raw from qb2 (fully qualified Base2)
Hidden:
Methods:
- __init__(qb64b=None, qb64=None, qb2=None, tag='', trait='', **kwa)[source]
- Inherited Parameters: (see Tagger)
- raw (bytes | bytearray | None): unqualified crypto material usable
for crypto operations.
code (str): stable (hard) part of derivation code soft (str | bytes): soft part for special codes rize (int | None): raw size in bytes when variable sized material not
including lead bytes if any Otherwise None
qb64b (bytes | None): fully qualified crypto material Base64 qb64 (str | bytes | None): fully qualified crypto material Base64 qb2 (bytes | None): fully qualified crypto material Base2 strip (bool): True means strip (delete) matter from input stream
bytearray after parsing qb64b or qb2. False means do not strip
tag (str | bytes): Base64 plain. Prepad is added as needed.
- Parameters:
trait (str) – configuration trait B64 from TraitDex
- property trait
- Returns:
B64 primitive without prepad (strips prepad from soft)
- Return type:
trait (str)
Alias for self.tag
- class keri.core.coring.Verfer(**kwa)[source]
Verfer is Matter subclass with method to verify signature of serialization using the .raw as verifier key and .code for signature cipher suite.
See Matter for inherited attributes and properties:
Attributes:
Properties:
- class keri.core.coring.Versage(proto, pvrsn, gvrsn)
- gvrsn
Alias for field number 2
- proto
Alias for field number 0
- pvrsn
Alias for field number 1
- class keri.core.coring.Verser(qb64b=None, qb64=None, qb2=None, versage=None, proto='KERI', pvrsn=(2, 0), gvrsn=None, tag='', **kwa)[source]
Verser is subclass of Tagger, cryptographic material, for formatted version primitives in Base64. Leverages Tagger support compact special fixed size primitives with non-empty soft part and empty raw part.
Verser provides a more compact representation than would be obtained by converting the raw ASCII representation to Base64.
Attributes:
- Inherited Properties: (See Tagger)
code (str): hard part of derivation code to indicate cypher suite hard (str): hard part of derivation code. alias for code soft (str): soft part of derivation code fs any.
Empty when ss = 0.
both (str): hard + soft parts of full text code size (int | None): Number of quadlets/triplets of chars/bytes including
lead bytes of variable sized material (fs = None). Converted value of the soft part (of len ss) of full derivation code.
Otherwise None when not variably sized (fs != None)
fullSize (int): full size of primitive raw (bytes): crypto material only. Not derivation code or lead bytes. qb64 (str): Base64 fully qualified with derivation code + crypto mat qb64b (bytes): Base64 fully qualified with derivation code + crypto mat qb2 (bytes): binary with derivation code + crypto material transferable (bool): True means transferable derivation code False otherwise digestive (bool): True means digest derivation code False otherwise prefixive (bool): True means identifier prefix derivation code False otherwise special (bool): True when soft is special raw is empty and fixed size composable (bool): True when .qb64b and .qb2 are 24 bit aligned and round trip tag (str): B64 primitive without prepad (strips prepad from soft)
- Properties:
versage (Versage): named tuple of (proto, pvrsn, gvrsn)
- Inherited Hidden: (See Tagger)
_code (str): value for .code property _soft (str): soft value of full code _raw (bytes): value for .raw property _rawSize(): _leadSize(): _special(): _infil(): creates qb64b from .raw and .code (fully qualified Base64) _binfil(): creates qb2 from .raw and .code (fully qualified Base2) _exfil(): extracts .code and .raw from qb64b (fully qualified Base64) _bexfil(): extracts .code and .raw from qb2 (fully qualified Base2)
Hidden:
Methods:
- __init__(qb64b=None, qb64=None, qb2=None, versage=None, proto='KERI', pvrsn=(2, 0), gvrsn=None, tag='', **kwa)[source]
- Inherited Parameters: (see Tagger)
- raw (bytes | bytearray | None): unqualified crypto material usable
for crypto operations.
code (str): stable (hard) part of derivation code soft (str | bytes): soft part for special codes rize (int | None): raw size in bytes when variable sized material not
including lead bytes if any Otherwise None
qb64b (bytes | None): fully qualified crypto material Base64 qb64 (str | bytes | None): fully qualified crypto material Base64 qb2 (bytes | None): fully qualified crypto material Base2 strip (bool): True means strip (delete) matter from input stream
bytearray after parsing qb64b or qb2. False means do not strip
tag (str | bytes): Base64 plain. Prepad is added as needed.
- Parameters:
versage (Versage | None) – namedtuple of (proto, pvrsn, gvrsn)
proto (str | None) – protocol from Protocols
pvrsn (Versionage | None) – instance protocol version. namedtuple (major, minor) of ints
gvrsn (Versionage | None) – instance genus version. namedtuple (major, minor) of ints
- static b64ToVer(b64, *, texted=False)[source]
Converts Base64 representation of version to Versionage or text dotted decimal format
default is Versionage
- Return type:
version (Versionage | str)
Example
.b64ToVer(“BAA”))
- Parameters:
b64 (str) – base64 string of three characters Mmm for Major minor
texted (bool) – return text format dotted decimal string
- static verToB64(version=None, *, text='', major=0, minor=0)[source]
Converts version to Base64 representation
- Return type:
verB64 (str)
Example
Verser.verToB64(verstr = “1.0”))
- Parameters:
version (Versionage) – instange of namedtuple Versionage(major=major,minor=minor)
text (str) – text format of version as dotted decimal “major.minor”
major (int) – When version is None and verstr is empty then use major minor range [0, 63] for one Base64 character
minor (int) – When version is None and verstr is empty then use major minor range [0, 4095] for two Base64 characters
- property versage
Returns: versage (Versage): named tuple of (proto, pvrsn, gvrsn)
- keri.core.coring.dumps(ked, kind='JSON')[source]
utility function to handle serialization by kind
- Returns:
serialized version of ked dict
- Return type:
raw (bytes)
- Parameters:
ked (Optional(dict, list)) – key event dict or message dict to serialize
kind (str) – serialization kind (JSON, MGPK, CBOR)
- keri.core.coring.loads(raw, size=None, kind='JSON')[source]
utility function to handle deserialization by kind
- Returns:
deserialized
- Return type:
ked (dict)
- Parameters:
raw (Union[bytes,bytearray]) – raw serialization to deserialze as dict
size (int) – number of bytes to consume for the deserialization. If None then consume all bytes
kind (str) – serialization kind (JSON, MGPK, CBOR)
- keri.core.coring.sizeify(ked, kind=None, version=(1, 0))[source]
Compute serialized size of ked and update version field Returns tuple of associated values extracted and or changed by sizeify
- Returns tuple of (raw, proto, kind, ked, version) where:
raw (str): serialized event as bytes of kind proto (str): protocol type as value of Protocolage kind (str): serialzation kind as value of Serialage ked (dict): key event dict version (Versionage): instance
- Parameters:
ked (dict) – key event dict
kind (str) – value of Serials is serialization type if not provided use that given in ked[“v”]
version (Versionage) – instance supported protocol version for message
Assumes only supports Version
keri.core.counting
keri.core.counting module
Provides versioning support for Counter classes and codes
- class keri.core.counting.Cizage(hs, ss, fs)
- fs
Alias for field number 2
- hs
Alias for field number 0
- ss
Alias for field number 1
- class keri.core.counting.Codenage(GenericGroup, BigGenericGroup, BodyWithAttachmentGroup, BigBodyWithAttachmentGroup, AttachmentGroup, BigAttachmentGroup, DatagramSegmentGroup, BigDatagramSegmentGroup, ESSRWrapperGroup, BigESSRWrapperGroup, FixBodyGroup, BigFixBodyGroup, MapBodyGroup, BigMapBodyGroup, NonNativeBodyGroup, BigNonNativeBodyGroup, GenericMapGroup, BigGenericMapGroup, GenericListGroup, BigGenericListGroup, ControllerIdxSigs, BigControllerIdxSigs, WitnessIdxSigs, BigWitnessIdxSigs, NonTransReceiptCouples, BigNonTransReceiptCouples, TransReceiptQuadruples, BigTransReceiptQuadruples, FirstSeenReplayCouples, BigFirstSeenReplayCouples, PathedMaterialCouples, BigPathedMaterialCouples, DigestSealSingles, BigDigestSealSingles, MerkleRootSealSingles, BigMerkleRootSealSingles, SealSourceCouples, BigSealSourceCouples, SealSourceTriples, BigSealSourceTriples, SealSourceLastSingles, BigSealSourceLastSingles, BackerRegistrarSealCouples, BigBackerRegistrarSealCouples, TypedDigestSealCouples, BigTypedDigestSealCouples, TransIdxSigGroups, BigTransIdxSigGroups, TransLastIdxSigGroups, BigTransLastIdxSigGroups, ESSRPayloadGroup, BigESSRPayloadGroup, BlindedStateQuadruples, BigBlindedStateQuadruples, BoundStateSextuples, BigBoundStateSextuples, TypedMediaQuadruples, BigTypedMediaQuadruples, KERIACDCGenusVersion)
- AttachmentGroup
Alias for field number 4
- BackerRegistrarSealCouples
Alias for field number 42
- BigAttachmentGroup
Alias for field number 5
- BigBackerRegistrarSealCouples
Alias for field number 43
- BigBlindedStateQuadruples
Alias for field number 53
- BigBodyWithAttachmentGroup
Alias for field number 3
- BigBoundStateSextuples
Alias for field number 55
- BigControllerIdxSigs
Alias for field number 21
- BigDatagramSegmentGroup
Alias for field number 7
- BigDigestSealSingles
Alias for field number 33
- BigESSRPayloadGroup
Alias for field number 51
- BigESSRWrapperGroup
Alias for field number 9
- BigFirstSeenReplayCouples
Alias for field number 29
- BigFixBodyGroup
Alias for field number 11
- BigGenericGroup
Alias for field number 1
- BigGenericListGroup
Alias for field number 19
- BigGenericMapGroup
Alias for field number 17
- BigMapBodyGroup
Alias for field number 13
- BigMerkleRootSealSingles
Alias for field number 35
- BigNonNativeBodyGroup
Alias for field number 15
- BigNonTransReceiptCouples
Alias for field number 25
- BigPathedMaterialCouples
Alias for field number 31
- BigSealSourceCouples
Alias for field number 37
- BigSealSourceLastSingles
Alias for field number 41
- BigSealSourceTriples
Alias for field number 39
- BigTransIdxSigGroups
Alias for field number 47
- BigTransLastIdxSigGroups
Alias for field number 49
- BigTransReceiptQuadruples
Alias for field number 27
- BigTypedDigestSealCouples
Alias for field number 45
- BigTypedMediaQuadruples
Alias for field number 57
- BigWitnessIdxSigs
Alias for field number 23
- BlindedStateQuadruples
Alias for field number 52
- BodyWithAttachmentGroup
Alias for field number 2
- BoundStateSextuples
Alias for field number 54
- ControllerIdxSigs
Alias for field number 20
- DatagramSegmentGroup
Alias for field number 6
- DigestSealSingles
Alias for field number 32
- ESSRPayloadGroup
Alias for field number 50
- ESSRWrapperGroup
Alias for field number 8
- FirstSeenReplayCouples
Alias for field number 28
- FixBodyGroup
Alias for field number 10
- GenericGroup
Alias for field number 0
- GenericListGroup
Alias for field number 18
- GenericMapGroup
Alias for field number 16
- KERIACDCGenusVersion
Alias for field number 58
- MapBodyGroup
Alias for field number 12
- MerkleRootSealSingles
Alias for field number 34
- NonNativeBodyGroup
Alias for field number 14
- NonTransReceiptCouples
Alias for field number 24
- PathedMaterialCouples
Alias for field number 30
- SealSourceCouples
Alias for field number 36
- SealSourceLastSingles
Alias for field number 40
- SealSourceTriples
Alias for field number 38
- TransIdxSigGroups
Alias for field number 46
- TransLastIdxSigGroups
Alias for field number 48
- TransReceiptQuadruples
Alias for field number 26
- TypedDigestSealCouples
Alias for field number 44
- TypedMediaQuadruples
Alias for field number 56
- WitnessIdxSigs
Alias for field number 22
- class keri.core.counting.Counter(code=None, *, count=None, countB64=None, qb64b=None, qb64=None, qb2=None, strip=False, version=(2, 0), **kwa)[source]
Counter is fully qualified cryptographic material primitive base class for counter primitives (framing composition grouping count codes).
Sub classes are derivation code and key event element context specific.
Includes the following attributes and properties:
- Class Attributes:
Codes (dict): nested of codexes keyed by major and minor version Names (dict): nested of map of code names to codes keyed by
major and minor version
Hards (dict): of hard code sizes keyed by text domain selector Bards (dict): of hard code sizes keyed by binary domain selector Sizes (dict): of size tables keyed by version. Size table is dict
of Sizages keyed by hard code
Attributes:
- Properties:
version (Versionage): current CESR code table protocol genus version codes (CounterCodex_1_0 | CounterCodex_1_0): version specific codex sizes (dict): version specific sizes table code (str): hard part of derivation code to indicate cypher suite raw (bytes): crypto material only without code pad (int): number of pad chars given raw count (int): count of quadlets/triplets of following framed material
(not including code)
- qb64 (str | bytes | bytearray): in Base64 fully qualified with
derivation code + crypto mat
- qb64b (bytes | bytearray): in Base64 fully qualified with
derivation code + crypto mat
- qb2 (bytes | bytearray): in binary with derivation code +
crypto material
- Hidden:
_version (Versionage): value for .version property _codes (CounterCodex_1_0 | CounterCodex_1_0): version specific codex _sizes (dict): version specific sizes table _code (str): value for .code property _raw (bytes): value for .raw property _count (int): value for .count property
- Versioning:
CESR Genus specific code tables have a major and a minor version.
For a given major version all minor versions must be backwards compatible. This means that minor version changes to tables are append only. New codes may be added but no existing codes may be changed. This means that a given implementation need only use use the latest minor version of the code table for a given major version when generating or parsing a primitive or group. Assuming the major versions match, when parsing, a primitive, when that primitive was generated with a later minor version than the implementation supports then it will not be recognized and raise an error. But if a primitive was generated with any earlier minor version than the version the implementation supports then the primitive will parse correctly using any later minor version of the code table.
Likewise a given protocol stack may have message bodies that carry a major and a minor version.
A given CESR Genus and a given Protocol message stack may be paired in order to synchronize versioning between the two when the message bodies use primitives and or groups defined by codes in the CESR Genus table.
In this case pairing is between the CESR Genus labeled KERI_ACDC_SPAC and the message body protocol stack labeled KERI/ACDC/SPAC
The two versions, CESR Genus and Protocol Stack, may be synchronized in the following way:
Major versions must match or be compatible
Minor versions may differ but must be compatible within a
major version.
Importantly the CESR code table version may not be included in the message body itself but only provided in the surrounding CESR stream. This means the code table version used by a message body may not be signed. Therefore the receiver of a message body with embedded CESR primitives and groups must be protected from a CESR code table genus version malleability attack.
When the major versions of the CESR code table and protocol stack match, the signed embedded protocol stack major version protects the receiver from a major version malleability attack on the CESR code table. Otherwise the major versions must be compatible in a way that does not allow malleability. For example the set of allowed codes for a given message protocol version are compatible across CESR code table major versions.
This, however, does not protect the receiver of a message body from a minor version malleability attack on the CESR code table. Nevertheless, the requirement that all minor versions of a CESR code table for a given major version must be backwards compatible, does indeed provide this protection.
Either, the receiver of the message body recognizes exactly all primitives and groups in the message body because the CESR code table minor version supported by the receiver is greater than or equal to that used by the the minor version of the sender or any unsupported (later appended) primitives or group codes will be unrecognized by the received thereby raising an error that results in the message being dropped.
- __init__(code=None, *, count=None, countB64=None, qb64b=None, qb64=None, qb2=None, strip=False, version=(2, 0), **kwa)[source]
Validate as fully qualified :param code: either stable (hard) part of derivation code or
code name. When code name then look up code from ._codes. This allows versioning to change code but keep stable code name.
- Parameters:
count (int | None) – count of framed material in quadlets/triplets for composition. Count does not include code. When both count and countB64 are None then count defaults to 1
countB64 (str | None) – count of framed material in quadlets/triplets for composition as Base64 representation of int. useful for genus-version version as count
qb64b (bytes | bytearray | None) – fully qualified crypto material text domain if code nor tag is provided
qb64 (str | None) – if code nor tag not qb64b is provided
qb2 (bytes | bytearray | None) – if code nor tag not qb64b nor qb54 is provided
strip (bool) – True means strip counter contents from input stream bytearray after parsing qb64b or qb2. False means do not strip. default False
version (Versionage) – instance of genera version of CESR code tables
Needs either code or qb64b or qb64 or qb2 Otherwise raises EmptyMaterialError When code and count provided then validate that code and count are correct Else when qb64b or qb64 or qb2 provided extract and assign .code and .count
- static b64ToVer(b64, *, texted=False)[source]
Converts Base64 representation of version to Versionage or text dotted decimal format
default is Versionage
- Return type:
version (Versionage | str)
Example
Counter(version=Counter.b64ToVer(“BAA”))
- Parameters:
b64 (str) – base64 string of three characters Mmm for Major minor
texted (bool) – return text format dotted decimal string
- property both
Getter for combined hard + soft parts of full text code :returns: hard + soft parts of full text code :rtype: both (str)
- byteCount(cold='txt')[source]
Computes number of bytes from .count quadlets/triplets given cold
- Returns:
number of bytes in .count quadlets/triplets given cold
- Return type:
byteCount (int)
- Parameters:
cold (str) – value of Coldage to indicate if text (qb64) or binary (qb2) in order to convert .count quadlets/triplets to byte count if not Colds.txt or Colds.bny raises ValueError
- byteSize(cold='txt')[source]
Computes number of bytes from .fullSize given cold (text or binary domain) so can strip appropriate number of bytes from stream when peeking at counter in stream without stripping it.
- Returns:
number of bytes given cold (text or binary domain)
- Return type:
byteSize (int)
- Parameters:
cold (str) – value of Coldage to indicate if text (qb64) or binary (qb2) in order to convert .count quadlets/triplets to byte count if not Colds.txt or Colds.bny raises ValueError
- property code
Property for code :returns:
- hard part only of full text code.
Getter for ._code. Makes .code read only
- Return type:
code (str)
Soft part is count
- property codes
Makes .codes read only Returns ._codes
- property count
Getter for ._count. Makes ._count read only :returns:
- count value in quadlets/triples chars/bytes of material
framed by counter.
- Return type:
count (int)
- countToB64(l=None)[source]
Returns count as Base64 left padded with “A”s :param l: minimum number characters including left padding
When not provided use the softsize of .code
- classmethod enclose(*, qb64=None, qb2=None, code='AttachmentGroup', version=(2, 0))[source]
Encloses (frames) CESR stream in qb64 (as bytes) or qb2 (as bytes) with prepended counter of type code. Assumes counter in quadlets/triplets. In V2 CESR, will work with all counters which must count quadlets/triplets) In V1 CESR, will only work with counters that count quadlets/triplets
- Returns:
- stream in qb64 or qb2 with prepended counter
of type code. If both qb64 and qb2 are None then empty counter. If qb64 then returns enclosure as bytearray in qb64 text domain If qb2 then returns enclosure as bytearray in qb2 binary domain
- Return type:
enclosure (bytearray)
- Parameters:
qb64 (str|bytes|bytearray|memoryview|None) – qualified Base64 sub-stream to be enclosed. May be empty. None means use qb2 if provided.
qb2 (bytes|bytearray|memoryview|None) – qualified Base2 sub-stream to be enclosed. May be empty. None means ignore
code (str) – either stable (hard) part of derivation code or code name. When code name then look up code from ._codes. This allows versioning to change code but keep stable code name.
- property fullSize
Getter for full size of counter in bytes in text domain Returns”
fs (int): full size of counter in bytes in text domain
- property hard
Alias for .code :returns: hard part only of full text code. Alias for .code. :rtype: hard (str)
- classmethod makeGVC(version)[source]
Makes genus version code from Versionage version
- Parameters::
version (Versionage): version portion of Genus Version Code
- Returns::
qb64b (bytes): qb64b serialized genus version counter for KERI/ACDC genus
- property name
Getter for ._name. Makes .name read only :returns:
- code name for self.code. Match interface
for annotation for primitives like Matter
- Return type:
name (str)
- property qb2
Property qb2: Returns Fully Qualified Binary Version Bytes
- property qb64
Property qb64: :returns: Fully Qualified Base64 Version, same as .both
Assumes self.raw and self.code are correctly populated
- property qb64b
Property qb64b: :returns: Fully Qualified Base64 Version encoded as bytes
Assumes self.raw and self.code are correctly populated
- property sizes
Makes .sizes read only Returns ._sizes
- property soft
Converts .count to b64 :returns:
- Base64 soft part of full counter code. Count value in
quadlets/triples chars/bytes of material framed by counter.
- Return type:
soft (str)
- static verToB64(version=None, *, text='', major=0, minor=0)[source]
Converts version to Base64 representation of countB64 suitable for CESR protocol genus and version
- Returns:
- suitable for input to Counter param countB64 for
creating genus-version code version count portion
- Return type:
countB64 (str)
- Parameters:
version (Versionage) – instange of namedtuple Versionage(major=major,minor=minor)
text (str) – text format of version as dotted decimal “major.minor”
major (int) – When version is None and verstr is empty then use major minor range [0, 63] for one Base64 character
minor (int) – When version is None and verstr is empty then use major minor range [0, 4095] for two Base64 characters
Example
Counter(countB64=Counter.verToB64(text = “1.0”)) Counter(countB64=Counter.verToB64(major=1, minor=0))
- property version
Makes .version read only Returns ._version genusversion
- class keri.core.counting.CounterCodex_1_0(ControllerIdxSigs: str = '-A', WitnessIdxSigs: str = '-B', NonTransReceiptCouples: str = '-C', TransReceiptQuadruples: str = '-D', FirstSeenReplayCouples: str = '-E', TransIdxSigGroups: str = '-F', SealSourceCouples: str = '-G', TransLastIdxSigGroups: str = '-H', SealSourceTriples: str = '-I', PathedMaterialCouples: str = '-L', BigPathedMaterialCouples: str = '--L', GenericGroup: str = '-T', BigGenericGroup: str = '--T', BodyWithAttachmentGroup: str = '-U', BigBodyWithAttachmentGroup: str = '--U', AttachmentGroup: str = '-V', BigAttachmentGroup: str = '--V', NonNativeBodyGroup: str = '-W', BigNonNativeBodyGroup: str = '--W', ESSRPayloadGroup: str = '-Z', BigESSRPayloadGroup: str = '--Z', KERIACDCGenusVersion: str = '-_AAA')[source]
CounterCodex_1_0 is codex hard (stable) part of all V1 counter codes. Only provide defined codes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
As subclass of MapCodex can get codes with item syntax using tag variables. Example: codex[tag]
- class keri.core.counting.CounterCodex_2_0(GenericGroup: str = '-A', BigGenericGroup: str = '--A', BodyWithAttachmentGroup: str = '-B', BigBodyWithAttachmentGroup: str = '--B', AttachmentGroup: str = '-C', BigAttachmentGroup: str = '--C', DatagramSegmentGroup: str = '-D', BigDatagramSegmentGroup: str = '--D', ESSRWrapperGroup: str = '-E', BigESSRWrapperGroup: str = '--E', FixBodyGroup: str = '-F', BigFixBodyGroup: str = '--F', MapBodyGroup: str = '-G', BigMapBodyGroup: str = '--G', NonNativeBodyGroup: str = '-H', BigNonNativeBodyGroup: str = '--H', GenericMapGroup: str = '-I', BigGenericMapGroup: str = '--I', GenericListGroup: str = '-J', BigGenericListGroup: str = '--J', ControllerIdxSigs: str = '-K', BigControllerIdxSigs: str = '--K', WitnessIdxSigs: str = '-L', BigWitnessIdxSigs: str = '--L', NonTransReceiptCouples: str = '-M', BigNonTransReceiptCouples: str = '--M', TransReceiptQuadruples: str = '-N', BigTransReceiptQuadruples: str = '--N', FirstSeenReplayCouples: str = '-O', BigFirstSeenReplayCouples: str = '--O', PathedMaterialCouples: str = '-P', BigPathedMaterialCouples: str = '--P', DigestSealSingles: str = '-Q', BigDigestSealSingles: str = '--Q', MerkleRootSealSingles: str = '-R', BigMerkleRootSealSingles: str = '--R', SealSourceCouples: str = '-S', BigSealSourceCouples: str = '--S', SealSourceTriples: str = '-T', BigSealSourceTriples: str = '--T', SealSourceLastSingles: str = '-U', BigSealSourceLastSingles: str = '--U', BackerRegistrarSealCouples: str = '-V', BigBackerRegistrarSealCouples: str = '--V', TypedDigestSealCouples: str = '-W', BigTypedDigestSealCouples: str = '--W', TransIdxSigGroups: str = '-X', BigTransIdxSigGroups: str = '--X', TransLastIdxSigGroups: str = '-Y', BigTransLastIdxSigGroups: str = '--Y', ESSRPayloadGroup: str = '-Z', BigESSRPayloadGroup: str = '--Z', BlindedStateQuadruples: str = '-a', BigBlindedStateQuadruples: str = '--a', BoundStateSextuples: str = '-b', BigBoundStateSextuples: str = '--b', TypedMediaQuadruples: str = '-c', BigTypedMediaQuadruples: str = '--c', KERIACDCGenusVersion: str = '-_AAA')[source]
CounterCodex_2_0 is codex hard (stable) part of all V2 counter codes. Only provide defined codes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
As subclass of MapCodex can get codes with item syntax using tag variables. Example: codex[tag]
- class keri.core.counting.GenusCodex(KERI: str = '-_AAA', ACDC: str = '-_AAB', SPAC: str = '-_AAC', TSP_: str = '-_AAD')[source]
GenusCodex is codex of protocol genera for code table.
Only provide defined codes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
- class keri.core.counting.MessageUniversalCodex_1_0(NonNativeBodyGroup: str = '-W', BigNonNativeBodyGroup: str = '--W')[source]
MessageUniversalCodex_1_0 is codex hard (stable) part of all V1 message universal counter codes that support CESR native messages. (currently none) But needed for symmetry when changing versions in how lookup happens in parser. Only provide defined codes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
As subclass of MapCodex can get codes with item syntax using tag variables. Example: codex[tag]
- class keri.core.counting.MessageUniversalCodex_2_0(DatagramSegmentGroup: str = '-D', BigDatagramSegmentGroup: str = '--D', ESSRWrapperGroup: str = '-E', BigESSRWrapperGroup: str = '--E', FixBodyGroup: str = '-F', BigFixBodyGroup: str = '--F', MapBodyGroup: str = '-G', BigMapBodyGroup: str = '--G', NonNativeBodyGroup: str = '-H', BigNonNativeBodyGroup: str = '--H')[source]
MessageUniversalCodex_2_0 is codex hard (stable) part of all V2 message universal counter codes that support CESR native messages. Only provide defined codes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
As subclass of MapCodex can get codes with item syntax using tag variables. Example: codex[tag]
- class keri.core.counting.QuadTripCodex_1_0(PathedMaterialCouples: str = '-L', BigPathedMaterialCouples: str = '--L', GenericGroup: str = '-T', BigGenericGroup: str = '--T', BodyWithAttachmentGroup: str = '-U', BigBodyWithAttachmentGroup: str = '--U', AttachmentGroup: str = '-V', BigAttachmentGroup: str = '--V', NonNativeBodyGroup: str = '-W', BigNonNativeBodyGroup: str = '--W', ESSRPayloadGroup: str = '-Z', BigESSRPayloadGroup: str = '--Z')[source]
QuadTripCodex_1_0 is codex hard (stable) part of all V1 counter codes that count quadlets/triplets.
Only provide defined codes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
As subclass of MapCodex can get codes with item syntax using tag variables. Example: codex[tag]
- class keri.core.counting.SealCodex_2_0(DigestSealSingles: str = '-Q', BigDigestSealSingles: str = '--Q', MerkleRootSealSingles: str = '-R', BigMerkleRootSealSingles: str = '--R', SealSourceCouples: str = '-S', BigSealSourceCouples: str = '--S', SealSourceTriples: str = '-T', BigSealSourceTriples: str = '--T', SealSourceLastSingles: str = '-U', BigSealSourceLastSingles: str = '--U', BackerRegistrarSealCouples: str = '-V', BigBackerRegistrarSealCouples: str = '--V', TypedDigestSealCouples: str = '-W', BigTypedDigestSealCouples: str = '--W')[source]
SealCodex_2_0 is codex of seal counter derivation codes. Only provide defined codes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
As subclass of MapCodex can get codes with item syntax using tag variables. Example: codex[tag]
- class keri.core.counting.SpecialUniversalCodex_1_0(GenericGroup: str = '-T', BigGenericGroup: str = '--T', BodyWithAttachmentGroup: str = '-U', BigBodyWithAttachmentGroup: str = '--U', AttachmentGroup: str = '-V', BigAttachmentGroup: str = '--V')[source]
SpecialUniversalCodex_1_0 is codex hard (stable) part of all V1 special universal counter codes that may have optional genus-version override as first code in enclosed group.
Only provide defined codes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
As subclass of MapCodex can get codes with item syntax using tag variables. Example: codex[tag]
- class keri.core.counting.SpecialUniversalCodex_2_0(GenericGroup: str = '-A', BigGenericGroup: str = '--A', BodyWithAttachmentGroup: str = '-B', BigBodyWithAttachmentGroup: str = '--B', AttachmentGroup: str = '-C', BigAttachmentGroup: str = '--C')[source]
SpecialUniversalCodex_2_0 is codex hard (stable) part of all V2 special universal counter codes that may have optional genus-version override as first code in enclosed group. Only provide defined codes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
As subclass of MapCodex can get codes with item syntax using tag variables. Example: codex[tag]
- class keri.core.counting.UniversalCodex_1_0(GenericGroup: str = '-T', BigGenericGroup: str = '--T', BodyWithAttachmentGroup: str = '-U', BigBodyWithAttachmentGroup: str = '--U', AttachmentGroup: str = '-V', BigAttachmentGroup: str = '--V', NonNativeBodyGroup: str = '-W', BigNonNativeBodyGroup: str = '--W', KERIACDCGenusVersion: str = '-_AAA')[source]
CounterCodex_1_0 is codex hard (stable) part of all V1 universal counter codes. Only provide defined codes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
As subclass of MapCodex can get codes with item syntax using tag variables. Example: codex[tag]
- class keri.core.counting.UniversalCodex_2_0(GenericGroup: str = '-A', BigGenericGroup: str = '--A', BodyWithAttachmentGroup: str = '-B', BigBodyWithAttachmentGroup: str = '--B', AttachmentGroup: str = '-C', BigAttachmentGroup: str = '--C', DatagramSegmentGroup: str = '-D', BigDatagramSegmentGroup: str = '--D', ESSRWrapperGroup: str = '-E', BigESSRWrapperGroup: str = '--E', FixBodyGroup: str = '-F', BigFixBodyGroup: str = '--F', MapBodyGroup: str = '-G', BigMapBodyGroup: str = '--G', NonNativeBodyGroup: str = '-H', BigNonNativeBodyGroup: str = '--H', GenericMapGroup: str = '-I', BigGenericMapGroup: str = '--I', GenericListGroup: str = '-J', BigGenericListGroup: str = '--J', KERIACDCGenusVersion: str = '-_AAA')[source]
CounterCodex_2_0 is codex hard (stable) part of all V2 universal counter codes. Only provide defined codes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
As subclass of MapCodex can get codes with item syntax using tag variables. Example: codex[tag]
keri.core.eventing
keri.core.eventing module
- class keri.core.eventing.Kever(*, state=None, serder=None, sigers=None, wigers=None, db=None, estOnly=None, delsner=None, delsger=None, firner=None, dater=None, cues=None, eager=False, local=True, check=False)[source]
Kever is KERI key event verifier class Only supports current version VERSION
Has the following public attributes and properties:
- Class Attributes:
- EstOnly (bool):
True means allow only establishment events False means allow all events
- DoNotDelegate (bool):
True means do not allow delegation other identifiers False means allow delegation of delegated identifiers
- db
instance that manages the LMDB database when provided. When None provided then create and assign vacuous instance of Baser.
- Type:
Baser | None
- cues
Injected Kevery.cues when provided. Default None.
- Type:
deque | None
- prefixes
Injected from Kevery when provided. qb64 identifier prefixes of own habitat identifiers. Assign db.prefixes when None When empty operate in promiscuous mode
- Type:
list | None
- version
serder.version instance of current event state version
- Type:
Versionage
- serder
instance of current event with .serder.diger for digest
- Type:
SerderKERI
- ilk
from Ilks for current event type
- Type:
str
- verfers
of Verfer instances for current event state set of signing keys
- Type:
list
- ndigers
of Diger instances for current event state set of next (rotation) key digests
- Type:
list
- wits
of qualified qb64 aids for witnesses
- Type:
list
- cuts
of qualified qb64 aids for witnesses cut from prev wits list
- Type:
list
- adds
- Type:
list
- estOnly
config trait True means only allow establishment events Default False. Corresponds to config trait string “EO”
- Type:
bool
- doNotDelegate
config trait True means do not allow delegation Default False. Corresponds to config trait string “DND”
- Type:
bool
- lastEst
namedtuple of int sn .s and qb64 digest .d of last est event
- Type:
- delegated
True means delegated identifier, False not delegated
- Type:
bool
- delpre
qb64 of delegator’s prefix
- Type:
str
- Properties:
sn (int): sequence number property that returns .sner.num fn (int): first seen ordinal number property the returns .fner.num ndigs (list): of digests qb64 of .digers kevers (dict): reference to self.db.kevers transferable (bool): True if .digers is not empty and pre is transferable
- __init__(*, state=None, serder=None, sigers=None, wigers=None, db=None, estOnly=None, delsner=None, delsger=None, firner=None, dater=None, cues=None, eager=False, local=True, check=False)[source]
Create incepting kever and state from inception serder Verify incepting serder against sigers raises ValidationError if not
- Parameters:
state (KeyStateRecord | None) – instance for key state notice
serder (SerderKERI | None) – instance of inception event
sigers (list | None) – of Siger instances of indexed controller signatures of event. Index is offset into keys list from latest est event
wigers (list | None) – of Siger instances of indexed witness signatures of event. Index is offset into wits list from latest est event
db (Baser | None) – instance of lmdb database
estOnly (bool | None) – True means establishment only events allowed ‘EO’. False all events allowed.
delsner (Seqner | None) – instance of delegating event sequence number. If this event is not delegated then seqner is ignored
delsger (Diger | None) – instance of of delegating event SAID diger. If this event is not delegated then saider is ignored
firner (Seqner | None) – instance optional of cloned first seen ordinal If cloned mode then firner maybe provided (not None) When firner provided then compare fn of dater and database and first seen if not match then log and add cue notify problem
dater (Dater | None) – optional instance of cloned replay datetime If cloned mode then dater maybe provided (not None) When dater provided then use dater for first seen datetime
cues (Deck | None) – reference to Kevery.cues Deck when provided i.e. notices of events or requests to respond to
eager (bool) –
- True means try harder to find validate events by
walking KELs. Enables only being eager in escrow processing not initial parsing.
- False means only use pre-existing information
if any, either percolated attached or in database.
local (bool) – event source for validation logic True means event source is local (protected). False means event source is remote (unprotected). Event validation logic is a function of local or remote
check (bool) – True means do not update the database in any non-idempotent way. Useful for reinitializing the Kevers from a persisted KEL without updating non-idempotent first seen .fels and timestamps.
- config(serder, estOnly=None, doNotDelegate=None)[source]
Process cnfg field for configuration traits
- deriveBacks(serder)[source]
Derives and return tuple of (wits, cuts, adds) for backers given current set and any changes provided by serder.
- Returns:
- of
wits (list[str]): prefixes of witnesses full list (backers) cuts (list[str]): prefixes of witnesses removed in latest est evt adds (list[str]): prefixes of witnesses added in latest est evt
- Return type:
wca (tuple)
- Parameters:
serder (SerderKeri) – instance of current event
- escrowDelegableEvent(serder, sigers, wigers=None, local=True)[source]
Update associated logs for escrow of Delegable event that needs delegation via an anchored seal in delegator’s KEl
- Parameters:
serder (SerderKERI) – instance of event
sigers (list) – of Siger instance for event
wigers (list) – of witness signatures
local (bool) – event source for validation logic True means event source is local (protected). False means event source is remote (unprotected). Event validation logic is a function of local or remote
- escrowMFEvent(serder, sigers, wigers=None, delsner=None, delsger=None, local=True)[source]
Update associated logs for escrow of MisFit event
- Parameters:
serder (SerderKERI) – instance of event
sigers (list) – of Siger instance for event
wigers (list) – of witness signatures
delsner (Number) – instance of sn of delegating event if any
delsger (Diger) – instance of said digest of delegating event if any
local (bool) – event source for validation logic True means event source is local (protected). False means event source is remote (unprotected). Event validation logic is a function of local or remote
- escrowPDEvent(serder, *, sigers=None, wigers=None, delsner=None, delsger=None, local=True)[source]
Update associated logs for escrow of partially delegated event. Assumes sigs (controller signatures) and wigs (witness signatures) are provided elsewhere. Partial authentication occurs once an event is fully signed and witnessed but the authorizing (delegating) source seal in the authorizer’s (delegator’s) key has not yet been verified.
The escrow of the authorizing event ref via source seal is not idempotent so that malicious or erroneous source seals may be nullified and/or replaced by found source seals.
Escrow allows escrow processor to retrieve serder from key and source couple from val in order to to re-verify authentication status.
- Parameters:
event (serder is SerderKERI instance of)
sigs (wigers is list of Siger instance of indexed witness)
sigs
sn (delsner is Number instance of sn of seal source delegating event)
said (delsger is Diger instance of digest of delegating event)
local (bool) – event source for validation logic True means event source is local (protected). False means event source is remote (unprotected). Event validation logic is a function of local or remote
- escrowPSEvent(serder, *, sigers=None, wigers=None, delsner=None, delsger=None, local=True)[source]
Update associated logs for escrow of partially signed event or fully signed delegated event but not yet verified delegation.
- Parameters:
event (serder is SerderKERI instance of)
sigs (wigers is optional list of Siger instance of indexed witness)
sigs
delsner (Number) – instance of sn of delegating event if any
delsger (Diger) – instance of said digest of delegating event if any
local (bool) – event source for validation logic True means event source is local (protected). False means event source is remote (unprotected). Event validation logic is a function of local or remote
- escrowPWEvent(serder, *, sigers=None, wigers=None, delsner=None, delsger=None, local=True)[source]
Update associated logs for escrow of partially witnessed event
- Parameters:
event (serder is SerderKERI instance of)
sigs (wigers is list of Siger instance of indexed witness)
sigs
delsner (Number) – instance of sn of delegating event if any
delsger (Diger) – instance of said digest of delegating event if any
local (bool) – event source for validation logic True means event source is local (protected). False means event source is remote (unprotected). Event validation logic is a function of local or remote
- exposeds(sigers)[source]
Returns list of ondices (indices) suitable for Tholder.satisfy from self.ndigers (prior next key digests ) as exposed by event sigers. Uses dual index feature of siger. Assumes that each siger.verfer is from the correct key given by siger.index and the signature has been verified.
A key given by siger.verfer (at siger.index in the current key list) may expose a prior next key hidden by the diger at siger.ondex in .digers.
Each returned ondex must be properly exposed by a siger in sigers such that the siger’s indexed key given by siger.verfer matches the siger’s ondexed digest from digers.
The ondexed digest’s code is used to compute the digest of the corresponding indexed key verfer to verify that they match. This supports crypto agility for different digest codes, i.e. all digests in .digers may use a different algorithm.
Only ondices from properly matching key and digest are returned.
Used to extract the indices from the list of prior next digests .digers exposed by the signatures (sigers) on a rotation event of the newly current keys given by each .verfer at .index from sigers. Only checks keys and digests that correspond to provided signatures not all keys and digests defined by the rotation event.
- Parameters:
sigers (list) – of Siger instances of indexed signature with .verfer
- fetchDelegatingEvent(delpre, serder, *, original=True, eager=False)[source]
Returns delegating event of delegator given by its aid delpre of delegated event given by serder otherwise raises ValidationError.
Assumes delegation event must have been accepted at some point even if it has subsequently been superseded. Therefore only looks in .aess for delegating event source seal references. So do not use for fetching delegating eventsthat have yet to be accepted. Checks that found delegation events have both been accepted.
When delegated event in serder has been accepted then will repair its .aess entry if needed.
- Returns:
- delegating key event with delegating seal of
delegated event serder. If can’t fetch then returns None when eager==False or raises ValidationError if can’t fetch but eager==True
- Return type:
dserder (SerderKERI)
- Parameters:
delpre (str) – qb64 of identifier prefix of delegator
serder (SerderKERI) – delegated serder
original (bool) – True means delegated event is the original candidate to be superseded. This means kel walk search should include superseded or disputed events. False means the delegated event is new candidate to supersede. This means kel walk search should not include superseded or disputed events.
eager (bool) – True means do more expensive KEL walk instead of escrow False means do not do expensive KEL walk now.
Assumes db.aes source seal couple of delegating event cannot be written unless that event has been accepted (first seen) into delegator’s KEL even if it has later been superseded. Confirms this by checking the .fons database of the delegator.
A malicious escrow of delegating event could only write source seal couple to escrow in db.udes not in accepted db.aes
Delegating event may have been superceded but delegated event validator does not know it yet because db.aes keeps original delegating event source seal from before is was superseded.
Therefore lookup of delegating event needs to check delegating event via db.fons and not last key event in .kels which would only return the superseding event.
When walking delegation tree a given delegating event may have been superceded by another delegating event in the same delegator KEL. This method does not distinguish between superseding and superseded so can’t assume that the delegating event is the last event at its sn, i.e. the superseding event. So this method must use db.fons to ensure that delegating event was accepted (first seen) even if it has subsequently been superseded.
When the .aess entry is missing and eager is True and a valid delegation is found and if delegate has been accepted then repairs missing .aess entry. Otherwise does not repair but simply returns found delegation.
Found delegation may not be superseding so do not repair .aess unless delegate was already accepted.
- fetchLatestContribFrom(verfer, sn: int | None = None)[source]
Returns tuple of form (sn, index, verfers) where verfers is a list of verfers from latest est event where verfer is found in that event’s verfers at index offset else None if not found. Fetches latest event sn and associated verfers list that recieved a contribution from the provided verfer at index.
Starts searching at sn or if sn is None at sn = .lastEst.s
Returns tuple (sn, index, list[verfers]) from the latest est event that matches by starting at the given sequence number (sn) and walking backwards otherwise returns None.
If given sn represents an interaction event (ixn) then a latest possible matching result may be from an event that is no later than the last est event prior to that interaction event. If the sn represents an establishment event then the latest possible matching result may be from that event.
- Parameters:
verfer (Verfer) – instance of verfer
sn (int | None) – sn to start searching. If None then start at .lastEst.s
- Returns:
where tuple is of form (sn, index, verfers)
sn is sequence number index is index into verfers of verfers verfers is list of Verfer instances.
- Return type:
tuple(int, int, list[Verfer]) | None
- fetchLatestContribTo(verfers, sn: int | None = None)[source]
Returns tuple of (sn, index, verfer) from latest est event whose verfer is found in verfers at index offset else None if not found. Fetches latest event sn and associated index and verfer that contributed to the provided verfers at index.
Starts searching at sn or if sn is None at sn = .lastEst.s
Returns tuple (sn, index, verfer) from the latest est event that matches by starting at the given sequence number (sn) and walking backwards otherwise returns None.
If given sn represents an interaction event (ixn) then a latest possible matching result may be from an event that is no later than the last est event prior to that interaction event. If the sn represents an establishment event then the latest possible matching result may be from that event.
- Parameters:
verfers (list[Verfer]) – of verfer instances
sn (int | None) – sn to start searching. If None then start at .lastEst.s
- Returns:
- where tuple is of form (sn, idx, verfer).
sn is sequence number. idx is index of verfer in verfers verfer is instance of Verfer
- Return type:
tuple(int, int,Verfer) | None
- fetchPriorDigers(sn: int | None = None) list | None[source]
Returns either the most recent prior list of digers before .lastEst or None
Starts searching at sn or if sn is None at sn = .lastEst.s - 1
Returns list of Digers instances at the most recent prior est event relative to the given sequence number (sn) otherwise returns None. Walks backwards to the more recent prior establishment event before the .sn if any. If sn represents an interaction event (ixn) then the result will be the current valid list of digers. If sn represents an establishment event then the result will be the list of digers immediately prior to the current list.
- Parameters:
sn (int | None) – sn to start searching. If None then start at .lastEst.s - 1
- Returns:
- of Diger instances or None if no prior est evt
to current .lastEst
- Return type:
digers (list | None)
- property fn
Returns: (int): .fner.num
- property groups
Returns .db.gids oset of group hab ids (prefixes)
- incept(serder, estOnly=None)[source]
Verify incept key event message from serder
- Parameters:
event (serder is SerderKERI instance of inception)
allowed (estOnly is boolean to indicate establish only events)
- property kevers
Returns .baser.kevers
- locallyContributedIndices(verfers: list[Verfer])[source]
Returns list of indices of public keys contributed by local members to the KEL with current signing keys represented by verfers
Using the pubs index to find members of a signing group
- Parameters:
verfers (list[Verfer]) – instance for each current signing key
- Returns:
list of indices of keys contributed by local members
- Return type:
indices list[int]
- locallyDelegated(pre: str)[source]
Returns True if pre w is in .prefixes which includes group AIDs in self.groups which have a local member AID.
Which means it is either locally controlled single sig or a multi-sig group with a locally controlled member. False otherwise.
Use when pre is a delegator, i.e. the delpre from some delegated event and want to confirm that pre is also locally controller as either the single sig AID or the group multisig AID of a locally controlled member of the group.
Indicates that provided identifier prefix is controlled by a local controller from .prefixes is a group prefix that is controlled by a local member of that group.
Because delpre may be None, changes the default to “” instead of self.prefixer.pre because self.prefixer.pre is delegate not delegator of self. Unaccepted dip events do not have self.delpre set yet.
- Returns:
- True if pre is local hab or group hab that has a local member
When pre=”” empty or None then returns False
- Return type:
(bool)
- Parameters:
pre (str) – qb64 identifier prefix if any.
ToDo: this code does not account for stale group members as delegators. i.e. a stale group membed is a member AID for a group AID in .groups for which the member AID was a signing (smids) or rotating (rmids) member in the past but is no longer. For delegation approval there must be a local member for the delegator group AID that is a current signing member i,e. in .smids for the group hab.
The current logic allows an event to be escrowed for later approval but whose delpre (delegator) is a group with a stale local member That later approval must detect and properly handle the staleness.
Alternatively the logic could be changed to short circut that later work by checking here for staleness. For example:
delpre.mhab.pre in delpre’s hab.smids (not stale )
- if pre in self.groups: # local group delegator
habord = self.db.habs.get(keys=(pre,)) return habord.mid in habord.smids # True not stale, False stale
return pre in self.prefixes # otherwise local non-group delegator
- locallyMembered(pre: str | None = None)[source]
Returns True if group hab identifier prefix pre has as a contributing member a locally owned prefix by virture of pre in .groups
- Returns:
- True if pre is group hab identifier in .groups
False otherwise
- Return type:
(bool)
- Parameters:
pre (str|None) – qb64 identifier prefix if any or None When None default to use self.prefixer.qb64
- locallyOwned(pre: str | None = None)[source]
Returns True if pre is in .prefixes and not in .groups False otherwise. Exclusively locally controlled. Indicates that provided identifier prefix is controlled by a local controller from .prefixes but is not a group with local member. i.e pre is an exclusively locally owned (controlled) AID (identifier prefix)
- Returns:
- True if pre is local hab but not group hab
When pre=”” empty then returns False
- Return type:
(bool)
- Parameters:
pre (str|None) – qb64 identifier prefix if any. Default None None means use self.prefixer.qb64
- locallyWitnessed(*, wits: list[str] = None, serder: str = None)[source]
- Returns True if a local controller is a witness of this Kever’s KEL
of wits in serder of if None then current wits for this Kever. i.e. self is witnessd by locally owned (controlled) AID (identifier prefix)
- Parameters:
wits (list[str]) – qb64 identifier prefixes of witnesses
serder (SerderKERI | None) – SerderKERI instace if any
- logEvent(serder, sigers=None, wigers=None, wits=None, first=False, delnum=None, diger=None, firner=None, dater=None, local=True)[source]
Update associated logs for verified event. Update is idempotent. Logs will not write dup at key if already exists.
- Parameters:
event (wits is optional list of current witnesses provide during any establishment)
event
sigs (wigers is optional list of Siger instance of indexed witness)
event
event. (first is Boolean True means first seen accepted log of) – Otherwise means idempotent log of event to accept additional signatures beyond the threshold provided for first seen
number. (delnum is Number instance of delegating event sequence) – If this event is not delegated then delnum is ignored
said. (diger is Diger instance of of delegating event) – If this event is not delegated then diger is ignored
ordinal (firner is optional Seqner instance of cloned first seen) – If cloned mode then firner maybe provided (not None) When firner provided then compare fn of dater and database and first seen if not match then log and add cue notify problem
datetime (dater is optional Dater instance of cloned replay) – If cloned mode then dater maybe provided (not None) When dater provided then use dater for first seen datetime
local (bool) – event source for validation logic True means event source is local (protected). False means event source is remote (unprotected). Event validation logic is a function of local or remote
- property ndigs
Returns: (list): digs of digers
- property prefixes
Returns .db.prefixes
- reload(state)[source]
Reload Kever attributes (aka its state) from state (KeyStateRecord)
- Parameters:
state (KeyStateRecord | None) – instance for key state notice
- rotate(serder)[source]
Generic Rotate Operation Validation Processing Validates provisional rotation Same logic for both ‘rot’ and ‘drt’ (plain and delegated rotation)
Returns: tuple (tholder, toader, wits, cuts, adds) of provisional results of rotation subject to additional validation
- Parameters:
serder (SerderKERI) – instance of rotation (‘rot’ or ‘drt’) event.
- property sn
Returns: (int): .sner.num
- property transferable
Property transferable: Returns True if identifier does not have non-transferable derivation code
and .nextor is not None False otherwise
- update(serder, sigers, wigers=None, delsner=None, delsger=None, firner=None, dater=None, eager=False, local=True, check=False)[source]
Not an inception event. Verify event serder and indexed signatures in sigers and update state
- Parameters:
serder (SerderKERI) – instance of event
sigers (list) – of SigMat instances of indexed signatures of controller signatures of event. Index is offset into keys list from latest est event and when provided ondex is offset into key digest list from prior next est event to latest est event.
wigers (list | None) – of Siger instances of indexed witness signatures of event. Index is offset into wits list from latest est event
delsner (Seqner | None) – instance of delegating event sequence number. If this event is not delegated then seqner is ignored
delsger (Diger | None) – instance of of delegating event said diger. If this event is not delegated then diger is ignored
firner (Seqner | None) – Seqner instance of cloned first seen ordinal If cloned mode then firner maybe provided (not None) When firner provided then compare fn of dater and database and first seen if not match then log and add cue notify problem
dater (Dater | None) – Dater instance of cloned replay datetime If cloned mode then dater maybe provided (not None) When dater provided then use dater for first seen datetime
eager (bool) –
- True means try harder to find validate events by
walking KELs. Enables only being eager in escrow processing not initial parsing.
- False means only use pre-existing information
if any, either percolated attached or in database.
local (bool) – event source for validation logic True means event source is local (protected). False means event source is remote (unprotected). Event validation logic is a function of local or remote
check (bool) – True means do not update the database in any non-idempotent way. Useful for reinitializing the Kevers from a persisted KEL without updating non-idempotent first seen .fels and timestamps.
- valSigsWigsDel(serder, sigers, verfers, tholder, wigers, toader, wits, *, delsner=None, delsger=None, eager=False, local=True)[source]
Returns triple (sigers, wigers, delegator) where: sigers is unique validated signature verified members of inputed sigers wigers is unique validated signature verified members of inputed wigers delegator is qb64 delegator prefix if delegated else None
- Validates sigers signatures by validating indexes, verifying signatures, and
validating threshold sith.
- Validate witness receipts by validating indexes, verifying
witness signatures and validating toad.
Witness validation is a function of wits .prefixes and .local
- Parameters:
serder (SerderKERI) – instance of event
sigers (list) – of Siger instances of indexed controllers signatures. Index is offset into verfers list from which public key may be derived.
verfers (list) – of Verfer instances of keys from latest est event
tholder (Tholder) – instance of sith threshold
wigers (list) – of Siger instances of indexed witness signatures. Index is offset into wits list of associated witness nontrans pre from which public key may be derived.
toader (Number) – instance of backer witness threshold
wits (list) – of qb64 non-transferable prefixes of witnesses used to derive werfers for wigers
delsner (Number | None) – instance of delegating event sequence number. If this event is not delegated then ignored
delsger (Diger | None) – instance of delegating event said diger. If this event is not delegated then diger is ignored
eager (bool) –
- True means try harder to find validate events by
walking KELs. Enables only being eager in escrow processing not initial parsing.
- False means only use pre-existing information
if any, either percolated attached or in database.
local (bool) – event source for validation logic True means event source is local (protected). False means event source is remote (unprotected). Event validation logic is a function of local or remote
- validateDelegation(serder, sigers, wigers, wits, delpre, *, delsner=None, delsger=None, eager=False, local=True)[source]
Returns delegator’s qb64 identifier prefix if validation successful. Assumes that local vs remote source checks have been applied before this function is called.
- Rules:
If event is not a delegated event then not valid delegation If delegatee’s own event (.mine) then valid delegation If delegation seal found in delgator’s KEL then valid delegation given
valid superseding rules below
Otherwise escrow or reject if error condition
seal validates with respect to Delegator’s KEL Location Seal is from Delegate’s establishment event Assumes state setup
self is last accepted event if any or yet to be accepted event, serder is received event
- Parameters:
serder (SerderKERI) – instance of delegated event serder
sigers (list[Siger]) – of Siger instances of indexed controller sigs of delegated event. Assumes sigers is list of unique verified sigs
wigers (list[Siger]) – of optional Siger instance of indexed witness sigs of delegated event. Assumes wigers is list of unique verified sigs
wits (list[str]) – of qb64 non-transferable prefixes of witnesses used to derive werfers for wigers
delpre (str) – qb64 prefix of delegator
delsner (Number | None) – instance of delegating event sequence number. If this event is not delegated then ignored
delsger (Diger | None) – instance of delegating event said diger. If this event is not delegated ignored local (bool): event source for validation logic True means event source is local (protected). False means event source is remote (unprotected). Event validation logic is a function of local or remote
eager (bool) –
- True means try harder to validate event by
walking KELs. Enables only being eager in escrow processing not initial parsing.
- False means only use pre-existing information
if any, either percolated attached or in database.
local (bool) – event source for validation logic True means event source is local (protected). False means event source is remote (unprotected). Event validation logic is a function of local or remote
- Returns:
None
- Process Logic:
A delegative event is processed differently for each of four different parties, namely, controller of event, witness to controller of event, delegator of event , and validator of event that is not controller, witness or delegator. Events are processed as either local (protected) or remote. A local event may assume that the event only came via a protected transmission path. This might be because the event is functions locally on a device under the supervision of the controller or was received via some protected channel using some form of MFA. A remote event is received in an unprotected manner. The purpose of local and remote is to allow increased security on local events where a threshold structure is imposed.
A witness pool may act a threshold structure for enchanced security when each witness only accepts local events that are protected by a unique authentication factor thereby making the controller’s signature(s) the first factor and the set of unique witness factors a secondary threshold factor. An attacker therefore has to compromise not merely the controller’s private key(s) but also the unique second factor on each of a threshold satisfycing number of witnesses.
Likewise a delegator may act as a threshold structure for enhanced security when the delegator only accepts local events for delegation that are protected by a unique authentication factor thereby making the controller’s signatures the first factor, a threshold satisfycing number of unique witness factors the second layer of factors, and the delegator’s unique authentication factor as the third factor. An attacker therefore has to compromise not merely the controller’s private key(s) but also the unique second factor on each of a threshold satisfycing number of witnesses and the unique third factor for the delegator.
Controller as delegatee must accept its own delegated event prior to full witnessing or delegator approval (anchored seal) by signing the event in order to trigger the logic to get witness receipts and delegator approval. This means a local (protected) event may be accepted into controller’s KEL when fully signed by controller.
Witness must accept a controller’s delegated event it witnesses prior to full witnessing or delegator approval in order to trigger its witnessing logic. This means a local (protected) event may be accepted into a witness’ KEL when fully signed by its controller.
Delegator may escrow or sandbox a delegated event prior to it anchoring a seal of the event in its KEL in order to trigger its approval logic. Alternatively the approval logic may be triggered immediately after it is received and authenticated on it its local (protected) channel but before it is submitted to its local Kevery for processing.
The delegator MUST NOT accept a delegable event unless it is locally sourced, fully signed by its controller, and fully witnessed by its controller’s designated witness pool. A Delegator may impose additional validation logic prior to approval. The approval logic may be handled by an escrow that only runs if the delegable event is sourced as local. This may require a sandboxed kel for the delegatee in order to not corrupt its pristine copy of the delegatee’s KEL with a valid delegable event from a malicious source. The sandboxing logic may create a virtual delegation event with seal for the purpose of checking the delegated event superseding logic prior to acceptance.
A malicious attacker that compromises the pre-rotated keys of the delegatee may issue a rotation that changes its witness pool in order to bypass the local security logic of the witness pool. The approval logic of the delegator may choose to not automatically approve a delegable rotation event unliess the change to the witness pool is below the threshold.
The logic for superseded events is NOT a requirement for acceptance in either a delegated event controller’s KEL or its witness’ KEL. The delegator’s kel creates a virtual (provisional) delegating interaction event in order to evaluate correct superseding logic so as not to accept an invalid supderseding delegated event into its local copy of the delegated KEL. This virtual event is needed because superseding logic requires an anchoring seal be present before the rules can be fully evaluated.
Should the actual anchor be via a superseding rotation in the delegator’s KEL not via an interaction event then the delegator must check the logic for a virtual delegating rotation instead. In either case the delegated event does not change so the virtual delegating checks are sufficient to accept the delegated event into the delegator’s local copy of the delegatee’s KEL.
Any of delegated controller, delegated witness, or delegator of delegated event may after the fact fully validate event by processing it as a remote event. Then the logic applied is same as validator below.
A validator of a delegated event that is not the event’s controller, witness, or delegator must not accept the event until is is fully signed by the controller (threshold), fully witnessed by the witness pool (threshold) and its seal anchored in the delegator’s KEL. The rules for event superseding in the delegated controller’s kel must also be satisfied. The logic should be the same for both local and remote event because the validator is not one of the protected parties to the event.
Superseding Recovery:
Supersede means that after an event has already been accepted as first seen into a KEL that a different event with the same sequence number is accepted that supersedes the pre-existing event at that sn. This enables the recovery of events signed by compromised keys. The result of superseded recovery is that the KEL is forked at the sn of the superseding event. All events in the superseded branch of the fork still exist but, by virtue of being superseded, are disputed. The set of superseding events in the superseding fork forms the authoritative branch of the KEL.
All the already seen superseded events in the superseded fork still remain in the KEL and may be viewed in order of their original acceptance because the database stores all accepted events in order of acceptance and denotes this order using the first seen ordinal number, fn.
Recall that the fn is not the same as the sn (sequence number). Each event accepted into a KEL has a unique fn but multiple events due to recovery forks may share the same sn.
Superseding Rules for Recovery at given ‘sn’ (sequence number)
- A0. Any rotation event may supersede an interaction event at the same sn.
where that interaction event is not before any other rotation event. (existing rule)
- A1. A non-delegated rotation may not supersede another rotation at the
same sn. (modified rule)
A2. An interaction event may not supersede any event. ( existing rule).
(B. and C. below provide the new rules)
A delegated rotation may supersede the latest seen delegated rotation at the same sn under either of the following conditions:
B1. The superseding rotation’s delegating event is later than the superseded rotation’s delegating event in the delegator’s KEL, i.e. the sn of the superseding event’s delegation is higher than the superseded event’s delegation.
B2. The sn of the superseding rotation’s delegating event is the same as the sn of the superseded rotation’s delegating event in the delegator’s KEL both have the same delegating event and the index of the delegating seal of the superceding delegation seal is later (higher) than the index of the delegating seal of the supderseded rotation. In other words the delegating event is the same event but the superseding delegation seal appears later in the seal list of the delegating event than the superseded delegation seal.
B3. The sn of the superseding rotation’s delegating event is the same as the sn of the superseded rotation’s delegating event in the delegator’s KEL and the superseding rotation’s delegating event is a rotation and the superseded rotation’s delegating event is an interaction, i.e. the delegating events are not the same event and the superseding rotation’s delegating event is itself a superseding rotation of the superseded rotations delegating interaction event in the delgator’s KEL.
- IF Neither A nor B is satisfied, then recursively apply rules A. and B. to
the delegating events of those delegating events and so on until either A. or B. is satisfied, or the root KEL of the delegation which must be undelegated has been reached.
C1. If neither A. nor B. is satisfied by recursive application on the delegator’s KEL (i.e. the root KEL of the delegation has been reached without satisfaction) then the superseding rotation is discarded. The terminal case of the recursive application will occur at the root KEL which by defintion is non-delegated wherefore either A. or B. must be satisfied, or else the superseding rotation must be discarded.
Note: The latest seen delegated rotation constraint means that any earlier delegated rotations CAN NOT be superseded. This greatly simplifies the validation logic and avoids a potential infinite regress of forks in the delegated identifier’s KEL while allowing the delegate to detect that a compromised delegation has occurred and give an opportunity for the delegator to refuse to approve a subsequent delegated rotation without additional verification with the delegate that the subsequent delegated rotation was not compromised.
In order to capture control of a delegated identifier the attacker must issue a delegated rotation that rotates to keys under the control of the attacker that must be approved by the delegator. A recovery rotation must therefore supersede the compromised rotation. If the attacker is able to issue and get approved by the delegator a subsequent rotation that follows but does not supersede the compromising rotation then recovery is no longer possible because the delegatee would no longer control the privete keys needed to verifiably sign a recovery rotation.
One way that detectability may be assured is when the delegator imposes a minimum time between approvals of a delegated rotation that is sufficient for the delgate to detect a compromised rotation recovery. Attempts to rotate sooner than the minimum time since the immediately prior rotation are refused until further verification has occurred.
A delegated rotation that occurs after the minimum time since the immediately prior delegated rotation might be automatically approved to minimize latency. While a subsequent delegated rotation that occurs within the minimum time would not be approed to maximize safety. The minimum time window is designed to give the delegate enough time to detect a comprimised or duplicitious superseding rotation and prevent the additional verification from proceding.
Mitigations of malicious source seal couples:
Repair the approval source seal couple in the ‘aess’ database on recursive climb the kel tree. Once an event has been accepted into its kel. Later adding a source seal couple to ‘aes’ should then be OK from a security perspective since its only making discovery less expensive.
When a malicious source seal couple is received but event is validly delegated and the delegation source seal is repaired then replace malicious source seal couple with repaired seal so repaired seal not malicous seal gets written to ‘aes’ db. When the event is valid but non-delegated then need to nullify malicous source seal couple so it does not get written to ‘aes’ database.
- class keri.core.eventing.Kevery(*, cues=None, db=None, rvy=None, exc=None, tvy=None, kramer=None, lax=True, local=False, cloned=False, direct=True, check=False)[source]
Kevery (Key Event Message Processing Facility) processes an incoming message stream composed of KERI key event related messages and attachments. Kevery acts a Kever (key event verifier) factory for managing key state of KERI identifier prefixes.
Only supports current version VERSION
Has the following public attributes and properties:
- cues
of Cues i.e. notices of events needing receipt or requests needing response
- Type:
Deck
- lax
True means operate in promiscuous (unrestricted) mode, False means operate in nonpromiscuous (restricted) mode
as determined by local and prefixes
- Type:
bool
- local
True means only process msgs for own events if not lax False means only process msgs for not own events if not lax
- Type:
bool
- cloned
True means cloned message stream so use attached datetimes from clone source not own. False means use current datetime
- Type:
bool
- direct
True means direct mode so cue notices for receipts etc False means indirect mode so don’t cue notices
- Type:
bool
- check
True means do not update the database in any non-idempotent way. Useful for reinitializing the Kevers from a persisted KEL without updating non-idempotent first seen .fels and timestamps.
- Type:
bool
- Properties:
.kevers is dict of db kevers indexed by pre (qb64) of each Kever .prefixes is OrderedSet of fully qualified base64 identifier prefixes of db
local habitats if any.
- __init__(*, cues=None, db=None, rvy=None, exc=None, tvy=None, kramer=None, lax=True, local=False, cloned=False, direct=True, check=False)[source]
Initialize instance:
- Parameters:
cues (Deck)
db (Baser)
db – instance of database
rvy (Revery) – instance for reply message processing
exc (Exchanger) – instance for exchange message processing
tvy (Tevery) – instance for TEL query route processing
kramer (Kramer) – instance for KRAM processing
lax (bool) –
True means operate in promiscuous (unrestricted) mode, False means operate in nonpromiscuous (restricted) mode
as determined by local and prefixes
local (bool) – True means event source is local (protected) for validation False means event source is remote (unprotected) for validation
cloned (bool) – True means cloned message stream so use attached datetimes from clone source not own. False means use current datetime
direct (bool) – True means direct mode so cue notices for receipts etc False means indirect mode so don’t cue notices
check (bool) – True means do not update the database in any non-idempotent way. Useful for reinitializing the Kevers from a persisted KEL without updating non-idempotent first seen .fels and timestamps.
- duplicity(serder, sigers)[source]
PlaceHolder Reminder Processes potential duplicitous events in PDELs
Handles duplicity detection and logging if duplicitous
Placeholder here for logic need to move
- escrowLDEvent(serder, sigers, local=True)[source]
Update associated logs for escrow of Likely Duplicitous event
- Parameters:
event (sigers is list of Siger instance for)
event
local (bool) – event source for validation logic True means event source is local (protected). False means event source is remote (unprotected). Event validation logic is a function of local or remote
- escrowMFEvent(serder, sigers, wigers=None, number=None, diger=None, local=True)[source]
Update associated logs for escrow of MisFit event
- Parameters:
serder (SerderKERI) – instance of event
sigers (list) – of Siger instance for event
number (Number) – instance of sn of delegating/issuing event if any
diger (Diger) – instance of dig of delegating/issuing event if any
wigers (list) – of witness signatures
local (bool) – event source for validation logic True means event source is local (protected). False means event source is remote (unprotected). Event validation logic is a function of local or remote
- escrowOOEvent(serder, sigers, delsner=None, delsger=None, wigers=None, local=True)[source]
Update associated logs for escrow of Out-of-Order event
- Parameters:
serder (SerderKERI) – instance of event
sigers (list) – of Siger instance for event
delnumber (Number) – instance of sn of delegating/issuing event if any
diger (Diger) – instance of said of delegating/issuing event if any
wigers (list) – of witness signatures
local (bool) – event source for validation logic True means event source is local (protected). False means event source is remote (unprotected). Event validation logic is a function of local or remote
- escrowQueryNotFoundEvent(prefixer, serder, sigers, cigars=None)[source]
Update associated logs for escrow of Query Not Found event
- Parameters:
prefixer (Prefixer) – source of query message
serder (SerderKERI) – instance of event
sigers (list) – of Siger instance for event
cigars (list) – of non-transferable receipts
- escrowTRGroups(serder, tsgs)[source]
Update associated logs for escrow of Transferable Receipt Groups for event (transferable)
- Parameters:
event (serder instance of receipt message not receipted)
form (tsgs is list of tuples of) – (prefixer,seqner,diger, sigers) prefixer is Prefixer instance of prefix of receipter number is Number instance of sn of est event of receiptor diger is Diger instance of digest of est event of receiptor sigers is list of Siger instances of multi-sig of receiptor
- escrow quintuple for each siger
quintuple = edig+pre+snu+dig+sig where:
edig is receipted event dig (serder.dig) pre is receipter prefix snu is receipter est event sn dig is receipt est evant dig sig is indexed sig of receiptor of receipted event
- escrowTRQuadruple(serder, sprefixer, snumber, diger, siger)[source]
Update associated logs for escrow of Unverified Transferable Receipt (transferable)
- escrow quintuple made from quadruple where:
quadruple = spre+ssnu+sdig+sig (s is trans receipt signer) quintuple = edig+spre+ssnu+sdig+sig (edig is signed event digest)
- Parameters:
serder (SerderKERI) – instance of receipt message not receipted event
sprefixer (Prefixer) – instance receiptor AID
snumber (Number) – instance of sn of est event for receiptor key state
diger (Diger) – instance said digest est event or receipt key state
siger (Siger) – instance of signature of receiptor
- escrowTReceipts(serder, prefixer, number, saider, sigers)[source]
Update associated logs for escrow of Transferable Event Receipt Group (transferable)
- Parameters:
event (serder instance of receipt message not receipted)
receipter (prefixer is Prefixer instance of prefix of)
receiptor (igers is list of Siger instances of multi-sig of)
receiptor
receiptor
- escrow quintuple for each siger
quintuple = edig+pre+snu+dig+sig where:
edig is receipted event dig (serder.dig) pre is receipter prefix snu is receipter est event sn dig is receipt est evant dig sig is indexed sig of receiptor of receipted event
- escrowUReceipt(serder, cigars, said)[source]
Update associated logs for escrow of Unverified Event Receipt (non-transferable) Escrowed value is triple edig+rpre+cig where:
edig is event dig rpre is nontrans receiptor prefix cig is non-indexed signature on event with key pair derived from rpre
- Parameters:
serder (SerderKERI) – instance of receipt msg not receipted event
cigars (list) – of Cigar instances for event receipt
said (str) – qb64 said in receipt of receipted event not serder.dig because serder is of receipt not receipted event
- escrowUWReceipt(serder, wigers, said)[source]
Update associated logs for escrow of Unverified Event Witness Receipt (non-transferable) Escrowed value is couple edig+wig where:
edig is receipted event dig not serder.dig wig is witness indexed signature on receipted event with key pair
derived from witness nontrans identifier prefix in witness list. Index is offset into witness list of latest establishment event for receipted event.
- Parameters:
serder (SerderKERI) – instance of receipt msg not receipted event
wigers (list) – of Siger instances for witness indexed signature of receipted event
said (str) – serder is a receipt not the receipted event
- fetchEstEvent(pre, sn)[source]
Returns SerderKERI instance of establishment event that is authoritative for event in KEL for pre at sn. Returns None if no event at sn accepted in KEL for pre
- Parameters:
KEL (pre is qb64 of identifier prefix for)
pre (sn is int sequence number of event in KEL of)
- fetchWitnessState(pre, sn)[source]
Returns the list of witness for the identifier prefix at the sequence number
Returns the witness state (list of witnesses) at the given sequence number (sn) of the identifier prefix (pre). It uses the .wits database that stores witness state at the sequence number of each establishment event. If sn represents an interaction event (ixn) it searches backwards for the last establishment event prior to sn and returns that witness state.
- Parameters:
pre (str) – identifier prefix qb64
sn (int) – sequence number of the event for which witness state is desired
- Returns:
- list of Prefixer objects representing the witness state for the identifier prefix at
the sequence number
- Return type:
list
- property kevers
Returns .db.kevers
- property prefixes
Returns .db.prefixes
- processAttachedReceiptCouples(serder, cigars, *, firner=None, local=None, **kwa)[source]
Process one attachment couple that represents an endorsement from a nontransferable AID that may or may not be a witness, maybe a watcher. Originally may have been a non-transferable receipt or key event attachment if signature is for witness then promote to indexed sig and store appropriately. The is the attachment version of .processReceipt
- Parameters:
serder (SerderKERI) – instance serialized event message to which attachments come from replay (clone)
cigars (list[Cigar]) – instances that contain receipt couple signature in .raw and public key in .verfer
firner (Seqner) – instance of first seen ordinal, if provided lookup event by fn = firner.sn used when in cloned replay mode
local (bool|None) – True means local (protected) event source. False means remote (unprotected). None means use default .local .
- processAttachedReceiptQuadruples(serder, trqs, *, firner=None, local=None, **kwa)[source]
Process one attachment quadruple that represents an endorsement from a transferable AID that is not the controller. Maybe a watcher. Originally may have been a transferable receipt or key event attachment
This is the attachement version of .processReceiptTrans
- Parameters:
serder (serderKERI) – instance serialized event message to which attachments come from replay (clone)
trqs (list[tuple]) – quadruples of (prefixer, number, diger, siger)
firner (Seqner) – instance of first seen ordinal, if provided lookup event by fn = firner.sn used when in cloned replay mode
local (bool|None) – True means local (protected) event source. False means remote (unprotected). None means use default .local .
- processEscrowDelegables()[source]
Process events escrowed by Kever that require delegation.
Escrowed items are indexed in database table keyed by prefix and sn with duplicates given by different dig inserted in insertion order. This allows FIFO processing of events with same prefix and sn but different digest.
Uses .db.delegables.add(key, val) which is IOVal with dups.
Value is dgkey for event stored in .Evt where .Evt has serder.raw of event.
- Steps:
- Each pass (walk index table)
- For each prefix,sn
- For each escrow item dup at prefix,sn:
Get Event Get and Attach Signatures Process event as if it came in over the wire If successful then remove from escrow table
- processEscrowDuplicitous()[source]
Process events escrowed by Kever that are likely duplicitous. An event is likely duplicitous if a different version of event already has been accepted into the KEL.
Escrowed items are indexed in database table keyed by prefix and sn with duplicates given by different dig inserted in insertion order. This allows FIFO processing of events with same prefix and sn but different digest.
Uses .db.addLde(self, key, val) which is IOVal with dups.
Value is dgkey for event stored in .Evt where .Evt has serder.raw of event.
- Original Escrow steps:
dgkey = dgKey(pre, serder.dig) self.db.dtss.put(keys=dgkey, val=Dater()) self.db.sigs.put(keys=dgkey, vals=sigers) self.db.evts.put(keys=(pre, serder.dig), val=serder) self.db.addLde(snKey(pre, sn), serder.digb) where:
serder is SerderKERI instance of event sigers is list of Siger instance for event pre is str qb64 of identifier prefix of event sn is int sequence number of event
- Steps:
- Each pass (walk index table)
- For each prefix,sn
- For each escrow item dup at prefix,sn:
Get Event Get and Attach Signatures Process event as if it came in over the wire If successful then remove from escrow table
- processEscrowOutOfOrders()[source]
Process events escrowed by Kever that are recieved out-of-order. An event is out of order if its prior event has not been accepted into its KEL. Without the prior event there is no way to know the key state and therefore no way to verify signatures on the out-of-order event.
Escrowed items are indexed in database table keyed by prefix and sn with duplicates given by different dig inserted in insertion order. This allows FIFO processing of events with same prefix and sn but different digest.
Uses .db.ooes.addOn(pre, key, val) which is OnIoVal with dups.
Value is dgkey for event stored in .Evt where .Evt has serder.raw of event.
- Original Escrow steps:
dgkey = dgKey(pre, serder.dig) self.db.dtss.put(keys=dgkey, val=Dater()) self.db.sigs.put(keys=dgkey, vals=sigers) self.db.evts.put(keys=(pre, serder.dig), val=serder) self.db.ooes.addOn(pre, sn, serder.dig)
- where:
serder is SerderKERI instance of event sigers is list of Siger instance for event pre is str qb64 of identifier prefix of event sn is int sequence number of event
- Steps:
- Each pass (walk index table)
- For each prefix,sn
- For each escrow item dup at prefix,sn:
Get Event Get and Attach Signatures Process event as if it came in over the wire If successful then remove from escrow table
- processEscrowPartialDels()[source]
Process delgated events escrowed by Kever that were only partially fulfilled due to missing or unverified delegation seals from delegators. Events only make into this escrow after fully signed and if witnessed fully witnessed.
db.pdes is an instance of subing.IoSetSuber and uses instance methods for access to the underlying database. Escrowed items in .pdes are indexed in database table keyed by prefix and sequence number with multiple entries at same key held in insertion order. This allows FIFO processing of escrowed events with same prefix and sn.
Value in each .pdes entry is dgkey (SAID) of event stored in db.evts where db.evts holds SerderKERI.raw of event.
- Steps:
- Each pass (walk index table)
- For each prefix,sn
- For each escrow item dup at prefix,sn:
Get Event Get and Attach Signatures Get and Attach Witness Signatures Process event as if it came in over the wire If successful then remove from escrow table
- processEscrowPartialSigs()[source]
Process events escrowed by Kever that were only partially fulfilled, either due to missing signatures or missing dependent events like a delegating event. But event has at least one verified signature.
Escrowed items are indexed in database table keyed by prefix and sequence number with duplicates inserted in insertion order. This allows FIFO processing of events with same prefix and sn. Uses .db.pses.addOn(pre, sn, val) which is OnIoVal with dups.
Value is dgkey for event stored in .Evt where .Evt has serder.raw of event.
- Original Escrow steps:
dgkey = dgKey(pre, serder.digb) .db.dtss.put(keys=dgkey, val=Dater()) self.db.sigs.put(keys=dgkey, vals=sigers) .db.evts.put(keys=(pre, serder.digb), val=serder) .db.pses.addOn(pre, sn, serder.digb) where:
serder is SerderKERI instance of event sigers is list of Siger instance for event pre is str qb64 of identifier prefix of event sn is int sequence number of event
- Steps:
- Each pass (walk index table)
- For each prefix,sn
- For each escrow item dup at prefix,sn:
Get Event Get and Attach Signatures Process event as if it came in over the wire If successful then remove from escrow table
- processEscrowPartialWigs()[source]
Process events escrowed by Kever that were only partially fulfilled due to missing signatures from witnesses. Events only make into this escrow after fully signed and if delegated, delegation has been verified.
Escrowed items in .pwes are indexed in database table keyed by prefix and sequence number with duplicates inserted in insertion order. This allows FIFO processing of events with same prefix and sn. Reads db.pwes .db.getPwe put there by .db.pwes.addOn(keys, on, val)
which is IOVal with dups.
Value is dgkey for event stored in .Evt where .Evt has serder.raw of event.
- Original Escrow steps:
dgkey = dgKey(pre, serder.digb) .db.dtss.put(keys=dgkey, val=Dater()) .db.putWigs(dgkey, [siger.qb64b for siger in sigers]) .db.pwes.addOn(pre, sn, serder.digb) .db.evts.put(keys=(pre, serder.digb), val=serder) where:
serder is SerderKERI instance of event wigers is list of Siger instance for of witnesses of event pre is str qb64 of identifier prefix of event sn is int sequence number of event
- Steps:
- Each pass (walk index table)
- For each prefix,sn
- For each escrow item dup at prefix,sn:
Get Event Get and Attach Signatures Get and Attach Witness Signatures Process event as if it came in over the wire If successful then remove from escrow table
- processEscrowUnverNonTrans()[source]
Process escrowed unverified event receipts from nontrans receiptors A receipt is unverified if the associated event has not been accepted into its KEL. Without the event, there is no way to know where to store the receipts.
- The escrow is a triple with edig+rpre+cig where:
edig is event digest rpre is receiptor (signer) of event cig is non-indexed signature by key-pair derived from rpre of event
The verified receipt is just the couple rpre+cig that is stored by event digest edig
Escrowed items are indexed in database table keyed by prefix and sn with duplicates given by different receipt triple inserted in insertion order. This allows FIFO processing of escrows for events with same prefix and sn but different digest.
Uses .db.ures.add(diger,prefixer,cigar)
Value is triple
- Original Escrow steps:
self.db.dtss.put(keys=dgKey(pre, dig), val=Dater()) for cigar in cigars: # escrow each triple
- if cigar.verfer.transferable: # skip transferable verfers
continue # skip invalid couplets
triple = dig.encode(“utf-8”) + cigar.verfer.qb64b + cigar.qb64b self.db.ures.add(keys=(serder.pre, Number(num=serder.sn, code=NumDex.Huge).qb64), val=triple) # should be snKey
- where:
dig is dig in receipt of receipted event cigars is list of cigars instances for receipted event pre is str qb64 of identifier prefix of receipted event sn is int sequence number of receipted event
- Steps:
- Each pass (walk index table)
- For each prefix,sn
- For each escrow item dup at prefix,sn:
Get Event compare dig so same event verify sigs via cigars If successful then remove from escrow table
- processEscrowUnverTrans()[source]
Process event receipts from transferable identifiers (validators) escrowed by Kever that are unverified. A transferable receipt is unverified if either the receipted event has not been accepted into the receipted’s KEL or the establishment event of the receiptor has not been accepted into the receipter’s KEL. Without either event there is no way to know where to store the receipt quadruples.
The escrow is a quintuple with dig+spre+ssnu+sdig+sig the verified receipt is just the quadruple spre+ssnu+sdig+sig that is stored by event dig
Escrowed items are indexed in database table keyed by prefix and sn with duplicates given by different receipt quintuple inserted in insertion order. This allows FIFO processing of escrows of events with same prefix and sn but different digest.
Uses .db.vres.add(key, val) which is IOVal with dups.
Value is quintuple
- Original Escrow steps:
self.db.dtss.put(keys=dgKey(serder.preb, dig), val=Dater()) prelet = (dig.encode(“utf-8”) + seal.i.encode(“utf-8”) +
Seqner(sn=int(seal.s, 16)).qb64b + seal.d.encode(“utf-8”))
- for siger in sigers: # escrow each quintlet
quintuple = prelet + siger.qb64b # quintuple self.db.vres.add(keys=snKey(serder.preb, serder.sn), val=quintuple)
- where:
dig is dig in receipt of receipted event sigers is list of Siger instances for receipted event
- Steps:
- Each pass (walk index table)
- For each prefix,sn
- For each escrow item dup at prefix,sn:
Get Event compare dig so same event verify sigs via sigers If successful then remove from escrow table
- processEscrowUnverWitness()[source]
Process escrowed unverified event receipts from witness receiptors A receipt is unverified if the associated event has not been accepted into its KEL. Without the event, there is no way to know where to store the receipt signatures neither to look up the witness list to verify the indexed signatures.
- The escrow is a couple with edig+wig where:
edig is receipted event digest wig is witness indexed signature by key-pair derived from witness
prefix in associated witness list. Index is offset into witness list of of latest establishment event for receipted event.
The (unescrowed) verified receipt is stored as wig at event digest edig
Escrowed items are indexed in database table keyed by prefix and sn with duplicates given by different receipt couple inserted in insertion order. This allows FIFO processing of escrows for events with same prefix and sn but different digest.
Uses .uwes reads .db.uwes.get() which is B64OnIoDupSuber
Value is couple
- Original Escrow steps:
self.db.dtss.put(keys=dgKey(pre, dig), val=Dater()) for wiger in wigers: # escrow each couple
couple = dig.encode(“utf-8”) + wiger.qb64b self.db.addUwe(key=snKey(pre, sn), val=triple)
- where:
dig is dig in receipt of receipted event wigers is list of Siger instances witness indexed signature of
receipted event
pre is str qb64 of identifier prefix of receipted event sn is int sequence number of receipted event
- Steps:
- Each pass (walk index table)
- For each prefix,sn
- For each escrow item dup at prefix,sn:
Get Event compare dig so same event verify wigs via wigers If successful then remove from escrow table
- processEscrows()[source]
Iterate throush escrows and process any that may now be finalized
Parameters:
- processEvent(serder, sigers, *, wigers=None, delsner=None, delsger=None, firner=None, dater=None, eager=False, local=None, **kwa)[source]
Process one event serder with attached indexd signatures sigers
- Parameters:
serder (SerderKERI) – instance of event to process
sigers (list[Siger]|None) – instances of attached controller indexed sigs
wigers (list[Siger]|None) – instances of attached witness indexed sigs otherwise None
delsner (Number|None) – instance of delegating event sequence number. If this event is not delegated then delnumber is ignored
delsger (Diger|None) – instance of of delegating event SAID diger. If this event is not delegated then deldiger is ignored
firner (Seqner|None) – instance of cloned first seen ordinal If cloned mode then firner maybe provided (not None) When firner provided then compare fn of dater and database and first seen if not match then log and add cue notify problem
dater (Dater|None) – instance of cloned replay datetime If cloned mode then dater maybe provided (not None) When dater provided then use dater for first seen datetime
eager (bool) –
- True means try harder to find validate events by
walking KELs. Enables only being eager in escrow processing not initial parsing.
- False means only use pre-existing information
if any, either percolated attached or in database.
local (bool|None) – True means local (protected) event source. False means remote (unprotected). None means use default .local .
- processMsg(serder, kwa=None)[source]
Process one non-key-event KERI message with attachments.
Consolidated entry point for non-event message types: qry, rpy, pro, bar, xip, exn.
- Processing order:
AID-based allow/deny logic
KRAM processing via self.kramer.intake()
Message-type-specific processing delegation
- Parameters:
serder (SerderKERI) – message instance
kwa (dict | None) – parser exts / attachment dict (sigers, cigars, tsgs, ssgs, sscs, ssts, tdcs, wigers, trqs, frcs, ptds, essrs, bsqs, bsss, tmqs, local, etc.); mutated in place (KRAM normalization, rvy/exc/tvy pops, qry source/sigers). Also accepts processor overrides injected by parser: rvy (Revery), exc (Exchanger), tvy (Tevery)
- processQuery(serder, *, source=None, sigers=None, cigars=None, **kwa)[source]
Process query mode replay message for collective or single element query. Assume promiscuous mode for now.
- Parameters:
serder (SerderKERI)
source (Prefixer)
sigers (list)
cigars (list)
- processQueryNotFound()[source]
Process qry events escrowed by Kevery for KELs that have not yet met the criteria of the query. A missing KEL or criteria for an event in a KEL at a particular sequence number or an event containing a specific anchor can result in query not found escrowed events.
Escrowed items are indexed in database table keyed by prefix and sn with duplicates given by different dig inserted in insertion order. This allows FIFO processing of events with same prefix and sn but different digest.
Uses .db.qnfs.add(key=(pre, said), val) which is IOVal with dups
Value is dgkey for event stored in .Evt where .Evt has serder.raw of event.
- Steps:
- Each pass (walk index table)
- For each prefix,sn
- For each escrow item dup at prefix,sn:
Get Event Get and Attach Signatures Process event as if it came in over the wire If successful then remove from escrow table
- processReceipt(serder, *, cigars=None, wigers=None, tsgs=None, local=None, **kwa)[source]
Process one receipt serder with attached cigars may or may not be a witness receipt. If prefix matches witness then promote to indexed witness signature and store appropriately. Otherwise signature is nontrans nonwitness endorser (watcher etc)
- Parameters:
serder (SerderKERI) – rct instance of serialized receipt message
cigars (list[Cigar]) – instances that contain receipt couple signature in .raw and public key in .verfer
wigers (list[Siger]) – instances that with witness indexed signatures signature in .raw. Index is offset into witness list of latest establishment event for receipted event. Signature uses key pair derived from nontrans witness prefix in associated witness list.
tsgs (list[tuple]) – from extracted transferable indexed sig groups each converted group is tuple of (i,s,d) triple plus list of sigs
local (bool|None) – True means local (protected) event source. False means remote (unprotected). None means use default .local .
- Receipt dict labels
vs # version string pre # qb64 prefix sn # hex string sequence number ilk # rct dig # qb64 digest of receipted event
- processReplyAddWatched(*, serder, diger, route, cigars=None, tsgs=None, **kwa)[source]
Process one reply message for adding an AID for a watcher to watch
Process one reply message for adding an AID for a watcher to watch = /watcher/{aid}/add 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
Reply Message: {
“v” : “KERI10JSON00011c_”, “t” : “rpy”, “d”: “EZ-i0d8JZAoTNZH3ULaU6JR2nmwyvYAfSVPzhzS6b5CM”, “dt”: “2020-08-22T17:50:12.988921+00:00”, “r” : “/watcher/BrHLayDN-mXKv62DAjFLX1_Y5yEUe0vA9YPe_ihiKYHE/add”, “a” : {
“cid”: “EyX-zd8JZAoTNZH3ULaU6JR2nmwyvYAfSVPzhzS6b5CM” “oid”: “EM0-i05TNZJZAoH3UR2nmLaU6JwyvPzhzS6YAfSVbMC5” “oobi”: “http://example.com/oobi/EyX-zd8JZAoTNZH3ULaU6JR2nmwyvYAfSVPzhzS6b5CM”
}
}
- processReplyEndRole(*, serder, diger, route, cigars=None, tsgs=None, **kwargs)[source]
Process one reply message for route = /end/role/add or /end/role/cut 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
- EndpointRecord:
allowed: bool = False # True eid allowed (add), False eid disallowed (cut) name: str = “” # optional user friendly name of endpoint
Reply Message: {
“v” : “KERI10JSON00011c_”, “t” : “rpy”, “d”: “EZ-i0d8JZAoTNZH3ULaU6JR2nmwyvYAfSVPzhzS6b5CM”, “dt”: “2020-08-22T17:50:12.988921+00:00”, “r” : “/end/role/add”, “a” : {
“cid”: “EaU6JR2nmwyZ-i0d8JZAoTNZH3ULvYAfSVPzhzS6b5CM”, “role”: “watcher”, # one of Roles “eid”: “BrHLayDN-mXKv62DAjFLX1_Y5yEUe0vA9YPe_ihiKYHE”,
}
}
- {
“v” : “KERI10JSON00011c_”, “t” : “rpy”, “d”: “EZ-i0d8JZAoTNZH3ULaU6JR2nmwyvYAfSVPzhzS6b5CM”, “dt”: “2020-08-22T17:50:12.988921+00:00”, “r” : “/end/role/cut”, “a” : {
“cid”: “EaU6JR2nmwyZ-i0d8JZAoTNZH3ULvYAfSVPzhzS6b5CM”, “role”: “watcher”, # one of Roles “eid”: “BrHLayDN-mXKv62DAjFLX1_Y5yEUe0vA9YPe_ihiKYHE”,
}
}
- processReplyKeyStateNotice(*, serder, diger, route, cigars=None, tsgs=None, **kwa)[source]
Process one reply message for key state = /ksn
Process one reply message for key state = /ksn 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
Reply Message: {
“v” : “KERI10JSON00011c_”, “t” : “rpy”, “d”: “EZ-i0d8JZAoTNZH3ULaU6JR2nmwyvYAfSVPzhzS6b5CM”, “dt”: “2020-08-22T17:50:12.988921+00:00”, “r” : “/ksn/EeS834LMlGVEOGR8WU3rzZ9M6HUv_vtF32pSXQXKP7jg”, “a” : {
“v”: “KERI10JSON000274_”, “i”: “EeS834LMlGVEOGR8WU3rzZ9M6HUv_vtF32pSXQXKP7jg”, “s”: “1”, “t”: “ksn”, “p”: “ESORkffLV3qHZljOcnijzhCyRT0aXM2XHGVoyd5ST-Iw”, “d”: “EtgNGVxYd6W0LViISr7RSn6ul8Yn92uyj2kiWzt51mHc”, “f”: “1”, “dt”: “2021-11-04T12:55:14.480038+00:00”, “et”: “ixn”, “kt”: “1”, “k”: [
“DTH0PwWwsrcO_4zGe7bUR-LJX_ZGBTRsmP-ZeJ7fVg_4”
], “n”: “E6qpfz7HeczuU3dAd1O9gPPS6-h_dCxZGYhU8UaDY2pc”, “bt”: “3”, “b”: [
“BGKVzj4ve0VSd8z_AmvhLg4lqcC_9WYX90k03q-R_Ydo”, “BuyRFMideczFZoapylLIyCjSdhtqVb31wZkRKvPfNqkw”, “Bgoq68HCmYNUDgOz4Skvlu306o_NY-NrYuKAVhk3Zh9c”
], “c”: [], “ee”: {
“s”: “0”, “d”: “ESORkffLV3qHZljOcnijzhCyRT0aXM2XHGVoyd5ST-Iw”, “br”: [], “ba”: []
}, “di”: “”
}
}
- processReplyLocScheme(*, serder, diger, route, cigars=None, tsgs=None)[source]
Process one reply message for route = /loc/scheme 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
- EndAuthRecord
cid: str = “” # identifier prefix of controller that authorizes endpoint roles: list[str] = field(default_factory=list) # str endpoint roles such as watcher, witness etc
- LocationRecord:
url: str # full url including host:port/path?query scheme is optional cids: list[EndAuthRecord] = field(default_factory=list) # optional authorization record references
Reply Message:
- {
“v” : “KERI10JSON00011c_”, “t” : “rpy”, “d”: “EZ-i0d8JZAoTNZH3ULaU6JR2nmwyvYAfSVPzhzS6b5CM”, “dt”: “2020-08-22T17:50:12.988921+00:00”, “r” : “/loc/scheme”, “a” : {
“eid”: “BrHLayDN-mXKv62DAjFLX1_Y5yEUe0vA9YPe_ihiKYHE”, “scheme”: “http”, # one of Schemes “url”: “http://localhost:8080/watcher/wilma”,
}
}
- {
“v” : “KERI10JSON00011c_”, “t” : “rpy”, “d”: “EZ-i0d8JZAoTNZH3ULaU6JR2nmwyvYAfSVPzhzS6b5CM”, “dt”: “2020-08-22T17:50:12.988921+00:00”, “r” : “/loc/scheme”, “a” : {
“eid”: “BrHLayDN-mXKv62DAjFLX1_Y5yEUe0vA9YPe_ihiKYHE”, “scheme”: “http”, # one of Schemes “url”: “”, # Nullifies
}
}
- registerReplyRoutes(router)[source]
Register the routes for processing messages embedded in rpy event messages
- Parameters:
router (Router) – reply message router
- updateEnd(keys, saider, allowed=None)[source]
Update end auth database .eans and end database .ends.
- Parameters:
keys (tuple) – of key strs for databases (cid, role, eid)
saider (Diger) – instance from said in reply serder (SAD)
allowed (bool) – True allow eid to be endpoint provided False otherwise
- updateKeyState(aid, ksr, saider, dater)[source]
Update Reply SAD in database given by by serder and associated databases for attached cig couple or sig quadruple. Overwrites val at key if already exists.
- updateLoc(keys, saider, url)[source]
Update loc auth database .lans and loc database .locs.
- Parameters:
keys (tuple) – of key strs for databases (eid, scheme)
saider (Diger) – instance from said in reply serder (SAD)
url (str) – endpoint url
- updateWatched(keys, saider, enabled=None)[source]
Update loc auth database .lans and loc database .locs.
- Parameters:
keys (tuple) – of key strs for databases (eid, scheme)
saider (Diger) – instance from said in reply serder (SAD)
enabled (bool) – True means add observed to watcher, False means remove (cut)
- keri.core.eventing.ample(n, f=None, weak=True)[source]
- Returns int as sufficient immune (ample) majority of n when n >=1
otherwise returns 0
- Parameters:
elements (n is int total number of)
number (f is int optional fault)
Boolean (weak is) –
- If f is not None and
weak is True then minimize m for f weak is False then maximize m for f that satisfies n >= 3*f+1
- Else
weak is True then find maximum f and minimize m weak is False then find maximum f and maximize m
n
m
to (f are subject)
0 (f >= 1 if n >)
3*f+1 (n >=)
n-f ((n+f+1)/2 <= m <=)
- keri.core.eventing.bare(pre='', route='', data=None, stamp=None, version=(1, 0), pvrsn=None, gvrsn=None, kind='JSON')[source]
Bare message
- Returns:
serder of bare ‘bar’ message.
- Return type:
bare (SerderKERI)
Utility function to automate creation of unhiding (bareing) messages for disclosure of sealed data associated with anchored seals in a KEL. Reference to anchoring seal is provided as an attachment to bare message. Bare ‘bar’ message is a SAD item with an associated derived SAID in a ‘d’ field in side its ‘a’ block.
- Parameters:
pre (str) – Identifier prefix (AID) of sender controller (Version 2)
route (str) – namesapaced path, ‘/’ delimited, that indicates data flow handler (behavior) to processs the exposure
data (dict) – dict of dicts of comitted SADS for SAIDs in seals keyed by SAID
stamp (str) – date-time-stamp RFC-3339 profile of ISO-8601 datetime of creation of message
version (Versionage) – KERI protocol default version if psvrsn is None
pvrsn (Versionage) – KERI protocol version
gvrsn (Versionage) – CESR genus vrsion
kind – serialization kind value of Serials
Version 1 {
“v” : “KERI10JSON00011c_”, “t” : “bar”, “d”: “EZ-i0d8JZAoTNZH3ULaU6JR2nmwyvYAfSVPzhzS6b5CM”, “dt”: “2020-08-22T17:50:12.988921+00:00”, “r” : “sealed/processor”, “a” :
- {
- “EaU6JR2nmwyZ-i0d8JZAoTNZH3ULvYAfSVPzhzS6b5CM”:
- {
“d”: “EaU6JR2nmwyZ-i0d8JZAoTNZH3ULvYAfSVPzhzS6b5CM”, “i”: “EAoTNZH3ULvYAfSVPzhzS6baU6JR2nmwyZ-i0d8JZ5CM”, “dt”: “2020-08-22T17:50:12.988921+00:00”, “name”: “John Jones”, “role”: “Founder”,
}
}
}
Version 2 {
“v” : “KERI10JSON00011c_”, “t” : “bar”, “d”: “EZ-i0d8JZAoTNZH3ULaU6JR2nmwyvYAfSVPzhzS6b5CM”, “i”: “EaU6JR2nmwyZ-i0d8JZAoTNZH3ULvYAfSVPzhzS6b5CM”, “dt”: “2020-08-22T17:50:12.988921+00:00”, “r” : “sealed/processor”, “a” :
- {
- “EaU6JR2nmwyZ-i0d8JZAoTNZH3ULvYAfSVPzhzS6b5CM”:
- {
“d”: “EaU6JR2nmwyZ-i0d8JZAoTNZH3ULvYAfSVPzhzS6b5CM”, “i”: “EAoTNZH3ULvYAfSVPzhzS6baU6JR2nmwyZ-i0d8JZ5CM”, “dt”: “2020-08-22T17:50:12.988921+00:00”, “name”: “John Jones”, “role”: “Founder”,
}
}
}
- keri.core.eventing.deReceiptCouple(data, strip=False)[source]
Returns tuple of (prefixer, cigar) from concatenated bytes or bytearray of data couple made up of qb64 or qb64b versions of pre+cig where:
pre is nontransferable identifier prefix of receiptor cig is nonindexed signature made with key pair derived from pre
Couple is used for receipts signed by nontransferable prefix keys
- Parameters:
receipt (data is couple of bytes concatenation of pre+sig from)
parsed (strip is Boolean True means delete from data each part as) – Only useful if data is bytearray from front of stream Raises error if not bytearray
- keri.core.eventing.deReceiptTriple(data, strip=False)[source]
Returns tuple of (diger, prefixer, cigar) from concatenated bytes or bytearray of data triple made up of qb64 or qb64b versions of dig+pre+cig where:
dig is receipted event digest pre is nontransferable identifier prefix of receiptor cig is nonindexed signature made with key pair derived from pre
Triple is used for escrows of unverified receipts signed by nontransferable prefix keys
- Parameters:
receipt (data is triple of bytes concatenation of dig+pre+cig from)
parsed (deletive is Boolean True means delete from data each part as) – Only useful if data is bytearray from front of stream
- keri.core.eventing.deSourceCouple(data, strip=False)[source]
Returns tuple of (number, diger) from concatenated bytes or bytearray of data couple made up of qb64 or qb64b versions of snu+dig where:
snu is sn of delegator/issuer source event dig is digest of delegator/issuer source event
Couple is used for delegated/issued event attachment of delegator/issuer evt
- Parameters:
receipt (data is couple of bytes concatenation of pre+sig from)
parsed (strip is Boolean True means delete from data each part as) – Only useful if data is bytearray from front of stream Raises error if not bytearray
- keri.core.eventing.deTransReceiptQuadruple(data, strip=False)[source]
Returns tuple (quadruple) of (prefixer, number, diger, siger) from concatenated bytes or bytearray of quadruple made up of qb64 or qb64b versions of spre+ssnu+sdig+sig. Quadruple is used for receipts signed by transferable prefix keys. Recept for event that is in kel where event is given by context or key
- Parameters:
receipt (quadruple is bytes concatenation of pre+snu+dig+sig from)
parsed (deletive is Boolean True means delete from data each part as) – Only useful if data is bytearray from front of stream
- keri.core.eventing.deTransReceiptQuintuple(data, strip=False)[source]
Returns tuple of (ediger, seal prefixer, seal number, seal diger, siger) from concatenated bytes or bytearray of quintuple made up of qb64 or qb64b versions of quntipuple given by concatenation of edig+spre+ssnu+sdig+sig. Quintuple is used for unverified escrows of validator receipts signed by transferable prefix keys. Receipt for event that is not yet in KEL where event is given by event digest (ediger)
- Parameters:
receipt (quintuple is bytes concatenation of edig+spre+ssnu+sdig+sig from)
parsed (deletive is Boolean True means delete from data each part as) – Only useful if data is bytearray from front of stream
- keri.core.eventing.deWitnessCouple(data, strip=False)[source]
Returns tuple of (diger, wiger) extracted from bytes or bytearray that hold concatenated data couple where:
diger is Diger instance wiger is Siger instance
- Couple is dig+wig where:
dig is receipted event digest wig is indexed signature made with key pair derived from witness nontrans
identifier prefix from witness list. Index is offset into witness list of latest establishment event for receipted event.
- Parameters:
receipt (data is couple of bytes concatenation of dig+wig from)
parsed (deletive is Boolean True means delete from data each part as) – Only useful if data is bytearray from front of stream
Witness couple is used for escrows of unverified witness recipts signed by nontransferable witness prefix keys with indexed signatures where index is offset into associated witness list. At time of escrow receipted event may not be in KEL so need the dig to look up event and then look up witness list from key state.
- keri.core.eventing.delcept(keys, delpre, **kwa)[source]
Returns serder of delegated inception event message. Utility function to automate creation of delegated inception events. Syntactic suger that calls incept but with delpre so ilk is dip.
- Parameters:
keys (list) – current signing keys qb64
isith (int | str | list | None) – current signing threshold input to Tholder
ndigs (list | None) – current signing key digests qb64
None) (nsith int | str | list |) – next signing threshold input to Tholder
toad (int | str | None) – witness threshold number if str then hex str
wits (list | None) – witness identifier prefixes qb64
cnfg (list | None) – configuration traits from TraitDex
data (list | None) – seal dicts
version (Versionage) – KERI protocol default version if psvrsn is None
pvrsn (Versionage) – KERI protocol version
gvrsn (Versionage) – CESR genus vrsion
kind (str) – serialization kind from Serials
code (str | None) – derivation code for computed prefix
intive (bool) – True means sith, nsith, and toad are serialized as ints not hex str when numeric threshold
delpre (str | None) – delegator identifier prefix qb64. When not None makes this a msg type “dip”, delegated inception event.
- keri.core.eventing.deltate(pre, keys, dig, ilk='drt', **kwa)[source]
Returns serder of delegated rotation event message. Utility function to automate creation of delegated rotation events. Syntactic suger that calls rotate but with ilk set to drt.
- Inherited Parameters:
pre (str): identifier prefix qb64 keys (list): current signing keys qb64 dig (str): said of previous event qb64 ilk (str): ilk of event. Must be in (Ilks.rot, Ilks.drt) sn (int | str): sequence number int or hex str isith (int | str | list): current signing threshold input to Tholder ndigs (list): current signing key digests qb64 nsith int | str | list): next signing threshold input to Tholder toad (int | str ): witness threshold number if str then hex str wits (list): prior witness identifier prefixes qb64 cuts (list): witness prefixes to cut qb64 adds (list): witness prefixes to add qb64 cnfg (list | None): configuration traits from TraitDex data (list): seal dicts version (Versionage): KERI protocol default version if psvrsn is None pvrsn (Versionage): KERI protocol version gvrsn (Versionage): CESR genus vrsion kind (str): serialization kind from Serials intive (bool): True means sith, nsith, and toad are serialized as ints
not hex str when numeric threshold
- keri.core.eventing.exchange(*, sender='', receiver='', xid='', prior='', route='', modifiers=None, attributes=None, stamp=None, version=(1, 0), pvrsn=None, gvrsn=None, kind='JSON')[source]
Create an exn message with the specified route and payload
- 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”)
- keri.core.eventing.exchept(sender='', receiver='', route='', modifiers=None, attributes=None, nonce=None, stamp=None, version=(2, 0), pvrsn=None, gvrsn=None, kind='JSON')[source]
Utility function to automate creation of exchange incept, exchept, ‘xip’, message. The exchept ‘xip’ message is a SAD item with an associated derived SAID in its ‘d’ field. Only defined for KERI v2.
- Returns:
‘xip’ message.
- Return type:
exchept (SerderKERI)
Fields in order: (v, t, d, u, ri, dt, r, q, a),
- Parameters:
sender (str) – qb64 of sender identifier (AID)
receiver (str) – qb64 of receiver identifier (AID)
route (str) – ‘/’ delimited path identifier of data flow handler (behavior) to processs the reply if any
modifiers (dict) – modifiers
attributes (dict) – attributes
nonce (str|None) – qb64 of UUID salty nonce. When None generate nonce.
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 vrsion
kind (str) – serialization kind value of Serials
Version 2: {
“v” : “KERI10JSON00011c_”, “t” : “rpy”, “d”: “EZ-i0d8JZAoTNZH3ULaU6JR2nmwyvYAfSVPzhzS6b5CM”, “u”: ‘0AAwMTIzNDU2Nzg5YWJjZGVm’, “i”: “EAoTNZH3ULvYAfSVPzhzS6baU6JR2nmwyZ-i0d8JZ5CM”, “ri”: “EBPzhzS6baU6JR2nmwyZ-i0d8JZ5CMAoTNZH3ULvYAfS”, “dt”: “2020-08-22T17:50:12.988921+00:00”, “r” : “/logs/processor”, “q”: {
“name”: “Zoe”, “color”: “Blue”
} “a”: {
“d”: “EaU6JR2nmwyZ-i0d8JZAoTNZH3ULvYAfSVPzhzS6b5CM”
}
}
- keri.core.eventing.incept(keys, *, isith=None, ndigs=None, nsith=None, toad=None, wits=None, cnfg=None, data=None, version=(1, 0), pvrsn=None, gvrsn=None, kind='CESR', code=None, intive=False, delpre=None)[source]
Returns serder of inception event message. Utility function to automate creation of inception events.
- Parameters:
keys (list) – current signing keys qb64
isith (int | str | list | None) – current signing threshold input to Tholder
ndigs (list | None) – current signing key digests qb64
nsith (int | str | list | None) – next signing threshold input to Tholder
toad (int | str | None) – witness threshold number if str then hex str
wits (list | None) – witness identifier prefixes qb64
cnfg (list | None) – configuration traits from TraitDex
data (list | None) – seal dicts
version (Versionage) – KERI protocol default version if psvrsn is None
pvrsn (Versionage) – KERI protocol version
gvrsn (Versionage) – CESR genus vrsion
kind (str) – serialization kind from Serials
code (str | None) – derivation code for computed prefix
intive (bool) – True means sith, nsith, and toad are serialized as ints not hex str when numeric threshold. Most compact JSON representation when Numbers are small because no quotes. Number accepts both.
delpre (str | None) – delegator identifier prefix qb64. When not None makes this a msg type “dip”, delegated inception event.
- keri.core.eventing.interact(pre, dig, sn=1, data=None, version=(1, 0), pvrsn=None, gvrsn=None, kind='CESR')[source]
Returns serder of interaction event message. Utility function to automate creation of interaction events.
- Parameters:
pre is identifier prefix qb64 dig is said digest of previous event qb64 sn is int sequence number data is list of dicts of comitted data such as seals version (Versionage): KERI protocol default version if psvrsn is None pvrsn (Versionage): KERI protocol version gvrsn (Versionage): CESR genus vrsion kind is serialization kind
- keri.core.eventing.loadEvent(db, preb, dig)[source]
Load event details from database
- Parameters:
db (Baser) – database to load event fro,
preb (bytes) – qb64b identifier prefix
dig (bytes) – digest of event to load
- Returns:
data from event
- Return type:
dict
- keri.core.eventing.messagize(serder, *, sigers=None, source=None, bonds=None, wigers=None, cigars=None, framed=False, nested=False, gvrsn=(1, 0), genusify=False)[source]
Attaches authenticator(s) from sigers (with or without source as seal) and/or cigars and/or wigers and/or bonds. A bond is typically a seal reference to an event with anchoring seal of message as authenticator. In v2 bonds may also include any Structor subclass not simply seal references.
- Parameters::
serder (SerderKERI): instance containing the event sigers (list): of Siger instances (optional) to create indexed signatures
based on seal type if any
- 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 each message plus attachments may be assumed to
be isolated as frame when parsing so do not need attachment group
- False means use attachment group since message plus
attachments may not be isolated as frame when parsing
- 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): KERI event with attachments if any
- keri.core.eventing.prod(pre='', route='', replyRoute='', query=None, stamp=None, version=(1, 0), pvrsn=None, gvrsn=None, kind='JSON')[source]
Prod message
- Returns:
of prod, ‘pro’, msg to request disclosure via bare, ‘bar’ msg
- Return type:
prod (SerderKERI)
of data anchored via seal(s) on KEL for identifier prefix, pre, when given by all SAIDs given in digs list.
- Parameters:
pre (str) – Identifier prefix (AID) of sender controller (Version 2)
route (str) – namesapaced path, ‘/’ delimited, that indicates data flow handler (behavior) to processs the query
replyRoute (str) – namesapaced path, ‘/’ delimited, that indicates data flow handler (behavior) to processs reply message to query if any.
query (dict) – query data paramaters modifiers
stamp (str) – date-time-stamp RFC-3339 profile of ISO-8601 datetime of creation of message
version (Versionage) – KERI protocol default version if psvrsn is None
pvrsn (Versionage) – KERI protocol version
gvrsn (Versionage) – CESR genus vrsion
kind (str) – serialization kind value of Serials
Version 1 {
“v” : “KERI10JSON00011c_”, “t” : “pro”, “d”: “EZ-i0d8JZAoTNZH3ULaU6JR2nmwyvYAfSVPzhzS6b5CM”, “dt”: “2020-08-22T17:50:12.988921+00:00”, “r” : “data”, “rr”: “data/processor”, “q”: {
“d”:”EaU6JR2nmwyZ-i0d8JZAoTNZH3ULvYAfSVPzhzS6b5CM”
}
}
Version 2
- {
“v” : “KERI10JSON00011c_”, “t” : “pro”, “d”: “EZ-i0d8JZAoTNZH3ULaU6JR2nmwyvYAfSVPzhzS6b5CM”, “i”: “EaU6JR2nmwyZ-i0d8JZAoTNZH3ULvYAfSVPzhzS6b5CM”, “dt”: “2020-08-22T17:50:12.988921+00:00”, “r” : “data”, “rr”: “data/processor”, “q”: {
“d”:”EaU6JR2nmwyZ-i0d8JZAoTNZH3ULvYAfSVPzhzS6b5CM”
}
}
- keri.core.eventing.query(pre='', route='', replyRoute='', query=None, stamp=None, version=(1, 0), pvrsn=None, gvrsn=None, kind='JSON')[source]
Returns serder of query ‘qry’ message. Utility function to automate creation of query messages.
- Parameters:
pre (str) – Identifier prefix (AID) of sender controller (Version 2)
route (str) – namesapaced path, ‘/’ delimited, that indicates data flow handler (behavior) to processs the query
replyRoute (str) – namesapaced path, ‘/’ delimited, that indicates data flow handler (behavior) to processs reply message to query if any.
query (dict) – query data paramaters modifiers
stamp (str) – date-time-stamp RFC-3339 profile of ISO-8601 datetime of creation of message
version (Versionage) – KERI protocol default version if psvrsn is None
pvrsn (Versionage) – KERI protocol version
gvrsn (Versionage) – CESR genus vrsion
kind (str) – serialization kind value of Serials
Version 1.0 {
“v” : “KERI10JSON00011c_”, “t” : “qry”, “d”: “EZ-i0d8JZAoTNZH3ULaU6JR2nmwyvYAfSVPzhzS6b5CM”, “dt”: “2020-08-22T17:50:12.988921+00:00”, “r” : “logs”, “rr”: “log/processor”, “q” : {
“i”: “EaU6JR2nmwyZ-i0d8JZAoTNZH3ULvYAfSVPzhzS6b5CM”, “sn”: “5”, “dt”: “2020-08-01T12:20:05.123456+00:00”,
}
}
Version 2.0 {
“v” : “KERI10JSON00011c_”, “t” : “qry”, “d”: “EZ-i0d8JZAoTNZH3ULaU6JR2nmwyvYAfSVPzhzS6b5CM”, “i”: “EaU6JR2nmwyZ-i0d8JZAoTNZH3ULvYAfSVPzhzS6b5CM” “dt”: “2020-08-22T17:50:12.988921+00:00”, “r” : “logs”, “rr”: “log/processor”, “q” : {
“i”: “EaU6JR2nmwyZ-i0d8JZAoTNZH3ULvYAfSVPzhzS6b5CM”, “sn”: “5”, “dt”: “2020-08-01T12:20:05.123456+00:00”,
}
}
- keri.core.eventing.receipt(pre, sn, said, *, version=(1, 0), pvrsn=None, gvrsn=None, kind='CESR')[source]
Returns serder of event receipt message. Used for both non-trans and trans signers as determined by signature attachment type (cigar or siger)
Utility function to automate creation of receipts.
- Parameters:
pre is qb64 str of prefix of event being receipted sn is int sequence number of event being receipted said is qb64 of said of event being receipted version (Versionage): KERI protocol default version if psvrsn is None pvrsn (Versionage): KERI protocol version gvrsn (Versionage): CESR genus vrsion kind is serialization kind of receipt
- keri.core.eventing.reply(pre='', route='', data=None, stamp=None, version=(1, 0), pvrsn=None, gvrsn=None, kind='JSON')[source]
Returns serder of reply ‘rpy’ message. Utility function to automate creation of reply messages. Reply ‘rpy’ message is a SAD item with an associated derived SAID in its ‘d’ field.
- Parameters:
pre (str) – identifier prefix of sender (AID)
route (str) – ‘/’ delimited path identifier of data flow handler (behavior) to processs the reply if any
data (dict) – attribute section of reply
stamp (str) – date-time-stamp RFC-3339 profile of ISO-8601 datetime of creation of message or data
version (Versionage) – KERI protocol default version if psvrsn is None
pvrsn (Versionage) – KERI protocol version
gvrsn (Versionage) – CESR genus vrsion
kind (str) – serialization kind value of Serials
Version 1: {
“v” : “KERI10JSON00011c_”, “t” : “rpy”, “d”: “EZ-i0d8JZAoTNZH3ULaU6JR2nmwyvYAfSVPzhzS6b5CM”, “dt”: “2020-08-22T17:50:12.988921+00:00”, “r” : “logs/processor”, “a” : {
“d”: “EaU6JR2nmwyZ-i0d8JZAoTNZH3ULvYAfSVPzhzS6b5CM”, “i”: “EAoTNZH3ULvYAfSVPzhzS6baU6JR2nmwyZ-i0d8JZ5CM”, “name”: “John Jones”, “role”: “Founder”,
}
}
Version 2: {
“v” : “KERI10JSON00011c_”, “t” : “rpy”, “d”: “EZ-i0d8JZAoTNZH3ULaU6JR2nmwyvYAfSVPzhzS6b5CM”, “i”: “EAoTNZH3ULvYAfSVPzhzS6baU6JR2nmwyZ-i0d8JZ5CM”, “dt”: “2020-08-22T17:50:12.988921+00:00”, “r” : “logs/processor”, “a” : {
“d”: “EaU6JR2nmwyZ-i0d8JZAoTNZH3ULvYAfSVPzhzS6b5CM”, “i”: “EAoTNZH3ULvYAfSVPzhzS6baU6JR2nmwyZ-i0d8JZ5CM”, “name”: “John Jones”, “role”: “Founder”,
}
}
- keri.core.eventing.rotate(pre, keys, dig, *, ilk='rot', sn=1, isith=None, ndigs=None, nsith=None, toad=None, wits=None, cuts=None, adds=None, cnfg=None, data=None, version=(1, 0), pvrsn=None, gvrsn=None, kind='CESR', intive=False)[source]
Returns serder of rotation event message. Utility function to automate creation of rotation events.
- Parameters:
pre (str) – identifier prefix qb64
keys (list) – current signing keys qb64
dig (str) – SAID of previous event qb64
ilk (str) – ilk of event. Must be in (Ilks.rot, Ilks.drt)
sn (int | str) – sequence number int or hex str
isith (int | str | list | None) – current signing threshold input to Tholder
ndigs (list | None) – current signing key digests qb64
nsith (int | str | list | None) – next signing threshold input to Tholder
toad (int | str | None) – witness threshold number if str then hex str
wits (list | None) – prior witness identifier prefixes qb64
cuts (list | None) – witness prefixes to cut qb64
adds (list | None) – witness prefixes to add qb64
cnfg (list | None) – configuration traits from TraitDex
data (list | None) – seal dicts
version (Versionage) – KERI protocol default version if psvrsn is None
pvrsn (Versionage) – KERI protocol version
gvrsn (Versionage) – CESR genus vrsion
kind (str) – serialization kind from Serials
intive (bool) – True means sith, nsith, and toad are serialized as ints instead of hex str when numeric threshold
- keri.core.eventing.simple(n)[source]
- Returns int as simple majority of n when n >=1
otherwise returns 0
- Parameters:
elements (n is int total number of)
- keri.core.eventing.state(pre, sn, pig, dig, fn, eilk, keys, eevt, stamp=None, sith=None, ndigs=None, nsith=None, toad=None, wits=None, cnfg=None, dpre=None, version=(1, 0), kind='JSON', intive=False)[source]
Returns instance of KeyStateRecord in support of key state notification messages. Utility function to automate creation embedded key static notices
- Parameters:
pre (str) – identifier prefix qb64
sn (int) – sequence number of latest event
pig (str) – SAID qb64 of prior event
dig (str) – SAID qb64 of latest (current) event
fn (int) – first seen ordinal number of latest event
eilk (str) – event (message) type (ilk) of latest (current) event
keys (list) – qb64 signing keys
eevt (StateEstEvent) – namedtuple (s,d,wr,wa) for latest est event s = sn of est event d = SAID of est event wr = witness remove list (cuts) wa = witness add list (adds)
stamp (str | None) – date-time-stamp RFC-3339 profile of ISO-8601 datetime of creation of message or data
sith (sith) – current signing threshold input to Tholder
ndigs (list | None) – current signing key digests qb64
None) (nsith int | str | list |) – next signing threshold input to Tholder
toad (int | str | None) – witness threshold number if str then hex str
wits (list | None) – prior witness identifier prefixes qb64
cnfg (list | None) – strings from TraitDex configuration trait strings
dpre (str | None) – identifier prefix qb64 delegator if any If None then dpre in state is empty “”
version (Version) – KERI protocol version string
kind (str) – serialization kind from Serials
intive (bool) – True means sith, nsith, and toad are serialized as ints instead of hex str when numeric threshold
- keri.core.eventing.validateSigs(serder, sigers, verfers, tholder)[source]
Validates signatures given by sigers using keys given by verfers on msg given by serder subject to threshold given by tholder. Returns subset of valid signatures for storage.
- Returns:
- (sigers, valid) where:
- sigers (list): subset of of provided sigers of verified signatures
on serder using verfers
- valid (bool): True means threshold from tholder satisfied by sigers,
False otherwise.
- Return type:
result (tuple)
- Parameters:
serder (SerderKERI) – instance of message
sigers (Iterable) – Siger instances of indexed signatures. Index is offset into verfers list each providing verification key
verfers (Iterable) – Verfer instances of keys
tholder (Tholder) – instance of signing threshold (sith)
number. (seqner is Seqner instance of delegating event sequence) – If this event is not delegated then seqner is ignored
digest. (diger is Diger instance of of delegating event) – If this event is not delegated then diger is ignored
- keri.core.eventing.verifySigs(raw, sigers, verfers)[source]
- Returns tuple of (vsigers, vindices) where:
vsigers is list of unique verified sigers with assigned verfer vindices is list of indices from those verified sigers
The returned vsigers and vindices may be used for threshold validation
Assigns appropriate verfer from verfers to each siger based on siger index If no signatures verify then sigers and indices are empty
- Parameters:
raw (bytes)
instances (sigers is list of indexed Siger)
instance (verfers is list of Verfer)
ker.core.indexing
keri.core.indexing module
Provides versioning support for Indexer classes and codes
- class keri.core.indexing.IndexedBothSigCodex(Ed25519_Sig: str = 'A', ECDSA_256k1_Sig: str = 'C', ECDSA_256r1_Sig: str = 'E', Ed448_Sig: str = '0A', Ed25519_Big_Sig: str = '2A', ECDSA_256k1_Big_Sig: str = '2C', ECDSA_256r1_Big_Sig: str = '2E', Ed448_Big_Sig: str = '3A')[source]
IndexedBothSigCodex is codex indexed signature codes for both lists.
Only provide defined codes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
- class keri.core.indexing.IndexedCurrentSigCodex(Ed25519_Crt_Sig: str = 'B', ECDSA_256k1_Crt_Sig: str = 'D', ECDSA_256r1_Crt_Sig: str = 'F', Ed448_Crt_Sig: str = '0B', Ed25519_Big_Crt_Sig: str = '2B', ECDSA_256k1_Big_Crt_Sig: str = '2D', ECDSA_256r1_Big_Crt_Sig: str = '2F', Ed448_Big_Crt_Sig: str = '3B')[source]
IndexedCurrentSigCodex is codex indexed signature codes for current list.
Only provide defined codes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
- class keri.core.indexing.IndexedSigCodex(Ed25519_Sig: str = 'A', Ed25519_Crt_Sig: str = 'B', ECDSA_256k1_Sig: str = 'C', ECDSA_256k1_Crt_Sig: str = 'D', ECDSA_256r1_Sig: str = 'E', ECDSA_256r1_Crt_Sig: str = 'F', Ed448_Sig: str = '0A', Ed448_Crt_Sig: str = '0B', Ed25519_Big_Sig: str = '2A', Ed25519_Big_Crt_Sig: str = '2B', ECDSA_256k1_Big_Sig: str = '2C', ECDSA_256k1_Big_Crt_Sig: str = '2D', ECDSA_256r1_Big_Sig: str = '2E', ECDSA_256r1_Big_Crt_Sig: str = '2F', Ed448_Big_Sig: str = '3A', Ed448_Big_Crt_Sig: str = '3B')[source]
IndexedSigCodex is codex all indexed signature derivation codes.
Only provide defined codes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
- class keri.core.indexing.Indexer(raw=None, code='A', index=0, ondex=None, qb64b=None, qb64=None, qb2=None, strip=False, **kwa)[source]
Indexer is fully qualified cryptographic material primitive base class for indexed primitives. In special cases some codes in the Index code table may be of variable length (i.e. not indexed) when the full size table entry is None. In that case the index is used instread as the length.
Sub classes are derivation code and key event element context specific.
Includes the following attributes and properties:
Attributes:
- Properties:
code is str of stable (hard) part of derivation code raw (bytes): unqualified crypto material usable for crypto operations index (int): main index offset into list or length of material ondex (int | None): other index offset into list or length of material qb64b (bytes): fully qualified Base64 crypto material qb64 (str | bytes): fully qualified Base64 crypto material qb2 (bytes): fully qualified binary crypto material
- Hidden:
._code (str): value for .code property ._raw (bytes): value for .raw property ._index (int): value for .index property ._ondex (int): value for .ondex property ._infil is method to compute fully qualified Base64 from .raw and .code ._binfil is method to compute fully qualified Base2 from .raw and .code ._exfil is method to extract .code and .raw from fully qualified Base64 ._bexfil is method to extract .code and .raw from fully qualified Base2
- __init__(raw=None, code='A', index=0, ondex=None, qb64b=None, qb64=None, qb2=None, strip=False, **kwa)[source]
Validate as fully qualified.
- Parameters:
raw (bytes) – unqualified crypto material usable for crypto operations
code (str) – stable (hard) part of derivation code
index (int) – main index offset into list or length of material
ondex (int | None) – other index offset into list or length of material
qb64b (bytes) – fully qualified Base64 crypto material
qb64 (str | bytes) – fully qualified Base64 crypto material
qb2 (bytes) – fully qualified binary crypto material
strip (bool) – True means strip counter contents from input stream bytearray after parsing qb64b or qb2. False means do not strip
Notes
Needs either (raw and code and index) or qb64b or qb64 or qb2. Otherwise raises EmptyMaterialError. When raw and code provided then validate that code is correct for length of raw and assign .raw. Else when qb64b or qb64 or qb2 provided extract and assign .raw, .code, .index, .ondex.
- property code
Returns ._code Makes .code read only
- property index
Returns ._index Makes .index read only
- property name
Returns: name (str): code name for self.code. Used for annotation for primitives like Matter
- property ondex
Returns ._ondex Makes .ondex read only
- property qb2
Property qb2: Returns Fully Qualified Binary Version Bytes
- property qb64
Property qb64: Returns Fully Qualified Base64 Version Assumes self.raw and self.code are correctly populated
- property qb64b
Property qb64b: Returns Fully Qualified Base64 Version encoded as bytes Assumes self.raw and self.code are correctly populated
- property raw
Returns ._raw Makes .raw read only
- class keri.core.indexing.IndexerCodex(Ed25519_Sig: str = 'A', Ed25519_Crt_Sig: str = 'B', ECDSA_256k1_Sig: str = 'C', ECDSA_256k1_Crt_Sig: str = 'D', ECDSA_256r1_Sig: str = 'E', ECDSA_256r1_Crt_Sig: str = 'F', Ed448_Sig: str = '0A', Ed448_Crt_Sig: str = '0B', Ed25519_Big_Sig: str = '2A', Ed25519_Big_Crt_Sig: str = '2B', ECDSA_256k1_Big_Sig: str = '2C', ECDSA_256k1_Big_Crt_Sig: str = '2D', ECDSA_256r1_Big_Sig: str = '2E', ECDSA_256r1_Big_Crt_Sig: str = '2F', Ed448_Big_Sig: str = '3A', Ed448_Big_Crt_Sig: str = '3B', TBD0: str = '0z', TBD1: str = '1z', TBD4: str = '4z')[source]
IndexerCodex is codex hard (stable) part of all indexer derivation codes.
Codes indicate which list of keys, current and/or prior next, index is for:
- _Sig: Indices in code may appear in both current signing and
prior next key lists when event has both current and prior next key lists. Two character code table has only one index so must be the same for both lists. Other index if for prior next. The indices may be different in those code tables which have two sets of indices.
_Crt_Sig: Index in code for current signing key list only.
_Big_: Big index values
Only provide defined codes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
- class keri.core.indexing.Siger(verfer=None, **kwa)[source]
Siger is subclass of Indexer, indexed signature material,
- Adds .verfer property which is instance of Verfer that provides
associated signature verifier.
See Indexer for inherited attributes and properties:
Attributes:
- Properties:
verfer (Verfer): instance if any provides public verification key
Methods:
- Hidden:
_verfer (Verfer): value for .verfer property
- __init__(verfer=None, **kwa)[source]
Initialze instance
- Parameters: See Matter for inherted parameters
verfer (Verfer): instance if any provides public verification key
- property verfer
Property verfer: Returns Verfer instance Assumes ._verfer is correctly assigned
keri.core.parsing
keri.core.parsing module
message stream parsing support
- class keri.core.parsing.Parser(ims=None, framed=True, piped=False, kvy=None, tvy=None, exc=None, rvy=None, vry=None, local=False, version=(2, 0))[source]
Parser is stream parser that processes an incoming message stream. Each message in the stream is composed of a message body with a message foot The message body includes a version string. The message foot is composed of composable concatenated attachments encoded in CESR (Composable Event Streaming Representation) CESR supports both binary and text formats where text is Base64 URL/Filesafe. The attachements in a CESR foot may be converted and round tripped en-masse between binary and text (Base64 URL/File). CESR encoding ensures alignment on 24 bit boundaries.
Only supports current version VERSION
Has the following public attributes and properties:
- ims
incoming message stream
- Type:
bytearray
- framed
True means stream is packet framed
- Type:
bool
- piped
True means use pipeline processor to process whenever stream includes pipelineable group count codes.
- Type:
bool
- vry
credential verifier with wallet storage
- Type:
Verfifier
- local
True means event source is local (protected) for validation False means event source is remote (unprotected) for validation
- Type:
bool
- Properties:
genus (str): genus portion of default CESR code table protocol genus code version (Versionage): current CESR protocol genus version in context methods (dict): method names for counter extraction, keyed by count code name codes (CtrDex): selected by .version from (CtrDex_1_0, CtrDex_2_0) sucodes (SUDex): selected by .version from (SUDex_1_0, SUDex_2_0) mucodes (MUDex): selected by .version from (MUDex_1_0, MUDex_2_0)
- Hidden:
_version (Versionage): value for .version property _genus (str): value for .genus property
_methods (dict): value for .methods property _codes (CtrDex): value for .codes property _sucodes (SUDex): value for .sucodes property _mucodes (MUDex): value for .mucodes property
- __init__(ims=None, framed=True, piped=False, kvy=None, tvy=None, exc=None, rvy=None, vry=None, local=False, version=(2, 0))[source]
Initialize instance:
- Parameters:
ims (bytearray) – incoming message stream
framed (bool) – True means ims contains only one msg body plus its foot of attachments, not multiple sets of msg body plus foot
piped (bool) – True means use pipeline processor to process ims msgs when stream includes pipelined count codes.
kvy (Kevery) – route KEL message types to this instance
tvy (Tevery) – route TEL message types to this instance
exc (Exchanger) – route EXN message types to this instance
rvy (Revery) – reply (RPY) message handler
vry (
Verfifier) – credential verifier with wallet storagelocal (bool) – True means event source is local (protected) for validation False means event source is remote (unprotected) for validation
version (Versionage) – instance of version portion of genus version code for default code table
- allParsator(ims=None, framed=None, piped=None, kvy=None, tvy=None, exc=None, rvy=None, vry=None, local=None, version=None)[source]
Returns generator to parse all messages from incoming message stream, ims until ims is exhausted (empty) then returns. Generator completes as soon as ims is empty. If ims not provided then parse messages from .ims
- Parameters:
ims (bytearray) – of incoming message stream. May contain one or more sets each of a serialized message with attached cryptographic material such as signatures or receipts.
framed (bool) – True means ims contains only one frame of msg plus counted attachments instead of stream with multiple messages
piped (bool) – True means use pipeline processor to process ims msgs when stream includes pipelineable count codes.
kvy (Kevery) – route KERI KEL message types to this instance
tvy (Tevery) – route TEL message types to this instance
exc (Exchanger)
rvy (Revery) – reply (RPY) message handler
vry (Verfifier) – credential verifier with wallet storage
local (bool) – True means event source is local (protected) for validation False means event source is remote (unprotected) for validation None means use default .local
version (Versionage) – default version of CESR to use None means do not change default
- New Logic:
Attachments must all have counters so know if txt or bny format for attachments. So even when framed==True must still have counters.
- property codes
Makes .codes read only :returns: selected by .version from (CtrDex_1_0, CtrDex_2_0) :rtype: _codes (CtrDex)
- extract(ims, klas, cold='txt')[source]
Extract and return instance of klas from input message stream, ims, given stream state, cold, is txt or bny. Inits klas from ims using qb64b or qb2 parameter based on cold.
- property genus
Makes .genus read only Returns ._genus
- groupParsator(ims=None, framed=True, piped=False, kvy=None, tvy=None, exc=None, rvy=None, vry=None, local=None, version=None)[source]
Returns generator to parse nested GenericGroups whose outermost nesting appears at the top-lever of an incoming message stream.
If ims not provided then parse messages from .ims
- Parameters:
ims (bytearray) – of incoming message stream. May contain one or more sets each of a serialized message with attached cryptographic material such as signatures or receipts.
framed (bool) – True means ims contains only one frame of msg plus counted attachments instead of stream with multiple messages
piped (bool) – True means use pipeline processor to process ims msgs when stream includes pipelineable count codes.
kvy (Kevery) – route KERI KEL message types to this instance
tvy (Tevery) – route TEL message types to this instance
exc (Exchanger)
rvy (Revery) – reply (RPY) message handler
vry (Verfifier) – credential verifier with wallet storage
local (bool) – True means event source is local (protected) for validation False means event source is remote (unprotected) for validation None means use default .local
version (Versionage) – default version of CESR to use None means do not change default
- property methods
Gets methods from .Methods for .version current version in stream context :returns: method names for counter extraction, keyed by count code name :rtype: methods (dict)
- msgParsator(ims=None, framed=True, piped=False, kvy=None, tvy=None, exc=None, rvy=None, vry=None, local=None, version=None)[source]
Returns generator that upon each iteration extracts and parses msg with attached crypto material (signature etc) from incoming message stream, ims, and dispatches processing of message with attachments.
Uses .ims when ims is not provided.
Iterator yields when not enough bytes in ims to finish one msg plus attachments. Returns (which raises StopIteration) when finished.
- Parameters:
ims (bytearray) – serialized incoming message stream. May contain one or more sets each of a serialized message with attached cryptographic material such as signatures or receipts.
framed (bool) – True means ims contains only one frame of msg plus counted attachments instead of stream with multiple messages
piped (bool) – True means use pipeline processor to process ims msgs when stream includes pipelineable count codes.
kvy (Kevery) – route KERI KEL message types to this instance
tvy (Tevery) – route TEL message types to this instance
exc (Exchanger) – route EXN message types to this instance
rvy (Revery) – reply (RPY) message handler
vry (Verifier) – ACDC credential processor
local (bool) – True means event source is local (protected) for validation False means event source is remote (unprotected) for validation None means use default .local
version (
Versionage) – default version of CESR to use. None means do not change default
Logic:
Currently only support couters on attachments not on combined or on message Attachments must all have counters so know if txt or bny format for attachments. So even when framed==True must still have counter. Do While loop sniff to set up first extraction raise exception and flush full tream if stream start is counter must be message extract message sniff for counter if group counter extract and discard but keep track of count so if error while processing attachments then only need to flush attachment count not full stream.
- property mucodes
Makes .mucodes read only :returns: selected by .version from (MUDex_1_0, MUDex_2_0) :rtype: _mucodes (MUDex)
- onceParsator(ims=None, framed=None, piped=None, kvy=None, tvy=None, exc=None, rvy=None, vry=None, local=None, version=None)[source]
Returns generator to parse one message from incoming message stream, ims. If ims not provided parse messages from .ims
- Parameters:
ims (bytearray) – incoming message stream. May contain one or more sets each of a serialized message with attached cryptographic material such as signatures or receipts.
framed (bool) – True means ims contains only one frame of msg plus counted attachments instead of stream with multiple messages
piped (bool) – True means use pipeline processor to process ims msgs when stream includes pipelineable count codes.
kvy (Kevery) – route KERI KEL message types to this instance
tvy (Tevery) – route TEL message types to this instance
exc (Exchanger)
rvy (Revery) – reply (RPY) message handler
vry (Verfifier) – credential verifier with wallet storage
local (bool) – True means event source is local (protected) for validation False means event source is remote (unprotected) for validation None means use default .local
version (Versionage) – default version of CESR to use None means do not change default
- New Logic:
Attachments must all have counters so know if txt or bny format for attachments. So even when framed==True must still have counters.
- parsator(ims=None, framed=None, piped=None, kvy=None, tvy=None, exc=None, rvy=None, vry=None, local=None, version=None)[source]
Returns generator to continually parse messages from incoming message stream, ims. Empty yields when ims is emply. Does not return. Useful for always running servers. One yield from per each message if any. Continually yields while ims is empty, i.e. does not return. If ims not provided then parse messages from .ims
- Parameters:
ims (bytearray) – incoming message stream. May contain one or more sets each of a serialized message with attached cryptographic material such as signatures or receipts.
framed (bool) – True means ims contains only one frame of msg plus counted attachments instead of stream with multiple messages
piped (bool) – True means use pipeline processor to process ims msgs when stream includes pipelineable count codes.
kvy (Kevery) – route KERI KEL message types to this instance
tvy (Tevery) – route TEL message types to this instance
exc (Exchanger)
rvy (Revery) – reply (RPY) message handler
vry (Verifier) – credential processor
local (bool) – True means event source is local (protected) for validation False means event source is remote (unprotected) for validation None means use default .local
version (Versionage) – default version of CESR to use None means do not change default
- New Logic:
Attachments must all have counters so know if txt or bny format for attachments. So even when framed==True must still have counters.
- parse(ims=None, framed=None, piped=None, kvy=None, tvy=None, exc=None, rvy=None, vry=None, local=None, version=None)[source]
Processes all messages from incoming message stream, ims, when provided. Otherwise process messages from .ims Returns when ims is empty. Convenience executor for .allParsatator when ims is not live, i.e. fixed
- Parameters:
ims (bytearray) – incoming message stream. May contain one or more sets each of a serialized message with attached cryptographic material such as signatures or receipts.
framed (bool) – True means ims contains only one frame of msg plus counted attachments instead of stream with multiple messages
piped (bool) – True means use pipeline processor to process ims msgs when stream incpyludes pipelineable count codes.
kvy (Kevery) – route KERI KEL message types to this instance
tvy (Tevery) – route TEL message types to this instance
exc (Exchanger)
rvy (Revery) – reply (RPY) message handler
vry (Verfifier) – credential verifier with wallet storage
local (bool) – True means event source is local (protected) for validation False means event source is remote (unprotected) for validation None means use default .local
version (Versionage) – default version of CESR to use None means do not change default
- New Logic:
Attachments must all have counters so know if txt or bny format for attachments. So even when framed==True must still have counters.
- parseOne(ims=None, framed=True, piped=False, kvy=None, tvy=None, exc=None, rvy=None, vry=None, local=None, version=None)[source]
Processes one messages from incoming message stream, ims, when provided. Otherwise process message from .ims Returns once one message is processed. Convenience executor for .processOneGen when ims is not live, i.e. fixed
- Parameters:
ims (bytearray) – serialized incoming message stream. May contain one or more sets each of a serialized message with attached cryptographic material such as signatures or receipts.
framed (bool) – counted attachments instead of stream with multiple messages
piped (bool) – True means use pipeline processor to process ims msgs when stream includes pipelineable count codes.
kvy (Kevery) – route KERI KEL message types to this instance
tvy (Tevery) – route TEL message types to this instance
exc (Exchanger)
rvy (Revery) – reply (RPY) message handler
local (bool) – True means event source is local (protected) for validation False means event source is remote (unprotected) for validation None means use default .local
version (Versionage) – default genera version of CESR to use None means do not change default
- New Logic:
Attachments must all have counters so know if txt or bny format for attachments. So even when framed==True must still have counters.
- property sucodes
Makes .sucodes read only :returns: selected by .version from (SUDex_1_0, SUDex_2_0) :rtype: _sucodes (SUDex)
- property version
Makes .version read only default version from genus-version code Returns ._version
keri.core.routing
keri.core.routing module
- class keri.core.routing.Revery(db, rtr=None, cues=None, lax=True, local=False)[source]
Reply message event processor
- acceptReply(serder, saider, route, aid, osaider=None, cigars=None, tsgs=None)[source]
Applies Best Available Data Acceptance policy to reply and signatures
- Returns:
True is successfully accepted. False otherwise
- Return type:
bool
- Parameters:
serder (Serder) – instance of reply msg (SAD)
saider (Diger) – instance from said in serder (SAD)
osaider (Diger) – instance of diger for previous reply if any
route (str) – reply route
aid (str) – identifier prefix qb64 of authorizing attributable ID
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 number 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
BADA (Best Available Data Acceptance) model for each reply message. Latest-Seen-Signed Pairwise comparison of new update reply compared to old already accepted reply from same source for same route (same data). Accept new reply (update) if new reply is later than old reply where:
If transferable, later is true when either:
- the sn (sequence number) of the last (if forked) Est evt that
provides keys for signature(s) of new is greater than the sn of the last Est evt that provides keys for signature(s) of old.
- the sn of new equals the sn of old and the date-time-stamp of
new is greater than old.
- If non-transferable, later is true if the date-time-stamp of
new is greater than old.
Otherwise, later is false.
If nontrans and last Est Evt is not yet accepted then escrow. If nontrans and partially signed then escrow.
Escrow process logic is route dependent and is dispatched by route, i.e. route is address of buffer with route specific handler of escrow.
- escrowReply(*, serder, saider, dater, route, prefixer, snumber, sdiger, sigers)[source]
Escrow reply by route
- Parameters:
serder (Serder) – instance of reply msg (SAD)
saider (Diger) – instance from said in serder (SAD)
dater (Dater) – instance from date-time in serder (SAD)
route (str) – reply route
prefixer (Prefixer) – is pre of trans endorser
snumber (Number) – is sequence number of trans endorser’s est evt for keys for sigs
sdiger (Diger)
sigers (list) – is indexed sigs from trans endorser’s key from est evt
- property prefixes
Returns .db.prefixes
- processEscrowReply()[source]
Process escrows for reply messages.
Escrows are keyed by reply route and val is reply said
triple (prefixer, seqner, diger) quadruple (prefixer, seqner, diger, siger)
- processReply(serder, cigars=None, tsgs=None, **kwa)[source]
Process one reply message with either attached nontrans signing couples in cigars or attached trans indexed sig groups in tsgs. Process logic is route dependent and dispatched by route.
- Parameters:
serder (Serder) – instance of reply message
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 number 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
BADA (Best Available Data Acceptance) model for each reply message. Latest-Seen-Signed Pairwise comparison of new update reply compared to old already accepted reply from same source for same route (same data). Accept new reply (update) if new reply is later than old reply where:
Later means date-time-stamp of new is greater than old.
If non-trans signer, later also means the sn (sequence number) of the last (if forked) Est evt that provides keys for signature(s) of new is greater than or equal to the sn of the last Est evt that provides keys for signature(s) of new.
If nontrans and last Est Evt is not yet accepted then escrow. If nontrans and partially signed then escrow.
Escrow process logic is route dependent and is dispatched by route, i.e. route is address of buffer with route specific handler of escrow.
- removeReply(saider)[source]
Remove Reply SAD artifacts given by saider.
- Parameters:
saider (Diger) – instance from said in serder (SAD)
- updateReply(*, serder, saider, dater, cigar=None, prefixer=None, seqner=None, diger=None, sigers=None)[source]
Update Reply SAD in database
Update Reply SAD in database given by by serder and associated databases for attached cig couple or sig quadruple. Overwrites val at key if already exists.
- Parameters:
serder (Serder) – instance of reply msg (SAD)
saider (Diger) – instance from said in serder (SAD)
dater (Dater) – instance from date-time in serder (SAD)
cigar (Cigar) – instance that contain nontrans signing couple signature in .raw and public key in .verfer
prefixer (Prefixer) – is pre of trans endorser
seqner (Seqner) – is sequence number of trans endorser’s est evt for keys for sigs
diger (Diger) – is digest of trans endorser’s est evt for keys for sigs
sigers (list) – of indexed sigs from trans endorser’s key from est evt
- class keri.core.routing.Route(regex, fields, resource, suffix=None)[source]
Route class for registration of reply message handlers
This class represents a registered route internally to the Revery. the properties are created by using the Falcon compile route utility method
- Properties:
.regex(re): compiled url template regex .fields(set): field names for matches in regex .resource(object): the handler for this route .suffix(Optional(str)): a suffix to be applied to the handler method
- __init__(regex, fields, resource, suffix=None)[source]
Initialize instance of route
- Parameters:
regex (re) – compiled url template regex
fields (set) – field names for matches in regex
resource (object) – the handler for this route
suffix (Optional(str)) – a suffix to be applied to the handler method
- class keri.core.routing.Router(routes=None)[source]
Reply message router
Reply message router that accepts registration of route r handlers and dispatches reply messages to the appropriate handler.
- __init__(routes=None)[source]
Initialized instance with optiona list of existing routes
- Parameters:
routes (list) – preregistered routes for this router
- addRoute(routeTemplate, resource, suffix=None)[source]
Add a route between a route template and a resource
- Parameters:
routeTemplate (str) – a route template to use for the resource
resource (object) – the resource instance to associate with the route template
suffix (str, optional) – Optional responder name suffix for this route. If a suffix is provided, Router will map reply routes to processReply{suffix}(). In this way, multiple closely-related routes can be mapped to the same resource.
- processRouteNotFound(*, serder, diger, route, cigars=None, tsgs=None, **kwargs)[source]
Default handler for processing reply message with an unregistered route
- Parameters:
serder (Serder) – reply event message
diger (Diger) – instance from said of reply serder
route (str) – route (‘r’) of the event message
cigars (Optional(list)) – list of non-transferable signature tuples
tsgs (Optional(list)) – list of transferable signature tuples
**kwargs (dict)
- keri.core.routing.compile_uri_template(template)[source]
Compile the given URI template string into a pattern matcher.
This function can be used to construct custom routing engines that iterate through a list of possible routes, attempting to match an incoming request against each route’s compiled regular expression.
Each field is converted to a named group, so that when a match is found, the fields can be easily extracted using
re.MatchObject.groupdict().This function does not support the more flexible templating syntax used in the default router. Only simple paths with bracketed field expressions are recognized. For example:
/ /books /books/{isbn} /books/{isbn}/characters /books/{isbn}/characters/{name}
Also, note that if the template contains a trailing slash character, it will be stripped in order to normalize the routing logic.
- Parameters:
template (str) – The template to compile. Note that field names are restricted to ASCII a-z, A-Z, and the underscore character.
- Returns:
(template_field_names, template_regex)
- Return type:
tuple
keri.core.scheming
keri.core.scheming module
self-addressing and schema support
- class keri.core.scheming.CacheResolver(db)[source]
Sample jsonschema resolver for loading schema $ref references from a local hash.
- __init__(db)[source]
Create a jsonschema resolver that can be used for loading references to schema remotely.
- Parameters:
db (Baser)
- add(key, schema)[source]
Add schema to cache for resolution
- Parameters:
key (str) – URI to resolve to the schema
schema (bytes) – is bytes of the schema for the URI
- class keri.core.scheming.JSONSchema(resolver=None)[source]
JSON Schema support class
- __init__(resolver=None)[source]
Initialize instance
- Parameters:
resolver (Optional(Resolver)) – instance used by JSONSchema parsing to resolve external refs
- static detect(raw)[source]
Detect if raw content is JSON Schema
- Parameters:
raw (bytes) – data to check for JSON Schema
- Returns:
- True if content represents JSON Schema by checking
for $schema; False otherwise
- Return type:
boolean
- static dump(sed, kind='JSON')[source]
Serailize schema based on kind
- Parameters:
sed (dict) – in memory representation of schema
kind (Optional(Serials)) – kind of serialization to perform. Defaults to JSON
- Returns:
Serialized schema
- Return type:
bytes
- load(raw, kind='JSON')[source]
Schema loader
Loads schema based on kind by performing deserialization on raw bytes of schema
- Parameters:
raw (bytes) – raw serialized schema
kind (Optional(Serials)) – serialization kind of schema raw content
- Returns:
(dict, Serials, Saider) of schema
- Return type:
tuple
- resolve(uri)[source]
Resolve remote reference to schema
- Parameters:
uri (str) – uniform resource identifier of schema to load
- verify_json(schema=b'', raw=b'')[source]
Verify the raw content against the schema for JSON that conforms to the schema
- Parameters:
schema (bytes) – is the schema use for validation
raw (bytes) – is JSON to validate against the Schema
- Returns:
- True if the JSON passes validation against the
provided complaint Draft 7 JSON Schema. Returns False if raw is not valid JSON, schema is not valid JSON Schema or the validation fails
- Return type:
boolean
- class keri.core.scheming.Schemer(raw=b'', sed=None, kind=None, typ=<keri.core.scheming.JSONSchema object>, code='E', verify=True)[source]
Schemer is KERI schema serializer-deserializer class
Verifies self-addressing identifier base on schema type Only supports current version VERSION
Has the following public properties:
- Properties:
.raw (bytes): of serialized event only .sed (dict): schema dict .kind (Schema): kind string value (see namedtuple coring.Serials) .saider (Saider): instance of self-addressing identifier .said (qb64): digest from .saider
- Hidden Attributes:
._raw (bytes): of serialized schema only ._sed (JSON): schema dict ._kind (schema): kind string value (see namedtuple coring.Serials), supported kinds are ‘JSONSchema’ ._code (default): code for .saider ._saider (Saider): instance of digest of .raw
- __init__(raw=b'', sed=None, kind=None, typ=<keri.core.scheming.JSONSchema object>, code='E', verify=True)[source]
Initialize instance of Schemer
Deserialize if raw provided Serialize if sed provided but not raw When serializing if kind provided then use kind instead of field in sed
- Parameters:
raw (bytes) – of serialized schema
sed (dict) – dict or None if None its deserialized from raw
typ (JSONSchema) – type of schema
kind (serialization) – kind string value or None (see namedtuple coring.Serials) supported kinds are ‘json’, ‘cbor’, ‘msgpack’, ‘binary’ if kind (None): then its extracted from ked or raw
code (MtrDex) – default digest code
verify (bool) – True means verify said(s) of given raw or sad. Raises ValidationError if verification fails False means don’t verify. Useful to avoid unnecessary reverification when deserializing from database as opposed to over the wire reception.
- property kind
kind property getter
- pretty(*, size=1024)[source]
Returns str JSON of .sed with pretty formatting
ToDo: add default size limit on pretty when used for syslog UDP MCU like 1024 for ogler.logger
- property raw
raw property getter
- property said
said property getter, relies on saider
- property saider
saider property getter
- property sed
ked property getter
keri.core.signing
keri.core.signing module
Provides support Signer class
- class keri.core.signing.Cipher(raw=None, code=None, **kwa)[source]
Cipher is Matter subclass holding a cipher text of a secret that may be either a secret seed (private key) or secret salt with appropriate CESR code to indicate which kind (which indicates size). The cipher text is created with assymetric encryption using an unrelated (public, private) encryption/decryption key pair. The public key is used for encryption the private key for decryption. The default is to use X25519 sealed box encryption.
The Cipher instances .raw is the raw binary encrypted cipher text and its .code indicates what type of plain text has been encrypted. The cipher suite used for the encryption/decryption is implied by the context where the cipher is used.
See Matter for inherited attributes and properties
- __init__(raw=None, code=None, **kwa)[source]
- Inherited Parameters:
(see Matter)
- Parmeters:
raw (bytes | str): cipher text (not plain text) code (str): cipher suite
- decrypt(prikey=None, seed=None, klas=None, transferable=False, bare=False, **kwa)[source]
Returns plain text as klas instance (Matter, Indexer, Streamer). When klas is None then klas default is based on .code. Maybe Salter, Signer, or Streamer. Encrypted plain text is fully qualified (qb64) via self so derivaton code of plain text preserved through encryption/decryption round trip.
The created Decrypter uses either decryption key given by prikey or when prikey missing derives prikey from signing key derived from private seed.
- Returns:
- instance of decrypted
cipher text of .raw which is encrypted qb64, qb2, or sniffable stream depending on .code when bare is False. Otherwise returns plaintext itself.
- Return type:
- Keyword Parameters:
See Matter because created Decrypter is Matter subclass.
- Parameters:
prikey (str | bytes) – qb64 or qb64b serialization of private decryption key. Must be fully qualified with code.
seed (str | bytes) – qb64 or qb64b serialization of private signing key seed used to derive private decryption key. Must be fully qualified with code.
klas (Matter | Indexer | Streamer) – Class used to create instance from decrypted serialization.
transferable (bool) – Modifier of klas instance creation. When klas init (such as Signer) supports transferabe parm, True means verfer of returned signer is transferable. False means non-transferable.
bare (bool) – False (default) means returns instance holding plaintext. True means returns plaintext itself.
- class keri.core.signing.CipherX25519AllCodex(X25519_Cipher_L0: str = '4C', X25519_Cipher_L1: str = '5C', X25519_Cipher_L2: str = '6C', X25519_Cipher_Big_L0: str = '7AAC', X25519_Cipher_Big_L1: str = '8AAC', X25519_Cipher_Big_L2: str = '9AAC', X25519_Cipher_Seed: str = 'P', X25519_Cipher_Salt: str = '1AAH', X25519_Cipher_QB64_L0: str = '4D', X25519_Cipher_QB64_L1: str = '5D', X25519_Cipher_QB64_L2: str = '6D', X25519_Cipher_QB64_Big_L0: str = '7AAD', X25519_Cipher_QB64_Big_L1: str = '8AAD', X25519_Cipher_QB64_Big_L2: str = '9AAD', X25519_Cipher_QB2_L0: str = '4E', X25519_Cipher_QB2_L1: str = '5E', X25519_Cipher_QB2_L2: str = '6E', X25519_Cipher_QB2_Big_L0: str = '7AAE', X25519_Cipher_QB2_Big_L1: str = '8AAE', X25519_Cipher_QB2_Big_L2: str = '9AAE')[source]
CipherX25519AllCodex is codex all codes and types of cipher bytes for sealed box encryped ciphertext. Plaintext maybe sniffable or qb64 or qb2. Only provide defined codes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
- class keri.core.signing.CipherX25519AllQB64Codex(X25519_Cipher_Seed: str = 'P', X25519_Cipher_Salt: str = '1AAH', X25519_Cipher_QB64_L0: str = '4D', X25519_Cipher_QB64_L1: str = '5D', X25519_Cipher_QB64_L2: str = '6D', X25519_Cipher_QB64_Big_L0: str = '7AAD', X25519_Cipher_QB64_Big_L1: str = '8AAD', X25519_Cipher_QB64_Big_L2: str = '9AAD')[source]
CipherX25519AllQB64Codex is codex all both fixed and variable sized cipher bytes derivation codes for sealed box encryped ciphertext. Plaintext is B64. Only provide defined codes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
- class keri.core.signing.CipherX25519AllVarCodex(X25519_Cipher_L0: str = '4C', X25519_Cipher_L1: str = '5C', X25519_Cipher_L2: str = '6C', X25519_Cipher_Big_L0: str = '7AAC', X25519_Cipher_Big_L1: str = '8AAC', X25519_Cipher_Big_L2: str = '9AAC', X25519_Cipher_QB64_L0: str = '4D', X25519_Cipher_QB64_L1: str = '5D', X25519_Cipher_QB64_L2: str = '6D', X25519_Cipher_QB64_Big_L0: str = '7AAD', X25519_Cipher_QB64_Big_L1: str = '8AAD', X25519_Cipher_QB64_Big_L2: str = '9AAD', X25519_Cipher_QB2_L0: str = '4E', X25519_Cipher_QB2_L1: str = '5E', X25519_Cipher_QB2_L2: str = '6E', X25519_Cipher_QB2_Big_L0: str = '7AAE', X25519_Cipher_QB2_Big_L1: str = '8AAE', X25519_Cipher_QB2_Big_L2: str = '9AAE')[source]
CipherX25519AllVarCodex is codex all variable size codes of cipher bytes for sealed box encryped ciphertext. Plaintext maybe sniffable CESR stream or qb64 or qb2. Only provide defined codes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
- class keri.core.signing.CipherX25519FixQB64Codex(X25519_Cipher_Seed: str = 'P', X25519_Cipher_Salt: str = '1AAH')[source]
CipherX25519FixQB64Codex is codex all fixed sized cipher bytes derivation codes for sealed box encryped ciphertext. Plaintext is B64. Only provide defined codes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
- class keri.core.signing.CipherX25519QB2VarCodex(X25519_Cipher_QB2_L0: str = '4E', X25519_Cipher_QB2_L1: str = '5E', X25519_Cipher_QB2_L2: str = '6E', X25519_Cipher_QB2_Big_L0: str = '7AAE', X25519_Cipher_QB2_Big_L1: str = '8AAE', X25519_Cipher_QB2_Big_L2: str = '9AAE')[source]
CipherX25519QB2VarCodex is codex all variable sized cipher bytes derivation codes for sealed box encryped ciphertext. Plaintext is B2. Only provide defined codes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
- class keri.core.signing.CipherX25519VarQB64Codex(X25519_Cipher_QB64_L0: str = '4D', X25519_Cipher_QB64_L1: str = '5D', X25519_Cipher_QB64_L2: str = '6D', X25519_Cipher_QB64_Big_L0: str = '7AAD', X25519_Cipher_QB64_Big_L1: str = '8AAD', X25519_Cipher_QB64_Big_L2: str = '9AAD')[source]
CipherX25519VarQB64Codex is codex all variable sized cipher bytes derivation codes for sealed box encryped ciphertext. Plaintext is QB64. Only provide defined codes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
- class keri.core.signing.CipherX25519VarStrmCodex(X25519_Cipher_L0: str = '4C', X25519_Cipher_L1: str = '5C', X25519_Cipher_L2: str = '6C', X25519_Cipher_Big_L0: str = '7AAC', X25519_Cipher_Big_L1: str = '8AAC', X25519_Cipher_Big_L2: str = '9AAC')[source]
CipherX25519VarCodex is codex all variable sized cipher bytes derivation codes for sealed box encryped ciphertext. Plaintext is Sniffable CESR Stream. Only provide defined codes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
- class keri.core.signing.Decrypter(code='O', seed=None, **kwa)[source]
Decrypter is Matter subclass with method to decrypt the plain text from a ciper text of a fully qualified (qb64) private key/seed where private key/seed is the plain text. Decrypter uses assymetric (public, private) key decryption of the cipher text using its .raw as the decrypting (private) key and its .code to indicate the cipher suite for the decryption operation.
For example .code == MtrDex.X25519 indicates that X25519 sealed box decyrption is used. The decryption key may be derived from an Ed25519 signing private key that is associated with a nontransferable or basic derivation self certifying identifier. This allows use of the self certifying identifier to track or manage the encryption/decryption key pair. And could be used to provide additional authentication operations for using the encryption/decryption key pair. Support for this is provided at init time with the sigkey parameter which allows deriving the decryption private key from the fully qualified sigkey (signing key).
See Matter for inherited attributes and properties:
Attributes:
Properties:
- __init__(code='O', seed=None, **kwa)[source]
Assign decrypting cipher suite function to ._decrypt
- Inherited Parameters:
(see Matter)
- Parameters:
parameters. (See Matter for inherited)
code (str) – derivation code for private decryption key
seed (str | bytes | bytearray | memoryview | None) – qb64b or qb64 of signing key seed used to derive raw which is private decryption key
- decrypt(*, cipher=None, qb64=None, qb2=None, klas=None, transferable=False, bare=False, **kwa)[source]
Returns plain text as klas instance (Matter, Indexer, Streamer). When klas is None then klas default is based on cipher.code or inferred from qb64 or qb2 code. Default maybe Salter, Signer, or Streamer. Cipher’s encrypted plain text is fully qualified (qb64) so derivaton code of plain text preserved through encryption/decryption round trip.
- Returns:
- When bare is False
returns instance of decrypted cipher text of .raw which is encrypted qb64, qb2, or sniffable stream depending on .code hhen Bare is True. Otherwise returns decrypted serialization plaintext whatever that may be.
- Return type:
- Keyword Parameters:
See Matter because created Decrypter is Matter subclass.
- Parameters:
cipher (Cipher) – instance. One of cipher, qb64, or qb2 required.
qb64 (str | bytes | bytearray | memoryview | None) – serialization of cipher text as fully qualified base64. When str, encodes as utf-8. When bytearray and strip in kwa is True then strips.
qb2 (bytes | bytearray | memoryview | None) – serialization of cipher text as fully qualified base2. Strips when bytearray and strip in kwa is True.
klas (Matter | Indexer | Streamer) – Class used to create instance from decrypted serialization.
transferable (bool) – Modifier of klas instance creation. When klas init (such as Signer) supports transferabe parm, True means verfer of returned signer is transferable. False means non-transferable.
bare (bool) – False (default) means returns instance holding plaintext. True means returns plaintext itself.
- class keri.core.signing.Encrypter(raw=None, code='C', verkey=None, **kwa)[source]
Encrypter is Matter subclass with method to create a cipher text of a fully qualified (qb64) private key/seed where private key/seed is the plain text. Encrypter uses assymetric (public, private) key encryption of a serialization (plain text). Using its .raw as the encrypting (public) key and its .code to indicate the cipher suite for the encryption operation.
For example .code == MtrDex.X25519 indicates that X25519 sealed box encyrption is used. The encryption key may be derived from an Ed25519 signing public key that associated with a nontransferable or basic derivation self certifying identifier. This allows use of the self certifying identifier to track or manage the encryption/decryption key pair. And could be used to provide additional authentication operations for using the encryption/decryption key pair. Support for this is provided at init time with the verkey parameter which allows deriving the encryption public key from the fully qualified verkey (signature verification key).
See Matter for inherited attributes and properties:
- __init__(raw=None, code='C', verkey=None, **kwa)[source]
Assign encrypting cipher suite function to ._encrypt
- Parameters: See Matter for inherted parameters such as qb64, qb64b
raw (bytes): public encryption key qb64b (bytes): fully qualified public encryption key qb64 (str): fully qualified public encryption key code (str): derivation code for public encryption key verkey (Union[bytes, str]): qb64b or qb64 of verkey used to derive raw
- encrypt(*, ser=None, prim=None, code=None)[source]
- Returns:
Cipher instance of cipher text encryption of plain text serialization provided by either ser or prim as CESR primitive instance.
- Parameters:
ser (str | bytes | bytearray | memoryview) – qb64b or qb64 or sniffable stream serialization of plain text
prim (Matter | Indexer | Streamer) – CESR primitive instance whose serialization is qb64 or qb2 or sniffable stream and is to be encrypted based on code
code (str) – code of plain text type for resultant encrypted cipher
- class keri.core.signing.Salter(raw=None, code='0A', tier=None, **kwa)[source]
Salter is Matter subclass to maintain random salt for secrets (private keys) Its .raw is random salt, .code as cipher suite for salt
- To initialize with deterministic salt pass in 16 bytes for raw:
salter = Salter(raw=b’0123456789abcdef’)
To create a deterministic secret, seed, or private key from salt call .signer:
signer = salter.signer(code=MtrDex.Ed25519_Seed, transferable=True, path="", tier=None, temp=False)
To create a deterministic set of secrets or seeds or private keys from salt call signers:
signers = salter.signers(count=1, start=0, path="", code=MtrDex.Ed25519_Seed, transferable=True, tier=None, temp=False)
- .level is str security level code. Provides default level
- Inherited Properties
.pad is int number of pad chars given raw .code is str derivation code to indicate cypher suite .raw is bytes crypto material only without code .index is int count of attached crypto material by context (receipts) .qb64 is str in Base64 fully qualified with derivation code + crypto mat .qb64b is bytes in Base64 fully qualified with derivation code + crypto mat .qb2 is bytes in binary with derivation code + crypto material .transferable is Boolean, True when transferable derivation code False otherwise
Properties:
Methods:
- Hidden:
._pad is method to compute .pad property ._code is str value for .code property ._raw is bytes value for .raw property ._index is int value for .index property ._infil is method to compute fully qualified Base64 from .raw and .code ._exfil is method to extract .code and .raw from fully qualified Base64
- __init__(raw=None, code='0A', tier=None, **kwa)[source]
Initialize salter’s raw and code
- Inherited Parameters:
raw is bytes of unqualified crypto material usable for crypto operations qb64b is bytes of fully qualified crypto material qb64 is str or bytes of fully qualified crypto material qb2 is bytes of fully qualified crypto material code is str of derivation code index is int of count of attached receipts for CryCntDex codes
Parameters:
- signer(*, code='A', transferable=True, path='', tier=None, temp=False)[source]
Returns Signer instance whose .raw secret is derived from path and salter’s .raw and stretched to size given by code. The signers public key for its .verfer is derived from code and transferable.
- Parameters:
suite (code is str code of secret crypto)
Boolean (temp is)
key (True means use transferace code for public)
signer (path is str of unique chars used in derivation of secret seed for)
level (tier is str Tierage security)
Boolean – for testing only, Otherwise use more time to stretch
salt (True means use quick method to stretch) – for testing only, Otherwise use more time to stretch
- signers(count=1, start=0, path='', **kwa)[source]
Returns list of count number of Signer instances with unique derivation path made from path prefix and suffix of start plus offset for each count value from 0 to count - 1.
See .signer for parameters used to create each signer.
- stretch(*, size=32, path='', tier=None, temp=False)[source]
Returns (bytes): raw binary seed (secret) derived from path and .raw and stretched to size given by code using argon2d stretching algorithm.
- Parameters:
size (int) – number of bytes in stretched seed
path (str) – unique chars used in derivation of seed (secret)
tier (str) – value from Tierage for security level of stretch
Boolean (temp is) – for testing only, Otherwise use time set by tier to stretch
salt (True means use quick method to stretch) – for testing only, Otherwise use time set by tier to stretch
- class keri.core.signing.Signer(raw=None, code='A', transferable=True, **kwa)[source]
Signer is Matter subclass with method to create signature of serialization using:
.raw as signing (private) key seed,
.code as cipher suite for signing
.verfer whose property .raw is public key for signing.
If not provided .verfer is generated from private key seed using .code as cipher suite for creating key-pair.
See Matter for inherited attributes and properties:
Inherited Properties:
code (str): hard part of derivation code to indicate cypher suite
both (int): hard and soft parts of full text code
- size (int): Number of triplets of bytes including lead bytes
(quadlets of chars) of variable sized material. Value of soft size, ss, part of full text code. Otherwise None.
rize (int): number of bytes of raw material not including lead bytes
raw (bytes): private signing key crypto material only without code
- qb64 (str): private signing key Base64 fully qualified with
derivation code + crypto mat
- qb64b (bytes): private signing keyBase64 fully qualified with
derivation code + crypto mat
- qb2 (bytes): private signing key binary with derivation code +
crypto material
transferable (bool): True means transferable derivation code False otherwise
digestive (bool): True means digest derivation code False otherwise
Properties:
- .verfer is Verfer object instance of public key derived from private key
seed which is .raw
- - sign
create signature
- __init__(raw=None, code='A', transferable=True, **kwa)[source]
Assign signing cipher suite function to ._sign
- Parameters:
parameters. (See Matter for inherted)
raw (bytes) – crypto material for signing seed from which to generate private key
code (str) – derivation code of signing seed
transferable (bool) – True means make verifier code transferable False make non-transferable
- sign(ser, index=None, only=False, ondex=None, **kwa)[source]
Returns either Cigar or Siger (indexed) instance of cryptographic signature material on bytes serialization ser
- If index is None
return Cigar instance
- Else
return Siger instance
- Parameters:
ser (bytes) – serialization to be signed
index (int) – main index of associated verifier key in event keys
only (bool) – True means main index only list, ondex ignored False means both index lists (default), ondex used
ondex (int | None) – other index offset into list such as prior next
- property verfer
Property verfer: Returns Verfer instance Assumes ._verfer is correctly assigned
- class keri.core.signing.Streamer(stream, verify=False)[source]
Streamer is CESR sniffable stream class
Has the following public properties:
- Properties:
stream (bytearray): sniffable CESR stream
Methods:
- Hidden:
_verify() -> bool
- __init__(stream, verify=False)[source]
Initialize instance Holds sniffable CESR stream as byte like string either (bytes, bytearray, or memoryview)
- Parameters:
stream (str | bytes | bytearray | memoryview) – sniffable CESR stream
verify (bool) – When True raise error if .stream is not sniffable.
- property bexter
stream as Bexter instance. Bexter of expanded text version of stream. First expand to text which requires parsing then create bexter:
Bexter(bext=self.text)
Because sniffable stream MUST NOT start with ‘A’ then there is no length ambiguity. The only tritet collison of ‘A’ is with ‘-’ but the remaining 5 bits are guaranteed to always be different. So bexter must check not just the starting tritet but the full starting byte to ensure not ‘A’ as first byte.
Requires parsing to ensure qb64 :returns: Bexter primitive of stream suitable wrapping :rtype: bexter (Bexter)
- property binary
compacted stream where all primitives and groups in stream are individually compacted to qb2. Requires parsing full depth to ensure compacted consistently :returns: compacted binary qb2 version of stream :rtype: stream (bytes)
Only works for ver 2 CESR because need for all count codes to be pipelineable in order to simply parse and compact stream
- property stream
stream property getter
- property text
expanded stream where all primitives and groups in stream are individually expanded to qb64. Requires parsing full depth to ensure expanded consistently. :returns: expanded text qb64 version of stream :rtype: stream (bytes)
Only works for ver 2 CESR because need for all count codes to be pipelineable in order to simply parse and expand stream
keri.core.annotating
keri.core.annotating module
Provides support for Annotater
- keri.core.annotating.annot(ims)[source]
Annotate CESR stream
- Returns:
annotation of input CESR stream
- Return type:
annotation (str)
- Parameters:
ims (str | bytes | bytearray | memoryview) – CESR incoming message stream as qb64 (maybe qb2)
- keri.core.annotating.denot(ams)[source]
De-annotate CESR stream
- Returns:
deannotation of input annotated CESR message stream
- Return type:
dms (bytes)
- Parameters:
ams (str) – CESR annotated message stream text
Note
The Streamer class was moved to keri.core.signing
but remains importable via from keri.core import Streamer.
keri.core.structing
keri.core.structing module
Creates fixed field data structures
- class keri.core.structing.AllCastDom(SealDigest: ~typing.NamedTuple = ((<class 'keri.core.coring.Diger'>, None), ), SealRoot: ~typing.NamedTuple = ((<class 'keri.core.coring.Diger'>, None), ), SealSource: ~typing.NamedTuple = ((<class 'keri.core.coring.Number'>, 'numh'), (<class 'keri.core.coring.Diger'>, None)), SealEvent: ~typing.NamedTuple = ((<class 'keri.core.coring.Prefixer'>, None), (<class 'keri.core.coring.Number'>, 'numh'), (<class 'keri.core.coring.Diger'>, None)), SealLast: ~typing.NamedTuple = ((<class 'keri.core.coring.Prefixer'>, None), ), SealBack: ~typing.NamedTuple = ((<class 'keri.core.coring.Prefixer'>, None), (<class 'keri.core.coring.Diger'>, None)), SealKind: ~typing.NamedTuple = ((<class 'keri.core.coring.Verser'>, None), (<class 'keri.core.coring.Diger'>, None)), BlindState: ~typing.NamedTuple = ((<class 'keri.core.coring.Noncer'>, 'nonce'), (<class 'keri.core.coring.Noncer'>, 'nonce'), (<class 'keri.core.coring.Noncer'>, 'nonce'), (<class 'keri.core.coring.Labeler'>, 'text')), BoundState: ~typing.NamedTuple = ((<class 'keri.core.coring.Noncer'>, 'nonce'), (<class 'keri.core.coring.Noncer'>, 'nonce'), (<class 'keri.core.coring.Noncer'>, 'nonce'), (<class 'keri.core.coring.Labeler'>, 'text'), (<class 'keri.core.coring.Number'>, 'numh'), (<class 'keri.core.coring.Noncer'>, 'nonce')), TypeMedia: ~typing.NamedTuple = ((<class 'keri.core.coring.Noncer'>, 'nonce'), (<class 'keri.core.coring.Noncer'>, 'nonce'), (<class 'keri.core.coring.Labeler'>, 'text'), (<class 'keri.core.coring.Texter'>, 'text')))[source]
AllCastDom is dataclass of namedtuple instances (casts) whose field values are Castage instances of named primitive class class references for those fields.
indexed by its namedtuple class name.
Only provide defined namedtuples casts. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
As subclass of MapCodex can get namedtuple instance with item syntax using name variables.
Example: AllCastDom[name]
- class keri.core.structing.AllClanDom(SealDigest: type[~typing.NamedTuple] = <class 'keri.core.structing.SealDigest'>, SealRoot: type[~typing.NamedTuple] = <class 'keri.core.structing.SealRoot'>, SealSource: type[~typing.NamedTuple] = <class 'keri.core.structing.SealSource'>, SealEvent: type[~typing.NamedTuple] = <class 'keri.core.structing.SealEvent'>, SealLast: type[~typing.NamedTuple] = <class 'keri.core.structing.SealLast'>, SealBack: type[~typing.NamedTuple] = <class 'keri.core.structing.SealBack'>, SealKind: type[~typing.NamedTuple] = <class 'keri.core.structing.SealKind'>, BlindState: type[~typing.NamedTuple] = <class 'keri.core.structing.BlindState'>, BoundState: type[~typing.NamedTuple] = <class 'keri.core.structing.BoundState'>, TypeMedia: type[~typing.NamedTuple] = <class 'keri.core.structing.TypeMedia'>)[source]
AllClanDom is dataclass of all namedtuple class references (clans) each indexed by its class name.
Only provide defined classes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
As subclass of MapCodex can get class reference with item syntax using name variables.
Example: AllClanDom[name]
- class BlindState(d, u, td, ts)
- d
Alias for field number 0
- td
Alias for field number 2
- ts
Alias for field number 3
- u
Alias for field number 1
- class BoundState(d, u, td, ts, bn, bd)
- bd
Alias for field number 5
- bn
Alias for field number 4
- d
Alias for field number 0
- td
Alias for field number 2
- ts
Alias for field number 3
- u
Alias for field number 1
- class keri.core.structing.BlindState(d, u, td, ts)
- d
Alias for field number 0
- td
Alias for field number 2
- ts
Alias for field number 3
- u
Alias for field number 1
- class keri.core.structing.BlindStateCastDom(BlindState: ~typing.NamedTuple = ((<class 'keri.core.coring.Noncer'>, 'nonce'), (<class 'keri.core.coring.Noncer'>, 'nonce'), (<class 'keri.core.coring.Noncer'>, 'nonce'), (<class 'keri.core.coring.Labeler'>, 'text')), BoundState: ~typing.NamedTuple = ((<class 'keri.core.coring.Noncer'>, 'nonce'), (<class 'keri.core.coring.Noncer'>, 'nonce'), (<class 'keri.core.coring.Noncer'>, 'nonce'), (<class 'keri.core.coring.Labeler'>, 'text'), (<class 'keri.core.coring.Number'>, 'numh'), (<class 'keri.core.coring.Noncer'>, 'nonce')))[source]
BlindStateCastDom is dataclass of namedtuple instances (blind casts) whose field values are Castage instances of named primitive class class references for those fields.
indexed by its namedtuple class name.
Only provide defined namedtuples casts. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
Example: BlindStateCastDom[name]
Note: the d, and td field values may be empty so instead of Diger users Noncer which allows all the Diger codes plus empty
- class keri.core.structing.BlindStateClanDom(BlindState: type[~typing.NamedTuple] = <class 'keri.core.structing.BlindState'>, BoundState: type[~typing.NamedTuple] = <class 'keri.core.structing.BoundState'>)[source]
BlindStateClanDom is dataclass of namedtuple blinded state class references (clans) each indexed by its class name.
Only provide defined classes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
Example: BlindStateClanDom[name]
- class keri.core.structing.Blinder(saidive=True, **kwa)[source]
Blinder is Structor subclass each instance holds a namedtuple .data of named values belonging to ACDC blinded state attribute for blindable state registry for TEL for ACDC to unblind the state attribute via a message attachment. Supports both BlindState and BoundState blinded state.
See Structor class for more details.
- Inherited Class Attributes:
- Clans (type[Namedtuple]): each value is known NamedTuple class keyed
by its own field names (tuple). Enables easy query of its values() to find known data types given field names tuple.
- Casts (NamedTuple): each value is primitive class of cast keyed by fields
names of the associated NamedTuple class in .Clans. Enables finding known primitive classes given NamedTuple class of clan or instance of cast or crew.
- Names (dict): maps tuple of clan/cast fields names to its namedtuple
class type name so can look up a know clan or cast given a matching tuple
- ClanCodens (dict): map of clan namedtuple to counter code name for
ser/des as group
- CodenClans (dict): map of counter code name to clan named tuple for
ser/des as group
- Saids (dict): default saidive fields at top-level. Assumes .mad already
in most compact form. Each key is label of saidive field. Each value is default primitive code of said digest value to be
computed from serialized dummied .mad
Dummy (str): dummy character for computing SAIDs
Class Attributes:
When known casts are provided in .Clans/.Casts then more flexible creation is supported for different types of provided cast and crew. When no clan is provided and an unknown cast and/or crew are provided as Mappings then Structor may create custom clan from the names given by the cast and/or crew keys(). Subclasses may override this behavior by raising an exception for unknown or custom clans.
- Inherited Properties:
data (NamedTuple): fields are named instances of CESR primitives clan (type[NamedTuple]): class reference of .data’s class cast (NamedTuple): CESR primitive class references of .data’s primitive
instances
crew (NamedTuple): named qb64 values of .data’s primitive instances qb64 (str): concatenated data values as qb64 str of data’s primitives qb64b (bytes): concatenated data values as qb64b of data’s primitives qb2 (bytes): concatenated data values as qb2 bytes of data’s primitives saids (dict): default saidive fields at top-level.
Assumes .mad already in most compact form. Each key is label of saidive field. Each value is default primitive code of said digest
value to be computed from serialized dummied .mad
- saidive (bool): True means compute SAID(s) for toplevel fields in .saids
False means do not compute SAIDs
- said (str): qb64 said given .saids given .saids as saidive .data.d.qb64
primary said field value if any. None otherwise primary has same label as zeroth item in .saids
saidb (bytes): qb64b said given .saids as saidive fields .data.d.qb64b
- Properties:
blid (str): alias of .said property blidb (bytes): alias .saidb property uuid (str): qb64 uuid of BlindState CESR .data.u ‘u’ field uuidb (bytes): qb64b uuid of BlindState CESR .data.u ‘u’ field acdc (str): qb64 transaction acdc said or empty of
BlindState CESR .data.td ‘td’ field
- acdcb (bytes): qb64b transaction acdc said of
BlindState CESR .data.td ‘td’ field
- state (str): transaction state string of
BlindState CESR .data.ts ‘ts’ field
- stateb (bytes): transaction state string of
BlindState CESR .data.ts ‘ts’ field
- bsn (int): bound key state sequence number of issuees key state at
time of update BoundState CESR .data.bn ‘bn’ field
- bnh (str): bound key state hex sequence number of issuees key state
at time of update BoundState CESR .data.bn ‘bn’ field
- bnhb (bytes): bound key state hex sequence number of issuees key
state at time of update BoundState CESR .data.bn ‘bn’ field
- bd (str): qb64 bound key state said of issuee at time of update
BoundState CESR .data.bd ‘bd’ field
- bdb (bytes): qb64b bound key state said of issuee at time of update
BoundState CESR .data.bd ‘bd’ field
Methods:
- Hidden:
_data (namedtuple): named CESR primitive instances _cast (namedtuple): named Castage instances _saids (dict): default top-level said fields and codes _saidive (bool): compute saids or not
Example
sdig = ‘ELC5L3iBVD77d_MYbYGGCUQgqQBju1o4x1Ud-z2sL-ux’ sdiger = Diger(qb64=dig) noncer = Noncer(code=NonceDex.Salt_256) adig = ‘EBju1o4x1Ud-z2sL-uxLC5L3iBVD77d_MYbYGGCUQgqQ’ adiger = Diger(qb64=adig) labeler = Labeler(text=”issued”) data = BlindState(d=sdiger, u=noncer, td=adiger, ts=labeler) name = BlindState.__name__
blinder = Blinder(data=data) assert blinder.data == data assert blinder.clan == BlindState assert blinder.name == BlindState.__name__ assert blinder.cast == BlindState(d=Castage(Diger),
u=Castage(Noncer, ‘nonce’), td=Castage(Noncer, ‘nonce’), ts=Castage(Labeler, ‘text’))
- assert blinder.crew == BlindState(d=sdig,
u=noncer.nonce, td=adig, ts=labeler.text)
assert blinder.asdict == data._asdict() == sealer.crew._asdict()
- __init__(saidive=True, **kwa)[source]
Initialize instance
- Inherited Parameters: (see Structor)
- data (NamedTuple): fields are named primitive instances for .data
Given data can derive clan, cast, crew, qb64, and qb2
- clan (type[NamedTuple]): provides class reference for generated .data
when data missing.
- cast (NamedTuple | dict | Iterable): each value provides CESR
primitive subclass reference used to create primitive instances for generating .data. Can be used to infer namedtuple type of .data when data and clan missing. Takes precendence over crew.
- crew (NamedTuple | dict | Iterable): each value provides qb64 value
of primitive for generating .data with .cast when data missing. Can be used to infer namedtuple type of .data when data and clan missing.
- qb64b (str|bytes|bytearray|None): concatenation of qb64b data values to
generate .data with data and crew missing.
qb64 (str|bytes|bytearray|None): alias for qb64b qb2 (bytes|bytearray|None): concatenation of qb2 data values to generate
.data when data and crew and qb64 missing.
- strip (bool): False means do not strip each value from qb64 or qb2.
Default is False. True means if qb64 or qb2 are bytearray then strip contained concatenated data values. Else convert qb64 or qb2 to bytearray so can strip inplace. Enables parser to extract data fields from front of CESR stream when stream is bytearray.
- makify (bool): True means compute saids when .saidive
False means do not comput saids even when .saidive
- verify (bool): True means verify serialization against mad.
False means do not verify
- saids (dict): default saidive fields at top-level.
Assumes .mad already in most compact form. Each key is label of saidive field. Each value is default primitive code of said digest
value to be computed from serialized dummied .mad
- saidive (bool): True means compute SAID(s) for toplevel fields in .saids
False means do not compute SAIDs
Parameters:
- property acdc
acdc property getter :returns:
- qb64 transaction acdc said or empty of
BlindState CESR .data.td ‘td’ field
- Return type:
acdc (str)
- property acdcb
acdcb property getter :returns:
- qb64b transaction acdc said of
BlindState CESR .data.td ‘td’ field
- Return type:
acdcb (bytes)
- property bd
bd property getter :returns:
- qb64 bound key state said of issuee at time of update
BoundState CESR .data.bd ‘bd’ field
- Return type:
bd (str)
- property bdb
bdb property getter :returns:
- qb64b bound key state said of issuee at time of update
BoundState CESR .data.bd ‘bd’ field
- Return type:
bdb (bytes)
- property blid
blid property getter (alias of .said) :returns: blid of BlindState CESR .data.d ‘d’ field :rtype: blid (str)
- property blidb
blidb property getter (alias of .saidb) :returns: qb64b blid of BlindState CESR .data.d ‘d’ field :rtype: blidb (bytes)
- classmethod blind(*, raw=None, salt=None, sn=1, tier=None, acdc='', state='', bound=False, bsn=0, bd='')[source]
- Creates blinded blinder by generating blinding factor uuid given:
either raw or salt as shared secret if both None then generate salt sn of blindable update event, acdc said (may be empty for placeholder state string (may be empty for placeholder) tier for generator salt when not provided
- Returns:
blinded blinder
- Return type:
blinder (Blinder)
- Parameters:
raw (bytes|None) – random crypto material as salt used to generate uuid
salt (str|None) – qb64 of 128 bit random salt used to generate uuid
sn (int) – sequence number of blindable update message. Converted to Number.huge which is qb64 (24 char) used to generate uuid
tier (str|None) – used to generate uuid
acdc (str) – qb64 said of associated acdc (trans event acdc). Allows empty str for placeholder
state (str) – state string value. Allows empty str for placeholder
bound (bool) – True means use BoundState False means use BlindState default
bsn (int) – bound sequence number of latest key event of issuee at time of state update as (cross anchor) when bound==True and bsaid is not empty when bsaid is empty then bsn must be 0 as placeholder
bd (str) –
bound key event said of latest issuee key event at time of state update as (cross anchor)
when bound==True and bsaid is not empty
Empty string means placeholder and bsn must be 0
- property bnh
bnh property getter :returns:
- bound key state hex sequence number of issuees key state
at time of update BoundState CESR .data.bn ‘bn’ field
- Return type:
bnh (str)
- property bnhb
bnhb property getter :returns:
- bound key state hex sequence number of issuees key
state at time of update BoundState CESR .data.bn ‘bn’ field
- Return type:
bnhb (bytes)
- property bsn
bsn property getter :returns:
- bound key state sequence number of issuees key state at
time of update BoundState CESR .data.bn ‘bn’ field
- Return type:
bsn (int)
- classmethod makeUUID(raw=None, salt=None, sn=1, tier=None)[source]
Creates UUID salty nonce from provided parameters
- Returns:
blinding factor qb64
- Return type:
uuid (str)
- Parameters:
raw (bytes|None) – random crypto material as salt
salt (str|None) – qb64 of 128 bit random salt
sn (int) – sequence number of blindable update message. Converted to Number.snh which is hex str no leading zeros
tier (str|None) – used to generate salt when not provided
- property state
state property getter :returns:
- transaction state string of
BlindState CESR .data.ts ‘ts’ field
- Return type:
state (str)
- property stateb
stateb property getter :returns:
- transaction state string of
BlindState CESR .data.ts ‘ts’ field
- Return type:
stateb (bytes)
- classmethod unblind(said, *, uuid=None, acdc='', states=None, raw=None, salt=None, sn=1, tier=None, bound=False, bounds=None)[source]
Creates unblinded blinder given said, uuid, acdc said, and states list of possible state values
- Returns:
- unblinded blinder when possbile
otherwise returns None
- Return type:
blinder (Blinder)
- Parameters:
said (str) – qb64 said of blinded blinder
uuid (str|None) – qb64 blinding uuid hierarchically derived from blindable update sn and salty nonce
acdc (str) – qb64 said of associated acdc (trans event acdc)
states (list[str]|None) – list of possible state value string
raw (bytes|None) – random crypto material as salt used to create uuid when provided uuid is None
salt (str|None) – qb64 of 128 bit random salt used to create uuid when provided uuid is None and raw is none
sn (int) – sequence number of blindable update message. Converted to Number.huge which is qb64 (24 char) used to create uuid when provided uuid is None
tier (str|None) – used to create uuid when provided uuid is None
bound (bool) – True means use BoundState False means use BlindState default
bounds (list[tuple[bsn, bd]]) – possible (bsn, bd) pairs to try in computing possible bound blinded state where: bsn (int): possible bound issuee key event sequence number bd (str): bound issuee key event SAID qb64
Tests possible combinations of empty acdc, provided acdc, with empty state string plus all states strings provided by states to find and unblinded blinder that verifies against the provided said and uuid. Empty combinations for placeholder blinder
- property uuid
uuid property getter :returns: uuid of BlindState CESR .data.u ‘u’ field :rtype: uuid (str)
- property uuidb
uuidb property getter :returns: qb64b uuid of BlindState CESR .data.u ‘u’ field :rtype: uuidb (bytes)
- class keri.core.structing.BoundState(d, u, td, ts, bn, bd)
- bd
Alias for field number 5
- bn
Alias for field number 4
- d
Alias for field number 0
- td
Alias for field number 2
- ts
Alias for field number 3
- u
Alias for field number 1
- class keri.core.structing.Castage(kls, ipn)
- ipn
Alias for field number 1
- kls
Alias for field number 0
- class keri.core.structing.EmptyCastDom[source]
EmptyCastCodex is dataclass of namedtuple instances (empty casts) whose field values are Castage instances of named primitive class class references for those fields.
indexed by its namedtuple class name.
Only provide defined namedtuples casts. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
Example: EmptyCastDex[name]
- class keri.core.structing.EmptyClanDom[source]
EmptyClanDom is dataclass of namedtuple empty class references (clans) each indexed by its class name.
Only provide defined classes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
Example: EmptyClanDex[name]
- class keri.core.structing.Mediar(saidive=True, **kwa)[source]
Mediar is Structor subclass each instance holds a namedtuple .data of named values belonging to IANA media type media quadrule with blindable SAID (BLID)
See Structor class for more details.
- Inherited Class Attributes:
- Clans (type[Namedtuple]): each value is known NamedTuple class keyed
by its own field names (tuple). Enables easy query of its values() to find known data types given field names tuple.
- Casts (NamedTuple): each value is primitive class of cast keyed by fields
names of the associated NamedTuple class in .Clans. Enables finding known primitive classes given NamedTuple class of clan or instance of cast or crew.
- Names (dict): maps tuple of clan/cast fields names to its namedtuple
class type name so can look up a know clan or cast given a matching tuple
- ClanCodens (dict): map of clan namedtuple to counter code name for
ser/des as group
- CodenClans (dict): map of counter code name to clan named tuple for
ser/des as group
- Saids (dict): default saidive fields at top-level. Assumes .mad already
in most compact form. Each key is label of saidive field. Each value is default primitive code of said digest value to be
computed from serialized dummied .mad
Dummy (str): dummy character for computing SAIDs
Class Attributes:
When known casts are provided in .Clans/.Casts then more flexible creation is supported for different types of provided cast and crew. When no clan is provided and an unknown cast and/or crew are provided as Mappings then Structor may create custom clan from the names given by the cast and/or crew keys(). Subclasses may override this behavior by raising an exception for unknown or custom clans.
- Inherited Properties:
data (NamedTuple): fields are named instances of CESR primitives clan (type[NamedTuple]): class reference of .data’s class cast (NamedTuple): CESR primitive class references of .data’s primitive
instances
crew (NamedTuple): named qb64 values of .data’s primitive instances qb64 (str): concatenated data values as qb64 str of data’s primitives qb64b (bytes): concatenated data values as qb64b of data’s primitives qb2 (bytes): concatenated data values as qb2 bytes of data’s primitives saids (dict): default saidive fields at top-level.
Assumes .mad already in most compact form. Each key is label of saidive field. Each value is default primitive code of said digest
value to be computed from serialized dummied .mad
- saidive (bool): True means compute SAID(s) for toplevel fields in .saids
False means do not compute SAIDs
- said (str): qb64 said given .saids given .saids as saidive .data.d.qb64
primary said field value if any. None otherwise primary has same label as zeroth item in .saids
saidb (bytes): qb64b said given .saids as saidive fields .data.d.qb64b
- Properties:
uuid (str): qb64 uuid of TypeMedia CESR .data.u.qb64 ‘u’ field uuidb (bytes): qb64b uuid of TypeMedia CESR .data.u.qb64b ‘u’ field mt (str): media type string TypeMedia .data.mt.text ‘mt’ field mtb (bytes): media tytpe as bytes TypeMedia .data.mt.text ‘mt’ field mv (str): media value string TypeMedia .data.mv.text ‘mv’ field mvb (bytes): media value as bytes TypeMedia .data.mv.text ‘mv’ field
Methods:
- Hidden:
_data (namedtuple): named CESR primitive instances _cast (namedtuple): named Castage instances _saids (dict): default top-level said fields and codes _saidive (bool): compute saids or not
Example:
- __init__(saidive=True, **kwa)[source]
Initialize instance
- Inherited Parameters: (see Structor)
- data (NamedTuple): fields are named primitive instances for .data
Given data can derive clan, cast, crew, qb64, and qb2
- clan (type[NamedTuple]): provides class reference for generated .data
when data missing.
- cast (NamedTuple | dict | Iterable): each value provides CESR
primitive subclass reference used to create primitive instances for generating .data. Can be used to infer namedtuple type of .data when data and clan missing. Takes precendence over crew.
- crew (NamedTuple | dict | Iterable): each value provides qb64 value
of primitive for generating .data with .cast when data missing. Can be used to infer namedtuple type of .data when data and clan missing.
- qb64b (str|bytes|bytearray|None): concatenation of qb64b data values to
generate .data with data and crew missing.
qb64 (str|bytes|bytearray|None): alias for qb64b qb2 (bytes|bytearray|None): concatenation of qb2 data values to generate
.data when data and crew and qb64 missing.
- strip (bool): False means do not strip each value from qb64 or qb2.
Default is False. True means if qb64 or qb2 are bytearray then strip contained concatenated data values. Else convert qb64 or qb2 to bytearray so can strip inplace. Enables parser to extract data fields from front of CESR stream when stream is bytearray.
- makify (bool): True means compute saids when .saidive
False means do not comput saids even when .saidive
- verify (bool): True means verify serialization against mad.
False means do not verify
- saids (dict): default saidive fields at top-level.
Assumes .mad already in most compact form. Each key is label of saidive field. Each value is default primitive code of said digest
value to be computed from serialized dummied .mad
- saidive (bool): True means compute SAID(s) for toplevel fields in .saids
False means do not compute SAIDs
Parameters:
- property mt
mt property getter :returns: media type string TypeMedia .data.mt.text ‘mt’ field :rtype: mt (str)
- property mtb
mtb property getter :returns: media type as bytes TypeMedia .data.mt.text ‘mt’ field :rtype: mtb (bytes)
- property mv
mv property getter :returns: media value string TypeMedia .data.mv.text ‘mv’ field :rtype: mv (str)
- property mvb
mvb property getter :returns: media value as bytes TypeMedia .data.mv.text ‘mv’ field :rtype: mvb (bytes)
- property uuid
uuid property getter :returns: uuid of TypeMedia CESR .data.u ‘u’ field :rtype: uuid (str)
- property uuidb
uuidb property getter :returns: qb64b uuid of TypeMedia CESR .data.u ‘u’ field :rtype: uuidb (bytes)
- class keri.core.structing.SealCastDom(SealDigest: ~typing.NamedTuple = ((<class 'keri.core.coring.Diger'>, None), ), SealRoot: ~typing.NamedTuple = ((<class 'keri.core.coring.Diger'>, None), ), SealSource: ~typing.NamedTuple = ((<class 'keri.core.coring.Number'>, 'numh'), (<class 'keri.core.coring.Diger'>, None)), SealEvent: ~typing.NamedTuple = ((<class 'keri.core.coring.Prefixer'>, None), (<class 'keri.core.coring.Number'>, 'numh'), (<class 'keri.core.coring.Diger'>, None)), SealLast: ~typing.NamedTuple = ((<class 'keri.core.coring.Prefixer'>, None), ), SealBack: ~typing.NamedTuple = ((<class 'keri.core.coring.Prefixer'>, None), (<class 'keri.core.coring.Diger'>, None)), SealKind: ~typing.NamedTuple = ((<class 'keri.core.coring.Verser'>, None), (<class 'keri.core.coring.Diger'>, None)))[source]
SealCastDom is dataclass of namedtuple instances (seal casts) whose field values are Castage instances of named primitive class class references for those fields.
indexed by its namedtuple class name.
Only provide defined namedtuples casts. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
Example: SealCastDom[name]
- class keri.core.structing.SealClanDom(SealDigest: type[~typing.NamedTuple] = <class 'keri.core.structing.SealDigest'>, SealRoot: type[~typing.NamedTuple] = <class 'keri.core.structing.SealRoot'>, SealSource: type[~typing.NamedTuple] = <class 'keri.core.structing.SealSource'>, SealEvent: type[~typing.NamedTuple] = <class 'keri.core.structing.SealEvent'>, SealLast: type[~typing.NamedTuple] = <class 'keri.core.structing.SealLast'>, SealBack: type[~typing.NamedTuple] = <class 'keri.core.structing.SealBack'>, SealKind: type[~typing.NamedTuple] = <class 'keri.core.structing.SealKind'>)[source]
SealClanDom is dataclass of namedtuple seal class references (clans) each indexed by its class name.
Only provide defined classes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
Example: SealClanDom[name]
- class keri.core.structing.SealEvent(i, s, d)
- d
Alias for field number 2
- i
Alias for field number 0
- s
Alias for field number 1
- class keri.core.structing.Sealer(*pa, **kwa)[source]
Sealer is Structor subclass each instance holds a namedtuple .data of named values belonging to KERI Seals for anchoring in messages or adding to message attachments.
See Structor class for more details.
- Inherited Class Attributes:
- Clans (type[Namedtuple]): each value is known NamedTuple class keyed
by its own field names (tuple). Enables easy query of its values() to find known data types given field names tuple.
- Casts (NamedTuple): each value is primitive class of cast keyed by fields
names of the associated NamedTuple class in .Clans. Enables finding known primitive classes given NamedTuple class of clan or instance of cast or crew.
- Names (dict): maps tuple of clan/cast fields names to its namedtuple
class type name so can look up a know clan or cast given a matching tuple
- ClanCodens (dict): map of clan namedtuple to counter code name for
ser/des as group
- CodenClans (dict): map of counter code name to clan named tuple for
ser/des as group
- Saids (dict): default saidive fields at top-level. Assumes .mad already
in most compact form. Each key is label of saidive field. Each value is default primitive code of said digest value to be
computed from serialized dummied .mad
Dummy (str): dummy character for computing SAIDs
When known casts are provided in .Clans/.Casts then more flexible creation is supported for different types of provided cast and crew. When no clan is provided and an unknown cast and/or crew are provided as Mappings then Structor may create custom clan from the names given by the cast and/or crew keys(). Subclasses may override this behavior by raising an exception for unknown or custom clans.
- Inherited Properties:
data (NamedTuple): fields are named instances of CESR primitives clan (type[NamedTuple]): class reference of .data’s class cast (NamedTuple): CESR primitive class references of .data’s primitive
instances
crew (NamedTuple): named qb64 values of .data’s primitive instances qb64 (str): concatenated data values as qb64 str of data’s primitives qb64b (bytes): concatenated data values as qb64b of data’s primitives qb2 (bytes): concatenated data values as qb2 bytes of data’s primitives saids (dict): default saidive fields at top-level.
Assumes .mad already in most compact form. Each key is label of saidive field. Each value is default primitive code of said digest
value to be computed from serialized dummied .mad
- saidive (bool): True means compute SAID(s) for toplevel fields in .saids
False means do not compute SAIDs
- said (str): qb64 said given .saids given .saids as saidive .data.d.qb64
primary said field value if any. None otherwise primary has same label as zeroth item in .saids
saidb (bytes): qb64b said given .saids as saidive fields .data.d.qb64b
Methods:
- Hidden:
_data (NamedTuple): named CESR primitive instances
Example
dig = ‘ELC5L3iBVD77d_MYbYGGCUQgqQBju1o4x1Ud-z2sL-ux’ diger = Diger(qb64=dig) data = SealDigest(d=diger) name = SealDigest.__name__
sealer = Sealer(data=data) assert sealer.data == data assert sealer.clan == SealDigest assert sealer.name == SealDigest.__name__ assert sealer.cast == SealDigest(d=Castage(Diger)) assert sealer.crew == SealDigest(d=dig) assert sealer.asdict == data._asdict() ==sealer.crew._asdict()
- __init__(*pa, **kwa)[source]
Initialize instance
- Inherited Parameters:
- data (NamedTuple): fields are named primitive instances for .data
Given data can derive clan, cast, crew, qb64, and qb2
- clan (type[NamedTuple]): provides class reference for generated .data
when data missing.
- cast (NamedTuple | dict | Iterable): each value provides CESR
primitive subclass reference used to create primitive instances for generating .data. Can be used to infer namedtuple type of .data when data and clan missing. Takes precendence over crew.
- crew (NamedTuple | dict | Iterable): each value provides qb64 value
of primitive for generating .data with .cast when data missing. Can be used to infer namedtuple type of .data when data and clan missing.
- qb64 (str | bytes | bytearray): concatenation of qb64 data values to
generate .data with data and crew missing.
- qb2 (bytes | bytearray): concatenation of qb2 data values to generate
.data when data and crew and qb64 missing.
- strip (bool): False means do not strip each value from qb64 or qb2.
Default is False.
- True means if qb64 or qb2 are bytearray then strip
contained concatenated data values. Enables parser to extract data fields from front of CESR stream.
- class keri.core.structing.StateEstEvent(s, d, br, ba)
- ba
Alias for field number 3
- br
Alias for field number 2
- d
Alias for field number 1
- s
Alias for field number 0
- class keri.core.structing.StateEvent(s, t, d)
- d
Alias for field number 2
- s
Alias for field number 0
- t
Alias for field number 1
- class keri.core.structing.Structor(data=None, *, clan=None, cast=None, crew=None, naive=False, qb64b=None, qb64=None, qb2=None, strip=False, makify=False, verify=True, saids=None, saidive=False)[source]
Structor class each instance holds a namedtuple .data of named values. Each value is a primitive instance of CESR primitive subclass that supports text (qb64) and binary (qb2) domains. Structor instances can be serialized to or deserialized from concatenation of the qb64 or qb2 representations of the data values. Creation requires input of an instance of an ordered collection of named classes for creating the named instances from the input data. Smart data format inputs are supported to accomodate the many ways the named data may appear in messages and or databases.
Instance Creation Patterns:
Structor(data): Structor(crew): when known cast in .Casts for crew fields mark
Structor(clan, crew): when known cast in .Casts for clan fields mark Structor(clan, qb64): when known cast in .Casts for clan fields mark Structor(clan, qb2): when known cast in .Casts for clan fields mark
Structor(cast, crew): Structor(cast, qb64): Structor(cast, qb2):
Structor(clan, cast, crew): Structor(clan, cast, qb64): Structor(clan, cast, qb2):
- Class Attributes:
- Clans (type[Namedtuple]): each value is known NamedTuple class keyed
by its own field names (tuple). Enables easy query of its values() to find known data types given field names tuple.
- Casts (NamedTuple): each value is primitive class of cast keyed by fields
names of the associated NamedTuple class in .Clans. Enables finding known primitive classes given NamedTuple class of clan or instance of cast or crew.
- Names (dict): maps tuple of clan/cast fields names to its namedtuple
class type name so can look up a know clan or cast given a matching tuple
- ClanCodens (dict): map of clan namedtuple to counter code name for
ser/des as group
- CodenClans (dict): map of counter code name to clan named tuple for
ser/des as group
- Saids (dict): default saidive fields at top-level. Assumes .mad already
in most compact form. Each key is label of saidive field. Each value is default primitive code of said digest value to be
computed from serialized dummied .mad
Dummy (str): dummy character for computing SAIDs
When known casts or provided in .Clans/.Casts then more flexible creation is supported for different types of provided cast and crew. When no clan is provided and an unknown cast and/or crew are provided as Mappings then Structor may create custom clan from the names given by the cast and/or crew keys(). Subclasses may override this behavior by raising an exception for unknown or custom clans.
- Properties:
data (NamedTuple): instance whose fields are named instances of CESR primitives clan (type[NamedTuple]): .data’s class, class object reference cast (NamedTuple | None): values are Castage instances that each provide
CESR primitive class references and primitive init parameters used to initialize .data’s primitive instances.
- crew (NamedTuple): named qb64 serialized values of .data’s CESR primitives
data.x = Matter(qb64=crew.x). Use crew to deserialize to data. Use cast to deserialize crew to data with Matter init parameter besides qb64. Clan holds class.
qb64 (str): concatenated data values as qb64 str of data’s primitives qb64b (bytes): concatenated data values as qb64b of data’s primitives qb2 (bytes): concatenated data values as qb2 bytes of data’s primitives saids (dict): default saidive fields at top-level.
Assumes .mad already in most compact form. Each key is label of saidive field. Each value is default primitive code of said digest
value to be computed from serialized dummied .mad
- saidive (bool): True means compute SAID(s) for toplevel fields in .saids
False means do not compute SAIDs
- said (str): qb64 said given .saids given .saids as saidive .data.d.qb64
primary said field value if any. None otherwise primary has same label as zeroth item in .saids
saidb (bytes): qb64b said given .saids as saidive fields .data.d.qb64b
Methods:
- Hidden:
_data (namedtuple): named CESR primitive instances _cast (namedtuple): named Castage instances _saids (dict): default top-level said fields and codes _saidive (bool): compute saids or not
Requires that any Castage where castage.ipn is not None must have a matching property or attribute name (same as value of ipn) on its Matter subclass so it can round trip as a data field in a structor.crew
For example: Given the cast for a structor of SealEvent(i=Castage(kls=<class ‘keri.core.coring.Prefixer’>, ipn=None),
s=Castage(kls=<class ‘keri.core.coring.Number’>, ipn=’numh’), d=Castage(kls=<class ‘keri.core.coring.Diger’>, ipn=None))
Then the castage.ipn = ‘numh’ for its field as a Number instance, then number.numh must be property or attribute whose value is a serialization that would be the value of the same named __init__ parameter ‘numh’, as in, getattr(number, ipn) == serialization value
as in: number = Number(numh=value) getattr(number,’numh’)== value
Note that default of ipn=’qb64’ is already property of Matter base class as in: matter = Matter(qb64=value) matter.qb64 == value
- __init__(data=None, *, clan=None, cast=None, crew=None, naive=False, qb64b=None, qb64=None, qb2=None, strip=False, makify=False, verify=True, saids=None, saidive=False)[source]
Initialize instance
- Parameters:
data (NamedTuple|None) – fields are named primitive instances for .data Given data can derive clan, cast, crew, qb64, and qb2
clan (type[NamedTuple]) – data’s class reference for generating .data from crew or qb64 or qb2 when data missing.
cast (NamedTuple|dict|Iterable|None) – field values are Castage instances that each provide CESR primitive class references and primitive init parameter applied to .data’s primitive instances. None means use .data provided not modified through casting. Each value provides CESR primitive subclass reference used to create primitive instances to generate .data. from crew or qb64 or qb2 Can be used to infer namedtuple type of .data for clan when data and clan missing. Takes precendence over crew.
crew (NamedTuple | dict | Iterable | None) – each value provides qb64 value of primitive for generating .data with .cast when data missing. Can be used to infer namedtuple type of .data for clan when data and clan missing.
naive (bool) –
- False means when none of cast, clan, crew provided
then infer cast from namedtupe type of data in .Costs otherwise create naive cast from fields in data
- True means when when none of cast, clan, crew provided
then create naive cast from fields in data
qb64b (str|bytes|bytearray|None) – concatenation of qb64b data values to generate .data with data and crew missing.
qb64 (str|bytes|bytearray|None) – alias for qb64b
qb2 (bytes|bytearray|None) – concatenation of qb2 data values to generate .data when data and crew and qb64 missing.
strip (bool) – False means do not strip each value from qb64 or qb2. Default is False. True means if qb64 or qb2 are bytearray then strip contained concatenated data values. Else convert qb64 or qb2 to bytearray so can strip inplace. Enables parser to extract data fields from front of CESR stream when stream is bytearray.
makify (bool) – True means compute saids when .saidive False means do not comput saids even when .saidive
verify (bool) – True means verify serialization against mad. False means do not verify
saids (dict) –
default saidive fields at top-level. Assumes .mad already in most compact form. Each key is label of saidive field. Each value is default primitive code of said digest
value to be computed from serialized dummied .mad
saidive (bool) – True means compute SAID(s) for toplevel fields in .saids False means do not compute SAIDs
- property asdict
Property asdict shorthand for .crew._asdict() for round trip conversion for sad dict representation in Serder instances.
.crew is namedtuple whose fields values are serializations of the data values that respect .cast Castage.ipn formats.
- Returns:
- .crew._asdict() as a field value map (dict) with
serialized values of the data value Matter instances whose serializations respect the .cast Castage.ipn serialization formats.
- Return type:
dcrew (dict)
- property cast
Property cast :returns: named primitive classes in .data :rtype: cast (NamedTuple)
Getter for ._cast makes it read only when not None
- property clan
Property clan :returns: class of .data :rtype: clan (type[NamedTuple])
- property crew
Property crew :returns: named qb64 field values from .data :rtype: crew (NamedTuple)
Requires that any Castage where castage.ipn is not None must have a matching property or attribute name (same as value of ipn) on its Matter subclass so it can round trip as a data field in a structor.crew
For example: Given the cast for a structor of SealEvent(i=Castage(kls=<class ‘keri.core.coring.Prefixer’>, ipn=None),
s=Castage(kls=<class ‘keri.core.coring.Number’>, ipn=’numh’), d=Castage(kls=<class ‘keri.core.coring.Diger’>, ipn=None))
Then the castage.ipn = ‘numh’ for its field as a Number instance, then number.numh must be property or attribute whose value is a serialization that would be the value of the same named __init__ parameter ‘numh’, as in, getattr(number, ipn) == serialization value
given: number = Number(numh=value) getattr(number,’numh’)== value
Note that default of ipn=’qb64’ is already property of Matter base class as in: matter = Matter(qb64=value) matter.qb64 == value
- property data
Property data :returns: ._data namedtuple of primitive instances :rtype: data (NamedTuple)
Getter for ._data makes it read only
- classmethod enclose(structors, cold='txt')[source]
Serializes structors with prepended counter code in either text or binary domain as bytes determined by cold where text=’txt’ or binary=’bny’ Uses .clan of zeroth structure to determine counter.code from .ClanCodes All structors must be of the same clan to join into one group.
- Returns:
- enclosure serialized structors with
leading Counter using .clan of zeroth structor that maps to Counter code given by .ClanCodes. When cold==Colds.txt then enclosure is in qb64 text domain When cold==Colds.bny then enclosure is in qb2 binary domain
- Return type:
enclosure (bytearray)
- Parameters:
structors (list[Structor]) – instances of Structure. Must all share the same clan
cold (str) – Colds value, ‘txt’ means qb64b text domain Colds value, ‘bny’ means qb2 binary domain
- classmethod extract(qb64b=None, qb64=None, qb2=None, strip=False)[source]
List of Structor instances from serialization of counted group
- Returns:
- extracts structor instances of type cls
from qb64 or qb2 of encoded Counter and framed group that is structor uses counter.code that maps to clan given by .CodeClans
- Return type:
structors (list[Structor])
- Parameters:
qb64b (str|bytes|bytearray|memoryview|None) – text domain CESR serializaton of framed counter group (count code inclusive)
qb64 (str|bytes|bytearray|memoryview|None) – alias of qb64 for matter interface compatability
qb2 (bytes|bytearray|memoryview|None) – binary domain CESR serializaton of framed counter group (count code inclusive)
strip (bool) –
- when True and qb64 or qb2 is bytearray then strip
extracted group from qb64/qb2
Otherwise do not strip
- property name
Property name :returns: name of class of .data :rtype: name (str)
- property qb2
Property qb2 :returns: concatenated qb2 of each primitive in .data :rtype: qb2 (bytes)
- property qb64
Property qb64 :returns: concatenated qb64 of each primitive in .data :rtype: qb64 (str)
- property qb64b
Property qb64b :returns: concatenated qb64b of each primitive in .data :rtype: qb64b (bytes)
- property said
primary said field value if any. None otherwise
- Returns:
- primary said field value if any. None otherwise
primary has same label as zeroth item in .saids
- Return type:
said (str|None)
- property saidb
primary said field value if any. None otherwise
- Returns:
- primary said field value if any. None otherwise
primary has same label as zeroth item in .saids
- Return type:
said (bytes|None)
- property saidive
Getter for ._saidive
- Returns:
- True means compute SAID(s) for toplevel fields in .saids
False means do not compute SAIDs
- Return type:
saidive (bool)
- property saids
Getter for ._saids
- Returns:
- default saidive fields at top-level.
Assumes .mad already in most compact form. Each key is label of saidive field. Each value is default primitive code of said digest
value to be computed from serialized dummied .mad
- Return type:
saids (dict)
- class keri.core.structing.TypeMedia(d, u, mt, mv)
- d
Alias for field number 0
- mt
Alias for field number 2
- mv
Alias for field number 3
- u
Alias for field number 1
- class keri.core.structing.TypeMediaCastDom(TypeMedia: ~typing.NamedTuple = ((<class 'keri.core.coring.Noncer'>, 'nonce'), (<class 'keri.core.coring.Noncer'>, 'nonce'), (<class 'keri.core.coring.Labeler'>, 'text'), (<class 'keri.core.coring.Texter'>, 'text')))[source]
TypeMediaCastDom is dataclass of namedtuple instances (blind casts) whose field values are Castage instances of named primitive class class references for those fields.
indexed by its namedtuple class name.
Only provide defined namedtuples casts. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
Example: TypeMediaCastDom[name]
Note: the d field value is a SAID but so instead of Diger users Noncer which allows all the Diger codes plus empty
- class keri.core.structing.TypeMediaClanDom(TypeMedia: type[~typing.NamedTuple] = <class 'keri.core.structing.TypeMedia'>)[source]
TypeMediaClanDom is dataclass of namedtuple blinded media class references (clans) each indexed by its class name.
Only provide defined classes. Undefined are left out so that inclusion(exclusion) via ‘in’ operator works.
Example: TypeMediaClanDom[name]