keri

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2026 License: Apache-2.0 Imports: 22 Imported by: 4 modules, 3 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.

README

keri-go

A KERI implementation in Go, built against conformance vectors captured from the reference implementation, and verified against two independent implementations.

go get github.com/grapeid/keri-go
package main

import (
	"fmt"

	keri "github.com/grapeid/keri-go"
)

func main() {
	// Keys live behind an interface, so a signer backed by a secure enclave —
	// which can never reveal its private key — satisfies it just as well.
	store := keri.NewMemoryKeyStore()
	chain, err := keri.NewKeychain(store, "my-identity", 1)
	if err != nil {
		panic(err)
	}

	keys, _ := chain.CurrentKeys()
	next, _ := chain.NextDigests() // the pre-rotation commitment

	icp, err := keri.BuildInception(keri.InceptionInput{
		Keys:        keys,
		NextDigests: next,
	})
	if err != nil {
		panic(err)
	}

	signed, err := keri.SignEvent(icp, chain.Signers()...)
	if err != nil {
		panic(err)
	}

	// What a peer receives is the event plus its attachments. Verifying it
	// establishes the identity and the keys in force.
	state, err := keri.ValidateSignedKEL([][]byte{signed.Message})
	if err != nil {
		panic(err)
	}
	fmt.Println(state.Identifier)
}

Why it exists

KERI identifiers are self-certifying: an identifier IS a digest of the event that created it. Change one byte of that event and you have a different identity. So two implementations either produce byte-for-byte identical output or they cannot interoperate at all. There is no partial credit.

There was no maintained, permissively licensed KERI implementation that can be linked into a mobile application. The Python one cannot be linked into a phone; the Rust one is EUPL-1.2, which a mobile app must statically link and therefore cannot hold at arm's length. Go links on both desktop and mobile, and this fills that gap.

What is implemented

Key events inception, rotation, interaction, delegated inception and rotation
Thresholds integer and fractional-weight, including nested weighted sets, for both current and next keys; SatisfiesThreshold answers whether signatures at given places meet one
Witnesses witness lists, thresholds, receipts, receipt streams
Validation key-log validation, signature verification against established key state, delegation authority; one event against the key state it follows (VerifyEvent), and an arriving event against a verified log (Admit: extends, repeats, or a recovery rotation over interactions, as keripy 1.3.6 decides it)
Duplicity detection of two conflicting events at one sequence number
Credentials ACDC credentials, registries, issuance, revocation, edge-chain verification
Keys generation, pre-rotation custody, encrypted-at-rest storage, an interface a hardware signer can satisfy
Streams CESR attachments, and publishing or reading a whole key log
Signatures indexed Ed25519 in all four forms keripy defines: A and 2A (a place in the key list and a place in the prior next-key commitments, the same or apart), B and 2B (the key list only)

Both CESR 1.0 and 2.0 can be read and built. 1.0 is the default, because 2.0 is not frozen: two builds of the reference produce different 2.0 bytes, and a self-addressing identifier minted under one form cannot be re-expressed under the other. See version.go.

What is not implemented

  • Post-quantum signatures. Ed25519 only.
  • Transaction receipt quadruples (the -D attachment group).
  • OOBI records, mailboxes, and witness network transport — this is the event layer, not an agent.
  • Serialisations other than JSON. No CBOR, MessagePack, or native CESR.

How correctness is established

Conformance. vectors/keri_vectors_v1.json holds what keripy actually produces — the reference implementation — captured exactly: canonical bytes, identifiers, and cases that must be refused. The implementation is written until it reproduces them. 71 of 71 cases pass.

The file is generated, never hand-written. An expectation somebody typed is a belief about what the answer should be; a captured one is what the reference actually does, and only the second is worth checking against.

python3 -m venv .venv && .venv/bin/pip install "keri==1.3.6"
.venv/bin/python3 vectors/generate_vectors.py > vectors/keri_vectors_v1.json
.venv/bin/python3 vectors/verify_vectors.py vectors/keri_vectors_v1.json
go test ./... -run TestConformance -v

Interoperability. Conformance is a string comparison. The stricter question is whether other implementations ACCEPT what this one produces, which runs their validators over our output. Both do:

# keripy judges what we build
go run ./interop | .venv/bin/python3 interop/verify_interop.py

# keriox — independent Rust — judges the same
go run ./interop | cargo run --manifest-path interop-keriox/Cargo.toml

# the reverse: keripy builds, keri-go must reach keripy's verdict
.venv/bin/python3 interop/keripy_builds.py | go run ./interop/judge

The rotation cases are the ones whose authority turns on which keys signed: a partial rotation with a dual-index signature, an augmented rotation, nested weighted thresholds for two and three owners, and the cases that must be refused (too few committed keys signing, a wrong prior-next place, an added key alone). Each carries keri-go's own verdict, and the keripy judge fails the run if the two disagree. Both directions exit non-zero on any disagreement.

One difference is deliberate and tested as such: keripy counts a key once per verified signature and removes only byte-identical ones, so one key signing at one place in two spellings (A and B, or A and 2A) counts twice and can meet a two-key signing or prior-next threshold alone. The same holds for a witness signing as A0 and B0 against a witness threshold of two. keripy also accepts a key list that names one key twice (k = [a, a], or n = [H(c), H(c)]), which lets that key count at both places. keri-go counts each place and each witness once and refuses any establishment event that repeats a key or digest. It refuses the key and digest cases outright, and reports the re-encoded witness case as not fully witnessed.

ValidateSignedKEL reports each event's witness-indexed signatures in Witnessing, counted against the witness list in force for that event, and FullyWitnessed says whether every event meets its witness threshold. The judge counts a log that is not fully witnessed as refused, as keripy does.

keriox judges 35 of the 45 cases as expected, including witness receipts, delegation, a credential registry, issuance and revocation, a whole key log published as a single stream, dual-index signatures and augmented rotations. The other ten are not put to it: eight carry nested weighted thresholds, which keriox does not read, and two carry a signature that does not verify, which keriox refuses outright where keripy and keri-go drop it and judge the rest. That matters more than the keripy result, because keripy generated the vectors this was built against and keriox had no part in producing anything here.

Reading a failure

A case nothing implements yet reports as a skip. A case answered wrongly fails loudly with both byte strings.

Those are deliberately different. Unimplemented is progress not yet made; wrong is a claim that the rest of the world is mistaken. A suite reporting them alike would hide the second among the first, which is how a quiet divergence survives to production.

Every case carries a why explaining what breaks if an implementation gets it wrong, and that text prints when the case fails — so a failure says what it means, not only what differed.

The rule under everything

The vector file is the specification, and it is never edited to make a test pass. If the code disagrees with a vector, the code is wrong; that assumption is correct almost every time. If somebody genuinely believes a vector is wrong, that is a finding to raise, not a line to change — a quietly edited expectation converts a disagreement with the whole KERI ecosystem into one nobody can see.

Other documents

  • MEASUREMENTS.md — what this package costs in binary size and parsing time, measured against the Rust implementation it replaces.
  • MOBILE.md — building and binding for iOS and Android, and what is not yet proven there.

Licence

Apache-2.0. See LICENSE and NOTICE.

Copyright 2026 Rob Andersen.

Documentation

Overview

Package keri implements KERI, the Key Event Receipt Infrastructure.

KERI gives an identifier a verifiable history. The identifier is derived from the event that created it, so it certifies itself: no registry, no certificate authority, and nothing to trust except the events and their signatures. Rotating keys, delegating authority, issuing and revoking credentials are all recorded as events in a log anyone can check.

Byte-for-byte or not at all

An identifier IS a digest of its own inception event. Change one byte of that event and the identity is different — so two implementations produce identical bytes or they cannot interoperate. There is no partial credit, and no amount of review substitutes for comparing the bytes.

This package is therefore written against captured expectations rather than against a reading of the specification. The vectors in vectors/ hold what the reference implementation actually produces, and the implementation is written until it reproduces them exactly. Other implementations have then been asked to accept what this one builds, which is the stricter question: keripy and keriox both do.

What is here

Building and validating key events — inception, rotation, interaction, and delegated forms — with integer and fractional-weight signing thresholds. Witness lists, witness receipts, and the thresholds that decide whether enough witnesses have agreed. Key logs, validated as a chain and against the key state they establish. ACDC credentials with registries, issuance, revocation, and verification of an edge chain back to its root. Detection of duplicity, where one identifier has signed two different histories.

Keys live behind the Signer interface, which asks for a signature and never for a key. A signer backed by a secure enclave, a TPM or an HSM cannot export its private key, so an interface demanding one would be unusable with all three; this one is not. SoftwareSigner is the in-process implementation, and FileKeyStore persists keys encrypted at rest.

Keychain manages pre-rotation, which is the property that makes a stolen key insufficient to take an identity over: an identity commits to its next key by digest, and a rotation must reveal the key that digest names. That only holds if the next key is generated in advance, kept secret until it is used, and still available when it is needed — so the keychain owns that lifecycle rather than leaving it to a caller to remember.

Versions

Both CESR 1.0 and 2.0 can be read and built, and an event says which it is, so reading needs no negotiation. Version 1.0 is the default because 2.0 is not frozen: two builds of the reference implementation produce different 2.0 bytes, and a self-addressing identifier minted under one form cannot be re-expressed under the other. See DefaultVersion.

What is not here

This is the event layer, not an agent. There is no transport, no mailbox, no OOBI resolution and no witness network. Signatures are Ed25519 only, with no post-quantum scheme. JSON is the only serialisation; CBOR, MessagePack and native CESR encoding are not implemented.

The conformance vectors: fixed answers this implementation is checked against.

Index

Constants

View Source
const (
	// CodeBlake3_256 marks a 32-byte Blake3 digest — the code every
	// self-addressing identifier carries.
	CodeBlake3_256 = "E"
	// CodeEd25519 marks a transferable Ed25519 public key: an identity that
	// may rotate.
	CodeEd25519 = "D"
	// CodeEd25519N marks a non-transferable one: an identifier that IS its key
	// and can never rotate. Witnesses are named this way, so a receipt can be
	// checked by anyone holding the identifier and nothing else.
	CodeEd25519N = "B"
	// CodeEd25519Sig marks a signature.
	CodeEd25519Sig = "0B"
	// CodeEd25519Seed marks an Ed25519 private-key seed.
	CodeEd25519Seed = "A"
)

Code lengths are fixed by the table, and the encoding depends on the length. A one-character code pads the raw bytes by one and replaces the leading character of the base64; a four-character code is a plain prefix. Decoding one with the other's rules yields bytes that are wrong rather than an error, which is the failure worth designing out.

View Source
const (
	StatusIssued  = "issued"
	StatusRevoked = "revoked"
)

The states a credential's transaction log can leave it in.

View Source
const (
	// RouteLocationScheme states the URL at which an endpoint is reachable.
	RouteLocationScheme = "/loc/scheme"
	// RouteEndRoleAdd authorises an endpoint provider in a role, and
	// RouteEndRoleCut withdraws that authorisation.
	RouteEndRoleAdd = "/end/role/add"
	RouteEndRoleCut = "/end/role/cut"
)

Routes an agent uses. A route is what tells a recipient how to read the payload, so it is part of the message rather than a hint about it.

View Source
const (
	// CounterControllerIdxSigs introduces controller indexed signatures.
	CounterControllerIdxSigs = counterControllerIdxSigs
	// CounterWitnessIdxSigs introduces witness indexed signatures.
	CounterWitnessIdxSigs = counterWitnessIdxSigs
	// CounterNonTransReceiptCouples introduces non-transferable receipt couples.
	CounterNonTransReceiptCouples = counterNonTransReceiptCouples
	// CounterTransReceiptQuadruples introduces transferable receipt quadruples.
	CounterTransReceiptQuadruples = counterTransReceiptQuadruples
	// CounterAttachedMaterialQuadlets introduces a nested run of attachments.
	CounterAttachedMaterialQuadlets = counterAttachedMaterial
)

Counter codes that introduce attachment groups. Public so a caller can assert the table without re-deriving the strings, and so the constants cases have a single source of truth that matches the wire.

View Source
const CodeSeqner = "0A"

CodeSeqner marks a sequence number written as a CESR primitive: 128 bits, so that a sequence number is a fixed width whatever its value. Its width is sizeSeqner, declared with the other attachment sizes in validation.go.

View Source
const CounterSealSourceCouples = "-G"

CounterSealSourceCouples introduces a group of source seal couples.

Variables

View Source
var (
	// V1 is CESR 1.0 — what every released implementation speaks today.
	V1 = Version{Major: 1, Minor: 0}
	// V2 is CESR 2.0. Its wire format is NOT FROZEN — see the warning below.
	V2 = Version{Major: 2, Minor: 0}
)
View Source
var DefaultVersion = V1

DefaultVersion is what this package builds when a caller does not say.

It is V1, and moving it is a decision rather than a preference.

CESR 1.0 is frozen. The same inputs produce byte-identical events across every keripy build from 1.1.17 to 2.0.0-dev6 — four releases spanning the 2.0 development — which is what makes it safe to mint identities against.

CESR 2.0 is not frozen yet. keripy 1.3.6 and keripy 2.0.0-dev6 disagree on EVERY 2.0 case in vectors/keri_vectors_v2_*.json, because the version string gained a second component between them:

1.3.6        KERICAAJSONAAEq.      16 characters
2.0.0-dev6   KERICAACAAJSONAAEt.   19 characters

Different bytes mean different digests, so an identity minted under one form is a different identity under the other. A self-addressing identifier cannot be re-expressed once issued, so minting production identities at 2.0 before the format settles is the one mistake here that cannot be undone.

Build V2 deliberately, for testing and for reading; do not make it the default until the reference stops moving.

View Source
var ErrNotImplemented = fmt.Errorf("not implemented yet")

ErrNotImplemented marks a case this implementation cannot yet answer.

Distinguished from a wrong answer on purpose. Unimplemented is a statement about how far the work has got; a wrong answer is a statement that this implementation disagrees with the rest of the world. Reporting them the same way would hide the second among the first, which is exactly the mistake this package exists to stop making.

Functions

func AnchoredEvent

func AnchoredEvent(event []byte, seal SourceSeal) ([]byte, error)

AnchoredEvent returns a transaction event with its source seal attached: the bytes that actually travel.

The seal must name the event in the ISSUER's key log that anchors this one. Getting it wrong does not corrupt anything locally — it produces a message whose authority cannot be found, which a receiver refuses.

func Answer

func Answer(c Case) ([]byte, error)

Answer produces this implementation's response to a conformance case.

This is the seam the work happens behind. Each case kind is answered by one function; filling one in moves a group of cases from "not implemented" to either agreement or a visible disagreement, and nothing in between.

It returns ErrNotImplemented rather than a wrong answer or an empty one. That distinction is the whole design of this harness: a missing answer is progress not yet made, a wrong answer is a claim that the rest of the world is wrong, and a suite that reported them identically would hide the second among the first.

func AnswerCredential

func AnswerCredential(c Case) ([]byte, error)

AnswerCredential produces this implementation's answer to a credential case.

The case kind says "credential" for everything in this file — a schema, a registry, an ACDC, an issuance, a revocation — so the input decides which. Dispatched on which fields the input HAS, never on the case's id: an implementation that recognised the case would pass the suite while being unable to do the same thing for anything else, which is the one failure this whole package exists to avoid.

func AnswerReceipt

func AnswerReceipt(c Case) ([]byte, error)

AnswerReceipt produces this implementation's answer to a receipt case.

The cigars arrive on the input and are framed, never re-signed: producing a signature requires a private key this package does not hold.

They must come from the input and nowhere else. An earlier version read them off the case's expect object, and where even that was absent, parsed them out of the expected stream itself — which meant four cases rebuilt the answer from the answer and could not fail on attachment content. The vectors were the real defect there: they asked for a stream their input could not produce. The generator now supplies the material, with every expected byte unchanged.

func AnswerStream

func AnswerStream(c Case) ([]byte, error)

AnswerStream produces this implementation's answer to a stream case.

func AttachControllerSigs

func AttachControllerSigs(sigers []string) ([]byte, error)

AttachControllerSigs frames a group of controller indexed signatures.

Order is load-bearing: the signatures are emitted in the order given, each already carrying its own index. Renumbering or reordering them breaks multi-sig exchange.

func AttachReceiptCouples

func AttachReceiptCouples(couples []ReceiptCouple) ([]byte, error)

AttachReceiptCouples frames a group of non-transferable receipt couples.

Order is part of the bytes. Reordering couples, dropping one, or deduplicating by key changes whether the toad is met.

func AttachSourceSeals

func AttachSourceSeals(seals []SourceSeal) ([]byte, error)

AttachSourceSeals frames a group of source seal couples.

func Blake3SAID

func Blake3SAID(data []byte) (string, error)

Blake3SAID returns the self-addressing identifier of some bytes.

This is the function an identity ultimately rests on: an identifier is the digest of the event that created it, so changing any byte of that event changes who the identity is.

func BuildCredential

func BuildCredential(in CredentialInput) ([]byte, error)

BuildCredential returns the canonical bytes of an ACDC.

THE ORDER THE DIGESTS ARE TAKEN IN.

A credential's identifier is a digest of the whole credential, and the attribute block inside it has an identifier of its own. So the inner one is computed FIRST and written in, and only then is the outer one taken over the result. Doing it the other way round — or recomputing the inner one after — digests a credential whose attribute block does not match its own identifier, which every verifier rejects. None of this is visible from the field list, which is why it is written down here.

The edge and rules blocks are different: this version of the format embeds them as given, with no identifier of their own, so they are digested only as part of the credential. They still have to survive byte-for-byte, which is why they are carried as raw JSON and never through a map.

func BuildDelegatedInception

func BuildDelegatedInception(in DelegationInput) ([]byte, error)

BuildDelegatedInception returns the canonical bytes of a `dip`.

THE DERIVATION RULE, which is the thing worth stating because it is invisible from the code and is where this is most easily got wrong:

A delegated inception is ALWAYS self-addressing, even with a single key.

An ordinary `icp` has two derivation styles and picks by key count: one key means BASIC derivation, where the identifier IS the public key and only `d` is blanked before digesting; anything else means SELF-ADDRESSING, where `i` and `d` are both blanked, one digest is taken, and it fills both. A `dip` does not get that choice — it takes the self-addressing path unconditionally, so `i` and `d` are equal and both are the digest of the event with both blanked.

Established from the reference implementation rather than assumed. keripy's eventing.incept() applies the single-key shortcut inside an `else` branch that runs only when no delegator was given:

if delpre is not None:      # delegated inception with ilk = dip
    ked['di'] = delpre
else:                       # non delegated
    if (code is None or code not in DigDex) and len(keys) == 1:
        ked["i"] = keys[0]

With `i` left empty, serdering.SerderKERI.makify() finds it still listed as a said field for the `dip` ilk (saids = {'d': 'E', 'i': 'E'}), dummies both, and fills both from the single digest. The vector agrees: the `dip` case has exactly one key and yet its `i` is an E… digest equal to its `d`, where the single-key `icp` case in the same file has `i` equal to its key.

WHY the protocol does it this way, since the rule is otherwise arbitrary: the delegated identifier has to commit to its delegator. If a single-key `dip` took its identifier from the key, `di` would sit outside the identifier, and the same identifier could be presented under a different delegator — the authority a delegated identity rests on could be rewritten without changing who the identity is. Digesting the whole event, `di` included, makes the delegator part of the identity itself.

Getting this wrong is the quiet failure this comment exists to prevent: using basic derivation yields a `D…` identifier and a `d` that both look perfectly well formed, verify against the event locally, and are rejected by every peer and by the delegator's own anchor.

func BuildDelegatedRotation

func BuildDelegatedRotation(in DelegationInput) ([]byte, error)

BuildDelegatedRotation returns the canonical bytes of a `drt`.

A `drt` is an ordinary rotation in every respect but one: `t` says "drt". It carries the same fields in the same order, chains to the prior event by digest, states witnesses as cuts and adds, and derives its SAID by blanking `d` alone — `i` is given, so it is not a said field here.

It carries NO `di`. That is worth stating because it looks like an omission and is not: the delegator was digested into the delegated identifier at inception and therefore cannot change, so restating it on every rotation would add bytes that say nothing new and could disagree with the founding event. Established the same way as the inception rule — keripy's eventing.deltate() is `rotate(..., ilk=Ilks.drt)` and nothing more, rotate() never writes `di`, and SerderKERI's field table for `drt` is identical to `rot`. The vector for the `drt` case shows no `di` either.

What still differs from a `rot`, and is the reason the ilk exists at all, is not in these bytes: acceptance of a `drt` depends on the delegator anchoring it, exactly as the `dip` did. A peer treating this identity as delegated will refuse a plain `rot` here, and will refuse a `drt` the delegator never anchored. Emitting `rot` therefore produces an event that is well formed, verifies against itself, and is accepted by nobody.

func BuildDelegation

func BuildDelegation(in DelegationInput) ([]byte, error)

BuildDelegation returns the canonical bytes of a delegated event.

Which event is meant is decided from the data, not from a flag: an inception is the event that has nothing before it, so an input carrying no prior event to chain to is a `dip` and one carrying a prior event is a `drt`. Reading it from a label instead would let a caller ask for a rotation at sequence zero, or an inception that chains to something, and both are events no peer accepts.

func BuildInception

func BuildInception(in InceptionInput) ([]byte, error)

BuildInception returns the canonical bytes of an inception event.

Two derivation styles live here, and getting the choice wrong is the failure this function exists to avoid:

  • BASIC — a single-key inception. The identifier IS the public key (D…), so the identity can be verified by anyone holding only the identifier. The event still carries a SAID in "d", but it is not the identifier.
  • SELF-ADDRESSING — anything else. The identifier is a digest of the event itself (E…) and equals the SAID, because no single key could stand for a set of keys.

The choice is made from the key count rather than from any label on the input, because that is what the reference implementation does: keripy's incept() takes an optional derivation code and, when none is given, uses basic derivation if and only if there is exactly one key. An implementation that always digests breaks every single-key identity that already exists; one that always uses the key cannot make a multi-key identity at all.

func BuildInteraction

func BuildInteraction(in InteractionInput) ([]byte, error)

BuildInteraction returns the canonical bytes of an interaction event.

func BuildIssuance

func BuildIssuance(in IssuanceInput) ([]byte, error)

BuildIssuance returns the canonical bytes of a credential issuance.

The event's `i` is the CREDENTIAL's identifier, not the issuer's and not the registry's: a credential has its own transaction log, and this is the first event in it. The registry is named separately in `ri`. Confusing the two produces a log no peer can reconcile with its own.

func BuildReceipt

func BuildReceipt(in ReceiptInput) ([]byte, error)

BuildReceipt returns the canonical bytes of a receipt event.

The receipt's d field is the digest of the event it covers — written into the body, not recomputed over the receipt. That is the whole point of a receipt: it names, by digest, what was seen.

func BuildReceiptStream

func BuildReceiptStream(body ReceiptInput, couples []ReceiptCouple) ([]byte, error)

BuildReceiptStream returns a receipt body with witness couples attached.

func BuildRegistryInception

func BuildRegistryInception(in RegistryInput) ([]byte, error)

BuildRegistryInception returns the canonical bytes of a registry inception.

The registry's identifier and its own event identifier are the same digest — a registry, like an identity, IS the digest of the event that founded it. So both fields are blanked together, hashed once, and filled with the same answer. Hashing with only one blanked would digest an event that never existed and produce a registry nothing else can name.

func BuildReply added in v0.1.5

func BuildReply(in ReplyInput) ([]byte, error)

BuildReply assembles a signed-in-place reply message.

func BuildRevocation

func BuildRevocation(in RevocationInput) ([]byte, error)

BuildRevocation returns the canonical bytes of a credential revocation.

Sequence number 1, chained by digest to the issuance at 0. Both are what makes an offline decision possible: a verifier holding the issuance and the revocation can tell they belong to the same credential and which came second, without asking anybody.

func BuildRotation

func BuildRotation(in RotationInput) ([]byte, error)

BuildRotation returns the canonical bytes of a rotation event.

A rotation carries the key the previous event committed to and chains to that event by digest. Both are checked by whoever reads the history, so both are places this can differ from the reference without anything local noticing.

Whether the presented key was actually pre-committed cannot be decided here — it needs the prior event, which building an event is not given. That check belongs to validation, and its absence here is why a rotation that looks perfectly well formed can still be rejected by a peer.

func BuildSchema

func BuildSchema(in SchemaInput) ([]byte, error)

BuildSchema fills a schema's $id with the digest of the schema itself.

A credential names its schema by that identifier, so a verifier holding the schema can confirm offline that it is the one the credential was issued against — and cannot be handed a modified schema that would accept a forgery.

$id rather than d: a schema is a JSON Schema document, not a KERI event, and it uses the identifier field its own format defines. Nothing else differs. It carries no version string, so there is no size to declare.

func BuildStream

func BuildStream(in StreamInput) ([]byte, error)

BuildStream returns event bytes followed by their CESR attachments.

func ComputeSAID

func ComputeSAID(raw []byte) (string, error)

ComputeSAID re-derives an event's self-addressing identifier from its bytes.

The procedure, stated because getting any part of it wrong yields a plausible answer that no other implementation agrees with: the identifier field is overwritten with placeholder characters of EXACTLY the final width, so the length the version string declares stays true, and the digest is taken over that. For a self-addressing inception the prefix field is a copy of the same identifier and is blanked too; for every other event the prefix is an identifier that already existed and is left alone.

The event's own d field is never trusted as input, since checking it is the entire point.

func CredentialStatus

func CredentialStatus(credentialSAID string, events [][]byte) (string, error)

CredentialStatus decides, offline, whether a credential is still valid.

Given the credential's identifier and the transaction events somebody handed over, in order, it walks the log and returns what state it ends in. The point is that "I was given an issuance" is not an answer: a holder presenting a revoked credential can simply not hand over the revocation, so the decision has to rest on a chain that is verifiably complete — sequence numbers with no gaps, and each event naming the digest of the one before it.

What this cannot know is whether there are later events it was not given. Nothing offline can. What it CAN do is refuse a log with a hole in it, which is what a withheld revocation would have to look like if the holder also wanted to present anything issued after it.

func DeriveMasterKey

func DeriveMasterKey(passphrase string, salt []byte) ([]byte, error)

DeriveMasterKey turns a passphrase into a master key.

The salt must be stored alongside the key directory and must not be secret; it must, however, be unique per store, or two stores protected by the same passphrase share a master key. Use NewSalt to make one.

The iteration count is deliberately not a parameter: a caller choosing it is a caller who can choose badly, and a low count is invisible until someone tries the passphrases.

func DetectVersion

func DetectVersion(raw []byte) (Protocol, Version, error)

DetectVersion reads which CESR version an event is written in, from the event.

An agent talking to a stranger calls this and then dispatches. It does not need to know in advance, and it does not need the stranger to announce anything out of band.

func EncodeIndexedSignature added in v0.2.0

func EncodeIndexedSignature(sig []byte, at SignaturePlace) (string, error)

EncodeIndexedSignature writes an Ed25519 signature with the places it counts at, choosing the code exactly as keripy 1.3.6 does: "A" when both places are the same and fit one character, "2A" otherwise; "B" for a current-only signature whose index fits one character, "2B" otherwise.

func EndpointLocation added in v0.1.5

func EndpointLocation(eid, scheme, url, dt string) ([]byte, error)

EndpointLocation states where an endpoint provider is reachable.

An empty url is meaningful rather than missing: it withdraws the location, which is how an identity says "not here any more" instead of leaving an address published that no longer answers.

func EndpointRole added in v0.1.5

func EndpointRole(cid, eid, role string, allow bool, dt string) ([]byte, error)

EndpointRole authorises, or withdraws, an endpoint provider in a role.

allow chooses the route rather than a field in the payload, because that is how the message distinguishes the two: a recipient reading only the route already knows which it is holding.

func ExportKEL

func ExportKEL(messages [][]byte) ([]byte, error)

ExportKEL writes signed messages as a single CESR stream.

The messages must be a key log in order. This does not reorder them: a log's order is part of what it asserts, and a publisher that silently sorted would hide a caller's bug rather than surface it.

func MatterQB64

func MatterQB64(code string, raw []byte) (string, error)

MatterQB64 encodes raw bytes with a CESR code.

The padding rule is the part worth stating: base64 works in three-byte groups, so the raw value is left-padded to a multiple of three and the code then replaces exactly the characters that padding produced. That is why a 32-byte value with a one-character code comes out 44 characters, and why getting the pad wrong shifts every subsequent character.

func MatterQB64Sized added in v0.5.0

func MatterQB64Sized(code string, raw []byte) (string, error)

MatterQB64Sized encodes raw under code where the code is a whole number of four-character groups, or its length past one matches the lead bytes the raw size needs: the raw bytes are left-padded with zero bytes to a multiple of three, and the code replaces as many leading characters of their base64 as its length past a multiple of four. For a four-character code and a raw size of 2 mod 3, such as an ML-DSA-65 key, that keeps the lead byte the encoding needs, which MatterQB64's one rule for every code would drop. A code whose length does not fit the raw size is refused: replacing a data character with a code character would change the value with no error.

func MatterRaw

func MatterRaw(code, qb64 string, expectLen int) ([]byte, error)

MatterRaw recovers the bytes from a CESR value, checking the code.

The code is checked rather than skipped. Values of different types are the same shape once the prefix is removed, so decoding one without checking what it claims to be is how a digest gets read as a key.

It reads only the canonical spelling, so each value has exactly one string. That matters wherever a value is compared or counted as text — an identifier is a key, a witness is counted once — and a reader that accepts a second spelling of the same bytes lets one party appear as two. Three things would otherwise give a value more than one string:

  • the lead bits. The code stands in for the lead bytes, but a code character carries 6 bits and a lead byte 8, so the character after the code carries the rest of the lead bytes. Unchecked, a one-character code gave every value 4 spellings and a two-character code 16;
  • characters outside base64url. The standard decoder skips line breaks, so a value with one inserted read as the same bytes;
  • the length. A qb64 value is always a whole number of four-character groups, and exactly as long as its code and size make it.

func MatterRawSized added in v0.5.0

func MatterRawSized(code, qb64 string, rawLen int) ([]byte, error)

MatterRawSized reads a value MatterQB64Sized wrote: exactly rawLen bytes under code, its lead bytes zero, in its one canonical spelling.

func NewSalt

func NewSalt() ([]byte, error)

NewSalt returns a fresh salt for DeriveMasterKey.

func NextDigest

func NextDigest(publicKeyQB64 string) (string, error)

NextDigest is the pre-rotation commitment for a key: the digest a current event carries in place of the key it will rotate to.

Pre-rotation is what stops a stolen current key from being enough to take an identity over. The next key is committed to by digest and never appears in the log until the rotation that uses it, so an attacker who holds the current key still cannot produce a rotation anyone will accept.

The digest is taken over the qb64 public key TEXT, not over the raw key bytes. That distinction is the whole commitment: digesting the wrong one produces a value that looks right, is the right length, and matches nothing any other implementation computes.

func ParseKELStream

func ParseKELStream(stream []byte) ([][]byte, error)

ParseKELStream splits a stream back into the messages it holds.

Every message is returned with its attachments, exactly as it appeared, so what comes out can be handed straight to ValidateSignedKEL. Re-serialising would risk changing a byte that a signature covers.

func ParseVersionString

func ParseVersionString(vs string) (proto Protocol, v Version, size int, err error)

ParseVersionString reads a version string back into its parts.

This is why no protocol negotiation is needed to READ an event: the version is the first field of the event itself, at a fixed offset, so an implementation that supports both never has to attempt one encoding and fall back to the other. Trying 2.0 and retrying as 1.0 would be both unnecessary and unsafe — a malformed event of one version can resemble a valid event of the other.

func PostQuantumTestCodes added in v0.5.0

func PostQuantumTestCodes() bool

PostQuantumTestCodes reports whether this build reads the provisional post-quantum codes: true only in a build with the "kerigo_pqtest" tag, which must never be a production one.

func ReceiptsMeetThreshold

func ReceiptsMeetThreshold(stream []byte, event []byte, designated []string) (count int, met bool, err error)

ReceiptsMeetThreshold reports how many DESIGNATED witnesses have validly receipted an event, and whether that meets the event's own parsedThreshold.

Separate from ValidateReceipts because "this receipt is genuine" and "enough witnesses have signed" are different questions, and a caller that conflates them either rejects a partly-witnessed event it should hold, or accepts one it should not.

func SatisfiesThreshold added in v0.2.0

func SatisfiesThreshold(threshold json.RawMessage, positions []int) (bool, error)

SatisfiesThreshold reports whether signatures by the keys at the given positions meet a signing threshold, given exactly as it appears in an event's kt or nt field ("2", ["1/2","1/2"], [["1","1"],["1","1"]], or a clause of weighted sets such as [{"1/2":["1","1"]},{"1/2":["1","1"]}]).

A position is a place in the key list the threshold weighs: the index of a verified signature for kt, or the prior-next place it opened for a prior nt. Each position counts once. This is the rule every validator in this package applies, exported so that code holding the positions some other way asks the same question rather than re-deriving it.

An unreadable threshold, or one no set of signatures could ever meet, is an error rather than a no, so a caller cannot mistake a broken event for an unsigned one.

func SelfTestJSON added in v0.1.2

func SelfTestJSON() (string, error)

SelfTestJSON runs the suite and returns the result as JSON.

The shape a language binding wants: one string across the boundary, rather than a structure that gomobile cannot carry.

func SeqnerFromQB64

func SeqnerFromQB64(qb64 string) (uint64, error)

SeqnerFromQB64 reads a sequence number back.

func SeqnerQB64

func SeqnerQB64(sn uint64) (string, error)

SeqnerQB64 renders a sequence number as CESR writes it.

Fixed at 128 bits regardless of the value, which is why sequence number one is twenty-four characters rather than two. A variable-width encoding would make the attachment's length depend on its contents, and the parser reads by width.

func ValidateDelegation

func ValidateDelegation(delegated []byte, delegatorKEL [][]byte) error

ValidateDelegation reports whether a delegator's key log authorises a delegated event.

`delegated` is the dip or drt being checked. `delegatorKEL` is the delegator's own key log, in order, which is validated in full first — an approval anchored in a log that does not hold up is not an approval.

A delegated inception names its delegator; a delegated rotation does not carry `di` at all, so for a drt the delegator is taken from whose log is supplied. That is the reference's shape, confirmed against the vectors, and it is why this function needs the log rather than just the event.

func ValidateDelegationSigned

func ValidateDelegationSigned(delegated []byte, delegatorMessages [][]byte) error

ValidateDelegationSigned is ValidateDelegation over a delegator log that carries its signatures.

Prefer it. ValidateDelegation checks that the approving seal is present in a structurally sound log, which is worth something but not everything: a seal lives in an interaction event, and an interaction carries no keys of its own, so nothing in a bare key log attests that the delegator produced it. Anyone able to hand you bytes could fabricate an interaction anchoring any delegation they liked.

This variant verifies every event in the delegator's log against the key state that log establishes, so the interaction holding the seal has been signed by the delegator's established keys before the seal is read.

func ValidateEvent

func ValidateEvent(raw []byte) error

ValidateEvent checks everything about an event that can be decided from the event alone.

That is: it is well formed, it carries exactly the fields its type defines in the order the protocol serialises them, its version string tells the truth about its length, its contents digest to the identifier it claims, and its thresholds are ones that could ever be met. Anything that needs a predecessor — sequence, prior digest, pre-rotation — is ValidateKEL's job, because it cannot be answered without one.

func ValidateKEL

func ValidateKEL(events [][]byte) error

ValidateKEL decides whether a sequence of events is really one identity's history, in the order given.

Events are raw serialised bytes — [][]byte rather than []json.RawMessage on purpose. json.RawMessage invites a caller to treat an event as a JSON value to be re-encoded, and re-encoding is precisely what destroys an identifier: the field order is part of what the digest covers and Go sorts a map's keys. These are bytes that happen to be JSON, and the type says so.

What it checks, beyond each event on its own:

  • the log begins with an inception at sequence number zero
  • every event names the same identity
  • sequence numbers are contiguous, so nothing was inserted or dropped
  • every event digests its predecessor, so nothing was substituted
  • every rotation lists keys that could, by signing, open enough of the previous establishment event's commitments to meet its next threshold. Whether the keys that actually signed do is ValidateSignedKEL's question, because it needs the signatures
  • a rotation's witness changes refer to witnesses that are actually there

Two things it deliberately does NOT check, stated here because a caller who mistook this verdict for either of them would be trusting something nobody checked:

  • Signatures. An event's bytes do not carry them, and inventing a verdict about a signature that was never supplied would be the most dangerous thing this package could do. Use ValidateStream, or ValidateReceipts, where the attachments are available.
  • Delegation. A dip or drt is checked as an event and as a link in this chain, but whether the DELEGATOR actually anchored it needs the delegator's own key history, which is not among the arguments. Accepting a delegated event here says the identity's own history is sound; it says nothing about whether the delegation was authorised.

func ValidateReceipts

func ValidateReceipts(stream []byte, event []byte, designated []string) error

ValidateReceipts checks a witness receipt stream against the event it covers.

A receipt is a witness saying "I saw this event, and this is the one I saw". Two things make that worth anything and both are checked here: the signature must verify under the witness's own identifier, and the witness must be one the identity designated. Dropping either check hands an attacker the toad — they either forge votes or bring their own witnesses.

designated may be nil, in which case the witnesses named by the event itself are used. Passing them explicitly is for the case where the event's witness list has since been changed by a rotation.

func ValidateStream

func ValidateStream(raw []byte) error

ValidateStream checks an event with its attachments as it arrives on the wire.

The event is validated as usual, the attachments must be complete, and — when the event is an establishment event, which carries its own keys — the attached controller signatures must verify against those keys and meet the event's own signing parsedThreshold. An interaction event's keys come from an earlier establishment event, so its signatures cannot be checked without the log; ValidateSignedKEL does that.

func VerifySchema

func VerifySchema(raw []byte) (string, error)

VerifySchema checks a schema against its own $id and returns it.

A verifier that accepted a schema without checking this could be handed a widened schema that validates a forgery, while the credential still named the original.

func VerifySignature

func VerifySignature(publicKeyQB64 string, data, signature []byte) error

VerifySignature checks a raw signature against a qb64 public key, through VerifyUnderKey.

Accepts either Ed25519 key code: a transferable controller key or a non-transferable witness key both verify the same way, and refusing one of them here would make witness receipts uncheckable. In a build with the kerigo_pqtest tag an ML-DSA-65 key verifies too; an ECDSA key never does.

func VerifyUnderKey added in v0.5.0

func VerifyUnderKey(key string, msg []byte, sigCode string, sig []byte) error

VerifyUnderKey checks one signature over msg under key, by the key's code: an Ed25519 key ("D" or "B") takes an Ed25519 signature, and a registered key (ML-DSA-65, in a build with the "kerigo_pqtest" tag only) the signature it was registered with. A build without the tag refuses a post-quantum key outright, as it refuses to read one.

sigCode is the signature's indexed code ("A", "B", "2A", "2B", or a registered one), or "" for a raw signature that carries none. A signature whose code does not fit the key's, such as an Ed25519 one offered for an ML-DSA-65 key, is refused, and so is a raw signature of the wrong size for the key. A nil error means the signature verifies; every other outcome is an error saying why.

func VersionString

func VersionString(proto Protocol, v Version, size int) (string, error)

VersionString renders the first field of an event.

Types

type Admission added in v0.4.0

type Admission struct {
	Verified
	// Supersedes is how many events at the end of the log this event
	// replaces: zero when it extends the log, and for a recovery rotation the
	// interactions after the event it follows.
	Supersedes int
	// Repeat is whether the log already holds this event at its place.
	// Nothing about the log changes. Signatures and Witnessing say which of
	// the signatures given with it verify, so a late witness signature or a
	// further controller signature can be kept; State is the state at the
	// event's own place, which for a repeat of an earlier event is not the end
	// of the log.
	Repeat bool
	// Log is the verified log with this event admitted: extended, with the
	// superseded interactions replaced, or unchanged for a repeat. Admit it
	// the next event, rather than verifying the whole log again.
	Log *SignedKELResult
}

Admission is an event judged against a verified log it arrived for.

type Case

type Case struct {
	ID string `json:"id"`
	// Kind selects what is being asserted — an event to build, a property that
	// must hold, or something that must be refused.
	Kind string `json:"kind"`
	// Why this case exists. Carried in the data so a failure explains what it
	// means rather than only what differed.
	Why string `json:"why"`
	// Assert names the property a "property" case states, so the assertion is
	// read from the vector rather than inferred from the case id.
	Assert string          `json:"assert"`
	Input  json.RawMessage `json:"input"`
	Expect Expectation     `json:"expect"`
	// ExpectRaw is the expect object as raw JSON. Structured Expectation only
	// models the fields every case shares; attachment material (couples,
	// cigars, constants tables) lives in the rest of the object and is read
	// from here by the builders that need it.
	ExpectRaw json.RawMessage `json:"-"`
}

Case is one expectation: given this input, exactly these bytes.

func (*Case) UnmarshalJSON

func (c *Case) UnmarshalJSON(data []byte) error

UnmarshalJSON keeps the expect object twice: once as the structured Expectation the harness compares against, and once as raw JSON so builders can read attachment material the struct does not model.

type CaseResult added in v0.1.2

type CaseResult struct {
	ID string `json:"id"`
	// Status is "pass", "fail", or "unimplemented".
	Status string `json:"status"`
	// Detail explains a failure. Empty when the case passed.
	Detail string `json:"detail,omitempty"`
	// Why is the case's own explanation of what breaks if an implementation
	// gets it wrong, carried through so a failure on a device says what it
	// means rather than only what differed.
	Why string `json:"why,omitempty"`
}

CaseResult is what happened to one conformance case.

type ChainEdge

type ChainEdge struct {
	// Name is the edge's label, which says what the link MEANS — which
	// authority is being claimed, not merely that one exists.
	Name string
	// Target is the identifier of the credential depended on.
	Target string
	// Schema, when stated, is the schema that credential must have.
	Schema string
}

ChainEdge is one link: an edge name, and the credential it points to.

type Credential

type Credential struct {
	SAID          string
	Issuer        string
	SchemaSAID    string
	Registry      string
	Recipient     string
	Salt          string
	AttributeSAID string
	Attributes    json.RawMessage
	Edges         json.RawMessage
	Rules         json.RawMessage
	Raw           []byte
}

Credential is what a verifier learns from a credential's bytes.

Every field here was read out of the credential and confirmed against its digests. Nothing was looked up.

func VerifyCredential

func VerifyCredential(raw []byte) (*Credential, error)

VerifyCredential checks a credential against itself, using nothing else.

This is the offline check. It confirms, in this order:

  1. the bytes are the canonical serialisation — not merely valid JSON that happens to parse to the same thing;
  2. the version string declares the length the credential actually is;
  3. the attribute block's identifier is a digest of that block;
  4. the credential's identifier is a digest of the whole credential.

The inner check comes first for the same reason the inner digest is computed first when building: the outer digest covers the inner identifier, so an outer digest that matched while the inner one did not would mean somebody had substituted an attribute block and recomputed around it. Checking the outer one alone would not catch a forged attribute block whose own `d` was left stale, and checking them in the other order reports the wrong failure.

What this does NOT establish: that the issuer authorised it. That is a signature over these bytes and a walk of the issuer's key history, which is a separate concern from the credential's own integrity. This function proves the bytes are intact and self-consistent; it never claims they are genuine.

func (*Credential) Private

func (c *Credential) Private() bool

Private reports whether the credential is privacy-preserving.

type CredentialInput

type CredentialInput struct {
	SchemaSAID string `json:"schema_said"`
	Issuer     string `json:"issuer"`
	// Recipient is who the credential is about. Omitted for a credential that
	// names no holder — a public attestation rather than something issued to
	// somebody.
	Recipient string `json:"recipient"`
	// Registry is the credential's revocation registry. Empty means the
	// credential is not registry-backed and carries no `ri` field at all.
	// Inventing an empty one would change the identifier.
	Registry string `json:"registry"`
	// Data are the issuer's claims, carried as the bytes they arrived as so
	// their order survives. `dt` is required: it moves to a fixed position in
	// the attribute block, and a builder that filled it with the current time
	// would produce a credential the caller cannot predict or reproduce.
	Data json.RawMessage `json:"data"`
	// Source is the edge block: what other credential this one depends on.
	Source json.RawMessage `json:"source"`
	// Rules is the rules block: the terms the credential is issued under.
	Rules json.RawMessage `json:"rules"`
	// Private marks a privacy-preserving credential, which carries a salt at
	// the top level and in its attribute block. The salt is part of both
	// digests, so a holder can disclose one attribute without the verifier
	// being able to guess the rest by hashing candidates.
	Private bool   `json:"private"`
	Salt    string `json:"salt"`
}

CredentialInput is what issuing a credential is given.

type CredentialResolver

type CredentialResolver interface {
	// Credential returns the credential with this identifier, or an error if it
	// cannot be found.
	Credential(said string) ([]byte, error)
}

CredentialResolver finds a credential by its identifier.

An interface because where credentials come from is not this package's business: a local store, a peer's agent, a registry service. What matters is that resolution can fail, and that failure is not the same as absence being acceptable.

type DelegationInput

type DelegationInput struct {
	// Delegator is the identifier that authorises this one. Required for a
	// `dip`, where it is written into `di` and therefore digested into the
	// delegated identifier itself.
	Delegator string `json:"delegator"`

	// Prefix is the delegated identity's own identifier. Absent on a `dip` —
	// that event is what computes it — and required on a `drt`.
	Prefix string `json:"prefix"`

	Keys        []string `json:"keys"`
	NextDigests []string `json:"next_digests"`

	// PriorSAID and SN chain a `drt` to the event before it. Their absence is
	// what marks an input as a delegated INCEPTION; see BuildDelegation.
	PriorSAID string `json:"prior_said"`
	SN        int    `json:"sn"`

	// Thresholds are either a hex count string ("2") or a list of weight
	// strings (["1/2","1/2","1/2"]). Kept as raw JSON so both forms the
	// reference produces survive the trip without this package inventing a type
	// that can only express one of them.
	Isith json.RawMessage `json:"isith"`
	Nsith json.RawMessage `json:"nsith"`

	// A `dip` states its witnesses outright, as any inception does. A `drt`
	// states them as a DELTA against the set the identity already has, which is
	// why it needs the prior set as well as the cuts and adds.
	Witnesses      []string `json:"witnesses"`
	PriorWitnesses []string `json:"prior_witnesses"`
	Cuts           []string `json:"cuts"`
	Adds           []string `json:"adds"`

	// A pointer because absent and zero are different answers: absent means
	// "derive the threshold from the witness count", zero means "no witness
	// need agree", and a plain int could not tell them apart.
	Toad *int `json:"toad"`

	// Seals stay as raw bytes. A seal's own field order is part of the event,
	// and Go marshals a map alphabetically, so any trip through one silently
	// reorders it and changes the identifier.
	Data []json.RawMessage `json:"data"`
	// Version is which CESR version to build. The zero value means
	// DefaultVersion. It is carried on the input rather than set globally so
	// that an agent can answer a 1.0 peer and a 2.0 peer concurrently.
	Version Version `json:"version"`
}

DelegationInput is what building a delegated event is given.

One type covers both `dip` and `drt` because the vectors present them as one kind, and because which one is meant is decided by the data rather than by a label: an inception has nothing before it, a rotation chains to something. Field names match the vector file, which matches the reference implementation's parameters.

type Derivation

type Derivation string

Derivation is how an identifier was made from its inception event.

Both kinds are real and both are in use, which is the whole point of naming them: an implementation that assumes the identifier is always the digest breaks every single-key identity that already exists, and one that assumes it is always the key cannot make a multi-signature identity at all.

const (
	// DerivationBasic: the identifier IS the public key. Single-key inception
	// only, and the identifier reads D… (or B… when the key can never rotate).
	DerivationBasic Derivation = "basic"
	// DerivationSelfAddressing: the identifier IS the digest of the inception
	// event, and reads E….
	DerivationSelfAddressing Derivation = "self-addressing"
)

type Duplicity

type Duplicity struct {
	// Identifier is the identity that signed both.
	Identifier string
	// SN is the position they disagree about.
	SN uint64
	// Seen is the event recorded first.
	Seen string
	// Conflicting is the event that disagrees with it.
	Conflicting string
	// SeenRaw and ConflictingRaw are both events, kept because the evidence is
	// the pair of signed events and not the assertion that they differ. Anyone
	// told about this must be able to check it rather than take it on trust.
	SeenRaw        []byte
	ConflictingRaw []byte
}

Duplicity is proof that an identity produced two different events at one point in its history.

func (*Duplicity) Error

func (d *Duplicity) Error() string

type Event

type Event struct {
	Raw        []byte
	Fields     []jsonField
	Ilk        string
	Identifier string
	SAID       string
	SN         uint64
	PriorSAID  string
	Keys       []string
	NextDigest []string
	Witnesses  []string // b, on an inception
	WitnessCut []string // br, on a rotation
	WitnessAdd []string // ba, on a rotation
	Delegator  string
	// Thresholds are kept in parsed form; nil when the ilk does not carry one.
	SigThreshold  *parsedThreshold
	NextThreshold *parsedThreshold
	TOAD          uint64
	HasTOAD       bool
}

Event is a KERI event as it was read from the wire.

Raw is kept because it, and not any field here, is what the identifier digests and what a signature covers. Everything else is a convenience for checks that do not need the bytes.

func ParseEvent

func ParseEvent(raw []byte) (*Event, error)

ParseEvent reads an event's bytes into the fields a check needs.

It does NOT decide whether the event is acceptable — that is ValidateEvent. The split matters: parsing failing means "these bytes are not an event", which is a different statement from "this event is not allowed", and a caller that cannot tell them apart cannot tell a corrupt file from an attack.

func (*Event) Derivation

func (e *Event) Derivation() Derivation

Derivation says how this event's identifier was made.

func (*Event) Establishment

func (e *Event) Establishment() bool

Establishment reports whether this event changes the identity's keys — the events a later rotation must chain its authority to.

func (*Event) Seals

func (e *Event) Seals() ([]Seal, error)

Seals returns the anchors in an event's `a` field.

An event with no `a` field, or an empty one, has no seals and that is not an error — most events anchor nothing.

type EventWitnessing added in v0.3.0

type EventWitnessing struct {
	SN  uint64
	Ilk string
	// Witnesses is the list the signatures' indexes point into.
	Witnesses []string
	// Threshold is the witness threshold (toad) in force for this event.
	Threshold uint64
	// Signed lists each witness whose signature verified, once, in the order
	// of Witnesses.
	Signed []string
	// Dropped counts attached witness signatures that attest nothing: one
	// that does not verify, or names a place outside Witnesses. Like a
	// controller signature that does not verify, it is dropped rather than
	// refusing the log, since anyone passing the event along could append it.
	Dropped int
	// Met is whether len(Signed) meets Threshold.
	Met bool
}

EventWitnessing is what one event's witness-indexed signatures establish.

A witness-indexed signature names its witness by position in the witness list in force for the event: the inception's b, changed by each rotation's cuts and adds, and carried unchanged across interactions. Each witness counts once however many of its signatures are attached. Ed25519 signatures are deterministic, so a witness's one signature can be re-attached under a second code by anyone holding it; counting signatures rather than witnesses would let one witness meet a threshold of two.

type Expectation

type Expectation struct {
	// RawB64 is the authoritative serialisation: the bytes a signature covers
	// and the bytes the identifier is a digest of. Everything else here is
	// derived from it or is for humans.
	RawB64 string `json:"raw_b64"`
	SAID   string `json:"said"`
	AID    string `json:"aid"`
	// Refused marks a case that must be rejected. A conformant implementation
	// failing to reject is as wrong as one producing the wrong bytes, and
	// rather more dangerous.
	Refused bool   `json:"refused"`
	Because string `json:"because"`
	// Constants for cases that assert normative code-table values.
	Codes map[string]string `json:"-"`
}

Expectation is what a conformant implementation must produce.

func (Expectation) Raw

func (e Expectation) Raw() ([]byte, error)

Raw returns the canonical bytes this case expects.

type Fault

type Fault struct {
	// Kind is what rule was broken.
	Kind FaultKind
	// Where names the event or attachment the fault is in, so a refusal in a
	// long log points at a place rather than at the log.
	Where string
	// Detail says what is wrong in plain words.
	Detail string
}

Fault is one reason something was refused.

func (Fault) String

func (f Fault) String() string

type FaultKind

type FaultKind string

FaultKind names what was wrong, in a form a program can branch on.

The kinds are stable strings rather than integers so a refusal survives a log file, a wire format, or a bug report without a lookup table.

const (
	// FaultMalformed is bytes that are not a readable KERI event at all.
	FaultMalformed FaultKind = "malformed"
	// FaultVersionLength is a version string that declares a size the event
	// does not have — the signal that something was appended or removed.
	FaultVersionLength FaultKind = "version-length"
	// FaultUnknownIlk is an event type this validator does not know.
	FaultUnknownIlk FaultKind = "unknown-ilk"
	// FaultUndefinedField is a field the schema does not define.
	FaultUndefinedField FaultKind = "undefined-field"
	// FaultMissingField is a field the schema requires and the event omits.
	FaultMissingField FaultKind = "missing-field"
	// FaultFieldOrder is the right fields in the wrong order. Order is part of
	// the serialisation the digest covers, so this is a real difference and not
	// a cosmetic one.
	FaultFieldOrder FaultKind = "field-order"
	// FaultSAIDMismatch is an event whose contents do not digest to the
	// identifier it claims.
	FaultSAIDMismatch FaultKind = "said-mismatch"
	// FaultDerivationMismatch is an identifier that does not match how the
	// event says it was derived — a self-addressing prefix that is not the
	// event's digest, or a basic prefix that is not the event's key.
	FaultDerivationMismatch FaultKind = "derivation-mismatch"
	// FaultThresholdExceedsKeys is a signing parsedThreshold larger than the number
	// of keys supplied, which can never be met.
	FaultThresholdExceedsKeys FaultKind = "parsedThreshold-exceeds-keys"
	// FaultTOADExceedsWitnesses is a witness parsedThreshold larger than the number
	// of witnesses designated.
	FaultTOADExceedsWitnesses FaultKind = "toad-exceeds-witnesses"
	// FaultSequenceSkip is a sequence number that does not follow its
	// predecessor.
	FaultSequenceSkip FaultKind = "sequence-skip"
	// FaultPriorDigestMismatch is a prior-event digest that is not the digest
	// of the previous event.
	FaultPriorDigestMismatch FaultKind = "prior-digest-mismatch"
	// FaultIdentifierMismatch is an event attributed to a different identity
	// than the log it arrived in.
	FaultIdentifierMismatch FaultKind = "identifier-mismatch"
	// FaultKeyNotPrecommitted is a rotation whose keys could not open enough
	// of the previous establishment event's commitments to meet its next
	// threshold, even if every one of them signed.
	FaultKeyNotPrecommitted FaultKind = "key-not-precommitted"
	// FaultWitnessListInvalid is a witness list that cannot be right: a
	// rotation cutting a witness that is not there or adding one that already
	// is, an entry that is not a canonical non-transferable identifier, or one
	// witness named twice.
	FaultWitnessListInvalid FaultKind = "witness-list-invalid"
	// FaultKeyListInvalid is an establishment event that lists one signing key
	// twice in k, or one next-key digest twice in n, so that one key could
	// count twice toward a threshold.
	FaultKeyListInvalid FaultKind = "key-list-invalid"
	// FaultReceiptSignature is a receipt whose signature does not verify —
	// including one whose signature or signer cannot be read at all, since in
	// neither case has a witness vote been demonstrated.
	FaultReceiptSignature FaultKind = "receipt-signature"
	// FaultUndesignatedWitness is a receipt from an identifier the event never
	// named as a witness.
	FaultUndesignatedWitness FaultKind = "undesignated-witness"
	// FaultReceiptTarget is a receipt that names a different event than the one
	// it was checked against.
	FaultReceiptTarget FaultKind = "receipt-target"
	// FaultStreamTruncated is a stream that ends before its attached material
	// is complete.
	FaultStreamTruncated FaultKind = "stream-truncated"
	// FaultStreamMalformed is attached material that is not readable CESR.
	FaultStreamMalformed FaultKind = "stream-malformed"
	// FaultSignatureInvalid is a controller signature that names a key outside
	// the key list, or whose key cannot be read. A signature that simply does
	// not verify is dropped rather than reported: it attests nothing, the rest
	// are judged without it, and if they fall short the refusal is
	// FaultThresholdNotMet.
	FaultSignatureInvalid FaultKind = "signature-invalid"
	// FaultThresholdNotMet is a signature set that does not meet the parsedThreshold
	// the identity committed to.
	FaultThresholdNotMet FaultKind = "parsedThreshold-not-met"
	// FaultPlaceTaken is an event at a place a verified log already holds a
	// different event at, which is not a recovery rotation that may replace
	// it. Two such events, each correctly signed, are duplicity, except where
	// the second is a delegated rotation: that is refused because whether it
	// may replace the first turns on the delegator's log, not because it is
	// duplicitous.
	FaultPlaceTaken FaultKind = "place-taken"
)

type FileKeyStore

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

FileKeyStore keeps keys on disk, encrypted under a master key.

func NewFileKeyStore

func NewFileKeyStore(dir string, masterKey []byte) (*FileKeyStore, error)

NewFileKeyStore opens or creates a store in dir, protected by masterKey.

masterKey must be 32 bytes and is the caller's responsibility: everything in the directory is readable to whoever holds it. Where it comes from is a deliberate omission — a passphrase, a system keyring, or hardware are all reasonable and none of them belong in this package. DeriveMasterKey is provided for the passphrase case.

func (*FileKeyStore) Generate

func (f *FileKeyStore) Generate(name string, transferable bool) (Signer, error)

Generate creates a new key under a name and writes it to disk.

func (*FileKeyStore) Names

func (f *FileKeyStore) Names() ([]string, error)

Names lists the keys held, sorted. Reveals no key material.

func (*FileKeyStore) PutSecret added in v0.1.3

func (f *FileKeyStore) PutSecret(name string, secret []byte) error

PutSecret stores bytes under a name, encrypted like everything else here.

func (*FileKeyStore) Secret added in v0.1.3

func (f *FileKeyStore) Secret(name string) ([]byte, error)

Secret returns bytes stored earlier.

func (*FileKeyStore) Signer

func (f *FileKeyStore) Signer(name string) (Signer, error)

Signer returns the signer for a key previously generated.

type InceptionInput

type InceptionInput struct {
	Keys        []string `json:"keys"`
	NextDigests []string `json:"next_digests"`
	Witnesses   []string `json:"witnesses"`
	// Toad is a POINTER so that "absent" and "zero" stay different instructions.
	//
	// Absent means take the reference's default, which is derived from the
	// witness count; zero means no witness need agree. An int cannot tell those
	// apart, and the version that could not rejected any witnessed inception
	// that did not state one — where the reference would have filled it in.
	Toad *int `json:"toad"`
	// Thresholds are either a string ("2") or a list of weight strings
	// (["1/2","1/2","1/2"]). Kept as raw JSON so both forms the reference
	// produces can round-trip without the harness inventing a type.
	Isith json.RawMessage `json:"isith"`
	Nsith json.RawMessage `json:"nsith"`
	// Seals stay as raw bytes. A seal's field order is part of the event, and
	// Go marshals a map alphabetically, so any trip through one silently
	// reorders it and changes the identifier.
	Data []json.RawMessage `json:"data"`
	// Version is which CESR version to build. The zero value means
	// DefaultVersion. It is carried on the input rather than set globally so
	// that an agent can answer a 1.0 peer and a 2.0 peer concurrently.
	Version Version `json:"version"`
	// Derivation forces how the identifier is made, overriding the default.
	//
	// Empty means the reference's rule: basic when there is exactly one key,
	// self-addressing otherwise. "self-addressing" forces a digest-derived
	// identifier even for a single key, which the reference supports and which
	// a caller must be able to ask for — an application that has issued
	// self-addressing single-key identities cannot be served by an
	// implementation that infers derivation from key count and will not be
	// told otherwise. "basic" is accepted for symmetry and is only valid with
	// one key.
	Derivation string `json:"derivation"`
}

InceptionInput is what founding an identity is given.

Field names match the vector file, which matches the reference implementation's parameters. Named the same on purpose: a translation layer between what the vectors say and what this package calls things is somewhere for a mismatch to hide.

type IndexedSignature added in v0.2.0

type IndexedSignature struct {
	// Code is the CESR code: "A", "B", "2A" or "2B".
	Code string
	// At is where it counts. CurrentOnly is set for "B" and "2B".
	At SignaturePlace
	// Raw is the 64-byte Ed25519 signature.
	Raw []byte
}

IndexedSignature is an indexed signature as read.

func ParseIndexedSignature added in v0.2.0

func ParseIndexedSignature(qb64 string) (IndexedSignature, error)

ParseIndexedSignature reads one indexed Ed25519 signature in any of the four forms keripy 1.3.6 defines, refusing an unknown code, a value of the wrong length for its code, and a current-only signature that carries a prior-next place.

type InteractionInput

type InteractionInput struct {
	Prefix    string `json:"prefix"`
	PriorSAID string `json:"prior_said"`
	SN        int    `json:"sn"`
	// Seals stay as raw bytes. Their field order is part of the event, and any
	// trip through a Go map would sort it alphabetically and change the
	// identifier.
	Data []json.RawMessage `json:"data"`
	// Version is which CESR version to build. The zero value means
	// DefaultVersion. It is carried on the input rather than set globally so
	// that an agent can answer a 1.0 peer and a 2.0 peer concurrently.
	Version Version `json:"version"`
}

InteractionInput is what anchoring something into a key history is given.

type IssuanceInput

type IssuanceInput struct {
	CredentialSAID string `json:"credential_said"`
	Registry       string `json:"registry"`
	DT             string `json:"dt"`
}

IssuanceInput is what placing a credential into a registry is given.

type KeyState added in v0.4.0

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

KeyState is an identity's key state after one event of its log: the keys in force, the commitment the next rotation must open, and the witnesses.

It has no exported constructor. A KeyState is something this package established by verifying events, never something a caller asserts, so the only ways to get one are ValidateSignedKEL (State, StateAt), VerifyEvent and Admit.

func (*KeyState) Delegated added in v0.4.0

func (s *KeyState) Delegated() bool

Delegated is whether the identity was founded by a delegated inception.

func (*KeyState) Digest added in v0.4.0

func (s *KeyState) Digest() string

Digest is the SAID of the event this state follows: what the next event's prior digest must be.

func (*KeyState) Identifier added in v0.4.0

func (s *KeyState) Identifier() string

Identifier is the identity this state belongs to.

func (*KeyState) Ilk added in v0.4.0

func (s *KeyState) Ilk() string

Ilk is the type of the event this state follows.

func (*KeyState) Keys added in v0.4.0

func (s *KeyState) Keys() []string

Keys are the signing keys in force.

func (*KeyState) LastEstablishment added in v0.4.0

func (s *KeyState) LastEstablishment() uint64

LastEstablishment is the sequence number of the last establishment event. A recovery rotation may replace only the interactions after it.

func (*KeyState) NextDigests added in v0.4.0

func (s *KeyState) NextDigests() []string

NextDigests is the next-key commitment the next rotation must open.

func (*KeyState) SN added in v0.4.0

func (s *KeyState) SN() uint64

SN is the sequence number of the event this state follows.

func (*KeyState) TOAD added in v0.4.0

func (s *KeyState) TOAD() uint64

TOAD is the witness threshold in force.

func (*KeyState) Witnesses added in v0.4.0

func (s *KeyState) Witnesses() []string

Witnesses are the witnesses designated for the next event.

type KeyStore

type KeyStore interface {
	// Generate creates a new key under a name, and returns a Signer for it.
	//
	// It must fail rather than overwrite if the name is already in use.
	// Overwriting a name silently destroys the key an identity has already
	// committed to, which is unrecoverable.
	Generate(name string, transferable bool) (Signer, error)
	// Signer returns the signer for a name that was generated earlier.
	Signer(name string) (Signer, error)
}

KeyStore creates and retrieves keys by name.

It is an interface for the same reason Signer is: a store backed by a secure enclave never hands out private material, and cannot satisfy an interface shaped as "return the key". A store's job is to produce a Signer, not a key.

type Keychain

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

Keychain manages the pre-rotation lifecycle for one identity.

It holds the keys currently in force and the keys already committed to as next. Rotating advances the second into the first and generates a new second, so an identity is never left without a committed successor.

func LoadKeychain

func LoadKeychain(store KeyStore, label string, count, generation int) (*Keychain, error)

LoadKeychain recovers a keychain whose keys are already in a store.

generation is how many rotations the identity has been through, which the caller reads from the key log rather than from the store: the log is the record of what the identity has actually done.

func NewKeychain

func NewKeychain(store KeyStore, label string, count int) (*Keychain, error)

NewKeychain creates the keys for a new identity: the ones it starts with, and the ones it commits to rotate to.

count is how many keys are in force at a time. Both generations are created here, which is what makes the identity rotatable from the moment it exists.

func (*Keychain) CurrentKeys

func (k *Keychain) CurrentKeys() ([]string, error)

CurrentKeys returns the public keys in force.

func (*Keychain) Generation

func (k *Keychain) Generation() int

Generation is how many establishment events this identity has had beyond its inception. Persist it alongside the store so a restart can reload correctly.

func (*Keychain) NextDigests

func (k *Keychain) NextDigests() ([]string, error)

NextDigests returns the pre-rotation commitments for the keys that will come next — digests, never the keys themselves.

The keys stay unrevealed until the rotation that uses them. Returning them here instead of their digests would defeat the point of holding them.

func (*Keychain) Rotate

func (k *Keychain) Rotate() (keys []string, nextDigests []string, err error)

Rotate advances the keychain: the committed next keys come into force, and a fresh set is generated and committed in their place.

It returns the keys now in force and the digests of the new commitments, which are what a rotation event must carry.

The new keys are generated BEFORE the advance is recorded, so a failure to generate leaves the keychain exactly as it was rather than in force with nothing committed — a state in which the identity could never rotate again.

func (*Keychain) Signers

func (k *Keychain) Signers() []Signer

Signers returns the signers in force, for signing an event.

type MapResolver

type MapResolver map[string][]byte

MapResolver resolves credentials from an in-memory map, for tests and for verifying a bundle that arrived all at once.

func (MapResolver) Credential

func (m MapResolver) Credential(said string) ([]byte, error)

type MemoryKeyStore

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

MemoryKeyStore keeps keys in this process and nowhere else.

For tests and for short-lived processes. It is NOT suitable for an identity that must survive a restart: when the process ends, every next key it holds is gone, and every identity whose commitment depended on one can never rotate again. A real deployment supplies a store that persists, and preferably one backed by hardware.

func NewMemoryKeyStore

func NewMemoryKeyStore() *MemoryKeyStore

func (*MemoryKeyStore) Generate

func (m *MemoryKeyStore) Generate(name string, transferable bool) (Signer, error)

func (*MemoryKeyStore) Names

func (m *MemoryKeyStore) Names() []string

Names lists the keys held, sorted. For tests and for operational inspection; it reveals no key material.

func (*MemoryKeyStore) PutSecret added in v0.1.3

func (m *MemoryKeyStore) PutSecret(name string, secret []byte) error

PutSecret stores bytes in memory. Lost when the process ends, with the same consequence as a key stored here: whatever committed to it cannot be recovered.

func (*MemoryKeyStore) Secret added in v0.1.3

func (m *MemoryKeyStore) Secret(name string) ([]byte, error)

Secret returns bytes stored earlier.

func (*MemoryKeyStore) Signer

func (m *MemoryKeyStore) Signer(name string) (Signer, error)

type PlacedSigner added in v0.2.0

type PlacedSigner struct {
	Signer Signer
	At     SignaturePlace
}

PlacedSigner is a signer and the places its signature counts at.

type Protocol

type Protocol string

Protocol is which specification an event belongs to. KERI events are key events; ACDC events are credentials. They are versioned independently, so the protocol travels with the version everywhere.

const (
	ProtocolKERI Protocol = "KERI"
	ProtocolACDC Protocol = "ACDC"
)

type ReceiptCouple

type ReceiptCouple struct {
	Witness   string `json:"witness"`
	CigarQB64 string `json:"cigar_qb64"`
}

ReceiptCouple is one non-transferable witness receipt: the witness identifier (which IS the verifying key) and the cigar over the event.

type ReceiptInput

type ReceiptInput struct {
	Prefix    string `json:"prefix"`
	SN        int    `json:"sn"`
	EventSAID string `json:"event_said"`

	// Version is which CESR version to build. The zero value means
	// DefaultVersion. Carried here rather than assumed, because the attachment
	// layer is where the two versions differ most.
	Version Version `json:"version"`
}

ReceiptInput is what building a receipt event is given.

A receipt body has exactly five fields — version, type, the digest of the receipted event, the identity's prefix, and the sequence number. It does not carry a witness identifier or a signature; those ride in the attachment.

type RegistryInput

type RegistryInput struct {
	Issuer  string   `json:"issuer"`
	Toad    int      `json:"toad"`
	Backers []string `json:"backers"`
	// Nonce is what makes two registries with the same issuer different
	// identities. Supplied by the caller rather than generated here, so that
	// founding a registry is reproducible and can be held to a fixed answer.
	Nonce string `json:"nonce"`
}

RegistryInput is what founding a credential registry is given.

type Reply added in v0.1.5

type Reply struct {
	SAID  string
	Route string
	DT    string
	Data  json.RawMessage
	Raw   []byte
}

Reply is what a recipient reads out of a reply message.

func VerifyReply added in v0.1.5

func VerifyReply(raw []byte) (*Reply, error)

VerifyReply checks that a reply is the message its own identifier commits to, and returns what it says.

The digest check is the whole of it: a reply is not part of a key log, so nothing else vouches for it, and an altered one would otherwise be indistinguishable from the original.

type ReplyInput added in v0.1.5

type ReplyInput struct {
	// Route says how to read the payload.
	Route string
	// DT is when the statement was made, and is what lets a recipient tell a
	// newer statement from an older one. A reply with no timestamp could never
	// be superseded, so it is required rather than defaulted.
	DT string
	// Data is the payload, already in the order the route expects.
	Data json.RawMessage
}

ReplyInput is a statement an identity is making about itself.

type RevocationInput

type RevocationInput struct {
	CredentialSAID string `json:"credential_said"`
	Registry       string `json:"registry"`
	// PriorISSSAID chains the revocation to the issuance it withdraws. Without
	// it a revocation is unattached to anything, and a holder could present the
	// issuance while claiming the revocation belongs to some other credential.
	PriorISSSAID string `json:"prior_iss_said"`
	DT           string `json:"dt"`
}

RevocationInput is what withdrawing a credential is given.

type RotationInput

type RotationInput struct {
	Prefix      string          `json:"prefix"`
	Keys        []string        `json:"keys"`
	PriorSAID   string          `json:"prior_said"`
	SN          int             `json:"sn"`
	NextDigests []string        `json:"next_digests"`
	Isith       json.RawMessage `json:"isith"`
	Nsith       json.RawMessage `json:"nsith"`
	// A rotation states witnesses as a DELTA against the set the identity
	// already has, so it needs that prior set to check the delta is applicable
	// as well as the cuts and adds themselves.
	PriorWitnesses []string `json:"prior_witnesses"`
	Cuts           []string `json:"cuts"`
	Adds           []string `json:"adds"`
	// A pointer because absent and zero are different answers: absent means
	// "derive the threshold", zero means "no witness need agree", and an int
	// could not tell them apart.
	Toad *int `json:"toad"`
	// Seals stay as raw bytes, for the reason given above.
	Data []json.RawMessage `json:"data"`
	// Version is which CESR version to build. The zero value means
	// DefaultVersion. It is carried on the input rather than set globally so
	// that an agent can answer a 1.0 peer and a 2.0 peer concurrently.
	Version Version `json:"version"`
}

RotationInput is what changing an identity's keys is given.

type SchemaInput

type SchemaInput struct {
	// Carried as raw bytes. A schema's field order is part of its identifier,
	// and this package neither chooses that order nor is entitled to change it.
	Schema json.RawMessage `json:"schema"`
}

SchemaInput is a JSON schema to give a self-addressing identifier to.

type Seal

type Seal struct {
	Identifier string
	SN         uint64
	SAID       string
}

Seal is an anchor carried in an event's `a` field.

type SecretStore added in v0.1.3

type SecretStore interface {
	// PutSecret stores bytes under a name, refusing to replace an existing one.
	//
	// The refusal is deliberate and matches key storage: overwriting a secret
	// an identity has already committed to is unrecoverable, and a store that
	// allowed it would make that mistake silent.
	PutSecret(name string, secret []byte) error
	// Secret returns bytes stored earlier.
	Secret(name string) ([]byte, error)
}

SecretStore keeps arbitrary secret material.

Implemented by the stores in this package. A caller holding secrets this package has no opinion about — post-quantum seeds, agreement keys, anything else — persists them here rather than inventing a second place.

type SelfTestResult added in v0.1.2

type SelfTestResult struct {
	Total         int `json:"total"`
	Passed        int `json:"passed"`
	Failed        int `json:"failed"`
	Unimplemented int `json:"unimplemented"`
	// AssertedElsewhere counts cases that produce no bytes to compare — code
	// tables, state transitions, refusals — and are checked by dedicated
	// assertions in the Go test suite rather than here. They are reported
	// rather than hidden, because a run that quietly skipped a fifth of the
	// suite while reporting "all passed" would be worse than one that failed.
	AssertedElsewhere int          `json:"asserted_elsewhere"`
	Cases             []CaseResult `json:"cases"`
}

SelfTestResult is the outcome of a whole run.

func SelfTest added in v0.1.2

func SelfTest() *SelfTestResult

SelfTest runs the embedded conformance vectors and reports the result.

Safe to call anywhere, including from a mobile binding. It reads no files and writes none.

func (*SelfTestResult) OK added in v0.1.2

func (r *SelfTestResult) OK() bool

OK reports whether every case that produces bytes produced the right ones.

Unimplemented cases do not fail a run: they are work not yet done, which is a different thing from a wrong answer, and conflating them would hide the second among the first. Nor do cases checked by assertion elsewhere — but both are counted and reported, so a caller can see how much of the suite this run actually covered.

type SignaturePlace added in v0.2.0

type SignaturePlace struct {
	Index       int
	Ondex       int
	CurrentOnly bool
}

SignaturePlace is where an indexed signature counts.

Index is the place in the event's key list of the key that signed. Ondex is the place in the PRIOR establishment event's next-key commitments that the same key opens, which is how a rotation reveals a committed key. They differ when a key sits at a different place in k than the commitment it opens: a partial rotation revealing the second commitment alone is Index 0, Ondex 1.

CurrentOnly says the signature opens no prior commitment at all; Ondex is then ignored. Such a signature counts toward the signing threshold and nothing else. An interaction's signatures, and any signature by a key a rotation adds without having committed to it, are of that kind.

func SamePlace added in v0.2.0

func SamePlace(index int) SignaturePlace

SamePlace is a signature whose key sits at the same place in both lists: the usual case, and what SignEvent writes.

type SignedEvent

type SignedEvent struct {
	// Event is the canonical event bytes, exactly as signed.
	Event []byte
	// Attachment is the CESR attachment group.
	Attachment []byte
	// Message is Event followed by Attachment: what actually travels.
	Message []byte
}

SignedEvent is an event with signatures attached, ready to send.

func SignEvent

func SignEvent(event []byte, signers ...Signer) (*SignedEvent, error)

SignEvent signs an event with each of the given signers and frames the result.

The signers must be in the same order as the keys the event declares, because each signature is indexed by position, and each opens the prior commitment at the same position. Use SignEventAt when a key's place in the prior commitment differs from its place in the event, or when a signature opens none.

Every signature is verified against the event's own declared key at that index before the message is returned. That check costs one verification per signature and catches the entire class of bug where a signer is paired with the wrong key — locally, at the point of production, instead of remotely as an unexplained rejection.

func SignEventAt added in v0.2.0

func SignEventAt(event []byte, signers ...PlacedSigner) (*SignedEvent, error)

SignEventAt signs an event with each signer at its stated places and frames the result.

Where the event declares keys, each signer must hold the key at its Index; the signature is verified under it before anything is returned. Whether Ondex names the right prior commitment cannot be checked here, because the prior event is not among the arguments; ValidateSignedKEL checks it.

type SignedKELResult

type SignedKELResult struct {
	Identifier string
	// Keys and Threshold are the state in force after the last event.
	Keys      []string
	Threshold *parsedThreshold
	// Events is how many events were verified.
	Events int
	// Witnessing holds, for each event in order, what its witness-indexed
	// signatures (the -B group) establish against the witnesses designated
	// for it. It is reported rather than enforced: a log whose events are
	// not yet witnessed enough is still a correctly signed log, and whether
	// to act on it before its witnesses have signed is the caller's
	// decision. FullyWitnessed is the usual question to ask of it.
	Witnessing []EventWitnessing
	// contains filtered or unexported fields
}

SignedKELResult is what a verified log establishes.

func ValidateSignedKEL

func ValidateSignedKEL(messages [][]byte) (*SignedKELResult, error)

ValidateSignedKEL checks a key log whose entries carry their attachments.

Each message is an event followed by its CESR attachments, as it travels. The log is validated structurally first — order, chaining, pre-rotation — and then every event's controller signatures are verified against the key state in force at that point in the log, rather than against whatever the event happens to carry.

The difference matters most for interaction events, which carry no keys and were previously not signature-checked at all.

Witnessing is reported in the result's Witnessing and not enforced, so a nil error means the log is correctly controller-signed, not that it is fully witnessed; ask FullyWitnessed for that.

func (*SignedKELResult) Admit added in v0.4.0

func (r *SignedKELResult) Admit(message []byte) (*Admission, error)

Admit judges an event that arrives for the identity whose log r is: whether it extends the log, repeats an event the log already holds, or is a recovery rotation, and refuses anything else.

A recovery rotation is a rotation at a place the log already holds, whose prior digest is the event before that place. It replaces the events from its place to the end of the log, so it is accepted only where every one of those is an interaction: one that would replace an establishment event is refused, and the first establishment event seen at a place stands. That is keripy 1.3.6's rule for a non-delegated identity. A delegated rotation at a taken place is refused here, where keripy may accept one under its delegation rules: whether it may supersede turns on its delegator's log, which this does not have.

A repeat is admitted when at least one controller or witness signature given with it verifies against the key state and witnesses at its place, as keripy 1.3.6 logs a duplicate: a repeat need not meet the signing threshold again, since the log already holds the event, and that is how late witness signatures arrive. The witnesses that signed it are counted in Log. One with no signature that verifies is refused, and so is one carrying a controller signature that names a place outside the key list, as keripy refuses it.

An event at a place past the end of the log is refused as out of order; one whose predecessor has not arrived cannot be judged.

func (*SignedKELResult) FullyWitnessed added in v0.3.0

func (r *SignedKELResult) FullyWitnessed() bool

FullyWitnessed reports whether every event in the log carries signatures from enough of its designated witnesses to meet its witness threshold. An identity with no witnesses is fully witnessed trivially.

func (*SignedKELResult) State added in v0.4.0

func (r *SignedKELResult) State() *KeyState

State is the key state after the last event of the log.

func (*SignedKELResult) StateAt added in v0.4.0

func (r *SignedKELResult) StateAt(sn uint64) *KeyState

StateAt is the key state after the event at sequence number sn, or nil when the log holds no event there.

type Signer

type Signer interface {
	// PublicKey returns the verifying key in CESR qb64 form, carrying the code
	// that says whether the identity it belongs to may rotate.
	PublicKey() (string, error)
	// Sign returns a raw Ed25519 signature over exactly these bytes.
	//
	// Exactly these bytes: a KERI signature covers the canonical serialisation
	// of an event, so an implementation that hashes, wraps, or re-encodes what
	// it is given produces a signature no other implementation will accept.
	Sign(data []byte) ([]byte, error)
}

Signer produces signatures over key events.

Implementations are not required to be able to reveal their private key, and most interesting ones cannot.

type SoftwareSigner

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

SoftwareSigner holds an Ed25519 private key in this process's memory.

Appropriate for tests, for development, and for hosts with no secure hardware. It is NOT appropriate for a production identity on a machine where the key could be read out of memory or off disk — for that, supply a Signer backed by hardware. This type deliberately has no method that returns the private key, so passing one around does not spread the material any further than the process that created it.

func GenerateSigner

func GenerateSigner(transferable bool) (*SoftwareSigner, error)

GenerateSigner makes a new key from the system's randomness.

func GenerateSignerFrom

func GenerateSignerFrom(r io.Reader, transferable bool) (*SoftwareSigner, error)

GenerateSignerFrom makes a new key from a supplied source of randomness.

Separate from GenerateSigner so that a test can be deterministic without the production path ever taking a source that might not be random. Do not pass anything but crypto/rand.Reader outside a test: a predictable seed is a predictable identity.

func NewSoftwareSigner

func NewSoftwareSigner(seed []byte, transferable bool) (*SoftwareSigner, error)

NewSoftwareSigner builds a signer from a 32-byte Ed25519 seed.

The seed is expanded immediately and not retained, so the caller's copy is the only one it needs to look after.

func (*SoftwareSigner) PublicKey

func (s *SoftwareSigner) PublicKey() (string, error)

PublicKey returns the verifying key in CESR qb64 form.

func (*SoftwareSigner) Sign

func (s *SoftwareSigner) Sign(data []byte) ([]byte, error)

Sign returns a raw Ed25519 signature over exactly the bytes given.

type SourceSeal

type SourceSeal struct {
	// SN is the sequence number of the anchoring event in the issuer's log.
	SN uint64
	// SAID is the digest of that anchoring event.
	SAID string
}

SourceSeal names the event in a key log that anchors a transaction event.

func ParseSourceSeals

func ParseSourceSeals(attached []byte) ([]SourceSeal, error)

ParseSourceSeals reads a source seal group back out of an attachment.

type StreamInput

type StreamInput struct {
	EventRawB64 string   `json:"event_raw_b64"`
	SigersQB64  []string `json:"sigers_qb64"`
	CigarsQB64  []string `json:"cigars_qb64"`
	// Witnesses names the signers of cigars_qb64, in the same order. Required
	// when cigars are present: a non-transferable couple is (identifier, cigar),
	// and the identifier is not recoverable from the cigar alone.
	Witnesses []string        `json:"witnesses"`
	Couples   []ReceiptCouple `json:"couples"`
}

StreamInput is what assembling a CESR stream is given.

The event arrives already built; the attachments are the signatures and receipts that travel with it. This does not re-derive signatures — it frames material the caller already holds, which is exactly what a sender does when packaging an event for the wire.

type TELEvent

type TELEvent struct {
	Ilk string
	// SAID is the event's own identifier.
	SAID string
	// Subject is what the event is about: for a registry inception the registry
	// itself, for an issuance or a revocation the credential.
	Subject  string
	SN       int
	Registry string
	Prior    string
	DateTime string
	Raw      []byte
}

TELEvent is a transaction event read back from its bytes.

func VerifyTELEvent

func VerifyTELEvent(raw []byte) (*TELEvent, error)

VerifyTELEvent checks a registry, issuance or revocation event against itself.

A registry inception is digested with BOTH its identifier and its prefix blank, because they are the same digest; the others have one identifier. That difference is not visible in the serialised event and is the thing most easily got wrong here, so the labels are chosen from the event type rather than assumed.

type ValidationError

type ValidationError struct {
	Faults []Fault
}

ValidationError is a refusal, carrying every fault found.

Every fault rather than the first, because tampering usually breaks several rules at once and reporting only one makes the reader guess at the rest.

func (*ValidationError) Error

func (e *ValidationError) Error() string

func (*ValidationError) Has

func (e *ValidationError) Has(kind FaultKind) bool

Has reports whether a fault of this kind was found.

type VectorFile

type VectorFile struct {
	Version int    `json:"vector_version"`
	Oracle  string `json:"oracle"`
	Cases   []Case `json:"cases"`
	What    string `json:"what_this_is"`
	How     string `json:"how_to_use"`
}

VectorFile is the fixed answers every conformant implementation reproduces.

Generated from keripy, which the KERI implementations table lists at 100% spec compliance. Read as data, never as code, so the same file can hold this implementation and any other to the same answers.

func LoadVectors

func LoadVectors(path string) (*VectorFile, error)

LoadVectors reads a vector file.

type Verified added in v0.4.0

type Verified struct {
	// State is the key state after the event.
	State *KeyState
	// Witnessing is what the event's witness-indexed signatures establish.
	// It is reported and not enforced, as in ValidateSignedKEL.
	Witnessing EventWitnessing
	// Signatures are the attached controller signatures that verified, one
	// for each key that signed, as attached: where a rotation's key opens a
	// commitment, the spelling that opens it. One that did not verify is not
	// among them, and nor is a second spelling of one key's signature.
	Signatures []string
}

Verified is one event verified against the key state it follows.

func VerifyEvent added in v0.4.0

func VerifyEvent(state *KeyState, message []byte) (*Verified, error)

VerifyEvent checks one event, with its attachments as it travels, against the key state it is to follow, and returns the state after it. A nil state means the event is the identity's founding.

It applies every rule ValidateSignedKEL applies to an event in a log: the event is well formed, it is the next sequence number of the same identity and digests the event the state follows, a rotation's keys open enough of the last establishment event's commitment and change the witnesses correctly, and its controller signatures meet the threshold in force. As there, a signature that does not verify is dropped and the rest are judged.

type VerifiedChain

type VerifiedChain struct {
	// Credential is the leaf that was asked about.
	Credential *Credential
	// Edges are the links out of the leaf.
	Edges []ChainEdge
	// Depends are the verified chains for each edge, in the same order.
	Depends []*VerifiedChain
	// Depth is how far this chain reaches, the leaf alone being one.
	Depth int
}

VerifiedChain is a credential and everything it rests on.

func VerifyCredentialChain

func VerifyCredentialChain(raw []byte, resolver CredentialResolver) (*VerifiedChain, error)

VerifyCredentialChain verifies a credential and every credential it depends on, following the edge blocks.

It fails if any link cannot be resolved or does not verify. That is the whole point: a leaf whose chain could not be checked has not been verified, and returning it as verified with the failure recorded somewhere would invite exactly the mistake this exists to prevent.

func (*VerifiedChain) Size

func (c *VerifiedChain) Size() int

Size is how many credentials the chain contains, including the leaf.

type Version

type Version struct {
	Major int
	Minor int
}

Version is a CESR protocol version.

func (Version) String

func (v Version) String() string

func (Version) Supported

func (v Version) Supported() bool

Supported reports whether this package can build and read a version.

type Watcher

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

Watcher remembers key events and reports duplicity.

It is what an agent uses to watch itself, and to cross-check a peer. The same memory answers both: an identity contradicting itself looks identical whether the identity is yours or somebody else's.

func NewSignatureCheckingWatcher

func NewSignatureCheckingWatcher() *Watcher

NewSignatureCheckingWatcher returns a watcher that verifies every event it is offered before recording it.

An establishment event is checked against the keys it declares, which are not self-asserted because a rotation must present keys the previous event committed to. An event carrying no keys — an interaction — is checked against the key state this watcher has already seen that identity establish, and is REFUSED if none is known.

That refusal matters. ValidateStream verifies signatures only on establishment events, because an interaction carries no keys for it to check against; handed one it reports no fault, which reads exactly like a pass. A watcher relying on that would accept any interaction anyone cared to invent, and the first version of this file did, which is how the gap was found.

func NewWatcher

func NewWatcher(verifySigned func(message []byte) error) *Watcher

NewWatcher returns a watcher that accepts only events whose signatures it can check.

verifySigned is given the event WITH its attachments and must return an error if it does not verify. Passing nil means structural validation only, which is weaker and appropriate only where the transport already authenticated the sender — state it deliberately rather than reaching for it by default.

func (*Watcher) Height

func (w *Watcher) Height(identifier string) (uint64, bool)

Height is the highest sequence number recorded for an identity, and whether anything is recorded at all.

func (*Watcher) Known

func (w *Watcher) Known() []string

Known reports the identifiers this watcher has recorded, sorted.

func (*Watcher) Observe

func (w *Watcher) Observe(message []byte) (*Duplicity, error)

Observe records an event and reports duplicity if it contradicts one already seen.

Returning the same event twice is not duplicity and not an error — an agent receives the same event from several sources routinely, and treating a repeat as a conflict would make the alarm useless.

func (*Watcher) ObserveLog

func (w *Watcher) ObserveLog(messages [][]byte) (*Duplicity, error)

ObserveLog records a whole key log, reporting the first duplicity found.

The events already recorded are kept when one is found, because the point of noticing is to have the evidence, not to discard the history that produced it.

Directories

Path Synopsis
Command interop emits everything this package can build, for keripy to judge.
Command interop emits everything this package can build, for keripy to judge.
judge command
Command judge validates key logs keripy built, and reports whether keri-go reaches the verdict keripy reached on each.
Command judge validates key logs keripy built, and reports whether keri-go reaches the verdict keripy reached on each.

Jump to

Keyboard shortcuts

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