@psavelis/enterprise-blockchain 1.1.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/README.md +322 -50
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  Production-grade TypeScript modules for recursive STARK settlement, post-quantum cryptography (ML-KEM/ML-DSA), MPC, HSM, and multi-rail (Solana + Bitcoin + fiat) infrastructure.
4
4
 
5
5
  [![npm version](https://img.shields.io/npm/v/@psavelis/enterprise-blockchain)](https://www.npmjs.com/package/@psavelis/enterprise-blockchain)
6
- [![License: Apache 2.0](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](../../LICENSE)
6
+ [![License: Apache 2.0](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://github.com/psavelis/enterprise-blockchain/blob/main/LICENSE)
7
7
 
8
8
  ## Install in 10 Seconds
9
9
 
@@ -24,32 +24,227 @@ const decrypted = kem.decapsulate(ciphertext, secretKey, "ml-kem-768");
24
24
 
25
25
  ---
26
26
 
27
- ## Quick Start
27
+ ## Industry Use Cases
28
28
 
29
- ### Post-Quantum Key Exchange (ML-KEM-768)
29
+ ### 1. Post-Quantum Key Exchange (ML-KEM-768)
30
+
31
+ **Use case:** Secure key agreement for encrypted channels, protecting against "harvest now, decrypt later" quantum attacks.
30
32
 
31
33
  ```typescript
32
34
  import { KyberKem } from "@psavelis/enterprise-blockchain/mpc";
33
35
 
36
+ // Server generates long-term key pair
34
37
  const kem = new KyberKem();
35
- const params = "ml-kem-768";
36
- const { publicKey, secretKey } = kem.generateKeyPair(params);
37
- const { ciphertext, sharedSecret } = kem.encapsulate(publicKey, params);
38
- const decapsulated = kem.decapsulate(ciphertext, secretKey, params);
38
+ const server = kem.generateKeyPair("ml-kem-768");
39
+
40
+ // Client encapsulates a shared secret using server's public key
41
+ const { ciphertext, sharedSecret: clientKey } = kem.encapsulate(
42
+ server.publicKey,
43
+ "ml-kem-768",
44
+ );
45
+
46
+ // Server decapsulates to derive the same shared secret
47
+ const serverKey = kem.decapsulate(ciphertext, server.secretKey, "ml-kem-768");
48
+
49
+ // Both parties now have identical 32-byte keys for AES-256-GCM
50
+ console.log(clientKey.equals(serverKey)); // true
39
51
  ```
40
52
 
41
- ### Post-Quantum Signatures (ML-DSA-65)
53
+ ---
54
+
55
+ ### 2. Post-Quantum Digital Signatures (ML-DSA-65)
56
+
57
+ **Use case:** Transaction signing, document authentication, code signing — quantum-resistant.
42
58
 
43
59
  ```typescript
44
60
  import { MlDsaSigner } from "@psavelis/enterprise-blockchain/mpc";
45
61
 
46
62
  const signer = new MlDsaSigner();
47
63
  const { publicKey, secretKey } = signer.generateKeyPair("ml-dsa-65");
48
- const { signature } = signer.sign(message, secretKey, "ml-dsa-65");
49
- const valid = signer.verify(message, signature, publicKey, "ml-dsa-65");
64
+
65
+ // Sign a transaction payload
66
+ const payload = JSON.stringify({
67
+ from: "alice",
68
+ to: "bob",
69
+ amount: "1000000",
70
+ timestamp: Date.now(),
71
+ });
72
+
73
+ const { signature } = signer.sign(payload, secretKey, "ml-dsa-65");
74
+
75
+ // Anyone can verify with the public key
76
+ const isValid = signer.verify(payload, signature, publicKey, "ml-dsa-65");
77
+ console.log("Signature valid:", isValid); // true
78
+ ```
79
+
80
+ ---
81
+
82
+ ### 3. Hybrid Key Encapsulation (X25519 + ML-KEM-768)
83
+
84
+ **Use case:** Defense-in-depth during the quantum transition — secure if either algorithm holds.
85
+
86
+ ```typescript
87
+ import { HybridKem } from "@psavelis/enterprise-blockchain/mpc";
88
+
89
+ const hybrid = new HybridKem();
90
+
91
+ // Recipient generates both classical and post-quantum key pairs
92
+ const recipient = hybrid.generateKeyPairs();
93
+
94
+ // Sender encapsulates using both channels
95
+ const { x25519EphemeralPublicKeyDer, kyberCiphertext, combinedKey } =
96
+ hybrid.encapsulate(recipient.x25519.publicKey, recipient.kyber.publicKey);
97
+
98
+ // Recipient decapsulates to derive the same combined key
99
+ const { combinedKey: recipientKey } = hybrid.decapsulate(
100
+ recipient.x25519.privateKey,
101
+ recipient.kyber.secretKey,
102
+ x25519EphemeralPublicKeyDer,
103
+ kyberCiphertext,
104
+ );
105
+
106
+ // Both parties have identical 32-byte keys
107
+ console.log(combinedKey.equals(recipientKey)); // true
108
+ ```
109
+
110
+ ---
111
+
112
+ ### 4. Threshold Secret Sharing (Shamir k-of-n)
113
+
114
+ **Use case:** Key custody, board approvals, disaster recovery — any 3 of 5 shareholders can reconstruct.
115
+
116
+ ```typescript
117
+ import { QuantumResistantVault } from "@psavelis/enterprise-blockchain/mpc";
118
+
119
+ const vault = new QuantumResistantVault({ fieldMode: "production" });
120
+
121
+ // CEO's master key (256-bit secret)
122
+ const masterKey =
123
+ 0xdeadbeefcafebabedeadbeefcafebabedeadbeefcafebabedeadbeefcafebaben;
124
+
125
+ // Distribute to 5 board members, require 3 to reconstruct
126
+ const shareholders = ["ceo", "cfo", "cto", "legal", "audit"];
127
+ const shares = vault.distributeSecret(masterKey, shareholders, 3);
128
+
129
+ // Any 3 shareholders can reconstruct
130
+ const subset = [shares.get("ceo")!, shares.get("cto")!, shares.get("audit")!];
131
+ const reconstructed = vault.reconstructSecretBigint(subset, 3);
132
+
133
+ console.log(reconstructed === masterKey); // true
134
+ // With only 2 shares: returns null (k-1 reveals nothing)
135
+ ```
136
+
137
+ ---
138
+
139
+ ### 5. MPC Confidential Computation
140
+
141
+ **Use case:** Joint risk analysis, sealed-bid auctions — compute on combined data without revealing inputs.
142
+
143
+ ```typescript
144
+ import { MPCEngine } from "@psavelis/enterprise-blockchain/mpc";
145
+
146
+ const mpc = new MPCEngine();
147
+
148
+ // Three banks want to compute total market exposure without revealing individual positions
149
+ ["bank-a", "bank-b", "bank-c"].forEach((id) =>
150
+ mpc.registerParty({ id, name: id, endpoint: `https://${id}.example.com` }),
151
+ );
152
+
153
+ // Each bank splits their exposure into additive shares
154
+ const exposures = {
155
+ "bank-a": 50_000_000,
156
+ "bank-b": 75_000_000,
157
+ "bank-c": 25_000_000,
158
+ };
159
+ const computationId = "market-exposure-q1-2026";
160
+
161
+ for (const [bankId, exposure] of Object.entries(exposures)) {
162
+ const shares = mpc.splitSecret(exposure, ["bank-a", "bank-b", "bank-c"]);
163
+ const myShare = shares.find((s) => s.partyId === bankId)!;
164
+ mpc.submitShare(computationId, myShare);
165
+ }
166
+
167
+ // Aggregate reveals total (150M) without exposing individual positions
168
+ const result = mpc.compute(computationId, "sum");
169
+ console.log("Total market exposure:", result.aggregate); // 150,000,000
170
+ ```
171
+
172
+ ---
173
+
174
+ ### 6. HSM Envelope Encryption
175
+
176
+ **Use case:** Encrypt sensitive data at rest with keys that never leave the HSM.
177
+
178
+ ```typescript
179
+ import { HsmClient } from "@psavelis/enterprise-blockchain/hsm";
180
+
181
+ const hsm = new HsmClient();
182
+ hsm.initialize({ slotId: "slot-1", label: "production-hsm" });
183
+
184
+ // Generate a Key Encryption Key (KEK) inside the HSM
185
+ hsm.generateSymmetricKey("master-kek");
186
+
187
+ // Encrypt a sensitive document
188
+ const document = JSON.stringify({
189
+ ssn: "123-45-6789",
190
+ accountNumber: "9876543210",
191
+ balance: 1_500_000,
192
+ });
193
+
194
+ const { wrappedDek, encryptedRecord } = hsm.encryptWithEnvelope(
195
+ "master-kek",
196
+ document,
197
+ );
198
+
199
+ // Decrypt when needed
200
+ const decrypted = hsm.decryptWithEnvelope(wrappedDek, encryptedRecord);
201
+ console.log(JSON.parse(decrypted).balance); // 1500000
202
+
203
+ // Full audit trail
204
+ const auditLog = hsm.getAuditLog();
205
+ console.log("Operations logged:", auditLog.length);
50
206
  ```
51
207
 
52
- ### STARK Settlement
208
+ ---
209
+
210
+ ### 7. HSM Transaction Signing
211
+
212
+ **Use case:** Sign blockchain transactions with audited, hardware-protected keys.
213
+
214
+ ```typescript
215
+ import { HsmClient } from "@psavelis/enterprise-blockchain/hsm";
216
+
217
+ const hsm = new HsmClient();
218
+ hsm.initialize({ slotId: "slot-1", label: "signing-hsm" });
219
+
220
+ // Generate signing key pair (EC P-256)
221
+ const { keyLabel, publicKeyPem } = hsm.generateKeyPair("tx-signing-key");
222
+
223
+ // Sign a transaction
224
+ const transaction = {
225
+ type: "transfer",
226
+ from: "0xAlice",
227
+ to: "0xBob",
228
+ value: "1000000000000000000", // 1 ETH
229
+ nonce: 42,
230
+ chainId: 1,
231
+ };
232
+
233
+ const { signature, digestHex } = hsm.sign(
234
+ keyLabel,
235
+ JSON.stringify(transaction),
236
+ );
237
+
238
+ // Verify signature (typically done by blockchain nodes)
239
+ const isValid = hsm.verify(keyLabel, JSON.stringify(transaction), signature);
240
+ console.log("Transaction signature valid:", isValid); // true
241
+ ```
242
+
243
+ ---
244
+
245
+ ### 8. STARK Settlement Layer
246
+
247
+ **Use case:** Cross-border payments with recursive proof aggregation and multi-rail settlement.
53
248
 
54
249
  ```typescript
55
250
  import {
@@ -57,64 +252,122 @@ import {
57
252
  LedgerService,
58
253
  AggregatorService,
59
254
  SettlementService,
255
+ MockSolanaAdapter,
256
+ MockBitcoinAdapter,
257
+ MockFiatAdapter,
60
258
  } from "@psavelis/enterprise-blockchain/stark-settlement";
61
259
 
62
- const ctx = createDefaultContext();
260
+ // Initialize services
261
+ const ctx = createDefaultContext({ tier1BatchSize: 4, tier2BatchSize: 2 });
63
262
  const ledger = new LedgerService(ctx);
64
263
  const aggregator = new AggregatorService(ctx);
65
- const settler = new SettlementService(ctx);
264
+ const settler = new SettlementService(ctx, {
265
+ solana: new MockSolanaAdapter(),
266
+ bitcoin: new MockBitcoinAdapter(),
267
+ fiat: new MockFiatAdapter(),
268
+ });
66
269
 
67
- // Create accounts, submit transactions, aggregate proofs, settle
68
- ```
270
+ // Create mirror accounts
271
+ const alice = await ledger.createAccount({
272
+ accountId: "alice",
273
+ initialBalance: 10_000_000_000n,
274
+ });
275
+ const bob = await ledger.createAccount({
276
+ accountId: "bob",
277
+ initialBalance: 0n,
278
+ });
69
279
 
70
- ### HSM Key Management
280
+ // Submit cross-border payment
281
+ const tx = await ledger.submitTransaction({
282
+ type: "transfer",
283
+ fromAccountId: "alice",
284
+ toAccountId: "bob",
285
+ assetType: "SOL",
286
+ amount: 1_000_000_000n, // 1 SOL
287
+ });
71
288
 
72
- ```typescript
73
- import { HsmClient } from "@psavelis/enterprise-blockchain/hsm";
289
+ // Generate proofs (Base → Tier-1 → Tier-2 block proof)
290
+ const blockProof = await aggregator.processToBlockProof();
291
+ console.log("Block proof generated:", blockProof.blockNumber);
74
292
 
75
- const hsm = new HsmClient();
76
- hsm.initialize({ slotId: "slot-1", label: "my-hsm" });
77
- const { keyLabel } = hsm.generateKeyPair("my-signing-key");
78
- const signResult = hsm.sign(keyLabel, message);
79
- const valid = hsm.verify(keyLabel, message, signResult.signature);
293
+ // Settle to multiple rails
294
+ const result = await settler.settleAllRails(blockProof);
295
+ console.log("Solana:", result.solana?.status); // "confirmed"
296
+ console.log("Bitcoin:", result.bitcoin?.status); // "confirmed"
297
+ console.log("Fiat:", result.fiat?.status); // "confirmed"
80
298
  ```
81
299
 
82
- ### Pay-to-Merkle-Root (Quantum-Safe Bitcoin)
300
+ ---
301
+
302
+ ### 9. Quantum-Safe Bitcoin (Pay-to-Merkle-Root)
303
+
304
+ **Use case:** Bitcoin outputs that resist quantum attacks by hiding public keys until spend time.
83
305
 
84
306
  ```typescript
85
307
  import {
86
308
  createP2MROutput,
87
309
  createSingleSigLeaf,
88
310
  createTimelockLeaf,
89
- MerkleTree,
311
+ createMultisigLeaf,
312
+ buildSpendProof,
313
+ verifySpendProofStructure,
90
314
  } from "@psavelis/enterprise-blockchain/p2mr";
91
315
 
316
+ // Create a quantum-safe output with multiple spending paths
317
+ const primaryKeyHash = "a1b2c3d4..."; // SHA-256 of primary public key
318
+ const backupKeyHash = "e5f6a7b8..."; // SHA-256 of backup public key
319
+ const boardKeyHashes = ["k1...", "k2...", "k3..."]; // 2-of-3 multisig
320
+
92
321
  const { output, tree } = createP2MROutput({
93
322
  leaves: [
94
- createSingleSigLeaf(primaryKeyHash),
95
- createTimelockLeaf(backupKeyHash, futureTimestamp),
323
+ createSingleSigLeaf(primaryKeyHash), // Path 0: Primary key
324
+ createTimelockLeaf(backupKeyHash, 1893456000), // Path 1: Backup after 2030-01-01
325
+ createMultisigLeaf(boardKeyHashes, 2), // Path 2: 2-of-3 board approval
96
326
  ],
97
- value: 100_000_000n,
327
+ value: 100_000_000n, // 1 BTC in satoshis
328
+ });
329
+
330
+ // Only merkleRoot is stored on-chain (no public keys exposed!)
331
+ console.log("Output ID:", output.outputId);
332
+ console.log("Merkle root:", output.merkleRoot);
333
+
334
+ // Later, spend via primary key (path 0)
335
+ const proof = buildSpendProof({
336
+ outputId: output.outputId,
337
+ tree,
338
+ leafIndex: 0,
339
+ witness: {
340
+ publicKeys: [primaryPublicKey],
341
+ signatures: [signature], // ML-DSA-65 signature
342
+ },
98
343
  });
344
+
345
+ // Verify proof structure before broadcasting
346
+ const verification = verifySpendProofStructure(proof, output);
347
+ console.log("Valid spend proof:", verification.valid); // true
99
348
  ```
100
349
 
350
+ ---
351
+
101
352
  ## Subpath Exports
102
353
 
103
354
  | Import Path | Description |
104
355
  | ------------------------------------------------------ | ----------------------------------------------------- |
105
- | `@psavelis/enterprise-blockchain/mpc` | MPC engine, ML-KEM, ML-DSA, Hybrid KEM, Shamir SSS |
106
- | `@psavelis/enterprise-blockchain/hsm` | PKCS#11 HSM simulator, envelope encryption |
356
+ | `@psavelis/enterprise-blockchain/mpc` | ML-KEM, ML-DSA, Hybrid KEM, Shamir SSS, MPC Engine |
357
+ | `@psavelis/enterprise-blockchain/hsm` | PKCS#11 HSM simulator, envelope encryption, signing |
107
358
  | `@psavelis/enterprise-blockchain/p2mr` | Pay-to-Merkle-Root quantum-safe Bitcoin outputs |
108
359
  | `@psavelis/enterprise-blockchain/stark-settlement` | 3-tier STARK proof aggregation, multi-rail settlement |
109
- | `@psavelis/enterprise-blockchain/credentialing` | Clinical credential verification |
110
- | `@psavelis/enterprise-blockchain/privacy` | Selective disclosure ledger |
111
- | `@psavelis/enterprise-blockchain/traceability` | Supply-chain traceability |
112
- | `@psavelis/enterprise-blockchain/aid-settlement` | Aid voucher reconciliation |
360
+ | `@psavelis/enterprise-blockchain/credentialing` | Clinical credential verification (healthcare) |
361
+ | `@psavelis/enterprise-blockchain/privacy` | Selective disclosure ledger (finance) |
362
+ | `@psavelis/enterprise-blockchain/traceability` | Supply-chain traceability (food/pharma) |
363
+ | `@psavelis/enterprise-blockchain/aid-settlement` | Aid voucher reconciliation (humanitarian) |
113
364
  | `@psavelis/enterprise-blockchain/protocols` | Fabric/Besu/Corda adapter interfaces |
114
365
  | `@psavelis/enterprise-blockchain/integrations` | SDK clients with circuit breaker patterns |
115
- | `@psavelis/enterprise-blockchain/shared` | Utilities, crypto, stores (no telemetry re-export) |
366
+ | `@psavelis/enterprise-blockchain/shared` | Utilities, crypto primitives, stores |
116
367
  | `@psavelis/enterprise-blockchain/shared/telemetry` | createTracer, createMeter, withSpan helpers |
117
- | `@psavelis/enterprise-blockchain/shared/telemetry-sdk` | OpenTelemetry SDK initialization (side-effect import) |
368
+ | `@psavelis/enterprise-blockchain/shared/telemetry-sdk` | OpenTelemetry SDK initialization |
369
+
370
+ ---
118
371
 
119
372
  ## Architecture
120
373
 
@@ -133,45 +386,64 @@ Strict hexagonal architecture with clean domain/ports/adapters separation. Domai
133
386
 
134
387
  ┌──────────────────────────┴──────────────────────────────────────┐
135
388
  │ Infrastructure Adapters │
136
- │ StoneProofAdapter │ MockStarkAdapterSolanaAdapterBitcoinAdapter
389
+ │ StoneProofAdapter │ SolanaAdapterBitcoinAdapterFiatAdapter
137
390
  └─────────────────────────────────────────────────────────────────┘
138
391
  ```
139
392
 
393
+ ---
394
+
140
395
  ## Key Features
141
396
 
142
- - **Post-Quantum Cryptography**: NIST FIPS 203 ML-KEM, FIPS 204 ML-DSA
143
- - **Hybrid KEM**: X25519 + ML-KEM-768 for defense-in-depth
144
- - **STARK Proofs**: 3-tier recursive aggregation (8,192 transactions per block)
145
- - **Multi-Rail Settlement**: Solana, Bitcoin (PSBT), Fiat (ISO 20022)
146
- - **HSM Integration**: PKCS#11-style key management with audit logging
147
- - **Protocol Adapters**: Fabric, Besu, Corda with circuit breakers
148
- - **OpenTelemetry**: Built-in observability with tracing and metrics
397
+ | Feature | Standard/Implementation |
398
+ | ------------------------- | ------------------------------------------------- |
399
+ | Post-Quantum Key Exchange | NIST FIPS 203 (ML-KEM-768) |
400
+ | Post-Quantum Signatures | NIST FIPS 204 (ML-DSA-65) |
401
+ | Hybrid KEM | X25519 + ML-KEM-768 (Chrome/Firefox TLS approach) |
402
+ | STARK Proofs | 3-tier recursive aggregation (8,192 tx/block) |
403
+ | Multi-Rail Settlement | Solana, Bitcoin (PSBT), Fiat (ISO 20022) |
404
+ | HSM Integration | PKCS#11-style with full audit logging |
405
+ | Threshold Secret Sharing | Shamir k-of-n with 256-bit production field |
406
+ | Quantum-Safe Bitcoin | BIP-360-inspired Pay-to-Merkle-Root |
407
+ | Observability | OpenTelemetry tracing and metrics |
408
+
409
+ ---
149
410
 
150
411
  ## Peer Dependencies
151
412
 
152
413
  Protocol-specific SDKs are optional peer dependencies:
153
414
 
154
415
  ```bash
155
- # For Fabric integration
156
- npm install @hyperledger/fabric-gateway @grpc/grpc-js
416
+ # For STARK proofs (starknet.js)
417
+ npm install starknet
157
418
 
158
- # For Besu integration
419
+ # For Besu/EVM integration
159
420
  npm install ethers
160
421
 
161
- # For STARK proofs
162
- npm install starknet
422
+ # For Fabric integration
423
+ npm install @hyperledger/fabric-gateway @grpc/grpc-js
163
424
 
164
425
  # For observability
165
426
  npm install @opentelemetry/api @opentelemetry/sdk-node
166
427
  ```
167
428
 
429
+ ---
430
+
431
+ ## Requirements
432
+
433
+ - Node.js ≥ 22.14.0 (for native crypto support)
434
+ - TypeScript ≥ 5.0 (ESM modules)
435
+
436
+ ---
437
+
168
438
  ## Documentation
169
439
 
170
440
  - [Main Repository](https://github.com/psavelis/enterprise-blockchain)
171
- - [Live Demo](https://github.com/psavelis/enterprise-blockchain#live-demo)
172
441
  - [Architecture Guide](https://github.com/psavelis/enterprise-blockchain/blob/main/docs/architecture/README.md)
442
+ - [22 Runnable Examples](https://github.com/psavelis/enterprise-blockchain/tree/main/examples)
173
443
  - [Skills Reference](https://github.com/psavelis/enterprise-blockchain/tree/main/skills)
174
444
 
445
+ ---
446
+
175
447
  ## License
176
448
 
177
449
  Apache 2.0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@psavelis/enterprise-blockchain",
3
- "version": "1.1.1",
3
+ "version": "1.2.0",
4
4
  "description": "Production-grade TypeScript modules for recursive STARK settlement, post-quantum cryptography (ML-KEM/ML-DSA), MPC, HSM, and multi-rail (Solana + Bitcoin + fiat) infrastructure.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",