Loading vLEI.wiki
Fetching knowledge base...
Fetching knowledge base...
This comprehensive explanation has been generated from 3 GitHub source documents. All source documents are searchable here.
Last updated: September 21, 2025
This content is meant to be consumed by AI agents via MCP. Click here to get the MCP configuration.
Note: In rare cases it may contain LLM hallucinations.
For authoritative documentation, please consult the official GLEIF vLEI trainings and the ToIP Glossary.
Well-known witnesses are a specialized category of KERI witness nodes that utilize predetermined cryptographic salts during key store initialization to generate deterministic witness identifiers. This approach enables predictable witness identifier creation where the resulting Autonomic Identifiers (AIDs) can be computed in advance, making them invaluable for testing scenarios but fundamentally unsuitable for production environments due to their inherent predictability.
Given a predetermined salt S and a key derivation function KDF, a well-known witness generates its identifier as:
Witness_ID = KDF(S, witness_index, derivation_parameters)
Where:
S is a publicly known salt valuewitness_index is the witness position in the configurationderivation_parameters include cryptographic suite specifications{
"salt": "0123456789abcdef",
"algorithm": "Ed25519",
"derivation_code": "A",
"witness_threshold": 2,
"witness_count": 3
}
# Example multi-layer environment detection
def is_safe_for_well_known_witnesses() -> bool:
checks = [
os.getenv('KERI_TESTING') == 'true',
os.getenv('ENVIRONMENT') in ['test', 'development'],
not any(prod_indicator in os.getenv('HOSTNAME', '').lower()
for prod_indicator in ['prod', 'production', 'live'])
]
return all(checks)
import asyncio
from concurrent.futures import ThreadPoolExecutor
async def initialize_witness_pool_parallel(salt: str, count: int) -> List[Witness]:
loop = asyncio.get_event_loop()
with ThreadPoolExecutor(max_workers=min(count, 8)) as executor:
tasks = [
loop.run_in_executor(executor, create_witness, salt, i)
for i in range(count)
]
return await asyncio.gather(*tasks)
class WellKnownWitnessKeyStore:
def __init__(self, salt: bytes, index: int):
self.salt = salt # 16-32 bytes predetermined value
self.index = index # Witness position (0-based)
self.seed = self._derive_seed(salt, index)
self.signing_key = self._generate_signing_key(self.seed)
self.identifier = self._compute_identifier(self.signing_key)
HKDF(salt, witness_index, info)Test Controller -> Witness Node: Initialize(salt, index)
Witness Node -> Key Store: DeriveKeys(salt, index)
Key Store -> Witness Node: SigningKey, Identifier
Witness Node -> Test Network: Register(identifier)
Test Network -> Test Controller: WitnessReady(identifier)
STATES: [UNINITIALIZED, DERIVING, READY, ACTIVE, ERROR]
UNINITIALIZED --[receive_salt]--> DERIVING
DERIVING --[keys_derived]--> READY
READY --[network_join]--> ACTIVE
ANY_STATE --[error]--> ERROR
def derive_witness_keys(salt: bytes, index: int, algorithm: str = "Ed25519") -> tuple:
# HKDF-based derivation for deterministic key generation
info = f"KERI-witness-{index}-{algorithm}".encode()
prk = HKDF.extract(salt, b"")
okm = HKDF.expand(prk, length=32, info=info)
if algorithm == "Ed25519":
signing_key = ed25519.SigningKey(okm)
verify_key = signing_key.get_verifying_key()
return signing_key, verify_key
else:
raise ValueError(f"Unsupported algorithm: {algorithm}")
Acceptable for Testing:
Unacceptable for Production:
@dataclass
class WellKnownWitnessConfig:
salt: str # Hex-encoded salt
index: int # Witness index
algorithm: str = "Ed25519"
threshold: int = 1
class WitnessAPI:
def initialize_well_known(self, config: WellKnownWitnessConfig) -> WitnessIdentifier:
"""Initialize witness with predetermined salt"""
if self.is_production_environment():
raise SecurityError("Well-known witnesses prohibited in production")
salt_bytes = bytes.fromhex(config.salt)
signing_key, verify_key = derive_witness_keys(salt_bytes, config.index)
identifier = self._compute_said(verify_key)
self.key_store.store(identifier, signing_key)
return WitnessIdentifier(identifier, verify_key.encode())
def validate_well_known_config(config: dict) -> bool:
required_fields = ["salt", "witnesses"]
if not all(field in config for field in required_fields):
return False
# Salt validation
salt = config["salt"]
if not isinstance(salt, str) or len(salt) < 32:
return False
# Witness configuration validation
witnesses = config["witnesses"]
if not isinstance(witnesses, list) or len(witnesses) == 0:
return False
return True
class SecureKeyStore:
def __init__(self):
self._keys = {} # In-memory key storage
self._lock = threading.RLock()
def store_key(self, identifier: str, key: bytes):
with self._lock:
# Zero-out any existing key before replacement
if identifier in self._keys:
self._secure_zero(self._keys[identifier])
self._keys[identifier] = bytearray(key)
def _secure_zero(self, data: bytearray):
"""Securely zero memory containing key material"""
for i in range(len(data)):
data[i] = 0
required_packages:
- cryptography >= 3.4.8
- pynacl >= 1.4.0
- keripy >= 1.1.0
- cesrpy >= 1.0.0
optional_packages:
- pytest >= 6.0.0 # For testing frameworks
- hypothesis >= 6.0.0 # Property-based testing
class EnvironmentDetector:
@staticmethod
def is_production() -> bool:
"""Detect production environment to prevent well-known witness usage"""
indicators = [
os.getenv("KERI_ENV") == "production",
os.getenv("NODE_ENV") == "production",
not os.getenv("TESTING"),
socket.gethostname().endswith(".prod")
]
return any(indicators)
| KERI Version | Well-Known Witnesses | CESR Version | Notes |
|---|---|---|---|
| 1.0.x | Supported | 1.0.x | Initial implementation |
| 1.1.x | Enhanced | 1.1.x | Added algorithm flexibility |
| 2.0.x | Deprecated | 2.0.x | Moving to secure alternatives |
class TestWitnessPool:
def __init__(self, salt: str, count: int, threshold: int):
self.witnesses = []
for i in range(count):
witness = WellKnownWitness(salt, i)
self.witnesses.append(witness)
self.threshold = threshold
def get_witness_identifiers(self) -> List[str]:
return [w.identifier for w in self.witnesses]
def create_test_inception_event(controller_keys, witness_pool):
"""Create inception event with well-known witnesses"""
witness_aids = witness_pool.get_witness_identifiers()
inception = {
"v": "KERI10JSON00011c_",
"t": "icp",
"d": "", # Self-addressing identifier placeholder
"i": "", # Controller identifier placeholder
"s": "0", # Sequence number
"kt": "1", # Key threshold
"k": [controller_keys[0].qb64], # Current keys
"nt": "1", # Next key threshold
"n": [controller_keys[1].qb64], # Next keys (pre-rotation)
"bt": str(witness_pool.threshold), # Witness threshold
"b": witness_aids, # Witness identifiers
"c": [], # Configuration traits
"a": [] # Anchors
}
return inception
def encode_well_known_witness_config(config: dict) -> str:
"""Encode witness configuration in CESR format"""
# Convert to CESR-compatible format
cesr_config = {
"salt": Matter(raw=bytes.fromhex(config["salt"])).qb64,
"witnesses": [
{
"i": witness["identifier"],
"idx": witness["index"]
}
for witness in config["witnesses"]
]
}
return json.dumps(cesr_config)
# Benchmark results on Intel i7-10700K @ 3.8GHz
BENCHMARK_RESULTS = {
"single_witness_init": "0.15ms",
"10_witness_pool": "1.2ms",
"100_witness_pool": "11.8ms",
"memory_per_witness": "64 bytes",
"salt_derivation": "0.05ms"
}
Per-Witness Memory Usage:
├── Signing Key: 32 bytes
├── Verifying Key: 32 bytes
├── Identifier (CESR): 44 bytes
├── Metadata: 16 bytes
└── Total: ~124 bytes per witness
Witness Pool (n=10):
├── Base Pool Object: 64 bytes
├── Witness Objects: 1,240 bytes
├── Configuration: 128 bytes
└── Total: ~1.4KB
class SaltCollisionError(Exception):
"""Raised when salt reuse is detected across test runs"""
pass
def detect_salt_collision(salt: str, test_id: str):
salt_registry = load_salt_registry()
if salt in salt_registry and salt_registry[salt] != test_id:
raise SaltCollisionError(
f"Salt {salt} already used in test {salt_registry[salt]}"
)
salt_registry[salt] = test_id
save_salt_registry(salt_registry)
class ProductionSecurityError(Exception):
"""Raised when well-known witnesses attempted in production"""
pass
def enforce_test_environment():
if EnvironmentDetector.is_production():
raise ProductionSecurityError(
"Well-known witnesses are prohibited in production environments. "
"Use secure witness initialization instead."
)
def safe_key_derivation(salt: bytes, index: int) -> Optional[Tuple[bytes, bytes]]:
try:
signing_key, verify_key = derive_witness_keys(salt, index)
# Validate key strength
if not validate_key_strength(signing_key):
logger.error(f"Weak key generated for witness {index}")
return None
return signing_key, verify_key
except CryptographicError as e:
logger.error(f"Key derivation failed for witness {index}: {e}")
return None
except Exception as e:
logger.error(f"Unexpected error in key derivation: {e}")
return None
class AtomicWitnessInitializer:
def __init__(self):
self._initialization_lock = asyncio.Lock()
self._initialized_witnesses = set()
async def initialize_witness(self, salt: str, index: int) -> WitnessIdentifier:
async with self._initialization_lock:
witness_key = f"{salt}:{index}"
if witness_key in self._initialized_witnesses:
raise ValueError(f"Witness {index} already initialized with salt {salt}")
identifier = await self._perform_initialization(salt, index)
self._initialized_witnesses.add(witness_key)
return identifier
v1.0.0 (2023-01): Initial well-known witness implementation
v1.1.0 (2023-06): Added multi-algorithm support
v1.2.0 (2023-12): Enhanced security validations
v2.0.0 (2024-06): Production environment protection
test_environment:
network_isolation: true
witness_pool_size: 5-10
salt_rotation: per_test_suite
cleanup_policy: immediate
staging_environment:
well_known_witnesses: disabled
secure_witnesses: required
production_environment:
well_known_witnesses: blocked
security_monitoring: enabled
class WellKnownWitnessMetrics:
def __init__(self):
self.initialization_count = Counter()
self.failure_count = Counter()
self.response_times = Histogram()
def record_initialization(self, witness_id: str, duration: float):
self.initialization_count.inc()
self.response_times.observe(duration)
# Alert if used in wrong environment
if EnvironmentDetector.is_production():
self.alert_production_usage(witness_id)
def monitor_well_known_usage():
"""Monitor for inappropriate well-known witness usage"""
alerts = []
# Check environment
if EnvironmentDetector.is_production():
alerts.append(SecurityAlert(
level="CRITICAL",
message="Well-known witnesses detected in production",
action="BLOCK_IMMEDIATELY"
))
# Check salt reuse
if detect_salt_reuse():
alerts.append(SecurityAlert(
level="WARNING",
message="Salt reuse detected across test runs",
action="ROTATE_SALT"
))
return alerts
def test_deterministic_witness_creation():
"""Verify same salt+index produces identical witnesses"""
salt = "test_salt_deterministic"
index = 0
witness1 = create_well_known_witness(salt, index)
witness2 = create_well_known_witness(salt, index)
assert witness1.aid == witness2.aid
assert witness1.public_key == witness2.public_key
def test_production_environment_blocking():
"""Verify production environment protection"""
with patch.dict(os.environ, {'KERI_ENV': 'production'}):
with pytest.raises(ProductionSecurityError):
create_well_known_witness("any_salt", 0)
def debug_witness_state(witness: WellKnownWitness) -> dict:
return {
'aid': witness.aid,
'index': witness.index,
'salt_hash': hashlib.sha256(witness.salt.encode()).hexdigest()[:8],
'key_strength': analyze_key_strength(witness.signing_key),
'network_status': witness.network_status,
'event_count': len(witness.event_log)
}