Upgrade from v1
v2 is not a drop-in upgrade. Keys, delegations, challenges, status, and the verifier call all change, and v1 proofs stay on a v1 verifier. This page follows the protocol’s upgrade guide, which also holds the full v1 to v2 concept map. Section numbers refer to SPEC-v2.
Compatibility
Section titled “Compatibility”- v2 is not backward compatible with v1. Signed bytes, key IDs, challenge signing, status references, and verifier ordering all differ. A v2 verifier rejects v1 objects, and there is no automatic fallback in either direction.
- Migration is a clean re-enrollment. Generate fresh v2 keys and issue new v2 delegations. No v1 key can authorize a v2 key, and importing a v1 key into a v2 identity is prohibited.
- Side by side is supported. v1 and v2 run together in one build or environment in every ecosystem. A deployment chooses the version explicitly at each API boundary and keeps a v1 verifier for v1 proofs until it retires them.
- v1 stays available and pinned. Released v1 tags and artifacts are never moved or replaced, and v2 never widens a v1 dependency range. There is no fixed, dated v1 support window today; v1 support terms will be announced with 2.0.0.
- Some capabilities stay on v1 until 2.1: the
SessionTokenfast path, A2A mutual presentation, the HTTP and registry bindings, and the geo and speed constraints. A claim that depends on one is a v1 claim. See v1-only until 2.1.
More detail: Is v2 compatible with v1?
Install
Section titled “Install”| SDK | v2 (beta line) | v1 (stays available) |
|---|---|---|
| Go | go get github.com/identities-ai/ratify-protocol/[email protected], import github.com/identities-ai/ratify-protocol/v2 | go get github.com/identities-ai/[email protected] (original module path) |
| TypeScript | npm install @identities-ai/[email protected] (dist-tag next), import from @identities-ai/ratify-protocol/v2 | npm install @identities-ai/[email protected] (dist-tag latest) |
| Python | pip install "ratify-protocol[protocol-v2]==2.0.0b2", import ratify_protocol.v2 | pip install ratify-protocol==1.0.0a21, import ratify_protocol |
| Rust | cargo add [email protected], use ratify_protocol::v2 | ratify-protocol = "=1.0.0-alpha.21" |
| C/C++ | ratify-c 2.x release archive, or cargo build –release in sdks/c; include ratify.h, call ratify_v2_, check | The 1.0.0-alpha.21 release archive and its ratify_ | ABI
Running both in one build
Section titled “Running both in one build”-
Go: the two lines have different module paths, so one module can require both and import them under different names, for example
ratifyv1andratify. -
TypeScript: the 2.x package exports v2 from the
/v2subpath and keeps the v1 API at the package root. To keep the exact v1 release as well, add an alias:Terminal window An unpinned npm install resolves to v1 until 2.0.0.
-
Python: the 2.x distribution keeps the v1 API at
ratify_protocoland addsratify_protocol.v2, so one environment runs both, andimport ratify_protocolnever loads v2. Theprotocol-v2extra brings v2’s requirements (theratify-protocol-native-v2signing backend and a pinnedtzdatarelease); the base install keeps v1’s. The exact v1 release cannot sit next to 2.x in one environment because both use the same distribution name, so a process that must run the exact v1 release needs its own environment. -
Rust: the 2.x crate keeps the v1 API at the crate root and adds
ratify_protocol::v2. To keep the exact v1 release as well, rename it:ratify_v1 = { package = "ratify-protocol", version = "=1.0.0-alpha.21" } -
C/C++: the 2.x library exports the unchanged v1
ratify_*ABI next to theratify_v2_*ABI. Checkratify_v2_abi_version()at startup.
Upgrade steps
Section titled “Upgrade steps”-
Keep v1 running and pin it. Pin the exact v1 release you run today and keep its verifier for existing v1 proofs. Do not widen a v1 dependency range to include 2.x. Install v2 next to it on a test branch.
-
Generate v2 keys and prove possession. Every principal (organization or person root, issuer, agent, verifier, status publisher) gets a fresh v2 hybrid key. Establish who owns each root out of band, have the holder prove possession of the new key, and configure trust as the complete root public key. Never pin trust to a key ID alone: the verifier recomputes the ID from the key you configured and fails closed on any mismatch or ambiguity. See Typed signing and key IDs.
-
Reissue delegations with v2 constraint schemas. Use the typed signer (
SignDelegationCertV2or its external-signer form), which checks issuer duties before it signs.- Every certificate has a finite
expires_at, at most 315360000 seconds (ten years) after issue. There is no no-expiry sentinel. - Amounts move from floats to integers: 50.00 USD is
{"type":"max_amount","currency":"USD","max_amount_micros":50000000}, and the verifier receives the requested amount in the same unit. - A required
custom:scope is one exactcustom:<name>that every certificate in the chain lists.custom:*is invalid. - Application-specific constraints move to extension types evaluated by a registered
profile: the standard
com.ratifyprotocol.max_count/v1andcom.ratifyprotocol.allowed_values/v1, or your own versioned profile. A verifier without the profile fails closed withconstraint_unknown. geo_circle,geo_polygon,geo_bbox, andmax_speed_mpshave no v2.0 equivalent. Keep those delegations on v1 until 2.1, or bind the condition in application policy after release.
- Every certificate has a finite
-
Set up signed status with a separate status key. Give each issuer a status key distinct from every root, issuer, agent, and verifier key. Record key roles and the status key epoch in the
SecurityJournalV2, and run the status publisher: a genesis list, heartbeats that refresh freshness, and revocations as a signed push plus the cumulative list. Persist the publisher state before you publish each object. This replaces v1 revocation callbacks; an unavailable or stale status yieldsindeterminate, never allow. See Status from signed evidence. -
Issue challenges with the issuance helper. It reads the authoritative clock, draws 32 random bytes, and persists the full record before it returns the challenge. The verifier loads the record by the presented challenge. Challenge lifetime is 1 to 300 seconds, and every deadline is exclusive. See One-time challenges and claims.
-
Move verifiers to verify, commit, release. Call
VerifyProofBundleV2with the stored expected challenge, an explicit context policy, the required scope, the request context, the status keys and policy, and the evaluator registry. Publish the committed receipt body to your receipt log, wait for the checkpoint acknowledgement, and callReleaseV2Decision. Gate each side effect onAllowed(clock)just before it runs. Move application policy (the v1PolicyProviderrole) to after release, where it may only narrow the decision. Map v1 statuses to the v2 decision, reason, and the 49 error classes (§2.7). See Committed vs. released. -
Supply durable Part B stores. The SDKs’ reference stores are in-memory and test-only. Production needs durable implementations of the claim store with an authoritative clock, the challenge issuance store, stream sequence and rate reservation, the receipt outbox and log, an independent checkpoint in a separate failure domain, and the anchored journal store with compare-and-swap. See Deployment profiles.
-
Test before cutover. Run the SDK’s own suite against
testvectors/v2, the lifecycle scenarios, and your deployment’s failure cases: status unavailable, checkpoint withheld, signer failure, clock regression, replay, and restore. -
Run side by side, then retire v1. Send a v1 proof to the v1 verifier and a v2 proof to the v2 verifier, with no fallback between them. Move issuers first so new delegations are v2, then move verifiers, then stop issuing v1 delegations. Remove the v1 verifier when no live v1 delegation remains. Retiring a hosted v1 endpoint does not revoke proofs that third-party offline verifiers may still accept, so revoke outstanding v1 delegations through the v1 status path first.
What changes at 2.0.0
Section titled “What changes at 2.0.0”2.0.0 changes what an unpinned install resolves to. It changes no import path, so code written
against 2.0.0-beta.2 needs no import change.
- Import paths are permanent. v2 stays at
github.com/identities-ai/ratify-protocol/v2,@identities-ai/ratify-protocol/v2,ratify_protocol.v2,ratify_protocol::v2, and theratify_v2_*C ABI. The package roots keep the v1 API; nothing changes meaning under an existing import. - Default installs move to v2. npm
latestmoves to 2.0.0, a plainpip install ratify-protocolandcargo add ratify-protocolresolve to 2.0.0, and the GitHub release is marked latest. - Python’s v2 requirements join the base install. From 2.0.0, installing
ratify-protocolalso installs the v2 signing backend and the pinnedtzdatarelease. Theprotocol-v2extra stays accepted, so existing install commands keep working. - v1 stays installable. Released v1 versions are never moved or replaced. After 2.0.0, v1
maintenance releases publish to npm under the
v1dist-tag and never takelatestback. Pinned v1 installs in every ecosystem are unaffected. v1 support terms will be announced with 2.0.0.
Per-SDK before and after
Section titled “Per-SDK before and after”The before side is the v1 flow you run today. The after side is the v2 quickstart example, rendered from the protocol repository at a pinned commit.
Before (v1):
v1 calls: ratify.GenerateChallenge (verifier generates a challenge), ratify.Verify(bundle, opts)
returning a result with Valid and IdentityStatus, and an optional RevocationProvider.
Full v1 program: Go SDK, three minutes end to end.
After (v2):
v2 calls: V2ChallengeIssuer.IssueChallengeV2, VerifyProofBundleV2 (committed outcome),
ReleaseV2Decision, then (*V2ReleasedDecision).Allowed(ctx, clock) before the side effect.
Status comes from NewV2StatusPublisher.
// Ratify Protocol v2 quickstart: delegate, present, verify, publish, release.//// DEVELOPMENT ONLY. This program uses the in-memory reference stores from// package v2reference (claim store, receipt log, checkpoint, journal and// challenge issuance store). They exist for tests and examples. A production// verifier supplies durable Part B stores and an independent checkpoint// (SPEC-v2 §7).//// Run from the repository root: go run ./examples/v2/go/quickstartpackage main
import ( "context" "fmt" "os" "strings"
ratify "github.com/identities-ai/ratify-protocol/v2" "github.com/identities-ai/ratify-protocol/v2/v2reference")
const ( start = int64(1800000000) // fixed clock so the output is reproducible namespace = "quickstart" epoch = int64(1) logID = "00000000000000000000000000000001")
func main() { if err := run(); err != nil { fmt.Fprintln(os.Stderr, "error:", err) os.Exit(1) }}
func run() error { ctx := context.Background() fmt.Println("Ratify Protocol v2 quickstart") fmt.Println("development only: in-memory reference stores")
// 1. Keys. Every party holds a hybrid Ed25519 + ML-DSA-65 key. The status // key is separate from the root key that issues delegations. rootPub, rootPriv, err := ratify.GenerateHybridKeypair() if err != nil { return err } agentPub, agentPriv, err := ratify.GenerateHybridKeypair() if err != nil { return err } statusPub, statusPriv, err := ratify.GenerateHybridKeypair() if err != nil { return err } verifierPub, verifierPriv, err := ratify.GenerateHybridKeypair() if err != nil { return err } rootID, _ := ratify.KeyIDV2(rootPub) agentID, _ := ratify.KeyIDV2(agentPub) verifierID, _ := ratify.KeyIDV2(verifierPub) fmt.Printf("keys: root, agent, status and verifier generated (key IDs are %d hex characters)\n", len(rootID))
// 2. The root delegates payments:send to the agent, capped at 50.00 USD // per action (amounts are integer micro-units in v2). cert, err := ratify.SignDelegationCertV2(&ratify.DelegationCertV2{ Version: 2, CertID: "quickstart-cert-1", IssuerID: rootID, IssuerPubKey: rootPub, SubjectID: agentID, SubjectPubKey: agentPub, Scope: []string{"payments:send"}, Constraints: []ratify.ConstraintV2{ {Type: ratify.ConstraintMaxAmount, Currency: "USD", MaxAmountMicros: 50_000_000}, }, IssuedAt: start, ExpiresAt: start + 86400, }, rootPriv) if err != nil { return err } fmt.Println("delegation: scope=payments:send max_amount=50000000 USD micros lifetime=86400s")
// 3. Verifier state: the reference store is the claim store, receipt log, // checkpoint and authoritative clock. The journal records key roles and // the root's status key. store, err := v2reference.NewStore(start, 30, logID, verifierPriv) if err != nil { return err } journal, err := v2reference.NewJournalStore() if err != nil { return err } for role, pub := range map[string]ratify.HybridPublicKey{"issuer": rootPub, "delegation": agentPub, "verifier": verifierPub} { if _, err := ratify.RecordSecurityKeyRoleV2(ctx, journal, role, pub); err != nil { return err } } if _, err := ratify.ConfigureStatusKeyEpochV2(ctx, journal, rootID, 1, statusPub); err != nil { return err }
// 4. The root's status publisher signs a genesis revocation list (no // revocations) under the separate status key. publisher, err := ratify.NewV2StatusPublisherWithKey(ctx, journal, rootPub, statusPriv, 3600) if err != nil { return err } genesis, err := publisher.Genesis(ctx, start) if err != nil { return err } statusWire, err := ratify.EncodeRevocationListV2(genesis.List) if err != nil { return err } fmt.Printf("status: genesis list signed by the status key (sequence %d, %d revoked)\n", genesis.State.Sequence, len(genesis.State.Revoked))
// 5. The verifier issues a challenge. The helper persists the record // before it returns the challenge. issuance := v2reference.NewTestOnlyChallengeIssuanceStore() issuer := ratify.V2ChallengeIssuer{Clock: store, Store: issuance} challenge, err := issuer.IssueChallengeV2(ctx, ratify.V2ChallengeIssueRequest{ VerifierNamespace: namespace, ReplayEpoch: epoch, VerifierID: verifierID, LifetimeSeconds: 120, ExpectedAgentID: agentID, ExpectedAgentPublicKey: &agentPub, }) if err != nil { return err } fmt.Printf("challenge: issued and persisted, expires in %ds\n", challenge.ExpiresAt-challenge.IssuedAt)
// 6. The agent signs a proof bundle over the challenge. store.SetTime(start + 2) bundle, err := ratify.SignProofBundleV2(&ratify.ProofBundleV2{ Version: 2, VerifierID: verifierID, AgentID: agentID, AgentPubKey: agentPub, Delegations: []ratify.DelegationCertV2{*cert}, Challenge: challenge.Value, ChallengeAt: challenge.IssuedAt, }, agentPriv) if err != nil { return err } bundleWire, err := ratify.EncodeProofBundleV2(bundle) if err != nil { return err } fmt.Printf("proof: agent signed the presentation (%d delegation)\n", len(bundle.Delegations))
// 7. Verify. The verifier loads the issuance record for the presented // challenge, then runs the full v2 decision path. verify := func() (ratify.V2VerifyOutcome, error) { expected, err := ratify.LoadExpectedChallengeV2(ctx, issuance, namespace, epoch, bundle.Challenge) if err != nil { return ratify.V2VerifyOutcome{}, err } policy, err := ratify.NewV2ContextPolicy("example.quickstart/v1", false, nil, nil) if err != nil { return ratify.V2VerifyOutcome{}, err } req := ratify.V2VerifyRequest{ Bundle: bundleWire, Expected: expected, ContextPolicy: policy, RequiredScope: "payments:send", VerifierNamespace: namespace, ReplayEpoch: epoch, VerifierID: verifierID, Now: store.Now(), MaxChallengeAgeSeconds: 300, FutureSkewSeconds: 5, Context: ratify.ConstraintContextV2{HasAmount: true, RequestedAmountMicros: 12_500_000, RequestedCurrency: "USD"}, TZDBVersion: ratify.TZDBVersionV2, StatusKeys: map[string]ratify.V2StatusKeyConfig{rootID: {Epoch: 1, Key: statusPub}}, StatusPolicy: ratify.RevocationStatusPolicyV2{MaxListLifetimeSeconds: 3600, MaxStatusAgeSeconds: 3600, ClockSkewSeconds: 5}, } cb := ratify.V2VerifyCallbacks{ ClaimStore: store, // Trust is pinned to the complete root public key, never a key ID. Trust: func(_ context.Context, chain []ratify.DelegationCertV2) (ratify.V2TrustResolution, error) { if last := chain[len(chain)-1]; last.IssuerID == rootID { return ratify.V2TrustResolution{Outcome: ratify.V2TrustTrusted, RootKey: rootPub}, nil } return ratify.V2TrustResolution{Outcome: ratify.V2TrustUntrusted}, nil }, StatusEvidence: func(context.Context, ratify.V2StatusEvidenceRequest) (ratify.V2StatusEvidenceBatch, error) { return ratify.V2StatusEvidenceBatch{Objects: []ratify.V2StatusEvidenceObject{{ObjectType: 3, Wire: statusWire}}}, nil }, StatusJournal: journal, } return ratify.VerifyProofBundleV2(ctx, req, cb) } outcome, err := verify() if err != nil { return err } if outcome.Stage != ratify.V2StageCommitted { return fmt.Errorf("verify stopped at %s: %v", outcome.Stage, outcome.Error) } fmt.Println("verify: stage=committed (not actionable until released)")
// 8. Publish the signed receipt to the log; the checkpoint acknowledges it. receiptWire, err := store.PublishV2Receipt(ctx, outcome.Committed.ClaimID(), outcome.Committed.ReceiptBody()) if err != nil { return err } receipt, err := ratify.DecodeVerificationReceiptV2(receiptWire) if err != nil { return err } fmt.Printf("receipt: published at log sequence %d\n", receipt.Sequence) ack, err := store.GetV2Acknowledgement(ctx, logID, receipt.Sequence) if err != nil { return err } fmt.Printf("checkpoint: acknowledged sequence %d\n", ack.Sequence)
// 9. Release. Only a released decision is actionable. result := ratify.ReleaseV2Decision(ctx, outcome.Committed, receiptWire, ratify.V2ReleaseConfig{ VerifierPublicKey: verifierPub, LogID: logID, ClaimStore: store, Checkpoint: store, }) if result.Status != ratify.V2ReleaseReleased { return fmt.Errorf("release %s: %s", result.Status, result.Reason) } decision := result.Decision fmt.Printf("release: status=%s decision=%s reason=%s\n", result.Status, decision.Decision(), decision.Reason()) fmt.Printf("granted scope: %s\n", strings.Join(decision.GrantedScope(), ","))
// 10. Gate the side effect on Allowed at the receiver's authoritative time. fmt.Printf("allowed now: %t\n", decision.Allowed(ctx, store))
// 11. Presenting the same proof again is a replay and is never evaluated. store.SetTime(start + 3) replay, _ := verify() fmt.Printf("replay: stage=%s disposition=%s\n", replay.Stage, replay.Disposition)
// 12. The released allow ends at the challenge expiry (an exclusive deadline). store.SetTime(challenge.ExpiresAt) fmt.Printf("allowed at challenge expiry: %t\n", decision.Allowed(ctx, store)) return nil}Source: examples/v2/go/quickstart at commit 5ca7585c2c1d, SHA-256 checked at build time.
Before (v1):
v1 calls: generateChallenge, signChallenge, verifyBundle(bundle, options) returning
valid and identity_status, and an optional revocation callback.
Full v1 program: TypeScript SDK, three minutes end to end.
After (v2):
# Exact pin (recommended). The "next" dist-tag tracks the newest v2 prerelease;# "latest" stays on Protocol v1 until 2.0.0.v2 calls (from the /v2 subpath): issueChallengeV2, verifyProofBundleV2,
releaseV2Decision, then await released.allowed(clock) before the side effect. Status comes
from newV2StatusPublisher.
// Ratify Protocol v2 quickstart: delegate, present, verify, publish, release.//// DEVELOPMENT ONLY. This program uses the in-memory reference stores from// @identities-ai/ratify-protocol/v2/reference (claim store, receipt log,// checkpoint, journal and challenge issuance store). They exist for tests and// examples. A production verifier supplies durable Part B stores and an// independent checkpoint (SPEC-v2 §7).//// Run from this directory: node quickstart.tsimport { generateHybridKeypair } from "@identities-ai/ratify-protocol";import { TZDB_VERSION_V2, configureStatusKeyEpochV2, decodeVerificationReceiptV2, encodeProofBundleV2, encodeRevocationListV2, issueChallengeV2, keyIDV2, loadExpectedChallengeV2, newV2ContextPolicy, newV2StatusPublisherWithKey, recordSecurityKeyRoleV2, releaseV2Decision, signDelegationCertV2, signProofBundleV2, verifyProofBundleV2, type DelegationCertV2, type HybridKeyPairV2, type V2VerifyOutcome,} from "@identities-ai/ratify-protocol/v2";import { ChallengeIssuanceStoreTestOnly, JournalStoreTestOnly, StoreTestOnly } from "@identities-ai/ratify-protocol/v2/reference";
const start = 1800000000; // fixed clock so the output is reproducibleconst namespace = "quickstart";const epoch = 1;const logID = "00000000000000000000000000000001";const unsigned = { ed25519: new Uint8Array(0), ml_dsa_65: new Uint8Array(0) }; // replaced when signed
console.log("Ratify Protocol v2 quickstart");console.log("development only: in-memory reference stores");
// 1. Keys. Every party holds a hybrid Ed25519 + ML-DSA-65 key. The status// key is separate from the root key that issues delegations.const root: HybridKeyPairV2 = await generateHybridKeypair();const agent: HybridKeyPairV2 = await generateHybridKeypair();const status: HybridKeyPairV2 = await generateHybridKeypair();const verifier: HybridKeyPairV2 = await generateHybridKeypair();const rootID = keyIDV2(root.publicKey);const agentID = keyIDV2(agent.publicKey);const verifierID = keyIDV2(verifier.publicKey);console.log(`keys: root, agent, status and verifier generated (key IDs are ${rootID.length} hex characters)`);
// 2. The root delegates payments:send to the agent, capped at 50.00 USD per// action (amounts are integer micro-units in v2).const cert: DelegationCertV2 = await signDelegationCertV2({ version: 2, cert_id: "quickstart-cert-1", issuer_id: rootID, issuer_pub_key: root.publicKey, subject_id: agentID, subject_pub_key: agent.publicKey, scope: ["payments:send"], constraints: [{ type: "max_amount", currency: "USD", max_amount_micros: 50_000_000 }], issued_at: start, expires_at: start + 86400, signature: unsigned,}, root);console.log("delegation: scope=payments:send max_amount=50000000 USD micros lifetime=86400s");
// 3. Verifier state: the reference store is the claim store, receipt log,// checkpoint and authoritative clock. The journal records key roles and the// root's status key.const store = new StoreTestOnly(start, 30, logID, verifier);const journal = new JournalStoreTestOnly();await recordSecurityKeyRoleV2(journal, "issuer", root.publicKey);await recordSecurityKeyRoleV2(journal, "delegation", agent.publicKey);await recordSecurityKeyRoleV2(journal, "verifier", verifier.publicKey);await configureStatusKeyEpochV2(journal, rootID, 1, status.publicKey);
// 4. The root's status publisher signs a genesis revocation list (no// revocations) under the separate status key.const publisher = await newV2StatusPublisherWithKey(journal, root.publicKey, status, 3600);const genesis = await publisher.genesis(start);const statusWire = encodeRevocationListV2(genesis.list);console.log(`status: genesis list signed by the status key (sequence ${genesis.state.sequence}, ${genesis.state.revoked.length} revoked)`);
// 5. The verifier issues a challenge. The helper persists the record before// it returns the challenge.const issuance = new ChallengeIssuanceStoreTestOnly();const challenge = await issueChallengeV2({ clock: store, store: issuance }, { verifierNamespace: namespace, replayEpoch: epoch, verifierID, lifetimeSeconds: 120, expectedAgentID: agentID, expectedAgentPublicKey: agent.publicKey,});console.log(`challenge: issued and persisted, expires in ${challenge.expiresAt - challenge.issuedAt}s`);
// 6. The agent signs a proof bundle over the challenge.store.setTime(start + 2);const bundle = await signProofBundleV2({ version: 2, verifier_id: verifierID, agent_id: agentID, agent_pub_key: agent.publicKey, delegations: [cert], delegation_digest: new Uint8Array(0), challenge: challenge.value, challenge_at: challenge.issuedAt, challenge_sig: unsigned, session_context: null, stream_id: null, stream_seq: null,}, agent);const bundleWire = encodeProofBundleV2(bundle);console.log(`proof: agent signed the presentation (${bundle.delegations!.length} delegation)`);
// 7. Verify. The verifier loads the issuance record for the presented// challenge, then runs the full v2 decision path.async function verify(): Promise<V2VerifyOutcome> { const expected = await loadExpectedChallengeV2(issuance, namespace, epoch, bundle.challenge); return verifyProofBundleV2({ bundle: bundleWire, expected, contextPolicy: newV2ContextPolicy("example.quickstart/v1", false, null, null), requiredScope: "payments:send", verifierNamespace: namespace, replayEpoch: epoch, verifierID, now: store.now(), maxChallengeAgeSeconds: 300, futureSkewSeconds: 5, context: { hasAmount: true, requestedAmountMicros: 12_500_000, requestedCurrency: "USD" }, tzdbVersion: TZDB_VERSION_V2, statusKeys: new Map([[rootID, { epoch: 1, key: status.publicKey }]]), statusPolicy: { maxListLifetimeSeconds: 3600, maxStatusAgeSeconds: 3600, clockSkewSeconds: 5 }, }, { claimStore: store, // Trust is pinned to the complete root public key, never a key ID. trust: (chain) => chain[chain.length - 1]!.issuer_id === rootID ? { outcome: "trusted", rootKey: root.publicKey } : { outcome: "untrusted" }, statusEvidence: async () => ({ objects: [{ objectType: 3, wire: statusWire }] }), statusJournal: journal, });}const outcome = await verify();if (outcome.stage !== "committed" || !outcome.committed) throw new Error(`verify stopped at ${outcome.stage}: ${outcome.error}`);console.log("verify: stage=committed (not actionable until released)");
// 8. Publish the signed receipt to the log; the checkpoint acknowledges it.const receiptWire = await store.publishV2Receipt(outcome.committed.claimID(), outcome.committed.receiptBody());const receipt = decodeVerificationReceiptV2(receiptWire);console.log(`receipt: published at log sequence ${receipt.sequence}`);const ack = await store.getV2Acknowledgement(logID, receipt.sequence);console.log(`checkpoint: acknowledged sequence ${ack.sequence}`);
// 9. Release. Only a released decision is actionable.const result = await releaseV2Decision(outcome.committed, receiptWire, { verifierPublicKey: verifier.publicKey, logID, claimStore: store, checkpoint: store,});if (result.status !== "released" || !result.decision) throw new Error(`release ${result.status}: ${result.reason}`);const decision = result.decision;console.log(`release: status=${result.status} decision=${decision.decision()} reason=${decision.reason()}`);console.log(`granted scope: ${decision.grantedScope().join(",")}`);
// 10. Gate the side effect on allowed() at the receiver's authoritative time.console.log(`allowed now: ${await decision.allowed(store)}`);
// 11. Presenting the same proof again is a replay and is never evaluated.store.setTime(start + 3);const replay = await verify();console.log(`replay: stage=${replay.stage} disposition=${replay.disposition}`);
// 12. The released allow ends at the challenge expiry (an exclusive deadline).store.setTime(challenge.expiresAt);console.log(`allowed at challenge expiry: ${await decision.allowed(store)}`);Source: examples/v2/typescript/quickstart at commit 5ca7585c2c1d, SHA-256 checked at build time.
Before (v1):
pip install ratify-protocol==1.0.0a21v1 calls: generate_challenge, sign_challenge, verify_bundle(bundle, options) returning
valid and identity_status.
Full v1 program: Python SDK, three minutes end to end.
After (v2):
# One distribution for both lines: import ratify_protocol.v2 for v2; ratify_protocol stays v1.# The protocol-v2 extra installs the v2 signing backend.pip install "ratify-protocol[protocol-v2]==2.0.0b2"v2 calls (module ratify_protocol.v2): V2ChallengeIssuer.issue_challenge_v2,
verify_v2.verify_proof_bundle_v2, release_v2.release_v2_decision, then
released.allowed(ctx, clock) before the side effect. Status comes from
status_publisher_v2.new_v2_status_publisher_with_key or its external-signer form.
"""Ratify Protocol v2 quickstart: delegate, present, verify, publish, release.
DEVELOPMENT ONLY. This program uses the in-memory reference stores fromratify_protocol.v2.v2reference (claim store, receipt log, checkpoint, journaland challenge issuance store). They exist for tests and examples. Aproduction verifier supplies durable Part B stores and an independentcheckpoint (SPEC-v2 §7).
Run: python examples/v2/python/quickstart.py"""from ratify_protocol.v2 import background, key_id_v2from ratify_protocol.v2.challenge_issuance_v2 import V2ChallengeIssuer, V2ChallengeIssueRequest, load_expected_challenge_v2from ratify_protocol.v2.constraints_v2 import CONSTRAINT_MAX_AMOUNT, TZDB_VERSION_V2, ConstraintContextV2, ConstraintV2from ratify_protocol.v2.context_policy_v2 import new_v2_context_policyfrom ratify_protocol.v2.protocol_v2 import ( DelegationCertV2, ProofBundleV2, encode_proof_bundle_v2, encode_revocation_list_v2, sign_delegation_cert_v2, sign_proof_bundle_v2,)from ratify_protocol.v2.release_v2 import V2_RELEASE_RELEASED, V2ReleaseConfig, release_v2_decisionfrom ratify_protocol.v2.security_journal_v2 import configure_status_key_epoch_v2, record_security_key_role_v2from ratify_protocol.v2.signing_v2 import generate_keypair_v2from ratify_protocol.v2.status_batch_v2 import V2StatusEvidenceBatch, V2StatusEvidenceObjectfrom ratify_protocol.v2.status_provenance_v2 import V2StatusKeyConfigfrom ratify_protocol.v2.status_publisher_v2 import new_v2_status_publisher_with_keyfrom ratify_protocol.v2.status_state_v2 import RevocationStatusPolicyV2from ratify_protocol.v2.v2reference.challenges import TestOnlyChallengeIssuanceStorefrom ratify_protocol.v2.v2reference.journal import new_journal_storefrom ratify_protocol.v2.v2reference.store import Storefrom ratify_protocol.v2.verification_receipt_v2 import decode_verification_receipt_v2from ratify_protocol.v2.verify_v2 import ( V2_STAGE_COMMITTED, V2TrustResolution, V2VerifyCallbacks, V2VerifyRequest, verify_proof_bundle_v2,)
START = 1800000000 # fixed clock so the output is reproducibleNAMESPACE = "quickstart"EPOCH = 1LOG_ID = "00000000000000000000000000000001"
def b(value: bool) -> str: return "true" if value else "false"
def main() -> None: ctx = background() print("Ratify Protocol v2 quickstart") print("development only: in-memory reference stores")
# 1. Keys. Every party holds a hybrid Ed25519 + ML-DSA-65 key. The status # key is separate from the root key that issues delegations. root_pub, root_priv = generate_keypair_v2() agent_pub, agent_priv = generate_keypair_v2() status_pub, status_priv = generate_keypair_v2() verifier_pub, verifier_priv = generate_keypair_v2() root_id, agent_id, verifier_id = key_id_v2(root_pub), key_id_v2(agent_pub), key_id_v2(verifier_pub) print(f"keys: root, agent, status and verifier generated (key IDs are {len(root_id)} hex characters)")
# 2. The root delegates payments:send to the agent, capped at 50.00 USD # per action (amounts are integer micro-units in v2). cert = sign_delegation_cert_v2(DelegationCertV2( version=2, cert_id="quickstart-cert-1", issuer_id=root_id, issuer_pub_key=root_pub, subject_id=agent_id, subject_pub_key=agent_pub, scope=["payments:send"], constraints=[ConstraintV2(type=CONSTRAINT_MAX_AMOUNT, currency="USD", max_amount_micros=50_000_000)], issued_at=START, expires_at=START + 86400, ), root_priv) print("delegation: scope=payments:send max_amount=50000000 USD micros lifetime=86400s")
# 3. Verifier state: the reference store is the claim store, receipt log, # checkpoint and authoritative clock. The journal records key roles and # the root's status key. store = Store(START, 30, LOG_ID, verifier_priv) journal = new_journal_store() for role, pub in (("issuer", root_pub), ("delegation", agent_pub), ("verifier", verifier_pub)): record_security_key_role_v2(ctx, journal, role, pub) configure_status_key_epoch_v2(ctx, journal, root_id, 1, status_pub)
# 4. The root's status publisher signs a genesis revocation list (no # revocations) under the separate status key. publisher = new_v2_status_publisher_with_key(ctx, journal, root_pub, status_priv, 3600) genesis = publisher.genesis(ctx, START) status_wire = encode_revocation_list_v2(genesis.list) print(f"status: genesis list signed by the status key (sequence {genesis.state.sequence}, {len(genesis.state.revoked)} revoked)")
# 5. The verifier issues a challenge. The helper persists the record # before it returns the challenge. issuance = TestOnlyChallengeIssuanceStore() challenge = V2ChallengeIssuer(clock=store, store=issuance).issue_challenge_v2(ctx, V2ChallengeIssueRequest( verifier_namespace=NAMESPACE, replay_epoch=EPOCH, verifier_id=verifier_id, lifetime_seconds=120, expected_agent_id=agent_id, expected_agent_public_key=agent_pub, )) print(f"challenge: issued and persisted, expires in {challenge.expires_at - challenge.issued_at}s")
# 6. The agent signs a proof bundle over the challenge. store.set_time(START + 2) bundle = sign_proof_bundle_v2(ProofBundleV2( version=2, verifier_id=verifier_id, agent_id=agent_id, agent_pub_key=agent_pub, delegations=[cert], challenge=challenge.value, challenge_at=challenge.issued_at, delegation_digest=b"", challenge_sig=None, # computed by sign_proof_bundle_v2 ), agent_priv) bundle_wire = encode_proof_bundle_v2(bundle) print(f"proof: agent signed the presentation ({len(bundle.delegations)} delegation)")
# 7. Verify. The verifier loads the issuance record for the presented # challenge, then runs the full v2 decision path. def trust(_ctx, chain): # Trust is pinned to the complete root public key, never a key ID. if chain[-1].issuer_id == root_id: return V2TrustResolution(outcome="trusted", root_key=root_pub) return V2TrustResolution(outcome="untrusted")
def status_evidence(_ctx, _req): return V2StatusEvidenceBatch(objects=[V2StatusEvidenceObject(object_type=3, wire=status_wire)])
def verify(): expected = load_expected_challenge_v2(ctx, issuance, NAMESPACE, EPOCH, bundle.challenge) req = V2VerifyRequest( bundle=bundle_wire, expected=expected, context_policy=new_v2_context_policy("example.quickstart/v1", False, [], None), required_scope="payments:send", verifier_namespace=NAMESPACE, replay_epoch=EPOCH, verifier_id=verifier_id, now=store.now(), max_challenge_age_seconds=300, future_skew_seconds=5, context=ConstraintContextV2(has_amount=True, requested_amount_micros=12_500_000, requested_currency="USD"), tzdb_version=TZDB_VERSION_V2, status_keys={root_id: V2StatusKeyConfig(epoch=1, key=status_pub)}, status_policy=RevocationStatusPolicyV2(max_list_lifetime_seconds=3600, max_status_age_seconds=3600, clock_skew_seconds=5), ) cb = V2VerifyCallbacks(claim_store=store, trust=trust, status_evidence=status_evidence, status_journal=journal) return verify_proof_bundle_v2(ctx, req, cb)
outcome = verify() if outcome.stage != V2_STAGE_COMMITTED: raise SystemExit(f"verify stopped at {outcome.stage}: {outcome.error}") print("verify: stage=committed (not actionable until released)")
# 8. Publish the signed receipt to the log; the checkpoint acknowledges it. receipt_wire = store.publish_v2_receipt(ctx, outcome.committed.claim_id(), outcome.committed.receipt_body()) receipt = decode_verification_receipt_v2(receipt_wire) print(f"receipt: published at log sequence {receipt.sequence}") ack = store.get_v2_acknowledgement(ctx, LOG_ID, receipt.sequence) print(f"checkpoint: acknowledged sequence {ack.sequence}")
# 9. Release. Only a released decision is actionable. result = release_v2_decision(ctx, outcome.committed, receipt_wire, V2ReleaseConfig( verifier_public_key=verifier_pub, log_id=LOG_ID, claim_store=store, checkpoint=store, )) if result.status != V2_RELEASE_RELEASED: raise SystemExit(f"release {result.status}: {result.reason}") decision = result.decision print(f"release: status={result.status} decision={decision.decision()} reason={decision.reason()}") print(f"granted scope: {','.join(decision.granted_scope())}")
# 10. Gate the side effect on allowed() at the receiver's authoritative time. print(f"allowed now: {b(decision.allowed(ctx, store))}")
# 11. Presenting the same proof again is a replay and is never evaluated. store.set_time(START + 3) replay = verify() print(f"replay: stage={replay.stage} disposition={replay.disposition}")
# 12. The released allow ends at the challenge expiry (an exclusive deadline). store.set_time(challenge.expires_at) print(f"allowed at challenge expiry: {b(decision.allowed(ctx, store))}")
if __name__ == "__main__": main()Source: examples/v2/python/quickstart at commit 5ca7585c2c1d, SHA-256 checked at build time.
Before (v1):
cargo add ratify-protocol@=1.0.0-alpha.21v1 calls: generate_challenge, sign_challenge, verify_bundle(&bundle, &options).
Full v1 program: Rust SDK, three minutes end to end.
After (v2):
v2 calls (module ratify_protocol::v2): issue_challenge_v2, verify_proof_bundle_v2,
release_v2_decision, then released.allowed(&ctx, &clock) before the side effect. Status
comes from V2StatusPublisher.
//! Ratify Protocol v2 quickstart: delegate, present, verify, publish, release.//!//! DEVELOPMENT ONLY. This program uses the in-memory reference stores from//! `ratify_protocol::v2::reference` (claim store, receipt log, checkpoint,//! journal and challenge issuance store). They exist for tests and examples.//! A production verifier supplies durable Part B stores and an independent//! checkpoint (SPEC-v2 §7).//!//! Run from examples/v2/rust: cargo run --bin quickstart
use std::collections::BTreeMap;use std::error::Error;use std::sync::Arc;
use ratify_protocol::v2::reference::{JournalStore, Store, TestOnlyChallengeIssuanceStore};use ratify_protocol::v2::*;use ratify_protocol::{generate_hybrid_keypair, HybridPublicKey, HybridSignature};
const START: i64 = 1_800_000_000; // fixed clock so the output is reproducibleconst NAMESPACE: &str = "quickstart";const EPOCH: i64 = 1;const LOG_ID: &str = "00000000000000000000000000000001";
fn unsigned() -> HybridSignature { HybridSignature { ed25519: Vec::new(), ml_dsa_65: Vec::new(), }}
fn main() { if let Err(e) = run() { eprintln!("error: {e}"); std::process::exit(1); }}
fn run() -> Result<(), Box<dyn Error>> { let ctx = V2Context::background(); println!("Ratify Protocol v2 quickstart"); println!("development only: in-memory reference stores");
// 1. Keys. Every party holds a hybrid Ed25519 + ML-DSA-65 key. The status // key is separate from the root key that issues delegations. let (root_pub, root_priv) = generate_hybrid_keypair(); let (agent_pub, agent_priv) = generate_hybrid_keypair(); let (status_pub, status_priv) = generate_hybrid_keypair(); let (verifier_pub, verifier_priv) = generate_hybrid_keypair(); let root_id = key_id_v2(&root_pub)?; let agent_id = key_id_v2(&agent_pub)?; let verifier_id = key_id_v2(&verifier_pub)?; println!( "keys: root, agent, status and verifier generated (key IDs are {} hex characters)", root_id.len() );
// 2. The root delegates payments:send to the agent, capped at 50.00 USD // per action (amounts are integer micro-units in v2). let cert = sign_delegation_cert_v2( &DelegationCertV2 { version: 2, cert_id: "quickstart-cert-1".into(), issuer_id: root_id.clone(), issuer_pub_key: root_pub.clone(), subject_id: agent_id.clone(), subject_pub_key: agent_pub.clone(), scope: vec!["payments:send".into()], constraints: vec![ConstraintV2 { kind: CONSTRAINT_MAX_AMOUNT.into(), currency: "USD".into(), max_amount_micros: 50_000_000, ..Default::default() }], issued_at: START, expires_at: START + 86400, signature: unsigned(), }, &root_priv, )?; println!("delegation: scope=payments:send max_amount=50000000 USD micros lifetime=86400s");
// 3. Verifier state: the reference store is the claim store, receipt log, // checkpoint and authoritative clock. The journal records key roles and // the root's status key. let store = Arc::new(Store::new(START, 30, LOG_ID, &verifier_priv)?); let journal = Arc::new(JournalStore::new()?); for (role, public) in [ ("issuer", &root_pub), ("delegation", &agent_pub), ("verifier", &verifier_pub), ] { record_security_key_role_v2(&ctx, journal.as_ref(), role, public)?; } configure_status_key_epoch_v2(&ctx, journal.as_ref(), &root_id, 1, &status_pub)?;
// 4. The root's status publisher signs a genesis revocation list (no // revocations) under the separate status key. let publisher = new_v2_status_publisher_with_key(&ctx, journal.as_ref(), &root_pub, &status_priv, 3600)?; let genesis = publisher.genesis(&ctx, START)?; let status_wire = encode_revocation_list_v2(&genesis.list)?; println!( "status: genesis list signed by the status key (sequence {}, {} revoked)", genesis.state.sequence, genesis.state.revoked.len() );
// 5. The verifier issues a challenge. The helper persists the record // before it returns the challenge. let issuance = Arc::new(TestOnlyChallengeIssuanceStore::new()); let issuer = V2ChallengeIssuer { clock: store.clone(), store: issuance.clone(), random: None, }; let challenge = issuer.issue_challenge_v2( &ctx, &V2ChallengeIssueRequest { verifier_namespace: NAMESPACE.into(), replay_epoch: EPOCH, verifier_id: verifier_id.clone(), lifetime_seconds: 120, expected_agent_id: agent_id.clone(), expected_agent_public_key: Some(agent_pub.clone()), ..Default::default() }, )?; println!( "challenge: issued and persisted, expires in {}s", challenge.expires_at - challenge.issued_at );
// 6. The agent signs a proof bundle over the challenge. store.set_time(START + 2); let bundle = sign_proof_bundle_v2( &ProofBundleV2 { version: 2, verifier_id: verifier_id.clone(), agent_id: agent_id.clone(), agent_pub_key: agent_pub.clone(), delegations: vec![cert], delegation_digest: Vec::new(), challenge: challenge.value.clone(), challenge_at: challenge.issued_at, challenge_sig: unsigned(), session_context: None, stream_id: None, stream_seq: None, }, &agent_priv, )?; let bundle_wire = encode_proof_bundle_v2(&bundle)?; println!( "proof: agent signed the presentation ({} delegation)", bundle.delegations.len() );
// 7. Verify. The verifier loads the issuance record for the presented // challenge, then runs the full v2 decision path. let verify = || -> Result<V2VerifyOutcome, Box<dyn Error>> { let expected = load_expected_challenge_v2( &ctx, issuance.as_ref(), NAMESPACE, EPOCH, &bundle.challenge, )?; let policy = V2ContextPolicy::new("example.quickstart/v1", false, &[], &[])?; let req = V2VerifyRequest { bundle: bundle_wire.clone(), expected: Some(expected), context_policy: Some(policy), required_scope: "payments:send".into(), verifier_namespace: NAMESPACE.into(), replay_epoch: EPOCH, verifier_id: verifier_id.clone(), now: store.now(), max_challenge_age_seconds: 300, future_skew_seconds: 5, context: ConstraintContextV2 { has_amount: true, requested_amount_micros: 12_500_000, requested_currency: "USD".into(), ..Default::default() }, tzdb_version: TZDB_VERSION_V2.into(), status_keys: BTreeMap::from([( root_id.clone(), V2StatusKeyConfig { epoch: 1, key: status_pub.clone(), }, )]), status_policy: RevocationStatusPolicyV2 { max_list_lifetime_seconds: 3600, max_status_age_seconds: 3600, clock_skew_seconds: 5, }, constraint_evaluators: None, }; let (trusted_id, trusted_key) = (root_id.clone(), root_pub.clone()); let evidence = status_wire.clone(); let cb = V2VerifyCallbacks { claim_store: Some(store.clone()), // Trust is pinned to the complete root public key, never a key ID. trust: Some(Arc::new( move |_ctx: &V2Context, chain: &[DelegationCertV2]| { Ok(match chain.last() { Some(last) if last.issuer_id == trusted_id => V2TrustResolution { outcome: V2TrustOutcome::Trusted, root_key: trusted_key.clone(), }, _ => V2TrustResolution { outcome: V2TrustOutcome::Untrusted, root_key: HybridPublicKey { ed25519: Vec::new(), ml_dsa_65: Vec::new(), }, }, }) }, )), status_evidence: Some(Arc::new( move |_ctx: &V2Context, _req: &V2StatusEvidenceRequest| { Ok(V2StatusEvidenceBatch { objects: vec![V2StatusEvidenceObject { object_type: 3, wire: evidence.clone(), }], }) }, )), status_journal: Some(journal.clone()), ..Default::default() }; Ok(verify_proof_bundle_v2(&ctx, &req, &cb)) }; let outcome = verify()?; let committed = match (outcome.stage, outcome.committed) { (V2VerifyStage::Committed, Some(c)) => c, (stage, _) => { return Err(format!("verify stopped at {}: {:?}", stage.as_str(), outcome.error).into()) } }; println!("verify: stage=committed (not actionable until released)");
// 8. Publish the signed receipt to the log; the checkpoint acknowledges it. let receipt_wire = store.publish_v2_receipt(&ctx, &committed.claim_id(), &committed.receipt_body())?; let receipt = decode_verification_receipt_v2(&receipt_wire)?; println!("receipt: published at log sequence {}", receipt.sequence); let ack = store.get_v2_acknowledgement(&ctx, LOG_ID, receipt.sequence)?; println!("checkpoint: acknowledged sequence {}", ack.sequence);
// 9. Release. Only a released decision is actionable. let result = release_v2_decision( &ctx, &committed, Some(&receipt_wire), V2ReleaseConfig { verifier_public_key: &verifier_pub, log_id: LOG_ID, claim_store: store.as_ref(), checkpoint: store.as_ref(), }, ); let status = result.status; let reason = result.reason.clone(); let decision = result .into_decision() .ok_or_else(|| format!("release {}: {}", status.as_str(), reason))?; println!( "release: status={} decision={} reason={}", status.as_str(), decision.decision(), decision.reason() ); println!("granted scope: {}", decision.granted_scope().join(","));
// 10. Gate the side effect on allowed at the receiver's authoritative time. println!("allowed now: {}", decision.allowed(&ctx, store.as_ref()));
// 11. Presenting the same proof again is a replay and is never evaluated. store.set_time(START + 3); let replay = verify()?; println!( "replay: stage={} disposition={}", replay.stage.as_str(), replay.disposition.map(|d| d.as_str()).unwrap_or("") );
// 12. The released allow ends at the challenge expiry (an exclusive deadline). store.set_time(challenge.expires_at); println!( "allowed at challenge expiry: {}", decision.allowed(&ctx, store.as_ref()) ); Ok(())}Source: examples/v2/rust/quickstart at commit 5ca7585c2c1d, SHA-256 checked at build time.
Before (v1): ratify_challenge_generate, ratify_verify_bundle, then
ratify_verify_result_is_valid. Full v1 program: C SDK guide.
After (v2):
# Use the ratify-c 2.0.0-beta.2 release archive, or build it from the release tag# (Rust toolchain required). Include ratify.h and call the ratify_v2_* functions.git clone --branch v2.0.0-beta.2 https://github.com/identities-ai/ratify-protocolcd ratify-protocol/sdks/ccargo build --releasev2 calls: ratify_v2_issue_challenge, ratify_v2_verify_proof_bundle (committed outcome),
ratify_v2_release_decision, then ratify_v2_released_allowed before the side effect. Stores
and providers are C callbacks; check ratify_v2_abi_version at startup.
/* * Ratify Protocol v2 quickstart: delegate, present, verify, publish, release. * * DEVELOPMENT ONLY. This program uses the in-memory reference stores * (ratify_v2_ref_*: claim store, receipt log, checkpoint, journal and * challenge issuance store). They exist for tests and examples and are * compiled only into a test-reference build. A production verifier supplies * durable Part B stores and an independent checkpoint through the callback * structs (SPEC-v2 §7). * * Build and run: examples/v2/c/test.sh */#include "example_util.h"
#define START 1800000000LL /* fixed clock so the output is reproducible */#define NAMESPACE "quickstart"#define EPOCH 1#define LOG_ID "00000000000000000000000000000001"#define TZDB_VERSION "2025c" /* the pinned tzdata release (SPEC-v2 §5.2) */
/* Trust is pinned to the complete root public key, never a key ID. */typedef struct { const char *root_id; const RatifyV2PublicKey *root_key;} trust_config;
static int32_t resolve_trust(void *user, const RatifyV2CertView *chain, uintptr_t chain_len, int32_t *outcome, RatifyV2PublicKey *root_key) { const trust_config *t = user; if (strcmp(chain[chain_len - 1].issuer_id, t->root_id) == 0) { *outcome = RatifyV2TrustTrusted; *root_key = *t->root_key; } else { *outcome = RatifyV2TrustUntrusted; } return 0;}
/* The status provider returns signed objects only. */static int32_t fetch_status(void *user, const RatifyV2StatusRequest *request, RatifyV2StatusBatch *out) { (void)request; out->objects = user; out->count = 1; return 0;}
/* Everything one verification needs. */typedef struct { RatifyV2RefStore *store; const RatifyV2IssuanceStoreCallbacks *issuance; const RatifyV2VerifyCallbacks *callbacks; const char *root_id; const char *verifier_id; const char *status_json; RatifyV2Slice bundle; const uint8_t *challenge;} verifier_config;
/* Loads the issuance record for the presented challenge, then runs the full * v2 decision path at the store's current time. */static RatifyV2VerifyOutcome verify(const verifier_config *v, RatifyV2Committed **committed) { RatifyV2Buffer expected_buf; CHECK(ratify_v2_load_expected_challenge(v->issuance, NAMESPACE, EPOCH, v->challenge, 32, &expected_buf)); char *expected = take_string(expected_buf); int64_t now; CHECK(ratify_v2_ref_store_time(v->store, &now)); char *request = format( "{\"required_scope\":\"payments:send\",\"verifier_namespace\":\"%s\",\"replay_epoch\":%d,\"verifier_id\":\"%s\",\"now\":%lld," "\"max_challenge_age_seconds\":300,\"future_skew_seconds\":5,\"tzdb_version\":\"%s\"," "\"status_keys\":{\"%s\":{\"epoch\":1,\"public_key\":%s}}," "\"status_policy\":{\"max_list_lifetime_seconds\":3600,\"max_status_age_seconds\":3600,\"clock_skew_seconds\":5}," "\"expected_challenge\":%s," "\"context_policy\":{\"profile\":\"example.quickstart/v1\",\"require_bound\":false,\"required_fields\":[]," "\"expected_session_context_b64\":null}," "\"context\":{\"has_amount\":true,\"requested_amount_micros\":12500000,\"requested_currency\":\"USD\"}}", NAMESPACE, EPOCH, v->verifier_id, (long long)now, TZDB_VERSION, v->root_id, v->status_json, expected); RatifyV2VerifyOutcome outcome; *committed = NULL; CHECK(ratify_v2_verify_proof_bundle(v->bundle.ptr, v->bundle.len, (const uint8_t *)request, strlen(request), NULL, v->callbacks, &outcome, NULL, committed)); free(expected); free(request); return outcome;}
int main(void) { printf("Ratify Protocol v2 quickstart\n"); printf("development only: in-memory reference stores\n");
/* 1. Keys. Every party holds a hybrid Ed25519 + ML-DSA-65 key. The status * key is separate from the root key that issues delegations. */ RatifyV2KeyPair *root, *agent, *status, *verifier; CHECK(ratify_v2_keypair_generate(&root, NULL, NULL)); CHECK(ratify_v2_keypair_generate(&agent, NULL, NULL)); CHECK(ratify_v2_keypair_generate(&status, NULL, NULL)); CHECK(ratify_v2_keypair_generate(&verifier, NULL, NULL)); static RatifyV2PublicKey root_pub, agent_pub, status_pub, verifier_pub; CHECK(ratify_v2_keypair_public_key(root, &root_pub)); CHECK(ratify_v2_keypair_public_key(agent, &agent_pub)); CHECK(ratify_v2_keypair_public_key(status, &status_pub)); CHECK(ratify_v2_keypair_public_key(verifier, &verifier_pub)); char root_id[RATIFY_V2_KEY_ID_BUF_LEN], agent_id[RATIFY_V2_KEY_ID_BUF_LEN], verifier_id[RATIFY_V2_KEY_ID_BUF_LEN]; CHECK(ratify_v2_keypair_key_id(root, root_id, sizeof root_id)); CHECK(ratify_v2_keypair_key_id(agent, agent_id, sizeof agent_id)); CHECK(ratify_v2_keypair_key_id(verifier, verifier_id, sizeof verifier_id)); char *root_json = key_json(&root_pub), *agent_json = key_json(&agent_pub), *status_json = key_json(&status_pub); printf("keys: root, agent, status and verifier generated (key IDs are %zu hex characters)\n", strlen(root_id));
/* 2. The root delegates payments:send to the agent, capped at 50.00 USD * per action (amounts are integer micro-units in v2). */ char *cert_in = format( "{\"cert_id\":\"quickstart-cert-1\",\"constraints\":[{\"currency\":\"USD\",\"max_amount_micros\":50000000," "\"type\":\"max_amount\"}],\"expires_at\":%lld,\"issued_at\":%lld,\"issuer_id\":\"%s\",\"issuer_pub_key\":%s," "\"scope\":[\"payments:send\"],\"subject_id\":\"%s\",\"subject_pub_key\":%s,\"version\":2}", START + 86400, START, root_id, root_json, agent_id, agent_json); RatifyV2Buffer cert_buf; CHECK(ratify_v2_sign_delegation_certificate((const uint8_t *)cert_in, strlen(cert_in), root, NULL, &cert_buf)); char *cert = take_string(cert_buf); printf("delegation: scope=payments:send max_amount=50000000 USD micros lifetime=86400s\n");
/* 3. Verifier state: the reference store is the claim store, receipt log, * checkpoint and authoritative clock. The journal records key roles and * the root's status key. */ RatifyV2RefStore *store; CHECK(ratify_v2_ref_store_new(START, 30, LOG_ID, verifier, &store)); RatifyV2ClaimStoreCallbacks claim_cb; RatifyV2ReleaseStoreCallbacks release_cb; RatifyV2CheckpointCallbacks checkpoint_cb; RatifyV2ClockCallbacks clock_cb; CHECK(ratify_v2_ref_store_callbacks(store, 0, &claim_cb, NULL, &release_cb, &checkpoint_cb, &clock_cb)); RatifyV2RefJournal *journal_store; RatifyV2JournalStoreCallbacks journal; CHECK(ratify_v2_ref_journal_new(&journal_store)); CHECK(ratify_v2_ref_journal_callbacks(journal_store, &journal, NULL, NULL)); CHECK(ratify_v2_journal_record_key_role(&journal, "issuer", &root_pub)); CHECK(ratify_v2_journal_record_key_role(&journal, "delegation", &agent_pub)); CHECK(ratify_v2_journal_record_key_role(&journal, "verifier", &verifier_pub)); CHECK(ratify_v2_journal_configure_status_key(&journal, root_id, 1, &status_pub));
/* 4. The root's status publisher signs a genesis revocation list (no * revocations) under the separate status key. The caller persists the * returned state before publishing the list. */ RatifyV2Buffer list_buf, push_buf, state_buf; CHECK(ratify_v2_status_publish(RatifyV2PublishGenesis, &journal, &root_pub, status, NULL, 3600, NULL, 0, NULL, 0, START, &list_buf, &push_buf, &state_buf)); ratify_v2_buffer_free(push_buf); char *state = take_string(state_buf); RatifyV2StatusObject status_object = {RatifyV2KindRevocationList, {list_buf.ptr, list_buf.len}}; printf("status: genesis list signed by the status key (sequence %lld, %d revoked)\n", (long long)json_int(state, "sequence"), strstr(state, "\"revoked\":[]") ? 0 : 1);
/* 5. The verifier issues a challenge. The helper persists the record * before it returns the challenge. */ RatifyV2RefIssuance *issuance_store; RatifyV2IssuanceStoreCallbacks issuance; CHECK(ratify_v2_ref_issuance_new(&issuance_store)); CHECK(ratify_v2_ref_issuance_control(issuance_store, -1, &issuance, NULL)); char *issue_req = format( "{\"verifier_namespace\":\"%s\",\"replay_epoch\":%d,\"verifier_id\":\"%s\",\"lifetime_seconds\":120," "\"expected_agent_id\":\"%s\",\"expected_agent_public_key\":%s}", NAMESPACE, EPOCH, verifier_id, agent_id, agent_json); RatifyV2Buffer challenge_buf; CHECK(ratify_v2_issue_challenge((const uint8_t *)issue_req, strlen(issue_req), &clock_cb, &issuance, NULL, &challenge_buf)); char *challenge = take_string(challenge_buf); char challenge_b64[64]; json_str(challenge, "value_b64", challenge_b64, sizeof challenge_b64); int64_t issued_at = json_int(challenge, "issued_at"), expires_at = json_int(challenge, "expires_at"); printf("challenge: issued and persisted, expires in %llds\n", (long long)(expires_at - issued_at));
/* 6. The agent signs a proof bundle over the challenge. */ CHECK(ratify_v2_ref_store_control(store, 1, START + 2)); char *bundle_in = format( "{\"agent_id\":\"%s\",\"agent_pub_key\":%s,\"challenge\":\"%s\",\"challenge_at\":%lld,\"delegations\":[%s]," "\"session_context\":null,\"stream_id\":null,\"stream_seq\":null,\"verifier_id\":\"%s\",\"version\":2}", agent_id, agent_json, challenge_b64, (long long)issued_at, cert, verifier_id); RatifyV2Buffer bundle; CHECK(ratify_v2_sign_proof_bundle((const uint8_t *)bundle_in, strlen(bundle_in), agent, NULL, &bundle)); printf("proof: agent signed the presentation (1 delegation)\n");
/* 7. Verify. */ uint8_t challenge_bytes[32]; b64_decode(challenge_b64, challenge_bytes, sizeof challenge_bytes); trust_config trust_user = {root_id, &root_pub}; RatifyV2TrustCallbacks trust = {&trust_user, resolve_trust}; RatifyV2StatusEvidenceCallbacks evidence = {&status_object, fetch_status}; RatifyV2VerifyCallbacks callbacks = {&claim_cb, &trust, &evidence, &journal, NULL, NULL, NULL}; verifier_config v = {store, &issuance, &callbacks, root_id, verifier_id, status_json, {bundle.ptr, bundle.len}, challenge_bytes}; RatifyV2Committed *committed; RatifyV2VerifyOutcome outcome = verify(&v, &committed); if (outcome.stage != RatifyV2StageCommitted) fail("verify did not commit"); printf("verify: stage=committed (not actionable until released)\n");
/* 8. Publish the signed receipt to the log; the checkpoint acknowledges it. */ char *claim_id; RatifyV2Buffer body, receipt_buf; const char *refusal = NULL; CHECK(ratify_v2_committed_claim_id(committed, &claim_id)); CHECK(ratify_v2_committed_receipt_body(committed, &body)); CHECK(ratify_v2_ref_store_publish(store, claim_id, body.ptr, body.len, &receipt_buf, &refusal)); ratify_v2_buffer_free(body); char *receipt = format("%.*s", (int)receipt_buf.len, (const char *)receipt_buf.ptr); int64_t sequence = json_int(receipt, "sequence"); printf("receipt: published at log sequence %lld\n", (long long)sequence); RatifyV2Acknowledgement ack; CHECK(checkpoint_cb.get(checkpoint_cb.user, LOG_ID, sequence, &ack)); printf("checkpoint: acknowledged sequence %lld\n", (long long)ack.sequence);
/* 9. Release. Only a released decision is actionable. */ int32_t release_status; char *release_reason = NULL; RatifyV2Released *decision = NULL; RatifyV2Slice receipt_wire = {receipt_buf.ptr, receipt_buf.len}; CHECK(ratify_v2_release_decision(committed, receipt_wire, &verifier_pub, LOG_ID, &release_cb, &checkpoint_cb, &release_status, &release_reason, &decision)); if (release_status != RatifyV2ReleaseReleased) fail("release did not release"); char *verdict, *reason; CHECK(ratify_v2_released_string(decision, RatifyV2ReleasedDecision, &verdict)); CHECK(ratify_v2_released_string(decision, RatifyV2ReleasedReason, &reason)); printf("release: status=%s decision=%s reason=%s\n", ratify_v2_release_status_str(release_status), verdict, reason); RatifyV2Buffer scope_buf; CHECK(ratify_v2_released_granted_scope(decision, &scope_buf)); char *scope = take_string(scope_buf); /* JSON array of one scope: ["payments:send"] */ printf("granted scope: %.*s\n", (int)(strlen(scope) - 4), scope + 2);
/* 10. Gate the side effect on Allowed at the receiver's authoritative time. */ printf("allowed now: %s\n", ratify_v2_released_allowed(decision, &clock_cb) ? "true" : "false");
/* 11. Presenting the same proof again is a replay and is never evaluated. */ CHECK(ratify_v2_ref_store_control(store, 1, START + 3)); RatifyV2Committed *replay_committed; RatifyV2VerifyOutcome replay = verify(&v, &replay_committed); printf("replay: stage=%s disposition=%s\n", stage_name(replay.stage), disposition_name(replay.disposition));
/* 12. The released allow ends at the challenge expiry (an exclusive deadline). */ CHECK(ratify_v2_ref_store_control(store, 1, expires_at)); printf("allowed at challenge expiry: %s\n", ratify_v2_released_allowed(decision, &clock_cb) ? "true" : "false");
ratify_v2_committed_free(replay_committed); free(scope); ratify_v2_string_free(reason); ratify_v2_string_free(verdict); ratify_v2_string_free(release_reason); ratify_v2_released_free(decision); free(receipt); ratify_v2_buffer_free(receipt_buf); ratify_v2_string_free(claim_id); ratify_v2_committed_free(committed); ratify_v2_buffer_free(bundle); free(bundle_in); free(challenge); free(issue_req); ratify_v2_ref_issuance_free(issuance_store); free(state); ratify_v2_buffer_free(list_buf); ratify_v2_ref_journal_free(journal_store); ratify_v2_ref_store_free(store); free(cert); free(cert_in); free(root_json); free(agent_json); free(status_json); ratify_v2_keypair_free(root); ratify_v2_keypair_free(agent); ratify_v2_keypair_free(status); ratify_v2_keypair_free(verifier); return 0;}Source: examples/v2/c/quickstart at commit 5ca7585c2c1d, SHA-256 checked at build time.
Concept map
Section titled “Concept map”| v1 | v2 |
|---|---|
HumanRoot, Anchor, AgentIdentity |
Complete hybrid keys and key_id_v2 in caller-authenticated trust configuration. No enrollment object |
AnchorResolver |
Application code after release, for metadata only. It never supplies trust |
PolicyProvider, PolicyVerdict |
Application policy after ReleaseV2Decision; it may only narrow the result |
AuditProvider |
Mandatory signed verification receipts in an acknowledged log |
RevocationProvider, IsRevoked |
Signed status evidence and the anchored SecurityJournalV2. No ForceRevocationCheck switch: an allow always needs current status |
ConstraintEvaluator |
The closed v2 registry plus registered evaluator profiles (com.ratifyprotocol.max_count/v1, com.ratifyprotocol.allowed_values/v1, or your own) |
max_amount (float) |
max_amount_micros (integer) with currency |
custom: required scope |
One exact custom: scope listed by every certificate in the chain |
| Self-issued challenges | Archival verification only (freshness_unverified, never actionable) |
VerifyResult statuses |
Error classes, plus the terminal decision, reason, and assessments |
SessionToken, mutual presentation, HTTP and registry bindings, geo and speed |
v1-only until 2.1 |
