@odatano/core 2.0.0-rc.3 → 2.0.0-rc.31

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 (162) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +251 -0
  2. package/@cds-models/CardanoAgentService/index.js +36 -0
  3. package/@cds-models/CardanoBackendService/index.d.ts +357 -0
  4. package/@cds-models/CardanoBackendService/index.js +40 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +194 -2
  6. package/@cds-models/CardanoIndexerService/index.js +25 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +294 -7
  8. package/@cds-models/CardanoODataService/index.js +33 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +28 -3
  10. package/@cds-models/CardanoSignService/index.js +3 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +52 -19
  12. package/@cds-models/CardanoTransactionService/index.js +4 -0
  13. package/@cds-models/index.d.ts +18 -0
  14. package/@cds-models/index.js +3 -0
  15. package/@cds-models/odatano/cardano/index.d.ts +408 -7
  16. package/@cds-models/odatano/cardano/index.js +42 -0
  17. package/README.md +64 -5
  18. package/db/schema.cds +677 -13
  19. package/db/types.cds +27 -0
  20. package/package.json +182 -173
  21. package/scripts/migrate-slot-leader.mjs +104 -0
  22. package/scripts/migrate-txseq.mjs +147 -0
  23. package/src/index.d.ts +11 -10
  24. package/src/index.js +28 -14
  25. package/src/plugin.js +39 -52
  26. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  27. package/srv/blockchain/backends/blockfrost-backend.js +49 -160
  28. package/srv/blockchain/backends/cardano-backend.d.ts +104 -158
  29. package/srv/blockchain/backends/cardano-backend.js +19 -5
  30. package/srv/blockchain/backends/koios-backend.d.ts +126 -60
  31. package/srv/blockchain/backends/koios-backend.js +356 -217
  32. package/srv/blockchain/backends/odatano-backend.d.ts +64 -0
  33. package/srv/blockchain/backends/odatano-backend.js +170 -0
  34. package/srv/blockchain/backends/ogmios-backend.d.ts +162 -94
  35. package/srv/blockchain/backends/ogmios-backend.js +548 -197
  36. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
  37. package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
  38. package/srv/blockchain/cardano-client.d.ts +78 -205
  39. package/srv/blockchain/cardano-client.js +186 -242
  40. package/srv/blockchain/cardano-indexer.d.ts +302 -242
  41. package/srv/blockchain/cardano-indexer.js +1193 -362
  42. package/srv/blockchain/cardano-tx-builder.d.ts +43 -81
  43. package/srv/blockchain/cardano-tx-builder.js +177 -132
  44. package/srv/blockchain/crawler/certificate-backfill.d.ts +67 -0
  45. package/srv/blockchain/crawler/certificate-backfill.js +169 -0
  46. package/srv/blockchain/crawler/crawler.d.ts +139 -54
  47. package/srv/blockchain/crawler/crawler.js +478 -96
  48. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  49. package/srv/blockchain/crawler/index.d.ts +5 -0
  50. package/srv/blockchain/crawler/index.js +35 -7
  51. package/srv/blockchain/crawler/sync-state.d.ts +46 -28
  52. package/srv/blockchain/crawler/sync-state.js +128 -43
  53. package/srv/blockchain/crawler/transaction-backfill.d.ts +52 -0
  54. package/srv/blockchain/crawler/transaction-backfill.js +283 -0
  55. package/srv/blockchain/crawler/utxo-set-import.d.ts +78 -0
  56. package/srv/blockchain/crawler/utxo-set-import.js +363 -0
  57. package/srv/blockchain/ledger-state.d.ts +101 -0
  58. package/srv/blockchain/ledger-state.js +432 -0
  59. package/srv/blockchain/pending-spends.d.ts +28 -0
  60. package/srv/blockchain/pending-spends.js +89 -0
  61. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  62. package/srv/blockchain/signing/cose-verifier.js +6 -12
  63. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  64. package/srv/blockchain/signing/external-signer.js +19 -122
  65. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  66. package/srv/blockchain/signing/hsm-signer.js +23 -63
  67. package/srv/blockchain/signing/signature-verifier.d.ts +8 -44
  68. package/srv/blockchain/signing/signature-verifier.js +13 -54
  69. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  70. package/srv/blockchain/signing/submission-finalizer.js +16 -49
  71. package/srv/blockchain/stored-chain.d.ts +33 -0
  72. package/srv/blockchain/stored-chain.js +234 -0
  73. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +115 -160
  74. package/srv/blockchain/transaction-building/buildooor-tx.js +651 -287
  75. package/srv/blockchain/transaction-building/caller-datums.d.ts +29 -0
  76. package/srv/blockchain/transaction-building/caller-datums.js +139 -0
  77. package/srv/blockchain/transaction-building/cardano-tx.d.ts +10 -35
  78. package/srv/blockchain/transaction-rows.d.ts +12 -0
  79. package/srv/blockchain/transaction-rows.js +43 -0
  80. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  81. package/srv/blockchain/wallet-worker/build-request.js +48 -24
  82. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
  83. package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
  84. package/srv/blockchain/wallet-worker/index.js +2 -8
  85. package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
  86. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  87. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  88. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  89. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  90. package/srv/blockchain/wallet-worker/signers.js +3 -8
  91. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  92. package/srv/blockchain/wallet-worker/wallet-worker.js +40 -91
  93. package/srv/cardano-agent-service.cds +146 -0
  94. package/srv/cardano-agent-service.d.ts +2 -0
  95. package/srv/cardano-agent-service.js +12 -0
  96. package/srv/cardano-backend-service.cds +52 -0
  97. package/srv/cardano-backend-service.d.ts +2 -0
  98. package/srv/cardano-backend-service.js +244 -0
  99. package/srv/cardano-indexer-service.cds +201 -73
  100. package/srv/cardano-indexer-service.js +280 -11
  101. package/srv/cardano-service.cds +56 -1
  102. package/srv/cardano-service.js +52 -113
  103. package/srv/cardano-sign-service.cds +200 -180
  104. package/srv/cardano-sign-service.js +55 -173
  105. package/srv/cardano-tx-service.cds +439 -364
  106. package/srv/cardano-tx-service.js +305 -209
  107. package/srv/cardano-ui.cds +16 -16
  108. package/srv/cardano-worker-service.js +7 -15
  109. package/srv/cbor/parse.js +13 -1
  110. package/srv/server.d.ts +28 -86
  111. package/srv/server.js +130 -135
  112. package/srv/utils/agent-grants-config.d.ts +37 -0
  113. package/srv/utils/agent-grants-config.js +138 -0
  114. package/srv/utils/agent-grants.d.ts +262 -0
  115. package/srv/utils/agent-grants.js +922 -0
  116. package/srv/utils/agent-token-auth.d.ts +16 -0
  117. package/srv/utils/agent-token-auth.js +78 -0
  118. package/srv/utils/backend-request-handler.d.ts +2 -16
  119. package/srv/utils/backend-request-handler.js +3 -18
  120. package/srv/utils/collections.d.ts +4 -8
  121. package/srv/utils/collections.js +4 -8
  122. package/srv/utils/const.d.ts +30 -67
  123. package/srv/utils/const.js +32 -72
  124. package/srv/utils/crypto.d.ts +3 -12
  125. package/srv/utils/crypto.js +5 -18
  126. package/srv/utils/db-indexes.d.ts +25 -0
  127. package/srv/utils/db-indexes.js +94 -0
  128. package/srv/utils/db-sanitize.d.ts +27 -0
  129. package/srv/utils/db-sanitize.js +85 -0
  130. package/srv/utils/epoch-slots.d.ts +13 -0
  131. package/srv/utils/epoch-slots.js +25 -0
  132. package/srv/utils/error-codes.d.ts +20 -73
  133. package/srv/utils/error-codes.js +19 -70
  134. package/srv/utils/errors.d.ts +50 -177
  135. package/srv/utils/errors.js +94 -218
  136. package/srv/utils/liveness.d.ts +16 -0
  137. package/srv/utils/liveness.js +40 -0
  138. package/srv/utils/mappers.d.ts +128 -214
  139. package/srv/utils/mappers.js +354 -299
  140. package/srv/utils/network-context.js +2 -11
  141. package/srv/utils/pg-inline-json.d.ts +8 -0
  142. package/srv/utils/pg-inline-json.js +62 -0
  143. package/srv/utils/pg-order-nulls.d.ts +14 -0
  144. package/srv/utils/pg-order-nulls.js +56 -0
  145. package/srv/utils/plutus-placeholders.d.ts +23 -16
  146. package/srv/utils/plutus-placeholders.js +63 -27
  147. package/srv/utils/rate-limiter.d.ts +46 -0
  148. package/srv/utils/rate-limiter.js +116 -0
  149. package/srv/utils/service-events.d.ts +2 -22
  150. package/srv/utils/service-events.js +3 -23
  151. package/srv/utils/signing-helper.d.ts +3 -18
  152. package/srv/utils/signing-helper.js +10 -32
  153. package/srv/utils/tx-build-helper.d.ts +26 -92
  154. package/srv/utils/tx-build-helper.js +68 -123
  155. package/srv/utils/tx-request-parsers.d.ts +107 -21
  156. package/srv/utils/tx-request-parsers.js +433 -34
  157. package/srv/utils/tx-utils.d.ts +4 -23
  158. package/srv/utils/tx-utils.js +12 -41
  159. package/srv/utils/types.d.ts +238 -169
  160. package/srv/utils/types.js +2 -6
  161. package/srv/utils/validators.d.ts +24 -90
  162. package/srv/utils/validators.js +50 -147
@@ -13,10 +13,7 @@ const error_codes_1 = require("../../utils/error-codes");
13
13
  const cbor_1 = require("@harmoniclabs/cbor");
14
14
  const uint8array_utils_1 = require("@harmoniclabs/uint8array-utils");
15
15
  const logger = cds_1.default.log('HsmSigner');
16
- /**
17
- * CKM_EDDSA mechanism ID (PKCS#11 v3.0)
18
- * Used for Ed25519 signing operations
19
- */
16
+ /** CKM_EDDSA mechanism ID (PKCS#11 v3.0) for Ed25519 signing. */
20
17
  const CKM_EDDSA = 0x00001057;
21
18
  const defaultPkcs11Loader = () => require('pkcs11js');
22
19
  let pkcs11Loader = defaultPkcs11Loader;
@@ -24,6 +21,10 @@ let pkcs11Loader = defaultPkcs11Loader;
24
21
  function setPkcs11Loader(loader) {
25
22
  pkcs11Loader = loader ?? defaultPkcs11Loader;
26
23
  }
24
+ /**
25
+ * Ed25519 transaction signing through a PKCS#11 HSM (YubiHSM 2, CloudHSM, Luna, …); private
26
+ * keys never leave the device. Lifecycle: init(network) → sign()/signTransaction() → shutdown().
27
+ */
27
28
  class HsmSigner {
28
29
  pkcs11;
29
30
  session;
@@ -37,13 +38,11 @@ class HsmSigner {
37
38
  this.config = config;
38
39
  }
39
40
  /**
40
- * Initialize PKCS#11 session and locate the signing key.
41
- * Called once during plugin startup.
42
- *
43
- * @param network - Cardano network (mainnet, preview, preprod) for address derivation
41
+ * Open the PKCS#11 session, locate the key, export the public key and derive the
42
+ * enterprise address for `network`. Called once at startup.
44
43
  */
45
44
  async init(network) {
46
- // Dynamic import — pkcs11js is only loaded when HSM is configured
45
+ // pkcs11js is only loaded when HSM is configured
47
46
  let pkcs11js;
48
47
  try {
49
48
  pkcs11js = pkcs11Loader();
@@ -53,31 +52,23 @@ class HsmSigner {
53
52
  }
54
53
  this.pkcs11 = new pkcs11js.PKCS11();
55
54
  try {
56
- // 1. Load PKCS#11 module
57
55
  this.pkcs11.load(this.config.pkcs11Module);
58
56
  this.pkcs11.C_Initialize();
59
57
  logger.info({ module: this.config.pkcs11Module }, 'PKCS#11 module loaded');
60
- // 2. Open session on configured slot.
61
- // NOTE: `config.slot` is the 0-based INDEX into the list of slots-with-token
62
- // returned by C_GetSlotList(true), NOT the PKCS#11 slot ID (which need not be
63
- // contiguous or zero-based). Configure it as a position, not a hardware slot id.
58
+ // `config.slot` is the 0-based index into C_GetSlotList(true) (slots with a token),
59
+ // not the PKCS#11 slot ID, which need not be contiguous or zero-based.
64
60
  const slots = this.pkcs11.C_GetSlotList(true);
65
61
  if (this.config.slot >= slots.length) {
66
62
  throw new errors_1.HsmError(`HSM slot index ${this.config.slot} not found. ${slots.length} slot(s) with a token present (valid indices 0..${slots.length - 1}).`, 503, error_codes_1.ERROR_CODES.HSM_UNAVAILABLE);
67
63
  }
68
64
  this.session = this.pkcs11.C_OpenSession(slots[this.config.slot], pkcs11js.CKF_SERIAL_SESSION | pkcs11js.CKF_RW_SESSION);
69
65
  logger.debug({ slot: this.config.slot }, 'PKCS#11 session opened');
70
- // 3. Login with PIN
71
66
  try {
72
67
  this.pkcs11.C_Login(this.session, pkcs11js.CKU_USER, this.config.pin);
73
68
  }
74
69
  finally {
75
- // Zero the PIN everywhere it could residue after login (crash-dump /
76
- // heap-inspection hardening), regardless of login outcome:
77
- // - this.config (shared reference with the server-side hsmConfigInstance
78
- // singleton) — mutate IN PLACE, not reassign, so the singleton clears too
79
- // - the HSM_PIN environment variable
80
- // - the CAP config (cds.env.requires['odatano-core'].hsm.pin)
70
+ // Zero the PIN wherever it could linger (config object shared with the server
71
+ // singleton — mutate in place —, HSM_PIN env, CAP config), whatever the login outcome.
81
72
  this.config.pin = '';
82
73
  if (process.env.HSM_PIN)
83
74
  delete process.env.HSM_PIN;
@@ -89,12 +80,10 @@ class HsmSigner {
89
80
  catch { /* best effort */ }
90
81
  }
91
82
  logger.debug('PKCS#11 login successful');
92
- // 4. Find private key by label or ID
93
83
  this.privateKeyHandle = this._findKey(pkcs11js, pkcs11js.CKO_PRIVATE_KEY);
94
- // 5. Export public key
95
84
  this.publicKeyBytes = this._exportPublicKey(pkcs11js);
96
85
  logger.debug({ publicKeyLength: this.publicKeyBytes.length }, 'Ed25519 public key exported');
97
- // 6. Derive Cardano key hash and enterprise address
86
+ // Key hash = blake2b-224 of the public key
98
87
  const blake2b = require('blake2b');
99
88
  const hashOut = Buffer.alloc(28);
100
89
  blake2b(28).update(this.publicKeyBytes).digest(hashOut);
@@ -124,19 +113,12 @@ class HsmSigner {
124
113
  throw new errors_1.HsmError(`Failed to initialize HSM: ${msg}`, 503, error_codes_1.ERROR_CODES.HSM_UNAVAILABLE, err);
125
114
  }
126
115
  }
127
- /**
128
- * Sign a 32-byte transaction body hash using the HSM.
129
- * Returns the Ed25519 signature + public key for witness construction.
130
- *
131
- * @param txBodyHash - 32-byte hash of the transaction body
132
- * @returns HsmSignResult with signature, public key, and key hash
133
- */
116
+ /** Sign a 32-byte tx body hash in the HSM; returns Ed25519 signature + public key for the witness. */
134
117
  sign(txBodyHash) {
135
118
  if (!this.connected) {
136
119
  throw new errors_1.HsmError('HSM not connected', 503, error_codes_1.ERROR_CODES.HSM_UNAVAILABLE);
137
120
  }
138
121
  try {
139
- // CKM_EDDSA = Ed25519 signing mechanism
140
122
  this.pkcs11.C_SignInit(this.session, { mechanism: CKM_EDDSA }, this.privateKeyHandle);
141
123
  const signature = this.pkcs11.C_Sign(this.session, txBodyHash, Buffer.alloc(64));
142
124
  return {
@@ -151,21 +133,13 @@ class HsmSigner {
151
133
  }
152
134
  }
153
135
  /**
154
- * Sign a transaction and produce a complete signed transaction CBOR.
155
- *
156
- * Takes the unsigned transaction CBOR, signs the body hash via HSM,
157
- * builds a VKey witness [publicKey, signature], and merges it into
158
- * the transaction's witness set using raw CBOR manipulation.
159
- *
160
- * @param unsignedTxCbor - Unsigned transaction CBOR (hex)
161
- * @param txBodyHash - Transaction body hash (hex, 64 chars)
162
- * @returns Signed transaction CBOR (hex)
136
+ * Sign the body hash (hex) in the HSM, build the VKey witness [publicKey, signature] and
137
+ * splice it into the witness set at the raw CBOR level. Returns the signed tx CBOR (hex).
163
138
  */
164
139
  signTransaction(unsignedTxCbor, txBodyHash) {
165
140
  const hashBytes = Buffer.from(txBodyHash, 'hex');
166
141
  const result = this.sign(hashBytes);
167
142
  try {
168
- // Parse unsigned transaction at raw CBOR level
169
143
  const txObj = cbor_1.Cbor.parse((0, uint8array_utils_1.fromHex)(unsignedTxCbor));
170
144
  if (!(txObj instanceof cbor_1.CborArray) || txObj.array.length < 2) {
171
145
  throw new errors_1.HsmError('Invalid transaction CBOR structure', 400, error_codes_1.ERROR_CODES.HSM_SIGNING_FAILED);
@@ -175,13 +149,10 @@ class HsmSigner {
175
149
  new cbor_1.CborBytes(Buffer.from(result.publicKeyHex, 'hex')),
176
150
  new cbor_1.CborBytes(Buffer.from(result.signatureHex, 'hex')),
177
151
  ]);
178
- // Merge into witness set (txObj.array[1])
179
- // Single-signer design: HSM is the sole signer for unsigned transactions.
180
- // Multi-sig (e.g. wallet + HSM) uses combineTransactionWithWitnesses() instead.
152
+ // Witness set (txObj.array[1]): vkey witnesses (key 0) become the HSM witness only — single
153
+ // signer; multi-sig goes through combineTransactionWithWitnesses(). Other keys are preserved.
181
154
  const origWs = txObj.array[1];
182
155
  if (origWs instanceof cbor_1.CborMap) {
183
- // Replace VKey witnesses (key 0) with HSM witness only
184
- // Preserves all other entries (redeemers key 5, datums key 4, scripts keys 1-3, 6-7)
185
156
  const entries = origWs.map.filter((e) => !(e.k instanceof cbor_1.CborUInt && Number(e.k.num) === 0));
186
157
  entries.push({
187
158
  k: new cbor_1.CborUInt(0),
@@ -249,9 +220,7 @@ class HsmSigner {
249
220
  // ---------------------------------------------------------------------------
250
221
  // Private helpers
251
222
  // ---------------------------------------------------------------------------
252
- /**
253
- * Find a key object (private or public) in the HSM by label and/or ID
254
- */
223
+ /** Find an Ed25519 key object (private or public) in the HSM by label and/or ID. */
255
224
  _findKey(pkcs11js, objectClass) {
256
225
  const template = [
257
226
  { type: pkcs11js.CKA_CLASS, value: objectClass },
@@ -280,12 +249,10 @@ class HsmSigner {
280
249
  */
281
250
  _exportPublicKey(pkcs11js) {
282
251
  const pubKeyHandle = this._findKey(pkcs11js, pkcs11js.CKO_PUBLIC_KEY);
283
- // Extract CKA_EC_POINT (DER-encoded public key)
284
252
  const attrs = this.pkcs11.C_GetAttributeValue(this.session, pubKeyHandle, [
285
253
  { type: pkcs11js.CKA_EC_POINT },
286
254
  ]);
287
- // CKA_EC_POINT for Ed25519 is DER OCTET STRING wrapping 32-byte public key
288
- // Format: 04 20 <32 bytes>
255
+ // CKA_EC_POINT for Ed25519 is a DER OCTET STRING around the 32-byte key: 04 20 <32 bytes>
289
256
  const ecPoint = Buffer.from(attrs[0].value);
290
257
  if (ecPoint.length === 34 && ecPoint[0] === 0x04 && ecPoint[1] === 0x20) {
291
258
  return ecPoint.slice(2);
@@ -298,20 +265,13 @@ class HsmSigner {
298
265
  }
299
266
  }
300
267
  exports.HsmSigner = HsmSigner;
301
- // ---------------------------------------------------------------------------
302
- // Singleton pattern (same as getExternalSignerModule())
303
- // ---------------------------------------------------------------------------
268
+ // Singleton instance
304
269
  let hsmSignerInstance = null;
305
- /**
306
- * Get the initialized HsmSigner instance.
307
- * Returns null if HSM is not configured.
308
- */
270
+ /** The initialized HsmSigner, or null when HSM is not configured. */
309
271
  function getHsmSigner() {
310
272
  return hsmSignerInstance;
311
273
  }
312
- /**
313
- * Set the HsmSigner instance (called during initialization and shutdown).
314
- */
274
+ /** Set the HsmSigner instance (initialization and shutdown). */
315
275
  function setHsmSigner(signer) {
316
276
  hsmSignerInstance = signer;
317
277
  }
@@ -1,56 +1,20 @@
1
1
  import { SignatureVerificationResult, VerificationOptions } from '../../utils/types';
2
2
  /**
3
- * SignatureVerifier - Verifies transaction signatures without accessing private keys
4
- *
5
- * This module provides signature verification for externally signed transactions.
6
- * It ensures:
7
- * 1. The signed CBOR is valid and parseable
8
- * 2. The transaction body hash matches the expected hash (integrity check)
9
- * 3. Required signatures are present (when specified)
10
- * 4. No tampering occurred between build and sign steps
3
+ * Verifies externally signed transactions without private keys: CBOR parse, body-hash
4
+ * integrity against the build, required signers present, Ed25519 check per witness.
11
5
  */
12
6
  export declare class SignatureVerifier {
13
- /**
14
- * Verify a signed transaction
15
- *
16
- * @param signedTxCbor - The signed transaction in CBOR hex format
17
- * @param options - Verification options
18
- * @returns Verification result with details
19
- */
7
+ /** Verify a signed tx (hex CBOR); all failures are reported in the result, never thrown. */
20
8
  verify(signedTxCbor: string, options?: VerificationOptions): SignatureVerificationResult;
21
- /**
22
- * Verify signature and throw on failure
23
- *
24
- * @param signedTxCbor - The signed transaction in CBOR hex format
25
- * @param options - Verification options
26
- * @throws {TransactionValidationError} if verification fails
27
- */
9
+ /** Like verify(), but throws TransactionValidationError on failure. */
28
10
  verifyOrThrow(signedTxCbor: string, options?: VerificationOptions): SignatureVerificationResult;
29
- /**
30
- * Extract transaction body hash from unsigned or signed CBOR
31
- *
32
- * @param txCbor - Transaction CBOR (signed or unsigned)
33
- * @returns Transaction body hash as hex string
34
- * @throws {Error} if CBOR is invalid
35
- */
11
+ /** Body hash (hex) of an unsigned or signed tx CBOR; throws BackendError 400 on invalid CBOR. */
36
12
  extractTxBodyHash(txCbor: string): string;
37
- /**
38
- * Check if a transaction is signed (has witnesses)
39
- *
40
- * @param txCbor - Transaction CBOR
41
- * @returns true if transaction has at least one witness
42
- */
13
+ /** True when the tx carries at least one vkey witness. */
43
14
  isSigned(txCbor: string): boolean;
44
- /**
45
- * Get witness count from transaction
46
- *
47
- * @param txCbor - Transaction CBOR
48
- * @returns Number of witnesses
49
- */
15
+ /** Number of vkey witnesses in the tx (0 on invalid CBOR). */
50
16
  getWitnessCount(txCbor: string): number;
51
17
  }
52
- /**
53
- * Get the singleton SignatureVerifier instance
54
- */
18
+ /** Singleton SignatureVerifier. */
55
19
  export declare function getSignatureVerifier(): SignatureVerifier;
56
20
  //# sourceMappingURL=signature-verifier.d.ts.map
@@ -13,11 +13,8 @@ const errors_1 = require("../../utils/errors");
13
13
  const error_codes_1 = require("../../utils/error-codes");
14
14
  const logger = cds_1.default.log('SignatureVerifier');
15
15
  /**
16
- * blake2b-256 over the ORIGINAL transaction-body bytes (CBOR array index 0).
17
- * subCborRef preserves the exact received bytes, so the hash matches what was signed
18
- * and re-serialization can never drift it. (Historically this also sidestepped the
19
- * ledger-ts AuxiliaryData.fromCbor bug on metadata-only aux_data — fixed in 0.5.6 —
20
- * but byte-exactness remains the reason to stay at the raw-CBOR level.)
16
+ * blake2b-256 over the ORIGINAL transaction-body bytes (CBOR array index 0). subCborRef
17
+ * preserves the exact received bytes, so the hash matches what was signed.
21
18
  */
22
19
  function computeBodyHash(txBytes) {
23
20
  const tx = cbor_1.Cbor.parse(txBytes);
@@ -43,9 +40,8 @@ function extractVkeyWitnesses(txBytes) {
43
40
  arr = arr.data;
44
41
  if (!(arr instanceof cbor_1.CborArray))
45
42
  return [];
46
- // Parse defensively: a malformed witness entry (wrong shape or non-bytes members)
47
- // would otherwise throw a TypeError and surface as an opaque internal error. Skip
48
- // any entry that isn't a [vkey, signature] pair of byte strings.
43
+ // Skip entries that are not a [vkey, signature] pair of byte strings instead of
44
+ // surfacing an opaque TypeError.
49
45
  const witnesses = [];
50
46
  let skipped = 0;
51
47
  for (const pair of arr.array) {
@@ -67,23 +63,11 @@ function extractVkeyWitnesses(txBytes) {
67
63
  return witnesses;
68
64
  }
69
65
  /**
70
- * SignatureVerifier - Verifies transaction signatures without accessing private keys
71
- *
72
- * This module provides signature verification for externally signed transactions.
73
- * It ensures:
74
- * 1. The signed CBOR is valid and parseable
75
- * 2. The transaction body hash matches the expected hash (integrity check)
76
- * 3. Required signatures are present (when specified)
77
- * 4. No tampering occurred between build and sign steps
66
+ * Verifies externally signed transactions without private keys: CBOR parse, body-hash
67
+ * integrity against the build, required signers present, Ed25519 check per witness.
78
68
  */
79
69
  class SignatureVerifier {
80
- /**
81
- * Verify a signed transaction
82
- *
83
- * @param signedTxCbor - The signed transaction in CBOR hex format
84
- * @param options - Verification options
85
- * @returns Verification result with details
86
- */
70
+ /** Verify a signed tx (hex CBOR); all failures are reported in the result, never thrown. */
87
71
  verify(signedTxCbor, options = {}) {
88
72
  const result = {
89
73
  isValid: false,
@@ -93,8 +77,7 @@ class SignatureVerifier {
93
77
  warnings: [],
94
78
  };
95
79
  try {
96
- // Compute the body hash over the original CBOR body bytes (no re-serialization),
97
- // matching exactly what was signed.
80
+ // Body hash over the original body bytes — exactly what was signed.
98
81
  const txBytes = (0, uint8array_utils_1.fromHex)(signedTxCbor);
99
82
  const computedHash = computeBodyHash(txBytes);
100
83
  result.txBodyHash = computedHash;
@@ -159,13 +142,7 @@ class SignatureVerifier {
159
142
  }
160
143
  return result;
161
144
  }
162
- /**
163
- * Verify signature and throw on failure
164
- *
165
- * @param signedTxCbor - The signed transaction in CBOR hex format
166
- * @param options - Verification options
167
- * @throws {TransactionValidationError} if verification fails
168
- */
145
+ /** Like verify(), but throws TransactionValidationError on failure. */
169
146
  verifyOrThrow(signedTxCbor, options = {}) {
170
147
  const result = this.verify(signedTxCbor, options);
171
148
  if (!result.isValid) {
@@ -173,13 +150,7 @@ class SignatureVerifier {
173
150
  }
174
151
  return result;
175
152
  }
176
- /**
177
- * Extract transaction body hash from unsigned or signed CBOR
178
- *
179
- * @param txCbor - Transaction CBOR (signed or unsigned)
180
- * @returns Transaction body hash as hex string
181
- * @throws {Error} if CBOR is invalid
182
- */
153
+ /** Body hash (hex) of an unsigned or signed tx CBOR; throws BackendError 400 on invalid CBOR. */
183
154
  extractTxBodyHash(txCbor) {
184
155
  try {
185
156
  return computeBodyHash((0, uint8array_utils_1.fromHex)(txCbor));
@@ -189,12 +160,7 @@ class SignatureVerifier {
189
160
  throw new errors_1.BackendError(`Failed to extract transaction body hash: ${msg}`, 400, error_codes_1.ERROR_CODES.INVALID_INPUT);
190
161
  }
191
162
  }
192
- /**
193
- * Check if a transaction is signed (has witnesses)
194
- *
195
- * @param txCbor - Transaction CBOR
196
- * @returns true if transaction has at least one witness
197
- */
163
+ /** True when the tx carries at least one vkey witness. */
198
164
  isSigned(txCbor) {
199
165
  try {
200
166
  return extractVkeyWitnesses((0, uint8array_utils_1.fromHex)(txCbor)).length > 0;
@@ -203,12 +169,7 @@ class SignatureVerifier {
203
169
  return false;
204
170
  }
205
171
  }
206
- /**
207
- * Get witness count from transaction
208
- *
209
- * @param txCbor - Transaction CBOR
210
- * @returns Number of witnesses
211
- */
172
+ /** Number of vkey witnesses in the tx (0 on invalid CBOR). */
212
173
  getWitnessCount(txCbor) {
213
174
  try {
214
175
  return extractVkeyWitnesses((0, uint8array_utils_1.fromHex)(txCbor)).length;
@@ -221,9 +182,7 @@ class SignatureVerifier {
221
182
  exports.SignatureVerifier = SignatureVerifier;
222
183
  // Singleton instance
223
184
  let verifierInstance = null;
224
- /**
225
- * Get the singleton SignatureVerifier instance
226
- */
185
+ /** Singleton SignatureVerifier. */
227
186
  function getSignatureVerifier() {
228
187
  if (!verifierInstance) {
229
188
  verifierInstance = new SignatureVerifier();
@@ -15,48 +15,21 @@ export interface FinalizeParams {
15
15
  signerInfo?: string;
16
16
  }
17
17
  /**
18
- * Submit a verified+claimed signing request to the blockchain and persist the
19
- * outcome — DELIBERATELY outside the caller's request transaction.
20
- *
21
- * The caller must already have durably committed `status:'submitting'` (the
22
- * claim). This function then:
23
- * 1. submits with NO DB write-lock held (the lock was the reason concurrent
24
- * submits serialized and the SQLite busy-timeout could fire mid-network),
25
- * 2. on submit failure: marks the request 'failed' in its own committed tx
26
- * and rethrows (NOT rolled back to a pre-submit status — losing the
27
- * attempt would hide a tx the node may have accepted),
28
- * 3. on success: persists the submission + 'submitted' status in a committed
29
- * transaction.
30
- *
31
- * Crash window: a process death between (1) and (3) leaves the request durably
32
- * at 'submitting'. Deferred-path requests carry their signed CBOR on the row
33
- * and are re-driven at the next boot (redriveInterruptedSubmissions); sync-path
34
- * requests are left for the operator/poller exactly as before.
18
+ * Submit a claimed signing request (status 'submitting' already committed by the caller) and
19
+ * persist the outcome in detached transactions, so no DB lock is held across the network call.
20
+ * Submit failure → 'failed' in its own tx, then rethrow. A crash before finalize leaves 'submitting'.
35
21
  */
36
22
  export declare function submitAndFinalize(SigningRequests: unknown, params: FinalizeParams, afterFinalize?: (db: cds.Transaction) => Promise<void>): Promise<unknown>;
37
23
  /**
38
- * Deferred-submit scheduler (KNOWN_ISSUES #11, Layer 2).
39
- *
40
- * Called by an action handler AFTER verify + claim ran on the CALLER's
41
- * transaction. Hooks the request's post-commit event: only once the caller's
42
- * root transaction has committed (claim durable, pooled connection released)
43
- * does the network submit + finalize run — detached via setImmediate +
44
- * runWithoutAmbientTx, so no ambient transaction is held across it.
45
- *
46
- * If the caller's transaction rolls back instead, 'succeeded' never fires and
47
- * nothing was claimed — strictly consistent.
24
+ * Deferred submit: runs submitAndFinalize only after the caller's root transaction has committed
25
+ * (claim durable, connection released), detached via setImmediate + runWithoutAmbientTx.
26
+ * If the caller rolls back, 'succeeded' never fires and nothing was claimed.
48
27
  */
49
28
  export declare function scheduleDeferredSubmit(req: Request, SigningRequests: unknown, params: FinalizeParams): void;
50
29
  /**
51
- * Boot-time recovery: re-drive submissions that were claimed on the deferred
52
- * path (status 'submitting' WITH persisted signedTxCbor) but never finalized —
53
- * i.e. the process died between the caller's commit and the detached submit.
54
- *
55
- * Safe to repeat: a tx the node already holds finalizes as 'submitted' via the
56
- * TransactionAlreadySubmittedError path in submitAndFinalize. Rows at
57
- * 'submitting' WITHOUT signed CBOR (sync-path crash window) are deliberately
58
- * left untouched for the operator/poller, exactly as before Layer 2.
59
- *
30
+ * Boot-time recovery: re-drive rows at 'submitting' WITH persisted signedTxCbor (process died between
31
+ * the caller's commit and the detached submit). Idempotent: a tx the node already holds finalizes as
32
+ * 'submitted'. Rows without signed CBOR are left for the operator/poller.
60
33
  * @returns number of rows re-driven (attempted, not necessarily succeeded)
61
34
  */
62
35
  export declare function redriveInterruptedSubmissions(): Promise<number>;
@@ -13,31 +13,15 @@ const tx_build_helper_1 = require("../../utils/tx-build-helper");
13
13
  const external_signer_1 = require("./external-signer");
14
14
  const { SELECT, UPDATE } = cds_1.default.ql;
15
15
  const logger = cds_1.default.log('SubmissionFinalizer');
16
- // Lazy require breaks the srv/server.ts <-> this-module import cycle (the
17
- // server calls redriveInterruptedSubmissions at boot; we need its app-context
18
- // getters at runtime only). Same pattern as src/plugin.ts.
16
+ // Lazy require avoids the srv/server.ts <-> this-module import cycle; the app-context
17
+ // getters are only needed at runtime.
19
18
  function server() {
20
- // eslint-disable-next-line @typescript-eslint/no-var-requires
21
19
  return require('../../server');
22
20
  }
23
21
  /**
24
- * Submit a verified+claimed signing request to the blockchain and persist the
25
- * outcome — DELIBERATELY outside the caller's request transaction.
26
- *
27
- * The caller must already have durably committed `status:'submitting'` (the
28
- * claim). This function then:
29
- * 1. submits with NO DB write-lock held (the lock was the reason concurrent
30
- * submits serialized and the SQLite busy-timeout could fire mid-network),
31
- * 2. on submit failure: marks the request 'failed' in its own committed tx
32
- * and rethrows (NOT rolled back to a pre-submit status — losing the
33
- * attempt would hide a tx the node may have accepted),
34
- * 3. on success: persists the submission + 'submitted' status in a committed
35
- * transaction.
36
- *
37
- * Crash window: a process death between (1) and (3) leaves the request durably
38
- * at 'submitting'. Deferred-path requests carry their signed CBOR on the row
39
- * and are re-driven at the next boot (redriveInterruptedSubmissions); sync-path
40
- * requests are left for the operator/poller exactly as before.
22
+ * Submit a claimed signing request (status 'submitting' already committed by the caller) and
23
+ * persist the outcome in detached transactions, so no DB lock is held across the network call.
24
+ * Submit failure → 'failed' in its own tx, then rethrow. A crash before finalize leaves 'submitting'.
41
25
  */
42
26
  async function submitAndFinalize(SigningRequests, params, afterFinalize) {
43
27
  // Persist the submission + 'submitted' status in its own committed transaction.
@@ -59,10 +43,8 @@ async function submitAndFinalize(SigningRequests, params, afterFinalize) {
59
43
  await server().getCardanoClient().submitTransaction(params.fullSignedTxCbor);
60
44
  }
61
45
  catch (submitErr) {
62
- // Already-submitted means the tx reached the mempool — e.g. the first backend accepted
63
- // it but its response was lost and a fallback observed the duplicate. That is SUCCESS,
64
- // not failure: finalize it as 'submitted' (same as the happy path) instead of durably
65
- // recording a spurious 'failed' for a tx the node already holds.
46
+ // Already-submitted means the tx reached the mempool (e.g. first backend accepted it, response
47
+ // lost, fallback saw the duplicate): finalize as 'submitted' rather than recording a spurious 'failed'.
66
48
  if (submitErr instanceof errors_1.TransactionAlreadySubmittedError) {
67
49
  logger.info({ signingRequestId: params.signingRequestId, txHash: params.txHash }, 'Submit reported already-submitted — finalizing as submitted (tx already in mempool)');
68
50
  return finalizeSubmitted();
@@ -78,16 +60,9 @@ async function submitAndFinalize(SigningRequests, params, afterFinalize) {
78
60
  return finalizeSubmitted();
79
61
  }
80
62
  /**
81
- * Deferred-submit scheduler (KNOWN_ISSUES #11, Layer 2).
82
- *
83
- * Called by an action handler AFTER verify + claim ran on the CALLER's
84
- * transaction. Hooks the request's post-commit event: only once the caller's
85
- * root transaction has committed (claim durable, pooled connection released)
86
- * does the network submit + finalize run — detached via setImmediate +
87
- * runWithoutAmbientTx, so no ambient transaction is held across it.
88
- *
89
- * If the caller's transaction rolls back instead, 'succeeded' never fires and
90
- * nothing was claimed — strictly consistent.
63
+ * Deferred submit: runs submitAndFinalize only after the caller's root transaction has committed
64
+ * (claim durable, connection released), detached via setImmediate + runWithoutAmbientTx.
65
+ * If the caller rolls back, 'succeeded' never fires and nothing was claimed.
91
66
  */
92
67
  function scheduleDeferredSubmit(req, SigningRequests, params) {
93
68
  req.on('succeeded', () => {
@@ -104,15 +79,9 @@ function scheduleDeferredSubmit(req, SigningRequests, params) {
104
79
  });
105
80
  }
106
81
  /**
107
- * Boot-time recovery: re-drive submissions that were claimed on the deferred
108
- * path (status 'submitting' WITH persisted signedTxCbor) but never finalized —
109
- * i.e. the process died between the caller's commit and the detached submit.
110
- *
111
- * Safe to repeat: a tx the node already holds finalizes as 'submitted' via the
112
- * TransactionAlreadySubmittedError path in submitAndFinalize. Rows at
113
- * 'submitting' WITHOUT signed CBOR (sync-path crash window) are deliberately
114
- * left untouched for the operator/poller, exactly as before Layer 2.
115
- *
82
+ * Boot-time recovery: re-drive rows at 'submitting' WITH persisted signedTxCbor (process died between
83
+ * the caller's commit and the detached submit). Idempotent: a tx the node already holds finalizes as
84
+ * 'submitted'. Rows without signed CBOR are left for the operator/poller.
116
85
  * @returns number of rows re-driven (attempted, not necessarily succeeded)
117
86
  */
118
87
  async function redriveInterruptedSubmissions() {
@@ -126,8 +95,7 @@ async function redriveInterruptedSubmissions() {
126
95
  let attempted = 0;
127
96
  for (const row of rows) {
128
97
  try {
129
- // Re-verify from the persisted CBOR (deterministic — it passed at claim
130
- // time; this recomputes the witness metadata the finalize step persists).
98
+ // Re-verify from the persisted CBOR to recompute the witness metadata the finalize step persists.
131
99
  const verificationResult = (0, external_signer_1.getExternalSignerModule)().verifyOrThrow(row.signedTxCbor, row.txBodyHash);
132
100
  attempted++;
133
101
  await submitAndFinalize(SigningRequests, {
@@ -142,9 +110,8 @@ async function redriveInterruptedSubmissions() {
142
110
  logger.info({ signingRequestId: row.id, txHash: row.txBodyHash }, 'Interrupted submission re-driven');
143
111
  }
144
112
  catch (err) {
145
- // submitAndFinalize marked the row 'failed' on submit errors; verification
146
- // errors leave it at 'submitting' for manual inspection (should not happen
147
- // for CBOR that verified once).
113
+ // Submit errors already marked the row 'failed'; verification errors leave it at
114
+ // 'submitting' for manual inspection.
148
115
  logger.error({ err, signingRequestId: row.id }, 'Re-drive of interrupted submission failed');
149
116
  }
150
117
  }
@@ -0,0 +1,33 @@
1
+ import type { Transaction as CapTransaction } from '@sap/cds';
2
+ import type { BlockData, MetadataLabelTx, Transaction as ProviderTransaction } from '../utils/types';
3
+ /**
4
+ * Stored blocks and transactions back in the provider shape (`BlockData`, `Transaction`), for
5
+ * serving other ODATANO instances from what this one has indexed. The rows hold the ledger view
6
+ * (see ledgerView), so the phase-2 flag follows from them: a valid transaction always spends a
7
+ * regular input. Not stored, so absent: `totalCollateral` and `outputAmount`.
8
+ */
9
+ type Row = Record<string, unknown>;
10
+ /** `Blocks` row -> BlockData. */
11
+ export declare function blockRowToData(row: Row): BlockData;
12
+ /** A stored block by hash; null when not indexed. */
13
+ export declare function readBlock(db: CapTransaction, hash: string): Promise<BlockData | null>;
14
+ /** A stored block by height; null when not indexed. */
15
+ export declare function readBlockByHeight(db: CapTransaction, height: number): Promise<BlockData | null>;
16
+ /**
17
+ * Up to `count` stored blocks following height `afterHeight`, contiguous only: the run stops at
18
+ * the first missing height, so a caller never walks over a gap.
19
+ */
20
+ export declare function readNextBlocks(db: CapTransaction, afterHeight: number, count: number): Promise<BlockData[]>;
21
+ /** True when a stored input lacks its outpoint (row indexed before outpoints were recorded). */
22
+ export declare function lacksOutpoints(t: ProviderTransaction): boolean;
23
+ /** Stored transactions by hash (missing hashes are absent from the map). */
24
+ export declare function readTransactionsByHash(db: CapTransaction, hashes: string[]): Promise<Map<string, ProviderTransaction>>;
25
+ /**
26
+ * Stored transactions of a block in block order; null when the block is not stored with all of its
27
+ * transactions (a lazily indexed block may hold only the ones somebody asked for).
28
+ */
29
+ export declare function readBlockTransactions(db: CapTransaction, blockHash: string): Promise<ProviderTransaction[] | null>;
30
+ /** Metadata of a stored transaction; null when the transaction is not stored. */
31
+ export declare function readTransactionMetadata(db: CapTransaction, txHash: string): Promise<MetadataLabelTx[] | null>;
32
+ export {};
33
+ //# sourceMappingURL=stored-chain.d.ts.map