evidencebook

package module
v0.12.2 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: Apache-2.0 Imports: 51 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@v0.9.0

Guide

docs/GUIDE.md walks the SDK as four paths: join the loop, seal a Result, build a Report, and serve a History. Each path has a runnable Example on a corpus vector. VECTORS.md lists the vector sets this repository holds and where each comes from.

Use

store, _ := evidencebook.OpenFileStore("book/records")
substrate, _ := evidencebook.OpenCLL("book/cll.jsonl", "orders-log", checkpointKey)
signer, _ := evidencebook.NewEd25519Signer(recordKey)
// Payload bytes live in an artifact store (capsule-emit's artifact.Store
// contract); this is its JSONL backend, trusting the book's signer.
originals, _ := evidencebook.OpenOriginalsFile(ctx, "artifacts.jsonl", "orders", signer.PublicKey())

book, err := evidencebook.Open(ctx, evidencebook.Config{
	BookID: "orders", Operator: "example-operator",
	Store: store, Substrate: substrate, Originals: originals, 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 and evidence-interop/1 (agent-action-capsule spec/interop-profile-v0.md and spec/interop-profile-v1.md), over the request map of draft-mih-agent-evidence-request-00, which -01 and -02 accept unchanged. A request naming no profile is answered under /0; the envelope names the profile the request asked for. 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

The ACP adapter (adapt acp) reads the Agentic Commerce Protocol's checkout session, order and delegated payment token. ACP signs none of them, so it reports possession of the exact octets and never a native PASS.

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. It does the same for a run that files each step under correlation.exchange_id, as capsule-cli#264's deal steps are filed (-correlated), and the History built from that run passes the same 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.
  • Python: the capsule-evidencebook package in this repository (python/, imported as evidencebook) implements the book and the evidence request interaction on both sides of it: asking, receiving and responding, with the same records, checkpoints and reply octets as this module. It is not yet published.
  • Parity vectors shared across implementations, all checked in CI:
    • schemas/vendor/epistemic-types.json: the epistemic type value set (TestEpistemicTypeThreeWayParity);
    • schemas/vendor/close-v1.json: agent-action-capsule's close/v1 schema at 201f4df, pinned by SHA-256, which every Close Book.Close seals validates against (TestCloseSealsTheCloseV1Body);
    • 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.

The SDK guide, https://github.com/action-state-group/evidencebook/blob/main/docs/GUIDE.md, walks this package as four paths; each has a runnable Example here on a corpus vector.

Example (JoinTheLoop)

Path 0, join the loop: record an action, ask another book for evidence, verify the answer, then check your own node as a stranger would see it.

The request is the request draft's vector pos-derivation-history-card (testdata/evidence-request/request.json): the public history card of a book's full history. Its expected_pin names the vector's own book, so the requester asks instead for any checkpoint of at least one entry.

package main

import (
	"context"
	"crypto/ed25519"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"time"

	"github.com/action-state-group/agent-action-capsule/go/evidencerequest"
	"github.com/action-state-group/evidencebook"
)

// node is one party's book with the keys a counterparty pins for it.
type node struct {
	book *evidencebook.Book
	keys evidencebook.ResponderKeys
}

// openNode opens a book in dir with keys derived from seed. Real deployments
// load their keys from storage; fixed seeds keep the output stable.
func openNode(ctx context.Context, dir, id string, seed byte) node {
	key := func(b byte) ed25519.PrivateKey {
		s := make([]byte, ed25519.SeedSize)
		for i := range s {
			s[i] = b + byte(i)
		}
		return ed25519.NewKeyFromSeed(s)
	}
	recordKey, checkpointKey := key(seed), key(seed+100)
	store, err := evidencebook.OpenFileStore(filepath.Join(dir, "records"))
	if err != nil {
		log.Fatal(err)
	}
	substrate, err := evidencebook.OpenCLL(filepath.Join(dir, "cll.jsonl"), id+"-log", checkpointKey)
	if err != nil {
		log.Fatal(err)
	}
	signer, err := evidencebook.NewEd25519Signer(recordKey)
	if err != nil {
		log.Fatal(err)
	}
	originals, err := evidencebook.OpenOriginalsFile(ctx, filepath.Join(dir, "originals.jsonl"), id, signer.PublicKey())
	if err != nil {
		log.Fatal(err)
	}
	now := time.Date(2026, 10, 27, 12, 0, 0, 0, time.UTC)
	book, err := evidencebook.Open(ctx, evidencebook.Config{
		BookID: id, Operator: id + "-operator",
		Store: store, Substrate: substrate, Originals: originals, Signer: signer,
		Now: func() time.Time { return now },
	})
	if err != nil {
		log.Fatal(err)
	}
	return node{book: book, keys: evidencebook.ResponderKeys{
		Signer:     evidencebook.KeyID(signer),
		Checkpoint: hex.EncodeToString(checkpointKey.Public().(ed25519.PublicKey)),
	}}
}

// requestCase is one case of the request draft's request.json corpus.
type requestCase struct {
	ID          string `json:"id"`
	RequestJSON string `json:"request_json"`
	Expect      struct {
		WellFormed bool   `json:"well_formed"`
		Reason     string `json:"reason"`
	} `json:"expect"`
}

func requestCases() []requestCase {
	data, err := os.ReadFile("testdata/evidence-request/request.json")
	if err != nil {
		log.Fatal(err)
	}
	var corpus struct {
		Cases []requestCase `json:"cases"`
	}
	if err := json.Unmarshal(data, &corpus); err != nil {
		log.Fatal(err)
	}
	return corpus.Cases
}

func requestCaseByID(id string) requestCase {
	for _, c := range requestCases() {
		if c.ID == id {
			return c
		}
	}
	log.Fatalf("no request case %s", id)
	return requestCase{}
}

func main() {
	ctx := context.Background()
	dir, err := os.MkdirTemp("", "evidencebook-example")
	if err != nil {
		log.Fatal(err)
	}
	defer os.RemoveAll(dir)
	alice := openNode(ctx, filepath.Join(dir, "alice"), "alice", 1)
	bob := openNode(ctx, filepath.Join(dir, "bob"), "bob", 2)
	defer alice.book.Release()
	defer bob.book.Release()

	// record: seal one action into alice's book and checkpoint it.
	if _, err := alice.book.Append(ctx, evidencebook.Entry{
		RecordType:    "observation",
		EpistemicType: evidencebook.ObservedEvent,
		SubjectRef:    "order-17",
		Payloads:      [][]byte{[]byte(`{"status":"approved"}`)},
	}); err != nil {
		log.Fatal(err)
	}
	if _, err := alice.book.Checkpoint(ctx); err != nil {
		log.Fatal(err)
	}

	// request: bob reads the vector's request map and records that he asks.
	vector := requestCaseByID("pos-derivation-history-card")
	parsed := evidencerequest.ParseRequest(evidencebook.Message{Octets: []byte(vector.RequestJSON), MediaType: evidencebook.MediaTypeJSON})
	if parsed.Reason != "" {
		log.Fatal(parsed.Reason)
	}
	req := parsed.Request
	one := uint64(1)
	req.Coverage = evidencebook.Coverage{MinFreshness: &evidencebook.Freshness{Size: &one}}
	sent, err := bob.book.Request(ctx, req, "alice")
	if err != nil {
		log.Fatal(err)
	}

	// alice answers bob as a stranger: no transport authentication.
	policy := evidencebook.DefaultSharePolicy()
	reply, _, err := alice.book.Respond(ctx, sent.Message(), evidencebook.RespondOptions{Policy: policy})
	if err != nil {
		log.Fatal(err)
	}

	// verify: bob checks the reply under alice's pinned keys and records it.
	received, err := bob.book.RecordResponse(ctx, sent.RecordID, reply.Message, alice.keys)
	if err != nil {
		log.Fatal(err)
	}
	var outcome evidencebook.ResponseStatement
	if err := json.Unmarshal(received.Header.Statement, &outcome); err != nil {
		log.Fatal(err)
	}
	fmt.Println("subject:", req.Subject.Kind, "derivation:", req.Derivation)
	fmt.Println("outcome:", outcome.Outcome)

	// doctor --probe: alice asks her own responder through the public path.
	findings, err := alice.book.Doctor(ctx, evidencebook.DoctorOptions{
		Policy: policy,
		Probe: func(ctx context.Context, request evidencebook.Message) (evidencebook.Message, error) {
			reply, _, err := alice.book.Respond(ctx, request, evidencebook.RespondOptions{Policy: policy})
			return reply.Message, err
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	for _, f := range findings {
		fmt.Printf("%s: %s\n", f.Check, f.State)
	}
}
Output:
subject: full_history derivation: history_card/1
outcome: artifact
self_attested: self_attested
controller_binding: unbound
checkpoint: present
witness: unwitnessed
not_checked: none
unsupported: unsupported
sharing: on
policy_in_commitment: NOT_CHECKED
stranger_view: answered
identified_view: answered
probe_checkpoints: match
probe_history_card: match

Index

Examples

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 (
	WitnessVerified   = "VERIFIED"
	WitnessNotChecked = "NOT_CHECKED"
	WitnessInvalid    = "INVALID"
)

The states of a receipt's check (Cadence.Witnessed): it verified under the configured witness directory; it was not checked (its witness has no row or no usable key there, or AAC's verifier withholds it); or it was checked and rejected.

View Source
const (
	HalfMemberDealID             = "deal_id"
	HalfMemberBookID             = "book_id"
	HalfMemberRecordedAt         = "recorded_at"
	HalfMemberCommitAlg          = "commit_alg"
	HalfMemberAmountCommitment   = "amount_commitment"
	HalfMemberCurrencyCommitment = "currency_commitment"
)

The six abstract half members a half mapping fills (DR §4.1).

View Source
const (
	SetComplete  = "COMPLETE"
	SetUndecided = "UNDECIDED"
	SetNotShown  = "NOT_SHOWN"
)

Set statuses (DR §6.1).

View Source
const (
	DoctorSelfAttested      = "self_attested"
	DoctorControllerBinding = "controller_binding"
	DoctorCheckpoint        = "checkpoint"
	DoctorWitnessed         = "witness"
	DoctorNotChecked        = "not_checked"
	DoctorUnsupported       = "unsupported"
	DoctorSharing           = "sharing"
	DoctorPolicyCommitment  = "policy_in_commitment"
	DoctorStrangerView      = "stranger_view"
	DoctorIdentifiedView    = "identified_view"
	DoctorProbeCheckpoints  = "probe_checkpoints"
	DoctorProbeHistoryCard  = "probe_history_card"
)

Doctor checks, one finding each, in the order Doctor reports them.

View Source
const (
	DoctorStateSelfAttested = "self_attested"
	DoctorStateUnbound      = "unbound"
	DoctorStateNone         = "none"
	DoctorStatePresent      = "present"
	DoctorStateMissing      = "missing"
	DoctorStateWitnessed    = "witnessed"
	DoctorStateUnwitnessed  = "unwitnessed"
	DoctorStateNotChecked   = "NOT_CHECKED"
	DoctorStateUnsupported  = "unsupported"
	DoctorStateOn           = "on"
	DoctorStateOff          = "off"
	DoctorStateAnswered     = "answered"
	DoctorStateMatch        = "match"
	DoctorStateMismatch     = "mismatch"
)

Doctor finding states. NOT_CHECKED means what it means everywhere: the check was not run, never that it passed or failed.

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
	ProfileIDv1           = evidencerequest.ProfileIDv1
	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, profiles evidence-interop/0 and /1); these names keep evidencebook's API.

View Source
const (
	RequestDraft01 = "draft-mih-agent-evidence-request-01"
	RequestDraft02 = "draft-mih-agent-evidence-request-02"
)

The later request drafts whose request map the book also accepts, listed in its manifest beside RequestDraft (profile v1 §11.4.2): -01 adds only categories, which the book ignores (P-64), and -02 adds no member (P-65).

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 (
	// MaxReplyBytes bounds a reply's octets, and an Evidence Bundle's. It
	// is the most a record's originals may hold (capsule-emit's artifact
	// record limit), so a larger reply could never be recorded anyway.
	MaxReplyBytes = 8 << 20
	// MaxReplyDepth bounds how deeply a JSON reply, its artifact or a bundle
	// nests arrays and objects; the outermost value is depth 1. It is no
	// looser than the agent-action-capsule decoder's own bound.
	MaxReplyDepth = 32
	// MaxReplyItems bounds each list an answer carries: its verification
	// entries, and the artifact's checkpoints, history entries or records
	// (a bundle's records too). It is the responder's own default cap
	// (DefaultMaxAnswerItems).
	MaxReplyItems = DefaultMaxAnswerItems
	// MaxReplyReceipts bounds the witness receipts a reply carries in
	// witness_receipts, or a bundle's checkpoint in its witnesses member.
	MaxReplyReceipts = 64
)

The requester's stated limits on what it will check. A hostile responder can shape an answer to make checking it expensive: an oversized reply, a deeply nested tree, thousands of checkpoints whose signatures and proofs must each be checked, or a pile of witness receipts. Every limit is checked before the work it bounds, and exceeding one is reported naming it, never a crash or a timeout.

Where a limit falls on octets nothing has authenticated yet (the reply's size and nesting, and the unsigned witness_receipts carrier), exceeding it refuses the reply and records nothing, so the request stays open: an unauthenticated message must not foreclose the real answer's outcome. Where it falls on what the responder signed (the artifact and its verification entries), the envelope signature (one Ed25519 check over a bounded body) and the artifact's digest are checked first, so the limit falls only on signed content, and exceeding it records the answer as received and failed, naming the limit, before any checkpoint signature, proof or receipt is checked.

View Source
const (
	Witnessed   = "witnessed"
	Unwitnessed = "unwitnessed"
)

Witness standing of a verified artifact, recorded in its response statement: witnessed only when a receipt from a witness in the requester's own directory covers the anchor checkpoint. A chain that only verifies against its own signatures could be a private fork, and reads unwitnessed.

View Source
const CadenceDepth = 16

CadenceDepth is the tree's fixed depth: every path is 16 hashes, and a tick holds at most 2^16 - 1 logs beside its filler.

View Source
const CadenceExtension = "x-cadence-witness/v0"

CadenceExtension is the bundle extension a deal's cadence chain travels in, capsule-cli's name for it. Bundles from before carried it as "cadence-witness/v0" or "x-deal-cadence-v0"; verifiers still read those.

View Source
const CloseRecordVersion = "close/v1"

CloseRecordVersion is the record_version of the Close body Book.Close seals: agent-action-capsule's close/v1 (schemas/judge/close-v1.json).

View Source
const CommitAlgNonce256 = "sha256-jcs-nonce256"

CommitAlgNonce256 names the salted per-field commitment a header's field_commitments use: agent-action-capsule spec/presentation-contract-v0.md §7.2, the construction capsule-cli's deal records already declare under the same identifier, and the one evidencebook#44 rules a History's deal-level commitments use:

commitment = lowercase_hex(SHA-256(JCS({"nonce": N, "text": T})))

N is 64 lowercase hex characters encoding 32 fresh CSPRNG bytes per committed text; T is the exact text, unnormalized. That is the Disclosure Envelope's DE-3 computation (JSON-DIGEST) applied to the opening object {nonce, text}, never to the bare text: without N a guess at T cannot be tested.

View Source
const DealReconcileContractRef = "ec:deal-reconcile@1"

DealReconcileContractRef is the contract_ref a claim under this contract carries.

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 DerivationStandardHistory = standardhistory.Derivation

DerivationStandardHistory is the registered token standard_history/1 (agent-action-capsule spec/standard-history-v0.md, cited as SH): a card, as of one anchor, that counts the holder's deals in the window its policy sets. It is recipient-free: every requester answered gets the same bytes.

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. It proves possession of those bytes only (FR-20). Its witness property is NOT_CHECKED: the receipt registers a record identity, a statement AAC's witness verifier (go/witness) defines no binding for, so nothing here can check it and it never counts as witnessed. Only a cadence checkpoint receipt that verifies does (Cadence.Witnessed). 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 RecordHeaderMember = "evidence_record_header"

RecordHeaderMember is the top-level Capsule member through which a capsule sealed by the book's caller (AppendCapsule) carries its own record header: the header's JSON, exactly as the book canonicalized it. capsule_id covers it like every member, so the capsule commits its header without a separate digest, and a reader of the capsule reads the header in it. A record the book seals itself (Append) commits its header as the capsule's agent_input_digest instead, and carries no such member.

View Source
const RecordTypeEvidenceResult = "evidence_result"

RecordTypeEvidenceResult is a sealed Evidence Result v0. SealResult names it; the caller's add writes it.

View Source
const RecordTypeRetentionCommitment = "retention_commitment"

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

View Source
const ShelfVersion = 1

ShelfVersion is the shelf file version this implementation writes and the only one it opens (shelf_meta.version).

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.

View Source
const WitnessReceiptsMember = "witness_receipts"

WitnessReceiptsMember is the reply member that carries witness receipts beside the envelope: an array of {checkpoint, witness}, checkpoint the anchor digest a receipt is for and witness a checkpoint.witnesses entry. It is not part of the interop profile and nothing signs it; a receipt authenticates itself, so it can only ever add "witnessed".

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")
	// ErrReleased reports a write to a book, or a call on a shelf, after it
	// was released.
	ErrReleased = errors.New("evidencebook: released")
)

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

SubjectForms lists the six forms in code-point order.

Functions

func DeriveStandardHistory added in v0.11.0

func DeriveStandardHistory(holderKind string, asOf standardhistory.AsOf, policy standardhistory.Policy, deals []standardhistory.Deal) ([]byte, error)

DeriveStandardHistory is the standard_history/1 card (SH §4) as of asOf, in its JCS octets: the card a Book answers and the card a host derives over a shelf as of a cadence tick (Cadence.StandardHistoryAnchor). Before it returns, the card is checked against the very inputs it was derived from (SH §6), so inputs that make no standard card are ErrInvalid, never a card.

func DerivedFillers added in v0.5.0

func DerivedFillers(seed []byte, count uint64, used map[uint64]bool) (map[uint64][]byte, error)

DerivedFillers returns fillers 1..count of a tick, by position. Filler i is SHA-256(0x03 ‖ n_i) with n_i = SHA-256(seed ‖ uint64be(i)); its position is the first unused one among, for attempt a = 0, 1, …, uint64be(SHA-256(seed ‖ "pos" ‖ uint64be(i) ‖ uint32be(a))[0:8]) mod 2^16, after the logs' leaves and filler 0 (used) and the fillers before it. used is updated. The same seed, count and used positions give the same fillers, so a tick's tree is rebuilt from what it stored.

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 MigratePayloadDir added in v0.5.0

func MigratePayloadDir(ctx context.Context, store Store, originals ArtifactStore, dir string) (int, error)

MigratePayloadDir moves the payload bytes an earlier evidencebook kept in a payload directory (one file per payload, named by its SHA-256) into the artifact store, one artifact.Record per record that commits payloads. It reads the records from store and changes none of them: no header, record id, log entry or checkpoint moves, so every existing proof still holds. A record whose originals are already in the artifact store is skipped, so an interrupted migration is resumed by running it again. Retention is now per record, folded as Retention folds it: a record whose latest lifecycle state is DELETED is not stored, even when a file survived because another record shares the digest (the book reads it as DELETED before it looks for originals), and a payload an earlier per-payload deletion named is left out of a record that stays readable. A payload whose file is missing is left out of the record, so reading it reports the store does not hold it rather than claiming it was never kept. It returns how many records it stored.

The directory itself is left for the caller to remove once the call returns without error.

func ReadClose added in v0.11.0

func ReadClose(h Header) (v1 *CloseStatement, legacy *LegacyCloseStatement, err error)

ReadClose reads a Close record's body, dispatching on record_version: a close/v1 body fills v1, a body without record_version (a Close sealed before close/v1) fills legacy, and any other version, null included, is refused. A v1 body must validate against the close/v1 schema and agree with its own header: record_id is the header's book_id#seq, closed_at its committed_at, the header's epistemic_type producer_claim, and the period's start before its end.

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 ReconcileHalvesWith added in v0.5.0

func ReconcileHalvesWith(a, b HalfSet, check ContentCheck) ([]PairResult, Tallies)

ReconcileHalvesWith is ReconcileHalves with a three-way content check: on a covered, trusted, correlated pair, Agree is MATCHED, Disagree is CONFLICTING and Undecided is INSUFFICIENT. The precedence is unchanged: a key conflict, then an uncovered half (INSUFFICIENT), then an untrusted half (UNRESOLVED), then the content check.

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.

func VerifyOpening added in v0.5.0

func VerifyOpening(commitment string, o Opening) bool

VerifyOpening reports whether o opens commitment: its nonce is well formed and SHA-256(JCS({nonce, text})) equals commitment, compared as lowercase hex strings. It never errors; a malformed opening does not open anything.

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 ArtifactStore added in v0.5.0

type ArtifactStore interface {
	Put(ctx context.Context, record artifact.Record) error
	Get(ctx context.Context, id string) (artifact.Record, error)
	// Purge erases a record's present originals and keeps their digests.
	Purge(ctx context.Context, id string) error
}

ArtifactStore is where a book keeps its records' originals: the payload bytes a header commits by digest. It is capsule-emit's artifact store contract (artifact.Store) reduced to what the book calls, so any of its backends (jsonl, sqlite, mysql) serves. The store holds one artifact.Record per record that has originals, keyed by the record id: the record capsule, its Producer Envelope, and the originals. The store must trust the book's signer, since Put and Get verify the envelope signer against the store's trusted keys.

The header commits digests, never storage locations, and the store's per-original ContentSHA256 is the same SHA-256 the header commits, so an original is found by the digest its record commits. Each record keeps its own copy: two records committing identical bytes hold two copies, and destroying one record's originals never touches the other's.

Put and Purge must be durable when they return: the book stores a record only after its originals' Put returns, so a record that survives a crash has originals that survived it too. OpenOriginalsFile's store syncs its file; a host supplying its own store makes the same guarantee.

func OpenOriginalsFile added in v0.5.0

func OpenOriginalsFile(ctx context.Context, path, namespace string, trusted ...ed25519.PublicKey) (ArtifactStore, error)

OpenOriginalsFile opens, creating it when absent, the reference ArtifactStore: capsule-emit's JSONL artifact store at path, under namespace, trusting the given keys (the book's signer key among them). It suits a single writer, as the book is. The file is kept owner-only, and every Put and Purge is synced to stable storage before it returns.

func SyncedFile added in v0.5.0

func SyncedFile(store ArtifactStore, path string) ArtifactStore

SyncedFile makes a file-backed ArtifactStore durable as the book requires: after each successful Put or Purge it syncs the file at path and the directory holding it.

type AskOutcome added in v0.11.0

type AskOutcome string

AskOutcome is how the provider answered the request for one exchange.

const (
	// AskAnswered: a verified answer, with the records it carried.
	AskAnswered AskOutcome = "answered"
	// AskRefused: a verified, signed refusal, with its reason.
	AskRefused AskOutcome = "refused"
	// AskAbsent: nothing came back.
	AskAbsent AskOutcome = "absent"
	// AskFailed: something came back and did not verify.
	AskFailed AskOutcome = "failed"
)

type AskedExchange added in v0.11.0

type AskedExchange struct {
	Own     AskedHalf  `json:"own"`
	Outcome AskOutcome `json:"outcome"`
	// Covers is the caller's statement that the answer or refusal is made
	// at an anchor that would hold the provider's record of this exchange if
	// the provider had sealed it: the anchor postdates the exchange and every
	// record the provider sealed for it. Without it, an answer missing the
	// record, or a no_such_subject, may only mean the anchor is too old, so
	// the half is UNRESOLVED.
	Covers bool `json:"covers"`
	// Records holds what an AskAnswered answer carried.
	Records []AskedRecord `json:"records,omitempty"`
	// Reason holds an AskRefused refusal's reason, as signed.
	Reason string `json:"reason,omitempty"`
}

AskedExchange is one of the requester's own halves and what came back when it asked the provider for that exchange.

type AskedHalf added in v0.11.0

type AskedHalf struct {
	RecordID       string `json:"record_id"`
	RequestDigest  string `json:"request_digest"`
	ResponseDigest string `json:"response_digest"`
}

AskedHalf is one of the requester's own sealed halves of an exchange with the provider, named by the exchange's two digests. Those are what the ask names (the exchange binding `exchange-digests:<request>:<response>`) and what both halves of one exchange commit to. An exchange_id is not: each side's host assigns its own.

type AskedRecord added in v0.11.0

type AskedRecord struct {
	RecordID       string  `json:"record_id"`
	RequestDigest  string  `json:"request_digest"`
	ResponseDigest string  `json:"response_digest"`
	Seq            uint64  `json:"seq"`
	PrevSeq        *uint64 `json:"prev_seq"`
}

AskedRecord is one record a verified answer carried: the provider's half of an exchange with the requester, with its per-pair sequence number and the one before it (nil for the first record of the pair).

type AskedReport added in v0.11.0

type AskedReport struct {
	Verdict AskedVerdict  `json:"verdict"`
	Results []AskedResult `json:"results"`
	// Omitted names the requester's halves the provider confirmed it holds
	// no record of, in input order.
	Omitted []string `json:"omitted"`
	// Run is the numbering of the provider's matched records. A gapless run
	// says no sealed record of theirs was removed between the first and the
	// last; it says nothing about exchanges they never sealed, which only
	// Omitted shows.
	Run SeqRun `json:"run"`
}

AskedReport is the reconcile over one pair.

func ReconcileAsked added in v0.11.0

func ReconcileAsked(asked []AskedExchange) AskedReport

ReconcileAsked checks the provider's answers about a pair against the requester's own sealed halves of that pair, one ask per half, and names every half the provider confirmed it holds no record of (evidencebook#206 row 9: an exchange left out before sealing, whose answers still verify and number without a gap).

It trusts the caller's verification and does not repeat it: Outcome must be AskAnswered or AskRefused only for an answer whose signature, anchor and inclusion proofs the caller checked under the provider's key, Records must hold only records that answer proved, and Covers must be set only when the answer's anchor would hold the record had it been sealed. A half is OMITTED only on such a covering answer: a verified answer without the record, or a signed no_such_subject. A record matches a half when both its request and response digests are the half's; only the records of that half's own answer are candidates, and each record matches at most one half, so two exchanges with the same request and answer never both match one record. The matching is a maximum one, so how many halves are OMITTED never depends on the order of the input; which of several equal halves is, when there are fewer records than halves, does.

It works only on bilateral traffic: a half the requester never sealed cannot be asked about, so an exchange both sides left out stays invisible (Mesh-LLM/mesh-llm#1965 §6). The verdict strings are local results, never written into a sealed record or onto the wire.

type AskedResult added in v0.11.0

type AskedResult struct {
	State AskedState `json:"state"`
	// Own is the requester's half (its RecordID).
	Own string `json:"own"`
	// Record is the provider's record it matched (its RecordID), when LOGGED.
	Record string `json:"record,omitempty"`
	// Why says what decided OMITTED, REFUSED or UNRESOLVED.
	Why string `json:"why,omitempty"`
}

AskedResult is one half's reconcile result.

type AskedState added in v0.11.0

type AskedState string

AskedState is what one of the requester's own halves comes to after it asked the provider for that exchange (evidencebook#206 row 9).

const (
	// AskedLogged: a verified answer carried a record of the provider's that
	// correlates with the half.
	AskedLogged AskedState = "LOGGED"
	// AskedOmitted: the provider confirmed it holds no record of the
	// exchange. Either a verified answer that should have carried the record
	// carried none that correlates, or a verified refusal with the reason
	// no_such_subject.
	AskedOmitted AskedState = "OMITTED"
	// AskedRefused: the provider refused, verified and signed, with a reason
	// other than no_such_subject. It says nothing about whether the record
	// exists (a uniform policy_declined reads the same either way), but it is a
	// finding of its own: an honest provider does not refuse its counterparty
	// about their own exchange.
	AskedRefused AskedState = "REFUSED"
	// AskedUnresolved: nothing says either way: an absence, an answer that
	// failed verification, or an answer that cannot be about this exchange.
	AskedUnresolved AskedState = "UNRESOLVED"
)

type AskedVerdict added in v0.11.0

type AskedVerdict string

AskedVerdict is the reconcile's verdict over one pair. It is never COMPLETE: a remote answer is the provider's selection (#206 row 7), so the most the requester can say is that none of its own halves was left out.

const (
	// OmissionsFound: at least one half is AskedOmitted.
	OmissionsFound AskedVerdict = "OMISSIONS_FOUND"
	// NoOmissionFound: every half is AskedLogged.
	NoOmissionFound AskedVerdict = "NO_OMISSION_FOUND"
	// AskedInconclusive: no half is AskedOmitted and at least one is
	// AskedRefused or AskedUnresolved.
	AskedInconclusive AskedVerdict = "UNRESOLVED"
)

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, seals its header into a record capsule, stores the capsule and its payload bytes in the artifact store (one Put), 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) AppendCapsule added in v0.5.0

func (b *Book) AppendCapsule(ctx context.Context, entry Entry, originals []artifact.Artifact, seal CapsuleSealer) (Record, error)

AppendCapsule commits a capsule its caller seals itself as the record: the capsule is the record, its id the log entry, with no wrapper record around it. The book takes the next position under its writer lock, builds the header (payload_commitments are the SHA-256 of each present original, in order; one declared never retained is stored as declared and not committed), and calls seal with it there; the capsule must carry that header in RecordHeaderMember and be signed by the book's signer, or nothing is written. The capsule, its envelope and originals are then stored in the artifact store in one Put, the record in the store, and its id appended to the substrate, as Append does.

entry.Payloads must be empty: a caller-sealed record's originals are named, and may be bound to the capsule's own digests (a payload bound to agent_input_digest, say), so they are passed as originals.

Crash contract: the position exists only in memory until the record is stored. A crash before that leaves no record, and the next record takes the same position; the artifact store may then hold the abandoned capsule, which no log entry names. A crash after it is the pending-tail case of Append: the next Open commits the stored record at its position.

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) CheckpointAt added in v0.5.0

func (b *Book) CheckpointAt(ctx context.Context, at time.Time) (Checkpoint, error)

CheckpointAt is Checkpoint with the checkpoint's time given: a cadence cuts every log at the tick's time, coarsened to the minute, so no checkpoint says when within the minute its log grew.

func (*Book) CheckpointCovers added in v0.8.0

func (b *Book) CheckpointCovers(ctx context.Context, seq uint64) (bool, error)

CheckpointCovers reports whether the book's latest checkpoint covers seq.

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/v1 Close record: a closes link to every own record the reconciliation placed, the period, the window's counts by record type and its head, and, when a peer Close is named, the tallies and a cites link to that Close. 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) Doctor added in v0.8.0

func (b *Book) Doctor(ctx context.Context, opts DoctorOptions) ([]DoctorFinding, error)

Doctor inspects this book and returns a list of findings: what is self-attested, unwitnessed, NOT_CHECKED or unsupported; whether the signing key is bound to a controller; whether sharing is on and whether the policy is in a commitment; and what a stranger and an identified requester would receive. With opts.Probe it asks the node's own responder as a stranger and compares the answers with the advertised policy. Both subjects it asks are public under every policy, so a match shows what a stranger is served; it does not show what an identified requester is.

Doctor seals nothing and never forces a checkpoint. The identified view is computed from the policy, not asked over the wire: Respond seals a record for every authenticated requester.

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) Opening added in v0.5.0

func (b *Book) Opening(ctx context.Context, recordID, field string) (Opening, error)

Opening returns the opening of one field commitment of a record, read from the artifact store, when the record's retention state allows it. It is checked against the commitment the record's header carries.

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, keeping the reply's octets as the response record's payload (ReplyOctets reads them back). 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. The requester's limits (MaxReplyBytes and the rest) apply first: over one on the reply's unauthenticated octets, the reply is refused and the request stays open; over one on what the responder signed, the answer is received-and-failed naming the limit.

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.

The identifier binds the document only, so registering it again must not change what it answers: a registration that declares the same recipient and the same sets of forms and fields returns the same identifier and changes nothing, and one that declares anything else is ErrInvalid.

func (*Book) Release

func (b *Book) Release() error

Release closes the store, substrate and operational index. It is idempotent, and afterwards every write (Append, AppendCapsule, Checkpoint, SetRetention) refuses with ErrReleased.

func (*Book) ReplyOctets added in v0.5.0

func (b *Book) ReplyOctets(ctx context.Context, responseRecordID string) ([]byte, error)

ReplyOctets returns the reply a response record observed, as received, from the artifact store. It is the response record's one payload.

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) RequestSent added in v0.12.0

func (b *Book) RequestSent(ctx context.Context, request Message, responder string) (SentRequest, error)

RequestSent records a request that another tool composed and sent to responder, exactly as given: every member is kept, including those the request draft does not define (a deployment profile's audience or requester authentication, ER §3), and no nonce or profile is added. The octets must be a well-formed request (profile §6.1 steps 1 to 5) in JCS, the form a requester transmits JSON in (P-9), so the recorded digest is the one the responder signs its reply over. A nonce this book already used is refused. RecordResponse and RecordAbsence then work on the record as they do on one Request made.

func (*Book) ResolvePayload

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

ResolvePayload returns one payload of one record, read from the artifact store, when the record's 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).

Respond answers from a snapshot of the log and holds the book's lock only to take it, to issue an anchor an authenticated requester's freshness floor needs, and to seal the evidence_request_answered record. Answering, however many requests arrive at once, never holds Append, Checkpoint or any other writer for longer than that (evidencebook#208).

Example

Path 3, serve a History: Respond answers request octets as received, and a History is served as a derivation the holder registers for one recipient.

Every case of the request draft's corpus (testdata/evidence-request/request.json) that is not well formed gets a signed refusal with exactly the reason the vector states. The History is the definition for-alice from testdata/derivation/vectors.json: its identifier binds the document alone, so this book derives the vector's identifier, and only its recipient is answered.

package main

import (
	"context"
	"crypto/ed25519"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"time"

	"github.com/action-state-group/evidencebook"
)

// node is one party's book with the keys a counterparty pins for it.
type node struct {
	book *evidencebook.Book
	keys evidencebook.ResponderKeys
}

// openNode opens a book in dir with keys derived from seed. Real deployments
// load their keys from storage; fixed seeds keep the output stable.
func openNode(ctx context.Context, dir, id string, seed byte) node {
	key := func(b byte) ed25519.PrivateKey {
		s := make([]byte, ed25519.SeedSize)
		for i := range s {
			s[i] = b + byte(i)
		}
		return ed25519.NewKeyFromSeed(s)
	}
	recordKey, checkpointKey := key(seed), key(seed+100)
	store, err := evidencebook.OpenFileStore(filepath.Join(dir, "records"))
	if err != nil {
		log.Fatal(err)
	}
	substrate, err := evidencebook.OpenCLL(filepath.Join(dir, "cll.jsonl"), id+"-log", checkpointKey)
	if err != nil {
		log.Fatal(err)
	}
	signer, err := evidencebook.NewEd25519Signer(recordKey)
	if err != nil {
		log.Fatal(err)
	}
	originals, err := evidencebook.OpenOriginalsFile(ctx, filepath.Join(dir, "originals.jsonl"), id, signer.PublicKey())
	if err != nil {
		log.Fatal(err)
	}
	now := time.Date(2026, 10, 27, 12, 0, 0, 0, time.UTC)
	book, err := evidencebook.Open(ctx, evidencebook.Config{
		BookID: id, Operator: id + "-operator",
		Store: store, Substrate: substrate, Originals: originals, Signer: signer,
		Now: func() time.Time { return now },
	})
	if err != nil {
		log.Fatal(err)
	}
	return node{book: book, keys: evidencebook.ResponderKeys{
		Signer:     evidencebook.KeyID(signer),
		Checkpoint: hex.EncodeToString(checkpointKey.Public().(ed25519.PublicKey)),
	}}
}

// requestCase is one case of the request draft's request.json corpus.
type requestCase struct {
	ID          string `json:"id"`
	RequestJSON string `json:"request_json"`
	Expect      struct {
		WellFormed bool   `json:"well_formed"`
		Reason     string `json:"reason"`
	} `json:"expect"`
}

func requestCases() []requestCase {
	data, err := os.ReadFile("testdata/evidence-request/request.json")
	if err != nil {
		log.Fatal(err)
	}
	var corpus struct {
		Cases []requestCase `json:"cases"`
	}
	if err := json.Unmarshal(data, &corpus); err != nil {
		log.Fatal(err)
	}
	return corpus.Cases
}

func main() {
	ctx := context.Background()
	dir, err := os.MkdirTemp("", "evidencebook-example")
	if err != nil {
		log.Fatal(err)
	}
	defer os.RemoveAll(dir)
	holder := openNode(ctx, dir, "holder", 1)
	defer holder.book.Release()
	if _, err := holder.book.Append(ctx, evidencebook.Entry{
		RecordType: "observation", EpistemicType: evidencebook.ObservedEvent,
		SubjectRef: "order-17", Payloads: [][]byte{[]byte(`{"status":"approved"}`)},
	}); err != nil {
		log.Fatal(err)
	}
	if _, err := holder.book.Checkpoint(ctx); err != nil {
		log.Fatal(err)
	}
	policy := evidencebook.DefaultSharePolicy()
	respond := func(octets []byte, authenticated string) evidencebook.Reply {
		reply, _, err := holder.book.Respond(ctx, evidencebook.Message{Octets: octets, MediaType: evidencebook.MediaTypeJSON},
			evidencebook.RespondOptions{AuthenticatedRequester: authenticated, Policy: policy})
		if err != nil {
			log.Fatal(err)
		}
		return reply
	}

	matched, malformed := 0, 0
	for _, c := range requestCases() {
		if c.Expect.WellFormed {
			continue
		}
		malformed++
		octets := []byte(c.RequestJSON)
		reply := respond(octets, "")
		if reply.Refusal == nil {
			log.Fatalf("%s: answered, want refusal %s", c.ID, c.Expect.Reason)
		}
		// The refusal is signed over the digest of the octets as received.
		digest := sha256.Sum256(octets)
		if err := reply.Refusal.VerifyFor(holder.keys.Signer, hex.EncodeToString(digest[:])); err != nil {
			log.Fatalf("%s: %v", c.ID, err)
		}
		if reply.Refusal.Reason == c.Expect.Reason {
			matched++
		}
	}
	fmt.Printf("%d of %d malformed cases refused with the vector's reason\n", matched, malformed)

	data, err := os.ReadFile("testdata/derivation/vectors.json")
	if err != nil {
		log.Fatal(err)
	}
	var corpus struct {
		Definitions []struct {
			Name      string                     `json:"name"`
			Document  string                     `json:"document"`
			ID        string                     `json:"id"`
			Recipient string                     `json:"recipient"`
			Forms     []evidencebook.SubjectKind `json:"forms"`
			Fields    []string                   `json:"fields"`
		} `json:"definitions"`
	}
	if err := json.Unmarshal(data, &corpus); err != nil {
		log.Fatal(err)
	}
	for _, d := range corpus.Definitions {
		if d.Name != "for-alice" {
			continue
		}
		id, err := holder.book.RegisterDerivation(evidencebook.DerivationDefinition{
			Document: []byte(d.Document), Recipient: d.Recipient, Forms: d.Forms, Fields: d.Fields,
		})
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println("derivation id matches the vector:", id == d.ID)

		one := uint64(1)
		history, err := evidencebook.EncodeRequest(evidencebook.EvidenceRequest{
			Subject:    evidencebook.Subject{Kind: evidencebook.SubjectCorrelation, Correlation: "order-17"},
			Coverage:   evidencebook.Coverage{MinFreshness: &evidencebook.Freshness{Size: &one}},
			Derivation: id,
			Profile:    evidencebook.ProfileID,
		}, evidencebook.MediaTypeJSON)
		if err != nil {
			log.Fatal(err)
		}
		for _, requester := range []string{d.Recipient, "bob", ""} {
			reply := respond(history, requester)
			outcome := "artifact"
			if reply.Refusal != nil {
				outcome = reply.Refusal.Reason
			}
			fmt.Printf("history for %q: %s\n", requester, outcome)
		}
	}
}
Output:
22 of 22 malformed cases refused with the vector's reason
derivation id matches the vector: true
history for "alice": artifact
history for "bob": not_authorized
history for "": not_authorized

func (*Book) Retention

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

Retention returns the record's current retention state (Evidence Layer §6.1): the state its header committed, folded forward through every lifecycle record that cites it, in log order. While a retention commitment this book issued covers the record and has not expired (CommitRetention), an AVAILABLE or PARTIAL record reads as LEGAL_HOLD: the hold blocks deletion and changes no resolvability. A WITHHELD record stays WITHHELD under a hold, which still blocks its deletion. A record that commits no payload and no field has no retention state and is refused.

func (*Book) SealResult added in v0.8.0

func (b *Book) SealResult(ctx context.Context, statement json.RawMessage, subject string, links []Link, reuse func() (Record, bool, error), add func(Entry) (Record, error)) (sealed Record, already bool, checkpoint uint64, err error)

SealResult seals statement, an Evidence Result v0 document the caller has already checked, as one RecordTypeEvidenceResult record about subject (the one contract the Result reports), with links, and makes sure a checkpoint covers it so a bundle can be built on it at once.

reuse reports a record an earlier run sealed for the same Result; when it finds one, nothing is appended. add appends the entry: Book.Append for a book that seals its own records, or AppendCapsule for a caller that seals Capsules itself. A checkpoint is cut whenever none covers the record yet: on the first seal, and on a repeat whose earlier run sealed the record but failed before its checkpoint. checkpoint is that checkpoint's size, or 0 when none was cut.

A failure after add committed the record (an index or automatic checkpoint failure) returns the record with the error, so the caller never loses its id. Errors from reuse and add are returned as they are.

It is not atomic: reuse, add and the checkpoint run one after another, so callers that may seal the same Result concurrently must serialize.

Example

Path 1, seal a Result: Terms Packs and their evaluation are outside this module (docs/GUIDE.md links where they live). A book seals the Result an evaluator produced and checkpoints it, so a bundle can be built on it.

The Result is the expected Evidence Result of the Deal Reconcile Contract's vector pair-matched (testdata/deal-reconcile-v0/vectors.json), written from the specification and never from an implementation.

package main

import (
	"context"
	"crypto/ed25519"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"time"

	"github.com/action-state-group/evidencebook"
)

// node is one party's book with the keys a counterparty pins for it.
type node struct {
	book *evidencebook.Book
	keys evidencebook.ResponderKeys
}

// openNode opens a book in dir with keys derived from seed. Real deployments
// load their keys from storage; fixed seeds keep the output stable.
func openNode(ctx context.Context, dir, id string, seed byte) node {
	key := func(b byte) ed25519.PrivateKey {
		s := make([]byte, ed25519.SeedSize)
		for i := range s {
			s[i] = b + byte(i)
		}
		return ed25519.NewKeyFromSeed(s)
	}
	recordKey, checkpointKey := key(seed), key(seed+100)
	store, err := evidencebook.OpenFileStore(filepath.Join(dir, "records"))
	if err != nil {
		log.Fatal(err)
	}
	substrate, err := evidencebook.OpenCLL(filepath.Join(dir, "cll.jsonl"), id+"-log", checkpointKey)
	if err != nil {
		log.Fatal(err)
	}
	signer, err := evidencebook.NewEd25519Signer(recordKey)
	if err != nil {
		log.Fatal(err)
	}
	originals, err := evidencebook.OpenOriginalsFile(ctx, filepath.Join(dir, "originals.jsonl"), id, signer.PublicKey())
	if err != nil {
		log.Fatal(err)
	}
	now := time.Date(2026, 10, 27, 12, 0, 0, 0, time.UTC)
	book, err := evidencebook.Open(ctx, evidencebook.Config{
		BookID: id, Operator: id + "-operator",
		Store: store, Substrate: substrate, Originals: originals, Signer: signer,
		Now: func() time.Time { return now },
	})
	if err != nil {
		log.Fatal(err)
	}
	return node{book: book, keys: evidencebook.ResponderKeys{
		Signer:     evidencebook.KeyID(signer),
		Checkpoint: hex.EncodeToString(checkpointKey.Public().(ed25519.PublicKey)),
	}}
}

func main() {
	ctx := context.Background()
	dir, err := os.MkdirTemp("", "evidencebook-example")
	if err != nil {
		log.Fatal(err)
	}
	defer os.RemoveAll(dir)
	alice := openNode(ctx, dir, "alice", 1)
	defer alice.book.Release()

	data, err := os.ReadFile("testdata/deal-reconcile-v0/vectors.json")
	if err != nil {
		log.Fatal(err)
	}
	var corpus struct {
		Contract struct {
			Ref string `json:"contract_ref"`
		} `json:"contract"`
		Cases []struct {
			ID       string `json:"id"`
			Expected struct {
				Result json.RawMessage `json:"result"`
			} `json:"expected"`
		} `json:"cases"`
	}
	if err := json.Unmarshal(data, &corpus); err != nil {
		log.Fatal(err)
	}
	var result json.RawMessage
	for _, c := range corpus.Cases {
		if c.ID == "pair-matched" {
			result = c.Expected.Result
		}
	}

	// A first run finds no earlier seal; a caller re-running the same
	// evaluation looks its earlier record up here instead.
	none := func() (evidencebook.Record, bool, error) { return evidencebook.Record{}, false, nil }
	add := func(e evidencebook.Entry) (evidencebook.Record, error) { return alice.book.Append(ctx, e) }
	sealed, already, checkpoint, err := alice.book.SealResult(ctx, result, corpus.Contract.Ref, nil, none, add)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("record type:", sealed.Header.RecordType)
	fmt.Println("subject:", sealed.Header.SubjectRef)
	fmt.Println("already sealed:", already, "checkpoint cut:", checkpoint > 0)
}
Output:
record type: evidence_result
subject: ec:deal-reconcile@1
already sealed: false checkpoint cut: true

func (*Book) SetRetention

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

SetRetention appends a lifecycle record moving recordID to state. DELETED is permanent and is refused while the record is held: under LEGAL_HOLD set by a lifecycle record, or covered by a live retention commitment. Deleting purges the record's originals from the artifact store after the lifecycle record is committed; the record's own commitments, and every other record's originals, are untouched. Asking for DELETED again on a deleted record retries a failed purge 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 disclosed header as withheld-with-digest. A
	// header carried inside its capsule (RecordHeaderMember) is part of the
	// capsule's committed bytes, so it travels whatever Suppress says. For
	// such a record, suppressing agent_input or agent_output also withholds
	// the original bound to it (unless another, unsuppressed member is bound
	// to the same bytes).
	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 are further extension blocks, by kind. producer-key/v1
	// is set through ProducerKey and composed/v1 is agent-action-capsule's
	// own, so both are refused here.
	Extensions map[string]json.RawMessage
	// ProducerKey, a raw 32-byte Ed25519 public key, declares the bundle's
	// producer key (the producer-key/v1 extension).
	ProducerKey ed25519.PublicKey
}

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 OpenCLLSQLite added in v0.5.0

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

OpenCLLSQLite opens (initializing if absent) the CLL log logID in the SQLite file at path. One file holds many logs, one per log id, as a profile's per-deal logs are held today (capsule-cli deal.db).

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 Cadence added in v0.5.0

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

Cadence runs a shelf's heartbeat ticks.

func (*Cadence) Chain added in v0.5.0

func (c *Cadence) Chain(ctx context.Context, statement []byte) (map[string]any, error)

Chain is the witnessed cadence chain for a log's checkpoint (its COSE statement): capsule-cli's cadenceChain, member for member, so its released verifier (deal_cadence_verify.go) checks it unchanged.

  • "all": a witnessed tick carries this very checkpoint;
  • "part": the newest witnessed tick carrying an earlier checkpoint of the log, plus that checkpoint and a consistency proof from it to this one ("earlier").

The leaf's salt, position and the tick's path; the cadence log's checkpoint, the tick's entry index and its inclusion proof; and the witness receipt the host reported. A profile adds its own members (a deal's "steps_witnessed" and "steps"). ErrNotFound when no witnessed tick carries the log up to this checkpoint: the host then says "pending" or "scheduled" from its own witness state.

func (*Cadence) Get added in v0.5.0

func (c *Cadence) Get(ctx context.Context, n uint64) (CadenceTick, error)

Get returns stored tick n.

func (*Cadence) ImportLegacy added in v0.6.0

func (c *Cadence) ImportLegacy(ctx context.Context, legacy LegacyCadence) error

ImportLegacy carries a pre-shelf cadence into this one, in one transaction, under the shelf's lock:

  • every log in legacy.Logs is registered: it counts into H, and shelf_logs records it as a host log;
  • each tick not already held is stored, numbered after the cadence's last tick, with its due time, leaves, checkpoint and receipt, so the cadence continues from it and Chain rebuilds a bundle anchored on it;
  • each witnessed tick it stores or promotes has its receipt verified under the configured witness directory, as Witnessed does: an import with such a receipt that is not VERIFIED (NOT_CHECKED or INVALID) is refused, naming the tick and the reason, and imports nothing. A tick already held witnessed is not checked again;
  • each witnessed tick's leaves get cadence_witnessed rows;
  • each registered log is live unless it has ended and has not grown past its largest witnessed checkpoint (the #36 rule).

It is re-runnable: a tick already held (the same cadence-log position and checkpoint) keeps its number and content, and is only promoted to witnessed when it now carries a receipt it did not (a pre-shelf writer delivered it since); a later run imports only ticks a pre-shelf writer added since, after the cadence's own. A tick at a held position with another checkpoint, or older than the newest tick held, is refused: it would rewrite what bundles may already name. So is any import while the cadence's own last tick is unfinished (a crash after its row): Tick resumes only the last tick, so a later tick would strand it; the host ticks first, which finishes it. Ended is evaluated before the transaction, as for Witnessed, and must not call the shelf.

func (*Cadence) Last added in v0.6.0

func (c *Cadence) Last(ctx context.Context) (tick CadenceTick, ok bool, err error)

Last returns the cadence's newest stored tick; ok is false when it has none. A host reads a log's pending standing from it (the newest tick holding the log, capsule-cli#242 §2.5) and maps a delivered cadence checkpoint back to its tick, walking back with Get.

func (*Cadence) Live added in v0.5.0

func (c *Cadence) Live(ctx context.Context) ([]string, error)

Live lists the live set, in log id order.

func (*Cadence) StandardHistoryAnchor added in v0.11.0

func (c *Cadence) StandardHistoryAnchor(ctx context.Context, n uint64) (StandardHistoryAnchor, error)

StandardHistoryAnchor is the anchor of tick n, or of the newest finished tick when n is 0. ErrNotFound when the cadence has no such finished tick.

func (*Cadence) Tick added in v0.5.0

func (c *Cadence) Tick(ctx context.Context, now time.Time) (TickResult, error)

Tick cuts a tick when one is due at now; otherwise it reports when one is. A tick is due when now is at or after the last tick's DueNext, and only then: its timing and size never depend on what the logs did.

func (*Cadence) Witnessed added in v0.5.0

func (c *Cadence) Witnessed(ctx context.Context, n uint64, receipt WitnessReceipt) (WitnessCheck, error)

Witnessed checks a witness's receipt for tick n's cadence checkpoint under the configured witness directory (CadenceConfig.Witnesses) and returns what it found. Only a verified receipt witnesses the tick: in one transaction, under the shelf's lock, each log checkpoint the tick carries gets a cadence_witnessed row, and each of those logs that has ended and has not grown past its largest witnessed checkpoint leaves the live set. Each log compares its own size, so a receipt for an older tick reported late never moves a log back. A receipt that is NOT_CHECKED changes nothing, and the host may report it again once its witness is in the directory; one that is INVALID changes nothing and is an ErrInvalid naming the reason.

func (*Cadence) WitnessedTick added in v0.5.0

func (c *Cadence) WitnessedTick(ctx context.Context, logID, checkpointSHA256 string, mmrSize uint64) (extent string, tick CadenceTick, leaf TickLeaf, err error)

WitnessedTick finds the witnessed tick a bundle of logID's checkpoint (its statement's SHA-256 and MMR size) is anchored by, from the index: "all" when a witnessed tick carries that very checkpoint, else "part" with the newest witnessed tick carrying an earlier checkpoint of the log (a bundle then adds a consistency proof from it). ErrNotFound when no witnessed tick carries any checkpoint of the log up to that size.

type CadenceConfig added in v0.5.0

type CadenceConfig struct {
	// LogID is the profile's cadence log, in the shelf's file
	// ("deal-cadence/<16hex>" for a deal profile).
	LogID string
	// Interval is at least 1m; Jitter is under half of it. Zero values take
	// the defaults (5m, 1m), unless NoJitter says the jitter is zero.
	Interval, Jitter time.Duration
	// NoJitter makes every tick due exactly Interval after the last (a
	// profile configured with no jitter).
	NoJitter bool
	// WitnessIDs are the witnesses each cadence checkpoint is queued for:
	// the checkpoint and a pending delivery to each are one commit of the
	// cadence log, as capsule-cli's checkpoint runner does. The host
	// delivers them (cll's PendingWitnesses on the cadence log) and reports
	// each receipt with Witnessed. None queues nothing.
	WitnessIDs []string
	// Witnesses is the witness directory receipts are verified under: the
	// transparency services' rows and keys (a witnesses.json, parsed with
	// AAC's witness.ParseDirectory). The zero Directory trusts no witness,
	// so every receipt is NOT_CHECKED and no tick is witnessed.
	Witnesses aacwitness.Directory
	// PadBucket pads the cadence log to a multiple of this many entries per
	// tick, at most 1024; zero is 1 (no padding).
	PadBucket uint64
	// Ended is the profile's predicate: whether a log has ended (for a
	// deal, a close step is sealed). It is evaluated each time it is
	// needed, never stored.
	Ended func(ctx context.Context, logID string) (bool, error)
}

CadenceConfig is a shelf's cadence. The defaults and limits are capsule-cli's: a tick every 5m, give or take 1m (288 a day).

type CadenceLog added in v0.5.0

type CadenceLog interface {
	LogID() string
	// MMRSize is the MMR node count of everything the log holds.
	MMRSize(ctx context.Context) (uint64, error)
	// CutLocal checkpoints everything the log holds at at, cutting a new
	// checkpoint only if the log grew, and returns the checkpoint's COSE
	// statement and MMR size. Nothing is sent to a witness.
	CutLocal(ctx context.Context, at time.Time) (statement []byte, mmrSize uint64, err error)
	// contains filtered or unexported methods
}

CadenceLog is what a tick checkpoints: a book, or a deal's log from before the upgrade (LegacyLog).

type CadenceTick added in v0.5.0

type CadenceTick struct {
	N        uint64
	At       time.Time
	DueNext  time.Time
	EntrySeq uint64
	// CheckpointSize and Checkpoint are the cadence log's checkpoint (MMR
	// size and COSE statement) that carries this tick's root.
	CheckpointSize uint64
	Checkpoint     []byte
	Leaves         TickLeaves
	// Witnessed is set once a receipt for the checkpoint verified
	// (Witnessed), and Receipt is that receipt. Ticks witnessed before
	// evidencebook verified receipts itself were set on the host's check.
	Witnessed bool
	Receipt   *WitnessReceipt
}

CadenceTick is one tick as stored: capsule-cli's deal_cadence row.

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 CapsuleSealer added in v0.5.0

type CapsuleSealer func(header Header, headerJSON []byte) (emit.Result, error)

CapsuleSealer seals a caller's own capsule as a record, under the book's writer lock (AppendCapsule). header is the record's header with its position and commit time assigned, and headerJSON its canonical bytes; the capsule must carry headerJSON as its RecordHeaderMember member and be signed by the book's signer. It returns the sealed capsule and its Producer Envelope. The book's lock is held while it runs and is not reentrant: the sealer must not call back into the Book.

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
	Period       ClosePeriod
	PeerClose    string
	Supersedes   string
}

CloseInput states what a Close binds. The book computes the reconciliation itself from Reconcile; a caller never supplies tallies. Reconcile's own window (FromSeq, ToSeq, zero leaving an end open) is the window the Close binds. PeerClose names the counterparty's Close for the same period, which the reconciliation answers; without it the Close seals counts only, with no reconcile block. Supersedes names a prior Close this one adjusts; the prior Close is never rewritten.

type ClosePeriod added in v0.11.0

type ClosePeriod struct {
	Start time.Time `json:"start"`
	End   time.Time `json:"end"`
}

ClosePeriod is the period a Close states, as RFC 3339 instants.

type CloseReconcile added in v0.11.0

type CloseReconcile struct {
	Tallies ResultTallies `json:"tallies"`
	Status  CloseStatus   `json:"status"`
}

CloseReconcile is a close/v1 Close's reconcile block. Status is the Close's own belief when sealed, always UNILATERAL here; a Close's status is read from the counterparty's links (StatusOfClose), never from it.

type CloseStatement

type CloseStatement struct {
	RecordVersion string         `json:"record_version"`
	RecordID      string         `json:"record_id"`
	EpistemicType EpistemicType  `json:"epistemic_type"`
	ClosedAt      string         `json:"closed_at"`
	Period        ClosePeriod    `json:"period"`
	CountsByKind  map[string]int `json:"counts_by_kind"`
	Head          EvidenceRef    `json:"head"`
	// Reconcile is present exactly when the Close cites the peer's Close,
	// the one cites link in EvidenceLinks.
	Reconcile     *CloseReconcile `json:"reconcile,omitempty"`
	EvidenceLinks []Link          `json:"x-evidence-links,omitempty"`
}

CloseStatement is the close/v1 body of a Close record.

RecordID is a locator, "<book_id>#<seq>" (the record capsule's action_id): the record's identity is its capsule id, a digest over the header that carries this body, so the body cannot name it. Head and every link target are record ids, never locators.

Head and CountsByKind describe the own window the Close binds: Head is the record at the window's last position, CountsByKind every record in the window by record_type. The window can begin before Period.Start when a caller chose it so (capsulectl's --since-last); Window recovers it.

func (CloseStatement) Window added in v0.11.0

func (s CloseStatement) Window(headSeq, closeSeq uint64) (from, to uint64, err error)

Window recovers the own window [from, to] a v1 Close binds, given the seq of its head record and the Close's own seq: to is the head's seq, and the counts cover every position from from to to. A body whose counts do not fit under its head (a negative count, more records than the head's position, or a head at or after the Close) is refused: a signed body is not proof that its counts are consistent. An empty window has from = to+1.

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.

func (Comparator) Check added in v0.5.0

func (c Comparator) Check() ContentCheck

Check lifts a Comparator to a ContentCheck: true agrees, false disagrees.

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
	// Originals is the artifact store that holds every record's payload
	// bytes (ArtifactStore). It must trust Signer's key.
	Originals ArtifactStore
	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
	// StandardHistory, when set, has Respond answer standard_history/1 to
	// authenticated requesters (StandardHistorySource).
	StandardHistory *StandardHistorySource
}

Config assembles a book. Store, Substrate, Originals 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 ContentCheck added in v0.5.0

type ContentCheck func(a, b Half) ContentVerdict

ContentCheck is a three-way content test: like a Comparator, but it can say the content needed is not there.

func OpenedFieldsAgree added in v0.5.0

func OpenedFieldsAgree(required ...string) ContentCheck

OpenedFieldsAgree compares the required fields' opened texts. Each record commits with its own fresh nonce, so two halves of the same text carry different commitments and only both openings can show agreement: a required field not opened on either half is Undecided; otherwise equal texts on every required field Agree, and any difference Disagrees. With no required field there is nothing to compare, so every pair is Undecided (INSUFFICIENT): name the fields the profile compares.

type ContentVerdict added in v0.5.0

type ContentVerdict int

ContentVerdict is what a content check concludes about a covered, trusted, correlated pair.

const (
	// Undecided: the content needed to compare is not available
	// (INSUFFICIENT), for example an unopened field commitment. Missing
	// content is never disagreement. It is the zero value, so a check that
	// returns nothing decided never reports a match.
	Undecided ContentVerdict = iota
	// Agree: the contents agree (MATCHED).
	Agree
	// Disagree: the contents were compared and differ (CONFLICTING).
	Disagree
)

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 CoverageGiven added in v0.6.0

type CoverageGiven struct {
	Period      ResultPeriod      `json:"period"`
	Declaration map[string]any    `json:"declaration"`
	Properties  map[string]string `json:"properties"`
}

CoverageGiven is a coverage declaration given for one book, with the period it is given for and the verifier's report of its coverage properties (IP §6.7.2), by property name.

type DealHalf added in v0.6.0

type DealHalf struct {
	Book   string
	Octets []byte
}

DealHalf is one half as the reconcile is given it: its octets as held and the book it comes from.

type DealReconcile added in v0.6.0

type DealReconcile struct {
	// FieldOpenings is each carried opening's status, PASS or FAIL, by half
	// digest and field, for the halves in the reconcile.
	FieldOpenings   map[string]map[string]string        `json:"field_openings"`
	SetCompleteness map[string]SetCompleteness          `json:"set_completeness"`
	Pairings        map[string]map[string]ExchangeState `json:"pairings"`
	Tallies         map[string]ResultTallies            `json:"tallies"`
	Sufficiency     map[string]string                   `json:"sufficiency"`
	Verdict         map[string]string                   `json:"verdict"`
	// DealState is DR §7.5's optional per-deal state; a caller may leave it
	// unshown.
	DealState map[string]string   `json:"deal_state"`
	Result    DealReconcileResult `json:"result"`
}

DealReconcile is the recompute's full outcome: every intermediate DR names, by requirement id where it is per requirement.

func RecomputeDealReconcile added in v0.6.0

func RecomputeDealReconcile(in DealReconcileInput) (DealReconcile, error)

RecomputeDealReconcile recomputes a reconcile under ec:deal-reconcile@1.

It reads each half only after its own format's checks have passed (DR §4.1, last paragraph): the caller verifies each half's signature, that it comes from the book it is given with, and that it is covered, and admits only halves that pass. This function checks the contract's structure only and treats every half it is given as admitted.

A malformed input, or a half malformed by DR §4.2, refuses the reconcile with ErrInvalid and no Result. Every half given is read through its book's mapping before the period and the two books scope it, so a malformed half refuses the reconcile even when it would be left out. A period holding no half of either book is refused with ErrInvalid too: a claim cites at least one record (RES §1, DR §7.3), and there is none.

type DealReconcileInput added in v0.6.0

type DealReconcileInput struct {
	// SideA is the book that produces the Result; Peer is side B.
	SideA, Peer string
	Period      ResultPeriod
	// HalfMappings is each book's half mapping, by book id.
	HalfMappings map[string]HalfMapping
	Halves       []DealHalf
	// FieldOpenings are by half digest, then by field name (DR §5).
	FieldOpenings map[string]map[string]Opening
	// Coverage is the coverage given for a book, by book id; a book with
	// none given is NOT_SHOWN.
	Coverage map[string]CoverageGiven
	// GeneratedAt is the Result's generated_at.
	GeneratedAt string
}

DealReconcileInput is everything a reconcile under the contract reads.

type DealReconcileResult added in v0.6.0

type DealReconcileResult struct {
	ResultVersion string           `json:"result_version"`
	GeneratedAt   string           `json:"generated_at"`
	Claims        []ReconcileClaim `json:"claims"`
	Aggregate     ResultAggregate  `json:"aggregate"`
}

DealReconcileResult is an Evidence Result v0 holding the two claims.

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, over
	// any form the definition declares: it is the holder's grant to that
	// requester. An empty Recipient makes the derivation answerable under
	// the share policy like the underived subject, so over range or
	// full_history it is answered to no one.
	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 DoctorFinding added in v0.8.0

type DoctorFinding struct {
	Check  string `json:"check"`
	State  string `json:"state"`
	Detail string `json:"detail"`
	// Records names what shows the finding: record ids, a binding digest,
	// or an envelope's anchor.
	Records []string `json:"records,omitempty"`
}

DoctorFinding is one line of a doctor report. A report is a list of findings and nothing else: no score, rank or grade is computed from it.

type DoctorOptions added in v0.8.0

type DoctorOptions struct {
	// Policy is the sharing policy this node advertises and answers under.
	Policy SharePolicy
	// ControllerBindings are controller binding records (controller-binding/0)
	// the host holds, as delivered.
	ControllerBindings []json.RawMessage
	// Witnesses are the host's witness deliveries; none means the book is
	// not delivered to any witness.
	Witnesses []DoctorWitness
	// Probe, when set, asks the node's own responder for checkpoints and
	// then history_card/1, as a stranger, and verifies both answers.
	Probe DoctorTransport
	// Keys are the responder keys this node advertises, which the probe
	// verifies under. Either left empty is this book's own key.
	Keys ResponderKeys
}

DoctorOptions is what Doctor reads besides the book.

type DoctorTransport added in v0.8.0

type DoctorTransport func(ctx context.Context, request Message) (Message, error)

DoctorTransport carries one request to this node's own responder and returns its reply, as a stranger would send and receive it. It must not authenticate the request: an authenticated request is sealed by Respond.

type DoctorWitness added in v0.8.0

type DoctorWitness struct {
	Witness  string
	TreeSize uint64
	Receipt  bool
}

DoctorWitness is what the host knows of one witness delivery of this book's checkpoints: the witness, the checkpoint's tree size, and whether a receipt is held for it.

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
	// Fields are texts committed with a fresh nonce each (CommitAlgNonce256),
	// by field name: the header carries the commitments, the artifact store
	// the openings.
	Fields          map[string]string
	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 EvidenceRef added in v0.6.0

type EvidenceRef struct {
	Digest    string `json:"digest"`
	DigestAlg string `json:"digest_alg"`
}

EvidenceRef is evidence by digest only (RES §5).

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
	// FieldCommitments are the record's salted field commitments, by name.
	FieldCommitments map[string]string
	// Opened holds the texts of the fields whose openings verified against
	// this half's own commitments (OpenHalf).
	Opened  map[string]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.

func OpenHalf added in v0.5.0

func OpenHalf(h Half, openings map[string]Opening) Half

OpenHalf checks each opening given for h against h's own field commitments. One that opens records its text in Opened; one that does not (a wrong nonce, a changed text, a field h does not commit) makes h untrusted, so its pair is UNRESOLVED whatever else holds. A missing opening changes nothing here: OpenedFieldsAgree reads it as Undecided.

type HalfMapping added in v0.6.0

type HalfMapping struct {
	Profile string            `json:"profile"`
	Members map[string]string `json:"members"`
}

HalfMapping is a profile's declared mapping onto the abstract members (DR §4.2): each member is a JSON Pointer (RFC 6901) into the half.

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"`
	// FieldCommitments are the record's salted per-field commitments, by
	// field name, under CommitAlg (CommitAlgNonce256). Their openings are
	// originals in the artifact store, never in the record. Presentation
	// contract §7.2 records carry the same values as `<name>_commitment`
	// members; here they are one map, and the values are identical.
	FieldCommitments map[string]string `json:"field_commitments,omitempty"`
	CommitAlg        string            `json:"commit_alg,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 HeldLock added in v0.12.2

type HeldLock interface {
	Held() error
}

HeldLock is a writer lock a host holds on the shelf's store. Held reports nil while the host holds it; the shelf asks once, when it opens, and never releases it.

type HostLog added in v0.12.2

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

HostLog is a log on the shelf whose records the host seals itself, in its own record format, never converted into book records (evidencebook#254 §2.7). The shelf hands the host, under its lock, the log's CLL backend on the shelf's file and the shelf's artifact store (Write), so the host's own log layer runs on the shelf's storage. A host log is in the cadence, which checkpoints it like a book, or outside it, when its checkpoints and witness rows are the host's own on that backend. shelf_logs records it as a host log, so Open refuses its id across reopens.

func (*HostLog) Append added in v0.12.2

func (l *HostLog) Append(ctx context.Context, write func() error) error

Append runs write, the profile's own step for this log (it opens its own handle on the log), under the shelf's lock. write must not call the shelf or its cadence: the lock is held. For a log in the cadence, Append puts it back in the live set: an append to a closed deal (later evidence) re-enters the tick like any append.

func (*HostLog) CutLocal added in v0.12.2

func (l *HostLog) CutLocal(ctx context.Context, at time.Time) ([]byte, uint64, error)

func (*HostLog) LogID added in v0.12.2

func (l *HostLog) LogID() string

func (*HostLog) MMRSize added in v0.12.2

func (l *HostLog) MMRSize(ctx context.Context) (uint64, error)

func (*HostLog) Write added in v0.12.2

func (l *HostLog) Write(ctx context.Context, write func(HostLogStores) error) error

Write runs write on the log's stores (HostLogStores) under the shelf's lock, as Append does. write must not call the shelf or its cadence.

type HostLogStores added in v0.12.2

type HostLogStores struct {
	Log       cll.Backend
	Originals ArtifactStore
}

HostLogStores is what a host log's writes run on: the log's CLL backend on the shelf's file and the shelf's artifact store, under the shelf's one namespace (ShelfConfig.Originals). Both are the shelf's; the host must not close them or keep them past the write.

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 LegacyCadence added in v0.6.0

type LegacyCadence struct {
	// Logs are the profile's pre-shelf logs, each a log of the shelf's file
	// that is not a book (capsule-cli: "deal/" + every deal_id of
	// deal_steps, sales included). Each counts into H.
	Logs []string
	// Ticks are the pre-shelf writer's finished ticks (CheckpointSize > 0),
	// in cadence-log order. N is ignored: a tick's identity is its place in
	// the cadence log (EntrySeq) and its checkpoint, and ImportLegacy
	// numbers it. Witnessed and Receipt are set on each tick the pre-shelf
	// writer recorded as witnessed; ImportLegacy verifies each such receipt
	// as Witnessed does. Every log a tick carries is one of Logs.
	Ticks []CadenceTick
}

LegacyCadence is a profile's cadence as a pre-shelf writer kept it: capsule-cli's deal_cadence rows, on the same cadence log, and the logs its deal index holds (evidencebook#36 §4, capsule-cli#242 §3.2).

type LegacyCloseStatement added in v0.11.0

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

LegacyCloseStatement is the body Closes carried before close/v1: no record_version, the book's whole reconciliation, and the profile string the caller named.

type LegacyLog added in v0.5.0

type LegacyLog = HostLog

LegacyLog is a deal's log from before the upgrade (#36 §4): a host log in the cadence, whose capsules are not book records, so it is never converted. Every write to it goes through Append, under the shelf's lock.

type LifecycleStatement

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

LifecycleStatement is the body of a lifecycle record: a later, separately committed statement that the cited record's retention state changed. The state belongs to the record as a whole, never to one of its payloads, and the record that committed the payloads is never rewritten.

A lifecycle record written before retention was kept per record also names a payload_commitment; it is read as applying to the whole record.

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 Opening added in v0.5.0

type Opening struct {
	Nonce string `json:"nonce"`
	Text  string `json:"text"`
}

Opening is what opens one field commitment: the nonce and the text. It stays with the record's originals and leaves only when disclosed.

func NewOpening added in v0.5.0

func NewOpening(text string) (Opening, error)

NewOpening draws a fresh 32-byte nonce for text.

func (Opening) Commitment added in v0.5.0

func (o Opening) Commitment() (string, error)

Commitment is the field commitment o opens.

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 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, or the capsule, verified, carries the header itself (RecordHeaderMember).

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 ReconcileBody added in v0.6.0

type ReconcileBody struct {
	JoinKey       string        `json:"join_key"`
	Peer          string        `json:"peer"`
	Period        ResultPeriod  `json:"period"`
	Tallies       ResultTallies `json:"tallies"`
	StateOfRecord string        `json:"state_of_record"`
}

ReconcileBody is the RES §4.1 reconcile body.

type ReconcileClaim added in v0.6.0

type ReconcileClaim struct {
	ID             string             `json:"id"`
	Type           string             `json:"type"`
	ContractRef    string             `json:"contract_ref"`
	RequirementRef string             `json:"requirement_ref"`
	Tier           string             `json:"tier"`
	Grade          string             `json:"grade"`
	Sufficiency    string             `json:"sufficiency"`
	Verdict        string             `json:"verdict"`
	Evidence       []EvidenceRef      `json:"evidence"`
	Proofs         []EvidenceRef      `json:"proofs"`
	Presentation   ResultPresentation `json:"presentation"`
	Reconcile      ReconcileBody      `json:"reconcile"`
}

ReconcileClaim is a type: reconcile claim citing the contract. It has no member that cites a Close (DR §7.4).

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 or Check is the content test; exactly one is set. Check can
	// answer Undecided (OpenedFieldsAgree, for salted field commitments).
	Compare Comparator
	Check   ContentCheck
	// OwnOpenings and PeerOpenings are field openings by record id, checked
	// against each half's own commitments (OpenHalf) before comparison.
	OwnOpenings, PeerOpenings map[string]map[string]Opening
}

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 for a limit: capacity_exceeded under evidence-interop/1, policy_declined under /0.

type RequestStatement

type RequestStatement struct {
	Request      json.RawMessage `json:"request"`
	ResponderRef string          `json:"responder_ref,omitempty"`
	// ComposedElsewhere marks a request RequestSent recorded: another tool
	// composed it, and the book checked only that it is a well-formed
	// request. Members it does not define, such as a deployment profile's
	// audience or requester authentication, are kept as sent and never
	// checked, so the record does not vouch for them.
	ComposedElsewhere bool `json:"composed_elsewhere,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: the witnesses whose
	// receipts it counts, on a reply's anchor (RecordResponse) and on an
	// Evidence Bundle's (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 for a limit, as a request over the limiter is.
	// 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"`
	// Witness is Witnessed or Unwitnessed for an artifact that verified,
	// and absent otherwise.
	Witness string `json:"witness,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 ResultAggregate added in v0.6.0

type ResultAggregate struct {
	Coverage struct {
		EvaluatedPopulation   int `json:"evaluated_population"`
		ExcludedNotApplicable int `json:"excluded_not_applicable"`
		UnknownCount          int `json:"unknown_count"`
	} `json:"coverage"`
	Buckets struct {
		Met          []string `json:"met"`
		NotMet       []string `json:"not_met"`
		NotEvaluable []string `json:"not_evaluable"`
	} `json:"buckets"`
}

ResultAggregate is the Result's coverage statement and buckets (RES §7).

type ResultPeriod added in v0.6.0

type ResultPeriod struct {
	Start string `json:"start"`
	End   string `json:"end"`
}

ResultPeriod is a reconcile's period [start, end), in RFC 3339 UTC with Z and seconds precision.

type ResultPresentation added in v0.6.0

type ResultPresentation struct {
	Kind     string        `json:"kind"`
	Status   string        `json:"status"`
	Evidence []EvidenceRef `json:"evidence"`
}

ResultPresentation is a claim's disclosure carrier (RES §2).

type ResultTallies added in v0.6.0

type ResultTallies 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"`
}

ResultTallies are a reconcile claim's six tallies (RES §4.1).

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 SeqRun added in v0.11.0

type SeqRun struct {
	Seqs []uint64 `json:"seqs"`
	// Gapless: each number is one more than the one before, and each
	// record's PrevSeq names the one before it. An empty or one-record run
	// is gapless when its first PrevSeq is unset or one less than its Seq.
	Gapless bool `json:"gapless"`
}

SeqRun is the provider's per-pair numbering across the records it matched, in sequence order.

type SetCompleteness added in v0.6.0

type SetCompleteness struct {
	Status string  `json:"status"`
	Kind   *string `json:"kind"`
}

SetCompleteness is a side's §6.1 status and its declared kind, null when no declaration is given.

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.

HistorySegments decides who may have the records an underived (or shared-derivation) record, exchange or correlation subject names: "counterparties" (the default) answers only the party each of those records names as its counterparty; "peers" answers any authenticated peer; "off" answers no one. "prospective" is accepted and read as "counterparties", as the mesh plugin reads it. A correlation subject is an exact-key lookup (bookView.Correlated), so it is gated like an exchange. Whatever the setting, range and full_history are refused, but for full_history under standard_history/1 when the host serves it (StandardHistorySource). A recipient-specific derivation is the holder's grant and is not gated by the setting: it is answered to its recipient over every form it declares, "off" included (gate.responderPolicy).

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 Shelf added in v0.5.0

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

Shelf is one profile's books, each its own log (evidencebook#36 §1): a deal's bundle is built from its book alone, so it carries no other deal's records. A shelf holds the profile's writer lock from OpenSQLiteShelf to Release and is the profile's only writer. It keeps one Book per log id for its lifetime: a Book allocates positions from its own in-memory order, so two instances of one log could give two records one position.

Each book keeps its own mutex; books of one shelf do not share one. Their positions are per log, so they need no common order, and their writes to the shared file are serialized by SQLite (WAL, a busy timeout, immediate CLL transactions). Operations across books, such as a cadence tick, take the shelf's mutex.

func OpenSQLiteShelf added in v0.5.0

func OpenSQLiteShelf(ctx context.Context, cfg ShelfConfig) (*Shelf, error)

OpenSQLiteShelf takes the writer lock, waiting for any other holder until ctx is done (or checks the host's held lock), and opens the shelf's SQLite file, creating its tables when absent. A file whose shelf_meta version it does not know is refused (ErrUnsupported); one with no shelf_meta row is a fresh file or a shelf from v0.12.0 or earlier, and gets version 1, with shelf_logs filled from what it holds (evidencebook#254 §2.2).

The file has two kinds of handle: the shelf's own (records and checkpoints of every book) and one per book's CLL log. Both use WAL and a busy timeout, and transactions on both begin IMMEDIATE, so two writers wait under the busy timeout rather than fail. A record's append spans two handles (its log leaf, then its row) and is not one transaction; that is the shape of the JSONL journal and FileStore too, and Open's recovery reconciles a crash between them. Do not fold the handles into one connection to "fix" it: the CLL store owns its own.

func (*Shelf) Books added in v0.5.0

func (s *Shelf) Books(ctx context.Context) ([]string, error)

Books lists the ids of the books that hold records, in id order.

func (*Shelf) Cadence added in v0.5.0

func (s *Shelf) Cadence(ctx context.Context, cfg CadenceConfig) (*Cadence, error)

Cadence opens the shelf's cadence log, creating it when absent.

func (*Shelf) HostLog added in v0.12.2

func (s *Shelf) HostLog(ctx context.Context, logID string, inCadence bool) (*HostLog, error)

HostLog opens logID as a host log, provisioning its CLL log when the file holds nothing of it. inCadence registers it with the cadence as Legacy does; otherwise the cadence never checkpoints it and the host checkpoints and witnesses it on its backend. It is the same *HostLog for the same id for the shelf's lifetime. An id opened before in the other mode, in this process or as the file records it, or a book's id, is refused (ErrInvalid).

func (*Shelf) Legacy added in v0.5.0

func (s *Shelf) Legacy(ctx context.Context, logID string) (*LegacyLog, error)

Legacy opens an existing log of the shelf's file that is not a book and registers it with the cadence: it counts into the lifetime log count and is live until it has ended and a witnessed tick carries its final checkpoint. It never provisions a log. A book's id is refused (ErrInvalid).

func (*Shelf) Open added in v0.5.0

func (s *Shelf) Open(ctx context.Context, logID string) (*Book, error)

Open returns the book whose log id is logID, creating it on first use. It is the same *Book for the same id for the shelf's lifetime. A host log's id is refused (ErrInvalid), in this process or as shelf_logs records it.

func (*Shelf) Records added in v0.6.0

func (s *Shelf) Records(ctx context.Context, bookIDs ...string) (ShelfRecords, error)

Records lists the committed records of the shelf's books, in book id then seq order, without opening a book: nothing is recovered, verified or written. A reader across every deal of a profile costs two queries (the records, and every log's entry count), not one book opened per deal.

A record is committed when 1 <= seq <= its book's log entry count (an entry count, not an MMR size). bookIDs narrows the listing to those books; none lists every book.

The headers are as stored. Records is for readers on the device that wrote them; a book's Open is what checks them against its log.

func (*Shelf) Release added in v0.5.0

func (s *Shelf) Release() error

Release releases every book the shelf opened, closes its file and gives up the writer lock. A book from this shelf refuses writes afterwards (ErrReleased).

type ShelfConfig added in v0.5.0

type ShelfConfig struct {
	// Path is the SQLite file holding every book's records, checkpoints and
	// CLL log (one log per book, keyed by its id), as capsule-cli keeps a
	// profile's per-deal logs in one deal.db.
	Path string
	// LockPath is the profile's writer lock file. A host that already has
	// a writer lock for the store passes that path, so its own writers and
	// the shelf exclude each other: capsule-cli's deal store must pass
	// "<deal.db>.deal.lock" (lockDealStore). Empty means Path + ".lock",
	// which excludes only other shelves.
	LockPath string
	// HeldLock is the store's writer lock when the host already holds it
	// under its own rules (evidencebook#254 §2.4): the shelf then takes no
	// lock of its own and leaves the host's to the host, so LockPath must be
	// empty. The shelf's own lock is unix-only; a shelf on a held lock opens
	// on any platform.
	HeldLock HeldLock
	// Random is the shelf's one random source: every salt, tree position,
	// filler nonce and seed, jitter and padding nonce the cadence draws comes
	// from it, in the order the shelf vectors (testdata/shelf) state. Nil is
	// the system CSPRNG, which production uses; a fixed stream makes a run
	// deterministic, as the cross-language vectors and interlock need.
	Random io.Reader

	Operator  string
	Developer string
	// Signer seals every book's records; CheckpointKey signs every book's
	// checkpoints, as one key signs a profile's deal logs today.
	Signer        Signer
	CheckpointKey ed25519.PrivateKey
	// Originals is the profile's one artifact store (capsule-cli#236
	// decision 3), shared by every book: an artifact record is keyed by its
	// record id, which is unique across books.
	Originals ArtifactStore
	Now       func() time.Time
	// AuthenticatedIndexes gives a book its authenticated indexes when the
	// shelf opens it. A nil function, or a nil result for a log, gives that
	// book the defaults (NewRecordIDIndex, NewSubjectIndex). An empty,
	// non-nil result gives it none, so its checkpoints commit no index_root
	// records: a deal's log then holds its own steps only.
	AuthenticatedIndexes func(logID string) []AuthenticatedIndex
}

ShelfConfig assembles a Shelf: one profile's books in one SQLite file.

type ShelfRecord added in v0.6.0

type ShelfRecord struct {
	BookID   string
	Seq      uint64
	RecordID string
	Header   Header
	// Retention is the record's retention state now, as Book.Retention
	// gives it; empty for a record that commits no payload or field, which
	// has none.
	Retention RetentionState
}

ShelfRecord is a committed record of one of a shelf's books, as Records lists it.

type ShelfRecords added in v0.6.0

type ShelfRecords struct {
	Records []ShelfRecord
	// Pending counts, by book, the records stored above the book's
	// committed entry count: a crash after PutRecord and before the log
	// append, which the book's next Open recovers. They are not listed.
	Pending map[string]int
}

ShelfRecords is what Records reads: the committed records, and how many records each book holds beyond them.

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. Respond signs without the book's lock, so Sign may be called concurrently.

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 under one subject_ref. A key range proof over it proves subject_ref membership only; it does not establish that a correlation subject's answer is complete, since a record that carries a correlation identifier is answered under that (bookView.Correlated).

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 StandardHistoryAnchor added in v0.11.0

type StandardHistoryAnchor struct {
	Tick CadenceTick
	// AsOf names the tick's cadence checkpoint (the SHA-256 of its signed
	// statement), its time, and the time of the cadence log's first
	// checkpoint.
	AsOf standardhistory.AsOf
	// Extents is, for every log a tick up to and including this one
	// carried, how many of its records (seq 1 to the extent) the tick
	// commits: the largest checkpoint of the log any of those ticks
	// carries. A log a tick drops once it is ended stays committed at the
	// checkpoint its last tick carried.
	Extents map[string]uint64
}

StandardHistoryAnchor is a cadence tick as the anchor of a shelf's card.

type StandardHistorySource added in v0.11.0

type StandardHistorySource struct {
	// HolderKind is "person" or "node": the kind of holder the book's key
	// answers for, as the holder's own controller declaration states it.
	HolderKind string
	// Inputs returns the two members of the policy in force at the anchor
	// (its digest and window, SH §5.1) and one deal entry per deal the
	// stream holds at the anchor (SH §5.2), read from records: the book's
	// servable records the anchor covers, in log order. Respond calls it
	// without the book's lock, and may call it for several requests at
	// once. Its result must depend on its arguments only, so the card does
	// not depend on who asks (ER §5).
	Inputs func(ctx context.Context, anchor Checkpoint, records []Record) (standardhistory.Policy, []standardhistory.Deal, error)
}

StandardHistorySource is what a host supplies for Respond to answer standard_history/1 over the full_history subject. With it set, Respond answers the card to any authenticated requester, whatever the share policy's tier; a stranger still has only the public questions answered (checkpoints and history_card/1). Without it, standard_history/1 is derivation_unsupported.

The book defines neither a disclosure policy format nor how its records make deals: the host reads both (SH §5.1, SH-2).

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.

The book writes under its own lock, but Respond reads GetRecord and Checkpoints without it, so they must be safe to call concurrently with the writes.

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 TickLeaf added in v0.5.0

type TickLeaf struct {
	LogID            string `json:"log_id"`
	Size             uint64 `json:"size"`
	CheckpointSHA256 string `json:"checkpoint_sha256"`
	Salt             string `json:"salt"`
	Index            uint64 `json:"index"`
	// Statement is the log's checkpoint itself (base64url COSE), kept on
	// the device so a later bundle can show an earlier witnessed checkpoint
	// is a prefix of its current one. The leaf commits to its SHA-256.
	Statement string `json:"statement,omitempty"`
}

TickLeaf is one log's leaf in one tick, as stored on the device. It is capsule-cli's dealTickLeaf, member for member.

type TickLeaves added in v0.5.0

type TickLeaves struct {
	Deals       map[string]TickLeaf `json:"deals"`
	FillerIndex uint64              `json:"filler_index"`
	FillerNonce string              `json:"filler_nonce"`
	// FillerSeed and FillerCount derive fillers 1..FillerCount
	// (DerivedFillers). The seed stays on the device, like the salts.
	FillerSeed  string `json:"filler_seed,omitempty"`
	FillerCount uint64 `json:"filler_count,omitempty"`
}

TickLeaves is every leaf of one tick: capsule-cli's dealTickLeaves (the logs under "deals", one filler) plus the derived fillers that keep a tick's occupancy at the profile's lifetime log count (§2, occupancy floor). A tick stored by a released capsule-cli build has no filler_seed and no derived fillers, and reads unchanged.

func (TickLeaves) Tree added in v0.5.0

func (l TickLeaves) Tree(index uint64) (root []byte, path [][]byte, err error)

Tree rebuilds the tick's tree from its stored leaves and returns the root and the path of the leaf at index.

type TickResult added in v0.5.0

type TickResult struct {
	// Ticked is false when no tick was due; DueNext then says when one is.
	Ticked  bool
	Tick    CadenceTick
	DueNext time.Time
}

TickResult is what one Tick call did.

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 (VerifyBundleAnswer does, through ResponderKeys.Witnesses).
	Witnesses []json.RawMessage
	// Witnessed is set by VerifyBundleAnswer when at least one carried
	// receipt verified under the requester's directory. Otherwise it adds
	// the finding "unwitnessed": the bundle verifies only against its
	// holder's own signatures.
	Witnessed     bool
	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.

The requester's limits apply before the bundle verifier runs: at most MaxReplyBytes, MaxReplyDepth deep, MaxReplyItems records and MaxReplyReceipts witness receipts. Over one is an error naming 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 that carries no receipt still verifies, with Witnessed false and the finding "unwitnessed". Unlike a reply's carried receipts, a bundle's must all verify: a bundle is checked on its own, with no open request whose outcome a forged receipt could foreclose. 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 WitnessCheck added in v0.8.0

type WitnessCheck struct {
	State  string
	Reason string
}

WitnessCheck is what checking one receipt found: its state and why. When AAC's verifier ran, Reason is its finding and its reason (for example "witness_unverified:<ts_url>: not checked: no directory row for this witness"); a receipt missing a member is INVALID before any check, with evidencebook's own reason.

type WitnessReceipt added in v0.5.0

type WitnessReceipt struct {
	TSURL     string `json:"ts_url"`
	EntryHash string `json:"entry_hash"`
	Receipt   []byte `json:"receipt"`
	LeafIndex uint64 `json:"leaf_index"`
	TreeSize  uint64 `json:"tree_size"`
}

WitnessReceipt is the witness's receipt for a tick's cadence checkpoint: capsule-cli's chain carries these members (cll.WitnessState's receipt).

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.
acp
Package acp is the evidencebook adapter for the Agentic Commerce Protocol (ACP), API version 2026-04-17: the checkout session, the order, and the delegated payment token, as declared in agent-action-capsule spec/adapters/acp-v0.md (cited here as acp-v0).
Package acp is the evidencebook adapter for the Agentic Commerce Protocol (ACP), API version 2026-04-17: the checkout session, the order, and the delegated payment token, as declared in agent-action-capsule spec/adapters/acp-v0.md (cited here as acp-v0).
internal/ijson
Package ijson is the adapters' one JSON reader and their one RFC 8785 serializer.
Package ijson is the adapters' one JSON reader and their one RFC 8785 serializer.
ucp
Package ucp is the evidencebook adapter for the Universal Commerce Protocol (UCP) v2026-08-25, as declared in agent-action-capsule spec/adapters/ucp-v0.md.
Package ucp is the evidencebook adapter for the Universal Commerce Protocol (UCP) v2026-08-25, as declared in agent-action-capsule spec/adapters/ucp-v0.md.
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.
Package dealprofile is the x-deal-v0 deal record profile: its names, the keys and fingerprints that keep raw identifiers out of a record, a record's payload and digest, the record-level checks a sealed record must pass, the sealed deal_report's payload, and the members of a step's Capsule.
Package dealprofile is the x-deal-v0 deal record profile: its names, the keys and fingerprints that keep raw identifiers out of a record, a record's payload and digest, the record-level checks a sealed record must pass, the sealed deal_report's payload, and the members of a step's Capsule.
internal
detrand
Package detrand is the deterministic random stream the shelf vectors and the storage interlock inject as a shelf's one random source (evidencebook#254 §5).
Package detrand is the deterministic random stream the shelf vectors and the storage interlock inject as a shelf's one random source (evidencebook#254 §5).
shelfscript
Package shelfscript is the scripted shelf of the cross-language shelf conformance (evidencebook#254 §5): one set of host parameters, a writer phase and a continuer phase, and a dump of everything a shelf file holds that the contract fixes.
Package shelfscript is the scripted shelf of the cross-language shelf conformance (evidencebook#254 §5): one set of host parameters, a writer phase and a continuer phase, and a dump of everything a shelf file holds that the contract fixes.
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/caller-sealed command
Command caller-sealed is Go's side of the caller-sealed record interlock: a deal book on a shelf whose records are Capsules their producer seals itself (Book.AppendCapsule), each carrying its header in evidence_record_header and committing three fields, as a deal step does (dealprofile x-deal-v0 §1).
Command caller-sealed is Go's side of the caller-sealed record interlock: a deal book on a shelf whose records are Capsules their producer seals itself (Book.AppendCapsule), each carrying its header in evidence_record_header and committing three fields, as a deal step does (dealprofile x-deal-v0 §1).
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/checkpoint-parity command
Command checkpoint-parity reads CLL checkpoint statements and says, for each, whether this module accepts it: the checks checkpointFromStatement makes (checkpoint.ParseRecord, VerifySignature, a complete MMR size).
Command checkpoint-parity reads CLL checkpoint statements and says, for each, whether this module accepts it: the checks checkpointFromStatement makes (checkpoint.ParseRecord, VerifySignature, a complete MMR size).
interop/goose-card command
Command goose-card is Go's check of a Goose node's standard_history/1 card (python/examples/goose): it opens a copy of the node's shelf with Go's evidencebook, derives the card's anchor from the cadence (Cadence.StandardHistoryAnchor) and every deal entry from the deal books under it (dealprofile.StandardHistoryDeal), and requires the card the Python node wrote to be exactly the card Go derives (DeriveStandardHistory), with every SH §6 property PASS against those inputs.
Command goose-card is Go's check of a Goose node's standard_history/1 card (python/examples/goose): it opens a copy of the node's shelf with Go's evidencebook, derives the card's anchor from the cadence (Cadence.StandardHistoryAnchor) and every deal entry from the deal books under it (dealprofile.StandardHistoryDeal), and requires the card the Python node wrote to be exactly the card Go derives (DeriveStandardHistory), with every SH §6 property PASS against those inputs.
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/shelf command
Command shelf is Go's side of the shelf storage interlock (evidencebook#254 §5 item 2): CLL's storage-interlock one layer up.
Command shelf is Go's side of the shelf storage interlock (evidencebook#254 §5 item 2): CLL's storage-interlock one layer up.
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