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
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.
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
111 changes: 71 additions & 40 deletions examples/batch-payments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/**
Expand Down Expand Up @@ -98,43 +100,70 @@ function validateBatch<T>(

/**
* 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<T>(
batch: BatchOperation<T>[],
execute: (op: BatchOperation<T>) => Promise<T>,
options: BatchProcessorOptions,
): Promise<BatchResult<T>[]> {
const results: BatchResult<T>[] = [];
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<BatchResult<T>> => {
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<T, R>(
items: T[],
limit: number,
worker: (item: T, index: number) => Promise<R>,
): Promise<R[]> {
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<T>(
operations: BatchOperation<T>[],
Expand All @@ -144,14 +173,18 @@ async function processBatches<T>(
): Promise<{ results: BatchResult<T>[]; analytics: BatchAnalytics }> {
const startedAt = Date.now();
const batches = chunkOperations(operations, options.batchSize);
const results: BatchResult<T>[] = [];

// 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<T>[] = batchResults.flat();

const analytics: BatchAnalytics = {
totalOperations: operations.length,
totalBatches: batches.length,
Expand Down Expand Up @@ -230,6 +263,7 @@ async function main() {
batchSize: 10,
maxRetries: 2,
retryDelayMs: 100,
concurrency: 4,
};

const { results, analytics } = await processBatches(
Expand All @@ -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);
});