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

219 lines
7.9 KiB
Go

package nearanchor
import (
"context"
"encoding/json"
"fmt"
"math/big"
"github.com/caelum0x/ration/services/audit-log/internal/store"
)
// AnchorRecord mirrors contracts-near/audit_anchor's AnchorRecord type
// field-for-field (near-sdk's default JSON serializer uses each Rust
// field's own snake_case name, so this struct's `json` tags are the
// literal wire format, not a guess) — this is the Go-side view of
// whatever is actually stored on-chain, used by VerifyAnchor to compare
// against the real local chain tip.
type AnchorRecord struct {
TenantID string `json:"tenant_id"`
ChainTipHash string `json:"chain_tip_hash"`
Sequence uint64 `json:"sequence"`
OccurredAtUnix int64 `json:"occurred_at_unix"`
AnchoredAtBlockTimestamp uint64 `json:"anchored_at_block_timestamp"`
}
// LocalTip reads cfg's configured audit-log file (AuditLogPath if set,
// else DataDir/audit.log, matching audit-log's own cmd/audit-log and
// cmd/verify-chain path convention) and returns its current chain tip.
func LocalTip(cfg Config) (store.Record, error) {
path := cfg.AuditLogPath
if path == "" {
path = cfg.DataDir + "/audit.log"
}
rec, ok, err := store.ReadTip(path)
if err != nil {
return store.Record{}, err
}
if !ok {
return store.Record{}, fmt.Errorf("nearanchor: %s has no records yet — nothing to anchor", path)
}
return rec, nil
}
// CommitResult is what CommitAnchor reports back: the on-chain
// transaction hash (independent proof this really executed on NEAR
// Testnet, not just locally) and the AnchorRecord the contract itself
// returned (re-derived from the chain's own SuccessValue, not just
// echoed from what was sent — if the contract's require!() ever
// rejects the commit, BroadcastTxCommit already returns a non-nil
// error before this is even populated).
type CommitResult struct {
TransactionHash string
Anchor AnchorRecord
ExplorerURL string
}
// CommitAnchor signs and submits a real NEAR Testnet transaction calling
// contracts-near/audit_anchor's commit_anchor(tenant_id, chain_tip_hash,
// sequence, occurred_at_unix) with tip's fields, waits for nearcore to
// report the transaction's final execution outcome, and returns the
// confirmed transaction hash plus the contract's own returned
// AnchorRecord.
func CommitAnchor(ctx context.Context, cfg Config, rpc *RPCClient, tip store.Record) (CommitResult, error) {
priv, pub, err := ParseSecretKey(cfg.SignerSecretKey)
if err != nil {
return CommitResult{}, err
}
nonce, err := rpc.AccessKeyNonce(ctx, cfg.SignerAccountID, pub)
if err != nil {
return CommitResult{}, fmt.Errorf("nearanchor: read signer access key nonce: %w", err)
}
blockHash, _, err := rpc.LatestBlock(ctx)
if err != nil {
return CommitResult{}, fmt.Errorf("nearanchor: read latest block hash: %w", err)
}
args, err := json.Marshal(map[string]interface{}{
"tenant_id": tip.TenantID,
"chain_tip_hash": tip.Hash,
"sequence": tip.Sequence,
"occurred_at_unix": tip.OccurredAtUnix,
})
if err != nil {
return CommitResult{}, fmt.Errorf("nearanchor: marshal commit_anchor args: %w", err)
}
tx := transaction{
SignerID: cfg.SignerAccountID,
PublicKey: pub,
Nonce: nonce + 1,
ReceiverID: cfg.ContractID,
BlockHash: blockHash,
Actions: []action{functionCallAction{
MethodName: "commit_anchor",
Args: args,
Gas: cfg.Gas,
Deposit: big.NewInt(0),
}},
}
signedBytes, _, err := signTransaction(tx, priv)
if err != nil {
return CommitResult{}, fmt.Errorf("nearanchor: sign commit_anchor transaction: %w", err)
}
broadcast, err := rpc.BroadcastTxCommit(ctx, signedBytes)
if err != nil {
return CommitResult{}, fmt.Errorf("nearanchor: broadcast commit_anchor: %w", err)
}
var anchor AnchorRecord
if broadcast.SuccessValue != nil {
if err := json.Unmarshal(broadcast.SuccessValue, &anchor); err != nil {
return CommitResult{}, fmt.Errorf("nearanchor: unmarshal commit_anchor return value: %w", err)
}
}
return CommitResult{
TransactionHash: broadcast.TransactionHash,
Anchor: anchor,
ExplorerURL: "https://testnet.nearblocks.io/txns/" + broadcast.TransactionHash,
}, nil
}
// VerifyResult is VerifyAnchor's outcome: whether the real local chain
// tip matches whatever is currently anchored on-chain, and both sides
// of the comparison so a caller can print a meaningful diff on
// mismatch.
type VerifyResult struct {
Match bool
LocalTip store.Record
OnChain AnchorRecord
Detail string
}
// VerifyAnchor reads cfg's local audit-log chain tip and compares it
// against contracts-near/audit_anchor's get_latest_anchor() view —
// independent of whichever process most recently called CommitAnchor,
// so this is a real "does the public, on-chain record match reality"
// check, not just re-confirming CommitAnchor's own return value.
func VerifyAnchor(ctx context.Context, cfg Config, rpc *RPCClient) (VerifyResult, error) {
local, err := LocalTip(cfg)
if err != nil {
return VerifyResult{}, err
}
var onChain AnchorRecord
if err := rpc.CallFunctionView(ctx, cfg.ContractID, "get_latest_anchor", map[string]string{}, &onChain); err != nil {
return VerifyResult{}, fmt.Errorf("nearanchor: read on-chain latest anchor: %w", err)
}
if onChain.Sequence == 0 && onChain.ChainTipHash == "" {
return VerifyResult{LocalTip: local, OnChain: onChain, Match: false,
Detail: "nothing anchored on-chain yet (get_latest_anchor returned null) — run `near-anchor commit` first"}, nil
}
match := onChain.Sequence == uint64(local.Sequence) && onChain.ChainTipHash == local.Hash
detail := "on-chain anchor matches the real local chain tip"
if !match {
detail = fmt.Sprintf("MISMATCH: local tip is sequence=%d hash=%s, on-chain anchor is sequence=%d hash=%s",
local.Sequence, local.Hash, onChain.Sequence, onChain.ChainTipHash)
}
return VerifyResult{Match: match, LocalTip: local, OnChain: onChain, Detail: detail}, nil
}
// DeployAndInit signs and submits a single transaction that both
// deploys wasmBytes to cfg.SignerAccountID (the contract's own account
// — see cmd/near-anchor's doc comment on why this repo deploys the
// contract directly onto the freshly-created signer account rather
// than a separate account) and, in the SAME transaction, calls `new()`
// to initialize contract state. nearcore applies a transaction's
// actions atomically and in order, so a DeployContract immediately
// followed by a FunctionCall to that same account's own just-deployed
// code is the standard NEAR deploy pattern (and means there is never a
// window where the account has code but uninitialized state).
func DeployAndInit(ctx context.Context, cfg Config, rpc *RPCClient, wasmBytes []byte) (CommitResult, error) {
priv, pub, err := ParseSecretKey(cfg.SignerSecretKey)
if err != nil {
return CommitResult{}, err
}
nonce, err := rpc.AccessKeyNonce(ctx, cfg.SignerAccountID, pub)
if err != nil {
return CommitResult{}, fmt.Errorf("nearanchor: read signer access key nonce: %w", err)
}
blockHash, _, err := rpc.LatestBlock(ctx)
if err != nil {
return CommitResult{}, fmt.Errorf("nearanchor: read latest block hash: %w", err)
}
tx := transaction{
SignerID: cfg.SignerAccountID,
PublicKey: pub,
Nonce: nonce + 1,
ReceiverID: cfg.SignerAccountID, // deploying to self
BlockHash: blockHash,
Actions: []action{
deployContractAction{Code: wasmBytes},
functionCallAction{MethodName: "new", Args: []byte("{}"), Gas: cfg.Gas, Deposit: big.NewInt(0)},
},
}
signedBytes, _, err := signTransaction(tx, priv)
if err != nil {
return CommitResult{}, fmt.Errorf("nearanchor: sign deploy+init transaction: %w", err)
}
broadcast, err := rpc.BroadcastTxCommit(ctx, signedBytes)
if err != nil {
return CommitResult{}, fmt.Errorf("nearanchor: broadcast deploy+init: %w", err)
}
return CommitResult{
TransactionHash: broadcast.TransactionHash,
ExplorerURL: "https://testnet.nearblocks.io/txns/" + broadcast.TransactionHash,
}, nil
}