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 (AdmitAPeer) ¶
Path 5, admit a peer: verify the staple, evaluate the admission pack, seal the decision. docs/GUIDE.md walks the steps.
The staple is the standard_history/1 vector of testdata/staple/staples.json. The pack and its cases are admission-baseline@1 (testdata/admission-baseline, VECTORS.md): the builder wrote the pack's rows and thresholds, and Evaluate computes the band, the tier, the card's freshness and each row's denominator. A case's input is what the caller verified about the counterparty, as the vector states it.
// SPDX-License-Identifier: Apache-2.0
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"os"
"github.com/action-state-group/capsule-engine/go/admission"
"github.com/action-state-group/capsule-engine/go/canon"
"github.com/action-state-group/evidencebook"
)
// Path 5, admit a peer: verify the staple, evaluate the admission pack,
// seal the decision. docs/GUIDE.md walks the steps.
//
// The staple is the standard_history/1 vector of testdata/staple/staples.json.
// The pack and its cases are admission-baseline@1 (testdata/admission-baseline,
// VECTORS.md): the builder wrote the pack's rows and thresholds, and
// Evaluate computes the band, the tier, the card's freshness and each row's
// denominator. A case's input is what the caller verified about the
// counterparty, as the vector states it.
func main() {
ctx := context.Background()
// 1. Verify the staple. CheckStaple checks the presenter, the request and
// the card's form; the card's own properties and the nonce's freshness
// are the reader's.
var staples []struct{ Name, Holder, Request, Reply string }
readJSON("testdata/staple/staples.json", &staples)
var stapled struct{ Name, Holder, Request, Reply string }
for _, v := range staples {
if v.Name == "standard_history/1" {
stapled = v
}
}
check, err := evidencebook.CheckStaple(evidencebook.Staple{
Request: evidencebook.Message{Octets: []byte(stapled.Request), MediaType: evidencebook.MediaTypeJSON},
Reply: evidencebook.Reply{Message: evidencebook.Message{Octets: []byte(stapled.Reply), MediaType: evidencebook.MediaTypeJSON}},
}, stapled.Holder)
if err != nil {
log.Fatal(err)
}
// The card's counts become Inputs.Card.Bands and .Disputes.
bands, disputes, err := admission.StandardHistoryCounts(check.Artifact)
if err != nil {
log.Fatal(err)
}
fmt.Printf("staple: %s, %d bands, %d of %d disputes open\n", check.Derivation, len(bands), disputes.Open, disputes.Of)
// 2. Load the pack. LoadPinned(src, id, digest) refuses a pack that is
// not the one the builder pinned.
src, err := os.ReadFile("testdata/admission-baseline/pack-definition.json")
if err != nil {
log.Fatal(err)
}
pack, err := admission.Load(src)
if err != nil {
log.Fatal(err)
}
fmt.Println("pack:", pack.ID)
// 3. Evaluate one deal per case: a GO, an ASK, a LIMIT after a refusal.
var corpus struct {
Cases []struct {
Case string `json:"case"`
Input json.RawMessage `json:"input"`
} `json:"cases"`
}
readJSON("testdata/admission-baseline/cases.json", &corpus)
input := func(name string) admission.Inputs {
for _, c := range corpus.Cases {
if c.Case == name {
in, err := admission.DecodeInputs(c.Input)
if err != nil {
log.Fatal(err)
}
return in
}
}
log.Fatalf("no case %s", name)
return admission.Inputs{}
}
dir, err := os.MkdirTemp("", "evidencebook-example")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
me := openNode(ctx, dir, "goose", 1)
defer me.book.Release()
var granted admission.Decision
for _, name := range []string{"t1-stranger-climbs-on-its-own-card", "t1-no-card-asks", "t1-card-refused-limits"} {
d := admission.Evaluate(pack, input(name))
fmt.Printf("%s: %s at %s, decided by %s", name, d.Verdict, d.Tier, d.Source)
for _, a := range d.Asks {
// The ask is the Evidence Request to send next: Book.Request
// records that this book asked, and returns the octets to
// transmit. The deadline is when to record an absence.
one := uint64(1)
sent, err := me.book.Request(ctx, evidencebook.EvidenceRequest{
Subject: evidencebook.Subject{Kind: evidencebook.SubjectFullHistory}, Derivation: a.Derivation,
Coverage: evidencebook.Coverage{MinFreshness: &evidencebook.Freshness{Size: &one}},
}, "mesh-node")
if err != nil {
log.Fatal(err)
}
fmt.Printf(", ask %s within %ds (request recorded: %v)", a.Derivation, a.DeadlineS, sent.RecordID != "")
}
fmt.Println()
if d.Verdict == "GO" {
granted = d
}
}
// 4. Seal a decision in the book. Block is the admission_decision block;
// it holds the pack by its digest and no counterparty text. Its reads
// cite the policy only: a caller that keeps the card appends its own
// commitment to the card to reads first. This Example seals the block as
// it comes, since its card is a fixture's.
block, err := canon.JCS(granted.Block())
if err != nil {
log.Fatal(err)
}
sealed, err := me.book.Append(ctx, evidencebook.Entry{
RecordType: "admission_decision", EpistemicType: evidencebook.DerivedMetric,
SubjectRef: "mesh-node", Statement: json.RawMessage(block),
})
if err != nil {
log.Fatal(err)
}
if _, err := me.book.Checkpoint(ctx); err != nil {
log.Fatal(err)
}
fmt.Println("sealed:", sealed.Header.RecordType)
}
func readJSON(path string, v any) {
raw, err := os.ReadFile(path)
if err != nil {
log.Fatal(err)
}
if err := json.Unmarshal(raw, v); err != nil {
log.Fatal(err)
}
}
Output: staple: standard_history/1, 2 bands, 0 of 0 disputes open pack: asg/admission_baseline/1.0.0 t1-stranger-climbs-on-its-own-card: GO at T1, decided by rows t1-no-card-asks: ASK at T0, decided by rows, ask served_summary/1 within 86400s (request recorded: true) t1-card-refused-limits: LIMIT at T0, decided by rows sealed: admission_decision
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
Example (Staple) ¶
Path 4, History cards that staple (docs/design/254-shelf.md §3): a Goose agent buys inference from a Mesh node. Each party keeps its own shelf and answers its own History; a relying party joins the two parties' evidence of the deal on the deal id, and joins a Mesh node to its operator's own Goose agent only through a controller binding.
The records are x-deal-v0 steps (dealprofile), the chain a Goose buyer seals (python/examples/goose). The keys are derived from fixed seeds.
// SPDX-License-Identifier: Apache-2.0
package main
import (
"context"
"crypto/ed25519"
"crypto/sha256"
"database/sql"
"encoding/hex"
"encoding/json"
"fmt"
"log"
"net/url"
"os"
"path/filepath"
"strings"
"time"
aacbundle "github.com/action-state-group/agent-action-capsule/go/bundle"
"github.com/action-state-group/agent-action-capsule/go/canonical"
"github.com/action-state-group/agent-action-capsule/go/evidencerequest"
"github.com/action-state-group/agent-action-capsule/go/standardhistory"
emit "github.com/action-state-group/capsule-emit/go"
"github.com/action-state-group/capsule-emit/go/artifact"
artifactsqlite "github.com/action-state-group/capsule-emit/go/artifact/sqlite"
"github.com/action-state-group/evidencebook"
"github.com/action-state-group/evidencebook/dealprofile"
_ "modernc.org/sqlite"
)
// party is one key's shelf: every log the key answers for, in one file
// (docs/design/254-shelf.md §2.1).
type party struct {
operator string
shelf *evidencebook.Shelf
db *sql.DB
originals *artifactsqlite.Store
key ed25519.PrivateKey
keys evidencebook.ResponderKeys
now time.Time
}
// openParty opens a shelf in dir under keys derived from seed. Real
// deployments load their keys from storage; fixed seeds keep the output
// stable.
func openParty(ctx context.Context, dir, operator string, seed byte) *party {
key := func(b byte) ed25519.PrivateKey {
s := make([]byte, ed25519.SeedSize)
for i := range s {
s[i] = b + byte(i)
}
return ed25519.NewKeyFromSeed(s)
}
p := &party{operator: operator, key: key(seed), now: time.Date(2026, 10, 27, 12, 0, 0, 0, time.UTC)}
checkpointKey := key(seed + 100)
if err := os.MkdirAll(dir, 0o700); err != nil {
log.Fatal(err)
}
path := filepath.Join(dir, "shelf.db")
db, err := sql.Open("sqlite", (&url.URL{Scheme: "file", Path: path}).String())
if err != nil {
log.Fatal(err)
}
db.SetMaxOpenConns(1)
p.db = db
signer, err := evidencebook.NewEd25519Signer(p.key)
if err != nil {
log.Fatal(err)
}
if p.originals, err = artifactsqlite.New(db, operator, []ed25519.PublicKey{signer.PublicKey()}); err != nil {
log.Fatal(err)
}
if err := p.originals.Init(ctx); err != nil {
log.Fatal(err)
}
if p.shelf, err = evidencebook.OpenSQLiteShelf(ctx, evidencebook.ShelfConfig{
Path: path, Operator: operator, Signer: signer, CheckpointKey: checkpointKey, Originals: p.originals,
Now: func() time.Time { return p.now },
// No authenticated index records: every record on a log is a step
// or an observation the party sealed.
AuthenticatedIndexes: func(string) []evidencebook.AuthenticatedIndex { return []evidencebook.AuthenticatedIndex{} },
}); err != nil {
log.Fatal(err)
}
p.keys = evidencebook.ResponderKeys{
Signer: evidencebook.KeyID(signer),
Checkpoint: hex.EncodeToString(checkpointKey.Public().(ed25519.PublicKey)),
}
return p
}
func (p *party) release() {
if err := p.shelf.Release(); err != nil {
log.Fatal(err)
}
if err := p.db.Close(); err != nil {
log.Fatal(err)
}
}
func (p *party) book(ctx context.Context, id string) *evidencebook.Book {
book, err := p.shelf.Open(ctx, id)
if err != nil {
log.Fatal(err)
}
return book
}
// keyHex is the party's key as a controller binding names it.
func (p *party) keyHex() string { return hex.EncodeToString(p.key.Public().(ed25519.PublicKey)) }
// stepRef names an earlier step of the same deal by its seq (1-based).
type stepRef struct {
rel string
seq int
}
// dealStep is one x-deal-v0 record before its chain members are filled.
type dealStep struct {
recordType string
body map[string]any
refs []stepRef
block map[string]any
decide *dealprofile.Decide
}
// sealDeal seals steps, in order, as the records of book: each an x-deal-v0
// record the profile's checks accept, sealed by the party as a Capsule
// carrying the deal id (dealprofile.StepCapsule), and committed as the
// book's record (Book.AppendCapsule). It returns the records.
func (p *party) sealDeal(ctx context.Context, book *evidencebook.Book, dealID, peer string, steps []dealStep) []evidencebook.Record {
identity, err := emit.NewEd25519SigningIdentity(p.key)
if err != nil {
log.Fatal(err)
}
ref := func(digest string) map[string]any {
return map[string]any{"type": dealprofile.RecordRef, "digest_alg": "SHA-256", "digest": digest}
}
var digests []string
var sealed []evidencebook.Record
for i, s := range steps {
block := map[string]any{
"profile": dealprofile.Profile, "canonicalization": dealprofile.Canonicalization,
"deal_id": dealID, "record_type": s.recordType, "seq": i + 1, "at": p.now.Format(time.RFC3339),
}
if i > 0 {
block["prev"] = ref(digests[i-1])
block["baseline_ref"] = ref(digests[0])
}
var refs []any
for _, r := range s.refs {
named := ref(digests[r.seq-1])
named["rel"] = r.rel
refs = append(refs, named)
}
if refs != nil {
block["refs"] = refs
}
for k, v := range s.block {
block[k] = v
}
payload, digest, err := dealprofile.Encode(map[string]any{"x-deal-v0": block, "body": s.body}, []string{peer})
if err != nil {
log.Fatal(err)
}
digests = append(digests, digest)
in := dealprofile.StepInput{DealID: dealID, Seq: int64(i + 1), Operator: p.operator, Developer: "staple-example",
At: p.now, Decide: s.decide, Local: s.recordType}
if i > 0 {
in.Parent = &emit.Chain{ParentCapsuleID: sealed[i-1].RecordID, Relation: dealprofile.RelationFollows}
}
capsule, header, err := dealprofile.StepCapsule(in)
if err != nil {
log.Fatal(err)
}
entry := evidencebook.Entry{RecordType: header.RecordType, EpistemicType: evidencebook.EpistemicType(header.EpistemicType),
SubjectRef: header.SubjectRef, Fields: header.Fields}
for _, cited := range header.Cites {
entry.Links = append(entry.Links, evidencebook.Link{Type: evidencebook.Cites, Target: cited})
}
seal := func(_ evidencebook.Header, headerJSON []byte) (emit.Result, error) {
c := capsule
c.Extensions = append(append([]emit.Extension(nil), capsule.Extensions...),
emit.Extension{Name: evidencebook.RecordHeaderMember, Value: headerJSON})
return emit.Seal(emit.SealInput{Capsule: c, Identity: identity, Payload: json.RawMessage(payload)})
}
originals := []artifact.Artifact{{Name: "payload", Binding: artifact.PayloadDigest, State: artifact.Present, Content: payload}}
record, err := book.AppendCapsule(ctx, entry, originals, seal)
if err != nil {
log.Fatal(err)
}
sealed = append(sealed, record)
p.now = p.now.Add(time.Minute)
}
if _, err := book.Checkpoint(ctx); err != nil {
log.Fatal(err)
}
return sealed
}
// historyCard has relying asks book's holder for history_card/1 over the
// book's full history, and returns what the relying party recorded.
func historyCard(ctx context.Context, relying *evidencebook.Book, holder *party, book *evidencebook.Book) string {
parsed := evidencerequest.ParseRequest(evidencebook.Message{
Octets: []byte(requestCaseByID("pos-derivation-history-card").RequestJSON), MediaType: evidencebook.MediaTypeJSON})
if parsed.Reason != "" {
log.Fatal(parsed.Reason)
}
req := parsed.Request
req.Nonce = "" // the book draws a fresh one per request
one := uint64(1)
req.Coverage = evidencebook.Coverage{MinFreshness: &evidencebook.Freshness{Size: &one}}
sent, err := relying.Request(ctx, req, holder.keys.Signer)
if err != nil {
log.Fatal(err)
}
reply, _, err := book.Respond(ctx, sent.Message(), evidencebook.RespondOptions{Policy: evidencebook.DefaultSharePolicy()})
if err != nil {
log.Fatal(err)
}
received, err := relying.RecordResponse(ctx, sent.RecordID, reply.Message, holder.keys)
if err != nil {
log.Fatal(err)
}
var outcome evidencebook.ResponseStatement
if err := json.Unmarshal(received.Header.Statement, &outcome); err != nil {
log.Fatal(err)
}
return outcome.Outcome
}
// member is one party's half of the deal as a composed/v1 member: an
// Evidence Bundle rooted at the record, as the answer to the request whose
// digest the relying party holds.
func member(ctx context.Context, id, observer string, book *evidencebook.Book, root evidencebook.Record) map[string]any {
built, err := book.Bundle(ctx, evidencebook.BundleRequest{Root: root.RecordID})
if err != nil {
log.Fatal(err)
}
body, err := aacbundle.Decode(built.JSON)
if err != nil {
log.Fatal(err)
}
digest, err := aacbundle.BundleDigest(body)
if err != nil {
log.Fatal(err)
}
request := sha256.Sum256([]byte("the relying party's request for " + id))
return map[string]any{"id": id, "observer": observer, "request_digest": hex.EncodeToString(request[:]),
"outcome": "artifact", "digest": digest, "bundle": body}
}
// bindingRecord is a same_controller_asserted controller binding record
// (draft-mih-zhang-agent-disclosure-bundle-02, "Controller Binding
// Records"), signed by both keys.
func bindingRecord(a, b *party, issued time.Time) map[string]any {
first, second := a, b
if first.keyHex() > second.keyHex() {
first, second = second, first
}
at := func(t time.Time) string { return t.UTC().Format("2006-01-02T15:04:05Z") }
record := map[string]any{
"binding_version": "controller-binding/0", "claim": "same_controller_asserted", "method": "dual_signature/0",
"keys": []any{first.keyHex(), second.keyHex()}, "issued_at": at(issued), "not_before": at(issued),
"not_after": at(issued.AddDate(1, 0, 0)), "revocation": "revocation_statement/0", "nonce": "staple-example-binding",
}
input, err := canonical.JCS(record)
if err != nil {
log.Fatal(err)
}
record["sigs"] = []any{
map[string]any{"key_id": first.keyHex(), "sig": hex.EncodeToString(ed25519.Sign(first.key, input))},
map[string]any{"key_id": second.keyHex(), "sig": hex.EncodeToString(ed25519.Sign(second.key, input))},
}
return record
}
func digestOf(s string) string {
sum := sha256.Sum256([]byte(s))
return hex.EncodeToString(sum[:])
}
// Path 4, History cards that staple (docs/design/254-shelf.md §3): a Goose
// agent buys inference from a Mesh node. Each party keeps its own shelf and
// answers its own History; a relying party joins the two parties' evidence
// of the deal on the deal id, and joins a Mesh node to its operator's own
// Goose agent only through a controller binding.
//
// The records are x-deal-v0 steps (dealprofile), the chain a Goose buyer
// seals (python/examples/goose). The keys are derived from fixed seeds.
func main() {
ctx := context.Background()
dir, err := os.MkdirTemp("", "evidencebook-staple")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
goose := openParty(ctx, filepath.Join(dir, "goose"), "goose", 11)
mesh := openParty(ctx, filepath.Join(dir, "mesh"), "mesh", 21)
owner := openParty(ctx, filepath.Join(dir, "owner"), "owner", 31) // the Mesh operator's own Goose agent
relying := openNode(ctx, filepath.Join(dir, "relying"), "relying", 41)
defer goose.release()
defer mesh.release()
defer owner.release()
defer relying.book.Release()
const dealID = "deal-7a41c09e5b2d8f36"
// Each party names its counterparty only by a fingerprint under its own
// deal key (x-deal-v0 §4); the raw key never enters a record.
counterparty := func(storeSecret, peer string) map[string]any {
payee, err := dealprofile.Fingerprint(dealprofile.DealKey([]byte(storeSecret), dealID), "payee", peer)
if err != nil {
log.Fatal(err)
}
return map[string]any{"fp_alg": dealprofile.FPAlg, "ids": map[string]any{"payee": payee}}
}
terms := map[string]any{"item": "inference", "price_minor": 1200, "currency": "USD"}
recourse := map[string]any{"rail": "lightning", "refundable": false}
// The Goose buyer: one book per deal, a node book, and the cadence that
// commits every book's checkpoint at each tick.
dealBook := goose.book(ctx, "deal/"+dealID)
// Each text is committed under its own nonce, drawn fresh by the party
// that wrote it; fixed nonces keep this output stable.
commit := func(nonce, text string) string {
c, err := dealprofile.CommitText(digestOf(nonce), text)
if err != nil {
log.Fatal(err)
}
return c
}
seller := counterparty("the Goose agent's deal store secret", mesh.keys.Signer)
gooseHalf := goose.sealDeal(ctx, dealBook, dealID, mesh.keys.Signer, []dealStep{
{recordType: dealprofile.TypeBaseline, block: map[string]any{"channel": "app_chat", "counterparty": seller},
body: map[string]any{"deal_type": "purchase", "terms": terms, "recourse": recourse,
"intent": map[string]any{"verbatim_commitment": commit("goose asked", "buy one inference call"), "asked": map[string]any{"item": "inference"}, "allowed": []any{"pay"}}}},
{recordType: dealprofile.TypeCheck, block: map[string]any{"counterparty": seller},
body: map[string]any{"action": "pay", "action_class": "money.purchase", "amount_minor": 1200, "authorized_max_minor": 1200,
"currency": "USD", "spend_minor": 1200, "spend_authorized_minor": 1200, "taxonomy_version": "6",
"terms": terms, "recourse": recourse}},
{recordType: dealprofile.TypeVerdict, refs: []stepRef{{"checks", 2}},
body: map[string]any{"result": "pass", "differences": []any{}, "options": []any{}, "judge": map[string]any{"kind": "rules"},
"rules": map[string]any{"status": "not_configured"}}},
{recordType: dealprofile.TypeApproval, refs: []stepRef{{"approves", 3}},
body: map[string]any{"choice": "proceed", "proceed": true, "approver": "standing_intent"}},
{recordType: dealprofile.TypeAction, refs: []stepRef{{"authorized_by", 4}}, block: map[string]any{"counterparty": seller},
decide: &dealprofile.Decide{Disposition: emit.Disposition{Decision: "accept", Approver: "policy", VerdictClass: "executed"},
EffectType: "send_payment", Irreversibility: "one_way_consequential"},
body: map[string]any{"action": "pay", "action_class": "money.purchase", "amount_minor": 1200, "currency": "USD",
"direction": "out", "rail": "lightning", "reference_commitment": commit("goose reference", "the payment's reference"), "spend_minor": 1200, "taxonomy_version": "6"}},
})
nodeBook := goose.book(ctx, "goose/node")
if _, err := nodeBook.Append(ctx, evidencebook.Entry{RecordType: "observation", EpistemicType: evidencebook.ObservedEvent,
SubjectRef: "admitted " + mesh.keys.Signer, Payloads: [][]byte{[]byte(`{"admitted":true}`)}}); err != nil {
log.Fatal(err)
}
if _, err := nodeBook.Checkpoint(ctx); err != nil {
log.Fatal(err)
}
cadence, err := goose.shelf.Cadence(ctx, evidencebook.CadenceConfig{LogID: "goose/cadence", NoJitter: true,
Ended: func(context.Context, string) (bool, error) { return false, nil }})
if err != nil {
log.Fatal(err)
}
if _, err := cadence.Tick(ctx, goose.now); err != nil {
log.Fatal(err)
}
// The Mesh seller: its whole history is one stream, which answers at its
// own checkpoint.
meshLog := mesh.book(ctx, "mesh/node")
sellerIntent := func(verbatim string) map[string]any {
return map[string]any{"verbatim_commitment": verbatim, "asked": map[string]any{"item": "inference"},
"allowed": []any{"offer", "commit"}, "party_role": "seller"}
}
meshHalf := mesh.sealDeal(ctx, meshLog, dealID, goose.keys.Signer, []dealStep{
{recordType: dealprofile.TypeBaseline, block: map[string]any{"channel": "app_chat",
"counterparty": counterparty("the Mesh node's deal store secret", goose.keys.Signer)},
body: map[string]any{"deal_type": "purchase", "terms": terms, "recourse": recourse,
"intent": sellerIntent(commit("mesh asked", "serve inference at the listed price"))}},
})
// The Mesh operator's own Goose agent recorded the same sale under its
// own key.
ownerBook := owner.book(ctx, "deal/"+dealID)
ownerHalf := owner.sealDeal(ctx, ownerBook, dealID, goose.keys.Signer, []dealStep{
{recordType: dealprofile.TypeBaseline, block: map[string]any{"channel": "app_chat",
"counterparty": counterparty("the operator's agent's deal store secret", goose.keys.Signer)},
body: map[string]any{"deal_type": "purchase", "terms": terms, "recourse": recourse,
"intent": sellerIntent(commit("owner asked", "sell inference from my node"))}},
})
// history_card/1 per log: the relying party asks each log's holder and
// verifies the answer under the holder's pinned keys.
fmt.Println("history_card/1 goose deal/" + dealID + ": " + historyCard(ctx, relying.book, goose, dealBook))
fmt.Println("history_card/1 goose goose/node: " + historyCard(ctx, relying.book, goose, nodeBook))
fmt.Println("history_card/1 mesh mesh/node: " + historyCard(ctx, relying.book, mesh, meshLog))
// The Mesh node's History, inference-service-history/0: the exchanges it
// served in the week that closes at 2026-11-02, checked with the Go reader
// (inferencehistory) under the node's pinned keys.
meshServes(ctx, meshLog, "model-a", 8)
meshServes(ctx, meshLog, "model-b", 4)
boundary := time.Date(2026, 11, 2, 0, 0, 0, 0, time.UTC)
lines, answer := meshHistory(ctx, mesh, meshLog, boundary)
for _, line := range lines {
fmt.Println(line)
}
// Path 5: the Goose agent reads that answer into an admission decision.
for _, line := range admitMeshNode(answer, boundary.Add(time.Hour)) {
fmt.Println(line)
}
// An answer the History check rejected, or whose pin is not the one the
// request sent, is unverifiable: card-verified fails and the 12 USD deal
// asks for a new card (ASK at T0); the 5 USD deal needs no card.
rejected, repinned := answer, answer
rejected.accepted = false
repinned.pin = strings.Repeat("0", 64)
for _, bad := range []meshAnswer{rejected, repinned} {
for _, line := range admitMeshNode(bad, boundary.Add(time.Hour)) {
if strings.HasPrefix(line, "mesh/node") || strings.Contains(line, "card-verified") {
fmt.Println(line)
}
}
}
// Goose's History: standard_history/1 as of a cadence tick, each book
// bounded by the checkpoint the tick carries, one deal entry per deal
// book. A relying party that holds the same inputs checks every SH
// property against them.
anchor, err := cadence.StandardHistoryAnchor(ctx, 0)
if err != nil {
log.Fatal(err)
}
var in dealprofile.HistoryInput
held, err := dealBook.Query(ctx, evidencebook.Filter{})
if err != nil {
log.Fatal(err)
}
for _, r := range held[:anchor.Extents["deal/"+dealID]] {
originals, err := goose.originals.Get(ctx, r.RecordID)
if err != nil {
log.Fatal(err)
}
at, err := time.Parse(time.RFC3339Nano, r.Header.CommittedAt)
if err != nil {
log.Fatal(err)
}
for _, a := range originals.Artifacts {
if a.Name == "payload" {
in.Records = append(in.Records, dealprofile.HistoryRecord{Payload: a.Content, CommittedAt: at})
}
}
}
entry, agreed, err := dealprofile.StandardHistoryDeal(in)
if err != nil || !agreed {
log.Fatalf("deal entry: %v %v", agreed, err)
}
deals := []standardhistory.Deal{entry}
policy := standardhistory.Policy{Digest: digestOf("the Goose agent's disclosure policy"), Window: standardhistory.Window{Months: 3}}
card, err := evidencebook.DeriveStandardHistory("person", anchor.AsOf, policy, deals)
if err != nil {
log.Fatal(err)
}
properties, err := standardhistory.Check(card, &policy, &anchor.AsOf, deals)
if err != nil {
log.Fatal(err)
}
passed := 0
for _, p := range standardhistory.Properties {
if properties[p] == standardhistory.Pass {
passed++
}
}
fmt.Printf("standard_history/1 goose at tick %d: %d deal, %d of %d properties PASS\n",
anchor.Tick.N, len(deals), passed, len(standardhistory.Properties))
// The staple: the relying party composes each party's half of the deal
// in composed/v1 and joins them on the deal id every half's Capsule
// carries. The Mesh node and its operator's agent are joined only by
// the binding record both keys signed.
binding := bindingRecord(mesh, owner, time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC))
unsigned := map[string]any{}
for k, v := range binding {
if k != "sigs" {
unsigned[k] = v
}
}
bindingInput, err := canonical.JCS(unsigned)
if err != nil {
log.Fatal(err)
}
bindingDigest := sha256.Sum256(bindingInput)
pointer, keyPointer := "/"+dealprofile.DealIDMember, "/key_id"
identifier := digestOf(dealID)
block := map[string]any{
"observers": []any{
map[string]any{"id": "goose", "role": "buyer", "custody_domain": "goose"},
map[string]any{"id": "mesh", "role": "seller", "custody_domain": "mesh-operator"},
map[string]any{"id": "owner", "role": "seller-agent", "custody_domain": "mesh-operator"},
},
"members": []any{
member(ctx, "goose-half", "goose", dealBook, gooseHalf[len(gooseHalf)-1]),
member(ctx, "mesh-half", "mesh", meshLog, meshHalf[0]),
member(ctx, "owner-half", "owner", ownerBook, ownerHalf[0]),
},
"joins": []any{
map[string]any{"members": []any{"goose-half", "mesh-half"}, "basis": "pre_agreed_identifier", "state": "agree",
"pointer": pointer, "identifier_digest": identifier},
map[string]any{"members": []any{"mesh-half", "owner-half"}, "basis": "controller_binding", "state": "agree",
"pointer": keyPointer, "identifier_digest": hex.EncodeToString(bindingDigest[:])},
},
}
// The digest covers the declarations only, not the digest member.
block["composed_digest"] = strings.Repeat("0", 64)
if block["composed_digest"], err = aacbundle.ComposedDigest(block); err != nil {
log.Fatal(err)
}
// A block travels as JSON; the verifier reads it back as JSON values.
carried, err := json.Marshal(block)
if err != nil {
log.Fatal(err)
}
raw, err := aacbundle.Decode(carried)
if err != nil {
log.Fatal(err)
}
result := aacbundle.VerifyComposed(raw, aacbundle.Options{ControllerBindings: []map[string]interface{}{binding}})
fmt.Println("composed/v1:", result.Status)
for _, m := range result.Members {
fmt.Printf("member %s: digest %s, graph closure %s, membership %s\n", m.ID, m.Digest,
m.Bundle.GraphClosure.Status, m.Bundle.PerRecordMembership.Status)
}
for i, j := range result.Joins {
c := result.Corroboration[i]
why := c.Qualifier
if c.Result == "redundant" {
why = strings.Join(c.Reasons, ", ")
}
fmt.Printf("join %s + %s on %s: %s, %s (%s)\n", j.Members[0], j.Members[1], j.Basis, j.Derived, c.Result, why)
}
// Without the binding record, nothing links the two keys: the join is
// not derivable, and the block does not pass.
unbound := aacbundle.VerifyComposed(raw, aacbundle.Options{})
fmt.Println("composed/v1 without the binding record:", unbound.Status, unbound.Joins[1].Result)
}
Output: history_card/1 goose deal/deal-7a41c09e5b2d8f36: artifact history_card/1 goose goose/node: artifact history_card/1 mesh mesh/node: artifact inference-service-history/0 mesh/node at 2026-11-02T00:00:00Z: accepted true artifact_form PASS definition_binding PASS definition_form PASS history_card_content PASS labels PASS period_alignment PASS period_anchor PASS period_floor PASS units PASS pack: asg/admission_node_baseline/1.0.0 mesh/node, a 5 USD deal: GO at T0, decided by rows deny-list pass confirmed-exchanges not_read coverage stream_interval, population NOT_CHECKED mesh/node, a 12 USD deal: LIMIT at T0, decided by rows deny-list pass confirmed-exchanges not_read card-verified pass card-fresh pass served-periods fail (1 of 4, self-reported) witness-receipts not_read coverage stream_interval, population NOT_CHECKED mesh/node, a 5 USD deal: GO at T0, decided by rows mesh/node, a 12 USD deal: ASK at T0, decided by rows card-verified fail mesh/node, a 5 USD deal: GO at T0, decided by rows mesh/node, a 12 USD deal: ASK at T0, decided by rows card-verified fail (anchor_match) standard_history/1 goose at tick 1: 1 deal, 6 of 6 properties PASS composed/v1: pass member goose-half: digest reproduced, graph closure pass, membership pass member mesh-half: digest reproduced, graph closure pass, membership pass member owner-half: digest reproduced, graph closure pass, membership pass join goose-half + mesh-half on pre_agreed_identifier: agree, corroborating (custody_declared) join mesh-half + owner-half on controller_binding: agree, redundant (same_custody_domain, controller_binding) composed/v1 without the binding record: withheld not_derivable
Index ¶
- Constants
- Variables
- func CheckHistoryCard2(artifact []byte, anchor string) error
- func DeriveStandardHistory(holderKind string, asOf standardhistory.AsOf, policy standardhistory.Policy, ...) ([]byte, error)
- func DerivedFillers(seed []byte, count uint64, used map[uint64]bool) (map[uint64][]byte, error)
- func EncodeRequest(r EvidenceRequest, mediaType string) ([]byte, error)
- func EntryID(doc any) ([32]byte, []byte, error)
- func KeyID(s Signer) string
- func MigratePayloadDir(ctx context.Context, store Store, originals ArtifactStore, dir string) (int, error)
- func OpeningsFor(kind string, audience Audience) (link, status bool, err error)
- func ReadClose(h Header) (v1 *CloseStatement, legacy *LegacyCloseStatement, err error)
- func ReconcileHalves(a, b HalfSet, compare Comparator) ([]PairResult, Tallies)
- func ReconcileHalvesWith(a, b HalfSet, check ContentCheck) ([]PairResult, Tallies)
- func SamePayloadCommitments(a, b Half) bool
- func VerifyKeyRange(root IndexRoot, lo, hi string, proof KeyRangeProof) ([]string, error)
- func VerifyLeaf(root IndexRoot, proof LeafProof) error
- func VerifyOpening(commitment string, o Opening) bool
- func VerifyOpenings(fact BookFact, link, status *FactOpening) error
- type A2AOptions
- type A2ARequest
- type A2AResponse
- type A2AServer
- type AbsenceRecord
- type AbsenceWindow
- type AfterReceiveProfile
- type Anchor
- type AnsweredStatement
- type ArtifactStore
- type AskOutcome
- type AskedExchange
- type AskedHalf
- type AskedRecord
- type AskedReport
- type AskedResult
- type AskedState
- type AskedVerdict
- type Audience
- type AudienceFact
- type AuthenticatedIndex
- type BatchEntry
- type BeforeStampProvider
- type Book
- func (b *Book) A2A(opts A2AOptions) (*A2AServer, error)
- func (b *Book) Acknowledge(ctx context.Context, peerCloseID, counterparty string) (Record, error)
- func (b *Book) AdoptPolicy(ctx context.Context, holder string) (DisclosurePolicy, Record, error)
- func (b *Book) Append(ctx context.Context, entry Entry) (Record, error)
- func (b *Book) AppendAt(ctx context.Context, seq uint64, entry Entry) (Record, error)
- func (b *Book) AppendCapsule(ctx context.Context, entry Entry, originals []artifact.Artifact, ...) (Record, error)
- func (b *Book) ApplyPolicyChange(ctx context.Context, c PolicyChange) (DisclosurePolicy, []Record, error)
- func (b *Book) Bundle(ctx context.Context, req BundleRequest) (Bundle, error)
- func (b *Book) Checkpoint(ctx context.Context) (Checkpoint, error)
- func (b *Book) CheckpointAt(ctx context.Context, at time.Time) (Checkpoint, error)
- func (b *Book) CheckpointCovers(ctx context.Context, seq uint64) (bool, error)
- func (b *Book) Checkpoints(ctx context.Context) ([]Checkpoint, error)
- func (b *Book) Close(ctx context.Context, in CloseInput) (Record, error)
- func (b *Book) CommitRetention(ctx context.Context, subject Subject, until time.Time) (Record, error)
- func (b *Book) DisclosurePolicy() (DisclosurePolicy, error)
- func (b *Book) Discover(ctx context.Context, query string, limit int) (Candidates, error)
- func (b *Book) Doctor(ctx context.Context, opts DoctorOptions) ([]DoctorFinding, error)
- func (b *Book) Get(_ context.Context, recordID string) (Record, error)
- func (b *Book) IndexState(ctx context.Context) (string, error)
- func (b *Book) Info() (string, SubstrateInfo)
- func (b *Book) MCP(opts MCPOptions) (*MCPServer, error)
- func (b *Book) Manifest(opts ManifestOptions) ([]byte, error)
- func (b *Book) Opening(ctx context.Context, recordID, field string) (Opening, error)
- func (b *Book) ProveKeyRange(ctx context.Context, index, lo, hi string) (KeyRangeAnswer, error)
- func (b *Book) Query(ctx context.Context, filter Filter) ([]Record, error)
- func (b *Book) Rebuild(ctx context.Context) (string, error)
- func (b *Book) Rebut(ctx context.Context, peerCloseID, counterparty string, reason json.RawMessage) (Record, error)
- func (b *Book) Reconcile(ctx context.Context, in ReconcileInput) (Reconciliation, error)
- func (b *Book) RecordAbsence(ctx context.Context, requestRecordID string, windowEnd time.Time, route string) (Record, error)
- func (b *Book) RecordResponse(ctx context.Context, requestRecordID string, reply Message, keys ResponderKeys) (Record, error)
- func (b *Book) RegisterDerivation(def DerivationDefinition) (string, error)
- func (b *Book) Release() error
- func (b *Book) ReplyOctets(ctx context.Context, responseRecordID string) ([]byte, error)
- func (b *Book) Request(ctx context.Context, req EvidenceRequest, responder string) (SentRequest, error)
- func (b *Book) RequestSent(ctx context.Context, request Message, responder string) (SentRequest, error)
- func (b *Book) ResolvePayload(ctx context.Context, recordID, digest string) ([]byte, error)
- func (b *Book) Respond(ctx context.Context, request Message, opts RespondOptions) (Reply, Record, error)
- func (b *Book) Retention(_ context.Context, recordID string) (RetentionState, error)
- func (b *Book) SealResult(ctx context.Context, statement json.RawMessage, subject string, links []Link, ...) (sealed Record, already bool, checkpoint uint64, err error)
- func (b *Book) SealUnavailableWindow(ctx context.Context, start, end time.Time, reasonClass string) (Record, error)
- func (b *Book) Sealed(ctx context.Context, recordID string) (StoredRecord, error)
- func (b *Book) SetRetention(ctx context.Context, recordID string, state RetentionState, reason string) (Record, error)
- func (b *Book) ShowAbsence(_ context.Context, absenceRecordID, responderKey string, ...) (evidencerequest.AbsenceDisplay, error)
- func (b *Book) Size() uint64
- func (b *Book) StandardCardDeals(ctx context.Context) ([]string, error)
- func (b *Book) StandardHistoryBundle(ctx context.Context, at Checkpoint, req StandardHistoryBundleRequest) (Bundle, error)
- func (b *Book) Staple(ctx context.Context, derivation string) (Staple, error)
- func (b *Book) StapleForDeal(ctx context.Context, derivation, deal string) (Staple, error)
- type BookFact
- type BookStatusProvider
- type Bundle
- type BundleCheckpoint
- type BundleClaims
- type BundleDiff
- type BundleRequest
- type CLLSubstrate
- func (s *CLLSubstrate) Append(ctx context.Context, recordID string, at time.Time) (uint64, error)
- func (s *CLLSubstrate) Checkpoint(ctx context.Context, now time.Time) (Checkpoint, error)
- func (s *CLLSubstrate) CheckpointWhole(ctx context.Context, now time.Time) (Checkpoint, error)
- func (s *CLLSubstrate) Entries(ctx context.Context, afterSeq uint64, limit int) ([]SubstrateEntry, error)
- func (s *CLLSubstrate) Info() SubstrateInfo
- func (s *CLLSubstrate) Latest(ctx context.Context) (Checkpoint, error)
- func (s *CLLSubstrate) ProveConsistency(ctx context.Context, older, newer Checkpoint) (ConsistencyEvidence, error)
- func (s *CLLSubstrate) ProveInclusion(ctx context.Context, seq uint64, at Checkpoint) (InclusionEvidence, error)
- func (s *CLLSubstrate) ProveInterval(ctx context.Context, firstSeq uint64, at Checkpoint) (IntervalEvidence, error)
- func (s *CLLSubstrate) Release() error
- func (s *CLLSubstrate) Size(ctx context.Context) (uint64, error)
- type Cadence
- func (c *Cadence) Chain(ctx context.Context, statement []byte) (map[string]any, error)
- func (c *Cadence) Get(ctx context.Context, n uint64) (CadenceTick, error)
- func (c *Cadence) Handover(ctx context.Context, n uint64) (Handover, error)
- func (c *Cadence) HistoryCard(ctx context.Context, n uint64) (Staple, error)
- func (c *Cadence) ImportLegacy(ctx context.Context, legacy LegacyCadence) error
- func (c *Cadence) Last(ctx context.Context) (tick CadenceTick, ok bool, err error)
- func (c *Cadence) Live(ctx context.Context) ([]string, error)
- func (c *Cadence) Migrate(ctx context.Context, now time.Time) error
- func (c *Cadence) Migrated(ctx context.Context) (bool, error)
- func (c *Cadence) Stamp(ctx context.Context, now time.Time) (TickResult, error)
- func (c *Cadence) StampProof(ctx context.Context, bookID string, n uint64, audience Audience) (StampProof, error)
- func (c *Cadence) StandardHistoryAnchor(ctx context.Context, n uint64) (StandardHistoryAnchor, error)
- func (c *Cadence) StandardHistoryBundles(ctx context.Context, anchor StandardHistoryAnchor, ...) (map[string]Bundle, error)
- func (c *Cadence) Tick(ctx context.Context, now time.Time) (TickResult, error)
- func (c *Cadence) Witnessed(ctx context.Context, n uint64, receipt WitnessReceipt) (WitnessCheck, error)
- func (c *Cadence) WitnessedTick(ctx context.Context, logID, checkpointSHA256 string, mmrSize uint64) (extent string, tick CadenceTick, leaf TickLeaf, err error)
- type CadenceConfig
- type CadenceLog
- type CadenceTick
- type Candidates
- type CapsuleSealer
- type Checkpoint
- type CloseInput
- type ClosePeriod
- type CloseReconcile
- type CloseStatement
- type CloseStatus
- type CommittedLog
- type Comparator
- type CompletenessCertificate
- type Config
- type ConsistencyEvidence
- type ContentCheck
- type ContentVerdict
- type Correlation
- type CountedPrefix
- type Coverage
- type CoverageGiven
- type DealHalf
- type DealMapping
- type DealReconcile
- type DealReconcileInput
- type DealReconcileResult
- type DerivationDefinition
- type DisclosurePolicy
- func (p DisclosurePolicy) Apply(c PolicyChange) ([]PolicyStep, error)
- func (p DisclosurePolicy) Digest() (string, error)
- func (p DisclosurePolicy) Rows() []SettingRow
- func (p DisclosurePolicy) SharePolicy() SharePolicy
- func (p DisclosurePolicy) StandardPolicy() (standardhistory.Policy, error)
- func (p DisclosurePolicy) Validate() error
- type DisclosureStatement
- type DiscoveryIndex
- type DoctorFinding
- type DoctorOptions
- type DoctorTransport
- type DoctorWitness
- type Ed25519Signer
- type Entry
- type Envelope
- type EpistemicType
- type Evidence
- type EvidenceRef
- type EvidenceRequest
- type ExchangeState
- type FactInput
- type FactOpening
- type FileStore
- func (s *FileStore) Checkpoints(context.Context) ([]Checkpoint, error)
- func (s *FileStore) GetRecord(_ context.Context, recordID string) (StoredRecord, error)
- func (s *FileStore) PutCheckpoint(ctx context.Context, cp Checkpoint) error
- func (s *FileStore) PutRecord(ctx context.Context, record StoredRecord) error
- func (s *FileStore) Records(context.Context) ([]StoredRecord, error)
- func (s *FileStore) Release() error
- type Filter
- type FormatSwitch
- type Freshness
- type Half
- type HalfMapping
- type HalfSet
- type Handover
- type HandoverCheckpoint
- type HandoverConsistency
- type HandoverDocument
- type HandoverLatest
- type HandoverResult
- type HandoverTie
- type HandoverTimes
- type Header
- type HeldLock
- type HeldProof
- type HeldRecord
- type HostLog
- func (l *HostLog) Append(ctx context.Context, write func() error) error
- func (l *HostLog) CutLocal(ctx context.Context, at time.Time) ([]byte, uint64, error)
- func (l *HostLog) LogID() string
- func (l *HostLog) MMRSize(ctx context.Context) (uint64, error)
- func (l *HostLog) Write(ctx context.Context, write func(HostLogStores) error) error
- type HostLogStores
- type InclusionEvidence
- type IndexRoot
- type IntervalEvidence
- type JournalStatus
- type KeyRangeAnswer
- type KeyRangeProof
- type LeafProof
- type LegacyCadence
- type LegacyCloseStatement
- type LegacyLog
- type LifecycleStatement
- type Link
- type LinkType
- type LinkValue
- type LogCoordinates
- type LoggedSize
- type MCPOptions
- type MCPServer
- type MMRInclusion
- type ManifestOptions
- type MaterialRecord
- type Membership
- type Message
- type Opening
- type OperationalIndex
- type PairResult
- type PayloadsMode
- type PeerRecord
- type PolicyChange
- type PolicyStep
- type ProofOutcome
- type RangeWitness
- type Receipt
- type ReceiveBounds
- type ReceiveChanges
- type ReceiveConfig
- type ReceiveProfile
- type ReceiveResult
- type ReceivedPosition
- type ReceivedRecord
- type ReconcileBody
- type ReconcileClaim
- type ReconcileInput
- type Reconciliation
- type Record
- type RecordOutcome
- type RecordSource
- type Refusal
- type Registrar
- type Reply
- type Reproduction
- type RequestLimiter
- type RequestStatement
- type RespondOptions
- type ResponderKeys
- type ResponderPolicy
- type ResponseStatement
- type ResultAggregate
- type ResultPeriod
- type ResultPresentation
- type ResultTallies
- type RetentionState
- type SCITTReceiptSubstrate
- func (s *SCITTReceiptSubstrate) Append(ctx context.Context, recordID string, at time.Time) (uint64, error)
- func (s *SCITTReceiptSubstrate) Checkpoint(ctx context.Context, _ time.Time) (Checkpoint, error)
- func (s *SCITTReceiptSubstrate) Entries(_ context.Context, afterSeq uint64, limit int) ([]SubstrateEntry, error)
- func (s *SCITTReceiptSubstrate) Info() SubstrateInfo
- func (s *SCITTReceiptSubstrate) Latest(context.Context) (Checkpoint, error)
- func (s *SCITTReceiptSubstrate) ProveConsistency(context.Context, Checkpoint, Checkpoint) (ConsistencyEvidence, error)
- func (s *SCITTReceiptSubstrate) ProveInclusion(_ context.Context, seq uint64, at Checkpoint) (InclusionEvidence, error)
- func (s *SCITTReceiptSubstrate) ProveInterval(context.Context, uint64, Checkpoint) (IntervalEvidence, error)
- func (s *SCITTReceiptSubstrate) Release() error
- func (s *SCITTReceiptSubstrate) Size(context.Context) (uint64, error)
- type SQLiteIndex
- func (x *SQLiteIndex) Add(ctx context.Context, record Record) error
- func (x *SQLiteIndex) Find(ctx context.Context, f Filter) ([]string, error)
- func (x *SQLiteIndex) Rebuild(ctx context.Context, source RecordSource) error
- func (x *SQLiteIndex) Release() error
- func (x *SQLiteIndex) StateDigest(ctx context.Context) (string, error)
- type SentCapsule
- type SentRequest
- type SeqRun
- type SetCompleteness
- type SettingRow
- type SharePolicy
- type Shelf
- func (s *Shelf) Books(ctx context.Context) ([]string, error)
- func (s *Shelf) Cadence(ctx context.Context, cfg CadenceConfig) (*Cadence, error)
- func (s *Shelf) CountedPrefix(ctx context.Context, senderKey, logID string) (CountedPrefix, error)
- func (s *Shelf) Evidence(ctx context.Context) ([]Evidence, error)
- func (s *Shelf) ExistingJournal(ctx context.Context) (*Book, error)
- func (s *Shelf) Forget(ctx context.Context, dealID string, now time.Time, ...) ([]string, error)
- func (s *Shelf) HeldByDeal(ctx context.Context, dealID string) ([]HeldRecord, error)
- func (s *Shelf) HeldFirst(ctx context.Context, logID string) ([]HeldRecord, error)
- func (s *Shelf) HeldProofs(ctx context.Context, senderKey, logID string) ([]HeldProof, error)
- func (s *Shelf) HostLog(ctx context.Context, logID string, inCadence bool) (*HostLog, error)
- func (s *Shelf) Journal(ctx context.Context) (*Book, error)
- func (s *Shelf) Legacy(ctx context.Context, logID string) (*LegacyLog, error)
- func (s *Shelf) Open(ctx context.Context, logID string) (*Book, error)
- func (s *Shelf) Openings(ctx context.Context, bookID string, audience Audience) ([]AudienceFact, error)
- func (s *Shelf) Receive(ctx context.Context, record []byte, proof *StampProof) (ReceiveResult, error)
- func (s *Shelf) ReceivedRecordOf(ctx context.Context, digest string) (HeldRecord, error)
- func (s *Shelf) ReceivedRecordStamp(ctx context.Context, bookID, receivedLogID string, position uint64) (n uint64, ok bool, err error)
- func (s *Shelf) ReceivedRecordTime(ctx context.Context, bookID, receivedLogID string, position uint64, ...) (t time.Time, ok bool, err error)
- func (s *Shelf) ReceivedRecordTimeByKey(ctx context.Context, bookID, receivedLogID string, position uint64, ...) (t time.Time, ok bool, err error)
- func (s *Shelf) RecordStamp(ctx context.Context, bookID string, position uint64) (n uint64, ok bool, err error)
- func (s *Shelf) RecordTime(ctx context.Context, bookID string, position uint64, witnesses []string) (t time.Time, ok bool, err error)
- func (s *Shelf) RecordTimeByKey(ctx context.Context, bookID string, position uint64, keyIDs []string) (t time.Time, ok bool, err error)
- func (s *Shelf) Records(ctx context.Context, bookIDs ...string) (ShelfRecords, error)
- func (s *Shelf) Release() error
- func (s *Shelf) SealSent(ctx context.Context, entry Entry, actionID string) (Record, SentCapsule, error)
- func (s *Shelf) StampTime(ctx context.Context, n uint64, witnesses []string) (t time.Time, ok bool, err error)
- func (s *Shelf) StampTimeByKey(ctx context.Context, n uint64, keyIDs []string) (t time.Time, ok bool, err error)
- type ShelfConfig
- type ShelfRecord
- type ShelfRecords
- type Signer
- type SortedMerkleIndex
- func (m *SortedMerkleIndex) Add(key, recordID string) error
- func (m *SortedMerkleIndex) KeyOf(record Record) (string, bool)
- func (m *SortedMerkleIndex) Name() string
- func (m *SortedMerkleIndex) ProveMember(key, recordID string) (LeafProof, error)
- func (m *SortedMerkleIndex) ProveRange(lo, hi string) (KeyRangeProof, error)
- func (m *SortedMerkleIndex) Reset()
- func (m *SortedMerkleIndex) Root() IndexRoot
- type StampBatch
- type StampEntry
- type StampProof
- type StampStatusProvider
- type StandardHistoryAnchor
- type StandardHistoryBundleRequest
- type StandardHistoryCheck
- type StandardHistoryMaterial
- type StandardHistorySource
- type Staple
- type StapleCheck
- type StatusInput
- type StatusProvider
- type Store
- type StoredRecord
- type Subject
- type SubjectKind
- type Substrate
- type SubstrateEntry
- type SubstrateInfo
- type Tallies
- type TickLeaf
- type TickLeaves
- type TickResult
- type TokenIndex
- type UnavailableError
- type VerificationEntry
- type VerifiedBundle
- type VerifiedStampProof
- type WindowLimiter
- type WithheldItem
- type WitnessCheck
- type WitnessReceipt
- type WitnessRow
Examples ¶
Constants ¶
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.
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.
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).
const ( SetComplete = "COMPLETE" SetUndecided = "UNDECIDED" SetNotShown = "NOT_SHOWN" )
Set statuses (DR §6.1).
const ( // PolicyProfile is the document's profile token, loop's. PolicyProfile = "disclosure-policy/0" // PolicyChangeProfile is the executor's input: a base policy, the // fields to change and the steps to run afterwards. PolicyChangeProfile = "policy-change/v1" // DefaultPolicyName is the shipped policy's name. DefaultPolicyName = "Action State default v1" // RecordTypePolicy is the record type of a policy record: the policy // adopted, or one field's change. It is the holder's own rules and is // never served to anyone. RecordTypePolicy = "disclosure_policy" )
The disclosure policy document extends loop's disclosure-policy/0 (the signed file whose digest sits in a holder's commitment). The `policy` member of that file is a DisclosurePolicy. Every change to it is a sealed policy record (RecordTypePolicy); a record already sent is never edited, and a reply already given stays what it was.
const ( HolderPerson = "person" HolderNode = "node" )
Holder kinds a policy is shipped for.
const ( FieldStandardHistory = "standard_history" FieldWindow = "window" FieldStaple = "staple" FieldMoreThanStd = "more_than_standard" FieldReceipt = "receipt" FieldUnsignedAsks = "unsigned_asks_per_week" FieldUnderContract = "under_contract" FieldAskedLogDays = "asked_log_retention_days" )
Settings fields a policy-change/v1 may name, in page order.
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" DoctorProbeStandardCard = "probe_standard_history" )
Doctor checks, one finding each, in the order Doctor reports them.
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.
const ( DoctorAsStranger = "stranger" DoctorAsSigned = "signed" // DoctorSettingPrefix starts the check of each settings row, the same // rows (DisclosurePolicy.Rows) the settings page shows. DoctorSettingPrefix = "setting_" )
Who a doctor probe answers for.
const ( MinHistoryWindow = 1 MaxHistoryWindow = evidencerequest.MaxHistoryWindow DefaultHistoryWindow = 16 )
History card windows: the number of newest checkpoints a /2 card lists in full, chosen by the responder from 1 to 64 (ER -03 §8.1.2).
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.
const ( BindingStream = "evidence-request/1" BindingHTTP = "http" BindingA2A = "a2a" BindingMCP = "mcp" )
Binding tokens a manifest may list (profile §4, §11.4.2).
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.
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.
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.
const ( RequestDraft01 = "draft-mih-agent-evidence-request-01" RequestDraft02 = "draft-mih-agent-evidence-request-02" // RequestDraft03 adds history_card/2 (§8.1.2) and a range on the // checkpoints subject (§8.1.3). RequestDraft03 = "draft-mih-agent-evidence-request-03" )
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).
const ( SubjectFullHistory = evidencerequest.SubjectFullHistory SubjectCheckpoints = evidencerequest.SubjectCheckpoints SubjectRecord = evidencerequest.SubjectRecord SubjectRange = evidencerequest.SubjectRange SubjectCorrelation = evidencerequest.SubjectCorrelation SubjectExchange = evidencerequest.SubjectExchange )
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).
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).
const ( DefaultMaxRequestBytes = 64 << 10 DefaultMaxAnswerItems = 10_000 )
Defaults of the responder's cost policy.
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.
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.
const ( JoinExchangeID = "exchange_id" JoinRequestDigest = "request_digest" )
Join keys a pair can be correlated by, in preference order.
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.
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.
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.
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.
const ( FactKindBook = "book_fact" FactKindJournal = "journal_fact" EntryKindStamp = "stamp" EntryKindFormatSwitch = "format_switch" )
Entry document kinds.
const ( // EvidenceFork is two records a sender signed at one position: a holds // the record held first, b the other. A record whose predecessor is // another than the one held at that position is a fork there too. Only // the first conflicting pair at a position is kept. EvidenceFork = "fork" // EvidenceCheckpoint is two book checkpoints a sender signed for one // log at one size with different roots: a the one held, b the other. // Only the first contradiction at a size is kept. EvidenceCheckpoint = "checkpoint" // EvidenceCheckpointRecords is a book checkpoint whose root the records // held from that sender and log do not recompute: a the checkpoint, b // the JSON array of the records' digests it was recomputed over. Only // the first at a size is kept. EvidenceCheckpointRecords = "checkpoint_records" )
Evidence kinds (shelf_evidence.kind).
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.
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.
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).
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.
const DealReconcileContractRef = "ec:deal-reconcile@1"
DealReconcileContractRef is the contract_ref a claim under this contract carries.
const DefaultClosureDepth = 2
DefaultClosureDepth is the citation depth a bundle follows from its root.
const DefaultDeveloper = "evidencebook"
DefaultDeveloper is the AAC developer value a book writes when none is set.
const DerivationHistoryCard2 = evidencerequest.DerivationHistoryCard2
DerivationHistoryCard2 is history_card/2 (ER -03 §8.1.2): a sample of the stream's checkpoints whose size grows with the logarithm of their number, where history_card/1 lists every one.
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.
const HeaderMember = "agent_input"
HeaderMember is the AAC disclosure member that carries a record header.
const HeaderVersion = 1
HeaderVersion is the version of the record header wire form this package writes and accepts.
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.
const JournalLogID = "journal"
JournalLogID is the log id of the shelf's journal.
const MinimumAbsenceWindow = time.Minute
MinimumAbsenceWindow is the shortest waiting window an absence may claim, measured from when the request was recorded.
const ProfileNone = "none"
ProfileNone is the profile of a book no profile describes; its status is the empty object.
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.
const RecordTypeEvidenceResult = "evidence_result"
RecordTypeEvidenceResult is a sealed Evidence Result v0. SealResult names it; the caller's add writes it.
const RecordTypeRetentionCommitment = "retention_commitment"
RecordTypeRetentionCommitment is the record type of a retention commitment this book has issued.
RecordTypeUnavailableWindow is the record type of an unavailable-window statement this book has sealed (ER -02 §4.7).
const ReproductionClockCaller = "caller"
ReproductionClockCaller is the only clock a Reproduction names: the caller gave the times.
const ShelfFactsFormat = "book_facts/1"
ShelfFactsFormat names the shelf log format the marker switches to.
const ShelfVersion = 1
ShelfVersion is the shelf file version this implementation writes and the only one it opens (shelf_meta.version).
const ShelfVersionFacts = 2
ShelfVersionFacts is the shelf file version once Migrate has switched the shelf to a log of book facts. An older build refuses it.
const SubstrateKindCLL = "cll"
SubstrateKindCLL labels checkpoints and proofs produced by the CLL binding.
const SubstrateKindSCITTReceipt = "scitt-receipt"
SubstrateKindSCITTReceipt labels the receipt-holding binding.
UnavailableWindowText is what a person is shown for an absence an unavailable-window statement covers (Sherlock2's wording, evidencebook#223). It reads as the holder's statement, never as proof of anything; the class, the stated period and the "stated afterwards" label go beside it. The token evidencerequest.UnavailableShownAs is the machine form.
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 ¶
var ( // ErrStaleRound reports a change composed against a policy round that // is no longer in force, as stale_check reports a stale approval. ErrStaleRound = errors.New("evidencebook: stale settings round") // ErrNeverList reports a change that names a never-list item. ErrNeverList = errors.New("evidencebook: never-list item") // ErrNoPolicy reports a book that has adopted no disclosure policy. ErrNoPolicy = errors.New("evidencebook: no disclosure policy adopted") )
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 = 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") // ErrOverLimit reports a Cadence.HistoryCard that would list more ticks // than DefaultMaxAnswerItems, or a received record past one of the // store's bounds (ReceiveBounds). A Book's card over its limit is a // refusal (Book.Staple reports ErrInvalid), not this error. ErrOverLimit = errors.New("evidencebook: over the item limit") // ErrRefused reports a received record or stamp proof whose sender may // not push it (Shelf.Receive): nothing of it is stored. ErrRefused = errors.New("evidencebook: refused") // ErrDeleted reports a received record deleted under the holder's // retention: the store keeps its tombstone, so it is deleted, not missing. ErrDeleted = errors.New("evidencebook: deleted") // ErrBusy reports a received offer refused because the holder's books // kept changing while room was made for it (Shelf.Receive): sending it // again later may succeed. ErrBusy = errors.New("evidencebook: busy; try again") )
var DefaultReceiveBounds = ReceiveBounds{
MaxRecordBytes: 1 << 20, MaxRecordsPerLog: 100000,
MaxOffersPerSender: 16, MaxOfferBytesPerSender: 4 << 20,
MaxOffers: 1024, MaxOfferBytes: 64 << 20,
MaxOfferEvidencePerSender: 16, MaxOfferEvidence: 1024,
}
DefaultReceiveBounds are the store's bounds when none is set.
var ErrMaterialWithheld = errors.New("evidencebook: a record member the deal mapping reads is withheld")
ErrMaterialWithheld is what a DealMapping returns for a member it reads that a handed bundle withholds: the check is then NOT_CHECKED, never a FAIL that would blame the holder for what it was not shown.
var NeverList = []string{
"name", "contact", "items", "amounts_beyond_bands", "counterparties_except_to_themselves",
"messages", "rules", "asked_of_you_log", "shop_purchases", "pre_book_history",
"forum_exception_holders_own_copy_only",
}
NeverList is the fixed text of what no setting and no asker can reach (Steven, 9b brief, primitive 3). It is in every policy document and is not a setting: a document that carries any other list is refused, and a change that names one of these is refused.
var RefusalReasons = evidencerequest.RefusalReasons
RefusalReasons is the registry, in the draft's order.
var SettingsFields = []string{FieldStandardHistory, FieldWindow, FieldStaple, FieldMoreThanStd, FieldReceipt, FieldUnsignedAsks, FieldUnderContract, FieldAskedLogDays}
SettingsFields lists every changeable field, in page order.
var SubjectForms = evidencerequest.SubjectForms
SubjectForms lists the six forms in code-point order.
Functions ¶
func CheckHistoryCard2 ¶ added in v0.16.0
CheckHistoryCard2 checks a history_card/2 artifact by the seven ordered checks of ER -03 §8.1.2 (evidencerequest.CheckHistoryCard2), after the members this profile's artifact has and nothing else. anchor is the digest the response resolved.
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
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 EntryID ¶ added in v0.15.0
EntryID is a shelf log entry: the SHA-256 of an entry document's canonical JSON, and those bytes.
func KeyID ¶
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 OpeningsFor ¶ added in v0.15.0
OpeningsFor says which of a fact's openings an audience may have: the link opening of a book fact goes to the counterparty, the adjudicator and an asker the disclosure pack lets in; its status opening to the counterparty and a reader the holder chooses; a journal fact's openings to the owner and an auditor it appoints, and to nobody else. The owner holds every opening of its own shelf.
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 of the same outcome 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 outcomes: two failed halves are MATCHED (both sides recorded the failure; each side's reason is its own view and is not compared), and a failed half against a served one is CONFLICTING, so a requester that timed out while the provider finished shows as a disagreement, never as a missing peer half. Only two served halves reach the content check.
func SamePayloadCommitments ¶
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 ¶
VerifyLeaf checks one leaf proof against a committed root.
func VerifyOpening ¶ added in v0.5.0
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.
func VerifyOpenings ¶ added in v0.15.0
func VerifyOpenings(fact BookFact, link, status *FactOpening) error
VerifyOpenings checks the openings a reader was handed for a fact: each one given (nil is not given) must recompute its commitment. Which openings an audience may be handed is OpeningsFor's; the shelf's per-book Openings call lands with the stamp (docs/design/461-shelf-facts.md §6, part 2).
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
// ConductPacks is RespondOptions.ConductPacks, applied to every request.
ConductPacks []string
// 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
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
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
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
AbsenceWindow is when the request was transmitted and when the waiting window closed.
type AfterReceiveProfile ¶ added in v0.18.0
type AfterReceiveProfile interface {
ReceiveProfile
AfterReceive(ctx context.Context, result ReceiveResult, at time.Time) error
}
AfterReceiveProfile is a ReceiveProfile that acts on what a Receive took before Receive returns: x-deal-v1 names a counted ruling's arrival in the holder's deal book (evidencebook#527), so no host can leave it unnamed by skipping a call. Receive calls AfterReceive on every call, a duplicate included, so a record sent again retries what an earlier call failed to do; it runs once the parts' transactions committed (on a proof part's store error too, with the record part's result), holding only the receive lock: it may read the shelf and append to the holder's own books, and must not call Receive or Forget. at is the shelf's clock. An error is Receive's, joined with the parts', whose result stays committed.
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"`
// Deal is set only on the record of the book's own standard_history/1
// staple (Book.StapleForDeal): the deal the card was attached for, as the
// host named it. It is how the holder reads which deals the standard card
// left the book for (Book.StandardCardDeals).
Deal string `json:"deal,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 Audience ¶ added in v0.15.0
type Audience string
Audience is who an opening is handed to (§2.2).
const ( AudienceCounterparty Audience = "counterparty" AudienceAdjudicator Audience = "adjudicator" // AudienceAsker is an asker the holder's disclosure pack lets see the // deal. AudienceAsker Audience = "asker" // AudienceChosenReader is a reader the holder chooses, such as a card // reader handed the whole shelf. AudienceChosenReader Audience = "chosen_reader" AudienceOwner Audience = "owner" AudienceAuditor Audience = "auditor" )
The audiences of a fact's openings.
type AudienceFact ¶ added in v0.15.0
type AudienceFact struct {
EntrySeq uint64
Fact BookFact
LinkOpening *FactOpening
StatusOpening *FactOpening
}
AudienceFact is one fact of a book with the openings an audience may have (nil where it may not).
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 BatchEntry ¶ added in v0.15.0
type BatchEntry struct {
Kind string `json:"kind"`
BookID string `json:"book_id,omitempty"`
LogID string `json:"log_id,omitempty"`
Doc []byte `json:"doc"`
LinkOpening []byte `json:"link_opening,omitempty"`
StatusOpening []byte `json:"status_opening,omitempty"`
}
BatchEntry is one entry of a batch: its document and, for a fact, the openings of its two commitments.
type BeforeStampProvider ¶ added in v0.18.0
type BeforeStampProvider interface {
StatusProvider
BeforeStamp(ctx context.Context, at time.Time) error
}
BeforeStampProvider is a StatusProvider that writes, before a stamp, what that stamp's values must read: x-deal-v1 names each counted ruling a Receive left unnamed (evidencebook#527), so a naming that failed is retried by the holder's next stamp whether or not anything more arrives. Stamp, and Tick when a stamp is due, call BeforeStamp before they take the shelf's lock, holding the receive lock as AfterReceive does, so what it reads of the received store stays as read until it appends (a naming's seen is the counterparty's latest counted record when it is sealed): it may call the shelf's methods but Receive, Forget, Stamp and Tick. at is the time the stamp is taken at. Its error does not stop the stamp: TickResult.BeforeStamp reports it, and the next stamp calls it again.
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 ¶
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 ¶
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) AdoptPolicy ¶ added in v0.13.4
AdoptPolicy seals the first policy record: the shipped default for a holder kind. A book that has a policy keeps it.
func (*Book) Append ¶
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) AppendAt ¶ added in v0.18.0
AppendAt appends entry only as the book's record seq, the next one: a profile whose record names its own place (seq, the record before it) builds it from the tail it read and appends it here, so a write that landed in between refuses it with ErrBusy instead of sealing a record whose place is wrong. The caller reads the tail again and retries.
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) ApplyPolicyChange ¶ added in v0.13.4
func (b *Book) ApplyPolicyChange(ctx context.Context, c PolicyChange) (DisclosurePolicy, []Record, error)
ApplyPolicyChange seals one policy record per changed field, in page order and returns the policy in force with the records. The then[] steps are checked here and run by the executor, which reads them from the block. The whole block is checked before anything is sealed, so a stale round or a refused field seals nothing.
func (*Book) Bundle ¶
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
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
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 ¶
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) DisclosurePolicy ¶ added in v0.13.4
func (b *Book) DisclosurePolicy() (DisclosurePolicy, error)
DisclosurePolicy returns the policy in force: the one the latest policy record carries. ErrNoPolicy when the book has adopted none.
func (*Book) Discover ¶
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) IndexState ¶
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
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 ¶
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 ¶
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 ¶
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 ¶
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
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 ¶
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": policy_declined history for "": policy_declined
func (*Book) Retention ¶
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) SealUnavailableWindow ¶ added in v0.13.7
func (b *Book) SealUnavailableWindow(ctx context.Context, start, end time.Time, reasonClass string) (Record, error)
SealUnavailableWindow seals the book's signed statement that it was unavailable from start to end, for one of the reason classes evidencerequest.UnavailableReasonClasses names (ER -02 §4.7). The statement carries the period, the class and the book's signature over them (the vectors' profile: Ed25519 over the JCS of end, reason_class and start, with key_id the book's signing key).
Sealing is not registering. A reader counts the statement only once a checkpoint covering it carries a receipt, with an attested time, from a transparency service the reader accepts as independent of this book's operator. This package obtains no receipt: the host gets a receipt for the checkpoint that covers the returned record, pins that checkpoint as BundleRequest.At, and passes the receipt (with the witness directory it is checked under) as BundleRequest.Witnesses, which carries it in the bundle's checkpoint.witnesses.
func (*Book) Sealed ¶ added in v0.15.0
Sealed is the record as it was sealed: its canonical header, its Capsule (without signature) and its Producer Envelope, as the store keeps them. They are what another party verifies the record by on its own, as a profile sending the record to its counterparty carries them. The returned bytes are the caller's own copies; changing them changes nothing held.
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) ShowAbsence ¶ added in v0.13.7
func (b *Book) ShowAbsence(_ context.Context, absenceRecordID, responderKey string, statements []evidencerequest.WindowStatement) (evidencerequest.AbsenceDisplay, error)
ShowAbsence shows the recorded absence absenceRecordID (RecordAbsence) beside statements held for the responder whose signing key is responderKey (VerifiedBundle.UnavailableWindowStatements), as ER -02 §4.7 asks: a covered absence is shown as evidencerequest.UnavailableShownAs, with each covering statement's class, stated period and registration time and whether it was stated after the waiting window closed; an uncovered one as recorded_absence. It is never a refusal and never proof the responder was attacked, flooded or unable to answer. The absence record and any retention commitment it cites are not touched.
func (*Book) StandardCardDeals ¶ added in v0.13.7
StandardCardDeals lists, in order and without repeats, the deals this book's standard_history/1 staples were attached for: the deals the standard card left the book for through a staple. It reads the book's own evidence_request_answered records and seals nothing. A history_card/1 staple leaves no record, so a deal absent from the list had that card only (the default stapled to every deal); the list never guesses a deal's level.
func (*Book) StandardHistoryBundle ¶ added in v0.13.7
func (b *Book) StandardHistoryBundle(ctx context.Context, at Checkpoint, req StandardHistoryBundleRequest) (Bundle, error)
StandardHistoryBundle is the evidence-bundle/v2 of this book's records from seq 1 to at, a checkpoint the book issued: the bundle for the log at the extent the card's anchor commits for it. The book appends the bundle's disclosure record, as Bundle does. A book with no record at or below at has nothing to hand (ErrNotFound), and a Disclose that lets no record through hands none (ErrInvalid).
func (*Book) Staple ¶ added in v0.13.0
Staple builds a staple of derivation, history_card/1, history_card/2 or standard_history/1, as of the book's newest checkpoint (cut now if the book grew). Any other derivation is ErrInvalid: a staple is shown to whoever reads the message it rides on, so it is capped at the standard card. Whether to staple at all is the host's disclosure setting ("attach it when I buy or sell"); the book has no default.
standard_history/1 needs Config.StandardHistory. Its answer is sealed as an evidence_request_answered record, as for any authenticated requester (the holder answers itself), so the holder's book records which standard card it attached; history_card/1 is public and grows no record. The book's own request is not counted by its limiter.
func (*Book) StapleForDeal ¶ added in v0.13.7
StapleForDeal is Staple for a staple attached to one deal. For standard_history/1 the sealed evidence_request_answered record carries deal, so the holder can list the deals the standard card left the book for (StandardCardDeals); a deal with no such record had history_card/1 only. deal is the host's opaque id (non-empty, at most 256 bytes of printable UTF-8) and is refused for history_card/1, which seals no record.
type BookFact ¶ added in v0.15.0
type BookFact struct {
V int `json:"v"`
Kind string `json:"kind"`
Profile string `json:"profile"`
BookID string `json:"book_id"`
LogID string `json:"log_id"`
Size uint64 `json:"size"`
CheckpointSHA256 string `json:"checkpoint_sha256"`
PrevFactSize uint64 `json:"prev_fact_size"`
LinkCommitment string `json:"link_commitment"`
StatusCommitment string `json:"status_commitment"`
}
BookFact is one book's state at a stamp (§2.2). A journal fact has the same members, with Size, CheckpointSHA256 and PrevFactSize zero in the clear and their true values inside its status commitment.
type BookStatusProvider ¶ added in v0.18.0
type BookStatusProvider interface {
StatusProvider
BookValues(ctx context.Context, in StatusInput) (profile string, link LinkValue, status json.RawMessage, ok bool, err error)
}
BookStatusProvider is a StatusProvider handed what it reads by the shelf, so it reads nothing through the shelf's own lock, which a stamp holds while it asks for values: the stamp's tick and the book and journal handles the shelf already has (docs/design/461-deal-profile.md §8.1). A shelf calls BookValues in place of StampValues or Values when its provider implements it. The provider may call the handles' readers (Query, ResolvePayload, Sealed) and the shelf's lock-free readers (CountedPrefix, ReceivedRecordOf, RecordTime, RecordStamp and the rest), never another Shelf method.
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 ¶
BundleClaims is the status of each Evidence Bundle verifier claim.
type BundleDiff ¶ added in v0.13.8
type BundleDiff struct {
// DroppedRecords are records whose header the higher bundle discloses
// and the lower does not.
DroppedRecords []string
// DroppedPayloads are payload digests the higher bundle carries and the
// lower does not.
DroppedPayloads []string
// Extra lists what the lower bundle discloses that the higher does not,
// as "record:ID" or "payload:DIGEST". Empty when the lower bundle is a
// subset of the higher; otherwise it is not a lower level of that bundle.
Extra []string
}
BundleDiff is what a lower disclosure level drops from a higher one, read from two verified bundles of the same history. A level is a scoped bundle, not a hidden row, so the difference is exactly what the two bundles disclose: nothing here is inferred from a policy.
A bundle also carries every record its interval covers, so the checkpoint proves completeness. A leaf whose header the bundle does not carry reveals nothing and is not compared: a record counts as disclosed in a bundle only when the bundle verifies its header, wherever the header travels (a caller-sealed record carries it inside its capsule). Only records and payloads are compared: a bundle's other extensions are the producer's own statements (VerifiedBundle .Extensions) and disclosed members other than the header are not read, so a caller that gates on Subset gates on records and payloads only.
func DiffBundles ¶ added in v0.13.8
func DiffBundles(higher, lower []byte) (BundleDiff, error)
DiffBundles verifies both bundles (VerifyBundle) and lists what lower drops from higher. Each list is sorted.
Both bundles must verify, carry an authenticated anchor and name the same log, else the error is ErrInvalid. The log id is then the signed one, but whether the signing key belongs to the expected party is the caller's check: compare VerifyBundle(...).AnchorKeyID of both bundles against a key obtained independently. Two forks of one log are not detected, and a bundle from a receipt-only substrate (no authenticated anchor) cannot be compared. Only records and payloads are compared (see BundleDiff).
func (BundleDiff) Empty ¶ added in v0.13.8
func (d BundleDiff) Empty() bool
Empty reports whether the two bundles disclose the same records and payloads.
func (BundleDiff) Subset ¶ added in v0.13.8
func (d BundleDiff) Subset() bool
Subset reports whether the lower bundle discloses no record or payload the higher does not.
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
// ConductPacks are the pack ids the book's owner holds as conduct packs
// (scope.kind conduct): private, judged only for the owner. A scoped
// bundle whose selected set holds a record of any type whose subject_ref
// names one, or a Result claim whose contract_ref does, is refused unless
// OwnerCopy is set. The kind is local policy, written into no
// record.
ConductPacks []string
// OwnerCopy marks a bundle that stays with the book's owner, so it may
// carry a conduct record.
OwnerCopy bool
// 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
// Witnesses are witness receipts for the anchor, as checkpoint.witnesses
// entries (ts_url, entry_hash, receipt_b64, leaf_index, tree_size): the
// bundle carries them in checkpoint.witnesses. The anchor must therefore
// be known when the receipts are made: At is required with them. Each is
// checked against the anchor's signed checkpoint under WitnessDirectory
// before the bundle is built; one that does not verify, or any receipt
// without a directory, is ErrInvalid. At most MaxReplyReceipts.
Witnesses []json.RawMessage
// WitnessDirectory names the witnesses and keys Witnesses are checked
// under (capsule-emit's witnesses.json rows; see ParseWitnessDirectory).
// This check is the producer's; a reader checks the receipts again
// under its own directory.
WitnessDirectory []WitnessRow
// contains filtered or unexported fields
}
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) Checkpoint ¶
func (s *CLLSubstrate) Checkpoint(ctx context.Context, now time.Time) (Checkpoint, error)
func (*CLLSubstrate) CheckpointWhole ¶ added in v0.15.0
func (s *CLLSubstrate) CheckpointWhole(ctx context.Context, now time.Time) (Checkpoint, error)
CheckpointWhole is Checkpoint over everything the log holds, as one checkpoint: every pending entry is indexed first, without a checkpoint, so a batch longer than one runner scan (cll.MaxScanLimit entries) is never covered in part (evidencebook#461, a stamp's batch).
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
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
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) Handover ¶ added in v0.15.0
Handover hands over the shelf up to tick n's checkpoint (the newest finished tick when n is 0), which must be a stamp's: the material a reader the holder chooses replays (§2.7). Link openings and journal openings are never handed over.
func (*Cadence) HistoryCard ¶ added in v0.13.2
HistoryCard is the profile's history_card/1 (ER §8.1) over the cadence log, as a staple the host attaches to its own message (evidencebook#341). Its stream is the cadence log: the card lists the cadence checkpoint of every finished tick from the first through tick n (the newest finished tick when n is 0), each with the consistency proof from the one before, and is as of tick n's checkpoint, the one the witness sees. The shelf's Signer signs the reply. It is the same staple Book.Staple gives a book, so CheckStaple accepts it for holder KeyID(the shelf's Signer), and the card holds no record content. ErrNotFound when the cadence has no such finished tick. ErrOverLimit when the card would list more than DefaultMaxAnswerItems ticks (about 35 days at the default interval), the bound a Book's card has: history_card/1 is linear in checkpoints, so a longer cadence staples its standard_history/1 (StandardHistoryAnchor) instead (evidencebook#354).
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
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) Migrate ¶ added in v0.15.0
Migrate switches the shelf to a log of book facts (§4). It is explicit and one-way, and recoverable at every step: a call after a crash resumes from the stored state. It first sets the file to version 2, so no older build writes it from then on, and then backs it up to <path>.v1.bak, a version 1 file an older build opens. It refuses a <path>.v1.bak that is not this migration's backup, naming that path, and leaves the file at version 2.
func (*Cadence) Migrated ¶ added in v0.15.0
Migrated reports whether the shelf's cadence log is a log of book facts.
func (*Cadence) Stamp ¶ added in v0.15.0
Stamp takes a stamp now (§2.5): on demand, whatever the heartbeat's schedule. A stamp stored but not finished is finished first, as the same stamp. It needs a migrated shelf.
func (*Cadence) StampProof ¶ added in v0.15.0
func (c *Cadence) StampProof(ctx context.Context, bookID string, n uint64, audience Audience) (StampProof, error)
StampProof builds the proof of a book's latest fact at stamp n (the newest finished stamp when n is 0), for an audience: the status opening is included when OpeningsFor lets that audience have it, and the link opening never is. The journal's facts are proved to nobody.
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) StandardHistoryBundles ¶ added in v0.13.7
func (c *Cadence) StandardHistoryBundles(ctx context.Context, anchor StandardHistoryAnchor, req StandardHistoryBundleRequest) (map[string]Bundle, error)
StandardHistoryBundles is, for every log the anchor's tick committed, the bundle of that log at the extent the anchor commits (anchor.Extents), keyed by log id. A committed log that is not a book of this shelf (a host log, or none) is ErrNotFound or ErrInvalid. A recipient still cannot show coverage from them for the tick's anchor, which commits its logs through a salted, sparse tree (SH-10).
func (*Cadence) Tick ¶ added in v0.5.0
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)
// Status gives each book's profile and fact values once the shelf is a
// log of book facts (Migrate). Nil gives every book profile "none".
Status StatusProvider
}
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
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
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 CommittedLog ¶ added in v0.13.7
CommittedLog is one log an anchor commits: the SHA-256 of the checkpoint statement it commits for the log, and the log's record count under it.
type Comparator ¶
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
// Reproduction makes this a reproduced scratch book: Now is the
// caller's given time, not a clock, and every record carries the
// Reproduction marker. It requires Now. A book is one or the other for
// its whole history: opened the other way, its writes are refused
// (ErrInvalid), checkpoints included, so a reproduction can be compared but
// never extended as a live book. A live book is not protected from a
// caller-supplied Now by this alone; capsulectl-book gives Now only to a
// Reproduction book.
Reproduction bool
// Responder is the responder's cost and abuse policy for Respond
// (FR-37). The zero value answers uniformly (policy_declined) with no rate
// limit; RefusalPolicySpecific is an explicit opt-in.
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 CountedPrefix ¶ added in v0.15.0
type CountedPrefix struct {
// Size is how many records, from position 1, are counted.
Size uint64
// Last is the digest of the last counted record ("" for none): what a
// record's seen field names.
Last string
// ForkAt is the lowest position with a fork, 0 for none; the prefix
// ends before it for good.
ForkAt uint64
}
CountedPrefix is a sender's counted prefix in one book log, as the store computes it now.
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
DealHalf is one half as the reconcile is given it: its octets as held and the book it comes from.
type DealMapping ¶ added in v0.13.7
type DealMapping func(records []MaterialRecord) ([]standardhistory.Deal, error)
DealMapping is the host profile's SH-2 mapping from the records of the covered logs, in log order within a log, to deal entries. It returns ErrMaterialWithheld for a record or payload member it reads that is withheld, and an error of its own for a record that is no deal's.
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 DisclosurePolicy ¶ added in v0.13.4
type DisclosurePolicy struct {
Name string `json:"name"`
Holder string `json:"holder"`
// Round counts the settings rounds applied; a change names the round
// it was composed against.
Round uint64 `json:"round"`
// StandardHistory is "on" or "off": whether standard_history/1 is
// answered to a requester that signs.
StandardHistory string `json:"standard_history"`
// Window is how far back the card counts: "1", "3", "12" (months) or "all".
Window string `json:"window"`
// Staple is "on" or "off": attach the card to offers and orders.
Staple string `json:"staple"`
// MoreThanStandard is who decides a signed ask past the policy:
// "ask_me" or "operator_decides".
MoreThanStandard string `json:"more_than_standard"`
// Receipt is "always" or "off": record-at-completion, both sides.
Receipt string `json:"receipt"`
// UnsignedAsksPerWeek limits askers that do not sign; 0 sets no limit.
// It is never applied to signed askers or to the staple.
UnsignedAsksPerWeek int `json:"unsigned_asks_per_week"`
// UnderContract is "none" or "named_by_contract" (the under_contract
// tier scope, applied only when a contract names it).
UnderContract string `json:"under_contract"`
// AskedLogRetentionDays is how long the holder-only asked-of-you log
// is kept; 0 keeps it until the holder deletes it.
AskedLogRetentionDays int `json:"asked_log_retention_days"`
Never []string `json:"never"`
}
DisclosurePolicy is the `policy` member of a disclosure-policy/0 file.
func DefaultDisclosurePolicy ¶ added in v0.13.4
func DefaultDisclosurePolicy(holder string) (DisclosurePolicy, error)
DefaultDisclosurePolicy is "Action State default v1" for a holder kind: Muse's person defaults, or Mesh's node defaults.
func (DisclosurePolicy) Apply ¶ added in v0.13.4
func (p DisclosurePolicy) Apply(c PolicyChange) ([]PolicyStep, error)
Apply returns the policy after c, as one step per field in page order. It is pure: nothing is sealed. A change composed against another round or another policy is ErrStaleRound; a change naming a never-list item is ErrNeverList; an unknown field or value is ErrInvalid.
func (DisclosurePolicy) Digest ¶ added in v0.13.4
func (p DisclosurePolicy) Digest() (string, error)
Digest is the sha256 of the policy's JCS octets: the digest a standard card names (SH §5.1) and a commitment carries.
func (DisclosurePolicy) Rows ¶ added in v0.13.4
func (p DisclosurePolicy) Rows() []SettingRow
Rows lists the settings page in order. The proof-of-records row is fixed.
func (DisclosurePolicy) SharePolicy ¶ added in v0.13.4
func (p DisclosurePolicy) SharePolicy() SharePolicy
SharePolicy is the switches Respond reads under this policy, the rest at their defaults. A book that holds the policy applies it over whatever SharePolicy its caller passes (Book.Respond, Book.Doctor).
func (DisclosurePolicy) StandardPolicy ¶ added in v0.13.4
func (p DisclosurePolicy) StandardPolicy() (standardhistory.Policy, error)
StandardPolicy is the two members of the policy a standard_history/1 card states: its digest and its window (SH §5.1).
func (DisclosurePolicy) Validate ¶ added in v0.13.4
func (p DisclosurePolicy) Validate() error
Validate rejects any value outside its enumeration and any never-list that is not the fixed one.
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"`
// Card is the standard_history/1 card exactly as the book serves it to
// a signed requester (the probe_standard_history finding only).
Card json.RawMessage `json:"card,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. A book
// that serves standard_history/1 also reports the card a signed
// requester receives, built in-process by the serve path's own decision
// and builder, so doctor seals nothing.
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
// As is who the probe answers for: DoctorAsStranger asks only the
// public questions, DoctorAsSigned also renders what a signed asker
// receives (the standard card, built in-process, sealing nothing).
// Empty is DoctorAsSigned, as before the option existed.
As string
}
DoctorOptions is what Doctor reads besides the book.
type DoctorTransport ¶ added in v0.8.0
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
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.
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
// Members are further top-level members of the record's Capsule, by
// name, each a JSON value (a profile's own member, such as the
// settlement leg draft-mih-agent-settlement-records puts there). The
// Capsule's id and signature cover them; the header does not, and a
// base-profile name is refused. Only a Capsule the book or SealSent
// seals carries them: AppendCapsule refuses them, since the caller
// seals that Capsule itself.
Members map[string]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
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 FactInput ¶ added in v0.15.0
type FactInput struct {
Profile string
BookID string
LogID string
Size uint64
CheckpointSHA256 string
PrevFactSize uint64
Link LinkValue
// Status is the profile's status value as JSON; nil is {} (ProfileNone).
Status json.RawMessage
}
FactInput is what a book's fact is made from at a stamp.
type FactOpening ¶ added in v0.15.0
type FactOpening struct {
Salt string `json:"salt"`
Value json.RawMessage `json:"value"`
}
FactOpening shows one committed value: the salt and the value.
func (FactOpening) Verify ¶ added in v0.15.0
func (o FactOpening) Verify(commitment string) error
Verify reports whether the opening recomputes commitment.
type FileStore ¶
type FileStore struct {
// contains filtered or unexported fields
}
FileStore is an append-only JSONL record journal plus a checkpoint journal.
func OpenFileStore ¶
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) PutCheckpoint ¶
func (s *FileStore) PutCheckpoint(ctx context.Context, cp Checkpoint) 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 FormatSwitch ¶ added in v0.15.0
type FormatSwitch struct {
V int `json:"v"`
Kind string `json:"kind"`
Format string `json:"format"`
LastTick uint64 `json:"last_tick"`
Logs []LoggedSize `json:"logs"`
}
FormatSwitch is the one marker entry the migration appends (§4); Logs is every log of the lifetime table, sorted by log id.
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
// Failed marks a record of an exchange that did not complete (a refused,
// errored, timed-out or dropped one). The profile reader sets it from the
// record's own outcome; the zero value is a served exchange. A failed
// half carries no payload commitments to compare, so its pair is decided
// by the outcomes (see ReconcileHalvesWith), never by the content check.
Failed 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
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 ¶
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 Handover ¶ added in v0.15.0
type Handover struct {
V int `json:"v"`
// LogID is the shelf log (the cadence log).
LogID string `json:"log_id"`
// Entries is every entry of the shelf log, in order, up to the anchor:
// 32-byte ids in lowercase hex.
Entries []string `json:"entries"`
// Documents are the entry documents after the format switch, with the
// status opening of each book fact.
Documents []HandoverDocument `json:"documents"`
// BookCheckpoints are the COSE statements of the book checkpoints the
// book facts carry.
BookCheckpoints [][]byte `json:"book_checkpoints"`
// Consistency is, for each pair of consecutive facts of a book whose
// size grew, the proof between their checkpoints.
Consistency []HandoverConsistency `json:"consistency"`
// Anchor is the shelf checkpoint the handover runs to, and Receipts the
// witness receipts the holder holds for it (shelf_receipts), one per
// witness and key, in URL order.
Anchor []byte `json:"anchor"`
Receipts []WitnessReceipt `json:"receipts,omitempty"`
// Witnessed are the shelf checkpoints before the anchor, within it,
// for which the holder holds receipts, each with every receipt held, in
// tick order (docs/design/461-deal-profile.md §8.1, invariant C): a
// record's time is the earliest named registration of any checkpoint
// that covers it, not only the anchor's, so a reader resolves the times
// the holder's RecordTime gives (HandoverTimes).
Witnessed []HandoverCheckpoint `json:"witnessed,omitempty"`
// Ties ties each genesis fact the holder can tie to the old witnessed
// tree (shelf_handover_tie.go), in book id order.
Ties []HandoverTie `json:"ties"`
}
Handover is the material a whole-shelf reader is handed (§2.7).
type HandoverCheckpoint ¶ added in v0.15.0
type HandoverCheckpoint struct {
Checkpoint []byte `json:"checkpoint"`
Receipts []WitnessReceipt `json:"receipts"`
}
HandoverCheckpoint is a shelf checkpoint before a handover's anchor and the witness receipts held for it, one per witness and key, in URL order.
type HandoverConsistency ¶ added in v0.15.0
type HandoverConsistency struct {
LogID string `json:"log_id"`
FromSize uint64 `json:"from_size"`
ToSize uint64 `json:"to_size"`
Proof ConsistencyEvidence `json:"proof"`
}
HandoverConsistency is a consistency proof between two checkpoints of one book.
type HandoverDocument ¶ added in v0.15.0
type HandoverDocument struct {
Seq uint64 `json:"seq"`
Doc []byte `json:"doc"`
StatusOpening *FactOpening `json:"status_opening,omitempty"`
}
HandoverDocument is one entry document and, for a book fact, its status opening.
type HandoverLatest ¶ added in v0.15.0
type HandoverLatest struct {
Fact BookFact `json:"fact"`
StatusOpening FactOpening `json:"status_opening"`
}
HandoverLatest is a book's latest fact up to the anchor.
type HandoverResult ¶ added in v0.15.0
type HandoverResult struct {
// Recomputed is true: VerifyHandover fails rather than return a result
// it could not recompute.
Recomputed bool `json:"recomputed"`
// Witnessed says a receipt from a witness in the directory verifies for
// the anchor and gives a registration time (§2.7); a receipt with no
// registration time cannot give the witnessed level. A shelf with no
// witness is a supported default and is unwitnessed.
Witnessed bool `json:"witnessed"`
// CoverageStart is the shelf log size, in entries, at which the facts
// begin to be complete: the end of the migration's stamp.
CoverageStart uint64 `json:"coverage_start"`
// Latest is each book's latest fact and its status opening.
Latest []HandoverLatest `json:"latest"`
// Untied lists the books whose genesis fact carries no tie to the old
// witnessed tree.
Untied []string `json:"untied"`
}
HandoverResult is what a verified handover shows.
func VerifyHandover ¶ added in v0.15.0
func VerifyHandover(h Handover, pinnedKey string, witnesses aacwitness.Directory) (HandoverResult, error)
VerifyHandover replays a handover (§2.7) under the holder's checkpoint key and the reader's witness directory. It fails when an entry is held back, a document is left out or does not hash to its entry, a status opening does not recompute its commitment, a book checkpoint is not the fact's or not the holder's, or a book's facts break their chain (a replaced book). The journal's chain is not checked and its openings are not asked for.
type HandoverTie ¶ added in v0.15.0
type HandoverTie struct {
// BookID is the genesis fact's book id.
BookID string `json:"book_id"`
// The old tick's leaf: the log, its size and checkpoint digest at the
// tick, the leaf's salt and position, and its path to the tick's root
// (CadenceDepth hashes, lowercase hex, from the leaf up).
LogID string `json:"log_id"`
Size uint64 `json:"size"`
CheckpointSHA256 string `json:"checkpoint_sha256"`
Salt string `json:"salt"`
Index uint64 `json:"index"`
Path []string `json:"path"`
// EntrySeq is the position, from 1, of the tick's root in the shelf
// log, before the format switch.
EntrySeq uint64 `json:"entry_seq"`
// CadenceCheckpoint is the COSE statement the tick cut, and Receipts the
// witness receipts held for it, one per witness and key, in URL order.
CadenceCheckpoint []byte `json:"cadence_checkpoint"`
Receipts []WitnessReceipt `json:"receipts"`
// OldCheckpoint is the COSE statement of the book checkpoint the leaf
// commits to.
OldCheckpoint []byte `json:"old_checkpoint"`
// Consistency proves the genesis fact's checkpoint extends the old one;
// absent when the two are of one size (their roots are then equal).
Consistency *ConsistencyEvidence `json:"consistency,omitempty"`
}
HandoverTie ties one book's genesis fact to the old witnessed tree.
type HandoverTimes ¶ added in v0.15.0
type HandoverTimes struct {
// contains filtered or unexported fields
}
HandoverTimes resolves record times from a verified handover.
func VerifyHandoverTimes ¶ added in v0.15.0
func VerifyHandoverTimes(h Handover, pinnedKey string, witnesses aacwitness.Directory) (HandoverTimes, error)
VerifyHandoverTimes replays h with VerifyHandover, then reads the registration times its receipts give under the reader's directory: a receipt that does not verify, or gives no registration time, gives none.
func (HandoverTimes) RecordTime ¶ added in v0.15.0
func (t HandoverTimes) RecordTime(bookID string, position uint64, witnesses []string) (time.Time, bool, error)
RecordTime is the record time of the record at position (from 1) of the book bookID, from the witnesses named (their URLs), as Shelf.RecordTime computes it: the earliest registration time of a handed-over checkpoint that covers the first fact of the book whose size covers the position.
func (HandoverTimes) RecordTimeByKey ¶ added in v0.15.0
func (t HandoverTimes) RecordTimeByKey(bookID string, position uint64, keyIDs []string) (time.Time, bool, error)
RecordTimeByKey is RecordTime with the witnesses named by their verified key ids, as Shelf.RecordTimeByKey.
type Header ¶
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"`
// Reproduction marks a record of a reproduced scratch book: its
// committed_at (and the book's checkpoint times) were given by the
// caller, not read from a clock, so no reader may take them as a real
// commit time. It is part of the digested header, so it cannot be
// stripped without changing the record's identity. Absent in a book that
// stamps the wall clock.
Reproduction *Reproduction `json:"reproduction,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.
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 HeldProof ¶ added in v0.15.0
type HeldProof struct {
// Proof is the proof as received, and Verified what it shows: the fact
// (its book id), both checkpoints (the shelf log's id) and the
// checkpoint key that signed them.
Proof StampProof
Verified VerifiedStampProof
// Recomputed says the records held recomputed the book checkpoint's root,
// and Contradicted that they did not; neither, that the records held do
// not reach its size yet.
Recomputed, Contradicted bool
// Covers is how many of the sender's currently counted records the proof
// covers: its book checkpoint's entries, capped to the counted prefix as
// the store computes it now, once recomputed; 0 otherwise. A fork found
// after the proof was recomputed lowers it, though the proof stays
// recomputed.
Covers uint64
ReceivedAt time.Time
}
HeldProof is a stamp proof the store holds from a sender, as it stands against that sender's counted prefix now.
type HeldRecord ¶ added in v0.15.0
type HeldRecord struct {
ReceivedRecord
Record []byte
ReceivedAt time.Time
}
HeldRecord is a received record the store holds.
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
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.
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 JournalStatus ¶ added in v0.15.0
type JournalStatus struct {
Size uint64 `json:"size"`
CheckpointSHA256 string `json:"checkpoint_sha256"`
PrevFactSize uint64 `json:"prev_fact_size"`
}
JournalStatus is a journal fact's status value: the journal's own size, checkpoint digest and previous fact size, which its fact does not show.
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 ¶
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).
type LinkValue ¶ added in v0.15.0
type LinkValue struct {
LastReceived *ReceivedPosition `json:"last_received"`
CheckedOver []string `json:"checked_over"`
}
LinkValue is what a fact's link commitment holds: the last record held from the other side, and the digests the recomputed checks ran over.
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 LoggedSize ¶ added in v0.15.0
LoggedSize is one log of the lifetime table at the migration.
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
// ConductPacks is RespondOptions.ConductPacks, applied to every request.
ConductPacks []string
// 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
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 MaterialRecord ¶ added in v0.13.7
type MaterialRecord struct {
PeerRecord
LogID string
// contains filtered or unexported fields
}
MaterialRecord is one record of a handed bundle whose log's coverage was shown.
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
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
NewOpening draws a fresh 32-byte nonce for text.
func (Opening) Commitment ¶ added in v0.5.0
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 PolicyChange ¶ added in v0.13.4
type PolicyChange struct {
Profile string `json:"profile"`
BasePolicy string `json:"base_policy"`
Round uint64 `json:"round"`
Changes map[string]json.RawMessage `json:"changes"`
Then []string `json:"then"`
}
PolicyChange is policy-change/v1: the one block the Muse laptop form, the Muse chat buttons (after agent-side batching) and the Mesh dashboard all produce. The executor runs the block, never the prose around it.
func ParsePolicyChange ¶ added in v0.13.4
func ParsePolicyChange(data []byte) (PolicyChange, error)
ParsePolicyChange reads a policy-change/v1 block.
type PolicyStep ¶ added in v0.13.4
type PolicyStep struct {
Field string
From string
To string
// Policy is the policy in force after this step.
Policy DisclosurePolicy
}
PolicyStep is one field's change as it was sealed.
type ProofOutcome ¶ added in v0.15.0
type ProofOutcome struct {
// Accepted is a proof the store keeps: new, or the same book checkpoint
// under another shelf checkpoint, kept beside the first.
Accepted bool
// Duplicate is a proof already held: acknowledged, not stored again.
Duplicate bool
// Refused is why the proof was refused (ErrInvalid or ErrRefused). A
// proof that contradicts a held one, or the records held, is refused and
// its evidence kept.
Refused error
}
ProofOutcome is what became of a received stamp proof.
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 ReceiveBounds ¶ added in v0.15.0
type ReceiveBounds struct {
// MaxRecordBytes refuses a larger record: 1 MiB.
MaxRecordBytes int64
// MaxRecordsPerLog refuses a record past this many held from one sender
// and log (one book): 100000.
MaxRecordsPerLog int64
// Unanswered unsolicited offers, per sender (16, 4 MiB) and in total
// (1024, 64 MiB). Reaching one drops the oldest unanswered offer first;
// an offer larger than a byte bound alone is refused.
MaxOffersPerSender int64
MaxOfferBytesPerSender int64
MaxOffers int64
MaxOfferBytes int64
// What unsolicited offers leave behind, per sender (16) and in total
// (1024) rows: the position of each dropped offer
// (shelf_received_vacated) and each conflict in a log that holds only
// offers (shelf_received_conflicts, with its evidence, at most two
// records' bytes). An offer belongs to no deal, so past either bound no
// row is kept: such a position may later be forgotten, and a fork there
// ends the counted prefix only while both its records are held. Rows
// Forget leaves and conflicts in a log holding any other record are
// kept for good and not counted.
MaxOfferEvidencePerSender int64
MaxOfferEvidence int64
}
ReceiveBounds are the store's bounds (§3). A zero member takes the default beside it.
type ReceiveChanges ¶ added in v0.15.0
type ReceiveChanges struct {
// Grew and Shrank are deals with records that entered or left their
// sender's counted prefix; Forked those with new evidence of a fork or
// a contradicting checkpoint.
Grew, Shrank, Forked []string
// Covered are deals whose records gained coverage: a held stamp proof
// whose size they reach and whose root they recompute, when the proof
// arrives or when the records do. A proof past the records held grants
// none until then.
Covered []string
}
ReceiveChanges are the deal ids a Receive call changed, each list sorted.
type ReceiveConfig ¶ added in v0.15.0
type ReceiveConfig struct {
// Profile reads received records; Receive refuses every call without one.
Profile ReceiveProfile
// Bounds are the store's bounds; a zero member takes its default.
Bounds ReceiveBounds
// Retention is how long a received record is kept once its deal is
// settled (Forget), the holder's own setting. Zero is the default: the
// life of the shelf, so nothing is ever deleted.
Retention time.Duration
}
ReceiveConfig is the shelf's store of received records.
type ReceiveProfile ¶ added in v0.15.0
type ReceiveProfile interface {
// Read checks a received record's signature and returns what the store
// needs of it. An error refuses the record as invalid.
Read(ctx context.Context, record []byte) (ReceivedRecord, error)
// Admit is the push rule (§3, "who may push"): whether this sender may
// push this record now. An offer may come from any key; any other
// record only from a key a book on the shelf names as its counterparty
// or adjudicator, whose offer our side answered, or to which an offer in
// the journal was sent. Holding someone's offer grants nothing.
Admit(ctx context.Context, r ReceivedRecord) (bool, error)
// Answered reports whether our side has answered a stored offer (a
// journal reply or our agreement). The store asks about each offer it
// would drop before its write transaction, under a mark of the holder's
// own books (their records and log entries); if the mark moved by the
// time the transaction holds the write lock, an answer may have been
// committed in between, so it asks again (ErrBusy after three tries).
// An answered offer leaves the offer bounds and is never dropped.
Answered(ctx context.Context, offer ReceivedRecord) (bool, error)
// ProofSender relates a stamp proof's key (the checkpoint key id that
// signed both its checkpoints) and the book log it names to the sender
// key its records are held under (ReceivedRecord.SenderKey), and says
// whether that sender may push a proof now. ok false refuses the proof.
ProofSender(ctx context.Context, checkpointKeyID, logID string) (senderKey string, ok bool, err error)
}
ReceiveProfile is what a profile (today x-deal-v0's records) tells the store about received records. The store calls it outside the shelf's mutex and outside any transaction of its own, so it may read the shelf; it must not call Receive or Forget.
type ReceiveResult ¶ added in v0.15.0
type ReceiveResult struct {
// Record is the record part's outcome; nil when no record was given.
Record *RecordOutcome
// Proof is the proof part's outcome; nil when no proof was given.
Proof *ProofOutcome
// Changes are the deal ids whose rows the profile recomputes.
Changes ReceiveChanges
}
ReceiveResult is what one Receive call did, part by part.
type ReceivedPosition ¶ added in v0.15.0
type ReceivedPosition struct {
LogID string `json:"log_id"`
Size uint64 `json:"size"`
RecordDigest string `json:"record_digest"`
}
ReceivedPosition names the last record held from the other side.
type ReceivedRecord ¶ added in v0.15.0
type ReceivedRecord struct {
// Digest is the record's entry in its sender's book log (for a book
// record, its record id): 64 lowercase hex characters, unique across
// senders. A book checkpoint's root recomputes from these.
Digest string
// SenderKey is the key the sender signs its records with.
SenderKey string
// LogID and Position place the record in the sender's book log; the
// first record is at position 1.
LogID string
Position uint64
// Prev is the digest of the record at Position-1 that this one follows,
// "" exactly when Position is 1.
Prev string
// DealID is the deal the record belongs to: what Receive reports as
// changed, and what Forget deletes by. An unsolicited offer's deal id is
// the profile's to choose (its own id, say).
DealID string
// Offer marks an unsolicited offer: one that belongs to no book the
// shelf holds. Offers have their own bounds (ReceiveBounds).
Offer bool
}
ReceivedRecord is what the store needs of a received record.
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
// OwnFailed and PeerFailed are the ids of the records that record an
// exchange that did not complete, as the profile reader reads them from
// its records (a header carries no outcome). A record not named is
// served. See Half.Failed.
OwnFailed, PeerFailed map[string]bool
}
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 ¶
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 RecordOutcome ¶ added in v0.15.0
type RecordOutcome struct {
Digest string
// DealID is the deal the profile read the record as belonging to
// (ReceivedRecord.DealID), set once it read; "" for a record it could
// not read.
DealID string
// Stored is a record stored by this call.
Stored bool
// Duplicate is a record already held: acknowledged, not stored again.
Duplicate bool
// Deleted is a record held once and deleted under the holder's
// retention: acknowledged, not stored again.
Deleted bool
// Counted is a held record within its sender's counted prefix.
Counted bool
// AskForBook is a held record past the counted prefix: the sender is
// asked for its book.
AskForBook bool
// Refused is why the record was refused (ErrInvalid, ErrRefused or
// ErrOverLimit); nothing of it is stored.
Refused error
}
RecordOutcome is what became of a received record.
type RecordSource ¶
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 ¶
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
ParseReply reads a received reply: exactly one of an envelope or a refusal. Every failure matches ErrInvalid.
type Reproduction ¶ added in v0.13.0
type Reproduction struct {
Clock string `json:"clock"`
}
Reproduction is the header marker of a reproduced scratch book (evidencebook#232).
type RequestLimiter ¶ added in v0.2.0
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
// ConductPacks are the pack ids the book's owner holds as conduct packs
// (BundleRequest.ConductPacks). A record that cites one, whatever its type
// and whoever sealed it, is treated like the holder's other private
// records (neverServed): no subject form or derivation serves it, and a
// request that names it gets the uniform refusal an unknown id gets. The
// kind is local policy, written into no record.
ConductPacks []string
// contains filtered or unexported fields
}
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 RefusalPolicyUniform (the default when empty) or
// RefusalPolicySpecific, an explicit operator opt-in: it tells a requester
// whether the holder has a record for a key it does not hold (#206 row 8).
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
// HistoryWindow is the window a history_card/2 states: how many of the
// newest checkpoints it lists in full, 1 to 64 (ER -03 §8.1.2). Zero is
// DefaultHistoryWindow.
HistoryWindow int
}
ResponderPolicy is the responder's cost and abuse policy (FR-37). The zero value answers uniformly (policy_declined) 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
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) 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 (s *SCITTReceiptSubstrate) Info() SubstrateInfo
func (*SCITTReceiptSubstrate) Latest ¶
func (s *SCITTReceiptSubstrate) Latest(context.Context) (Checkpoint, error)
func (*SCITTReceiptSubstrate) ProveConsistency ¶
func (s *SCITTReceiptSubstrate) ProveConsistency(context.Context, Checkpoint, Checkpoint) (ConsistencyEvidence, error)
func (*SCITTReceiptSubstrate) ProveInclusion ¶
func (s *SCITTReceiptSubstrate) ProveInclusion(_ context.Context, seq uint64, at Checkpoint) (InclusionEvidence, error)
func (*SCITTReceiptSubstrate) ProveInterval ¶
func (s *SCITTReceiptSubstrate) ProveInterval(context.Context, uint64, Checkpoint) (IntervalEvidence, error)
func (*SCITTReceiptSubstrate) Release ¶
func (s *SCITTReceiptSubstrate) Release() error
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) 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 SentCapsule ¶ added in v0.15.0
SentCapsule is a sent record's standalone Capsule: its id, its bytes, its Producer Envelope (which carries the signature) and the payload it commits, the record's bytes, which travel with it.
type SentRequest ¶
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
SetCompleteness is a side's §6.1 status and its declared kind, null when no declaration is given.
type SettingRow ¶ added in v0.13.4
type SettingRow struct {
Setting string `json:"setting"`
Value string `json:"value"`
Sends string `json:"sends"`
}
SettingRow is one line of the settings page, and of doctor's report: what a setting is and what it sends. The page and doctor render the same rows, so they cannot disagree on what a setting sends.
type SharePolicy ¶
type SharePolicy struct {
// host that serves standard_history/1 answers it. Off, it is
// derivation_unsupported, as for a host that does not serve it.
StandardHistory string `json:"standard_history,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
Books lists the ids of the books that hold records, in id order. The journal is not among them: it counts toward no completeness and no tally (evidencebook#461 §2.7).
func (*Shelf) Cadence ¶ added in v0.5.0
Cadence opens the shelf's cadence log, creating it when absent.
func (*Shelf) CountedPrefix ¶ added in v0.15.0
CountedPrefix computes a sender's counted prefix in one log from the store. It takes no lock: a StatusProvider or ReceiveProfile may call it.
func (*Shelf) Evidence ¶ added in v0.15.0
Evidence lists the store's evidence of forks and contradicting checkpoints, oldest first. It takes no lock: a StatusProvider or ReceiveProfile may call it.
func (*Shelf) ExistingJournal ¶ added in v0.19.0
ExistingJournal is the shelf's journal when the shelf has one, nil otherwise. Unlike Journal it never creates it, so a reader (a report) changes nothing.
func (*Shelf) Forget ¶ added in v0.15.0
func (s *Shelf) Forget(ctx context.Context, dealID string, now time.Time, settled func(ctx context.Context, dealID string) (bool, error)) ([]string, error)
Forget deletes a deal's received records under the holder's retention (§3, retention): only when the shelf's Retention is set (by default nothing is ever deleted), only once settled reports the deal settled (every row agreed, uncontested, or ruled with its remedy done, as the row status function computes it), and only the records received at least Retention before now. Each deleted record leaves a tombstone, so reading it reports it deleted, not missing. The deal's proofs, evidence and the forks found stay: a fork's position still ends its sender's counted prefix, another record arriving at a deleted position is a fork there, and a proof reaching a deleted position grants no coverage until the records it was checked against are held again. It returns the digests deleted. A call racing Release may fail with database/sql's closed-database error rather than ErrReleased.
func (*Shelf) HeldByDeal ¶ added in v0.18.0
HeldByDeal is every received record held for the deal dealID, the deal id its profile's Read gave it: across senders and logs, forks included, ordered by sender key, log id, position and digest. A profile reading a deal's received books at a stamp reads them here, and the counted prefix of each with CountedPrefix. It takes no lock.
func (*Shelf) HeldFirst ¶ added in v0.15.0
HeldFirst is every received record held at position 1 of a log with id logID: across senders, and both records of a fork at position 1 from one sender, which the store keeps. They come ordered by sender key, then digest. A profile matching a stamp proof to its sender reads them to refuse a sender whose log forks at its genesis before it filters by anything else. It takes no lock.
func (*Shelf) HeldProofs ¶ added in v0.15.0
HeldProofs is every stamp proof held from senderKey for logID, by size and then shelf checkpoint, each re-verified from the bytes kept and set against the sender's counted prefix in one read, so a profile can check every held proof's bindings (its book id, checkpoint key and shelf log) at the moment it acts, never from one Receive call's events or a stored flag alone. It takes no lock.
func (*Shelf) HostLog ¶ added in v0.12.2
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) Journal ¶ added in v0.15.0
Journal returns the shelf's journal (evidencebook#461 §3): a book of kind journal, one per shelf, opened on first use, whose records are full records. Its facts are journal facts: a whole-shelf reader sees that it changed at a stamp, never its size, and its openings go only to the owner and an auditor it appoints. It needs a shelf of book facts (Migrate), and it refuses a shelf on which a book or host log already has its log id.
func (*Shelf) Legacy ¶ added in v0.5.0
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
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) Openings ¶ added in v0.15.0
func (s *Shelf) Openings(ctx context.Context, bookID string, audience Audience) ([]AudienceFact, error)
Openings is every fact of a book (by its book id) with the openings the audience may have, as OpeningsFor says (§2.2). It is the only call that hands openings out.
func (*Shelf) Receive ¶ added in v0.15.0
func (s *Shelf) Receive(ctx context.Context, record []byte, proof *StampProof) (ReceiveResult, error)
Receive takes a pushed record, a stamp proof, or both (§3), and handles each part on its own, the record first: a record sent again with a proof it lacked the first time still delivers the proof. A part refused is reported in its outcome and in the returned error (errors.Join of each part's refusal), with the result of the other part. Any other error is the store's or the profile's: one in the record part reports nothing, since nothing of it was committed; one in the proof part returns the record part's outcome and changes beside it. A call racing Release may fail with database/sql's closed-database error rather than ErrReleased.
func (*Shelf) ReceivedRecordOf ¶ added in v0.15.0
ReceivedRecordOf reads a received record by its digest. A record deleted under retention reports ErrDeleted, one never held ErrNotFound. It takes no lock: a StatusProvider or ReceiveProfile may call it.
func (*Shelf) ReceivedRecordStamp ¶ added in v0.16.0
func (s *Shelf) ReceivedRecordStamp(ctx context.Context, bookID, receivedLogID string, position uint64) (n uint64, ok bool, err error)
ReceivedRecordStamp is RecordStamp for a record the holder received: the stamp whose fact of bookID is the first whose link value's last_received names receivedLogID at a size that reaches the position, as ReceivedRecordTime finds it.
func (*Shelf) ReceivedRecordTime ¶ added in v0.15.0
func (s *Shelf) ReceivedRecordTime(ctx context.Context, bookID, receivedLogID string, position uint64, witnesses []string) (t time.Time, ok bool, err error)
ReceivedRecordTime is the record time the holder's own stamps give a record it received (docs/design/461-deal-profile.md §4.3): the record at position (from 1) of the other side's log receivedLogID, as the holder's book bookID names it. Its time is the earliest registration time, among the receipts held from the witnesses named, of a shelf checkpoint that covers the first fact of bookID whose link value's last_received names receivedLogID at a size (a record count) that reaches the position. ok is false when there is none, as for RecordTime. The other side's own stamps may give an earlier time; the profile takes the earlier of the two.
It takes no lock and reads in one transaction, as RecordTime does.
func (*Shelf) ReceivedRecordTimeByKey ¶ added in v0.15.0
func (s *Shelf) ReceivedRecordTimeByKey(ctx context.Context, bookID, receivedLogID string, position uint64, keyIDs []string) (t time.Time, ok bool, err error)
ReceivedRecordTimeByKey is ReceivedRecordTime with the witnesses named by their verified key ids, as RecordTimeByKey.
func (*Shelf) RecordStamp ¶ added in v0.16.0
func (s *Shelf) RecordStamp(ctx context.Context, bookID string, position uint64) (n uint64, ok bool, err error)
RecordStamp is the stamp (its tick, from 1) whose fact is the first to cover the record at position (from 1) of the book bookID, as RecordTime finds that fact: a record's time can come from no earlier stamp. ok is false when no fact covers the position yet, so the next stamp will be the first (docs/design/461-deal-profile.md §8.1, "Times"). It takes no lock, as RecordTime.
func (*Shelf) RecordTime ¶ added in v0.15.0
func (s *Shelf) RecordTime(ctx context.Context, bookID string, position uint64, witnesses []string) (t time.Time, ok bool, err error)
RecordTime is the record time of the record at position (from 1) of the book bookID (its book id, §2.2; the journal's included): the earliest registration time, among the receipts held from the witnesses named (their URLs), of a shelf checkpoint that covers the first fact of that book whose size covers the position (§2.6). ok is false when there is none: no fact covers the position yet, no checkpoint covering that fact has a receipt from a named witness, or every such receipt gives no registration time. A status resting on a record with no time is local, never witnessed.
It takes no lock, so a StatusProvider or ReceiveProfile may call it, and reads in one transaction, so a stamp being finished is seen whole or not at all.
func (*Shelf) RecordTimeByKey ¶ added in v0.15.0
func (s *Shelf) RecordTimeByKey(ctx context.Context, bookID string, position uint64, keyIDs []string) (t time.Time, ok bool, err error)
RecordTimeByKey is RecordTime with the witnesses named by their verified key ids (lowercase hex), as an x-deal-v1 agreement names them (Steven, #482 Q1, u604: a witness is its key, its URL only a hint, so a witness that moved stays the same witness).
func (*Shelf) Records ¶ added in v0.6.0
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
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).
func (*Shelf) SealSent ¶ added in v0.15.0
func (s *Shelf) SealSent(ctx context.Context, entry Entry, actionID string) (Record, SentCapsule, error)
SealSent appends entry to the shelf's journal and seals its standalone Capsule under actionID, with entry's Members as further top-level members of that Capsule only (the journal record's Capsule carries none: the record stays in the journal, and the members travel). entry carries exactly one payload, the record's canonical JSON (JCS) bytes, so the journal record's payload commitment and the Capsule's payload are the same bytes. The Capsule is sealed first and the journal record appended under the journal's lock. An error with an empty Record left no journal record, and the call may be retried. An error with a Record (the record was stored and its log append is pending, or it was committed and a later step failed) comes with its Capsule: the record is in the journal, so the caller sends that Capsule and does not seal the record again.
func (*Shelf) StampTime ¶ added in v0.19.0
func (s *Shelf) StampTime(ctx context.Context, n uint64, witnesses []string) (t time.Time, ok bool, err error)
StampTime is the witnessed time of the stamp n (its tick, from 1), which an x-deal-v1 status time {"stamp": n} names (docs/design/461-deal-profile.md §8.1, "Times"): the earliest registration time, among the receipts held from the witnesses named (their URLs), of the shelf checkpoint of tick n or of a later one. It is the time RecordTime gives a record that stamp is the first to cover. ok is false when no such receipt is held yet (the time is not known), and when n is a tick with no checkpoint and none later has one. It takes no lock and reads in one transaction, as RecordTime.
A stamp index is local to the shelf that cut it: n resolves only in facts of this shelf's own books. A counterparty's fact names a stamp of the counterparty's shelf, which this call cannot resolve (it would read this shelf's unrelated tick n).
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
// Receive is the store of what the other side pushes (Shelf.Receive):
// the profile that reads its records, the store's bounds and the
// holder's retention.
Receive ReceiveConfig
}
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) 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 StampBatch ¶ added in v0.15.0
type StampBatch struct {
V int `json:"v"`
Entries []BatchEntry `json:"entries"`
}
StampBatch is a stamp's stored batch: its entry documents in append order, the stamp entry last. Bytes are base64 in JSON.
type StampEntry ¶ added in v0.15.0
type StampEntry struct {
V int `json:"v"`
Kind string `json:"kind"`
Stamp uint64 `json:"stamp"`
Facts uint64 `json:"facts"`
}
StampEntry ends every stamp, so every stamp grows the shelf log and cuts a new shelf checkpoint, even one with no fact (§2.5).
type StampProof ¶ added in v0.15.0
type StampProof struct {
// Fact is the fact document's canonical JSON, a book fact.
Fact []byte `json:"fact"`
// StatusOpening is the fact's status opening, when the audience the
// proof was made for may have it.
StatusOpening *FactOpening `json:"status_opening,omitempty"`
// BookCheckpoint is the COSE statement of the book checkpoint the fact
// carries.
BookCheckpoint []byte `json:"book_checkpoint"`
// Inclusion is the fact entry's inclusion proof in the shelf log, at
// its entry position, under ShelfCheckpoint.
Inclusion InclusionEvidence `json:"inclusion"`
// ShelfCheckpoint is the COSE statement of the shelf checkpoint.
ShelfCheckpoint []byte `json:"shelf_checkpoint"`
}
StampProof shows that a holder's shelf log carries a fact of one of its books (evidencebook#461 §3): the fact, the book checkpoint it carries, the fact's inclusion in the shelf log and the shelf checkpoint that includes it. One checkpoint key signs both checkpoints: the proof's key. Its wire form on the MCP and A2A bindings is the AAC item's (§5); this is the library's form.
type StampStatusProvider ¶ added in v0.16.0
type StampStatusProvider interface {
StatusProvider
StampValues(ctx context.Context, n uint64, bookID, logID string) (profile string, link LinkValue, status json.RawMessage, ok bool, err error)
}
StampStatusProvider is a StatusProvider that is also told the stamp it gives values for: n, the tick the stamp will have (from 1), which a status value may use to name a record its own stamp is the first to cover (docs/design/461-deal-profile.md §8.1, "Times"). A shelf calls StampValues in place of Values when its provider implements it. BookStatusProvider, which is also handed the book, supersedes it.
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 StandardHistoryBundleRequest ¶ added in v0.13.7
type StandardHistoryBundleRequest struct {
// Disclose reports whether the recipient's share gate lets it have the
// record's header and payloads; nil discloses every record. A record
// that is not disclosed still travels as a digest-only capsule, which
// is what shows coverage without showing the record. The policy behind
// it is the host's (SH §6): the recipient learns nothing it may not see.
// A record its caller sealed (AppendCapsule) carries its header inside
// its capsule, and every record of the interval travels as a capsule, so
// that header cannot be withheld: refusing such a record is ErrInvalid.
Disclose func(Record) bool
// Witnesses and WitnessDirectory are BundleRequest's: witness receipts
// for the anchor, checked against the directory before the bundle is
// built.
Witnesses []json.RawMessage
WitnessDirectory []WitnessRow
// ConductPacks is BundleRequest's: a handover goes to a recipient, so a
// record citing one of these packs is refused if Disclose lets it
// through, or if its header is inline. One Disclose withholds travels
// digest-only, which shows no claim.
ConductPacks []string
}
StandardHistoryBundleRequest is what the holder hands one recipient of a log, for the log's checkpoint the card's anchor commits.
type StandardHistoryCheck ¶ added in v0.13.7
type StandardHistoryCheck struct {
Properties map[string]string
// Why is empty unless counts_recompute is NOT_CHECKED because of the
// handed material or its mapping.
Why string
}
StandardHistoryCheck is the card's six properties and, when counts_recompute is NOT_CHECKED for want of material, why.
func CheckStandardHistoryMaterial ¶ added in v0.13.7
func CheckStandardHistoryMaterial(m StandardHistoryMaterial) (StandardHistoryCheck, error)
CheckStandardHistoryMaterial reports the card's properties (SH §6), recomputing the counts from the handed bundles when, and only when, coverage is shown for the anchor's own log (a) and every other log the anchor commits (b), the mapping reads every member it needs, and the card is well formed. Otherwise counts_recompute is NOT_CHECKED: a partial handover never yields PASS, and never FAIL. The error is for a malformed input or a mapping failure, never for missing material.
type StandardHistoryMaterial ¶ added in v0.13.7
type StandardHistoryMaterial struct {
Card []byte
AsOf standardhistory.AsOf
Policy *standardhistory.Policy
// Keys pins the holder's checkpoint key (and the recipient's witness
// directory) the bundles are verified under.
Keys ResponderKeys
// Committed is every log the anchor commits, in a form the recipient
// checked against the anchor: for a log's own checkpoint, that
// checkpoint alone. It is empty for an anchor that commits its logs
// through a salted or sparse tree, such as a cadence tick's (SH-10);
// coverage is then not shown.
Committed map[string]CommittedLog
Bundles [][]byte
Deals DealMapping
}
StandardHistoryMaterial is what a recipient holds of a standard_history 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 Staple ¶ added in v0.13.0
type Staple struct {
// Request is the holder's own request, as JSON.
Request Message
// Reply is the holder's signed envelope answering Request, as JSON.
Reply Reply
}
A staple is a History card the holder attaches to its own message (a deal opening, an offer, a commitment), so a counterparty with no way to ask back can still read it (evidencebook#275, frame 4 "Stapled"; the cross-ecosystem admission design, "The stapled history").
It is built from the evidence request's own objects, so it adds no wire member: the holder's request names the derivation, pins the coverage to the holder's newest checkpoint (the staple's as-of) and carries a fresh nonce; the holder's book answers it with the signed envelope it would give any requester. A reader detects a replayed staple by the nonce and the anchor against its own min_freshness. Where the staple sits, and the witness Receipts that travel beside a card (SH-4), are the carrier's.
A staple never carries more than the standard card: only history_card/1 or history_card/2 (over the checkpoints subject) and standard_history/1 (over full_history) are stapled, all recipient-free, so the bytes are the ones every requester those cards are answered to gets.
type StapleCheck ¶ added in v0.13.0
type StapleCheck struct {
Derivation string
// Anchor is the digest of the holder checkpoint the card is as of.
Anchor string
// Nonce is the holder's nonce, for the reader's replay check.
Nonce string
IssuedAt string
// Artifact is the card, in its canonical octets.
Artifact []byte
}
StapleCheck is what CheckStaple read from a staple that passed.
func CheckStaple ¶ added in v0.13.0
func CheckStaple(s Staple, holder string) (StapleCheck, error)
CheckStaple checks that a staple is presented by holder (the lowercase hex Ed25519 key the reader names for its counterparty) and stays inside the cap: the envelope verifies under holder's key and answers this very request, the derivation is history_card/1 or history_card/2 over checkpoints or standard_history/1 over full_history, the anchor and profile are the ones the request named, and a standard_history/1 card is of the standard card's form, and a history_card/1 artifact has the card's members and nothing else (historyCardForm) and its checkpoints form one chain (historyCardChain). It does not check the anchor's checkpoint, the card's own properties or the nonce's freshness: those are the reader's verifier and policy.
type StatusInput ¶ added in v0.18.0
StatusInput is what a BookStatusProvider is handed for one book's fact: the stamp's tick n (from 1), the book's id and log id, the book itself, and the shelf's journal, nil when the shelf has none yet: before Migrate, or before the host first opens it with Shelf.Journal. A stamp never creates the journal.
type StatusProvider ¶ added in v0.15.0
type StatusProvider interface {
Values(ctx context.Context, bookID, logID string) (profile string, link LinkValue, status json.RawMessage, ok bool, err error)
}
StatusProvider gives a book's profile and the values its fact commits to (§2.4): the shelf asks it for each book at each stamp. A book no provider claims (ok false) has profile "none", the empty link value and {}.
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 ¶
SubstrateEntry is one committed position.
type SubstrateInfo ¶
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"`
// Stamp is set on a tick cut after the shelf's format switch
// (evidencebook#461, shelf_stamp.go): the tick is a stamp, its entries
// are entry documents and not a tree root, and Deals holds, for each
// fact, the log's size and checkpoint.
Stamp *StampBatch `json:"stamp,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.
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
// Unstated are the books (by log id) whose status provider failed at
// this stamp, with its error: each keeps its last fact, and the other
// books' facts are written, so one book's values never stop the shelf's
// stamps. The next stamp asks again. It is this call's report only: a
// stamp resumed after a crash does not repeat it. A reader learns that a
// book's fact is older than a stamp from the fact itself (its entry's
// tick), which is what a card shows.
Unstated map[string]string
// BeforeStamp is the status provider's BeforeStamp error before this
// stamp, "" for none (BeforeStampProvider); the stamp was still taken.
BeforeStamp string
}
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) 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 {
}
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.
func (VerifiedBundle) UnavailableWindowStatements ¶ added in v0.13.7
func (v VerifiedBundle) UnavailableWindowStatements(responderKey string, witnesses []WitnessRow) ([]evidencerequest.WindowStatement, error)
UnavailableWindowStatements reads the unavailable-window statements out of a bundle VerifyBundleAnswer accepted, as the reader holding them for the responder whose signing key is responderKey: each record of type RecordTypeUnavailableWindow whose header the bundle verified and whose position the authenticated anchor covers. The anchor's receipts are checked against witnesses, the reader's own list of the transparency services it accepts (the directory VerifyBundleAnswer takes); a receipt counts when it verifies there, attests a time, and is made under neither responderKey nor the anchor's checkpoint key (a service the responder controls is never independent). responderKey is the raw Ed25519 key in lowercase hex a response would be authenticated by. The IDs are the records' ids.
The receipts are those the bundle's anchor carries (checkpoint.witnesses). This package does not fetch them; BundleRequest.Witnesses carries them (see SealUnavailableWindow); a bundle whose anchor carries none registers no statement.
A statement that is malformed, unsigned by the responder or unregistered is returned all the same: evidencerequest.DisplayAbsence ignores it, as the draft's reader does.
type VerifiedStampProof ¶ added in v0.15.0
type VerifiedStampProof struct {
Fact BookFact
BookCheckpoint Checkpoint
ShelfCheckpoint Checkpoint
// KeyID is the checkpoint key that signed both checkpoints.
KeyID string
}
VerifiedStampProof is what a stamp proof shows once verified.
func VerifyStampProof ¶ added in v0.15.0
func VerifyStampProof(p StampProof) (VerifiedStampProof, error)
VerifyStampProof checks a stamp proof on its own (§3, "the proof"): both checkpoints verify and are signed by one key; the fact is a canonical book fact whose log and size are the book checkpoint's, and whose checkpoint_sha256 is the statement's digest; a status opening given recomputes its commitment; and the fact's entry is included under the shelf checkpoint. What the proof says against the records held is the store's (Receive).
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.
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
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.
Source Files
¶
- book.go
- bundle.go
- bundle_diff.go
- bundle_producer.go
- cadence.go
- cadence_chain.go
- cadence_history_card.go
- cadence_import.go
- cadence_standard_history.go
- cadence_tree.go
- canonical.go
- close.go
- commitment.go
- deal_reconcile.go
- disclosure_policy.go
- doc.go
- doctor.go
- errors.go
- history_card2.go
- index_authenticated.go
- index_discovery.go
- index_operational.go
- interop_a2a.go
- interop_artifact.go
- interop_cll.go
- interop_derivation.go
- interop_manifest.go
- interop_mcp.go
- interop_reply.go
- interop_request.go
- interop_respond.go
- interop_retention.go
- interop_standard_history.go
- interop_value.go
- jsontree.go
- originals.go
- reconcile.go
- reconcile_asked.go
- record.go
- request.go
- request_limits.go
- result_seal.go
- retention.go
- shelf.go
- shelf_facts.go
- shelf_handover.go
- shelf_handover_tie.go
- shelf_handover_times.go
- shelf_held.go
- shelf_lock_unix.go
- shelf_random.go
- shelf_receive.go
- shelf_record_time.go
- shelf_records.go
- shelf_sent.go
- shelf_stamp.go
- shelf_stamp_proof.go
- signer.go
- standard_history_material.go
- staple.go
- store.go
- store_sqlite.go
- substrate.go
- substrate_cll.go
- substrate_scitt.go
- unavailable_window.go
- witness.go
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. |
|
x-deal-v1
Package xdealv1files ships the x-deal-v1 profile's files (its record schema) to Go code.
|
Package xdealv1files ships the x-deal-v1 profile's files (its record schema) to Go code. |
|
xdealv1
Package xdealv1 is the x-deal-v1 deal record profile (evidencebook#461, docs/design/461-deal-profile.md): its names, its record types and bodies, a record's strict encoding and digest, and the checks a single record must pass.
|
Package xdealv1 is the x-deal-v1 deal record profile (evidencebook#461, docs/design/461-deal-profile.md): its names, its record types and bodies, a record's strict encoding and digest, and the checks a single record must pass. |
|
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
|
|
|
Package rowstatus computes the status of one term row of a deal from the two sides' statements on it and the dates (evidencebook#461, acceptance 6).
|
Package rowstatus computes the status of one term row of a deal from the two sides' statements on it and the dates (evidencebook#461, acceptance 6). |
|
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/deal-v1
command
Command deal-v1 is the Go side of the x-deal-v1 differential check (test/interop/deal-v1/diff.py): one JSON request per line on stdin, {"kind": "check", "record": <text>}, {"kind": "status", "books": ...} or {"kind": "report", "books": ..., "copy": ...} or {"kind": "verify_report", "payload": ..., "first": <hex>}, and one line out for each: "ok" or the refusal's stage for a check, the JCS of the status value or the report, the JCS of {"key_id", "report"} for a verified report and {"stage": ...} for one refused, or {"error":true} when it is refused.
|
Command deal-v1 is the Go side of the x-deal-v1 differential check (test/interop/deal-v1/diff.py): one JSON request per line on stdin, {"kind": "check", "record": <text>}, {"kind": "status", "books": ...} or {"kind": "report", "books": ..., "copy": ...} or {"kind": "verify_report", "payload": ..., "first": <hex>}, and one line out for each: "ok" or the refusal's stage for a check, the JCS of the status value or the report, the JCS of {"key_id", "report"} for a verified report and {"stage": ...} for one refused, or {"error":true} when it is refused. |
|
interop/goose-capsule
command
Command goose-capsule is Go's check of a Capsule the Goose reference (python/examples/goose) sealed with loop_seal: Class 1 verification, the producer envelope under the key_id it carries, and the effect and model members the loop's step 01 reads.
|
Command goose-capsule is Go's check of a Capsule the Goose reference (python/examples/goose) sealed with loop_seal: Class 1 verification, the producer envelope under the key_id it carries, and the effect and model members the loop's step 01 reads. |
|
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/row-status
command
Command row-status is the Go side of the row status differential check (test/interop/row-status/diff.py): one JSON input per line on stdin, one line out for each, the result or {"error":true}.
|
Command row-status is the Go side of the row status differential check (test/interop/row-status/diff.py): one JSON input per line on stdin, one line out for each, the result or {"error":true}. |
|
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. |