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/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); });