Constants and Enums

Overview

The keychain library provides a comprehensive set of constants and enumerations that define cryptographic algorithms, data types, security levels, and protocol parameters. All enum classes inherit from IntEnum to ensure compatibility with the underlying C library.

Package: keychain.constants

from keychain.constants import (
    SecurityLevel,
    DataType,
    KeychainType,
    ConsensusAlgorithm,
    EncryptionScheme,
    SignatureScheme,
    # ... and many more
)

Security and Configuration

SecurityLevel

class SecurityLevel(IntEnum):
    """Persona security level for key generation and rollovers."""

Defines security levels that determine cryptographic parameters for key generation:

Values:

  • UNKNOWN_LEVEL = 0 - Unknown security level

  • LIGHTWEIGHT = 1 - Transient crypto period (weeks/months), very low risk

  • LOW = 2 - Up to 2 year crypto period, low risk

  • MEDIUM = 3 - Up to 5 year crypto period, moderate risk

  • HIGH = 4 - Up to 10 year crypto period, high risk

  • ULTRA = 5 - 10+ year crypto period, very high risk

Example:

from keychain.constants import SecurityLevel

# Set security level for persona creation
security_level = SecurityLevel.HIGH
print(f"Security level: {security_level.name} ({security_level.value})")

SerializationFormat

class SerializationFormat(IntEnum):
    """String serialization format."""

Defines available serialization formats:

Values:

  • XML = 1 - XML format (deprecated as of 3.0)

  • PROTOBUF = 2 - Protocol Buffers format (default)

  • JSON = 3 - JSON format (coming soon)

CharEncoding

class CharEncoding(IntEnum):
    """Character encoding of data."""

Extensive character encoding support including:

Primary Encodings:

  • UTF8 = 1 - UTF-8 encoding

  • UTF16 = 2 - UTF-16 encoding

  • UTF32 = 5 - UTF-32 encoding

  • BINARY = 3 - Binary data (no character encoding)

  • US_ASCII = 6 - US ASCII encoding

ISO Encodings:

  • ISO_8859_1 through ISO_8859_10 - Various ISO 8859 encodings

  • ISO_8859_6_E, ISO_8859_6_I, ISO_8859_8_E, ISO_8859_8_I - Extended ISO variants

Asian Encodings:

  • SHIFT_JIS = 17 - Shift JIS (Japanese)

  • EUC_JP = 18 - EUC-JP (Japanese)

  • EUC_KR = 20 - EUC-KR (Korean)

  • ISO_2022_JP = 21, ISO_2022_KR = 19 - ISO 2022 variants

  • GB2312 = 27 - GB 2312 (Chinese)

  • BIG5 = 28 - Big5 (Chinese)

Other Encodings:

  • KOI8_R = 29 - KOI8-R (Russian)

  • OTHER_TEXT = 4 - Other text encoding not listed

Data Types

DataType

class DataType(IntEnum):
    """Data type metadata for serialized data."""

Comprehensive data type system supporting primitive types, complex objects, and arrays:

Primitive Types:

  • BYTES = 0 - Binary byte array

  • UTF8_STRING = 1 - UTF-8 string

  • INT32 = 2, INT64 = 3 - Signed integers

  • UINT32 = 4, UINT64 = 5 - Unsigned integers

  • BOOLEAN = 6 - Boolean value

  • SINGLE_FLOAT = 12, DOUBLE_FLOAT = 13 - Floating point numbers

Complex Types:

  • DID = 7 - Decentralized Identifier

  • VERIFIABLE_DATA = 8 - Verifiable data object

  • CREDENTIAL = 9 - W3C credential

  • TRANSACTION = 10 - Ledger transaction

  • ENCRYPTED_DATA = 11 - Encrypted data

  • KEY_LOCK = 30 - Key lock object

  • ATTESTATION = 31 - Attestation

  • PUBLIC_KEY = 34 - Public key

  • SERIALIZABLE = 36 - Generic serializable object

Array Types:

All primitive and complex types have corresponding array variants (e.g., ARRAY_BYTES = 15, ARRAY_DID = 22, etc.)

Example:

from keychain.constants import DataType

# Check data types
if data.data_type() == DataType.CREDENTIAL:
    print("This is a credential")
elif data.data_type() == DataType.ARRAY_DID:
    print("This is an array of DIDs")

Cryptographic Algorithms

Encryption Algorithms

EncryptionAlgorithmClass

class EncryptionAlgorithmClass(IntEnum):
    """Encryption algorithm class."""

Values:

  • ECIES = 1 - Elliptic Curve Integrated Encryption Scheme

  • RSA = 2 - RSA Encryption Scheme

  • DLIES = 3 - Discrete Logarithm Integrated Encryption Scheme

  • ELGAMAL = 4 - ElGamal Integrated Encryption Scheme

EncryptionScheme

class EncryptionScheme(IntEnum):
    """Specific public-key encryption algorithms."""

ECIES Variants:

  • ECIES_ECP_SECP160R1 = 1 - 160-bit curve

  • ECIES_ECP_SECP192K1 = 2 - 192-bit curve

  • ECIES_ECP_SECP224R1 = 3 - 224-bit curve

  • ECIES_ECP_SECP256R1 = 4 - 256-bit curve

  • ECIES_ECP_SECP384R1 = 5 - 384-bit curve

  • ECIES_ECP_SECP521R1 = 6 - 521-bit curve

RSA Variants:

  • RSA_OAEP_SHA_1024 = 7 - 1024-bit RSA with OAEP

  • RSA_OAEP_SHA_2048 = 8 - 2048-bit RSA with OAEP

  • RSA_OAEP_SHA_3072 = 9 - 3072-bit RSA with OAEP

  • RSA_OAEP_SHA_4096 = 10 - 4096-bit RSA with OAEP

DLIES Variants:

  • DLIES_1024 = 11 through DLIES_4096 = 14 - Various key sizes

ElGamal Variants:

  • ELGAMAL_1024 = 15 through ELGAMAL_4096 = 18 - Various key sizes

Signature Algorithms

SignatureAlgorithmClass

class SignatureAlgorithmClass(IntEnum):
    """Public-key signing algorithm class."""

Values:

  • ECDSA = 1 - Elliptic Curve Digital Signature Algorithm

  • ECGDSA = 2 - German Elliptic Curve Digital Signature Algorithm

  • RSASS = 3 - RSA Probabilistic Signature Scheme

  • DSA = 4 - Digital Signature Algorithm

SignatureScheme

class SignatureScheme(IntEnum):
    """Specific public-key signing algorithms."""

ECDSA Variants:

  • ECDSA_ECP_SECP112R2 = 150 - 112-bit curve

  • ECDSA_ECP_SECP128R1 = 149 - 128-bit curve

  • ECDSA_ECP_SECP160R1 = 129 - 160-bit curve

  • ECDSA_ECP_SECP192K1 = 130 - 192-bit curve

  • ECDSA_ECP_SECP224R1 = 131 - 224-bit curve

  • ECDSA_ECP_SECP256R1 = 132 - 256-bit curve

  • ECDSA_ECP_SECP384R1 = 133 - 384-bit curve

  • ECDSA_ECP_SECP521R1 = 134 - 521-bit curve

ECGDSA Variants:

  • ECGDSA_ECP_SECP112R2 = 152 through ECGDSA_ECP_SECP521R1 = 140 - Various curves

RSASS Variants:

  • RSASS_PSS_1024 = 141 through RSASS_PSS_4096 = 144 - Various key sizes

DSA Variants:

  • DSA_1024 = 145 through DSA_4096 = 148 - Various key sizes

Symmetric Cryptography

CipherClass

class CipherClass(IntEnum):
    """Symmetric cipher class."""

Values:

  • AES = 1 - Advanced Encryption Standard

  • CAMELIA = 2 - Camellia block cipher

Cipher

class Cipher(IntEnum):
    """Specific symmetric cipher algorithms."""

AES Variants:

  • AES_GCM_128 = 1 - AES-GCM with 128-bit key

  • AES_GCM_192 = 2 - AES-GCM with 192-bit key

  • AES_GCM_256 = 3 - AES-GCM with 256-bit key

Camellia Variants:

  • CAMELLIA_GCM_128 = 4 - Camellia-GCM with 128-bit key

  • CAMELLIA_GCM_192 = 5 - Camellia-GCM with 192-bit key

  • CAMELLIA_GCM_256 = 6 - Camellia-GCM with 256-bit key

Hash Algorithms

HashScheme

class HashScheme(IntEnum):
    """Hash algorithm."""

Values:

  • SHA_256 = 1 - SHA-256 hash algorithm

Keychain and Identity

KeychainType

class KeychainType(IntEnum):
    """Keychain type (encrypt or sign)."""

Values:

  • ENCRYPT = 0 - Encryption keychain

  • SIGN = 1 - Signature keychain

Example:

from keychain.constants import KeychainType

# Create different keychain types
encrypt_keychain = create_keychain(KeychainType.ENCRYPT)
sign_keychain = create_keychain(KeychainType.SIGN)

KeyIdType

class KeyIdType(IntEnum):
    """How a public key is represented in verifiable and encrypted data."""

Values:

  • PUBLIC_KEY = 0 - Full public key is provided

  • PUBLIC_KEY_HASH = 1 - Hash of the public key is provided

  • TXID_VOUT = 2 - Bitcoin transaction ID/output (deprecated)

DidStatus

class DidStatus(IntEnum):
    """DID lifecycle status tracked in the database."""

Values:

  • UNINITIALIZED = 0 - Yet uninitialized state

  • CREATED = 1 - Key pair created and stored

  • FUNDING = 2 - Acquiring resources for broadcasting

  • BROADCASTED = 3 - Self-signed certificate broadcasted

  • CONFIRMING = 4 - Confirmation in progress

  • CONFIRMED = 5 - Certificate confirmed (mature persona)

  • EXPIRING = 6 - Certificate expiration imminent

  • EXPIRED = 7 - Certificate has expired

Consensus and Ledger

ConsensusAlgorithm

class ConsensusAlgorithm(IntEnum):
    """Consensus algorithm used in ledger protocols."""

Values:

  • UNINITIALIZED = 0 - No algorithm specified

  • ONE_PHASE_COMMIT = 1 - Single-phase commit

  • TWO_PHASE_COMMIT = 2 - Two-phase commit (Propose/Commit)

  • THREE_PHASE_COMMIT = 3 - Three-phase commit (Propose/PreCommit/Commit)

Example:

from keychain.constants import ConsensusAlgorithm

# Set consensus algorithm
consensus = ConsensusAlgorithm.THREE_PHASE_COMMIT
print(f"Using {consensus.name} consensus")

ConsensusStage

class ConsensusStage(IntEnum):
    """Stage of a consensus protocol."""

Values:

  • PROPOSE = 1 - Propose application state

  • PRECOMMIT = 2 - Pre-commitment attestations

  • COMMIT = 3 - Final commitment attestations

  • REJECTED = 4 - Transaction rejected

LedgerResult

class LedgerResult(IntEnum):
    """Ledger-state evaluation result during consensus."""

Values:

  • NO_RESPONSE_NEEDED = 0 - No response required

  • RESPONSE_NEEDED = 1 - Response should be sent

  • PROTOCOL_LEVEL_REJECTED = 2 - Protocol rejection, send transaction

  • APPLICATION_LEVEL_REJECTED = 3 - Application rejection, don’t send

Version

class Version(IntEnum):
    """Version numbers for data formats and schemas."""

Values:

  • UNINITIALIZED_VERSION = 0 - Uninitialized

  • V20190716 = 1 - Version from July 16, 2019

  • V20200304 = 2 - Version from March 4, 2020

  • V20220412 = 3 - Version from April 12, 2022

  • V20230102 = 4 - Version from January 2, 2023

  • V20240412 = 5 - Version from April 12, 2024 (Herbie Hancock’s birthday)

Configuration Constants

Library Configuration

# Library paths
DEFAULT_LIBRARY_PATH: Final[str] = "~/.local/lib/libkeychain.so"
LIBRARY_SEARCH_PATHS: Final[List[str]] = [
    "~/.local/lib/libkeychain.so",
    "/usr/local/lib/libkeychain.so",
    "/usr/lib/libkeychain.so",
    "./libkeychain.so"
]

Default Values

# Security and serialization defaults
DEFAULT_SECURITY_LEVEL: Final[SecurityLevel] = SecurityLevel.MEDIUM
DEFAULT_SERIALIZATION_FORMAT: Final[SerializationFormat] = SerializationFormat.PROTOBUF

Protocol Constants

# Protocol identifiers
PROTOCOL_DOMAIN: Final[str] = "KC"
QUORUM_MEMBERS: Final[str] = "Members"
CONSENSUS_STAGE_TAG: Final[str] = "CS"

Confirmation and Timing

# Confirmation depths
WEAK_DEPTH: Final[int] = 1
STRONG_DEPTH: Final[int] = 3
CERTIFICATE_EXPIRATION_BLOCKS: Final[int] = 5000

Length Limits

# Size constraints
MAX_LABEL_LENGTH: Final[int] = 256
MAX_TXID_LENGTH: Final[int] = 80
MIN_TXID_LENGTH: Final[int] = 31
MAX_TRANSACTION_ATTESTATIONS: Final[int] = 1000

Transaction Indices

# Bitcoin transaction output indices
PAYLOAD_VOUT: Final[int] = 0
LINK_VOUT: Final[int] = 1

Example: Using Constants and Enums

from keychain.constants import (
    SecurityLevel,
    KeychainType,
    ConsensusAlgorithm,
    EncryptionScheme,
    SignatureScheme,
    DEFAULT_SECURITY_LEVEL,
    STRONG_DEPTH
)
from keychain.core.gateway import Gateway

def create_secure_persona():
    """Create a persona with high security settings."""

    gateway = Gateway()

    # Use high security level
    security_level = SecurityLevel.HIGH
    print(f"Creating persona with {security_level.name} security")

    # Create persona with custom settings
    persona = gateway.create_persona(
        name="secure_persona",
        security_level=security_level
    )

    return persona

def setup_consensus_transaction():
    """Setup a transaction with three-phase commit consensus."""

    # Configure consensus algorithm
    consensus_algo = ConsensusAlgorithm.THREE_PHASE_COMMIT
    print(f"Using {consensus_algo.name} consensus algorithm")

    # Transaction setup with consensus
    transaction_config = {
        "consensus_algorithm": consensus_algo,
        "confirmation_depth": STRONG_DEPTH
    }

    return transaction_config

def compare_crypto_algorithms():
    """Compare different cryptographic algorithm options."""

    # Available encryption schemes
    encryption_options = [
        EncryptionScheme.ECIES_ECP_SECP256R1,
        EncryptionScheme.RSA_OAEP_SHA_2048,
        EncryptionScheme.ECIES_ECP_SECP384R1
    ]

    # Available signature schemes
    signature_options = [
        SignatureScheme.ECDSA_ECP_SECP256R1,
        SignatureScheme.RSASS_PSS_2048,
        SignatureScheme.ECDSA_ECP_SECP384R1
    ]

    print("Encryption Options:")
    for scheme in encryption_options:
        print(f"  {scheme.name} (value: {scheme.value})")

    print("\\nSignature Options:")
    for scheme in signature_options:
        print(f"  {scheme.name} (value: {scheme.value})")

def check_data_types(data_objects):
    """Check and categorize different data types."""

    for obj in data_objects:
        data_type = obj.data_type()

        if data_type == DataType.CREDENTIAL:
            print(f"Found credential: {obj}")
        elif data_type == DataType.DID:
            print(f"Found DID: {obj}")
        elif data_type == DataType.TRANSACTION:
            print(f"Found transaction: {obj}")
        elif data_type.name.startswith("ARRAY_"):
            print(f"Found array of {data_type.name[6:].lower()}: {obj}")
        else:
            print(f"Found {data_type.name.lower()}: {obj}")

def demonstrate_keychain_types():
    """Demonstrate different keychain types."""

    # Create different keychain types
    for keychain_type in KeychainType:
        print(f"Creating {keychain_type.name.lower()} keychain")

        # Keychain type determines purpose
        if keychain_type == KeychainType.ENCRYPT:
            print("  - Used for encryption operations")
        elif keychain_type == KeychainType.SIGN:
            print("  - Used for signature operations")

# Usage examples
if __name__ == "__main__":
    print("=== Keychain Constants and Enums Demo ===\\n")

    # Default values
    print(f"Default security level: {DEFAULT_SECURITY_LEVEL.name}")
    print(f"Strong confirmation depth: {STRONG_DEPTH} blocks\\n")

    # Create secure persona
    persona = create_secure_persona()
    print()

    # Setup consensus
    config = setup_consensus_transaction()
    print(f"Transaction config: {config}\\n")

    # Compare algorithms
    compare_crypto_algorithms()
    print()

    # Demonstrate keychain types
    demonstrate_keychain_types()

Example: Algorithm Selection

from keychain.constants import (
    SecurityLevel,
    EncryptionScheme,
    SignatureScheme,
    CipherClass,
    Cipher
)

class CryptographicProfile:
    """Cryptographic algorithm profile for different security needs."""

    def __init__(self, security_level: SecurityLevel):
        self.security_level = security_level
        self.encryption_scheme = self._select_encryption_scheme()
        self.signature_scheme = self._select_signature_scheme()
        self.cipher = self._select_cipher()

    def _select_encryption_scheme(self) -> EncryptionScheme:
        """Select encryption scheme based on security level."""
        if self.security_level <= SecurityLevel.LOW:
            return EncryptionScheme.ECIES_ECP_SECP256R1
        elif self.security_level == SecurityLevel.MEDIUM:
            return EncryptionScheme.ECIES_ECP_SECP384R1
        elif self.security_level == SecurityLevel.HIGH:
            return EncryptionScheme.ECIES_ECP_SECP521R1
        else:  # ULTRA
            return EncryptionScheme.RSA_OAEP_SHA_4096

    def _select_signature_scheme(self) -> SignatureScheme:
        """Select signature scheme based on security level."""
        if self.security_level <= SecurityLevel.LOW:
            return SignatureScheme.ECDSA_ECP_SECP256R1
        elif self.security_level == SecurityLevel.MEDIUM:
            return SignatureScheme.ECDSA_ECP_SECP384R1
        elif self.security_level == SecurityLevel.HIGH:
            return SignatureScheme.ECDSA_ECP_SECP521R1
        else:  # ULTRA
            return SignatureScheme.RSASS_PSS_4096

    def _select_cipher(self) -> Cipher:
        """Select symmetric cipher based on security level."""
        if self.security_level <= SecurityLevel.MEDIUM:
            return Cipher.AES_GCM_256
        else:
            return Cipher.CAMELLIA_GCM_256

    def get_profile_summary(self) -> dict:
        """Get a summary of the cryptographic profile."""
        return {
            "security_level": self.security_level.name,
            "encryption": self.encryption_scheme.name,
            "signature": self.signature_scheme.name,
            "symmetric_cipher": self.cipher.name
        }

# Usage example
def create_security_profiles():
    """Create cryptographic profiles for different security levels."""

    profiles = {}

    for level in SecurityLevel:
        if level == SecurityLevel.UNKNOWN_LEVEL:
            continue

        profile = CryptographicProfile(level)
        profiles[level.name] = profile.get_profile_summary()

    return profiles

# Demonstrate security profiles
profiles = create_security_profiles()
for level_name, profile in profiles.items():
    print(f"\\n{level_name} Security Profile:")
    for key, value in profile.items():
        print(f"  {key}: {value}")

See Also