Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 4 additions & 5 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,11 +108,10 @@ Two cheap checks before assuming a token problem:
401s for the same session, the code validated fine and the failure is
downstream of this service.

**Do not use `notifications` as that canary.** It falls back to a
body-supplied `user` when validation fails, and overrides even a validated
username with that field whenever it is present. It can therefore answer
happily for a request whose code was rejected, which tells you nothing about
validation and actively misleads.
`notifications` also 401s without a valid code. With a valid code, a body
`user` naming another account is still served (the restricted feed, for
Decks columns), so only use it as the canary for a request without `user` or
naming the session's own account.
- **Check the failure rate.** A token or session problem affects a subset of
users; a backend gate that is misconfigured fails for everyone. An endpoint at
100% 401 while its siblings are at 100% success is not an authentication bug
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ docker run -it --rm -p 4000:4000 \
| `BLOCKSTREAM_CLIENT_ID` / `BLOCKSTREAM_CLIENT_SECRET` | optional Blockstream Enterprise esplora auth (BTC fallback) |
| `HELIUS_API_KEY` | optional Helius API key added as an extra Solana RPC fallback |
| `ETH_RPC_URLS` / `BNB_RPC_URLS` / `SOL_RPC_URLS` / `BTC_ESPLORA_URLS` | optional comma-separated endpoint lists overriding the built-in chain provider pools |
| `PUBLIC_DIR` | static assets directory (default `<app>/public`) |
| `Logging__LogLevel__Default` | log level (default `Warning`; set `Information` for per-request logs) |
| `SSR_INTERNAL_SECRET` | shared header secret that switches on the internal SSR RPC cache routes (`/private-api/ssr/*`); unset = they answer like unknown routes |
| `SSR_CACHE_BYTES` | byte budget of the SSR RPC cache, LRU beyond it (default 512 MiB) |
Expand Down
9 changes: 0 additions & 9 deletions dotnet/EcencyApi/Config.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,6 @@ public static class Config
public static string PrivateApiAuth { get; } =
Env("PRIVATE_API_AUTH") ?? "privateapiauth";

/// <summary>
/// Shared secret presented to enotify to unlock a user's complete notification feed.
/// enotify has no authentication of its own and defaults to chain-derived activity
/// only, so without this a self-view silently loses favorites, bookmarks, Points
/// transfers and the aggregates. Must match [APP] INTERNAL_TOKEN there.
/// </summary>
public static string EnotifyInternalToken { get; } =
Env("ENOTIFY_INTERNAL_TOKEN") ?? "";

/// <summary>
/// Shared secret presented to the curation desk backend on every desk call,
/// public reads included: the desk answers only requests that carry it, so
Expand Down
14 changes: 3 additions & 11 deletions dotnet/EcencyApi/Handlers/PrivateApi.UserData1.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,6 @@ public static bool IsOwnDeviceRequest(string? validatedUsername, string? request
internal static Func<string, HttpMethod, JsonNode?, Task<UpstreamResponse>> DeviceUpstream =
(endpoint, method, payload) => ApiClient.ApiRequest(endpoint, method, null, payload);

/// <summary>Header enotify reads the shared secret from.</summary>
public const string EnotifyInternalTokenHeader = "X-Ecency-Internal-Token";

/// <summary>
/// Upstream path for the notifications feed, or null when a value cannot be
/// expressed as a single path segment.
Expand Down Expand Up @@ -143,14 +140,9 @@ await ValidateCode(body),
return;
}

// The secret rides alongside scope=full. enotify honours the parameter only when
// the header matches, and fails closed otherwise, so a missing or wrong token
// costs this user their own private activity rather than exposing anyone else's.
var extraHeaders = fullScope && Config.EnotifyInternalToken.Length > 0
? new[] { new KeyValuePair<string, string>(EnotifyInternalTokenHeader, Config.EnotifyInternalToken) }
: null;

await Upstream.Pipe(ApiClient.ApiRequest(u, HttpMethod.Get, extraHeaders), ctx);
// enotify honours scope=full only for a request arriving from the private-API
// gateway's private address, and fails closed to the chain-derived feed otherwise.
await Upstream.Pipe(ApiClient.ApiRequest(u, HttpMethod.Get), ctx);
}

// GET ^/private-api/pub-notifications/:username
Expand Down
59 changes: 39 additions & 20 deletions dotnet/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,22 +20,26 @@ win is a faster, more predictable proxy under concurrent load.
dotnet/
EcencyApi/ the service
Program.cs host, middleware, static files, error handler
Config.cs mirror of src/config.ts (same env vars + defaults)
Config.cs env-var configuration (started as a mirror of src/config.ts)
Handlers/
Routes.cs 1:1 map of src/server/index.tsx route table
SearchApi.cs search-api.ts
AuthApi.cs auth-api.ts (HiveSigner code create/refresh)
PrivateApi.*.cs private-api.ts, split by concern
WalletApi.*.cs wallet-api.ts (market helpers, portfolio layers, engine)
SsrRpc.cs internal SSR RPC read cache (/private-api/ssr/*)
Announcements.cs / Spotlights.cs / HiveExplorer.cs / Constants.cs / ChainProviders.cs
Infrastructure/
Upstream.cs axios baseApiRequest + Express pipe() parity
ApiClient.cs helper.ts apiRequest (PRIVATE_API_AUTH header injection)
NodeHealthTracker.cs per-node health state + pool ordering (see below)
HiveRpcClient.cs dhive-style Client with node failover (see below)
EngineRpcClient.cs Hive-Engine RPC with the same failover
ServerErrors.cs 500/503 error responses
HiveCrypto.cs dhive crypto: key-from-login, canonical ECDSA, recovery
JsJson.cs JS-identical JSON.stringify (for signed messages)
JsVal.cs JS parseFloat / Number / typeof coercions
B64u.cs, MemCache.cs, HttpContextExtensions.cs
B64u.cs, MemCache.cs, BytesCache.cs, HttpContextExtensions.cs, ...
Models/HiveEngine.cs hiveEngine.types.ts + converters.ts
EcencyApi.Tests/ xUnit: crypto golden vectors, failover, JS semantics
parity/ differential HTTP parity harness (Node vs C#)
Expand All @@ -57,28 +61,41 @@ failover with a health tracker adopted from the vision-web SDK's
without a throttle). Parked nodes sort last but remain a final resort.
- **Recent failures deprioritize** (30s window) — one bad response moves
traffic away without banning the node; it re-enters when the window lapses.
- **Latency EWMA ranking** (alpha 0.3, trusted after 3 samples, stale after
5 min): a proven-slow node (>1s) is demoted behind unexplored nodes; config
order breaks ties so cold start behaves like the configured list.
- **Repeated failures park a node that is not answering**: 3 failures in a row
park it for 30s, doubling to 120s, but only when it has never succeeded or its
failure-rate EWMA (alpha 0.1) is at least 50%, so a node that is usually
healthy rides out a short burst. A parked node is not tried while any other
node is available; a success clears the streak.
- **Latency EWMA ranking per call class** (`CallClass.Cheap` point reads vs
`CallClass.Heavy` feed-shaped queries, each with its own profile; alpha 0.3,
trusted after 3 samples, stale after 5 min): a proven-slow node (>1s) is
demoted behind unexplored nodes; config order breaks ties so cold start behaves like the configured list.
- **Overload responses** (429/502/503/504) advance to the next node
immediately — no wasted local retry on a throttled node.
- **RPC-level errors** (a JSON `error` field) surface without failover — an
application error, not an unhealthy node (matches dhive).
- **Result shape is validated** by the typed helpers (`get_accounts` must be an
array, `get_dynamic_global_properties` an object): a 200 with no usable
result is a node failure and fails over.

`EngineRpcClient` applies the same tracker to the Hive-Engine `/contracts` and
history pools.

Not adopted from the SDK (overkill at proxy call rates, documented for later:
request hedging, per-API failure profiles, head-block staleness checks).
request hedging, head-block staleness checks).

The chain-balance providers (`ChainProviders.cs` / `PrivateApi.Chain.cs`) have
their own equivalent provider-pool failover for the EVM/Solana/BTC endpoints.

Covered by `EcencyApi.Tests/HiveRpcFailoverTests.cs` (rate-limit parking,
failure deprioritization, timeout rollover, EWMA demotion, all-down error).
failure deprioritization, timeout rollover, EWMA demotion, all-down error) and
`EngineFailoverTests.cs`.

## Verifying identical responses

Two layers of verification:

**1. Unit tests** (`dotnet test`, 40 tests):
**1. Unit tests** (`dotnet test`):
- Crypto is checked **byte-for-byte against dhive**. `tools/gen-vectors.js` runs
the exact `@hiveio/dhive` the Node service uses and emits golden vectors
(key-from-login, canonical ECDSA signatures, public-key recovery, the full
Expand All @@ -88,7 +105,7 @@ Two layers of verification:
`parseFloat("")` is `NaN`, etc.) that the wallet numeric parity depends on.
- `HiveRpcFailoverTests` exercise the failover against local stub nodes.

**2. Differential HTTP parity** (`parity/`): fires an identical catalog of 301
**2. Differential HTTP parity** (`parity/`): fires an identical catalog of
request variants (every route × empty/populated/bad-auth bodies, plus error and
fallback probes) at the running Node image and the C# build, then diffs status,
content-type, and body.
Expand All @@ -115,8 +132,9 @@ python3 parity/driver.py run csharp http://127.0.0.1:14001
python3 parity/driver.py diff node csharp node2
```

Latest result: **0 unexplained mismatches / 301 cases** (the intentional
divergences listed above are recorded in the harness). A handful of cases compare "loose"
Result at the migration cutover: **0 unexplained mismatches / 301 cases** (the
intentional divergences listed below are recorded in the harness). The catalog
has grown with the route table since. A handful of cases compare "loose"
(status + content-type only) because they are inherently nondeterministic —
timestamped HiveSigner tokens, random promoted-entry shuffles, and live
portfolio data. The full `portfolio-v2` aggregation was additionally compared
Expand Down Expand Up @@ -166,8 +184,9 @@ same CPU budget**.
`:permlink` route params their POST routes never declared, so they always
queried `undefined/undefined` upstream.

All three are recorded in the parity harness (`KNOWN_DIVERGENCES` /
route-table-driven catalog).
All three are recorded in the parity harness's `KNOWN_DIVERGENCES`, together
with every later intentional change (mostly routes added after the port, which
the Node reference answers as unknown).

## Remaining edges (low-risk, documented)

Expand Down Expand Up @@ -198,13 +217,14 @@ Run from this `dotnet/` directory:

```bash
dotnet build EcencyApi/EcencyApi.csproj # compile
dotnet test EcencyApi.Tests/EcencyApi.Tests.csproj # 40 tests: crypto vectors, failover, JS semantics
dotnet test EcencyApi.Tests/EcencyApi.Tests.csproj # crypto vectors, failover, JS semantics, handlers
```

### Run locally

Configuration comes entirely from environment variables — the same set, with
the same defaults, as the Node service (`Config.cs` mirrors `src/config.ts`):
Configuration comes entirely from environment variables. The variables the
Node service had keep its names and defaults. This table covers the common
ones; the root `README.md` has the complete list:

| variable | purpose | default |
|---|---|---|
Expand Down Expand Up @@ -255,9 +275,8 @@ docker run -d --name vapi-csharp -p 4000:4000 \
ecency/api-csharp
```

For swarm, `docker-compose.yml` in this directory is a drop-in equivalent of
the repo-root stack file (same service shape, ports, env list, and deploy
policy) pointing at the C# image.
For swarm, `docker-compose.yml` in this directory is the stack file (see the
root `README.md`).

### Deployment tags & rollback

Expand Down Expand Up @@ -286,7 +305,7 @@ API_PORT=4000 ... dotnet /opt/vapi-csharp/EcencyApi.dll

### Regenerate crypto golden vectors

Only needed if the dhive dependency of the Node service changes:
Only needed to refresh the vectors against a different dhive version:

```bash
# the repo no longer carries Node dependencies; install the two packages anywhere
Expand Down
6 changes: 4 additions & 2 deletions dotnet/parity/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@ whole route surface.
- `mock_upstream.py` — a stub for every upstream (private API, search, chain
RPC/esplora) that records each proxied request and returns deterministic
bodies, so both services observe identical upstreams.
- `driver.py` — generates a catalog of 305 request variants from the Express
route table (`src/server/index.tsx`), fires it at a target, and diffs two runs.
- `driver.py` — generates the request catalog from the C# route table
(`EcencyApi/Handlers/Routes.cs`; `VAPI_ROUTES_CS` overrides it, `VAPI_INDEX_TSX`
points it at a legacy Express `index.tsx`), fires it at a target, and diffs two
runs. `python3 driver.py catalog` shows the current cases.

```bash
python3 driver.py catalog # inspect the generated cases
Expand Down
Loading