evidencebook

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2026 License: Apache-2.0 Imports: 37 Imported by: 4

README

evidencebook

evidencebook is a Go implementation of the evidence layer: a local evidence store that records evidence and the typed links between records, commits payload digests while payload bytes are resolved separately, keeps three distinct classes of index, and answers requests for evidence with portable bundles that anyone can verify.

A book embeds a commitment substrate and never exposes it. The Checkpointed Local Log (CLL Go) is the reference substrate; a SCITT receipt-holding binding shows the book does not depend on it. Every record is sealed as an Agent Action Capsule, so a bundle from a book on the CLL substrate verifies, interval and all, with the neutral Evidence Bundle verifier alone.

Terms Packs (packs): EU AI Act Obligations and Outcomes (draft) are published at actionstate.ai/packs, and Everyday Rules ships with the Muse integration.

Install

Requires Go 1.27 or newer.

go get github.com/action-state-group/evidencebook

Use

store, _ := evidencebook.OpenFileStore("book/records")
substrate, _ := evidencebook.OpenCLL("book/cll.jsonl", "orders-log", checkpointKey)
payloads, _ := evidencebook.OpenPayloadDir("book/payloads")
signer, _ := evidencebook.NewEd25519Signer(recordKey)

book, err := evidencebook.Open(ctx, evidencebook.Config{
	BookID: "orders", Operator: "example-operator",
	Store: store, Substrate: substrate, Payloads: payloads, Signer: signer,
})

observed, err := book.Append(ctx, evidencebook.Entry{
	RecordType:    "observation",
	EpistemicType: evidencebook.ObservedEvent,
	SubjectRef:    "order-17",
	Payloads:      [][]byte{[]byte(`{"status":"approved"}`)},
})

bundle, err := book.Bundle(ctx, evidencebook.BundleRequest{Root: observed.RecordID})

Production code must handle every error. The verbs are Append, Query, Bundle, Request, Respond, Reconcile and Close. See docs/design.md for how each public type maps to the specification, the cross-implementation checks, and the known limits.

Answering requests

Respond implements the responder side of the Minimum Evidence Interoperability Profile, evidence-interop/0 (agent-action-capsule spec/interop-profile-v0.md), over the request map of draft-mih-agent-evidence-request-00. It takes the request octets with their media type (application/json or application/cbor) and answers in the same encoding with a signed envelope carrying the canonical Artifact, or a signed refusal with exactly one registered reason. The Artifact depends only on the subject, the resolved anchor and the derivation: never on the requester, the nonce, the route or the encoding. Manifest returns the profile's history-free manifest.

A protected subject is answered only to a requester the transport has authenticated: set RespondOptions.AuthenticatedRequester from that authentication. With it empty, only checkpoints and the history_card/1 derivation are answered and every other subject gets a signed not_authorized refusal. A declared requester id is never trusted and is not recorded. See the CHANGELOG for the upgrade note.

Testing evidencebook with your own verifier

To check evidencebook's answers with a verifier you wrote yourself, from the profile text and with keys you choose to trust, follow docs/THIRD-PARTY-VERIFIER.md. It starts from a fresh machine. It names the pinned profile, request draft and conformance vectors, and runs a test responder (go run ./test/interop/answer) that answers your own request octets. For each vector class it gives the request to send and the result the vectors specify, and it says what to report back. Its personal-evidence part reproduces the run the Personal-Agent History vectors were cut from (go run ./test/interop/personal-history) and gives the result specified for each of their cases.

Checking foreign evidence

Adapters check objects produced by other protocols under each protocol's own verification method and report every property with the method used. The first is x402 (the payer's signed transfer authorization, the settlement response, and an optional payee receipt):

go run ./cmd/evidencebook adapt x402 -policy trust-policy.json exchange.http

See docs/ADAPTERS.md for the interface, what each adapter checks and does not check, and how a failed check maps to a requirement.

Development

gofmt -l .
go vet ./...
go test ./...
go test -race ./...

CI also checks bundles both ways: a bundle produced here is verified by the Python Agent Action Capsule bundle verifier (test/interop/python-aac/verify_bundle.py) and the Python CLL reference (test/interop/python-cll/verify_bundle.py), and a bundle produced in Python (test/interop/python-cll/build_bundle.py) is verified here (test/interop/verify); a tampered copy must fail in each direction. The profile's reference verifier checks this responder's replies against the profile's conformance vectors (test/interop/responder, test/interop/python-profile/verify_responder.py), over the native stream, the A2A carriage (Book.A2A) and the MCP carriage (Book.MCP), and checks that all three carry a byte-identical canonical Artifact. CI also reproduces the responder run of the Personal-Agent History vectors byte for byte (test/interop/personal-history), rebuilds the corpus from it, and runs the corpus's own test.

Other implementations and parity

  • Rust: the evidencebook crate in this repository (rust/evidencebook, moved here from checkpointed-local-log with its history) implements the same evidence-layer semantics over the Rust Checkpointed Local Log: records, epistemic types, links, disclosure, retention, requests and reconcile/close.
  • Parity vectors shared across implementations, all checked in CI:
    • schemas/vendor/epistemic-types.json: the epistemic type value set (TestEpistemicTypeThreeWayParity);
    • testdata/refusal-interop/: a refusal signed in Python, verified here; a refusal signed here is verified in Python;
    • testdata/evidence-request/: the request draft's spec-derived request, resolution and refusal vectors, vendored with their upstream SHA-256s (TestRequestVectors, TestResolutionVectors, TestRefusalVectors);
    • testdata/reconcile-parity/: exchange halves and the Python correlator's outcomes, which ReconcileHalves must match.
  • Bundles are Evidence Bundle v2: anything that verifies one (the Go and Python Agent Action Capsule bundle verifiers) checks a bundle from a book.

docs/design.md lists every cross-implementation check.

License

Apache-2.0.

Documentation

Overview

Package evidencebook is a reference implementation of the Evidence Layer: a local evidence store that records evidence and the typed links between records, keeps payload digests committed while payload bytes are resolved separately, maintains three distinct classes of index, and answers requests for evidence with portable, independently verifiable bundles.

A Book embeds a commitment substrate. The Checkpointed Local Log binding (OpenCLL) is the reference; a SCITT receipt-holding binding (NewSCITTReceiptSubstrate) shows that conformance does not depend on it. The substrate never appears in the Book's API: callers append records and ask for bundles, requests, reconciliations and closes, and the book composes every proof itself.

Every record is sealed as an Agent Action Capsule whose agent input digest commits the record header, so a bundle this package produces is checked by the neutral Evidence Bundle verifier with nothing from this package. Over the SCITT stub, which keeps no ordered log, that verifier reports interval coverage as withheld.

Index

Constants

View Source
const (
	ExtensionPayloads  = "evidencebook/payloads"
	ExtensionInclusion = "evidencebook/inclusion"
	ExtensionSubject   = "evidencebook/subject"
)

Bundle extension keys this package writes. Extensions are integrity-covered by the bundle digest and uninterpreted by the neutral bundle verifier.

View Source
const (
	// A2AProtocolVersion is the one A2A-Version this carriage speaks.
	A2AProtocolVersion = "1.0"
	// A2AExtensionURI is the extension the exchange is advertised and
	// activated under (P-37): the request draft's Datatracker URL.
	A2AExtensionURI = "https://datatracker.ietf.org/doc/draft-mih-agent-evidence-request/"
	// A2AProtocolBinding is the Agent Card protocolBinding this carriage
	// serves.
	A2AProtocolBinding = "JSONRPC"
)

The A2A carriage of the exchange (profile §11.4.4), over A2A 1.0 in its JSON-RPC binding.

View Source
const (
	BindingStream = "evidence-request/1"
	BindingHTTP   = "http"
	BindingA2A    = "a2a"
	BindingMCP    = "mcp"
)

Binding tokens a manifest may list (profile §4, §11.4.2).

View Source
const (
	// MCPProtocolVersion is the one MCP revision this carriage speaks.
	MCPProtocolVersion = "2026-07-28"
	// MCPToolManifest returns the manifest (profile §11.4.2) as its
	// structuredContent.
	MCPToolManifest = "evidence_manifest"
	// MCPToolRequest carries one request and returns its reply.
	MCPToolRequest = "evidence_request"
)

The MCP carriage of the exchange (profile §11.4.5), over MCP 2026-07-28.

View Source
const (
	KindCLLCheckpoint       = evidencerequest.KindCLLCheckpoint
	KindCLLInclusionProof   = evidencerequest.KindCLLInclusionProof
	KindCLLConsistencyProof = evidencerequest.KindCLLConsistencyProof
)

Verification-material kinds (profile §6.2.1), the Checkpointed Local Log mechanism's proof formats.

View Source
const (
	ProfileID             = evidencerequest.ProfileID
	RequestDraft          = evidencerequest.RequestDraft
	DerivationHistoryCard = evidencerequest.DerivationHistoryCard
)

The request draft's identifiers, subject forms, refusal reasons and request types are defined in go/evidencerequest (draft-mih-agent-evidence-request-00, profile evidence-interop/0); these names keep evidencebook's API.

View Source
const (
	SubjectFullHistory = evidencerequest.SubjectFullHistory
	SubjectCheckpoints = evidencerequest.SubjectCheckpoints
	SubjectRecord      = evidencerequest.SubjectRecord
	SubjectRange       = evidencerequest.SubjectRange
	SubjectCorrelation = evidencerequest.SubjectCorrelation
	SubjectExchange    = evidencerequest.SubjectExchange
)
View Source
const (
	ReasonNotAuthorized         = evidencerequest.ReasonNotAuthorized
	ReasonNoSuchSubject         = evidencerequest.ReasonNoSuchSubject
	ReasonCoverageUnsatisfiable = evidencerequest.ReasonCoverageUnsatisfiable
	ReasonDerivationUnsupported = evidencerequest.ReasonDerivationUnsupported
	ReasonPolicyDeclined        = evidencerequest.ReasonPolicyDeclined
	ReasonDeadlineUnmet         = evidencerequest.ReasonDeadlineUnmet
	ReasonRequestMalformed      = evidencerequest.ReasonRequestMalformed
	ReasonRetentionExpired      = evidencerequest.ReasonRetentionExpired
)

The registered refusal reasons (ER §13).

View Source
const (
	// RefusalPolicySpecific answers the most specific registered token.
	RefusalPolicySpecific = "specific"
	// RefusalPolicyUniform answers policy_declined wherever a more specific
	// token would disclose what the responder's policy protects: whether a
	// subject exists, whether it is covered yet, and whether this requester
	// may see it (ER §4.2, §12).
	RefusalPolicyUniform = "uniform"
)

Refusal policies a responder may declare (profile §11.4.2 refusal_policy).

View Source
const (
	DefaultMaxRequestBytes = 64 << 10
	DefaultMaxAnswerItems  = 10_000
)

Defaults of the responder's cost policy.

View Source
const (
	RelationshipStranger     = "stranger"
	RelationshipIdentified   = "identified"
	RelationshipCounterparty = "counterparty"
)

Relationship of a requester to this book, checkable from local records. A stranger is a caller with no authenticated identity.

View Source
const (
	MediaTypeJSON = evidencerequest.MediaTypeJSON
	MediaTypeCBOR = evidencerequest.MediaTypeCBOR
)

The two encodings a request and its reply travel in (profile §4, §11.4.1 rule 7). The wire values, their strict decoders and deterministic encoders live in go/evidencerequest; these names keep evidencebook's API.

View Source
const (
	JoinExchangeID    = "exchange_id"
	JoinRequestDigest = "request_digest"
)

Join keys a pair can be correlated by, in preference order.

View Source
const (
	RecordTypeClose           = "close"
	RecordTypeDisclosure      = "disclosure"
	RecordTypeLifecycle       = "lifecycle"
	RecordTypeIndexRoot       = "index_root"
	RecordTypeRequest         = "evidence_request"
	RecordTypeRequestAnswered = "evidence_request_answered"
	RecordTypeResponse        = "evidence_response"
	RecordTypeAbsence         = "recorded_absence"
	RecordTypeAcknowledgement = "acknowledgement"
	RecordTypeRebuttal        = "rebuttal"
)

Record types this package writes itself. Callers may use any other token; record_type is open vocabulary.

View Source
const (
	OutcomeArtifact             = "artifact"
	OutcomeRefusal              = "refusal"
	OutcomeArtifactFailed       = "artifact_verification_failed"
	OutcomeRefusalNonconforming = "refusal_nonconformant"
)

Response outcomes as recorded by a requester. Artifact and refusal are two of the request draft's three outcomes; the other two values are sub-states of a received reply that did not verify (a response received and failed, profile P-21), named as the request-draft vectors name them. None is ever an absence.

View Source
const DefaultClosureDepth = 2

DefaultClosureDepth is the citation depth a bundle follows from its root.

View Source
const DefaultDeveloper = "evidencebook"

DefaultDeveloper is the AAC developer value a book writes when none is set.

View Source
const HeaderMember = "agent_input"

HeaderMember is the AAC disclosure member that carries a record header.

View Source
const HeaderVersion = 1

HeaderVersion is the version of the record header wire form this package writes and accepts.

View Source
const InclusionKindSCITTReceiptUnverified = "scitt-receipt-unverified"

InclusionKindSCITTReceiptUnverified labels the inclusion evidence this stub carries: a transparency-service receipt held as opaque bytes and never verified here. It proves possession of those bytes only (FR-20); a verifier runs the receipt's own check. The stub's receipts are never served as checkpoints or proofs in a profile answer: Respond answers only from a Checkpointed Local Log.

View Source
const MinimumAbsenceWindow = time.Minute

MinimumAbsenceWindow is the shortest waiting window an absence may claim, measured from when the request was recorded.

View Source
const RecordTypeRetentionCommitment = "retention_commitment"

RecordTypeRetentionCommitment is the record type of a retention commitment this book has issued.

View Source
const SubstrateKindCLL = "cll"

SubstrateKindCLL labels checkpoints and proofs produced by the CLL binding.

View Source
const SubstrateKindSCITTReceipt = "scitt-receipt"

SubstrateKindSCITTReceipt labels the receipt-holding binding.

Variables

View Source
var (
	// ErrInvalid reports input that violates the record model or a request
	// shape. It is go/evidencerequest's own sentinel, so an error from the
	// aliased protocol types (Refusal.Verify, Envelope.Verify, ...) and one
	// raised here both match it.
	ErrInvalid = evidencerequest.ErrInvalid
	// ErrNotFound reports a record, payload or checkpoint the book does not hold.
	ErrNotFound = errors.New("evidencebook: not found")
	// ErrCorrupt reports stored state that disagrees with the commitment substrate.
	ErrCorrupt = errors.New("evidencebook: corrupt")
	// ErrUnsupported reports a capability the configured substrate or index does
	// not provide, such as range proofs over a receipt-only substrate.
	ErrUnsupported = errors.New("evidencebook: unsupported")
	// ErrNotCovered reports a record that no checkpoint covers yet.
	ErrNotCovered = errors.New("evidencebook: not checkpoint-covered")
	// ErrUnavailable reports a payload whose retention state yields no bytes.
	ErrUnavailable = errors.New("evidencebook: payload unavailable")
	// ErrLegalHold reports a deletion blocked by a legal hold.
	ErrLegalHold = errors.New("evidencebook: legal hold")
)

RefusalReasons is the registry, in the draft's order.

SubjectForms lists the six forms in code-point order.

Functions

func EncodeRequest added in v0.2.0

func EncodeRequest(r EvidenceRequest, mediaType string) ([]byte, error)

EncodeRequest encodes r in the given media type: JCS for JSON, core deterministic CBOR for CBOR.

func KeyID

func KeyID(s Signer) string

KeyID is the lowercase hex encoding of the signer's raw public key, the same key_id convention the record envelopes and checkpoints use.

func ReconcileHalves

func ReconcileHalves(a, b HalfSet, compare Comparator) ([]PairResult, Tallies)

ReconcileHalves pairs two sides' halves and classifies every exchange seen on either side into exactly one of six states.

Correlation runs in two passes over all halves, so the result does not depend on input order: first exchange_id (preferring a counterpart whose request_digest also agrees), then request_digest for halves still unpaired. An agreeing exchange_id with disagreeing request digests is CONFLICTING and is never re-paired on the weaker key. twin_bracket_id is recorded when both halves carry the same value and is never a join key.

One half unavailable is not disagreement: an unpaired half is A_ONLY or B_ONLY when the other side's account is complete, INSUFFICIENT otherwise, and never CONFLICTING.

func SamePayloadCommitments

func SamePayloadCommitments(a, b Half) bool

SamePayloadCommitments is a Comparator for deterministic content: the two halves committed identical payload digests. Content produced by sampling needs a comparator over the disclosed content instead.

func VerifyKeyRange

func VerifyKeyRange(root IndexRoot, lo, hi string, proof KeyRangeProof) ([]string, error)

VerifyKeyRange checks a range proof against a committed root and returns the record ids it proves are exactly the leaves with keys in [lo, hi].

func VerifyLeaf

func VerifyLeaf(root IndexRoot, proof LeafProof) error

VerifyLeaf checks one leaf proof against a committed root.

Types

type A2AOptions added in v0.2.0

type A2AOptions struct {
	// Manifest is what the host states about its carriers; Bindings must
	// list BindingA2A. The Agent Card's extension params are
	// Book.Manifest(Manifest), byte for byte the manifest served elsewhere.
	Manifest ManifestOptions
	// Policy is the sharing policy every request is answered under, as for
	// RespondOptions.Policy.
	Policy SharePolicy
	// Name and URL are the Agent Card's name and the JSON-RPC endpoint the
	// host serves Handle at. Both are required.
	Name, URL string
	// Description is the Agent Card's description; empty is a fixed default.
	Description string
	// Version is the Agent Card's version; empty is "unversioned".
	Version string
}

A2AOptions configures the A2A carriage of a book's responder.

type A2ARequest added in v0.2.0

type A2ARequest struct {
	Version    string
	Extensions []string
	Body       []byte
}

A2ARequest is one JSON-RPC message received over A2A with the service parameters it arrived with (A2A §3.2.6): the A2A-Version value ("" when absent) and the A2A-Extensions URIs, which the host splits from their comma-separated header or metadata entry.

type A2AResponse added in v0.2.0

type A2AResponse struct {
	Body       []byte
	Extensions []string
}

A2AResponse is the JSON-RPC message to send back, and the extensions this carriage activated, to send as the response's A2A-Extensions. Body is nil for a notification.

type A2AServer added in v0.2.0

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

A2AServer carries the evidence request exchange over A2A (profile §11.4.4): the Agent Card extension entry, and SendMessage answered with a completed Task holding the reply in one Artifact. It is a carriage only. It moves the request and reply octets as opaque bytes and adds nothing to what Respond answers: the canonical Artifact is the one the native stream and MCP get for the same request (FR-8, ER §5).

It keeps no task. The Task is returned whole, completed, in the SendMessage response; no other client can list or fetch it (§11.4.3), and GetTask and CancelTask find nothing. Its identifiers are random, encoding no count and no time. It does not stream (capabilities.streaming false) and offers no push notifications and no extended Agent Card.

It is transport-neutral: the host owns the HTTP endpoint, the Agent Card URL and their authentication.

func (*A2AServer) AgentCard added in v0.2.0

func (s *A2AServer) AgentCard() []byte

AgentCard returns the Agent Card to serve at the host's well-known URL. It is the same for every caller (§11.4.2, §11.4.3): it carries the manifest as the extension's params and nothing about what the book holds. A host that adds security schemes adds them to this JSON.

func (*A2AServer) Handle added in v0.2.0

func (s *A2AServer) Handle(ctx context.Context, req A2ARequest, authenticated string) A2AResponse

Handle answers one JSON-RPC message received over A2A.

authenticated is the requester identity the host's transport established through the A2A security scheme it enforces, exactly as for RespondOptions.AuthenticatedRequester, or "" when the caller is not authenticated. It is the only identity Respond sees. Nothing inside the message is ever read as one: not the Agent Card the client presents or claims, not the Message or request metadata, messageId, contextId, tenant or extensions, not the JSON-RPC id. As in Respond, authentication decides whether a subject is answered, never what is answered (profile §11.4.1 rule 5).

Every reply, envelope or refusal, is a completed Task holding one Artifact with the extension URI and one raw Part of the request's media type (P-39). Anything that is not a request under §11.4.4 gets a JSON-RPC or A2A error, which is a transport condition and never a refusal.

type AbsenceRecord added in v0.2.0

type AbsenceRecord struct {
	Outcome       string        `json:"outcome"`
	RequestDigest string        `json:"request_digest"`
	Route         string        `json:"route,omitempty"`
	Window        AbsenceWindow `json:"window"`
	RecordedAt    string        `json:"recorded_at"`
}

AbsenceRecord is the requester's own record that neither an envelope nor a refusal arrived in its waiting window (ER §4.4, profile §6.4). It is the statement of a recorded_absence record, so the book's signature over the record attributes it to the requester; it carries no responder act.

type AbsenceWindow added in v0.2.0

type AbsenceWindow struct {
	Opened string `json:"opened"`
	Closed string `json:"closed"`
}

AbsenceWindow is when the request was transmitted and when the waiting window closed.

type Anchor added in v0.2.0

type Anchor = evidencerequest.Anchor

The reply types are the request draft's, defined in go/evidencerequest (ER §4.1, §4.2, profile §6.2, §6.3); these names keep evidencebook's API.

type AnsweredStatement

type AnsweredStatement struct {
	RequestDigest  string      `json:"request_digest"`
	SubjectKind    SubjectKind `json:"subject_kind,omitempty"`
	Outcome        string      `json:"outcome"`
	Reason         string      `json:"reason,omitempty"`
	Relationship   string      `json:"relationship"`
	Anchor         string      `json:"anchor,omitempty"`
	ArtifactDigest string      `json:"artifact_digest,omitempty"`
}

AnsweredStatement is the body of the record a responder seals for a request it answered for an authenticated requester. It names no requester, and records of this type are never served to anyone (they are not servable), so asking leaves no trace another requester can read.

type AuthenticatedIndex

type AuthenticatedIndex interface {
	Name() string
	// KeyOf returns the key a record contributes, or false for none.
	KeyOf(record Record) (string, bool)
	Add(key, recordID string) error
	Reset()
	Root() IndexRoot
	ProveMember(key, recordID string) (LeafProof, error)
	// ProveRange proves exactly which records carry a key in [lo, hi]; with
	// lo == hi it is a completeness proof for one key, and an empty result is
	// a non-membership proof.
	ProveRange(lo, hi string) (KeyRangeProof, error)
}

AuthenticatedIndex is a deterministic structure whose root the book commits as a record.

What a party that does not trust the book can check, and what it cannot: a membership proof shows a (key, record id) leaf is under the committed root, with no further trust. Non-membership, range and completeness proofs additionally rely on the committed tree being sorted and holding every record: a book that commits an unsorted or incomplete tree can prove a false absence or omit a match. Only a party holding the full leaf set (for example the book's full history) can audit that, by rebuilding the root. Those three claims are therefore statements by the book, checkable against its commitment but not against a dishonest book.

type Book

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

Book is an evidence store: records, typed links, payload separation, three index classes and request/reconcile mechanics over an embedded commitment substrate. The substrate is never exposed; callers get records, bundles and answers, and the book composes every proof itself.

func Open

func Open(ctx context.Context, cfg Config) (*Book, error)

Open validates cfg, reconciles the record store with the substrate, and rebuilds every index from the committed history.

func (*Book) A2A added in v0.2.0

func (b *Book) A2A(opts A2AOptions) (*A2AServer, error)

A2A returns the A2A carriage of this book's responder.

func (*Book) Acknowledge

func (b *Book) Acknowledge(ctx context.Context, peerCloseID, counterparty string) (Record, error)

Acknowledge records that this book has seen and holds a counterparty's Close, which is what makes that Close AGREED from the counterparty's side.

func (*Book) Append

func (b *Book) Append(ctx context.Context, entry Entry) (Record, error)

Append validates entry, commits its payload bytes by digest, seals the header into a record capsule, stores the record, appends its identity to the substrate, and updates every index — in that order. When the record is committed but a later step (indexing, an automatic checkpoint) fails, the committed record is returned together with the error: do not retry it.

func (*Book) Bundle

func (b *Book) Bundle(ctx context.Context, req BundleRequest) (Bundle, error)

Bundle resolves the root's citation closure, constructs the disclosure, asks the substrate for interval and membership evidence under one anchor, and returns a portable bundle. It then commits a disclosure record citing every record whose header or payload the bundle disclosed.

func (*Book) Checkpoint

func (b *Book) Checkpoint(ctx context.Context) (Checkpoint, error)

Checkpoint commits any changed authenticated-index roots as records, then checkpoints the commitment history underlying this book.

func (*Book) Checkpoints

func (b *Book) Checkpoints(ctx context.Context) ([]Checkpoint, error)

Checkpoints returns every checkpoint this book has issued, oldest first.

func (*Book) Close

func (b *Book) Close(ctx context.Context, in CloseInput) (Record, error)

Close reconciles, then seals a Close record: a closes link to every own record the reconciliation placed, and the full state population in its statement. Its status is read later from the links other records make to it.

func (*Book) CommitRetention added in v0.2.0

func (b *Book) CommitRetention(ctx context.Context, subject Subject, until time.Time) (Record, error)

CommitRetention seals a retention commitment: a signed statement that subject stays answerable under this interaction until until (ER §9). The subject is a record, an exchange or a range: a digest or a position, never a correlation or the whole history (ERV A11). After until, a request for a subject the book no longer answers is refused retention_expired, never no_such_subject (ER §4.2 item 2).

func (*Book) Discover

func (b *Book) Discover(ctx context.Context, query string, limit int) (Candidates, error)

Discover returns approximate candidates. See Candidates for what that result may and may not be used for.

func (*Book) Get

func (b *Book) Get(_ context.Context, recordID string) (Record, error)

Get returns one record by id.

func (*Book) IndexState

func (b *Book) IndexState(ctx context.Context) (string, error)

IndexState is the operational index's current state digest.

func (*Book) Info

func (b *Book) Info() (string, SubstrateInfo)

Info names the book and the substrate it states it uses.

func (*Book) MCP added in v0.2.0

func (b *Book) MCP(opts MCPOptions) (*MCPServer, error)

MCP returns the MCP carriage of this book's responder.

func (*Book) Manifest added in v0.2.0

func (b *Book) Manifest(opts ManifestOptions) ([]byte, error)

Manifest returns the responder's manifest (ER §10, profile §11.4.2): a JSON object, in JCS, whose every value is a text string or a sorted array of text strings. It says what can be asked, never what exists: it carries no count, digest, anchor, time, principal, counterparty or history card (profile §11.4.3), and it is the same for every caller. The book's discovery index (Discover) is never part of it.

func (*Book) ProveKeyRange

func (b *Book) ProveKeyRange(ctx context.Context, index, lo, hi string) (KeyRangeAnswer, error)

ProveKeyRange proves exactly which records carry a key in [lo, hi] of the named authenticated index. It first commits the index's current root as a record and checkpoints, so the proof is always against a root the book has committed and a checkpoint covers — never a live root that has drifted from the last committed one. An empty result is a non-membership proof.

func (*Book) Query

func (b *Book) Query(ctx context.Context, filter Filter) ([]Record, error)

Query answers from the operational index. Its result is a local lookup, not a proof; use Bundle or Respond for anything a stranger must check.

func (*Book) Rebuild

func (b *Book) Rebuild(ctx context.Context) (string, error)

Rebuild re-derives the operational and discovery indexes from the committed history alone and returns the operational index's state digest.

func (*Book) Rebut

func (b *Book) Rebut(ctx context.Context, peerCloseID, counterparty string, reason json.RawMessage) (Record, error)

Rebut records that this book disputes a counterparty's Close.

func (*Book) Reconcile

func (b *Book) Reconcile(ctx context.Context, in ReconcileInput) (Reconciliation, error)

Reconcile compares this book's halves in its window with the halves a peer disclosed in a verified bundle.

func (*Book) RecordAbsence

func (b *Book) RecordAbsence(ctx context.Context, requestRecordID string, windowEnd time.Time, route string) (Record, error)

RecordAbsence commits that no reply arrived for the recorded request between its recording and windowEnd. The request digest, its deadline and the window's opening come from the committed request record, and so does the route when the request named one: a different route is refused. When the request named none, route is the route the binding attempted, if any. It refuses while the request is still pending (window not closed, or closing before the request's own deadline) and once any reply has been recorded, so an outcome is never converted into another. The record's statement is the profile's absence record (AbsenceRecord), in JCS.

func (*Book) RecordResponse

func (b *Book) RecordResponse(ctx context.Context, requestRecordID string, reply Message, keys ResponderKeys) (Record, error)

RecordResponse verifies and records the reply that came back for the request recorded as requestRecordID. Both responder keys are required. A reply that is not signed under the pinned signer key for this request's digest is refused and is not recorded: an unauthenticated message can neither become an outcome nor foreclose the real one. A reply genuinely signed by the responder that fails a check of profile §7.2 is recorded as received-and-failed, never as a grant and never as an absence.

func (*Book) RegisterDerivation added in v0.2.0

func (b *Book) RegisterDerivation(def DerivationDefinition) (string, error)

RegisterDerivation makes a derivation answerable by its identifier, which it returns. The registration is held in memory: a host registers its definitions each time it opens the book, and they are never written into the book's history, because a recipient-specific definition names its recipient.

func (*Book) Release

func (b *Book) Release() error

Release closes the store, substrate and operational index.

func (*Book) Request

func (b *Book) Request(ctx context.Context, req EvidenceRequest, responder string) (SentRequest, error)

Request records that this book is asking responder for evidence and returns the octets to transmit: the request map under this profile (its profile member set to ProfileID), in JCS (profile §6.1, P-9). An empty nonce is filled with a fresh random one, and a nonce this book already used is refused. Recording happens before sending, so "I asked" is committed whatever comes back.

func (*Book) ResolvePayload

func (b *Book) ResolvePayload(ctx context.Context, recordID, digest string) ([]byte, error)

ResolvePayload returns one payload of one record when its retention state allows it.

func (*Book) Respond

func (b *Book) Respond(ctx context.Context, request Message, opts RespondOptions) (Reply, Record, error)

Respond answers one request, received as request (octets and media type), with a signed envelope carrying the canonical Artifact or a signed refusal with exactly one registered reason, encoded in the request's encoding (profile §6, §11.4.1 rule 3). The artifact is a deterministic function of (subject, resolved anchor, derivation) only: the requester, nonce, route, profile member and encoding never change its bytes (ER §5, FR-8).

For an authenticated requester whose request was well formed, Respond seals an evidence_request_answered record and returns it; otherwise the returned Record is zero. Malformed and unauthenticated traffic never grows the log and never forces a checkpoint (FR-37).

func (*Book) Retention

func (b *Book) Retention(_ context.Context, recordID, digest string) (RetentionState, error)

Retention returns the current retention state of one payload of one record: the state the record committed, folded forward through every lifecycle record that cites that record for that payload, in log order. State belongs to the (record, payload) pair, so two records that commit identical bytes have independent retention.

func (*Book) SetRetention

func (b *Book) SetRetention(ctx context.Context, recordID, digest string, state RetentionState, reason string) (Record, error)

SetRetention appends a lifecycle record moving one payload of recordID to state. DELETED is permanent and is blocked while a legal hold stands. The bytes are destroyed after the lifecycle record is committed, and only when no other record still holds the same bytes in a resolvable state. Asking for DELETED again on a deleted payload retries a failed byte deletion and returns the existing lifecycle record.

func (*Book) Size

func (b *Book) Size() uint64

Size is the number of committed records.

type Bundle

type Bundle struct {
	JSON       []byte
	Digest     string
	Anchor     Checkpoint
	Disclosure Record
}

Bundle is a portable, self-verifying Evidence Bundle v2 plus the disclosure record the book committed about it.

type BundleCheckpoint

type BundleCheckpoint struct {
	LogID   string `json:"log_id,omitempty"`
	Root    string `json:"root"`
	MMRSize uint64 `json:"mmr_size"`
	COSE    string `json:"cose,omitempty"`
}

BundleCheckpoint is the checkpoint member of an Evidence Bundle. COSE is the base64url signed checkpoint statement, so a verifier authenticates the root rather than trusting the producer's copy of it. LogID is the log id the statement signs, as the completeness certificate states it; a bundle from before it was stated has none.

type BundleClaims

type BundleClaims struct {
	GraphClosure        string
	IntervalCoverage    string
	PerRecordMembership string
}

BundleClaims is the status of each Evidence Bundle verifier claim.

type BundleRequest

type BundleRequest struct {
	Root string
	// Include adds records to the selected set beyond the root's closure.
	Include []string
	// ClosureDepth is how many link hops to follow from Root; zero selects
	// DefaultClosureDepth.
	ClosureDepth int
	// Payloads is the disclosure claim for the selected set: all carries
	// every payload of every selected record (refused if any is unavailable),
	// selected carries those not withheld.
	Payloads PayloadsMode
	// WithholdPayloads carries headers only: every payload of the selected
	// set is withheld with its digest.
	WithholdPayloads bool
	// Suppress names disclosure members left out of the overlay; suppressing
	// HeaderMember leaves every header as withheld-with-digest.
	Suppress []string
	// Withhold names payload digests this disclosure does not carry.
	Withhold []string
	// At pins the coverage anchor; nil checkpoints the book now.
	At         *Checkpoint
	Extensions map[string]json.RawMessage
}

BundleRequest selects what a bundle carries and how much it discloses.

type CLLSubstrate

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

CLLSubstrate embeds a Checkpointed Local Log. It is the only place this module touches CLL; everything it returns is an evidencebook type.

func OpenCLL

func OpenCLL(path, logID string, checkpointKey ed25519.PrivateKey) (*CLLSubstrate, error)

OpenCLL opens (initializing if absent) a CLL journal at path. checkpointKey signs the log's checkpoints in the CLL checkpoint wire format; it is the substrate's key, held by the substrate, and may differ from the book signer.

func (*CLLSubstrate) Append

func (s *CLLSubstrate) Append(ctx context.Context, recordID string, at time.Time) (uint64, error)

func (*CLLSubstrate) Checkpoint

func (s *CLLSubstrate) Checkpoint(ctx context.Context, now time.Time) (Checkpoint, error)

func (*CLLSubstrate) Entries

func (s *CLLSubstrate) Entries(ctx context.Context, afterSeq uint64, limit int) ([]SubstrateEntry, error)

func (*CLLSubstrate) Info

func (s *CLLSubstrate) Info() SubstrateInfo

func (*CLLSubstrate) Latest

func (s *CLLSubstrate) Latest(ctx context.Context) (Checkpoint, error)

func (*CLLSubstrate) ProveConsistency

func (s *CLLSubstrate) ProveConsistency(ctx context.Context, older, newer Checkpoint) (ConsistencyEvidence, error)

func (*CLLSubstrate) ProveInclusion

func (s *CLLSubstrate) ProveInclusion(ctx context.Context, seq uint64, at Checkpoint) (InclusionEvidence, error)

func (*CLLSubstrate) ProveInterval

func (s *CLLSubstrate) ProveInterval(ctx context.Context, firstSeq uint64, at Checkpoint) (IntervalEvidence, error)

func (*CLLSubstrate) Release

func (s *CLLSubstrate) Release() error

func (*CLLSubstrate) Size

func (s *CLLSubstrate) Size(ctx context.Context) (uint64, error)

type Candidates

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

Candidates is the only result type a DiscoveryIndex returns. It is a list of places to look, never a statement about what exists or what is true: no function in this package that produces a proof, a bundle, or an answer to a request accepts it (enforced by TestDiscoveryCandidatesNeverReachProofs). To act on a candidate, fetch it by id through the book.

func (Candidates) IDs

func (c Candidates) IDs() []string

IDs returns candidate record ids, best match first.

func (Candidates) Query

func (c Candidates) Query() string

Query returns the text that produced these candidates.

type Checkpoint

type Checkpoint struct {
	Kind      string    `json:"kind"`
	LogID     string    `json:"log_id"`
	ID        string    `json:"id"`
	Entries   uint64    `json:"entries"`
	Root      string    `json:"root,omitempty"`
	TreeSize  uint64    `json:"tree_size,omitempty"`
	KeyID     string    `json:"key_id,omitempty"`
	IssuedAt  time.Time `json:"issued_at"`
	Statement []byte    `json:"statement,omitempty"`
}

Checkpoint names one committed state. ID is independent of which party serves the checkpoint: for the CLL binding it is "<root-hex>:<mmr_size>".

func VerifyCheckpoints

func VerifyCheckpoints(checkpoints []Checkpoint, consistency []ConsistencyEvidence, pinnedKey string) (Checkpoint, error)

VerifyCheckpoints checks a checkpoints/v1 history and returns its newest checkpoint as the signed statement states it. Every field is taken from the signed statement, never from the listed copy: each statement must verify, sign under pinnedKey, name the same log as the first, and match its listed fields exactly; sizes must strictly grow; and each consistency proof must show the next signed root append-only extends the previous one.

func (Checkpoint) Covers

func (c Checkpoint) Covers(seq uint64) bool

Covers reports whether seq is committed under this checkpoint.

type CloseInput

type CloseInput struct {
	Reconcile    ReconcileInput
	Counterparty string
	// Profile names the contract or profile version whose comparator and
	// windows produced the reconciliation.
	Profile    string
	Supersedes string
	Reason     string
}

CloseInput states what a Close binds. The book computes the reconciliation itself from Reconcile; a caller never supplies tallies. Supersedes names a prior Close this one adjusts; the prior Close is never rewritten.

type CloseStatement

type CloseStatement struct {
	Counterparty   string         `json:"counterparty"`
	Profile        string         `json:"profile"`
	Reconciliation Reconciliation `json:"reconciliation"`
	Reason         string         `json:"reason,omitempty"`
}

CloseStatement is the body of a Close record.

type CloseStatus

type CloseStatus string

CloseStatus is read from links, never from a field the Close sets.

const (
	Agreed     CloseStatus = "AGREED"
	Unilateral CloseStatus = "UNILATERAL"
	Contested  CloseStatus = "CONTESTED"
)

func StatusOfClose

func StatusOfClose(closeID, counterpartyBookID, counterpartyCheckpointKey string, counterparty VerifiedBundle) (CloseStatus, error)

StatusOfClose derives a Close's status from the counterparty's own records: a rebuts link makes it CONTESTED, an acknowledges link AGREED, and neither leaves it UNILATERAL. Only records that verified, carry the counterparty's book id, and sit under a checkpoint signed by the key the caller pinned for that counterparty count; a bundle from anyone else says nothing about the Close.

type Comparator

type Comparator func(a, b Half) bool

Comparator is the content test a declared profile supplies. It runs only on covered, trusted, correlated pairs and returns whether the contents agree.

type CompletenessCertificate

type CompletenessCertificate struct {
	LogID       string                `json:"log_id"`
	RangeRoot   string                `json:"range_root"`
	FirstSeq    uint64                `json:"first_seq"`
	LastSeq     uint64                `json:"last_seq"`
	BodyDigests []string              `json:"body_digests"`
	RangeProof  RangeWitness          `json:"range_proof"`
	Memberships map[string]Membership `json:"memberships"`
}

CompletenessCertificate is the Evidence Bundle v2 per-record range claim.

type Config

type Config struct {
	BookID    string
	Operator  string
	Developer string

	Store     Store
	Substrate Substrate
	Payloads  PayloadResolver
	Signer    Signer

	Operational   OperationalIndex
	Authenticated []AuthenticatedIndex
	Discovery     DiscoveryIndex

	// CheckpointEvery checkpoints after every N appends; zero checkpoints
	// only when Checkpoint is called or an answer requires it.
	CheckpointEvery uint64
	Now             func() time.Time

	// Responder is the responder's cost and abuse policy for Respond
	// (FR-37). The zero value answers the most specific reason with no rate
	// limit.
	Responder ResponderPolicy
}

Config assembles a book. Store, Substrate, Payloads and Signer are required; every index defaults to the reference implementation.

type ConsistencyEvidence

type ConsistencyEvidence struct {
	Kind  string          `json:"kind"`
	Proof json.RawMessage `json:"proof"`
}

ConsistencyEvidence proves newer append-only extends older.

type Correlation

type Correlation struct {
	ExchangeID    string `json:"exchange_id,omitempty"`
	RequestDigest string `json:"request_digest,omitempty"`
	TwinBracketID string `json:"twin_bracket_id,omitempty"`
}

Correlation carries the exchange correlation keys used to pair two halves of one interaction across independently held books. Join order is ExchangeID, then RequestDigest; TwinBracketID is recorded, never joined on.

type Coverage

type Coverage = evidencerequest.Coverage

type DerivationDefinition added in v0.2.0

type DerivationDefinition struct {
	// Document is the definition document, a JSON object. The derivation's
	// identifier is SHA-256 over UTF-8 of its JCS. The profile does not fix
	// its member names (P-14); this package reads none of them, and the
	// holder states what it declares in the fields below as well.
	Document []byte
	// Recipient is the authenticated requester the projection is prepared
	// for, as the definition names it. Only that requester is answered. An
	// empty Recipient makes the derivation answerable under the share policy
	// like any protected subject.
	Recipient string
	// Forms are the subject forms the derivation is defined over; any other
	// form is answered no_such_subject (ER §3.3).
	Forms []SubjectKind
	// Fields is the declared field set: the record header members the
	// projection reveals, and nothing else (ER §8).
	Fields []string
}

DerivationDefinition is a derivation this responder serves by the digest of its definition (ER §3.3). A recipient-specific disclosure is exactly such a derivation (profile §6.5, ruling 5): a new identity, never a variant of the canonical Artifact of the underived subject.

type DisclosureStatement

type DisclosureStatement struct {
	BundleDigest     string         `json:"bundle_digest"`
	Anchor           string         `json:"anchor"`
	Payloads         PayloadsMode   `json:"payloads"`
	SuppressedFields []string       `json:"suppressed_fields"`
	Withheld         []WithheldItem `json:"withheld"`
}

DisclosureStatement is the body of a disclosure record (Evidence Layer §6.2).

type DiscoveryIndex

type DiscoveryIndex interface {
	Add(ctx context.Context, record Record) error
	Search(ctx context.Context, query string, limit int) (Candidates, error)
	Rebuild(ctx context.Context, source RecordSource) error
}

DiscoveryIndex finds candidate records by approximate match. It is always rebuildable and is never proof of completeness or of truth.

type Ed25519Signer

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

Ed25519Signer is the reference in-process Signer.

func NewEd25519Signer

func NewEd25519Signer(private ed25519.PrivateKey) (*Ed25519Signer, error)

NewEd25519Signer copies private so later mutation by the caller has no effect.

func (*Ed25519Signer) PublicKey

func (s *Ed25519Signer) PublicKey() ed25519.PublicKey

PublicKey returns a copy of the verifying key.

func (*Ed25519Signer) Sign

func (s *Ed25519Signer) Sign(ctx context.Context, message []byte) ([]byte, error)

Sign returns the Ed25519 signature over message.

type Entry

type Entry struct {
	RecordType      string
	EpistemicType   EpistemicType
	EventTimeClaim  time.Time
	Payloads        [][]byte
	Links           []Link
	SubjectRef      string
	PrincipalRef    string
	CounterpartyRef string
	Correlation     Correlation
	Statement       json.RawMessage
}

Entry is what a caller asks the book to record. Seq, CommittedAt, BookID and the record identity are assigned by the book.

type Envelope added in v0.2.0

type Envelope = evidencerequest.Envelope

The reply types are the request draft's, defined in go/evidencerequest (ER §4.1, §4.2, profile §6.2, §6.3); these names keep evidencebook's API.

type EpistemicType

type EpistemicType string

EpistemicType states how a record's content came to be known. It is a closed set (Evidence Layer §4.1), assigned once at commit and never upgraded by anything attached to the record later.

const (
	ObservedEvent       EpistemicType = "observed_event"
	SystemOfRecordFact  EpistemicType = "system_of_record_fact"
	ProducerClaim       EpistemicType = "producer_claim"
	HumanReport         EpistemicType = "human_report"
	SemanticJudgment    EpistemicType = "semantic_judgment"
	DerivedMetric       EpistemicType = "derived_metric"
	Adjudication        EpistemicType = "adjudication"
	ObligationReference EpistemicType = "obligation_reference"
)

func EpistemicTypes

func EpistemicTypes() []EpistemicType

EpistemicTypes returns the closed value set in registry order.

func (EpistemicType) Valid

func (t EpistemicType) Valid() bool

Valid reports whether t is one of the eight registered values.

type EvidenceRequest

type EvidenceRequest = evidencerequest.Request

type ExchangeState

type ExchangeState string

ExchangeState is the per-exchange reconciliation state.

const (
	Matched      ExchangeState = "MATCHED"
	AOnly        ExchangeState = "A_ONLY"
	BOnly        ExchangeState = "B_ONLY"
	Conflicting  ExchangeState = "CONFLICTING"
	Insufficient ExchangeState = "INSUFFICIENT"
	Unresolved   ExchangeState = "UNRESOLVED"
)

type FileStore

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

FileStore is an append-only JSONL record journal plus a checkpoint journal.

func OpenFileStore

func OpenFileStore(dir string) (*FileStore, error)

OpenFileStore opens (creating if absent) a store in dir. A torn final line left by a crash is truncated; a malformed complete line is corruption.

func (*FileStore) Checkpoints

func (s *FileStore) Checkpoints(context.Context) ([]Checkpoint, error)

func (*FileStore) GetRecord

func (s *FileStore) GetRecord(_ context.Context, recordID string) (StoredRecord, error)

func (*FileStore) PutCheckpoint

func (s *FileStore) PutCheckpoint(ctx context.Context, cp Checkpoint) error

func (*FileStore) PutRecord

func (s *FileStore) PutRecord(ctx context.Context, record StoredRecord) error

func (*FileStore) Records

func (s *FileStore) Records(context.Context) ([]StoredRecord, error)

func (*FileStore) Release

func (s *FileStore) Release() error

type Filter

type Filter struct {
	RecordType      string
	SubjectRef      string
	CounterpartyRef string
	ExchangeID      string
	RequestDigest   string
	LinkType        LinkType
	LinkTarget      string
	FromSeq         uint64
	ToSeq           uint64
}

Filter selects records from the operational index. Zero-valued fields do not constrain the result.

type Freshness

type Freshness = evidencerequest.Freshness

type Half

type Half struct {
	RecordID           string
	Seq                uint64
	Correlation        Correlation
	PayloadCommitments []string
	Covered            bool
	Trusted            bool
}

Half is one side's record of one exchange as the reconciliation sees it. Covered means inside an authenticated checkpoint; Trusted means the record verifies and its header matches what it committed.

type HalfSet

type HalfSet struct {
	Halves   []Half
	Complete bool
}

HalfSet is one side's account of a period. Complete means that account is checkpoint-covered, so a missing counterpart on this side is a provable absence rather than an unknown.

type Header struct {
	Version            int             `json:"v"`
	BookID             string          `json:"book_id"`
	Seq                uint64          `json:"seq"`
	RecordType         string          `json:"record_type"`
	EpistemicType      EpistemicType   `json:"epistemic_type"`
	CommittedAt        string          `json:"committed_at"`
	EventTimeClaim     string          `json:"event_time_claim,omitempty"`
	PayloadCommitments []string        `json:"payload_commitments,omitempty"`
	RetentionState     RetentionState  `json:"retention_state,omitempty"`
	Links              []Link          `json:"links"`
	SubjectRef         string          `json:"subject_ref,omitempty"`
	PrincipalRef       string          `json:"principal_ref,omitempty"`
	CounterpartyRef    string          `json:"counterparty_ref,omitempty"`
	Correlation        *Correlation    `json:"correlation,omitempty"`
	Statement          json.RawMessage `json:"statement,omitempty"`
}

Header is the durable, privacy-minimized record header (Evidence Layer §4). Its canonical JSON is committed as the record capsule's agent_input_digest, so every field below is fixed at commit.

func (Header) LinksTo

func (h Header) LinksTo(t LinkType) []string

LinksTo returns the targets of every link of type t in h.

type InclusionEvidence

type InclusionEvidence struct {
	Kind  string          `json:"kind"`
	Seq   uint64          `json:"seq"`
	Proof json.RawMessage `json:"proof"`
}

InclusionEvidence is a substrate-specific inclusion proof for one record, labelled by Kind so a verifier knows which algorithm checks it.

type IndexRoot

type IndexRoot struct {
	Index string `json:"index"`
	Root  string `json:"root"`
	Size  uint64 `json:"size"`
}

IndexRoot is what the book commits: the index name, its Merkle root, and its leaf count.

type IntervalEvidence

type IntervalEvidence struct {
	Certificate CompletenessCertificate `json:"completeness_certificate"`
	Checkpoint  BundleCheckpoint        `json:"checkpoint"`
}

IntervalEvidence carries the completeness certificate and authenticated checkpoint in the Evidence Bundle v2 wire shape.

type KeyRangeAnswer

type KeyRangeAnswer struct {
	Root         IndexRoot     `json:"root"`
	RootRecordID string        `json:"root_record_id"`
	Anchor       Checkpoint    `json:"anchor"`
	Proof        KeyRangeProof `json:"proof"`
}

KeyRangeAnswer is a key-range proof bound to what the book committed: the index root it verifies under, the index_root record that committed that root, and the checkpoint that covers that record. This package ships no standalone verifier for the binding (that the root equals the index_root record's statement and that the record is included under Anchor); a relying party checks the proof with VerifyKeyRange and the binding from a bundle carrying the index_root record. See AuthenticatedIndex for what the proof does not establish against a dishonest book.

type KeyRangeProof

type KeyRangeProof struct {
	Lo      string      `json:"lo"`
	Hi      string      `json:"hi"`
	First   uint64      `json:"first"`
	Matches []LeafProof `json:"matches"`
	Left    *LeafProof  `json:"left,omitempty"`
	Right   *LeafProof  `json:"right,omitempty"`
}

KeyRangeProof proves the complete set of leaves whose key lies in [Lo, Hi]: the matches are contiguous, and the neighbours on either side (when the range does not touch an edge of the tree) have keys outside the range.

type LeafProof

type LeafProof struct {
	Key      string   `json:"key"`
	RecordID string   `json:"record_id"`
	Index    uint64   `json:"index"`
	Path     []string `json:"path"`
}

LeafProof proves one (key, record id) leaf sits at Index under a root.

type LifecycleStatement

type LifecycleStatement struct {
	PayloadCommitment string         `json:"payload_commitment"`
	RetentionState    RetentionState `json:"retention_state"`
	Reason            string         `json:"reason,omitempty"`
}

LifecycleStatement is the body of a lifecycle record: a later, separately committed statement that one payload of the cited record changed retention state. The record that committed the payload is never rewritten.

type Link struct {
	Type   LinkType `json:"type"`
	Target string   `json:"target"`
}

Link is a typed, directed reference to another record by its record id. A link is committed inside the carrying record and never mutates its target.

type LinkType

type LinkType string

LinkType is the closed typed-link vocabulary (Evidence Layer §5).

const (
	Cites        LinkType = "cites"
	Adjudicates  LinkType = "adjudicates"
	Supersedes   LinkType = "supersedes"
	Acknowledges LinkType = "acknowledges"
	Rebuts       LinkType = "rebuts"
	Closes       LinkType = "closes"
)

func LinkTypes

func LinkTypes() []LinkType

LinkTypes returns the closed link vocabulary in registry order.

func (LinkType) Valid

func (t LinkType) Valid() bool

Valid reports whether t is a registered link type.

type LogCoordinates

type LogCoordinates struct {
	LogID     string `json:"log_id"`
	Seq       uint64 `json:"seq"`
	LeafIndex uint64 `json:"leaf_index"`
}

LogCoordinates locates a record in the log.

type MCPOptions added in v0.2.0

type MCPOptions struct {
	// Manifest is what the host states about its carriers; Bindings must
	// list BindingMCP. The manifest served by evidence_manifest is
	// Book.Manifest(Manifest), byte for byte the one served elsewhere.
	Manifest ManifestOptions
	// Policy is the sharing policy every request is answered under, as for
	// RespondOptions.Policy.
	Policy SharePolicy
	// ServerVersion is the version in the serverInfo each result carries;
	// empty is "unversioned".
	ServerVersion string
}

MCPOptions configures the MCP carriage of a book's responder.

type MCPServer added in v0.2.0

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

MCPServer carries the evidence request exchange over MCP (profile §11.4.5): the tools evidence_manifest and evidence_request, and the server/discover and tools/list requests MCP requires around them. It is a carriage only. It moves the request and reply octets as opaque bytes and adds nothing to what Respond answers: the canonical Artifact is the one the native stream gets for the same request (FR-8, ER §5).

It is transport-neutral: Handle takes one received JSON-RPC message and returns the message to send back. The host owns the transport and its authentication.

func (*MCPServer) Handle added in v0.2.0

func (s *MCPServer) Handle(ctx context.Context, message []byte, authenticated string) []byte

Handle answers one JSON-RPC message received over MCP and returns the JSON-RPC message to send back, or nil for a notification.

authenticated is the requester identity the host's transport established by its own authentication of this message (MCP authorization over HTTP, or the credentials of a stdio process), exactly as for RespondOptions.AuthenticatedRequester, or "" when the caller is not authenticated. It is the only identity Respond sees. Nothing inside the message is ever read as one: not the MCP _meta (clientInfo included), not a tool argument, not the JSON-RPC id, and not the connection the message arrived on. MCP 2026-07-28 has no session to read one from either. As in Respond, authentication decides whether a subject is answered, never what is answered (profile §11.4.1 rule 5).

Every reply, envelope or refusal, is a tool result with isError false and structuredContent {"reply", "media_type"} (P-40). Anything that is not a request under §11.4.5 gets a JSON-RPC error, which is a transport condition and never a refusal.

type MMRInclusion

type MMRInclusion struct {
	V          uint64   `json:"v"`
	Kind       string   `json:"kind"`
	Size       uint64   `json:"size"`
	LeafIndex  uint64   `json:"leaf_index"`
	Witness    []string `json:"witness"`
	PeaksLeft  []string `json:"peaks_left"`
	PeaksRight []string `json:"peaks_right"`
}

MMRInclusion is the portable MMR inclusion proof.

type ManifestOptions added in v0.2.0

type ManifestOptions struct {
	// Bindings are the binding tokens the host answers this exchange over.
	Bindings []string
	// Retention is a URI where the responder's retention commitments can be
	// fetched, or empty. It must not be an enumerable index open to
	// unauthenticated callers (profile §11.4.3).
	Retention string
}

ManifestOptions is what the host states about how it carries the exchange. The book knows its own profile, drafts, subject forms, derivations and refusal policy; it does not know its carriers.

type Membership

type Membership struct {
	LogCoordinates LogCoordinates `json:"log_coordinates"`
	InclusionProof MMRInclusion   `json:"inclusion_proof"`
}

Membership binds one record to its log coordinates with an inclusion proof.

type Message added in v0.2.0

type Message = evidencerequest.Message

Message is octets as carried, with the media type they were carried under.

type OperationalIndex

type OperationalIndex interface {
	Add(ctx context.Context, record Record) error
	// Find returns matching record ids in log order.
	Find(ctx context.Context, filter Filter) ([]string, error)
	// Rebuild discards all state and re-derives it from source.
	Rebuild(ctx context.Context, source RecordSource) error
	// StateDigest is a deterministic digest of the full index contents.
	StateDigest(ctx context.Context) (string, error)
	Release() error
}

OperationalIndex is fast local lookup with no independent trust value: its answers are only as trustworthy as the store producing them, and nothing that produces a proof reads from it.

type PairResult

type PairResult struct {
	State         ExchangeState `json:"state"`
	JoinKey       string        `json:"join_key,omitempty"`
	A             string        `json:"a,omitempty"`
	B             string        `json:"b,omitempty"`
	TwinBracketID string        `json:"twin_bracket_id,omitempty"`
}

PairResult classifies one exchange.

type PayloadDir

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

PayloadDir is the reference PayloadResolver.

func OpenPayloadDir

func OpenPayloadDir(dir string) (*PayloadDir, error)

OpenPayloadDir stores payload bytes as files named by semantic digest, with no storage transform, so the storage digest equals the semantic digest.

func (*PayloadDir) Delete

func (p *PayloadDir) Delete(_ context.Context, digest string) error

func (*PayloadDir) Put

func (p *PayloadDir) Put(_ context.Context, digest string, data []byte) error

func (*PayloadDir) Resolve

func (p *PayloadDir) Resolve(_ context.Context, digest string) ([]byte, error)

func (*PayloadDir) StorageDigest

func (p *PayloadDir) StorageDigest(ctx context.Context, digest string) (string, error)

type PayloadResolver

type PayloadResolver interface {
	Put(ctx context.Context, semanticDigest string, data []byte) error
	// Resolve returns the bytes, or ErrNotFound when they are not held.
	// Retention policy is applied by the book, not the resolver.
	Resolve(ctx context.Context, semanticDigest string) ([]byte, error)
	StorageDigest(ctx context.Context, semanticDigest string) (string, error)
	Delete(ctx context.Context, semanticDigest string) error
}

PayloadResolver turns a committed payload digest back into bytes. It is digest-addressed: the header commits digests, never storage locations. The semantic digest (what the header commits) and the storage digest (of the bytes as held at rest, after any host transform) are independent values.

type PayloadsMode

type PayloadsMode string

PayloadsMode is the disclosure record's payloads claim.

const (
	PayloadsAll      PayloadsMode = "all"
	PayloadsSelected PayloadsMode = "selected"
)

type PeerRecord

type PeerRecord struct {
	RecordID       string
	Seq            uint64
	Header         *Header
	HeaderVerified bool
	CapsuleOK      bool
}

PeerRecord is one record read from a verified bundle. Header is nil when the bundle withheld it; HeaderVerified is true only when the disclosed header hashes to the digest the record's capsule commits.

type RangeWitness

type RangeWitness struct {
	FromSeq   uint64   `json:"from_seq"`
	ToSeq     uint64   `json:"to_seq"`
	Size      uint64   `json:"size"`
	FromIndex uint64   `json:"from_index"`
	ToIndex   uint64   `json:"to_index"`
	Witness   []string `json:"witness"`
}

RangeWitness is the index-shaped range proof a completeness certificate carries.

type Receipt

type Receipt struct {
	ServiceID string `json:"service_id"`
	TreeSize  uint64 `json:"tree_size"`
	LeafIndex uint64 `json:"leaf_index"`
	Bytes     []byte `json:"bytes"`
}

Receipt is an opaque transparency-service receipt (for example a COSE Receipt) with the tree coordinates it attests.

type ReconcileInput

type ReconcileInput struct {
	Peer VerifiedBundle
	// RecordType restricts both sides to one record type; empty takes every
	// record that carries correlation keys.
	RecordType string
	// FromSeq and ToSeq bound this book's own window; zero leaves an end open.
	FromSeq, ToSeq uint64
	// PeerFromSeq and PeerToSeq bound the peer's window the same way.
	PeerFromSeq, PeerToSeq uint64
	Compare                Comparator
}

ReconcileInput names the peer's disclosed account and the content test. Each side's window is in that side's own log positions.

type Reconciliation

type Reconciliation struct {
	OwnHead      string       `json:"own_head"`
	PeerHead     string       `json:"peer_head"`
	PeerLog      string       `json:"peer_log"`
	PeerComplete bool         `json:"peer_complete"`
	FromSeq      uint64       `json:"from_seq"`
	ToSeq        uint64       `json:"to_seq"`
	PeerFromSeq  uint64       `json:"peer_from_seq"`
	PeerToSeq    uint64       `json:"peer_to_seq"`
	Pairs        []PairResult `json:"pairs"`
	Tallies      Tallies      `json:"states"`
}

Reconciliation is the result of comparing this book (side A) with a peer's verified bundle (side B). It is computed from bundles alone.

type Record

type Record struct {
	RecordID string
	Seq      uint64
	Header   Header
}

Record is one committed entry: its identity, position, and header. RecordID is the Capsule ID of the sealed record capsule and is the exact 32-byte value appended to the commitment substrate.

type RecordSource

type RecordSource func(ctx context.Context, yield func(Record) error) error

RecordSource yields every committed record in log order. Index rebuilds read only from a RecordSource, so an index can always be reproduced from the committed history alone.

type Refusal

type Refusal = evidencerequest.Refusal

The reply types are the request draft's, defined in go/evidencerequest (ER §4.1, §4.2, profile §6.2, §6.3); these names keep evidencebook's API.

type Registrar

type Registrar interface {
	Register(ctx context.Context, recordID string) (Receipt, error)
}

Registrar registers a record identity with a SCITT transparency service and returns the service's receipt. The service, not the book, assigns the position the receipt proves.

type Reply added in v0.2.0

type Reply = evidencerequest.Reply

The reply types are the request draft's, defined in go/evidencerequest (ER §4.1, §4.2, profile §6.2, §6.3); these names keep evidencebook's API.

func ParseReply added in v0.2.0

func ParseReply(m Message) (Reply, error)

ParseReply reads a received reply: exactly one of an envelope or a refusal. Every failure matches ErrInvalid.

type RequestLimiter added in v0.2.0

type RequestLimiter interface {
	Allow(requester string, now time.Time) bool
}

RequestLimiter decides whether a requester may be answered now. The requester is the authenticated identity, or "" for every caller the transport did not authenticate. A request over the limit is refused policy_declined.

type RequestStatement

type RequestStatement struct {
	Request      json.RawMessage `json:"request"`
	ResponderRef string          `json:"responder_ref,omitempty"`
}

RequestStatement is the body of the record a requester seals before it sends a request. The responder is named here, not in counterparty_ref: asking a party does not make it a counterparty of this book.

type RespondOptions

type RespondOptions struct {
	AuthenticatedRequester string
	// Deprecated: a declared identity is not authentication. Respond ignores
	// it; set AuthenticatedRequester from the transport's authentication.
	RequesterID string
	Policy      SharePolicy
}

RespondOptions carries the requester's identity and the sharing policy.

AuthenticatedRequester is the requester identity established by the transport's own authentication of the caller (for example a verified mutual-TLS peer or a verified signature over the request). Set it only from that authentication; leave it empty when the caller is not authenticated. It is the only input to the relationship gate: with it empty, Respond answers only public questions (the checkpoints subject and the history_card/1 derivation) and refuses every other subject with a signed not_authorized refusal, whatever the policy tier. It decides whether a subject is answered, never what is answered (ER §3.7, §5).

RequesterID is the identity the caller declared. It is never trusted: it does not select a relationship, does not grant any scope, and is not recorded. A handle, route, Agent Card or connection is not authorization either; only AuthenticatedRequester is read.

type ResponderKeys

type ResponderKeys struct {
	Signer     string
	Checkpoint string
	// Witnesses is the requester's witness directory, used when it checks an
	// Evidence Bundle (VerifyBundleAnswer).
	Witnesses []WitnessRow
}

ResponderKeys are the responder's keys as the requester obtained them, independently of any reply: Signer signs refusals and envelopes, Checkpoint signs the checkpoints an artifact is anchored to.

type ResponderPolicy added in v0.2.0

type ResponderPolicy struct {
	// RefusalPolicy is RefusalPolicySpecific (the default when empty) or
	// RefusalPolicyUniform.
	RefusalPolicy string
	// Limiter rate-limits requests per requester; nil sets no limit.
	Limiter RequestLimiter
	// MaxRequestBytes caps a request's size; zero is DefaultMaxRequestBytes.
	MaxRequestBytes int
	// MaxAnswerItems caps the records or checkpoints one artifact carries; a
	// larger answer is refused policy_declined. Zero is DefaultMaxAnswerItems.
	MaxAnswerItems int
}

ResponderPolicy is the responder's cost and abuse policy (FR-37). The zero value answers the most specific token with no rate limit.

type ResponseStatement

type ResponseStatement struct {
	RequestDigest string `json:"request_digest"`
	Outcome       string `json:"outcome"`
	Reason        string `json:"reason,omitempty"`
	KeyID         string `json:"key_id"`
	CheckpointKey string `json:"checkpoint_key_id"`
	Artifact      string `json:"artifact_digest,omitempty"`
	Anchor        string `json:"anchor,omitempty"`
	// NotChecked names the profile properties (§7.2) this requester could
	// not check for a recorded artifact, for example anchor_inclusion where
	// the profile defines no material kind for the subject (P-13).
	NotChecked []string `json:"not_checked,omitempty"`
	Failure    string   `json:"failure,omitempty"`
}

ResponseStatement is the body of the record a requester seals on receipt. KeyID is always the pinned responder key the reply verified under.

type RetentionState

type RetentionState string

RetentionState names whether a record's payload can currently be resolved (Evidence Layer §6.1).

const (
	Available RetentionState = "AVAILABLE"
	Partial   RetentionState = "PARTIAL"
	Withheld  RetentionState = "WITHHELD"
	Deleted   RetentionState = "DELETED"
	LegalHold RetentionState = "LEGAL_HOLD"
)

func (RetentionState) Valid

func (s RetentionState) Valid() bool

Valid reports whether s is a registered retention state.

type SCITTReceiptSubstrate

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

SCITTReceiptSubstrate is a stub binding: it holds one receipt per record in memory and answers inclusion with that receipt. It keeps no log of its own, so interval and consistency proofs are ErrUnsupported and the book's bundles over it carry receipts instead of a completeness certificate. It exists so the "no particular substrate required" property is exercised in code, not asserted in prose; it is not durable.

func NewSCITTReceiptSubstrate

func NewSCITTReceiptSubstrate(serviceID string, registrar Registrar) (*SCITTReceiptSubstrate, error)

NewSCITTReceiptSubstrate returns the receipt-holding substrate stub.

func (*SCITTReceiptSubstrate) Append

func (s *SCITTReceiptSubstrate) Append(ctx context.Context, recordID string, at time.Time) (uint64, error)

func (*SCITTReceiptSubstrate) Checkpoint

func (s *SCITTReceiptSubstrate) Checkpoint(ctx context.Context, _ time.Time) (Checkpoint, error)

Checkpoint names the latest receipt's tree state. The identity comes from the transparency service's coordinates, not from anything the book computes.

func (*SCITTReceiptSubstrate) Entries

func (s *SCITTReceiptSubstrate) Entries(_ context.Context, afterSeq uint64, limit int) ([]SubstrateEntry, error)

func (*SCITTReceiptSubstrate) Info

func (*SCITTReceiptSubstrate) Latest

func (*SCITTReceiptSubstrate) ProveConsistency

func (*SCITTReceiptSubstrate) ProveInclusion

func (*SCITTReceiptSubstrate) ProveInterval

func (*SCITTReceiptSubstrate) Release

func (s *SCITTReceiptSubstrate) Release() error

func (*SCITTReceiptSubstrate) Size

type SQLiteIndex

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

SQLiteIndex is the reference OperationalIndex.

func OpenSQLiteIndex

func OpenSQLiteIndex(path string) (*SQLiteIndex, error)

OpenSQLiteIndex opens the reference operational index. An empty path keeps it in memory, which is safe because it is always rebuildable.

func (*SQLiteIndex) Add

func (x *SQLiteIndex) Add(ctx context.Context, record Record) error

func (*SQLiteIndex) Find

func (x *SQLiteIndex) Find(ctx context.Context, f Filter) ([]string, error)

func (*SQLiteIndex) Rebuild

func (x *SQLiteIndex) Rebuild(ctx context.Context, source RecordSource) error

func (*SQLiteIndex) Release

func (x *SQLiteIndex) Release() error

func (*SQLiteIndex) StateDigest

func (x *SQLiteIndex) StateDigest(ctx context.Context) (string, error)

type SentRequest

type SentRequest struct {
	Bytes    []byte
	Digest   string
	RecordID string
}

SentRequest is a request as transmitted: its octets (JCS JSON), their digest, and the id of the record of having asked. RecordResponse and RecordAbsence re-derive everything else from that committed record.

func (SentRequest) Message added in v0.2.0

func (s SentRequest) Message() Message

Message is the request as carried.

type SharePolicy

type SharePolicy struct {
	RecordAtCompletion string `json:"record_at_completion"`
	HistorySegments    string `json:"history_segments"`
	Adjudications      string `json:"adjudications"`
	Witness            string `json:"witness,omitempty"`
}

SharePolicy is the four-switch sharing policy, carried unchanged from the mesh plugin's share.* object. Every default keys on relationship.

func DefaultSharePolicy

func DefaultSharePolicy() SharePolicy

DefaultSharePolicy returns the documented defaults.

func (SharePolicy) Validate

func (p SharePolicy) Validate() error

Validate rejects any switch outside its enumerated values.

type Signer

type Signer interface {
	PublicKey() ed25519.PublicKey
	Sign(ctx context.Context, message []byte) ([]byte, error)
}

Signer is the book's signing seam. A host plugs in any key custodian (a local key, an HSM, a KMS) that produces raw Ed25519 signatures; the book never holds or requires a particular key. Sign receives the exact bytes to be signed (for COSE, the Sig_structure), never a pre-hash.

type SortedMerkleIndex

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

SortedMerkleIndex is the reference AuthenticatedIndex: a sorted list of (key, record id) leaves under an RFC 9162 Merkle tree.

func NewRecordIDIndex

func NewRecordIDIndex() *SortedMerkleIndex

NewRecordIDIndex indexes every record under its own record id, so the book can prove that a record id is, or is not, committed.

func NewSubjectIndex

func NewSubjectIndex() *SortedMerkleIndex

NewSubjectIndex indexes records under subject_ref, so the book can prove the complete set of records it holds for one correlation subject.

func (*SortedMerkleIndex) Add

func (m *SortedMerkleIndex) Add(key, recordID string) error

func (*SortedMerkleIndex) KeyOf

func (m *SortedMerkleIndex) KeyOf(record Record) (string, bool)

func (*SortedMerkleIndex) Name

func (m *SortedMerkleIndex) Name() string

func (*SortedMerkleIndex) ProveMember

func (m *SortedMerkleIndex) ProveMember(key, recordID string) (LeafProof, error)

func (*SortedMerkleIndex) ProveRange

func (m *SortedMerkleIndex) ProveRange(lo, hi string) (KeyRangeProof, error)

func (*SortedMerkleIndex) Reset

func (m *SortedMerkleIndex) Reset()

func (*SortedMerkleIndex) Root

func (m *SortedMerkleIndex) Root() IndexRoot

type Store

type Store interface {
	PutRecord(ctx context.Context, record StoredRecord) error
	GetRecord(ctx context.Context, recordID string) (StoredRecord, error)
	Records(ctx context.Context) ([]StoredRecord, error)
	PutCheckpoint(ctx context.Context, cp Checkpoint) error
	Checkpoints(ctx context.Context) ([]Checkpoint, error)
	Release() error
}

Store holds complete records and the checkpoints the book has observed. A record is stored before its identity is appended to the substrate, so the substrate never commits an identity the book cannot produce.

type StoredRecord

type StoredRecord struct {
	Seq      uint64          `json:"seq"`
	RecordID string          `json:"record_id"`
	Header   json.RawMessage `json:"header"`
	Capsule  json.RawMessage `json:"capsule"`
	Envelope []byte          `json:"envelope"`
}

StoredRecord is the durable form of one record: the canonical header bytes, the sealed signature-free capsule, and its Producer Envelope.

type Subject

type Subject = evidencerequest.Subject

type SubjectKind

type SubjectKind = evidencerequest.SubjectKind

SubjectKind names one of the six subject forms (ER §3.1).

type Substrate

type Substrate interface {
	Info() SubstrateInfo
	// Append assigns the next position to recordID. Appending an identity
	// that is already present returns its original position.
	Append(ctx context.Context, recordID string, at time.Time) (uint64, error)
	Size(ctx context.Context) (uint64, error)
	Entries(ctx context.Context, afterSeq uint64, limit int) ([]SubstrateEntry, error)
	// Checkpoint commits a checkpoint over everything appended so far.
	Checkpoint(ctx context.Context, now time.Time) (Checkpoint, error)
	// Latest returns the newest checkpoint, or ErrNotFound when none exists.
	Latest(ctx context.Context) (Checkpoint, error)
	ProveInclusion(ctx context.Context, seq uint64, at Checkpoint) (InclusionEvidence, error)
	// ProveInterval returns the per-record range and membership evidence for
	// positions [firstSeq, at.Entries]. Substrates that do not maintain an
	// ordered log return ErrUnsupported.
	ProveInterval(ctx context.Context, firstSeq uint64, at Checkpoint) (IntervalEvidence, error)
	ProveConsistency(ctx context.Context, older, newer Checkpoint) (ConsistencyEvidence, error)
	Release() error
}

Substrate is the commitment-substrate interface (Evidence Layer §8). A book needs exactly four properties from it: append order, inclusion, consistency, and checkpoint identity. A Checkpointed Local Log is the reference binding (OpenCLL); a SCITT receipt-holding binding (NewSCITTReceiptSubstrate) shows the book does not require one.

Record identities cross this interface as lowercase hex strings and every proof leaves it as an evidencebook type, so no substrate implementation type is ever visible to a book caller.

type SubstrateEntry

type SubstrateEntry struct {
	Seq        uint64
	RecordID   string
	AppendedAt time.Time
}

SubstrateEntry is one committed position.

type SubstrateInfo

type SubstrateInfo struct {
	Kind  string `json:"kind"`
	LogID string `json:"log_id"`
}

SubstrateInfo names the substrate a book states it uses.

type Tallies

type Tallies struct {
	Matched      int `json:"MATCHED"`
	AOnly        int `json:"A_ONLY"`
	BOnly        int `json:"B_ONLY"`
	Conflicting  int `json:"CONFLICTING"`
	Insufficient int `json:"INSUFFICIENT"`
	Unresolved   int `json:"UNRESOLVED"`
}

Tallies counts exchanges per state.

type TokenIndex

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

TokenIndex is the reference DiscoveryIndex.

func NewTokenIndex

func NewTokenIndex() *TokenIndex

NewTokenIndex is a small reference DiscoveryIndex that matches word tokens in record_type, subject_ref and statement text.

func (*TokenIndex) Add

func (x *TokenIndex) Add(_ context.Context, record Record) error

func (*TokenIndex) Rebuild

func (x *TokenIndex) Rebuild(ctx context.Context, source RecordSource) error

func (*TokenIndex) Search

func (x *TokenIndex) Search(_ context.Context, query string, limit int) (Candidates, error)

type UnavailableError

type UnavailableError struct {
	RecordID string
	Digest   string
	State    RetentionState
}

UnavailableError reports why a payload yields no bytes. WITHHELD and DELETED both yield none; only DELETED is permanent, so callers read State.

func (*UnavailableError) Error

func (e *UnavailableError) Error() string

func (*UnavailableError) Unwrap

func (e *UnavailableError) Unwrap() error

type VerificationEntry added in v0.2.0

type VerificationEntry = evidencerequest.VerificationEntry

The reply types are the request draft's, defined in go/evidencerequest (ER §4.1, §4.2, profile §6.2, §6.3); these names keep evidencebook's API.

type VerifiedBundle

type VerifiedBundle struct {
	Digest              string
	LogID               string
	Anchor              BundleCheckpoint
	AnchorAuthenticated bool
	AnchorKeyID         string
	// AnchorStatement is the anchor's signed checkpoint statement, when
	// AnchorAuthenticated.
	AnchorStatement []byte
	// Witnesses are the witness receipts the bundle carries
	// (checkpoint.witnesses), as given. Nothing here verifies them: a
	// requester checks them against the anchor under its own witness
	// directory (RecordResponse does, through ResponderKeys.Witnesses).
	Witnesses     []json.RawMessage
	IntervalFirst uint64
	IntervalLast  uint64
	Records       []PeerRecord
	Payloads      map[string][]byte
	// Extensions are integrity-covered by the bundle digest but are the
	// producer's statements; nothing in them is independently verified.
	Extensions map[string]json.RawMessage
	Findings   []string
	// Claims is each of the three verifier claims' status ("pass",
	// "withheld", "unverified", ...). VerifyBundle refuses only "fail";
	// FullyVerified reports whether everything passed.
	Claims BundleClaims
}

VerifiedBundle is what a relying party learns from a bundle after the neutral Evidence Bundle verifier has checked it. AnchorAuthenticated means the checkpoint statement verifies under the key it names (AnchorKeyID); whether that key and log belong to the party the relying party expects is the relying party's check, against a key it obtained independently.

func VerifyBundle

func VerifyBundle(data []byte) (VerifiedBundle, error)

VerifyBundle checks a bundle with the neutral AAC Evidence Bundle verifier and then reads the evidence-layer content out of what verified. It never trusts the producer's own verification member.

Everything is read from the one decoded tree the verifier checked, by exact key, so the verifier and this reader can never see different members: a second copy of a member under a case-variant key ("Disclosures", "CHECKPOINT") is refused outright, and a member present only under a case-variant key is simply absent, exactly as the verifier sees it.

func VerifyBundleAnswer added in v0.2.0

func VerifyBundleAnswer(data []byte, keys ResponderKeys) (VerifiedBundle, error)

VerifyBundleAnswer checks an Evidence Bundle a holder disclosed to this requester (Book.Bundle) under the holder's pinned keys: the neutral bundle verifier must pass every claim, the anchor must be a checkpoint signed by keys.Checkpoint, and every witness receipt carried on it must verify against that checkpoint under the requester's own witness directory. A bundle is never the canonical Artifact of an evidence request; this is the separate disclosure path (profile §6.6).

func (VerifiedBundle) Covers

func (v VerifiedBundle) Covers(seq uint64) bool

Covers reports whether the bundle proves seq is inside its authenticated interval.

func (VerifiedBundle) FullyVerified

func (v VerifiedBundle) FullyVerified() error

FullyVerified returns nil only when all three claims passed and every record's capsule verified. VerifyBundle accepts a bundle whose claims are "withheld" or "unverified" (nothing in it is false); a caller that treats the bundle as proof of what it answers must also require this.

type WindowLimiter added in v0.2.0

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

WindowLimiter allows each requester at most N requests in any window of Window. Unauthenticated callers share the one "" bucket.

func NewWindowLimiter added in v0.2.0

func NewWindowLimiter(n int, window time.Duration) *WindowLimiter

NewWindowLimiter returns a limiter of n requests per window.

func (*WindowLimiter) Allow added in v0.2.0

func (l *WindowLimiter) Allow(requester string, now time.Time) bool

Allow records a request at now and reports whether it is within the limit.

type WithheldItem

type WithheldItem struct {
	RecordID          string         `json:"record_id"`
	Member            string         `json:"member,omitempty"`
	PayloadCommitment string         `json:"payload_commitment,omitempty"`
	Digest            string         `json:"digest"`
	RetentionState    RetentionState `json:"retention_state,omitempty"`
}

WithheldItem names material committed but not carried, always with its digest.

type WitnessRow added in v0.1.1

type WitnessRow struct {
	Name       string   `json:"name"`
	Endpoint   string   `json:"endpoint"`
	Binding    string   `json:"binding"`
	KeyIDs     []string `json:"key_ids"`
	PublicKeys []string `json:"public_keys"`
}

WitnessRow is one row of a witness directory, in capsule-emit's witnesses.json format: the witness's endpoint, its binding (cll when absent) and its keys. A key id is a raw Ed25519 key in hex, or the SHA-256 of a DER key listed in public_keys. Other row fields are read past.

func ParseWitnessDirectory added in v0.1.1

func ParseWitnessDirectory(raw []byte) ([]WitnessRow, error)

ParseWitnessDirectory reads a witness directory: {"witnesses": [rows]} or a bare array of rows.

Directories

Path Synopsis
Package adapter defines the interface every foreign-evidence adapter implements, and the bridge from its per-property results to a requirement's sufficiency and verdict.
Package adapter defines the interface every foreign-evidence adapter implements, and the bridge from its per-property results to a requirement's sufficiency and verdict.
x402
Package x402 is the evidencebook adapter for x402 payments, implementing the x402 adapter declaration v0 (agent-action-capsule spec/adapters/x402-v0.md) as ruled for its first implementation.
Package x402 is the evidencebook adapter for x402 payments, implementing the x402 adapter declaration v0 (agent-action-capsule spec/adapters/x402-v0.md) as ruled for its first implementation.
capsulectl module
cmd
evidencebook command
Command evidencebook runs evidencebook's foreign-evidence adapters.
Command evidencebook runs evidencebook's foreign-evidence adapters.
report module
test
interop/answer command
Command answer is a test responder for anyone checking evidencebook with their own verifier (docs/THIRD-PARTY-VERIFIER.md).
Command answer is a test responder for anyone checking evidencebook with their own verifier (docs/THIRD-PARTY-VERIFIER.md).
interop/bundle command
Command bundle writes an Evidence Bundle and a signed refusal produced by a fresh book, for verification by other implementations.
Command bundle writes an Evidence Bundle and a signed refusal produced by a fresh book, for verification by other implementations.
interop/capsules command
Command capsules writes every record capsule a fresh book seals when its records carry each link type, and when it bundles them, as one JSON array for the producer-side registry conformance check (AAC agent_action_capsule.registry_conformance).
Command capsules writes every record capsule a fresh book seals when its records carry each link type, and when it bundles them, as one JSON array for the producer-side registry conformance check (AAC agent_action_capsule.registry_conformance).
interop/personal-history command
Command personal-history produces the positive run of the Personal-Agent History Profile v0 conformance vectors (spec/personal-agent-history-profile-v0.md §6.4) with an IP responder: evidencebook's Book.Respond, unmodified.
Command personal-history produces the positive run of the Personal-Agent History Profile v0 conformance vectors (spec/personal-agent-history-profile-v0.md §6.4) with an IP responder: evidencebook's Book.Respond, unmodified.
interop/responder command
Command responder answers the responder-side requests of the evidence interoperability profile's conformance vectors with a fresh book, and writes every request and reply as carried, for checking by an independent verifier (test/interop/python-profile/verify_responder.py runs the AAC reference verifier over them).
Command responder answers the responder-side requests of the evidence interoperability profile's conformance vectors with a fresh book, and writes every request and reply as carried, for checking by an independent verifier (test/interop/python-profile/verify_responder.py runs the AAC reference verifier over them).
interop/verify command
Command verify checks a bundle produced by another implementation with evidencebook.VerifyBundle, and requires it to be fully verified: all three claims pass, the checkpoint is authenticated, and every record's capsule verifies.
Command verify checks a bundle produced by another implementation with evidencebook.VerifyBundle, and requires it to be fully verified: all three claims pass, the checkpoint is authenticated, and every record's capsule verifies.

Jump to

Keyboard shortcuts

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