Owner directive (2026-11-11): submit a single project to the NEAR Hackathon instead of two separate entries from the same person. Vendors Ration's NEAR audit-anchor work (github.com/caelum0x/ration, commit cff0ed3 + follow-ups) into ration-anchor/ as a first-class component: - contracts-near/audit_anchor (NEAR Rust contract, 5/5 cargo tests green, target/ deleted) - signer/ — a new, self-contained Go module (no dependency on Ration's other services or go.work) with the hand-rolled NEAR transaction signer + JSON-RPC client (cross-checked byte-for-byte against near-api-js) and the hash-chained audit ledger it anchors; 15/15 Go tests green (go test ./... -race) - docs/ and media/ — Ration's original pitch deck, demo recordings, and submission checklist Re-verified live via raw NEAR Testnet JSON-RPC this pass: ration-anchor-286ca315f1.testnet still deployed and queryable, the deliberate replay-rejection transaction still fails with nearcore's own "sequence must strictly advance" panic — no redeploy needed. Provenance notes added throughout (package doc comments, lib.rs header, README) crediting the origin repo. README.md and HACKATHON.md rewritten to tell one story: Cred402's SpendGuard enforces the protocol-level spending limit, the vendored Audit Anchor proves the tamper-evident spend history, both independently verifiable on NEAR Testnet. No mainnet claims anywhere (see prior overclaim fix 524f2dd). cred402's own build (npm run typecheck) and existing tests are untouched. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
219 lines
7.9 KiB
Go
219 lines
7.9 KiB
Go
package nearanchor
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"math/big"
|
|
|
|
"github.com/caelum0x/cred402/ration-anchor/signer/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
|
|
}
|