caelum0x 07136e7b73 feat(near-hackathon): fold Ration's audit-anchor work into this repo as ONE combined NEAR submission
Owner directive (2026-11-11): submit a single project to the NEAR
Hackathon instead of two separate entries from the same person. Vendors
Ration's NEAR audit-anchor work (github.com/caelum0x/ration, commit
cff0ed3 + follow-ups) into ration-anchor/ as a first-class component:

- contracts-near/audit_anchor (NEAR Rust contract, 5/5 cargo tests
  green, target/ deleted)
- signer/ — a new, self-contained Go module (no dependency on Ration's
  other services or go.work) with the hand-rolled NEAR transaction
  signer + JSON-RPC client (cross-checked byte-for-byte against
  near-api-js) and the hash-chained audit ledger it anchors; 15/15 Go
  tests green (go test ./... -race)
- docs/ and media/ — Ration's original pitch deck, demo recordings, and
  submission checklist

Re-verified live via raw NEAR Testnet JSON-RPC this pass:
ration-anchor-286ca315f1.testnet still deployed and queryable, the
deliberate replay-rejection transaction still fails with nearcore's own
"sequence must strictly advance" panic — no redeploy needed.

Provenance notes added throughout (package doc comments, lib.rs header,
README) crediting the origin repo. README.md and HACKATHON.md rewritten
to tell one story: Cred402's SpendGuard enforces the protocol-level
spending limit, the vendored Audit Anchor proves the tamper-evident
spend history, both independently verifiable on NEAR Testnet. No mainnet
claims anywhere (see prior overclaim fix 524f2dd). cred402's own build
(npm run typecheck) and existing tests are untouched.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 15:32:24 +03:00

338 lines
12 KiB
Go

// Command near-anchor anchors Ration's audit-log hash chain tip to NEAR
// Testnet, so the chain is independently, publicly, tamper-evidently
// verifiable by anyone — not just by whoever can query Ration's own
// database. See ../../../contracts-near/audit_anchor for the on-chain
// side and ../../nearanchor for the signing/RPC logic this binary
// drives.
//
// Provenance: this command originates from Ration
// (github.com/caelum0x/ration, commit cff0ed3). Vendored here, with
// import paths adjusted only, as Ration audit anchor, now part of
// Cred402 — see ../../../README.md.
//
// This is a standalone operator/demo tool (same "tools"-profile spirit
// as services/cli and services/tui — not a long-running service, no
// docker-compose entry needed) with five subcommands:
//
// near-anchor create-account generate a key pair and create a
// fresh NEAR Testnet account via the
// public faucet (no owner credential)
// near-anchor deploy <wasm-path> deploy contracts-near/audit_anchor's
// wasm to the signer account and
// initialize it (one transaction)
// near-anchor commit read the real local audit-log chain
// tip and anchor it on-chain
// near-anchor verify compare the real local chain tip
// against what is currently anchored
// on-chain and report match/mismatch
// near-anchor demo the judge-facing, single-command
// walkthrough: append two real
// audit-log records, read the real
// local chain tip, anchor it on real
// NEAR Testnet, then independently
// verify the on-chain record matches
// — see docs/near-hackathon/HACKATHON.md
//
// Configuration is via the RATION_NEAR_ANCHOR_* environment variables
// (see internal/nearanchor/config.go) — deliberately the same
// env-var-driven convention every other Go binary in this repo uses,
// rather than a pile of CLI flags.
package main
import (
"context"
"encoding/json"
"fmt"
"os"
"time"
"github.com/caelum0x/cred402/ration-anchor/signer/nearanchor"
"github.com/caelum0x/cred402/ration-anchor/signer/store"
)
func main() {
os.Exit(run(os.Args[1:]))
}
func run(args []string) int {
if len(args) == 0 {
printUsage()
return 2
}
ctx := context.Background()
switch args[0] {
case "create-account":
return cmdCreateAccount(ctx)
case "deploy":
return cmdDeploy(ctx, args[1:])
case "commit":
return cmdCommit(ctx)
case "verify":
return cmdVerify(ctx)
case "demo":
return cmdDemo(ctx)
default:
fmt.Fprintf(os.Stderr, "near-anchor: unknown subcommand %q\n\n", args[0])
printUsage()
return 2
}
}
func printUsage() {
fmt.Fprintln(os.Stderr, `near-anchor <subcommand>
Subcommands:
create-account generate a key pair and create a fresh NEAR Testnet
account via the public faucet
deploy <wasm> deploy contracts-near/audit_anchor's wasm to the
signer account and initialize it
commit anchor the real local audit-log chain tip on-chain
verify compare the local chain tip against what is
currently anchored on-chain
demo append two real audit-log records, anchor the real
resulting chain tip on NEAR Testnet, then verify it
Configuration via environment variables — see
services/audit-log/internal/nearanchor/config.go.`)
}
func cmdCreateAccount(ctx context.Context) int {
rpcURL := getenvDefault("RATION_NEAR_ANCHOR_RPC_URL", nearanchor.DefaultRPCURL)
faucetURL := getenvDefault("RATION_NEAR_ANCHOR_FAUCET_URL", nearanchor.DefaultFaucetURL)
accountID := os.Getenv("RATION_NEAR_ANCHOR_NEW_ACCOUNT_ID")
if accountID == "" {
fmt.Fprintln(os.Stderr, "near-anchor create-account: set RATION_NEAR_ANCHOR_NEW_ACCOUNT_ID to the *.testnet account name to create")
return 1
}
secretKey, publicKey, err := nearanchor.GenerateKeyPair()
if err != nil {
fmt.Fprintf(os.Stderr, "near-anchor create-account: %v\n", err)
return 1
}
fmt.Printf("near-anchor: creating %s via %s ...\n", accountID, faucetURL)
if err := nearanchor.CreateTestnetAccount(ctx, faucetURL, accountID, publicKey); err != nil {
fmt.Fprintf(os.Stderr, "near-anchor create-account: %v\n", err)
return 1
}
if err := writeCredentials(accountID, secretKey, publicKey, rpcURL); err != nil {
fmt.Fprintf(os.Stderr, "near-anchor create-account: account created but failed to write credentials file: %v\n", err)
fmt.Printf("account_id=%s\npublic_key=%s\nsecret_key=%s\n", accountID, publicKey, secretKey)
return 1
}
fmt.Printf(`near-anchor: created %s
Set these before running "deploy"/"commit"/"verify":
export RATION_NEAR_ANCHOR_SIGNER_ACCOUNT_ID=%s
export RATION_NEAR_ANCHOR_SIGNER_SECRET_KEY=%s
export RATION_NEAR_ANCHOR_CONTRACT_ID=%s # deploying to self in this flow
(also written to .secrets/near_anchor_credentials.json)
`, accountID, accountID, secretKey, accountID)
return 0
}
func writeCredentials(accountID, secretKey, publicKey, rpcURL string) error {
if err := os.MkdirAll(".secrets", 0o700); err != nil {
return err
}
payload, err := json.MarshalIndent(map[string]string{
"account_id": accountID,
"public_key": publicKey,
"secret_key": secretKey,
"rpc_url": rpcURL,
}, "", " ")
if err != nil {
return err
}
return os.WriteFile(".secrets/near_anchor_credentials.json", payload, 0o600)
}
func cmdDeploy(ctx context.Context, args []string) int {
wasmPath := "contracts-near/audit_anchor/target/near/audit_anchor.wasm"
if len(args) > 0 && args[0] != "" {
wasmPath = args[0]
}
cfg, err := nearanchor.LoadForCommit()
if err != nil {
fmt.Fprintf(os.Stderr, "near-anchor deploy: %v\n", err)
return 1
}
if cfg.ContractID != cfg.SignerAccountID {
fmt.Fprintf(os.Stderr, "near-anchor deploy: this flow deploys to the signer's own account; set RATION_NEAR_ANCHOR_CONTRACT_ID=%s (your signer account)\n", cfg.SignerAccountID)
return 1
}
wasm, err := os.ReadFile(wasmPath)
if err != nil {
fmt.Fprintf(os.Stderr, "near-anchor deploy: read %s: %v\n", wasmPath, err)
return 1
}
rpc := nearanchor.NewRPCClient(cfg.RPCURL)
fmt.Printf("near-anchor: deploying %d bytes of audit_anchor.wasm to %s and calling new() ...\n", len(wasm), cfg.SignerAccountID)
result, err := nearanchor.DeployAndInit(ctx, cfg, rpc, wasm)
if err != nil {
fmt.Fprintf(os.Stderr, "near-anchor deploy: %v\n", err)
return 1
}
fmt.Printf("near-anchor: deployed. tx=%s\n %s\n", result.TransactionHash, result.ExplorerURL)
return 0
}
func cmdCommit(ctx context.Context) int {
cfg, err := nearanchor.LoadForCommit()
if err != nil {
fmt.Fprintf(os.Stderr, "near-anchor commit: %v\n", err)
return 1
}
tip, err := nearanchor.LocalTip(cfg)
if err != nil {
fmt.Fprintf(os.Stderr, "near-anchor commit: %v\n", err)
return 1
}
fmt.Printf("near-anchor: local chain tip is sequence=%d hash=%s tenant=%s\n", tip.Sequence, tip.Hash, tip.TenantID)
rpc := nearanchor.NewRPCClient(cfg.RPCURL)
result, err := nearanchor.CommitAnchor(ctx, cfg, rpc, tip)
if err != nil {
fmt.Fprintf(os.Stderr, "near-anchor commit: %v\n", err)
return 1
}
fmt.Printf("near-anchor: anchored on NEAR Testnet. tx=%s\n %s\n on-chain record: sequence=%d hash=%s anchored_at_block_timestamp=%d\n",
result.TransactionHash, result.ExplorerURL, result.Anchor.Sequence, result.Anchor.ChainTipHash, result.Anchor.AnchoredAtBlockTimestamp)
return 0
}
func cmdVerify(ctx context.Context) int {
cfg, err := nearanchor.LoadForCommit()
if err != nil {
fmt.Fprintf(os.Stderr, "near-anchor verify: %v\n", err)
return 1
}
rpc := nearanchor.NewRPCClient(cfg.RPCURL)
result, err := nearanchor.VerifyAnchor(ctx, cfg, rpc)
if err != nil {
fmt.Fprintf(os.Stderr, "near-anchor verify: %v\n", err)
return 1
}
fmt.Println(result.Detail)
if !result.Match {
return 1
}
return 0
}
// cmdDemo is the single-command, judge-facing walkthrough referenced by
// docs/near-hackathon/HACKATHON.md: it writes two real records to the
// real audit-log append-only file (a late-deposit bridge-funding
// AgentDecision and the LedgerEntry it produced — the exact shape
// services/agent and services/ledger-core already mirror into
// audit-log in production, see services/ledger-core/src/audit_mirror.rs),
// confirms the chain advanced and is intact, anchors the resulting real
// chain tip on NEAR Testnet, and then independently re-reads both sides
// (the local file and the live contract) to prove they agree — the
// same four-step proof docs/near-hackathon/HACKATHON.md promises a
// judge can watch happen, end to end, from one command.
func cmdDemo(ctx context.Context) int {
cfg, err := nearanchor.LoadForCommit()
if err != nil {
fmt.Fprintf(os.Stderr, "near-anchor demo: %v\n", err)
return 1
}
path := cfg.AuditLogPath
if path == "" {
path = cfg.DataDir + "/audit.log"
}
fmt.Printf("[1/4] appending two real records to the audit-log chain at %s ...\n", path)
st, err := store.Open(path)
if err != nil {
fmt.Fprintf(os.Stderr, "near-anchor demo: open audit log: %v\n", err)
return 1
}
defer st.Close()
now := time.Now().Unix()
decision, err := st.Append(store.AppendInput{
SourceService: "agent",
Kind: store.SourceKindAgentDecision,
TenantID: "tenant-near-hackathon-demo",
RefID: fmt.Sprintf("demo-decision-%d", now),
PayloadJSON: `{"action":"RationBridge","amount_minor_units":5000,"reason":"late deposit, headroom available"}`,
OccurredAtUnix: now,
}, now)
if err != nil {
fmt.Fprintf(os.Stderr, "near-anchor demo: append agent decision: %v\n", err)
return 1
}
fmt.Printf(" appended AgentDecision: sequence=%d hash=%s\n", decision.Sequence, decision.Hash)
entry, err := st.Append(store.AppendInput{
SourceService: "ledger-core",
Kind: store.SourceKindLedgerEntry,
TenantID: "tenant-near-hackathon-demo",
RefID: fmt.Sprintf("demo-entry-%d", now),
PayloadJSON: `{"entry_type":"Hold","amount_minor_units":5000,"reference":"bridge:demo-deposit"}`,
OccurredAtUnix: now,
}, now)
if err != nil {
fmt.Fprintf(os.Stderr, "near-anchor demo: append ledger entry: %v\n", err)
return 1
}
fmt.Printf(" appended LedgerEntry: sequence=%d hash=%s\n", entry.Sequence, entry.Hash)
chainCheck := st.VerifyChain()
fmt.Printf("[2/4] local chain integrity: intact=%v records_checked=%d, tip is now sequence=%d hash=%s\n",
chainCheck.Intact, chainCheck.RecordsChecked, entry.Sequence, entry.Hash)
if !chainCheck.Intact {
fmt.Fprintln(os.Stderr, "near-anchor demo: local chain is NOT intact — refusing to anchor a broken chain")
return 1
}
// Close before CommitAnchor/VerifyAnchor re-open the same file
// read-only via LocalTip/store.ReadTip — avoids holding the
// read-write handle open any longer than this command needs it.
_ = st.Close()
rpc := nearanchor.NewRPCClient(cfg.RPCURL)
fmt.Printf("[3/4] anchoring sequence=%d hash=%s on NEAR Testnet (contract %s) ...\n", entry.Sequence, entry.Hash, cfg.ContractID)
commitResult, err := nearanchor.CommitAnchor(ctx, cfg, rpc, entry)
if err != nil {
fmt.Fprintf(os.Stderr, "near-anchor demo: %v\n", err)
return 1
}
fmt.Printf(" committed. tx=%s\n %s\n", commitResult.TransactionHash, commitResult.ExplorerURL)
fmt.Println("[4/4] independently re-reading the local chain tip and the live on-chain anchor to confirm they match ...")
verifyResult, err := nearanchor.VerifyAnchor(ctx, cfg, rpc)
if err != nil {
fmt.Fprintf(os.Stderr, "near-anchor demo: %v\n", err)
return 1
}
fmt.Println(" " + verifyResult.Detail)
if !verifyResult.Match {
return 1
}
fmt.Println("\nnear-anchor demo: PASSED — a real audit-log entry was written, the hash chain advanced, the anchor transaction was confirmed on NEAR Testnet, and the on-chain stored hash matches the real local chain tip.")
return 0
}
func getenvDefault(key, def string) string {
if v := os.Getenv(key); v != "" {
return v
}
return def
}