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

273 lines
9.5 KiB
Go

package nearanchor
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
// DefaultRPCURL is FastNear's free public NEAR Testnet RPC. NEAR's own
// legacy public endpoint (rpc.testnet.near.org) now rate-limits most
// calls with HTTP 429 (the same finding cred402's NEAR work already
// documented, see plans/cred402.md and
// ~/products/blockhain/cred402/HACKATHON.md) — FastNear is the same
// fallback cred402 standardized on, and
// RATION_NEAR_ANCHOR_RPC_URL still overrides this for any caller who
// wants a different (or self-hosted) RPC node.
const DefaultRPCURL = "https://rpc.testnet.fastnear.com"
// DefaultFaucetURL is NEAR's public testnet account-creation faucet —
// free, no captcha, no API key. Used only by cmd/near-anchor's
// create-account subcommand (never by CommitAnchor/VerifyAnchor, which
// assume an account already exists).
const DefaultFaucetURL = "https://helper.testnet.near.org/account"
// RPCClient is a minimal NEAR JSON-RPC 2.0 client covering exactly the
// methods this package needs: reading an access key's nonce, reading
// the latest finalized block hash (required on every transaction, to
// bound how long it stays valid for replay), broadcasting a signed
// transaction and waiting for its outcome, and read-only contract view
// calls. See https://docs.near.org/api/rpc/introduction.
type RPCClient struct {
URL string
HTTPClient *http.Client
}
// NewRPCClient returns a client pointed at url (DefaultRPCURL if url is
// empty) with a sane default timeout.
func NewRPCClient(url string) *RPCClient {
if url == "" {
url = DefaultRPCURL
}
return &RPCClient{URL: url, HTTPClient: &http.Client{Timeout: 30 * time.Second}}
}
type rpcRequest struct {
JSONRPC string `json:"jsonrpc"`
ID string `json:"id"`
Method string `json:"method"`
Params interface{} `json:"params"`
}
type rpcError struct {
Name string `json:"name"`
Cause struct {
Name string `json:"name"`
Info json.RawMessage `json:"info"`
} `json:"cause"`
}
func (e *rpcError) Error() string {
return fmt.Sprintf("nearanchor: rpc error %s/%s: %s", e.Name, e.Cause.Name, string(e.Cause.Info))
}
type rpcResponse struct {
Result json.RawMessage `json:"result"`
Error *rpcError `json:"error"`
}
func (c *RPCClient) call(ctx context.Context, method string, params interface{}, out interface{}) error {
reqBody, err := json.Marshal(rpcRequest{JSONRPC: "2.0", ID: "nearanchor", Method: method, Params: params})
if err != nil {
return fmt.Errorf("nearanchor: marshal rpc request: %w", err)
}
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, c.URL, bytes.NewReader(reqBody))
if err != nil {
return fmt.Errorf("nearanchor: build rpc request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
resp, err := c.HTTPClient.Do(httpReq)
if err != nil {
return fmt.Errorf("nearanchor: rpc call %s: %w", method, err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("nearanchor: read rpc response for %s: %w", method, err)
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("nearanchor: rpc call %s: HTTP %d: %s", method, resp.StatusCode, string(body))
}
var rpcResp rpcResponse
if err := json.Unmarshal(body, &rpcResp); err != nil {
return fmt.Errorf("nearanchor: unmarshal rpc response for %s: %w (body: %s)", method, err, string(body))
}
if rpcResp.Error != nil {
return rpcResp.Error
}
if out != nil {
if err := json.Unmarshal(rpcResp.Result, out); err != nil {
return fmt.Errorf("nearanchor: unmarshal rpc result for %s: %w", method, err)
}
}
return nil
}
// LatestBlock returns the hash (raw 32 bytes) and height of the latest
// finalized block, for stamping onto an outgoing transaction.
func (c *RPCClient) LatestBlock(ctx context.Context) (hash []byte, height uint64, err error) {
var result struct {
Header struct {
Hash string `json:"hash"`
Height uint64 `json:"height"`
} `json:"header"`
}
if err := c.call(ctx, "block", map[string]string{"finality": "final"}, &result); err != nil {
return nil, 0, fmt.Errorf("nearanchor: get latest block: %w", err)
}
raw, err := base58Decode(result.Header.Hash)
if err != nil {
return nil, 0, fmt.Errorf("nearanchor: decode block hash: %w", err)
}
return raw, result.Header.Height, nil
}
// AccessKeyNonce returns accountID's current nonce for publicKey — the
// next transaction signed with this key must use a nonce strictly
// greater than this value.
func (c *RPCClient) AccessKeyNonce(ctx context.Context, accountID, publicKey string) (uint64, error) {
var result struct {
Nonce uint64 `json:"nonce"`
}
params := map[string]string{
"request_type": "view_access_key",
"finality": "final",
"account_id": accountID,
"public_key": publicKey,
}
if err := c.call(ctx, "query", params, &result); err != nil {
return 0, fmt.Errorf("nearanchor: view access key for %s: %w", accountID, err)
}
return result.Nonce, nil
}
// BroadcastResult is broadcast_tx_commit's outcome, trimmed to what
// this package's callers need.
type BroadcastResult struct {
TransactionHash string // base58, as independently computed by signTransaction AND echoed back by nearcore
SuccessValue json.RawMessage // decoded SuccessValue (the called method's JSON return value), nil on failure
Failure json.RawMessage // raw Failure detail, nil on success
}
// BroadcastTxCommit submits a signed, Borsh-encoded transaction and
// blocks until nearcore reports its final execution outcome (success or
// failure) — the "_commit" RPC variant, not the fire-and-forget
// broadcast_tx_async, because this package's callers (CommitAnchor,
// cmd/near-anchor's deploy) need to know for certain whether the
// transaction actually executed before reporting success to a judge.
func (c *RPCClient) BroadcastTxCommit(ctx context.Context, signedTxBytes []byte) (BroadcastResult, error) {
b64 := base64.StdEncoding.EncodeToString(signedTxBytes)
var result struct {
TransactionOutcome struct {
ID string `json:"id"`
} `json:"transaction_outcome"`
Status struct {
SuccessValue json.RawMessage `json:"SuccessValue"`
Failure json.RawMessage `json:"Failure"`
} `json:"status"`
}
if err := c.call(ctx, "broadcast_tx_commit", []string{b64}, &result); err != nil {
return BroadcastResult{}, err
}
out := BroadcastResult{TransactionHash: result.TransactionOutcome.ID}
if result.Status.Failure != nil {
out.Failure = result.Status.Failure
return out, fmt.Errorf("nearanchor: transaction %s failed on-chain: %s", out.TransactionHash, string(result.Status.Failure))
}
if result.Status.SuccessValue != nil {
// SuccessValue is itself base64-encoded JSON (nearcore
// base64-encodes a FunctionCall's raw return bytes, which in
// this contract's case are always UTF-8 JSON — near-sdk's
// default `json` serializer for public methods).
var rawB64 string
if err := json.Unmarshal(result.Status.SuccessValue, &rawB64); err == nil && rawB64 != "" {
decoded, decErr := base64.StdEncoding.DecodeString(rawB64)
if decErr == nil {
out.SuccessValue = json.RawMessage(decoded)
}
}
}
return out, nil
}
// CallFunctionView performs a read-only contract call (no transaction,
// no signature, no gas cost) via NEAR's query RPC method, and
// JSON-unmarshals the result into out.
func (c *RPCClient) CallFunctionView(ctx context.Context, contractID, methodName string, args interface{}, out interface{}) error {
argsJSON, err := json.Marshal(args)
if err != nil {
return fmt.Errorf("nearanchor: marshal view-call args: %w", err)
}
var result struct {
Result []byte `json:"result"`
}
params := map[string]string{
"request_type": "call_function",
"finality": "optimistic",
"account_id": contractID,
"method_name": methodName,
"args_base64": base64.StdEncoding.EncodeToString(argsJSON),
}
if err := c.call(ctx, "query", params, &result); err != nil {
return fmt.Errorf("nearanchor: view-call %s.%s: %w", contractID, methodName, err)
}
if out == nil || len(result.Result) == 0 {
return nil
}
if err := json.Unmarshal(result.Result, out); err != nil {
return fmt.Errorf("nearanchor: unmarshal view-call %s.%s result: %w", contractID, methodName, err)
}
return nil
}
// CreateTestnetAccount creates a brand-new named *.testnet account for
// free via NEAR's public faucet helper — no owner credential, no
// captcha, no payment. Only ever used by cmd/near-anchor's
// create-account subcommand, never by the anchoring flow itself.
func CreateTestnetAccount(ctx context.Context, faucetURL, accountID, publicKey string) error {
if faucetURL == "" {
faucetURL = DefaultFaucetURL
}
body, err := json.Marshal(map[string]string{
"newAccountId": accountID,
"newAccountPublicKey": publicKey,
})
if err != nil {
return fmt.Errorf("nearanchor: marshal faucet request: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, faucetURL, bytes.NewReader(body))
if err != nil {
return fmt.Errorf("nearanchor: build faucet request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("nearanchor: faucet request for %s: %w", accountID, err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("nearanchor: read faucet response for %s: %w", accountID, err)
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("nearanchor: faucet account creation for %s failed (HTTP %d): %s", accountID, resp.StatusCode, string(respBody))
}
return nil
}