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

180 lines
7.9 KiB
Go

// Scheduler support for near-anchor: the auto-anchoring loop that
// turns the previously-manual "run `near-anchor commit` by hand
// whenever you remember to" workflow into an unattended, interval-based
// background job (see cmd/near-anchor's `schedule` subcommand).
//
// Design choices worth stating plainly, since they're the actual
// answer to "batch, idempotent, skip-when-nothing-new, survives
// restarts" rather than something bolted on after the fact:
//
// - "Batch" is structural, not a buffer this package manages: because
// every record is hash-chained to the one before it
// (services/audit-log/internal/store), anchoring the *current tip*
// already cryptographically commits to every record appended since
// the last anchor, no matter how many there were. A tick that fires
// after 50 new audit-log records still does exactly one
// commit_anchor call, and that one anchor is just as strong a proof
// for all 50 as 50 separate anchors would have been. There is
// nothing to batch in memory — the chain itself already is the
// batch.
// - Idempotency and "skip when nothing new" are the same check: before
// ever signing a transaction, RunOnce reads the contract's own
// get_latest_anchor() (a free view call) and only calls CommitAnchor
// if the local chain has advanced past what is already anchored.
// This also means two schedulers (or a human running `near-anchor
// commit` by hand) can never double-anchor the same sequence —
// contracts-near/audit_anchor's own `sequence > prev.sequence` guard
// would reject it on-chain even if this check were skipped, so the
// Go-side check is a courtesy that avoids a wasted/failing
// transaction, not the only line of defense.
// - "Survives restarts" needs no local checkpoint file at all: the
// scheduler's only state is "what does the chain say right now?",
// read fresh from the local audit-log file and the live contract on
// every tick (including the very first tick after a restart). A
// crash between deciding to commit and the transaction landing is
// safe too — on restart, the next tick re-asks the chain, and
// either the transaction never made it (so it anchors now) or it
// did (so the on-chain sequence already matches and it skips).
package nearanchor
import (
"context"
"fmt"
"io"
"time"
"github.com/caelum0x/ration/services/audit-log/internal/store"
)
// DefaultScheduleInterval is how often `near-anchor schedule` checks
// for new records when RATION_NEAR_ANCHOR_INTERVAL is unset. Five
// minutes is frequent enough that a judge or operator watching the
// on-chain anchor count doesn't wait long to see it move, without
// spamming NEAR Testnet RPC/gas on an idle chain (a tick where nothing
// is new costs exactly one free view call, never a transaction).
const DefaultScheduleInterval = 5 * time.Minute
// decideAnchor is the pure decision rule RunOnce applies: given the
// real local chain tip and whatever is currently anchored on-chain,
// should this tick submit a new anchor transaction, or skip because
// nothing has happened since the last anchor? Split out from RunOnce
// (which also has to make two network calls) so the actual rule this
// scheduler promises — "idempotent, skip when nothing new" — has a
// plain table-driven unit test that needs no network and no testnet
// credentials.
func decideAnchor(local store.Record, onChain AnchorRecord) (shouldCommit bool, reason string) {
if onChain.Sequence == 0 && onChain.ChainTipHash == "" {
return true, "nothing anchored on-chain yet"
}
if local.Sequence <= int64(onChain.Sequence) {
return false, fmt.Sprintf(
"local tip sequence=%d is not ahead of the on-chain anchor sequence=%d — nothing new to anchor",
local.Sequence, onChain.Sequence)
}
return true, fmt.Sprintf(
"local tip sequence=%d is ahead of the on-chain anchor sequence=%d",
local.Sequence, onChain.Sequence)
}
// TickResult is what one RunOnce call decided and (if it committed)
// did.
type TickResult struct {
Committed bool
Reason string
Local store.Record // zero value if there were no local records at all
HadLocal bool
Commit CommitResult // zero value unless Committed
}
// RunOnce performs exactly one scheduler tick: read the real local
// chain tip, read the real on-chain latest anchor (a free view call,
// no gas, no transaction), apply decideAnchor, and — only if it says
// to — sign and submit exactly one commit_anchor transaction for the
// current tip. Safe to call repeatedly and concurrently with a human
// running `near-anchor commit`/`verify` by hand: it never anchors a
// sequence that is already on-chain, and relies on nothing but what it
// reads fresh on every call (see this file's package-level doc comment
// for why that's what makes the scheduler restart-safe with zero
// checkpoint state of its own).
func RunOnce(ctx context.Context, cfg Config, rpc *RPCClient) (TickResult, error) {
path := cfg.AuditLogPath
if path == "" {
path = cfg.DataDir + "/audit.log"
}
local, ok, err := store.ReadTip(path)
if err != nil {
return TickResult{}, fmt.Errorf("nearanchor: read local tip: %w", err)
}
if !ok {
return TickResult{Committed: false, Reason: "no local audit-log records yet"}, nil
}
var onChain AnchorRecord
if err := rpc.CallFunctionView(ctx, cfg.ContractID, "get_latest_anchor", map[string]string{}, &onChain); err != nil {
return TickResult{}, fmt.Errorf("nearanchor: read on-chain latest anchor: %w", err)
}
should, reason := decideAnchor(local, onChain)
if !should {
return TickResult{Committed: false, Reason: reason, Local: local, HadLocal: true}, nil
}
result, err := CommitAnchor(ctx, cfg, rpc, local)
if err != nil {
return TickResult{}, fmt.Errorf("nearanchor: commit anchor for sequence=%d: %w", local.Sequence, err)
}
return TickResult{Committed: true, Reason: reason, Local: local, HadLocal: true, Commit: result}, nil
}
// RunScheduler runs RunOnce immediately and then on every tick of
// interval until ctx is cancelled, writing a one-line outcome for each
// tick to out. It never returns on a tick-level error (a transient RPC
// hiccup, or losing a race against another anchoring process) — those
// are logged and the loop keeps going, because an unattended scheduler
// that exits on the first flaky RPC call is strictly worse than one
// that logs and retries next interval. It only returns when ctx is
// cancelled (nil error) — the caller (cmd/near-anchor's `schedule`
// subcommand) wires ctx to SIGINT/SIGTERM so the process shuts down
// cleanly instead of being killed mid-transaction.
func RunScheduler(ctx context.Context, cfg Config, rpc *RPCClient, interval time.Duration, out io.Writer) error {
fmt.Fprintf(out, "near-anchor schedule: starting, interval=%s contract=%s signer=%s\n",
interval, cfg.ContractID, cfg.SignerAccountID)
tick := func() {
result, err := RunOnce(ctx, cfg, rpc)
if err != nil {
fmt.Fprintf(out, "near-anchor schedule: tick error (will retry next interval): %v\n", err)
return
}
if result.Committed {
fmt.Fprintf(out, "near-anchor schedule: anchored sequence=%d hash=%s tx=%s %s\n",
result.Local.Sequence, result.Local.Hash, result.Commit.TransactionHash, result.Commit.ExplorerURL)
return
}
fmt.Fprintf(out, "near-anchor schedule: skipped — %s\n", result.Reason)
}
// Run once immediately on start, not just after the first
// interval elapses — after a restart (or on first launch) there
// may already be a batch of unanchored records waiting, and
// nothing should sit for a full interval before that gets picked
// up. decideAnchor's idempotency check makes this safe to do
// unconditionally: if there's genuinely nothing new, this call
// just skips.
tick()
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
fmt.Fprintln(out, "near-anchor schedule: stopping")
return nil
case <-ticker.C:
tick()
}
}
}