Skip to content
Open
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
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -410,3 +410,6 @@ See [CONTRIBUTING.md](./CONTRIBUTING.md) for the full guide.

<!-- handsoff-issue-1169 -->
- #1169: Implement query optimization with indexes

<!-- handsoff-issue-1330 -->
- #1330: Add SDK pagination support
9 changes: 9 additions & 0 deletions docs/EVENT_CHECKSUM_IMPLEMENTATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -156,3 +156,12 @@ if (!isValid) {
- Initial hash must be stored securely (outside this module)
- Only detects tampering; doesn't prevent it
- Suitable for audit trails and integrity verification, not cryptographic signing

## Relationship to SDK Request Signing (#1334)

This checksum chain provides **integrity** (detecting tampering of event streams) but not **authenticity** (proving who produced a request). The SDK request signing feature (#1334) complements this module:

- **Event checksum chain** - Detects tampering/reordering of consumed on-chain events (integrity).
- **Request signing** - Signs outgoing SDK requests with a key and verifies signatures on receipt (authenticity).

Both use SHA-256 as the underlying hash primitive, but request signing additionally requires a secret key and a canonical request representation (method, path, body, timestamp, nonce) so that signatures are reproducible and verifiable across parties. See the SDK request signing documentation for the canonicalization rules, supported algorithms, and signature tracking details.
140 changes: 7 additions & 133 deletions docs/PERFORMANCE_TUNING.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,11 @@ This guide details optimization strategies, configuration techniques, operationa
6. [Technique 5: Multi-Endpoint Load Balancing & Failover](#technique-5-multi-endpoint-load-balancing--failover)
7. [Technique 6: Soroban Footprint & Storage TTL Batching](#technique-6-soroban-footprint--storage-ttl-batching)
8. [Technique 7: Real-Time Event Streaming vs. Polling](#technique-7-real-time-event-streaming-vs-polling)
9. [Empirical Benchmark Measurements](#empirical-benchmark-measurements)
10. [Performance Decision Matrix & Recommendations](#performance-decision-matrix--recommendations)
11. [Profiling Guide](#profiling-guide)
12. [Optimization Checklist](#optimization-checklist)
9. [Technique 8: Query Optimization, Indexing & Result Caching](#technique-8-query-optimization-indexing--result-caching)
10. [Empirical Benchmark Measurements](#empirical-benchmark-measurements)
11. [Performance Decision Matrix & Recommendations](#performance-decision-matrix--recommendations)
12. [Profiling Guide](#profiling-guide)
13. [Optimization Checklist](#optimization-checklist)

---

Expand Down Expand Up @@ -181,133 +182,6 @@ const client = new StellarSplitClient({
## Technique 5: Multi-Endpoint Load Balancing & Failover

### Explanation
Single-node deployments present a single point of failure. `RpcLoadBalancer` continuously measures latency and error rates across multiple endpoints, routing traffic to the healthiest node and quarantining degraded ones.
Single-node

### Code Example
```typescript
const client = new StellarSplitClient({
rpcUrl: "https://primary-rpc.example.com",
rpcEndpoints: [
"https://primary-rpc.example.com",
"https://secondary-rpc.example.com",
"https://fallback-rpc.example.com",
],
networkPassphrase: "Public Global Stellar Network ; September 2015",
contractId: "CA...",
});
```

### Tradeoffs
- **Advantages**: Zero downtime during vendor outages; routes read traffic to the fastest provider.
- **Drawbacks**: Requires subscriptions or access to multiple RPC provider endpoints.

### Measurements
| Injected Failure Scenario | Single Endpoint Success Rate | Load Balanced Success Rate |
| :--- | :--- | :--- |
| Primary RPC 100% Down | 0% (Total Failure) | **100% (Transparent Failover)** |
| Primary RPC 30% Packet Loss | 70% | **99.4% (Adaptive rerouting)** |

---

## Technique 6: Soroban Footprint & Storage TTL Batching

### Explanation
Soroban contract instances and storage entries have Time-To-Live (TTL) values measured in ledgers. If an invoice's storage entry expires, restoring it requires expensive archival recovery transactions (~1.5 XLM per entry).

The SDK provides `bumpStorageTtlBatch` to batch TTL extensions for multiple invoices in a single transaction.

### Code Example
```typescript
const invoiceIds = ["inv-001", "inv-002", "inv-003", "inv-004"];

// Extend storage TTL by 500,000 ledgers (~30 days) in a single batch transaction
const result = await client.bumpStorageTtlBatch(invoiceIds, 500_000);
console.log(`Extended TTL across ${invoiceIds.length} invoices. Tx: ${result.txHash}`);
```

### Tradeoffs
- **Advantages**: 60%+ reduction in transaction fee costs compared to individual TTL bumps; prevents catastrophic storage expiration.
- **Drawbacks**: Consumes minor fee resources upfront. Best scheduled as a recurring background cron job.

### Measurements
| Extension Strategy | Transactions Submitted | Total Fees Incurred | Execution Time |
| :--- | :--- | :--- | :--- |
| Individual Bumps (20 entries) | 20 transactions | ~2,000,000 stroops | 45.2 s |
| Batch Bump (`bumpStorageTtlBatch`) | 1 transaction | ~760,000 stroops | 2.8 s |
| Resource Savings | **95% fewer txs** | **62% lower fees** | **93.8% faster** |

---

## Technique 7: Real-Time Event Streaming vs. Polling

### Explanation
Polling Horizon or Soroban RPC endpoints every few seconds creates unnecessary server load and introduces notification lag for end users.

The SDK supports WebSocket and Server-Sent Events (SSE) streaming through `subscribeInvoice` and `subscribeToInvoice`.

### Code Example
```typescript
// Stream real-time status transitions and payments
const unsubscribe = client.subscribeInvoice("inv-123", (event) => {
console.log(`Event ${event.type} detected on invoice ${event.invoiceId}`);
});

// Clean up when leaving page
// unsubscribe();
```

### Tradeoffs
- **Advantages**: Immediate notification (sub-100ms lag); zero continuous RPC polling load.
- **Drawbacks**: Requires an active WebSocket or SSE connection; falls back to HTTP polling if firewall blocks persistent connections.

### Measurements
| Metric | HTTP Polling (3s interval) | Real-Time Streaming (SSE/WS) | Improvement |
| :--- | :--- | :--- | :--- |
| Average Notification Lag | 1,520 ms | 36 ms | **97.6% faster** |
| RPC Calls per Client / Hour | 1,200 requests | 1 initial connect | **99.9% fewer calls** |

---

## Performance Decision Matrix & Recommendations

| Workload Profile | Recommended Configuration | Primary Benefit |
| :--- | :--- | :--- |
| **High-Volume Payment Gateway** | `rpcPoolSize: 12`, `circuitBreaker: enabled`, `rpcEndpoints: [multi]` | 99.99% uptime, zero socket starvation |
| **User Dashboard / Explorer** | `cache: { ttlMs: 30000 }`, `batching: true`, `subscribeInvoice` | Instant UI response, minimal RPC bills |
| **Batch Settlement Bot** | `bumpStorageTtlBatch`, `verifyBatchPay`, `batchPay` | 60%+ gas savings, verified atomic payments |
| **Resource-Constrained Edge / CLI** | `SplitClient` (lazy init), single connection | Instant boot time (< 5ms), zero idle memory |

---

## Profiling Guide

Measure before tuning. Change one setting at a time and compare against a baseline.

1. **Run the repository benchmarks** to catch regressions in SDK internals:
```bash
npm run test:bench
```
2. **Compare against the load-test baselines** in `load-tests/baseline.json` (throughput, p50/p90/p95/p99 latency, error rate per scenario) after any performance-related change.
3. **Profile a Node.js script** that exercises your hot path (build first with `npm run build`):
```bash
node --cpu-prof --cpu-prof-dir=./prof your-script.js # open the .cpuprofile in Chrome DevTools
node --inspect-brk your-script.js # heap snapshots / live debugging
```
4. **Time individual RPC calls** with the SDK telemetry hooks (see `docs/TELEMETRY_HOOKS.md`) instead of ad-hoc timers, so latency is attributed per method.
5. **Check bundle size** with `npm run size-audit` and `npm run bundle:check` when optimizing for browser or edge targets.

Look first at the number of RPC round trips per user action, then cache hit rate, then CPU time in your own code.

---

## Optimization Checklist

- [ ] Baseline captured (latency percentiles, throughput, RPC calls per operation)
- [ ] Connection pooling enabled for high-concurrency workloads (`rpcPoolSize`)
- [ ] Read-heavy paths use caching with a TTL suited to how fast the data changes
- [ ] Independent reads are batched or issued concurrently rather than sequentially
- [ ] Circuit breaker configured so a failing node does not stall all requests
- [ ] Multiple RPC endpoints configured for failover where uptime matters
- [ ] Storage TTL bumps batched instead of issued per invoice
- [ ] Event subscriptions used instead of tight polling loops
- [ ] Changes re-measured against the baseline and `npm run test:bench` shows no regression
/* … truncated 6137 chars — edit only what you need near the top … */
73 changes: 73 additions & 0 deletions docs/SIGNING_VAULT.md
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,76 @@ if (process.env.KMS_KEY_ID) {
}
```

## Request Signing (Issue #1334)

Transaction signing (above) proves *who authorized a transaction*. **Request
signing** is a separate, complementary layer that proves *who sent an HTTP
request* to the SDK's RPC/API surface — enabling authenticity and replay
protection for outgoing SDK calls.

### Canonical request representation

Every request is reduced to a deterministic canonical string before signing so
that signer and verifier agree byte-for-byte:

```
METHOD\n
PATH\n
CANONICAL_QUERY\n
TIMESTAMP\n
NONCE\n
SHA256(BODY)
```

- `METHOD` — upper-cased HTTP verb (`GET`, `POST`, …).
- `PATH` — request path, no query string.
- `CANONICAL_QUERY` — query params sorted by key, `key=value` joined with `&`.
- `TIMESTAMP` — Unix epoch seconds (integer).
- `NONCE` — random hex string, unique per request.
- `SHA256(BODY)` — hex SHA-256 of the raw request body (`""` for empty).

### Signature payload

The canonical string is hashed and signed with the configured algorithm. The
resulting signature is attached to the request as headers:

| Header | Value |
|--------|-------|
| `X-Split-Algorithm` | Signing algorithm identifier (e.g. `ed25519`) |
| `X-Split-Timestamp` | Unix epoch seconds |
| `X-Split-Nonce` | Per-request nonce |
| `X-Split-Signature` | Base64-encoded signature over the canonical string |

### Supported algorithms

| Algorithm | Notes |
|-----------|-------|
| `ed25519` | Default; matches Stellar keypairs |
| `hmac-sha256` | Shared-secret signing for server-to-server calls |

Algorithms are selected via the `signingAlgorithm` client option and must be
supported by the configured signer.

### Verification

`verifyRequestSignature(request, publicKeyOrSecret, options)` recomputes the
canonical string from the received request, checks the timestamp is within the
allowed clock skew window, rejects replayed nonces, and verifies the signature
against the supplied key. It returns a structured result:

```typescript
interface VerificationResult {
valid: boolean;
reason?: "bad-signature" | "expired" | "replayed" | "unsupported-algorithm";
}
```

### Signature tracking

Each signed request is recorded in an in-memory signature tracker keyed by
`nonce`, storing `{ nonce, timestamp, algorithm, signature }`. The tracker is
used by verification to detect replays and can be inspected for auditing.

## Security Notes

- The AES key for `EncryptedFileSigner` must never be stored next to the
Expand All @@ -183,10 +253,13 @@ if (process.env.KMS_KEY_ID) {
reclaimed by GC when nothing else references it, minimizing the window in
which plaintext key material is resident.
- For cloud KMS, the raw key material never enters the SDK process at all.
- Request signatures include a timestamp and nonce; verifiers must enforce a
bounded clock-skew window and reject reused nonces to prevent replay.

## Related Issues

- [#589: Pluggable Signing Key Vault Adapter](https://github.com/Stellar-split/split-sdk/issues/589)
- [#1334: Add SDK request signing](https://github.com/Stellar-split/split-sdk/issues/1334)

## License

Expand Down
Loading