Skip to content

Feature/xrouter v2 -draft - #68

Draft
atcsecure wants to merge 6 commits into
blocknetdx:masterfrom
atcsecure:feature/xrouter-v2
Draft

Feature/xrouter v2 -draft#68
atcsecure wants to merge 6 commits into
blocknetdx:masterfrom
atcsecure:feature/xrouter-v2

Conversation

@atcsecure

Copy link
Copy Markdown

No description provided.

Primary implementation target — daemon + client SDK. Documents project
structure, sprint plan, reusable v1 code, and payment channel flow.
Core v2 infrastructure:
- types/: Protocol messages (QueryRequest, CommitResponse, RevealSignal,
  PrimaryReveal, AttestorReveal, PromotionRequest/Response, PaymentRejection),
  ServiceNode, ServiceConfig, ChannelInfo, QueryReceipt
- config/: INI-style xrouter.conf parser (main, chain, service, plugin sections)
- crypto/: secp256k1 key management, message signing/verification,
  commit-reveal (GenerateCommitment/VerifyCommitment), SHA256d, nonce generation
- store/: BoltDB-backed persistent storage for receipts and channel state

All packages build cleanly. 11 unit tests passing (crypto + store).
- connector/connector.go: Connector interface (GetBlockCount, GetBlock,
  GetRawTransaction, GetBlockHeader, etc.)
- connector/btc.go: Bitcoin JSON-RPC connector with full RPC plumbing
  (works for BTC, LTC, DASH, any Bitcoin-derived chain)
- proof/types.go: MerkleProof, BlockHeader, TxInclusionProof,
  VerificationResult structs
- proof/merkle.go: Binary Merkle tree construction (SHA256d),
  proof path generation, proof verification
- proof/verify.go: 80-byte block header parsing, PoW verification
  (compact target expansion), BIP-34 coinbase height extraction,
  segwit witness stripping, full TxInclusionProof verification chain
- proof/merkle_test.go: 7 tests (single/two/odd/4-tx trees, proof
  generation and verification, wrong txid/root rejection, 7-tx block)
- proof/verify_test.go: 6 tests (real block #100000 header parsing,
  PoW verification, compact target, genesis difficulty, BIP-34 height)

24 total tests passing (crypto + store + proof).
- server/server.go: HTTP server with TLS support, graceful shutdown,
  route registration for v2 endpoints
- server/querystore.go: Thread-safe in-flight query state store with
  TTL cleanup (holds results between commit and reveal phases)
- server/middleware.go: Per-client rate limiter with sliding window
- server/handlers.go: Full request handler implementation:
  - POST /v2/query: execute service, compute commitment, return opaque hash
  - POST /v2/reveal: return full result (primary) or hash only (attestor)
  - POST /v2/promote: attestor sends full result after primary rejection
  - GET /v2/health: node status with connector health checks
  - GET /v2/services: list offered services with fees
  - Blockchain query routing (xr:: namespace) with Merkle proof assembly
  - Plugin routing (xrs:: namespace) delegates to plugin executor
- server/plugin.go: External binary execution with timeout, stdout
  capture, JSON validation
- server/handlers_test.go: 6 tests covering complete commit-reveal flow:
  - Health and services endpoints
  - Full query→commit→reveal round-trip with signature verification
  - Attestor reveal (hash only, no full result)
  - Promotion flow (attestor→primary with matching hash)
  - Unknown service rejection (404)

30 total tests passing across all packages.
- client/client.go: Full Client SDK with Query() method that orchestrates
  the complete commit-reveal protocol across primary + N attestors:
  1. Discover nodes for service, select primary (highest rep) + attestors
  2. Send QueryRequests in parallel, collect commitments
  3. Send RevealSignal, collect reveals (full result from primary, hash from attestors)
  4. Verify all commitments match reveals
  5. Check attestation (primary hash vs attestor hashes)
  6. If primary rejected: promote attestor (request full result, verify hash match)
  7. Return verified QueryResult with attestation percentage

- client/discovery.go: Config-based node discovery (Phase 1 — read JSON file).
  FindNodesForService(), SelectRoles() for primary/attestor assignment.

- client/verify.go: Attestation verification logic:
  VerifyCommitments(), ComputeConsensus(), CheckAttestation(), BuildReceipt()

- client/client_test.go: 6 tests including 3 full integration tests:
  - Happy path: 4 honest nodes, 100% attestation, correct result
  - One disagreeing attestor: 2/3 match, primary validated
  - Primary rejected + promoted: primary returns wrong data, attestors
    catch it, one attestor promoted to primary, correct result returned
  - SelectRoles: highest rep becomes primary
  - SelectRoles error: not enough nodes
  - CheckAttestation: 2/3 matching percentage calculation

Integration tests spin up 4 real HTTP servers (httptest) and run
the full commit-reveal protocol end-to-end through the network stack.

36 total tests passing across all packages.
Payment channel lifecycle for off-chain BLOCK payments:

- channel/state.go: Channel state machine with 5 states
  (Negotiating→Funding→Open→Closing→Closed). Thread-safe state
  transitions with validation. Pay() enforces: channel must be open,
  sufficient balance, positive fee, query_id required. State history
  tracking for dispute evidence (capped at 1000 entries).
  Custom JSON marshaling for Status enum.

- channel/scripts.go: Transaction construction helpers:
  CreateMultisig (2-of-2 via RPC), BuildFundingTx (UTXO selection
  with greedy algorithm, change output), BuildRefundTx (timelocked
  at current_height + 43200 blocks ~30 days), BuildCommitmentTx
  (reflects current balance split), BuildCloseTx (cooperative close).
  Fee estimation at 20 sat/byte.

- channel/channel.go: High-level channel operations:
  OpenChannel (full protocol: multisig→funding→refund→broadcast),
  ProcessPayment (build+sign commitment TX, update state),
  CooperativeClose (build+sign+broadcast close TX),
  UnilateralClose (broadcast latest commitment TX).

- channel/manager.go: Multi-channel management with:
  Add/Get/Remove, GetForNode (one channel per node),
  HasChannelFor (balance check), ListOpen, TotalBalance.
  BoltDB persistence — channels survive daemon restarts.

- rpc/blocknet.go: Blocknet daemon JSON-RPC client:
  ListUnspent, CreateRawTransaction (with optional locktime),
  SignRawTransaction (with wallet or explicit keys + prevtxs),
  SendRawTransaction, GetNewAddress, ValidateAddress,
  CreateMultisig, AddMultisigAddress, GetBlockCount,
  GetRawTransaction.

- channel/channel_test.go: 9 tests covering:
  Full lifecycle (negotiating→funding→open→closing→closed),
  payments with balance tracking, validation (zero fee, insufficient
  balance, empty query_id, closed channel), state history,
  close lifecycle, manager CRUD + node lookup + balance check,
  persistence across store reopen, Status JSON round-trip.

45 total tests passing across all packages.
@atcsecure
atcsecure marked this pull request as draft April 5, 2026 14:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant