caelum0x cff0ed3129 feat(near-hackathon): anchor audit-log's hash-chain tip to NEAR Testnet
Adds a focused NEAR Hackathon 2026 entry built on Ration's existing,
real audit-log service rather than a Ration-on-NEAR rewrite: a minimal
NEAR smart contract (contracts-near/audit_anchor) storing/verifying
{tenant_id, chain_tip_hash, sequence, occurred_at_unix}, plus a
from-scratch Go NEAR transaction signer and CLI
(services/audit-log/internal/nearanchor, cmd/near-anchor) that reads
audit-log's real local chain tip and anchors it on-chain.

Verified live on NEAR Testnet (account ration-anchor-286ca315f1.testnet):
contract deployed and code_hash-matched, two successful on-chain
anchors, one deliberate replay correctly rejected by nearcore's own
sequence guard, and a real (non-mocked) Go integration test passing
against the live contract. Transaction encoding cross-checked
byte-for-byte against near-api-js. Zero regressions in existing Go/Rust
suites. Full detail and every tx hash in docs/near-hackathon/.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-09 14:19:33 +03:00

141 lines
5.6 KiB
Go

package nearanchor
import (
"context"
"os"
"path/filepath"
"testing"
"time"
"github.com/caelum0x/ration/services/audit-log/internal/store"
)
// TestCommitAndVerifyAgainstRealTestnet is the real, non-mocked
// integration test the NEAR hackathon submission asks for: it writes a
// real record to a real audit-log file (advancing the hash chain),
// anchors the resulting real chain tip in a real signed transaction
// submitted to NEAR Testnet, waits for nearcore's own confirmed
// execution outcome, and then independently re-reads the on-chain
// get_latest_anchor view to prove the stored hash matches the local
// chain tip exactly.
//
// This intentionally talks to the real network (no RPC mock, no
// in-process fake contract) — the whole point is proving this
// package's hand-rolled Borsh/signing code produces a transaction the
// real nearcore testnet actually accepts, not just a transaction this
// package's own code agrees is well-formed. It is skipped unless a
// real signer account + deployed contract are configured (see "How to
// run it" in docs/near-hackathon/HACKATHON.md) — the same
// gated-by-real-credentials pattern
// ~/products/blockhain/cred402 already uses for its own NEAR Testnet
// tests, so `go test ./...` stays green with no network/credentials
// available, while this test is real and re-runnable by anyone who
// does set the env vars (including a judge).
func TestCommitAndVerifyAgainstRealTestnet(t *testing.T) {
cfg, err := LoadForCommit()
if err != nil {
t.Skipf("skipping real NEAR Testnet 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)
}
// Deliberately NOT a fresh t.TempDir(): contracts-near/audit_anchor
// enforces a single, strictly-increasing sequence counter per
// contract account (see its own doc comment on why — rejecting
// stale/replayed anchors), which matches a single, ever-growing
// production audit-log, not a disposable per-test chain starting
// back at sequence 1 every run. So this test appends onto whatever
// audit-log already exists at cfg's configured path (defaulting to
// RATION_AUDIT_LOG_DATA_DIR/audit.log, the same convention
// cmd/near-anchor's own subcommands use) — exactly like a real
// operator re-running `near-anchor commit` against the same
// long-lived chain and the same long-lived contract.
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)
}
t.Cleanup(func() { _ = st.Close() })
now := time.Now().Unix()
before := st.VerifyChain()
rec, err := st.Append(store.AppendInput{
SourceService: "agent",
Kind: store.SourceKindAgentDecision,
TenantID: "tenant-integration-test",
RefID: "integration-test-decision",
PayloadJSON: `{"action":"RationBridge","amount_minor_units":1234}`,
OccurredAtUnix: now,
}, now)
if err != nil {
t.Fatalf("append: %v", err)
}
after := st.VerifyChain()
if !after.Intact {
t.Fatalf("chain not intact after append: %s", after.Detail)
}
if after.RecordsChecked != before.RecordsChecked+1 {
t.Fatalf("chain did not advance: before=%d after=%d", before.RecordsChecked, after.RecordsChecked)
}
// Close before CommitAnchor re-opens the file read-only via
// LocalTip/store.ReadTip.
_ = st.Close()
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
rpc := NewRPCClient(cfg.RPCURL)
commitResult, err := CommitAnchor(ctx, cfg, rpc, rec)
if err != nil {
t.Fatalf("CommitAnchor against real NEAR Testnet: %v", err)
}
if commitResult.TransactionHash == "" {
t.Fatal("CommitAnchor returned an empty transaction hash")
}
t.Logf("anchored on real NEAR Testnet: tx=%s %s", commitResult.TransactionHash, commitResult.ExplorerURL)
if commitResult.Anchor.Sequence != uint64(rec.Sequence) {
t.Fatalf("on-chain returned sequence %d, want %d", commitResult.Anchor.Sequence, rec.Sequence)
}
if commitResult.Anchor.ChainTipHash != rec.Hash {
t.Fatalf("on-chain returned hash %q, want %q", commitResult.Anchor.ChainTipHash, rec.Hash)
}
verifyResult, err := VerifyAnchor(ctx, cfg, rpc)
if err != nil {
t.Fatalf("VerifyAnchor against real NEAR Testnet: %v", err)
}
if !verifyResult.Match {
t.Fatalf("VerifyAnchor reported a mismatch: %s", verifyResult.Detail)
}
if verifyResult.LocalTip.Hash != rec.Hash || verifyResult.OnChain.ChainTipHash != rec.Hash {
t.Fatalf("verify result did not reflect the record just anchored: local=%+v onChain=%+v", verifyResult.LocalTip, verifyResult.OnChain)
}
t.Logf("PASSED: real audit-log entry written (seq=%d hash=%s), hash chain advanced, anchor transaction %s confirmed on NEAR Testnet, on-chain stored hash matches local chain tip",
rec.Sequence, rec.Hash, commitResult.TransactionHash)
}
// TestLocalTipErrorsOnEmptyLog guards against CommitAnchor ever being
// called with a zero-value Record (sequence 0, empty hash) just
// because the audit log happens to be empty — anchoring "nothing" would
// otherwise silently succeed and look identical to a real anchor.
func TestLocalTipErrorsOnEmptyLog(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}
if _, err := LocalTip(cfg); err == nil {
t.Fatal("LocalTip on an empty audit log succeeded, want an error")
}
}