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

89 lines
3.0 KiB
Go

package nearanchor
import (
"fmt"
"os"
"time"
)
// defaultFunctionCallGas is 100 Tgas — nearcore's own convention for a
// single, simple contract call (the protocol-wide max per function
// call is 300 Tgas); commit_anchor/new are both small, O(1) methods, so
// this is comfortably more than either ever needs.
const defaultFunctionCallGas = 100_000_000_000_000
// Config holds everything the near-anchor CLI needs, read from the
// environment (RATION_NEAR_ANCHOR_* — matches every other Go service in
// this repo's env-var-based config convention, see
// services/audit-log/internal/config). None of these have safe
// defaults for SignerAccountID/SignerSecretKey/ContractID — Load
// returns an error rather than silently anchoring to nothing or signing
// with an empty key.
type Config struct {
RPCURL string
FaucetURL string
DataDir string
AuditLogPath string
ContractID string
SignerAccountID string
SignerSecretKey string
Gas uint64
}
// LoadForCommit reads the subset of config needed to read the local
// chain tip and submit it on-chain (near-anchor commit/verify) —
// ContractID, SignerAccountID and SignerSecretKey are required; the
// rest have the same sane defaults the rest of this repo already uses.
func LoadForCommit() (Config, error) {
cfg := Config{
RPCURL: getenvDefault("RATION_NEAR_ANCHOR_RPC_URL", DefaultRPCURL),
FaucetURL: getenvDefault("RATION_NEAR_ANCHOR_FAUCET_URL", DefaultFaucetURL),
DataDir: getenvDefault("RATION_AUDIT_LOG_DATA_DIR", "./data"),
ContractID: os.Getenv("RATION_NEAR_ANCHOR_CONTRACT_ID"),
SignerAccountID: os.Getenv("RATION_NEAR_ANCHOR_SIGNER_ACCOUNT_ID"),
SignerSecretKey: os.Getenv("RATION_NEAR_ANCHOR_SIGNER_SECRET_KEY"),
Gas: defaultFunctionCallGas,
}
cfg.AuditLogPath = os.Getenv("RATION_NEAR_ANCHOR_AUDIT_LOG_PATH")
var missing []string
if cfg.ContractID == "" {
missing = append(missing, "RATION_NEAR_ANCHOR_CONTRACT_ID")
}
if cfg.SignerAccountID == "" {
missing = append(missing, "RATION_NEAR_ANCHOR_SIGNER_ACCOUNT_ID")
}
if cfg.SignerSecretKey == "" {
missing = append(missing, "RATION_NEAR_ANCHOR_SIGNER_SECRET_KEY")
}
if len(missing) > 0 {
return Config{}, fmt.Errorf("nearanchor: missing required env var(s): %v", missing)
}
return cfg, nil
}
func getenvDefault(key, def string) string {
if v := os.Getenv(key); v != "" {
return v
}
return def
}
// ScheduleInterval reads RATION_NEAR_ANCHOR_INTERVAL as a Go duration
// string (e.g. "5m", "30s", "1h") for `near-anchor schedule`, falling
// back to DefaultScheduleInterval if it is unset, empty, unparsable, or
// non-positive — a scheduler should never start with a zero or
// negative tick interval, since that would spin as fast as the RPC
// round-trip allows instead of waiting at all.
func ScheduleInterval() time.Duration {
v := os.Getenv("RATION_NEAR_ANCHOR_INTERVAL")
if v == "" {
return DefaultScheduleInterval
}
d, err := time.ParseDuration(v)
if err != nil || d <= 0 {
return DefaultScheduleInterval
}
return d
}