diff --git a/README.md b/README.md index 0d0aa817..0011a0f0 100644 --- a/README.md +++ b/README.md @@ -410,3 +410,6 @@ See [CONTRIBUTING.md](./CONTRIBUTING.md) for the full guide. - #1169: Implement query optimization with indexes + + +- #1330: Add SDK pagination support diff --git a/docs/EVENT_CHECKSUM_IMPLEMENTATION.md b/docs/EVENT_CHECKSUM_IMPLEMENTATION.md index c02c871d..885255b5 100644 --- a/docs/EVENT_CHECKSUM_IMPLEMENTATION.md +++ b/docs/EVENT_CHECKSUM_IMPLEMENTATION.md @@ -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. diff --git a/docs/PERFORMANCE_TUNING.md b/docs/PERFORMANCE_TUNING.md index 24d454cb..0c402a29 100644 --- a/docs/PERFORMANCE_TUNING.md +++ b/docs/PERFORMANCE_TUNING.md @@ -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) --- @@ -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 … */ diff --git a/docs/SIGNING_VAULT.md b/docs/SIGNING_VAULT.md index 9eec38b9..197f4db4 100644 --- a/docs/SIGNING_VAULT.md +++ b/docs/SIGNING_VAULT.md @@ -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 @@ -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 diff --git a/examples/batch-payments.ts b/examples/batch-payments.ts index f6d2aae6..7c372704 100644 --- a/examples/batch-payments.ts +++ b/examples/batch-payments.ts @@ -52,6 +52,8 @@ interface BatchProcessorOptions { batchSize: number; maxRetries: number; retryDelayMs: number; + /** Maximum number of batches executed in parallel (bounded to avoid deadlocks). */ + concurrency?: number; } /** @@ -98,43 +100,70 @@ function validateBatch( /** * Executes a batch with per-operation retry and graceful error handling. + * Operations within a batch run in parallel since they are independent. */ async function executeBatch( batch: BatchOperation[], execute: (op: BatchOperation) => Promise, options: BatchProcessorOptions, ): Promise[]> { - const results: BatchResult[] = []; - for (const op of batch) { - let attempts = 0; - let lastError: unknown; - let succeeded = false; - let value: T | undefined; - while (attempts <= options.maxRetries && !succeeded) { - attempts += 1; - try { - value = await execute(op); - succeeded = true; - } catch (err) { - lastError = err; - if (attempts <= options.maxRetries) { - await new Promise((resolve) => setTimeout(resolve, options.retryDelayMs)); + return Promise.all( + batch.map(async (op): Promise> => { + let attempts = 0; + let lastError: unknown; + let succeeded = false; + let value: T | undefined; + while (attempts <= options.maxRetries && !succeeded) { + attempts += 1; + try { + value = await execute(op); + succeeded = true; + } catch (err) { + lastError = err; + if (attempts <= options.maxRetries) { + await new Promise((resolve) => setTimeout(resolve, options.retryDelayMs)); + } } } + return { + id: op.id, + success: succeeded, + value, + error: succeeded ? undefined : lastError instanceof Error ? lastError.message : String(lastError), + attempts, + }; + }), + ); +} + +/** + * Runs tasks with a bounded concurrency limit, preserving input order. + * Bounding concurrency prevents unbounded fan-out and deadlocks. + */ +async function runWithConcurrency( + items: T[], + limit: number, + worker: (item: T, index: number) => Promise, +): Promise { + const results: R[] = new Array(items.length); + let nextIndex = 0; + const workerCount = Math.max(1, Math.min(limit, items.length)); + const runners = Array.from({ length: workerCount }, async () => { + while (true) { + const current = nextIndex++; + if (current >= items.length) { + return; + } + results[current] = await worker(items[current], current); } - results.push({ - id: op.id, - success: succeeded, - value, - error: succeeded ? undefined : lastError instanceof Error ? lastError.message : String(lastError), - attempts, - }); - } + }); + await Promise.all(runners); return results; } /** * Processes all operations in batches, collecting analytics across the run. + * Batches are validated up front, then executed with bounded parallelism. */ async function processBatches( operations: BatchOperation[], @@ -144,14 +173,18 @@ async function processBatches( ): Promise<{ results: BatchResult[]; analytics: BatchAnalytics }> { const startedAt = Date.now(); const batches = chunkOperations(operations, options.batchSize); - const results: BatchResult[] = []; + // Validate all batches before executing any, so invalid input fails fast. for (const batch of batches) { validateBatch(batch, validate); - const batchResults = await executeBatch(batch, execute, options); - results.push(...batchResults); } + const concurrency = options.concurrency ?? 4; + const batchResults = await runWithConcurrency(batches, concurrency, (batch) => + executeBatch(batch, execute, options), + ); + const results: BatchResult[] = batchResults.flat(); + const analytics: BatchAnalytics = { totalOperations: operations.length, totalBatches: batches.length, @@ -230,6 +263,7 @@ async function main() { batchSize: 10, maxRetries: 2, retryDelayMs: 100, + concurrency: 4, }; const { results, analytics } = await processBatches( @@ -249,31 +283,28 @@ async function main() { console.log(" Submitting atomic batch payment transaction..."); for (const res of results) { if (res.success && res.value) { - console.log(` ✓ Payment to ${res.value.invoiceId} confirmed: ${res.value.txHash} (${formatAmount(res.value.amount)} USDC)`); + console.log(` ✓ Payment to ${res.value.invoiceId} confirmed: ${formatAmount(res.value.amount)} USDC (attempts: ${res.attempts})`); } else { console.log(` ✗ Payment to ${res.id} failed after ${res.attempts} attempt(s): ${res.error}`); } } console.log(); - // Step 4: Verification and Reconciliation - console.log("4. Verifying Batch Integrity:"); - const allSucceeded = results.every((r) => r.success); - console.log(` Batch status: ${allSucceeded ? "ALL PAYMENTS CONFIRMED" : "PARTIAL FAILURE DETECTED"}`); - - const totalDisbursed = results.reduce((sum, r) => sum + (r.value?.amount ?? 0n), 0n); - console.log(` Total Disbursed: ${formatAmount(totalDisbursed)} USDC`); + console.log("4. Batch Analytics:"); + console.log(` Total operations : ${analytics.totalOperations}`); + console.log(` Total batches : ${analytics.totalBatches}`); + console.log(` Succeeded : ${analytics.succeeded}`); + console.log(` Failed : ${analytics.failed}`); + console.log(` Retried : ${analytics.retried}`); + console.log(` Duration : ${analytics.durationMs}ms`); + console.log(); - console.log("5. Batch Analytics:"); - console.log(` Batches: ${analytics.totalBatches} | Operations: ${analytics.totalOperations}`); - console.log(` Succeeded: ${analytics.succeeded} | Failed: ${analytics.failed} | Retried: ${analytics.retried}`); - console.log(` Duration: ${analytics.durationMs}ms`); console.log("=================================================================="); - console.log(" ✓ Batch Payment application completed successfully."); + console.log(" Batch processing complete."); console.log("=================================================================="); } main().catch((err) => { - console.error("Batch payment failed:", err); + console.error("Batch payments example failed:", err); process.exit(1); });