caelum0x f5b6c6a75e feat(near-anchor): add scheduled auto-anchoring (near-anchor schedule)
Audit-log's NEAR Testnet anchoring was manual-only (an operator running
`near-anchor commit` by hand). Add a `schedule` subcommand that repeats
the decide-then-anchor flow on a fixed interval
(RATION_NEAR_ANCHOR_INTERVAL, default 5m) until SIGINT/SIGTERM:

- Batching is structural, not buffered: anchoring the current hash-chain
  tip already cryptographically commits every record appended since the
  last anchor, so one tick = one anchor tx no matter how many new
  records landed.
- Idempotent / skips when nothing new: decideAnchor compares the local
  tip's sequence against the contract's own get_latest_anchor() (a free
  view call) before ever signing a transaction, so a tick with no new
  records costs nothing and two concurrent anchorers can't double-commit
  (the contract's own sequence guard is the backstop either way).
- Survives restarts with zero checkpoint state: every tick re-reads the
  real local file and the real on-chain state fresh, so a crash
  mid-tick is safe — the next tick just re-decides from the chain
  itself.

Verified for real against NEAR Testnet (dedicated demo account
ration-demo-23bd92e5.testnet, never the primary submission account):
found a real pre-existing backlog of 3 un-anchored local records
(sequence 2 on-chain vs. sequence 5 local), ran the scheduler, and
confirmed exactly one batched anchor tx closed the gap
(tx HP5VcN88FbDzTw3VBD7fgaftgzhoM5f8fc6Yibx5w9qM, sequence 6), with a
second tick correctly skipping. A follow-up run (tx
6w6FUTWTSKGhnmJWqzYGuNBrZrkFW6Ux4g32wqEP9SDq, sequence 8) re-confirmed
the same batch-then-skip behavior after fixing a race the first attempt
surfaced (back-to-back ticks faster than RPC view-propagation lag can
see a stale on-chain state — safe, since no corruption/double-anchor
occurred, but real and worth a comment; irrelevant at any real
multi-minute interval). All on-chain state independently re-verified via
raw JSON-RPC against rpc.testnet.fastnear.com outside the Go tooling.

On branch feat/auto-anchoring — not merged to main, since the NEAR
hackathon entry is submitted from main and must not change before then.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-10 17:13:37 +03:00

377 lines
14 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
// services/audit-log/internal/nearanchor for the signing/RPC logic this
// binary drives.
//
// 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 schedule long-running: repeat `commit`'s
// decide-then-anchor logic on a fixed
// interval (RATION_NEAR_ANCHOR_INTERVAL,
// default 5m) forever, skipping ticks
// where nothing new has been appended
// since the last on-chain anchor — see
// internal/nearanchor/scheduler.go
// 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"
"os/signal"
"syscall"
"time"
"github.com/caelum0x/ration/services/audit-log/internal/nearanchor"
"github.com/caelum0x/ration/services/audit-log/internal/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 "schedule":
return cmdSchedule(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
schedule long-running: repeat commit's decide-then-anchor
logic every RATION_NEAR_ANCHOR_INTERVAL (default 5m)
until SIGINT/SIGTERM, skipping ticks where nothing
new has been appended since the last anchor
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
}
// cmdSchedule runs the auto-anchoring loop (internal/nearanchor's
// RunScheduler) until the process receives SIGINT or SIGTERM, at which
// point signal.NotifyContext cancels ctx and RunScheduler returns
// cleanly after finishing (not aborting mid-flight) whatever tick is
// currently in progress. This is the real fix for the "anchoring is
// manual" gap: instead of an operator remembering to run `near-anchor
// commit` by hand, this runs unattended, batching however many new
// audit-log records have landed since the last tick into exactly one
// anchor transaction, and doing nothing (not even a failed on-chain
// call) on a tick where nothing changed.
func cmdSchedule(ctx context.Context) int {
cfg, err := nearanchor.LoadForCommit()
if err != nil {
fmt.Fprintf(os.Stderr, "near-anchor schedule: %v\n", err)
return 1
}
ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)
defer stop()
interval := nearanchor.ScheduleInterval()
rpc := nearanchor.NewRPCClient(cfg.RPCURL)
if err := nearanchor.RunScheduler(ctx, cfg, rpc, interval, os.Stdout); err != nil {
fmt.Fprintf(os.Stderr, "near-anchor schedule: %v\n", err)
return 1
}
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
}