chore: initial commit for v0.0.1
DChain single-node blockchain + React Native messenger client. Core: - PBFT consensus with multi-sig validator admission + equivocation slashing - BadgerDB + schema migration scaffold (CurrentSchemaVersion=0) - libp2p gossipsub (tx/v1, blocks/v1, relay/v1, version/v1) - Native Go contracts (username_registry) alongside WASM (wazero) - WebSocket gateway with topic-based fanout + Ed25519-nonce auth - Relay mailbox with NaCl envelope encryption (X25519 + Ed25519) - Prometheus /metrics, per-IP rate limit, body-size cap Deployment: - Single-node compose (deploy/single/) with Caddy TLS + optional Prometheus - 3-node dev compose (docker-compose.yml) with mocked internet topology - 3-validator prod compose (deploy/prod/) for federation - Auto-update from Gitea via /api/update-check + systemd timer - Build-time version injection (ldflags → node --version) - UI / Swagger toggle flags (DCHAIN_DISABLE_UI, DCHAIN_DISABLE_SWAGGER) Client (client-app/): - Expo / React Native / NativeWind - E2E NaCl encryption, typing indicator, contact requests - Auto-discovery of canonical contracts, chain_id aware, WS reconnect on node switch Documentation: - README.md, CHANGELOG.md, CONTEXT.md - deploy/single/README.md with 6 operator scenarios - deploy/UPDATE_STRATEGY.md with 4-layer forward-compat design - docs/contracts/*.md per contract
This commit is contained in:
701
client-app/lib/api.ts
Normal file
701
client-app/lib/api.ts
Normal file
@@ -0,0 +1,701 @@
|
||||
/**
|
||||
* DChain REST API client.
|
||||
* All requests go to the configured node URL (e.g. http://192.168.1.10:8081).
|
||||
*/
|
||||
|
||||
import type { Envelope, TxRecord, NetStats, Contact } from './types';
|
||||
|
||||
// ─── Base ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
let _nodeUrl = 'http://localhost:8081';
|
||||
|
||||
/**
|
||||
* Listeners invoked AFTER _nodeUrl changes. The WS client registers here so
|
||||
* that switching nodes in Settings tears down the old socket and re-dials
|
||||
* the new one (without this, a user who pointed their app at node A would
|
||||
* keep receiving A's events forever after flipping to B).
|
||||
*/
|
||||
const nodeUrlListeners = new Set<(url: string) => void>();
|
||||
|
||||
export function setNodeUrl(url: string) {
|
||||
const normalised = url.replace(/\/$/, '');
|
||||
if (_nodeUrl === normalised) return;
|
||||
_nodeUrl = normalised;
|
||||
for (const fn of nodeUrlListeners) {
|
||||
try { fn(_nodeUrl); } catch { /* ignore — listeners are best-effort */ }
|
||||
}
|
||||
}
|
||||
|
||||
export function getNodeUrl(): string {
|
||||
return _nodeUrl;
|
||||
}
|
||||
|
||||
/** Register a callback for node-URL changes. Returns an unsubscribe fn. */
|
||||
export function onNodeUrlChange(fn: (url: string) => void): () => void {
|
||||
nodeUrlListeners.add(fn);
|
||||
return () => { nodeUrlListeners.delete(fn); };
|
||||
}
|
||||
|
||||
async function get<T>(path: string): Promise<T> {
|
||||
const res = await fetch(`${_nodeUrl}${path}`);
|
||||
if (!res.ok) throw new Error(`GET ${path} → ${res.status}`);
|
||||
return res.json() as Promise<T>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enhanced error reporter for POST failures. The node's `jsonErr` writes
|
||||
* `{"error": "..."}` as the response body; we parse that out so the UI layer
|
||||
* can show a meaningful message instead of a raw status code.
|
||||
*
|
||||
* Rate-limit and timestamp-skew rejections produce specific strings the UI
|
||||
* can translate to user-friendly Russian via matcher functions below.
|
||||
*/
|
||||
async function post<T>(path: string, body: unknown): Promise<T> {
|
||||
const res = await fetch(`${_nodeUrl}${path}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const text = await res.text();
|
||||
// Try to extract {"error":"..."} payload for a cleaner message.
|
||||
let detail = text;
|
||||
try {
|
||||
const parsed = JSON.parse(text);
|
||||
if (parsed?.error) detail = parsed.error;
|
||||
} catch { /* keep raw text */ }
|
||||
// Include HTTP status so `humanizeTxError` can branch on 429/400/etc.
|
||||
throw new Error(`${res.status}: ${detail}`);
|
||||
}
|
||||
return res.json() as Promise<T>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn a submission error from `post()` / `submitTx()` into a user-facing
|
||||
* Russian message with actionable hints. Preserves the raw detail at the end
|
||||
* so advanced users can still copy the original for support.
|
||||
*/
|
||||
export function humanizeTxError(e: unknown): string {
|
||||
const raw = e instanceof Error ? e.message : String(e);
|
||||
if (raw.startsWith('429')) {
|
||||
return 'Слишком много запросов к ноде. Подождите пару секунд и попробуйте снова.';
|
||||
}
|
||||
if (raw.startsWith('400') && raw.includes('timestamp')) {
|
||||
return 'Часы устройства не синхронизированы с нодой. Проверьте время на телефоне (±1 час).';
|
||||
}
|
||||
if (raw.startsWith('400') && raw.includes('signature')) {
|
||||
return 'Подпись транзакции невалидна. Попробуйте ещё раз; если не помогает — вероятна несовместимость версий клиента и ноды.';
|
||||
}
|
||||
if (raw.startsWith('400')) {
|
||||
return `Нода отклонила транзакцию: ${raw.replace(/^400:\s*/, '')}`;
|
||||
}
|
||||
if (raw.startsWith('5')) {
|
||||
return `Ошибка ноды (${raw}). Попробуйте позже.`;
|
||||
}
|
||||
// Network-level
|
||||
if (raw.toLowerCase().includes('network request failed')) {
|
||||
return 'Нет связи с нодой. Проверьте URL в настройках и доступность сервера.';
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
// ─── Chain API ────────────────────────────────────────────────────────────────
|
||||
|
||||
export async function getNetStats(): Promise<NetStats> {
|
||||
return get<NetStats>('/api/netstats');
|
||||
}
|
||||
|
||||
interface AddrResponse {
|
||||
balance_ut: number;
|
||||
balance: string;
|
||||
transactions: Array<{
|
||||
id: string;
|
||||
type: string;
|
||||
from: string;
|
||||
to?: string;
|
||||
amount_ut: number;
|
||||
fee_ut: number;
|
||||
time: string; // ISO-8601 e.g. "2025-01-01T12:00:00Z"
|
||||
block_index: number;
|
||||
}>;
|
||||
tx_count: number;
|
||||
has_more: boolean;
|
||||
}
|
||||
|
||||
export async function getBalance(pubkey: string): Promise<number> {
|
||||
const data = await get<AddrResponse>(`/api/address/${pubkey}`);
|
||||
return data.balance_ut ?? 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transaction as sent to /api/tx — maps 1-to-1 to blockchain.Transaction JSON.
|
||||
* Key facts:
|
||||
* - `payload` is base64-encoded JSON bytes (Go []byte → base64 in JSON)
|
||||
* - `signature` is base64-encoded Ed25519 sig (Go []byte → base64 in JSON)
|
||||
* - `timestamp` is RFC3339 string (Go time.Time → string in JSON)
|
||||
* - There is NO nonce field; dedup is by `id`
|
||||
*/
|
||||
export interface RawTx {
|
||||
id: string; // "tx-<nanoseconds>" or sha256-based
|
||||
type: string; // "TRANSFER", "CONTACT_REQUEST", etc.
|
||||
from: string; // hex Ed25519 pub key
|
||||
to: string; // hex Ed25519 pub key (empty string if N/A)
|
||||
amount: number; // µT (uint64)
|
||||
fee: number; // µT (uint64)
|
||||
memo?: string; // optional
|
||||
payload: string; // base64(json.Marshal(TypeSpecificPayload))
|
||||
signature: string; // base64(ed25519.Sign(canonical_bytes, priv))
|
||||
timestamp: string; // RFC3339 e.g. "2025-01-01T12:00:00Z"
|
||||
}
|
||||
|
||||
export async function submitTx(tx: RawTx): Promise<{ id: string; status: string }> {
|
||||
console.log('[submitTx] →', {
|
||||
id: tx.id,
|
||||
type: tx.type,
|
||||
from: tx.from.slice(0, 12) + '…',
|
||||
to: tx.to ? tx.to.slice(0, 12) + '…' : '',
|
||||
amount: tx.amount,
|
||||
fee: tx.fee,
|
||||
timestamp: tx.timestamp,
|
||||
transport: 'auto',
|
||||
});
|
||||
|
||||
// Try the WebSocket path first: no HTTP round-trip, and we get a proper
|
||||
// submit_ack correlated back to our tx id. Falls through to HTTP if WS is
|
||||
// unavailable (old node, disconnected, timeout, etc.) so legacy setups
|
||||
// keep working.
|
||||
try {
|
||||
// Lazy import avoids a circular dep with lib/ws.ts (which itself
|
||||
// imports getNodeUrl from this module).
|
||||
const { getWSClient } = await import('./ws');
|
||||
const ws = getWSClient();
|
||||
if (ws.isConnected()) {
|
||||
try {
|
||||
const res = await ws.submitTx(tx);
|
||||
console.log('[submitTx] ← accepted via WS', res);
|
||||
return { id: res.id || tx.id, status: 'accepted' };
|
||||
} catch (e) {
|
||||
console.warn('[submitTx] WS path failed, falling back to HTTP:', e);
|
||||
}
|
||||
}
|
||||
} catch { /* circular import edge case — ignore and use HTTP */ }
|
||||
|
||||
try {
|
||||
const res = await post<{ id: string; status: string }>('/api/tx', tx);
|
||||
console.log('[submitTx] ← accepted via HTTP', res);
|
||||
return res;
|
||||
} catch (e) {
|
||||
console.warn('[submitTx] ← rejected', e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getTxHistory(pubkey: string, limit = 50): Promise<TxRecord[]> {
|
||||
const data = await get<AddrResponse>(`/api/address/${pubkey}?limit=${limit}`);
|
||||
return (data.transactions ?? []).map(tx => ({
|
||||
hash: tx.id,
|
||||
type: tx.type,
|
||||
from: tx.from,
|
||||
to: tx.to,
|
||||
amount: tx.amount_ut,
|
||||
fee: tx.fee_ut,
|
||||
// Convert ISO-8601 string → unix seconds
|
||||
timestamp: tx.time ? Math.floor(new Date(tx.time).getTime() / 1000) : 0,
|
||||
status: 'confirmed' as const,
|
||||
}));
|
||||
}
|
||||
|
||||
// ─── Relay API ────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface SendEnvelopeReq {
|
||||
sender_pub: string;
|
||||
recipient_pub: string;
|
||||
nonce: string;
|
||||
ciphertext: string;
|
||||
}
|
||||
|
||||
export async function sendEnvelope(env: SendEnvelopeReq): Promise<{ ok: boolean }> {
|
||||
return post<{ ok: boolean }>('/api/relay/send', env);
|
||||
}
|
||||
|
||||
export async function fetchInbox(x25519PubHex: string): Promise<Envelope[]> {
|
||||
return get<Envelope[]>(`/api/relay/inbox?pub=${x25519PubHex}`);
|
||||
}
|
||||
|
||||
// ─── Contact requests (on-chain) ─────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Maps blockchain.ContactInfo returned by GET /api/relay/contacts?pub=...
|
||||
* The response shape is { pub, count, contacts: ContactInfo[] }.
|
||||
*/
|
||||
export interface ContactRequestRaw {
|
||||
requester_pub: string; // Ed25519 pubkey of requester
|
||||
requester_addr: string; // DChain address (DC…)
|
||||
status: string; // "pending" | "accepted" | "blocked"
|
||||
intro: string; // plaintext intro message (may be empty)
|
||||
fee_ut: number; // anti-spam fee paid in µT
|
||||
tx_id: string; // transaction ID
|
||||
created_at: number; // unix seconds
|
||||
}
|
||||
|
||||
export async function fetchContactRequests(edPubHex: string): Promise<ContactRequestRaw[]> {
|
||||
const data = await get<{ contacts: ContactRequestRaw[] }>(`/api/relay/contacts?pub=${edPubHex}`);
|
||||
return data.contacts ?? [];
|
||||
}
|
||||
|
||||
// ─── Identity API ─────────────────────────────────────────────────────────────
|
||||
|
||||
export interface IdentityInfo {
|
||||
pub_key: string;
|
||||
address: string;
|
||||
x25519_pub: string; // hex Curve25519 key; empty string if not published
|
||||
nickname: string;
|
||||
registered: boolean;
|
||||
}
|
||||
|
||||
/** Fetch identity info for any pubkey or DC address. Returns null on 404. */
|
||||
export async function getIdentity(pubkeyOrAddr: string): Promise<IdentityInfo | null> {
|
||||
try {
|
||||
return await get<IdentityInfo>(`/api/identity/${pubkeyOrAddr}`);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Contract API ─────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Response shape from GET /api/contracts/{id}/state/{key}.
|
||||
* The node handler (node/api_contract.go:handleContractState) returns either:
|
||||
* { value_b64: null, value_hex: null, ... } when the key is missing
|
||||
* or
|
||||
* { value_b64: "...", value_hex: "...", value_u64?: 0 } when the key exists.
|
||||
*/
|
||||
interface ContractStateResponse {
|
||||
contract_id: string;
|
||||
key: string;
|
||||
value_b64: string | null;
|
||||
value_hex: string | null;
|
||||
value_u64?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode a hex string (lowercase/uppercase) back to the original string value
|
||||
* it represents. The username registry contract stores values as plain ASCII
|
||||
* bytes (pubkey hex strings / username strings), so `value_hex` on the wire
|
||||
* is the hex-encoding of UTF-8 bytes. We hex-decode to bytes, then interpret
|
||||
* those bytes as UTF-8.
|
||||
*/
|
||||
function hexToUtf8(hex: string): string {
|
||||
if (hex.length % 2 !== 0) return '';
|
||||
const bytes = new Uint8Array(hex.length / 2);
|
||||
for (let i = 0; i < hex.length; i += 2) {
|
||||
bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
|
||||
}
|
||||
// TextDecoder is available in Hermes / RN's JS runtime.
|
||||
try {
|
||||
return new TextDecoder('utf-8').decode(bytes);
|
||||
} catch {
|
||||
// Fallback for environments without TextDecoder.
|
||||
let s = '';
|
||||
for (const b of bytes) s += String.fromCharCode(b);
|
||||
return s;
|
||||
}
|
||||
}
|
||||
|
||||
/** username → address (hex pubkey). Returns null if unregistered. */
|
||||
export async function resolveUsername(contractId: string, username: string): Promise<string | null> {
|
||||
try {
|
||||
const data = await get<ContractStateResponse>(`/api/contracts/${contractId}/state/name:${username}`);
|
||||
if (!data.value_hex) return null;
|
||||
const decoded = hexToUtf8(data.value_hex).trim();
|
||||
return decoded || null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** address (hex pubkey) → username. Returns null if this address hasn't registered a name. */
|
||||
export async function reverseResolve(contractId: string, address: string): Promise<string | null> {
|
||||
try {
|
||||
const data = await get<ContractStateResponse>(`/api/contracts/${contractId}/state/addr:${address}`);
|
||||
if (!data.value_hex) return null;
|
||||
const decoded = hexToUtf8(data.value_hex).trim();
|
||||
return decoded || null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Well-known contracts ─────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Per-entry shape returned by GET /api/well-known-contracts.
|
||||
* Matches node/api_well_known.go:WellKnownContract.
|
||||
*/
|
||||
export interface WellKnownContract {
|
||||
contract_id: string;
|
||||
name: string;
|
||||
version?: string;
|
||||
deployed_at: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Response from GET /api/well-known-contracts.
|
||||
* `contracts` is keyed by ABI name (e.g. "username_registry").
|
||||
*/
|
||||
export interface WellKnownResponse {
|
||||
count: number;
|
||||
contracts: Record<string, WellKnownContract>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the node's view of canonical system contracts so the client doesn't
|
||||
* have to force the user to paste contract IDs into settings.
|
||||
*
|
||||
* The node returns the earliest-deployed contract per ABI name; this means
|
||||
* every peer in the same chain reports the same mapping.
|
||||
*
|
||||
* Returns `null` on failure (old node, network hiccup, endpoint missing).
|
||||
*/
|
||||
export async function fetchWellKnownContracts(): Promise<WellKnownResponse | null> {
|
||||
try {
|
||||
return await get<WellKnownResponse>('/api/well-known-contracts');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Node version / update-check ─────────────────────────────────────────────
|
||||
//
|
||||
// The three calls below let the client:
|
||||
// 1. fetchNodeVersion() — see what tag/commit/features the connected node
|
||||
// exposes. Used on first boot + on every chain-switch so we can warn if
|
||||
// a required feature is missing.
|
||||
// 2. checkNodeVersion(required) — thin wrapper that returns {supported,
|
||||
// missing} by diffing a client-expected feature list against the node's.
|
||||
// 3. fetchUpdateCheck() — ask the node whether its operator has a newer
|
||||
// release available from their configured release source (Gitea). For
|
||||
// messenger UX this is purely informational ("the node you're on is N
|
||||
// versions behind"), never used to update the node automatically.
|
||||
|
||||
/** The shape returned by GET /api/well-known-version. */
|
||||
export interface NodeVersionInfo {
|
||||
node_version: string;
|
||||
protocol_version: number;
|
||||
features: string[];
|
||||
chain_id?: string;
|
||||
build?: {
|
||||
tag: string;
|
||||
commit: string;
|
||||
date: string;
|
||||
dirty: string;
|
||||
};
|
||||
}
|
||||
|
||||
/** Client-expected protocol version. Bumped only when wire-protocol breaks. */
|
||||
export const CLIENT_PROTOCOL_VERSION = 1;
|
||||
|
||||
/**
|
||||
* Minimum feature set this client build relies on. A node missing any of
|
||||
* these is considered "unsupported" — caller should surface an upgrade
|
||||
* prompt to the user instead of silently failing on the first feature call.
|
||||
*/
|
||||
export const CLIENT_REQUIRED_FEATURES = [
|
||||
'chain_id',
|
||||
'identity_registry',
|
||||
'onboarding_api',
|
||||
'relay_mailbox',
|
||||
'ws_submit_tx',
|
||||
];
|
||||
|
||||
/** GET /api/well-known-version. Returns null on failure (old node, network hiccup). */
|
||||
export async function fetchNodeVersion(): Promise<NodeVersionInfo | null> {
|
||||
try {
|
||||
return await get<NodeVersionInfo>('/api/well-known-version');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether the connected node supports this client's required features
|
||||
* and protocol version. Returns a decision blob the UI can render directly.
|
||||
*
|
||||
* { supported: true } → everything fine
|
||||
* { supported: false, reason: "...", ... } → show update prompt
|
||||
* { supported: null, reason: "unreachable" } → couldn't reach the endpoint,
|
||||
* likely old node — assume OK
|
||||
* but warn quietly.
|
||||
*/
|
||||
export async function checkNodeVersion(
|
||||
required: string[] = CLIENT_REQUIRED_FEATURES,
|
||||
): Promise<{
|
||||
supported: boolean | null;
|
||||
reason?: string;
|
||||
missing?: string[];
|
||||
info?: NodeVersionInfo;
|
||||
}> {
|
||||
const info = await fetchNodeVersion();
|
||||
if (!info) {
|
||||
return { supported: null, reason: 'unreachable' };
|
||||
}
|
||||
if (info.protocol_version !== CLIENT_PROTOCOL_VERSION) {
|
||||
return {
|
||||
supported: false,
|
||||
reason: `protocol v${info.protocol_version} but client expects v${CLIENT_PROTOCOL_VERSION}`,
|
||||
info,
|
||||
};
|
||||
}
|
||||
const have = new Set(info.features || []);
|
||||
const missing = required.filter((f) => !have.has(f));
|
||||
if (missing.length > 0) {
|
||||
return {
|
||||
supported: false,
|
||||
reason: `node missing features: ${missing.join(', ')}`,
|
||||
missing,
|
||||
info,
|
||||
};
|
||||
}
|
||||
return { supported: true, info };
|
||||
}
|
||||
|
||||
/** The shape returned by GET /api/update-check. */
|
||||
export interface UpdateCheckResponse {
|
||||
current: { tag: string; commit: string; date: string; dirty: string };
|
||||
latest?: { tag: string; commit?: string; url?: string; published_at?: string };
|
||||
update_available: boolean;
|
||||
checked_at: string;
|
||||
source?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/update-check. Returns null when:
|
||||
* - the node operator hasn't configured DCHAIN_UPDATE_SOURCE_URL (503),
|
||||
* - upstream Gitea call failed (502),
|
||||
* - request errored out.
|
||||
* All three are non-fatal for the client; the UI just doesn't render the
|
||||
* "update available" banner.
|
||||
*/
|
||||
export async function fetchUpdateCheck(): Promise<UpdateCheckResponse | null> {
|
||||
try {
|
||||
return await get<UpdateCheckResponse>('/api/update-check');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Transaction builder helpers ─────────────────────────────────────────────
|
||||
|
||||
import { signBase64, bytesToBase64 } from './crypto';
|
||||
|
||||
/** Minimum blockchain tx fee paid to the block validator (matches blockchain.MinFee = 1000 µT). */
|
||||
const MIN_TX_FEE = 1000;
|
||||
|
||||
const _encoder = new TextEncoder();
|
||||
|
||||
/** RFC3339 timestamp with second precision — matches Go time.Time JSON output. */
|
||||
function rfc3339Now(): string {
|
||||
const d = new Date();
|
||||
d.setMilliseconds(0);
|
||||
// toISOString() gives "2025-01-01T12:00:00.000Z" → replace ".000Z" with "Z"
|
||||
return d.toISOString().replace('.000Z', 'Z');
|
||||
}
|
||||
|
||||
/** Unique transaction ID (nanoseconds-like using Date.now + random). */
|
||||
function newTxID(): string {
|
||||
return `tx-${Date.now()}${Math.floor(Math.random() * 1_000_000)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Canonical bytes for signing — must match identity.txSignBytes in Go exactly.
|
||||
*
|
||||
* Go struct field order: id, type, from, to, amount, fee, payload, timestamp.
|
||||
* JS JSON.stringify preserves insertion order, so we rely on that here.
|
||||
*/
|
||||
function txCanonicalBytes(tx: {
|
||||
id: string; type: string; from: string; to: string;
|
||||
amount: number; fee: number; payload: string; timestamp: string;
|
||||
}): Uint8Array {
|
||||
const s = JSON.stringify({
|
||||
id: tx.id,
|
||||
type: tx.type,
|
||||
from: tx.from,
|
||||
to: tx.to,
|
||||
amount: tx.amount,
|
||||
fee: tx.fee,
|
||||
payload: tx.payload,
|
||||
timestamp: tx.timestamp,
|
||||
});
|
||||
return _encoder.encode(s);
|
||||
}
|
||||
|
||||
/** Encode a JS string (UTF-8) to base64. */
|
||||
function strToBase64(s: string): string {
|
||||
return bytesToBase64(_encoder.encode(s));
|
||||
}
|
||||
|
||||
export function buildTransferTx(params: {
|
||||
from: string;
|
||||
to: string;
|
||||
amount: number;
|
||||
fee: number;
|
||||
privKey: string;
|
||||
memo?: string;
|
||||
}): RawTx {
|
||||
const id = newTxID();
|
||||
const timestamp = rfc3339Now();
|
||||
const payloadObj = params.memo ? { memo: params.memo } : {};
|
||||
const payload = strToBase64(JSON.stringify(payloadObj));
|
||||
|
||||
const canonical = txCanonicalBytes({
|
||||
id, type: 'TRANSFER', from: params.from, to: params.to,
|
||||
amount: params.amount, fee: params.fee, payload, timestamp,
|
||||
});
|
||||
|
||||
return {
|
||||
id, type: 'TRANSFER', from: params.from, to: params.to,
|
||||
amount: params.amount, fee: params.fee,
|
||||
memo: params.memo,
|
||||
payload, timestamp,
|
||||
signature: signBase64(canonical, params.privKey),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* CONTACT_REQUEST transaction.
|
||||
*
|
||||
* blockchain.Transaction fields:
|
||||
* Amount = contactFee — anti-spam fee, paid directly to recipient (>= 5000 µT)
|
||||
* Fee = MIN_TX_FEE — blockchain tx fee to the block validator (1000 µT)
|
||||
* Payload = ContactRequestPayload { intro? } as base64 JSON bytes
|
||||
*/
|
||||
export function buildContactRequestTx(params: {
|
||||
from: string; // sender Ed25519 pubkey
|
||||
to: string; // recipient Ed25519 pubkey
|
||||
contactFee: number; // anti-spam amount paid to recipient (>= 5000 µT)
|
||||
intro?: string; // optional plaintext intro message (≤ 280 chars)
|
||||
privKey: string;
|
||||
}): RawTx {
|
||||
const id = newTxID();
|
||||
const timestamp = rfc3339Now();
|
||||
// Payload matches ContactRequestPayload{Intro: "..."} in Go
|
||||
const payloadObj = params.intro ? { intro: params.intro } : {};
|
||||
const payload = strToBase64(JSON.stringify(payloadObj));
|
||||
|
||||
const canonical = txCanonicalBytes({
|
||||
id, type: 'CONTACT_REQUEST', from: params.from, to: params.to,
|
||||
amount: params.contactFee, fee: MIN_TX_FEE, payload, timestamp,
|
||||
});
|
||||
|
||||
return {
|
||||
id, type: 'CONTACT_REQUEST', from: params.from, to: params.to,
|
||||
amount: params.contactFee, fee: MIN_TX_FEE, payload, timestamp,
|
||||
signature: signBase64(canonical, params.privKey),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* ACCEPT_CONTACT transaction.
|
||||
* AcceptContactPayload is an empty struct in Go — no fields needed.
|
||||
*/
|
||||
export function buildAcceptContactTx(params: {
|
||||
from: string; // acceptor Ed25519 pubkey (us — the recipient of the request)
|
||||
to: string; // requester Ed25519 pubkey
|
||||
privKey: string;
|
||||
}): RawTx {
|
||||
const id = newTxID();
|
||||
const timestamp = rfc3339Now();
|
||||
const payload = strToBase64(JSON.stringify({})); // AcceptContactPayload{}
|
||||
|
||||
const canonical = txCanonicalBytes({
|
||||
id, type: 'ACCEPT_CONTACT', from: params.from, to: params.to,
|
||||
amount: 0, fee: MIN_TX_FEE, payload, timestamp,
|
||||
});
|
||||
|
||||
return {
|
||||
id, type: 'ACCEPT_CONTACT', from: params.from, to: params.to,
|
||||
amount: 0, fee: MIN_TX_FEE, payload, timestamp,
|
||||
signature: signBase64(canonical, params.privKey),
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Contract call ────────────────────────────────────────────────────────────
|
||||
|
||||
/** Minimum base fee for CALL_CONTRACT (matches blockchain.MinCallFee). */
|
||||
const MIN_CALL_FEE = 1000;
|
||||
|
||||
/**
|
||||
* CALL_CONTRACT transaction.
|
||||
*
|
||||
* Payload shape (CallContractPayload):
|
||||
* { contract_id, method, args_json?, gas_limit }
|
||||
*
|
||||
* `amount` is the payment attached to the call and made available to the
|
||||
* contract as `tx.Amount`. Whether it's collected depends on the contract
|
||||
* — e.g. username_registry.register requires exactly 10_000 µT. Contracts
|
||||
* that don't need payment should be called with `amount: 0` (default).
|
||||
*
|
||||
* The on-chain tx envelope carries `amount` openly, so the explorer shows
|
||||
* the exact cost of a call rather than hiding it in a contract-internal
|
||||
* debit — this was the UX motivation for this field.
|
||||
*
|
||||
* `fee` is the NETWORK fee paid to the block validator (not the contract).
|
||||
* `gas` costs are additional and billed at the live gas price.
|
||||
*/
|
||||
export function buildCallContractTx(params: {
|
||||
from: string;
|
||||
contractId: string;
|
||||
method: string;
|
||||
args?: unknown[]; // JSON-serializable arguments
|
||||
amount?: number; // µT attached to the call (default 0)
|
||||
gasLimit?: number; // default 1_000_000
|
||||
privKey: string;
|
||||
}): RawTx {
|
||||
const id = newTxID();
|
||||
const timestamp = rfc3339Now();
|
||||
const amount = params.amount ?? 0;
|
||||
|
||||
const argsJson = params.args && params.args.length > 0
|
||||
? JSON.stringify(params.args)
|
||||
: '';
|
||||
|
||||
const payloadObj = {
|
||||
contract_id: params.contractId,
|
||||
method: params.method,
|
||||
args_json: argsJson,
|
||||
gas_limit: params.gasLimit ?? 1_000_000,
|
||||
};
|
||||
const payload = strToBase64(JSON.stringify(payloadObj));
|
||||
|
||||
const canonical = txCanonicalBytes({
|
||||
id, type: 'CALL_CONTRACT', from: params.from, to: '',
|
||||
amount, fee: MIN_CALL_FEE, payload, timestamp,
|
||||
});
|
||||
|
||||
return {
|
||||
id, type: 'CALL_CONTRACT', from: params.from, to: '',
|
||||
amount, fee: MIN_CALL_FEE, payload, timestamp,
|
||||
signature: signBase64(canonical, params.privKey),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Flat registration fee for a username, in µT.
|
||||
*
|
||||
* The native username_registry charges a single flat fee (10 000 µT = 0.01 T)
|
||||
* per register() call regardless of name length, replacing the earlier
|
||||
* length-based formula. Flat pricing is easier to communicate and the
|
||||
* 4-char minimum (enforced both in the client UI and the on-chain contract)
|
||||
* already removes the squatting pressure that tiered pricing mitigated.
|
||||
*/
|
||||
export const USERNAME_REGISTRATION_FEE = 10_000;
|
||||
|
||||
/** Minimum/maximum allowed username length. Match blockchain/native_username.go. */
|
||||
export const MIN_USERNAME_LENGTH = 4;
|
||||
export const MAX_USERNAME_LENGTH = 32;
|
||||
|
||||
/** @deprecated Kept for backward compatibility; always returns the flat fee. */
|
||||
export function usernameRegistrationFee(_name: string): number {
|
||||
return USERNAME_REGISTRATION_FEE;
|
||||
}
|
||||
156
client-app/lib/crypto.ts
Normal file
156
client-app/lib/crypto.ts
Normal file
@@ -0,0 +1,156 @@
|
||||
/**
|
||||
* Cryptographic operations for DChain messenger.
|
||||
*
|
||||
* Ed25519 — transaction signing (via TweetNaCl sign)
|
||||
* X25519 — Diffie-Hellman key exchange for NaCl box
|
||||
* NaCl box — authenticated encryption for relay messages
|
||||
*/
|
||||
|
||||
import nacl from 'tweetnacl';
|
||||
import { decodeUTF8, encodeUTF8 } from 'tweetnacl-util';
|
||||
import { getRandomBytes } from 'expo-crypto';
|
||||
import type { KeyFile } from './types';
|
||||
|
||||
// ─── PRNG ─────────────────────────────────────────────────────────────────────
|
||||
// TweetNaCl looks for window.crypto which doesn't exist in React Native/Hermes.
|
||||
// Wire nacl to expo-crypto which uses the platform's secure RNG natively.
|
||||
nacl.setPRNG((output: Uint8Array, length: number) => {
|
||||
const bytes = getRandomBytes(length);
|
||||
for (let i = 0; i < length; i++) output[i] = bytes[i];
|
||||
});
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
export function hexToBytes(hex: string): Uint8Array {
|
||||
if (hex.length % 2 !== 0) throw new Error('odd hex length');
|
||||
const bytes = new Uint8Array(hex.length / 2);
|
||||
for (let i = 0; i < bytes.length; i++) {
|
||||
bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
export function bytesToHex(bytes: Uint8Array): string {
|
||||
return Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
|
||||
// ─── Key generation ───────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Generate a new identity: Ed25519 signing keys + X25519 encryption keys.
|
||||
* Returns a KeyFile compatible with the Go node format.
|
||||
*/
|
||||
export function generateKeyFile(): KeyFile {
|
||||
// Ed25519 for signing / blockchain identity
|
||||
const signKP = nacl.sign.keyPair();
|
||||
|
||||
// X25519 for NaCl box encryption
|
||||
// nacl.box.keyPair() returns Curve25519 keys
|
||||
const boxKP = nacl.box.keyPair();
|
||||
|
||||
return {
|
||||
pub_key: bytesToHex(signKP.publicKey),
|
||||
priv_key: bytesToHex(signKP.secretKey),
|
||||
x25519_pub: bytesToHex(boxKP.publicKey),
|
||||
x25519_priv: bytesToHex(boxKP.secretKey),
|
||||
};
|
||||
}
|
||||
|
||||
// ─── NaCl box encryption ──────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Encrypt a plaintext message using NaCl box.
|
||||
* Sender uses their X25519 secret key + recipient's X25519 public key.
|
||||
* Returns { nonce, ciphertext } as hex strings.
|
||||
*/
|
||||
export function encryptMessage(
|
||||
plaintext: string,
|
||||
senderSecretHex: string,
|
||||
recipientPubHex: string,
|
||||
): { nonce: string; ciphertext: string } {
|
||||
const nonce = nacl.randomBytes(nacl.box.nonceLength);
|
||||
const message = decodeUTF8(plaintext);
|
||||
const secretKey = hexToBytes(senderSecretHex);
|
||||
const publicKey = hexToBytes(recipientPubHex);
|
||||
|
||||
const box = nacl.box(message, nonce, publicKey, secretKey);
|
||||
return {
|
||||
nonce: bytesToHex(nonce),
|
||||
ciphertext: bytesToHex(box),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypt a NaCl box.
|
||||
* Recipient uses their X25519 secret key + sender's X25519 public key.
|
||||
*/
|
||||
export function decryptMessage(
|
||||
ciphertextHex: string,
|
||||
nonceHex: string,
|
||||
senderPubHex: string,
|
||||
recipientSecHex: string,
|
||||
): string | null {
|
||||
try {
|
||||
const ciphertext = hexToBytes(ciphertextHex);
|
||||
const nonce = hexToBytes(nonceHex);
|
||||
const senderPub = hexToBytes(senderPubHex);
|
||||
const secretKey = hexToBytes(recipientSecHex);
|
||||
|
||||
const plain = nacl.box.open(ciphertext, nonce, senderPub, secretKey);
|
||||
if (!plain) return null;
|
||||
return encodeUTF8(plain);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Ed25519 signing ──────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Sign arbitrary data with the Ed25519 private key.
|
||||
* Returns signature as hex.
|
||||
*/
|
||||
export function sign(data: Uint8Array, privKeyHex: string): string {
|
||||
const secretKey = hexToBytes(privKeyHex);
|
||||
const sig = nacl.sign.detached(data, secretKey);
|
||||
return bytesToHex(sig);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sign arbitrary data with the Ed25519 private key.
|
||||
* Returns signature as base64 — this is the format the Go blockchain node
|
||||
* expects ([]byte fields are base64 in JSON).
|
||||
*/
|
||||
export function signBase64(data: Uint8Array, privKeyHex: string): string {
|
||||
const secretKey = hexToBytes(privKeyHex);
|
||||
const sig = nacl.sign.detached(data, secretKey);
|
||||
return bytesToBase64(sig);
|
||||
}
|
||||
|
||||
/** Encode bytes as base64. Works on Hermes (btoa is available since RN 0.71). */
|
||||
export function bytesToBase64(bytes: Uint8Array): string {
|
||||
let binary = '';
|
||||
for (let i = 0; i < bytes.length; i++) {
|
||||
binary += String.fromCharCode(bytes[i]);
|
||||
}
|
||||
return btoa(binary);
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify an Ed25519 signature.
|
||||
*/
|
||||
export function verify(data: Uint8Array, sigHex: string, pubKeyHex: string): boolean {
|
||||
try {
|
||||
return nacl.sign.detached.verify(data, hexToBytes(sigHex), hexToBytes(pubKeyHex));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Address helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
/** Truncate a long hex address for display: 8...8 */
|
||||
export function shortAddr(hex: string, chars = 8): string {
|
||||
if (hex.length <= chars * 2 + 3) return hex;
|
||||
return `${hex.slice(0, chars)}…${hex.slice(-chars)}`;
|
||||
}
|
||||
101
client-app/lib/storage.ts
Normal file
101
client-app/lib/storage.ts
Normal file
@@ -0,0 +1,101 @@
|
||||
/**
|
||||
* Persistent storage for keys and app settings.
|
||||
* On mobile: expo-secure-store for key material, AsyncStorage for settings.
|
||||
* On web: falls back to localStorage (dev only).
|
||||
*/
|
||||
|
||||
import * as SecureStore from 'expo-secure-store';
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage';
|
||||
import type { KeyFile, Contact, NodeSettings } from './types';
|
||||
|
||||
// ─── Keys ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
const KEYFILE_KEY = 'dchain_keyfile';
|
||||
const CONTACTS_KEY = 'dchain_contacts';
|
||||
const SETTINGS_KEY = 'dchain_settings';
|
||||
const CHATS_KEY = 'dchain_chats';
|
||||
|
||||
/** Save the key file in secure storage (encrypted on device). */
|
||||
export async function saveKeyFile(kf: KeyFile): Promise<void> {
|
||||
await SecureStore.setItemAsync(KEYFILE_KEY, JSON.stringify(kf));
|
||||
}
|
||||
|
||||
/** Load key file. Returns null if not set. */
|
||||
export async function loadKeyFile(): Promise<KeyFile | null> {
|
||||
const raw = await SecureStore.getItemAsync(KEYFILE_KEY);
|
||||
if (!raw) return null;
|
||||
return JSON.parse(raw) as KeyFile;
|
||||
}
|
||||
|
||||
/** Delete key file (logout / factory reset). */
|
||||
export async function deleteKeyFile(): Promise<void> {
|
||||
await SecureStore.deleteItemAsync(KEYFILE_KEY);
|
||||
}
|
||||
|
||||
// ─── Node settings ─────────────────────────────────────────────────────────────
|
||||
|
||||
const DEFAULT_SETTINGS: NodeSettings = {
|
||||
nodeUrl: 'http://localhost:8081',
|
||||
contractId: '',
|
||||
};
|
||||
|
||||
export async function loadSettings(): Promise<NodeSettings> {
|
||||
const raw = await AsyncStorage.getItem(SETTINGS_KEY);
|
||||
if (!raw) return DEFAULT_SETTINGS;
|
||||
return { ...DEFAULT_SETTINGS, ...JSON.parse(raw) };
|
||||
}
|
||||
|
||||
export async function saveSettings(s: Partial<NodeSettings>): Promise<void> {
|
||||
const current = await loadSettings();
|
||||
await AsyncStorage.setItem(SETTINGS_KEY, JSON.stringify({ ...current, ...s }));
|
||||
}
|
||||
|
||||
// ─── Contacts ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export async function loadContacts(): Promise<Contact[]> {
|
||||
const raw = await AsyncStorage.getItem(CONTACTS_KEY);
|
||||
if (!raw) return [];
|
||||
return JSON.parse(raw) as Contact[];
|
||||
}
|
||||
|
||||
export async function saveContact(c: Contact): Promise<void> {
|
||||
const contacts = await loadContacts();
|
||||
const idx = contacts.findIndex(x => x.address === c.address);
|
||||
if (idx >= 0) contacts[idx] = c;
|
||||
else contacts.push(c);
|
||||
await AsyncStorage.setItem(CONTACTS_KEY, JSON.stringify(contacts));
|
||||
}
|
||||
|
||||
export async function deleteContact(address: string): Promise<void> {
|
||||
const contacts = await loadContacts();
|
||||
await AsyncStorage.setItem(
|
||||
CONTACTS_KEY,
|
||||
JSON.stringify(contacts.filter(c => c.address !== address)),
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Message cache (per-chat local store) ────────────────────────────────────
|
||||
|
||||
export interface CachedMessage {
|
||||
id: string;
|
||||
from: string;
|
||||
text: string;
|
||||
timestamp: number;
|
||||
mine: boolean;
|
||||
}
|
||||
|
||||
export async function loadMessages(chatId: string): Promise<CachedMessage[]> {
|
||||
const raw = await AsyncStorage.getItem(`${CHATS_KEY}_${chatId}`);
|
||||
if (!raw) return [];
|
||||
return JSON.parse(raw) as CachedMessage[];
|
||||
}
|
||||
|
||||
export async function appendMessage(chatId: string, msg: CachedMessage): Promise<void> {
|
||||
const msgs = await loadMessages(chatId);
|
||||
// Deduplicate by id
|
||||
if (msgs.find(m => m.id === msg.id)) return;
|
||||
msgs.push(msg);
|
||||
// Keep last 500 messages per chat
|
||||
const trimmed = msgs.slice(-500);
|
||||
await AsyncStorage.setItem(`${CHATS_KEY}_${chatId}`, JSON.stringify(trimmed));
|
||||
}
|
||||
103
client-app/lib/store.ts
Normal file
103
client-app/lib/store.ts
Normal file
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* Global app state via Zustand.
|
||||
* Keeps runtime state; persistent data lives in storage.ts.
|
||||
*/
|
||||
|
||||
import { create } from 'zustand';
|
||||
import type { KeyFile, Contact, Chat, Message, ContactRequest, NodeSettings } from './types';
|
||||
|
||||
interface AppState {
|
||||
// Identity
|
||||
keyFile: KeyFile | null;
|
||||
username: string | null;
|
||||
setKeyFile: (kf: KeyFile | null) => void;
|
||||
setUsername: (u: string | null) => void;
|
||||
|
||||
// Node settings
|
||||
settings: NodeSettings;
|
||||
setSettings: (s: Partial<NodeSettings>) => void;
|
||||
|
||||
// Contacts
|
||||
contacts: Contact[];
|
||||
setContacts: (contacts: Contact[]) => void;
|
||||
upsertContact: (c: Contact) => void;
|
||||
|
||||
// Chats (derived from contacts + messages)
|
||||
chats: Chat[];
|
||||
setChats: (chats: Chat[]) => void;
|
||||
|
||||
// Active chat messages
|
||||
messages: Record<string, Message[]>; // key: contactAddress
|
||||
setMessages: (chatId: string, msgs: Message[]) => void;
|
||||
appendMessage: (chatId: string, msg: Message) => void;
|
||||
|
||||
// Contact requests (pending)
|
||||
requests: ContactRequest[];
|
||||
setRequests: (reqs: ContactRequest[]) => void;
|
||||
|
||||
// Balance
|
||||
balance: number;
|
||||
setBalance: (b: number) => void;
|
||||
|
||||
// Loading / error states
|
||||
loading: boolean;
|
||||
setLoading: (v: boolean) => void;
|
||||
error: string | null;
|
||||
setError: (e: string | null) => void;
|
||||
|
||||
// Nonce cache (to avoid refetching)
|
||||
nonce: number;
|
||||
setNonce: (n: number) => void;
|
||||
}
|
||||
|
||||
export const useStore = create<AppState>((set, get) => ({
|
||||
keyFile: null,
|
||||
username: null,
|
||||
setKeyFile: (kf) => set({ keyFile: kf }),
|
||||
setUsername: (u) => set({ username: u }),
|
||||
|
||||
settings: {
|
||||
nodeUrl: 'http://localhost:8081',
|
||||
contractId: '',
|
||||
},
|
||||
setSettings: (s) => set(state => ({ settings: { ...state.settings, ...s } })),
|
||||
|
||||
contacts: [],
|
||||
setContacts: (contacts) => set({ contacts }),
|
||||
upsertContact: (c) => set(state => {
|
||||
const idx = state.contacts.findIndex(x => x.address === c.address);
|
||||
if (idx >= 0) {
|
||||
const updated = [...state.contacts];
|
||||
updated[idx] = c;
|
||||
return { contacts: updated };
|
||||
}
|
||||
return { contacts: [...state.contacts, c] };
|
||||
}),
|
||||
|
||||
chats: [],
|
||||
setChats: (chats) => set({ chats }),
|
||||
|
||||
messages: {},
|
||||
setMessages: (chatId, msgs) => set(state => ({
|
||||
messages: { ...state.messages, [chatId]: msgs },
|
||||
})),
|
||||
appendMessage: (chatId, msg) => set(state => {
|
||||
const current = state.messages[chatId] ?? [];
|
||||
if (current.find(m => m.id === msg.id)) return {};
|
||||
return { messages: { ...state.messages, [chatId]: [...current, msg] } };
|
||||
}),
|
||||
|
||||
requests: [],
|
||||
setRequests: (reqs) => set({ requests: reqs }),
|
||||
|
||||
balance: 0,
|
||||
setBalance: (b) => set({ balance: b }),
|
||||
|
||||
loading: false,
|
||||
setLoading: (v) => set({ loading: v }),
|
||||
error: null,
|
||||
setError: (e) => set({ error: e }),
|
||||
|
||||
nonce: 0,
|
||||
setNonce: (n) => set({ nonce: n }),
|
||||
}));
|
||||
86
client-app/lib/types.ts
Normal file
86
client-app/lib/types.ts
Normal file
@@ -0,0 +1,86 @@
|
||||
// ─── Key material ────────────────────────────────────────────────────────────
|
||||
|
||||
export interface KeyFile {
|
||||
pub_key: string; // hex Ed25519 public key (32 bytes)
|
||||
priv_key: string; // hex Ed25519 private key (64 bytes)
|
||||
x25519_pub: string; // hex X25519 public key (32 bytes)
|
||||
x25519_priv: string; // hex X25519 private key (32 bytes)
|
||||
}
|
||||
|
||||
// ─── Contact ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface Contact {
|
||||
address: string; // Ed25519 pubkey hex — blockchain address
|
||||
x25519Pub: string; // X25519 pubkey hex — encryption key
|
||||
username?: string; // @name from registry contract
|
||||
alias?: string; // local nickname
|
||||
addedAt: number; // unix ms
|
||||
}
|
||||
|
||||
// ─── Messages ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface Envelope {
|
||||
sender_pub: string; // X25519 hex
|
||||
recipient_pub: string; // X25519 hex
|
||||
nonce: string; // hex 24 bytes
|
||||
ciphertext: string; // hex NaCl box
|
||||
timestamp: number; // unix seconds
|
||||
}
|
||||
|
||||
export interface Message {
|
||||
id: string;
|
||||
from: string; // X25519 pubkey of sender
|
||||
text: string;
|
||||
timestamp: number;
|
||||
mine: boolean;
|
||||
}
|
||||
|
||||
// ─── Chat ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface Chat {
|
||||
contactAddress: string; // Ed25519 pubkey hex
|
||||
contactX25519: string; // X25519 pubkey hex
|
||||
username?: string;
|
||||
alias?: string;
|
||||
lastMessage?: string;
|
||||
lastTime?: number;
|
||||
unread: number;
|
||||
}
|
||||
|
||||
// ─── Contact request ─────────────────────────────────────────────────────────
|
||||
|
||||
export interface ContactRequest {
|
||||
from: string; // Ed25519 pubkey hex
|
||||
x25519Pub: string; // X25519 pubkey hex; empty until fetched from identity
|
||||
username?: string;
|
||||
intro: string; // plaintext intro (stored on-chain)
|
||||
timestamp: number;
|
||||
txHash: string;
|
||||
}
|
||||
|
||||
// ─── Transaction ─────────────────────────────────────────────────────────────
|
||||
|
||||
export interface TxRecord {
|
||||
hash: string;
|
||||
type: string;
|
||||
from: string;
|
||||
to?: string;
|
||||
amount?: number;
|
||||
fee: number;
|
||||
timestamp: number;
|
||||
status: 'confirmed' | 'pending';
|
||||
}
|
||||
|
||||
// ─── Node info ───────────────────────────────────────────────────────────────
|
||||
|
||||
export interface NetStats {
|
||||
total_blocks: number;
|
||||
total_txs: number;
|
||||
peer_count: number;
|
||||
chain_id: string;
|
||||
}
|
||||
|
||||
export interface NodeSettings {
|
||||
nodeUrl: string;
|
||||
contractId: string; // username_registry contract
|
||||
}
|
||||
35
client-app/lib/utils.ts
Normal file
35
client-app/lib/utils.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import { clsx, type ClassValue } from 'clsx';
|
||||
import { twMerge } from 'tailwind-merge';
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
|
||||
/** Format µT amount to human-readable string */
|
||||
export function formatAmount(microTokens: number | undefined | null): string {
|
||||
if (microTokens == null) return '—';
|
||||
if (microTokens >= 1_000_000) return `${(microTokens / 1_000_000).toFixed(2)} T`;
|
||||
if (microTokens >= 1_000) return `${(microTokens / 1_000).toFixed(1)} mT`;
|
||||
return `${microTokens} µT`;
|
||||
}
|
||||
|
||||
/** Format unix seconds to relative time */
|
||||
export function relativeTime(unixSeconds: number | undefined | null): string {
|
||||
if (!unixSeconds) return '';
|
||||
const diff = Date.now() / 1000 - unixSeconds;
|
||||
if (diff < 60) return 'just now';
|
||||
if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
|
||||
if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
|
||||
return new Date(unixSeconds * 1000).toLocaleDateString();
|
||||
}
|
||||
|
||||
/** Format unix seconds to HH:MM */
|
||||
export function formatTime(unixSeconds: number | undefined | null): string {
|
||||
if (!unixSeconds) return '';
|
||||
return new Date(unixSeconds * 1000).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||
}
|
||||
|
||||
/** Generate a random nonce string */
|
||||
export function randomId(): string {
|
||||
return Math.random().toString(36).slice(2) + Date.now().toString(36);
|
||||
}
|
||||
401
client-app/lib/ws.ts
Normal file
401
client-app/lib/ws.ts
Normal file
@@ -0,0 +1,401 @@
|
||||
/**
|
||||
* DChain WebSocket client — replaces balance / inbox / contacts polling with
|
||||
* server-push. Matches `node/ws.go` exactly.
|
||||
*
|
||||
* Usage:
|
||||
* const ws = getWSClient();
|
||||
* ws.connect(); // idempotent
|
||||
* const off = ws.subscribe('addr:ab12…', ev => { ... });
|
||||
* // later:
|
||||
* off(); // unsubscribe + stop handler
|
||||
* ws.disconnect();
|
||||
*
|
||||
* Features:
|
||||
* - Auto-reconnect with exponential backoff (1s → 30s cap).
|
||||
* - Re-subscribes all topics after a reconnect.
|
||||
* - `hello` frame exposes chain_id + tip_height for connection state UI.
|
||||
* - Degrades silently if the endpoint returns 501 (old node without WS).
|
||||
*/
|
||||
|
||||
import { getNodeUrl, onNodeUrlChange } from './api';
|
||||
import { sign } from './crypto';
|
||||
|
||||
export type WSEventName =
|
||||
| 'hello'
|
||||
| 'block'
|
||||
| 'tx'
|
||||
| 'contract_log'
|
||||
| 'inbox'
|
||||
| 'typing'
|
||||
| 'pong'
|
||||
| 'error'
|
||||
| 'subscribed'
|
||||
| 'submit_ack'
|
||||
| 'lag';
|
||||
|
||||
export interface WSFrame {
|
||||
event: WSEventName;
|
||||
data?: unknown;
|
||||
topic?: string;
|
||||
msg?: string;
|
||||
chain_id?: string;
|
||||
tip_height?: number;
|
||||
/** Server-issued nonce in the hello frame; client signs it for auth. */
|
||||
auth_nonce?: string;
|
||||
// submit_ack fields
|
||||
id?: string;
|
||||
status?: 'accepted' | 'rejected';
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
type Handler = (frame: WSFrame) => void;
|
||||
|
||||
class WSClient {
|
||||
private ws: WebSocket | null = null;
|
||||
private url: string | null = null;
|
||||
private reconnectMs: number = 1000;
|
||||
private closing: boolean = false;
|
||||
|
||||
/** topic → set of handlers interested in frames for this topic */
|
||||
private handlers: Map<string, Set<Handler>> = new Map();
|
||||
/** topics we want the server to push — replayed on every reconnect */
|
||||
private wantedTopics: Set<string> = new Set();
|
||||
|
||||
private connectionListeners: Set<(ok: boolean, err?: string) => void> = new Set();
|
||||
private helloInfo: { chainId?: string; tipHeight?: number; authNonce?: string } = {};
|
||||
|
||||
/**
|
||||
* Credentials used for auto-auth on every (re)connect. The signer runs on
|
||||
* each hello frame so scoped subscriptions (addr:*, inbox:*) are accepted.
|
||||
* Without these, subscribe requests to scoped topics get rejected by the
|
||||
* server; global topics (blocks, tx, …) still work unauthenticated.
|
||||
*/
|
||||
private authCreds: { pubKey: string; privKey: string } | null = null;
|
||||
|
||||
/** Current connection state (read-only for UI). */
|
||||
isConnected(): boolean {
|
||||
return this.ws?.readyState === WebSocket.OPEN;
|
||||
}
|
||||
getHelloInfo(): { chainId?: string; tipHeight?: number } {
|
||||
return this.helloInfo;
|
||||
}
|
||||
|
||||
/** Subscribe to a connection-state listener — fires on connect/disconnect. */
|
||||
onConnectionChange(cb: (ok: boolean, err?: string) => void): () => void {
|
||||
this.connectionListeners.add(cb);
|
||||
return () => this.connectionListeners.delete(cb) as unknown as void;
|
||||
}
|
||||
private fireConnectionChange(ok: boolean, err?: string) {
|
||||
for (const cb of this.connectionListeners) {
|
||||
try { cb(ok, err); } catch { /* noop */ }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the Ed25519 keypair used for auto-auth. The signer runs on each
|
||||
* (re)connect against the server-issued nonce so the connection is bound
|
||||
* to this identity. Pass null to disable auth (only global topics will
|
||||
* work — useful for observers).
|
||||
*/
|
||||
setAuthCreds(creds: { pubKey: string; privKey: string } | null): void {
|
||||
this.authCreds = creds;
|
||||
// If we're already connected, kick off auth immediately.
|
||||
if (creds && this.isConnected() && this.helloInfo.authNonce) {
|
||||
this.sendAuth(this.helloInfo.authNonce);
|
||||
}
|
||||
}
|
||||
|
||||
/** Idempotent connect. Call once on app boot. */
|
||||
connect(): void {
|
||||
const base = getNodeUrl();
|
||||
const newURL = base.replace(/^http/, 'ws') + '/api/ws';
|
||||
if (this.ws) {
|
||||
const state = this.ws.readyState;
|
||||
// Already pointing at this URL and connected / connecting — nothing to do.
|
||||
if (this.url === newURL && (state === WebSocket.OPEN || state === WebSocket.CONNECTING)) {
|
||||
return;
|
||||
}
|
||||
// URL changed (operator flipped nodes in settings) — tear down and
|
||||
// re-dial. Existing subscriptions live in wantedTopics and will be
|
||||
// replayed after the new onopen fires.
|
||||
if (this.url !== newURL && (state === WebSocket.OPEN || state === WebSocket.CONNECTING)) {
|
||||
try { this.ws.close(); } catch { /* noop */ }
|
||||
this.ws = null;
|
||||
}
|
||||
}
|
||||
this.closing = false;
|
||||
this.url = newURL;
|
||||
try {
|
||||
this.ws = new WebSocket(this.url);
|
||||
} catch (e: any) {
|
||||
this.fireConnectionChange(false, e?.message ?? 'ws construct failed');
|
||||
this.scheduleReconnect();
|
||||
return;
|
||||
}
|
||||
|
||||
this.ws.onopen = () => {
|
||||
this.reconnectMs = 1000; // reset backoff
|
||||
this.fireConnectionChange(true);
|
||||
// Replay all wanted subscriptions.
|
||||
for (const topic of this.wantedTopics) {
|
||||
this.sendRaw({ op: 'subscribe', topic });
|
||||
}
|
||||
};
|
||||
|
||||
this.ws.onmessage = (ev) => {
|
||||
let frame: WSFrame;
|
||||
try {
|
||||
frame = JSON.parse(typeof ev.data === 'string' ? ev.data : '');
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (frame.event === 'hello') {
|
||||
this.helloInfo = {
|
||||
chainId: frame.chain_id,
|
||||
tipHeight: frame.tip_height,
|
||||
authNonce: frame.auth_nonce,
|
||||
};
|
||||
// Auto-authenticate if credentials are set. The server binds this
|
||||
// connection to the signed pubkey so scoped subscriptions (addr:*,
|
||||
// inbox:*) get through. On reconnect a new nonce is issued, so the
|
||||
// auth dance repeats transparently.
|
||||
if (this.authCreds && frame.auth_nonce) {
|
||||
this.sendAuth(frame.auth_nonce);
|
||||
}
|
||||
}
|
||||
// Dispatch to all handlers for any topic that could match this frame.
|
||||
// We use a simple predicate: look at the frame to decide which topics it
|
||||
// was fanned out to, then fire every matching handler.
|
||||
for (const topic of this.topicsForFrame(frame)) {
|
||||
const set = this.handlers.get(topic);
|
||||
if (!set) continue;
|
||||
for (const h of set) {
|
||||
try { h(frame); } catch (e) { console.warn('[ws] handler error', e); }
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
this.ws.onerror = (e: any) => {
|
||||
this.fireConnectionChange(false, 'ws error');
|
||||
};
|
||||
|
||||
this.ws.onclose = () => {
|
||||
this.ws = null;
|
||||
this.fireConnectionChange(false);
|
||||
if (!this.closing) this.scheduleReconnect();
|
||||
};
|
||||
}
|
||||
|
||||
disconnect(): void {
|
||||
this.closing = true;
|
||||
if (this.ws) {
|
||||
try { this.ws.close(); } catch { /* noop */ }
|
||||
this.ws = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe to a topic. Returns an `off()` function that unsubscribes AND
|
||||
* removes the handler. If multiple callers subscribe to the same topic,
|
||||
* the server is only notified on the first and last caller.
|
||||
*/
|
||||
subscribe(topic: string, handler: Handler): () => void {
|
||||
let set = this.handlers.get(topic);
|
||||
if (!set) {
|
||||
set = new Set();
|
||||
this.handlers.set(topic, set);
|
||||
}
|
||||
set.add(handler);
|
||||
|
||||
// Notify server only on the first handler for this topic.
|
||||
if (!this.wantedTopics.has(topic)) {
|
||||
this.wantedTopics.add(topic);
|
||||
if (this.isConnected()) {
|
||||
this.sendRaw({ op: 'subscribe', topic });
|
||||
} else {
|
||||
this.connect(); // lazy-connect on first subscribe
|
||||
}
|
||||
}
|
||||
|
||||
return () => {
|
||||
const s = this.handlers.get(topic);
|
||||
if (!s) return;
|
||||
s.delete(handler);
|
||||
if (s.size === 0) {
|
||||
this.handlers.delete(topic);
|
||||
this.wantedTopics.delete(topic);
|
||||
if (this.isConnected()) {
|
||||
this.sendRaw({ op: 'unsubscribe', topic });
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** Force a keepalive ping. Useful for debugging. */
|
||||
ping(): void {
|
||||
this.sendRaw({ op: 'ping' });
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a typing indicator to another user. Recipient is their X25519 pubkey
|
||||
* (the one used for inbox encryption). Ephemeral — no ack, no retry; just
|
||||
* fire and forget. Call on each keystroke but throttle to once per 2-3s
|
||||
* at the caller side so we don't flood the WS with frames.
|
||||
*/
|
||||
sendTyping(recipientX25519: string): void {
|
||||
if (!this.isConnected()) return;
|
||||
try {
|
||||
this.ws!.send(JSON.stringify({ op: 'typing', to: recipientX25519 }));
|
||||
} catch { /* best-effort */ }
|
||||
}
|
||||
|
||||
/**
|
||||
* Submit a signed transaction over the WebSocket and resolve once the
|
||||
* server returns a `submit_ack`. Saves the HTTP round-trip on every tx
|
||||
* and gives the UI immediate accept/reject feedback.
|
||||
*
|
||||
* Rejects if:
|
||||
* - WS is not connected (caller should fall back to HTTP)
|
||||
* - Server returns `status: "rejected"` — `reason` is surfaced as error msg
|
||||
* - No ack within `timeoutMs` (default 10 s)
|
||||
*/
|
||||
submitTx(tx: unknown, timeoutMs = 10_000): Promise<{ id: string }> {
|
||||
if (!this.isConnected()) {
|
||||
return Promise.reject(new Error('WS not connected'));
|
||||
}
|
||||
const reqId = 's_' + Date.now() + '_' + Math.random().toString(36).slice(2, 8);
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const off = this.subscribe('$system', (frame) => {
|
||||
if (frame.event !== 'submit_ack' || frame.id !== reqId) return;
|
||||
off();
|
||||
clearTimeout(timer);
|
||||
if (frame.status === 'accepted') {
|
||||
// `msg` carries the server-confirmed tx id.
|
||||
resolve({ id: typeof frame.msg === 'string' ? frame.msg : '' });
|
||||
} else {
|
||||
reject(new Error(frame.reason || 'submit_tx rejected'));
|
||||
}
|
||||
});
|
||||
const timer = setTimeout(() => {
|
||||
off();
|
||||
reject(new Error('submit_tx timeout (' + timeoutMs + 'ms)'));
|
||||
}, timeoutMs);
|
||||
|
||||
try {
|
||||
this.ws!.send(JSON.stringify({ op: 'submit_tx', tx, id: reqId }));
|
||||
} catch (e: any) {
|
||||
off();
|
||||
clearTimeout(timer);
|
||||
reject(new Error('WS send failed: ' + (e?.message ?? 'unknown')));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ── internals ───────────────────────────────────────────────────────────
|
||||
|
||||
private scheduleReconnect(): void {
|
||||
if (this.closing) return;
|
||||
const delay = Math.min(this.reconnectMs, 30_000);
|
||||
this.reconnectMs = Math.min(this.reconnectMs * 2, 30_000);
|
||||
setTimeout(() => {
|
||||
if (!this.closing) this.connect();
|
||||
}, delay);
|
||||
}
|
||||
|
||||
private sendRaw(cmd: { op: string; topic?: string }): void {
|
||||
if (!this.isConnected()) return;
|
||||
try { this.ws!.send(JSON.stringify(cmd)); } catch { /* noop */ }
|
||||
}
|
||||
|
||||
/**
|
||||
* Sign the server nonce with our Ed25519 private key and send the `auth`
|
||||
* op. The server binds this connection to `authCreds.pubKey`; subsequent
|
||||
* subscribe requests to `addr:<pubKey>` / `inbox:<my_x25519>` are accepted.
|
||||
*/
|
||||
private sendAuth(nonce: string): void {
|
||||
if (!this.authCreds || !this.isConnected()) return;
|
||||
try {
|
||||
const bytes = new TextEncoder().encode(nonce);
|
||||
const sig = sign(bytes, this.authCreds.privKey);
|
||||
this.ws!.send(JSON.stringify({
|
||||
op: 'auth',
|
||||
pubkey: this.authCreds.pubKey,
|
||||
sig,
|
||||
}));
|
||||
} catch (e) {
|
||||
console.warn('[ws] auth send failed:', e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Given an incoming frame, enumerate every topic that handlers could have
|
||||
* subscribed to and still be interested. This mirrors the fan-out logic in
|
||||
* node/ws.go:EmitBlock / EmitTx / EmitContractLog.
|
||||
*/
|
||||
private topicsForFrame(frame: WSFrame): string[] {
|
||||
switch (frame.event) {
|
||||
case 'block':
|
||||
return ['blocks'];
|
||||
case 'tx': {
|
||||
const d = frame.data as { from?: string; to?: string } | undefined;
|
||||
const topics = ['tx'];
|
||||
if (d?.from) topics.push('addr:' + d.from);
|
||||
if (d?.to && d.to !== d.from) topics.push('addr:' + d.to);
|
||||
return topics;
|
||||
}
|
||||
case 'contract_log': {
|
||||
const d = frame.data as { contract_id?: string } | undefined;
|
||||
const topics = ['contract_log'];
|
||||
if (d?.contract_id) topics.push('contract:' + d.contract_id);
|
||||
return topics;
|
||||
}
|
||||
case 'inbox': {
|
||||
// Node fans inbox events to `inbox` + `inbox:<recipient_x25519>`;
|
||||
// we mirror that here so both firehose listeners and address-scoped
|
||||
// subscribers see the event.
|
||||
const d = frame.data as { recipient_pub?: string } | undefined;
|
||||
const topics = ['inbox'];
|
||||
if (d?.recipient_pub) topics.push('inbox:' + d.recipient_pub);
|
||||
return topics;
|
||||
}
|
||||
case 'typing': {
|
||||
// Server fans to `typing:<to>` only (the recipient).
|
||||
const d = frame.data as { to?: string } | undefined;
|
||||
return d?.to ? ['typing:' + d.to] : [];
|
||||
}
|
||||
// Control-plane events — no topic fan-out; use a pseudo-topic so UI
|
||||
// can listen for them via subscribe('$system', ...).
|
||||
case 'hello':
|
||||
case 'pong':
|
||||
case 'error':
|
||||
case 'subscribed':
|
||||
case 'submit_ack':
|
||||
case 'lag':
|
||||
return ['$system'];
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let _singleton: WSClient | null = null;
|
||||
|
||||
/**
|
||||
* Return the app-wide WebSocket client. Safe to call from any component;
|
||||
* `.connect()` is idempotent.
|
||||
*
|
||||
* On first creation we register a node-URL listener so flipping the node
|
||||
* in Settings tears down the existing socket and dials the new one — the
|
||||
* user's active subscriptions (addr:*, inbox:*) replay automatically.
|
||||
*/
|
||||
export function getWSClient(): WSClient {
|
||||
if (!_singleton) {
|
||||
_singleton = new WSClient();
|
||||
onNodeUrlChange(() => {
|
||||
// Fire and forget — connect() is idempotent and handles stale URLs.
|
||||
_singleton!.connect();
|
||||
});
|
||||
}
|
||||
return _singleton;
|
||||
}
|
||||
Reference in New Issue
Block a user