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

193 lines
7.4 KiB
Go

package nearanchor
import (
"context"
"fmt"
"os"
"path/filepath"
"testing"
"time"
"github.com/caelum0x/ration/services/audit-log/internal/store"
)
// TestDecideAnchor is the plain, no-network unit test for the exact
// rule RunOnce relies on to be "idempotent, skip when nothing new":
// whether to submit an anchor transaction depends only on comparing the
// real local tip's sequence against whatever is already anchored
// on-chain.
func TestDecideAnchor(t *testing.T) {
cases := []struct {
name string
local store.Record
onChain AnchorRecord
want bool
}{
{
name: "nothing anchored yet — first commit always proceeds",
local: store.Record{Sequence: 1, Hash: "h1"},
onChain: AnchorRecord{},
want: true,
},
{
name: "local ahead of on-chain — new records since last anchor",
local: store.Record{Sequence: 7, Hash: "h7"},
onChain: AnchorRecord{Sequence: 5, ChainTipHash: "h5"},
want: true,
},
{
name: "local equal to on-chain — nothing new, must skip",
local: store.Record{Sequence: 5, Hash: "h5"},
onChain: AnchorRecord{Sequence: 5, ChainTipHash: "h5"},
want: false,
},
{
name: "local behind on-chain — must never resubmit a stale sequence",
local: store.Record{Sequence: 3, Hash: "h3"},
onChain: AnchorRecord{Sequence: 5, ChainTipHash: "h5"},
want: false,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got, reason := decideAnchor(tc.local, tc.onChain)
if got != tc.want {
t.Fatalf("decideAnchor() = %v (%q), want %v", got, reason, tc.want)
}
if reason == "" {
t.Fatal("decideAnchor returned an empty reason")
}
})
}
}
// TestRunOnceSkipsOnEmptyLocalLog guards the same "anchoring nothing
// looks identical to a real anchor" failure mode
// TestLocalTipErrorsOnEmptyLog (integration_test.go) guards for
// LocalTip/CommitAnchor: RunOnce must report a clean skip, not an
// error and not a commit, when the local audit-log has no records at
// all yet. No real RPC call should happen in this case (and none does
// — this test supplies no valid signer/contract config, so any attempt
// to reach the network would fail loudly rather than silently pass).
func TestRunOnceSkipsOnEmptyLocalLog(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "audit.log")
if _, err := os.Create(path); err != nil {
t.Fatalf("create empty file: %v", err)
}
cfg := Config{AuditLogPath: path}
result, err := RunOnce(context.Background(), cfg, nil)
if err != nil {
t.Fatalf("RunOnce on an empty local log returned an error: %v", err)
}
if result.Committed {
t.Fatal("RunOnce committed with no local records at all")
}
if result.HadLocal {
t.Fatal("RunOnce reported HadLocal=true with no local records at all")
}
}
// TestRunSchedulerAgainstRealTestnet is the real, non-mocked
// integration test for the auto-anchoring loop itself (not just
// decideAnchor's pure logic): it appends a fresh real record to a real
// audit-log file, runs RunScheduler for a couple of short ticks against
// real NEAR Testnet, and checks that (a) the first tick actually
// anchors the new tip and (b) every subsequent tick correctly skips
// because nothing changed — proving the scheduler's idempotency holds
// against the real chain, not just against decideAnchor's unit test.
//
// Skipped unless real signer/contract credentials are configured — see
// TestCommitAndVerifyAgainstRealTestnet's doc comment
// (integration_test.go) for the same gating convention. Point this at
// the dedicated demo account (ration-demo-*.testnet), never the
// primary submission account, so a verification run never advances
// that account's on-chain history.
func TestRunSchedulerAgainstRealTestnet(t *testing.T) {
cfg, err := LoadForCommit()
if err != nil {
t.Skipf("skipping real NEAR Testnet scheduler integration test (set RATION_NEAR_ANCHOR_SIGNER_ACCOUNT_ID / RATION_NEAR_ANCHOR_SIGNER_SECRET_KEY / RATION_NEAR_ANCHOR_CONTRACT_ID to run it for real): %v", err)
}
if cfg.AuditLogPath == "" {
cfg.AuditLogPath = filepath.Join(cfg.DataDir, "audit.log")
}
if err := os.MkdirAll(filepath.Dir(cfg.AuditLogPath), 0o755); err != nil {
t.Fatalf("mkdir audit log dir: %v", err)
}
st, err := store.Open(cfg.AuditLogPath)
if err != nil {
t.Fatalf("open audit log: %v", err)
}
now := time.Now().Unix()
// RefID is time-varying (matching cmd/near-anchor's own cmdDemo
// convention), not a fixed string: Store.Append is itself
// idempotent on (source_service, kind, ref_id) — see store.go's
// doc comment — so a fixed RefID would make a second run of this
// test return the already-appended record instead of a genuinely
// new one, making it impossible to tell "the scheduler skipped
// because nothing is new" apart from "the test never appended
// anything new to begin with."
rec, err := st.Append(store.AppendInput{
SourceService: "agent",
Kind: store.SourceKindAgentDecision,
TenantID: "tenant-scheduler-integration-test",
RefID: fmt.Sprintf("scheduler-integration-test-decision-%d", time.Now().UnixNano()),
PayloadJSON: `{"action":"RationBridge","amount_minor_units":4321}`,
OccurredAtUnix: now,
}, now)
if err != nil {
_ = st.Close()
t.Fatalf("append: %v", err)
}
_ = st.Close() // RunOnce re-opens read-only via store.ReadTip
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
defer cancel()
rpc := NewRPCClient(cfg.RPCURL)
first, err := RunOnce(ctx, cfg, rpc)
if err != nil {
t.Fatalf("first RunOnce against real NEAR Testnet: %v", err)
}
if !first.Committed {
t.Fatalf("first RunOnce did not commit a new tip (sequence=%d): reason=%q", rec.Sequence, first.Reason)
}
if first.Commit.TransactionHash == "" {
t.Fatal("first RunOnce committed but returned an empty transaction hash")
}
t.Logf("tick 1: anchored sequence=%d hash=%s tx=%s %s", rec.Sequence, rec.Hash, first.Commit.TransactionHash, first.Commit.ExplorerURL)
// Give the RPC node(s) a moment to reflect the just-finalized
// commit before reading it back. Real-world findings from this
// test (first observed empirically, not assumed): calling
// get_latest_anchor() within ~1-2s of broadcast_tx_commit
// returning can still see the pre-commit state on a different
// backend node behind fastnear's public endpoint, and (separately)
// re-deriving the access key nonce that fast can race the
// just-used nonce before it's visible, failing a same-sequence
// retry with a transaction-layer InvalidNonce error rather than a
// clean decideAnchor skip. Neither corrupts on-chain state or
// double-anchors (confirmed live: get_anchor_count stayed
// unchanged across that race) — it only means two ticks fired
// faster than RPC propagation, which a real scheduler interval
// (minutes, see DefaultScheduleInterval) never does. This sleep
// makes the test reflect that real operating condition instead of
// deliberately hammering the race.
time.Sleep(5 * time.Second)
// Re-run without appending anything new: the real on-chain anchor
// now matches the real local tip exactly, so this must be a clean
// skip, not a duplicate (and on-chain-rejected) commit.
second, err := RunOnce(ctx, cfg, rpc)
if err != nil {
t.Fatalf("second RunOnce against real NEAR Testnet: %v", err)
}
if second.Committed {
t.Fatal("second RunOnce committed again with nothing new since the first — idempotency check failed against the real chain")
}
t.Logf("tick 2: correctly skipped — %s", second.Reason)
}