identity

package
v0.0.0-...-de45444 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 17, 2026 License: MIT Imports: 24 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	// DilithiumLabel is the HKDF info label for the Dilithium sub-seed.
	// The .v1 suffix reserves headroom for a future re-key-without-changing-seed.
	DilithiumLabel = "ensemble.id.dilithium.v1"
	// Ed25519Label is the HKDF info label for the Ed25519 sub-seed.
	Ed25519Label = "ensemble.id.ed25519.v1"

	// SeedSize is the size of the master identity seed in bytes.
	SeedSize = 32

	// DilithiumPublicKeySize is the size of an ML-DSA-65 public key in bytes.
	DilithiumPublicKeySize = mldsa65.PublicKeySize
	// DilithiumSignatureSize is the size of an ML-DSA-65 signature in bytes.
	DilithiumSignatureSize = mldsa65.SignatureSize
)
View Source
const BindingCanonicalLabel = "ensemble.v1.idbinding"

BindingCanonicalLabel domain-separates the bytes signed by a Binding from any other Dilithium signing context. Anyone re-implementing the binding in a different language MUST use this exact byte sequence; otherwise signatures will not interop.

View Source
const NodeService = "node"

NodeService is the reserved name for the daemon's primary identity.

View Source
const ServiceDocLabel = "ensemble.v1.servicedoc"

ServiceDocLabel domain-separates service-document signatures from every other ed25519 signing context (wire envelopes use SigDomainEnvelope, admin auth its own form). Anyone re-implementing verification in another language MUST use this exact byte sequence.

View Source
const VersionByte = 0x21

VersionByte is the address version prefix. 0x21 produces addresses starting with "E" in Base58Check — the project's identity convention (see CLAUDE.md).

Variables

View Source
var ErrBundleNotFound = errors.New("identity: bundle not found")

ErrBundleNotFound is returned by LoadBundle when no identity has been persisted under the given root yet.

View Source
var ErrInvalidBinding = errors.New("identity: binding verification failed")

ErrInvalidBinding is returned when a Binding fails any verification step (tampered fields, wrong identity pubkey, or invalid Dilithium signature).

View Source
var ErrInvalidSeed = errors.New("identity: seed must be 32 bytes")

ErrInvalidSeed is returned when DeriveIdentity is called with a seed of the wrong length.

Functions

func CanonicalBindingBytes

func CanonicalBindingBytes(ed25519Pub ed25519.PublicKey, createdAtMillis int64) []byte

CanonicalBindingBytes returns the deterministic byte sequence that CreateBinding signs and VerifyBinding verifies against.

Layout (byte-exact):

BindingCanonicalLabel        ("ensemble.v1.idbinding", 21 bytes)
0x00                         (label terminator)
uint16 big-endian            (length of ed25519_pub, currently always 32)
ed25519_pub                  (raw bytes)
int64 big-endian             (created_at_millis)

Every length is fixed today; the prefixes are present so that a future schema extension (e.g., a wider operational pubkey, or extra signed fields) can be parsed unambiguously.

func DebugLogs

func DebugLogs() bool

DebugLogs reports whether the daemon is running with verbose (debug) log output enabled. Toggled by the EnsembleLogLevel environment variable; "debug" (case-insensitive) enables full-detail logging of peer addresses and other potentially correlation-leaking fields.

func Ed25519PublicKeyToX25519

func Ed25519PublicKeyToX25519(pub ed25519.PublicKey) ([]byte, error)

Ed25519PublicKeyToX25519 converts a raw Ed25519 public key to X25519.

func IdentityDir

func IdentityDir(root string) string

IdentityDir returns the absolute path of the identity bundle directory under the given root (typically a daemon's DataDir).

func MarshalBinding

func MarshalBinding(b *Binding) ([]byte, error)

MarshalBinding serialises a Binding into its proto wire form.

func OnionSeedLabel

func OnionSeedLabel(name string) string

OnionSeedLabel returns the HKDF info label for the per-service Tor onion keypair seed: ensemble.service.<name>.onion.v1. Distinct from ServiceSeedLabel so a compromise / rotation of one role does not require rotating the other. Exposed so tests can assert label stability.

func OnionSeedLabelGen

func OnionSeedLabelGen(name string, gen int) string

OnionSeedLabelGen is OnionSeedLabel for a specific rotation generation.

func ServiceDocSigningBytes

func ServiceDocSigningBytes(doc []byte) []byte

ServiceDocSigningBytes returns the canonical byte sequence signed for a service document: label || 0x00 || doc. A single variable-length field needs no length prefix — the label terminator makes the form unambiguous.

func ServiceSeedLabel

func ServiceSeedLabel(name string) string

ServiceSeedLabel returns the HKDF info label for the per-service seed derived from a parent identity for the service named name. The label is namespaced (ensemble.service.<name>.v1) so a future schema change can rotate every service's derived seed by bumping the .v1 suffix without breaking parent identity material. Exposed so tests can assert label stability.

func ServiceSeedLabelGen

func ServiceSeedLabelGen(name string, gen int) string

ServiceSeedLabelGen is ServiceSeedLabel for a specific rotation generation.

func ShortAddress

func ShortAddress(a string) string

ShortAddress returns a redacted form of an address-like string for default log output: first 6 chars + "..." + last 4 chars. Inputs shorter than 10 chars are returned unchanged (truncation would expose more than it hides). Used at default log level so a passive log observer cannot enumerate the full peer set a node interacts with.

func StoreBundle

func StoreBundle(root string, b *Bundle) error

StoreBundle writes the 5-file identity bundle under ${root}/identity/. Each individual file uses tmp+rename so it is never torn (you read either the old bytes or the new bytes, never a partial line). Bundle-level atomicity is NOT provided — a crash partway through the five writes can leave a mix of old and new files. LoadBundle's cross-checks catch that case and refuse to load (see the package doc comment for the recovery path). The directory is created with 0700 if absent.

func Validate

func Validate(addr string) bool

Validate checks that an address has a valid Base58Check checksum and the recognised version byte.

func VerifyBinding

func VerifyBinding(b *Binding, identityDilithiumPub []byte) error

VerifyBinding checks the Dilithium signature against the given identity pubkey. Returns nil on success; otherwise ErrInvalidBinding (the underlying reason is intentionally hidden so callers can't use error strings as a timing oracle for which field failed verification).

func VerifyBindingForAddress

func VerifyBindingForAddress(pinnedAddr string, dilithiumPub, bindingBytes []byte) (ed25519.PublicKey, error)

VerifyBindingForAddress checks the address→Dilithium→binding→ed25519 chain:

  1. dilithiumPub must hash to pinnedAddr (the address IS the key pin),
  2. bindingBytes must unmarshal to an IdentityBinding that verifies under dilithiumPub.

On success it returns the bound ed25519 operational pubkey, so a caller can then verify that identity's per-message signatures locally without re-parsing the binding. This is the single source of truth for "does this binding belong to this address", shared by VerifyServiceDoc and the VerifyBinding RPC.

Reasons are descriptive: this is an operator-/consumer-side verification of caller-supplied bytes diagnosing a bad hand-off, not a signing oracle an attacker probes (the low-level VerifyBinding stays opaque for that).

func VerifyDilithium

func VerifyDilithium(pub, msg, sig []byte) (bool, error)

VerifyDilithium verifies an ML-DSA-65 signature against a marshalled Dilithium public key.

func VerifyServiceDoc

func VerifyServiceDoc(pinnedAddr string, dilithiumPub, bindingBytes, doc, sig []byte) error

VerifyServiceDoc checks the full publication chain for doc against the publisher's pinned E-address:

  1. dilithiumPub must hash to pinnedAddr (the address IS the key pin),
  2. bindingBytes must unmarshal to an IdentityBinding that verifies under dilithiumPub,
  3. sig must verify under the binding's ed25519 key over the domain-separated doc.

Returns nil only when every link holds. Distinct errors are fine here — the verifier is an operator-side consumer diagnosing a bad subscription, not a signing oracle an attacker probes (cf. ErrInvalidBinding's opacity).

Types

type Address

type Address string

Address is a Bitcoin-style Base58Check-encoded identity string.

func AddressFromDilithiumPub

func AddressFromDilithiumPub(pub []byte) Address

AddressFromDilithiumPub computes the canonical Base58Check address from a marshalled ML-DSA-65 public key. Pipeline: dilPub -> SHA-256 -> RIPEMD-160 -> Base58Check(VersionByte 0x21). The resulting address starts with "E".

func (Address) Short

func (a Address) Short() string

Short returns a truncated display form like "EaBC12...xYz9".

func (Address) String

func (a Address) String() string

String implements the Stringer interface.

type Binding

type Binding struct {
	Ed25519Pub      ed25519.PublicKey
	CreatedAtMillis int64
	DilithiumSig    []byte
}

Binding authorises an ed25519 operational pubkey under a Dilithium identity.

func UnmarshalBinding

func UnmarshalBinding(data []byte) (*Binding, error)

UnmarshalBinding parses the proto wire form. Note: parsing does NOT verify the signature — callers must invoke VerifyBinding before trusting the contents.

type Bundle

type Bundle struct {
	Identity *Identity
	Binding  *Binding
}

Bundle is the in-memory representation of a persisted identity. The Identity drives signing; the Binding accompanies it on the wire and in CONN_CONFIRM.

func DeriveBundle

func DeriveBundle(seed []byte, now time.Time) (*Bundle, error)

DeriveBundle builds a complete identity bundle from a 32-byte master seed: both keypairs (via DeriveIdentity) plus a freshly signed IdentityBinding authorising the derived operational ed25519 key, stamped with now.

The Dilithium + ed25519 keypairs and the address are fully determined by the seed alone — recover the same seed on any machine and you get the same identity. Only the binding's created_at (and therefore its deterministic Dilithium signature) depends on now; the binding is a re-attestation of the same operational key, not part of the seed-invariant identity. This is the single derive→bind→bundle path shared by first-boot generation, per-service bundle generation, and the `ensemble init` recovery flow.

func LoadBundle

func LoadBundle(root string) (*Bundle, error)

LoadBundle reads the 5-file identity bundle from ${root}/identity/. The loaded Identity is reconstructed from the on-disk Dilithium private key + ed25519 seed (rather than re-derived from a master seed) so a bundle whose master seed is unknown to the caller can still be loaded faithfully.

Returns ErrBundleNotFound if any required file is missing — callers can use that to drive first-boot generation.

LoadBundle DOES verify the binding against the persisted Dilithium pubkey. A bundle that loads but whose binding fails verification is treated as corrupt and the error returned reflects that.

type Identity

type Identity struct {
	// contains filtered or unexported fields
}

Identity is a unified node/service identity. The address is anchored to the Dilithium pubkey; the ed25519 key is an operational sub-key bound to the identity via the IdentityBinding (T2).

func DeriveIdentity

func DeriveIdentity(seed []byte) (*Identity, error)

DeriveIdentity deterministically derives both keypairs from a 32-byte seed using HKDF-SHA256 with distinct info labels per key role.

func GenerateIdentity

func GenerateIdentity() (*Identity, error)

GenerateIdentity creates a fresh Identity from a cryptographically random seed. Equivalent to DeriveIdentity(crypto-random 32-byte seed). Used by tests that don't need a deterministic identity.

func (*Identity) Address

func (id *Identity) Address() Address

Address returns the canonical post-quantum identity address: Base58Check (VersionByte || ripemd160(sha256(dilithium_pub))).

func (*Identity) BindOperationalKey

func (id *Identity) BindOperationalKey(now time.Time) (*Binding, error)

BindOperationalKey is shorthand for `id.CreateBinding(id.Ed25519Public(), now)` — produces a Binding authorising this identity's own ed25519 sub-key. First-boot identities use this; rotation flows pass an alternate ed25519 pubkey to CreateBinding directly.

func (*Identity) CreateBinding

func (id *Identity) CreateBinding(ed25519Pub ed25519.PublicKey, now time.Time) (*Binding, error)

CreateBinding signs the operational ed25519 pubkey with this identity's Dilithium private key. Returns a Binding ready to marshal + persist.

func (*Identity) DeriveOnionSeed

func (id *Identity) DeriveOnionSeed(name string) ([]byte, error)

DeriveOnionSeed deterministically derives a 32-byte seed for the named service's Tor v3 onion keypair. Same construction as DeriveServiceSeed (HKDF-SHA256 over the ed25519 sub-seed) with the onion-specific label, so the chain is master_seed → ed25519_seed → onion_seed and the onion key is recoverable from the master seed alone — closing the "seed-only recovery does not reproduce the onion" gap that the per-service identity HKDF work alone did not address (the Tor onion key was previously random-generated by tor on first AddOnion and persisted to disk).

Returns a 32-byte seed suitable for bineed25519.GenerateKey via bytes.NewReader. The clamping / sha512 expansion bine performs on the 32-byte input is deterministic, so the resulting keypair — and therefore the .onion address — is fully determined by (master_seed, service name).

func (*Identity) DeriveOnionSeedGen

func (id *Identity) DeriveOnionSeedGen(name string, gen int) ([]byte, error)

DeriveOnionSeedGen is DeriveOnionSeed for a specific rotation generation. Generation 0 reproduces the legacy onion seed exactly; a higher generation derives an unrelated seed (new .onion address) for a rotated service identity. Ticket 7a9b8f66.

func (*Identity) DeriveServiceSeed

func (id *Identity) DeriveServiceSeed(name string) ([]byte, error)

DeriveServiceSeed deterministically derives a 32-byte seed for the named service from this identity's ed25519 sub-seed via HKDF-SHA256, with the label produced by ServiceSeedLabel(name). The ed25519 sub-seed is itself HKDF-derived from the master seed in DeriveIdentity, so the full chain is master_seed → ed25519_seed → service_seed and the service seed is recoverable from the master seed alone (no per-service backup required).

The ed25519 sub-seed is chosen as the HKDF parent (rather than the master seed directly) because it is byte-stable across both DeriveIdentity(seed) and LoadBundle(root) — i.e. callable on any in-memory Identity, regardless of how it was reconstructed. Identity.Seed() returns nil for bundle-loaded identities, which would break the seed-derived contract on daemon restart.

Security trade-off: a compromise of the master seed (or any identity derived from it) reproduces every per-service identity exactly — the per-service material is no longer an independent random sample. The alternative (random per-service seeds) loses recoverability without an extra backup channel for each service. See ensemble ticket 9ef9dd21 for the full analysis.

func (*Identity) DeriveServiceSeedGen

func (id *Identity) DeriveServiceSeedGen(name string, gen int) ([]byte, error)

DeriveServiceSeedGen is DeriveServiceSeed for a specific rotation generation. Generation 0 reproduces the legacy service seed exactly; a higher generation derives an unrelated seed (new Dilithium + ed25519 keys, new address) for a rotated service identity. Ticket 7a9b8f66.

func (*Identity) DilithiumPublic

func (id *Identity) DilithiumPublic() []byte

DilithiumPublic returns the marshalled ML-DSA-65 public key bytes.

func (*Identity) DilithiumSign

func (id *Identity) DilithiumSign(msg []byte) ([]byte, error)

DilithiumSign produces an ML-DSA-65 signature over msg. Reserved for identity-level proofs (the IdentityBinding in T2); per-envelope signing uses Ed25519Sign.

func (*Identity) Ed25519Public

func (id *Identity) Ed25519Public() ed25519.PublicKey

Ed25519Public returns the Ed25519 public key.

func (*Identity) Ed25519Sign

func (id *Identity) Ed25519Sign(msg []byte) []byte

Ed25519Sign produces an Ed25519 signature over msg. Used for per-envelope wire-message authentication.

func (*Identity) Seed

func (id *Identity) Seed() []byte

Seed returns a copy of the master seed. Sensitive — callers must zeroize.

func (*Identity) ToLibp2pKey

func (id *Identity) ToLibp2pKey() (libp2pcrypto.PrivKey, error)

ToLibp2pKey returns the operational ed25519 private key wrapped as a libp2p PrivKey. Used by transport.NewHost — the libp2p host runs under the operational key (it changes if the operational key rotates; the identity Address does not).

func (*Identity) ToX25519PrivateKey

func (id *Identity) ToX25519PrivateKey() []byte

ToX25519PrivateKey converts the Identity's ed25519 operational private key to an X25519 private key for ECDH (IPInfo encryption in signaling).

func (*Identity) ToX25519PublicKey

func (id *Identity) ToX25519PublicKey() ([]byte, error)

ToX25519PublicKey converts the Identity's ed25519 operational public key to an X25519 public key.

type Keystore

type Keystore struct {
	// contains filtered or unexported fields
}

Keystore is a directory-rooted holder for per-service post-quantum identity bundles. Each service's bundle lives under <dir>/services/<name>/identity/ in the five-file layout written by StoreBundle / LoadBundle. The bundle methods (ServiceRoot, GetOrGenerateBundle, HasBundle, RemoveBundle) live in service_keystore.go.

func NewKeystore

func NewKeystore(dir string) (*Keystore, error)

NewKeystore creates a keystore rooted at dir.

func (*Keystore) GetOrGenerateBundle

func (ks *Keystore) GetOrGenerateBundle(name string, parent *Identity) (*Bundle, error)

GetOrGenerateBundle loads the persisted PQ identity bundle for name, or — if none exists yet (or the on-disk bundle is incomplete) — derives a fresh one from parent.DeriveServiceSeed(name) and persists it atomically before returning.

A missing or partial bundle (e.g. an operator deleted binding.bin) is treated as "regenerate": LoadBundle reports ErrBundleNotFound, and StoreBundle then rewrites all five files consistently from the freshly derived identity. The keypair material will be byte-identical to the previous bundle if parent and name are unchanged; only the binding's created_at timestamp will differ.

parent must be non-nil — the contract is that every service identity is derivable from a parent, so service-seed recovery from master_seed is always possible. Passing nil is a programmer error and rejected explicitly.

func (*Keystore) HasBundle

func (ks *Keystore) HasBundle(name string) bool

HasBundle reports whether a PQ identity bundle is persisted for name. It checks for the Dilithium private key, the load-bearing secret of the bundle.

func (*Keystore) RemoveBundle

func (ks *Keystore) RemoveBundle(name string) error

RemoveBundle wipes the persisted identity for name. It removes the whole per-service directory but NOT the rotation-generation sidecar, so the next GetOrGenerateBundle re-derives at the *same* generation — i.e. byte-identical keys when parent + name are unchanged. This is the "reset/recover" primitive (recover a corrupt/partial bundle), NOT rotation; use RotateBundle to get fresh keys. Removing a non-existent bundle is not an error.

func (*Keystore) RotateBundle

func (ks *Keystore) RotateBundle(name string) error

RotateBundle rotates the persisted identity for name: it bumps the rotation generation (persisted in the sidecar, which survives the wipe) and then removes the bundle directory, so the next GetOrGenerateBundle derives a *fresh, unrelated* identity — new Dilithium + ed25519 keys, new address, and (when the onion derivation reads the same generation) a new .onion. This is the real rotation primitive backing DeleteService's "fresh keypair" contract, for recovery after a suspected service-key compromise. Ticket 7a9b8f66.

func (*Keystore) ServiceGeneration

func (ks *Keystore) ServiceGeneration(name string) (int, error)

ServiceGeneration returns the current rotation generation for name (0 if the service has never been rotated / has no sidecar yet). Each RotateBundle bumps it; GetOrGenerateBundle and the onion derivation fold it into the HKDF label so a higher generation yields fresh, unrelated keys. Ticket 7a9b8f66.

func (*Keystore) ServiceRoot

func (ks *Keystore) ServiceRoot(name string) string

ServiceRoot returns the per-service directory <dir>/services/<name>. The PQ identity bundle for the service lives under <ServiceRoot>/identity/.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL